@skmtc/core 0.35.3 → 0.36.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.
@@ -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,9 +1,15 @@
1
+ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
2
+ if (kind === "m") throw new TypeError("Private method is not writable");
3
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
4
+ 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");
5
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
6
+ };
1
7
  var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
2
8
  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
3
9
  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");
4
10
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
5
11
  };
6
- var _ParseContext_refConsumers, _ParseContext_refErrors;
12
+ var _ParseContext_instances, _ParseContext_refConsumers, _ParseContext_refErrors, _ParseContext_rootFrames, _ParseContext_removeComponent, _ParseContext_removeConsumer, _ParseContext_removePathParameterConsumer, _ParseContext_toRawComponentParameter, _ParseContext_logDependencyIssue, _ParseContext_toDocumentTrail;
7
13
  /**
8
14
  * Unified parse context for both OAS and GraphQL inputs.
9
15
  *
@@ -18,12 +24,8 @@ var _ParseContext_refConsumers, _ParseContext_refErrors;
18
24
  * `logSkippedFields` with a pre-computed `location` string) accepts a
19
25
  * raw string. Both funnel into the shared {@link ParseContext.logIssueAt}.
20
26
  *
21
- * `removeErroredItems` is universal but its body dispatches on
22
- * `protocol.type` — the cleanup step is document-shaped. The GQL branch
23
- * is a no-op stub today; the infrastructure (the `#refConsumers` /
24
- * `#refErrors` maps, `registerRef` / `registerRefError`) is in place
25
- * for GQL parsers to populate when type-reference invalidation is
26
- * needed.
27
+ * `removeErroredItems` is universal; the removal it runs dispatches on
28
+ * `protocol.type` because the cleanup step is document-shaped.
27
29
  */
28
30
  import "../_dnt.polyfills.js";
29
31
  import { buildSchema } from 'graphql';
@@ -36,8 +38,11 @@ import { GqlRegistry } from '../gql/registry/GqlRegistry.js';
36
38
  import { GqlDocument } from '../gql/document/GqlDocument.js';
37
39
  import { parseGqlDocument } from '../gql/document/parseGqlDocument.js';
38
40
  import { StackTrail } from './StackTrail.js';
41
+ import { isPlainObject } from '../parse/isPlainObject.js';
42
+ import { toApplyingBrokenParameter, toNameAndIn } from '../parse/pathParameters.js';
39
43
  export class ParseContext {
40
44
  constructor({ input, logger, silent = true, options }) {
45
+ _ParseContext_instances.add(this);
41
46
  Object.defineProperty(this, "issues", {
42
47
  enumerable: true,
43
48
  configurable: true,
@@ -78,7 +83,19 @@ export class ParseContext {
78
83
  // encounter references. OAS uses `$ref` strings as keys; GQL would
79
84
  // use type names. The maps don't care about the encoding.
80
85
  _ParseContext_refConsumers.set(this, new Map());
81
- _ParseContext_refErrors.set(this, new Map());
86
+ _ParseContext_refErrors.set(this, new Map()
87
+ /**
88
+ * Frames of the trail `parse()` was called with (`[traceId, spanId,
89
+ * 'parse']` through `toArtifacts`). Every trail built during the walk
90
+ * starts with them; `#toDocumentTrail` strips them.
91
+ */
92
+ );
93
+ /**
94
+ * Frames of the trail `parse()` was called with (`[traceId, spanId,
95
+ * 'parse']` through `toArtifacts`). Every trail built during the walk
96
+ * starts with them; `#toDocumentTrail` strips them.
97
+ */
98
+ _ParseContext_rootFrames.set(this, []);
82
99
  this.logger = logger;
83
100
  this.silent = silent;
84
101
  switch (input.type) {
@@ -175,11 +192,12 @@ export class ParseContext {
175
192
  }
176
193
  /**
177
194
  * Runs the protocol-appropriate parse step and returns the result
178
- * wrapped in {@link SkmtcParsedDocument}. `stackTrail` is required
179
- * for OAS (used by `toDocumentFieldsV3` for issue location tracking)
180
- * and ignored by GQL (which uses pre-computed schema addresses).
195
+ * wrapped in {@link SkmtcParsedDocument}. Both protocols walk under
196
+ * `stackTrail`, so issue locations start with its frames; pruning
197
+ * removes those frames before it reads a trail as a document address.
181
198
  */
182
199
  parse(stackTrail) {
200
+ __classPrivateFieldSet(this, _ParseContext_rootFrames, [...stackTrail.stackTrail], "f");
183
201
  switch (this.protocol.type) {
184
202
  case 'oas': {
185
203
  const oasState = this.protocol;
@@ -238,76 +256,40 @@ export class ParseContext {
238
256
  }
239
257
  }
240
258
  /**
241
- * Walks any registered ref errors and prunes their consumers from
242
- * the parsed document. Symmetric across protocols: OAS prunes via
243
- * `OasDocument.removeItem`, GQL via `GqlDocument.removeItem`. Each
244
- * pruned consumer yields an `INVALID_DEPENDENCY_REF` issue.
259
+ * Removes every item that depends on a ref with a registered error.
245
260
  *
246
- * Pruning is deliberately **single-level** — only the direct
247
- * consumers of a parse-errored schema are removed. Anything those
248
- * removals leave with a dangling reference is left in place: if a
249
- * generator never resolves it, it is harmless; if one does, that
250
- * single artifact fails at generate time and is isolated there. We
251
- * do not cascade transitively.
261
+ * OAS: a component with an error is removed, even when the error is in
262
+ * one of its properties. Each consumer of a removed component is removed
263
+ * too. A consumer that is itself a component (its trail starts
264
+ * `components:<bucket>:<name>`) has its own consumers removed next, at any
265
+ * depth. GraphQL removes the consuming field, union member or operation,
266
+ * which leaves no ref to follow.
252
267
  *
253
- * Known coarseness, intentionally left as-is for now: a `paths:P:M:…`
254
- * consumer trail resolves to the *whole operation*, so an operation
255
- * that references a broken schema is pruned even when the reference
256
- * is only through a response it does not generate from. A finer
257
- * design — don't prune operations for response-position refs and let
258
- * generate-time isolation handle the dangling ref — is deferred; the
259
- * single-level + generate-time-isolation contract above keeps the
260
- * dangling ref safe in the meantime.
268
+ * Each removed consumer yields one `INVALID_DEPENDENCY_REF` at its
269
+ * location. The message names the ref it depends on and the error that
270
+ * started the removal; that error is the `cause`.
271
+ *
272
+ * A `paths:P:M:…` consumer trail resolves to the whole operation, so an
273
+ * operation is removed even when the ref is only in a response it does
274
+ * not generate from.
261
275
  */
262
276
  removeErroredItems() {
263
- switch (this.protocol.type) {
264
- case 'oas': {
265
- const oasState = this.protocol;
266
- for (const [refKey, errors] of __classPrivateFieldGet(this, _ParseContext_refErrors, "f")) {
267
- for (const error of errors) {
268
- const consumers = __classPrivateFieldGet(this, _ParseContext_refConsumers, "f").get(refKey) ?? [];
269
- for (const stackTrail of consumers) {
270
- const removed = oasState.oasDocument.removeItem(stackTrail);
271
- if (removed) {
272
- this.issues.push({
273
- protocol: 'oas',
274
- level: 'error',
275
- type: 'INVALID_DEPENDENCY_REF',
276
- location: stackTrail.toString(),
277
- message: error instanceof Error ? error.message : String(error),
278
- cause: error
279
- });
280
- }
281
- }
282
- }
277
+ const pending = [...__classPrivateFieldGet(this, _ParseContext_refErrors, "f")].flatMap(([refKey, [rootCause]]) => rootCause === undefined ? [] : [{ refKey, rootCause }]);
278
+ pending.forEach(({ refKey }) => __classPrivateFieldGet(this, _ParseContext_instances, "m", _ParseContext_removeComponent).call(this, refKey));
279
+ // `pending` grows while it is walked: each removed component queues its own consumers.
280
+ for (const { refKey, rootCause } of pending) {
281
+ for (const consumer of __classPrivateFieldGet(this, _ParseContext_refConsumers, "f").get(refKey) ?? []) {
282
+ const documentTrail = __classPrivateFieldGet(this, _ParseContext_instances, "m", _ParseContext_toDocumentTrail).call(this, consumer);
283
+ const removedLocations = __classPrivateFieldGet(this, _ParseContext_instances, "m", _ParseContext_removeConsumer).call(this, consumer, documentTrail);
284
+ removedLocations.forEach(location => __classPrivateFieldGet(this, _ParseContext_instances, "m", _ParseContext_logDependencyIssue).call(this, { location, refKey, rootCause }));
285
+ // A removed consumer that is a component has consumers of its own.
286
+ // `removeItem` finds a component only once, so each is queued once and a cycle ends.
287
+ const removedRefKey = this.protocol.type === 'oas' && removedLocations.length > 0
288
+ ? documentTrail.toStackRef()
289
+ : undefined;
290
+ if (removedRefKey !== undefined) {
291
+ pending.push({ refKey: removedRefKey, rootCause });
283
292
  }
284
- break;
285
- }
286
- case 'gql': {
287
- const gqlState = this.protocol;
288
- for (const [refKey, errors] of __classPrivateFieldGet(this, _ParseContext_refErrors, "f")) {
289
- for (const error of errors) {
290
- const consumers = __classPrivateFieldGet(this, _ParseContext_refConsumers, "f").get(refKey) ?? [];
291
- for (const stackTrail of consumers) {
292
- const removed = gqlState.gqlDocument.removeItem(stackTrail);
293
- if (removed) {
294
- this.issues.push({
295
- protocol: 'gql',
296
- level: 'error',
297
- type: 'INVALID_DEPENDENCY_REF',
298
- location: stackTrail.toString(),
299
- message: error instanceof Error ? error.message : String(error),
300
- cause: error
301
- });
302
- }
303
- }
304
- }
305
- }
306
- break;
307
- }
308
- default: {
309
- const _exhaustive = this.protocol;
310
- throw new Error(`Unhandled protocol type: ${JSON.stringify(_exhaustive)}`);
311
293
  }
312
294
  }
313
295
  }
@@ -354,17 +336,19 @@ export class ParseContext {
354
336
  * target of a `$ref` (or type reference) fails to parse. `undefined`
355
337
  * `refKey` is a deliberate no-op: callers may pass the result of
356
338
  * `StackTrail.toStackRef()` directly, which is `undefined` for
357
- * non-component stack trails.
339
+ * non-component stack trails. `location` is where the error was logged;
340
+ * each `INVALID_DEPENDENCY_REF` it causes names it.
358
341
  */
359
- registerRefError(error, refKey) {
342
+ registerRefError(error, refKey, location) {
360
343
  if (!refKey)
361
344
  return;
345
+ const refError = { error, location };
362
346
  const existing = __classPrivateFieldGet(this, _ParseContext_refErrors, "f").get(refKey);
363
347
  if (existing) {
364
- existing.push(error);
348
+ existing.push(refError);
365
349
  }
366
350
  else {
367
- __classPrivateFieldGet(this, _ParseContext_refErrors, "f").set(refKey, [error]);
351
+ __classPrivateFieldGet(this, _ParseContext_refErrors, "f").set(refKey, [refError]);
368
352
  }
369
353
  }
370
354
  /**
@@ -416,7 +400,7 @@ export class ParseContext {
416
400
  // points at. No-op for non-component trails (and for GQL
417
401
  // trails) because `toStackRef` returns `undefined` and
418
402
  // `registerRefError` ignores undefined refs.
419
- this.registerRefError(issue.cause ?? issue.message, stackTrail.toStackRef());
403
+ this.registerRefError(issue.cause ?? issue.message, __classPrivateFieldGet(this, _ParseContext_instances, "m", _ParseContext_toDocumentTrail).call(this, stackTrail).toStackRef(), location);
420
404
  this.logIssueAt({
421
405
  protocol,
422
406
  level: 'error',
@@ -498,4 +482,117 @@ export class ParseContext {
498
482
  });
499
483
  }
500
484
  }
501
- _ParseContext_refConsumers = new WeakMap(), _ParseContext_refErrors = new WeakMap();
485
+ _ParseContext_refConsumers = new WeakMap(), _ParseContext_refErrors = new WeakMap(), _ParseContext_rootFrames = new WeakMap(), _ParseContext_instances = new WeakSet(), _ParseContext_removeComponent = function _ParseContext_removeComponent(refKey) {
486
+ if (this.protocol.type !== 'oas') {
487
+ return;
488
+ }
489
+ const match = /^#\/components\/([^/]+)\/(.+)$/.exec(refKey);
490
+ if (match) {
491
+ this.protocol.oasDocument.removeItem(new StackTrail(['components', match[1], match[2]]));
492
+ }
493
+ }, _ParseContext_removeConsumer = function _ParseContext_removeConsumer(consumer, documentTrail) {
494
+ switch (this.protocol.type) {
495
+ case 'oas': {
496
+ const [first, , third] = documentTrail.stackTrail;
497
+ if ((first === 'paths' || first === 'webhooks') && third === 'parameters') {
498
+ return __classPrivateFieldGet(this, _ParseContext_instances, "m", _ParseContext_removePathParameterConsumer).call(this, consumer, documentTrail);
499
+ }
500
+ return this.protocol.oasDocument.removeItem(documentTrail) === undefined
501
+ ? []
502
+ : [consumer.toString()];
503
+ }
504
+ case 'gql':
505
+ return this.protocol.gqlDocument.removeItem(documentTrail) === undefined
506
+ ? []
507
+ : [consumer.toString()];
508
+ default: {
509
+ const _exhaustive = this.protocol;
510
+ throw new Error(`Unhandled protocol type: ${JSON.stringify(_exhaustive)}`);
511
+ }
512
+ }
513
+ }, _ParseContext_removePathParameterConsumer = function _ParseContext_removePathParameterConsumer(consumer, documentTrail) {
514
+ if (this.protocol.type !== 'oas') {
515
+ return [];
516
+ }
517
+ const { oasDocument, documentObject } = this.protocol;
518
+ const [first, second, , index] = documentTrail.stackTrail;
519
+ const prefix = consumer.stackTrail.slice(0, consumer.stackTrail.length - documentTrail.stackTrail.length);
520
+ const items = first === 'paths'
521
+ ? documentObject.paths
522
+ : 'webhooks' in documentObject
523
+ ? documentObject.webhooks
524
+ : undefined;
525
+ const rawPathItem = isPlainObject(items) ? items[second] : undefined;
526
+ const rawEntries = isPlainObject(rawPathItem) && Array.isArray(rawPathItem.parameters)
527
+ ? rawPathItem.parameters
528
+ : [];
529
+ const rawEntry = rawEntries[Number(index)];
530
+ const entryRef = isPlainObject(rawEntry) && typeof rawEntry.$ref === 'string' ? rawEntry.$ref : undefined;
531
+ const nameAndIn = toNameAndIn(entryRef === undefined ? rawEntry : __classPrivateFieldGet(this, _ParseContext_instances, "m", _ParseContext_toRawComponentParameter).call(this, entryRef));
532
+ const broken = [{ location: documentTrail.toString(), message: '', ...nameAndIn }];
533
+ const operations = first === 'paths'
534
+ ? oasDocument.operations.filter(({ path }) => path === second)
535
+ : oasDocument.webhooks.filter(({ name }) => name === second);
536
+ const removedLocations = operations.flatMap(({ method, pathItem }) => {
537
+ const rawOperation = isPlainObject(rawPathItem) ? rawPathItem[method] : undefined;
538
+ if (toApplyingBrokenParameter({ broken, operation: rawOperation }) === undefined) {
539
+ if (pathItem?.parameters) {
540
+ pathItem.parameters = pathItem.parameters.filter(parameter => parameter.isRef()
541
+ ? parameter.$ref !== entryRef
542
+ : entryRef !== undefined ||
543
+ parameter.name !== nameAndIn.name ||
544
+ parameter.location !== nameAndIn.in);
545
+ }
546
+ return [];
547
+ }
548
+ return oasDocument.removeItem(new StackTrail([first, second, method])) === undefined
549
+ ? []
550
+ : [new StackTrail([...prefix, first, second, method]).toString()];
551
+ });
552
+ return removedLocations;
553
+ }, _ParseContext_toRawComponentParameter = function _ParseContext_toRawComponentParameter($ref) {
554
+ if (this.protocol.type !== 'oas') {
555
+ return undefined;
556
+ }
557
+ const match = /^#\/components\/parameters\/(.+)$/.exec($ref);
558
+ const parameters = this.protocol.documentObject.components?.parameters;
559
+ return match && isPlainObject(parameters) ? parameters[match[1]] : undefined;
560
+ }, _ParseContext_logDependencyIssue = function _ParseContext_logDependencyIssue({ location, refKey, rootCause }) {
561
+ const { error } = rootCause;
562
+ const errorMessage = error instanceof Error ? error.message : String(error);
563
+ const at = rootCause.location === undefined ? '' : ` at '${rootCause.location}'`;
564
+ const message = `Depends on '${refKey}', removed because of the error${at}: ${errorMessage}`;
565
+ switch (this.protocol.type) {
566
+ case 'oas':
567
+ this.issues.push({
568
+ protocol: 'oas',
569
+ level: 'error',
570
+ type: 'INVALID_DEPENDENCY_REF',
571
+ location,
572
+ message,
573
+ cause: error
574
+ });
575
+ break;
576
+ case 'gql':
577
+ this.issues.push({
578
+ protocol: 'gql',
579
+ level: 'error',
580
+ type: 'INVALID_DEPENDENCY_REF',
581
+ location,
582
+ message,
583
+ cause: error
584
+ });
585
+ break;
586
+ default: {
587
+ const _exhaustive = this.protocol;
588
+ throw new Error(`Unhandled protocol type: ${JSON.stringify(_exhaustive)}`);
589
+ }
590
+ }
591
+ }, _ParseContext_toDocumentTrail = function _ParseContext_toDocumentTrail(stackTrail) {
592
+ const frames = stackTrail.stackTrail;
593
+ const rootFrames = __classPrivateFieldGet(this, _ParseContext_rootFrames, "f");
594
+ const startsWithRoot = rootFrames.length > 0 &&
595
+ frames.length >= rootFrames.length &&
596
+ rootFrames.every((frame, index) => frames[index] === frame);
597
+ return startsWithRoot ? new StackTrail(frames.slice(rootFrames.length)) : stackTrail;
598
+ };
@@ -35,10 +35,10 @@ export const tryParseAt = ({ stackTrail, key, context, type, parent, refKey, fn
35
35
  }
36
36
  catch (error) {
37
37
  const normalized = error instanceof Error ? error : new Error(String(error));
38
- if (refKey !== undefined) {
39
- context.registerRefError(error, refKey);
40
- }
41
38
  stackTrail.trace(key, childStack => {
39
+ if (refKey !== undefined) {
40
+ context.registerRefError(error, refKey, childStack.toString());
41
+ }
42
42
  context.logIssueNoKey({
43
43
  level: 'error',
44
44
  stackTrail: childStack,
@@ -9,7 +9,7 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
9
9
  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");
10
10
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11
11
  };
12
- var _GqlDocument_fields;
12
+ var _GqlDocument_fields, _GqlDocument_parseTimeMembers;
13
13
  import { OasObject } from '../../oas/object/Object.js';
14
14
  import { OasUnion } from '../../oas/union/Union.js';
15
15
  /**
@@ -52,6 +52,15 @@ export class GqlDocument {
52
52
  });
53
53
  /** @internal Private fields storage — set after parsing. */
54
54
  _GqlDocument_fields.set(this, void 0);
55
+ /** Members of each union as they were before `removeItem` first removed one. */
56
+ _GqlDocument_parseTimeMembers.set(this, new WeakMap()
57
+ /**
58
+ * Creates a new GqlDocument instance.
59
+ *
60
+ * The document is typically created without fields and populated later
61
+ * during parsing. See the class-level docstring for why.
62
+ */
63
+ );
55
64
  __classPrivateFieldSet(this, _GqlDocument_fields, fields, "f");
56
65
  }
57
66
  /**
@@ -130,7 +139,8 @@ export class GqlDocument {
130
139
  // Case 1: root-field operation removal.
131
140
  const isRootType = first === rootTypes.query || first === rootTypes.mutation || first === rootTypes.subscription;
132
141
  if (isRootType) {
133
- const index = operations.findIndex(op => op.fieldName === second);
142
+ // Query and Mutation can share a field name: match the root type too.
143
+ const index = operations.findIndex(op => op.fieldName === second && rootTypes[op.rootKind] === first);
134
144
  if (index === -1)
135
145
  return undefined;
136
146
  const [removed] = operations.splice(index, 1);
@@ -140,10 +150,16 @@ export class GqlDocument {
140
150
  if (second === 'members' && typeof third === 'string') {
141
151
  const parent = registry.schemas[first];
142
152
  if (parent instanceof OasUnion) {
143
- const idx = Number.parseInt(third, 10);
144
- if (!Number.isFinite(idx) || idx < 0 || idx >= parent.members.length)
153
+ // The index is the member's position at parse time. Look the member up
154
+ // in the list as it was before the first removal, so an earlier
155
+ // removal does not shift it.
156
+ const parseTimeMembers = __classPrivateFieldGet(this, _GqlDocument_parseTimeMembers, "f").get(parent) ?? [...parent.members];
157
+ __classPrivateFieldGet(this, _GqlDocument_parseTimeMembers, "f").set(parent, parseTimeMembers);
158
+ const member = parseTimeMembers[Number.parseInt(third, 10)];
159
+ const index = member === undefined ? -1 : parent.members.indexOf(member);
160
+ if (index === -1)
145
161
  return undefined;
146
- const [removed] = parent.members.splice(idx, 1);
162
+ const [removed] = parent.members.splice(index, 1);
147
163
  return removed;
148
164
  }
149
165
  return undefined;
@@ -167,4 +183,4 @@ export class GqlDocument {
167
183
  return undefined;
168
184
  }
169
185
  }
170
- _GqlDocument_fields = new WeakMap();
186
+ _GqlDocument_fields = new WeakMap(), _GqlDocument_parseTimeMembers = new WeakMap();
@@ -136,9 +136,11 @@ const addNamedType = ({ name, type, stackTrail, context, synthesizeInterfaceUnio
136
136
  // `refKey: name` (the type's own name, not `refName`) preserves the
137
137
  // prior behavior where an interface-union failure marks the base
138
138
  // type as errored so dependents of either form get pruned together.
139
+ // `key: refName` traces the synthesized interface union under its own
140
+ // registered name, so its member trails name the union.
139
141
  const value = tryParseAt({
140
142
  stackTrail,
141
- key: name,
143
+ key: refName,
142
144
  context,
143
145
  type: 'INVALID_TYPE_DEFINITION',
144
146
  parent: type,
@@ -36,6 +36,8 @@ export type ComponentsFields = {
36
36
  /** Custom extension fields (x-* properties) */
37
37
  extensionFields?: Record<string, unknown>;
38
38
  };
39
+ /** One entry of any {@link ComponentsFields} bucket. */
40
+ export type ComponentsEntry = OasSchema | OasRef<'schema'> | OasResponse | OasRef<'response'> | OasParameter | OasRef<'parameter'> | OasExample | OasRef<'example'> | OasRequestBody | OasRef<'requestBody'> | OasHeader | OasRef<'header'> | OasSecurityScheme | OasRef<'securityScheme'> | OasLink | OasRef<'link'>;
39
41
  /**
40
42
  * Represents the OpenAPI Components Object in the SKMTC OAS processing system.
41
43
  *
@@ -285,6 +287,14 @@ export declare class OasComponents {
285
287
  * ```
286
288
  */
287
289
  removeSchema(refName: RefName): OasSchema | OasRef<'schema'>;
290
+ /**
291
+ * Removes the entry `refName` from the `bucket` record (`schemas`,
292
+ * `requestBodies`, `headers`, …) and returns it.
293
+ *
294
+ * Returns `undefined` when the bucket has no such entry, and for a bucket
295
+ * outside {@link componentsKeys}.
296
+ */
297
+ removeEntry(bucket: string, refName: RefName): ComponentsEntry | undefined;
288
298
  /** Record holding re-usable {@link OasResponse} objects or Refs */
289
299
  get responses(): Record<RefName, OasResponse | OasRef<'response'>> | undefined;
290
300
  /** Record holding re-usable {@link OasParameter} objects or Refs */
@@ -24,6 +24,16 @@ export const componentsKeys = [
24
24
  'securitySchemes',
25
25
  'links'
26
26
  ];
27
+ /** Copy of `record` without `name`, and the value it held. */
28
+ const withoutEntry = (record, name) => {
29
+ if (!record || !Object.hasOwn(record, name)) {
30
+ return { removed: undefined, rest: record };
31
+ }
32
+ const rest = { ...record };
33
+ const removed = rest[name];
34
+ delete rest[name];
35
+ return { removed, rest };
36
+ };
27
37
  /**
28
38
  * Represents the OpenAPI Components Object in the SKMTC OAS processing system.
29
39
  *
@@ -289,6 +299,60 @@ export class OasComponents {
289
299
  __classPrivateFieldGet(this, _OasComponents_fields, "f").schemas = rest;
290
300
  return removed;
291
301
  }
302
+ /**
303
+ * Removes the entry `refName` from the `bucket` record (`schemas`,
304
+ * `requestBodies`, `headers`, …) and returns it.
305
+ *
306
+ * Returns `undefined` when the bucket has no such entry, and for a bucket
307
+ * outside {@link componentsKeys}.
308
+ */
309
+ removeEntry(bucket, refName) {
310
+ const fields = __classPrivateFieldGet(this, _OasComponents_fields, "f");
311
+ switch (bucket) {
312
+ case 'schemas': {
313
+ const { removed, rest } = withoutEntry(fields.schemas, refName);
314
+ fields.schemas = rest;
315
+ return removed;
316
+ }
317
+ case 'responses': {
318
+ const { removed, rest } = withoutEntry(fields.responses, refName);
319
+ fields.responses = rest;
320
+ return removed;
321
+ }
322
+ case 'parameters': {
323
+ const { removed, rest } = withoutEntry(fields.parameters, refName);
324
+ fields.parameters = rest;
325
+ return removed;
326
+ }
327
+ case 'examples': {
328
+ const { removed, rest } = withoutEntry(fields.examples, refName);
329
+ fields.examples = rest;
330
+ return removed;
331
+ }
332
+ case 'requestBodies': {
333
+ const { removed, rest } = withoutEntry(fields.requestBodies, refName);
334
+ fields.requestBodies = rest;
335
+ return removed;
336
+ }
337
+ case 'headers': {
338
+ const { removed, rest } = withoutEntry(fields.headers, refName);
339
+ fields.headers = rest;
340
+ return removed;
341
+ }
342
+ case 'securitySchemes': {
343
+ const { removed, rest } = withoutEntry(fields.securitySchemes, refName);
344
+ fields.securitySchemes = rest;
345
+ return removed;
346
+ }
347
+ case 'links': {
348
+ const { removed, rest } = withoutEntry(fields.links, refName);
349
+ fields.links = rest;
350
+ return removed;
351
+ }
352
+ default:
353
+ return undefined;
354
+ }
355
+ }
292
356
  /** Record holding re-usable {@link OasResponse} objects or Refs */
293
357
  get responses() {
294
358
  return __classPrivateFieldGet(this, _OasComponents_fields, "f").responses;