@skmtc/core 0.44.2 → 0.46.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 (113) hide show
  1. package/esm/anchors/attribute.js +3 -2
  2. package/esm/context/CoreContext.d.ts +1 -1
  3. package/esm/context/CoreContext.js +1 -1
  4. package/esm/context/GenerateContext.d.ts +13 -10
  5. package/esm/context/GenerateContext.js +36 -25
  6. package/esm/context/ParseContext.js +136 -34
  7. package/esm/context/generateTypes.d.ts +7 -6
  8. package/esm/context/generateTypes.js +2 -0
  9. package/esm/dsl/GeneratorKeys.d.ts +21 -15
  10. package/esm/dsl/GeneratorKeys.js +16 -11
  11. package/esm/dsl/Inserted.d.ts +1 -1
  12. package/esm/dsl/Inserted.js +1 -1
  13. package/esm/dsl/model/ModelDriver.d.ts +6 -5
  14. package/esm/dsl/model/ModelDriver.js +22 -20
  15. package/esm/dsl/model/toModelEntry.d.ts +18 -18
  16. package/esm/dsl/model/toModelEntry.js +9 -9
  17. package/esm/dsl/model/toModelProjectionBase.d.ts +17 -16
  18. package/esm/dsl/model/toModelProjectionBase.js +12 -8
  19. package/esm/dsl/model/types.d.ts +26 -17
  20. package/esm/dsl/operation/gql/toGqlOperationProjectionBase.d.ts +2 -2
  21. package/esm/dsl/operation/gql/toGqlOperationProjectionBase.js +2 -2
  22. package/esm/dsl/operation/oas/toOasOperationProjectionBase.d.ts +2 -2
  23. package/esm/dsl/operation/oas/toOasOperationProjectionBase.js +2 -2
  24. package/esm/dsl/webhook/toWebhookProjectionBase.d.ts +2 -2
  25. package/esm/dsl/webhook/toWebhookProjectionBase.js +2 -2
  26. package/esm/helpers/refFns.d.ts +108 -43
  27. package/esm/helpers/refFns.js +166 -57
  28. package/esm/oas/document/Document.d.ts +6 -0
  29. package/esm/oas/document/Document.js +44 -2
  30. package/esm/oas/header/Header.js +4 -1
  31. package/esm/oas/parameter/Parameter.d.ts +1 -1
  32. package/esm/oas/parameter/Parameter.js +5 -2
  33. package/esm/oas/ref/DanglingRefError.d.ts +5 -2
  34. package/esm/oas/ref/DanglingRefError.js +4 -3
  35. package/esm/oas/ref/Ref.d.ts +23 -12
  36. package/esm/oas/ref/Ref.js +68 -72
  37. package/esm/oas/schemaPath/traverseSchema.js +11 -5
  38. package/esm/parse/missingSchema.d.ts +30 -0
  39. package/esm/parse/missingSchema.js +33 -0
  40. package/esm/parse/v3-0/header/toHeadersV3.js +5 -0
  41. package/esm/parse/v3-0/parameter/toParameterV3.js +11 -0
  42. package/esm/parse/v3-0/ref/toRefTargetV3.d.ts +23 -0
  43. package/esm/parse/v3-0/ref/toRefTargetV3.js +70 -0
  44. package/esm/parse/v3-1/header/toHeadersV3.js +5 -0
  45. package/esm/parse/v3-1/parameter/toParameterV3.js +11 -0
  46. package/esm/parse/v3-1/ref/toRefTargetV3.d.ts +23 -0
  47. package/esm/parse/v3-1/ref/toRefTargetV3.js +70 -0
  48. package/esm/parse/v3-2/header/toHeadersV3.js +5 -0
  49. package/esm/parse/v3-2/parameter/toParameterV3.js +11 -0
  50. package/esm/parse/v3-2/ref/toRefTargetV3.d.ts +23 -0
  51. package/esm/parse/v3-2/ref/toRefTargetV3.js +70 -0
  52. package/esm/types/GeneratorType.d.ts +1 -1
  53. package/esm/types/ProjectionOptions.d.ts +1 -1
  54. package/esm/types/ProjectionOptions.js +1 -1
  55. package/esm/types/RefName.d.ts +3 -3
  56. package/esm/types/TypeSystem.d.ts +3 -3
  57. package/package.json +1 -1
  58. package/script/anchors/attribute.js +3 -2
  59. package/script/context/CoreContext.d.ts +1 -1
  60. package/script/context/CoreContext.js +1 -1
  61. package/script/context/GenerateContext.d.ts +13 -10
  62. package/script/context/GenerateContext.js +36 -25
  63. package/script/context/ParseContext.js +135 -33
  64. package/script/context/generateTypes.d.ts +7 -6
  65. package/script/context/generateTypes.js +2 -0
  66. package/script/dsl/GeneratorKeys.d.ts +21 -15
  67. package/script/dsl/GeneratorKeys.js +16 -11
  68. package/script/dsl/Inserted.d.ts +1 -1
  69. package/script/dsl/Inserted.js +1 -1
  70. package/script/dsl/model/ModelDriver.d.ts +6 -5
  71. package/script/dsl/model/ModelDriver.js +22 -20
  72. package/script/dsl/model/toModelEntry.d.ts +18 -18
  73. package/script/dsl/model/toModelEntry.js +9 -9
  74. package/script/dsl/model/toModelProjectionBase.d.ts +17 -16
  75. package/script/dsl/model/toModelProjectionBase.js +12 -8
  76. package/script/dsl/model/types.d.ts +26 -17
  77. package/script/dsl/operation/gql/toGqlOperationProjectionBase.d.ts +2 -2
  78. package/script/dsl/operation/gql/toGqlOperationProjectionBase.js +2 -2
  79. package/script/dsl/operation/oas/toOasOperationProjectionBase.d.ts +2 -2
  80. package/script/dsl/operation/oas/toOasOperationProjectionBase.js +2 -2
  81. package/script/dsl/webhook/toWebhookProjectionBase.d.ts +2 -2
  82. package/script/dsl/webhook/toWebhookProjectionBase.js +2 -2
  83. package/script/helpers/refFns.d.ts +108 -43
  84. package/script/helpers/refFns.js +180 -59
  85. package/script/oas/document/Document.d.ts +6 -0
  86. package/script/oas/document/Document.js +44 -2
  87. package/script/oas/header/Header.js +4 -1
  88. package/script/oas/parameter/Parameter.d.ts +1 -1
  89. package/script/oas/parameter/Parameter.js +5 -2
  90. package/script/oas/ref/DanglingRefError.d.ts +5 -2
  91. package/script/oas/ref/DanglingRefError.js +4 -3
  92. package/script/oas/ref/Ref.d.ts +23 -12
  93. package/script/oas/ref/Ref.js +67 -71
  94. package/script/oas/schemaPath/traverseSchema.js +10 -4
  95. package/script/parse/missingSchema.d.ts +30 -0
  96. package/script/parse/missingSchema.js +38 -0
  97. package/script/parse/v3-0/header/toHeadersV3.js +5 -0
  98. package/script/parse/v3-0/parameter/toParameterV3.js +11 -0
  99. package/script/parse/v3-0/ref/toRefTargetV3.d.ts +23 -0
  100. package/script/parse/v3-0/ref/toRefTargetV3.js +74 -0
  101. package/script/parse/v3-1/header/toHeadersV3.js +5 -0
  102. package/script/parse/v3-1/parameter/toParameterV3.js +11 -0
  103. package/script/parse/v3-1/ref/toRefTargetV3.d.ts +23 -0
  104. package/script/parse/v3-1/ref/toRefTargetV3.js +74 -0
  105. package/script/parse/v3-2/header/toHeadersV3.js +5 -0
  106. package/script/parse/v3-2/parameter/toParameterV3.js +11 -0
  107. package/script/parse/v3-2/ref/toRefTargetV3.d.ts +23 -0
  108. package/script/parse/v3-2/ref/toRefTargetV3.js +74 -0
  109. package/script/types/GeneratorType.d.ts +1 -1
  110. package/script/types/ProjectionOptions.d.ts +1 -1
  111. package/script/types/ProjectionOptions.js +1 -1
  112. package/script/types/RefName.d.ts +3 -3
  113. package/script/types/TypeSystem.d.ts +3 -3
@@ -11,7 +11,7 @@ import type { GeneratedValue } from '../GeneratedValue.js';
11
11
  import type { Inserted } from '../Inserted.js';
12
12
  import type { ModelProjection, NormalizedModelProjection } from '../model/types.js';
13
13
  import type { OasOperationProjection } from '../operation/oas/types.js';
14
- import type { RefName } from '../../types/RefName.js';
14
+ import type { RefParts } from '../../helpers/refFns.js';
15
15
  import type { OasSchema } from '../../oas/schema/Schema.js';
16
16
  import type { OasRef } from '../../oas/ref/Ref.js';
17
17
  import type { OasVoid } from '../../oas/void/Void.js';
@@ -98,7 +98,7 @@ export declare const toWebhookProjectionBase: <EnrichmentType = undefined, IdTyp
98
98
  * webhook's payload type). `{ options }` is required when the peer
99
99
  * declares options and refused when it does not.
100
100
  */
101
- insertModel<V extends GeneratedValue, PeerEnrichmentType_1 = undefined, PeerProjectionOptions_1 = undefined>(projection: ModelProjection<V, PeerEnrichmentType_1, PeerProjectionOptions_1>, refName: RefName, ...rest: ProjectionOptionsRest<PeerInsertOptions<PeerProjectionOptions_1>, PeerProjectionOptions_1>): Inserted<V, PeerEnrichmentType_1>;
101
+ insertModel<V extends GeneratedValue, PeerEnrichmentType_1 = undefined, PeerProjectionOptions_1 = undefined>(projection: ModelProjection<V, PeerEnrichmentType_1, PeerProjectionOptions_1>, ref: RefParts, ...rest: ProjectionOptionsRest<PeerInsertOptions<PeerProjectionOptions_1>, PeerProjectionOptions_1>): Inserted<V, PeerEnrichmentType_1>;
102
102
  /**
103
103
  * Insert a related model with reference normalization. Useful for inline
104
104
  * payload schemas where the schema may be either a `$ref` or a concrete
@@ -73,8 +73,8 @@ const toWebhookProjectionBase = (base, config) => {
73
73
  * webhook's payload type). `{ options }` is required when the peer
74
74
  * declares options and refused when it does not.
75
75
  */
76
- insertModel(projection, refName, ...rest) {
77
- return this.context.insertModel(projection, refName, {
76
+ insertModel(projection, ref, ...rest) {
77
+ return this.context.insertModel(projection, ref, {
78
78
  ...(0, InsertOptions_js_1.toPeerInsertOptions)(rest),
79
79
  destinationPath: this.settings.exportPath
80
80
  });
@@ -3,52 +3,117 @@ import type { RefName } from '../types/RefName.js';
3
3
  import type { OpenAPIV3 } from 'openapi-types';
4
4
  import type { ReferenceObject } from '../parse/v3-0/_merge-all-of/types.js';
5
5
  import { DanglingRefError } from '../oas/ref/DanglingRefError.js';
6
+ import type { OasRefData } from '../oas/ref/ref-types.js';
7
+ /** The kind of component a `$ref` points at: `schema`, `parameter`, `response`, and so on. */
8
+ type RefType = OasRefData['refType'];
6
9
  /**
7
- * Extracts a reference name from an OpenAPI $ref string.
8
- *
9
- * This function parses JSON Pointer references (like '#/components/schemas/User')
10
- * and extracts the final component as a branded RefName type. It's used throughout
11
- * the SKMTC system to convert string references into type-safe reference names.
12
- *
13
- * A `$ref` is a URI fragment that holds a JSON pointer (RFC 6901), so the name
14
- * is unescaped as one: `%20` is a space, and `~1` and `~0` are `/` and `~`.
15
- * `#/components/schemas/Foo%20Bar` names the component `Foo Bar`.
16
- *
17
- * @param $ref - The OpenAPI reference string (e.g., '#/components/schemas/User')
18
- * @returns The extracted reference name as a branded RefName type
19
- *
20
- * @throws {Error} When the reference string is invalid or empty
21
- *
22
- * @example Basic usage
23
- * ```typescript
24
- * import { toRefName } from '@skmtc/core/helpers';
25
- *
26
- * const refName = toRefName('#/components/schemas/User');
27
- * console.log(refName); // 'User' (typed as RefName)
28
- *
29
- * const responseRef = toRefName('#/components/responses/ErrorResponse');
30
- * console.log(responseRef); // 'ErrorResponse' (typed as RefName)
31
- * ```
10
+ * Where a `$ref` points, in two parts: `refPath`, the JSON pointer before its
11
+ * last segment, and `refName`, that last segment unescaped.
12
+ * `#/components/schemas/Pet` is `refPath` `#/components/schemas` and `refName`
13
+ * `Pet`. `#/components/schemas/__sharedInput/$defs/schema0` is `refPath`
14
+ * `#/components/schemas/__sharedInput/$defs` and `refName` `schema0`.
15
+ *
16
+ * `refPath` has one spelling, whatever the `$ref` has: no percent escapes, and
17
+ * `~` and `/` in a segment as `~0` and `~1` (RFC 6901). Two refs to one place
18
+ * have equal parts.
19
+ *
20
+ * The model API takes a model's ref in this shape (`insertModel(Peer, ref)`,
21
+ * `toIdentifierName({ ref, … })`), so the two parts travel together. An
22
+ * `OasRef` has both fields and fits it as it is.
23
+ */
24
+ export type RefParts = {
25
+ /** The last segment of the pointer, unescaped. Empty for a `$ref` that ends in `/`. */
26
+ refName: RefName;
27
+ /**
28
+ * The pointer before the last segment, starting with `#`, with no percent
29
+ * escapes. A remote `$ref` ({@link isRemoteRefPath}) has the file before the `#`.
30
+ */
31
+ refPath: string;
32
+ };
33
+ type ToRefPartsArgs = {
34
+ $ref: string;
35
+ };
36
+ /**
37
+ * Splits a `$ref` into {@link RefParts}.
32
38
  *
33
- * @example Error cases
34
- * ```typescript
35
- * // These will throw errors:
36
- * toRefName('invalid/ref/'); // Error: 'Invalid reference'
37
- * toRefName('#/components/schemas/'); // Error: 'Invalid reference'
38
- * ```
39
+ * A `$ref` is a URI whose fragment holds a JSON pointer (RFC 6901), so the
40
+ * name is unescaped as one: `%20` is a space, and `~1` and `~0` are `/` and
41
+ * `~`. `#/components/schemas/Foo%20Bar` names the component `Foo Bar`.
39
42
  *
40
- * @example Integration with OAS processing
41
- * ```typescript
42
- * class SchemaProcessor {
43
- * processReference(ref: string) {
44
- * const refName = toRefName(ref);
45
- * const schema = this.document.components.schemas[refName];
46
- * return this.processSchema(schema, refName);
47
- * }
48
- * }
49
- * ```
43
+ * A remote `$ref`, one that does not start with `#`, points outside the
44
+ * document, so its `refPath` does not start with `#` and it names nothing
45
+ * here: `other.yml#/components/schemas/A` is `refPath`
46
+ * `other.yml#/components/schemas` and `refName` `A`. This never throws: a
47
+ * `$ref` that names nothing is found out when it is resolved.
48
+ */
49
+ export declare const toRefParts: ({ $ref }: ToRefPartsArgs) => RefParts;
50
+ /** The `components` bucket that holds components of each kind: `schemas`, `parameters`, and so on. */
51
+ export declare const toComponentsBucket: (refType: RefType) => string;
52
+ /**
53
+ * Whether a `refPath` is that of a remote `$ref`: one that points outside the
54
+ * document (`other.yml#/components/schemas/A`, `./pet.yaml`, a bare id). Core
55
+ * does not fetch, so a remote `$ref` names nothing. The document is bundled
56
+ * into one before core reads it.
57
+ */
58
+ export declare const isRemoteRefPath: (refPath: string) => boolean;
59
+ /** The segments of a `refPath` in the document, each unescaped. `#` has none. */
60
+ export declare const toRefPathSegments: (refPath: string) => string[];
61
+ type IsDefaultRefPathArgs = {
62
+ refPath: string;
63
+ refType: RefType;
64
+ };
65
+ /**
66
+ * The `components` bucket a `refPath` is, such as `schemas` for
67
+ * `#/components/schemas`, or `undefined` for any other path. A ref whose path
68
+ * is a bucket names a component, of the bucket's kind whatever kind the ref
69
+ * is written for; any other ref points into a document's content, as one into
70
+ * an extension of `components` (`#/components/x-shared/Foo`) does. A bucket
71
+ * core does not read (`pathItems`) is still a bucket.
72
+ */
73
+ export declare const toRefPathBucket: (refPath: string) => string | undefined;
74
+ /** Whether `refPath` is where components of `refType` live, as `toRefParts` spells it. */
75
+ export declare const isDefaultRefPath: ({ refPath, refType }: IsDefaultRefPathArgs) => boolean;
76
+ /**
77
+ * The whole pointer of a ref, with no percent escapes. Two `$ref`s that point
78
+ * at the same place give the same pointer, so it keys a ref that does not
79
+ * point at a component. A remote `$ref` is given as written.
80
+ */
81
+ export declare const toRefPointer: ({ refName, refPath }: RefParts) => string;
82
+ /**
83
+ * The ref of the schema component named `refName`: `refPath`
84
+ * `#/components/schemas`. For code that holds a component's name but no
85
+ * `OasRef`, such as the engine's sweep over `components.schemas`.
86
+ */
87
+ export declare const toSchemaComponentRef: (refName: RefName) => RefParts;
88
+ /**
89
+ * The key a model is known by in the engine: its generator key, its
90
+ * enrichments (`[id][key][variant]`) and its manifest entry. A component
91
+ * (`refPath` `#/components/schemas`) is keyed by its `refName`, as it always
92
+ * was. Any other target is keyed by its whole pointer ({@link toRefPointer}),
93
+ * so two targets that share a `refName` stay apart.
94
+ */
95
+ export declare const toModelKey: ({ refName, refPath }: RefParts) => string;
96
+ /**
97
+ * A name for a model that differs between targets with one `refName`
98
+ * (`…/properties/disk` under two schemas). A component is named by its
99
+ * `refName`, through `toComponentName`. Any other target is named by its whole
100
+ * pointer, its segments joined by `_`: `Order_items`, `Pet_properties_tag`.
101
+ * A segment that is not alphanumeric gets a hash, so `@type` and `type` differ.
102
+ */
103
+ export declare const toModelName: ({ refName, refPath }: RefParts, toComponentName?: (refName: string) => string) => string;
104
+ /** Whether a model key ({@link toModelKey}) is a whole pointer, and not a component's `refName`. */
105
+ export declare const isPointerKey: (key: string) => boolean;
106
+ /**
107
+ * Reverses {@link toModelKey}, for a key read back out of a generator key.
108
+ * A pointer starts with `#/`; any other key is a component's `refName`. A key
109
+ * has no percent escapes, so a `%` in it is read as written.
110
+ */
111
+ export declare const fromModelKey: (key: string) => RefParts;
112
+ /**
113
+ * The value at a ref's pointer in a raw document, or `undefined` when the
114
+ * pointer leads nowhere, or out of the document. It walks objects by key and arrays by index.
50
115
  */
51
- export declare const toRefName: ($ref: string) => RefName;
116
+ export declare const toRawRefTarget: (document: unknown, { refName, refPath }: RefParts) => unknown;
52
117
  /**
53
118
  * Type representing an object with a $ref property.
54
119
  */
@@ -75,7 +140,7 @@ type Ref = {
75
140
  * if (isRef(schemaOrRef)) {
76
141
  * // TypeScript now knows schemaOrRef has a $ref property
77
142
  * console.log(schemaOrRef.$ref); // Safe to access
78
- * const refName = toRefName(schemaOrRef.$ref);
143
+ * const { refName, refPath } = toRefParts({ $ref: schemaOrRef.$ref });
79
144
  * } else {
80
145
  * // Handle as actual schema object
81
146
  * console.log('Direct schema object');
@@ -1,65 +1,173 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.toGetRef = exports.isRef = exports.toRefName = void 0;
3
+ exports.toGetRef = exports.isRef = exports.toRawRefTarget = exports.fromModelKey = exports.isPointerKey = exports.toModelName = exports.toModelKey = exports.toSchemaComponentRef = exports.toRefPointer = exports.isDefaultRefPath = exports.toRefPathBucket = exports.toRefPathSegments = exports.isRemoteRefPath = exports.toComponentsBucket = exports.toRefParts = void 0;
4
4
  require("../_dnt.polyfills.js");
5
5
  const DanglingRefError_js_1 = require("../oas/ref/DanglingRefError.js");
6
+ const JsonPointer_js_1 = require("../types/JsonPointer.js");
7
+ const Components_js_1 = require("../oas/components/Components.js");
8
+ const isPlainObject_js_1 = require("../parse/isPlainObject.js");
9
+ const strings_js_1 = require("./strings.js");
6
10
  /**
7
- * Extracts a reference name from an OpenAPI $ref string.
11
+ * Splits a `$ref` into {@link RefParts}.
8
12
  *
9
- * This function parses JSON Pointer references (like '#/components/schemas/User')
10
- * and extracts the final component as a branded RefName type. It's used throughout
11
- * the SKMTC system to convert string references into type-safe reference names.
13
+ * A `$ref` is a URI whose fragment holds a JSON pointer (RFC 6901), so the
14
+ * name is unescaped as one: `%20` is a space, and `~1` and `~0` are `/` and
15
+ * `~`. `#/components/schemas/Foo%20Bar` names the component `Foo Bar`.
12
16
  *
13
- * A `$ref` is a URI fragment that holds a JSON pointer (RFC 6901), so the name
14
- * is unescaped as one: `%20` is a space, and `~1` and `~0` are `/` and `~`.
15
- * `#/components/schemas/Foo%20Bar` names the component `Foo Bar`.
16
- *
17
- * @param $ref - The OpenAPI reference string (e.g., '#/components/schemas/User')
18
- * @returns The extracted reference name as a branded RefName type
19
- *
20
- * @throws {Error} When the reference string is invalid or empty
21
- *
22
- * @example Basic usage
23
- * ```typescript
24
- * import { toRefName } from '@skmtc/core/helpers';
25
- *
26
- * const refName = toRefName('#/components/schemas/User');
27
- * console.log(refName); // 'User' (typed as RefName)
28
- *
29
- * const responseRef = toRefName('#/components/responses/ErrorResponse');
30
- * console.log(responseRef); // 'ErrorResponse' (typed as RefName)
31
- * ```
32
- *
33
- * @example Error cases
34
- * ```typescript
35
- * // These will throw errors:
36
- * toRefName('invalid/ref/'); // Error: 'Invalid reference'
37
- * toRefName('#/components/schemas/'); // Error: 'Invalid reference'
38
- * ```
39
- *
40
- * @example Integration with OAS processing
41
- * ```typescript
42
- * class SchemaProcessor {
43
- * processReference(ref: string) {
44
- * const refName = toRefName(ref);
45
- * const schema = this.document.components.schemas[refName];
46
- * return this.processSchema(schema, refName);
47
- * }
48
- * }
49
- * ```
17
+ * A remote `$ref`, one that does not start with `#`, points outside the
18
+ * document, so its `refPath` does not start with `#` and it names nothing
19
+ * here: `other.yml#/components/schemas/A` is `refPath`
20
+ * `other.yml#/components/schemas` and `refName` `A`. This never throws: a
21
+ * `$ref` that names nothing is found out when it is resolved.
22
+ */
23
+ const toRefParts = ({ $ref }) => {
24
+ if (!$ref.startsWith('#')) {
25
+ const cut = $ref.lastIndexOf('/');
26
+ const refName = $ref.slice(cut + 1);
27
+ return { refName, refPath: cut === -1 ? '.' : $ref.slice(0, cut) };
28
+ }
29
+ const pointer = $ref.slice(1);
30
+ const segments = (pointer.startsWith('/') ? pointer.slice(1) : pointer)
31
+ .split('/')
32
+ .map(segment => (0, JsonPointer_js_1.unescapeSegment)(toPercentDecoded(segment)));
33
+ return toPartsOf(segments);
34
+ };
35
+ exports.toRefParts = toRefParts;
36
+ /** The parts of a pointer's segments, each unescaped. */
37
+ const toPartsOf = (segments) => ({
38
+ refName: (segments.at(-1) ?? ''),
39
+ refPath: segments.length > 1 ? (0, JsonPointer_js_1.toJsonPointer)(segments.slice(0, -1)) : '#'
40
+ });
41
+ /** The `components` bucket that holds components of each kind: `schemas`, `parameters`, and so on. */
42
+ const toComponentsBucket = (refType) => {
43
+ switch (refType) {
44
+ case 'schema':
45
+ return 'schemas';
46
+ case 'requestBody':
47
+ return 'requestBodies';
48
+ case 'parameter':
49
+ return 'parameters';
50
+ case 'response':
51
+ return 'responses';
52
+ case 'example':
53
+ return 'examples';
54
+ case 'header':
55
+ return 'headers';
56
+ case 'securityScheme':
57
+ return 'securitySchemes';
58
+ case 'link':
59
+ return 'links';
60
+ default: {
61
+ const _exhaustive = refType;
62
+ throw new Error(`Unhandled ref type: ${_exhaustive}`);
63
+ }
64
+ }
65
+ };
66
+ exports.toComponentsBucket = toComponentsBucket;
67
+ /**
68
+ * Whether a `refPath` is that of a remote `$ref`: one that points outside the
69
+ * document (`other.yml#/components/schemas/A`, `./pet.yaml`, a bare id). Core
70
+ * does not fetch, so a remote `$ref` names nothing. The document is bundled
71
+ * into one before core reads it.
72
+ */
73
+ const isRemoteRefPath = (refPath) => !refPath.startsWith('#');
74
+ exports.isRemoteRefPath = isRemoteRefPath;
75
+ /** The segments of a `refPath` in the document, each unescaped. `#` has none. */
76
+ const toRefPathSegments = (refPath) => {
77
+ const body = refPath.startsWith('#/') ? refPath.slice(2) : refPath.slice(1);
78
+ return body === '' ? [] : body.split('/').map(JsonPointer_js_1.unescapeSegment);
79
+ };
80
+ exports.toRefPathSegments = toRefPathSegments;
81
+ /**
82
+ * The `components` bucket a `refPath` is, such as `schemas` for
83
+ * `#/components/schemas`, or `undefined` for any other path. A ref whose path
84
+ * is a bucket names a component, of the bucket's kind whatever kind the ref
85
+ * is written for; any other ref points into a document's content, as one into
86
+ * an extension of `components` (`#/components/x-shared/Foo`) does. A bucket
87
+ * core does not read (`pathItems`) is still a bucket.
50
88
  */
51
- const toRefName = ($ref) => {
52
- const segment = $ref.split('/').slice(-1)[0];
53
- if (!segment) {
54
- throw new Error('Invalid reference');
89
+ const toRefPathBucket = (refPath) => {
90
+ if ((0, exports.isRemoteRefPath)(refPath)) {
91
+ return undefined;
55
92
  }
56
- return toUnescapedSegment(segment);
93
+ const [first, bucket, ...rest] = (0, exports.toRefPathSegments)(refPath);
94
+ return first === 'components' && rest.length === 0 && isBucket(bucket) ? bucket : undefined;
57
95
  };
58
- exports.toRefName = toRefName;
59
- /** A JSON pointer segment of a URI fragment, unescaped: percent escapes first, then `~1` and `~0`. */
60
- const toUnescapedSegment = (segment) => {
61
- return toPercentDecoded(segment).replaceAll('~1', '/').replaceAll('~0', '~');
96
+ exports.toRefPathBucket = toRefPathBucket;
97
+ /** The `components` buckets OpenAPI defines that core does not read. */
98
+ const unreadBuckets = ['callbacks', 'pathItems', 'mediaTypes'];
99
+ const isBucket = (key) => Components_js_1.componentsKeys.includes(key) || unreadBuckets.includes(key);
100
+ /** Whether `refPath` is where components of `refType` live, as `toRefParts` spells it. */
101
+ const isDefaultRefPath = ({ refPath, refType }) => (0, exports.toRefPathBucket)(refPath) === (0, exports.toComponentsBucket)(refType);
102
+ exports.isDefaultRefPath = isDefaultRefPath;
103
+ /**
104
+ * The whole pointer of a ref, with no percent escapes. Two `$ref`s that point
105
+ * at the same place give the same pointer, so it keys a ref that does not
106
+ * point at a component. A remote `$ref` is given as written.
107
+ */
108
+ const toRefPointer = ({ refName, refPath }) => (0, exports.isRemoteRefPath)(refPath) ? `${refPath}/${refName}` : (0, JsonPointer_js_1.toJsonPointer)([...(0, exports.toRefPathSegments)(refPath), refName]);
109
+ exports.toRefPointer = toRefPointer;
110
+ /**
111
+ * The ref of the schema component named `refName`: `refPath`
112
+ * `#/components/schemas`. For code that holds a component's name but no
113
+ * `OasRef`, such as the engine's sweep over `components.schemas`.
114
+ */
115
+ const toSchemaComponentRef = (refName) => ({
116
+ refName,
117
+ refPath: `#/components/${(0, exports.toComponentsBucket)('schema')}`
118
+ });
119
+ exports.toSchemaComponentRef = toSchemaComponentRef;
120
+ /**
121
+ * The key a model is known by in the engine: its generator key, its
122
+ * enrichments (`[id][key][variant]`) and its manifest entry. A component
123
+ * (`refPath` `#/components/schemas`) is keyed by its `refName`, as it always
124
+ * was. Any other target is keyed by its whole pointer ({@link toRefPointer}),
125
+ * so two targets that share a `refName` stay apart.
126
+ */
127
+ const toModelKey = ({ refName, refPath }) => (0, exports.isDefaultRefPath)({ refPath, refType: 'schema' }) ? refName : (0, exports.toRefPointer)({ refName, refPath });
128
+ exports.toModelKey = toModelKey;
129
+ /**
130
+ * A name for a model that differs between targets with one `refName`
131
+ * (`…/properties/disk` under two schemas). A component is named by its
132
+ * `refName`, through `toComponentName`. Any other target is named by its whole
133
+ * pointer, its segments joined by `_`: `Order_items`, `Pet_properties_tag`.
134
+ * A segment that is not alphanumeric gets a hash, so `@type` and `type` differ.
135
+ */
136
+ const toModelName = ({ refName, refPath }, toComponentName = name => name) => {
137
+ if ((0, exports.isDefaultRefPath)({ refPath, refType: 'schema' })) {
138
+ return toComponentName(refName);
139
+ }
140
+ const segments = [...((0, exports.isRemoteRefPath)(refPath) ? [refPath] : (0, exports.toRefPathSegments)(refPath)), refName];
141
+ const [first, second, ...rest] = segments;
142
+ const named = first === 'components' && second === 'schemas' ? rest : segments;
143
+ return (0, strings_js_1.capitalize)(named.map(segment => (/^[a-zA-Z0-9]+$/.test(segment) ? segment : `${(0, strings_js_1.camelCase)(segment)}${toShortHash(segment)}`)).join('_'));
62
144
  };
145
+ exports.toModelName = toModelName;
146
+ /** A 32-bit FNV-1a hash, in base 36. */
147
+ const toShortHash = (value) => [...value]
148
+ .reduce((hash, char) => Math.imul(hash ^ (char.codePointAt(0) ?? 0), 0x01000193) >>> 0, 0x811c9dc5)
149
+ .toString(36);
150
+ /** Whether a model key ({@link toModelKey}) is a whole pointer, and not a component's `refName`. */
151
+ const isPointerKey = (key) => key.startsWith('#/');
152
+ exports.isPointerKey = isPointerKey;
153
+ /**
154
+ * Reverses {@link toModelKey}, for a key read back out of a generator key.
155
+ * A pointer starts with `#/`; any other key is a component's `refName`. A key
156
+ * has no percent escapes, so a `%` in it is read as written.
157
+ */
158
+ const fromModelKey = (key) => (0, exports.isPointerKey)(key) ? toPartsOf(key.slice(2).split('/').map(JsonPointer_js_1.unescapeSegment)) : (0, exports.toSchemaComponentRef)(key);
159
+ exports.fromModelKey = fromModelKey;
160
+ /**
161
+ * The value at a ref's pointer in a raw document, or `undefined` when the
162
+ * pointer leads nowhere, or out of the document. It walks objects by key and arrays by index.
163
+ */
164
+ const toRawRefTarget = (document, { refName, refPath }) => (0, exports.isRemoteRefPath)(refPath) ? undefined : [...(0, exports.toRefPathSegments)(refPath), refName].reduce((value, segment) => {
165
+ if (Array.isArray(value)) {
166
+ return /^\d+$/.test(segment) ? value[Number(segment)] : undefined;
167
+ }
168
+ return (0, isPlainObject_js_1.isPlainObject)(value) && Object.hasOwn(value, segment) ? value[segment] : undefined;
169
+ }, document);
170
+ exports.toRawRefTarget = toRawRefTarget;
63
171
  const toPercentDecoded = (segment) => {
64
172
  try {
65
173
  return decodeURIComponent(segment);
@@ -88,7 +196,7 @@ const toPercentDecoded = (segment) => {
88
196
  * if (isRef(schemaOrRef)) {
89
197
  * // TypeScript now knows schemaOrRef has a $ref property
90
198
  * console.log(schemaOrRef.$ref); // Safe to access
91
- * const refName = toRefName(schemaOrRef.$ref);
199
+ * const { refName, refPath } = toRefParts({ $ref: schemaOrRef.$ref });
92
200
  * } else {
93
201
  * // Handle as actual schema object
94
202
  * console.log('Direct schema object');
@@ -197,20 +305,27 @@ exports.isRef = isRef;
197
305
  const toGetRef = (oasDocument, onDangling) => ({ $ref }) => toTargetSchema({ oasDocument, onDangling, $ref, followed: [] });
198
306
  exports.toGetRef = toGetRef;
199
307
  /**
200
- * The schema at the end of the chain of `$ref`s. A `$ref` that names nothing,
201
- * or a chain that comes back to a component it has passed (`A` is a `$ref`
202
- * to `B`, and `B` to `A`), gives `onDangling` a `DanglingRefError`, or throws it.
308
+ * The schema at the end of the chain of `$ref`s, each followed by its whole
309
+ * pointer: a component (`#/components/schemas/Pet`) or any other place in
310
+ * the document (`#/components/schemas/Pet/properties/tag`). A `$ref` that
311
+ * names nothing, one to a component that is not a schema, or a chain that
312
+ * comes back to a place it has passed (`A` is a `$ref` to `B`, and `B` to
313
+ * `A`), gives `onDangling` a `DanglingRefError`, or throws it.
203
314
  */
204
315
  const toTargetSchema = ({ oasDocument, onDangling, $ref, followed }) => {
205
- const item = oasDocument.components?.schemas?.[(0, exports.toRefName)($ref)];
206
- if (!item) {
207
- return toDangling(onDangling, new DanglingRefError_js_1.DanglingRefError($ref));
316
+ const parts = (0, exports.toRefParts)({ $ref });
317
+ const bucket = (0, exports.toRefPathBucket)(parts.refPath);
318
+ const namesSchema = parts.refName !== '' && (bucket === undefined || bucket === (0, exports.toComponentsBucket)('schema'));
319
+ const item = namesSchema ? (0, exports.toRawRefTarget)(oasDocument, parts) : undefined;
320
+ if (!isRawSchema(item)) {
321
+ return toDangling(onDangling, new DanglingRefError_js_1.DanglingRefError($ref, { remote: (0, exports.isRemoteRefPath)(parts.refPath) }));
208
322
  }
209
323
  if (!(0, exports.isRef)(item)) {
210
324
  return item;
211
325
  }
212
326
  const passed = [...followed, $ref];
213
- const loopStart = passed.findIndex(each => (0, exports.toRefName)(each) === (0, exports.toRefName)(item.$ref));
327
+ const toPointer = (each) => (0, exports.toRefPointer)((0, exports.toRefParts)({ $ref: each }));
328
+ const loopStart = passed.findIndex(each => toPointer(each) === toPointer(item.$ref));
214
329
  if (loopStart === -1) {
215
330
  return toTargetSchema({ oasDocument, onDangling, $ref: item.$ref, followed: passed });
216
331
  }
@@ -219,6 +334,12 @@ const toTargetSchema = ({ oasDocument, onDangling, $ref, followed }) => {
219
334
  const loop = [...passed.slice(loopStart + 1), item.$ref];
220
335
  return toDangling(onDangling, new DanglingRefError_js_1.DanglingRefError(passed[0] ?? $ref, { loop }));
221
336
  };
337
+ /**
338
+ * Whether a value found at a pointer can be read as a schema: an object. Its
339
+ * keywords are read as the merge reads any member; nothing more is checked
340
+ * here, as for a component.
341
+ */
342
+ const isRawSchema = (value) => (0, isPlainObject_js_1.isPlainObject)(value);
222
343
  const toDangling = (onDangling, error) => {
223
344
  if (onDangling) {
224
345
  return onDangling(error);
@@ -173,6 +173,12 @@ export declare class OasDocument {
173
173
  * ```
174
174
  */
175
175
  constructor(fields?: DocumentFields);
176
+ /** The parsed target of a ref that does not point at a component, by its whole pointer. */
177
+ toRefTarget(pointer: string): ComponentsEntry | undefined;
178
+ /** Keeps the parsed target of a ref that does not point at a component, under its whole pointer. */
179
+ setRefTarget(pointer: string, target: ComponentsEntry): void;
180
+ /** Removes a ref target, as {@link removeItem} removes a component, and returns it. */
181
+ removeRefTarget(pointer: string): ComponentsEntry | undefined;
176
182
  /**
177
183
  * Removes an item from the document based on a stack trail path.
178
184
  *
@@ -10,7 +10,7 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
10
10
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
11
11
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
12
12
  };
13
- var _OasDocument_fields;
13
+ var _OasDocument_fields, _OasDocument_refTargets;
14
14
  Object.defineProperty(exports, "__esModule", { value: true });
15
15
  exports.OasDocument = void 0;
16
16
  require("../../_dnt.polyfills.js");
@@ -142,8 +142,50 @@ class OasDocument {
142
142
  });
143
143
  /** @internal Private fields storage */
144
144
  _OasDocument_fields.set(this, void 0);
145
+ /**
146
+ * The targets of refs that do not point at a component, such as
147
+ * `#/components/schemas/Pet/properties/tag` or
148
+ * `#/paths/~1pets/get/responses/200/content/application~1json/schema`.
149
+ * Each is parsed once, at its own position, and kept under its whole
150
+ * pointer (`toRefPointer`). The model sweep does not visit them: a
151
+ * generator reaches one through a ref.
152
+ */
153
+ _OasDocument_refTargets.set(this, new Map()
154
+ /**
155
+ * Creates a new OasDocument instance.
156
+ *
157
+ * The document is typically created with undefined fields and populated
158
+ * later during the parsing process. This allows for lazy initialization
159
+ * and proper error handling during document processing.
160
+ *
161
+ * @param fields - Optional document fields (usually set later during parsing)
162
+ *
163
+ * @example
164
+ * ```typescript
165
+ * // Usually created without fields during parsing
166
+ * const document = new OasDocument();
167
+ *
168
+ * // Fields are set later by the parser
169
+ * document.fields = parsedDocumentFields;
170
+ * ```
171
+ */
172
+ );
145
173
  __classPrivateFieldSet(this, _OasDocument_fields, fields, "f");
146
174
  }
175
+ /** The parsed target of a ref that does not point at a component, by its whole pointer. */
176
+ toRefTarget(pointer) {
177
+ return __classPrivateFieldGet(this, _OasDocument_refTargets, "f").get(pointer);
178
+ }
179
+ /** Keeps the parsed target of a ref that does not point at a component, under its whole pointer. */
180
+ setRefTarget(pointer, target) {
181
+ __classPrivateFieldGet(this, _OasDocument_refTargets, "f").set(pointer, target);
182
+ }
183
+ /** Removes a ref target, as {@link removeItem} removes a component, and returns it. */
184
+ removeRefTarget(pointer) {
185
+ const target = __classPrivateFieldGet(this, _OasDocument_refTargets, "f").get(pointer);
186
+ __classPrivateFieldGet(this, _OasDocument_refTargets, "f").delete(pointer);
187
+ return target;
188
+ }
147
189
  /**
148
190
  * Removes an item from the document based on a stack trail path.
149
191
  *
@@ -336,4 +378,4 @@ class OasDocument {
336
378
  }
337
379
  }
338
380
  exports.OasDocument = OasDocument;
339
- _OasDocument_fields = new WeakMap();
381
+ _OasDocument_fields = new WeakMap(), _OasDocument_refTargets = new WeakMap();
@@ -128,7 +128,10 @@ class OasHeader {
128
128
  if (this.schema) {
129
129
  return this.schema;
130
130
  }
131
- const contentEntries = Object.values(this.content ?? {});
131
+ if (this.content === undefined) {
132
+ throw new Error('Header has neither schema nor content');
133
+ }
134
+ const contentEntries = Object.values(this.content);
132
135
  const onlyEntry = contentEntries.length === 1 ? contentEntries[0] : undefined;
133
136
  const schema = (0, toContentSchema_js_1.toContentSchema)(this.content, mediaType) ?? onlyEntry?.schema;
134
137
  if (!schema) {
@@ -249,7 +249,7 @@ export declare class OasParameter extends OasBase {
249
249
  *
250
250
  * @param mediaType - Media type to extract schema from when using content definitions, an exact lookup. Omitted: the JSON media type (`application/json`, else the first JSON-like type, else `*\/*`).
251
251
  * @returns The parameter's schema object
252
- * @throws Error if no schema is found for the specified media type
252
+ * @throws Error if the parameter has neither schema nor content, or no schema is found for the specified media type
253
253
  */
254
254
  toSchema(mediaType?: string): OasSchema | OasRef<'schema'>;
255
255
  /**
@@ -309,13 +309,16 @@ class OasParameter extends OasBase_js_1.OasBase {
309
309
  *
310
310
  * @param mediaType - Media type to extract schema from when using content definitions, an exact lookup. Omitted: the JSON media type (`application/json`, else the first JSON-like type, else `*\/*`).
311
311
  * @returns The parameter's schema object
312
- * @throws Error if no schema is found for the specified media type
312
+ * @throws Error if the parameter has neither schema nor content, or no schema is found for the specified media type
313
313
  */
314
314
  toSchema(mediaType) {
315
315
  if (this.schema) {
316
316
  return this.schema;
317
317
  }
318
- const contentEntries = Object.values(this.content ?? {});
318
+ if (this.content === undefined) {
319
+ throw new Error(`Parameter '${this.name}' in ${this.location} has neither schema nor content`);
320
+ }
321
+ const contentEntries = Object.values(this.content);
319
322
  const onlyEntry = contentEntries.length === 1 ? contentEntries[0] : undefined;
320
323
  const schema = (0, toContentSchema_js_1.toContentSchema)(this.content, mediaType) ?? onlyEntry?.schema;
321
324
  if (!schema) {
@@ -7,10 +7,13 @@ type DanglingRefErrorOptions = {
7
7
  * `['#/components/schemas/B', '#/components/schemas/A']`.
8
8
  */
9
9
  loop?: string[];
10
+ /** The `$ref` points outside the document, which core does not fetch. */
11
+ remote?: boolean;
10
12
  };
11
13
  /**
12
14
  * Thrown when a reference that names nothing in the document is resolved:
13
- * no component has its name, or its chain of `$ref`s comes back to one it
15
+ * no component has its name, it points outside the document (core does not
16
+ * fetch), or its chain of `$ref`s comes back to one it
14
17
  * has passed (`A` is a `$ref` to `B`, and `B` to `A`), so it never reaches a
15
18
  * component.
16
19
  *
@@ -25,7 +28,7 @@ export declare class DanglingRefError extends Error {
25
28
  ref: string;
26
29
  /** When the chain of `$ref`s loops: see {@link DanglingRefErrorOptions.loop}. */
27
30
  loop: string[] | undefined;
28
- constructor(ref: string, { loop }?: DanglingRefErrorOptions);
31
+ constructor(ref: string, { loop, remote }?: DanglingRefErrorOptions);
29
32
  /**
30
33
  * True when `error` is a `DanglingRefError`. It reads the error's name,
31
34
  * not its class, so it is also true for one thrown by another copy of