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/dist/schema.js CHANGED
@@ -6,28 +6,30 @@
6
6
  // combinations TypeScript would print badly (`string & "a"` is `"a"`). Adding a
7
7
  // keyword means adding a part here, not another special case.
8
8
  import { isBinaryMedia } from "./client.js";
9
- import { get, JsonNumber, JsonObject, str, toJson, unescapeToken, } from "./json.js";
9
+ import { escapeToken, get, JsonNumber, JsonObject, str, toJson, unescapeToken, } from "./json.js";
10
10
  import { child, DiagError } from "./pointer.js";
11
- import { array as arrayTy, BLOB, BOOLEAN, INTEGER, inter, lit, NEVER, NULL, NUMBER, prop, RECORD, ref, STRING, tuple, UNDEFINED, UNKNOWN, union, } from "./ty.js";
11
+ import { MAX_UNION, patternType } from "./template.js";
12
+ import { array as arrayTy, BLOB, BOOLEAN, equalValues, INTEGER, inter, lit, NEVER, NULL, NUMBER, prop, RECORD, ref, STRING, tuple, UNDEFINED, UNKNOWN, union, } from "./ty.js";
12
13
  const SCHEMA_PREFIX = "#/components/schemas/";
13
- /** Keywords that change which values are valid but have no TypeScript form: ignored, with a warning. */
14
- const IGNORED = [
15
- ["not", "not cannot be expressed in TypeScript; ignored"],
16
- ["if", "if / then / else cannot be expressed in TypeScript; ignored"],
17
- [
18
- "dependentSchemas",
19
- "dependentSchemas cannot be expressed in TypeScript; ignored",
20
- ],
21
- [
22
- "unevaluatedProperties",
23
- "unevaluatedProperties cannot be expressed in TypeScript; ignored",
24
- ],
25
- [
26
- "unevaluatedItems",
27
- "unevaluatedItems cannot be expressed in TypeScript; ignored",
28
- ],
29
- ["$dynamicRef", "$dynamicRef is not supported; ignored"],
14
+ /** Keywords that apply subschemas to the same value: they decide what `unevaluated*` see. */
15
+ const APPLICATORS = [
16
+ "allOf",
17
+ "oneOf",
18
+ "anyOf",
19
+ "$ref",
20
+ "$dynamicRef",
21
+ "if",
22
+ "dependentSchemas",
30
23
  ];
24
+ /**
25
+ * `unevaluatedProperties` / `unevaluatedItems` where no applicator evaluates anything:
26
+ * then they are `additionalProperties` / `items`. undefined where they are not that.
27
+ */
28
+ function unevaluated(v, key) {
29
+ return APPLICATORS.every((k) => v.get(k) === undefined)
30
+ ? v.get(key)
31
+ : undefined;
32
+ }
31
33
  /** Converts a schema. */
32
34
  export function schema(cx, v, at) {
33
35
  if (v === true)
@@ -36,27 +38,82 @@ export function schema(cx, v, at) {
36
38
  return NEVER;
37
39
  if (!(v instanceof JsonObject))
38
40
  return UNKNOWN; // not a schema
39
- // A schema with $id is a resource: $refs inside it resolve against its URI.
40
- const id = v.str("$id");
41
- if (id !== undefined && cx.refSiblings)
42
- return cx.withBase(cx.baseOf(id), () => convert(cx, v, at));
43
- return convert(cx, v, at);
41
+ // This schema is where `raw` says; the schemas in it are elsewhere unless they say.
42
+ const saved = cx.here;
43
+ cx.here = cx.raw;
44
+ try {
45
+ return cx.inSchema(() => cx.withRaw(undefined, () => {
46
+ // A schema with $id is a resource: $refs inside it resolve against its URI.
47
+ const id = v.str("$id");
48
+ if (id !== undefined && cx.refSiblings)
49
+ return cx.inResource(cx.baseOf(id), () => convert(cx, v, at));
50
+ return convert(cx, v, at);
51
+ }));
52
+ }
53
+ finally {
54
+ cx.here = saved;
55
+ }
56
+ }
57
+ /**
58
+ * Whether a schema has bytes where it is: a binary string as a body or a part, or a
59
+ * part that is one for a multipart body; through `$ref` and composition too.
60
+ */
61
+ function binaryAt(cx, v, pos, seen = new Set()) {
62
+ if (!(v instanceof JsonObject))
63
+ return false;
64
+ const r = v.str("$ref");
65
+ const target = r === undefined ? undefined : cx.tryLocate(r);
66
+ if (target !== undefined && !seen.has(target.uri)) {
67
+ seen.add(target.uri);
68
+ if (cx.withBase(target.base, () => binaryAt(cx, target.value, pos, seen)))
69
+ return true;
70
+ }
71
+ const inPlace = ["allOf", "oneOf", "anyOf"].flatMap((k) => {
72
+ const m = v.get(k);
73
+ return Array.isArray(m) ? m : [];
74
+ });
75
+ if (inPlace.some((m) => binaryAt(cx, m, pos, seen)))
76
+ return true;
77
+ if (pos === "parts") {
78
+ const props = v.get("properties");
79
+ const pp = v.get("patternProperties");
80
+ return [
81
+ ...(props instanceof JsonObject ? props.entries.map(([, s]) => s) : []),
82
+ ...(pp instanceof JsonObject ? pp.entries.map(([, s]) => s) : []),
83
+ v.get("additionalProperties"),
84
+ ].some((s) => s !== undefined && binaryAt(cx, s, "part", seen));
85
+ }
86
+ const t = v.get("type");
87
+ if ((t === "string" || (Array.isArray(t) && t.includes("string"))) &&
88
+ isBinaryString(v))
89
+ return true;
90
+ if (pos !== "part")
91
+ return false;
92
+ const prefix = v.get("prefixItems");
93
+ return [v.get("items"), ...(Array.isArray(prefix) ? prefix : [])].some((s) => s !== undefined && binaryAt(cx, s, "part", seen));
44
94
  }
45
95
  function convert(cx, v, at) {
46
- const t = parts(cx, v, at);
47
- // In 3.0 the keywords next to $ref have no effect, so ignoring them is no news.
48
- if (cx.refSiblings || v.str("$ref") === undefined)
49
- for (const [keyword, message] of IGNORED)
50
- if (v.get(keyword) !== undefined)
51
- cx.warn(child(at, keyword), message);
52
- return t;
53
- }
54
- /** JSDoc text from `description` and `deprecated`. */
55
- export function doc(v) {
96
+ return parts(cx, v, at);
97
+ }
98
+ /**
99
+ * JSDoc text from an object's `description` and `deprecated`; `description` may be one
100
+ * that replaces the object's (next to the `$ref` that reached it, in 3.1 and 3.2).
101
+ */
102
+ export function doc(v, description = v.str("description")) {
103
+ return docText(description, v.get("deprecated") === true);
104
+ }
105
+ /**
106
+ * A schema's JSDoc: in 3.0 the keywords next to `$ref` are ignored, `deprecated` among
107
+ * them; `description` is read there too (docs/types.md).
108
+ */
109
+ export function schemaDoc(cx, v) {
56
110
  if (!(v instanceof JsonObject))
57
111
  return undefined;
58
- const desc = v.str("description")?.trim() || undefined;
59
- const deprecated = v.get("deprecated") === true;
112
+ const siblings = cx.refSiblings || v.get("$ref") === undefined;
113
+ return docText(v.str("description"), siblings && v.get("deprecated") === true);
114
+ }
115
+ function docText(description, deprecated) {
116
+ const desc = description?.trim() || undefined;
60
117
  if (!deprecated)
61
118
  return desc;
62
119
  return desc === undefined ? "@deprecated" : `${desc}\n@deprecated`;
@@ -70,14 +127,33 @@ function parts(cx, v, at) {
70
127
  const nullable = !cx.refSiblings && v.get("nullable") === true;
71
128
  const loose = nullable && cx.looseNullable;
72
129
  const out = [];
130
+ // A member that requires a key this closed object forbids admits no value.
131
+ const closed = closedKeys(v);
132
+ const admitted = (members, tys) => closed === undefined
133
+ ? tys
134
+ : tys.map((t, i) => requiredKeys(cx, members[i]).some((k) => !closed.has(k))
135
+ ? NEVER
136
+ : t);
73
137
  const r = v.str("$ref");
74
138
  if (r !== undefined) {
75
- const target = reference(cx, r, at);
139
+ // The target is the same value, this schema's keywords around it.
140
+ const target = cx.withAround(v, () => reference(cx, r, at));
76
141
  // In 3.1 (JSON Schema 2020-12) the keywords next to $ref apply too; in 3.0 they
77
142
  // are ignored, nullable among them unless loose.
78
143
  if (!cx.refSiblings)
79
144
  return loose ? union([target, NULL]) : target;
80
- out.push(target);
145
+ out.push(...admitted([v], [target]));
146
+ }
147
+ // $dynamicRef is $ref, except where it reaches a $dynamicAnchor: then it reaches the
148
+ // one of that name in the outermost resource the value was reached through.
149
+ const dr = v.str("$dynamicRef");
150
+ if (dr !== undefined) {
151
+ const target = cx.locate(dr, at);
152
+ const name = new URL(target.uri).hash.slice(1);
153
+ const outer = cx.isDynamicAnchor(target.uri)
154
+ ? cx.dynamicTarget(name)
155
+ : undefined;
156
+ out.push(cx.withAround(v, () => reference(cx, outer ?? dr, at)));
81
157
  }
82
158
  const c = v.get("const");
83
159
  if (c !== undefined)
@@ -85,63 +161,890 @@ function parts(cx, v, at) {
85
161
  const e = v.get("enum");
86
162
  if (Array.isArray(e))
87
163
  out.push(union(e.map(literal)));
88
- // A member that requires a key this closed object forbids admits no value.
89
- const closed = closedKeys(v);
90
- const admitted = (members, tys) => closed === undefined
91
- ? tys
92
- : tys.map((t, i) => requiredKeys(cx, members[i]).some((k) => !closed.has(k))
93
- ? NEVER
94
- : t);
164
+ // Every member is the same object: a property one member leaves out of this view
165
+ // stays out even where another member lists it as required.
166
+ const group = leftOutKeys(cx, v);
167
+ for (const k of cx.leftOutIn(v))
168
+ group.add(k);
95
169
  const allOf = v.get("allOf");
96
170
  if (Array.isArray(allOf)) {
97
- // Every member is the same object: a property one member leaves out of this
98
- // view stays out even where another member lists it as required.
99
- const group = leftOutKeys(cx, v);
100
- for (const k of cx.leftOutIn(v))
101
- group.add(k);
102
- const members = cx.withLeftOut(allOf, group, () => list(cx, allOf, child(at, "allOf")));
103
- out.push(...admitted(allOf, members));
171
+ const members = membersIn(cx, v, allOf, group, child(at, "allOf"));
172
+ out.push(...passing(cx, v, allOf, admitted(allOf, members)));
104
173
  }
174
+ // A closed object admits no key its $ref target or members have but it does not;
175
+ // one without properties already says so (`{ [key: string]: never }`).
176
+ const self = closed === undefined || closed.size === 0
177
+ ? own(cx, v, at)
178
+ : forbid(own(cx, v, at), outsideKeys(cx, v, closed));
105
179
  const typedNull = nullable && !loose && v.get("type") !== undefined;
106
- out.push(typedNull ? union([own(cx, v, at), NULL]) : own(cx, v, at));
180
+ out.push(typedNull ? union([self, NULL]) : self);
107
181
  // `discriminator` is not read: it must not change what the schema accepts (OAS 3.0.4, 3.1.1),
108
182
  // and a member is narrowed by the property only where the member itself fixes it.
109
183
  for (const key of ["oneOf", "anyOf"]) {
110
184
  const members = v.get(key);
111
185
  if (!Array.isArray(members))
112
186
  continue;
113
- const tys = admitted(members, list(cx, members, child(at, key)));
114
- out.push(union(key === "oneOf" ? exclusive(cx, members, tys, child(at, key)) : tys));
187
+ const tys = passing(cx, v, members, closedAmong(cx, members, admitted(members, membersIn(cx, v, members, group, child(at, key)))));
188
+ out.push(union(key === "oneOf"
189
+ ? shared(exclusive(cx, members, tys, child(at, key), group))
190
+ : tys));
191
+ }
192
+ // A key present asks what its dependent schema asks: without the key, or that schema.
193
+ const ds = v.get("dependentSchemas");
194
+ if (ds instanceof JsonObject) {
195
+ const members = ds.entries.map(([, s]) => s);
196
+ const tys = membersIn(cx, v, members, group, child(at, "dependentSchemas"), ds.entries.map(([k]) => k));
197
+ ds.entries.forEach(([key], i) => {
198
+ out.push(widen(cx, v, "object", union([
199
+ { kind: "object", props: [{ key, ty: NEVER, optional: true }] },
200
+ tys[i],
201
+ ])));
202
+ });
115
203
  }
116
- return loose ? union([inter(out), NULL]) : inter(out);
204
+ // The value is as `then` says where `if` admits it, and as `else` says where it does
205
+ // not: TypeScript can say so where it can say which values `if` does not admit.
206
+ const cond = v.get("if");
207
+ if (cond !== undefined &&
208
+ (v.get("then") !== undefined || v.get("else") !== undefined)) {
209
+ const not = refuted(cx, cond, [v, ...cx.around]);
210
+ if (not === undefined)
211
+ cx.warn(child(at, "if"), "if / then / else cannot be expressed in TypeScript; ignored");
212
+ else {
213
+ const branches = [cond, v.get("then") ?? true, v.get("else") ?? true];
214
+ const [i, t, e] = membersIn(cx, v, branches, group, at, [
215
+ "if",
216
+ "then",
217
+ "else",
218
+ ]).map((ty, k) => anyKind(cx, v, branches[k], ty));
219
+ // Each kind `if` does not admit meets `else` on its own, so that `else` reads as that kind.
220
+ const nots = not.kind === "union" ? not.items : [not];
221
+ out.push(union([
222
+ inter([i, t]),
223
+ ...nots.map((n) => inter([n, e])),
224
+ ]));
225
+ }
226
+ }
227
+ out.push(...unevaluatedParts(cx, v, at));
228
+ out.push(...keywordParts(cx, v, at, group));
229
+ out.push(...arrayTargets(cx, out, at));
230
+ // The schema's own keywords drop the literals (from const, enum, members) they reject,
231
+ // and `not: { enum }` those it lists.
232
+ const t = inter(out);
233
+ const members = t.kind === "union" ? t.items : [t];
234
+ const out$ = excluded(v) ?? [];
235
+ const listed = (m) => out$.some((x) => x.kind === m.kind &&
236
+ (m.kind !== "lit" ||
237
+ x === m ||
238
+ x.text === m.text));
239
+ // The keywords are read where there are literals to drop.
240
+ const admits = members.some((m) => m.kind === "lit")
241
+ ? admitting(cx, v)
242
+ : () => true;
243
+ const keep = (m) => admits(m) && !listed(m);
244
+ const kept = members.every(keep) ? t : union(members.filter(keep));
245
+ // A value `not` lists that a member may admit other than by listing it (`string` for
246
+ // "a", a reference) stays.
247
+ if (out$.some((x) => members.some((m) => mayAdmit(m, x))))
248
+ cx.warn(child(at, "not"), "not cannot be expressed in TypeScript; ignored");
249
+ return loose ? union([kept, NULL]) : kept;
117
250
  }
118
251
  /**
119
252
  * The keys a closed object admits (`additionalProperties: false`, no
120
253
  * `patternProperties`): its declared properties. undefined when it is not closed.
121
254
  */
122
255
  function closedKeys(v) {
123
- if (v.get("additionalProperties") !== false)
256
+ const ap = v.get("additionalProperties") ?? unevaluated(v, "unevaluatedProperties");
257
+ if (ap !== false)
124
258
  return undefined;
125
259
  if (v.get("patternProperties") !== undefined)
126
260
  return undefined;
127
261
  const props = v.get("properties");
128
262
  return new Set(props instanceof JsonObject ? props.entries.map(([k]) => k) : []);
129
263
  }
130
- /** The keys a schema requires: its own `required`, and those of the schema its `$ref` reaches. */
131
- function requiredKeys(cx, s) {
264
+ /**
265
+ * The keys a schema requires: its own `required`, and those of the schema its `$ref`
266
+ * reaches and of its `allOf` members.
267
+ */
268
+ function requiredKeys(cx, s, seen = new Set()) {
269
+ return keysOf(cx, s, seen, false);
270
+ }
271
+ /** The keys a schema names, as properties or as required, there or through `$ref` and `allOf`. */
272
+ function namedKeys(cx, s, seen = new Set()) {
273
+ return keysOf(cx, s, seen, true);
274
+ }
275
+ function keysOf(cx, s, seen, properties) {
132
276
  const req = get(s, "required");
133
- const own = Array.isArray(req)
277
+ const keys = Array.isArray(req)
134
278
  ? req.filter((n) => typeof n === "string")
135
279
  : [];
280
+ const props = get(s, "properties");
281
+ if (properties && props instanceof JsonObject)
282
+ keys.push(...props.entries.map(([k]) => k));
283
+ const allOf = get(s, "allOf");
284
+ for (const m of Array.isArray(allOf) ? allOf : [])
285
+ keys.push(...keysOf(cx, m, seen, properties));
136
286
  const r = str(s, "$ref");
137
287
  const target = r === undefined ? undefined : cx.tryLocate(r);
138
- if (target === undefined)
139
- return own;
288
+ if (target === undefined || seen.has(target.uri))
289
+ return keys;
290
+ seen.add(target.uri);
140
291
  // The target's own $refs resolve against the document it is in.
141
292
  return [
142
- ...own,
143
- ...cx.withBase(target.base, () => requiredKeys(cx, target.value)),
293
+ ...keys,
294
+ ...cx.withBase(target.base, () => keysOf(cx, target.value, seen, properties)),
295
+ ];
296
+ }
297
+ /**
298
+ * The keys a closed object's `$ref` target (3.1, 3.2) and members name that it does not
299
+ * declare: it admits none of them.
300
+ */
301
+ function outsideKeys(cx, v, closed) {
302
+ const named = [];
303
+ const r = v.str("$ref");
304
+ const target = r === undefined ? undefined : cx.tryLocate(r);
305
+ if (target !== undefined)
306
+ named.push(...cx.withBase(target.base, () => namedKeys(cx, target.value)));
307
+ for (const key of ["allOf", "oneOf", "anyOf"]) {
308
+ const members = v.get(key);
309
+ for (const m of Array.isArray(members) ? members : [])
310
+ named.push(...namedKeys(cx, m));
311
+ }
312
+ return [...new Set(named)].filter((k) => !closed.has(k));
313
+ }
314
+ /** The keys a closed member admits: its own, or those of the closed schema its `$ref` alone reaches. */
315
+ function closedMember(cx, s) {
316
+ if (!(s instanceof JsonObject))
317
+ return undefined;
318
+ const r = s.str("$ref");
319
+ if (r === undefined ||
320
+ !s.entries.every(([k]) => k === "$ref" || isAnnotation(k)))
321
+ return closedKeys(s);
322
+ const target = cx.tryLocate(r);
323
+ return target?.value instanceof JsonObject
324
+ ? closedKeys(target.value)
325
+ : undefined;
326
+ }
327
+ /**
328
+ * The array types of the components among `out` that are arrays, where another array
329
+ * meets them: the reference stays, and its type beside it lets the items read as it
330
+ * says (`Tags & [unknown?]` is `Tags & [string?]`). TypeScript reads an item of an
331
+ * intersection of arrays as one member's alone.
332
+ */
333
+ function arrayTargets(cx, out, at) {
334
+ const isArray = (t) => t.kind === "array" || t.kind === "tuple";
335
+ const arrays = out.filter(isArray).length;
336
+ const refs = out.filter((t) => t.kind === "ref" && cx.schemas.has(t.schema));
337
+ if (refs.length + arrays < 2)
338
+ return [];
339
+ const targets = [];
340
+ for (const t of refs) {
341
+ const { value, base, uri, where } = cx.withBase(cx.documentBase, () => cx.locate(SCHEMA_PREFIX + escapeToken(t.schema), at));
342
+ // Only an array schema has an array type.
343
+ const type = get(value, "type");
344
+ const array = type === "array" ||
345
+ (type === undefined &&
346
+ value instanceof JsonObject &&
347
+ hasArrayKeywords(value));
348
+ if (!array || !cx.enter(uri))
349
+ continue;
350
+ try {
351
+ const target = cx.withBase(base, () => schema(cx, value, where));
352
+ if (isArray(target))
353
+ targets.push(target);
354
+ }
355
+ finally {
356
+ cx.leave();
357
+ }
358
+ }
359
+ return targets.length > 0 && targets.length + arrays > 1 ? targets : [];
360
+ }
361
+ /** The type of each value kind `type` names. */
362
+ const KIND = {
363
+ string: STRING,
364
+ number: NUMBER,
365
+ integer: INTEGER,
366
+ boolean: BOOLEAN,
367
+ null: NULL,
368
+ array: arrayTy(UNKNOWN),
369
+ object: RECORD,
370
+ };
371
+ /**
372
+ * A member without `type` whose keywords are all of one kind (`{ required: [a] }`,
373
+ * `{ minItems: 1 }`) constrains only values of that kind. Where the schema's own `type`
374
+ * (or `nullable: true`, 3.0) names other kinds, their values pass the member.
375
+ */
376
+ function passing(cx, v, members, tys) {
377
+ return tys.map((ty, i) => {
378
+ const m = members[i];
379
+ if (!(m instanceof JsonObject) || !typeless(m))
380
+ return ty;
381
+ return widen(cx, v, hasObjectKeywords(m) ? "object" : "array", ty);
382
+ });
383
+ }
384
+ /** The kinds `type` names, and null where 3.0's `nullable: true` adds it; undefined without `type`. */
385
+ function typeKinds(cx, v) {
386
+ const t = v.get("type");
387
+ const kinds = typeof t === "string"
388
+ ? [t]
389
+ : Array.isArray(t)
390
+ ? t.filter((k) => typeof k === "string")
391
+ : undefined;
392
+ if (kinds === undefined)
393
+ return undefined;
394
+ return !cx.refSiblings && v.get("nullable") === true
395
+ ? [...kinds, "null"]
396
+ : kinds;
397
+ }
398
+ /** `ty`, a constraint on values of `kind` only, with the other kinds `type` names, which pass it. */
399
+ function widen(cx, v, kind, ty) {
400
+ const kinds = typeKinds(cx, v);
401
+ if (kinds === undefined)
402
+ return ty;
403
+ return union([
404
+ ty,
405
+ ...kinds.filter((k) => k !== kind && k in KIND).map((k) => KIND[k]),
406
+ ]);
407
+ }
408
+ /**
409
+ * What `dependentRequired`, `propertyNames`, `contains` and `not` say that TypeScript
410
+ * can, as parts of the schema; a warning where they say more.
411
+ */
412
+ function keywordParts(cx, v, at, left) {
413
+ const parts = [];
414
+ // A key present requires the keys it lists: it is absent, or they are all present.
415
+ // A key left out of this view is required on the other side only.
416
+ for (const [key, deps] of dependencies(v)) {
417
+ const names = deps.filter((d) => !left.has(d));
418
+ if (names.length === 0)
419
+ continue;
420
+ parts.push(widen(cx, v, "object", union([
421
+ { kind: "object", props: [{ key, ty: NEVER, optional: true }] },
422
+ {
423
+ kind: "object",
424
+ props: names.map((n) => ({ ...prop(n, UNKNOWN), present: true })),
425
+ },
426
+ ])));
427
+ }
428
+ const names = v.get("propertyNames");
429
+ if (names === false)
430
+ parts.push(widen(cx, v, "object", { kind: "map", props: [], index: NEVER }));
431
+ else if (names !== undefined &&
432
+ keyNames(names) === undefined &&
433
+ keyPattern(names) === undefined)
434
+ cx.warn(child(at, "propertyNames"), "propertyNames cannot be expressed in TypeScript; ignored");
435
+ // contains requires minContains items (1 if not given) that match it; TypeScript can say how many.
436
+ if (v.get("contains") !== undefined) {
437
+ const min = count(v, "minContains") ?? 1;
438
+ if (min > 0)
439
+ parts.push(widen(cx, v, "array", {
440
+ kind: "tuple",
441
+ items: Array.from({ length: min }, () => UNKNOWN),
442
+ min,
443
+ rest: UNKNOWN,
444
+ }));
445
+ cx.warn(child(at, "contains"), "contains: which items match it cannot be expressed in TypeScript; only how many is typed");
446
+ }
447
+ const n = v.get("not");
448
+ if (n !== undefined) {
449
+ const t = negation(n);
450
+ if (t !== undefined)
451
+ parts.push(t);
452
+ else if (excluded(v) === undefined)
453
+ cx.warn(child(at, "not"), "not cannot be expressed in TypeScript; ignored");
454
+ }
455
+ return parts;
456
+ }
457
+ /**
458
+ * The values `not` leaves, where TypeScript can say them: none for a schema that admits
459
+ * everything, the other kinds for `not: { type }`, the objects without a key for
460
+ * `not: { required }`. undefined otherwise (`not: false` leaves everything: unknown).
461
+ */
462
+ function negation(n) {
463
+ if (n === false)
464
+ return UNKNOWN;
465
+ // true, and anything else read as a schema that admits every value.
466
+ if (!(n instanceof JsonObject))
467
+ return NEVER;
468
+ const keys = n.entries.map(([k]) => k).filter((k) => !isAnnotation(k));
469
+ if (keys.length === 0)
470
+ return NEVER;
471
+ if (keys.length !== 1)
472
+ return undefined;
473
+ if (keys[0] === "type")
474
+ return otherKinds(n.get("type"));
475
+ const req = n.get("required");
476
+ if (keys[0] === "required" && Array.isArray(req))
477
+ return lacking(req);
478
+ return undefined;
479
+ }
480
+ /** The values of the kinds `type` does not name; undefined for `integer` without `number`. */
481
+ function otherKinds(t) {
482
+ const named = Array.isArray(t) ? t : [t];
483
+ // Without number, an integer is a number TypeScript cannot leave out.
484
+ if (named.includes("integer") && !named.includes("number"))
485
+ return undefined;
486
+ return union(["string", "number", "boolean", "null", "array", "object"]
487
+ .filter((k) => !named.includes(k))
488
+ .map((k) => KIND[k]));
489
+ }
490
+ /** The objects without one of these keys. */
491
+ function lacking(names) {
492
+ return union(names
493
+ .filter((r) => typeof r === "string")
494
+ .map((key) => ({
495
+ kind: "object",
496
+ props: [{ key, ty: NEVER, optional: true }],
497
+ })));
498
+ }
499
+ /**
500
+ * The values `if` does not admit, where TypeScript can say them: the other kinds for
501
+ * `type`, the objects without a key for `required`, and for `properties` the objects with
502
+ * a property it does not admit: of the other kinds for one with `type`, or of the values
503
+ * the schema and the schemas around it declare the property with (`enum`, `const`) that
504
+ * it rejects. undefined for any other `if`.
505
+ */
506
+ function refuted(cx, cond, around) {
507
+ if (cond === false)
508
+ return UNKNOWN;
509
+ if (!(cond instanceof JsonObject))
510
+ return NEVER;
511
+ const terms = [];
512
+ for (const [k, x] of cond.entries) {
513
+ if (isAnnotation(k))
514
+ continue;
515
+ if (k === "type") {
516
+ const t = otherKinds(x);
517
+ if (t === undefined)
518
+ return undefined;
519
+ terms.push(t);
520
+ }
521
+ else if (k === "required" && Array.isArray(x))
522
+ terms.push(lacking(x));
523
+ else if (k === "properties" && x instanceof JsonObject) {
524
+ for (const [p, s] of x.entries) {
525
+ const t = rejected(cx, s, declared(cx, around, p));
526
+ if (t === undefined)
527
+ return undefined;
528
+ if (t.kind !== "never")
529
+ terms.push({
530
+ kind: "object",
531
+ props: [{ key: p, ty: t, optional: false, present: true }],
532
+ });
533
+ }
534
+ }
535
+ else
536
+ return undefined;
537
+ }
538
+ return union(terms);
539
+ }
540
+ /** The values a property schema rejects among those it can be, where TypeScript can say them. */
541
+ function rejected(cx, s, values) {
542
+ if (s === false)
543
+ return UNKNOWN;
544
+ if (!(s instanceof JsonObject))
545
+ return NEVER;
546
+ const keys = s.entries.map(([k]) => k).filter((k) => !isAnnotation(k));
547
+ if (keys.length === 0)
548
+ return NEVER;
549
+ if (values !== undefined) {
550
+ const verdicts = values.map((x) => accepts(cx, s, x));
551
+ if (verdicts.every((a) => a !== undefined))
552
+ return union(values.filter((_, i) => !verdicts[i]).map(literal));
553
+ }
554
+ return keys.length === 1 && keys[0] === "type"
555
+ ? otherKinds(s.get("type"))
556
+ : undefined;
557
+ }
558
+ /**
559
+ * The values a property can have, where the schemas say a list of them (`enum`, `const`,
560
+ * `type: boolean`): in these schemas, the `$ref`s they have and their `allOf` members.
561
+ * undefined where none does.
562
+ */
563
+ function declared(cx, schemas, key, seen = new Set()) {
564
+ let out;
565
+ const meet = (values) => {
566
+ if (values === undefined)
567
+ return;
568
+ out =
569
+ out === undefined
570
+ ? values
571
+ : out.filter((x) => values.some((y) => sameValue(x, y)));
572
+ };
573
+ for (const s of schemas) {
574
+ meet(listed(cx, get(get(s, "properties"), key), new Set()));
575
+ const allOf = get(s, "allOf");
576
+ if (Array.isArray(allOf))
577
+ meet(declared(cx, allOf, key, seen));
578
+ const r = str(s, "$ref");
579
+ const target = r === undefined ? undefined : cx.tryLocate(r);
580
+ if (target !== undefined && !seen.has(target.uri)) {
581
+ seen.add(target.uri);
582
+ meet(cx.withBase(target.base, () => declared(cx, [target.value], key, seen)));
583
+ }
584
+ }
585
+ return out;
586
+ }
587
+ /** The values a schema lists (`enum`, `const`, `type: boolean` or `null`), through its `$ref`. */
588
+ function listed(cx, s, seen) {
589
+ if (!(s instanceof JsonObject))
590
+ return undefined;
591
+ const r = s.str("$ref");
592
+ const target = r === undefined ? undefined : cx.tryLocate(r);
593
+ if (target !== undefined && !seen.has(target.uri)) {
594
+ seen.add(target.uri);
595
+ const values = cx.withBase(target.base, () => listed(cx, target.value, seen));
596
+ if (values !== undefined)
597
+ return values;
598
+ }
599
+ const c = s.get("const");
600
+ if (c !== undefined)
601
+ return [c];
602
+ const e = s.get("enum");
603
+ if (Array.isArray(e))
604
+ return e;
605
+ const t = s.get("type");
606
+ if (t === "boolean")
607
+ return [true, false];
608
+ return t === "null" ? [null] : undefined;
609
+ }
610
+ /** Keywords `accepts` decides for a literal value. */
611
+ const VALUE_KEYWORDS = new Set([
612
+ "pattern",
613
+ "minLength",
614
+ "maxLength",
615
+ "minimum",
616
+ "maximum",
617
+ "exclusiveMinimum",
618
+ "exclusiveMaximum",
619
+ "multipleOf",
620
+ "format",
621
+ ]);
622
+ /** Whether a schema admits a value; undefined where it says what this cannot decide. */
623
+ function accepts(cx, s, x) {
624
+ const t = literal(x);
625
+ for (const [k, y] of s.entries) {
626
+ if (isAnnotation(k) || VALUE_KEYWORDS.has(k))
627
+ continue;
628
+ if (k === "type") {
629
+ const named = Array.isArray(y) ? y : [y];
630
+ if (!named.some((n) => typeof n === "string" && isOfKind(x, n)))
631
+ return false;
632
+ }
633
+ else if (k === "const") {
634
+ if (!sameValue(x, y))
635
+ return false;
636
+ }
637
+ else if (k === "enum" && Array.isArray(y)) {
638
+ if (!y.some((e) => sameValue(x, e)))
639
+ return false;
640
+ }
641
+ else
642
+ return undefined;
643
+ }
644
+ return admitting(cx, s)(t);
645
+ }
646
+ /** Whether a JSON value is of a kind `type` names. */
647
+ function isOfKind(x, kind) {
648
+ if (x === null)
649
+ return kind === "null";
650
+ if (typeof x === "string")
651
+ return kind === "string";
652
+ if (typeof x === "boolean")
653
+ return kind === "boolean";
654
+ if (x instanceof JsonNumber)
655
+ return (kind === "number" || (kind === "integer" && isWhole(decimal(x.text))));
656
+ return kind === (Array.isArray(x) ? "array" : "object");
657
+ }
658
+ /** Whether two JSON values are equal, numbers by value. */
659
+ function sameValue(a, b) {
660
+ return equalValues(literal(a), literal(b));
661
+ }
662
+ /**
663
+ * A member's type as the values it admits: one with keywords of one kind only (no `type`)
664
+ * admits every value of the other kinds too, of those the schema and the schemas around
665
+ * it can be (their `type`s; any kind where none has one).
666
+ */
667
+ function anyKind(cx, v, m, ty) {
668
+ if (!(m instanceof JsonObject) || !typeless(m))
669
+ return ty;
670
+ return orOther(cx, v, hasObjectKeywords(m) ? "object" : "array", ty);
671
+ }
672
+ /**
673
+ * `ty`, a constraint on values of `kind` only, with the values of the other kinds the
674
+ * schema and the schemas around it can be (their `type`s; any kind where none has one).
675
+ */
676
+ function orOther(cx, v, kind, ty) {
677
+ return union([
678
+ ty,
679
+ ...contextKinds(cx, v)
680
+ .filter((k) => k !== kind)
681
+ .map((k) => KIND[k]),
682
+ ]);
683
+ }
684
+ /** The kinds the schema and the schemas around it can be: those their `type`s all name; any where none has one. */
685
+ function contextKinds(cx, v) {
686
+ let kinds = [
687
+ "string",
688
+ "number",
689
+ "integer",
690
+ "boolean",
691
+ "null",
692
+ "array",
693
+ "object",
144
694
  ];
695
+ for (const s of [v, ...cx.around]) {
696
+ const named = typeKinds(cx, s);
697
+ if (named !== undefined)
698
+ kinds = kinds.filter((k) => named.includes(k) || (k === "integer" && named.includes("number")));
699
+ }
700
+ return kinds;
701
+ }
702
+ const nothingEvaluated = () => ({
703
+ names: new Set(),
704
+ patterns: [],
705
+ all: false,
706
+ length: 0,
707
+ rest: false,
708
+ contains: false,
709
+ undecided: false,
710
+ keys: new Set(),
711
+ branches: [],
712
+ });
713
+ /** Adds what `b` evaluates to `a`. */
714
+ function evaluateBoth(a, b) {
715
+ for (const n of b.names)
716
+ a.names.add(n);
717
+ a.patterns.push(...b.patterns);
718
+ a.all ||= b.all;
719
+ a.length = Math.max(a.length, b.length);
720
+ a.rest ||= b.rest;
721
+ a.contains ||= b.contains;
722
+ a.undecided ||= b.undecided;
723
+ for (const k of b.keys)
724
+ a.keys.add(k);
725
+ a.branches.push(...b.branches);
726
+ }
727
+ /**
728
+ * What a schema evaluates (see `Evaluated`); its own `unevaluated*` too unless `top`, the
729
+ * schema they are read for.
730
+ */
731
+ function evaluates(cx, s, at, top, seen) {
732
+ const ev = nothingEvaluated();
733
+ if (!(s instanceof JsonObject))
734
+ return ev;
735
+ const r = s.str("$ref");
736
+ if (r !== undefined) {
737
+ const target = cx.locate(r, at);
738
+ if (!seen.has(target.uri)) {
739
+ seen.add(target.uri);
740
+ evaluateBoth(ev, cx.withBase(target.base, () => evaluates(cx, target.value, target.where, false, seen)));
741
+ }
742
+ // In 3.0 the keywords next to $ref are ignored.
743
+ if (!cx.refSiblings)
744
+ return ev;
745
+ }
746
+ const props = s.get("properties");
747
+ for (const [k] of props instanceof JsonObject ? props.entries : []) {
748
+ ev.names.add(k);
749
+ ev.keys.add(k);
750
+ }
751
+ const pp = s.get("patternProperties");
752
+ if (pp instanceof JsonObject)
753
+ ev.patterns.push(...pp.entries.map(([k]) => k));
754
+ ev.all =
755
+ s.get("additionalProperties") !== undefined ||
756
+ (!top && s.get("unevaluatedProperties") !== undefined);
757
+ const prefix = s.get("prefixItems");
758
+ ev.length = Array.isArray(prefix) ? prefix.length : 0;
759
+ ev.rest =
760
+ s.get("items") !== undefined ||
761
+ (!top && s.get("unevaluatedItems") !== undefined);
762
+ ev.contains = s.get("contains") !== undefined;
763
+ for (const k of requiredKeys(cx, s))
764
+ ev.keys.add(k);
765
+ for (const [k, names] of dependencies(s)) {
766
+ ev.keys.add(k);
767
+ for (const n of names)
768
+ ev.keys.add(n);
769
+ }
770
+ for (const k of keyNames(s.get("propertyNames")) ?? [])
771
+ ev.keys.add(k);
772
+ const group = leftOutKeys(cx, s);
773
+ for (const k of cx.leftOutIn(s))
774
+ group.add(k);
775
+ const allOf = s.get("allOf");
776
+ for (const [i, m] of (Array.isArray(allOf) ? allOf : []).entries())
777
+ evaluateBoth(ev, cx.withAround(s, () => evaluates(cx, m, child(child(at, "allOf"), String(i)), false, seen)));
778
+ // A member, if or dependent schema evaluates where it matches.
779
+ const branch = (cond, e) => {
780
+ for (const k of e.keys)
781
+ ev.keys.add(k);
782
+ ev.contains ||= e.contains;
783
+ ev.undecided ||= e.undecided;
784
+ ev.branches.push({ cond, ev: e });
785
+ };
786
+ const inner = (m, where) => cx.withAround(s, () => evaluates(cx, m, where, false, seen));
787
+ for (const key of ["oneOf", "anyOf"]) {
788
+ const members = s.get(key);
789
+ if (!Array.isArray(members))
790
+ continue;
791
+ const tys = membersIn(cx, s, members, group, child(at, key));
792
+ for (const [i, m] of members.entries())
793
+ branch(tys[i], inner(m, child(child(at, key), String(i))));
794
+ }
795
+ const cond = s.get("if");
796
+ if (cond !== undefined) {
797
+ const then = s.get("then") ?? true;
798
+ const otherwise = s.get("else") ?? true;
799
+ const [i, t, e] = membersIn(cx, s, [cond, then, otherwise], group, at, [
800
+ "if",
801
+ "then",
802
+ "else",
803
+ ]);
804
+ // if and then evaluate where if admits the value; else where it does not.
805
+ const both = inner(cond, child(at, "if"));
806
+ evaluateBoth(both, inner(then, child(at, "then")));
807
+ branch(inter([i, t]), both);
808
+ const not = refuted(cx, cond, [s, ...cx.around]);
809
+ if (not === undefined)
810
+ ev.undecided ||= otherwise !== true;
811
+ else
812
+ branch(inter([not, e]), inner(otherwise, child(at, "else")));
813
+ }
814
+ const ds = s.get("dependentSchemas");
815
+ for (const [k, d] of ds instanceof JsonObject ? ds.entries : [])
816
+ branch({
817
+ kind: "object",
818
+ props: [{ key: k, ty: UNKNOWN, optional: false, present: true }],
819
+ }, inner(d, child(child(at, "dependentSchemas"), k)));
820
+ return ev;
821
+ }
822
+ /** The conditions under which some branch of `ev` evaluates `key`. */
823
+ function evaluating(ev, key) {
824
+ return ev.branches.flatMap(({ cond, ev: e }) => e.all || e.names.has(key) || e.patterns.some((p) => matches(p, key))
825
+ ? [cond]
826
+ : evaluating(e, key).map((c) => inter([cond, c])));
827
+ }
828
+ /** Each branch of `ev` that evaluates more items than `length`: its condition and how many, or every one. */
829
+ function evaluatingItems(ev, length) {
830
+ return ev.branches.flatMap(({ cond, ev: e }) => {
831
+ const n = Math.max(length, e.length);
832
+ const own = { cond, length: n, rest: e.rest };
833
+ return [
834
+ own,
835
+ ...evaluatingItems(e, n).map((x) => ({
836
+ ...x,
837
+ cond: inter([cond, x.cond]),
838
+ })),
839
+ ];
840
+ });
841
+ }
842
+ /**
843
+ * `unevaluatedProperties` / `unevaluatedItems` next to an applicator: a key the schema
844
+ * names that nothing evaluates wherever it is present is absent or as the keyword says,
845
+ * and items past those evaluated are as it says (none for `false`).
846
+ */
847
+ function unevaluatedParts(cx, v, at) {
848
+ const up = v.get("unevaluatedProperties");
849
+ const ui = v.get("unevaluatedItems");
850
+ const asked = (x) => x !== undefined && x !== true;
851
+ if (!asked(up) && !asked(ui))
852
+ return [];
853
+ if (APPLICATORS.every((k) => v.get(k) === undefined))
854
+ return [];
855
+ const ev = evaluates(cx, v, at, true, new Set());
856
+ const warn = (key, x) => {
857
+ if (asked(x))
858
+ cx.warn(child(at, key), `${key} next to an applicator cannot be expressed in TypeScript; ignored`);
859
+ };
860
+ if (ev.undecided) {
861
+ warn("unevaluatedProperties", up);
862
+ warn("unevaluatedItems", ui);
863
+ return [];
864
+ }
865
+ const parts = [];
866
+ if (asked(up) && !ev.all) {
867
+ const ty = schema(cx, up, child(at, "unevaluatedProperties"));
868
+ // The schemas this one is a member of name keys of the same object, which it does not evaluate.
869
+ for (const s of cx.around)
870
+ for (const k of namedKeys(cx, s))
871
+ ev.keys.add(k);
872
+ for (const key of ev.keys) {
873
+ if (ev.names.has(key) || ev.patterns.some((p) => matches(p, key)))
874
+ continue;
875
+ parts.push(orOther(cx, v, "object", union([
876
+ { kind: "object", props: [{ key, ty, optional: true }] },
877
+ ...evaluating(ev, key),
878
+ ])));
879
+ }
880
+ }
881
+ if (asked(ui) && !ev.rest) {
882
+ if (ev.contains)
883
+ warn("unevaluatedItems", ui);
884
+ else {
885
+ const ty = schema(cx, ui, child(at, "unevaluatedItems"));
886
+ const upTo = (n) => ty.kind === "never"
887
+ ? { kind: "tuple", items: Array(n).fill(UNKNOWN), min: 0 }
888
+ : n === 0
889
+ ? arrayTy(ty)
890
+ : {
891
+ kind: "tuple",
892
+ items: Array(n).fill(UNKNOWN),
893
+ min: 0,
894
+ rest: ty,
895
+ };
896
+ parts.push(orOther(cx, v, "array", union([
897
+ upTo(ev.length),
898
+ ...evaluatingItems(ev, ev.length).map((b) => b.rest ? b.cond : inter([b.cond, upTo(b.length)])),
899
+ ])));
900
+ }
901
+ }
902
+ return parts;
903
+ }
904
+ /** `dependentRequired`: each key and the keys it requires. */
905
+ function dependencies(v) {
906
+ const dr = v.get("dependentRequired");
907
+ return (dr instanceof JsonObject ? dr.entries : []).map(([key, deps]) => [
908
+ key,
909
+ Array.isArray(deps)
910
+ ? deps.filter((d) => typeof d === "string")
911
+ : [],
912
+ ]);
913
+ }
914
+ /** The values `not: { enum }` or `not: { const }` leave out; undefined for any other `not`. */
915
+ function excluded(v) {
916
+ const n = v.get("not");
917
+ if (!(n instanceof JsonObject))
918
+ return undefined;
919
+ const keys = n.entries.map(([k]) => k).filter((k) => !isAnnotation(k));
920
+ if (keys.length !== 1)
921
+ return undefined;
922
+ const e = n.get("enum");
923
+ if (keys[0] === "enum" && Array.isArray(e))
924
+ return e.map(literal);
925
+ const c = n.get("const");
926
+ return keys[0] === "const" && c !== undefined ? [literal(c)] : undefined;
927
+ }
928
+ /** The keys `propertyNames: { enum }` or `{ const }` allow; undefined for any other. */
929
+ function keyNames(names) {
930
+ if (!(names instanceof JsonObject))
931
+ return undefined;
932
+ const keys = names.entries.map(([k]) => k).filter((k) => !isAnnotation(k));
933
+ if (keys.length !== 1)
934
+ return undefined;
935
+ const e = names.get("enum");
936
+ const c = names.get("const");
937
+ const values = keys[0] === "enum" && Array.isArray(e) ? e : keys[0] === "const" ? [c] : [];
938
+ const strings = values.filter((x) => typeof x === "string");
939
+ return strings.length > 0 ? strings : undefined;
940
+ }
941
+ /** Whether a schema says nothing but keywords of one kind, without `type`. */
942
+ function typeless(m) {
943
+ return (["type", "$ref", "const", "enum", "allOf", "oneOf", "anyOf"].every((k) => m.get(k) === undefined) &&
944
+ (hasObjectKeywords(m) || hasArrayKeywords(m)));
945
+ }
946
+ /**
947
+ * Members, converted knowing the keys the group leaves out of this view. A member that
948
+ * is only a `$ref` to a schema naming one of them is written out without it: the
949
+ * reference's own view would have it.
950
+ */
951
+ function membersIn(cx, parent, members, group, at, tokens = members.map((_, i) => String(i))) {
952
+ // Members are the same value, so they are where it is, and the parent's keywords apply to it too.
953
+ const here = cx.here;
954
+ return cx.withLeftOut(members, group, () => members.map((m, i) => cx.withAround(parent, () => cx.withRaw(here, () => {
955
+ const where = child(at, tokens[i]);
956
+ const r = str(m, "$ref");
957
+ if (r === undefined ||
958
+ group.size === 0 ||
959
+ !m.entries.every(([k]) => k === "$ref" || isAnnotation(k)))
960
+ return schema(cx, m, where);
961
+ const { value, base, uri, where: there } = cx.locate(r, where);
962
+ const named = cx.withBase(base, () => namedKeys(cx, value));
963
+ const own = cx.withBase(base, () => leftOutKeys(cx, value));
964
+ if (!named.some((k) => group.has(k) && !own.has(k)) || !cx.enter(uri))
965
+ return schema(cx, m, where);
966
+ try {
967
+ return cx.withBase(base, () => cx.withLeftOut([value], group, () => schema(cx, value, there)));
968
+ }
969
+ finally {
970
+ cx.leave();
971
+ }
972
+ }))));
973
+ }
974
+ /** A closed oneOf / anyOf member admits no key another member names. */
975
+ function closedAmong(cx, members, tys) {
976
+ const named = members.map((m) => namedKeys(cx, m));
977
+ return tys.map((t, i) => {
978
+ const keys = closedMember(cx, members[i]);
979
+ if (keys === undefined || keys.size === 0)
980
+ return t;
981
+ const others = named.flatMap((n, j) => (j === i ? [] : n));
982
+ return forbid(t, [...new Set(others)].filter((k) => !keys.has(k)));
983
+ });
984
+ }
985
+ /** `t` without these keys: `k?: never`, in its own object type where it is one. */
986
+ function forbid(t, keys) {
987
+ if (keys.length === 0)
988
+ return t;
989
+ const props = keys.map((key) => ({ key, ty: NEVER, optional: true }));
990
+ if (t.kind !== "object")
991
+ return inter([t, { kind: "object", props }]);
992
+ const have = new Set(t.props.map((p) => p.key));
993
+ return {
994
+ kind: "object",
995
+ props: [...t.props, ...props.filter((p) => !have.has(p.key))],
996
+ };
997
+ }
998
+ /**
999
+ * oneOf admits a value only one member admits, so a literal or `null` two members
1000
+ * admit is in neither. TypeScript can leave it out only where no member admits it by
1001
+ * its kind (`string` for `"a"`); other members, refs among them, are not counted.
1002
+ */
1003
+ function shared(tys) {
1004
+ const listed = (t) => (t.kind === "union" ? t.items : [t]);
1005
+ const same = (a, b) => a.kind === b.kind &&
1006
+ (a.kind !== "lit" || a.text === b.text);
1007
+ const values = tys
1008
+ .flatMap(listed)
1009
+ .filter((m) => m.kind === "lit" || m.kind === "null");
1010
+ const out = new Set();
1011
+ for (const value of values) {
1012
+ if (tys.some((t) => listed(t).some((m) => byKind(m, value))))
1013
+ continue;
1014
+ if (tys.filter((t) => listed(t).some((m) => same(m, value))).length > 1)
1015
+ out.add(value);
1016
+ }
1017
+ if (out.size === 0)
1018
+ return tys;
1019
+ const drop = [...out];
1020
+ return tys.map((t) => union(listed(t).filter((m) => !drop.some((d) => same(m, d)))));
1021
+ }
1022
+ /** Whether a type may admit a value (from `const` / `enum`) other than by listing it. */
1023
+ function mayAdmit(m, x) {
1024
+ const of = (kinds, t) => kinds.includes(t.kind);
1025
+ const objects = ["object", "map", "record"];
1026
+ if (of(["lit", "null", "blob"], m))
1027
+ return false;
1028
+ if (of(["string", "number", "integer", "boolean"], m))
1029
+ return byKind(m, x);
1030
+ if (of(objects, m))
1031
+ return of(objects, x);
1032
+ if (of(["array", "tuple"], m))
1033
+ return x.kind === "tuple";
1034
+ return true;
1035
+ }
1036
+ /** Whether a member admits a literal by its kind, not by listing it. */
1037
+ function byKind(m, value) {
1038
+ if (m.kind === "unknown")
1039
+ return true;
1040
+ if (value.kind !== "lit")
1041
+ return false;
1042
+ const text = value.text;
1043
+ if (text.startsWith('"'))
1044
+ return m.kind === "string";
1045
+ if (text === "true" || text === "false")
1046
+ return m.kind === "boolean";
1047
+ return (m.kind === "number" || (m.kind === "integer" && isWhole(decimal(text))));
145
1048
  }
146
1049
  /**
147
1050
  * oneOf admits a value only one member admits. A member that asks nothing but some
@@ -152,8 +1055,9 @@ function requiredKeys(cx, s) {
152
1055
  * all of another's keys admits nothing. Other members stay as they are: TypeScript
153
1056
  * cannot say what they do not admit.
154
1057
  */
155
- function exclusive(cx, members, tys, at) {
156
- const keys = members.map((m, i) => keysOnly(cx, m, child(at, String(i))));
1058
+ function exclusive(cx, members, tys, at, left) {
1059
+ // A key left out of this view is required on the other side only.
1060
+ const keys = members.map((m, i) => keysOnly(cx, m, child(at, String(i)))?.filter((k) => !left.has(k)));
157
1061
  const without = (key, ty) => ({ key, ty, optional: true });
158
1062
  return tys.map((t, i) => {
159
1063
  const own = keys[i];
@@ -240,12 +1144,13 @@ function follow(cx, r, at, f) {
240
1144
  }
241
1145
  /** Keywords that only apply to objects; their presence implies `type: object`. */
242
1146
  function hasObjectKeywords(v) {
243
- return [
1147
+ return ([
244
1148
  "properties",
245
1149
  "patternProperties",
246
1150
  "additionalProperties",
247
1151
  "required",
248
- ].some((k) => v.get(k) !== undefined);
1152
+ ].some((k) => v.get(k) !== undefined) ||
1153
+ unevaluated(v, "unevaluatedProperties") !== undefined);
249
1154
  }
250
1155
  /** The type given by `type`, or inferred from object / array keywords; `unknown` when neither says anything. */
251
1156
  function own(cx, v, at) {
@@ -256,9 +1161,24 @@ function own(cx, v, at) {
256
1161
  return union(type.map((t) => typed(cx, v, t, at)));
257
1162
  if (hasObjectKeywords(v))
258
1163
  return object(cx, v, at);
259
- if (v.get("items") !== undefined || v.get("prefixItems") !== undefined)
1164
+ if (hasArrayKeywords(v))
260
1165
  return array(cx, v, at);
261
- return UNKNOWN;
1166
+ // Keywords for strings and numbers without type constrain those kinds alone.
1167
+ const s = text(v);
1168
+ const n = numeric(cx, v, false);
1169
+ if (s === STRING && n === NUMBER)
1170
+ return UNKNOWN;
1171
+ return union(contextKinds(cx, v).map((k) => k === "string"
1172
+ ? s
1173
+ : k === "number"
1174
+ ? n
1175
+ : k === "integer"
1176
+ ? numeric(cx, v, true)
1177
+ : KIND[k]));
1178
+ }
1179
+ /** Keywords that only apply to arrays and that the type reads; their presence implies `type: array`. */
1180
+ function hasArrayKeywords(v) {
1181
+ return (["items", "prefixItems", "minItems", "maxItems"].some((k) => v.get(k) !== undefined) || unevaluated(v, "unevaluatedItems") !== undefined);
262
1182
  }
263
1183
  function list(cx, items, at) {
264
1184
  return items.map((item, i) => schema(cx, item, child(at, String(i))));
@@ -285,7 +1205,15 @@ function literal(v) {
285
1205
  * in another file, under a key of its own; any other target is expanded inline.
286
1206
  */
287
1207
  function reference(cx, r, at) {
288
- if (r.startsWith(SCHEMA_PREFIX) && cx.inDocument) {
1208
+ // Where bytes are bytes, a schema with them is written out here: its named type,
1209
+ // which is the same wherever it is used, has text.
1210
+ const here = cx.here;
1211
+ if (here !== undefined) {
1212
+ const located = cx.locate(r, at);
1213
+ if (cx.withBase(located.base, () => binaryAt(cx, located.value, here)))
1214
+ return expand(cx, located, cx.componentKey(located.value));
1215
+ }
1216
+ if (r.startsWith(SCHEMA_PREFIX) && cx.inDocument && !cx.dynamicScope) {
289
1217
  const rest = r.slice(SCHEMA_PREFIX.length);
290
1218
  if (!rest.includes("/")) {
291
1219
  const name = unescapeToken(rest);
@@ -295,7 +1223,11 @@ function reference(cx, r, at) {
295
1223
  }
296
1224
  }
297
1225
  const located = cx.locate(r, at);
298
- const { value: target, base, uri, where } = located;
1226
+ const { value: target, base, uri } = located;
1227
+ // A named type is the target as reached from the document. Where a $dynamicRef in it
1228
+ // reaches another $dynamicAnchor from here, it is written out here.
1229
+ if (cx.dynamicScope && rescoped(cx, target, base))
1230
+ return expand(cx, located, cx.componentKey(target));
299
1231
  // An $anchor, $id or file naming a component schema refers to that type (except
300
1232
  // in the component's own definition, which is what defines it).
301
1233
  const key = cx.componentKey(target);
@@ -303,15 +1235,65 @@ function reference(cx, r, at) {
303
1235
  if (at !== child("#/components/schemas", key))
304
1236
  return ref(key, cx.mode);
305
1237
  }
306
- else if (cx.isFile(base)) {
1238
+ else if (cx.isFile(base) || cx.isHoisted(uri)) {
307
1239
  return ref(cx.hoist(target, located), cx.mode);
308
1240
  }
309
- if (!cx.enter(uri)) {
310
- cx.warn(at, `circular $ref expanded as unknown: ${r}`);
311
- return UNKNOWN;
312
- }
1241
+ return expand(cx, located, key);
1242
+ }
1243
+ /**
1244
+ * Whether a `$dynamicRef` in a schema (through its `$ref`s) reaches another
1245
+ * `$dynamicAnchor` from where it is now than from the document, through its own resource.
1246
+ */
1247
+ function rescoped(cx, target, base) {
1248
+ for (const name of dynamicNames(cx, target, base, new Set()))
1249
+ if (cx.dynamicTarget(name, [...cx.scope, base]) !==
1250
+ cx.dynamicTarget(name, [base]))
1251
+ return true;
1252
+ return false;
1253
+ }
1254
+ /** The names of the `$dynamicAnchor`s the `$dynamicRef`s in a schema reach, through its `$ref`s. */
1255
+ function dynamicNames(cx, v, base, seen) {
1256
+ const out = new Set();
1257
+ const walk = (x, base) => {
1258
+ if (Array.isArray(x)) {
1259
+ for (const y of x)
1260
+ walk(y, base);
1261
+ return;
1262
+ }
1263
+ if (!(x instanceof JsonObject))
1264
+ return;
1265
+ const id = x.str("$id");
1266
+ const here = id === undefined ? base : cx.withBase(base, () => cx.baseOf(id));
1267
+ for (const key of ["$ref", "$dynamicRef"]) {
1268
+ const r = x.str(key);
1269
+ const target = r === undefined ? undefined : cx.withBase(here, () => cx.tryLocate(r));
1270
+ if (target === undefined)
1271
+ continue;
1272
+ if (key === "$dynamicRef" && cx.isDynamicAnchor(target.uri))
1273
+ out.add(new URL(target.uri).hash.slice(1));
1274
+ if (!seen.has(target.uri)) {
1275
+ seen.add(target.uri);
1276
+ walk(target.value, target.base);
1277
+ }
1278
+ }
1279
+ for (const [k, y] of x.entries)
1280
+ if (!["const", "enum", "default", "example", "examples"].includes(k))
1281
+ walk(y, here);
1282
+ };
1283
+ walk(v, base);
1284
+ return out;
1285
+ }
1286
+ /** A `$ref`'s target written out where it is used, in the position the `$ref` is in. */
1287
+ function expand(cx, located, key) {
1288
+ const { value: target, base, uri, where } = located;
1289
+ // A schema reached again while it is expanded inline is a cycle: a component is
1290
+ // its name, another schema gets one, as a schema in another file does.
1291
+ if (!cx.enter(uri))
1292
+ return ref(key ?? cx.hoist(target, located), cx.mode);
313
1293
  try {
314
- return cx.withBase(base, () => schema(cx, target, where));
1294
+ const t = cx.inResource(base, () => cx.withRaw(cx.here, () => schema(cx, target, where)));
1295
+ // It reached itself, so it has a name now: every view refers to it by that.
1296
+ return cx.isHoisted(uri) ? ref(cx.hoist(target, located), cx.mode) : t;
315
1297
  }
316
1298
  finally {
317
1299
  cx.leave();
@@ -320,11 +1302,14 @@ function reference(cx, r, at) {
320
1302
  function typed(cx, v, t, at) {
321
1303
  switch (t) {
322
1304
  case "string":
323
- return isBinaryString(v) ? BLOB : STRING;
1305
+ // Bytes are a Blob as a body or a part; in JSON, a form or a parameter, text.
1306
+ return isBinaryString(v) && (cx.here === "body" || cx.here === "part")
1307
+ ? BLOB
1308
+ : text(v);
324
1309
  case "integer":
325
- return INTEGER;
1310
+ return numeric(cx, v, true);
326
1311
  case "number":
327
- return NUMBER;
1312
+ return numeric(cx, v, false);
328
1313
  case "boolean":
329
1314
  return BOOLEAN;
330
1315
  case "null":
@@ -337,6 +1322,231 @@ function typed(cx, v, t, at) {
337
1322
  return UNKNOWN; // a type JSON Schema does not have says nothing
338
1323
  }
339
1324
  }
1325
+ /**
1326
+ * A string: `""` where its lengths admit only it (`maxLength: 0`), none where they admit
1327
+ * none, and the template literal types of its `pattern` where they say its strings.
1328
+ */
1329
+ function text(v) {
1330
+ const max = count(v, "maxLength");
1331
+ if (max !== undefined && (count(v, "minLength") ?? 0) > max)
1332
+ return NEVER;
1333
+ if (max === 0)
1334
+ return lit('""');
1335
+ const pattern = v.str("pattern");
1336
+ return (pattern === undefined ? undefined : patternType(pattern)) ?? STRING;
1337
+ }
1338
+ /**
1339
+ * `numeric`'s type for each schema object, read once: a schema is converted again for
1340
+ * each view and place it is reached from, and its values can be thousands.
1341
+ */
1342
+ const numerics = new WeakMap();
1343
+ /**
1344
+ * A number (an integer if `integer`), or the values its bounds admit where they are
1345
+ * finitely many: the integers, or the multiples of `multipleOf`, between them, as long
1346
+ * as TypeScript builds their union.
1347
+ */
1348
+ function numeric(cx, v, integer) {
1349
+ // The bounds read the same in a document: as 3.0's or as 3.1's.
1350
+ const key = `${integer} ${cx.refSiblings}`;
1351
+ let known = numerics.get(v);
1352
+ if (known === undefined) {
1353
+ known = new Map();
1354
+ numerics.set(v, known);
1355
+ }
1356
+ const ty = known.get(key) ?? valuesBetween(cx, v, integer);
1357
+ known.set(key, ty);
1358
+ return ty;
1359
+ }
1360
+ function valuesBetween(cx, v, integer) {
1361
+ const { low, high } = bounds(cx, v);
1362
+ const any = integer ? INTEGER : NUMBER;
1363
+ if (low === undefined || high === undefined)
1364
+ return any;
1365
+ const order = compare(low.at, high.at);
1366
+ if (order > 0 || (order === 0 && (low.open || high.open)))
1367
+ return NEVER;
1368
+ const m = v.get("multipleOf");
1369
+ const step = m instanceof JsonNumber && decimal(m.text).digits > 0n
1370
+ ? decimal(m.text)
1371
+ : undefined;
1372
+ if (!integer && step === undefined)
1373
+ return order === 0 ? lit(low.text) : NUMBER;
1374
+ // The values are the whole multiples of a unit: the step, or for integers the least
1375
+ // integer that is a multiple of it (1 without one).
1376
+ const unit = !integer
1377
+ ? step
1378
+ : step === undefined
1379
+ ? { digits: 1n, scale: 0 }
1380
+ : {
1381
+ digits: step.digits / gcd(step.digits, 10n ** BigInt(step.scale)),
1382
+ scale: 0,
1383
+ };
1384
+ // From the least multiple above low to the greatest below high.
1385
+ const above = (b) => {
1386
+ const [x, u] = aligned(b.at, unit);
1387
+ const q = x / u + (x % u > 0n ? 1n : 0n);
1388
+ return q + (b.open && x % u === 0n ? 1n : 0n);
1389
+ };
1390
+ const below = (b) => {
1391
+ const [x, u] = aligned(b.at, unit);
1392
+ const q = x / u - (x % u < 0n ? 1n : 0n);
1393
+ return q - (b.open && x % u === 0n ? 1n : 0n);
1394
+ };
1395
+ const first = above(low);
1396
+ const last = below(high);
1397
+ if (first > last)
1398
+ return NEVER;
1399
+ if (last - first >= BigInt(MAX_UNION))
1400
+ return any;
1401
+ const values = [];
1402
+ for (let k = first; k <= last; k++) {
1403
+ const value = lit(unit.scale === 0
1404
+ ? (k * unit.digits).toString()
1405
+ : decimalText({ digits: k * unit.digits, scale: unit.scale }));
1406
+ boundedBy.set(value, v);
1407
+ values.push(value);
1408
+ }
1409
+ // Distinct literals in order are a union as it is.
1410
+ return values.length === 1
1411
+ ? values[0]
1412
+ : { kind: "union", items: values };
1413
+ }
1414
+ /** The schema whose bounds each of `valuesBetween`'s values comes from: they admit it already. */
1415
+ const boundedBy = new WeakMap();
1416
+ function gcd(a, b) {
1417
+ return b === 0n ? a : gcd(b, a % b);
1418
+ }
1419
+ /** A decimal as JSON writes it: `-1.25`, `3`. */
1420
+ function decimalText(d) {
1421
+ const sign = d.digits < 0n ? "-" : "";
1422
+ const digits = (d.digits < 0n ? -d.digits : d.digits)
1423
+ .toString()
1424
+ .padStart(d.scale + 1, "0");
1425
+ const int = digits.slice(0, digits.length - d.scale);
1426
+ const frac = digits.slice(digits.length - d.scale).replace(/0+$/, "");
1427
+ return `${sign}${int}${frac === "" ? "" : `.${frac}`}`;
1428
+ }
1429
+ /**
1430
+ * The tightest lower and upper bound. In 3.1 and 3.2 (JSON Schema 2020-12)
1431
+ * `exclusiveMinimum` / `exclusiveMaximum` are numbers; in 3.0 they are booleans that
1432
+ * make `minimum` / `maximum` exclusive.
1433
+ */
1434
+ function bounds(cx, v) {
1435
+ const num = (key, open) => {
1436
+ const n = v.get(key);
1437
+ return n instanceof JsonNumber
1438
+ ? { at: decimal(n.text), text: n.text, open }
1439
+ : undefined;
1440
+ };
1441
+ const side = (inclusive, exclusive, sign) => {
1442
+ if (!cx.refSiblings)
1443
+ return num(inclusive, v.get(exclusive) === true);
1444
+ const closed = num(inclusive, false);
1445
+ const open = num(exclusive, true);
1446
+ if (open === undefined)
1447
+ return closed;
1448
+ // The exclusive one is tighter unless the inclusive one is past it.
1449
+ return closed !== undefined && compare(closed.at, open.at) * sign > 0
1450
+ ? closed
1451
+ : open;
1452
+ };
1453
+ const low = side("minimum", "exclusiveMinimum", 1);
1454
+ const high = side("maximum", "exclusiveMaximum", -1);
1455
+ return {
1456
+ ...(low === undefined ? {} : { low }),
1457
+ ...(high === undefined ? {} : { high }),
1458
+ };
1459
+ }
1460
+ /**
1461
+ * Whether a literal is one of the values a schema's own keywords for its kind admit:
1462
+ * lengths and `pattern` for strings, bounds and `multipleOf` for numbers. A pattern
1463
+ * JavaScript cannot read admits every string. The keywords are read once, for the many
1464
+ * literals a schema can list.
1465
+ */
1466
+ function admitting(cx, v) {
1467
+ const minLength = count(v, "minLength") ?? 0;
1468
+ const maxLength = count(v, "maxLength");
1469
+ const pattern = v.str("pattern");
1470
+ const { low, high } = bounds(cx, v);
1471
+ const m = v.get("multipleOf");
1472
+ const step = m instanceof JsonNumber ? decimal(m.text) : undefined;
1473
+ // Without these keywords, every value is admitted: an enum's thousands are not looked at.
1474
+ if (minLength === 0 &&
1475
+ maxLength === undefined &&
1476
+ pattern === undefined &&
1477
+ low === undefined &&
1478
+ high === undefined &&
1479
+ step === undefined)
1480
+ return () => true;
1481
+ const beyond = (n, b, sign) => {
1482
+ if (b === undefined)
1483
+ return false;
1484
+ const order = compare(n, b.at) * sign;
1485
+ return order < 0 || (order === 0 && b.open);
1486
+ };
1487
+ return (t) => {
1488
+ if (t.kind !== "lit" || boundedBy.get(t) === v)
1489
+ return true;
1490
+ if (t.text.startsWith('"')) {
1491
+ const s = JSON.parse(t.text);
1492
+ const length = [...s].length;
1493
+ if (length < minLength)
1494
+ return false;
1495
+ if (maxLength !== undefined && length > maxLength)
1496
+ return false;
1497
+ return pattern === undefined || matches(pattern, s);
1498
+ }
1499
+ if (t.text === "true" || t.text === "false")
1500
+ return true;
1501
+ const n = decimal(t.text);
1502
+ if (beyond(n, low, 1) || beyond(n, high, -1))
1503
+ return false;
1504
+ return step === undefined || isMultiple(n, step);
1505
+ };
1506
+ }
1507
+ /** Patterns compiled once each; null for one JavaScript cannot read. */
1508
+ const compiled = new Map();
1509
+ /** Whether `s` matches an ECMA-262 pattern; true when JavaScript cannot read the pattern. */
1510
+ function matches(pattern, s) {
1511
+ let re = compiled.get(pattern);
1512
+ if (re === undefined) {
1513
+ try {
1514
+ re = new RegExp(pattern, "u");
1515
+ }
1516
+ catch {
1517
+ re = null;
1518
+ }
1519
+ compiled.set(pattern, re);
1520
+ }
1521
+ return re === null || re.test(s);
1522
+ }
1523
+ function decimal(text) {
1524
+ // A JsonNumber's text is in JSON's grammar.
1525
+ const [, int = "", frac = "", exp = "0"] = /^(-?\d+)(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/.exec(text);
1526
+ const scale = frac.length - Number(exp);
1527
+ const digits = BigInt(int + frac);
1528
+ return scale >= 0
1529
+ ? { digits, scale }
1530
+ : { digits: digits * 10n ** BigInt(-scale), scale: 0 };
1531
+ }
1532
+ /** a and b over one scale. */
1533
+ function aligned(a, b) {
1534
+ const scale = Math.max(a.scale, b.scale);
1535
+ return [
1536
+ a.digits * 10n ** BigInt(scale - a.scale),
1537
+ b.digits * 10n ** BigInt(scale - b.scale),
1538
+ ];
1539
+ }
1540
+ function compare(a, b) {
1541
+ const [x, y] = aligned(a, b);
1542
+ return x < y ? -1 : x > y ? 1 : 0;
1543
+ }
1544
+ /** Whether a is a whole multiple of m; a `multipleOf` that is not positive admits all. */
1545
+ function isMultiple(a, m) {
1546
+ const [x, y] = aligned(a, m);
1547
+ return y <= 0n || x % y === 0n;
1548
+ }
1549
+ const isWhole = (d) => d.digits % 10n ** BigInt(d.scale) === 0n;
340
1550
  /**
341
1551
  * Raw bytes: `format: binary` (3.0), or a binary `contentMediaType` without a
342
1552
  * `contentEncoding` (3.1; with base64 and the like it is text).
@@ -349,22 +1559,46 @@ function isBinaryString(v) {
349
1559
  v.get("contentEncoding") === undefined &&
350
1560
  isBinaryMedia(media));
351
1561
  }
1562
+ /**
1563
+ * An array, or a tuple where `prefixItems`, `minItems` or `maxItems` say more: the first
1564
+ * `minItems` items are required, `prefixItems` types the first ones and `items` the rest
1565
+ * (absent means any; false, next to `prefixItems`, none), and `maxItems` closes the tuple,
1566
+ * which TypeScript bounds only item by item.
1567
+ */
352
1568
  function array(cx, v, at) {
353
- const items = v.get("items");
1569
+ // unevaluatedItems is items where nothing else evaluates the rest.
1570
+ const key = v.get("items") === undefined ? "unevaluatedItems" : "items";
1571
+ const items = key === "items" ? v.get("items") : unevaluated(v, "unevaluatedItems");
354
1572
  const prefix = v.get("prefixItems");
355
- if (!Array.isArray(prefix)) {
356
- return arrayTy(items === undefined ? UNKNOWN : schema(cx, items, child(at, "items")));
357
- }
358
- // prefixItems: items past minItems may be missing; `items` describes the rest
359
- // (absent means any, false means none).
360
- const tupleItems = list(cx, prefix, child(at, "prefixItems"));
361
- const minItems = v.get("minItems");
362
- const n = minItems instanceof JsonNumber ? Number(minItems.text) : 0;
363
- const min = Number.isInteger(n) && n > 0 ? Math.min(n, tupleItems.length) : 0;
364
- if (items === false)
365
- return { kind: "tuple", items: tupleItems, min };
366
- const rest = items === undefined ? UNKNOWN : schema(cx, items, child(at, "items"));
367
- return { kind: "tuple", items: tupleItems, min, rest };
1573
+ // The items of a part are parts: an array repeats the field.
1574
+ const part = cx.here === "part" ? "part" : undefined;
1575
+ const head = Array.isArray(prefix)
1576
+ ? cx.withRaw(part, () => list(cx, prefix, child(at, "prefixItems")))
1577
+ : [];
1578
+ const rest = items === undefined
1579
+ ? UNKNOWN
1580
+ : items === false && Array.isArray(prefix)
1581
+ ? undefined
1582
+ : cx.withRaw(part, () => schema(cx, items, child(at, key)));
1583
+ const min = count(v, "minItems") ?? 0;
1584
+ const max = count(v, "maxItems");
1585
+ if (max !== undefined && max < min)
1586
+ return NEVER;
1587
+ if (rest === undefined && min > head.length)
1588
+ return NEVER;
1589
+ if (!Array.isArray(prefix) && min === 0 && max === undefined)
1590
+ return arrayTy(rest);
1591
+ const length = max ?? Math.max(head.length, min);
1592
+ const written = Array.from({ length: rest === undefined ? Math.min(length, head.length) : length }, (_, i) => head[i] ?? rest);
1593
+ return max !== undefined || rest === undefined
1594
+ ? { kind: "tuple", items: written, min }
1595
+ : { kind: "tuple", items: written, min, rest };
1596
+ }
1597
+ /** A count keyword (`minItems`, `maxItems`): a non-negative integer, or undefined. */
1598
+ function count(v, key) {
1599
+ const n = v.get(key);
1600
+ const value = n instanceof JsonNumber ? Number(n.text) : Number.NaN;
1601
+ return Number.isInteger(value) && value >= 0 ? value : undefined;
368
1602
  }
369
1603
  /**
370
1604
  * A readOnly property is not sent and a writeOnly one is not returned, even when
@@ -398,31 +1632,32 @@ function isLeftOut(cx, s, seen = new Set()) {
398
1632
  */
399
1633
  function leftOutKeys(cx, v, seen = new Set()) {
400
1634
  const keys = new Set();
401
- const props = get(v, "properties");
402
- if (props instanceof JsonObject)
403
- for (const [k, s] of props.entries)
404
- if (isLeftOut(cx, s))
405
- keys.add(k);
406
- const allOf = get(v, "allOf");
407
- for (const m of Array.isArray(allOf) ? allOf : []) {
408
- const r = str(m, "$ref");
409
- if (r === undefined) {
1635
+ const r = str(v, "$ref");
1636
+ // In 3.0 the keywords next to $ref are ignored; in 3.1 and 3.2 they and the target
1637
+ // are one schema.
1638
+ if (r === undefined || cx.refSiblings) {
1639
+ const props = get(v, "properties");
1640
+ if (props instanceof JsonObject)
1641
+ for (const [k, s] of props.entries)
1642
+ if (isLeftOut(cx, s))
1643
+ keys.add(k);
1644
+ const allOf = get(v, "allOf");
1645
+ for (const m of Array.isArray(allOf) ? allOf : [])
410
1646
  for (const k of leftOutKeys(cx, m, seen))
411
1647
  keys.add(k);
412
- continue;
413
- }
414
- const target = cx.tryLocate(r);
415
- if (target === undefined || seen.has(target.uri))
416
- continue;
417
- const { value, base, uri } = target;
418
- seen.add(uri);
419
- // The target's own $refs resolve against the document it is in.
420
- for (const k of cx.withBase(base, () => leftOutKeys(cx, value, seen)))
421
- keys.add(k);
422
1648
  }
1649
+ const target = r === undefined ? undefined : cx.tryLocate(r);
1650
+ if (target === undefined || seen.has(target.uri))
1651
+ return keys;
1652
+ seen.add(target.uri);
1653
+ // The target's own $refs resolve against the document it is in.
1654
+ for (const k of cx.withBase(target.base, () => leftOutKeys(cx, target.value, seen)))
1655
+ keys.add(k);
423
1656
  return keys;
424
1657
  }
425
1658
  function object(cx, v, at) {
1659
+ // A multipart body's properties are its parts.
1660
+ const part = cx.here === "parts" ? "part" : undefined;
426
1661
  const req = v.get("required");
427
1662
  const required = Array.isArray(req)
428
1663
  ? req.filter((n) => typeof n === "string")
@@ -439,12 +1674,12 @@ function object(cx, v, at) {
439
1674
  continue;
440
1675
  const p = {
441
1676
  key,
442
- ty: schema(cx, s, child(base, key)),
1677
+ ty: cx.withRaw(part, () => schema(cx, s, child(base, key))),
443
1678
  optional: !required.includes(key),
444
1679
  };
445
1680
  if (!p.optional)
446
1681
  p.present = true;
447
- const d = doc(s);
1682
+ const d = schemaDoc(cx, s);
448
1683
  if (d !== undefined)
449
1684
  p.doc = d;
450
1685
  props.push(p);
@@ -459,37 +1694,192 @@ function object(cx, v, at) {
459
1694
  return required.some((n) => !left.has(n))
460
1695
  ? NEVER
461
1696
  : { kind: "map", props: [], index: NEVER };
462
- // A required key without a property schema must be present with any value.
463
- for (const name of required) {
464
- if (!left.has(name) && !props.some((p) => p.key === name))
465
- props.push({ ...prop(name, UNKNOWN), present: true });
466
- }
467
- const ap = v.get("additionalProperties");
1697
+ // unevaluatedProperties is additionalProperties where nothing else evaluates the rest.
1698
+ const apKey = v.get("additionalProperties") === undefined
1699
+ ? "unevaluatedProperties"
1700
+ : "additionalProperties";
1701
+ const ap = apKey === "additionalProperties"
1702
+ ? v.get(apKey)
1703
+ : unevaluated(v, "unevaluatedProperties");
468
1704
  let additional;
469
1705
  if (ap === false)
470
1706
  additional = NEVER;
471
1707
  else if (ap === true)
472
1708
  additional = UNKNOWN;
473
1709
  else if (ap !== undefined)
474
- additional = schema(cx, ap, child(at, "additionalProperties"));
475
- // Keys matching a pattern are allowed whatever additionalProperties says. TypeScript
476
- // cannot check the pattern, so their types join the index signature.
1710
+ additional = cx.withRaw(part, () => schema(cx, ap, child(at, apKey)));
477
1711
  const pp = v.get("patternProperties");
478
1712
  const patterns = pp instanceof JsonObject
479
- ? pp.entries.map(([key, s]) => schema(cx, s, child(child(at, "patternProperties"), key)))
1713
+ ? pp.entries.map(([key, s]) => [
1714
+ key,
1715
+ cx.withRaw(part, () => schema(cx, s, child(child(at, "patternProperties"), key))),
1716
+ ])
480
1717
  : [];
481
- if (patterns.length > 0 && additional !== undefined) {
482
- additional = union(additional.kind === "never" ? patterns : [additional, ...patterns]);
1718
+ // A property a pattern matches has both types.
1719
+ for (const p of props) {
1720
+ const matched = patterns
1721
+ .filter(([k]) => matches(k, p.key))
1722
+ .map(([, t]) => t);
1723
+ if (matched.length > 0)
1724
+ p.ty = inter([p.ty, ...matched]);
1725
+ }
1726
+ // A required key without a property schema must be present, with the value the
1727
+ // patterns it matches admit, or else additionalProperties; any value without either.
1728
+ for (const name of required) {
1729
+ if (left.has(name) || props.some((p) => p.key === name))
1730
+ continue;
1731
+ const matched = patterns
1732
+ .filter(([p]) => matches(p, name))
1733
+ .map(([, t]) => t);
1734
+ const ty = matched.length > 0 ? inter(matched) : (additional ?? UNKNOWN);
1735
+ if (ty.kind === "never")
1736
+ return NEVER;
1737
+ props.push({ ...prop(name, ty), present: true });
1738
+ }
1739
+ // propertyNames that lists the keys closes the object over them: a declared property
1740
+ // it does not list cannot be there, and one it lists but nothing declares has the
1741
+ // value the patterns or additionalProperties give it.
1742
+ const allowed = keyNames(v.get("propertyNames"));
1743
+ if (allowed !== undefined) {
1744
+ if (props.some((p) => !p.optional && !allowed.includes(p.key)))
1745
+ return NEVER;
1746
+ const kept = props.map((p) => allowed.includes(p.key) ? p : { ...p, ty: NEVER });
1747
+ for (const name of allowed) {
1748
+ if (left.has(name) || kept.some((p) => p.key === name))
1749
+ continue;
1750
+ const matched = patterns
1751
+ .filter(([p]) => matches(p, name))
1752
+ .map(([, t]) => t);
1753
+ const ty = matched.length > 0 ? inter(matched) : (additional ?? UNKNOWN);
1754
+ if (ty.kind !== "never")
1755
+ kept.push({ key: name, ty, optional: true });
1756
+ }
1757
+ return counted(v, kept);
1758
+ }
1759
+ // Keys a pattern matches have its type whatever additionalProperties says. A pattern
1760
+ // whose keys template literal types say keys index signatures by them, and a key it
1761
+ // names is a property; another pattern's type joins the index signature by any string.
1762
+ const keyed = [];
1763
+ const unwritten = [];
1764
+ const named = (name, ty) => {
1765
+ if (left.has(name) || props.some((p) => p.key === name))
1766
+ return;
1767
+ if (ty.kind !== "never")
1768
+ props.push({ key: name, ty, optional: true });
1769
+ };
1770
+ for (const [pattern, ty] of patterns) {
1771
+ const keys = patternType(pattern);
1772
+ if (keys === undefined)
1773
+ unwritten.push(ty);
1774
+ else
1775
+ for (const key of keys.kind === "union" ? keys.items : [keys])
1776
+ if (key.kind === "lit")
1777
+ named(JSON.parse(key.text), ty);
1778
+ else
1779
+ keyed.push({ pattern, key, ty });
1780
+ }
1781
+ // An index signature admits each property it applies to, `undefined` too for an optional one.
1782
+ const admitting = (ty, applies) => {
1783
+ const own = props.filter((p) => applies(p.key));
1784
+ return union([
1785
+ ty,
1786
+ ...own.map((p) => p.ty),
1787
+ ...(own.some((p) => p.optional) ? [UNDEFINED] : []),
1788
+ ]);
1789
+ };
1790
+ const byPattern = keyed.map((k) => ({
1791
+ key: k.key,
1792
+ ty: admitting(k.ty, (key) => matches(k.pattern, key)),
1793
+ }));
1794
+ const everyType = [
1795
+ ...unwritten,
1796
+ ...keyed.map((k) => k.ty),
1797
+ ...props.map((p) => p.ty),
1798
+ ];
1799
+ // propertyNames: { pattern } keys the object by it: a property it does not admit cannot
1800
+ // be there, a key it names is a property, and the others index signatures by its templates.
1801
+ const names = keyPattern(v.get("propertyNames"));
1802
+ if (names !== undefined) {
1803
+ const pattern = v.get("propertyNames").str("pattern");
1804
+ if (props.some((p) => !p.optional && !matches(pattern, p.key)))
1805
+ return NEVER;
1806
+ for (const p of props)
1807
+ if (!matches(pattern, p.key))
1808
+ p.ty = NEVER;
1809
+ const rest = [];
1810
+ for (const key of names.kind === "union" ? names.items : [names])
1811
+ if (key.kind === "lit")
1812
+ named(JSON.parse(key.text), additional ?? UNKNOWN);
1813
+ else if (additional?.kind !== "never")
1814
+ rest.push({
1815
+ key,
1816
+ ty: admitting(union([additional ?? UNKNOWN, ...everyType]), () => true),
1817
+ });
1818
+ if (byPattern.length === 0 && rest.length === 0)
1819
+ return counted(v, props);
1820
+ return { kind: "map", props, keyed: [...byPattern, ...rest] };
1821
+ }
1822
+ if (additional === undefined) {
1823
+ if (byPattern.length === 0)
1824
+ return props.length === 0 ? RECORD : { kind: "object", props };
1825
+ // Without properties, other keys have any value, as for an object without either.
1826
+ return props.length === 0
1827
+ ? { kind: "map", props, keyed: byPattern, index: UNKNOWN }
1828
+ : { kind: "map", props, keyed: byPattern };
483
1829
  }
484
- if (additional === undefined)
485
- return props.length === 0 ? RECORD : { kind: "object", props };
486
1830
  // `additionalProperties: false` closes the object; TypeScript can only say so
487
- // when there are no properties at all.
488
- if (additional.kind === "never" && props.length > 0)
489
- return { kind: "object", props };
490
- // The index signature must admit every declared property too.
491
- const members = [additional, ...props.map((p) => p.ty)];
492
- if (props.some((p) => p.optional))
493
- members.push(UNDEFINED);
494
- return { kind: "map", props, index: union(members) };
1831
+ // when there are no properties at all, but its counts can say which are present.
1832
+ if (additional.kind === "never" &&
1833
+ byPattern.length === 0 &&
1834
+ unwritten.length === 0)
1835
+ return counted(v, props);
1836
+ const index = additional.kind === "never" && unwritten.length === 0
1837
+ ? undefined
1838
+ : admitting(union([additional, ...everyType]), () => true);
1839
+ return {
1840
+ kind: "map",
1841
+ props,
1842
+ ...(byPattern.length === 0 ? {} : { keyed: byPattern }),
1843
+ ...(index === undefined ? {} : { index }),
1844
+ };
1845
+ }
1846
+ /** The keys a `propertyNames` with only `pattern` admits, as template literal types; undefined for any other, or a pattern none says. */
1847
+ function keyPattern(names) {
1848
+ if (!(names instanceof JsonObject))
1849
+ return undefined;
1850
+ const keys = names.entries.map(([k]) => k).filter((k) => !isAnnotation(k));
1851
+ const pattern = names.str("pattern");
1852
+ return keys.length === 1 && pattern !== undefined
1853
+ ? patternType(pattern)
1854
+ : undefined;
1855
+ }
1856
+ /**
1857
+ * A closed object, its properties all it can have: `minProperties` requires that many
1858
+ * of them (a union over which), `maxProperties` leaves out the others.
1859
+ */
1860
+ function counted(v, props) {
1861
+ if (props.length === 0)
1862
+ return { kind: "map", props: [], index: NEVER };
1863
+ const optional = props.filter((p) => p.optional).map((p) => p.key);
1864
+ const present = props.length - optional.length;
1865
+ const min = count(v, "minProperties") ?? 0;
1866
+ const max = count(v, "maxProperties") ?? props.length;
1867
+ if (min > Math.min(max, props.length) || present > max)
1868
+ return NEVER;
1869
+ const variant = (f) => ({
1870
+ kind: "object",
1871
+ props: props.map((p) => (p.optional ? f(p) : p)),
1872
+ });
1873
+ const parts = [];
1874
+ if (min > present)
1875
+ parts.push(union(subsets(optional, min - present).map((keys) => variant((p) => keys.includes(p.key) ? { ...p, optional: false, present: true } : p))));
1876
+ if (max < props.length)
1877
+ parts.push(union(subsets(optional, max - present).map((keys) => variant((p) => (keys.includes(p.key) ? p : { ...p, ty: NEVER })))));
1878
+ return parts.length === 0 ? { kind: "object", props } : inter(parts);
1879
+ }
1880
+ /** The subsets of `items` with `size` members, in order. */
1881
+ function subsets(items, size) {
1882
+ if (size === 0)
1883
+ return [[]];
1884
+ return items.flatMap((item, i) => subsets(items.slice(i + 1), size - 1).map((rest) => [item, ...rest]));
495
1885
  }