@skmtc/core 0.46.0 → 0.47.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.
Files changed (107) hide show
  1. package/esm/context/ParseContext.d.ts +3 -0
  2. package/esm/context/ParseContext.js +17 -7
  3. package/esm/context/generateTypes.d.ts +2 -2
  4. package/esm/helpers/collateExamples.js +35 -17
  5. package/esm/mod.d.ts +1 -0
  6. package/esm/mod.js +1 -0
  7. package/esm/oas/intersection/Intersection.d.ts +122 -0
  8. package/esm/oas/intersection/Intersection.js +266 -0
  9. package/esm/oas/mediaType/jsonMediaType.d.ts +1 -1
  10. package/esm/oas/mediaType/jsonMediaType.js +3 -3
  11. package/esm/oas/requestBody/RequestBody.d.ts +1 -1
  12. package/esm/oas/requestBody/RequestBody.js +1 -1
  13. package/esm/oas/response/Response.d.ts +1 -1
  14. package/esm/oas/response/Response.js +1 -1
  15. package/esm/oas/schema/Schema.d.ts +4 -2
  16. package/esm/oas/schema/siblings.d.ts +10 -2
  17. package/esm/oas/schema/siblings.js +87 -22
  18. package/esm/oas/schemaPath/traverseSchema.d.ts +2 -0
  19. package/esm/oas/schemaPath/traverseSchema.js +40 -0
  20. package/esm/parse/allOfSystem.d.ts +3 -0
  21. package/esm/parse/allOfSystem.js +2 -1
  22. package/esm/parse/keptIntersection.d.ts +53 -0
  23. package/esm/parse/keptIntersection.js +155 -0
  24. package/esm/parse/keptRefs.d.ts +23 -0
  25. package/esm/parse/keptRefs.js +59 -0
  26. package/esm/parse/toCyclicRefs.d.ts +8 -0
  27. package/esm/parse/toCyclicRefs.js +126 -0
  28. package/esm/parse/toDeclaredTypes.d.ts +20 -0
  29. package/esm/parse/toDeclaredTypes.js +43 -0
  30. package/esm/parse/v3-0/_merge-all-of/merge-intersection.js +8 -4
  31. package/esm/parse/v3-0/_merge-all-of/merge-union.js +7 -1
  32. package/esm/parse/v3-0/_merge-all-of/merge.js +13 -0
  33. package/esm/parse/v3-0/_merge-all-of/types.d.ts +3 -0
  34. package/esm/parse/v3-0/intersection/toIntersection.d.ts +12 -0
  35. package/esm/parse/v3-0/intersection/toIntersection.js +61 -0
  36. package/esm/parse/v3-0/schema/toSchemasV3.js +13 -1
  37. package/esm/parse/v3-1/_merge-all-of/merge-intersection.js +8 -4
  38. package/esm/parse/v3-1/_merge-all-of/merge-union.js +7 -1
  39. package/esm/parse/v3-1/_merge-all-of/merge.js +13 -0
  40. package/esm/parse/v3-1/_merge-all-of/types.d.ts +3 -0
  41. package/esm/parse/v3-1/intersection/toIntersection.d.ts +12 -0
  42. package/esm/parse/v3-1/intersection/toIntersection.js +61 -0
  43. package/esm/parse/v3-1/schema/toSchemasV3.js +15 -2
  44. package/esm/parse/v3-2/_merge-all-of/merge-intersection.js +8 -4
  45. package/esm/parse/v3-2/_merge-all-of/merge-union.js +7 -1
  46. package/esm/parse/v3-2/_merge-all-of/merge.js +13 -0
  47. package/esm/parse/v3-2/_merge-all-of/types.d.ts +3 -0
  48. package/esm/parse/v3-2/intersection/toIntersection.d.ts +12 -0
  49. package/esm/parse/v3-2/intersection/toIntersection.js +61 -0
  50. package/esm/parse/v3-2/schema/toSchemasV3.js +15 -2
  51. package/esm/types/Settings.d.ts +9 -0
  52. package/esm/types/Settings.js +2 -1
  53. package/esm/types/TypeSystem.d.ts +17 -2
  54. package/package.json +1 -1
  55. package/script/context/ParseContext.d.ts +3 -0
  56. package/script/context/ParseContext.js +17 -7
  57. package/script/context/generateTypes.d.ts +2 -2
  58. package/script/helpers/collateExamples.js +35 -17
  59. package/script/mod.d.ts +1 -0
  60. package/script/mod.js +1 -0
  61. package/script/oas/intersection/Intersection.d.ts +122 -0
  62. package/script/oas/intersection/Intersection.js +270 -0
  63. package/script/oas/mediaType/jsonMediaType.d.ts +1 -1
  64. package/script/oas/mediaType/jsonMediaType.js +3 -3
  65. package/script/oas/requestBody/RequestBody.d.ts +1 -1
  66. package/script/oas/requestBody/RequestBody.js +1 -1
  67. package/script/oas/response/Response.d.ts +1 -1
  68. package/script/oas/response/Response.js +1 -1
  69. package/script/oas/schema/Schema.d.ts +4 -2
  70. package/script/oas/schema/siblings.d.ts +10 -2
  71. package/script/oas/schema/siblings.js +89 -23
  72. package/script/oas/schemaPath/traverseSchema.d.ts +2 -0
  73. package/script/oas/schemaPath/traverseSchema.js +40 -0
  74. package/script/parse/allOfSystem.d.ts +3 -0
  75. package/script/parse/allOfSystem.js +2 -1
  76. package/script/parse/keptIntersection.d.ts +53 -0
  77. package/script/parse/keptIntersection.js +164 -0
  78. package/script/parse/keptRefs.d.ts +23 -0
  79. package/script/parse/keptRefs.js +63 -0
  80. package/script/parse/toCyclicRefs.d.ts +8 -0
  81. package/script/parse/toCyclicRefs.js +130 -0
  82. package/script/parse/toDeclaredTypes.d.ts +20 -0
  83. package/script/parse/toDeclaredTypes.js +48 -0
  84. package/script/parse/v3-0/_merge-all-of/merge-intersection.js +8 -4
  85. package/script/parse/v3-0/_merge-all-of/merge-union.js +7 -1
  86. package/script/parse/v3-0/_merge-all-of/merge.js +13 -0
  87. package/script/parse/v3-0/_merge-all-of/types.d.ts +3 -0
  88. package/script/parse/v3-0/intersection/toIntersection.d.ts +12 -0
  89. package/script/parse/v3-0/intersection/toIntersection.js +65 -0
  90. package/script/parse/v3-0/schema/toSchemasV3.js +13 -1
  91. package/script/parse/v3-1/_merge-all-of/merge-intersection.js +8 -4
  92. package/script/parse/v3-1/_merge-all-of/merge-union.js +7 -1
  93. package/script/parse/v3-1/_merge-all-of/merge.js +13 -0
  94. package/script/parse/v3-1/_merge-all-of/types.d.ts +3 -0
  95. package/script/parse/v3-1/intersection/toIntersection.d.ts +12 -0
  96. package/script/parse/v3-1/intersection/toIntersection.js +65 -0
  97. package/script/parse/v3-1/schema/toSchemasV3.js +15 -2
  98. package/script/parse/v3-2/_merge-all-of/merge-intersection.js +8 -4
  99. package/script/parse/v3-2/_merge-all-of/merge-union.js +7 -1
  100. package/script/parse/v3-2/_merge-all-of/merge.js +13 -0
  101. package/script/parse/v3-2/_merge-all-of/types.d.ts +3 -0
  102. package/script/parse/v3-2/intersection/toIntersection.d.ts +12 -0
  103. package/script/parse/v3-2/intersection/toIntersection.js +65 -0
  104. package/script/parse/v3-2/schema/toSchemasV3.js +15 -2
  105. package/script/types/Settings.d.ts +9 -0
  106. package/script/types/Settings.js +2 -1
  107. package/script/types/TypeSystem.d.ts +17 -2
@@ -0,0 +1,126 @@
1
+ import { isPlainObject } from './isPlainObject.js';
2
+ import { isRef, toRawRefTarget, toRefParts, toRefPathBucket, toRefPointer, toSchemaComponentRef, isRemoteRefPath } from '../helpers/refFns.js';
3
+ /** Keywords whose value is data, so a `$ref` inside it is not a reference. */
4
+ const DATA_KEYWORDS = ['default', 'example', 'examples', 'enum', 'const'];
5
+ /** Keywords whose value is a map of names to schemas: a name in it is not a keyword. */
6
+ const SCHEMA_MAP_KEYWORDS = ['properties', 'patternProperties', '$defs', 'definitions', 'dependentSchemas'];
7
+ /** Every `$ref` object anywhere inside a raw schema. */
8
+ const toSchemaRefs = (value) => {
9
+ if (Array.isArray(value)) {
10
+ return value.flatMap(toSchemaRefs);
11
+ }
12
+ if (!isPlainObject(value)) {
13
+ return [];
14
+ }
15
+ const nested = Object.entries(value).flatMap(([key, child]) => {
16
+ if (DATA_KEYWORDS.includes(key) || key.startsWith('x-')) {
17
+ return [];
18
+ }
19
+ return SCHEMA_MAP_KEYWORDS.includes(key) && isPlainObject(child)
20
+ ? Object.values(child).flatMap(toSchemaRefs)
21
+ : toSchemaRefs(child);
22
+ });
23
+ return isRef(value) ? [value, ...nested] : nested;
24
+ };
25
+ /** Every `$ref` object anywhere in a raw document. */
26
+ const toDocumentRefs = (value) => {
27
+ if (Array.isArray(value)) {
28
+ return value.flatMap(toDocumentRefs);
29
+ }
30
+ if (!isPlainObject(value)) {
31
+ return [];
32
+ }
33
+ const nested = Object.values(value).flatMap(toDocumentRefs);
34
+ return isRef(value) ? [value, ...nested] : nested;
35
+ };
36
+ /** Whether a ref can point at a schema: not a remote one, and not one to another kind of component. */
37
+ const canNameSchema = ({ refName, refPath }) => {
38
+ const bucket = toRefPathBucket(refPath);
39
+ return refName !== '' && !isRemoteRefPath(refPath) && (bucket === undefined || bucket === 'schemas');
40
+ };
41
+ /** The document's schema ref graph: each schema component and each other ref target, by `toRefPointer`, with the refs inside it. */
42
+ const toRefGraph = (document) => {
43
+ const components = isPlainObject(document) ? document.components : undefined;
44
+ const schemas = isPlainObject(components) ? components.schemas : undefined;
45
+ const names = isPlainObject(schemas) ? Object.keys(schemas) : [];
46
+ const graph = new Map();
47
+ const pending = [
48
+ ...names.map(name => toSchemaComponentRef(name)),
49
+ ...toDocumentRefs(document).map(({ $ref }) => toRefParts({ $ref }))
50
+ ];
51
+ // `pending` grows while it is walked: each target may hold refs to more targets.
52
+ for (const parts of pending) {
53
+ const key = toRefPointer(parts);
54
+ if (graph.has(key) || !canNameSchema(parts)) {
55
+ continue;
56
+ }
57
+ const edges = toSchemaRefs(toRawRefTarget(document, parts)).map(ref => ({
58
+ ref,
59
+ parts: toRefParts({ $ref: ref.$ref })
60
+ }));
61
+ graph.set(key, edges.map(edge => ({ ref: edge.ref, target: toRefPointer(edge.parts) })));
62
+ edges.forEach(edge => pending.push(edge.parts));
63
+ }
64
+ return graph;
65
+ };
66
+ /**
67
+ * The strongly connected set of each node, as a number (Tarjan). Iterative, so
68
+ * a long chain of refs does not run out of stack.
69
+ */
70
+ const toConnectedSets = (graph) => {
71
+ const visits = new Map();
72
+ const open = [];
73
+ const sets = new Map();
74
+ const enter = (node) => {
75
+ visits.set(node, { index: visits.size, low: visits.size });
76
+ open.push(node);
77
+ return { node, edges: graph.get(node) ?? [], next: 0 };
78
+ };
79
+ for (const root of graph.keys()) {
80
+ if (visits.has(root)) {
81
+ continue;
82
+ }
83
+ const frames = [enter(root)];
84
+ for (let frame = frames.at(-1); frame !== undefined; frame = frames.at(-1)) {
85
+ const visit = visits.get(frame.node);
86
+ const edge = frame.edges[frame.next];
87
+ if (visit === undefined) {
88
+ break;
89
+ }
90
+ if (edge !== undefined) {
91
+ frame.next += 1;
92
+ const seen = visits.get(edge.target);
93
+ if (seen === undefined) {
94
+ frames.push(enter(edge.target));
95
+ }
96
+ else if (!sets.has(edge.target)) {
97
+ visit.low = Math.min(visit.low, seen.index);
98
+ }
99
+ continue;
100
+ }
101
+ frames.pop();
102
+ const caller = frames.at(-1);
103
+ const parent = caller && visits.get(caller.node);
104
+ if (parent) {
105
+ parent.low = Math.min(parent.low, visit.low);
106
+ }
107
+ if (visit.low === visit.index) {
108
+ const id = visit.index;
109
+ open.splice(open.lastIndexOf(frame.node)).forEach(node => sets.set(node, id));
110
+ }
111
+ }
112
+ }
113
+ return sets;
114
+ };
115
+ /**
116
+ * The `$ref` objects of a raw document that are in a cycle: the ref's target
117
+ * leads back, through any refs, to a schema that holds the ref. A ref inside a
118
+ * deep ref target is held by that target and by the schema around it.
119
+ *
120
+ * The answer depends on the document only, not on where a parse enters it.
121
+ */
122
+ export const toCyclicRefs = (document) => {
123
+ const graph = toRefGraph(document);
124
+ const sets = toConnectedSets(graph);
125
+ return new WeakSet([...graph].flatMap(([holder, edges]) => edges.filter(({ target }) => sets.get(target) === sets.get(holder)).map(({ ref }) => ref)));
126
+ };
@@ -0,0 +1,20 @@
1
+ import type { OpenAPIV3 } from 'openapi-types';
2
+ type SchemaOrReference = OpenAPIV3.SchemaObject | OpenAPIV3.ReferenceObject;
3
+ /** The types a schema allows, or `any`. */
4
+ export type DeclaredTypes = string[] | 'any';
5
+ type ToDeclaredTypesArgs = {
6
+ schema: SchemaOrReference;
7
+ /** The schema a ref names, or `undefined` when it names nothing. */
8
+ peek: (ref: OpenAPIV3.ReferenceObject) => OpenAPIV3.SchemaObject | undefined;
9
+ /** The types of each ref target met so far: `any` for one that is being read. */
10
+ known?: Map<string, DeclaredTypes>;
11
+ };
12
+ /**
13
+ * The types a schema declares, itself or through its refs and its `allOf`,
14
+ * `oneOf` and `anyOf` members. A member that leads back to a schema that is
15
+ * being read counts as any type, so the types are never too few.
16
+ */
17
+ export declare const toDeclaredTypes: ({ schema, peek, known }: ToDeclaredTypesArgs) => DeclaredTypes;
18
+ /** Whether two schemas' types have none in common. */
19
+ export declare const haveNoCommonType: (first: DeclaredTypes, second: DeclaredTypes) => boolean;
20
+ export {};
@@ -0,0 +1,43 @@
1
+ import { isRef, toRefParts, toRefPointer } from '../helpers/refFns.js';
2
+ /**
3
+ * The types a schema declares, itself or through its refs and its `allOf`,
4
+ * `oneOf` and `anyOf` members. A member that leads back to a schema that is
5
+ * being read counts as any type, so the types are never too few.
6
+ */
7
+ export const toDeclaredTypes = ({ schema, peek, known = new Map() }) => {
8
+ if (isRef(schema)) {
9
+ const pointer = toRefPointer(toRefParts({ $ref: schema.$ref }));
10
+ const found = known.get(pointer);
11
+ if (found !== undefined) {
12
+ return found;
13
+ }
14
+ known.set(pointer, 'any');
15
+ const target = peek(schema);
16
+ const types = target === undefined ? 'any' : toDeclaredTypes({ schema: target, peek, known });
17
+ known.set(pointer, types);
18
+ return types;
19
+ }
20
+ const toMemberTypes = (members) => (Array.isArray(members) ? members : [])
21
+ .filter((member) => typeof member === 'object' && member !== null)
22
+ .map(member => toDeclaredTypes({ schema: member, peek, known }));
23
+ const constraints = [
24
+ toOwnTypes(schema.type),
25
+ ...toMemberTypes(schema.allOf),
26
+ toUnionTypes(toMemberTypes(schema.oneOf)),
27
+ toUnionTypes(toMemberTypes(schema.anyOf))
28
+ ].filter(isTypeList);
29
+ const [first, ...rest] = constraints;
30
+ return first === undefined ? 'any' : rest.reduce(toCommonTypes, first);
31
+ };
32
+ /** Whether two schemas' types have none in common. */
33
+ export const haveNoCommonType = (first, second) => isTypeList(first) && isTypeList(second) && toCommonTypes(first, second).length === 0;
34
+ /** A `type` as a list without `null`, which 3.1 writes in one. Every integer is a number. */
35
+ const toOwnTypes = (type) => {
36
+ const types = (Array.isArray(type) ? type : [type])
37
+ .filter(item => typeof item === 'string' && item !== 'null')
38
+ .flatMap(item => (item === 'number' ? ['number', 'integer'] : [item]));
39
+ return types.length > 0 ? types : 'any';
40
+ };
41
+ const toUnionTypes = (members) => members.length > 0 && members.every(isTypeList) ? [...new Set(members.flat())] : 'any';
42
+ const isTypeList = (types) => Array.isArray(types);
43
+ const toCommonTypes = (first, second) => first.filter(type => second.includes(type));
@@ -1,16 +1,20 @@
1
1
  import { decomposeIntersection } from './decompose-intersection.js';
2
2
  import { mergeSchemasOrRefs } from './merge.js';
3
+ import { isEmpty } from '../../../helpers/isEmpty.js';
4
+ import { splitOwnKeywords, withOwnKeywords } from '../../keptIntersection.js';
3
5
  export const mergeIntersection = ({ schema, getRef, system }) => {
4
- const decomposed = decomposeIntersection({ schema });
5
- if (decomposed.length === 1) {
6
+ // Where a ref stays a ref, the wrapper's own keywords stay beside the `allOf`.
7
+ const { own, rest } = system.keptRefs?.holds(schema) ? splitOwnKeywords(schema) : { own: {}, rest: schema };
8
+ const decomposed = decomposeIntersection({ schema: rest });
9
+ if (decomposed.length === 1 && isEmpty(own)) {
6
10
  return decomposed[0];
7
11
  }
8
12
  const dereffed = decomposed.map(decomposed => {
9
- return '$ref' in decomposed ? getRef(decomposed) : decomposed;
13
+ return '$ref' in decomposed && !system.keptRefs?.has(decomposed) ? getRef(decomposed) : decomposed;
10
14
  });
11
15
  const result = dereffed.reduce((acc, decomposed) => {
12
16
  const merged = mergeSchemasOrRefs({ first: acc, second: decomposed, getRef, system });
13
17
  return merged;
14
18
  }, {});
15
- return result;
19
+ return withOwnKeywords(result, own);
16
20
  };
@@ -85,7 +85,13 @@ export const mergeCrossProduct = ({ first, second, getRef, system, groupType })
85
85
  const secondGroup = Array.isArray(second[groupType]) ? second[groupType] : [second];
86
86
  const mergedGroup = mergePairs({
87
87
  pairs: crossProduct(firstGroup, secondGroup),
88
- merge: ([firstItem, secondItem], pairSystem) => mergeSchemasOrRefs({ first: firstItem, second: secondItem, getRef, system: pairSystem }),
88
+ merge: ([firstItem, secondItem], pairSystem) => {
89
+ // A kept ref is not read into the merge, so its type is compared here.
90
+ if (pairSystem.allOf === 'strict' && system.keptRefs?.contradict(firstItem, secondItem)) {
91
+ throw new Error('Cannot merge schemas: a member has another type than the reference');
92
+ }
93
+ return mergeSchemasOrRefs({ first: firstItem, second: secondItem, getRef, system: pairSystem });
94
+ },
89
95
  system
90
96
  });
91
97
  return {
@@ -17,8 +17,21 @@ import { mergeIntersection } from './merge-intersection.js';
17
17
  import { mergeCrossProduct, toOwnSystem } from './merge-union.js';
18
18
  import { isEmpty } from '../../../helpers/isEmpty.js';
19
19
  import { isNullOnly, mergeNullOnly } from './nullable-merge.js';
20
+ import { mergeKept, toIntersectionParts } from '../../keptIntersection.js';
20
21
  import { withoutUnknownAnyOf } from '../../anyOfSystem.js';
21
22
  export const mergeSchemasOrRefs = ({ first, second, getRef, system }) => {
23
+ const { keptRefs } = system;
24
+ if (keptRefs && (toIntersectionParts(first, keptRefs) || toIntersectionParts(second, keptRefs))) {
25
+ return mergeKept({
26
+ first,
27
+ second,
28
+ keptRefs,
29
+ merge: (a, b) => mergeSchemasOrRefs({ first: a, second: b, getRef, system }),
30
+ mergeAllOf: schema => mergeIntersection({ schema, getRef, system: toOwnSystem(system) }),
31
+ readRef: getRef,
32
+ normalize: schema => schema
33
+ });
34
+ }
22
35
  if (containsRef(first, second)) {
23
36
  return mergeWithRef({ first, second, getRef, system });
24
37
  }
@@ -1,5 +1,6 @@
1
1
  import type { OpenAPIV3 } from 'openapi-types';
2
2
  import * as v from 'valibot';
3
+ import type { KeptRefs } from '../../keptRefs.js';
3
4
  export type GetRefFn = (ref: OpenAPIV3.ReferenceObject) => OpenAPIV3.SchemaObject;
4
5
  /**
5
6
  * The `system` settings as the merge reads them (`client.json#settings.system`),
@@ -22,6 +23,8 @@ export type MergeSystem = {
22
23
  anyOf?: 'union' | 'unknown';
23
24
  /** The keywords the merge read as any value: `anyOf` under `system.anyOf: unknown`. */
24
25
  unknown?: Set<string>;
26
+ /** The refs that stay refs (`system.intersections`). Left out: every ref is followed. */
27
+ keptRefs?: KeptRefs;
25
28
  };
26
29
  export type OneOfObject = {
27
30
  oneOf?: (OpenAPIV3.ReferenceObject | OpenAPIV3.SchemaObject)[];
@@ -0,0 +1,12 @@
1
+ import type { OpenAPIV3 } from 'openapi-types';
2
+ import type { ParseContextType } from '../../../context/parseTypes.js';
3
+ import type { StackTrail } from '../../../context/StackTrail.js';
4
+ import { OasIntersection } from '../../../oas/intersection/Intersection.js';
5
+ export type ToIntersectionArgs = {
6
+ /** The intersection's own keywords, without `allOf`. */
7
+ value: OpenAPIV3.SchemaObject;
8
+ members: (OpenAPIV3.ReferenceObject | OpenAPIV3.SchemaObject)[];
9
+ stackTrail: StackTrail;
10
+ context: ParseContextType;
11
+ };
12
+ export declare const toIntersection: ({ value, members, stackTrail, context }: ToIntersectionArgs) => OasIntersection;
@@ -0,0 +1,61 @@
1
+ import { OasIntersection } from '../../../oas/intersection/Intersection.js';
2
+ import { isRef } from '../../../helpers/refFns.js';
3
+ import { hasShapeKeyword } from '../../anyOfSystem.js';
4
+ import { withKeywordType } from '../../keptIntersection.js';
5
+ import { toSchemaV3 } from '../schema/toSchemasV3.js';
6
+ import { toUnknown } from '../unknown/toUnknown.js';
7
+ import { toSpecificationExtensionsV3 } from '../specificationExtensions/toSpecificationExtensionsV3.js';
8
+ import { parseNullable } from '../_helpers/parseNullable.js';
9
+ import { parseExample } from '../_helpers/parseExample.js';
10
+ import { parseDefault } from '../_helpers/parseDefault.js';
11
+ import { toExternalDocs } from '../externalDocs/toExternalDocs.js';
12
+ export const toIntersection = ({ value, members, stackTrail, context }) => {
13
+ const { nullable, value: valueWithoutNullable } = parseNullable({ value, context, stackTrail });
14
+ const { title, description, externalDocs, readOnly, writeOnly, deprecated, example: unparsedExample, default: unparsedDefaultValue, ...skipped } = valueWithoutNullable;
15
+ const example = parseExample({
16
+ value: unparsedExample,
17
+ context,
18
+ parent: value,
19
+ nullable,
20
+ check: isPresent,
21
+ toMessage: item => `Removed invalid example. Expected a non-null value, got: ${item}`,
22
+ stackTrail
23
+ });
24
+ const defaultValue = parseDefault({
25
+ value: unparsedDefaultValue,
26
+ context,
27
+ parent: value,
28
+ nullable,
29
+ check: isPresent,
30
+ toMessage: item => `Removed invalid default. Expected a non-null value, got: ${item}`,
31
+ stackTrail
32
+ });
33
+ const extensionFields = toSpecificationExtensionsV3({
34
+ skipped,
35
+ parent: value,
36
+ context,
37
+ stackTrail,
38
+ parentType: 'schema:allOf'
39
+ });
40
+ // A member with no shape of its own (`{ description }`) is any value: the
41
+ // parser must not guess a type from its `example`.
42
+ const membersParsed = members.map(withKeywordType).map((member, index) => stackTrail.trace(`${index}`, st => isRef(member) || hasShapeKeyword(member) || 'anyOf' in member || 'not' in member
43
+ ? toSchemaV3({ schema: member, stackTrail: st, context })
44
+ : toUnknown({ value: member, stackTrail: st, context })));
45
+ return context.withStackTrail(stackTrail, () => new OasIntersection({
46
+ title,
47
+ description,
48
+ externalDocs: stackTrail.trace('externalDocs', st => toExternalDocs({ externalDocs, stackTrail: st, context })),
49
+ nullable,
50
+ readOnly,
51
+ writeOnly,
52
+ deprecated,
53
+ default: defaultValue,
54
+ members: membersParsed,
55
+ example,
56
+ extensionFields
57
+ }, context));
58
+ };
59
+ // A value matches every member, so without resolving them the most we can
60
+ // check is that a present default/example is not `null` on a non-nullable schema.
61
+ const isPresent = (value) => value !== null && value !== undefined;
@@ -10,6 +10,8 @@ import { toBoolean } from '../boolean/toBoolean.js';
10
10
  import { toString } from '../string/toString.js';
11
11
  import { toUnknown } from '../unknown/toUnknown.js';
12
12
  import { toUnion } from '../union/toUnion.js';
13
+ import { toIntersection } from '../intersection/toIntersection.js';
14
+ import { toIntersectionParts, toSiteIntersection } from '../../keptIntersection.js';
13
15
  import { toGetRef } from '../../../helpers/refFns.js';
14
16
  import { toSiblingKeywords } from '../../toSiblingKeywords.js';
15
17
  import { logAllOfContradictions, toAllOfSystem } from '../../allOfSystem.js';
@@ -182,7 +184,17 @@ export const toSchemaV3 = ({ schema, stackTrail, context }) => {
182
184
  });
183
185
  logAllOfContradictions({ system, stackTrail, parent: schema, context });
184
186
  logMergedUnknownAnyOf({ system, stackTrail, parent: schema, context });
185
- return toSchemaV3({ schema: merged, stackTrail: st, context });
187
+ const parts = system.keptRefs && toIntersectionParts(merged, system.keptRefs);
188
+ if (parts === undefined) {
189
+ return toSchemaV3({ schema: merged, stackTrail: st, context });
190
+ }
191
+ const { own, members: kept } = toSiteIntersection(parts);
192
+ const [only] = kept;
193
+ if (kept.length > 1 || only === undefined) {
194
+ return toIntersection({ value: own, members: kept, stackTrail: st, context });
195
+ }
196
+ // An intersection of one ref is that ref with the keywords beside it.
197
+ return toSchemaV3({ schema: isEmpty(own) ? only : { ...own, allOf: [only] }, stackTrail: st, context });
186
198
  });
187
199
  }
188
200
  if ('oneOf' in schema && Array.isArray(schema.oneOf)) {
@@ -1,16 +1,20 @@
1
1
  import { decomposeIntersection } from './decompose-intersection.js';
2
2
  import { mergeSchemasOrRefs } from './merge.js';
3
+ import { isEmpty } from '../../../helpers/isEmpty.js';
4
+ import { splitOwnKeywords, withOwnKeywords } from '../../keptIntersection.js';
3
5
  export const mergeIntersection = ({ schema, getRef, normalize, system }) => {
4
- const decomposed = decomposeIntersection({ schema });
5
- if (decomposed.length === 1) {
6
+ // Where a ref stays a ref, the wrapper's own keywords stay beside the `allOf`.
7
+ const { own, rest } = system.keptRefs?.holds(schema) ? splitOwnKeywords(schema) : { own: {}, rest: schema };
8
+ const decomposed = decomposeIntersection({ schema: rest });
9
+ if (decomposed.length === 1 && isEmpty(own)) {
6
10
  return decomposed[0];
7
11
  }
8
12
  const dereffed = decomposed.map(decomposed => {
9
- return '$ref' in decomposed ? getRef(decomposed) : decomposed;
13
+ return '$ref' in decomposed && !system.keptRefs?.has(decomposed) ? getRef(decomposed) : decomposed;
10
14
  });
11
15
  const result = dereffed.reduce((acc, decomposed) => {
12
16
  const merged = mergeSchemasOrRefs({ first: acc, second: decomposed, getRef, normalize, system });
13
17
  return merged;
14
18
  }, {});
15
- return result;
19
+ return withOwnKeywords(result, own);
16
20
  };
@@ -101,7 +101,13 @@ export const mergeCrossProduct = ({ first, second, getRef, normalize, system, gr
101
101
  secondGroup.length !== secondMembers.length;
102
102
  const mergedGroup = mergePairs({
103
103
  pairs: crossProduct(withGroupSiblings({ schema: first, members: firstGroup, getRef, normalize, system, groupType }), withGroupSiblings({ schema: second, members: secondGroup, getRef, normalize, system, groupType })),
104
- merge: ([firstItem, secondItem], pairSystem) => mergeSchemasOrRefs({ first: firstItem, second: secondItem, getRef, normalize, system: pairSystem }),
104
+ merge: ([firstItem, secondItem], pairSystem) => {
105
+ // A kept ref is not read into the merge, so its type is compared here.
106
+ if (pairSystem.allOf === 'strict' && system.keptRefs?.contradict(firstItem, secondItem)) {
107
+ throw new Error('Cannot merge schemas: a member has another type than the reference');
108
+ }
109
+ return mergeSchemasOrRefs({ first: firstItem, second: secondItem, getRef, normalize, system: pairSystem });
110
+ },
105
111
  system
106
112
  });
107
113
  // A nested group is spread into this one below; its `nullable` carries over.
@@ -17,6 +17,7 @@ import { mergeIntersection } from './merge-intersection.js';
17
17
  import { collapseNullOnlyUnion, mergeCrossProduct, toOwnSystem } from './merge-union.js';
18
18
  import { isEmpty } from '../../../helpers/isEmpty.js';
19
19
  import { isNullOnly, mergeNullOnly } from './nullable-merge.js';
20
+ import { mergeKept, toIntersectionParts } from '../../keptIntersection.js';
20
21
  import { withoutUnknownAnyOf } from '../../anyOfSystem.js';
21
22
  export const mergeSchemasOrRefs = ({ first: inputFirst, second: inputSecond, getRef, normalize, system }) => {
22
23
  const first = isRef(inputFirst)
@@ -25,6 +26,18 @@ export const mergeSchemasOrRefs = ({ first: inputFirst, second: inputSecond, get
25
26
  const second = isRef(inputSecond)
26
27
  ? inputSecond
27
28
  : collapseNullOnlyUnion(normalize(inputSecond), normalize);
29
+ const { keptRefs } = system;
30
+ if (keptRefs && (toIntersectionParts(first, keptRefs) || toIntersectionParts(second, keptRefs))) {
31
+ return mergeKept({
32
+ first,
33
+ second,
34
+ keptRefs,
35
+ merge: (a, b) => mergeSchemasOrRefs({ first: a, second: b, getRef, normalize, system }),
36
+ mergeAllOf: schema => mergeIntersection({ schema, getRef, normalize, system: toOwnSystem(system) }),
37
+ readRef: ref => normalize(getRef(ref)),
38
+ normalize
39
+ });
40
+ }
28
41
  if (containsRef(first, second)) {
29
42
  return mergeWithRef({ first, second, getRef, normalize, system });
30
43
  }
@@ -1,5 +1,6 @@
1
1
  import type { OpenAPIV3 } from 'openapi-types';
2
2
  import * as v from 'valibot';
3
+ import type { KeptRefs } from '../../keptRefs.js';
3
4
  export type GetRefFn = (ref: OpenAPIV3.ReferenceObject) => OpenAPIV3.SchemaObject;
4
5
  /**
5
6
  * Maps a schema the merge reads (a member, a nested property or item schema,
@@ -28,6 +29,8 @@ export type MergeSystem = {
28
29
  anyOf?: 'union' | 'unknown';
29
30
  /** The keywords the merge read as any value: `anyOf` under `system.anyOf: unknown`. */
30
31
  unknown?: Set<string>;
32
+ /** The refs that stay refs (`system.intersections`). Left out: every ref is followed. */
33
+ keptRefs?: KeptRefs;
31
34
  };
32
35
  export type OneOfObject = {
33
36
  oneOf?: (OpenAPIV3.ReferenceObject | OpenAPIV3.SchemaObject)[];
@@ -0,0 +1,12 @@
1
+ import type { OpenAPIV3 } from 'openapi-types';
2
+ import type { ParseContextType } from '../../../context/parseTypes.js';
3
+ import type { StackTrail } from '../../../context/StackTrail.js';
4
+ import { OasIntersection } from '../../../oas/intersection/Intersection.js';
5
+ export type ToIntersectionArgs = {
6
+ /** The intersection's own keywords, without `allOf`. */
7
+ value: OpenAPIV3.SchemaObject;
8
+ members: (OpenAPIV3.ReferenceObject | OpenAPIV3.SchemaObject)[];
9
+ stackTrail: StackTrail;
10
+ context: ParseContextType;
11
+ };
12
+ export declare const toIntersection: ({ value, members, stackTrail, context }: ToIntersectionArgs) => OasIntersection;
@@ -0,0 +1,61 @@
1
+ import { OasIntersection } from '../../../oas/intersection/Intersection.js';
2
+ import { isRef } from '../../../helpers/refFns.js';
3
+ import { hasShapeKeyword } from '../../anyOfSystem.js';
4
+ import { withKeywordType } from '../../keptIntersection.js';
5
+ import { toSchemaV3 } from '../schema/toSchemasV3.js';
6
+ import { toUnknown } from '../unknown/toUnknown.js';
7
+ import { toSpecificationExtensionsV3 } from '../specificationExtensions/toSpecificationExtensionsV3.js';
8
+ import { parseNullable } from '../_helpers/parseNullable.js';
9
+ import { parseExample } from '../_helpers/parseExample.js';
10
+ import { parseDefault } from '../_helpers/parseDefault.js';
11
+ import { toExternalDocs } from '../externalDocs/toExternalDocs.js';
12
+ export const toIntersection = ({ value, members, stackTrail, context }) => {
13
+ const { nullable, value: valueWithoutNullable } = parseNullable({ value, context, stackTrail });
14
+ const { title, description, externalDocs, readOnly, writeOnly, deprecated, example: unparsedExample, default: unparsedDefaultValue, ...skipped } = valueWithoutNullable;
15
+ const example = parseExample({
16
+ value: unparsedExample,
17
+ context,
18
+ parent: value,
19
+ nullable,
20
+ check: isPresent,
21
+ toMessage: item => `Removed invalid example. Expected a non-null value, got: ${item}`,
22
+ stackTrail
23
+ });
24
+ const defaultValue = parseDefault({
25
+ value: unparsedDefaultValue,
26
+ context,
27
+ parent: value,
28
+ nullable,
29
+ check: isPresent,
30
+ toMessage: item => `Removed invalid default. Expected a non-null value, got: ${item}`,
31
+ stackTrail
32
+ });
33
+ const extensionFields = toSpecificationExtensionsV3({
34
+ skipped,
35
+ parent: value,
36
+ context,
37
+ stackTrail,
38
+ parentType: 'schema:allOf'
39
+ });
40
+ // A member with no shape of its own (`{ description }`) is any value: the
41
+ // parser must not guess a type from its `example`.
42
+ const membersParsed = members.map(withKeywordType).map((member, index) => stackTrail.trace(`${index}`, st => isRef(member) || hasShapeKeyword(member) || 'anyOf' in member || 'not' in member
43
+ ? toSchemaV3({ schema: member, stackTrail: st, context })
44
+ : toUnknown({ value: member, stackTrail: st, context })));
45
+ return context.withStackTrail(stackTrail, () => new OasIntersection({
46
+ title,
47
+ description,
48
+ externalDocs: stackTrail.trace('externalDocs', st => toExternalDocs({ externalDocs, stackTrail: st, context })),
49
+ nullable,
50
+ readOnly,
51
+ writeOnly,
52
+ deprecated,
53
+ default: defaultValue,
54
+ members: membersParsed,
55
+ example,
56
+ extensionFields
57
+ }, context));
58
+ };
59
+ // A value matches every member, so without resolving them the most we can
60
+ // check is that a present default/example is not `null` on a non-nullable schema.
61
+ const isPresent = (value) => value !== null && value !== undefined;
@@ -10,6 +10,8 @@ import { toBoolean } from '../boolean/toBoolean.js';
10
10
  import { toString } from '../string/toString.js';
11
11
  import { toUnknown } from '../unknown/toUnknown.js';
12
12
  import { toUnion } from '../union/toUnion.js';
13
+ import { toIntersection } from '../intersection/toIntersection.js';
14
+ import { toIntersectionParts, toSiteIntersection } from '../../keptIntersection.js';
13
15
  import { toGetRef } from '../../../helpers/refFns.js';
14
16
  import { toSiblingKeywords } from '../../toSiblingKeywords.js';
15
17
  import { logAllOfContradictions, toAllOfSystem } from '../../allOfSystem.js';
@@ -132,8 +134,9 @@ export const toSchemaV3 = ({ schema, stackTrail, context }) => {
132
134
  });
133
135
  }
134
136
  const members = Array.isArray(allOf) ? allOf : [];
137
+ const bareRef = context.keptRefs?.copy(schema, { $ref }) ?? { $ref };
135
138
  return Object.keys(keywords).length > 0
136
- ? toSchemaV3({ schema: { ...keywords, allOf: [{ $ref }, ...members] }, stackTrail, context })
139
+ ? toSchemaV3({ schema: { ...keywords, allOf: [bareRef, ...members] }, stackTrail, context })
137
140
  : toRefV31({ ref: schema, refType: 'schema', stackTrail, context });
138
141
  }
139
142
  // OpenAPI `not` has no faithful TypeScript representation: a generated type
@@ -235,7 +238,17 @@ export const toSchemaV3 = ({ schema, stackTrail, context }) => {
235
238
  });
236
239
  logAllOfContradictions({ system, stackTrail, parent: schema, context });
237
240
  logMergedUnknownAnyOf({ system, stackTrail, parent: schema, context });
238
- return toSchemaV3({ schema: merged, stackTrail: st, context });
241
+ const parts = system.keptRefs && toIntersectionParts(merged, system.keptRefs);
242
+ if (parts === undefined) {
243
+ return toSchemaV3({ schema: merged, stackTrail: st, context });
244
+ }
245
+ const { own, members: kept } = toSiteIntersection(parts);
246
+ const [only] = kept;
247
+ if (kept.length > 1 || only === undefined) {
248
+ return toIntersection({ value: own, members: kept, stackTrail: st, context });
249
+ }
250
+ // An intersection of one ref is that ref with the keywords beside it.
251
+ return toSchemaV3({ schema: isEmpty(own) ? only : { ...own, allOf: [only] }, stackTrail: st, context });
239
252
  });
240
253
  }
241
254
  // A `oneOf`/`anyOf` of only null members reads as nullable, not as an
@@ -1,16 +1,20 @@
1
1
  import { decomposeIntersection } from './decompose-intersection.js';
2
2
  import { mergeSchemasOrRefs } from './merge.js';
3
+ import { isEmpty } from '../../../helpers/isEmpty.js';
4
+ import { splitOwnKeywords, withOwnKeywords } from '../../keptIntersection.js';
3
5
  export const mergeIntersection = ({ schema, getRef, normalize, system }) => {
4
- const decomposed = decomposeIntersection({ schema });
5
- if (decomposed.length === 1) {
6
+ // Where a ref stays a ref, the wrapper's own keywords stay beside the `allOf`.
7
+ const { own, rest } = system.keptRefs?.holds(schema) ? splitOwnKeywords(schema) : { own: {}, rest: schema };
8
+ const decomposed = decomposeIntersection({ schema: rest });
9
+ if (decomposed.length === 1 && isEmpty(own)) {
6
10
  return decomposed[0];
7
11
  }
8
12
  const dereffed = decomposed.map(decomposed => {
9
- return '$ref' in decomposed ? getRef(decomposed) : decomposed;
13
+ return '$ref' in decomposed && !system.keptRefs?.has(decomposed) ? getRef(decomposed) : decomposed;
10
14
  });
11
15
  const result = dereffed.reduce((acc, decomposed) => {
12
16
  const merged = mergeSchemasOrRefs({ first: acc, second: decomposed, getRef, normalize, system });
13
17
  return merged;
14
18
  }, {});
15
- return result;
19
+ return withOwnKeywords(result, own);
16
20
  };
@@ -101,7 +101,13 @@ export const mergeCrossProduct = ({ first, second, getRef, normalize, system, gr
101
101
  secondGroup.length !== secondMembers.length;
102
102
  const mergedGroup = mergePairs({
103
103
  pairs: crossProduct(withGroupSiblings({ schema: first, members: firstGroup, getRef, normalize, system, groupType }), withGroupSiblings({ schema: second, members: secondGroup, getRef, normalize, system, groupType })),
104
- merge: ([firstItem, secondItem], pairSystem) => mergeSchemasOrRefs({ first: firstItem, second: secondItem, getRef, normalize, system: pairSystem }),
104
+ merge: ([firstItem, secondItem], pairSystem) => {
105
+ // A kept ref is not read into the merge, so its type is compared here.
106
+ if (pairSystem.allOf === 'strict' && system.keptRefs?.contradict(firstItem, secondItem)) {
107
+ throw new Error('Cannot merge schemas: a member has another type than the reference');
108
+ }
109
+ return mergeSchemasOrRefs({ first: firstItem, second: secondItem, getRef, normalize, system: pairSystem });
110
+ },
105
111
  system
106
112
  });
107
113
  // A nested group is spread into this one below; its `nullable` carries over.
@@ -17,6 +17,7 @@ import { mergeIntersection } from './merge-intersection.js';
17
17
  import { collapseNullOnlyUnion, mergeCrossProduct, toOwnSystem } from './merge-union.js';
18
18
  import { isEmpty } from '../../../helpers/isEmpty.js';
19
19
  import { isNullOnly, mergeNullOnly } from './nullable-merge.js';
20
+ import { mergeKept, toIntersectionParts } from '../../keptIntersection.js';
20
21
  import { withoutUnknownAnyOf } from '../../anyOfSystem.js';
21
22
  export const mergeSchemasOrRefs = ({ first: inputFirst, second: inputSecond, getRef, normalize, system }) => {
22
23
  const first = isRef(inputFirst)
@@ -25,6 +26,18 @@ export const mergeSchemasOrRefs = ({ first: inputFirst, second: inputSecond, get
25
26
  const second = isRef(inputSecond)
26
27
  ? inputSecond
27
28
  : collapseNullOnlyUnion(normalize(inputSecond), normalize);
29
+ const { keptRefs } = system;
30
+ if (keptRefs && (toIntersectionParts(first, keptRefs) || toIntersectionParts(second, keptRefs))) {
31
+ return mergeKept({
32
+ first,
33
+ second,
34
+ keptRefs,
35
+ merge: (a, b) => mergeSchemasOrRefs({ first: a, second: b, getRef, normalize, system }),
36
+ mergeAllOf: schema => mergeIntersection({ schema, getRef, normalize, system: toOwnSystem(system) }),
37
+ readRef: ref => normalize(getRef(ref)),
38
+ normalize
39
+ });
40
+ }
28
41
  if (containsRef(first, second)) {
29
42
  return mergeWithRef({ first, second, getRef, normalize, system });
30
43
  }