@skmtc/core 0.35.1 → 0.35.3

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 (75) hide show
  1. package/esm/context/StackTrail.js +3 -13
  2. package/esm/context/documentTrail.d.ts +17 -0
  3. package/esm/context/documentTrail.js +28 -0
  4. package/esm/parse/isPlainObject.d.ts +2 -0
  5. package/esm/parse/isPlainObject.js +2 -0
  6. package/esm/parse/pathParameters.d.ts +57 -0
  7. package/esm/parse/pathParameters.js +138 -0
  8. package/esm/parse/securityRequirements.d.ts +63 -0
  9. package/esm/parse/securityRequirements.js +128 -0
  10. package/esm/parse/toComponentEntries.js +1 -2
  11. package/esm/parse/v3-0/document/toDocumentFieldsV3.js +21 -7
  12. package/esm/parse/v3-0/operation/toOperationsV3.js +7 -1
  13. package/esm/parse/v3-0/parameter/toParameterV3.d.ts +7 -0
  14. package/esm/parse/v3-0/parameter/toParameterV3.js +19 -11
  15. package/esm/parse/v3-0/pathItem/toPathItemV3.d.ts +7 -1
  16. package/esm/parse/v3-0/pathItem/toPathItemV3.js +5 -3
  17. package/esm/parse/v3-0/securityRequirement/toSecurityRequirement.d.ts +2 -1
  18. package/esm/parse/v3-0/securityRequirement/toSecurityRequirement.js +2 -4
  19. package/esm/parse/v3-0/webhook/toWebhooksV3.js +7 -1
  20. package/esm/parse/v3-1/document/toDocumentFieldsV3.js +21 -7
  21. package/esm/parse/v3-1/operation/toOperationsV3.js +7 -1
  22. package/esm/parse/v3-1/parameter/toParameterV3.d.ts +7 -0
  23. package/esm/parse/v3-1/parameter/toParameterV3.js +19 -11
  24. package/esm/parse/v3-1/pathItem/toPathItemV3.d.ts +7 -1
  25. package/esm/parse/v3-1/pathItem/toPathItemV3.js +5 -3
  26. package/esm/parse/v3-1/securityRequirement/toSecurityRequirement.d.ts +2 -1
  27. package/esm/parse/v3-1/securityRequirement/toSecurityRequirement.js +2 -4
  28. package/esm/parse/v3-1/webhook/toWebhooksV3.js +7 -1
  29. package/esm/parse/v3-2/document/toDocumentFieldsV3.js +21 -7
  30. package/esm/parse/v3-2/operation/toOperationsV3.js +11 -10
  31. package/esm/parse/v3-2/parameter/toParameterV3.d.ts +7 -0
  32. package/esm/parse/v3-2/parameter/toParameterV3.js +30 -24
  33. package/esm/parse/v3-2/pathItem/toPathItemV3.d.ts +6 -13
  34. package/esm/parse/v3-2/pathItem/toPathItemV3.js +5 -30
  35. package/esm/parse/v3-2/securityRequirement/toSecurityRequirement.d.ts +2 -1
  36. package/esm/parse/v3-2/securityRequirement/toSecurityRequirement.js +2 -4
  37. package/esm/parse/v3-2/webhook/toWebhooksV3.js +11 -10
  38. package/package.json +1 -1
  39. package/script/context/StackTrail.js +3 -13
  40. package/script/context/documentTrail.d.ts +17 -0
  41. package/script/context/documentTrail.js +34 -0
  42. package/script/parse/isPlainObject.d.ts +2 -0
  43. package/script/parse/isPlainObject.js +4 -1
  44. package/script/parse/pathParameters.d.ts +57 -0
  45. package/script/parse/pathParameters.js +144 -0
  46. package/script/parse/securityRequirements.d.ts +63 -0
  47. package/script/parse/securityRequirements.js +134 -0
  48. package/script/parse/toComponentEntries.js +1 -2
  49. package/script/parse/v3-0/document/toDocumentFieldsV3.js +21 -7
  50. package/script/parse/v3-0/operation/toOperationsV3.js +7 -1
  51. package/script/parse/v3-0/parameter/toParameterV3.d.ts +7 -0
  52. package/script/parse/v3-0/parameter/toParameterV3.js +22 -13
  53. package/script/parse/v3-0/pathItem/toPathItemV3.d.ts +7 -1
  54. package/script/parse/v3-0/pathItem/toPathItemV3.js +4 -2
  55. package/script/parse/v3-0/securityRequirement/toSecurityRequirement.d.ts +2 -1
  56. package/script/parse/v3-0/securityRequirement/toSecurityRequirement.js +2 -4
  57. package/script/parse/v3-0/webhook/toWebhooksV3.js +7 -1
  58. package/script/parse/v3-1/document/toDocumentFieldsV3.js +21 -7
  59. package/script/parse/v3-1/operation/toOperationsV3.js +7 -1
  60. package/script/parse/v3-1/parameter/toParameterV3.d.ts +7 -0
  61. package/script/parse/v3-1/parameter/toParameterV3.js +22 -13
  62. package/script/parse/v3-1/pathItem/toPathItemV3.d.ts +7 -1
  63. package/script/parse/v3-1/pathItem/toPathItemV3.js +4 -2
  64. package/script/parse/v3-1/securityRequirement/toSecurityRequirement.d.ts +2 -1
  65. package/script/parse/v3-1/securityRequirement/toSecurityRequirement.js +2 -4
  66. package/script/parse/v3-1/webhook/toWebhooksV3.js +7 -1
  67. package/script/parse/v3-2/document/toDocumentFieldsV3.js +21 -7
  68. package/script/parse/v3-2/operation/toOperationsV3.js +10 -9
  69. package/script/parse/v3-2/parameter/toParameterV3.d.ts +7 -0
  70. package/script/parse/v3-2/parameter/toParameterV3.js +33 -26
  71. package/script/parse/v3-2/pathItem/toPathItemV3.d.ts +6 -13
  72. package/script/parse/v3-2/pathItem/toPathItemV3.js +5 -31
  73. package/script/parse/v3-2/securityRequirement/toSecurityRequirement.d.ts +2 -1
  74. package/script/parse/v3-2/securityRequirement/toSecurityRequirement.js +2 -4
  75. package/script/parse/v3-2/webhook/toWebhooksV3.js +10 -9
@@ -13,6 +13,7 @@ var _StackTrail_stack;
13
13
  import "../_dnt.polyfills.js";
14
14
  import { componentsKeys } from '../oas/components/Components.js';
15
15
  import { toJsonPointer } from '../types/JsonPointer.js';
16
+ import { toDocumentFrames, toTrailString } from './documentTrail.js';
16
17
  export class StackTrail {
17
18
  constructor(stack = []) {
18
19
  /** Internal stack of traversal frames */
@@ -211,15 +212,7 @@ export class StackTrail {
211
212
  * ```
212
213
  */
213
214
  toSchemaPointer() {
214
- // Phase frames seeded by `CoreContext.toArtifacts` (PhaseType plus the
215
- // `post-pass` trace). The operational phase always sits before any
216
- // document key, so the FIRST match is the boundary — a document key
217
- // that happens to share a phase name (e.g. a schema literally named
218
- // `parse`) appears later and is unaffected.
219
- const phaseFrames = new Set(['parse', 'generate', 'render', 'post-pass']);
220
- const phaseIndex = __classPrivateFieldGet(this, _StackTrail_stack, "f").findIndex(frame => phaseFrames.has(frame));
221
- const documentFrames = phaseIndex === -1 ? __classPrivateFieldGet(this, _StackTrail_stack, "f") : __classPrivateFieldGet(this, _StackTrail_stack, "f").slice(phaseIndex + 1);
222
- return toJsonPointer(documentFrames);
215
+ return toJsonPointer(toDocumentFrames(__classPrivateFieldGet(this, _StackTrail_stack, "f")));
223
216
  }
224
217
  toStackRef() {
225
218
  const [first, second, third] = this.stackTrail;
@@ -305,9 +298,7 @@ export class StackTrail {
305
298
  * ```
306
299
  */
307
300
  toString() {
308
- return __classPrivateFieldGet(this, _StackTrail_stack, "f")
309
- .map(frame => frame.replace(/[%:]/g, character => escapes[character]))
310
- .join(':');
301
+ return toTrailString(__classPrivateFieldGet(this, _StackTrail_stack, "f"));
311
302
  }
312
303
  /**
313
304
  * Reads a string written by {@link StackTrail.toString} back into a trail.
@@ -330,5 +321,4 @@ export class StackTrail {
330
321
  }
331
322
  }
332
323
  _StackTrail_stack = new WeakMap();
333
- const escapes = { '%': '%25', ':': '%3A' };
334
324
  const decodes = { '25': '%', '3A': ':' };
@@ -0,0 +1,17 @@
1
+ /** Joins trail frames with `:`, escaping `%` as `%25` and `:` as `%3A` inside a frame. */
2
+ export declare const toTrailString: (frames: string[]) => string;
3
+ /**
4
+ * The frames of a trail that address the input document: everything after
5
+ * the first phase frame, or every frame when there is no phase frame.
6
+ */
7
+ export declare const toDocumentFrames: (frames: string[]) => string[];
8
+ /**
9
+ * The document-relative trail in `StackTrail.toString` form.
10
+ *
11
+ * @example
12
+ * ```typescript
13
+ * toDocumentString(['trace-1', 'span-1', 'parse', 'paths', '/pets', 'parameters', '0'])
14
+ * // 'paths:/pets:parameters:0'
15
+ * ```
16
+ */
17
+ export declare const toDocumentString: (frames: string[]) => string;
@@ -0,0 +1,28 @@
1
+ const escapes = { '%': '%25', ':': '%3A' };
2
+ // Phase frames seeded by `CoreContext.toArtifacts` (PhaseType plus the
3
+ // `post-pass` trace).
4
+ const phaseFrames = new Set(['parse', 'generate', 'render', 'post-pass']);
5
+ /** Joins trail frames with `:`, escaping `%` as `%25` and `:` as `%3A` inside a frame. */
6
+ export const toTrailString = (frames) => frames.map(frame => frame.replace(/[%:]/g, character => escapes[character])).join(':');
7
+ /**
8
+ * The frames of a trail that address the input document: everything after
9
+ * the first phase frame, or every frame when there is no phase frame.
10
+ */
11
+ export const toDocumentFrames = (frames) => {
12
+ // The operational phase always sits before any document key, so the
13
+ // FIRST match is the boundary — a document key that happens to share a
14
+ // phase name (e.g. a schema literally named `parse`) appears later and
15
+ // is unaffected.
16
+ const phaseIndex = frames.findIndex(frame => phaseFrames.has(frame));
17
+ return phaseIndex === -1 ? frames : frames.slice(phaseIndex + 1);
18
+ };
19
+ /**
20
+ * The document-relative trail in `StackTrail.toString` form.
21
+ *
22
+ * @example
23
+ * ```typescript
24
+ * toDocumentString(['trace-1', 'span-1', 'parse', 'paths', '/pets', 'parameters', '0'])
25
+ * // 'paths:/pets:parameters:0'
26
+ * ```
27
+ */
28
+ export const toDocumentString = (frames) => toTrailString(toDocumentFrames(frames));
@@ -1,2 +1,4 @@
1
1
  /** A non-null object that is not an array. */
2
2
  export declare const isPlainObject: (value: unknown) => value is Record<string, unknown>;
3
+ /** Name the kind of a value for an error message: `null`, `an array`, or its `typeof`. */
4
+ export declare const toKind: (value: unknown) => string;
@@ -1,2 +1,4 @@
1
1
  /** A non-null object that is not an array. */
2
2
  export const isPlainObject = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
3
+ /** Name the kind of a value for an error message: `null`, `an array`, or its `typeof`. */
4
+ export const toKind = (value) => value === null ? 'null' : Array.isArray(value) ? 'an array' : typeof value;
@@ -0,0 +1,57 @@
1
+ import type { ParseContextType } from '../context/parseTypes.js';
2
+ import type { StackTrail } from '../context/StackTrail.js';
3
+ /**
4
+ * Reads a `parameters` field. `undefined` is no parameters. `{}` or `null`
5
+ * is read as no parameters with an `EMPTY_PARAMETER` warning at the
6
+ * field. Any other value that is not an array throws.
7
+ */
8
+ export declare const toParameterEntries: <Entry>({ parameters, stackTrail, context }: {
9
+ parameters: Entry[] | undefined;
10
+ /** Trail that ends in `parameters`. */
11
+ stackTrail: StackTrail;
12
+ context: ParseContextType;
13
+ }) => Entry[] | undefined;
14
+ /** A path-level parameter entry, or the whole field, that failed to parse. */
15
+ export type BrokenPathParameter = {
16
+ /** Document-relative trail of the entry, or of the `parameters` field when it is not an array. */
17
+ location: string;
18
+ /** Set only when the raw entry has string `name` and `in`. */
19
+ name?: string;
20
+ in?: string;
21
+ message: string;
22
+ };
23
+ export type PathParameterList<Parameter> = {
24
+ parameters: Parameter[] | undefined;
25
+ broken: BrokenPathParameter[];
26
+ };
27
+ export type ToPathParameterListArgs<Entry, Parameter> = {
28
+ parameters: Entry[] | undefined;
29
+ /** Trail that ends in `parameters`. */
30
+ stackTrail: StackTrail;
31
+ context: ParseContextType;
32
+ /** The tree's parser for one list entry, as used by `toParameterListV3`. */
33
+ toEntry: (args: {
34
+ parameter: Entry;
35
+ index: number;
36
+ }) => Parameter[];
37
+ };
38
+ /**
39
+ * Parses a path item's `parameters` without letting a throw escape. Each
40
+ * entry that fails logs one `INVALID_PARAMETER` error at its index and is
41
+ * returned in `broken`; a field that is not an array logs one at the field.
42
+ * The caller decides per operation which broken entries apply.
43
+ */
44
+ export declare const toPathParameterList: <Entry, Parameter>({ parameters, stackTrail, context, toEntry }: ToPathParameterListArgs<Entry, Parameter>) => PathParameterList<Parameter>;
45
+ /**
46
+ * True when a broken path-level parameter applies to the operation. Logs
47
+ * one `INVALID_OPERATION` error at the operation that names the first
48
+ * such entry.
49
+ */
50
+ export declare const isDroppedByPathParameter: ({ brokenParameters, operation, stackTrail, context }: {
51
+ brokenParameters: BrokenPathParameter[];
52
+ /** The raw operation object. */
53
+ operation: unknown;
54
+ /** Trail that ends in the operation's method. */
55
+ stackTrail: StackTrail;
56
+ context: ParseContextType;
57
+ }) => boolean;
@@ -0,0 +1,138 @@
1
+ import { isEmptyParameter } from './emptyParameter.js';
2
+ import { toDocumentString } from '../context/documentTrail.js';
3
+ /**
4
+ * Reads a `parameters` field. `undefined` is no parameters. `{}` or `null`
5
+ * is read as no parameters with an `EMPTY_PARAMETER` warning at the
6
+ * field. Any other value that is not an array throws.
7
+ */
8
+ export const toParameterEntries = ({ parameters, stackTrail, context }) => {
9
+ if (parameters === undefined) {
10
+ return undefined;
11
+ }
12
+ if (Array.isArray(parameters)) {
13
+ return parameters;
14
+ }
15
+ if (isEmptyParameter(parameters)) {
16
+ context.logIssueNoKey({
17
+ stackTrail,
18
+ parent: parameters,
19
+ level: 'warning',
20
+ type: 'EMPTY_PARAMETER',
21
+ message: 'Empty parameters field; read as no parameters'
22
+ });
23
+ return undefined;
24
+ }
25
+ throw new Error(`Expected parameters to be an array but received ${typeof parameters}`);
26
+ };
27
+ const toError = (error) => error instanceof Error ? error : new Error(String(error));
28
+ const toNameAndIn = (parameter) => {
29
+ if (typeof parameter === 'object' &&
30
+ parameter !== null &&
31
+ 'name' in parameter &&
32
+ 'in' in parameter &&
33
+ typeof parameter.name === 'string' &&
34
+ typeof parameter.in === 'string') {
35
+ return { name: parameter.name, in: parameter.in };
36
+ }
37
+ return {};
38
+ };
39
+ /**
40
+ * Parses a path item's `parameters` without letting a throw escape. Each
41
+ * entry that fails logs one `INVALID_PARAMETER` error at its index and is
42
+ * returned in `broken`; a field that is not an array logs one at the field.
43
+ * The caller decides per operation which broken entries apply.
44
+ */
45
+ export const toPathParameterList = ({ parameters, stackTrail, context, toEntry }) => {
46
+ const logBroken = (st, parent, error) => {
47
+ const normalized = toError(error);
48
+ context.logIssueNoKey({
49
+ level: 'error',
50
+ stackTrail: st,
51
+ parent,
52
+ message: normalized.message,
53
+ cause: normalized,
54
+ type: 'INVALID_PARAMETER'
55
+ });
56
+ return { location: toDocumentString(st.stackTrail), message: normalized.message };
57
+ };
58
+ const readEntries = () => {
59
+ try {
60
+ return { entries: toParameterEntries({ parameters, stackTrail, context }) };
61
+ }
62
+ catch (error) {
63
+ // A field that is not an array cannot be matched to an override.
64
+ return { broken: logBroken(stackTrail, parameters, error) };
65
+ }
66
+ };
67
+ const read = readEntries();
68
+ if ('broken' in read) {
69
+ return { parameters: undefined, broken: [read.broken] };
70
+ }
71
+ if (read.entries === undefined) {
72
+ return { parameters: undefined, broken: [] };
73
+ }
74
+ const results = read.entries.map((parameter, index) => {
75
+ try {
76
+ return { parsed: toEntry({ parameter, index }), broken: [] };
77
+ }
78
+ catch (error) {
79
+ return {
80
+ parsed: [],
81
+ broken: [
82
+ {
83
+ ...stackTrail.trace(`${index}`, st => logBroken(st, parameter, error)),
84
+ ...toNameAndIn(parameter)
85
+ }
86
+ ]
87
+ };
88
+ }
89
+ });
90
+ return {
91
+ parameters: results.flatMap(({ parsed }) => parsed),
92
+ broken: results.flatMap(({ broken }) => broken)
93
+ };
94
+ };
95
+ /**
96
+ * The first broken path-level parameter that applies to an operation. An
97
+ * entry applies unless it has a readable `name` and `in` and the
98
+ * operation's inline `parameters` hold the same pair, which overrides it.
99
+ * A `$ref` operation parameter cannot be resolved during parse, so it
100
+ * overrides nothing.
101
+ */
102
+ const toApplyingBrokenParameter = ({ broken, operation }) => {
103
+ if (broken.length === 0) {
104
+ return undefined;
105
+ }
106
+ const operationParameters = typeof operation === 'object' &&
107
+ operation !== null &&
108
+ 'parameters' in operation &&
109
+ Array.isArray(operation.parameters)
110
+ ? operation.parameters
111
+ : [];
112
+ const overrides = new Set(operationParameters.flatMap((parameter) => {
113
+ const { name, in: parameterIn } = toNameAndIn(parameter);
114
+ return name === undefined || parameterIn === undefined ? [] : [`${parameterIn}:${name}`];
115
+ }));
116
+ return broken.find(entry => entry.name === undefined ||
117
+ entry.in === undefined ||
118
+ !overrides.has(`${entry.in}:${entry.name}`));
119
+ };
120
+ /**
121
+ * True when a broken path-level parameter applies to the operation. Logs
122
+ * one `INVALID_OPERATION` error at the operation that names the first
123
+ * such entry.
124
+ */
125
+ export const isDroppedByPathParameter = ({ brokenParameters, operation, stackTrail, context }) => {
126
+ const broken = toApplyingBrokenParameter({ broken: brokenParameters, operation });
127
+ if (!broken) {
128
+ return false;
129
+ }
130
+ context.logIssueNoKey({
131
+ parent: operation,
132
+ level: 'error',
133
+ message: `Path-level parameter ${broken.location} failed to parse: ${broken.message}`,
134
+ stackTrail,
135
+ type: 'INVALID_OPERATION'
136
+ });
137
+ return true;
138
+ };
@@ -0,0 +1,63 @@
1
+ import type { ParseContextType } from '../context/parseTypes.js';
2
+ import type { StackTrail } from '../context/StackTrail.js';
3
+ import type { OasSecurityRequirement } from '../oas/securityRequirement/SecurityRequirement.js';
4
+ /**
5
+ * Check a `security` field before its requirements are parsed. Shared by
6
+ * the 3.0, 3.1 and 3.2 parsers.
7
+ *
8
+ * - Missing: returns `undefined`.
9
+ * - Not an array, or an entry that is not an object of scheme name to a
10
+ * list of string scopes: throws, so the operation is dropped as
11
+ * `INVALID_OPERATION`. At the root, {@link toSecurityCheck} catches it.
12
+ * - Otherwise: returns the checked requirement objects.
13
+ */
14
+ export declare const toSecurityRequirementObjects: (security: unknown) => Record<string, string[]>[] | undefined;
15
+ /** The document-level facts each operation's security is checked against. */
16
+ export type SecurityCheck = {
17
+ /** The parsed root `security`; `undefined` when absent or malformed. */
18
+ rootSecurity: OasSecurityRequirement[] | undefined;
19
+ /** Why the root `security` cannot be used, or `undefined` when it can. */
20
+ rootProblem: string | undefined;
21
+ /** Scheme names in the document's `components.securitySchemes`. */
22
+ declaredSchemes: string[];
23
+ /** Declared scheme names that failed to parse. */
24
+ failedSchemes: string[];
25
+ context: ParseContextType;
26
+ };
27
+ export type ToSecurityCheckArgs = {
28
+ /** Parses the root `security`; throws when it is malformed. */
29
+ parse: () => OasSecurityRequirement[] | undefined;
30
+ /** The raw `components.securitySchemes`. */
31
+ declared: Record<string, unknown> | undefined;
32
+ /** The parsed `components.securitySchemes`. */
33
+ parsed: Record<string, unknown> | undefined;
34
+ /** Trail that ends in the root `security` key. */
35
+ stackTrail: StackTrail;
36
+ context: ParseContextType;
37
+ };
38
+ /**
39
+ * Parse the document's root `security` and collect the scheme facts that
40
+ * {@link toOperationsWithValidSecurity} checks each operation against.
41
+ *
42
+ * A root `security` that is malformed, or that names a scheme that failed
43
+ * to parse or is not defined, logs one `INVALID_OPERATION` warning at
44
+ * `security` and sets `rootProblem`. The document then has no `security`,
45
+ * and the operations that inherit it are dropped.
46
+ */
47
+ export declare const toSecurityCheck: ({ parse, declared, parsed, stackTrail, context }: ToSecurityCheckArgs) => SecurityCheck;
48
+ type SecuredItem = {
49
+ security: OasSecurityRequirement[] | undefined;
50
+ stackTrail: StackTrail;
51
+ };
52
+ export type ToOperationsWithValidSecurityArgs<Item extends SecuredItem> = {
53
+ items: Item[];
54
+ check: SecurityCheck;
55
+ };
56
+ /**
57
+ * Drop each operation or webhook whose own `security` names a scheme that
58
+ * failed to parse or is not defined, or that has no `security` and
59
+ * inherits an unusable root. Each dropped item logs one `INVALID_OPERATION`
60
+ * error on its own trail. `security: []` inherits nothing and is kept.
61
+ */
62
+ export declare const toOperationsWithValidSecurity: <Item extends SecuredItem>({ items, check }: ToOperationsWithValidSecurityArgs<Item>) => Item[];
63
+ export {};
@@ -0,0 +1,128 @@
1
+ import { isPlainObject, toKind } from './isPlainObject.js';
2
+ const isScopeList = (value) => Array.isArray(value) && value.every((scope) => typeof scope === 'string');
3
+ const toRequirementObject = (requirement, index) => {
4
+ if (!isPlainObject(requirement)) {
5
+ throw new Error(`"security" entry ${index} must be a security requirement object, got ${toKind(requirement)}`);
6
+ }
7
+ return Object.fromEntries(Object.entries(requirement).map(([name, scopes]) => {
8
+ if (!isScopeList(scopes)) {
9
+ throw new Error(`"security" entry ${index} must map each scheme name to a list of scopes; '${name}' does not`);
10
+ }
11
+ return [name, scopes];
12
+ }));
13
+ };
14
+ /**
15
+ * Check a `security` field before its requirements are parsed. Shared by
16
+ * the 3.0, 3.1 and 3.2 parsers.
17
+ *
18
+ * - Missing: returns `undefined`.
19
+ * - Not an array, or an entry that is not an object of scheme name to a
20
+ * list of string scopes: throws, so the operation is dropped as
21
+ * `INVALID_OPERATION`. At the root, {@link toSecurityCheck} catches it.
22
+ * - Otherwise: returns the checked requirement objects.
23
+ */
24
+ export const toSecurityRequirementObjects = (security) => {
25
+ if (security === undefined) {
26
+ return undefined;
27
+ }
28
+ if (!Array.isArray(security)) {
29
+ throw new Error(`"security" must be a list of security requirement objects, got ${toKind(security)}`);
30
+ }
31
+ return security.map((requirement, index) => toRequirementObject(requirement, index));
32
+ };
33
+ // Valid scheme types that core does not parse yet. Such a scheme logs
34
+ // INVALID_SECURITY_SCHEME but is not counted as failed, so the operations
35
+ // that require it are kept, as before.
36
+ const unmodeledSchemeTypes = ['mutualTLS'];
37
+ const isUnmodeledScheme = (scheme) => isPlainObject(scheme) &&
38
+ typeof scheme.type === 'string' &&
39
+ unmodeledSchemeTypes.includes(scheme.type);
40
+ const quote = (names) => names.map(name => `'${name}'`).join(', ');
41
+ const toSchemeProblem = (names, reason) => {
42
+ const one = names.length === 1;
43
+ return `requires security ${one ? 'scheme' : 'schemes'} ${quote(names)}, which ${reason(one)}`;
44
+ };
45
+ /** One lowercase clause per kind of unusable scheme in `security`. */
46
+ const toSchemeProblems = (security, { declaredSchemes, failedSchemes }) => {
47
+ const names = [
48
+ ...new Set((security ?? []).flatMap(({ requirement }) => Object.keys(requirement)))
49
+ ];
50
+ const failed = names.filter(name => failedSchemes.includes(name));
51
+ const undefinedNames = names.filter(name => !declaredSchemes.includes(name));
52
+ return [
53
+ failed.length > 0 ? toSchemeProblem(failed, () => 'failed to parse') : undefined,
54
+ undefinedNames.length > 0
55
+ ? toSchemeProblem(undefinedNames, one => `${one ? 'is' : 'are'} not defined in components.securitySchemes`)
56
+ : undefined
57
+ ].filter(part => part !== undefined);
58
+ };
59
+ const capitalize = (text) => text.charAt(0).toUpperCase() + text.slice(1);
60
+ /**
61
+ * Parse the document's root `security` and collect the scheme facts that
62
+ * {@link toOperationsWithValidSecurity} checks each operation against.
63
+ *
64
+ * A root `security` that is malformed, or that names a scheme that failed
65
+ * to parse or is not defined, logs one `INVALID_OPERATION` warning at
66
+ * `security` and sets `rootProblem`. The document then has no `security`,
67
+ * and the operations that inherit it are dropped.
68
+ */
69
+ export const toSecurityCheck = ({ parse, declared, parsed, stackTrail, context }) => {
70
+ const declaredSchemes = Object.keys(declared ?? {});
71
+ const failedSchemes = declaredSchemes.filter(name => !Object.hasOwn(parsed ?? {}, name) && !isUnmodeledScheme(declared?.[name]));
72
+ const logRootProblem = (problem) => context.logIssueNoKey({
73
+ stackTrail,
74
+ parent: undefined,
75
+ level: 'warning',
76
+ type: 'INVALID_OPERATION',
77
+ message: `${problem}; root security is left out and operations that inherit it are dropped`
78
+ });
79
+ try {
80
+ const rootSecurity = parse();
81
+ const problems = toSchemeProblems(rootSecurity, { declaredSchemes, failedSchemes });
82
+ if (problems.length === 0) {
83
+ return { rootSecurity, rootProblem: undefined, declaredSchemes, failedSchemes, context };
84
+ }
85
+ logRootProblem(`Root security ${problems.join(' and ')}`);
86
+ return {
87
+ rootSecurity: undefined,
88
+ rootProblem: `Inherits root security, which ${problems.join(' and ')}`,
89
+ declaredSchemes,
90
+ failedSchemes,
91
+ context
92
+ };
93
+ }
94
+ catch (error) {
95
+ logRootProblem(error instanceof Error ? error.message : String(error));
96
+ return {
97
+ rootSecurity: undefined,
98
+ rootProblem: 'Inherits root security, which is not a list of security requirement objects',
99
+ declaredSchemes,
100
+ failedSchemes,
101
+ context
102
+ };
103
+ }
104
+ };
105
+ /**
106
+ * Drop each operation or webhook whose own `security` names a scheme that
107
+ * failed to parse or is not defined, or that has no `security` and
108
+ * inherits an unusable root. Each dropped item logs one `INVALID_OPERATION`
109
+ * error on its own trail. `security: []` inherits nothing and is kept.
110
+ */
111
+ export const toOperationsWithValidSecurity = ({ items, check }) => {
112
+ return items.filter(item => {
113
+ const message = item.security
114
+ ? toSchemeProblems(item.security, check).map(capitalize).join('. ') || undefined
115
+ : check.rootProblem;
116
+ if (message === undefined) {
117
+ return true;
118
+ }
119
+ check.context.logIssueNoKey({
120
+ stackTrail: item.stackTrail,
121
+ parent: undefined,
122
+ level: 'error',
123
+ type: 'INVALID_OPERATION',
124
+ message
125
+ });
126
+ return false;
127
+ });
128
+ };
@@ -1,5 +1,5 @@
1
1
  import { tryParseAt } from '../context/tryParseAt.js';
2
- import { isPlainObject } from './isPlainObject.js';
2
+ import { isPlainObject, toKind } from './isPlainObject.js';
3
3
  /**
4
4
  * Parse each entry of a `components` bucket inside its own `tryParseAt`
5
5
  * boundary. Shared by the 3.0, 3.1 and 3.2 parsers.
@@ -28,4 +28,3 @@ export const toComponentEntries = ({ entries, stackTrail, context, type, label,
28
28
  });
29
29
  return Object.fromEntries(parsedEntries);
30
30
  };
31
- const toKind = (value) => value === null ? 'null' : Array.isArray(value) ? 'an array' : typeof value;
@@ -7,6 +7,7 @@ import { toSpecificationExtensionsV3 } from '../specificationExtensions/toSpecif
7
7
  import { toOptionalServersV3 } from '../server/toServerV3.js';
8
8
  import { toSecurityRequirementsV3 } from '../securityRequirement/toSecurityRequirement.js';
9
9
  import { toExternalDocs } from '../externalDocs/toExternalDocs.js';
10
+ import { toOperationsWithValidSecurity, toSecurityCheck } from '../../securityRequirements.js';
10
11
  export const toDocumentFieldsV3 = ({ documentObject, stackTrail, context }) => {
11
12
  const { openapi, info, paths, components, tags, servers, security, externalDocs, webhooks, ...skipped } = documentObject;
12
13
  const extensionFields = toSpecificationExtensionsV3({
@@ -16,15 +17,28 @@ export const toDocumentFieldsV3 = ({ documentObject, stackTrail, context }) => {
16
17
  stackTrail,
17
18
  parentType: 'document'
18
19
  });
20
+ const parsedInfo = stackTrail.trace('info', st => toInfoV3({ info, stackTrail: st, context }));
21
+ const parsedServers = stackTrail.trace('servers', st => toOptionalServersV3({ servers, stackTrail: st, context }));
22
+ const parsedOperations = stackTrail.trace('paths', st => toOperationsV3({ paths, stackTrail: st, context }));
23
+ const parsedWebhooks = stackTrail.trace('webhooks', st => toWebhooksV3({ webhooks, stackTrail: st, context }));
24
+ const parsedComponents = stackTrail.trace('components', st => toComponentsV3({ components, stackTrail: st, context }));
25
+ const parsedTags = stackTrail.trace('tags', st => toTagsV3({ tags, stackTrail: st, context }));
26
+ const securityCheck = stackTrail.trace('security', st => toSecurityCheck({
27
+ parse: () => toSecurityRequirementsV3({ security, stackTrail: st, context }),
28
+ declared: components?.securitySchemes,
29
+ parsed: parsedComponents?.securitySchemes,
30
+ stackTrail: st,
31
+ context
32
+ }));
19
33
  return {
20
34
  openapi,
21
- info: stackTrail.trace('info', st => toInfoV3({ info, stackTrail: st, context })),
22
- servers: stackTrail.trace('servers', st => toOptionalServersV3({ servers, stackTrail: st, context })),
23
- operations: stackTrail.trace('paths', st => toOperationsV3({ paths, stackTrail: st, context })),
24
- webhooks: stackTrail.trace('webhooks', st => toWebhooksV3({ webhooks, stackTrail: st, context })),
25
- components: stackTrail.trace('components', st => toComponentsV3({ components, stackTrail: st, context })),
26
- tags: stackTrail.trace('tags', st => toTagsV3({ tags, stackTrail: st, context })),
27
- security: stackTrail.trace('security', st => toSecurityRequirementsV3({ security, stackTrail: st, context })),
35
+ info: parsedInfo,
36
+ servers: parsedServers,
37
+ operations: toOperationsWithValidSecurity({ items: parsedOperations, check: securityCheck }),
38
+ webhooks: toOperationsWithValidSecurity({ items: parsedWebhooks, check: securityCheck }),
39
+ components: parsedComponents,
40
+ tags: parsedTags,
41
+ security: securityCheck.rootSecurity,
28
42
  extensionFields,
29
43
  externalDocs: stackTrail.trace('externalDocs', st => toExternalDocs({ externalDocs, stackTrail: st, context }))
30
44
  };
@@ -9,6 +9,7 @@ import { toSecurityRequirementsV3 } from '../securityRequirement/toSecurityRequi
9
9
  import { isEmpty } from '../../../helpers/isEmpty.js';
10
10
  import { toExternalDocs } from '../externalDocs/toExternalDocs.js';
11
11
  import { toOptionalServersV3 } from '../server/toServerV3.js';
12
+ import { isDroppedByPathParameter } from '../../pathParameters.js';
12
13
  export const toOperationV3 = ({ operation, operationInfo, stackTrail, context }) => {
13
14
  const { method, path, pathItem } = operationInfo;
14
15
  const { operationId, tags, summary, description, parameters, requestBody, responses, deprecated, security, externalDocs, servers,
@@ -70,9 +71,11 @@ export const toOperationsV3 = ({ paths, stackTrail, context }) => {
70
71
  rest: pathItem,
71
72
  methodObject: {}
72
73
  });
73
- const pathItemObject = !isEmpty(cleaned.rest)
74
+ const pathItemResult = !isEmpty(cleaned.rest)
74
75
  ? toPathItemV3({ pathItem: cleaned.rest, stackTrail: pathStack, context })
75
76
  : undefined;
77
+ const pathItemObject = pathItemResult?.pathItem;
78
+ const brokenParameters = pathItemResult?.brokenParameters ?? [];
76
79
  return Object.entries(cleaned.methodObject)
77
80
  .map(([method, operation]) => {
78
81
  // Use `pathStack` (the trail with `path` already pushed),
@@ -84,6 +87,9 @@ export const toOperationsV3 = ({ paths, stackTrail, context }) => {
84
87
  if (!operation) {
85
88
  return;
86
89
  }
90
+ if (isDroppedByPathParameter({ brokenParameters, operation, stackTrail: st, context })) {
91
+ return undefined;
92
+ }
87
93
  try {
88
94
  return toOperationV3({
89
95
  operation,
@@ -4,6 +4,7 @@ import type { OpenAPIV3 } from 'openapi-types';
4
4
  import { OasParameter } from '../../../oas/parameter/Parameter.js';
5
5
  import type { OasRef } from '../../../oas/ref/Ref.js';
6
6
  import type { StackTrail } from '../../../context/StackTrail.js';
7
+ import { type PathParameterList } from '../../pathParameters.js';
7
8
  type ParameterLocation = Exclude<OasParameterLocation, 'querystring'>;
8
9
  type ParameterStyle = Exclude<OasParameterStyle, 'cookie'>;
9
10
  export type ToParameterListV3Args = {
@@ -12,6 +13,12 @@ export type ToParameterListV3Args = {
12
13
  context: ParseContextType;
13
14
  };
14
15
  export declare const toParameterListV3: ({ parameters, stackTrail, context }: ToParameterListV3Args) => (OasParameter | OasRef<"parameter">)[] | undefined;
16
+ /**
17
+ * Path-level `parameters`: like {@link toParameterListV3}, but an entry
18
+ * that fails to parse is logged and returned in `broken` instead of
19
+ * throwing.
20
+ */
21
+ export declare const toPathParameterListV3: ({ parameters, stackTrail, context }: ToParameterListV3Args) => PathParameterList<OasParameter | OasRef<"parameter">>;
15
22
  export type ToParametersV3Args = {
16
23
  parameters: Record<string, OpenAPIV3.ParameterObject | OpenAPIV3.ReferenceObject>;
17
24
  stackTrail: StackTrail;
@@ -8,6 +8,7 @@ import { OasParameter } from '../../../oas/parameter/Parameter.js';
8
8
  import { toSpecificationExtensionsV3 } from '../specificationExtensions/toSpecificationExtensionsV3.js';
9
9
  import * as v from 'valibot';
10
10
  import { isEmptyParameter, logEmptyParameter } from '../../emptyParameter.js';
11
+ import { toParameterEntries, toPathParameterList } from '../../pathParameters.js';
11
12
  const parameterLocation = v.enum({
12
13
  query: 'query',
13
14
  header: 'header',
@@ -23,18 +24,25 @@ const parameterStyle = v.enum({
23
24
  pipeDelimited: 'pipeDelimited',
24
25
  deepObject: 'deepObject'
25
26
  });
26
- export const toParameterListV3 = ({ parameters, stackTrail, context }) => {
27
- if (!parameters) {
28
- return undefined;
27
+ export const toParameterListV3 = ({ parameters, stackTrail, context }) => toParameterEntries({ parameters, stackTrail, context })?.flatMap((parameter, index) => toParameterEntryV3({ parameter, index, stackTrail, context }));
28
+ /**
29
+ * Path-level `parameters`: like {@link toParameterListV3}, but an entry
30
+ * that fails to parse is logged and returned in `broken` instead of
31
+ * throwing.
32
+ */
33
+ export const toPathParameterListV3 = ({ parameters, stackTrail, context }) => toPathParameterList({
34
+ parameters,
35
+ stackTrail,
36
+ context,
37
+ toEntry: ({ parameter, index }) => toParameterEntryV3({ parameter, index, stackTrail, context })
38
+ });
39
+ const toParameterEntryV3 = ({ parameter, index, stackTrail, context }) => stackTrail.trace(`${index}`, st => {
40
+ if (isEmptyParameter(parameter)) {
41
+ logEmptyParameter({ parameter, stackTrail: st, context });
42
+ return [];
29
43
  }
30
- return parameters.flatMap((parameter, index) => stackTrail.trace(`${index}`, st => {
31
- if (isEmptyParameter(parameter)) {
32
- logEmptyParameter({ parameter, stackTrail: st, context });
33
- return [];
34
- }
35
- return [toParameterV3({ parameter, stackTrail: st, context })];
36
- }));
37
- };
44
+ return [toParameterV3({ parameter, stackTrail: st, context })];
45
+ });
38
46
  export const toParametersV3 = ({ parameters, stackTrail, context }) => {
39
47
  const output = {};
40
48
  const entries = Object.entries(parameters);