kanagata 0.2.0 → 0.2.2
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 +34 -9
- package/dist/cli.js +15 -3
- package/dist/client.d.ts +23 -6
- package/dist/client.js +18 -2
- package/dist/error.d.ts +1 -0
- package/dist/error.js +2 -0
- package/dist/index.d.ts +9 -1
- package/dist/index.js +2 -2
- package/dist/pointer.d.ts +3 -1
- package/dist/pointer.js +4 -1
- package/dist/schema.js +12 -2
- package/package.json +1 -1
- package/src/client.ts +48 -10
package/README.md
CHANGED
|
@@ -44,11 +44,12 @@ kanagata generate - < openapi.yaml > src/api/schema.d.ts # stdin to stdout
|
|
|
44
44
|
kanagata init -o src/api/client.ts # copy the client into your project
|
|
45
45
|
```
|
|
46
46
|
|
|
47
|
-
| Option
|
|
48
|
-
|
|
|
49
|
-
| `-o <path>`
|
|
50
|
-
| `--check`
|
|
51
|
-
| `--
|
|
47
|
+
| Option | Meaning |
|
|
48
|
+
| ------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
49
|
+
| `-o <path>` | output file (`generate`: stdout; `init`: `./client.ts`) |
|
|
50
|
+
| `--check` | `generate`: compare with the `-o` file instead of writing |
|
|
51
|
+
| `--strict-nullable-enum` | `generate`: in 3.0, keep `null` out of an `enum` or `const` that does not list it, even with `nullable: true`; see [`nullable`](#nullable-30) |
|
|
52
|
+
| `--force` | `init`: overwrite an existing file |
|
|
52
53
|
|
|
53
54
|
- **Exit codes:** 0 success, 1 `--check` found a difference, 2 an error (document, command line, or file I/O), 3 a bug in kanagata (stack on stderr).
|
|
54
55
|
- **Messages** go to stderr as `location: message` or `location: warning: message`. The location is `line:col` for JSON and YAML syntax, a JSON Pointer otherwise, and starts with the file's path relative to the document for other files (`schemas/User.yaml#/properties/id`, `common.json:3:5`).
|
|
@@ -117,6 +118,28 @@ A method of `additionalOperations` (3.2) is called through `api.request`, named
|
|
|
117
118
|
- **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`.
|
|
118
119
|
- **Response headers** are typed in the declarations (`responses[200].headers`); read them from `res.response.headers`.
|
|
119
120
|
|
|
121
|
+
### Wrapping a call
|
|
122
|
+
|
|
123
|
+
`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:
|
|
124
|
+
|
|
125
|
+
```ts
|
|
126
|
+
import type { ArgsOf, ParseAs, PathsOf, ResultOf } from "kanagata/client";
|
|
127
|
+
|
|
128
|
+
async function get<
|
|
129
|
+
Path extends PathsOf<paths, "get">,
|
|
130
|
+
A extends ParseAs | undefined = undefined,
|
|
131
|
+
>(
|
|
132
|
+
path: Path,
|
|
133
|
+
...args: ArgsOf<paths, "get", Path, A>
|
|
134
|
+
): Promise<ResultOf<paths, "get", Path, A>> {
|
|
135
|
+
const res = await api.get<Path, A>(path, ...args);
|
|
136
|
+
log(path, res.status);
|
|
137
|
+
return res;
|
|
138
|
+
}
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
For `api.request`, the method takes the place of `"get"`: `ArgsOf<paths, "COPY", Path>`.
|
|
142
|
+
|
|
120
143
|
### Details
|
|
121
144
|
|
|
122
145
|
- **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.
|
|
@@ -129,9 +152,9 @@ A method of `additionalOperations` (3.2) is called through `api.request`, named
|
|
|
129
152
|
- 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.
|
|
130
153
|
- 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.
|
|
131
154
|
- A raw body (string, `Blob`, `URLSearchParams`, …) is sent as it is for form media types too.
|
|
132
|
-
- **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 `..`
|
|
155
|
+
- **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.
|
|
133
156
|
- **`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.
|
|
134
|
-
- **Errors:** HTTP error statuses never throw; network failures are fetch's own errors. 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.
|
|
157
|
+
- **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.
|
|
135
158
|
- **`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.
|
|
136
159
|
- **`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.
|
|
137
160
|
|
|
@@ -161,7 +184,7 @@ try {
|
|
|
161
184
|
}
|
|
162
185
|
```
|
|
163
186
|
|
|
164
|
-
`generate(src, source?)` returns `{ code, warnings }` and throws `GenerateError
|
|
187
|
+
`generate(src, source?, options?)` 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. `options` is `{ strictNullableEnum?: boolean }`, as `--strict-nullable-enum`.
|
|
165
188
|
|
|
166
189
|
## Output
|
|
167
190
|
|
|
@@ -223,7 +246,9 @@ A sequential media type's `itemSchema` (3.2) is checked like a schema but types
|
|
|
223
246
|
|
|
224
247
|
### `nullable` (3.0)
|
|
225
248
|
|
|
226
|
-
`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.
|
|
249
|
+
`nullable: true` adds `null` even without `type` (`{ nullable: true, allOf: [{ $ref: … }] }`) and next to an `enum` (or `const`) 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.
|
|
250
|
+
|
|
251
|
+
`--strict-nullable-enum` (`generate(src, source, { strictNullableEnum: true })`) reads the `enum` case as OpenAPI 3.0.3 does: an `enum` or `const` that does not list `null` keeps it out, so `{ type: string, enum: [a, b], nullable: true }` is `"a" | "b"`. `nullable` without `type` still adds `null`.
|
|
227
252
|
|
|
228
253
|
## Not supported
|
|
229
254
|
|
package/dist/cli.js
CHANGED
|
@@ -11,6 +11,7 @@ const HELP = `kanagata - TypeScript types from OpenAPI 3.0 / 3.1 / 3.2 (JSON or
|
|
|
11
11
|
|
|
12
12
|
Usage:
|
|
13
13
|
kanagata generate <openapi.json|yaml> [-o <out.d.ts>] [--check]
|
|
14
|
+
[--strict-nullable-enum]
|
|
14
15
|
kanagata init [-o <client.ts>] [--force]
|
|
15
16
|
|
|
16
17
|
Commands:
|
|
@@ -20,6 +21,9 @@ Commands:
|
|
|
20
21
|
Options:
|
|
21
22
|
-o <path> Output file (generate: stdout, init: ./client.ts)
|
|
22
23
|
--check Exit with 1 if the -o file differs from the generated output
|
|
24
|
+
--strict-nullable-enum
|
|
25
|
+
In 3.0, keep null out of an enum or const that does not
|
|
26
|
+
list it, even with nullable: true (as OpenAPI 3.0.3 says)
|
|
23
27
|
--force Let init overwrite an existing file
|
|
24
28
|
-h, --help Show this help
|
|
25
29
|
-V, --version Show the version
|
|
@@ -104,7 +108,13 @@ function attempt(label, f) {
|
|
|
104
108
|
}
|
|
105
109
|
}
|
|
106
110
|
function parseFlags(args, allowed) {
|
|
107
|
-
const f = {
|
|
111
|
+
const f = {
|
|
112
|
+
positional: [],
|
|
113
|
+
check: false,
|
|
114
|
+
force: false,
|
|
115
|
+
strictNullableEnum: false,
|
|
116
|
+
help: false,
|
|
117
|
+
};
|
|
108
118
|
const rest = args[Symbol.iterator]();
|
|
109
119
|
for (const a of rest) {
|
|
110
120
|
const isOption = a.startsWith("-") && a !== "-";
|
|
@@ -121,6 +131,8 @@ function parseFlags(args, allowed) {
|
|
|
121
131
|
f.check = true;
|
|
122
132
|
else if (a === "--force")
|
|
123
133
|
f.force = true;
|
|
134
|
+
else if (a === "--strict-nullable-enum")
|
|
135
|
+
f.strictNullableEnum = true;
|
|
124
136
|
else if (isHelp)
|
|
125
137
|
f.help = true;
|
|
126
138
|
else
|
|
@@ -129,7 +141,7 @@ function parseFlags(args, allowed) {
|
|
|
129
141
|
return f;
|
|
130
142
|
}
|
|
131
143
|
function generateCommand(args, io, out, err) {
|
|
132
|
-
const f = parseFlags(args, ["-o", "--check"]);
|
|
144
|
+
const f = parseFlags(args, ["-o", "--check", "--strict-nullable-enum"]);
|
|
133
145
|
if (f.help) {
|
|
134
146
|
out(HELP);
|
|
135
147
|
return 0;
|
|
@@ -144,7 +156,7 @@ function generateCommand(args, io, out, err) {
|
|
|
144
156
|
const label = input === "-" ? "stdin" : input;
|
|
145
157
|
const src = decode(label, attempt(label, () => io.read(input === "-" ? 0 : input)));
|
|
146
158
|
// A file has a location, so its $refs to other files can be followed; stdin has none.
|
|
147
|
-
const generated = generate(src, input === "-" ? undefined : fileSource(input, io));
|
|
159
|
+
const generated = generate(src, input === "-" ? undefined : fileSource(input, io), { strictNullableEnum: f.strictNullableEnum });
|
|
148
160
|
for (const w of generated.warnings)
|
|
149
161
|
err(`${w.at}: warning: ${w.msg}`);
|
|
150
162
|
const target = f.output;
|
package/dist/client.d.ts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
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 string> = {
|
|
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
8
|
type Op<P, Path, M extends string> = Get<Get<P, Path>, M>;
|
|
@@ -126,8 +126,13 @@ type NeedsAll<O> = Get<(O extends unknown ? (n: {
|
|
|
126
126
|
type Init<N, A> = N & RequestOptions & {
|
|
127
127
|
parseAs?: A;
|
|
128
128
|
};
|
|
129
|
-
/**
|
|
130
|
-
|
|
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>];
|
|
131
136
|
/** "2XX" and default have no single status. */
|
|
132
137
|
type Status<S> = S extends number ? S : number;
|
|
133
138
|
/** Whether a status key is a success: `200`…`299` or `"2XX"`. */
|
|
@@ -204,9 +209,9 @@ export interface DataCall {
|
|
|
204
209
|
request: Request;
|
|
205
210
|
response: Response;
|
|
206
211
|
}
|
|
207
|
-
type Call<P, M extends Method> = <Path extends PathsOf<P, M>, A extends ParseAs | undefined = undefined>(path: Path, ...args:
|
|
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>>;
|
|
208
213
|
/** A call by a method of `additionalOperations`, named first: `request("COPY", path, init)`. */
|
|
209
|
-
type OtherCall<P> = <M extends Sendable<OtherMethod<P>>, Path extends PathsOf<P, M>, A extends ParseAs | undefined = undefined>(method: M, path: Path, ...args:
|
|
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>>;
|
|
210
215
|
/**
|
|
211
216
|
* A function per method fetch sends: every fixed one but TRACE, which fetch rejects, and
|
|
212
217
|
* `request` for the methods of `additionalOperations`.
|
|
@@ -224,8 +229,20 @@ export declare const METHODS: readonly Method[];
|
|
|
224
229
|
* documented statuses. HTTP error statuses do not throw.
|
|
225
230
|
*/
|
|
226
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
|
+
}
|
|
227
243
|
/** A body that is not valid JSON where its content-type (or parseAs) says JSON, such as an HTML error page. */
|
|
228
244
|
export declare class ResponseBodyError extends Error {
|
|
245
|
+
readonly name = "ResponseBodyError";
|
|
229
246
|
readonly response: Response;
|
|
230
247
|
readonly text: string;
|
|
231
248
|
constructor(response: Response, text: string, cause: unknown);
|
package/dist/client.js
CHANGED
|
@@ -211,16 +211,31 @@ function simple(value) {
|
|
|
211
211
|
: [value];
|
|
212
212
|
return parts.map(scalar);
|
|
213
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
|
+
}
|
|
214
229
|
/** Path parameters in the simple style, each part encoded. */
|
|
215
230
|
function fillPath(path, params = {}) {
|
|
216
231
|
return path.replace(/\{([^}]+)\}/g, (_, name) => {
|
|
217
232
|
const value = params[name];
|
|
218
233
|
if (value == null)
|
|
219
|
-
throw new
|
|
234
|
+
throw new PathParameterError(`missing path parameter: ${name}`, name, value);
|
|
220
235
|
const segment = simple(value).map(encodeURIComponent).join(",");
|
|
221
236
|
// URLs resolve `.` and `..` segments, so these would reach another endpoint.
|
|
222
237
|
if (segment === "" || segment === "." || segment === "..")
|
|
223
|
-
throw new
|
|
238
|
+
throw new PathParameterError(`path parameter ${name} would change the path: ${JSON.stringify(value)}`, name, value);
|
|
224
239
|
return segment;
|
|
225
240
|
});
|
|
226
241
|
}
|
|
@@ -364,6 +379,7 @@ async function readData(response, parseAs) {
|
|
|
364
379
|
}
|
|
365
380
|
/** A body that is not valid JSON where its content-type (or parseAs) says JSON, such as an HTML error page. */
|
|
366
381
|
export class ResponseBodyError extends Error {
|
|
382
|
+
name = "ResponseBodyError";
|
|
367
383
|
response;
|
|
368
384
|
text;
|
|
369
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.d.ts
CHANGED
|
@@ -13,8 +13,16 @@ export interface Source {
|
|
|
13
13
|
/** The text of the document at an absolute URL; throws, with a message saying why, when it cannot be read. */
|
|
14
14
|
read: (url: string) => string;
|
|
15
15
|
}
|
|
16
|
+
/** How the document is read. */
|
|
17
|
+
export interface Options {
|
|
18
|
+
/**
|
|
19
|
+
* In 3.0, keep `null` out of an `enum` or `const` that does not list it, even with
|
|
20
|
+
* `nullable: true`, as OpenAPI 3.0.3 says. Off by default: documents mean "or null".
|
|
21
|
+
*/
|
|
22
|
+
strictNullableEnum?: boolean;
|
|
23
|
+
}
|
|
16
24
|
/**
|
|
17
25
|
* Converts an OpenAPI document (JSON or YAML) to a `.d.ts` file. With a `source`,
|
|
18
26
|
* `$ref`s to other files are read through it. Throws GenerateError.
|
|
19
27
|
*/
|
|
20
|
-
export declare function generate(src: string, source?: Source): Generated;
|
|
28
|
+
export declare function generate(src: string, source?: Source, options?: Options): Generated;
|
package/dist/index.js
CHANGED
|
@@ -17,7 +17,7 @@ function parseText(src, warnings) {
|
|
|
17
17
|
* Converts an OpenAPI document (JSON or YAML) to a `.d.ts` file. With a `source`,
|
|
18
18
|
* `$ref`s to other files are read through it. Throws GenerateError.
|
|
19
19
|
*/
|
|
20
|
-
export function generate(src, source) {
|
|
20
|
+
export function generate(src, source, options = {}) {
|
|
21
21
|
const read = [];
|
|
22
22
|
const root = parseText(src, read);
|
|
23
23
|
if (!(root instanceof JsonObject))
|
|
@@ -33,7 +33,7 @@ export function generate(src, source) {
|
|
|
33
33
|
!root.get("openapi").startsWith("3.0."), source && {
|
|
34
34
|
url: source.url,
|
|
35
35
|
load: (url) => loadText(cx, url, source.read(url)),
|
|
36
|
-
});
|
|
36
|
+
}, options.strictNullableEnum === true);
|
|
37
37
|
const p = paths(cx, root);
|
|
38
38
|
// Every component schema, then every schema from another file that got a key (the
|
|
39
39
|
// list grows as they are converted), named, in both views; the write view gets its
|
package/dist/pointer.d.ts
CHANGED
|
@@ -51,6 +51,8 @@ export declare class Ctx {
|
|
|
51
51
|
mode: View;
|
|
52
52
|
/** Whether keywords next to `$ref` apply (OpenAPI 3.1) or are ignored (3.0). */
|
|
53
53
|
readonly refSiblings: boolean;
|
|
54
|
+
/** Whether an `enum` or `const` that does not list `null` keeps it out despite 3.0 `nullable: true`. */
|
|
55
|
+
readonly strictNullableEnum: boolean;
|
|
54
56
|
/** Schemas from other files that got a key, in the order they were first referred to. */
|
|
55
57
|
readonly hoisted: Hoisted[];
|
|
56
58
|
/**
|
|
@@ -63,7 +65,7 @@ export declare class Ctx {
|
|
|
63
65
|
uri: string;
|
|
64
66
|
where: string;
|
|
65
67
|
}): string;
|
|
66
|
-
constructor(root: Value, schemas?: ReadonlySet<string>, refSiblings?: boolean, location?: Location);
|
|
68
|
+
constructor(root: Value, schemas?: ReadonlySet<string>, refSiblings?: boolean, location?: Location, strictNullableEnum?: boolean);
|
|
67
69
|
warn(at: string, msg: string): void;
|
|
68
70
|
get warnings(): Diag[];
|
|
69
71
|
leftOutIn(v: Value): ReadonlySet<string>;
|
package/dist/pointer.js
CHANGED
|
@@ -92,6 +92,8 @@ export class Ctx {
|
|
|
92
92
|
mode = "read";
|
|
93
93
|
/** Whether keywords next to `$ref` apply (OpenAPI 3.1) or are ignored (3.0). */
|
|
94
94
|
refSiblings;
|
|
95
|
+
/** Whether an `enum` or `const` that does not list `null` keeps it out despite 3.0 `nullable: true`. */
|
|
96
|
+
strictNullableEnum;
|
|
95
97
|
/** Schemas from other files that got a key, in the order they were first referred to. */
|
|
96
98
|
hoisted = [];
|
|
97
99
|
/** Hoisted keys by the URI of the schema. */
|
|
@@ -123,10 +125,11 @@ export class Ctx {
|
|
|
123
125
|
this.hoisted.push({ key, value, base: target.base, where: target.where });
|
|
124
126
|
return key;
|
|
125
127
|
}
|
|
126
|
-
constructor(root, schemas = new Set(), refSiblings = false, location) {
|
|
128
|
+
constructor(root, schemas = new Set(), refSiblings = false, location, strictNullableEnum = false) {
|
|
127
129
|
this.root = root;
|
|
128
130
|
this.schemas = schemas;
|
|
129
131
|
this.refSiblings = refSiblings;
|
|
132
|
+
this.strictNullableEnum = strictNullableEnum;
|
|
130
133
|
this.documentUrl =
|
|
131
134
|
location === undefined
|
|
132
135
|
? DOCUMENT
|
package/dist/schema.js
CHANGED
|
@@ -63,7 +63,8 @@ export function doc(v) {
|
|
|
63
63
|
}
|
|
64
64
|
/**
|
|
65
65
|
* `nullable: true` (3.0 only; 3.1 has no such keyword) adds `null` to whatever the rest
|
|
66
|
-
* of the schema gives, as documents mean it (see README)
|
|
66
|
+
* of the schema gives, as documents mean it (see README); with `strictNullableEnum`,
|
|
67
|
+
* an `enum` or `const` that does not list `null` keeps it out, as OAS 3.0.3 says.
|
|
67
68
|
*/
|
|
68
69
|
function parts(cx, v, at) {
|
|
69
70
|
const nullable = !cx.refSiblings && v.get("nullable") === true;
|
|
@@ -108,7 +109,16 @@ function parts(cx, v, at) {
|
|
|
108
109
|
if (Array.isArray(members))
|
|
109
110
|
out.push(union(admitted(members, list(cx, members, child(at, key)))));
|
|
110
111
|
}
|
|
111
|
-
|
|
112
|
+
const addsNull = nullable && (!cx.strictNullableEnum || valuesAdmitNull(v));
|
|
113
|
+
return addsNull ? union([inter(out), NULL]) : inter(out);
|
|
114
|
+
}
|
|
115
|
+
/** Whether the schema's own `enum` and `const`, where present, admit `null`. */
|
|
116
|
+
function valuesAdmitNull(v) {
|
|
117
|
+
const e = v.get("enum");
|
|
118
|
+
if (Array.isArray(e) && !e.includes(null))
|
|
119
|
+
return false;
|
|
120
|
+
const c = v.get("const");
|
|
121
|
+
return c === undefined || c === null;
|
|
112
122
|
}
|
|
113
123
|
/**
|
|
114
124
|
* The keys a closed object admits (`additionalProperties: false`, no
|
package/package.json
CHANGED
package/src/client.ts
CHANGED
|
@@ -17,8 +17,8 @@ type BodyInit = NonNullable<RequestInit["body"]>;
|
|
|
17
17
|
|
|
18
18
|
type Get<T, K> = K extends keyof T ? T[K] : never;
|
|
19
19
|
|
|
20
|
-
/**
|
|
21
|
-
type PathsOf<P, M extends string> = {
|
|
20
|
+
/** The path templates of P that have method M: `PathsOf<paths, "get">`. */
|
|
21
|
+
export type PathsOf<P, M extends string> = {
|
|
22
22
|
[K in keyof P]: M extends keyof P[K] ? K : never;
|
|
23
23
|
}[keyof P] &
|
|
24
24
|
string;
|
|
@@ -185,8 +185,21 @@ type NeedsAll<O> = Get<
|
|
|
185
185
|
|
|
186
186
|
type Init<N, A> = N & RequestOptions & { parseAs?: A };
|
|
187
187
|
|
|
188
|
-
/**
|
|
189
|
-
|
|
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>];
|
|
190
203
|
|
|
191
204
|
/** "2XX" and default have no single status. */
|
|
192
205
|
type Status<S> = S extends number ? S : number;
|
|
@@ -311,8 +324,8 @@ type Call<P, M extends Method> = <
|
|
|
311
324
|
A extends ParseAs | undefined = undefined,
|
|
312
325
|
>(
|
|
313
326
|
path: Path,
|
|
314
|
-
...args:
|
|
315
|
-
) => Promise<
|
|
327
|
+
...args: ArgsOf<P, M, Path, A>
|
|
328
|
+
) => Promise<ResultOf<P, M, Path, A>>;
|
|
316
329
|
|
|
317
330
|
/** A call by a method of `additionalOperations`, named first: `request("COPY", path, init)`. */
|
|
318
331
|
type OtherCall<P> = <
|
|
@@ -322,8 +335,8 @@ type OtherCall<P> = <
|
|
|
322
335
|
>(
|
|
323
336
|
method: M,
|
|
324
337
|
path: Path,
|
|
325
|
-
...args:
|
|
326
|
-
) => Promise<
|
|
338
|
+
...args: ArgsOf<P, M, Path, A>
|
|
339
|
+
) => Promise<ResultOf<P, M, Path, A>>;
|
|
327
340
|
|
|
328
341
|
/**
|
|
329
342
|
* A function per method fetch sends: every fixed one but TRACE, which fetch rejects, and
|
|
@@ -606,16 +619,40 @@ function simple(value: unknown): string[] {
|
|
|
606
619
|
return parts.map(scalar);
|
|
607
620
|
}
|
|
608
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
|
+
|
|
609
639
|
/** Path parameters in the simple style, each part encoded. */
|
|
610
640
|
function fillPath(path: string, params: Record<string, unknown> = {}): string {
|
|
611
641
|
return path.replace(/\{([^}]+)\}/g, (_, name: string) => {
|
|
612
642
|
const value = params[name];
|
|
613
|
-
if (value == null)
|
|
643
|
+
if (value == null)
|
|
644
|
+
throw new PathParameterError(
|
|
645
|
+
`missing path parameter: ${name}`,
|
|
646
|
+
name,
|
|
647
|
+
value,
|
|
648
|
+
);
|
|
614
649
|
const segment = simple(value).map(encodeURIComponent).join(",");
|
|
615
650
|
// URLs resolve `.` and `..` segments, so these would reach another endpoint.
|
|
616
651
|
if (segment === "" || segment === "." || segment === "..")
|
|
617
|
-
throw new
|
|
652
|
+
throw new PathParameterError(
|
|
618
653
|
`path parameter ${name} would change the path: ${JSON.stringify(value)}`,
|
|
654
|
+
name,
|
|
655
|
+
value,
|
|
619
656
|
);
|
|
620
657
|
return segment;
|
|
621
658
|
});
|
|
@@ -781,6 +818,7 @@ async function readData(
|
|
|
781
818
|
|
|
782
819
|
/** A body that is not valid JSON where its content-type (or parseAs) says JSON, such as an HTML error page. */
|
|
783
820
|
export class ResponseBodyError extends Error {
|
|
821
|
+
override readonly name = "ResponseBodyError";
|
|
784
822
|
readonly response: Response;
|
|
785
823
|
readonly text: string;
|
|
786
824
|
|