-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
executable file
·172 lines (132 loc) · 4.31 KB
/
index.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
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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
#!/usr/bin/env node
const { extname } = require('path');
const { readFileSync } = require('fs')
const acorn = require('acorn');
const chalk = require('chalk');
const { codeFrameColumns } = require('@babel/code-frame');
const beautify = require('js-beautify').js;
const { isMinified } = require('is-minified-performant');
const { debug } = require('./helper/debug');
const { fetch } = require('./helper/fetch');
const args = process.argv.slice(2);
const silent = process.env.SILENT === "true";
async function main() {
const inline = args.includes('--inline')
let filepaths = args;
if (inline) {
filepaths = filepaths.filter((fp) => !fp.startsWith('--'))
}
printResult(await validate(filepaths, { inline }));
}
main();
/**
* @param {string[]} filePaths
* @param {{ inline: boolean; }} options
* @returns {Promise<{ errors: string[]; compressed: boolean; }>}
*/
async function validate(filePaths, { inline }) {
let errors = [];
let compressed = false;
debug(`got files:`, filePaths);
const jsFilePaths = inline ? filePaths : filePaths.filter(path => {
if (extname(path) === '.js') {
return true;
}
debug(path, 'not a js file, ignored');
});
if (!jsFilePaths || !jsFilePaths.length) {
console.warn('[es5-validator] No file to validate: $ es5-validator FILE_1_TO_VALIDATE.js FILE_2_TO_VALIDATE.js');
process.exit(0);
}
await Promise.all(jsFilePaths.map(async fileName => {
debug(`validate es5 for "${fileName}"`);
const rawSource = inline ? fileName : await fetchFileContent(fileName).catch(error => {
console.error('fetchFileContent', error);
process.exit(1);
});
debug(`rawSource:`, `"${rawSource}"`);
compressed = isCompressed(rawSource);
const source = compressed ?
beautify(rawSource, { indent_size: 2, space_in_empty_paren: true }) :
rawSource;
compressed && debug(`source after beautified:`, source);
try {
acorn.parse(source, {
ecmaVersion: 5,
});
debug(`parse success ${fileName}`);
} catch (e) {
debug(`parse failed ${fileName}, error:`, e);
errors = [
chalk.black.bgRed('Error') +
chalk.red(
': ECMAScript 5 validate failed when parsing',
`${chalk.green.bold(fileName +
(compressed || isRemoteFile(fileName) ? ` (formatted) (${e.loc.line}, ${e.loc.column})` : `:${e.loc.line}:${e.loc.column}`)
)}`
),
];
errors.push('');
errors.push('');
errors.push(codeFrameColumns(source, {
start: e.loc,
}, {
highlightCode: true,
forceColor: true,
message: 'Invalid ECMAScript 5 syntax',
linesAbove: 10,
linesBelow: 2,
}));
}
}));
return { errors, compressed };
}
function printResult({ errors = [], compressed = false } = {}) {
console.log('');
const compatible = errors.length === 0;
if (compatible) {
console.log(chalk.greenBright('[es5-validator] Congratulations! Your code is ES5 Compatible. It\'s ready to ship to production.'));
} else {
if (compressed) {
console.log(chalk.italic(`[es5-validator] NOTICE: It's hard to locate the problem when code is compressed, so it will be formatted before validation.`));
console.log('');
}
console.log(chalk.redBright('[es5-validator] Your code is not ES5 Compatible. It\'s not ready to ship to production, otherwise it will break you App on Android 4+ or iOS 8+.'));
console.log('');
console.error(errors.join('\n'));
}
console.log('');
console.log(chalk.cyan(`Give a star ❤️ if it helped you https://github.com/legend80s/es5-validator.`));
console.log('');
process.exit((compatible || silent) ? 0 : 1)
}
/**
* @param {string} path
*/
function isRemoteFile(path) {
return /^https?:\/\//.test(path);
}
async function fetchFileContent(filePath) {
if (!isRemoteFile(filePath)) {
return readFileSync(filePath).toString();
}
return fetch(filePath);
}
/**
* @param {T[]} array
* @param {(element: T, index: number) => Promise<any>} cb
*/
// async function asyncForEach(array, cb) {
// for (let index = 0; index < array.length; index++) {
// const element = array[index];
// await cb(element, index, array);
// }
// }
/**
*
* @param {string} source
* @returns {boolean}
*/
function isCompressed(source) {
return isMinified(source)
}