utils.js
2.55 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
"use strict";
const {
resolve
} = require('path');
const {
statSync
} = require('fs');
const normalizePath = require('normalize-path');
/**
* @template T
* @param {T} value
* @return {
T extends (null | undefined)
? []
: T extends string
? [string]
: T extends readonly unknown[]
? T
: T extends Iterable<infer T>
? T[]
: [T]
}
*/
/* istanbul ignore next */
function arrify(value) {
// eslint-disable-next-line no-undefined
if (value === null || value === undefined) {
// @ts-ignore
return [];
}
if (Array.isArray(value)) {
// @ts-ignore
return value;
}
if (typeof value === 'string') {
// @ts-ignore
return [value];
} // @ts-ignore
if (typeof value[Symbol.iterator] === 'function') {
// @ts-ignore
return [...value];
} // @ts-ignore
return [value];
}
/**
* @param {string|string[]} files
* @param {string} context
* @returns {string[]}
*/
function parseFiles(files, context) {
return arrify(files).map((
/** @type {string} */
file) => normalizePath(resolve(context, file)));
}
/**
* @param {string|string[]} patterns
* @param {string|string[]} extensions
* @returns {string[]}
*/
function parseFoldersToGlobs(patterns, extensions = []) {
const extensionsList = arrify(extensions);
const [prefix, postfix] = extensionsList.length > 1 ? ['{', '}'] : ['', ''];
const extensionsGlob = extensionsList.map((
/** @type {string} */
extension) => extension.replace(/^\./u, '')).join(',');
return arrify(patterns).map((
/** @type {string} */
pattern) => {
try {
// The patterns are absolute because they are prepended with the context.
const stats = statSync(pattern);
/* istanbul ignore else */
if (stats.isDirectory()) {
return pattern.replace(/[/\\]*?$/u, `/**${extensionsGlob ? `/*.${prefix + extensionsGlob + postfix}` : ''}`);
}
} catch (_) {// Return the pattern as is on error.
}
return pattern;
});
}
/**
* @param {string} _ key, but unused
* @param {any} value
*/
const jsonStringifyReplacerSortKeys = (_, value) => {
/**
* @param {{ [x: string]: any; }} sorted
* @param {string | number} key
*/
const insert = (sorted, key) => {
// eslint-disable-next-line no-param-reassign
sorted[key] = value[key];
return sorted;
};
return value instanceof Object && !(value instanceof Array) ? Object.keys(value).sort().reduce(insert, {}) : value;
};
module.exports = {
arrify,
parseFiles,
parseFoldersToGlobs,
jsonStringifyReplacerSortKeys
};