@skmtc/core 0.40.0 → 0.42.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 (79) hide show
  1. package/esm/context/GenerateContext.d.ts +1 -1
  2. package/esm/context/GenerateContext.js +4 -3
  3. package/esm/context/ParseContext.d.ts +26 -0
  4. package/esm/context/ParseContext.js +112 -2
  5. package/esm/context/generateTypes.d.ts +16 -2
  6. package/esm/context/generateTypes.js +2 -0
  7. package/esm/context/tryParseAt.d.ts +4 -1
  8. package/esm/context/tryParseAt.js +10 -3
  9. package/esm/helpers/collateExamples.js +15 -5
  10. package/esm/helpers/refFns.d.ts +9 -3
  11. package/esm/helpers/refFns.js +29 -9
  12. package/esm/mod.d.ts +1 -0
  13. package/esm/mod.js +1 -0
  14. package/esm/oas/ref/DanglingRefError.d.ts +22 -0
  15. package/esm/oas/ref/DanglingRefError.js +33 -0
  16. package/esm/oas/ref/Ref.d.ts +5 -0
  17. package/esm/oas/ref/Ref.js +28 -2
  18. package/esm/oas/schema/siblings.js +12 -2
  19. package/esm/oas/union/Union.d.ts +2 -1
  20. package/esm/oas/union/Union.js +23 -12
  21. package/esm/parse/securityRequirements.d.ts +6 -0
  22. package/esm/parse/securityRequirements.js +8 -0
  23. package/esm/parse/v3-0/_merge-all-of/merge-union.js +9 -1
  24. package/esm/parse/v3-0/mediaType/toMediaTypeItemV3.js +4 -3
  25. package/esm/parse/v3-0/parameter/toParameterV3.js +4 -3
  26. package/esm/parse/v3-0/ref/toRefV31.js +5 -2
  27. package/esm/parse/v3-0/schema/toSchemasV3.js +6 -3
  28. package/esm/parse/v3-1/_merge-all-of/merge-union.js +16 -4
  29. package/esm/parse/v3-1/mediaType/toMediaTypeItemV3.js +4 -3
  30. package/esm/parse/v3-1/parameter/toParameterV3.js +4 -3
  31. package/esm/parse/v3-1/ref/toRefV31.js +5 -2
  32. package/esm/parse/v3-1/schema/toSchemasV3.js +6 -3
  33. package/esm/parse/v3-2/_merge-all-of/merge-union.js +16 -4
  34. package/esm/parse/v3-2/mediaType/toMediaTypeItemV3.js +4 -3
  35. package/esm/parse/v3-2/parameter/toParameterV3.js +4 -3
  36. package/esm/parse/v3-2/ref/toRefV31.js +5 -2
  37. package/esm/parse/v3-2/schema/toSchemasV3.js +6 -3
  38. package/esm/types/Settings.d.ts +21 -0
  39. package/esm/types/Settings.js +19 -1
  40. package/package.json +5 -1
  41. package/script/context/GenerateContext.d.ts +1 -1
  42. package/script/context/GenerateContext.js +4 -3
  43. package/script/context/ParseContext.d.ts +26 -0
  44. package/script/context/ParseContext.js +112 -2
  45. package/script/context/generateTypes.d.ts +16 -2
  46. package/script/context/generateTypes.js +2 -0
  47. package/script/context/tryParseAt.d.ts +4 -1
  48. package/script/context/tryParseAt.js +10 -3
  49. package/script/helpers/collateExamples.js +15 -5
  50. package/script/helpers/refFns.d.ts +9 -3
  51. package/script/helpers/refFns.js +29 -9
  52. package/script/mod.d.ts +1 -0
  53. package/script/mod.js +1 -0
  54. package/script/oas/ref/DanglingRefError.d.ts +22 -0
  55. package/script/oas/ref/DanglingRefError.js +37 -0
  56. package/script/oas/ref/Ref.d.ts +5 -0
  57. package/script/oas/ref/Ref.js +28 -2
  58. package/script/oas/schema/siblings.js +12 -2
  59. package/script/oas/union/Union.d.ts +2 -1
  60. package/script/oas/union/Union.js +23 -12
  61. package/script/parse/securityRequirements.d.ts +6 -0
  62. package/script/parse/securityRequirements.js +8 -0
  63. package/script/parse/v3-0/_merge-all-of/merge-union.js +9 -1
  64. package/script/parse/v3-0/mediaType/toMediaTypeItemV3.js +4 -3
  65. package/script/parse/v3-0/parameter/toParameterV3.js +4 -3
  66. package/script/parse/v3-0/ref/toRefV31.js +5 -2
  67. package/script/parse/v3-0/schema/toSchemasV3.js +6 -3
  68. package/script/parse/v3-1/_merge-all-of/merge-union.js +16 -4
  69. package/script/parse/v3-1/mediaType/toMediaTypeItemV3.js +4 -3
  70. package/script/parse/v3-1/parameter/toParameterV3.js +4 -3
  71. package/script/parse/v3-1/ref/toRefV31.js +5 -2
  72. package/script/parse/v3-1/schema/toSchemasV3.js +6 -3
  73. package/script/parse/v3-2/_merge-all-of/merge-union.js +16 -4
  74. package/script/parse/v3-2/mediaType/toMediaTypeItemV3.js +4 -3
  75. package/script/parse/v3-2/parameter/toParameterV3.js +4 -3
  76. package/script/parse/v3-2/ref/toRefV31.js +5 -2
  77. package/script/parse/v3-2/schema/toSchemasV3.js +6 -3
  78. package/script/types/Settings.d.ts +21 -0
  79. package/script/types/Settings.js +20 -2
@@ -169,12 +169,30 @@ export const anchorsSettings = v.object({
169
169
  enabled: v.boolean(),
170
170
  out: v.optional(v.string())
171
171
  });
172
+ /**
173
+ * What `client.json#settings.system.danglingRefs` can list: each kind of
174
+ * `$ref`, and `allOfMember`, a `$ref` that core merges at parse: a member of
175
+ * an `allOf`, also one inside a `oneOf` or `anyOf` member, or a `oneOf` or
176
+ * `anyOf` member merged with the keywords beside the union.
177
+ */
178
+ export const danglingRefKinds = [
179
+ 'schema',
180
+ 'parameter',
181
+ 'requestBody',
182
+ 'response',
183
+ 'header',
184
+ 'securityScheme',
185
+ 'example',
186
+ 'link',
187
+ 'allOfMember'
188
+ ];
172
189
  /** Valibot schema for {@link SystemSettings}: `client.json#settings.system`. */
173
190
  export const systemSettings = v.object({
174
191
  allOf: v.optional(v.picklist(['strict', 'latestWins'])),
175
192
  responseContradictions: v.optional(v.picklist(['strict', 'unknown'])),
176
193
  not: v.optional(v.picklist(['strict', 'unknown'])),
177
- anyOf: v.optional(v.picklist(['union', 'unknown']))
194
+ anyOf: v.optional(v.picklist(['union', 'unknown'])),
195
+ danglingRefs: v.optional(v.array(v.picklist(danglingRefKinds)))
178
196
  });
179
197
  export const clientSettings = v.object({
180
198
  basePath: v.optional(v.pipe(v.string(), v.check(basePath => !isAbsolutePath(basePath), 'basePath must be relative to the SKMTC root (the directory containing .skmtc/); ' +
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@skmtc/core",
3
- "version": "0.40.0",
3
+ "version": "0.42.0",
4
4
  "description": "Skmtc is a declarative code generation framework",
5
5
  "keywords": [
6
6
  "openapi",
@@ -35,6 +35,10 @@
35
35
  "import": "./esm/dsl/CustomValue.js",
36
36
  "require": "./script/dsl/CustomValue.js"
37
37
  },
38
+ "./DanglingRefError": {
39
+ "import": "./esm/oas/ref/DanglingRefError.js",
40
+ "require": "./script/oas/ref/DanglingRefError.js"
41
+ },
38
42
  "./DenoJson": {
39
43
  "import": "./esm/types/DenoJson.js",
40
44
  "require": "./script/types/DenoJson.js"
@@ -328,7 +328,7 @@ export declare class GenerateContext implements GenerateContextType {
328
328
  * Perform one lookup of schema by `refName`.
329
329
  * @param refName
330
330
  * @returns Matching schema or ref
331
- * @throws if schema is not found
331
+ * @throws {DanglingRefError} when no schema has that name
332
332
  */
333
333
  resolveSchemaRefOnce(refName: RefName): OasSchema | OasRef<'schema'>;
334
334
  /**
@@ -18,6 +18,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
18
18
  exports.toModelSource = exports.toGqlOperationSource = exports.toWebhookSource = exports.toOasOperationSource = exports.GenerateContext = void 0;
19
19
  const normalizeWorkspacePath_js_1 = require("../helpers/normalizeWorkspacePath.js");
20
20
  const applyGeneratedSuffix_js_1 = require("../helpers/applyGeneratedSuffix.js");
21
+ const DanglingRefError_js_1 = require("../oas/ref/DanglingRefError.js");
21
22
  const Method_js_1 = require("../types/Method.js");
22
23
  const OasOperationDriver_js_1 = require("../dsl/operation/oas/OasOperationDriver.js");
23
24
  const WebhookDriver_js_1 = require("../dsl/webhook/WebhookDriver.js");
@@ -836,14 +837,14 @@ class GenerateContext {
836
837
  * Perform one lookup of schema by `refName`.
837
838
  * @param refName
838
839
  * @returns Matching schema or ref
839
- * @throws if schema is not found
840
+ * @throws {DanglingRefError} when no schema has that name
840
841
  */
841
842
  resolveSchemaRefOnce(refName) {
842
843
  switch (this.document.type) {
843
844
  case 'oas': {
844
845
  const component = this.document.value.components?.schemas?.[refName];
845
846
  if (!component) {
846
- throw new Error(`Schema not found: ${refName}`);
847
+ throw new DanglingRefError_js_1.DanglingRefError(refName);
847
848
  }
848
849
  const target = component.resolveOnce();
849
850
  // One step, with what the component adds next to its reference
@@ -856,7 +857,7 @@ class GenerateContext {
856
857
  case 'gql': {
857
858
  const schema = this.document.value.registry.schemas[refName];
858
859
  if (!schema) {
859
- throw new Error(`Schema not found: ${refName}`);
860
+ throw new DanglingRefError_js_1.DanglingRefError(refName);
860
861
  }
861
862
  // GqlRegistry stores OasSchema | OasRef entries: one step, as for OAS.
862
863
  return schema.resolveOnce();
@@ -28,6 +28,8 @@ import { StackTrail } from './StackTrail.js';
28
28
  import type { SkmtcDocumentInput, SkmtcParsedDocument } from '../types/SkmtcDocument.js';
29
29
  import type { GqlParseOptions, LogAtArgs, LogIssueArgs, LogIssueAtArgs, LogIssueNoKeyArgs, LogSkippedValuesArgs } from './parseTypes.js';
30
30
  import type { ParseIssue } from './ParseIssue.js';
31
+ import type { OasRef } from '../oas/ref/Ref.js';
32
+ import type { OasRefData } from '../oas/ref/ref-types.js';
31
33
  export type { ParseIssue, GqlIssueType } from './ParseIssue.js';
32
34
  export type { GqlParseOptions, LogAtArgs, LogIssueArgs, LogIssueAtArgs, LogIssueNoKeyArgs, LogSkippedValuesArgs, ParseContextType, ParseErrorInput, ParseIssueInput, ParseWarningInput } from './parseTypes.js';
33
35
  type OasProtocolState = {
@@ -50,6 +52,11 @@ type GqlProtocolState = {
50
52
  options: GqlParseOptions;
51
53
  };
52
54
  type ProtocolState = OasProtocolState | GqlProtocolState;
55
+ type ToDanglingAllOfMemberArgs = {
56
+ $ref: string;
57
+ /** The schema that holds the `allOf`. */
58
+ stackTrail: StackTrail;
59
+ };
53
60
  type ConstructorArgs = {
54
61
  input: SkmtcDocumentInput;
55
62
  logger: Logger;
@@ -157,6 +164,25 @@ export declare class ParseContext {
157
164
  * would use type names or qualified field paths.
158
165
  */
159
166
  registerRef(consumer: StackTrail, refKey: string): void;
167
+ /**
168
+ * Register an OAS `$ref` at its consumer site, as {@link registerRef}
169
+ * does, under the key {@link toRefKey} gives its `$ref`, and keep the ref
170
+ * with that site, so that once the document is parsed `#checkRefs` can
171
+ * resolve it there.
172
+ */
173
+ registerOasRef<T extends OasRefData['refType']>(consumer: StackTrail, ref: OasRef<T>): void;
174
+ /**
175
+ * What a merge reads in place of a `$ref` that names nothing: an `allOf`
176
+ * member, or in a `oneOf` or `anyOf`, a member's own `allOf` member or a
177
+ * member merged with the keywords beside the union. When
178
+ * `system.danglingRefs` lists `allOfMember`, it is `{}`, which
179
+ * adds nothing to the merge (`A & unknown` is `A`), and a `DANGLING_REF`
180
+ * warning at `stackTrail`: the model has no properties from that member.
181
+ * Otherwise it throws `DanglingRefError`, and what holds the `allOf` is
182
+ * removed. It is separate from `schema`: here core decides, at parse, and
183
+ * the generator never sees the member.
184
+ */
185
+ toDanglingAllOfMember({ $ref, stackTrail }: ToDanglingAllOfMemberArgs): OpenAPIV3.SchemaObject;
160
186
  /**
161
187
  * Register an error against a ref key — typically called when the
162
188
  * target of a `$ref` (or type reference) fails to parse. `undefined`
@@ -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 _ParseContext_instances, _ParseContext_refConsumers, _ParseContext_refErrors, _ParseContext_rootFrames, _ParseContext_removeComponent, _ParseContext_removeConsumer, _ParseContext_removePathParameterConsumer, _ParseContext_toRawComponentParameter, _ParseContext_logDependencyIssue, _ParseContext_toDocumentTrail;
13
+ var _ParseContext_instances, _ParseContext_refConsumers, _ParseContext_refErrors, _ParseContext_oasRefs, _ParseContext_rootFrames, _ParseContext_removeComponent, _ParseContext_removeConsumer, _ParseContext_removePathParameterConsumer, _ParseContext_toRawComponentParameter, _ParseContext_logDependencyIssue, _ParseContext_toDocumentTrail, _ParseContext_checkRefs, _ParseContext_removeHolder;
14
14
  Object.defineProperty(exports, "__esModule", { value: true });
15
15
  exports.ParseContext = void 0;
16
16
  /**
@@ -44,6 +44,20 @@ const StackTrail_js_1 = require("./StackTrail.js");
44
44
  const isPlainObject_js_1 = require("../parse/isPlainObject.js");
45
45
  const pathParameters_js_1 = require("../parse/pathParameters.js");
46
46
  const SerializedError_js_1 = require("../types/SerializedError.js");
47
+ const DanglingRefError_js_1 = require("../oas/ref/DanglingRefError.js");
48
+ const refFns_js_1 = require("../helpers/refFns.js");
49
+ /**
50
+ * The key a `$ref`'s consumers and errors are kept under. A
51
+ * `#/components/<bucket>/…` ref is keyed by the name it resolves (`toRefName`
52
+ * unescapes it), which is the key `StackTrail.toStackRef()` gives that
53
+ * component's own errors: `#/components/schemas/Foo%20Bar` is kept under
54
+ * `#/components/schemas/Foo Bar`. Any other `$ref` is its own key.
55
+ */
56
+ const toRefKey = ($ref) => {
57
+ // The last segment is not empty, so `toRefName` does not throw.
58
+ const bucket = /^#\/components\/([^/]+)\/.*[^/]$/.exec($ref)?.[1];
59
+ return bucket === undefined ? $ref : `#/components/${bucket}/${(0, refFns_js_1.toRefName)($ref)}`;
60
+ };
47
61
  /** The stored form of an issue: an error's `cause` as a `SerializedError`. */
48
62
  const toParseIssue = (issue) => {
49
63
  if (issue.level !== 'error') {
@@ -116,6 +130,10 @@ class ParseContext {
116
130
  // use type names. The maps don't care about the encoding.
117
131
  _ParseContext_refConsumers.set(this, new Map());
118
132
  _ParseContext_refErrors.set(this, new Map()
133
+ /** Each OAS ref and the place it is written, which `#checkRefs` resolves once the document is parsed. */
134
+ );
135
+ /** Each OAS ref and the place it is written, which `#checkRefs` resolves once the document is parsed. */
136
+ _ParseContext_oasRefs.set(this, []
119
137
  /**
120
138
  * Frames of the trail `parse()` was called with (`[traceId, spanId,
121
139
  * 'parse']` through `toArtifacts`). Every trail built during the walk
@@ -265,6 +283,7 @@ class ParseContext {
265
283
  throw new Error(`Unhandled OAS dialect: ${JSON.stringify(_exhaustive)}`);
266
284
  }
267
285
  }
286
+ __classPrivateFieldGet(this, _ParseContext_instances, "m", _ParseContext_checkRefs).call(this);
268
287
  this.removeErroredItems();
269
288
  return { type: 'oas', value: oasState.oasDocument };
270
289
  }
@@ -364,6 +383,41 @@ class ParseContext {
364
383
  __classPrivateFieldGet(this, _ParseContext_refConsumers, "f").set(refKey, [consumer]);
365
384
  }
366
385
  }
386
+ /**
387
+ * Register an OAS `$ref` at its consumer site, as {@link registerRef}
388
+ * does, under the key {@link toRefKey} gives its `$ref`, and keep the ref
389
+ * with that site, so that once the document is parsed `#checkRefs` can
390
+ * resolve it there.
391
+ */
392
+ registerOasRef(consumer, ref) {
393
+ this.registerRef(consumer, toRefKey(ref.$ref));
394
+ __classPrivateFieldGet(this, _ParseContext_oasRefs, "f").push({ consumer, ref });
395
+ }
396
+ /**
397
+ * What a merge reads in place of a `$ref` that names nothing: an `allOf`
398
+ * member, or in a `oneOf` or `anyOf`, a member's own `allOf` member or a
399
+ * member merged with the keywords beside the union. When
400
+ * `system.danglingRefs` lists `allOfMember`, it is `{}`, which
401
+ * adds nothing to the merge (`A & unknown` is `A`), and a `DANGLING_REF`
402
+ * warning at `stackTrail`: the model has no properties from that member.
403
+ * Otherwise it throws `DanglingRefError`, and what holds the `allOf` is
404
+ * removed. It is separate from `schema`: here core decides, at parse, and
405
+ * the generator never sees the member.
406
+ */
407
+ toDanglingAllOfMember({ $ref, stackTrail }) {
408
+ const error = new DanglingRefError_js_1.DanglingRefError($ref);
409
+ if (!this.system.danglingRefs?.includes('allOfMember')) {
410
+ throw error;
411
+ }
412
+ this.logIssueNoKey({
413
+ level: 'warning',
414
+ message: `${error.message}. It is left out of the allOf merge (system.danglingRefs lists 'allOfMember').`,
415
+ parent: { $ref },
416
+ stackTrail,
417
+ type: 'DANGLING_REF'
418
+ });
419
+ return {};
420
+ }
367
421
  /**
368
422
  * Register an error against a ref key — typically called when the
369
423
  * target of a `$ref` (or type reference) fails to parse. `undefined`
@@ -516,7 +570,7 @@ class ParseContext {
516
570
  }
517
571
  }
518
572
  exports.ParseContext = ParseContext;
519
- _ParseContext_refConsumers = new WeakMap(), _ParseContext_refErrors = new WeakMap(), _ParseContext_rootFrames = new WeakMap(), _ParseContext_instances = new WeakSet(), _ParseContext_removeComponent = function _ParseContext_removeComponent(refKey) {
573
+ _ParseContext_refConsumers = new WeakMap(), _ParseContext_refErrors = new WeakMap(), _ParseContext_oasRefs = new WeakMap(), _ParseContext_rootFrames = new WeakMap(), _ParseContext_instances = new WeakSet(), _ParseContext_removeComponent = function _ParseContext_removeComponent(refKey) {
520
574
  if (this.protocol.type !== 'oas') {
521
575
  return;
522
576
  }
@@ -629,4 +683,60 @@ _ParseContext_refConsumers = new WeakMap(), _ParseContext_refErrors = new WeakMa
629
683
  frames.length >= rootFrames.length &&
630
684
  rootFrames.every((frame, index) => frames[index] === frame);
631
685
  return startsWithRoot ? new StackTrail_js_1.StackTrail(frames.slice(rootFrames.length)) : stackTrail;
686
+ }, _ParseContext_checkRefs = function _ParseContext_checkRefs() {
687
+ __classPrivateFieldGet(this, _ParseContext_oasRefs, "f").forEach(({ consumer, ref }) => {
688
+ if (__classPrivateFieldGet(this, _ParseContext_refErrors, "f").has(toRefKey(ref.$ref))) {
689
+ return;
690
+ }
691
+ try {
692
+ ref.resolveOnce();
693
+ }
694
+ catch (error) {
695
+ if (!DanglingRefError_js_1.DanglingRefError.is(error)) {
696
+ const message = error instanceof Error ? error.message : String(error);
697
+ __classPrivateFieldGet(this, _ParseContext_instances, "m", _ParseContext_removeHolder).call(this, {
698
+ consumer,
699
+ ref,
700
+ error,
701
+ type: 'REF_TYPE_MISMATCH',
702
+ message: `${message}, so what holds it is removed.`
703
+ });
704
+ }
705
+ else if (this.system.danglingRefs?.includes(ref.refType)) {
706
+ this.logIssueNoKey({
707
+ level: 'warning',
708
+ message: `${error.message}. It is kept (system.danglingRefs lists '${ref.refType}'), and resolving it throws DanglingRefError.`,
709
+ parent: { $ref: ref.$ref },
710
+ stackTrail: consumer,
711
+ type: 'DANGLING_REF'
712
+ });
713
+ }
714
+ else {
715
+ __classPrivateFieldGet(this, _ParseContext_instances, "m", _ParseContext_removeHolder).call(this, {
716
+ consumer,
717
+ ref,
718
+ error,
719
+ type: 'DANGLING_REF',
720
+ message: `${error.message}, so what holds it is removed. To keep it, list '${ref.refType}' in system.danglingRefs.`
721
+ });
722
+ }
723
+ }
724
+ });
725
+ }, _ParseContext_removeHolder = function _ParseContext_removeHolder({ consumer, ref, error, type, message }) {
726
+ this.logIssueNoKey({
727
+ level: 'error',
728
+ message,
729
+ cause: error,
730
+ parent: { $ref: ref.$ref },
731
+ stackTrail: consumer,
732
+ type
733
+ });
734
+ const documentTrail = __classPrivateFieldGet(this, _ParseContext_instances, "m", _ParseContext_toDocumentTrail).call(this, consumer);
735
+ if (documentTrail.toStackRef() !== undefined) {
736
+ return;
737
+ }
738
+ const location = consumer.toString();
739
+ __classPrivateFieldGet(this, _ParseContext_instances, "m", _ParseContext_removeConsumer).call(this, consumer, documentTrail)
740
+ .filter(removed => removed !== location)
741
+ .forEach(removed => __classPrivateFieldGet(this, _ParseContext_instances, "m", _ParseContext_logDependencyIssue).call(this, { location: removed, refKey: ref.$ref, rootCause: { error, location } }));
632
742
  };
@@ -185,11 +185,25 @@ export type AnyOasDocument = OpenAPIV2.Document | OpenAPIV3.Document | OpenAPIV3
185
185
  * of two or more members as any value. The schema keeps its other keywords.
186
186
  * One for each schema.
187
187
  *
188
+ * `DANGLING_REF` — a `$ref` names nothing in the document. One for each
189
+ * place the `$ref` is written. A `warning` when `system.danglingRefs` lists
190
+ * the `$ref`'s kind: the ref stays, and resolving it throws
191
+ * `DanglingRefError`; with `allOfMember` listed, a `$ref` that core merges
192
+ * (in an `allOf`, or in a `oneOf` or `anyOf` member) is left out of the
193
+ * merge. Otherwise (the default lists none)
194
+ * an `error`: what holds the ref is removed, and each item that uses it gets
195
+ * an `INVALID_DEPENDENCY_REF`.
196
+ *
197
+ * `REF_TYPE_MISMATCH` (`error`) — a `$ref` names a component of the wrong
198
+ * kind, such as a request body that is a `$ref` to
199
+ * `#/components/schemas/Pet`. One for each place the `$ref` is written. What
200
+ * holds the ref is removed; `system.danglingRefs` does not apply.
201
+ *
188
202
  * `RUN_FAILED` (`error`) — the run itself failed outside the per-item
189
203
  * catches. Its `location` names the entry and phase, for example
190
204
  * `toArtifacts:render`.
191
205
  */
192
- export type OasIssueType = 'UNEXPECTED_PROPERTY' | 'MISSING_OBJECT_TYPE' | 'MISSING_STRING_TYPE' | 'MISSING_ARRAY_TYPE' | 'MISSING_BOOLEAN_TYPE' | 'MISSING_RESPONSES' | 'MISSING_INFO' | 'EMPTY_PARAMETER' | 'INVALID_EXAMPLE' | 'INVALID_ENUM' | 'INVALID_DEFAULT' | 'INVALID_NULLABLE' | 'UNEXPECTED_FORMAT' | 'INVALID_RESPONSE' | 'INVALID_REQUEST_BODY' | 'INVALID_HEADER' | 'INVALID_FORMAT' | 'INVALID_OPERATION' | 'INVALID_SCHEMA' | 'INVALID_PARAMETER' | 'INVALID_SECURITY_SCHEME' | 'INVALID_DEPENDENCY_REF' | 'EXAMPLE_AND_EXAMPLES_DEFINED' | 'INVALID_TAG_PARENT' | 'INVALID_TAG' | 'INVALID_EXTERNAL_DOCS' | 'UNSUPPORTED_OPERATION_METHOD' | 'WILDCARD_MEDIA_TYPE' | 'NO_JSON_MEDIA_TYPE' | 'ALLOF_CONTRADICTION' | 'ANYOF_AS_UNKNOWN' | 'RUN_FAILED';
206
+ export type OasIssueType = 'UNEXPECTED_PROPERTY' | 'MISSING_OBJECT_TYPE' | 'MISSING_STRING_TYPE' | 'MISSING_ARRAY_TYPE' | 'MISSING_BOOLEAN_TYPE' | 'MISSING_RESPONSES' | 'MISSING_INFO' | 'EMPTY_PARAMETER' | 'INVALID_EXAMPLE' | 'INVALID_ENUM' | 'INVALID_DEFAULT' | 'INVALID_NULLABLE' | 'UNEXPECTED_FORMAT' | 'INVALID_RESPONSE' | 'INVALID_REQUEST_BODY' | 'INVALID_HEADER' | 'INVALID_FORMAT' | 'INVALID_OPERATION' | 'INVALID_SCHEMA' | 'INVALID_PARAMETER' | 'INVALID_SECURITY_SCHEME' | 'INVALID_DEPENDENCY_REF' | 'EXAMPLE_AND_EXAMPLES_DEFINED' | 'INVALID_TAG_PARENT' | 'INVALID_TAG' | 'INVALID_EXTERNAL_DOCS' | 'UNSUPPORTED_OPERATION_METHOD' | 'WILDCARD_MEDIA_TYPE' | 'NO_JSON_MEDIA_TYPE' | 'ALLOF_CONTRADICTION' | 'ANYOF_AS_UNKNOWN' | 'DANGLING_REF' | 'REF_TYPE_MISMATCH' | 'RUN_FAILED';
193
207
  /**
194
208
  * Valibot schema for {@link OasIssueType}. Annotation deliberately omitted
195
209
  * so the precise literal-union output type flows through to consumers
@@ -197,7 +211,7 @@ export type OasIssueType = 'UNEXPECTED_PROPERTY' | 'MISSING_OBJECT_TYPE' | 'MISS
197
211
  * this list and {@link OasIssueType} is caught by `assertSchemaMatchesType`
198
212
  * below.
199
213
  */
200
- export declare const oasIssueType: v.UnionSchema<[v.LiteralSchema<"UNEXPECTED_PROPERTY", undefined>, v.LiteralSchema<"MISSING_OBJECT_TYPE", undefined>, v.LiteralSchema<"MISSING_STRING_TYPE", undefined>, v.LiteralSchema<"MISSING_ARRAY_TYPE", undefined>, v.LiteralSchema<"MISSING_BOOLEAN_TYPE", undefined>, v.LiteralSchema<"MISSING_RESPONSES", undefined>, v.LiteralSchema<"MISSING_INFO", undefined>, v.LiteralSchema<"EMPTY_PARAMETER", undefined>, v.LiteralSchema<"INVALID_EXAMPLE", undefined>, v.LiteralSchema<"INVALID_ENUM", undefined>, v.LiteralSchema<"INVALID_DEFAULT", undefined>, v.LiteralSchema<"INVALID_NULLABLE", undefined>, v.LiteralSchema<"UNEXPECTED_FORMAT", undefined>, v.LiteralSchema<"INVALID_RESPONSE", undefined>, v.LiteralSchema<"INVALID_REQUEST_BODY", undefined>, v.LiteralSchema<"INVALID_HEADER", undefined>, v.LiteralSchema<"INVALID_FORMAT", undefined>, v.LiteralSchema<"INVALID_OPERATION", undefined>, v.LiteralSchema<"INVALID_SCHEMA", undefined>, v.LiteralSchema<"INVALID_PARAMETER", undefined>, v.LiteralSchema<"INVALID_SECURITY_SCHEME", undefined>, v.LiteralSchema<"INVALID_DEPENDENCY_REF", undefined>, v.LiteralSchema<"EXAMPLE_AND_EXAMPLES_DEFINED", undefined>, v.LiteralSchema<"INVALID_TAG_PARENT", undefined>, v.LiteralSchema<"INVALID_TAG", undefined>, v.LiteralSchema<"INVALID_EXTERNAL_DOCS", undefined>, v.LiteralSchema<"UNSUPPORTED_OPERATION_METHOD", undefined>, v.LiteralSchema<"WILDCARD_MEDIA_TYPE", undefined>, v.LiteralSchema<"NO_JSON_MEDIA_TYPE", undefined>, v.LiteralSchema<"ALLOF_CONTRADICTION", undefined>, v.LiteralSchema<"ANYOF_AS_UNKNOWN", undefined>, v.LiteralSchema<"RUN_FAILED", undefined>], undefined>;
214
+ export declare const oasIssueType: v.UnionSchema<[v.LiteralSchema<"UNEXPECTED_PROPERTY", undefined>, v.LiteralSchema<"MISSING_OBJECT_TYPE", undefined>, v.LiteralSchema<"MISSING_STRING_TYPE", undefined>, v.LiteralSchema<"MISSING_ARRAY_TYPE", undefined>, v.LiteralSchema<"MISSING_BOOLEAN_TYPE", undefined>, v.LiteralSchema<"MISSING_RESPONSES", undefined>, v.LiteralSchema<"MISSING_INFO", undefined>, v.LiteralSchema<"EMPTY_PARAMETER", undefined>, v.LiteralSchema<"INVALID_EXAMPLE", undefined>, v.LiteralSchema<"INVALID_ENUM", undefined>, v.LiteralSchema<"INVALID_DEFAULT", undefined>, v.LiteralSchema<"INVALID_NULLABLE", undefined>, v.LiteralSchema<"UNEXPECTED_FORMAT", undefined>, v.LiteralSchema<"INVALID_RESPONSE", undefined>, v.LiteralSchema<"INVALID_REQUEST_BODY", undefined>, v.LiteralSchema<"INVALID_HEADER", undefined>, v.LiteralSchema<"INVALID_FORMAT", undefined>, v.LiteralSchema<"INVALID_OPERATION", undefined>, v.LiteralSchema<"INVALID_SCHEMA", undefined>, v.LiteralSchema<"INVALID_PARAMETER", undefined>, v.LiteralSchema<"INVALID_SECURITY_SCHEME", undefined>, v.LiteralSchema<"INVALID_DEPENDENCY_REF", undefined>, v.LiteralSchema<"EXAMPLE_AND_EXAMPLES_DEFINED", undefined>, v.LiteralSchema<"INVALID_TAG_PARENT", undefined>, v.LiteralSchema<"INVALID_TAG", undefined>, v.LiteralSchema<"INVALID_EXTERNAL_DOCS", undefined>, v.LiteralSchema<"UNSUPPORTED_OPERATION_METHOD", undefined>, v.LiteralSchema<"WILDCARD_MEDIA_TYPE", undefined>, v.LiteralSchema<"NO_JSON_MEDIA_TYPE", undefined>, v.LiteralSchema<"ALLOF_CONTRADICTION", undefined>, v.LiteralSchema<"ANYOF_AS_UNKNOWN", undefined>, v.LiteralSchema<"DANGLING_REF", undefined>, v.LiteralSchema<"REF_TYPE_MISMATCH", undefined>, v.LiteralSchema<"RUN_FAILED", undefined>], undefined>;
201
215
  export type GenerateResult = {
202
216
  files: Map<string, FileBase>;
203
217
  previews: Record<string, Preview>;
@@ -74,6 +74,8 @@ exports.oasIssueType = v.union([
74
74
  v.literal('NO_JSON_MEDIA_TYPE'),
75
75
  v.literal('ALLOF_CONTRADICTION'),
76
76
  v.literal('ANYOF_AS_UNKNOWN'),
77
+ v.literal('DANGLING_REF'),
78
+ v.literal('REF_TYPE_MISMATCH'),
77
79
  v.literal('RUN_FAILED')
78
80
  ]);
79
81
  // Compile-time drift detector: this binding fails to type-check if
@@ -60,7 +60,10 @@ export type TryParseAtArgs<T> = {
60
60
  * Run `fn(childStack)` inside `stackTrail.trace(key, ...)`. On throw:
61
61
  *
62
62
  * - logs a `level: 'error'` issue at the child location with the
63
- * given `type` and the thrown value as `cause`
63
+ * given `type` and the thrown value as `cause`. A `DanglingRefError`
64
+ * is logged as `DANGLING_REF`: core resolved a ref while it parsed (one
65
+ * it merges, in an `allOf` or a `oneOf` or `anyOf` member, when
66
+ * `system.danglingRefs` does not list `allOfMember`)
64
67
  * - registers a ref error if `refKey` is provided
65
68
  * - returns `undefined`
66
69
  *
@@ -22,11 +22,15 @@
22
22
  */
23
23
  Object.defineProperty(exports, "__esModule", { value: true });
24
24
  exports.tryParseAt = void 0;
25
+ const DanglingRefError_js_1 = require("../oas/ref/DanglingRefError.js");
25
26
  /**
26
27
  * Run `fn(childStack)` inside `stackTrail.trace(key, ...)`. On throw:
27
28
  *
28
29
  * - logs a `level: 'error'` issue at the child location with the
29
- * given `type` and the thrown value as `cause`
30
+ * given `type` and the thrown value as `cause`. A `DanglingRefError`
31
+ * is logged as `DANGLING_REF`: core resolved a ref while it parsed (one
32
+ * it merges, in an `allOf` or a `oneOf` or `anyOf` member, when
33
+ * `system.danglingRefs` does not list `allOfMember`)
30
34
  * - registers a ref error if `refKey` is provided
31
35
  * - returns `undefined`
32
36
  *
@@ -38,6 +42,7 @@ const tryParseAt = ({ stackTrail, key, context, type, parent, refKey, fn }) => {
38
42
  }
39
43
  catch (error) {
40
44
  const normalized = error instanceof Error ? error : new Error(String(error));
45
+ const dangling = DanglingRefError_js_1.DanglingRefError.is(error);
41
46
  stackTrail.trace(key, childStack => {
42
47
  if (refKey !== undefined) {
43
48
  context.registerRefError(error, refKey, childStack.toString());
@@ -46,9 +51,11 @@ const tryParseAt = ({ stackTrail, key, context, type, parent, refKey, fn }) => {
46
51
  level: 'error',
47
52
  stackTrail: childStack,
48
53
  parent,
49
- message: normalized.message,
54
+ message: dangling
55
+ ? `${normalized.message}. Core resolves it while it parses, so what holds it is removed.`
56
+ : normalized.message,
50
57
  cause: normalized,
51
- type
58
+ type: dangling ? 'DANGLING_REF' : type
52
59
  });
53
60
  });
54
61
  return undefined;
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.collateExamples = void 0;
4
4
  require("../_dnt.polyfills.js");
5
5
  const isEmpty_js_1 = require("./isEmpty.js");
6
+ const DanglingRefError_js_1 = require("../oas/ref/DanglingRefError.js");
6
7
  /**
7
8
  * Recursively collates and builds example values from OpenAPI schemas.
8
9
  *
@@ -168,11 +169,20 @@ const collateExamples = ({ objectSchema, depth, seen }) => {
168
169
  if (seen?.has(objectSchema.$ref)) {
169
170
  return undefined;
170
171
  }
171
- return (0, exports.collateExamples)({
172
- objectSchema: objectSchema.resolve(),
173
- depth: depth + 1,
174
- seen: new Set(seen ?? []).add(objectSchema.$ref)
175
- });
172
+ try {
173
+ return (0, exports.collateExamples)({
174
+ objectSchema: objectSchema.resolve(),
175
+ depth: depth + 1,
176
+ seen: new Set(seen ?? []).add(objectSchema.$ref)
177
+ });
178
+ }
179
+ catch (error) {
180
+ // A dangling reference names no schema, so it has no example either.
181
+ if (DanglingRefError_js_1.DanglingRefError.is(error)) {
182
+ return undefined;
183
+ }
184
+ throw error;
185
+ }
176
186
  }
177
187
  case 'object': {
178
188
  if (objectSchema.example) {
@@ -9,6 +9,10 @@ import type { ReferenceObject } from '../parse/v3-0/_merge-all-of/types.js';
9
9
  * and extracts the final component as a branded RefName type. It's used throughout
10
10
  * the SKMTC system to convert string references into type-safe reference names.
11
11
  *
12
+ * A `$ref` is a URI fragment that holds a JSON pointer (RFC 6901), so the name
13
+ * is unescaped as one: `%20` is a space, and `~1` and `~0` are `/` and `~`.
14
+ * `#/components/schemas/Foo%20Bar` names the component `Foo Bar`.
15
+ *
12
16
  * @param $ref - The OpenAPI reference string (e.g., '#/components/schemas/User')
13
17
  * @returns The extracted reference name as a branded RefName type
14
18
  *
@@ -117,7 +121,7 @@ export declare const isRef: (value: unknown) => value is Ref;
117
121
  * @param oasDocument - The OpenAPI document containing the schemas to resolve against
118
122
  * @returns A function that resolves reference objects to schema objects
119
123
  *
120
- * @throws {Error} When a reference cannot be resolved or points to a non-existent schema
124
+ * @throws {DanglingRefError} When a reference names no schema in the document
121
125
  *
122
126
  * @example Basic usage
123
127
  * ```typescript
@@ -148,7 +152,7 @@ export declare const isRef: (value: unknown) => value is Ref;
148
152
  * const schema = resolver({ $ref: '#/components/schemas/NonExistent' });
149
153
  * } catch (error) {
150
154
  * console.error('Reference resolution failed:', error.message);
151
- * // Error: Invalid reference: #/components/schemas/NonExistent
155
+ * // Ref "#/components/schemas/NonExistent" names nothing in the document
152
156
  * }
153
157
  * ```
154
158
  *
@@ -167,5 +171,7 @@ export declare const isRef: (value: unknown) => value is Ref;
167
171
  * }
168
172
  * ```
169
173
  */
170
- export declare const toGetRef: (oasDocument: OpenAPIV3.Document) => ({ $ref }: ReferenceObject) => OpenAPIV3.SchemaObject;
174
+ export declare const toGetRef: (oasDocument: OpenAPIV3.Document, onDangling?: OnDangling) => ({ $ref }: ReferenceObject) => OpenAPIV3.SchemaObject;
175
+ /** What a resolver reads in place of a `$ref` that names nothing; it may throw. */
176
+ type OnDangling = ($ref: string) => OpenAPIV3.SchemaObject;
171
177
  export {};
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.toGetRef = exports.isRef = exports.toRefName = void 0;
4
4
  require("../_dnt.polyfills.js");
5
+ const DanglingRefError_js_1 = require("../oas/ref/DanglingRefError.js");
5
6
  /**
6
7
  * Extracts a reference name from an OpenAPI $ref string.
7
8
  *
@@ -9,6 +10,10 @@ require("../_dnt.polyfills.js");
9
10
  * and extracts the final component as a branded RefName type. It's used throughout
10
11
  * the SKMTC system to convert string references into type-safe reference names.
11
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
+ *
12
17
  * @param $ref - The OpenAPI reference string (e.g., '#/components/schemas/User')
13
18
  * @returns The extracted reference name as a branded RefName type
14
19
  *
@@ -44,14 +49,26 @@ require("../_dnt.polyfills.js");
44
49
  * ```
45
50
  */
46
51
  const toRefName = ($ref) => {
47
- // TODO: Add validation here to ensure reference exists
48
- const refName = $ref.split('/').slice(-1)[0];
49
- if (!refName) {
52
+ const segment = $ref.split('/').slice(-1)[0];
53
+ if (!segment) {
50
54
  throw new Error('Invalid reference');
51
55
  }
52
- return refName;
56
+ return toUnescapedSegment(segment);
53
57
  };
54
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', '~');
62
+ };
63
+ const toPercentDecoded = (segment) => {
64
+ try {
65
+ return decodeURIComponent(segment);
66
+ }
67
+ catch {
68
+ // A `%` that starts no valid escape is read as written.
69
+ return segment;
70
+ }
71
+ };
55
72
  /**
56
73
  * Type guard function to check if a value is an OpenAPI reference object.
57
74
  *
@@ -126,7 +143,7 @@ exports.isRef = isRef;
126
143
  * @param oasDocument - The OpenAPI document containing the schemas to resolve against
127
144
  * @returns A function that resolves reference objects to schema objects
128
145
  *
129
- * @throws {Error} When a reference cannot be resolved or points to a non-existent schema
146
+ * @throws {DanglingRefError} When a reference names no schema in the document
130
147
  *
131
148
  * @example Basic usage
132
149
  * ```typescript
@@ -157,7 +174,7 @@ exports.isRef = isRef;
157
174
  * const schema = resolver({ $ref: '#/components/schemas/NonExistent' });
158
175
  * } catch (error) {
159
176
  * console.error('Reference resolution failed:', error.message);
160
- * // Error: Invalid reference: #/components/schemas/NonExistent
177
+ * // Ref "#/components/schemas/NonExistent" names nothing in the document
161
178
  * }
162
179
  * ```
163
180
  *
@@ -176,15 +193,18 @@ exports.isRef = isRef;
176
193
  * }
177
194
  * ```
178
195
  */
179
- const toGetRef = (oasDocument) => ({ $ref }) => {
196
+ const toGetRef = (oasDocument, onDangling) => ({ $ref }) => {
180
197
  const refName = (0, exports.toRefName)($ref);
181
198
  const item = oasDocument.components?.schemas?.[refName];
182
199
  if ((0, exports.isRef)(item)) {
183
- return (0, exports.toGetRef)(oasDocument)(item);
200
+ return (0, exports.toGetRef)(oasDocument, onDangling)(item);
184
201
  }
185
202
  if (item) {
186
203
  return item;
187
204
  }
188
- throw new Error(`Invalid reference: ${$ref}`);
205
+ if (onDangling) {
206
+ return onDangling($ref);
207
+ }
208
+ throw new DanglingRefError_js_1.DanglingRefError($ref);
189
209
  };
190
210
  exports.toGetRef = toGetRef;
package/script/mod.d.ts CHANGED
@@ -163,6 +163,7 @@ export * from './oas/parameter/Parameter.js';
163
163
  export * from './oas/parameter/parameter-types.js';
164
164
  export * from './oas/pathItem/PathItem.js';
165
165
  export * from './oas/ref/Ref.js';
166
+ export * from './oas/ref/DanglingRefError.js';
166
167
  export * from './oas/ref/ref-types.js';
167
168
  export * from './parse/v3-0/ref/toRefV31.js';
168
169
  export * from './oas/requestBody/RequestBody.js';
package/script/mod.js CHANGED
@@ -179,6 +179,7 @@ __exportStar(require("./oas/parameter/Parameter.js"), exports);
179
179
  __exportStar(require("./oas/parameter/parameter-types.js"), exports);
180
180
  __exportStar(require("./oas/pathItem/PathItem.js"), exports);
181
181
  __exportStar(require("./oas/ref/Ref.js"), exports);
182
+ __exportStar(require("./oas/ref/DanglingRefError.js"), exports);
182
183
  __exportStar(require("./oas/ref/ref-types.js"), exports);
183
184
  __exportStar(require("./parse/v3-0/ref/toRefV31.js"), exports);
184
185
  __exportStar(require("./oas/requestBody/RequestBody.js"), exports);
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Thrown when a reference that names nothing in the document is resolved.
3
+ *
4
+ * By default the parser removes what holds such a reference, so a generator
5
+ * never meets one. When `client.json` `system.danglingRefs` lists the
6
+ * reference's kind, it stays, and a generator that resolves it can catch
7
+ * this error and render something else in its place. Test for it with
8
+ * {@link DanglingRefError.is}, not `instanceof`.
9
+ */
10
+ import "../../_dnt.polyfills.js";
11
+ export declare class DanglingRefError extends Error {
12
+ /** The `$ref`, or the component name, that names nothing. */
13
+ ref: string;
14
+ constructor(ref: string);
15
+ /**
16
+ * True when `error` is a `DanglingRefError`. It reads the error's name,
17
+ * not its class, so it is also true for one thrown by another copy of
18
+ * `@skmtc/core`, such as the copy a generator bundle resolves, where
19
+ * `instanceof` is false.
20
+ */
21
+ static is(error: unknown): error is DanglingRefError;
22
+ }