@dlenroc/typed-client 0.1.0 → 0.3.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/README.md +102 -70
- package/dist/{codec-BWlr5T5u.js → codec-DpNVlh9j.js} +51 -43
- package/dist/{errors-D1bIeOq9.js → errors-Dcje8BxZ.js} +19 -62
- package/dist/fetch.d.ts +25 -8
- package/dist/fetch.js +62 -91
- package/dist/index.d.ts +123 -106
- package/dist/index.js +59 -111
- package/dist/k6.d.ts +45 -13
- package/dist/k6.js +80 -73
- package/dist/playwright.d.ts +24 -10
- package/dist/playwright.js +57 -58
- package/dist/{types-Cq8XAc1z.d.ts → types-XCe4DTv4.d.ts} +64 -34
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -8,19 +8,22 @@ Declare typed HTTP endpoints and call them through Fetch, Playwright, or k6.
|
|
|
8
8
|
npm install @dlenroc/typed-client
|
|
9
9
|
```
|
|
10
10
|
|
|
11
|
-
The package uses ESM. Fetch works in Node.js 24+ and
|
|
11
|
+
The package uses ESM. Fetch works in Node.js 24+ and in browsers with
|
|
12
|
+
`AbortSignal.any`.
|
|
12
13
|
|
|
13
|
-
## `c.endpoint(url,
|
|
14
|
+
## `c.endpoint(url, definition?)`
|
|
14
15
|
|
|
15
|
-
`method` defaults to `GET`.
|
|
16
|
-
|
|
16
|
+
`method` defaults to `GET`. Each `{name}` before `?` or `#` is a required path
|
|
17
|
+
parameter. A parameter can be part of a segment, for example
|
|
18
|
+
`/files/{name}.json` or `/jobs/{id}:cancel`. `{}` is literal text. The client
|
|
19
|
+
escapes path values with `encodeURIComponent`.
|
|
17
20
|
|
|
18
21
|
```ts
|
|
19
22
|
import { c } from "@dlenroc/typed-client";
|
|
20
23
|
|
|
21
24
|
type User = { id: number; name: string };
|
|
22
25
|
|
|
23
|
-
export const getUser = c.endpoint("/users
|
|
26
|
+
export const getUser = c.endpoint("/users/{id}", {
|
|
24
27
|
responses: {
|
|
25
28
|
200: c.type<User>(),
|
|
26
29
|
404: "none",
|
|
@@ -59,12 +62,13 @@ if (result.status === 200) {
|
|
|
59
62
|
```
|
|
60
63
|
|
|
61
64
|
The built-in transports append relative endpoints to the path in `baseUrl`.
|
|
62
|
-
Both calls use `https://api.example.test/v1/users/42`.
|
|
65
|
+
Both calls use `https://api.example.test/v1/users/42`. `fetchTransport` also
|
|
66
|
+
accepts `fetch`, a replacement for `globalThis.fetch`.
|
|
63
67
|
|
|
64
68
|
## Bodies
|
|
65
69
|
|
|
66
|
-
|
|
67
|
-
or a schema to give callers a typed JSON body.
|
|
70
|
+
Without a `body` declaration, a call accepts an optional JSON body. Use
|
|
71
|
+
`c.type<T>()` or a schema to give callers a typed JSON body.
|
|
68
72
|
|
|
69
73
|
```ts
|
|
70
74
|
const createUser = c.bind(
|
|
@@ -79,8 +83,8 @@ const createUser = c.bind(
|
|
|
79
83
|
await createUser({ body: { name: "Ada" } });
|
|
80
84
|
```
|
|
81
85
|
|
|
82
|
-
Use a kind such as `"text"`
|
|
83
|
-
|
|
86
|
+
Use a kind such as `"text"` instead of JSON, `{ kind, schema }` to validate
|
|
87
|
+
it, or `"none"` to forbid a request body.
|
|
84
88
|
|
|
85
89
|
Response entries accept the same declarations. Use `{ body, headers }` to add
|
|
86
90
|
a response header schema, for example `404: { body: "none", headers }`.
|
|
@@ -94,20 +98,24 @@ a response header schema, for example `404: { body: "none", headers }`.
|
|
|
94
98
|
| `urlencoded` | Encoded string or fields | Record of strings or arrays |
|
|
95
99
|
| `multipart` | Fields with text or file values | Record of strings, files or arrays |
|
|
96
100
|
|
|
97
|
-
Fetch also
|
|
98
|
-
|
|
101
|
+
Fetch also sends `blob` and `stream` bodies and decodes `blob` and `stream`
|
|
102
|
+
responses. A `blob` body is a `Blob` or `File`. Fetch uses its `type`, if not
|
|
103
|
+
empty, as the default `Content-Type`. A `stream` body is a `ReadableStream` of
|
|
104
|
+
bytes. Fetch reads the stream once while it sends the body. With
|
|
105
|
+
`follow: true`, a redirect other than 303 fails for a `stream` body. Consume or
|
|
106
|
+
cancel a returned stream when you finish with it.
|
|
99
107
|
|
|
100
|
-
|
|
101
|
-
Content-Type
|
|
102
|
-
|
|
103
|
-
|
|
108
|
+
If the body is absent or `undefined`, the client sends no body and no default
|
|
109
|
+
`Content-Type`. The client sends JSON `null` as a value. If JSON serialization
|
|
110
|
+
fails, the call throws a `request` error. Do not send a body with Fetch `GET`
|
|
111
|
+
or `HEAD`.
|
|
104
112
|
|
|
105
113
|
### Fields, headers and files
|
|
106
114
|
|
|
107
115
|
Query, URL-encoded, and multipart fields accept records or arrays of
|
|
108
116
|
`[name, value]` pairs. Repeat a name in the pairs or use an array as a record
|
|
109
|
-
value. `undefined` omits a field and `null` sends an empty value.
|
|
110
|
-
|
|
117
|
+
value. `undefined` omits a field and `null` sends an empty value. A query or
|
|
118
|
+
URL-encoded body also accepts an encoded string.
|
|
111
119
|
|
|
112
120
|
```ts
|
|
113
121
|
await api.users.get({
|
|
@@ -132,22 +140,21 @@ await upload({
|
|
|
132
140
|
});
|
|
133
141
|
```
|
|
134
142
|
|
|
135
|
-
File
|
|
143
|
+
File values accept `data`, `filename?`, and `mediaType?`. The defaults are
|
|
136
144
|
`blob` and `application/octet-stream`. A binary view sends its selected byte
|
|
137
145
|
range. Fetch and Playwright accept `FormData` as the body. k6 accepts
|
|
138
146
|
`http.file()` values as fields.
|
|
139
147
|
|
|
140
|
-
Headers accept
|
|
141
|
-
|
|
142
|
-
|
|
148
|
+
Headers accept a record. The client sends header names as given. Names that
|
|
149
|
+
differ only in case are one header, so the client sends the last spelling and
|
|
150
|
+
the last value. k6, Playwright, and HTTP/2 can change the case. `undefined`
|
|
151
|
+
allows a default value, `null` suppresses the header and its default, and `""`
|
|
152
|
+
sends an empty value. With Playwright, do not set `content-type: null` on a
|
|
153
|
+
request with a body.
|
|
143
154
|
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
Content-Type enabled on requests with a body.
|
|
148
|
-
|
|
149
|
-
Checked multipart calls use the encoder's boundary. Use `unchecked: true`
|
|
150
|
-
to send a custom Content-Type in a negative test.
|
|
155
|
+
A checked call is a call without `unchecked: true`. Checked multipart calls use
|
|
156
|
+
the encoder's boundary. To send a custom `Content-Type` in a negative test, use
|
|
157
|
+
`unchecked: true`.
|
|
151
158
|
|
|
152
159
|
## Runtime validation
|
|
153
160
|
|
|
@@ -158,7 +165,7 @@ Validators for `path`, `query`, `headers`, and `body` follow
|
|
|
158
165
|
import { z } from "zod";
|
|
159
166
|
|
|
160
167
|
const getVerifiedUser = c.bind(
|
|
161
|
-
c.endpoint("/users
|
|
168
|
+
c.endpoint("/users/{id}", {
|
|
162
169
|
responses: { 200: z.object({ id: z.number(), name: z.string() }) },
|
|
163
170
|
}),
|
|
164
171
|
transport,
|
|
@@ -190,19 +197,20 @@ const input = {
|
|
|
190
197
|
type VerifiedUser = InferResponse<typeof getVerifiedUser, 200>["body"];
|
|
191
198
|
```
|
|
192
199
|
|
|
193
|
-
`InferResponse` includes the body and transport
|
|
194
|
-
all declared statuses. Pass one status or a union to select results. For
|
|
195
|
-
|
|
200
|
+
`InferResponse` includes the body and the `transport` field. It defaults to
|
|
201
|
+
all declared statuses. Pass one status or a union to select results. For an
|
|
202
|
+
endpoint without declared responses, pass the status you expect.
|
|
196
203
|
|
|
197
204
|
## Call options and statuses
|
|
198
205
|
|
|
199
|
-
Request fields
|
|
206
|
+
Request fields and call options share one object. Native transport options
|
|
207
|
+
go under `transport`.
|
|
200
208
|
|
|
201
209
|
```ts
|
|
202
210
|
await api.users.get({
|
|
203
211
|
path: { id: 42 },
|
|
204
212
|
status: 200,
|
|
205
|
-
|
|
213
|
+
timeout: 5000,
|
|
206
214
|
});
|
|
207
215
|
```
|
|
208
216
|
|
|
@@ -211,6 +219,23 @@ await api.users.get({
|
|
|
211
219
|
| `status` | Accept one status or a nonempty array and narrow the result. |
|
|
212
220
|
| `unchecked` | Skip request schemas and allow `method`, `path`, and `bodyKind` overrides. |
|
|
213
221
|
| `discard` | Check status and headers, then discard the body before decoding. |
|
|
222
|
+
| `timeout` | Milliseconds to wait. Defaults to k6: 60 s, Playwright: 30 s. |
|
|
223
|
+
| `follow` | Follow redirects and return the final response. Defaults to `false`. |
|
|
224
|
+
| `transport` | Native options for the bound transport. |
|
|
225
|
+
|
|
226
|
+
The built-in transports support `timeout`, `follow`, and `transport`.
|
|
227
|
+
|
|
228
|
+
Without `follow`, declare the 3xx status or accept it with `status`. In a
|
|
229
|
+
browser, Fetch reports an unfollowed redirect as status 0.
|
|
230
|
+
|
|
231
|
+
`transport` accepts the native request options, except the method, headers,
|
|
232
|
+
and body, which the client sets. A native redirect option overrides `follow`.
|
|
233
|
+
On k6, a native `timeout` overrides `timeout`. On Fetch, the client combines a
|
|
234
|
+
native `signal` with `timeout`.
|
|
235
|
+
|
|
236
|
+
```ts
|
|
237
|
+
await api.users.get({ path: { id: 42 }, transport: { signal: controller.signal } });
|
|
238
|
+
```
|
|
214
239
|
|
|
215
240
|
Calls accept all declared statuses by default, including 4xx and 5xx.
|
|
216
241
|
If there are no declared responses, pass `status` on each call. Accepted
|
|
@@ -242,7 +267,7 @@ Declared responses still use their schemas.
|
|
|
242
267
|
Responses contain `status`, `url`, `headers`, and `body`. Raw headers use
|
|
243
268
|
lowercase names and preserve repeated values when the native API exposes them
|
|
244
269
|
separately. The `transport` field carries metadata such as Fetch `redirected`,
|
|
245
|
-
Playwright `
|
|
270
|
+
Playwright `serverAddr`, or k6 `timings`.
|
|
246
271
|
|
|
247
272
|
```ts
|
|
248
273
|
import { ClientError } from "@dlenroc/typed-client";
|
|
@@ -251,40 +276,36 @@ try {
|
|
|
251
276
|
await api.users.get({ path: { id: 42 }, status: 200 });
|
|
252
277
|
} catch (error) {
|
|
253
278
|
if (error instanceof ClientError && error.code === "status") {
|
|
254
|
-
console.error(error.meta.operationId, error.status
|
|
279
|
+
console.error(error.meta.operationId, error.status);
|
|
255
280
|
}
|
|
256
281
|
|
|
257
282
|
throw error;
|
|
258
283
|
}
|
|
259
284
|
```
|
|
260
285
|
|
|
261
|
-
| Code
|
|
262
|
-
|
|
|
263
|
-
| `request
|
|
264
|
-
| `
|
|
265
|
-
| `
|
|
266
|
-
| `
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
`cause` holds the underlying failure. If cleanup also fails,
|
|
278
|
-
`cleanupError` holds the secondary failure. Reporters that serialize errors
|
|
279
|
-
can read `code`, `meta`, and other enumerable diagnostics. Read
|
|
280
|
-
`message` and `cause` explicitly when building a JSON report.
|
|
286
|
+
| Code | When it occurs | Fields |
|
|
287
|
+
| ----------- | --------------------------------------------------------------------------------- | ---------------------------- |
|
|
288
|
+
| `request` | Nothing was sent because the call input, URL, preparation, or a schema failed. | `schema`, `issues` |
|
|
289
|
+
| `transport` | The transport failed to deliver or release a response. | `status` if any |
|
|
290
|
+
| `status` | The status falls outside the accepted set. | `status` |
|
|
291
|
+
| `response` | The body cannot be decoded, or a response schema rejects the response. | `status`, `schema`, `issues` |
|
|
292
|
+
|
|
293
|
+
Every `ClientError` includes `method`, `meta`, and `cause`. `url` is set when
|
|
294
|
+
available. `schema` names the schema that failed: `path`, `query`, `headers`,
|
|
295
|
+
or `body`. That schema either reported `issues` or threw `cause`. A `response`
|
|
296
|
+
error without `schema` means the body could not be decoded.
|
|
297
|
+
|
|
298
|
+
If cleanup fails as well, `cleanupError` holds the secondary failure.
|
|
299
|
+
Reporters that serialize errors can read `code`, `meta`, and the other
|
|
300
|
+
enumerable fields. Read `message` and `cause` explicitly when building a
|
|
301
|
+
JSON report.
|
|
281
302
|
|
|
282
303
|
## Other transports
|
|
283
304
|
|
|
284
305
|
### Playwright
|
|
285
306
|
|
|
286
307
|
Use Playwright 1.62 or later. Pass Playwright Test's `request` fixture to the
|
|
287
|
-
|
|
308
|
+
transport as its `context`.
|
|
288
309
|
|
|
289
310
|
```ts
|
|
290
311
|
import { test } from "@playwright/test";
|
|
@@ -305,15 +326,20 @@ test("get user", async ({ request }) => {
|
|
|
305
326
|
```
|
|
306
327
|
|
|
307
328
|
`@playwright/test` already brings in `playwright-core`. If TypeScript reports
|
|
308
|
-
that it cannot find `playwright-core` in the
|
|
309
|
-
`playwright-core@^1.62.0` directly.
|
|
310
|
-
|
|
311
|
-
|
|
329
|
+
that it cannot find `playwright-core` in the transport's declarations, install
|
|
330
|
+
`playwright-core@^1.62.0` directly.
|
|
331
|
+
|
|
332
|
+
For a standalone script:
|
|
333
|
+
|
|
334
|
+
1. Install `playwright-core` and import `request` from it.
|
|
335
|
+
2. Create a context with `request.newContext()`.
|
|
336
|
+
3. Dispose the context when finished.
|
|
312
337
|
|
|
313
338
|
### k6
|
|
314
339
|
|
|
315
340
|
Use k6 2.2 or later. For TypeScript checking, add `@types/k6@^2.2.0` as a dev
|
|
316
|
-
dependency.
|
|
341
|
+
dependency. `k6Transport` also accepts `http`, a replacement for the `k6/http`
|
|
342
|
+
module.
|
|
317
343
|
|
|
318
344
|
```ts
|
|
319
345
|
import { c } from "@dlenroc/typed-client";
|
|
@@ -332,12 +358,15 @@ export default async function () {
|
|
|
332
358
|
}
|
|
333
359
|
```
|
|
334
360
|
|
|
361
|
+
k6 joins repeated `Set-Cookie` headers into one value. Read the parsed cookies
|
|
362
|
+
from `transport.cookies`.
|
|
363
|
+
|
|
335
364
|
See [Loading npm packages in k6](https://grafana.com/docs/k6/latest/using-k6/modules/#use-nodejs-modules).
|
|
336
365
|
|
|
337
366
|
## Custom transports
|
|
338
367
|
|
|
339
368
|
A `Transport` takes a prepared `TransportRequest` and returns a promise of a
|
|
340
|
-
|
|
369
|
+
`TransportResponse`. Use the kind maps to describe what it can send and decode.
|
|
341
370
|
|
|
342
371
|
```ts
|
|
343
372
|
import { c, type RequestKindMap, type Transport } from "@dlenroc/typed-client";
|
|
@@ -355,9 +384,12 @@ const ping = c.bind(endpoint, empty);
|
|
|
355
384
|
await ping();
|
|
356
385
|
```
|
|
357
386
|
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
387
|
+
- Read native options from `request.input`.
|
|
388
|
+
- To support `timeout` and `follow`, add `CommonOptions` to the transport's
|
|
389
|
+
options and apply them from `request.input`.
|
|
390
|
+
- Release buffered resources in `read()`. This includes `read("none")`, which
|
|
391
|
+
the client calls to skip decoding.
|
|
392
|
+
- If resources can stay live after `read()`, for example a returned stream,
|
|
393
|
+
implement `discard()`. The client calls it when a schema rejects the value
|
|
394
|
+
that `read()` returned.
|
|
395
|
+
- The caller owns live resources that a successful call returns.
|
|
@@ -1,22 +1,17 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { u as forEachField } from "./errors-Dcje8BxZ.js";
|
|
2
2
|
// src/transports/body.ts
|
|
3
3
|
function encodeJson(body) {
|
|
4
4
|
const encoded = JSON.stringify(body);
|
|
5
|
-
if (encoded === void 0) throw new
|
|
5
|
+
if (encoded === void 0) throw new TypeError("JSON body cannot be serialized");
|
|
6
6
|
return encoded;
|
|
7
7
|
}
|
|
8
|
-
function binaryView(input) {
|
|
9
|
-
if (input instanceof Uint8Array) return input;
|
|
10
|
-
return input instanceof ArrayBuffer ? new Uint8Array(input) : new Uint8Array(input.buffer, input.byteOffset, input.byteLength);
|
|
11
|
-
}
|
|
12
8
|
function asFormData(fields) {
|
|
13
9
|
if (fields instanceof FormData) return fields;
|
|
14
10
|
const output = new FormData();
|
|
15
11
|
forEachField(fields, (name, value) => {
|
|
16
12
|
if (value === void 0) return;
|
|
17
13
|
if (value !== null && typeof value === "object" && "data" in value) {
|
|
18
|
-
const
|
|
19
|
-
const blob = new Blob([bytes], value.mediaType === void 0 ? {} : { type: value.mediaType });
|
|
14
|
+
const blob = new Blob([value.data], value.mediaType === void 0 ? {} : { type: value.mediaType });
|
|
20
15
|
if (value.filename === void 0) output.append(name, blob);
|
|
21
16
|
else output.append(name, blob, value.filename);
|
|
22
17
|
} else output.append(name, value === null ? "" : String(value));
|
|
@@ -31,37 +26,44 @@ function defaultContentType(bodyKind) {
|
|
|
31
26
|
case "urlencoded": return "application/x-www-form-urlencoded";
|
|
32
27
|
}
|
|
33
28
|
}
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
29
|
+
/**
|
|
30
|
+
* Merge names that differ only in case and add the default `Content-Type`.
|
|
31
|
+
* A checked multipart body drops the caller's `Content-Type`, because the
|
|
32
|
+
* encoder sets the boundary.
|
|
33
|
+
*/
|
|
34
|
+
function prepareHeaders(headers, bodyKind, bodyPresent, unchecked) {
|
|
35
|
+
const fields = Object.create(null);
|
|
36
|
+
const spellings = Object.create(null);
|
|
37
|
+
let contentTypeSuppressed = false;
|
|
38
|
+
if (headers !== void 0) for (const name in headers) {
|
|
39
|
+
const value = headers[name];
|
|
40
|
+
if (value === void 0) continue;
|
|
41
|
+
const key = name.toLowerCase();
|
|
42
|
+
const previous = spellings[key];
|
|
43
|
+
if (previous !== void 0) delete fields[previous];
|
|
44
|
+
if (value === null) delete spellings[key];
|
|
45
|
+
else {
|
|
46
|
+
fields[name] = String(value);
|
|
47
|
+
spellings[key] = name;
|
|
51
48
|
}
|
|
52
|
-
if (
|
|
53
|
-
else forEachField(headers, (name, value) => {
|
|
54
|
-
const key = name.toLowerCase();
|
|
55
|
-
if (Array.isArray(value)) for (const item of value) append(key, item);
|
|
56
|
-
else append(key, value);
|
|
57
|
-
});
|
|
49
|
+
if (key === "content-type") contentTypeSuppressed = value === null;
|
|
58
50
|
}
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
51
|
+
const contentTypeName = spellings["content-type"];
|
|
52
|
+
let contentType = contentTypeName === void 0 ? void 0 : fields[contentTypeName];
|
|
53
|
+
if (bodyPresent && bodyKind === "multipart" && !unchecked) {
|
|
54
|
+
if (contentTypeName !== void 0) {
|
|
55
|
+
delete fields[contentTypeName];
|
|
56
|
+
contentType = void 0;
|
|
57
|
+
}
|
|
58
|
+
} else if (bodyPresent && contentType === void 0 && !contentTypeSuppressed) {
|
|
59
|
+
contentType = defaultContentType(bodyKind);
|
|
60
|
+
if (contentType !== void 0) fields["content-type"] = contentType;
|
|
62
61
|
}
|
|
63
|
-
|
|
64
|
-
|
|
62
|
+
return {
|
|
63
|
+
fields,
|
|
64
|
+
contentType,
|
|
65
|
+
contentTypeSuppressed
|
|
66
|
+
};
|
|
65
67
|
}
|
|
66
68
|
function appendResponseHeader(target, name, value) {
|
|
67
69
|
const key = name.toLowerCase();
|
|
@@ -106,8 +108,9 @@ function decodeUrlEncoded(text) {
|
|
|
106
108
|
}
|
|
107
109
|
if (typeof URLSearchParams !== "undefined") for (const [key, value] of new URLSearchParams(text)) add(key, value);
|
|
108
110
|
else {
|
|
109
|
-
const
|
|
110
|
-
for (
|
|
111
|
+
const pairs = (text.startsWith("?") ? text.slice(1) : text).split("&");
|
|
112
|
+
for (let i = 0; i < pairs.length; i++) {
|
|
113
|
+
const pair = pairs[i];
|
|
111
114
|
if (pair === "") continue;
|
|
112
115
|
const equal = pair.indexOf("=");
|
|
113
116
|
add(decodeFormValue(equal < 0 ? pair : pair.slice(0, equal)), decodeFormValue(equal < 0 ? "" : pair.slice(equal + 1)));
|
|
@@ -115,6 +118,10 @@ function decodeUrlEncoded(text) {
|
|
|
115
118
|
}
|
|
116
119
|
return result;
|
|
117
120
|
}
|
|
121
|
+
/** The lowercase media type of a `Content-Type` value, without parameters. */
|
|
122
|
+
function mediaTypeOf(contentType) {
|
|
123
|
+
return contentType.split(";", 1)[0].trim().toLowerCase();
|
|
124
|
+
}
|
|
118
125
|
const multipartParameter = /;\s*([^=;\s]+)\s*=\s*(?:"([^"\\]*(?:\\.[^"\\]*)*)"|([^";\s]+))/g;
|
|
119
126
|
function parameterValue(match) {
|
|
120
127
|
const quoted = match[2];
|
|
@@ -124,6 +131,7 @@ function decodeMultipart(bytes, contentType) {
|
|
|
124
131
|
const header = typeof contentType === "string" ? contentType : contentType?.[0];
|
|
125
132
|
let boundaryValue;
|
|
126
133
|
if (header !== void 0) {
|
|
134
|
+
if (mediaTypeOf(header) !== "multipart/form-data") throw new TypeError("Multipart response is not multipart/form-data");
|
|
127
135
|
multipartParameter.lastIndex = 0;
|
|
128
136
|
let match;
|
|
129
137
|
while ((match = multipartParameter.exec(header)) !== null) if (match[1].toLowerCase() === "boundary") {
|
|
@@ -131,7 +139,7 @@ function decodeMultipart(bytes, contentType) {
|
|
|
131
139
|
break;
|
|
132
140
|
}
|
|
133
141
|
}
|
|
134
|
-
if (!boundaryValue) throw new TypeError("
|
|
142
|
+
if (!boundaryValue) throw new TypeError("Multipart boundary is missing");
|
|
135
143
|
const boundary = encodeUtf8("--" + boundaryValue);
|
|
136
144
|
const lineBoundary = new Uint8Array(boundary.length + 2);
|
|
137
145
|
lineBoundary[0] = 13;
|
|
@@ -177,10 +185,10 @@ function decodeMultipart(bytes, contentType) {
|
|
|
177
185
|
}
|
|
178
186
|
let at = findBytes(boundary, 0) === 0 ? afterDelimiter(0) : -1;
|
|
179
187
|
if (at < 0) at = findDelimiter(0)?.after ?? -1;
|
|
180
|
-
if (at < 0) throw new TypeError("Multipart opening boundary
|
|
188
|
+
if (at < 0) throw new TypeError("Multipart opening boundary is missing");
|
|
181
189
|
while (at > 0) {
|
|
182
190
|
const headerEnd = findBytes(endOfHeaders, at);
|
|
183
|
-
if (headerEnd < 0) throw new TypeError("
|
|
191
|
+
if (headerEnd < 0) throw new TypeError("Multipart headers are malformed");
|
|
184
192
|
const headerText = decodeUtf8(bytes.subarray(at, headerEnd));
|
|
185
193
|
const disposition = /(?:^|\r\n)content-disposition:\s*([^\r\n]+)/i.exec(headerText)?.[1];
|
|
186
194
|
let name;
|
|
@@ -198,7 +206,7 @@ function decodeMultipart(bytes, contentType) {
|
|
|
198
206
|
const mediaType = /(?:^|\r\n)content-type:\s*([^\r\n]+)/i.exec(headerText)?.[1];
|
|
199
207
|
const bodyStart = headerEnd + endOfHeaders.length;
|
|
200
208
|
const next = findDelimiter(bodyStart);
|
|
201
|
-
if (next === void 0) throw new TypeError("Multipart closing boundary missing");
|
|
209
|
+
if (next === void 0) throw new TypeError("Multipart closing boundary is missing");
|
|
202
210
|
if (name !== void 0) {
|
|
203
211
|
const data = bytes.subarray(bodyStart, next.at);
|
|
204
212
|
const value = filename === void 0 ? decodeUtf8(data) : {
|
|
@@ -215,4 +223,4 @@ function decodeMultipart(bytes, contentType) {
|
|
|
215
223
|
}
|
|
216
224
|
return result;
|
|
217
225
|
}
|
|
218
|
-
export { appendResponseHeader as a,
|
|
226
|
+
export { appendResponseHeader as a, encodeJson as c, encodeUtf8 as i, decodeUrlEncoded as n, prepareHeaders as o, decodeUtf8 as r, asFormData as s, decodeMultipart as t };
|
|
@@ -56,64 +56,21 @@ function createUrlResolver(baseUrl) {
|
|
|
56
56
|
};
|
|
57
57
|
}
|
|
58
58
|
// src/core/errors.ts
|
|
59
|
-
function errorMessage(failure) {
|
|
60
|
-
switch (failure.code) {
|
|
61
|
-
case "request-input": return "Invalid call input";
|
|
62
|
-
case "request-url": return "Request URL construction failed";
|
|
63
|
-
case "request-prepare": return "Request preparation failed";
|
|
64
|
-
case "transport": return "Transport failed to return a response";
|
|
65
|
-
case "response-cleanup": return `Response cleanup failed (status ${failure.status})`;
|
|
66
|
-
case "status": return `Unexpected status ${failure.status}; expected ${failure.expectedStatuses.join(", ")}`;
|
|
67
|
-
case "response-decode": return `Cannot decode ${failure.kind} response (status ${failure.status})`;
|
|
68
|
-
case "request-schema":
|
|
69
|
-
case "response-schema": {
|
|
70
|
-
const origin = failure.code === "request-schema" ? "Request" : "Response";
|
|
71
|
-
const reason = failure.reason === "issues" ? `reported ${failure.issues.length} issue${failure.issues.length === 1 ? "" : "s"}` : "threw";
|
|
72
|
-
const status = failure.code === "response-schema" ? ` (status ${failure.status})` : "";
|
|
73
|
-
return `${origin} ${failure.field} schema ${reason}${status}`;
|
|
74
|
-
}
|
|
75
|
-
}
|
|
76
|
-
}
|
|
77
59
|
var ClientErrorInstance = class extends Error {
|
|
78
|
-
url
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
this.
|
|
84
|
-
this.
|
|
85
|
-
this.
|
|
60
|
+
constructor(code, message, method, url, meta, status, schema, issues, cause) {
|
|
61
|
+
super(message);
|
|
62
|
+
this.code = code;
|
|
63
|
+
this.method = method;
|
|
64
|
+
this.url = url;
|
|
65
|
+
this.meta = meta;
|
|
66
|
+
this.status = status;
|
|
67
|
+
this.schema = schema;
|
|
68
|
+
this.issues = issues;
|
|
69
|
+
this.cause = cause;
|
|
86
70
|
}
|
|
87
71
|
};
|
|
88
|
-
|
|
89
|
-
* Narrow by `code` to read failure-specific fields.
|
|
90
|
-
*
|
|
91
|
-
* @remarks
|
|
92
|
-
* `cause` holds the underlying failure and `cleanupError` holds a
|
|
93
|
-
* secondary cleanup failure. Diagnostic fields such as `code` and
|
|
94
|
-
* `meta` are enumerable. Read `message` and `cause` explicitly for JSON.
|
|
95
|
-
*
|
|
96
|
-
* @example
|
|
97
|
-
* ```ts
|
|
98
|
-
* if (error instanceof ClientError && error.code === "status") {
|
|
99
|
-
* console.log(error.status, error.expectedStatuses);
|
|
100
|
-
* }
|
|
101
|
-
* ```
|
|
102
|
-
*
|
|
103
|
-
* @example
|
|
104
|
-
* ```ts
|
|
105
|
-
* throw new ClientError({
|
|
106
|
-
* code: "transport", method: "GET", cause,
|
|
107
|
-
* });
|
|
108
|
-
* ```
|
|
109
|
-
*/
|
|
72
|
+
ClientErrorInstance.prototype.name = "ClientError";
|
|
110
73
|
const ClientError = ClientErrorInstance;
|
|
111
|
-
var RequestPreparationError = class extends Error {
|
|
112
|
-
constructor(message, options) {
|
|
113
|
-
super(message, options);
|
|
114
|
-
this.name = "RequestPreparationError";
|
|
115
|
-
}
|
|
116
|
-
};
|
|
117
74
|
var ResponseCleanupError = class extends Error {
|
|
118
75
|
constructor(cause) {
|
|
119
76
|
super("Failed to release transport response resources", { cause });
|
|
@@ -128,11 +85,11 @@ var FailureWithCleanupError = class extends Error {
|
|
|
128
85
|
this.name = "FailureWithCleanupError";
|
|
129
86
|
}
|
|
130
87
|
};
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
}
|
|
138
|
-
export {
|
|
88
|
+
function preserveCleanupError(error, failure) {
|
|
89
|
+
if (failure !== null && (typeof failure === "object" || typeof failure === "function") && "cleanupError" in failure) error.cleanupError = failure.cleanupError;
|
|
90
|
+
return error;
|
|
91
|
+
}
|
|
92
|
+
function transportError(prepared, method, url, meta, failure) {
|
|
93
|
+
return preserveCleanupError(new ClientError(prepared ? "transport" : "request", prepared ? "Transport failed to return a response" : "Request preparation failed", method, url, meta, void 0, void 0, void 0, failure instanceof FailureWithCleanupError ? failure.cause : failure), failure);
|
|
94
|
+
}
|
|
95
|
+
export { transportError as a, asSearchParams as c, preserveCleanupError as i, encodeFields as l, FailureWithCleanupError as n, appendQuery as o, ResponseCleanupError as r, createUrlResolver as s, ClientError as t, forEachField as u };
|
package/dist/fetch.d.ts
CHANGED
|
@@ -1,4 +1,16 @@
|
|
|
1
|
-
import { _ as Transport, f as RequestKindMap, m as ResponseKindMap } from "./types-
|
|
1
|
+
import { _ as Transport, f as RequestKindMap, m as ResponseKindMap, n as CommonOptions } from "./types-XCe4DTv4.js";
|
|
2
|
+
interface FetchRequestKinds extends RequestKindMap {
|
|
3
|
+
/**
|
|
4
|
+
* A `Blob` or `File`. Fetch uses its `type`, if not empty, as the default
|
|
5
|
+
* `Content-Type`.
|
|
6
|
+
*/
|
|
7
|
+
readonly blob: Blob;
|
|
8
|
+
/**
|
|
9
|
+
* A `ReadableStream` of bytes. Fetch reads the stream once while it sends
|
|
10
|
+
* the body. With `follow: true`, a redirect other than 303 fails.
|
|
11
|
+
*/
|
|
12
|
+
readonly stream: ReadableStream<Uint8Array>;
|
|
13
|
+
}
|
|
2
14
|
interface FetchResponseKinds extends ResponseKindMap {
|
|
3
15
|
readonly blob: Blob;
|
|
4
16
|
readonly stream: ReadableStream<Uint8Array>;
|
|
@@ -7,14 +19,19 @@ interface FetchMetadata {
|
|
|
7
19
|
readonly redirected: boolean;
|
|
8
20
|
readonly type: ResponseType;
|
|
9
21
|
}
|
|
10
|
-
|
|
11
|
-
|
|
22
|
+
type FetchNativeOptions = CommonOptions & {
|
|
23
|
+
/**
|
|
24
|
+
* Passed to `fetch`. `redirect` here overrides `follow`. The client
|
|
25
|
+
* combines `signal` here with `timeout`.
|
|
26
|
+
*/
|
|
27
|
+
readonly transport?: Omit<RequestInit, "method" | "headers" | "body">;
|
|
28
|
+
};
|
|
12
29
|
/**
|
|
13
|
-
*
|
|
30
|
+
* Send requests with the Fetch API of a browser or Node.js 24+.
|
|
14
31
|
*
|
|
15
32
|
* @remarks
|
|
16
|
-
*
|
|
17
|
-
* `signal`
|
|
33
|
+
* Do not send a body with `GET` or `HEAD`. Pass native options such as
|
|
34
|
+
* `signal` under `transport`. This transport also decodes `blob` and
|
|
18
35
|
* `stream` responses. Consume or cancel returned streams. A stream
|
|
19
36
|
* schema must release its reader lock before it returns or throws.
|
|
20
37
|
* If the schema replaces the stream, consume or cancel the original.
|
|
@@ -27,7 +44,7 @@ type FetchNativeOptions = Pick<RequestInit, (typeof NATIVE_OPTION_KEYS)[number]>
|
|
|
27
44
|
*
|
|
28
45
|
* const transport = fetchTransport({ baseUrl: "https://api.example.test" });
|
|
29
46
|
* const health = c.bind(c.endpoint("/health"), transport);
|
|
30
|
-
* await health({ status: 204,
|
|
47
|
+
* await health({ status: 204, timeout: 5000 });
|
|
31
48
|
* ```
|
|
32
49
|
*
|
|
33
50
|
* @throws
|
|
@@ -38,5 +55,5 @@ export declare function fetchTransport(config?: {
|
|
|
38
55
|
readonly baseUrl?: string;
|
|
39
56
|
/** @defaultValue globalThis.fetch */
|
|
40
57
|
readonly fetch?: typeof globalThis.fetch;
|
|
41
|
-
}): Transport<
|
|
58
|
+
}): Transport<FetchRequestKinds, FetchResponseKinds, FetchNativeOptions, FetchMetadata>;
|
|
42
59
|
export {};
|