@baukit/api-runtime 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Patrick Koss
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,117 @@
1
+ # `@baukit/api-runtime`
2
+
3
+ Shared client-side behavior for Baukit product APIs: explicit environment selection, bearer-token and request-ID headers, optional W3C trace propagation, normalized errors, safe retries, and a test fetch transport. It works in browsers and React Native and never reads `process.env`.
4
+
5
+ ## Generated client usage
6
+
7
+ The package wraps `openapi-fetch`; each product continues to own its generated `paths` type.
8
+
9
+ ```ts
10
+ import { createApiClient, resolveApiEnvironment } from '@baukit/api-runtime';
11
+ import type { paths } from './generated/api.js';
12
+
13
+ const environment = resolveApiEnvironment('production', {
14
+ development: 'http://localhost:3000',
15
+ production: 'https://api.example.com',
16
+ });
17
+
18
+ export const api = createApiClient<paths>({
19
+ ...environment,
20
+ tokenProvider: async () => session.accessToken ?? null,
21
+ onUnauthorized: async ({ canRetry }) => {
22
+ if (!canRetry) return 'handled';
23
+ const token = await session.accessToken({ forceRefresh: true });
24
+ return token === undefined ? 'handled' : 'retry-once';
25
+ },
26
+ });
27
+
28
+ const { data } = await api.GET('/widgets');
29
+ ```
30
+
31
+ If a generated wrapper already creates the client, pass it a configured runtime instead:
32
+
33
+ ```ts
34
+ import createClient from 'openapi-fetch';
35
+ import { createApiRuntime } from '@baukit/api-runtime';
36
+
37
+ const runtime = createApiRuntime({
38
+ baseUrl: 'https://api.example.com',
39
+ environment: 'production',
40
+ tokenProvider: getAccessToken,
41
+ });
42
+
43
+ const api = createClient<paths>({ baseUrl: runtime.baseUrl, fetch: runtime.fetch });
44
+ ```
45
+
46
+ `tokenProvider` runs for every logical request; the runtime does not cache its result. Every request receives a new UUID in `x-request-id`. Configure `traceparentProvider` only when the product has a tracing implementation.
47
+
48
+ ## Unauthorized recovery
49
+
50
+ `onUnauthorized` remains a notification hook when it returns `void` or `'handled'`: the normalized 401 is thrown as before. Returning `'retry-once'` explicitly asks the runtime to reacquire credentials through `tokenProvider` and replay a preflighted request clone. The hook receives `canRetry: false` when the body cannot be cloned; returning `'retry-once'` then safely falls back to the original 401. Recovery runs at most once, a second 401 stops, and the original `AbortSignal` remains effective during refresh and replay.
51
+
52
+ Set `onUnauthorizedExhausted` when the product must stop schedulers or move to
53
+ a signed-out state after that replay also returns 401. It receives the final
54
+ normalized error with `canRetry: false`; observer failures never replace the
55
+ API failure.
56
+
57
+ This handshake does not make arbitrary mutations safe. Replaying `POST`, `PATCH`, or any write whose outcome may already have committed still requires a product/server idempotency contract. Follow the repository's [integration reliability recipe](../../../docs/platform/integration-reliability.md), [offline replay contract](../../../docs/platform/offline-readiness-contract.md), and [add-endpoint replay/idempotency guidance](../../../agent-skills/skills/baukit-add-endpoint/SKILL.md).
58
+
59
+ ## Error handling
60
+
61
+ Non-success responses throw one of three typed errors. Raw fetch/CORS errors are always wrapped.
62
+
63
+ ```ts
64
+ import { isApiError, isHttpError, isNetworkError } from '@baukit/api-runtime';
65
+
66
+ try {
67
+ await api.POST('/widgets', { body: widget });
68
+ } catch (error) {
69
+ if (isApiError(error, 'validation_failed')) {
70
+ showValidation(error.details, error.requestId);
71
+ } else if (isNetworkError(error)) {
72
+ showOfflineMessage();
73
+ } else if (isHttpError(error)) {
74
+ reportUnexpectedResponse(error.status, error.requestId);
75
+ } else {
76
+ throw error;
77
+ }
78
+ }
79
+ ```
80
+
81
+ - `ApiError`: a valid Baukit `{ error: { code, message, request_id, details } }` envelope.
82
+ - `HttpError`: an HTTP failure with a missing or malformed envelope, including non-JSON bodies.
83
+ - `NetworkError`: no HTTP response, such as an offline, DNS, fetch, or CORS failure. Aborts set `aborted` to `true`.
84
+
85
+ The backend `message` is public, safe fallback text. Localized clients should resolve `ApiError.code` plus structured `ApiError.details` through their product catalog and use `ApiError.message` only when that resolution is unavailable. Do not parse the message or use it as a stable localization key.
86
+
87
+ ## Retry semantics
88
+
89
+ Retries use exponential backoff with full jitter, capped by `maxDelayMs`. The same request ID is retained across attempts.
90
+
91
+ | Request/result | Default | Configurable |
92
+ | ----------------------------- | ---------------- | -------------------------------------------- |
93
+ | `GET`, `HEAD` + network error | Retry | `maxRetries`, delays, or disable |
94
+ | `GET`, `HEAD` + 502/503/504 | Retry | `maxRetries`, delays, or disable |
95
+ | `OPTIONS`, `PUT`, `DELETE` | No retry | May be explicitly opted in through `methods` |
96
+ | Any 4xx | Never | No |
97
+ | `POST`, `PATCH` | Never | No |
98
+ | Abort | Stop immediately | No |
99
+
100
+ Defaults are two retries, a 100 ms initial ceiling, and a 2,000 ms maximum ceiling. Use `retry: false` to disable retries.
101
+
102
+ ## Tests
103
+
104
+ `MockFetch` queues responses, errors, or handlers and records cloned requests:
105
+
106
+ ```ts
107
+ const mock = new MockFetch().enqueueJson({ widgets: [] });
108
+ const runtime = createApiRuntime({
109
+ baseUrl: 'https://api.example.test',
110
+ environment: 'test',
111
+ fetch: mock.fetch,
112
+ });
113
+
114
+ await runtime.fetch('/widgets');
115
+ mock.assertRequest(0, { method: 'GET', url: 'https://api.example.test/widgets' });
116
+ mock.assertQueueEmpty();
117
+ ```
@@ -0,0 +1,144 @@
1
+ import type { Client, ClientOptions } from 'openapi-fetch';
2
+ /** The request ID header accepted and returned by `baukit-http`. */
3
+ export declare const REQUEST_ID_HEADER: "x-request-id";
4
+ /** An explicitly selected API environment. */
5
+ export interface ApiEnvironmentConfig {
6
+ readonly baseUrl: string;
7
+ readonly environment: string;
8
+ }
9
+ /** A product-owned map from environment names to API base URLs. */
10
+ export type ApiEnvironmentMap = Readonly<Record<string, string>>;
11
+ /** Resolves an explicit environment name from a caller-provided map. */
12
+ export declare function resolveApiEnvironment(environment: string, environments: ApiEnvironmentMap): ApiEnvironmentConfig;
13
+ /** Supplies an access token for each logical request. Token lifecycle and caching stay product-owned. */
14
+ export type TokenProvider = () => Promise<string | null>;
15
+ /** Supplies a W3C `traceparent` value. No tracing provider is installed by this package. */
16
+ export type TraceparentProvider = (request: Request) => string | null | Promise<string | null>;
17
+ /** HTTP methods that may be opted into automatic retries. */
18
+ export type RetryableMethod = 'GET' | 'HEAD' | 'OPTIONS' | 'PUT' | 'DELETE';
19
+ /** Retry behavior for transient failures. */
20
+ export interface RetryOptions {
21
+ /** Additional attempts after the initial attempt. Defaults to 2. */
22
+ readonly maxRetries?: number;
23
+ /** Initial backoff ceiling in milliseconds. Defaults to 100. */
24
+ readonly baseDelayMs?: number;
25
+ /** Maximum backoff ceiling in milliseconds. Defaults to 2,000. */
26
+ readonly maxDelayMs?: number;
27
+ /** Methods eligible for retries. Defaults to GET and HEAD. */
28
+ readonly methods?: readonly RetryableMethod[];
29
+ /** Random source used for full jitter. Defaults to `Math.random`. */
30
+ readonly random?: () => number;
31
+ /** Abort-aware delay seam, primarily useful for deterministic tests. */
32
+ readonly sleep?: (delayMs: number, signal: AbortSignal | null) => Promise<void>;
33
+ }
34
+ /** The fetch shape accepted by browsers, React Native, and `openapi-fetch`. */
35
+ export type FetchImplementation = (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
36
+ /** Context delivered when a response has status 401. */
37
+ export interface UnauthorizedContext {
38
+ readonly error: ApiError | HttpError;
39
+ readonly request: Request;
40
+ readonly response: Response;
41
+ /** False when the request body cannot be cloned safely for replay. */
42
+ readonly canRetry: boolean;
43
+ }
44
+ /** Explicit outcome of a 401 hook. `handled` preserves the original normalized rejection. */
45
+ export type UnauthorizedRecovery = 'handled' | 'retry-once';
46
+ /** Backward-compatible 401 notification or explicit recovery callback. */
47
+ export type UnauthorizedHandler = ((context: UnauthorizedContext) => void) | ((context: UnauthorizedContext) => Promise<void>) | ((context: UnauthorizedContext) => UnauthorizedRecovery) | ((context: UnauthorizedContext) => Promise<UnauthorizedRecovery>);
48
+ /** Notification emitted when an explicit credential replay also returns 401. */
49
+ export type UnauthorizedExhaustedHandler = (context: UnauthorizedContext) => void | Promise<void>;
50
+ /** Options shared by the standalone fetch wrapper and generated clients. */
51
+ export interface ApiRuntimeOptions extends ApiEnvironmentConfig {
52
+ readonly fetch?: FetchImplementation;
53
+ readonly requestConstructor?: typeof Request;
54
+ readonly tokenProvider?: TokenProvider;
55
+ readonly traceparentProvider?: TraceparentProvider;
56
+ readonly requestIdFactory?: () => string;
57
+ readonly onUnauthorized?: UnauthorizedHandler;
58
+ readonly onUnauthorizedExhausted?: UnauthorizedExhaustedHandler;
59
+ readonly retry?: RetryOptions | false;
60
+ }
61
+ /** A configured runtime that can be handed to a product's generated client. */
62
+ export interface ApiRuntime extends ApiEnvironmentConfig {
63
+ readonly fetch: FetchImplementation;
64
+ }
65
+ /** JSON values accepted in Baukit error details. */
66
+ export type JsonValue = null | boolean | number | string | readonly JsonValue[] | {
67
+ readonly [key: string]: JsonValue;
68
+ };
69
+ /** A validated Baukit error envelope. */
70
+ export interface ApiErrorEnvelope<Code extends string = string> {
71
+ readonly error: {
72
+ readonly code: Code;
73
+ readonly message: string;
74
+ readonly request_id: string;
75
+ readonly details: Readonly<Record<string, JsonValue>>;
76
+ };
77
+ }
78
+ /** A non-success response using Baukit's standard JSON error envelope. */
79
+ export declare class ApiError<Code extends string = string> extends Error {
80
+ readonly kind: "api";
81
+ readonly code: Code;
82
+ readonly requestId: string;
83
+ readonly details: Readonly<Record<string, JsonValue>>;
84
+ readonly status: number;
85
+ constructor(envelope: ApiErrorEnvelope<Code>, status: number);
86
+ }
87
+ /** A transport failure where no HTTP response was available (including CORS failures). */
88
+ export declare class NetworkError extends Error {
89
+ readonly kind: "network";
90
+ readonly requestId: string;
91
+ readonly aborted: boolean;
92
+ constructor(message: string, requestId: string, cause: unknown, aborted?: boolean);
93
+ }
94
+ /** A non-success HTTP response that did not contain a valid Baukit error envelope. */
95
+ export declare class HttpError extends Error {
96
+ readonly kind: "http";
97
+ readonly status: number;
98
+ readonly requestId: string | null;
99
+ readonly body: unknown;
100
+ constructor(response: Response, body: unknown);
101
+ }
102
+ /** Narrows an unknown value to an ApiError, optionally with one specific code. */
103
+ export declare function isApiError(value: unknown): value is ApiError;
104
+ export declare function isApiError<Code extends string>(value: unknown, code: Code): value is ApiError<Code>;
105
+ /** Narrows an unknown value to a NetworkError. */
106
+ export declare function isNetworkError(value: unknown): value is NetworkError;
107
+ /** Narrows an unknown value to an HttpError. */
108
+ export declare function isHttpError(value: unknown): value is HttpError;
109
+ /** Parses the exact Baukit error envelope shape, returning null for any other value. */
110
+ export declare function parseApiErrorEnvelope(value: unknown, status: number): ApiError | null;
111
+ /** Converts a non-success HTTP response into an ApiError or HttpError. */
112
+ export declare function normalizeResponseError(response: Response): Promise<ApiError | HttpError>;
113
+ /** Creates the fetch runtime used by standalone callers and generated clients. */
114
+ export declare function createApiRuntime(options: ApiRuntimeOptions): ApiRuntime;
115
+ /** Creates an `openapi-fetch` client backed by the Baukit runtime. */
116
+ export declare function createApiClient<Paths extends object>(runtimeOptions: ApiRuntimeOptions, clientOptions?: Omit<ClientOptions, 'baseUrl' | 'fetch'>): Client<Paths>;
117
+ /** Creates a standalone fetch wrapper with auth, request IDs, errors, and safe retries. */
118
+ export declare function createApiFetch(options: ApiRuntimeOptions): FetchImplementation;
119
+ /** Expected request fields used by MockFetch assertions. */
120
+ export interface MockRequestExpectation {
121
+ readonly method?: string;
122
+ readonly url?: string;
123
+ readonly headers?: Readonly<Record<string, string>>;
124
+ }
125
+ /** A queued response factory for MockFetch. */
126
+ export type MockFetchHandler = (request: Request) => Response | Promise<Response>;
127
+ /** A small queued fetch transport for product and package tests. */
128
+ export declare class MockFetch {
129
+ #private;
130
+ readonly requests: Request[];
131
+ readonly fetch: FetchImplementation;
132
+ constructor();
133
+ /** Adds a response, transport error, or response factory to the queue. */
134
+ enqueue(next: Response | Error | MockFetchHandler): this;
135
+ /** Adds a JSON response to the queue. */
136
+ enqueueJson(body: unknown, init?: ResponseInit): this;
137
+ /** Returns one recorded request or throws a clear assertion error. */
138
+ request(index: number): Request;
139
+ /** Asserts selected fields of a recorded request without a test-framework dependency. */
140
+ assertRequest(index: number, expected: MockRequestExpectation): void;
141
+ /** Asserts that every queued result has been consumed. */
142
+ assertQueueEmpty(): void;
143
+ }
144
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AAE3D,oEAAoE;AACpE,eAAO,MAAM,iBAAiB,EAAG,cAAuB,CAAC;AAEzD,8CAA8C;AAC9C,MAAM,WAAW,oBAAoB;IACnC,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;CAC9B;AAED,mEAAmE;AACnE,MAAM,MAAM,iBAAiB,GAAG,QAAQ,CAAC,MAAM,CAAC,M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E,IAAI,CAAC,aAAa,EAAE,SAAS,GAAG,OAAO,CAAM,GAC3D,MAAM,CAAC,KAAK,CAAC,CAGf;AAED,2FAA2F;AAC3F,wBAAgB,cAAc,CAAC,OAAO,EAAE,iBAAiB,GAAG,mBAAmB,CAqI9E;AAwCD,4DAA4D;AAC5D,MAAM,WAAW,sBAAsB;IACrC,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,GAAG,CAAC,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,OAAO,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;CACrD;AAED,+CAA+C;AAC/C,MAAM,MAAM,gBAAgB,GAAG,CAAC,OAAO,EAAE,OAAO,KAAK,QAAQ,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC;AAElF,oEAAoE;AACpE,qBAAa,SAAS;;IACpB,QAAQ,CAAC,QAAQ,EAAE,OAAO,EAAE,CAAM;IAClC,QAAQ,CAAC,KAAK,EAAE,mBAAmB,CAAC;;IAkBpC,0EAA0E;IAC1E,OAAO,CAAC,IAAI,EAAE,QAAQ,GAAG,KAAK,GAAG,gBAAgB,GAAG,IAAI;IAKxD,yCAAyC;IACzC,WAAW,CAAC,IAAI,EAAE,OAAO,EAAE,IAAI,GAAE,YAAiB,GAAG,IAAI;IAQzD,sEAAsE;IACtE,OAAO,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO;IAQ/B,yFAAyF;IACzF,aAAa,CAAC,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,sBAAsB,GAAG,IAAI;IAgBpE,0DAA0D;IAC1D,gBAAgB,IAAI,IAAI;CAKzB"}
package/dist/index.js ADDED
@@ -0,0 +1,476 @@
1
+ /// <reference lib="dom" />
2
+ import createClient from 'openapi-fetch';
3
+ /** The request ID header accepted and returned by `baukit-http`. */
4
+ export const REQUEST_ID_HEADER = 'x-request-id';
5
+ /** Resolves an explicit environment name from a caller-provided map. */
6
+ export function resolveApiEnvironment(environment, environments) {
7
+ const baseUrl = Object.hasOwn(environments, environment) ? environments[environment] : undefined;
8
+ if (baseUrl === undefined) {
9
+ throw new Error(`Unknown API environment: ${environment}`);
10
+ }
11
+ return { baseUrl: normalizeBaseUrl(baseUrl), environment };
12
+ }
13
+ /** A non-success response using Baukit's standard JSON error envelope. */
14
+ export class ApiError extends Error {
15
+ kind = 'api';
16
+ code;
17
+ requestId;
18
+ details;
19
+ status;
20
+ constructor(envelope, status) {
21
+ super(envelope.error.message);
22
+ this.name = 'ApiError';
23
+ this.code = envelope.error.code;
24
+ this.requestId = envelope.error.request_id;
25
+ this.details = envelope.error.details;
26
+ this.status = status;
27
+ }
28
+ }
29
+ /** A transport failure where no HTTP response was available (including CORS failures). */
30
+ export class NetworkError extends Error {
31
+ kind = 'network';
32
+ requestId;
33
+ aborted;
34
+ constructor(message, requestId, cause, aborted = false) {
35
+ super(message, { cause });
36
+ this.name = 'NetworkError';
37
+ this.requestId = requestId;
38
+ this.aborted = aborted;
39
+ }
40
+ }
41
+ /** A non-success HTTP response that did not contain a valid Baukit error envelope. */
42
+ export class HttpError extends Error {
43
+ kind = 'http';
44
+ status;
45
+ requestId;
46
+ body;
47
+ constructor(response, body) {
48
+ const suffix = response.statusText === '' ? '' : ` ${response.statusText}`;
49
+ super(`HTTP ${String(response.status)}${suffix}`);
50
+ this.name = 'HttpError';
51
+ this.status = response.status;
52
+ this.requestId = response.headers.get(REQUEST_ID_HEADER);
53
+ this.body = body;
54
+ }
55
+ }
56
+ export function isApiError(value, code) {
57
+ return value instanceof ApiError && (code === undefined || value.code === code);
58
+ }
59
+ /** Narrows an unknown value to a NetworkError. */
60
+ export function isNetworkError(value) {
61
+ return value instanceof NetworkError;
62
+ }
63
+ /** Narrows an unknown value to an HttpError. */
64
+ export function isHttpError(value) {
65
+ return value instanceof HttpError;
66
+ }
67
+ /** Parses the exact Baukit error envelope shape, returning null for any other value. */
68
+ export function parseApiErrorEnvelope(value, status) {
69
+ if (!isRecord(value) || !isRecord(value['error'])) {
70
+ return null;
71
+ }
72
+ const error = value['error'];
73
+ if (typeof error['code'] !== 'string' ||
74
+ typeof error['message'] !== 'string' ||
75
+ typeof error['request_id'] !== 'string' ||
76
+ !isJsonObject(error['details'])) {
77
+ return null;
78
+ }
79
+ return new ApiError({
80
+ error: {
81
+ code: error['code'],
82
+ message: error['message'],
83
+ request_id: error['request_id'],
84
+ details: error['details'],
85
+ },
86
+ }, status);
87
+ }
88
+ /** Converts a non-success HTTP response into an ApiError or HttpError. */
89
+ export async function normalizeResponseError(response) {
90
+ let body;
91
+ try {
92
+ const text = await response.clone().text();
93
+ if (text !== '') {
94
+ try {
95
+ body = JSON.parse(text);
96
+ }
97
+ catch {
98
+ body = text;
99
+ }
100
+ }
101
+ }
102
+ catch {
103
+ body = undefined;
104
+ }
105
+ return parseApiErrorEnvelope(body, response.status) ?? new HttpError(response, body);
106
+ }
107
+ /** Creates the fetch runtime used by standalone callers and generated clients. */
108
+ export function createApiRuntime(options) {
109
+ const baseUrl = normalizeBaseUrl(options.baseUrl);
110
+ return {
111
+ baseUrl,
112
+ environment: options.environment,
113
+ fetch: createApiFetch({ ...options, baseUrl }),
114
+ };
115
+ }
116
+ /** Creates an `openapi-fetch` client backed by the Baukit runtime. */
117
+ export function createApiClient(runtimeOptions, clientOptions = {}) {
118
+ const runtime = createApiRuntime(runtimeOptions);
119
+ return createClient({ ...clientOptions, baseUrl: runtime.baseUrl, fetch: runtime.fetch });
120
+ }
121
+ /** Creates a standalone fetch wrapper with auth, request IDs, errors, and safe retries. */
122
+ export function createApiFetch(options) {
123
+ const baseUrl = normalizeBaseUrl(options.baseUrl);
124
+ const requestConstructor = options.requestConstructor ?? globalThis.Request;
125
+ const transport = options.fetch ?? globalThis.fetch.bind(globalThis);
126
+ const requestIdFactory = options.requestIdFactory ?? createUuid;
127
+ const retry = normalizeRetryOptions(options.retry);
128
+ return async (input, init) => {
129
+ const requestId = requestIdFactory();
130
+ let request;
131
+ try {
132
+ request = createRequest(input, init, baseUrl, requestConstructor);
133
+ request = await decorateRequest(request, requestId, requestConstructor, options);
134
+ }
135
+ catch (cause) {
136
+ if (cause instanceof NetworkError) {
137
+ throw cause;
138
+ }
139
+ throw networkError(cause, requestId, init?.signal ?? null);
140
+ }
141
+ let replaySource = cloneRequest(request);
142
+ let useOriginalRequest = true;
143
+ let retries = 0;
144
+ let unauthorizedReplayUsed = false;
145
+ for (;;) {
146
+ throwIfAborted(request.signal, requestId);
147
+ try {
148
+ const attempt = useOriginalRequest ? request : replaySource?.clone();
149
+ if (attempt === undefined) {
150
+ throw new TypeError('API request body cannot be replayed');
151
+ }
152
+ useOriginalRequest = false;
153
+ const response = await transport(attempt);
154
+ throwIfAborted(request.signal, requestId);
155
+ if (replaySource !== undefined &&
156
+ shouldRetryResponse(request.method, response.status, retries, retry)) {
157
+ await retryDelay(retries, retry, request.signal, requestId);
158
+ retries += 1;
159
+ continue;
160
+ }
161
+ if (response.ok) {
162
+ return response;
163
+ }
164
+ const error = await normalizeResponseError(response);
165
+ if (response.status === 401 &&
166
+ unauthorizedReplayUsed &&
167
+ options.onUnauthorizedExhausted !== undefined) {
168
+ try {
169
+ await options.onUnauthorizedExhausted({
170
+ error,
171
+ request: replaySource?.clone() ?? request,
172
+ response,
173
+ canRetry: false,
174
+ });
175
+ }
176
+ catch {
177
+ // Terminal authentication observers cannot replace the normalized API failure.
178
+ }
179
+ throwIfAborted(request.signal, requestId);
180
+ }
181
+ if (response.status === 401 &&
182
+ options.onUnauthorized !== undefined &&
183
+ !unauthorizedReplayUsed) {
184
+ let recovery;
185
+ try {
186
+ recovery = await options.onUnauthorized({
187
+ error,
188
+ request: replaySource?.clone() ?? request,
189
+ response,
190
+ canRetry: replaySource !== undefined,
191
+ });
192
+ }
193
+ catch {
194
+ // Re-authentication failures must not replace the normalized API failure.
195
+ }
196
+ throwIfAborted(request.signal, requestId);
197
+ if (recovery === 'retry-once' && replaySource !== undefined) {
198
+ unauthorizedReplayUsed = true;
199
+ try {
200
+ request = await decorateRequest(replaySource.clone(), requestId, requestConstructor, options);
201
+ }
202
+ catch (cause) {
203
+ throwIfAborted(request.signal, requestId);
204
+ if (cause instanceof NetworkError) {
205
+ throw cause;
206
+ }
207
+ throw error;
208
+ }
209
+ replaySource = cloneRequest(request);
210
+ if (replaySource === undefined) {
211
+ throw error;
212
+ }
213
+ useOriginalRequest = true;
214
+ retries = 0;
215
+ continue;
216
+ }
217
+ }
218
+ throw error;
219
+ }
220
+ catch (cause) {
221
+ if (cause instanceof ApiError || cause instanceof HttpError) {
222
+ throw cause;
223
+ }
224
+ const aborted = request.signal.aborted || isAbortError(cause);
225
+ if (!aborted &&
226
+ replaySource !== undefined &&
227
+ shouldRetryMethod(request.method, retry) &&
228
+ retries < retry.maxRetries) {
229
+ await retryDelay(retries, retry, request.signal, requestId);
230
+ retries += 1;
231
+ continue;
232
+ }
233
+ throw new NetworkError(aborted ? 'API request was aborted' : 'API network request failed', requestId, cause, aborted);
234
+ }
235
+ }
236
+ };
237
+ }
238
+ async function decorateRequest(request, requestId, requestConstructor, options) {
239
+ throwIfAborted(request.signal, requestId);
240
+ const headers = new Headers(request.headers);
241
+ headers.set(REQUEST_ID_HEADER, requestId);
242
+ if (options.tokenProvider !== undefined) {
243
+ const token = await options.tokenProvider();
244
+ throwIfAborted(request.signal, requestId);
245
+ headers.delete('authorization');
246
+ if (token !== null) {
247
+ headers.set('authorization', `Bearer ${token}`);
248
+ }
249
+ }
250
+ if (options.traceparentProvider !== undefined) {
251
+ const traceparent = await options.traceparentProvider(request);
252
+ throwIfAborted(request.signal, requestId);
253
+ if (traceparent !== null) {
254
+ headers.set('traceparent', traceparent);
255
+ }
256
+ }
257
+ return new requestConstructor(request, { headers });
258
+ }
259
+ function cloneRequest(request) {
260
+ try {
261
+ return request.clone();
262
+ }
263
+ catch {
264
+ return undefined;
265
+ }
266
+ }
267
+ /** A small queued fetch transport for product and package tests. */
268
+ export class MockFetch {
269
+ requests = [];
270
+ fetch;
271
+ #queue = [];
272
+ constructor() {
273
+ this.fetch = async (input, init) => {
274
+ const request = new Request(input, init);
275
+ this.requests.push(request.clone());
276
+ const next = this.#queue.shift();
277
+ if (next === undefined) {
278
+ throw new Error('MockFetch has no queued response');
279
+ }
280
+ if (next instanceof Error) {
281
+ throw next;
282
+ }
283
+ return typeof next === 'function' ? next(request) : next;
284
+ };
285
+ }
286
+ /** Adds a response, transport error, or response factory to the queue. */
287
+ enqueue(next) {
288
+ this.#queue.push(next);
289
+ return this;
290
+ }
291
+ /** Adds a JSON response to the queue. */
292
+ enqueueJson(body, init = {}) {
293
+ const headers = new Headers(init.headers);
294
+ if (!headers.has('content-type')) {
295
+ headers.set('content-type', 'application/json');
296
+ }
297
+ return this.enqueue(new Response(JSON.stringify(body), { ...init, headers }));
298
+ }
299
+ /** Returns one recorded request or throws a clear assertion error. */
300
+ request(index) {
301
+ const request = this.requests[index];
302
+ if (request === undefined) {
303
+ throw new Error(`MockFetch request ${String(index)} was not recorded`);
304
+ }
305
+ return request;
306
+ }
307
+ /** Asserts selected fields of a recorded request without a test-framework dependency. */
308
+ assertRequest(index, expected) {
309
+ const request = this.request(index);
310
+ if (expected.method !== undefined && request.method !== expected.method.toUpperCase()) {
311
+ throw new Error(`Expected request method ${expected.method}, received ${request.method}`);
312
+ }
313
+ if (expected.url !== undefined && request.url !== expected.url) {
314
+ throw new Error(`Expected request URL ${expected.url}, received ${request.url}`);
315
+ }
316
+ for (const [name, value] of Object.entries(expected.headers ?? {})) {
317
+ const received = request.headers.get(name);
318
+ if (received !== value) {
319
+ throw new Error(`Expected request header ${name}=${value}, received ${String(received)}`);
320
+ }
321
+ }
322
+ }
323
+ /** Asserts that every queued result has been consumed. */
324
+ assertQueueEmpty() {
325
+ if (this.#queue.length !== 0) {
326
+ throw new Error(`MockFetch has ${String(this.#queue.length)} queued result(s) remaining`);
327
+ }
328
+ }
329
+ }
330
+ const NEVER_RETRY = new Set(['POST', 'PATCH']);
331
+ const RETRYABLE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS', 'PUT', 'DELETE']);
332
+ const RETRYABLE_STATUSES = new Set([502, 503, 504]);
333
+ function normalizeBaseUrl(baseUrl) {
334
+ let parsed;
335
+ try {
336
+ parsed = new URL(baseUrl);
337
+ }
338
+ catch {
339
+ throw new Error(`API base URL must be absolute: ${baseUrl}`);
340
+ }
341
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
342
+ throw new Error(`API base URL must use HTTP or HTTPS: ${baseUrl}`);
343
+ }
344
+ if (parsed.search !== '' || parsed.hash !== '') {
345
+ throw new Error(`API base URL must not contain a query or fragment: ${baseUrl}`);
346
+ }
347
+ return parsed.toString().replace(/\/$/u, '');
348
+ }
349
+ function createRequest(input, init, baseUrl, requestConstructor) {
350
+ if (typeof input === 'string' || input instanceof URL) {
351
+ return new requestConstructor(new URL(input.toString(), `${baseUrl}/`), init);
352
+ }
353
+ return new requestConstructor(input, init);
354
+ }
355
+ function createUuid() {
356
+ const cryptoApi = globalThis.crypto;
357
+ if (typeof cryptoApi?.randomUUID === 'function') {
358
+ return cryptoApi.randomUUID();
359
+ }
360
+ const bytes = new Uint8Array(16);
361
+ if (typeof cryptoApi?.getRandomValues === 'function') {
362
+ cryptoApi.getRandomValues(bytes);
363
+ }
364
+ else {
365
+ for (let index = 0; index < bytes.length; index += 1) {
366
+ bytes[index] = Math.floor(Math.random() * 256);
367
+ }
368
+ }
369
+ bytes[6] = ((bytes[6] ?? 0) & 0x0f) | 0x40;
370
+ bytes[8] = ((bytes[8] ?? 0) & 0x3f) | 0x80;
371
+ const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('');
372
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
373
+ }
374
+ function normalizeRetryOptions(options) {
375
+ const maxRetries = options === false ? 0 : (options?.maxRetries ?? 2);
376
+ const baseDelayMs = options === false ? 100 : (options?.baseDelayMs ?? 100);
377
+ const maxDelayMs = options === false ? 2_000 : (options?.maxDelayMs ?? 2_000);
378
+ assertFiniteNonNegativeInteger(maxRetries, 'maxRetries');
379
+ assertFiniteNonNegative(baseDelayMs, 'baseDelayMs');
380
+ assertFiniteNonNegative(maxDelayMs, 'maxDelayMs');
381
+ const requestedMethods = options === false ? [] : (options?.methods ?? ['GET', 'HEAD']);
382
+ const methods = new Set(requestedMethods.filter((method) => RETRYABLE_METHODS.has(method) && !NEVER_RETRY.has(method)));
383
+ return {
384
+ maxRetries,
385
+ baseDelayMs,
386
+ maxDelayMs,
387
+ methods,
388
+ random: options === false ? Math.random : (options?.random ?? Math.random),
389
+ sleep: options === false ? abortableSleep : (options?.sleep ?? abortableSleep),
390
+ };
391
+ }
392
+ function assertFiniteNonNegative(value, name) {
393
+ if (!Number.isFinite(value) || value < 0) {
394
+ throw new Error(`${name} must be a finite non-negative number`);
395
+ }
396
+ }
397
+ function assertFiniteNonNegativeInteger(value, name) {
398
+ assertFiniteNonNegative(value, name);
399
+ if (!Number.isInteger(value)) {
400
+ throw new Error(`${name} must be an integer`);
401
+ }
402
+ }
403
+ function shouldRetryMethod(method, retry) {
404
+ return !NEVER_RETRY.has(method) && retry.methods.has(method);
405
+ }
406
+ function shouldRetryResponse(method, status, retries, retry) {
407
+ return (retries < retry.maxRetries && shouldRetryMethod(method, retry) && RETRYABLE_STATUSES.has(status));
408
+ }
409
+ async function retryDelay(retryIndex, retry, signal, requestId) {
410
+ const ceiling = Math.min(retry.maxDelayMs, retry.baseDelayMs * 2 ** retryIndex);
411
+ const random = Math.max(0, Math.min(1, retry.random()));
412
+ try {
413
+ await retry.sleep(ceiling * random, signal);
414
+ }
415
+ catch (cause) {
416
+ throw new NetworkError('API request was aborted', requestId, cause, true);
417
+ }
418
+ throwIfAborted(signal, requestId);
419
+ }
420
+ function abortableSleep(delayMs, signal) {
421
+ if (signal === null) {
422
+ return new Promise((resolve) => {
423
+ globalThis.setTimeout(resolve, delayMs);
424
+ });
425
+ }
426
+ if (signal.aborted) {
427
+ return Promise.reject(abortReason(signal));
428
+ }
429
+ return new Promise((resolve, reject) => {
430
+ const onAbort = () => {
431
+ globalThis.clearTimeout(timer);
432
+ reject(abortReason(signal));
433
+ };
434
+ const timer = globalThis.setTimeout(() => {
435
+ signal.removeEventListener('abort', onAbort);
436
+ resolve();
437
+ }, delayMs);
438
+ signal.addEventListener('abort', onAbort, { once: true });
439
+ });
440
+ }
441
+ function abortReason(signal) {
442
+ return signal.reason instanceof Error
443
+ ? signal.reason
444
+ : new Error('API request was aborted', { cause: signal.reason });
445
+ }
446
+ function throwIfAborted(signal, requestId) {
447
+ if (signal.aborted) {
448
+ throw new NetworkError('API request was aborted', requestId, signal.reason, true);
449
+ }
450
+ }
451
+ function networkError(cause, requestId, signal) {
452
+ const aborted = signal?.aborted === true || isAbortError(cause);
453
+ return new NetworkError(aborted ? 'API request was aborted' : 'API network request failed', requestId, cause, aborted);
454
+ }
455
+ function isAbortError(value) {
456
+ return value instanceof Error && value.name === 'AbortError';
457
+ }
458
+ function isRecord(value) {
459
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
460
+ }
461
+ function isJsonObject(value) {
462
+ return isRecord(value) && Object.values(value).every(isJsonValue);
463
+ }
464
+ function isJsonValue(value) {
465
+ if (value === null ||
466
+ typeof value === 'string' ||
467
+ typeof value === 'boolean' ||
468
+ (typeof value === 'number' && Number.isFinite(value))) {
469
+ return true;
470
+ }
471
+ if (Array.isArray(value)) {
472
+ return value.every(isJsonValue);
473
+ }
474
+ return isJsonObject(value);
475
+ }
476
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,2BAA2B;AAE3B,OAAO,YAAY,MAAM,eAAe,CAAC;AAGzC,oEAAoE;AACpE,MAAM,CAAC,MAAM,iBAAiB,GAAG,cAAuB,CAAC;AAWzD,w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AC,yBAAyB,CAAC,CAAC,CAAC,4BAA4B,EAClE,SAAS,EACT,KAAK,EACL,OAAO,CACR,CAAC;AACJ,CAAC;AAED,SAAS,YAAY,CAAC,KAAc;IAClC,OAAO,KAAK,YAAY,KAAK,IAAI,KAAK,CAAC,IAAI,KAAK,YAAY,CAAC;AAC/D,CAAC;AAED,SAAS,QAAQ,CAAC,KAAc;IAC9B,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAC9E,CAAC;AAED,SAAS,YAAY,CAAC,KAAc;IAClC,OAAO,QAAQ,CAAC,KAAK,CAAC,IAAI,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC;AACpE,CAAC;AAED,SAAS,WAAW,CAAC,KAAc;IACjC,IACE,KAAK,KAAK,IAAI;QACd,OAAO,KAAK,KAAK,QAAQ;QACzB,OAAO,KAAK,KAAK,SAAS;QAC1B,CAAC,OAAO,KAAK,KAAK,QAAQ,IAAI,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,EACrD,CAAC;QACD,OAAO,IAAI,CAAC;IACd,CAAC;IACD,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC;QACzB,OAAO,KAAK,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC;IAClC,CAAC;IACD,OAAO,YAAY,CAAC,KAAK,CAAC,CAAC;AAC7B,CAAC"}
package/package.json ADDED
@@ -0,0 +1,47 @@
1
+ {
2
+ "name": "@baukit/api-runtime",
3
+ "version": "0.1.0",
4
+ "description": "Shared client-side behavior for product APIs: environment selection, auth and request-ID headers, trace propagation, normalized errors, and safe retries.",
5
+ "license": "MIT",
6
+ "author": "Patrick Koss",
7
+ "homepage": "https://github.com/PatrickKoss/baukit#readme",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/PatrickKoss/baukit.git",
11
+ "directory": "typescript/packages/api-runtime"
12
+ },
13
+ "bugs": {
14
+ "url": "https://github.com/PatrickKoss/baukit/issues"
15
+ },
16
+ "publishConfig": {
17
+ "access": "public"
18
+ },
19
+ "type": "module",
20
+ "engines": {
21
+ "node": ">=24.0.0"
22
+ },
23
+ "types": "./dist/index.d.ts",
24
+ "exports": {
25
+ ".": {
26
+ "types": "./dist/index.d.ts",
27
+ "import": "./dist/index.js"
28
+ }
29
+ },
30
+ "files": [
31
+ "dist",
32
+ "README.md",
33
+ "LICENSE"
34
+ ],
35
+ "devDependencies": {
36
+ "typescript": "6.0.3"
37
+ },
38
+ "dependencies": {
39
+ "openapi-fetch": "^0.17.0"
40
+ },
41
+ "scripts": {
42
+ "build": "tsc -p tsconfig.json",
43
+ "test": "vitest run --config ../../vitest.config.ts",
44
+ "lint": "eslint src --max-warnings=0",
45
+ "format:check": "prettier --check src package.json tsconfig.json"
46
+ }
47
+ }