-
-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathminify.js
84 lines (70 loc) · 2.36 KB
/
minify.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
/** @typedef {import("./index.js").MinimizedResult} MinimizedResult */
/** @typedef {import("./index.js").InternalResult} InternalResult */
/**
* @template T
* @param {import("./index.js").InternalOptions<T>} options
* @returns {Promise<InternalResult>}
*/
async function minify(options) {
const minifyFns = Array.isArray(options.minimizer.implementation)
? options.minimizer.implementation
: [options.minimizer.implementation];
/** @type {InternalResult} */
const result = { outputs: [], warnings: [], errors: [] };
let needSourceMap = false;
for (let i = 0; i <= minifyFns.length - 1; i++) {
const minifyFn = minifyFns[i];
const minifyOptions = Array.isArray(options.minimizer.options)
? options.minimizer.options[i]
: options.minimizer.options;
const prevResult =
result.outputs.length > 0
? result.outputs[result.outputs.length - 1]
: { code: options.input, map: options.inputSourceMap };
const { code, map } = prevResult;
// eslint-disable-next-line no-await-in-loop
const minifyResult = await minifyFn(
{ [options.name]: code },
map,
minifyOptions,
);
if (typeof minifyResult.code !== "string") {
throw new Error(
"minimizer function doesn't return the 'code' property or result is not a string value",
);
}
if (minifyResult.map) {
needSourceMap = true;
}
if (minifyResult.errors) {
result.errors = result.errors.concat(minifyResult.errors);
}
if (minifyResult.warnings) {
result.warnings = result.warnings.concat(minifyResult.warnings);
}
result.outputs.push({ code: minifyResult.code, map: minifyResult.map });
}
if (!needSourceMap) {
result.outputs = [result.outputs[result.outputs.length - 1]];
}
return result;
}
/**
* @param {string} options
* @returns {Promise<InternalResult>}
*/
async function transform(options) {
// 'use strict' => this === undefined (Clean Scope)
// Safer for possible security issues, albeit not critical at all here
// eslint-disable-next-line no-new-func, no-param-reassign
const evaluatedOptions = new Function(
"exports",
"require",
"module",
"__filename",
"__dirname",
`'use strict'\nreturn ${options}`,
)(exports, require, module, __filename, __dirname);
return minify(evaluatedOptions);
}
module.exports = { minify, transform };