|
| 1 | +"use strict"; |
| 2 | + |
| 3 | +/** |
| 4 | + * Asserts the contract `EvalDevToolModulePlugin` relies on: it drops each |
| 5 | + * rendered source's cached copy, and reading that source afterwards still |
| 6 | + * returns the same text. |
| 7 | + * @type {import("../../../../").WebpackPluginInstance} |
| 8 | + */ |
| 9 | +const observeSourceCacheClearing = { |
| 10 | + apply(compiler) { |
| 11 | + const { ExternalModule } = compiler.webpack; |
| 12 | + const { JavascriptModulesPlugin } = compiler.webpack.javascript; |
| 13 | + compiler.hooks.compilation.tap("Observe", (compilation) => { |
| 14 | + /** @type {Map<import("webpack-sources").Source, string>} */ |
| 15 | + const textBefore = new Map(); |
| 16 | + /** @type {Set<import("webpack-sources").Source>} */ |
| 17 | + const cleared = new Set(); |
| 18 | + |
| 19 | + // Registered before EvalDevToolModulePlugin taps, so this sees each |
| 20 | + // original source rather than the eval wrapper replacing it. |
| 21 | + JavascriptModulesPlugin.getCompilationHooks( |
| 22 | + compilation |
| 23 | + ).renderModuleContent.tap("Observe", (source, module) => { |
| 24 | + // The plugin hands an external module's source back untouched, so its |
| 25 | + // cache is never cleared and it is not part of the contract tested here. |
| 26 | + if (module instanceof ExternalModule) return source; |
| 27 | + if (textBefore.has(source)) return source; |
| 28 | + textBefore.set(source, String(source.source())); |
| 29 | + const { clearCache } = source; |
| 30 | + if (typeof clearCache === "function") { |
| 31 | + source.clearCache = (...args) => { |
| 32 | + cleared.add(source); |
| 33 | + return clearCache.apply(source, args); |
| 34 | + }; |
| 35 | + } |
| 36 | + return source; |
| 37 | + }); |
| 38 | + |
| 39 | + compilation.hooks.afterSeal.tap("Observe", () => { |
| 40 | + // A run restoring its assets from the persistent cache renders |
| 41 | + // nothing, so there is nothing to assert; the uncached run asserts it. |
| 42 | + if (textBefore.size === 0) return; |
| 43 | + if (cleared.size !== textBefore.size) { |
| 44 | + compilation.errors.push( |
| 45 | + new Error( |
| 46 | + `Observe: cleared ${cleared.size} of ${textBefore.size} rendered sources` |
| 47 | + ) |
| 48 | + ); |
| 49 | + } |
| 50 | + for (const [source, before] of textBefore) { |
| 51 | + if (String(source.source()) !== before) { |
| 52 | + compilation.errors.push( |
| 53 | + new Error("Observe: a source read differently after clearCache") |
| 54 | + ); |
| 55 | + return; |
| 56 | + } |
| 57 | + } |
| 58 | + }); |
| 59 | + }); |
| 60 | + } |
| 61 | +}; |
| 62 | + |
| 63 | +/** @type {import("../../../../").Configuration} */ |
| 64 | +module.exports = { |
| 65 | + devtool: "eval", |
| 66 | + plugins: [observeSourceCacheClearing] |
| 67 | +}; |
0 commit comments