@dlenroc/typed-client 0.1.0 → 0.3.1
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 +107 -70
- package/dist/{codec-BWlr5T5u.js → codec-CaVxvHce.js} +51 -43
- package/dist/errors-25xWqgvt.js +138 -0
- package/dist/fetch.d.ts +25 -8
- package/dist/fetch.js +62 -91
- package/dist/index.d.ts +123 -106
- package/dist/index.js +61 -113
- 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/dist/errors-D1bIeOq9.js +0 -138
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,41 @@ 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
|
-
|
|
278
|
-
`cleanupError` holds the secondary failure.
|
|
279
|
-
can read `code`, `meta`, and other
|
|
280
|
-
`message` and `cause` explicitly when building a
|
|
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
|
+
The message names the method and the URL when the URL is known. It lists up to
|
|
299
|
+
10 issues, one per line, or gives the first line of the cause and of its cause.
|
|
300
|
+
It leaves out URL credentials. The `url` and `cause` fields keep the full
|
|
301
|
+
values.
|
|
302
|
+
|
|
303
|
+
If cleanup fails as well, `cleanupError` holds the secondary failure.
|
|
304
|
+
Reporters that serialize errors can read `code`, `meta`, and the other
|
|
305
|
+
enumerable fields. Read `message` and `cause` explicitly when building a
|
|
306
|
+
JSON report.
|
|
281
307
|
|
|
282
308
|
## Other transports
|
|
283
309
|
|
|
284
310
|
### Playwright
|
|
285
311
|
|
|
286
312
|
Use Playwright 1.62 or later. Pass Playwright Test's `request` fixture to the
|
|
287
|
-
|
|
313
|
+
transport as its `context`.
|
|
288
314
|
|
|
289
315
|
```ts
|
|
290
316
|
import { test } from "@playwright/test";
|
|
@@ -305,15 +331,20 @@ test("get user", async ({ request }) => {
|
|
|
305
331
|
```
|
|
306
332
|
|
|
307
333
|
`@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
|
-
|
|
334
|
+
that it cannot find `playwright-core` in the transport's declarations, install
|
|
335
|
+
`playwright-core@^1.62.0` directly.
|
|
336
|
+
|
|
337
|
+
For a standalone script:
|
|
338
|
+
|
|
339
|
+
1. Install `playwright-core` and import `request` from it.
|
|
340
|
+
2. Create a context with `request.newContext()`.
|
|
341
|
+
3. Dispose the context when finished.
|
|
312
342
|
|
|
313
343
|
### k6
|
|
314
344
|
|
|
315
345
|
Use k6 2.2 or later. For TypeScript checking, add `@types/k6@^2.2.0` as a dev
|
|
316
|
-
dependency.
|
|
346
|
+
dependency. `k6Transport` also accepts `http`, a replacement for the `k6/http`
|
|
347
|
+
module.
|
|
317
348
|
|
|
318
349
|
```ts
|
|
319
350
|
import { c } from "@dlenroc/typed-client";
|
|
@@ -332,12 +363,15 @@ export default async function () {
|
|
|
332
363
|
}
|
|
333
364
|
```
|
|
334
365
|
|
|
366
|
+
k6 joins repeated `Set-Cookie` headers into one value. Read the parsed cookies
|
|
367
|
+
from `transport.cookies`.
|
|
368
|
+
|
|
335
369
|
See [Loading npm packages in k6](https://grafana.com/docs/k6/latest/using-k6/modules/#use-nodejs-modules).
|
|
336
370
|
|
|
337
371
|
## Custom transports
|
|
338
372
|
|
|
339
373
|
A `Transport` takes a prepared `TransportRequest` and returns a promise of a
|
|
340
|
-
|
|
374
|
+
`TransportResponse`. Use the kind maps to describe what it can send and decode.
|
|
341
375
|
|
|
342
376
|
```ts
|
|
343
377
|
import { c, type RequestKindMap, type Transport } from "@dlenroc/typed-client";
|
|
@@ -355,9 +389,12 @@ const ping = c.bind(endpoint, empty);
|
|
|
355
389
|
await ping();
|
|
356
390
|
```
|
|
357
391
|
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
392
|
+
- Read native options from `request.input`.
|
|
393
|
+
- To support `timeout` and `follow`, add `CommonOptions` to the transport's
|
|
394
|
+
options and apply them from `request.input`.
|
|
395
|
+
- Release buffered resources in `read()`. This includes `read("none")`, which
|
|
396
|
+
the client calls to skip decoding.
|
|
397
|
+
- If resources can stay live after `read()`, for example a returned stream,
|
|
398
|
+
implement `discard()`. The client calls it when a schema rejects the value
|
|
399
|
+
that `read()` returned.
|
|
400
|
+
- The caller owns live resources that a successful call returns.
|
|
@@ -1,22 +1,17 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { u as forEachField } from "./errors-25xWqgvt.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 };
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
// src/shared/fields.ts
|
|
2
|
+
function forEachField(fields, emit) {
|
|
3
|
+
if (Array.isArray(fields)) {
|
|
4
|
+
for (let i = 0; i < fields.length; i++) {
|
|
5
|
+
const pair = fields[i];
|
|
6
|
+
emit(pair[0], pair[1]);
|
|
7
|
+
}
|
|
8
|
+
return;
|
|
9
|
+
}
|
|
10
|
+
for (const name in fields) {
|
|
11
|
+
const value = fields[name];
|
|
12
|
+
if (Array.isArray(value)) for (let i = 0; i < value.length; i++) emit(name, value[i]);
|
|
13
|
+
else emit(name, value);
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
const formEscapes = /[!'()~]/g;
|
|
17
|
+
function escapeFormCharacter(char) {
|
|
18
|
+
return "%" + char.charCodeAt(0).toString(16).toUpperCase();
|
|
19
|
+
}
|
|
20
|
+
function encodeFormValue(value) {
|
|
21
|
+
return encodeURIComponent(value).replace(formEscapes, escapeFormCharacter).replaceAll("%20", "+");
|
|
22
|
+
}
|
|
23
|
+
function asSearchParams(fields) {
|
|
24
|
+
if (fields instanceof URLSearchParams) return fields;
|
|
25
|
+
const params = new URLSearchParams();
|
|
26
|
+
forEachField(fields, (name, value) => {
|
|
27
|
+
if (value !== void 0) params.append(name, value === null ? "" : String(value));
|
|
28
|
+
});
|
|
29
|
+
return params;
|
|
30
|
+
}
|
|
31
|
+
function encodeFields(fields) {
|
|
32
|
+
if (typeof fields === "string") return fields;
|
|
33
|
+
if (typeof URLSearchParams !== "undefined") return asSearchParams(fields).toString();
|
|
34
|
+
const items = [];
|
|
35
|
+
forEachField(fields, (name, value) => {
|
|
36
|
+
if (value !== void 0) items.push(`${encodeFormValue(name)}=${encodeFormValue(value === null ? "" : String(value))}`);
|
|
37
|
+
});
|
|
38
|
+
return items.join("&");
|
|
39
|
+
}
|
|
40
|
+
// src/shared/url.ts
|
|
41
|
+
function appendQuery(url, query) {
|
|
42
|
+
if (query === void 0) return url;
|
|
43
|
+
const queryString = encodeFields(query);
|
|
44
|
+
if (queryString === "") return url;
|
|
45
|
+
const fragmentIndex = url.indexOf("#");
|
|
46
|
+
const prefix = fragmentIndex < 0 ? url : url.slice(0, fragmentIndex);
|
|
47
|
+
const fragment = fragmentIndex < 0 ? "" : url.slice(fragmentIndex);
|
|
48
|
+
return prefix + (!prefix.includes("?") ? "?" : prefix.endsWith("?") || prefix.endsWith("&") ? "" : "&") + queryString + fragment;
|
|
49
|
+
}
|
|
50
|
+
function createUrlResolver(baseUrl) {
|
|
51
|
+
if (baseUrl === void 0) return (path) => path;
|
|
52
|
+
const prefix = baseUrl.replace(/\/+$/, "");
|
|
53
|
+
return (path) => {
|
|
54
|
+
if (path.charCodeAt(0) === 47) return path.charCodeAt(1) === 47 ? path : prefix + path;
|
|
55
|
+
return /^[A-Za-z][A-Za-z0-9+.-]*:\/\//.test(path) ? path : prefix + "/" + path;
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
// src/core/errors.ts
|
|
59
|
+
function withoutCredentials(url) {
|
|
60
|
+
return url.replace(/^((?:[a-z][a-z\d+.-]*:)?\/\/)[^/?#]*@/i, "$1");
|
|
61
|
+
}
|
|
62
|
+
function pathText(path = []) {
|
|
63
|
+
let text = "";
|
|
64
|
+
for (let i = 0; i < path.length; i++) {
|
|
65
|
+
const segment = path[i];
|
|
66
|
+
const key = typeof segment === "object" ? segment.key : segment;
|
|
67
|
+
text += typeof key === "number" ? `[${key}]` : (i === 0 ? "" : ".") + String(key);
|
|
68
|
+
}
|
|
69
|
+
return text;
|
|
70
|
+
}
|
|
71
|
+
function issueText(issue) {
|
|
72
|
+
const path = pathText(issue.path);
|
|
73
|
+
if (path === "" || issue.message.startsWith(`${path} `)) return issue.message;
|
|
74
|
+
return issue.message === "" ? path : `${path}: ${issue.message}`;
|
|
75
|
+
}
|
|
76
|
+
const shownIssues = 10;
|
|
77
|
+
function issuesText(issues) {
|
|
78
|
+
const shown = Math.min(issues.length, shownIssues);
|
|
79
|
+
let text = "";
|
|
80
|
+
for (let i = 0; i < shown; i++) text += `\n - ${issueText(issues[i])}`;
|
|
81
|
+
if (issues.length > shown) text += `\n - … ${issues.length - shown} more`;
|
|
82
|
+
return text;
|
|
83
|
+
}
|
|
84
|
+
function firstLine(error) {
|
|
85
|
+
const line = (typeof error === "string" ? error : error instanceof Error ? error.message : "").split("\n", 1)[0];
|
|
86
|
+
const code = error?.code;
|
|
87
|
+
return line === "" && typeof code === "string" ? code : line;
|
|
88
|
+
}
|
|
89
|
+
function causeText(cause) {
|
|
90
|
+
const outer = firstLine(cause);
|
|
91
|
+
if (outer === "") return "";
|
|
92
|
+
const inner = firstLine(cause.cause);
|
|
93
|
+
return inner === "" ? `: ${outer}` : `: ${outer} (${inner})`;
|
|
94
|
+
}
|
|
95
|
+
function describe(summary, method, url, issues, cause) {
|
|
96
|
+
const detail = issues !== void 0 && issues.length > 0 ? issuesText(issues) : causeText(cause);
|
|
97
|
+
if (!url) return summary + detail;
|
|
98
|
+
const requestUrl = withoutCredentials(url);
|
|
99
|
+
return `${summary} for ${method} ${requestUrl}${detail.replaceAll(url, () => requestUrl)}`;
|
|
100
|
+
}
|
|
101
|
+
var ClientErrorInstance = class extends Error {
|
|
102
|
+
constructor(code, summary, method, url, meta, status, schema, issues, cause) {
|
|
103
|
+
super(describe(summary, method, url, issues, cause));
|
|
104
|
+
this.code = code;
|
|
105
|
+
this.method = method;
|
|
106
|
+
this.url = url;
|
|
107
|
+
this.meta = meta;
|
|
108
|
+
this.status = status;
|
|
109
|
+
this.schema = schema;
|
|
110
|
+
this.issues = issues;
|
|
111
|
+
this.cause = cause;
|
|
112
|
+
}
|
|
113
|
+
};
|
|
114
|
+
Object.defineProperty(ClientErrorInstance, "name", { value: "ClientError" });
|
|
115
|
+
ClientErrorInstance.prototype.name = "ClientError";
|
|
116
|
+
const ClientError = ClientErrorInstance;
|
|
117
|
+
var ResponseCleanupError = class extends Error {
|
|
118
|
+
constructor(cause) {
|
|
119
|
+
super("Failed to release transport response resources", { cause });
|
|
120
|
+
this.name = "ResponseCleanupError";
|
|
121
|
+
}
|
|
122
|
+
};
|
|
123
|
+
var FailureWithCleanupError = class extends Error {
|
|
124
|
+
cleanupError;
|
|
125
|
+
constructor(cause, cleanupError) {
|
|
126
|
+
super("Operation and response cleanup failed", { cause });
|
|
127
|
+
this.cleanupError = cleanupError;
|
|
128
|
+
this.name = "FailureWithCleanupError";
|
|
129
|
+
}
|
|
130
|
+
};
|
|
131
|
+
function preserveCleanupError(error, failure) {
|
|
132
|
+
if (failure !== null && (typeof failure === "object" || typeof failure === "function") && "cleanupError" in failure) error.cleanupError = failure.cleanupError;
|
|
133
|
+
return error;
|
|
134
|
+
}
|
|
135
|
+
function transportError(prepared, method, url, meta, failure) {
|
|
136
|
+
return preserveCleanupError(new ClientError(prepared ? "transport" : "request", prepared ? "Cannot get response" : "Cannot prepare request", method, url, meta, void 0, void 0, void 0, failure instanceof FailureWithCleanupError ? failure.cause : failure), failure);
|
|
137
|
+
}
|
|
138
|
+
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 };
|