|
| 1 | +"use strict"; |
| 2 | + |
| 3 | +const assert = require("assert"); |
| 4 | +const { NormalModule } = require("../.."); |
| 5 | + |
| 6 | +/** @import { Compiler, LoaderContext } from "../../" */ |
| 7 | +/** @typedef {(error: Error | null, source?: string) => void} LoaderCallback */ |
| 8 | +/** @typedef {LoaderContext<Record<string, never>> & { watchTestBarrier?: (source: string, callback: LoaderCallback) => void }} BarrierLoaderContext */ |
| 9 | + |
| 10 | +/** |
| 11 | + * Pauses the next watch loader after it has read its source. |
| 12 | + * @returns {{ plugin: (compiler: Compiler) => void, arm: () => Promise<void>, release: () => void }} loader barrier |
| 13 | + */ |
| 14 | +const createWatchLoaderBarrier = () => { |
| 15 | + /** @type {(() => void) | undefined} */ |
| 16 | + let reached; |
| 17 | + /** @type {(() => void) | undefined} */ |
| 18 | + let resume; |
| 19 | + return { |
| 20 | + /** |
| 21 | + * @param {Compiler} compiler watched compiler |
| 22 | + * @returns {void} |
| 23 | + */ |
| 24 | + plugin(compiler) { |
| 25 | + compiler.hooks.compilation.tap("WatchLoaderBarrier", (compilation) => { |
| 26 | + if (!compiler.watchMode) return; |
| 27 | + NormalModule.getCompilationHooks(compilation).loader.tap( |
| 28 | + "WatchLoaderBarrier", |
| 29 | + (loaderContext) => { |
| 30 | + /** @type {BarrierLoaderContext} */ ( |
| 31 | + loaderContext |
| 32 | + ).watchTestBarrier = (source, callback) => { |
| 33 | + if (!reached) return callback(null, source); |
| 34 | + resume = () => callback(null, source); |
| 35 | + const notify = reached; |
| 36 | + reached = undefined; |
| 37 | + notify(); |
| 38 | + }; |
| 39 | + } |
| 40 | + ); |
| 41 | + }); |
| 42 | + }, |
| 43 | + /** |
| 44 | + * @returns {Promise<void>} resolves when the next loader is paused |
| 45 | + */ |
| 46 | + arm() { |
| 47 | + assert(!reached && !resume, "A loader barrier is already armed"); |
| 48 | + return new Promise((resolve, reject) => { |
| 49 | + const timeout = setTimeout(() => { |
| 50 | + reached = undefined; |
| 51 | + reject(new Error("Timed out waiting for the watch loader")); |
| 52 | + }, 10000); |
| 53 | + reached = () => { |
| 54 | + clearTimeout(timeout); |
| 55 | + resolve(); |
| 56 | + }; |
| 57 | + }); |
| 58 | + }, |
| 59 | + /** |
| 60 | + * @returns {void} |
| 61 | + */ |
| 62 | + release() { |
| 63 | + const callback = resume; |
| 64 | + resume = undefined; |
| 65 | + if (callback) callback(); |
| 66 | + } |
| 67 | + }; |
| 68 | +}; |
| 69 | + |
| 70 | +module.exports = createWatchLoaderBarrier; |
0 commit comments