fetch-layers 0.0.0-stage → 1.0.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.
- package/CHANGELOG.md +12 -0
- package/LICENSE +21 -0
- package/README.md +262 -2
- package/README.ru.md +263 -0
- package/dist/classify-body-DOG6Vbf_.mjs +1 -0
- package/dist/errors-CSZuncD0.d.mts +119 -0
- package/dist/index.d.mts +74 -0
- package/dist/index.mjs +1 -0
- package/dist/layer-C9nwqcxP.d.mts +69 -0
- package/dist/layer-D1S2Wlu1.d.mts +238 -0
- package/dist/layer-DRRyGTne.d.mts +99 -0
- package/dist/layer-Db25lSAX.d.mts +132 -0
- package/dist/layer-Dhb1y_u6.mjs +1 -0
- package/dist/layers/auth/index.d.mts +12 -0
- package/dist/layers/auth/index.mjs +1 -0
- package/dist/layers/idempotency/index.d.mts +55 -0
- package/dist/layers/idempotency/index.mjs +1 -0
- package/dist/layers/index.d.mts +38 -0
- package/dist/layers/index.mjs +1 -0
- package/dist/layers/retry/index.d.mts +2 -0
- package/dist/layers/retry/index.mjs +1 -0
- package/dist/reset-registry-CQPiZVBB.mjs +1 -0
- package/dist/session-Dm-H-5hJ.mjs +1 -0
- package/dist/shared/storage.d.mts +2 -0
- package/dist/shared/storage.mjs +1 -0
- package/dist/signals-DQjF6ojU.mjs +1 -0
- package/dist/storage-C0XsVkz-.d.mts +44 -0
- package/package.json +100 -4
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 1.0.0
|
|
4
|
+
|
|
5
|
+
- Layer pipeline: idempotency -> retry -> auth.
|
|
6
|
+
- `withAuth`: single-flight refresh, circuit breaker, cooldown, `resetRefreshCircuit`.
|
|
7
|
+
- `withIdempotency`: one key per operation, `IdempotencySource`, sources for `sessionStorage`, `localStorage`, memory.
|
|
8
|
+
- `withRetry`: exponential backoff with jitter, `Retry-After` support.
|
|
9
|
+
- `ApiError` with structural fields, content fields from the response body, and getters.
|
|
10
|
+
- Error body: flat parser as default, `ErrorBodyParser` as extension point for custom formats.
|
|
11
|
+
- Transport: JSON, `FormData`, `Blob`, `File`, `ArrayBuffer`, `TypedArray`, `URLSearchParams`, `ReadableStream`, Node.js `Readable`.
|
|
12
|
+
- Cross-realm type detection, recursive rejection of non-serializable bodies.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 smlnkv
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,263 @@
|
|
|
1
|
-
#
|
|
1
|
+
# fetch-layers
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
**English** | [Русский](./README.ru.md)
|
|
4
|
+
|
|
5
|
+
An HTTP client built from layers. Each layer handles a single concern: auth, retries, idempotency. Layers are added as needed, and the order is validated at client creation.
|
|
6
|
+
|
|
7
|
+
Three built-in layers:
|
|
8
|
+
|
|
9
|
+
- `withAuth` - token refresh on 401, one refresh for all concurrent requests
|
|
10
|
+
- `withRetry` - retries 5xx and network errors, honors `Retry-After`
|
|
11
|
+
- `withIdempotency` - one `Idempotency-Key` per operation, including retries
|
|
12
|
+
|
|
13
|
+
Errors from layers and transport come back as `ApiError`. Zero dependencies, tree-shaking.
|
|
14
|
+
|
|
15
|
+
## Contents
|
|
16
|
+
|
|
17
|
+
- [Who it's for](#who-its-for)
|
|
18
|
+
- [Problems it solves](#problems-it-solves)
|
|
19
|
+
- [Features](#features)
|
|
20
|
+
- [Install and first request](#install-and-first-request)
|
|
21
|
+
- [Requirements](#requirements)
|
|
22
|
+
- [Modules](#modules)
|
|
23
|
+
- [How layers work](#how-layers-work)
|
|
24
|
+
- [Working with TanStack Query](#working-with-tanstack-query)
|
|
25
|
+
|
|
26
|
+
## Who it's for
|
|
27
|
+
|
|
28
|
+
- **SPA with auth.** Several requests go out at once, all get 401. `withAuth` runs a single refresh for all of them and resends each request with the new token.
|
|
29
|
+
|
|
30
|
+
- **API with mutations.** Orders, payments, bookings. You need to retry 5xx and timeouts, but a retried POST /orders creates a second order. `withIdempotency` generates a key once and keeps it until the server confirms.
|
|
31
|
+
|
|
32
|
+
- **Several APIs in one app.** Public and private, different tokens, different error shapes. Each API gets its own client with its own layers and its own `SessionProvider`.
|
|
33
|
+
|
|
34
|
+
## Problems it solves
|
|
35
|
+
|
|
36
|
+
### Session expired, requests fail with 401
|
|
37
|
+
|
|
38
|
+
Five requests go out at once, all get 401. Without coordination each request starts its own refresh - five refresh calls instead of one. The token is written to storage five times in a race: the last one wins, but some requests keep the old token and get 401 again.
|
|
39
|
+
|
|
40
|
+
`withAuth` collects every waiting request into a single refresh. While it runs, the rest wait. Once the token is fresh, each request is sent again with the new header. One refresh instead of five.
|
|
41
|
+
|
|
42
|
+
### Retries and duplicates
|
|
43
|
+
|
|
44
|
+
Network errors and 5xx: server may be down, connection may drop. A retry often succeeds on the second or third attempt.
|
|
45
|
+
|
|
46
|
+
A retry creates duplicates when the operation is not idempotent. POST /orders on retry creates two orders: the first one may have reached the server, the response was lost, the retry created another.
|
|
47
|
+
|
|
48
|
+
The fix is `Idempotency-Key`. The server matches it against previous requests and returns the result of the first one. The catch: the key must stay the same across the whole logical operation, including all retries and any refresh in between.
|
|
49
|
+
|
|
50
|
+
`withIdempotency` generates the key once, before the first attempt, and keeps it until the server confirms. Even if the request failed on the network and replays five minutes later from somewhere else - same key.
|
|
51
|
+
|
|
52
|
+
### Different error shapes
|
|
53
|
+
|
|
54
|
+
Every backend has its own error format. One returns `{ code, message }`, another `{ error: { code } }`, a third RFC 7807. Without a common mechanism, the parsing has to be repeated everywhere an error is handled.
|
|
55
|
+
|
|
56
|
+
The library splits error fields into two layers. The structural layer is the same for every backend: `kind`, `status`, `isRetryable`, `isCancelled`, `isUncertain`, `requestId` (from the `X-Request-Id` header), `retryAfterMs`. The content layer comes from the response body: `code`, `message`, `fields`, `details`. By default the client understands the flat shape `{ code, message, fields }` and plain text. For other formats (Fastify, RFC 7807, DRF, Laravel, `{ error: { code } }`) the app passes its own parsing function via `parseErrorBody`.
|
|
57
|
+
|
|
58
|
+
The full response body is always available in `err.rawBody`, even when the format isn't recognized.
|
|
59
|
+
|
|
60
|
+
### Token refresh temporarily unavailable
|
|
61
|
+
|
|
62
|
+
Token refresh may fail: network is down, refresh endpoint returns 5xx. Without protection every new 401 starts another refresh attempt, and this adds load on the server.
|
|
63
|
+
|
|
64
|
+
`withAuth` blocks refresh for a while after a failure. While the block is active, 401s are returned to the app without an attempt to refresh. `onCircuitOpen` and `onCircuitClose` report when the breaker opens or closes.
|
|
65
|
+
|
|
66
|
+
## Features
|
|
67
|
+
|
|
68
|
+
- **Auth.** `withAuth` works with any `SessionProvider`. To wire the layer up, implement three methods: `getAuthHeaders`, `refresh`, `clear`. Three refresh states (`success`, `definitely-failed`, `temporarily-failed`) give the app control: log the user out or retry later. Circuit breaker settings: `circuitBreakerMs` and `refreshTimeoutMs`. The breaker opens only on network errors, timeouts and 5xx, not on errors in `refresh`. The `resetRefreshCircuit(client)` function resets it manually when the app knows the problem is gone.
|
|
69
|
+
|
|
70
|
+
- **Idempotency.** `withIdempotency` adds an `Idempotency-Key` header to every mutating method (POST, PUT, PATCH, DELETE). For endpoints that do not accept the header, pass `skipIdempotency: true` on the request. The key can live in `localStorage`, `sessionStorage` or memory - depending on whether you need it to survive a reload. For custom storage there is the `IdempotencySource` interface (two methods) and the `stableSerialize` helper for the body hash. `maxEntries` limits the store size, eviction by last use time.
|
|
71
|
+
|
|
72
|
+
- **Retries.** `withRetry` is configurable: `maxAttempts`, `baseDelayMs`, `maxDelayMs`, `jitterRatio`, `retryOnNetwork`, `retryOnTimeout`. Custom policies via `shouldRetry`, `computeDelay`, `onBeforeRetry`. `Retry-After` from the server takes priority over the computed delay.
|
|
73
|
+
|
|
74
|
+
- **Errors.** `ApiError` with getters `isRetryable`, `isCancelled`, `isAuthError`, `isUncertain` and others. `err.fields` is a ready-to-use `Record<string, string>` for forms, when the server returns the flat shape. `err.rawBody` - the original response body for everything else. Custom parsing via `parseErrorBody`.
|
|
75
|
+
|
|
76
|
+
- **Transport.** Validates `baseUrl`, `timeoutMs`, `fetch` and layer order at client creation. Headers accept `Record`, `Headers` or an array of pairs. `defaultHeaders` for common headers. `timeoutMs` and `signal` in a specific request. `requestWithMeta` returns HTTP metadata together with data - for cases when a response header affects the next step: `Retry-After` in `202 Accepted`, `Location` in `201`, `X-Request-Id` for logs. `fetchOptions` for other `fetch` params.
|
|
77
|
+
|
|
78
|
+
For async operations the server may answer `202 Accepted` with a `Retry-After` header. The pause value in milliseconds is available in `meta.retryAfterMs` - exactly as the server sent it. The library does not cap the value: the app decides how long to wait.
|
|
79
|
+
|
|
80
|
+
```ts
|
|
81
|
+
const { meta } = await client.requestWithMeta({
|
|
82
|
+
path: '/api/jobs',
|
|
83
|
+
method: 'POST',
|
|
84
|
+
body: { action: 'start' },
|
|
85
|
+
});
|
|
86
|
+
await new Promise((resolve) => setTimeout(resolve, meta.retryAfterMs ?? 1000));
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
- **Request bodies.** JSON, `FormData`, `Blob`, `File`, `ArrayBuffer`, `TypedArray`, `DataView`, `URLSearchParams`, `ReadableStream`, Node.js `stream.Readable`. Works with types from iframes and Workers. Recursive check: nested non-serializable values are rejected before the request is sent with `BODY_SERIALIZATION_ERROR`.
|
|
90
|
+
|
|
91
|
+
- **Layers.** A custom layer is an object with four fields: `name`, `stage`, `wrap`, `attach`. `LayerContext` exposes `warn`. Priorities `2.5` and `1.5` for inserting between built-in layers.
|
|
92
|
+
|
|
93
|
+
## Install and first request
|
|
94
|
+
|
|
95
|
+
```
|
|
96
|
+
npm install fetch-layers
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
```ts
|
|
100
|
+
import { createClient } from 'fetch-layers';
|
|
101
|
+
|
|
102
|
+
const client = createClient({ baseUrl: '/api' });
|
|
103
|
+
|
|
104
|
+
const products = await client.get<Product[]>('/products');
|
|
105
|
+
|
|
106
|
+
const review = await client.post('/reviews', {
|
|
107
|
+
productId: products[0].id,
|
|
108
|
+
rating: 5,
|
|
109
|
+
comment: 'Great product',
|
|
110
|
+
});
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
Both methods return the parsed response body. `post` sends an object as JSON. Any error comes back as `ApiError` - catch it with `try/catch` or `.catch()`.
|
|
114
|
+
|
|
115
|
+
### Wiring up layers
|
|
116
|
+
|
|
117
|
+
The `layers` option takes an array of layers, ordered from outermost to innermost:
|
|
118
|
+
|
|
119
|
+
```ts
|
|
120
|
+
import { createClient } from 'fetch-layers';
|
|
121
|
+
import {
|
|
122
|
+
withAuth,
|
|
123
|
+
withRetry,
|
|
124
|
+
withIdempotency,
|
|
125
|
+
sessionStorageSource,
|
|
126
|
+
} from 'fetch-layers/layers';
|
|
127
|
+
|
|
128
|
+
const client = createClient({
|
|
129
|
+
baseUrl: '/api',
|
|
130
|
+
layers: [
|
|
131
|
+
withIdempotency(sessionStorageSource()),
|
|
132
|
+
withRetry({ maxAttempts: 3 }),
|
|
133
|
+
withAuth({ provider: sessionProvider }),
|
|
134
|
+
],
|
|
135
|
+
});
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
What the layers do, in this order:
|
|
139
|
+
|
|
140
|
+
- `withIdempotency` wraps everything else. The key is generated once per operation and stays put across retries.
|
|
141
|
+
- `withRetry` retries on 5xx, network errors and timeouts, without changing the key.
|
|
142
|
+
- `withAuth` adds auth headers and refreshes the token on 401.
|
|
143
|
+
|
|
144
|
+
The order is not arbitrary - the library validates it at client creation. Swap `withIdempotency` and `withRetry` and the key gets regenerated on every retry - that breaks deduplication. `createClient` throws with the name of the layer that breaks the rule.
|
|
145
|
+
|
|
146
|
+
If you don't need layers, `createClient({ baseUrl: '/api' })` gives you a plain HTTP client without auth, retries or idempotency.
|
|
147
|
+
|
|
148
|
+
## Requirements
|
|
149
|
+
|
|
150
|
+
Runs on Node.js 20.6+, modern browsers, Deno and Bun.
|
|
151
|
+
|
|
152
|
+
Needs a global `fetch`. If it's missing, `createClient` throws.
|
|
153
|
+
|
|
154
|
+
ESM only. CommonJS is not supported.
|
|
155
|
+
|
|
156
|
+
`crypto.randomUUID` is only needed when `withIdempotency` is in use with the built-in key generator. It is checked on the first mutating request.
|
|
157
|
+
|
|
158
|
+
## Modules
|
|
159
|
+
|
|
160
|
+
The library is split into modules. Bundle size depends on what you import.
|
|
161
|
+
|
|
162
|
+
| Module | What it exports |
|
|
163
|
+
| ------------------------- | --------------------------------------------------------------------------------------------------------- |
|
|
164
|
+
| `fetch-layers` | `createClient`, `ApiError`, `toApiError`, `ErrorBodyParser`, storages and public types |
|
|
165
|
+
| `fetch-layers/layers` | Factories for all built-in layers and idempotency key sources |
|
|
166
|
+
| `fetch-layers/auth` | Types `SessionProvider`, `RefreshResult`, `SessionExpiredReason`, `resetRefreshCircuit` |
|
|
167
|
+
| `fetch-layers/idempotency` | `IdempotencySource`, `IdempotencyContext`, `IdempotencyOutcome`, `createSessionSource`, `stableSerialize` |
|
|
168
|
+
| `fetch-layers/retry` | Only `withRetry` and its options |
|
|
169
|
+
| `fetch-layers/storage` | `StorageLike`, `createMemoryStorage`, `fromWebStorage` |
|
|
170
|
+
|
|
171
|
+
### Direct imports for a smaller bundle
|
|
172
|
+
|
|
173
|
+
`fetch-layers/layers` re-exports all three layers. If you only use one, import it directly - the bundler won't pull the others in.
|
|
174
|
+
|
|
175
|
+
```ts
|
|
176
|
+
import { withRetry } from 'fetch-layers/retry';
|
|
177
|
+
import { withAuth } from 'fetch-layers/auth';
|
|
178
|
+
import { withIdempotency, sessionStorageSource } from 'fetch-layers/idempotency';
|
|
179
|
+
```
|
|
180
|
+
|
|
181
|
+
`fetch-layers/layers` remains convenient for the common case: one import instead of three.
|
|
182
|
+
|
|
183
|
+
## How layers work
|
|
184
|
+
|
|
185
|
+
Every layer is a wrapper around a request function. The `wrap` method takes `next` and returns its own version. The library follows the Decorator pattern (GoF): it adds behavior while keeping the interface. The first layer in the array sees the request first, the last sees it last. Built-in layers run in order: idempotency, retries, auth. The transport receives the request last.
|
|
186
|
+
|
|
187
|
+
Each layer has a priority (`stage`). Higher number - earlier in the chain. Built-in priorities: `withIdempotency: 3`, `withRetry: 2`, `withAuth: 1`. To insert a custom layer between built-ins, use fractional values: `2.5` goes between idempotency and retries, `1.5` between retries and auth.
|
|
188
|
+
|
|
189
|
+
Layers without `stage` skip the order check. They can go anywhere in the array.
|
|
190
|
+
|
|
191
|
+
The order is not arbitrary. The idempotency key must be generated before the first attempt, otherwise every retry creates a new key and deduplication stops working. Auth must sit after retries, so a 401 goes to the auth layer, not to retry. `createClient` validates the order and throws with the name of the layer that breaks the rule.
|
|
192
|
+
|
|
193
|
+
Each client has its own state. The same `Layer` object can be passed to two `createClient` calls: each gets its own `RefreshManager`, its own warnings, its own counter. One client's state does not affect the other.
|
|
194
|
+
|
|
195
|
+
### Why layered architecture instead of hooks or interceptors
|
|
196
|
+
|
|
197
|
+
A layer controls the call: it can call `next` several times, catch an error and call again with different data, run code before and after. A callback can't do this: it receives data and returns it back. It does not decide when and how many times to call the next step.
|
|
198
|
+
|
|
199
|
+
A hook in ky or ofetch, an interceptor in axios - these are callbacks invoked at a fixed point: before the request or after the response. Each gets data and returns it.
|
|
200
|
+
|
|
201
|
+
`withRetry` calls `next` in a loop until it gets a successful response. `withAuth` catches 401, does a refresh separately, then calls `next` with a new token. `withIdempotency` wraps the whole call and clears the key only after the server confirms.
|
|
202
|
+
|
|
203
|
+
Hooks and interceptors can only change data on the way in and out. They don't describe the loop or the order of calls.
|
|
204
|
+
|
|
205
|
+
## Working with TanStack Query
|
|
206
|
+
|
|
207
|
+
fetch-layers plugs into `queryFn` and `mutationFn`.
|
|
208
|
+
|
|
209
|
+
```tsx
|
|
210
|
+
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
|
211
|
+
|
|
212
|
+
const client = createClient({
|
|
213
|
+
baseUrl: '/api',
|
|
214
|
+
layers: [
|
|
215
|
+
withIdempotency(sessionStorageSource()),
|
|
216
|
+
withAuth({ provider: sessionProvider }),
|
|
217
|
+
],
|
|
218
|
+
});
|
|
219
|
+
|
|
220
|
+
function useUser(id: string) {
|
|
221
|
+
return useQuery({
|
|
222
|
+
queryKey: ['user', id],
|
|
223
|
+
queryFn: ({ signal }) => client.get<User>(`/users/${id}`, { signal }),
|
|
224
|
+
});
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
function useCreateOrder() {
|
|
228
|
+
const queryClient = useQueryClient();
|
|
229
|
+
|
|
230
|
+
return useMutation({
|
|
231
|
+
mutationFn: (order: Order) => client.post<Order>('/orders', order),
|
|
232
|
+
onSuccess: () => {
|
|
233
|
+
queryClient.invalidateQueries({ queryKey: ['orders'] });
|
|
234
|
+
},
|
|
235
|
+
});
|
|
236
|
+
}
|
|
237
|
+
```
|
|
238
|
+
|
|
239
|
+
`queryFn` gets `signal` from TanStack Query, fetch-layers accepts it and combines with its own timeout. Cancellation works both ways.
|
|
240
|
+
|
|
241
|
+
The main conflict is retry. TanStack Query has its own retry for `useQuery`, fetch-layers has its own for HTTP. If both are enabled, 3 attempts x 3 attempts = 9 requests. Keep retry in one place:
|
|
242
|
+
|
|
243
|
+
```ts
|
|
244
|
+
// Retry in fetch-layers, TanStack Query without retry.
|
|
245
|
+
const client = createClient({
|
|
246
|
+
baseUrl: '/api',
|
|
247
|
+
layers: [withRetry({ maxAttempts: 3 })],
|
|
248
|
+
});
|
|
249
|
+
|
|
250
|
+
useQuery({
|
|
251
|
+
queryKey: ['user', id],
|
|
252
|
+
queryFn: () => client.get<User>(`/users/${id}`),
|
|
253
|
+
retry: false,
|
|
254
|
+
});
|
|
255
|
+
```
|
|
256
|
+
|
|
257
|
+
Everything else works without adapters: `ApiError` propagates to `error`, `signal` is accepted as-is, DevTools shows `queryFn` calls unchanged.
|
|
258
|
+
|
|
259
|
+
## License
|
|
260
|
+
|
|
261
|
+
MIT. See [LICENSE](./LICENSE).
|
|
262
|
+
|
|
263
|
+
Changelog: [CHANGELOG.md](./CHANGELOG.md).
|
package/README.ru.md
ADDED
|
@@ -0,0 +1,263 @@
|
|
|
1
|
+
# fetch-layers
|
|
2
|
+
|
|
3
|
+
[English](./README.md) | **Русский**
|
|
4
|
+
|
|
5
|
+
HTTP-клиент, который собирается из слоёв. Каждый слой решает одну задачу: авторизация, повторы, идемпотентность. Слои добавляются по необходимости, порядок слоёв проверяется при создании клиента.
|
|
6
|
+
|
|
7
|
+
Три встроенных слоя:
|
|
8
|
+
|
|
9
|
+
- `withAuth` - обновление токена при 401, один refresh на все параллельные запросы;
|
|
10
|
+
- `withRetry` - повторы 5xx и сетевых ошибок с учётом `Retry-After`;
|
|
11
|
+
- `withIdempotency` - один `Idempotency-Key` на всю операцию, включая повторы.
|
|
12
|
+
|
|
13
|
+
Все ошибки слоёв и транспорта приводятся к классу `ApiError`. Ноль зависимостей, tree-shaking.
|
|
14
|
+
|
|
15
|
+
## Содержание
|
|
16
|
+
|
|
17
|
+
- [Кому подойдёт](#кому-подойдёт)
|
|
18
|
+
- [Какие проблемы решает](#какие-проблемы-решает)
|
|
19
|
+
- [Возможности](#возможности)
|
|
20
|
+
- [Установка и первый запрос](#установка-и-первый-запрос)
|
|
21
|
+
- [Требования](#требования)
|
|
22
|
+
- [Модули](#модули)
|
|
23
|
+
- [Как устроены слои](#как-устроены-слои)
|
|
24
|
+
- [Совместная работа с TanStack Query](#совместная-работа-с-tanstack-query)
|
|
25
|
+
|
|
26
|
+
## Кому подойдёт
|
|
27
|
+
|
|
28
|
+
- **SPA с авторизацией.** Несколько запросов уходят одновременно и получают 401. `withAuth` запустит один refresh на все запросы и повторит каждый с новым токеном.
|
|
29
|
+
|
|
30
|
+
- **API с мутирующими операциями.** Заказы, платежи, бронирования. Требуется повторить запрос при 5xx и таймауте, но повтор POST на создание заказа создаст второй заказ. `withIdempotency` генерирует ключ один раз и сохраняет его до подтверждения сервером.
|
|
31
|
+
|
|
32
|
+
- **Несколько API в одном приложении.** Публичный и приватный, разные токены, разные форматы ошибок. Каждый API - отдельный клиент со своими слоями и своим `SessionProvider`.
|
|
33
|
+
|
|
34
|
+
## Какие проблемы решает
|
|
35
|
+
|
|
36
|
+
### Сессия истекла, запросы падают с 401
|
|
37
|
+
|
|
38
|
+
Пять запросов уходят одновременно, все получают 401. Без координации каждый запрос запустит свой refresh - пять обновлений вместо одного. Токен записывается в хранилище пять раз с гонкой: побеждает последний, а часть запросов остаётся со старым токеном и снова получает 401.
|
|
39
|
+
|
|
40
|
+
`withAuth` собирает все ожидающие запросы в один refresh. Пока он выполняется, остальные ждут. Когда токен обновится, каждый повторяется с новым заголовком. Один refresh на все запросы вместо пяти.
|
|
41
|
+
|
|
42
|
+
### Повторы и дубликаты
|
|
43
|
+
|
|
44
|
+
Сетевые ошибки и 5xx: сервер может быть недоступен, соединение может оборваться. Повтор часто проходит со второй или третьей попытки.
|
|
45
|
+
|
|
46
|
+
Повтор создаёт дубликаты, если операция не идемпотентна. POST на создание заказа при повторе создаст два заказа: первый мог дойти до сервера, ответ потерялся, повтор создал ещё один.
|
|
47
|
+
|
|
48
|
+
Решение - `Idempotency-Key`. Сервер по нему распознаёт дубликат и возвращает результат первой операции. Проблема в том, что ключ должен быть один на всю логическую операцию, включая все повторы и refresh между ними.
|
|
49
|
+
|
|
50
|
+
`withIdempotency` генерирует ключ один раз, до первой попытки, и сохраняет его до подтверждения сервером. Даже если запрос упал по сети и повторяется через пять минут из другого места - ключ тот же.
|
|
51
|
+
|
|
52
|
+
### Разные форматы ошибок
|
|
53
|
+
|
|
54
|
+
У каждого бэкенда свой формат ошибок. Один отдаёт `{ code, message }`, другой `{ error: { code } }`, третий RFC 7807. Без общего механизма разбор приходится повторять в каждом месте, где ошибка обрабатывается.
|
|
55
|
+
|
|
56
|
+
Библиотека делит поля ошибки на два слоя. Структурный слой одинаков для всех серверов: `kind`, `status`, `isRetryable`, `isCancelled`, `isUncertain`, `requestId` (из заголовка `X-Request-Id`), `retryAfterMs`. Контентный слой приходит из тела ответа: `code`, `message`, `fields`, `details`. По умолчанию клиент понимает плоский формат `{ code, message, fields }` и plain-text. Для остальных форматов (Fastify, RFC 7807, DRF, Laravel, `{ error: { code } }`) приложение передаёт свою функцию разбора через `parseErrorBody`.
|
|
57
|
+
|
|
58
|
+
Полное тело ответа всегда доступно в `err.rawBody`, даже если формат не распознан.
|
|
59
|
+
|
|
60
|
+
### Обновление токена временно недоступно
|
|
61
|
+
|
|
62
|
+
При обновлении токена сервер может быть недоступен: сеть упала, refresh-эндпоинт вернул 5xx. Без защиты каждый новый 401 запускает новую попытку refresh, и это добавляет нагрузку на сервер.
|
|
63
|
+
|
|
64
|
+
`withAuth` временно блокирует refresh после сбоя. Пока блокировка активна, 401 возвращается приложению без попытки обновления. `onCircuitOpen` и `onCircuitClose` сообщают, когда предохранитель открывается или закрывается.
|
|
65
|
+
|
|
66
|
+
## Возможности
|
|
67
|
+
|
|
68
|
+
- **Авторизация.** `withAuth` работает с любым `SessionProvider`. Чтобы подключить слой, реализуйте три метода: `getAuthHeaders`, `refresh`, `clear`. Три состояния refresh (`success`, `definitely-failed`, `temporarily-failed`) дают приложению контроль: разлогинить пользователя или повторить позже. Параметры предохранителя: `circuitBreakerMs` и `refreshTimeoutMs`. Предохранитель открывается только на сетевые ошибки, таймауты и 5xx, а не на ошибки в `refresh`. Функция `resetRefreshCircuit(client)` сбрасывает его вручную, если приложение знает, что проблема устранена.
|
|
69
|
+
|
|
70
|
+
- **Идемпотентность.** `withIdempotency` добавляет заголовок `Idempotency-Key` на все мутирующие методы (POST, PUT, PATCH, DELETE). Для эндпоинтов, которые заголовок не принимают, передайте `skipIdempotency: true` на конкретном запросе. Ключ можно хранить в `localStorage`, `sessionStorage` или памяти, в зависимости от того, требуется ли сохранять его при перезагрузке. Для кастомного хранилища - интерфейс `IdempotencySource` (два метода) и утилита `stableSerialize` для отпечатка тела. `maxEntries` ограничивает размер хранилища, вытеснение по времени использования.
|
|
71
|
+
|
|
72
|
+
- **Повторы запросов.** `withRetry` настраивается: `maxAttempts`, `baseDelayMs`, `maxDelayMs`, `jitterRatio`, `retryOnNetwork`, `retryOnTimeout`. Свои политики через `shouldRetry`, `computeDelay`, `onBeforeRetry`. `Retry-After` от сервера имеет приоритет над вычисленной задержкой.
|
|
73
|
+
|
|
74
|
+
- **Ошибки.** `ApiError` с геттерами `isRetryable`, `isCancelled`, `isAuthError`, `isUncertain` и другими. `err.fields` - готовая структура `Record<string, string>` для формы, если сервер отдаёт плоский формат. `err.rawBody` - оригинальное тело ответа для всего остального. Свой разбор через `parseErrorBody`.
|
|
75
|
+
|
|
76
|
+
- **Транспорт.** Валидация `baseUrl`, `timeoutMs`, `fetch` и порядка слоёв при создании клиента. Заголовки принимаются как `Record`, `Headers` или массив пар. `defaultHeaders` для сквозных заголовков. `timeoutMs` и `signal` в конкретном запросе. `requestWithMeta` возвращает HTTP-метаданные вместе с данными - для случаев, когда заголовок ответа влияет на дальнейшие действия: `Retry-After` в `202 Accepted`, `Location` в `201`, `X-Request-Id` для логов. `fetchOptions` для остальных параметров `fetch`.
|
|
77
|
+
|
|
78
|
+
Асинхронные операции сервер может подтвердить ответом `202 Accepted` с заголовком `Retry-After`. Значение паузы в миллисекундах доступно в `meta.retryAfterMs` - ровно таким, каким его прислал сервер. Верхнюю границу библиотека не ставит: сколько ждать, решает приложение.
|
|
79
|
+
|
|
80
|
+
```ts
|
|
81
|
+
const { meta } = await client.requestWithMeta({
|
|
82
|
+
path: '/api/jobs',
|
|
83
|
+
method: 'POST',
|
|
84
|
+
body: { action: 'start' },
|
|
85
|
+
});
|
|
86
|
+
await new Promise((resolve) => setTimeout(resolve, meta.retryAfterMs ?? 1000));
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
- **Тела запросов.** JSON, `FormData`, `Blob`, `File`, `ArrayBuffer`, `TypedArray`, `DataView`, `URLSearchParams`, `ReadableStream`, Node.js `stream.Readable`. Работа с типами из iframe и Worker. Рекурсивная проверка: вложенные несериализуемые значения отклоняются до отправки с `BODY_SERIALIZATION_ERROR`.
|
|
90
|
+
|
|
91
|
+
- **Слои.** Свой слой - объект из четырёх полей: `name`, `stage`, `wrap`, `attach`. `LayerContext` даёт доступ к `warn`. Приоритеты `2.5` и `1.5` для вставки между встроенными.
|
|
92
|
+
|
|
93
|
+
## Установка и первый запрос
|
|
94
|
+
|
|
95
|
+
```
|
|
96
|
+
npm install fetch-layers
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
```ts
|
|
100
|
+
import { createClient } from 'fetch-layers';
|
|
101
|
+
|
|
102
|
+
const client = createClient({ baseUrl: '/api' });
|
|
103
|
+
|
|
104
|
+
const products = await client.get<Product[]>('/products');
|
|
105
|
+
|
|
106
|
+
const review = await client.post('/reviews', {
|
|
107
|
+
productId: products[0].id,
|
|
108
|
+
rating: 5,
|
|
109
|
+
comment: 'Отличный товар',
|
|
110
|
+
});
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
Оба метода возвращают распарсенное тело ответа. `post` отправляет объект как JSON. Любая ошибка приходит как `ApiError` - её можно поймать через `try/catch` или `.catch()`.
|
|
114
|
+
|
|
115
|
+
### Подключение слоёв
|
|
116
|
+
|
|
117
|
+
Опция `layers` принимает массив слоёв в порядке от самого внешнего к самому внутреннему:
|
|
118
|
+
|
|
119
|
+
```ts
|
|
120
|
+
import { createClient } from 'fetch-layers';
|
|
121
|
+
import {
|
|
122
|
+
withAuth,
|
|
123
|
+
withRetry,
|
|
124
|
+
withIdempotency,
|
|
125
|
+
sessionStorageSource,
|
|
126
|
+
} from 'fetch-layers/layers';
|
|
127
|
+
|
|
128
|
+
const client = createClient({
|
|
129
|
+
baseUrl: '/api',
|
|
130
|
+
layers: [
|
|
131
|
+
withIdempotency(sessionStorageSource()),
|
|
132
|
+
withRetry({ maxAttempts: 3 }),
|
|
133
|
+
withAuth({ provider: sessionProvider }),
|
|
134
|
+
],
|
|
135
|
+
});
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
Что делают слои в этом порядке:
|
|
139
|
+
|
|
140
|
+
- `withIdempotency` оборачивает всё остальное. Ключ генерируется один раз на операцию и не меняется при повторах.
|
|
141
|
+
- `withRetry` повторяет запрос при 5xx, сети и таймаутах, но не трогает ключ.
|
|
142
|
+
- `withAuth` добавляет заголовки авторизации и обновляет токен при 401.
|
|
143
|
+
|
|
144
|
+
Порядок нельзя переставить произвольно - библиотека проверяет его при создании клиента. Если поменять `withIdempotency` и `withRetry` местами, ключ будет генерироваться заново на каждом повторе - это ошибка. `createClient` выбросит исключение с указанием, какой слой нарушил правило.
|
|
145
|
+
|
|
146
|
+
Если слои не нужны, `createClient({ baseUrl: '/api' })` даёт чистый HTTP-клиент без авторизации, повторов и идемпотентности.
|
|
147
|
+
|
|
148
|
+
## Требования
|
|
149
|
+
|
|
150
|
+
Библиотека работает на Node.js 20.6+, в современных браузерах, Deno и Bun.
|
|
151
|
+
|
|
152
|
+
Нужен глобальный `fetch`. Если его нет, `createClient` выбросит исключение.
|
|
153
|
+
|
|
154
|
+
Пакет только ESM. CommonJS не поддерживается.
|
|
155
|
+
|
|
156
|
+
`crypto.randomUUID` нужен только если подключён `withIdempotency` со встроенным генератором ключей. Библиотека проверяет его при первом мутирующем запросе.
|
|
157
|
+
|
|
158
|
+
## Модули
|
|
159
|
+
|
|
160
|
+
Библиотека разбита на модули. Размер бандла зависит от того, что импортируете.
|
|
161
|
+
|
|
162
|
+
| Модуль | Что экспортирует |
|
|
163
|
+
| ------------------------- | --------------------------------------------------------------------------------------------------------- |
|
|
164
|
+
| `fetch-layers` | `createClient`, `ApiError`, `toApiError`, `ErrorBodyParser`, хранилища и публичные типы |
|
|
165
|
+
| `fetch-layers/layers` | Фабрики всех встроенных слоёв и источники ключей идемпотентности |
|
|
166
|
+
| `fetch-layers/auth` | Типы `SessionProvider`, `RefreshResult`, `SessionExpiredReason`, `resetRefreshCircuit` |
|
|
167
|
+
| `fetch-layers/idempotency` | `IdempotencySource`, `IdempotencyContext`, `IdempotencyOutcome`, `createSessionSource`, `stableSerialize` |
|
|
168
|
+
| `fetch-layers/retry` | Только `withRetry` и его опции |
|
|
169
|
+
| `fetch-layers/storage` | `StorageLike`, `createMemoryStorage`, `fromWebStorage` |
|
|
170
|
+
|
|
171
|
+
### Прямые импорты для минимального размера
|
|
172
|
+
|
|
173
|
+
`fetch-layers/layers` реэкспортирует все три слоя. Если используете только один, импортируйте его напрямую: бандлер не потянет остальные.
|
|
174
|
+
|
|
175
|
+
```ts
|
|
176
|
+
import { withRetry } from 'fetch-layers/retry';
|
|
177
|
+
import { withAuth } from 'fetch-layers/auth';
|
|
178
|
+
import { withIdempotency, sessionStorageSource } from 'fetch-layers/idempotency';
|
|
179
|
+
```
|
|
180
|
+
|
|
181
|
+
`fetch-layers/layers` остаётся удобным вариантом для типового случая: один импорт вместо трёх.
|
|
182
|
+
|
|
183
|
+
## Как устроены слои
|
|
184
|
+
|
|
185
|
+
Каждый слой - обёртка вокруг функции запроса. Метод `wrap` получает `next` и возвращает свою версию. Здесь библиотека следует паттерну Decorator (GoF): добавляет поведение, сохраняя интерфейс. Первый слой в массиве получает запрос первым, последний - последним. Встроенные слои идут в порядке: идемпотентность, повторы, авторизация. Последним запрос получает транспорт.
|
|
186
|
+
|
|
187
|
+
У каждого слоя есть приоритет (stage). Чем больше число, тем раньше слой получает запрос. Встроенные приоритеты: `withIdempotency: 3`, `withRetry: 2`, `withAuth: 1`. Если нужен свой слой между встроенными, используйте дробные значения: `2.5` встанет между идемпотентностью и повторами, `1.5` - между повторами и авторизацией.
|
|
188
|
+
|
|
189
|
+
Слои без stage в проверке не участвуют. Их можно ставить в любое место массива.
|
|
190
|
+
|
|
191
|
+
Порядок слоёв не может быть произвольным. Ключ идемпотентности должен сгенерироваться до первой попытки, иначе каждый повтор создаст новый ключ и дедупликация сломается. Авторизация должна стоять после повторов, чтобы 401 попал в auth-слой, а не в retry. `createClient` проверяет порядок и выбрасывает исключение, если он нарушен: в сообщении будет имя слоя, который нарушает порядок.
|
|
192
|
+
|
|
193
|
+
У каждого клиента собственный экземпляр состояния. Один и тот же объект `Layer` можно передать в два `createClient`: у каждого будет свой `RefreshManager`, свой набор предупреждений, свой счётчик. Состояние одного клиента не влияет на другой.
|
|
194
|
+
|
|
195
|
+
### Почему выбрана слоистая архитектура вместо хуков или интерцепторов
|
|
196
|
+
|
|
197
|
+
Слой управляет вызовом: может вызвать `next` несколько раз, перехватить ошибку и вызвать снова с другими данными, выполнить код до и после. Колбэк так не может: он получает данные и возвращает их обратно, но не решает, когда и сколько раз вызвать следующий шаг.
|
|
198
|
+
|
|
199
|
+
Хук в ky или ofetch, интерцептор в axios - это колбэки, которые вызываются в фиксированной точке: до запроса или после ответа. Каждый получает данные и возвращает их.
|
|
200
|
+
|
|
201
|
+
`withRetry` вызывает `next` в цикле, пока не получит успешный ответ. `withAuth` перехватывает 401, отдельно делает refresh, затем вызывает `next` с новым токеном. `withIdempotency` оборачивает вызов целиком и удаляет ключ только после подтверждения от сервера.
|
|
202
|
+
|
|
203
|
+
Хуки и интерцепторы умеют только менять данные на входе и выходе. Логику цикла и порядка они не описывают.
|
|
204
|
+
|
|
205
|
+
## Совместная работа с TanStack Query
|
|
206
|
+
|
|
207
|
+
fetch-layers встраивается в `queryFn` и `mutationFn`.
|
|
208
|
+
|
|
209
|
+
```tsx
|
|
210
|
+
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
|
211
|
+
|
|
212
|
+
const client = createClient({
|
|
213
|
+
baseUrl: '/api',
|
|
214
|
+
layers: [
|
|
215
|
+
withIdempotency(sessionStorageSource()),
|
|
216
|
+
withAuth({ provider: sessionProvider }),
|
|
217
|
+
],
|
|
218
|
+
});
|
|
219
|
+
|
|
220
|
+
function useUser(id: string) {
|
|
221
|
+
return useQuery({
|
|
222
|
+
queryKey: ['user', id],
|
|
223
|
+
queryFn: ({ signal }) => client.get<User>(`/users/${id}`, { signal }),
|
|
224
|
+
});
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
function useCreateOrder() {
|
|
228
|
+
const queryClient = useQueryClient();
|
|
229
|
+
|
|
230
|
+
return useMutation({
|
|
231
|
+
mutationFn: (order: Order) => client.post<Order>('/orders', order),
|
|
232
|
+
onSuccess: () => {
|
|
233
|
+
queryClient.invalidateQueries({ queryKey: ['orders'] });
|
|
234
|
+
},
|
|
235
|
+
});
|
|
236
|
+
}
|
|
237
|
+
```
|
|
238
|
+
|
|
239
|
+
`queryFn` получает `signal` от TanStack Query, fetch-layers его принимает и объединяет с внутренним таймаутом. Отмена работает в обе стороны.
|
|
240
|
+
|
|
241
|
+
Основной конфликт - retry. У TanStack Query есть свой retry для `useQuery`, у fetch-layers - свой для HTTP. Если оба включены, 3 попытки x 3 попытки = 9 запросов. Оставьте retry в одном месте:
|
|
242
|
+
|
|
243
|
+
```ts
|
|
244
|
+
// Retry в fetch-layers, TanStack Query без retry.
|
|
245
|
+
const client = createClient({
|
|
246
|
+
baseUrl: '/api',
|
|
247
|
+
layers: [withRetry({ maxAttempts: 3 })],
|
|
248
|
+
});
|
|
249
|
+
|
|
250
|
+
useQuery({
|
|
251
|
+
queryKey: ['user', id],
|
|
252
|
+
queryFn: () => client.get<User>(`/users/${id}`),
|
|
253
|
+
retry: false,
|
|
254
|
+
});
|
|
255
|
+
```
|
|
256
|
+
|
|
257
|
+
Остальное работает без адаптеров: `ApiError` пробрасывается в `error`, `signal` принимается как есть, DevTools показывает вызовы `queryFn` без изменений.
|
|
258
|
+
|
|
259
|
+
## Лицензия
|
|
260
|
+
|
|
261
|
+
MIT. См. [LICENSE](./LICENSE).
|
|
262
|
+
|
|
263
|
+
История изменений: [CHANGELOG.md](./CHANGELOG.md).
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const e=new Set([`AUTH_PROVIDER_ERROR`,`REFRESH_TIMEOUT`,`REFRESH_CIRCUIT_OPEN`]);var t=class extends Error{kind;status;code;fields;requestId;retryAfterMs;rawBody;details;isUncertain;constructor(e){super(e.message,{cause:e.cause}),this.name=`ApiError`,this.kind=e.kind,this.status=e.status??0,this.code=e.code??`UNKNOWN`,this.fields=e.fields,this.requestId=e.requestId,this.retryAfterMs=e.retryAfterMs,this.rawBody=e.rawBody,this.details=e.details,this.isUncertain=e.isUncertain??!1}get isNetwork(){return this.kind===`network`||this.kind===`timeout`}get isCancelled(){return this.kind===`abort`}get isAuthError(){return e.has(this.code)||this.status===401||this.status===403}get isRetryable(){return this.kind===`abort`||e.has(this.code)?!1:this.isNetwork||this.status===408||this.status===429?!0:this.status>=500&&this.status<600}get isClientError(){return this.status>=400&&this.status<500}get isServerError(){return this.status>=500&&this.status<600}get isConflict(){return this.status===409}};function n(e){return e instanceof t?e:i(e,`AbortError`)?new t({kind:`abort`,message:`Request aborted`,code:`ABORTED`}):i(e,`TimeoutError`)?new t({kind:`timeout`,message:`Request timeout`,code:`TIMEOUT`,isUncertain:!0}):i(e,`SyntaxError`)?new t({kind:`parse`,message:`Failed to parse response`,code:`PARSE_ERROR`,isUncertain:!1,cause:e}):a(e)?new t({kind:`unknown`,message:e.message,cause:e}):new t({kind:`unknown`,message:`Unknown error`,cause:e})}function r(e){return i(e,`TypeError`)?new t({kind:`network`,message:`Network error`,code:`NETWORK_ERROR`,isUncertain:!0,cause:e}):n(e)}function i(e,t){return typeof e==`object`&&!!e&&`name`in e&&e.name===t}function a(e){return typeof e!=`object`||!e||!(`message`in e)?!1:typeof e.message==`string`}function o(e,t,n){if(!Number.isInteger(e)||e<n)throw Error(`${t} must be an integer >= ${n}, got ${String(e)}`)}function s(e,t){if(!Number.isFinite(e)||e<0)throw Error(`${t} must be a non-negative number, got ${String(e)}`)}function c(e,t){if(!Number.isFinite(e)||e<=0)throw Error(`${t} must be a positive number, got ${String(e)}`)}function l(e,t){if(typeof e!=`string`||e.length===0)throw Error(`${t} must be a non-empty string`)}function u(e,t){return Number.isFinite(e)?Math.max(t,e):t}function d(e){if(e==null)return`undefined`;switch(Object.prototype.toString.call(e)){case`[object FormData]`:return`form-data`;case`[object Blob]`:case`[object File]`:return`blob`;case`[object ArrayBuffer]`:return`binary`;case`[object ReadableStream]`:return`stream`;case`[object URLSearchParams]`:return`url-search-params`;case`[object Map]`:case`[object Set]`:case`[object WeakMap]`:case`[object WeakSet]`:case`[object RegExp]`:case`[object Error]`:return`unsupported`}return typeof e==`string`?`string`:ArrayBuffer.isView(e)?`binary`:_(e)?`stream`:`json`}function f(e){return e===`undefined`||e===`json`||e===`string`}function p(e){return e===`unsupported`}function m(e){return f(d(e))}function h(e){return d(e)===`stream`}function g(e){return _(e)?`NodeReadable`:Object.prototype.toString.call(e).slice(8,-1)}function _(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.pipe==`function`&&typeof t.on==`function`&&typeof t[Symbol.asyncIterator]==`function`}export{h as a,l as c,u as d,t as f,n as h,f as i,s as l,i as m,g as n,p as o,r as p,m as r,o as s,d as t,c as u};
|