@xberg-io/sdk 0.11.0 → 0.13.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.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../src/errors.ts","../src/_internal.ts","../src/types.ts","../src/version.ts","../src/client.ts","../src/webhooks.ts"],"sourcesContent":["/**\n * Error class hierarchy for the Xberg SDK (Enterprise + Pro).\n *\n * Every non-2xx HTTP response is mapped to a subclass of {@link XbergError}.\n * `TimeoutError` is also raised when {@link XbergClient.waitForJob} exceeds its\n * configured deadline (distinct from a network/fetch timeout).\n */\n\nexport interface XbergErrorOptions {\n status: number;\n body: unknown;\n cause?: unknown;\n /** Stable machine-readable error code from the response envelope, e.g. `gateway_timeout`. */\n code?: string;\n /** Context-specific detail object from the response envelope. */\n details?: Record<string, unknown>;\n}\n\nexport class XbergError extends Error {\n public readonly status: number;\n public readonly body: unknown;\n /** Stable error code from the response envelope; branch on this, not on `message`. */\n public readonly code?: string;\n /** The envelope's `details` object, when the server sent one. */\n public readonly details?: Record<string, unknown>;\n\n public constructor(message: string, options: XbergErrorOptions) {\n const errorInit: ErrorOptions = options.cause === undefined ? {} : { cause: options.cause };\n super(message, errorInit);\n this.name = \"XbergError\";\n this.status = options.status;\n this.body = options.body;\n if (options.code !== undefined) {\n this.code = options.code;\n }\n if (options.details !== undefined) {\n this.details = options.details;\n }\n }\n}\n\nexport class AuthError extends XbergError {\n public constructor(message: string, options: XbergErrorOptions) {\n super(message, options);\n this.name = \"AuthError\";\n }\n}\n\nexport interface RateLimitErrorOptions extends XbergErrorOptions {\n retryAfter?: number;\n}\n\nexport class RateLimitError extends XbergError {\n public readonly retryAfter?: number;\n\n public constructor(message: string, options: RateLimitErrorOptions) {\n super(message, options);\n this.name = \"RateLimitError\";\n if (options.retryAfter !== undefined) {\n this.retryAfter = options.retryAfter;\n }\n }\n}\n\nexport class ValidationError extends XbergError {\n public constructor(message: string, options: XbergErrorOptions) {\n super(message, options);\n this.name = \"ValidationError\";\n }\n}\n\nexport class NotFoundError extends XbergError {\n public constructor(message: string, options: XbergErrorOptions) {\n super(message, options);\n this.name = \"NotFoundError\";\n }\n}\n\n/**\n * HTTP 404 with code `data_room.disabled`: the deployment's plan does not offer\n * data rooms, so every room route answers this before any other check.\n * `enterpriseHealthz()` reports the same state ahead of time as\n * `data_rooms.enabled === false`. Extends {@link NotFoundError}, which this\n * response mapped to before.\n */\nexport class DataRoomsDisabledError extends NotFoundError {\n public constructor(message: string, options: XbergErrorOptions) {\n super(message, options);\n this.name = \"DataRoomsDisabledError\";\n }\n}\n\n/** Envelope code of the 404 every data-room route answers on a plan without data rooms. */\nconst DATA_ROOM_DISABLED_CODE = \"data_room.disabled\";\n\nexport class ServerError extends XbergError {\n public constructor(message: string, options: XbergErrorOptions) {\n super(message, options);\n this.name = \"ServerError\";\n }\n}\n\n/**\n * HTTP 408: the request body stopped arriving before the upload completed\n * (`details.limit` is `body_idle`). Not retried by default — the body must be\n * sent again. Extends {@link ValidationError}, which every 4xx mapped to before.\n */\nexport class RequestTimeoutError extends ValidationError {\n /** Which server limit fired (`body_idle`), from `details.limit`. */\n public readonly limit?: string;\n /** The limit that was exceeded, in seconds, from `details.timeout_seconds`. */\n public readonly timeoutSeconds?: number;\n\n public constructor(message: string, options: XbergErrorOptions) {\n super(message, options);\n this.name = \"RequestTimeoutError\";\n const limits = timeoutLimits(options.details);\n if (limits.limit !== undefined) {\n this.limit = limits.limit;\n }\n if (limits.timeoutSeconds !== undefined) {\n this.timeoutSeconds = limits.timeoutSeconds;\n }\n }\n}\n\n/** HTTP 410: the job's stored result has expired and can no longer be fetched. */\nexport class ResultExpiredError extends ValidationError {\n public constructor(message: string, options: XbergErrorOptions) {\n super(message, options);\n this.name = \"ResultExpiredError\";\n }\n}\n\n/** HTTP 412: the `If-Match` precondition did not match the resource's current version. */\nexport class PreconditionFailedError extends ValidationError {\n public constructor(message: string, options: XbergErrorOptions) {\n super(message, options);\n this.name = \"PreconditionFailedError\";\n }\n}\n\n/** HTTP 428: the endpoint requires an `If-Match` header and none was sent. */\nexport class PreconditionRequiredError extends ValidationError {\n public constructor(message: string, options: XbergErrorOptions) {\n super(message, options);\n this.name = \"PreconditionRequiredError\";\n }\n}\n\n/**\n * HTTP 504: the server did not produce a response in time (`details.limit` is\n * `handler`). The work may still have happened server-side, which is why a\n * POST is not retried on 504 unless the client opts in. Extends\n * {@link ServerError}, which 504 mapped to before.\n */\nexport class GatewayTimeoutError extends ServerError {\n /** Which server limit fired (`handler`), from `details.limit`. */\n public readonly limit?: string;\n /** The limit that was exceeded, in seconds, from `details.timeout_seconds`. */\n public readonly timeoutSeconds?: number;\n\n public constructor(message: string, options: XbergErrorOptions) {\n super(message, options);\n this.name = \"GatewayTimeoutError\";\n const limits = timeoutLimits(options.details);\n if (limits.limit !== undefined) {\n this.limit = limits.limit;\n }\n if (limits.timeoutSeconds !== undefined) {\n this.timeoutSeconds = limits.timeoutSeconds;\n }\n }\n}\n\nexport class TimeoutError extends XbergError {\n public constructor(message: string, options: XbergErrorOptions) {\n super(message, options);\n this.name = \"TimeoutError\";\n }\n}\n\n/**\n * Map an HTTP response status to the matching error subclass and throw it.\n *\n * Always throws — call as `throw await raiseForStatus(response)` if you want\n * the type system to see the unreachable code, otherwise just `await`. Both\n * 401 and 403 map to {@link AuthError} — the API uses 403 for a\n * valid-but-forbidden principal.\n */\nexport async function raiseForStatus(response: Response): Promise<never> {\n const body = await readBody(response);\n const envelope = parseErrorEnvelope(body);\n const message = envelope.message ?? `Request failed with status ${response.status}`;\n const options: XbergErrorOptions = { status: response.status, body };\n if (envelope.code !== undefined) {\n options.code = envelope.code;\n }\n if (envelope.details !== undefined) {\n options.details = envelope.details;\n }\n\n if (response.status === 401 || response.status === 403) {\n throw new AuthError(message, options);\n }\n if (response.status === 404) {\n if (options.code === DATA_ROOM_DISABLED_CODE) {\n throw new DataRoomsDisabledError(message, options);\n }\n throw new NotFoundError(message, options);\n }\n if (response.status === 429) {\n const retryAfterRaw = response.headers.get(\"retry-after\");\n const retryAfter = parseRetryAfter(retryAfterRaw);\n const opts: RateLimitErrorOptions = retryAfter === undefined ? options : { ...options, retryAfter };\n throw new RateLimitError(message, opts);\n }\n const specific = STATUS_ERRORS[response.status];\n if (specific !== undefined) {\n throw new specific(message, options);\n }\n if (response.status >= 400 && response.status < 500) {\n throw new ValidationError(message, options);\n }\n if (response.status >= 500) {\n throw new ServerError(message, options);\n }\n throw new XbergError(message, options);\n}\n\nasync function readBody(response: Response): Promise<unknown> {\n const contentType = response.headers.get(\"content-type\") ?? \"\";\n if (contentType.includes(\"application/json\")) {\n try {\n return await response.json();\n } catch {\n return undefined;\n }\n }\n try {\n const text = await response.text();\n return text === \"\" ? undefined : text;\n } catch {\n return undefined;\n }\n}\n\nconst STATUS_ERRORS: Readonly<Record<number, new (message: string, options: XbergErrorOptions) => XbergError>> = {\n 408: RequestTimeoutError,\n 410: ResultExpiredError,\n 412: PreconditionFailedError,\n 428: PreconditionRequiredError,\n 504: GatewayTimeoutError,\n};\n\n/** The parts of an error body the SDK understands. */\ninterface ErrorEnvelope {\n message?: string;\n code?: string;\n details?: Record<string, unknown>;\n}\n\n/**\n * Read an error body in any shape the servers send: the canonical nested\n * envelope `{\"error\":{\"code\",\"message\",\"details\"}}`, the older flat\n * `{\"error\":\"...\"}` / `{\"message\":\"...\",\"code\":\"...\"}`, or plain text.\n */\nfunction parseErrorEnvelope(body: unknown): ErrorEnvelope {\n if (typeof body === \"string\") {\n return body.length > 0 ? { message: body } : {};\n }\n if (!isRecord(body)) {\n return {};\n }\n const error = body[\"error\"];\n const source = isRecord(error) ? error : body;\n const envelope: ErrorEnvelope = {};\n const message =\n nonEmptyString(source === body && typeof error === \"string\" ? error : undefined) ??\n nonEmptyString(source[\"message\"]);\n if (message !== undefined) {\n envelope.message = message;\n }\n const code = nonEmptyString(source[\"code\"]);\n if (code !== undefined) {\n envelope.code = code;\n }\n const details = source[\"details\"];\n if (isRecord(details)) {\n envelope.details = details;\n }\n return envelope;\n}\n\nfunction timeoutLimits(details: Record<string, unknown> | undefined): {\n limit?: string;\n timeoutSeconds?: number;\n} {\n const out: { limit?: string; timeoutSeconds?: number } = {};\n const limit = details?.[\"limit\"];\n if (typeof limit === \"string\") {\n out.limit = limit;\n }\n const seconds = details?.[\"timeout_seconds\"];\n if (typeof seconds === \"number\" && Number.isFinite(seconds)) {\n out.timeoutSeconds = seconds;\n }\n return out;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction nonEmptyString(value: unknown): string | undefined {\n return typeof value === \"string\" && value.length > 0 ? value : undefined;\n}\n\nfunction parseRetryAfter(value: string | null): number | undefined {\n if (value === null) {\n return undefined;\n }\n const seconds = Number(value);\n if (Number.isFinite(seconds) && seconds >= 0) {\n return seconds;\n }\n const parsed = Date.parse(value);\n if (Number.isNaN(parsed)) {\n return undefined;\n }\n const delta = Math.max(0, Math.ceil((parsed - Date.now()) / 1000));\n return delta;\n}\n","/**\n * Internal helpers for {@link XbergClient}: base-URL resolution, query-string\n * and backoff arithmetic, the file-to-`Blob` conversion the multipart request\n * paths need, and the event-stream frame decoder `streamCrawlEvents` reads its\n * response through. Not part of the public API — of the names here only\n * {@link FileLike} and {@link BackoffStrategy} are re-exported, via `client.ts`,\n * because they appear in public client signatures.\n */\n\nimport { XbergError } from \"./errors.js\";\n\nexport const DEFAULT_RETRY_BACKOFF_CAP_MS = 30_000;\nexport const DEFAULT_BACKOFF_FACTOR = 2;\n\n/**\n * Caps an event-stream frame. The frames this endpoint sends are a few hundred\n * bytes; the cap exists so a server that never closes a frame cannot grow this\n * decoder without bound.\n *\n * It is applied twice, because one application does not cover the other: to the\n * pending line, so one endless line cannot fill memory, and to the running\n * total of a frame's `data:` fields, so an endless succession of shorter lines\n * never followed by the blank line that would close the frame cannot either.\n */\nexport const MAX_EVENT_STREAM_FRAME_BYTES = 1 << 20;\n\n/**\n * Backoff strategy for retries and `waitForJob` polling.\n *\n * - `exponential` — interval doubles after every attempt, capped at 30s.\n * - `constant` — interval stays the same on every attempt.\n */\nexport type BackoffStrategy = \"exponential\" | \"constant\";\n\n/** Which product the client targets. */\nexport type Target = \"enterprise\" | \"pro\";\n\n/** Query-string values accepted by the internal request engine. */\nexport type QueryParams = Record<string, string | number | undefined>;\n\n/** Anything the client accepts as an uploadable file. */\nexport type FileLike = File | Blob | Uint8Array | { name?: string; data: Blob | Uint8Array; mimeType?: string };\n\n/**\n * Resolve the deployer's base URL; neither self-hosted product has a default.\n */\nexport function resolveBaseUrl(baseUrl: string | undefined, target: Target | undefined): string {\n const resolved = baseUrl?.replace(/\\/+$/, \"\");\n if (resolved !== undefined && resolved.length > 0) {\n return resolved;\n }\n const product = target === \"pro\" ? \"Xberg Pro\" : target === \"enterprise\" ? \"Xberg Enterprise\" : \"Xberg\";\n throw new XbergError(`${product} has no default base URL; pass baseUrl pointing at your deployment.`, {\n status: 0,\n body: null,\n });\n}\n\n/**\n * Resolve the base URL of the Enterprise control plane, defaulting to the data plane's.\n *\n * Enterprise runs the control plane (projects, API keys, integrations, RAG\n * config, members, invitations, managed webhooks, usage, analytics, billing) as\n * a second binary on its own origin; Pro serves it from the same one. The\n * default therefore has to be `baseUrl`, exactly as the console's\n * `NEXT_PUBLIC_BACKEND_API_URL` is same-origin unless set — anything else would\n * break every Pro control-plane call the moment this option existed.\n */\nexport function resolveControlPlaneBaseUrl(controlPlaneBaseUrl: string | undefined, baseUrl: string): string {\n if (controlPlaneBaseUrl !== undefined) {\n return controlPlaneBaseUrl.replace(/\\/+$/, \"\");\n }\n return baseUrl;\n}\n\nexport function defaultSleep(ms: number): Promise<void> {\n return new Promise((resolve) => {\n setTimeout(resolve, ms);\n });\n}\n\nexport function buildQueryString(params: QueryParams | undefined): string {\n if (params === undefined) {\n return \"\";\n }\n const search = new URLSearchParams();\n for (const [key, value] of Object.entries(params)) {\n if (value !== undefined) {\n search.append(key, String(value));\n }\n }\n const query = search.toString();\n return query.length > 0 ? `?${query}` : \"\";\n}\n\nexport function nextBackoffInterval(current: number, strategy: BackoffStrategy): number {\n if (strategy === \"constant\") {\n return current;\n }\n return Math.min(current * DEFAULT_BACKOFF_FACTOR, DEFAULT_RETRY_BACKOFF_CAP_MS);\n}\n\nexport function parseRetryAfterHeader(value: string | null): number | undefined {\n if (value === null) {\n return undefined;\n }\n const seconds = Number(value);\n if (Number.isFinite(seconds) && seconds >= 0) {\n return seconds;\n }\n const parsed = Date.parse(value);\n if (Number.isNaN(parsed)) {\n return undefined;\n }\n return Math.max(0, Math.ceil((parsed - Date.now()) / 1000));\n}\n\n/** Convert a {@link FileLike} input into a `Blob` plus best-guess filename. */\nexport function toBlob(file: FileLike): { blob: Blob; filename: string } {\n if (typeof File !== \"undefined\" && file instanceof File) {\n return { blob: file, filename: file.name };\n }\n if (file instanceof Blob) {\n return { blob: file, filename: \"upload.bin\" };\n }\n if (file instanceof Uint8Array) {\n return {\n blob: new Blob([blobBytes(file)], { type: \"application/octet-stream\" }),\n filename: \"upload.bin\",\n };\n }\n const wrapper = file;\n const name = wrapper.name ?? \"upload.bin\";\n const mimeType = wrapper.mimeType ?? guessMimeType(name);\n if (wrapper.data instanceof Blob) {\n return { blob: wrapper.data, filename: name };\n }\n return {\n blob: new Blob([blobBytes(wrapper.data)], { type: mimeType }),\n filename: name,\n };\n}\n\nfunction blobBytes(bytes: Uint8Array): Uint8Array<ArrayBuffer> {\n // ~keep Blob snapshots its input. A view avoids a second payload copy; shared backing requires an ordinary buffer.\n return bytes.buffer instanceof ArrayBuffer\n ? new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength)\n : new Uint8Array(bytes);\n}\n\nfunction guessMimeType(filename: string): string {\n const lower = filename.toLowerCase();\n if (lower.endsWith(\".csv\")) {\n return \"text/csv\";\n }\n if (lower.endsWith(\".md\")) {\n return \"text/markdown\";\n }\n if (lower.endsWith(\".pdf\")) {\n return \"application/pdf\";\n }\n if (lower.endsWith(\".txt\")) {\n return \"text/plain\";\n }\n if (lower.endsWith(\".docx\")) {\n return \"application/vnd.openxmlformats-officedocument.wordprocessingml.document\";\n }\n return \"application/octet-stream\";\n}\n\n/** Guess a display name for a file (used to populate `Job.filename`). */\nexport function describeFile(file: FileLike): string {\n if (typeof File !== \"undefined\" && file instanceof File) {\n return file.name;\n }\n if (file instanceof Blob || file instanceof Uint8Array) {\n return \"upload.bin\";\n }\n return file.name ?? \"upload.bin\";\n}\n\n/**\n * Incremental decoder for a `text/event-stream` body, fed the decoded text of\n * each network chunk.\n *\n * Implements the parts of the WHATWG event-stream parser this endpoint can\n * exercise. A frame is terminated by a *blank line*, not by a newline: its\n * payload is every `data:` field it carried, joined with `\\n`. Lines opening\n * with `:` are comments — the endpoint's 15s heartbeat is one — and\n * `event:`/`id:`/`retry:` fields are accepted and ignored. A single space\n * after a field's colon is framing, not value, so it is stripped.\n *\n * All of which is why this exists instead of `JSON.parse` per line: against a\n * server that happens to emit one compact frame per line the naive version\n * passes every test, then silently drops every multi-line payload and throws\n * on the first heartbeat against a real one. Chunk boundaries fall wherever\n * the network puts them, so lines are also reassembled here rather than\n * assumed to arrive whole.\n */\nexport class EventStreamDecoder {\n private buffer = \"\";\n private data: string[] = [];\n /** Running length of the frame being assembled, reset with `data` on dispatch. */\n private size = 0;\n\n /** Consume one chunk of decoded text, returning the payload of every frame it completed. */\n public push(chunk: string): string[] {\n this.buffer += chunk;\n const payloads: string[] = [];\n for (;;) {\n const boundary = this.nextLineBoundary();\n if (boundary === undefined) {\n if (this.buffer.length > MAX_EVENT_STREAM_FRAME_BYTES) {\n throw new XbergError(`Crawl event stream sent a line longer than ${MAX_EVENT_STREAM_FRAME_BYTES} bytes`, {\n status: 0,\n body: null,\n });\n }\n return payloads;\n }\n const line = this.buffer.slice(0, boundary.index);\n this.buffer = this.buffer.slice(boundary.index + boundary.width);\n const payload = this.feed(line);\n if (payload !== undefined) {\n payloads.push(payload);\n }\n }\n }\n\n /**\n * Locate the next `\\n`, `\\r\\n` or `\\r` in the buffer. A trailing `\\r` is\n * reported as \"no boundary yet\": it may be the first half of a `\\r\\n` the\n * network split across two chunks, and treating it as a terminator there\n * would dispatch a frame one line early.\n */\n private nextLineBoundary(): { index: number; width: number } | undefined {\n for (let index = 0; index < this.buffer.length; index += 1) {\n const character = this.buffer[index];\n if (character === \"\\n\") {\n return { index, width: 1 };\n }\n if (character === \"\\r\") {\n if (index === this.buffer.length - 1) {\n return undefined;\n }\n return { index, width: this.buffer[index + 1] === \"\\n\" ? 2 : 1 };\n }\n }\n return undefined;\n }\n\n /** Consume one terminator-stripped line, returning a payload if it completed a frame. */\n private feed(line: string): string | undefined {\n if (line === \"\") {\n return this.dispatch();\n }\n if (line.startsWith(\":\")) {\n return undefined;\n }\n const colon = line.indexOf(\":\");\n const field = colon === -1 ? line : line.slice(0, colon);\n let value = colon === -1 ? \"\" : line.slice(colon + 1);\n if (value.startsWith(\" \")) {\n value = value.slice(1);\n }\n if (field === \"data\") {\n this.size += value.length + 1; // +1 for the \"\\n\" dispatch joins with\n if (this.size > MAX_EVENT_STREAM_FRAME_BYTES) {\n throw new XbergError(\n `Crawl event frame exceeded ${MAX_EVENT_STREAM_FRAME_BYTES} bytes before the stream closed it`,\n { status: 0, body: null },\n );\n }\n this.data.push(value);\n }\n return undefined;\n }\n\n /** Emit the buffered `data` payload, or nothing when the blank line closed no frame. */\n private dispatch(): string | undefined {\n if (this.data.length === 0) {\n return undefined;\n }\n const payload = this.data.join(\"\\n\");\n this.data = [];\n this.size = 0;\n return payload;\n }\n}\n\n/** Encode a path identifier without allowing the HTTP client to change its route. */\nexport function encodePathSegment(value: string): string {\n // ~keep WHATWG URL normalizes even percent-encoded dot segments, so encoding alone is insufficient.\n if (value === \".\" || value === \"..\") {\n throw new XbergError(\"Path identifiers must not be '.' or '..'\", { status: 400, body: null });\n }\n return encodeURIComponent(value);\n}\n","/**\n * Friendly re-exports of the independently generated API, Pro and backend schema sets.\n *\n * Shared and Enterprise-only types key off `_generated/api.d.ts` (the Xberg\n * Enterprise managed API); Pro-only response types key off\n * `_generated/pro.d.ts`; Backend-prefixed types use `_generated/backend.d.ts`.\n * Schema sets are generated separately and never merged — mirrors ADR-0072.\n */\n\nimport type { components, operations } from \"./_generated/api.js\";\nimport type { components as proComponents } from \"./_generated/pro.js\";\nimport type { components as backendComponents } from \"./_generated/backend.js\";\n\n// -- Shared surface (present in both schema sets; typed off the Enterprise API) --\nexport type ExtractionOptions = components[\"schemas\"][\"ExtractionOptions\"];\nexport type ExtractionConfig = components[\"schemas\"][\"ExtractionConfig\"];\n/** A per-file extraction override, carried by `DocumentInput.config` and the `config-<filename>` multipart part. */\nexport type FileExtractionConfig = components[\"schemas\"][\"FileExtractionConfig\"];\nexport type ExtractedDocument = components[\"schemas\"][\"ExtractedDocument\"];\nexport type ExtractionResult = ExtractedDocument;\n// ~keep Upstream renamed this schema `JobResponse` -> `ExtractionJobResponse`; `Job` is public API and stays.\nexport type Job = components[\"schemas\"][\"ExtractionJobResponse\"];\nexport type JobStatus = components[\"schemas\"][\"JobStatus\"];\nexport type WebhookConfig = components[\"schemas\"][\"WebhookConfig\"];\nexport type ExtractResponse = components[\"schemas\"][\"ExtractResponse\"];\nexport type DocumentInput = components[\"schemas\"][\"DocumentInput\"];\nexport type ListJobsResponse = components[\"schemas\"][\"ListJobsResponse\"];\nexport type ListAuditEntriesResponse = components[\"schemas\"][\"ListAuditEntriesResponse\"];\nexport type PresetSummary = components[\"schemas\"][\"PresetSummary\"];\nexport type PresetDetail = components[\"schemas\"][\"PresetDetail\"];\n\n/**\n * The stored result document of a terminal job, returned by\n * `GET /v1/jobs/{id}/result` on both tiers. Distinct from {@link Job}, which is\n * the job's metadata record from `GET /v1/jobs/{id}`.\n */\nexport type JobResult = components[\"schemas\"][\"JobResult\"];\n/** A non-fatal per-document error attached to a {@link JobResult}. */\nexport type JobResultError = components[\"schemas\"][\"JobResultError\"];\n\n// -- Shared saved presets (both specs declare these identically) --\nexport type ListSavedPresetsResponse = components[\"schemas\"][\"ListSavedPresetsResponse\"];\nexport type SavedPresetSummary = components[\"schemas\"][\"SavedPresetSummary\"];\nexport type SavedPresetDetail = components[\"schemas\"][\"SavedPresetDetail\"];\nexport type CreateSavedPresetRequest = components[\"schemas\"][\"CreateSavedPresetRequest\"];\nexport type CreateSavedPresetResponse = components[\"schemas\"][\"CreateSavedPresetResponse\"];\nexport type UpdateSavedPresetRequest = components[\"schemas\"][\"UpdateSavedPresetRequest\"];\nexport type UpdateSavedPresetResponse = components[\"schemas\"][\"UpdateSavedPresetResponse\"];\n\n// -- Shared auto-tune surface (both specs declare these identically) --\nexport type ListAutoTuneJobsResponse = components[\"schemas\"][\"ListAutoTuneJobsResponse\"];\nexport type AutoTuneJobSummary = components[\"schemas\"][\"AutoTuneJobSummary\"];\nexport type CreateAutoTuneJobRequest = components[\"schemas\"][\"CreateAutoTuneJobRequest\"];\nexport type CreateAutoTuneJobResponse = components[\"schemas\"][\"CreateAutoTuneJobResponse\"];\nexport type AutoTuneCapabilitiesResponse = components[\"schemas\"][\"AutoTuneCapabilitiesResponse\"];\nexport type AutoTuneJobStatus = components[\"schemas\"][\"AutoTuneJobStatus\"];\nexport type AutoTuneResult = components[\"schemas\"][\"AutoTuneResult\"];\nexport type PromoteProfileRequest = components[\"schemas\"][\"PromoteProfileRequest\"];\n\n// -- Shared tuning profiles (both specs declare these identically) --\nexport type ListTuningProfilesResponse = components[\"schemas\"][\"ListTuningProfilesResponse\"];\nexport type TuningProfileSummary = components[\"schemas\"][\"TuningProfileSummary\"];\nexport type TuningProfileDetail = components[\"schemas\"][\"TuningProfileDetail\"];\n\n// -- Shared managed embedding presets (both specs declare these identically) --\nexport type ListManagedEmbeddingPresetsResponse = components[\"schemas\"][\"ListManagedEmbeddingPresetsResponse\"];\nexport type ManagedEmbeddingPreset = components[\"schemas\"][\"ManagedEmbeddingPreset\"];\n\n// -- Shared uploads, usage and enrichment (both specs declare these) --\nexport type UsageResponse = components[\"schemas\"][\"UsageResponse\"];\nexport type PresignUploadRequest = components[\"schemas\"][\"PresignUploadRequest\"];\nexport type PresignUploadResponse = components[\"schemas\"][\"PresignUploadResponse\"];\nexport type ConfirmUploadRequest = components[\"schemas\"][\"ConfirmUploadRequest\"];\nexport type ConfirmUploadResponse = components[\"schemas\"][\"ConfirmUploadResponse\"];\nexport type EnrichTextRequest = components[\"schemas\"][\"EnrichTextRequest\"];\nexport type EnrichRequestOptions = components[\"schemas\"][\"EnrichRequestOptions\"];\nexport type EnrichJobSubmitted = components[\"schemas\"][\"EnrichJobSubmitted\"];\nexport type EnrichJobStatus = components[\"schemas\"][\"EnrichJobStatus\"];\n\n// -- Enterprise-only surface (api schema) --\nexport type DiffResponse = components[\"schemas\"][\"DiffResponse\"];\n/** The async-pending envelope `diff`/`getDiffJob` return in place of {@link DiffResponse} while a diff is still computing. */\nexport type DiffAsyncAccepted = components[\"schemas\"][\"DiffAsyncAccepted\"];\n\n/**\n * Result of {@link XbergClient.diff} and {@link XbergClient.getDiffJob}.\n *\n * Both operations answer `200` with the computed {@link DiffResponse} or\n * `202` with the {@link DiffAsyncAccepted} polling envelope when the server\n * falls back to async computation — the same fallback `getDiffJob` exists to\n * poll. The two schemas share no field to discriminate on, so `status` here\n * is not part of either wire schema: it is the HTTP status code the response\n * actually carried, reattached so callers can narrow with a plain\n * `if (result.status === 200)` / `else` instead of a type assertion.\n */\nexport type DiffResult =\n | { readonly status: 200; readonly body: DiffResponse }\n | { readonly status: 202; readonly body: DiffAsyncAccepted };\nexport type DocumentVersionEntry = components[\"schemas\"][\"DocumentVersionEntry\"];\nexport type ListExtractionEventsResponse = components[\"schemas\"][\"ListExtractionEventsResponse\"];\nexport type ExtractionEventSummary = components[\"schemas\"][\"ExtractionEventSummary\"];\n/** Delivery attempts of a data-plane webhook subscription, without payload previews. */\nexport type ListWebhookDeliveriesResponse = components[\"schemas\"][\"ListWebhookDeliveriesResponse\"];\n/** One delivery attempt with its bounded request and response previews. */\nexport type WebhookDeliveryDetailResponse = components[\"schemas\"][\"WebhookDeliveryDetailResponse\"];\n\n// -- Enterprise-only documents and data rooms (api schema) --\n// ~keep Spec names too generic to stand alone in the package namespace (`ListItemsResponse`,\n// `AddMemberRequest`, `PublicationResponse`, ...) carry a `Room` prefix here; the right-hand\n// side names the schema each one aliases.\n/** One page of the project's logical documents, from `GET /v1/documents`. */\nexport type ListProjectDocumentsResponse = components[\"schemas\"][\"ListProjectDocumentsResponse\"];\n/** One logical document shown by its newest finished version; its `document_id` adds it to a room. */\nexport type ProjectDocumentEntry = components[\"schemas\"][\"ProjectDocumentEntry\"];\nexport type RoomResponse = components[\"schemas\"][\"RoomResponse\"];\nexport type RoomRightsResponse = components[\"schemas\"][\"RoomRightsResponse\"];\nexport type ListRoomsResponse = components[\"schemas\"][\"ListRoomsResponse\"];\nexport type CreateRoomRequest = components[\"schemas\"][\"CreateRoomRequest\"];\nexport type UpdateRoomRequest = components[\"schemas\"][\"UpdateRoomRequest\"];\n/** Which rooms `listRooms` asks for: the live ones, or the deleted ones that can still be restored. */\nexport type RoomListState = NonNullable<NonNullable<operations[\"list_rooms\"][\"parameters\"][\"query\"]>[\"state\"]>;\nexport type ListRoomItemsResponse = components[\"schemas\"][\"ListItemsResponse\"];\nexport type RoomItemResponse = components[\"schemas\"][\"RoomItemResponse\"];\nexport type AddRoomItemRequest = components[\"schemas\"][\"AddItemRequest\"];\nexport type ReorderRoomItemsRequest = components[\"schemas\"][\"ReorderItemsRequest\"];\nexport type ReorderRoomItemsResponse = components[\"schemas\"][\"ReorderItemsResponse\"];\nexport type RoomItemContentResponse = components[\"schemas\"][\"ItemContentResponse\"];\nexport type ListRoomMembersResponse = components[\"schemas\"][\"ListRoomMembersResponse\"];\nexport type RoomMemberResponse = components[\"schemas\"][\"RoomMemberResponse\"];\nexport type AddRoomMemberRequest = components[\"schemas\"][\"AddMemberRequest\"];\nexport type RoomChangeRoleRequest = components[\"schemas\"][\"RoomChangeRoleRequest\"];\nexport type RoomTransferOwnershipRequest = components[\"schemas\"][\"RoomTransferOwnershipRequest\"];\n/** The roles a room grant, invitation or role change can name. */\nexport type GrantableRole = components[\"schemas\"][\"GrantableRole\"];\nexport type ListRoomInvitationsResponse = components[\"schemas\"][\"ListRoomInvitationsResponse\"];\nexport type RoomInvitationResponse = components[\"schemas\"][\"RoomInvitationResponse\"];\nexport type RoomInviteRequest = components[\"schemas\"][\"RoomInviteRequest\"];\nexport type RoomAcceptInvitationRequest = components[\"schemas\"][\"RoomAcceptInvitationRequest\"];\nexport type AcceptedRoomInvitationResponse = components[\"schemas\"][\"AcceptedInvitationResponse\"];\nexport type RoomInvitationPreviewResponse = components[\"schemas\"][\"InvitationPreviewResponse\"];\nexport type RoomPublicationResponse = components[\"schemas\"][\"PublicationResponse\"];\nexport type SetRoomPublicationRequest = components[\"schemas\"][\"SetPublicationRequest\"];\nexport type PublicationStateName = components[\"schemas\"][\"PublicationStateName\"];\nexport type PublicationModeName = components[\"schemas\"][\"PublicationModeName\"];\nexport type PublicRoomResponse = components[\"schemas\"][\"PublicRoomResponse\"];\nexport type PublicRoomItemsResponse = components[\"schemas\"][\"PublicItemsResponse\"];\nexport type PublicRoomItemResponse = components[\"schemas\"][\"PublicItemResponse\"];\nexport type PublicRoomItemContentResponse = components[\"schemas\"][\"PublicItemContentResponse\"];\n\n/**\n * One event from {@link XbergClient.streamCrawlEvents}.\n *\n * A tagged union discriminated on `kind`, the same shape {@link DiffResult}\n * uses — except the discriminant here is a real wire field, not a reattached\n * HTTP status. Narrow before touching a variant-specific field:\n *\n * ```ts\n * for await (const event of client.streamCrawlEvents(crawlJobId)) {\n * if (event.kind === \"page\") {\n * // event.status_code, event.depth, event.url\n * } else if (event.kind === \"complete\") {\n * break;\n * }\n * }\n * ```\n *\n * `crawl_job_id` and `ts` are carried by every variant, so they read without\n * narrowing.\n */\nexport type CrawlEvent = components[\"schemas\"][\"CrawlEventV1\"];\n/** The `kind` discriminator of a {@link CrawlEvent}. */\nexport type CrawlEventKind = CrawlEvent[\"kind\"];\n/** A page was successfully crawled and indexed. */\nexport type CrawlPageEvent = Extract<CrawlEvent, { kind: \"page\" }>;\n/** A new URL was discovered during crawling. */\nexport type CrawlDiscoveredEvent = Extract<CrawlEvent, { kind: \"discovered\" }>;\n/** The crawl job finished; the stream closes after this event. */\nexport type CrawlCompleteEvent = Extract<CrawlEvent, { kind: \"complete\" }>;\n/** A single URL failed. The crawl continues; this is not a stream-level error. */\nexport type CrawlErrorEvent = Extract<CrawlEvent, { kind: \"error\" }>;\n\n// -- Pro-only surface (pro schema) --\nexport type GetJobResponse = proComponents[\"schemas\"][\"GetJobResponse\"];\nexport type AuthConfigResponse = proComponents[\"schemas\"][\"AuthConfigResponse\"];\nexport type LoginRequest = proComponents[\"schemas\"][\"LoginRequest\"];\nexport type LoginResponse = proComponents[\"schemas\"][\"LoginResponse\"];\nexport type SetRagConfigRequest = proComponents[\"schemas\"][\"SetRagConfigRequest\"];\nexport type RagConfigResponse = proComponents[\"schemas\"][\"RagConfigResponse\"];\n/** Licensee, plan, expiry and grace window of the running Pro instance. */\nexport type ProHealthResponse = proComponents[\"schemas\"][\"HealthResponse\"];\nexport type LicenseInfoResponse = proComponents[\"schemas\"][\"LicenseInfoResponse\"];\n\n/** One feature flag reported by Enterprise `GET /healthz`. */\nexport interface EnterpriseHealthFeature {\n enabled: boolean;\n}\n\n/**\n * Enterprise `GET /healthz`, as `enterpriseHealthz` decodes it. Written by hand\n * rather than aliased from the spec because the decode is lenient: a feature\n * object an older server omits, such as `data_rooms` before data rooms shipped,\n * reads as `{ enabled: false }`, and fields the server adds later are kept.\n */\nexport interface EnterpriseHealthResponse {\n status: string;\n tier: string;\n rag: EnterpriseHealthFeature;\n auto_tune: EnterpriseHealthFeature;\n data_rooms: EnterpriseHealthFeature;\n [key: string]: unknown;\n}\n\n// -- Pro-only control plane (projects, API keys, integrations) --\nexport type ListProjectsResponse = proComponents[\"schemas\"][\"ListProjectsResponse\"];\nexport type CreateProjectRequest = proComponents[\"schemas\"][\"CreateProjectRequest\"];\nexport type ProjectResponse = proComponents[\"schemas\"][\"ProjectResponse\"];\nexport type ApiKeyResponse = proComponents[\"schemas\"][\"ApiKeyResponse\"];\nexport type ApiKeyScope = proComponents[\"schemas\"][\"ApiKeyScope\"];\nexport type ListApiKeysResponse = proComponents[\"schemas\"][\"ListApiKeysResponse\"];\nexport type CreateApiKeyRequest = proComponents[\"schemas\"][\"CreateApiKeyRequest\"];\nexport type CreateApiKeyResponse = proComponents[\"schemas\"][\"CreateApiKeyResponse\"];\nexport type ProIntegrationListResponse = proComponents[\"schemas\"][\"ProIntegrationListResponse\"];\nexport type ListIntegrationsResponse = ProIntegrationListResponse;\nexport type CreateIntegrationRequest = proComponents[\"schemas\"][\"CreateIntegrationRequest\"];\nexport type IntegrationSyncResponse = proComponents[\"schemas\"][\"IntegrationSyncResponse\"];\nexport type SetIntegrationSyncRequest = proComponents[\"schemas\"][\"SetIntegrationSyncRequest\"];\nexport type IntegrationResponse = proComponents[\"schemas\"][\"IntegrationResponse\"];\nexport type BeginOAuthResponse = proComponents[\"schemas\"][\"BeginOAuthResponse\"];\nexport type ListDocumentsResponse = proComponents[\"schemas\"][\"ListDocumentsResponse\"];\nexport type DocumentResponse = proComponents[\"schemas\"][\"DocumentResponse\"];\n\n/**\n * Terminal job statuses — once observed, polling stops and the job result is\n * returned (or thrown, for `failed`/`cancelled`).\n */\nexport const TERMINAL_JOB_STATUSES: readonly JobStatus[] = [\n \"completed\",\n \"partial_success\",\n \"failed\",\n \"cancelled\",\n] as const;\n\n/**\n * Job statuses that indicate a successful extraction. Used to distinguish a\n * \"completed but check warnings\" result from a hard failure.\n */\nexport const SUCCESS_JOB_STATUSES: readonly JobStatus[] = [\"completed\", \"partial_success\"] as const;\n\nexport type BackendAcceptInvitationRequest = backendComponents[\"schemas\"][\"AcceptInvitationRequest\"];\nexport type BackendAnalyticsResponse = backendComponents[\"schemas\"][\"AnalyticsResponse\"];\nexport type BackendAuthConfigResponse = backendComponents[\"schemas\"][\"AuthConfigResponse\"];\nexport type BackendBeginConnectResponse = backendComponents[\"schemas\"][\"BeginConnectResponse\"];\nexport type BackendBillingResponse = backendComponents[\"schemas\"][\"BillingResponse\"];\nexport type BackendCheckoutResponse = backendComponents[\"schemas\"][\"CheckoutResponse\"];\nexport type BackendCreateApiKeyRequest = backendComponents[\"schemas\"][\"CreateApiKeyRequest\"];\nexport type BackendCreateApiKeyResponse = backendComponents[\"schemas\"][\"CreateApiKeyResponse\"];\n/** Backend integration configuration accepts arbitrary JSON object properties. */\nexport type BackendCreateIntegrationRequest = Omit<\n backendComponents[\"schemas\"][\"CreateIntegrationRequest\"],\n \"config\" | \"credentials\"\n> & { config?: Record<string, unknown>; credentials?: Record<string, unknown> };\nexport type BackendCreateInvitationRequest = backendComponents[\"schemas\"][\"CreateInvitationRequest\"];\nexport type BackendCreateInvitationResponse = backendComponents[\"schemas\"][\"CreateInvitationResponse\"];\nexport type BackendCreateProjectRequest = backendComponents[\"schemas\"][\"CreateProjectRequest\"];\nexport type BackendCreateWebhookRequest = backendComponents[\"schemas\"][\"CreateWebhookRequest\"];\nexport type BackendHealthResponse = backendComponents[\"schemas\"][\"HealthResponse\"];\nexport type BackendIntegrationResponse = backendComponents[\"schemas\"][\"IntegrationResponse\"];\nexport type BackendListApiKeysResponse = backendComponents[\"schemas\"][\"ListApiKeysResponse\"];\nexport type BackendListAuditEntriesResponse = backendComponents[\"schemas\"][\"ListAuditEntriesResponse\"];\nexport type BackendListDocumentsResponse = backendComponents[\"schemas\"][\"ListDocumentsResponse\"];\nexport type BackendListIntegrationsResponse = backendComponents[\"schemas\"][\"ListIntegrationsResponse\"];\nexport type BackendListInvitationsResponse = backendComponents[\"schemas\"][\"ListInvitationsResponse\"];\nexport type BackendListMembersResponse = backendComponents[\"schemas\"][\"ListMembersResponse\"];\nexport type BackendListProjectsResponse = backendComponents[\"schemas\"][\"ListProjectsResponse\"];\nexport type BackendListWebhookDeliveriesResponse = backendComponents[\"schemas\"][\"ListWebhookDeliveriesResponse\"];\nexport type BackendListWebhooksResponse = backendComponents[\"schemas\"][\"ListWebhooksResponse\"];\nexport type BackendLoginRequest = backendComponents[\"schemas\"][\"LoginRequest\"];\nexport type BackendLoginResponse = backendComponents[\"schemas\"][\"LoginResponse\"];\nexport type BackendMemberResponse = backendComponents[\"schemas\"][\"MemberResponse\"];\nexport type BackendPortalResponse = backendComponents[\"schemas\"][\"PortalResponse\"];\nexport type BackendProjectResponse = backendComponents[\"schemas\"][\"ProjectResponse\"];\nexport type BackendRagConfigResponse = backendComponents[\"schemas\"][\"RagConfigResponse\"];\nexport type BackendReadinessResponse = backendComponents[\"schemas\"][\"ReadinessResponse\"];\nexport type BackendRetryWebhookDeliveryResponse = backendComponents[\"schemas\"][\"RetryWebhookDeliveryResponse\"];\nexport type BackendSandboxExtractResponse = backendComponents[\"schemas\"][\"SandboxExtractResponse\"];\nexport type BackendSetRagConfigRequest = backendComponents[\"schemas\"][\"SetRagConfigRequest\"];\nexport type BackendUpdateMemberRoleRequest = backendComponents[\"schemas\"][\"UpdateMemberRoleRequest\"];\nexport type BackendUpdateProjectRequest = backendComponents[\"schemas\"][\"UpdateProjectRequest\"];\nexport type BackendUpdateWebhookRequest = backendComponents[\"schemas\"][\"UpdateWebhookRequest\"];\nexport type BackendUsageResponse = backendComponents[\"schemas\"][\"UsageResponse\"];\nexport type BackendWebhookDeliveryDetailResponse = backendComponents[\"schemas\"][\"WebhookDeliveryDetailResponse\"];\nexport type BackendWebhookResponse = backendComponents[\"schemas\"][\"WebhookResponse\"];\nexport type BackendWebhookTestResponse = backendComponents[\"schemas\"][\"WebhookTestResponse\"];\n\nexport type BackendUserProfileResponse = backendComponents[\"schemas\"][\"UserProfileResponse\"];\nexport type BackendUpdateUserProfileRequest = backendComponents[\"schemas\"][\"UpdateUserProfileRequest\"];\nexport type BackendAssignProjectRoleRequest = backendComponents[\"schemas\"][\"AssignProjectRoleRequest\"];\nexport type BackendCreateProjectRoleRequest = backendComponents[\"schemas\"][\"CreateProjectRoleRequest\"];\nexport type BackendCreateScimConnectionRequest = backendComponents[\"schemas\"][\"CreateScimConnectionRequest\"];\nexport type BackendCreateScimConnectionResponse = backendComponents[\"schemas\"][\"CreateScimConnectionResponse\"];\nexport type BackendIntegrationSyncResponse = backendComponents[\"schemas\"][\"IntegrationSyncResponse\"];\nexport type BackendListProjectRolesResponse = backendComponents[\"schemas\"][\"ListProjectRolesResponse\"];\nexport type BackendListScimAdminGroupsResponse = backendComponents[\"schemas\"][\"ListScimAdminGroupsResponse\"];\nexport type BackendListScimConnectionsResponse = backendComponents[\"schemas\"][\"ListScimConnectionsResponse\"];\nexport type BackendProjectRoleResponse = backendComponents[\"schemas\"][\"ProjectRoleResponse\"];\nexport type BackendReplaceScimGroupRolesRequest = backendComponents[\"schemas\"][\"ReplaceScimGroupRolesRequest\"];\nexport type BackendSamlDomainRequest = backendComponents[\"schemas\"][\"SamlDomainRequest\"];\nexport type BackendSamlDomainResponse = backendComponents[\"schemas\"][\"SamlDomainResponse\"];\nexport type BackendSamlProviderRequest = backendComponents[\"schemas\"][\"SamlProviderRequest\"];\nexport type BackendSamlProviderResponse = backendComponents[\"schemas\"][\"SamlProviderResponse\"];\nexport type BackendSetIntegrationSyncRequest = backendComponents[\"schemas\"][\"SetIntegrationSyncRequest\"];\nexport type BackendUpdateProjectRoleRequest = backendComponents[\"schemas\"][\"UpdateProjectRoleRequest\"];\nexport type CreateRoomLinkRequest = components[\"schemas\"][\"CreateRoomLinkRequest\"];\nexport type ListRoomLinksResponse = components[\"schemas\"][\"ListRoomLinksResponse\"];\nexport type RoomLinkResponse = components[\"schemas\"][\"RoomLinkResponse\"];\nexport type ProjectExtractionConfigResponse = components[\"schemas\"][\"ProjectExtractionConfigResponse\"];\nexport type ProUpdateProjectRequest = proComponents[\"schemas\"][\"UpdateProjectRequest\"];\n","/**\n * Package version, synced from the repo-root `VERSION` file by\n * `scripts/sync-versions.py`. Used to build the `User-Agent` header. ~keep\n */\nexport const VERSION = \"0.11.0\";\n","/**\n * High-level dual-target client for the Xberg Enterprise and Xberg Pro HTTP APIs.\n *\n * One {@link XbergClient} speaks to either product. The shared surface —\n * extraction, jobs (including job results), audit, curated presets, and the RAG\n * API — is written once and carries no tier gate. Tier-specific methods are\n * capability-gated: they probe the connected instance (`GET /healthz`'s `tier`,\n * or an explicit `target`) and throw a clear error instead of a raw 404 when\n * invoked against the wrong tier.\n *\n * Both products authenticate identically: `Authorization: Bearer {apiKey}`.\n * Both products are self-hosted and require the deployment's `baseUrl`.\n *\n * Enterprise splits into two binaries — the data plane `baseUrl` addresses and a\n * control plane (projects, API keys, integrations) on its own origin — while Pro\n * serves both from one. `controlPlaneBaseUrl` records the origin of the second\n * and defaults to `baseUrl`. The backend methods use that origin and an optional\n * separate `controlPlaneToken`; existing Pro methods retain their data-plane routing.\n */\n\nimport createOpenApiClient, { type Client } from \"openapi-fetch\";\nimport type { paths } from \"./_generated/api.js\";\nimport {\n DEFAULT_BACKOFF_FACTOR,\n DEFAULT_RETRY_BACKOFF_CAP_MS,\n EventStreamDecoder,\n encodePathSegment,\n buildQueryString,\n defaultSleep,\n describeFile,\n nextBackoffInterval,\n parseRetryAfterHeader,\n resolveBaseUrl,\n resolveControlPlaneBaseUrl,\n toBlob,\n} from \"./_internal.js\";\nimport type { BackoffStrategy, FileLike, QueryParams, Target } from \"./_internal.js\";\nimport { TimeoutError, ValidationError, XbergError, raiseForStatus } from \"./errors.js\";\nimport type {\n AuthConfigResponse,\n BackendAcceptInvitationRequest,\n BackendAnalyticsResponse,\n BackendAuthConfigResponse,\n BackendUserProfileResponse,\n BackendUpdateUserProfileRequest,\n BackendBeginConnectResponse,\n BackendBillingResponse,\n BackendCheckoutResponse,\n BackendCreateApiKeyRequest,\n BackendCreateApiKeyResponse,\n BackendCreateIntegrationRequest,\n BackendCreateInvitationRequest,\n BackendCreateInvitationResponse,\n BackendCreateProjectRequest,\n BackendCreateWebhookRequest,\n BackendHealthResponse,\n BackendIntegrationResponse,\n BackendListApiKeysResponse,\n BackendListAuditEntriesResponse,\n BackendListDocumentsResponse,\n BackendListIntegrationsResponse,\n BackendListInvitationsResponse,\n BackendListMembersResponse,\n BackendListProjectsResponse,\n BackendListWebhookDeliveriesResponse,\n BackendListWebhooksResponse,\n BackendLoginRequest,\n BackendLoginResponse,\n BackendMemberResponse,\n BackendPortalResponse,\n BackendProjectResponse,\n BackendRagConfigResponse,\n BackendReadinessResponse,\n BackendRetryWebhookDeliveryResponse,\n BackendSandboxExtractResponse,\n BackendSetRagConfigRequest,\n BackendUpdateMemberRoleRequest,\n BackendUpdateProjectRequest,\n BackendUpdateWebhookRequest,\n BackendUsageResponse,\n BackendWebhookDeliveryDetailResponse,\n BackendWebhookResponse,\n BackendWebhookTestResponse,\n BackendAssignProjectRoleRequest,\n BackendCreateProjectRoleRequest,\n BackendCreateScimConnectionRequest,\n BackendCreateScimConnectionResponse,\n BackendIntegrationSyncResponse,\n BackendListProjectRolesResponse,\n BackendListScimAdminGroupsResponse,\n BackendListScimConnectionsResponse,\n BackendProjectRoleResponse,\n BackendReplaceScimGroupRolesRequest,\n BackendSamlDomainRequest,\n BackendSamlDomainResponse,\n BackendSamlProviderRequest,\n BackendSamlProviderResponse,\n BackendSetIntegrationSyncRequest,\n BackendUpdateProjectRoleRequest,\n AutoTuneCapabilitiesResponse,\n AutoTuneJobStatus,\n AutoTuneResult,\n BeginOAuthResponse,\n ConfirmUploadRequest,\n ConfirmUploadResponse,\n CrawlEvent,\n CreateApiKeyRequest,\n CreateApiKeyResponse,\n CreateAutoTuneJobRequest,\n CreateAutoTuneJobResponse,\n CreateIntegrationRequest,\n CreateProjectRequest,\n CreateSavedPresetRequest,\n CreateSavedPresetResponse,\n DiffAsyncAccepted,\n DiffResponse,\n DiffResult,\n DocumentVersionEntry,\n EnrichJobStatus,\n EnrichJobSubmitted,\n EnterpriseHealthFeature,\n EnterpriseHealthResponse,\n EnrichTextRequest,\n ExtractResponse,\n ExtractionOptions,\n FileExtractionConfig,\n IntegrationResponse,\n IntegrationSyncResponse,\n SetIntegrationSyncRequest,\n Job,\n GetJobResponse,\n JobResult,\n LicenseInfoResponse,\n ProHealthResponse,\n ListApiKeysResponse,\n ListAuditEntriesResponse,\n ListAutoTuneJobsResponse,\n ListDocumentsResponse,\n ListExtractionEventsResponse,\n ListIntegrationsResponse,\n ListJobsResponse,\n ListManagedEmbeddingPresetsResponse,\n ListProjectsResponse,\n ListSavedPresetsResponse,\n ListTuningProfilesResponse,\n ListWebhookDeliveriesResponse,\n LoginRequest,\n LoginResponse,\n PresetDetail,\n PresetSummary,\n PresignUploadRequest,\n PresignUploadResponse,\n CreateRoomLinkRequest,\n ListRoomLinksResponse,\n RoomLinkResponse,\n ProjectExtractionConfigResponse,\n ProUpdateProjectRequest,\n ExtractionConfig,\n ProjectResponse,\n PromoteProfileRequest,\n RagConfigResponse,\n SavedPresetDetail,\n SetRagConfigRequest,\n TuningProfileDetail,\n UpdateSavedPresetRequest,\n UpdateSavedPresetResponse,\n UsageResponse,\n WebhookConfig,\n WebhookDeliveryDetailResponse,\n AcceptedRoomInvitationResponse,\n AddRoomItemRequest,\n AddRoomMemberRequest,\n CreateRoomRequest,\n ListProjectDocumentsResponse,\n ListRoomInvitationsResponse,\n ListRoomItemsResponse,\n ListRoomMembersResponse,\n ListRoomsResponse,\n PublicRoomItemContentResponse,\n PublicRoomItemsResponse,\n PublicRoomResponse,\n ReorderRoomItemsRequest,\n ReorderRoomItemsResponse,\n RoomAcceptInvitationRequest,\n RoomChangeRoleRequest,\n RoomInvitationPreviewResponse,\n RoomInvitationResponse,\n RoomInviteRequest,\n RoomItemContentResponse,\n RoomItemResponse,\n RoomListState,\n RoomMemberResponse,\n RoomPublicationResponse,\n RoomResponse,\n RoomTransferOwnershipRequest,\n SetRoomPublicationRequest,\n UpdateRoomRequest,\n} from \"./types.js\";\nimport { SUCCESS_JOB_STATUSES, TERMINAL_JOB_STATUSES } from \"./types.js\";\nimport { VERSION } from \"./version.js\";\n\n/**\n * Public types that live in the internal helper module because the helpers\n * there operate on them; re-exported so `./client.js` stays their import site.\n */\nexport type { BackoffStrategy, FileLike, Target } from \"./_internal.js\";\n\nconst USER_AGENT = `xberg-io-sdk-typescript/${VERSION}`;\nconst DEFAULT_TIMEOUT_MS = 30_000;\nconst DEFAULT_POLL_INTERVAL_MS = 1_000;\nconst DEFAULT_WAIT_TIMEOUT_MS = 5 * 60_000;\nconst DEFAULT_RETRY_STATUSES: readonly number[] = [429, 502, 503, 504];\n/**\n * ~keep Methods a retry cannot duplicate work through. A 502/503/504 on a POST may\n * arrive after the server accepted the submission, so retrying it can create a\n * second job; 429 is safe for every method because the request was refused.\n */\nconst IDEMPOTENT_METHODS: ReadonlySet<string> = new Set([\"GET\", \"HEAD\", \"OPTIONS\", \"PUT\", \"DELETE\"]);\nconst DEFAULT_RETRY_BACKOFF_BASE_MS = 200;\n\n/**\n * ~keep `saved-presets` is an OpenAPI *tag* name, not a route: both specs serve\n * `/v1/saved_presets`, so there is no per-tier spelling to select between.\n */\nconst SAVED_PRESETS_PATH = \"/v1/saved_presets\";\nconst AUTO_TUNE_PATH = \"/v1/auto-tune\";\nconst TUNING_PROFILES_PATH = \"/v1/tuning-profiles\";\nconst ENRICH_PATH = \"/v1/enrich\";\nconst EXTRACTIONS_PATH = \"/v1/extractions\";\nconst DOCUMENTS_PATH = \"/v1/documents\";\nconst JOBS_PATH = \"/v1/jobs\";\nconst CRAWL_JOBS_PATH = \"/v1/crawl-jobs\";\nconst WEBHOOKS_PATH = \"/v1/webhooks\";\nconst ROOMS_PATH = \"/v1/rooms\";\nconst ROOM_INVITATIONS_PATH = \"/v1/room-invitations\";\nconst PUBLIC_ROOMS_PATH = \"/public/rooms\";\n\n/** Headers that carry a credential, stripped from every request to an unauthenticated public route. */\nconst CREDENTIAL_HEADERS: readonly string[] = [\"authorization\", \"proxy-authorization\", \"cookie\", \"x-api-key\"];\n\n/** Media type of a raw upload body, and the fallback when a submitted file declares none. */\nconst OCTET_STREAM_MEDIA_TYPE = \"application/octet-stream\";\n\n/** Media type of the crawl-event stream, sent as `Accept` and served as `Content-Type`. */\nconst EVENT_STREAM_MEDIA_TYPE = \"text/event-stream\";\n\n/** The `kind` values `CrawlEventV1` declares. A frame carrying anything else is rejected. */\nconst CRAWL_EVENT_KINDS: ReadonlySet<string> = new Set([\"page\", \"discovered\", \"complete\", \"error\"]);\n\nexport interface XbergClientOptions {\n apiKey?: string;\n baseUrl: string;\n /**\n * Origin of the Enterprise control plane, which runs as a second binary\n * alongside the data plane. Defaults to `baseUrl` — Pro serves both planes\n * from one binary, so every Pro call keeps working untouched.\n *\n */\n controlPlaneBaseUrl?: string;\n /** Bearer token for protected backend calls; defaults to `apiKey`. */\n controlPlaneToken?: string;\n /** Product for tier-specific data-plane methods; discovered lazily when omitted. */\n target?: Target;\n fetch?: typeof fetch;\n headers?: Record<string, string>;\n timeoutMs?: number;\n /** Retry attempts after the first request. Default 0 (retries off). */\n retries?: number;\n /**\n * Statuses to retry. Default `[429, 502, 503, 504]`. A 429 is retried for\n * every method, honouring `Retry-After`; any other listed status is retried\n * only for GET, HEAD, OPTIONS, PUT and DELETE without `If-Match` unless\n * `retryNonIdempotent` is set. A replayed DELETE whose first attempt applied\n * answers 404.\n */\n retryOn?: readonly number[];\n /**\n * Also retry POST, PATCH and `If-Match` writes on the non-429 `retryOn` statuses.\n * Default `false`: a 502/503/504 can arrive after the server accepted the request,\n * so a retry may submit the same document twice, and a replayed `If-Match` write\n * fails with 412 because the version moved. Enable only when repeating is acceptable.\n */\n retryNonIdempotent?: boolean;\n retryBackoff?: BackoffStrategy;\n /** Sleep helper, swappable in tests. Defaults to `setTimeout`. */\n sleep?: (ms: number) => Promise<void>;\n}\n\nexport interface JobScopeParams {\n /** ~keep Pro only: select a visible project instead of the credential's default project. */\n projectId?: string;\n}\n\nexport interface ExtractParams extends JobScopeParams {\n /** Enterprise document lineage UUID; omitted for a new document. */\n documentId?: string;\n file: FileLike;\n options?: ExtractionOptions;\n webhook?: WebhookConfig;\n /**\n * Per-file extraction override for this document, sent as the\n * `config-<filename>` part. The server resolves it against\n * `options.extraction_config`, any preset and the project default.\n */\n config?: FileExtractionConfig;\n}\n\nexport interface ExtractBatchParams extends JobScopeParams {\n /** Enterprise lineage UUIDs aligned with files; null entries omit lineage. */\n documentIds?: readonly (string | null)[];\n files: readonly FileLike[];\n options?: ExtractionOptions;\n webhook?: WebhookConfig;\n /**\n * One optional per-file override per entry of `files`, in the same order —\n * `null` for no override. Must be the same length as `files` when given.\n *\n * The override travels as a `config-<filename>` part, so two documents sharing\n * a filename cannot carry different overrides; that combination throws rather\n * than dropping one silently.\n */\n configs?: readonly (FileExtractionConfig | null)[];\n}\n\nexport interface WaitOptions extends JobScopeParams {\n /** Total time to wait before throwing TimeoutError. Default 5 minutes. */\n timeoutMs?: number;\n /** Initial poll interval. Default 1000ms. */\n pollIntervalMs?: number;\n /** `exponential` doubles the interval each cycle (capped). Default exponential. */\n backoff?: BackoffStrategy;\n}\n\nexport interface ExtractAndWaitParams extends ExtractParams, WaitOptions {}\n\nexport interface ListJobsParams extends JobScopeParams {\n limit?: number;\n offset?: number;\n}\n\nexport interface AuditParams {\n action?: string;\n limit?: number;\n offset?: number;\n}\n\n/** Offset pagination accepted by the paginated list endpoints. */\nexport interface PaginationParams {\n limit?: number;\n offset?: number;\n}\n\n/** Filters accepted by `listExtractionEvents`. */\nexport interface ListExtractionEventsParams extends PaginationParams {\n /** How many days to look back. Defaults to 30 server-side, clamped to 1..=365. */\n days?: number;\n}\n\n/** The two multipart parts `submitAutoTune` sends. */\nexport interface SubmitAutoTuneParams {\n /** JSON-encoded into the required `request` part. */\n request: CreateAutoTuneJobRequest;\n /** One binary `file` part per document referenced by `request.documents[].filename`. */\n files: readonly FileLike[];\n}\n\n/** Options accepted by `streamCrawlEvents`. */\nexport interface StreamCrawlEventsOptions extends JobScopeParams {\n /**\n * Aborts the stream from outside the loop. Breaking out of the `for await`\n * already closes the response body, so this is only needed to hang up from\n * somewhere else — a React effect teardown, a shutdown handler.\n */\n signal?: AbortSignal;\n}\n\n/** Filters accepted by `listRooms`. */\nexport interface ListRoomsParams extends PaginationParams {\n /** `deleted` lists the deleted rooms that can still be restored; the server default is `live`. */\n state?: RoomListState;\n}\n\n/** Options accepted by `previewRoomInvitation` and `acceptRoomInvitation`. */\nexport interface RoomInvitationOptions {\n /**\n * Dashboard session token of the signed-in invitee, sent as the bearer for\n * this call only. The invitation routes admit a signed-in user, never an API\n * key (which answers 403), so pass it unless the client itself was built\n * with that user's session token as `apiKey`.\n */\n sessionToken?: string;\n}\n\n/** Filters accepted by `listIntegrationDocuments`. */\nexport interface ListIntegrationDocumentsParams {\n /** Comma-separated MIME types to restrict the listing to. */\n mimeTypes?: string;\n /** Source-specific folder to list instead of the connection root. */\n folderId?: string;\n /** Upper bound on the number of documents returned. */\n limit?: number;\n /** Number of documents to skip before returning results. */\n offset?: number;\n}\n\nexport interface BackendDateRange {\n startDate: string;\n endDate: string;\n}\nexport interface BackendOAuthCallbackParams {\n code: string;\n state: string;\n}\nexport interface BackendAuditParams {\n action?: string;\n limit?: number;\n offset?: number;\n}\nexport interface BackendSandboxExtractParams {\n file: FileLike;\n}\nexport interface PublicSandboxExtractParams {\n file?: FileLike;\n mode?: string;\n preset?: string;\n url?: string;\n sandboxToken?: string;\n}\n\n/** Underlying `openapi-fetch` client, typed over the Enterprise API schema. */\nexport type XbergRawClient = Client<paths>;\n\n/**\n * High-level dual-target client. Construct with `new XbergClient({ baseUrl, apiKey })`.\n */\nexport class XbergClient {\n private readonly baseUrl: string;\n /**\n * Origin used by the Enterprise backend methods. Defaults to `baseUrl`.\n */\n public readonly controlPlaneBaseUrl: string;\n private readonly controlPlaneToken: string | undefined;\n private readonly headers: Record<string, string>;\n private readonly fetchImpl: typeof fetch;\n private readonly timeoutMs: number;\n private readonly retries: number;\n private readonly retryOn: readonly number[];\n private readonly retryNonIdempotent: boolean;\n private readonly retryBackoff: BackoffStrategy;\n private readonly sleep: (ms: number) => Promise<void>;\n private readonly target?: Target;\n private probedTier: Target | undefined;\n /** In-flight `/healthz` probe, memoised so concurrent callers share one request (single-flight). */\n private tierProbe: Promise<Target> | undefined;\n /** Underlying `openapi-fetch` client — exposed for advanced use. */\n public readonly raw: XbergRawClient;\n\n public constructor(options: XbergClientOptions) {\n if (options.target !== undefined) {\n this.target = options.target;\n }\n this.baseUrl = resolveBaseUrl(options.baseUrl, options.target);\n this.controlPlaneBaseUrl = resolveControlPlaneBaseUrl(options.controlPlaneBaseUrl, this.baseUrl);\n this.controlPlaneToken = options.controlPlaneToken ?? options.apiKey;\n this.fetchImpl = options.fetch ?? fetch;\n this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n this.retries = options.retries ?? 0;\n this.retryOn = options.retryOn ?? DEFAULT_RETRY_STATUSES;\n this.retryNonIdempotent = options.retryNonIdempotent ?? false;\n this.retryBackoff = options.retryBackoff ?? \"exponential\";\n this.sleep = options.sleep ?? defaultSleep;\n\n this.headers = {\n \"User-Agent\": USER_AGENT,\n ...options.headers,\n };\n if (options.apiKey !== undefined) {\n this.headers[\"Authorization\"] = `Bearer ${options.apiKey}`;\n }\n\n this.raw = createOpenApiClient<paths>({\n baseUrl: this.baseUrl,\n headers: this.headers,\n fetch: this.fetchImpl,\n });\n }\n\n /** Enterprise backend `DELETE /auth/account`. */\n public async deleteAccount(): Promise<void> {\n return await this.backendRequest<void>(\"DELETE\", `/auth/account`);\n }\n /** Enterprise backend `GET /auth/config`. */\n public async getAuthConfig(): Promise<BackendAuthConfigResponse> {\n return await this.backendRequest<BackendAuthConfigResponse>(\"GET\", `/auth/config`, { backendPublic: true });\n }\n /** Enterprise backend `GET /auth/profile`. */\n public async getUserProfile(): Promise<BackendUserProfileResponse> {\n return await this.backendRequest<BackendUserProfileResponse>(\"GET\", \"/auth/profile\");\n }\n /** Enterprise backend `PATCH /auth/profile`. */\n public async updateUserProfile(body: BackendUpdateUserProfileRequest): Promise<BackendUserProfileResponse> {\n return await this.backendRequest<BackendUserProfileResponse>(\"PATCH\", \"/auth/profile\", { json: body });\n }\n /** Enterprise backend `POST /auth/login`. */\n public async backendLogin(body: BackendLoginRequest): Promise<BackendLoginResponse> {\n return await this.backendRequest<BackendLoginResponse>(\"POST\", `/auth/login`, { json: body, backendPublic: true });\n }\n /** Enterprise backend `GET /healthz`. */\n public async healthz(): Promise<BackendHealthResponse> {\n return await this.backendRequest<BackendHealthResponse>(\"GET\", `/healthz`, { backendPublic: true });\n }\n /** Enterprise backend `GET /readyz`. */\n public async readyz(): Promise<BackendReadinessResponse> {\n return await this.backendRequest<BackendReadinessResponse>(\"GET\", `/readyz`, { backendPublic: true });\n }\n /** Enterprise backend `POST /v1/invitations/accept`. */\n public async acceptInvitation(body: BackendAcceptInvitationRequest): Promise<BackendMemberResponse> {\n return await this.backendRequest<BackendMemberResponse>(\"POST\", `/v1/invitations/accept`, { json: body });\n }\n /** Enterprise backend `GET /v1/oauth/callback`. */\n public async oauthCallback(params: BackendOAuthCallbackParams): Promise<string> {\n const response = await this.requestWithRetry(\"GET\", \"/v1/oauth/callback\", {\n controlPlane: true,\n backendPublic: true,\n acceptRedirect: true,\n params: { code: params.code, state: params.state },\n });\n const location = response.headers.get(\"location\");\n await response.body?.cancel();\n if (response.status !== 303 || location === null || location.length === 0) {\n throw new XbergError(\"OAuth callback did not return a 303 Location\", { status: response.status, body: null });\n }\n return location;\n }\n /** Enterprise backend `GET /v1/projects`. */\n public async backendListProjects(params: PaginationParams = {}): Promise<BackendListProjectsResponse> {\n return await this.backendRequest<BackendListProjectsResponse>(\"GET\", `/v1/projects`, {\n params: { limit: params.limit, offset: params.offset },\n });\n }\n /** Enterprise backend `POST /v1/projects`. */\n public async backendCreateProject(body: BackendCreateProjectRequest): Promise<BackendProjectResponse> {\n return await this.backendRequest<BackendProjectResponse>(\"POST\", `/v1/projects`, { json: body });\n }\n /** Enterprise backend `GET /v1/projects/{id}`. */\n public async getProject(projectId: string): Promise<BackendProjectResponse> {\n return await this.backendRequest<BackendProjectResponse>(\"GET\", `/v1/projects/${encodePathSegment(projectId)}`);\n }\n /** Enterprise backend `DELETE /v1/projects/{id}`. */\n public async deleteProject(projectId: string, params: { erase?: boolean } = {}): Promise<void> {\n return await this.backendRequest<void>(\"DELETE\", `/v1/projects/${encodePathSegment(projectId)}`, {\n params: { erase: params.erase === undefined ? undefined : String(params.erase) },\n });\n }\n /** Enterprise backend `PATCH /v1/projects/{id}`. */\n public async updateProject(projectId: string, body: BackendUpdateProjectRequest): Promise<BackendProjectResponse> {\n return await this.backendRequest<BackendProjectResponse>(\"PATCH\", `/v1/projects/${encodePathSegment(projectId)}`, {\n json: body,\n });\n }\n /** Enterprise backend `GET /v1/projects/{id}/analytics`. */\n public async getAnalytics(projectId: string, params: BackendDateRange): Promise<BackendAnalyticsResponse> {\n return await this.backendRequest<BackendAnalyticsResponse>(\n \"GET\",\n `/v1/projects/${encodePathSegment(projectId)}/analytics`,\n { params: { start_date: params.startDate, end_date: params.endDate } },\n );\n }\n /** Enterprise backend `GET /v1/projects/{id}/api-keys`. */\n public async backendListApiKeys(\n projectId: string,\n params: PaginationParams = {},\n ): Promise<BackendListApiKeysResponse> {\n return await this.backendRequest<BackendListApiKeysResponse>(\n \"GET\",\n `/v1/projects/${encodePathSegment(projectId)}/api-keys`,\n { params: { limit: params.limit, offset: params.offset } },\n );\n }\n /** Enterprise backend `POST /v1/projects/{id}/api-keys`. */\n public async backendCreateApiKey(\n projectId: string,\n body: BackendCreateApiKeyRequest,\n ): Promise<BackendCreateApiKeyResponse> {\n return await this.backendRequest<BackendCreateApiKeyResponse>(\n \"POST\",\n `/v1/projects/${encodePathSegment(projectId)}/api-keys`,\n { json: body },\n );\n }\n /** Enterprise backend `DELETE /v1/projects/{id}/api-keys/{key_id}`. */\n public async backendRevokeApiKey(projectId: string, apiKeyId: string): Promise<void> {\n return await this.backendRequest<void>(\n \"DELETE\",\n `/v1/projects/${encodePathSegment(projectId)}/api-keys/${encodePathSegment(apiKeyId)}`,\n );\n }\n /** Enterprise backend `POST /v1/projects/{id}/api-keys/{key_id}/regenerate`. */\n public async regenerateApiKey(projectId: string, apiKeyId: string): Promise<BackendCreateApiKeyResponse> {\n return await this.backendRequest<BackendCreateApiKeyResponse>(\n \"POST\",\n `/v1/projects/${encodePathSegment(projectId)}/api-keys/${encodePathSegment(apiKeyId)}/regenerate`,\n );\n }\n /** Enterprise backend `GET /v1/projects/{id}/audit`. */\n public async listProjectAudit(\n projectId: string,\n params: BackendAuditParams = {},\n ): Promise<BackendListAuditEntriesResponse> {\n return await this.backendRequest<BackendListAuditEntriesResponse>(\n \"GET\",\n `/v1/projects/${encodePathSegment(projectId)}/audit`,\n { params: { action: params.action, limit: params.limit, offset: params.offset } },\n );\n }\n /** Enterprise backend `GET /v1/projects/{id}/billing`. */\n public async getBilling(projectId: string): Promise<BackendBillingResponse> {\n return await this.backendRequest<BackendBillingResponse>(\n \"GET\",\n `/v1/projects/${encodePathSegment(projectId)}/billing`,\n );\n }\n /** Enterprise backend `POST /v1/projects/{id}/billing/checkout`. */\n public async createCheckout(projectId: string): Promise<BackendCheckoutResponse> {\n return await this.backendRequest<BackendCheckoutResponse>(\n \"POST\",\n `/v1/projects/${encodePathSegment(projectId)}/billing/checkout`,\n );\n }\n /** Enterprise backend `POST /v1/projects/{id}/billing/portal`. */\n public async createPortal(projectId: string): Promise<BackendPortalResponse> {\n return await this.backendRequest<BackendPortalResponse>(\n \"POST\",\n `/v1/projects/${encodePathSegment(projectId)}/billing/portal`,\n );\n }\n /** Enterprise backend `GET /v1/projects/{id}/integrations`. */\n public async backendListIntegrations(\n projectId: string,\n params: PaginationParams = {},\n ): Promise<BackendListIntegrationsResponse> {\n return await this.backendRequest<BackendListIntegrationsResponse>(\n \"GET\",\n `/v1/projects/${encodePathSegment(projectId)}/integrations`,\n { params: { limit: params.limit, offset: params.offset } },\n );\n }\n /** Enterprise backend `POST /v1/projects/{id}/integrations`. */\n public async backendCreateIntegration(\n projectId: string,\n body: BackendCreateIntegrationRequest,\n ): Promise<BackendIntegrationResponse> {\n return await this.backendRequest<BackendIntegrationResponse>(\n \"POST\",\n `/v1/projects/${encodePathSegment(projectId)}/integrations`,\n { json: body },\n );\n }\n /** Enterprise backend `GET /v1/projects/{id}/integrations/{iid}`. */\n public async backendGetIntegration(projectId: string, integrationId: string): Promise<BackendIntegrationResponse> {\n return await this.backendRequest<BackendIntegrationResponse>(\n \"GET\",\n `/v1/projects/${encodePathSegment(projectId)}/integrations/${encodePathSegment(integrationId)}`,\n );\n }\n /** Enterprise backend `DELETE /v1/projects/{id}/integrations/{iid}`. */\n public async backendDeleteIntegration(projectId: string, integrationId: string): Promise<void> {\n return await this.backendRequest<void>(\n \"DELETE\",\n `/v1/projects/${encodePathSegment(projectId)}/integrations/${encodePathSegment(integrationId)}`,\n );\n }\n /** Enterprise backend `POST /v1/projects/{id}/integrations/{iid}/connect`. */\n public async oauthConnect(projectId: string, integrationId: string): Promise<BackendBeginConnectResponse> {\n return await this.backendRequest<BackendBeginConnectResponse>(\n \"POST\",\n `/v1/projects/${encodePathSegment(projectId)}/integrations/${encodePathSegment(integrationId)}/connect`,\n );\n }\n /** Enterprise backend `POST /v1/projects/{id}/integrations/{iid}/disconnect`. */\n public async backendDisconnectIntegration(projectId: string, integrationId: string): Promise<void> {\n return await this.backendRequest<void>(\n \"POST\",\n `/v1/projects/${encodePathSegment(projectId)}/integrations/${encodePathSegment(integrationId)}/disconnect`,\n );\n }\n /** Enterprise backend `GET /v1/projects/{id}/integrations/{iid}/documents`. */\n public async backendListIntegrationDocuments(\n projectId: string,\n integrationId: string,\n params: ListIntegrationDocumentsParams = {},\n ): Promise<BackendListDocumentsResponse> {\n return await this.backendRequest<BackendListDocumentsResponse>(\n \"GET\",\n `/v1/projects/${encodePathSegment(projectId)}/integrations/${encodePathSegment(integrationId)}/documents`,\n {\n params: {\n mime_types: params.mimeTypes,\n folder_id: params.folderId,\n limit: params.limit,\n offset: params.offset,\n },\n },\n );\n }\n /** Enterprise backend `GET /v1/projects/{id}/integrations/{iid}/documents/{doc_id}`. */\n public async backendFetchIntegrationDocument(\n projectId: string,\n integrationId: string,\n documentId: string,\n ): Promise<Uint8Array> {\n return await this.requestBytes(\n \"GET\",\n `/v1/projects/${encodePathSegment(projectId)}/integrations/${encodePathSegment(integrationId)}/documents/${encodePathSegment(documentId)}`,\n { controlPlane: true },\n );\n }\n /** Enterprise backend `GET /v1/projects/{id}/integrations/{iid}/sync`. */\n public async backendGetIntegrationSync(\n projectId: string,\n integrationId: string,\n ): Promise<BackendIntegrationSyncResponse> {\n return await this.backendRequest<BackendIntegrationSyncResponse>(\n \"GET\",\n `/v1/projects/${encodePathSegment(projectId)}/integrations/${encodePathSegment(integrationId)}/sync`,\n );\n }\n /** Enterprise backend `PUT /v1/projects/{id}/integrations/{iid}/sync`. */\n public async backendSetIntegrationSync(\n projectId: string,\n integrationId: string,\n body: BackendSetIntegrationSyncRequest,\n ): Promise<void> {\n return await this.backendRequest<void>(\n \"PUT\",\n `/v1/projects/${encodePathSegment(projectId)}/integrations/${encodePathSegment(integrationId)}/sync`,\n { json: body },\n );\n }\n /** Enterprise backend `GET /v1/projects/{id}/invitations`. */\n public async listInvitations(\n projectId: string,\n params: PaginationParams = {},\n ): Promise<BackendListInvitationsResponse> {\n return await this.backendRequest<BackendListInvitationsResponse>(\n \"GET\",\n `/v1/projects/${encodePathSegment(projectId)}/invitations`,\n { params: { limit: params.limit, offset: params.offset } },\n );\n }\n /** Enterprise backend `POST /v1/projects/{id}/invitations`. */\n public async inviteUser(\n projectId: string,\n body: BackendCreateInvitationRequest,\n ): Promise<BackendCreateInvitationResponse> {\n return await this.backendRequest<BackendCreateInvitationResponse>(\n \"POST\",\n `/v1/projects/${encodePathSegment(projectId)}/invitations`,\n { json: body },\n );\n }\n /** Enterprise backend `DELETE /v1/projects/{id}/invitations/{inv_id}`. */\n public async revokeInvitation(projectId: string, invitationId: string): Promise<void> {\n return await this.backendRequest<void>(\n \"DELETE\",\n `/v1/projects/${encodePathSegment(projectId)}/invitations/${encodePathSegment(invitationId)}`,\n );\n }\n /** Enterprise backend `POST /v1/projects/{id}/leave`. */\n public async leaveProject(projectId: string): Promise<void> {\n return await this.backendRequest<void>(\"POST\", `/v1/projects/${encodePathSegment(projectId)}/leave`);\n }\n /** Enterprise backend `GET /v1/projects/{id}/members`. */\n public async listMembers(projectId: string, params: PaginationParams = {}): Promise<BackendListMembersResponse> {\n return await this.backendRequest<BackendListMembersResponse>(\n \"GET\",\n `/v1/projects/${encodePathSegment(projectId)}/members`,\n { params: { limit: params.limit, offset: params.offset } },\n );\n }\n /** Enterprise backend `DELETE /v1/projects/{id}/members/{user_id}`. */\n public async removeMember(projectId: string, userId: string): Promise<void> {\n return await this.backendRequest<void>(\n \"DELETE\",\n `/v1/projects/${encodePathSegment(projectId)}/members/${encodePathSegment(userId)}`,\n );\n }\n /** Enterprise backend `PATCH /v1/projects/{id}/members/{user_id}`. */\n public async updateMemberRole(\n projectId: string,\n userId: string,\n body: BackendUpdateMemberRoleRequest,\n ): Promise<BackendMemberResponse> {\n return await this.backendRequest<BackendMemberResponse>(\n \"PATCH\",\n `/v1/projects/${encodePathSegment(projectId)}/members/${encodePathSegment(userId)}`,\n { json: body },\n );\n }\n /** Enterprise backend `PATCH /v1/projects/{id}/members/{user_id}/custom-role`. */\n public async assignProjectRole(\n projectId: string,\n userId: string,\n body: BackendAssignProjectRoleRequest,\n ): Promise<void> {\n return await this.backendRequest<void>(\n \"PATCH\",\n `/v1/projects/${encodePathSegment(projectId)}/members/${encodePathSegment(userId)}/custom-role`,\n {\n json: body,\n },\n );\n }\n /** Enterprise backend `GET /v1/projects/{id}/rag-config`. */\n public async backendGetRagConfig(projectId: string): Promise<BackendRagConfigResponse> {\n return await this.backendRequest<BackendRagConfigResponse>(\n \"GET\",\n `/v1/projects/${encodePathSegment(projectId)}/rag-config`,\n );\n }\n /** Enterprise backend `PUT /v1/projects/{id}/rag-config`. */\n public async backendSetRagConfig(\n projectId: string,\n body: BackendSetRagConfigRequest,\n ): Promise<BackendRagConfigResponse> {\n return await this.backendRequest<BackendRagConfigResponse>(\n \"PUT\",\n `/v1/projects/${encodePathSegment(projectId)}/rag-config`,\n { json: body },\n );\n }\n /** Enterprise backend `GET /v1/projects/{id}/roles`. */\n public async listProjectRoles(\n projectId: string,\n params: PaginationParams = {},\n ): Promise<BackendListProjectRolesResponse> {\n return await this.backendRequest<BackendListProjectRolesResponse>(\n \"GET\",\n `/v1/projects/${encodePathSegment(projectId)}/roles`,\n {\n params: { limit: params.limit, offset: params.offset },\n },\n );\n }\n /** Enterprise backend `POST /v1/projects/{id}/roles`. */\n public async createProjectRole(\n projectId: string,\n body: BackendCreateProjectRoleRequest,\n ): Promise<BackendProjectRoleResponse> {\n return await this.backendRequest<BackendProjectRoleResponse>(\n \"POST\",\n `/v1/projects/${encodePathSegment(projectId)}/roles`,\n { json: body },\n );\n }\n /** Enterprise backend `GET /v1/projects/{id}/roles/{role_id}`. */\n public async getProjectRole(projectId: string, roleId: string): Promise<BackendProjectRoleResponse> {\n return await this.backendRequest<BackendProjectRoleResponse>(\n \"GET\",\n `/v1/projects/${encodePathSegment(projectId)}/roles/${encodePathSegment(roleId)}`,\n );\n }\n /** Enterprise backend `PATCH /v1/projects/{id}/roles/{role_id}`. */\n public async updateProjectRole(\n projectId: string,\n roleId: string,\n body: BackendUpdateProjectRoleRequest,\n ): Promise<BackendProjectRoleResponse> {\n return await this.backendRequest<BackendProjectRoleResponse>(\n \"PATCH\",\n `/v1/projects/${encodePathSegment(projectId)}/roles/${encodePathSegment(roleId)}`,\n {\n json: body,\n },\n );\n }\n /** Enterprise backend `DELETE /v1/projects/{id}/roles/{role_id}`. */\n public async deleteProjectRole(projectId: string, roleId: string): Promise<void> {\n return await this.backendRequest<void>(\n \"DELETE\",\n `/v1/projects/${encodePathSegment(projectId)}/roles/${encodePathSegment(roleId)}`,\n );\n }\n /** Enterprise backend `GET /v1/projects/{project_id}/saml/domains`. */\n public async listSamlDomains(projectId: string): Promise<BackendSamlDomainResponse[]> {\n return await this.backendRequest<BackendSamlDomainResponse[]>(\n \"GET\",\n `/v1/projects/${encodePathSegment(projectId)}/saml/domains`,\n );\n }\n /** Enterprise backend `POST /v1/projects/{project_id}/saml/domains`. */\n public async createSamlDomain(projectId: string, body: BackendSamlDomainRequest): Promise<BackendSamlDomainResponse> {\n return await this.backendRequest<BackendSamlDomainResponse>(\n \"POST\",\n `/v1/projects/${encodePathSegment(projectId)}/saml/domains`,\n { json: body },\n );\n }\n /** Enterprise backend `POST /v1/projects/{project_id}/saml/domains/{domain}/verify`. */\n public async verifySamlDomain(projectId: string, domain: string): Promise<void> {\n return await this.backendRequest<void>(\n \"POST\",\n `/v1/projects/${encodePathSegment(projectId)}/saml/domains/${encodePathSegment(domain)}/verify`,\n );\n }\n /** Enterprise backend `GET /v1/projects/{project_id}/saml/providers`. */\n public async listSamlProviders(projectId: string): Promise<BackendSamlProviderResponse[]> {\n return await this.backendRequest<BackendSamlProviderResponse[]>(\n \"GET\",\n `/v1/projects/${encodePathSegment(projectId)}/saml/providers`,\n );\n }\n /** Enterprise backend `POST /v1/projects/{project_id}/saml/providers`. */\n public async createSamlProvider(\n projectId: string,\n body: BackendSamlProviderRequest,\n ): Promise<BackendSamlProviderResponse> {\n return await this.backendRequest<BackendSamlProviderResponse>(\n \"POST\",\n `/v1/projects/${encodePathSegment(projectId)}/saml/providers`,\n {\n json: body,\n },\n );\n }\n /** Enterprise backend `PUT /v1/projects/{project_id}/saml/providers/{provider_id}`. */\n public async updateSamlProvider(\n projectId: string,\n providerId: string,\n body: BackendSamlProviderRequest,\n ): Promise<BackendSamlProviderResponse> {\n return await this.backendRequest<BackendSamlProviderResponse>(\n \"PUT\",\n `/v1/projects/${encodePathSegment(projectId)}/saml/providers/${encodePathSegment(providerId)}`,\n { json: body },\n );\n }\n /** Enterprise backend `DELETE /v1/projects/{project_id}/saml/providers/{provider_id}`. */\n public async deleteSamlProvider(projectId: string, providerId: string): Promise<void> {\n return await this.backendRequest<void>(\n \"DELETE\",\n `/v1/projects/${encodePathSegment(projectId)}/saml/providers/${encodePathSegment(providerId)}`,\n );\n }\n /** Enterprise backend `POST /v1/projects/{id}/sandbox/extract`. */\n public async sandboxExtract(\n projectId: string,\n params: BackendSandboxExtractParams,\n ): Promise<BackendSandboxExtractResponse> {\n return await this.backendRequest<BackendSandboxExtractResponse>(\n \"POST\",\n `/v1/projects/${encodePathSegment(projectId)}/sandbox/extract`,\n { body: sandboxForm(params) },\n );\n }\n /** Enterprise backend `GET /v1/projects/{id}/scim/connections`. */\n public async listScimConnections(projectId: string): Promise<BackendListScimConnectionsResponse> {\n return await this.backendRequest<BackendListScimConnectionsResponse>(\n \"GET\",\n `/v1/projects/${encodePathSegment(projectId)}/scim/connections`,\n );\n }\n /** Enterprise backend `POST /v1/projects/{id}/scim/connections`. */\n public async createScimConnection(\n projectId: string,\n body: BackendCreateScimConnectionRequest,\n ): Promise<BackendCreateScimConnectionResponse> {\n return await this.backendRequest<BackendCreateScimConnectionResponse>(\n \"POST\",\n `/v1/projects/${encodePathSegment(projectId)}/scim/connections`,\n {\n json: body,\n },\n );\n }\n /** Enterprise backend `GET /v1/projects/{id}/scim/connections/{connection_id}/groups`. */\n public async listScimAdminGroups(\n projectId: string,\n connectionId: string,\n ): Promise<BackendListScimAdminGroupsResponse> {\n return await this.backendRequest<BackendListScimAdminGroupsResponse>(\n \"GET\",\n `/v1/projects/${encodePathSegment(projectId)}/scim/connections/${encodePathSegment(connectionId)}/groups`,\n );\n }\n /** Enterprise backend `PUT /v1/projects/{id}/scim/connections/{connection_id}/groups/{group_id}/roles`. */\n public async replaceScimGroupRoles(\n projectId: string,\n connectionId: string,\n groupId: string,\n body: BackendReplaceScimGroupRolesRequest,\n ): Promise<void> {\n return await this.backendRequest<void>(\n \"PUT\",\n `/v1/projects/${encodePathSegment(projectId)}/scim/connections/${encodePathSegment(connectionId)}/groups/${encodePathSegment(groupId)}/roles`,\n {\n json: body,\n },\n );\n }\n /** Enterprise backend `POST /v1/projects/{id}/scim/connections/{connection_id}/rotate`. */\n public async rotateScimConnectionSecret(\n projectId: string,\n connectionId: string,\n ): Promise<BackendCreateScimConnectionResponse> {\n return await this.backendRequest<BackendCreateScimConnectionResponse>(\n \"POST\",\n `/v1/projects/${encodePathSegment(projectId)}/scim/connections/${encodePathSegment(connectionId)}/rotate`,\n );\n }\n /** Enterprise backend `GET /v1/projects/{id}/usage`. */\n public async getUsage(projectId: string, params: BackendDateRange): Promise<BackendUsageResponse> {\n return await this.backendRequest<BackendUsageResponse>(\n \"GET\",\n `/v1/projects/${encodePathSegment(projectId)}/usage`,\n { params: { start_date: params.startDate, end_date: params.endDate } },\n );\n }\n /** Enterprise backend `GET /v1/projects/{id}/webhooks`. */\n public async listWebhooks(projectId: string, params: PaginationParams = {}): Promise<BackendListWebhooksResponse> {\n return await this.backendRequest<BackendListWebhooksResponse>(\n \"GET\",\n `/v1/projects/${encodePathSegment(projectId)}/webhooks`,\n { params: { limit: params.limit, offset: params.offset } },\n );\n }\n /** Enterprise backend `POST /v1/projects/{id}/webhooks`. */\n public async createWebhook(projectId: string, body: BackendCreateWebhookRequest): Promise<BackendWebhookResponse> {\n return await this.backendRequest<BackendWebhookResponse>(\n \"POST\",\n `/v1/projects/${encodePathSegment(projectId)}/webhooks`,\n { json: body },\n );\n }\n /** Enterprise backend `DELETE /v1/projects/{id}/webhooks/{wh_id}`. */\n public async deleteWebhook(projectId: string, webhookId: string): Promise<void> {\n return await this.backendRequest<void>(\n \"DELETE\",\n `/v1/projects/${encodePathSegment(projectId)}/webhooks/${encodePathSegment(webhookId)}`,\n );\n }\n /** Enterprise backend `PATCH /v1/projects/{id}/webhooks/{wh_id}`. */\n public async updateWebhook(\n projectId: string,\n webhookId: string,\n body: BackendUpdateWebhookRequest,\n ): Promise<BackendWebhookResponse> {\n return await this.backendRequest<BackendWebhookResponse>(\n \"PATCH\",\n `/v1/projects/${encodePathSegment(projectId)}/webhooks/${encodePathSegment(webhookId)}`,\n { json: body },\n );\n }\n /** Enterprise backend `GET /v1/projects/{id}/webhooks/{wh_id}/deliveries`. */\n public async listWebhookDeliveries(\n projectId: string,\n webhookId: string,\n params: PaginationParams = {},\n ): Promise<BackendListWebhookDeliveriesResponse> {\n return await this.backendRequest<BackendListWebhookDeliveriesResponse>(\n \"GET\",\n `/v1/projects/${encodePathSegment(projectId)}/webhooks/${encodePathSegment(webhookId)}/deliveries`,\n { params: { limit: params.limit, offset: params.offset } },\n );\n }\n /** Enterprise backend `GET /v1/projects/{id}/webhooks/{wh_id}/deliveries/{delivery_id}`. */\n public async getWebhookDelivery(\n projectId: string,\n webhookId: string,\n deliveryId: string,\n ): Promise<BackendWebhookDeliveryDetailResponse> {\n return await this.backendRequest<BackendWebhookDeliveryDetailResponse>(\n \"GET\",\n `/v1/projects/${encodePathSegment(projectId)}/webhooks/${encodePathSegment(webhookId)}/deliveries/${encodePathSegment(deliveryId)}`,\n );\n }\n /** Enterprise backend `POST /v1/projects/{id}/webhooks/{wh_id}/deliveries/{delivery_id}/retry`. */\n public async retryWebhookDelivery(\n projectId: string,\n webhookId: string,\n deliveryId: string,\n ): Promise<BackendRetryWebhookDeliveryResponse> {\n return await this.backendRequest<BackendRetryWebhookDeliveryResponse>(\n \"POST\",\n `/v1/projects/${encodePathSegment(projectId)}/webhooks/${encodePathSegment(webhookId)}/deliveries/${encodePathSegment(deliveryId)}/retry`,\n );\n }\n /** Enterprise backend `POST /v1/projects/{id}/webhooks/{wh_id}/test`. */\n public async testWebhook(projectId: string, webhookId: string): Promise<BackendWebhookTestResponse> {\n return await this.backendRequest<BackendWebhookTestResponse>(\n \"POST\",\n `/v1/projects/${encodePathSegment(projectId)}/webhooks/${encodePathSegment(webhookId)}/test`,\n );\n }\n /** Enterprise backend `POST /v1/sandbox/public/extract`. */\n public async publicSandboxExtract(params: PublicSandboxExtractParams): Promise<BackendSandboxExtractResponse> {\n return await this.backendRequest<BackendSandboxExtractResponse>(\"POST\", `/v1/sandbox/public/extract`, {\n body: sandboxForm(params),\n ...(params.sandboxToken !== undefined ? { sandboxToken: params.sandboxToken } : {}),\n backendPublic: true,\n });\n }\n\n // -- Shared surface (Enterprise + Pro) ---------------------------------\n\n /**\n * Submit a single document for extraction. Returns the initial {@link Job}\n * record (still pending — call `waitForJob` to await completion).\n */\n public async extract(params: ExtractParams): Promise<Job> {\n const jobs = await this.extractBatch({\n files: [params.file],\n ...(params.projectId !== undefined ? { projectId: params.projectId } : {}),\n ...(params.documentId !== undefined ? { documentIds: [params.documentId] } : {}),\n ...(params.options !== undefined ? { options: params.options } : {}),\n ...(params.webhook !== undefined ? { webhook: params.webhook } : {}),\n ...(params.config !== undefined ? { configs: [params.config] } : {}),\n });\n const first = jobs[0];\n if (first === undefined) {\n throw new XbergError(\"Server did not return any job IDs\", { status: 500, body: { jobs } });\n }\n return first;\n }\n\n /**\n * Submit multiple documents in a single multipart request. Returns one\n * {@link Job} per file, in the same order.\n */\n public async extractBatch(params: ExtractBatchParams): Promise<Job[]> {\n if (params.files.length === 0) {\n throw new XbergError(\"extractBatch called with no files\", { status: 400, body: null });\n }\n\n const filenames = params.files.map(describeFile);\n const documentIds = prepareDocumentLineage(filenames, params.documentIds);\n if (documentIds.size > 0) await this.requireTier(\"enterprise\", \"extract document lineage\");\n if (params.projectId !== undefined) await this.requireTier(\"pro\", \"projectId\");\n const projectHeader = this.projectHeaderName();\n const form = new FormData();\n // ~keep The Enterprise parser captures lineage when reading each file part.\n for (const [filename, documentId] of documentIds) form.append(`document_id-${filename}`, documentId);\n const parts = params.files.map(toBlob);\n for (const { blob, filename } of parts) {\n form.append(\"file\", blob, filename);\n }\n if (params.options !== undefined) {\n form.append(\"options\", JSON.stringify(params.options));\n }\n if (params.webhook !== undefined) {\n form.append(\"webhook\", JSON.stringify(params.webhook));\n }\n appendPerFileConfigs(form, filenames, params.configs);\n\n const body = await this.requestJson<ExtractResponse>(\"POST\", \"/v1/extract\", {\n body: form,\n ...(params.projectId !== undefined ? { headers: { [projectHeader]: params.projectId } } : {}),\n });\n const jobIds = body.job_ids ?? [];\n const now = new Date().toISOString();\n // ~keep `POST /v1/extract` answers with job IDs alone, so the rest of each record is\n // synthesized from what was submitted; `mime_type` is the type the file was uploaded under.\n return parts.map(({ blob, filename }, index) => {\n const id = jobIds[index];\n if (id === undefined) {\n throw new XbergError(`Server returned ${jobIds.length} job IDs for ${params.files.length} files`, {\n status: 500,\n body,\n });\n }\n return {\n id,\n filename,\n mime_type: blob.type.length > 0 ? blob.type : OCTET_STREAM_MEDIA_TYPE,\n status: \"pending\",\n created_at: now,\n };\n });\n }\n\n /** Fetch a tagged extraction or crawl job record (`GET /v1/jobs/{id}`). */\n public async getJob(jobId: string, scope: JobScopeParams = {}): Promise<GetJobResponse> {\n return parseJobResponse(\n await this.requestJson<unknown>(\"GET\", `${JOBS_PATH}/${encodePathSegment(jobId)}`, {\n params: await this.jobScope(scope),\n }),\n );\n }\n\n /**\n * Fetch a job's stored result document (`GET /v1/jobs/{id}/result`).\n *\n * Declared by both tiers with an identical `JobResult` envelope; the\n * extracted documents live in `results`. Distinct from {@link getJob}, which\n * returns the job's metadata record.\n */\n public async getJobResult(jobId: string, scope: JobScopeParams = {}): Promise<JobResult> {\n return await this.requestJson<JobResult>(\"GET\", `${JOBS_PATH}/${encodePathSegment(jobId)}/result`, {\n params: await this.jobScope(scope),\n });\n }\n\n /** List jobs (paginated) via `GET /v1/jobs`. */\n public async listJobs(params: ListJobsParams = {}): Promise<ListJobsResponse> {\n return await this.requestJson<ListJobsResponse>(\"GET\", JOBS_PATH, {\n params: { ...(await this.jobScope(params)), limit: params.limit, offset: params.offset },\n });\n }\n\n /**\n * Cancel a job (`DELETE /v1/jobs/{id}`). Idempotent: both a successful\n * cancellation and a job that already reached a terminal status answer\n * `204`.\n */\n public async cancelJob(jobId: string, scope: JobScopeParams = {}): Promise<void> {\n await this.requestJson(\"DELETE\", `${JOBS_PATH}/${encodePathSegment(jobId)}`, {\n params: await this.jobScope(scope),\n });\n }\n\n /**\n * Poll {@link getJob} until the job reaches a terminal status. Throws\n * {@link TimeoutError} if the wait exceeds `timeoutMs`. Throws\n * {@link XbergError} if the terminal status is `failed` or `cancelled`.\n */\n public async waitForJob(jobId: string, options: WaitOptions = {}): Promise<Job> {\n const timeoutMs = options.timeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS;\n const initialInterval = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;\n const backoff = options.backoff ?? \"exponential\";\n const start = Date.now();\n let interval = initialInterval;\n\n for (;;) {\n const job = await this.getJob(jobId, options);\n if (job.job_type !== \"extraction\") {\n throw new ValidationError(\"expected extraction job, received crawl job\", { status: 200, body: job });\n }\n if (TERMINAL_JOB_STATUSES.includes(job.status)) {\n if (SUCCESS_JOB_STATUSES.includes(job.status)) {\n return job;\n }\n throw new XbergError(`Job ${jobId} ended with status ${job.status}`, { status: 200, body: job });\n }\n\n const elapsed = Date.now() - start;\n const remaining = timeoutMs - elapsed;\n if (remaining <= 0) {\n throw new TimeoutError(`Timed out waiting for job ${jobId} after ${timeoutMs}ms`, { status: 408, body: job });\n }\n const delay = Math.min(interval, remaining);\n await this.sleep(delay);\n if (backoff === \"exponential\") {\n interval = Math.min(interval * DEFAULT_BACKOFF_FACTOR, DEFAULT_RETRY_BACKOFF_CAP_MS);\n }\n }\n }\n\n /** Wait for many jobs in parallel. */\n public async waitForJobs(jobIds: readonly string[], options: WaitOptions = {}): Promise<Job[]> {\n return await Promise.all(jobIds.map((id) => this.waitForJob(id, options)));\n }\n\n /** Convenience: extract one file and await its result. */\n public async extractAndWait(params: ExtractAndWaitParams): Promise<Job> {\n const extractParams: ExtractParams = {\n file: params.file,\n ...(params.projectId !== undefined ? { projectId: params.projectId } : {}),\n ...(params.documentId !== undefined ? { documentId: params.documentId } : {}),\n ...(params.options !== undefined ? { options: params.options } : {}),\n ...(params.webhook !== undefined ? { webhook: params.webhook } : {}),\n ...(params.config !== undefined ? { config: params.config } : {}),\n };\n const job = await this.extract(extractParams);\n const waitOptions: WaitOptions = {\n ...(params.projectId !== undefined ? { projectId: params.projectId } : {}),\n ...(params.timeoutMs !== undefined ? { timeoutMs: params.timeoutMs } : {}),\n ...(params.pollIntervalMs !== undefined ? { pollIntervalMs: params.pollIntervalMs } : {}),\n ...(params.backoff !== undefined ? { backoff: params.backoff } : {}),\n };\n return this.waitForJob(job.id, waitOptions);\n }\n\n /** Fetch audit-log entries via `GET /v1/audit`. */\n public async audit(params: AuditParams = {}): Promise<ListAuditEntriesResponse> {\n return await this.requestJson<ListAuditEntriesResponse>(\"GET\", \"/v1/audit\", {\n params: { action: params.action, limit: params.limit, offset: params.offset },\n });\n }\n\n // -- Shared preset catalogue -------------------------------------------\n\n /** List the read-only curated presets (`GET /v1/presets`). */\n public async presets(): Promise<PresetSummary[]> {\n return await this.requestJson<PresetSummary[]>(\"GET\", \"/v1/presets\");\n }\n\n /** Fetch one curated preset in full (`GET /v1/presets/{id}`). */\n public async getPreset(presetId: string): Promise<PresetDetail> {\n return await this.requestJson<PresetDetail>(\"GET\", `/v1/presets/${encodePathSegment(presetId)}`);\n }\n\n /**\n * Download a preset's bundled sample file\n * (`GET /v1/presets/{id}/sample/{name}`). The response is raw bytes, not\n * JSON.\n */\n public async getPresetSample(presetId: string, name: string): Promise<Uint8Array> {\n const path = `/v1/presets/${encodePathSegment(presetId)}/sample/${encodePathSegment(name)}`;\n return await this.requestBytes(\"GET\", path);\n }\n\n // -- Shared RAG surface ------------------------------------------------\n\n /** List RAG collections (`GET /v1/rag/collections`). */\n public async listRagCollections(): Promise<unknown> {\n return await this.requestJson(\"GET\", \"/v1/rag/collections\");\n }\n\n /** Create a RAG collection (`POST /v1/rag/collections`). */\n public async createRagCollection(body: Record<string, unknown>): Promise<unknown> {\n return await this.requestJson(\"POST\", \"/v1/rag/collections\", { json: body });\n }\n\n /** Fetch a RAG collection (`GET /v1/rag/collections/{name}`). */\n public async getRagCollection(name: string): Promise<unknown> {\n return await this.requestJson(\"GET\", `/v1/rag/collections/${encodePathSegment(name)}`);\n }\n\n /** Delete a RAG collection (`DELETE /v1/rag/collections/{name}`). The spec documents a 204 with no content. */\n public async deleteRagCollection(name: string): Promise<void> {\n await this.requestJson(\"DELETE\", `/v1/rag/collections/${encodePathSegment(name)}`);\n }\n\n /** Add documents to a RAG collection (`POST /v1/rag/collections/{name}/documents`). */\n public async addRagDocuments(name: string, body: Record<string, unknown>): Promise<unknown> {\n return await this.requestJson(\"POST\", `/v1/rag/collections/${encodePathSegment(name)}/documents`, { json: body });\n }\n\n /**\n * Delete documents from a RAG collection, by ID list or metadata filter\n * (`DELETE /v1/rag/collections/{name}/documents`). Unlike\n * {@link deleteRagCollection}, this answers `200` with a body reporting how\n * many documents were removed.\n */\n public async deleteRagDocuments(name: string, body: Record<string, unknown>): Promise<unknown> {\n return await this.requestJson(\"DELETE\", `/v1/rag/collections/${encodePathSegment(name)}/documents`, {\n json: body,\n });\n }\n\n /** Reindex a RAG document (`POST /v1/rag/collections/{name}/documents/{id}/reindex`). */\n public async reindexRagDocument(name: string, documentId: string, body?: Record<string, unknown>): Promise<unknown> {\n const path = `/v1/rag/collections/${encodePathSegment(name)}/documents/${encodePathSegment(documentId)}/reindex`;\n return await this.requestJson(\"POST\", path, body !== undefined ? { json: body } : {});\n }\n\n /** Retrieve chunks from a RAG collection (`POST /v1/rag/collections/{name}/retrieve`). */\n public async ragRetrieve(name: string, body: Record<string, unknown>): Promise<unknown> {\n return await this.requestJson(\"POST\", `/v1/rag/collections/${encodePathSegment(name)}/retrieve`, { json: body });\n }\n\n /** Kick off an embedding migration (`POST /v1/rag/collections/{name}/migrate-embeddings`). */\n public async migrateRagEmbeddings(name: string, body: Record<string, unknown>): Promise<unknown> {\n return await this.requestJson(\"POST\", `/v1/rag/collections/${encodePathSegment(name)}/migrate-embeddings`, {\n json: body,\n });\n }\n\n /** Poll an embedding-migration job (`GET .../migrate-embeddings/{jobId}`). */\n public async getRagMigrationJob(name: string, jobId: string): Promise<unknown> {\n const path = `/v1/rag/collections/${encodePathSegment(name)}/migrate-embeddings/${encodePathSegment(jobId)}`;\n return await this.requestJson(\"GET\", path);\n }\n\n /** Fetch a RAG job's status (`GET /v1/rag/jobs/{jobId}`). */\n public async getRagJob(jobId: string): Promise<unknown> {\n return await this.requestJson(\"GET\", `/v1/rag/jobs/${encodePathSegment(jobId)}`);\n }\n\n /**\n * List the managed embedding presets this server build ships\n * (`GET /v1/rag/embedding-presets`), in the canonical backend order.\n */\n public async listManagedEmbeddingPresets(): Promise<ListManagedEmbeddingPresetsResponse> {\n return await this.requestJson<ListManagedEmbeddingPresetsResponse>(\"GET\", \"/v1/rag/embedding-presets\");\n }\n\n // -- Shared saved presets ----------------------------------------------\n //\n // Both tiers serve the same routes under the same spelling and the same\n // schemas, so nothing here is tier-dependent.\n\n /** List the project's saved presets (`GET /v1/saved_presets`). */\n public async listSavedPresets(params: PaginationParams = {}): Promise<ListSavedPresetsResponse> {\n return await this.requestJson<ListSavedPresetsResponse>(\"GET\", SAVED_PRESETS_PATH, {\n params: { limit: params.limit, offset: params.offset },\n });\n }\n\n /** Create a saved preset (`POST /v1/saved_presets`). */\n public async createSavedPreset(body: CreateSavedPresetRequest): Promise<CreateSavedPresetResponse> {\n return await this.requestJson<CreateSavedPresetResponse>(\"POST\", SAVED_PRESETS_PATH, { json: body });\n }\n\n /** Fetch one saved preset (`GET /v1/saved_presets/{preset_id}`). */\n public async getSavedPreset(presetId: string): Promise<SavedPresetDetail> {\n return await this.requestJson<SavedPresetDetail>(\"GET\", this.savedPresetPath(presetId));\n }\n\n /** Update a saved preset (`PATCH /v1/saved_presets/{preset_id}`). */\n public async updateSavedPreset(presetId: string, body: UpdateSavedPresetRequest): Promise<UpdateSavedPresetResponse> {\n return await this.requestJson<UpdateSavedPresetResponse>(\"PATCH\", this.savedPresetPath(presetId), { json: body });\n }\n\n /** Delete a saved preset (`DELETE /v1/saved_presets/{preset_id}`). */\n public async deleteSavedPreset(presetId: string): Promise<void> {\n await this.requestJson(\"DELETE\", this.savedPresetPath(presetId));\n }\n\n // -- Shared auto-tune surface ------------------------------------------\n\n /** List the project's auto-tune jobs (`GET /v1/auto-tune`). */\n public async listAutoTuneJobs(params: PaginationParams = {}): Promise<ListAutoTuneJobsResponse> {\n return await this.requestJson<ListAutoTuneJobsResponse>(\"GET\", AUTO_TUNE_PATH, {\n params: { limit: params.limit, offset: params.offset },\n });\n }\n\n /**\n * Submit an auto-tune job (`POST /v1/auto-tune`). Sent as `multipart/form-data`:\n * a JSON `request` part plus one binary `file` part per document.\n */\n public async submitAutoTune(params: SubmitAutoTuneParams): Promise<CreateAutoTuneJobResponse> {\n if (params.files.length === 0) {\n throw new XbergError(\"submitAutoTune called with no files\", { status: 400, body: null });\n }\n const form = new FormData();\n form.append(\"request\", JSON.stringify(params.request));\n for (const file of params.files) {\n const { blob, filename } = toBlob(file);\n form.append(\"file\", blob, filename);\n }\n return await this.requestJson<CreateAutoTuneJobResponse>(\"POST\", AUTO_TUNE_PATH, { body: form });\n }\n\n /** Fetch the deployment's tunable knobs and OCR backends (`GET /v1/auto-tune/capabilities`). */\n public async getAutoTuneCapabilities(): Promise<AutoTuneCapabilitiesResponse> {\n return await this.requestJson<AutoTuneCapabilitiesResponse>(\"GET\", `${AUTO_TUNE_PATH}/capabilities`);\n }\n\n /** Fetch an auto-tune job's status (`GET /v1/auto-tune/{id}`). */\n public async getAutoTuneStatus(autoTuneJobId: string): Promise<AutoTuneJobStatus> {\n return await this.requestJson<AutoTuneJobStatus>(\"GET\", this.autoTunePath(autoTuneJobId));\n }\n\n /** Delete an auto-tune job (`DELETE /v1/auto-tune/{id}`). */\n public async deleteAutoTuneJob(autoTuneJobId: string): Promise<void> {\n await this.requestJson(\"DELETE\", this.autoTunePath(autoTuneJobId));\n }\n\n /**\n * Stop a running auto-tune job (`POST /v1/auto-tune/{id}/stop`).\n *\n * The run finishes the trial in flight and then completes with the partial\n * leaderboard, so {@link getAutoTuneResult} still serves the best configuration\n * the search found. Idempotent: a job that already reached a terminal state\n * answers `204` and nothing changes.\n */\n public async stopAutoTuneJob(autoTuneJobId: string): Promise<void> {\n await this.requestJson(\"POST\", `${this.autoTunePath(autoTuneJobId)}/stop`);\n }\n\n /** Promote an auto-tune result to a named tuning profile (`POST /v1/auto-tune/{id}/promote`). */\n public async promoteAutoTuneProfile(\n autoTuneJobId: string,\n body: PromoteProfileRequest,\n ): Promise<TuningProfileDetail> {\n return await this.requestJson<TuningProfileDetail>(\"POST\", `${this.autoTunePath(autoTuneJobId)}/promote`, {\n json: body,\n });\n }\n\n /** Fetch a completed auto-tune job's result (`GET /v1/auto-tune/{id}/result`). */\n public async getAutoTuneResult(autoTuneJobId: string): Promise<AutoTuneResult> {\n return await this.requestJson<AutoTuneResult>(\"GET\", `${this.autoTunePath(autoTuneJobId)}/result`);\n }\n\n // -- Shared tuning profiles --------------------------------------------\n\n /** List the project's tuning profiles (`GET /v1/tuning-profiles`). */\n public async listTuningProfiles(params: PaginationParams = {}): Promise<ListTuningProfilesResponse> {\n return await this.requestJson<ListTuningProfilesResponse>(\"GET\", TUNING_PROFILES_PATH, {\n params: { limit: params.limit, offset: params.offset },\n });\n }\n\n /** Fetch one tuning profile (`GET /v1/tuning-profiles/{id}`). */\n public async getTuningProfile(profileId: string): Promise<TuningProfileDetail> {\n return await this.requestJson<TuningProfileDetail>(\"GET\", this.tuningProfilePath(profileId));\n }\n\n /** Delete a tuning profile (`DELETE /v1/tuning-profiles/{id}`). */\n public async deleteTuningProfile(profileId: string): Promise<void> {\n await this.requestJson(\"DELETE\", this.tuningProfilePath(profileId));\n }\n\n // -- Shared uploads, usage, pages, enrichment and crawl streams ---------\n //\n // ~keep Every route below is declared by both specs; the Enterprise gate these\n // once carried denied Pro callers endpoints Pro serves.\n\n /**\n * Request presigned upload URLs (`POST /v1/uploads/presign`).\n *\n * The request body is typed off the Enterprise schema, whose `config` is a full\n * `ExtractionConfig`; Pro declares that field as an open object and accepts the\n * same payload.\n */\n public async presignUpload(body: PresignUploadRequest): Promise<PresignUploadResponse> {\n return await this.requestJson<PresignUploadResponse>(\"POST\", \"/v1/uploads/presign\", { json: body });\n }\n\n /** Confirm presigned uploads and start processing (`POST /v1/uploads/confirm`). */\n public async confirmUpload(body: ConfirmUploadRequest): Promise<ConfirmUploadResponse> {\n return await this.requestJson<ConfirmUploadResponse>(\"POST\", \"/v1/uploads/confirm\", { json: body });\n }\n\n /** Fetch usage/metering data for a date window (`GET /v1/usage`). */\n public async usage(params?: QueryParams): Promise<UsageResponse> {\n const init: RequestParts = params !== undefined ? { params } : {};\n return await this.requestJson<UsageResponse>(\"GET\", \"/v1/usage\", init);\n }\n\n /**\n * Download one rendered page of an extraction job\n * (`GET /v1/jobs/{job_id}/pages/{page_number}`). The response is a PNG image —\n * raw bytes, not JSON. `pageNumber` is 1-indexed.\n */\n public async getJobPage(jobId: string, pageNumber: number, scope: JobScopeParams = {}): Promise<Uint8Array> {\n const path = `${JOBS_PATH}/${encodePathSegment(jobId)}/pages/${encodePathSegment(String(pageNumber))}`;\n return await this.requestBytes(\"GET\", path, { params: await this.jobScope(scope) });\n }\n\n /** Submit text for enrichment (`POST /v1/enrich`). */\n public async submitEnrich(body: EnrichTextRequest, scope: JobScopeParams = {}): Promise<EnrichJobSubmitted> {\n return await this.requestJson<EnrichJobSubmitted>(\"POST\", ENRICH_PATH, {\n json: body,\n params: await this.jobScope(scope),\n });\n }\n\n /** Fetch an enrichment job's status (`GET /v1/enrich/{job_id}`). */\n public async getEnrichStatus(jobId: string, scope: JobScopeParams = {}): Promise<EnrichJobStatus> {\n return await this.requestJson<EnrichJobStatus>(\"GET\", `${ENRICH_PATH}/${encodePathSegment(jobId)}`, {\n params: await this.jobScope(scope),\n });\n }\n\n /**\n * Stream a crawl job's events (`GET /v1/crawl-jobs/{crawl_job_id}/events`,\n * Server-Sent Events).\n *\n * Returns an `AsyncIterable` of the `kind`-discriminated {@link CrawlEvent}\n * union; the server closes the stream after the `complete` event.\n *\n * ```ts\n * for await (const event of client.streamCrawlEvents(crawlJobId)) {\n * if (event.kind === \"page\") {\n * console.log(event.url, event.status_code);\n * }\n * }\n * ```\n *\n * Nothing is requested until iteration begins, and the response body is\n * cancelled when iteration ends: on `complete`, on `break`/`return` out of the\n * loop, on a thrown error, or when `options.signal` aborts. A stream is idle\n * between events by design, so unlike every other method here it carries no\n * request timeout and is not routed through the retry engine — a retried\n * subscription would redeliver every event the caller had already handled.\n */\n public streamCrawlEvents(crawlJobId: string, options: StreamCrawlEventsOptions = {}): AsyncIterable<CrawlEvent> {\n const path = `${CRAWL_JOBS_PATH}/${encodePathSegment(crawlJobId)}/events`;\n const open = async (): Promise<Response> =>\n this.openEventStream(`${path}${buildQueryString(await this.jobScope(options))}`, options.signal);\n return { [Symbol.asyncIterator]: (): AsyncIterator<CrawlEvent> => iterateCrawlEvents(open) };\n }\n\n /**\n * Enterprise liveness and feature availability (`GET /healthz` on the data plane).\n * Decoded leniently: a missing feature object reads as `{ enabled: false }` and\n * unknown fields are kept, so an older or newer server does not break the call. ~keep\n */\n public async enterpriseHealthz(): Promise<EnterpriseHealthResponse> {\n await this.requireTier(\"enterprise\", \"enterpriseHealthz\");\n const body = await this.requestJson<unknown>(\"GET\", \"/healthz\");\n return decodeEnterpriseHealth(body);\n }\n\n // -- Pro-only surface --------------------------------------------------\n\n /**\n * Pro liveness and coarse license/capability state (`GET /healthz`).\n * Use readiness checks to assess dependencies. ~keep\n */\n public async proHealthz(): Promise<ProHealthResponse> {\n await this.requireTier(\"pro\", \"proHealthz\");\n return this.requestJson<ProHealthResponse>(\"GET\", \"/healthz\");\n }\n\n /** Pro only: fetch the instance's accepted auth methods (`GET /auth/config`). */\n public async authConfig(): Promise<AuthConfigResponse> {\n await this.requireTier(\"pro\", \"authConfig\");\n return this.requestJson<AuthConfigResponse>(\"GET\", \"/auth/config\");\n }\n\n /** Pro only: exchange a verified OIDC ID token for a Pro session JWT (`POST /auth/login`). */\n public async login(body: LoginRequest): Promise<LoginResponse> {\n await this.requireTier(\"pro\", \"login\");\n return this.requestJson<LoginResponse>(\"POST\", \"/auth/login\", { json: body });\n }\n\n /**\n * Pro only: read the running instance's license detail (`GET /v1/license`) —\n * licensee, plan, expiry, grace window and days remaining. Requires an admin\n * API key or an admin session.\n */\n public async getLicenseInfo(): Promise<LicenseInfoResponse> {\n await this.requireTier(\"pro\", \"getLicenseInfo\");\n return this.requestJson<LicenseInfoResponse>(\"GET\", \"/v1/license\");\n }\n\n /**\n * Pro only: upload a document's bytes against a presigned local capability\n * (`PUT /v1/uploads/local/{project_id}/{token}`).\n *\n * `projectId` and `token` come from the `upload_url` {@link presignUpload}\n * returns when the instance stages uploads locally. The capability is one-use,\n * expiring, and bounded by the size limit recorded when it was issued; the\n * body is sent as raw bytes.\n */\n public async putLocalUpload(projectId: string, token: string, file: FileLike): Promise<void> {\n await this.requireTier(\"pro\", \"putLocalUpload\");\n const { blob } = toBlob(file);\n const path = `/v1/uploads/local/${encodePathSegment(projectId)}/${encodePathSegment(token)}`;\n await this.requestJson(\"PUT\", path, {\n body: new Uint8Array(await blob.arrayBuffer()),\n headers: { \"Content-Type\": OCTET_STREAM_MEDIA_TYPE },\n });\n }\n\n /** Pro only: fetch a project's RAG config (`GET /v1/projects/{projectId}/rag-config`). */\n public async getRagConfig(projectId: string): Promise<RagConfigResponse> {\n await this.requireTier(\"pro\", \"getRagConfig\");\n return this.requestJson<RagConfigResponse>(\"GET\", `/v1/projects/${encodePathSegment(projectId)}/rag-config`);\n }\n\n /** Pro only: update a project's RAG config (`PUT /v1/projects/{projectId}/rag-config`). */\n public async setRagConfig(projectId: string, body: SetRagConfigRequest): Promise<RagConfigResponse> {\n await this.requireTier(\"pro\", \"setRagConfig\");\n return this.requestJson<RagConfigResponse>(\"PUT\", `/v1/projects/${encodePathSegment(projectId)}/rag-config`, {\n json: body,\n });\n }\n\n // -- Pro-only control plane (projects, API keys, integrations) ---------\n\n /** Pro only: list the caller's projects (`GET /v1/projects`). */\n public async listProjects(params: PaginationParams = {}): Promise<ListProjectsResponse> {\n await this.requireTier(\"pro\", \"listProjects\");\n return this.requestJson<ListProjectsResponse>(\"GET\", \"/v1/projects\", {\n params: { limit: params.limit, offset: params.offset },\n });\n }\n\n /** Pro only: create a project owned by the caller (`POST /v1/projects`). */\n public async createProject(body: CreateProjectRequest): Promise<ProjectResponse> {\n await this.requireTier(\"pro\", \"createProject\");\n return this.requestJson<ProjectResponse>(\"POST\", \"/v1/projects\", { json: body });\n }\n\n /** Pro only: read a live project visible to the caller. */\n public async proGetProject(projectId: string): Promise<ProjectResponse> {\n await this.requireTier(\"pro\", \"proGetProject\");\n return this.requestJson<ProjectResponse>(\"GET\", this.projectPath(projectId));\n }\n\n /** Pro only: rename a project. */\n public async proUpdateProject(projectId: string, body: ProUpdateProjectRequest): Promise<ProjectResponse> {\n await this.requireTier(\"pro\", \"proUpdateProject\");\n return this.requestJson<ProjectResponse>(\"PATCH\", this.projectPath(projectId), { json: body });\n }\n\n /** Pro only: soft-delete a project and revoke its API keys. */\n public async proDeleteProject(projectId: string): Promise<void> {\n await this.requireTier(\"pro\", \"proDeleteProject\");\n await this.requestJson(\"DELETE\", this.projectPath(projectId));\n }\n\n /** Enterprise only: read the project's stored extraction defaults. */\n public async getProjectExtractionConfig(projectId: string): Promise<ProjectExtractionConfigResponse> {\n await this.requireTier(\"enterprise\", \"getProjectExtractionConfig\");\n const projectHeader = this.projectHeaderName();\n return this.requestJson<ProjectExtractionConfigResponse>(\n \"GET\",\n `${this.projectPath(projectId)}/extraction-config`,\n {\n headers: { [projectHeader]: projectId },\n },\n );\n }\n\n /** Enterprise only: replace the project's stored extraction defaults. */\n public async setProjectExtractionConfig(\n projectId: string,\n body: ExtractionConfig,\n ): Promise<ProjectExtractionConfigResponse> {\n await this.requireTier(\"enterprise\", \"setProjectExtractionConfig\");\n const projectHeader = this.projectHeaderName();\n return this.requestJson<ProjectExtractionConfigResponse>(\n \"PUT\",\n `${this.projectPath(projectId)}/extraction-config`,\n {\n headers: { [projectHeader]: projectId },\n json: body,\n },\n );\n }\n\n /** Enterprise only: clear the project's stored extraction defaults. */\n public async clearProjectExtractionConfig(projectId: string): Promise<void> {\n await this.requireTier(\"enterprise\", \"clearProjectExtractionConfig\");\n const projectHeader = this.projectHeaderName();\n await this.requestJson(\"DELETE\", `${this.projectPath(projectId)}/extraction-config`, {\n headers: { [projectHeader]: projectId },\n });\n }\n\n /** Pro only: list a project's API keys (`GET /v1/projects/{projectId}/api-keys`). */\n public async listApiKeys(projectId: string, params: PaginationParams = {}): Promise<ListApiKeysResponse> {\n await this.requireTier(\"pro\", \"listApiKeys\");\n return this.requestJson<ListApiKeysResponse>(\"GET\", `${this.projectPath(projectId)}/api-keys`, {\n params: { limit: params.limit, offset: params.offset },\n });\n }\n\n /** Pro only: mint an API key for a project (`POST /v1/projects/{projectId}/api-keys`). */\n public async createApiKey(projectId: string, body: CreateApiKeyRequest): Promise<CreateApiKeyResponse> {\n await this.requireTier(\"pro\", \"createApiKey\");\n return this.requestJson<CreateApiKeyResponse>(\"POST\", `${this.projectPath(projectId)}/api-keys`, { json: body });\n }\n\n /** Pro only: revoke an API key (`DELETE /v1/projects/{projectId}/api-keys/{keyId}`). */\n public async revokeApiKey(projectId: string, keyId: string): Promise<void> {\n await this.requireTier(\"pro\", \"revokeApiKey\");\n await this.requestJson(\"DELETE\", `${this.projectPath(projectId)}/api-keys/${encodePathSegment(keyId)}`);\n }\n\n /** Pro only: list a project's integrations (`GET /v1/projects/{projectId}/integrations`). */\n public async listIntegrations(projectId: string, params: PaginationParams = {}): Promise<ListIntegrationsResponse> {\n await this.requireTier(\"pro\", \"listIntegrations\");\n return this.requestJson<ListIntegrationsResponse>(\"GET\", `${this.projectPath(projectId)}/integrations`, {\n params: { limit: params.limit, offset: params.offset },\n });\n }\n\n /** Pro only: create an integration (`POST /v1/projects/{projectId}/integrations`). */\n public async createIntegration(projectId: string, body: CreateIntegrationRequest): Promise<IntegrationResponse> {\n await this.requireTier(\"pro\", \"createIntegration\");\n return this.requestJson<IntegrationResponse>(\"POST\", `${this.projectPath(projectId)}/integrations`, {\n json: body,\n });\n }\n\n /** Pro only: fetch one integration (`GET .../integrations/{integrationId}`). */\n public async getIntegration(projectId: string, integrationId: string): Promise<IntegrationResponse> {\n await this.requireTier(\"pro\", \"getIntegration\");\n return this.requestJson<IntegrationResponse>(\"GET\", this.integrationPath(projectId, integrationId));\n }\n\n /** Pro only: read durable synchronization state for an integration. */\n public async getIntegrationSync(projectId: string, integrationId: string): Promise<IntegrationSyncResponse> {\n await this.requireTier(\"pro\", \"getIntegrationSync\");\n return this.requestJson<IntegrationSyncResponse>(\"GET\", `${this.integrationPath(projectId, integrationId)}/sync`);\n }\n\n /** Pro only: enable or disable durable synchronization for an integration. */\n public async setIntegrationSync(\n projectId: string,\n integrationId: string,\n body: SetIntegrationSyncRequest,\n ): Promise<void> {\n await this.requireTier(\"pro\", \"setIntegrationSync\");\n await this.requestJson(\"PUT\", `${this.integrationPath(projectId, integrationId)}/sync`, {\n json: body,\n });\n }\n\n /** Pro only: delete an integration (`DELETE .../integrations/{integrationId}`). */\n public async deleteIntegration(projectId: string, integrationId: string): Promise<void> {\n await this.requireTier(\"pro\", \"deleteIntegration\");\n await this.requestJson(\"DELETE\", this.integrationPath(projectId, integrationId));\n }\n\n /**\n * Pro only: begin the OAuth flow for an integration\n * (`POST .../integrations/{integrationId}/connect`). Returns the provider\n * authorize URL to redirect the user to.\n */\n public async connectIntegration(projectId: string, integrationId: string): Promise<BeginOAuthResponse> {\n await this.requireTier(\"pro\", \"connectIntegration\");\n return this.requestJson<BeginOAuthResponse>(\"POST\", `${this.integrationPath(projectId, integrationId)}/connect`);\n }\n\n /** Pro only: revoke an integration's OAuth connection (`POST .../disconnect`). */\n public async disconnectIntegration(projectId: string, integrationId: string): Promise<void> {\n await this.requireTier(\"pro\", \"disconnectIntegration\");\n await this.requestJson(\"POST\", `${this.integrationPath(projectId, integrationId)}/disconnect`);\n }\n\n /** Pro only: list the documents an integration exposes (`GET .../documents`). */\n public async listIntegrationDocuments(\n projectId: string,\n integrationId: string,\n params: ListIntegrationDocumentsParams = {},\n ): Promise<ListDocumentsResponse> {\n await this.requireTier(\"pro\", \"listIntegrationDocuments\");\n return this.requestJson<ListDocumentsResponse>(\n \"GET\",\n `${this.integrationPath(projectId, integrationId)}/documents`,\n {\n params: {\n mime_types: params.mimeTypes,\n folder_id: params.folderId,\n limit: params.limit,\n offset: params.offset,\n },\n },\n );\n }\n\n /**\n * Pro only: download one document from an integration\n * (`GET .../documents/{documentId}`). The response is raw bytes, not JSON.\n */\n public async fetchIntegrationDocument(\n projectId: string,\n integrationId: string,\n documentId: string,\n ): Promise<Uint8Array> {\n await this.requireTier(\"pro\", \"fetchIntegrationDocument\");\n const path = `${this.integrationPath(projectId, integrationId)}/documents/${encodePathSegment(documentId)}`;\n return this.requestBytes(\"GET\", path);\n }\n\n // -- Enterprise-only surface ------------------------------------------\n\n /**\n * Enterprise only: fetch a document's latest version with its extraction\n * result (`GET /v1/documents/{documentId}`). The spec declares an inline\n * schema, so the body is returned untyped.\n */\n public async getDocument(documentId: string): Promise<unknown> {\n await this.requireTier(\"enterprise\", \"getDocument\");\n return this.requestJson(\"GET\", this.documentPath(documentId));\n }\n\n /** Enterprise only: list a document's versions (`GET /v1/documents/{id}/versions`). */\n public async versions(documentId: string): Promise<DocumentVersionEntry[]> {\n await this.requireTier(\"enterprise\", \"versions\");\n return this.requestJson<DocumentVersionEntry[]>(\"GET\", `${this.documentPath(documentId)}/versions`);\n }\n\n /**\n * Enterprise only: diff document versions (`GET /v1/documents/{id}/diff`).\n *\n * Computed inline when the server can afford it (`200`, {@link DiffResponse}\n * in `result.body`), or queued for async computation when it can't (`202`,\n * a {@link DiffAsyncAccepted} job envelope in `result.body`) — the same\n * fallback {@link getDiffJob} polls. Narrow on `result.status`:\n *\n * ```ts\n * const result = await client.diff(documentId);\n * if (result.status === 200) {\n * // result.body: DiffResponse\n * } else {\n * // result.body: DiffAsyncAccepted — poll getDiffJob(documentId, result.body.diff_job_id)\n * }\n * ```\n */\n public async diff(documentId: string, params?: QueryParams): Promise<DiffResult> {\n await this.requireTier(\"enterprise\", \"diff\");\n const init: RequestParts = params !== undefined ? { params } : {};\n const { status, body } = await this.requestJsonWithStatus<DiffResponse | DiffAsyncAccepted>(\n \"GET\",\n `${this.documentPath(documentId)}/diff`,\n init,\n );\n return toDiffResult(status, body);\n }\n\n /**\n * Enterprise only: poll a diff job (`GET /v1/documents/{id}/diff/{diffJobId}`).\n *\n * Returns the same {@link DiffResult} union as {@link diff}: `200` once the\n * job has finished (`result.body`: {@link DiffResponse}), `202` while it is\n * still pending (`result.body`: {@link DiffAsyncAccepted}). Narrow on\n * `result.status` as shown in {@link diff}'s TSDoc.\n */\n public async getDiffJob(documentId: string, diffJobId: string): Promise<DiffResult> {\n await this.requireTier(\"enterprise\", \"getDiffJob\");\n const path = `${this.documentPath(documentId)}/diff/${encodePathSegment(diffJobId)}`;\n const { status, body } = await this.requestJsonWithStatus<DiffResponse | DiffAsyncAccepted>(\"GET\", path);\n return toDiffResult(status, body);\n }\n\n /** Enterprise only: list the project's extraction events (`GET /v1/extractions`). */\n public async listExtractionEvents(params: ListExtractionEventsParams = {}): Promise<ListExtractionEventsResponse> {\n await this.requireTier(\"enterprise\", \"listExtractionEvents\");\n return this.requestJson<ListExtractionEventsResponse>(\"GET\", EXTRACTIONS_PATH, {\n params: { days: params.days, limit: params.limit, offset: params.offset },\n });\n }\n\n /**\n * Enterprise only: list a webhook subscription's delivery attempts\n * (`GET /v1/webhooks/{webhook_id}/deliveries`). Metadata only — call\n * {@link getSubscriptionDelivery} for an attempt's payload previews.\n *\n * ~keep Distinct from {@link listWebhookDeliveries}, which reads the same\n * history through the control plane's project-scoped route.\n */\n public async listSubscriptionDeliveries(\n webhookId: string,\n params: PaginationParams = {},\n ): Promise<ListWebhookDeliveriesResponse> {\n await this.requireTier(\"enterprise\", \"listSubscriptionDeliveries\");\n return this.requestJson<ListWebhookDeliveriesResponse>(\"GET\", this.webhookDeliveriesPath(webhookId), {\n params: { limit: params.limit, offset: params.offset },\n });\n }\n\n /**\n * Enterprise only: fetch one delivery attempt with its bounded request and\n * response previews (`GET /v1/webhooks/{webhook_id}/deliveries/{delivery_id}`).\n * The previews can carry project document content.\n */\n public async getSubscriptionDelivery(webhookId: string, deliveryId: string): Promise<WebhookDeliveryDetailResponse> {\n await this.requireTier(\"enterprise\", \"getSubscriptionDelivery\");\n const path = `${this.webhookDeliveriesPath(webhookId)}/${encodePathSegment(deliveryId)}`;\n return this.requestJson<WebhookDeliveryDetailResponse>(\"GET\", path);\n }\n\n // -- Enterprise-only documents and data rooms --------------------------\n //\n // ~keep Every room route answers 404 `data_room.disabled` on a plan without data\n // rooms; that surfaces as DataRoomsDisabledError, and `enterpriseHealthz()`\n // reports it ahead of time as `data_rooms.enabled === false`.\n\n /**\n * Enterprise only: list the project's logical documents (`GET /v1/documents`),\n * each shown by its newest finished version, most recently updated first. An\n * entry's `document_id` is the id {@link addRoomItem} takes.\n */\n public async listDocuments(params: PaginationParams = {}): Promise<ListProjectDocumentsResponse> {\n await this.requireTier(\"enterprise\", \"listDocuments\");\n return this.requestJson<ListProjectDocumentsResponse>(\"GET\", DOCUMENTS_PATH, {\n params: { limit: params.limit, offset: params.offset },\n });\n }\n\n /**\n * Enterprise only: list the data rooms the caller can see (`GET /v1/rooms`),\n * with the rights it holds on each. `state: \"deleted\"` lists the deleted rooms\n * that can still be restored.\n */\n public async listRooms(params: ListRoomsParams = {}): Promise<ListRoomsResponse> {\n await this.requireTier(\"enterprise\", \"listRooms\");\n return this.requestJson<ListRoomsResponse>(\"GET\", ROOMS_PATH, {\n params: { limit: params.limit, offset: params.offset, state: params.state },\n });\n }\n\n /**\n * Enterprise only: create a data room owned by the caller (`POST /v1/rooms`).\n * A project at its room limit answers 409 `quota_exceeded`.\n */\n public async createRoom(body: CreateRoomRequest): Promise<RoomResponse> {\n await this.requireTier(\"enterprise\", \"createRoom\");\n return this.requestJson<RoomResponse>(\"POST\", ROOMS_PATH, { json: body });\n }\n\n /** Enterprise only: fetch one live data room with the caller's rights on it (`GET /v1/rooms/{id}`). */\n public async getRoom(roomId: string): Promise<RoomResponse> {\n await this.requireTier(\"enterprise\", \"getRoom\");\n return this.requestJson<RoomResponse>(\"GET\", this.roomPath(roomId));\n }\n\n /**\n * Enterprise only: rename a data room or change its description\n * (`PATCH /v1/rooms/{id}`).\n *\n * `version` is the room's `version` as last read, sent as `If-Match`. A stale\n * one throws {@link PreconditionFailedError}; read the room again and retry.\n * The returned room carries the new `version`. A `null` description clears it.\n */\n public async updateRoom(roomId: string, body: UpdateRoomRequest, version: number): Promise<RoomResponse> {\n await this.requireTier(\"enterprise\", \"updateRoom\");\n return this.requestJson<RoomResponse>(\"PATCH\", this.roomPath(roomId), {\n json: body,\n headers: ifMatch(version),\n });\n }\n\n /**\n * Enterprise only: delete a live data room (`DELETE /v1/rooms/{id}`). It stays\n * restorable until its `restorable_until`; see {@link restoreRoom}.\n */\n public async deleteRoom(roomId: string): Promise<void> {\n await this.requireTier(\"enterprise\", \"deleteRoom\");\n await this.requestJson(\"DELETE\", this.roomPath(roomId));\n }\n\n /**\n * Enterprise only: restore a deleted data room inside its restore window\n * (`POST /v1/rooms/{id}/restore`). A project at its room limit answers 409.\n */\n public async restoreRoom(roomId: string): Promise<RoomResponse> {\n await this.requireTier(\"enterprise\", \"restoreRoom\");\n return this.requestJson<RoomResponse>(\"POST\", `${this.roomPath(roomId)}/restore`);\n }\n\n /**\n * Enterprise only: list a room's documents in room order\n * (`GET /v1/rooms/{id}/items`). The answer's `version` is the one\n * {@link reorderRoomItems} sends.\n */\n public async listRoomItems(roomId: string, params: PaginationParams = {}): Promise<ListRoomItemsResponse> {\n await this.requireTier(\"enterprise\", \"listRoomItems\");\n return this.requestJson<ListRoomItemsResponse>(\"GET\", `${this.roomPath(roomId)}/items`, {\n params: { limit: params.limit, offset: params.offset },\n });\n }\n\n /**\n * Enterprise only: add a project document to the end of a room\n * (`POST /v1/rooms/{id}/items`). The document needs a finished version; take\n * its id from {@link listDocuments}. It moves the room version without\n * returning it: read it again before the next versioned write.\n */\n public async addRoomItem(roomId: string, body: AddRoomItemRequest): Promise<RoomItemResponse> {\n await this.requireTier(\"enterprise\", \"addRoomItem\");\n return this.requestJson<RoomItemResponse>(\"POST\", `${this.roomPath(roomId)}/items`, { json: body });\n }\n\n /**\n * Enterprise only: set the order of every item in a room\n * (`PUT /v1/rooms/{id}/items/order`). `body.document_ids` names each item once.\n *\n * `version` is the room version from {@link listRoomItems} or\n * {@link getRoom}, sent as `If-Match`; a stale one throws\n * {@link PreconditionFailedError}. The answer carries the new `version`.\n */\n public async reorderRoomItems(\n roomId: string,\n body: ReorderRoomItemsRequest,\n version: number,\n ): Promise<ReorderRoomItemsResponse> {\n await this.requireTier(\"enterprise\", \"reorderRoomItems\");\n return this.requestJson<ReorderRoomItemsResponse>(\"PUT\", `${this.roomPath(roomId)}/items/order`, {\n json: body,\n headers: ifMatch(version),\n });\n }\n\n /**\n * Enterprise only: remove a document from a room\n * (`DELETE /v1/rooms/{id}/items/{document_id}`). The document stays in the project.\n * It moves the room version without returning it. A retried call whose first\n * attempt applied throws {@link NotFoundError}.\n */\n public async removeRoomItem(roomId: string, documentId: string): Promise<void> {\n await this.requireTier(\"enterprise\", \"removeRoomItem\");\n await this.requestJson(\"DELETE\", this.roomItemPath(roomId, documentId));\n }\n\n /**\n * Enterprise only: fetch the extraction result of a room item's newest\n * finished version (`GET /v1/rooms/{id}/items/{document_id}/content`).\n * `result` is `null` while extraction has not finished.\n */\n public async getRoomItemContent(roomId: string, documentId: string): Promise<RoomItemContentResponse> {\n await this.requireTier(\"enterprise\", \"getRoomItemContent\");\n return this.requestJson<RoomItemContentResponse>(\"GET\", `${this.roomItemPath(roomId, documentId)}/content`);\n }\n\n /**\n * Enterprise only: download a room item's original file\n * (`GET /v1/rooms/{id}/items/{document_id}/download`). The response is raw\n * bytes, not JSON. A room that does not allow downloads answers 403.\n */\n public async downloadRoomItem(roomId: string, documentId: string): Promise<Uint8Array> {\n await this.requireTier(\"enterprise\", \"downloadRoomItem\");\n return this.requestBytes(\"GET\", `${this.roomItemPath(roomId, documentId)}/download`);\n }\n\n /**\n * Enterprise only: download one rendered page of a room item as a PNG\n * (`GET /v1/rooms/{id}/items/{document_id}/pages/{page_number}`). Raw bytes,\n * not JSON. `pageNumber` is 1-indexed. Every reader of the room can open it,\n * whatever its download setting.\n */\n public async getRoomItemPage(roomId: string, documentId: string, pageNumber: number): Promise<Uint8Array> {\n await this.requireTier(\"enterprise\", \"getRoomItemPage\");\n const path = `${this.roomItemPath(roomId, documentId)}/pages/${encodePathSegment(String(pageNumber))}`;\n return this.requestBytes(\"GET\", path);\n }\n\n /** Enterprise only: list the users holding a grant on a room (`GET /v1/rooms/{id}/members`). */\n public async listRoomMembers(roomId: string, params: PaginationParams = {}): Promise<ListRoomMembersResponse> {\n await this.requireTier(\"enterprise\", \"listRoomMembers\");\n return this.requestJson<ListRoomMembersResponse>(\"GET\", `${this.roomPath(roomId)}/members`, {\n params: { limit: params.limit, offset: params.offset },\n });\n }\n\n /**\n * Enterprise only: give a project member a grant on a room\n * (`POST /v1/rooms/{id}/members`). Anyone outside the project joins by\n * {@link createRoomInvitation} instead.\n */\n public async addRoomMember(roomId: string, body: AddRoomMemberRequest): Promise<RoomMemberResponse> {\n await this.requireTier(\"enterprise\", \"addRoomMember\");\n return this.requestJson<RoomMemberResponse>(\"POST\", `${this.roomPath(roomId)}/members`, { json: body });\n }\n\n /**\n * Enterprise only: remove a member's grant on a room\n * (`DELETE /v1/rooms/{id}/members/{user_id}`). The owner answers 409; transfer\n * ownership first.\n */\n public async removeRoomMember(roomId: string, userId: string): Promise<void> {\n await this.requireTier(\"enterprise\", \"removeRoomMember\");\n await this.requestJson(\"DELETE\", this.roomMemberPath(roomId, userId));\n }\n\n /**\n * Enterprise only: change a room member's role to an editor or a viewer\n * (`PATCH /v1/rooms/{id}/members/{user_id}`).\n */\n public async changeRoomMemberRole(\n roomId: string,\n userId: string,\n body: RoomChangeRoleRequest,\n ): Promise<RoomMemberResponse> {\n await this.requireTier(\"enterprise\", \"changeRoomMemberRole\");\n return this.requestJson<RoomMemberResponse>(\"PATCH\", this.roomMemberPath(roomId, userId), { json: body });\n }\n\n /**\n * Enterprise only: remove the caller's own grant on a room\n * (`POST /v1/rooms/{id}/leave`). The owner answers 409.\n */\n public async leaveRoom(roomId: string): Promise<void> {\n await this.requireTier(\"enterprise\", \"leaveRoom\");\n await this.requestJson(\"POST\", `${this.roomPath(roomId)}/leave`);\n }\n\n /**\n * Enterprise only: make another room member the owner\n * (`POST /v1/rooms/{id}/ownership`). The new owner must be a project member\n * who already holds a grant on the room.\n */\n public async transferRoomOwnership(roomId: string, body: RoomTransferOwnershipRequest): Promise<void> {\n await this.requireTier(\"enterprise\", \"transferRoomOwnership\");\n await this.requestJson(\"POST\", `${this.roomPath(roomId)}/ownership`, { json: body });\n }\n\n /** Enterprise only: list a data room's share links. */\n public async listRoomLinks(roomId: string, params: PaginationParams = {}): Promise<ListRoomLinksResponse> {\n await this.requireTier(\"enterprise\", \"listRoomLinks\");\n return this.requestJson<ListRoomLinksResponse>(\"GET\", `${this.roomPath(roomId)}/links`, {\n params: { limit: params.limit, offset: params.offset },\n });\n }\n\n /** Enterprise only: create a share link for a data room. */\n public async createRoomLink(roomId: string, body: CreateRoomLinkRequest): Promise<RoomLinkResponse> {\n await this.requireTier(\"enterprise\", \"createRoomLink\");\n return this.requestJson<RoomLinkResponse>(\"POST\", `${this.roomPath(roomId)}/links`, {\n json: body,\n });\n }\n\n /** Enterprise only: revoke a data room share link and its grants. */\n public async revokeRoomLink(roomId: string, linkId: string): Promise<void> {\n await this.requireTier(\"enterprise\", \"revokeRoomLink\");\n await this.requestJson(\"DELETE\", `${this.roomPath(roomId)}/links/${encodePathSegment(linkId)}`);\n }\n\n /** Enterprise only: accept a share link with a signed-in user's session. */\n public async acceptRoomLink(\n body: RoomAcceptInvitationRequest,\n options: RoomInvitationOptions = {},\n ): Promise<AcceptedRoomInvitationResponse> {\n const bearer = sessionBearer(options);\n await this.requireTier(\"enterprise\", \"acceptRoomLink\");\n return this.requestJson<AcceptedRoomInvitationResponse>(\"POST\", \"/v1/room-links/accept\", {\n json: body,\n ...bearer,\n });\n }\n\n /**\n * Enterprise only: list a room's invitations (`GET /v1/rooms/{id}/invitations`).\n * The answer never carries an invitation token.\n */\n public async listRoomInvitations(\n roomId: string,\n params: PaginationParams = {},\n ): Promise<ListRoomInvitationsResponse> {\n await this.requireTier(\"enterprise\", \"listRoomInvitations\");\n return this.requestJson<ListRoomInvitationsResponse>(\"GET\", `${this.roomPath(roomId)}/invitations`, {\n params: { limit: params.limit, offset: params.offset },\n });\n }\n\n /**\n * Enterprise only: invite an email address to a room\n * (`POST /v1/rooms/{id}/invitations`). `token` is in the answer only when the\n * configured delivery channel returns it.\n */\n public async createRoomInvitation(roomId: string, body: RoomInviteRequest): Promise<RoomInvitationResponse> {\n await this.requireTier(\"enterprise\", \"createRoomInvitation\");\n return this.requestJson<RoomInvitationResponse>(\"POST\", `${this.roomPath(roomId)}/invitations`, { json: body });\n }\n\n /**\n * Enterprise only: revoke a pending room invitation\n * (`DELETE /v1/rooms/{id}/invitations/{invitation_id}`).\n */\n public async revokeRoomInvitation(roomId: string, invitationId: string): Promise<void> {\n await this.requireTier(\"enterprise\", \"revokeRoomInvitation\");\n await this.requestJson(\"DELETE\", `${this.roomPath(roomId)}/invitations/${encodePathSegment(invitationId)}`);\n }\n\n /**\n * Enterprise only: show a signed-in invitee the room an invitation token opens\n * (`POST /v1/room-invitations/preview`).\n *\n * Requires a dashboard user session, not an API key: pass\n * `options.sessionToken` or build the client with the session token as\n * `apiKey`. A token that cannot be accepted answers 404, whatever the reason.\n */\n public async previewRoomInvitation(\n body: RoomAcceptInvitationRequest,\n options: RoomInvitationOptions = {},\n ): Promise<RoomInvitationPreviewResponse> {\n await this.requireTier(\"enterprise\", \"previewRoomInvitation\");\n return this.requestJson<RoomInvitationPreviewResponse>(\"POST\", `${ROOM_INVITATIONS_PATH}/preview`, {\n json: body,\n ...sessionBearer(options),\n });\n }\n\n /**\n * Enterprise only: accept an invitation token for the signed-in user\n * (`POST /v1/room-invitations/accept`), granting them the room.\n *\n * Requires a dashboard user session, not an API key: pass\n * `options.sessionToken` or build the client with the session token as\n * `apiKey`. A token that cannot be accepted answers 404, whatever the reason.\n */\n public async acceptRoomInvitation(\n body: RoomAcceptInvitationRequest,\n options: RoomInvitationOptions = {},\n ): Promise<AcceptedRoomInvitationResponse> {\n await this.requireTier(\"enterprise\", \"acceptRoomInvitation\");\n return this.requestJson<AcceptedRoomInvitationResponse>(\"POST\", `${ROOM_INVITATIONS_PATH}/accept`, {\n json: body,\n ...sessionBearer(options),\n });\n }\n\n /**\n * Enterprise only: read a room's publication settings\n * (`GET /v1/rooms/{id}/publication`). `room_version` is the value\n * {@link setRoomPublication} sends.\n */\n public async getRoomPublication(roomId: string): Promise<RoomPublicationResponse> {\n await this.requireTier(\"enterprise\", \"getRoomPublication\");\n return this.requestJson<RoomPublicationResponse>(\"GET\", `${this.roomPath(roomId)}/publication`);\n }\n\n /**\n * Enterprise only: publish or unpublish a room, optionally changing its mode\n * and download setting (`PUT /v1/rooms/{id}/publication`).\n *\n * `version` is the room version (`room_version` from\n * {@link getRoomPublication}, or the room's `version`), sent as `If-Match`; a\n * stale one throws {@link PreconditionFailedError}. The answer carries the\n * new `room_version` and, once published, the public `slug`.\n */\n public async setRoomPublication(\n roomId: string,\n body: SetRoomPublicationRequest,\n version: number,\n ): Promise<RoomPublicationResponse> {\n await this.requireTier(\"enterprise\", \"setRoomPublication\");\n return this.requestJson<RoomPublicationResponse>(\"PUT\", `${this.roomPath(roomId)}/publication`, {\n json: body,\n headers: ifMatch(version),\n });\n }\n\n /**\n * Enterprise only: read a published room by its slug (`GET /public/rooms/{slug}`).\n *\n * Unauthenticated: sends no credential and no cookie, even when the client\n * has an API key. A room that is not published answers 404.\n */\n public async getPublicRoom(slug: string): Promise<PublicRoomResponse> {\n await this.requireTier(\"enterprise\", \"getPublicRoom\");\n return this.requestJson<PublicRoomResponse>(\"GET\", this.publicRoomPath(slug), { anonymous: true });\n }\n\n /**\n * Enterprise only: list a published room's items in room order\n * (`GET /public/rooms/{slug}/items`). Unauthenticated; each item's `item_ref`\n * is what the public content and download methods take.\n */\n public async listPublicRoomItems(slug: string, params: PaginationParams = {}): Promise<PublicRoomItemsResponse> {\n await this.requireTier(\"enterprise\", \"listPublicRoomItems\");\n return this.requestJson<PublicRoomItemsResponse>(\"GET\", `${this.publicRoomPath(slug)}/items`, {\n anonymous: true,\n params: { limit: params.limit, offset: params.offset },\n });\n }\n\n /**\n * Enterprise only: fetch the extraction result of a published room's item\n * (`GET /public/rooms/{slug}/items/{item_ref}/content`). Unauthenticated;\n * `result` is `null` until extraction finishes.\n */\n public async getPublicRoomItemContent(slug: string, itemRef: string): Promise<PublicRoomItemContentResponse> {\n await this.requireTier(\"enterprise\", \"getPublicRoomItemContent\");\n return this.requestJson<PublicRoomItemContentResponse>(\"GET\", `${this.publicRoomItemPath(slug, itemRef)}/content`, {\n anonymous: true,\n });\n }\n\n /**\n * Enterprise only: download a published room item's original file\n * (`GET /public/rooms/{slug}/items/{item_ref}/download`). Unauthenticated; raw\n * bytes, not JSON. A room that does not allow downloads answers 404.\n */\n public async downloadPublicRoomItem(slug: string, itemRef: string): Promise<Uint8Array> {\n await this.requireTier(\"enterprise\", \"downloadPublicRoomItem\");\n return this.requestBytes(\"GET\", `${this.publicRoomItemPath(slug, itemRef)}/download`, { anonymous: true });\n }\n\n // -- Internals ---------------------------------------------------------\n\n private async jobScope(scope: JobScopeParams): Promise<QueryParams> {\n if (scope.projectId !== undefined) await this.requireTier(\"pro\", \"projectId\");\n return { project_id: scope.projectId };\n }\n\n private projectHeaderName(): string {\n return Object.keys(this.headers).find((name) => name.toLowerCase() === \"x-project-id\") ?? \"X-Project-ID\";\n }\n\n /** Build `/v1/projects/{projectId}` with the id percent-encoded. */\n private projectPath(projectId: string): string {\n return `/v1/projects/${encodePathSegment(projectId)}`;\n }\n\n /** Build `/v1/projects/{projectId}/integrations/{integrationId}`. */\n private integrationPath(projectId: string, integrationId: string): string {\n return `${this.projectPath(projectId)}/integrations/${encodePathSegment(integrationId)}`;\n }\n\n /** Build `/v1/documents/{documentId}` with the id percent-encoded. */\n private documentPath(documentId: string): string {\n return `${DOCUMENTS_PATH}/${encodePathSegment(documentId)}`;\n }\n\n /** Build `/v1/rooms/{id}` with the id percent-encoded. */\n private roomPath(roomId: string): string {\n return `${ROOMS_PATH}/${encodePathSegment(roomId)}`;\n }\n\n /** Build `/v1/rooms/{id}/items/{document_id}`. */\n private roomItemPath(roomId: string, documentId: string): string {\n return `${this.roomPath(roomId)}/items/${encodePathSegment(documentId)}`;\n }\n\n /** Build `/v1/rooms/{id}/members/{user_id}`. */\n private roomMemberPath(roomId: string, userId: string): string {\n return `${this.roomPath(roomId)}/members/${encodePathSegment(userId)}`;\n }\n\n /** Build `/public/rooms/{slug}` with the slug percent-encoded. */\n private publicRoomPath(slug: string): string {\n return `${PUBLIC_ROOMS_PATH}/${encodePathSegment(slug)}`;\n }\n\n /** Build `/public/rooms/{slug}/items/{item_ref}`. */\n private publicRoomItemPath(slug: string, itemRef: string): string {\n return `${this.publicRoomPath(slug)}/items/${encodePathSegment(itemRef)}`;\n }\n\n /** Build `/v1/saved_presets/{preset_id}` with the id percent-encoded. */\n private savedPresetPath(presetId: string): string {\n return `${SAVED_PRESETS_PATH}/${encodePathSegment(presetId)}`;\n }\n\n /** Build `/v1/auto-tune/{id}` with the id percent-encoded. */\n private autoTunePath(autoTuneJobId: string): string {\n return `${AUTO_TUNE_PATH}/${encodePathSegment(autoTuneJobId)}`;\n }\n\n /** Build `/v1/tuning-profiles/{id}` with the id percent-encoded. */\n private tuningProfilePath(profileId: string): string {\n return `${TUNING_PROFILES_PATH}/${encodePathSegment(profileId)}`;\n }\n\n /** Build `/v1/webhooks/{webhook_id}/deliveries` with the id percent-encoded. */\n private webhookDeliveriesPath(webhookId: string): string {\n return `${WEBHOOKS_PATH}/${encodePathSegment(webhookId)}/deliveries`;\n }\n\n /**\n * Return the effective tier — an explicit `target` if set, else probed from\n * `/healthz` and cached after the first *successful* probe. A probe that\n * fails (missing, `null`, or unrecognised `tier`) is not cached, so the\n * next call retries instead of being stuck with a poisoned result for the\n * client's lifetime. Concurrent callers share a single in-flight probe.\n */\n private async resolveTier(): Promise<Target> {\n if (this.target !== undefined) {\n return this.target;\n }\n if (this.probedTier !== undefined) {\n return this.probedTier;\n }\n if (this.tierProbe === undefined) {\n this.tierProbe = this.probeTier();\n }\n try {\n const tier = await this.tierProbe;\n this.probedTier = tier;\n return tier;\n } finally {\n this.tierProbe = undefined;\n }\n }\n\n /**\n * Issue the `/healthz` capability probe. Only `\"enterprise\"` and `\"pro\"` —\n * the tier values the specs actually declare — are accepted; anything else\n * (missing `tier`, `null`, or an unrecognised string) throws instead of\n * being treated as a usable result.\n */\n private async probeTier(): Promise<Target> {\n const body = await this.requestJson<{ tier?: unknown }>(\"GET\", \"/healthz\");\n const tier = body?.tier;\n if (tier === \"enterprise\" || tier === \"pro\") {\n return tier;\n }\n throw new XbergError(\n `/healthz returned an unrecognised tier (${JSON.stringify(tier ?? null)}); expected \"enterprise\" or \"pro\"`,\n { status: 0, body },\n );\n }\n\n /** Throw a clear error when the connected tier does not match the required one. */\n private async requireTier(required: Target, methodName: string): Promise<void> {\n const tier = await this.resolveTier();\n if (tier !== required) {\n throw new XbergError(`${methodName}() is not available on the '${tier}' tier (requires the '${required}' tier)`, {\n status: 0,\n body: null,\n });\n }\n }\n\n private backendRequest<T>(method: string, path: string, init: RequestParts = {}): Promise<T> {\n return this.requestJson<T>(method, path, { ...init, controlPlane: true });\n }\n\n private backendHeaders(init: RequestParts): Record<string, string> {\n const headers = new Headers({ ...this.headers, ...init.headers });\n for (const name of [\"authorization\", \"proxy-authorization\", \"cookie\", \"x-api-key\"]) headers.delete(name);\n const token = init.backendPublic ? init.sandboxToken : this.controlPlaneToken;\n if (token !== undefined && token.length > 0) headers.set(\"Authorization\", `Bearer ${token}`);\n if (init.body instanceof FormData || init.json !== undefined) headers.delete(\"content-type\");\n return Object.fromEntries(headers);\n }\n\n /**\n * Data-plane headers: the client's own merged with the call's, then stripped\n * of every credential for an anonymous call, or given a per-call bearer.\n */\n private dataPlaneHeaders(init: RequestParts): Record<string, string> {\n const merged = { ...this.headers, ...init.headers };\n if (!init.anonymous && init.bearerToken === undefined) {\n return merged;\n }\n const headers = new Headers(merged);\n if (init.anonymous) {\n for (const name of CREDENTIAL_HEADERS) headers.delete(name);\n } else if (init.bearerToken !== undefined) {\n headers.set(\"Authorization\", `Bearer ${init.bearerToken}`);\n }\n return Object.fromEntries(headers);\n }\n\n /** Issue a request, raise on non-2xx, and decode the JSON body (undefined for empty bodies). */\n private async requestJson<T = unknown>(method: string, path: string, init: RequestParts = {}): Promise<T> {\n const { body } = await this.requestJsonWithStatus<T>(method, path, init);\n return body;\n }\n\n /**\n * Like {@link requestJson}, but also returns the response's status code.\n * Used by endpoints whose 2xx responses carry different schemas per status\n * (currently only `diff`/`getDiffJob`'s `200`/`202` split).\n */\n private async requestJsonWithStatus<T = unknown>(\n method: string,\n path: string,\n init: RequestParts = {},\n ): Promise<{ status: number; body: T }> {\n const response = await this.requestWithRetry(method, path, init);\n if (response.status === 204) {\n return { status: response.status, body: undefined as T };\n }\n const text = await response.text();\n const body = (text.length > 0 ? JSON.parse(text) : undefined) as T;\n return { status: response.status, body };\n }\n\n /**\n * Open a `text/event-stream` response, deliberately bypassing\n * {@link requestWithRetry}.\n *\n * Two of that method's behaviours are wrong for a subscription. Its retry\n * loop would re-open a partly-consumed stream and redeliver every event the\n * caller already handled — indistinguishable, from the caller's side, from\n * the server sending them twice. And its `AbortSignal.timeout(timeoutMs)`\n * bounds a request/response round trip, while this response stays open for\n * the length of a crawl and is idle between events by design; the caller's\n * own `signal` is the only deadline.\n */\n private async openEventStream(path: string, signal?: AbortSignal): Promise<Response> {\n const url = `${this.baseUrl}${path}`;\n const requestInit: RequestInit = {\n method: \"GET\",\n headers: { ...this.headers, Accept: EVENT_STREAM_MEDIA_TYPE },\n };\n if (signal !== undefined) {\n requestInit.signal = signal;\n }\n\n let response: Response;\n try {\n response = await this.fetchImpl(url, requestInit);\n } catch (cause) {\n throw new XbergError(`Network error contacting ${url}`, { status: 0, body: null, cause });\n }\n if (!response.ok) {\n await raiseForStatus(response);\n throw new XbergError(\"Unreachable\", { status: response.status, body: null });\n }\n return response;\n }\n\n /** Issue a request, raise on non-2xx, and return the response body as raw bytes. */\n private async requestBytes(method: string, path: string, init: RequestParts = {}): Promise<Uint8Array> {\n const response = await this.requestWithRetry(method, path, init);\n return new Uint8Array(await response.arrayBuffer());\n }\n\n /**\n * Issue a raw HTTP request with auth, timeout, query params, and retry\n * handling. Returns the raw (2xx) {@link Response}; non-2xx responses are\n * mapped to a thrown {@link XbergError} subclass.\n */\n private prepareRequest(method: string, init: RequestParts): RequestInit {\n const headers = init.controlPlane ? this.backendHeaders(init) : this.dataPlaneHeaders(init);\n let body: FormData | string | Uint8Array | undefined = init.body;\n if (init.json !== undefined) {\n headers[\"Content-Type\"] = \"application/json\";\n body = JSON.stringify(init.json);\n }\n const requestInit: RequestInit = {\n method,\n headers,\n signal: AbortSignal.timeout(this.timeoutMs),\n ...(init.controlPlane ? ({ credentials: \"omit\", redirect: \"manual\" } as const) : {}),\n ...(init.anonymous ? ({ credentials: \"omit\" } as const) : {}),\n };\n if (body !== undefined) {\n requestInit.body = body;\n }\n return requestInit;\n }\n\n /**\n * Whether a response status is retryable for this request under the configured policy. A request\n * carrying `If-Match` (`conditional`) is treated like a POST: once an attempt applied, the room\n * version moved, so a replay can only answer 412.\n */\n private shouldRetryStatus(method: string, status: number, conditional: boolean): boolean {\n if (!this.retryOn.includes(status)) {\n return false;\n }\n if (status === 429 || this.retryNonIdempotent) {\n return true;\n }\n return !conditional && IDEMPOTENT_METHODS.has(method.toUpperCase());\n }\n\n private async requestWithRetry(method: string, path: string, init: RequestParts = {}): Promise<Response> {\n if (init.controlPlane && (this.target ?? this.probedTier) === \"pro\") {\n throw new XbergError(\"Enterprise backend methods are not available on the 'pro' tier\", { status: 0, body: null });\n }\n const origin = init.controlPlane ? this.controlPlaneBaseUrl : this.baseUrl;\n const url = `${origin}${path}${buildQueryString(init.params)}`;\n const conditional = Object.keys(init.headers ?? {}).some((name) => name.toLowerCase() === \"if-match\");\n let attempt = 0;\n let interval = DEFAULT_RETRY_BACKOFF_BASE_MS;\n for (;;) {\n const requestInit = this.prepareRequest(method, init);\n\n let response: Response;\n try {\n response = await this.fetchImpl(url, requestInit);\n } catch (cause) {\n if (attempt < this.retries) {\n attempt += 1;\n await this.sleep(interval);\n interval = nextBackoffInterval(interval, this.retryBackoff);\n continue;\n }\n if (init.controlPlane) {\n throw new XbergError(`Network error contacting Enterprise control plane (${method} ${path})`, {\n status: 0,\n body: null,\n });\n }\n throw new XbergError(`Network error contacting ${url}`, { status: 0, body: null, cause });\n }\n\n if (response.ok || (init.acceptRedirect && response.status === 303)) {\n return response;\n }\n\n if (this.shouldRetryStatus(method, response.status, conditional) && attempt < this.retries) {\n attempt += 1;\n const retryAfter = parseRetryAfterHeader(response.headers.get(\"retry-after\"));\n const wait = retryAfter !== undefined ? retryAfter * 1000 : interval;\n await this.sleep(wait);\n interval = nextBackoffInterval(interval, this.retryBackoff);\n continue;\n }\n\n throw await raiseForStatus(response);\n }\n }\n}\n\n/** Parts accepted by the internal request engine. */\ninterface RequestParts {\n controlPlane?: boolean;\n /** Send no credential header and no cookie: the unauthenticated `/public/...` routes. */\n anonymous?: boolean;\n /** Replace the client's data-plane bearer for this one call. */\n bearerToken?: string;\n backendPublic?: boolean;\n sandboxToken?: string;\n acceptRedirect?: boolean;\n body?: FormData | string | Uint8Array;\n json?: unknown;\n headers?: Record<string, string>;\n params?: QueryParams;\n}\n\n/** The `If-Match` header a room write sends: the room version, quoted as an entity tag. */\nfunction ifMatch(version: number): Record<string, string> {\n if (!Number.isSafeInteger(version) || version < 0) {\n throw new ValidationError(`Room version must be a non-negative integer, got ${String(version)}`, {\n status: 0,\n body: null,\n });\n }\n return { \"If-Match\": `\"${version}\"` };\n}\n\n/** The per-call bearer an invitation route sends, when the caller supplied a session token. */\nfunction sessionBearer(options: RoomInvitationOptions): Pick<RequestParts, \"bearerToken\"> {\n if (options.sessionToken === undefined) {\n return {};\n }\n if (options.sessionToken.trim().length === 0) {\n throw new ValidationError(\"sessionToken must not be blank\", { status: 0, body: null });\n }\n return { bearerToken: options.sessionToken };\n}\n\nfunction decodeEnterpriseHealth(payload: unknown): EnterpriseHealthResponse {\n if (typeof payload !== \"object\" || payload === null || Array.isArray(payload)) {\n throw new ValidationError(\"unexpected /healthz response shape\", { status: 200, body: payload });\n }\n const record = payload as Record<string, unknown>;\n return {\n ...record,\n status: typeof record[\"status\"] === \"string\" ? record[\"status\"] : \"\",\n tier: typeof record[\"tier\"] === \"string\" ? record[\"tier\"] : \"\",\n rag: decodeHealthFeature(record[\"rag\"]),\n auto_tune: decodeHealthFeature(record[\"auto_tune\"]),\n data_rooms: decodeHealthFeature(record[\"data_rooms\"]),\n };\n}\n\nfunction decodeHealthFeature(value: unknown): EnterpriseHealthFeature {\n if (typeof value !== \"object\" || value === null) {\n return { enabled: false };\n }\n return { ...value, enabled: (value as Record<string, unknown>)[\"enabled\"] === true };\n}\n\nfunction parseJobResponse(payload: unknown): GetJobResponse {\n if (typeof payload !== \"object\" || payload === null || Array.isArray(payload)) {\n throw new ValidationError(\"unexpected job response shape\", { status: 200, body: payload });\n }\n const record = payload as Record<string, unknown>;\n if (!(\"job_type\" in record) && typeof record[\"filename\"] === \"string\") {\n return { ...record, job_type: \"extraction\" } as GetJobResponse;\n }\n if (record[\"job_type\"] === \"extraction\" || record[\"job_type\"] === \"crawl\") {\n return record as GetJobResponse;\n }\n throw new ValidationError(\"unexpected job_type\", { status: 200, body: payload });\n}\n\n/**\n * Pair a diff response's status code with its body to build the\n * {@link DiffResult} union `diff`/`getDiffJob` return. `202` is the only\n * status carrying {@link DiffAsyncAccepted}; everything else (in practice\n * only `200`) carries the computed {@link DiffResponse}.\n */\nfunction toDiffResult(status: number, body: DiffResponse | DiffAsyncAccepted): DiffResult {\n if (status === 202) {\n return { status: 202, body: body as DiffAsyncAccepted };\n }\n return { status: 200, body: body as DiffResponse };\n}\n\n/**\n * Serialize a value with object keys sorted, so two configs that differ only in\n * key order compare equal when {@link appendPerFileConfigs} looks for a conflict.\n * Only ever used for that comparison — the value actually appended to the form is\n * a plain `JSON.stringify`, matching the `options` and `webhook` parts.\n */\nfunction canonicalJson(value: unknown): string {\n if (Array.isArray(value)) {\n return `[${value.map((entry) => canonicalJson(entry)).join(\",\")}]`;\n }\n if (typeof value === \"object\" && value !== null) {\n const entries = Object.entries(value as Record<string, unknown>)\n .filter(([, entry]) => entry !== undefined)\n .sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0));\n return `{${entries.map(([key, entry]) => `${JSON.stringify(key)}:${canonicalJson(entry)}`).join(\",\")}}`;\n }\n return JSON.stringify(value) ?? \"null\";\n}\n\n/**\n * Append one `config-<filename>` part per document carrying a per-file override.\n *\n * Appended after the `file`, `options` and `webhook` parts, and skipped entirely\n * when `configs` is undefined, so a request without overrides is byte-identical\n * to one built before this existed.\n *\n * The part is keyed on the filename, mirroring the `document_id-<filename>`\n * convention. Two documents submitted under the same filename therefore have one\n * slot for two overrides: rather than let the later `append` win and lose the\n * other with no signal, that case throws and names the file.\n */\nfunction appendPerFileConfigs(\n form: FormData,\n filenames: readonly string[],\n configs: readonly (FileExtractionConfig | null)[] | undefined,\n): void {\n if (configs === undefined) {\n return;\n }\n if (configs.length !== filenames.length) {\n throw new XbergError(\n `configs has ${configs.length} entries but ${filenames.length} files were supplied; ` +\n \"pass exactly one entry per file (null for no override)\",\n { status: 400, body: null },\n );\n }\n const seen = new Map<string, string>();\n filenames.forEach((filename, index) => {\n const config = configs[index] ?? null;\n const canonical = canonicalJson(config);\n const prior = seen.get(filename);\n if (prior !== undefined && prior !== canonical) {\n throw new XbergError(\n `per-file config conflict for \"${filename}\": the same filename appears more than once in ` +\n \"this batch with different configs, but a multipart request carries at most one config \" +\n \"part per filename. Give the copies distinct filenames.\",\n { status: 400, body: null },\n );\n }\n if (prior === undefined && config !== null) {\n form.append(`config-${filename}`, JSON.stringify(config));\n }\n seen.set(filename, canonical);\n });\n}\n\n/** Parse one SSE frame payload into the `kind`-discriminated {@link CrawlEvent} it names. */\nfunction parseCrawlEvent(payload: string): CrawlEvent {\n let body: unknown;\n try {\n body = JSON.parse(payload);\n } catch (cause) {\n throw new XbergError(`Crawl event stream sent a non-JSON frame: ${payload}`, {\n status: 0,\n body: payload,\n cause,\n });\n }\n const kind = (body as { kind?: unknown } | null)?.kind;\n if (typeof kind !== \"string\" || !CRAWL_EVENT_KINDS.has(kind)) {\n throw new XbergError(`Crawl event stream sent an unrecognised kind (${JSON.stringify(kind ?? null)})`, {\n status: 0,\n body,\n });\n }\n return body as CrawlEvent;\n}\n\n/**\n * Drive one crawl-event subscription: open it, decode its frames, and cancel\n * the response body on every exit path.\n *\n * `open` is a thunk rather than an already-opened `Response` so that a caller\n * who never iterates opens nothing — the tier gate and the request both live\n * inside the generator. The `finally` runs when the consumer `break`s or\n * `return`s out of its `for await` as much as when the stream ends, which is\n * what makes the subscription cancellable without a separate handle.\n */\nasync function* iterateCrawlEvents(open: () => Promise<Response>): AsyncGenerator<CrawlEvent> {\n const response = await open();\n if (response.body === null) {\n throw new XbergError(\"Crawl event stream response carried no body\", {\n status: response.status,\n body: null,\n });\n }\n const reader = response.body.getReader();\n const text = new TextDecoder();\n const frames = new EventStreamDecoder();\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) {\n return;\n }\n for (const payload of frames.push(text.decode(value, { stream: true }))) {\n yield parseCrawlEvent(payload);\n }\n }\n } finally {\n // Never let a teardown failure mask the error that caused the teardown.\n await reader.cancel().catch(() => undefined);\n }\n}\n\n/** Backwards-compatible factory returning the low-level `openapi-fetch` client. */\nexport interface CreateClientOptions {\n baseUrl: string;\n apiKey?: string;\n headers?: Record<string, string>;\n fetch?: typeof fetch;\n}\n\nexport function createClient(options: CreateClientOptions): XbergRawClient {\n const headers: Record<string, string> = {\n \"User-Agent\": USER_AGENT,\n ...options.headers,\n };\n if (options.apiKey !== undefined) {\n headers[\"Authorization\"] = `Bearer ${options.apiKey}`;\n }\n return createOpenApiClient<paths>({\n baseUrl: resolveBaseUrl(options.baseUrl, undefined),\n headers,\n ...(options.fetch !== undefined ? { fetch: options.fetch } : {}),\n });\n}\n\nfunction sandboxForm(params: PublicSandboxExtractParams): FormData {\n if (params.file === undefined && !(params.mode === \"web\" && params.url !== undefined && params.url.length > 0)) {\n throw new XbergError(\"Sandbox extraction requires a file or web mode with a URL\", { status: 400, body: null });\n }\n const form = new FormData();\n if (params.file !== undefined) {\n const { blob, filename } = toBlob(params.file);\n form.append(\"file\", blob, filename);\n }\n for (const name of [\"mode\", \"preset\", \"url\"] as const) {\n const value = params[name];\n if (value !== undefined) form.append(name, value);\n }\n return form;\n}\n\nfunction prepareDocumentLineage(\n filenames: readonly string[],\n ids: readonly (string | null)[] | undefined,\n): Map<string, string> {\n const fields = new Map<string, string>();\n if (ids === undefined) return fields;\n if (ids.length !== filenames.length)\n throw new XbergError(\"documentIds must contain one entry per file\", { status: 400, body: null });\n const seen = new Map<string, string | null>();\n for (const [index, filename] of filenames.entries()) {\n const id = ids[index];\n if (\n id !== null &&\n (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))\n ) {\n throw new XbergError(\"documentIds must contain UUID strings or null\", { status: 400, body: null });\n }\n const canonical = id === null ? null : id.toLowerCase();\n if (seen.has(filename) && seen.get(filename) !== canonical)\n throw new XbergError(\"Conflicting document IDs for the same filename\", { status: 400, body: null });\n seen.set(filename, canonical);\n if (canonical !== null) fields.set(filename, canonical);\n }\n return fields;\n}\n","/**\n * Verification of the `X-Webhook-Signature` header on webhook deliveries.\n *\n * The header is `t=<unix seconds>,v1=<hex HMAC-SHA256(secret, \"<t>.<body>\")>`.\n * Uses WebCrypto (`globalThis.crypto.subtle`) rather than `node:crypto`, so the\n * same code runs on Node, Deno, Bun, edge runtimes and browsers.\n */\n\n/** The request header that carries the signature. */\nexport const WEBHOOK_SIGNATURE_HEADER = \"X-Webhook-Signature\";\n\n/** Default replay window, in seconds, matching the server's. */\nexport const DEFAULT_WEBHOOK_TOLERANCE_SECONDS = 300;\n\nexport interface VerifyWebhookSignatureOptions {\n /** How far `t` may sit from `now` before the delivery is rejected. Default 300. */\n toleranceSeconds?: number;\n /** The receiver's clock in unix seconds. Defaults to the current time. */\n now?: number;\n}\n\nconst encoder = new TextEncoder();\n\n/**\n * Verify a webhook delivery's `X-Webhook-Signature` header against its raw body.\n *\n * Resolves `true` only when `t` is within `toleranceSeconds` of `now` and some\n * `v1` element is the HMAC-SHA256 of `\"<t>.<body>\"` under `secret`. Every `v1`\n * element is tried, so a sender signing with two secrets during a rotation\n * still verifies. The digest comparison is constant-time (`crypto.subtle.verify`).\n *\n * Pass the body exactly as received — re-serialising parsed JSON changes the\n * bytes and fails verification.\n */\nexport async function verifyWebhookSignature(\n secret: string,\n header: string,\n body: string | Uint8Array,\n options: VerifyWebhookSignatureOptions = {},\n): Promise<boolean> {\n const tolerance = options.toleranceSeconds ?? DEFAULT_WEBHOOK_TOLERANCE_SECONDS;\n const now = options.now ?? Math.floor(Date.now() / 1000);\n\n let timestamp: number | undefined;\n const candidates: string[] = [];\n for (const element of header.split(\",\")) {\n const trimmed = element.trim();\n const eq = trimmed.indexOf(\"=\");\n if (eq === -1) {\n continue;\n }\n const key = trimmed.slice(0, eq);\n const value = trimmed.slice(eq + 1);\n if (key === \"t\") {\n timestamp = /^[+-]?\\d+$/.test(value) ? Number(value) : undefined;\n } else if (key === \"v1\") {\n candidates.push(value);\n }\n }\n\n if (timestamp === undefined || !Number.isSafeInteger(timestamp) || candidates.length === 0) {\n return false;\n }\n if (!(Math.abs(now - timestamp) <= tolerance)) {\n return false;\n }\n\n const key = await crypto.subtle.importKey(\"raw\", encoder.encode(secret), { name: \"HMAC\", hash: \"SHA-256\" }, false, [\n \"verify\",\n ]);\n const prefix = encoder.encode(`${timestamp}.`);\n const bodyBytes = typeof body === \"string\" ? encoder.encode(body) : body;\n const signed = new Uint8Array(prefix.length + bodyBytes.length);\n signed.set(prefix, 0);\n signed.set(bodyBytes, prefix.length);\n\n for (const candidate of candidates) {\n const expected = decodeHex(candidate);\n if (expected !== undefined && (await crypto.subtle.verify(\"HMAC\", key, expected, signed))) {\n return true;\n }\n }\n return false;\n}\n\nfunction decodeHex(value: string): Uint8Array<ArrayBuffer> | undefined {\n if (value.length === 0 || value.length % 2 !== 0 || !/^[0-9a-fA-F]+$/.test(value)) {\n return undefined;\n }\n const bytes = new Uint8Array(value.length / 2);\n for (let index = 0; index < bytes.length; index += 1) {\n bytes[index] = Number.parseInt(value.slice(index * 2, index * 2 + 2), 16);\n }\n return bytes;\n}\n"],"mappings":";;AAkBA,IAAa,aAAb,cAAgC,MAAM;CACpB;CACA;;CAEA;;CAEA;CAET,YAAY,SAAiB,SAA4B;EAC9D,MAAM,YAA0B,QAAQ,UAAU,KAAA,IAAY,CAAC,IAAI,EAAE,OAAO,QAAQ,MAAM;EAC1F,MAAM,SAAS,SAAS;EACxB,KAAK,OAAO;EACZ,KAAK,SAAS,QAAQ;EACtB,KAAK,OAAO,QAAQ;EACpB,IAAI,QAAQ,SAAS,KAAA,GACnB,KAAK,OAAO,QAAQ;EAEtB,IAAI,QAAQ,YAAY,KAAA,GACtB,KAAK,UAAU,QAAQ;CAE3B;AACF;AAEA,IAAa,YAAb,cAA+B,WAAW;CACjC,YAAY,SAAiB,SAA4B;EAC9D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AAM;CAAU,GAAG,OAAO,CACjH,QACF,CAAC;CACD,MAAM,SAAS,QAAQ,OAAO,GAAG,UAAU,EAAE;CAC7C,MAAM,YAAY,OAAO,SAAS,WAAW,QAAQ,OAAO,IAAI,IAAI;CACpE,MAAM,SAAS,IAAI,WAAW,OAAO,SAAS,UAAU,MAAM;CAC9D,OAAO,IAAI,QAAQ,CAAC;CACpB,OAAO,IAAI,WAAW,OAAO,MAAM;CAEnC,KAAK,MAAM,aAAa,YAAY;EAClC,MAAM,WAAW,UAAU,SAAS;EACpC,IAAI,aAAa,KAAA,KAAc,MAAM,OAAO,OAAO,OAAO,QAAQ,KAAK,UAAU,MAAM,GACrF,OAAO;CAEX;CACA,OAAO;AACT;AAEA,SAAS,UAAU,OAAoD;CACrE,IAAI,MAAM,WAAW,KAAK,MAAM,SAAS,MAAM,KAAK,CAAC,iBAAiB,KAAK,KAAK,GAC9E;CAEF,MAAM,QAAQ,IAAI,WAAW,MAAM,SAAS,CAAC;CAC7C,KAAK,IAAI,QAAQ,GAAG,QAAQ,MAAM,QAAQ,SAAS,GACjD,MAAM,SAAS,OAAO,SAAS,MAAM,MAAM,QAAQ,GAAG,QAAQ,IAAI,CAAC,GAAG,EAAE;CAE1E,OAAO;AACT"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/errors.ts","../src/_internal.ts","../src/types.ts","../src/version.ts","../src/client.ts","../src/webhooks.ts"],"sourcesContent":["/**\n * Error class hierarchy for the Xberg SDK (Enterprise + Pro).\n *\n * Every non-2xx HTTP response is mapped to a subclass of {@link XbergError}.\n * `TimeoutError` is also raised when {@link XbergClient.waitForJob} exceeds its\n * configured deadline (distinct from a network/fetch timeout).\n */\n\nexport interface XbergErrorOptions {\n status: number;\n body: unknown;\n cause?: unknown;\n /** Stable machine-readable error code from the response envelope, e.g. `gateway_timeout`. */\n code?: string;\n /** Context-specific detail object from the response envelope. */\n details?: Record<string, unknown>;\n}\n\nexport class XbergError extends Error {\n public readonly status: number;\n public readonly body: unknown;\n /** Stable error code from the response envelope; branch on this, not on `message`. */\n public readonly code?: string;\n /** The envelope's `details` object, when the server sent one. */\n public readonly details?: Record<string, unknown>;\n\n public constructor(message: string, options: XbergErrorOptions) {\n const errorInit: ErrorOptions = options.cause === undefined ? {} : { cause: options.cause };\n super(message, errorInit);\n this.name = \"XbergError\";\n this.status = options.status;\n this.body = options.body;\n if (options.code !== undefined) {\n this.code = options.code;\n }\n if (options.details !== undefined) {\n this.details = options.details;\n }\n }\n}\n\nexport class AuthError extends XbergError {\n public constructor(message: string, options: XbergErrorOptions) {\n super(message, options);\n this.name = \"AuthError\";\n }\n}\n\nexport interface RateLimitErrorOptions extends XbergErrorOptions {\n retryAfter?: number;\n}\n\nexport class RateLimitError extends XbergError {\n public readonly retryAfter?: number;\n\n public constructor(message: string, options: RateLimitErrorOptions) {\n super(message, options);\n this.name = \"RateLimitError\";\n if (options.retryAfter !== undefined) {\n this.retryAfter = options.retryAfter;\n }\n }\n}\n\nexport class ValidationError extends XbergError {\n public constructor(message: string, options: XbergErrorOptions) {\n super(message, options);\n this.name = \"ValidationError\";\n }\n}\n\nexport class NotFoundError extends XbergError {\n public constructor(message: string, options: XbergErrorOptions) {\n super(message, options);\n this.name = \"NotFoundError\";\n }\n}\n\n/**\n * HTTP 404 with code `data_room.disabled`: the deployment's plan does not offer\n * data rooms, so every room route answers this before any other check.\n * `enterpriseHealthz()` reports the same state ahead of time as\n * `data_rooms.enabled === false`. Extends {@link NotFoundError}, which this\n * response mapped to before.\n */\nexport class DataRoomsDisabledError extends NotFoundError {\n public constructor(message: string, options: XbergErrorOptions) {\n super(message, options);\n this.name = \"DataRoomsDisabledError\";\n }\n}\n\n/** Envelope code of the 404 every data-room route answers on a plan without data rooms. */\nconst DATA_ROOM_DISABLED_CODE = \"data_room.disabled\";\n\nexport class ServerError extends XbergError {\n public constructor(message: string, options: XbergErrorOptions) {\n super(message, options);\n this.name = \"ServerError\";\n }\n}\n\n/**\n * HTTP 408: the request body stopped arriving before the upload completed\n * (`details.limit` is `body_idle`). Not retried by default — the body must be\n * sent again. Extends {@link ValidationError}, which every 4xx mapped to before.\n */\nexport class RequestTimeoutError extends ValidationError {\n /** Which server limit fired (`body_idle`), from `details.limit`. */\n public readonly limit?: string;\n /** The limit that was exceeded, in seconds, from `details.timeout_seconds`. */\n public readonly timeoutSeconds?: number;\n\n public constructor(message: string, options: XbergErrorOptions) {\n super(message, options);\n this.name = \"RequestTimeoutError\";\n const limits = timeoutLimits(options.details);\n if (limits.limit !== undefined) {\n this.limit = limits.limit;\n }\n if (limits.timeoutSeconds !== undefined) {\n this.timeoutSeconds = limits.timeoutSeconds;\n }\n }\n}\n\n/** HTTP 410: the job's stored result has expired and can no longer be fetched. */\nexport class ResultExpiredError extends ValidationError {\n public constructor(message: string, options: XbergErrorOptions) {\n super(message, options);\n this.name = \"ResultExpiredError\";\n }\n}\n\n/** HTTP 412: the `If-Match` precondition did not match the resource's current version. */\nexport class PreconditionFailedError extends ValidationError {\n public constructor(message: string, options: XbergErrorOptions) {\n super(message, options);\n this.name = \"PreconditionFailedError\";\n }\n}\n\n/** HTTP 428: the endpoint requires an `If-Match` header and none was sent. */\nexport class PreconditionRequiredError extends ValidationError {\n public constructor(message: string, options: XbergErrorOptions) {\n super(message, options);\n this.name = \"PreconditionRequiredError\";\n }\n}\n\n/**\n * HTTP 504: the server did not produce a response in time (`details.limit` is\n * `handler`). The work may still have happened server-side, which is why a\n * POST is not retried on 504 unless the client opts in. Extends\n * {@link ServerError}, which 504 mapped to before.\n */\nexport class GatewayTimeoutError extends ServerError {\n /** Which server limit fired (`handler`), from `details.limit`. */\n public readonly limit?: string;\n /** The limit that was exceeded, in seconds, from `details.timeout_seconds`. */\n public readonly timeoutSeconds?: number;\n\n public constructor(message: string, options: XbergErrorOptions) {\n super(message, options);\n this.name = \"GatewayTimeoutError\";\n const limits = timeoutLimits(options.details);\n if (limits.limit !== undefined) {\n this.limit = limits.limit;\n }\n if (limits.timeoutSeconds !== undefined) {\n this.timeoutSeconds = limits.timeoutSeconds;\n }\n }\n}\n\nexport class TimeoutError extends XbergError {\n public constructor(message: string, options: XbergErrorOptions) {\n super(message, options);\n this.name = \"TimeoutError\";\n }\n}\n\n/**\n * Map an HTTP response status to the matching error subclass and throw it.\n *\n * Always throws — call as `throw await raiseForStatus(response)` if you want\n * the type system to see the unreachable code, otherwise just `await`. Both\n * 401 and 403 map to {@link AuthError} — the API uses 403 for a\n * valid-but-forbidden principal.\n */\nexport async function raiseForStatus(response: Response): Promise<never> {\n const body = await readBody(response);\n const envelope = parseErrorEnvelope(body);\n const message = envelope.message ?? `Request failed with status ${response.status}`;\n const options: XbergErrorOptions = { status: response.status, body };\n if (envelope.code !== undefined) {\n options.code = envelope.code;\n }\n if (envelope.details !== undefined) {\n options.details = envelope.details;\n }\n\n if (response.status === 401 || response.status === 403) {\n throw new AuthError(message, options);\n }\n if (response.status === 404) {\n if (options.code === DATA_ROOM_DISABLED_CODE) {\n throw new DataRoomsDisabledError(message, options);\n }\n throw new NotFoundError(message, options);\n }\n if (response.status === 429) {\n const retryAfterRaw = response.headers.get(\"retry-after\");\n const retryAfter = parseRetryAfter(retryAfterRaw);\n const opts: RateLimitErrorOptions = retryAfter === undefined ? options : { ...options, retryAfter };\n throw new RateLimitError(message, opts);\n }\n const specific = STATUS_ERRORS[response.status];\n if (specific !== undefined) {\n throw new specific(message, options);\n }\n if (response.status >= 400 && response.status < 500) {\n throw new ValidationError(message, options);\n }\n if (response.status >= 500) {\n throw new ServerError(message, options);\n }\n throw new XbergError(message, options);\n}\n\nasync function readBody(response: Response): Promise<unknown> {\n const contentType = response.headers.get(\"content-type\") ?? \"\";\n if (contentType.includes(\"application/json\")) {\n try {\n return await response.json();\n } catch {\n return undefined;\n }\n }\n try {\n const text = await response.text();\n return text === \"\" ? undefined : text;\n } catch {\n return undefined;\n }\n}\n\nconst STATUS_ERRORS: Readonly<Record<number, new (message: string, options: XbergErrorOptions) => XbergError>> = {\n 408: RequestTimeoutError,\n 410: ResultExpiredError,\n 412: PreconditionFailedError,\n 428: PreconditionRequiredError,\n 504: GatewayTimeoutError,\n};\n\n/** The parts of an error body the SDK understands. */\ninterface ErrorEnvelope {\n message?: string;\n code?: string;\n details?: Record<string, unknown>;\n}\n\n/**\n * Read an error body in any shape the servers send: the canonical nested\n * envelope `{\"error\":{\"code\",\"message\",\"details\"}}`, the older flat\n * `{\"error\":\"...\"}` / `{\"message\":\"...\",\"code\":\"...\"}`, or plain text.\n */\nfunction parseErrorEnvelope(body: unknown): ErrorEnvelope {\n if (typeof body === \"string\") {\n return body.length > 0 ? { message: body } : {};\n }\n if (!isRecord(body)) {\n return {};\n }\n const error = body[\"error\"];\n const source = isRecord(error) ? error : body;\n const envelope: ErrorEnvelope = {};\n const message =\n nonEmptyString(source === body && typeof error === \"string\" ? error : undefined) ??\n nonEmptyString(source[\"message\"]);\n if (message !== undefined) {\n envelope.message = message;\n }\n const code = nonEmptyString(source[\"code\"]);\n if (code !== undefined) {\n envelope.code = code;\n }\n const details = source[\"details\"];\n if (isRecord(details)) {\n envelope.details = details;\n }\n return envelope;\n}\n\nfunction timeoutLimits(details: Record<string, unknown> | undefined): {\n limit?: string;\n timeoutSeconds?: number;\n} {\n const out: { limit?: string; timeoutSeconds?: number } = {};\n const limit = details?.[\"limit\"];\n if (typeof limit === \"string\") {\n out.limit = limit;\n }\n const seconds = details?.[\"timeout_seconds\"];\n if (typeof seconds === \"number\" && Number.isFinite(seconds)) {\n out.timeoutSeconds = seconds;\n }\n return out;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction nonEmptyString(value: unknown): string | undefined {\n return typeof value === \"string\" && value.length > 0 ? value : undefined;\n}\n\nfunction parseRetryAfter(value: string | null): number | undefined {\n if (value === null) {\n return undefined;\n }\n const seconds = Number(value);\n if (Number.isFinite(seconds) && seconds >= 0) {\n return seconds;\n }\n const parsed = Date.parse(value);\n if (Number.isNaN(parsed)) {\n return undefined;\n }\n const delta = Math.max(0, Math.ceil((parsed - Date.now()) / 1000));\n return delta;\n}\n","/**\n * Internal helpers for {@link XbergClient}: base-URL resolution, query-string\n * and backoff arithmetic, the file-to-`Blob` conversion the multipart request\n * paths need, and the event-stream frame decoder `streamCrawlEvents` reads its\n * response through. Not part of the public API — of the names here only\n * {@link FileLike} and {@link BackoffStrategy} are re-exported, via `client.ts`,\n * because they appear in public client signatures.\n */\n\nimport { XbergError } from \"./errors.js\";\n\nexport const DEFAULT_RETRY_BACKOFF_CAP_MS = 30_000;\nexport const DEFAULT_BACKOFF_FACTOR = 2;\n\n/**\n * Caps an event-stream frame. The frames this endpoint sends are a few hundred\n * bytes; the cap exists so a server that never closes a frame cannot grow this\n * decoder without bound.\n *\n * It is applied twice, because one application does not cover the other: to the\n * pending line, so one endless line cannot fill memory, and to the running\n * total of a frame's `data:` fields, so an endless succession of shorter lines\n * never followed by the blank line that would close the frame cannot either.\n */\nexport const MAX_EVENT_STREAM_FRAME_BYTES = 1 << 20;\n\n/**\n * Backoff strategy for retries and `waitForJob` polling.\n *\n * - `exponential` — interval doubles after every attempt, capped at 30s.\n * - `constant` — interval stays the same on every attempt.\n */\nexport type BackoffStrategy = \"exponential\" | \"constant\";\n\n/** Which product the client targets. */\nexport type Target = \"enterprise\" | \"pro\";\n\n/** Query-string values accepted by the internal request engine. */\nexport type QueryParams = Record<string, string | number | undefined>;\n\n/** Anything the client accepts as an uploadable file. */\nexport type FileLike = File | Blob | Uint8Array | { name?: string; data: Blob | Uint8Array; mimeType?: string };\n\n/**\n * Resolve the deployer's base URL; neither self-hosted product has a default.\n */\nexport function resolveBaseUrl(baseUrl: string | undefined, target: Target | undefined): string {\n const resolved = baseUrl?.replace(/\\/+$/, \"\");\n if (resolved !== undefined && resolved.length > 0) {\n return resolved;\n }\n const product = target === \"pro\" ? \"Xberg Pro\" : target === \"enterprise\" ? \"Xberg Enterprise\" : \"Xberg\";\n throw new XbergError(`${product} has no default base URL; pass baseUrl pointing at your deployment.`, {\n status: 0,\n body: null,\n });\n}\n\n/**\n * Resolve the base URL of the Enterprise control plane, defaulting to the data plane's.\n *\n * Enterprise runs the control plane (projects, API keys, integrations, RAG\n * config, members, invitations, managed webhooks, usage, analytics, billing) as\n * a second binary on its own origin; Pro serves it from the same one. The\n * default therefore has to be `baseUrl`, exactly as the console's\n * `NEXT_PUBLIC_BACKEND_API_URL` is same-origin unless set — anything else would\n * break every Pro control-plane call the moment this option existed.\n */\nexport function resolveControlPlaneBaseUrl(controlPlaneBaseUrl: string | undefined, baseUrl: string): string {\n if (controlPlaneBaseUrl !== undefined) {\n return controlPlaneBaseUrl.replace(/\\/+$/, \"\");\n }\n return baseUrl;\n}\n\nexport function defaultSleep(ms: number): Promise<void> {\n return new Promise((resolve) => {\n setTimeout(resolve, ms);\n });\n}\n\nexport function buildQueryString(params: QueryParams | undefined): string {\n if (params === undefined) {\n return \"\";\n }\n const search = new URLSearchParams();\n for (const [key, value] of Object.entries(params)) {\n if (value !== undefined) {\n search.append(key, String(value));\n }\n }\n const query = search.toString();\n return query.length > 0 ? `?${query}` : \"\";\n}\n\nexport function nextBackoffInterval(current: number, strategy: BackoffStrategy): number {\n if (strategy === \"constant\") {\n return current;\n }\n return Math.min(current * DEFAULT_BACKOFF_FACTOR, DEFAULT_RETRY_BACKOFF_CAP_MS);\n}\n\nexport function parseRetryAfterHeader(value: string | null): number | undefined {\n if (value === null) {\n return undefined;\n }\n const seconds = Number(value);\n if (Number.isFinite(seconds) && seconds >= 0) {\n return seconds;\n }\n const parsed = Date.parse(value);\n if (Number.isNaN(parsed)) {\n return undefined;\n }\n return Math.max(0, Math.ceil((parsed - Date.now()) / 1000));\n}\n\n/** Convert a {@link FileLike} input into a `Blob` plus best-guess filename. */\nexport function toBlob(file: FileLike): { blob: Blob; filename: string } {\n if (typeof File !== \"undefined\" && file instanceof File) {\n return { blob: file, filename: file.name };\n }\n if (file instanceof Blob) {\n return { blob: file, filename: \"upload.bin\" };\n }\n if (file instanceof Uint8Array) {\n return {\n blob: new Blob([blobBytes(file)], { type: \"application/octet-stream\" }),\n filename: \"upload.bin\",\n };\n }\n const wrapper = file;\n const name = wrapper.name ?? \"upload.bin\";\n const mimeType = wrapper.mimeType ?? guessMimeType(name);\n if (wrapper.data instanceof Blob) {\n return { blob: wrapper.data, filename: name };\n }\n return {\n blob: new Blob([blobBytes(wrapper.data)], { type: mimeType }),\n filename: name,\n };\n}\n\nfunction blobBytes(bytes: Uint8Array): Uint8Array<ArrayBuffer> {\n // ~keep Blob snapshots its input. A view avoids a second payload copy; shared backing requires an ordinary buffer.\n return bytes.buffer instanceof ArrayBuffer\n ? new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength)\n : new Uint8Array(bytes);\n}\n\nfunction guessMimeType(filename: string): string {\n const lower = filename.toLowerCase();\n if (lower.endsWith(\".csv\")) {\n return \"text/csv\";\n }\n if (lower.endsWith(\".md\")) {\n return \"text/markdown\";\n }\n if (lower.endsWith(\".pdf\")) {\n return \"application/pdf\";\n }\n if (lower.endsWith(\".txt\")) {\n return \"text/plain\";\n }\n if (lower.endsWith(\".docx\")) {\n return \"application/vnd.openxmlformats-officedocument.wordprocessingml.document\";\n }\n return \"application/octet-stream\";\n}\n\n/** Guess a display name for a file (used to populate `Job.filename`). */\nexport function describeFile(file: FileLike): string {\n if (typeof File !== \"undefined\" && file instanceof File) {\n return file.name;\n }\n if (file instanceof Blob || file instanceof Uint8Array) {\n return \"upload.bin\";\n }\n return file.name ?? \"upload.bin\";\n}\n\n/**\n * Incremental decoder for a `text/event-stream` body, fed the decoded text of\n * each network chunk.\n *\n * Implements the parts of the WHATWG event-stream parser this endpoint can\n * exercise. A frame is terminated by a *blank line*, not by a newline: its\n * payload is every `data:` field it carried, joined with `\\n`. Lines opening\n * with `:` are comments — the endpoint's 15s heartbeat is one — and\n * `event:`/`id:`/`retry:` fields are accepted and ignored. A single space\n * after a field's colon is framing, not value, so it is stripped.\n *\n * All of which is why this exists instead of `JSON.parse` per line: against a\n * server that happens to emit one compact frame per line the naive version\n * passes every test, then silently drops every multi-line payload and throws\n * on the first heartbeat against a real one. Chunk boundaries fall wherever\n * the network puts them, so lines are also reassembled here rather than\n * assumed to arrive whole.\n */\nexport class EventStreamDecoder {\n private buffer = \"\";\n private data: string[] = [];\n /** Running length of the frame being assembled, reset with `data` on dispatch. */\n private size = 0;\n\n /** Consume one chunk of decoded text, returning the payload of every frame it completed. */\n public push(chunk: string): string[] {\n this.buffer += chunk;\n const payloads: string[] = [];\n for (;;) {\n const boundary = this.nextLineBoundary();\n if (boundary === undefined) {\n if (this.buffer.length > MAX_EVENT_STREAM_FRAME_BYTES) {\n throw new XbergError(`Crawl event stream sent a line longer than ${MAX_EVENT_STREAM_FRAME_BYTES} bytes`, {\n status: 0,\n body: null,\n });\n }\n return payloads;\n }\n const line = this.buffer.slice(0, boundary.index);\n this.buffer = this.buffer.slice(boundary.index + boundary.width);\n const payload = this.feed(line);\n if (payload !== undefined) {\n payloads.push(payload);\n }\n }\n }\n\n /**\n * Locate the next `\\n`, `\\r\\n` or `\\r` in the buffer. A trailing `\\r` is\n * reported as \"no boundary yet\": it may be the first half of a `\\r\\n` the\n * network split across two chunks, and treating it as a terminator there\n * would dispatch a frame one line early.\n */\n private nextLineBoundary(): { index: number; width: number } | undefined {\n for (let index = 0; index < this.buffer.length; index += 1) {\n const character = this.buffer[index];\n if (character === \"\\n\") {\n return { index, width: 1 };\n }\n if (character === \"\\r\") {\n if (index === this.buffer.length - 1) {\n return undefined;\n }\n return { index, width: this.buffer[index + 1] === \"\\n\" ? 2 : 1 };\n }\n }\n return undefined;\n }\n\n /** Consume one terminator-stripped line, returning a payload if it completed a frame. */\n private feed(line: string): string | undefined {\n if (line === \"\") {\n return this.dispatch();\n }\n if (line.startsWith(\":\")) {\n return undefined;\n }\n const colon = line.indexOf(\":\");\n const field = colon === -1 ? line : line.slice(0, colon);\n let value = colon === -1 ? \"\" : line.slice(colon + 1);\n if (value.startsWith(\" \")) {\n value = value.slice(1);\n }\n if (field === \"data\") {\n this.size += value.length + 1; // +1 for the \"\\n\" dispatch joins with\n if (this.size > MAX_EVENT_STREAM_FRAME_BYTES) {\n throw new XbergError(\n `Crawl event frame exceeded ${MAX_EVENT_STREAM_FRAME_BYTES} bytes before the stream closed it`,\n { status: 0, body: null },\n );\n }\n this.data.push(value);\n }\n return undefined;\n }\n\n /** Emit the buffered `data` payload, or nothing when the blank line closed no frame. */\n private dispatch(): string | undefined {\n if (this.data.length === 0) {\n return undefined;\n }\n const payload = this.data.join(\"\\n\");\n this.data = [];\n this.size = 0;\n return payload;\n }\n}\n\n/** Encode a path identifier without allowing the HTTP client to change its route. */\nexport function encodePathSegment(value: string): string {\n // ~keep WHATWG URL normalizes even percent-encoded dot segments, so encoding alone is insufficient.\n if (value === \".\" || value === \"..\") {\n throw new XbergError(\"Path identifiers must not be '.' or '..'\", { status: 400, body: null });\n }\n return encodeURIComponent(value);\n}\n","/**\n * Friendly re-exports of the independently generated API, Pro and backend schema sets.\n *\n * Shared and Enterprise-only types key off `_generated/api.d.ts` (the Xberg\n * Enterprise managed API); Pro-only response types key off\n * `_generated/pro.d.ts`; Backend-prefixed types use `_generated/backend.d.ts`.\n * Schema sets are generated separately and never merged — mirrors ADR-0072.\n */\n\nimport type { components, operations } from \"./_generated/api.js\";\nimport type { components as proComponents } from \"./_generated/pro.js\";\nimport type { components as backendComponents } from \"./_generated/backend.js\";\n\n// -- Shared surface (present in both schema sets; typed off the Enterprise API) --\nexport type ExtractionOptions = components[\"schemas\"][\"ExtractionOptions\"];\nexport type ExtractionConfig = components[\"schemas\"][\"ExtractionConfig\"];\n/** A per-file extraction override, carried by `DocumentInput.config` and the `config-<filename>` multipart part. */\nexport type FileExtractionConfig = components[\"schemas\"][\"FileExtractionConfig\"];\nexport type ExtractedDocument = components[\"schemas\"][\"ExtractedDocument\"];\nexport type ExtractionResult = ExtractedDocument;\n// ~keep Upstream renamed this schema `JobResponse` -> `ExtractionJobResponse`; `Job` is public API and stays.\nexport type Job = components[\"schemas\"][\"ExtractionJobResponse\"];\nexport type JobStatus = components[\"schemas\"][\"JobStatus\"];\nexport type WebhookConfig = components[\"schemas\"][\"WebhookConfig\"];\nexport type ExtractResponse = components[\"schemas\"][\"ExtractResponse\"];\nexport type DocumentInput = components[\"schemas\"][\"DocumentInput\"];\nexport type ListJobsResponse = components[\"schemas\"][\"ListJobsResponse\"];\nexport type ListAuditEntriesResponse = components[\"schemas\"][\"ListAuditEntriesResponse\"];\nexport type PresetSummary = components[\"schemas\"][\"PresetSummary\"];\nexport type PresetDetail = components[\"schemas\"][\"PresetDetail\"];\n\n/**\n * The stored result document of a terminal job, returned by\n * `GET /v1/jobs/{id}/result` on both tiers. Distinct from {@link Job}, which is\n * the job's metadata record from `GET /v1/jobs/{id}`.\n */\nexport type JobResult = components[\"schemas\"][\"JobResult\"];\n/** A non-fatal per-document error attached to a {@link JobResult}. */\nexport type JobResultError = components[\"schemas\"][\"JobResultError\"];\n\n// -- Shared saved presets (both specs declare these identically) --\nexport type ListSavedPresetsResponse = components[\"schemas\"][\"ListSavedPresetsResponse\"];\nexport type SavedPresetSummary = components[\"schemas\"][\"SavedPresetSummary\"];\nexport type SavedPresetDetail = components[\"schemas\"][\"SavedPresetDetail\"];\nexport type CreateSavedPresetRequest = components[\"schemas\"][\"CreateSavedPresetRequest\"];\nexport type CreateSavedPresetResponse = components[\"schemas\"][\"CreateSavedPresetResponse\"];\nexport type UpdateSavedPresetRequest = components[\"schemas\"][\"UpdateSavedPresetRequest\"];\nexport type UpdateSavedPresetResponse = components[\"schemas\"][\"UpdateSavedPresetResponse\"];\n\n// -- Shared auto-tune surface (both specs declare these identically) --\nexport type ListAutoTuneJobsResponse = components[\"schemas\"][\"ListAutoTuneJobsResponse\"];\nexport type AutoTuneJobSummary = components[\"schemas\"][\"AutoTuneJobSummary\"];\nexport type CreateAutoTuneJobRequest = components[\"schemas\"][\"CreateAutoTuneJobRequest\"];\nexport type CreateAutoTuneJobResponse = components[\"schemas\"][\"CreateAutoTuneJobResponse\"];\nexport type AutoTuneCapabilitiesResponse = components[\"schemas\"][\"AutoTuneCapabilitiesResponse\"];\nexport type AutoTuneJobStatus = components[\"schemas\"][\"AutoTuneJobStatus\"];\nexport type AutoTuneResult = components[\"schemas\"][\"AutoTuneResult\"];\nexport type PromoteProfileRequest = components[\"schemas\"][\"PromoteProfileRequest\"];\n\n// -- Shared tuning profiles (both specs declare these identically) --\nexport type ListTuningProfilesResponse = components[\"schemas\"][\"ListTuningProfilesResponse\"];\nexport type TuningProfileSummary = components[\"schemas\"][\"TuningProfileSummary\"];\nexport type TuningProfileDetail = components[\"schemas\"][\"TuningProfileDetail\"];\n\n// -- Shared managed embedding presets (both specs declare these identically) --\nexport type ListManagedEmbeddingPresetsResponse = components[\"schemas\"][\"ListManagedEmbeddingPresetsResponse\"];\nexport type ManagedEmbeddingPreset = components[\"schemas\"][\"ManagedEmbeddingPreset\"];\n\n// -- Shared uploads, usage and enrichment (both specs declare these) --\nexport type UsageResponse = components[\"schemas\"][\"UsageResponse\"];\nexport type PresignUploadRequest = components[\"schemas\"][\"PresignUploadRequest\"];\nexport type PresignUploadResponse = components[\"schemas\"][\"PresignUploadResponse\"];\nexport type ConfirmUploadRequest = components[\"schemas\"][\"ConfirmUploadRequest\"];\nexport type ConfirmUploadResponse = components[\"schemas\"][\"ConfirmUploadResponse\"];\nexport type EnrichTextRequest = components[\"schemas\"][\"EnrichTextRequest\"];\nexport type EnrichRequestOptions = components[\"schemas\"][\"EnrichRequestOptions\"];\nexport type EnrichJobSubmitted = components[\"schemas\"][\"EnrichJobSubmitted\"];\nexport type EnrichJobStatus = components[\"schemas\"][\"EnrichJobStatus\"];\n\n// -- Enterprise-only surface (api schema) --\nexport type DiffResponse = components[\"schemas\"][\"DiffResponse\"];\n/** The async-pending envelope `diff`/`getDiffJob` return in place of {@link DiffResponse} while a diff is still computing. */\nexport type DiffAsyncAccepted = components[\"schemas\"][\"DiffAsyncAccepted\"];\n\n/**\n * Result of {@link XbergClient.diff} and {@link XbergClient.getDiffJob}.\n *\n * Both operations answer `200` with the computed {@link DiffResponse} or\n * `202` with the {@link DiffAsyncAccepted} polling envelope when the server\n * falls back to async computation — the same fallback `getDiffJob` exists to\n * poll. The two schemas share no field to discriminate on, so `status` here\n * is not part of either wire schema: it is the HTTP status code the response\n * actually carried, reattached so callers can narrow with a plain\n * `if (result.status === 200)` / `else` instead of a type assertion.\n */\nexport type DiffResult =\n | { readonly status: 200; readonly body: DiffResponse }\n | { readonly status: 202; readonly body: DiffAsyncAccepted };\nexport type DocumentVersionEntry = components[\"schemas\"][\"DocumentVersionEntry\"];\nexport type ListExtractionEventsResponse = components[\"schemas\"][\"ListExtractionEventsResponse\"];\nexport type ExtractionEventSummary = components[\"schemas\"][\"ExtractionEventSummary\"];\n/** Delivery attempts of a data-plane webhook subscription, without payload previews. */\nexport type ListWebhookDeliveriesResponse = components[\"schemas\"][\"ListWebhookDeliveriesResponse\"];\n/** One delivery attempt with its bounded request and response previews. */\nexport type WebhookDeliveryDetailResponse = components[\"schemas\"][\"WebhookDeliveryDetailResponse\"];\n\n// -- Enterprise-only documents and data rooms (api schema) --\n// ~keep Spec names too generic to stand alone in the package namespace (`ListItemsResponse`,\n// `AddMemberRequest`, `PublicationResponse`, ...) carry a `Room` prefix here; the right-hand\n// side names the schema each one aliases.\n/** One page of the project's logical documents, from `GET /v1/documents`. */\nexport type ListProjectDocumentsResponse = components[\"schemas\"][\"ListProjectDocumentsResponse\"];\n/** One logical document shown by its newest finished version; its `document_id` adds it to a room. */\nexport type ProjectDocumentEntry = components[\"schemas\"][\"ProjectDocumentEntry\"];\nexport type RoomResponse = components[\"schemas\"][\"RoomResponse\"];\nexport type RoomRightsResponse = components[\"schemas\"][\"RoomRightsResponse\"];\nexport type ListRoomsResponse = components[\"schemas\"][\"ListRoomsResponse\"];\nexport type CreateRoomRequest = components[\"schemas\"][\"CreateRoomRequest\"];\nexport type UpdateRoomRequest = components[\"schemas\"][\"UpdateRoomRequest\"];\n/** Which rooms `listRooms` asks for: the live ones, or the deleted ones that can still be restored. */\nexport type RoomListState = NonNullable<NonNullable<operations[\"list_rooms\"][\"parameters\"][\"query\"]>[\"state\"]>;\nexport type ListRoomItemsResponse = components[\"schemas\"][\"ListItemsResponse\"];\nexport type RoomItemResponse = components[\"schemas\"][\"RoomItemResponse\"];\nexport type AddRoomItemRequest = components[\"schemas\"][\"AddItemRequest\"];\nexport type ReorderRoomItemsRequest = components[\"schemas\"][\"ReorderItemsRequest\"];\nexport type ReorderRoomItemsResponse = components[\"schemas\"][\"ReorderItemsResponse\"];\nexport type RoomItemContentResponse = components[\"schemas\"][\"ItemContentResponse\"];\nexport type ListRoomMembersResponse = components[\"schemas\"][\"ListRoomMembersResponse\"];\nexport type RoomMemberResponse = components[\"schemas\"][\"RoomMemberResponse\"];\nexport type AddRoomMemberRequest = components[\"schemas\"][\"AddMemberRequest\"];\nexport type RoomChangeRoleRequest = components[\"schemas\"][\"RoomChangeRoleRequest\"];\nexport type RoomTransferOwnershipRequest = components[\"schemas\"][\"RoomTransferOwnershipRequest\"];\n/** The roles a room grant, invitation or role change can name. */\nexport type GrantableRole = components[\"schemas\"][\"GrantableRole\"];\nexport type ListRoomInvitationsResponse = components[\"schemas\"][\"ListRoomInvitationsResponse\"];\nexport type RoomInvitationResponse = components[\"schemas\"][\"RoomInvitationResponse\"];\nexport type RoomInviteRequest = components[\"schemas\"][\"RoomInviteRequest\"];\nexport type RoomAcceptInvitationRequest = components[\"schemas\"][\"RoomAcceptInvitationRequest\"];\nexport type AcceptedRoomInvitationResponse = components[\"schemas\"][\"AcceptedInvitationResponse\"];\nexport type RoomInvitationPreviewResponse = components[\"schemas\"][\"InvitationPreviewResponse\"];\nexport type RoomPublicationResponse = components[\"schemas\"][\"PublicationResponse\"];\nexport type SetRoomPublicationRequest = components[\"schemas\"][\"SetPublicationRequest\"];\nexport type PublicationStateName = components[\"schemas\"][\"PublicationStateName\"];\nexport type PublicationModeName = components[\"schemas\"][\"PublicationModeName\"];\nexport type PublicRoomResponse = components[\"schemas\"][\"PublicRoomResponse\"];\nexport type PublicRoomItemsResponse = components[\"schemas\"][\"PublicItemsResponse\"];\nexport type PublicRoomItemResponse = components[\"schemas\"][\"PublicItemResponse\"];\nexport type PublicRoomItemContentResponse = components[\"schemas\"][\"PublicItemContentResponse\"];\n\n/**\n * One event from {@link XbergClient.streamCrawlEvents}.\n *\n * A tagged union discriminated on `kind`, the same shape {@link DiffResult}\n * uses — except the discriminant here is a real wire field, not a reattached\n * HTTP status. Narrow before touching a variant-specific field:\n *\n * ```ts\n * for await (const event of client.streamCrawlEvents(crawlJobId)) {\n * if (event.kind === \"page\") {\n * // event.status_code, event.depth, event.url\n * } else if (event.kind === \"complete\") {\n * break;\n * }\n * }\n * ```\n *\n * `crawl_job_id` and `ts` are carried by every variant, so they read without\n * narrowing.\n */\nexport type CrawlEvent = components[\"schemas\"][\"CrawlEventV1\"];\n/** The `kind` discriminator of a {@link CrawlEvent}. */\nexport type CrawlEventKind = CrawlEvent[\"kind\"];\n/** A page was successfully crawled and indexed. */\nexport type CrawlPageEvent = Extract<CrawlEvent, { kind: \"page\" }>;\n/** A new URL was discovered during crawling. */\nexport type CrawlDiscoveredEvent = Extract<CrawlEvent, { kind: \"discovered\" }>;\n/** The crawl job finished; the stream closes after this event. */\nexport type CrawlCompleteEvent = Extract<CrawlEvent, { kind: \"complete\" }>;\n/** A single URL failed. The crawl continues; this is not a stream-level error. */\nexport type CrawlErrorEvent = Extract<CrawlEvent, { kind: \"error\" }>;\n\n// -- Pro-only surface (pro schema) --\nexport type GetJobResponse = proComponents[\"schemas\"][\"GetJobResponse\"];\nexport type AuthConfigResponse = proComponents[\"schemas\"][\"AuthConfigResponse\"];\nexport type LoginRequest = proComponents[\"schemas\"][\"LoginRequest\"];\nexport type LoginResponse = proComponents[\"schemas\"][\"LoginResponse\"];\nexport type SetRagConfigRequest = proComponents[\"schemas\"][\"SetRagConfigRequest\"];\nexport type RagConfigResponse = proComponents[\"schemas\"][\"RagConfigResponse\"];\n/** Licensee, plan, expiry and grace window of the running Pro instance. */\nexport type ProHealthResponse = proComponents[\"schemas\"][\"HealthResponse\"];\nexport type LicenseInfoResponse = proComponents[\"schemas\"][\"LicenseInfoResponse\"];\n\n/** One feature flag reported by Enterprise `GET /healthz`. */\nexport interface EnterpriseHealthFeature {\n enabled: boolean;\n}\n\n/**\n * Enterprise `GET /healthz`, as `enterpriseHealthz` decodes it. Written by hand\n * rather than aliased from the spec because the decode is lenient: a feature\n * object an older server omits, such as `data_rooms` before data rooms shipped,\n * reads as `{ enabled: false }`, and fields the server adds later are kept.\n */\nexport interface EnterpriseHealthResponse {\n status: string;\n tier: string;\n rag: EnterpriseHealthFeature;\n auto_tune: EnterpriseHealthFeature;\n data_rooms: EnterpriseHealthFeature;\n [key: string]: unknown;\n}\n\n// -- Pro-only control plane (projects, API keys, integrations) --\nexport type ListProjectsResponse = proComponents[\"schemas\"][\"ListProjectsResponse\"];\nexport type CreateProjectRequest = proComponents[\"schemas\"][\"CreateProjectRequest\"];\nexport type ProjectResponse = proComponents[\"schemas\"][\"ProjectResponse\"];\nexport type ApiKeyResponse = proComponents[\"schemas\"][\"ApiKeyResponse\"];\nexport type ApiKeyScope = proComponents[\"schemas\"][\"ApiKeyScope\"];\nexport type ListApiKeysResponse = proComponents[\"schemas\"][\"ListApiKeysResponse\"];\nexport type CreateApiKeyRequest = proComponents[\"schemas\"][\"CreateApiKeyRequest\"];\nexport type CreateApiKeyResponse = proComponents[\"schemas\"][\"CreateApiKeyResponse\"];\nexport type ProIntegrationListResponse = proComponents[\"schemas\"][\"ProIntegrationListResponse\"];\nexport type ListIntegrationsResponse = ProIntegrationListResponse;\nexport type CreateIntegrationRequest = proComponents[\"schemas\"][\"CreateIntegrationRequest\"];\nexport type IntegrationSyncResponse = proComponents[\"schemas\"][\"IntegrationSyncResponse\"];\nexport type SetIntegrationSyncRequest = proComponents[\"schemas\"][\"SetIntegrationSyncRequest\"];\nexport type IntegrationResponse = proComponents[\"schemas\"][\"IntegrationResponse\"];\nexport type BeginOAuthResponse = proComponents[\"schemas\"][\"BeginOAuthResponse\"];\nexport type ListDocumentsResponse = proComponents[\"schemas\"][\"ListDocumentsResponse\"];\nexport type DocumentResponse = proComponents[\"schemas\"][\"DocumentResponse\"];\n\n/**\n * Terminal job statuses — once observed, polling stops and the job result is\n * returned (or thrown, for `failed`/`cancelled`).\n */\nexport const TERMINAL_JOB_STATUSES: readonly JobStatus[] = [\n \"completed\",\n \"partial_success\",\n \"failed\",\n \"cancelled\",\n] as const;\n\n/**\n * Job statuses that indicate a successful extraction. Used to distinguish a\n * \"completed but check warnings\" result from a hard failure.\n */\nexport const SUCCESS_JOB_STATUSES: readonly JobStatus[] = [\"completed\", \"partial_success\"] as const;\n\nexport type BackendAcceptInvitationRequest = backendComponents[\"schemas\"][\"AcceptInvitationRequest\"];\nexport type BackendAnalyticsResponse = backendComponents[\"schemas\"][\"AnalyticsResponse\"];\nexport type BackendAuthConfigResponse = backendComponents[\"schemas\"][\"AuthConfigResponse\"];\nexport type BackendBeginConnectResponse = backendComponents[\"schemas\"][\"BeginConnectResponse\"];\nexport type BackendBillingResponse = backendComponents[\"schemas\"][\"BillingResponse\"];\nexport type BackendCheckoutResponse = backendComponents[\"schemas\"][\"CheckoutResponse\"];\nexport type BackendCreateApiKeyRequest = backendComponents[\"schemas\"][\"CreateApiKeyRequest\"];\nexport type BackendCreateApiKeyResponse = backendComponents[\"schemas\"][\"CreateApiKeyResponse\"];\n/** Backend integration configuration accepts arbitrary JSON object properties. */\nexport type BackendCreateIntegrationRequest = Omit<\n backendComponents[\"schemas\"][\"CreateIntegrationRequest\"],\n \"config\" | \"credentials\"\n> & { config?: Record<string, unknown>; credentials?: Record<string, unknown> };\nexport type BackendCreateInvitationRequest = backendComponents[\"schemas\"][\"CreateInvitationRequest\"];\nexport type BackendCreateInvitationResponse = backendComponents[\"schemas\"][\"CreateInvitationResponse\"];\nexport type BackendCreateProjectRequest = backendComponents[\"schemas\"][\"CreateProjectRequest\"];\nexport type BackendCreateWebhookRequest = backendComponents[\"schemas\"][\"CreateWebhookRequest\"];\nexport type BackendHealthResponse = backendComponents[\"schemas\"][\"HealthResponse\"];\nexport type BackendIntegrationResponse = backendComponents[\"schemas\"][\"IntegrationResponse\"];\nexport type BackendListApiKeysResponse = backendComponents[\"schemas\"][\"ListApiKeysResponse\"];\nexport type BackendListAuditEntriesResponse = backendComponents[\"schemas\"][\"ListAuditEntriesResponse\"];\nexport type BackendListDocumentsResponse = backendComponents[\"schemas\"][\"ListDocumentsResponse\"];\nexport type BackendListIntegrationsResponse = backendComponents[\"schemas\"][\"ListIntegrationsResponse\"];\nexport type BackendListInvitationsResponse = backendComponents[\"schemas\"][\"ListInvitationsResponse\"];\nexport type BackendListMembersResponse = backendComponents[\"schemas\"][\"ListMembersResponse\"];\nexport type BackendListProjectsResponse = backendComponents[\"schemas\"][\"ListProjectsResponse\"];\nexport type BackendListWebhookDeliveriesResponse = backendComponents[\"schemas\"][\"ListWebhookDeliveriesResponse\"];\nexport type BackendListWebhooksResponse = backendComponents[\"schemas\"][\"ListWebhooksResponse\"];\nexport type BackendLoginRequest = backendComponents[\"schemas\"][\"LoginRequest\"];\nexport type BackendLoginResponse = backendComponents[\"schemas\"][\"LoginResponse\"];\nexport type BackendMemberResponse = backendComponents[\"schemas\"][\"MemberResponse\"];\nexport type BackendPortalResponse = backendComponents[\"schemas\"][\"PortalResponse\"];\nexport type BackendProjectResponse = backendComponents[\"schemas\"][\"ProjectResponse\"];\nexport type BackendRagConfigResponse = backendComponents[\"schemas\"][\"RagConfigResponse\"];\nexport type BackendReadinessResponse = backendComponents[\"schemas\"][\"ReadinessResponse\"];\nexport type BackendRetryWebhookDeliveryResponse = backendComponents[\"schemas\"][\"RetryWebhookDeliveryResponse\"];\nexport type BackendSandboxExtractResponse = backendComponents[\"schemas\"][\"SandboxExtractResponse\"];\nexport type BackendSetRagConfigRequest = backendComponents[\"schemas\"][\"SetRagConfigRequest\"];\nexport type BackendUpdateMemberRoleRequest = backendComponents[\"schemas\"][\"UpdateMemberRoleRequest\"];\nexport type BackendUpdateProjectRequest = backendComponents[\"schemas\"][\"UpdateProjectRequest\"];\nexport type BackendUpdateWebhookRequest = backendComponents[\"schemas\"][\"UpdateWebhookRequest\"];\nexport type BackendUsageResponse = backendComponents[\"schemas\"][\"UsageResponse\"];\nexport type BackendWebhookDeliveryDetailResponse = backendComponents[\"schemas\"][\"WebhookDeliveryDetailResponse\"];\nexport type BackendWebhookResponse = backendComponents[\"schemas\"][\"WebhookResponse\"];\nexport type BackendWebhookTestResponse = backendComponents[\"schemas\"][\"WebhookTestResponse\"];\n\nexport type BackendUserProfileResponse = backendComponents[\"schemas\"][\"UserProfileResponse\"];\nexport type BackendUpdateUserProfileRequest = backendComponents[\"schemas\"][\"UpdateUserProfileRequest\"];\nexport type BackendAssignProjectRoleRequest = backendComponents[\"schemas\"][\"AssignProjectRoleRequest\"];\nexport type BackendCreateProjectRoleRequest = backendComponents[\"schemas\"][\"CreateProjectRoleRequest\"];\nexport type BackendCreateRoleBoundApiKeyRequest = backendComponents[\"schemas\"][\"CreateRoleBoundApiKeyRequest\"];\nexport type BackendScimConnectionResponse = backendComponents[\"schemas\"][\"ScimConnectionResponse\"];\nexport type BackendSamlAttributeMapping = backendComponents[\"schemas\"][\"SamlAttributeMapping\"];\nexport type BackendSamlConnectionTestStarted = backendComponents[\"schemas\"][\"SamlConnectionTestStarted\"];\nexport type BackendSamlConnectionTestStatus = backendComponents[\"schemas\"][\"SamlConnectionTestStatus\"];\nexport type BackendCreateScimConnectionRequest = backendComponents[\"schemas\"][\"CreateScimConnectionRequest\"];\nexport type BackendCreateScimConnectionResponse = backendComponents[\"schemas\"][\"CreateScimConnectionResponse\"];\nexport type BackendIntegrationSyncResponse = backendComponents[\"schemas\"][\"IntegrationSyncResponse\"];\nexport type BackendListProjectRolesResponse = backendComponents[\"schemas\"][\"ListProjectRolesResponse\"];\nexport type BackendListScimAdminGroupsResponse = backendComponents[\"schemas\"][\"ListScimAdminGroupsResponse\"];\nexport type BackendListScimConnectionsResponse = backendComponents[\"schemas\"][\"ListScimConnectionsResponse\"];\nexport type BackendProjectRoleResponse = backendComponents[\"schemas\"][\"ProjectRoleResponse\"];\nexport type BackendReplaceScimGroupRolesRequest = backendComponents[\"schemas\"][\"ReplaceScimGroupRolesRequest\"];\nexport type BackendSamlDomainRequest = backendComponents[\"schemas\"][\"SamlDomainRequest\"];\nexport type BackendSamlDomainResponse = backendComponents[\"schemas\"][\"SamlDomainResponse\"];\nexport type BackendSamlProviderRequest = backendComponents[\"schemas\"][\"SamlProviderRequest\"];\nexport type BackendSamlProviderResponse = backendComponents[\"schemas\"][\"SamlProviderResponse\"];\nexport type BackendSetIntegrationSyncRequest = backendComponents[\"schemas\"][\"SetIntegrationSyncRequest\"];\nexport type BackendUpdateProjectRoleRequest = backendComponents[\"schemas\"][\"UpdateProjectRoleRequest\"];\nexport type ListRagDocumentsResponse = components[\"schemas\"][\"ListRagDocumentsResponse\"];\nexport type RagDocumentSummary = components[\"schemas\"][\"RagDocumentSummary\"];\nexport type SetRoomLinkAccessRequest = components[\"schemas\"][\"SetRoomLinkAccessRequest\"];\nexport type RoomLinkAccessResponse = components[\"schemas\"][\"RoomLinkAccessResponse\"];\nexport type JobPageInventory = proComponents[\"schemas\"][\"JobPageInventory\"];\nexport type BindIntegrationRagTargetRequest = proComponents[\"schemas\"][\"BindIntegrationRagTargetRequest\"];\nexport type CreateRoomLinkRequest = components[\"schemas\"][\"CreateRoomLinkRequest\"];\nexport type ListRoomLinksResponse = components[\"schemas\"][\"ListRoomLinksResponse\"];\nexport type RoomLinkResponse = components[\"schemas\"][\"RoomLinkResponse\"];\nexport type ProjectExtractionConfigResponse = components[\"schemas\"][\"ProjectExtractionConfigResponse\"];\nexport type ProUpdateProjectRequest = proComponents[\"schemas\"][\"UpdateProjectRequest\"];\n","/**\n * Package version, synced from the repo-root `VERSION` file by\n * `scripts/sync-versions.py`. Used to build the `User-Agent` header. ~keep\n */\nexport const VERSION = \"0.13.0\";\n","/**\n * High-level dual-target client for the Xberg Enterprise and Xberg Pro HTTP APIs.\n *\n * One {@link XbergClient} speaks to either product. The shared surface —\n * extraction, jobs (including job results), audit, curated presets, and the RAG\n * API — is written once and carries no tier gate. Tier-specific methods are\n * capability-gated: they probe the connected instance (`GET /healthz`'s `tier`,\n * or an explicit `target`) and throw a clear error instead of a raw 404 when\n * invoked against the wrong tier.\n *\n * Both products authenticate identically: `Authorization: Bearer {apiKey}`.\n * Both products are self-hosted and require the deployment's `baseUrl`.\n *\n * Enterprise splits into two binaries — the data plane `baseUrl` addresses and a\n * control plane (projects, API keys, integrations) on its own origin — while Pro\n * serves both from one. `controlPlaneBaseUrl` records the origin of the second\n * and defaults to `baseUrl`. The backend methods use that origin and an optional\n * separate `controlPlaneToken`; existing Pro methods retain their data-plane routing.\n */\n\nimport createOpenApiClient, { type Client } from \"openapi-fetch\";\nimport type { paths } from \"./_generated/api.js\";\nimport {\n DEFAULT_BACKOFF_FACTOR,\n DEFAULT_RETRY_BACKOFF_CAP_MS,\n EventStreamDecoder,\n encodePathSegment,\n buildQueryString,\n defaultSleep,\n describeFile,\n nextBackoffInterval,\n parseRetryAfterHeader,\n resolveBaseUrl,\n resolveControlPlaneBaseUrl,\n toBlob,\n} from \"./_internal.js\";\nimport type { BackoffStrategy, FileLike, QueryParams, Target } from \"./_internal.js\";\nimport { TimeoutError, ValidationError, XbergError, raiseForStatus } from \"./errors.js\";\nimport type {\n AuthConfigResponse,\n BackendAcceptInvitationRequest,\n BackendAnalyticsResponse,\n BackendAuthConfigResponse,\n BackendUserProfileResponse,\n BackendUpdateUserProfileRequest,\n BackendBeginConnectResponse,\n BackendCreateApiKeyRequest,\n BackendCreateApiKeyResponse,\n BackendCreateIntegrationRequest,\n BackendCreateInvitationRequest,\n BackendCreateInvitationResponse,\n BackendCreateProjectRequest,\n BackendCreateWebhookRequest,\n BackendHealthResponse,\n BackendIntegrationResponse,\n BackendListApiKeysResponse,\n BackendListAuditEntriesResponse,\n BackendListDocumentsResponse,\n BackendListIntegrationsResponse,\n BackendListInvitationsResponse,\n BackendListMembersResponse,\n BackendListProjectsResponse,\n BackendListWebhookDeliveriesResponse,\n BackendListWebhooksResponse,\n BackendLoginRequest,\n BackendLoginResponse,\n BackendMemberResponse,\n BackendProjectResponse,\n BackendRagConfigResponse,\n BackendReadinessResponse,\n BackendRetryWebhookDeliveryResponse,\n BackendSandboxExtractResponse,\n BackendSetRagConfigRequest,\n BackendUpdateMemberRoleRequest,\n BackendUpdateProjectRequest,\n BackendUpdateWebhookRequest,\n BackendUsageResponse,\n BackendWebhookDeliveryDetailResponse,\n BackendWebhookResponse,\n BackendWebhookTestResponse,\n BackendAssignProjectRoleRequest,\n BackendCreateProjectRoleRequest,\n BackendCreateRoleBoundApiKeyRequest,\n BackendScimConnectionResponse,\n BackendSamlAttributeMapping,\n BackendSamlConnectionTestStarted,\n BackendSamlConnectionTestStatus,\n BackendCreateScimConnectionRequest,\n BackendCreateScimConnectionResponse,\n BackendIntegrationSyncResponse,\n BackendListProjectRolesResponse,\n BackendListScimAdminGroupsResponse,\n BackendListScimConnectionsResponse,\n BackendProjectRoleResponse,\n BackendReplaceScimGroupRolesRequest,\n BackendSamlDomainRequest,\n BackendSamlDomainResponse,\n BackendSamlProviderRequest,\n BackendSamlProviderResponse,\n BackendSetIntegrationSyncRequest,\n BackendUpdateProjectRoleRequest,\n AutoTuneCapabilitiesResponse,\n AutoTuneJobStatus,\n AutoTuneResult,\n BeginOAuthResponse,\n ConfirmUploadRequest,\n ConfirmUploadResponse,\n CrawlEvent,\n CreateApiKeyRequest,\n CreateApiKeyResponse,\n CreateAutoTuneJobRequest,\n CreateAutoTuneJobResponse,\n CreateIntegrationRequest,\n CreateProjectRequest,\n CreateSavedPresetRequest,\n CreateSavedPresetResponse,\n DiffAsyncAccepted,\n DiffResponse,\n DiffResult,\n DocumentVersionEntry,\n EnrichJobStatus,\n EnrichJobSubmitted,\n EnterpriseHealthFeature,\n EnterpriseHealthResponse,\n EnrichTextRequest,\n ExtractResponse,\n ExtractionOptions,\n FileExtractionConfig,\n IntegrationResponse,\n IntegrationSyncResponse,\n SetIntegrationSyncRequest,\n Job,\n GetJobResponse,\n JobResult,\n LicenseInfoResponse,\n ProHealthResponse,\n ListApiKeysResponse,\n ListAuditEntriesResponse,\n ListAutoTuneJobsResponse,\n ListDocumentsResponse,\n ListExtractionEventsResponse,\n ListIntegrationsResponse,\n ListJobsResponse,\n ListManagedEmbeddingPresetsResponse,\n ListProjectsResponse,\n ListSavedPresetsResponse,\n ListTuningProfilesResponse,\n ListWebhookDeliveriesResponse,\n LoginRequest,\n LoginResponse,\n PresetDetail,\n PresetSummary,\n PresignUploadRequest,\n PresignUploadResponse,\n ListRagDocumentsResponse,\n SetRoomLinkAccessRequest,\n RoomLinkAccessResponse,\n JobPageInventory,\n BindIntegrationRagTargetRequest,\n CreateRoomLinkRequest,\n ListRoomLinksResponse,\n RoomLinkResponse,\n ProjectExtractionConfigResponse,\n ProUpdateProjectRequest,\n ExtractionConfig,\n ProjectResponse,\n PromoteProfileRequest,\n RagConfigResponse,\n SavedPresetDetail,\n SetRagConfigRequest,\n TuningProfileDetail,\n UpdateSavedPresetRequest,\n UpdateSavedPresetResponse,\n UsageResponse,\n WebhookConfig,\n WebhookDeliveryDetailResponse,\n AcceptedRoomInvitationResponse,\n AddRoomItemRequest,\n AddRoomMemberRequest,\n CreateRoomRequest,\n ListProjectDocumentsResponse,\n ListRoomInvitationsResponse,\n ListRoomItemsResponse,\n ListRoomMembersResponse,\n ListRoomsResponse,\n PublicRoomItemContentResponse,\n PublicRoomItemsResponse,\n PublicRoomResponse,\n ReorderRoomItemsRequest,\n ReorderRoomItemsResponse,\n RoomAcceptInvitationRequest,\n RoomChangeRoleRequest,\n RoomInvitationPreviewResponse,\n RoomInvitationResponse,\n RoomInviteRequest,\n RoomItemContentResponse,\n RoomItemResponse,\n RoomListState,\n RoomMemberResponse,\n RoomPublicationResponse,\n RoomResponse,\n RoomTransferOwnershipRequest,\n SetRoomPublicationRequest,\n UpdateRoomRequest,\n} from \"./types.js\";\nimport { SUCCESS_JOB_STATUSES, TERMINAL_JOB_STATUSES } from \"./types.js\";\nimport { VERSION } from \"./version.js\";\n\n/**\n * Public types that live in the internal helper module because the helpers\n * there operate on them; re-exported so `./client.js` stays their import site.\n */\nexport type { BackoffStrategy, FileLike, Target } from \"./_internal.js\";\n\nconst USER_AGENT = `xberg-io-sdk-typescript/${VERSION}`;\nconst DEFAULT_TIMEOUT_MS = 30_000;\nconst DEFAULT_POLL_INTERVAL_MS = 1_000;\nconst DEFAULT_WAIT_TIMEOUT_MS = 5 * 60_000;\nconst DEFAULT_RETRY_STATUSES: readonly number[] = [429, 502, 503, 504];\n/**\n * ~keep Methods a retry cannot duplicate work through. A 502/503/504 on a POST may\n * arrive after the server accepted the submission, so retrying it can create a\n * second job; 429 is safe for every method because the request was refused.\n */\nconst IDEMPOTENT_METHODS: ReadonlySet<string> = new Set([\"GET\", \"HEAD\", \"OPTIONS\", \"PUT\", \"DELETE\"]);\nconst DEFAULT_RETRY_BACKOFF_BASE_MS = 200;\n\n/**\n * ~keep `saved-presets` is an OpenAPI *tag* name, not a route: both specs serve\n * `/v1/saved_presets`, so there is no per-tier spelling to select between.\n */\nconst SAVED_PRESETS_PATH = \"/v1/saved_presets\";\nconst AUTO_TUNE_PATH = \"/v1/auto-tune\";\nconst TUNING_PROFILES_PATH = \"/v1/tuning-profiles\";\nconst ENRICH_PATH = \"/v1/enrich\";\nconst EXTRACTIONS_PATH = \"/v1/extractions\";\nconst DOCUMENTS_PATH = \"/v1/documents\";\nconst JOBS_PATH = \"/v1/jobs\";\nconst CRAWL_JOBS_PATH = \"/v1/crawl-jobs\";\nconst WEBHOOKS_PATH = \"/v1/webhooks\";\nconst ROOMS_PATH = \"/v1/rooms\";\nconst ROOM_INVITATIONS_PATH = \"/v1/room-invitations\";\nconst PUBLIC_ROOMS_PATH = \"/public/rooms\";\n\n/** Headers that carry a credential, stripped from every request to an unauthenticated public route. */\nconst CREDENTIAL_HEADERS: readonly string[] = [\"authorization\", \"proxy-authorization\", \"cookie\", \"x-api-key\"];\n\n/** Media type of a raw upload body, and the fallback when a submitted file declares none. */\nconst OCTET_STREAM_MEDIA_TYPE = \"application/octet-stream\";\n\n/** Media type of the crawl-event stream, sent as `Accept` and served as `Content-Type`. */\nconst EVENT_STREAM_MEDIA_TYPE = \"text/event-stream\";\n\n/** The `kind` values `CrawlEventV1` declares. A frame carrying anything else is rejected. */\nconst CRAWL_EVENT_KINDS: ReadonlySet<string> = new Set([\"page\", \"discovered\", \"complete\", \"error\"]);\n\nexport interface XbergClientOptions {\n apiKey?: string;\n baseUrl: string;\n /**\n * Origin of the Enterprise control plane, which runs as a second binary\n * alongside the data plane. Defaults to `baseUrl` — Pro serves both planes\n * from one binary, so every Pro call keeps working untouched.\n *\n */\n controlPlaneBaseUrl?: string;\n /** Bearer token for protected backend calls; defaults to `apiKey`. */\n controlPlaneToken?: string;\n /** Product for tier-specific data-plane methods; discovered lazily when omitted. */\n target?: Target;\n fetch?: typeof fetch;\n headers?: Record<string, string>;\n timeoutMs?: number;\n /** Retry attempts after the first request. Default 0 (retries off). */\n retries?: number;\n /**\n * Statuses to retry. Default `[429, 502, 503, 504]`. A 429 is retried for\n * every method, honouring `Retry-After`; any other listed status is retried\n * only for GET, HEAD, OPTIONS, PUT and DELETE without `If-Match` unless\n * `retryNonIdempotent` is set. A replayed DELETE whose first attempt applied\n * answers 404.\n */\n retryOn?: readonly number[];\n /**\n * Also retry POST, PATCH and `If-Match` writes on the non-429 `retryOn` statuses.\n * Default `false`: a 502/503/504 can arrive after the server accepted the request,\n * so a retry may submit the same document twice, and a replayed `If-Match` write\n * fails with 412 because the version moved. Enable only when repeating is acceptable.\n */\n retryNonIdempotent?: boolean;\n retryBackoff?: BackoffStrategy;\n /** Sleep helper, swappable in tests. Defaults to `setTimeout`. */\n sleep?: (ms: number) => Promise<void>;\n}\n\nexport interface JobScopeParams {\n /** ~keep Pro only: select a visible project instead of the credential's default project. */\n projectId?: string;\n}\n\nexport interface ExtractParams extends JobScopeParams {\n /** Enterprise document lineage UUID; omitted for a new document. */\n documentId?: string;\n file: FileLike;\n options?: ExtractionOptions;\n webhook?: WebhookConfig;\n /**\n * Per-file extraction override for this document, sent as the\n * `config-<filename>` part. The server resolves it against\n * `options.extraction_config`, any preset and the project default.\n */\n config?: FileExtractionConfig;\n}\n\nexport interface ExtractBatchParams extends JobScopeParams {\n /** Enterprise lineage UUIDs aligned with files; null entries omit lineage. */\n documentIds?: readonly (string | null)[];\n files: readonly FileLike[];\n options?: ExtractionOptions;\n webhook?: WebhookConfig;\n /**\n * One optional per-file override per entry of `files`, in the same order —\n * `null` for no override. Must be the same length as `files` when given.\n *\n * The override travels as a `config-<filename>` part, so two documents sharing\n * a filename cannot carry different overrides; that combination throws rather\n * than dropping one silently.\n */\n configs?: readonly (FileExtractionConfig | null)[];\n}\n\nexport interface ExtractKeyedParams extends JobScopeParams {\n files: readonly FileLike[];\n /**\n * Required project-scoped `Idempotency-Key`. Resubmitting the same files and\n * configuration under the same key replays the accepted response instead of\n * creating new jobs; reusing it for different input answers 409.\n */\n idempotencyKey: string;\n options?: ExtractionOptions;\n /** Per-file overrides aligned with `files`, as in {@link ExtractBatchParams.configs}. */\n configs?: readonly (FileExtractionConfig | null)[];\n}\n\nexport interface WaitOptions extends JobScopeParams {\n /** Total time to wait before throwing TimeoutError. Default 5 minutes. */\n timeoutMs?: number;\n /** Initial poll interval. Default 1000ms. */\n pollIntervalMs?: number;\n /** `exponential` doubles the interval each cycle (capped). Default exponential. */\n backoff?: BackoffStrategy;\n}\n\nexport interface ExtractAndWaitParams extends ExtractParams, WaitOptions {}\n\nexport interface ListJobsParams extends JobScopeParams {\n limit?: number;\n offset?: number;\n}\n\nexport interface AuditParams {\n action?: string;\n limit?: number;\n offset?: number;\n}\n\n/** Offset pagination accepted by the paginated list endpoints. */\nexport interface PaginationParams {\n limit?: number;\n offset?: number;\n}\n\nexport interface ListRagDocumentsParams {\n limit?: number;\n cursor?: string;\n /** Pro only: select a project with the X-Project-ID header. */\n projectId?: string;\n}\n\n/** Filters accepted by `listExtractionEvents`. */\nexport interface ListExtractionEventsParams extends PaginationParams {\n /** How many days to look back. Defaults to 30 server-side, clamped to 1..=365. */\n days?: number;\n}\n\n/** The two multipart parts `submitAutoTune` sends. */\nexport interface SubmitAutoTuneParams {\n /** JSON-encoded into the required `request` part. */\n request: CreateAutoTuneJobRequest;\n /** One binary `file` part per document referenced by `request.documents[].filename`. */\n files: readonly FileLike[];\n}\n\n/** Options accepted by `streamCrawlEvents`. */\nexport interface StreamCrawlEventsOptions extends JobScopeParams {\n /**\n * Aborts the stream from outside the loop. Breaking out of the `for await`\n * already closes the response body, so this is only needed to hang up from\n * somewhere else — a React effect teardown, a shutdown handler.\n */\n signal?: AbortSignal;\n}\n\n/** Filters accepted by `listRooms`. */\nexport interface ListRoomsParams extends PaginationParams {\n /** `deleted` lists the deleted rooms that can still be restored; the server default is `live`. */\n state?: RoomListState;\n}\n\n/** Options accepted by `previewRoomInvitation` and `acceptRoomInvitation`. */\nexport interface RoomInvitationOptions {\n /**\n * Dashboard session token of the signed-in invitee, sent as the bearer for\n * this call only. The invitation routes admit a signed-in user, never an API\n * key (which answers 403), so pass it unless the client itself was built\n * with that user's session token as `apiKey`.\n */\n sessionToken?: string;\n}\n\n/** Filters accepted by `listIntegrationDocuments`. */\nexport interface ListIntegrationDocumentsParams {\n /** Comma-separated MIME types to restrict the listing to. */\n mimeTypes?: string;\n /** Source-specific folder to list instead of the connection root. */\n folderId?: string;\n /** Upper bound on the number of documents returned. */\n limit?: number;\n /** Number of documents to skip before returning results. */\n offset?: number;\n}\n\nexport interface BackendDateRange {\n startDate: string;\n endDate: string;\n}\nexport interface BackendOAuthCallbackParams {\n code: string;\n state: string;\n}\nexport interface BackendAuditParams {\n action?: string;\n limit?: number;\n offset?: number;\n}\nexport interface BackendSandboxExtractParams {\n file: FileLike;\n}\nexport interface PublicSandboxExtractParams {\n file?: FileLike;\n mode?: string;\n preset?: string;\n url?: string;\n sandboxToken?: string;\n}\n\n/** Underlying `openapi-fetch` client, typed over the Enterprise API schema. */\nexport type XbergRawClient = Client<paths>;\n\n/**\n * High-level dual-target client. Construct with `new XbergClient({ baseUrl, apiKey })`.\n */\nexport class XbergClient {\n private readonly baseUrl: string;\n /**\n * Origin used by the Enterprise backend methods. Defaults to `baseUrl`.\n */\n public readonly controlPlaneBaseUrl: string;\n private readonly controlPlaneToken: string | undefined;\n private readonly headers: Record<string, string>;\n private readonly fetchImpl: typeof fetch;\n private readonly timeoutMs: number;\n private readonly retries: number;\n private readonly retryOn: readonly number[];\n private readonly retryNonIdempotent: boolean;\n private readonly retryBackoff: BackoffStrategy;\n private readonly sleep: (ms: number) => Promise<void>;\n private readonly target?: Target;\n private probedTier: Target | undefined;\n /** In-flight `/healthz` probe, memoised so concurrent callers share one request (single-flight). */\n private tierProbe: Promise<Target> | undefined;\n /** Underlying `openapi-fetch` client — exposed for advanced use. */\n public readonly raw: XbergRawClient;\n\n public constructor(options: XbergClientOptions) {\n if (options.target !== undefined) {\n this.target = options.target;\n }\n this.baseUrl = resolveBaseUrl(options.baseUrl, options.target);\n this.controlPlaneBaseUrl = resolveControlPlaneBaseUrl(options.controlPlaneBaseUrl, this.baseUrl);\n this.controlPlaneToken = options.controlPlaneToken ?? options.apiKey;\n this.fetchImpl = options.fetch ?? fetch;\n this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n this.retries = options.retries ?? 0;\n this.retryOn = options.retryOn ?? DEFAULT_RETRY_STATUSES;\n this.retryNonIdempotent = options.retryNonIdempotent ?? false;\n this.retryBackoff = options.retryBackoff ?? \"exponential\";\n this.sleep = options.sleep ?? defaultSleep;\n\n this.headers = {\n \"User-Agent\": USER_AGENT,\n ...options.headers,\n };\n if (options.apiKey !== undefined) {\n this.headers[\"Authorization\"] = `Bearer ${options.apiKey}`;\n }\n\n this.raw = createOpenApiClient<paths>({\n baseUrl: this.baseUrl,\n headers: this.headers,\n fetch: this.fetchImpl,\n });\n }\n\n /** Enterprise backend `DELETE /auth/account`. */\n public async deleteAccount(): Promise<void> {\n return await this.backendRequest<void>(\"DELETE\", `/auth/account`);\n }\n /** Enterprise backend `GET /auth/config`. */\n public async getAuthConfig(): Promise<BackendAuthConfigResponse> {\n return await this.backendRequest<BackendAuthConfigResponse>(\"GET\", `/auth/config`, { backendPublic: true });\n }\n /** Enterprise backend `GET /auth/profile`. */\n public async getUserProfile(): Promise<BackendUserProfileResponse> {\n return await this.backendRequest<BackendUserProfileResponse>(\"GET\", \"/auth/profile\");\n }\n /** Enterprise backend `PATCH /auth/profile`. */\n public async updateUserProfile(body: BackendUpdateUserProfileRequest): Promise<BackendUserProfileResponse> {\n return await this.backendRequest<BackendUserProfileResponse>(\"PATCH\", \"/auth/profile\", { json: body });\n }\n /** Enterprise backend `POST /auth/login`. */\n public async backendLogin(body: BackendLoginRequest): Promise<BackendLoginResponse> {\n return await this.backendRequest<BackendLoginResponse>(\"POST\", `/auth/login`, { json: body, backendPublic: true });\n }\n /** Enterprise backend `GET /healthz`. */\n public async healthz(): Promise<BackendHealthResponse> {\n return await this.backendRequest<BackendHealthResponse>(\"GET\", `/healthz`, { backendPublic: true });\n }\n /** Enterprise backend `GET /readyz`. */\n public async readyz(): Promise<BackendReadinessResponse> {\n return await this.backendRequest<BackendReadinessResponse>(\"GET\", `/readyz`, { backendPublic: true });\n }\n /** Enterprise backend `POST /v1/invitations/accept`. */\n public async acceptInvitation(body: BackendAcceptInvitationRequest): Promise<BackendMemberResponse> {\n return await this.backendRequest<BackendMemberResponse>(\"POST\", `/v1/invitations/accept`, { json: body });\n }\n /** Enterprise backend `GET /v1/oauth/callback`. */\n public async oauthCallback(params: BackendOAuthCallbackParams): Promise<string> {\n const response = await this.requestWithRetry(\"GET\", \"/v1/oauth/callback\", {\n controlPlane: true,\n backendPublic: true,\n acceptRedirect: true,\n params: { code: params.code, state: params.state },\n });\n const location = response.headers.get(\"location\");\n await response.body?.cancel();\n if (response.status !== 303 || location === null || location.length === 0) {\n throw new XbergError(\"OAuth callback did not return a 303 Location\", { status: response.status, body: null });\n }\n return location;\n }\n /** Enterprise backend `GET /v1/projects`. */\n public async backendListProjects(params: PaginationParams = {}): Promise<BackendListProjectsResponse> {\n return await this.backendRequest<BackendListProjectsResponse>(\"GET\", `/v1/projects`, {\n params: { limit: params.limit, offset: params.offset },\n });\n }\n /** Enterprise backend `POST /v1/projects`. */\n public async backendCreateProject(body: BackendCreateProjectRequest): Promise<BackendProjectResponse> {\n return await this.backendRequest<BackendProjectResponse>(\"POST\", `/v1/projects`, { json: body });\n }\n /** Enterprise backend `GET /v1/projects/{id}`. */\n public async getProject(projectId: string): Promise<BackendProjectResponse> {\n return await this.backendRequest<BackendProjectResponse>(\"GET\", `/v1/projects/${encodePathSegment(projectId)}`);\n }\n /** Enterprise backend `DELETE /v1/projects/{id}`. */\n public async deleteProject(projectId: string, params: { erase?: boolean } = {}): Promise<void> {\n return await this.backendRequest<void>(\"DELETE\", `/v1/projects/${encodePathSegment(projectId)}`, {\n params: { erase: params.erase === undefined ? undefined : String(params.erase) },\n });\n }\n /** Enterprise backend `PATCH /v1/projects/{id}`. */\n public async updateProject(projectId: string, body: BackendUpdateProjectRequest): Promise<BackendProjectResponse> {\n return await this.backendRequest<BackendProjectResponse>(\"PATCH\", `/v1/projects/${encodePathSegment(projectId)}`, {\n json: body,\n });\n }\n /** Enterprise backend `GET /v1/projects/{id}/analytics`. */\n public async getAnalytics(projectId: string, params: BackendDateRange): Promise<BackendAnalyticsResponse> {\n return await this.backendRequest<BackendAnalyticsResponse>(\n \"GET\",\n `/v1/projects/${encodePathSegment(projectId)}/analytics`,\n { params: { start_date: params.startDate, end_date: params.endDate } },\n );\n }\n /** Enterprise backend `GET /v1/projects/{id}/api-keys`. */\n public async backendListApiKeys(\n projectId: string,\n params: PaginationParams = {},\n ): Promise<BackendListApiKeysResponse> {\n return await this.backendRequest<BackendListApiKeysResponse>(\n \"GET\",\n `/v1/projects/${encodePathSegment(projectId)}/api-keys`,\n { params: { limit: params.limit, offset: params.offset } },\n );\n }\n /** Enterprise backend `POST /v1/projects/{id}/api-keys`. */\n public async backendCreateApiKey(\n projectId: string,\n body: BackendCreateApiKeyRequest,\n ): Promise<BackendCreateApiKeyResponse> {\n return await this.backendRequest<BackendCreateApiKeyResponse>(\n \"POST\",\n `/v1/projects/${encodePathSegment(projectId)}/api-keys`,\n { json: body },\n );\n }\n /** Enterprise backend: issue an API key restricted to a custom project role. */\n public async backendCreateRoleBoundApiKey(\n projectId: string,\n body: BackendCreateRoleBoundApiKeyRequest,\n ): Promise<BackendCreateApiKeyResponse> {\n return await this.backendRequest<BackendCreateApiKeyResponse>(\n \"POST\",\n `${this.projectPath(projectId)}/api-keys/role-bound`,\n {\n json: body,\n },\n );\n }\n /** Enterprise backend `DELETE /v1/projects/{id}/api-keys/{key_id}`. */\n public async backendRevokeApiKey(projectId: string, apiKeyId: string): Promise<void> {\n return await this.backendRequest<void>(\n \"DELETE\",\n `/v1/projects/${encodePathSegment(projectId)}/api-keys/${encodePathSegment(apiKeyId)}`,\n );\n }\n /** Enterprise backend `POST /v1/projects/{id}/api-keys/{key_id}/regenerate`. */\n public async regenerateApiKey(projectId: string, apiKeyId: string): Promise<BackendCreateApiKeyResponse> {\n return await this.backendRequest<BackendCreateApiKeyResponse>(\n \"POST\",\n `/v1/projects/${encodePathSegment(projectId)}/api-keys/${encodePathSegment(apiKeyId)}/regenerate`,\n );\n }\n /** Enterprise backend `GET /v1/projects/{id}/audit`. */\n public async listProjectAudit(\n projectId: string,\n params: BackendAuditParams = {},\n ): Promise<BackendListAuditEntriesResponse> {\n return await this.backendRequest<BackendListAuditEntriesResponse>(\n \"GET\",\n `/v1/projects/${encodePathSegment(projectId)}/audit`,\n { params: { action: params.action, limit: params.limit, offset: params.offset } },\n );\n }\n /** Enterprise backend `GET /v1/projects/{id}/integrations`. */\n public async backendListIntegrations(\n projectId: string,\n params: PaginationParams = {},\n ): Promise<BackendListIntegrationsResponse> {\n return await this.backendRequest<BackendListIntegrationsResponse>(\n \"GET\",\n `/v1/projects/${encodePathSegment(projectId)}/integrations`,\n { params: { limit: params.limit, offset: params.offset } },\n );\n }\n /** Enterprise backend `POST /v1/projects/{id}/integrations`. */\n public async backendCreateIntegration(\n projectId: string,\n body: BackendCreateIntegrationRequest,\n ): Promise<BackendIntegrationResponse> {\n return await this.backendRequest<BackendIntegrationResponse>(\n \"POST\",\n `/v1/projects/${encodePathSegment(projectId)}/integrations`,\n { json: body },\n );\n }\n /** Enterprise backend `GET /v1/projects/{id}/integrations/{iid}`. */\n public async backendGetIntegration(projectId: string, integrationId: string): Promise<BackendIntegrationResponse> {\n return await this.backendRequest<BackendIntegrationResponse>(\n \"GET\",\n `/v1/projects/${encodePathSegment(projectId)}/integrations/${encodePathSegment(integrationId)}`,\n );\n }\n /** Enterprise backend `DELETE /v1/projects/{id}/integrations/{iid}`. */\n public async backendDeleteIntegration(projectId: string, integrationId: string): Promise<void> {\n return await this.backendRequest<void>(\n \"DELETE\",\n `/v1/projects/${encodePathSegment(projectId)}/integrations/${encodePathSegment(integrationId)}`,\n );\n }\n /** Enterprise backend `POST /v1/projects/{id}/integrations/{iid}/connect`. */\n public async oauthConnect(projectId: string, integrationId: string): Promise<BackendBeginConnectResponse> {\n return await this.backendRequest<BackendBeginConnectResponse>(\n \"POST\",\n `/v1/projects/${encodePathSegment(projectId)}/integrations/${encodePathSegment(integrationId)}/connect`,\n );\n }\n /** Enterprise backend `POST /v1/projects/{id}/integrations/{iid}/disconnect`. */\n public async backendDisconnectIntegration(projectId: string, integrationId: string): Promise<void> {\n return await this.backendRequest<void>(\n \"POST\",\n `/v1/projects/${encodePathSegment(projectId)}/integrations/${encodePathSegment(integrationId)}/disconnect`,\n );\n }\n /** Enterprise backend `GET /v1/projects/{id}/integrations/{iid}/documents`. */\n public async backendListIntegrationDocuments(\n projectId: string,\n integrationId: string,\n params: ListIntegrationDocumentsParams = {},\n ): Promise<BackendListDocumentsResponse> {\n return await this.backendRequest<BackendListDocumentsResponse>(\n \"GET\",\n `/v1/projects/${encodePathSegment(projectId)}/integrations/${encodePathSegment(integrationId)}/documents`,\n {\n params: {\n mime_types: params.mimeTypes,\n folder_id: params.folderId,\n limit: params.limit,\n offset: params.offset,\n },\n },\n );\n }\n /** Enterprise backend `GET /v1/projects/{id}/integrations/{iid}/documents/{doc_id}`. */\n public async backendFetchIntegrationDocument(\n projectId: string,\n integrationId: string,\n documentId: string,\n ): Promise<Uint8Array> {\n return await this.requestBytes(\n \"GET\",\n `/v1/projects/${encodePathSegment(projectId)}/integrations/${encodePathSegment(integrationId)}/documents/${encodePathSegment(documentId)}`,\n { controlPlane: true },\n );\n }\n /** Enterprise backend `GET /v1/projects/{id}/integrations/{iid}/sync`. */\n public async backendGetIntegrationSync(\n projectId: string,\n integrationId: string,\n ): Promise<BackendIntegrationSyncResponse> {\n return await this.backendRequest<BackendIntegrationSyncResponse>(\n \"GET\",\n `/v1/projects/${encodePathSegment(projectId)}/integrations/${encodePathSegment(integrationId)}/sync`,\n );\n }\n /** Enterprise backend `PUT /v1/projects/{id}/integrations/{iid}/sync`. */\n public async backendSetIntegrationSync(\n projectId: string,\n integrationId: string,\n body: BackendSetIntegrationSyncRequest,\n ): Promise<void> {\n return await this.backendRequest<void>(\n \"PUT\",\n `/v1/projects/${encodePathSegment(projectId)}/integrations/${encodePathSegment(integrationId)}/sync`,\n { json: body },\n );\n }\n /** Enterprise backend `GET /v1/projects/{id}/invitations`. */\n public async listInvitations(\n projectId: string,\n params: PaginationParams = {},\n ): Promise<BackendListInvitationsResponse> {\n return await this.backendRequest<BackendListInvitationsResponse>(\n \"GET\",\n `/v1/projects/${encodePathSegment(projectId)}/invitations`,\n { params: { limit: params.limit, offset: params.offset } },\n );\n }\n /** Enterprise backend `POST /v1/projects/{id}/invitations`. */\n public async inviteUser(\n projectId: string,\n body: BackendCreateInvitationRequest,\n ): Promise<BackendCreateInvitationResponse> {\n return await this.backendRequest<BackendCreateInvitationResponse>(\n \"POST\",\n `/v1/projects/${encodePathSegment(projectId)}/invitations`,\n { json: body },\n );\n }\n /** Enterprise backend `DELETE /v1/projects/{id}/invitations/{inv_id}`. */\n public async revokeInvitation(projectId: string, invitationId: string): Promise<void> {\n return await this.backendRequest<void>(\n \"DELETE\",\n `/v1/projects/${encodePathSegment(projectId)}/invitations/${encodePathSegment(invitationId)}`,\n );\n }\n /** Enterprise backend `POST /v1/projects/{id}/leave`. */\n public async leaveProject(projectId: string): Promise<void> {\n return await this.backendRequest<void>(\"POST\", `/v1/projects/${encodePathSegment(projectId)}/leave`);\n }\n /** Enterprise backend `GET /v1/projects/{id}/members`. */\n public async listMembers(projectId: string, params: PaginationParams = {}): Promise<BackendListMembersResponse> {\n return await this.backendRequest<BackendListMembersResponse>(\n \"GET\",\n `/v1/projects/${encodePathSegment(projectId)}/members`,\n { params: { limit: params.limit, offset: params.offset } },\n );\n }\n /** Enterprise backend `DELETE /v1/projects/{id}/members/{user_id}`. */\n public async removeMember(projectId: string, userId: string): Promise<void> {\n return await this.backendRequest<void>(\n \"DELETE\",\n `/v1/projects/${encodePathSegment(projectId)}/members/${encodePathSegment(userId)}`,\n );\n }\n /** Enterprise backend `PATCH /v1/projects/{id}/members/{user_id}`. */\n public async updateMemberRole(\n projectId: string,\n userId: string,\n body: BackendUpdateMemberRoleRequest,\n ): Promise<BackendMemberResponse> {\n return await this.backendRequest<BackendMemberResponse>(\n \"PATCH\",\n `/v1/projects/${encodePathSegment(projectId)}/members/${encodePathSegment(userId)}`,\n { json: body },\n );\n }\n /** Enterprise backend `PATCH /v1/projects/{id}/members/{user_id}/custom-role`. */\n public async assignProjectRole(\n projectId: string,\n userId: string,\n body: BackendAssignProjectRoleRequest,\n ): Promise<void> {\n return await this.backendRequest<void>(\n \"PATCH\",\n `/v1/projects/${encodePathSegment(projectId)}/members/${encodePathSegment(userId)}/custom-role`,\n {\n json: body,\n },\n );\n }\n /** Enterprise backend `GET /v1/projects/{id}/rag-config`. */\n public async backendGetRagConfig(projectId: string): Promise<BackendRagConfigResponse> {\n return await this.backendRequest<BackendRagConfigResponse>(\n \"GET\",\n `/v1/projects/${encodePathSegment(projectId)}/rag-config`,\n );\n }\n /** Enterprise backend `PUT /v1/projects/{id}/rag-config`. */\n public async backendSetRagConfig(\n projectId: string,\n body: BackendSetRagConfigRequest,\n ): Promise<BackendRagConfigResponse> {\n return await this.backendRequest<BackendRagConfigResponse>(\n \"PUT\",\n `/v1/projects/${encodePathSegment(projectId)}/rag-config`,\n { json: body },\n );\n }\n /** Enterprise backend `GET /v1/projects/{id}/roles`. */\n public async listProjectRoles(\n projectId: string,\n params: PaginationParams = {},\n ): Promise<BackendListProjectRolesResponse> {\n return await this.backendRequest<BackendListProjectRolesResponse>(\n \"GET\",\n `/v1/projects/${encodePathSegment(projectId)}/roles`,\n {\n params: { limit: params.limit, offset: params.offset },\n },\n );\n }\n /** Enterprise backend `POST /v1/projects/{id}/roles`. */\n public async createProjectRole(\n projectId: string,\n body: BackendCreateProjectRoleRequest,\n ): Promise<BackendProjectRoleResponse> {\n return await this.backendRequest<BackendProjectRoleResponse>(\n \"POST\",\n `/v1/projects/${encodePathSegment(projectId)}/roles`,\n { json: body },\n );\n }\n /** Enterprise backend `GET /v1/projects/{id}/roles/{role_id}`. */\n public async getProjectRole(projectId: string, roleId: string): Promise<BackendProjectRoleResponse> {\n return await this.backendRequest<BackendProjectRoleResponse>(\n \"GET\",\n `/v1/projects/${encodePathSegment(projectId)}/roles/${encodePathSegment(roleId)}`,\n );\n }\n /** Enterprise backend `PATCH /v1/projects/{id}/roles/{role_id}`. */\n public async updateProjectRole(\n projectId: string,\n roleId: string,\n body: BackendUpdateProjectRoleRequest,\n ): Promise<BackendProjectRoleResponse> {\n return await this.backendRequest<BackendProjectRoleResponse>(\n \"PATCH\",\n `/v1/projects/${encodePathSegment(projectId)}/roles/${encodePathSegment(roleId)}`,\n {\n json: body,\n },\n );\n }\n /** Enterprise backend `DELETE /v1/projects/{id}/roles/{role_id}`. */\n public async deleteProjectRole(projectId: string, roleId: string): Promise<void> {\n return await this.backendRequest<void>(\n \"DELETE\",\n `/v1/projects/${encodePathSegment(projectId)}/roles/${encodePathSegment(roleId)}`,\n );\n }\n /** Enterprise backend `GET /v1/projects/{project_id}/saml/domains`. */\n public async listSamlDomains(projectId: string): Promise<BackendSamlDomainResponse[]> {\n return await this.backendRequest<BackendSamlDomainResponse[]>(\n \"GET\",\n `/v1/projects/${encodePathSegment(projectId)}/saml/domains`,\n );\n }\n /** Enterprise backend `POST /v1/projects/{project_id}/saml/domains`. */\n public async createSamlDomain(projectId: string, body: BackendSamlDomainRequest): Promise<BackendSamlDomainResponse> {\n return await this.backendRequest<BackendSamlDomainResponse>(\n \"POST\",\n `/v1/projects/${encodePathSegment(projectId)}/saml/domains`,\n { json: body },\n );\n }\n /** Enterprise backend `POST /v1/projects/{project_id}/saml/domains/{domain}/verify`. */\n public async verifySamlDomain(projectId: string, domain: string): Promise<void> {\n return await this.backendRequest<void>(\n \"POST\",\n `/v1/projects/${encodePathSegment(projectId)}/saml/domains/${encodePathSegment(domain)}/verify`,\n );\n }\n /** Enterprise backend `GET /v1/projects/{project_id}/saml/providers`. */\n public async listSamlProviders(projectId: string): Promise<BackendSamlProviderResponse[]> {\n return await this.backendRequest<BackendSamlProviderResponse[]>(\n \"GET\",\n `/v1/projects/${encodePathSegment(projectId)}/saml/providers`,\n );\n }\n /** Enterprise backend `POST /v1/projects/{project_id}/saml/providers`. */\n public async createSamlProvider(\n projectId: string,\n body: BackendSamlProviderRequest,\n ): Promise<BackendSamlProviderResponse> {\n return await this.backendRequest<BackendSamlProviderResponse>(\n \"POST\",\n `/v1/projects/${encodePathSegment(projectId)}/saml/providers`,\n {\n json: body,\n },\n );\n }\n /** Enterprise backend `PUT /v1/projects/{project_id}/saml/providers/{provider_id}`. */\n public async updateSamlProvider(\n projectId: string,\n providerId: string,\n body: BackendSamlProviderRequest,\n ): Promise<BackendSamlProviderResponse> {\n return await this.backendRequest<BackendSamlProviderResponse>(\"PUT\", this.samlProviderPath(projectId, providerId), {\n json: body,\n });\n }\n /** Enterprise backend: replace a SAML provider's attribute mapping. */\n public async updateSamlAttributeMapping(\n projectId: string,\n providerId: string,\n body: BackendSamlAttributeMapping,\n ): Promise<BackendSamlProviderResponse> {\n return await this.backendRequest<BackendSamlProviderResponse>(\n \"PATCH\",\n `${this.samlProviderPath(projectId, providerId)}/attribute-mapping`,\n { json: body },\n );\n }\n /** Enterprise backend: start a SAML test and return its browser redirect. */\n public async startSamlConnectionTest(\n projectId: string,\n providerId: string,\n ): Promise<BackendSamlConnectionTestStarted> {\n return await this.backendRequest<BackendSamlConnectionTestStarted>(\n \"POST\",\n `${this.samlProviderPath(projectId, providerId)}/test`,\n );\n }\n /** Enterprise backend: check the status of a SAML connection test. */\n public async getSamlConnectionTestStatus(\n projectId: string,\n providerId: string,\n testId: string,\n ): Promise<BackendSamlConnectionTestStatus> {\n return await this.backendRequest<BackendSamlConnectionTestStatus>(\n \"GET\",\n `${this.samlProviderPath(projectId, providerId)}/test/${encodePathSegment(testId)}`,\n );\n }\n /** Enterprise backend `DELETE /v1/projects/{project_id}/saml/providers/{provider_id}`. */\n public async deleteSamlProvider(projectId: string, providerId: string): Promise<void> {\n return await this.backendRequest<void>(\"DELETE\", this.samlProviderPath(projectId, providerId));\n }\n /** Enterprise backend `POST /v1/projects/{id}/sandbox/extract`. */\n public async sandboxExtract(\n projectId: string,\n params: BackendSandboxExtractParams,\n ): Promise<BackendSandboxExtractResponse> {\n return await this.backendRequest<BackendSandboxExtractResponse>(\n \"POST\",\n `/v1/projects/${encodePathSegment(projectId)}/sandbox/extract`,\n { body: sandboxForm(params) },\n );\n }\n /** Enterprise backend `GET /v1/projects/{id}/scim/connections`. */\n public async listScimConnections(projectId: string): Promise<BackendListScimConnectionsResponse> {\n return await this.backendRequest<BackendListScimConnectionsResponse>(\n \"GET\",\n `/v1/projects/${encodePathSegment(projectId)}/scim/connections`,\n );\n }\n /** Enterprise backend `POST /v1/projects/{id}/scim/connections`. */\n public async createScimConnection(\n projectId: string,\n body: BackendCreateScimConnectionRequest,\n ): Promise<BackendCreateScimConnectionResponse> {\n return await this.backendRequest<BackendCreateScimConnectionResponse>(\n \"POST\",\n `/v1/projects/${encodePathSegment(projectId)}/scim/connections`,\n {\n json: body,\n },\n );\n }\n /** Enterprise backend `GET /v1/projects/{id}/scim/connections/{connection_id}/groups`. */\n public async listScimAdminGroups(\n projectId: string,\n connectionId: string,\n ): Promise<BackendListScimAdminGroupsResponse> {\n return await this.backendRequest<BackendListScimAdminGroupsResponse>(\n \"GET\",\n `/v1/projects/${encodePathSegment(projectId)}/scim/connections/${encodePathSegment(connectionId)}/groups`,\n );\n }\n /** Enterprise backend `PUT /v1/projects/{id}/scim/connections/{connection_id}/groups/{group_id}/roles`. */\n public async replaceScimGroupRoles(\n projectId: string,\n connectionId: string,\n groupId: string,\n body: BackendReplaceScimGroupRolesRequest,\n ): Promise<void> {\n return await this.backendRequest<void>(\n \"PUT\",\n `/v1/projects/${encodePathSegment(projectId)}/scim/connections/${encodePathSegment(connectionId)}/groups/${encodePathSegment(groupId)}/roles`,\n {\n json: body,\n },\n );\n }\n /** Enterprise backend `POST /v1/projects/{id}/scim/connections/{connection_id}/rotate`. */\n public async rotateScimConnectionSecret(\n projectId: string,\n connectionId: string,\n ): Promise<BackendCreateScimConnectionResponse> {\n return await this.backendRequest<BackendCreateScimConnectionResponse>(\n \"POST\",\n `/v1/projects/${encodePathSegment(projectId)}/scim/connections/${encodePathSegment(connectionId)}/rotate`,\n );\n }\n /** Enterprise backend: revoke a SCIM connection. */\n public async revokeScimConnection(projectId: string, connectionId: string): Promise<BackendScimConnectionResponse> {\n return await this.backendRequest<BackendScimConnectionResponse>(\n \"POST\",\n `${this.projectPath(projectId)}/scim/connections/${encodePathSegment(connectionId)}/revoke`,\n );\n }\n /** Enterprise backend `GET /v1/projects/{id}/usage`. */\n public async getUsage(projectId: string, params: BackendDateRange): Promise<BackendUsageResponse> {\n return await this.backendRequest<BackendUsageResponse>(\n \"GET\",\n `/v1/projects/${encodePathSegment(projectId)}/usage`,\n { params: { start_date: params.startDate, end_date: params.endDate } },\n );\n }\n /** Enterprise backend `GET /v1/projects/{id}/webhooks`. */\n public async listWebhooks(projectId: string, params: PaginationParams = {}): Promise<BackendListWebhooksResponse> {\n return await this.backendRequest<BackendListWebhooksResponse>(\n \"GET\",\n `/v1/projects/${encodePathSegment(projectId)}/webhooks`,\n { params: { limit: params.limit, offset: params.offset } },\n );\n }\n /** Enterprise backend `POST /v1/projects/{id}/webhooks`. */\n public async createWebhook(projectId: string, body: BackendCreateWebhookRequest): Promise<BackendWebhookResponse> {\n return await this.backendRequest<BackendWebhookResponse>(\n \"POST\",\n `/v1/projects/${encodePathSegment(projectId)}/webhooks`,\n { json: body },\n );\n }\n /** Enterprise backend `DELETE /v1/projects/{id}/webhooks/{wh_id}`. */\n public async deleteWebhook(projectId: string, webhookId: string): Promise<void> {\n return await this.backendRequest<void>(\n \"DELETE\",\n `/v1/projects/${encodePathSegment(projectId)}/webhooks/${encodePathSegment(webhookId)}`,\n );\n }\n /** Enterprise backend `PATCH /v1/projects/{id}/webhooks/{wh_id}`. */\n public async updateWebhook(\n projectId: string,\n webhookId: string,\n body: BackendUpdateWebhookRequest,\n ): Promise<BackendWebhookResponse> {\n return await this.backendRequest<BackendWebhookResponse>(\n \"PATCH\",\n `/v1/projects/${encodePathSegment(projectId)}/webhooks/${encodePathSegment(webhookId)}`,\n { json: body },\n );\n }\n /** Enterprise backend `GET /v1/projects/{id}/webhooks/{wh_id}/deliveries`. */\n public async listWebhookDeliveries(\n projectId: string,\n webhookId: string,\n params: PaginationParams = {},\n ): Promise<BackendListWebhookDeliveriesResponse> {\n return await this.backendRequest<BackendListWebhookDeliveriesResponse>(\n \"GET\",\n `/v1/projects/${encodePathSegment(projectId)}/webhooks/${encodePathSegment(webhookId)}/deliveries`,\n { params: { limit: params.limit, offset: params.offset } },\n );\n }\n /** Enterprise backend `GET /v1/projects/{id}/webhooks/{wh_id}/deliveries/{delivery_id}`. */\n public async getWebhookDelivery(\n projectId: string,\n webhookId: string,\n deliveryId: string,\n ): Promise<BackendWebhookDeliveryDetailResponse> {\n return await this.backendRequest<BackendWebhookDeliveryDetailResponse>(\n \"GET\",\n `/v1/projects/${encodePathSegment(projectId)}/webhooks/${encodePathSegment(webhookId)}/deliveries/${encodePathSegment(deliveryId)}`,\n );\n }\n /** Enterprise backend `POST /v1/projects/{id}/webhooks/{wh_id}/deliveries/{delivery_id}/retry`. */\n public async retryWebhookDelivery(\n projectId: string,\n webhookId: string,\n deliveryId: string,\n ): Promise<BackendRetryWebhookDeliveryResponse> {\n return await this.backendRequest<BackendRetryWebhookDeliveryResponse>(\n \"POST\",\n `/v1/projects/${encodePathSegment(projectId)}/webhooks/${encodePathSegment(webhookId)}/deliveries/${encodePathSegment(deliveryId)}/retry`,\n );\n }\n /** Enterprise backend `POST /v1/projects/{id}/webhooks/{wh_id}/test`. */\n public async testWebhook(projectId: string, webhookId: string): Promise<BackendWebhookTestResponse> {\n return await this.backendRequest<BackendWebhookTestResponse>(\n \"POST\",\n `/v1/projects/${encodePathSegment(projectId)}/webhooks/${encodePathSegment(webhookId)}/test`,\n );\n }\n /** Enterprise backend `POST /v1/sandbox/public/extract`. */\n public async publicSandboxExtract(params: PublicSandboxExtractParams): Promise<BackendSandboxExtractResponse> {\n return await this.backendRequest<BackendSandboxExtractResponse>(\"POST\", `/v1/sandbox/public/extract`, {\n body: sandboxForm(params),\n ...(params.sandboxToken !== undefined ? { sandboxToken: params.sandboxToken } : {}),\n backendPublic: true,\n });\n }\n\n // -- Shared surface (Enterprise + Pro) ---------------------------------\n\n /**\n * Submit a single document for extraction. Returns the initial {@link Job}\n * record (still pending — call `waitForJob` to await completion).\n */\n public async extract(params: ExtractParams): Promise<Job> {\n const jobs = await this.extractBatch({\n files: [params.file],\n ...(params.projectId !== undefined ? { projectId: params.projectId } : {}),\n ...(params.documentId !== undefined ? { documentIds: [params.documentId] } : {}),\n ...(params.options !== undefined ? { options: params.options } : {}),\n ...(params.webhook !== undefined ? { webhook: params.webhook } : {}),\n ...(params.config !== undefined ? { configs: [params.config] } : {}),\n });\n const first = jobs[0];\n if (first === undefined) {\n throw new XbergError(\"Server did not return any job IDs\", { status: 500, body: { jobs } });\n }\n return first;\n }\n\n /**\n * Submit multiple documents in a single multipart request. Returns one\n * {@link Job} per file, in the same order.\n */\n public async extractBatch(params: ExtractBatchParams): Promise<Job[]> {\n if (params.files.length === 0) {\n throw new XbergError(\"extractBatch called with no files\", { status: 400, body: null });\n }\n\n const filenames = params.files.map(describeFile);\n const documentIds = prepareDocumentLineage(filenames, params.documentIds);\n if (documentIds.size > 0) await this.requireTier(\"enterprise\", \"extract document lineage\");\n if (params.projectId !== undefined) await this.requireTier(\"pro\", \"projectId\");\n const projectHeader = this.projectHeaderName();\n const form = new FormData();\n // ~keep The Enterprise parser captures lineage when reading each file part.\n for (const [filename, documentId] of documentIds) form.append(`document_id-${filename}`, documentId);\n const parts = params.files.map(toBlob);\n for (const { blob, filename } of parts) {\n form.append(\"file\", blob, filename);\n }\n if (params.options !== undefined) {\n form.append(\"options\", JSON.stringify(params.options));\n }\n if (params.webhook !== undefined) {\n form.append(\"webhook\", JSON.stringify(params.webhook));\n }\n appendPerFileConfigs(form, filenames, params.configs);\n\n const body = await this.requestJson<ExtractResponse>(\"POST\", \"/v1/extract\", {\n body: form,\n ...(params.projectId !== undefined ? { headers: { [projectHeader]: params.projectId } } : {}),\n });\n return pendingJobs(parts, body);\n }\n\n /**\n * Submit one retryable inline batch to Pro's `POST /v1/extract/keyed`.\n *\n * Sends every file in a single multipart request with `idempotencyKey` as the\n * `Idempotency-Key` header. Webhooks and document lineage are not accepted on\n * this route. Returns one {@link Job} per file, in the same order.\n */\n public async extractKeyed(params: ExtractKeyedParams): Promise<Job[]> {\n if (params.idempotencyKey.trim().length === 0) {\n throw new ValidationError(\"extractKeyed requires a non-blank idempotencyKey\", { status: 0, body: null });\n }\n if (params.files.length === 0) {\n throw new XbergError(\"extractKeyed called with no files\", { status: 400, body: null });\n }\n const filenames = params.files.map(describeFile);\n await this.requireTier(\"pro\", \"extractKeyed\");\n const form = new FormData();\n const parts = params.files.map(toBlob);\n for (const { blob, filename } of parts) {\n form.append(\"file\", blob, filename);\n }\n if (params.options !== undefined) {\n form.append(\"options\", JSON.stringify(params.options));\n }\n appendPerFileConfigs(form, filenames, params.configs);\n\n const headers: Record<string, string> = { \"Idempotency-Key\": params.idempotencyKey };\n if (params.projectId !== undefined) headers[this.projectHeaderName()] = params.projectId;\n const body = await this.requestJson<ExtractResponse>(\"POST\", \"/v1/extract/keyed\", { body: form, headers });\n return pendingJobs(parts, body);\n }\n\n /** Fetch a tagged extraction or crawl job record (`GET /v1/jobs/{id}`). */\n public async getJob(jobId: string, scope: JobScopeParams = {}): Promise<GetJobResponse> {\n return parseJobResponse(\n await this.requestJson<unknown>(\"GET\", `${JOBS_PATH}/${encodePathSegment(jobId)}`, {\n params: await this.jobScope(scope),\n }),\n );\n }\n\n /**\n * Fetch a job's stored result document (`GET /v1/jobs/{id}/result`).\n *\n * Declared by both tiers with an identical `JobResult` envelope; the\n * extracted documents live in `results`. Distinct from {@link getJob}, which\n * returns the job's metadata record.\n */\n public async getJobResult(jobId: string, scope: JobScopeParams = {}): Promise<JobResult> {\n return await this.requestJson<JobResult>(\"GET\", `${JOBS_PATH}/${encodePathSegment(jobId)}/result`, {\n params: await this.jobScope(scope),\n });\n }\n\n /** List jobs (paginated) via `GET /v1/jobs`. */\n public async listJobs(params: ListJobsParams = {}): Promise<ListJobsResponse> {\n return await this.requestJson<ListJobsResponse>(\"GET\", JOBS_PATH, {\n params: { ...(await this.jobScope(params)), limit: params.limit, offset: params.offset },\n });\n }\n\n /**\n * Cancel a job (`DELETE /v1/jobs/{id}`). Idempotent: both a successful\n * cancellation and a job that already reached a terminal status answer\n * `204`.\n */\n public async cancelJob(jobId: string, scope: JobScopeParams = {}): Promise<void> {\n await this.requestJson(\"DELETE\", `${JOBS_PATH}/${encodePathSegment(jobId)}`, {\n params: await this.jobScope(scope),\n });\n }\n\n /**\n * Poll {@link getJob} until the job reaches a terminal status. Throws\n * {@link TimeoutError} if the wait exceeds `timeoutMs`. Throws\n * {@link XbergError} if the terminal status is `failed` or `cancelled`.\n */\n public async waitForJob(jobId: string, options: WaitOptions = {}): Promise<Job> {\n const timeoutMs = options.timeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS;\n const initialInterval = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;\n const backoff = options.backoff ?? \"exponential\";\n const start = Date.now();\n let interval = initialInterval;\n\n for (;;) {\n const job = await this.getJob(jobId, options);\n if (job.job_type !== \"extraction\") {\n throw new ValidationError(\"expected extraction job, received crawl job\", { status: 200, body: job });\n }\n if (TERMINAL_JOB_STATUSES.includes(job.status)) {\n if (SUCCESS_JOB_STATUSES.includes(job.status)) {\n return job;\n }\n throw new XbergError(`Job ${jobId} ended with status ${job.status}`, { status: 200, body: job });\n }\n\n const elapsed = Date.now() - start;\n const remaining = timeoutMs - elapsed;\n if (remaining <= 0) {\n throw new TimeoutError(`Timed out waiting for job ${jobId} after ${timeoutMs}ms`, { status: 408, body: job });\n }\n const delay = Math.min(interval, remaining);\n await this.sleep(delay);\n if (backoff === \"exponential\") {\n interval = Math.min(interval * DEFAULT_BACKOFF_FACTOR, DEFAULT_RETRY_BACKOFF_CAP_MS);\n }\n }\n }\n\n /** Wait for many jobs in parallel. */\n public async waitForJobs(jobIds: readonly string[], options: WaitOptions = {}): Promise<Job[]> {\n return await Promise.all(jobIds.map((id) => this.waitForJob(id, options)));\n }\n\n /** Convenience: extract one file and await its result. */\n public async extractAndWait(params: ExtractAndWaitParams): Promise<Job> {\n const extractParams: ExtractParams = {\n file: params.file,\n ...(params.projectId !== undefined ? { projectId: params.projectId } : {}),\n ...(params.documentId !== undefined ? { documentId: params.documentId } : {}),\n ...(params.options !== undefined ? { options: params.options } : {}),\n ...(params.webhook !== undefined ? { webhook: params.webhook } : {}),\n ...(params.config !== undefined ? { config: params.config } : {}),\n };\n const job = await this.extract(extractParams);\n const waitOptions: WaitOptions = {\n ...(params.projectId !== undefined ? { projectId: params.projectId } : {}),\n ...(params.timeoutMs !== undefined ? { timeoutMs: params.timeoutMs } : {}),\n ...(params.pollIntervalMs !== undefined ? { pollIntervalMs: params.pollIntervalMs } : {}),\n ...(params.backoff !== undefined ? { backoff: params.backoff } : {}),\n };\n return this.waitForJob(job.id, waitOptions);\n }\n\n /** Fetch audit-log entries via `GET /v1/audit`. */\n public async audit(params: AuditParams = {}): Promise<ListAuditEntriesResponse> {\n return await this.requestJson<ListAuditEntriesResponse>(\"GET\", \"/v1/audit\", {\n params: { action: params.action, limit: params.limit, offset: params.offset },\n });\n }\n\n // -- Shared preset catalogue -------------------------------------------\n\n /** List the read-only curated presets (`GET /v1/presets`). */\n public async presets(): Promise<PresetSummary[]> {\n return await this.requestJson<PresetSummary[]>(\"GET\", \"/v1/presets\");\n }\n\n /** Fetch one curated preset in full (`GET /v1/presets/{id}`). */\n public async getPreset(presetId: string): Promise<PresetDetail> {\n return await this.requestJson<PresetDetail>(\"GET\", `/v1/presets/${encodePathSegment(presetId)}`);\n }\n\n /**\n * Download a preset's bundled sample file\n * (`GET /v1/presets/{id}/sample/{name}`). The response is raw bytes, not\n * JSON.\n */\n public async getPresetSample(presetId: string, name: string): Promise<Uint8Array> {\n const path = `/v1/presets/${encodePathSegment(presetId)}/sample/${encodePathSegment(name)}`;\n return await this.requestBytes(\"GET\", path);\n }\n\n // -- Shared RAG surface ------------------------------------------------\n\n /** List RAG collections (`GET /v1/rag/collections`). */\n public async listRagCollections(): Promise<unknown> {\n return await this.requestJson(\"GET\", \"/v1/rag/collections\");\n }\n\n /** Create a RAG collection (`POST /v1/rag/collections`). */\n public async createRagCollection(body: Record<string, unknown>): Promise<unknown> {\n return await this.requestJson(\"POST\", \"/v1/rag/collections\", { json: body });\n }\n\n /** Fetch a RAG collection (`GET /v1/rag/collections/{name}`). */\n public async getRagCollection(name: string): Promise<unknown> {\n return await this.requestJson(\"GET\", `/v1/rag/collections/${encodePathSegment(name)}`);\n }\n\n /** Delete a RAG collection (`DELETE /v1/rag/collections/{name}`). The spec documents a 204 with no content. */\n public async deleteRagCollection(name: string): Promise<void> {\n await this.requestJson(\"DELETE\", `/v1/rag/collections/${encodePathSegment(name)}`);\n }\n\n /** List the documents in a RAG collection, using the returned cursor for the next page. */\n public async listRagDocuments(name: string, params: ListRagDocumentsParams = {}): Promise<ListRagDocumentsResponse> {\n const { limit, cursor, projectId } = params;\n if (projectId !== undefined) await this.requireTier(\"pro\", \"projectId\");\n return await this.requestJson<ListRagDocumentsResponse>(\n \"GET\",\n `/v1/rag/collections/${encodePathSegment(name)}/documents`,\n {\n params: { limit, cursor },\n ...(projectId !== undefined ? { headers: { [this.projectHeaderName()]: projectId } } : {}),\n },\n );\n }\n\n /** Add documents to a RAG collection (`POST /v1/rag/collections/{name}/documents`). */\n public async addRagDocuments(name: string, body: Record<string, unknown>): Promise<unknown> {\n return await this.requestJson(\"POST\", `/v1/rag/collections/${encodePathSegment(name)}/documents`, { json: body });\n }\n\n /**\n * Delete documents from a RAG collection, by ID list or metadata filter\n * (`DELETE /v1/rag/collections/{name}/documents`). Unlike\n * {@link deleteRagCollection}, this answers `200` with a body reporting how\n * many documents were removed.\n */\n public async deleteRagDocuments(name: string, body: Record<string, unknown>): Promise<unknown> {\n return await this.requestJson(\"DELETE\", `/v1/rag/collections/${encodePathSegment(name)}/documents`, {\n json: body,\n });\n }\n\n /** Reindex a RAG document (`POST /v1/rag/collections/{name}/documents/{id}/reindex`). */\n public async reindexRagDocument(name: string, documentId: string, body?: Record<string, unknown>): Promise<unknown> {\n const path = `/v1/rag/collections/${encodePathSegment(name)}/documents/${encodePathSegment(documentId)}/reindex`;\n return await this.requestJson(\"POST\", path, body !== undefined ? { json: body } : {});\n }\n\n /** Retrieve chunks from a RAG collection (`POST /v1/rag/collections/{name}/retrieve`). */\n public async ragRetrieve(name: string, body: Record<string, unknown>): Promise<unknown> {\n return await this.requestJson(\"POST\", `/v1/rag/collections/${encodePathSegment(name)}/retrieve`, { json: body });\n }\n\n /** Kick off an embedding migration (`POST /v1/rag/collections/{name}/migrate-embeddings`). */\n public async migrateRagEmbeddings(name: string, body: Record<string, unknown>): Promise<unknown> {\n return await this.requestJson(\"POST\", `/v1/rag/collections/${encodePathSegment(name)}/migrate-embeddings`, {\n json: body,\n });\n }\n\n /** Poll an embedding-migration job (`GET .../migrate-embeddings/{jobId}`). */\n public async getRagMigrationJob(name: string, jobId: string): Promise<unknown> {\n const path = `/v1/rag/collections/${encodePathSegment(name)}/migrate-embeddings/${encodePathSegment(jobId)}`;\n return await this.requestJson(\"GET\", path);\n }\n\n /** Fetch a RAG job's status (`GET /v1/rag/jobs/{jobId}`). */\n public async getRagJob(jobId: string): Promise<unknown> {\n return await this.requestJson(\"GET\", `/v1/rag/jobs/${encodePathSegment(jobId)}`);\n }\n\n /**\n * List the managed embedding presets this server build ships\n * (`GET /v1/rag/embedding-presets`), in the canonical backend order.\n */\n public async listManagedEmbeddingPresets(): Promise<ListManagedEmbeddingPresetsResponse> {\n return await this.requestJson<ListManagedEmbeddingPresetsResponse>(\"GET\", \"/v1/rag/embedding-presets\");\n }\n\n // -- Shared saved presets ----------------------------------------------\n //\n // Both tiers serve the same routes under the same spelling and the same\n // schemas, so nothing here is tier-dependent.\n\n /** List the project's saved presets (`GET /v1/saved_presets`). */\n public async listSavedPresets(params: PaginationParams = {}): Promise<ListSavedPresetsResponse> {\n return await this.requestJson<ListSavedPresetsResponse>(\"GET\", SAVED_PRESETS_PATH, {\n params: { limit: params.limit, offset: params.offset },\n });\n }\n\n /** Create a saved preset (`POST /v1/saved_presets`). */\n public async createSavedPreset(body: CreateSavedPresetRequest): Promise<CreateSavedPresetResponse> {\n return await this.requestJson<CreateSavedPresetResponse>(\"POST\", SAVED_PRESETS_PATH, { json: body });\n }\n\n /** Fetch one saved preset (`GET /v1/saved_presets/{preset_id}`). */\n public async getSavedPreset(presetId: string): Promise<SavedPresetDetail> {\n return await this.requestJson<SavedPresetDetail>(\"GET\", this.savedPresetPath(presetId));\n }\n\n /** Update a saved preset (`PATCH /v1/saved_presets/{preset_id}`). */\n public async updateSavedPreset(presetId: string, body: UpdateSavedPresetRequest): Promise<UpdateSavedPresetResponse> {\n return await this.requestJson<UpdateSavedPresetResponse>(\"PATCH\", this.savedPresetPath(presetId), { json: body });\n }\n\n /** Delete a saved preset (`DELETE /v1/saved_presets/{preset_id}`). */\n public async deleteSavedPreset(presetId: string): Promise<void> {\n await this.requestJson(\"DELETE\", this.savedPresetPath(presetId));\n }\n\n // -- Shared auto-tune surface ------------------------------------------\n\n /** List the project's auto-tune jobs (`GET /v1/auto-tune`). */\n public async listAutoTuneJobs(params: PaginationParams = {}): Promise<ListAutoTuneJobsResponse> {\n return await this.requestJson<ListAutoTuneJobsResponse>(\"GET\", AUTO_TUNE_PATH, {\n params: { limit: params.limit, offset: params.offset },\n });\n }\n\n /**\n * Submit an auto-tune job (`POST /v1/auto-tune`). Sent as `multipart/form-data`:\n * a JSON `request` part plus one binary `file` part per document.\n */\n public async submitAutoTune(params: SubmitAutoTuneParams): Promise<CreateAutoTuneJobResponse> {\n if (params.files.length === 0) {\n throw new XbergError(\"submitAutoTune called with no files\", { status: 400, body: null });\n }\n const form = new FormData();\n form.append(\"request\", JSON.stringify(params.request));\n for (const file of params.files) {\n const { blob, filename } = toBlob(file);\n form.append(\"file\", blob, filename);\n }\n return await this.requestJson<CreateAutoTuneJobResponse>(\"POST\", AUTO_TUNE_PATH, { body: form });\n }\n\n /** Fetch the deployment's tunable knobs and OCR backends (`GET /v1/auto-tune/capabilities`). */\n public async getAutoTuneCapabilities(): Promise<AutoTuneCapabilitiesResponse> {\n return await this.requestJson<AutoTuneCapabilitiesResponse>(\"GET\", `${AUTO_TUNE_PATH}/capabilities`);\n }\n\n /** Fetch an auto-tune job's status (`GET /v1/auto-tune/{id}`). */\n public async getAutoTuneStatus(autoTuneJobId: string): Promise<AutoTuneJobStatus> {\n return await this.requestJson<AutoTuneJobStatus>(\"GET\", this.autoTunePath(autoTuneJobId));\n }\n\n /** Delete an auto-tune job (`DELETE /v1/auto-tune/{id}`). */\n public async deleteAutoTuneJob(autoTuneJobId: string): Promise<void> {\n await this.requestJson(\"DELETE\", this.autoTunePath(autoTuneJobId));\n }\n\n /**\n * Stop a running auto-tune job (`POST /v1/auto-tune/{id}/stop`).\n *\n * The run finishes the trial in flight and then completes with the partial\n * leaderboard, so {@link getAutoTuneResult} still serves the best configuration\n * the search found. Idempotent: a job that already reached a terminal state\n * answers `204` and nothing changes.\n */\n public async stopAutoTuneJob(autoTuneJobId: string): Promise<void> {\n await this.requestJson(\"POST\", `${this.autoTunePath(autoTuneJobId)}/stop`);\n }\n\n /** Promote an auto-tune result to a named tuning profile (`POST /v1/auto-tune/{id}/promote`). */\n public async promoteAutoTuneProfile(\n autoTuneJobId: string,\n body: PromoteProfileRequest,\n ): Promise<TuningProfileDetail> {\n return await this.requestJson<TuningProfileDetail>(\"POST\", `${this.autoTunePath(autoTuneJobId)}/promote`, {\n json: body,\n });\n }\n\n /** Fetch a completed auto-tune job's result (`GET /v1/auto-tune/{id}/result`). */\n public async getAutoTuneResult(autoTuneJobId: string): Promise<AutoTuneResult> {\n return await this.requestJson<AutoTuneResult>(\"GET\", `${this.autoTunePath(autoTuneJobId)}/result`);\n }\n\n // -- Shared tuning profiles --------------------------------------------\n\n /** List the project's tuning profiles (`GET /v1/tuning-profiles`). */\n public async listTuningProfiles(params: PaginationParams = {}): Promise<ListTuningProfilesResponse> {\n return await this.requestJson<ListTuningProfilesResponse>(\"GET\", TUNING_PROFILES_PATH, {\n params: { limit: params.limit, offset: params.offset },\n });\n }\n\n /** Fetch one tuning profile (`GET /v1/tuning-profiles/{id}`). */\n public async getTuningProfile(profileId: string): Promise<TuningProfileDetail> {\n return await this.requestJson<TuningProfileDetail>(\"GET\", this.tuningProfilePath(profileId));\n }\n\n /** Delete a tuning profile (`DELETE /v1/tuning-profiles/{id}`). */\n public async deleteTuningProfile(profileId: string): Promise<void> {\n await this.requestJson(\"DELETE\", this.tuningProfilePath(profileId));\n }\n\n // -- Shared uploads, usage, pages, enrichment and crawl streams ---------\n //\n // ~keep Every route below is declared by both specs; the Enterprise gate these\n // once carried denied Pro callers endpoints Pro serves.\n\n /**\n * Request presigned upload URLs (`POST /v1/uploads/presign`).\n *\n * The request body is typed off the Enterprise schema, whose `config` is a full\n * `ExtractionConfig`; Pro declares that field as an open object and accepts the\n * same payload.\n */\n public async presignUpload(body: PresignUploadRequest): Promise<PresignUploadResponse> {\n return await this.requestJson<PresignUploadResponse>(\"POST\", \"/v1/uploads/presign\", { json: body });\n }\n\n /** Confirm presigned uploads and start processing (`POST /v1/uploads/confirm`). */\n public async confirmUpload(body: ConfirmUploadRequest): Promise<ConfirmUploadResponse> {\n return await this.requestJson<ConfirmUploadResponse>(\"POST\", \"/v1/uploads/confirm\", { json: body });\n }\n\n /** Fetch usage/metering data for a date window (`GET /v1/usage`). */\n public async usage(params?: QueryParams): Promise<UsageResponse> {\n const init: RequestParts = params !== undefined ? { params } : {};\n return await this.requestJson<UsageResponse>(\"GET\", \"/v1/usage\", init);\n }\n\n /**\n * Download one rendered page of an extraction job\n * (`GET /v1/jobs/{job_id}/pages/{page_number}`). The response is a PNG image —\n * raw bytes, not JSON. `pageNumber` is 1-indexed.\n */\n public async getJobPage(jobId: string, pageNumber: number, scope: JobScopeParams = {}): Promise<Uint8Array> {\n const path = `${JOBS_PATH}/${encodePathSegment(jobId)}/pages/${encodePathSegment(String(pageNumber))}`;\n return await this.requestBytes(\"GET\", path, { params: await this.jobScope(scope) });\n }\n\n /** Pro only: list the available rendered page numbers for an extraction job. */\n public async getJobPageInventory(jobId: string, scope: JobScopeParams = {}): Promise<JobPageInventory> {\n await this.requireTier(\"pro\", \"getJobPageInventory\");\n return await this.requestJson<JobPageInventory>(\"GET\", `${JOBS_PATH}/${encodePathSegment(jobId)}/pages`, {\n params: { project_id: scope.projectId },\n });\n }\n\n /** Submit text for enrichment (`POST /v1/enrich`). */\n public async submitEnrich(body: EnrichTextRequest, scope: JobScopeParams = {}): Promise<EnrichJobSubmitted> {\n return await this.requestJson<EnrichJobSubmitted>(\"POST\", ENRICH_PATH, {\n json: body,\n params: await this.jobScope(scope),\n });\n }\n\n /** Fetch an enrichment job's status (`GET /v1/enrich/{job_id}`). */\n public async getEnrichStatus(jobId: string, scope: JobScopeParams = {}): Promise<EnrichJobStatus> {\n return await this.requestJson<EnrichJobStatus>(\"GET\", `${ENRICH_PATH}/${encodePathSegment(jobId)}`, {\n params: await this.jobScope(scope),\n });\n }\n\n /**\n * Stream a crawl job's events (`GET /v1/crawl-jobs/{crawl_job_id}/events`,\n * Server-Sent Events).\n *\n * Returns an `AsyncIterable` of the `kind`-discriminated {@link CrawlEvent}\n * union; the server closes the stream after the `complete` event.\n *\n * ```ts\n * for await (const event of client.streamCrawlEvents(crawlJobId)) {\n * if (event.kind === \"page\") {\n * console.log(event.url, event.status_code);\n * }\n * }\n * ```\n *\n * Nothing is requested until iteration begins, and the response body is\n * cancelled when iteration ends: on `complete`, on `break`/`return` out of the\n * loop, on a thrown error, or when `options.signal` aborts. A stream is idle\n * between events by design, so unlike every other method here it carries no\n * request timeout and is not routed through the retry engine — a retried\n * subscription would redeliver every event the caller had already handled.\n */\n public streamCrawlEvents(crawlJobId: string, options: StreamCrawlEventsOptions = {}): AsyncIterable<CrawlEvent> {\n const path = `${CRAWL_JOBS_PATH}/${encodePathSegment(crawlJobId)}/events`;\n const open = async (): Promise<Response> =>\n this.openEventStream(`${path}${buildQueryString(await this.jobScope(options))}`, options.signal);\n return { [Symbol.asyncIterator]: (): AsyncIterator<CrawlEvent> => iterateCrawlEvents(open) };\n }\n\n /**\n * Enterprise liveness and feature availability (`GET /healthz` on the data plane).\n * Decoded leniently: a missing feature object reads as `{ enabled: false }` and\n * unknown fields are kept, so an older or newer server does not break the call. ~keep\n */\n public async enterpriseHealthz(): Promise<EnterpriseHealthResponse> {\n await this.requireTier(\"enterprise\", \"enterpriseHealthz\");\n const body = await this.requestJson<unknown>(\"GET\", \"/healthz\");\n return decodeEnterpriseHealth(body);\n }\n\n // -- Pro-only surface --------------------------------------------------\n\n /**\n * Pro liveness and coarse license/capability state (`GET /healthz`).\n * Use readiness checks to assess dependencies. ~keep\n */\n public async proHealthz(): Promise<ProHealthResponse> {\n await this.requireTier(\"pro\", \"proHealthz\");\n return this.requestJson<ProHealthResponse>(\"GET\", \"/healthz\");\n }\n\n /** Pro only: fetch the instance's accepted auth methods (`GET /auth/config`). */\n public async authConfig(): Promise<AuthConfigResponse> {\n await this.requireTier(\"pro\", \"authConfig\");\n return this.requestJson<AuthConfigResponse>(\"GET\", \"/auth/config\");\n }\n\n /** Pro only: exchange a verified OIDC ID token for a Pro session JWT (`POST /auth/login`). */\n public async login(body: LoginRequest): Promise<LoginResponse> {\n await this.requireTier(\"pro\", \"login\");\n return this.requestJson<LoginResponse>(\"POST\", \"/auth/login\", { json: body });\n }\n\n /**\n * Pro only: read the running instance's license detail (`GET /v1/license`) —\n * licensee, plan, expiry, grace window and days remaining. Requires an admin\n * API key or an admin session.\n */\n public async getLicenseInfo(): Promise<LicenseInfoResponse> {\n await this.requireTier(\"pro\", \"getLicenseInfo\");\n return this.requestJson<LicenseInfoResponse>(\"GET\", \"/v1/license\");\n }\n\n /**\n * Pro only: upload a document's bytes against a presigned local capability\n * (`PUT /v1/uploads/local/{project_id}/{token}`).\n *\n * `projectId` and `token` come from the `upload_url` {@link presignUpload}\n * returns when the instance stages uploads locally. The capability is one-use,\n * expiring, and bounded by the size limit recorded when it was issued; the\n * body is sent as raw bytes.\n */\n public async putLocalUpload(projectId: string, token: string, file: FileLike): Promise<void> {\n await this.requireTier(\"pro\", \"putLocalUpload\");\n const { blob } = toBlob(file);\n const path = `/v1/uploads/local/${encodePathSegment(projectId)}/${encodePathSegment(token)}`;\n await this.requestJson(\"PUT\", path, {\n body: new Uint8Array(await blob.arrayBuffer()),\n headers: { \"Content-Type\": OCTET_STREAM_MEDIA_TYPE },\n });\n }\n\n /** Pro only: fetch a project's RAG config (`GET /v1/projects/{projectId}/rag-config`). */\n public async getRagConfig(projectId: string): Promise<RagConfigResponse> {\n await this.requireTier(\"pro\", \"getRagConfig\");\n return this.requestJson<RagConfigResponse>(\"GET\", `/v1/projects/${encodePathSegment(projectId)}/rag-config`);\n }\n\n /** Pro only: update a project's RAG config (`PUT /v1/projects/{projectId}/rag-config`). */\n public async setRagConfig(projectId: string, body: SetRagConfigRequest): Promise<RagConfigResponse> {\n await this.requireTier(\"pro\", \"setRagConfig\");\n return this.requestJson<RagConfigResponse>(\"PUT\", `/v1/projects/${encodePathSegment(projectId)}/rag-config`, {\n json: body,\n });\n }\n\n // -- Pro-only control plane (projects, API keys, integrations) ---------\n\n /** Pro only: list the caller's projects (`GET /v1/projects`). */\n public async listProjects(params: PaginationParams = {}): Promise<ListProjectsResponse> {\n await this.requireTier(\"pro\", \"listProjects\");\n return this.requestJson<ListProjectsResponse>(\"GET\", \"/v1/projects\", {\n params: { limit: params.limit, offset: params.offset },\n });\n }\n\n /** Pro only: create a project owned by the caller (`POST /v1/projects`). */\n public async createProject(body: CreateProjectRequest): Promise<ProjectResponse> {\n await this.requireTier(\"pro\", \"createProject\");\n return this.requestJson<ProjectResponse>(\"POST\", \"/v1/projects\", { json: body });\n }\n\n /** Pro only: read a live project visible to the caller. */\n public async proGetProject(projectId: string): Promise<ProjectResponse> {\n await this.requireTier(\"pro\", \"proGetProject\");\n return this.requestJson<ProjectResponse>(\"GET\", this.projectPath(projectId));\n }\n\n /** Pro only: rename a project. */\n public async proUpdateProject(projectId: string, body: ProUpdateProjectRequest): Promise<ProjectResponse> {\n await this.requireTier(\"pro\", \"proUpdateProject\");\n return this.requestJson<ProjectResponse>(\"PATCH\", this.projectPath(projectId), { json: body });\n }\n\n /** Pro only: soft-delete a project and revoke its API keys. */\n public async proDeleteProject(projectId: string): Promise<void> {\n await this.requireTier(\"pro\", \"proDeleteProject\");\n await this.requestJson(\"DELETE\", this.projectPath(projectId));\n }\n\n /** Enterprise only: read the project's stored extraction defaults. */\n public async getProjectExtractionConfig(projectId: string): Promise<ProjectExtractionConfigResponse> {\n await this.requireTier(\"enterprise\", \"getProjectExtractionConfig\");\n const projectHeader = this.projectHeaderName();\n return this.requestJson<ProjectExtractionConfigResponse>(\n \"GET\",\n `${this.projectPath(projectId)}/extraction-config`,\n {\n headers: { [projectHeader]: projectId },\n },\n );\n }\n\n /** Enterprise only: replace the project's stored extraction defaults. */\n public async setProjectExtractionConfig(\n projectId: string,\n body: ExtractionConfig,\n ): Promise<ProjectExtractionConfigResponse> {\n await this.requireTier(\"enterprise\", \"setProjectExtractionConfig\");\n const projectHeader = this.projectHeaderName();\n return this.requestJson<ProjectExtractionConfigResponse>(\n \"PUT\",\n `${this.projectPath(projectId)}/extraction-config`,\n {\n headers: { [projectHeader]: projectId },\n json: body,\n },\n );\n }\n\n /** Enterprise only: clear the project's stored extraction defaults. */\n public async clearProjectExtractionConfig(projectId: string): Promise<void> {\n await this.requireTier(\"enterprise\", \"clearProjectExtractionConfig\");\n const projectHeader = this.projectHeaderName();\n await this.requestJson(\"DELETE\", `${this.projectPath(projectId)}/extraction-config`, {\n headers: { [projectHeader]: projectId },\n });\n }\n\n /** Pro only: list a project's API keys (`GET /v1/projects/{projectId}/api-keys`). */\n public async listApiKeys(projectId: string, params: PaginationParams = {}): Promise<ListApiKeysResponse> {\n await this.requireTier(\"pro\", \"listApiKeys\");\n return this.requestJson<ListApiKeysResponse>(\"GET\", `${this.projectPath(projectId)}/api-keys`, {\n params: { limit: params.limit, offset: params.offset },\n });\n }\n\n /** Pro only: mint an API key for a project (`POST /v1/projects/{projectId}/api-keys`). */\n public async createApiKey(projectId: string, body: CreateApiKeyRequest): Promise<CreateApiKeyResponse> {\n await this.requireTier(\"pro\", \"createApiKey\");\n return this.requestJson<CreateApiKeyResponse>(\"POST\", `${this.projectPath(projectId)}/api-keys`, { json: body });\n }\n\n /** Pro only: revoke an API key (`DELETE /v1/projects/{projectId}/api-keys/{keyId}`). */\n public async revokeApiKey(projectId: string, keyId: string): Promise<void> {\n await this.requireTier(\"pro\", \"revokeApiKey\");\n await this.requestJson(\"DELETE\", `${this.projectPath(projectId)}/api-keys/${encodePathSegment(keyId)}`);\n }\n\n /** Pro only: list a project's integrations (`GET /v1/projects/{projectId}/integrations`). */\n public async listIntegrations(projectId: string, params: PaginationParams = {}): Promise<ListIntegrationsResponse> {\n await this.requireTier(\"pro\", \"listIntegrations\");\n return this.requestJson<ListIntegrationsResponse>(\"GET\", `${this.projectPath(projectId)}/integrations`, {\n params: { limit: params.limit, offset: params.offset },\n });\n }\n\n /** Pro only: create an integration (`POST /v1/projects/{projectId}/integrations`). */\n public async createIntegration(projectId: string, body: CreateIntegrationRequest): Promise<IntegrationResponse> {\n await this.requireTier(\"pro\", \"createIntegration\");\n return this.requestJson<IntegrationResponse>(\"POST\", `${this.projectPath(projectId)}/integrations`, {\n json: body,\n });\n }\n\n /** Pro only: fetch one integration (`GET .../integrations/{integrationId}`). */\n public async getIntegration(projectId: string, integrationId: string): Promise<IntegrationResponse> {\n await this.requireTier(\"pro\", \"getIntegration\");\n return this.requestJson<IntegrationResponse>(\"GET\", this.integrationPath(projectId, integrationId));\n }\n\n /** Pro only: read durable synchronization state for an integration. */\n public async getIntegrationSync(projectId: string, integrationId: string): Promise<IntegrationSyncResponse> {\n await this.requireTier(\"pro\", \"getIntegrationSync\");\n return this.requestJson<IntegrationSyncResponse>(\"GET\", `${this.integrationPath(projectId, integrationId)}/sync`);\n }\n\n /** Pro only: enable or disable durable synchronization for an integration. */\n public async setIntegrationSync(\n projectId: string,\n integrationId: string,\n body: SetIntegrationSyncRequest,\n ): Promise<void> {\n await this.requireTier(\"pro\", \"setIntegrationSync\");\n await this.requestJson(\"PUT\", `${this.integrationPath(projectId, integrationId)}/sync`, {\n json: body,\n });\n }\n\n /** Pro only: permanently bind an integration to a RAG collection in the same project. */\n public async bindIntegrationRagTarget(\n projectId: string,\n integrationId: string,\n body: BindIntegrationRagTargetRequest,\n ): Promise<void> {\n await this.requireTier(\"pro\", \"bindIntegrationRagTarget\");\n await this.requestJson(\"PUT\", `${this.integrationPath(projectId, integrationId)}/sync/rag-target`, { json: body });\n }\n\n /** Pro only: delete an integration (`DELETE .../integrations/{integrationId}`). */\n public async deleteIntegration(projectId: string, integrationId: string): Promise<void> {\n await this.requireTier(\"pro\", \"deleteIntegration\");\n await this.requestJson(\"DELETE\", this.integrationPath(projectId, integrationId));\n }\n\n /**\n * Pro only: begin the OAuth flow for an integration\n * (`POST .../integrations/{integrationId}/connect`). Returns the provider\n * authorize URL to redirect the user to.\n */\n public async connectIntegration(projectId: string, integrationId: string): Promise<BeginOAuthResponse> {\n await this.requireTier(\"pro\", \"connectIntegration\");\n return this.requestJson<BeginOAuthResponse>(\"POST\", `${this.integrationPath(projectId, integrationId)}/connect`);\n }\n\n /** Pro only: revoke an integration's OAuth connection (`POST .../disconnect`). */\n public async disconnectIntegration(projectId: string, integrationId: string): Promise<void> {\n await this.requireTier(\"pro\", \"disconnectIntegration\");\n await this.requestJson(\"POST\", `${this.integrationPath(projectId, integrationId)}/disconnect`);\n }\n\n /** Pro only: list the documents an integration exposes (`GET .../documents`). */\n public async listIntegrationDocuments(\n projectId: string,\n integrationId: string,\n params: ListIntegrationDocumentsParams = {},\n ): Promise<ListDocumentsResponse> {\n await this.requireTier(\"pro\", \"listIntegrationDocuments\");\n return this.requestJson<ListDocumentsResponse>(\n \"GET\",\n `${this.integrationPath(projectId, integrationId)}/documents`,\n {\n params: {\n mime_types: params.mimeTypes,\n folder_id: params.folderId,\n limit: params.limit,\n offset: params.offset,\n },\n },\n );\n }\n\n /**\n * Pro only: download one document from an integration\n * (`GET .../documents/{documentId}`). The response is raw bytes, not JSON.\n */\n public async fetchIntegrationDocument(\n projectId: string,\n integrationId: string,\n documentId: string,\n ): Promise<Uint8Array> {\n await this.requireTier(\"pro\", \"fetchIntegrationDocument\");\n const path = `${this.integrationPath(projectId, integrationId)}/documents/${encodePathSegment(documentId)}`;\n return this.requestBytes(\"GET\", path);\n }\n\n // -- Enterprise-only surface ------------------------------------------\n\n /**\n * Enterprise only: fetch a document's latest version with its extraction\n * result (`GET /v1/documents/{documentId}`). The spec declares an inline\n * schema, so the body is returned untyped.\n */\n public async getDocument(documentId: string): Promise<unknown> {\n await this.requireTier(\"enterprise\", \"getDocument\");\n return this.requestJson(\"GET\", this.documentPath(documentId));\n }\n\n /** Enterprise only: list a document's versions (`GET /v1/documents/{id}/versions`). */\n public async versions(documentId: string): Promise<DocumentVersionEntry[]> {\n await this.requireTier(\"enterprise\", \"versions\");\n return this.requestJson<DocumentVersionEntry[]>(\"GET\", `${this.documentPath(documentId)}/versions`);\n }\n\n /**\n * Enterprise only: diff document versions (`GET /v1/documents/{id}/diff`).\n *\n * Computed inline when the server can afford it (`200`, {@link DiffResponse}\n * in `result.body`), or queued for async computation when it can't (`202`,\n * a {@link DiffAsyncAccepted} job envelope in `result.body`) — the same\n * fallback {@link getDiffJob} polls. Narrow on `result.status`:\n *\n * ```ts\n * const result = await client.diff(documentId);\n * if (result.status === 200) {\n * // result.body: DiffResponse\n * } else {\n * // result.body: DiffAsyncAccepted — poll getDiffJob(documentId, result.body.diff_job_id)\n * }\n * ```\n */\n public async diff(documentId: string, params?: QueryParams): Promise<DiffResult> {\n await this.requireTier(\"enterprise\", \"diff\");\n const init: RequestParts = params !== undefined ? { params } : {};\n const { status, body } = await this.requestJsonWithStatus<DiffResponse | DiffAsyncAccepted>(\n \"GET\",\n `${this.documentPath(documentId)}/diff`,\n init,\n );\n return toDiffResult(status, body);\n }\n\n /**\n * Enterprise only: poll a diff job (`GET /v1/documents/{id}/diff/{diffJobId}`).\n *\n * Returns the same {@link DiffResult} union as {@link diff}: `200` once the\n * job has finished (`result.body`: {@link DiffResponse}), `202` while it is\n * still pending (`result.body`: {@link DiffAsyncAccepted}). Narrow on\n * `result.status` as shown in {@link diff}'s TSDoc.\n */\n public async getDiffJob(documentId: string, diffJobId: string): Promise<DiffResult> {\n await this.requireTier(\"enterprise\", \"getDiffJob\");\n const path = `${this.documentPath(documentId)}/diff/${encodePathSegment(diffJobId)}`;\n const { status, body } = await this.requestJsonWithStatus<DiffResponse | DiffAsyncAccepted>(\"GET\", path);\n return toDiffResult(status, body);\n }\n\n /** Enterprise only: list the project's extraction events (`GET /v1/extractions`). */\n public async listExtractionEvents(params: ListExtractionEventsParams = {}): Promise<ListExtractionEventsResponse> {\n await this.requireTier(\"enterprise\", \"listExtractionEvents\");\n return this.requestJson<ListExtractionEventsResponse>(\"GET\", EXTRACTIONS_PATH, {\n params: { days: params.days, limit: params.limit, offset: params.offset },\n });\n }\n\n /**\n * Enterprise only: list a webhook subscription's delivery attempts\n * (`GET /v1/webhooks/{webhook_id}/deliveries`). Metadata only — call\n * {@link getSubscriptionDelivery} for an attempt's payload previews.\n *\n * ~keep Distinct from {@link listWebhookDeliveries}, which reads the same\n * history through the control plane's project-scoped route.\n */\n public async listSubscriptionDeliveries(\n webhookId: string,\n params: PaginationParams = {},\n ): Promise<ListWebhookDeliveriesResponse> {\n await this.requireTier(\"enterprise\", \"listSubscriptionDeliveries\");\n return this.requestJson<ListWebhookDeliveriesResponse>(\"GET\", this.webhookDeliveriesPath(webhookId), {\n params: { limit: params.limit, offset: params.offset },\n });\n }\n\n /**\n * Enterprise only: fetch one delivery attempt with its bounded request and\n * response previews (`GET /v1/webhooks/{webhook_id}/deliveries/{delivery_id}`).\n * The previews can carry project document content.\n */\n public async getSubscriptionDelivery(webhookId: string, deliveryId: string): Promise<WebhookDeliveryDetailResponse> {\n await this.requireTier(\"enterprise\", \"getSubscriptionDelivery\");\n const path = `${this.webhookDeliveriesPath(webhookId)}/${encodePathSegment(deliveryId)}`;\n return this.requestJson<WebhookDeliveryDetailResponse>(\"GET\", path);\n }\n\n // -- Enterprise-only documents and data rooms --------------------------\n //\n // ~keep Every room route answers 404 `data_room.disabled` on a plan without data\n // rooms; that surfaces as DataRoomsDisabledError, and `enterpriseHealthz()`\n // reports it ahead of time as `data_rooms.enabled === false`.\n\n /**\n * Enterprise only: list the project's logical documents (`GET /v1/documents`),\n * each shown by its newest finished version, most recently updated first. An\n * entry's `document_id` is the id {@link addRoomItem} takes.\n */\n public async listDocuments(params: PaginationParams = {}): Promise<ListProjectDocumentsResponse> {\n await this.requireTier(\"enterprise\", \"listDocuments\");\n return this.requestJson<ListProjectDocumentsResponse>(\"GET\", DOCUMENTS_PATH, {\n params: { limit: params.limit, offset: params.offset },\n });\n }\n\n /**\n * Enterprise only: list the data rooms the caller can see (`GET /v1/rooms`),\n * with the rights it holds on each. `state: \"deleted\"` lists the deleted rooms\n * that can still be restored.\n */\n public async listRooms(params: ListRoomsParams = {}): Promise<ListRoomsResponse> {\n await this.requireTier(\"enterprise\", \"listRooms\");\n return this.requestJson<ListRoomsResponse>(\"GET\", ROOMS_PATH, {\n params: { limit: params.limit, offset: params.offset, state: params.state },\n });\n }\n\n /**\n * Enterprise only: create a data room owned by the caller (`POST /v1/rooms`).\n * A project at its room limit answers 409 `quota_exceeded`.\n */\n public async createRoom(body: CreateRoomRequest): Promise<RoomResponse> {\n await this.requireTier(\"enterprise\", \"createRoom\");\n return this.requestJson<RoomResponse>(\"POST\", ROOMS_PATH, { json: body });\n }\n\n /** Enterprise only: fetch one live data room with the caller's rights on it (`GET /v1/rooms/{id}`). */\n public async getRoom(roomId: string): Promise<RoomResponse> {\n await this.requireTier(\"enterprise\", \"getRoom\");\n return this.requestJson<RoomResponse>(\"GET\", this.roomPath(roomId));\n }\n\n /**\n * Enterprise only: rename a data room or change its description\n * (`PATCH /v1/rooms/{id}`).\n *\n * `version` is the room's `version` as last read, sent as `If-Match`. A stale\n * one throws {@link PreconditionFailedError}; read the room again and retry.\n * The returned room carries the new `version`. A `null` description clears it.\n */\n public async updateRoom(roomId: string, body: UpdateRoomRequest, version: number): Promise<RoomResponse> {\n await this.requireTier(\"enterprise\", \"updateRoom\");\n return this.requestJson<RoomResponse>(\"PATCH\", this.roomPath(roomId), {\n json: body,\n headers: ifMatch(version),\n });\n }\n\n /**\n * Enterprise only: delete a live data room (`DELETE /v1/rooms/{id}`). It stays\n * restorable until its `restorable_until`; see {@link restoreRoom}.\n */\n public async deleteRoom(roomId: string): Promise<void> {\n await this.requireTier(\"enterprise\", \"deleteRoom\");\n await this.requestJson(\"DELETE\", this.roomPath(roomId));\n }\n\n /**\n * Enterprise only: restore a deleted data room inside its restore window\n * (`POST /v1/rooms/{id}/restore`). A project at its room limit answers 409.\n */\n public async restoreRoom(roomId: string): Promise<RoomResponse> {\n await this.requireTier(\"enterprise\", \"restoreRoom\");\n return this.requestJson<RoomResponse>(\"POST\", `${this.roomPath(roomId)}/restore`);\n }\n\n /**\n * Enterprise only: list a room's documents in room order\n * (`GET /v1/rooms/{id}/items`). The answer's `version` is the one\n * {@link reorderRoomItems} sends.\n */\n public async listRoomItems(roomId: string, params: PaginationParams = {}): Promise<ListRoomItemsResponse> {\n await this.requireTier(\"enterprise\", \"listRoomItems\");\n return this.requestJson<ListRoomItemsResponse>(\"GET\", `${this.roomPath(roomId)}/items`, {\n params: { limit: params.limit, offset: params.offset },\n });\n }\n\n /**\n * Enterprise only: add a project document to the end of a room\n * (`POST /v1/rooms/{id}/items`). The document needs a finished version; take\n * its id from {@link listDocuments}. It moves the room version without\n * returning it: read it again before the next versioned write.\n */\n public async addRoomItem(roomId: string, body: AddRoomItemRequest): Promise<RoomItemResponse> {\n await this.requireTier(\"enterprise\", \"addRoomItem\");\n return this.requestJson<RoomItemResponse>(\"POST\", `${this.roomPath(roomId)}/items`, { json: body });\n }\n\n /**\n * Enterprise only: set the order of every item in a room\n * (`PUT /v1/rooms/{id}/items/order`). `body.document_ids` names each item once.\n *\n * `version` is the room version from {@link listRoomItems} or\n * {@link getRoom}, sent as `If-Match`; a stale one throws\n * {@link PreconditionFailedError}. The answer carries the new `version`.\n */\n public async reorderRoomItems(\n roomId: string,\n body: ReorderRoomItemsRequest,\n version: number,\n ): Promise<ReorderRoomItemsResponse> {\n await this.requireTier(\"enterprise\", \"reorderRoomItems\");\n return this.requestJson<ReorderRoomItemsResponse>(\"PUT\", `${this.roomPath(roomId)}/items/order`, {\n json: body,\n headers: ifMatch(version),\n });\n }\n\n /**\n * Enterprise only: remove a document from a room\n * (`DELETE /v1/rooms/{id}/items/{document_id}`). The document stays in the project.\n * It moves the room version without returning it. A retried call whose first\n * attempt applied throws {@link NotFoundError}.\n */\n public async removeRoomItem(roomId: string, documentId: string): Promise<void> {\n await this.requireTier(\"enterprise\", \"removeRoomItem\");\n await this.requestJson(\"DELETE\", this.roomItemPath(roomId, documentId));\n }\n\n /**\n * Enterprise only: fetch the extraction result of a room item's newest\n * finished version (`GET /v1/rooms/{id}/items/{document_id}/content`).\n * `result` is `null` while extraction has not finished.\n */\n public async getRoomItemContent(roomId: string, documentId: string): Promise<RoomItemContentResponse> {\n await this.requireTier(\"enterprise\", \"getRoomItemContent\");\n return this.requestJson<RoomItemContentResponse>(\"GET\", `${this.roomItemPath(roomId, documentId)}/content`);\n }\n\n /**\n * Enterprise only: download a room item's original file\n * (`GET /v1/rooms/{id}/items/{document_id}/download`). The response is raw\n * bytes, not JSON. A room that does not allow downloads answers 403.\n */\n public async downloadRoomItem(roomId: string, documentId: string): Promise<Uint8Array> {\n await this.requireTier(\"enterprise\", \"downloadRoomItem\");\n return this.requestBytes(\"GET\", `${this.roomItemPath(roomId, documentId)}/download`);\n }\n\n /**\n * Enterprise only: download one rendered page of a room item as a PNG\n * (`GET /v1/rooms/{id}/items/{document_id}/pages/{page_number}`). Raw bytes,\n * not JSON. `pageNumber` is 1-indexed. Every reader of the room can open it,\n * whatever its download setting.\n */\n public async getRoomItemPage(roomId: string, documentId: string, pageNumber: number): Promise<Uint8Array> {\n await this.requireTier(\"enterprise\", \"getRoomItemPage\");\n const path = `${this.roomItemPath(roomId, documentId)}/pages/${encodePathSegment(String(pageNumber))}`;\n return this.requestBytes(\"GET\", path);\n }\n\n /** Enterprise only: list the users holding a grant on a room (`GET /v1/rooms/{id}/members`). */\n public async listRoomMembers(roomId: string, params: PaginationParams = {}): Promise<ListRoomMembersResponse> {\n await this.requireTier(\"enterprise\", \"listRoomMembers\");\n return this.requestJson<ListRoomMembersResponse>(\"GET\", `${this.roomPath(roomId)}/members`, {\n params: { limit: params.limit, offset: params.offset },\n });\n }\n\n /**\n * Enterprise only: give a project member a grant on a room\n * (`POST /v1/rooms/{id}/members`). Anyone outside the project joins by\n * {@link createRoomInvitation} instead.\n */\n public async addRoomMember(roomId: string, body: AddRoomMemberRequest): Promise<RoomMemberResponse> {\n await this.requireTier(\"enterprise\", \"addRoomMember\");\n return this.requestJson<RoomMemberResponse>(\"POST\", `${this.roomPath(roomId)}/members`, { json: body });\n }\n\n /**\n * Enterprise only: remove a member's grant on a room\n * (`DELETE /v1/rooms/{id}/members/{user_id}`). The owner answers 409; transfer\n * ownership first.\n */\n public async removeRoomMember(roomId: string, userId: string): Promise<void> {\n await this.requireTier(\"enterprise\", \"removeRoomMember\");\n await this.requestJson(\"DELETE\", this.roomMemberPath(roomId, userId));\n }\n\n /**\n * Enterprise only: change a room member's role to an editor or a viewer\n * (`PATCH /v1/rooms/{id}/members/{user_id}`).\n */\n public async changeRoomMemberRole(\n roomId: string,\n userId: string,\n body: RoomChangeRoleRequest,\n ): Promise<RoomMemberResponse> {\n await this.requireTier(\"enterprise\", \"changeRoomMemberRole\");\n return this.requestJson<RoomMemberResponse>(\"PATCH\", this.roomMemberPath(roomId, userId), { json: body });\n }\n\n /**\n * Enterprise only: remove the caller's own grant on a room\n * (`POST /v1/rooms/{id}/leave`). The owner answers 409.\n */\n public async leaveRoom(roomId: string): Promise<void> {\n await this.requireTier(\"enterprise\", \"leaveRoom\");\n await this.requestJson(\"POST\", `${this.roomPath(roomId)}/leave`);\n }\n\n /**\n * Enterprise only: make another room member the owner\n * (`POST /v1/rooms/{id}/ownership`). The new owner must be a project member\n * who already holds a grant on the room.\n */\n public async transferRoomOwnership(roomId: string, body: RoomTransferOwnershipRequest): Promise<void> {\n await this.requireTier(\"enterprise\", \"transferRoomOwnership\");\n await this.requestJson(\"POST\", `${this.roomPath(roomId)}/ownership`, { json: body });\n }\n\n /** Enterprise only: list a data room's share links. */\n public async listRoomLinks(roomId: string, params: PaginationParams = {}): Promise<ListRoomLinksResponse> {\n await this.requireTier(\"enterprise\", \"listRoomLinks\");\n return this.requestJson<ListRoomLinksResponse>(\"GET\", `${this.roomPath(roomId)}/links`, {\n params: { limit: params.limit, offset: params.offset },\n });\n }\n\n /** Enterprise only: update link access using the room's last observed version. */\n public async setRoomLinkAccess(\n roomId: string,\n body: SetRoomLinkAccessRequest,\n version: number,\n ): Promise<RoomLinkAccessResponse> {\n await this.requireTier(\"enterprise\", \"setRoomLinkAccess\");\n return this.requestJson<RoomLinkAccessResponse>(\"PUT\", `${this.roomPath(roomId)}/links`, {\n json: body,\n headers: ifMatch(version),\n });\n }\n\n /** Enterprise only: create a share link for a data room. */\n public async createRoomLink(roomId: string, body: CreateRoomLinkRequest): Promise<RoomLinkResponse> {\n await this.requireTier(\"enterprise\", \"createRoomLink\");\n return this.requestJson<RoomLinkResponse>(\"POST\", `${this.roomPath(roomId)}/links`, {\n json: body,\n });\n }\n\n /** Enterprise only: revoke a data room share link and its grants. */\n public async revokeRoomLink(roomId: string, linkId: string): Promise<void> {\n await this.requireTier(\"enterprise\", \"revokeRoomLink\");\n await this.requestJson(\"DELETE\", `${this.roomPath(roomId)}/links/${encodePathSegment(linkId)}`);\n }\n\n /** Enterprise only: accept a share link with a signed-in user's session. */\n public async acceptRoomLink(\n body: RoomAcceptInvitationRequest,\n options: RoomInvitationOptions = {},\n ): Promise<AcceptedRoomInvitationResponse> {\n const bearer = sessionBearer(options);\n await this.requireTier(\"enterprise\", \"acceptRoomLink\");\n return this.requestJson<AcceptedRoomInvitationResponse>(\"POST\", \"/v1/room-links/accept\", {\n json: body,\n ...bearer,\n });\n }\n\n /**\n * Enterprise only: list a room's invitations (`GET /v1/rooms/{id}/invitations`).\n * The answer never carries an invitation token.\n */\n public async listRoomInvitations(\n roomId: string,\n params: PaginationParams = {},\n ): Promise<ListRoomInvitationsResponse> {\n await this.requireTier(\"enterprise\", \"listRoomInvitations\");\n return this.requestJson<ListRoomInvitationsResponse>(\"GET\", `${this.roomPath(roomId)}/invitations`, {\n params: { limit: params.limit, offset: params.offset },\n });\n }\n\n /**\n * Enterprise only: invite an email address to a room\n * (`POST /v1/rooms/{id}/invitations`). `token` is in the answer only when the\n * configured delivery channel returns it.\n */\n public async createRoomInvitation(roomId: string, body: RoomInviteRequest): Promise<RoomInvitationResponse> {\n await this.requireTier(\"enterprise\", \"createRoomInvitation\");\n return this.requestJson<RoomInvitationResponse>(\"POST\", `${this.roomPath(roomId)}/invitations`, { json: body });\n }\n\n /**\n * Enterprise only: revoke a pending room invitation\n * (`DELETE /v1/rooms/{id}/invitations/{invitation_id}`).\n */\n public async revokeRoomInvitation(roomId: string, invitationId: string): Promise<void> {\n await this.requireTier(\"enterprise\", \"revokeRoomInvitation\");\n await this.requestJson(\"DELETE\", `${this.roomPath(roomId)}/invitations/${encodePathSegment(invitationId)}`);\n }\n\n /**\n * Enterprise only: show a signed-in invitee the room an invitation token opens\n * (`POST /v1/room-invitations/preview`).\n *\n * Requires a dashboard user session, not an API key: pass\n * `options.sessionToken` or build the client with the session token as\n * `apiKey`. A token that cannot be accepted answers 404, whatever the reason.\n */\n public async previewRoomInvitation(\n body: RoomAcceptInvitationRequest,\n options: RoomInvitationOptions = {},\n ): Promise<RoomInvitationPreviewResponse> {\n await this.requireTier(\"enterprise\", \"previewRoomInvitation\");\n return this.requestJson<RoomInvitationPreviewResponse>(\"POST\", `${ROOM_INVITATIONS_PATH}/preview`, {\n json: body,\n ...sessionBearer(options),\n });\n }\n\n /**\n * Enterprise only: accept an invitation token for the signed-in user\n * (`POST /v1/room-invitations/accept`), granting them the room.\n *\n * Requires a dashboard user session, not an API key: pass\n * `options.sessionToken` or build the client with the session token as\n * `apiKey`. A token that cannot be accepted answers 404, whatever the reason.\n */\n public async acceptRoomInvitation(\n body: RoomAcceptInvitationRequest,\n options: RoomInvitationOptions = {},\n ): Promise<AcceptedRoomInvitationResponse> {\n await this.requireTier(\"enterprise\", \"acceptRoomInvitation\");\n return this.requestJson<AcceptedRoomInvitationResponse>(\"POST\", `${ROOM_INVITATIONS_PATH}/accept`, {\n json: body,\n ...sessionBearer(options),\n });\n }\n\n /**\n * Enterprise only: read a room's publication settings\n * (`GET /v1/rooms/{id}/publication`). `room_version` is the value\n * {@link setRoomPublication} sends.\n */\n public async getRoomPublication(roomId: string): Promise<RoomPublicationResponse> {\n await this.requireTier(\"enterprise\", \"getRoomPublication\");\n return this.requestJson<RoomPublicationResponse>(\"GET\", `${this.roomPath(roomId)}/publication`);\n }\n\n /**\n * Enterprise only: publish or unpublish a room, optionally changing its mode\n * and download setting (`PUT /v1/rooms/{id}/publication`).\n *\n * `version` is the room version (`room_version` from\n * {@link getRoomPublication}, or the room's `version`), sent as `If-Match`; a\n * stale one throws {@link PreconditionFailedError}. The answer carries the\n * new `room_version` and, once published, the public `slug`.\n */\n public async setRoomPublication(\n roomId: string,\n body: SetRoomPublicationRequest,\n version: number,\n ): Promise<RoomPublicationResponse> {\n await this.requireTier(\"enterprise\", \"setRoomPublication\");\n return this.requestJson<RoomPublicationResponse>(\"PUT\", `${this.roomPath(roomId)}/publication`, {\n json: body,\n headers: ifMatch(version),\n });\n }\n\n /**\n * Enterprise only: read a published room by its slug (`GET /public/rooms/{slug}`).\n *\n * Unauthenticated: sends no credential and no cookie, even when the client\n * has an API key. A room that is not published answers 404.\n */\n public async getPublicRoom(slug: string): Promise<PublicRoomResponse> {\n await this.requireTier(\"enterprise\", \"getPublicRoom\");\n return this.requestJson<PublicRoomResponse>(\"GET\", this.publicRoomPath(slug), { anonymous: true });\n }\n\n /**\n * Enterprise only: list a published room's items in room order\n * (`GET /public/rooms/{slug}/items`). Unauthenticated; each item's `item_ref`\n * is what the public content and download methods take.\n */\n public async listPublicRoomItems(slug: string, params: PaginationParams = {}): Promise<PublicRoomItemsResponse> {\n await this.requireTier(\"enterprise\", \"listPublicRoomItems\");\n return this.requestJson<PublicRoomItemsResponse>(\"GET\", `${this.publicRoomPath(slug)}/items`, {\n anonymous: true,\n params: { limit: params.limit, offset: params.offset },\n });\n }\n\n /**\n * Enterprise only: fetch the extraction result of a published room's item\n * (`GET /public/rooms/{slug}/items/{item_ref}/content`). Unauthenticated;\n * `result` is `null` until extraction finishes.\n */\n public async getPublicRoomItemContent(slug: string, itemRef: string): Promise<PublicRoomItemContentResponse> {\n await this.requireTier(\"enterprise\", \"getPublicRoomItemContent\");\n return this.requestJson<PublicRoomItemContentResponse>(\"GET\", `${this.publicRoomItemPath(slug, itemRef)}/content`, {\n anonymous: true,\n });\n }\n\n /**\n * Enterprise only: download a published room item's original file\n * (`GET /public/rooms/{slug}/items/{item_ref}/download`). Unauthenticated; raw\n * bytes, not JSON. A room that does not allow downloads answers 404.\n */\n public async downloadPublicRoomItem(slug: string, itemRef: string): Promise<Uint8Array> {\n await this.requireTier(\"enterprise\", \"downloadPublicRoomItem\");\n return this.requestBytes(\"GET\", `${this.publicRoomItemPath(slug, itemRef)}/download`, { anonymous: true });\n }\n\n // -- Internals ---------------------------------------------------------\n\n private async jobScope(scope: JobScopeParams): Promise<QueryParams> {\n if (scope.projectId !== undefined) await this.requireTier(\"pro\", \"projectId\");\n return { project_id: scope.projectId };\n }\n\n private projectHeaderName(): string {\n return Object.keys(this.headers).find((name) => name.toLowerCase() === \"x-project-id\") ?? \"X-Project-ID\";\n }\n\n /** Build `/v1/projects/{projectId}` with the id percent-encoded. */\n private projectPath(projectId: string): string {\n return `/v1/projects/${encodePathSegment(projectId)}`;\n }\n\n /** Build `/v1/projects/{projectId}/integrations/{integrationId}`. */\n private integrationPath(projectId: string, integrationId: string): string {\n return `${this.projectPath(projectId)}/integrations/${encodePathSegment(integrationId)}`;\n }\n\n private samlProviderPath(projectId: string, providerId: string): string {\n return `${this.projectPath(projectId)}/saml/providers/${encodePathSegment(providerId)}`;\n }\n\n /** Build `/v1/documents/{documentId}` with the id percent-encoded. */\n private documentPath(documentId: string): string {\n return `${DOCUMENTS_PATH}/${encodePathSegment(documentId)}`;\n }\n\n /** Build `/v1/rooms/{id}` with the id percent-encoded. */\n private roomPath(roomId: string): string {\n return `${ROOMS_PATH}/${encodePathSegment(roomId)}`;\n }\n\n /** Build `/v1/rooms/{id}/items/{document_id}`. */\n private roomItemPath(roomId: string, documentId: string): string {\n return `${this.roomPath(roomId)}/items/${encodePathSegment(documentId)}`;\n }\n\n /** Build `/v1/rooms/{id}/members/{user_id}`. */\n private roomMemberPath(roomId: string, userId: string): string {\n return `${this.roomPath(roomId)}/members/${encodePathSegment(userId)}`;\n }\n\n /** Build `/public/rooms/{slug}` with the slug percent-encoded. */\n private publicRoomPath(slug: string): string {\n return `${PUBLIC_ROOMS_PATH}/${encodePathSegment(slug)}`;\n }\n\n /** Build `/public/rooms/{slug}/items/{item_ref}`. */\n private publicRoomItemPath(slug: string, itemRef: string): string {\n return `${this.publicRoomPath(slug)}/items/${encodePathSegment(itemRef)}`;\n }\n\n /** Build `/v1/saved_presets/{preset_id}` with the id percent-encoded. */\n private savedPresetPath(presetId: string): string {\n return `${SAVED_PRESETS_PATH}/${encodePathSegment(presetId)}`;\n }\n\n /** Build `/v1/auto-tune/{id}` with the id percent-encoded. */\n private autoTunePath(autoTuneJobId: string): string {\n return `${AUTO_TUNE_PATH}/${encodePathSegment(autoTuneJobId)}`;\n }\n\n /** Build `/v1/tuning-profiles/{id}` with the id percent-encoded. */\n private tuningProfilePath(profileId: string): string {\n return `${TUNING_PROFILES_PATH}/${encodePathSegment(profileId)}`;\n }\n\n /** Build `/v1/webhooks/{webhook_id}/deliveries` with the id percent-encoded. */\n private webhookDeliveriesPath(webhookId: string): string {\n return `${WEBHOOKS_PATH}/${encodePathSegment(webhookId)}/deliveries`;\n }\n\n /**\n * Return the effective tier — an explicit `target` if set, else probed from\n * `/healthz` and cached after the first *successful* probe. A probe that\n * fails (missing, `null`, or unrecognised `tier`) is not cached, so the\n * next call retries instead of being stuck with a poisoned result for the\n * client's lifetime. Concurrent callers share a single in-flight probe.\n */\n private async resolveTier(): Promise<Target> {\n if (this.target !== undefined) {\n return this.target;\n }\n if (this.probedTier !== undefined) {\n return this.probedTier;\n }\n if (this.tierProbe === undefined) {\n this.tierProbe = this.probeTier();\n }\n try {\n const tier = await this.tierProbe;\n this.probedTier = tier;\n return tier;\n } finally {\n this.tierProbe = undefined;\n }\n }\n\n /**\n * Issue the `/healthz` capability probe. Only `\"enterprise\"` and `\"pro\"` —\n * the tier values the specs actually declare — are accepted; anything else\n * (missing `tier`, `null`, or an unrecognised string) throws instead of\n * being treated as a usable result.\n */\n private async probeTier(): Promise<Target> {\n const body = await this.requestJson<{ tier?: unknown }>(\"GET\", \"/healthz\");\n const tier = body?.tier;\n if (tier === \"enterprise\" || tier === \"pro\") {\n return tier;\n }\n throw new XbergError(\n `/healthz returned an unrecognised tier (${JSON.stringify(tier ?? null)}); expected \"enterprise\" or \"pro\"`,\n { status: 0, body },\n );\n }\n\n /** Throw a clear error when the connected tier does not match the required one. */\n private async requireTier(required: Target, methodName: string): Promise<void> {\n const tier = await this.resolveTier();\n if (tier !== required) {\n throw new XbergError(`${methodName}() is not available on the '${tier}' tier (requires the '${required}' tier)`, {\n status: 0,\n body: null,\n });\n }\n }\n\n private backendRequest<T>(method: string, path: string, init: RequestParts = {}): Promise<T> {\n return this.requestJson<T>(method, path, { ...init, controlPlane: true });\n }\n\n private backendHeaders(init: RequestParts): Record<string, string> {\n const headers = new Headers({ ...this.headers, ...init.headers });\n for (const name of [\"authorization\", \"proxy-authorization\", \"cookie\", \"x-api-key\"]) headers.delete(name);\n const token = init.backendPublic ? init.sandboxToken : this.controlPlaneToken;\n if (token !== undefined && token.length > 0) headers.set(\"Authorization\", `Bearer ${token}`);\n if (init.body instanceof FormData || init.json !== undefined) headers.delete(\"content-type\");\n return Object.fromEntries(headers);\n }\n\n /**\n * Data-plane headers: the client's own merged with the call's, then stripped\n * of every credential for an anonymous call, or given a per-call bearer.\n */\n private dataPlaneHeaders(init: RequestParts): Record<string, string> {\n const merged = { ...this.headers, ...init.headers };\n if (!init.anonymous && init.bearerToken === undefined) {\n return merged;\n }\n const headers = new Headers(merged);\n if (init.anonymous) {\n for (const name of CREDENTIAL_HEADERS) headers.delete(name);\n } else if (init.bearerToken !== undefined) {\n headers.set(\"Authorization\", `Bearer ${init.bearerToken}`);\n }\n return Object.fromEntries(headers);\n }\n\n /** Issue a request, raise on non-2xx, and decode the JSON body (undefined for empty bodies). */\n private async requestJson<T = unknown>(method: string, path: string, init: RequestParts = {}): Promise<T> {\n const { body } = await this.requestJsonWithStatus<T>(method, path, init);\n return body;\n }\n\n /**\n * Like {@link requestJson}, but also returns the response's status code.\n * Used by endpoints whose 2xx responses carry different schemas per status\n * (currently only `diff`/`getDiffJob`'s `200`/`202` split).\n */\n private async requestJsonWithStatus<T = unknown>(\n method: string,\n path: string,\n init: RequestParts = {},\n ): Promise<{ status: number; body: T }> {\n const response = await this.requestWithRetry(method, path, init);\n if (response.status === 204) {\n return { status: response.status, body: undefined as T };\n }\n const text = await response.text();\n const body = (text.length > 0 ? JSON.parse(text) : undefined) as T;\n return { status: response.status, body };\n }\n\n /**\n * Open a `text/event-stream` response, deliberately bypassing\n * {@link requestWithRetry}.\n *\n * Two of that method's behaviours are wrong for a subscription. Its retry\n * loop would re-open a partly-consumed stream and redeliver every event the\n * caller already handled — indistinguishable, from the caller's side, from\n * the server sending them twice. And its `AbortSignal.timeout(timeoutMs)`\n * bounds a request/response round trip, while this response stays open for\n * the length of a crawl and is idle between events by design; the caller's\n * own `signal` is the only deadline.\n */\n private async openEventStream(path: string, signal?: AbortSignal): Promise<Response> {\n const url = `${this.baseUrl}${path}`;\n const requestInit: RequestInit = {\n method: \"GET\",\n headers: { ...this.headers, Accept: EVENT_STREAM_MEDIA_TYPE },\n };\n if (signal !== undefined) {\n requestInit.signal = signal;\n }\n\n let response: Response;\n try {\n response = await this.fetchImpl(url, requestInit);\n } catch (cause) {\n throw new XbergError(`Network error contacting ${url}`, { status: 0, body: null, cause });\n }\n if (!response.ok) {\n await raiseForStatus(response);\n throw new XbergError(\"Unreachable\", { status: response.status, body: null });\n }\n return response;\n }\n\n /** Issue a request, raise on non-2xx, and return the response body as raw bytes. */\n private async requestBytes(method: string, path: string, init: RequestParts = {}): Promise<Uint8Array> {\n const response = await this.requestWithRetry(method, path, init);\n return new Uint8Array(await response.arrayBuffer());\n }\n\n /**\n * Issue a raw HTTP request with auth, timeout, query params, and retry\n * handling. Returns the raw (2xx) {@link Response}; non-2xx responses are\n * mapped to a thrown {@link XbergError} subclass.\n */\n private prepareRequest(method: string, init: RequestParts): RequestInit {\n const headers = init.controlPlane ? this.backendHeaders(init) : this.dataPlaneHeaders(init);\n let body: FormData | string | Uint8Array | undefined = init.body;\n if (init.json !== undefined) {\n headers[\"Content-Type\"] = \"application/json\";\n body = JSON.stringify(init.json);\n }\n const requestInit: RequestInit = {\n method,\n headers,\n signal: AbortSignal.timeout(this.timeoutMs),\n ...(init.controlPlane ? ({ credentials: \"omit\", redirect: \"manual\" } as const) : {}),\n ...(init.anonymous ? ({ credentials: \"omit\" } as const) : {}),\n };\n if (body !== undefined) {\n requestInit.body = body;\n }\n return requestInit;\n }\n\n /**\n * Whether a response status is retryable for this request under the configured policy. A request\n * carrying `If-Match` (`conditional`) is treated like a POST: once an attempt applied, the room\n * version moved, so a replay can only answer 412.\n */\n private shouldRetryStatus(method: string, status: number, conditional: boolean): boolean {\n if (!this.retryOn.includes(status)) {\n return false;\n }\n if (status === 429 || this.retryNonIdempotent) {\n return true;\n }\n return !conditional && IDEMPOTENT_METHODS.has(method.toUpperCase());\n }\n\n private async requestWithRetry(method: string, path: string, init: RequestParts = {}): Promise<Response> {\n if (init.controlPlane && (this.target ?? this.probedTier) === \"pro\") {\n throw new XbergError(\"Enterprise backend methods are not available on the 'pro' tier\", { status: 0, body: null });\n }\n const origin = init.controlPlane ? this.controlPlaneBaseUrl : this.baseUrl;\n const url = `${origin}${path}${buildQueryString(init.params)}`;\n const conditional = Object.keys(init.headers ?? {}).some((name) => name.toLowerCase() === \"if-match\");\n let attempt = 0;\n let interval = DEFAULT_RETRY_BACKOFF_BASE_MS;\n for (;;) {\n const requestInit = this.prepareRequest(method, init);\n\n let response: Response;\n try {\n response = await this.fetchImpl(url, requestInit);\n } catch (cause) {\n if (attempt < this.retries) {\n attempt += 1;\n await this.sleep(interval);\n interval = nextBackoffInterval(interval, this.retryBackoff);\n continue;\n }\n if (init.controlPlane) {\n throw new XbergError(`Network error contacting Enterprise control plane (${method} ${path})`, {\n status: 0,\n body: null,\n });\n }\n throw new XbergError(`Network error contacting ${url}`, { status: 0, body: null, cause });\n }\n\n if (response.ok || (init.acceptRedirect && response.status === 303)) {\n return response;\n }\n\n if (this.shouldRetryStatus(method, response.status, conditional) && attempt < this.retries) {\n attempt += 1;\n const retryAfter = parseRetryAfterHeader(response.headers.get(\"retry-after\"));\n const wait = retryAfter !== undefined ? retryAfter * 1000 : interval;\n await this.sleep(wait);\n interval = nextBackoffInterval(interval, this.retryBackoff);\n continue;\n }\n\n throw await raiseForStatus(response);\n }\n }\n}\n\n/** Parts accepted by the internal request engine. */\ninterface RequestParts {\n controlPlane?: boolean;\n /** Send no credential header and no cookie: the unauthenticated `/public/...` routes. */\n anonymous?: boolean;\n /** Replace the client's data-plane bearer for this one call. */\n bearerToken?: string;\n backendPublic?: boolean;\n sandboxToken?: string;\n acceptRedirect?: boolean;\n body?: FormData | string | Uint8Array;\n json?: unknown;\n headers?: Record<string, string>;\n params?: QueryParams;\n}\n\n/**\n * Build the pending {@link Job} records for an extraction submission.\n *\n * Both extraction routes answer with job IDs alone, so the rest of each record is\n * synthesized from what was submitted; `mime_type` is the type the file was uploaded under.\n */\nfunction pendingJobs(parts: readonly { blob: Blob; filename: string }[], body: ExtractResponse): Job[] {\n const jobIds = body.job_ids ?? [];\n const now = new Date().toISOString();\n return parts.map(({ blob, filename }, index) => {\n const id = jobIds[index];\n if (id === undefined) {\n throw new XbergError(`Server returned ${jobIds.length} job IDs for ${parts.length} files`, {\n status: 500,\n body,\n });\n }\n return {\n id,\n filename,\n mime_type: blob.type.length > 0 ? blob.type : OCTET_STREAM_MEDIA_TYPE,\n status: \"pending\",\n created_at: now,\n };\n });\n}\n\n/** The `If-Match` header a room write sends: the room version, quoted as an entity tag. */\nfunction ifMatch(version: number): Record<string, string> {\n if (!Number.isSafeInteger(version) || version < 0) {\n throw new ValidationError(`Room version must be a non-negative integer, got ${String(version)}`, {\n status: 0,\n body: null,\n });\n }\n return { \"If-Match\": `\"${version}\"` };\n}\n\n/** The per-call bearer an invitation route sends, when the caller supplied a session token. */\nfunction sessionBearer(options: RoomInvitationOptions): Pick<RequestParts, \"bearerToken\"> {\n if (options.sessionToken === undefined) {\n return {};\n }\n if (options.sessionToken.trim().length === 0) {\n throw new ValidationError(\"sessionToken must not be blank\", { status: 0, body: null });\n }\n return { bearerToken: options.sessionToken };\n}\n\nfunction decodeEnterpriseHealth(payload: unknown): EnterpriseHealthResponse {\n if (typeof payload !== \"object\" || payload === null || Array.isArray(payload)) {\n throw new ValidationError(\"unexpected /healthz response shape\", { status: 200, body: payload });\n }\n const record = payload as Record<string, unknown>;\n return {\n ...record,\n status: typeof record[\"status\"] === \"string\" ? record[\"status\"] : \"\",\n tier: typeof record[\"tier\"] === \"string\" ? record[\"tier\"] : \"\",\n rag: decodeHealthFeature(record[\"rag\"]),\n auto_tune: decodeHealthFeature(record[\"auto_tune\"]),\n data_rooms: decodeHealthFeature(record[\"data_rooms\"]),\n };\n}\n\nfunction decodeHealthFeature(value: unknown): EnterpriseHealthFeature {\n if (typeof value !== \"object\" || value === null) {\n return { enabled: false };\n }\n return { ...value, enabled: (value as Record<string, unknown>)[\"enabled\"] === true };\n}\n\nfunction parseJobResponse(payload: unknown): GetJobResponse {\n if (typeof payload !== \"object\" || payload === null || Array.isArray(payload)) {\n throw new ValidationError(\"unexpected job response shape\", { status: 200, body: payload });\n }\n const record = payload as Record<string, unknown>;\n if (!(\"job_type\" in record) && typeof record[\"filename\"] === \"string\") {\n return { ...record, job_type: \"extraction\" } as GetJobResponse;\n }\n if (record[\"job_type\"] === \"extraction\" || record[\"job_type\"] === \"crawl\") {\n return record as GetJobResponse;\n }\n throw new ValidationError(\"unexpected job_type\", { status: 200, body: payload });\n}\n\n/**\n * Pair a diff response's status code with its body to build the\n * {@link DiffResult} union `diff`/`getDiffJob` return. `202` is the only\n * status carrying {@link DiffAsyncAccepted}; everything else (in practice\n * only `200`) carries the computed {@link DiffResponse}.\n */\nfunction toDiffResult(status: number, body: DiffResponse | DiffAsyncAccepted): DiffResult {\n if (status === 202) {\n return { status: 202, body: body as DiffAsyncAccepted };\n }\n return { status: 200, body: body as DiffResponse };\n}\n\n/**\n * Serialize a value with object keys sorted, so two configs that differ only in\n * key order compare equal when {@link appendPerFileConfigs} looks for a conflict.\n * Only ever used for that comparison — the value actually appended to the form is\n * a plain `JSON.stringify`, matching the `options` and `webhook` parts.\n */\nfunction canonicalJson(value: unknown): string {\n if (Array.isArray(value)) {\n return `[${value.map((entry) => canonicalJson(entry)).join(\",\")}]`;\n }\n if (typeof value === \"object\" && value !== null) {\n const entries = Object.entries(value as Record<string, unknown>)\n .filter(([, entry]) => entry !== undefined)\n .sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0));\n return `{${entries.map(([key, entry]) => `${JSON.stringify(key)}:${canonicalJson(entry)}`).join(\",\")}}`;\n }\n return JSON.stringify(value) ?? \"null\";\n}\n\n/**\n * Append one `config-<filename>` part per document carrying a per-file override.\n *\n * Appended after the `file`, `options` and `webhook` parts, and skipped entirely\n * when `configs` is undefined, so a request without overrides is byte-identical\n * to one built before this existed.\n *\n * The part is keyed on the filename, mirroring the `document_id-<filename>`\n * convention. Two documents submitted under the same filename therefore have one\n * slot for two overrides: rather than let the later `append` win and lose the\n * other with no signal, that case throws and names the file.\n */\nfunction appendPerFileConfigs(\n form: FormData,\n filenames: readonly string[],\n configs: readonly (FileExtractionConfig | null)[] | undefined,\n): void {\n if (configs === undefined) {\n return;\n }\n if (configs.length !== filenames.length) {\n throw new XbergError(\n `configs has ${configs.length} entries but ${filenames.length} files were supplied; ` +\n \"pass exactly one entry per file (null for no override)\",\n { status: 400, body: null },\n );\n }\n const seen = new Map<string, string>();\n filenames.forEach((filename, index) => {\n const config = configs[index] ?? null;\n const canonical = canonicalJson(config);\n const prior = seen.get(filename);\n if (prior !== undefined && prior !== canonical) {\n throw new XbergError(\n `per-file config conflict for \"${filename}\": the same filename appears more than once in ` +\n \"this batch with different configs, but a multipart request carries at most one config \" +\n \"part per filename. Give the copies distinct filenames.\",\n { status: 400, body: null },\n );\n }\n if (prior === undefined && config !== null) {\n form.append(`config-${filename}`, JSON.stringify(config));\n }\n seen.set(filename, canonical);\n });\n}\n\n/** Parse one SSE frame payload into the `kind`-discriminated {@link CrawlEvent} it names. */\nfunction parseCrawlEvent(payload: string): CrawlEvent {\n let body: unknown;\n try {\n body = JSON.parse(payload);\n } catch (cause) {\n throw new XbergError(`Crawl event stream sent a non-JSON frame: ${payload}`, {\n status: 0,\n body: payload,\n cause,\n });\n }\n const kind = (body as { kind?: unknown } | null)?.kind;\n if (typeof kind !== \"string\" || !CRAWL_EVENT_KINDS.has(kind)) {\n throw new XbergError(`Crawl event stream sent an unrecognised kind (${JSON.stringify(kind ?? null)})`, {\n status: 0,\n body,\n });\n }\n return body as CrawlEvent;\n}\n\n/**\n * Drive one crawl-event subscription: open it, decode its frames, and cancel\n * the response body on every exit path.\n *\n * `open` is a thunk rather than an already-opened `Response` so that a caller\n * who never iterates opens nothing — the tier gate and the request both live\n * inside the generator. The `finally` runs when the consumer `break`s or\n * `return`s out of its `for await` as much as when the stream ends, which is\n * what makes the subscription cancellable without a separate handle.\n */\nasync function* iterateCrawlEvents(open: () => Promise<Response>): AsyncGenerator<CrawlEvent> {\n const response = await open();\n if (response.body === null) {\n throw new XbergError(\"Crawl event stream response carried no body\", {\n status: response.status,\n body: null,\n });\n }\n const reader = response.body.getReader();\n const text = new TextDecoder();\n const frames = new EventStreamDecoder();\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) {\n return;\n }\n for (const payload of frames.push(text.decode(value, { stream: true }))) {\n yield parseCrawlEvent(payload);\n }\n }\n } finally {\n // Never let a teardown failure mask the error that caused the teardown.\n await reader.cancel().catch(() => undefined);\n }\n}\n\n/** Backwards-compatible factory returning the low-level `openapi-fetch` client. */\nexport interface CreateClientOptions {\n baseUrl: string;\n apiKey?: string;\n headers?: Record<string, string>;\n fetch?: typeof fetch;\n}\n\nexport function createClient(options: CreateClientOptions): XbergRawClient {\n const headers: Record<string, string> = {\n \"User-Agent\": USER_AGENT,\n ...options.headers,\n };\n if (options.apiKey !== undefined) {\n headers[\"Authorization\"] = `Bearer ${options.apiKey}`;\n }\n return createOpenApiClient<paths>({\n baseUrl: resolveBaseUrl(options.baseUrl, undefined),\n headers,\n ...(options.fetch !== undefined ? { fetch: options.fetch } : {}),\n });\n}\n\nfunction sandboxForm(params: PublicSandboxExtractParams): FormData {\n if (params.file === undefined && !(params.mode === \"web\" && params.url !== undefined && params.url.length > 0)) {\n throw new XbergError(\"Sandbox extraction requires a file or web mode with a URL\", { status: 400, body: null });\n }\n const form = new FormData();\n if (params.file !== undefined) {\n const { blob, filename } = toBlob(params.file);\n form.append(\"file\", blob, filename);\n }\n for (const name of [\"mode\", \"preset\", \"url\"] as const) {\n const value = params[name];\n if (value !== undefined) form.append(name, value);\n }\n return form;\n}\n\nfunction prepareDocumentLineage(\n filenames: readonly string[],\n ids: readonly (string | null)[] | undefined,\n): Map<string, string> {\n const fields = new Map<string, string>();\n if (ids === undefined) return fields;\n if (ids.length !== filenames.length)\n throw new XbergError(\"documentIds must contain one entry per file\", { status: 400, body: null });\n const seen = new Map<string, string | null>();\n for (const [index, filename] of filenames.entries()) {\n const id = ids[index];\n if (\n id !== null &&\n (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))\n ) {\n throw new XbergError(\"documentIds must contain UUID strings or null\", { status: 400, body: null });\n }\n const canonical = id === null ? null : id.toLowerCase();\n if (seen.has(filename) && seen.get(filename) !== canonical)\n throw new XbergError(\"Conflicting document IDs for the same filename\", { status: 400, body: null });\n seen.set(filename, canonical);\n if (canonical !== null) fields.set(filename, canonical);\n }\n return fields;\n}\n","/**\n * Verification of the `X-Webhook-Signature` header on webhook deliveries.\n *\n * The header is `t=<unix seconds>,v1=<hex HMAC-SHA256(secret, \"<t>.<body>\")>`.\n * Uses WebCrypto (`globalThis.crypto.subtle`) rather than `node:crypto`, so the\n * same code runs on Node, Deno, Bun, edge runtimes and browsers.\n */\n\n/** The request header that carries the signature. */\nexport const WEBHOOK_SIGNATURE_HEADER = \"X-Webhook-Signature\";\n\n/** Default replay window, in seconds, matching the server's. */\nexport const DEFAULT_WEBHOOK_TOLERANCE_SECONDS = 300;\n\nexport interface VerifyWebhookSignatureOptions {\n /** How far `t` may sit from `now` before the delivery is rejected. Default 300. */\n toleranceSeconds?: number;\n /** The receiver's clock in unix seconds. Defaults to the current time. */\n now?: number;\n}\n\nconst encoder = new TextEncoder();\n\n/**\n * Verify a webhook delivery's `X-Webhook-Signature` header against its raw body.\n *\n * Resolves `true` only when `t` is within `toleranceSeconds` of `now` and some\n * `v1` element is the HMAC-SHA256 of `\"<t>.<body>\"` under `secret`. Every `v1`\n * element is tried, so a sender signing with two secrets during a rotation\n * still verifies. The digest comparison is constant-time (`crypto.subtle.verify`).\n *\n * Pass the body exactly as received — re-serialising parsed JSON changes the\n * bytes and fails verification.\n */\nexport async function verifyWebhookSignature(\n secret: string,\n header: string,\n body: string | Uint8Array,\n options: VerifyWebhookSignatureOptions = {},\n): Promise<boolean> {\n const tolerance = options.toleranceSeconds ?? DEFAULT_WEBHOOK_TOLERANCE_SECONDS;\n const now = options.now ?? Math.floor(Date.now() / 1000);\n\n let timestamp: number | undefined;\n const candidates: string[] = [];\n for (const element of header.split(\",\")) {\n const trimmed = element.trim();\n const eq = trimmed.indexOf(\"=\");\n if (eq === -1) {\n continue;\n }\n const key = trimmed.slice(0, eq);\n const value = trimmed.slice(eq + 1);\n if (key === \"t\") {\n timestamp = /^[+-]?\\d+$/.test(value) ? Number(value) : undefined;\n } else if (key === \"v1\") {\n candidates.push(value);\n }\n }\n\n if (timestamp === undefined || !Number.isSafeInteger(timestamp) || candidates.length === 0) {\n return false;\n }\n if (!(Math.abs(now - timestamp) <= tolerance)) {\n return false;\n }\n\n const key = await crypto.subtle.importKey(\"raw\", encoder.encode(secret), { name: \"HMAC\", hash: \"SHA-256\" }, false, [\n \"verify\",\n ]);\n const prefix = encoder.encode(`${timestamp}.`);\n const bodyBytes = typeof body === \"string\" ? encoder.encode(body) : body;\n const signed = new Uint8Array(prefix.length + bodyBytes.length);\n signed.set(prefix, 0);\n signed.set(bodyBytes, prefix.length);\n\n for (const candidate of candidates) {\n const expected = decodeHex(candidate);\n if (expected !== undefined && (await crypto.subtle.verify(\"HMAC\", key, expected, signed))) {\n return true;\n }\n }\n return false;\n}\n\nfunction decodeHex(value: string): Uint8Array<ArrayBuffer> | undefined {\n if (value.length === 0 || value.length % 2 !== 0 || !/^[0-9a-fA-F]+$/.test(value)) {\n return undefined;\n }\n const bytes = new Uint8Array(value.length / 2);\n for (let index = 0; index < bytes.length; index += 1) {\n bytes[index] = Number.parseInt(value.slice(index * 2, index * 2 + 2), 16);\n }\n return bytes;\n}\n"],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