kanagata 0.3.1 → 0.4.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 CHANGED
@@ -1,5 +1,7 @@
1
1
  # kanagata
2
2
 
3
+ ![kanagata: types, not generated clients](docs/header.svg)
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.
@@ -22,12 +24,21 @@ const res = await api.get("/users/{id}", { path: { id: 1 } });
22
24
  if (res.status === 200) {
23
25
  const user: User = res.data;
24
26
  } else {
25
- res.data.message; // the 404 body
27
+ res.data.message; // typed as the 404 body; a status the document does not list (a gateway's 502) lands here too
26
28
  }
27
29
  ```
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,7 +78,7 @@ 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: checking `status` or `ok` narrows `data`. HTTP error statuses never throw.
81
+ - The result is `{ status, ok, data, response }`, a union over the statuses the operation documents: checking `status` or `ok` narrows `data`. In an operation with `default`, neither narrows to the success body alone: `default`'s `status` is `number` and its `ok` is `boolean`, so its `data` stays after `res.status === 200` and after `res.ok`. 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).
@@ -85,8 +96,9 @@ Every rule, with `$ref` resolution and media types: [docs/types.md](docs/types.m
85
96
 
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.
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.
88
100
  - 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.
89
- - 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.
101
+ - 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)).
90
102
 
91
103
  ## Development
92
104
 
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, ["-o", "--check", "--loose-nullable"]);
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), { looseNullable: f.looseNullable });
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/emit.d.ts CHANGED
@@ -1,5 +1,4 @@
1
1
  import type { Prop, Ty, View } from "./ty.ts";
2
- export declare const HEADER = "// Generated by kanagata. Do not edit.\n";
3
2
  /** Context precedence. A type binding looser than its context is parenthesized. */
4
3
  export declare const Prec: {
5
4
  readonly Union: 0;
@@ -39,4 +38,4 @@ export interface Document {
39
38
  schemas: Prop[];
40
39
  decls: Decl[];
41
40
  }
42
- export declare function render(doc: Document, name: Namer): string;
41
+ export declare function render(doc: Document, name: Namer, version: string | undefined): string;
package/dist/emit.js CHANGED
@@ -1,6 +1,10 @@
1
1
  // Turns `Ty` into TypeScript source text.
2
2
  import { isIdent, isNumericKey } from "./ident.js";
3
- export const HEADER = "// Generated by kanagata. Do not edit.\n";
3
+ /** The first line, naming the kanagata version when one is given. */
4
+ function header(version) {
5
+ const by = version === undefined ? "kanagata" : `kanagata ${version}`;
6
+ return `// Generated by ${by}. Do not edit.\n`;
7
+ }
4
8
  /** Context precedence. A type binding looser than its context is parenthesized. */
5
9
  export const Prec = { Union: 0, Inter: 1, Postfix: 2 };
6
10
  export class Out {
@@ -149,9 +153,9 @@ export class Out {
149
153
  this.buf += " */\n";
150
154
  }
151
155
  }
152
- export function render(doc, name) {
156
+ export function render(doc, name, version) {
153
157
  const out = new Out(name);
154
- out.buf += HEADER;
158
+ out.buf += header(version);
155
159
  const interfaces = [["paths", doc.paths]];
156
160
  if (doc.webhooks !== undefined)
157
161
  interfaces.push(["webhooks", doc.webhooks]);
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
@@ -6,7 +6,7 @@ import { get, JsonObject, parse } from "./json.js";
6
6
  import { paths } from "./operation.js";
7
7
  import { Ctx, child, DiagError } from "./pointer.js";
8
8
  import { doc, schema } from "./schema.js";
9
- import { admitsAny, equal, presentKeys, prop, ref, refs, } from "./ty.js";
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";
12
12
  /** Text that starts with `{` (or is blank) is JSON; anything else is YAML. */
@@ -59,6 +59,7 @@ export function generate(src, source, options = {}) {
59
59
  write: view("write"),
60
60
  });
61
61
  }
62
+ rejectBareCycles(converted);
62
63
  const names = typeNames(converted.map((c) => c.key));
63
64
  // typeNames gives one name per key, in order
64
65
  const components = converted.map((c, i) => ({
@@ -92,7 +93,7 @@ export function generate(src, source, options = {}) {
92
93
  operations: props(p.operations),
93
94
  ...(p.webhooks === undefined ? {} : { webhooks: props(p.webhooks) }),
94
95
  };
95
- const code = render({ ...ops, schemas: index, decls }, name);
96
+ const code = render({ ...ops, schemas: index, decls }, name, options.version);
96
97
  return { code, warnings: [...read, ...cx.warnings] };
97
98
  }
98
99
  /** Parses another document; its problems are located in that file (`defs/a.yaml:3:1`, `defs/a.yaml#/b`). */
@@ -111,6 +112,34 @@ function loadText(cx, url, text) {
111
112
  throw new GenerateError(err.kind, `${file}:${err.message}`);
112
113
  }
113
114
  }
115
+ /**
116
+ * Rejects a schema that reaches itself through unions, intersections and references
117
+ * only (`Tree: { oneOf: [{ type: string }, { $ref: Tree }] }`): TypeScript rejects
118
+ * `type Tree = string | Tree` (TS2456). A reference inside an object, array or tuple
119
+ * type is deferred, so a cycle through one is a type. Only properties differ between
120
+ * the views, so the read view's references are the write view's too.
121
+ */
122
+ function rejectBareCycles(converted) {
123
+ const byKey = new Map(converted.map((c) => [c.key, c]));
124
+ const done = new Set();
125
+ const path = [];
126
+ const visit = (key) => {
127
+ const start = path.indexOf(key);
128
+ if (start >= 0) {
129
+ const cycle = [...path.slice(start), key].join(" → ");
130
+ throw new DiagError(byKey.get(key).at, `circular reference without an object, array or tuple in between, which TypeScript rejects: ${cycle}`);
131
+ }
132
+ if (done.has(key))
133
+ return;
134
+ path.push(key);
135
+ for (const r of bareRefs(byKey.get(key).read))
136
+ visit(r);
137
+ path.pop();
138
+ done.add(key);
139
+ };
140
+ for (const c of converted)
141
+ visit(c.key);
142
+ }
114
143
  /** `presentKeys`, with references resolved to the components' types in their view. */
115
144
  function presentIn(components) {
116
145
  const byKey = new Map(components.map((c) => [c.key, c]));
package/dist/operation.js CHANGED
@@ -3,7 +3,7 @@ import { isBinaryMedia, isFormMedia, isTextMedia, METHODS } from "./client.js";
3
3
  import { JsonObject } from "./json.js";
4
4
  import { child, DiagError } from "./pointer.js";
5
5
  import { doc, schema } from "./schema.js";
6
- import { BLOB, lit, object, opRef, prop, STRING, tuple, UNKNOWN, } from "./ty.js";
6
+ import { BLOB, equal, lit, object, opRef, prop, STRING, tuple, UNKNOWN, } from "./ty.js";
7
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"];
@@ -15,15 +15,32 @@ function documented(key, ty, optional, d) {
15
15
  }
16
16
  /** `paths` and `webhooks`: both map names to Path Items, and share `operations`. */
17
17
  export function paths(cx, root) {
18
- const operations = [];
18
+ const operations = new Map();
19
19
  const out = {
20
20
  paths: pathItems(cx, root, "paths", operations),
21
- operations,
21
+ operations: [],
22
22
  };
23
23
  if (root.get("webhooks") !== undefined)
24
24
  out.webhooks = pathItems(cx, root, "webhooks", operations);
25
+ out.operations = [...operations.values()].map((o) => o.prop);
25
26
  return out;
26
27
  }
28
+ /**
29
+ * Adds an operation with an operationId. A Path Item shared by `$ref` (or a YAML alias)
30
+ * gives the same Operation Object again, which is declared once; another Operation
31
+ * Object with the same operationId, which OpenAPI requires to be unique, is an error.
32
+ * The same operation as a path's and a webhook's has two types (the API sends a
33
+ * webhook's request) but one `operations[id]`, which TypeScript cannot declare twice.
34
+ */
35
+ function addOperation(operations, id, op, prop, at) {
36
+ const known = operations.get(id);
37
+ if (known === undefined)
38
+ operations.set(id, { op, prop, at });
39
+ else if (known.op !== op)
40
+ throw new DiagError(at, `operationId ${JSON.stringify(id)} is also ${known.at}'s; OpenAPI requires it to be unique`);
41
+ else if (!equal(known.prop.ty, prop.ty))
42
+ throw new DiagError(at, `operation ${JSON.stringify(id)} is also ${known.at}, as a path's and a webhook's, whose types differ; operations[${JSON.stringify(id)}] has one type`);
43
+ }
27
44
  function pathItems(cx, root, key, operations) {
28
45
  const out = [];
29
46
  const entries = root.get(key);
@@ -37,7 +54,7 @@ function pathItems(cx, root, key, operations) {
37
54
  continue;
38
55
  const itemAt = child(`#/${key}`, path);
39
56
  const methods = cx.derefIn(rawItem, itemAt, (value) => {
40
- const item = value;
57
+ const item = objectAt(value, itemAt, "a path item");
41
58
  const methods = [];
42
59
  for (const [method, op, opAt] of itemOperations(cx, item, itemAt)) {
43
60
  // A webhook is called by the API: it sends the request and reads the response.
@@ -47,9 +64,11 @@ function pathItems(cx, root, key, operations) {
47
64
  const body = key === "webhooks" || (method !== "get" && method !== "head");
48
65
  const ty = operation(cx, { item, itemAt, op, at: opAt, sent, body });
49
66
  const opDoc = doc(op);
50
- const id = op.str("operationId");
67
+ const id = op.get("operationId");
68
+ if (id !== undefined && typeof id !== "string")
69
+ throw new DiagError(child(opAt, "operationId"), "operationId must be a string");
51
70
  if (id !== undefined && id !== "") {
52
- operations.push(documented(id, ty, false, opDoc));
71
+ addOperation(operations, id, op, documented(id, ty, false, opDoc), opAt);
53
72
  methods.push(prop(method, opRef(id)));
54
73
  }
55
74
  else {
@@ -73,13 +92,14 @@ function itemOperations(cx, item, itemAt) {
73
92
  if (method === "query" && !cx.v32)
74
93
  continue;
75
94
  const op = item.get(method);
95
+ const at = child(itemAt, method);
76
96
  if (op !== undefined)
77
- out.push([method, op, child(itemAt, method)]);
97
+ out.push([method, objectAt(op, at, "an operation"), at]);
78
98
  }
79
- const more = cx.v32
80
- ? item.get("additionalOperations")
81
- : undefined;
99
+ const more = cx.v32 ? item.get("additionalOperations") : undefined;
82
100
  const moreAt = child(itemAt, "additionalOperations");
101
+ if (more !== undefined && !(more instanceof JsonObject))
102
+ throw new DiagError(moreAt, "additionalOperations must be an object");
83
103
  for (const [method, op] of more?.entries ?? []) {
84
104
  const at = child(moreAt, method);
85
105
  // OpenAPI forbids the method a fixed field sends (`POST` for `post`); the field's own
@@ -88,7 +108,7 @@ function itemOperations(cx, item, itemAt) {
88
108
  const field = METHODS.find((m) => method === m || method === m.toUpperCase());
89
109
  if (field !== undefined)
90
110
  throw new DiagError(at, `${method} is the Path Item's ${field} field, so additionalOperations must not have it`);
91
- out.push([method, op, at]);
111
+ out.push([method, objectAt(op, at, "an operation"), at]);
92
112
  }
93
113
  return out;
94
114
  }
@@ -97,7 +117,9 @@ function operation(cx, { item, itemAt, op: o, at, sent, body: hasBody }) {
97
117
  const received = sent === "write" ? "read" : "write";
98
118
  // The servers that serve this operation, in place of the document's: its own, or its
99
119
  // path item's. A webhook's request is sent by the API, so it has none to choose.
100
- const servers = sent === "write" ? (serverUrls(o) ?? serverUrls(item)) : undefined;
120
+ const servers = sent === "write"
121
+ ? (serverUrls(o, at) ?? serverUrls(item, itemAt))
122
+ : undefined;
101
123
  if (servers !== undefined)
102
124
  fields.push(prop("servers", tuple(servers)));
103
125
  // Path-level parameters first; an operation parameter with the same in + name replaces it.
@@ -113,9 +135,9 @@ function operation(cx, { item, itemAt, op: o, at, sent, body: hasBody }) {
113
135
  for (const [p, pAt, base] of params) {
114
136
  if (p.str("in") !== loc)
115
137
  continue;
116
- const optional = loc !== "path" && p.get("required") !== true;
138
+ const optional = loc !== "path" && !booleanAt(p, pAt, "required");
117
139
  const whole = loc === "querystring";
118
- const ty = cx.inMode(sent, () => cx.withBase(base, () => paramType(cx, p, pAt, whole)));
140
+ const ty = cx.inMode(sent, () => cx.withBase(base, () => paramType(cx, p, pAt, "parameter")));
119
141
  // The whole query string (3.2) is one value; its name is not sent.
120
142
  if (whole)
121
143
  groups.push(documented(loc, ty, optional, doc(p)));
@@ -136,19 +158,24 @@ function operation(cx, { item, itemAt, op: o, at, sent, body: hasBody }) {
136
158
  if (rawBody !== undefined && hasBody) {
137
159
  const bodyAt = child(at, "requestBody");
138
160
  cx.derefIn(rawBody, bodyAt, (value) => {
139
- const body = value;
140
- const c = cx.inMode(sent, () => content(cx, body, bodyAt));
141
- fields.push(documented("requestBody", object([prop("content", c)]), body.get("required") !== true, doc(body)));
161
+ const body = objectAt(value, bodyAt, "a request body");
162
+ if (body.get("content") === undefined)
163
+ throw new DiagError(bodyAt, "a request body must have content");
164
+ // An empty content describes no representation: no body can be passed.
165
+ const c = cx.inMode(sent, () => content(cx, body, bodyAt)) ?? object([]);
166
+ fields.push(documented("requestBody", object([prop("content", c)]), !booleanAt(body, bodyAt, "required"), doc(body)));
142
167
  });
143
168
  }
144
169
  const responses = [];
145
170
  const rs = o.get("responses");
146
171
  const base = child(at, "responses");
147
- for (const [status, raw] of rs?.entries ?? []) {
172
+ const statuses = rs === undefined ? [] : objectAt(rs, base, "responses").entries;
173
+ for (const [status, raw] of statuses) {
148
174
  if (status.startsWith("x-"))
149
175
  continue; // a specification extension, not a status
150
176
  const rAt = child(base, status);
151
- const parts = cx.derefIn(raw, rAt, (r) => {
177
+ const parts = cx.derefIn(raw, rAt, (value) => {
178
+ const r = objectAt(value, rAt, "a response");
152
179
  const parts = [];
153
180
  const h = cx.inMode(received, () => headers(cx, r, rAt));
154
181
  if (h !== undefined)
@@ -167,30 +194,32 @@ function operation(cx, { item, itemAt, op: o, at, sent, body: hasBody }) {
167
194
  * The URLs of a non-empty `servers`, as literals; a URL with variables (`{region}`) is
168
195
  * any string, since TypeScript cannot check the template.
169
196
  */
170
- function serverUrls(owner) {
171
- const servers = owner.get("servers");
172
- if (!Array.isArray(servers) || servers.length === 0)
197
+ function serverUrls(owner, ownerAt) {
198
+ const at = child(ownerAt, "servers");
199
+ const servers = arrayAt(owner.get("servers"), at, "servers");
200
+ if (servers.length === 0)
173
201
  return undefined;
174
- return servers.map((s) => {
175
- const url = s.str("url");
202
+ return servers.map((s, i) => {
203
+ const url = s instanceof JsonObject ? s.str("url") : undefined;
204
+ if (url === undefined)
205
+ throw new DiagError(child(at, String(i)), "a server must have a url");
176
206
  return url.includes("{") ? STRING : lit(JSON.stringify(url));
177
207
  });
178
208
  }
179
209
  function collectParams(cx, out, owner, ownerAt) {
180
- const list = owner.get("parameters");
181
- if (!Array.isArray(list))
182
- return;
183
210
  const base = child(ownerAt, "parameters");
184
- list.forEach((raw, i) => {
211
+ arrayAt(owner.get("parameters"), base, "parameters").forEach((raw, i) => {
185
212
  const pAt = child(base, String(i));
186
213
  cx.derefIn(raw, pAt, (p) => collectParam(cx, out, p, pAt));
187
214
  });
188
215
  }
189
216
  /** Adds one parameter; header parameters OpenAPI reserves are left out, as it requires. */
190
217
  function collectParam(cx, out, value, pAt) {
191
- const p = value;
218
+ const p = objectAt(value, pAt, "a parameter");
192
219
  const name = p.str("name");
193
220
  const loc = p.str("in");
221
+ if (name === undefined || loc === undefined)
222
+ throw new DiagError(pAt, "a parameter must have name and in");
194
223
  if (loc === "header" && RESERVED_HEADERS.includes(asciiLower(name)))
195
224
  return;
196
225
  // Header names are case-insensitive, so `X-Id` replaces `x-id`; an operation has one
@@ -211,20 +240,30 @@ function asciiLower(s) {
211
240
  return s.replace(/[A-Z]/g, (c) => c.toLowerCase());
212
241
  }
213
242
  /**
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.
243
+ * The type of a parameter or header (`kind`): its `schema`, or the schema of its one
244
+ * `content` media type; OpenAPI requires one of the two. A parameter's `content` is that
245
+ * schema for application/x-www-form-urlencoded, which the client encodes as it does any
246
+ * parameter; for any other media type it is the serialized text, a string, since the
247
+ * client has no document to serialize the value by. A response header is read, not sent,
248
+ * so it keeps the schema.
217
249
  */
218
- function paramType(cx, p, at, whole = false) {
250
+ function paramType(cx, p, at, kind) {
219
251
  const s = p.get("schema");
220
252
  if (s !== undefined)
221
253
  return schema(cx, s, child(at, "schema"));
222
- const [[mt, raw]] = p.get("content").entries;
223
- const mAt = child(child(at, "content"), mt);
254
+ const media = p.get("content");
255
+ if (media === undefined)
256
+ throw new DiagError(at, `a ${kind} must have schema or content`);
257
+ const cAt = child(at, "content");
258
+ const entries = objectAt(media, cAt, "content").entries;
259
+ if (entries.length !== 1)
260
+ throw new DiagError(cAt, `a ${kind}'s content must have exactly one media type`);
261
+ const [[mt, raw]] = entries;
262
+ const mAt = child(cAt, mt);
224
263
  return mediaType(cx, raw, mAt, (m) => {
225
264
  const ty = schema(cx, m.get("schema"), child(mAt, "schema"));
226
265
  const urlEncoded = essence(mt) === "application/x-www-form-urlencoded";
227
- return whole && !urlEncoded ? STRING : ty;
266
+ return kind === "parameter" && !urlEncoded ? STRING : ty;
228
267
  });
229
268
  }
230
269
  /** The media type without parameters, in lower case, as the client compares it. */
@@ -236,9 +275,31 @@ function essence(mt) {
236
275
  * (`components.mediaTypes`); before 3.2, `$ref` is no field of it.
237
276
  */
238
277
  function mediaType(cx, raw, at, f) {
278
+ const media = (m) => f(objectAt(m, at, "a media type"));
239
279
  if (!cx.v32)
240
- return f(raw);
241
- return cx.derefIn(raw, at, (m) => f(m));
280
+ return media(raw);
281
+ return cx.derefIn(raw, at, media);
282
+ }
283
+ /** `v` as an object, or an error: `what` (`a response`) must be one. */
284
+ function objectAt(v, at, what) {
285
+ if (v instanceof JsonObject)
286
+ return v;
287
+ throw new DiagError(at, `${what} must be an object`);
288
+ }
289
+ /** An array field (`servers`, `parameters`): its items, none when absent, or an error. */
290
+ function arrayAt(v, at, key) {
291
+ if (v === undefined)
292
+ return [];
293
+ if (Array.isArray(v))
294
+ return v;
295
+ throw new DiagError(at, `${key} must be an array`);
296
+ }
297
+ /** A boolean field (`required`): false when absent, or an error. */
298
+ function booleanAt(owner, at, key) {
299
+ const v = owner.get(key);
300
+ if (v === undefined || typeof v === "boolean")
301
+ return v === true;
302
+ throw new DiagError(child(at, key), `${key} must be a boolean`);
242
303
  }
243
304
  /** `{ Name: T }` for a response's `headers`; Content-Type is ignored, as OpenAPI requires. */
244
305
  function headers(cx, response, at) {
@@ -247,13 +308,13 @@ function headers(cx, response, at) {
247
308
  return undefined;
248
309
  const base = child(at, "headers");
249
310
  const props = [];
250
- for (const [name, raw] of declared.entries) {
311
+ for (const [name, raw] of objectAt(declared, base, "headers").entries) {
251
312
  if (name.toLowerCase() === "content-type")
252
313
  continue;
253
314
  const hAt = child(base, name);
254
315
  cx.derefIn(raw, hAt, (value) => {
255
- const h = value;
256
- props.push(documented(name, paramType(cx, h, hAt), h.get("required") !== true, doc(h)));
316
+ const h = objectAt(value, hAt, "a header");
317
+ props.push(documented(name, paramType(cx, h, hAt, "header"), !booleanAt(h, hAt, "required"), doc(h)));
257
318
  });
258
319
  }
259
320
  return props.length === 0 ? undefined : object(props);
@@ -267,10 +328,13 @@ function headers(cx, response, at) {
267
328
  * rules say, not item by item.
268
329
  */
269
330
  function content(cx, owner, at) {
270
- const media = owner.get("content");
271
- if (media === undefined || media.entries.length === 0)
331
+ const declared = owner.get("content");
332
+ if (declared === undefined)
272
333
  return undefined;
273
334
  const base = child(at, "content");
335
+ const media = objectAt(declared, base, "content");
336
+ if (media.entries.length === 0)
337
+ return undefined;
274
338
  return object(media.entries.map(([mt, raw]) => {
275
339
  const mAt = child(base, mt);
276
340
  const ty = mediaType(cx, raw, mAt, (m) => {
package/dist/ty.d.ts CHANGED
@@ -109,6 +109,11 @@ export declare const prop: (key: string, ty: Ty) => Prop;
109
109
  export declare function equal(a: Ty, b: Ty, views?: boolean): boolean;
110
110
  /** Every component schema a type refers to. */
111
111
  export declare function refs(t: Ty, out?: Set<string>): Set<string>;
112
+ /**
113
+ * The component schemas a type is made of directly: through unions and intersections,
114
+ * not inside an object, array or tuple type, where TypeScript defers a reference.
115
+ */
116
+ export declare function bareRefs(t: Ty, out?: string[]): string[];
112
117
  /**
113
118
  * Whether a type admits any value: `unknown`, a union with a member that does, an
114
119
  * intersection of such types, or a reference to a component whose type (`resolve`) does.
package/dist/ty.js CHANGED
@@ -110,6 +110,18 @@ export function refs(t, out = new Set()) {
110
110
  }
111
111
  return out;
112
112
  }
113
+ /**
114
+ * The component schemas a type is made of directly: through unions and intersections,
115
+ * not inside an object, array or tuple type, where TypeScript defers a reference.
116
+ */
117
+ export function bareRefs(t, out = []) {
118
+ if (t.kind === "ref")
119
+ out.push(t.schema);
120
+ else if (t.kind === "union" || t.kind === "inter")
121
+ for (const i of t.items)
122
+ bareRefs(i, out);
123
+ return out;
124
+ }
113
125
  /**
114
126
  * Whether a type admits any value: `unknown`, a union with a member that does, an
115
127
  * intersection of such types, or a reference to a component whose type (`resolve`) does.
package/dist/yaml.js CHANGED
@@ -2,7 +2,7 @@
2
2
  import { isAlias, isMap, isSeq, LineCounter, parseDocument, } from "yaml";
3
3
  import { GenerateError } from "./error.js";
4
4
  import { isJsonNumber, JsonNumber, JsonObject } from "./json.js";
5
- import { child } from "./pointer.js";
5
+ import { child, DiagError } from "./pointer.js";
6
6
  /**
7
7
  * Parses a YAML 1.2 document (core schema). Syntax errors throw a GenerateError of
8
8
  * kind `yaml` with `line:col`; a merge key `<<` is added to `warnings`.
@@ -16,10 +16,22 @@ export function parseYaml(src, warnings) {
16
16
  const [start] = error.linePos;
17
17
  throw new GenerateError("yaml", `${start.line}:${start.col}: ${firstLine(error.message)}`);
18
18
  }
19
+ // An alias is the node anchored with its name, not a copy: both are one value.
20
+ const anchored = new Map();
19
21
  const convert = (node, at) => {
20
- // An alias is a copy of the node anchored with its name.
21
- if (isAlias(node))
22
- return convert(node.resolve(doc), at);
22
+ if (isAlias(node)) {
23
+ // An anchored node is converted before its aliases, unless one is inside it.
24
+ const value = anchored.get(node.resolve(doc));
25
+ if (value === undefined)
26
+ throw new DiagError(at, `alias *${node.source} is inside the node it names`);
27
+ return value;
28
+ }
29
+ const value = convertNode(node, at);
30
+ if (node.anchor !== undefined)
31
+ anchored.set(node, value);
32
+ return value;
33
+ };
34
+ const convertNode = (node, at) => {
23
35
  if (isMap(node))
24
36
  return new JsonObject(node.items.map(({ key, value }) => {
25
37
  const k = key;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "kanagata",
3
- "version": "0.3.1",
3
+ "version": "0.4.0",
4
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",