kanagata 0.1.0 → 0.2.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 +43 -12
- package/dist/cli.js +1 -1
- package/dist/client.d.ts +51 -12
- package/dist/client.js +41 -4
- package/dist/error.d.ts +1 -0
- package/dist/error.js +2 -0
- package/dist/index.js +6 -4
- package/dist/operation.d.ts +1 -1
- package/dist/operation.js +84 -20
- package/dist/pointer.d.ts +4 -0
- package/dist/pointer.js +26 -8
- package/package.json +2 -2
- package/src/client.ts +130 -20
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# kanagata
|
|
2
2
|
|
|
3
|
-
TypeScript types from an OpenAPI 3.0 / 3.1 document (JSON or YAML), and a typed `fetch` client for them.
|
|
3
|
+
TypeScript types from an OpenAPI 3.0 / 3.1 / 3.2 document (JSON or YAML), and a typed `fetch` client for them.
|
|
4
4
|
|
|
5
5
|
- `kanagata generate` writes one `.d.ts` file.
|
|
6
6
|
- `createClient` from `kanagata/client` is one function over `fetch`, with no imports: the path, query, header and cookie parameters and the body are checked against the operation, and the result is a union per status code.
|
|
@@ -76,7 +76,9 @@ await api.put("/files/{name}", {
|
|
|
76
76
|
const events = await api.get("/events", { parseAs: "stream" }); // events.data: ReadableStream | null
|
|
77
77
|
```
|
|
78
78
|
|
|
79
|
-
`api.get`, `api.post`, … (one per HTTP method but `trace`, which fetch rejects; the declarations still type trace operations) take the path template and an object of options, which is optional when nothing in it is required. A required body cannot be `undefined`, even when its schema admits any value. A union of path templates takes options that hold what every one of them needs.
|
|
79
|
+
`api.get`, `api.post`, … (one per HTTP method of the Path Item, `query` included, but `trace`, which fetch rejects; the declarations still type trace operations) take the path template and an object of options, which is optional when nothing in it is required. A required body cannot be `undefined`, even when its schema admits any value. A union of path templates takes options that hold what every one of them needs.
|
|
80
|
+
|
|
81
|
+
A method of `additionalOperations` (3.2) is called through `api.request`, named as the document writes it, which is how it is sent: `api.request("COPY", "/files/{name}", { path: { name: "a.png" } })`. fetch rejects CONNECT, TRACE and TRACK, and sends DELETE, GET, HEAD, OPTIONS, POST and PUT in upper case whatever their case (`Post` as POST), so `request` does not take them.
|
|
80
82
|
|
|
81
83
|
### Config (`createClient`)
|
|
82
84
|
|
|
@@ -96,6 +98,7 @@ const events = await api.get("/events", { parseAs: "stream" }); // events.data:
|
|
|
96
98
|
| ----------------------------------- | --------------------------------------------------------------------------------------------- |
|
|
97
99
|
| `baseUrl` | required for an operation that declares `servers`: one of them, used in place of the config's |
|
|
98
100
|
| `path`, `query`, `header`, `cookie` | the parameters the operation declares |
|
|
101
|
+
| `querystring` | the operation's `in: querystring` parameter (3.2), the whole query; see Details |
|
|
99
102
|
| `body`, `contentType` | the request body and which of the operation's media types it is |
|
|
100
103
|
| `parseAs` | `json`, `text`, `blob`, `arrayBuffer` or `stream`: read the response this way |
|
|
101
104
|
| `headers` | headers for this call |
|
|
@@ -104,7 +107,7 @@ const events = await api.get("/events", { parseAs: "stream" }); // events.data:
|
|
|
104
107
|
|
|
105
108
|
### Result
|
|
106
109
|
|
|
107
|
-
`{ status, ok, data, response }`, a union over the statuses the operation documents. `ResultOf<paths, "get", "/users/{id}">` is its type for `api.get("/users/{id}", …)`, and `ResultOf<paths, "get", "/users/{id}", "text">` with `parseAs: "text"`. `Result<Operation, ParseAs, Method>` is the same by operation; without the method, a HEAD result keeps the declared body.
|
|
110
|
+
`{ status, ok, data, response }`, a union over the statuses the operation documents. `ResultOf<paths, "get", "/users/{id}">` is its type for `api.get("/users/{id}", …)`, `ResultOf<paths, "COPY", "/files/{name}">` for `api.request("COPY", "/files/{name}", …)`, and `ResultOf<paths, "get", "/users/{id}", "text">` with `parseAs: "text"`. `Result<Operation, ParseAs, Method>` is the same by operation; without the method, a HEAD result keeps the declared body.
|
|
108
111
|
|
|
109
112
|
- **`data`** is parsed by the response's content-type: JSON, text, or `Blob` for binary types. An empty body gives `undefined`. fetch gives HEAD responses and 204, 205 and 304 no body, so their `data` is typed `undefined` whatever the document declares. A status that declares `content` but sends none also gives `undefined`; check for it in `onData`.
|
|
110
113
|
- The content-type the server sends decides, not the document: content typed by a wildcard (`*/*`) is typed by its schema but read as whatever arrives, and a response without a content-type is text (`parseAs: "blob"` keeps its bytes).
|
|
@@ -114,6 +117,28 @@ const events = await api.get("/events", { parseAs: "stream" }); // events.data:
|
|
|
114
117
|
- **Undocumented statuses:** list them with `default` or a range (`4XX`, `5XX`) in the document and they are typed. A status outside the document is still returned, in the branch the types call unreachable. An operation that documents no responses gives `status: number`, `ok: boolean` and `data: unknown`.
|
|
115
118
|
- **Response headers** are typed in the declarations (`responses[200].headers`); read them from `res.response.headers`.
|
|
116
119
|
|
|
120
|
+
### Wrapping a call
|
|
121
|
+
|
|
122
|
+
`PathsOf<paths, "get">` (the path templates with that method), `ArgsOf<paths, "get", Path, ParseAs>` (the arguments after the path) and `ResultOf` type a function that wraps a call, with no assertion. TypeScript cannot infer `parseAs` through the spread, so the call names its type arguments:
|
|
123
|
+
|
|
124
|
+
```ts
|
|
125
|
+
import type { ArgsOf, ParseAs, PathsOf, ResultOf } from "kanagata/client";
|
|
126
|
+
|
|
127
|
+
async function get<
|
|
128
|
+
Path extends PathsOf<paths, "get">,
|
|
129
|
+
A extends ParseAs | undefined = undefined,
|
|
130
|
+
>(
|
|
131
|
+
path: Path,
|
|
132
|
+
...args: ArgsOf<paths, "get", Path, A>
|
|
133
|
+
): Promise<ResultOf<paths, "get", Path, A>> {
|
|
134
|
+
const res = await api.get<Path, A>(path, ...args);
|
|
135
|
+
log(path, res.status);
|
|
136
|
+
return res;
|
|
137
|
+
}
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
For `api.request`, the method takes the place of `"get"`: `ArgsOf<paths, "COPY", Path>`.
|
|
141
|
+
|
|
117
142
|
### Details
|
|
118
143
|
|
|
119
144
|
- **baseUrl:** a relative one resolves on every call as fetch resolves it: against the page's base URL, or the worker's location. Where there is neither (Node), it throws a TypeError. `""` is the origin of the page's base URL. Its own query is kept, before the call's. An operation that declares `servers` (or whose path item does) is served there, not by the document's servers, so its call names one of them as `baseUrl`; other operations take the config's and cannot be given one.
|
|
@@ -126,10 +151,11 @@ const events = await api.get("/events", { parseAs: "stream" }); // events.data:
|
|
|
126
151
|
- A URL-encoded or multipart value that is not a raw body must be an object; otherwise a TypeError. A `Blob` cannot be URL-encoded, in a body or a query; that is a TypeError too.
|
|
127
152
|
- Multipart fields: an array repeats the field, a `Blob` is a file, a `Date` its ISO string, another object JSON. Another multipart type (`multipart/mixed`, `multipart/related`) gets the same named parts under its own type.
|
|
128
153
|
- A raw body (string, `Blob`, `URLSearchParams`, …) is sent as it is for form media types too.
|
|
129
|
-
- **Parameters:** the delimiters `[`, `]` and `|` are percent-encoded, as OpenAPI requires (`filter%5Bname%5D=n`, `ids=1%7C2`). An object or array inside an array is JSON, in every `arrayFormat`. Path, header and cookie parameters take the same values: arrays `1,2`, objects `x,1,y,2`. Undefined and null are left out, and so is an empty array. A path parameter of `""`, `.` or `..`
|
|
130
|
-
-
|
|
154
|
+
- **Parameters:** the delimiters `[`, `]` and `|` are percent-encoded, as OpenAPI requires (`filter%5Bname%5D=n`, `ids=1%7C2`). An object or array inside an array is JSON, in every `arrayFormat`. Path, header and cookie parameters take the same values: arrays `1,2`, objects `x,1,y,2`. Undefined and null are left out, and so is an empty array. A missing path parameter, or one of `""`, `.` or `..` (the URL would reach another endpoint), throws `PathParameterError` before anything is sent; see Errors.
|
|
155
|
+
- **`querystring`** is the whole query, after any other: for `application/x-www-form-urlencoded` an object, encoded as `query` is (`foo=a%20%2B%20b&bar=true`); for any other media type the text that media type serializes to (`JSON.stringify(value)` for JSON), percent-encoded as one value (`%7B%22n%22%3A1%7D`), as OpenAPI 3.2's examples show.
|
|
156
|
+
- **Errors:** HTTP error statuses never throw; network failures are fetch's own errors. A path parameter the URL cannot carry throws `PathParameterError`, a `TypeError` with `parameter` (its name) and `value`, before `config.fetch` is called; a server passing on a client's value can answer 404 for it (`e instanceof PathParameterError`), apart from fetch's network errors, which are `TypeError`s too. A body that is not valid JSON where its content-type or `parseAs: "json"` says JSON (HTML sent as JSON) throws `ResponseBodyError`, which carries the response and the text. An error thrown by `config.headers`, `config.fetch` or `onData` rejects the call as it is. The client's own errors are named as their classes (`e.name` is `"PathParameterError"`, `"ResponseBodyError"`), so logs tell them apart.
|
|
131
157
|
- **`config.fetch`** receives the built `Request`; what it returns is read. A request body can be sent once, so a retrying wrapper sends a `request.clone()` taken before the first attempt.
|
|
132
|
-
- **`onData`'s `call`** has `method`, `path` (the template, `/users/{id}`), `status`, `parseAs`, `request` and `response`. Plug a zod or valibot schema in here; `data` stays typed by the OpenAPI schema.
|
|
158
|
+
- **`onData`'s `call`** has `method` (the function's name, `get`, or the method given to `request`, `COPY`), `path` (the template, `/users/{id}`), `status`, `parseAs`, `request` and `response`. Plug a zod or valibot schema in here; `data` stays typed by the OpenAPI schema.
|
|
133
159
|
|
|
134
160
|
### Owning the client
|
|
135
161
|
|
|
@@ -157,12 +183,13 @@ try {
|
|
|
157
183
|
}
|
|
158
184
|
```
|
|
159
185
|
|
|
160
|
-
`generate(src, source?)` returns `{ code, warnings }` and throws `GenerateError
|
|
186
|
+
`generate(src, source?)` returns `{ code, warnings }` and throws `GenerateError` (`e.name` is `"GenerateError"` for every `kind`). `source` is the document's absolute URL and `read(url)`, which returns the text of a file a `$ref` points to; without it, `$ref`s to other files are errors.
|
|
161
187
|
|
|
162
188
|
## Output
|
|
163
189
|
|
|
164
190
|
- Every schema in `components.schemas` is a named type (`export type User = { … }`), referenced by name. Names are PascalCase, with `_` before one that would start with a digit; a taken or reserved name gets a number (`User2`). `export interface schemas` maps each original name to its type.
|
|
165
|
-
- Operations are `paths[path][method]`, `webhooks[name][method]` (3.1; every key is a name, `x-` ones included), and `operations[operationId]`.
|
|
191
|
+
- Operations are `paths[path][method]`, `webhooks[name][method]` (3.1 and 3.2; every key is a name, `x-` ones included), and `operations[operationId]`. The methods are the Path Item's fields in OpenAPI's order (`get` … `trace`, then `query`), then the keys of `additionalOperations` (3.2) as written (`COPY`). A key that is a fixed field's method (`POST`), which OpenAPI forbids, or its name (`post`) is an error; methods are case-sensitive, so `Patch` is another method. The fields OpenAPI 3.2 adds (`$self`, `query`, `additionalOperations`, `in: querystring`, a `$ref` as a media type, `itemSchema`) are read in 3.2 documents only.
|
|
192
|
+
- An `in: querystring` parameter (3.2) is `parameters.querystring`, without its name, which is not sent: the schema of its media type for `application/x-www-form-urlencoded`, `string` (the serialized text) for any other.
|
|
166
193
|
- A schema with a `readOnly` / `writeOnly` property (on it or on a schema it references) gets a second type for requests, `UserInput`.
|
|
167
194
|
- `description` and `deprecated` become JSDoc.
|
|
168
195
|
- Header parameters named `Accept`, `Content-Type` or `Authorization`, and a response header `Content-Type`, are ignored, as OpenAPI requires.
|
|
@@ -171,8 +198,10 @@ try {
|
|
|
171
198
|
|
|
172
199
|
### `$ref`
|
|
173
200
|
|
|
174
|
-
- Resolved as JSON Schema 2020-12 does: JSON Pointers, `$anchor`s (`#node`), and the `$id`s the document declares, relative to the nearest `$id` (3.1).
|
|
175
|
-
-
|
|
201
|
+
- Resolved as JSON Schema 2020-12 does: JSON Pointers, `$anchor`s (`#node`), and the `$id`s the document declares, relative to the nearest `$id` (3.1 and 3.2).
|
|
202
|
+
- The document's `$self` (3.2), resolved against where it was read, is its base URI: relative `$ref`s in it resolve against `$self`, and a `$ref` to `$self` means the document (so does one to the URL it was read from). A `$self` that is not a URI reference is an error. With `$self: https://api.example.com/openapi.yaml`, `schemas/User.yaml` is `https://api.example.com/schemas/User.yaml`, which is not read (below).
|
|
203
|
+
- Parameters, request bodies, responses, headers, path items and media types (3.2) may be `$ref`s.
|
|
204
|
+
- Other files (`schemas/User.yaml`, `common.json#/Error`) resolve against the base URI where the `$ref` is: the file it is in, or the document's `$self`. Each is read once, JSON or YAML by its content, and known by where it is read: another file's `$self` is not read. URLs are not fetched.
|
|
176
205
|
- A schema in another file is a named type. A component that is only a `$ref` to it (with at most `title` and `description`) gives the name (`User: { $ref: schemas/User.yaml }`); otherwise it is named after the file (`Order.yaml` → `Order`) or the pointer's last token (`common.json#/Error` → `Error`), numbered when taken, and listed in `schemas`.
|
|
177
206
|
- A component that is only a `$ref` within the document names its target the same way; other targets within the document are expanded where they are used.
|
|
178
207
|
- A schema may refer to itself through an object, array or tuple (`next?: Node`). A cycle among `$ref`s expanded inline becomes `unknown`, with a warning.
|
|
@@ -188,7 +217,7 @@ Types follow what the schema accepts, not another generator's output.
|
|
|
188
217
|
| `const`, `enum` | literal types; objects and arrays become exact object and tuple types |
|
|
189
218
|
| `allOf`, `oneOf` / `anyOf`, sibling `type` / object keywords | all intersected: `A & B & (C \| D)` |
|
|
190
219
|
| `discriminator` | not read (it must not change what is accepted, OAS 3.0.4 / 3.1.1); members narrow where they fix the property (`const`, `enum`) |
|
|
191
|
-
| keywords next to `$ref` | intersected in 3.1; ignored in 3.0 (`readOnly` / `writeOnly` too) except `nullable` and `description`
|
|
220
|
+
| keywords next to `$ref` | intersected in 3.1 and 3.2; ignored in 3.0 (`readOnly` / `writeOnly` too) except `nullable` and `description` |
|
|
192
221
|
| `type: [...]`, `nullable: true` (3.0) | union, with `null` |
|
|
193
222
|
| `type` with `const` / `enum`, and these with each other | the values all allow: `type: string, enum: ["a", 1]` is `"a"`; a contradiction is `never` |
|
|
194
223
|
| `type: integer` | `number`; non-integer `enum` / `const` values are dropped |
|
|
@@ -212,6 +241,8 @@ Content by media type:
|
|
|
212
241
|
| forms (`application/x-www-form-urlencoded`, `multipart/*`) | request: its schema; response: `string` |
|
|
213
242
|
| any other (binary), not a wildcard | `Blob` |
|
|
214
243
|
|
|
244
|
+
A sequential media type's `itemSchema` (3.2) is checked like a schema but types nothing: the client reads the content whole, by the rules above (`application/jsonl` is `Blob`, `text/event-stream` `string`). Read it item by item with `parseAs: "stream"`.
|
|
245
|
+
|
|
215
246
|
### `nullable` (3.0)
|
|
216
247
|
|
|
217
248
|
`nullable: true` adds `null` even without `type` (`{ nullable: true, allOf: [{ $ref: … }] }`) and next to an `enum` that does not list `null`. OpenAPI 3.0.3 says neither takes effect, but documents use both to mean "this schema or null" (Stripe and GitHub among them) and their servers return `null`, so kanagata follows the intent.
|
|
@@ -220,7 +251,7 @@ Content by media type:
|
|
|
220
251
|
|
|
221
252
|
- Runtime validation (use `onData`), middleware (wrap `config.fetch`), per-operation functions, framework bindings, mocks.
|
|
222
253
|
- Per-parameter `style` / `explode` / `encoding`: a server parses every query and form the same way, so one `arrayFormat` / `objectFormat` per client (or per call) matches it.
|
|
223
|
-
- Fetching `$ref`s over the network; Swagger 2.0.
|
|
254
|
+
- Fetching `$ref`s over the network; finding another file by its `$self` (3.2), since files are read by where they are; Swagger 2.0.
|
|
224
255
|
- Pathological inputs: a schema that is directly itself (`A: { $ref: A }`), looping `$ref`s or YAML aliases, nesting thousands of levels deep, or exponential expansion may crash (exit code 3) or not finish.
|
|
225
256
|
|
|
226
257
|
## Development
|
package/dist/cli.js
CHANGED
|
@@ -7,7 +7,7 @@ import { GenerateError, generate } from "./index.js";
|
|
|
7
7
|
/** An I/O failure; the message says what went wrong without naming the file (`no such file or directory`). */
|
|
8
8
|
export class IoError extends Error {
|
|
9
9
|
}
|
|
10
|
-
const HELP = `kanagata - TypeScript types from OpenAPI 3.0 / 3.1 (JSON or YAML), and a typed fetch client
|
|
10
|
+
const HELP = `kanagata - TypeScript types from OpenAPI 3.0 / 3.1 / 3.2 (JSON or YAML), and a typed fetch client
|
|
11
11
|
|
|
12
12
|
Usage:
|
|
13
13
|
kanagata generate <openapi.json|yaml> [-o <out.d.ts>] [--check]
|
package/dist/client.d.ts
CHANGED
|
@@ -1,11 +1,23 @@
|
|
|
1
|
-
export type Method = "get" | "put" | "post" | "delete" | "options" | "head" | "patch" | "trace";
|
|
1
|
+
export type Method = "get" | "put" | "post" | "delete" | "options" | "head" | "patch" | "trace" | "query";
|
|
2
2
|
type HeadersInit = NonNullable<ConstructorParameters<typeof Headers>[0]>;
|
|
3
3
|
type Get<T, K> = K extends keyof T ? T[K] : never;
|
|
4
|
-
/**
|
|
5
|
-
type PathsOf<P, M extends
|
|
4
|
+
/** The path templates of P that have method M: `PathsOf<paths, "get">`. */
|
|
5
|
+
export type PathsOf<P, M extends string> = {
|
|
6
6
|
[K in keyof P]: M extends keyof P[K] ? K : never;
|
|
7
7
|
}[keyof P] & string;
|
|
8
|
-
type Op<P, Path, M extends
|
|
8
|
+
type Op<P, Path, M extends string> = Get<Get<P, Path>, M>;
|
|
9
|
+
/**
|
|
10
|
+
* The methods of P's path items beyond OpenAPI's fixed fields: the keys of their
|
|
11
|
+
* `additionalOperations` (OpenAPI 3.2), as written, which is how they are sent.
|
|
12
|
+
*/
|
|
13
|
+
type OtherMethod<P> = Exclude<{
|
|
14
|
+
[K in keyof P]: keyof P[K];
|
|
15
|
+
}[keyof P], Method> & string;
|
|
16
|
+
/**
|
|
17
|
+
* The methods fetch sends as written: not CONNECT, TRACE and TRACK, which it rejects, nor
|
|
18
|
+
* DELETE, GET, HEAD, OPTIONS, POST and PUT in another case, which it sends in upper case.
|
|
19
|
+
*/
|
|
20
|
+
type Sendable<M extends string> = M extends unknown ? Uppercase<M> extends "CONNECT" | "TRACE" | "TRACK" ? never : Uppercase<M> extends "DELETE" | "GET" | "HEAD" | "OPTIONS" | "POST" | "PUT" ? never : M : never;
|
|
9
21
|
/** Union of every media type in `content`; `undefined` without content. */
|
|
10
22
|
type Content<B> = B extends {
|
|
11
23
|
content: infer C;
|
|
@@ -114,8 +126,13 @@ type NeedsAll<O> = Get<(O extends unknown ? (n: {
|
|
|
114
126
|
type Init<N, A> = N & RequestOptions & {
|
|
115
127
|
parseAs?: A;
|
|
116
128
|
};
|
|
117
|
-
/**
|
|
118
|
-
|
|
129
|
+
/**
|
|
130
|
+
* The arguments after the path of `client[M](path, …)`: the options, optional when nothing
|
|
131
|
+
* in them is required. With `PathsOf` and `ResultOf`, it types a function that wraps a call:
|
|
132
|
+
* `(path: Path, ...args: ArgsOf<paths, "get", Path, A>) => api.get<Path, A>(path, ...args)`;
|
|
133
|
+
* TypeScript cannot infer A through the spread, so the call names it.
|
|
134
|
+
*/
|
|
135
|
+
export type ArgsOf<P, M extends string, Path extends PathsOf<P, M>, A extends ParseAs | undefined = undefined> = Empty extends NeedsAll<Op<P, Path, M>> ? [init?: Init<NeedsAll<Op<P, Path, M>>, A>] : [init: Init<NeedsAll<Op<P, Path, M>>, A>];
|
|
119
136
|
/** "2XX" and default have no single status. */
|
|
120
137
|
type Status<S> = S extends number ? S : number;
|
|
121
138
|
/** Whether a status key is a success: `200`…`299` or `"2XX"`. */
|
|
@@ -133,7 +150,7 @@ type Undocumented = {
|
|
|
133
150
|
content: Record<string, unknown>;
|
|
134
151
|
};
|
|
135
152
|
/** Discriminated union over the documented statuses. */
|
|
136
|
-
export type Result<O, A extends ParseAs | undefined = undefined, M extends
|
|
153
|
+
export type Result<O, A extends ParseAs | undefined = undefined, M extends string = Method> = O extends {
|
|
137
154
|
responses: infer R;
|
|
138
155
|
} ? [keyof R] extends [never] ? {
|
|
139
156
|
status: number;
|
|
@@ -153,7 +170,7 @@ export type Result<O, A extends ParseAs | undefined = undefined, M extends Metho
|
|
|
153
170
|
* `ResultOf<paths, "get", "/users/{id}">`. `Result` of the path's operation, with the
|
|
154
171
|
* method given once (so HEAD has no body, as in the call).
|
|
155
172
|
*/
|
|
156
|
-
export type ResultOf<P, M extends
|
|
173
|
+
export type ResultOf<P, M extends string, Path extends PathsOf<P, M>, A extends ParseAs | undefined = undefined> = Result<Op<P, Path, M>, A, M>;
|
|
157
174
|
type MaybePromise<T> = T | Promise<T>;
|
|
158
175
|
export interface ClientConfig extends FetchOptions {
|
|
159
176
|
/** Absolute, or relative to the page (`/api`) as fetch resolves it, on every call. */
|
|
@@ -180,19 +197,29 @@ export interface ClientConfig extends FetchOptions {
|
|
|
180
197
|
*/
|
|
181
198
|
onData?: (data: unknown, call: DataCall) => MaybePromise<unknown>;
|
|
182
199
|
}
|
|
183
|
-
/**
|
|
200
|
+
/**
|
|
201
|
+
* Which call a body answers. `method` is the client function's name (`get`), or the
|
|
202
|
+
* method given to `request` (`COPY`); `path` is the template as written, such as `/users/{id}`.
|
|
203
|
+
*/
|
|
184
204
|
export interface DataCall {
|
|
185
|
-
method:
|
|
205
|
+
method: string;
|
|
186
206
|
path: string;
|
|
187
207
|
status: number;
|
|
188
208
|
parseAs: ParseAs | undefined;
|
|
189
209
|
request: Request;
|
|
190
210
|
response: Response;
|
|
191
211
|
}
|
|
192
|
-
type Call<P, M extends Method> = <Path extends PathsOf<P, M>, A extends ParseAs | undefined = undefined>(path: Path, ...args:
|
|
193
|
-
/** A
|
|
212
|
+
type Call<P, M extends Method> = <Path extends PathsOf<P, M>, A extends ParseAs | undefined = undefined>(path: Path, ...args: ArgsOf<P, M, Path, A>) => Promise<ResultOf<P, M, Path, A>>;
|
|
213
|
+
/** A call by a method of `additionalOperations`, named first: `request("COPY", path, init)`. */
|
|
214
|
+
type OtherCall<P> = <M extends Sendable<OtherMethod<P>>, Path extends PathsOf<P, M>, A extends ParseAs | undefined = undefined>(method: M, path: Path, ...args: ArgsOf<P, M, Path, A>) => Promise<ResultOf<P, M, Path, A>>;
|
|
215
|
+
/**
|
|
216
|
+
* A function per method fetch sends: every fixed one but TRACE, which fetch rejects, and
|
|
217
|
+
* `request` for the methods of `additionalOperations`.
|
|
218
|
+
*/
|
|
194
219
|
export type Client<P> = {
|
|
195
220
|
[M in Exclude<Method, "trace">]: Call<P, M>;
|
|
221
|
+
} & {
|
|
222
|
+
request: OtherCall<P>;
|
|
196
223
|
};
|
|
197
224
|
/** The HTTP methods of a Path Item, in OpenAPI's order. The generator reads them from here too. */
|
|
198
225
|
export declare const METHODS: readonly Method[];
|
|
@@ -202,8 +229,20 @@ export declare const METHODS: readonly Method[];
|
|
|
202
229
|
* documented statuses. HTTP error statuses do not throw.
|
|
203
230
|
*/
|
|
204
231
|
export declare function createClient<P>(config: ClientConfig): Client<P>;
|
|
232
|
+
/**
|
|
233
|
+
* A path parameter the URL cannot carry: missing, or one that would change the path (`""`,
|
|
234
|
+
* `.`, `..`). Thrown before anything is sent; a TypeError, which fetch's network errors are too.
|
|
235
|
+
* `parameter` is its name in the path template (`id` in `/users/{id}`), `value` what was given.
|
|
236
|
+
*/
|
|
237
|
+
export declare class PathParameterError extends TypeError {
|
|
238
|
+
readonly name = "PathParameterError";
|
|
239
|
+
readonly parameter: string;
|
|
240
|
+
readonly value: unknown;
|
|
241
|
+
constructor(message: string, parameter: string, value: unknown);
|
|
242
|
+
}
|
|
205
243
|
/** A body that is not valid JSON where its content-type (or parseAs) says JSON, such as an HTML error page. */
|
|
206
244
|
export declare class ResponseBodyError extends Error {
|
|
245
|
+
readonly name = "ResponseBodyError";
|
|
207
246
|
readonly response: Response;
|
|
208
247
|
readonly text: string;
|
|
209
248
|
constructor(response: Response, text: string, cause: unknown);
|
package/dist/client.js
CHANGED
|
@@ -9,6 +9,7 @@ const OWN_KEYS = new Set([
|
|
|
9
9
|
"onData",
|
|
10
10
|
"path",
|
|
11
11
|
"query",
|
|
12
|
+
"querystring",
|
|
12
13
|
"header",
|
|
13
14
|
"cookie",
|
|
14
15
|
"body",
|
|
@@ -30,6 +31,7 @@ export const METHODS = [
|
|
|
30
31
|
"head",
|
|
31
32
|
"patch",
|
|
32
33
|
"trace",
|
|
34
|
+
"query",
|
|
33
35
|
];
|
|
34
36
|
/**
|
|
35
37
|
* The base URL of a call. A relative one (`/api`) resolves as fetch resolves a relative URL:
|
|
@@ -64,7 +66,11 @@ export function createClient(config) {
|
|
|
64
66
|
array: init.arrayFormat ?? config.arrayFormat ?? "repeat",
|
|
65
67
|
object: init.objectFormat ?? config.objectFormat ?? "deepObject",
|
|
66
68
|
};
|
|
67
|
-
const query = [
|
|
69
|
+
const query = [
|
|
70
|
+
base.search.slice(1),
|
|
71
|
+
urlEncode(init.query ?? {}, formats),
|
|
72
|
+
queryString(init.querystring, formats),
|
|
73
|
+
]
|
|
68
74
|
.filter((q) => q !== "")
|
|
69
75
|
.join("&");
|
|
70
76
|
const url = `${base.origin}${base.pathname.replace(/\/+$/, "")}${fillPath(path, init.path)}${query === "" ? "" : `?${query}`}`;
|
|
@@ -88,7 +94,10 @@ export function createClient(config) {
|
|
|
88
94
|
const requestInit = {
|
|
89
95
|
...fetchOptions(config),
|
|
90
96
|
...fetchOptions(init),
|
|
91
|
-
method
|
|
97
|
+
// A method of additionalOperations is sent as written; the fixed ones in upper case.
|
|
98
|
+
method: METHODS.includes(method)
|
|
99
|
+
? method.toUpperCase()
|
|
100
|
+
: method,
|
|
92
101
|
headers,
|
|
93
102
|
};
|
|
94
103
|
if (init.body !== undefined) {
|
|
@@ -117,8 +126,20 @@ export function createClient(config) {
|
|
|
117
126
|
if (method !== "trace")
|
|
118
127
|
client[method] = (path, init) => send(method, path, init);
|
|
119
128
|
}
|
|
129
|
+
client.request = send;
|
|
120
130
|
return client;
|
|
121
131
|
}
|
|
132
|
+
/**
|
|
133
|
+
* A querystring parameter (OpenAPI 3.2), the whole query: an object is URL-encoded as
|
|
134
|
+
* a query is; a string, the text of another media type, is percent-encoded as one value.
|
|
135
|
+
*/
|
|
136
|
+
function queryString(value, formats) {
|
|
137
|
+
if (value == null)
|
|
138
|
+
return "";
|
|
139
|
+
if (typeof value === "string")
|
|
140
|
+
return encodeURIComponent(value);
|
|
141
|
+
return urlEncode(value, formats);
|
|
142
|
+
}
|
|
122
143
|
/**
|
|
123
144
|
* Encodes a body by its contentType and sets content-type for it, unless the call's
|
|
124
145
|
* headers did: a value is JSON without a contentType, a form for a form media type; a
|
|
@@ -190,16 +211,31 @@ function simple(value) {
|
|
|
190
211
|
: [value];
|
|
191
212
|
return parts.map(scalar);
|
|
192
213
|
}
|
|
214
|
+
/**
|
|
215
|
+
* A path parameter the URL cannot carry: missing, or one that would change the path (`""`,
|
|
216
|
+
* `.`, `..`). Thrown before anything is sent; a TypeError, which fetch's network errors are too.
|
|
217
|
+
* `parameter` is its name in the path template (`id` in `/users/{id}`), `value` what was given.
|
|
218
|
+
*/
|
|
219
|
+
export class PathParameterError extends TypeError {
|
|
220
|
+
name = "PathParameterError";
|
|
221
|
+
parameter;
|
|
222
|
+
value;
|
|
223
|
+
constructor(message, parameter, value) {
|
|
224
|
+
super(message);
|
|
225
|
+
this.parameter = parameter;
|
|
226
|
+
this.value = value;
|
|
227
|
+
}
|
|
228
|
+
}
|
|
193
229
|
/** Path parameters in the simple style, each part encoded. */
|
|
194
230
|
function fillPath(path, params = {}) {
|
|
195
231
|
return path.replace(/\{([^}]+)\}/g, (_, name) => {
|
|
196
232
|
const value = params[name];
|
|
197
233
|
if (value == null)
|
|
198
|
-
throw new
|
|
234
|
+
throw new PathParameterError(`missing path parameter: ${name}`, name, value);
|
|
199
235
|
const segment = simple(value).map(encodeURIComponent).join(",");
|
|
200
236
|
// URLs resolve `.` and `..` segments, so these would reach another endpoint.
|
|
201
237
|
if (segment === "" || segment === "." || segment === "..")
|
|
202
|
-
throw new
|
|
238
|
+
throw new PathParameterError(`path parameter ${name} would change the path: ${JSON.stringify(value)}`, name, value);
|
|
203
239
|
return segment;
|
|
204
240
|
});
|
|
205
241
|
}
|
|
@@ -343,6 +379,7 @@ async function readData(response, parseAs) {
|
|
|
343
379
|
}
|
|
344
380
|
/** A body that is not valid JSON where its content-type (or parseAs) says JSON, such as an HTML error page. */
|
|
345
381
|
export class ResponseBodyError extends Error {
|
|
382
|
+
name = "ResponseBodyError";
|
|
346
383
|
response;
|
|
347
384
|
text;
|
|
348
385
|
constructor(response, text, cause) {
|
package/dist/error.d.ts
CHANGED
|
@@ -6,6 +6,7 @@ import type { Diag } from "./pointer.ts";
|
|
|
6
6
|
* `location: message`, where the location is `line:col` or a JSON Pointer.
|
|
7
7
|
*/
|
|
8
8
|
export declare class GenerateError extends Error {
|
|
9
|
+
readonly name = "GenerateError";
|
|
9
10
|
readonly kind: "json" | "yaml" | "input";
|
|
10
11
|
/** The JSON Pointer and message, for `input` errors. */
|
|
11
12
|
readonly diag?: Diag;
|
package/dist/error.js
CHANGED
|
@@ -6,6 +6,8 @@
|
|
|
6
6
|
* `location: message`, where the location is `line:col` or a JSON Pointer.
|
|
7
7
|
*/
|
|
8
8
|
export class GenerateError extends Error {
|
|
9
|
+
// Also the name of the internal subclasses, which are GenerateErrors to the caller.
|
|
10
|
+
name = "GenerateError";
|
|
9
11
|
kind;
|
|
10
12
|
/** The JSON Pointer and message, for `input` errors. */
|
|
11
13
|
diag;
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// Generate TypeScript declarations from OpenAPI 3.0 / 3.1 (JSON or YAML).
|
|
1
|
+
// Generate TypeScript declarations from OpenAPI 3.0 / 3.1 / 3.2 (JSON or YAML).
|
|
2
2
|
import { render } from "./emit.js";
|
|
3
3
|
import { GenerateError } from "./error.js";
|
|
4
4
|
import { inputNames, typeNames } from "./ident.js";
|
|
@@ -28,7 +28,9 @@ export function generate(src, source) {
|
|
|
28
28
|
throw new DiagError("#/components/schemas", "schemas must be an object");
|
|
29
29
|
}
|
|
30
30
|
const schemas = s?.entries ?? [];
|
|
31
|
-
const cx = new Ctx(root, new Set(schemas.map(([k]) => k)),
|
|
31
|
+
const cx = new Ctx(root, new Set(schemas.map(([k]) => k)),
|
|
32
|
+
// 3.1 and 3.2 Schema Objects are JSON Schema 2020-12.
|
|
33
|
+
!root.get("openapi").startsWith("3.0."), source && {
|
|
32
34
|
url: source.url,
|
|
33
35
|
load: (url) => loadText(cx, url, source.read(url)),
|
|
34
36
|
});
|
|
@@ -149,9 +151,9 @@ function differingViews(components) {
|
|
|
149
151
|
function checkVersion(root) {
|
|
150
152
|
const v = root.get("openapi");
|
|
151
153
|
if (typeof v === "string") {
|
|
152
|
-
if (v.startsWith("3.0.") || v.startsWith("3.1."))
|
|
154
|
+
if (v.startsWith("3.0.") || v.startsWith("3.1.") || v.startsWith("3.2."))
|
|
153
155
|
return;
|
|
154
|
-
throw new DiagError("#/openapi", `unsupported OpenAPI version ${JSON.stringify(v)} (3.0.x or 3.
|
|
156
|
+
throw new DiagError("#/openapi", `unsupported OpenAPI version ${JSON.stringify(v)} (3.0.x, 3.1.x or 3.2.x required)`);
|
|
155
157
|
}
|
|
156
158
|
if (v !== undefined)
|
|
157
159
|
throw new DiagError("#/openapi", "openapi must be a string");
|
package/dist/operation.d.ts
CHANGED
|
@@ -3,7 +3,7 @@ import { type Ctx } from "./pointer.ts";
|
|
|
3
3
|
import { type Prop } from "./ty.ts";
|
|
4
4
|
export interface Paths {
|
|
5
5
|
paths: Prop[];
|
|
6
|
-
/** Present only when the document has `webhooks` (3.1). */
|
|
6
|
+
/** Present only when the document has `webhooks` (3.1 and later). */
|
|
7
7
|
webhooks?: Prop[];
|
|
8
8
|
operations: Prop[];
|
|
9
9
|
}
|
package/dist/operation.js
CHANGED
|
@@ -4,7 +4,7 @@ import { JsonObject } from "./json.js";
|
|
|
4
4
|
import { child, DiagError } from "./pointer.js";
|
|
5
5
|
import { doc, schema } from "./schema.js";
|
|
6
6
|
import { BLOB, lit, object, opRef, prop, STRING, tuple, UNKNOWN, } from "./ty.js";
|
|
7
|
-
const LOCATIONS = ["path", "query", "header", "cookie"];
|
|
7
|
+
const LOCATIONS = ["path", "query", "querystring", "header", "cookie"];
|
|
8
8
|
/** Header parameters OpenAPI says to ignore, in lower case. */
|
|
9
9
|
const RESERVED_HEADERS = ["accept", "content-type", "authorization"];
|
|
10
10
|
/** A property with optional documentation. */
|
|
@@ -39,11 +39,7 @@ function pathItems(cx, root, key, operations) {
|
|
|
39
39
|
const methods = cx.derefIn(rawItem, itemAt, (value) => {
|
|
40
40
|
const item = value;
|
|
41
41
|
const methods = [];
|
|
42
|
-
for (const method of
|
|
43
|
-
const op = item.get(method);
|
|
44
|
-
if (op === undefined)
|
|
45
|
-
continue;
|
|
46
|
-
const opAt = child(itemAt, method);
|
|
42
|
+
for (const [method, op, opAt] of itemOperations(cx, item, itemAt)) {
|
|
47
43
|
// A webhook is called by the API: it sends the request and reads the response.
|
|
48
44
|
const sent = key === "webhooks" ? "read" : "write";
|
|
49
45
|
// fetch cannot send a body with GET or HEAD (OpenAPI 3.0 has consumers ignore
|
|
@@ -66,6 +62,36 @@ function pathItems(cx, root, key, operations) {
|
|
|
66
62
|
}
|
|
67
63
|
return out;
|
|
68
64
|
}
|
|
65
|
+
/**
|
|
66
|
+
* A Path Item's operations, keyed by method: its fixed fields in OpenAPI's order, then its
|
|
67
|
+
* `additionalOperations`, whose keys are methods as they are sent (`COPY`). `query` and
|
|
68
|
+
* `additionalOperations` are OpenAPI 3.2 fields.
|
|
69
|
+
*/
|
|
70
|
+
function itemOperations(cx, item, itemAt) {
|
|
71
|
+
const out = [];
|
|
72
|
+
for (const method of METHODS) {
|
|
73
|
+
if (method === "query" && !cx.v32)
|
|
74
|
+
continue;
|
|
75
|
+
const op = item.get(method);
|
|
76
|
+
if (op !== undefined)
|
|
77
|
+
out.push([method, op, child(itemAt, method)]);
|
|
78
|
+
}
|
|
79
|
+
const more = cx.v32
|
|
80
|
+
? item.get("additionalOperations")
|
|
81
|
+
: undefined;
|
|
82
|
+
const moreAt = child(itemAt, "additionalOperations");
|
|
83
|
+
for (const [method, op] of more?.entries ?? []) {
|
|
84
|
+
const at = child(moreAt, method);
|
|
85
|
+
// OpenAPI forbids the method a fixed field sends (`POST` for `post`); the field's own
|
|
86
|
+
// name would be that field in the declarations. Methods are case-sensitive, so
|
|
87
|
+
// `Patch` is another method.
|
|
88
|
+
const field = METHODS.find((m) => method === m || method === m.toUpperCase());
|
|
89
|
+
if (field !== undefined)
|
|
90
|
+
throw new DiagError(at, `${method} is the Path Item's ${field} field, so additionalOperations must not have it`);
|
|
91
|
+
out.push([method, op, at]);
|
|
92
|
+
}
|
|
93
|
+
return out;
|
|
94
|
+
}
|
|
69
95
|
function operation(cx, { item, itemAt, op: o, at, sent, body: hasBody }) {
|
|
70
96
|
const fields = [];
|
|
71
97
|
const received = sent === "write" ? "read" : "write";
|
|
@@ -80,13 +106,21 @@ function operation(cx, { item, itemAt, op: o, at, sent, body: hasBody }) {
|
|
|
80
106
|
collectParams(cx, params, o, at);
|
|
81
107
|
const groups = [];
|
|
82
108
|
for (const loc of LOCATIONS) {
|
|
109
|
+
// `in: querystring` is OpenAPI 3.2.
|
|
110
|
+
if (loc === "querystring" && !cx.v32)
|
|
111
|
+
continue;
|
|
83
112
|
const props = [];
|
|
84
113
|
for (const [p, pAt, base] of params) {
|
|
85
114
|
if (p.str("in") !== loc)
|
|
86
115
|
continue;
|
|
87
116
|
const optional = loc !== "path" && p.get("required") !== true;
|
|
88
|
-
const
|
|
89
|
-
|
|
117
|
+
const whole = loc === "querystring";
|
|
118
|
+
const ty = cx.inMode(sent, () => cx.withBase(base, () => paramType(cx, p, pAt, whole)));
|
|
119
|
+
// The whole query string (3.2) is one value; its name is not sent.
|
|
120
|
+
if (whole)
|
|
121
|
+
groups.push(documented(loc, ty, optional, doc(p)));
|
|
122
|
+
else
|
|
123
|
+
props.push(documented(p.str("name"), ty, optional, doc(p)));
|
|
90
124
|
}
|
|
91
125
|
if (props.length === 0)
|
|
92
126
|
continue;
|
|
@@ -159,8 +193,10 @@ function collectParam(cx, out, value, pAt) {
|
|
|
159
193
|
const loc = p.str("in");
|
|
160
194
|
if (loc === "header" && RESERVED_HEADERS.includes(asciiLower(name)))
|
|
161
195
|
return;
|
|
162
|
-
// Header names are case-insensitive, so `X-Id` replaces `x-id
|
|
163
|
-
|
|
196
|
+
// Header names are case-insensitive, so `X-Id` replaces `x-id`; an operation has one
|
|
197
|
+
// querystring, whose name is not sent.
|
|
198
|
+
const same = (n) => loc === "querystring" ||
|
|
199
|
+
(loc === "header" ? asciiLower(n) === asciiLower(name) : n === name);
|
|
164
200
|
// Collected parameters all have a name.
|
|
165
201
|
const slot = out.findIndex(([q]) => q.str("in") === loc && same(q.str("name")));
|
|
166
202
|
// Its schema is converted later, against the document the parameter is in.
|
|
@@ -174,13 +210,35 @@ function collectParam(cx, out, value, pAt) {
|
|
|
174
210
|
function asciiLower(s) {
|
|
175
211
|
return s.replace(/[A-Z]/g, (c) => c.toLowerCase());
|
|
176
212
|
}
|
|
177
|
-
/**
|
|
178
|
-
|
|
213
|
+
/**
|
|
214
|
+
* The type of a parameter or header: its `schema`, or the schema of its one `content`
|
|
215
|
+
* media type. A querystring (`whole`) is that schema for application/x-www-form-urlencoded,
|
|
216
|
+
* which the client URL-encodes; for any other media type it is the serialized text, a string.
|
|
217
|
+
*/
|
|
218
|
+
function paramType(cx, p, at, whole = false) {
|
|
179
219
|
const s = p.get("schema");
|
|
180
220
|
if (s !== undefined)
|
|
181
221
|
return schema(cx, s, child(at, "schema"));
|
|
182
|
-
const [[mt,
|
|
183
|
-
|
|
222
|
+
const [[mt, raw]] = p.get("content").entries;
|
|
223
|
+
const mAt = child(child(at, "content"), mt);
|
|
224
|
+
return mediaType(cx, raw, mAt, (m) => {
|
|
225
|
+
const ty = schema(cx, m.get("schema"), child(mAt, "schema"));
|
|
226
|
+
const urlEncoded = essence(mt) === "application/x-www-form-urlencoded";
|
|
227
|
+
return whole && !urlEncoded ? STRING : ty;
|
|
228
|
+
});
|
|
229
|
+
}
|
|
230
|
+
/** The media type without parameters, in lower case, as the client compares it. */
|
|
231
|
+
function essence(mt) {
|
|
232
|
+
return mt.split(";")[0].trim().toLowerCase();
|
|
233
|
+
}
|
|
234
|
+
/**
|
|
235
|
+
* Runs `f` on a Media Type Object, which may be a `$ref` in OpenAPI 3.2
|
|
236
|
+
* (`components.mediaTypes`); before 3.2, `$ref` is no field of it.
|
|
237
|
+
*/
|
|
238
|
+
function mediaType(cx, raw, at, f) {
|
|
239
|
+
if (!cx.v32)
|
|
240
|
+
return f(raw);
|
|
241
|
+
return cx.derefIn(raw, at, (m) => f(m));
|
|
184
242
|
}
|
|
185
243
|
/** `{ Name: T }` for a response's `headers`; Content-Type is ignored, as OpenAPI requires. */
|
|
186
244
|
function headers(cx, response, at) {
|
|
@@ -204,18 +262,24 @@ function headers(cx, response, at) {
|
|
|
204
262
|
* `{ "<media type>": T }` for a non-empty `content`, keeping every media type.
|
|
205
263
|
* A binary media type is `Blob` and a text one `string` whatever its schema says, as is
|
|
206
264
|
* a form in a response (read view): that is what the client reads and sends. The schema
|
|
207
|
-
* is still converted so its errors are reported.
|
|
265
|
+
* is still converted so its errors are reported, and so is `itemSchema` (3.2): the client
|
|
266
|
+
* reads a sequential media type (`application/jsonl`, `text/event-stream`) whole, as these
|
|
267
|
+
* rules say, not item by item.
|
|
208
268
|
*/
|
|
209
269
|
function content(cx, owner, at) {
|
|
210
270
|
const media = owner.get("content");
|
|
211
271
|
if (media === undefined || media.entries.length === 0)
|
|
212
272
|
return undefined;
|
|
213
273
|
const base = child(at, "content");
|
|
214
|
-
return object(media.entries.map(([mt,
|
|
215
|
-
const
|
|
216
|
-
const ty =
|
|
217
|
-
?
|
|
218
|
-
|
|
274
|
+
return object(media.entries.map(([mt, raw]) => {
|
|
275
|
+
const mAt = child(base, mt);
|
|
276
|
+
const ty = mediaType(cx, raw, mAt, (m) => {
|
|
277
|
+
const items = cx.v32 ? m.get("itemSchema") : undefined;
|
|
278
|
+
if (items !== undefined)
|
|
279
|
+
schema(cx, items, child(mAt, "itemSchema"));
|
|
280
|
+
const s = m.get("schema");
|
|
281
|
+
return s === undefined ? UNKNOWN : schema(cx, s, child(mAt, "schema"));
|
|
282
|
+
});
|
|
219
283
|
const text = isTextMedia(mt) || (cx.mode === "read" && isFormMedia(mt));
|
|
220
284
|
return prop(mt, isBinaryMedia(mt) ? BLOB : text ? STRING : ty);
|
|
221
285
|
}));
|
package/dist/pointer.d.ts
CHANGED
|
@@ -38,6 +38,10 @@ export declare class Ctx {
|
|
|
38
38
|
readonly root: Value;
|
|
39
39
|
/** The document's URL: from its Location, or a placeholder when it has none. */
|
|
40
40
|
readonly documentUrl: string;
|
|
41
|
+
/** The document's base URI: its `$self` (3.2), resolved against its URL, or the URL. */
|
|
42
|
+
readonly documentBase: string;
|
|
43
|
+
/** Whether the document is OpenAPI 3.2, whose fields (`$self`, `query`, …) are read. */
|
|
44
|
+
readonly v32: boolean;
|
|
41
45
|
/** Keys of `#/components/schemas`. */
|
|
42
46
|
readonly schemas: ReadonlySet<string>;
|
|
43
47
|
/**
|
package/dist/pointer.js
CHANGED
|
@@ -74,6 +74,10 @@ export class Ctx {
|
|
|
74
74
|
root;
|
|
75
75
|
/** The document's URL: from its Location, or a placeholder when it has none. */
|
|
76
76
|
documentUrl;
|
|
77
|
+
/** The document's base URI: its `$self` (3.2), resolved against its URL, or the URL. */
|
|
78
|
+
documentBase;
|
|
79
|
+
/** Whether the document is OpenAPI 3.2, whose fields (`$self`, `query`, …) are read. */
|
|
80
|
+
v32;
|
|
77
81
|
#load;
|
|
78
82
|
/** `$ref`s being expanded inline, for cycle detection. */
|
|
79
83
|
#stack = [];
|
|
@@ -128,7 +132,16 @@ export class Ctx {
|
|
|
128
132
|
? DOCUMENT
|
|
129
133
|
: withoutFragment(new URL(location.url));
|
|
130
134
|
this.#load = location?.load;
|
|
131
|
-
this.
|
|
135
|
+
this.v32 = str(root, "openapi")?.startsWith("3.2.") === true;
|
|
136
|
+
const self = this.v32 ? get(root, "$self") : undefined;
|
|
137
|
+
if (self !== undefined &&
|
|
138
|
+
(typeof self !== "string" || !URL.canParse(self, this.documentUrl)))
|
|
139
|
+
throw new DiagError("#/$self", "$self must be a URI reference");
|
|
140
|
+
this.documentBase =
|
|
141
|
+
self === undefined
|
|
142
|
+
? this.documentUrl
|
|
143
|
+
: withoutFragment(new URL(self, this.documentUrl));
|
|
144
|
+
this.base = this.documentBase;
|
|
132
145
|
}
|
|
133
146
|
warn(at, msg) {
|
|
134
147
|
const key = `${at}\n${msg}`;
|
|
@@ -173,7 +186,7 @@ export class Ctx {
|
|
|
173
186
|
base;
|
|
174
187
|
/** Whether `$ref`s resolve against the document itself (not another file, nor inside a schema with `$id`). */
|
|
175
188
|
get inDocument() {
|
|
176
|
-
return this.base === this.
|
|
189
|
+
return this.base === this.documentBase;
|
|
177
190
|
}
|
|
178
191
|
/**
|
|
179
192
|
* How a location is written in messages: a JSON Pointer in the document (`#/a`), a
|
|
@@ -181,7 +194,7 @@ export class Ctx {
|
|
|
181
194
|
*/
|
|
182
195
|
where(resource, fragment) {
|
|
183
196
|
const hash = fragment === undefined ? "" : `#${fragment}`;
|
|
184
|
-
if (resource === this.
|
|
197
|
+
if (resource === this.documentBase)
|
|
185
198
|
return hash;
|
|
186
199
|
const url = new URL(resource);
|
|
187
200
|
const doc = new URL(this.documentUrl);
|
|
@@ -218,10 +231,12 @@ export class Ctx {
|
|
|
218
231
|
*/
|
|
219
232
|
locate(r, at) {
|
|
220
233
|
const url = new URL(r, this.base);
|
|
221
|
-
const resource = withoutFragment(url);
|
|
222
234
|
const fragment = url.hash.slice(1);
|
|
235
|
+
// A reference by the URL the document was read from still means the document.
|
|
236
|
+
const named = withoutFragment(url);
|
|
237
|
+
const resource = named === this.documentUrl ? this.documentBase : named;
|
|
223
238
|
const index = this.#ids();
|
|
224
|
-
const doc = resource === this.
|
|
239
|
+
const doc = resource === this.documentBase
|
|
225
240
|
? this.root
|
|
226
241
|
: (index.ids.get(resource) ?? this.#read(resource, r, at));
|
|
227
242
|
const value = fragment === "" || fragment.startsWith("/")
|
|
@@ -236,7 +251,10 @@ export class Ctx {
|
|
|
236
251
|
where: this.where(resource, fragment),
|
|
237
252
|
};
|
|
238
253
|
}
|
|
239
|
-
/**
|
|
254
|
+
/**
|
|
255
|
+
* Loads another document, once, and indexes its `$id`s and `$anchor`s. It is known by
|
|
256
|
+
* the URL it is read from: kanagata reads files, so another document's `$self` is not read.
|
|
257
|
+
*/
|
|
240
258
|
#read(resource, r, at) {
|
|
241
259
|
if (this.#load === undefined)
|
|
242
260
|
throw new DiagError(at, `external $ref, but the document's location is unknown: ${r}`);
|
|
@@ -275,7 +293,7 @@ export class Ctx {
|
|
|
275
293
|
if (this.#index !== undefined)
|
|
276
294
|
return this.#index;
|
|
277
295
|
const index = { ids: new Map(), anchors: new Map() };
|
|
278
|
-
indexIds(index, this.root, this.
|
|
296
|
+
indexIds(index, this.root, this.documentBase);
|
|
279
297
|
this.#index = index;
|
|
280
298
|
return index;
|
|
281
299
|
}
|
|
@@ -309,7 +327,7 @@ export class Ctx {
|
|
|
309
327
|
!s.entries.every(([k]) => ALIAS_KEYS.has(k)))
|
|
310
328
|
continue;
|
|
311
329
|
// A target that does not resolve is reported where the component is converted.
|
|
312
|
-
const target = this.withBase(this.
|
|
330
|
+
const target = this.withBase(this.documentBase, () => this.tryLocate(r)?.value);
|
|
313
331
|
if (target !== undefined && !aliases.has(target))
|
|
314
332
|
aliases.set(target, key);
|
|
315
333
|
}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "kanagata",
|
|
3
|
-
"version": "0.1
|
|
4
|
-
"description": "TypeScript types from OpenAPI 3.0 / 3.1 (JSON or YAML), and a typed fetch client",
|
|
3
|
+
"version": "0.2.1",
|
|
4
|
+
"description": "TypeScript types from OpenAPI 3.0 / 3.1 / 3.2 (JSON or YAML), and a typed fetch client",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"openapi",
|
|
7
7
|
"typescript",
|
package/src/client.ts
CHANGED
|
@@ -8,7 +8,8 @@ export type Method =
|
|
|
8
8
|
| "options"
|
|
9
9
|
| "head"
|
|
10
10
|
| "patch"
|
|
11
|
-
| "trace"
|
|
11
|
+
| "trace"
|
|
12
|
+
| "query";
|
|
12
13
|
|
|
13
14
|
// Derived from fetch itself, so this file type-checks with Node's types as well as the DOM's.
|
|
14
15
|
type HeadersInit = NonNullable<ConstructorParameters<typeof Headers>[0]>;
|
|
@@ -16,13 +17,38 @@ type BodyInit = NonNullable<RequestInit["body"]>;
|
|
|
16
17
|
|
|
17
18
|
type Get<T, K> = K extends keyof T ? T[K] : never;
|
|
18
19
|
|
|
19
|
-
/**
|
|
20
|
-
type PathsOf<P, M extends
|
|
20
|
+
/** The path templates of P that have method M: `PathsOf<paths, "get">`. */
|
|
21
|
+
export type PathsOf<P, M extends string> = {
|
|
21
22
|
[K in keyof P]: M extends keyof P[K] ? K : never;
|
|
22
23
|
}[keyof P] &
|
|
23
24
|
string;
|
|
24
25
|
|
|
25
|
-
type Op<P, Path, M extends
|
|
26
|
+
type Op<P, Path, M extends string> = Get<Get<P, Path>, M>;
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* The methods of P's path items beyond OpenAPI's fixed fields: the keys of their
|
|
30
|
+
* `additionalOperations` (OpenAPI 3.2), as written, which is how they are sent.
|
|
31
|
+
*/
|
|
32
|
+
type OtherMethod<P> = Exclude<{ [K in keyof P]: keyof P[K] }[keyof P], Method> &
|
|
33
|
+
string;
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* The methods fetch sends as written: not CONNECT, TRACE and TRACK, which it rejects, nor
|
|
37
|
+
* DELETE, GET, HEAD, OPTIONS, POST and PUT in another case, which it sends in upper case.
|
|
38
|
+
*/
|
|
39
|
+
type Sendable<M extends string> = M extends unknown
|
|
40
|
+
? Uppercase<M> extends "CONNECT" | "TRACE" | "TRACK"
|
|
41
|
+
? never
|
|
42
|
+
: Uppercase<M> extends
|
|
43
|
+
| "DELETE"
|
|
44
|
+
| "GET"
|
|
45
|
+
| "HEAD"
|
|
46
|
+
| "OPTIONS"
|
|
47
|
+
| "POST"
|
|
48
|
+
| "PUT"
|
|
49
|
+
? never
|
|
50
|
+
: M
|
|
51
|
+
: never;
|
|
26
52
|
|
|
27
53
|
/** Union of every media type in `content`; `undefined` without content. */
|
|
28
54
|
type Content<B> = B extends { content: infer C } ? C[keyof C] : undefined;
|
|
@@ -159,8 +185,21 @@ type NeedsAll<O> = Get<
|
|
|
159
185
|
|
|
160
186
|
type Init<N, A> = N & RequestOptions & { parseAs?: A };
|
|
161
187
|
|
|
162
|
-
/**
|
|
163
|
-
|
|
188
|
+
/**
|
|
189
|
+
* The arguments after the path of `client[M](path, …)`: the options, optional when nothing
|
|
190
|
+
* in them is required. With `PathsOf` and `ResultOf`, it types a function that wraps a call:
|
|
191
|
+
* `(path: Path, ...args: ArgsOf<paths, "get", Path, A>) => api.get<Path, A>(path, ...args)`;
|
|
192
|
+
* TypeScript cannot infer A through the spread, so the call names it.
|
|
193
|
+
*/
|
|
194
|
+
export type ArgsOf<
|
|
195
|
+
P,
|
|
196
|
+
M extends string,
|
|
197
|
+
Path extends PathsOf<P, M>,
|
|
198
|
+
A extends ParseAs | undefined = undefined,
|
|
199
|
+
> =
|
|
200
|
+
Empty extends NeedsAll<Op<P, Path, M>>
|
|
201
|
+
? [init?: Init<NeedsAll<Op<P, Path, M>>, A>]
|
|
202
|
+
: [init: Init<NeedsAll<Op<P, Path, M>>, A>];
|
|
164
203
|
|
|
165
204
|
/** "2XX" and default have no single status. */
|
|
166
205
|
type Status<S> = S extends number ? S : number;
|
|
@@ -206,7 +245,7 @@ type Undocumented = { content: Record<string, unknown> };
|
|
|
206
245
|
export type Result<
|
|
207
246
|
O,
|
|
208
247
|
A extends ParseAs | undefined = undefined,
|
|
209
|
-
M extends
|
|
248
|
+
M extends string = Method,
|
|
210
249
|
> = O extends {
|
|
211
250
|
responses: infer R;
|
|
212
251
|
}
|
|
@@ -234,7 +273,7 @@ export type Result<
|
|
|
234
273
|
*/
|
|
235
274
|
export type ResultOf<
|
|
236
275
|
P,
|
|
237
|
-
M extends
|
|
276
|
+
M extends string,
|
|
238
277
|
Path extends PathsOf<P, M>,
|
|
239
278
|
A extends ParseAs | undefined = undefined,
|
|
240
279
|
> = Result<Op<P, Path, M>, A, M>;
|
|
@@ -267,9 +306,12 @@ export interface ClientConfig extends FetchOptions {
|
|
|
267
306
|
onData?: (data: unknown, call: DataCall) => MaybePromise<unknown>;
|
|
268
307
|
}
|
|
269
308
|
|
|
270
|
-
/**
|
|
309
|
+
/**
|
|
310
|
+
* Which call a body answers. `method` is the client function's name (`get`), or the
|
|
311
|
+
* method given to `request` (`COPY`); `path` is the template as written, such as `/users/{id}`.
|
|
312
|
+
*/
|
|
271
313
|
export interface DataCall {
|
|
272
|
-
method:
|
|
314
|
+
method: string;
|
|
273
315
|
path: string;
|
|
274
316
|
status: number;
|
|
275
317
|
parseAs: ParseAs | undefined;
|
|
@@ -282,16 +324,33 @@ type Call<P, M extends Method> = <
|
|
|
282
324
|
A extends ParseAs | undefined = undefined,
|
|
283
325
|
>(
|
|
284
326
|
path: Path,
|
|
285
|
-
...args:
|
|
286
|
-
) => Promise<
|
|
327
|
+
...args: ArgsOf<P, M, Path, A>
|
|
328
|
+
) => Promise<ResultOf<P, M, Path, A>>;
|
|
287
329
|
|
|
288
|
-
/** A
|
|
289
|
-
|
|
330
|
+
/** A call by a method of `additionalOperations`, named first: `request("COPY", path, init)`. */
|
|
331
|
+
type OtherCall<P> = <
|
|
332
|
+
M extends Sendable<OtherMethod<P>>,
|
|
333
|
+
Path extends PathsOf<P, M>,
|
|
334
|
+
A extends ParseAs | undefined = undefined,
|
|
335
|
+
>(
|
|
336
|
+
method: M,
|
|
337
|
+
path: Path,
|
|
338
|
+
...args: ArgsOf<P, M, Path, A>
|
|
339
|
+
) => Promise<ResultOf<P, M, Path, A>>;
|
|
340
|
+
|
|
341
|
+
/**
|
|
342
|
+
* A function per method fetch sends: every fixed one but TRACE, which fetch rejects, and
|
|
343
|
+
* `request` for the methods of `additionalOperations`.
|
|
344
|
+
*/
|
|
345
|
+
export type Client<P> = { [M in Exclude<Method, "trace">]: Call<P, M> } & {
|
|
346
|
+
request: OtherCall<P>;
|
|
347
|
+
};
|
|
290
348
|
|
|
291
349
|
interface AnyInit extends RequestOptions {
|
|
292
350
|
baseUrl?: string;
|
|
293
351
|
path?: Record<string, unknown>;
|
|
294
352
|
query?: Record<string, unknown>;
|
|
353
|
+
querystring?: unknown;
|
|
295
354
|
header?: Record<string, unknown>;
|
|
296
355
|
cookie?: Record<string, unknown>;
|
|
297
356
|
body?: unknown;
|
|
@@ -316,6 +375,7 @@ const OWN_KEYS = new Set([
|
|
|
316
375
|
"onData",
|
|
317
376
|
"path",
|
|
318
377
|
"query",
|
|
378
|
+
"querystring",
|
|
319
379
|
"header",
|
|
320
380
|
"cookie",
|
|
321
381
|
"body",
|
|
@@ -343,6 +403,7 @@ export const METHODS: readonly Method[] = [
|
|
|
343
403
|
"head",
|
|
344
404
|
"patch",
|
|
345
405
|
"trace",
|
|
406
|
+
"query",
|
|
346
407
|
];
|
|
347
408
|
|
|
348
409
|
/**
|
|
@@ -379,7 +440,7 @@ function resolveBase(baseUrl: string): URL {
|
|
|
379
440
|
*/
|
|
380
441
|
export function createClient<P>(config: ClientConfig): Client<P> {
|
|
381
442
|
async function send(
|
|
382
|
-
method:
|
|
443
|
+
method: string,
|
|
383
444
|
path: string,
|
|
384
445
|
init: AnyInit = {},
|
|
385
446
|
): Promise<AnyResult> {
|
|
@@ -389,7 +450,11 @@ export function createClient<P>(config: ClientConfig): Client<P> {
|
|
|
389
450
|
array: init.arrayFormat ?? config.arrayFormat ?? "repeat",
|
|
390
451
|
object: init.objectFormat ?? config.objectFormat ?? "deepObject",
|
|
391
452
|
};
|
|
392
|
-
const query = [
|
|
453
|
+
const query = [
|
|
454
|
+
base.search.slice(1),
|
|
455
|
+
urlEncode(init.query ?? {}, formats),
|
|
456
|
+
queryString(init.querystring, formats),
|
|
457
|
+
]
|
|
393
458
|
.filter((q) => q !== "")
|
|
394
459
|
.join("&");
|
|
395
460
|
const url = `${base.origin}${base.pathname.replace(/\/+$/, "")}${fillPath(path, init.path)}${query === "" ? "" : `?${query}`}`;
|
|
@@ -414,7 +479,10 @@ export function createClient<P>(config: ClientConfig): Client<P> {
|
|
|
414
479
|
const requestInit: RequestInit & { duplex?: "half" } = {
|
|
415
480
|
...fetchOptions(config),
|
|
416
481
|
...fetchOptions(init),
|
|
417
|
-
method
|
|
482
|
+
// A method of additionalOperations is sent as written; the fixed ones in upper case.
|
|
483
|
+
method: (METHODS as readonly string[]).includes(method)
|
|
484
|
+
? method.toUpperCase()
|
|
485
|
+
: method,
|
|
418
486
|
headers,
|
|
419
487
|
};
|
|
420
488
|
if (init.body !== undefined) {
|
|
@@ -446,14 +514,31 @@ export function createClient<P>(config: ClientConfig): Client<P> {
|
|
|
446
514
|
|
|
447
515
|
const client: Partial<
|
|
448
516
|
Record<Method, (path: string, init?: AnyInit) => Promise<AnyResult>>
|
|
449
|
-
>
|
|
517
|
+
> & {
|
|
518
|
+
request?: (
|
|
519
|
+
method: string,
|
|
520
|
+
path: string,
|
|
521
|
+
init?: AnyInit,
|
|
522
|
+
) => Promise<AnyResult>;
|
|
523
|
+
} = {};
|
|
450
524
|
for (const method of METHODS) {
|
|
451
525
|
if (method !== "trace")
|
|
452
526
|
client[method] = (path, init) => send(method, path, init);
|
|
453
527
|
}
|
|
528
|
+
client.request = send;
|
|
454
529
|
return client as unknown as Client<P>;
|
|
455
530
|
}
|
|
456
531
|
|
|
532
|
+
/**
|
|
533
|
+
* A querystring parameter (OpenAPI 3.2), the whole query: an object is URL-encoded as
|
|
534
|
+
* a query is; a string, the text of another media type, is percent-encoded as one value.
|
|
535
|
+
*/
|
|
536
|
+
function queryString(value: unknown, formats: Formats): string {
|
|
537
|
+
if (value == null) return "";
|
|
538
|
+
if (typeof value === "string") return encodeURIComponent(value);
|
|
539
|
+
return urlEncode(value as Record<string, unknown>, formats);
|
|
540
|
+
}
|
|
541
|
+
|
|
457
542
|
/**
|
|
458
543
|
* Encodes a body by its contentType and sets content-type for it, unless the call's
|
|
459
544
|
* headers did: a value is JSON without a contentType, a form for a form media type; a
|
|
@@ -534,16 +619,40 @@ function simple(value: unknown): string[] {
|
|
|
534
619
|
return parts.map(scalar);
|
|
535
620
|
}
|
|
536
621
|
|
|
622
|
+
/**
|
|
623
|
+
* A path parameter the URL cannot carry: missing, or one that would change the path (`""`,
|
|
624
|
+
* `.`, `..`). Thrown before anything is sent; a TypeError, which fetch's network errors are too.
|
|
625
|
+
* `parameter` is its name in the path template (`id` in `/users/{id}`), `value` what was given.
|
|
626
|
+
*/
|
|
627
|
+
export class PathParameterError extends TypeError {
|
|
628
|
+
override readonly name = "PathParameterError";
|
|
629
|
+
readonly parameter: string;
|
|
630
|
+
readonly value: unknown;
|
|
631
|
+
|
|
632
|
+
constructor(message: string, parameter: string, value: unknown) {
|
|
633
|
+
super(message);
|
|
634
|
+
this.parameter = parameter;
|
|
635
|
+
this.value = value;
|
|
636
|
+
}
|
|
637
|
+
}
|
|
638
|
+
|
|
537
639
|
/** Path parameters in the simple style, each part encoded. */
|
|
538
640
|
function fillPath(path: string, params: Record<string, unknown> = {}): string {
|
|
539
641
|
return path.replace(/\{([^}]+)\}/g, (_, name: string) => {
|
|
540
642
|
const value = params[name];
|
|
541
|
-
if (value == null)
|
|
643
|
+
if (value == null)
|
|
644
|
+
throw new PathParameterError(
|
|
645
|
+
`missing path parameter: ${name}`,
|
|
646
|
+
name,
|
|
647
|
+
value,
|
|
648
|
+
);
|
|
542
649
|
const segment = simple(value).map(encodeURIComponent).join(",");
|
|
543
650
|
// URLs resolve `.` and `..` segments, so these would reach another endpoint.
|
|
544
651
|
if (segment === "" || segment === "." || segment === "..")
|
|
545
|
-
throw new
|
|
652
|
+
throw new PathParameterError(
|
|
546
653
|
`path parameter ${name} would change the path: ${JSON.stringify(value)}`,
|
|
654
|
+
name,
|
|
655
|
+
value,
|
|
547
656
|
);
|
|
548
657
|
return segment;
|
|
549
658
|
});
|
|
@@ -709,6 +818,7 @@ async function readData(
|
|
|
709
818
|
|
|
710
819
|
/** A body that is not valid JSON where its content-type (or parseAs) says JSON, such as an HTML error page. */
|
|
711
820
|
export class ResponseBodyError extends Error {
|
|
821
|
+
override readonly name = "ResponseBodyError";
|
|
712
822
|
readonly response: Response;
|
|
713
823
|
readonly text: string;
|
|
714
824
|
|