@zap-studio/fetch 0.5.4 → 0.5.6
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/CHANGELOG.md +15 -0
- package/LICENSE +1 -1
- package/README.md +19 -5
- package/dist/constants.d.ts +17 -0
- package/dist/constants.d.ts.map +1 -0
- package/dist/{constants.mjs → constants.js} +1 -1
- package/dist/constants.js.map +1 -0
- package/dist/errors.d.ts +41 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/{errors.mjs → errors.js} +1 -1
- package/dist/errors.js.map +1 -0
- package/dist/fetch-D0IXjsUD.js +222 -0
- package/dist/fetch-D0IXjsUD.js.map +1 -0
- package/dist/fetch.d.ts +114 -0
- package/dist/fetch.d.ts.map +1 -0
- package/dist/fetch.js +3 -0
- package/dist/headers.d.ts +26 -0
- package/dist/headers.d.ts.map +1 -0
- package/dist/{headers.mjs → headers.js} +6 -6
- package/dist/headers.js.map +1 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.js +7 -0
- package/dist/request.d.ts +30 -0
- package/dist/request.d.ts.map +1 -0
- package/dist/{request.mjs → request.js} +15 -12
- package/dist/request.js.map +1 -0
- package/dist/types.d.ts +168 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +0 -0
- package/dist/url.d.ts +26 -0
- package/dist/url.d.ts.map +1 -0
- package/dist/{url.mjs → url.js} +36 -37
- package/dist/url.js.map +1 -0
- package/package.json +19 -28
- package/dist/constants.d.mts +0 -18
- package/dist/constants.d.mts.map +0 -1
- package/dist/constants.mjs.map +0 -1
- package/dist/errors.d.mts +0 -41
- package/dist/errors.d.mts.map +0 -1
- package/dist/errors.mjs.map +0 -1
- package/dist/headers.d.mts +0 -26
- package/dist/headers.d.mts.map +0 -1
- package/dist/headers.mjs.map +0 -1
- package/dist/index.d.mts +0 -115
- package/dist/index.d.mts.map +0 -1
- package/dist/index.mjs +0 -103
- package/dist/index.mjs.map +0 -1
- package/dist/internal.d.mts +0 -33
- package/dist/internal.d.mts.map +0 -1
- package/dist/internal.mjs +0 -76
- package/dist/internal.mjs.map +0 -1
- package/dist/methods.d.mts +0 -23
- package/dist/methods.d.mts.map +0 -1
- package/dist/methods.mjs +0 -58
- package/dist/methods.mjs.map +0 -1
- package/dist/request.d.mts +0 -31
- package/dist/request.d.mts.map +0 -1
- package/dist/request.mjs.map +0 -1
- package/dist/types.d.mts +0 -169
- package/dist/types.d.mts.map +0 -1
- package/dist/types.mjs +0 -1
- package/dist/url.d.mts +0 -27
- package/dist/url.d.mts.map +0 -1
- package/dist/url.mjs.map +0 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,3 +1,18 @@
|
|
|
1
|
+
## @zap-studio/fetch@0.5.6
|
|
2
|
+
|
|
3
|
+
### Tree-shakeable root re-exports
|
|
4
|
+
|
|
5
|
+
The package root now re-exports the full public API, so everything can be imported from `@zap-studio/fetch` directly (`$fetch`, `api`, `createFetch`, `FetchError`, `mergeHeaders`, `GLOBAL_DEFAULTS`, `normalizeRequest`, `resolveRequestUrl`, and all public types). All exports are side-effect free and tree-shakeable; granular subpath imports keep working.
|
|
6
|
+
|
|
7
|
+
- The `$fetch`/`api`/`createFetch` implementation moved from the entrypoint into its own module, available as the new `./fetch` subpath.
|
|
8
|
+
- Removed the `./internal` and `./methods` subpath exports. Both were implementation details (`fetchInternal`, `createMethod`) and are no longer part of the public API.
|
|
9
|
+
|
|
10
|
+
## @zap-studio/fetch@0.5.5
|
|
11
|
+
|
|
12
|
+
### Migrate to ultracite lint/format
|
|
13
|
+
|
|
14
|
+
Internal formatting and lint cleanup only. No public API or behavior change.
|
|
15
|
+
|
|
1
16
|
# @zap-studio/fetch
|
|
2
17
|
|
|
3
18
|
## 0.5.4
|
package/LICENSE
CHANGED
package/README.md
CHANGED
|
@@ -5,9 +5,25 @@ A small fetch wrapper with [**Standard Schema**](https://standardschema.dev/sche
|
|
|
5
5
|
## Installation
|
|
6
6
|
|
|
7
7
|
```bash
|
|
8
|
+
nub add @zap-studio/fetch
|
|
9
|
+
# or
|
|
8
10
|
npm install @zap-studio/fetch
|
|
11
|
+
# or
|
|
12
|
+
pnpm add @zap-studio/fetch
|
|
9
13
|
```
|
|
10
14
|
|
|
15
|
+
## Runtime Support
|
|
16
|
+
|
|
17
|
+
| Runtime | Minimum version |
|
|
18
|
+
| ------------------ | ------------------------------------------------ |
|
|
19
|
+
| Node.js | 18.0.0 (ships native `fetch`) |
|
|
20
|
+
| Bun | 1.0.0 |
|
|
21
|
+
| Deno | 1.42 |
|
|
22
|
+
| Cloudflare Workers | Any current release |
|
|
23
|
+
| Browsers | Latest evergreen (Chrome, Edge, Firefox, Safari) |
|
|
24
|
+
|
|
25
|
+
The package relies on the global `fetch` API and ships standard ESM only. Deno 1.42 is the first release that can install packages from JSR (`deno add jsr:@zap-studio/fetch`).
|
|
26
|
+
|
|
11
27
|
## Quick Example
|
|
12
28
|
|
|
13
29
|
```ts
|
|
@@ -107,8 +123,7 @@ const created = await api.post("/api/users", UserSchema, {
|
|
|
107
123
|
});
|
|
108
124
|
```
|
|
109
125
|
|
|
110
|
-
In this example, `UserSchema` validates the response from `/api/users`.
|
|
111
|
-
The `json` value is the outgoing request body and is not validated by `UserSchema`.
|
|
126
|
+
In this example, `UserSchema` validates the response from `/api/users`. The `json` value is the outgoing request body and is not validated by `UserSchema`.
|
|
112
127
|
|
|
113
128
|
These helpers set the HTTP method for you. For raw responses without validation, use `$fetch`.
|
|
114
129
|
|
|
@@ -124,8 +139,7 @@ await api.post("/api/users", UserSchema, {
|
|
|
124
139
|
});
|
|
125
140
|
```
|
|
126
141
|
|
|
127
|
-
The schema argument still validates the response. Validate request bodies separately before
|
|
128
|
-
passing them to `json` if your application needs outgoing payload validation.
|
|
142
|
+
The schema argument still validates the response. Validate request bodies separately before passing them to `json` if your application needs outgoing payload validation.
|
|
129
143
|
|
|
130
144
|
This sets:
|
|
131
145
|
|
|
@@ -230,7 +244,7 @@ if (result.issues) {
|
|
|
230
244
|
By default, non-ok responses throw a `FetchError`.
|
|
231
245
|
|
|
232
246
|
```ts
|
|
233
|
-
import { FetchError } from "@zap-studio/fetch
|
|
247
|
+
import { FetchError } from "@zap-studio/fetch";
|
|
234
248
|
|
|
235
249
|
try {
|
|
236
250
|
await api.get("/api/users/404", UserSchema);
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { FetchDefaults } from "./types.js";
|
|
2
|
+
//#region src/constants.d.ts
|
|
3
|
+
/**
|
|
4
|
+
* Default options for the global $fetch
|
|
5
|
+
*
|
|
6
|
+
* These defaults are used by the top-level `$fetch` export.
|
|
7
|
+
* Use `createFetch(...)` when you need per-client defaults.
|
|
8
|
+
*
|
|
9
|
+
* @example
|
|
10
|
+
* import { GLOBAL_DEFAULTS } from "@zap-studio/fetch/constants";
|
|
11
|
+
*
|
|
12
|
+
* console.log(GLOBAL_DEFAULTS.throwOnFetchError); // true
|
|
13
|
+
*/
|
|
14
|
+
declare const GLOBAL_DEFAULTS: FetchDefaults;
|
|
15
|
+
//#endregion
|
|
16
|
+
export { GLOBAL_DEFAULTS };
|
|
17
|
+
//# sourceMappingURL=constants.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"constants.d.ts","names":[],"sources":["../src/constants.ts"],"mappings":";;;;;;;;;;;;;cAmBa,iBAAiB"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"constants.js","names":[],"sources":["../src/constants.ts"],"sourcesContent":["/**\n * Shared defaults and constants for fetch behavior.\n *\n * @module @zap-studio/fetch/constants\n */\n\nimport type { FetchDefaults } from \"./types.js\";\n\n/**\n * Default options for the global $fetch\n *\n * These defaults are used by the top-level `$fetch` export.\n * Use `createFetch(...)` when you need per-client defaults.\n *\n * @example\n * import { GLOBAL_DEFAULTS } from \"@zap-studio/fetch/constants\";\n *\n * console.log(GLOBAL_DEFAULTS.throwOnFetchError); // true\n */\nexport const GLOBAL_DEFAULTS: FetchDefaults = {\n baseURL: \"\",\n throwOnFetchError: true,\n throwOnValidationError: true,\n};\n"],"mappings":";;;;;;;;;;;;AAmBA,MAAa,kBAAiC;CAC5C,SAAS;CACT,mBAAmB;CACnB,wBAAwB;AAC1B"}
|
package/dist/errors.d.ts
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
//#region src/errors.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* Custom error types used by the fetch package.
|
|
4
|
+
*
|
|
5
|
+
* @module @zap-studio/fetch/errors
|
|
6
|
+
*/
|
|
7
|
+
/**
|
|
8
|
+
* Error thrown for HTTP errors (non-2xx responses)
|
|
9
|
+
*
|
|
10
|
+
* Includes the failing `Response` object and status code for
|
|
11
|
+
* downstream error handling and response inspection.
|
|
12
|
+
*
|
|
13
|
+
* @example
|
|
14
|
+
* import { FetchError } from "@zap-studio/fetch/errors";
|
|
15
|
+
*
|
|
16
|
+
* try {
|
|
17
|
+
* await $fetch("/users/404");
|
|
18
|
+
* } catch (error) {
|
|
19
|
+
* if (error instanceof FetchError) {
|
|
20
|
+
* console.error(error.status);
|
|
21
|
+
* console.error(await error.response.text());
|
|
22
|
+
* }
|
|
23
|
+
* }
|
|
24
|
+
*/
|
|
25
|
+
declare class FetchError extends Error {
|
|
26
|
+
/**
|
|
27
|
+
* HTTP status code from the failing response.
|
|
28
|
+
*/
|
|
29
|
+
status: Response["status"];
|
|
30
|
+
/**
|
|
31
|
+
* Full response object for additional inspection.
|
|
32
|
+
*/
|
|
33
|
+
response: Response;
|
|
34
|
+
/**
|
|
35
|
+
* Creates a FetchError from a non-ok response.
|
|
36
|
+
*/
|
|
37
|
+
constructor(message: string, response: Response);
|
|
38
|
+
}
|
|
39
|
+
//#endregion
|
|
40
|
+
export { FetchError };
|
|
41
|
+
//# sourceMappingURL=errors.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"errors.d.ts","names":[],"sources":["../src/errors.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;cAwBa,mBAAmB;;;;EAI9B,QAAQ;;;;EAIR,UAAU;;;;EAKV,YAAY,iBAAiB,UAAU"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"errors.js","names":[],"sources":["../src/errors.ts"],"sourcesContent":["/**\n * Custom error types used by the fetch package.\n *\n * @module @zap-studio/fetch/errors\n */\n\n/**\n * Error thrown for HTTP errors (non-2xx responses)\n *\n * Includes the failing `Response` object and status code for\n * downstream error handling and response inspection.\n *\n * @example\n * import { FetchError } from \"@zap-studio/fetch/errors\";\n *\n * try {\n * await $fetch(\"/users/404\");\n * } catch (error) {\n * if (error instanceof FetchError) {\n * console.error(error.status);\n * console.error(await error.response.text());\n * }\n * }\n */\nexport class FetchError extends Error {\n /**\n * HTTP status code from the failing response.\n */\n status: Response[\"status\"];\n /**\n * Full response object for additional inspection.\n */\n response: Response;\n\n /**\n * Creates a FetchError from a non-ok response.\n */\n constructor(message: string, response: Response) {\n super(message);\n this.name = \"FetchError\";\n this.status = response.status;\n this.response = response;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAwBA,IAAa,aAAb,cAAgC,MAAM;;;;CAIpC;;;;CAIA;;;;CAKA,YAAY,SAAiB,UAAoB;EAC/C,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,SAAS,SAAS;EACvB,KAAK,WAAW;CAClB;AACF"}
|
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
import { GLOBAL_DEFAULTS } from "./constants.js";
|
|
2
|
+
import { FetchError } from "./errors.js";
|
|
3
|
+
import { mergeHeaders } from "./headers.js";
|
|
4
|
+
import { normalizeRequest } from "./request.js";
|
|
5
|
+
import { resolveRequestUrl } from "./url.js";
|
|
6
|
+
import { isStandardSchema, standardValidate } from "@zap-studio/validation";
|
|
7
|
+
//#region src/_internal.ts
|
|
8
|
+
/**
|
|
9
|
+
* Normalizes request-level options into a final RequestInit payload and runtime flags.
|
|
10
|
+
*
|
|
11
|
+
* @param options - Request-level options.
|
|
12
|
+
* @param defaults - Client-level defaults.
|
|
13
|
+
* @returns Fully merged request init payload and effective runtime flags.
|
|
14
|
+
*/
|
|
15
|
+
const prepareRequestInit = (options, defaults) => {
|
|
16
|
+
const { headers, json, searchParams, throwOnFetchError = defaults.throwOnFetchError, throwOnValidationError = defaults.throwOnValidationError, ...rest } = options;
|
|
17
|
+
const init = { ...rest };
|
|
18
|
+
const mergedHeaders = mergeHeaders(defaults.headers, headers);
|
|
19
|
+
if (mergedHeaders !== void 0) init.headers = mergedHeaders;
|
|
20
|
+
if (json !== void 0) {
|
|
21
|
+
if (init.body !== void 0 && init.body !== null) throw new TypeError("Cannot provide both `body` and `json`.");
|
|
22
|
+
init.body = JSON.stringify(json);
|
|
23
|
+
if (init.headers === void 0) init.headers = new Headers({ "Content-Type": "application/json" });
|
|
24
|
+
else {
|
|
25
|
+
const requestHeaders = new Headers(init.headers);
|
|
26
|
+
if (!requestHeaders.has("Content-Type")) requestHeaders.set("Content-Type", "application/json");
|
|
27
|
+
init.headers = requestHeaders;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
return {
|
|
31
|
+
init,
|
|
32
|
+
searchParams,
|
|
33
|
+
throwOnFetchError,
|
|
34
|
+
throwOnValidationError
|
|
35
|
+
};
|
|
36
|
+
};
|
|
37
|
+
/**
|
|
38
|
+
* Internal fetch implementation used by both $fetch and createFetch.
|
|
39
|
+
*
|
|
40
|
+
* This function normalizes request input, resolves final URL + query params,
|
|
41
|
+
* executes `fetch`, optionally throws `FetchError`, and optionally validates
|
|
42
|
+
* JSON response payloads using Standard Schema.
|
|
43
|
+
*
|
|
44
|
+
* @param input - Request URL, path, or Request object.
|
|
45
|
+
* @param schema - Optional Standard Schema for response validation.
|
|
46
|
+
* @param options - Optional request options and package-specific flags.
|
|
47
|
+
* @param defaults - Effective client defaults.
|
|
48
|
+
* @returns Raw `Response` when no schema is provided; otherwise validated output.
|
|
49
|
+
* @throws {FetchError} When `throwOnFetchError` is `true` and the response is not ok.
|
|
50
|
+
* @throws {ValidationError} When a schema is provided, validation returns issues, and
|
|
51
|
+
* `throwOnValidationError` is `true`.
|
|
52
|
+
* @throws {TypeError} When both `body` and `json` are provided, when JSON request
|
|
53
|
+
* serialization fails, when request construction fails, when headers/search params are
|
|
54
|
+
* invalid, when `response.json()` cannot read the body, or when the runtime `fetch`
|
|
55
|
+
* implementation rejects network-level failures as `TypeError`.
|
|
56
|
+
* @throws {DOMException} When the runtime rejects an aborted request or response body read
|
|
57
|
+
* as an `AbortError` DOMException.
|
|
58
|
+
* @throws {SyntaxError} When a schema is provided and `response.json()` cannot parse the
|
|
59
|
+
* response body.
|
|
60
|
+
* @throws {unknown} Any error thrown or rejected by the provided Standard Schema validator.
|
|
61
|
+
*/
|
|
62
|
+
const fetchInternal = async (input, schema, options, defaults) => {
|
|
63
|
+
const request = normalizeRequest(input, options);
|
|
64
|
+
const { init, searchParams, throwOnFetchError, throwOnValidationError } = prepareRequestInit(request.options, defaults);
|
|
65
|
+
const url = resolveRequestUrl(request.url, defaults, searchParams);
|
|
66
|
+
const response = request.request ? await fetch(new Request(url, request.request), init) : await fetch(url, init);
|
|
67
|
+
if (throwOnFetchError && !response.ok) throw new FetchError(`HTTP ${response.status}: ${response.statusText}`, response);
|
|
68
|
+
if (schema === void 0) return response;
|
|
69
|
+
const raw = await response.json();
|
|
70
|
+
if (throwOnValidationError) return await standardValidate(schema, raw, { throwOnError: true });
|
|
71
|
+
return await standardValidate(schema, raw, { throwOnError: false });
|
|
72
|
+
};
|
|
73
|
+
//#endregion
|
|
74
|
+
//#region src/_methods.ts
|
|
75
|
+
/**
|
|
76
|
+
* Method helper factories used to build verb-specific fetch functions.
|
|
77
|
+
*
|
|
78
|
+
* @module @zap-studio/fetch/_methods (private)
|
|
79
|
+
*/
|
|
80
|
+
/**
|
|
81
|
+
* Creates an HTTP method helper bound to a fetch function.
|
|
82
|
+
*
|
|
83
|
+
* The returned function mirrors `$Fetch` overloads but forces the provided
|
|
84
|
+
* HTTP method (`GET`, `POST`, etc.) into request options.
|
|
85
|
+
*
|
|
86
|
+
* @param fetchFn - Fetch function to wrap.
|
|
87
|
+
* @param method - HTTP method to enforce.
|
|
88
|
+
* @returns Method-bound fetch function.
|
|
89
|
+
* @throws {unknown} Any error thrown or rejected by `fetchFn` when the returned method-bound
|
|
90
|
+
* fetch function is called.
|
|
91
|
+
*
|
|
92
|
+
* @example
|
|
93
|
+
* const get = createMethod($fetch, "GET");
|
|
94
|
+
* const user = await get("/users/1", UserSchema);
|
|
95
|
+
*/
|
|
96
|
+
const createMethod = (fetchFn, method) => {
|
|
97
|
+
/**
|
|
98
|
+
* Method-bound `$Fetch` implementation.
|
|
99
|
+
*
|
|
100
|
+
* Resolves schema/option overloads and injects the configured HTTP method.
|
|
101
|
+
*/
|
|
102
|
+
async function methodFetch(input, schemaOrOptions, optionsOrUndefined) {
|
|
103
|
+
if (isStandardSchema(schemaOrOptions)) {
|
|
104
|
+
if (optionsOrUndefined?.throwOnValidationError === false) return await fetchFn(input, schemaOrOptions, {
|
|
105
|
+
...optionsOrUndefined,
|
|
106
|
+
method,
|
|
107
|
+
throwOnValidationError: false
|
|
108
|
+
});
|
|
109
|
+
const { throwOnValidationError, ...restOptions } = optionsOrUndefined ?? {};
|
|
110
|
+
if (throwOnValidationError === true) return await fetchFn(input, schemaOrOptions, {
|
|
111
|
+
...restOptions,
|
|
112
|
+
method,
|
|
113
|
+
throwOnValidationError: true
|
|
114
|
+
});
|
|
115
|
+
return await fetchFn(input, schemaOrOptions, {
|
|
116
|
+
...restOptions,
|
|
117
|
+
method
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
return await fetchFn(input, {
|
|
121
|
+
...schemaOrOptions,
|
|
122
|
+
method
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
return methodFetch;
|
|
126
|
+
};
|
|
127
|
+
//#endregion
|
|
128
|
+
//#region src/fetch.ts
|
|
129
|
+
/**
|
|
130
|
+
* Typed fetch client: `$fetch`, `api` method shortcuts, and the `createFetch`
|
|
131
|
+
* instance factory.
|
|
132
|
+
*
|
|
133
|
+
* @module @zap-studio/fetch/fetch
|
|
134
|
+
*/
|
|
135
|
+
async function $fetch(input, schemaOrOptions, optionsOrUndefined) {
|
|
136
|
+
const [schema, options] = isStandardSchema(schemaOrOptions) ? [schemaOrOptions, optionsOrUndefined] : [void 0, schemaOrOptions];
|
|
137
|
+
return await fetchInternal(input, schema, options, GLOBAL_DEFAULTS);
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* Convenience methods for common HTTP verbs.
|
|
141
|
+
*
|
|
142
|
+
* These methods always require a schema for validation.
|
|
143
|
+
* For raw responses without validation, use `$fetch` directly.
|
|
144
|
+
*
|
|
145
|
+
* Each method has the same throw behavior as {@link $fetch}.
|
|
146
|
+
*
|
|
147
|
+
* @example
|
|
148
|
+
* import { z } from "zod";
|
|
149
|
+
* import { api } from "@zap-studio/fetch";
|
|
150
|
+
*
|
|
151
|
+
* const PostSchema = z.object({
|
|
152
|
+
* id: z.number(),
|
|
153
|
+
* title: z.string(),
|
|
154
|
+
* content: z.string(),
|
|
155
|
+
* });
|
|
156
|
+
*
|
|
157
|
+
* async function fetchPost(postId: number) {
|
|
158
|
+
* const post = await api.get(`https://api.example.com/posts/${postId}`, PostSchema);
|
|
159
|
+
* return post; // post is typed as { id: number; title: string; content: string; }
|
|
160
|
+
* }
|
|
161
|
+
*/
|
|
162
|
+
const api = {
|
|
163
|
+
delete: createMethod($fetch, "DELETE"),
|
|
164
|
+
get: createMethod($fetch, "GET"),
|
|
165
|
+
patch: createMethod($fetch, "PATCH"),
|
|
166
|
+
post: createMethod($fetch, "POST"),
|
|
167
|
+
put: createMethod($fetch, "PUT")
|
|
168
|
+
};
|
|
169
|
+
/**
|
|
170
|
+
* Creates a custom fetch instance with pre-configured defaults.
|
|
171
|
+
*
|
|
172
|
+
* Use this factory to create API clients with a base URL, default headers,
|
|
173
|
+
* and other shared configuration. Each instance is independent.
|
|
174
|
+
*
|
|
175
|
+
* The returned `$fetch` and `api` methods have the same throw behavior as the
|
|
176
|
+
* top-level {@link $fetch} export.
|
|
177
|
+
*
|
|
178
|
+
* @example
|
|
179
|
+
* import { z } from "zod";
|
|
180
|
+
* import { createFetch } from "@zap-studio/fetch";
|
|
181
|
+
*
|
|
182
|
+
* // Create a configured instance
|
|
183
|
+
* const { $fetch, api } = createFetch({
|
|
184
|
+
* baseURL: "https://api.example.com",
|
|
185
|
+
* headers: { "Authorization": "Bearer token" },
|
|
186
|
+
* });
|
|
187
|
+
*
|
|
188
|
+
* const UserSchema = z.object({ id: z.number(), name: z.string() });
|
|
189
|
+
*
|
|
190
|
+
* // Now use relative paths - baseURL is prepended automatically
|
|
191
|
+
* const user = await api.get("/users/1", UserSchema);
|
|
192
|
+
*
|
|
193
|
+
* // Or use $fetch directly
|
|
194
|
+
* const response = await $fetch("/users", UserSchema, { method: "POST", json: { name: "John" } });
|
|
195
|
+
*/
|
|
196
|
+
const createFetch = (factoryOptions = {}) => {
|
|
197
|
+
const defaults = {
|
|
198
|
+
...GLOBAL_DEFAULTS,
|
|
199
|
+
...factoryOptions,
|
|
200
|
+
baseURL: factoryOptions.baseURL ?? GLOBAL_DEFAULTS.baseURL,
|
|
201
|
+
throwOnFetchError: factoryOptions.throwOnFetchError ?? GLOBAL_DEFAULTS.throwOnFetchError,
|
|
202
|
+
throwOnValidationError: factoryOptions.throwOnValidationError ?? GLOBAL_DEFAULTS.throwOnValidationError
|
|
203
|
+
};
|
|
204
|
+
async function customFetch(input, schemaOrOptions, optionsOrUndefined) {
|
|
205
|
+
const [schema, options] = isStandardSchema(schemaOrOptions) ? [schemaOrOptions, optionsOrUndefined] : [void 0, schemaOrOptions];
|
|
206
|
+
return await fetchInternal(input, schema, options, defaults);
|
|
207
|
+
}
|
|
208
|
+
return {
|
|
209
|
+
$fetch: customFetch,
|
|
210
|
+
api: {
|
|
211
|
+
delete: createMethod(customFetch, "DELETE"),
|
|
212
|
+
get: createMethod(customFetch, "GET"),
|
|
213
|
+
patch: createMethod(customFetch, "PATCH"),
|
|
214
|
+
post: createMethod(customFetch, "POST"),
|
|
215
|
+
put: createMethod(customFetch, "PUT")
|
|
216
|
+
}
|
|
217
|
+
};
|
|
218
|
+
};
|
|
219
|
+
//#endregion
|
|
220
|
+
export { api as n, createFetch as r, $fetch as t };
|
|
221
|
+
|
|
222
|
+
//# sourceMappingURL=fetch-D0IXjsUD.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"fetch-D0IXjsUD.js","names":[],"sources":["../src/_internal.ts","../src/_methods.ts","../src/fetch.ts"],"sourcesContent":["/**\n * Internal request execution and option preparation utilities.\n *\n * @module @zap-studio/fetch/_internal (private)\n */\n\nimport type { StandardSchemaV1 } from \"@zap-studio/validation\";\nimport { standardValidate } from \"@zap-studio/validation\";\n\nimport { FetchError } from \"./errors.js\";\nimport { mergeHeaders } from \"./headers.js\";\nimport { normalizeRequest } from \"./request.js\";\nimport type {\n ExtendedRequestInit,\n FetchDefaults,\n FetchInput,\n} from \"./types.js\";\nimport { resolveRequestUrl } from \"./url.js\";\n\n/**\n * Normalizes request-level options into a final RequestInit payload and runtime flags.\n *\n * @param options - Request-level options.\n * @param defaults - Client-level defaults.\n * @returns Fully merged request init payload and effective runtime flags.\n */\nconst prepareRequestInit = (\n options: ExtendedRequestInit,\n defaults: FetchDefaults\n): {\n init: RequestInit;\n searchParams: ExtendedRequestInit[\"searchParams\"] | undefined;\n throwOnFetchError: boolean;\n throwOnValidationError: boolean;\n} => {\n const {\n headers,\n json,\n searchParams,\n throwOnFetchError = defaults.throwOnFetchError,\n throwOnValidationError = defaults.throwOnValidationError,\n ...rest\n } = options;\n\n const init: RequestInit = { ...rest };\n const mergedHeaders = mergeHeaders(defaults.headers, headers);\n if (mergedHeaders !== undefined) {\n init.headers = mergedHeaders;\n }\n\n if (json !== undefined) {\n if (init.body !== undefined && init.body !== null) {\n throw new TypeError(\"Cannot provide both `body` and `json`.\");\n }\n\n init.body = JSON.stringify(json);\n if (init.headers === undefined) {\n init.headers = new Headers({ \"Content-Type\": \"application/json\" });\n } else {\n const requestHeaders = new Headers(init.headers);\n if (!requestHeaders.has(\"Content-Type\")) {\n requestHeaders.set(\"Content-Type\", \"application/json\");\n }\n init.headers = requestHeaders;\n }\n }\n\n return {\n init,\n searchParams,\n throwOnFetchError,\n throwOnValidationError,\n };\n};\n\n/**\n * Internal fetch implementation used by both $fetch and createFetch.\n *\n * This function normalizes request input, resolves final URL + query params,\n * executes `fetch`, optionally throws `FetchError`, and optionally validates\n * JSON response payloads using Standard Schema.\n *\n * @param input - Request URL, path, or Request object.\n * @param schema - Optional Standard Schema for response validation.\n * @param options - Optional request options and package-specific flags.\n * @param defaults - Effective client defaults.\n * @returns Raw `Response` when no schema is provided; otherwise validated output.\n * @throws {FetchError} When `throwOnFetchError` is `true` and the response is not ok.\n * @throws {ValidationError} When a schema is provided, validation returns issues, and\n * `throwOnValidationError` is `true`.\n * @throws {TypeError} When both `body` and `json` are provided, when JSON request\n * serialization fails, when request construction fails, when headers/search params are\n * invalid, when `response.json()` cannot read the body, or when the runtime `fetch`\n * implementation rejects network-level failures as `TypeError`.\n * @throws {DOMException} When the runtime rejects an aborted request or response body read\n * as an `AbortError` DOMException.\n * @throws {SyntaxError} When a schema is provided and `response.json()` cannot parse the\n * response body.\n * @throws {unknown} Any error thrown or rejected by the provided Standard Schema validator.\n */\nexport const fetchInternal = async (\n input: FetchInput,\n schema: StandardSchemaV1 | undefined,\n options: ExtendedRequestInit | undefined,\n defaults: FetchDefaults\n): Promise<unknown> => {\n const request = normalizeRequest(input, options);\n const { init, searchParams, throwOnFetchError, throwOnValidationError } =\n prepareRequestInit(request.options, defaults);\n const url = resolveRequestUrl(request.url, defaults, searchParams);\n const response = request.request\n ? await fetch(new Request(url, request.request), init)\n : await fetch(url, init);\n\n if (throwOnFetchError && !response.ok) {\n throw new FetchError(\n `HTTP ${response.status}: ${response.statusText}`,\n response\n );\n }\n\n if (schema === undefined) {\n return response;\n }\n\n const raw: unknown = await response.json();\n if (throwOnValidationError) {\n return await standardValidate(schema, raw, { throwOnError: true });\n }\n return await standardValidate(schema, raw, { throwOnError: false });\n};\n","/**\n * Method helper factories used to build verb-specific fetch functions.\n *\n * @module @zap-studio/fetch/_methods (private)\n */\n\nimport { isStandardSchema } from \"@zap-studio/validation\";\nimport type { StandardSchemaV1 } from \"@zap-studio/validation\";\n\nimport type { $Fetch, ExtendedRequestInit, FetchInput } from \"./types.js\";\n\n/**\n * Creates an HTTP method helper bound to a fetch function.\n *\n * The returned function mirrors `$Fetch` overloads but forces the provided\n * HTTP method (`GET`, `POST`, etc.) into request options.\n *\n * @param fetchFn - Fetch function to wrap.\n * @param method - HTTP method to enforce.\n * @returns Method-bound fetch function.\n * @throws {unknown} Any error thrown or rejected by `fetchFn` when the returned method-bound\n * fetch function is called.\n *\n * @example\n * const get = createMethod($fetch, \"GET\");\n * const user = await get(\"/users/1\", UserSchema);\n */\nexport const createMethod = (fetchFn: $Fetch, method: string): $Fetch => {\n function methodFetch<TSchema extends StandardSchemaV1>(\n input: FetchInput,\n schema: TSchema,\n options: ExtendedRequestInit & {\n throwOnValidationError: false;\n }\n ): Promise<StandardSchemaV1.Result<StandardSchemaV1.InferOutput<TSchema>>>;\n\n function methodFetch<TSchema extends StandardSchemaV1>(\n input: FetchInput,\n schema: TSchema,\n options?: ExtendedRequestInit & {\n throwOnValidationError?: true;\n }\n ): Promise<StandardSchemaV1.InferOutput<TSchema>>;\n\n function methodFetch(\n input: FetchInput,\n options?: ExtendedRequestInit\n ): Promise<Response>;\n\n /**\n * Method-bound `$Fetch` implementation.\n *\n * Resolves schema/option overloads and injects the configured HTTP method.\n */\n async function methodFetch(\n input: FetchInput,\n schemaOrOptions?: StandardSchemaV1 | ExtendedRequestInit,\n optionsOrUndefined?: ExtendedRequestInit\n ): Promise<unknown> {\n if (isStandardSchema(schemaOrOptions)) {\n if (optionsOrUndefined?.throwOnValidationError === false) {\n return await fetchFn(input, schemaOrOptions, {\n ...optionsOrUndefined,\n method,\n throwOnValidationError: false,\n });\n }\n\n const { throwOnValidationError, ...restOptions } =\n optionsOrUndefined ?? {};\n\n if (throwOnValidationError === true) {\n return await fetchFn(input, schemaOrOptions, {\n ...restOptions,\n method,\n throwOnValidationError: true,\n });\n }\n\n return await fetchFn(input, schemaOrOptions, {\n ...restOptions,\n method,\n });\n }\n\n return await fetchFn(input, {\n ...schemaOrOptions,\n method,\n });\n }\n\n return methodFetch;\n};\n","/**\n * Typed fetch client: `$fetch`, `api` method shortcuts, and the `createFetch`\n * instance factory.\n *\n * @module @zap-studio/fetch/fetch\n */\n\nimport { isStandardSchema } from \"@zap-studio/validation\";\nimport type { StandardSchemaV1 } from \"@zap-studio/validation\";\n\nimport { fetchInternal } from \"./_internal.js\";\nimport { createMethod } from \"./_methods.js\";\nimport { GLOBAL_DEFAULTS } from \"./constants.js\";\nimport type {\n $Fetch,\n ApiMethods,\n ExtendedRequestInit,\n FetchDefaults,\n FetchInput,\n} from \"./types.js\";\n\n/**\n * Type-safe fetch wrapper with Standard Schema validation.\n *\n * - When `throwOnValidationError: true`: validated data of type `TSchema`\n * - When `throwOnValidationError: false`: Standard Schema Result object `{ value?, issues? }`\n * - When `throwOnFetchError: true`: throws `FetchError` on non-ok responses\n *\n * If no schema is provided, returns the raw `Response` object.\n *\n * @throws {FetchError} When `throwOnFetchError` is `true` and the response is not ok.\n * @throws {ValidationError} When a schema is provided, validation returns issues, and\n * `throwOnValidationError` is `true`.\n * @throws {TypeError} When both `body` and `json` are provided, when JSON request\n * serialization fails, when request construction fails, when headers/search params are\n * invalid, when `response.json()` cannot read the body, or when the runtime `fetch`\n * implementation rejects network-level failures as `TypeError`.\n * @throws {DOMException} When the runtime rejects an aborted request or response body read\n * as an `AbortError` DOMException.\n * @throws {SyntaxError} When a schema is provided and `response.json()` cannot parse the\n * response body.\n * @throws {unknown} Any error thrown or rejected by the provided Standard Schema validator.\n *\n * @example\n * import { z } from \"zod\";\n * import { $fetch } from \"@zap-studio/fetch\";\n *\n * const UserSchema = z.object({ id: z.number(), name: z.string() });\n *\n * // Basic usage (schema validation)\n * const user = await $fetch(\"/api/users/1\", UserSchema, { headers: { \"Authorization\": \"Bearer token\" } });\n * console.log(\"Validated user:\", user);\n *\n * // Raw usage (no schema validation and typed Response object)\n * const result = await $fetch(\"/api/data\", { method: \"POST\", body: JSON.stringify({ key: \"value\" }) });\n * const json = await result.json() as ResultType;\n * console.log(\"Raw response data:\", json);\n *\n * // Usage with validation errors returned instead of thrown\n * const result = await $fetch(\"/api/users/1\", UserSchema, { throwOnValidationError: false });\n *\n * if (result.issues) {\n * console.error(\"Validation errors:\", result.issues);\n * } else {\n * console.log(\"Validated user:\", result.value);\n * }\n */\nexport async function $fetch<TSchema extends StandardSchemaV1>(\n input: FetchInput,\n schema: TSchema,\n options: ExtendedRequestInit & { throwOnValidationError: false }\n): Promise<StandardSchemaV1.Result<StandardSchemaV1.InferOutput<TSchema>>>;\n\nexport async function $fetch<TSchema extends StandardSchemaV1>(\n input: FetchInput,\n schema: TSchema,\n options?: ExtendedRequestInit & { throwOnValidationError?: true }\n): Promise<StandardSchemaV1.InferOutput<TSchema>>;\n\nexport async function $fetch(\n input: FetchInput,\n options?: ExtendedRequestInit\n): Promise<Response>;\n\nexport async function $fetch(\n input: FetchInput,\n schemaOrOptions?: StandardSchemaV1 | ExtendedRequestInit,\n optionsOrUndefined?: ExtendedRequestInit\n): Promise<unknown> {\n const [schema, options] = isStandardSchema(schemaOrOptions)\n ? [schemaOrOptions, optionsOrUndefined]\n : [undefined, schemaOrOptions];\n\n return await fetchInternal(input, schema, options, GLOBAL_DEFAULTS);\n}\n\n/**\n * Convenience methods for common HTTP verbs.\n *\n * These methods always require a schema for validation.\n * For raw responses without validation, use `$fetch` directly.\n *\n * Each method has the same throw behavior as {@link $fetch}.\n *\n * @example\n * import { z } from \"zod\";\n * import { api } from \"@zap-studio/fetch\";\n *\n * const PostSchema = z.object({\n * id: z.number(),\n * title: z.string(),\n * content: z.string(),\n * });\n *\n * async function fetchPost(postId: number) {\n * const post = await api.get(`https://api.example.com/posts/${postId}`, PostSchema);\n * return post; // post is typed as { id: number; title: string; content: string; }\n * }\n */\nexport const api: ApiMethods = {\n delete: createMethod($fetch, \"DELETE\"),\n get: createMethod($fetch, \"GET\"),\n patch: createMethod($fetch, \"PATCH\"),\n post: createMethod($fetch, \"POST\"),\n put: createMethod($fetch, \"PUT\"),\n};\n\n/**\n * Creates a custom fetch instance with pre-configured defaults.\n *\n * Use this factory to create API clients with a base URL, default headers,\n * and other shared configuration. Each instance is independent.\n *\n * The returned `$fetch` and `api` methods have the same throw behavior as the\n * top-level {@link $fetch} export.\n *\n * @example\n * import { z } from \"zod\";\n * import { createFetch } from \"@zap-studio/fetch\";\n *\n * // Create a configured instance\n * const { $fetch, api } = createFetch({\n * baseURL: \"https://api.example.com\",\n * headers: { \"Authorization\": \"Bearer token\" },\n * });\n *\n * const UserSchema = z.object({ id: z.number(), name: z.string() });\n *\n * // Now use relative paths - baseURL is prepended automatically\n * const user = await api.get(\"/users/1\", UserSchema);\n *\n * // Or use $fetch directly\n * const response = await $fetch(\"/users\", UserSchema, { method: \"POST\", json: { name: \"John\" } });\n */\nexport const createFetch = (\n factoryOptions: Partial<FetchDefaults> = {}\n): {\n $fetch: $Fetch;\n api: ApiMethods;\n} => {\n const defaults: FetchDefaults = {\n ...GLOBAL_DEFAULTS,\n ...factoryOptions,\n baseURL: factoryOptions.baseURL ?? GLOBAL_DEFAULTS.baseURL,\n throwOnFetchError:\n factoryOptions.throwOnFetchError ?? GLOBAL_DEFAULTS.throwOnFetchError,\n throwOnValidationError:\n factoryOptions.throwOnValidationError ??\n GLOBAL_DEFAULTS.throwOnValidationError,\n };\n\n async function customFetch<TSchema extends StandardSchemaV1>(\n input: FetchInput,\n schema: TSchema,\n options: ExtendedRequestInit & { throwOnValidationError: false }\n ): Promise<StandardSchemaV1.Result<StandardSchemaV1.InferOutput<TSchema>>>;\n\n async function customFetch<TSchema extends StandardSchemaV1>(\n input: FetchInput,\n schema: TSchema,\n options?: ExtendedRequestInit & {\n throwOnValidationError?: true;\n }\n ): Promise<StandardSchemaV1.InferOutput<TSchema>>;\n\n async function customFetch(\n input: FetchInput,\n options?: ExtendedRequestInit\n ): Promise<Response>;\n\n async function customFetch(\n input: FetchInput,\n schemaOrOptions?: StandardSchemaV1 | ExtendedRequestInit,\n optionsOrUndefined?: ExtendedRequestInit\n ): Promise<unknown> {\n const [schema, options] = isStandardSchema(schemaOrOptions)\n ? [schemaOrOptions, optionsOrUndefined]\n : [undefined, schemaOrOptions];\n\n return await fetchInternal(input, schema, options, defaults);\n }\n\n const customApi = {\n delete: createMethod(customFetch, \"DELETE\"),\n get: createMethod(customFetch, \"GET\"),\n patch: createMethod(customFetch, \"PATCH\"),\n post: createMethod(customFetch, \"POST\"),\n put: createMethod(customFetch, \"PUT\"),\n };\n\n return {\n $fetch: customFetch,\n api: customApi,\n };\n};\n"],"mappings":"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"}
|
package/dist/fetch.d.ts
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import { $Fetch, ApiMethods, ExtendedRequestInit, FetchDefaults, FetchInput } from "./types.js";
|
|
2
|
+
import { StandardSchemaV1 } from "@zap-studio/validation";
|
|
3
|
+
//#region src/fetch.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* Type-safe fetch wrapper with Standard Schema validation.
|
|
6
|
+
*
|
|
7
|
+
* - When `throwOnValidationError: true`: validated data of type `TSchema`
|
|
8
|
+
* - When `throwOnValidationError: false`: Standard Schema Result object `{ value?, issues? }`
|
|
9
|
+
* - When `throwOnFetchError: true`: throws `FetchError` on non-ok responses
|
|
10
|
+
*
|
|
11
|
+
* If no schema is provided, returns the raw `Response` object.
|
|
12
|
+
*
|
|
13
|
+
* @throws {FetchError} When `throwOnFetchError` is `true` and the response is not ok.
|
|
14
|
+
* @throws {ValidationError} When a schema is provided, validation returns issues, and
|
|
15
|
+
* `throwOnValidationError` is `true`.
|
|
16
|
+
* @throws {TypeError} When both `body` and `json` are provided, when JSON request
|
|
17
|
+
* serialization fails, when request construction fails, when headers/search params are
|
|
18
|
+
* invalid, when `response.json()` cannot read the body, or when the runtime `fetch`
|
|
19
|
+
* implementation rejects network-level failures as `TypeError`.
|
|
20
|
+
* @throws {DOMException} When the runtime rejects an aborted request or response body read
|
|
21
|
+
* as an `AbortError` DOMException.
|
|
22
|
+
* @throws {SyntaxError} When a schema is provided and `response.json()` cannot parse the
|
|
23
|
+
* response body.
|
|
24
|
+
* @throws {unknown} Any error thrown or rejected by the provided Standard Schema validator.
|
|
25
|
+
*
|
|
26
|
+
* @example
|
|
27
|
+
* import { z } from "zod";
|
|
28
|
+
* import { $fetch } from "@zap-studio/fetch";
|
|
29
|
+
*
|
|
30
|
+
* const UserSchema = z.object({ id: z.number(), name: z.string() });
|
|
31
|
+
*
|
|
32
|
+
* // Basic usage (schema validation)
|
|
33
|
+
* const user = await $fetch("/api/users/1", UserSchema, { headers: { "Authorization": "Bearer token" } });
|
|
34
|
+
* console.log("Validated user:", user);
|
|
35
|
+
*
|
|
36
|
+
* // Raw usage (no schema validation and typed Response object)
|
|
37
|
+
* const result = await $fetch("/api/data", { method: "POST", body: JSON.stringify({ key: "value" }) });
|
|
38
|
+
* const json = await result.json() as ResultType;
|
|
39
|
+
* console.log("Raw response data:", json);
|
|
40
|
+
*
|
|
41
|
+
* // Usage with validation errors returned instead of thrown
|
|
42
|
+
* const result = await $fetch("/api/users/1", UserSchema, { throwOnValidationError: false });
|
|
43
|
+
*
|
|
44
|
+
* if (result.issues) {
|
|
45
|
+
* console.error("Validation errors:", result.issues);
|
|
46
|
+
* } else {
|
|
47
|
+
* console.log("Validated user:", result.value);
|
|
48
|
+
* }
|
|
49
|
+
*/
|
|
50
|
+
declare function $fetch<TSchema extends StandardSchemaV1>(input: FetchInput, schema: TSchema, options: ExtendedRequestInit & {
|
|
51
|
+
throwOnValidationError: false;
|
|
52
|
+
}): Promise<StandardSchemaV1.Result<StandardSchemaV1.InferOutput<TSchema>>>;
|
|
53
|
+
declare function $fetch<TSchema extends StandardSchemaV1>(input: FetchInput, schema: TSchema, options?: ExtendedRequestInit & {
|
|
54
|
+
throwOnValidationError?: true;
|
|
55
|
+
}): Promise<StandardSchemaV1.InferOutput<TSchema>>;
|
|
56
|
+
declare function $fetch(input: FetchInput, options?: ExtendedRequestInit): Promise<Response>;
|
|
57
|
+
/**
|
|
58
|
+
* Convenience methods for common HTTP verbs.
|
|
59
|
+
*
|
|
60
|
+
* These methods always require a schema for validation.
|
|
61
|
+
* For raw responses without validation, use `$fetch` directly.
|
|
62
|
+
*
|
|
63
|
+
* Each method has the same throw behavior as {@link $fetch}.
|
|
64
|
+
*
|
|
65
|
+
* @example
|
|
66
|
+
* import { z } from "zod";
|
|
67
|
+
* import { api } from "@zap-studio/fetch";
|
|
68
|
+
*
|
|
69
|
+
* const PostSchema = z.object({
|
|
70
|
+
* id: z.number(),
|
|
71
|
+
* title: z.string(),
|
|
72
|
+
* content: z.string(),
|
|
73
|
+
* });
|
|
74
|
+
*
|
|
75
|
+
* async function fetchPost(postId: number) {
|
|
76
|
+
* const post = await api.get(`https://api.example.com/posts/${postId}`, PostSchema);
|
|
77
|
+
* return post; // post is typed as { id: number; title: string; content: string; }
|
|
78
|
+
* }
|
|
79
|
+
*/
|
|
80
|
+
declare const api: ApiMethods;
|
|
81
|
+
/**
|
|
82
|
+
* Creates a custom fetch instance with pre-configured defaults.
|
|
83
|
+
*
|
|
84
|
+
* Use this factory to create API clients with a base URL, default headers,
|
|
85
|
+
* and other shared configuration. Each instance is independent.
|
|
86
|
+
*
|
|
87
|
+
* The returned `$fetch` and `api` methods have the same throw behavior as the
|
|
88
|
+
* top-level {@link $fetch} export.
|
|
89
|
+
*
|
|
90
|
+
* @example
|
|
91
|
+
* import { z } from "zod";
|
|
92
|
+
* import { createFetch } from "@zap-studio/fetch";
|
|
93
|
+
*
|
|
94
|
+
* // Create a configured instance
|
|
95
|
+
* const { $fetch, api } = createFetch({
|
|
96
|
+
* baseURL: "https://api.example.com",
|
|
97
|
+
* headers: { "Authorization": "Bearer token" },
|
|
98
|
+
* });
|
|
99
|
+
*
|
|
100
|
+
* const UserSchema = z.object({ id: z.number(), name: z.string() });
|
|
101
|
+
*
|
|
102
|
+
* // Now use relative paths - baseURL is prepended automatically
|
|
103
|
+
* const user = await api.get("/users/1", UserSchema);
|
|
104
|
+
*
|
|
105
|
+
* // Or use $fetch directly
|
|
106
|
+
* const response = await $fetch("/users", UserSchema, { method: "POST", json: { name: "John" } });
|
|
107
|
+
*/
|
|
108
|
+
declare const createFetch: (factoryOptions?: Partial<FetchDefaults>) => {
|
|
109
|
+
$fetch: $Fetch;
|
|
110
|
+
api: ApiMethods;
|
|
111
|
+
};
|
|
112
|
+
//#endregion
|
|
113
|
+
export { $fetch, api, createFetch };
|
|
114
|
+
//# sourceMappingURL=fetch.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"fetch.d.ts","names":[],"sources":["../src/fetch.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAmEsB,OAAO,gBAAgB,kBAC3C,OAAO,YACP,QAAQ,SACR,SAAS;EAAwB;IAChC,QAAQ,iBAAiB,OAAO,iBAAiB,YAAY;iBAE1C,OAAO,gBAAgB,kBAC3C,OAAO,YACP,QAAQ,SACR,UAAU;EAAwB;IACjC,QAAQ,iBAAiB,YAAY;iBAElB,OACpB,OAAO,YACP,UAAU,sBACT,QAAQ;;;;;;;;;;;;;;;;;;;;;;;;cAqCE,KAAK;;;;;;;;;;;;;;;;;;;;;;;;;;;;cAmCL,cACX,iBAAgB,QAAQ;EAExB,QAAQ;EACR,KAAK"}
|
package/dist/fetch.js
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
//#region src/headers.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* Header utility helpers for request normalization and merging.
|
|
4
|
+
*
|
|
5
|
+
* @module @zap-studio/fetch/headers
|
|
6
|
+
*/
|
|
7
|
+
/**
|
|
8
|
+
* Merges two HeadersInit objects, with the second one taking precedence.
|
|
9
|
+
*
|
|
10
|
+
* @param base - Base/default headers.
|
|
11
|
+
* @param override - Request-level override headers.
|
|
12
|
+
* @returns A merged `Headers` object, or `undefined` when both inputs are empty.
|
|
13
|
+
* @throws {TypeError} When either header input contains invalid header names or values.
|
|
14
|
+
*
|
|
15
|
+
* @example
|
|
16
|
+
* const headers = mergeHeaders(
|
|
17
|
+
* { Authorization: "Bearer token" },
|
|
18
|
+
* { "X-Trace-Id": "abc" },
|
|
19
|
+
* );
|
|
20
|
+
*
|
|
21
|
+
* console.log(headers?.get("Authorization")); // Bearer token
|
|
22
|
+
*/
|
|
23
|
+
declare const mergeHeaders: (base?: HeadersInit, override?: HeadersInit) => Headers | undefined;
|
|
24
|
+
//#endregion
|
|
25
|
+
export { mergeHeaders };
|
|
26
|
+
//# sourceMappingURL=headers.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"headers.d.ts","names":[],"sources":["../src/headers.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;cAsBa,eACX,OAAO,aACP,WAAW,gBACV"}
|
|
@@ -20,15 +20,15 @@
|
|
|
20
20
|
*
|
|
21
21
|
* console.log(headers?.get("Authorization")); // Bearer token
|
|
22
22
|
*/
|
|
23
|
-
|
|
24
|
-
if (
|
|
25
|
-
if (
|
|
26
|
-
if (
|
|
23
|
+
const mergeHeaders = (base, override) => {
|
|
24
|
+
if (base === void 0 && override === void 0) return;
|
|
25
|
+
if (base === void 0) return new Headers(override);
|
|
26
|
+
if (override === void 0) return new Headers(base);
|
|
27
27
|
const merged = new Headers(base);
|
|
28
28
|
for (const [key, value] of new Headers(override).entries()) merged.set(key, value);
|
|
29
29
|
return merged;
|
|
30
|
-
}
|
|
30
|
+
};
|
|
31
31
|
//#endregion
|
|
32
32
|
export { mergeHeaders };
|
|
33
33
|
|
|
34
|
-
//# sourceMappingURL=headers.
|
|
34
|
+
//# sourceMappingURL=headers.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"headers.js","names":[],"sources":["../src/headers.ts"],"sourcesContent":["/**\n * Header utility helpers for request normalization and merging.\n *\n * @module @zap-studio/fetch/headers\n */\n\n/**\n * Merges two HeadersInit objects, with the second one taking precedence.\n *\n * @param base - Base/default headers.\n * @param override - Request-level override headers.\n * @returns A merged `Headers` object, or `undefined` when both inputs are empty.\n * @throws {TypeError} When either header input contains invalid header names or values.\n *\n * @example\n * const headers = mergeHeaders(\n * { Authorization: \"Bearer token\" },\n * { \"X-Trace-Id\": \"abc\" },\n * );\n *\n * console.log(headers?.get(\"Authorization\")); // Bearer token\n */\nexport const mergeHeaders = (\n base?: HeadersInit,\n override?: HeadersInit\n): Headers | undefined => {\n if (base === undefined && override === undefined) {\n return undefined;\n }\n\n if (base === undefined) {\n return new Headers(override);\n }\n\n if (override === undefined) {\n return new Headers(base);\n }\n\n const merged = new Headers(base);\n for (const [key, value] of new Headers(override).entries()) {\n merged.set(key, value);\n }\n return merged;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAsBA,MAAa,gBACX,MACA,aACwB;CACxB,IAAI,SAAS,KAAA,KAAa,aAAa,KAAA,GACrC;CAGF,IAAI,SAAS,KAAA,GACX,OAAO,IAAI,QAAQ,QAAQ;CAG7B,IAAI,aAAa,KAAA,GACf,OAAO,IAAI,QAAQ,IAAI;CAGzB,MAAM,SAAS,IAAI,QAAQ,IAAI;CAC/B,KAAK,MAAM,CAAC,KAAK,UAAU,IAAI,QAAQ,QAAQ,CAAC,CAAC,QAAQ,GACvD,OAAO,IAAI,KAAK,KAAK;CAEvB,OAAO;AACT"}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { $Fetch, ApiMethods, ExtendedRequestInit, FetchDefaults, FetchInput } from "./types.js";
|
|
2
|
+
import { GLOBAL_DEFAULTS } from "./constants.js";
|
|
3
|
+
import { FetchError } from "./errors.js";
|
|
4
|
+
import { $fetch, api, createFetch } from "./fetch.js";
|
|
5
|
+
import { mergeHeaders } from "./headers.js";
|
|
6
|
+
import { NormalizedRequest, normalizeRequest } from "./request.js";
|
|
7
|
+
import { resolveRequestUrl } from "./url.js";
|
|
8
|
+
export { type $Fetch, $fetch, type ApiMethods, type ExtendedRequestInit, type FetchDefaults, FetchError, type FetchInput, GLOBAL_DEFAULTS, type NormalizedRequest, api, createFetch, mergeHeaders, normalizeRequest, resolveRequestUrl };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { GLOBAL_DEFAULTS } from "./constants.js";
|
|
2
|
+
import { FetchError } from "./errors.js";
|
|
3
|
+
import { mergeHeaders } from "./headers.js";
|
|
4
|
+
import { normalizeRequest } from "./request.js";
|
|
5
|
+
import { resolveRequestUrl } from "./url.js";
|
|
6
|
+
import { n as api, r as createFetch, t as $fetch } from "./fetch-D0IXjsUD.js";
|
|
7
|
+
export { $fetch, FetchError, GLOBAL_DEFAULTS, api, createFetch, mergeHeaders, normalizeRequest, resolveRequestUrl };
|