@hyper-fetch/core 9.9.0 → 10.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/README.md +126 -86
  2. package/__tests__/features/adapter/adapter.base.spec.ts +32 -0
  3. package/__tests__/features/adapter/adapter.bindings.progress.spec.ts +14 -0
  4. package/__tests__/features/adapter/adapter.bindings.spec.ts +17 -0
  5. package/__tests__/features/adapter/adapter.query-params-resolver.spec.ts +93 -0
  6. package/__tests__/features/adapter/adapter.server.spec.ts +46 -0
  7. package/__tests__/features/cache/cache.timing.spec.ts +34 -12
  8. package/__tests__/features/dispatcher/dispatcher.cancel.spec.ts +72 -0
  9. package/__tests__/features/dispatcher/dispatcher.lazy-storage.spec.ts +237 -0
  10. package/__tests__/features/dispatcher/dispatcher.persistence.spec.ts +187 -0
  11. package/__tests__/features/dispatcher/dispatcher.retry-time.spec.ts +142 -0
  12. package/__tests__/features/http-adapter/http-adapter.e2e.spec.ts +146 -0
  13. package/__tests__/features/managers/app/app.manager.events.spec.ts +46 -1
  14. package/__tests__/features/request/request.inference.spec.ts +78 -0
  15. package/__tests__/features/sdk/sdk.base.spec.ts +39 -0
  16. package/__tests__/features/sdk/sdk.request-fields.spec.ts +23 -0
  17. package/__tests__/features/sdk/sdk.types.spec.ts +28 -1
  18. package/dist/adapter/adapter.bindings.d.ts.map +1 -1
  19. package/dist/adapter/adapter.d.ts +18 -0
  20. package/dist/adapter/adapter.d.ts.map +1 -1
  21. package/dist/cache/cache.d.ts +2 -1
  22. package/dist/cache/cache.d.ts.map +1 -1
  23. package/dist/client/client.d.ts +2 -2
  24. package/dist/client/client.d.ts.map +1 -1
  25. package/dist/dispatcher/dispatcher.d.ts +28 -1
  26. package/dist/dispatcher/dispatcher.d.ts.map +1 -1
  27. package/dist/dispatcher/dispatcher.types.d.ts +17 -0
  28. package/dist/dispatcher/dispatcher.types.d.ts.map +1 -1
  29. package/dist/http-adapter/http-adapter.fetch.d.ts.map +1 -1
  30. package/dist/http-adapter/http-adapter.types.d.ts +12 -0
  31. package/dist/http-adapter/http-adapter.types.d.ts.map +1 -1
  32. package/dist/index.mjs +280 -42
  33. package/dist/index.mjs.map +1 -1
  34. package/dist/managers/app/app.manager.d.ts +5 -0
  35. package/dist/managers/app/app.manager.d.ts.map +1 -1
  36. package/dist/managers/request/request.manager.d.ts +7 -0
  37. package/dist/managers/request/request.manager.d.ts.map +1 -1
  38. package/dist/request/request.d.ts +3 -3
  39. package/dist/request/request.d.ts.map +1 -1
  40. package/dist/request/request.types.d.ts +45 -7
  41. package/dist/request/request.types.d.ts.map +1 -1
  42. package/dist/request/request.utils.d.ts +26 -1
  43. package/dist/request/request.utils.d.ts.map +1 -1
  44. package/dist/sdk/sdk.d.ts +22 -3
  45. package/dist/sdk/sdk.d.ts.map +1 -1
  46. package/package.json +1 -1
  47. package/src/adapter/adapter.bindings.ts +5 -3
  48. package/src/adapter/adapter.ts +24 -1
  49. package/src/cache/cache.ts +5 -2
  50. package/src/client/client.ts +10 -3
  51. package/src/dispatcher/dispatcher.ts +161 -6
  52. package/src/dispatcher/dispatcher.types.ts +18 -0
  53. package/src/http-adapter/http-adapter.fetch.ts +76 -19
  54. package/src/http-adapter/http-adapter.types.ts +13 -0
  55. package/src/managers/app/app.manager.ts +17 -2
  56. package/src/managers/request/request.manager.ts +15 -1
  57. package/src/request/request.ts +5 -4
  58. package/src/request/request.types.ts +71 -11
  59. package/src/request/request.utils.ts +55 -0
  60. package/src/sdk/sdk.ts +33 -3
package/README.md CHANGED
@@ -1,51 +1,42 @@
1
- # ⚡ Hyper Fetch
1
+ <p align="center">
2
+ <a href="https://hyperfetch.bettertyped.com/docs/core/overview"><img src="https://raw.githubusercontent.com/BetterTyped/hyper-fetch/main/.github/assets/packages/core.png" alt="Hyper Fetch Core. From REST to realtime. Fully typed. Typed requests with cache, deduplication, retries, queues and offline replay built in." /></a>
3
+ </p>
2
4
 
3
5
  <p align="center">
4
- <b>One SDK for every API. The type-safe API layer for TypeScript apps — REST, GraphQL, WebSockets, SSE, Firebase, and more.</b>
6
+ <a href="https://hyperfetch.bettertyped.com/docs/getting-started/quick-start"><b>Quick Start</b></a> ·
7
+ <a href="https://hyperfetch.bettertyped.com/docs/core/overview">Documentation</a> ·
8
+ <a href="https://hyperfetch.bettertyped.com/docs/api/core/Classes/Client">API Reference</a> ·
9
+ <a href="https://github.com/BetterTyped/hyper-fetch">GitHub</a> ·
10
+ <a href="https://discord.gg/7upC2kVmyM">Discord</a>
5
11
  </p>
6
12
 
7
13
  <p align="center">
8
- <a href="https://bettertyped.com/">
9
- <img src="https://custom-icon-badges.demolab.com/static/v1?label=&message=BetterTyped&color=333&logo=BT" />
10
- </a>
11
- <a href="https://github.com/BetterTyped/hyper-fetch">
12
- <img src="https://custom-icon-badges.demolab.com/github/stars/BetterTyped/hyper-fetch?logo=star&color=118ab2" />
13
- </a>
14
- <a href="https://github.com/BetterTyped/hyper-fetch/blob/main/License.md">
15
- <img src="https://custom-icon-badges.demolab.com/github/license/BetterTyped/hyper-fetch?logo=law&color=yellow" />
16
- </a>
17
- <a href="https://www.npmjs.com/package/@hyper-fetch/core">
18
- <img src="https://custom-icon-badges.demolab.com/npm/v/@hyper-fetch/core.svg?logo=npm&color=e76f51" />
19
- </a>
20
- <a href="https://www.npmjs.com/package/@hyper-fetch/core">
21
- <img src="https://custom-icon-badges.demolab.com/npm/dm/@hyper-fetch/core?logoColor=fff&logo=trending-up" />
22
- </a>
23
- <a href="https://github.com/BetterTyped/hyper-fetch">
24
- <img src="https://custom-icon-badges.demolab.com/badge/typescript-%23007ACC.svg?logo=typescript&logoColor=white" />
25
- </a>
26
- <a href="https://bundlephobia.com/package/@hyper-fetch/core">
27
- <img src="https://custom-icon-badges.demolab.com/bundlephobia/minzip/@hyper-fetch/core?color=64BC4B&logo=package" />
28
- </a>
14
+ <a href="https://github.com/BetterTyped/hyper-fetch"><img src="https://img.shields.io/github/stars/BetterTyped/hyper-fetch?style=flat&logo=github&color=333" alt="GitHub stars" /></a>
15
+ <a href="https://www.npmjs.com/package/@hyper-fetch/core"><img src="https://img.shields.io/npm/v/@hyper-fetch/core?logo=npm&color=e76f51" alt="npm version" /></a>
16
+ <a href="https://www.npmjs.com/package/@hyper-fetch/core"><img src="https://api.maciejpyrc.com/portfolio/npm/downloads.svg?packages=@hyper-fetch/core&color=fbc646" alt="Monthly downloads" /></a>
17
+ <a href="https://bundlejs.com/?q=@hyper-fetch/core"><img src="https://api.maciejpyrc.com/portfolio/npm/size.svg?package=@hyper-fetch/core" alt="Bundle size" /></a>
18
+ <a href="https://github.com/BetterTyped/hyper-fetch"><img src="https://img.shields.io/badge/TypeScript-strict-3178C6?logo=typescript&logoColor=white" alt="TypeScript" /></a>
19
+ <a href="https://github.com/BetterTyped/hyper-fetch/blob/main/License.md"><img src="https://img.shields.io/github/license/BetterTyped/hyper-fetch?color=blue" alt="License" /></a>
29
20
  </p>
30
21
 
31
22
  ## 📖 About
32
23
 
33
- HyperFetch Core is the foundation of the HyperFetch ecosystem. Every API call is a typed, immutable request object with
34
- built-in caching, queuing, retries, and offline support. It works in any JavaScript environment — browser, server, or
35
- edge — and connects to any API through pluggable adapters.
24
+ `@hyper-fetch/core` is the foundation of Hyper Fetch. Every API call is a typed, immutable request with cache,
25
+ deduplication, queues, retries and offline replay built in. It runs in the browser, Node.js and Bun, and every adapter
26
+ in the ecosystem (GraphQL, tRPC, oRPC, Firebase, Axios) plugs into the same `createRequest()`.
36
27
 
37
28
  ## 🎯 Key Capabilities
38
29
 
39
- - 🔮 **Zero guesswork** — Full autocompletion for every request, response, param, and error. Never cast to `any` again
40
- - 📡 **One interface for everything** — REST, GraphQL, Firebase, WebSockets, SSE — switch APIs without rewriting a line
41
- - 💾 **Stop re-fetching what you already have** — Smart cache with TTL and invalidation out of the box
42
- - 🔁 **Failed requests retry themselves** — Configurable retry count and delay so users never see random failures
43
- - 📴 **Works without internet** — Queues requests offline and replays them when connection returns
44
- - 🚫 **No duplicate requests** — Concurrent identical calls are deduplicated automatically
45
- - ⏱️ **Know exactly what's happening** — Upload and download progress with time estimates for every request
46
- - 🎯 **Cancel anything, anytime** — Kill pending requests individually or by group with one call
47
- - 🔌 **Swap engines without touching your code** — Switch between Axios, GraphQL, Firebase adapters in one line
48
- - 🪄 **Generate your SDK** — Point CLI at an OpenAPI schema and get a fully typed client instantly
30
+ - 🔮 **Zero guesswork** - Params, payload, query params, response and error are typed on every request. No `any`
31
+ - 🧭 **URL params checked at compile time** - `/users/:userId` makes `userId` required. A typo fails the build
32
+ - 💾 **Stop re-fetching what you have** - Cache with stale time, invalidation and persistence through `lazyStorage`
33
+ - 🚫 **No duplicate calls** - Identical requests in flight share one response
34
+ - 🔁 **Failed requests retry themselves** - Attempts and delay per request with `setRetry()` and `setRetryTime()`
35
+ - 📴 **Works offline** - Requests sent offline wait in the queue and replay when the connection returns
36
+ - 🎯 **Cancel anything** - Abort one request or a whole group that shares an abort key
37
+ - ⏱️ **Progress you can show** - Upload and download progress events with time estimates
38
+ - 🧪 **Mocks without a server** - `setMock()` returns your data and status with no network call
39
+ - 🔌 **One API for every backend** - Swap the adapter for GraphQL, tRPC, oRPC, Firebase or Axios and keep your requests
49
40
 
50
41
  ## 🚀 Quick Start
51
42
 
@@ -56,28 +47,36 @@ npm install @hyper-fetch/core
56
47
  ```ts
57
48
  import { createClient } from "@hyper-fetch/core";
58
49
 
59
- // Single entry point — all requests inherit this base URL
50
+ // One client per API. Every request inherits its base URL
60
51
  const client = createClient({ url: "https://api.example.com" });
61
52
 
62
- // Define a request with typed response — :userId becomes a required param
53
+ // :userId becomes a required, typed param
63
54
  const getUser = client.createRequest<{ response: { id: number; name: string } }>()({
64
55
  endpoint: "/users/:userId",
65
56
  method: "GET",
66
57
  });
67
58
 
68
- // setParams is typed from the endpoint string, send() returns typed data
69
- const { data, error } = await getUser.setParams({ userId: 1 }).send();
59
+ // send() never throws. data, error and status are typed
60
+ const { data, error, status } = await getUser.setParams({ userId: 1 }).send();
70
61
  ```
71
62
 
63
+ Have an OpenAPI schema? Generate every request at once with
64
+ [`@hyper-fetch/cli`](https://github.com/BetterTyped/hyper-fetch/tree/main/packages/cli).
65
+
72
66
  ## 📚 Documentation
73
67
 
74
- - [Getting Started](https://hyperfetch.bettertyped.com/docs/getting-started/quick-start)
75
- - [Core Overview](https://hyperfetch.bettertyped.com/docs/core/overview)
76
- - [API Reference](https://hyperfetch.bettertyped.com/api/)
68
+ - **[Quick Start](https://hyperfetch.bettertyped.com/docs/getting-started/quick-start)** - Install and send your first typed request
69
+ - **[Client](https://hyperfetch.bettertyped.com/docs/core/client)** - Base URL, interceptors, auth and global error types
70
+ - **[Request](https://hyperfetch.bettertyped.com/docs/core/request)** - Params, payload, query params, retries and keys
71
+ - **[Cache](https://hyperfetch.bettertyped.com/docs/core/cache)** - Stale time, invalidation and persistent storage
72
+ - **[SDK](https://hyperfetch.bettertyped.com/docs/core/sdk)** - Typed request trees from a schema or a backend type
73
+ - **[Mocking](https://hyperfetch.bettertyped.com/docs/core/mocking)** - Fake responses for tests, stories and demos
74
+ - **[Guides](https://hyperfetch.bettertyped.com/docs/guides/core/basics/setup)** - Auth, error handling, offline, persistence and more
75
+ - **[API Reference](https://hyperfetch.bettertyped.com/docs/api/core/Classes/Client)** - Every class, function and type
77
76
 
78
77
  ## 💡 Examples
79
78
 
80
- ### Typed requests with params, payload, and query params
79
+ ### Params, payload and query params
81
80
 
82
81
  ```ts
83
82
  interface User {
@@ -86,73 +85,114 @@ interface User {
86
85
  email: string;
87
86
  }
88
87
 
89
- // GET request — only response type needed, params inferred from :userId
90
- const getUser = client.createRequest<{ response: User }>()({
91
- endpoint: "/users/:userId",
92
- method: "GET",
93
- });
94
-
95
- // POST request — define both response and payload types
96
88
  const createUser = client.createRequest<{
97
89
  response: User;
98
90
  payload: { name: string; email: string };
99
91
  }>()({
100
- endpoint: "/users",
92
+ endpoint: "/teams/:teamId/users",
101
93
  method: "POST",
102
94
  });
103
95
 
104
- // Params are type-checked: { userId: string | number } required here
105
- const { data } = await getUser.setParams({ userId: 1 }).send();
106
-
107
- // Payload is type-checked: { name, email } required here
108
- const { data: newUser } = await createUser.send({
109
- payload: { name: "Jane", email: "jane@example.com" },
110
- });
111
- ```
112
-
113
- ### Dynamic data with query params
114
-
115
- ```ts
116
- // Define allowed query params — all are optional and type-checked
117
96
  const listUsers = client.createRequest<{
118
97
  response: User[];
119
- queryParams: { page?: number; limit?: number; search?: string };
98
+ queryParams: { page?: number; search?: string };
120
99
  }>()({
121
100
  endpoint: "/users",
122
101
  method: "GET",
123
102
  });
124
103
 
125
- // Query params are appended to the URL: /users?page=1&limit=20&search=john
126
- const { data } = await listUsers.setQueryParams({ page: 1, limit: 20, search: "john" }).send();
104
+ // params go in the URL, the payload in the body. Both are checked
105
+ await createUser.send({ params: { teamId: 1 }, payload: { name: "Jane", email: "jane@example.com" } });
106
+
107
+ // GET /users?page=2&search=jane
108
+ await listUsers.send({ queryParams: { page: 2, search: "jane" } });
127
109
  ```
128
110
 
129
- ### Lifecycle callbacks
111
+ ### Auth for every request
130
112
 
131
113
  ```ts
132
- // Hook into the request lifecycle — track progress, log events, handle responses
133
- const { data } = await getUser.setParams({ userId: 1 }).send({
134
- onRequestStart: ({ requestId }) => console.log(`Request ${requestId} started`),
135
- onResponse: ({ response }) => console.log("Got data:", response.data),
136
- onUploadProgress: ({ progress }) => console.log(`Upload: ${progress}%`),
137
- onDownloadProgress: ({ progress }) => console.log(`Download: ${progress}%`),
114
+ const client = createClient<{ error: ApiError | Error }>({ url: "https://api.example.com" }).onAuth((request) => {
115
+ const token = tokenStore.get();
116
+ return token ? request.setHeaders({ ...request.headers, Authorization: `Bearer ${token}` }) : request;
138
117
  });
139
118
  ```
140
119
 
141
- ### Response mapping
120
+ `onAuth` runs before every request that has `auth` enabled, which is the default. Mark public endpoints with
121
+ `auth: false`.
122
+
123
+ ### Retries and caching per request
124
+
125
+ ```ts
126
+ const getDashboard = client
127
+ .createRequest<{ response: Dashboard }>()({ endpoint: "/dashboard" })
128
+ .setRetry(3) // try 3 more times when it fails
129
+ .setRetryTime(1000) // wait 1s between attempts
130
+ .setStaleTime(30_000) // cached data counts as fresh for 30s
131
+ .setDeduplicate(true); // concurrent calls share one response
132
+ ```
133
+
134
+ ### Errors come back in the response
135
+
136
+ ```ts
137
+ const { data, error, status, success } = await getUser.setParams({ userId: 1 }).send();
138
+
139
+ if (!success) {
140
+ // error is typed from the client and request error generics
141
+ reportError(status, error);
142
+ }
143
+ ```
144
+
145
+ ### Mock a request
142
146
 
143
147
  ```ts
144
- // Transform the response before it reaches your code
145
- const getUser = client
146
- .createRequest<{ response: User }>()({
147
- endpoint: "/users/:userId",
148
- method: "GET",
149
- })
150
- .setResponseMapper((response) => ({
151
- ...response,
152
- data: response.data ? { ...response.data, name: response.data.name.toUpperCase() } : null,
153
- }));
148
+ const mocked = getUser.setMock(() => ({ data: { id: 1, name: "Jane" }, status: 200 }));
149
+
150
+ // resolves with the mock, no network call
151
+ const { data } = await mocked.setParams({ userId: 1 }).send();
154
152
  ```
155
153
 
154
+ ### Progress and lifecycle callbacks
155
+
156
+ ```ts
157
+ await uploadAvatar.send({
158
+ payload: formData,
159
+ onRequestStart: ({ requestId }) => console.log(`Request ${requestId} started`),
160
+ onUploadProgress: ({ progress, timeLeft }) => setUpload({ progress, timeLeft }),
161
+ onResponse: ({ response }) => console.log("Done with", response.status),
162
+ });
163
+ ```
164
+
165
+ ## 🧩 Hyper Fetch Ecosystem
166
+
167
+ One typed client for every backend. Swap the adapter and keep the same `createRequest()` everywhere.
168
+
169
+ <table align="center">
170
+ <tr>
171
+ <td align="center" width="110"><a href="https://github.com/BetterTyped/hyper-fetch/tree/main/packages/core"><img src="https://raw.githubusercontent.com/BetterTyped/hyper-fetch/main/documentation/static/img/integration-hyper-fetch.svg" width="36" height="36" alt="" /><br /><sub><b>Core</b></sub></a></td>
172
+ <td align="center" width="110"><a href="https://github.com/BetterTyped/hyper-fetch/tree/main/packages/react"><img src="https://raw.githubusercontent.com/BetterTyped/hyper-fetch/main/documentation/static/img/integration-react.svg" width="36" height="36" alt="" /><br /><sub><b>React</b></sub></a></td>
173
+ <td align="center" width="110"><a href="https://github.com/BetterTyped/hyper-fetch/tree/main/packages/sockets"><img src="https://raw.githubusercontent.com/BetterTyped/hyper-fetch/main/documentation/static/img/integration-sockets.svg" width="36" height="36" alt="" /><br /><sub><b>Sockets</b></sub></a></td>
174
+ <td align="center" width="110"><a href="https://github.com/BetterTyped/hyper-fetch/tree/main/packages/cli"><img src="https://raw.githubusercontent.com/BetterTyped/hyper-fetch/main/documentation/static/img/integration-openapi.svg" width="36" height="36" alt="" /><br /><sub><b>OpenAPI CLI</b></sub></a></td>
175
+ <td align="center" width="110"><a href="https://github.com/BetterTyped/hyper-fetch/tree/main/packages/adapter-graphql"><img src="https://raw.githubusercontent.com/BetterTyped/hyper-fetch/main/documentation/static/img/integration-graphql.svg" width="36" height="36" alt="" /><br /><sub><b>GraphQL</b></sub></a></td>
176
+ <td align="center" width="110"><a href="https://github.com/BetterTyped/hyper-fetch/tree/main/packages/adapter-trpc"><img src="https://raw.githubusercontent.com/BetterTyped/hyper-fetch/main/documentation/static/img/integration-trpc.svg" width="36" height="36" alt="" /><br /><sub><b>tRPC</b></sub></a></td>
177
+ </tr>
178
+ <tr>
179
+ <td align="center" width="110"><a href="https://github.com/BetterTyped/hyper-fetch/tree/main/packages/adapter-orpc"><picture><source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/BetterTyped/hyper-fetch/main/documentation/static/img/integration-orpc-dark.svg" /><img src="https://raw.githubusercontent.com/BetterTyped/hyper-fetch/main/documentation/static/img/integration-orpc.svg" width="36" height="36" alt="" /></picture><br /><sub><b>oRPC</b></sub></a></td>
180
+ <td align="center" width="110"><a href="https://github.com/BetterTyped/hyper-fetch/tree/main/packages/hono"><img src="https://raw.githubusercontent.com/BetterTyped/hyper-fetch/main/documentation/static/img/integration-hono.svg" width="36" height="36" alt="" /><br /><sub><b>Hono</b></sub></a></td>
181
+ <td align="center" width="110"><a href="https://github.com/BetterTyped/hyper-fetch/tree/main/packages/elysia"><img src="https://raw.githubusercontent.com/BetterTyped/hyper-fetch/main/documentation/static/img/integration-elysia.svg" width="36" height="36" alt="" /><br /><sub><b>Elysia</b></sub></a></td>
182
+ <td align="center" width="110"><a href="https://github.com/BetterTyped/hyper-fetch/tree/main/packages/adapter-firebase"><img src="https://raw.githubusercontent.com/BetterTyped/hyper-fetch/main/documentation/static/img/integration-firebase.svg" width="36" height="36" alt="" /><br /><sub><b>Firebase</b></sub></a></td>
183
+ <td align="center" width="110"><a href="https://github.com/BetterTyped/hyper-fetch/tree/main/packages/adapter-axios"><img src="https://raw.githubusercontent.com/BetterTyped/hyper-fetch/main/documentation/static/img/integration-axios.svg" width="36" height="36" alt="" /><br /><sub><b>Axios</b></sub></a></td>
184
+ <td align="center" width="110"><a href="https://github.com/BetterTyped/hyper-fetch/tree/main/packages/hyper-flow"><img src="https://raw.githubusercontent.com/BetterTyped/hyper-fetch/main/documentation/static/img/hyper-flow.svg" width="36" height="36" alt="" /><br /><sub><b>HyperFlow</b></sub></a></td>
185
+ </tr>
186
+ </table>
187
+
188
+ ## 💖 Sponsors
189
+
190
+ <p align="center">
191
+ <a href="https://github.com/sponsors/prc5">
192
+ <img src="https://raw.githubusercontent.com/prc5/sponsors/main/packages/other/sponsorkit/sponsors.svg?raw=true" alt="Sponsors" />
193
+ </a>
194
+ </p>
195
+
156
196
  ## License
157
197
 
158
198
  [Apache-2.0](https://github.com/BetterTyped/hyper-fetch/blob/main/License.md)
@@ -388,6 +388,38 @@ describe("Adapter [ Base ]", () => {
388
388
  );
389
389
  });
390
390
 
391
+ it("should resolve with the error when an async fetcher rejects", async () => {
392
+ const testError = new Error("Test error");
393
+
394
+ const client = new Client({ url: "test" });
395
+ const newAdapter = new Adapter({
396
+ name: "test-adapter",
397
+ defaultMethod: HttpMethods.GET,
398
+ defaultExtra: {},
399
+ systemErrorStatus: 500,
400
+ systemErrorExtra: { systemError: true },
401
+ }).setFetcher(async () => {
402
+ throw testError;
403
+ });
404
+
405
+ const request = client.createRequest()({
406
+ endpoint: "test",
407
+ });
408
+ client.setAdapter(newAdapter);
409
+
410
+ const response = await request.send();
411
+
412
+ expect(response).toEqual(
413
+ expect.objectContaining({
414
+ data: null,
415
+ error: testError,
416
+ status: 500,
417
+ success: false,
418
+ extra: { systemError: true },
419
+ }),
420
+ );
421
+ });
422
+
391
423
  it("should use current timestamp if startTime is not set during error", async () => {
392
424
  const fetcherSpy = vi.fn().mockImplementation(() => {
393
425
  throw new Error("Test error");
@@ -71,6 +71,20 @@ describe("Adapter [ Bindings progress ]", () => {
71
71
  expect(downloads).toHaveLength(size === 1 ? 2 : 3);
72
72
  });
73
73
 
74
+ it("should never report more than 100% when the body is bigger than its announced size", async () => {
75
+ const { onResponseStart, onResponseProgress, onResponseEnd, downloads } = await setup();
76
+
77
+ // A compressed body: the size from the headers is smaller than the decompressed bytes counted by the adapter
78
+ onResponseStart({ total: 100, loaded: 0 });
79
+ onResponseProgress({ total: 100, loaded: 80 });
80
+ onResponseProgress({ total: 100, loaded: 400 });
81
+ onResponseProgress({ total: 100, loaded: 1000 });
82
+ onResponseEnd();
83
+
84
+ expect(downloads.every(({ progress }) => progress <= 100)).toBeTrue();
85
+ expect(downloads.at(-1)).toEqual({ loaded: 1000, total: 1000, progress: 100 });
86
+ });
87
+
74
88
  it("should not report the same progress twice in a row", async () => {
75
89
  const { onResponseStart, onResponseProgress, onResponseEnd, downloads } = await setup();
76
90
 
@@ -970,6 +970,23 @@ describe("Adapter [ Bindings ]", () => {
970
970
  responseTimestamp: expect.toBeNumber(),
971
971
  } satisfies ResponseErrorType<any, HttpAdapterType>);
972
972
  });
973
+ it.each([
974
+ ["onAbortError", getErrorMessage("abort")],
975
+ ["onTimeoutError", getErrorMessage("timeout")],
976
+ ["onUnexpectedError", getErrorMessage()],
977
+ ] as const)("should pass the error of %s through the internal error mapping", async (method, error) => {
978
+ const bindings = await getAdapterBindings({
979
+ request,
980
+ requestId,
981
+ resolve: () => null,
982
+ onStartTime: () => null,
983
+ internalErrorMapping: (internalError) => ({ mapped: internalError }),
984
+ });
985
+
986
+ const response = await bindings[method]({ status: 0, extra: xhrExtra });
987
+
988
+ expect(response.error).toEqual({ mapped: error });
989
+ });
973
990
  });
974
991
  });
975
992
 
@@ -0,0 +1,93 @@
1
+ import { Adapter } from "adapter";
2
+ import { Client } from "client";
3
+
4
+ type Filter = { field: string; value: string };
5
+
6
+ class FiltersBuilder {
7
+ constructor(readonly filters: Filter[] = []) {}
8
+
9
+ where = (field: string, value: string) => new FiltersBuilder([...this.filters, { field, value }]);
10
+
11
+ toJSON = () => this.filters;
12
+ }
13
+
14
+ type FiltersQueryParams = Filter[] | ((builder: FiltersBuilder) => FiltersBuilder);
15
+
16
+ const createAdapter = (onFetch: (queryParams: unknown) => void) =>
17
+ new Adapter<Record<string, never>, string, number, Record<string, never>, FiltersQueryParams, FiltersQueryParams>({
18
+ name: "filters-adapter",
19
+ defaultMethod: "GET",
20
+ defaultExtra: {},
21
+ systemErrorStatus: 500,
22
+ systemErrorExtra: {},
23
+ }).setFetcher(({ request, onSuccess }) => {
24
+ onFetch(request.queryParams);
25
+ onSuccess({ data: null, status: 200, extra: {} });
26
+ });
27
+
28
+ describe("Adapter [ Query params resolver ]", () => {
29
+ let fetched: unknown[] = [];
30
+ let client = new Client({ url: "shared-base-url" }).setAdapter(createAdapter((queryParams) => fetched.push(queryParams)));
31
+
32
+ beforeEach(() => {
33
+ fetched = [];
34
+ client = new Client({ url: "shared-base-url" }).setAdapter(
35
+ createAdapter((queryParams) => fetched.push(queryParams)).setQueryParamsResolver((callback) =>
36
+ (callback(new FiltersBuilder()) as FiltersBuilder).toJSON(),
37
+ ),
38
+ );
39
+ });
40
+
41
+ const getUsers = () => client.createRequest<{ response: null; queryParams: FiltersQueryParams }>()({ endpoint: "/users" });
42
+
43
+ it("should store the data a callback resolves to when it is set", () => {
44
+ const request = getUsers().setQueryParams((filters) => filters.where("role", "admin"));
45
+
46
+ expect(request.queryParams).toStrictEqual([{ field: "role", value: "admin" }]);
47
+ });
48
+
49
+ it("should derive cache and query keys from the resolved data", () => {
50
+ const fromCallback = getUsers().setQueryParams((filters) => filters.where("role", "admin"));
51
+ const fromData = getUsers().setQueryParams([{ field: "role", value: "admin" }]);
52
+ const other = getUsers().setQueryParams((filters) => filters.where("role", "guest"));
53
+
54
+ expect(fromCallback.cacheKey).toBe(fromData.cacheKey);
55
+ expect(fromCallback.queryKey).toBe(fromData.queryKey);
56
+ expect(fromCallback.cacheKey).not.toBe(other.cacheKey);
57
+ });
58
+
59
+ it("should keep the resolved data in toJSON and clones", () => {
60
+ const request = getUsers().setQueryParams((filters) => filters.where("role", "admin"));
61
+
62
+ expect(request.toJSON().queryParams).toStrictEqual([{ field: "role", value: "admin" }]);
63
+ expect(request.clone().queryParams).toStrictEqual([{ field: "role", value: "admin" }]);
64
+ });
65
+
66
+ it("should resolve a callback given to send", async () => {
67
+ await getUsers().send({ queryParams: (filters) => filters.where("role", "admin").where("active", "yes") });
68
+
69
+ expect(fetched).toStrictEqual([
70
+ [
71
+ { field: "role", value: "admin" },
72
+ { field: "active", value: "yes" },
73
+ ],
74
+ ]);
75
+ });
76
+
77
+ it("should store query params as given when the adapter has no resolver", () => {
78
+ const callback = (filters: FiltersBuilder) => filters.where("role", "admin");
79
+ const plainClient = new Client({ url: "shared-base-url" }).setAdapter(createAdapter(() => null));
80
+ const request = plainClient
81
+ .createRequest<{ response: null; queryParams: FiltersQueryParams }>()({ endpoint: "/users" })
82
+ .setQueryParams(callback);
83
+
84
+ expect(request.queryParams).toBe(callback);
85
+ });
86
+
87
+ it("should leave data query params untouched", () => {
88
+ const data = [{ field: "role", value: "admin" }];
89
+ const request = getUsers().setQueryParams(data);
90
+
91
+ expect(request.queryParams).toBe(data);
92
+ });
93
+ });
@@ -200,6 +200,52 @@ describe("Http Adapter [ Fetch ]", () => {
200
200
  });
201
201
  });
202
202
 
203
+ describe("When response.body has no getReader and a binary response type is set", () => {
204
+ const createBinaryResponse = (ok: boolean) => {
205
+ const blob = new Blob(["binary"], { type: "application/octet-stream" });
206
+ return {
207
+ ok,
208
+ status: ok ? 200 : 404,
209
+ headers: new Headers({ "content-type": "application/octet-stream" }),
210
+ body: null,
211
+ blob: vi.fn().mockResolvedValue(blob),
212
+ arrayBuffer: vi.fn().mockResolvedValue(new TextEncoder().encode("binary").buffer),
213
+ text: vi.fn().mockResolvedValue(JSON.stringify({ message: "Not found" })),
214
+ };
215
+ };
216
+
217
+ it.each(["blob", "arrayBuffer"] as const)("should read the body with the %s method", async (responseType) => {
218
+ const originalFetch = globalThis.fetch;
219
+ const response = createBinaryResponse(true);
220
+ globalThis.fetch = vi.fn().mockResolvedValue(response);
221
+
222
+ try {
223
+ const adapter = HttpAdapter().initialize(client);
224
+ const result = await adapter.fetch(request.setOptions({ responseType }), requestId);
225
+
226
+ expect(result.data).toBe(await response[responseType].mock.results[0].value);
227
+ expect(response.text).not.toHaveBeenCalled();
228
+ } finally {
229
+ globalThis.fetch = originalFetch;
230
+ }
231
+ });
232
+
233
+ it("should parse the error body as text", async () => {
234
+ const originalFetch = globalThis.fetch;
235
+ globalThis.fetch = vi.fn().mockResolvedValue(createBinaryResponse(false));
236
+
237
+ try {
238
+ const adapter = HttpAdapter().initialize(client);
239
+ const result = await adapter.fetch(request.setOptions({ responseType: "blob" }), requestId);
240
+
241
+ expect(result.data).toBeNull();
242
+ expect(result.error).toStrictEqual({ message: "Not found" });
243
+ } finally {
244
+ globalThis.fetch = originalFetch;
245
+ }
246
+ });
247
+ });
248
+
203
249
  describe("When non-timeout, non-abort error occurs", () => {
204
250
  it("should call onError with the error", async () => {
205
251
  const originalFetch = globalThis.fetch;
@@ -24,6 +24,40 @@ describe("Cache [ Timing ]", () => {
24
24
  vi.useRealTimers();
25
25
  });
26
26
 
27
+ describe("When the cached data gets updated locally", () => {
28
+ it("should count the cache time from the update", () => {
29
+ client.cache.set(request, createCacheResponse({ id: 1 }));
30
+ vi.advanceTimersByTime(800);
31
+
32
+ client.cache.update(request, { data: { id: 2 } });
33
+ vi.advanceTimersByTime(cacheTime - 1);
34
+
35
+ expect(client.cache.get(request.cacheKey)?.data).toStrictEqual({ id: 2 });
36
+
37
+ vi.advanceTimersByTime(1);
38
+ expect(client.cache.get(request.cacheKey)).toBeUndefined();
39
+ });
40
+
41
+ it("should set the response timestamp to the time of the update", () => {
42
+ client.cache.set(request, createCacheResponse({ id: 1 }));
43
+ vi.advanceTimersByTime(800);
44
+
45
+ client.cache.update(request, (previous) => ({ data: { id: (previous?.data.id ?? 0) + 1 } }));
46
+
47
+ expect(client.cache.get(request.cacheKey)?.responseTimestamp).toBe(Date.now());
48
+ expect(client.cache.get(request.cacheKey)?.data).toStrictEqual({ id: 2 });
49
+ });
50
+
51
+ it("should refresh the response timestamp when the callback spreads the previous value", () => {
52
+ client.cache.set(request, createCacheResponse({ id: 1 }));
53
+ vi.advanceTimersByTime(800);
54
+
55
+ client.cache.update(request, (previous) => ({ ...previous, data: { id: 2 } }));
56
+
57
+ expect(client.cache.get(request.cacheKey)?.responseTimestamp).toBe(Date.now());
58
+ });
59
+ });
60
+
27
61
  describe("When cache time passes", () => {
28
62
  it("should keep the element just before the cache time passes", () => {
29
63
  client.cache.set(request, createCacheResponse({ id: 1 }));
@@ -186,18 +220,6 @@ describe("Cache [ Timing ]", () => {
186
220
  expect(client.cache.get(request.cacheKey)).toBeUndefined();
187
221
  });
188
222
 
189
- it("should not extend the cache time with the update which keeps the response timestamp", () => {
190
- client.cache.set(request, createCacheResponse({ id: 1 }));
191
- vi.advanceTimersByTime(600);
192
- client.cache.update(request, { data: { id: 2 } });
193
-
194
- vi.advanceTimersByTime(399);
195
- expect(client.cache.get(request.cacheKey)?.data).toStrictEqual({ id: 2 });
196
-
197
- vi.advanceTimersByTime(1);
198
- expect(client.cache.get(request.cacheKey)).toBeUndefined();
199
- });
200
-
201
223
  it("should not extend the cache time with the invalidation", () => {
202
224
  client.cache.set(request, createCacheResponse({ id: 1 }));
203
225
  vi.advanceTimersByTime(600);