utils.js 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597
  1. "use strict";
  2. /** @typedef {import("./index.js").ExtractCommentsOptions} ExtractCommentsOptions */
  3. /** @typedef {import("./index.js").ExtractCommentsFunction} ExtractCommentsFunction */
  4. /** @typedef {import("./index.js").ExtractCommentsCondition} ExtractCommentsCondition */
  5. /** @typedef {import("./index.js").Input} Input */
  6. /** @typedef {import("./index.js").MinimizedResult} MinimizedResult */
  7. /** @typedef {import("./index.js").CustomOptions} CustomOptions */
  8. /** @typedef {import("./index.js").RawSourceMap} RawSourceMap */
  9. /** @typedef {import("./index.js").EXPECTED_OBJECT} EXPECTED_OBJECT */
  10. /**
  11. * @typedef {string[]} ExtractedComments
  12. */
  13. const JS_FILE_RE = /\.[cm]?js(\?.*)?$/i;
  14. const JSON_FILE_RE = /\.json(\?.*)?$/i;
  15. const HTML_FILE_RE = /\.html?(\?.*)?$/i;
  16. const CSS_FILE_RE = /\.css(\?.*)?$/i;
  17. /**
  18. * Map a webpack `output.environment` configuration to the highest
  19. * ECMAScript version that the target is known to support. Returns `5`
  20. * when no ES2015+ features are flagged.
  21. * @param {NonNullable<NonNullable<import("webpack").Configuration["output"]>["environment"]>} environment environment
  22. * @returns {number} ecma version (5, 2015, 2017 or 2020)
  23. */
  24. function getEcmaVersion(environment) {
  25. // ES2020 (11th edition)
  26. if (environment.bigIntLiteral || environment.dynamicImport || environment.dynamicImportInWorker || environment.globalThis || environment.optionalChaining) {
  27. return 2020;
  28. }
  29. // ES2017 (8th edition)
  30. if (environment.asyncFunction) {
  31. return 2017;
  32. }
  33. // ES2015 (6th edition)
  34. if (environment.arrowFunction || environment.const || environment.destructuring || environment.forOf || environment.methodShorthand || environment.module || environment.templateLiteral) {
  35. return 2015;
  36. }
  37. return 5;
  38. }
  39. const notSettled = Symbol("not-settled");
  40. /**
  41. * @template T
  42. * @typedef {() => Promise<T>} Task
  43. */
  44. /**
  45. * Run tasks with limited concurrency.
  46. * @template T
  47. * @param {number} limit Limit of tasks that run at once.
  48. * @param {Task<T>[]} tasks List of tasks to run.
  49. * @returns {Promise<T[]>} A promise that fulfills to an array of the results
  50. */
  51. function throttleAll(limit, tasks) {
  52. return new Promise((resolve, reject) => {
  53. const result = Array.from({
  54. length: tasks.length
  55. }).fill(notSettled);
  56. const entries = tasks.entries();
  57. const next = () => {
  58. const {
  59. done,
  60. value
  61. } = entries.next();
  62. if (done) {
  63. const isLast = !result.includes(notSettled);
  64. if (isLast) resolve(result);
  65. return;
  66. }
  67. const [index, task] = value;
  68. /**
  69. * @param {T} resultValue Result value
  70. */
  71. const onFulfilled = resultValue => {
  72. result[index] = resultValue;
  73. next();
  74. };
  75. task().then(onFulfilled, reject);
  76. };
  77. for (let i = 0; i < limit; i++) {
  78. next();
  79. }
  80. });
  81. }
  82. /* istanbul ignore next */
  83. /**
  84. * @param {Input} input input
  85. * @param {RawSourceMap=} sourceMap source map
  86. * @param {CustomOptions=} minimizerOptions options
  87. * @param {ExtractCommentsOptions=} extractComments extract comments option
  88. * @returns {Promise<MinimizedResult>} minimized result
  89. */
  90. async function terserMinify(input, sourceMap, minimizerOptions, extractComments) {
  91. /**
  92. * @param {unknown} value value
  93. * @returns {value is EXPECTED_OBJECT} true when value is object or function
  94. */
  95. const isObject = value => {
  96. const type = typeof value;
  97. // eslint-disable-next-line no-eq-null, eqeqeq
  98. return value != null && (type === "object" || type === "function");
  99. };
  100. /**
  101. * @param {import("terser").MinifyOptions & { sourceMap: import("terser").SourceMapOptions | undefined } & ({ output: import("terser").FormatOptions & { beautify: boolean } } | { format: import("terser").FormatOptions & { beautify: boolean } })} terserOptions terser options
  102. * @param {ExtractedComments} extractedComments extracted comments
  103. * @returns {ExtractCommentsFunction} function to extract comments
  104. */
  105. const buildComments = (terserOptions, extractedComments) => {
  106. /** @type {{ [index: string]: ExtractCommentsCondition }} */
  107. const condition = {};
  108. let comments;
  109. if (terserOptions.format) {
  110. ({
  111. comments
  112. } = terserOptions.format);
  113. } else if (terserOptions.output) {
  114. ({
  115. comments
  116. } = terserOptions.output);
  117. }
  118. condition.preserve = typeof comments !== "undefined" ? comments : false;
  119. if (typeof extractComments === "boolean" && extractComments) {
  120. condition.extract = "some";
  121. } else if (typeof extractComments === "string" || extractComments instanceof RegExp) {
  122. condition.extract = extractComments;
  123. } else if (typeof extractComments === "function") {
  124. condition.extract = extractComments;
  125. } else if (extractComments && isObject(extractComments)) {
  126. condition.extract = typeof extractComments.condition === "boolean" && extractComments.condition ? "some" : typeof extractComments.condition !== "undefined" ? extractComments.condition : "some";
  127. } else {
  128. // No extract
  129. // Preserve using "commentsOpts" or "some"
  130. condition.preserve = typeof comments !== "undefined" ? comments : "some";
  131. condition.extract = false;
  132. }
  133. // Ensure that both conditions are functions
  134. for (const key of ["preserve", "extract"]) {
  135. /** @type {undefined | string} */
  136. let regexStr;
  137. /** @type {undefined | RegExp} */
  138. let regex;
  139. switch (typeof condition[key]) {
  140. case "boolean":
  141. condition[key] = condition[key] ? () => true : () => false;
  142. break;
  143. case "function":
  144. break;
  145. case "string":
  146. if (condition[key] === "all") {
  147. condition[key] = () => true;
  148. break;
  149. }
  150. if (condition[key] === "some") {
  151. condition[key] = /** @type {ExtractCommentsFunction} */
  152. (astNode, comment) => (comment.type === "comment2" || comment.type === "comment1") && /@preserve|@lic|@cc_on|^\**!/i.test(comment.value);
  153. break;
  154. }
  155. regexStr = /** @type {string} */condition[key];
  156. condition[key] = /** @type {ExtractCommentsFunction} */
  157. (astNode, comment) => new RegExp(/** @type {string} */regexStr).test(comment.value);
  158. break;
  159. default:
  160. regex = /** @type {RegExp} */condition[key];
  161. condition[key] = /** @type {ExtractCommentsFunction} */
  162. (astNode, comment) => /** @type {RegExp} */regex.test(comment.value);
  163. }
  164. }
  165. // Redefine the comments function to extract and preserve
  166. // comments according to the two conditions
  167. return (astNode, comment) => {
  168. if (/** @type {{ extract: ExtractCommentsFunction }} */
  169. condition.extract(astNode, comment)) {
  170. const commentText = comment.type === "comment2" ? `/*${comment.value}*/` : `//${comment.value}`;
  171. // Don't include duplicate comments
  172. if (!extractedComments.includes(commentText)) {
  173. extractedComments.push(commentText);
  174. }
  175. }
  176. return /** @type {{ preserve: ExtractCommentsFunction }} */condition.preserve(astNode, comment);
  177. };
  178. };
  179. /**
  180. * @param {import("terser").MinifyOptions=} terserOptions terser options
  181. * @returns {import("terser").MinifyOptions & { sourceMap: import("terser").SourceMapOptions | undefined } & { compress: import("terser").CompressOptions } & ({ output: import("terser").FormatOptions & { beautify: boolean } } | { format: import("terser").FormatOptions & { beautify: boolean } })} built terser options
  182. */
  183. const buildTerserOptions = (terserOptions = {}) => (
  184. // Need deep copy objects to avoid https://github.com/terser/terser/issues/366
  185. {
  186. ...terserOptions,
  187. compress: typeof terserOptions.compress === "boolean" ? terserOptions.compress ? {} : false : {
  188. ...terserOptions.compress
  189. },
  190. // ecma: terserOptions.ecma,
  191. // ie8: terserOptions.ie8,
  192. // keep_classnames: terserOptions.keep_classnames,
  193. // keep_fnames: terserOptions.keep_fnames,
  194. mangle:
  195. // eslint-disable-next-line no-eq-null, eqeqeq
  196. terserOptions.mangle == null ? true : typeof terserOptions.mangle === "boolean" ? terserOptions.mangle : {
  197. ...terserOptions.mangle
  198. },
  199. // module: terserOptions.module,
  200. // nameCache: { ...terserOptions.toplevel },
  201. // the `output` option is deprecated
  202. ...(terserOptions.format ? {
  203. format: {
  204. beautify: false,
  205. ...terserOptions.format
  206. }
  207. } : {
  208. output: {
  209. beautify: false,
  210. ...terserOptions.output
  211. }
  212. }),
  213. parse: {
  214. ...terserOptions.parse
  215. },
  216. // safari10: terserOptions.safari10,
  217. // Ignoring sourceMap from options
  218. sourceMap: undefined
  219. // toplevel: terserOptions.toplevel
  220. });
  221. let minify;
  222. try {
  223. ({
  224. minify
  225. } = require("terser"));
  226. } catch (err) {
  227. return {
  228. errors: [(/** @type {Error} */err)]
  229. };
  230. }
  231. // Copy `terser` options
  232. const terserOptions = buildTerserOptions(minimizerOptions);
  233. // Let terser generate a SourceMap. The dispatcher in `minify.js`
  234. // chains the previous step's map onto this one.
  235. if (sourceMap) {
  236. terserOptions.sourceMap = {
  237. asObject: true
  238. };
  239. }
  240. /** @type {ExtractedComments} */
  241. const extractedComments = [];
  242. if (terserOptions.output) {
  243. terserOptions.output.comments = buildComments(terserOptions, extractedComments);
  244. } else if (terserOptions.format) {
  245. terserOptions.format.comments = buildComments(terserOptions, extractedComments);
  246. }
  247. if (terserOptions.compress) {
  248. // More optimizations
  249. if (typeof terserOptions.compress.ecma === "undefined") {
  250. terserOptions.compress.ecma = terserOptions.ecma;
  251. }
  252. // https://github.com/webpack/webpack/issues/16135
  253. if (terserOptions.ecma === 5 && typeof terserOptions.compress.arrows === "undefined") {
  254. terserOptions.compress.arrows = false;
  255. }
  256. }
  257. const [[filename, code]] = Object.entries(input);
  258. const result = await minify({
  259. [filename]: code
  260. }, terserOptions);
  261. return {
  262. code: (/** @type {string} * */result.code),
  263. map: result.map ? (/** @type {RawSourceMap} * */result.map) : undefined,
  264. extractedComments
  265. };
  266. }
  267. /**
  268. * @returns {string | undefined} the minimizer version
  269. */
  270. terserMinify.getMinimizerVersion = () => {
  271. let packageJson;
  272. try {
  273. packageJson = require("terser/package.json");
  274. } catch (_err) {
  275. // Ignore
  276. }
  277. return packageJson && packageJson.version;
  278. };
  279. /**
  280. * @returns {boolean | undefined} true if worker thread is supported, false otherwise
  281. */
  282. terserMinify.supportsWorkerThreads = () => true;
  283. /**
  284. * @param {string} name asset name
  285. * @returns {boolean} true if `name` looks like a JavaScript file
  286. */
  287. terserMinify.filter = name => JS_FILE_RE.test(name);
  288. /* istanbul ignore next */
  289. /**
  290. * @param {Input} input input
  291. * @param {RawSourceMap=} sourceMap source map
  292. * @param {CustomOptions=} minimizerOptions options
  293. * @param {ExtractCommentsOptions=} extractComments extract comments option
  294. * @returns {Promise<MinimizedResult>} minimized result
  295. */
  296. async function uglifyJsMinify(input, sourceMap, minimizerOptions, extractComments) {
  297. /**
  298. * @param {unknown} value value
  299. * @returns {boolean} true when value is object or function
  300. */
  301. const isObject = value => {
  302. const type = typeof value;
  303. // eslint-disable-next-line no-eq-null, eqeqeq
  304. return value != null && (type === "object" || type === "function");
  305. };
  306. /**
  307. * @param {import("uglify-js").MinifyOptions & { sourceMap: boolean | import("uglify-js").SourceMapOptions | undefined } & { output: import("uglify-js").OutputOptions & { beautify: boolean } }} uglifyJsOptions uglify-js options
  308. * @param {ExtractedComments} extractedComments extracted comments
  309. * @returns {ExtractCommentsFunction} extract comments function
  310. */
  311. const buildComments = (uglifyJsOptions, extractedComments) => {
  312. /** @type {{ [index: string]: ExtractCommentsCondition }} */
  313. const condition = {};
  314. const {
  315. comments
  316. } = uglifyJsOptions.output;
  317. condition.preserve = typeof comments !== "undefined" ? comments : false;
  318. if (typeof extractComments === "boolean" && extractComments) {
  319. condition.extract = "some";
  320. } else if (typeof extractComments === "string" || extractComments instanceof RegExp) {
  321. condition.extract = extractComments;
  322. } else if (typeof extractComments === "function") {
  323. condition.extract = extractComments;
  324. } else if (extractComments && isObject(extractComments)) {
  325. condition.extract = typeof extractComments.condition === "boolean" && extractComments.condition ? "some" : typeof extractComments.condition !== "undefined" ? extractComments.condition : "some";
  326. } else {
  327. // No extract
  328. // Preserve using "commentsOpts" or "some"
  329. condition.preserve = typeof comments !== "undefined" ? comments : "some";
  330. condition.extract = false;
  331. }
  332. // Ensure that both conditions are functions
  333. for (const key of ["preserve", "extract"]) {
  334. /** @type {undefined | string} */
  335. let regexStr;
  336. /** @type {undefined | RegExp} */
  337. let regex;
  338. switch (typeof condition[key]) {
  339. case "boolean":
  340. condition[key] = condition[key] ? () => true : () => false;
  341. break;
  342. case "function":
  343. break;
  344. case "string":
  345. if (condition[key] === "all") {
  346. condition[key] = () => true;
  347. break;
  348. }
  349. if (condition[key] === "some") {
  350. condition[key] = /** @type {ExtractCommentsFunction} */
  351. (astNode, comment) => (comment.type === "comment2" || comment.type === "comment1") && /@preserve|@lic|@cc_on|^\**!/i.test(comment.value);
  352. break;
  353. }
  354. regexStr = /** @type {string} */condition[key];
  355. condition[key] = /** @type {ExtractCommentsFunction} */
  356. (astNode, comment) => new RegExp(/** @type {string} */regexStr).test(comment.value);
  357. break;
  358. default:
  359. regex = /** @type {RegExp} */condition[key];
  360. condition[key] = /** @type {ExtractCommentsFunction} */
  361. (astNode, comment) => /** @type {RegExp} */regex.test(comment.value);
  362. }
  363. }
  364. // Redefine the comments function to extract and preserve
  365. // comments according to the two conditions
  366. return (astNode, comment) => {
  367. if (/** @type {{ extract: ExtractCommentsFunction }} */
  368. condition.extract(astNode, comment)) {
  369. const commentText = comment.type === "comment2" ? `/*${comment.value}*/` : `//${comment.value}`;
  370. // Don't include duplicate comments
  371. if (!extractedComments.includes(commentText)) {
  372. extractedComments.push(commentText);
  373. }
  374. }
  375. return /** @type {{ preserve: ExtractCommentsFunction }} */condition.preserve(astNode, comment);
  376. };
  377. };
  378. /**
  379. * @param {import("uglify-js").MinifyOptions & { ecma?: number | string }=} uglifyJsOptions uglify-js options
  380. * @returns {import("uglify-js").MinifyOptions & { sourceMap: boolean | import("uglify-js").SourceMapOptions | undefined } & { output: import("uglify-js").OutputOptions & { beautify: boolean } }} uglify-js options
  381. */
  382. const buildUglifyJsOptions = (uglifyJsOptions = {}) => {
  383. if (typeof uglifyJsOptions.ecma !== "undefined") {
  384. delete uglifyJsOptions.ecma;
  385. }
  386. if (typeof uglifyJsOptions.module !== "undefined") {
  387. delete uglifyJsOptions.module;
  388. }
  389. // Need deep copy objects to avoid https://github.com/terser/terser/issues/366
  390. return {
  391. ...uglifyJsOptions,
  392. // warnings: uglifyJsOptions.warnings,
  393. parse: {
  394. ...uglifyJsOptions.parse
  395. },
  396. compress: typeof uglifyJsOptions.compress === "boolean" ? uglifyJsOptions.compress : {
  397. ...uglifyJsOptions.compress
  398. },
  399. mangle:
  400. // eslint-disable-next-line no-eq-null, eqeqeq
  401. uglifyJsOptions.mangle == null ? true : typeof uglifyJsOptions.mangle === "boolean" ? uglifyJsOptions.mangle : {
  402. ...uglifyJsOptions.mangle
  403. },
  404. output: {
  405. beautify: false,
  406. ...uglifyJsOptions.output
  407. },
  408. // Ignoring sourceMap from options
  409. sourceMap: undefined
  410. // toplevel: uglifyJsOptions.toplevel
  411. // nameCache: { ...uglifyJsOptions.toplevel },
  412. // ie8: uglifyJsOptions.ie8,
  413. // keep_fnames: uglifyJsOptions.keep_fnames,
  414. };
  415. };
  416. let minify;
  417. try {
  418. ({
  419. minify
  420. } = require("uglify-js"));
  421. } catch (err) {
  422. return {
  423. errors: [(/** @type {Error} */err)]
  424. };
  425. }
  426. // Copy `uglify-js` options
  427. const uglifyJsOptions = buildUglifyJsOptions(minimizerOptions);
  428. // Let `uglify-js` generate a SourceMap. The dispatcher in `minify.js`
  429. // chains the previous step's map onto this one.
  430. if (sourceMap) {
  431. uglifyJsOptions.sourceMap = true;
  432. }
  433. /** @type {ExtractedComments} */
  434. const extractedComments = [];
  435. // @ts-expect-error wrong types in uglify-js
  436. uglifyJsOptions.output.comments = buildComments(uglifyJsOptions, extractedComments);
  437. const [[filename, code]] = Object.entries(input);
  438. const result = await minify({
  439. [filename]: code
  440. }, uglifyJsOptions);
  441. return {
  442. code: result.code,
  443. map: result.map ? JSON.parse(result.map) : undefined,
  444. errors: result.error ? [result.error] : [],
  445. warnings: result.warnings || [],
  446. extractedComments
  447. };
  448. }
  449. /**
  450. * @returns {string | undefined} the minimizer version
  451. */
  452. uglifyJsMinify.getMinimizerVersion = () => {
  453. let packageJson;
  454. try {
  455. packageJson = require("uglify-js/package.json");
  456. } catch (_err) {
  457. // Ignore
  458. }
  459. return packageJson && packageJson.version;
  460. };
  461. /**
  462. * @returns {boolean | undefined} true if worker thread is supported, false otherwise
  463. */
  464. uglifyJsMinify.supportsWorkerThreads = () => true;
  465. /**
  466. * @param {string} name asset name
  467. * @returns {boolean} true if `name` looks like a JavaScript file
  468. */
  469. uglifyJsMinify.filter = name => JS_FILE_RE.test(name);
  470. /* istanbul ignore next */
  471. /**
  472. * @param {Input} input input
  473. * @param {RawSourceMap=} sourceMap source map
  474. * @param {CustomOptions=} minimizerOptions options
  475. * @param {ExtractCommentsOptions=} extractComments extract comments option
  476. * @returns {Promise<MinimizedResult>} minimized result
  477. */
  478. async function swcMinify(input, sourceMap, minimizerOptions, extractComments) {
  479. /**
  480. * @param {unknown} value value
  481. * @returns {boolean} true when value is object or function
  482. */
  483. const isObject = value => {
  484. const type = typeof value;
  485. // eslint-disable-next-line no-eq-null, eqeqeq
  486. return value != null && (type === "object" || type === "function");
  487. };
  488. /**
  489. * @param {unknown} extractCommentsOptions extract comments option
  490. * @returns {Error} error for unsupported extract comments option
  491. */
  492. const createExtractCommentsError = extractCommentsOptions => new Error(`The 'extractComments' option for 'swcMinify' only supports booleans, "some", "all", string patterns, RegExp values without flags, or object conditions that resolve to those forms. Received: ${extractCommentsOptions instanceof RegExp ? extractCommentsOptions.toString() : typeof extractCommentsOptions}.`);
  493. /**
  494. * @param {unknown} extractCommentsOptions extract comments option
  495. * @returns {{ extractComments: false | true | "some" | "all" | { regex: string }, useDefaultPreserveComments: boolean }} normalized swc extract comments options
  496. */
  497. const normalizeExtractComments = extractCommentsOptions => {
  498. if (typeof extractCommentsOptions === "boolean") {
  499. return {
  500. extractComments: extractCommentsOptions,
  501. useDefaultPreserveComments: !extractCommentsOptions
  502. };
  503. }
  504. if (typeof extractCommentsOptions === "string") {
  505. return {
  506. extractComments: extractCommentsOptions === "some" || extractCommentsOptions === "all" ? extractCommentsOptions : {
  507. regex: extractCommentsOptions
  508. },
  509. useDefaultPreserveComments: false
  510. };
  511. }
  512. if (extractCommentsOptions instanceof RegExp) {
  513. if (extractCommentsOptions.flags) {
  514. throw createExtractCommentsError(extractCommentsOptions);
  515. }
  516. return {
  517. extractComments: {
  518. regex: extractCommentsOptions.source
  519. },
  520. useDefaultPreserveComments: false
  521. };
  522. }
  523. if (typeof extractCommentsOptions === "function") {
  524. throw createExtractCommentsError(extractCommentsOptions);
  525. }
  526. if (extractCommentsOptions && isObject(extractCommentsOptions)) {
  527. const {
  528. condition = "some"
  529. } = /** @type {{ condition?: unknown }} */
  530. extractCommentsOptions;
  531. if (typeof condition === "boolean") {
  532. return {
  533. extractComments: condition ? "some" : false,
  534. useDefaultPreserveComments: false
  535. };
  536. }
  537. if (typeof condition === "string") {
  538. return {
  539. extractComments: condition === "some" || condition === "all" ? condition : {
  540. regex: condition
  541. },
  542. useDefaultPreserveComments: false
  543. };
  544. }
  545. if (condition instanceof RegExp) {
  546. if (condition.flags) {
  547. throw createExtractCommentsError(condition);
  548. }
  549. return {
  550. extractComments: {
  551. regex: condition.source
  552. },
  553. useDefaultPreserveComments: false
  554. };
  555. }
  556. throw createExtractCommentsError(condition);
  557. }
  558. return {
  559. extractComments: false,
  560. useDefaultPreserveComments: false
  561. };
  562. };
  563. /**
  564. * @param {import("@swc/core").JsMinifyOptions=} swcOptions swc options
  565. * @returns {import("@swc/core").JsMinifyOptions & { extractComments?: false | true | "some" | "all" | { regex: string } } & { sourceMap: undefined | boolean } & { compress: import("@swc/core").TerserCompressOptions }} built swc options
  566. */
  567. const buildSwcOptions = (swcOptions = {}) => (
  568. // Need deep copy objects to avoid https://github.com/terser/terser/issues/366
  569. {
  570. ...swcOptions,
  571. compress: typeof swcOptions.compress === "boolean" ? swcOptions.compress ? {} : false : {
  572. ...swcOptions.compress
  573. },
  574. mangle:
  575. // eslint-disable-next-line no-eq-null, eqeqeq
  576. swcOptions.mangle == null ? true : typeof swcOptions.mangle === "boolean" ? swcOptions.mangle : {
  577. ...swcOptions.mangle
  578. },
  579. format: {
  580. ...swcOptions.format
  581. },
  582. // ecma: swcOptions.ecma,
  583. // keep_classnames: swcOptions.keep_classnames,
  584. // keep_fnames: swcOptions.keep_fnames,
  585. // module: swcOptions.module,
  586. // safari10: swcOptions.safari10,
  587. // toplevel: swcOptions.toplevel
  588. sourceMap: undefined
  589. });
  590. let swc;
  591. try {
  592. swc = require("@swc/core");
  593. } catch (err) {
  594. return {
  595. errors: [(/** @type {Error} */err)]
  596. };
  597. }
  598. // Copy `swc` options
  599. const swcOptions = buildSwcOptions(minimizerOptions);
  600. const normalizedExtractComments = normalizeExtractComments(extractComments);
  601. if (!swcOptions.format) {
  602. swcOptions.format = {};
  603. }
  604. // Let `swc` generate a SourceMap.
  605. if (sourceMap) {
  606. swcOptions.sourceMap = true;
  607. }
  608. if (normalizedExtractComments.useDefaultPreserveComments && typeof swcOptions.format.comments === "undefined") {
  609. swcOptions.format.comments = "some";
  610. }
  611. if (normalizedExtractComments.extractComments !== false) {
  612. /** @type {import("@swc/core").JsMinifyOptions & { extractComments?: false | true | "some" | "all" | { regex: string } }} */
  613. swcOptions.extractComments = normalizedExtractComments.extractComments;
  614. }
  615. if (swcOptions.compress) {
  616. // More optimizations
  617. if (typeof swcOptions.compress.ecma === "undefined") {
  618. swcOptions.compress.ecma = swcOptions.ecma;
  619. }
  620. // https://github.com/webpack/webpack/issues/16135
  621. if (swcOptions.ecma === 5 && typeof swcOptions.compress.arrows === "undefined") {
  622. swcOptions.compress.arrows = false;
  623. }
  624. }
  625. const [[filename, code]] = Object.entries(input);
  626. const result = /** @type {import("@swc/core").Output & { extractedComments?: string[] }} */
  627. await swc.minify(code, swcOptions);
  628. let map;
  629. if (result.map) {
  630. map = JSON.parse(result.map);
  631. // TODO workaround for swc because `filename` is not preset as in `swc` signature as for `terser`
  632. map.sources = [filename];
  633. delete map.sourcesContent;
  634. }
  635. return {
  636. code: result.code,
  637. map,
  638. extractedComments: result.extractedComments || []
  639. };
  640. }
  641. /**
  642. * @returns {string | undefined} the minimizer version
  643. */
  644. swcMinify.getMinimizerVersion = () => {
  645. let packageJson;
  646. try {
  647. packageJson = require("@swc/core/package.json");
  648. } catch (_err) {
  649. // Ignore
  650. }
  651. return packageJson && packageJson.version;
  652. };
  653. /**
  654. * @returns {boolean | undefined} true if worker thread is supported, false otherwise
  655. */
  656. swcMinify.supportsWorkerThreads = () => false;
  657. /**
  658. * @param {string} name asset name
  659. * @returns {boolean} true if `name` looks like a JavaScript file
  660. */
  661. swcMinify.filter = name => JS_FILE_RE.test(name);
  662. /* istanbul ignore next */
  663. /**
  664. * @param {Input} input input
  665. * @param {RawSourceMap=} sourceMap source map
  666. * @param {CustomOptions=} minimizerOptions options
  667. * @returns {Promise<MinimizedResult>} minimized result
  668. */
  669. async function esbuildMinify(input, sourceMap, minimizerOptions) {
  670. /**
  671. * @param {import("esbuild").TransformOptions & { ecma?: string | number, module?: boolean }=} esbuildOptions esbuild options
  672. * @returns {import("esbuild").TransformOptions} built esbuild options
  673. */
  674. const buildEsbuildOptions = (esbuildOptions = {}) => {
  675. delete esbuildOptions.ecma;
  676. if (esbuildOptions.module) {
  677. esbuildOptions.format = "esm";
  678. }
  679. delete esbuildOptions.module;
  680. // Need deep copy objects to avoid https://github.com/terser/terser/issues/366
  681. return {
  682. minify: true,
  683. legalComments: "inline",
  684. ...esbuildOptions,
  685. sourcemap: false
  686. };
  687. };
  688. let esbuild;
  689. try {
  690. esbuild = require("esbuild");
  691. } catch (err) {
  692. return {
  693. errors: [(/** @type {Error} */err)]
  694. };
  695. }
  696. // Copy `esbuild` options
  697. const esbuildOptions = buildEsbuildOptions(minimizerOptions);
  698. // Let `esbuild` generate a SourceMap
  699. if (sourceMap) {
  700. esbuildOptions.sourcemap = true;
  701. esbuildOptions.sourcesContent = false;
  702. }
  703. const [[filename, code]] = Object.entries(input);
  704. esbuildOptions.sourcefile = filename;
  705. const result = await esbuild.transform(code, esbuildOptions);
  706. return {
  707. code: result.code,
  708. map: result.map ? JSON.parse(result.map) : undefined,
  709. warnings: result.warnings.length > 0 ? result.warnings.map(item => {
  710. const plugin = item.pluginName ? `\nPlugin Name: ${item.pluginName}` : "";
  711. const location = item.location ? `\n\n${item.location.file}:${item.location.line}:${item.location.column}:\n ${item.location.line} | ${item.location.lineText}\n\nSuggestion: ${item.location.suggestion}` : "";
  712. const notes = item.notes.length > 0 ? `\n\nNotes:\n${item.notes.map(note => `${note.location ? `[${note.location.file}:${note.location.line}:${note.location.column}] ` : ""}${note.text}${note.location ? `\nSuggestion: ${note.location.suggestion}` : ""}${note.location ? `\nLine text:\n${note.location.lineText}\n` : ""}`).join("\n")}` : "";
  713. return `${item.text} [${item.id}]${plugin}${location}${item.detail ? `\nDetails:\n${item.detail}` : ""}${notes}`;
  714. }) : []
  715. };
  716. }
  717. /**
  718. * @returns {string | undefined} the minimizer version
  719. */
  720. esbuildMinify.getMinimizerVersion = () => {
  721. let packageJson;
  722. try {
  723. packageJson = require("esbuild/package.json");
  724. } catch (_err) {
  725. // Ignore
  726. }
  727. return packageJson && packageJson.version;
  728. };
  729. /**
  730. * @returns {boolean | undefined} true if worker thread is supported, false otherwise
  731. */
  732. esbuildMinify.supportsWorkerThreads = () => false;
  733. /**
  734. * @param {string} name asset name
  735. * @returns {boolean} true if `name` looks like a JavaScript file
  736. */
  737. esbuildMinify.filter = name => JS_FILE_RE.test(name);
  738. /* istanbul ignore next */
  739. /**
  740. * @param {Input} input input
  741. * @param {RawSourceMap=} sourceMap source map
  742. * @param {CustomOptions=} minimizerOptions options
  743. * @returns {Promise<MinimizedResult>} minimized result
  744. */
  745. async function jsonMinify(input, sourceMap, minimizerOptions) {
  746. const options = /** @type {{ replacer?: Parameters<typeof JSON.stringify>[1], space?: Parameters<typeof JSON.stringify>[2] }} */
  747. minimizerOptions;
  748. const [[, code]] = Object.entries(input);
  749. const result = JSON.stringify(JSON.parse(code), options.replacer, options.space);
  750. return {
  751. code: result
  752. };
  753. }
  754. jsonMinify.getMinimizerVersion = () => "1.0.0";
  755. jsonMinify.supportsWorker = () => false;
  756. jsonMinify.supportsWorkerThreads = () => false;
  757. /**
  758. * @param {string} name asset name
  759. * @returns {boolean} true if `name` looks like a JSON file
  760. */
  761. jsonMinify.filter = name => JSON_FILE_RE.test(name);
  762. /* istanbul ignore next */
  763. /**
  764. * Minify HTML using `html-minifier-terser`.
  765. * @param {Input} input input
  766. * @param {RawSourceMap=} sourceMap source map (ignored for HTML)
  767. * @param {CustomOptions=} minimizerOptions options
  768. * @returns {Promise<MinimizedResult>} minimized result
  769. */
  770. async function htmlMinifierTerser(input, sourceMap, minimizerOptions) {
  771. let htmlMinifier;
  772. try {
  773. htmlMinifier = require("html-minifier-terser");
  774. } catch (err) {
  775. return {
  776. errors: [(/** @type {Error} */err)]
  777. };
  778. }
  779. const [[, code]] = Object.entries(input);
  780. /** @type {import("html-minifier-terser").Options} */
  781. const defaultMinimizerOptions = {
  782. caseSensitive: true,
  783. // `collapseBooleanAttributes` is not always safe, since this can break CSS attribute selectors and not safe for XHTML
  784. collapseWhitespace: true,
  785. conservativeCollapse: true,
  786. keepClosingSlash: true,
  787. // We need ability to use cssnano, or setup own function without extra dependencies
  788. minifyCSS: true,
  789. minifyJS: true,
  790. // `minifyURLs` is unsafe, because we can't guarantee what the base URL is
  791. // `removeAttributeQuotes` is not safe in some rare cases, also HTML spec recommends against doing this
  792. removeComments: true,
  793. // `removeEmptyAttributes` is not safe, can affect certain style or script behavior, look at https://github.com/webpack-contrib/html-loader/issues/323
  794. // `removeRedundantAttributes` is not safe, can affect certain style or script behavior, look at https://github.com/webpack-contrib/html-loader/issues/323
  795. removeScriptTypeAttributes: true,
  796. removeStyleLinkTypeAttributes: true
  797. // `useShortDoctype` is not safe for XHTML
  798. };
  799. const result = await htmlMinifier.minify(code, {
  800. ...defaultMinimizerOptions,
  801. ...(/** @type {import("html-minifier-terser").Options} */minimizerOptions)
  802. });
  803. return {
  804. code: result
  805. };
  806. }
  807. /**
  808. * @returns {string | undefined} the minimizer version
  809. */
  810. htmlMinifierTerser.getMinimizerVersion = () => {
  811. let packageJson;
  812. try {
  813. packageJson = require("html-minifier-terser/package.json");
  814. } catch (_err) {
  815. // Ignore
  816. }
  817. return packageJson && packageJson.version;
  818. };
  819. /**
  820. * @returns {boolean | undefined} true if worker threads are supported
  821. */
  822. htmlMinifierTerser.supportsWorkerThreads = () => true;
  823. /**
  824. * @param {string} name asset name
  825. * @returns {boolean} true if `name` looks like an HTML file
  826. */
  827. htmlMinifierTerser.filter = name => HTML_FILE_RE.test(name);
  828. /* istanbul ignore next */
  829. /**
  830. * Minify HTML using `@minify-html/node`.
  831. * @param {Input} input input
  832. * @param {RawSourceMap=} sourceMap source map (ignored for HTML)
  833. * @param {CustomOptions=} minimizerOptions options
  834. * @returns {Promise<MinimizedResult>} minimized result
  835. */
  836. async function minifyHtmlNode(input, sourceMap, minimizerOptions) {
  837. let minifyHtmlPkg;
  838. try {
  839. minifyHtmlPkg = require("@minify-html/node");
  840. } catch (err) {
  841. return {
  842. errors: [(/** @type {Error} */err)]
  843. };
  844. }
  845. const [[, code]] = Object.entries(input);
  846. const options = /** @type {Parameters<import("@minify-html/node").minify>[1]} */{
  847. ...minimizerOptions
  848. };
  849. const result = await minifyHtmlPkg.minify(Buffer.from(code), options);
  850. return {
  851. code: result.toString()
  852. };
  853. }
  854. /**
  855. * @returns {string | undefined} the minimizer version
  856. */
  857. minifyHtmlNode.getMinimizerVersion = () => {
  858. let packageJson;
  859. try {
  860. packageJson = require("@minify-html/node/package.json");
  861. } catch (_err) {
  862. // Ignore
  863. }
  864. return packageJson && packageJson.version;
  865. };
  866. /**
  867. * @returns {boolean | undefined} false because `@minify-html/node` is a native binding
  868. */
  869. minifyHtmlNode.supportsWorkerThreads = () => false;
  870. /**
  871. * @param {string} name asset name
  872. * @returns {boolean} true if `name` looks like an HTML file
  873. */
  874. minifyHtmlNode.filter = name => HTML_FILE_RE.test(name);
  875. /* istanbul ignore next */
  876. /**
  877. * Map an `@swc/html` diagnostic to a regular `Error`.
  878. * @param {EXPECTED_OBJECT} diagnostic diagnostic from `@swc/html`
  879. * @returns {Error} error preserving `span` and `level` from the diagnostic
  880. */
  881. function swcHtmlDiagnosticToError(diagnostic) {
  882. const typed = /** @type {{ message: string, span?: unknown, level?: unknown }} */
  883. diagnostic;
  884. /** @type {Error & { span?: unknown, level?: unknown }} */
  885. const error = new Error(typed.message);
  886. error.span = typed.span;
  887. error.level = typed.level;
  888. return error;
  889. }
  890. /* istanbul ignore next */
  891. /**
  892. * Minify a complete HTML document using `@swc/html`.
  893. * @param {Input} input input
  894. * @param {RawSourceMap=} sourceMap source map (ignored for HTML)
  895. * @param {CustomOptions=} minimizerOptions options
  896. * @returns {Promise<MinimizedResult>} minimized result
  897. */
  898. async function swcMinifyHtml(input, sourceMap, minimizerOptions) {
  899. let swcMinifier;
  900. try {
  901. swcMinifier = require("@swc/html");
  902. } catch (err) {
  903. return {
  904. errors: [(/** @type {Error} */err)]
  905. };
  906. }
  907. const [[, code]] = Object.entries(input);
  908. const options = /** @type {import("@swc/html").Options} */{
  909. ...minimizerOptions
  910. };
  911. const result = await swcMinifier.minify(Buffer.from(code), options);
  912. return {
  913. code: result.code,
  914. errors: result.errors ? result.errors.map(swcHtmlDiagnosticToError) : undefined
  915. };
  916. }
  917. /**
  918. * @returns {string | undefined} the minimizer version
  919. */
  920. swcMinifyHtml.getMinimizerVersion = () => {
  921. let packageJson;
  922. try {
  923. packageJson = require("@swc/html/package.json");
  924. } catch (_err) {
  925. // Ignore
  926. }
  927. return packageJson && packageJson.version;
  928. };
  929. /**
  930. * @returns {boolean | undefined} false because `@swc/html` is a native binding
  931. */
  932. swcMinifyHtml.supportsWorkerThreads = () => false;
  933. /**
  934. * @param {string} name asset name
  935. * @returns {boolean} true if `name` looks like an HTML file
  936. */
  937. swcMinifyHtml.filter = name => HTML_FILE_RE.test(name);
  938. /* istanbul ignore next */
  939. /**
  940. * Minify an HTML fragment using `@swc/html`.
  941. *
  942. * Use this for partial HTML (e.g. inside `<template></template>` tags or
  943. * HTML strings that are inserted into another document).
  944. * @param {Input} input input
  945. * @param {RawSourceMap=} sourceMap source map (ignored for HTML)
  946. * @param {CustomOptions=} minimizerOptions options
  947. * @returns {Promise<MinimizedResult>} minimized result
  948. */
  949. async function swcMinifyHtmlFragment(input, sourceMap, minimizerOptions) {
  950. let swcMinifier;
  951. try {
  952. swcMinifier = require("@swc/html");
  953. } catch (err) {
  954. return {
  955. errors: [(/** @type {Error} */err)]
  956. };
  957. }
  958. const [[, code]] = Object.entries(input);
  959. const options = /** @type {import("@swc/html").FragmentOptions} */{
  960. ...minimizerOptions
  961. };
  962. const result = await swcMinifier.minifyFragment(Buffer.from(code), options);
  963. return {
  964. code: result.code,
  965. errors: result.errors ? result.errors.map(swcHtmlDiagnosticToError) : undefined
  966. };
  967. }
  968. /**
  969. * @returns {string | undefined} the minimizer version
  970. */
  971. swcMinifyHtmlFragment.getMinimizerVersion = () => {
  972. let packageJson;
  973. try {
  974. packageJson = require("@swc/html/package.json");
  975. } catch (_err) {
  976. // Ignore
  977. }
  978. return packageJson && packageJson.version;
  979. };
  980. /**
  981. * @returns {boolean | undefined} false because `@swc/html` is a native binding
  982. */
  983. swcMinifyHtmlFragment.supportsWorkerThreads = () => false;
  984. /**
  985. * @param {string} name asset name
  986. * @returns {boolean} true if `name` looks like an HTML file
  987. */
  988. swcMinifyHtmlFragment.filter = name => HTML_FILE_RE.test(name);
  989. /* istanbul ignore next */
  990. /**
  991. * Minify CSS using `cssnano` (via `postcss`).
  992. * @param {Input} input input
  993. * @param {RawSourceMap=} sourceMap source map
  994. * @param {CustomOptions=} minimizerOptions options
  995. * @returns {Promise<MinimizedResult>} minimized result
  996. */
  997. async function cssnanoMinify(input, sourceMap, minimizerOptions = {
  998. preset: "default"
  999. }) {
  1000. /**
  1001. * @template T
  1002. * @param {string} mod module to load
  1003. * @returns {Promise<T>} loaded module
  1004. */
  1005. const load = async mod => {
  1006. let exports;
  1007. try {
  1008. exports = require(mod);
  1009. return exports;
  1010. } catch (err) {
  1011. let importESM;
  1012. try {
  1013. // eslint-disable-next-line no-new-func
  1014. importESM = new Function("id", "return import(id);");
  1015. } catch (_err) {
  1016. importESM = null;
  1017. }
  1018. if (/** @type {Error & { code: string }} */
  1019. err.code === "ERR_REQUIRE_ESM" && importESM) {
  1020. exports = await importESM(mod);
  1021. return exports.default;
  1022. }
  1023. throw err;
  1024. }
  1025. };
  1026. let postcss;
  1027. let cssnano;
  1028. try {
  1029. postcss = require("postcss");
  1030. cssnano = require("cssnano");
  1031. } catch (err) {
  1032. return {
  1033. errors: [(/** @type {Error} */err)]
  1034. };
  1035. }
  1036. const [[name, code]] = Object.entries(input);
  1037. /** @type {import("postcss").ProcessOptions} */
  1038. const postcssOptions = {
  1039. from: name,
  1040. ... /** @type {{ processorOptions?: import("postcss").ProcessOptions }} */minimizerOptions.processorOptions
  1041. };
  1042. if (typeof postcssOptions.parser === "string") {
  1043. try {
  1044. postcssOptions.parser = await load(postcssOptions.parser);
  1045. } catch (error) {
  1046. throw new Error(`Loading PostCSS "${postcssOptions.parser}" parser failed: ${ /** @type {Error} */error.message}\n\n(@${name})`, {
  1047. cause: error
  1048. });
  1049. }
  1050. }
  1051. if (typeof postcssOptions.stringifier === "string") {
  1052. try {
  1053. postcssOptions.stringifier = await load(postcssOptions.stringifier);
  1054. } catch (error) {
  1055. throw new Error(`Loading PostCSS "${postcssOptions.stringifier}" stringifier failed: ${ /** @type {Error} */error.message}\n\n(@${name})`, {
  1056. cause: error
  1057. });
  1058. }
  1059. }
  1060. if (typeof postcssOptions.syntax === "string") {
  1061. try {
  1062. postcssOptions.syntax = await load(postcssOptions.syntax);
  1063. } catch (error) {
  1064. throw new Error(`Loading PostCSS "${postcssOptions.syntax}" syntax failed: ${ /** @type {Error} */error.message}\n\n(@${name})`, {
  1065. cause: error
  1066. });
  1067. }
  1068. }
  1069. if (sourceMap) {
  1070. postcssOptions.map = {
  1071. annotation: false
  1072. };
  1073. }
  1074. const result = await postcss.default([cssnano(minimizerOptions)]).process(code, postcssOptions);
  1075. return {
  1076. code: result.css,
  1077. map: result.map ? (/** @type {RawSourceMap} */
  1078. /** @type {unknown} */result.map.toJSON()) : undefined,
  1079. warnings: result.warnings().map(String)
  1080. };
  1081. }
  1082. /**
  1083. * @returns {string | undefined} the minimizer version
  1084. */
  1085. cssnanoMinify.getMinimizerVersion = () => {
  1086. let packageJson;
  1087. try {
  1088. packageJson = require("cssnano/package.json");
  1089. } catch (_err) {
  1090. // Ignore
  1091. }
  1092. return packageJson && packageJson.version;
  1093. };
  1094. /**
  1095. * @returns {boolean | undefined} true if worker threads are supported
  1096. */
  1097. cssnanoMinify.supportsWorkerThreads = () => true;
  1098. /**
  1099. * @param {string} name asset name
  1100. * @returns {boolean} true if `name` looks like a CSS file
  1101. */
  1102. cssnanoMinify.filter = name => CSS_FILE_RE.test(name);
  1103. /* istanbul ignore next */
  1104. /**
  1105. * Minify CSS using `csso`.
  1106. * @param {Input} input input
  1107. * @param {RawSourceMap=} sourceMap source map
  1108. * @param {CustomOptions=} minimizerOptions options
  1109. * @returns {Promise<MinimizedResult>} minimized result
  1110. */
  1111. async function cssoMinify(input, sourceMap, minimizerOptions) {
  1112. let csso;
  1113. try {
  1114. csso = require("csso");
  1115. } catch (err) {
  1116. return {
  1117. errors: [(/** @type {Error} */err)]
  1118. };
  1119. }
  1120. const [[filename, code]] = Object.entries(input);
  1121. const result = csso.minify(code, {
  1122. filename,
  1123. sourceMap: Boolean(sourceMap),
  1124. ...minimizerOptions
  1125. });
  1126. return {
  1127. code: result.css,
  1128. map: result.map ? (/** @type {RawSourceMap} */
  1129. /** @type {{ toJSON(): RawSourceMap }} */result.map.toJSON()) : undefined
  1130. };
  1131. }
  1132. /**
  1133. * @returns {string | undefined} the minimizer version
  1134. */
  1135. cssoMinify.getMinimizerVersion = () => {
  1136. let packageJson;
  1137. try {
  1138. packageJson = require("csso/package.json");
  1139. } catch (_err) {
  1140. // Ignore
  1141. }
  1142. return packageJson && packageJson.version;
  1143. };
  1144. /**
  1145. * @returns {boolean | undefined} true if worker threads are supported
  1146. */
  1147. cssoMinify.supportsWorkerThreads = () => true;
  1148. /**
  1149. * @param {string} name asset name
  1150. * @returns {boolean} true if `name` looks like a CSS file
  1151. */
  1152. cssoMinify.filter = name => CSS_FILE_RE.test(name);
  1153. /* istanbul ignore next */
  1154. /**
  1155. * Minify CSS using `clean-css`.
  1156. * @param {Input} input input
  1157. * @param {RawSourceMap=} sourceMap source map
  1158. * @param {CustomOptions=} minimizerOptions options
  1159. * @returns {Promise<MinimizedResult>} minimized result
  1160. */
  1161. async function cleanCssMinify(input, sourceMap, minimizerOptions) {
  1162. let CleanCSS;
  1163. try {
  1164. CleanCSS = require("clean-css");
  1165. } catch (err) {
  1166. return {
  1167. errors: [(/** @type {Error} */err)]
  1168. };
  1169. }
  1170. const [[name, code]] = Object.entries(input);
  1171. const result = await new CleanCSS({
  1172. sourceMap: Boolean(sourceMap),
  1173. ...minimizerOptions,
  1174. returnPromise: true
  1175. }).minify({
  1176. [name]: {
  1177. styles: code
  1178. }
  1179. });
  1180. const generatedSourceMap = result.sourceMap ? (/** @type {RawSourceMap} */
  1181. /** @type {{ toJSON(): RawSourceMap }} */(/** @type {unknown} */result.sourceMap).toJSON()) : undefined;
  1182. // workaround for source maps on windows
  1183. if (generatedSourceMap) {
  1184. const isWindowsPathSep = require("path").sep === "\\";
  1185. generatedSourceMap.sources = generatedSourceMap.sources.map(
  1186. /**
  1187. * @param {string | null} item path item
  1188. * @returns {string} normalized path
  1189. */
  1190. item => isWindowsPathSep ? (item || "").replace(/\\/g, "/") : item || "");
  1191. }
  1192. return {
  1193. code: result.styles,
  1194. map: generatedSourceMap,
  1195. warnings: result.warnings
  1196. };
  1197. }
  1198. /**
  1199. * @returns {string | undefined} the minimizer version
  1200. */
  1201. cleanCssMinify.getMinimizerVersion = () => {
  1202. let packageJson;
  1203. try {
  1204. packageJson = require("clean-css/package.json");
  1205. } catch (_err) {
  1206. // Ignore
  1207. }
  1208. return packageJson && packageJson.version;
  1209. };
  1210. /**
  1211. * @returns {boolean | undefined} true if worker threads are supported
  1212. */
  1213. cleanCssMinify.supportsWorkerThreads = () => true;
  1214. /**
  1215. * @param {string} name asset name
  1216. * @returns {boolean} true if `name` looks like a CSS file
  1217. */
  1218. cleanCssMinify.filter = name => CSS_FILE_RE.test(name);
  1219. /* istanbul ignore next */
  1220. /**
  1221. * Minify CSS using `esbuild` (with the CSS loader).
  1222. * @param {Input} input input
  1223. * @param {RawSourceMap=} sourceMap source map
  1224. * @param {CustomOptions=} minimizerOptions options
  1225. * @returns {Promise<MinimizedResult>} minimized result
  1226. */
  1227. async function esbuildMinifyCss(input, sourceMap, minimizerOptions) {
  1228. /**
  1229. * @param {import("esbuild").TransformOptions & { ecma?: string | number, module?: boolean }=} esbuildOptions esbuild options
  1230. * @returns {import("esbuild").TransformOptions} built esbuild options
  1231. */
  1232. const buildEsbuildOptions = (esbuildOptions = {}) => {
  1233. // `module` and `ecma` are JavaScript-only concepts; the dispatcher
  1234. // injects them for every minimizer, but esbuild's CSS transform
  1235. // rejects unknown options.
  1236. delete esbuildOptions.ecma;
  1237. delete esbuildOptions.module;
  1238. // Need deep copy objects to avoid https://github.com/terser/terser/issues/366
  1239. return {
  1240. loader: "css",
  1241. minify: true,
  1242. legalComments: "inline",
  1243. ...esbuildOptions,
  1244. sourcemap: false
  1245. };
  1246. };
  1247. let esbuild;
  1248. try {
  1249. esbuild = require("esbuild");
  1250. } catch (err) {
  1251. return {
  1252. errors: [(/** @type {Error} */err)]
  1253. };
  1254. }
  1255. // Copy `esbuild` options
  1256. const esbuildOptions = buildEsbuildOptions(minimizerOptions);
  1257. // Let `esbuild` generate a SourceMap
  1258. if (sourceMap) {
  1259. esbuildOptions.sourcemap = true;
  1260. esbuildOptions.sourcesContent = false;
  1261. }
  1262. const [[filename, code]] = Object.entries(input);
  1263. esbuildOptions.sourcefile = filename;
  1264. const result = await esbuild.transform(code, esbuildOptions);
  1265. return {
  1266. code: result.code,
  1267. map: result.map ? JSON.parse(result.map) : undefined,
  1268. warnings: result.warnings.length > 0 ? result.warnings.map(item => {
  1269. const plugin = item.pluginName ? `\nPlugin Name: ${item.pluginName}` : "";
  1270. const location = item.location ? `\n\n${item.location.file}:${item.location.line}:${item.location.column}:\n ${item.location.line} | ${item.location.lineText}\n\nSuggestion: ${item.location.suggestion}` : "";
  1271. const notes = item.notes.length > 0 ? `\n\nNotes:\n${item.notes.map(note => `${note.location ? `[${note.location.file}:${note.location.line}:${note.location.column}] ` : ""}${note.text}${note.location ? `\nSuggestion: ${note.location.suggestion}` : ""}${note.location ? `\nLine text:\n${note.location.lineText}\n` : ""}`).join("\n")}` : "";
  1272. return `${item.text} [${item.id}]${plugin}${location}${item.detail ? `\nDetails:\n${item.detail}` : ""}${notes}`;
  1273. }) : []
  1274. };
  1275. }
  1276. /**
  1277. * @returns {string | undefined} the minimizer version
  1278. */
  1279. esbuildMinifyCss.getMinimizerVersion = () => {
  1280. let packageJson;
  1281. try {
  1282. packageJson = require("esbuild/package.json");
  1283. } catch (_err) {
  1284. // Ignore
  1285. }
  1286. return packageJson && packageJson.version;
  1287. };
  1288. /**
  1289. * @returns {boolean | undefined} false because `esbuild` is a native binding
  1290. */
  1291. esbuildMinifyCss.supportsWorkerThreads = () => false;
  1292. /**
  1293. * @param {string} name asset name
  1294. * @returns {boolean} true if `name` looks like a CSS file
  1295. */
  1296. esbuildMinifyCss.filter = name => CSS_FILE_RE.test(name);
  1297. /* istanbul ignore next */
  1298. /**
  1299. * Minify CSS using `lightningcss`.
  1300. * @param {Input} input input
  1301. * @param {RawSourceMap=} sourceMap source map
  1302. * @param {CustomOptions=} minimizerOptions options
  1303. * @returns {Promise<MinimizedResult>} minimized result
  1304. */
  1305. async function lightningCssMinify(input, sourceMap, minimizerOptions) {
  1306. let lightningCss;
  1307. try {
  1308. lightningCss = require("lightningcss");
  1309. } catch (err) {
  1310. return {
  1311. errors: [(/** @type {Error} */err)]
  1312. };
  1313. }
  1314. const [[filename, code]] = Object.entries(input);
  1315. /**
  1316. * @param {Partial<import("lightningcss").TransformOptions<import("lightningcss").CustomAtRules>>=} lightningCssOptions lightning css options
  1317. * @returns {import("lightningcss").TransformOptions<import("lightningcss").CustomAtRules>} built lightning css options
  1318. */
  1319. const buildLightningCssOptions = (lightningCssOptions = {}) => (
  1320. // Need deep copy objects to avoid https://github.com/terser/terser/issues/366
  1321. {
  1322. minify: true,
  1323. ...lightningCssOptions,
  1324. sourceMap: false,
  1325. filename,
  1326. code: new Uint8Array(Buffer.from(code))
  1327. });
  1328. // Copy `lightningCss` options
  1329. const lightningCssOptions = buildLightningCssOptions(minimizerOptions);
  1330. // Let `lightningcss` generate a SourceMap. The dispatcher in
  1331. // `minify.js` chains the previous step's map onto this one.
  1332. if (sourceMap) {
  1333. lightningCssOptions.sourceMap = true;
  1334. }
  1335. const result = lightningCss.transform(lightningCssOptions);
  1336. return {
  1337. code: result.code.toString(),
  1338. map: result.map ? JSON.parse(result.map.toString()) : undefined
  1339. };
  1340. }
  1341. /**
  1342. * @returns {string | undefined} the minimizer version
  1343. */
  1344. lightningCssMinify.getMinimizerVersion = () => {
  1345. let packageJson;
  1346. try {
  1347. packageJson = require("lightningcss/package.json");
  1348. } catch (_err) {
  1349. // Ignore
  1350. }
  1351. return packageJson && packageJson.version;
  1352. };
  1353. /**
  1354. * @returns {boolean | undefined} false because `lightningcss` is a native binding
  1355. */
  1356. lightningCssMinify.supportsWorkerThreads = () => false;
  1357. /**
  1358. * @param {string} name asset name
  1359. * @returns {boolean} true if `name` looks like a CSS file
  1360. */
  1361. lightningCssMinify.filter = name => CSS_FILE_RE.test(name);
  1362. /* istanbul ignore next */
  1363. /**
  1364. * Map a `@swc/css` diagnostic to a regular `Error`.
  1365. * @param {EXPECTED_OBJECT} diagnostic diagnostic from `@swc/css`
  1366. * @returns {Error} error preserving `span` and `level` from the diagnostic
  1367. */
  1368. function swcCssDiagnosticToError(diagnostic) {
  1369. const typed = /** @type {{ message: string, span?: unknown, level?: unknown }} */
  1370. diagnostic;
  1371. /** @type {Error & { span?: unknown, level?: unknown }} */
  1372. const error = new Error(typed.message);
  1373. error.span = typed.span;
  1374. error.level = typed.level;
  1375. return error;
  1376. }
  1377. /* istanbul ignore next */
  1378. /**
  1379. * Minify CSS using `@swc/css`.
  1380. * @param {Input} input input
  1381. * @param {RawSourceMap=} sourceMap source map
  1382. * @param {CustomOptions=} minimizerOptions options
  1383. * @returns {Promise<MinimizedResult>} minimized result
  1384. */
  1385. async function swcMinifyCss(input, sourceMap, minimizerOptions) {
  1386. let swc;
  1387. try {
  1388. swc = require("@swc/css");
  1389. } catch (err) {
  1390. return {
  1391. errors: [(/** @type {Error} */err)]
  1392. };
  1393. }
  1394. const [[filename, code]] = Object.entries(input);
  1395. /**
  1396. * @param {Partial<import("@swc/css").MinifyOptions>=} swcOptions swc options
  1397. * @returns {import("@swc/css").MinifyOptions} built swc options
  1398. */
  1399. const buildSwcOptions = (swcOptions = {}) => (
  1400. // Need deep copy objects to avoid https://github.com/terser/terser/issues/366
  1401. {
  1402. ...swcOptions,
  1403. filename
  1404. });
  1405. // Copy `swc` options
  1406. const swcOptions = buildSwcOptions(minimizerOptions);
  1407. // Let `swc` generate a SourceMap
  1408. if (sourceMap) {
  1409. swcOptions.sourceMap = true;
  1410. }
  1411. const result = await swc.minify(Buffer.from(code), swcOptions);
  1412. return {
  1413. code: result.code.toString(),
  1414. map: result.map ? JSON.parse(result.map.toString()) : undefined,
  1415. errors: result.errors ? result.errors.map(swcCssDiagnosticToError) : undefined
  1416. };
  1417. }
  1418. /**
  1419. * @returns {string | undefined} the minimizer version
  1420. */
  1421. swcMinifyCss.getMinimizerVersion = () => {
  1422. let packageJson;
  1423. try {
  1424. packageJson = require("@swc/css/package.json");
  1425. } catch (_err) {
  1426. // Ignore
  1427. }
  1428. return packageJson && packageJson.version;
  1429. };
  1430. /**
  1431. * @returns {boolean | undefined} false because `@swc/css` is a native binding
  1432. */
  1433. swcMinifyCss.supportsWorkerThreads = () => false;
  1434. /**
  1435. * @param {string} name asset name
  1436. * @returns {boolean} true if `name` looks like a CSS file
  1437. */
  1438. swcMinifyCss.filter = name => CSS_FILE_RE.test(name);
  1439. /**
  1440. * @template T
  1441. * @typedef {() => T} FunctionReturning
  1442. */
  1443. /**
  1444. * @template T
  1445. * @param {FunctionReturning<T>} fn memorized function
  1446. * @returns {FunctionReturning<T>} new function
  1447. */
  1448. function memoize(fn) {
  1449. let cache = false;
  1450. /** @type {T} */
  1451. let result;
  1452. return () => {
  1453. if (cache) {
  1454. return result;
  1455. }
  1456. result = fn();
  1457. cache = true;
  1458. // Allow to clean up memory for fn
  1459. // and all dependent resources
  1460. /** @type {FunctionReturning<T> | undefined} */
  1461. fn = undefined;
  1462. return /** @type {T} */result;
  1463. };
  1464. }
  1465. module.exports = {
  1466. cleanCssMinify,
  1467. cssnanoMinify,
  1468. cssoMinify,
  1469. esbuildMinify,
  1470. esbuildMinifyCss,
  1471. getEcmaVersion,
  1472. htmlMinifierTerser,
  1473. jsonMinify,
  1474. lightningCssMinify,
  1475. memoize,
  1476. minifyHtmlNode,
  1477. swcMinify,
  1478. swcMinifyCss,
  1479. swcMinifyHtml,
  1480. swcMinifyHtmlFragment,
  1481. terserMinify,
  1482. throttleAll,
  1483. uglifyJsMinify
  1484. };