@askrjs/fetch 0.0.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,202 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2025 Jeffrey Repanich
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
202
+
package/README.md ADDED
@@ -0,0 +1,167 @@
1
+ # @askrjs/fetch
2
+
3
+ Function-first HTTP contracts, typed clients, codecs, and middleware for Askr. The package is
4
+ ESM-only, has no runtime dependencies, and works with the standard Fetch APIs in modern browsers
5
+ and Node.js 20.19 or newer.
6
+
7
+ ## Install
8
+
9
+ ```sh
10
+ npm install @askrjs/fetch
11
+ ```
12
+
13
+ ## Define and call an API
14
+
15
+ ```ts
16
+ import { createClient, defineApi, get, json } from "@askrjs/fetch";
17
+
18
+ const api = defineApi({
19
+ getUser: get("/users/{id}")
20
+ .params<{ id: string }>()
21
+ .query<{ include?: string[] }>({
22
+ include: { style: "form", explode: true },
23
+ })
24
+ .returns(200, json<{ id: string; name: string }>())
25
+ .errors({ 404: json<{ title: string }>() }),
26
+ });
27
+
28
+ const client = createClient(api, { baseUrl: "https://api.example.com" });
29
+ const result = await client.getUser({
30
+ params: { id: "user-1" },
31
+ query: { include: ["teams", "roles"] },
32
+ });
33
+
34
+ if (result.ok) {
35
+ console.log(result.status, result.data.name);
36
+ } else if (result.kind === "http") {
37
+ console.error(result.status, result.error);
38
+ } else {
39
+ console.error(result.kind, result.error);
40
+ }
41
+ ```
42
+
43
+ Paths use OpenAPI-style `{name}` parameters. Colon parameters and wildcards are rejected. A path
44
+ parameter declaration must exactly match the names in the path.
45
+
46
+ Every call returns a discriminated result instead of throwing for request, transport, HTTP, or
47
+ decode failures. Use `unwrap(result)` when exception-based control flow is more convenient.
48
+
49
+ ## Codecs and validation
50
+
51
+ The built-in codecs are:
52
+
53
+ - `json(schema?)`
54
+ - `text()`
55
+ - `urlEncoded()`
56
+ - `multipart()`
57
+ - `blob()`
58
+ - `arrayBuffer()`
59
+ - `stream()`
60
+ - `empty()`
61
+ - `content({ mediaType: codec })`
62
+
63
+ A validator only needs a `safeParse(value)` method, so schema libraries with that contract can be
64
+ used without an adapter. Validators run for request bodies, path parameters, query parameters,
65
+ headers, and decoded response bodies. Successful validator transformations are used for
66
+ serialization and returned data.
67
+
68
+ ```ts
69
+ const positiveInteger = {
70
+ safeParse(value: unknown) {
71
+ const parsed = Number(value);
72
+ return Number.isInteger(parsed) && parsed > 0
73
+ ? { success: true as const, data: parsed }
74
+ : { success: false as const, error: new TypeError("Expected a positive integer") };
75
+ },
76
+ };
77
+
78
+ const api = defineApi({
79
+ getJob: get("/jobs/{id}")
80
+ .params<{ id: number }>({ id: positiveInteger })
81
+ .returns(json<{ id: number }>()),
82
+ });
83
+ ```
84
+
85
+ Responses are decoded against the codec registered for the actual HTTP status and content type.
86
+ Missing status codecs, incompatible media types, invalid payloads, and unexpected non-empty bodies
87
+ for `empty()` produce a `decode` failure. `204`, `205`, and `HEAD` responses must use `empty()`.
88
+
89
+ ## Parameter serialization
90
+
91
+ Descriptors support the OpenAPI serialization styles used by generated clients:
92
+
93
+ - Path: `simple`, `label`, and `matrix`
94
+ - Query: `form`, `spaceDelimited`, `pipeDelimited`, and `deepObject`
95
+ - Header: `simple`
96
+
97
+ Use a parameter specification to combine serialization metadata with validation:
98
+
99
+ ```ts
100
+ get("/search")
101
+ .query<{ tags: string[]; filter: { state: string } }>({
102
+ tags: { style: "pipeDelimited", explode: false },
103
+ filter: { style: "deepObject", explode: true },
104
+ })
105
+ .returns(json());
106
+ ```
107
+
108
+ ## Middleware
109
+
110
+ Import middleware from the dedicated subpath:
111
+
112
+ ```ts
113
+ import { createClient } from "@askrjs/fetch";
114
+ import { bearerAuth, logging, retry, telemetry } from "@askrjs/fetch/middleware";
115
+
116
+ const client = createClient(api, {
117
+ baseUrl: "https://api.example.com",
118
+ middleware: [
119
+ bearerAuth({ token: () => session.accessToken }),
120
+ logging(),
121
+ telemetry(hooks),
122
+ retry({ attempts: 3 }),
123
+ ],
124
+ });
125
+ ```
126
+
127
+ Middleware runs outward in declaration order. The package includes bearer and API-key auth,
128
+ idempotent-method retries, redacted structured logging, and telemetry hooks. Logging redacts common
129
+ credential names as well as arbitrary header or query names added by `apiKeyAuth()`.
130
+
131
+ Retries default to `GET`, `HEAD`, `PUT`, `DELETE`, and `OPTIONS`, and to statuses `408`, `425`,
132
+ `429`, `500`, `502`, `503`, and `504`. `Retry-After` is honored when present. Requests with bodies
133
+ are not retried automatically.
134
+
135
+ ## Cancellation and timeouts
136
+
137
+ Set a default timeout on the client or override it for one call. A caller `AbortSignal` is composed
138
+ with the timeout signal. Timeouts return `kind: "timeout"`; caller cancellation returns
139
+ `kind: "abort"`.
140
+
141
+ ```ts
142
+ const controller = new AbortController();
143
+ const pending = client.getUser({
144
+ params: { id: "user-1" },
145
+ signal: controller.signal,
146
+ timeout: 5_000,
147
+ });
148
+
149
+ controller.abort();
150
+ const result = await pending;
151
+ ```
152
+
153
+ ## Lower-level requests
154
+
155
+ `createFetch(options)` exposes the same result, codec, middleware, timeout, and cancellation
156
+ contracts without an API descriptor. Supply either an absolute URL or a `baseUrl` plus a rooted
157
+ path.
158
+
159
+ ```ts
160
+ import { createFetch, json } from "@askrjs/fetch";
161
+
162
+ const execute = createFetch({ baseUrl: "https://api.example.com" });
163
+ const result = await execute({
164
+ url: "/health",
165
+ response: json<{ status: "ok" }>(),
166
+ });
167
+ ```
@@ -0,0 +1,48 @@
1
+ import { AnyEndpointDescriptor, ApiDefinition, ClientOptions, Codec, EndpointDescriptor, FailureResult, FetchResult, HttpResult, InferCodec, ParameterMap, SuccessResult } from "./types.js";
2
+ //#region src/client.d.ts
3
+ interface AdHocCall {
4
+ url: string;
5
+ method?: string;
6
+ headers?: HeadersInit;
7
+ query?: Record<string, unknown>;
8
+ querySpec?: ParameterMap;
9
+ body?: unknown;
10
+ bodyCodec?: Codec;
11
+ response?: Codec;
12
+ responses?: Readonly<Record<number, Codec>>;
13
+ errors?: Partial<Record<number | "default", Codec>>;
14
+ signal?: AbortSignal;
15
+ timeout?: number;
16
+ endpoint?: EndpointDescriptor;
17
+ operationId?: string;
18
+ }
19
+ declare function createFetch(options?: ClientOptions): (call: AdHocCall) => Promise<FetchResult>;
20
+ type InputParts<D> = D extends EndpointDescriptor<infer P, infer Q, infer H, infer B, any, any> ? {
21
+ params: P;
22
+ query: Q;
23
+ headers: H;
24
+ body: B;
25
+ } : never;
26
+ type RequiredKeys<T> = { [K in keyof T]-?: {} extends Pick<T, K> ? never : K; }[keyof T];
27
+ type Container<K extends string, T, Always extends boolean = false> = [T] extends [undefined] ? {} : Always extends true ? { [P in K]: T; } : RequiredKeys<T> extends never ? { [P in K]?: T; } : { [P in K]: T; };
28
+ type EndpointInput<D extends AnyEndpointDescriptor> = Container<"params", InputParts<D>["params"], true> & Container<"query", InputParts<D>["query"]> & Container<"headers", InputParts<D>["headers"]> & Container<"body", InputParts<D>["body"], true> & {
29
+ signal?: AbortSignal;
30
+ timeout?: number;
31
+ };
32
+ type Successes<D> = D extends EndpointDescriptor<any, any, any, any, infer R, any> ? { [S in keyof R & number]: SuccessResult<InferCodec<R[S]>, S>; }[keyof R & number] : never;
33
+ type Errors<D> = D extends EndpointDescriptor<any, any, any, any, any, infer E> ? { [S in Exclude<keyof E, "default"> & number]: HttpResult<InferCodec<NonNullable<E[S]>>, S>; }[Exclude<keyof E, "default"> & number] | ("default" extends keyof E ? HttpResult<InferCodec<NonNullable<E["default"]>>, number> : never) : never;
34
+ type ClientResult<D extends AnyEndpointDescriptor> = Successes<D> | Errors<D> | FailureResult;
35
+ type ClientMethod<D extends AnyEndpointDescriptor> = RequiredKeys<EndpointInput<D>> extends never ? (input?: EndpointInput<D>) => Promise<ClientResult<D>> : (input: EndpointInput<D>) => Promise<ClientResult<D>>;
36
+ type ApiClient<A extends ApiDefinition> = Readonly<{ [K in keyof A["endpoints"]]: ClientMethod<A["endpoints"][K]>; }>;
37
+ declare function createClient<A extends ApiDefinition>(api: A, options?: ClientOptions): ApiClient<A>;
38
+ declare class FetchError extends Error {
39
+ readonly result: Exclude<FetchResult, {
40
+ ok: true;
41
+ }>;
42
+ constructor(result: Exclude<FetchResult, {
43
+ ok: true;
44
+ }>);
45
+ }
46
+ declare function unwrap<T>(result: FetchResult<T>): T;
47
+ //#endregion
48
+ export { AdHocCall, ApiClient, ClientResult, FetchError, createClient, createFetch, unwrap };
package/dist/client.js ADDED
@@ -0,0 +1,299 @@
1
+ //#region src/client.ts
2
+ const media = (response) => response.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase() ?? null;
3
+ const compatible = (codec, type) => codec.kind === "empty" || codec.kind === "blob" || codec.kind === "arrayBuffer" || codec.kind === "stream" || !!type && codec.mediaTypes.some((expected) => expected === "*/*" || expected === type || expected === "text/*" && type.startsWith("text/") || expected === "+json" && type.endsWith("+json"));
4
+ async function decode(response, codec) {
5
+ const type = media(response);
6
+ const selected = codec.kind === "content" ? codec.variants?.[type ?? ""] : codec;
7
+ if (!selected || !compatible(selected, type)) throw new TypeError(`Cannot decode ${type ?? "missing content type"} as ${codec.mediaTypes.join(", ") || "empty"}`);
8
+ let value;
9
+ switch (selected.kind) {
10
+ case "empty":
11
+ if ((await response.clone().arrayBuffer()).byteLength) throw new TypeError("Expected an empty response body");
12
+ return;
13
+ case "json":
14
+ value = await response.json();
15
+ break;
16
+ case "text":
17
+ value = await response.text();
18
+ break;
19
+ case "urlEncoded":
20
+ value = new URLSearchParams(await response.text());
21
+ break;
22
+ case "multipart":
23
+ value = await response.formData();
24
+ break;
25
+ case "blob":
26
+ value = await response.blob();
27
+ break;
28
+ case "arrayBuffer":
29
+ value = await response.arrayBuffer();
30
+ break;
31
+ case "stream": return response.body;
32
+ default: throw new TypeError("Invalid codec");
33
+ }
34
+ if (selected.validator) {
35
+ const parsed = selected.validator.safeParse(value);
36
+ if (!parsed.success) throw parsed.error;
37
+ return parsed.data;
38
+ }
39
+ return value;
40
+ }
41
+ function encode(value, codec, headers) {
42
+ if (codec.validator) {
43
+ const parsed = codec.validator.safeParse(value);
44
+ if (!parsed.success) throw parsed.error;
45
+ value = parsed.data;
46
+ }
47
+ switch (codec.kind) {
48
+ case "empty": return;
49
+ case "json":
50
+ headers.set("content-type", "application/json");
51
+ return JSON.stringify(value);
52
+ case "text":
53
+ headers.set("content-type", "text/plain;charset=UTF-8");
54
+ return String(value);
55
+ case "urlEncoded":
56
+ headers.set("content-type", "application/x-www-form-urlencoded;charset=UTF-8");
57
+ return value;
58
+ case "multipart": return value;
59
+ case "blob":
60
+ case "arrayBuffer":
61
+ case "stream": return value;
62
+ case "content": {
63
+ const [type, selected] = Object.entries(codec.variants ?? {})[0] ?? [];
64
+ if (!selected) throw new TypeError("content() has no variants");
65
+ const body = encode(value, selected, headers);
66
+ if (selected.kind !== "multipart") headers.set("content-type", type);
67
+ return body;
68
+ }
69
+ }
70
+ }
71
+ const failure = (kind, error, url, response) => ({
72
+ ok: false,
73
+ kind,
74
+ status: response?.status ?? 0,
75
+ error,
76
+ headers: response?.headers ?? new Headers(),
77
+ url,
78
+ ...response ? { response } : {}
79
+ });
80
+ const entries = (value) => value && typeof value === "object" && !Array.isArray(value) ? Object.entries(value) : [];
81
+ const values = (value) => Array.isArray(value) ? value : [value];
82
+ const encoded = (value) => encodeURIComponent(String(value));
83
+ function pathParameter(name, value, spec = {}) {
84
+ const style = spec.style ?? "simple";
85
+ const explode = spec.explode ?? false;
86
+ const object = entries(value);
87
+ const array = Array.isArray(value);
88
+ if (style === "label") return `.${(object.length ? object.flatMap(([k, v]) => explode ? [`${encoded(k)}=${encoded(v)}`] : [encoded(k), encoded(v)]) : values(value).map(encoded)).join(explode ? "." : ",")}`;
89
+ if (style === "matrix") {
90
+ if (object.length) return explode ? object.map(([k, v]) => `;${encoded(k)}=${encoded(v)}`).join("") : `;${encoded(name)}=${object.flatMap(([k, v]) => [encoded(k), encoded(v)]).join(",")}`;
91
+ if (array && explode) return values(value).map((v) => `;${encoded(name)}=${encoded(v)}`).join("");
92
+ return `;${encoded(name)}=${values(value).map(encoded).join(",")}`;
93
+ }
94
+ if (style !== "simple") throw new TypeError(`Unsupported path parameter style: ${style}`);
95
+ if (object.length) return object.flatMap(([k, v]) => explode ? [`${encoded(k)}=${encoded(v)}`] : [encoded(k), encoded(v)]).join(",");
96
+ return values(value).map(encoded).join(",");
97
+ }
98
+ function queryParameter(output, name, value, spec = {}) {
99
+ const style = spec.style ?? "form";
100
+ const explode = spec.explode ?? true;
101
+ const object = entries(value);
102
+ const array = Array.isArray(value);
103
+ const append = (key, item) => output.append(key, String(item));
104
+ if (style === "deepObject") {
105
+ if (!object.length) throw new TypeError(`deepObject query parameter ${name} must be an object`);
106
+ for (const [key, item] of object) append(`${name}[${key}]`, item);
107
+ return;
108
+ }
109
+ if (style === "spaceDelimited" || style === "pipeDelimited") {
110
+ if (!array) throw new TypeError(`${style} query parameter ${name} must be an array`);
111
+ append(name, values(value).join(style === "spaceDelimited" ? " " : "|"));
112
+ return;
113
+ }
114
+ if (style !== "form") throw new TypeError(`Unsupported query parameter style: ${style}`);
115
+ if (object.length) {
116
+ if (explode) for (const [key, item] of object) append(key, item);
117
+ else append(name, object.flatMap(([key, item]) => [key, item]).join(","));
118
+ return;
119
+ }
120
+ if (array && explode) for (const item of values(value)) append(name, item);
121
+ else append(name, values(value).join(","));
122
+ }
123
+ function headerParameter(value, spec = {}) {
124
+ if ((spec.style ?? "simple") !== "simple") throw new TypeError(`Unsupported header parameter style: ${spec.style}`);
125
+ const object = entries(value);
126
+ if (object.length) return object.flatMap(([key, item]) => spec.explode ? [`${key}=${String(item)}`] : [key, item]).join(",");
127
+ return values(value).join(",");
128
+ }
129
+ const parameterSpec = (map, name) => {
130
+ const value = map?.[name];
131
+ return value && typeof value === "object" && !("safeParse" in value) ? value : {};
132
+ };
133
+ const parameterValue = (map, name, value) => {
134
+ const definition = map?.[name];
135
+ const validator = definition && typeof definition === "object" && "safeParse" in definition ? definition : definition?.validator;
136
+ if (!validator) return value;
137
+ const parsed = validator.safeParse(value);
138
+ if (!parsed.success) throw parsed.error;
139
+ return parsed.data;
140
+ };
141
+ function createFetch(options = {}) {
142
+ return async (call) => {
143
+ let url = `${options.baseUrl?.replace(/\/$/, "") ?? ""}${call.url}`;
144
+ const headers = new Headers(options.headers);
145
+ new Headers(call.headers).forEach((v, k) => headers.set(k, v));
146
+ try {
147
+ if (call.query) {
148
+ const query = new URLSearchParams();
149
+ for (const [key, value] of Object.entries(call.query)) if (value !== void 0) queryParameter(query, key, parameterValue(call.querySpec, key, value), parameterSpec(call.querySpec, key));
150
+ const rendered = query.toString();
151
+ if (rendered) url += `${url.includes("?") ? "&" : "?"}${rendered}`;
152
+ }
153
+ } catch (error) {
154
+ return failure("request", error, url);
155
+ }
156
+ let body;
157
+ try {
158
+ if (call.bodyCodec) body = encode(call.body, call.bodyCodec, headers);
159
+ } catch (error) {
160
+ return failure("request", error, url);
161
+ }
162
+ const timeout = call.timeout ?? options.timeout;
163
+ const controller = new AbortController();
164
+ let timedOut = false;
165
+ let timer;
166
+ const abort = () => controller.abort(call.signal?.reason);
167
+ call.signal?.addEventListener("abort", abort, { once: true });
168
+ if (call.signal?.aborted) abort();
169
+ if (timeout !== void 0) timer = setTimeout(() => {
170
+ timedOut = true;
171
+ controller.abort(new DOMException("Timed out", "TimeoutError"));
172
+ }, timeout);
173
+ const cleanup = () => {
174
+ if (timer) clearTimeout(timer);
175
+ call.signal?.removeEventListener("abort", abort);
176
+ };
177
+ if (controller.signal.aborted) {
178
+ cleanup();
179
+ return failure("abort", controller.signal.reason, url);
180
+ }
181
+ let request;
182
+ try {
183
+ request = new Request(url, {
184
+ method: call.method ?? "GET",
185
+ headers,
186
+ body,
187
+ credentials: options.credentials,
188
+ signal: controller.signal,
189
+ ...body instanceof ReadableStream ? { duplex: "half" } : {}
190
+ });
191
+ } catch (error) {
192
+ cleanup();
193
+ return failure("request", error, url);
194
+ }
195
+ const transport = options.fetch ?? globalThis.fetch;
196
+ const terminal = async (context) => {
197
+ let response;
198
+ try {
199
+ response = await transport(context.request);
200
+ } catch (error) {
201
+ return failure(timedOut ? "timeout" : call.signal?.aborted ? "abort" : "network", error, url);
202
+ }
203
+ const codec = response.ok ? call.responses?.[response.status] ?? call.response : call.errors?.[response.status] ?? call.errors?.default;
204
+ if (!codec) return failure("decode", /* @__PURE__ */ new TypeError(`No codec for status ${response.status}`), url, response);
205
+ try {
206
+ const data = await decode(response.clone(), codec);
207
+ return response.ok ? {
208
+ ok: true,
209
+ kind: "success",
210
+ status: response.status,
211
+ data,
212
+ mediaType: media(response),
213
+ headers: response.headers,
214
+ url: response.url || url,
215
+ response
216
+ } : {
217
+ ok: false,
218
+ kind: "http",
219
+ status: response.status,
220
+ error: data,
221
+ mediaType: media(response),
222
+ headers: response.headers,
223
+ url: response.url || url,
224
+ response
225
+ };
226
+ } catch (error) {
227
+ return failure("decode", error, url, response);
228
+ }
229
+ };
230
+ const middleware = options.middleware ?? [];
231
+ const dispatch = (index, context) => index === middleware.length ? terminal(context) : Promise.resolve().then(() => middleware[index](context, (next = context) => dispatch(index + 1, next))).catch((error) => failure("middleware", error, url));
232
+ try {
233
+ return await dispatch(0, Object.freeze({
234
+ request,
235
+ endpoint: call.endpoint,
236
+ operationId: call.operationId,
237
+ security: call.endpoint?.security,
238
+ attempt: 1,
239
+ ...timeout === void 0 ? {} : { deadline: Date.now() + timeout }
240
+ }));
241
+ } finally {
242
+ cleanup();
243
+ }
244
+ };
245
+ }
246
+ function createClient(api, options = {}) {
247
+ const execute = createFetch(options);
248
+ const methods = Object.fromEntries(Object.entries(api.endpoints).map(([id, endpoint]) => [id, async (input = {}) => {
249
+ let path = endpoint.path;
250
+ try {
251
+ for (const name of path.matchAll(/\{([^}]+)\}/g)) {
252
+ const key = name[1];
253
+ const value = input.params?.[key];
254
+ if (value === void 0) return failure("request", /* @__PURE__ */ new TypeError(`Missing path parameter: ${key}`), path);
255
+ path = path.replace(name[0], pathParameter(key, parameterValue(endpoint.params, key, value), parameterSpec(endpoint.params, key)));
256
+ }
257
+ } catch (error) {
258
+ return failure("request", error, path);
259
+ }
260
+ const extras = Object.keys(input.params ?? {}).filter((key) => !endpoint.path.includes(`{${key}}`));
261
+ if (extras.length) return failure("request", /* @__PURE__ */ new TypeError(`Unexpected path parameter: ${extras[0]}`), path);
262
+ const headers = new Headers();
263
+ try {
264
+ for (const [key, value] of Object.entries(input.headers ?? {})) if (value !== void 0) headers.set(key, headerParameter(parameterValue(endpoint.headers, key, value), parameterSpec(endpoint.headers, key)));
265
+ } catch (error) {
266
+ return failure("request", error, path);
267
+ }
268
+ return execute({
269
+ url: path,
270
+ method: endpoint.method,
271
+ headers,
272
+ query: input.query,
273
+ querySpec: endpoint.query,
274
+ body: input.body,
275
+ bodyCodec: endpoint.body,
276
+ responses: endpoint.responses,
277
+ errors: endpoint.errors,
278
+ signal: input.signal,
279
+ timeout: input.timeout,
280
+ endpoint,
281
+ operationId: id
282
+ });
283
+ }]));
284
+ return Object.freeze(methods);
285
+ }
286
+ var FetchError = class extends Error {
287
+ result;
288
+ constructor(result) {
289
+ super(`Fetch failed: ${result.kind}`);
290
+ this.result = result;
291
+ this.name = "FetchError";
292
+ }
293
+ };
294
+ function unwrap(result) {
295
+ if (!result.ok) throw new FetchError(result);
296
+ return result.data;
297
+ }
298
+ //#endregion
299
+ export { FetchError, createClient, createFetch, unwrap };
@@ -0,0 +1,14 @@
1
+ import { Codec, Validator } from "./types.js";
2
+ //#region src/codecs.d.ts
3
+ declare function json<T = unknown>(): Codec<T>;
4
+ declare function json<V extends Validator>(schema: V): Codec<V extends Validator<infer T> ? T : never>;
5
+ declare const text: () => Codec<string>;
6
+ declare const urlEncoded: () => Codec<URLSearchParams>;
7
+ declare const multipart: () => Codec<FormData>;
8
+ declare const blob: () => Codec<Blob>;
9
+ declare const arrayBuffer: () => Codec<ArrayBuffer>;
10
+ declare const stream: () => Codec<ReadableStream<Uint8Array>>;
11
+ declare const empty: () => Codec<undefined>;
12
+ declare const content: <T extends Record<string, Codec>>(variants: T) => Codec<{ [K in keyof T]: T[K] extends Codec<infer V> ? V : never; }[keyof T]>;
13
+ //#endregion
14
+ export { arrayBuffer, blob, content, empty, json, multipart, stream, text, urlEncoded };
package/dist/codecs.js ADDED
@@ -0,0 +1,23 @@
1
+ //#region src/codecs.ts
2
+ const codec = (kind, mediaTypes, validator) => Object.freeze({
3
+ kind,
4
+ mediaTypes: Object.freeze(mediaTypes),
5
+ validator
6
+ });
7
+ function json(schema) {
8
+ return codec("json", ["application/json", "+json"], schema);
9
+ }
10
+ const text = () => codec("text", ["text/*"]);
11
+ const urlEncoded = () => codec("urlEncoded", ["application/x-www-form-urlencoded"]);
12
+ const multipart = () => codec("multipart", ["multipart/form-data"]);
13
+ const blob = () => codec("blob", ["*/*"]);
14
+ const arrayBuffer = () => codec("arrayBuffer", ["*/*"]);
15
+ const stream = () => codec("stream", ["*/*"]);
16
+ const empty = () => codec("empty", []);
17
+ const content = (variants) => Object.freeze({
18
+ kind: "content",
19
+ mediaTypes: Object.freeze(Object.keys(variants).sort()),
20
+ variants: Object.freeze({ ...variants })
21
+ });
22
+ //#endregion
23
+ export { arrayBuffer, blob, content, empty, json, multipart, stream, text, urlEncoded };
package/dist/dsl.d.ts ADDED
@@ -0,0 +1,33 @@
1
+ import { AnyEndpointDescriptor, ApiDefinition, ApiMetadata, Codec, EndpointDescriptor, ParameterMap } from "./types.js";
2
+ //#region src/dsl.d.ts
3
+ declare function pathNames(path: string): string[];
4
+ type Responses = Record<number, Codec>;
5
+ type Errors = Partial<Record<number | "default", Codec>>;
6
+ type State = Omit<EndpointDescriptor, "responses" | "errors"> & {
7
+ responses: Responses;
8
+ errors: Errors;
9
+ };
10
+ declare const STATE: unique symbol;
11
+ interface EndpointBuilder<P = undefined, Q = undefined, H = undefined, B = undefined, R extends Responses = {}, E extends Errors = {}> {
12
+ readonly [STATE]: State;
13
+ params<T extends Record<string, unknown>>(spec?: ParameterMap): EndpointBuilder<T, Q, H, B, R, E>;
14
+ query<T extends Record<string, unknown>>(spec?: ParameterMap): EndpointBuilder<P, T, H, B, R, E>;
15
+ headers<T extends Record<string, unknown>>(spec?: ParameterMap): EndpointBuilder<P, Q, T, B, R, E>;
16
+ body<C extends Codec>(codec: C): EndpointBuilder<P, Q, H, C extends Codec<infer T> ? T : never, R, E>;
17
+ returns<C extends Codec>(codec: C): EndpointBuilder<P, Q, H, B, R & Record<200, C>, E>;
18
+ returns<S extends number, C extends Codec>(status: S, codec: C): EndpointBuilder<P, Q, H, B, R & Record<S, C>, E>;
19
+ errors<T extends Errors>(spec: T): EndpointBuilder<P, Q, H, B, R, E & T>;
20
+ security(requirements: readonly Readonly<Record<string, readonly string[]>>[]): EndpointBuilder<P, Q, H, B, R, E>;
21
+ }
22
+ declare const get: (path: string) => EndpointBuilder<undefined, undefined, undefined, undefined, {}, {}>;
23
+ declare const post: (path: string) => EndpointBuilder<undefined, undefined, undefined, undefined, {}, {}>;
24
+ declare const put: (path: string) => EndpointBuilder<undefined, undefined, undefined, undefined, {}, {}>;
25
+ declare const patch: (path: string) => EndpointBuilder<undefined, undefined, undefined, undefined, {}, {}>;
26
+ declare const del: (path: string) => EndpointBuilder<undefined, undefined, undefined, undefined, {}, {}>;
27
+ declare const head: (path: string) => EndpointBuilder<undefined, undefined, undefined, undefined, {}, {}>;
28
+ declare const options: (path: string) => EndpointBuilder<undefined, undefined, undefined, undefined, {}, {}>;
29
+ type DescriptorOf<T> = T extends EndpointBuilder<infer P, infer Q, infer H, infer B, infer R, infer E> ? EndpointDescriptor<P, Q, H, B, R, E> : T extends AnyEndpointDescriptor ? T : never;
30
+ type Defined<E extends Record<string, AnyEndpointDescriptor | EndpointBuilder>> = { [K in keyof E]: DescriptorOf<E[K]>; };
31
+ declare function defineApi<E extends Record<string, AnyEndpointDescriptor | EndpointBuilder>>(endpoints: E, metadata?: ApiMetadata): ApiDefinition<Defined<E>>;
32
+ //#endregion
33
+ export { EndpointBuilder, defineApi, del, get, head, options, patch, pathNames, post, put };
package/dist/dsl.js ADDED
@@ -0,0 +1,107 @@
1
+ //#region src/dsl.ts
2
+ const PATH_NAME = /^[A-Za-z_$][\w$]*$/;
3
+ function pathNames(path) {
4
+ if (path.includes(":") || path.includes("*")) throw new TypeError(`Invalid path syntax: ${path}`);
5
+ const names = [];
6
+ let index = 0;
7
+ for (const match of path.matchAll(/\{([^{}]*)\}/g)) {
8
+ const literal = path.slice(index, match.index);
9
+ if (literal.includes("{") || literal.includes("}") || !PATH_NAME.test(match[1])) throw new TypeError(`Malformed path parameter in ${path}`);
10
+ if (names.includes(match[1])) throw new TypeError(`Duplicate path parameter: ${match[1]}`);
11
+ names.push(match[1]);
12
+ index = (match.index ?? 0) + match[0].length;
13
+ }
14
+ if (path.slice(index).includes("{") || path.slice(index).includes("}")) throw new TypeError(`Malformed path parameter in ${path}`);
15
+ return names;
16
+ }
17
+ const STATE = Symbol("endpoint-state");
18
+ const needsEmpty = (state, status) => status === 204 || status === 205 || state.method === "HEAD";
19
+ function build(state) {
20
+ const update = (next) => build({
21
+ ...state,
22
+ ...next
23
+ });
24
+ return Object.freeze({
25
+ [STATE]: state,
26
+ params(spec) {
27
+ const names = pathNames(state.path);
28
+ if (spec && (Object.keys(spec).some((k) => !names.includes(k)) || names.some((k) => !(k in spec)))) throw new TypeError(`Path params must exactly match ${names.join(", ")}`);
29
+ return update({ params: spec ?? Object.fromEntries(names.map((name) => [name, void 0])) });
30
+ },
31
+ query(spec = {}) {
32
+ return update({ query: spec });
33
+ },
34
+ headers(spec = {}) {
35
+ return update({ headers: spec });
36
+ },
37
+ body(value) {
38
+ return update({ body: value });
39
+ },
40
+ returns(statusOrCodec, maybeCodec) {
41
+ const status = typeof statusOrCodec === "number" ? statusOrCodec : 200;
42
+ const responseCodec = typeof statusOrCodec === "number" ? maybeCodec : statusOrCodec;
43
+ if (status < 200 || status > 299) throw new TypeError("returns() accepts only 2xx statuses");
44
+ if (needsEmpty(state, status) && responseCodec.kind !== "empty") throw new TypeError(`${state.method} ${status} requires empty()`);
45
+ return update({ responses: {
46
+ ...state.responses,
47
+ [status]: responseCodec
48
+ } });
49
+ },
50
+ errors(spec) {
51
+ for (const key of Object.keys(spec)) if (key !== "default" && Number(key) >= 200 && Number(key) <= 299) throw new TypeError("errors() accepts only non-2xx statuses or default");
52
+ return update({ errors: {
53
+ ...state.errors,
54
+ ...spec
55
+ } });
56
+ },
57
+ security(security) {
58
+ return update({ security });
59
+ }
60
+ });
61
+ }
62
+ const method = (value) => (path) => {
63
+ const names = pathNames(path);
64
+ return build({
65
+ method: value,
66
+ path,
67
+ params: names.length ? Object.fromEntries(names.map((name) => [name, void 0])) : void 0,
68
+ responses: {},
69
+ errors: {}
70
+ });
71
+ };
72
+ const get = method("GET");
73
+ const post = method("POST");
74
+ const put = method("PUT");
75
+ const patch = method("PATCH");
76
+ const del = method("DELETE");
77
+ const head = method("HEAD");
78
+ const options = method("OPTIONS");
79
+ const snapshotParameters = (parameters) => parameters ? Object.freeze(Object.fromEntries(Object.entries(parameters).map(([name, definition]) => [name, definition && typeof definition === "object" && !("safeParse" in definition) ? Object.freeze({ ...definition }) : definition]))) : void 0;
80
+ const snapshotSecurity = (security) => security ? Object.freeze(security.map((requirement) => Object.freeze(Object.fromEntries(Object.entries(requirement).map(([name, scopes]) => [name, Object.freeze([...scopes])]))))) : void 0;
81
+ const snapshotMetadata = (metadata) => Object.freeze({
82
+ ...metadata,
83
+ ...metadata.servers ? { servers: Object.freeze(metadata.servers.map((server) => typeof server === "string" ? server : Object.freeze({ ...server }))) } : {},
84
+ ...metadata.tags ? { tags: Object.freeze([...metadata.tags]) } : {},
85
+ ...metadata.securitySchemes ? { securitySchemes: Object.freeze({ ...metadata.securitySchemes }) } : {}
86
+ });
87
+ function defineApi(endpoints, metadata) {
88
+ const frozen = Object.fromEntries(Object.entries(endpoints).map(([id, value]) => {
89
+ const endpoint = STATE in value ? value[STATE] : value;
90
+ return [id, Object.freeze({
91
+ ...endpoint,
92
+ operationId: id,
93
+ params: snapshotParameters(endpoint.params),
94
+ query: snapshotParameters(endpoint.query),
95
+ headers: snapshotParameters(endpoint.headers),
96
+ security: snapshotSecurity(endpoint.security),
97
+ responses: Object.freeze({ ...endpoint.responses }),
98
+ errors: Object.freeze({ ...endpoint.errors })
99
+ })];
100
+ }));
101
+ return Object.freeze({
102
+ endpoints: Object.freeze(frozen),
103
+ ...metadata ? { metadata: snapshotMetadata(metadata) } : {}
104
+ });
105
+ }
106
+ //#endregion
107
+ export { defineApi, del, get, head, options, patch, pathNames, post, put };
@@ -0,0 +1,5 @@
1
+ import { AnyEndpointDescriptor, ApiDefinition, ApiMetadata, ClientOptions, Codec, EndpointDescriptor, FailureKind, FailureResult, FetchResult, HttpMethod, HttpResult, InferCodec, InferValidator, Middleware, Next, ParameterMap, ParameterSpec, ParameterStyle, RequestContext, SuccessResult, Validator } from "./types.js";
2
+ import { arrayBuffer, blob, content, empty, json, multipart, stream, text, urlEncoded } from "./codecs.js";
3
+ import { EndpointBuilder, defineApi, del, get, head, options, patch, pathNames, post, put } from "./dsl.js";
4
+ import { AdHocCall, ApiClient, ClientResult, FetchError, createClient, createFetch, unwrap } from "./client.js";
5
+ export { AdHocCall, AnyEndpointDescriptor, ApiClient, ApiDefinition, ApiMetadata, ClientOptions, ClientResult, Codec, EndpointBuilder, EndpointDescriptor, FailureKind, FailureResult, FetchError, FetchResult, HttpMethod, HttpResult, InferCodec, InferValidator, Middleware, Next, ParameterMap, ParameterSpec, ParameterStyle, RequestContext, SuccessResult, Validator, arrayBuffer, blob, content, createClient, createFetch, defineApi, del, empty, get, head, json, multipart, options, patch, pathNames, post, put, stream, text, unwrap, urlEncoded };
package/dist/index.js ADDED
@@ -0,0 +1,4 @@
1
+ import { arrayBuffer, blob, content, empty, json, multipart, stream, text, urlEncoded } from "./codecs.js";
2
+ import { defineApi, del, get, head, options, patch, pathNames, post, put } from "./dsl.js";
3
+ import { FetchError, createClient, createFetch, unwrap } from "./client.js";
4
+ export { FetchError, arrayBuffer, blob, content, createClient, createFetch, defineApi, del, empty, get, head, json, multipart, options, patch, pathNames, post, put, stream, text, unwrap, urlEncoded };
@@ -0,0 +1,28 @@
1
+ import { FetchResult, Middleware, RequestContext } from "./types.js";
2
+ //#region src/middleware.d.ts
3
+ declare const bearerAuth: ({ token }: {
4
+ token: string | (() => string | Promise<string>);
5
+ }) => Middleware;
6
+ declare function apiKeyAuth({ key, value, in: location }: {
7
+ key: string;
8
+ value: string | (() => string | Promise<string>);
9
+ in?: "header" | "query";
10
+ }): Middleware;
11
+ interface RetryOptions {
12
+ attempts?: number;
13
+ methods?: readonly string[];
14
+ statuses?: readonly number[];
15
+ delay?: (attempt: number) => number;
16
+ }
17
+ declare function retry(options?: RetryOptions): Middleware;
18
+ declare function logging(logger?: {
19
+ log(event: Record<string, unknown>): void;
20
+ }): Middleware;
21
+ interface TelemetryHooks {
22
+ start?(context: RequestContext): unknown;
23
+ end?(span: unknown, result: FetchResult): void;
24
+ error?(span: unknown, error: unknown): void;
25
+ }
26
+ declare function telemetry(hooks: TelemetryHooks): Middleware;
27
+ //#endregion
28
+ export { RetryOptions, TelemetryHooks, apiKeyAuth, bearerAuth, logging, retry, telemetry };
@@ -0,0 +1,140 @@
1
+ //#region src/middleware.ts
2
+ const SENSITIVE = Symbol("askr-fetch-sensitive-fields");
3
+ const markSensitive = (context, location, name) => {
4
+ const current = context[SENSITIVE] ?? {
5
+ headers: [],
6
+ query: []
7
+ };
8
+ return Object.freeze({
9
+ ...context,
10
+ [SENSITIVE]: Object.freeze({
11
+ ...current,
12
+ [location]: Object.freeze([.../* @__PURE__ */ new Set([...current[location], name.toLowerCase()])])
13
+ })
14
+ });
15
+ };
16
+ const replaceHeaders = (context, mutate) => {
17
+ const headers = new Headers(context.request.headers);
18
+ mutate(headers);
19
+ return Object.freeze({
20
+ ...context,
21
+ request: new Request(context.request, { headers })
22
+ });
23
+ };
24
+ const bearerAuth = ({ token }) => async (context, next) => {
25
+ const resolved = typeof token === "function" ? await token() : token;
26
+ return next(replaceHeaders(context, (headers) => headers.set("authorization", `Bearer ${resolved}`)));
27
+ };
28
+ function apiKeyAuth({ key, value, in: location = "header" }) {
29
+ return async (context, next) => {
30
+ const resolved = typeof value === "function" ? await value() : value;
31
+ if (location === "header") return next(markSensitive(replaceHeaders(context, (headers) => headers.set(key, resolved)), "headers", key));
32
+ const url = new URL(context.request.url);
33
+ url.searchParams.set(key, resolved);
34
+ return next(markSensitive(Object.freeze({
35
+ ...context,
36
+ request: new Request(url, context.request)
37
+ }), "query", key));
38
+ };
39
+ }
40
+ function retry(options = {}) {
41
+ const attempts = options.attempts ?? 3;
42
+ const methods = options.methods ?? [
43
+ "GET",
44
+ "HEAD",
45
+ "PUT",
46
+ "DELETE",
47
+ "OPTIONS"
48
+ ];
49
+ const statuses = options.statuses ?? [
50
+ 408,
51
+ 425,
52
+ 429,
53
+ 500,
54
+ 502,
55
+ 503,
56
+ 504
57
+ ];
58
+ return async (context, next) => {
59
+ if (!methods.includes(context.request.method) || context.request.body) return next(context);
60
+ let result = await next(context);
61
+ for (let attempt = 2; attempt <= attempts && !result.ok && (result.kind === "network" || result.response !== void 0 && statuses.includes(result.status)); attempt++) {
62
+ const retryAfter = "response" in result ? result.response?.headers.get("retry-after") : null;
63
+ const wait = retryAfter ? /^\d+$/.test(retryAfter) ? Number(retryAfter) * 1e3 : Math.max(0, Date.parse(retryAfter) - Date.now()) : options.delay?.(attempt) ?? 100 * 2 ** (attempt - 2);
64
+ if (context.deadline && Date.now() + wait >= context.deadline) break;
65
+ if (!await new Promise((resolve) => {
66
+ const onAbort = () => {
67
+ clearTimeout(timer);
68
+ resolve(false);
69
+ };
70
+ const timer = setTimeout(() => {
71
+ context.request.signal.removeEventListener("abort", onAbort);
72
+ resolve(true);
73
+ }, wait);
74
+ if (context.request.signal.aborted) onAbort();
75
+ else context.request.signal.addEventListener("abort", onAbort, { once: true });
76
+ })) return {
77
+ ok: false,
78
+ kind: "abort",
79
+ status: 0,
80
+ error: context.request.signal.reason,
81
+ headers: new Headers(),
82
+ url: context.request.url
83
+ };
84
+ result = await next(Object.freeze({
85
+ ...context,
86
+ attempt,
87
+ request: context.request.clone()
88
+ }));
89
+ }
90
+ return result;
91
+ };
92
+ }
93
+ const SENSITIVE_NAME = /(?:^|[-_])(authorization|cookie|token|secret|password|api[-_]?key)(?:$|[-_])/i;
94
+ const redacted = (headers, names = []) => Object.fromEntries([...headers].map(([key, value]) => [key, SENSITIVE_NAME.test(key) || names.includes(key.toLowerCase()) ? "[REDACTED]" : value]));
95
+ const redactedUrl = (value, names = []) => {
96
+ const url = new URL(value);
97
+ for (const key of new Set(url.searchParams.keys())) if (SENSITIVE_NAME.test(key) || names.includes(key.toLowerCase())) {
98
+ const count = url.searchParams.getAll(key).length;
99
+ url.searchParams.delete(key);
100
+ for (let index = 0; index < count; index++) url.searchParams.append(key, "[REDACTED]");
101
+ }
102
+ return url.toString();
103
+ };
104
+ function logging(logger = console) {
105
+ return async (context, next) => {
106
+ const sensitive = context[SENSITIVE];
107
+ logger.log({
108
+ phase: "request",
109
+ operationId: context.operationId,
110
+ method: context.request.method,
111
+ url: redactedUrl(context.request.url, sensitive?.query),
112
+ headers: redacted(context.request.headers, sensitive?.headers),
113
+ attempt: context.attempt
114
+ });
115
+ const result = await next(context);
116
+ logger.log({
117
+ phase: "response",
118
+ operationId: context.operationId,
119
+ kind: result.kind,
120
+ status: result.status,
121
+ attempt: context.attempt
122
+ });
123
+ return result;
124
+ };
125
+ }
126
+ function telemetry(hooks) {
127
+ return async (context, next) => {
128
+ const span = hooks.start?.(context);
129
+ try {
130
+ const result = await next(context);
131
+ hooks.end?.(span, result);
132
+ return result;
133
+ } catch (error) {
134
+ hooks.error?.(span, error);
135
+ throw error;
136
+ }
137
+ };
138
+ }
139
+ //#endregion
140
+ export { apiKeyAuth, bearerAuth, logging, retry, telemetry };
@@ -0,0 +1,107 @@
1
+ //#region src/types.d.ts
2
+ interface Validator<T = unknown> {
3
+ safeParse(value: unknown): {
4
+ success: true;
5
+ data: T;
6
+ } | {
7
+ success: false;
8
+ error: unknown;
9
+ };
10
+ }
11
+ type InferValidator<V> = V extends Validator<infer T> ? T : never;
12
+ interface Codec<T = unknown> {
13
+ readonly kind: "json" | "text" | "urlEncoded" | "multipart" | "blob" | "arrayBuffer" | "stream" | "empty" | "content";
14
+ readonly mediaTypes: readonly string[];
15
+ readonly validator?: Validator<T>;
16
+ readonly variants?: Readonly<Record<string, Codec<unknown>>>;
17
+ }
18
+ type InferCodec<C> = C extends Codec<infer T> ? T : never;
19
+ type HttpMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE" | "HEAD" | "OPTIONS";
20
+ type ParameterStyle = "simple" | "label" | "matrix" | "form" | "spaceDelimited" | "pipeDelimited" | "deepObject";
21
+ interface ParameterSpec<T = unknown> {
22
+ readonly validator?: Validator<T>;
23
+ readonly style?: ParameterStyle;
24
+ readonly explode?: boolean;
25
+ }
26
+ type ParameterMap = Readonly<Record<string, Validator<unknown> | ParameterSpec | undefined>>;
27
+ interface EndpointDescriptor<P = undefined, Q = undefined, H = undefined, B = undefined, R extends Record<number, Codec> = Record<number, Codec>, E extends Partial<Record<number | "default", Codec>> = Partial<Record<number | "default", Codec>>> {
28
+ readonly method: HttpMethod;
29
+ readonly path: string;
30
+ readonly params?: ParameterMap;
31
+ readonly query?: ParameterMap;
32
+ readonly headers?: ParameterMap;
33
+ readonly body?: Codec;
34
+ readonly responses: Readonly<R>;
35
+ readonly errors: Readonly<E>;
36
+ readonly security?: readonly Readonly<Record<string, readonly string[]>>[];
37
+ readonly operationId?: string;
38
+ readonly __input?: {
39
+ params: P;
40
+ query: Q;
41
+ headers: H;
42
+ body: B;
43
+ };
44
+ }
45
+ type AnyEndpointDescriptor = EndpointDescriptor<any, any, any, any, any, any>;
46
+ interface ApiMetadata {
47
+ readonly servers?: readonly (string | {
48
+ readonly url: string;
49
+ })[];
50
+ readonly tags?: readonly unknown[];
51
+ readonly securitySchemes?: Readonly<Record<string, unknown>>;
52
+ }
53
+ interface ApiDefinition<E extends Record<string, AnyEndpointDescriptor> = Record<string, AnyEndpointDescriptor>> {
54
+ readonly endpoints: E;
55
+ readonly metadata?: ApiMetadata;
56
+ }
57
+ type SuccessResult<T = unknown, S extends number = number> = {
58
+ ok: true;
59
+ kind: "success";
60
+ status: S;
61
+ data: T;
62
+ mediaType: string | null;
63
+ headers: Headers;
64
+ url: string;
65
+ response: Response;
66
+ };
67
+ type HttpResult<T = unknown, S extends number = number> = {
68
+ ok: false;
69
+ kind: "http";
70
+ status: S;
71
+ error: T;
72
+ mediaType: string | null;
73
+ headers: Headers;
74
+ url: string;
75
+ response: Response;
76
+ };
77
+ type FailureKind = "request" | "network" | "timeout" | "abort" | "decode" | "middleware";
78
+ type FailureResult = {
79
+ ok: false;
80
+ kind: FailureKind;
81
+ status: number;
82
+ error: unknown;
83
+ headers: Headers;
84
+ url: string;
85
+ response?: Response;
86
+ };
87
+ type FetchResult<T = unknown> = SuccessResult<T> | HttpResult<T> | FailureResult;
88
+ interface RequestContext {
89
+ readonly request: Request;
90
+ readonly endpoint?: AnyEndpointDescriptor;
91
+ readonly operationId?: string;
92
+ readonly security?: AnyEndpointDescriptor["security"];
93
+ readonly attempt: number;
94
+ readonly deadline?: number;
95
+ }
96
+ type Next = (context?: RequestContext) => Promise<FetchResult>;
97
+ type Middleware = (context: RequestContext, next: Next) => Promise<FetchResult>;
98
+ interface ClientOptions {
99
+ baseUrl?: string;
100
+ fetch?: (request: Request) => Promise<Response>;
101
+ headers?: HeadersInit;
102
+ credentials?: RequestCredentials;
103
+ timeout?: number;
104
+ middleware?: readonly Middleware[];
105
+ }
106
+ //#endregion
107
+ export { AnyEndpointDescriptor, ApiDefinition, ApiMetadata, ClientOptions, Codec, EndpointDescriptor, FailureKind, FailureResult, FetchResult, HttpMethod, HttpResult, InferCodec, InferValidator, Middleware, Next, ParameterMap, ParameterSpec, ParameterStyle, RequestContext, SuccessResult, Validator };
package/package.json ADDED
@@ -0,0 +1,72 @@
1
+ {
2
+ "name": "@askrjs/fetch",
3
+ "version": "0.0.1",
4
+ "description": "Function-first typed HTTP contracts and clients for Askr.",
5
+ "keywords": [
6
+ "askr",
7
+ "fetch",
8
+ "http",
9
+ "typescript"
10
+ ],
11
+ "homepage": "https://github.com/askrjs/askr-fetch#readme",
12
+ "bugs": {
13
+ "url": "https://github.com/askrjs/askr-fetch/issues"
14
+ },
15
+ "license": "Apache-2.0",
16
+ "author": {
17
+ "name": "askrjs",
18
+ "url": "https://github.com/askrjs"
19
+ },
20
+ "repository": {
21
+ "type": "git",
22
+ "url": "git+https://github.com/askrjs/askr-fetch.git"
23
+ },
24
+ "files": [
25
+ "dist/**/*.js",
26
+ "dist/**/*.d.ts",
27
+ "README.md",
28
+ "LICENSE"
29
+ ],
30
+ "type": "module",
31
+ "sideEffects": false,
32
+ "main": "./dist/index.js",
33
+ "types": "./dist/index.d.ts",
34
+ "exports": {
35
+ ".": {
36
+ "types": "./dist/index.d.ts",
37
+ "import": "./dist/index.js"
38
+ },
39
+ "./middleware": {
40
+ "types": "./dist/middleware.d.ts",
41
+ "import": "./dist/middleware.js"
42
+ },
43
+ "./package.json": "./package.json"
44
+ },
45
+ "publishConfig": {
46
+ "access": "public"
47
+ },
48
+ "scripts": {
49
+ "build": "vp pack",
50
+ "fmt": "vp fmt .",
51
+ "lint": "vp lint src tests vite.config.ts && npm run typecheck",
52
+ "typecheck": "tsc -p tsconfig.json --noEmit --pretty false",
53
+ "test": "vp test run",
54
+ "test:installed": "node tests/installed-smoke.mjs",
55
+ "test:publint": "publint",
56
+ "pack:check": "npm pack --ignore-scripts --dry-run --json",
57
+ "check": "npm run lint && npm test && npm run build && npm run test:installed && npm run test:publint && npm run pack:check",
58
+ "prepack": "npm run build",
59
+ "prepublishOnly": "npm run check"
60
+ },
61
+ "devDependencies": {
62
+ "@types/node": "^26.1.1",
63
+ "publint": "^0.3.21",
64
+ "typescript": "^6.0.3",
65
+ "vite-plus": "^0.2.4",
66
+ "vitest": "^4.1.10"
67
+ },
68
+ "engines": {
69
+ "node": ">=20.19.0"
70
+ },
71
+ "packageManager": "npm@12.0.1"
72
+ }