@x-requests/core 0.0.0-stage → 0.2.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 +16 -0
- package/LICENSE +21 -0
- package/README.md +365 -2
- package/dist/Fetch.d.ts +11 -0
- package/dist/Fetch.js +96 -0
- package/dist/MiddlewareFetcher.d.ts +9 -0
- package/dist/MiddlewareFetcher.js +14 -0
- package/dist/XClient.d.ts +21 -0
- package/dist/XClient.js +50 -0
- package/dist/XRequest.d.ts +37 -0
- package/dist/XRequest.js +161 -0
- package/dist/errors.d.ts +39 -0
- package/dist/errors.js +55 -0
- package/dist/index.d.ts +17 -0
- package/dist/index.js +9 -0
- package/dist/middleware.d.ts +4 -0
- package/dist/middleware.js +1 -0
- package/dist/openapi.d.ts +55 -0
- package/dist/openapi.js +1 -0
- package/dist/routes.d.ts +80 -0
- package/dist/routes.js +1 -0
- package/dist/statusCodes.d.ts +30 -0
- package/dist/statusCodes.js +29 -0
- package/dist/types.d.ts +30 -0
- package/dist/types.js +1 -0
- package/package.json +77 -4
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## @x-requests/core 0.2.0
|
|
4
|
+
|
|
5
|
+
- Middleware — `client.use()`, `client.onRequest()`, `client.onResponse()` and `config.middleware`.
|
|
6
|
+
|
|
7
|
+
## @x-requests/codegen 0.1.1
|
|
8
|
+
|
|
9
|
+
- Add README to the package.
|
|
10
|
+
|
|
11
|
+
## 0.1.0 (@x-requests/core, @x-requests/codegen)
|
|
12
|
+
|
|
13
|
+
- Initial public release of `@x-requests/core`: fluent request builder, retries with backoff,
|
|
14
|
+
timeouts, `.fallback()`, `.result()`, typed routes and typed errors.
|
|
15
|
+
- `FromOpenApi` maps `openapi-typescript` output to typed routes.
|
|
16
|
+
- `@x-requests/codegen`: `x-requests gen --from <file|url> --to <out.d.ts>`.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Saveliy Anikeev
|
|
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,366 @@
|
|
|
1
|
-
#
|
|
1
|
+
# x-requests
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A small, promise-like HTTP client where **the route is the contract**: path params, query, body,
|
|
4
|
+
responses and error bodies are typed per route, and retries, timeouts and fallbacks are built in.
|
|
5
|
+
|
|
6
|
+
```ts
|
|
7
|
+
import xclient, { type FromOpenApi, isHttpError } from '@x-requests/core';
|
|
8
|
+
import type { paths } from './api/schema'; // generated: npx @x-requests/codegen gen -f openapi.json -t src/api/schema.d.ts
|
|
9
|
+
|
|
10
|
+
const api = xclient<FromOpenApi<paths>>({ config: { baseUrl: 'https://api.example.com' } });
|
|
11
|
+
|
|
12
|
+
const result = await api
|
|
13
|
+
.get('/users/{id}', { id: 1 }) // path params are required and checked
|
|
14
|
+
.params({ expand: 'profile' }) // query is typed from the schema
|
|
15
|
+
.timeout(5000)
|
|
16
|
+
.retries(3) // exponential backoff, only for errors worth retrying
|
|
17
|
+
.result(); // never rejects: { ok, data } | { ok, error }
|
|
18
|
+
|
|
19
|
+
if (result.ok) {
|
|
20
|
+
result.data; // typed response
|
|
21
|
+
} else if (isHttpError(result.error, 404)) {
|
|
22
|
+
result.error.data; // typed 404 body
|
|
23
|
+
}
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
## Why
|
|
27
|
+
|
|
28
|
+
| | x-requests | [ky](https://github.com/sindresorhus/ky) | [ofetch](https://github.com/unjs/ofetch) | [openapi-fetch](https://openapi-ts.dev/openapi-fetch/) |
|
|
29
|
+
| --- | :---: | :---: | :---: | :---: |
|
|
30
|
+
| Types per route from OpenAPI | yes | no | no | yes |
|
|
31
|
+
| Typed error bodies per status | yes | no | no | yes |
|
|
32
|
+
| Built-in retries with backoff | yes | yes | yes | no |
|
|
33
|
+
| Built-in timeout | yes | yes | yes | no |
|
|
34
|
+
| `.fallback(value)` | yes | no | no | no |
|
|
35
|
+
| Non-throwing `result()` | yes | no | no | yes (default) |
|
|
36
|
+
|
|
37
|
+
The comparison reflects the default behaviour of each library at the time of writing; the others
|
|
38
|
+
can usually do more through hooks or middleware. `x-requests` is the combination: the typing of
|
|
39
|
+
`openapi-fetch` with the resilience of `ky`/`ofetch`, in one fluent builder.
|
|
40
|
+
|
|
41
|
+
## Features
|
|
42
|
+
|
|
43
|
+
- Fluent, chainable request builder — a request is a thenable, so you simply `await` it.
|
|
44
|
+
- Types per route (manual or generated from OpenAPI) for path params, query, body, responses and errors.
|
|
45
|
+
- Typed errors (`.result()`, `isHttpError`) and typed error bodies per route.
|
|
46
|
+
- Retries with exponential backoff (only for errors that make sense to retry).
|
|
47
|
+
- Per-request timeouts and `.fallback()`.
|
|
48
|
+
- Automatic JSON handling for request bodies and responses.
|
|
49
|
+
- Pluggable `Fetcher` — swap the transport for tests or custom logic.
|
|
50
|
+
- Written in TypeScript with strict types; ESM-only.
|
|
51
|
+
|
|
52
|
+
## Installation
|
|
53
|
+
|
|
54
|
+
```bash
|
|
55
|
+
npm install @x-requests/core
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
The package is ESM-only (`"type": "module"`) and ships its own type declarations.
|
|
59
|
+
|
|
60
|
+
## Requirements
|
|
61
|
+
|
|
62
|
+
Node.js with a global `fetch` (Node 18+). If `fetch` is unavailable, the client falls back to `node-fetch`.
|
|
63
|
+
|
|
64
|
+
## Usage
|
|
65
|
+
|
|
66
|
+
### Creating a client
|
|
67
|
+
|
|
68
|
+
```ts
|
|
69
|
+
import xclient from '@x-requests/core';
|
|
70
|
+
|
|
71
|
+
const client = xclient({
|
|
72
|
+
config: {
|
|
73
|
+
baseUrl: 'https://api.example.com', // prepended to relative URLs
|
|
74
|
+
maxRetries: 5, // upper limit for .retries()
|
|
75
|
+
},
|
|
76
|
+
});
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
Both options are optional. `xclient()` with no arguments is valid.
|
|
80
|
+
|
|
81
|
+
### Making requests
|
|
82
|
+
|
|
83
|
+
Available methods: `get`, `post`, `put`, `patch`, `delete`, `options`.
|
|
84
|
+
|
|
85
|
+
```ts
|
|
86
|
+
await client.get('/users');
|
|
87
|
+
|
|
88
|
+
await client
|
|
89
|
+
.post('/users')
|
|
90
|
+
.headers({ Authorization: 'Bearer <token>' })
|
|
91
|
+
.body({ name: 'Alice' });
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
Absolute URLs (`https://...`) ignore `baseUrl`.
|
|
95
|
+
|
|
96
|
+
### Path parameters
|
|
97
|
+
|
|
98
|
+
Use `{name}` placeholders and pass the values as an object — either as the second
|
|
99
|
+
argument or via `.path()`:
|
|
100
|
+
|
|
101
|
+
```ts
|
|
102
|
+
await client.get('/companies/{companyId}/users/{userId}', { companyId: 1, userId: 42 });
|
|
103
|
+
|
|
104
|
+
await client.get('/users/{id}').path({ id: 42 }).timeout(3000);
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
Values are URL-encoded. A missing value throws `The path parameter is missing: <name>`
|
|
108
|
+
before any request is sent (and is never replaced by `.fallback()`). Use unique names
|
|
109
|
+
(`companyId`, `userId`) rather than repeating `{id}`.
|
|
110
|
+
|
|
111
|
+
### Request builder
|
|
112
|
+
|
|
113
|
+
| Method | Description |
|
|
114
|
+
| ---------------------------- | ----------------------------------------------------------------- |
|
|
115
|
+
| `.path(data)` | Values for `{name}` placeholders in the URL. |
|
|
116
|
+
| `.body(data)` | Request body. Objects are serialized to JSON, strings are sent as-is. |
|
|
117
|
+
| `.params(data)` | Query string parameters. `null` and `undefined` values are skipped. |
|
|
118
|
+
| `.headers(data)` | Request headers. |
|
|
119
|
+
| `.timeout(ms)` | Abort the request (per attempt) after `ms` milliseconds. |
|
|
120
|
+
| `.retries(count, backoffMs?)`| Retry failed requests up to `count` times. `backoffMs` defaults to `500`. |
|
|
121
|
+
| `.fallback(value \| fn)` | Resolve with `value` (or `fn(error)`) instead of throwing when the request finally fails. |
|
|
122
|
+
|
|
123
|
+
The request is sent on the first `await` (or `.then`). Awaiting the same
|
|
124
|
+
request several times never sends it again — the result is cached.
|
|
125
|
+
|
|
126
|
+
### Responses
|
|
127
|
+
|
|
128
|
+
- `application/json` responses are parsed automatically.
|
|
129
|
+
- Other content types are returned as text.
|
|
130
|
+
- `204` / `205` responses resolve to `undefined`.
|
|
131
|
+
- `Content-Type: application/json` is set automatically only when a body is sent.
|
|
132
|
+
|
|
133
|
+
### Retries
|
|
134
|
+
|
|
135
|
+
`.retries(3)` means **1 main request + up to 3 retries** (4 requests at most).
|
|
136
|
+
The delay between attempts grows exponentially: `backoffMs * 2^attempt`
|
|
137
|
+
(500 ms, 1 s, 2 s, ... by default).
|
|
138
|
+
|
|
139
|
+
Only the following failures are retried:
|
|
140
|
+
|
|
141
|
+
- network errors and timeouts;
|
|
142
|
+
- `5xx` responses;
|
|
143
|
+
- `429 Too Many Requests` (see `isRetryableStatus`).
|
|
144
|
+
|
|
145
|
+
Other `4xx` responses and validation errors are thrown immediately.
|
|
146
|
+
|
|
147
|
+
`retries` must be at least `1` and cannot exceed `config.maxRetries` if it is set.
|
|
148
|
+
|
|
149
|
+
### Fallback
|
|
150
|
+
|
|
151
|
+
`.fallback()` replaces the final error with a default value. It runs only after all
|
|
152
|
+
retries are exhausted, and the result type becomes `T | F`.
|
|
153
|
+
|
|
154
|
+
```ts
|
|
155
|
+
const users = await client.get('/users').retries(2).fallback([]);
|
|
156
|
+
|
|
157
|
+
// a function is treated as a lazy factory and receives the error
|
|
158
|
+
const user = await client.get('/me').fallback((error) => ({ guest: true }));
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
Any value works, including `0`, `null`, `''` and `false`. Validation errors (e.g. a
|
|
162
|
+
missing URL) are never replaced by the fallback.
|
|
163
|
+
|
|
164
|
+
### Errors
|
|
165
|
+
|
|
166
|
+
A request fails with one of four classes, all extending `XRequestError` and
|
|
167
|
+
distinguished by a `kind` field:
|
|
168
|
+
|
|
169
|
+
| Class | `kind` | When |
|
|
170
|
+
| -------------- | ----------- | ------------------------------------------------------------ |
|
|
171
|
+
| `HttpError` | `'http'` | Non-2xx response. Has `status`, raw `body` and parsed `data` (JSON when the response is JSON, otherwise the text). |
|
|
172
|
+
| `TimeoutError` | `'timeout'` | `.timeout(ms)` exceeded. |
|
|
173
|
+
| `NetworkError` | `'network'` | No response (DNS, connection reset, offline). `cause` holds the original error. |
|
|
174
|
+
| `ParseError` | `'parse'` | A successful response with invalid JSON. |
|
|
175
|
+
|
|
176
|
+
Programmer mistakes (missing URL, missing path parameter) throw a `ValidationError`
|
|
177
|
+
and are not part of this set.
|
|
178
|
+
|
|
179
|
+
TypeScript types `catch (error)` as `unknown`, so the typed way to handle errors is
|
|
180
|
+
`.result()`, which never rejects with a request failure:
|
|
181
|
+
|
|
182
|
+
```ts
|
|
183
|
+
const result = await client.get('/orders/{id}', { id: 1 }).result();
|
|
184
|
+
|
|
185
|
+
if (result.ok) {
|
|
186
|
+
result.data; // typed response
|
|
187
|
+
} else if (isHttpError(result.error, 404)) {
|
|
188
|
+
result.error.data.message; // typed by routes: HttpError<404, NotFound>
|
|
189
|
+
} else {
|
|
190
|
+
result.error.kind; // 'http' | 'timeout' | 'network' | 'parse'
|
|
191
|
+
}
|
|
192
|
+
```
|
|
193
|
+
|
|
194
|
+
`isHttpError(error, status?)` also works in a plain `catch` block (it narrows `unknown`
|
|
195
|
+
to `HttpError`). `HttpStatus` provides named constants:
|
|
196
|
+
|
|
197
|
+
```ts
|
|
198
|
+
import { HttpStatus, isHttpError } from '@x-requests/core';
|
|
199
|
+
|
|
200
|
+
try {
|
|
201
|
+
await client.get('/missing');
|
|
202
|
+
} catch (error) {
|
|
203
|
+
if (isHttpError(error, HttpStatus.NOT_FOUND)) {
|
|
204
|
+
console.log(error.status, error.body);
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
```
|
|
208
|
+
|
|
209
|
+
Declare the error bodies of a route with `errors` to get them typed:
|
|
210
|
+
|
|
211
|
+
```ts
|
|
212
|
+
interface Routes {
|
|
213
|
+
'/orders/{id}': {
|
|
214
|
+
get: {
|
|
215
|
+
response: Order;
|
|
216
|
+
errors: { 404: { message: string }; 422: { fields: string[] } };
|
|
217
|
+
};
|
|
218
|
+
};
|
|
219
|
+
}
|
|
220
|
+
```
|
|
221
|
+
|
|
222
|
+
`result.error` is then `HttpError<404, {message: string}> | HttpError<422, {fields: string[]}> | RequestError`:
|
|
223
|
+
the server may always answer with an undeclared status, so the generic errors stay in the union.
|
|
224
|
+
|
|
225
|
+
### Middleware
|
|
226
|
+
|
|
227
|
+
A middleware wraps every attempt of a request (including retries) and can change the request,
|
|
228
|
+
the response, or skip the call altogether:
|
|
229
|
+
|
|
230
|
+
```ts
|
|
231
|
+
const off = client.use(async (req, next) => {
|
|
232
|
+
const started = Date.now();
|
|
233
|
+
const response = await next({ ...req, headers: { ...req.headers, Authorization: `Bearer ${token}` } });
|
|
234
|
+
|
|
235
|
+
console.log(req.url, Date.now() - started, 'ms');
|
|
236
|
+
|
|
237
|
+
return response;
|
|
238
|
+
});
|
|
239
|
+
|
|
240
|
+
client.onRequest(req => ({ ...req, headers: { ...req.headers, 'X-Trace': id } })); // before
|
|
241
|
+
client.onResponse(response => unwrap(response)); // after
|
|
242
|
+
|
|
243
|
+
off(); // remove a middleware
|
|
244
|
+
```
|
|
245
|
+
|
|
246
|
+
Middlewares can also be passed up front: `xclient({ config: { middleware: [...] } })`.
|
|
247
|
+
|
|
248
|
+
- Order: the first registered middleware is the outermost one, so `onRequest` handlers run in
|
|
249
|
+
registration order and `onResponse` handlers in reverse.
|
|
250
|
+
- Middlewares added later apply to the requests made after that; each client has its own list.
|
|
251
|
+
- An error thrown by a middleware goes through the same rules as a fetcher error (`NetworkError`, retries).
|
|
252
|
+
- A middleware sees the plain request and the raw response (`unknown`), not the types of a route.
|
|
253
|
+
|
|
254
|
+
### Custom fetcher
|
|
255
|
+
|
|
256
|
+
Anything implementing the `Fetcher` interface can be used as the transport,
|
|
257
|
+
which is handy for tests:
|
|
258
|
+
|
|
259
|
+
```ts
|
|
260
|
+
import xclient, { type Fetcher } from '@x-requests/core';
|
|
261
|
+
|
|
262
|
+
const fetcher: Fetcher = {
|
|
263
|
+
async request(data) {
|
|
264
|
+
console.log(data.method, data.url);
|
|
265
|
+
return { ok: true } as never;
|
|
266
|
+
},
|
|
267
|
+
};
|
|
268
|
+
|
|
269
|
+
const client = xclient({ fetcher });
|
|
270
|
+
```
|
|
271
|
+
|
|
272
|
+
## Typed routes
|
|
273
|
+
|
|
274
|
+
Describe your API once and get autocomplete and type checks for urls, path parameters,
|
|
275
|
+
`.params()` (query), `.body()` and the response:
|
|
276
|
+
|
|
277
|
+
```ts
|
|
278
|
+
import xclient from '@x-requests/core';
|
|
279
|
+
|
|
280
|
+
interface Routes {
|
|
281
|
+
'/users': {
|
|
282
|
+
get: { query?: { page?: number }; response: User[] };
|
|
283
|
+
post: { body: CreateUser; response: User };
|
|
284
|
+
};
|
|
285
|
+
'/companies/{companyId}/users/{userId}': {
|
|
286
|
+
get: { response: User };
|
|
287
|
+
};
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
const client = xclient<Routes>({ config: { baseUrl: 'https://api.example.com' } });
|
|
291
|
+
|
|
292
|
+
const users = await client.get('/users').params({ page: 2 }); // User[]
|
|
293
|
+
const user = await client.post('/users').body({ name: 'Alice' }); // User
|
|
294
|
+
const one = await client.get('/companies/{companyId}/users/{userId}', {
|
|
295
|
+
companyId: 1,
|
|
296
|
+
userId: 2,
|
|
297
|
+
}); // User
|
|
298
|
+
```
|
|
299
|
+
|
|
300
|
+
What is checked:
|
|
301
|
+
|
|
302
|
+
- only routes that declare the called method are accepted (`client.post('/ping')` is an error);
|
|
303
|
+
- path parameters are required and checked by name, taken from the `{placeholders}`;
|
|
304
|
+
- `.body()` / `.params()` accept the declared types and are rejected for routes without them;
|
|
305
|
+
- `.fallback(x)` widens the result type to `T | typeof x`.
|
|
306
|
+
|
|
307
|
+
Route description: `{ [path]: { [method]: { query?, body?, headers?, path?, response?, errors? } } }`.
|
|
308
|
+
|
|
309
|
+
`path` declares the types of the path parameters (otherwise `string | number`), and
|
|
310
|
+
`errors.default` types the body of every status that is not listed explicitly.
|
|
311
|
+
|
|
312
|
+
Without `Routes` the client stays untyped and accepts any url.
|
|
313
|
+
|
|
314
|
+
To describe the API once for the whole app, use declaration merging instead of a generic:
|
|
315
|
+
|
|
316
|
+
```ts
|
|
317
|
+
declare module '@x-requests/core' {
|
|
318
|
+
interface RegisteredRoutes extends Routes {}
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
const client = xclient(); // typed
|
|
322
|
+
```
|
|
323
|
+
|
|
324
|
+
### From OpenAPI
|
|
325
|
+
|
|
326
|
+
Types generated by [`openapi-typescript`](https://openapi-ts.dev) (via `@x-requests/codegen`) can be used directly:
|
|
327
|
+
|
|
328
|
+
```bash
|
|
329
|
+
npm install -D @x-requests/codegen openapi-typescript
|
|
330
|
+
npx @x-requests/codegen gen --from ./openapi.yaml --to ./src/api/schema.d.ts
|
|
331
|
+
```
|
|
332
|
+
|
|
333
|
+
`--from` accepts a file path or an `http(s)` url (short flags: `-f`, `-t`). `openapi-typescript`
|
|
334
|
+
is an optional peer dependency of `@x-requests/codegen` and has to be installed next to it.
|
|
335
|
+
|
|
336
|
+
```ts
|
|
337
|
+
import xclient, { type FromOpenApi } from '@x-requests/core';
|
|
338
|
+
import type { paths } from './api/schema';
|
|
339
|
+
|
|
340
|
+
const client = xclient<FromOpenApi<paths>>();
|
|
341
|
+
```
|
|
342
|
+
|
|
343
|
+
`FromOpenApi` maps parameters (`query`, `header`, `path`), the JSON request body,
|
|
344
|
+
`2xx` responses to `response`, `4xx`/`5xx` responses to `errors[status]` and a `default`
|
|
345
|
+
response to `errors.default`. Optional and required parameters keep their optionality.
|
|
346
|
+
Not mapped: cookie parameters, `head`/`trace` operations.
|
|
347
|
+
|
|
348
|
+
## Packages
|
|
349
|
+
|
|
350
|
+
- [`@x-requests/core`](.) — the client.
|
|
351
|
+
- [`@x-requests/codegen`](packages/codegen) — CLI that turns an OpenAPI document into the `paths` types.
|
|
352
|
+
|
|
353
|
+
## Scripts
|
|
354
|
+
|
|
355
|
+
```bash
|
|
356
|
+
npm run build # compile core to dist/ and packages/codegen to its dist/
|
|
357
|
+
npm test # unit + type tests for core and codegen (type tests are checked at compile time)
|
|
358
|
+
npm run test:e2e # client against a real local HTTP server
|
|
359
|
+
npm run coverage # unit tests with coverage thresholds
|
|
360
|
+
npm run lint # check code style
|
|
361
|
+
npm run lint:fix # fix code style automatically
|
|
362
|
+
```
|
|
363
|
+
|
|
364
|
+
## License
|
|
365
|
+
|
|
366
|
+
[MIT](LICENSE)
|
package/dist/Fetch.d.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { Fetcher, FetcherRequestParams } from './types.js';
|
|
2
|
+
declare class Fetch implements Fetcher {
|
|
3
|
+
request<T = unknown>(data: FetcherRequestParams): Promise<T>;
|
|
4
|
+
private toTransportError;
|
|
5
|
+
private getFetch;
|
|
6
|
+
private prepareUrl;
|
|
7
|
+
private prepareHeaders;
|
|
8
|
+
private prepareResult;
|
|
9
|
+
private parseErrorBody;
|
|
10
|
+
}
|
|
11
|
+
export default Fetch;
|
package/dist/Fetch.js
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import { stringify } from 'fast-stringify';
|
|
2
|
+
import { HttpError, NetworkError, ParseError, TimeoutError } from './errors.js';
|
|
3
|
+
import { isEmptyResponse } from './statusCodes.js';
|
|
4
|
+
class Fetch {
|
|
5
|
+
async request(data) {
|
|
6
|
+
const fetch = await this.getFetch();
|
|
7
|
+
const url = this.prepareUrl(data.url, data.params);
|
|
8
|
+
const headers = this.prepareHeaders(data.headers, Boolean(data.body));
|
|
9
|
+
let response;
|
|
10
|
+
try {
|
|
11
|
+
response = await fetch(url, {
|
|
12
|
+
method: (data.method ?? 'GET').toUpperCase(),
|
|
13
|
+
headers,
|
|
14
|
+
...(data.timeout && {
|
|
15
|
+
signal: AbortSignal.timeout(data.timeout),
|
|
16
|
+
}),
|
|
17
|
+
...(data.body && {
|
|
18
|
+
body: typeof data.body === 'string'
|
|
19
|
+
? data.body
|
|
20
|
+
: stringify(data.body),
|
|
21
|
+
}),
|
|
22
|
+
});
|
|
23
|
+
}
|
|
24
|
+
catch (error) {
|
|
25
|
+
throw this.toTransportError(error, data.timeout);
|
|
26
|
+
}
|
|
27
|
+
return (await this.prepareResult(response));
|
|
28
|
+
}
|
|
29
|
+
toTransportError(error, timeout) {
|
|
30
|
+
if (error instanceof Error && error.name === 'TimeoutError') {
|
|
31
|
+
return new TimeoutError(timeout, { cause: error });
|
|
32
|
+
}
|
|
33
|
+
return new NetworkError(error instanceof Error ? error.message : String(error), { cause: error });
|
|
34
|
+
}
|
|
35
|
+
async getFetch() {
|
|
36
|
+
if (typeof globalThis.fetch === 'function') {
|
|
37
|
+
return globalThis.fetch.bind(globalThis);
|
|
38
|
+
}
|
|
39
|
+
const { default: nodeFetch } = await import('node-fetch');
|
|
40
|
+
return nodeFetch;
|
|
41
|
+
}
|
|
42
|
+
prepareUrl(rawUrl, params) {
|
|
43
|
+
const url = new URL(rawUrl);
|
|
44
|
+
if (params && typeof params === 'object') {
|
|
45
|
+
const searchParams = new URLSearchParams(url.search);
|
|
46
|
+
for (const [key, value] of Object.entries(params)) {
|
|
47
|
+
if (value !== undefined && value !== null) {
|
|
48
|
+
searchParams.append(key, String(value));
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
url.search = searchParams.toString();
|
|
52
|
+
}
|
|
53
|
+
return url.toString();
|
|
54
|
+
}
|
|
55
|
+
prepareHeaders(rawHeaders, hasBody) {
|
|
56
|
+
const headers = new Headers(rawHeaders);
|
|
57
|
+
if (hasBody && !headers.has('Content-Type')) {
|
|
58
|
+
headers.set('Content-Type', 'application/json');
|
|
59
|
+
}
|
|
60
|
+
return headers;
|
|
61
|
+
}
|
|
62
|
+
async prepareResult(response) {
|
|
63
|
+
const rawResponse = await response.text();
|
|
64
|
+
const contentType = response.headers.get('Content-Type')?.toLowerCase() ?? '';
|
|
65
|
+
const isJson = contentType.includes('application/json');
|
|
66
|
+
if (!response.ok) {
|
|
67
|
+
throw new HttpError(response.status, rawResponse, this.parseErrorBody(rawResponse, isJson));
|
|
68
|
+
}
|
|
69
|
+
if (isEmptyResponse(response.status)) {
|
|
70
|
+
return undefined;
|
|
71
|
+
}
|
|
72
|
+
if (!isJson) {
|
|
73
|
+
return rawResponse;
|
|
74
|
+
}
|
|
75
|
+
if (!rawResponse.trim()) {
|
|
76
|
+
return rawResponse;
|
|
77
|
+
}
|
|
78
|
+
try {
|
|
79
|
+
return JSON.parse(rawResponse);
|
|
80
|
+
}
|
|
81
|
+
catch (err) {
|
|
82
|
+
throw new ParseError(rawResponse, { cause: err });
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
parseErrorBody(raw, isJson) {
|
|
86
|
+
if (!isJson || !raw.trim())
|
|
87
|
+
return raw;
|
|
88
|
+
try {
|
|
89
|
+
return JSON.parse(raw);
|
|
90
|
+
}
|
|
91
|
+
catch {
|
|
92
|
+
return raw;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
export default Fetch;
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { Middleware } from './middleware.js';
|
|
2
|
+
import type { Fetcher, FetcherRequestParams } from './types.js';
|
|
3
|
+
declare class MiddlewareFetcher implements Fetcher {
|
|
4
|
+
private readonly fetcher;
|
|
5
|
+
private readonly middlewares;
|
|
6
|
+
constructor(fetcher: Fetcher, middlewares: readonly Middleware[]);
|
|
7
|
+
request<T = unknown>(data: FetcherRequestParams): Promise<T>;
|
|
8
|
+
}
|
|
9
|
+
export default MiddlewareFetcher;
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { compose } from './middleware.js';
|
|
2
|
+
class MiddlewareFetcher {
|
|
3
|
+
fetcher;
|
|
4
|
+
middlewares;
|
|
5
|
+
constructor(fetcher, middlewares) {
|
|
6
|
+
this.fetcher = fetcher;
|
|
7
|
+
this.middlewares = middlewares;
|
|
8
|
+
}
|
|
9
|
+
request(data) {
|
|
10
|
+
const run = compose(this.middlewares, _data => this.fetcher.request(_data));
|
|
11
|
+
return run(data);
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
export default MiddlewareFetcher;
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { Config, Fetcher, FetcherRequestParams } from './types.js';
|
|
2
|
+
import type { ErrorOf, InputOf, PathArgs, RegisteredRoutes, ResponseOf, RoutesConstraint, UrlOf } from './routes.js';
|
|
3
|
+
import type { Middleware } from './middleware.js';
|
|
4
|
+
import XRequest from './XRequest.js';
|
|
5
|
+
declare class XClient<R extends RoutesConstraint<R> = RegisteredRoutes> {
|
|
6
|
+
private readonly config?;
|
|
7
|
+
private readonly middlewares;
|
|
8
|
+
private readonly fetcher;
|
|
9
|
+
constructor(fetcher: Fetcher, config?: Config | undefined);
|
|
10
|
+
get<P extends UrlOf<R, 'get'> & string>(url: P, ...path: PathArgs<R, P, 'get'>): XRequest<ResponseOf<R, P, "get">, InputOf<R, P, "get">, ErrorOf<R, P, "get">>;
|
|
11
|
+
post<P extends UrlOf<R, 'post'> & string>(url: P, ...path: PathArgs<R, P, 'post'>): XRequest<ResponseOf<R, P, "post">, InputOf<R, P, "post">, ErrorOf<R, P, "post">>;
|
|
12
|
+
put<P extends UrlOf<R, 'put'> & string>(url: P, ...path: PathArgs<R, P, 'put'>): XRequest<ResponseOf<R, P, "put">, InputOf<R, P, "put">, ErrorOf<R, P, "put">>;
|
|
13
|
+
patch<P extends UrlOf<R, 'patch'> & string>(url: P, ...path: PathArgs<R, P, 'patch'>): XRequest<ResponseOf<R, P, "patch">, InputOf<R, P, "patch">, ErrorOf<R, P, "patch">>;
|
|
14
|
+
delete<P extends UrlOf<R, 'delete'> & string>(url: P, ...path: PathArgs<R, P, 'delete'>): XRequest<ResponseOf<R, P, "delete">, InputOf<R, P, "delete">, ErrorOf<R, P, "delete">>;
|
|
15
|
+
options<P extends UrlOf<R, 'options'> & string>(url: P, ...path: PathArgs<R, P, 'options'>): XRequest<ResponseOf<R, P, "options">, InputOf<R, P, "options">, ErrorOf<R, P, "options">>;
|
|
16
|
+
use(middleware: Middleware): () => void;
|
|
17
|
+
onRequest(handler: (data: FetcherRequestParams) => FetcherRequestParams | Promise<FetcherRequestParams>): () => void;
|
|
18
|
+
onResponse(handler: (response: unknown) => unknown): () => void;
|
|
19
|
+
private createXRequest;
|
|
20
|
+
}
|
|
21
|
+
export default XClient;
|
package/dist/XClient.js
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import MiddlewareFetcher from './MiddlewareFetcher.js';
|
|
2
|
+
import XRequest from './XRequest.js';
|
|
3
|
+
class XClient {
|
|
4
|
+
config;
|
|
5
|
+
middlewares;
|
|
6
|
+
fetcher;
|
|
7
|
+
constructor(fetcher, config) {
|
|
8
|
+
this.config = config;
|
|
9
|
+
this.middlewares = [...(config?.middleware ?? [])];
|
|
10
|
+
this.fetcher = new MiddlewareFetcher(fetcher, this.middlewares);
|
|
11
|
+
}
|
|
12
|
+
get(url, ...path) {
|
|
13
|
+
return this.createXRequest('get', url, path);
|
|
14
|
+
}
|
|
15
|
+
post(url, ...path) {
|
|
16
|
+
return this.createXRequest('post', url, path);
|
|
17
|
+
}
|
|
18
|
+
put(url, ...path) {
|
|
19
|
+
return this.createXRequest('put', url, path);
|
|
20
|
+
}
|
|
21
|
+
patch(url, ...path) {
|
|
22
|
+
return this.createXRequest('patch', url, path);
|
|
23
|
+
}
|
|
24
|
+
delete(url, ...path) {
|
|
25
|
+
return this.createXRequest('delete', url, path);
|
|
26
|
+
}
|
|
27
|
+
options(url, ...path) {
|
|
28
|
+
return this.createXRequest('options', url, path);
|
|
29
|
+
}
|
|
30
|
+
use(middleware) {
|
|
31
|
+
this.middlewares.push(middleware);
|
|
32
|
+
return () => {
|
|
33
|
+
const index = this.middlewares.indexOf(middleware);
|
|
34
|
+
if (index !== -1)
|
|
35
|
+
this.middlewares.splice(index, 1);
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
onRequest(handler) {
|
|
39
|
+
return this.use(async (data, next) => next(await handler(data)));
|
|
40
|
+
}
|
|
41
|
+
onResponse(handler) {
|
|
42
|
+
return this.use(async (data, next) => handler(await next(data)));
|
|
43
|
+
}
|
|
44
|
+
createXRequest(method, url, args) {
|
|
45
|
+
const request = new XRequest(this.fetcher, method, url, this.config);
|
|
46
|
+
const [path] = args;
|
|
47
|
+
return (path ? request.path(path) : request);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
export default XClient;
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import type { RequestError } from './errors.js';
|
|
2
|
+
import type { DefaultInput, RequestInput, Result } from './routes.js';
|
|
3
|
+
import type { Config as GlobalConfig, Method, Fetcher } from './types.js';
|
|
4
|
+
declare class XRequest<T = unknown, In extends RequestInput = DefaultInput, E = RequestError> implements PromiseLike<T> {
|
|
5
|
+
private readonly globalConfig;
|
|
6
|
+
private readonly fetcher;
|
|
7
|
+
private readonly requestData;
|
|
8
|
+
private readonly requestConfig;
|
|
9
|
+
private fallbackHandler;
|
|
10
|
+
private promise;
|
|
11
|
+
private static RequiredFields;
|
|
12
|
+
constructor(fetcher: Fetcher, method: Method, url: string, globalConfig?: GlobalConfig);
|
|
13
|
+
body(data: In['body']): this;
|
|
14
|
+
path(data: In['path']): this;
|
|
15
|
+
params(data: In['query']): this;
|
|
16
|
+
headers(data: In['headers']): this;
|
|
17
|
+
timeout(ms: number | null): this;
|
|
18
|
+
fallback<F>(fallback: F | ((error: unknown) => F)): XRequest<T | F, In, E>;
|
|
19
|
+
retries(retries: number, backoffMs?: number): this;
|
|
20
|
+
then<TResult1 = T, TResult2 = unknown>(onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | null, onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null): PromiseLike<TResult1 | TResult2>;
|
|
21
|
+
/**
|
|
22
|
+
* Like `await`, but never rejects with a request failure: the error is returned
|
|
23
|
+
* as a typed value instead. Programmer mistakes (`ValidationError`) still throw.
|
|
24
|
+
*
|
|
25
|
+
* const result = await client.get('/users/{id}', { id: 1 }).result();
|
|
26
|
+
* if (!result.ok) { result.error.kind; }
|
|
27
|
+
*/
|
|
28
|
+
result(): Promise<Result<T, E>>;
|
|
29
|
+
private run;
|
|
30
|
+
private validate;
|
|
31
|
+
private execute;
|
|
32
|
+
private executeWithRetries;
|
|
33
|
+
private static isRetryable;
|
|
34
|
+
private fillPath;
|
|
35
|
+
private resolveUrl;
|
|
36
|
+
}
|
|
37
|
+
export default XRequest;
|
package/dist/XRequest.js
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
import { HttpError, ParseError, ValidationError, toRequestError } from './errors.js';
|
|
2
|
+
import { isRetryableStatus } from './statusCodes.js';
|
|
3
|
+
class XRequest {
|
|
4
|
+
globalConfig;
|
|
5
|
+
fetcher;
|
|
6
|
+
requestData;
|
|
7
|
+
requestConfig = {};
|
|
8
|
+
fallbackHandler;
|
|
9
|
+
promise;
|
|
10
|
+
static RequiredFields = new Set([
|
|
11
|
+
'url',
|
|
12
|
+
'method',
|
|
13
|
+
]);
|
|
14
|
+
constructor(fetcher, method, url, globalConfig) {
|
|
15
|
+
this.fetcher = fetcher;
|
|
16
|
+
this.globalConfig = globalConfig;
|
|
17
|
+
this.requestData = {
|
|
18
|
+
url,
|
|
19
|
+
method,
|
|
20
|
+
};
|
|
21
|
+
if (this.globalConfig?.maxRetries === 0) {
|
|
22
|
+
throw new Error(`maxRetries cannot be equal to zero.`);
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
body(data) {
|
|
26
|
+
this.requestData.body = data;
|
|
27
|
+
return this;
|
|
28
|
+
}
|
|
29
|
+
path(data) {
|
|
30
|
+
this.requestData.path = data;
|
|
31
|
+
return this;
|
|
32
|
+
}
|
|
33
|
+
params(data) {
|
|
34
|
+
this.requestData.params = data;
|
|
35
|
+
return this;
|
|
36
|
+
}
|
|
37
|
+
headers(data) {
|
|
38
|
+
this.requestData.headers = data;
|
|
39
|
+
return this;
|
|
40
|
+
}
|
|
41
|
+
timeout(ms) {
|
|
42
|
+
this.requestConfig.timeout = ms;
|
|
43
|
+
return this;
|
|
44
|
+
}
|
|
45
|
+
fallback(fallback) {
|
|
46
|
+
this.fallbackHandler = typeof fallback === 'function'
|
|
47
|
+
? fallback
|
|
48
|
+
: () => fallback;
|
|
49
|
+
return this;
|
|
50
|
+
}
|
|
51
|
+
retries(retries, backoffMs) {
|
|
52
|
+
const maxRetries = this.globalConfig?.maxRetries;
|
|
53
|
+
if (maxRetries !== undefined && retries > maxRetries) {
|
|
54
|
+
throw new Error(`Retry count cannot be greater than maxRetries - ${retries} > ${maxRetries}`);
|
|
55
|
+
}
|
|
56
|
+
if (retries < 1) {
|
|
57
|
+
throw new Error(`Retry count cannot be looser than 1`);
|
|
58
|
+
}
|
|
59
|
+
this.requestConfig.retries = retries;
|
|
60
|
+
this.requestConfig.backoffMs = backoffMs ?? this.requestConfig.backoffMs ?? 500;
|
|
61
|
+
return this;
|
|
62
|
+
}
|
|
63
|
+
then(onfulfilled, onrejected) {
|
|
64
|
+
this.promise ??= this.run();
|
|
65
|
+
return this.promise.then(onfulfilled, onrejected);
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Like `await`, but never rejects with a request failure: the error is returned
|
|
69
|
+
* as a typed value instead. Programmer mistakes (`ValidationError`) still throw.
|
|
70
|
+
*
|
|
71
|
+
* const result = await client.get('/users/{id}', { id: 1 }).result();
|
|
72
|
+
* if (!result.ok) { result.error.kind; }
|
|
73
|
+
*/
|
|
74
|
+
async result() {
|
|
75
|
+
try {
|
|
76
|
+
return { ok: true, data: await this };
|
|
77
|
+
}
|
|
78
|
+
catch (error) {
|
|
79
|
+
if (error instanceof ValidationError)
|
|
80
|
+
throw error;
|
|
81
|
+
return { ok: false, error: toRequestError(error) };
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
async run() {
|
|
85
|
+
this.validate();
|
|
86
|
+
try {
|
|
87
|
+
return await this.executeWithRetries();
|
|
88
|
+
}
|
|
89
|
+
catch (error) {
|
|
90
|
+
if (!this.fallbackHandler)
|
|
91
|
+
throw error;
|
|
92
|
+
return this.fallbackHandler(error);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
validate() {
|
|
96
|
+
for (const [key, value] of Object.entries(this.requestData)) {
|
|
97
|
+
if (XRequest.RequiredFields.has(key)
|
|
98
|
+
&& [null, undefined, ''].includes(value)) {
|
|
99
|
+
throw new ValidationError(`The value is missing: ${key}`);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
this.resolveUrl();
|
|
103
|
+
}
|
|
104
|
+
execute() {
|
|
105
|
+
return this.fetcher.request({
|
|
106
|
+
url: this.resolveUrl(),
|
|
107
|
+
method: this.requestData.method,
|
|
108
|
+
...(this.requestData.body && {
|
|
109
|
+
body: this.requestData.body,
|
|
110
|
+
}),
|
|
111
|
+
...(this.requestData.params && {
|
|
112
|
+
params: this.requestData.params,
|
|
113
|
+
}),
|
|
114
|
+
...(this.requestData.headers && {
|
|
115
|
+
headers: this.requestData.headers,
|
|
116
|
+
}),
|
|
117
|
+
...(this.requestConfig.timeout && {
|
|
118
|
+
timeout: this.requestConfig.timeout,
|
|
119
|
+
}),
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
async executeWithRetries() {
|
|
123
|
+
const retries = this.requestConfig.retries ?? 0;
|
|
124
|
+
const backoffMs = this.requestConfig.backoffMs ?? 500;
|
|
125
|
+
for (let attempt = 0;; attempt++) {
|
|
126
|
+
try {
|
|
127
|
+
return await this.execute();
|
|
128
|
+
}
|
|
129
|
+
catch (error) {
|
|
130
|
+
if (attempt >= retries || !XRequest.isRetryable(error)) {
|
|
131
|
+
throw error;
|
|
132
|
+
}
|
|
133
|
+
await new Promise(resolve => setTimeout(resolve, backoffMs * 2 ** attempt));
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
static isRetryable(error) {
|
|
138
|
+
if (error instanceof HttpError) {
|
|
139
|
+
return isRetryableStatus(error.status);
|
|
140
|
+
}
|
|
141
|
+
// an invalid response will be just as invalid on the next attempt
|
|
142
|
+
return !(error instanceof ParseError);
|
|
143
|
+
}
|
|
144
|
+
fillPath(url) {
|
|
145
|
+
return url.replace(/\{([^{}]+)\}/g, (_match, name) => {
|
|
146
|
+
const value = this.requestData.path?.[name];
|
|
147
|
+
if (value === undefined || value === null) {
|
|
148
|
+
throw new ValidationError(`The path parameter is missing: ${name}`);
|
|
149
|
+
}
|
|
150
|
+
return encodeURIComponent(String(value));
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
resolveUrl() {
|
|
154
|
+
const url = this.fillPath(this.requestData.url);
|
|
155
|
+
const baseUrl = this.globalConfig?.baseUrl;
|
|
156
|
+
if (!baseUrl || /^[a-z][a-z\d+.-]*:\/\//i.test(url))
|
|
157
|
+
return url;
|
|
158
|
+
return `${baseUrl.replace(/\/+$/, '')}/${url.replace(/^\/+/, '')}`;
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
export default XRequest;
|
package/dist/errors.d.ts
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
export declare class XRequestError extends Error {
|
|
2
|
+
constructor(message: string, options?: ErrorOptions);
|
|
3
|
+
}
|
|
4
|
+
export declare class HttpError<S extends number = number, D = unknown> extends XRequestError {
|
|
5
|
+
readonly status: S;
|
|
6
|
+
readonly body: string;
|
|
7
|
+
readonly data: D;
|
|
8
|
+
readonly kind: "http";
|
|
9
|
+
/**
|
|
10
|
+
* @param status HTTP status code
|
|
11
|
+
* @param body raw response body
|
|
12
|
+
* @param data parsed body (JSON when the response is JSON, otherwise the raw text)
|
|
13
|
+
*/
|
|
14
|
+
constructor(status: S, body: string, data?: D);
|
|
15
|
+
}
|
|
16
|
+
export declare class TimeoutError extends XRequestError {
|
|
17
|
+
readonly timeoutMs: number | undefined;
|
|
18
|
+
readonly kind: "timeout";
|
|
19
|
+
constructor(timeoutMs: number | undefined, options?: ErrorOptions);
|
|
20
|
+
}
|
|
21
|
+
export declare class NetworkError extends XRequestError {
|
|
22
|
+
readonly kind: "network";
|
|
23
|
+
}
|
|
24
|
+
export declare class ParseError extends XRequestError {
|
|
25
|
+
readonly body: string;
|
|
26
|
+
readonly kind: "parse";
|
|
27
|
+
constructor(body: string, options?: ErrorOptions);
|
|
28
|
+
}
|
|
29
|
+
export declare class ValidationError extends Error {
|
|
30
|
+
readonly kind: "validation";
|
|
31
|
+
constructor(message: string);
|
|
32
|
+
}
|
|
33
|
+
export type RequestError = HttpError | TimeoutError | NetworkError | ParseError;
|
|
34
|
+
export declare const toRequestError: (error: unknown) => RequestError;
|
|
35
|
+
type ExactHttp<E, S extends number> = E extends HttpError<infer St, infer D> ? [number] extends [St] ? never : S extends St ? HttpError<S, D> : never : never;
|
|
36
|
+
type WideHttp<E, S extends number> = E extends HttpError<infer St, infer D> ? [number] extends [St] ? HttpError<S, D> : never : never;
|
|
37
|
+
type NarrowHttp<E, S extends number> = unknown extends E ? HttpError<S> : number extends S ? Extract<E, HttpError<number, unknown>> : [ExactHttp<E, S>] extends [never] ? WideHttp<E, S> : ExactHttp<E, S>;
|
|
38
|
+
export declare const isHttpError: <E, S extends number = number>(error: E | NoInfer<NarrowHttp<E, S>>, status?: S) => error is NarrowHttp<E, S>;
|
|
39
|
+
export {};
|
package/dist/errors.js
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
export class XRequestError extends Error {
|
|
2
|
+
constructor(message, options) {
|
|
3
|
+
super(message, options);
|
|
4
|
+
this.name = new.target.name;
|
|
5
|
+
}
|
|
6
|
+
}
|
|
7
|
+
export class HttpError extends XRequestError {
|
|
8
|
+
status;
|
|
9
|
+
body;
|
|
10
|
+
data;
|
|
11
|
+
kind = 'http';
|
|
12
|
+
/**
|
|
13
|
+
* @param status HTTP status code
|
|
14
|
+
* @param body raw response body
|
|
15
|
+
* @param data parsed body (JSON when the response is JSON, otherwise the raw text)
|
|
16
|
+
*/
|
|
17
|
+
constructor(status, body, data = body) {
|
|
18
|
+
super(`HTTP error! Status: ${status}. Body: ${body}`);
|
|
19
|
+
this.status = status;
|
|
20
|
+
this.body = body;
|
|
21
|
+
this.data = data;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
export class TimeoutError extends XRequestError {
|
|
25
|
+
timeoutMs;
|
|
26
|
+
kind = 'timeout';
|
|
27
|
+
constructor(timeoutMs, options) {
|
|
28
|
+
super(`Request timed out${timeoutMs ? ` after ${timeoutMs} ms` : ''}`, options);
|
|
29
|
+
this.timeoutMs = timeoutMs;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
export class NetworkError extends XRequestError {
|
|
33
|
+
kind = 'network';
|
|
34
|
+
}
|
|
35
|
+
export class ParseError extends XRequestError {
|
|
36
|
+
body;
|
|
37
|
+
kind = 'parse';
|
|
38
|
+
constructor(body, options) {
|
|
39
|
+
super(`Failed to parse JSON in http response: ${options?.cause}`, options);
|
|
40
|
+
this.body = body;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
export class ValidationError extends Error {
|
|
44
|
+
kind = 'validation';
|
|
45
|
+
constructor(message) {
|
|
46
|
+
super(message);
|
|
47
|
+
this.name = 'ValidationError';
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
export const toRequestError = (error) => {
|
|
51
|
+
if (error instanceof XRequestError)
|
|
52
|
+
return error;
|
|
53
|
+
return new NetworkError(error instanceof Error ? error.message : String(error), { cause: error });
|
|
54
|
+
};
|
|
55
|
+
export const isHttpError = (error, status) => error instanceof HttpError && (status === undefined || error.status === status);
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { Config, Fetcher } from './types.js';
|
|
2
|
+
import type { RegisteredRoutes, RoutesConstraint } from './routes.js';
|
|
3
|
+
import XClient from './XClient.js';
|
|
4
|
+
declare const xclient: <R extends RoutesConstraint<R> = RegisteredRoutes>(config?: {
|
|
5
|
+
config?: Config;
|
|
6
|
+
fetcher?: Fetcher;
|
|
7
|
+
}) => XClient<R>;
|
|
8
|
+
export default xclient;
|
|
9
|
+
export { HttpError, NetworkError, ParseError, TimeoutError, ValidationError, XRequestError, isHttpError, } from './errors.js';
|
|
10
|
+
export type { RequestError } from './errors.js';
|
|
11
|
+
export { HttpStatus } from './statusCodes.js';
|
|
12
|
+
export type { HttpStatusCode } from './statusCodes.js';
|
|
13
|
+
export type { Result } from './routes.js';
|
|
14
|
+
export type { FromOpenApi } from './openapi.js';
|
|
15
|
+
export type { RegisteredRoutes, RouteDef } from './routes.js';
|
|
16
|
+
export type { Config, Fetcher, FetcherRequestParams } from './types.js';
|
|
17
|
+
export type { Middleware, Next } from './middleware.js';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import XClient from './XClient.js';
|
|
2
|
+
import Fetch from './Fetch.js';
|
|
3
|
+
const xclient = (config) => {
|
|
4
|
+
const fetch = config?.fetcher ?? new Fetch();
|
|
5
|
+
return new XClient(fetch, config?.config);
|
|
6
|
+
};
|
|
7
|
+
export default xclient;
|
|
8
|
+
export { HttpError, NetworkError, ParseError, TimeoutError, ValidationError, XRequestError, isHttpError, } from './errors.js';
|
|
9
|
+
export { HttpStatus } from './statusCodes.js';
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { FetcherRequestParams } from './types.js';
|
|
2
|
+
export type Next = (data: FetcherRequestParams) => Promise<unknown>;
|
|
3
|
+
export type Middleware = (data: FetcherRequestParams, next: Next) => Promise<unknown>;
|
|
4
|
+
export declare const compose: (middlewares: readonly Middleware[], last: Next) => Next;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export const compose = (middlewares, last) => middlewares.reduceRight((next, middleware) => data => middleware(data, next), last);
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import type { Method } from './types.js';
|
|
2
|
+
export type FromOpenApi<Paths> = {
|
|
3
|
+
[Path in keyof Paths & string]: MethodsOf<Paths[Path]>;
|
|
4
|
+
};
|
|
5
|
+
type Defined<T> = Exclude<T, undefined>;
|
|
6
|
+
type Simplify<T> = {
|
|
7
|
+
[K in keyof T]: T[K];
|
|
8
|
+
};
|
|
9
|
+
type MethodsOf<PathItem> = {
|
|
10
|
+
[M in Method as [OperationOf<PathItem, M>] extends [never] ? never : M]: RouteOf<OperationOf<PathItem, M>>;
|
|
11
|
+
};
|
|
12
|
+
type OperationOf<PathItem, M extends Method> = M extends keyof PathItem ? Defined<PathItem[M]> : never;
|
|
13
|
+
type RouteOf<Operation> = Simplify<ParamsPart<Operation, 'query', 'query'> & ParamsPart<Operation, 'header', 'headers'> & ParamsPart<Operation, 'path', 'path'> & BodyOf<Operation> & ResponseOf<Operation> & ErrorsOf<Operation>>;
|
|
14
|
+
type IsOptional<Obj, Key extends keyof Obj> = Partial<Pick<Obj, Key>> extends Pick<Obj, Key> ? true : false;
|
|
15
|
+
type ParamsPart<Operation, Kind extends 'query' | 'header' | 'path', Key extends string> = Operation extends {
|
|
16
|
+
parameters: infer P;
|
|
17
|
+
} ? Kind extends keyof P ? [Defined<P[Kind]>] extends [never] ? unknown : IsOptional<P, Kind> extends true ? {
|
|
18
|
+
[K in Key]?: Defined<P[Kind]>;
|
|
19
|
+
} : {
|
|
20
|
+
[K in Key]: Defined<P[Kind]>;
|
|
21
|
+
} : unknown : unknown;
|
|
22
|
+
type ContentOf<Content> = 'application/json' extends keyof Content ? Content['application/json'] : Content[keyof Content];
|
|
23
|
+
type PayloadOf<ResponseObject> = ResponseObject extends {
|
|
24
|
+
content?: infer Content;
|
|
25
|
+
} ? [Defined<Content>] extends [never] ? undefined : ContentOf<Defined<Content>> : undefined;
|
|
26
|
+
type BodyOf<Operation> = 'requestBody' extends keyof Operation ? [Defined<Operation['requestBody']>] extends [never] ? unknown : Defined<Operation['requestBody']> extends {
|
|
27
|
+
content: infer Content;
|
|
28
|
+
} ? IsOptional<Operation, 'requestBody'> extends true ? {
|
|
29
|
+
body?: ContentOf<Content>;
|
|
30
|
+
} : {
|
|
31
|
+
body: ContentOf<Content>;
|
|
32
|
+
} : unknown : unknown;
|
|
33
|
+
type ResponsesOf<Operation> = Operation extends {
|
|
34
|
+
responses: infer R;
|
|
35
|
+
} ? R : never;
|
|
36
|
+
type StatusKey<Status> = `${Status & (string | number)}`;
|
|
37
|
+
type SuccessStatuses<R> = {
|
|
38
|
+
[S in keyof R]: StatusKey<S> extends `2${string}` ? S : never;
|
|
39
|
+
}[keyof R];
|
|
40
|
+
type ResponseOf<Operation> = [SuccessStatuses<ResponsesOf<Operation>>] extends [never] ? unknown : {
|
|
41
|
+
response: PayloadOf<ResponsesOf<Operation>[SuccessStatuses<ResponsesOf<Operation>>]>;
|
|
42
|
+
};
|
|
43
|
+
type ErrorStatuses<R> = {
|
|
44
|
+
[S in keyof R]: StatusKey<S> extends `4${string}` | `5${string}` ? S : never;
|
|
45
|
+
}[keyof R];
|
|
46
|
+
type DefaultError<R> = 'default' extends keyof R ? {
|
|
47
|
+
default: PayloadOf<R['default']>;
|
|
48
|
+
} : unknown;
|
|
49
|
+
type ErrorMap<R> = Simplify<{
|
|
50
|
+
[S in ErrorStatuses<R>]: PayloadOf<R[S]>;
|
|
51
|
+
} & DefaultError<R>>;
|
|
52
|
+
type ErrorsOf<Operation> = [keyof ErrorMap<ResponsesOf<Operation>>] extends [never] ? unknown : {
|
|
53
|
+
errors: ErrorMap<ResponsesOf<Operation>>;
|
|
54
|
+
};
|
|
55
|
+
export {};
|
package/dist/openapi.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/dist/routes.d.ts
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import type { HttpError, RequestError } from './errors.js';
|
|
2
|
+
import type { Body, HeadersData, Method, Params, PathParams } from './types.js';
|
|
3
|
+
/**
|
|
4
|
+
* Empty on purpose: extend it with declaration merging to describe the API
|
|
5
|
+
* of the whole application, or pass your own routes to `xclient<Routes>()`.
|
|
6
|
+
*
|
|
7
|
+
* declare module '@x-requests/core' {
|
|
8
|
+
* interface RegisteredRoutes extends MyRoutes {}
|
|
9
|
+
* }
|
|
10
|
+
*/
|
|
11
|
+
export interface RegisteredRoutes {
|
|
12
|
+
}
|
|
13
|
+
export type RouteDef = {
|
|
14
|
+
response?: unknown;
|
|
15
|
+
body?: unknown;
|
|
16
|
+
query?: unknown;
|
|
17
|
+
headers?: HeadersData;
|
|
18
|
+
/** Types of path parameters; names and arity still come from the url placeholders. */
|
|
19
|
+
path?: Record<string, unknown>;
|
|
20
|
+
/**
|
|
21
|
+
* Error bodies by status: `{ 404: NotFoundBody; 422: ValidationBody }`.
|
|
22
|
+
* `default` is the body for every status that is not listed.
|
|
23
|
+
*/
|
|
24
|
+
errors?: Partial<Record<number | 'default', unknown>>;
|
|
25
|
+
};
|
|
26
|
+
export type RoutesConstraint<R> = {
|
|
27
|
+
[P in keyof R]: Partial<Record<Method, RouteDef>>;
|
|
28
|
+
};
|
|
29
|
+
export type IsUntyped<R> = [keyof R] extends [never] ? true : false;
|
|
30
|
+
export type PathsWith<R, M extends Method> = {
|
|
31
|
+
[P in keyof R & string]: M extends keyof R[P] ? P : never;
|
|
32
|
+
}[keyof R & string];
|
|
33
|
+
export type UrlOf<R, M extends Method> = IsUntyped<R> extends true ? string : PathsWith<R, M>;
|
|
34
|
+
type DefOf<R, P, M extends Method> = P extends keyof R ? R[P] extends infer Methods ? M extends keyof Methods ? Methods[M] : never : never : never;
|
|
35
|
+
type Field<D, K extends string> = K extends keyof D ? Exclude<D[K], undefined> : never;
|
|
36
|
+
export type PathParamNames<P extends string> = P extends `${string}{${infer Name}}${infer Rest}` ? Name | PathParamNames<Rest> : never;
|
|
37
|
+
export type PathParamsOf<P extends string> = {
|
|
38
|
+
[K in PathParamNames<P>]: string | number;
|
|
39
|
+
};
|
|
40
|
+
/** Path parameter types declared by the route, otherwise `string | number` per placeholder. */
|
|
41
|
+
type PathOf<R, P extends string, M extends Method> = DefOf<R, P, M> extends infer D ? 'path' extends keyof D ? Exclude<D['path'], undefined> : PathParamsOf<P> : PathParamsOf<P>;
|
|
42
|
+
export type PathArgs<R, P extends string, M extends Method> = IsUntyped<R> extends true ? [path?: PathParams] : [PathParamNames<P>] extends [never] ? [] : [path: PathOf<R, P, M>];
|
|
43
|
+
export type RequestInput = {
|
|
44
|
+
body: unknown;
|
|
45
|
+
query: unknown;
|
|
46
|
+
headers: unknown;
|
|
47
|
+
path: unknown;
|
|
48
|
+
};
|
|
49
|
+
export type DefaultInput = {
|
|
50
|
+
body: Body;
|
|
51
|
+
query: Params;
|
|
52
|
+
headers: HeadersData;
|
|
53
|
+
path: PathParams;
|
|
54
|
+
};
|
|
55
|
+
export type InputOf<R, P extends string, M extends Method> = IsUntyped<R> extends true ? DefaultInput : {
|
|
56
|
+
body: Field<DefOf<R, P, M>, 'body'>;
|
|
57
|
+
query: Field<DefOf<R, P, M>, 'query'>;
|
|
58
|
+
headers: 'headers' extends keyof DefOf<R, P, M> ? Field<DefOf<R, P, M>, 'headers'> : HeadersData;
|
|
59
|
+
path: PathOf<R, P, M>;
|
|
60
|
+
};
|
|
61
|
+
export type ResponseOf<R, P extends string, M extends Method> = IsUntyped<R> extends true ? unknown : DefOf<R, P, M> extends infer D ? 'response' extends keyof D ? D['response'] : unknown : unknown;
|
|
62
|
+
export type Result<T, E> = {
|
|
63
|
+
ok: true;
|
|
64
|
+
data: T;
|
|
65
|
+
error?: undefined;
|
|
66
|
+
} | {
|
|
67
|
+
ok: false;
|
|
68
|
+
error: E;
|
|
69
|
+
data?: undefined;
|
|
70
|
+
};
|
|
71
|
+
type DeclaredErrors<D> = Field<D, 'errors'> extends infer Errors ? [Errors] extends [never] ? never : {
|
|
72
|
+
[S in keyof Errors & number]: HttpError<S, Errors[S]>;
|
|
73
|
+
}[keyof Errors & number] : never;
|
|
74
|
+
type AnyStatusError<D> = Field<D, 'errors'> extends infer Errors ? [Errors] extends [never] ? HttpError : 'default' extends keyof Errors ? HttpError<number, Errors['default']> : HttpError : HttpError;
|
|
75
|
+
/**
|
|
76
|
+
* Declared `HttpError<status, body>`s, an `HttpError` for any other status
|
|
77
|
+
* (typed by `errors.default` when present) and the non-HTTP failures.
|
|
78
|
+
*/
|
|
79
|
+
export type ErrorOf<R, P extends string, M extends Method> = IsUntyped<R> extends true ? RequestError : DeclaredErrors<DefOf<R, P, M>> | AnyStatusError<DefOf<R, P, M>> | Exclude<RequestError, HttpError>;
|
|
80
|
+
export {};
|
package/dist/routes.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* HTTP status codes. `node:http` only has `STATUS_CODES` (code -> text) and no
|
|
3
|
+
* named constants, so we keep our own (this also keeps the library runtime-agnostic).
|
|
4
|
+
*/
|
|
5
|
+
export declare const HttpStatus: {
|
|
6
|
+
readonly OK: 200;
|
|
7
|
+
readonly CREATED: 201;
|
|
8
|
+
readonly ACCEPTED: 202;
|
|
9
|
+
readonly NO_CONTENT: 204;
|
|
10
|
+
readonly RESET_CONTENT: 205;
|
|
11
|
+
readonly BAD_REQUEST: 400;
|
|
12
|
+
readonly UNAUTHORIZED: 401;
|
|
13
|
+
readonly FORBIDDEN: 403;
|
|
14
|
+
readonly NOT_FOUND: 404;
|
|
15
|
+
readonly METHOD_NOT_ALLOWED: 405;
|
|
16
|
+
readonly CONFLICT: 409;
|
|
17
|
+
readonly GONE: 410;
|
|
18
|
+
readonly UNPROCESSABLE_ENTITY: 422;
|
|
19
|
+
readonly TOO_MANY_REQUESTS: 429;
|
|
20
|
+
readonly INTERNAL_SERVER_ERROR: 500;
|
|
21
|
+
readonly NOT_IMPLEMENTED: 501;
|
|
22
|
+
readonly BAD_GATEWAY: 502;
|
|
23
|
+
readonly SERVICE_UNAVAILABLE: 503;
|
|
24
|
+
readonly GATEWAY_TIMEOUT: 504;
|
|
25
|
+
};
|
|
26
|
+
export type HttpStatusCode = typeof HttpStatus[keyof typeof HttpStatus];
|
|
27
|
+
export declare const isClientError: (status: number) => boolean;
|
|
28
|
+
export declare const isServerError: (status: number) => boolean;
|
|
29
|
+
export declare const isEmptyResponse: (status: number) => boolean;
|
|
30
|
+
export declare const isRetryableStatus: (status: number) => boolean;
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* HTTP status codes. `node:http` only has `STATUS_CODES` (code -> text) and no
|
|
3
|
+
* named constants, so we keep our own (this also keeps the library runtime-agnostic).
|
|
4
|
+
*/
|
|
5
|
+
export const HttpStatus = {
|
|
6
|
+
OK: 200,
|
|
7
|
+
CREATED: 201,
|
|
8
|
+
ACCEPTED: 202,
|
|
9
|
+
NO_CONTENT: 204,
|
|
10
|
+
RESET_CONTENT: 205,
|
|
11
|
+
BAD_REQUEST: 400,
|
|
12
|
+
UNAUTHORIZED: 401,
|
|
13
|
+
FORBIDDEN: 403,
|
|
14
|
+
NOT_FOUND: 404,
|
|
15
|
+
METHOD_NOT_ALLOWED: 405,
|
|
16
|
+
CONFLICT: 409,
|
|
17
|
+
GONE: 410,
|
|
18
|
+
UNPROCESSABLE_ENTITY: 422,
|
|
19
|
+
TOO_MANY_REQUESTS: 429,
|
|
20
|
+
INTERNAL_SERVER_ERROR: 500,
|
|
21
|
+
NOT_IMPLEMENTED: 501,
|
|
22
|
+
BAD_GATEWAY: 502,
|
|
23
|
+
SERVICE_UNAVAILABLE: 503,
|
|
24
|
+
GATEWAY_TIMEOUT: 504,
|
|
25
|
+
};
|
|
26
|
+
export const isClientError = (status) => status >= 400 && status < 500;
|
|
27
|
+
export const isServerError = (status) => status >= 500 && status < 600;
|
|
28
|
+
export const isEmptyResponse = (status) => status === HttpStatus.NO_CONTENT || status === HttpStatus.RESET_CONTENT;
|
|
29
|
+
export const isRetryableStatus = (status) => status === HttpStatus.TOO_MANY_REQUESTS || isServerError(status);
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import type { Middleware } from './middleware.js';
|
|
2
|
+
export type Config = {
|
|
3
|
+
baseUrl?: string;
|
|
4
|
+
maxRetries?: number;
|
|
5
|
+
middleware?: Middleware[];
|
|
6
|
+
};
|
|
7
|
+
export type RequestData = {
|
|
8
|
+
method: Method;
|
|
9
|
+
headers: HeadersData;
|
|
10
|
+
params: Params;
|
|
11
|
+
path: PathParams;
|
|
12
|
+
body: Body;
|
|
13
|
+
url: string;
|
|
14
|
+
};
|
|
15
|
+
export type Body = Record<string, unknown> | unknown[] | string;
|
|
16
|
+
export type Params = Record<string, unknown> | string;
|
|
17
|
+
export type HeadersData = Record<string, string>;
|
|
18
|
+
export type PathParams = Record<string, string | number>;
|
|
19
|
+
export type Method = 'get' | 'post' | 'put' | 'patch' | 'delete' | 'options';
|
|
20
|
+
export type FetcherRequestParams = {
|
|
21
|
+
method: Method;
|
|
22
|
+
url: string;
|
|
23
|
+
body?: Body;
|
|
24
|
+
params?: Params;
|
|
25
|
+
headers?: HeadersData;
|
|
26
|
+
timeout?: number;
|
|
27
|
+
};
|
|
28
|
+
export interface Fetcher {
|
|
29
|
+
request<T = unknown>(data: FetcherRequestParams): Promise<T>;
|
|
30
|
+
}
|
package/dist/types.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/package.json
CHANGED
|
@@ -1,6 +1,79 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@x-requests/core",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Promise-like HTTP client with per-route types, retries, timeouts and fallbacks",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/sdanikeev/x-requests.git"
|
|
9
|
+
},
|
|
10
|
+
"homepage": "https://github.com/sdanikeev/x-requests#readme",
|
|
11
|
+
"bugs": {
|
|
12
|
+
"url": "https://github.com/sdanikeev/x-requests/issues"
|
|
13
|
+
},
|
|
14
|
+
"author": {
|
|
15
|
+
"name": "Saveliy Anikeev"
|
|
16
|
+
},
|
|
17
|
+
"main": "./dist/index.js",
|
|
18
|
+
"scripts": {
|
|
19
|
+
"test": "rm -rf .test-build && tsc -p tsconfig.test.json && node --test .test-build/tests/*.test.js && npm test -w packages/codegen",
|
|
20
|
+
"lint": "eslint .",
|
|
21
|
+
"lint:fix": "eslint . --fix",
|
|
22
|
+
"build": "rm -rf dist && tsc -p tsconfig.build.json && npm run build -w packages/codegen",
|
|
23
|
+
"prepublishOnly": "npm run lint && npm test && npm run test:e2e && npm run build",
|
|
24
|
+
"coverage": "rm -rf .test-build && tsc -p tsconfig.test.json && node --test --experimental-test-coverage --test-coverage-exclude=\".test-build/tests/**\" --test-coverage-lines=95 --test-coverage-branches=90 --test-coverage-functions=95 .test-build/tests/*.test.js",
|
|
25
|
+
"test:e2e": "rm -rf .test-build && tsc -p tsconfig.test.json && node --test .test-build/tests/e2e/*.test.js"
|
|
26
|
+
},
|
|
27
|
+
"keywords": [
|
|
28
|
+
"http",
|
|
29
|
+
"fetch",
|
|
30
|
+
"client",
|
|
31
|
+
"typescript",
|
|
32
|
+
"openapi",
|
|
33
|
+
"retry",
|
|
34
|
+
"typed"
|
|
35
|
+
],
|
|
36
|
+
"type": "module",
|
|
37
|
+
"workspaces": [
|
|
38
|
+
"packages/*"
|
|
39
|
+
],
|
|
40
|
+
"devDependencies": {
|
|
41
|
+
"@eslint/js": "^10.0.1",
|
|
42
|
+
"@stylistic/eslint-plugin": "^6.0.1",
|
|
43
|
+
"@types/node": "^26.6.6",
|
|
44
|
+
"eslint": "^10.15.0",
|
|
45
|
+
"globals": "^17.14.0",
|
|
46
|
+
"openapi-typescript": "^7.13.0",
|
|
47
|
+
"typescript": "^6.0.3",
|
|
48
|
+
"typescript-eslint": "^8.73.0"
|
|
49
|
+
},
|
|
50
|
+
"overrides": {
|
|
51
|
+
"openapi-typescript": {
|
|
52
|
+
"typescript": "$typescript"
|
|
53
|
+
}
|
|
54
|
+
},
|
|
55
|
+
"dependencies": {
|
|
56
|
+
"fast-stringify": "^4.0.3",
|
|
57
|
+
"node-fetch": "^3.3.2"
|
|
58
|
+
},
|
|
59
|
+
"types": "./dist/index.d.ts",
|
|
60
|
+
"sideEffects": false,
|
|
61
|
+
"engines": {
|
|
62
|
+
"node": ">=18"
|
|
63
|
+
},
|
|
64
|
+
"exports": {
|
|
65
|
+
".": {
|
|
66
|
+
"types": "./dist/index.d.ts",
|
|
67
|
+
"default": "./dist/index.js"
|
|
68
|
+
}
|
|
69
|
+
},
|
|
70
|
+
"files": [
|
|
71
|
+
"dist",
|
|
72
|
+
"README.md",
|
|
73
|
+
"LICENSE",
|
|
74
|
+
"CHANGELOG.md"
|
|
75
|
+
],
|
|
76
|
+
"publishConfig": {
|
|
77
|
+
"access": "public"
|
|
78
|
+
}
|
|
79
|
+
}
|