forked from nodejs/nodejs.org
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathordered-yaml-keys.mjs
More file actions
60 lines (54 loc) · 1.42 KB
/
Copy pathordered-yaml-keys.mjs
File metadata and controls
60 lines (54 loc) · 1.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/**
* Default allowed keys and their required order at the top level.
* Order matters for validation.
*/
export const DEFAULT_VALID_KEYS = [
'added',
'napiVersion',
'deprecated',
'removed',
'changes',
];
/**
* Validate that:
* - Only valid keys are present
* - Keys appear in the expected order (relative order respected)
*
* @type {import('./index.mjs').YAMLRule}
* @param {readonly string[]} [validKeys=DEFAULT_VALID_KEYS] - Allowed keys in the expected order.
* @param {string} [prefix=''] - Message prefix for context.
*/
export default function orderedYamlKeys(
yaml,
report,
_,
validKeys = DEFAULT_VALID_KEYS,
prefix = ''
) {
if (!yaml || typeof yaml !== 'object' || Array.isArray(yaml)) {
return;
}
const keys = Object.keys(yaml);
// Check for invalid keys
const invalidKeys = keys.filter(key => !validKeys.includes(key));
if (invalidKeys.length > 0) {
report(`${prefix}Invalid key(s) found: ${invalidKeys.join(', ')}`);
}
// Check key order
let lastIndex = -1;
for (const key of keys) {
const index = validKeys.indexOf(key);
if (index === -1) {
// Non-validated keys are ignored for ordering, since
// they were already reported as invalid above
continue;
}
if (index < lastIndex) {
report(
`${prefix}Key "${key}" is out of order. Expected order: ${validKeys.join(', ')}`
);
break;
}
lastIndex = index;
}
}