-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathremove-extensions.js
64 lines (57 loc) · 2.25 KB
/
remove-extensions.js
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
61
62
63
64
module.exports = RemoveExtensions;
/** @type {import('@redocly/cli').OasDecorator} */
const openAPIExtensions = /x-*/;
// a console.assert that actually abort execution
// message is str
// bool is boolean
function assert(bool, message) {
if (!bool) {
const err = message !== undefined ? new Error(message) : new Error("an error occured")
throw err
}
}
function doRemoveParamFromNode(node, param) {
assert(typeof param === 'string', "extension must be a string")
assert(isExtensionValid(param), `[Aborting] String "${param}" is not a valid OpenAPI extension, it must begin with "x-"`)
delete node[param]
console.log('Deleteted extension "%s" from object "%O"', param, node)
}
function isExtensionValid(extension) {
assert(typeof extension === 'string', "extension must be a string")
if (extension.match(openAPIExtensions)) {
return true
} else {
return false
}
}
function removeExtensionsFromNode(node, extensions) {
const extensionsType = typeof extensions
assert(extensionsType === undefined || extensionsType === 'string' || extensionsType === 'object', `Extensions must be a string or a list of string instead of being of type "${extensionsType}"`)
if (extensions === undefined || extensions === null || extensions === {} || extensions === '') {
console.log('Deleting all OpenAPI extensions (params starting with "x-")...')
Object.keys(node).filter(param => param.match(openAPIExtensions)).forEach((param) => {
doRemoveParamFromNode(node, param)
})
} else if (extensionsType === 'string') {
// extensions is a string representing a regex - delete all the params that match this regex
Object.keys(node).filter(param => param.match(extensions)).forEach((param) => {
doRemoveParamFromNode(node, param)
})
} else {
// extensions a list
// only return something if all strings are valid OpenAPI spec, otherwise panic (handled by the assert)
extensions.forEach((extension) => {
// extension is a string representing a regex - delete all the params that match this regex
Object.keys(node).filter(param => param.match(extension)).forEach((param) => {
doRemoveParamFromNode(node, param)
})
})
}
}
function RemoveExtensions({extensions}) {
return {
any: {
enter: (node, _ctx) => removeExtensionsFromNode(node, extensions),
}
}
};