@xemahq/api-client-generator 1.1.2 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
  {
2
2
  "algorithm": "sha256/len-framed-v1",
3
- "hash": "a53dc767152be4b941240bf90059c728f7bd113751da0df7e8bfe2ee8be2f1b7",
3
+ "hash": "677c8e4cd5526a675f69343740c1b1f55e14c7af03ca7c3e4266466de91711b1",
4
4
  "fileCount": 22
5
5
  }
@@ -1,2 +1,2 @@
1
- export declare const CANONICAL_CUSTOM_FETCH = "/**\n * Configurable fetch wrapper for Orval-generated clients.\n *\n * GENERATED by `@xemahq/api-client-generator` \u2014 do not edit. Every client in\n * the fleet ships this file byte-for-byte; a local edit is erased by the next\n * `pnpm refresh` and, until then, makes this one client speak to the platform\n * differently from all of its siblings. Change the template instead:\n * `api-client-generator/src/lib/custom-fetch-template.ts`.\n *\n * Consumers must call `configureClient()` before using any endpoint function.\n * The baseUrl is prepended to the relative paths generated by Orval.\n *\n * By default this transport issues exactly ONE request and adds no delay of its\n * own, so a slow call is a slow server. Retrying is opt-in, and opting in\n * requires supplying an observer \u2014 see `maxRetries` / `onRetry` below.\n */\n\n/** What {@link ClientConfig.onRetry} is told before each re-attempt. */\nexport interface RetryNotice {\n /** 1-based index of the re-attempt about to be made. */\n attempt: number;\n /** The configured budget this re-attempt is spending from. */\n maxRetries: number;\n /** The response status that made the previous attempt retryable. */\n status: number;\n /** Delay before the re-attempt, in ms \u2014 from `Retry-After` when the server sent one. */\n waitMs: number;\n /** Whether {@link waitMs} came from the server's `Retry-After` header. */\n retryAfterHonoured: boolean;\n /** Absolute URL being re-requested. */\n url: string;\n /** HTTP method being re-requested. */\n method: string;\n}\n\nexport interface ClientConfig {\n /**\n * Static base URL (e.g. 'http://localhost:3140') \u2014 no trailing slash.\n * Mutually exclusive with `baseUrlResolver`; exactly one MUST be set.\n */\n baseUrl?: string;\n /**\n * Per-request base-URL resolver. When set, the peer URL is resolved from\n * the service registry on EVERY request (boot-order-safe). Wired by\n * `configureOrvalClientResolved` from `@xemahq/platform-common`.\n */\n baseUrlResolver?: () => string | Promise<string>;\n /** Optional async callback to get an auth token. Auto-sets Authorization header on every request. */\n getAuthToken?: () => Promise<string>;\n /** Optional callback returning headers to inject on every request. Per-call headers take precedence. */\n getHeaders?: () => Record<string, string> | Promise<Record<string, string>>;\n /**\n * Optional resolver for the CORRELATION ID of the request being made \u2014 the\n * handle that ties one causal chain together across every service hop.\n *\n * WHY IT IS A CALLBACK AND NOT A VALUE. `ClientConfig` is process-global\n * (`configureClient` is called once at wiring time), and a correlation id is\n * per-request. This is invoked INSIDE the request, so a server can point it\n * at whatever carries its ambient request context and get the CURRENT id\n * rather than the one that happened to be live at boot.\n *\n * WHY THE TRANSPORT DOES NOT MINT ONE. Returning `undefined` sends no header,\n * and the receiving service's `RequestContextMiddleware` mints its own \u2014 a\n * new trace, which is honest. A transport that minted per call would produce\n * a FRESH id on every hop while looking like propagation, which is strictly\n * worse than none: every row would carry a correlation id and no two rows\n * that belong together would share one. That is the exact defect this exists\n * to fix, so the transport must not reproduce it one layer down.\n *\n * A caller-supplied `X-Correlation-Id` header always wins, and so does one\n * from `getHeaders`.\n */\n getCorrelationId?: () =>\n | string\n | undefined\n | Promise<string | undefined>;\n /**\n * Optional callback invoked on a 401 before ONE re-attempt. Supplying it is\n * what opts this client into that re-attempt; without it a 401 comes back to\n * the caller as a `ClientError` like any other 4xx.\n */\n onUnauthorized?: () => Promise<void>;\n /**\n * Re-attempts for a retryable status. **Defaults to 0 \u2014 no retry.**\n *\n * Setting it above 0 REQUIRES `onRetry`; `configureClient` throws otherwise.\n * See the block above `customFetch` for why the budget is opt-in and why an\n * observer is mandatory rather than advisory.\n */\n maxRetries?: number;\n /**\n * Called immediately before every re-attempt, with the reason and the delay.\n *\n * Mandatory whenever `maxRetries` is above 0. It is the difference between a\n * retry and a hidden degradation path: without it a caller cannot tell a slow\n * server from this transport sleeping between attempts.\n */\n onRetry?: (notice: RetryNotice) => void;\n}\n\n/**\n * Cross-package identity for `ClientError`.\n *\n * \u2500\u2500 THE OUTAGE THIS IS FOR \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n *\n * PRODUCTION, 2026-09-22. A session launch aborted on\n * `HTTP 503 from http://skill-registry-api\u2026/skills`. A 503 is the archetypal\n * TRANSIENT \u2014 agent-session's launch taxonomy already listed it as retryable \u2014\n * but it was classified PERMANENT and the launch was abandoned.\n *\n * The cause was this file. Every generated client package gets its OWN copy of\n * `ClientError`, so there are as many classes as there are clients (81 at the\n * time of writing), all byte-identical and all DIFFERENT OBJECTS. A consumer\n * naturally writes `err instanceof ClientError` against the one client it\n * imported \u2014 which reads as obviously correct and is silently package-local. An\n * error from any OTHER client fails it, falls past every status check, and lands\n * on whatever the default is.\n *\n * That was not the first time: biome-host had already switched to structural\n * detection for the same reason, and canopy imports TWO `ClientError` classes\n * and tests both. Three more call sites elsewhere carry the same shape.\n *\n * \u2500\u2500 WHY A BRAND AND NOT A SHARED PACKAGE \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n *\n * The obvious fix is one shared runtime class every client imports. It was\n * rejected on measurement: the 81 generated clients are DEPENDENCY-FREE by\n * design (exactly one has any dependency at all), and a shared class would have\n * to be a PEER dependency to be safe \u2014 a normal dependency can be installed\n * twice under version skew, which reinstates this identical bug in a form that\n * is HARDER to see, because the classes then look like they ought to match.\n *\n * `Symbol.for` is a process-wide registry keyed by STRING, so every copy of\n * this template resolves the same symbol without importing anything. The brand\n * costs no dependency, cannot skew, and needs no new package.\n *\n * `Symbol.hasInstance` then makes plain `instanceof` mean the right thing\n * fleet-wide: an error from ANY generated client satisfies `instanceof\n * ClientError` in ANY other. A helper would have made the safe pattern\n * available; this makes the dangerous pattern impossible.\n *\n * Narrow on purpose \u2014 the brand is set only by this constructor, so an unrelated\n * error carrying a `status` is not admitted.\n */\nconst CLIENT_ERROR_BRAND: unique symbol = Symbol.for(\n 'xema.generatedClientError',\n) as never;\n\nexport class ClientError extends Error {\n constructor(\n public readonly status: number,\n public readonly url: string,\n public readonly body: unknown,\n ) {\n super(`HTTP ${status} from ${url}`);\n this.name = 'ClientError';\n // Non-enumerable: it must not appear in JSON, logs or snapshots \u2014 it is an\n // identity marker, not payload.\n Object.defineProperty(this, CLIENT_ERROR_BRAND, { value: true });\n }\n\n static [Symbol.hasInstance](candidate: unknown): boolean {\n return (\n typeof candidate === 'object' &&\n candidate !== null &&\n CLIENT_ERROR_BRAND in candidate\n );\n }\n}\n\nlet clientConfig: ClientConfig | null = null;\n\nexport function configureClient(config: ClientConfig): void {\n // Fail at WIRING time, not on the request that happens to be retried. A\n // client configured to retry without an observer is the exact defect this\n // transport was rebuilt to remove, so it must not be constructible.\n if ((config.maxRetries ?? 0) > 0 && !config.onRetry) {\n throw new Error(\n 'configureClient: maxRetries above 0 requires onRetry. A retry nothing ' +\n 'reports is indistinguishable from a slow server, which is how two ' +\n 'silent re-attempts were read as a 3,312ms call.',\n );\n }\n clientConfig = config;\n}\n\nexport function getClientConfig(): ClientConfig {\n if (!clientConfig) {\n throw new Error(\n 'Client not configured. Call configureClient({ baseUrl }) before using endpoint functions.',\n );\n }\n return clientConfig;\n}\n\n/*\n * RETRYING IS OPT-IN, OBSERVED, AND NARROW. Do not widen any of the three.\n *\n * This transport used to retry up to `maxRetries` (defaulting to THREE) over\n * 429/502/503/504 AND over any thrown network error, backing off from 1000ms,\n * with no log line anywhere. Three properties were wrong:\n *\n * 1. The DEFAULT was on. ~99% of the fleet's client configurations never\n * mention `maxRetries`, so two re-attempts could add ~3s to any call with\n * nothing to distinguish that from a slow peer. Every caller that DID set\n * it set it LOWER \u2014 canopy's control plane to 1, \"so a hard outage\n * surfaces inside the turn's latency budget rather than after three\n * backoffs\"; two llm-registry callers to 1; a test to 0. Nobody ever\n * raised it. A default three separate call sites work around is not a\n * default, and `configureOrvalClientResolved` cannot express the field at\n * all, so most callers could not have opted out if they had wanted to.\n * 2. It retried AMBIGUOUS failures. 502 and 504 mean a gateway did not get a\n * timely answer from upstream \u2014 the upstream may well have APPLIED the\n * request. So did a thrown network error mid-flight. Re-sending a POST in\n * either case is a duplicate write, and no amount of logging makes that\n * safe. Only 429 and 503 state positively that the request was NOT\n * processed, so only those are retried; everything else surfaces at once.\n * 3. Nothing reported it. Now `onRetry` is mandatory whenever the budget is\n * above 0, enforced in `configureClient`.\n *\n * Also note `baseUrlResolver` is awaited ONCE, above the loop: a re-attempt\n * returns to the same resolved instance. In a registry-resolved fleet the cure\n * for an unhealthy peer is re-resolution, which lives above this file \u2014 which\n * is a further reason not to lean on retrying here.\n *\n * Retry policy a caller genuinely wants belongs in `@xemahq/managed-fetch`,\n * which has backoff, a circuit breaker, a token bucket and health reporting,\n * and reports what it did.\n *\n * Enforced fleet-wide by `check-client-transport-envelope`, which compares\n * every client's transport to this template.\n */\n\n/** The only statuses that state the request was NOT processed. See above. */\nconst RETRYABLE_STATUSES = [429, 503];\n\n/**\n * The platform's correlation header, spelled once.\n *\n * Value-identical to what `RequestContextMiddleware` reads in\n * `@xemahq/platform-common`. It is a literal here rather than an import\n * because this file has ZERO imports on purpose: it ships byte-identical into\n * browser-target clients as well as server-target ones, and a dependency on a\n * NestJS-peer package would follow it into every one of them.\n */\nconst CORRELATION_ID_HEADER = 'X-Correlation-Id';\n\n/** Backoff floor, doubling per attempt up to {@link MAX_BACKOFF_MS}. */\nconst BASE_BACKOFF_MS = 1000;\n\n/** Ceiling on a single backoff, however many attempts have elapsed. */\nconst MAX_BACKOFF_MS = 30_000;\n\nasync function buildHeaders(\n config: ClientConfig,\n callerHeaders: RequestInit['headers'],\n): Promise<Headers> {\n const headers = new Headers(callerHeaders);\n\n // Global headers from config (caller-provided headers take precedence)\n if (config.getHeaders) {\n const globalHeaders = await Promise.resolve(config.getHeaders());\n for (const [key, value] of Object.entries(globalHeaders)) {\n if (!headers.has(key)) {\n headers.set(key, value);\n }\n }\n }\n\n // Correlation id (caller and global headers still take precedence).\n //\n // Without this, every server-to-server hop through a generated client started\n // a NEW trace: the id is read-or-minted per hop by the receiving service's\n // RequestContextMiddleware, and nothing carried it outbound \u2014 so an audit\n // journal could record a whole causal chain and offer no way to join it back\n // together.\n //\n // Absent resolver, or a resolver that answers `undefined`: NO header. The\n // receiver mints and a new trace begins, which is the truthful outcome when\n // there is nothing to continue.\n if (config.getCorrelationId && !headers.has(CORRELATION_ID_HEADER)) {\n const correlationId = await Promise.resolve(config.getCorrelationId());\n if (correlationId) {\n headers.set(CORRELATION_ID_HEADER, correlationId);\n }\n }\n\n // Auth token (caller or global headers take precedence)\n if (config.getAuthToken && !headers.has('Authorization')) {\n const token = await config.getAuthToken();\n headers.set('Authorization', `Bearer ${token}`);\n }\n\n return headers;\n}\n\n/*\n * THE TRANSPORT RETURNS THE BODY UNCHANGED. Do not reintroduce an unwrap here.\n *\n * Xema services wrap every 2xx payload in a { data: T } envelope via the global\n * ResponseEnvelopeInterceptor (platform-common), and the generator emits types\n * that describe THAT ENVELOPE \u2014 every endpoint returns Promise<XDataEnvelope>\n * or Promise<XPaginatedEnvelope>, never a bare inner T. Consumers read the data\n * property themselves.\n *\n * This template used to peel data, justified by a comment claiming generated\n * types describe the inner T. That stopped being true when the generator moved\n * to envelope-typed returns, and the comment outlived the fact \u2014 so the peel\n * then contradicted every type in every package it seeded. Four clients shipped\n * that way (resource-governance x3, workload-runtime-api): declared\n * *DataEnvelope, returned the already-peeled inner object, so .data read\n * undefined at runtime on every non-paginated endpoint. Paginated calls hid it,\n * because the old peel deliberately preserved an envelope carrying pagination.\n *\n * Four MORE shipped it in repositories the gate could not see \u2014 license-api and\n * license-internal-api in xema-operator, plus their host-web mirrors \u2014 because\n * the gate ran in xema-base only. That is why it now runs in every repository\n * that ships a client, and why this file is generator-owned rather than seeded.\n */\n\nexport const customFetch = async <T>(\n url: string,\n options: RequestInit,\n): Promise<T> => {\n const config = getClientConfig();\n const base = config.baseUrlResolver\n ? await config.baseUrlResolver()\n : config.baseUrl;\n if (base === undefined) {\n throw new Error(\n 'Client not configured: set baseUrl or baseUrlResolver via configureClient().',\n );\n }\n const fullUrl = `${base}${url}`;\n const maxRetries = config.maxRetries ?? 0;\n\n // A caller that supplied its own Authorization header owns that credential.\n // `buildHeaders` lets it win, so refreshing the CLIENT-WIDE token and\n // re-sending would replay the identical failing request with the identical\n // credential: one wasted round trip, plus a global refresh nobody asked for.\n const callerSuppliedAuth = new Headers(options.headers).has('Authorization');\n\n const headers = await buildHeaders(config, options.headers);\n const requestInit: RequestInit = { ...options, headers };\n\n let delay = BASE_BACKOFF_MS;\n\n for (let attempt = 0; ; attempt++) {\n const response = await fetch(fullUrl, requestInit);\n\n if (\n response.status === 401 &&\n config.onUnauthorized &&\n !callerSuppliedAuth &&\n attempt === 0\n ) {\n await config.onUnauthorized();\n const refreshedHeaders = await buildHeaders(config, options.headers);\n const retryResponse = await fetch(fullUrl, {\n ...options,\n headers: refreshedHeaders,\n });\n const retryBody = await parseBody(retryResponse);\n if (retryResponse.status >= 400) {\n throw new ClientError(retryResponse.status, fullUrl, retryBody);\n }\n return retryBody as T;\n }\n\n if (\n !RETRYABLE_STATUSES.includes(response.status) ||\n attempt >= maxRetries\n ) {\n const body = await parseBody(response);\n if (response.status >= 400) {\n throw new ClientError(response.status, fullUrl, body);\n }\n return body as T;\n }\n\n const retryAfter = parseRetryAfter(response.headers.get('Retry-After'));\n const waitMs = retryAfter ?? addJitter(delay);\n // Non-null: `configureClient` refuses a budget above 0 without an observer,\n // and this line is unreachable unless `maxRetries` is above 0.\n (config.onRetry as (notice: RetryNotice) => void)({\n attempt: attempt + 1,\n maxRetries,\n status: response.status,\n waitMs,\n retryAfterHonoured: retryAfter !== undefined,\n url: fullUrl,\n method: options.method ?? 'GET',\n });\n await sleep(waitMs);\n delay = Math.min(delay * 2, MAX_BACKOFF_MS);\n }\n};\n\n/**\n * Does this media type carry JSON?\n *\n * \u2500\u2500 THE OUTAGE THIS FIXES \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n *\n * This used to be `contentType?.includes('application/json')`, and EVERY error\n * this fleet returns failed that test. The platform's `GlobalExceptionFilter`\n * emits RFC 9457 problem documents and sets the media type explicitly \u2014\n * `.type(PROBLEM_DETAILS_CONTENT_TYPE)` before `.json()`, so it cannot be\n * overridden \u2014 and that constant is `application/problem+json`, which does NOT\n * contain the substring `application/json`: after `application/` comes\n * `problem+json`.\n *\n * So every non-2xx body fell through to `response.text()` and reached the\n * caller as an UNPARSED STRING. `ClientError.body` is typed `unknown`, so\n * nothing complained; every consumer that reads a machine-readable code off an\n * error \u2014 `error.body.code`, `error.body.details.code` \u2014 silently read\n * `undefined` instead, for every error, in every service.\n *\n * Measured in production on 2026-09-15: skill-registry-api's\n * `resolveOrNull()` absorbs `RELEASE_CHANNEL_NOT_FOUND` into `null` by exactly\n * that read. With the code unreadable the absorb never fired, a routine \"no\n * pointer on this channel\" 404 became a 500 on `GET /skills` and\n * `GET /describe-objects`, and agent-session-api's `apply_control_bundle` step\n * aborted EVERY session launch in the organisation \u2014 7,871 failed resolutions\n * an hour. A fix written for that exact page months earlier was present in the\n * running image and could not help, because the classifier it repaired was\n * being handed a string.\n *\n * \u2500\u2500 WHY THE STRUCTURED SUFFIX, NOT A SECOND SUBSTRING \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n *\n * Adding `|| includes('application/problem+json')` would fix this one media\n * type and leave the next one \u2014 `application/vnd.api+json`, and anything else\n * a service legitimately emits. RFC 6839 defines `+json` as the structured\n * syntax suffix meaning \"this is JSON\"; that is the actual rule, so it is the\n * rule implemented. Parameters are stripped first, because\n * `application/problem+json; charset=utf-8` is the same media type.\n */\nfunction isJsonMediaType(contentType: string | null): boolean {\n if (contentType === null) {\n return false;\n }\n const essence = contentType.split(';')[0]?.trim().toLowerCase() ?? '';\n return essence === 'application/json' || essence.endsWith('+json');\n}\n\nasync function parseBody(response: Response): Promise<unknown> {\n // 204 FIRST, and deliberately \u2014 this ORDER is carried from `develop`, which\n // fixed the same defect independently and got this half right where `main`\n // did not. A 204 carries no body, so `response.json()` on one throws\n // SyntaxError; and a 204 whose headers STILL declare a JSON content type is\n // ordinary, because the framework sets the header before the handler returns\n // nothing. With the JSON branch first, a documented `undefined` becomes a\n // thrown parse error. Pinned by a case in `transport-problem-json.test.cjs`.\n if (response.status === 204) {\n return undefined;\n }\n const contentType = response.headers.get('content-type');\n if (isJsonMediaType(contentType)) {\n return response.json();\n }\n return response.text();\n}\n\nfunction parseRetryAfter(value: string | null): number | undefined {\n if (!value) return undefined;\n const seconds = Number(value);\n if (!isNaN(seconds) && seconds >= 0) return seconds * 1000;\n const date = new Date(value);\n if (!isNaN(date.getTime())) return Math.max(0, date.getTime() - Date.now());\n return undefined;\n}\n\nfunction addJitter(delay: number): number {\n return delay + (Math.random() * 2 - 1) * delay * 0.25;\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nexport default customFetch;\n";
1
+ export declare const CANONICAL_CUSTOM_FETCH = "/**\n * Configurable fetch wrapper for Orval-generated clients.\n *\n * GENERATED by `@xemahq/api-client-generator` \u2014 do not edit. Every client in\n * the fleet ships this file byte-for-byte; a local edit is erased by the next\n * `pnpm refresh` and, until then, makes this one client speak to the platform\n * differently from all of its siblings. Change the template instead:\n * `api-client-generator/src/lib/custom-fetch-template.ts`.\n *\n * Consumers must call `configureClient()` before using any endpoint function.\n * The baseUrl is prepended to the relative paths generated by Orval.\n *\n * By default this transport issues exactly ONE request and adds no delay of its\n * own, so a slow call is a slow server. Retrying is opt-in, and opting in\n * requires supplying an observer \u2014 see `maxRetries` / `onRetry` below.\n */\n\n/** What {@link ClientConfig.onRetry} is told before each re-attempt. */\nexport interface RetryNotice {\n /** 1-based index of the re-attempt about to be made. */\n attempt: number;\n /** The configured budget this re-attempt is spending from. */\n maxRetries: number;\n /** The response status that made the previous attempt retryable. */\n status: number;\n /** Delay before the re-attempt, in ms \u2014 from `Retry-After` when the server sent one. */\n waitMs: number;\n /** Whether {@link waitMs} came from the server's `Retry-After` header. */\n retryAfterHonoured: boolean;\n /** Absolute URL being re-requested. */\n url: string;\n /** HTTP method being re-requested. */\n method: string;\n}\n\n/**\n * Per-request context handed to the callbacks this transport awaits BEFORE it\n * sends the request.\n *\n * `signal` is the request's own `AbortSignal` (`options.signal`). It is the\n * CALLER's cancellation: a callback may use it to stop work that is private to\n * this request, but a callback serving several requests from one shared,\n * single-flight acquisition (a token refresh) must NOT abort that shared work\n * because one caller stopped \u2014 every other caller waiting on it would fail.\n * The transport stops WAITING on its own regardless, so a callback that\n * ignores the signal still cannot hold an aborted request.\n */\nexport interface ClientCallbackOptions {\n signal?: AbortSignal;\n}\n\nexport interface ClientConfig {\n /**\n * Static base URL (e.g. 'http://localhost:3140') \u2014 no trailing slash.\n * Mutually exclusive with `baseUrlResolver`; exactly one MUST be set.\n */\n baseUrl?: string;\n /**\n * Per-request base-URL resolver. When set, the peer URL is resolved from\n * the service registry on EVERY request (boot-order-safe). Wired by\n * `configureOrvalClientResolved` from `@xemahq/platform-common`.\n */\n baseUrlResolver?: (\n options?: ClientCallbackOptions,\n ) => string | Promise<string>;\n /**\n * Optional async callback to get an auth token. Auto-sets Authorization\n * header on every request. Receives the request's signal \u2014 see\n * {@link ClientCallbackOptions} for what it may and may not abort.\n */\n getAuthToken?: (options?: ClientCallbackOptions) => Promise<string>;\n /** Optional callback returning headers to inject on every request. Per-call headers take precedence. */\n getHeaders?: () => Record<string, string> | Promise<Record<string, string>>;\n /**\n * Optional resolver for the CORRELATION ID of the request being made \u2014 the\n * handle that ties one causal chain together across every service hop.\n *\n * WHY IT IS A CALLBACK AND NOT A VALUE. `ClientConfig` is process-global\n * (`configureClient` is called once at wiring time), and a correlation id is\n * per-request. This is invoked INSIDE the request, so a server can point it\n * at whatever carries its ambient request context and get the CURRENT id\n * rather than the one that happened to be live at boot.\n *\n * WHY THE TRANSPORT DOES NOT MINT ONE. Returning `undefined` sends no header,\n * and the receiving service's `RequestContextMiddleware` mints its own \u2014 a\n * new trace, which is honest. A transport that minted per call would produce\n * a FRESH id on every hop while looking like propagation, which is strictly\n * worse than none: every row would carry a correlation id and no two rows\n * that belong together would share one. That is the exact defect this exists\n * to fix, so the transport must not reproduce it one layer down.\n *\n * A caller-supplied `X-Correlation-Id` header always wins, and so does one\n * from `getHeaders`.\n */\n getCorrelationId?: () =>\n | string\n | undefined\n | Promise<string | undefined>;\n /**\n * Optional callback invoked on a 401 before ONE re-attempt. Supplying it is\n * what opts this client into that re-attempt; without it a 401 comes back to\n * the caller as a `ClientError` like any other 4xx.\n */\n onUnauthorized?: () => Promise<void>;\n /**\n * Re-attempts for a retryable status. **Defaults to 0 \u2014 no retry.**\n *\n * Setting it above 0 REQUIRES `onRetry`; `configureClient` throws otherwise.\n * See the block above `customFetch` for why the budget is opt-in and why an\n * observer is mandatory rather than advisory.\n */\n maxRetries?: number;\n /**\n * Called immediately before every re-attempt, with the reason and the delay.\n *\n * Mandatory whenever `maxRetries` is above 0. It is the difference between a\n * retry and a hidden degradation path: without it a caller cannot tell a slow\n * server from this transport sleeping between attempts.\n */\n onRetry?: (notice: RetryNotice) => void;\n}\n\n/**\n * Cross-package identity for `ClientError`.\n *\n * \u2500\u2500 THE OUTAGE THIS IS FOR \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n *\n * PRODUCTION, 2026-09-22. A session launch aborted on\n * `HTTP 503 from http://skill-registry-api\u2026/skills`. A 503 is the archetypal\n * TRANSIENT \u2014 agent-session's launch taxonomy already listed it as retryable \u2014\n * but it was classified PERMANENT and the launch was abandoned.\n *\n * The cause was this file. Every generated client package gets its OWN copy of\n * `ClientError`, so there are as many classes as there are clients (81 at the\n * time of writing), all byte-identical and all DIFFERENT OBJECTS. A consumer\n * naturally writes `err instanceof ClientError` against the one client it\n * imported \u2014 which reads as obviously correct and is silently package-local. An\n * error from any OTHER client fails it, falls past every status check, and lands\n * on whatever the default is.\n *\n * That was not the first time: biome-host had already switched to structural\n * detection for the same reason, and canopy imports TWO `ClientError` classes\n * and tests both. Three more call sites elsewhere carry the same shape.\n *\n * \u2500\u2500 WHY A BRAND AND NOT A SHARED PACKAGE \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n *\n * The obvious fix is one shared runtime class every client imports. It was\n * rejected on measurement: the 81 generated clients are DEPENDENCY-FREE by\n * design (exactly one has any dependency at all), and a shared class would have\n * to be a PEER dependency to be safe \u2014 a normal dependency can be installed\n * twice under version skew, which reinstates this identical bug in a form that\n * is HARDER to see, because the classes then look like they ought to match.\n *\n * `Symbol.for` is a process-wide registry keyed by STRING, so every copy of\n * this template resolves the same symbol without importing anything. The brand\n * costs no dependency, cannot skew, and needs no new package.\n *\n * `Symbol.hasInstance` then makes plain `instanceof` mean the right thing\n * fleet-wide: an error from ANY generated client satisfies `instanceof\n * ClientError` in ANY other. A helper would have made the safe pattern\n * available; this makes the dangerous pattern impossible.\n *\n * Narrow on purpose \u2014 the brand is set only by this constructor, so an unrelated\n * error carrying a `status` is not admitted.\n */\nconst CLIENT_ERROR_BRAND: unique symbol = Symbol.for(\n 'xema.generatedClientError',\n) as never;\n\nexport class ClientError extends Error {\n constructor(\n public readonly status: number,\n public readonly url: string,\n public readonly body: unknown,\n ) {\n super(`HTTP ${status} from ${url}`);\n this.name = 'ClientError';\n // Non-enumerable: it must not appear in JSON, logs or snapshots \u2014 it is an\n // identity marker, not payload.\n Object.defineProperty(this, CLIENT_ERROR_BRAND, { value: true });\n }\n\n static [Symbol.hasInstance](candidate: unknown): boolean {\n return (\n typeof candidate === 'object' &&\n candidate !== null &&\n CLIENT_ERROR_BRAND in candidate\n );\n }\n}\n\nlet clientConfig: ClientConfig | null = null;\n\nexport function configureClient(config: ClientConfig): void {\n // Fail at WIRING time, not on the request that happens to be retried. A\n // client configured to retry without an observer is the exact defect this\n // transport was rebuilt to remove, so it must not be constructible.\n if ((config.maxRetries ?? 0) > 0 && !config.onRetry) {\n throw new Error(\n 'configureClient: maxRetries above 0 requires onRetry. A retry nothing ' +\n 'reports is indistinguishable from a slow server, which is how two ' +\n 'silent re-attempts were read as a 3,312ms call.',\n );\n }\n clientConfig = config;\n}\n\nexport function getClientConfig(): ClientConfig {\n if (!clientConfig) {\n throw new Error(\n 'Client not configured. Call configureClient({ baseUrl }) before using endpoint functions.',\n );\n }\n return clientConfig;\n}\n\n/*\n * RETRYING IS OPT-IN, OBSERVED, AND NARROW. Do not widen any of the three.\n *\n * This transport used to retry up to `maxRetries` (defaulting to THREE) over\n * 429/502/503/504 AND over any thrown network error, backing off from 1000ms,\n * with no log line anywhere. Three properties were wrong:\n *\n * 1. The DEFAULT was on. ~99% of the fleet's client configurations never\n * mention `maxRetries`, so two re-attempts could add ~3s to any call with\n * nothing to distinguish that from a slow peer. Every caller that DID set\n * it set it LOWER \u2014 canopy's control plane to 1, \"so a hard outage\n * surfaces inside the turn's latency budget rather than after three\n * backoffs\"; two llm-registry callers to 1; a test to 0. Nobody ever\n * raised it. A default three separate call sites work around is not a\n * default, and `configureOrvalClientResolved` cannot express the field at\n * all, so most callers could not have opted out if they had wanted to.\n * 2. It retried AMBIGUOUS failures. 502 and 504 mean a gateway did not get a\n * timely answer from upstream \u2014 the upstream may well have APPLIED the\n * request. So did a thrown network error mid-flight. Re-sending a POST in\n * either case is a duplicate write, and no amount of logging makes that\n * safe. Only 429 and 503 state positively that the request was NOT\n * processed, so only those are retried; everything else surfaces at once.\n * 3. Nothing reported it. Now `onRetry` is mandatory whenever the budget is\n * above 0, enforced in `configureClient`.\n *\n * Also note `baseUrlResolver` is awaited ONCE, above the loop: a re-attempt\n * returns to the same resolved instance. In a registry-resolved fleet the cure\n * for an unhealthy peer is re-resolution, which lives above this file \u2014 which\n * is a further reason not to lean on retrying here.\n *\n * Retry policy a caller genuinely wants belongs in `@xemahq/managed-fetch`,\n * which has backoff, a circuit breaker, a token bucket and health reporting,\n * and reports what it did.\n *\n * Enforced fleet-wide by `check-client-transport-envelope`, which compares\n * every client's transport to this template.\n */\n\n/** The only statuses that state the request was NOT processed. See above. */\nconst RETRYABLE_STATUSES = [429, 503];\n\n/**\n * The platform's correlation header, spelled once.\n *\n * Value-identical to what `RequestContextMiddleware` reads in\n * `@xemahq/platform-common`. It is a literal here rather than an import\n * because this file has ZERO imports on purpose: it ships byte-identical into\n * browser-target clients as well as server-target ones, and a dependency on a\n * NestJS-peer package would follow it into every one of them.\n */\nconst CORRELATION_ID_HEADER = 'X-Correlation-Id';\n\n/** Backoff floor, doubling per attempt up to {@link MAX_BACKOFF_MS}. */\nconst BASE_BACKOFF_MS = 1000;\n\n/** Ceiling on a single backoff, however many attempts have elapsed. */\nconst MAX_BACKOFF_MS = 30_000;\n\n/*\n * CALLER CANCELLATION REACHES EVERY WAIT BEFORE THE REQUEST IS SENT.\n *\n * `fetch` always honoured `options.signal`, but everything this transport\n * awaits BEFORE `fetch` \u2014 base-URL resolution, the header callbacks, the auth\n * token \u2014 did not, so a caller that aborted while a token was being minted sat\n * out the mint and then, at best, had its request refused. The only way to\n * cancel that wait was a process-wide interceptor aborting every outbound\n * request, which also aborts a SHARED single-flight token refresh and so fails\n * every other caller waiting on it.\n *\n * So each pre-send wait is RACED against the signal: the caller stops waiting\n * at once, and the work it was waiting on carries on for anybody else. The\n * rejection is the signal's own reason \u2014 exactly what `fetch` rejects with \u2014\n * so a caller sees ONE abort shape whenever it aborts. An aborted request is\n * never retried. Without a signal nothing here changes.\n */\nfunction abortedReason(signal: AbortSignal): unknown {\n // `abort()` with no argument sets a DOMException reason, so this is only\n // ever `undefined` for a hand-built signal; say so rather than throw it.\n return signal.reason ?? new DOMException('This operation was aborted', 'AbortError');\n}\n\nfunction throwIfAborted(signal: AbortSignal | undefined): void {\n if (signal?.aborted) {\n throw abortedReason(signal);\n }\n}\n\nfunction raceAbort<V>(\n pending: V | Promise<V>,\n signal: AbortSignal | undefined,\n): Promise<V> {\n const promise = Promise.resolve(pending);\n if (!signal) {\n return promise;\n }\n if (signal.aborted) {\n promise.catch(() => undefined);\n return Promise.reject(abortedReason(signal));\n }\n return new Promise<V>((resolve, reject) => {\n const onAbort = (): void => {\n // The pending work may be shared; it carries on, and its eventual\n // rejection must not surface as an unhandled one on this side.\n promise.catch(() => undefined);\n reject(abortedReason(signal));\n };\n signal.addEventListener('abort', onAbort, { once: true });\n promise.then(\n (value) => {\n signal.removeEventListener('abort', onAbort);\n resolve(value);\n },\n (err: unknown) => {\n signal.removeEventListener('abort', onAbort);\n reject(err);\n },\n );\n });\n}\n\nasync function buildHeaders(\n config: ClientConfig,\n callerHeaders: RequestInit['headers'],\n signal: AbortSignal | undefined,\n): Promise<Headers> {\n const headers = new Headers(callerHeaders);\n\n // Global headers from config (caller-provided headers take precedence)\n if (config.getHeaders) {\n const globalHeaders = await raceAbort(config.getHeaders(), signal);\n for (const [key, value] of Object.entries(globalHeaders)) {\n if (!headers.has(key)) {\n headers.set(key, value);\n }\n }\n }\n\n // Correlation id (caller and global headers still take precedence).\n //\n // Without this, every server-to-server hop through a generated client started\n // a NEW trace: the id is read-or-minted per hop by the receiving service's\n // RequestContextMiddleware, and nothing carried it outbound \u2014 so an audit\n // journal could record a whole causal chain and offer no way to join it back\n // together.\n //\n // Absent resolver, or a resolver that answers `undefined`: NO header. The\n // receiver mints and a new trace begins, which is the truthful outcome when\n // there is nothing to continue.\n if (config.getCorrelationId && !headers.has(CORRELATION_ID_HEADER)) {\n const correlationId = await raceAbort(config.getCorrelationId(), signal);\n if (correlationId) {\n headers.set(CORRELATION_ID_HEADER, correlationId);\n }\n }\n\n // Auth token (caller or global headers take precedence)\n if (config.getAuthToken && !headers.has('Authorization')) {\n const token = await raceAbort(\n config.getAuthToken(signal ? { signal } : undefined),\n signal,\n );\n headers.set('Authorization', `Bearer ${token}`);\n }\n\n return headers;\n}\n\n/*\n * THE TRANSPORT RETURNS THE BODY UNCHANGED. Do not reintroduce an unwrap here.\n *\n * Xema services wrap every 2xx payload in a { data: T } envelope via the global\n * ResponseEnvelopeInterceptor (platform-common), and the generator emits types\n * that describe THAT ENVELOPE \u2014 every endpoint returns Promise<XDataEnvelope>\n * or Promise<XPaginatedEnvelope>, never a bare inner T. Consumers read the data\n * property themselves.\n *\n * This template used to peel data, justified by a comment claiming generated\n * types describe the inner T. That stopped being true when the generator moved\n * to envelope-typed returns, and the comment outlived the fact \u2014 so the peel\n * then contradicted every type in every package it seeded. Four clients shipped\n * that way (resource-governance x3, workload-runtime-api): declared\n * *DataEnvelope, returned the already-peeled inner object, so .data read\n * undefined at runtime on every non-paginated endpoint. Paginated calls hid it,\n * because the old peel deliberately preserved an envelope carrying pagination.\n *\n * Four MORE shipped it in repositories the gate could not see \u2014 license-api and\n * license-internal-api in xema-operator, plus their host-web mirrors \u2014 because\n * the gate ran in xema-base only. That is why it now runs in every repository\n * that ships a client, and why this file is generator-owned rather than seeded.\n */\n\nexport const customFetch = async <T>(\n url: string,\n options: RequestInit,\n): Promise<T> => {\n const config = getClientConfig();\n const signal = options.signal ?? undefined;\n throwIfAborted(signal);\n const base = config.baseUrlResolver\n ? await raceAbort(\n config.baseUrlResolver(signal ? { signal } : undefined),\n signal,\n )\n : config.baseUrl;\n if (base === undefined) {\n throw new Error(\n 'Client not configured: set baseUrl or baseUrlResolver via configureClient().',\n );\n }\n const fullUrl = `${base}${url}`;\n const maxRetries = config.maxRetries ?? 0;\n\n // A caller that supplied its own Authorization header owns that credential.\n // `buildHeaders` lets it win, so refreshing the CLIENT-WIDE token and\n // re-sending would replay the identical failing request with the identical\n // credential: one wasted round trip, plus a global refresh nobody asked for.\n const callerSuppliedAuth = new Headers(options.headers).has('Authorization');\n\n const headers = await buildHeaders(config, options.headers, signal);\n const requestInit: RequestInit = { ...options, headers };\n\n let delay = BASE_BACKOFF_MS;\n\n for (let attempt = 0; ; attempt++) {\n const response = await fetch(fullUrl, requestInit);\n\n if (\n response.status === 401 &&\n config.onUnauthorized &&\n !callerSuppliedAuth &&\n attempt === 0\n ) {\n await raceAbort(config.onUnauthorized(), signal);\n const refreshedHeaders = await buildHeaders(\n config,\n options.headers,\n signal,\n );\n const retryResponse = await fetch(fullUrl, {\n ...options,\n headers: refreshedHeaders,\n });\n const retryBody = await parseBody(retryResponse);\n if (retryResponse.status >= 400) {\n throw new ClientError(retryResponse.status, fullUrl, retryBody);\n }\n return retryBody as T;\n }\n\n if (\n !RETRYABLE_STATUSES.includes(response.status) ||\n attempt >= maxRetries\n ) {\n const body = await parseBody(response);\n if (response.status >= 400) {\n throw new ClientError(response.status, fullUrl, body);\n }\n return body as T;\n }\n\n const retryAfter = parseRetryAfter(response.headers.get('Retry-After'));\n const waitMs = retryAfter ?? addJitter(delay);\n // Non-null: `configureClient` refuses a budget above 0 without an observer,\n // and this line is unreachable unless `maxRetries` is above 0.\n (config.onRetry as (notice: RetryNotice) => void)({\n attempt: attempt + 1,\n maxRetries,\n status: response.status,\n waitMs,\n retryAfterHonoured: retryAfter !== undefined,\n url: fullUrl,\n method: options.method ?? 'GET',\n });\n await sleep(waitMs, signal);\n delay = Math.min(delay * 2, MAX_BACKOFF_MS);\n }\n};\n\n/**\n * Does this media type carry JSON?\n *\n * \u2500\u2500 THE OUTAGE THIS FIXES \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n *\n * This used to be `contentType?.includes('application/json')`, and EVERY error\n * this fleet returns failed that test. The platform's `GlobalExceptionFilter`\n * emits RFC 9457 problem documents and sets the media type explicitly \u2014\n * `.type(PROBLEM_DETAILS_CONTENT_TYPE)` before `.json()`, so it cannot be\n * overridden \u2014 and that constant is `application/problem+json`, which does NOT\n * contain the substring `application/json`: after `application/` comes\n * `problem+json`.\n *\n * So every non-2xx body fell through to `response.text()` and reached the\n * caller as an UNPARSED STRING. `ClientError.body` is typed `unknown`, so\n * nothing complained; every consumer that reads a machine-readable code off an\n * error \u2014 `error.body.code`, `error.body.details.code` \u2014 silently read\n * `undefined` instead, for every error, in every service.\n *\n * Measured in production on 2026-09-15: skill-registry-api's\n * `resolveOrNull()` absorbs `RELEASE_CHANNEL_NOT_FOUND` into `null` by exactly\n * that read. With the code unreadable the absorb never fired, a routine \"no\n * pointer on this channel\" 404 became a 500 on `GET /skills` and\n * `GET /describe-objects`, and agent-session-api's `apply_control_bundle` step\n * aborted EVERY session launch in the organisation \u2014 7,871 failed resolutions\n * an hour. A fix written for that exact page months earlier was present in the\n * running image and could not help, because the classifier it repaired was\n * being handed a string.\n *\n * \u2500\u2500 WHY THE STRUCTURED SUFFIX, NOT A SECOND SUBSTRING \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n *\n * Adding `|| includes('application/problem+json')` would fix this one media\n * type and leave the next one \u2014 `application/vnd.api+json`, and anything else\n * a service legitimately emits. RFC 6839 defines `+json` as the structured\n * syntax suffix meaning \"this is JSON\"; that is the actual rule, so it is the\n * rule implemented. Parameters are stripped first, because\n * `application/problem+json; charset=utf-8` is the same media type.\n */\nfunction isJsonMediaType(contentType: string | null): boolean {\n if (contentType === null) {\n return false;\n }\n const essence = contentType.split(';')[0]?.trim().toLowerCase() ?? '';\n return essence === 'application/json' || essence.endsWith('+json');\n}\n\nasync function parseBody(response: Response): Promise<unknown> {\n // 204 FIRST, and deliberately \u2014 this ORDER is carried from `develop`, which\n // fixed the same defect independently and got this half right where `main`\n // did not. A 204 carries no body, so `response.json()` on one throws\n // SyntaxError; and a 204 whose headers STILL declare a JSON content type is\n // ordinary, because the framework sets the header before the handler returns\n // nothing. With the JSON branch first, a documented `undefined` becomes a\n // thrown parse error. Pinned by a case in `transport-problem-json.test.cjs`.\n if (response.status === 204) {\n return undefined;\n }\n const contentType = response.headers.get('content-type');\n if (isJsonMediaType(contentType)) {\n return response.json();\n }\n return response.text();\n}\n\nfunction parseRetryAfter(value: string | null): number | undefined {\n if (!value) return undefined;\n const seconds = Number(value);\n if (!isNaN(seconds) && seconds >= 0) return seconds * 1000;\n const date = new Date(value);\n if (!isNaN(date.getTime())) return Math.max(0, date.getTime() - Date.now());\n return undefined;\n}\n\nfunction addJitter(delay: number): number {\n return delay + (Math.random() * 2 - 1) * delay * 0.25;\n}\n\n/** A retry backoff; the caller's signal ends it at once and is never retried. */\nfunction sleep(ms: number, signal: AbortSignal | undefined): Promise<void> {\n if (!signal) {\n return new Promise((resolve) => setTimeout(resolve, ms));\n }\n if (signal.aborted) {\n return Promise.reject(abortedReason(signal));\n }\n return new Promise((resolve, reject) => {\n const onAbort = (): void => {\n clearTimeout(timer);\n reject(abortedReason(signal));\n };\n const timer = setTimeout(() => {\n signal.removeEventListener('abort', onAbort);\n resolve();\n }, ms);\n signal.addEventListener('abort', onAbort, { once: true });\n });\n}\n\nexport default customFetch;\n";
2
2
  //# sourceMappingURL=custom-fetch-template.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"custom-fetch-template.d.ts","sourceRoot":"","sources":["../../src/lib/custom-fetch-template.ts"],"names":[],"mappings":"AAcA,eAAO,MAAM,sBAAsB,gvrBA+dlC,CAAC"}
1
+ {"version":3,"file":"custom-fetch-template.d.ts","sourceRoot":"","sources":["../../src/lib/custom-fetch-template.ts"],"names":[],"mappings":"AAcA,eAAO,MAAM,sBAAsB,y2zBAilBlC,CAAC"}
@@ -36,6 +36,22 @@ export interface RetryNotice {
36
36
  method: string;
37
37
  }
38
38
 
39
+ /**
40
+ * Per-request context handed to the callbacks this transport awaits BEFORE it
41
+ * sends the request.
42
+ *
43
+ * \`signal\` is the request's own \`AbortSignal\` (\`options.signal\`). It is the
44
+ * CALLER's cancellation: a callback may use it to stop work that is private to
45
+ * this request, but a callback serving several requests from one shared,
46
+ * single-flight acquisition (a token refresh) must NOT abort that shared work
47
+ * because one caller stopped — every other caller waiting on it would fail.
48
+ * The transport stops WAITING on its own regardless, so a callback that
49
+ * ignores the signal still cannot hold an aborted request.
50
+ */
51
+ export interface ClientCallbackOptions {
52
+ signal?: AbortSignal;
53
+ }
54
+
39
55
  export interface ClientConfig {
40
56
  /**
41
57
  * Static base URL (e.g. 'http://localhost:3140') — no trailing slash.
@@ -47,9 +63,15 @@ export interface ClientConfig {
47
63
  * the service registry on EVERY request (boot-order-safe). Wired by
48
64
  * \`configureOrvalClientResolved\` from \`@xemahq/platform-common\`.
49
65
  */
50
- baseUrlResolver?: () => string | Promise<string>;
51
- /** Optional async callback to get an auth token. Auto-sets Authorization header on every request. */
52
- getAuthToken?: () => Promise<string>;
66
+ baseUrlResolver?: (
67
+ options?: ClientCallbackOptions,
68
+ ) => string | Promise<string>;
69
+ /**
70
+ * Optional async callback to get an auth token. Auto-sets Authorization
71
+ * header on every request. Receives the request's signal — see
72
+ * {@link ClientCallbackOptions} for what it may and may not abort.
73
+ */
74
+ getAuthToken?: (options?: ClientCallbackOptions) => Promise<string>;
53
75
  /** Optional callback returning headers to inject on every request. Per-call headers take precedence. */
54
76
  getHeaders?: () => Record<string, string> | Promise<Record<string, string>>;
55
77
  /**
@@ -253,15 +275,78 @@ const BASE_BACKOFF_MS = 1000;
253
275
  /** Ceiling on a single backoff, however many attempts have elapsed. */
254
276
  const MAX_BACKOFF_MS = 30_000;
255
277
 
278
+ /*
279
+ * CALLER CANCELLATION REACHES EVERY WAIT BEFORE THE REQUEST IS SENT.
280
+ *
281
+ * \`fetch\` always honoured \`options.signal\`, but everything this transport
282
+ * awaits BEFORE \`fetch\` — base-URL resolution, the header callbacks, the auth
283
+ * token — did not, so a caller that aborted while a token was being minted sat
284
+ * out the mint and then, at best, had its request refused. The only way to
285
+ * cancel that wait was a process-wide interceptor aborting every outbound
286
+ * request, which also aborts a SHARED single-flight token refresh and so fails
287
+ * every other caller waiting on it.
288
+ *
289
+ * So each pre-send wait is RACED against the signal: the caller stops waiting
290
+ * at once, and the work it was waiting on carries on for anybody else. The
291
+ * rejection is the signal's own reason — exactly what \`fetch\` rejects with —
292
+ * so a caller sees ONE abort shape whenever it aborts. An aborted request is
293
+ * never retried. Without a signal nothing here changes.
294
+ */
295
+ function abortedReason(signal: AbortSignal): unknown {
296
+ // \`abort()\` with no argument sets a DOMException reason, so this is only
297
+ // ever \`undefined\` for a hand-built signal; say so rather than throw it.
298
+ return signal.reason ?? new DOMException('This operation was aborted', 'AbortError');
299
+ }
300
+
301
+ function throwIfAborted(signal: AbortSignal | undefined): void {
302
+ if (signal?.aborted) {
303
+ throw abortedReason(signal);
304
+ }
305
+ }
306
+
307
+ function raceAbort<V>(
308
+ pending: V | Promise<V>,
309
+ signal: AbortSignal | undefined,
310
+ ): Promise<V> {
311
+ const promise = Promise.resolve(pending);
312
+ if (!signal) {
313
+ return promise;
314
+ }
315
+ if (signal.aborted) {
316
+ promise.catch(() => undefined);
317
+ return Promise.reject(abortedReason(signal));
318
+ }
319
+ return new Promise<V>((resolve, reject) => {
320
+ const onAbort = (): void => {
321
+ // The pending work may be shared; it carries on, and its eventual
322
+ // rejection must not surface as an unhandled one on this side.
323
+ promise.catch(() => undefined);
324
+ reject(abortedReason(signal));
325
+ };
326
+ signal.addEventListener('abort', onAbort, { once: true });
327
+ promise.then(
328
+ (value) => {
329
+ signal.removeEventListener('abort', onAbort);
330
+ resolve(value);
331
+ },
332
+ (err: unknown) => {
333
+ signal.removeEventListener('abort', onAbort);
334
+ reject(err);
335
+ },
336
+ );
337
+ });
338
+ }
339
+
256
340
  async function buildHeaders(
257
341
  config: ClientConfig,
258
342
  callerHeaders: RequestInit['headers'],
343
+ signal: AbortSignal | undefined,
259
344
  ): Promise<Headers> {
260
345
  const headers = new Headers(callerHeaders);
261
346
 
262
347
  // Global headers from config (caller-provided headers take precedence)
263
348
  if (config.getHeaders) {
264
- const globalHeaders = await Promise.resolve(config.getHeaders());
349
+ const globalHeaders = await raceAbort(config.getHeaders(), signal);
265
350
  for (const [key, value] of Object.entries(globalHeaders)) {
266
351
  if (!headers.has(key)) {
267
352
  headers.set(key, value);
@@ -281,7 +366,7 @@ async function buildHeaders(
281
366
  // receiver mints and a new trace begins, which is the truthful outcome when
282
367
  // there is nothing to continue.
283
368
  if (config.getCorrelationId && !headers.has(CORRELATION_ID_HEADER)) {
284
- const correlationId = await Promise.resolve(config.getCorrelationId());
369
+ const correlationId = await raceAbort(config.getCorrelationId(), signal);
285
370
  if (correlationId) {
286
371
  headers.set(CORRELATION_ID_HEADER, correlationId);
287
372
  }
@@ -289,7 +374,10 @@ async function buildHeaders(
289
374
 
290
375
  // Auth token (caller or global headers take precedence)
291
376
  if (config.getAuthToken && !headers.has('Authorization')) {
292
- const token = await config.getAuthToken();
377
+ const token = await raceAbort(
378
+ config.getAuthToken(signal ? { signal } : undefined),
379
+ signal,
380
+ );
293
381
  headers.set('Authorization', \`Bearer \${token}\`);
294
382
  }
295
383
 
@@ -325,8 +413,13 @@ export const customFetch = async <T>(
325
413
  options: RequestInit,
326
414
  ): Promise<T> => {
327
415
  const config = getClientConfig();
416
+ const signal = options.signal ?? undefined;
417
+ throwIfAborted(signal);
328
418
  const base = config.baseUrlResolver
329
- ? await config.baseUrlResolver()
419
+ ? await raceAbort(
420
+ config.baseUrlResolver(signal ? { signal } : undefined),
421
+ signal,
422
+ )
330
423
  : config.baseUrl;
331
424
  if (base === undefined) {
332
425
  throw new Error(
@@ -342,7 +435,7 @@ export const customFetch = async <T>(
342
435
  // credential: one wasted round trip, plus a global refresh nobody asked for.
343
436
  const callerSuppliedAuth = new Headers(options.headers).has('Authorization');
344
437
 
345
- const headers = await buildHeaders(config, options.headers);
438
+ const headers = await buildHeaders(config, options.headers, signal);
346
439
  const requestInit: RequestInit = { ...options, headers };
347
440
 
348
441
  let delay = BASE_BACKOFF_MS;
@@ -356,8 +449,12 @@ export const customFetch = async <T>(
356
449
  !callerSuppliedAuth &&
357
450
  attempt === 0
358
451
  ) {
359
- await config.onUnauthorized();
360
- const refreshedHeaders = await buildHeaders(config, options.headers);
452
+ await raceAbort(config.onUnauthorized(), signal);
453
+ const refreshedHeaders = await buildHeaders(
454
+ config,
455
+ options.headers,
456
+ signal,
457
+ );
361
458
  const retryResponse = await fetch(fullUrl, {
362
459
  ...options,
363
460
  headers: refreshedHeaders,
@@ -393,7 +490,7 @@ export const customFetch = async <T>(
393
490
  url: fullUrl,
394
491
  method: options.method ?? 'GET',
395
492
  });
396
- await sleep(waitMs);
493
+ await sleep(waitMs, signal);
397
494
  delay = Math.min(delay * 2, MAX_BACKOFF_MS);
398
495
  }
399
496
  };
@@ -475,8 +572,25 @@ function addJitter(delay: number): number {
475
572
  return delay + (Math.random() * 2 - 1) * delay * 0.25;
476
573
  }
477
574
 
478
- function sleep(ms: number): Promise<void> {
479
- return new Promise((resolve) => setTimeout(resolve, ms));
575
+ /** A retry backoff; the caller's signal ends it at once and is never retried. */
576
+ function sleep(ms: number, signal: AbortSignal | undefined): Promise<void> {
577
+ if (!signal) {
578
+ return new Promise((resolve) => setTimeout(resolve, ms));
579
+ }
580
+ if (signal.aborted) {
581
+ return Promise.reject(abortedReason(signal));
582
+ }
583
+ return new Promise((resolve, reject) => {
584
+ const onAbort = (): void => {
585
+ clearTimeout(timer);
586
+ reject(abortedReason(signal));
587
+ };
588
+ const timer = setTimeout(() => {
589
+ signal.removeEventListener('abort', onAbort);
590
+ resolve();
591
+ }, ms);
592
+ signal.addEventListener('abort', onAbort, { once: true });
593
+ });
480
594
  }
481
595
 
482
596
  export default customFetch;
@@ -1 +1 @@
1
- {"version":3,"file":"custom-fetch-template.js","sourceRoot":"","sources":["../../src/lib/custom-fetch-template.ts"],"names":[],"mappings":";;;AAca,QAAA,sBAAsB,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA+drC,CAAC"}
1
+ {"version":3,"file":"custom-fetch-template.js","sourceRoot":"","sources":["../../src/lib/custom-fetch-template.ts"],"names":[],"mappings":";;;AAca,QAAA,sBAAsB,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAilBrC,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xemahq/api-client-generator",
3
- "version": "1.1.2",
3
+ "version": "1.2.0",
4
4
  "description": "Layer 1 — the single, central OpenAPI + ORVAL client generator for every Xema NestJS service. Replaces the per-service orval.config.ts / scripts/extract-openapi.ts / scripts/build-client-index.js trio with two bins (xema-openapi, xema-client-generate). Extracts one OpenAPI document per ApiSurface (public/internal/operator) using the @XemaApiSurface decorator metadata, generates one ORVAL client package per non-empty surface (every surface of a service landing on ONE derived version — the highest its clients already carry, advanced a patch when the generated output changes), and stamps deterministic `xema` provenance metadata into each generated client package.json. No heuristics: a route ships in a surface only if it (or its controller) is explicitly classified, and no client version is ever typed by hand.",
5
5
  "keywords": [
6
6
  "xema",
@@ -62,8 +62,8 @@
62
62
  "prettier": "3.6.2",
63
63
  "reflect-metadata": "0.2.2",
64
64
  "typescript": "5.9.3",
65
- "@xemahq/eslint-config": "0.7.0",
66
- "@xemahq/xema-decorators": "0.19.0"
65
+ "@xemahq/xema-decorators": "0.19.0",
66
+ "@xemahq/eslint-config": "0.7.1"
67
67
  },
68
68
  "exports": {
69
69
  ".": {