fetch-layers 0.0.0-stage → 1.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.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","names":["blob"],"sources":["../src/core/layer.ts","../src/core/error-body.ts","../src/transport/body.ts","../src/transport/retry-after.ts","../src/transport/url.ts","../src/transport/transport.ts","../src/client.ts"],"sourcesContent":["import type { Client, RequestFn } from './types';\n\n/**\n * Context that createClient passes to every layer when building the\n * pipeline. Shared by all client layers.\n */\nexport interface LayerContext {\n readonly warn?: (message: string) => void;\n}\n\n/**\n * fn is the request function produced by this layer. state - a value\n * the layer saves until attach: this is how a layer ties its state\n * to a specific client, even if the same Layer is used across\n * several clients.\n */\nexport interface LayerWrapResult {\n fn: RequestFn;\n state?: unknown;\n}\n\n/**\n * Layer. Passed to ClientOptions.layers from the outside in: the\n * first in the array wraps all subsequent layers, the last receives\n * the base transport.\n */\nexport interface Layer {\n /**\n * Name used in validation error messages. Must be unique: a\n * duplicate fails client creation. For built-ins it matches the\n * factory name.\n */\n readonly name: string;\n\n /**\n * Priority: higher means further outside. Layers must go in\n * descending stage order. If omitted, the layer skips order\n * validation. Built-ins: withIdempotency: 3, withRetry: 2,\n * withAuth: 1. To insert between built-ins: 2.5 - between\n * withIdempotency and withRetry, 1.5 - between withRetry\n * and withAuth.\n */\n readonly stage?: number;\n\n /**\n * Wraps the next function in the pipeline. Called from the inside\n * out: the last layer in the array receives the base transport.\n * state is passed back to the same layer's attach.\n */\n wrap(next: RequestFn, context: LayerContext): LayerWrapResult;\n\n /**\n * Called after client creation. For service functions that need\n * the client itself (resetRefreshCircuit). state is what wrap\n * returned for this client. An exception aborts createClient;\n * the message includes the layer name.\n */\n attach?(client: Client, state: unknown): void;\n}\n\n/**\n * Layers without stage are skipped.\n *\n * Checks name uniqueness, descending stage, and no duplicate stages:\n * with equal stage the order would be determined by position in the\n * array, which is implicit.\n *\n * @internal\n */\nexport function validateLayerOrder(layers: readonly Layer[]): void {\n const seenNames = new Set<string>();\n const seenStages = new Map<number, string>();\n let prevStage = Infinity;\n let prevName: string | undefined;\n\n for (const layer of layers) {\n if (seenNames.has(layer.name)) {\n throw new Error(\n `createClient: layer \"${layer.name}\" is passed more than once. ` +\n `Each layer must have a unique name.`,\n );\n }\n seenNames.add(layer.name);\n\n if (layer.stage === undefined) continue;\n\n if (!Number.isFinite(layer.stage)) {\n throw new Error(\n `createClient: layer \"${layer.name}\" has invalid stage ${String(layer.stage)}. ` +\n `Stage must be a finite number.`,\n );\n }\n\n if (layer.stage > prevStage) {\n throw new Error(\n `createClient: layer \"${layer.name}\" (stage ${layer.stage}) breaks the order ` +\n `after \"${prevName}\" (stage ${prevStage}). ` +\n `Expected descending stage. Built-in stages: withIdempotency=3, ` +\n `withRetry=2, withAuth=1. ` +\n `For a custom layer between withIdempotency and withRetry use stage 2.5, ` +\n `between withRetry and withAuth use stage 1.5.`,\n );\n }\n\n const stageOwner = seenStages.get(layer.stage);\n if (stageOwner !== undefined) {\n throw new Error(\n `createClient: layers \"${stageOwner}\" and \"${layer.name}\" have the same stage ` +\n `${layer.stage}. Order between them would be determined by position in the ` +\n `layers array, which is ambiguous. Use fractional stages (for example 2.5) ` +\n `to make the order explicit.`,\n );\n }\n\n seenStages.set(layer.stage, layer.name);\n\n prevStage = layer.stage;\n prevName = layer.name;\n }\n}\n\n/**\n * Applies layers from the inside out. state[i] corresponds to\n * layers[i].\n *\n * @internal\n */\nexport function applyLayers(\n base: RequestFn,\n layers: readonly Layer[],\n context: LayerContext,\n): { pipeline: RequestFn; states: unknown[] } {\n const states: unknown[] = new Array(layers.length);\n let pipeline = base;\n\n for (let i = layers.length - 1; i >= 0; i--) {\n const result = layers[i]!.wrap(pipeline, context);\n pipeline = result.fn;\n states[i] = result.state;\n }\n\n return { pipeline, states };\n}\n\n/**\n * Call order matches array order, state comes from the same\n * position. If attach throws, createClient aborts; the error\n * includes the layer name.\n *\n * @internal\n */\nexport function runAttach(\n layers: readonly Layer[],\n states: readonly unknown[],\n client: Client,\n): void {\n for (let i = 0; i < layers.length; i++) {\n const layer = layers[i]!;\n try {\n layer.attach?.(client, states[i]);\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n throw new Error(`createClient: layer \"${layer.name}\" attach threw: ${message}`, {\n cause: e,\n });\n }\n }\n}\n","type ErrorBodyContent = {\n code?: string;\n message?: string;\n fields?: Record<string, string>;\n details?: unknown;\n};\n\n/**\n * Error body parser. Passed to ClientOptions.parseErrorBody when\n * server returns errors in a format other than flat. What is not\n * extracted stays undefined, full body is in ApiError.rawBody.\n */\nexport type ErrorBodyParser = (raw: unknown) => ErrorBodyContent;\n\n/**\n * Keeps only string values: ApiError.fields promises\n * Record<string, string>. Non-string values are dropped, the full\n * original stays in rawBody.\n *\n * @internal\n */\nexport function parseFields(raw: unknown): Record<string, string> | undefined {\n if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return undefined;\n\n const result: Record<string, string> = {};\n let hasAny = false;\n\n for (const [key, value] of Object.entries(raw)) {\n if (typeof value === 'string') {\n result[key] = value;\n hasAny = true;\n }\n }\n\n return hasAny ? result : undefined;\n}\n\n/**\n * Default parser: flat JSON object or plain-text string.\n *\n * @internal\n */\nexport function parseFlatErrorBody(raw: unknown): ErrorBodyContent {\n if (typeof raw === 'string' && raw.length > 0) {\n return { message: raw };\n }\n\n if (raw && typeof raw === 'object') {\n const b = raw as Record<string, unknown>;\n return {\n code: typeof b.code === 'string' ? b.code : undefined,\n message: typeof b.message === 'string' ? b.message : undefined,\n fields: parseFields(b.fields),\n };\n }\n\n return {};\n}\n","import { ApiError, toApiError } from '../core/errors';\nimport {\n classifyBody,\n getTypeName,\n isSerializableKind,\n isUnsupportedKind,\n} from '../shared/classify-body';\n\nimport type { ResponseType } from '../core/types';\n\nclass UnsupportedBodyTypeError extends TypeError {\n readonly typeName: string;\n\n constructor(typeName: string) {\n super('Unsupported body type');\n this.typeName = typeName;\n }\n}\n\nfunction unsupportedBodyError(name: string): ApiError {\n return new ApiError({\n kind: 'serialize',\n code: 'BODY_SERIALIZATION_ERROR',\n message:\n `Unsupported value in request body: ${name}. ` +\n `Convert it to a plain object or an array before sending.`,\n });\n}\n\n/**\n * contentType === undefined: transport does not set the header. No\n * body, or the browser decides (FormData with boundary), or the app\n * set its own.\n */\nexport interface PreparedBody {\n body: BodyInit | undefined;\n contentType: string | undefined;\n}\n\n/**\n * Prepares body for fetch. Returns body and recommended Content-Type.\n * Explicit Content-Type from the app is not overwritten.\n *\n * Streams get no Content-Type: a stream may carry binary data, text,\n * JSON Lines. The type is set by the app when it matters to server.\n *\n * @throws ApiError with code BODY_SERIALIZATION_ERROR if body\n * contains Map, Set, WeakMap, WeakSet, RegExp or Error at top\n * level, or any value not JSON-serializable at any nesting level:\n * Blob, File, FormData, ArrayBuffer, TypedArray, ReadableStream,\n * URLSearchParams. JSON.stringify would turn them into {}, and\n * server would get empty object instead of data.\n */\nexport function prepareBody(value: unknown): PreparedBody {\n const kind = classifyBody(value);\n\n if (isUnsupportedKind(kind)) {\n throw unsupportedBodyError(getTypeName(value));\n }\n\n switch (kind) {\n case 'undefined':\n return { body: undefined, contentType: undefined };\n\n case 'form-data':\n return { body: value as BodyInit, contentType: undefined };\n\n case 'blob': {\n const blob = value as Blob;\n return {\n body: value as BodyInit,\n contentType: blob.type || 'application/octet-stream',\n };\n }\n\n case 'binary':\n return { body: value as BodyInit, contentType: 'application/octet-stream' };\n\n case 'stream':\n return { body: value as BodyInit, contentType: undefined };\n\n case 'url-search-params':\n return {\n body: value as BodyInit,\n contentType: 'application/x-www-form-urlencoded;charset=UTF-8',\n };\n\n case 'string':\n return { body: value as string, contentType: undefined };\n\n case 'json':\n return prepareJsonBody(value);\n }\n}\n\nfunction prepareJsonBody(value: unknown): PreparedBody {\n try {\n const json = JSON.stringify(value, (_key, val) => {\n const kind = classifyBody(val);\n if (!isSerializableKind(kind)) {\n throw new UnsupportedBodyTypeError(getTypeName(val));\n }\n return val;\n });\n\n if (json === undefined) {\n throw new TypeError('JSON.stringify returned undefined');\n }\n\n return { body: json, contentType: 'application/json' };\n } catch (e) {\n if (e instanceof UnsupportedBodyTypeError) {\n throw unsupportedBodyError(e.typeName);\n }\n\n throw new ApiError({\n kind: 'serialize',\n code: 'BODY_SERIALIZATION_ERROR',\n message: 'Failed to serialize request body to JSON',\n cause: e,\n });\n }\n}\n\n/**\n * Parses response body according to responseType.\n *\n * For json, empty body gives undefined, invalid - PARSE_ERROR with\n * content-type in the message. For 2xx and 5xx the error is marked\n * isUncertain: true, for 4xx - false.\n *\n * @param signal - abort during read is classified as abort or\n * timeout, not as parse error. For the stream branch, abort is\n * checked before returning the body: otherwise the caller would\n * get a stream after the timeout already fired.\n */\nexport async function parseResponse(\n response: Response,\n responseType: ResponseType,\n signal?: AbortSignal,\n): Promise<unknown> {\n if (signal?.aborted) {\n throw toApiError(signal.reason);\n }\n\n try {\n switch (responseType) {\n case 'json': {\n const text = await response.text();\n if (text === '') return undefined;\n return JSON.parse(text);\n }\n case 'text':\n return await response.text();\n case 'blob':\n return await response.blob();\n case 'arrayBuffer':\n return await response.arrayBuffer();\n case 'stream':\n return response.body;\n }\n } catch (e) {\n if (signal?.aborted) {\n throw toApiError(signal.reason);\n }\n\n const contentType = response.headers.get('content-type');\n throw new ApiError({\n kind: 'parse',\n code: 'PARSE_ERROR',\n message: contentType\n ? `Failed to parse response body as ${responseType} (content-type: ${contentType})`\n : `Failed to parse response body as ${responseType}`,\n status: response.status,\n isUncertain: response.status < 400 || response.status >= 500,\n cause: e,\n });\n }\n}\n\n/**\n * Error body: text, then JSON.parse.\n *\n * Returns parsed value or the original string, null if body is empty\n * or read failed.\n *\n * @param signal - abort during read is thrown as ApiError, not\n * returned as null.\n */\nexport async function readBodyAsJsonOrText(\n response: Response,\n signal?: AbortSignal,\n): Promise<unknown> {\n try {\n const text = await response.text();\n if (!text) return null;\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n } catch {\n if (signal?.aborted) {\n throw toApiError(signal.reason);\n }\n return null;\n }\n}\n","/**\n * The only HTTP date format allowed by RFC 7231: IMF-fixdate like\n * \"Sun, 06 Nov 1994 08:49:37 GMT\".\n *\n * Full shape check is needed: Date.parse() in V8 is too liberal.\n * '+5', ' 5 ', '-5 GMT', 'garbage GMT' it accepts as valid dates\n * from the distant past, Retry-After would turn into 0, and the\n * protection against request floods would be gone. Weekdays and\n * months are listed explicitly: RFC allows only these values.\n */\nconst IMF_FIXDATE_RE =\n /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), \\d{2} (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) \\d{4} \\d{2}:\\d{2}:\\d{2} GMT$/;\n\n/**\n * Milliseconds until retry, or undefined for empty and unparseable\n * header.\n *\n * The function only parses the header, minimum delay is set by\n * withRetry. Numeric format is checked strictly (/^\\d+$/): without\n * this, '1e3', '0x10', '+5', '1.5' would pass as valid numbers.\n *\n * Leading and trailing OWS is trimmed before checks: RFC 7230\n * allows spaces around header value.\n */\nexport function parseRetryAfterMs(header: string | null): number | undefined {\n if (!header) return undefined;\n\n const trimmed = header.trim();\n\n if (/^\\d+$/.test(trimmed)) {\n return Math.max(0, Number(trimmed) * 1000);\n }\n\n if (!IMF_FIXDATE_RE.test(trimmed)) {\n return undefined;\n }\n\n const timestamp = Date.parse(trimmed);\n if (Number.isFinite(timestamp)) {\n return Math.max(0, timestamp - Date.now());\n }\n\n return undefined;\n}\n","import type {\n QueryArrayFormat,\n QueryObjectFormat,\n QueryParamValue,\n QueryParams,\n} from '../core/types';\n\n/**\n * Square brackets stay readable: filter[status]=active instead\n * of filter%5Bstatus%5D=active.\n */\nfunction encodeQueryKey(key: string): string {\n return encodeURIComponent(key).replace(/%5B/g, '[').replace(/%5D/g, ']');\n}\n\nfunction encodeQueryValue(value: string): string {\n return encodeURIComponent(value);\n}\n\n/**\n * Encodes path per segment, keeping / separators. A segment is\n * decoded first, then encoded: the function is idempotent for\n * already encoded segments, John%20Doe does not become John%2520Doe.\n *\n * On invalid escape sequence the segment is encoded as is.\n */\nfunction encodePath(path: string): string {\n return path\n .split('/')\n .map((segment) => {\n if (segment === '') return '';\n try {\n return encodeURIComponent(decodeURIComponent(segment));\n } catch {\n return encodeURIComponent(segment);\n }\n })\n .join('/');\n}\n\nfunction isQueryObject(value: QueryParamValue): value is { [key: string]: QueryParamValue } {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/**\n * Serializes a single value into key=value strings. Recursively\n * walks nested objects and arrays. undefined and null are skipped,\n * empty arrays and objects too. Object keys are sorted alphabetically.\n */\nexport function serializeQueryValue(\n key: string,\n value: QueryParamValue,\n arrayFormat: QueryArrayFormat,\n objectFormat: QueryObjectFormat,\n): string[] {\n if (value === undefined || value === null) return [];\n\n if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {\n return [`${encodeQueryKey(key)}=${encodeQueryValue(String(value))}`];\n }\n\n if (Array.isArray(value)) {\n const filtered = value.filter((v) => v !== undefined && v !== null);\n if (filtered.length === 0) return [];\n\n switch (arrayFormat) {\n case 'repeat':\n return filtered.map((v) => `${encodeQueryKey(key)}=${encodeQueryValue(String(v))}`);\n case 'brackets':\n return filtered.map((v) => `${encodeQueryKey(`${key}[]`)}=${encodeQueryValue(String(v))}`);\n case 'comma':\n return [\n `${encodeQueryKey(key)}=${filtered.map((v) => encodeQueryValue(String(v))).join(',')}`,\n ];\n }\n }\n\n if (isQueryObject(value)) {\n const entries = Object.entries(value).sort(([a], [b]) => Number(a > b) - Number(a < b));\n\n switch (objectFormat) {\n case 'brackets': {\n const parts: string[] = [];\n for (const [k, v] of entries) {\n parts.push(...serializeQueryValue(`${key}[${k}]`, v, arrayFormat, objectFormat));\n }\n return parts;\n }\n case 'dots': {\n const parts: string[] = [];\n for (const [k, v] of entries) {\n parts.push(...serializeQueryValue(`${key}.${k}`, v, arrayFormat, objectFormat));\n }\n return parts;\n }\n }\n }\n\n return [];\n}\n\n/**\n * Builds URL from baseUrl, path and query params.\n *\n * Path segments are encoded: `?` and `#` inside a segment become\n * %3F and %23 instead of starting a query or a fragment. An already\n * encoded segment is kept as is, so `%3F` stays `%3F`.\n *\n * Query param keys are sorted alphabetically, including nested ones.\n * Trailing slashes on baseUrl are stripped, leading on path too:\n * /api/ + /users and /api + users both give /api/users.\n */\nexport function buildUrl(\n baseUrl: string,\n path: string,\n query?: QueryParams,\n arrayFormat: QueryArrayFormat = 'repeat',\n objectFormat: QueryObjectFormat = 'brackets',\n): string {\n const trimmedBase = baseUrl.replace(/\\/+$/, '');\n const trimmedPath = path.replace(/^\\//, '');\n const url = `${trimmedBase}/${encodePath(trimmedPath)}`;\n\n if (!query) return url;\n\n const parts: string[] = [];\n for (const key of Object.keys(query).sort()) {\n const segments = serializeQueryValue(key, query[key], arrayFormat, objectFormat);\n for (const segment of segments) parts.push(segment);\n }\n\n return parts.length > 0 ? `${url}?${parts.join('&')}` : url;\n}\n","import { parseFlatErrorBody } from '../core/error-body';\nimport { ApiError, classifyFetchError, toApiError } from '../core/errors';\nimport { isStreamingBody } from '../shared/classify-body';\nimport { setAbortTimeout, throwIfAborted } from '../shared/signals';\n\nimport { parseResponse, prepareBody, readBodyAsJsonOrText } from './body';\nimport { getHeader, mergeHeaders, setHeader } from './headers';\nimport { parseRetryAfterMs } from './retry-after';\nimport { buildUrl } from './url';\n\nimport type { ErrorBodyParser } from '../core/error-body';\nimport type {\n QueryArrayFormat,\n QueryObjectFormat,\n RequestFn,\n ResolvedRequestConfig,\n ResponseMeta,\n ResponseType,\n} from '../core/types';\n\nconst DEFAULT_TIMEOUT_MS = 10_000;\n\n/**\n * ClientOptions fields for the base transport. createClient passes\n * options here without layers and warn.\n *\n * @internal\n */\nexport interface TransportOptions {\n baseUrl: string;\n\n /** Request timeout in milliseconds. Defaults to 10000. */\n timeoutMs?: number;\n\n /** fetch function. Defaults to the global one. */\n fetch?: typeof fetch;\n\n credentials?: RequestCredentials;\n\n /**\n * Headers for all requests. Merged with per-request headers at the\n * bottom of the pipeline; per-request headers and headers from\n * layers override defaultHeaders.\n */\n defaultHeaders?: HeadersInit;\n\n queryArrayFormat?: QueryArrayFormat;\n\n queryObjectFormat?: QueryObjectFormat;\n\n /**\n * Custom error body parser. Defaults to flat shape:\n * { code, message, fields } or a plain-text string as message.\n */\n parseErrorBody?: ErrorBodyParser;\n}\n\n/**\n * Accept header value for a response type. json and text get their\n * MIME types, everything else falls back to * / *.\n */\nfunction acceptFor(responseType: ResponseType): string {\n if (responseType === 'json') return 'application/json';\n if (responseType === 'text') return 'text/plain';\n return '*/*';\n}\n\n/**\n * Runs the app error parser and keeps the structural fields alive.\n *\n * A parser that throws or returns a non-object would otherwise lose\n * status, rawBody, requestId and retryAfterMs: the exception escapes\n * to toApiError, which has no response. Fall back to the flat parser\n * and keep the parser failure in cause.\n */\nfunction runErrorParser(\n parser: ErrorBodyParser,\n rawBody: unknown,\n): { parsed: ReturnType<ErrorBodyParser>; parserError?: unknown } {\n try {\n const parsed = parser(rawBody);\n if (parsed && typeof parsed === 'object') {\n return { parsed };\n }\n return { parsed: parseFlatErrorBody(rawBody) };\n } catch (parserError) {\n return { parsed: parseFlatErrorBody(rawBody), parserError };\n }\n}\n\n/**\n * Base request function: fetch, response parsing, error\n * normalization. Takes ResolvedRequestConfig with headers in Record.\n */\nexport function createBaseRequest(options: TransportOptions): RequestFn {\n const {\n baseUrl,\n timeoutMs: defaultTimeoutMs = DEFAULT_TIMEOUT_MS,\n fetch: fetchImpl = globalThis.fetch,\n credentials: defaultCredentials,\n defaultHeaders,\n queryArrayFormat: defaultArrayFormat = 'repeat',\n queryObjectFormat: defaultObjectFormat = 'brackets',\n } = options;\n\n const errorParser = options.parseErrorBody ?? parseFlatErrorBody;\n\n return async function baseRequest<T>(config: ResolvedRequestConfig): Promise<T> {\n throwIfAborted(config.signal);\n\n const method = config.method ?? 'GET';\n\n // Timer starts before try: buildUrl and prepareBody are inside\n // try too, and finally must see timeout in any branch.\n const effectiveTimeoutMs = config.timeoutMs ?? defaultTimeoutMs;\n const timeout = setAbortTimeout(effectiveTimeoutMs);\n\n // AbortSignal.any preserves the reason: timeout stays TimeoutError,\n // not AbortError. Listeners are garbage collected, no cleanup needed.\n const signal = config.signal\n ? AbortSignal.any([config.signal, timeout.signal])\n : timeout.signal;\n\n try {\n const url = buildUrl(\n baseUrl,\n config.path,\n config.query,\n config.queryArrayFormat ?? defaultArrayFormat,\n config.queryObjectFormat ?? defaultObjectFormat,\n );\n\n // HEAD and OPTIONS have no body, cannot parse as JSON.\n const defaultResponseType: ResponseType =\n method === 'HEAD' || method === 'OPTIONS' ? 'text' : 'json';\n const responseType: ResponseType = config.responseType ?? defaultResponseType;\n\n const includeMeta = config.includeResponseMeta === true;\n\n const defaultAccept = acceptFor(responseType);\n\n // Order: Accept -> defaultHeaders -> config.headers. Headers\n // from layers (Idempotency-Key, Authorization) override\n // defaultHeaders, so a stray Idempotency-Key in defaultHeaders\n // does not break deduplication.\n const headers = mergeHeaders({ Accept: defaultAccept }, defaultHeaders, config.headers);\n\n const { body, contentType } = prepareBody(config.body);\n if (contentType !== undefined && getHeader(headers, 'Content-Type') === undefined) {\n setHeader(headers, 'Content-Type', contentType);\n }\n\n const init: RequestInit = {\n ...config.fetchOptions,\n method,\n headers,\n body,\n signal,\n };\n\n const effectiveCredentials = config.credentials ?? defaultCredentials;\n if (effectiveCredentials !== undefined) {\n init.credentials = effectiveCredentials;\n }\n\n // Streaming body requires duplex: 'half', without it fetch\n // throws TypeError.\n if (isStreamingBody(body)) {\n (init as RequestInit & { duplex: 'half' }).duplex = 'half';\n }\n\n // TypeError around fetch means network error. Only here:\n // elsewhere the source is unknown.\n let response: Response;\n try {\n response = await fetchImpl(url, init);\n } catch (e) {\n throw classifyFetchError(e);\n }\n\n const meta: ResponseMeta = {\n status: response.status,\n headers: response.headers,\n requestId: response.headers.get('X-Request-Id') ?? undefined,\n retryAfterMs: parseRetryAfterMs(response.headers.get('Retry-After')),\n };\n\n // 204 and 304 have no body. Checked before response.ok: 304\n // is not in the ok range.\n if (response.status === 204 || response.status === 304) {\n if (includeMeta) {\n return { data: undefined, meta } as unknown as T;\n }\n return undefined as T;\n }\n\n if (!response.ok) {\n const rawBody = await readBodyAsJsonOrText(response, signal);\n const { parsed, parserError } = runErrorParser(errorParser, rawBody);\n throw new ApiError({\n kind: 'http',\n status: response.status,\n code: parsed.code ?? `HTTP_${response.status}`,\n message: parsed.message ?? `HTTP ${response.status}`,\n fields: parsed.fields,\n requestId: meta.requestId,\n retryAfterMs: meta.retryAfterMs,\n rawBody,\n details: parsed.details,\n isUncertain: response.status >= 500,\n ...(parserError !== undefined ? { cause: parserError } : {}),\n });\n }\n\n // HEAD and OPTIONS return only metadata: body is discarded\n // even if server sent one.\n if (!response.body || method === 'HEAD' || method === 'OPTIONS') {\n if (includeMeta) {\n return { data: undefined, meta } as unknown as T;\n }\n return undefined as T;\n }\n\n const data = await parseResponse(response, responseType, signal);\n\n if (includeMeta) {\n return { data, meta } as unknown as T;\n }\n\n return data as T;\n } catch (e) {\n // ApiError (http, parse, network, timeout, abort) is thrown\n // inside try, so toApiError is idempotent.\n throw toApiError(e);\n } finally {\n timeout.clear();\n }\n };\n}\n","import { ApiError, toApiError } from './core/errors';\nimport { applyLayers, runAttach, validateLayerOrder } from './core/layer';\nimport { assertNonEmptyString } from './shared/validators';\nimport { mergeHeaders } from './transport/headers';\nimport { createBaseRequest, type TransportOptions } from './transport/transport';\n\nimport type { Layer, LayerContext } from './core/layer';\nimport type {\n Client,\n HttpMethod,\n InternalRequestConfig,\n RequestConfig,\n RequestOptions,\n ResolvedRequestConfig,\n ResponseWithMeta,\n} from './core/types';\n\nconst MIN_TIMEOUT_MS = 100;\n\n/**\n * Internal request function. Public client.request takes RequestConfig\n * without includeResponseMeta.\n */\ntype PublicRequestFn = <T = unknown>(config: InternalRequestConfig) => Promise<T>;\n\n/** Client options: TransportOptions plus warn and layers. */\nexport interface ClientOptions extends TransportOptions {\n /**\n * Where misuse warnings go. Defaults to console.warn, null disables.\n */\n warn?: ((message: string) => void) | null;\n\n /**\n * Client layers. Empty by default. Order and stage are described\n * in Layer.\n */\n layers?: readonly Layer[];\n}\n\n/**\n * Converts public RequestConfig to internal shape: headers are\n * normalized to Record. undefined stays undefined, so layers do not\n * see an empty object instead of missing headers.\n */\nfunction resolveConfig(config: InternalRequestConfig): ResolvedRequestConfig {\n return {\n ...config,\n headers: config.headers ? mergeHeaders(config.headers) : undefined,\n };\n}\n\n/**\n * Validates timeoutMs: number >= MIN_TIMEOUT_MS. Separate from\n * assertPositiveNumber: different threshold and message.\n */\nfunction assertTimeout(value: unknown, prefix: string): asserts value is number {\n if (typeof value !== 'number' || !Number.isFinite(value) || value < MIN_TIMEOUT_MS) {\n throw new Error(\n `${prefix}: timeoutMs must be a number >= ${MIN_TIMEOUT_MS} ms, got ${String(value)}`,\n );\n }\n}\n\n/**\n * undefined means console.warn, null disables, a function is used\n * as is.\n *\n * The default is wrapped in an arrow function: console.warn as a\n * method depends on `this`, and the pipeline calls it without context.\n */\nfunction resolveWarn(value: ClientOptions['warn']): ((message: string) => void) | undefined {\n if (value === undefined) return (message) => console.warn(message);\n if (value === null) return undefined;\n return value;\n}\n\n/**\n * Builds the pipeline from base transport and layers, validates\n * order.\n *\n * @throws Error on invalid config: empty baseUrl, invalid or too\n * small timeoutMs, unavailable fetch, layer order violation.\n */\nexport function createClient(options: ClientOptions): Client {\n validateOptions(options);\n\n const layers = options.layers ?? [];\n\n validateLayerOrder(layers);\n\n const warn = resolveWarn(options.warn);\n\n const context: LayerContext = {\n warn,\n };\n\n const baseRequest = createBaseRequest(options);\n const { pipeline, states } = applyLayers(baseRequest, layers, context);\n\n const wrapped: PublicRequestFn = async <T>(config: InternalRequestConfig): Promise<T> => {\n const resolved = resolveConfig(config);\n\n let finalConfig: ResolvedRequestConfig;\n try {\n assertNonEmptyString(resolved.path, 'client: path');\n\n if (resolved.timeoutMs !== undefined) {\n assertTimeout(resolved.timeoutMs, 'client');\n }\n\n // Method is uppercased: layers (withIdempotency, withRetry)\n // compare it to POST, PUT and others. Fetch normalizes anyway,\n // but layers get the config before fetch.\n finalConfig = {\n ...resolved,\n method: (resolved.method ?? 'GET').toUpperCase() as HttpMethod,\n origin: options.baseUrl,\n };\n } catch (e) {\n throw new ApiError({\n kind: 'unknown',\n code: 'INVALID_REQUEST_CONFIG',\n message: e instanceof Error ? e.message : String(e),\n cause: e,\n });\n }\n\n // Custom layers may throw errors other than ApiError. Contract:\n // everything thrown by the client is normalized. toApiError is\n // idempotent and returns the same object for transport errors.\n try {\n return await pipeline<T>(finalConfig);\n } catch (e) {\n throw toApiError(e);\n }\n };\n\n const client = makeClient(wrapped);\n runAttach(layers, states, client);\n\n return client;\n}\n\n/**\n * Validation at client creation, not at first request.\n */\nfunction validateOptions(options: ClientOptions): void {\n assertNonEmptyString(options.baseUrl, 'createClient: baseUrl');\n\n if (options.timeoutMs !== undefined) {\n assertTimeout(options.timeoutMs, 'createClient');\n }\n\n const fetchImpl = options.fetch ?? globalThis.fetch;\n if (typeof fetchImpl !== 'function') {\n throw new Error(\n 'createClient: fetch is not available. Pass it via the fetch option ' +\n 'or use an environment with a global fetch (Node >= 22.18, modern browser).',\n );\n }\n}\n\nfunction makeBodyless(request: PublicRequestFn, method: HttpMethod) {\n return <T>(path: string, options?: RequestOptions): Promise<T> =>\n request<T>({ ...options, path, method });\n}\n\nfunction makeBody(request: PublicRequestFn, method: HttpMethod) {\n return <T>(path: string, body?: unknown, options?: RequestOptions): Promise<T> =>\n request<T>({ ...options, path, method, body });\n}\n\nfunction makeMetaOnly(request: PublicRequestFn, method: 'HEAD' | 'OPTIONS') {\n return (path: string, options?: RequestOptions): Promise<ResponseWithMeta<undefined>> =>\n request<ResponseWithMeta<undefined>>({\n ...options,\n path,\n method,\n includeResponseMeta: true,\n });\n}\n\nfunction makeClient(request: PublicRequestFn): Client {\n return {\n request: <T>(config: RequestConfig) => request<T>(config),\n requestWithMeta: <T>(config: RequestConfig) =>\n request<ResponseWithMeta<T>>({ ...config, includeResponseMeta: true }),\n\n get: makeBodyless(request, 'GET'),\n post: makeBody(request, 'POST'),\n put: makeBody(request, 'PUT'),\n patch: makeBody(request, 'PATCH'),\n delete: makeBody(request, 'DELETE'),\n\n head: makeMetaOnly(request, 'HEAD'),\n options: makeMetaOnly(request, 'OPTIONS'),\n };\n}\n"],"mappings":"qPAqEA,SAAgB,EAAmB,EAAgC,CACjE,IAAM,EAAY,IAAI,IAChB,EAAa,IAAI,IACnB,EAAY,IACZ,EAEJ,IAAK,IAAM,KAAS,EAAQ,CAC1B,GAAI,EAAU,IAAI,EAAM,IAAI,EAC1B,MAAU,MACR,wBAAwB,EAAM,KAAK,gEAErC,EAIF,GAFA,EAAU,IAAI,EAAM,IAAI,EAEpB,EAAM,QAAU,IAAA,GAAW,SAE/B,GAAI,CAAC,OAAO,SAAS,EAAM,KAAK,EAC9B,MAAU,MACR,wBAAwB,EAAM,KAAK,sBAAsB,OAAO,EAAM,KAAK,EAAE,iCAE/E,EAGF,GAAI,EAAM,MAAQ,EAChB,MAAU,MACR,wBAAwB,EAAM,KAAK,WAAW,EAAM,MAAM,4BAC9C,EAAS,WAAW,EAAU,iNAK5C,EAGF,IAAM,EAAa,EAAW,IAAI,EAAM,KAAK,EAC7C,GAAI,IAAe,IAAA,GACjB,MAAU,MACR,yBAAyB,EAAW,SAAS,EAAM,KAAK,wBACnD,EAAM,MAAM,kKAGnB,EAGF,EAAW,IAAI,EAAM,MAAO,EAAM,IAAI,EAEtC,EAAY,EAAM,MAClB,EAAW,EAAM,IACnB,CACF,CAQA,SAAgB,EACd,EACA,EACA,EAC4C,CAC5C,IAAM,EAAwB,MAAM,EAAO,MAAM,EAC7C,EAAW,EAEf,IAAK,IAAI,EAAI,EAAO,OAAS,EAAG,GAAK,EAAG,IAAK,CAC3C,IAAM,EAAS,EAAO,EAAE,CAAE,KAAK,EAAU,CAAO,EAChD,EAAW,EAAO,GAClB,EAAO,GAAK,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CAAE,GAAG,EAAS,OAAM,SAAQ,MAAK,CAAC,CACjD,CAEA,SAAS,EAAa,EAA0B,EAA4B,CAC1E,OAAQ,EAAc,IACpB,EAAqC,CACnC,GAAG,EACH,OACA,SACA,oBAAqB,EACvB,CAAC,CACL,CAEA,SAAS,EAAW,EAAkC,CACpD,MAAO,CACL,QAAa,GAA0B,EAAW,CAAM,EACxD,gBAAqB,GACnB,EAA6B,CAAE,GAAG,EAAQ,oBAAqB,EAAK,CAAC,EAEvE,IAAK,EAAa,EAAS,KAAK,EAChC,KAAM,EAAS,EAAS,MAAM,EAC9B,IAAK,EAAS,EAAS,KAAK,EAC5B,MAAO,EAAS,EAAS,OAAO,EAChC,OAAQ,EAAS,EAAS,QAAQ,EAElC,KAAM,EAAa,EAAS,MAAM,EAClC,QAAS,EAAa,EAAS,SAAS,CAC1C,CACF"}
@@ -0,0 +1,133 @@
1
+ import { t as Layer } from "./layer-C5h5TXG6.mjs";
2
+ //#region src/layers/auth/types.d.ts
3
+ /**
4
+ * Session expiry reason. Passed to onSessionExpired.
5
+ *
6
+ * - refresh-rejected: server rejected token refresh (401);
7
+ * - refresh-forbidden: server forbade refresh (403);
8
+ * - token-rejected: after a successful refresh the new token was
9
+ * rejected too.
10
+ */
11
+ type SessionExpiredReason = 'refresh-rejected' | 'refresh-forbidden' | 'token-rejected';
12
+ /**
13
+ * Session refresh result.
14
+ *
15
+ * success. Token refreshed. If headers is set, the client uses it for
16
+ * the retry, otherwise calls getAuthHeaders. Prefer returning
17
+ * headers: this closes the race when the state is not updated yet
18
+ * but the request is already retrying.
19
+ *
20
+ * definitely-failed. Session is dead. The client calls
21
+ * onSessionExpired and rethrows the original 401.
22
+ *
23
+ * temporarily-failed. Session may still be alive. The client
24
+ * rethrows the error but does not call onSessionExpired or clear.
25
+ *
26
+ * error is any value. The client normalizes it: TypeError becomes
27
+ * network, AbortError and TimeoutError - the matching kind,
28
+ * everything else - unknown.
29
+ */
30
+ type RefreshResult = {
31
+ status: 'success';
32
+ headers?: Record<string, string>;
33
+ } | {
34
+ status: 'definitely-failed';
35
+ reason: SessionExpiredReason;
36
+ } | {
37
+ status: 'temporarily-failed';
38
+ error: unknown;
39
+ };
40
+ /**
41
+ * Auth provider. Implemented by the app: the library does not store
42
+ * tokens, it only asks for ready headers.
43
+ *
44
+ * refresh must not use the client with withAuth: a 401 from the
45
+ * refresh endpoint would go back into withAuth and loop. Use a
46
+ * separate client without the auth layer for the refresh endpoint.
47
+ */
48
+ interface SessionProvider {
49
+ /**
50
+ * Auth headers: one or several (Authorization, X-CSRF-Token,
51
+ * X-API-Key). May be async.
52
+ *
53
+ * @throws On error the client wraps the exception in ApiError with
54
+ * code AUTH_PROVIDER_ERROR and does not send the request.
55
+ */
56
+ getAuthHeaders(): Record<string, string> | Promise<Record<string, string>>;
57
+ /**
58
+ * Refreshes the session. Called on 401. Concurrent 401s produce one
59
+ * refresh call, the rest wait for its result.
60
+ *
61
+ * @param signal - abort on refreshTimeoutMs. Pass it to your fetch:
62
+ * fetch(url, { signal }). Optional: a provider without it still
63
+ * matches the interface, but will not be aborted on timeout.
64
+ */
65
+ refresh(signal?: AbortSignal): Promise<RefreshResult>;
66
+ /**
67
+ * Resets session state. Called on definitely-failed. Exceptions
68
+ * are ignored. Must be idempotent.
69
+ */
70
+ clear?(): void;
71
+ }
72
+ //#endregion
73
+ //#region src/layers/auth/layer.d.ts
74
+ interface AuthOptions {
75
+ /** Required. */
76
+ provider: SessionProvider;
77
+ /**
78
+ * Called on final session expiry. The app decides what to do:
79
+ * show a modal, redirect, nothing. Exceptions are ignored: a
80
+ * callback failure does not replace the original 401.
81
+ */
82
+ onSessionExpired?: (reason: SessionExpiredReason) => void;
83
+ /**
84
+ * Blocking duration after a temporary refresh failure, in
85
+ * milliseconds. Defaults to 5000. Must be positive.
86
+ *
87
+ * Used by the breaker (blocks new refreshes after a failure) and
88
+ * by cooldown (blocks a second refresh right after a successful
89
+ * one).
90
+ */
91
+ circuitBreakerMs?: number;
92
+ /**
93
+ * Timeout of a single refresh attempt, in milliseconds. Defaults
94
+ * to 30000.
95
+ *
96
+ * The provider gets an AbortSignal and may pass it to its fetch.
97
+ * If the signal is ignored, the library-side timeout does not
98
+ * fire: bound refresh in SessionProvider.refresh instead.
99
+ */
100
+ refreshTimeoutMs?: number;
101
+ /**
102
+ * Called when the token refresh breaker opens. The breaker opens
103
+ * after a temporary refresh failure and blocks new attempts for
104
+ * circuitBreakerMs.
105
+ */
106
+ onCircuitOpen?: () => void;
107
+ /**
108
+ * Called when the breaker closes. Closes either after
109
+ * circuitBreakerMs or manually via resetRefreshCircuit(client).
110
+ */
111
+ onCircuitClose?: () => void;
112
+ }
113
+ /**
114
+ * Auth layer.
115
+ *
116
+ * Adds headers from provider before each request. On 401 starts a
117
+ * token refresh and retries the original request once. On a temporary
118
+ * refresh failure rethrows the error without logging the user out. On
119
+ * a final failure calls onSessionExpired.
120
+ *
121
+ * Refresh starts only on 401: 403 does not trigger it.
122
+ *
123
+ * If a successful refresh happened less than circuitBreakerMs ago and
124
+ * the request got 401 again, the layer retries with the current
125
+ * headers without a new refresh.
126
+ *
127
+ * Layer is a template: if the same object is passed to two
128
+ * createClient calls, each gets its own RefreshManager.
129
+ */
130
+ declare function withAuth(options: AuthOptions): Layer;
131
+ //#endregion
132
+ export { SessionProvider as a, SessionExpiredReason as i, withAuth as n, RefreshResult as r, AuthOptions as t };
133
+ //# sourceMappingURL=layer-3tx7wJdK.d.mts.map
@@ -0,0 +1,104 @@
1
+ import { m as ResolvedRequestConfig, t as Layer } from "./layer-C5h5TXG6.mjs";
2
+ import { t as ApiError } from "./errors-BITxtr5V.mjs";
3
+ //#region src/layers/retry/layer.d.ts
4
+ interface RetryOptions {
5
+ /**
6
+ * Max attempts, including the first one. Defaults to 3, minimum 1.
7
+ */
8
+ maxAttempts?: number;
9
+ /**
10
+ * Initial delay in milliseconds. Defaults to 300. Values below
11
+ * MIN_RETRY_MS are raised to the minimum.
12
+ */
13
+ baseDelayMs?: number;
14
+ /**
15
+ * Upper bound of the delay. Defaults to 10000. Caps the computed
16
+ * delay and acts as threshold for Retry-After: if the server asked
17
+ * for more, the retry is skipped.
18
+ *
19
+ * Must be >= baseDelayMs after it was raised to MIN_RETRY_MS,
20
+ * otherwise withRetry throws.
21
+ */
22
+ maxDelayMs?: number;
23
+ /**
24
+ * Spread around the computed delay, defaults to 0.15 (+-15%).
25
+ * 0 disables the spread, 1 gives +-100%. Not applied to
26
+ * Retry-After. Value in [0, 1].
27
+ */
28
+ jitterRatio?: number;
29
+ /**
30
+ * Warn about a mutating retry without idempotency header. Defaults
31
+ * to true.
32
+ *
33
+ * No warning when withIdempotency applied a key, the app set
34
+ * Idempotency-Key itself, or passed skipIdempotency: true. Once per
35
+ * method and root path segment: for DELETE /sessions/123 the root
36
+ * segment is sessions.
37
+ */
38
+ warnOnUnsafeRetry?: boolean;
39
+ /** Retry network errors (kind network). Defaults to true. */
40
+ retryOnNetwork?: boolean;
41
+ /**
42
+ * Retry timeouts (kind timeout). Defaults to true. For unsafe
43
+ * methods a retry without Idempotency-Key may create a duplicate.
44
+ */
45
+ retryOnTimeout?: boolean;
46
+ /**
47
+ * Retry policy. Defaults to isRetryable, adjusted by retryOnNetwork
48
+ * and retryOnTimeout. Cancel and auth errors are not retried even
49
+ * if the function returns true.
50
+ *
51
+ * On callback failure the default policy is used, the error goes
52
+ * to warn.
53
+ *
54
+ * @param attempt - failed attempt number, 1-based.
55
+ */
56
+ shouldRetry?: (error: ApiError, attempt: number) => boolean;
57
+ /**
58
+ * Delay before retry. Not applied when the server sent Retry-After.
59
+ * Result is clamped to [MIN_RETRY_MS, maxDelayMs].
60
+ *
61
+ * On callback failure the default delay is used, the error goes
62
+ * to warn.
63
+ *
64
+ * @param attempt - failed attempt number, 1-based.
65
+ */
66
+ computeDelay?: (attempt: number, error: ApiError) => number;
67
+ /**
68
+ * Before each retry. May return a new config (e.g. replace
69
+ * Idempotency-Key on 409) or stop retries by returning
70
+ * skipRetry: true - the error is rethrown at once.
71
+ *
72
+ * Runs only when shouldRetry allowed the retry, so a status the
73
+ * default policy does not retry (409, 404, 400) never reaches it.
74
+ * To handle 409 here, add it to shouldRetry.
75
+ *
76
+ * @param attempt - attempt number from 1. First retry: attempt === 1.
77
+ */
78
+ onBeforeRetry?: (config: ResolvedRequestConfig, attempt: number, error: ApiError) => ResolvedRequestConfig | void;
79
+ /** Pause between attempts. Defaults to setTimeout with abort. */
80
+ sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;
81
+ }
82
+ /**
83
+ * Automatic retry layer.
84
+ *
85
+ * Retries network errors, timeouts, 5xx, 408 and 429. Does not retry
86
+ * cancel, auth errors and other 4xx.
87
+ *
88
+ * Delays are exponential with +-15% spread (300, 600, 1200 ms), upper
89
+ * bound is maxDelayMs.
90
+ *
91
+ * Retry-After from the response replaces the computed delay. If the
92
+ * value is above maxDelayMs, the retry is skipped: the server asks to
93
+ * wait longer than the app is ready to.
94
+ *
95
+ * Retries are disabled for streaming bodies: a stream is single-use,
96
+ * a second fetch throws TypeError, which transport takes for a
97
+ * network error.
98
+ *
99
+ * @throws Error on invalid options.
100
+ */
101
+ declare function withRetry(options?: RetryOptions): Layer;
102
+ //#endregion
103
+ export { withRetry as n, RetryOptions as t };
104
+ //# sourceMappingURL=layer-BvZMV3L4.d.mts.map
@@ -0,0 +1,247 @@
1
+ //#region src/core/types.d.ts
2
+ type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'HEAD' | 'OPTIONS';
3
+ /**
4
+ * Format for parsing successful responses. Defaults to json.
5
+ *
6
+ * - json: empty body returns undefined, not an error;
7
+ * - text: CSV, HTML, plain text;
8
+ * - blob: binary data with a MIME type;
9
+ * - arrayBuffer: binary data without a MIME type;
10
+ * - stream: ReadableStream<Uint8Array>.
11
+ */
12
+ type ResponseType = 'json' | 'text' | 'blob' | 'arrayBuffer' | 'stream';
13
+ /** Numbers and booleans are stringified automatically. */
14
+ type QueryParamPrimitive = string | number | boolean;
15
+ /**
16
+ * Primitive, array of primitives, or nested object. undefined and
17
+ * null are skipped.
18
+ */
19
+ type QueryParamValue = QueryParamPrimitive | undefined | null | Array<QueryParamPrimitive | undefined | null> | QueryParamObject;
20
+ interface QueryParamObject {
21
+ [key: string]: QueryParamValue;
22
+ }
23
+ type QueryParams = Record<string, QueryParamValue>;
24
+ /**
25
+ * - repeat: ?ids=1&ids=2. Default.
26
+ * - brackets: ?ids[]=1&ids[]=2.
27
+ * - comma: ?ids=1,2.
28
+ */
29
+ type QueryArrayFormat = 'repeat' | 'brackets' | 'comma';
30
+ /**
31
+ * - brackets: ?filter[status]=active. Default.
32
+ * - dots: ?filter.status=active.
33
+ */
34
+ type QueryObjectFormat = 'brackets' | 'dots';
35
+ /**
36
+ * HTTP response metadata. Returned by requestWithMeta, head and
37
+ * options.
38
+ */
39
+ interface ResponseMeta {
40
+ status: number;
41
+ headers: Headers;
42
+ /** X-Request-Id, if server returned one. */
43
+ requestId?: string;
44
+ /** Retry-After in milliseconds, uncapped. */
45
+ retryAfterMs?: number;
46
+ }
47
+ interface ResponseWithMeta<T> {
48
+ data: T;
49
+ meta: ResponseMeta;
50
+ }
51
+ /**
52
+ * Request configuration. In shorthand methods like client.get,
53
+ * path, method and body are set by the method and are not part
54
+ * of RequestOptions.
55
+ */
56
+ interface RequestConfig {
57
+ /**
58
+ * Path relative to baseUrl, e.g. `/orders`. Without a query
59
+ * string: pass params via query.
60
+ *
61
+ * Segments are encoded automatically: `/users/John Doe` goes out
62
+ * as `/users/John%20Doe`.
63
+ */
64
+ path: string;
65
+ /** Defaults to GET. */
66
+ method?: HttpMethod;
67
+ /**
68
+ * Body format is inferred from the type: JSON object and array
69
+ * are sent as JSON, FormData as multipart, Blob and File as
70
+ * binary data, ArrayBuffer and TypedArray as
71
+ * application/octet-stream, ReadableStream as a stream,
72
+ * URLSearchParams as form-urlencoded, string as is.
73
+ *
74
+ * An explicit Content-Type is not overwritten.
75
+ */
76
+ body?: unknown;
77
+ /**
78
+ * Request headers: Record, Headers or an array of pairs. Header
79
+ * names are case-insensitive.
80
+ */
81
+ headers?: HeadersInit;
82
+ query?: QueryParams;
83
+ /**
84
+ * Abort signal. Merged with the internal timeout: whichever fires
85
+ * first wins, the reason is preserved.
86
+ */
87
+ signal?: AbortSignal;
88
+ /**
89
+ * Request timeout in ms. Overrides the client's timeoutMs for this
90
+ * request. Must be >= 100.
91
+ */
92
+ timeoutMs?: number;
93
+ /**
94
+ * Skip auth and 401 handling. For requests that create a session.
95
+ */
96
+ skipAuth?: boolean;
97
+ /** Skip automatic retries. */
98
+ skipRetry?: boolean;
99
+ /** Skip adding idempotency header. */
100
+ skipIdempotency?: boolean;
101
+ /** Explicit idempotency scope. Defaults to "${method} ${path}". */
102
+ idempotencyScope?: string;
103
+ /** Format for parsing response body. Defaults to json. */
104
+ responseType?: ResponseType;
105
+ /** Cookie mode: omit, same-origin or include. */
106
+ credentials?: RequestCredentials;
107
+ /** Query array format. Overrides the client setting. */
108
+ queryArrayFormat?: QueryArrayFormat;
109
+ /** Query object format. Overrides the client setting. */
110
+ queryObjectFormat?: QueryObjectFormat;
111
+ /**
112
+ * Extra fetch options. method, headers, body, signal, credentials
113
+ * and duplex are ignored.
114
+ */
115
+ fetchOptions?: Partial<Omit<RequestInit, 'method' | 'headers' | 'body' | 'signal' | 'credentials' | 'duplex'>>;
116
+ }
117
+ /**
118
+ * Config with response metadata flag. Used inside requestWithMeta,
119
+ * head and options: the public RequestConfig does not expose it,
120
+ * otherwise a stray call from JS could get ResponseWithMeta instead
121
+ * of a plain body.
122
+ *
123
+ * @internal
124
+ */
125
+ interface InternalRequestConfig extends RequestConfig {
126
+ includeResponseMeta?: true;
127
+ }
128
+ /**
129
+ * Internal config: headers are normalized to Record. Layers and
130
+ * transport receive this type after client.ts called mergeHeaders
131
+ * on the public RequestConfig.
132
+ */
133
+ interface ResolvedRequestConfig extends Omit<InternalRequestConfig, 'headers'> {
134
+ headers?: Record<string, string>;
135
+ /**
136
+ * Set by withIdempotency. withRetry reads the marker to decide
137
+ * whether retrying a mutating method is safe.
138
+ *
139
+ * The field is set both when withIdempotency generated a key and
140
+ * when the app sets it manually. headerName is for debugging,
141
+ * withRetry does not rely on it.
142
+ *
143
+ * @internal
144
+ */
145
+ idempotency?: {
146
+ headerName: string;
147
+ key: string;
148
+ };
149
+ /**
150
+ * Client baseUrl, set by client.ts. Layers run before transport
151
+ * joins baseUrl with path, so withIdempotency needs it to tell two
152
+ * APIs on the same storage apart.
153
+ *
154
+ * @internal
155
+ */
156
+ origin?: string;
157
+ }
158
+ /**
159
+ * RequestConfig without path, method and body. Used in shorthand
160
+ * methods like client.get.
161
+ */
162
+ type RequestOptions = Omit<RequestConfig, 'path' | 'method' | 'body'>;
163
+ /** Low-level request function that the pipeline is built from. */
164
+ type RequestFn = <T = unknown>(config: ResolvedRequestConfig) => Promise<T>;
165
+ /**
166
+ * HTTP client. Created by createClient.
167
+ *
168
+ * get, post, put, patch, delete return parsed body. head and
169
+ * options return { data, meta }: no body, metadata is the main
170
+ * result. requestWithMeta exposes metadata for any HTTP method.
171
+ */
172
+ interface Client {
173
+ /** Request with any HTTP method. */
174
+ request: <T = unknown>(config: RequestConfig) => Promise<T>;
175
+ /** Request with response metadata: { data, meta }. */
176
+ requestWithMeta: <T = unknown>(config: RequestConfig) => Promise<ResponseWithMeta<T>>;
177
+ get: <T = unknown>(path: string, options?: RequestOptions) => Promise<T>;
178
+ post: <T = unknown>(path: string, body?: unknown, options?: RequestOptions) => Promise<T>;
179
+ put: <T = unknown>(path: string, body?: unknown, options?: RequestOptions) => Promise<T>;
180
+ patch: <T = unknown>(path: string, body?: unknown, options?: RequestOptions) => Promise<T>;
181
+ /**
182
+ * Accepts an optional body. HTTP spec leaves DELETE body semantics
183
+ * undefined, but many APIs support it.
184
+ */
185
+ delete: <T = unknown>(path: string, body?: unknown, options?: RequestOptions) => Promise<T>;
186
+ /** Headers only. data is always undefined. */
187
+ head: (path: string, options?: RequestOptions) => Promise<ResponseWithMeta<undefined>>;
188
+ /** Allowed methods for a resource. data is always undefined. */
189
+ options: (path: string, options?: RequestOptions) => Promise<ResponseWithMeta<undefined>>;
190
+ }
191
+ //#endregion
192
+ //#region src/core/layer.d.ts
193
+ /**
194
+ * Context that createClient passes to every layer when building the
195
+ * pipeline. Shared by all client layers.
196
+ */
197
+ interface LayerContext {
198
+ readonly warn?: (message: string) => void;
199
+ }
200
+ /**
201
+ * fn is the request function produced by this layer. state - a value
202
+ * the layer saves until attach: this is how a layer ties its state
203
+ * to a specific client, even if the same Layer is used across
204
+ * several clients.
205
+ */
206
+ interface LayerWrapResult {
207
+ fn: RequestFn;
208
+ state?: unknown;
209
+ }
210
+ /**
211
+ * Layer. Passed to ClientOptions.layers from the outside in: the
212
+ * first in the array wraps all subsequent layers, the last receives
213
+ * the base transport.
214
+ */
215
+ interface Layer {
216
+ /**
217
+ * Name used in validation error messages. Must be unique: a
218
+ * duplicate fails client creation. For built-ins it matches the
219
+ * factory name.
220
+ */
221
+ readonly name: string;
222
+ /**
223
+ * Priority: higher means further outside. Layers must go in
224
+ * descending stage order. If omitted, the layer skips order
225
+ * validation. Built-ins: withIdempotency: 3, withRetry: 2,
226
+ * withAuth: 1. To insert between built-ins: 2.5 - between
227
+ * withIdempotency and withRetry, 1.5 - between withRetry
228
+ * and withAuth.
229
+ */
230
+ readonly stage?: number;
231
+ /**
232
+ * Wraps the next function in the pipeline. Called from the inside
233
+ * out: the last layer in the array receives the base transport.
234
+ * state is passed back to the same layer's attach.
235
+ */
236
+ wrap(next: RequestFn, context: LayerContext): LayerWrapResult;
237
+ /**
238
+ * Called after client creation. For service functions that need
239
+ * the client itself (resetRefreshCircuit). state is what wrap
240
+ * returned for this client. An exception aborts createClient;
241
+ * the message includes the layer name.
242
+ */
243
+ attach?(client: Client, state: unknown): void;
244
+ }
245
+ //#endregion
246
+ export { ResponseWithMeta as _, QueryArrayFormat as a, QueryParamPrimitive as c, RequestConfig as d, RequestFn as f, ResponseType as g, ResponseMeta as h, HttpMethod as i, QueryParamValue as l, ResolvedRequestConfig as m, LayerContext as n, QueryObjectFormat as o, RequestOptions as p, Client as r, QueryParamObject as s, Layer as t, QueryParams as u };
247
+ //# sourceMappingURL=layer-C5h5TXG6.d.mts.map