CleanPlugin.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Sergey Melyukov @smelukov
  4. */
  5. "use strict";
  6. const path = require("path");
  7. const asyncLib = require("neo-async");
  8. const { SyncBailHook } = require("tapable");
  9. const createHooksRegistry = require("./util/createHooksRegistry");
  10. const { join } = require("./util/fs");
  11. const { ABSOLUTE_PATH_REGEXP } = require("./util/identifier");
  12. const processAsyncTree = require("./util/processAsyncTree");
  13. /** @import { CleanOptions } from "../declarations/WebpackOptions" */
  14. /** @import Compiler from "./Compiler" */
  15. /** @import { Logger } from "./logging/Logger" */
  16. /** @import { IStats, OutputFileSystem, StatsCallback } from "./util/fs" */
  17. /** @typedef {Map<string, number>} Assets */
  18. const createCompilationHooks = () => ({
  19. /**
  20. * When returning true the file/directory will be kept during cleaning, returning false will clean it and ignore the following plugins and config.
  21. * @type {SyncBailHook<[string], boolean | void>}
  22. * @since 5.20.0
  23. */
  24. keep: new SyncBailHook(["ignore"])
  25. });
  26. /**
  27. * @typedef {ReturnType<typeof createCompilationHooks>} CleanPluginCompilationHooks
  28. */
  29. /**
  30. * Defines the keep fn callback.
  31. * @callback KeepFn
  32. * @param {string} path path
  33. * @returns {boolean | undefined} true, if the path should be kept
  34. */
  35. const _10sec = 10 * 1000;
  36. /**
  37. * merge assets map 2 into map 1
  38. * @param {Assets} as1 assets
  39. * @param {Assets} as2 assets
  40. * @returns {void}
  41. */
  42. const mergeAssets = (as1, as2) => {
  43. for (const [key, value1] of as2) {
  44. const value2 = as1.get(key);
  45. if (!value2 || value1 > value2) as1.set(key, value1);
  46. }
  47. };
  48. /** @typedef {Map<string, number>} CurrentAssets */
  49. /**
  50. * Returns set of directory paths.
  51. * @param {CurrentAssets} assets current assets
  52. * @returns {Set<string>} Set of directory paths
  53. */
  54. function getDirectories(assets) {
  55. /** @type {Set<string>} */
  56. const directories = new Set();
  57. /**
  58. * Adds the provided filename to this object.
  59. * @param {string} filename asset filename
  60. */
  61. const addDirectory = (filename) => {
  62. directories.add(path.dirname(filename));
  63. };
  64. // get directories of assets
  65. for (const [asset] of assets) {
  66. addDirectory(asset);
  67. }
  68. // and all parent directories
  69. for (const directory of directories) {
  70. addDirectory(directory);
  71. }
  72. return directories;
  73. }
  74. /** @typedef {Set<string>} Diff */
  75. /**
  76. * Returns diff to fs.
  77. * @param {OutputFileSystem} fs filesystem
  78. * @param {string} outputPath output path
  79. * @param {CurrentAssets} currentAssets filename of the current assets (must not start with .. or ., must only use / as path separator)
  80. * @param {(err?: Error | null, set?: Diff) => void} callback returns the filenames of the assets that shouldn't be there
  81. * @returns {void}
  82. */
  83. const getDiffToFs = (fs, outputPath, currentAssets, callback) => {
  84. const directories = getDirectories(currentAssets);
  85. /** @type {Diff} */
  86. const diff = new Set();
  87. asyncLib.forEachLimit(
  88. directories,
  89. 10,
  90. (directory, callback) => {
  91. /** @type {NonNullable<OutputFileSystem["readdir"]>} */
  92. (fs.readdir)(join(fs, outputPath, directory), (err, entries) => {
  93. if (err) {
  94. if (err.code === "ENOENT") return callback();
  95. if (err.code === "ENOTDIR") {
  96. diff.add(directory);
  97. return callback();
  98. }
  99. return callback(err);
  100. }
  101. for (const entry of /** @type {string[]} */ (entries)) {
  102. const file = entry;
  103. // Since path.normalize("./file") === path.normalize("file"),
  104. // return file directly when directory === "."
  105. const filename =
  106. directory && directory !== "." ? `${directory}/${file}` : file;
  107. if (!directories.has(filename) && !currentAssets.has(filename)) {
  108. diff.add(filename);
  109. }
  110. }
  111. callback();
  112. });
  113. },
  114. (err) => {
  115. if (err) return callback(err);
  116. callback(null, diff);
  117. }
  118. );
  119. };
  120. /**
  121. * Gets diff to old assets.
  122. * @param {Assets} currentAssets assets list
  123. * @param {Assets} oldAssets old assets list
  124. * @returns {Diff} diff
  125. */
  126. const getDiffToOldAssets = (currentAssets, oldAssets) => {
  127. /** @type {Diff} */
  128. const diff = new Set();
  129. const now = Date.now();
  130. for (const [asset, ts] of oldAssets) {
  131. if (ts >= now) continue;
  132. if (!currentAssets.has(asset)) diff.add(asset);
  133. }
  134. return diff;
  135. };
  136. /**
  137. * Processes the provided f.
  138. * @param {OutputFileSystem} fs filesystem
  139. * @param {string} filename path to file
  140. * @param {StatsCallback} callback callback for provided filename
  141. * @returns {void}
  142. */
  143. const doStat = (fs, filename, callback) => {
  144. if ("lstat" in fs) {
  145. /** @type {NonNullable<OutputFileSystem["lstat"]>} */
  146. (fs.lstat)(filename, callback);
  147. } else {
  148. fs.stat(filename, callback);
  149. }
  150. };
  151. /**
  152. * Processes the provided f.
  153. * @param {OutputFileSystem} fs filesystem
  154. * @param {string} outputPath output path
  155. * @param {boolean} dry only log instead of fs modification
  156. * @param {Logger} logger logger
  157. * @param {Diff} diff filenames of the assets that shouldn't be there
  158. * @param {KeepFn} isKept check if the entry is ignored
  159. * @param {(err?: Error, assets?: Assets) => void} callback callback
  160. * @returns {void}
  161. */
  162. const applyDiff = (fs, outputPath, dry, logger, diff, isKept, callback) => {
  163. /**
  164. * Processes the provided msg.
  165. * @param {string} msg message
  166. */
  167. const log = (msg) => {
  168. if (dry) {
  169. logger.info(msg);
  170. } else {
  171. logger.log(msg);
  172. }
  173. };
  174. /** @typedef {{ type: "check" | "unlink" | "rmdir", filename: string, parent: { remaining: number, job: Job } | undefined }} Job */
  175. /** @type {Job[]} */
  176. const jobs = Array.from(diff.keys(), (filename) => ({
  177. type: "check",
  178. filename,
  179. parent: undefined
  180. }));
  181. /** @type {Assets} */
  182. const keptAssets = new Map();
  183. processAsyncTree(
  184. jobs,
  185. 10,
  186. ({ type, filename, parent }, push, callback) => {
  187. const path = join(fs, outputPath, filename);
  188. /**
  189. * Describes how this handle error operation behaves.
  190. * @param {Error & { code?: string }} err error
  191. * @returns {void}
  192. */
  193. const handleError = (err) => {
  194. const isAlreadyRemoved = () =>
  195. new Promise((resolve) => {
  196. if (err.code === "ENOENT") {
  197. resolve(true);
  198. } else if (err.code === "EPERM") {
  199. // https://github.com/isaacs/rimraf/blob/main/src/fix-eperm.ts#L37
  200. // fs.existsSync(path) === false https://github.com/webpack/webpack/actions/runs/15493412975/job/43624272783?pr=19586
  201. doStat(fs, path, (err) => {
  202. if (err) {
  203. resolve(err.code === "ENOENT");
  204. } else {
  205. resolve(false);
  206. }
  207. });
  208. } else {
  209. resolve(false);
  210. }
  211. });
  212. isAlreadyRemoved().then((isRemoved) => {
  213. if (isRemoved) {
  214. log(`${filename} was removed during cleaning by something else`);
  215. handleParent();
  216. return callback();
  217. }
  218. return callback(err);
  219. });
  220. };
  221. const handleParent = () => {
  222. if (parent && --parent.remaining === 0) push(parent.job);
  223. };
  224. switch (type) {
  225. case "check":
  226. if (isKept(filename)) {
  227. keptAssets.set(filename, 0);
  228. // do not decrement parent entry as we don't want to delete the parent
  229. log(`${filename} will be kept`);
  230. return process.nextTick(callback);
  231. }
  232. doStat(fs, path, (err, stats) => {
  233. if (err) return handleError(err);
  234. if (!(/** @type {IStats} */ (stats).isDirectory())) {
  235. push({
  236. type: "unlink",
  237. filename,
  238. parent
  239. });
  240. return callback();
  241. }
  242. /** @type {NonNullable<OutputFileSystem["readdir"]>} */
  243. (fs.readdir)(path, (err, _entries) => {
  244. if (err) return handleError(err);
  245. /** @type {Job} */
  246. const deleteJob = {
  247. type: "rmdir",
  248. filename,
  249. parent
  250. };
  251. const entries = /** @type {string[]} */ (_entries);
  252. if (entries.length === 0) {
  253. push(deleteJob);
  254. } else {
  255. const parentToken = {
  256. remaining: entries.length,
  257. job: deleteJob
  258. };
  259. for (const entry of entries) {
  260. const file = /** @type {string} */ (entry);
  261. if (file.startsWith(".")) {
  262. log(
  263. `${filename} will be kept (dot-files will never be removed)`
  264. );
  265. continue;
  266. }
  267. push({
  268. type: "check",
  269. filename: `${filename}/${file}`,
  270. parent: parentToken
  271. });
  272. }
  273. }
  274. return callback();
  275. });
  276. });
  277. break;
  278. case "rmdir":
  279. log(`${filename} will be removed`);
  280. if (dry) {
  281. handleParent();
  282. return process.nextTick(callback);
  283. }
  284. if (!fs.rmdir) {
  285. logger.warn(
  286. `${filename} can't be removed because output file system doesn't support removing directories (rmdir)`
  287. );
  288. return process.nextTick(callback);
  289. }
  290. fs.rmdir(path, (err) => {
  291. if (err) return handleError(err);
  292. handleParent();
  293. callback();
  294. });
  295. break;
  296. case "unlink":
  297. log(`${filename} will be removed`);
  298. if (dry) {
  299. handleParent();
  300. return process.nextTick(callback);
  301. }
  302. if (!fs.unlink) {
  303. logger.warn(
  304. `${filename} can't be removed because output file system doesn't support removing files (rmdir)`
  305. );
  306. return process.nextTick(callback);
  307. }
  308. fs.unlink(path, (err) => {
  309. if (err) return handleError(err);
  310. handleParent();
  311. callback();
  312. });
  313. break;
  314. }
  315. },
  316. (err) => {
  317. if (err) return callback(err);
  318. callback(undefined, keptAssets);
  319. }
  320. );
  321. };
  322. const PLUGIN_NAME = "CleanPlugin";
  323. class CleanPlugin {
  324. /** @param {CleanOptions} options options */
  325. constructor(options = {}) {
  326. /** @type {CleanOptions} */
  327. this.options = options;
  328. }
  329. /**
  330. * Applies the plugin by registering its hooks on the compiler.
  331. * @param {Compiler} compiler the compiler instance
  332. * @returns {void}
  333. */
  334. apply(compiler) {
  335. compiler.hooks.validate.tap(PLUGIN_NAME, () => {
  336. compiler.validate(
  337. () => {
  338. const { definitions } = require("../schemas/WebpackOptions.json");
  339. return {
  340. definitions,
  341. oneOf: [{ $ref: "#/definitions/CleanOptions" }]
  342. };
  343. },
  344. this.options,
  345. {
  346. name: "Clean Plugin",
  347. baseDataPath: "options"
  348. }
  349. );
  350. });
  351. const { keep } = this.options;
  352. /** @type {boolean} */
  353. const dry = this.options.dry || false;
  354. /** @type {KeepFn} */
  355. const keepFn =
  356. typeof keep === "function"
  357. ? keep
  358. : typeof keep === "string"
  359. ? (path) => path.startsWith(keep)
  360. : typeof keep === "object" && keep.test
  361. ? (path) => keep.test(path)
  362. : () => false;
  363. // We assume that no external modification happens while the compiler is active
  364. // So we can store the old assets and only diff to them to avoid fs access on
  365. // incremental builds
  366. /** @type {undefined | Assets} */
  367. let oldAssets;
  368. compiler.hooks.emit.tapAsync(
  369. {
  370. name: PLUGIN_NAME,
  371. stage: 100
  372. },
  373. (compilation, callback) => {
  374. const hooks = CleanPlugin.getCompilationHooks(compilation);
  375. const logger = compilation.getLogger(`webpack.${PLUGIN_NAME}`);
  376. const fs = /** @type {OutputFileSystem} */ (compiler.outputFileSystem);
  377. if (!fs.readdir) {
  378. return callback(
  379. new Error(
  380. `${PLUGIN_NAME}: Output filesystem doesn't support listing directories (readdir)`
  381. )
  382. );
  383. }
  384. /** @type {Assets} */
  385. const currentAssets = new Map();
  386. const now = Date.now();
  387. for (const asset of Object.keys(compilation.assets)) {
  388. if (ABSOLUTE_PATH_REGEXP.test(asset)) continue;
  389. /** @type {string} */
  390. let normalizedAsset;
  391. let newNormalizedAsset = asset.replace(/\\/g, "/");
  392. do {
  393. normalizedAsset = newNormalizedAsset;
  394. newNormalizedAsset = normalizedAsset.replace(
  395. /(^|\/)(?!\.\.)[^/]+\/\.\.\//g,
  396. "$1"
  397. );
  398. } while (newNormalizedAsset !== normalizedAsset);
  399. if (normalizedAsset.startsWith("../")) continue;
  400. const assetInfo = compilation.assetsInfo.get(asset);
  401. if (assetInfo && assetInfo.hotModuleReplacement) {
  402. currentAssets.set(normalizedAsset, now + _10sec);
  403. } else {
  404. currentAssets.set(normalizedAsset, 0);
  405. }
  406. }
  407. const outputPath = compilation.getPath(compiler.outputPath, {});
  408. /**
  409. * Checks whether this clean plugin is kept.
  410. * @param {string} path path
  411. * @returns {boolean | undefined} true, if needs to be kept
  412. */
  413. const isKept = (path) => {
  414. const result = hooks.keep.call(path);
  415. if (result !== undefined) return result;
  416. return keepFn(path);
  417. };
  418. /**
  419. * Processes the provided err.
  420. * @param {(Error | null)=} err err
  421. * @param {Diff=} diff diff
  422. */
  423. const diffCallback = (err, diff) => {
  424. if (err) {
  425. oldAssets = undefined;
  426. callback(err);
  427. return;
  428. }
  429. applyDiff(
  430. fs,
  431. outputPath,
  432. dry,
  433. logger,
  434. /** @type {Diff} */ (diff),
  435. isKept,
  436. (err, keptAssets) => {
  437. if (err) {
  438. oldAssets = undefined;
  439. } else {
  440. if (oldAssets) mergeAssets(currentAssets, oldAssets);
  441. oldAssets = currentAssets;
  442. if (keptAssets) mergeAssets(oldAssets, keptAssets);
  443. }
  444. callback(err);
  445. }
  446. );
  447. };
  448. if (oldAssets) {
  449. diffCallback(null, getDiffToOldAssets(currentAssets, oldAssets));
  450. } else {
  451. getDiffToFs(fs, outputPath, currentAssets, diffCallback);
  452. }
  453. }
  454. );
  455. }
  456. }
  457. CleanPlugin.getCompilationHooks = createHooksRegistry(createCompilationHooks);
  458. module.exports = CleanPlugin;