oas-truth 0.7.1 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -29,21 +29,11 @@ if (result.ok) {
29
29
  with `@apidevtools/swagger-parser` to resolve external `$ref`s
30
30
  - TypeSpec files (`.tsp`) are compiled with `@typespec/compiler` and then bundled; the compiler is
31
31
  loaded only for a `.tsp` input
32
- - Returns a `Result<OpenAPI>`, `{ ok: true, value } | { ok: false, error }`, and never throws: an
32
+ - Returns `{ ok: true, value } | { ok: false, error }` and never throws: an
33
33
  unsupported input, a missing file, an unreachable URL and a TypeSpec diagnostic all come back as
34
34
  `error`
35
35
 
36
- The input is typed as `OpenAPIInput`. `isOpenAPIInput` narrows a CLI argument or a config value
37
- to it:
38
-
39
- ```ts
40
- import { isOpenAPIInput, parseOpenAPI } from 'oas-truth'
41
-
42
- const input = process.argv[2]
43
- if (isOpenAPIInput(input)) {
44
- const result = await parseOpenAPI(input)
45
- }
46
- ```
36
+ The input is typed as a template literal union of these documents (`Parameters<typeof parseOpenAPI>[0]`). A string that names none of them is checked at runtime too and comes back as `{ ok: false, error }` before anything is read.
47
37
 
48
38
  ## Component schemas
49
39
 
package/dist/index.d.ts CHANGED
@@ -1,22 +1,3 @@
1
- /**
2
- * The outcome of an operation that can fail: the value, or the reason it failed. The public
3
- * API never throws; every failure is folded into `{ ok: false, error }`.
4
- */
5
- export type Result<T, E = string> = {
6
- readonly ok: true;
7
- readonly value: T;
8
- } | {
9
- readonly ok: false;
10
- readonly error: E;
11
- };
12
- /**
13
- * A document `parseOpenAPI` reads: an OpenAPI file by its extension, a TypeSpec file, or an
14
- * `http(s)` URL whatever its path (a document served without an extension is OpenAPI by
15
- * content).
16
- */
17
- export type OpenAPIInput = `${string}.yaml` | `${string}.yml` | `${string}.json` | `${string}.tsp` | `http://${string}` | `https://${string}`;
18
- /** Whether a value names a document `parseOpenAPI` reads, for narrowing a CLI or config value. */
19
- export declare function isOpenAPIInput(value: unknown): value is OpenAPIInput;
20
1
  /**
21
2
  * Read an OpenAPI or TypeSpec document into a typed OpenAPI document.
22
3
  *
@@ -25,8 +6,23 @@ export declare function isOpenAPIInput(value: unknown): value is OpenAPIInput;
25
6
  * the code builders can emit schema variables instead of inline copies. A local `.tsp` file
26
7
  * is compiled with `@typespec/compiler` and emitted with `@typespec/openapi3`, both loaded
27
8
  * only for TypeSpec, then bundled the same way.
9
+ *
10
+ * The input type lists what it reads: an OpenAPI file by its extension, a TypeSpec file, or an
11
+ * `http(s)` URL whatever its path (a document served without an extension is OpenAPI by
12
+ * content).
13
+ *
14
+ * It never throws: the document comes back as `{ ok: true, value }` and every failure as
15
+ * `{ ok: false, error }` with a message.
28
16
  */
29
- export declare function parseOpenAPI(input: OpenAPIInput): Promise<Result<OpenAPI>>;
17
+ export declare function parseOpenAPI(input: `${string}.yaml` | `${string}.yml` | `${string}.json` | `${string}.tsp` | `http://${string}` | `https://${string}`): Promise<{
18
+ readonly ok: true;
19
+ readonly value: OpenAPI;
20
+ readonly error?: never;
21
+ } | {
22
+ readonly value?: never;
23
+ readonly ok: false;
24
+ readonly error: string;
25
+ }>;
30
26
  export type OpenAPI = {
31
27
  readonly openapi?: string;
32
28
  readonly $self?: string;
@@ -627,8 +623,8 @@ type SchemaReplacementsOptions = {
627
623
  readonly slot?: SchemaSlot;
628
624
  readonly identifiers?: ReadonlyMap<string, string>;
629
625
  };
630
- export declare function makeSchemaReplacements(value: unknown, adapter: ComponentAdapter, options?: SchemaReplacementsOptions): ReadonlyMap<unknown, string>;
631
- export declare function toPascalCase(str: string): string;
626
+ export declare function makeSchemaReplacements(value: unknown, adapter: ComponentAdapter, options?: SchemaReplacementsOptions): Map<unknown, string>;
627
+ export declare function toPascalCase(text: string): string;
632
628
  /**
633
629
  * Extract the component name from a `$ref`, decoding percent-encoding so the
634
630
  * result matches the (decoded) key under `components.schemas`. Pure-ASCII refs
@@ -681,23 +677,68 @@ type ComponentCodeOptions = {
681
677
  readonly readonly?: boolean;
682
678
  readonly identifiers?: ReadonlyMap<string, string>;
683
679
  };
684
- export declare function makeCallbacksDeclarations(components: Components, adapter: ComponentAdapter, options?: ComponentCodeOptions): readonly ComponentDeclaration[];
680
+ export declare function makeCallbacksDeclarations(components: Components, adapter: ComponentAdapter, options?: ComponentCodeOptions): {
681
+ name: string;
682
+ varName: string;
683
+ fileName: string;
684
+ code: string;
685
+ }[];
685
686
  export declare function makeCallbacksCode(components: Components, adapter: ComponentAdapter, readonly: boolean): string;
686
- export declare function makeExamplesDeclarations(components: Components, options?: ComponentCodeOptions): readonly ComponentDeclaration[];
687
+ export declare function makeExamplesDeclarations(components: Components, options?: ComponentCodeOptions): {
688
+ name: string;
689
+ varName: string;
690
+ fileName: string;
691
+ code: string;
692
+ }[];
687
693
  export declare function makeExamplesCode(components: Components, readonly: boolean): string;
688
- export declare function makeHeadersDeclarations(components: Components, adapter: ComponentAdapter, options?: ComponentCodeOptions): readonly ComponentDeclaration[];
694
+ export declare function makeHeadersDeclarations(components: Components, adapter: ComponentAdapter, options?: ComponentCodeOptions): {
695
+ name: string;
696
+ varName: string;
697
+ fileName: string;
698
+ code: string;
699
+ }[];
689
700
  export declare function makeHeadersCode(components: Components, adapter: ComponentAdapter, exportTypes?: boolean): string;
690
- export declare function makeLinksDeclarations(components: Components, options?: ComponentCodeOptions): readonly ComponentDeclaration[];
701
+ export declare function makeLinksDeclarations(components: Components, options?: ComponentCodeOptions): {
702
+ name: string;
703
+ varName: string;
704
+ fileName: string;
705
+ code: string;
706
+ }[];
691
707
  export declare function makeLinksCode(components: Components, readonly: boolean): string;
692
- export declare function makeMediaTypesDeclarations(components: Components, adapter: ComponentAdapter, options?: ComponentCodeOptions): readonly ComponentDeclaration[];
708
+ export declare function makeMediaTypesDeclarations(components: Components, adapter: ComponentAdapter, options?: ComponentCodeOptions): {
709
+ name: string;
710
+ varName: string;
711
+ fileName: string;
712
+ code: string;
713
+ }[];
693
714
  export declare function makeMediaTypesCode(components: Components, adapter: ComponentAdapter, exportTypes?: boolean): string;
694
- export declare function makeParametersDeclarations(components: Components, adapter: ComponentAdapter, options?: ComponentCodeOptions): readonly ComponentDeclaration[];
715
+ export declare function makeParametersDeclarations(components: Components, adapter: ComponentAdapter, options?: ComponentCodeOptions): {
716
+ name: string;
717
+ varName: string;
718
+ fileName: string;
719
+ code: string;
720
+ }[];
695
721
  export declare function makeParametersCode(components: Components, adapter: ComponentAdapter, exportTypes?: boolean): string;
696
- export declare function makePathItemsDeclarations(components: Components, adapter: ComponentAdapter, options?: ComponentCodeOptions): readonly ComponentDeclaration[];
722
+ export declare function makePathItemsDeclarations(components: Components, adapter: ComponentAdapter, options?: ComponentCodeOptions): {
723
+ name: string;
724
+ varName: string;
725
+ fileName: string;
726
+ code: string;
727
+ }[];
697
728
  export declare function makePathItemsCode(components: Components, adapter: ComponentAdapter, readonly: boolean): string;
698
- export declare function makeRequestBodiesDeclarations(components: Components, adapter: ComponentAdapter, options?: ComponentCodeOptions): readonly ComponentDeclaration[];
729
+ export declare function makeRequestBodiesDeclarations(components: Components, adapter: ComponentAdapter, options?: ComponentCodeOptions): {
730
+ name: string;
731
+ varName: string;
732
+ fileName: string;
733
+ code: string;
734
+ }[];
699
735
  export declare function makeRequestBodiesCode(components: Components, adapter: ComponentAdapter, readonly: boolean): string;
700
- export declare function makeResponsesDeclarations(components: Components, adapter: ComponentAdapter, options?: ComponentCodeOptions): readonly ComponentDeclaration[];
736
+ export declare function makeResponsesDeclarations(components: Components, adapter: ComponentAdapter, options?: ComponentCodeOptions): {
737
+ name: string;
738
+ varName: string;
739
+ fileName: string;
740
+ code: string;
741
+ }[];
701
742
  export declare function makeResponsesCode(components: Components, adapter: ComponentAdapter, readonly: boolean): string;
702
743
  type SchemasOptions = {
703
744
  readonly exportTypes?: boolean;
@@ -767,6 +808,11 @@ export declare function makeSchemaDeclarations(schemas: {
767
808
  * order. Returns `''` when schemas are missing or empty.
768
809
  */
769
810
  export declare function makeSchemasCode(components: Components, adapter: ComponentAdapter, options?: SchemasOptions): string;
770
- export declare function makeSecuritySchemesDeclarations(components: Components, options?: ComponentCodeOptions): readonly ComponentDeclaration[];
811
+ export declare function makeSecuritySchemesDeclarations(components: Components, options?: ComponentCodeOptions): {
812
+ name: string;
813
+ varName: string;
814
+ fileName: string;
815
+ code: string;
816
+ }[];
771
817
  export declare function makeSecuritySchemesCode(components: Components, readonly: boolean): string;
772
818
  export type { ComponentCodeOptions, ComponentDeclaration, SchemaDeclaration, SchemasOptions };
package/dist/index.js CHANGED
@@ -6,19 +6,6 @@ import { schemaToTypebox } from "schema-truth/typebox";
6
6
  import { schemaToValibot } from "schema-truth/valibot";
7
7
  import { schemaToZod } from "schema-truth/zod";
8
8
  // src/openapi/index.ts
9
- const INPUT_EXTENSIONS = [
10
- ".yaml",
11
- ".yml",
12
- ".json",
13
- ".tsp"
14
- ];
15
- /** Whether a value names a document `parseOpenAPI` reads, for narrowing a CLI or config value. */
16
- function isOpenAPIInput(value) {
17
- return typeof value === "string" && (isURL(value) || INPUT_EXTENSIONS.some((extension) => value.endsWith(extension)));
18
- }
19
- function isURL(value) {
20
- return /^https?:\/\//iu.test(value);
21
- }
22
9
  /**
23
10
  * Read an OpenAPI or TypeSpec document into a typed OpenAPI document.
24
11
  *
@@ -27,53 +14,58 @@ function isURL(value) {
27
14
  * the code builders can emit schema variables instead of inline copies. A local `.tsp` file
28
15
  * is compiled with `@typespec/compiler` and emitted with `@typespec/openapi3`, both loaded
29
16
  * only for TypeSpec, then bundled the same way.
17
+ *
18
+ * The input type lists what it reads: an OpenAPI file by its extension, a TypeSpec file, or an
19
+ * `http(s)` URL whatever its path (a document served without an extension is OpenAPI by
20
+ * content).
21
+ *
22
+ * It never throws: the document comes back as `{ ok: true, value }` and every failure as
23
+ * `{ ok: false, error }` with a message.
30
24
  */
31
25
  async function parseOpenAPI(input) {
32
- if (typeof input === "string" && !isOpenAPIInput(input)) return {
26
+ const isURL = typeof input === "string" && /^https?:\/\//iu.test(input);
27
+ if (typeof input === "string" && !isURL && ![
28
+ ".yaml",
29
+ ".yml",
30
+ ".json",
31
+ ".tsp"
32
+ ].some((extension) => input.endsWith(extension))) return {
33
33
  ok: false,
34
- error: `Unsupported input: ${String(input)} (expected a .yaml, .yml, .json or .tsp file, or an http(s) URL)`
34
+ error: `Unsupported input: ${input} (expected a .yaml, .yml, .json or .tsp file, or an http(s) URL)`
35
35
  };
36
36
  try {
37
- if (typeof input === "string" && input.endsWith(".tsp") && !isURL(input)) return await parseTypeSpec(input);
38
- return {
37
+ if (typeof input !== "string" || isURL || !input.endsWith(".tsp")) return {
39
38
  ok: true,
40
39
  value: await SwaggerParser.bundle(input)
41
40
  };
41
+ const [{ compile, NodeHost }, { getOpenAPI3 }] = await Promise.all([import("@typespec/compiler"), import("@typespec/openapi3")]);
42
+ const program = await compile(NodeHost, path.resolve(input), { noEmit: true });
43
+ if (program.diagnostics.length > 0) return {
44
+ ok: false,
45
+ error: `TypeSpec compile failed:\n${program.diagnostics.map((diagnostic) => diagnostic.message).join("\n")}`
46
+ };
47
+ const [record] = await getOpenAPI3(program);
48
+ const document = record === void 0 ? void 0 : "document" in record ? record.document : record.versions[0]?.document;
49
+ if (document === void 0) return {
50
+ ok: false,
51
+ error: `TypeSpec emitted no OpenAPI document: ${input}`
52
+ };
53
+ return {
54
+ ok: true,
55
+ value: await SwaggerParser.bundle(document)
56
+ };
42
57
  } catch (error) {
58
+ if (!(error instanceof Error)) return {
59
+ ok: false,
60
+ error: String(error)
61
+ };
62
+ const code = "ioErrorCode" in error ? error.ioErrorCode : void 0;
43
63
  return {
44
64
  ok: false,
45
- error: errorMessage(error)
65
+ error: (error.message.trim() === "" || error.message.trimEnd().endsWith(":")) && typeof code === "string" && code !== "" ? `${error.message.trimEnd()} ${code}`.trim() : error.message
46
66
  };
47
67
  }
48
68
  }
49
- async function parseTypeSpec(input) {
50
- const [{ compile, NodeHost }, { getOpenAPI3 }] = await Promise.all([import("@typespec/compiler"), import("@typespec/openapi3")]);
51
- const program = await compile(NodeHost, path.resolve(input), { noEmit: true });
52
- if (program.diagnostics.length > 0) return {
53
- ok: false,
54
- error: `TypeSpec compile failed:\n${program.diagnostics.map((d) => d.message).join("\n")}`
55
- };
56
- const [record] = await getOpenAPI3(program);
57
- const document = record === void 0 ? void 0 : "document" in record ? record.document : record.versions[0]?.document;
58
- if (document === void 0) return {
59
- ok: false,
60
- error: `TypeSpec emitted no OpenAPI document: ${input}`
61
- };
62
- return {
63
- ok: true,
64
- value: await SwaggerParser.bundle(document)
65
- };
66
- }
67
- /**
68
- * The message of a thrown value. swagger-parser reports some I/O failures (a URL that does
69
- * not resolve, a missing file) with a message that ends before the reason and the reason in
70
- * `ioErrorCode`; it is appended so the message says what went wrong.
71
- */
72
- function errorMessage(error) {
73
- if (!(error instanceof Error)) return String(error);
74
- const code = "ioErrorCode" in error ? error.ioErrorCode : void 0;
75
- return (error.message.trim() === "" || error.message.trimEnd().endsWith(":")) && typeof code === "string" && code !== "" ? `${error.message.trimEnd()} ${code}`.trim() : error.message;
76
- }
77
69
  // src/adapter/index.ts
78
70
  const PARAM_STYLES = [
79
71
  "matrix",
@@ -119,7 +111,7 @@ function extractParts(code, stripRefs = (s) => s) {
119
111
  const firstCode = lines.findIndex((line) => line.trim() !== "" && !line.startsWith("//"));
120
112
  const comments = (firstCode === -1 ? lines : lines.slice(0, firstCode)).filter((line) => line.startsWith("//"));
121
113
  const joined = (firstCode === -1 ? [] : lines.slice(firstCode)).join("\n").trim();
122
- const expr = joined.match(/^export const \w+ = (.+)$/su)?.[1];
114
+ const expr = /^export const \w+ = (.+)$/su.exec(joined)?.[1];
123
115
  return {
124
116
  expression: stripRefs(expr === void 0 ? joined : expr.replace(/;?\s*$/u, "")),
125
117
  comments
@@ -175,7 +167,7 @@ function stripEffectSuspend(code) {
175
167
  * references that leave the cycle.
176
168
  */
177
169
  function renderArktypeCyclic(varName, containerExpr, externals) {
178
- const body = containerExpr.match(/scope\(\{([\s\S]*)\}\)\.export\(\)/u)?.[1];
170
+ const body = /scope\(\{([\s\S]*)\}\)\.export\(\)/u.exec(containerExpr)?.[1];
179
171
  if (body === void 0) return containerExpr;
180
172
  return `scope({${[...externals.map((ref) => `${ref}:${ref}`), body].join(",")}}).export().${varName}`;
181
173
  }
@@ -302,8 +294,8 @@ function makeEffectAdapter() {
302
294
  };
303
295
  }
304
296
  // src/utils/index.ts
305
- function toPascalCase(str) {
306
- return str.replaceAll(/[^a-zA-Z0-9]+(.)/gu, (_, c) => c.toUpperCase()).replace(/^(.)/u, (_, c) => c.toUpperCase());
297
+ function toPascalCase(text) {
298
+ return text.replaceAll(/[^a-zA-Z0-9]+(.)/gu, (_, letter) => letter.toUpperCase()).replace(/^(.)/u, (_, letter) => letter.toUpperCase());
307
299
  }
308
300
  /**
309
301
  * Decode percent-encoding, falling back to the raw input on malformed sequences
@@ -345,7 +337,7 @@ function toIdentifierPascalCase(name) {
345
337
  const parts = encodeNonAscii(name).split(/[^a-zA-Z0-9]+/u).filter(Boolean);
346
338
  if (parts.length === 0) return "Schema";
347
339
  const result = parts.map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join("");
348
- if (/^[0-9]/u.test(result)) return `_${result}`.replace(/([0-9])([a-z])/u, (_, d, c) => `${d}${c.toUpperCase()}`);
340
+ if (/^[0-9]/u.test(result)) return `_${result}`.replace(/([0-9])([a-z])/u, (_, digit, letter) => `${digit}${letter.toUpperCase()}`);
349
341
  return result;
350
342
  }
351
343
  /**
@@ -375,7 +367,7 @@ function declarationFileName(ident) {
375
367
  * the suffixed name (`User` → `User2Schema`).
376
368
  */
377
369
  function makeSchemaVarName(ref, identifiers) {
378
- const name = ref.match(/^#\/components\/schemas\/(.+)$/u)?.[1];
370
+ const name = /^#\/components\/schemas\/(.+)$/u.exec(ref)?.[1];
379
371
  if (name === void 0) return void 0;
380
372
  const key = safeDecode(name);
381
373
  return `${identifiers?.get(key) ?? toIdentifierPascalCase(key)}Schema`;
@@ -467,7 +459,7 @@ function makeEntries(v, adapter, seen, path, options) {
467
459
  */
468
460
  function joinDeclarations(declarations, options) {
469
461
  if (declarations.length === 0) return "";
470
- const body = declarations.map((d) => d.code).join(";");
462
+ const body = declarations.map((declaration) => declaration.code).join(";");
471
463
  const text = options?.trailingNewline === true ? `${body}\n` : body;
472
464
  const importLine = typeof options?.importLine === "function" ? options.importLine(body) : options?.importLine;
473
465
  return importLine === void 0 ? text : `${importLine}\n\n${text}`;
@@ -478,7 +470,7 @@ function makeCallbacksDeclarations(components, adapter, options) {
478
470
  if (!callbacks) return [];
479
471
  const asConst = options?.readonly === true ? " as const" : "";
480
472
  return Object.entries(callbacks).flatMap(([name, callback]) => {
481
- if ("$ref" in callback && callback.$ref) return [];
473
+ if ("$ref" in callback && typeof callback.$ref === "string") return [];
482
474
  const ident = toIdentifierPascalCase(name);
483
475
  const varName = `${ident}Callback`;
484
476
  const replacements = makeSchemaReplacements(callback, adapter, {
@@ -520,7 +512,7 @@ function makeHeadersDeclarations(components, adapter, options) {
520
512
  const { headers } = components;
521
513
  if (!headers) return [];
522
514
  return Object.entries(headers).flatMap(([name, header]) => {
523
- if (!("schema" in header) || !header.schema) return [];
515
+ if (!("schema" in header) || !isRecord(header.schema)) return [];
524
516
  const ident = toIdentifierPascalCase(name);
525
517
  const varName = `${ident}HeaderSchema`;
526
518
  const raw = adapter.toExpression(header.schema);
@@ -565,7 +557,7 @@ function makeMediaTypesDeclarations(components, adapter, options) {
565
557
  if (!mediaTypes) return [];
566
558
  return Object.entries(mediaTypes).flatMap(([name, media]) => {
567
559
  if ("$ref" in media && media.$ref) return [];
568
- if (!("schema" in media) || !media.schema) return [];
560
+ if (!("schema" in media) || !isRecord(media.schema)) return [];
569
561
  const ident = toIdentifierPascalCase(name);
570
562
  const varName = `${ident}MediaTypeSchema`;
571
563
  const raw = adapter.toExpression(media.schema);
@@ -866,15 +858,15 @@ const SUBSCHEMA_MAP_KEYS = /* @__PURE__ */ new Set([
866
858
  function isSchema(value) {
867
859
  return isRecord(value);
868
860
  }
869
- /** Rewrites a schema bottom-up with `fn`, following only subschemas (never example or default values). */
870
- function mapSchema(schema, fn) {
871
- const map = (value) => isSchema(value) ? mapSchema(value, fn) : value;
861
+ /** Rewrites a schema bottom-up with `rewrite`, following only subschemas (never example or default values). */
862
+ function mapSchema(schema, rewrite) {
863
+ const map = (value) => isSchema(value) ? mapSchema(value, rewrite) : value;
872
864
  const node = Object.fromEntries(Object.entries(schema).map(([key, value]) => {
873
865
  if (SUBSCHEMA_KEYS.has(key)) return [key, Array.isArray(value) ? value.map(map) : map(value)];
874
866
  if (SUBSCHEMA_MAP_KEYS.has(key) && isRecord(value)) return [key, Object.fromEntries(Object.entries(value).map(([k, v]) => [k, map(v)]))];
875
867
  return [key, value];
876
868
  }));
877
- return fn(isSchema(node) ? node : schema);
869
+ return rewrite(isSchema(node) ? node : schema);
878
870
  }
879
871
  /**
880
872
  * `readonly` as the declarative `x-readonly` extension on every object and array,
@@ -904,11 +896,46 @@ function rewriteCollisionRef(node, identifiers) {
904
896
  $ref: `#/components/schemas/${ident}`
905
897
  };
906
898
  }
899
+ /** The component key a `#/components/schemas/...` reference names; undefined for any other reference. */
900
+ function componentSchemaKey(ref) {
901
+ return ref.startsWith("#/components/schemas/") ? schemaRefToName(ref) : void 0;
902
+ }
907
903
  function makeCyclicContainer(varName, group, schemas, identifiers, adapter, ref) {
908
904
  const groupIdentifiers = new Map(group.map((name) => [name, identifiers.get(name) ?? name]));
905
+ const localRef = (key) => {
906
+ const groupIdent = groupIdentifiers.get(key);
907
+ return groupIdent === void 0 ? void 0 : `#/$defs/${groupIdent}Schema`;
908
+ };
909
+ const keyByLocalRef = new Map(group.map((name) => [localRef(name), name]));
910
+ /**
911
+ * A member localized to `#/$defs/<Ident>Schema` would take that name as its implicit
912
+ * discriminator value, so the schema name is pinned in the mapping, and mapping targets
913
+ * that point into the cycle follow the members to their local refs.
914
+ */
915
+ const localizeDiscriminator = (node) => {
916
+ const { discriminator } = node;
917
+ if (discriminator?.propertyName === void 0) return node;
918
+ const mapping = Object.entries(discriminator.mapping ?? {});
919
+ const mapped = new Set(mapping.map(([, target]) => componentSchemaKey(target)));
920
+ const values = new Set(mapping.map(([value]) => value));
921
+ const implicit = [...node.oneOf ?? [], ...node.anyOf ?? []].flatMap((member) => {
922
+ const key = member.$ref === void 0 ? void 0 : keyByLocalRef.get(member.$ref);
923
+ return key === void 0 || mapped.has(key) || values.has(key) ? [] : [[key, member.$ref]];
924
+ });
925
+ const localized = mapping.map(([value, target]) => {
926
+ const key = componentSchemaKey(target);
927
+ return [value, (key === void 0 ? void 0 : localRef(key)) ?? target];
928
+ });
929
+ if (implicit.length === 0 && localized.every(([, target], index) => target === mapping[index]?.[1])) return node;
930
+ const local = Object.fromEntries([...Object.entries(node), ["discriminator", {
931
+ ...discriminator,
932
+ mapping: Object.fromEntries([...localized, ...implicit])
933
+ }]]);
934
+ return isSchema(local) ? local : node;
935
+ };
909
936
  const localize = (node) => {
910
937
  const key = node.$ref ? schemaRefToName(node.$ref) : void 0;
911
- if (key === void 0) return node;
938
+ if (key === void 0) return localizeDiscriminator(node);
912
939
  const groupIdent = groupIdentifiers.get(key);
913
940
  if (groupIdent !== void 0) {
914
941
  const local = Object.fromEntries([...Object.entries(node), ["$ref", `#/$defs/${groupIdent}Schema`]]);
@@ -1013,8 +1040,8 @@ function makeSchemasCode(components, adapter, options) {
1013
1040
  if (!schemas) return "";
1014
1041
  const declarations = makeSchemaDeclarations(schemas, adapter, options);
1015
1042
  if (declarations.length === 0) return "";
1016
- const cyclic = declarations.some((d) => d.importLine !== schemaImportLine(adapter, options, false, d.code));
1017
- const code = declarations.map((d) => d.code).join(";");
1043
+ const cyclic = declarations.some((declaration) => declaration.importLine !== schemaImportLine(adapter, options, false, declaration.code));
1044
+ const code = declarations.map((declaration) => declaration.code).join(";");
1018
1045
  return `${schemaImportLine(adapter, options, cyclic, code)}\n\n${code}\n`;
1019
1046
  }
1020
1047
  // src/generator/components/security-schemes.ts
@@ -1036,4 +1063,4 @@ function makeSecuritySchemesDeclarations(components, options) {
1036
1063
  function makeSecuritySchemesCode(components, readonly) {
1037
1064
  return joinDeclarations(makeSecuritySchemesDeclarations(components, { readonly }), { trailingNewline: true });
1038
1065
  }
1039
- export { declarationFileName, isOpenAPIInput, isParamStyle, isRecord, makeAdapter, makeCallbacksCode, makeCallbacksDeclarations, makeExamplesCode, makeExamplesDeclarations, makeHeadersCode, makeHeadersDeclarations, makeLinksCode, makeLinksDeclarations, makeMediaTypesCode, makeMediaTypesDeclarations, makeParametersCode, makeParametersDeclarations, makePathItemsCode, makePathItemsDeclarations, makeRequestBodiesCode, makeRequestBodiesDeclarations, makeResponsesCode, makeResponsesDeclarations, makeSafeKey, makeSchemaDeclarations, makeSchemaIdentifiers, makeSchemaReplacements, makeSchemaVarName, makeSchemasCode, makeSecuritySchemesCode, makeSecuritySchemesDeclarations, parseOpenAPI, schemaImportLine, schemaRefToName, toIdentifierPascalCase, toPascalCase, valueToCode };
1066
+ export { declarationFileName, isParamStyle, isRecord, makeAdapter, makeCallbacksCode, makeCallbacksDeclarations, makeExamplesCode, makeExamplesDeclarations, makeHeadersCode, makeHeadersDeclarations, makeLinksCode, makeLinksDeclarations, makeMediaTypesCode, makeMediaTypesDeclarations, makeParametersCode, makeParametersDeclarations, makePathItemsCode, makePathItemsDeclarations, makeRequestBodiesCode, makeRequestBodiesDeclarations, makeResponsesCode, makeResponsesDeclarations, makeSafeKey, makeSchemaDeclarations, makeSchemaIdentifiers, makeSchemaReplacements, makeSchemaVarName, makeSchemasCode, makeSecuritySchemesCode, makeSecuritySchemesDeclarations, parseOpenAPI, schemaImportLine, schemaRefToName, toIdentifierPascalCase, toPascalCase, valueToCode };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "oas-truth",
3
- "version": "0.7.1",
3
+ "version": "0.8.1",
4
4
  "description": "oas-truth is a parser from OpenAPI and TypeSpec to a typed OpenAPI document",
5
5
  "keywords": [
6
6
  "openapi",
@@ -32,7 +32,7 @@
32
32
  "provenance": true
33
33
  },
34
34
  "dependencies": {
35
- "schema-truth": "^0.8.5"
35
+ "schema-truth": "^0.8.15"
36
36
  },
37
37
  "devDependencies": {
38
38
  "@apidevtools/swagger-parser": "^13.1.0",