UNPKG

1.78 kBJavaScriptView Raw
1"use strict";
2
3/** @typedef {import("./index.js").MinimizedResult} MinimizedResult */
4
5/** @typedef {import("./index.js").InternalResult} InternalResult */
6
7/**
8 * @template T
9 * @param {import("./index.js").InternalOptions<T>} options
10 * @returns {Promise<InternalResult>}
11 */
12const minify = async options => {
13 /** @type {InternalResult} */
14 const result = {
15 code: options.input,
16 warnings: [],
17 errors: []
18 };
19 const transformers = Array.isArray(options.minimizer) ? options.minimizer : [options.minimizer];
20
21 for (let i = 0; i <= transformers.length - 1; i++) {
22 const {
23 implementation
24 } = transformers[i]; // eslint-disable-next-line no-await-in-loop
25
26 const minifyResult = await implementation({
27 [options.name]: result.code
28 }, transformers[i].options);
29
30 if (Object.prototype.toString.call(minifyResult) === "[object Object]" && minifyResult !== null && "code" in minifyResult) {
31 result.code = minifyResult.code;
32 result.warnings = result.warnings.concat(minifyResult.warnings || []);
33 result.errors = result.errors.concat(minifyResult.errors || []);
34 } else {
35 // @ts-ignore
36 result.code = minifyResult;
37 }
38 }
39
40 return result;
41};
42/**
43 * @param {string} options
44 * @returns {Promise<InternalResult>}
45 */
46
47
48async function transform(options) {
49 // 'use strict' => this === undefined (Clean Scope)
50 // Safer for possible security issues, albeit not critical at all here
51 // eslint-disable-next-line no-new-func, no-param-reassign
52 const evaluatedOptions = new Function("exports", "require", "module", "__filename", "__dirname", `'use strict'\nreturn ${options}`)(exports, require, module, __filename, __dirname);
53 return minify(evaluatedOptions);
54}
55
56module.exports = {
57 minify,
58 transform
59};
\No newline at end of file