kanagata 0.3.2 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +17 -5
- package/dist/cli.js +18 -3
- package/dist/client.d.ts +63 -35
- package/dist/emit.d.ts +18 -4
- package/dist/emit.js +171 -28
- package/dist/index.d.ts +6 -1
- package/dist/index.js +8 -3
- package/dist/operation.d.ts +17 -2
- package/dist/operation.js +214 -71
- package/dist/pointer.d.ts +51 -8
- package/dist/pointer.js +136 -5
- package/dist/schema.d.ts +11 -3
- package/dist/schema.js +1528 -138
- package/dist/template.d.ts +12 -0
- package/dist/template.js +349 -0
- package/dist/ty.d.ts +28 -4
- package/dist/ty.js +367 -60
- package/package.json +1 -1
- package/src/client.ts +82 -54
package/README.md
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
# kanagata
|
|
2
2
|
|
|
3
|
+

|
|
4
|
+
|
|
3
5
|
TypeScript types from an OpenAPI 3.0 / 3.1 / 3.2 document (JSON or YAML), and a typed `fetch` client for them.
|
|
4
6
|
|
|
5
7
|
- `kanagata generate` writes one `.d.ts` file.
|
|
@@ -28,6 +30,15 @@ if (res.status === 200) {
|
|
|
28
30
|
|
|
29
31
|
Run `generate` again after upgrading kanagata: the types and the client come from the same version.
|
|
30
32
|
|
|
33
|
+
## Types, not generated clients
|
|
34
|
+
|
|
35
|
+
kanagata generates no code per operation. It translates the OpenAPI schema into accurate TypeScript types, then lets TypeScript do the rest. Rather than generating a collection of abstractions, it provides the foundation for building a type-safe API environment:
|
|
36
|
+
|
|
37
|
+
- Each call is checked against its operation, and the editor autocompletes its path, parameters and request body.
|
|
38
|
+
- Responses form a discriminated union, so checking `status` narrows `data` to the corresponding response type.
|
|
39
|
+
- When the document changes, regenerate types: TypeScript flags affected calls that no longer match the updated contract, and `--check` fails CI if generated files are stale.
|
|
40
|
+
- Your own wrappers, query functions, hooks and validators are typed by the same `paths` and `operations` ([Wrapping a call](docs/client.md#wrapping-a-call)), without generating parallel runtime implementations.
|
|
41
|
+
|
|
31
42
|
## Install
|
|
32
43
|
|
|
33
44
|
- The CLI needs Node 24 or later (`engines`). Its one dependency is [`yaml`](https://github.com/eemeli/yaml), which has none.
|
|
@@ -44,7 +55,7 @@ kanagata generate - < openapi.yaml > src/api/schema.d.ts # stdin to stdout
|
|
|
44
55
|
kanagata init -o src/api/client.ts # copy the client into your project
|
|
45
56
|
```
|
|
46
57
|
|
|
47
|
-
`--loose-nullable` reads 3.0 `nullable: true` as "this schema or null" (see [Generated types](#generated-types)). Every option, the exit codes and messages, and `generate` as a library: [docs/cli.md](docs/cli.md).
|
|
58
|
+
`--loose-nullable` reads 3.0 `nullable: true` as "this schema or null" (see [Generated types](#generated-types)). The file's first line names the kanagata version that wrote it (`--omit-version` leaves it out): after upgrading, a regenerated file that differs only in that line has the same types. Every option, the exit codes and messages, and `generate` as a library: [docs/cli.md](docs/cli.md).
|
|
48
59
|
|
|
49
60
|
## Client
|
|
50
61
|
|
|
@@ -67,16 +78,16 @@ const events = await api.get("/events", { parseAs: "stream" }); // events.data:
|
|
|
67
78
|
```
|
|
68
79
|
|
|
69
80
|
- `api.get`, `api.post`, … take the path template and the operation's parameters and body; a method of `additionalOperations` (3.2) goes through `api.request("COPY", …)`.
|
|
70
|
-
- The result is `{ status, ok, data, response }`, a union over the statuses the operation documents
|
|
81
|
+
- The result is `{ status, ok, data, response }`, a union over the statuses fetch returns: each one the operation documents, the others of a range (`4XX`) or `default`, and without `default`, the undocumented ones, whose `data` is `unknown`. Comparing `status` narrows `data` to that status's body; `ok` narrows to the 2xx results, which include an undocumented 2xx unless `2XX` or `default` covers it. HTTP error statuses never throw.
|
|
71
82
|
- `kanagata init` copies the client's source into your project to edit as you like.
|
|
72
83
|
|
|
73
84
|
Config, call options, results, typing a wrapper, how requests are built, and errors: [docs/client.md](docs/client.md).
|
|
74
85
|
|
|
75
86
|
## Generated types
|
|
76
87
|
|
|
77
|
-
- Every schema in `components.schemas` is a named type; operations are `paths[path][method]`, `webhooks[name][method]` and `operations[operationId]`.
|
|
78
|
-
- Types follow what the schema accepts, not another generator's output.
|
|
79
|
-
- A schema with a `readOnly` / `writeOnly` property gets a second type for
|
|
88
|
+
- Every schema in `components.schemas` is a named type; operations are `paths[path][method]`, `webhooks[name][method]`, an operation's `callbacks[name][expression][method]` and `operations[operationId]`.
|
|
89
|
+
- Types follow what the schema accepts, not another generator's output. Equal tuple items and integers in a row are written with the helper types `repeated` and `integers` where that is shorter, the same types; the file declares the ones it uses.
|
|
90
|
+
- A schema with a `readOnly` / `writeOnly` property gets a second type for what is sent to the API (a path's request, a webhook's responses), `UserInput`.
|
|
80
91
|
- In 3.0, `nullable: true` adds `null` to the `type` next to it, as OpenAPI 3.0.3 says, so it takes no effect without `type`, next to `$ref`, or past an `enum` without `null`. Many documents mean "this schema or null" instead; `--loose-nullable` reads them that way.
|
|
81
92
|
|
|
82
93
|
Every rule, with `$ref` resolution and media types: [docs/types.md](docs/types.md).
|
|
@@ -86,6 +97,7 @@ Every rule, with `$ref` resolution and media types: [docs/types.md](docs/types.m
|
|
|
86
97
|
- Runtime validation (use `onData`), middleware (wrap `config.fetch`), per-operation functions, framework bindings, mocks.
|
|
87
98
|
- 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.
|
|
88
99
|
- Serializing a parameter by its `content` media type: such a parameter (other than `application/x-www-form-urlencoded`) is typed `string`, and the call passes the serialized text.
|
|
100
|
+
- An operation's `security` (and the document's `securitySchemes`) and a response's `links`, which are not read: set credentials in `headers` or `config.fetch`.
|
|
89
101
|
- 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.
|
|
90
102
|
- Pathological inputs: looping `$ref`s outside schemas (a parameter that is a `$ref` to itself), nesting thousands of levels deep, or exponential expansion may crash (exit code 3) or not finish. A schema that is itself without an object, array or tuple in between (`A: { $ref: A }`) is an error ([docs/types.md](docs/types.md#ref)).
|
|
91
103
|
|
package/dist/cli.js
CHANGED
|
@@ -11,7 +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
|
-
[--loose-nullable]
|
|
14
|
+
[--loose-nullable] [--omit-version]
|
|
15
15
|
kanagata init [-o <client.ts>] [--force]
|
|
16
16
|
|
|
17
17
|
Commands:
|
|
@@ -25,6 +25,7 @@ Options:
|
|
|
25
25
|
In 3.0, read nullable: true as "this schema or null", even
|
|
26
26
|
where OpenAPI 3.0.3 gives it no effect (no type, next to
|
|
27
27
|
$ref, an enum without null)
|
|
28
|
+
--omit-version Leave the kanagata version out of the first line
|
|
28
29
|
--force Let init overwrite an existing file
|
|
29
30
|
-h, --help Show this help
|
|
30
31
|
-V, --version Show the version
|
|
@@ -114,6 +115,7 @@ function parseFlags(args, allowed) {
|
|
|
114
115
|
check: false,
|
|
115
116
|
force: false,
|
|
116
117
|
looseNullable: false,
|
|
118
|
+
omitVersion: false,
|
|
117
119
|
help: false,
|
|
118
120
|
};
|
|
119
121
|
const rest = args[Symbol.iterator]();
|
|
@@ -134,6 +136,8 @@ function parseFlags(args, allowed) {
|
|
|
134
136
|
f.force = true;
|
|
135
137
|
else if (a === "--loose-nullable")
|
|
136
138
|
f.looseNullable = true;
|
|
139
|
+
else if (a === "--omit-version")
|
|
140
|
+
f.omitVersion = true;
|
|
137
141
|
else if (isHelp)
|
|
138
142
|
f.help = true;
|
|
139
143
|
else
|
|
@@ -142,7 +146,12 @@ function parseFlags(args, allowed) {
|
|
|
142
146
|
return f;
|
|
143
147
|
}
|
|
144
148
|
function generateCommand(args, io, out, err) {
|
|
145
|
-
const f = parseFlags(args, [
|
|
149
|
+
const f = parseFlags(args, [
|
|
150
|
+
"-o",
|
|
151
|
+
"--check",
|
|
152
|
+
"--loose-nullable",
|
|
153
|
+
"--omit-version",
|
|
154
|
+
]);
|
|
146
155
|
if (f.help) {
|
|
147
156
|
out(HELP);
|
|
148
157
|
return 0;
|
|
@@ -157,7 +166,13 @@ function generateCommand(args, io, out, err) {
|
|
|
157
166
|
const label = input === "-" ? "stdin" : input;
|
|
158
167
|
const src = decode(label, attempt(label, () => io.read(input === "-" ? 0 : input)));
|
|
159
168
|
// A file has a location, so its $refs to other files can be followed; stdin has none.
|
|
160
|
-
const generated = generate(src, input === "-" ? undefined : fileSource(input, io),
|
|
169
|
+
const generated = generate(src, input === "-" ? undefined : fileSource(input, io),
|
|
170
|
+
// The version tells which kanagata's rules the file follows: after an upgrade, a
|
|
171
|
+
// regenerated file that differs only in its first line has the same types.
|
|
172
|
+
{
|
|
173
|
+
looseNullable: f.looseNullable,
|
|
174
|
+
...(f.omitVersion ? {} : { version: version(io) }),
|
|
175
|
+
});
|
|
161
176
|
for (const w of generated.warnings)
|
|
162
177
|
err(`${w.at}: warning: ${w.msg}`);
|
|
163
178
|
const target = f.output;
|
package/dist/client.d.ts
CHANGED
|
@@ -62,6 +62,21 @@ type BodyVariant<K, T> = IsMedia<K, "application/json"> extends true ? {
|
|
|
62
62
|
} | {
|
|
63
63
|
contentType?: K;
|
|
64
64
|
body: URLSearchParams;
|
|
65
|
+
} : RangeVariant<K, T>;
|
|
66
|
+
/**
|
|
67
|
+
* A media type range (`image/*`) is named as written, or as a media type it covers
|
|
68
|
+
* (`image/png`), which is sent. Under `*\/*` and `application/*` a covered type may be
|
|
69
|
+
* one the client encodes a value by (JSON, a form), so naming it takes a raw body.
|
|
70
|
+
*/
|
|
71
|
+
type RangeVariant<K, T> = K extends `${infer R}/*` | `${infer R}/*;${string}` ? R extends "*" | "application" ? {
|
|
72
|
+
contentType: K;
|
|
73
|
+
body: BodyOf<T>;
|
|
74
|
+
} | {
|
|
75
|
+
contentType: R extends "*" ? string : `application/${string}`;
|
|
76
|
+
body: string | RawBinary;
|
|
77
|
+
} : {
|
|
78
|
+
contentType: K | `${R}/${string}`;
|
|
79
|
+
body: BodyOf<T>;
|
|
65
80
|
} : {
|
|
66
81
|
contentType: K;
|
|
67
82
|
body: BodyOf<T>;
|
|
@@ -133,38 +148,55 @@ type Init<N, A> = N & RequestOptions & {
|
|
|
133
148
|
* TypeScript cannot infer A through the spread, so the call names it.
|
|
134
149
|
*/
|
|
135
150
|
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>];
|
|
136
|
-
|
|
137
|
-
type
|
|
138
|
-
/**
|
|
139
|
-
type
|
|
140
|
-
/**
|
|
141
|
-
|
|
151
|
+
type Digit = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9;
|
|
152
|
+
type ToNumber<T> = T extends `${infer N extends number}` ? N : never;
|
|
153
|
+
/** The statuses whose first digit is C: `Codes<4>` is `400 | 401 | … | 499`. */
|
|
154
|
+
type Codes<C extends number> = ToNumber<`${C}${Digit}${Digit}`>;
|
|
155
|
+
/**
|
|
156
|
+
* The statuses fetch resolves with: those of the Fetch Standard (0 to 999) but 1xx, which
|
|
157
|
+
* it does not return. 0 is an opaque response (`mode: "no-cors"`, or a redirect with
|
|
158
|
+
* `redirect: "manual"` in a browser).
|
|
159
|
+
*/
|
|
160
|
+
type AnyStatus = 0 | Codes<2 | 3 | 4 | 5 | 6 | 7 | 8 | 9>;
|
|
161
|
+
/** The statuses a response key covers: its code, or every code of its range. */
|
|
162
|
+
type Covered<K> = K extends number ? K : K extends `${infer C extends number}XX` ? Codes<C> : ToNumber<K>;
|
|
163
|
+
/**
|
|
164
|
+
* The statuses of response key S among the keys K: a code itself, a range its codes K
|
|
165
|
+
* does not list, and `default` every status nothing else covers.
|
|
166
|
+
*/
|
|
167
|
+
type StatusesOf<S, K> = S extends "default" ? Exclude<AnyStatus, Covered<K>> : S extends `${string}XX` ? Extract<Exclude<Covered<S>, Covered<Exclude<K, S>>>, AnyStatus> : Covered<S>;
|
|
142
168
|
/** `data` for a response object B (its `content`), read as parseAs A says. */
|
|
143
169
|
type Parsed<A, B> = A extends "text" ? string : A extends "blob" ? Blob : A extends "arrayBuffer" ? ArrayBuffer : A extends "stream" ? ReadableStream<Uint8Array> | null : A extends "json" ? JsonContent<B> : Content<B>;
|
|
144
|
-
/** fetch gives
|
|
145
|
-
type NullBodyStatus = 204 | 205 | 304;
|
|
146
|
-
/** The
|
|
147
|
-
type
|
|
148
|
-
/** A response nothing documents: any
|
|
170
|
+
/** fetch gives these statuses a null body, whatever is declared (0: an opaque response). */
|
|
171
|
+
type NullBodyStatus = 0 | 204 | 205 | 304;
|
|
172
|
+
/** The statuses for which fetch sets `ok`. */
|
|
173
|
+
type OkStatus = Codes<2>;
|
|
174
|
+
/** A response nothing documents: any body. */
|
|
149
175
|
type Undocumented = {
|
|
150
176
|
content: Record<string, unknown>;
|
|
151
177
|
};
|
|
152
|
-
/**
|
|
178
|
+
/** One result, for statuses St, unless there are none. */
|
|
179
|
+
type Member<St, Ok, B, A> = [St] extends [never] ? never : {
|
|
180
|
+
status: St;
|
|
181
|
+
ok: Ok;
|
|
182
|
+
data: Parsed<A, B>;
|
|
183
|
+
response: Response;
|
|
184
|
+
};
|
|
185
|
+
/**
|
|
186
|
+
* The results for statuses St with response object B, split where fetch's `ok` differs
|
|
187
|
+
* and where it gives no body (HEAD, and the null body statuses).
|
|
188
|
+
*/
|
|
189
|
+
type Results<St, B, A, M> = [M] extends ["head"] ? Member<Extract<St, OkStatus>, true, Empty, A> | Member<Exclude<St, OkStatus>, false, Empty, A> : Member<Exclude<Extract<St, OkStatus>, NullBodyStatus>, true, B, A> | Member<Extract<Extract<St, OkStatus>, NullBodyStatus>, true, Empty, A> | Member<Exclude<Exclude<St, OkStatus>, NullBodyStatus>, false, B, A> | Member<Extract<Exclude<St, OkStatus>, NullBodyStatus>, false, Empty, A>;
|
|
190
|
+
/**
|
|
191
|
+
* A union over the statuses: each documented code, each range's codes the document does
|
|
192
|
+
* not list on their own, and `default`'s statuses, or without `default`, the statuses the
|
|
193
|
+
* document does not list, with any body.
|
|
194
|
+
*/
|
|
153
195
|
export type Result<O, A extends ParseAs | undefined = undefined, M extends string = Method> = O extends {
|
|
154
196
|
responses: infer R;
|
|
155
|
-
} ?
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
data: Parsed<A, Undocumented>;
|
|
159
|
-
response: Response;
|
|
160
|
-
} : {
|
|
161
|
-
[S in keyof R]: {
|
|
162
|
-
status: Status<S>;
|
|
163
|
-
ok: Ok<S>;
|
|
164
|
-
data: Parsed<A, Delivered<M, S, R[S]>>;
|
|
165
|
-
response: Response;
|
|
166
|
-
};
|
|
167
|
-
}[keyof R] : never;
|
|
197
|
+
} ? {
|
|
198
|
+
[S in keyof R]: Results<StatusesOf<S, keyof R>, R[S], A, M>;
|
|
199
|
+
}[keyof R] | ("default" extends keyof R ? never : Results<Exclude<AnyStatus, Covered<keyof R>>, Undocumented, A, M>) : never;
|
|
168
200
|
/**
|
|
169
201
|
* What `client[M](path, { parseAs: A })` resolves to, named in the order of the call:
|
|
170
202
|
* `ResultOf<paths, "get", "/users/{id}">`. `Result` of the path's operation, with the
|
|
@@ -172,21 +204,17 @@ export type Result<O, A extends ParseAs | undefined = undefined, M extends strin
|
|
|
172
204
|
*/
|
|
173
205
|
export type ResultOf<P, M extends string, Path extends PathsOf<P, M>, A extends ParseAs | undefined = undefined> = Result<Op<P, Path, M>, A, M>;
|
|
174
206
|
/**
|
|
175
|
-
* The results of R that `if (res.ok)` leaves: the 2xx statuses,
|
|
176
|
-
*
|
|
177
|
-
*
|
|
207
|
+
* The results of R that `if (res.ok)` leaves: the 2xx statuses, among them those of a
|
|
208
|
+
* range, `default` or the undocumented ones. `OkResult<ResultOf<…>>["data"]` types what
|
|
209
|
+
* a wrapper returns when it throws the others.
|
|
178
210
|
*/
|
|
179
211
|
export type OkResult<R> = R extends {
|
|
180
|
-
ok: infer K;
|
|
181
|
-
} ? true extends K ? R & {
|
|
182
212
|
ok: true;
|
|
183
|
-
}
|
|
184
|
-
/** The results of R that `if (!res.ok)` leaves: the other statuses
|
|
213
|
+
} ? R : never;
|
|
214
|
+
/** The results of R that `if (!res.ok)` leaves: the other statuses. */
|
|
185
215
|
export type NotOkResult<R> = R extends {
|
|
186
|
-
ok: infer K;
|
|
187
|
-
} ? false extends K ? R & {
|
|
188
216
|
ok: false;
|
|
189
|
-
}
|
|
217
|
+
} ? R : never;
|
|
190
218
|
type MaybePromise<T> = T | Promise<T>;
|
|
191
219
|
export interface ClientConfig extends FetchOptions {
|
|
192
220
|
/** Absolute, or relative to the page (`/api`) as fetch resolves it, on every call. */
|
package/dist/emit.d.ts
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
import type
|
|
2
|
-
export declare const HEADER = "// Generated by kanagata. Do not edit.\n";
|
|
1
|
+
import { type Keyed, type Prop, type Ty, type View } from "./ty.ts";
|
|
3
2
|
/** Context precedence. A type binding looser than its context is parenthesized. */
|
|
4
3
|
export declare const Prec: {
|
|
5
4
|
readonly Union: 0;
|
|
@@ -13,10 +12,25 @@ export declare class Out {
|
|
|
13
12
|
#private;
|
|
14
13
|
buf: string;
|
|
15
14
|
depth: number;
|
|
15
|
+
/** The helper types written so far. */
|
|
16
|
+
readonly used: Set<"integers" | "repeated">;
|
|
16
17
|
constructor(name: Namer);
|
|
17
18
|
ty(t: Ty, ctx: Prec): void;
|
|
19
|
+
/** A type as text, written as it would be here. */
|
|
20
|
+
private text;
|
|
21
|
+
/** Types, or text written as it is, joined by `sep`. */
|
|
18
22
|
private list;
|
|
19
|
-
|
|
23
|
+
/**
|
|
24
|
+
* `[A, B?, ...R[]]`. TypeScript bounds a length only item by item, so equal items in a
|
|
25
|
+
* row are `...repeated<[T], n>` where that is shorter than writing each.
|
|
26
|
+
*/
|
|
27
|
+
private tuple;
|
|
28
|
+
/**
|
|
29
|
+
* Members joined by `|`. Integers in a row are `integers<…>`, spelled by their digits,
|
|
30
|
+
* where that is shorter than listing each.
|
|
31
|
+
*/
|
|
32
|
+
private union;
|
|
33
|
+
object(props: Prop[], index?: Ty, keyed?: Keyed[]): void;
|
|
20
34
|
private indent;
|
|
21
35
|
/** Writes a property key: bare if it is an identifier or a canonical integer, otherwise as a JSON string. */
|
|
22
36
|
key(k: string): void;
|
|
@@ -39,4 +53,4 @@ export interface Document {
|
|
|
39
53
|
schemas: Prop[];
|
|
40
54
|
decls: Decl[];
|
|
41
55
|
}
|
|
42
|
-
export declare function render(doc: Document, name: Namer): string;
|
|
56
|
+
export declare function render(doc: Document, name: Namer, version: string | undefined): string;
|
package/dist/emit.js
CHANGED
|
@@ -1,11 +1,84 @@
|
|
|
1
1
|
// Turns `Ty` into TypeScript source text.
|
|
2
2
|
import { isIdent, isNumericKey } from "./ident.js";
|
|
3
|
-
|
|
3
|
+
import { equal } from "./ty.js";
|
|
4
|
+
/**
|
|
5
|
+
* The helper types the output declares where it uses them. Their names are lower case,
|
|
6
|
+
* which no schema's name is (see `typeNames`).
|
|
7
|
+
*/
|
|
8
|
+
const HELPERS = {
|
|
9
|
+
repeated: `/** \`N\` times the items of \`T\`, by the digits \`D\` of \`N\`: \`repeated<[string?], 3>\` is \`[string?, string?, string?]\`. */
|
|
10
|
+
export type repeated<T extends unknown[], N extends number, D extends string = \`\${N}\`, R extends unknown[] = []> = D extends \`\${infer F extends number}\${infer E}\`
|
|
11
|
+
? repeated<T, N, E, [...R, ...R, ...R, ...R, ...R, ...R, ...R, ...R, ...R, ...R, ...[[], T, [...T, ...T], [...T, ...T, ...T], [...T, ...T, ...T, ...T], [...T, ...T, ...T, ...T, ...T], [...T, ...T, ...T, ...T, ...T, ...T], [...T, ...T, ...T, ...T, ...T, ...T, ...T], [...T, ...T, ...T, ...T, ...T, ...T, ...T, ...T], [...T, ...T, ...T, ...T, ...T, ...T, ...T, ...T, ...T]][F]]>
|
|
12
|
+
: R;
|
|
13
|
+
`,
|
|
14
|
+
integers: `/** The integers the decimal texts \`S\` spell: \`\`integers<\`1\${0 | 1}\`>\`\` is \`10 | 11\`. */
|
|
15
|
+
export type integers<S extends string> = S extends \`\${infer N extends number}\` ? N : never;
|
|
16
|
+
`,
|
|
17
|
+
};
|
|
18
|
+
/** An integer literal TypeScript reads back from its text (`${infer N extends number}`), as a number. */
|
|
19
|
+
function integerOf(t) {
|
|
20
|
+
if (t.kind !== "lit" ||
|
|
21
|
+
!/^-?(0|[1-9][0-9]*)$/.test(t.text) ||
|
|
22
|
+
t.text === "-0")
|
|
23
|
+
return undefined;
|
|
24
|
+
const n = Number(t.text);
|
|
25
|
+
return Number.isSafeInteger(n) ? n : undefined;
|
|
26
|
+
}
|
|
27
|
+
/** Template literal types of the decimal texts of the integers from `lo` to `hi`. */
|
|
28
|
+
function spell(lo, hi) {
|
|
29
|
+
const out = [];
|
|
30
|
+
if (lo < 0)
|
|
31
|
+
for (const s of unsigned(Math.max(1, -hi), -lo))
|
|
32
|
+
out.push(`-${s}`);
|
|
33
|
+
if (hi >= 0)
|
|
34
|
+
out.push(...unsigned(Math.max(0, lo), hi));
|
|
35
|
+
return out.map((s) => `\`${s}\``);
|
|
36
|
+
}
|
|
37
|
+
/** The texts of the non-negative integers from `lo` to `hi`, by their number of digits. */
|
|
38
|
+
function unsigned(lo, hi) {
|
|
39
|
+
const [a, b] = [String(lo), String(hi)];
|
|
40
|
+
const out = [];
|
|
41
|
+
for (let n = a.length; n <= b.length; n++)
|
|
42
|
+
out.push(...sameLength(n === a.length ? a : `1${"0".repeat(n - 1)}`, n === b.length ? b : "9".repeat(n)));
|
|
43
|
+
return out;
|
|
44
|
+
}
|
|
45
|
+
/** The texts from `lo` to `hi`, of one length, as digits and sets of digits. */
|
|
46
|
+
function sameLength(lo, hi) {
|
|
47
|
+
if (lo === "")
|
|
48
|
+
return [""];
|
|
49
|
+
const [a, b] = [Number(lo[0]), Number(hi[0])];
|
|
50
|
+
const [restLo, restHi] = [lo.slice(1), hi.slice(1)];
|
|
51
|
+
if (a === b)
|
|
52
|
+
return sameLength(restLo, restHi).map((r) => `${a}${r}`);
|
|
53
|
+
const zeros = "0".repeat(restLo.length);
|
|
54
|
+
const nines = "9".repeat(restLo.length);
|
|
55
|
+
// The first and last digits take every rest only from or up to the bound.
|
|
56
|
+
const from = restLo === zeros ? a : a + 1;
|
|
57
|
+
const to = restHi === nines ? b : b - 1;
|
|
58
|
+
const out = [];
|
|
59
|
+
if (from !== a)
|
|
60
|
+
out.push(...sameLength(restLo, nines).map((r) => `${a}${r}`));
|
|
61
|
+
if (from <= to) {
|
|
62
|
+
const set = Array.from({ length: to - from + 1 }, (_, i) => from + i);
|
|
63
|
+
const d = set.length === 1 ? `${from}` : `\${${set.join(" | ")}}`;
|
|
64
|
+
out.push(...sameLength(zeros, nines).map((r) => `${d}${r}`));
|
|
65
|
+
}
|
|
66
|
+
if (to !== b)
|
|
67
|
+
out.push(...sameLength(zeros, restHi).map((r) => `${b}${r}`));
|
|
68
|
+
return out;
|
|
69
|
+
}
|
|
70
|
+
/** The first line, naming the kanagata version when one is given. */
|
|
71
|
+
function header(version) {
|
|
72
|
+
const by = version === undefined ? "kanagata" : `kanagata ${version}`;
|
|
73
|
+
return `// Generated by ${by}. Do not edit.\n`;
|
|
74
|
+
}
|
|
4
75
|
/** Context precedence. A type binding looser than its context is parenthesized. */
|
|
5
76
|
export const Prec = { Union: 0, Inter: 1, Postfix: 2 };
|
|
6
77
|
export class Out {
|
|
7
78
|
buf = "";
|
|
8
79
|
depth = 0;
|
|
80
|
+
/** The helper types written so far. */
|
|
81
|
+
used = new Set();
|
|
9
82
|
#name;
|
|
10
83
|
constructor(name) {
|
|
11
84
|
this.#name = name;
|
|
@@ -34,6 +107,7 @@ export class Out {
|
|
|
34
107
|
this.buf += "Record<string, unknown>";
|
|
35
108
|
break;
|
|
36
109
|
case "lit":
|
|
110
|
+
case "template":
|
|
37
111
|
this.buf += t.text;
|
|
38
112
|
break;
|
|
39
113
|
case "ref":
|
|
@@ -47,54 +121,112 @@ export class Out {
|
|
|
47
121
|
this.buf += "[]";
|
|
48
122
|
break;
|
|
49
123
|
case "tuple":
|
|
50
|
-
this.
|
|
51
|
-
t.items.forEach((item, i) => {
|
|
52
|
-
if (i > 0)
|
|
53
|
-
this.buf += ", ";
|
|
54
|
-
if (i < t.min) {
|
|
55
|
-
this.ty(item, Prec.Union);
|
|
56
|
-
}
|
|
57
|
-
else {
|
|
58
|
-
this.ty(item, Prec.Postfix);
|
|
59
|
-
this.buf += "?";
|
|
60
|
-
}
|
|
61
|
-
});
|
|
62
|
-
if (t.rest !== undefined) {
|
|
63
|
-
if (t.items.length > 0)
|
|
64
|
-
this.buf += ", ";
|
|
65
|
-
this.buf += "...";
|
|
66
|
-
this.ty(t.rest, Prec.Postfix);
|
|
67
|
-
this.buf += "[]";
|
|
68
|
-
}
|
|
69
|
-
this.buf += "]";
|
|
124
|
+
this.tuple(t);
|
|
70
125
|
break;
|
|
71
126
|
case "object":
|
|
72
127
|
this.object(t.props);
|
|
73
128
|
break;
|
|
74
129
|
case "map":
|
|
75
|
-
this.object(t.props, t.index);
|
|
130
|
+
this.object(t.props, t.index, t.keyed);
|
|
76
131
|
break;
|
|
77
132
|
case "union":
|
|
78
|
-
this.
|
|
133
|
+
this.union(t.items, ctx > Prec.Union);
|
|
79
134
|
break;
|
|
80
135
|
case "inter":
|
|
81
136
|
this.list(t.items, " & ", ctx > Prec.Inter, Prec.Inter);
|
|
82
137
|
break;
|
|
83
138
|
}
|
|
84
139
|
}
|
|
140
|
+
/** A type as text, written as it would be here. */
|
|
141
|
+
text(t, ctx) {
|
|
142
|
+
const outer = this.buf;
|
|
143
|
+
this.buf = "";
|
|
144
|
+
this.ty(t, ctx);
|
|
145
|
+
const text = this.buf;
|
|
146
|
+
this.buf = outer;
|
|
147
|
+
return text;
|
|
148
|
+
}
|
|
149
|
+
/** Types, or text written as it is, joined by `sep`. */
|
|
85
150
|
list(items, sep, paren, inner) {
|
|
86
151
|
if (paren)
|
|
87
152
|
this.buf += "(";
|
|
88
153
|
items.forEach((item, i) => {
|
|
89
154
|
if (i > 0)
|
|
90
155
|
this.buf += sep;
|
|
91
|
-
|
|
156
|
+
if (typeof item === "string")
|
|
157
|
+
this.buf += item;
|
|
158
|
+
else
|
|
159
|
+
this.ty(item, inner);
|
|
92
160
|
});
|
|
93
161
|
if (paren)
|
|
94
162
|
this.buf += ")";
|
|
95
163
|
}
|
|
96
|
-
|
|
97
|
-
|
|
164
|
+
/**
|
|
165
|
+
* `[A, B?, ...R[]]`. TypeScript bounds a length only item by item, so equal items in a
|
|
166
|
+
* row are `...repeated<[T], n>` where that is shorter than writing each.
|
|
167
|
+
*/
|
|
168
|
+
tuple(t) {
|
|
169
|
+
const parts = [];
|
|
170
|
+
for (let i = 0; i < t.items.length;) {
|
|
171
|
+
const first = t.items[i];
|
|
172
|
+
const required = i < t.min;
|
|
173
|
+
let j = i + 1;
|
|
174
|
+
while (j < t.items.length &&
|
|
175
|
+
j < t.min === required &&
|
|
176
|
+
equal(t.items[j], first))
|
|
177
|
+
j++;
|
|
178
|
+
const item = required
|
|
179
|
+
? this.text(first, Prec.Union)
|
|
180
|
+
: `${this.text(first, Prec.Postfix)}?`;
|
|
181
|
+
const n = j - i;
|
|
182
|
+
const run = `...repeated<[${item}], ${n}>`;
|
|
183
|
+
if (run.length < n * item.length + (n - 1) * 2) {
|
|
184
|
+
this.used.add("repeated");
|
|
185
|
+
parts.push(run);
|
|
186
|
+
}
|
|
187
|
+
else
|
|
188
|
+
for (let k = 0; k < n; k++)
|
|
189
|
+
parts.push(item);
|
|
190
|
+
i = j;
|
|
191
|
+
}
|
|
192
|
+
if (t.rest !== undefined)
|
|
193
|
+
parts.push(`...${this.text(t.rest, Prec.Postfix)}[]`);
|
|
194
|
+
this.buf += "[";
|
|
195
|
+
this.list(parts, ", ", false, Prec.Union);
|
|
196
|
+
this.buf += "]";
|
|
197
|
+
}
|
|
198
|
+
/**
|
|
199
|
+
* Members joined by `|`. Integers in a row are `integers<…>`, spelled by their digits,
|
|
200
|
+
* where that is shorter than listing each.
|
|
201
|
+
*/
|
|
202
|
+
union(items, paren) {
|
|
203
|
+
const parts = [];
|
|
204
|
+
for (let i = 0; i < items.length;) {
|
|
205
|
+
const first = integerOf(items[i]);
|
|
206
|
+
let j = i + 1;
|
|
207
|
+
if (first !== undefined)
|
|
208
|
+
while (j < items.length &&
|
|
209
|
+
integerOf(items[j]) === first + (j - i))
|
|
210
|
+
j++;
|
|
211
|
+
const run = items.slice(i, j);
|
|
212
|
+
i = j;
|
|
213
|
+
if (run.length > 1) {
|
|
214
|
+
// An integer literal is written as its text.
|
|
215
|
+
const listed = run.reduce((n, t) => n + t.text.length + 3, -3);
|
|
216
|
+
const last = first + run.length - 1;
|
|
217
|
+
const spelled = `integers<${spell(first, last).join(" | ")}>`;
|
|
218
|
+
if (spelled.length < listed) {
|
|
219
|
+
this.used.add("integers");
|
|
220
|
+
parts.push(spelled);
|
|
221
|
+
continue;
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
parts.push(...run);
|
|
225
|
+
}
|
|
226
|
+
this.list(parts, " | ", paren && parts.length > 1, Prec.Union);
|
|
227
|
+
}
|
|
228
|
+
object(props, index, keyed = []) {
|
|
229
|
+
if (props.length === 0 && index === undefined && keyed.length === 0) {
|
|
98
230
|
this.buf += "{}";
|
|
99
231
|
return;
|
|
100
232
|
}
|
|
@@ -111,6 +243,14 @@ export class Out {
|
|
|
111
243
|
this.ty(p.ty, Prec.Union);
|
|
112
244
|
this.buf += ";\n";
|
|
113
245
|
}
|
|
246
|
+
for (const k of keyed) {
|
|
247
|
+
this.indent();
|
|
248
|
+
this.buf += "[key: ";
|
|
249
|
+
this.ty(k.key, Prec.Union);
|
|
250
|
+
this.buf += "]: ";
|
|
251
|
+
this.ty(k.ty, Prec.Union);
|
|
252
|
+
this.buf += ";\n";
|
|
253
|
+
}
|
|
114
254
|
if (index !== undefined) {
|
|
115
255
|
this.indent();
|
|
116
256
|
this.buf += "[key: string]: ";
|
|
@@ -149,9 +289,9 @@ export class Out {
|
|
|
149
289
|
this.buf += " */\n";
|
|
150
290
|
}
|
|
151
291
|
}
|
|
152
|
-
export function render(doc, name) {
|
|
292
|
+
export function render(doc, name, version) {
|
|
153
293
|
const out = new Out(name);
|
|
154
|
-
out.buf +=
|
|
294
|
+
out.buf += header(version);
|
|
155
295
|
const interfaces = [["paths", doc.paths]];
|
|
156
296
|
if (doc.webhooks !== undefined)
|
|
157
297
|
interfaces.push(["webhooks", doc.webhooks]);
|
|
@@ -169,5 +309,8 @@ export function render(doc, name) {
|
|
|
169
309
|
out.ty(decl.ty, Prec.Union);
|
|
170
310
|
out.buf += ";\n";
|
|
171
311
|
}
|
|
312
|
+
for (const helper of Object.keys(HELPERS))
|
|
313
|
+
if (out.used.has(helper))
|
|
314
|
+
out.buf += `\n${HELPERS[helper]}`;
|
|
172
315
|
return out.buf;
|
|
173
316
|
}
|
package/dist/index.d.ts
CHANGED
|
@@ -13,7 +13,7 @@ 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. */
|
|
16
|
+
/** How the document is read, and what the output's first line says. */
|
|
17
17
|
export interface Options {
|
|
18
18
|
/**
|
|
19
19
|
* In 3.0, read `nullable: true` as "this schema or null": `null` even without `type`,
|
|
@@ -21,6 +21,11 @@ export interface Options {
|
|
|
21
21
|
* Off by default: `nullable` adds `null` to `type` only, as OpenAPI 3.0.3 says.
|
|
22
22
|
*/
|
|
23
23
|
looseNullable?: boolean;
|
|
24
|
+
/**
|
|
25
|
+
* The kanagata version the first line names (`// Generated by kanagata 0.4.0. Do not edit.`),
|
|
26
|
+
* as the CLI writes it. Without it, the line names no version.
|
|
27
|
+
*/
|
|
28
|
+
version?: string;
|
|
24
29
|
}
|
|
25
30
|
/**
|
|
26
31
|
* Converts an OpenAPI document (JSON or YAML) to a `.d.ts` file. With a `source`,
|
package/dist/index.js
CHANGED
|
@@ -5,7 +5,7 @@ import { inputNames, typeNames } from "./ident.js";
|
|
|
5
5
|
import { get, JsonObject, parse } from "./json.js";
|
|
6
6
|
import { paths } from "./operation.js";
|
|
7
7
|
import { Ctx, child, DiagError } from "./pointer.js";
|
|
8
|
-
import {
|
|
8
|
+
import { schema, schemaDoc } from "./schema.js";
|
|
9
9
|
import { admitsAny, bareRefs, equal, presentKeys, prop, ref, refs, } from "./ty.js";
|
|
10
10
|
import { parseYaml } from "./yaml.js";
|
|
11
11
|
export { GenerateError } from "./error.js";
|
|
@@ -67,6 +67,11 @@ export function generate(src, source, options = {}) {
|
|
|
67
67
|
name: names[i],
|
|
68
68
|
}));
|
|
69
69
|
const differing = differingViews(components);
|
|
70
|
+
// An operation reached again is declared once, so its types must be declared alike:
|
|
71
|
+
// a reference to either view of a schema without a second type is the same name.
|
|
72
|
+
for (const a of p.again)
|
|
73
|
+
if (!equal(a.first.ty, a.ty, differing))
|
|
74
|
+
throw new DiagError(a.at, `operation ${JSON.stringify(a.id)} is also ${a.first.at}, where its type differs; operations[${JSON.stringify(a.id)}] has one type`);
|
|
70
75
|
const withInput = components.filter((c) => differing.has(c.key));
|
|
71
76
|
const inputs = inputNames(withInput.map((c) => c.name), names);
|
|
72
77
|
const readName = new Map(components.map((c) => [c.key, c.name]));
|
|
@@ -79,7 +84,7 @@ export function generate(src, source, options = {}) {
|
|
|
79
84
|
const decls = [];
|
|
80
85
|
const index = [];
|
|
81
86
|
for (const c of components) {
|
|
82
|
-
const d =
|
|
87
|
+
const d = schemaDoc(cx, c.value);
|
|
83
88
|
const decl = (n, ty) => d === undefined ? { name: n, ty } : { name: n, ty, doc: d };
|
|
84
89
|
index.push(prop(c.key, ref(c.key)));
|
|
85
90
|
decls.push(decl(c.name, present(c.read)));
|
|
@@ -93,7 +98,7 @@ export function generate(src, source, options = {}) {
|
|
|
93
98
|
operations: props(p.operations),
|
|
94
99
|
...(p.webhooks === undefined ? {} : { webhooks: props(p.webhooks) }),
|
|
95
100
|
};
|
|
96
|
-
const code = render({ ...ops, schemas: index, decls }, name);
|
|
101
|
+
const code = render({ ...ops, schemas: index, decls }, name, options.version);
|
|
97
102
|
return { code, warnings: [...read, ...cx.warnings] };
|
|
98
103
|
}
|
|
99
104
|
/** Parses another document; its problems are located in that file (`defs/a.yaml:3:1`, `defs/a.yaml#/b`). */
|
package/dist/operation.d.ts
CHANGED
|
@@ -1,11 +1,26 @@
|
|
|
1
1
|
import { JsonObject } from "./json.ts";
|
|
2
2
|
import { type Ctx } from "./pointer.ts";
|
|
3
|
-
import { type Prop } from "./ty.ts";
|
|
3
|
+
import { type Prop, type Ty } from "./ty.ts";
|
|
4
4
|
export interface Paths {
|
|
5
5
|
paths: Prop[];
|
|
6
|
-
/** Present only when the document has `webhooks`
|
|
6
|
+
/** Present only when the document has `webhooks` and is 3.1 or later. */
|
|
7
7
|
webhooks?: Prop[];
|
|
8
8
|
operations: Prop[];
|
|
9
|
+
/** Operations with an operationId reached again, whose types `generate` compares. */
|
|
10
|
+
again: Again[];
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* An operation with an operationId reached again through a Path Item that paths or
|
|
14
|
+
* webhooks share: `ty` is its type there, `first` the one `operations[id]` declares.
|
|
15
|
+
*/
|
|
16
|
+
export interface Again {
|
|
17
|
+
id: string;
|
|
18
|
+
ty: Ty;
|
|
19
|
+
at: string;
|
|
20
|
+
first: {
|
|
21
|
+
ty: Ty;
|
|
22
|
+
at: string;
|
|
23
|
+
};
|
|
9
24
|
}
|
|
10
25
|
/** `paths` and `webhooks`: both map names to Path Items, and share `operations`. */
|
|
11
26
|
export declare function paths(cx: Ctx, root: JsonObject): Paths;
|