@skmtc/core 0.35.3 → 0.36.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,14 +1,12 @@
1
1
  import "../../_dnt.polyfills.js";
2
2
  import type { OasTag } from '../tag/Tag.js';
3
- import type { OasComponents } from '../components/Components.js';
3
+ import type { ComponentsEntry, OasComponents } from '../components/Components.js';
4
4
  import type { OasOperation } from '../operation/Operation.js';
5
5
  import type { OasWebhook } from '../webhook/Webhook.js';
6
6
  import type { OasInfo } from '../info/Info.js';
7
7
  import type { OasServer } from '../server/Server.js';
8
8
  import type { OasSecurityRequirement } from '../securityRequirement/SecurityRequirement.js';
9
9
  import type { StackTrail } from '../../context/StackTrail.js';
10
- import type { OasSchema } from '../schema/Schema.js';
11
- import type { OasRef } from '../ref/Ref.js';
12
10
  import type { OasExternalDocs } from '../externalDocs/ExternalDocs.js';
13
11
  /**
14
12
  * Fields that define the structure of an OpenAPI v3 document.
@@ -179,10 +177,12 @@ export declare class OasDocument {
179
177
  * Removes an item from the document based on a stack trail path.
180
178
  *
181
179
  * This method is used internally during document processing to remove
182
- * specific operations or schema components. The stack trail indicates
183
- * the path to the item within the document structure.
180
+ * specific operations, webhooks or components. The stack trail indicates
181
+ * the path to the item within the document structure. A
182
+ * `components:<bucket>:<name>` trail removes the entry from that bucket
183
+ * (`components:requestBodies:X` removes request body `X`, not schema `X`).
184
184
  *
185
- * @param stackTrail - Path to the item to remove
185
+ * @param stackTrail - Document-relative path to the item to remove
186
186
  * @returns The removed item, or undefined if not found
187
187
  *
188
188
  * @internal This method is primarily used by the processing pipeline
@@ -196,7 +196,7 @@ export declare class OasDocument {
196
196
  * const removedSchema = document.removeItem(new StackTrail(['components', 'schemas', 'User']));
197
197
  * ```
198
198
  */
199
- removeItem(stackTrail: StackTrail): OasOperation | OasWebhook | OasSchema | OasRef<'schema'> | undefined;
199
+ removeItem(stackTrail: StackTrail): OasOperation | OasWebhook | ComponentsEntry | undefined;
200
200
  /**
201
201
  * Sets the document fields after parsing.
202
202
  *
@@ -145,10 +145,12 @@ export class OasDocument {
145
145
  * Removes an item from the document based on a stack trail path.
146
146
  *
147
147
  * This method is used internally during document processing to remove
148
- * specific operations or schema components. The stack trail indicates
149
- * the path to the item within the document structure.
148
+ * specific operations, webhooks or components. The stack trail indicates
149
+ * the path to the item within the document structure. A
150
+ * `components:<bucket>:<name>` trail removes the entry from that bucket
151
+ * (`components:requestBodies:X` removes request body `X`, not schema `X`).
150
152
  *
151
- * @param stackTrail - Path to the item to remove
153
+ * @param stackTrail - Document-relative path to the item to remove
152
154
  * @returns The removed item, or undefined if not found
153
155
  *
154
156
  * @internal This method is primarily used by the processing pipeline
@@ -189,7 +191,7 @@ export class OasDocument {
189
191
  if (typeof third !== 'string') {
190
192
  throw new Error(`RefName cannot be a number: ${third}`);
191
193
  }
192
- return __classPrivateFieldGet(this, _OasDocument_fields, "f").components.removeSchema(third);
194
+ return __classPrivateFieldGet(this, _OasDocument_fields, "f")?.components?.removeEntry(second, third);
193
195
  }
194
196
  default:
195
197
  throw new Error(`Unexpected stack trail: ${stackTrail}`);
@@ -35,6 +35,7 @@ export type ToPathParameterListArgs<Entry, Parameter> = {
35
35
  index: number;
36
36
  }) => Parameter[];
37
37
  };
38
+ export declare const toNameAndIn: (parameter: unknown) => Pick<BrokenPathParameter, "name" | "in">;
38
39
  /**
39
40
  * Parses a path item's `parameters` without letting a throw escape. Each
40
41
  * entry that fails logs one `INVALID_PARAMETER` error at its index and is
@@ -42,6 +43,18 @@ export type ToPathParameterListArgs<Entry, Parameter> = {
42
43
  * The caller decides per operation which broken entries apply.
43
44
  */
44
45
  export declare const toPathParameterList: <Entry, Parameter>({ parameters, stackTrail, context, toEntry }: ToPathParameterListArgs<Entry, Parameter>) => PathParameterList<Parameter>;
46
+ /**
47
+ * The first broken path-level parameter that applies to an operation. An
48
+ * entry applies unless it has a readable `name` and `in` and the
49
+ * operation's inline `parameters` hold the same pair, which overrides it.
50
+ * A `$ref` operation parameter cannot be resolved during parse, so it
51
+ * overrides nothing.
52
+ */
53
+ export declare const toApplyingBrokenParameter: ({ broken, operation }: {
54
+ broken: BrokenPathParameter[];
55
+ /** The raw operation object. */
56
+ operation: unknown;
57
+ }) => BrokenPathParameter | undefined;
45
58
  /**
46
59
  * True when a broken path-level parameter applies to the operation. Logs
47
60
  * one `INVALID_OPERATION` error at the operation that names the first
@@ -25,7 +25,7 @@ export const toParameterEntries = ({ parameters, stackTrail, context }) => {
25
25
  throw new Error(`Expected parameters to be an array but received ${typeof parameters}`);
26
26
  };
27
27
  const toError = (error) => error instanceof Error ? error : new Error(String(error));
28
- const toNameAndIn = (parameter) => {
28
+ export const toNameAndIn = (parameter) => {
29
29
  if (typeof parameter === 'object' &&
30
30
  parameter !== null &&
31
31
  'name' in parameter &&
@@ -99,7 +99,7 @@ export const toPathParameterList = ({ parameters, stackTrail, context, toEntry }
99
99
  * A `$ref` operation parameter cannot be resolved during parse, so it
100
100
  * overrides nothing.
101
101
  */
102
- const toApplyingBrokenParameter = ({ broken, operation }) => {
102
+ export const toApplyingBrokenParameter = ({ broken, operation }) => {
103
103
  if (broken.length === 0) {
104
104
  return undefined;
105
105
  }
@@ -3,6 +3,16 @@ import { toSpecificationExtensionsV3 } from '../specificationExtensions/toSpecif
3
3
  import { toOptionalServerVariablesV3 } from '../serverVariable/toServerVariableV3.js';
4
4
  import { tryParseAt } from '../../../context/tryParseAt.js';
5
5
  export const toServersV3 = ({ servers, stackTrail, context }) => {
6
+ if (!Array.isArray(servers)) {
7
+ context.logIssueNoKey({
8
+ level: 'error',
9
+ stackTrail,
10
+ parent: servers,
11
+ message: '"servers" must be an array; left out',
12
+ type: 'INVALID_OPERATION'
13
+ });
14
+ return [];
15
+ }
6
16
  return servers.flatMap((server, index) => {
7
17
  const parsed = tryParseAt({
8
18
  stackTrail,
@@ -21,7 +31,7 @@ export const toServersV3 = ({ servers, stackTrail, context }) => {
21
31
  });
22
32
  };
23
33
  export const toOptionalServersV3 = ({ servers, stackTrail, context }) => {
24
- if (!servers) {
34
+ if (servers === undefined || servers === null) {
25
35
  return undefined;
26
36
  }
27
37
  return toServersV3({ servers, stackTrail, context });
@@ -3,6 +3,16 @@ import { toSpecificationExtensionsV3 } from '../specificationExtensions/toSpecif
3
3
  import { toOptionalServerVariablesV3 } from '../serverVariable/toServerVariableV3.js';
4
4
  import { tryParseAt } from '../../../context/tryParseAt.js';
5
5
  export const toServersV3 = ({ servers, stackTrail, context }) => {
6
+ if (!Array.isArray(servers)) {
7
+ context.logIssueNoKey({
8
+ level: 'error',
9
+ stackTrail,
10
+ parent: servers,
11
+ message: '"servers" must be an array; left out',
12
+ type: 'INVALID_OPERATION'
13
+ });
14
+ return [];
15
+ }
6
16
  return servers.flatMap((server, index) => {
7
17
  const parsed = tryParseAt({
8
18
  stackTrail,
@@ -21,7 +31,7 @@ export const toServersV3 = ({ servers, stackTrail, context }) => {
21
31
  });
22
32
  };
23
33
  export const toOptionalServersV3 = ({ servers, stackTrail, context }) => {
24
- if (!servers) {
34
+ if (servers === undefined || servers === null) {
25
35
  return undefined;
26
36
  }
27
37
  return toServersV3({ servers, stackTrail, context });
@@ -3,6 +3,16 @@ import { toSpecificationExtensionsV3 } from '../specificationExtensions/toSpecif
3
3
  import { toOptionalServerVariablesV3 } from '../serverVariable/toServerVariableV3.js';
4
4
  import { tryParseAt } from '../../../context/tryParseAt.js';
5
5
  export const toServersV3 = ({ servers, stackTrail, context }) => {
6
+ if (!Array.isArray(servers)) {
7
+ context.logIssueNoKey({
8
+ level: 'error',
9
+ stackTrail,
10
+ parent: servers,
11
+ message: '"servers" must be an array; left out',
12
+ type: 'INVALID_OPERATION'
13
+ });
14
+ return [];
15
+ }
6
16
  return servers.flatMap((server, index) => {
7
17
  const parsed = tryParseAt({
8
18
  stackTrail,
@@ -21,7 +31,7 @@ export const toServersV3 = ({ servers, stackTrail, context }) => {
21
31
  });
22
32
  };
23
33
  export const toOptionalServersV3 = ({ servers, stackTrail, context }) => {
24
- if (!servers) {
34
+ if (servers === undefined || servers === null) {
25
35
  return undefined;
26
36
  }
27
37
  return toServersV3({ servers, stackTrail, context });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@skmtc/core",
3
- "version": "0.35.3",
3
+ "version": "0.36.1",
4
4
  "description": "Skmtc is a declarative code generation framework",
5
5
  "keywords": [
6
6
  "openapi",
@@ -1,9 +1,3 @@
1
- declare global {
2
- interface Error {
3
- cause?: unknown;
4
- }
5
- }
6
- export {};
7
1
  declare global {
8
2
  interface Object {
9
3
  /**
@@ -15,6 +9,12 @@ declare global {
15
9
  }
16
10
  }
17
11
  export {};
12
+ declare global {
13
+ interface Error {
14
+ cause?: unknown;
15
+ }
16
+ }
17
+ export {};
18
18
  /**
19
19
  * Based on [import-meta-ponyfill](https://github.com/gaubee/import-meta-ponyfill),
20
20
  * but instead of using npm to install additional dependencies,
@@ -12,12 +12,8 @@
12
12
  * `logSkippedFields` with a pre-computed `location` string) accepts a
13
13
  * raw string. Both funnel into the shared {@link ParseContext.logIssueAt}.
14
14
  *
15
- * `removeErroredItems` is universal but its body dispatches on
16
- * `protocol.type` — the cleanup step is document-shaped. The GQL branch
17
- * is a no-op stub today; the infrastructure (the `#refConsumers` /
18
- * `#refErrors` maps, `registerRef` / `registerRefError`) is in place
19
- * for GQL parsers to populate when type-reference invalidation is
20
- * needed.
15
+ * `removeErroredItems` is universal; the removal it runs dispatches on
16
+ * `protocol.type` because the cleanup step is document-shaped.
21
17
  */
22
18
  import "../_dnt.polyfills.js";
23
19
  import type { OpenAPIV3 } from 'openapi-types';
@@ -108,32 +104,28 @@ export declare class ParseContext {
108
104
  get parsedDocument(): SkmtcParsedDocument;
109
105
  /**
110
106
  * Runs the protocol-appropriate parse step and returns the result
111
- * wrapped in {@link SkmtcParsedDocument}. `stackTrail` is required
112
- * for OAS (used by `toDocumentFieldsV3` for issue location tracking)
113
- * and ignored by GQL (which uses pre-computed schema addresses).
107
+ * wrapped in {@link SkmtcParsedDocument}. Both protocols walk under
108
+ * `stackTrail`, so issue locations start with its frames; pruning
109
+ * removes those frames before it reads a trail as a document address.
114
110
  */
115
111
  parse(stackTrail: StackTrail): SkmtcParsedDocument;
116
112
  /**
117
- * Walks any registered ref errors and prunes their consumers from
118
- * the parsed document. Symmetric across protocols: OAS prunes via
119
- * `OasDocument.removeItem`, GQL via `GqlDocument.removeItem`. Each
120
- * pruned consumer yields an `INVALID_DEPENDENCY_REF` issue.
113
+ * Removes every item that depends on a ref with a registered error.
121
114
  *
122
- * Pruning is deliberately **single-level** — only the direct
123
- * consumers of a parse-errored schema are removed. Anything those
124
- * removals leave with a dangling reference is left in place: if a
125
- * generator never resolves it, it is harmless; if one does, that
126
- * single artifact fails at generate time and is isolated there. We
127
- * do not cascade transitively.
115
+ * OAS: a component with an error is removed, even when the error is in
116
+ * one of its properties. Each consumer of a removed component is removed
117
+ * too. A consumer that is itself a component (its trail starts
118
+ * `components:<bucket>:<name>`) has its own consumers removed next, at any
119
+ * depth. GraphQL removes the consuming field, union member or operation,
120
+ * which leaves no ref to follow.
128
121
  *
129
- * Known coarseness, intentionally left as-is for now: a `paths:P:M:…`
130
- * consumer trail resolves to the *whole operation*, so an operation
131
- * that references a broken schema is pruned even when the reference
132
- * is only through a response it does not generate from. A finer
133
- * design — don't prune operations for response-position refs and let
134
- * generate-time isolation handle the dangling ref — is deferred; the
135
- * single-level + generate-time-isolation contract above keeps the
136
- * dangling ref safe in the meantime.
122
+ * Each removed consumer yields one `INVALID_DEPENDENCY_REF` at its
123
+ * location. The message names the ref it depends on and the error that
124
+ * started the removal; that error is the `cause`.
125
+ *
126
+ * A `paths:P:M:…` consumer trail resolves to the whole operation, so an
127
+ * operation is removed even when the ref is only in a response it does
128
+ * not generate from.
137
129
  */
138
130
  removeErroredItems(): void;
139
131
  /**
@@ -162,9 +154,10 @@ export declare class ParseContext {
162
154
  * target of a `$ref` (or type reference) fails to parse. `undefined`
163
155
  * `refKey` is a deliberate no-op: callers may pass the result of
164
156
  * `StackTrail.toStackRef()` directly, which is `undefined` for
165
- * non-component stack trails.
157
+ * non-component stack trails. `location` is where the error was logged;
158
+ * each `INVALID_DEPENDENCY_REF` it causes names it.
166
159
  */
167
- registerRefError(error: unknown, refKey: string | undefined): void;
160
+ registerRefError(error: unknown, refKey: string | undefined, location?: string): void;
168
161
  /**
169
162
  * Universal issue recorder. Pushes to `issues` and (when not silent)
170
163
  * mirrors to the logger. Both protocols' surface methods funnel
@@ -1,10 +1,16 @@
1
1
  "use strict";
2
+ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
3
+ if (kind === "m") throw new TypeError("Private method is not writable");
4
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
5
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
6
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
7
+ };
2
8
  var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
3
9
  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
4
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");
5
11
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
6
12
  };
7
- var _ParseContext_refConsumers, _ParseContext_refErrors;
13
+ var _ParseContext_instances, _ParseContext_refConsumers, _ParseContext_refErrors, _ParseContext_rootFrames, _ParseContext_removeComponent, _ParseContext_removeConsumer, _ParseContext_removePathParameterConsumer, _ParseContext_toRawComponentParameter, _ParseContext_logDependencyIssue, _ParseContext_toDocumentTrail;
8
14
  Object.defineProperty(exports, "__esModule", { value: true });
9
15
  exports.ParseContext = void 0;
10
16
  /**
@@ -21,12 +27,8 @@ exports.ParseContext = void 0;
21
27
  * `logSkippedFields` with a pre-computed `location` string) accepts a
22
28
  * raw string. Both funnel into the shared {@link ParseContext.logIssueAt}.
23
29
  *
24
- * `removeErroredItems` is universal but its body dispatches on
25
- * `protocol.type` — the cleanup step is document-shaped. The GQL branch
26
- * is a no-op stub today; the infrastructure (the `#refConsumers` /
27
- * `#refErrors` maps, `registerRef` / `registerRefError`) is in place
28
- * for GQL parsers to populate when type-reference invalidation is
29
- * needed.
30
+ * `removeErroredItems` is universal; the removal it runs dispatches on
31
+ * `protocol.type` because the cleanup step is document-shaped.
30
32
  */
31
33
  require("../_dnt.polyfills.js");
32
34
  const graphql_1 = require("graphql");
@@ -39,8 +41,11 @@ const GqlRegistry_js_1 = require("../gql/registry/GqlRegistry.js");
39
41
  const GqlDocument_js_1 = require("../gql/document/GqlDocument.js");
40
42
  const parseGqlDocument_js_1 = require("../gql/document/parseGqlDocument.js");
41
43
  const StackTrail_js_1 = require("./StackTrail.js");
44
+ const isPlainObject_js_1 = require("../parse/isPlainObject.js");
45
+ const pathParameters_js_1 = require("../parse/pathParameters.js");
42
46
  class ParseContext {
43
47
  constructor({ input, logger, silent = true, options }) {
48
+ _ParseContext_instances.add(this);
44
49
  Object.defineProperty(this, "issues", {
45
50
  enumerable: true,
46
51
  configurable: true,
@@ -81,7 +86,19 @@ class ParseContext {
81
86
  // encounter references. OAS uses `$ref` strings as keys; GQL would
82
87
  // use type names. The maps don't care about the encoding.
83
88
  _ParseContext_refConsumers.set(this, new Map());
84
- _ParseContext_refErrors.set(this, new Map());
89
+ _ParseContext_refErrors.set(this, new Map()
90
+ /**
91
+ * Frames of the trail `parse()` was called with (`[traceId, spanId,
92
+ * 'parse']` through `toArtifacts`). Every trail built during the walk
93
+ * starts with them; `#toDocumentTrail` strips them.
94
+ */
95
+ );
96
+ /**
97
+ * Frames of the trail `parse()` was called with (`[traceId, spanId,
98
+ * 'parse']` through `toArtifacts`). Every trail built during the walk
99
+ * starts with them; `#toDocumentTrail` strips them.
100
+ */
101
+ _ParseContext_rootFrames.set(this, []);
85
102
  this.logger = logger;
86
103
  this.silent = silent;
87
104
  switch (input.type) {
@@ -178,11 +195,12 @@ class ParseContext {
178
195
  }
179
196
  /**
180
197
  * Runs the protocol-appropriate parse step and returns the result
181
- * wrapped in {@link SkmtcParsedDocument}. `stackTrail` is required
182
- * for OAS (used by `toDocumentFieldsV3` for issue location tracking)
183
- * and ignored by GQL (which uses pre-computed schema addresses).
198
+ * wrapped in {@link SkmtcParsedDocument}. Both protocols walk under
199
+ * `stackTrail`, so issue locations start with its frames; pruning
200
+ * removes those frames before it reads a trail as a document address.
184
201
  */
185
202
  parse(stackTrail) {
203
+ __classPrivateFieldSet(this, _ParseContext_rootFrames, [...stackTrail.stackTrail], "f");
186
204
  switch (this.protocol.type) {
187
205
  case 'oas': {
188
206
  const oasState = this.protocol;
@@ -241,76 +259,40 @@ class ParseContext {
241
259
  }
242
260
  }
243
261
  /**
244
- * Walks any registered ref errors and prunes their consumers from
245
- * the parsed document. Symmetric across protocols: OAS prunes via
246
- * `OasDocument.removeItem`, GQL via `GqlDocument.removeItem`. Each
247
- * pruned consumer yields an `INVALID_DEPENDENCY_REF` issue.
262
+ * Removes every item that depends on a ref with a registered error.
248
263
  *
249
- * Pruning is deliberately **single-level** — only the direct
250
- * consumers of a parse-errored schema are removed. Anything those
251
- * removals leave with a dangling reference is left in place: if a
252
- * generator never resolves it, it is harmless; if one does, that
253
- * single artifact fails at generate time and is isolated there. We
254
- * do not cascade transitively.
264
+ * OAS: a component with an error is removed, even when the error is in
265
+ * one of its properties. Each consumer of a removed component is removed
266
+ * too. A consumer that is itself a component (its trail starts
267
+ * `components:<bucket>:<name>`) has its own consumers removed next, at any
268
+ * depth. GraphQL removes the consuming field, union member or operation,
269
+ * which leaves no ref to follow.
255
270
  *
256
- * Known coarseness, intentionally left as-is for now: a `paths:P:M:…`
257
- * consumer trail resolves to the *whole operation*, so an operation
258
- * that references a broken schema is pruned even when the reference
259
- * is only through a response it does not generate from. A finer
260
- * design — don't prune operations for response-position refs and let
261
- * generate-time isolation handle the dangling ref — is deferred; the
262
- * single-level + generate-time-isolation contract above keeps the
263
- * dangling ref safe in the meantime.
271
+ * Each removed consumer yields one `INVALID_DEPENDENCY_REF` at its
272
+ * location. The message names the ref it depends on and the error that
273
+ * started the removal; that error is the `cause`.
274
+ *
275
+ * A `paths:P:M:…` consumer trail resolves to the whole operation, so an
276
+ * operation is removed even when the ref is only in a response it does
277
+ * not generate from.
264
278
  */
265
279
  removeErroredItems() {
266
- switch (this.protocol.type) {
267
- case 'oas': {
268
- const oasState = this.protocol;
269
- for (const [refKey, errors] of __classPrivateFieldGet(this, _ParseContext_refErrors, "f")) {
270
- for (const error of errors) {
271
- const consumers = __classPrivateFieldGet(this, _ParseContext_refConsumers, "f").get(refKey) ?? [];
272
- for (const stackTrail of consumers) {
273
- const removed = oasState.oasDocument.removeItem(stackTrail);
274
- if (removed) {
275
- this.issues.push({
276
- protocol: 'oas',
277
- level: 'error',
278
- type: 'INVALID_DEPENDENCY_REF',
279
- location: stackTrail.toString(),
280
- message: error instanceof Error ? error.message : String(error),
281
- cause: error
282
- });
283
- }
284
- }
285
- }
280
+ const pending = [...__classPrivateFieldGet(this, _ParseContext_refErrors, "f")].flatMap(([refKey, [rootCause]]) => rootCause === undefined ? [] : [{ refKey, rootCause }]);
281
+ pending.forEach(({ refKey }) => __classPrivateFieldGet(this, _ParseContext_instances, "m", _ParseContext_removeComponent).call(this, refKey));
282
+ // `pending` grows while it is walked: each removed component queues its own consumers.
283
+ for (const { refKey, rootCause } of pending) {
284
+ for (const consumer of __classPrivateFieldGet(this, _ParseContext_refConsumers, "f").get(refKey) ?? []) {
285
+ const documentTrail = __classPrivateFieldGet(this, _ParseContext_instances, "m", _ParseContext_toDocumentTrail).call(this, consumer);
286
+ const removedLocations = __classPrivateFieldGet(this, _ParseContext_instances, "m", _ParseContext_removeConsumer).call(this, consumer, documentTrail);
287
+ removedLocations.forEach(location => __classPrivateFieldGet(this, _ParseContext_instances, "m", _ParseContext_logDependencyIssue).call(this, { location, refKey, rootCause }));
288
+ // A removed consumer that is a component has consumers of its own.
289
+ // `removeItem` finds a component only once, so each is queued once and a cycle ends.
290
+ const removedRefKey = this.protocol.type === 'oas' && removedLocations.length > 0
291
+ ? documentTrail.toStackRef()
292
+ : undefined;
293
+ if (removedRefKey !== undefined) {
294
+ pending.push({ refKey: removedRefKey, rootCause });
286
295
  }
287
- break;
288
- }
289
- case 'gql': {
290
- const gqlState = this.protocol;
291
- for (const [refKey, errors] of __classPrivateFieldGet(this, _ParseContext_refErrors, "f")) {
292
- for (const error of errors) {
293
- const consumers = __classPrivateFieldGet(this, _ParseContext_refConsumers, "f").get(refKey) ?? [];
294
- for (const stackTrail of consumers) {
295
- const removed = gqlState.gqlDocument.removeItem(stackTrail);
296
- if (removed) {
297
- this.issues.push({
298
- protocol: 'gql',
299
- level: 'error',
300
- type: 'INVALID_DEPENDENCY_REF',
301
- location: stackTrail.toString(),
302
- message: error instanceof Error ? error.message : String(error),
303
- cause: error
304
- });
305
- }
306
- }
307
- }
308
- }
309
- break;
310
- }
311
- default: {
312
- const _exhaustive = this.protocol;
313
- throw new Error(`Unhandled protocol type: ${JSON.stringify(_exhaustive)}`);
314
296
  }
315
297
  }
316
298
  }
@@ -357,17 +339,19 @@ class ParseContext {
357
339
  * target of a `$ref` (or type reference) fails to parse. `undefined`
358
340
  * `refKey` is a deliberate no-op: callers may pass the result of
359
341
  * `StackTrail.toStackRef()` directly, which is `undefined` for
360
- * non-component stack trails.
342
+ * non-component stack trails. `location` is where the error was logged;
343
+ * each `INVALID_DEPENDENCY_REF` it causes names it.
361
344
  */
362
- registerRefError(error, refKey) {
345
+ registerRefError(error, refKey, location) {
363
346
  if (!refKey)
364
347
  return;
348
+ const refError = { error, location };
365
349
  const existing = __classPrivateFieldGet(this, _ParseContext_refErrors, "f").get(refKey);
366
350
  if (existing) {
367
- existing.push(error);
351
+ existing.push(refError);
368
352
  }
369
353
  else {
370
- __classPrivateFieldGet(this, _ParseContext_refErrors, "f").set(refKey, [error]);
354
+ __classPrivateFieldGet(this, _ParseContext_refErrors, "f").set(refKey, [refError]);
371
355
  }
372
356
  }
373
357
  /**
@@ -419,7 +403,7 @@ class ParseContext {
419
403
  // points at. No-op for non-component trails (and for GQL
420
404
  // trails) because `toStackRef` returns `undefined` and
421
405
  // `registerRefError` ignores undefined refs.
422
- this.registerRefError(issue.cause ?? issue.message, stackTrail.toStackRef());
406
+ this.registerRefError(issue.cause ?? issue.message, __classPrivateFieldGet(this, _ParseContext_instances, "m", _ParseContext_toDocumentTrail).call(this, stackTrail).toStackRef(), location);
423
407
  this.logIssueAt({
424
408
  protocol,
425
409
  level: 'error',
@@ -502,4 +486,117 @@ class ParseContext {
502
486
  }
503
487
  }
504
488
  exports.ParseContext = ParseContext;
505
- _ParseContext_refConsumers = new WeakMap(), _ParseContext_refErrors = new WeakMap();
489
+ _ParseContext_refConsumers = new WeakMap(), _ParseContext_refErrors = new WeakMap(), _ParseContext_rootFrames = new WeakMap(), _ParseContext_instances = new WeakSet(), _ParseContext_removeComponent = function _ParseContext_removeComponent(refKey) {
490
+ if (this.protocol.type !== 'oas') {
491
+ return;
492
+ }
493
+ const match = /^#\/components\/([^/]+)\/(.+)$/.exec(refKey);
494
+ if (match) {
495
+ this.protocol.oasDocument.removeItem(new StackTrail_js_1.StackTrail(['components', match[1], match[2]]));
496
+ }
497
+ }, _ParseContext_removeConsumer = function _ParseContext_removeConsumer(consumer, documentTrail) {
498
+ switch (this.protocol.type) {
499
+ case 'oas': {
500
+ const [first, , third] = documentTrail.stackTrail;
501
+ if ((first === 'paths' || first === 'webhooks') && third === 'parameters') {
502
+ return __classPrivateFieldGet(this, _ParseContext_instances, "m", _ParseContext_removePathParameterConsumer).call(this, consumer, documentTrail);
503
+ }
504
+ return this.protocol.oasDocument.removeItem(documentTrail) === undefined
505
+ ? []
506
+ : [consumer.toString()];
507
+ }
508
+ case 'gql':
509
+ return this.protocol.gqlDocument.removeItem(documentTrail) === undefined
510
+ ? []
511
+ : [consumer.toString()];
512
+ default: {
513
+ const _exhaustive = this.protocol;
514
+ throw new Error(`Unhandled protocol type: ${JSON.stringify(_exhaustive)}`);
515
+ }
516
+ }
517
+ }, _ParseContext_removePathParameterConsumer = function _ParseContext_removePathParameterConsumer(consumer, documentTrail) {
518
+ if (this.protocol.type !== 'oas') {
519
+ return [];
520
+ }
521
+ const { oasDocument, documentObject } = this.protocol;
522
+ const [first, second, , index] = documentTrail.stackTrail;
523
+ const prefix = consumer.stackTrail.slice(0, consumer.stackTrail.length - documentTrail.stackTrail.length);
524
+ const items = first === 'paths'
525
+ ? documentObject.paths
526
+ : 'webhooks' in documentObject
527
+ ? documentObject.webhooks
528
+ : undefined;
529
+ const rawPathItem = (0, isPlainObject_js_1.isPlainObject)(items) ? items[second] : undefined;
530
+ const rawEntries = (0, isPlainObject_js_1.isPlainObject)(rawPathItem) && Array.isArray(rawPathItem.parameters)
531
+ ? rawPathItem.parameters
532
+ : [];
533
+ const rawEntry = rawEntries[Number(index)];
534
+ const entryRef = (0, isPlainObject_js_1.isPlainObject)(rawEntry) && typeof rawEntry.$ref === 'string' ? rawEntry.$ref : undefined;
535
+ const nameAndIn = (0, pathParameters_js_1.toNameAndIn)(entryRef === undefined ? rawEntry : __classPrivateFieldGet(this, _ParseContext_instances, "m", _ParseContext_toRawComponentParameter).call(this, entryRef));
536
+ const broken = [{ location: documentTrail.toString(), message: '', ...nameAndIn }];
537
+ const operations = first === 'paths'
538
+ ? oasDocument.operations.filter(({ path }) => path === second)
539
+ : oasDocument.webhooks.filter(({ name }) => name === second);
540
+ const removedLocations = operations.flatMap(({ method, pathItem }) => {
541
+ const rawOperation = (0, isPlainObject_js_1.isPlainObject)(rawPathItem) ? rawPathItem[method] : undefined;
542
+ if ((0, pathParameters_js_1.toApplyingBrokenParameter)({ broken, operation: rawOperation }) === undefined) {
543
+ if (pathItem?.parameters) {
544
+ pathItem.parameters = pathItem.parameters.filter(parameter => parameter.isRef()
545
+ ? parameter.$ref !== entryRef
546
+ : entryRef !== undefined ||
547
+ parameter.name !== nameAndIn.name ||
548
+ parameter.location !== nameAndIn.in);
549
+ }
550
+ return [];
551
+ }
552
+ return oasDocument.removeItem(new StackTrail_js_1.StackTrail([first, second, method])) === undefined
553
+ ? []
554
+ : [new StackTrail_js_1.StackTrail([...prefix, first, second, method]).toString()];
555
+ });
556
+ return removedLocations;
557
+ }, _ParseContext_toRawComponentParameter = function _ParseContext_toRawComponentParameter($ref) {
558
+ if (this.protocol.type !== 'oas') {
559
+ return undefined;
560
+ }
561
+ const match = /^#\/components\/parameters\/(.+)$/.exec($ref);
562
+ const parameters = this.protocol.documentObject.components?.parameters;
563
+ return match && (0, isPlainObject_js_1.isPlainObject)(parameters) ? parameters[match[1]] : undefined;
564
+ }, _ParseContext_logDependencyIssue = function _ParseContext_logDependencyIssue({ location, refKey, rootCause }) {
565
+ const { error } = rootCause;
566
+ const errorMessage = error instanceof Error ? error.message : String(error);
567
+ const at = rootCause.location === undefined ? '' : ` at '${rootCause.location}'`;
568
+ const message = `Depends on '${refKey}', removed because of the error${at}: ${errorMessage}`;
569
+ switch (this.protocol.type) {
570
+ case 'oas':
571
+ this.issues.push({
572
+ protocol: 'oas',
573
+ level: 'error',
574
+ type: 'INVALID_DEPENDENCY_REF',
575
+ location,
576
+ message,
577
+ cause: error
578
+ });
579
+ break;
580
+ case 'gql':
581
+ this.issues.push({
582
+ protocol: 'gql',
583
+ level: 'error',
584
+ type: 'INVALID_DEPENDENCY_REF',
585
+ location,
586
+ message,
587
+ cause: error
588
+ });
589
+ break;
590
+ default: {
591
+ const _exhaustive = this.protocol;
592
+ throw new Error(`Unhandled protocol type: ${JSON.stringify(_exhaustive)}`);
593
+ }
594
+ }
595
+ }, _ParseContext_toDocumentTrail = function _ParseContext_toDocumentTrail(stackTrail) {
596
+ const frames = stackTrail.stackTrail;
597
+ const rootFrames = __classPrivateFieldGet(this, _ParseContext_rootFrames, "f");
598
+ const startsWithRoot = rootFrames.length > 0 &&
599
+ frames.length >= rootFrames.length &&
600
+ rootFrames.every((frame, index) => frames[index] === frame);
601
+ return startsWithRoot ? new StackTrail_js_1.StackTrail(frames.slice(rootFrames.length)) : stackTrail;
602
+ };