index.js 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712
  1. "use strict";
  2. const os = require("os");
  3. const path = require("path");
  4. const {
  5. validate
  6. } = require("schema-utils");
  7. const {
  8. minify
  9. } = require("./minify");
  10. const schema = require("./options.json");
  11. const {
  12. esbuildMinify,
  13. jsonMinify,
  14. memoize,
  15. swcMinify,
  16. terserMinify,
  17. throttleAll,
  18. uglifyJsMinify
  19. } = require("./utils");
  20. /** @typedef {import("schema-utils/declarations/validate").Schema} Schema */
  21. /** @typedef {import("webpack").Compiler} Compiler */
  22. /** @typedef {import("webpack").Compilation} Compilation */
  23. /** @typedef {import("webpack").Configuration} Configuration */
  24. /** @typedef {import("webpack").Asset} Asset */
  25. /** @typedef {import("webpack").AssetInfo} AssetInfo */
  26. /** @typedef {import("webpack").TemplatePath} TemplatePath */
  27. /** @typedef {import("jest-worker").Worker} JestWorker */
  28. /** @typedef {import("@jridgewell/trace-mapping").EncodedSourceMap & { sources: string[], sourcesContent?: string[], file: string }} RawSourceMap */
  29. /** @typedef {import("@jridgewell/trace-mapping").TraceMap} TraceMap */
  30. /** @typedef {RegExp | string} Rule */
  31. /** @typedef {Rule[] | Rule} Rules */
  32. // eslint-disable-next-line jsdoc/reject-any-type
  33. /** @typedef {any} EXPECTED_ANY */
  34. /**
  35. * @callback ExtractCommentsFunction
  36. * @param {EXPECTED_ANY} astNode ast Node
  37. * @param {{ value: string, type: "comment1" | "comment2" | "comment3" | "comment4", pos: number, line: number, col: number }} comment comment node
  38. * @returns {boolean} true when need to extract comment, otherwise false
  39. */
  40. /**
  41. * @typedef {boolean | "all" | "some" | RegExp | ExtractCommentsFunction} ExtractCommentsCondition
  42. */
  43. /**
  44. * @typedef {TemplatePath} ExtractCommentsFilename
  45. */
  46. /**
  47. * @typedef {boolean | string | ((commentsFile: string) => string)} ExtractCommentsBanner
  48. */
  49. /**
  50. * @typedef {object} ExtractCommentsObject
  51. * @property {ExtractCommentsCondition=} condition condition which comments need to be expected
  52. * @property {ExtractCommentsFilename=} filename filename for extracted comments
  53. * @property {ExtractCommentsBanner=} banner banner in filename for extracted comments
  54. */
  55. /**
  56. * @typedef {ExtractCommentsCondition | ExtractCommentsObject} ExtractCommentsOptions
  57. */
  58. /**
  59. * @typedef {object} ErrorObject
  60. * @property {string} message message
  61. * @property {number=} line line number
  62. * @property {number=} column column number
  63. * @property {string=} stack error stack trace
  64. */
  65. /**
  66. * @typedef {object} MinimizedResult
  67. * @property {string=} code code
  68. * @property {RawSourceMap=} map source map
  69. * @property {(Error | string)[]=} errors errors
  70. * @property {(Error | string)[]=} warnings warnings
  71. * @property {string[]=} extractedComments extracted comments
  72. */
  73. /**
  74. * @typedef {{ [file: string]: string }} Input
  75. */
  76. /**
  77. * @typedef {{ [key: string]: EXPECTED_ANY }} CustomOptions
  78. */
  79. /**
  80. * @template T
  81. * @typedef {T extends infer U ? U : CustomOptions} InferDefaultType
  82. */
  83. /**
  84. * @template T
  85. * @typedef {object} PredefinedOptions
  86. * @property {T extends { module?: infer P } ? P : boolean | string=} module true when code is a EC module, otherwise false
  87. * @property {T extends { ecma?: infer P } ? P : number | string=} ecma ecma version
  88. */
  89. /**
  90. * @template T
  91. * @typedef {PredefinedOptions<T> & InferDefaultType<T>} MinimizerOptions
  92. */
  93. /**
  94. * @template T
  95. * @callback BasicMinimizerImplementation
  96. * @param {Input} input
  97. * @param {RawSourceMap | undefined} sourceMap
  98. * @param {MinimizerOptions<T>} minifyOptions
  99. * @param {ExtractCommentsOptions | undefined} extractComments
  100. * @returns {Promise<MinimizedResult> | MinimizedResult}
  101. */
  102. /**
  103. * @typedef {object} MinimizeFunctionHelpers
  104. * @property {() => string | undefined=} getMinimizerVersion function that returns version of minimizer
  105. * @property {() => boolean | undefined=} supportsWorkerThreads true when minimizer support worker threads, otherwise false
  106. * @property {() => boolean | undefined=} supportsWorker true when minimizer support worker, otherwise false
  107. */
  108. /**
  109. * @template T
  110. * @typedef {BasicMinimizerImplementation<T> & MinimizeFunctionHelpers} MinimizerImplementation
  111. */
  112. /**
  113. * @template T
  114. * @typedef {object} InternalOptions
  115. * @property {string} name name
  116. * @property {string} input input
  117. * @property {RawSourceMap | undefined} inputSourceMap input source map
  118. * @property {ExtractCommentsOptions | undefined} extractComments extract comments option
  119. * @property {{ implementation: MinimizerImplementation<T>, options: MinimizerOptions<T> }} minimizer minimizer
  120. */
  121. /**
  122. * @template T
  123. * @typedef {JestWorker & { transform: (options: string) => Promise<MinimizedResult>, minify: (options: InternalOptions<T>) => Promise<MinimizedResult> }} MinimizerWorker
  124. */
  125. /**
  126. * @typedef {undefined | boolean | number} Parallel
  127. */
  128. /**
  129. * @typedef {object} BasePluginOptions
  130. * @property {Rules=} test test rule
  131. * @property {Rules=} include include rile
  132. * @property {Rules=} exclude exclude rule
  133. * @property {ExtractCommentsOptions=} extractComments extract comments options
  134. * @property {Parallel=} parallel parallel option
  135. */
  136. /**
  137. * @template T
  138. * @typedef {T extends import("terser").MinifyOptions ? { minify?: MinimizerImplementation<T> | undefined, terserOptions?: MinimizerOptions<T> | undefined } : { minify: MinimizerImplementation<T>, terserOptions?: MinimizerOptions<T> | undefined }} DefinedDefaultMinimizerAndOptions
  139. */
  140. /**
  141. * @template T
  142. * @typedef {BasePluginOptions & { minimizer: { implementation: MinimizerImplementation<T>, options: MinimizerOptions<T> } }} InternalPluginOptions
  143. */
  144. const getTraceMapping = memoize(() => require("@jridgewell/trace-mapping"));
  145. const getSerializeJavascript = memoize(() => require("./serialize-javascript"));
  146. /**
  147. * @template [T=import("terser").MinifyOptions]
  148. */
  149. class TerserPlugin {
  150. /**
  151. * @param {BasePluginOptions & DefinedDefaultMinimizerAndOptions<T>=} options options
  152. */
  153. constructor(options) {
  154. validate(/** @type {Schema} */schema, options || {}, {
  155. name: "Terser Plugin",
  156. baseDataPath: "options"
  157. });
  158. // TODO handle json and etc in the next major release
  159. // TODO make `minimizer` option instead `minify` and `terserOptions` in the next major release, also rename `terserMinify` to `terserMinimize`
  160. const {
  161. minify = (/** @type {MinimizerImplementation<T>} */terserMinify),
  162. terserOptions = (/** @type {MinimizerOptions<T>} */{}),
  163. test = /\.[cm]?js(\?.*)?$/i,
  164. extractComments = true,
  165. parallel = true,
  166. include,
  167. exclude
  168. } = options || {};
  169. /**
  170. * @private
  171. * @type {InternalPluginOptions<T>}
  172. */
  173. this.options = {
  174. test,
  175. extractComments,
  176. parallel,
  177. include,
  178. exclude,
  179. minimizer: {
  180. implementation: minify,
  181. options: terserOptions
  182. }
  183. };
  184. }
  185. /**
  186. * @private
  187. * @param {unknown} input Input to check
  188. * @returns {boolean} Whether input is a source map
  189. */
  190. static isSourceMap(input) {
  191. // All required options for `new TraceMap(...options)`
  192. // https://github.com/jridgewell/trace-mapping#usage
  193. return Boolean(input && typeof input === "object" && input !== null && "version" in input && "sources" in input && Array.isArray(input.sources) && "mappings" in input && typeof input.mappings === "string");
  194. }
  195. /**
  196. * @private
  197. * @param {unknown} warning warning
  198. * @param {string} file file
  199. * @returns {Error} built warning
  200. */
  201. static buildWarning(warning, file) {
  202. /**
  203. * @type {Error & { hideStack: true, file: string }}
  204. */
  205. // @ts-expect-error
  206. const builtWarning = new Error(warning.toString());
  207. builtWarning.name = "Warning";
  208. builtWarning.hideStack = true;
  209. builtWarning.file = file;
  210. return builtWarning;
  211. }
  212. /**
  213. * @private
  214. * @param {Error | ErrorObject | string} error error
  215. * @param {string} file file
  216. * @param {TraceMap=} sourceMap source map
  217. * @param {Compilation["requestShortener"]=} requestShortener request shortener
  218. * @returns {Error} built error
  219. */
  220. static buildError(error, file, sourceMap, requestShortener) {
  221. /**
  222. * @type {Error & { file?: string }}
  223. */
  224. let builtError;
  225. if (typeof error === "string") {
  226. builtError = new Error(`${file} from Terser plugin\n${error}`);
  227. builtError.file = file;
  228. return builtError;
  229. }
  230. if (/** @type {ErrorObject} */error.line) {
  231. const {
  232. line,
  233. column
  234. } = /** @type {ErrorObject & { line: number, column: number }} */error;
  235. const original = sourceMap && getTraceMapping().originalPositionFor(sourceMap, {
  236. line,
  237. column
  238. });
  239. if (original && original.source && requestShortener) {
  240. builtError = new Error(`${file} from Terser plugin\n${error.message} [${requestShortener.shorten(original.source)}:${original.line},${original.column}][${file}:${line},${column}]${error.stack ? `\n${error.stack.split("\n").slice(1).join("\n")}` : ""}`);
  241. builtError.file = file;
  242. return builtError;
  243. }
  244. builtError = new Error(`${file} from Terser plugin\n${error.message} [${file}:${line},${column}]${error.stack ? `\n${error.stack.split("\n").slice(1).join("\n")}` : ""}`);
  245. builtError.file = file;
  246. return builtError;
  247. }
  248. if (error.stack) {
  249. builtError = new Error(`${file} from Terser plugin\n${typeof error.message !== "undefined" ? error.message : ""}\n${error.stack}`);
  250. builtError.file = file;
  251. return builtError;
  252. }
  253. builtError = new Error(`${file} from Terser plugin\n${error.message}`);
  254. builtError.file = file;
  255. return builtError;
  256. }
  257. /**
  258. * @private
  259. * @param {Parallel} parallel value of the `parallel` option
  260. * @returns {number} number of cores for parallelism
  261. */
  262. static getAvailableNumberOfCores(parallel) {
  263. // In some cases cpus() returns undefined
  264. // https://github.com/nodejs/node/issues/19022
  265. const cpus =
  266. // eslint-disable-next-line n/no-unsupported-features/node-builtins
  267. typeof os.availableParallelism === "function" ?
  268. // eslint-disable-next-line n/no-unsupported-features/node-builtins
  269. {
  270. length: os.availableParallelism()
  271. } : os.cpus() || {
  272. length: 1
  273. };
  274. return parallel === true || typeof parallel === "undefined" ? cpus.length - 1 : Math.min(parallel || 0, cpus.length - 1);
  275. }
  276. /**
  277. * @private
  278. * @param {Compiler} compiler compiler
  279. * @param {Compilation} compilation compilation
  280. * @param {Record<string, import("webpack").sources.Source>} assets assets
  281. * @param {{ availableNumberOfCores: number }} optimizeOptions optimize options
  282. * @returns {Promise<void>}
  283. */
  284. async optimize(compiler, compilation, assets, optimizeOptions) {
  285. const cache = compilation.getCache("TerserWebpackPlugin");
  286. let numberOfAssets = 0;
  287. const assetsForMinify = await Promise.all(Object.keys(assets).filter(name => {
  288. const {
  289. info
  290. } = /** @type {Asset} */compilation.getAsset(name);
  291. if (
  292. // Skip double minimize assets from child compilation
  293. info.minimized ||
  294. // Skip minimizing for extracted comments assets
  295. info.extractedComments) {
  296. return false;
  297. }
  298. if (!compiler.webpack.ModuleFilenameHelpers.matchObject.bind(undefined, this.options)(name)) {
  299. return false;
  300. }
  301. return true;
  302. }).map(async name => {
  303. const {
  304. info,
  305. source
  306. } = /** @type {Asset} */
  307. compilation.getAsset(name);
  308. const eTag = cache.getLazyHashedEtag(source);
  309. const cacheItem = cache.getItemCache(name, eTag);
  310. const output = await cacheItem.getPromise();
  311. if (!output) {
  312. numberOfAssets += 1;
  313. }
  314. return {
  315. name,
  316. info,
  317. inputSource: source,
  318. output,
  319. cacheItem
  320. };
  321. }));
  322. if (assetsForMinify.length === 0) {
  323. return;
  324. }
  325. /** @type {undefined | (() => MinimizerWorker<T>)} */
  326. let getWorker;
  327. /** @type {undefined | MinimizerWorker<T>} */
  328. let initializedWorker;
  329. /** @type {undefined | number} */
  330. let numberOfWorkers;
  331. const needCreateWorker = optimizeOptions.availableNumberOfCores > 0 && (typeof this.options.minimizer.implementation.supportsWorker === "undefined" || typeof this.options.minimizer.implementation.supportsWorker === "function" && this.options.minimizer.implementation.supportsWorker());
  332. if (needCreateWorker) {
  333. // Do not create unnecessary workers when the number of files is less than the available cores, it saves memory
  334. numberOfWorkers = Math.min(numberOfAssets, optimizeOptions.availableNumberOfCores);
  335. getWorker = () => {
  336. if (initializedWorker) {
  337. return initializedWorker;
  338. }
  339. const {
  340. Worker
  341. } = require("jest-worker");
  342. initializedWorker = /** @type {MinimizerWorker<T>} */
  343. new Worker(require.resolve("./minify"), {
  344. numWorkers: numberOfWorkers,
  345. enableWorkerThreads: typeof this.options.minimizer.implementation.supportsWorkerThreads !== "undefined" ? this.options.minimizer.implementation.supportsWorkerThreads() !== false : true
  346. });
  347. // https://github.com/facebook/jest/issues/8872#issuecomment-524822081
  348. const workerStdout = initializedWorker.getStdout();
  349. if (workerStdout) {
  350. workerStdout.on("data", chunk => process.stdout.write(chunk));
  351. }
  352. const workerStderr = initializedWorker.getStderr();
  353. if (workerStderr) {
  354. workerStderr.on("data", chunk => process.stderr.write(chunk));
  355. }
  356. return initializedWorker;
  357. };
  358. }
  359. const {
  360. SourceMapSource,
  361. ConcatSource,
  362. RawSource
  363. } = compiler.webpack.sources;
  364. /** @typedef {{ extractedCommentsSource: import("webpack").sources.RawSource, commentsFilename: string }} ExtractedCommentsInfo */
  365. /** @type {Map<string, ExtractedCommentsInfo>} */
  366. const allExtractedComments = new Map();
  367. const scheduledTasks = [];
  368. for (const asset of assetsForMinify) {
  369. scheduledTasks.push(async () => {
  370. const {
  371. name,
  372. inputSource,
  373. info,
  374. cacheItem
  375. } = asset;
  376. let {
  377. output
  378. } = asset;
  379. if (!output) {
  380. let input;
  381. /** @type {RawSourceMap | undefined} */
  382. let inputSourceMap;
  383. const {
  384. source: sourceFromInputSource,
  385. map
  386. } = inputSource.sourceAndMap();
  387. input = sourceFromInputSource;
  388. if (map) {
  389. if (!TerserPlugin.isSourceMap(map)) {
  390. compilation.warnings.push(new Error(`${name} contains invalid source map`));
  391. } else {
  392. inputSourceMap = /** @type {RawSourceMap} */map;
  393. }
  394. }
  395. if (Buffer.isBuffer(input)) {
  396. input = input.toString();
  397. }
  398. /**
  399. * @type {InternalOptions<T>}
  400. */
  401. const options = {
  402. name,
  403. input,
  404. inputSourceMap,
  405. minimizer: {
  406. implementation: this.options.minimizer.implementation,
  407. options: {
  408. ...this.options.minimizer.options
  409. }
  410. },
  411. extractComments: this.options.extractComments
  412. };
  413. if (typeof options.minimizer.options.module === "undefined") {
  414. if (typeof info.javascriptModule !== "undefined") {
  415. options.minimizer.options.module = /** @type {PredefinedOptions<T>["module"]} */
  416. info.javascriptModule;
  417. } else if (/\.mjs(\?.*)?$/i.test(name)) {
  418. options.minimizer.options.module = /** @type {PredefinedOptions<T>["module"]} */true;
  419. } else if (/\.cjs(\?.*)?$/i.test(name)) {
  420. options.minimizer.options.module = /** @type {PredefinedOptions<T>["module"]} */false;
  421. }
  422. }
  423. if (typeof options.minimizer.options.ecma === "undefined") {
  424. options.minimizer.options.ecma = /** @type {PredefinedOptions<T>["ecma"]} */
  425. TerserPlugin.getEcmaVersion(compiler.options.output.environment || {});
  426. }
  427. try {
  428. output = await (getWorker ? getWorker().transform(getSerializeJavascript()(options)) : minify(options));
  429. } catch (error) {
  430. const hasSourceMap = inputSourceMap && TerserPlugin.isSourceMap(inputSourceMap);
  431. compilation.errors.push(TerserPlugin.buildError(/** @type {Error | ErrorObject | string} */
  432. error, name, hasSourceMap ? new (getTraceMapping().TraceMap)(/** @type {RawSourceMap} */
  433. inputSourceMap) : undefined, hasSourceMap ? compilation.requestShortener : undefined));
  434. return;
  435. }
  436. if (typeof output.code === "undefined") {
  437. compilation.errors.push(new Error(`${name} from Terser plugin\nMinimizer doesn't return result`));
  438. }
  439. if (output.warnings && output.warnings.length > 0) {
  440. output.warnings = output.warnings.map(
  441. /**
  442. * @param {Error | string} item a warning
  443. * @returns {Error} built warning with extra info
  444. */
  445. item => TerserPlugin.buildWarning(item, name));
  446. }
  447. if (output.errors && output.errors.length > 0) {
  448. const hasSourceMap = inputSourceMap && TerserPlugin.isSourceMap(inputSourceMap);
  449. output.errors = output.errors.map(
  450. /**
  451. * @param {Error | string} item an error
  452. * @returns {Error} built error with extra info
  453. */
  454. item => TerserPlugin.buildError(item, name, hasSourceMap ? new (getTraceMapping().TraceMap)(/** @type {RawSourceMap} */
  455. inputSourceMap) : undefined, hasSourceMap ? compilation.requestShortener : undefined));
  456. }
  457. // Custom functions can return `undefined` or `null`
  458. if (typeof output.code !== "undefined" && output.code !== null) {
  459. let shebang;
  460. if (/** @type {ExtractCommentsObject} */
  461. this.options.extractComments.banner !== false && output.extractedComments && output.extractedComments.length > 0 && output.code.startsWith("#!")) {
  462. const firstNewlinePosition = output.code.indexOf("\n");
  463. shebang = output.code.slice(0, Math.max(0, firstNewlinePosition));
  464. output.code = output.code.slice(Math.max(0, firstNewlinePosition + 1));
  465. }
  466. if (output.map) {
  467. output.source = new SourceMapSource(output.code, name, output.map, input, /** @type {RawSourceMap} */
  468. inputSourceMap, true);
  469. } else {
  470. output.source = new RawSource(output.code);
  471. }
  472. if (output.extractedComments && output.extractedComments.length > 0) {
  473. const commentsFilename = /** @type {ExtractCommentsObject} */
  474. this.options.extractComments.filename || "[file].LICENSE.txt[query]";
  475. let query = "";
  476. let filename = name;
  477. const querySplit = filename.indexOf("?");
  478. if (querySplit >= 0) {
  479. query = filename.slice(querySplit);
  480. filename = filename.slice(0, querySplit);
  481. }
  482. const lastSlashIndex = filename.lastIndexOf("/");
  483. const basename = lastSlashIndex === -1 ? filename : filename.slice(lastSlashIndex + 1);
  484. const data = {
  485. filename,
  486. basename,
  487. query
  488. };
  489. output.commentsFilename = compilation.getPath(commentsFilename, data);
  490. let banner;
  491. // Add a banner to the original file
  492. if (/** @type {ExtractCommentsObject} */
  493. this.options.extractComments.banner !== false) {
  494. banner = /** @type {ExtractCommentsObject} */
  495. this.options.extractComments.banner || `For license information please see ${path.relative(path.dirname(name), output.commentsFilename).replace(/\\/g, "/")}`;
  496. if (typeof banner === "function") {
  497. banner = banner(output.commentsFilename);
  498. }
  499. if (banner) {
  500. output.source = new ConcatSource(shebang ? `${shebang}\n` : "", `/*! ${banner} */\n`, output.source);
  501. }
  502. }
  503. const extractedCommentsString = output.extractedComments.sort().join("\n\n");
  504. output.extractedCommentsSource = new RawSource(`${extractedCommentsString}\n`);
  505. }
  506. }
  507. await cacheItem.storePromise({
  508. source: output.source,
  509. errors: output.errors,
  510. warnings: output.warnings,
  511. commentsFilename: output.commentsFilename,
  512. extractedCommentsSource: output.extractedCommentsSource
  513. });
  514. }
  515. if (output.warnings && output.warnings.length > 0) {
  516. for (const warning of output.warnings) {
  517. compilation.warnings.push(warning);
  518. }
  519. }
  520. if (output.errors && output.errors.length > 0) {
  521. for (const error of output.errors) {
  522. compilation.errors.push(error);
  523. }
  524. }
  525. if (!output.source) {
  526. return;
  527. }
  528. /** @type {AssetInfo} */
  529. const newInfo = {
  530. minimized: true
  531. };
  532. const {
  533. source,
  534. extractedCommentsSource
  535. } = output;
  536. // Write extracted comments to commentsFilename
  537. if (extractedCommentsSource) {
  538. const {
  539. commentsFilename
  540. } = output;
  541. newInfo.related = {
  542. license: commentsFilename
  543. };
  544. allExtractedComments.set(name, {
  545. extractedCommentsSource,
  546. commentsFilename
  547. });
  548. }
  549. compilation.updateAsset(name, source, newInfo);
  550. });
  551. }
  552. const limit = getWorker && numberOfAssets > 0 ? (/** @type {number} */numberOfWorkers) : scheduledTasks.length;
  553. await throttleAll(limit, scheduledTasks);
  554. if (initializedWorker) {
  555. await initializedWorker.end();
  556. }
  557. /** @typedef {{ source: import("webpack").sources.Source, commentsFilename: string, from: string }} ExtractedCommentsInfoWithFrom */
  558. await [...allExtractedComments].sort().reduce(
  559. /**
  560. * @param {Promise<unknown>} previousPromise previous result
  561. * @param {[string, ExtractedCommentsInfo]} extractedComments extracted comments
  562. * @returns {Promise<ExtractedCommentsInfoWithFrom>} extract comments with info
  563. */
  564. async (previousPromise, [from, value]) => {
  565. const previous = /** @type {ExtractedCommentsInfoWithFrom | undefined} * */
  566. await previousPromise;
  567. const {
  568. commentsFilename,
  569. extractedCommentsSource
  570. } = value;
  571. if (previous && previous.commentsFilename === commentsFilename) {
  572. const {
  573. from: previousFrom,
  574. source: prevSource
  575. } = previous;
  576. const mergedName = `${previousFrom}|${from}`;
  577. const name = `${commentsFilename}|${mergedName}`;
  578. const eTag = [prevSource, extractedCommentsSource].map(item => cache.getLazyHashedEtag(item)).reduce((previousValue, currentValue) => cache.mergeEtags(previousValue, currentValue));
  579. let source = await cache.getPromise(name, eTag);
  580. if (!source) {
  581. source = new ConcatSource([...new Set([... /** @type {string} */prevSource.source().split("\n\n"), ... /** @type {string} */extractedCommentsSource.source().split("\n\n")])].join("\n\n"));
  582. await cache.storePromise(name, eTag, source);
  583. }
  584. compilation.updateAsset(commentsFilename, source);
  585. return {
  586. source,
  587. commentsFilename,
  588. from: mergedName
  589. };
  590. }
  591. const existingAsset = compilation.getAsset(commentsFilename);
  592. if (existingAsset) {
  593. return {
  594. source: existingAsset.source,
  595. commentsFilename,
  596. from: commentsFilename
  597. };
  598. }
  599. compilation.emitAsset(commentsFilename, extractedCommentsSource, {
  600. extractedComments: true
  601. });
  602. return {
  603. source: extractedCommentsSource,
  604. commentsFilename,
  605. from
  606. };
  607. }, /** @type {Promise<unknown>} */Promise.resolve());
  608. }
  609. /**
  610. * @private
  611. * @param {NonNullable<NonNullable<Configuration["output"]>["environment"]>} environment environment
  612. * @returns {number} ecma version
  613. */
  614. static getEcmaVersion(environment) {
  615. // ES 6th
  616. if (environment.arrowFunction || environment.const || environment.destructuring || environment.forOf || environment.module) {
  617. return 2015;
  618. }
  619. // ES 11th
  620. if (environment.bigIntLiteral || environment.dynamicImport) {
  621. return 2020;
  622. }
  623. return 5;
  624. }
  625. /**
  626. * @param {Compiler} compiler compiler
  627. * @returns {void}
  628. */
  629. apply(compiler) {
  630. const pluginName = this.constructor.name;
  631. const availableNumberOfCores = TerserPlugin.getAvailableNumberOfCores(this.options.parallel);
  632. compiler.hooks.compilation.tap(pluginName, compilation => {
  633. const hooks = compiler.webpack.javascript.JavascriptModulesPlugin.getCompilationHooks(compilation);
  634. const data = getSerializeJavascript()({
  635. minimizer: typeof this.options.minimizer.implementation.getMinimizerVersion !== "undefined" ? this.options.minimizer.implementation.getMinimizerVersion() || "0.0.0" : "0.0.0",
  636. options: this.options.minimizer.options
  637. });
  638. hooks.chunkHash.tap(pluginName, (chunk, hash) => {
  639. hash.update("TerserPlugin");
  640. hash.update(data);
  641. });
  642. compilation.hooks.processAssets.tapPromise({
  643. name: pluginName,
  644. stage: compiler.webpack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_SIZE,
  645. additionalAssets: true
  646. }, assets => this.optimize(compiler, compilation, assets, {
  647. availableNumberOfCores
  648. }));
  649. compilation.hooks.statsPrinter.tap(pluginName, stats => {
  650. stats.hooks.print.for("asset.info.minimized").tap("terser-webpack-plugin", (minimized, {
  651. green,
  652. formatFlag
  653. }) => minimized ? /** @type {(text: string) => string} */green(/** @type {(flag: string) => string} */formatFlag("minimized")) : "");
  654. });
  655. });
  656. }
  657. }
  658. TerserPlugin.terserMinify = terserMinify;
  659. TerserPlugin.uglifyJsMinify = uglifyJsMinify;
  660. TerserPlugin.swcMinify = swcMinify;
  661. TerserPlugin.esbuildMinify = esbuildMinify;
  662. TerserPlugin.jsonMinify = jsonMinify;
  663. module.exports = TerserPlugin;