openapi-result 0.0.0-stage → 0.1.1

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 m1chlcz
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 CHANGED
@@ -1,3 +1,168 @@
1
- # Temporary Holding Version
1
+ # openapi-result
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A typed OpenAPI client with a Result union and bounded RFC 7807 problem
4
+ normalization. The package has no runtime dependencies.
5
+
6
+ The client turns every HTTP failure, timeout, abort and network error into a
7
+ return value. Invalid caller input, such as a circular JSON body, can still
8
+ throw before the request starts.
9
+
10
+ ## Requirements
11
+
12
+ - Node.js 20.3 or later (continuous integration tests Node 24).
13
+ - TypeScript 5.0 or later.
14
+ - A runtime with the global `fetch` API, `AbortSignal.timeout` and
15
+ `AbortSignal.any` (Chrome 116+, Firefox 124+, Safari 17.4+, Node 20.3+).
16
+
17
+ ## Install
18
+
19
+ ```sh
20
+ npm install openapi-result
21
+ ```
22
+
23
+ ## Quick start
24
+
25
+ First, generate a `paths` type with your OpenAPI generator. This example uses
26
+ `openapi-typescript`:
27
+
28
+ ```sh
29
+ npx openapi-typescript ./openapi.yaml -o ./src/schema.d.ts
30
+ ```
31
+
32
+ Then create a client and call an operation:
33
+
34
+ ```ts
35
+ import { createApi } from "openapi-result";
36
+ import type { paths } from "./schema";
37
+
38
+ const api = createApi<paths>({
39
+ baseUrl: "https://api.example.test",
40
+ onUnauthorized: (path) => {
41
+ console.error("Unauthorized request:", path);
42
+ },
43
+ });
44
+
45
+ const result = await api.fetch("/v1/items/{id}", "get", {
46
+ pathParams: { id: "item-1" },
47
+ query: { locale: "en" },
48
+ timeoutMs: 5000,
49
+ });
50
+
51
+ if (result.ok) {
52
+ console.log(result.status, result.data);
53
+ } else {
54
+ console.error(result.problem.code, result.problem.title);
55
+ }
56
+ ```
57
+
58
+ The client stores no application schema. The `paths` type supplies every path,
59
+ method, parameter and response type.
60
+
61
+ ## The Result contract
62
+
63
+ - Every call returns a promise of `ApiResult<T>`.
64
+ - `ok: true` carries `status`, `data` and `headers`.
65
+ - `ok: false` carries `problem` and `headers`.
66
+ - The client returns `undefined` data for status 204, status 304 and HEAD
67
+ requests.
68
+ - A JSON response maps to the declared data type.
69
+ - Any other success body maps to `ArrayBuffer`.
70
+
71
+ ## The problem contract
72
+
73
+ `ApiProblem` describes every failure:
74
+
75
+ | Field | Type | Notes |
76
+ | --- | --- | --- |
77
+ | `status` | `number` | The HTTP status code, or 0 for a client-side failure |
78
+ | `code` | `string` | The error code. The default is `http_error` |
79
+ | `title` | `string` | The short summary. The default is `HTTP <status>` |
80
+ | `detail` | `string` | The explanation, or an empty string |
81
+ | `field_errors` | `Record<string, string>` | The field messages |
82
+ | `request_id` | `string` | The `x-request-id` value, or the argument value |
83
+
84
+ The client bounds every problem:
85
+
86
+ - The client truncates text to 500 characters.
87
+ - The client keeps at most 50 field errors.
88
+ - The client reads at most 64 KiB of an error body.
89
+ - The client releases a non-JSON error body without a read.
90
+
91
+ The client builds a synthetic problem for local failures. The codes are:
92
+
93
+ - `client_invalid_timeout`
94
+ - `client_timeout`
95
+ - `client_aborted`
96
+ - `client_network_error`
97
+
98
+ A server response that cannot be decoded produces `invalid_response`. That
99
+ problem carries the HTTP status.
100
+
101
+ ## Request behavior
102
+
103
+ - Path parameters pass through `encodeURIComponent`.
104
+ - Query values skip `undefined` and `null`.
105
+ - A JSON body gets the `application/json` content type. A caller content type
106
+ wins.
107
+ - An `ArrayBuffer` or `Blob` body passes through without a content type.
108
+ - Every request uses `credentials: "same-origin"` and `redirect: "error"`.
109
+ - A caller `signal` and the timeout signal combine with `AbortSignal.any`.
110
+ - A 401 response calls `onUnauthorized(path)`.
111
+ - A timeout value must be an integer from 0 to 2147483647.
112
+
113
+ ## The type layer
114
+
115
+ The package exports these types: `PathKey`, `MethodOf`, `OperationOf`,
116
+ `PathParamsOf`, `QueryOf`, `HeaderParamsOf`, `ContentOf`, `JsonBodyOf`,
117
+ `BinaryBodyOf`, `RequiredKeysOf`, `PathInitOf`, `QueryInitOf`, `BodyInitOf`,
118
+ `HeadersInitOf`, `ApiInit`, `ApiArgs`, `DataOf`, `ApiResult`, `ApiClient` and
119
+ `ApiClientOptions`.
120
+
121
+ The init argument is optional only when the operation declares no mandatory
122
+ fragment. TypeScript requires each declared path parameter, required query
123
+ value, JSON body and required header.
124
+
125
+ `ApiInit` also accepts `signal`, `timeoutMs` and `baseUrl` for one call. A
126
+ call-level `baseUrl` wins over the client `baseUrl`.
127
+
128
+ ## The sync CLI
129
+
130
+ The `openapi-result-sync` command verifies a spec checksum and copies the
131
+ generated types into a target directory:
132
+
133
+ ```sh
134
+ npx openapi-result-sync \
135
+ --spec ./openapi.yaml \
136
+ --checksum ./openapi.sha256 \
137
+ --types ./schema.d.ts \
138
+ --out ./src/api
139
+ ```
140
+
141
+ The command has these properties:
142
+
143
+ - All four flags are required. The command reads no environment variables.
144
+ - The command computes the SHA-256 digest of the spec file.
145
+ - The command compares the digest with the first whitespace token of the
146
+ checksum file.
147
+ - If the digest differs, the command exits with code 1 and writes nothing.
148
+ - If the digest matches, the command writes `<out>/schema.d.ts` and
149
+ `<out>/openapi.sha256` atomically.
150
+ - If an input is unreadable, or an output cannot be written, the command
151
+ exits with code 2 and prints a message to stderr.
152
+
153
+ ## Development
154
+
155
+ ```sh
156
+ npm install
157
+ npm run typecheck
158
+ npm test
159
+ npm run build
160
+ ```
161
+
162
+ `npm run typecheck` covers `src/`, `test/` and the config files, including the
163
+ compile-time assertions in `test/types.ts`. `npm test` runs the Vitest suites for the
164
+ problem, the client and the sync CLI.
165
+
166
+ ## License
167
+
168
+ MIT. See [LICENSE](./LICENSE).
@@ -0,0 +1,93 @@
1
+ #!/usr/bin/env node
2
+ import { createHash } from "node:crypto";
3
+ import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
4
+ import { join } from "node:path";
5
+
6
+ const USAGE = `openapi-result-sync --spec <file> --checksum <file> --types <file> --out <dir>
7
+
8
+ Reads an OpenAPI document and a generated type declaration file. Computes the
9
+ SHA-256 digest of the spec and compares it with the first token of the checksum
10
+ file. On a match, copies the type declaration to <out>/schema.d.ts and the
11
+ checksum file to <out>/openapi.sha256. Both writes are atomic.
12
+
13
+ Exit codes:
14
+ 0 the checksum matches and both outputs are written
15
+ 1 the checksum does not match; nothing is written
16
+ 2 a flag is missing, a flag is unknown, or an input is unreadable`;
17
+
18
+ function fail(code, message) {
19
+ console.error(`openapi-result-sync: ${message}`);
20
+ process.exit(code);
21
+ }
22
+
23
+ function parseArgs(argv) {
24
+ const values = { spec: null, checksum: null, types: null, out: null };
25
+ for (let index = 0; index < argv.length; index += 1) {
26
+ const flag = argv[index];
27
+ if (flag === "--help" || flag === "-h") {
28
+ console.log(USAGE);
29
+ process.exit(0);
30
+ }
31
+ const key = flag.startsWith("--") ? flag.slice(2) : "";
32
+ if (!(key in values)) {
33
+ fail(2, `unknown argument: ${flag}`);
34
+ }
35
+ const value = argv[index + 1];
36
+ if (value === undefined || value.startsWith("--")) {
37
+ fail(2, `missing value for ${flag}`);
38
+ }
39
+ values[key] = value;
40
+ index += 1;
41
+ }
42
+ for (const key of ["spec", "checksum", "types", "out"]) {
43
+ if (values[key] === null) {
44
+ fail(2, `missing required flag --${key}`);
45
+ }
46
+ }
47
+ return values;
48
+ }
49
+
50
+ const args = parseArgs(process.argv.slice(2));
51
+
52
+ let specBytes;
53
+ let checksumText;
54
+ try {
55
+ specBytes = readFileSync(args.spec);
56
+ checksumText = readFileSync(args.checksum, "utf8");
57
+ } catch {
58
+ fail(2, "cannot read the spec file or the checksum file");
59
+ }
60
+
61
+ let typesBytes;
62
+ try {
63
+ typesBytes = readFileSync(args.types);
64
+ } catch {
65
+ fail(2, `cannot read the generated types at ${args.types}`);
66
+ }
67
+
68
+ const computed = createHash("sha256").update(specBytes).digest("hex");
69
+ const recorded = checksumText.trim().split(/\s+/)[0] ?? "";
70
+ if (computed !== recorded) {
71
+ fail(
72
+ 1,
73
+ `checksum drift: computed ${computed}, recorded ${recorded}; nothing written`,
74
+ );
75
+ }
76
+
77
+ function atomicWrite(name, bytes) {
78
+ const tmp = join(args.out, `.${name}.${process.pid}.tmp`);
79
+ writeFileSync(tmp, bytes);
80
+ renameSync(tmp, join(args.out, name));
81
+ }
82
+
83
+ try {
84
+ mkdirSync(args.out, { recursive: true });
85
+ atomicWrite("schema.d.ts", typesBytes);
86
+ atomicWrite("openapi.sha256", checksumText);
87
+ } catch (error) {
88
+ fail(
89
+ 2,
90
+ `cannot write output: ${error instanceof Error ? error.message : String(error)}`,
91
+ );
92
+ }
93
+ console.log(`openapi-result-sync: synced (sha256 ${computed})`);
@@ -0,0 +1,183 @@
1
+ import { type ApiProblem } from "./problem.js";
2
+ /**
3
+ * Union of every path that the `Paths` type declares.
4
+ */
5
+ export type PathKey<Paths> = keyof Paths & string;
6
+ type HttpMethod = "get" | "put" | "post" | "delete" | "patch" | "head";
7
+ type Index<T, K> = K extends keyof T ? T[K] : never;
8
+ /**
9
+ * HTTP methods that the `Paths` type declares for the path `P`. This type
10
+ * excludes a method when the generated schema maps it to `never`.
11
+ */
12
+ export type MethodOf<Paths, P extends PathKey<Paths>> = {
13
+ [M in HttpMethod]: Index<Paths[P], M> extends never ? never : M;
14
+ }[HttpMethod];
15
+ /**
16
+ * Operation object that the `Paths` type declares for the path `P` and the
17
+ * method `M`.
18
+ */
19
+ export type OperationOf<Paths, P extends PathKey<Paths>, M extends MethodOf<Paths, P>> = Index<Paths[P], M>;
20
+ /**
21
+ * Path parameters that an operation declares.
22
+ */
23
+ export type PathParamsOf<Op> = Op extends {
24
+ parameters: {
25
+ path: infer PP;
26
+ };
27
+ } ? PP extends Record<string, unknown> ? PP : never : never;
28
+ /**
29
+ * Query parameters that an operation declares.
30
+ */
31
+ export type QueryOf<Op> = Op extends {
32
+ parameters: {
33
+ query?: infer Q;
34
+ };
35
+ } ? Q extends Record<string, unknown> ? Q : never : never;
36
+ /**
37
+ * Header parameters that an operation declares.
38
+ */
39
+ export type HeaderParamsOf<Op> = Op extends {
40
+ parameters: {
41
+ header?: infer H;
42
+ };
43
+ } ? H extends Record<string, unknown> ? H : never : never;
44
+ /**
45
+ * Request body content map that an operation declares.
46
+ */
47
+ export type ContentOf<Op> = Op extends {
48
+ requestBody: {
49
+ content: infer C;
50
+ };
51
+ } ? C : never;
52
+ /**
53
+ * JSON request body that an operation declares, or `never`.
54
+ */
55
+ export type JsonBodyOf<Op> = [ContentOf<Op>] extends [never] ? never : ContentOf<Op> extends {
56
+ "application/json": infer B;
57
+ } ? B : never;
58
+ /**
59
+ * Raw request body that an operation accepts when the contract has no JSON
60
+ * body. Raw bytes are valid only for uploads of non-JSON data.
61
+ */
62
+ export type BinaryBodyOf<Op> = [ContentOf<Op>] extends [never] ? never : ContentOf<Op> extends {
63
+ "application/json": unknown;
64
+ } ? never : ArrayBuffer | Blob;
65
+ /**
66
+ * Keys of `T` whose property type does not permit `undefined`.
67
+ */
68
+ export type RequiredKeysOf<T> = {
69
+ [K in keyof T]-?: undefined extends T[K] ? never : K;
70
+ }[keyof T];
71
+ /**
72
+ * Init fragment for the path parameters of an operation.
73
+ */
74
+ export type PathInitOf<Op> = [PathParamsOf<Op>] extends [never] ? {
75
+ pathParams?: never;
76
+ } : {
77
+ pathParams: PathParamsOf<Op>;
78
+ };
79
+ /**
80
+ * Init fragment for the query of an operation. The `query` key is optional
81
+ * only when the operation declares no required query parameter.
82
+ */
83
+ export type QueryInitOf<Op> = [QueryOf<Op>] extends [never] ? {
84
+ query?: never;
85
+ } : [RequiredKeysOf<QueryOf<Op>>] extends [never] ? {
86
+ query?: QueryOf<Op>;
87
+ } : {
88
+ query: QueryOf<Op>;
89
+ };
90
+ /**
91
+ * Init fragment for the body of an operation. A declared JSON body is
92
+ * mandatory. A non-JSON contract accepts `ArrayBuffer` or `Blob` bytes.
93
+ */
94
+ export type BodyInitOf<Op> = [JsonBodyOf<Op>] extends [never] ? [BinaryBodyOf<Op>] extends [never] ? {
95
+ body?: never;
96
+ } : {
97
+ body: BinaryBodyOf<Op>;
98
+ } : {
99
+ body: JsonBodyOf<Op>;
100
+ };
101
+ /**
102
+ * Init fragment for the headers of an operation. The caller can always add
103
+ * free-form headers. Declared headers are mandatory when the operation marks
104
+ * at least one of them as required.
105
+ */
106
+ export type HeadersInitOf<Op> = [HeaderParamsOf<Op>] extends [never] ? {
107
+ headers?: Record<string, string>;
108
+ } : [RequiredKeysOf<HeaderParamsOf<Op>>] extends [never] ? {
109
+ headers?: HeaderParamsOf<Op> & Record<string, string>;
110
+ } : {
111
+ headers: HeaderParamsOf<Op> & Record<string, string>;
112
+ };
113
+ /**
114
+ * Complete init object for one operation.
115
+ */
116
+ export type ApiInit<Paths, P extends PathKey<Paths>, M extends MethodOf<Paths, P>> = PathInitOf<OperationOf<Paths, P, M>> & QueryInitOf<OperationOf<Paths, P, M>> & BodyInitOf<OperationOf<Paths, P, M>> & HeadersInitOf<OperationOf<Paths, P, M>> & {
117
+ /** Caller signal. The client combines it with the timeout signal. */
118
+ signal?: AbortSignal;
119
+ /** Timeout in milliseconds. Valid values are integers from 0 to 2147483647. */
120
+ timeoutMs?: number;
121
+ /** Base URL for this call. This value wins over the client base URL. */
122
+ baseUrl?: string;
123
+ };
124
+ /**
125
+ * Variadic argument tuple for one operation. The init argument is optional
126
+ * only when the operation declares no mandatory fragment.
127
+ */
128
+ export type ApiArgs<Paths, P extends PathKey<Paths>, M extends MethodOf<Paths, P>> = [RequiredKeysOf<ApiInit<Paths, P, M>>] extends [never] ? [init?: ApiInit<Paths, P, M>] : [init: ApiInit<Paths, P, M>];
129
+ /**
130
+ * Response data of an operation, mapped from the success statuses. A status
131
+ * without content maps to `undefined`.
132
+ */
133
+ export type DataOf<Op> = Op extends {
134
+ responses: infer R;
135
+ } ? {
136
+ [S in keyof R]: S extends 200 | 201 | 202 | 203 | 204 | 205 | 206 | 304 ? R[S] extends {
137
+ content: infer C;
138
+ } ? C extends {
139
+ "application/json": infer J;
140
+ } ? J : ArrayBuffer : undefined : never;
141
+ }[keyof R] : never;
142
+ /**
143
+ * Result of an API call. The union never throws for HTTP, timeout, abort or
144
+ * network failures. Failures arrive as an {@link ApiProblem}.
145
+ */
146
+ export type ApiResult<T> = {
147
+ ok: true;
148
+ status: number;
149
+ data: T;
150
+ headers: Headers;
151
+ } | {
152
+ ok: false;
153
+ problem: ApiProblem;
154
+ headers: Headers;
155
+ };
156
+ /**
157
+ * Options for {@link createApi}.
158
+ */
159
+ export interface ApiClientOptions {
160
+ /** Prefix for every request URL. A per-call `baseUrl` wins over this value. */
161
+ baseUrl?: string;
162
+ /** Called after a `401` response. Receives the request path. */
163
+ onUnauthorized?: (path: string) => void;
164
+ }
165
+ /**
166
+ * Typed client that {@link createApi} returns.
167
+ */
168
+ export interface ApiClient<Paths> {
169
+ /**
170
+ * Performs one request. TypeScript requires the path parameters, query
171
+ * values, JSON body and required headers that the operation declares.
172
+ */
173
+ fetch<P extends PathKey<Paths>, M extends MethodOf<Paths, P>>(path: P, method: M, ...args: ApiArgs<Paths, P, M>): Promise<ApiResult<DataOf<OperationOf<Paths, P, M>>>>;
174
+ }
175
+ /**
176
+ * Creates a typed API client for the generated `Paths` type.
177
+ *
178
+ * The client stores no application schema. Pass the `paths` type of your
179
+ * OpenAPI generator as the generic argument. Every call returns an
180
+ * {@link ApiResult} and never throws for HTTP or network failures.
181
+ */
182
+ export declare function createApi<Paths>(options?: ApiClientOptions): ApiClient<Paths>;
183
+ export {};
package/dist/client.js ADDED
@@ -0,0 +1,205 @@
1
+ import { normalizeProblem, syntheticProblem, } from "./problem.js";
2
+ const MAX_ERROR_BODY_BYTES = 64 * 1024;
3
+ const MAX_TIMEOUT_MS = 2_147_483_647;
4
+ function buildUrl(path, init, defaultBaseUrl) {
5
+ let url = path;
6
+ for (const [name, value] of Object.entries(init.pathParams ?? {})) {
7
+ url = url.replace(`{${name}}`, encodeURIComponent(String(value)));
8
+ }
9
+ const params = new URLSearchParams();
10
+ for (const [name, value] of Object.entries(init.query ?? {})) {
11
+ if (value === undefined || value === null)
12
+ continue;
13
+ params.append(name, String(value));
14
+ }
15
+ const qs = params.toString();
16
+ if (qs)
17
+ url += `?${qs}`;
18
+ return `${init.baseUrl ?? defaultBaseUrl}${url}`;
19
+ }
20
+ function isRawBody(body) {
21
+ return body instanceof ArrayBuffer || body instanceof Blob;
22
+ }
23
+ function isValidTimeout(timeoutMs) {
24
+ return (Number.isInteger(timeoutMs) &&
25
+ timeoutMs >= 0 &&
26
+ timeoutMs <= MAX_TIMEOUT_MS);
27
+ }
28
+ function normalizeTimeout(timeoutMs) {
29
+ if (timeoutMs === undefined)
30
+ return {};
31
+ if (!isValidTimeout(timeoutMs)) {
32
+ return {
33
+ problem: syntheticProblem(0, "client_invalid_timeout", "Invalid timeout", `timeoutMs must be an integer between 0 and ${MAX_TIMEOUT_MS}`),
34
+ };
35
+ }
36
+ try {
37
+ return { signal: AbortSignal.timeout(timeoutMs) };
38
+ }
39
+ catch {
40
+ return {
41
+ problem: syntheticProblem(0, "client_invalid_timeout", "Invalid timeout"),
42
+ };
43
+ }
44
+ }
45
+ async function readBoundedText(response, max) {
46
+ if (!response.body)
47
+ return "";
48
+ const reader = response.body.getReader();
49
+ const chunks = [];
50
+ let total = 0;
51
+ try {
52
+ for (;;) {
53
+ const { done, value } = await reader.read();
54
+ if (done || !value)
55
+ break;
56
+ const remaining = max - total;
57
+ if (remaining <= 0)
58
+ break;
59
+ chunks.push(value.subarray(0, remaining));
60
+ total += Math.min(value.length, remaining);
61
+ if (total >= max)
62
+ break;
63
+ }
64
+ }
65
+ finally {
66
+ await reader.cancel().catch(() => { });
67
+ }
68
+ const merged = new Uint8Array(total);
69
+ let offset = 0;
70
+ for (const chunk of chunks) {
71
+ merged.set(chunk, offset);
72
+ offset += chunk.length;
73
+ }
74
+ return new TextDecoder().decode(merged);
75
+ }
76
+ /**
77
+ * Creates a typed API client for the generated `Paths` type.
78
+ *
79
+ * The client stores no application schema. Pass the `paths` type of your
80
+ * OpenAPI generator as the generic argument. Every call returns an
81
+ * {@link ApiResult} and never throws for HTTP or network failures.
82
+ */
83
+ export function createApi(options = {}) {
84
+ async function clientFetch(path, method, ...args) {
85
+ const init = args[0] ?? {};
86
+ const timeout = normalizeTimeout(init.timeoutMs);
87
+ if (timeout.problem) {
88
+ return { ok: false, problem: timeout.problem, headers: new Headers() };
89
+ }
90
+ const headers = new Headers(init.headers);
91
+ let body;
92
+ const declaredBody = init.body;
93
+ if (declaredBody !== undefined) {
94
+ if (isRawBody(declaredBody)) {
95
+ body = declaredBody;
96
+ }
97
+ else {
98
+ if (!headers.has("content-type")) {
99
+ headers.set("content-type", "application/json");
100
+ }
101
+ body = JSON.stringify(declaredBody);
102
+ }
103
+ }
104
+ const signals = [];
105
+ if (init.signal)
106
+ signals.push(init.signal);
107
+ if (timeout.signal)
108
+ signals.push(timeout.signal);
109
+ const signal = signals.length === 0
110
+ ? undefined
111
+ : signals.length === 1
112
+ ? signals[0]
113
+ : AbortSignal.any(signals);
114
+ let response;
115
+ try {
116
+ response = await globalThis.fetch(buildUrl(path, init, options.baseUrl ?? ""), {
117
+ method: method.toUpperCase(),
118
+ credentials: "same-origin",
119
+ redirect: "error",
120
+ headers,
121
+ body,
122
+ signal,
123
+ });
124
+ }
125
+ catch (error) {
126
+ const name = error instanceof DOMException || error instanceof Error
127
+ ? error.name
128
+ : "";
129
+ const code = name === "TimeoutError"
130
+ ? "client_timeout"
131
+ : name === "AbortError"
132
+ ? "client_aborted"
133
+ : "client_network_error";
134
+ return {
135
+ ok: false,
136
+ problem: syntheticProblem(0, code, "Request failed"),
137
+ headers: new Headers(),
138
+ };
139
+ }
140
+ if (response.status === 401 && options.onUnauthorized) {
141
+ try {
142
+ options.onUnauthorized(path);
143
+ }
144
+ catch { }
145
+ }
146
+ const requestId = response.headers.get("x-request-id") ?? "";
147
+ if (!response.ok && response.status !== 304) {
148
+ let parsed;
149
+ const contentType = (response.headers.get("content-type") ?? "").toLowerCase();
150
+ if (contentType.includes("json")) {
151
+ try {
152
+ parsed = JSON.parse(await readBoundedText(response, MAX_ERROR_BODY_BYTES));
153
+ }
154
+ catch {
155
+ parsed = undefined;
156
+ }
157
+ }
158
+ else {
159
+ await response.body?.cancel().catch(() => { });
160
+ }
161
+ return {
162
+ ok: false,
163
+ problem: normalizeProblem(response.status, parsed, requestId),
164
+ headers: response.headers,
165
+ };
166
+ }
167
+ try {
168
+ if (response.status === 204 ||
169
+ response.status === 304 ||
170
+ method === "head") {
171
+ return {
172
+ ok: true,
173
+ status: response.status,
174
+ data: undefined,
175
+ headers: response.headers,
176
+ };
177
+ }
178
+ const contentType = (response.headers.get("content-type") ?? "").toLowerCase();
179
+ if (contentType.includes("application/json")) {
180
+ const data = (await response.json());
181
+ return {
182
+ ok: true,
183
+ status: response.status,
184
+ data,
185
+ headers: response.headers,
186
+ };
187
+ }
188
+ const data = (await response.arrayBuffer());
189
+ return {
190
+ ok: true,
191
+ status: response.status,
192
+ data,
193
+ headers: response.headers,
194
+ };
195
+ }
196
+ catch {
197
+ return {
198
+ ok: false,
199
+ problem: syntheticProblem(response.status, "invalid_response", "Invalid response", "The response body could not be decoded", requestId),
200
+ headers: response.headers,
201
+ };
202
+ }
203
+ }
204
+ return { fetch: clientFetch };
205
+ }
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Normalized problem object that describes every failed request.
3
+ *
4
+ * The shape follows RFC 7807 with the small field set that the client
5
+ * returns to callers.
6
+ */
7
+ export interface ApiProblem {
8
+ /** HTTP status code, or 0 for failures without a response. */
9
+ status: number;
10
+ /** Stable machine-readable error code. */
11
+ code: string;
12
+ /** Short human-readable summary. */
13
+ title: string;
14
+ /** Longer human-readable explanation, or an empty string. */
15
+ detail: string;
16
+ /** Field-level validation messages, keyed by field name. */
17
+ field_errors: Record<string, string>;
18
+ /** Correlation identifier, usually from the `x-request-id` header. */
19
+ request_id: string;
20
+ }
21
+ /**
22
+ * Maps a parsed or unreadable error body onto the problem contract.
23
+ *
24
+ * Text values are truncated to 500 characters. Field errors are limited to
25
+ * 50 entries. Unknown shapes fall back to the defaults `http_error` and
26
+ * `HTTP <status>`. When the body has no `request_id`, the function uses the
27
+ * `requestId` argument.
28
+ */
29
+ export declare function normalizeProblem(status: number, body: unknown, requestId?: string): ApiProblem;
30
+ /**
31
+ * Builds a client-side problem for failures without a backend response,
32
+ * such as invalid options, timeouts, aborts and network errors.
33
+ */
34
+ export declare function syntheticProblem(status: number, code: string, title: string, detail?: string, requestId?: string): ApiProblem;
@@ -0,0 +1,61 @@
1
+ const MAX_TEXT_LENGTH = 500;
2
+ const MAX_FIELD_ERRORS = 50;
3
+ function boundedText(value) {
4
+ if (typeof value !== "string")
5
+ return "";
6
+ return value.slice(0, MAX_TEXT_LENGTH);
7
+ }
8
+ function boundedFieldErrors(value) {
9
+ if (value === null || typeof value !== "object" || Array.isArray(value)) {
10
+ return {};
11
+ }
12
+ const result = {};
13
+ let count = 0;
14
+ for (const key in value) {
15
+ if (count >= MAX_FIELD_ERRORS)
16
+ break;
17
+ if (!Object.prototype.hasOwnProperty.call(value, key))
18
+ continue;
19
+ const raw = value[key];
20
+ if (typeof raw !== "string")
21
+ continue;
22
+ result[key.slice(0, MAX_TEXT_LENGTH)] = raw.slice(0, MAX_TEXT_LENGTH);
23
+ count += 1;
24
+ }
25
+ return result;
26
+ }
27
+ /**
28
+ * Maps a parsed or unreadable error body onto the problem contract.
29
+ *
30
+ * Text values are truncated to 500 characters. Field errors are limited to
31
+ * 50 entries. Unknown shapes fall back to the defaults `http_error` and
32
+ * `HTTP <status>`. When the body has no `request_id`, the function uses the
33
+ * `requestId` argument.
34
+ */
35
+ export function normalizeProblem(status, body, requestId = "") {
36
+ const source = body !== null && typeof body === "object" && !Array.isArray(body)
37
+ ? body
38
+ : {};
39
+ return {
40
+ status,
41
+ code: boundedText(source.code) || "http_error",
42
+ title: boundedText(source.title) || `HTTP ${status}`,
43
+ detail: boundedText(source.detail),
44
+ field_errors: boundedFieldErrors(source.field_errors),
45
+ request_id: boundedText(source.request_id) || requestId.slice(0, MAX_TEXT_LENGTH),
46
+ };
47
+ }
48
+ /**
49
+ * Builds a client-side problem for failures without a backend response,
50
+ * such as invalid options, timeouts, aborts and network errors.
51
+ */
52
+ export function syntheticProblem(status, code, title, detail = "", requestId = "") {
53
+ return {
54
+ status,
55
+ code,
56
+ title,
57
+ detail: detail.slice(0, MAX_TEXT_LENGTH),
58
+ field_errors: {},
59
+ request_id: requestId.slice(0, MAX_TEXT_LENGTH),
60
+ };
61
+ }
package/package.json CHANGED
@@ -1,6 +1,48 @@
1
1
  {
2
2
  "name": "openapi-result",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Typed OpenAPI client with a never-throwing Result union and bounded RFC 7807 problem normalization.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "author": "m1chlcz",
8
+ "sideEffects": false,
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/client.d.ts",
12
+ "default": "./dist/client.js"
13
+ },
14
+ "./problem": {
15
+ "types": "./dist/problem.d.ts",
16
+ "default": "./dist/problem.js"
17
+ }
18
+ },
19
+ "bin": {
20
+ "openapi-result-sync": "./bin/openapi-result-sync.mjs"
21
+ },
22
+ "files": [
23
+ "dist",
24
+ "bin",
25
+ "README.md",
26
+ "LICENSE"
27
+ ],
28
+ "engines": {
29
+ "node": ">=20.3.0"
30
+ },
31
+ "scripts": {
32
+ "build": "tsc -p tsconfig.build.json",
33
+ "prepack": "npm run build",
34
+ "typecheck": "tsc --noEmit",
35
+ "test": "vitest run"
36
+ },
37
+ "devDependencies": {
38
+ "@types/node": "^26.6.5",
39
+ "typescript": "6.0.3",
40
+ "vitest": "4.1.11"
41
+ },
42
+ "repository": {
43
+ "type": "git",
44
+ "url": "git+https://github.com/M1chlCZ/openapi-result.git"
45
+ },
46
+ "homepage": "https://github.com/M1chlCZ/openapi-result#readme",
47
+ "bugs": "https://github.com/M1chlCZ/openapi-result/issues"
48
+ }