| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| Author Alexander Akait @alexander-akait | ||
| */ | ||
| "use strict"; | ||
| const NormalModule = require("../NormalModule"); | ||
| const makeSerializable = require("../util/makeSerializable"); | ||
| /** @typedef {import("../Module")} Module */ | ||
| /** @typedef {import("../NormalModule").NormalModuleCreateData} NormalModuleCreateData */ | ||
| /** @typedef {import("../RequestShortener")} RequestShortener */ | ||
| /** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ | ||
| /** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ | ||
| /** @typedef {import("../../declarations/WebpackOptions").CssParserExportType} CssParserExportType */ | ||
| /** @typedef {string | undefined} CssLayer */ | ||
| /** @typedef {string | undefined} Supports */ | ||
| /** @typedef {string | undefined} Media */ | ||
| /** @typedef {[CssLayer, Supports, Media]} InheritanceItem */ | ||
| /** @typedef {InheritanceItem[]} Inheritance */ | ||
| /** @typedef {NormalModuleCreateData & { cssLayer: CssLayer, supports: Supports, media: Media, inheritance?: Inheritance, exportType?: CssParserExportType }} CssModuleCreateData */ | ||
| class CssModule extends NormalModule { | ||
| /** | ||
| * Creates an instance of CssModule. | ||
| * @param {CssModuleCreateData} options options object | ||
| */ | ||
| constructor(options) { | ||
| super(options); | ||
| // Avoid override `layer` for `Module` class, because it is a feature to run module in specific layer | ||
| /** @type {CssModuleCreateData['cssLayer']} */ | ||
| this.cssLayer = options.cssLayer; | ||
| /** @type {CssModuleCreateData['supports']} */ | ||
| this.supports = options.supports; | ||
| /** @type {CssModuleCreateData['media']} */ | ||
| this.media = options.media; | ||
| /** @type {CssModuleCreateData['inheritance']} */ | ||
| this.inheritance = options.inheritance; | ||
| /** @type {CssModuleCreateData['exportType']} */ | ||
| this.exportType = options.exportType; | ||
| } | ||
| /** | ||
| * Returns the unique identifier used to reference this module. | ||
| * @returns {string} a unique identifier of the module | ||
| */ | ||
| identifier() { | ||
| let identifier = super.identifier(); | ||
| if (this.cssLayer) { | ||
| identifier += `|${this.cssLayer}`; | ||
| } | ||
| if (this.supports) { | ||
| identifier += `|${this.supports}`; | ||
| } | ||
| if (this.media) { | ||
| identifier += `|${this.media}`; | ||
| } | ||
| if (this.inheritance) { | ||
| const inheritance = this.inheritance.map( | ||
| (item, index) => | ||
| `inheritance_${index}|${item[0] || ""}|${item[1] || ""}|${ | ||
| item[2] || "" | ||
| }` | ||
| ); | ||
| identifier += `|${inheritance.join("|")}`; | ||
| } | ||
| if (this.exportType) { | ||
| identifier += `|${this.exportType}`; | ||
| } | ||
| // We generate extra code for HMR, so we need to invalidate the module | ||
| if (this.hot) { | ||
| identifier += `|${this.hot}`; | ||
| } | ||
| return identifier; | ||
| } | ||
| /** | ||
| * Returns a human-readable identifier for this module. | ||
| * @param {RequestShortener} requestShortener the request shortener | ||
| * @returns {string} a user readable identifier of the module | ||
| */ | ||
| readableIdentifier(requestShortener) { | ||
| const readableIdentifier = super.readableIdentifier(requestShortener); | ||
| let identifier = `css ${readableIdentifier}`; | ||
| if (this.cssLayer) { | ||
| identifier += ` (layer: ${this.cssLayer})`; | ||
| } | ||
| if (this.supports) { | ||
| identifier += ` (supports: ${this.supports})`; | ||
| } | ||
| if (this.media) { | ||
| identifier += ` (media: ${this.media})`; | ||
| } | ||
| if (this.exportType) { | ||
| identifier += ` (exportType: ${this.exportType})`; | ||
| } | ||
| return identifier; | ||
| } | ||
| /** | ||
| * Assuming this module is in the cache. Update the (cached) module with | ||
| * the fresh module from the factory. Usually updates internal references | ||
| * and properties. | ||
| * @param {Module} module fresh module | ||
| * @returns {void} | ||
| */ | ||
| updateCacheModule(module) { | ||
| super.updateCacheModule(module); | ||
| const m = /** @type {CssModule} */ (module); | ||
| this.cssLayer = m.cssLayer; | ||
| this.supports = m.supports; | ||
| this.media = m.media; | ||
| this.inheritance = m.inheritance; | ||
| this.exportType = m.exportType; | ||
| } | ||
| /** | ||
| * Serializes this instance into the provided serializer context. | ||
| * @param {ObjectSerializerContext} context context | ||
| */ | ||
| serialize(context) { | ||
| const { write } = context; | ||
| write(this.cssLayer); | ||
| write(this.supports); | ||
| write(this.media); | ||
| write(this.inheritance); | ||
| write(this.exportType); | ||
| super.serialize(context); | ||
| } | ||
| /** | ||
| * Restores this instance from the provided deserializer context. | ||
| * @param {ObjectDeserializerContext} context context | ||
| * @returns {CssModule} the deserialized object | ||
| */ | ||
| static deserialize(context) { | ||
| const obj = new CssModule({ | ||
| // will be deserialized by Module | ||
| layer: /** @type {EXPECTED_ANY} */ (null), | ||
| type: "", | ||
| // will be filled by updateCacheModule | ||
| resource: "", | ||
| context: "", | ||
| request: /** @type {EXPECTED_ANY} */ (null), | ||
| userRequest: /** @type {EXPECTED_ANY} */ (null), | ||
| rawRequest: /** @type {EXPECTED_ANY} */ (null), | ||
| loaders: /** @type {EXPECTED_ANY} */ (null), | ||
| matchResource: /** @type {EXPECTED_ANY} */ (null), | ||
| parser: /** @type {EXPECTED_ANY} */ (null), | ||
| parserOptions: /** @type {EXPECTED_ANY} */ (null), | ||
| generator: /** @type {EXPECTED_ANY} */ (null), | ||
| generatorOptions: /** @type {EXPECTED_ANY} */ (null), | ||
| resolveOptions: /** @type {EXPECTED_ANY} */ (null), | ||
| cssLayer: /** @type {EXPECTED_ANY} */ (null), | ||
| supports: /** @type {EXPECTED_ANY} */ (null), | ||
| media: /** @type {EXPECTED_ANY} */ (null), | ||
| inheritance: /** @type {EXPECTED_ANY} */ (null), | ||
| extractSourceMap: /** @type {EXPECTED_ANY} */ (null), | ||
| exportType: /** @type {EXPECTED_ANY} */ (null) | ||
| }); | ||
| obj.deserialize(context); | ||
| return obj; | ||
| } | ||
| /** | ||
| * Restores this instance from the provided deserializer context. | ||
| * @param {ObjectDeserializerContext} context context | ||
| */ | ||
| deserialize(context) { | ||
| const { read } = context; | ||
| this.cssLayer = read(); | ||
| this.supports = read(); | ||
| this.media = read(); | ||
| this.inheritance = read(); | ||
| this.exportType = read(); | ||
| super.deserialize(context); | ||
| } | ||
| } | ||
| makeSerializable(CssModule, "webpack/lib/CssModule"); | ||
| module.exports = CssModule; |
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| */ | ||
| "use strict"; | ||
| const WebpackError = require("../errors/WebpackError"); | ||
| class HarmonyLinkingError extends WebpackError { | ||
| /** @param {string} message Error message */ | ||
| constructor(message) { | ||
| super(message); | ||
| /** @type {string} */ | ||
| this.name = "HarmonyLinkingError"; | ||
| this.hideStack = true; | ||
| } | ||
| } | ||
| module.exports = HarmonyLinkingError; |
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| */ | ||
| "use strict"; | ||
| const makeSerializable = require("../util/makeSerializable"); | ||
| const CssUrlDependency = require("./CssUrlDependency"); | ||
| const ModuleDependency = require("./ModuleDependency"); | ||
| /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ | ||
| /** @typedef {import("../Chunk")} Chunk */ | ||
| /** @typedef {import("../Dependency")} Dependency */ | ||
| /** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ | ||
| /** @typedef {import("../Entrypoint")} Entrypoint */ | ||
| /** @typedef {import("../javascript/JavascriptParser").Range} Range */ | ||
| /** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ | ||
| /** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ | ||
| /** | ||
| * Represents an inline `<script>...</script>` block in an HTML module. The | ||
| * tag's body is bundled as its own entry chunk — the same pipeline that | ||
| * processes `<script src>` — and the inline body is replaced with a | ||
| * `src` attribute pointing at the emitted chunk URL. | ||
| */ | ||
| class HtmlInlineScriptDependency extends ModuleDependency { | ||
| /** | ||
| * Creates an instance of HtmlInlineScriptDependency. | ||
| * @param {string} request virtual request resolving to the inline JS (data URI) | ||
| * @param {number} insertPos position right after `<script` where ` src="…"` is inserted | ||
| * @param {Range} contentRange range of the inline JS body (between `<script>` and `</script>`) | ||
| * @param {string} entryName name of the entry the inline JS is bundled into | ||
| * @param {string=} category dependency category used for resolving and grouping | ||
| */ | ||
| constructor(request, insertPos, contentRange, entryName, category) { | ||
| super(request); | ||
| this.insertPos = insertPos; | ||
| this.contentRange = contentRange; | ||
| this.range = contentRange; | ||
| this.entryName = entryName; | ||
| /** @type {string} */ | ||
| this._category = category || "commonjs"; | ||
| } | ||
| get type() { | ||
| return "html inline script"; | ||
| } | ||
| get category() { | ||
| return this._category; | ||
| } | ||
| /** | ||
| * Serializes this instance into the provided serializer context. | ||
| * @param {ObjectSerializerContext} context context | ||
| */ | ||
| serialize(context) { | ||
| const { write } = context; | ||
| write(this.insertPos); | ||
| write(this.contentRange); | ||
| write(this.entryName); | ||
| write(this._category); | ||
| super.serialize(context); | ||
| } | ||
| /** | ||
| * Restores this instance from the provided deserializer context. | ||
| * @param {ObjectDeserializerContext} context context | ||
| */ | ||
| deserialize(context) { | ||
| const { read } = context; | ||
| this.insertPos = read(); | ||
| this.contentRange = read(); | ||
| this.range = this.contentRange; | ||
| this.entryName = read(); | ||
| this._category = read(); | ||
| super.deserialize(context); | ||
| } | ||
| } | ||
| HtmlInlineScriptDependency.Template = class HtmlInlineScriptDependencyTemplate extends ( | ||
| ModuleDependency.Template | ||
| ) { | ||
| /** | ||
| * Applies the plugin by registering its hooks on the compiler. | ||
| * @param {Dependency} dependency the dependency for which the template should be applied | ||
| * @param {ReplaceSource} source the current replace source which can be modified | ||
| * @param {DependencyTemplateContext} templateContext the context object | ||
| * @returns {void} | ||
| */ | ||
| apply(dependency, source, templateContext) { | ||
| const { runtimeTemplate } = templateContext; | ||
| const dep = /** @type {HtmlInlineScriptDependency} */ (dependency); | ||
| const compilation = runtimeTemplate.compilation; | ||
| const entrypoint = /** @type {Entrypoint | undefined} */ ( | ||
| compilation.entrypoints.get(dep.entryName) | ||
| ); | ||
| /** @type {string} */ | ||
| let url = "data:,"; | ||
| if (entrypoint) { | ||
| const chunk = /** @type {Chunk} */ (entrypoint.getEntrypointChunk()); | ||
| const outputOptions = runtimeTemplate.outputOptions; | ||
| const filenameTemplate = | ||
| chunk.filenameTemplate || | ||
| (chunk.canBeInitial() | ||
| ? outputOptions.filename | ||
| : outputOptions.chunkFilename); | ||
| const filename = compilation.getPath(filenameTemplate, { | ||
| chunk, | ||
| contentHashType: "javascript" | ||
| }); | ||
| url = `${CssUrlDependency.PUBLIC_PATH_AUTO}${filename}`; | ||
| } | ||
| // Insert ` src="…"` right after `<script` so the inline body is | ||
| // served from the emitted chunk instead. The browser ignores the | ||
| // remaining inline body once `src` is present, but we still clear | ||
| // it below so the unprocessed JS doesn't ride along. | ||
| source.insert(dep.insertPos, ` src="${url}"`); | ||
| source.replace(dep.contentRange[0], dep.contentRange[1] - 1, ""); | ||
| } | ||
| }; | ||
| makeSerializable( | ||
| HtmlInlineScriptDependency, | ||
| "webpack/lib/dependencies/HtmlInlineScriptDependency" | ||
| ); | ||
| module.exports = HtmlInlineScriptDependency; |
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| */ | ||
| "use strict"; | ||
| const { CSS_TEXT_TYPE } = require("../ModuleSourceTypeConstants"); | ||
| const makeSerializable = require("../util/makeSerializable"); | ||
| const ModuleDependency = require("./ModuleDependency"); | ||
| /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ | ||
| /** @typedef {import("../CodeGenerationResults")} CodeGenerationResults */ | ||
| /** @typedef {import("../Dependency")} Dependency */ | ||
| /** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ | ||
| /** @typedef {import("../Module")} Module */ | ||
| /** @typedef {import("../javascript/JavascriptParser").Range} Range */ | ||
| /** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ | ||
| /** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ | ||
| /** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ | ||
| /** | ||
| * Represents an inline `<style>...</style>` block in an HTML module. The | ||
| * tag's content is fed into webpack's CSS pipeline as a virtual CSS module | ||
| * with `exportType: "text"` so `url()` and `\@import` references are | ||
| * resolved relative to the HTML file. At render time the original content | ||
| * range is replaced with the processed CSS text read from the CSS module's | ||
| * code generation data. | ||
| */ | ||
| class HtmlInlineStyleDependency extends ModuleDependency { | ||
| /** | ||
| * Creates an instance of HtmlInlineStyleDependency. | ||
| * @param {string} request virtual request resolving to the inline CSS (data URI) | ||
| * @param {Range} range range of the inline CSS content (between `<style>` and `</style>`) | ||
| */ | ||
| constructor(request, range) { | ||
| super(request); | ||
| this.range = range; | ||
| } | ||
| get type() { | ||
| return "html inline style"; | ||
| } | ||
| get category() { | ||
| return "html-style"; | ||
| } | ||
| /** | ||
| * Serializes this instance into the provided serializer context. | ||
| * @param {ObjectSerializerContext} context context | ||
| */ | ||
| serialize(context) { | ||
| super.serialize(context); | ||
| } | ||
| /** | ||
| * Restores this instance from the provided deserializer context. | ||
| * @param {ObjectDeserializerContext} context context | ||
| */ | ||
| deserialize(context) { | ||
| super.deserialize(context); | ||
| } | ||
| } | ||
| HtmlInlineStyleDependency.Template = class HtmlInlineStyleDependencyTemplate extends ( | ||
| ModuleDependency.Template | ||
| ) { | ||
| /** | ||
| * Applies the plugin by registering its hooks on the compiler. | ||
| * @param {Dependency} dependency the dependency for which the template should be applied | ||
| * @param {ReplaceSource} source the current replace source which can be modified | ||
| * @param {DependencyTemplateContext} templateContext the context object | ||
| * @returns {void} | ||
| */ | ||
| apply(dependency, source, { moduleGraph, runtime, codeGenerationResults }) { | ||
| const dep = /** @type {HtmlInlineStyleDependency} */ (dependency); | ||
| const module = /** @type {Module} */ (moduleGraph.getModule(dep)); | ||
| /** @type {string} */ | ||
| let cssText = ""; | ||
| if (module) { | ||
| const codeGen = | ||
| /** @type {CodeGenerationResults} */ | ||
| (codeGenerationResults).get(module, runtime); | ||
| const cssTextSource = codeGen.sources.get(CSS_TEXT_TYPE); | ||
| if (cssTextSource) { | ||
| cssText = /** @type {string} */ (cssTextSource.source()); | ||
| } | ||
| } | ||
| source.replace(dep.range[0], dep.range[1] - 1, cssText); | ||
| } | ||
| }; | ||
| makeSerializable( | ||
| HtmlInlineStyleDependency, | ||
| "webpack/lib/dependencies/HtmlInlineStyleDependency" | ||
| ); | ||
| module.exports = HtmlInlineStyleDependency; |
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| */ | ||
| "use strict"; | ||
| const makeSerializable = require("../util/makeSerializable"); | ||
| const CssUrlDependency = require("./CssUrlDependency"); | ||
| const ModuleDependency = require("./ModuleDependency"); | ||
| /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ | ||
| /** @typedef {import("../Chunk")} Chunk */ | ||
| /** @typedef {import("../Dependency")} Dependency */ | ||
| /** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ | ||
| /** @typedef {import("../Entrypoint")} Entrypoint */ | ||
| /** @typedef {import("../javascript/JavascriptParser").Range} Range */ | ||
| /** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ | ||
| /** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ | ||
| /** @typedef {"script-classic" | "script-module" | "modulepreload" | "stylesheet"} HtmlScriptElementKind */ | ||
| class HtmlScriptSrcDependency extends ModuleDependency { | ||
| /** | ||
| * Creates an instance of HtmlScriptSrcDependency. | ||
| * @param {string} request request | ||
| * @param {Range} range range of the attribute value in the source | ||
| * @param {string} entryName name of the entry this script src is bundled into | ||
| * @param {string=} category dependency category used for resolving and grouping | ||
| * @param {HtmlScriptElementKind=} elementKind shape of the originating HTML element; used when expanding sibling tags for split/runtime chunks | ||
| * @param {number=} tagStart position of the opening `<` of the originating tag in the source; sibling tags emitted for additional entry chunks are inserted right before this | ||
| * @param {number=} tagOpenEnd position of the character immediately after the opening tag's `>` in the source; combined with `tagStart` this lets the template clone the original opening tag verbatim (preserving attributes like `nonce`, `crossorigin`, `referrerpolicy`, `defer`, `async`) when generating sibling tags | ||
| */ | ||
| constructor( | ||
| request, | ||
| range, | ||
| entryName, | ||
| category, | ||
| elementKind, | ||
| tagStart, | ||
| tagOpenEnd | ||
| ) { | ||
| super(request); | ||
| this.range = range; | ||
| this.entryName = entryName; | ||
| /** @type {string} */ | ||
| this._category = category || "commonjs"; | ||
| /** @type {HtmlScriptElementKind} */ | ||
| this.elementKind = elementKind || "script-classic"; | ||
| /** @type {number} */ | ||
| this.tagStart = tagStart === undefined ? -1 : tagStart; | ||
| /** @type {number} */ | ||
| this.tagOpenEnd = tagOpenEnd === undefined ? -1 : tagOpenEnd; | ||
| } | ||
| get type() { | ||
| return "html script src"; | ||
| } | ||
| get category() { | ||
| return this._category; | ||
| } | ||
| /** | ||
| * Serializes this instance into the provided serializer context. | ||
| * @param {ObjectSerializerContext} context context | ||
| */ | ||
| serialize(context) { | ||
| const { write } = context; | ||
| write(this.entryName); | ||
| write(this._category); | ||
| write(this.elementKind); | ||
| write(this.tagStart); | ||
| write(this.tagOpenEnd); | ||
| super.serialize(context); | ||
| } | ||
| /** | ||
| * Restores this instance from the provided deserializer context. | ||
| * @param {ObjectDeserializerContext} context context | ||
| */ | ||
| deserialize(context) { | ||
| const { read } = context; | ||
| this.entryName = read(); | ||
| this._category = read(); | ||
| this.elementKind = read(); | ||
| this.tagStart = read(); | ||
| this.tagOpenEnd = read(); | ||
| super.deserialize(context); | ||
| } | ||
| } | ||
| /** | ||
| * @param {Chunk} chunk a chunk | ||
| * @param {import("../Compilation")} compilation compilation | ||
| * @param {"javascript" | "css"} contentHashType which content hash to plug into the filename template | ||
| * @returns {string} chunk filename path (no public-path prefix) | ||
| */ | ||
| const getChunkFilename = (chunk, compilation, contentHashType) => { | ||
| const outputOptions = compilation.outputOptions; | ||
| let filenameTemplate; | ||
| if (contentHashType === "css") { | ||
| // For a CSS-typed chunk, use the same template the CSS pipeline | ||
| // will use when it actually emits the `.css` file, so the `<link | ||
| // rel="stylesheet" href>` URL we write into the HTML matches the | ||
| // asset on disk. | ||
| filenameTemplate = | ||
| require("../css/CssModulesPlugin").getChunkFilenameTemplate( | ||
| chunk, | ||
| outputOptions | ||
| ); | ||
| } else { | ||
| filenameTemplate = | ||
| chunk.filenameTemplate || | ||
| (chunk.canBeInitial() | ||
| ? outputOptions.filename | ||
| : outputOptions.chunkFilename); | ||
| } | ||
| return compilation.getPath(filenameTemplate, { | ||
| chunk, | ||
| contentHashType | ||
| }); | ||
| }; | ||
| /** | ||
| * @param {Entrypoint} entrypoint entrypoint | ||
| * @returns {Chunk[]} every chunk this entrypoint needs in load order: the | ||
| * runtime chunk first (when `optimization.runtimeChunk` splits it off), then | ||
| * any intermediate chunks (e.g. from `optimization.splitChunks`), and finally | ||
| * the entry chunk itself. The entry chunk is always returned last so callers | ||
| * can identify it as the tag whose `src`/`href` attribute is being rewritten | ||
| * in place. Chunks that are already loaded by an ancestor (`dependOn`) entry's | ||
| * own script tag — i.e. the parent entrypoint's entry chunk *and* its runtime | ||
| * chunk — are skipped, otherwise they would be loaded twice when the same | ||
| * HTML contains tags for both the leader and the dependant entries. | ||
| */ | ||
| const getEntrypointChunksInLoadOrder = (entrypoint) => { | ||
| const entryChunk = /** @type {Chunk} */ (entrypoint.getEntrypointChunk()); | ||
| const runtimeChunk = entrypoint.getRuntimeChunk(); | ||
| /** @type {Set<Chunk>} */ | ||
| const chunksLoadedByAncestorTags = new Set(); | ||
| /** @type {Set<import("../ChunkGroup")>} */ | ||
| const visitedGroups = new Set(); | ||
| const walk = (/** @type {import("../ChunkGroup")} */ group) => { | ||
| if (visitedGroups.has(group)) return; | ||
| visitedGroups.add(group); | ||
| for (const parent of group.parentsIterable) { | ||
| if ( | ||
| typeof (/** @type {Entrypoint} */ (parent).getEntrypointChunk) === | ||
| "function" | ||
| ) { | ||
| const parentEntry = | ||
| /** @type {Entrypoint} */ | ||
| (parent).getEntrypointChunk(); | ||
| if (parentEntry) chunksLoadedByAncestorTags.add(parentEntry); | ||
| const parentRuntime = | ||
| /** @type {Entrypoint} */ | ||
| (parent).getRuntimeChunk(); | ||
| if (parentRuntime) chunksLoadedByAncestorTags.add(parentRuntime); | ||
| } | ||
| walk(parent); | ||
| } | ||
| }; | ||
| walk(entrypoint); | ||
| /** @type {Chunk[]} */ | ||
| const ordered = []; | ||
| /** @type {Set<Chunk>} */ | ||
| const seen = new Set(); | ||
| const push = (/** @type {Chunk | null | undefined} */ chunk) => { | ||
| if (!chunk || seen.has(chunk) || chunk === entryChunk) return; | ||
| if (chunksLoadedByAncestorTags.has(chunk)) return; | ||
| seen.add(chunk); | ||
| ordered.push(chunk); | ||
| }; | ||
| if (runtimeChunk !== entryChunk) { | ||
| push(runtimeChunk); | ||
| } | ||
| for (const chunk of entrypoint.chunks) { | ||
| push(chunk); | ||
| } | ||
| ordered.push(entryChunk); | ||
| return ordered; | ||
| }; | ||
| /** | ||
| * Clone the original `<script>`/`<link>` opening tag with its `src`/`href` | ||
| * value swapped for a different chunk URL. Reusing the source text verbatim | ||
| * preserves attributes such as `nonce`, `crossorigin`, `referrerpolicy`, | ||
| * `defer`, and `async` so the sibling tags load with the same semantics as | ||
| * the entry tag that's already there. `integrity` is dropped because it's | ||
| * content-specific. When the original tag was upgraded to a module script | ||
| * (either by the author or by the `output.module` auto-upgrade in | ||
| * `HtmlParser`), the sibling is forced to `type="module"` regardless of what | ||
| * the source originally said. | ||
| * @param {string} originalTag the opening tag's source text including `>` | ||
| * @param {number} srcStartInTag offset of the src/href value start within `originalTag` | ||
| * @param {number} srcEndInTag offset of the src/href value end within `originalTag` | ||
| * @param {string} newUrl URL to put into the cloned tag's src/href slot | ||
| * @param {HtmlScriptElementKind} elementKind shape of the originating tag | ||
| * @returns {string} the sibling tag's HTML (including a closing `</script>` for script tags) | ||
| */ | ||
| const cloneTagWithUrl = ( | ||
| originalTag, | ||
| srcStartInTag, | ||
| srcEndInTag, | ||
| newUrl, | ||
| elementKind | ||
| ) => { | ||
| let body = | ||
| originalTag.slice(0, srcStartInTag) + | ||
| newUrl + | ||
| originalTag.slice(srcEndInTag); | ||
| // Strip dangerous-to-copy attributes from the cloned tag — currently | ||
| // just `integrity`. The match handles all three quoting styles | ||
| // (`"…"`, `'…'`, unquoted) and the bare-attribute form. | ||
| body = body.replace( | ||
| /\s+integrity(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+))?(?=[\s/>])/gi, | ||
| "" | ||
| ); | ||
| if (elementKind === "script-module") { | ||
| if (/\stype\s*=/i.test(body)) { | ||
| body = body.replace( | ||
| /(\stype\s*=\s*)(?:"[^"]*"|'[^']*'|[^\s>]+)/i, | ||
| '$1"module"' | ||
| ); | ||
| } else { | ||
| body = body.replace(/^<script\b/i, '<script type="module"'); | ||
| } | ||
| } | ||
| // `<link>` is a void element — no closing tag. `<script>` needs `</script>`. | ||
| return elementKind === "modulepreload" || elementKind === "stylesheet" | ||
| ? body | ||
| : `${body}</script>`; | ||
| }; | ||
| HtmlScriptSrcDependency.Template = class HtmlScriptSrcDependencyTemplate extends ( | ||
| ModuleDependency.Template | ||
| ) { | ||
| /** | ||
| * Applies the plugin by registering its hooks on the compiler. | ||
| * @param {Dependency} dependency the dependency for which the template should be applied | ||
| * @param {ReplaceSource} source the current replace source which can be modified | ||
| * @param {DependencyTemplateContext} templateContext the context object | ||
| * @returns {void} | ||
| */ | ||
| apply(dependency, source, templateContext) { | ||
| const { runtimeTemplate } = templateContext; | ||
| const dep = /** @type {HtmlScriptSrcDependency} */ (dependency); | ||
| const compilation = runtimeTemplate.compilation; | ||
| const entrypoint = /** @type {Entrypoint | undefined} */ ( | ||
| compilation.entrypoints.get(dep.entryName) | ||
| ); | ||
| if (!entrypoint) { | ||
| source.replace(dep.range[0], dep.range[1] - 1, "data:,"); | ||
| return; | ||
| } | ||
| const orderedChunks = getEntrypointChunksInLoadOrder(entrypoint); | ||
| const entryChunk = orderedChunks[orderedChunks.length - 1]; | ||
| const contentHashType = | ||
| dep.elementKind === "stylesheet" ? "css" : "javascript"; | ||
| const entryUrl = `${CssUrlDependency.PUBLIC_PATH_AUTO}${getChunkFilename( | ||
| entryChunk, | ||
| compilation, | ||
| contentHashType | ||
| )}`; | ||
| source.replace(dep.range[0], dep.range[1] - 1, entryUrl); | ||
| if ( | ||
| orderedChunks.length <= 1 || | ||
| dep.tagStart < 0 || | ||
| dep.tagOpenEnd <= dep.tagStart | ||
| ) { | ||
| return; | ||
| } | ||
| // The browser must load every chunk in dependency order, not just the | ||
| // entry chunk. Clone the original tag for each non-entry chunk so the | ||
| // preserved attributes (nonce, crossorigin, …) match the entry tag, | ||
| // and insert the clones before the original tag's `<`. | ||
| const originalContent = /** @type {string} */ (source.original().source()); | ||
| const originalTag = originalContent.slice(dep.tagStart, dep.tagOpenEnd); | ||
| const srcStartInTag = dep.range[0] - dep.tagStart; | ||
| const srcEndInTag = dep.range[1] - dep.tagStart; | ||
| const siblings = []; | ||
| for (let i = 0; i < orderedChunks.length - 1; i++) { | ||
| const url = `${CssUrlDependency.PUBLIC_PATH_AUTO}${getChunkFilename( | ||
| orderedChunks[i], | ||
| compilation, | ||
| contentHashType | ||
| )}`; | ||
| siblings.push( | ||
| cloneTagWithUrl( | ||
| originalTag, | ||
| srcStartInTag, | ||
| srcEndInTag, | ||
| url, | ||
| dep.elementKind | ||
| ) | ||
| ); | ||
| } | ||
| source.insert(dep.tagStart, siblings.join("")); | ||
| } | ||
| }; | ||
| makeSerializable( | ||
| HtmlScriptSrcDependency, | ||
| "webpack/lib/dependencies/HtmlScriptSrcDependency" | ||
| ); | ||
| module.exports = HtmlScriptSrcDependency; |
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| Author Alexander Akait @alexander-akait | ||
| */ | ||
| "use strict"; | ||
| const RawDataUrlModule = require("../asset/RawDataUrlModule"); | ||
| const makeSerializable = require("../util/makeSerializable"); | ||
| const memoize = require("../util/memoize"); | ||
| const ModuleDependency = require("./ModuleDependency"); | ||
| /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ | ||
| /** @typedef {import("../CodeGenerationResults")} CodeGenerationResults */ | ||
| /** @typedef {import("../Dependency")} Dependency */ | ||
| /** @typedef {import("../DependencyTemplate").CssDependencyTemplateContext} DependencyTemplateContext */ | ||
| /** @typedef {import("../Module")} Module */ | ||
| /** @typedef {import("../Module").CodeGenerationResult} CodeGenerationResult */ | ||
| /** @typedef {import("../Module").CodeGenerationResultData} CodeGenerationResultData */ | ||
| /** @typedef {import("../javascript/JavascriptParser").Range} Range */ | ||
| /** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ | ||
| /** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ | ||
| /** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ | ||
| const getIgnoredRawDataUrlModule = memoize( | ||
| () => new RawDataUrlModule("data:,", "ignored-asset", "(ignored asset)") | ||
| ); | ||
| class HtmlSourceDependency extends ModuleDependency { | ||
| /** | ||
| * Creates an instance of HtmlSourceDependency. | ||
| * @param {string} request request | ||
| * @param {Range} range range of the argument | ||
| */ | ||
| constructor(request, range) { | ||
| super(request); | ||
| this.range = range; | ||
| } | ||
| get type() { | ||
| return "html source()"; | ||
| } | ||
| get category() { | ||
| return "url"; | ||
| } | ||
| /** | ||
| * Creates an ignored module. | ||
| * @param {string} context context directory | ||
| * @returns {Module} ignored module | ||
| */ | ||
| createIgnoredModule(context) { | ||
| return getIgnoredRawDataUrlModule(); | ||
| } | ||
| /** | ||
| * Serializes this instance into the provided serializer context. | ||
| * @param {ObjectSerializerContext} context context | ||
| */ | ||
| serialize(context) { | ||
| super.serialize(context); | ||
| } | ||
| /** | ||
| * Restores this instance from the provided deserializer context. | ||
| * @param {ObjectDeserializerContext} context context | ||
| */ | ||
| deserialize(context) { | ||
| super.deserialize(context); | ||
| } | ||
| } | ||
| HtmlSourceDependency.Template = class HtmlSourceDependencyTemplate extends ( | ||
| ModuleDependency.Template | ||
| ) { | ||
| /** | ||
| * Applies the plugin by registering its hooks on the compiler. | ||
| * @param {Dependency} dependency the dependency for which the template should be applied | ||
| * @param {ReplaceSource} source the current replace source which can be modified | ||
| * @param {DependencyTemplateContext} templateContext the context object | ||
| * @returns {void} | ||
| */ | ||
| apply( | ||
| dependency, | ||
| source, | ||
| { moduleGraph, runtimeTemplate, codeGenerationResults } | ||
| ) { | ||
| const dep = /** @type {HtmlSourceDependency} */ (dependency); | ||
| const module = /** @type {Module} */ (moduleGraph.getModule(dep)); | ||
| /** @type {string | undefined} */ | ||
| const newValue = this.assetUrl({ | ||
| module, | ||
| codeGenerationResults | ||
| }); | ||
| source.replace(dep.range[0], dep.range[1] - 1, newValue); | ||
| } | ||
| /** | ||
| * Returns the url of the asset. | ||
| * @param {object} options options object | ||
| * @param {Module} options.module the module | ||
| * @param {RuntimeSpec=} options.runtime runtime | ||
| * @param {CodeGenerationResults} options.codeGenerationResults the code generation results | ||
| * @returns {string} the url of the asset | ||
| */ | ||
| assetUrl({ runtime, module, codeGenerationResults }) { | ||
| if (!module) { | ||
| return "data:,"; | ||
| } | ||
| const codeGen = codeGenerationResults.get(module, runtime); | ||
| const data = codeGen.data; | ||
| if (!data) return "data:,"; | ||
| const url = data.get("url"); | ||
| if (!url || !url["css-url"]) return "data:,"; | ||
| return url["css-url"]; | ||
| } | ||
| }; | ||
| makeSerializable( | ||
| HtmlSourceDependency, | ||
| "webpack/lib/dependencies/HtmlSourceDependency" | ||
| ); | ||
| module.exports = HtmlSourceDependency; |
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| Author Tobias Koppers @sokra | ||
| */ | ||
| "use strict"; | ||
| const { | ||
| JAVASCRIPT_MODULE_TYPE_AUTO, | ||
| JAVASCRIPT_MODULE_TYPE_DYNAMIC | ||
| } = require("../ModuleTypeConstants"); | ||
| const RuntimeGlobals = require("../RuntimeGlobals"); | ||
| const { | ||
| toConstantDependency | ||
| } = require("../javascript/JavascriptParserHelpers"); | ||
| const ConstDependency = require("./ConstDependency"); | ||
| /** @typedef {import("../../declarations/WebpackOptions").JavascriptParserOptions} JavascriptParserOptions */ | ||
| /** @typedef {import("../Compiler")} Compiler */ | ||
| /** @typedef {import("../javascript/JavascriptParser")} JavascriptParser */ | ||
| const PLUGIN_NAME = "RequireJsStuffPlugin"; | ||
| module.exports = class RequireJsStuffPlugin { | ||
| /** | ||
| * Applies the plugin by registering its hooks on the compiler. | ||
| * @param {Compiler} compiler the compiler instance | ||
| * @returns {void} | ||
| */ | ||
| apply(compiler) { | ||
| compiler.hooks.compilation.tap( | ||
| PLUGIN_NAME, | ||
| (compilation, { normalModuleFactory }) => { | ||
| compilation.dependencyTemplates.set( | ||
| ConstDependency, | ||
| new ConstDependency.Template() | ||
| ); | ||
| /** | ||
| * Handles the hook callback for this code path. | ||
| * @param {JavascriptParser} parser the parser | ||
| * @param {JavascriptParserOptions} parserOptions options | ||
| * @returns {void} | ||
| */ | ||
| const handler = (parser, parserOptions) => { | ||
| if ( | ||
| parserOptions.requireJs === undefined || | ||
| !parserOptions.requireJs | ||
| ) { | ||
| return; | ||
| } | ||
| parser.hooks.call | ||
| .for("require.config") | ||
| .tap(PLUGIN_NAME, toConstantDependency(parser, "undefined")); | ||
| parser.hooks.call | ||
| .for("requirejs.config") | ||
| .tap(PLUGIN_NAME, toConstantDependency(parser, "undefined")); | ||
| parser.hooks.expression | ||
| .for("require.version") | ||
| .tap( | ||
| PLUGIN_NAME, | ||
| toConstantDependency(parser, JSON.stringify("0.0.0")) | ||
| ); | ||
| parser.hooks.expression | ||
| .for("requirejs.onError") | ||
| .tap( | ||
| PLUGIN_NAME, | ||
| toConstantDependency( | ||
| parser, | ||
| RuntimeGlobals.uncaughtErrorHandler, | ||
| [RuntimeGlobals.uncaughtErrorHandler] | ||
| ) | ||
| ); | ||
| }; | ||
| normalModuleFactory.hooks.parser | ||
| .for(JAVASCRIPT_MODULE_TYPE_AUTO) | ||
| .tap(PLUGIN_NAME, handler); | ||
| normalModuleFactory.hooks.parser | ||
| .for(JAVASCRIPT_MODULE_TYPE_DYNAMIC) | ||
| .tap(PLUGIN_NAME, handler); | ||
| } | ||
| ); | ||
| } | ||
| }; |
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| Author Tobias Koppers @sokra | ||
| */ | ||
| "use strict"; | ||
| const { OriginalSource, RawSource } = require("webpack-sources"); | ||
| const Module = require("../Module"); | ||
| const { | ||
| JAVASCRIPT_TYPE, | ||
| JAVASCRIPT_TYPES | ||
| } = require("../ModuleSourceTypeConstants"); | ||
| const { JAVASCRIPT_MODULE_TYPE_DYNAMIC } = require("../ModuleTypeConstants"); | ||
| const RuntimeGlobals = require("../RuntimeGlobals"); | ||
| const DelegatedSourceDependency = require("../dependencies/DelegatedSourceDependency"); | ||
| const StaticExportsDependency = require("../dependencies/StaticExportsDependency"); | ||
| const makeSerializable = require("../util/makeSerializable"); | ||
| /** @typedef {import("../../declarations/plugins/dll/DllReferencePlugin").DllReferencePluginOptions} DllReferencePluginOptions */ | ||
| /** @typedef {import("../config/defaults").WebpackOptionsNormalizedWithDefaults} WebpackOptions */ | ||
| /** @typedef {import("../Compilation")} Compilation */ | ||
| /** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ | ||
| /** @typedef {import("../Generator").SourceTypes} SourceTypes */ | ||
| /** @typedef {import("./LibManifestPlugin").ManifestModuleData} ManifestModuleData */ | ||
| /** @typedef {import("../Module").ModuleId} ModuleId */ | ||
| /** @typedef {import("../Module").BuildCallback} BuildCallback */ | ||
| /** @typedef {import("../Module").BuildMeta} BuildMeta */ | ||
| /** @typedef {import("../Module").CodeGenerationContext} CodeGenerationContext */ | ||
| /** @typedef {import("../Module").CodeGenerationResult} CodeGenerationResult */ | ||
| /** @typedef {import("../Module").LibIdentOptions} LibIdentOptions */ | ||
| /** @typedef {import("../Module").LibIdent} LibIdent */ | ||
| /** @typedef {import("../Module").NeedBuildCallback} NeedBuildCallback */ | ||
| /** @typedef {import("../Module").NeedBuildContext} NeedBuildContext */ | ||
| /** @typedef {import("../Module").Sources} Sources */ | ||
| /** @typedef {import("../Module").RuntimeRequirements} RuntimeRequirements */ | ||
| /** @typedef {import("../RequestShortener")} RequestShortener */ | ||
| /** @typedef {import("../ResolverFactory").ResolverWithOptions} ResolverWithOptions */ | ||
| /** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ | ||
| /** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ | ||
| /** @typedef {import("../dependencies/StaticExportsDependency").Exports} Exports */ | ||
| /** @typedef {import("../util/Hash")} Hash */ | ||
| /** @typedef {import("../util/fs").InputFileSystem} InputFileSystem */ | ||
| /** @typedef {string} DelegatedModuleSourceRequest */ | ||
| /** @typedef {NonNullable<DllReferencePluginOptions["type"]>} DelegatedModuleType */ | ||
| /** | ||
| * Defines the delegated module data type used by this module. | ||
| * @typedef {object} DelegatedModuleData | ||
| * @property {BuildMeta=} buildMeta build meta | ||
| * @property {Exports=} exports exports | ||
| * @property {ModuleId} id module id | ||
| */ | ||
| const RUNTIME_REQUIREMENTS = new Set([ | ||
| RuntimeGlobals.module, | ||
| RuntimeGlobals.require | ||
| ]); | ||
| class DelegatedModule extends Module { | ||
| /** | ||
| * Creates an instance of DelegatedModule. | ||
| * @param {DelegatedModuleSourceRequest} sourceRequest source request | ||
| * @param {DelegatedModuleData} data data | ||
| * @param {DelegatedModuleType} type type | ||
| * @param {string} userRequest user request | ||
| * @param {string | Module} originalRequest original request | ||
| */ | ||
| constructor(sourceRequest, data, type, userRequest, originalRequest) { | ||
| super(JAVASCRIPT_MODULE_TYPE_DYNAMIC, null); | ||
| // Info from Factory | ||
| this.sourceRequest = sourceRequest; | ||
| this.request = data.id; | ||
| this.delegationType = type; | ||
| this.userRequest = userRequest; | ||
| this.originalRequest = originalRequest; | ||
| this.delegateData = data; | ||
| // Build info | ||
| /** @type {undefined | DelegatedSourceDependency} */ | ||
| this.delegatedSourceDependency = undefined; | ||
| } | ||
| /** | ||
| * Returns the source types this module can generate. | ||
| * @returns {SourceTypes} types available (do not mutate) | ||
| */ | ||
| getSourceTypes() { | ||
| return JAVASCRIPT_TYPES; | ||
| } | ||
| /** | ||
| * Gets the library identifier. | ||
| * @param {LibIdentOptions} options options | ||
| * @returns {LibIdent | null} an identifier for library inclusion | ||
| */ | ||
| libIdent(options) { | ||
| return typeof this.originalRequest === "string" | ||
| ? this.originalRequest | ||
| : this.originalRequest.libIdent(options); | ||
| } | ||
| /** | ||
| * Returns the unique identifier used to reference this module. | ||
| * @returns {string} a unique identifier of the module | ||
| */ | ||
| identifier() { | ||
| return `delegated ${JSON.stringify(this.request)} from ${ | ||
| this.sourceRequest | ||
| }`; | ||
| } | ||
| /** | ||
| * Returns a human-readable identifier for this module. | ||
| * @param {RequestShortener} requestShortener the request shortener | ||
| * @returns {string} a user readable identifier of the module | ||
| */ | ||
| readableIdentifier(requestShortener) { | ||
| return `delegated ${this.userRequest} from ${this.sourceRequest}`; | ||
| } | ||
| /** | ||
| * Checks whether the module needs to be rebuilt for the current build state. | ||
| * @param {NeedBuildContext} context context info | ||
| * @param {NeedBuildCallback} callback callback function, returns true, if the module needs a rebuild | ||
| * @returns {void} | ||
| */ | ||
| needBuild(context, callback) { | ||
| return callback(null, !this.buildMeta); | ||
| } | ||
| /** | ||
| * Builds the module using the provided compilation context. | ||
| * @param {WebpackOptions} options webpack options | ||
| * @param {Compilation} compilation the compilation | ||
| * @param {ResolverWithOptions} resolver the resolver | ||
| * @param {InputFileSystem} fs the file system | ||
| * @param {BuildCallback} callback callback function | ||
| * @returns {void} | ||
| */ | ||
| build(options, compilation, resolver, fs, callback) { | ||
| const delegateData = /** @type {ManifestModuleData} */ (this.delegateData); | ||
| this.buildMeta = { ...delegateData.buildMeta }; | ||
| this.buildInfo = {}; | ||
| this.dependencies.length = 0; | ||
| this.delegatedSourceDependency = new DelegatedSourceDependency( | ||
| this.sourceRequest | ||
| ); | ||
| this.addDependency(this.delegatedSourceDependency); | ||
| this.addDependency( | ||
| new StaticExportsDependency(delegateData.exports || true, false) | ||
| ); | ||
| callback(); | ||
| } | ||
| /** | ||
| * Generates code and runtime requirements for this module. | ||
| * @param {CodeGenerationContext} context context for code generation | ||
| * @returns {CodeGenerationResult} result | ||
| */ | ||
| codeGeneration({ runtimeTemplate, moduleGraph, chunkGraph }) { | ||
| const dep = /** @type {DelegatedSourceDependency} */ (this.dependencies[0]); | ||
| const sourceModule = moduleGraph.getModule(dep); | ||
| /** @type {string} */ | ||
| let str; | ||
| if (!sourceModule) { | ||
| str = runtimeTemplate.throwMissingModuleErrorBlock({ | ||
| request: this.sourceRequest | ||
| }); | ||
| } else { | ||
| str = `module.exports = (${runtimeTemplate.moduleExports({ | ||
| module: sourceModule, | ||
| chunkGraph, | ||
| request: dep.request, | ||
| /** @type {RuntimeRequirements} */ | ||
| runtimeRequirements: new Set() | ||
| })})`; | ||
| switch (this.delegationType) { | ||
| case "require": | ||
| str += `(${JSON.stringify(this.request)})`; | ||
| break; | ||
| case "object": | ||
| str += `[${JSON.stringify(this.request)}]`; | ||
| break; | ||
| } | ||
| str += ";"; | ||
| } | ||
| /** @type {Sources} */ | ||
| const sources = new Map(); | ||
| if (this.useSourceMap || this.useSimpleSourceMap) { | ||
| sources.set(JAVASCRIPT_TYPE, new OriginalSource(str, this.identifier())); | ||
| } else { | ||
| sources.set(JAVASCRIPT_TYPE, new RawSource(str)); | ||
| } | ||
| return { | ||
| sources, | ||
| runtimeRequirements: RUNTIME_REQUIREMENTS | ||
| }; | ||
| } | ||
| /** | ||
| * Returns the estimated size for the requested source type. | ||
| * @param {string=} type the source type for which the size should be estimated | ||
| * @returns {number} the estimated size of the module (must be non-zero) | ||
| */ | ||
| size(type) { | ||
| return 42; | ||
| } | ||
| /** | ||
| * Updates the hash with the data contributed by this instance. | ||
| * @param {Hash} hash the hash used to track dependencies | ||
| * @param {UpdateHashContext} context context | ||
| * @returns {void} | ||
| */ | ||
| updateHash(hash, context) { | ||
| hash.update(this.delegationType); | ||
| hash.update(JSON.stringify(this.request)); | ||
| super.updateHash(hash, context); | ||
| } | ||
| /** | ||
| * Serializes this instance into the provided serializer context. | ||
| * @param {ObjectSerializerContext} context context | ||
| */ | ||
| serialize(context) { | ||
| const { write } = context; | ||
| // constructor | ||
| write(this.sourceRequest); | ||
| write(this.delegateData); | ||
| write(this.delegationType); | ||
| write(this.userRequest); | ||
| write(this.originalRequest); | ||
| super.serialize(context); | ||
| } | ||
| /** | ||
| * Restores this instance from the provided deserializer context. | ||
| * @param {ObjectDeserializerContext} context context\ | ||
| * @returns {DelegatedModule} DelegatedModule | ||
| */ | ||
| static deserialize(context) { | ||
| const { read } = context; | ||
| const obj = new DelegatedModule( | ||
| read(), // sourceRequest | ||
| read(), // delegateData | ||
| read(), // delegationType | ||
| read(), // userRequest | ||
| read() // originalRequest | ||
| ); | ||
| obj.deserialize(context); | ||
| return obj; | ||
| } | ||
| /** | ||
| * Assuming this module is in the cache. Update the (cached) module with | ||
| * the fresh module from the factory. Usually updates internal references | ||
| * and properties. | ||
| * @param {Module} module fresh module | ||
| * @returns {void} | ||
| */ | ||
| updateCacheModule(module) { | ||
| super.updateCacheModule(module); | ||
| const m = /** @type {DelegatedModule} */ (module); | ||
| this.delegationType = m.delegationType; | ||
| this.userRequest = m.userRequest; | ||
| this.originalRequest = m.originalRequest; | ||
| this.delegateData = m.delegateData; | ||
| } | ||
| /** | ||
| * Assuming this module is in the cache. Remove internal references to allow freeing some memory. | ||
| */ | ||
| cleanupForCache() { | ||
| super.cleanupForCache(); | ||
| this.delegateData = | ||
| /** @type {EXPECTED_ANY} */ | ||
| (undefined); | ||
| } | ||
| } | ||
| makeSerializable(DelegatedModule, "webpack/lib/dll/DelegatedModule"); | ||
| module.exports = DelegatedModule; |
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| Author Tobias Koppers @sokra | ||
| */ | ||
| "use strict"; | ||
| const DelegatedModule = require("./DelegatedModule"); | ||
| /** @typedef {import("../../declarations/plugins/dll/DllReferencePlugin").DllReferencePluginOptions} DllReferencePluginOptions */ | ||
| /** @typedef {import("../../declarations/plugins/dll/DllReferencePlugin").DllReferencePluginOptionsContent} DllReferencePluginOptionsContent */ | ||
| /** @typedef {import("./DelegatedModule").DelegatedModuleData} DelegatedModuleData */ | ||
| /** @typedef {import("./DelegatedModule").DelegatedModuleSourceRequest} DelegatedModuleSourceRequest */ | ||
| /** @typedef {import("./DelegatedModule").DelegatedModuleType} DelegatedModuleType */ | ||
| /** @typedef {import("../NormalModuleFactory")} NormalModuleFactory */ | ||
| /** @typedef {import("../util/identifier").AssociatedObjectForCache} AssociatedObjectForCache */ | ||
| /** | ||
| * Defines the options type used by this module. | ||
| * @typedef {object} Options | ||
| * @property {DelegatedModuleSourceRequest} source source | ||
| * @property {NonNullable<DllReferencePluginOptions["context"]>} context absolute context path to which lib ident is relative to | ||
| * @property {DllReferencePluginOptionsContent} content content | ||
| * @property {DllReferencePluginOptions["type"]} type type | ||
| * @property {DllReferencePluginOptions["extensions"]} extensions extensions | ||
| * @property {DllReferencePluginOptions["scope"]} scope scope | ||
| * @property {AssociatedObjectForCache=} associatedObjectForCache object for caching | ||
| */ | ||
| const PLUGIN_NAME = "DelegatedModuleFactoryPlugin"; | ||
| class DelegatedModuleFactoryPlugin { | ||
| /** | ||
| * Creates an instance of DelegatedModuleFactoryPlugin. | ||
| * @param {Options} options options | ||
| */ | ||
| constructor(options) { | ||
| this.options = options; | ||
| options.type = options.type || "require"; | ||
| options.extensions = options.extensions || ["", ".js", ".json", ".wasm"]; | ||
| } | ||
| /** | ||
| * Applies the plugin by registering its hooks on the compiler. | ||
| * @param {NormalModuleFactory} normalModuleFactory the normal module factory | ||
| * @returns {void} | ||
| */ | ||
| apply(normalModuleFactory) { | ||
| const scope = this.options.scope; | ||
| if (scope) { | ||
| normalModuleFactory.hooks.factorize.tapAsync( | ||
| PLUGIN_NAME, | ||
| (data, callback) => { | ||
| const [dependency] = data.dependencies; | ||
| const { request } = dependency; | ||
| if (request && request.startsWith(`${scope}/`)) { | ||
| const innerRequest = `.${request.slice(scope.length)}`; | ||
| /** @type {undefined | DelegatedModuleData} */ | ||
| let resolved; | ||
| if (innerRequest in this.options.content) { | ||
| resolved = this.options.content[innerRequest]; | ||
| return callback( | ||
| null, | ||
| new DelegatedModule( | ||
| this.options.source, | ||
| resolved, | ||
| /** @type {DelegatedModuleType} */ | ||
| (this.options.type), | ||
| innerRequest, | ||
| request | ||
| ) | ||
| ); | ||
| } | ||
| const extensions = | ||
| /** @type {string[]} */ | ||
| (this.options.extensions); | ||
| for (let i = 0; i < extensions.length; i++) { | ||
| const extension = extensions[i]; | ||
| const requestPlusExt = innerRequest + extension; | ||
| if (requestPlusExt in this.options.content) { | ||
| resolved = this.options.content[requestPlusExt]; | ||
| return callback( | ||
| null, | ||
| new DelegatedModule( | ||
| this.options.source, | ||
| resolved, | ||
| /** @type {DelegatedModuleType} */ | ||
| (this.options.type), | ||
| requestPlusExt, | ||
| request + extension | ||
| ) | ||
| ); | ||
| } | ||
| } | ||
| } | ||
| return callback(); | ||
| } | ||
| ); | ||
| } else { | ||
| normalModuleFactory.hooks.module.tap(PLUGIN_NAME, (module) => { | ||
| const request = module.libIdent(this.options); | ||
| if (request && request in this.options.content) { | ||
| const resolved = this.options.content[request]; | ||
| return new DelegatedModule( | ||
| this.options.source, | ||
| resolved, | ||
| /** @type {DelegatedModuleType} */ | ||
| (this.options.type), | ||
| request, | ||
| module | ||
| ); | ||
| } | ||
| return module; | ||
| }); | ||
| } | ||
| } | ||
| } | ||
| module.exports = DelegatedModuleFactoryPlugin; |
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| Author Tobias Koppers @sokra | ||
| */ | ||
| "use strict"; | ||
| const DelegatedSourceDependency = require("../dependencies/DelegatedSourceDependency"); | ||
| const DelegatedModuleFactoryPlugin = require("./DelegatedModuleFactoryPlugin"); | ||
| /** @typedef {import("../Compiler")} Compiler */ | ||
| /** @typedef {import("./DelegatedModuleFactoryPlugin").Options} Options */ | ||
| const PLUGIN_NAME = "DelegatedPlugin"; | ||
| class DelegatedPlugin { | ||
| /** | ||
| * Creates an instance of DelegatedPlugin. | ||
| * @param {Options} options options | ||
| */ | ||
| constructor(options) { | ||
| this.options = options; | ||
| } | ||
| /** | ||
| * Applies the plugin by registering its hooks on the compiler. | ||
| * @param {Compiler} compiler the compiler instance | ||
| * @returns {void} | ||
| */ | ||
| apply(compiler) { | ||
| compiler.hooks.compilation.tap( | ||
| PLUGIN_NAME, | ||
| (compilation, { normalModuleFactory }) => { | ||
| compilation.dependencyFactories.set( | ||
| DelegatedSourceDependency, | ||
| normalModuleFactory | ||
| ); | ||
| } | ||
| ); | ||
| compiler.hooks.compile.tap(PLUGIN_NAME, ({ normalModuleFactory }) => { | ||
| new DelegatedModuleFactoryPlugin({ | ||
| associatedObjectForCache: compiler.root, | ||
| ...this.options | ||
| }).apply(normalModuleFactory); | ||
| }); | ||
| } | ||
| } | ||
| module.exports = DelegatedPlugin; |
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| Author Tobias Koppers @sokra | ||
| */ | ||
| "use strict"; | ||
| const DllEntryDependency = require("../dependencies/DllEntryDependency"); | ||
| const EntryDependency = require("../dependencies/EntryDependency"); | ||
| const DllModuleFactory = require("./DllModuleFactory"); | ||
| /** @typedef {import("../Compiler")} Compiler */ | ||
| /** @typedef {import("../Entrypoint").EntryOptions} EntryOptions */ | ||
| /** @typedef {string[]} Entries */ | ||
| /** @typedef {EntryOptions & { name: string }} Options */ | ||
| const PLUGIN_NAME = "DllEntryPlugin"; | ||
| class DllEntryPlugin { | ||
| /** | ||
| * Creates an instance of DllEntryPlugin. | ||
| * @param {string} context context | ||
| * @param {Entries} entries entry names | ||
| * @param {Options} options options | ||
| */ | ||
| constructor(context, entries, options) { | ||
| this.context = context; | ||
| this.entries = entries; | ||
| this.options = options; | ||
| } | ||
| /** | ||
| * Applies the plugin by registering its hooks on the compiler. | ||
| * @param {Compiler} compiler the compiler instance | ||
| * @returns {void} | ||
| */ | ||
| apply(compiler) { | ||
| compiler.hooks.compilation.tap( | ||
| PLUGIN_NAME, | ||
| (compilation, { normalModuleFactory }) => { | ||
| const dllModuleFactory = new DllModuleFactory(); | ||
| compilation.dependencyFactories.set( | ||
| DllEntryDependency, | ||
| dllModuleFactory | ||
| ); | ||
| compilation.dependencyFactories.set( | ||
| EntryDependency, | ||
| normalModuleFactory | ||
| ); | ||
| } | ||
| ); | ||
| compiler.hooks.make.tapAsync(PLUGIN_NAME, (compilation, callback) => { | ||
| compilation.addEntry( | ||
| this.context, | ||
| new DllEntryDependency( | ||
| this.entries.map((e, idx) => { | ||
| const dep = new EntryDependency(e); | ||
| dep.loc = { | ||
| name: this.options.name, | ||
| index: idx | ||
| }; | ||
| return dep; | ||
| }), | ||
| this.options.name | ||
| ), | ||
| this.options, | ||
| (error) => { | ||
| if (error) return callback(error); | ||
| callback(); | ||
| } | ||
| ); | ||
| }); | ||
| } | ||
| } | ||
| module.exports = DllEntryPlugin; |
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| Author Tobias Koppers @sokra | ||
| */ | ||
| "use strict"; | ||
| const { RawSource } = require("webpack-sources"); | ||
| const Module = require("../Module"); | ||
| const { | ||
| JAVASCRIPT_TYPE, | ||
| JAVASCRIPT_TYPES | ||
| } = require("../ModuleSourceTypeConstants"); | ||
| const { JAVASCRIPT_MODULE_TYPE_DYNAMIC } = require("../ModuleTypeConstants"); | ||
| const RuntimeGlobals = require("../RuntimeGlobals"); | ||
| const makeSerializable = require("../util/makeSerializable"); | ||
| /** @typedef {import("../config/defaults").WebpackOptionsNormalizedWithDefaults} WebpackOptions */ | ||
| /** @typedef {import("../Compilation")} Compilation */ | ||
| /** @typedef {import("../Dependency")} Dependency */ | ||
| /** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ | ||
| /** @typedef {import("../Generator").SourceTypes} SourceTypes */ | ||
| /** @typedef {import("../Module").BuildCallback} BuildCallback */ | ||
| /** @typedef {import("../Module").CodeGenerationContext} CodeGenerationContext */ | ||
| /** @typedef {import("../Module").CodeGenerationResult} CodeGenerationResult */ | ||
| /** @typedef {import("../Module").NeedBuildCallback} NeedBuildCallback */ | ||
| /** @typedef {import("../Module").NeedBuildContext} NeedBuildContext */ | ||
| /** @typedef {import("../Module").Sources} Sources */ | ||
| /** @typedef {import("../RequestShortener")} RequestShortener */ | ||
| /** @typedef {import("../ResolverFactory").ResolverWithOptions} ResolverWithOptions */ | ||
| /** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ | ||
| /** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ | ||
| /** @typedef {import("../util/Hash")} Hash */ | ||
| /** @typedef {import("../util/fs").InputFileSystem} InputFileSystem */ | ||
| const RUNTIME_REQUIREMENTS = new Set([ | ||
| RuntimeGlobals.require, | ||
| RuntimeGlobals.module | ||
| ]); | ||
| class DllModule extends Module { | ||
| /** | ||
| * Creates an instance of DllModule. | ||
| * @param {string} context context path | ||
| * @param {Dependency[]} dependencies dependencies | ||
| * @param {string} name name | ||
| */ | ||
| constructor(context, dependencies, name) { | ||
| super(JAVASCRIPT_MODULE_TYPE_DYNAMIC, context); | ||
| // Info from Factory | ||
| /** @type {Dependency[]} */ | ||
| this.dependencies = dependencies; | ||
| this.name = name; | ||
| } | ||
| /** | ||
| * Returns the source types this module can generate. | ||
| * @returns {SourceTypes} types available (do not mutate) | ||
| */ | ||
| getSourceTypes() { | ||
| return JAVASCRIPT_TYPES; | ||
| } | ||
| /** | ||
| * Returns the unique identifier used to reference this module. | ||
| * @returns {string} a unique identifier of the module | ||
| */ | ||
| identifier() { | ||
| return `dll ${this.name}`; | ||
| } | ||
| /** | ||
| * Returns a human-readable identifier for this module. | ||
| * @param {RequestShortener} requestShortener the request shortener | ||
| * @returns {string} a user readable identifier of the module | ||
| */ | ||
| readableIdentifier(requestShortener) { | ||
| return `dll ${this.name}`; | ||
| } | ||
| /** | ||
| * Builds the module using the provided compilation context. | ||
| * @param {WebpackOptions} options webpack options | ||
| * @param {Compilation} compilation the compilation | ||
| * @param {ResolverWithOptions} resolver the resolver | ||
| * @param {InputFileSystem} fs the file system | ||
| * @param {BuildCallback} callback callback function | ||
| * @returns {void} | ||
| */ | ||
| build(options, compilation, resolver, fs, callback) { | ||
| this.buildMeta = {}; | ||
| this.buildInfo = {}; | ||
| return callback(); | ||
| } | ||
| /** | ||
| * Generates code and runtime requirements for this module. | ||
| * @param {CodeGenerationContext} context context for code generation | ||
| * @returns {CodeGenerationResult} result | ||
| */ | ||
| codeGeneration(context) { | ||
| /** @type {Sources} */ | ||
| const sources = new Map(); | ||
| sources.set( | ||
| JAVASCRIPT_TYPE, | ||
| new RawSource(`module.exports = ${RuntimeGlobals.require};`) | ||
| ); | ||
| return { | ||
| sources, | ||
| runtimeRequirements: RUNTIME_REQUIREMENTS | ||
| }; | ||
| } | ||
| /** | ||
| * Checks whether the module needs to be rebuilt for the current build state. | ||
| * @param {NeedBuildContext} context context info | ||
| * @param {NeedBuildCallback} callback callback function, returns true, if the module needs a rebuild | ||
| * @returns {void} | ||
| */ | ||
| needBuild(context, callback) { | ||
| return callback(null, !this.buildMeta); | ||
| } | ||
| /** | ||
| * Returns the estimated size for the requested source type. | ||
| * @param {string=} type the source type for which the size should be estimated | ||
| * @returns {number} the estimated size of the module (must be non-zero) | ||
| */ | ||
| size(type) { | ||
| return 12; | ||
| } | ||
| /** | ||
| * Updates the hash with the data contributed by this instance. | ||
| * @param {Hash} hash the hash used to track dependencies | ||
| * @param {UpdateHashContext} context context | ||
| * @returns {void} | ||
| */ | ||
| updateHash(hash, context) { | ||
| hash.update(`dll module${this.name || ""}`); | ||
| super.updateHash(hash, context); | ||
| } | ||
| /** | ||
| * Serializes this instance into the provided serializer context. | ||
| * @param {ObjectSerializerContext} context context | ||
| */ | ||
| serialize(context) { | ||
| context.write(this.name); | ||
| super.serialize(context); | ||
| } | ||
| /** | ||
| * Restores this instance from the provided deserializer context. | ||
| * @param {ObjectDeserializerContext} context context | ||
| */ | ||
| deserialize(context) { | ||
| this.name = context.read(); | ||
| super.deserialize(context); | ||
| } | ||
| /** | ||
| * Assuming this module is in the cache. Update the (cached) module with | ||
| * the fresh module from the factory. Usually updates internal references | ||
| * and properties. | ||
| * @param {Module} module fresh module | ||
| * @returns {void} | ||
| */ | ||
| updateCacheModule(module) { | ||
| super.updateCacheModule(module); | ||
| this.dependencies = module.dependencies; | ||
| } | ||
| /** | ||
| * Assuming this module is in the cache. Remove internal references to allow freeing some memory. | ||
| */ | ||
| cleanupForCache() { | ||
| super.cleanupForCache(); | ||
| this.dependencies = /** @type {EXPECTED_ANY} */ (undefined); | ||
| } | ||
| } | ||
| makeSerializable(DllModule, "webpack/lib/dll/DllModule"); | ||
| module.exports = DllModule; |
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| Author Tobias Koppers @sokra | ||
| */ | ||
| "use strict"; | ||
| const ModuleFactory = require("../ModuleFactory"); | ||
| const DllModule = require("./DllModule"); | ||
| /** @typedef {import("../ModuleFactory").ModuleFactoryCallback} ModuleFactoryCallback */ | ||
| /** @typedef {import("../ModuleFactory").ModuleFactoryCreateData} ModuleFactoryCreateData */ | ||
| /** @typedef {import("../dependencies/DllEntryDependency")} DllEntryDependency */ | ||
| class DllModuleFactory extends ModuleFactory { | ||
| constructor() { | ||
| super(); | ||
| this.hooks = Object.freeze({}); | ||
| } | ||
| /** | ||
| * Processes the provided data. | ||
| * @param {ModuleFactoryCreateData} data data object | ||
| * @param {ModuleFactoryCallback} callback callback | ||
| * @returns {void} | ||
| */ | ||
| create(data, callback) { | ||
| const dependency = /** @type {DllEntryDependency} */ (data.dependencies[0]); | ||
| callback(null, { | ||
| module: new DllModule( | ||
| data.context, | ||
| dependency.dependencies, | ||
| dependency.name | ||
| ) | ||
| }); | ||
| } | ||
| } | ||
| module.exports = DllModuleFactory; |
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| Author Tobias Koppers @sokra | ||
| */ | ||
| "use strict"; | ||
| const FlagAllModulesAsUsedPlugin = require("../FlagAllModulesAsUsedPlugin"); | ||
| const DllEntryPlugin = require("./DllEntryPlugin"); | ||
| const LibManifestPlugin = require("./LibManifestPlugin"); | ||
| /** @typedef {import("../../declarations/plugins/dll/DllPlugin").DllPluginOptions} DllPluginOptions */ | ||
| /** @typedef {import("../Compiler")} Compiler */ | ||
| /** @typedef {import("./DllEntryPlugin").Entries} Entries */ | ||
| /** @typedef {import("./DllEntryPlugin").Options} Options */ | ||
| const PLUGIN_NAME = "DllPlugin"; | ||
| class DllPlugin { | ||
| /** | ||
| * Creates an instance of DllPlugin. | ||
| * @param {DllPluginOptions} options options object | ||
| */ | ||
| constructor(options) { | ||
| /** @type {DllPluginOptions} */ | ||
| this.options = options; | ||
| } | ||
| /** | ||
| * Applies the plugin by registering its hooks on the compiler. | ||
| * @param {Compiler} compiler the compiler instance | ||
| * @returns {void} | ||
| */ | ||
| apply(compiler) { | ||
| compiler.hooks.validate.tap(PLUGIN_NAME, () => { | ||
| compiler.validate( | ||
| () => require("../../schemas/plugins/dll/DllPlugin.json"), | ||
| this.options, | ||
| { | ||
| name: "Dll Plugin", | ||
| baseDataPath: "options" | ||
| }, | ||
| (options) => | ||
| require("../../schemas/plugins/dll/DllPlugin.check")(options) | ||
| ); | ||
| }); | ||
| const entryOnly = this.options.entryOnly !== false; | ||
| compiler.hooks.entryOption.tap(PLUGIN_NAME, (context, entry) => { | ||
| if (typeof entry !== "function") { | ||
| for (const name of Object.keys(entry)) { | ||
| /** @type {Options} */ | ||
| const options = { name }; | ||
| new DllEntryPlugin( | ||
| context, | ||
| /** @type {Entries} */ | ||
| (entry[name].import), | ||
| options | ||
| ).apply(compiler); | ||
| } | ||
| } else { | ||
| throw new Error( | ||
| `${PLUGIN_NAME} doesn't support dynamic entry (function) yet` | ||
| ); | ||
| } | ||
| return true; | ||
| }); | ||
| new LibManifestPlugin({ ...this.options, entryOnly }).apply(compiler); | ||
| if (!entryOnly) { | ||
| new FlagAllModulesAsUsedPlugin(PLUGIN_NAME).apply(compiler); | ||
| } | ||
| } | ||
| } | ||
| module.exports = DllPlugin; |
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| Author Tobias Koppers @sokra | ||
| */ | ||
| "use strict"; | ||
| const ExternalModuleFactoryPlugin = require("../ExternalModuleFactoryPlugin"); | ||
| const DelegatedSourceDependency = require("../dependencies/DelegatedSourceDependency"); | ||
| const WebpackError = require("../errors/WebpackError"); | ||
| const { makePathsRelative } = require("../util/identifier"); | ||
| const parseJson = require("../util/parseJson"); | ||
| const DelegatedModuleFactoryPlugin = require("./DelegatedModuleFactoryPlugin"); | ||
| /** @typedef {import("../../declarations/WebpackOptions").Externals} Externals */ | ||
| /** @typedef {import("../../declarations/plugins/dll/DllReferencePlugin").DllReferencePluginOptions} DllReferencePluginOptions */ | ||
| /** @typedef {import("../../declarations/plugins/dll/DllReferencePlugin").DllReferencePluginOptionsContent} DllReferencePluginOptionsContent */ | ||
| /** @typedef {import("../../declarations/plugins/dll/DllReferencePlugin").DllReferencePluginOptionsManifest} DllReferencePluginOptionsManifest */ | ||
| /** @typedef {import("../Compiler")} Compiler */ | ||
| /** @typedef {import("../Compiler").CompilationParams} CompilationParams */ | ||
| /** @typedef {import("../util/fs").InputFileSystem} InputFileSystem */ | ||
| /** @typedef {{ path: string, data: DllReferencePluginOptionsManifest | undefined, error: Error | undefined }} CompilationDataItem */ | ||
| const PLUGIN_NAME = "DllReferencePlugin"; | ||
| class DllReferencePlugin { | ||
| /** | ||
| * Creates an instance of DllReferencePlugin. | ||
| * @param {DllReferencePluginOptions} options options object | ||
| */ | ||
| constructor(options) { | ||
| this.options = options; | ||
| } | ||
| /** | ||
| * Applies the plugin by registering its hooks on the compiler. | ||
| * @param {Compiler} compiler the compiler instance | ||
| * @returns {void} | ||
| */ | ||
| apply(compiler) { | ||
| compiler.hooks.validate.tap(PLUGIN_NAME, () => { | ||
| compiler.validate( | ||
| () => require("../../schemas/plugins/dll/DllReferencePlugin.json"), | ||
| this.options, | ||
| { | ||
| name: "Dll Reference Plugin", | ||
| baseDataPath: "options" | ||
| }, | ||
| (options) => | ||
| require("../../schemas/plugins/dll/DllReferencePlugin.check")(options) | ||
| ); | ||
| }); | ||
| compiler.hooks.compilation.tap( | ||
| PLUGIN_NAME, | ||
| (compilation, { normalModuleFactory }) => { | ||
| compilation.dependencyFactories.set( | ||
| DelegatedSourceDependency, | ||
| normalModuleFactory | ||
| ); | ||
| } | ||
| ); | ||
| /** @type {WeakMap<CompilationParams, CompilationDataItem>} */ | ||
| const compilationData = new WeakMap(); | ||
| compiler.hooks.beforeCompile.tapAsync(PLUGIN_NAME, (params, callback) => { | ||
| if ("manifest" in this.options) { | ||
| const manifest = this.options.manifest; | ||
| if (typeof manifest === "string") { | ||
| /** @type {InputFileSystem} */ | ||
| (compiler.inputFileSystem).readFile(manifest, (err, result) => { | ||
| if (err) return callback(err); | ||
| /** @type {CompilationDataItem} */ | ||
| const data = { | ||
| path: manifest, | ||
| data: undefined, | ||
| error: undefined | ||
| }; | ||
| // Catch errors parsing the manifest so that blank | ||
| // or malformed manifest files don't kill the process. | ||
| try { | ||
| data.data = | ||
| /** @type {DllReferencePluginOptionsManifest} */ | ||
| ( | ||
| /** @type {unknown} */ | ||
| (parseJson(/** @type {Buffer} */ (result).toString("utf8"))) | ||
| ); | ||
| } catch (parseErr) { | ||
| // Store the error in the params so that it can | ||
| // be added as a compilation error later on. | ||
| const manifestPath = makePathsRelative( | ||
| compiler.context, | ||
| manifest, | ||
| compiler.root | ||
| ); | ||
| data.error = new DllManifestError( | ||
| manifestPath, | ||
| /** @type {Error} */ (parseErr).message | ||
| ); | ||
| } | ||
| compilationData.set(params, data); | ||
| return callback(); | ||
| }); | ||
| return; | ||
| } | ||
| } | ||
| return callback(); | ||
| }); | ||
| compiler.hooks.compile.tap(PLUGIN_NAME, (params) => { | ||
| let name = this.options.name; | ||
| let sourceType = this.options.sourceType; | ||
| let resolvedContent = | ||
| "content" in this.options ? this.options.content : undefined; | ||
| if ("manifest" in this.options) { | ||
| const manifestParameter = this.options.manifest; | ||
| /** @type {undefined | DllReferencePluginOptionsManifest} */ | ||
| let manifest; | ||
| if (typeof manifestParameter === "string") { | ||
| const data = | ||
| /** @type {CompilationDataItem} */ | ||
| (compilationData.get(params)); | ||
| // If there was an error parsing the manifest | ||
| // file, exit now because the error will be added | ||
| // as a compilation error in the "compilation" hook. | ||
| if (data.error) { | ||
| return; | ||
| } | ||
| manifest = data.data; | ||
| } else { | ||
| manifest = manifestParameter; | ||
| } | ||
| if (manifest) { | ||
| if (!name) name = manifest.name; | ||
| if (!sourceType) sourceType = manifest.type; | ||
| if (!resolvedContent) resolvedContent = manifest.content; | ||
| } | ||
| } | ||
| /** @type {Externals} */ | ||
| const externals = {}; | ||
| const source = `dll-reference ${name}`; | ||
| externals[source] = /** @type {string} */ (name); | ||
| const normalModuleFactory = params.normalModuleFactory; | ||
| new ExternalModuleFactoryPlugin(sourceType || "var", externals).apply( | ||
| normalModuleFactory | ||
| ); | ||
| new DelegatedModuleFactoryPlugin({ | ||
| source, | ||
| type: this.options.type, | ||
| scope: this.options.scope, | ||
| context: this.options.context || compiler.context, | ||
| content: | ||
| /** @type {DllReferencePluginOptionsContent} */ | ||
| (resolvedContent), | ||
| extensions: this.options.extensions, | ||
| associatedObjectForCache: compiler.root | ||
| }).apply(normalModuleFactory); | ||
| }); | ||
| compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation, params) => { | ||
| if ("manifest" in this.options) { | ||
| const manifest = this.options.manifest; | ||
| if (typeof manifest === "string") { | ||
| const data = | ||
| /** @type {CompilationDataItem} */ | ||
| (compilationData.get(params)); | ||
| // If there was an error parsing the manifest file, add the | ||
| // error as a compilation error to make the compilation fail. | ||
| if (data.error) { | ||
| compilation.errors.push( | ||
| /** @type {DllManifestError} */ (data.error) | ||
| ); | ||
| } | ||
| compilation.fileDependencies.add(manifest); | ||
| } | ||
| } | ||
| }); | ||
| } | ||
| } | ||
| class DllManifestError extends WebpackError { | ||
| /** | ||
| * Creates an instance of DllManifestError. | ||
| * @param {string} filename filename of the manifest | ||
| * @param {string} message error message | ||
| */ | ||
| constructor(filename, message) { | ||
| super(); | ||
| this.name = "DllManifestError"; | ||
| this.message = `Dll manifest ${filename}\n${message}`; | ||
| } | ||
| } | ||
| module.exports = DllReferencePlugin; |
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| Author Tobias Koppers @sokra | ||
| */ | ||
| "use strict"; | ||
| const asyncLib = require("neo-async"); | ||
| const EntryDependency = require("../dependencies/EntryDependency"); | ||
| const { someInIterable } = require("../util/IterableHelpers"); | ||
| const { compareModulesById } = require("../util/comparators"); | ||
| const { dirname, mkdirp } = require("../util/fs"); | ||
| /** @typedef {import("../ChunkGraph").ModuleId} ModuleId */ | ||
| /** @typedef {import("../Compiler")} Compiler */ | ||
| /** @typedef {import("../Compiler").IntermediateFileSystem} IntermediateFileSystem */ | ||
| /** @typedef {import("../Module").BuildMeta} BuildMeta */ | ||
| /** @typedef {import("../ExportsInfo").ExportInfoName} ExportInfoName */ | ||
| /** | ||
| * Defines the manifest module data type used by this module. | ||
| * @typedef {object} ManifestModuleData | ||
| * @property {ModuleId} id | ||
| * @property {BuildMeta=} buildMeta | ||
| * @property {ExportInfoName[]=} exports | ||
| */ | ||
| /** | ||
| * Defines the lib manifest plugin options type used by this module. | ||
| * @typedef {object} LibManifestPluginOptions | ||
| * @property {string=} context Context of requests in the manifest file (defaults to the webpack context). | ||
| * @property {boolean=} entryOnly If true, only entry points will be exposed (default: true). | ||
| * @property {boolean=} format If true, manifest json file (output) will be formatted. | ||
| * @property {string=} name Name of the exposed dll function (external name, use value of 'output.library'). | ||
| * @property {string} path Absolute path to the manifest json file (output). | ||
| * @property {string=} type Type of the dll bundle (external type, use value of 'output.libraryTarget'). | ||
| */ | ||
| const PLUGIN_NAME = "LibManifestPlugin"; | ||
| class LibManifestPlugin { | ||
| /** | ||
| * Creates an instance of LibManifestPlugin. | ||
| * @param {LibManifestPluginOptions} options the options | ||
| */ | ||
| constructor(options) { | ||
| this.options = options; | ||
| } | ||
| /** | ||
| * Applies the plugin by registering its hooks on the compiler. | ||
| * @param {Compiler} compiler the compiler instance | ||
| * @returns {void} | ||
| */ | ||
| apply(compiler) { | ||
| compiler.hooks.emit.tapAsync( | ||
| { name: PLUGIN_NAME, stage: 110 }, | ||
| (compilation, callback) => { | ||
| const moduleGraph = compilation.moduleGraph; | ||
| // store used paths to detect issue and output an error. #18200 | ||
| /** @type {Set<string>} */ | ||
| const usedPaths = new Set(); | ||
| asyncLib.each( | ||
| [...compilation.chunks], | ||
| (chunk, callback) => { | ||
| if (!chunk.canBeInitial()) { | ||
| callback(); | ||
| return; | ||
| } | ||
| const chunkGraph = compilation.chunkGraph; | ||
| const targetPath = compilation.getPath(this.options.path, { | ||
| chunk | ||
| }); | ||
| if (usedPaths.has(targetPath)) { | ||
| callback(new Error("each chunk must have a unique path")); | ||
| return; | ||
| } | ||
| usedPaths.add(targetPath); | ||
| const name = | ||
| this.options.name && | ||
| compilation.getPath(this.options.name, { | ||
| chunk, | ||
| contentHashType: "javascript" | ||
| }); | ||
| const content = Object.create(null); | ||
| for (const module of chunkGraph.getOrderedChunkModulesIterable( | ||
| chunk, | ||
| compareModulesById(chunkGraph) | ||
| )) { | ||
| if ( | ||
| this.options.entryOnly && | ||
| !someInIterable( | ||
| moduleGraph.getIncomingConnections(module), | ||
| (c) => c.dependency instanceof EntryDependency | ||
| ) | ||
| ) { | ||
| continue; | ||
| } | ||
| const ident = module.libIdent({ | ||
| context: this.options.context || compiler.context, | ||
| associatedObjectForCache: compiler.root | ||
| }); | ||
| if (ident) { | ||
| const exportsInfo = moduleGraph.getExportsInfo(module); | ||
| const providedExports = exportsInfo.getProvidedExports(); | ||
| /** @type {ManifestModuleData} */ | ||
| const data = { | ||
| id: /** @type {ModuleId} */ (chunkGraph.getModuleId(module)), | ||
| buildMeta: /** @type {BuildMeta} */ (module.buildMeta), | ||
| exports: Array.isArray(providedExports) | ||
| ? providedExports | ||
| : undefined | ||
| }; | ||
| content[ident] = data; | ||
| } | ||
| } | ||
| const manifest = { | ||
| name, | ||
| type: this.options.type, | ||
| content | ||
| }; | ||
| // Apply formatting to content if format flag is true; | ||
| const manifestContent = this.options.format | ||
| ? JSON.stringify(manifest, null, 2) | ||
| : JSON.stringify(manifest); | ||
| const buffer = Buffer.from(manifestContent, "utf8"); | ||
| const intermediateFileSystem = | ||
| /** @type {IntermediateFileSystem} */ ( | ||
| compiler.intermediateFileSystem | ||
| ); | ||
| mkdirp( | ||
| intermediateFileSystem, | ||
| dirname(intermediateFileSystem, targetPath), | ||
| (err) => { | ||
| if (err) return callback(err); | ||
| intermediateFileSystem.writeFile(targetPath, buffer, callback); | ||
| } | ||
| ); | ||
| }, | ||
| callback | ||
| ); | ||
| } | ||
| ); | ||
| } | ||
| } | ||
| module.exports = LibManifestPlugin; |
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| Author Ivan Kopeykin @vankop | ||
| */ | ||
| "use strict"; | ||
| const WebpackError = require("./WebpackError"); | ||
| const CURRENT_METHOD_REGEXP = /at ([a-zA-Z0-9_.]*)/; | ||
| /** | ||
| * Creates the error message shown when an abstract API is called without | ||
| * being implemented by a subclass. | ||
| * @param {string=} method method name | ||
| * @returns {string} message | ||
| */ | ||
| function createMessage(method) { | ||
| return `Abstract method${method ? ` ${method}` : ""}. Must be overridden.`; | ||
| } | ||
| /** | ||
| * Captures a stack trace so the calling method name can be folded into the | ||
| * final abstract-method error message. | ||
| * @constructor | ||
| */ | ||
| function Message() { | ||
| /** @type {string | undefined} */ | ||
| this.stack = undefined; | ||
| Error.captureStackTrace(this); | ||
| /** @type {RegExpMatchArray | null} */ | ||
| const match = | ||
| /** @type {string} */ | ||
| (/** @type {unknown} */ (this.stack)) | ||
| .split("\n")[3] | ||
| .match(CURRENT_METHOD_REGEXP); | ||
| this.message = match && match[1] ? createMessage(match[1]) : createMessage(); | ||
| } | ||
| /** | ||
| * Error thrown when code reaches a method that is intended to be overridden by | ||
| * a subclass. | ||
| * @example | ||
| * ```js | ||
| * class FooClass { | ||
| * abstractMethod() { | ||
| * throw new AbstractMethodError(); // error message: Abstract method FooClass.abstractMethod. Must be overridden. | ||
| * } | ||
| * } | ||
| * ``` | ||
| */ | ||
| class AbstractMethodError extends WebpackError { | ||
| /** | ||
| * Creates an error whose message points at the abstract method that was | ||
| * invoked. | ||
| */ | ||
| constructor() { | ||
| super(new Message().message); | ||
| /** @type {string} */ | ||
| this.name = "AbstractMethodError"; | ||
| } | ||
| } | ||
| module.exports = AbstractMethodError; |
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| Author Sean Larkin @thelarkinn | ||
| */ | ||
| "use strict"; | ||
| const WebpackError = require("./WebpackError"); | ||
| /** @typedef {import("../Dependency").DependencyLocation} DependencyLocation */ | ||
| /** @typedef {import("../Module")} Module */ | ||
| /** | ||
| * Error raised when webpack detects an attempt to lazy-load a chunk name that | ||
| * is already claimed by an entrypoint's initial chunk. | ||
| */ | ||
| class AsyncDependencyToInitialChunkError extends WebpackError { | ||
| /** | ||
| * Captures the chunk name, originating module, and source location for an | ||
| * invalid async dependency targeting an initial chunk. | ||
| * @param {string} chunkName Name of Chunk | ||
| * @param {Module} module module tied to dependency | ||
| * @param {DependencyLocation} loc location of dependency | ||
| */ | ||
| constructor(chunkName, module, loc) { | ||
| super( | ||
| `It's not allowed to load an initial chunk on demand. The chunk name "${chunkName}" is already used by an entrypoint.` | ||
| ); | ||
| /** @type {string} */ | ||
| this.name = "AsyncDependencyToInitialChunkError"; | ||
| /** @type {Module} */ | ||
| this.module = module; | ||
| /** @type {DependencyLocation} */ | ||
| this.loc = loc; | ||
| } | ||
| } | ||
| module.exports = AsyncDependencyToInitialChunkError; |
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| Author Tobias Koppers @sokra | ||
| */ | ||
| "use strict"; | ||
| const WebpackError = require("./WebpackError"); | ||
| /** @typedef {import("../Chunk")} Chunk */ | ||
| class ChunkRenderError extends WebpackError { | ||
| /** | ||
| * Create a new ChunkRenderError | ||
| * @param {Chunk} chunk A chunk | ||
| * @param {string} file Related file | ||
| * @param {Error} error Original error | ||
| */ | ||
| constructor(chunk, file, error) { | ||
| super(); | ||
| /** @type {string} */ | ||
| this.name = "ChunkRenderError"; | ||
| /** @type {Chunk} */ | ||
| this.chunk = chunk; | ||
| /** @type {string} */ | ||
| this.file = file; | ||
| /** @type {Error} */ | ||
| this.error = error; | ||
| /** @type {string} */ | ||
| this.message = error.message; | ||
| /** @type {string} */ | ||
| this.details = error.stack; | ||
| } | ||
| } | ||
| /** @type {typeof ChunkRenderError} */ | ||
| module.exports = ChunkRenderError; |
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| Author Tobias Koppers @sokra | ||
| */ | ||
| "use strict"; | ||
| const WebpackError = require("./WebpackError"); | ||
| /** @typedef {import("../Module")} Module */ | ||
| class CodeGenerationError extends WebpackError { | ||
| /** | ||
| * Create a new CodeGenerationError | ||
| * @param {Module} module related module | ||
| * @param {Error} error Original error | ||
| */ | ||
| constructor(module, error) { | ||
| super(); | ||
| /** @type {string} */ | ||
| this.name = "CodeGenerationError"; | ||
| /** @type {Module} */ | ||
| this.module = module; | ||
| /** @type {Error} */ | ||
| this.error = error; | ||
| /** @type {string} */ | ||
| this.message = error.message; | ||
| /** @type {string} */ | ||
| this.details = error.stack; | ||
| } | ||
| } | ||
| /** @type {typeof CodeGenerationError} */ | ||
| module.exports = CodeGenerationError; |
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| Author Tobias Koppers @sokra | ||
| */ | ||
| "use strict"; | ||
| const makeSerializable = require("../util/makeSerializable"); | ||
| const WebpackError = require("./WebpackError"); | ||
| /** @typedef {import("../Dependency").DependencyLocation} DependencyLocation */ | ||
| /** | ||
| * Warning used for comment-related compilation issues, such as malformed magic | ||
| * comments that webpack can parse but wants to report. | ||
| */ | ||
| class CommentCompilationWarning extends WebpackError { | ||
| /** | ||
| * Captures a warning message together with the dependency location that | ||
| * triggered it. | ||
| * @param {string} message warning message | ||
| * @param {DependencyLocation} loc affected lines of code | ||
| */ | ||
| constructor(message, loc) { | ||
| super(message); | ||
| /** @type {string} */ | ||
| this.name = "CommentCompilationWarning"; | ||
| /** @type {DependencyLocation} */ | ||
| this.loc = loc; | ||
| } | ||
| } | ||
| makeSerializable( | ||
| CommentCompilationWarning, | ||
| "webpack/lib/errors/CommentCompilationWarning" | ||
| ); | ||
| module.exports = CommentCompilationWarning; |
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| Author Maksim Nazarjev @acupofspirt | ||
| */ | ||
| "use strict"; | ||
| const WebpackError = require("./WebpackError"); | ||
| class ConcurrentCompilationError extends WebpackError { | ||
| constructor() { | ||
| super( | ||
| "You ran Webpack twice. Each instance only supports a single concurrent compilation at a time." | ||
| ); | ||
| this.name = "ConcurrentCompilationError"; | ||
| } | ||
| } | ||
| module.exports = ConcurrentCompilationError; |
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| Author Gengkun He @ahabhgk | ||
| */ | ||
| "use strict"; | ||
| const makeSerializable = require("../util/makeSerializable"); | ||
| const WebpackError = require("./WebpackError"); | ||
| /** @typedef {import("../Module")} Module */ | ||
| /** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ | ||
| /** @typedef {"asyncWebAssembly" | "topLevelAwait" | "external promise" | "external script" | "external import" | "external module"} Feature */ | ||
| class EnvironmentNotSupportAsyncWarning extends WebpackError { | ||
| /** | ||
| * Creates an instance of EnvironmentNotSupportAsyncWarning. | ||
| * @param {Module} module module | ||
| * @param {Feature} feature feature | ||
| */ | ||
| constructor(module, feature) { | ||
| const message = `The generated code contains 'async/await' because this module is using "${feature}". | ||
| However, your target environment does not appear to support 'async/await'. | ||
| As a result, the code may not run as expected or may cause runtime errors.`; | ||
| super(message); | ||
| /** @type {string} */ | ||
| this.name = "EnvironmentNotSupportAsyncWarning"; | ||
| /** @type {Module} */ | ||
| this.module = module; | ||
| } | ||
| /** | ||
| * Creates an instance of EnvironmentNotSupportAsyncWarning. | ||
| * @param {Module} module module | ||
| * @param {RuntimeTemplate} runtimeTemplate compilation | ||
| * @param {Feature} feature feature | ||
| */ | ||
| static check(module, runtimeTemplate, feature) { | ||
| if (!runtimeTemplate.supportsAsyncFunction()) { | ||
| module.addWarning(new EnvironmentNotSupportAsyncWarning(module, feature)); | ||
| } | ||
| } | ||
| } | ||
| makeSerializable( | ||
| EnvironmentNotSupportAsyncWarning, | ||
| "webpack/lib/errors/EnvironmentNotSupportAsyncWarning" | ||
| ); | ||
| module.exports = EnvironmentNotSupportAsyncWarning; |
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| Author Sean Larkin @thelarkinn | ||
| */ | ||
| "use strict"; | ||
| const makeSerializable = require("../util/makeSerializable"); | ||
| const WebpackError = require("./WebpackError"); | ||
| /** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ | ||
| /** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ | ||
| /** | ||
| * Defines the callback callback. | ||
| * @template T | ||
| * @callback Callback | ||
| * @param {Error | null} err | ||
| * @param {T=} stats | ||
| * @returns {void} | ||
| */ | ||
| class HookWebpackError extends WebpackError { | ||
| /** | ||
| * Creates an instance of HookWebpackError. | ||
| * @param {Error} error inner error | ||
| * @param {string} hook name of hook | ||
| */ | ||
| constructor(error, hook) { | ||
| super(error ? error.message : undefined, error ? { cause: error } : {}); | ||
| this.hook = hook; | ||
| this.error = error; | ||
| /** @type {string} */ | ||
| this.name = "HookWebpackError"; | ||
| this.hideStack = true; | ||
| this.stack += `\n-- inner error --\n${error ? error.stack : ""}`; | ||
| this.details = `caused by plugins in ${hook}\n${error ? error.stack : ""}`; | ||
| } | ||
| /** | ||
| * Serializes this instance into the provided serializer context. | ||
| * @param {ObjectSerializerContext} context context | ||
| */ | ||
| serialize(context) { | ||
| const { write } = context; | ||
| write(this.error); | ||
| write(this.hook); | ||
| super.serialize(context); | ||
| } | ||
| /** | ||
| * Restores this instance from the provided deserializer context. | ||
| * @param {ObjectDeserializerContext} context context | ||
| */ | ||
| deserialize(context) { | ||
| const { read } = context; | ||
| this.error = read(); | ||
| this.hook = read(); | ||
| super.deserialize(context); | ||
| } | ||
| } | ||
| makeSerializable(HookWebpackError, "webpack/lib/errors/HookWebpackError"); | ||
| module.exports = HookWebpackError; | ||
| /** | ||
| * Creates webpack error. | ||
| * @param {Error} error an error | ||
| * @param {string} hook name of the hook | ||
| * @returns {WebpackError} a webpack error | ||
| */ | ||
| const makeWebpackError = (error, hook) => { | ||
| if (error instanceof WebpackError) return error; | ||
| return new HookWebpackError(error, hook); | ||
| }; | ||
| module.exports.makeWebpackError = makeWebpackError; | ||
| /** | ||
| * Creates webpack error callback. | ||
| * @template T | ||
| * @param {(err: Error | null, result?: T) => void} callback webpack error callback | ||
| * @param {string} hook name of hook | ||
| * @returns {Callback<T>} generic callback | ||
| */ | ||
| const makeWebpackErrorCallback = (callback, hook) => (err, result) => { | ||
| if (err) { | ||
| if (err instanceof WebpackError) { | ||
| callback(err); | ||
| return; | ||
| } | ||
| callback(new HookWebpackError(err, hook)); | ||
| return; | ||
| } | ||
| callback(null, result); | ||
| }; | ||
| module.exports.makeWebpackErrorCallback = makeWebpackErrorCallback; | ||
| /** | ||
| * Try run or webpack error. | ||
| * @template T | ||
| * @param {() => T} fn function which will be wrapping in try catch | ||
| * @param {string} hook name of hook | ||
| * @returns {T} the result | ||
| */ | ||
| const tryRunOrWebpackError = (fn, hook) => { | ||
| /** @type {T} */ | ||
| let r; | ||
| try { | ||
| r = fn(); | ||
| } catch (err) { | ||
| if (err instanceof WebpackError) { | ||
| throw err; | ||
| } | ||
| throw new HookWebpackError(/** @type {Error} */ (err), hook); | ||
| } | ||
| return r; | ||
| }; | ||
| module.exports.tryRunOrWebpackError = tryRunOrWebpackError; |
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| Author Ivan Kopeykin @vankop | ||
| */ | ||
| "use strict"; | ||
| const ModuleFactory = require("../ModuleFactory"); | ||
| /** @typedef {import("../ModuleFactory").ModuleFactoryCallback} ModuleFactoryCallback */ | ||
| /** @typedef {import("../ModuleFactory").ModuleFactoryCreateData} ModuleFactoryCreateData */ | ||
| /** @typedef {import("../NormalModuleFactory")} NormalModuleFactory */ | ||
| /** | ||
| * Ignores error when module is unresolved | ||
| */ | ||
| class IgnoreErrorModuleFactory extends ModuleFactory { | ||
| /** | ||
| * Creates an instance of IgnoreErrorModuleFactory. | ||
| * @param {NormalModuleFactory} normalModuleFactory normalModuleFactory instance | ||
| */ | ||
| constructor(normalModuleFactory) { | ||
| super(); | ||
| this.normalModuleFactory = normalModuleFactory; | ||
| } | ||
| /** | ||
| * Processes the provided data. | ||
| * @param {ModuleFactoryCreateData} data data object | ||
| * @param {ModuleFactoryCallback} callback callback | ||
| * @returns {void} | ||
| */ | ||
| create(data, callback) { | ||
| this.normalModuleFactory.create(data, (err, result) => | ||
| callback(null, result) | ||
| ); | ||
| } | ||
| } | ||
| module.exports = IgnoreErrorModuleFactory; |
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| Author Tobias Koppers @sokra | ||
| */ | ||
| "use strict"; | ||
| const makeSerializable = require("../util/makeSerializable"); | ||
| const WebpackError = require("./WebpackError"); | ||
| /** @typedef {import("../Module")} Module */ | ||
| class InvalidDependenciesModuleWarning extends WebpackError { | ||
| /** | ||
| * Creates an instance of InvalidDependenciesModuleWarning. | ||
| * @param {Module} module module tied to dependency | ||
| * @param {Iterable<string>} deps invalid dependencies | ||
| */ | ||
| constructor(module, deps) { | ||
| const orderedDeps = deps ? [...deps].sort() : []; | ||
| const depsList = orderedDeps.map((dep) => ` * ${JSON.stringify(dep)}`); | ||
| super(`Invalid dependencies have been reported by plugins or loaders for this module. All reported dependencies need to be absolute paths. | ||
| Invalid dependencies may lead to broken watching and caching. | ||
| As best effort we try to convert all invalid values to absolute paths and converting globs into context dependencies, but this is deprecated behavior. | ||
| Loaders: Pass absolute paths to this.addDependency (existing files), this.addMissingDependency (not existing files), and this.addContextDependency (directories). | ||
| Plugins: Pass absolute paths to fileDependencies (existing files), missingDependencies (not existing files), and contextDependencies (directories). | ||
| Globs: They are not supported. Pass absolute path to the directory as context dependencies. | ||
| The following invalid values have been reported: | ||
| ${depsList.slice(0, 3).join("\n")}${ | ||
| depsList.length > 3 ? "\n * and more ..." : "" | ||
| }`); | ||
| /** @type {string} */ | ||
| this.name = "InvalidDependenciesModuleWarning"; | ||
| this.details = depsList.slice(3).join("\n"); | ||
| this.module = module; | ||
| } | ||
| } | ||
| makeSerializable( | ||
| InvalidDependenciesModuleWarning, | ||
| "webpack/lib/errors/InvalidDependenciesModuleWarning" | ||
| ); | ||
| module.exports = InvalidDependenciesModuleWarning; |
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| */ | ||
| "use strict"; | ||
| /** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ | ||
| /** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ | ||
| const makeSerializable = require("../util/makeSerializable"); | ||
| const CONTEXT = 20; | ||
| class JSONParseError extends SyntaxError { | ||
| /** | ||
| * @param {Error} err err | ||
| * @param {EXPECTED_ANY} raw raw | ||
| * @param {string} txt text | ||
| */ | ||
| constructor(err, raw, txt) { | ||
| let originalMessage = err.message; | ||
| /** @type {string} */ | ||
| let message; | ||
| /** @type {number} */ | ||
| let position; | ||
| if (typeof raw !== "string") { | ||
| message = `Cannot parse ${Array.isArray(raw) && raw.length === 0 ? "an empty array" : String(raw)}`; | ||
| position = 0; | ||
| } else if (!txt) { | ||
| message = `${originalMessage} while parsing empty string`; | ||
| position = 0; | ||
| } else { | ||
| // Node 20 puts single quotes around the token and a comma after it | ||
| const UNEXPECTED_TOKEN = /^Unexpected token '?(.)'?(,)? /i; | ||
| const badTokenMatch = originalMessage.match(UNEXPECTED_TOKEN); | ||
| const badIndexMatch = originalMessage.match(/ position\s+(\d+)/i); | ||
| if (badTokenMatch) { | ||
| const h = badTokenMatch[1].charCodeAt(0).toString(16).toUpperCase(); | ||
| const hex = `0x${h.length % 2 ? "0" : ""}${h}`; | ||
| originalMessage = originalMessage.replace( | ||
| UNEXPECTED_TOKEN, | ||
| `Unexpected token ${JSON.stringify(badTokenMatch[1])} (${hex})$2 ` | ||
| ); | ||
| } | ||
| /** @type {number | undefined} */ | ||
| let errIdx; | ||
| if (badIndexMatch) { | ||
| errIdx = Number(badIndexMatch[1]); | ||
| } else if ( | ||
| // doesn't happen in Node 22+ | ||
| /^Unexpected end of JSON.*/i.test(originalMessage) | ||
| ) { | ||
| errIdx = txt.length - 1; | ||
| } | ||
| if (errIdx === undefined) { | ||
| message = `${originalMessage} while parsing '${txt.slice(0, CONTEXT * 2)}'`; | ||
| position = 0; | ||
| } else { | ||
| const start = errIdx <= CONTEXT ? 0 : errIdx - CONTEXT; | ||
| const end = | ||
| errIdx + CONTEXT >= txt.length ? txt.length : errIdx + CONTEXT; | ||
| const slice = `${start ? "..." : ""}${txt.slice(start, end)}${end === txt.length ? "" : "..."}`; | ||
| message = `${originalMessage} while parsing ${txt === slice ? "" : "near "}${JSON.stringify(slice)}`; | ||
| position = errIdx; | ||
| } | ||
| } | ||
| super(message); | ||
| /** @type {string} */ | ||
| this.name = "JSONParseError"; | ||
| /** @type {string | undefined} */ | ||
| this.stack = undefined; | ||
| /** @type {Error} */ | ||
| this.systemError = err; | ||
| /** @type {EXPECTED_ANY} */ | ||
| this.raw = raw; | ||
| /** @type {string} */ | ||
| this.txt = txt; | ||
| /** @type {number} */ | ||
| this.position = position; | ||
| } | ||
| /** | ||
| * Serializes this instance into the provided serializer context. | ||
| * @param {ObjectSerializerContext} context context | ||
| */ | ||
| serialize({ write }) { | ||
| write(this.systemError); | ||
| write(this.raw); | ||
| write(this.txt); | ||
| } | ||
| /** | ||
| * Restores this instance from the provided deserializer context. | ||
| * @param {ObjectDeserializerContext} context context | ||
| * @returns {JSONParseError} DelegatedModule | ||
| */ | ||
| static deserialize(context) { | ||
| const { read } = context; | ||
| return new JSONParseError(read(), read(), read()); | ||
| } | ||
| } | ||
| makeSerializable(JSONParseError, "webpack/lib/errors/JSONParseError"); | ||
| module.exports = JSONParseError; |
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| Author Tobias Koppers @sokra | ||
| */ | ||
| "use strict"; | ||
| const { cutOffLoaderExecution } = require("../ErrorHelpers"); | ||
| const makeSerializable = require("../util/makeSerializable"); | ||
| const WebpackError = require("./WebpackError"); | ||
| /** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ | ||
| /** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ | ||
| /** @typedef {Error & { hideStack?: boolean }} ErrorWithHideStack */ | ||
| class ModuleBuildError extends WebpackError { | ||
| /** | ||
| * Creates an instance of ModuleBuildError. | ||
| * @param {string | ErrorWithHideStack} err error thrown | ||
| * @param {{ from?: string | null }} info additional info | ||
| */ | ||
| constructor(err, { from = null } = {}) { | ||
| let message = "Module build failed"; | ||
| /** @type {undefined | string} */ | ||
| let details; | ||
| message += from ? ` (from ${from}):\n` : ": "; | ||
| if (err !== null && typeof err === "object") { | ||
| if (typeof err.stack === "string" && err.stack) { | ||
| const stack = cutOffLoaderExecution(err.stack); | ||
| if (!err.hideStack) { | ||
| message += stack; | ||
| } else { | ||
| details = stack; | ||
| message += | ||
| typeof err.message === "string" && err.message ? err.message : err; | ||
| } | ||
| } else if (typeof err.message === "string" && err.message) { | ||
| message += err.message; | ||
| } else { | ||
| message += String(err); | ||
| } | ||
| } else { | ||
| message += String(err); | ||
| } | ||
| super(message); | ||
| /** @type {string} */ | ||
| this.name = "ModuleBuildError"; | ||
| this.details = details; | ||
| this.error = err; | ||
| } | ||
| /** | ||
| * Serializes this instance into the provided serializer context. | ||
| * @param {ObjectSerializerContext} context context | ||
| */ | ||
| serialize(context) { | ||
| const { write } = context; | ||
| write(this.error); | ||
| super.serialize(context); | ||
| } | ||
| /** | ||
| * Restores this instance from the provided deserializer context. | ||
| * @param {ObjectDeserializerContext} context context | ||
| */ | ||
| deserialize(context) { | ||
| const { read } = context; | ||
| this.error = read(); | ||
| super.deserialize(context); | ||
| } | ||
| } | ||
| makeSerializable(ModuleBuildError, "webpack/lib/errors/ModuleBuildError"); | ||
| module.exports = ModuleBuildError; |
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| Author Tobias Koppers @sokra | ||
| */ | ||
| "use strict"; | ||
| const WebpackError = require("./WebpackError"); | ||
| /** @typedef {import("../Dependency").DependencyLocation} DependencyLocation */ | ||
| /** @typedef {import("../Module")} Module */ | ||
| /** @typedef {import("./ModuleBuildError").ErrorWithHideStack} ErrorWithHideStack */ | ||
| class ModuleDependencyError extends WebpackError { | ||
| /** | ||
| * Creates an instance of ModuleDependencyError. | ||
| * @param {Module} module module tied to dependency | ||
| * @param {ErrorWithHideStack} err error thrown | ||
| * @param {DependencyLocation} loc location of dependency | ||
| */ | ||
| constructor(module, err, loc) { | ||
| super(err.message); | ||
| /** @type {string} */ | ||
| this.name = "ModuleDependencyError"; | ||
| this.details = | ||
| err && !err.hideStack | ||
| ? /** @type {string} */ (err.stack).split("\n").slice(1).join("\n") | ||
| : undefined; | ||
| this.module = module; | ||
| this.loc = loc; | ||
| /** error is not (de)serialized, so it might be undefined after deserialization */ | ||
| this.error = err; | ||
| if (err && err.hideStack && err.stack) { | ||
| this.stack = /** @type {string} */ `${err.stack | ||
| .split("\n") | ||
| .slice(1) | ||
| .join("\n")}\n\n${this.stack}`; | ||
| } | ||
| } | ||
| } | ||
| module.exports = ModuleDependencyError; |
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| Author Tobias Koppers @sokra | ||
| */ | ||
| "use strict"; | ||
| const makeSerializable = require("../util/makeSerializable"); | ||
| const WebpackError = require("./WebpackError"); | ||
| /** @typedef {import("../Dependency").DependencyLocation} DependencyLocation */ | ||
| /** @typedef {import("../Module")} Module */ | ||
| /** @typedef {import("./ModuleDependencyError").ErrorWithHideStack} ErrorWithHideStack */ | ||
| class ModuleDependencyWarning extends WebpackError { | ||
| /** | ||
| * Creates an instance of ModuleDependencyWarning. | ||
| * @param {Module} module module tied to dependency | ||
| * @param {ErrorWithHideStack} err error thrown | ||
| * @param {DependencyLocation} loc location of dependency | ||
| */ | ||
| constructor(module, err, loc) { | ||
| super(err ? err.message : ""); | ||
| /** @type {string} */ | ||
| this.name = "ModuleDependencyWarning"; | ||
| this.details = | ||
| err && !err.hideStack | ||
| ? /** @type {string} */ (err.stack).split("\n").slice(1).join("\n") | ||
| : undefined; | ||
| this.module = module; | ||
| this.loc = loc; | ||
| /** error is not (de)serialized, so it might be undefined after deserialization */ | ||
| this.error = err; | ||
| if (err && err.hideStack && err.stack) { | ||
| this.stack = /** @type {string} */ `${err.stack | ||
| .split("\n") | ||
| .slice(1) | ||
| .join("\n")}\n\n${this.stack}`; | ||
| } | ||
| } | ||
| } | ||
| makeSerializable( | ||
| ModuleDependencyWarning, | ||
| "webpack/lib/errors/ModuleDependencyWarning" | ||
| ); | ||
| module.exports = ModuleDependencyWarning; |
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| Author Tobias Koppers @sokra | ||
| */ | ||
| "use strict"; | ||
| const { cleanUp } = require("../ErrorHelpers"); | ||
| const makeSerializable = require("../util/makeSerializable"); | ||
| const WebpackError = require("./WebpackError"); | ||
| /** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ | ||
| /** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ | ||
| class ModuleError extends WebpackError { | ||
| /** | ||
| * @param {Error} err error thrown | ||
| * @param {{ from?: string | null }} info additional info | ||
| */ | ||
| constructor(err, { from = null } = {}) { | ||
| let message = "Module Error"; | ||
| message += from ? ` (from ${from}):\n` : ": "; | ||
| if (err && typeof err === "object" && err.message) { | ||
| message += err.message; | ||
| } else if (err) { | ||
| message += err; | ||
| } | ||
| super(message); | ||
| /** @type {string} */ | ||
| this.name = "ModuleError"; | ||
| /** @type {Error} */ | ||
| this.error = err; | ||
| /** @type {string | undefined} */ | ||
| this.details = | ||
| err && typeof err === "object" && err.stack | ||
| ? cleanUp(err.stack, this.message) | ||
| : undefined; | ||
| } | ||
| /** | ||
| * Serializes this instance into the provided serializer context. | ||
| * @param {ObjectSerializerContext} context context | ||
| */ | ||
| serialize(context) { | ||
| const { write } = context; | ||
| write(this.error); | ||
| super.serialize(context); | ||
| } | ||
| /** | ||
| * Restores this instance from the provided deserializer context. | ||
| * @param {ObjectDeserializerContext} context context | ||
| */ | ||
| deserialize(context) { | ||
| const { read } = context; | ||
| this.error = read(); | ||
| super.deserialize(context); | ||
| } | ||
| } | ||
| makeSerializable(ModuleError, "webpack/lib/errors/ModuleError"); | ||
| module.exports = ModuleError; |
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| Author Tobias Koppers @sokra | ||
| */ | ||
| "use strict"; | ||
| const WebpackError = require("./WebpackError"); | ||
| /** @typedef {import("../Module")} Module */ | ||
| class ModuleHashingError extends WebpackError { | ||
| /** | ||
| * Create a new ModuleHashingError | ||
| * @param {Module} module related module | ||
| * @param {Error} error Original error | ||
| */ | ||
| constructor(module, error) { | ||
| super(); | ||
| /** @type {string} */ | ||
| this.name = "ModuleHashingError"; | ||
| this.error = error; | ||
| this.message = error.message; | ||
| this.details = error.stack; | ||
| this.module = module; | ||
| } | ||
| } | ||
| /** @type {typeof ModuleHashingError} */ | ||
| module.exports = ModuleHashingError; |
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| Author Tobias Koppers @sokra | ||
| */ | ||
| "use strict"; | ||
| const WebpackError = require("./WebpackError"); | ||
| /** @typedef {import("../Dependency").DependencyLocation} DependencyLocation */ | ||
| /** @typedef {import("../Module")} Module */ | ||
| const previouslyPolyfilledBuiltinModules = { | ||
| assert: "assert/", | ||
| buffer: "buffer/", | ||
| console: "console-browserify", | ||
| constants: "constants-browserify", | ||
| crypto: "crypto-browserify", | ||
| domain: "domain-browser", | ||
| events: "events/", | ||
| http: "stream-http", | ||
| https: "https-browserify", | ||
| os: "os-browserify/browser", | ||
| path: "path-browserify", | ||
| punycode: "punycode/", | ||
| process: "process/browser", | ||
| querystring: "querystring-es3", | ||
| stream: "stream-browserify", | ||
| _stream_duplex: "readable-stream/duplex", | ||
| _stream_passthrough: "readable-stream/passthrough", | ||
| _stream_readable: "readable-stream/readable", | ||
| _stream_transform: "readable-stream/transform", | ||
| _stream_writable: "readable-stream/writable", | ||
| string_decoder: "string_decoder/", | ||
| sys: "util/", | ||
| timers: "timers-browserify", | ||
| tty: "tty-browserify", | ||
| url: "url/", | ||
| util: "util/", | ||
| vm: "vm-browserify", | ||
| zlib: "browserify-zlib" | ||
| }; | ||
| class ModuleNotFoundError extends WebpackError { | ||
| /** | ||
| * Creates an instance of ModuleNotFoundError. | ||
| * @param {Module | null} module module tied to dependency | ||
| * @param {Error & { details?: string }} err error thrown | ||
| * @param {DependencyLocation} loc location of dependency | ||
| */ | ||
| constructor(module, err, loc) { | ||
| let message = `Module not found: ${err.toString()}`; | ||
| // TODO remove in webpack 6 | ||
| const match = err.message.match(/Can't resolve '([^']+)'/); | ||
| if (match) { | ||
| const request = match[1]; | ||
| const alias = | ||
| previouslyPolyfilledBuiltinModules[ | ||
| /** @type {keyof previouslyPolyfilledBuiltinModules} */ (request) | ||
| ]; | ||
| if (alias) { | ||
| const pathIndex = alias.indexOf("/"); | ||
| const dependency = pathIndex > 0 ? alias.slice(0, pathIndex) : alias; | ||
| message += | ||
| "\n\n" + | ||
| "BREAKING CHANGE: " + | ||
| "webpack < 5 used to include polyfills for node.js core modules by default.\n" + | ||
| "This is no longer the case. Verify if you need this module and configure a polyfill for it.\n\n"; | ||
| message += | ||
| "If you want to include a polyfill, you need to:\n" + | ||
| `\t- add a fallback 'resolve.fallback: { "${request}": require.resolve("${alias}") }'\n` + | ||
| `\t- install '${dependency}'\n`; | ||
| message += | ||
| "If you don't want to include a polyfill, you can use an empty module like this:\n" + | ||
| `\tresolve.fallback: { "${request}": false }`; | ||
| } | ||
| } | ||
| super(message); | ||
| /** @type {string} */ | ||
| this.name = "ModuleNotFoundError"; | ||
| this.details = err.details; | ||
| this.module = module; | ||
| this.error = err; | ||
| this.loc = loc; | ||
| } | ||
| } | ||
| module.exports = ModuleNotFoundError; |
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| Author Tobias Koppers @sokra | ||
| */ | ||
| "use strict"; | ||
| const makeSerializable = require("../util/makeSerializable"); | ||
| const WebpackError = require("./WebpackError"); | ||
| /** @typedef {import("../Dependency").DependencyLocation} DependencyLocation */ | ||
| /** @typedef {import("../Dependency").SourcePosition} SourcePosition */ | ||
| /** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ | ||
| /** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ | ||
| const WASM_HEADER = Buffer.from([0x00, 0x61, 0x73, 0x6d]); | ||
| class ModuleParseError extends WebpackError { | ||
| /** | ||
| * Creates an instance of ModuleParseError. | ||
| * @param {string | Buffer} source source code | ||
| * @param {Error & { loc?: SourcePosition }} err the parse error | ||
| * @param {string[]} loaders the loaders used | ||
| * @param {string} type module type | ||
| */ | ||
| constructor(source, err, loaders, type) { | ||
| let message = `Module parse failed: ${err && err.message}`; | ||
| /** @type {undefined | DependencyLocation} */ | ||
| let loc; | ||
| if ( | ||
| ((Buffer.isBuffer(source) && source.subarray(0, 4).equals(WASM_HEADER)) || | ||
| (typeof source === "string" && /^\0asm/.test(source))) && | ||
| !type.startsWith("webassembly") | ||
| ) { | ||
| message += | ||
| "\nThe module seem to be a WebAssembly module, but module is not flagged as WebAssembly module for webpack."; | ||
| message += | ||
| "\nBREAKING CHANGE: Since webpack 5 WebAssembly is not enabled by default and flagged as experimental feature."; | ||
| message += | ||
| "\nYou need to enable one of the WebAssembly experiments via 'experiments.asyncWebAssembly: true' (based on async modules) or 'experiments.syncWebAssembly: true' (like webpack 4, deprecated)."; | ||
| message += | ||
| "\nFor files that transpile to WebAssembly, make sure to set the module type in the 'module.rules' section of the config (e. g. 'type: \"webassembly/async\"')."; | ||
| } else if (!loaders) { | ||
| message += | ||
| "\nYou may need an appropriate loader to handle this file type. " + | ||
| "See https://webpack.js.org/concepts/loaders"; | ||
| } else if (loaders.length >= 1) { | ||
| message += `\nFile was processed with these loaders:${loaders | ||
| .map((loader) => `\n * ${loader}`) | ||
| .join("")}`; | ||
| message += | ||
| "\nYou may need an additional loader to handle the result of these loaders."; | ||
| } else { | ||
| message += | ||
| "\nYou may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders"; | ||
| } | ||
| if ( | ||
| err && | ||
| err.loc && | ||
| typeof err.loc === "object" && | ||
| typeof err.loc.line === "number" | ||
| ) { | ||
| const lineNumber = err.loc.line; | ||
| if ( | ||
| Buffer.isBuffer(source) || | ||
| // eslint-disable-next-line no-control-regex | ||
| /[\0\u0001\u0002\u0003\u0004\u0005\u0006\u0007]/.test(source) | ||
| ) { | ||
| // binary file | ||
| message += "\n(Source code omitted for this binary file)"; | ||
| } else { | ||
| const sourceLines = source.split(/\r?\n/); | ||
| const start = Math.max(0, lineNumber - 3); | ||
| const linesBefore = sourceLines.slice(start, lineNumber - 1); | ||
| const theLine = sourceLines[lineNumber - 1]; | ||
| const linesAfter = sourceLines.slice(lineNumber, lineNumber + 2); | ||
| message += `${linesBefore | ||
| .map((l) => `\n| ${l}`) | ||
| .join( | ||
| "" | ||
| )}\n> ${theLine}${linesAfter.map((l) => `\n| ${l}`).join("")}`; | ||
| } | ||
| loc = { start: err.loc }; | ||
| } else if (err && err.stack) { | ||
| message += `\n${err.stack}`; | ||
| } | ||
| super(message); | ||
| /** @type {string} */ | ||
| this.name = "ModuleParseError"; | ||
| /** @type {undefined | DependencyLocation} */ | ||
| this.loc = loc; | ||
| /** @type {Error} */ | ||
| this.error = err; | ||
| } | ||
| /** | ||
| * Serializes this instance into the provided serializer context. | ||
| * @param {ObjectSerializerContext} context context | ||
| */ | ||
| serialize(context) { | ||
| const { write } = context; | ||
| write(this.error); | ||
| super.serialize(context); | ||
| } | ||
| /** | ||
| * Restores this instance from the provided deserializer context. | ||
| * @param {ObjectDeserializerContext} context context | ||
| */ | ||
| deserialize(context) { | ||
| const { read } = context; | ||
| this.error = read(); | ||
| super.deserialize(context); | ||
| } | ||
| } | ||
| makeSerializable(ModuleParseError, "webpack/lib/errors/ModuleParseError"); | ||
| module.exports = ModuleParseError; |
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| Author Tobias Koppers @sokra | ||
| */ | ||
| "use strict"; | ||
| const WebpackError = require("./WebpackError"); | ||
| /** @typedef {import("../Module")} Module */ | ||
| class ModuleRestoreError extends WebpackError { | ||
| /** | ||
| * Creates an instance of ModuleRestoreError. | ||
| * @param {Module} module module tied to dependency | ||
| * @param {string | Error} err error thrown | ||
| */ | ||
| constructor(module, err) { | ||
| let message = "Module restore failed: "; | ||
| /** @type {string | undefined} */ | ||
| const details = undefined; | ||
| if (err !== null && typeof err === "object") { | ||
| if (typeof err.stack === "string" && err.stack) { | ||
| const stack = err.stack; | ||
| message += stack; | ||
| } else if (typeof err.message === "string" && err.message) { | ||
| message += err.message; | ||
| } else { | ||
| message += err; | ||
| } | ||
| } else { | ||
| message += String(err); | ||
| } | ||
| super(message); | ||
| /** @type {string} */ | ||
| this.name = "ModuleRestoreError"; | ||
| /** @type {string | undefined} */ | ||
| this.details = details; | ||
| this.module = module; | ||
| this.error = err; | ||
| } | ||
| } | ||
| /** @type {typeof ModuleRestoreError} */ | ||
| module.exports = ModuleRestoreError; |
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| Author Tobias Koppers @sokra | ||
| */ | ||
| "use strict"; | ||
| const WebpackError = require("./WebpackError"); | ||
| /** @typedef {import("../Module")} Module */ | ||
| class ModuleStoreError extends WebpackError { | ||
| /** | ||
| * Creates an instance of ModuleStoreError. | ||
| * @param {Module} module module tied to dependency | ||
| * @param {string | Error} err error thrown | ||
| */ | ||
| constructor(module, err) { | ||
| let message = "Module storing failed: "; | ||
| /** @type {string | undefined} */ | ||
| const details = undefined; | ||
| if (err !== null && typeof err === "object") { | ||
| if (typeof err.stack === "string" && err.stack) { | ||
| const stack = err.stack; | ||
| message += stack; | ||
| } else if (typeof err.message === "string" && err.message) { | ||
| message += err.message; | ||
| } else { | ||
| message += err; | ||
| } | ||
| } else { | ||
| message += String(err); | ||
| } | ||
| super(message); | ||
| /** @type {string} */ | ||
| this.name = "ModuleStoreError"; | ||
| this.details = /** @type {string | undefined} */ (details); | ||
| this.module = module; | ||
| this.error = err; | ||
| } | ||
| } | ||
| /** @type {typeof ModuleStoreError} */ | ||
| module.exports = ModuleStoreError; |
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| Author Tobias Koppers @sokra | ||
| */ | ||
| "use strict"; | ||
| const { cleanUp } = require("../ErrorHelpers"); | ||
| const makeSerializable = require("../util/makeSerializable"); | ||
| const WebpackError = require("./WebpackError"); | ||
| /** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ | ||
| /** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ | ||
| class ModuleWarning extends WebpackError { | ||
| /** | ||
| * Creates an instance of ModuleWarning. | ||
| * @param {Error} warning error thrown | ||
| * @param {{ from?: string | null }} info additional info | ||
| */ | ||
| constructor(warning, { from = null } = {}) { | ||
| let message = "Module Warning"; | ||
| message += from ? ` (from ${from}):\n` : ": "; | ||
| if (warning && typeof warning === "object" && warning.message) { | ||
| message += warning.message; | ||
| } else if (warning) { | ||
| message += String(warning); | ||
| } | ||
| super(message); | ||
| /** @type {string} */ | ||
| this.name = "ModuleWarning"; | ||
| this.warning = warning; | ||
| this.details = | ||
| warning && typeof warning === "object" && warning.stack | ||
| ? cleanUp(warning.stack, this.message) | ||
| : undefined; | ||
| } | ||
| /** | ||
| * Serializes this instance into the provided serializer context. | ||
| * @param {ObjectSerializerContext} context context | ||
| */ | ||
| serialize(context) { | ||
| const { write } = context; | ||
| write(this.warning); | ||
| super.serialize(context); | ||
| } | ||
| /** | ||
| * Restores this instance from the provided deserializer context. | ||
| * @param {ObjectDeserializerContext} context context | ||
| */ | ||
| deserialize(context) { | ||
| const { read } = context; | ||
| this.warning = read(); | ||
| super.deserialize(context); | ||
| } | ||
| } | ||
| makeSerializable(ModuleWarning, "webpack/lib/errors/ModuleWarning"); | ||
| /** @type {typeof ModuleWarning} */ | ||
| module.exports = ModuleWarning; |
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| Author Tobias Koppers @sokra | ||
| */ | ||
| "use strict"; | ||
| /** @typedef {import("../Dependency").DependencyLocation} DependencyLocation */ | ||
| const makeSerializable = require("../util/makeSerializable"); | ||
| const WebpackError = require("./WebpackError"); | ||
| class NodeStuffInWebError extends WebpackError { | ||
| /** | ||
| * Creates an instance of NodeStuffInWebError. | ||
| * @param {DependencyLocation} loc loc | ||
| * @param {string} expression expression | ||
| * @param {string} description description | ||
| */ | ||
| constructor(loc, expression, description) { | ||
| super( | ||
| `${JSON.stringify( | ||
| expression | ||
| )} has been used, it will be undefined in next major version. | ||
| ${description}` | ||
| ); | ||
| /** @type {string} */ | ||
| this.name = "NodeStuffInWebError"; | ||
| this.loc = loc; | ||
| } | ||
| } | ||
| makeSerializable(NodeStuffInWebError, "webpack/lib/NodeStuffInWebError"); | ||
| module.exports = NodeStuffInWebError; |
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| Author Tobias Koppers @sokra | ||
| */ | ||
| "use strict"; | ||
| const makeSerializable = require("../util/makeSerializable"); | ||
| const WebpackError = require("./WebpackError"); | ||
| class NonErrorEmittedError extends WebpackError { | ||
| /** | ||
| * @param {EXPECTED_ANY} error value which is not an instance of Error | ||
| */ | ||
| constructor(error) { | ||
| super(); | ||
| this.name = "NonErrorEmittedError"; | ||
| this.message = `(Emitted value instead of an instance of Error) ${error}`; | ||
| } | ||
| } | ||
| makeSerializable( | ||
| NonErrorEmittedError, | ||
| "webpack/lib/errors/NonErrorEmittedError" | ||
| ); | ||
| module.exports = NonErrorEmittedError; |
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| Author Ivan Kopeykin @vankop | ||
| */ | ||
| "use strict"; | ||
| const makeSerializable = require("../util/makeSerializable"); | ||
| const WebpackError = require("./WebpackError"); | ||
| /** | ||
| * Error raised when webpack encounters a resource URI scheme that no installed | ||
| * plugin knows how to read. | ||
| */ | ||
| class UnhandledSchemeError extends WebpackError { | ||
| /** | ||
| * Creates an error explaining that the current resource scheme is not | ||
| * supported by the active plugin set. | ||
| * @param {string} scheme scheme | ||
| * @param {string} resource resource | ||
| */ | ||
| constructor(scheme, resource) { | ||
| super( | ||
| `Reading from "${resource}" is not handled by plugins (Unhandled scheme).` + | ||
| '\nWebpack supports "data:" and "file:" URIs by default.' + | ||
| `\nYou may need an additional plugin to handle "${scheme}:" URIs.` | ||
| ); | ||
| this.file = resource; | ||
| /** @type {string} */ | ||
| this.name = "UnhandledSchemeError"; | ||
| } | ||
| } | ||
| makeSerializable( | ||
| UnhandledSchemeError, | ||
| "webpack/lib/errors/UnhandledSchemeError", | ||
| "UnhandledSchemeError" | ||
| ); | ||
| module.exports = UnhandledSchemeError; |
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| Author Tobias Koppers @sokra | ||
| */ | ||
| "use strict"; | ||
| const makeSerializable = require("../util/makeSerializable"); | ||
| const WebpackError = require("./WebpackError"); | ||
| /** @typedef {import("../Dependency").DependencyLocation} DependencyLocation */ | ||
| class UnsupportedFeatureWarning extends WebpackError { | ||
| /** | ||
| * Creates an instance of UnsupportedFeatureWarning. | ||
| * @param {string} message description of warning | ||
| * @param {DependencyLocation} loc location start and end positions of the module | ||
| */ | ||
| constructor(message, loc) { | ||
| super(message); | ||
| /** @type {string} */ | ||
| this.name = "UnsupportedFeatureWarning"; | ||
| /** @type {DependencyLocation} */ | ||
| this.loc = loc; | ||
| /** @type {boolean} */ | ||
| this.hideStack = true; | ||
| } | ||
| } | ||
| makeSerializable( | ||
| UnsupportedFeatureWarning, | ||
| "webpack/lib/errors/UnsupportedFeatureWarning" | ||
| ); | ||
| module.exports = UnsupportedFeatureWarning; |
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| Author Jarid Margolin @jaridmargolin | ||
| */ | ||
| "use strict"; | ||
| const inspect = require("util").inspect.custom; | ||
| const makeSerializable = require("../util/makeSerializable"); | ||
| /** @typedef {import("../Chunk")} Chunk */ | ||
| /** @typedef {import("../Dependency").DependencyLocation} DependencyLocation */ | ||
| /** @typedef {import("../Module")} Module */ | ||
| /** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ | ||
| /** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ | ||
| class WebpackError extends Error { | ||
| /** | ||
| * Creates an instance of WebpackError. | ||
| * @param {string=} message error message | ||
| * @param {{ cause?: unknown }} options error options | ||
| */ | ||
| constructor(message, options = {}) { | ||
| super(message, options); | ||
| /** @type {string=} */ | ||
| this.details = undefined; | ||
| /** @type {(Module | null)=} */ | ||
| this.module = undefined; | ||
| /** @type {DependencyLocation=} */ | ||
| this.loc = undefined; | ||
| /** @type {boolean=} */ | ||
| this.hideStack = undefined; | ||
| /** @type {Chunk=} */ | ||
| this.chunk = undefined; | ||
| /** @type {string=} */ | ||
| this.file = undefined; | ||
| } | ||
| /** | ||
| * Returns inspect message. | ||
| * @returns {string} inspect message | ||
| */ | ||
| [inspect]() { | ||
| return ( | ||
| this.stack + | ||
| (this.details ? `\n${this.details}` : "") + | ||
| (this.cause ? `\n${this.cause}` : "") | ||
| ); | ||
| } | ||
| /** | ||
| * Serializes this instance into the provided serializer context. | ||
| * @param {ObjectSerializerContext} context context | ||
| */ | ||
| serialize({ write }) { | ||
| write(this.name); | ||
| write(this.message); | ||
| write(this.stack); | ||
| write(this.cause); | ||
| write(this.details); | ||
| write(this.loc); | ||
| write(this.hideStack); | ||
| } | ||
| /** | ||
| * Restores this instance from the provided deserializer context. | ||
| * @param {ObjectDeserializerContext} context context | ||
| */ | ||
| deserialize({ read }) { | ||
| this.name = read(); | ||
| this.message = read(); | ||
| this.stack = read(); | ||
| this.cause = read(); | ||
| this.details = read(); | ||
| this.loc = read(); | ||
| this.hideStack = read(); | ||
| } | ||
| } | ||
| makeSerializable(WebpackError, "webpack/lib/errors/WebpackError"); | ||
| /** @type {typeof WebpackError} */ | ||
| module.exports = WebpackError; |
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| */ | ||
| "use strict"; | ||
| const { RawSource, ReplaceSource } = require("webpack-sources"); | ||
| const ConcatenationScope = require("../ConcatenationScope"); | ||
| const Generator = require("../Generator"); | ||
| const { | ||
| HTML_TYPE, | ||
| JAVASCRIPT_TYPE, | ||
| JAVASCRIPT_TYPES | ||
| } = require("../ModuleSourceTypeConstants"); | ||
| const RuntimeGlobals = require("../RuntimeGlobals"); | ||
| const CssUrlDependency = require("../dependencies/CssUrlDependency"); | ||
| /** @typedef {import("webpack-sources").Source} Source */ | ||
| /** @typedef {import("../../declarations/WebpackOptions").HtmlGeneratorOptions} HtmlGeneratorOptions */ | ||
| /** @typedef {import("../Compilation").DependencyConstructor} DependencyConstructor */ | ||
| /** @typedef {import("../CodeGenerationResults")} CodeGenerationResults */ | ||
| /** @typedef {import("../Dependency")} Dependency */ | ||
| /** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ | ||
| /** @typedef {import("../Generator").GenerateContext} GenerateContext */ | ||
| /** @typedef {import("../Generator").UpdateHashContext} UpdateHashContext */ | ||
| /** @typedef {import("../Module").SourceType} SourceType */ | ||
| /** @typedef {import("../Module").SourceTypes} SourceTypes */ | ||
| /** @typedef {import("../Module").ConcatenationBailoutReasonContext} ConcatenationBailoutReasonContext */ | ||
| /** @typedef {import("../ModuleGraph")} ModuleGraph */ | ||
| /** @typedef {import("../NormalModule")} NormalModule */ | ||
| /** @typedef {import("../util/Hash")} Hash */ | ||
| /** | ||
| * @template T | ||
| * @typedef {import("../InitFragment")<T>} InitFragment | ||
| */ | ||
| /** | ||
| * @type {ReadonlySet<"javascript" | "html">} | ||
| */ | ||
| const JAVASCRIPT_AND_HTML_TYPES = new Set([JAVASCRIPT_TYPE, HTML_TYPE]); | ||
| class HtmlGenerator extends Generator { | ||
| /** | ||
| * Creates an instance of HtmlGenerator. | ||
| * @param {HtmlGeneratorOptions=} options generator options | ||
| * @param {ModuleGraph=} moduleGraph the module graph; used to detect when an HTML module is reached as a compilation entry so `extract` can default to `true` for it | ||
| */ | ||
| constructor(options, moduleGraph) { | ||
| super(); | ||
| this.options = options || {}; | ||
| /** @type {ModuleGraph | undefined} */ | ||
| this._moduleGraph = moduleGraph; | ||
| } | ||
| /** | ||
| * Returns the reason this module cannot be concatenated, when one exists. | ||
| * @param {NormalModule} module module for which the bailout reason should be determined | ||
| * @param {ConcatenationBailoutReasonContext} context context | ||
| * @returns {string | undefined} reason why this module can't be concatenated, undefined when it can be concatenated | ||
| */ | ||
| getConcatenationBailoutReason(module, context) { | ||
| return undefined; | ||
| } | ||
| /** | ||
| * Whether this HTML module is reached as a compilation entry. Entry | ||
| * modules have at least one incoming connection without an | ||
| * `originModule` (the EntryDependency added by `compilation.addEntry`). | ||
| * @param {NormalModule} module module | ||
| * @returns {boolean} true when the module is an entry | ||
| */ | ||
| _isEntryModule(module) { | ||
| if (!this._moduleGraph) return false; | ||
| for (const connection of this._moduleGraph.getIncomingConnections(module)) { | ||
| if (!connection.originModule) return true; | ||
| } | ||
| return false; | ||
| } | ||
| /** | ||
| * Whether to emit the extracted `.html` file for this module. | ||
| * `options.extract === true` always extracts; `false` never; when the | ||
| * option is left unspecified, extraction defaults to on for HTML modules | ||
| * used as compilation entries — that's the HTML-as-entry-point use case. | ||
| * @param {NormalModule} module module | ||
| * @returns {boolean} true when the `.html` file should be emitted | ||
| */ | ||
| _shouldExtract(module) { | ||
| const { extract } = this.options; | ||
| if (extract === true) return true; | ||
| if (extract === false) return false; | ||
| return this._isEntryModule(module); | ||
| } | ||
| /** | ||
| * Returns the source types available for this module. | ||
| * @param {NormalModule} module fresh module | ||
| * @returns {SourceTypes} available types (do not mutate) | ||
| */ | ||
| getTypes(module) { | ||
| if (this._shouldExtract(module)) { | ||
| return JAVASCRIPT_AND_HTML_TYPES; | ||
| } | ||
| return JAVASCRIPT_TYPES; | ||
| } | ||
| /** | ||
| * Returns the estimated size for the requested source type. | ||
| * @param {NormalModule} module the module | ||
| * @param {SourceType=} type source type | ||
| * @returns {number} estimate size of the module | ||
| */ | ||
| getSize(module, type) { | ||
| const originalSource = module.originalSource(); | ||
| if (!originalSource) return 0; | ||
| if (type === HTML_TYPE) return originalSource.size(); | ||
| return originalSource.size() + 10; | ||
| } | ||
| /** | ||
| * Processes the provided module. | ||
| * @param {NormalModule} module the current module | ||
| * @param {Dependency} dependency the dependency to generate | ||
| * @param {InitFragment<GenerateContext>[]} initFragments mutable list of init fragments | ||
| * @param {ReplaceSource} source the current replace source which can be modified | ||
| * @param {GenerateContext} generateContext the render context | ||
| * @returns {void} | ||
| */ | ||
| sourceDependency(module, dependency, initFragments, source, generateContext) { | ||
| const constructor = | ||
| /** @type {DependencyConstructor} */ | ||
| (dependency.constructor); | ||
| const template = generateContext.dependencyTemplates.get(constructor); | ||
| if (!template) { | ||
| throw new Error( | ||
| `No template for dependency: ${dependency.constructor.name}` | ||
| ); | ||
| } | ||
| /** @type {DependencyTemplateContext} */ | ||
| /** @type {InitFragment<GenerateContext>[] | undefined} */ | ||
| let chunkInitFragments; | ||
| /** @type {DependencyTemplateContext} */ | ||
| const templateContext = { | ||
| runtimeTemplate: generateContext.runtimeTemplate, | ||
| dependencyTemplates: generateContext.dependencyTemplates, | ||
| moduleGraph: generateContext.moduleGraph, | ||
| chunkGraph: generateContext.chunkGraph, | ||
| module, | ||
| runtime: generateContext.runtime, | ||
| runtimeRequirements: generateContext.runtimeRequirements, | ||
| concatenationScope: generateContext.concatenationScope, | ||
| codeGenerationResults: | ||
| /** @type {CodeGenerationResults} */ | ||
| (generateContext.codeGenerationResults), | ||
| initFragments, | ||
| get chunkInitFragments() { | ||
| if (!chunkInitFragments) { | ||
| const data = | ||
| /** @type {NonNullable<GenerateContext["getData"]>} */ | ||
| (generateContext.getData)(); | ||
| chunkInitFragments = data.get("chunkInitFragments"); | ||
| if (!chunkInitFragments) { | ||
| chunkInitFragments = []; | ||
| data.set("chunkInitFragments", chunkInitFragments); | ||
| } | ||
| } | ||
| return chunkInitFragments; | ||
| } | ||
| }; | ||
| template.apply(dependency, source, templateContext); | ||
| } | ||
| /** | ||
| * Processes the provided dependencies block. | ||
| * @param {NormalModule} module the module to generate | ||
| * @param {import("../DependenciesBlock")} block the dependencies block which will be processed | ||
| * @param {InitFragment<GenerateContext>[]} initFragments mutable list of init fragments | ||
| * @param {ReplaceSource} source the current replace source which can be modified | ||
| * @param {GenerateContext} generateContext the generateContext | ||
| * @returns {void} | ||
| */ | ||
| sourceBlock(module, block, initFragments, source, generateContext) { | ||
| for (const dependency of block.dependencies) { | ||
| this.sourceDependency( | ||
| module, | ||
| dependency, | ||
| initFragments, | ||
| source, | ||
| generateContext | ||
| ); | ||
| } | ||
| for (const childBlock of block.blocks) { | ||
| this.sourceBlock( | ||
| module, | ||
| childBlock, | ||
| initFragments, | ||
| source, | ||
| generateContext | ||
| ); | ||
| } | ||
| } | ||
| /** | ||
| * Processes the provided module. | ||
| * @param {NormalModule} module the module to generate | ||
| * @param {InitFragment<GenerateContext>[]} initFragments mutable list of init fragments | ||
| * @param {ReplaceSource} source the current replace source which can be modified | ||
| * @param {GenerateContext} generateContext the generateContext | ||
| * @returns {void} | ||
| */ | ||
| sourceModule(module, initFragments, source, generateContext) { | ||
| for (const dependency of module.dependencies) { | ||
| this.sourceDependency( | ||
| module, | ||
| dependency, | ||
| initFragments, | ||
| source, | ||
| generateContext | ||
| ); | ||
| } | ||
| if (module.presentationalDependencies !== undefined) { | ||
| for (const dependency of module.presentationalDependencies) { | ||
| this.sourceDependency( | ||
| module, | ||
| dependency, | ||
| initFragments, | ||
| source, | ||
| generateContext | ||
| ); | ||
| } | ||
| } | ||
| for (const childBlock of module.blocks) { | ||
| this.sourceBlock( | ||
| module, | ||
| childBlock, | ||
| initFragments, | ||
| source, | ||
| generateContext | ||
| ); | ||
| } | ||
| } | ||
| /** | ||
| * Run all HTML dependency templates against the original module source and | ||
| * return the rewritten HTML. When `undoPath` is a string, `[webpack/auto]` | ||
| * placeholders left in by asset/url dependencies are resolved to that | ||
| * undo path (use `""` to make URLs root-relative). When `undoPath` is | ||
| * `undefined`, the placeholders are preserved so the caller (typically | ||
| * `HtmlModulesPlugin#renderManifest`, which only knows the final | ||
| * `.html` filename after code generation) can resolve them itself. | ||
| * @param {NormalModule} module the module to render | ||
| * @param {GenerateContext} generateContext the generate context | ||
| * @param {string=} undoPath value to substitute for `[webpack/auto]` placeholders | ||
| * @returns {string} the rewritten HTML | ||
| */ | ||
| _renderHtml(module, generateContext, undoPath) { | ||
| const originalSource = /** @type {Source} */ (module.originalSource()); | ||
| const source = new ReplaceSource(originalSource); | ||
| /** @type {InitFragment<GenerateContext>[]} */ | ||
| const initFragments = []; | ||
| this.sourceModule(module, initFragments, source, generateContext); | ||
| if (undoPath === undefined) { | ||
| return /** @type {string} */ (source.source()); | ||
| } | ||
| const moduleSourceContent = source.source(); | ||
| const generatedSource = new ReplaceSource(source); | ||
| const autoPlaceholder = CssUrlDependency.PUBLIC_PATH_AUTO; | ||
| const autoPlaceholderLen = autoPlaceholder.length; | ||
| for ( | ||
| let idx = moduleSourceContent.indexOf(autoPlaceholder); | ||
| idx !== -1; | ||
| idx = moduleSourceContent.indexOf( | ||
| autoPlaceholder, | ||
| idx + autoPlaceholderLen | ||
| ) | ||
| ) { | ||
| generatedSource.replace(idx, idx + autoPlaceholderLen - 1, undoPath); | ||
| } | ||
| // TODO handle `[fullhash]` | ||
| return /** @type {string} */ (generatedSource.source()); | ||
| } | ||
| /** | ||
| * Generates generated code for this runtime module. | ||
| * @param {NormalModule} module module for which the code should be generated | ||
| * @param {GenerateContext} generateContext context for generate | ||
| * @returns {Source | null} generated code | ||
| */ | ||
| generate(module, generateContext) { | ||
| const originalSource = module.originalSource(); | ||
| if (!originalSource) { | ||
| return new RawSource(""); | ||
| } | ||
| if (generateContext.type === HTML_TYPE) { | ||
| // Preserve `[webpack/auto]` placeholders here — the plugin's | ||
| // `renderManifest` hook knows the final `.html` filename and | ||
| // resolves them to an undo path relative to that location. | ||
| return new RawSource( | ||
| this._renderHtml(module, generateContext, undefined) | ||
| ); | ||
| } | ||
| // JS export: the rewritten HTML is a string the consumer reads at | ||
| // runtime, so resolve placeholders to root-relative URLs. | ||
| const generated = this._renderHtml(module, generateContext, ""); | ||
| /** @type {string} */ | ||
| let sourceContent; | ||
| if (generateContext.concatenationScope) { | ||
| generateContext.concatenationScope.registerNamespaceExport( | ||
| ConcatenationScope.NAMESPACE_OBJECT_EXPORT | ||
| ); | ||
| sourceContent = `${generateContext.runtimeTemplate.renderConst()} ${ | ||
| ConcatenationScope.NAMESPACE_OBJECT_EXPORT | ||
| } = ${JSON.stringify(generated)};`; | ||
| } else { | ||
| generateContext.runtimeRequirements.add(RuntimeGlobals.module); | ||
| sourceContent = `${module.moduleArgument}.exports = ${JSON.stringify( | ||
| generated | ||
| )};`; | ||
| } | ||
| return new RawSource(sourceContent); | ||
| } | ||
| /** | ||
| * Generates fallback output for the provided error condition. | ||
| * @param {Error} error the error | ||
| * @param {NormalModule} module module for which the code should be generated | ||
| * @param {GenerateContext} generateContext context for generate | ||
| * @returns {Source | null} generated code | ||
| */ | ||
| generateError(error, module, generateContext) { | ||
| if (generateContext.type === HTML_TYPE) { | ||
| // The error message can contain arbitrary text (file paths, user | ||
| // input, dep request strings). Strip `<`, `>`, and `--` runs so a | ||
| // crafted message can't close the comment with `-->` (or open a | ||
| // fake nested comment) and inject HTML into the extracted page. | ||
| const safe = String(error.message) | ||
| .replace(/[<>]/g, "") | ||
| .replace(/-{2,}/g, (m) => `${"-".repeat(m.length - 1)} `); | ||
| return new RawSource(`<!-- webpack error: ${safe} -->`); | ||
| } | ||
| return new RawSource(`throw new Error(${JSON.stringify(error.message)});`); | ||
| } | ||
| /** | ||
| * Updates the hash with the data contributed by this instance. | ||
| * @param {Hash} hash hash that will be modified | ||
| * @param {UpdateHashContext} updateHashContext context for updating hash | ||
| */ | ||
| updateHash(hash, updateHashContext) { | ||
| hash.update("html"); | ||
| // Hash the *effective* extraction state, not just the raw option, | ||
| // so the module hash flips when a module becomes (or stops being) | ||
| // a compilation entry under the `extract: undefined` default — the | ||
| // generator's source-type set changes with it, so any cached | ||
| // HTML-type codegen result must be invalidated. | ||
| if (this._shouldExtract(updateHashContext.module)) { | ||
| hash.update("extract"); | ||
| } | ||
| } | ||
| } | ||
| module.exports = HtmlGenerator; |
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| */ | ||
| "use strict"; | ||
| const { RawSource } = require("webpack-sources"); | ||
| const EntryPlugin = require("../EntryPlugin"); | ||
| const HotUpdateChunk = require("../HotUpdateChunk"); | ||
| const { HTML_TYPE } = require("../ModuleSourceTypeConstants"); | ||
| const { HTML_MODULE_TYPE } = require("../ModuleTypeConstants"); | ||
| const NormalModule = require("../NormalModule"); | ||
| const ConstDependency = require("../dependencies/ConstDependency"); | ||
| const HtmlInlineScriptDependency = require("../dependencies/HtmlInlineScriptDependency"); | ||
| const HtmlInlineStyleDependency = require("../dependencies/HtmlInlineStyleDependency"); | ||
| const HtmlScriptSrcDependency = require("../dependencies/HtmlScriptSrcDependency"); | ||
| const HtmlSourceDependency = require("../dependencies/HtmlSourceDependency"); | ||
| const StaticExportsDependency = require("../dependencies/StaticExportsDependency"); | ||
| const { compareModulesByFullName } = require("../util/comparators"); | ||
| const removeBOM = require("../util/removeBOM"); | ||
| const HtmlGenerator = require("./HtmlGenerator"); | ||
| const HtmlParser = require("./HtmlParser"); | ||
| /** @typedef {import("../Compiler")} Compiler */ | ||
| /** @typedef {{ request: string, entryName: string, kind: "classic" | "esm-script" | "modulepreload" | "stylesheet" }} EntryScriptInfo */ | ||
| const PLUGIN_NAME = "HtmlModulesPlugin"; | ||
| /** | ||
| * @param {string} name definition name in `schemas/WebpackOptions.json` | ||
| * @returns {EXPECTED_OBJECT} a schema referencing `#/definitions/<name>` | ||
| */ | ||
| const getSchema = (name) => { | ||
| const { definitions } = require("../../schemas/WebpackOptions.json"); | ||
| return { | ||
| definitions, | ||
| oneOf: [{ $ref: `#/definitions/${name}` }] | ||
| }; | ||
| }; | ||
| const generatorValidationOptions = { | ||
| name: "Html Modules Plugin", | ||
| baseDataPath: "generator" | ||
| }; | ||
| class HtmlModulesPlugin { | ||
| /** | ||
| * Applies the plugin by registering its hooks on the compiler. | ||
| * @param {Compiler} compiler the compiler instance | ||
| * @returns {void} | ||
| */ | ||
| apply(compiler) { | ||
| // `<script src>` and `<link rel="modulepreload">` references collected | ||
| // by HtmlParser become real compilation entries here. The classic | ||
| // and esm-script groups are chained via a leader-only dependOn so | ||
| // they share a runtime — the first entry of the group owns it and | ||
| // every subsequent entry sets `dependOn: [leader]`. Modulepreload | ||
| // entries are emitted as independent entries (no dependOn) so they | ||
| // can never be imported as a runtime leader by a later script — | ||
| // that's what keeps the "preload but don't execute" contract of | ||
| // `<link rel="modulepreload">` intact. | ||
| /** @type {WeakMap<import("../Compilation"), Set<string>>} */ | ||
| const stylesheetEntriesPerCompilation = new WeakMap(); | ||
| compiler.hooks.finishMake.tapAsync(PLUGIN_NAME, (compilation, callback) => { | ||
| /** @type {Promise<void>[]} */ | ||
| const promises = []; | ||
| /** @type {Set<string>} */ | ||
| const stylesheetEntries = new Set(); | ||
| stylesheetEntriesPerCompilation.set(compilation, stylesheetEntries); | ||
| for (const module of compilation.modules) { | ||
| if (module.type !== HTML_MODULE_TYPE) continue; | ||
| const buildInfo = module.buildInfo; | ||
| const htmlEntryScripts = | ||
| buildInfo && | ||
| /** @type {Record<string, EntryScriptInfo[]> | undefined} */ | ||
| (buildInfo.htmlEntryScripts); | ||
| if (!htmlEntryScripts) continue; | ||
| const context = /** @type {string} */ (module.context); | ||
| for (const [groupKind, group] of Object.entries(htmlEntryScripts)) { | ||
| // Only the script chains (`classic`, `esm-script`) need a | ||
| // shared runtime via leader-only `dependOn` — the others | ||
| // either preload without executing (`modulepreload`) or | ||
| // produce CSS chunks (`stylesheet`) which have no runtime | ||
| // to share. CSS entries must NOT chain into a JS leader | ||
| // either, because the resulting chunk would mix a CSS | ||
| // stylesheet with a JS runtime. | ||
| const isChainGroup = | ||
| groupKind !== "modulepreload" && groupKind !== "stylesheet"; | ||
| /** @type {string | undefined} */ | ||
| let leaderName; | ||
| for (const entry of group) { | ||
| const dependOn = | ||
| isChainGroup && leaderName !== undefined | ||
| ? [leaderName] | ||
| : undefined; | ||
| if (isChainGroup && leaderName === undefined) { | ||
| leaderName = entry.entryName; | ||
| } | ||
| if (groupKind === "stylesheet") { | ||
| stylesheetEntries.add(entry.entryName); | ||
| } | ||
| promises.push( | ||
| new Promise((resolve, reject) => { | ||
| compilation.addEntry( | ||
| context, | ||
| EntryPlugin.createDependency(entry.request, { | ||
| name: entry.entryName | ||
| }), | ||
| { | ||
| name: entry.entryName, | ||
| // Each script src / modulepreload entry gets its own | ||
| // filename derived from the synthetic entry name so it | ||
| // doesn't collide with the user's `output.filename`. | ||
| // For CSS entries the JS `filename` is irrelevant (no | ||
| // `.js` is emitted) — the CSS file's name is set on the | ||
| // chunk via `cssFilenameTemplate` in `afterChunks` below. | ||
| filename: | ||
| compilation.outputOptions.chunkFilename || "[name].js", | ||
| dependOn | ||
| }, | ||
| (err) => { | ||
| if (err) reject(err); | ||
| else resolve(); | ||
| } | ||
| ); | ||
| }) | ||
| ); | ||
| } | ||
| } | ||
| } | ||
| Promise.all(promises).then( | ||
| () => callback(), | ||
| (err) => callback(err) | ||
| ); | ||
| }); | ||
| compiler.hooks.compilation.tap( | ||
| PLUGIN_NAME, | ||
| (compilation, { normalModuleFactory }) => { | ||
| // CSS entries created by `<link rel="stylesheet">` in HTML need | ||
| // their `.css` filename set via `chunk.cssFilenameTemplate` | ||
| // (the field `CssModulesPlugin.getChunkFilenameTemplate` reads). | ||
| // Compilation only flows `options.filename` to `chunk.filenameTemplate`, | ||
| // which controls JS emit — there's no entry-level `cssFilename`. | ||
| // Set it ourselves after chunks are created so each stylesheet | ||
| // entry emits to a distinct file derived from `output.cssFilename` | ||
| // (or `output.cssChunkFilename` for non-initial CSS chunks). | ||
| compilation.hooks.afterChunks.tap(PLUGIN_NAME, () => { | ||
| const stylesheetEntries = | ||
| stylesheetEntriesPerCompilation.get(compilation); | ||
| if (!stylesheetEntries || stylesheetEntries.size === 0) return; | ||
| for (const entryName of stylesheetEntries) { | ||
| const entrypoint = compilation.entrypoints.get(entryName); | ||
| if (!entrypoint) continue; | ||
| const chunk = entrypoint.getEntrypointChunk(); | ||
| if (!chunk) continue; | ||
| // Each html-derived stylesheet entry uses the | ||
| // `cssChunkFilename` template — even though the entry | ||
| // chunk technically `canBeInitial()`, we deliberately | ||
| // avoid `cssFilename` here because that template often | ||
| // has no per-entry placeholder (it's derived from | ||
| // `output.filename`, which can be a literal like | ||
| // `bundle0.js`), and multiple `<link rel="stylesheet">` | ||
| // tags would then collide on the same emitted `.css` | ||
| // file. `cssChunkFilename` is derived from | ||
| // `output.chunkFilename` which webpack auto-extends | ||
| // with `[id].` when needed, guaranteeing uniqueness. | ||
| chunk.cssFilenameTemplate = | ||
| compilation.outputOptions.cssChunkFilename; | ||
| } | ||
| }); | ||
| compilation.dependencyFactories.set( | ||
| HtmlSourceDependency, | ||
| normalModuleFactory | ||
| ); | ||
| compilation.dependencyTemplates.set( | ||
| HtmlSourceDependency, | ||
| new HtmlSourceDependency.Template() | ||
| ); | ||
| compilation.dependencyFactories.set( | ||
| HtmlScriptSrcDependency, | ||
| normalModuleFactory | ||
| ); | ||
| compilation.dependencyTemplates.set( | ||
| HtmlScriptSrcDependency, | ||
| new HtmlScriptSrcDependency.Template() | ||
| ); | ||
| // Inline `<script>` content is bundled as its own entry — the | ||
| // same pipeline that handles `<script src>` — via a | ||
| // `data:text/javascript,...` request. The dependency | ||
| // template rewrites the original tag to `<script src=…>`. | ||
| compilation.dependencyFactories.set( | ||
| HtmlInlineScriptDependency, | ||
| normalModuleFactory | ||
| ); | ||
| compilation.dependencyTemplates.set( | ||
| HtmlInlineScriptDependency, | ||
| new HtmlInlineScriptDependency.Template() | ||
| ); | ||
| // Inline `<style>` content is routed through the CSS pipeline | ||
| // as a `data:text/css` module. The dependency template reads | ||
| // the processed CSS text from the CSS module's code | ||
| // generation data (`css-text` channel set by CssGenerator | ||
| // when `exportType` is `"text"`). | ||
| compilation.dependencyFactories.set( | ||
| HtmlInlineStyleDependency, | ||
| normalModuleFactory | ||
| ); | ||
| compilation.dependencyTemplates.set( | ||
| HtmlInlineStyleDependency, | ||
| new HtmlInlineStyleDependency.Template() | ||
| ); | ||
| compilation.dependencyTemplates.set( | ||
| StaticExportsDependency, | ||
| new StaticExportsDependency.Template() | ||
| ); | ||
| // `ConstDependency` is used by HtmlParser to insert | ||
| // ` type="module"` into the rewritten <script> tag when | ||
| // `output.module` is on. Register its template so the HTML | ||
| // generator runs the insertion. | ||
| compilation.dependencyTemplates.set( | ||
| ConstDependency, | ||
| new ConstDependency.Template() | ||
| ); | ||
| const cssEnabled = Boolean( | ||
| compiler.options.experiments && compiler.options.experiments.css | ||
| ); | ||
| normalModuleFactory.hooks.createParser | ||
| .for(HTML_MODULE_TYPE) | ||
| .tap( | ||
| PLUGIN_NAME, | ||
| () => | ||
| new HtmlParser( | ||
| compilation.outputOptions.hashFunction, | ||
| compiler.context, | ||
| compilation.outputOptions.module, | ||
| cssEnabled | ||
| ) | ||
| ); | ||
| normalModuleFactory.hooks.createGenerator | ||
| .for(HTML_MODULE_TYPE) | ||
| .tap(PLUGIN_NAME, (generatorOptions) => { | ||
| compiler.validate( | ||
| () => getSchema("HtmlGeneratorOptions"), | ||
| generatorOptions, | ||
| generatorValidationOptions, | ||
| (options) => | ||
| require("../../schemas/plugins/HtmlGeneratorOptions.check")( | ||
| options | ||
| ) | ||
| ); | ||
| return new HtmlGenerator( | ||
| /** @type {import("../../declarations/WebpackOptions").HtmlGeneratorOptions} */ | ||
| (generatorOptions), | ||
| compilation.moduleGraph | ||
| ); | ||
| }); | ||
| NormalModule.getCompilationHooks(compilation).processResult.tap( | ||
| PLUGIN_NAME, | ||
| (result, module) => { | ||
| if (module.type === HTML_MODULE_TYPE) { | ||
| const [source, ...rest] = result; | ||
| return [removeBOM(source), ...rest]; | ||
| } | ||
| return result; | ||
| } | ||
| ); | ||
| // Emit extracted `.html` files for any HTML module that opted | ||
| // into extraction. The opt-in is computed by | ||
| // `HtmlGenerator#_shouldExtract`: `module.generator.html.extract: | ||
| // true` always extracts, `false` never extracts, and when | ||
| // `extract` is unset the generator extracts iff the HTML module | ||
| // is a compilation entry — the iteration below picks up only | ||
| // modules whose generator reported the `html` source type, so | ||
| // that decision is honored implicitly. The HTML content is read | ||
| // from the generator's secondary `"html"` source type (see | ||
| // HtmlGenerator#generate). The filename template comes from | ||
| // `output.htmlFilename` (initial chunks) or | ||
| // `output.htmlChunkFilename` (non-initial chunks), mirroring | ||
| // the CSS pipeline. Path data follows the asset-module pattern — | ||
| // `module` + a relative source `filename`, with `chunk` | ||
| // intentionally omitted so `[name]` resolves to the HTML | ||
| // source's basename (e.g. `page` for `./page.html`) rather | ||
| // than the importing chunk's name (e.g. `main`). A per-module | ||
| // content hash is computed from the rewritten HTML so the | ||
| // template's `[contenthash]` placeholder works; the | ||
| // compilation hash is also forwarded so `[fullhash]` / | ||
| // `[hash]` work in user-supplied templates. | ||
| const { | ||
| getUndoPath, | ||
| makePathsRelative | ||
| } = require("../util/identifier"); | ||
| const createHash = require("../util/createHash"); | ||
| const nonNumericOnlyHash = require("../util/nonNumericOnlyHash"); | ||
| const CssUrlDependency = require("../dependencies/CssUrlDependency"); | ||
| const autoPlaceholder = CssUrlDependency.PUBLIC_PATH_AUTO; | ||
| compilation.hooks.renderManifest.tap( | ||
| PLUGIN_NAME, | ||
| (result, { chunk, codeGenerationResults, hash: compilationHash }) => { | ||
| // HMR's `HotUpdateChunk`s flow through the same hook | ||
| // but aren't real output chunks — extracting `.html` | ||
| // for them would create stray hot-update HTML files. | ||
| // `CssModulesPlugin` early-returns for the same reason. | ||
| if (chunk instanceof HotUpdateChunk) return result; | ||
| const { chunkGraph } = compilation; | ||
| const modules = | ||
| chunkGraph.getOrderedChunkModulesIterableBySourceType( | ||
| chunk, | ||
| HTML_TYPE, | ||
| compareModulesByFullName(compilation.compiler) | ||
| ); | ||
| if (!modules) return result; | ||
| const outputOptions = compilation.outputOptions; | ||
| for (const module of modules) { | ||
| const normalModule = /** @type {NormalModule} */ (module); | ||
| const codeGenResult = codeGenerationResults.get( | ||
| module, | ||
| chunk.runtime | ||
| ); | ||
| const placeholderSource = codeGenResult.sources.get(HTML_TYPE); | ||
| if (!placeholderSource) continue; | ||
| const filenameTemplate = chunk.canBeInitial() | ||
| ? outputOptions.htmlFilename | ||
| : outputOptions.htmlChunkFilename; | ||
| const sourceFilename = makePathsRelative( | ||
| compiler.context, | ||
| /** @type {string} */ | ||
| (normalModule.getResource() || normalModule.resource), | ||
| compiler.root | ||
| ).replace(/^\.\//, ""); | ||
| const placeholderContent = /** @type {string} */ ( | ||
| placeholderSource.source() | ||
| ); | ||
| const hashInput = createHash(outputOptions.hashFunction); | ||
| if (outputOptions.hashSalt) { | ||
| hashInput.update(outputOptions.hashSalt); | ||
| } | ||
| hashInput.update(placeholderContent); | ||
| const fullContentHash = /** @type {string} */ ( | ||
| hashInput.digest(outputOptions.hashDigest) | ||
| ); | ||
| const contentHash = nonNumericOnlyHash( | ||
| fullContentHash, | ||
| outputOptions.hashDigestLength | ||
| ); | ||
| const { path: filename, info } = compilation.getPathWithInfo( | ||
| /** @type {import("../TemplatedPathPlugin").TemplatePath} */ | ||
| (filenameTemplate), | ||
| { | ||
| module, | ||
| runtime: chunk.runtime, | ||
| chunkGraph, | ||
| contentHash, | ||
| contentHashType: HTML_TYPE, | ||
| filename: sourceFilename, | ||
| hash: compilationHash | ||
| } | ||
| ); | ||
| // Resolve any remaining `[webpack/auto]` placeholders to | ||
| // an undo path computed from the emitted HTML's location. | ||
| // Without this, an `output.htmlFilename` that emits into | ||
| // a subdirectory (e.g. `pages/[name].html`) would leave | ||
| // asset URLs like `image.png` and chunk URLs like | ||
| // `main.js` root-relative, so the browser would resolve | ||
| // them under the HTML's directory instead of the | ||
| // `output.path` root. | ||
| const undoPath = getUndoPath( | ||
| filename, | ||
| /** @type {string} */ (outputOptions.path), | ||
| false | ||
| ); | ||
| const finalContent = placeholderContent | ||
| .split(autoPlaceholder) | ||
| .join(undoPath); | ||
| const finalSource = new RawSource(finalContent); | ||
| // The same HTML module can land in multiple chunks | ||
| // with different `output.htmlFilename` / | ||
| // `output.htmlChunkFilename` shapes, which means | ||
| // different `undoPath`s and therefore different | ||
| // final content for the same module id. Include | ||
| // the emitted filename in the asset cache key and | ||
| // the post-undo-path content in the hash, so the | ||
| // asset cache can't reuse one variant's bytes at | ||
| // another variant's URL. | ||
| const finalHash = createHash(outputOptions.hashFunction); | ||
| if (outputOptions.hashSalt) { | ||
| finalHash.update(outputOptions.hashSalt); | ||
| } | ||
| finalHash.update(finalContent); | ||
| const finalContentHash = nonNumericOnlyHash( | ||
| /** @type {string} */ ( | ||
| finalHash.digest(outputOptions.hashDigest) | ||
| ), | ||
| outputOptions.hashDigestLength | ||
| ); | ||
| result.push({ | ||
| render: () => finalSource, | ||
| filename, | ||
| info, | ||
| auxiliary: true, | ||
| identifier: `htmlModule${chunkGraph.getModuleId( | ||
| module | ||
| )}|${filename}`, | ||
| hash: finalContentHash | ||
| }); | ||
| } | ||
| return result; | ||
| } | ||
| ); | ||
| } | ||
| ); | ||
| } | ||
| } | ||
| module.exports = HtmlModulesPlugin; |
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| */ | ||
| "use strict"; | ||
| const vm = require("vm"); | ||
| const Parser = require("../Parser"); | ||
| const ConstDependency = require("../dependencies/ConstDependency"); | ||
| const HtmlInlineScriptDependency = require("../dependencies/HtmlInlineScriptDependency"); | ||
| const HtmlInlineStyleDependency = require("../dependencies/HtmlInlineStyleDependency"); | ||
| const HtmlScriptSrcDependency = require("../dependencies/HtmlScriptSrcDependency"); | ||
| const HtmlSourceDependency = require("../dependencies/HtmlSourceDependency"); | ||
| const StaticExportsDependency = require("../dependencies/StaticExportsDependency"); | ||
| const CommentCompilationWarning = require("../errors/CommentCompilationWarning"); | ||
| const ModuleDependencyError = require("../errors/ModuleDependencyError"); | ||
| const UnsupportedFeatureWarning = require("../errors/UnsupportedFeatureWarning"); | ||
| const WebpackError = require("../errors/WebpackError"); | ||
| const LocConverter = require("../util/LocConverter"); | ||
| const createHash = require("../util/createHash"); | ||
| const { contextify } = require("../util/identifier"); | ||
| const { | ||
| createMagicCommentContext, | ||
| webpackCommentRegExp | ||
| } = require("../util/magicComment"); | ||
| const walkHtmlTokens = require("./walkHtmlTokens"); | ||
| /** @typedef {import("../Module").BuildInfo} BuildInfo */ | ||
| /** @typedef {import("../Module").BuildMeta} BuildMeta */ | ||
| /** @typedef {import("../Parser").ParserState} ParserState */ | ||
| /** @typedef {import("../Parser").PreparsedAst} PreparsedAst */ | ||
| const HORIZONTAL_TAB = "\u0009".charCodeAt(0); | ||
| const NEWLINE = "\u000A".charCodeAt(0); | ||
| const FORM_FEED = "\u000C".charCodeAt(0); | ||
| const CARRIAGE_RETURN = "\u000D".charCodeAt(0); | ||
| const SPACE = "\u0020".charCodeAt(0); | ||
| const COMMA = ",".charCodeAt(0); | ||
| const LEFT_PARENTHESIS = "(".charCodeAt(0); | ||
| const RIGHT_PARENTHESIS = ")".charCodeAt(0); | ||
| const SMALL_LETTER_W = "w".charCodeAt(0); | ||
| const SMALL_LETTER_X = "x".charCodeAt(0); | ||
| const SMALL_LETTER_H = "h".charCodeAt(0); | ||
| /** | ||
| * @param {number} char char | ||
| * @returns {boolean} true when ASCII whitespace, otherwise false | ||
| */ | ||
| function isASCIIWhitespace(char) { | ||
| return ( | ||
| // Horizontal tab | ||
| char === HORIZONTAL_TAB || | ||
| // New line | ||
| char === NEWLINE || | ||
| // Form feed | ||
| char === FORM_FEED || | ||
| // Carriage return | ||
| char === CARRIAGE_RETURN || | ||
| // Space | ||
| char === SPACE | ||
| ); | ||
| } | ||
| /** @typedef {[string, number, number]} ParsedSource */ | ||
| // eslint-disable-next-line no-control-regex | ||
| const IGNORE_CHARS_REGEXP = /[\u0000-\u001F\u007F-\u009F\u00A0]/g; | ||
| /** | ||
| * @param {string} input input | ||
| * @returns {ParsedSource[]} parsed src | ||
| */ | ||
| const parseSrc = (input) => { | ||
| const len = input.length; | ||
| if (len === 0) throw new Error("Must be non-empty"); | ||
| let start = 0; | ||
| let end = len; | ||
| while (start < end) { | ||
| const code = input.charCodeAt(start); | ||
| if (code > 32 && code !== 160) break; | ||
| start++; | ||
| } | ||
| if (start === end) throw new Error("Must be non-empty"); | ||
| while (end > start) { | ||
| const code = input.charCodeAt(end - 1); | ||
| if (code > 32 && code !== 160) break; | ||
| end--; | ||
| } | ||
| let value = input.slice(start, end); | ||
| if (IGNORE_CHARS_REGEXP.test(value)) { | ||
| value = value.replace(IGNORE_CHARS_REGEXP, ""); | ||
| if (value.length === 0) throw new Error("Must be non-empty"); | ||
| } | ||
| return [[value, start, end]]; | ||
| }; | ||
| // HTML `<style>` content is rawtext: it ends at the first `</style>` | ||
| // where the tag name is followed by whitespace, `>` or `/`. The | ||
| // lookahead (rather than a consuming character class) keeps the match | ||
| // from running past the first `>` into a later tag — the | ||
| // `[^>]*` only consumes any (rarely-seen) end-tag attributes before the | ||
| // closing `>` of the end tag itself. | ||
| const STYLE_END_REGEXP = /<\/style(?=[\s/>])[^>]*>/gi; | ||
| // (Don't use \s, to avoid matching non-breaking space) | ||
| // eslint-disable-next-line no-control-regex | ||
| const LEADING_SPACES_REGEXP = /^[ \t\n\r\u000C]+/; | ||
| // eslint-disable-next-line no-control-regex | ||
| const LEADING_COMMAS_OR_SPACES_REGEXP = /^[, \t\n\r\u000C]+/; | ||
| // eslint-disable-next-line no-control-regex | ||
| const LEADING_NOT_SPACES = /^[^ \t\n\r\u000C]+/; | ||
| const TRAILING_COMMAS_REGEXP = /[,]+$/; | ||
| const NON_NEGATIVE_INTEGER_REGEXP = /^\d+$/; | ||
| // ( Positive or negative or unsigned integers or decimals, without or without exponents. | ||
| // Must include at least one digit. | ||
| // According to spec tests any decimal point must be followed by a digit. | ||
| // No leading plus sign is allowed.) | ||
| // https://html.spec.whatwg.org/multipage/infrastructure.html#valid-floating-point-number | ||
| const FLOATING_POINT_REGEXP = | ||
| /^-?(?:[0-9]+|[0-9]*\.[0-9]+)(?:[eE][+-]?[0-9]+)?$/; | ||
| /** | ||
| * @param {string} input input | ||
| * @returns {ParsedSource[]} parsed srcset | ||
| */ | ||
| const parseSrcset = (input) => { | ||
| // 1. Let input be the value passed to this algorithm. | ||
| const inputLength = input.length; | ||
| /** @type {string | undefined} */ | ||
| let url; | ||
| /** @type {string[]} */ | ||
| let descriptors; | ||
| /** @type {string} */ | ||
| let currentDescriptor; | ||
| /** @type {string} */ | ||
| let state; | ||
| /** @type {number} */ | ||
| let charCode; | ||
| /** @type {number} */ | ||
| let position = 0; | ||
| /** @type {number} */ | ||
| let start; | ||
| /** @type {[string, number, number][]} */ | ||
| const candidates = []; | ||
| /** | ||
| * @param {RegExp} regExp reg exp to collect characters | ||
| * @returns {string | undefined} characters | ||
| */ | ||
| function collectCharacters(regExp) { | ||
| /** @type {string} */ | ||
| let chars; | ||
| const match = regExp.exec(input.slice(Math.max(0, position))); | ||
| if (match) { | ||
| [chars] = match; | ||
| position += chars.length; | ||
| return chars; | ||
| } | ||
| } | ||
| /** | ||
| * @returns {void} | ||
| */ | ||
| function parseDescriptors() { | ||
| // 9. Descriptor parser: Let error be no. | ||
| let pError = false; | ||
| // 10. Let width be absent. | ||
| // 11. Let density be absent. | ||
| // 12. Let future-compat-h be absent. (We're implementing it now as h) | ||
| /** @type {number | undefined} */ | ||
| let width; | ||
| /** @type {number | undefined} */ | ||
| let density; | ||
| /** @type {number | undefined} */ | ||
| let height; | ||
| /** @type {string | undefined} */ | ||
| let desc; | ||
| // 13. For each descriptor in descriptors, run the appropriate set of steps | ||
| // from the following list: | ||
| for (let i = 0; i < descriptors.length; i++) { | ||
| desc = descriptors[i]; | ||
| const lastChar = desc[desc.length - 1].charCodeAt(0); | ||
| const value = desc.slice(0, Math.max(0, desc.length - 1)); | ||
| // If the descriptor consists of a valid non-negative integer followed by | ||
| // a U+0077 LATIN SMALL LETTER W character | ||
| if ( | ||
| NON_NEGATIVE_INTEGER_REGEXP.test(value) && | ||
| lastChar === SMALL_LETTER_W | ||
| ) { | ||
| // If width and density are not both absent, then let error be yes. | ||
| if (width || density) { | ||
| pError = true; | ||
| } | ||
| const intVal = Number.parseInt(value, 10); | ||
| // Apply the rules for parsing non-negative integers to the descriptor. | ||
| // If the result is zero, let error be yes. | ||
| // Otherwise, let width be the result. | ||
| if (intVal === 0) { | ||
| pError = true; | ||
| } else { | ||
| width = intVal; | ||
| } | ||
| } | ||
| // If the descriptor consists of a valid floating-point number followed by | ||
| // a U+0078 LATIN SMALL LETTER X character | ||
| else if ( | ||
| FLOATING_POINT_REGEXP.test(value) && | ||
| lastChar === SMALL_LETTER_X | ||
| ) { | ||
| // If width, density and future-compat-h are not all absent, then let error | ||
| // be yes. | ||
| if (width || density || height) { | ||
| pError = true; | ||
| } | ||
| const floatVal = Number.parseFloat(value); | ||
| // Apply the rules for parsing floating-point number values to the descriptor. | ||
| // If the result is less than zero, let error be yes. Otherwise, let density | ||
| // be the result. | ||
| if (floatVal < 0) { | ||
| pError = true; | ||
| } else { | ||
| density = floatVal; | ||
| } | ||
| } | ||
| // If the descriptor consists of a valid non-negative integer followed by | ||
| // a U+0068 LATIN SMALL LETTER H character | ||
| else if ( | ||
| NON_NEGATIVE_INTEGER_REGEXP.test(value) && | ||
| lastChar === SMALL_LETTER_H | ||
| ) { | ||
| // If height and density are not both absent, then let error be yes. | ||
| if (height || density) { | ||
| pError = true; | ||
| } | ||
| const intVal = Number.parseInt(value, 10); | ||
| // Apply the rules for parsing non-negative integers to the descriptor. | ||
| // If the result is zero, let error be yes. Otherwise, let future-compat-h | ||
| // be the result. | ||
| if (intVal === 0) { | ||
| pError = true; | ||
| } else { | ||
| height = intVal; | ||
| } | ||
| // Anything else, Let error be yes. | ||
| } else { | ||
| pError = true; | ||
| } | ||
| } | ||
| // 15. If error is still no, then append a new image source to candidates whose | ||
| // URL is url, associated with a width width if not absent and a pixel | ||
| // density density if not absent. Otherwise, there is a parse error. | ||
| if (!pError) { | ||
| candidates.push([ | ||
| /** @type {string} */ (url), | ||
| start, | ||
| start + /** @type {string} */ (url).length | ||
| ]); | ||
| } else { | ||
| throw new Error( | ||
| `Invalid srcset descriptor found in '${input}' at '${desc}'` | ||
| ); | ||
| } | ||
| } | ||
| /** | ||
| * @returns {void} | ||
| */ | ||
| function tokenize() { | ||
| // 8.1. Descriptor tokenizer: Skip whitespace | ||
| collectCharacters(LEADING_SPACES_REGEXP); | ||
| // 8.2. Let current descriptor be the empty string. | ||
| currentDescriptor = ""; | ||
| // 8.3. Let state be in descriptor. | ||
| state = "in descriptor"; | ||
| while (true) { | ||
| // 8.4. Let charCode be the character at position. | ||
| charCode = input.charCodeAt(position); | ||
| // Do the following depending on the value of state. | ||
| // For the purpose of this step, "EOF" is a special character representing | ||
| // that position is past the end of input. | ||
| // In descriptor | ||
| if (state === "in descriptor") { | ||
| // Do the following, depending on the value of charCode: | ||
| // Space character | ||
| // If current descriptor is not empty, append current descriptor to | ||
| // descriptors and let current descriptor be the empty string. | ||
| // Set state to after descriptor. | ||
| if (isASCIIWhitespace(charCode)) { | ||
| if (currentDescriptor) { | ||
| descriptors.push(currentDescriptor); | ||
| currentDescriptor = ""; | ||
| state = "after descriptor"; | ||
| } | ||
| } | ||
| // U+002C COMMA (,) | ||
| // Advance position to the next character in input. If current descriptor | ||
| // is not empty, append current descriptor to descriptors. Jump to the step | ||
| // labeled descriptor parser. | ||
| else if (charCode === COMMA) { | ||
| position += 1; | ||
| if (currentDescriptor) { | ||
| descriptors.push(currentDescriptor); | ||
| } | ||
| parseDescriptors(); | ||
| return; | ||
| } | ||
| // U+0028 LEFT PARENTHESIS (() | ||
| // Append charCode to current descriptor. Set state to in parens. | ||
| else if (charCode === LEFT_PARENTHESIS) { | ||
| currentDescriptor += input.charAt(position); | ||
| state = "in parens"; | ||
| } | ||
| // EOF | ||
| // If current descriptor is not empty, append current descriptor to | ||
| // descriptors. Jump to the step labeled descriptor parser. | ||
| else if (Number.isNaN(charCode)) { | ||
| if (currentDescriptor) { | ||
| descriptors.push(currentDescriptor); | ||
| } | ||
| parseDescriptors(); | ||
| return; | ||
| // Anything else | ||
| // Append charCode to current descriptor. | ||
| } else { | ||
| currentDescriptor += input.charAt(position); | ||
| } | ||
| } | ||
| // In parens | ||
| else if (state === "in parens") { | ||
| // U+0029 RIGHT PARENTHESIS ()) | ||
| // Append charCode to current descriptor. Set state to in descriptor. | ||
| if (charCode === RIGHT_PARENTHESIS) { | ||
| currentDescriptor += input.charAt(position); | ||
| state = "in descriptor"; | ||
| } | ||
| // EOF | ||
| // Append current descriptor to descriptors. Jump to the step labeled | ||
| // descriptor parser. | ||
| else if (Number.isNaN(charCode)) { | ||
| descriptors.push(currentDescriptor); | ||
| parseDescriptors(); | ||
| return; | ||
| } | ||
| // Anything else | ||
| // Append charCode to current descriptor. | ||
| else { | ||
| currentDescriptor += input.charAt(position); | ||
| } | ||
| } | ||
| // After descriptor | ||
| else if (state === "after descriptor") { | ||
| // Do the following, depending on the value of charCode: | ||
| if (isASCIIWhitespace(charCode)) { | ||
| // Space character: Stay in this state. | ||
| } | ||
| // EOF: Jump to the step labeled descriptor parser. | ||
| else if (Number.isNaN(charCode)) { | ||
| parseDescriptors(); | ||
| return; | ||
| } | ||
| // Anything else | ||
| // Set state to in descriptor. Set position to the previous character in input. | ||
| else { | ||
| state = "in descriptor"; | ||
| position -= 1; | ||
| } | ||
| } | ||
| // Advance position to the next character in input. | ||
| position += 1; | ||
| } | ||
| } | ||
| // 3. Let candidates be an initially empty source set. | ||
| // const candidates = []; // Moved to top | ||
| // 4. Splitting loop: Collect a sequence of characters that are space | ||
| // characters or U+002C COMMA characters. If any U+002C COMMA characters | ||
| // were collected, that is a parse error. | ||
| while (true) { | ||
| collectCharacters(LEADING_COMMAS_OR_SPACES_REGEXP); | ||
| // 5. If position is past the end of input, return candidates and abort these steps. | ||
| if (position >= inputLength) { | ||
| if (candidates.length === 0) { | ||
| throw new Error("Must contain one or more image candidate strings"); | ||
| } | ||
| // (we're done, this is the sole return path) | ||
| return candidates; | ||
| } | ||
| // 6. Collect a sequence of characters that are not space characters, | ||
| // and let that be url. | ||
| start = position; | ||
| url = collectCharacters(LEADING_NOT_SPACES); | ||
| // 7. Let descriptors be a new empty list. | ||
| descriptors = []; | ||
| // 8. If url ends with a U+002C COMMA character (,), follow these sub steps: | ||
| // (1). Remove all trailing U+002C COMMA characters from url. If this removed | ||
| // more than one character, that is a parse error. | ||
| if (url && url.charCodeAt(url.length - 1) === COMMA) { | ||
| url = url.replace(TRAILING_COMMAS_REGEXP, ""); | ||
| // (Jump ahead to step 9 to skip tokenization and just push the candidate). | ||
| parseDescriptors(); | ||
| } | ||
| // Otherwise, follow these sub steps: | ||
| else { | ||
| tokenize(); | ||
| } | ||
| // 16. Return to the step labeled splitting loop. | ||
| } | ||
| }; | ||
| /** | ||
| * @param {Map<string, string>} attributes attributes | ||
| * @param {string} name name | ||
| * @returns {string | undefined} attribute value | ||
| */ | ||
| const getAttributeValue = (attributes, name) => attributes.get(name); | ||
| /** @type {Map<string, Set<string>>} */ | ||
| const META = new Map([ | ||
| [ | ||
| "name", | ||
| new Set([ | ||
| // msapplication-TileImage | ||
| "msapplication-tileimage", | ||
| "msapplication-square70x70logo", | ||
| "msapplication-square150x150logo", | ||
| "msapplication-wide310x150logo", | ||
| "msapplication-square310x310logo", | ||
| "msapplication-config", | ||
| // TODO Do we need to parser it? | ||
| // "msapplication-task", | ||
| "twitter:image" | ||
| ]) | ||
| ], | ||
| [ | ||
| "property", | ||
| new Set([ | ||
| "og:image", | ||
| "og:image:url", | ||
| "og:image:secure_url", | ||
| "og:audio", | ||
| "og:audio:secure_url", | ||
| "og:video", | ||
| "og:video:secure_url", | ||
| "vk:image" | ||
| ]) | ||
| ], | ||
| [ | ||
| "itemprop", | ||
| new Set([ | ||
| "image", | ||
| "logo", | ||
| "screenshot", | ||
| "thumbnailurl", | ||
| "contenturl", | ||
| "downloadurl", | ||
| "duringmedia", | ||
| "embedurl", | ||
| "installurl", | ||
| "layoutimage" | ||
| ]) | ||
| ] | ||
| ]); | ||
| /** | ||
| * @param {Map<string, string>} attributes attributes | ||
| * @returns {boolean} true when need to parse, otherwise false | ||
| */ | ||
| const filterLinkItemprop = (attributes) => { | ||
| const value = getAttributeValue(attributes, "itemprop"); | ||
| if (!value) return false; | ||
| const allowedAttributes = META.get("itemprop"); | ||
| if (!allowedAttributes) return false; | ||
| return allowedAttributes.has(value.trim().toLowerCase()); | ||
| }; | ||
| /** | ||
| * @param {Map<string, string>} attributes attributes | ||
| * @returns {boolean} true when need to parse, otherwise false | ||
| */ | ||
| const filterLinkHref = (attributes) => { | ||
| const rel = getAttributeValue(attributes, "rel"); | ||
| if (!rel) return false; | ||
| const usedRels = rel.trim().toLowerCase().split(" ").filter(Boolean); | ||
| const allowedRels = [ | ||
| "stylesheet", | ||
| "icon", | ||
| "mask-icon", | ||
| "apple-touch-icon", | ||
| "apple-touch-icon-precomposed", | ||
| "apple-touch-startup-image", | ||
| "manifest", | ||
| "prefetch", | ||
| "preload", | ||
| "modulepreload" | ||
| ]; | ||
| return allowedRels.some((value) => usedRels.includes(value)); | ||
| }; | ||
| /** | ||
| * @param {Map<string, string>} attributes attributes | ||
| * @returns {boolean} true when need to parse, otherwise false | ||
| */ | ||
| const filterLinkUnion = (attributes) => | ||
| filterLinkHref(attributes) || filterLinkItemprop(attributes); | ||
| /** | ||
| * @param {Map<string, string>} attributes attributes | ||
| * @returns {boolean} true when need to parse, otherwise false | ||
| */ | ||
| const filterMetaContent = (attributes) => { | ||
| for (const item of META) { | ||
| const [key, allowedNames] = item; | ||
| const name = getAttributeValue(attributes, key); | ||
| if (!name) continue; | ||
| return allowedNames.has(name.trim().toLowerCase()); | ||
| } | ||
| return false; | ||
| }; | ||
| /** | ||
| * @param {Map<string, string>} attributes attributes | ||
| * @returns {boolean} true when the script element opts into ES module semantics | ||
| */ | ||
| const isModuleScript = (attributes) => { | ||
| const type = getAttributeValue(attributes, "type"); | ||
| if (!type) return false; | ||
| return type.trim().toLowerCase() === "module"; | ||
| }; | ||
| // HTML `<script>` `type` values that the browser treats as executable | ||
| // JavaScript. Anything outside this set (e.g. `application/ld+json`, | ||
| // `importmap`, `application/wasm`) is a data block — webpack must not | ||
| // try to bundle it as a JS entry; it should pass through as an asset URL. | ||
| const JS_SCRIPT_TYPES = new Set([ | ||
| "", | ||
| "module", | ||
| "text/javascript", | ||
| "application/javascript", | ||
| "text/ecmascript", | ||
| "application/ecmascript" | ||
| ]); | ||
| /** | ||
| * @param {Map<string, string>} attributes attributes | ||
| * @returns {boolean} true when the script element's `type` is executable JS | ||
| */ | ||
| const isExecutableJsScript = (attributes) => { | ||
| const type = getAttributeValue(attributes, "type"); | ||
| if (type === undefined) return true; | ||
| return JS_SCRIPT_TYPES.has(type.trim().toLowerCase()); | ||
| }; | ||
| /** | ||
| * @param {Map<string, string>} attributes attributes | ||
| * @returns {boolean} true when the link points at an ES module that should be bundled as an entry chunk | ||
| */ | ||
| const isLinkModulePreload = (attributes) => { | ||
| const rel = getAttributeValue(attributes, "rel"); | ||
| if (!rel) return false; | ||
| return rel.trim().toLowerCase().split(/\s+/).includes("modulepreload"); | ||
| }; | ||
| /** | ||
| * @param {Map<string, string>} attributes attributes | ||
| * @returns {boolean} true when the link is a `<link rel="stylesheet">` that should be bundled as a CSS entry chunk | ||
| */ | ||
| const isLinkStylesheet = (attributes) => { | ||
| const rel = getAttributeValue(attributes, "rel"); | ||
| if (!rel) return false; | ||
| return rel.trim().toLowerCase().split(/\s+/).includes("stylesheet"); | ||
| }; | ||
| /** @type {Map<string, Map<string, { parse: (input: string) => ParsedSource[] | undefined, filter?: (attributes: Map<string, string>) => boolean, entry?: boolean | ((attributes: Map<string, string>) => boolean), entryCategory?: string }>>} */ | ||
| const DEFAULT_SOURCES = new Map([ | ||
| [ | ||
| "audio", | ||
| new Map([ | ||
| [ | ||
| "src", | ||
| { | ||
| parse: parseSrc | ||
| } | ||
| ] | ||
| ]) | ||
| ], | ||
| [ | ||
| "embed", | ||
| new Map([ | ||
| [ | ||
| "src", | ||
| { | ||
| parse: parseSrc | ||
| } | ||
| ] | ||
| ]) | ||
| ], | ||
| [ | ||
| "img", | ||
| new Map([ | ||
| [ | ||
| "src", | ||
| { | ||
| parse: parseSrc | ||
| } | ||
| ], | ||
| [ | ||
| "srcset", | ||
| { | ||
| parse: parseSrcset | ||
| } | ||
| ] | ||
| ]) | ||
| ], | ||
| [ | ||
| "input", | ||
| new Map([ | ||
| [ | ||
| "src", | ||
| { | ||
| parse: parseSrc | ||
| } | ||
| ] | ||
| ]) | ||
| ], | ||
| [ | ||
| "link", | ||
| new Map([ | ||
| [ | ||
| "href", | ||
| { | ||
| parse: parseSrc, | ||
| filter: filterLinkUnion, | ||
| entry: isLinkModulePreload, | ||
| entryCategory: "esm" | ||
| } | ||
| ], | ||
| [ | ||
| "imagesrcset", | ||
| { | ||
| parse: parseSrcset, | ||
| filter: filterLinkHref | ||
| } | ||
| ] | ||
| ]) | ||
| ], | ||
| [ | ||
| "meta", | ||
| new Map([ | ||
| [ | ||
| "content", | ||
| { | ||
| parse: parseSrc, | ||
| filter: filterMetaContent | ||
| } | ||
| ] | ||
| ]) | ||
| ], | ||
| [ | ||
| "object", | ||
| new Map([ | ||
| [ | ||
| "data", | ||
| { | ||
| parse: parseSrc | ||
| } | ||
| ] | ||
| ]) | ||
| ], | ||
| [ | ||
| "script", | ||
| new Map([ | ||
| [ | ||
| "src", | ||
| { | ||
| parse: parseSrc, | ||
| // Only executable-JS scripts become entries. Non-JS | ||
| // `<script>` types (e.g. `application/ld+json`, | ||
| // `importmap`) fall through to HtmlSourceDependency so | ||
| // the browser keeps seeing them as data blocks, with | ||
| // the asset URL rewritten like any other resource. | ||
| entry: isExecutableJsScript | ||
| } | ||
| ] | ||
| ]) | ||
| ], | ||
| [ | ||
| "source", | ||
| new Map([ | ||
| [ | ||
| "src", | ||
| { | ||
| parse: parseSrc | ||
| } | ||
| ], | ||
| [ | ||
| "srcset", | ||
| { | ||
| parse: parseSrcset | ||
| } | ||
| ] | ||
| ]) | ||
| ], | ||
| [ | ||
| "track", | ||
| new Map([ | ||
| [ | ||
| "src", | ||
| { | ||
| parse: parseSrc | ||
| } | ||
| ] | ||
| ]) | ||
| ], | ||
| [ | ||
| "video", | ||
| new Map([ | ||
| [ | ||
| "poster", | ||
| { | ||
| parse: parseSrc | ||
| } | ||
| ], | ||
| [ | ||
| "src", | ||
| { | ||
| parse: parseSrc | ||
| } | ||
| ] | ||
| ]) | ||
| ], | ||
| // SVG | ||
| [ | ||
| "image", | ||
| new Map([ | ||
| [ | ||
| "xlink:href", | ||
| { | ||
| parse: parseSrc | ||
| } | ||
| ], | ||
| [ | ||
| "href", | ||
| { | ||
| parse: parseSrc | ||
| } | ||
| ] | ||
| ]) | ||
| ], | ||
| [ | ||
| "use", | ||
| new Map([ | ||
| [ | ||
| "xlink:href", | ||
| { | ||
| parse: parseSrc | ||
| } | ||
| ], | ||
| [ | ||
| "href", | ||
| { | ||
| parse: parseSrc | ||
| } | ||
| ] | ||
| ]) | ||
| ] | ||
| ]); | ||
| class HtmlParser extends Parser { | ||
| /** | ||
| * Creates an instance of HtmlParser. | ||
| * @param {(string | typeof import("../util/Hash"))=} hashFunction algorithm or constructor used by `output.hashFunction`; falls back to the default when omitted | ||
| * @param {string=} context compilation context used to contextify the HTML module's identifier when seeding the entry-name hash | ||
| * @param {boolean=} outputModule whether `output.module` is enabled; when true, classic `<script src>` tags get `type="module"` auto-inserted so the rewritten src can load the emitted ES module chunk | ||
| * @param {boolean=} css whether `experiments.css` is enabled; when true, inline `<style>` bodies are routed through the CSS pipeline as `data:text/css` modules | ||
| */ | ||
| constructor(hashFunction, context, outputModule, css) { | ||
| super(); | ||
| this.magicCommentContext = createMagicCommentContext(); | ||
| this.hashFunction = hashFunction; | ||
| this.context = context; | ||
| this.outputModule = outputModule; | ||
| this.css = css; | ||
| } | ||
| /** | ||
| * Parses the provided source and updates the parser state. | ||
| * @param {string | Buffer | PreparsedAst} source the source to parse | ||
| * @param {ParserState} state the parser state | ||
| * @returns {ParserState} the parser state | ||
| */ | ||
| parse(source, state) { | ||
| if (Buffer.isBuffer(source)) { | ||
| source = source.toString("utf8"); | ||
| } else if (typeof source === "object") { | ||
| throw new Error("webpackAst is unexpected for the HtmlParser"); | ||
| } | ||
| if (source[0] === "\uFEFF") { | ||
| source = source.slice(1); | ||
| } | ||
| const locConverter = new LocConverter(source); | ||
| const module = state.module; | ||
| // Stable, per-HTML-module prefix used when generating entry names for | ||
| // script src / modulepreload references so they don't collide across | ||
| // HTML modules in the same compilation. We hash the module's resource | ||
| // path (a plain absolute path) — going through `contextify` against | ||
| // the compilation root keeps the hash machine-stable for the same | ||
| // project layout. Note: `module.identifier()` returns `html|<path>` | ||
| // for HTML modules, which doesn't start with `/`, so contextify would | ||
| // leave it absolute. `module.resource` is the bare path. | ||
| /** @type {string} */ | ||
| const resource = | ||
| /** @type {EXPECTED_ANY} */ (module).resource || module.identifier(); | ||
| const moduleHash = createHash(this.hashFunction || "md4") | ||
| .update(this.context ? contextify(this.context, resource) : resource) | ||
| .digest("hex") | ||
| .slice(0, 8); | ||
| /** @typedef {{ nameStart: number, nameEnd: number, valueStart: number, valueEnd: number }} AttrToken */ | ||
| /** @type {AttrToken[]} */ | ||
| const pendingAttributes = []; | ||
| /** | ||
| * Reconciles the rewritten `<script>` tag's `type` attribute with the | ||
| * emitted chunk's actual format. Used by both the `<script src>` and | ||
| * inline `<script>` paths so the two stay in sync. | ||
| * @param {AttrToken | undefined} typeAttr existing `type` attribute, if any | ||
| * @param {number} nameEnd position right after `<script` (for inserts) | ||
| * @param {"classic" | "esm-script"} kind chunk kind decided by the parser | ||
| * @param {string} input full source string | ||
| * @returns {void} | ||
| */ | ||
| const reconcileScriptTypeAttr = (typeAttr, nameEnd, kind, input) => { | ||
| if (this.outputModule && kind === "classic") { | ||
| // Chunk is an ES module; upgrade the tag. | ||
| if (typeAttr && typeAttr.valueStart !== -1) { | ||
| module.addPresentationalDependency( | ||
| new ConstDependency("module", [ | ||
| typeAttr.valueStart, | ||
| typeAttr.valueEnd | ||
| ]) | ||
| ); | ||
| } else { | ||
| module.addPresentationalDependency( | ||
| new ConstDependency(' type="module"', nameEnd) | ||
| ); | ||
| } | ||
| } else if (!this.outputModule && kind === "esm-script" && typeAttr) { | ||
| // Chunk is a classic IIFE; drop `type="module"` so the | ||
| // browser doesn't load it under module semantics. | ||
| let attrEnd; | ||
| if (typeAttr.valueStart === -1) { | ||
| attrEnd = typeAttr.nameEnd; | ||
| } else if ( | ||
| input[typeAttr.valueEnd] === '"' || | ||
| input[typeAttr.valueEnd] === "'" | ||
| ) { | ||
| attrEnd = typeAttr.valueEnd + 1; | ||
| } else { | ||
| attrEnd = typeAttr.valueEnd; | ||
| } | ||
| // Consume one leading whitespace char so we don't leave a | ||
| // double space between `<script` and the next attribute. | ||
| let attrStart = typeAttr.nameStart; | ||
| if ( | ||
| attrStart > 0 && | ||
| isASCIIWhitespace(input.charCodeAt(attrStart - 1)) | ||
| ) { | ||
| attrStart -= 1; | ||
| } | ||
| module.addPresentationalDependency( | ||
| new ConstDependency("", [attrStart, attrEnd]) | ||
| ); | ||
| } | ||
| }; | ||
| // Inline `<script>` body extraction is deferred to the matching | ||
| // `closeTag` event so the walker's script-data state machine | ||
| // (including its escaped/double-escaped sub-states) decides where | ||
| // the body ends. This is the spec-compliant way to find the close | ||
| // — a plain `</script>` regex would split too early inside | ||
| // `<!--<script>…</script>-->` patterns. | ||
| /** @type {null | { contentStart: number, attrs: Map<string, string>, typeAttr: AttrToken | undefined, nameEnd: number }} */ | ||
| let pendingInlineScript = null; | ||
| // Script src / modulepreload references are collected per-category | ||
| // during the walk; HtmlModulesPlugin later turns them into real | ||
| // entries. Classic <script src> and <script type="module" src> are | ||
| // chained via a leader-only dependOn so they share a runtime. | ||
| // `<link rel="modulepreload">` entries are kept independent — they | ||
| // must preload without running, so they can never become a runtime | ||
| // leader that other entries would import. | ||
| /** | ||
| * @typedef {object} EntryScriptInfo | ||
| * @property {string} request | ||
| * @property {string} entryName | ||
| * @property {"classic" | "esm-script" | "modulepreload" | "stylesheet"} kind | ||
| */ | ||
| /** @type {EntryScriptInfo[]} */ | ||
| const classicEntries = []; | ||
| /** @type {EntryScriptInfo[]} */ | ||
| const esmScriptEntries = []; | ||
| /** @type {EntryScriptInfo[]} */ | ||
| const modulePreloadEntries = []; | ||
| /** @type {EntryScriptInfo[]} */ | ||
| const stylesheetEntries = []; | ||
| let nextEntryIndex = 0; | ||
| /** | ||
| * Tracks the `webpackIgnore` value from the most recent comment that | ||
| * appears before the next tag. Reset whenever a tag is emitted or a | ||
| * comment without a `webpackIgnore` value is encountered. | ||
| * @type {boolean | undefined} | ||
| */ | ||
| let pendingWebpackIgnore; | ||
| const magicCommentContext = this.magicCommentContext; | ||
| // TODO implement full HTML parser (WASM) | ||
| walkHtmlTokens(source, 0, { | ||
| comment: (input, start, end) => { | ||
| // Only proper `<!-- ... -->` comments carry magic comments. | ||
| // `walkHtmlTokens` also dispatches this callback for bogus | ||
| // comments such as `<!DOCTYPE …>` and `<?…>`, which must not | ||
| // be parsed as magic comments. | ||
| if ( | ||
| end - start < 7 || | ||
| input.charCodeAt(start) !== 0x3c /* < */ || | ||
| input.charCodeAt(start + 1) !== 0x21 /* ! */ || | ||
| input.charCodeAt(start + 2) !== 0x2d /* - */ || | ||
| input.charCodeAt(start + 3) !== 0x2d /* - */ || | ||
| input.charCodeAt(end - 1) !== 0x3e /* > */ || | ||
| input.charCodeAt(end - 2) !== 0x2d /* - */ || | ||
| input.charCodeAt(end - 3) !== 0x2d /* - */ | ||
| ) { | ||
| pendingWebpackIgnore = undefined; | ||
| return end; | ||
| } | ||
| const contentStart = start + 4; | ||
| const contentEnd = end - 3; | ||
| const value = input.slice(contentStart, contentEnd); | ||
| if (!webpackCommentRegExp.test(value)) { | ||
| pendingWebpackIgnore = undefined; | ||
| return end; | ||
| } | ||
| /** @type {Record<string, EXPECTED_ANY>} */ | ||
| let options; | ||
| try { | ||
| options = vm.runInContext( | ||
| `(function(){return {${value}};})()`, | ||
| magicCommentContext | ||
| ); | ||
| } catch (err) { | ||
| const { line: sl, column: sc } = locConverter.get(start); | ||
| const { line: el, column: ec } = locConverter.get(end); | ||
| module.addWarning( | ||
| new CommentCompilationWarning( | ||
| `Compilation error while processing magic comment(-s): /*${value}*/: ${ | ||
| /** @type {Error} */ (err).message | ||
| }`, | ||
| { | ||
| start: { line: sl, column: sc }, | ||
| end: { line: el, column: ec } | ||
| } | ||
| ) | ||
| ); | ||
| pendingWebpackIgnore = undefined; | ||
| return end; | ||
| } | ||
| if (options.webpackIgnore === undefined) { | ||
| pendingWebpackIgnore = undefined; | ||
| return end; | ||
| } | ||
| if (typeof options.webpackIgnore !== "boolean") { | ||
| const { line: sl, column: sc } = locConverter.get(start); | ||
| const { line: el, column: ec } = locConverter.get(end); | ||
| module.addWarning( | ||
| new UnsupportedFeatureWarning( | ||
| `\`webpackIgnore\` expected a boolean, but received: ${options.webpackIgnore}.`, | ||
| { | ||
| start: { line: sl, column: sc }, | ||
| end: { line: el, column: ec } | ||
| } | ||
| ) | ||
| ); | ||
| pendingWebpackIgnore = undefined; | ||
| return end; | ||
| } | ||
| pendingWebpackIgnore = options.webpackIgnore; | ||
| return end; | ||
| }, | ||
| attribute: ( | ||
| input, | ||
| nameStart, | ||
| nameEnd, | ||
| valueStart, | ||
| valueEnd, | ||
| quoteType | ||
| ) => { | ||
| pendingAttributes.push({ nameStart, nameEnd, valueStart, valueEnd }); | ||
| if (valueStart === -1) return nameEnd; | ||
| return quoteType !== walkHtmlTokens.QUOTE_NONE | ||
| ? valueEnd + 1 | ||
| : valueEnd; | ||
| }, | ||
| closeTag: (input, start, end, nameStart, nameEnd) => { | ||
| pendingWebpackIgnore = undefined; | ||
| if (pendingInlineScript) { | ||
| const elName = input.slice(nameStart, nameEnd).toLowerCase(); | ||
| if (elName === "script") { | ||
| const ps = pendingInlineScript; | ||
| pendingInlineScript = null; | ||
| const contentStart = ps.contentStart; | ||
| const contentEnd = start; // start of `</script>` | ||
| const jsContent = input.slice(contentStart, contentEnd); | ||
| if (jsContent.trim() === "") return end; | ||
| // Base64-encode the JS body so the data URI round-trips | ||
| // arbitrary JavaScript text, including non-ASCII source | ||
| // (`decodeDataURI` decodes non-base64 bodies as ASCII, | ||
| // which would corrupt Unicode string literals or | ||
| // identifiers). | ||
| const request = `data:text/javascript;base64,${Buffer.from( | ||
| jsContent, | ||
| "utf8" | ||
| ).toString("base64")}`; | ||
| const useEsmEntry = isModuleScript(ps.attrs); | ||
| const entryName = `__html_${moduleHash}_${nextEntryIndex++}`; | ||
| /** @type {"classic" | "esm-script"} */ | ||
| const kind = useEsmEntry ? "esm-script" : "classic"; | ||
| const { line: sl, column: sc } = locConverter.get(contentStart); | ||
| const { line: el, column: ec } = locConverter.get(contentEnd); | ||
| const dep = new HtmlInlineScriptDependency( | ||
| request, | ||
| ps.nameEnd, | ||
| [contentStart, contentEnd], | ||
| entryName, | ||
| useEsmEntry ? "esm" : "commonjs" | ||
| ); | ||
| dep.setLoc(sl, sc, el, ec); | ||
| module.addPresentationalDependency(dep); | ||
| reconcileScriptTypeAttr(ps.typeAttr, ps.nameEnd, kind, input); | ||
| const collection = | ||
| kind === "classic" ? classicEntries : esmScriptEntries; | ||
| collection.push({ request, entryName, kind }); | ||
| } | ||
| } | ||
| return end; | ||
| }, | ||
| openTag: (input, start, end, nameStart, nameEnd) => { | ||
| const ignore = pendingWebpackIgnore === true; | ||
| pendingWebpackIgnore = undefined; | ||
| if (ignore) { | ||
| // For `<script>` and `<style>` we don't emit a dependency, | ||
| // but we must NOT advance past the close tag either: the | ||
| // walker is already in script-data/rawtext state for | ||
| // those tags and will consume the body and emit the | ||
| // matching `closeTag` itself. Returning a position past | ||
| // `</script>`/`</style>` would leave the walker stuck in | ||
| // rawtext mode, swallowing later markup. | ||
| pendingAttributes.length = 0; | ||
| return end; | ||
| } | ||
| const elementName = input.slice(nameStart, nameEnd).toLowerCase(); | ||
| // `<style>` is rawtext: capture the inline CSS and hand it to | ||
| // the CSS pipeline as a virtual `data:text/css` module with | ||
| // `exportType: "text"`. We use the regex only to discover the | ||
| // `</style>` position so we can slice the body; the walker is | ||
| // already in rawtext state for `<style>` and will emit the | ||
| // matching `closeTag` event itself, so we must return `end` | ||
| // (the position right after the opening tag's `>`) rather | ||
| // than advancing past `</style>`. Only `<style>` tags whose | ||
| // `type` attribute is absent, empty, or `text/css` are | ||
| // processed; other types are left untouched. | ||
| if (elementName === "style") { | ||
| /** @type {string | undefined} */ | ||
| let typeValue; | ||
| for (const attr of pendingAttributes) { | ||
| const attrName = input | ||
| .slice(attr.nameStart, attr.nameEnd) | ||
| .toLowerCase(); | ||
| if (attrName === "type") { | ||
| typeValue = | ||
| attr.valueStart !== -1 | ||
| ? input.slice(attr.valueStart, attr.valueEnd) | ||
| : ""; | ||
| break; | ||
| } | ||
| } | ||
| pendingAttributes.length = 0; | ||
| STYLE_END_REGEXP.lastIndex = end; | ||
| const closeMatch = STYLE_END_REGEXP.exec(input); | ||
| if (!closeMatch) return end; | ||
| const contentStart = end; | ||
| const contentEnd = closeMatch.index; | ||
| const trimmedType = | ||
| typeValue !== undefined ? typeValue.trim().toLowerCase() : ""; | ||
| if ( | ||
| typeValue !== undefined && | ||
| trimmedType !== "" && | ||
| trimmedType !== "text/css" | ||
| ) { | ||
| return end; | ||
| } | ||
| // Inline-style processing requires the CSS pipeline; when | ||
| // `experiments.css` is off, leave the body alone — the | ||
| // walker is in rawtext mode for `<style>` and will skip | ||
| // over the body to the matching `</style>` itself. | ||
| if (!this.css) { | ||
| return end; | ||
| } | ||
| const cssContent = input.slice(contentStart, contentEnd); | ||
| if (cssContent.trim() === "") { | ||
| return end; | ||
| } | ||
| // URL-encode the CSS body so the data URI parser's `(.*)$` | ||
| // body group matches even when the source has newlines or | ||
| // other characters that would otherwise break the regex. | ||
| const request = `data:text/css,${encodeURIComponent(cssContent)}`; | ||
| const { line: sl, column: sc } = locConverter.get(contentStart); | ||
| const { line: el, column: ec } = locConverter.get(contentEnd); | ||
| const dep = new HtmlInlineStyleDependency(request, [ | ||
| contentStart, | ||
| contentEnd | ||
| ]); | ||
| dep.setLoc(sl, sc, el, ec); | ||
| module.addDependency(dep); | ||
| module.addCodeGenerationDependency(dep); | ||
| return end; | ||
| } | ||
| const sources = DEFAULT_SOURCES.get(elementName); | ||
| if (!sources) { | ||
| pendingAttributes.length = 0; | ||
| return end; | ||
| } | ||
| /** @type {Map<string, string> | undefined} */ | ||
| let attributesMap; | ||
| const getAttributesMap = () => { | ||
| if (attributesMap) return attributesMap; | ||
| attributesMap = new Map(); | ||
| for (const attr of pendingAttributes) { | ||
| const name = input | ||
| .slice(attr.nameStart, attr.nameEnd) | ||
| .toLowerCase(); | ||
| const value = | ||
| attr.valueStart !== -1 | ||
| ? input.slice(attr.valueStart, attr.valueEnd) | ||
| : ""; | ||
| attributesMap.set(name, value); | ||
| } | ||
| return attributesMap; | ||
| }; | ||
| for (const attr of pendingAttributes) { | ||
| const attributeName = input | ||
| .slice(attr.nameStart, attr.nameEnd) | ||
| .toLowerCase(); | ||
| const sourceItem = sources.get(attributeName); | ||
| if (!sourceItem) continue; | ||
| // TODO(html-entities): We should ideally decode entities here using | ||
| // `walkHtmlTokens.decodeHtmlEntities(input.slice(...))` so that URLs | ||
| // like `image.png?a=1&b=2` are correctly resolved as `&`. | ||
| // However, doing so currently breaks `srcset` parsing tests (e.g. `errors.js`) | ||
| // which explicitly expect whitespace entities like `	` to NOT be decoded | ||
| // before the srcset parser runs. A follow-up PR should implement selective | ||
| // decoding for specific URL attributes. | ||
| const attributeValue = | ||
| attr.valueStart !== -1 | ||
| ? input.slice(attr.valueStart, attr.valueEnd) | ||
| : ""; | ||
| if (!attributeValue) continue; | ||
| if ( | ||
| typeof sourceItem.filter === "function" && | ||
| !sourceItem.filter(getAttributesMap()) | ||
| ) { | ||
| continue; | ||
| } | ||
| /** @type {ParsedSource[] | undefined} */ | ||
| let parsedAttributeValue; | ||
| try { | ||
| parsedAttributeValue = sourceItem.parse(attributeValue); | ||
| } catch (err) { | ||
| const { line: sl, column: sc } = locConverter.get(attr.valueStart); | ||
| const { line: el, column: ec } = locConverter.get(attr.valueEnd); | ||
| module.addError( | ||
| new ModuleDependencyError( | ||
| module, | ||
| new WebpackError( | ||
| `Bad value for attribute "${attributeName}" on element "${elementName}": ${ | ||
| /** @type {Error} */ (err).message | ||
| }` | ||
| ), | ||
| { | ||
| start: { line: sl, column: sc }, | ||
| end: { line: el, column: ec } | ||
| } | ||
| ) | ||
| ); | ||
| } | ||
| if (!parsedAttributeValue) continue; | ||
| // `<link rel="stylesheet">` is upgraded to an entry only when | ||
| // `experiments.css` is on — that's the mode where webpack can | ||
| // bundle the CSS into its own chunk. Without it, the | ||
| // stylesheet href stays a plain asset URL. Scope this to the | ||
| // `href` attribute only: `<link>` also exposes | ||
| // `imagesrcset` URLs which must continue to flow through | ||
| // the regular asset rewriting path even on a stylesheet | ||
| // link. | ||
| const isStylesheetEntry = | ||
| this.css && | ||
| elementName === "link" && | ||
| attributeName === "href" && | ||
| isLinkStylesheet(getAttributesMap()); | ||
| const isEntry = | ||
| isStylesheetEntry || | ||
| sourceItem.entry === true || | ||
| (typeof sourceItem.entry === "function" && | ||
| sourceItem.entry(getAttributesMap())); | ||
| // `<script type="module" src>` and `<link rel="modulepreload">` | ||
| // reference ES modules; everything else under `<script src>` is a | ||
| // classic script. The category drives ESM vs CommonJS resolution | ||
| // of the entry — the chunk format is controlled by the user via | ||
| // `output.module` / `experiments.outputModule`. | ||
| const useEsmEntry = | ||
| (elementName === "script" && isModuleScript(getAttributesMap())) || | ||
| sourceItem.entryCategory === "esm"; | ||
| for (const parsedSource of parsedAttributeValue) { | ||
| const [value, innerStart, innerEnd] = parsedSource; | ||
| if (value.startsWith("#")) continue; | ||
| const sourceStart = attr.valueStart + innerStart; | ||
| const sourceEnd = attr.valueStart + innerEnd; | ||
| const { line: sl, column: sc } = locConverter.get(sourceStart); | ||
| const { line: el, column: ec } = locConverter.get(sourceEnd); | ||
| if (isEntry) { | ||
| const entryName = `__html_${moduleHash}_${nextEntryIndex++}`; | ||
| const isStylesheetLink = | ||
| elementName === "link" && isLinkStylesheet(getAttributesMap()); | ||
| /** @type {"classic" | "esm-script" | "modulepreload" | "stylesheet"} */ | ||
| const kind = | ||
| elementName === "link" | ||
| ? isStylesheetLink | ||
| ? "stylesheet" | ||
| : "modulepreload" | ||
| : useEsmEntry | ||
| ? "esm-script" | ||
| : "classic"; | ||
| // With `output.module` enabled, a classic `<script src>` is | ||
| // upgraded in place to `<script type="module" src>` (see the | ||
| // ConstDependency insertion below). Account for that in the | ||
| // dependency's `elementKind` so sibling tags emitted by the | ||
| // template for additional entry chunks (runtime / split chunks) | ||
| // also use `type="module"`. | ||
| const willBeModuleScript = | ||
| kind === "esm-script" || | ||
| (this.outputModule && | ||
| kind === "classic" && | ||
| elementName === "script"); | ||
| /** @type {"script-classic" | "script-module" | "modulepreload" | "stylesheet"} */ | ||
| const elementKind = | ||
| kind === "modulepreload" | ||
| ? "modulepreload" | ||
| : kind === "stylesheet" | ||
| ? "stylesheet" | ||
| : willBeModuleScript | ||
| ? "script-module" | ||
| : "script-classic"; | ||
| const dep = new HtmlScriptSrcDependency( | ||
| value, | ||
| [sourceStart, sourceEnd], | ||
| entryName, | ||
| // `<link rel="stylesheet">` is bundled as a CSS entry — | ||
| // using a non-"url" category so the default `.css` rule | ||
| // (which gives the resolved module the CSS module type) | ||
| // wins over the `dependency: "url"` → asset rule. | ||
| kind === "stylesheet" | ||
| ? "css-import" | ||
| : useEsmEntry | ||
| ? "esm" | ||
| : sourceItem.entryCategory, | ||
| elementKind, | ||
| start, | ||
| end | ||
| ); | ||
| dep.setLoc(sl, sc, el, ec); | ||
| module.addPresentationalDependency(dep); | ||
| // Reconcile the rewritten `<script>` tag's `type` | ||
| // attribute with the chunk's actual format. See | ||
| // `reconcileScriptTypeAttr` for the rules. | ||
| if ( | ||
| elementName === "script" && | ||
| (kind === "classic" || kind === "esm-script") | ||
| ) { | ||
| /** @type {AttrToken | undefined} */ | ||
| let typeAttr; | ||
| for (const a of pendingAttributes) { | ||
| if ( | ||
| input.slice(a.nameStart, a.nameEnd).toLowerCase() === "type" | ||
| ) { | ||
| typeAttr = a; | ||
| break; | ||
| } | ||
| } | ||
| reconcileScriptTypeAttr(typeAttr, nameEnd, kind, input); | ||
| } | ||
| const collection = | ||
| kind === "classic" | ||
| ? classicEntries | ||
| : kind === "esm-script" | ||
| ? esmScriptEntries | ||
| : kind === "stylesheet" | ||
| ? stylesheetEntries | ||
| : modulePreloadEntries; | ||
| collection.push({ request: value, entryName, kind }); | ||
| } else { | ||
| const dep = new HtmlSourceDependency(value, [ | ||
| sourceStart, | ||
| sourceEnd | ||
| ]); | ||
| dep.setLoc(sl, sc, el, ec); | ||
| module.addDependency(dep); | ||
| module.addCodeGenerationDependency(dep); | ||
| } | ||
| } | ||
| } | ||
| // `<script>` is rawtext (the "script data state" in the HTML | ||
| // tokenizer): its body must never be reparsed as HTML, | ||
| // regardless of whether the tag has a `src` attribute. The | ||
| // walker is already in script-data state for `<script>` and | ||
| // will emit the matching `closeTag` event itself, so we | ||
| // return `end` and defer body extraction to the closeTag | ||
| // callback (which gets the spec-correct `</script>` position | ||
| // even in escaped/double-escaped script-data sub-states). | ||
| // When the tag has no `src` and its body is non-empty, the | ||
| // closeTag handler bundles the inline JS as its own entry — | ||
| // the same pipeline that processes `<script src>` — by | ||
| // issuing a `data:text/javascript;base64,...` virtual request | ||
| // and adding a dependency that rewrites the tag to | ||
| // `<script src="…">` at render time. Only `<script>` tags | ||
| // whose `type` attribute is absent, empty, or a recognized | ||
| // JS mimetype are processed as JS; other types (e.g. | ||
| // `application/ld+json`, `importmap`) are left untouched. | ||
| if (elementName === "script") { | ||
| const attrs = getAttributesMap(); | ||
| // Use attribute presence, not value: a `<script src>` with | ||
| // an empty or valueless `src` still ignores its inline | ||
| // body in the browser, so we must not bundle the body. | ||
| const hasSrc = attrs.has("src"); | ||
| /** @type {AttrToken | undefined} */ | ||
| let typeAttr; | ||
| for (const a of pendingAttributes) { | ||
| if (input.slice(a.nameStart, a.nameEnd).toLowerCase() === "type") { | ||
| typeAttr = a; | ||
| break; | ||
| } | ||
| } | ||
| pendingAttributes.length = 0; | ||
| if (hasSrc || !isExecutableJsScript(attrs)) { | ||
| // `<script src>` body is ignored by the browser, and | ||
| // non-JS `<script type>` (e.g. importmap, JSON-LD) | ||
| // passes through unchanged. Either way the walker | ||
| // consumes the body and emits the close tag itself. | ||
| return end; | ||
| } | ||
| pendingInlineScript = { | ||
| contentStart: end, | ||
| attrs, | ||
| typeAttr, | ||
| nameEnd | ||
| }; | ||
| return end; | ||
| } | ||
| pendingAttributes.length = 0; | ||
| return end; | ||
| } | ||
| }); | ||
| const buildInfo = /** @type {BuildInfo} */ (module.buildInfo); | ||
| buildInfo.strict = true; | ||
| // Hand off the collected entries to HtmlModulesPlugin; it creates the | ||
| // real compilation entries during the finishMake hook. The classic | ||
| // and esm-script groups are chained via a leader-only dependOn so | ||
| // they share a runtime; modulepreload entries are emitted as | ||
| // independent entries since `<link rel=modulepreload>` must preload | ||
| // without running. | ||
| if ( | ||
| classicEntries.length > 0 || | ||
| esmScriptEntries.length > 0 || | ||
| modulePreloadEntries.length > 0 || | ||
| stylesheetEntries.length > 0 | ||
| ) { | ||
| /** @type {Record<string, EntryScriptInfo[]>} */ | ||
| (buildInfo.htmlEntryScripts) = { | ||
| classic: classicEntries, | ||
| "esm-script": esmScriptEntries, | ||
| modulepreload: modulePreloadEntries, | ||
| stylesheet: stylesheetEntries | ||
| }; | ||
| } | ||
| const buildMeta = /** @type {BuildMeta} */ (state.module.buildMeta); | ||
| buildMeta.exportsType = "default"; | ||
| state.module.addDependency(new StaticExportsDependency(["default"], true)); | ||
| return state; | ||
| } | ||
| } | ||
| module.exports = HtmlParser; |
Sorry, the diff of this file is too big to display
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| Author Arka Pratim Chaudhuri @arkapratimc | ||
| */ | ||
| "use strict"; | ||
| const WebpackError = require("../errors/WebpackError"); | ||
| class FalseIIFEUmdWarning extends WebpackError { | ||
| constructor() { | ||
| super(); | ||
| /** @type {string} */ | ||
| this.name = "FalseIIFEUmdWarning"; | ||
| this.message = | ||
| "Configuration:\nSetting 'output.iife' to 'false' is incompatible with 'output.library.type' set to 'umd'. This configuration may cause unexpected behavior, as UMD libraries are expected to use an IIFE (Immediately Invoked Function Expression) to support various module formats. Consider setting 'output.iife' to 'true' or choosing a different 'library.type' to ensure compatibility.\nLearn more: https://webpack.js.org/configuration/output/"; | ||
| } | ||
| } | ||
| module.exports = FalseIIFEUmdWarning; |
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| */ | ||
| "use strict"; | ||
| const RuntimeGlobals = require("../RuntimeGlobals"); | ||
| const Template = require("../Template"); | ||
| const HelperRuntimeModule = require("./HelperRuntimeModule"); | ||
| /** @typedef {import("../Compilation")} Compilation */ | ||
| class SetAnonymousDefaultNameRuntimeModule extends HelperRuntimeModule { | ||
| constructor() { | ||
| super("set anonymous default export name"); | ||
| } | ||
| /** | ||
| * Generates runtime code for this runtime module. | ||
| * @returns {string | null} runtime code | ||
| */ | ||
| generate() { | ||
| const compilation = /** @type {Compilation} */ (this.compilation); | ||
| const { runtimeTemplate } = compilation; | ||
| const fn = RuntimeGlobals.setAnonymousDefaultName; | ||
| return Template.asString([ | ||
| "// set .name for anonymous default exports per ES spec", | ||
| `${fn} = ${runtimeTemplate.basicFunction("x", [ | ||
| '(Object.getOwnPropertyDescriptor(x, "name") || {}).writable || Object.defineProperty(x, "name", { value: "default", configurable: true });' | ||
| ])};` | ||
| ]); | ||
| } | ||
| } | ||
| module.exports = SetAnonymousDefaultNameRuntimeModule; |
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| Author Alexander Akait @alexander-akait | ||
| */ | ||
| "use strict"; | ||
| const mod = require("module"); | ||
| const { | ||
| JAVASCRIPT_MODULE_TYPE_AUTO, | ||
| JAVASCRIPT_MODULE_TYPE_DYNAMIC, | ||
| JAVASCRIPT_MODULE_TYPE_ESM | ||
| } = require("../ModuleTypeConstants"); | ||
| const NormalModule = require("../NormalModule"); | ||
| const ModuleBuildError = require("../errors/ModuleBuildError"); | ||
| const memoize = require("../util/memoize"); | ||
| const removeBOM = require("../util/removeBOM"); | ||
| /** @typedef {import("webpack-sources").RawSourceMap} RawSourceMap */ | ||
| /** @typedef {import("../Compiler")} Compiler */ | ||
| /** @typedef {import("../NormalModule")} NormalModuleType */ | ||
| /** @typedef {import("../NormalModule").Result} Result */ | ||
| /** @typedef {import("../javascript/JavascriptParser")} JavascriptParser */ | ||
| const getSourceMapSource = memoize( | ||
| () => require("webpack-sources").SourceMapSource | ||
| ); | ||
| const PLUGIN_NAME = "TypeScriptPlugin"; | ||
| /** @type {Set<string>} */ | ||
| const JS_MODULE_TYPES = new Set([ | ||
| JAVASCRIPT_MODULE_TYPE_AUTO, | ||
| JAVASCRIPT_MODULE_TYPE_DYNAMIC, | ||
| JAVASCRIPT_MODULE_TYPE_ESM | ||
| ]); | ||
| const TS_RESOURCE_RE = /\.(?:[mc]?tsx?)$/i; | ||
| const TSX_RESOURCE_RE = /\.[mc]?tsx$/i; | ||
| const TS_DATA_URI_RE = /^data:(?:text|application)\/typescript/i; | ||
| const TSX_NOT_SUPPORTED = | ||
| "experiments.typescript does not support .tsx/JSX. " + | ||
| "Use a TSX-capable loader (e.g. swc-loader, esbuild-loader, ts-loader) for .tsx files."; | ||
| const NODE_API_MISSING = | ||
| "experiments.typescript requires Node.js >= 22.6. " + | ||
| "`module.stripTypeScriptTypes` is not available on this Node.js version."; | ||
| /** | ||
| * Whether the resource (path or `data:` URI) should go through the TypeScript | ||
| * transform. Returns true for `.ts`, `.cts`, `.mts`, and the JSX-flavoured | ||
| * variants (so the `.tsx` branch can throw a friendly error), as well as the | ||
| * `text/typescript` / `application/typescript` data URIs. | ||
| * @param {string} resource module resource (without query string) | ||
| * @returns {boolean} true if the resource should be transformed | ||
| */ | ||
| const isTypeScriptResource = (resource) => | ||
| TS_RESOURCE_RE.test(resource) || TS_DATA_URI_RE.test(resource); | ||
| /** | ||
| * Build a line-granularity identity source map for a strip-types output. | ||
| * `mode: "strip"` replaces type annotations with whitespace, so the stripped | ||
| * output preserves the original line layout — an identity mapping is correct. | ||
| * Node's API does not emit a source map in strip mode (`sourceMap: true` is | ||
| * rejected on Node 22+ and Node 26+), so we construct one by hand. | ||
| * @param {string} resource module resource path | ||
| * @param {string} originalSource pre-strip source content | ||
| * @returns {RawSourceMap} identity source map | ||
| */ | ||
| const createIdentitySourceMap = (resource, originalSource) => { | ||
| const lineCount = (originalSource.match(/\n/g) || []).length + 1; | ||
| // Mappings: each line emits a single segment at column 0 mapping to | ||
| // column 0 of the same line in the source. `AAAA` for line 1, `;AACA` | ||
| // for each subsequent line (cumulative source-line delta of +1 per line). | ||
| const mappings = `AAAA${";AACA".repeat(lineCount - 1)}`; | ||
| return { | ||
| version: 3, | ||
| file: resource, | ||
| sources: [resource], | ||
| sourcesContent: [originalSource], | ||
| names: [], | ||
| mappings | ||
| }; | ||
| }; | ||
| /** | ||
| * Compose the strip-types source map with an upstream loader source map so the | ||
| * final map points back to the loader's original input (e.g. a `.vue` / | ||
| * `.svelte` / custom loader that emits TS code). | ||
| * @param {string} resource module resource | ||
| * @param {string} strippedSource post-strip JS | ||
| * @param {RawSourceMap} stripMap identity map for the strip step | ||
| * @param {string} preStripSource pre-strip TS (loader output) | ||
| * @param {string | RawSourceMap} loaderSourceMap upstream loader source map | ||
| * @returns {RawSourceMap} composed map | ||
| */ | ||
| const composeWithLoaderSourceMap = ( | ||
| resource, | ||
| strippedSource, | ||
| stripMap, | ||
| preStripSource, | ||
| loaderSourceMap | ||
| ) => { | ||
| const SourceMapSource = getSourceMapSource(); | ||
| const composed = new SourceMapSource( | ||
| strippedSource, | ||
| resource, | ||
| stripMap, | ||
| preStripSource, | ||
| loaderSourceMap, | ||
| true | ||
| ); | ||
| return /** @type {RawSourceMap} */ (composed.sourceAndMap().map) || stripMap; | ||
| }; | ||
| /** | ||
| * Run `module.stripTypeScriptTypes` on the input, wrapping any thrown | ||
| * `TypeScript ...` errors as `ModuleBuildError` so they surface as | ||
| * per-module build errors instead of uncaught exceptions. | ||
| * @param {string} input pre-strip TS source (BOM-free string) | ||
| * @returns {string} stripped JS | ||
| */ | ||
| const stripTypes = (input) => { | ||
| try { | ||
| // Pass only `mode`. `sourceUrl` would emit a `//# sourceURL=…` pragma | ||
| // into the output (V8 debugger hint), and `sourceMap: true` is | ||
| // rejected in strip mode — we build the source map by hand instead. | ||
| // eslint-disable-next-line n/no-unsupported-features/node-builtins | ||
| return mod.stripTypeScriptTypes(input, { mode: "strip" }); | ||
| } catch (err) { | ||
| throw new ModuleBuildError(/** @type {Error} */ (err)); | ||
| } | ||
| }; | ||
| /** | ||
| * Coerce a Buffer-or-string source to a UTF-8 string, dropping any BOM. | ||
| * @param {string | Buffer} source raw source from the loader pipeline | ||
| * @returns {string} UTF-8 string without BOM | ||
| */ | ||
| const toBomFreeString = (source) => { | ||
| const text = Buffer.isBuffer(source) ? source.toString("utf8") : source; | ||
| const stripped = removeBOM(text); | ||
| return typeof stripped === "string" ? stripped : stripped.toString("utf8"); | ||
| }; | ||
| class TypeScriptPlugin { | ||
| /** | ||
| * @param {Compiler} compiler webpack compiler | ||
| * @returns {void} | ||
| */ | ||
| apply(compiler) { | ||
| compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => { | ||
| NormalModule.getCompilationHooks(compilation).processResult.tap( | ||
| PLUGIN_NAME, | ||
| (result, module) => this._processResult(result, module) | ||
| ); | ||
| }); | ||
| } | ||
| /** | ||
| * processResult tap body. Returns the input untouched unless this is a | ||
| * TypeScript module that needs to be transformed. | ||
| * @param {Result} result loader result tuple | ||
| * @param {NormalModuleType} module the normal module | ||
| * @returns {Result} possibly transformed result | ||
| */ | ||
| _processResult(result, module) { | ||
| if (!JS_MODULE_TYPES.has(module.type)) return result; | ||
| const parser = /** @type {JavascriptParser} */ (module.parser); | ||
| if (!parser.options.typescript) return result; | ||
| const resource = module.nameForCondition(); | ||
| if (!resource || !isTypeScriptResource(resource)) return result; | ||
| if (TSX_RESOURCE_RE.test(resource)) { | ||
| throw new ModuleBuildError(new Error(TSX_NOT_SUPPORTED)); | ||
| } | ||
| if (!("stripTypeScriptTypes" in mod)) { | ||
| throw new ModuleBuildError(new Error(NODE_API_MISSING)); | ||
| } | ||
| const [rawSource, loaderSourceMap, ...rest] = result; | ||
| const preStripSource = toBomFreeString(rawSource); | ||
| const strippedSource = stripTypes(preStripSource); | ||
| const needSourceMap = module.useSourceMap || module.useSimpleSourceMap; | ||
| const stripMap = needSourceMap | ||
| ? createIdentitySourceMap(module.resource, preStripSource) | ||
| : undefined; | ||
| const outputSourceMap = | ||
| stripMap && loaderSourceMap | ||
| ? composeWithLoaderSourceMap( | ||
| module.resource, | ||
| strippedSource, | ||
| stripMap, | ||
| preStripSource, | ||
| loaderSourceMap | ||
| ) | ||
| : stripMap || loaderSourceMap; | ||
| return [strippedSource, outputSourceMap, ...rest]; | ||
| } | ||
| } | ||
| module.exports = TypeScriptPlugin; |
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| */ | ||
| "use strict"; | ||
| /** | ||
| * Utilities for building V3 source-map `mappings` strings without pulling in a | ||
| * full source-map library. The shape of the input is intentionally minimal — | ||
| * one slot per generated line, each holding zero, one, or many segments — so | ||
| * call sites that have a "one mapping per line" structure (like the CSS-module | ||
| * exports emit in `lib/css/CssGenerator.js`) can build mappings directly, | ||
| * while richer call sites can pass arrays of segments. | ||
| * | ||
| * TODO move this encoder into `webpack-sources` and replace the body of this | ||
| * file with re-exports. The public shape (`encodeVLQ`, `encodeMappings(lines)`, | ||
| * `MappingSegment`, `LineMappings`) is intended to match what would land | ||
| * upstream so call sites don't have to change. | ||
| */ | ||
| const VLQ_BASE64 = | ||
| "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; | ||
| /** | ||
| * Encode a signed integer as a base64 VLQ string per the source-map V3 spec. | ||
| * @param {number} value signed integer to encode | ||
| * @returns {string} base64 VLQ encoded value | ||
| */ | ||
| const encodeVLQ = (value) => { | ||
| let vlq = value < 0 ? (-value << 1) | 1 : value << 1; | ||
| let result = ""; | ||
| do { | ||
| let digit = vlq & 0x1f; | ||
| vlq >>>= 5; | ||
| if (vlq > 0) digit |= 0x20; | ||
| result += VLQ_BASE64[digit]; | ||
| } while (vlq > 0); | ||
| return result; | ||
| }; | ||
| /** | ||
| * @typedef {object} MappingSegment | ||
| * @property {number=} generatedColumn 0-based generated column (defaults to 0) | ||
| * @property {number=} sourceIndex index into the surrounding source map's `sources` array; omit for a generated-only segment | ||
| * @property {number=} originalLine 0-based line in the original source (required when `sourceIndex` is set) | ||
| * @property {number=} originalColumn 0-based column in the original source (required when `sourceIndex` is set) | ||
| * @property {number=} nameIndex index into the surrounding source map's `names` array | ||
| */ | ||
| /** @typedef {null | MappingSegment | MappingSegment[]} LineMappings */ | ||
| /** | ||
| * Encode a V3 source-map `mappings` string from a per-generated-line | ||
| * description of segments. | ||
| * | ||
| * Each entry of `lines` describes the mappings for one generated line: | ||
| * | ||
| * - `null` (or `undefined`) — the line has no mappings. | ||
| * - a single `MappingSegment` — convenience for the common "one mapping at | ||
| * column 0" case. | ||
| * - `MappingSegment[]` — multiple segments on the same line. | ||
| * | ||
| * Lines are joined with `;`, segments within a line with `,`. All numeric | ||
| * fields are encoded as deltas relative to the previous emitted segment, per | ||
| * the V3 spec. | ||
| * @param {LineMappings[]} lines per-generated-line mapping segments | ||
| * @returns {string} VLQ-encoded V3 mappings string | ||
| */ | ||
| const encodeMappings = (lines) => { | ||
| let prevSourceIndex = 0; | ||
| let prevOriginalLine = 0; | ||
| let prevOriginalColumn = 0; | ||
| let prevNameIndex = 0; | ||
| const encodedLines = []; | ||
| for (const line of lines) { | ||
| if (line === null || line === undefined) { | ||
| encodedLines.push(""); | ||
| continue; | ||
| } | ||
| const segments = Array.isArray(line) ? line : [line]; | ||
| let prevGeneratedColumn = 0; | ||
| const encodedSegments = []; | ||
| for (const segment of segments) { | ||
| const generatedColumn = segment.generatedColumn || 0; | ||
| let encoded = encodeVLQ(generatedColumn - prevGeneratedColumn); | ||
| prevGeneratedColumn = generatedColumn; | ||
| if (segment.sourceIndex !== undefined) { | ||
| const originalLine = /** @type {number} */ (segment.originalLine); | ||
| const originalColumn = /** @type {number} */ (segment.originalColumn); | ||
| encoded += encodeVLQ(segment.sourceIndex - prevSourceIndex); | ||
| encoded += encodeVLQ(originalLine - prevOriginalLine); | ||
| encoded += encodeVLQ(originalColumn - prevOriginalColumn); | ||
| prevSourceIndex = segment.sourceIndex; | ||
| prevOriginalLine = originalLine; | ||
| prevOriginalColumn = originalColumn; | ||
| if (segment.nameIndex !== undefined) { | ||
| encoded += encodeVLQ(segment.nameIndex - prevNameIndex); | ||
| prevNameIndex = segment.nameIndex; | ||
| } | ||
| } | ||
| encodedSegments.push(encoded); | ||
| } | ||
| encodedLines.push(encodedSegments.join(",")); | ||
| } | ||
| return encodedLines.join(";"); | ||
| }; | ||
| module.exports.encodeMappings = encodeMappings; | ||
| module.exports.encodeVLQ = encodeVLQ; |
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| Author Tobias Koppers @sokra | ||
| */ | ||
| "use strict"; | ||
| /** @typedef {import("../Dependency").DependencyLocation} DependencyLocation */ | ||
| /** @typedef {import("../Dependency").SourcePosition} SourcePosition */ | ||
| /** | ||
| * Returns formatted position. | ||
| * @param {SourcePosition} pos position | ||
| * @returns {string} formatted position | ||
| */ | ||
| const formatPosition = (pos) => { | ||
| if (pos && typeof pos === "object") { | ||
| if ("line" in pos && "column" in pos) { | ||
| return `${pos.line}:${pos.column}`; | ||
| } else if ("line" in pos) { | ||
| return `${pos.line}:?`; | ||
| } | ||
| } | ||
| return ""; | ||
| }; | ||
| /** | ||
| * Returns formatted location. | ||
| * @param {DependencyLocation} loc location | ||
| * @returns {string} formatted location | ||
| */ | ||
| const formatLocation = (loc) => { | ||
| if (loc && typeof loc === "object") { | ||
| if ("start" in loc && loc.start && "end" in loc && loc.end) { | ||
| if ( | ||
| typeof loc.start === "object" && | ||
| typeof loc.start.line === "number" && | ||
| typeof loc.end === "object" && | ||
| typeof loc.end.line === "number" && | ||
| typeof loc.end.column === "number" && | ||
| loc.start.line === loc.end.line | ||
| ) { | ||
| return `${formatPosition(loc.start)}-${loc.end.column}`; | ||
| } else if ( | ||
| typeof loc.start === "object" && | ||
| typeof loc.start.line === "number" && | ||
| typeof loc.start.column !== "number" && | ||
| typeof loc.end === "object" && | ||
| typeof loc.end.line === "number" && | ||
| typeof loc.end.column !== "number" | ||
| ) { | ||
| return `${loc.start.line}-${loc.end.line}`; | ||
| } | ||
| return `${formatPosition(loc.start)}-${formatPosition(loc.end)}`; | ||
| } | ||
| if ("start" in loc && loc.start) { | ||
| return formatPosition(loc.start); | ||
| } | ||
| if ("name" in loc && "index" in loc) { | ||
| return `${loc.name}[${loc.index}]`; | ||
| } | ||
| if ("name" in loc) { | ||
| return loc.name; | ||
| } | ||
| } | ||
| return ""; | ||
| }; | ||
| module.exports = formatLocation; |
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| Author Sean Larkin @thelarkinn | ||
| */ | ||
| "use strict"; | ||
| /** | ||
| * Returns the formatted size. | ||
| * @param {number=} size the size in bytes | ||
| * @returns {string} the formatted size | ||
| */ | ||
| const formatSize = (size) => { | ||
| if (typeof size !== "number" || Number.isNaN(size) === true) { | ||
| return "unknown size"; | ||
| } | ||
| if (size <= 0) { | ||
| return "0 bytes"; | ||
| } | ||
| const abbreviations = ["bytes", "KiB", "MiB", "GiB"]; | ||
| const index = Math.floor(Math.log(size) / Math.log(1024)); | ||
| return `${Number((size / 1024 ** index).toPrecision(3))} ${abbreviations[index]}`; | ||
| }; | ||
| module.exports = formatSize; |
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| Author Alexander Akait @alexander-akait | ||
| */ | ||
| "use strict"; | ||
| class LocConverter { | ||
| /** | ||
| * Creates an instance of LocConverter. | ||
| * @param {string} input input | ||
| */ | ||
| constructor(input) { | ||
| this._input = input; | ||
| this.line = 1; | ||
| this.column = 0; | ||
| this.pos = 0; | ||
| } | ||
| /** | ||
| * Returns location converter. | ||
| * @param {number} pos position | ||
| * @returns {LocConverter} location converter | ||
| */ | ||
| get(pos) { | ||
| if (this.pos !== pos) { | ||
| if (this.pos < pos) { | ||
| const str = this._input.slice(this.pos, pos); | ||
| let i = str.lastIndexOf("\n"); | ||
| if (i === -1) { | ||
| this.column += str.length; | ||
| } else { | ||
| this.column = str.length - i - 1; | ||
| this.line++; | ||
| while (i > 0 && (i = str.lastIndexOf("\n", i - 1)) !== -1) { | ||
| this.line++; | ||
| } | ||
| } | ||
| } else { | ||
| let i = this._input.lastIndexOf("\n", this.pos); | ||
| while (i >= pos) { | ||
| this.line--; | ||
| i = i > 0 ? this._input.lastIndexOf("\n", i - 1) : -1; | ||
| } | ||
| this.column = i === -1 ? pos : pos - i - 1; | ||
| } | ||
| this.pos = pos; | ||
| } | ||
| return this; | ||
| } | ||
| } | ||
| module.exports = LocConverter; |
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| */ | ||
| "use strict"; | ||
| /** | ||
| * Topologically sort `nodes` using Kahn's algorithm with source-order | ||
| * tie-breaking. Nodes that participate in a cycle remain unvisited — | ||
| * `visit` is never called for them — so the caller can naturally keep | ||
| * them in their original position by treating "no visit" as "keep | ||
| * source order". | ||
| * | ||
| * Precondition: every node appearing in `graph` (as a key OR inside any | ||
| * successor set) must also appear in `nodes`. The caller owns this | ||
| * invariant; the function does not validate it. | ||
| * | ||
| * Complexity: O(V·(V + E)). Each outer iteration scans the ready set | ||
| * linearly to find the smallest source-index node. CSS composes graphs | ||
| * are small (a handful of files per module) so this is fine; if a much | ||
| * larger graph ever needs sorting here, swap in a min-heap. | ||
| * @template T | ||
| * @param {Map<T, Set<T>>} graph adjacency list (`a -> b` means `a` must come before `b`) | ||
| * @param {T[]} nodes nodes in source first-appearance order | ||
| * @param {(node: T, index: number) => void} visit called once per non-cyclic node in topological order | ||
| * @returns {void} | ||
| */ | ||
| module.exports = (graph, nodes, visit) => { | ||
| /** @type {Map<T, number>} */ | ||
| const inDegree = new Map(); | ||
| /** @type {Map<T, number>} */ | ||
| const sourceIndex = new Map(); | ||
| for (let i = 0; i < nodes.length; i++) { | ||
| inDegree.set(nodes[i], 0); | ||
| sourceIndex.set(nodes[i], i); | ||
| } | ||
| for (const successors of graph.values()) { | ||
| for (const to of successors) { | ||
| inDegree.set(to, /** @type {number} */ (inDegree.get(to)) + 1); | ||
| } | ||
| } | ||
| const ready = nodes.filter((n) => inDegree.get(n) === 0); | ||
| let index = 0; | ||
| while (ready.length > 0) { | ||
| // Smallest-source-index wins ties. Linear scan + swap-with-last | ||
| // + pop avoids re-sorting the ready set on every iteration. | ||
| let minIdx = 0; | ||
| for (let i = 1; i < ready.length; i++) { | ||
| if ( | ||
| /** @type {number} */ (sourceIndex.get(ready[i])) < | ||
| /** @type {number} */ (sourceIndex.get(ready[minIdx])) | ||
| ) { | ||
| minIdx = i; | ||
| } | ||
| } | ||
| const node = ready[minIdx]; | ||
| ready[minIdx] = ready[ready.length - 1]; | ||
| ready.pop(); | ||
| visit(node, index++); | ||
| const successors = graph.get(node); | ||
| if (!successors) continue; | ||
| for (const to of successors) { | ||
| const newDeg = /** @type {number} */ (inDegree.get(to)) - 1; | ||
| inDegree.set(to, newDeg); | ||
| if (newDeg === 0) ready.push(to); | ||
| } | ||
| } | ||
| }; |
| /* | ||
| * This file was automatically generated. | ||
| * DO NOT MODIFY BY HAND. | ||
| * Run `yarn fix:special` to update | ||
| */ | ||
| declare const check: (options: any) => boolean; | ||
| export = check; |
| /* | ||
| * This file was automatically generated. | ||
| * DO NOT MODIFY BY HAND. | ||
| * Run `yarn fix:special` to update | ||
| */ | ||
| "use strict";module.exports=t,module.exports.default=t;const e={type:"object",additionalProperties:!1,properties:{animation:{$ref:"#/definitions/CssParserAnimation"},container:{$ref:"#/definitions/CssParserContainer"},customIdents:{$ref:"#/definitions/CssParserCustomIdents"},dashedIdents:{$ref:"#/definitions/CssParserDashedIdents"},exportType:{$ref:"#/definitions/CssParserExportType"},function:{$ref:"#/definitions/CssParserFunction"},grid:{$ref:"#/definitions/CssParserGrid"},import:{$ref:"#/definitions/CssParserImport"},namedExports:{$ref:"#/definitions/CssParserNamedExports"},pure:{$ref:"#/definitions/CssParserPure"},url:{$ref:"#/definitions/CssParserUrl"}}},r=Object.prototype.hasOwnProperty;function o(t,{instancePath:s="",parentData:n,parentDataProperty:i,rootData:a=t}={}){if(!t||"object"!=typeof t||Array.isArray(t))return o.errors=[{params:{type:"object"}}],!1;{const s=0;for(const s in t)if(!r.call(e.properties,s))return o.errors=[{params:{additionalProperty:s}}],!1;if(0===s){if(void 0!==t.animation){const e=0;if("boolean"!=typeof t.animation)return o.errors=[{params:{type:"boolean"}}],!1;var f=0===e}else f=!0;if(f){if(void 0!==t.container){const e=0;if("boolean"!=typeof t.container)return o.errors=[{params:{type:"boolean"}}],!1;f=0===e}else f=!0;if(f){if(void 0!==t.customIdents){const e=0;if("boolean"!=typeof t.customIdents)return o.errors=[{params:{type:"boolean"}}],!1;f=0===e}else f=!0;if(f){if(void 0!==t.dashedIdents){const e=0;if("boolean"!=typeof t.dashedIdents)return o.errors=[{params:{type:"boolean"}}],!1;f=0===e}else f=!0;if(f){if(void 0!==t.exportType){let e=t.exportType;const r=0;if("link"!==e&&"text"!==e&&"css-style-sheet"!==e&&"style"!==e)return o.errors=[{params:{}}],!1;f=0===r}else f=!0;if(f){if(void 0!==t.function){const e=0;if("boolean"!=typeof t.function)return o.errors=[{params:{type:"boolean"}}],!1;f=0===e}else f=!0;if(f){if(void 0!==t.grid){const e=0;if("boolean"!=typeof t.grid)return o.errors=[{params:{type:"boolean"}}],!1;f=0===e}else f=!0;if(f){if(void 0!==t.import){const e=0;if("boolean"!=typeof t.import)return o.errors=[{params:{type:"boolean"}}],!1;f=0===e}else f=!0;if(f){if(void 0!==t.namedExports){const e=0;if("boolean"!=typeof t.namedExports)return o.errors=[{params:{type:"boolean"}}],!1;f=0===e}else f=!0;if(f){if(void 0!==t.pure){const e=0;if("boolean"!=typeof t.pure)return o.errors=[{params:{type:"boolean"}}],!1;f=0===e}else f=!0;if(f)if(void 0!==t.url){const e=0;if("boolean"!=typeof t.url)return o.errors=[{params:{type:"boolean"}}],!1;f=0===e}else f=!0}}}}}}}}}}}return o.errors=null,!0}function t(e,{instancePath:r="",parentData:s,parentDataProperty:n,rootData:i=e}={}){let a=null,f=0;return o(e,{instancePath:r,parentData:s,parentDataProperty:n,rootData:i})||(a=null===a?o.errors:a.concat(o.errors),f=a.length),t.errors=a,0===f} |
| { | ||
| "$ref": "../../WebpackOptions.json#/definitions/CssAutoOrModuleParserOptions" | ||
| } |
| /* | ||
| * This file was automatically generated. | ||
| * DO NOT MODIFY BY HAND. | ||
| * Run `yarn fix:special` to update | ||
| */ | ||
| declare const check: (options: import("../../../declarations/plugins/dll/DllPlugin").DllPluginOptions) => boolean; | ||
| export = check; |
| /* | ||
| * This file was automatically generated. | ||
| * DO NOT MODIFY BY HAND. | ||
| * Run `yarn fix:special` to update | ||
| */ | ||
| "use strict";function r(e,{instancePath:t="",parentData:o,parentDataProperty:n,rootData:a=e}={}){if(!e||"object"!=typeof e||Array.isArray(e))return r.errors=[{params:{type:"object"}}],!1;{let t;if(void 0===e.path&&(t="path"))return r.errors=[{params:{missingProperty:t}}],!1;{const t=0;for(const t in e)if("context"!==t&&"entryOnly"!==t&&"format"!==t&&"name"!==t&&"path"!==t&&"type"!==t)return r.errors=[{params:{additionalProperty:t}}],!1;if(0===t){if(void 0!==e.context){let t=e.context;const o=0;if(0===o){if("string"!=typeof t)return r.errors=[{params:{type:"string"}}],!1;if(t.length<1)return r.errors=[{params:{}}],!1}var s=0===o}else s=!0;if(s){if(void 0!==e.entryOnly){const t=0;if("boolean"!=typeof e.entryOnly)return r.errors=[{params:{type:"boolean"}}],!1;s=0===t}else s=!0;if(s){if(void 0!==e.format){const t=0;if("boolean"!=typeof e.format)return r.errors=[{params:{type:"boolean"}}],!1;s=0===t}else s=!0;if(s){if(void 0!==e.name){let t=e.name;const o=0;if(0===o){if("string"!=typeof t)return r.errors=[{params:{type:"string"}}],!1;if(t.length<1)return r.errors=[{params:{}}],!1}s=0===o}else s=!0;if(s){if(void 0!==e.path){let t=e.path;const o=0;if(0===o){if("string"!=typeof t)return r.errors=[{params:{type:"string"}}],!1;if(t.length<1)return r.errors=[{params:{}}],!1}s=0===o}else s=!0;if(s)if(void 0!==e.type){let t=e.type;const o=0;if(0===o){if("string"!=typeof t)return r.errors=[{params:{type:"string"}}],!1;if(t.length<1)return r.errors=[{params:{}}],!1}s=0===o}else s=!0}}}}}}}return r.errors=null,!0}module.exports=r,module.exports.default=r; |
| { | ||
| "title": "DllPluginOptions", | ||
| "type": "object", | ||
| "additionalProperties": false, | ||
| "properties": { | ||
| "context": { | ||
| "description": "Context of requests in the manifest file (defaults to the webpack context).", | ||
| "type": "string", | ||
| "minLength": 1 | ||
| }, | ||
| "entryOnly": { | ||
| "description": "If true, only entry points will be exposed (default: true).", | ||
| "type": "boolean" | ||
| }, | ||
| "format": { | ||
| "description": "If true, manifest json file (output) will be formatted.", | ||
| "type": "boolean" | ||
| }, | ||
| "name": { | ||
| "description": "Name of the exposed dll function (external name, use value of 'output.library').", | ||
| "type": "string", | ||
| "minLength": 1 | ||
| }, | ||
| "path": { | ||
| "description": "Absolute path to the manifest json file (output).", | ||
| "type": "string", | ||
| "minLength": 1 | ||
| }, | ||
| "type": { | ||
| "description": "Type of the dll bundle (external type, use value of 'output.libraryTarget').", | ||
| "type": "string", | ||
| "minLength": 1 | ||
| } | ||
| }, | ||
| "required": ["path"] | ||
| } |
| /* | ||
| * This file was automatically generated. | ||
| * DO NOT MODIFY BY HAND. | ||
| * Run `yarn fix:special` to update | ||
| */ | ||
| declare const check: (options: import("../../../declarations/plugins/dll/DllReferencePlugin").DllReferencePluginOptions) => boolean; | ||
| export = check; |
| /* | ||
| * This file was automatically generated. | ||
| * DO NOT MODIFY BY HAND. | ||
| * Run `yarn fix:special` to update | ||
| */ | ||
| const s=/^(?:[A-Za-z]:[\\/]|\\\\|\/)/;function t(s,{instancePath:e="",parentData:n,parentDataProperty:l,rootData:o=s}={}){let r=null,i=0;if(0===i){if(!s||"object"!=typeof s||Array.isArray(s))return t.errors=[{params:{type:"object"}}],!1;{let e;if(void 0===s.content&&(e="content"))return t.errors=[{params:{missingProperty:e}}],!1;{const e=i;for(const e in s)if("content"!==e&&"name"!==e&&"type"!==e)return t.errors=[{params:{additionalProperty:e}}],!1;if(e===i){if(void 0!==s.content){let e=s.content;const n=i,l=i;let o=!1,f=null;const m=i;if(i==i)if(e&&"object"==typeof e&&!Array.isArray(e))if(Object.keys(e).length<1){const s={params:{limit:1}};null===r?r=[s]:r.push(s),i++}else for(const s in e){let t=e[s];const n=i;if(i===n)if(t&&"object"==typeof t&&!Array.isArray(t)){let s;if(void 0===t.id&&(s="id")){const t={params:{missingProperty:s}};null===r?r=[t]:r.push(t),i++}else{const s=i;for(const s in t)if("buildMeta"!==s&&"exports"!==s&&"id"!==s){const t={params:{additionalProperty:s}};null===r?r=[t]:r.push(t),i++;break}if(s===i){if(void 0!==t.buildMeta){let s=t.buildMeta;const e=i;if(!s||"object"!=typeof s||Array.isArray(s)){const s={params:{type:"object"}};null===r?r=[s]:r.push(s),i++}var a=e===i}else a=!0;if(a){if(void 0!==t.exports){let s=t.exports;const e=i,n=i;let l=!1;const o=i;if(i===o)if(Array.isArray(s)){const t=s.length;for(let e=0;e<t;e++){let t=s[e];const n=i;if(i===n)if("string"==typeof t){if(t.length<1){const s={params:{}};null===r?r=[s]:r.push(s),i++}}else{const s={params:{type:"string"}};null===r?r=[s]:r.push(s),i++}if(n!==i)break}}else{const s={params:{type:"array"}};null===r?r=[s]:r.push(s),i++}var p=o===i;if(l=l||p,!l){const t=i;if(!0!==s){const s={params:{}};null===r?r=[s]:r.push(s),i++}p=t===i,l=l||p}if(l)i=n,null!==r&&(n?r.length=n:r=null);else{const s={params:{}};null===r?r=[s]:r.push(s),i++}a=e===i}else a=!0;if(a)if(void 0!==t.id){let s=t.id;const e=i,n=i;let l=!1;const o=i;if("number"!=typeof s){const s={params:{type:"number"}};null===r?r=[s]:r.push(s),i++}var u=o===i;if(l=l||u,!l){const t=i;if(i===t)if("string"==typeof s){if(s.length<1){const s={params:{}};null===r?r=[s]:r.push(s),i++}}else{const s={params:{type:"string"}};null===r?r=[s]:r.push(s),i++}u=t===i,l=l||u}if(l)i=n,null!==r&&(n?r.length=n:r=null);else{const s={params:{}};null===r?r=[s]:r.push(s),i++}a=e===i}else a=!0}}}}else{const s={params:{type:"object"}};null===r?r=[s]:r.push(s),i++}if(n!==i)break}else{const s={params:{type:"object"}};null===r?r=[s]:r.push(s),i++}if(m===i&&(o=!0,f=0),!o){const s={params:{passingSchemas:f}};return null===r?r=[s]:r.push(s),i++,t.errors=r,!1}i=l,null!==r&&(l?r.length=l:r=null);var c=n===i}else c=!0;if(c){if(void 0!==s.name){let e=s.name;const n=i;if(i===n){if("string"!=typeof e)return t.errors=[{params:{type:"string"}}],!1;if(e.length<1)return t.errors=[{params:{}}],!1}c=n===i}else c=!0;if(c)if(void 0!==s.type){let e=s.type;const n=i,l=i;let o=!1,a=null;const p=i;if("var"!==e&&"assign"!==e&&"this"!==e&&"window"!==e&&"global"!==e&&"commonjs"!==e&&"commonjs2"!==e&&"commonjs-module"!==e&&"amd"!==e&&"amd-require"!==e&&"umd"!==e&&"umd2"!==e&&"jsonp"!==e&&"system"!==e){const s={params:{}};null===r?r=[s]:r.push(s),i++}if(p===i&&(o=!0,a=0),!o){const s={params:{passingSchemas:a}};return null===r?r=[s]:r.push(s),i++,t.errors=r,!1}i=l,null!==r&&(l?r.length=l:r=null),c=n===i}else c=!0}}}}}return t.errors=r,0===i}function e(n,{instancePath:l="",parentData:o,parentDataProperty:r,rootData:i=n}={}){let a=null,p=0;const u=p;let c=!1;const f=p;if(p===f)if(n&&"object"==typeof n&&!Array.isArray(n)){let e;if(void 0===n.manifest&&(e="manifest")){const s={params:{missingProperty:e}};null===a?a=[s]:a.push(s),p++}else{const e=p;for(const s in n)if("context"!==s&&"extensions"!==s&&"manifest"!==s&&"name"!==s&&"scope"!==s&&"sourceType"!==s&&"type"!==s){const t={params:{additionalProperty:s}};null===a?a=[t]:a.push(t),p++;break}if(e===p){if(void 0!==n.context){let t=n.context;const e=p;if(p===e)if("string"==typeof t){if(t.includes("!")||!0!==s.test(t)){const s={params:{}};null===a?a=[s]:a.push(s),p++}}else{const s={params:{type:"string"}};null===a?a=[s]:a.push(s),p++}var m=e===p}else m=!0;if(m){if(void 0!==n.extensions){let s=n.extensions;const t=p;if(p===t)if(Array.isArray(s)){const t=s.length;for(let e=0;e<t;e++){const t=p;if("string"!=typeof s[e]){const s={params:{type:"string"}};null===a?a=[s]:a.push(s),p++}if(t!==p)break}}else{const s={params:{type:"array"}};null===a?a=[s]:a.push(s),p++}m=t===p}else m=!0;if(m){if(void 0!==n.manifest){let e=n.manifest;const o=p,r=p;let u=!1;const c=p;if(p===c)if("string"==typeof e){if(e.includes("!")||!0!==s.test(e)){const s={params:{}};null===a?a=[s]:a.push(s),p++}}else{const s={params:{type:"string"}};null===a?a=[s]:a.push(s),p++}var y=c===p;if(u=u||y,!u){const s=p;t(e,{instancePath:l+"/manifest",parentData:n,parentDataProperty:"manifest",rootData:i})||(a=null===a?t.errors:a.concat(t.errors),p=a.length),y=s===p,u=u||y}if(u)p=r,null!==a&&(r?a.length=r:a=null);else{const s={params:{}};null===a?a=[s]:a.push(s),p++}m=o===p}else m=!0;if(m){if(void 0!==n.name){let s=n.name;const t=p;if(p===t)if("string"==typeof s){if(s.length<1){const s={params:{}};null===a?a=[s]:a.push(s),p++}}else{const s={params:{type:"string"}};null===a?a=[s]:a.push(s),p++}m=t===p}else m=!0;if(m){if(void 0!==n.scope){let s=n.scope;const t=p;if(p===t)if("string"==typeof s){if(s.length<1){const s={params:{}};null===a?a=[s]:a.push(s),p++}}else{const s={params:{type:"string"}};null===a?a=[s]:a.push(s),p++}m=t===p}else m=!0;if(m){if(void 0!==n.sourceType){let s=n.sourceType;const t=p,e=p;let l=!1,o=null;const r=p;if("var"!==s&&"assign"!==s&&"this"!==s&&"window"!==s&&"global"!==s&&"commonjs"!==s&&"commonjs2"!==s&&"commonjs-module"!==s&&"amd"!==s&&"amd-require"!==s&&"umd"!==s&&"umd2"!==s&&"jsonp"!==s&&"system"!==s){const s={params:{}};null===a?a=[s]:a.push(s),p++}if(r===p&&(l=!0,o=0),l)p=e,null!==a&&(e?a.length=e:a=null);else{const s={params:{passingSchemas:o}};null===a?a=[s]:a.push(s),p++}m=t===p}else m=!0;if(m)if(void 0!==n.type){let s=n.type;const t=p;if("require"!==s&&"object"!==s){const s={params:{}};null===a?a=[s]:a.push(s),p++}m=t===p}else m=!0}}}}}}}}else{const s={params:{type:"object"}};null===a?a=[s]:a.push(s),p++}var h=f===p;if(c=c||h,!c){const t=p;if(p===t)if(n&&"object"==typeof n&&!Array.isArray(n)){let t;if(void 0===n.content&&(t="content")||void 0===n.name&&(t="name")){const s={params:{missingProperty:t}};null===a?a=[s]:a.push(s),p++}else{const t=p;for(const s in n)if("content"!==s&&"context"!==s&&"extensions"!==s&&"name"!==s&&"scope"!==s&&"sourceType"!==s&&"type"!==s){const t={params:{additionalProperty:s}};null===a?a=[t]:a.push(t),p++;break}if(t===p){if(void 0!==n.content){let s=n.content;const t=p,e=p;let l=!1,o=null;const r=p;if(p==p)if(s&&"object"==typeof s&&!Array.isArray(s))if(Object.keys(s).length<1){const s={params:{limit:1}};null===a?a=[s]:a.push(s),p++}else for(const t in s){let e=s[t];const n=p;if(p===n)if(e&&"object"==typeof e&&!Array.isArray(e)){let s;if(void 0===e.id&&(s="id")){const t={params:{missingProperty:s}};null===a?a=[t]:a.push(t),p++}else{const s=p;for(const s in e)if("buildMeta"!==s&&"exports"!==s&&"id"!==s){const t={params:{additionalProperty:s}};null===a?a=[t]:a.push(t),p++;break}if(s===p){if(void 0!==e.buildMeta){let s=e.buildMeta;const t=p;if(!s||"object"!=typeof s||Array.isArray(s)){const s={params:{type:"object"}};null===a?a=[s]:a.push(s),p++}var d=t===p}else d=!0;if(d){if(void 0!==e.exports){let s=e.exports;const t=p,n=p;let l=!1;const o=p;if(p===o)if(Array.isArray(s)){const t=s.length;for(let e=0;e<t;e++){let t=s[e];const n=p;if(p===n)if("string"==typeof t){if(t.length<1){const s={params:{}};null===a?a=[s]:a.push(s),p++}}else{const s={params:{type:"string"}};null===a?a=[s]:a.push(s),p++}if(n!==p)break}}else{const s={params:{type:"array"}};null===a?a=[s]:a.push(s),p++}var g=o===p;if(l=l||g,!l){const t=p;if(!0!==s){const s={params:{}};null===a?a=[s]:a.push(s),p++}g=t===p,l=l||g}if(l)p=n,null!==a&&(n?a.length=n:a=null);else{const s={params:{}};null===a?a=[s]:a.push(s),p++}d=t===p}else d=!0;if(d)if(void 0!==e.id){let s=e.id;const t=p,n=p;let l=!1;const o=p;if("number"!=typeof s){const s={params:{type:"number"}};null===a?a=[s]:a.push(s),p++}var b=o===p;if(l=l||b,!l){const t=p;if(p===t)if("string"==typeof s){if(s.length<1){const s={params:{}};null===a?a=[s]:a.push(s),p++}}else{const s={params:{type:"string"}};null===a?a=[s]:a.push(s),p++}b=t===p,l=l||b}if(l)p=n,null!==a&&(n?a.length=n:a=null);else{const s={params:{}};null===a?a=[s]:a.push(s),p++}d=t===p}else d=!0}}}}else{const s={params:{type:"object"}};null===a?a=[s]:a.push(s),p++}if(n!==p)break}else{const s={params:{type:"object"}};null===a?a=[s]:a.push(s),p++}if(r===p&&(l=!0,o=0),l)p=e,null!==a&&(e?a.length=e:a=null);else{const s={params:{passingSchemas:o}};null===a?a=[s]:a.push(s),p++}var v=t===p}else v=!0;if(v){if(void 0!==n.context){let t=n.context;const e=p;if(p===e)if("string"==typeof t){if(t.includes("!")||!0!==s.test(t)){const s={params:{}};null===a?a=[s]:a.push(s),p++}}else{const s={params:{type:"string"}};null===a?a=[s]:a.push(s),p++}v=e===p}else v=!0;if(v){if(void 0!==n.extensions){let s=n.extensions;const t=p;if(p===t)if(Array.isArray(s)){const t=s.length;for(let e=0;e<t;e++){const t=p;if("string"!=typeof s[e]){const s={params:{type:"string"}};null===a?a=[s]:a.push(s),p++}if(t!==p)break}}else{const s={params:{type:"array"}};null===a?a=[s]:a.push(s),p++}v=t===p}else v=!0;if(v){if(void 0!==n.name){let s=n.name;const t=p;if(p===t)if("string"==typeof s){if(s.length<1){const s={params:{}};null===a?a=[s]:a.push(s),p++}}else{const s={params:{type:"string"}};null===a?a=[s]:a.push(s),p++}v=t===p}else v=!0;if(v){if(void 0!==n.scope){let s=n.scope;const t=p;if(p===t)if("string"==typeof s){if(s.length<1){const s={params:{}};null===a?a=[s]:a.push(s),p++}}else{const s={params:{type:"string"}};null===a?a=[s]:a.push(s),p++}v=t===p}else v=!0;if(v){if(void 0!==n.sourceType){let s=n.sourceType;const t=p,e=p;let l=!1,o=null;const r=p;if("var"!==s&&"assign"!==s&&"this"!==s&&"window"!==s&&"global"!==s&&"commonjs"!==s&&"commonjs2"!==s&&"commonjs-module"!==s&&"amd"!==s&&"amd-require"!==s&&"umd"!==s&&"umd2"!==s&&"jsonp"!==s&&"system"!==s){const s={params:{}};null===a?a=[s]:a.push(s),p++}if(r===p&&(l=!0,o=0),l)p=e,null!==a&&(e?a.length=e:a=null);else{const s={params:{passingSchemas:o}};null===a?a=[s]:a.push(s),p++}v=t===p}else v=!0;if(v)if(void 0!==n.type){let s=n.type;const t=p;if("require"!==s&&"object"!==s){const s={params:{}};null===a?a=[s]:a.push(s),p++}v=t===p}else v=!0}}}}}}}}else{const s={params:{type:"object"}};null===a?a=[s]:a.push(s),p++}h=t===p,c=c||h}if(!c){const s={params:{}};return null===a?a=[s]:a.push(s),p++,e.errors=a,!1}return p=u,null!==a&&(u?a.length=u:a=null),e.errors=a,0===p}module.exports=e,module.exports.default=e; |
| { | ||
| "definitions": { | ||
| "DllReferencePluginOptionsContent": { | ||
| "description": "The mappings from request to module info.", | ||
| "type": "object", | ||
| "additionalProperties": { | ||
| "description": "Module info.", | ||
| "type": "object", | ||
| "additionalProperties": false, | ||
| "properties": { | ||
| "buildMeta": { | ||
| "description": "Meta information about the module.", | ||
| "type": "object" | ||
| }, | ||
| "exports": { | ||
| "description": "Information about the provided exports of the module.", | ||
| "anyOf": [ | ||
| { | ||
| "description": "List of provided exports of the module.", | ||
| "type": "array", | ||
| "items": { | ||
| "description": "Name of the export.", | ||
| "type": "string", | ||
| "minLength": 1 | ||
| } | ||
| }, | ||
| { | ||
| "description": "Exports unknown/dynamic.", | ||
| "enum": [true] | ||
| } | ||
| ] | ||
| }, | ||
| "id": { | ||
| "description": "Module ID.", | ||
| "anyOf": [ | ||
| { | ||
| "type": "number" | ||
| }, | ||
| { | ||
| "type": "string", | ||
| "minLength": 1 | ||
| } | ||
| ] | ||
| } | ||
| }, | ||
| "required": ["id"] | ||
| }, | ||
| "minProperties": 1 | ||
| }, | ||
| "DllReferencePluginOptionsManifest": { | ||
| "description": "An object containing content, name and type.", | ||
| "type": "object", | ||
| "additionalProperties": false, | ||
| "properties": { | ||
| "content": { | ||
| "description": "The mappings from request to module info.", | ||
| "oneOf": [ | ||
| { | ||
| "$ref": "#/definitions/DllReferencePluginOptionsContent" | ||
| } | ||
| ] | ||
| }, | ||
| "name": { | ||
| "description": "The name where the dll is exposed (external name).", | ||
| "type": "string", | ||
| "minLength": 1 | ||
| }, | ||
| "type": { | ||
| "description": "The type how the dll is exposed (external type).", | ||
| "oneOf": [ | ||
| { | ||
| "$ref": "#/definitions/DllReferencePluginOptionsSourceType" | ||
| } | ||
| ] | ||
| } | ||
| }, | ||
| "required": ["content"] | ||
| }, | ||
| "DllReferencePluginOptionsSourceType": { | ||
| "description": "The type how the dll is exposed (external type).", | ||
| "enum": [ | ||
| "var", | ||
| "assign", | ||
| "this", | ||
| "window", | ||
| "global", | ||
| "commonjs", | ||
| "commonjs2", | ||
| "commonjs-module", | ||
| "amd", | ||
| "amd-require", | ||
| "umd", | ||
| "umd2", | ||
| "jsonp", | ||
| "system" | ||
| ] | ||
| } | ||
| }, | ||
| "title": "DllReferencePluginOptions", | ||
| "anyOf": [ | ||
| { | ||
| "type": "object", | ||
| "additionalProperties": false, | ||
| "properties": { | ||
| "context": { | ||
| "description": "Context of requests in the manifest (or content property) as absolute path.", | ||
| "type": "string", | ||
| "absolutePath": true | ||
| }, | ||
| "extensions": { | ||
| "description": "Extensions used to resolve modules in the dll bundle (only used when using 'scope').", | ||
| "type": "array", | ||
| "items": { | ||
| "description": "An extension.", | ||
| "type": "string" | ||
| } | ||
| }, | ||
| "manifest": { | ||
| "description": "An object containing content and name or a string to the absolute path of the JSON manifest to be loaded upon compilation.", | ||
| "anyOf": [ | ||
| { | ||
| "type": "string", | ||
| "absolutePath": true | ||
| }, | ||
| { | ||
| "$ref": "#/definitions/DllReferencePluginOptionsManifest" | ||
| } | ||
| ] | ||
| }, | ||
| "name": { | ||
| "description": "The name where the dll is exposed (external name, defaults to manifest.name).", | ||
| "type": "string", | ||
| "minLength": 1 | ||
| }, | ||
| "scope": { | ||
| "description": "Prefix which is used for accessing the content of the dll.", | ||
| "type": "string", | ||
| "minLength": 1 | ||
| }, | ||
| "sourceType": { | ||
| "description": "How the dll is exposed (libraryTarget, defaults to manifest.type).", | ||
| "oneOf": [ | ||
| { | ||
| "$ref": "#/definitions/DllReferencePluginOptionsSourceType" | ||
| } | ||
| ] | ||
| }, | ||
| "type": { | ||
| "description": "The way how the export of the dll bundle is used.", | ||
| "enum": ["require", "object"] | ||
| } | ||
| }, | ||
| "required": ["manifest"] | ||
| }, | ||
| { | ||
| "type": "object", | ||
| "additionalProperties": false, | ||
| "properties": { | ||
| "content": { | ||
| "description": "The mappings from request to module info.", | ||
| "oneOf": [ | ||
| { | ||
| "$ref": "#/definitions/DllReferencePluginOptionsContent" | ||
| } | ||
| ] | ||
| }, | ||
| "context": { | ||
| "description": "Context of requests in the manifest (or content property) as absolute path.", | ||
| "type": "string", | ||
| "absolutePath": true | ||
| }, | ||
| "extensions": { | ||
| "description": "Extensions used to resolve modules in the dll bundle (only used when using 'scope').", | ||
| "type": "array", | ||
| "items": { | ||
| "description": "An extension.", | ||
| "type": "string" | ||
| } | ||
| }, | ||
| "name": { | ||
| "description": "The name where the dll is exposed (external name).", | ||
| "type": "string", | ||
| "minLength": 1 | ||
| }, | ||
| "scope": { | ||
| "description": "Prefix which is used for accessing the content of the dll.", | ||
| "type": "string", | ||
| "minLength": 1 | ||
| }, | ||
| "sourceType": { | ||
| "description": "How the dll is exposed (libraryTarget).", | ||
| "oneOf": [ | ||
| { | ||
| "$ref": "#/definitions/DllReferencePluginOptionsSourceType" | ||
| } | ||
| ] | ||
| }, | ||
| "type": { | ||
| "description": "The way how the export of the dll bundle is used.", | ||
| "enum": ["require", "object"] | ||
| } | ||
| }, | ||
| "required": ["content", "name"] | ||
| } | ||
| ] | ||
| } |
| /* | ||
| * This file was automatically generated. | ||
| * DO NOT MODIFY BY HAND. | ||
| * Run `yarn fix:special` to update | ||
| */ | ||
| declare const check: (options: any) => boolean; | ||
| export = check; |
| /* | ||
| * This file was automatically generated. | ||
| * DO NOT MODIFY BY HAND. | ||
| * Run `yarn fix:special` to update | ||
| */ | ||
| "use strict";function r(t,{instancePath:e="",parentData:a,parentDataProperty:o,rootData:n=t}={}){if(!t||"object"!=typeof t||Array.isArray(t))return r.errors=[{params:{type:"object"}}],!1;{const e=0;for(const e in t)if("extract"!==e)return r.errors=[{params:{additionalProperty:e}}],!1;if(0===e&&void 0!==t.extract&&"boolean"!=typeof t.extract)return r.errors=[{params:{type:"boolean"}}],!1}return r.errors=null,!0}module.exports=r,module.exports.default=r; |
| { | ||
| "$ref": "../WebpackOptions.json#/definitions/HtmlGeneratorOptions" | ||
| } |
+1
-1
@@ -17,6 +17,6 @@ /* | ||
| const RuntimeGlobals = require("./RuntimeGlobals"); | ||
| const WebpackError = require("./WebpackError"); | ||
| const ConstDependency = require("./dependencies/ConstDependency"); | ||
| const ModuleInitFragmentDependency = require("./dependencies/ModuleInitFragmentDependency"); | ||
| const RuntimeRequirementsDependency = require("./dependencies/RuntimeRequirementsDependency"); | ||
| const WebpackError = require("./errors/WebpackError"); | ||
| const BasicEvaluatedExpression = require("./javascript/BasicEvaluatedExpression"); | ||
@@ -23,0 +23,0 @@ const JavascriptModulesPlugin = require("./javascript/JavascriptModulesPlugin"); |
@@ -15,2 +15,3 @@ /* | ||
| CSS_URL_TYPES, | ||
| HTML_TYPE, | ||
| JAVASCRIPT_AND_CSS_URL_TYPES, | ||
@@ -150,5 +151,8 @@ JAVASCRIPT_TYPE, | ||
| if (sourceTypes.size > 0) { | ||
| if (sourceTypes.has(JAVASCRIPT_TYPE) && sourceTypes.has(CSS_TYPE)) { | ||
| if ( | ||
| sourceTypes.has(JAVASCRIPT_TYPE) && | ||
| (sourceTypes.has(CSS_TYPE) || sourceTypes.has(HTML_TYPE)) | ||
| ) { | ||
| return JAVASCRIPT_AND_CSS_URL_TYPES; | ||
| } else if (sourceTypes.has(CSS_TYPE)) { | ||
| } else if (sourceTypes.has(CSS_TYPE) || sourceTypes.has(HTML_TYPE)) { | ||
| return CSS_URL_TYPES; | ||
@@ -155,0 +159,0 @@ } |
@@ -20,2 +20,3 @@ /* | ||
| CSS_URL_TYPES, | ||
| HTML_TYPE, | ||
| JAVASCRIPT_AND_CSS_URL_TYPES, | ||
@@ -33,2 +34,3 @@ JAVASCRIPT_TYPE, | ||
| const nonNumericOnlyHash = require("../util/nonNumericOnlyHash"); | ||
| const { updateHashFromSource } = require("../util/source"); | ||
@@ -264,3 +266,3 @@ const getMimeTypes = memoize(() => require("../util/mimeTypes")); | ||
| if (source) { | ||
| hash.update(source.buffer()); | ||
| updateHashFromSource(hash, source); | ||
| } | ||
@@ -404,3 +406,9 @@ | ||
| : compilation.getAssetPath(compilation.outputOptions.publicPath, { | ||
| hash: compilation.hash | ||
| hash: | ||
| compilation.hash || | ||
| `${CssUrlDependency.PUBLIC_PATH_FULL_HASH}0__`, | ||
| hashWithLength: (length) => | ||
| compilation.hash | ||
| ? compilation.hash.slice(0, length) | ||
| : `${CssUrlDependency.PUBLIC_PATH_FULL_HASH}${length}__` | ||
| }); | ||
@@ -574,3 +582,3 @@ | ||
| if (data) { | ||
| data.set("url", { [type]: content, ...data.get("url") }); | ||
| data.set("url", { ...data.get("url"), [type]: content }); | ||
| } | ||
@@ -614,3 +622,3 @@ } else { | ||
| if (data && (type === JAVASCRIPT_TYPE || type === CSS_URL_TYPE)) { | ||
| data.set("url", { [type]: assetPath, ...data.get("url") }); | ||
| data.set("url", { ...data.get("url"), [type]: assetPath }); | ||
| } | ||
@@ -707,5 +715,8 @@ | ||
| if (sourceTypes.size > 0) { | ||
| if (sourceTypes.has(JAVASCRIPT_TYPE) && sourceTypes.has(CSS_TYPE)) { | ||
| if ( | ||
| sourceTypes.has(JAVASCRIPT_TYPE) && | ||
| (sourceTypes.has(CSS_TYPE) || sourceTypes.has(HTML_TYPE)) | ||
| ) { | ||
| return JAVASCRIPT_AND_CSS_URL_TYPES; | ||
| } else if (sourceTypes.has(CSS_TYPE)) { | ||
| } else if (sourceTypes.has(CSS_TYPE) || sourceTypes.has(HTML_TYPE)) { | ||
| return CSS_URL_TYPES; | ||
@@ -720,5 +731,8 @@ } | ||
| if (sourceTypes.size > 0) { | ||
| if (sourceTypes.has(JAVASCRIPT_TYPE) && sourceTypes.has(CSS_TYPE)) { | ||
| if ( | ||
| sourceTypes.has(JAVASCRIPT_TYPE) && | ||
| (sourceTypes.has(CSS_TYPE) || sourceTypes.has(HTML_TYPE)) | ||
| ) { | ||
| return ASSET_AND_JAVASCRIPT_AND_CSS_URL_TYPES; | ||
| } else if (sourceTypes.has(CSS_TYPE)) { | ||
| } else if (sourceTypes.has(CSS_TYPE) || sourceTypes.has(HTML_TYPE)) { | ||
| return ASSET_AND_CSS_URL_TYPES; | ||
@@ -725,0 +739,0 @@ } |
@@ -37,3 +37,5 @@ /* | ||
| const getSchema = (name) => { | ||
| const { definitions } = require("../../schemas/WebpackOptions.json"); | ||
| const { definitions } = | ||
| /** @type {EXPECTED_ANY} */ | ||
| (require("../../schemas/WebpackOptions.json")); | ||
@@ -40,0 +42,0 @@ return { |
@@ -15,2 +15,3 @@ /* | ||
| CSS_URL_TYPES, | ||
| HTML_TYPE, | ||
| JAVASCRIPT_AND_CSS_URL_TYPES, | ||
@@ -149,5 +150,8 @@ JAVASCRIPT_TYPE, | ||
| if (sourceTypes.size > 0) { | ||
| if (sourceTypes.has(JAVASCRIPT_TYPE) && sourceTypes.has(CSS_TYPE)) { | ||
| if ( | ||
| sourceTypes.has(JAVASCRIPT_TYPE) && | ||
| (sourceTypes.has(CSS_TYPE) || sourceTypes.has(HTML_TYPE)) | ||
| ) { | ||
| return JAVASCRIPT_AND_CSS_URL_TYPES; | ||
| } else if (sourceTypes.has(CSS_TYPE)) { | ||
| } else if (sourceTypes.has(CSS_TYPE) || sourceTypes.has(HTML_TYPE)) { | ||
| return CSS_URL_TYPES; | ||
@@ -154,0 +158,0 @@ } |
@@ -8,5 +8,4 @@ /* | ||
| const AsyncDependencyToInitialChunkError = require("./AsyncDependencyToInitialChunkError"); | ||
| const { connectChunkGroupParentAndChild } = require("./GraphHelpers"); | ||
| const ModuleGraphConnection = require("./ModuleGraphConnection"); | ||
| const AsyncDependencyToInitialChunkError = require("./errors/AsyncDependencyToInitialChunkError"); | ||
| const { getEntryRuntime, mergeRuntime } = require("./util/runtime"); | ||
@@ -1315,6 +1314,5 @@ | ||
| // 4. Connect chunk with parent | ||
| connectChunkGroupParentAndChild( | ||
| originChunkGroupInfo.chunkGroup, | ||
| chunkGroup | ||
| ); | ||
| if (originChunkGroupInfo.chunkGroup.addChild(chunkGroup)) { | ||
| chunkGroup.addParent(originChunkGroupInfo.chunkGroup); | ||
| } | ||
| } | ||
@@ -1321,0 +1319,0 @@ } |
+3
-6
@@ -12,6 +12,4 @@ /* | ||
| makeWebpackErrorCallback | ||
| } = require("./HookWebpackError"); | ||
| } = require("./errors/HookWebpackError"); | ||
| /** @typedef {import("./WebpackError")} WebpackError */ | ||
| /** | ||
@@ -25,7 +23,6 @@ * Cache validation token whose string representation identifies the build | ||
| /** | ||
| * Completion callback used by cache operations that either fail with a | ||
| * `WebpackError` or resolve with a typed result. | ||
| * Completion callback used by cache operations that either fail with a `Error` or resolve with a typed result. | ||
| * @template T | ||
| * @callback CallbackCache | ||
| * @param {WebpackError | null} err | ||
| * @param {Error | null} err | ||
| * @param {T=} result | ||
@@ -32,0 +29,0 @@ * @returns {void} |
@@ -10,5 +10,5 @@ /* | ||
| const ProgressPlugin = require("../ProgressPlugin"); | ||
| const { formatSize } = require("../SizeFormatHelpers"); | ||
| const SerializerMiddleware = require("../serialization/SerializerMiddleware"); | ||
| const LazySet = require("../util/LazySet"); | ||
| const formatSize = require("../util/formatSize"); | ||
| const makeSerializable = require("../util/makeSerializable"); | ||
@@ -109,3 +109,3 @@ const memoize = require("../util/memoize"); | ||
| const MAX_ITEMS_IN_FRESH_PACK = 50000; | ||
| const MAX_TIME_IN_FRESH_PACK = 1 * 60 * 1000; // 1 min | ||
| const MAX_TIME_IN_FRESH_PACK = 60 * 1000; // 1 min | ||
@@ -804,3 +804,3 @@ class PackItemInfo { | ||
| } else if (profile) { | ||
| /** @type {Map<EXPECTED_ANY, EXPECTED_ANY>} */ | ||
| /** @type {Content} */ | ||
| const map = new Map(); | ||
@@ -831,3 +831,3 @@ let key = read(); | ||
| } else { | ||
| /** @type {Map<EXPECTED_ANY, EXPECTED_ANY>} */ | ||
| /** @type {Content} */ | ||
| const map = new Map(); | ||
@@ -834,0 +834,0 @@ let key = read(); |
+3
-1
@@ -10,3 +10,5 @@ /* | ||
| const tty = require("tty"); | ||
| const webpackSchema = require("../schemas/WebpackOptions.json"); | ||
| const webpackSchema = | ||
| /** @type {EXPECTED_ANY} */ | ||
| (require("../schemas/WebpackOptions.json")); | ||
@@ -13,0 +15,0 @@ /** @typedef {import("json-schema").JSONSchema4} JSONSchema4 */ |
@@ -189,9 +189,10 @@ /* | ||
| ) { | ||
| const { name, declaration } = | ||
| /** @type {CompatibilitySettings} */ ( | ||
| parser.getTagData( | ||
| declarator.id.name, | ||
| nestedWebpackIdentifierTag | ||
| ) | ||
| ); | ||
| const tagData = /** @type {CompatibilitySettings | undefined} */ ( | ||
| parser.getTagData( | ||
| declarator.id.name, | ||
| nestedWebpackIdentifierTag | ||
| ) | ||
| ); | ||
| if (!tagData) return; | ||
| const { name, declaration } = tagData; | ||
| if (!declaration.updated) { | ||
@@ -198,0 +199,0 @@ const dep = new ConstDependency(name, declaration.range); |
+4
-13
@@ -20,3 +20,2 @@ /* | ||
| const Compilation = require("./Compilation"); | ||
| const ConcurrentCompilationError = require("./ConcurrentCompilationError"); | ||
| const ContextModuleFactory = require("./ContextModuleFactory"); | ||
@@ -29,3 +28,4 @@ const ModuleGraph = require("./ModuleGraph"); | ||
| const Watching = require("./Watching"); | ||
| const WebpackError = require("./WebpackError"); | ||
| const ConcurrentCompilationError = require("./errors/ConcurrentCompilationError"); | ||
| const WebpackError = require("./errors/WebpackError"); | ||
| const { Logger } = require("./logging/Logger"); | ||
@@ -1482,8 +1482,3 @@ const { dirname, join, mkdirp } = require("./util/fs"); | ||
| if (!check(value)) { | ||
| getValidate()( | ||
| getSchema(), | ||
| /** @type {EXPECTED_OBJECT | EXPECTED_OBJECT[]} */ | ||
| (value), | ||
| options | ||
| ); | ||
| getValidate()(getSchema(), value, options); | ||
| require("util").deprecate( | ||
@@ -1499,7 +1494,3 @@ () => {}, | ||
| // Otherwise let's standard validation | ||
| getValidate()( | ||
| getSchema(), | ||
| /** @type {EXPECTED_OBJECT | EXPECTED_OBJECT[]} */ (value), | ||
| options | ||
| ); | ||
| getValidate()(getSchema(), value, options); | ||
| } | ||
@@ -1506,0 +1497,0 @@ } |
@@ -25,3 +25,3 @@ /* | ||
| /** @typedef {import("../../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptionsNormalized */ | ||
| /** @typedef {import("../WebpackError")} WebpackError */ | ||
| /** @typedef {import("../errors/WebpackError")} WebpackError */ | ||
@@ -372,2 +372,4 @@ /** | ||
| hotUpdateMainFilename: output.hotUpdateMainFilename, | ||
| htmlChunkFilename: output.htmlChunkFilename, | ||
| htmlFilename: output.htmlFilename, | ||
| ignoreBrowserWarnings: output.ignoreBrowserWarnings, | ||
@@ -374,0 +376,0 @@ iife: output.iife, |
@@ -10,3 +10,2 @@ /* | ||
| const AsyncDependenciesBlock = require("./AsyncDependenciesBlock"); | ||
| const { makeWebpackError } = require("./HookWebpackError"); | ||
| const Module = require("./Module"); | ||
@@ -20,3 +19,2 @@ const { | ||
| const Template = require("./Template"); | ||
| const WebpackError = require("./WebpackError"); | ||
| const { | ||
@@ -26,2 +24,4 @@ getOutgoingAsyncModules | ||
| const { ImportPhase, ImportPhaseUtils } = require("./dependencies/ImportPhase"); | ||
| const { makeWebpackError } = require("./errors/HookWebpackError"); | ||
| const WebpackError = require("./errors/WebpackError"); | ||
| const { | ||
@@ -28,0 +28,0 @@ compareLocations, |
+320
-105
@@ -10,2 +10,3 @@ /* | ||
| ConcatSource, | ||
| OriginalSource, | ||
| RawSource, | ||
@@ -19,4 +20,7 @@ ReplaceSource, | ||
| const { | ||
| CSS_TEXT_TYPE, | ||
| CSS_TEXT_TYPES, | ||
| CSS_TYPE, | ||
| CSS_TYPES, | ||
| JAVASCRIPT_AND_CSS_TEXT_TYPES, | ||
| JAVASCRIPT_AND_CSS_TYPES, | ||
@@ -31,2 +35,3 @@ JAVASCRIPT_TYPE, | ||
| const { encodeMappings } = require("../util/createMappings"); | ||
| const memoize = require("../util/memoize"); | ||
@@ -52,3 +57,3 @@ | ||
| /** @typedef {import("./CssModulesPlugin").ModuleFactoryCacheEntry} ModuleFactoryCacheEntry */ | ||
| /** @typedef {import("../CssModule")} CssModule */ | ||
| /** @typedef {import("./CssModule")} CssModule */ | ||
| /** @typedef {import("../Compilation")} Compilation */ | ||
@@ -58,5 +63,65 @@ /** @typedef {import("../Module").RuntimeRequirements} RuntimeRequirements */ | ||
| /** @typedef {{ line: number, column: number }} SourcePosition */ | ||
| /** @typedef {Map<string, SourcePosition>} ExportLocsMap */ | ||
| const getPropertyName = memoize(() => require("../util/property")); | ||
| const getCssModulesPlugin = memoize(() => require("./CssModulesPlugin")); | ||
| /** @typedef {import("webpack-sources").RawSourceMap} RawSourceMap */ | ||
| /** | ||
| * Build a v3 source map that maps each line in `generatedJs` containing a | ||
| * known CSS-class export entry back to the corresponding selector position | ||
| * in the original CSS. Lines without an associated export are left | ||
| * unmapped — devtools simply shows them as part of the bundled JS. | ||
| * @param {string} generatedJs the generated JS string | ||
| * @param {ExportLocsMap} exportLocs map of export names to CSS source location | ||
| * @param {string} cssContent original CSS source content | ||
| * @param {string} sourceName source identifier to use in the map | ||
| * @returns {RawSourceMap} a v3 RawSourceMap | ||
| */ | ||
| const buildExportsSourceMap = ( | ||
| generatedJs, | ||
| exportLocs, | ||
| cssContent, | ||
| sourceName | ||
| ) => { | ||
| const lines = generatedJs.split("\n"); | ||
| const lineByExport = new Map(); | ||
| for (const [exportName] of exportLocs) { | ||
| const needle = `${JSON.stringify(exportName)}:`; | ||
| for (let i = 0; i < lines.length; i++) { | ||
| if (lines[i].includes(needle)) { | ||
| lineByExport.set(exportName, i); | ||
| break; | ||
| } | ||
| } | ||
| } | ||
| /** @type {(import("../util/createMappings").LineMappings)[]} */ | ||
| const perLine = lines.map(() => null); | ||
| for (const [exportName, genLine] of lineByExport) { | ||
| const pos = /** @type {SourcePosition} */ (exportLocs.get(exportName)); | ||
| // Source-map V3 uses 0-based lines and 0-based columns. webpack's | ||
| // dependency `loc` uses 1-based lines and 0-based columns, so subtract | ||
| // one from the line. | ||
| perLine[genLine] = { | ||
| generatedColumn: 0, | ||
| sourceIndex: 0, | ||
| originalLine: pos.line - 1, | ||
| originalColumn: pos.column | ||
| }; | ||
| } | ||
| return { | ||
| version: 3, | ||
| file: "", | ||
| sources: [sourceName], | ||
| sourcesContent: [cssContent], | ||
| names: [], | ||
| mappings: encodeMappings(perLine) | ||
| }; | ||
| }; | ||
| class CssGenerator extends Generator { | ||
@@ -93,18 +158,63 @@ /** | ||
| /** | ||
| * Generate JavaScript code that requires and concatenates all CSS imports | ||
| * Returns the `@charset` that will appear at the start of this module's | ||
| * default export, walking through text imports when the module has no | ||
| * local `@charset` of its own. | ||
| * @param {NormalModule} module the module | ||
| * @param {ModuleGraph} moduleGraph module graph | ||
| * @param {WeakSet<NormalModule>=} visited cycle guard | ||
| * @returns {string | undefined} the effective charset | ||
| */ | ||
| _getEffectiveCharset(module, moduleGraph, visited = new WeakSet()) { | ||
| if (!module || visited.has(module)) return undefined; | ||
| const exportType = /** @type {CssModule} */ (module).exportType; | ||
| if (exportType !== "text" && exportType !== "css-style-sheet") { | ||
| return undefined; | ||
| } | ||
| visited.add(module); | ||
| const own = | ||
| module.buildInfo && /** @type {BuildInfo} */ (module.buildInfo).charset; | ||
| if (own !== undefined) return own; | ||
| if (exportType !== "text") return undefined; | ||
| for (const dep of module.dependencies) { | ||
| if (dep instanceof CssImportDependency) { | ||
| const depModule = /** @type {NormalModule} */ ( | ||
| moduleGraph.getModule(dep) | ||
| ); | ||
| const inherited = this._getEffectiveCharset( | ||
| depModule, | ||
| moduleGraph, | ||
| visited | ||
| ); | ||
| if (inherited !== undefined) return inherited; | ||
| } | ||
| } | ||
| return undefined; | ||
| } | ||
| /** | ||
| * Generate JavaScript expressions that evaluate each `@import`'d module | ||
| * for side effects. Only used by `style` exportType, where each imported | ||
| * style module injects its own `<style>` element independently — no | ||
| * content merging happens at the parent. `text` and `css-style-sheet` | ||
| * instead inline their imports at build time via | ||
| * {@link CssGenerator#_generateMergedContentSource}. | ||
| * @param {NormalModule} module the module to generate CSS text for | ||
| * @param {GenerateContext} generateContext the generate context | ||
| * @param {boolean} getDefaultExport whether to get the default export | ||
| * @returns {{ expr: string, type: CssParserExportType }[]} JavaScript code that concatenates all imported CSS | ||
| * @returns {string[]} JS expressions, one per `@import` dependency | ||
| */ | ||
| _generateImportCode(module, generateContext, getDefaultExport = true) { | ||
| const moduleGraph = generateContext.moduleGraph; | ||
| /** @type {{ expr: string, type: CssParserExportType }[]} */ | ||
| _generateImportSideEffects(module, generateContext) { | ||
| const { moduleGraph, concatenationScope } = generateContext; | ||
| const parts = []; | ||
| // Iterate through module.dependencies to maintain source order | ||
| for (const dep of module.dependencies) { | ||
| if (dep instanceof CssImportDependency) { | ||
| const depModule = /** @type {CssModule} */ (moduleGraph.getModule(dep)); | ||
| const importVar = generateContext.runtimeTemplate.moduleExports({ | ||
| if (!(dep instanceof CssImportDependency)) continue; | ||
| const depModule = /** @type {CssModule} */ (moduleGraph.getModule(dep)); | ||
| // Concat-scoped deps are inlined into the same module; their side | ||
| // effect (own `<style>` injection) is emitted at the dep's own | ||
| // site, so no explicit reference is needed here. | ||
| if (concatenationScope && concatenationScope.isModuleInScope(depModule)) { | ||
| continue; | ||
| } | ||
| parts.push( | ||
| generateContext.runtimeTemplate.moduleExports({ | ||
| module: depModule, | ||
@@ -115,22 +225,64 @@ chunkGraph: generateContext.chunkGraph, | ||
| runtimeRequirements: generateContext.runtimeRequirements | ||
| }); | ||
| }) | ||
| ); | ||
| } | ||
| if (getDefaultExport) { | ||
| generateContext.runtimeRequirements.add( | ||
| RuntimeGlobals.compatGetDefaultExport | ||
| ); | ||
| parts.push({ | ||
| expr: `(${RuntimeGlobals.compatGetDefaultExport}(${importVar})() || "")`, | ||
| type: /** @type {CssParserExportType} */ (depModule.exportType) | ||
| }); | ||
| } else { | ||
| parts.push({ | ||
| expr: importVar, | ||
| type: /** @type {CssParserExportType} */ (depModule.exportType) | ||
| }); | ||
| return parts; | ||
| } | ||
| /** | ||
| * Build a single CSS `Source` that contains, in source order, the rendered | ||
| * CSS text of every transitively `@import`'d module followed by the | ||
| * current module's own CSS text. Imports are inlined at build time so | ||
| * the resulting `Source` carries a single, accurate source map covering | ||
| * every contributing file — no runtime merge helper required. | ||
| * | ||
| * Only `text` / `css-style-sheet` imports contribute CSS text; `link` and | ||
| * `style` imports are emitted separately (own `.css` file or own | ||
| * `<style>` injection) and are skipped here. | ||
| * | ||
| * `ancestors` tracks the path from the top-level caller down to the | ||
| * current module — not every module ever visited. A module reappearing | ||
| * along a sibling branch (a "diamond import" like two different files | ||
| * each `@import`'ing the same shared module) must be inlined every time, | ||
| * matching the prior runtime behavior where each `default` getter was | ||
| * invoked at every import site. | ||
| * @param {NormalModule} module the module to render | ||
| * @param {GenerateContext} generateContext the generate context | ||
| * @param {Set<NormalModule>} ancestors modules on the current path | ||
| * @returns {Source | null} merged CSS source, or null when the module has no content | ||
| */ | ||
| _generateMergedContentSource(module, generateContext, ancestors) { | ||
| if (ancestors.has(module)) return null; | ||
| ancestors.add(module); | ||
| try { | ||
| const { moduleGraph } = generateContext; | ||
| /** @type {Source[]} */ | ||
| const parts = []; | ||
| for (const dep of module.dependencies) { | ||
| if (!(dep instanceof CssImportDependency)) continue; | ||
| const depModule = /** @type {CssModule} */ (moduleGraph.getModule(dep)); | ||
| if (!depModule) continue; | ||
| const depExportType = depModule.exportType; | ||
| if (depExportType !== "text" && depExportType !== "css-style-sheet") { | ||
| continue; | ||
| } | ||
| const depMerged = this._generateMergedContentSource( | ||
| depModule, | ||
| generateContext, | ||
| ancestors | ||
| ); | ||
| if (depMerged) parts.push(depMerged); | ||
| } | ||
| const own = this._generateContentSource(module, generateContext); | ||
| if (own) parts.push(own); | ||
| if (parts.length === 0) return null; | ||
| if (parts.length === 1) return parts[0]; | ||
| return new ConcatSource(...parts); | ||
| } finally { | ||
| ancestors.delete(module); | ||
| } | ||
| return parts; | ||
| } | ||
@@ -178,16 +330,24 @@ | ||
| /** | ||
| * Convert a CSS Source to a JS string literal Source, preserving source map. | ||
| * Wraps the CSS content with JSON.stringify so it can be embedded in JS code. | ||
| * Serialize a CSS Source into a JS string literal with an optional | ||
| * inline `sourceMappingURL` data URI so DevTools can resolve the | ||
| * original sources at runtime. | ||
| * @param {Source} cssSource the CSS source | ||
| * @param {NormalModule} module the module | ||
| * @param {import("../../declarations/WebpackOptions").DevTool | undefined} devtool the devtool option | ||
| * @returns {Source} a Source representing a JS string literal | ||
| */ | ||
| _cssSourceToJsStringLiteral(cssSource, module) { | ||
| _cssToJsLiteral(cssSource, devtool) { | ||
| const { source, map } = cssSource.sourceAndMap(); | ||
| const content = /** @type {string} */ (source); | ||
| const escaped = JSON.stringify(content); | ||
| let content = /** @type {string} */ (source); | ||
| if (map) { | ||
| return new SourceMapSource(escaped, module.identifier(), map, content); | ||
| const inlineMap = | ||
| typeof devtool === "string" && devtool.includes("nosources") | ||
| ? { ...map, sourcesContent: undefined } | ||
| : map; | ||
| const base64Map = Buffer.from(JSON.stringify(inlineMap), "utf8").toString( | ||
| "base64" | ||
| ); | ||
| const trailingNewline = content.endsWith("\n") ? "" : "\n"; | ||
| content += `${trailingNewline}/*# sourceMappingURL=data:application/json;charset=utf-8;base64,${base64Map}*/`; | ||
| } | ||
| return new RawSource(escaped); | ||
| return new RawSource(JSON.stringify(content)); | ||
| } | ||
@@ -302,3 +462,4 @@ | ||
| esModule: /** @type {boolean} */ (this._esModule), | ||
| exports: new Map() | ||
| exports: new Map(), | ||
| exportLocs: new Map() | ||
| }; | ||
@@ -313,2 +474,7 @@ | ||
| case JAVASCRIPT_TYPE: { | ||
| const compilation = generateContext.runtimeTemplate.compilation; | ||
| const devtool = compilation.options.devtool; | ||
| const isCssModule = /** @type {BuildMeta} */ (module.buildMeta) | ||
| .isCssModule; | ||
| const generateContentCode = () => { | ||
@@ -322,3 +488,2 @@ switch (exportType) { | ||
| if (!cssSource) return ""; | ||
| const moduleId = generateContext.chunkGraph.getModuleId(module); | ||
@@ -329,5 +494,15 @@ generateContext.runtimeRequirements.add( | ||
| const moduleId = generateContext.chunkGraph.getModuleId(module); | ||
| if (generateContext.concatenationScope) { | ||
| return new ConcatSource( | ||
| `__webpack_css_styles__.push([${JSON.stringify(moduleId)}, `, | ||
| this._cssToJsLiteral(cssSource, devtool), | ||
| "]);" | ||
| ); | ||
| } | ||
| return new ConcatSource( | ||
| `${RuntimeGlobals.cssInjectStyle}(${JSON.stringify(moduleId || "")}, `, | ||
| this._cssSourceToJsStringLiteral(cssSource, module), | ||
| `${RuntimeGlobals.cssInjectStyle}(${JSON.stringify(moduleId)}, `, | ||
| this._cssToJsLiteral(cssSource, devtool), | ||
| ");" | ||
@@ -344,4 +519,4 @@ ); | ||
| case "style": { | ||
| return this._generateImportCode(module, generateContext, false) | ||
| .map((part) => `${part.expr};`) | ||
| return this._generateImportSideEffects(module, generateContext) | ||
| .map((expr) => `${expr};`) | ||
| .join("\n"); | ||
@@ -356,48 +531,19 @@ } | ||
| const generateCssText = () => { | ||
| const importCode = this._generateImportCode( | ||
| const cssSource = this._generateMergedContentSource( | ||
| module, | ||
| generateContext | ||
| generateContext, | ||
| new Set() | ||
| ); | ||
| const cssSource = this._generateContentSource( | ||
| module, | ||
| generateContext | ||
| ); | ||
| let jsLiteral = cssSource | ||
| ? this._cssSourceToJsStringLiteral(cssSource, module) | ||
| ? this._cssToJsLiteral(cssSource, devtool) | ||
| : new RawSource('""'); | ||
| if (importCode.length > 0) { | ||
| if ( | ||
| exportType === "css-style-sheet" || | ||
| importCode.some((part) => part.type !== exportType) | ||
| ) { | ||
| generateContext.runtimeRequirements.add( | ||
| RuntimeGlobals.cssMergeStyleSheets | ||
| ); | ||
| const args = importCode.map((part) => part.expr); | ||
| jsLiteral = new ConcatSource( | ||
| `${RuntimeGlobals.cssMergeStyleSheets}([${args.join(", ")}, `, | ||
| jsLiteral, | ||
| "])" | ||
| ); | ||
| } else { | ||
| jsLiteral = new ConcatSource( | ||
| `${generateContext.runtimeTemplate.concatenation( | ||
| ...importCode | ||
| )} + `, | ||
| jsLiteral | ||
| ); | ||
| } | ||
| } | ||
| if ( | ||
| exportType === "css-style-sheet" && | ||
| typeof (/** @type {BuildInfo} */ (module.buildInfo).charset) !== | ||
| "undefined" | ||
| ) { | ||
| const effectiveCharset = | ||
| exportType === "css-style-sheet" || exportType === "text" | ||
| ? this._getEffectiveCharset(module, generateContext.moduleGraph) | ||
| : undefined; | ||
| if (effectiveCharset !== undefined) { | ||
| jsLiteral = new ConcatSource( | ||
| `'@charset "${/** @type {BuildInfo} */ (module.buildInfo).charset}";\\n' + `, | ||
| `'@charset "${effectiveCharset}";\\n' + `, | ||
| jsLiteral | ||
@@ -419,5 +565,5 @@ ); | ||
| case "css-style-sheet": { | ||
| const constOrVar = | ||
| generateContext.runtimeTemplate.renderConst(); | ||
| const cssText = generateCssText(); | ||
| // Build a constructable stylesheet from the statically | ||
| // merged CSS text. The merged literal carries a single | ||
| // inline source map covering every contributing module. | ||
| const fnPrefix = | ||
@@ -427,10 +573,8 @@ generateContext.runtimeTemplate.supportsArrowFunction() | ||
| : "function() {\n"; | ||
| const body = | ||
| `${constOrVar} sheet = new CSSStyleSheet();\n` + | ||
| "sheet.replaceSync(cssText);\n" + | ||
| "return sheet;\n"; | ||
| const constOrVar = | ||
| generateContext.runtimeTemplate.renderConst(); | ||
| return new ConcatSource( | ||
| `(${fnPrefix}${constOrVar} cssText = `, | ||
| cssText, | ||
| `;\n${body}})()` | ||
| `(${fnPrefix}${constOrVar} sheet = new CSSStyleSheet();\nsheet.replaceSync(`, | ||
| generateCssText(), | ||
| ");\nreturn sheet;\n})()" | ||
| ); | ||
@@ -443,4 +587,2 @@ } | ||
| const isCSSModule = /** @type {BuildMeta} */ (module.buildMeta) | ||
| .isCSSModule; | ||
| /** @type {Source | null} */ | ||
@@ -457,3 +599,3 @@ const defaultExport = generateJSDefaultExport(); | ||
| if (!defaultExport && cssData.exports.size === 0 && !isCSSModule) { | ||
| if (!defaultExport && cssData.exports.size === 0 && !isCssModule) { | ||
| return new RawSource(""); | ||
@@ -535,3 +677,3 @@ } | ||
| if (!isCSSModule && !needNsObj) { | ||
| if (!isCssModule && !needNsObj) { | ||
| return new ConcatSource( | ||
@@ -584,11 +726,39 @@ `${module.moduleArgument}.exports = `, | ||
| } | ||
| return source; | ||
| // For link-type modules without any JS emit, skip source wrapping | ||
| if ( | ||
| exportType === "link" && | ||
| !isCssModule && | ||
| cssData.exports.size === 0 | ||
| ) { | ||
| return source; | ||
| } | ||
| const generatedJs = /** @type {string} */ (source.source()); | ||
| const sourceName = module.readableIdentifier( | ||
| compilation.requestShortener | ||
| ); | ||
| // When per-export source positions are available, emit a | ||
| // SourceMapSource mapping each export line back to its CSS | ||
| // selector; otherwise fall back to OriginalSource. | ||
| if ( | ||
| /** @type {ExportLocsMap} */ | ||
| (cssData.exportLocs).size > 0 | ||
| ) { | ||
| const cssOriginal = module.originalSource(); | ||
| if (cssOriginal) { | ||
| const sourceMap = buildExportsSourceMap( | ||
| generatedJs, | ||
| /** @type {ExportLocsMap} */ | ||
| (cssData.exportLocs), | ||
| /** @type {string} */ (cssOriginal.source()), | ||
| sourceName | ||
| ); | ||
| return new SourceMapSource(generatedJs, sourceName, sourceMap); | ||
| } | ||
| } | ||
| return new OriginalSource(generatedJs, sourceName); | ||
| } | ||
| case CSS_TYPE: { | ||
| if ( | ||
| !( | ||
| this._exportsOnly || | ||
| /** @type {boolean} */ (exportType && exportType !== "link") | ||
| ) | ||
| ) { | ||
| if (!(this._exportsOnly || (exportType && exportType !== "link"))) { | ||
| generateContext.runtimeRequirements.add(RuntimeGlobals.hasCssModules); | ||
@@ -599,2 +769,32 @@ } | ||
| } | ||
| case CSS_TEXT_TYPE: { | ||
| // The merged CSS text — what consumers like | ||
| // `HtmlInlineStyleDependency.Template` need when they want to | ||
| // drop the processed CSS straight into an inline `<style>` | ||
| // tag. Mirrors the JS-side `generateCssText()` (charset | ||
| // prefix included), without the JS string-literal wrapper. | ||
| const cssSource = this._generateMergedContentSource( | ||
| module, | ||
| generateContext, | ||
| new Set() | ||
| ); | ||
| const effectiveCharset = this._getEffectiveCharset( | ||
| module, | ||
| generateContext.moduleGraph | ||
| ); | ||
| const charsetPrefix = | ||
| effectiveCharset !== undefined | ||
| ? `@charset "${effectiveCharset}";\n` | ||
| : ""; | ||
| if (!cssSource) { | ||
| return charsetPrefix | ||
| ? new RawSource(charsetPrefix) | ||
| : new RawSource(""); | ||
| } | ||
| return charsetPrefix | ||
| ? new ConcatSource(charsetPrefix, cssSource) | ||
| : cssSource; | ||
| } | ||
| default: | ||
@@ -655,2 +855,15 @@ return null; | ||
| // Inline `<style>` blocks in HTML modules read the merged CSS | ||
| // text directly via the `css-text` source type — they don't go | ||
| // through the JS-string wrapper that other consumers use. | ||
| // Matched by dependency category so the CSS package doesn't | ||
| // have to import HtmlInlineStyleDependency. | ||
| if ( | ||
| connection.dependency && | ||
| connection.dependency.category === "html-style" | ||
| ) { | ||
| sourceTypes.add(CSS_TEXT_TYPE); | ||
| continue; | ||
| } | ||
| if (!connection.originModule) { | ||
@@ -679,5 +892,7 @@ continue; | ||
| ) { | ||
| if (sourceTypes.has(JAVASCRIPT_TYPE)) { | ||
| return JAVASCRIPT_TYPES; | ||
| } | ||
| const hasJs = sourceTypes.has(JAVASCRIPT_TYPE); | ||
| const hasCssText = sourceTypes.has(CSS_TEXT_TYPE); | ||
| if (hasJs && hasCssText) return JAVASCRIPT_AND_CSS_TEXT_TYPES; | ||
| if (hasJs) return JAVASCRIPT_TYPES; | ||
| if (hasCssText) return CSS_TEXT_TYPES; | ||
| return new Set(); | ||
@@ -705,3 +920,3 @@ } | ||
| if (cssData.exports.size === 0) { | ||
| if (/** @type {BuildMeta} */ (module.buildMeta).isCSSModule) { | ||
| if (/** @type {BuildMeta} */ (module.buildMeta).isCssModule) { | ||
| return 42; | ||
@@ -708,0 +923,0 @@ } |
@@ -73,10 +73,21 @@ /* | ||
| // Only emit the nonce check when scriptNonce is part of the runtime | ||
| // requirements. Otherwise referencing `__webpack_require__.nc` would | ||
| // keep the require runtime alive for nothing. | ||
| const withScriptNonce = | ||
| _runtimeRequirements && | ||
| _runtimeRequirements.has(RuntimeGlobals.scriptNonce); | ||
| const createStyleElementCode = Template.asString([ | ||
| "var style = document.createElement('style');", | ||
| "", | ||
| `if (${RuntimeGlobals.scriptNonce}) {`, | ||
| Template.indent( | ||
| `style.setAttribute("nonce", ${RuntimeGlobals.scriptNonce});` | ||
| ), | ||
| "}", | ||
| ...(withScriptNonce | ||
| ? [ | ||
| `if (${RuntimeGlobals.scriptNonce}) {`, | ||
| Template.indent( | ||
| `style.setAttribute("nonce", ${RuntimeGlobals.scriptNonce});` | ||
| ), | ||
| "}" | ||
| ] | ||
| : []), | ||
| 'style.setAttribute("data-webpack", getDataWebpackId(key));' | ||
@@ -92,14 +103,2 @@ ]); | ||
| "", | ||
| "function applyStyle(styleElement, css) {", | ||
| Template.indent("styleElement.textContent = css;"), | ||
| "}", | ||
| "", | ||
| "function removeStyleElement(styleElement) {", | ||
| Template.indent([ | ||
| "if (styleElement.parentNode) {", | ||
| Template.indent("styleElement.parentNode.removeChild(styleElement);"), | ||
| "}" | ||
| ]), | ||
| "}", | ||
| "", | ||
| "function findStyleElement(identifier) {", | ||
@@ -136,32 +135,35 @@ Template.indent([ | ||
| [ | ||
| "var element = findStyleElement(identifier);", | ||
| "if (element) {", | ||
| Template.indent("applyStyle(element, css);"), | ||
| "} else {", | ||
| Template.indent([ | ||
| "var element = insertStyleElement(identifier);", | ||
| "applyStyle(element, css);" | ||
| ]), | ||
| "}" | ||
| "var element = findStyleElement(identifier) || insertStyleElement(identifier);", | ||
| "element.textContent = css;" | ||
| ] | ||
| )};`, | ||
| "", | ||
| `${RuntimeGlobals.cssInjectStyle}.removeModules = ${runtimeTemplate.basicFunction( | ||
| "removedModules", | ||
| [ | ||
| "if (!removedModules) return;", | ||
| "var identifiers = Array.isArray(removedModules) ? removedModules : [removedModules];", | ||
| "for (var i = 0; i < identifiers.length; i++) {", | ||
| Template.indent([ | ||
| "var identifier = identifiers[i];", | ||
| "var element = findStyleElement(identifier);", | ||
| "if (element) {", | ||
| Template.indent("removeStyleElement(element);"), | ||
| "}" | ||
| ]), | ||
| "}" | ||
| ] | ||
| )};`, | ||
| withHmr | ||
| ? Template.asString([ | ||
| "", | ||
| "function removeStyleElement(styleElement) {", | ||
| Template.indent([ | ||
| "if (styleElement.parentNode) {", | ||
| Template.indent( | ||
| "styleElement.parentNode.removeChild(styleElement);" | ||
| ), | ||
| "}" | ||
| ]), | ||
| "}", | ||
| `${RuntimeGlobals.cssInjectStyle}.removeModules = ${runtimeTemplate.basicFunction( | ||
| "removedModules", | ||
| [ | ||
| "if (!removedModules) return;", | ||
| "var identifiers = Array.isArray(removedModules) ? removedModules : [removedModules];", | ||
| "for (var i = 0; i < identifiers.length; i++) {", | ||
| Template.indent([ | ||
| "var identifier = identifiers[i];", | ||
| "var element = findStyleElement(identifier);", | ||
| "if (element) {", | ||
| Template.indent("removeStyleElement(element);"), | ||
| "}" | ||
| ]), | ||
| "}" | ||
| ] | ||
| )};`, | ||
| `${RuntimeGlobals.hmrDownloadUpdateHandlers}.cssInjectStyle = ${runtimeTemplate.basicFunction( | ||
@@ -168,0 +170,0 @@ "chunkIds, removedChunks, removedModules, promises, applyHandlers, updatedModulesList, css", |
@@ -27,2 +27,3 @@ /* | ||
| * @property {SyncWaterfallHook<[string, Chunk]>} linkPrefetch | ||
| * @property {SyncWaterfallHook<[string, Chunk]>} linkInsert | ||
| */ | ||
@@ -49,3 +50,4 @@ | ||
| linkPreload: new SyncWaterfallHook(["source", "chunk"]), | ||
| linkPrefetch: new SyncWaterfallHook(["source", "chunk"]) | ||
| linkPrefetch: new SyncWaterfallHook(["source", "chunk"]), | ||
| linkInsert: new SyncWaterfallHook(["source", "chunk"]) | ||
| }; | ||
@@ -127,3 +129,3 @@ compilationHooksMap.set(compilation, hooks); | ||
| const { linkPreload, linkPrefetch, createStylesheet } = | ||
| const { linkPreload, linkPrefetch, createStylesheet, linkInsert } = | ||
| CssLoadingRuntimeModule.getCompilationHooks(compilation); | ||
@@ -248,4 +250,20 @@ | ||
| : "", | ||
| withHmr ? "hmr ? document.head.insertBefore(link, hmr) :" : "", | ||
| "needAttach && document.head.appendChild(link);", | ||
| linkInsert.call( | ||
| withHmr | ||
| ? Template.asString([ | ||
| "if (hmr) {", | ||
| Template.indent( | ||
| "hmr.parentNode.insertBefore(link, hmr);" | ||
| ), | ||
| "} else if (needAttach) {", | ||
| Template.indent("document.head.appendChild(link);"), | ||
| "}" | ||
| ]) | ||
| : Template.asString([ | ||
| "if (needAttach) {", | ||
| Template.indent("document.head.appendChild(link);"), | ||
| "}" | ||
| ]), | ||
| /** @type {Chunk} */ (this.chunk) | ||
| ), | ||
| "return link;" | ||
@@ -252,0 +270,0 @@ ] |
+166
-86
@@ -8,3 +8,3 @@ /* | ||
| const { SyncHook, SyncWaterfallHook } = require("tapable"); | ||
| const { SyncBailHook, SyncHook, SyncWaterfallHook } = require("tapable"); | ||
| const { | ||
@@ -18,4 +18,2 @@ CachedSource, | ||
| const Compilation = require("../Compilation"); | ||
| const CssModule = require("../CssModule"); | ||
| const { tryRunOrWebpackError } = require("../HookWebpackError"); | ||
| const HotUpdateChunk = require("../HotUpdateChunk"); | ||
@@ -32,3 +30,2 @@ const { CSS_IMPORT_TYPE, CSS_TYPE } = require("../ModuleSourceTypeConstants"); | ||
| const Template = require("../Template"); | ||
| const WebpackError = require("../WebpackError"); | ||
| const CssIcssExportDependency = require("../dependencies/CssIcssExportDependency"); | ||
@@ -40,3 +37,6 @@ const CssIcssImportDependency = require("../dependencies/CssIcssImportDependency"); | ||
| const StaticExportsDependency = require("../dependencies/StaticExportsDependency"); | ||
| const { tryRunOrWebpackError } = require("../errors/HookWebpackError"); | ||
| const WebpackError = require("../errors/WebpackError"); | ||
| const JavascriptModulesPlugin = require("../javascript/JavascriptModulesPlugin"); | ||
| const ConcatenatedModule = require("../optimize/ConcatenatedModule"); | ||
| const { compareModulesByFullName } = require("../util/comparators"); | ||
@@ -49,6 +49,5 @@ const createHash = require("../util/createHash"); | ||
| const CssGenerator = require("./CssGenerator"); | ||
| const CssModule = require("./CssModule"); | ||
| const CssParser = require("./CssParser"); | ||
| const publicPathAutoRegex = new RegExp(CssUrlDependency.PUBLIC_PATH_AUTO, "g"); | ||
| /** @typedef {import("webpack-sources").Source} Source */ | ||
@@ -61,4 +60,4 @@ /** @typedef {import("../config/defaults").OutputNormalizedWithDefaults} OutputOptions */ | ||
| /** @typedef {import("../Compiler")} Compiler */ | ||
| /** @typedef {import("../CssModule").Inheritance} Inheritance */ | ||
| /** @typedef {import("../CssModule").CSSModuleCreateData} CSSModuleCreateData */ | ||
| /** @typedef {import("./CssModule").Inheritance} Inheritance */ | ||
| /** @typedef {import("./CssModule").CssModuleCreateData} CssModuleCreateData */ | ||
| /** @typedef {import("../Module")} Module */ | ||
@@ -81,2 +80,3 @@ /** @typedef {import("../Module").BuildInfo} BuildInfo */ | ||
| * @property {string} undoPath undo path to css file | ||
| * @property {string=} hash compilation hash | ||
| * @property {CssModule[]} modules modules | ||
@@ -93,2 +93,3 @@ */ | ||
| * @property {string} undoPath undo path to css file | ||
| * @property {string=} hash compilation hash | ||
| * @property {WeakMap<Source, ModuleFactoryCacheEntry>} moduleFactoryCache moduleFactoryCache | ||
@@ -103,2 +104,3 @@ * @property {Source} moduleSourceContent content | ||
| * @property {SyncHook<[Chunk, Hash, ChunkHashContext]>} chunkHash | ||
| * @property {SyncBailHook<[Chunk, Module[], Compilation], Module[] | undefined | void>} orderModules called for each CSS source type (CSS_IMPORT_TYPE, CSS_TYPE) with the chunk's modules pre-sorted by full module name; return an ordered `Module[]` to override the default import-order topological sort, or return `undefined` to keep the default | ||
| */ | ||
@@ -110,2 +112,3 @@ | ||
| * @property {string} undoPath - The undo path to the CSS file | ||
| * @property {string | undefined} hash - The compilation hash | ||
| * @property {Inheritance} inheritance - The inheritance chain | ||
@@ -118,5 +121,2 @@ * @property {CachedSource} source - The cached source | ||
| ); | ||
| const getCssMergeStyleSheetsRuntimeModule = memoize(() => | ||
| require("./CssMergeStyleSheetsRuntimeModule") | ||
| ); | ||
| const getCssInjectStyleRuntimeModule = memoize(() => | ||
@@ -175,3 +175,4 @@ require("./CssInjectStyleRuntimeModule") | ||
| ]), | ||
| chunkHash: new SyncHook(["chunk", "hash", "context"]) | ||
| chunkHash: new SyncHook(["chunk", "hash", "context"]), | ||
| orderModules: new SyncBailHook(["chunk", "modules", "compilation"]) | ||
| }; | ||
@@ -276,7 +277,7 @@ compilationHooksMap.set(compilation, hooks); | ||
| compiler.validate( | ||
| () => getSchema("CssModuleParserOptions"), | ||
| () => getSchema("CssAutoOrModuleParserOptions"), | ||
| parserOptions, | ||
| parserValidationOptions, | ||
| (options) => | ||
| require("../../schemas/plugins/css/CssModuleParserOptions.check")( | ||
| require("../../schemas/plugins/css/CssAutoOrModuleParserOptions.check")( | ||
| options | ||
@@ -290,7 +291,7 @@ ) | ||
| compiler.validate( | ||
| () => getSchema("CssModuleParserOptions"), | ||
| () => getSchema("CssAutoOrModuleParserOptions"), | ||
| parserOptions, | ||
| parserValidationOptions, | ||
| (options) => | ||
| require("../../schemas/plugins/css/CssModuleParserOptions.check")( | ||
| require("../../schemas/plugins/css/CssAutoOrModuleParserOptions.check")( | ||
| options | ||
@@ -415,3 +416,3 @@ ) | ||
| return new CssModule( | ||
| /** @type {CSSModuleCreateData} */ | ||
| /** @type {CssModuleCreateData} */ | ||
| ({ | ||
@@ -429,3 +430,3 @@ ...createData, | ||
| return new CssModule( | ||
| /** @type {CSSModuleCreateData} */ | ||
| /** @type {CssModuleCreateData} */ | ||
| ({ | ||
@@ -443,3 +444,3 @@ ...createData, | ||
| return new CssModule( | ||
| /** @type {CSSModuleCreateData} */ | ||
| /** @type {CssModuleCreateData} */ | ||
| ( | ||
@@ -471,41 +472,73 @@ /** @type {unknown} */ ({ | ||
| ).renderModuleContent.tap(PLUGIN_NAME, (source, module) => { | ||
| if (module instanceof CssModule && module.hot) { | ||
| const exportType = module.exportType; | ||
| // When exportType !== "link", modules behave like JavaScript modules | ||
| if (exportType && !["link", "style"].includes(exportType)) { | ||
| return source; | ||
| } | ||
| // For exportType === "link", we can optimize with self-acceptance | ||
| const cssData = /** @type {BuildInfo} */ (module.buildInfo).cssData; | ||
| if (!cssData) { | ||
| return source; | ||
| } | ||
| const exports = cssData.exports; | ||
| /** @type {Record<string, string>} */ | ||
| const exportsObj = {}; | ||
| for (const [key, value] of exports) { | ||
| exportsObj[key] = value; | ||
| } | ||
| const stringifiedExports = JSON.stringify( | ||
| JSON.stringify(exportsObj) | ||
| const injectCssStylesVar = | ||
| module instanceof ConcatenatedModule && | ||
| module.modules.find( | ||
| (m) => | ||
| m instanceof CssModule && | ||
| m.exportType === "style" && | ||
| !(/** @type {CssGenerator} */ (m.generator)._exportsOnly) | ||
| ); | ||
| const injectHMRCode = | ||
| (module instanceof CssModule && module.hot) || | ||
| (module instanceof ConcatenatedModule && | ||
| module.rootModule instanceof CssModule && | ||
| module.rootModule.hot); | ||
| const hmrCode = Template.asString([ | ||
| "", | ||
| `var __webpack_css_exports__ = ${stringifiedExports};`, | ||
| "// only invalidate when locals change", | ||
| "if (module.hot.data && module.hot.data.__webpack_css_exports__ && module.hot.data.__webpack_css_exports__ != __webpack_css_exports__) {", | ||
| Template.indent("module.hot.invalidate();"), | ||
| "} else {", | ||
| Template.indent("module.hot.accept();"), | ||
| "}", | ||
| "module.hot.dispose(function(data) {", | ||
| Template.indent([ | ||
| "data.__webpack_css_exports__ = __webpack_css_exports__;" | ||
| ]), | ||
| "});" | ||
| ]); | ||
| if (injectCssStylesVar) { | ||
| source = new ConcatSource( | ||
| "var __webpack_css_styles__ = [];", | ||
| "\n", | ||
| source | ||
| ); | ||
| } | ||
| if (injectHMRCode) { | ||
| const currentModule = /** @type {CssModule} */ ( | ||
| module instanceof ConcatenatedModule ? module.rootModule : module | ||
| ); | ||
| const exportType = currentModule.exportType || "link"; | ||
| // When exportType !== "link", modules behave like JavaScript modules | ||
| if (["link", "style"].includes(exportType)) { | ||
| // For exportType === "link", we can optimize with self-acceptance | ||
| const cssData = /** @type {BuildInfo} */ (module.buildInfo) | ||
| .cssData; | ||
| if (!cssData) { | ||
| return source; | ||
| } | ||
| const exports = cssData.exports; | ||
| /** @type {Record<string, string>} */ | ||
| const exportsObj = {}; | ||
| for (const [key, value] of exports) { | ||
| exportsObj[key] = value; | ||
| } | ||
| const stringifiedExports = JSON.stringify( | ||
| JSON.stringify(exportsObj) | ||
| ); | ||
| return new ConcatSource(source, "\n", new RawSource(hmrCode)); | ||
| const hmrCode = Template.asString([ | ||
| "", | ||
| `var __webpack_css_exports__ = ${stringifiedExports};`, | ||
| "// only invalidate when locals change", | ||
| "if (module.hot.data && module.hot.data.__webpack_css_exports__ && module.hot.data.__webpack_css_exports__ != __webpack_css_exports__) {", | ||
| Template.indent("module.hot.invalidate();"), | ||
| "} else {", | ||
| Template.indent("module.hot.accept();"), | ||
| "}", | ||
| "module.hot.dispose(function(data) {", | ||
| Template.indent([ | ||
| "data.__webpack_css_exports__ = __webpack_css_exports__;" | ||
| ]), | ||
| "});" | ||
| ]); | ||
| source = new ConcatSource(source, "\n", new RawSource(hmrCode)); | ||
| } | ||
| } | ||
| if (injectCssStylesVar) { | ||
| /** @type {ConcatSource} */ | ||
| (source).add( | ||
| "for (let i = 0; i < __webpack_css_styles__.length; i++) {\n" + | ||
| `${RuntimeGlobals.cssInjectStyle}(__webpack_css_styles__[i][0], __webpack_css_styles__[i][1]);\n` + | ||
| "}" | ||
| ); | ||
| } | ||
@@ -598,2 +631,3 @@ return source; | ||
| undoPath, | ||
| hash, | ||
| modules, | ||
@@ -686,15 +720,6 @@ runtimeTemplate | ||
| compilation.hooks.runtimeRequirementInTree | ||
| .for(RuntimeGlobals.cssMergeStyleSheets) | ||
| .tap(PLUGIN_NAME, (chunk) => { | ||
| const CssMergeStyleSheetsRuntimeModule = | ||
| getCssMergeStyleSheetsRuntimeModule(); | ||
| compilation.addRuntimeModule( | ||
| chunk, | ||
| new CssMergeStyleSheetsRuntimeModule() | ||
| ); | ||
| }); | ||
| compilation.hooks.runtimeRequirementInTree | ||
| .for(RuntimeGlobals.cssInjectStyle) | ||
| .tap(PLUGIN_NAME, (chunk, set) => { | ||
| // Same as above: namespace stub is enough. | ||
| set.add(RuntimeGlobals.requireScope); | ||
| const CssInjectStyleRuntimeModule = | ||
@@ -869,5 +894,17 @@ getCssInjectStyleRuntimeModule(); | ||
| const hooks = CssModulesPlugin.getCompilationHooks(compilation); | ||
| /** | ||
| * @param {Iterable<Module> | undefined} iter modules pre-sorted by full module name | ||
| * @returns {Module[]} ordered modules | ||
| */ | ||
| const orderModules = (iter) => { | ||
| const modules = iter ? [...iter] : []; | ||
| const result = hooks.orderModules.call(chunk, modules, compilation); | ||
| if (result !== undefined) return result; | ||
| return this.getModulesInOrder(chunk, modules, compilation); | ||
| }; | ||
| return /** @type {CssModule[]} */ ([ | ||
| ...this.getModulesInOrder( | ||
| chunk, | ||
| ...orderModules( | ||
| chunkGraph.getOrderedChunkModulesIterableBySourceType( | ||
@@ -877,7 +914,5 @@ chunk, | ||
| compareModulesByFullName(compilation.compiler) | ||
| ), | ||
| compilation | ||
| ) | ||
| ), | ||
| ...this.getModulesInOrder( | ||
| chunk, | ||
| ...orderModules( | ||
| chunkGraph.getOrderedChunkModulesIterableBySourceType( | ||
@@ -887,4 +922,3 @@ chunk, | ||
| compareModulesByFullName(compilation.compiler) | ||
| ), | ||
| compilation | ||
| ) | ||
| ).map((module) => { | ||
@@ -932,3 +966,4 @@ if ( | ||
| static renderModule(module, renderContext, hooks) { | ||
| const { undoPath, moduleFactoryCache, moduleSourceContent } = renderContext; | ||
| const { undoPath, hash, moduleFactoryCache, moduleSourceContent } = | ||
| renderContext; | ||
| const cacheEntry = moduleFactoryCache.get(moduleSourceContent); | ||
@@ -947,2 +982,3 @@ | ||
| cacheEntry.undoPath === undoPath && | ||
| cacheEntry.hash === hash && | ||
| cacheEntry.inheritance.length === inheritance.length && | ||
@@ -963,15 +999,56 @@ cacheEntry.inheritance.every(([layer, supports, media], i) => { | ||
| (moduleSourceContent.source()); | ||
| publicPathAutoRegex.lastIndex = 0; | ||
| /** @type {Source} */ | ||
| let moduleSource = new ReplaceSource(moduleSourceContent); | ||
| /** @type {null | RegExpExecArray} */ | ||
| let match; | ||
| while ((match = publicPathAutoRegex.exec(moduleSourceCode))) { | ||
| /** @type {ReplaceSource} */ (moduleSource).replace( | ||
| match.index, | ||
| match.index + match[0].length - 1, | ||
| undoPath | ||
| ); | ||
| const replaceSource = new ReplaceSource(moduleSourceContent); | ||
| const autoPlaceholder = CssUrlDependency.PUBLIC_PATH_AUTO; | ||
| const autoPlaceholderLen = autoPlaceholder.length; | ||
| for ( | ||
| let idx = moduleSourceCode.indexOf(autoPlaceholder); | ||
| idx !== -1; | ||
| idx = moduleSourceCode.indexOf( | ||
| autoPlaceholder, | ||
| idx + autoPlaceholderLen | ||
| ) | ||
| ) { | ||
| replaceSource.replace(idx, idx + autoPlaceholderLen - 1, undoPath); | ||
| } | ||
| if (hash) { | ||
| const hashPrefix = CssUrlDependency.PUBLIC_PATH_FULL_HASH; | ||
| const hashPrefixLen = hashPrefix.length; | ||
| const sourceLen = moduleSourceCode.length; | ||
| let idx = moduleSourceCode.indexOf(hashPrefix); | ||
| while (idx !== -1) { | ||
| let digitEnd = idx + hashPrefixLen; | ||
| while (digitEnd < sourceLen) { | ||
| const cc = moduleSourceCode.charCodeAt(digitEnd); | ||
| if (cc < 48 || cc > 57) break; | ||
| digitEnd++; | ||
| } | ||
| let nextSearch; | ||
| if ( | ||
| digitEnd > idx + hashPrefixLen && | ||
| digitEnd + 1 < sourceLen && | ||
| moduleSourceCode.charCodeAt(digitEnd) === 95 && | ||
| moduleSourceCode.charCodeAt(digitEnd + 1) === 95 | ||
| ) { | ||
| const length = Number.parseInt( | ||
| moduleSourceCode.slice(idx + hashPrefixLen, digitEnd), | ||
| 10 | ||
| ); | ||
| replaceSource.replace( | ||
| idx, | ||
| digitEnd + 1, | ||
| length === 0 ? hash : hash.slice(0, length) | ||
| ); | ||
| nextSearch = digitEnd + 2; | ||
| } else { | ||
| nextSearch = idx + hashPrefixLen; | ||
| } | ||
| idx = moduleSourceCode.indexOf(hashPrefix, nextSearch); | ||
| } | ||
| } | ||
| /** @type {Source} */ | ||
| let moduleSource = replaceSource; | ||
| for (let i = 0; i < inheritance.length; i++) { | ||
@@ -1016,2 +1093,3 @@ const layer = inheritance[i][0]; | ||
| undoPath, | ||
| hash, | ||
| source | ||
@@ -1040,3 +1118,4 @@ }); | ||
| runtimeTemplate, | ||
| chunkGraph | ||
| chunkGraph, | ||
| hash | ||
| }, | ||
@@ -1071,2 +1150,3 @@ hooks | ||
| undoPath, | ||
| hash, | ||
| chunk, | ||
@@ -1073,0 +1153,0 @@ chunkGraph, |
+148
-2
@@ -8,2 +8,4 @@ /* | ||
| const { makeCacheable } = require("../util/identifier"); | ||
| /** | ||
@@ -165,2 +167,139 @@ * Defines the css token callbacks type used by this module. | ||
| const REGEX_SINGLE_ESCAPE = /[ -,./:-@[\]^`{-~]/; | ||
| const REGEX_EXCESSIVE_SPACES = /(^|\\+)?(\\[A-F0-9]{1,6}) (?![a-fA-F0-9 ])/g; | ||
| const REGEX_CTRL_WHITESPACE = /[\t\n\f\r\v]/; | ||
| const REGEX_LEADING_HYPHEN_DIGIT = /^-[-\d]/; | ||
| const REGEX_DIGIT = /\d/; | ||
| const CONTAINS_ESCAPE = /\\/; | ||
| /** | ||
| * Returns escaped identifier. | ||
| * @param {string} str string | ||
| * @returns {string} escaped identifier | ||
| */ | ||
| const _escapeIdentifier = (str) => { | ||
| let output = ""; | ||
| let counter = 0; | ||
| while (counter < str.length) { | ||
| const character = str.charAt(counter++); | ||
| /** @type {string} */ | ||
| let value; | ||
| if (REGEX_CTRL_WHITESPACE.test(character)) { | ||
| const codePoint = character.charCodeAt(0); | ||
| value = `\\${codePoint.toString(16).toUpperCase()} `; | ||
| } else if (character === "\\" || REGEX_SINGLE_ESCAPE.test(character)) { | ||
| value = `\\${character}`; | ||
| } else { | ||
| value = character; | ||
| } | ||
| output += value; | ||
| } | ||
| const firstChar = str.charAt(0); | ||
| if (REGEX_LEADING_HYPHEN_DIGIT.test(output)) { | ||
| output = `\\-${output.slice(1)}`; | ||
| } else if (REGEX_DIGIT.test(firstChar)) { | ||
| output = `\\3${firstChar} ${output.slice(1)}`; | ||
| } | ||
| // Remove spaces after `\HEX` escapes that are not followed by a hex digit, | ||
| // since they’re redundant. Note that this is only possible if the escape | ||
| // sequence isn’t preceded by an odd number of backslashes. | ||
| output = output.replace(REGEX_EXCESSIVE_SPACES, ($0, $1, $2) => { | ||
| if ($1 && $1.length % 2) { | ||
| // It’s not safe to remove the space, so don’t. | ||
| return $0; | ||
| } | ||
| // Strip the space. | ||
| return ($1 || "") + $2; | ||
| }); | ||
| return output; | ||
| }; | ||
| /** | ||
| * Returns hex. | ||
| * @param {string} str string | ||
| * @returns {[string, number] | undefined} hex | ||
| */ | ||
| const gobbleHex = (str) => { | ||
| const lower = str.toLowerCase(); | ||
| let hex = ""; | ||
| let spaceTerminated = false; | ||
| for (let i = 0; i < 6 && lower[i] !== undefined; i++) { | ||
| const code = lower.charCodeAt(i); | ||
| // check to see if we are dealing with a valid hex char [a-f|0-9] | ||
| const valid = (code >= 97 && code <= 102) || (code >= 48 && code <= 57); | ||
| // https://drafts.csswg.org/css-syntax/#consume-escaped-code-point | ||
| spaceTerminated = code === 32; | ||
| if (!valid) break; | ||
| hex += lower[i]; | ||
| } | ||
| if (hex.length === 0) return undefined; | ||
| const codePoint = Number.parseInt(hex, 16); | ||
| const isSurrogate = codePoint >= 0xd800 && codePoint <= 0xdfff; | ||
| // Add special case for | ||
| // "If this number is zero, or is for a surrogate, or is greater than the maximum allowed code point" | ||
| // https://drafts.csswg.org/css-syntax/#maximum-allowed-code-point | ||
| if (isSurrogate || codePoint === 0x0000 || codePoint > 0x10ffff) { | ||
| return ["�", hex.length + (spaceTerminated ? 1 : 0)]; | ||
| } | ||
| return [ | ||
| String.fromCodePoint(codePoint), | ||
| hex.length + (spaceTerminated ? 1 : 0) | ||
| ]; | ||
| }; | ||
| /** | ||
| * Unescape identifier. | ||
| * @param {string} str string | ||
| * @returns {string} unescaped string | ||
| */ | ||
| const _unescapeIdentifier = (str) => { | ||
| const needToProcess = CONTAINS_ESCAPE.test(str); | ||
| if (!needToProcess) return str; | ||
| let ret = ""; | ||
| for (let i = 0; i < str.length; i++) { | ||
| if (str[i] === "\\") { | ||
| const gobbled = gobbleHex(str.slice(i + 1, i + 7)); | ||
| if (gobbled !== undefined) { | ||
| ret += gobbled[0]; | ||
| i += gobbled[1]; | ||
| continue; | ||
| } | ||
| // Retain a pair of \\ if double escaped `\\\\` | ||
| // https://github.com/postcss/postcss-selector-parser/commit/268c9a7656fb53f543dc620aa5b73a30ec3ff20e | ||
| if (str[i + 1] === "\\") { | ||
| ret += "\\"; | ||
| i += 1; | ||
| continue; | ||
| } | ||
| // if \\ is at the end of the string retain it | ||
| // https://github.com/postcss/postcss-selector-parser/commit/01a6b346e3612ce1ab20219acc26abdc259ccefb | ||
| if (str.length === i + 1) { | ||
| ret += str[i]; | ||
| } | ||
| continue; | ||
| } | ||
| ret += str[i]; | ||
| } | ||
| return ret; | ||
| }; | ||
| const escapeIdentifier = makeCacheable(_escapeIdentifier); | ||
| const unescapeIdentifier = makeCacheable(_unescapeIdentifier); | ||
| /** @type {CharHandler} */ | ||
@@ -1637,7 +1776,7 @@ const consumeDelimToken = (input, pos, callbacks) => { | ||
| * @param {CssTokenCallbacks} cbs callbacks | ||
| * @returns {[[number, number, number, number] | undefined, [number, number] | undefined, [number, number] | undefined, [number, number] | undefined]} positions of top level tokens | ||
| * @returns {[[number, number, number, number, boolean?] | undefined, [number, number] | undefined, [number, number] | undefined, [number, number] | undefined]} positions of top level tokens — the URL tuple's optional 5th element is `true` when the URL was given as an identifier (CSS Modules `@value` reference) | ||
| */ | ||
| const eatImportTokens = (input, pos, cbs) => { | ||
| const result = | ||
| /** @type {[[number, number, number, number] | undefined, [number, number] | undefined, [number, number] | undefined, [number, number] | undefined]} */ | ||
| /** @type {[[number, number, number, number, boolean?] | undefined, [number, number] | undefined, [number, number] | undefined, [number, number] | undefined]} */ | ||
| (Array.from({ length: 4 })); | ||
@@ -1746,2 +1885,7 @@ | ||
| scope = undefined; | ||
| } else if (result[0] === undefined) { | ||
| // Capture as URL identifier (e.g. `@import myValue;` where | ||
| // `myValue` is a CSS Modules `@value` definition). | ||
| result[0] = [start, end, start, end, true]; | ||
| scope = undefined; | ||
| } | ||
@@ -1875,2 +2019,3 @@ } | ||
| module.exports.eatWhitespaceAndComments = eatWhitespaceAndComments; | ||
| module.exports.escapeIdentifier = escapeIdentifier; | ||
| module.exports.isIdentStartCodePoint = isIdentStartCodePoint; | ||
@@ -1880,1 +2025,2 @@ module.exports.isWhiteSpace = _isWhiteSpace; | ||
| skipCommentsAndEatIdentSequence; | ||
| module.exports.unescapeIdentifier = unescapeIdentifier; |
@@ -15,4 +15,4 @@ /* | ||
| const RuntimeGlobals = require("./RuntimeGlobals"); | ||
| const WebpackError = require("./WebpackError"); | ||
| const ConstDependency = require("./dependencies/ConstDependency"); | ||
| const WebpackError = require("./errors/WebpackError"); | ||
| const BasicEvaluatedExpression = require("./javascript/BasicEvaluatedExpression"); | ||
@@ -323,3 +323,3 @@ const { VariableInfo } = require("./javascript/JavascriptParser"); | ||
| value: toCacheVersion( | ||
| /** @type {Record<string, EXPECTED_ANY>} */ | ||
| /** @type {Record<string, CodeValue>} */ | ||
| (code)[key] | ||
@@ -326,0 +326,0 @@ ) |
@@ -9,3 +9,3 @@ /* | ||
| const RuntimeGlobals = require("../RuntimeGlobals"); | ||
| const UnsupportedFeatureWarning = require("../UnsupportedFeatureWarning"); | ||
| const UnsupportedFeatureWarning = require("../errors/UnsupportedFeatureWarning"); | ||
| const AMDRequireArrayDependency = require("./AMDRequireArrayDependency"); | ||
@@ -12,0 +12,0 @@ const AMDRequireContextDependency = require("./AMDRequireContextDependency"); |
@@ -9,8 +9,69 @@ /* | ||
| const RuntimeGlobals = require("../RuntimeGlobals"); | ||
| const { propertyAccess } = require("../util/property"); | ||
| /** @typedef {import("../Module")} Module */ | ||
| /** @typedef {import("../Module").RuntimeRequirements} RuntimeRequirements */ | ||
| /** @typedef {import("../ModuleGraph")} ModuleGraph */ | ||
| /** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ | ||
| /** @typedef {"exports" | "module.exports" | "this" | "Object.defineProperty(exports)" | "Object.defineProperty(module.exports)" | "Object.defineProperty(this)"} CommonJSDependencyBaseKeywords */ | ||
| /** | ||
| * The well-known name of the ESM named export that, when present, is unwrapped | ||
| * by CommonJS `require()` to match Node.js v23+ `require(esm)` semantics: | ||
| * https://nodejs.org/docs/latest/api/modules.html#loading-ecmascript-modules-using-require | ||
| */ | ||
| const ESM_MODULE_EXPORTS_NAME = "module.exports"; | ||
| /** | ||
| * Whether `require()` of `importedModule` would trigger Node.js's | ||
| * `require(esm)` `"module.exports"` named-export unwrap. This is the | ||
| * usage-independent eligibility check: it only looks at module type and | ||
| * whether the export is declared, so it can be safely used from | ||
| * `getReferencedExports` before usage info is finalized (otherwise the | ||
| * check would be circular — we'd need `"module.exports"` to already be | ||
| * marked used in order to ask whether to mark it used). | ||
| * @param {Module} importedModule the imported module | ||
| * @param {ModuleGraph} moduleGraph the module graph | ||
| * @returns {boolean} true if `require()` should unwrap `"module.exports"` | ||
| */ | ||
| const isRequireEsmModuleExportsModule = (importedModule, moduleGraph) => { | ||
| if (importedModule.getExportsType(moduleGraph, false) !== "namespace") { | ||
| return false; | ||
| } | ||
| const exportsInfo = moduleGraph.getExportsInfo(importedModule); | ||
| const exportInfo = exportsInfo.getReadOnlyExportInfo(ESM_MODULE_EXPORTS_NAME); | ||
| return exportInfo.provided === true; | ||
| }; | ||
| /** | ||
| * When CommonJS `require()` resolves to an ES module that has a named export | ||
| * with the literal string name `"module.exports"`, Node.js returns the value of | ||
| * that export instead of the namespace object. Returns the property-access | ||
| * expression to apply to the require result for that unwrapping, or `null` if | ||
| * the imported module is not eligible (not strictly ESM, or no such export, | ||
| * or the export was tree-shaken away). | ||
| * @param {Module} importedModule the imported module | ||
| * @param {ModuleGraph} moduleGraph the module graph | ||
| * @param {RuntimeSpec} runtime the runtime for which the module is analysed | ||
| * @returns {string | null} property-access expression (e.g. `["module.exports"]`), or `null` | ||
| */ | ||
| const getRequireEsmModuleExportsAccess = ( | ||
| importedModule, | ||
| moduleGraph, | ||
| runtime | ||
| ) => { | ||
| if (!isRequireEsmModuleExportsModule(importedModule, moduleGraph)) { | ||
| return null; | ||
| } | ||
| const exportsInfo = moduleGraph.getExportsInfo(importedModule); | ||
| const usedName = exportsInfo.getUsedName([ESM_MODULE_EXPORTS_NAME], runtime); | ||
| if (usedName === false) return null; | ||
| return propertyAccess(/** @type {readonly string[]} */ (usedName)); | ||
| }; | ||
| module.exports.ESM_MODULE_EXPORTS_NAME = ESM_MODULE_EXPORTS_NAME; | ||
| module.exports.getRequireEsmModuleExportsAccess = | ||
| getRequireEsmModuleExportsAccess; | ||
| /** | ||
| * Returns type and base. | ||
@@ -68,1 +129,3 @@ * @param {CommonJSDependencyBaseKeywords} depBase commonjs dependency base | ||
| }; | ||
| module.exports.isRequireEsmModuleExportsModule = | ||
| isRequireEsmModuleExportsModule; |
@@ -14,3 +14,8 @@ /* | ||
| const { propertyAccess } = require("../util/property"); | ||
| const { handleDependencyBase } = require("./CommonJsDependencyHelpers"); | ||
| const { | ||
| ESM_MODULE_EXPORTS_NAME, | ||
| getRequireEsmModuleExportsAccess, | ||
| handleDependencyBase, | ||
| isRequireEsmModuleExportsModule | ||
| } = require("./CommonJsDependencyHelpers"); | ||
| const ModuleDependency = require("./ModuleDependency"); | ||
@@ -111,2 +116,12 @@ const processExportInfo = require("./processExportInfo"); | ||
| const ids = this.getIds(moduleGraph); | ||
| const importedModule = moduleGraph.getModule(this); | ||
| if ( | ||
| importedModule && | ||
| isRequireEsmModuleExportsModule(importedModule, moduleGraph) | ||
| ) { | ||
| // `require(esm)` unwraps the "module.exports" named export; any | ||
| // further property access lands on that value (which webpack does | ||
| // not model), so only the "module.exports" export is observable. | ||
| return [[ESM_MODULE_EXPORTS_NAME]]; | ||
| } | ||
| const getFullResult = () => { | ||
@@ -164,2 +179,6 @@ if (ids.length === 0) { | ||
| getExports(moduleGraph) { | ||
| const importedModule = moduleGraph.getModule(this); | ||
| const esmUnwrap = | ||
| importedModule && | ||
| isRequireEsmModuleExportsModule(importedModule, moduleGraph); | ||
| if (this.names.length === 1) { | ||
@@ -170,2 +189,7 @@ const ids = this.getIds(moduleGraph); | ||
| if (!from) return; | ||
| const exportChain = esmUnwrap | ||
| ? [ESM_MODULE_EXPORTS_NAME, ...ids] | ||
| : ids.length === 0 | ||
| ? null | ||
| : ids; | ||
| return { | ||
@@ -176,3 +200,3 @@ exports: [ | ||
| from, | ||
| export: ids.length === 0 ? null : ids, | ||
| export: exportChain, | ||
| // we can't mangle names that are in an empty object | ||
@@ -203,2 +227,13 @@ // because one could access the prototype property | ||
| if (!from) return; | ||
| if (esmUnwrap) { | ||
| // Full re-export `module.exports = require("./esm")` of a module | ||
| // with a `"module.exports"` named export: the wrapping module's | ||
| // `module.exports` becomes the unwrapped value, whose own | ||
| // properties webpack cannot enumerate statically. | ||
| return { | ||
| exports: true, | ||
| canMangle: false, | ||
| dependencies: [from.module] | ||
| }; | ||
| } | ||
| const reexportInfo = this.getStarReexports( | ||
@@ -402,10 +437,19 @@ moduleGraph, | ||
| const ids = dep.getIds(moduleGraph); | ||
| const usedImported = moduleGraph | ||
| .getExportsInfo(importedModule) | ||
| .getUsedName(ids, runtime); | ||
| if (usedImported) { | ||
| const comment = equals(usedImported, ids) | ||
| ? "" | ||
| : `${Template.toNormalComment(propertyAccess(ids))} `; | ||
| requireExpr += `${comment}${propertyAccess(usedImported)}`; | ||
| const esmRequireAccess = getRequireEsmModuleExportsAccess( | ||
| importedModule, | ||
| moduleGraph, | ||
| runtime | ||
| ); | ||
| if (esmRequireAccess !== null) { | ||
| requireExpr += `${esmRequireAccess}${propertyAccess(ids)}`; | ||
| } else { | ||
| const usedImported = moduleGraph | ||
| .getExportsInfo(importedModule) | ||
| .getUsedName(ids, runtime); | ||
| if (usedImported) { | ||
| const comment = equals(usedImported, ids) | ||
| ? "" | ||
| : `${Template.toNormalComment(propertyAccess(ids))} `; | ||
| requireExpr += `${comment}${propertyAccess(usedImported)}`; | ||
| } | ||
| } | ||
@@ -412,0 +456,0 @@ } |
@@ -9,4 +9,4 @@ /* | ||
| const RuntimeGlobals = require("../RuntimeGlobals"); | ||
| const formatLocation = require("../formatLocation"); | ||
| const { evaluateToString } = require("../javascript/JavascriptParserHelpers"); | ||
| const formatLocation = require("../util/formatLocation"); | ||
| const { propertyAccess } = require("../util/property"); | ||
@@ -13,0 +13,0 @@ const CommonJsExportRequireDependency = require("./CommonJsExportRequireDependency"); |
@@ -13,2 +13,7 @@ /* | ||
| const { propertyAccess } = require("../util/property"); | ||
| const { | ||
| ESM_MODULE_EXPORTS_NAME, | ||
| getRequireEsmModuleExportsAccess, | ||
| isRequireEsmModuleExportsModule | ||
| } = require("./CommonJsDependencyHelpers"); | ||
| const ModuleDependency = require("./ModuleDependency"); | ||
@@ -59,11 +64,19 @@ | ||
| getReferencedExports(moduleGraph, runtime) { | ||
| if (this.call) { | ||
| const importedModule = moduleGraph.getModule(this); | ||
| if ( | ||
| !importedModule || | ||
| importedModule.getExportsType(moduleGraph, false) !== "namespace" | ||
| ) { | ||
| return [this.names.slice(0, -1)]; | ||
| } | ||
| const importedModule = moduleGraph.getModule(this); | ||
| if ( | ||
| importedModule && | ||
| isRequireEsmModuleExportsModule(importedModule, moduleGraph) | ||
| ) { | ||
| // When `require(esm)` unwraps a `"module.exports"` named export, the | ||
| // user's property access lands on that value (which webpack does not | ||
| // model), so only the "module.exports" export itself is referenced. | ||
| return [[ESM_MODULE_EXPORTS_NAME]]; | ||
| } | ||
| if ( | ||
| this.call && | ||
| (!importedModule || | ||
| importedModule.getExportsType(moduleGraph, false) !== "namespace") | ||
| ) { | ||
| return [this.names.slice(0, -1)]; | ||
| } | ||
| return [this.names]; | ||
@@ -133,2 +146,6 @@ } | ||
| const esmRequireAccess = importedModule | ||
| ? getRequireEsmModuleExportsAccess(importedModule, moduleGraph, runtime) | ||
| : null; | ||
| const { | ||
@@ -145,3 +162,9 @@ trimmedRange: [trimmedRangeStart, trimmedRangeEnd], | ||
| if (importedModule) { | ||
| if (esmRequireAccess !== null) { | ||
| const access = `${esmRequireAccess}${propertyAccess(trimmedIds)}`; | ||
| requireExpr = | ||
| dep.asiSafe === true | ||
| ? `(${requireExpr}${access})` | ||
| : `${requireExpr}${access}`; | ||
| } else if (importedModule) { | ||
| const usedImported = moduleGraph | ||
@@ -148,0 +171,0 @@ .getExportsInfo(importedModule) |
@@ -8,5 +8,5 @@ /* | ||
| const CommentCompilationWarning = require("../CommentCompilationWarning"); | ||
| const RuntimeGlobals = require("../RuntimeGlobals"); | ||
| const UnsupportedFeatureWarning = require("../UnsupportedFeatureWarning"); | ||
| const CommentCompilationWarning = require("../errors/CommentCompilationWarning"); | ||
| const UnsupportedFeatureWarning = require("../errors/UnsupportedFeatureWarning"); | ||
| const { | ||
@@ -164,3 +164,4 @@ evaluateToIdentifier, | ||
| getContext(), | ||
| referencedExports | ||
| referencedExports, | ||
| /** @type {Range} */ (expr.range) | ||
| ); | ||
@@ -167,0 +168,0 @@ dep.loc = /** @type {DependencyLocation} */ (expr.loc); |
@@ -10,7 +10,14 @@ /* | ||
| const makeSerializable = require("../util/makeSerializable"); | ||
| const { | ||
| ESM_MODULE_EXPORTS_NAME, | ||
| getRequireEsmModuleExportsAccess, | ||
| isRequireEsmModuleExportsModule | ||
| } = require("./CommonJsDependencyHelpers"); | ||
| const ModuleDependency = require("./ModuleDependency"); | ||
| const ModuleDependencyTemplateAsId = require("./ModuleDependencyTemplateAsId"); | ||
| /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ | ||
| /** @typedef {import("../Dependency").RawReferencedExports} RawReferencedExports */ | ||
| /** @typedef {import("../Dependency").ReferencedExports} ReferencedExports */ | ||
| /** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ | ||
| /** @typedef {import("../Module")} Module */ | ||
| /** @typedef {import("../ModuleGraph")} ModuleGraph */ | ||
@@ -26,7 +33,14 @@ /** @typedef {import("../javascript/JavascriptParser").Range} Range */ | ||
| * @param {string} request request | ||
| * @param {Range=} range location in source code | ||
| * @param {Range=} range location in source code of the string-literal argument (gets replaced by the module id) | ||
| * @param {string=} context request context | ||
| * @param {RawReferencedExports | null=} referencedExports list of referenced exports | ||
| * @param {Range=} valueRange location in source code of the whole `require(...)` call (for `require(esm)` interop) | ||
| */ | ||
| constructor(request, range, context, referencedExports = null) { | ||
| constructor( | ||
| request, | ||
| range, | ||
| context, | ||
| referencedExports = null, | ||
| valueRange = undefined | ||
| ) { | ||
| super(request); | ||
@@ -36,2 +50,3 @@ this.range = range; | ||
| this.referencedExports = referencedExports; | ||
| this.valueRange = valueRange; | ||
| } | ||
@@ -54,2 +69,11 @@ | ||
| getReferencedExports(moduleGraph, runtime) { | ||
| const importedModule = moduleGraph.getModule(this); | ||
| if ( | ||
| importedModule && | ||
| isRequireEsmModuleExportsModule(importedModule, moduleGraph) | ||
| ) { | ||
| // `require(esm)` will unwrap the "module.exports" named export; only | ||
| // that export is observable through this `require()` call. | ||
| return [[ESM_MODULE_EXPORTS_NAME]]; | ||
| } | ||
| if (!this.referencedExports) return Dependency.EXPORTS_OBJECT_REFERENCED; | ||
@@ -69,2 +93,3 @@ return this.referencedExports.map((name) => ({ | ||
| write(this.referencedExports); | ||
| write(this.valueRange); | ||
| super.serialize(context); | ||
@@ -80,2 +105,3 @@ } | ||
| this.referencedExports = read(); | ||
| this.valueRange = read(); | ||
| super.deserialize(context); | ||
@@ -85,4 +111,41 @@ } | ||
| CommonJsRequireDependency.Template = ModuleDependencyTemplateAsId; | ||
| CommonJsRequireDependency.Template = class CommonJsRequireDependencyTemplate extends ( | ||
| ModuleDependency.Template | ||
| ) { | ||
| /** | ||
| * Applies the plugin by registering its hooks on the compiler. | ||
| * @param {Dependency} dependency the dependency for which the template should be applied | ||
| * @param {ReplaceSource} source the current replace source which can be modified | ||
| * @param {DependencyTemplateContext} templateContext the context object | ||
| * @returns {void} | ||
| */ | ||
| apply( | ||
| dependency, | ||
| source, | ||
| { runtimeTemplate, moduleGraph, chunkGraph, runtime } | ||
| ) { | ||
| const dep = /** @type {CommonJsRequireDependency} */ (dependency); | ||
| if (!dep.range) return; | ||
| const importedModule = /** @type {Module} */ (moduleGraph.getModule(dep)); | ||
| const content = runtimeTemplate.moduleId({ | ||
| module: importedModule, | ||
| chunkGraph, | ||
| request: dep.request, | ||
| weak: dep.weak | ||
| }); | ||
| source.replace(dep.range[0], dep.range[1] - 1, content); | ||
| if (dep.valueRange && importedModule) { | ||
| const access = getRequireEsmModuleExportsAccess( | ||
| importedModule, | ||
| moduleGraph, | ||
| runtime | ||
| ); | ||
| if (access !== null) { | ||
| source.insert(dep.valueRange[1], access); | ||
| } | ||
| } | ||
| } | ||
| }; | ||
| makeSerializable( | ||
@@ -89,0 +152,0 @@ CommonJsRequireDependency, |
@@ -17,3 +17,3 @@ /* | ||
| /** @typedef {import("../ModuleGraph")} ModuleGraph */ | ||
| /** @typedef {import("../WebpackError")} WebpackError */ | ||
| /** @typedef {import("../errors/WebpackError")} WebpackError */ | ||
| /** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ | ||
@@ -20,0 +20,0 @@ /** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ |
@@ -51,3 +51,3 @@ /* | ||
| * @template T | ||
| * @typedef {T extends new (options: ContextDependencyOptions, range: Range, valueRange: Range, ...remains: infer R) => EXPECTED_ANY ? R : []} GetAdditionalDepArgs | ||
| * @typedef {T extends new (options: ContextDependencyOptions, range: Range, valueRange: Range, ...remains: infer R) => ContextDependency ? R : []} GetAdditionalDepArgs | ||
| */ | ||
@@ -54,0 +54,0 @@ |
@@ -9,3 +9,3 @@ /* | ||
| const { fileURLToPath } = require("url"); | ||
| const WebpackError = require("../WebpackError"); | ||
| const WebpackError = require("../errors/WebpackError"); | ||
| const BasicEvaluatedExpression = require("../javascript/BasicEvaluatedExpression"); | ||
@@ -12,0 +12,0 @@ const { VariableInfo } = require("../javascript/JavascriptParser"); |
@@ -8,3 +8,3 @@ /* | ||
| const WebpackError = require("../WebpackError"); | ||
| const WebpackError = require("../errors/WebpackError"); | ||
| const makeSerializable = require("../util/makeSerializable"); | ||
@@ -11,0 +11,0 @@ |
@@ -10,3 +10,3 @@ /* | ||
| const { interpolate } = require("../TemplatedPathPlugin"); | ||
| const WebpackError = require("../WebpackError"); | ||
| const WebpackError = require("../errors/WebpackError"); | ||
| const { cssExportConvention } = require("../util/conventions"); | ||
@@ -18,2 +18,3 @@ const createHash = require("../util/createHash"); | ||
| const nonNumericOnlyHash = require("../util/nonNumericOnlyHash"); | ||
| const { updateHashFromSource } = require("../util/source"); | ||
| const CssIcssImportDependency = require("./CssIcssImportDependency"); | ||
@@ -28,3 +29,4 @@ const NullDependency = require("./NullDependency"); | ||
| /** @typedef {import("../../declarations/WebpackOptions").CssGeneratorLocalIdentName} CssGeneratorLocalIdentName */ | ||
| /** @typedef {import("../CssModule")} CssModule */ | ||
| /** @typedef {import("../css/CssModule")} CssModule */ | ||
| /** @typedef {import("../Module").BuildInfo} BuildInfo */ | ||
| /** @typedef {import("../Dependency")} Dependency */ | ||
@@ -42,6 +44,7 @@ /** @typedef {import("../Dependency").ReferencedExports} ReferencedExports */ | ||
| /** @typedef {import("../ChunkGraph")} ChunkGraph */ | ||
| /** @typedef {import("../Compilation").ModulePathData} ModulePathData */ | ||
| /** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ | ||
| /** @typedef {import("../css/CssParser").Range} Range */ | ||
| /** @typedef {(name: string) => string} ExportsConventionFn */ | ||
| /** @typedef {(name: string) => string | string[]} ExportsConventionFn */ | ||
@@ -111,3 +114,3 @@ /** | ||
| if (source) { | ||
| hash.update(source.buffer()); | ||
| updateHashFromSource(hash, source); | ||
| } | ||
@@ -165,3 +168,3 @@ | ||
| /** @typedef {string | [string, string]} Value */ | ||
| /** @typedef {string | [string, string] | [string, string, string]} Value */ | ||
@@ -173,2 +176,102 @@ // 0 - replace, 1 - replace, 2 - append, 2 - once | ||
| /** | ||
| * Computes the interpolated identifier for `(module, value, exportType)`. | ||
| * Module-level reference so `moduleGraph.cached` can use it as a stable | ||
| * computer key — repeated lookups during a build skip | ||
| * `cssExportConvention`, `getLocalIdent` (with its content / path hashing) | ||
| * and `escapeIdentifier`. | ||
| * @param {ModuleGraph} _moduleGraph module graph (unused, kept for `cached` signature) | ||
| * @param {CssModule} module css module the value resolves in | ||
| * @param {string} value raw value to interpolate | ||
| * @param {ExportType} exportType export type discriminator | ||
| * @param {ChunkGraph} chunkGraph chunk graph | ||
| * @param {RuntimeTemplate} runtimeTemplate runtime template | ||
| * @returns {string} interpolated identifier | ||
| */ | ||
| const computeInterpolatedIdentifier = ( | ||
| _moduleGraph, | ||
| module, | ||
| value, | ||
| exportType, | ||
| chunkGraph, | ||
| runtimeTemplate | ||
| ) => { | ||
| const generator = /** @type {CssGenerator} */ (module.generator); | ||
| const local = cssExportConvention( | ||
| value, | ||
| /** @type {CssGeneratorExportsConvention} */ | ||
| (generator.options.exportsConvention) | ||
| )[0]; | ||
| const prefix = | ||
| exportType === CssIcssExportDependency.EXPORT_TYPE.CUSTOM_VARIABLE | ||
| ? "--" | ||
| : ""; | ||
| return ( | ||
| prefix + | ||
| getCssParser().escapeIdentifier( | ||
| getLocalIdent(local, module, chunkGraph, runtimeTemplate), | ||
| runtimeTemplate.compilation.compiler.root | ||
| ) | ||
| ); | ||
| }; | ||
| /** | ||
| * Top-level computer for `resolve`. Allocates a fresh `seen` set; recursive | ||
| * calls go through the un-cached inner path so cycle detection still works. | ||
| * @param {ModuleGraph} moduleGraph module graph | ||
| * @param {CssModule} module module to search | ||
| * @param {string} localName local name | ||
| * @param {string} importName imported export name | ||
| * @param {string | undefined} request request of the active `@value` import | ||
| * @param {ChunkGraph} chunkGraph chunk graph | ||
| * @param {RuntimeTemplate} runtimeTemplate runtime template | ||
| * @returns {string | undefined} resolved value or undefined | ||
| */ | ||
| const computeResolve = ( | ||
| moduleGraph, | ||
| module, | ||
| localName, | ||
| importName, | ||
| request, | ||
| chunkGraph, | ||
| runtimeTemplate | ||
| ) => | ||
| CssIcssExportDependency.Template._doResolve( | ||
| localName, | ||
| importName, | ||
| /** @type {DependencyTemplateContext} */ | ||
| ( | ||
| /** @type {unknown} */ | ||
| ({ moduleGraph, module, chunkGraph, runtimeTemplate }) | ||
| ), | ||
| request, | ||
| new Set() | ||
| ); | ||
| /** | ||
| * Top-level computer for `resolveReferences`. See `computeResolve`. | ||
| * @param {ModuleGraph} moduleGraph module graph | ||
| * @param {CssIcssExportDependency} dep export dependency | ||
| * @param {CssModule} module module that hosts `dep` | ||
| * @param {ChunkGraph} chunkGraph chunk graph | ||
| * @param {RuntimeTemplate} runtimeTemplate runtime template | ||
| * @returns {string[]} final references, deduplicated | ||
| */ | ||
| const computeResolveReferences = ( | ||
| moduleGraph, | ||
| dep, | ||
| module, | ||
| chunkGraph, | ||
| runtimeTemplate | ||
| ) => | ||
| CssIcssExportDependency.Template._doResolveReferences( | ||
| dep, | ||
| /** @type {DependencyTemplateContext} */ | ||
| ( | ||
| /** @type {unknown} */ | ||
| ({ moduleGraph, module, chunkGraph, runtimeTemplate }) | ||
| ), | ||
| new Set() | ||
| ); | ||
| class CssIcssExportDependency extends NullDependency { | ||
@@ -203,2 +306,6 @@ /** | ||
| this._hashUpdate = undefined; | ||
| /** @type {undefined | string[]} */ | ||
| this._conventionNames = undefined; | ||
| /** @type {undefined | string[]} */ | ||
| this._valueConventionNames = undefined; | ||
| } | ||
@@ -225,2 +332,22 @@ | ||
| /** | ||
| * Memoized `cssExportConvention(this.value, convention)`. Used by every | ||
| * code path that needs the convention-derived aliases of the composed / | ||
| * referenced class: `getReferencedExports`, `getWarnings`, and the template's | ||
| * `getIdentifier`. Caller guarantees `typeof this.value === "string"` — | ||
| * the array form (cross-module references) is resolved separately. | ||
| * @param {CssGeneratorExportsConvention} convention convention of the export name | ||
| * @returns {string[]} convention results | ||
| */ | ||
| getValueConventionNames(convention) { | ||
| if (this._valueConventionNames) { | ||
| return this._valueConventionNames; | ||
| } | ||
| this._valueConventionNames = cssExportConvention( | ||
| /** @type {string} */ (this.value), | ||
| convention | ||
| ); | ||
| return this._valueConventionNames; | ||
| } | ||
| /** | ||
| * Returns list of exports referenced by this dependency | ||
@@ -233,10 +360,22 @@ * @param {ModuleGraph} moduleGraph module graph | ||
| if ( | ||
| this.exportMode === CssIcssExportDependency.EXPORT_MODE.SELF_REFERENCE | ||
| this.exportMode === CssIcssExportDependency.EXPORT_MODE.SELF_REFERENCE && | ||
| typeof this.value === "string" | ||
| ) { | ||
| return [ | ||
| { | ||
| name: [this.name], | ||
| canMangle: true | ||
| } | ||
| ]; | ||
| // `composes: foo;` — the composed class (`this.value`) is the one | ||
| // referenced, not the class doing the composing (`this.name`). Apply | ||
| // the generator's `exportsConvention` so the export names produced | ||
| // by the convention are what the optimizer sees. | ||
| const module = | ||
| /** @type {CssModule | undefined} */ | ||
| (moduleGraph.getParentModule(this)); | ||
| if (!module) return super.getReferencedExports(moduleGraph, runtime); | ||
| const generator = /** @type {CssGenerator} */ (module.generator); | ||
| const names = this.getValueConventionNames( | ||
| /** @type {CssGeneratorExportsConvention} */ | ||
| (generator.options.exportsConvention) | ||
| ); | ||
| return names.map((name) => ({ | ||
| name: [name], | ||
| canMangle: true | ||
| })); | ||
| } | ||
@@ -285,10 +424,26 @@ | ||
| this.exportMode === CssIcssExportDependency.EXPORT_MODE.SELF_REFERENCE && | ||
| !Array.isArray(this.value) | ||
| typeof this.value === "string" | ||
| ) { | ||
| const module = moduleGraph.getParentModule(this); | ||
| const module = | ||
| /** @type {CssModule | undefined} */ | ||
| (moduleGraph.getParentModule(this)); | ||
| if ( | ||
| module && | ||
| !moduleGraph.getExportsInfo(module).isExportProvided(this.value) | ||
| ) { | ||
| if (!module) return null; | ||
| // `ExportsInfo` only stores names produced by `exportsConvention`, | ||
| // so a raw `isExportProvided(this.value)` check is a false-positive | ||
| // for `camel-case-only` / `dashes-only` (and any custom function | ||
| // that drops the original spelling). Treat the composed class as | ||
| // provided if *any* of its convention-produced aliases is provided. | ||
| const generator = /** @type {CssGenerator} */ (module.generator); | ||
| const exportsInfo = moduleGraph.getExportsInfo(module); | ||
| const names = this.getValueConventionNames( | ||
| /** @type {CssGeneratorExportsConvention} */ | ||
| (generator.options.exportsConvention) | ||
| ); | ||
| const isProvided = names.some((name) => | ||
| exportsInfo.isExportProvided(name) | ||
| ); | ||
| if (!isProvided) { | ||
| const error = new WebpackError( | ||
@@ -323,3 +478,7 @@ `Self-referencing name "${this.value}" not found` | ||
| ); | ||
| this._hashUpdate = `exportsConvention|${JSON.stringify(names)}|localIdentName|${JSON.stringify(generator.options.localIdentName)}`; | ||
| // Include all instance state that affects the emitted output — | ||
| // `name`, `value`, `range`, `interpolate`, `exportMode`, | ||
| // `exportType` — so changes like switching `composes: foo` → | ||
| // `composes: bar` or `ONCE` → `APPEND` invalidate caches. | ||
| this._hashUpdate = `exportsConvention|${JSON.stringify(names)}|localIdentName|${JSON.stringify(generator.options.localIdentName)}|value|${JSON.stringify(this.value)}|range|${JSON.stringify(this.range)}|interpolate|${this.interpolate}|exportMode|${this.exportMode}|exportType|${this.exportType}`; | ||
| } | ||
@@ -363,12 +522,48 @@ hash.update(this._hashUpdate); | ||
| ) { | ||
| // TODO looking how to cache | ||
| /** | ||
| * Returns found reference. | ||
| * Returns found reference. The top-level call (no `seen` argument) is | ||
| * memoized via `moduleGraph.cached` keyed by `(module, localName, | ||
| * importName, request, chunkGraph, runtimeTemplate)`. Recursive callers | ||
| * pass `seen` and skip the cache so the cycle guard is preserved — only | ||
| * completed top-level resolutions land in the cache. | ||
| * @param {string} localName local name | ||
| * @param {string} importName import name | ||
| * @param {DependencyTemplateContext} templateContext the context object | ||
| * @param {string | undefined} request user request of the `@value` import that was active when the reference was parsed — used to disambiguate when the same local name is imported from multiple modules | ||
| * @param {Set<CssIcssExportDependency>=} seen seen to prevent cyclical problems | ||
| * @returns {string | undefined} found reference | ||
| */ | ||
| static resolve(localName, importName, templateContext, request, seen) { | ||
| if (seen !== undefined) { | ||
| return CssIcssExportDependencyTemplate._doResolve( | ||
| localName, | ||
| importName, | ||
| templateContext, | ||
| request, | ||
| seen | ||
| ); | ||
| } | ||
| const { moduleGraph, module, chunkGraph, runtimeTemplate } = | ||
| templateContext; | ||
| return moduleGraph.cached( | ||
| computeResolve, | ||
| /** @type {CssModule} */ (module), | ||
| localName, | ||
| importName, | ||
| request, | ||
| chunkGraph, | ||
| runtimeTemplate | ||
| ); | ||
| } | ||
| /** | ||
| * Inner recursive worker for `resolve`. Not memoized — see `resolve`. | ||
| * @param {string} localName local name | ||
| * @param {string} importName import name | ||
| * @param {DependencyTemplateContext} templateContext the context object | ||
| * @param {string | undefined} request user request | ||
| * @param {Set<CssIcssExportDependency>} seen seen to prevent cyclical problems | ||
| * @returns {string | undefined} found reference | ||
| */ | ||
| static resolve(localName, importName, templateContext, seen = new Set()) { | ||
| static _doResolve(localName, importName, templateContext, request, seen) { | ||
| const { moduleGraph } = templateContext; | ||
@@ -378,5 +573,6 @@ const importDep = | ||
| ( | ||
| templateContext.module.dependencies.find( | ||
| (d) => | ||
| d instanceof CssIcssImportDependency && d.localName === localName | ||
| CssIcssExportDependencyTemplate.findImportDep( | ||
| templateContext.module.dependencies, | ||
| localName, | ||
| request | ||
| ) | ||
@@ -405,3 +601,3 @@ ); | ||
| if (Array.isArray(value)) { | ||
| return this.resolve( | ||
| return CssIcssExportDependencyTemplate._doResolve( | ||
| value[0], | ||
@@ -413,2 +609,3 @@ value[1], | ||
| }, | ||
| value[2], | ||
| seen | ||
@@ -429,9 +626,61 @@ ); | ||
| /** | ||
| * Resolves references. | ||
| * Finds the active `CssIcssImportDependency` for a given local name. When a | ||
| * `request` is provided the lookup also requires the import dependency's | ||
| * `request` to match — this lets references that appear between two | ||
| * `@value foo from "..."` declarations resolve through the import that was | ||
| * in scope at the reference site, rather than always picking the first. | ||
| * @param {Iterable<Dependency>} dependencies module dependencies to search | ||
| * @param {string} localName local name | ||
| * @param {string=} request user request of the `@value` import to match | ||
| * @returns {CssIcssImportDependency | undefined} matching import dep, if any | ||
| */ | ||
| static findImportDep(dependencies, localName, request) { | ||
| /** @type {CssIcssImportDependency | undefined} */ | ||
| let firstMatch; | ||
| for (const d of dependencies) { | ||
| if (d instanceof CssIcssImportDependency && d.localName === localName) { | ||
| if (request === undefined) return d; | ||
| if (d.request === request) return d; | ||
| if (firstMatch === undefined) firstMatch = d; | ||
| } | ||
| } | ||
| return firstMatch; | ||
| } | ||
| /** | ||
| * Resolves references. The top-level call (no `seen` argument) is | ||
| * memoized via `moduleGraph.cached`; recursive callers pass `seen` and | ||
| * bypass the cache to keep the cycle guard intact. | ||
| * @param {CssIcssExportDependency} dep value | ||
| * @param {DependencyTemplateContext} templateContext template context | ||
| * @param {Set<CssIcssExportDependency>=} seen to prevent cyclical problems | ||
| * @returns {string[]} final names | ||
| */ | ||
| static resolveReferences(dep, templateContext, seen) { | ||
| if (seen !== undefined) { | ||
| return CssIcssExportDependencyTemplate._doResolveReferences( | ||
| dep, | ||
| templateContext, | ||
| seen | ||
| ); | ||
| } | ||
| const { moduleGraph, module, chunkGraph, runtimeTemplate } = | ||
| templateContext; | ||
| return moduleGraph.cached( | ||
| computeResolveReferences, | ||
| dep, | ||
| /** @type {CssModule} */ (module), | ||
| chunkGraph, | ||
| runtimeTemplate | ||
| ); | ||
| } | ||
| /** | ||
| * Inner recursive worker for `resolveReferences`. Not memoized. | ||
| * @param {CssIcssExportDependency} dep value | ||
| * @param {DependencyTemplateContext} templateContext template context | ||
| * @param {Set<CssIcssExportDependency>} seen to prevent cyclical problems | ||
| * @returns {string[]} final names | ||
| */ | ||
| static resolveReferences(dep, templateContext, seen = new Set()) { | ||
| static _doResolveReferences(dep, templateContext, seen) { | ||
| /** @type {string[]} */ | ||
@@ -447,6 +696,6 @@ const references = []; | ||
| ( | ||
| templateContext.module.dependencies.find( | ||
| (d) => | ||
| d instanceof CssIcssImportDependency && | ||
| d.localName === dep.value[0] | ||
| CssIcssExportDependencyTemplate.findImportDep( | ||
| templateContext.module.dependencies, | ||
| dep.value[0], | ||
| dep.value[2] | ||
| ) | ||
@@ -465,3 +714,3 @@ ); | ||
| const deepReferences = | ||
| CssIcssExportDependencyTemplate.resolveReferences( | ||
| CssIcssExportDependencyTemplate._doResolveReferences( | ||
| d, | ||
@@ -504,3 +753,3 @@ { | ||
| const deepReferences = | ||
| CssIcssExportDependencyTemplate.resolveReferences( | ||
| CssIcssExportDependencyTemplate._doResolveReferences( | ||
| d, | ||
@@ -529,3 +778,7 @@ templateContext, | ||
| /** | ||
| * Returns identifier. | ||
| * Returns identifier. When the dep opts into interpolation the full | ||
| * computation is memoized via `moduleGraph.cached` keyed by | ||
| * `(module, value, exportType, chunkGraph, runtimeTemplate)` so | ||
| * `cssExportConvention` / `getLocalIdent` / `escapeIdentifier` are not | ||
| * re-run for the same identifier during code generation. | ||
| * @param {string} value value to identifier | ||
@@ -538,32 +791,13 @@ * @param {Dependency} dependency the dependency for which the template should be applied | ||
| const dep = /** @type {CssIcssExportDependency} */ (dependency); | ||
| if (dep.interpolate) { | ||
| const { module: m } = templateContext; | ||
| const module = /** @type {CssModule} */ (m); | ||
| const generator = /** @type {CssGenerator} */ (module.generator); | ||
| const local = cssExportConvention( | ||
| value, | ||
| /** @type {CssGeneratorExportsConvention} */ | ||
| (generator.options.exportsConvention) | ||
| )[0]; | ||
| const prefix = | ||
| dep.exportType === CssIcssExportDependency.EXPORT_TYPE.CUSTOM_VARIABLE | ||
| ? "--" | ||
| : ""; | ||
| return ( | ||
| prefix + | ||
| getCssParser().escapeIdentifier( | ||
| getLocalIdent( | ||
| local, | ||
| /** @type {CssModule} */ | ||
| (m), | ||
| templateContext.chunkGraph, | ||
| templateContext.runtimeTemplate | ||
| ) | ||
| ) | ||
| ); | ||
| } | ||
| return value; | ||
| if (!dep.interpolate) return value; | ||
| const { moduleGraph, module, chunkGraph, runtimeTemplate } = | ||
| templateContext; | ||
| return moduleGraph.cached( | ||
| computeInterpolatedIdentifier, | ||
| /** @type {CssModule} */ (module), | ||
| value, | ||
| dep.exportType, | ||
| chunkGraph, | ||
| runtimeTemplate | ||
| ); | ||
| } | ||
@@ -602,3 +836,4 @@ | ||
| dep.value[1], | ||
| templateContext | ||
| templateContext, | ||
| dep.value[2] | ||
| ); | ||
@@ -642,4 +877,11 @@ | ||
| const allNames = new Set([...usedNames, ...names]); | ||
| const unescaped = getCssParser().unescapeIdentifier(value); | ||
| const unescaped = getCssParser().unescapeIdentifier( | ||
| value, | ||
| templateContext.runtimeTemplate.compilation.compiler.root | ||
| ); | ||
| const depLocStart = | ||
| dep.loc && | ||
| /** @type {{ start?: { line: number, column: number } }} */ (dep.loc) | ||
| .start; | ||
| for (const used of allNames) { | ||
@@ -649,2 +891,12 @@ if (dep.exportMode === CssIcssExportDependency.EXPORT_MODE.ONCE) { | ||
| cssData.exports.set(used, unescaped); | ||
| if ( | ||
| depLocStart && | ||
| cssData.exportLocs && | ||
| !cssData.exportLocs.has(used) | ||
| ) { | ||
| cssData.exportLocs.set(used, { | ||
| line: depLocStart.line, | ||
| column: depLocStart.column | ||
| }); | ||
| } | ||
| } else { | ||
@@ -660,2 +912,15 @@ const originalValue = | ||
| ); | ||
| // Record the source location once per export (use the first | ||
| // occurrence — for APPEND/REPLACE this corresponds to the | ||
| // first selector seen, which is a reasonable anchor). | ||
| if ( | ||
| depLocStart && | ||
| cssData.exportLocs && | ||
| !cssData.exportLocs.has(used) | ||
| ) { | ||
| cssData.exportLocs.set(used, { | ||
| line: depLocStart.line, | ||
| column: depLocStart.column | ||
| }); | ||
| } | ||
| } | ||
@@ -662,0 +927,0 @@ } |
@@ -8,3 +8,4 @@ /* | ||
| const WebpackError = require("../WebpackError"); | ||
| const WebpackError = require("../errors/WebpackError"); | ||
| const { cssExportConvention } = require("../util/conventions"); | ||
| const makeSerializable = require("../util/makeSerializable"); | ||
@@ -17,3 +18,4 @@ const CssImportDependency = require("./CssImportDependency"); | ||
| /** @typedef {import("../Module")} Module */ | ||
| /** @typedef {import("../CssModule")} CssModule */ | ||
| /** @typedef {import("../css/CssGenerator")} CssGenerator */ | ||
| /** @typedef {import("../css/CssModule")} CssModule */ | ||
| /** @typedef {import("../ModuleGraph")} ModuleGraph */ | ||
@@ -44,4 +46,24 @@ /** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ | ||
| this.localName = localName; | ||
| /** @type {undefined | string[]} */ | ||
| this._importNameConventionNames = undefined; | ||
| } | ||
| /** | ||
| * Memoized `cssExportConvention(this.importName, convention)`. The target | ||
| * module is fixed for a given dep, so its `exportsConvention` is fixed, | ||
| * so the convention-derived aliases of `importName` can be cached on the dep. | ||
| * @param {CssGeneratorExportsConvention} convention convention from the target module's generator | ||
| * @returns {string[]} convention results | ||
| */ | ||
| getImportNameConventionNames(convention) { | ||
| if (this._importNameConventionNames) { | ||
| return this._importNameConventionNames; | ||
| } | ||
| this._importNameConventionNames = cssExportConvention( | ||
| this.importName, | ||
| convention | ||
| ); | ||
| return this._importNameConventionNames; | ||
| } | ||
| get type() { | ||
@@ -72,8 +94,28 @@ return "css :import"; | ||
| getWarnings(moduleGraph) { | ||
| const module = moduleGraph.getModule(this); | ||
| const module = /** @type {CssModule | undefined} */ ( | ||
| moduleGraph.getModule(this) | ||
| ); | ||
| if ( | ||
| module && | ||
| !moduleGraph.getExportsInfo(module).isExportProvided(this.importName) | ||
| ) { | ||
| if (!module) return null; | ||
| // The target module stores exports under the names produced by its | ||
| // `exportsConvention`, so a raw `isExportProvided(this.importName)` | ||
| // would false-positive against `camel-case-only` / `dashes-only` (and | ||
| // any custom function that drops the original spelling). Expand | ||
| // `importName` through the *target* module's convention and accept | ||
| // if any alias is provided. | ||
| const generator = | ||
| /** @type {CssGenerator | undefined} */ | ||
| (module.generator); | ||
| const convention = | ||
| generator && | ||
| /** @type {CssGeneratorExportsConvention | undefined} */ | ||
| (generator.options && generator.options.exportsConvention); | ||
| const exportsInfo = moduleGraph.getExportsInfo(module); | ||
| const names = convention | ||
| ? this.getImportNameConventionNames(convention) | ||
| : [this.importName]; | ||
| const isProvided = names.some((name) => exportsInfo.isExportProvided(name)); | ||
| if (!isProvided) { | ||
| const error = new WebpackError( | ||
@@ -80,0 +122,0 @@ `Referenced name "${this.importName}" in "${this.userRequest}" not found` |
@@ -33,4 +33,5 @@ /* | ||
| * @param {string=} importName import name when it was imported from other module | ||
| * @param {string=} request request of the `@value` import that was active when this reference was parsed — used to disambiguate when the same local name is imported from multiple modules | ||
| */ | ||
| constructor(localName, range, value, importName) { | ||
| constructor(localName, range, value, importName, request) { | ||
| super(); | ||
@@ -41,2 +42,3 @@ this.localName = localName; | ||
| this.importName = importName; | ||
| this.request = request; | ||
| /** @type {undefined | string} */ | ||
@@ -58,3 +60,6 @@ this._hashUpdate = undefined; | ||
| if (this._hashUpdate === undefined) { | ||
| this._hashUpdate = `${this.range}${this.localName}${this.value || this.importName}`; | ||
| // Concatenate with explicit field separators so adjacent fields | ||
| // can't alias each other (e.g. range `[1,11]` + localName `"foo"` | ||
| // vs range `[1,1]` + localName `"1foo"`). | ||
| this._hashUpdate = `range|${JSON.stringify(this.range)}|localName|${this.localName}|value|${this.value || ""}|importName|${this.importName || ""}|request|${this.request || ""}`; | ||
| } | ||
@@ -74,2 +79,3 @@ hash.update(this._hashUpdate); | ||
| write(this.importName); | ||
| write(this.request); | ||
| super.serialize(context); | ||
@@ -88,2 +94,3 @@ } | ||
| this.importName = read(); | ||
| this.request = read(); | ||
| super.deserialize(context); | ||
@@ -111,3 +118,4 @@ } | ||
| dep.importName, | ||
| templateContext | ||
| templateContext, | ||
| dep.request | ||
| ) | ||
@@ -114,0 +122,0 @@ : dep.value; |
@@ -47,2 +47,10 @@ /* | ||
| /** | ||
| * Returns true if this dependency can be concatenated | ||
| * @returns {boolean} true if this dependency can be concatenated | ||
| */ | ||
| canConcatenate() { | ||
| return true; | ||
| } | ||
| /** | ||
| * Returns an identifier to merge equal requests. | ||
@@ -49,0 +57,0 @@ * @returns {string | null} an identifier to merge equal requests |
@@ -15,5 +15,7 @@ /* | ||
| /** @typedef {import("../CodeGenerationResults")} CodeGenerationResults */ | ||
| /** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ | ||
| /** @typedef {import("../Dependency")} Dependency */ | ||
| /** @typedef {import("../DependencyTemplate").CssDependencyTemplateContext} DependencyTemplateContext */ | ||
| /** @typedef {import("../Module")} Module */ | ||
| /** @typedef {import("../Module").BuildInfo} BuildInfo */ | ||
| /** @typedef {import("../Module").CodeGenerationResult} CodeGenerationResult */ | ||
@@ -24,2 +26,3 @@ /** @typedef {import("../Module").CodeGenerationResultData} CodeGenerationResultData */ | ||
| /** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ | ||
| /** @typedef {import("../util/Hash")} Hash */ | ||
| /** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ | ||
@@ -62,2 +65,23 @@ | ||
| /** | ||
| * Updates the hash with the data contributed by this instance. | ||
| * @param {Hash} hash hash to be updated | ||
| * @param {UpdateHashContext} context context | ||
| * @returns {void} | ||
| */ | ||
| updateHash(hash, context) { | ||
| // The dependency template substitutes the referenced asset's hashed | ||
| // filename into the rendered CSS at code-generation time. Folding the | ||
| // asset module's content hash into the dependency hash ensures the | ||
| // CSS module's hash invalidates — and the CSS chunk's contenthash | ||
| // updates — whenever the referenced asset's content changes. | ||
| const { chunkGraph } = context; | ||
| const module = chunkGraph.moduleGraph.getModule(this); | ||
| if (!module) return; | ||
| const buildInfo = /** @type {BuildInfo | undefined} */ (module.buildInfo); | ||
| if (buildInfo && buildInfo.hash) { | ||
| hash.update(/** @type {string} */ (buildInfo.hash)); | ||
| } | ||
| } | ||
| /** | ||
| * Serializes this instance into the provided serializer context. | ||
@@ -198,3 +222,4 @@ * @param {ObjectSerializerContext} context context | ||
| CssUrlDependency.PUBLIC_PATH_AUTO = "__WEBPACK_CSS_PUBLIC_PATH_AUTO__"; | ||
| CssUrlDependency.PUBLIC_PATH_FULL_HASH = "__WEBPACK_CSS_PUBLIC_PATH_FULL_HASH_"; | ||
| module.exports = CssUrlDependency; |
@@ -8,4 +8,4 @@ /* | ||
| const EnvironmentNotSupportAsyncWarning = require("../EnvironmentNotSupportAsyncWarning"); | ||
| const { JAVASCRIPT_MODULE_TYPE_ESM } = require("../ModuleTypeConstants"); | ||
| const EnvironmentNotSupportAsyncWarning = require("../errors/EnvironmentNotSupportAsyncWarning"); | ||
| const DynamicExports = require("./DynamicExports"); | ||
@@ -12,0 +12,0 @@ const HarmonyCompatibilityDependency = require("./HarmonyCompatibilityDependency"); |
@@ -9,3 +9,3 @@ /* | ||
| const CompatibilityPlugin = require("../CompatibilityPlugin"); | ||
| const WebpackError = require("../WebpackError"); | ||
| const WebpackError = require("../errors/WebpackError"); | ||
| const { getImportAttributes } = require("../javascript/JavascriptParser"); | ||
@@ -148,8 +148,9 @@ const InnerGraph = require("../optimize/InnerGraph"); | ||
| dep.isAnonymousDefault = | ||
| node.type === "ArrowFunctionExpression" || | ||
| ((node.type === "FunctionDeclaration" || | ||
| node.type === "FunctionExpression" || | ||
| node.type === "ClassDeclaration" || | ||
| node.type === "ClassExpression") && | ||
| !node.id); | ||
| this.options.anonymousDefaultExportName !== false && | ||
| (node.type === "ArrowFunctionExpression" || | ||
| ((node.type === "FunctionDeclaration" || | ||
| node.type === "FunctionExpression" || | ||
| node.type === "ClassDeclaration" || | ||
| node.type === "ClassExpression") && | ||
| !node.id)); | ||
| dep.loc = Object.create( | ||
@@ -156,0 +157,0 @@ /** @type {DependencyLocation} */ (statement.loc) |
@@ -146,14 +146,13 @@ /* | ||
| const used = concatenationScope | ||
| ? undefined | ||
| : moduleGraph.getExportsInfo(module).getUsedName("default", runtime); | ||
| if (concatenationScope) { | ||
| concatenationScope.registerExport("default", name); | ||
| } else { | ||
| const used = moduleGraph | ||
| .getExportsInfo(module) | ||
| .getUsedName("default", runtime); | ||
| if (used) { | ||
| /** @type {ExportMap} */ | ||
| const map = new Map(); | ||
| map.set(used, `/* export default binding */ ${name}`); | ||
| initFragments.push(new HarmonyExportInitFragment(exportsName, map)); | ||
| } | ||
| } else if (used) { | ||
| /** @type {ExportMap} */ | ||
| const map = new Map(); | ||
| map.set(used, `/* export default binding */ ${name}`); | ||
| initFragments.push(new HarmonyExportInitFragment(exportsName, map)); | ||
| } | ||
@@ -167,8 +166,13 @@ | ||
| if (typeof declarationId !== "string" && dep.isAnonymousDefault) { | ||
| if ( | ||
| typeof declarationId !== "string" && | ||
| dep.isAnonymousDefault && | ||
| (concatenationScope || used) | ||
| ) { | ||
| // Fix .name for anonymous default export function declarations | ||
| // see test/test262-cases/test/language/module-code/instn-named-bndng-dflt-fun-anon.js cspell:disable-line | ||
| runtimeRequirements.add(RuntimeGlobals.setAnonymousDefaultName); | ||
| initFragments.push( | ||
| new InitFragment( | ||
| `Object.defineProperty(${name}, "name", { value: "default", configurable: true });\n`, | ||
| `${RuntimeGlobals.setAnonymousDefaultName}(${name});\n`, | ||
| InitFragment.STAGE_HARMONY_EXPORTS, | ||
@@ -183,2 +187,3 @@ 2 | ||
| let name = ConcatenationScope.DEFAULT_EXPORT; | ||
| let defaultIsUsed = Boolean(concatenationScope); | ||
| if (runtimeTemplate.supportsConst()) { | ||
@@ -193,2 +198,3 @@ content = `/* harmony default export */ const ${name} = `; | ||
| if (used) { | ||
| defaultIsUsed = true; | ||
| runtimeRequirements.add(RuntimeGlobals.exports); | ||
@@ -211,2 +217,3 @@ /** @type {ExportMap} */ | ||
| if (used) { | ||
| defaultIsUsed = true; | ||
| runtimeRequirements.add(RuntimeGlobals.exports); | ||
@@ -232,9 +239,10 @@ // This is a little bit incorrect as TDZ is not correct, but we can't use const. | ||
| ); | ||
| if (dep.isAnonymousDefault) { | ||
| if (dep.isAnonymousDefault && defaultIsUsed) { | ||
| // Fix .name for anonymous default export expressions | ||
| // see test/test262-cases/test/language/module-code/eval-export-dflt-cls-anon.js cspell:disable-line | ||
| runtimeRequirements.add(RuntimeGlobals.setAnonymousDefaultName); | ||
| source.replace( | ||
| dep.range[1], | ||
| dep.rangeStatement[1] - 0.5, | ||
| `);\n(Object.getOwnPropertyDescriptor(${name}, "name") || {}).writable || Object.defineProperty(${name}, "name", { value: "default", configurable: true });` | ||
| `);\n${RuntimeGlobals.setAnonymousDefaultName}(${name});` | ||
| ); | ||
@@ -241,0 +249,0 @@ } else { |
@@ -11,3 +11,2 @@ /* | ||
| const { UsageState } = require("../ExportsInfo"); | ||
| const HarmonyLinkingError = require("../HarmonyLinkingError"); | ||
| const InitFragment = require("../InitFragment"); | ||
@@ -30,2 +29,3 @@ const RuntimeGlobals = require("../RuntimeGlobals"); | ||
| const HarmonyImportDependency = require("./HarmonyImportDependency"); | ||
| const HarmonyLinkingError = require("./HarmonyLinkingError"); | ||
| const { ImportPhaseUtils } = require("./ImportPhase"); | ||
@@ -55,3 +55,3 @@ const processExportInfo = require("./processExportInfo"); | ||
| /** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ | ||
| /** @typedef {import("../WebpackError")} WebpackError */ | ||
| /** @typedef {import("../errors/WebpackError")} WebpackError */ | ||
| /** @typedef {import("../javascript/JavascriptParser").ImportAttributes} ImportAttributes */ | ||
@@ -134,3 +134,76 @@ /** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ | ||
| const RETURNS_TRUE = () => true; | ||
| /** | ||
| * Detect a per-name cycle when collecting `export *` contributions from | ||
| * `exportInfo`'s module into `parentModule`. The TC39 `ResolveExport` | ||
| * algorithm tracks a `resolveSet` of `(module, exportName)` pairs and | ||
| * returns null when an entry is revisited — letting the `StarExportEntries` | ||
| * loop fall through to a non-cyclic source. Webpack's static export graph | ||
| * does not run that resolution algorithm, so we approximate it: if the | ||
| * imported module's same-named export ultimately re-exports from | ||
| * `parentModule` under the same name, the star contribution is cyclic and | ||
| * must be skipped. The non-cyclic alternative (a sibling `export *` that | ||
| * provides a real binding) then wins. | ||
| * | ||
| * We walk the target chain one hop at a time using `findTarget` with a | ||
| * "match anything" filter so we can guard against namespace targets | ||
| * (`export * as ns from`, where `target.export` is undefined) and against | ||
| * unrelated cycles in the graph that would otherwise loop forever inside | ||
| * `_findTarget`. | ||
| * @param {ModuleGraph} moduleGraph the module graph | ||
| * @param {ExportInfo} exportInfo export info on the imported module | ||
| * @param {Module} parentModule the module that contains the star reexport | ||
| * @returns {boolean} true when this export reexports back to the parent module under the same name | ||
| */ | ||
| const isStarReexportBackToParent = (moduleGraph, exportInfo, parentModule) => { | ||
| // Fast path: probe the first hop directly. The overwhelmingly common case | ||
| // in real builds is a terminal local binding (no `_target`) — `findTarget` | ||
| // returns `undefined` and we exit without allocating a `visited` set. | ||
| const firstTarget = exportInfo.findTarget(moduleGraph, RETURNS_TRUE); | ||
| if (!firstTarget || typeof firstTarget !== "object") return false; | ||
| const name = exportInfo.name; | ||
| if ( | ||
| firstTarget.module === parentModule && | ||
| Array.isArray(firstTarget.export) && | ||
| firstTarget.export.length === 1 && | ||
| firstTarget.export[0] === name | ||
| ) { | ||
| return true; | ||
| } | ||
| if (!Array.isArray(firstTarget.export) || firstTarget.export.length === 0) { | ||
| return false; | ||
| } | ||
| // Multi-hop chain — allocate visited tracking now. The set protects against | ||
| // unrelated cycles in the graph that would otherwise spin inside | ||
| // `_findTarget` (its `alreadyVisited` is only seeded for the entry node). | ||
| let current = moduleGraph | ||
| .getExportsInfo(firstTarget.module) | ||
| .getReadOnlyExportInfo(firstTarget.export[0]); | ||
| /** @type {Set<ExportInfo>} */ | ||
| const visited = new Set([exportInfo, current]); | ||
| for (;;) { | ||
| const target = current.findTarget(moduleGraph, RETURNS_TRUE); | ||
| if (!target || typeof target !== "object") return false; | ||
| if ( | ||
| target.module === parentModule && | ||
| Array.isArray(target.export) && | ||
| target.export.length === 1 && | ||
| target.export[0] === name | ||
| ) { | ||
| return true; | ||
| } | ||
| if (!Array.isArray(target.export) || target.export.length === 0) { | ||
| return false; | ||
| } | ||
| const next = moduleGraph | ||
| .getExportsInfo(target.module) | ||
| .getReadOnlyExportInfo(target.export[0]); | ||
| if (visited.has(next)) return false; | ||
| visited.add(next); | ||
| current = next; | ||
| } | ||
| }; | ||
| /** | ||
| * Determine export assignments. | ||
@@ -156,2 +229,7 @@ * @param {ModuleGraph} moduleGraph module graph | ||
| const referenceDep = dependencies[0] || additionalDependency; | ||
| const parentModule = referenceDep | ||
| ? moduleGraph.getParentModule(referenceDep) | ||
| : null; | ||
| for (const dep of dependencies) { | ||
@@ -167,3 +245,7 @@ const i = dependencyIndices.length; | ||
| exportInfo.name !== "default" && | ||
| !names.has(exportInfo.name) | ||
| !names.has(exportInfo.name) && | ||
| !( | ||
| parentModule && | ||
| isStarReexportBackToParent(moduleGraph, exportInfo, parentModule) | ||
| ) | ||
| ) { | ||
@@ -544,2 +626,6 @@ names.add(exportInfo.name); | ||
| const parentModule = /** @type {Module} */ ( | ||
| moduleGraph.getParentModule(this) | ||
| ); | ||
| if (noExtraImports) { | ||
@@ -554,2 +640,5 @@ for (const exportInfo of exportsInfo.orderedExports) { | ||
| if (hiddenExports !== undefined && hiddenExports.has(name)) { | ||
| // Earlier star deps already provided this name non-cyclically | ||
| // (`determineExportAssignments` filters cyclic candidates), so | ||
| // the cycle check below would be wasted work. | ||
| /** @type {Hidden} */ | ||
@@ -559,2 +648,11 @@ (hidden).add(name); | ||
| } | ||
| if ( | ||
| isStarReexportBackToParent( | ||
| moduleGraph, | ||
| importedExportInfo, | ||
| parentModule | ||
| ) | ||
| ) { | ||
| continue; | ||
| } | ||
| exports.add(name); | ||
@@ -576,2 +674,11 @@ if (importedExportInfo.provided === true) continue; | ||
| } | ||
| if ( | ||
| isStarReexportBackToParent( | ||
| moduleGraph, | ||
| importedExportInfo, | ||
| parentModule | ||
| ) | ||
| ) { | ||
| continue; | ||
| } | ||
| exports.add(name); | ||
@@ -578,0 +685,0 @@ if (importedExportInfo.provided === true) continue; |
@@ -10,3 +10,2 @@ /* | ||
| const Dependency = require("../Dependency"); | ||
| const HarmonyLinkingError = require("../HarmonyLinkingError"); | ||
| const InitFragment = require("../InitFragment"); | ||
@@ -16,2 +15,3 @@ const Template = require("../Template"); | ||
| const { filterRuntime, mergeRuntime } = require("../util/runtime"); | ||
| const HarmonyLinkingError = require("./HarmonyLinkingError"); | ||
| const { ImportPhase, ImportPhaseUtils } = require("./ImportPhase"); | ||
@@ -28,3 +28,3 @@ const ModuleDependency = require("./ModuleDependency"); | ||
| /** @typedef {import("../ModuleGraph")} ModuleGraph */ | ||
| /** @typedef {import("../WebpackError")} WebpackError */ | ||
| /** @typedef {import("../errors/WebpackError")} WebpackError */ | ||
| /** @typedef {import("../javascript/JavascriptParser").ImportAttributes} ImportAttributes */ | ||
@@ -119,2 +119,10 @@ /** @typedef {import("./ImportPhase").ImportPhaseType} ImportPhaseType */ | ||
| /** | ||
| * Returns true if this dependency can be concatenated | ||
| * @returns {boolean} true if this dependency can be concatenated | ||
| */ | ||
| canConcatenate() { | ||
| return true; | ||
| } | ||
| /** | ||
| * Returns an identifier to merge equal requests. | ||
@@ -121,0 +129,0 @@ * @returns {string | null} an identifier to merge equal requests |
@@ -9,3 +9,3 @@ /* | ||
| const HotModuleReplacementPlugin = require("../HotModuleReplacementPlugin"); | ||
| const WebpackError = require("../WebpackError"); | ||
| const WebpackError = require("../errors/WebpackError"); | ||
| const { | ||
@@ -417,2 +417,23 @@ VariableInfo, | ||
| ); | ||
| // Per the TC39 import-defer spec, [[Set]] on a Module Namespace | ||
| // Exotic Object returns false without triggering evaluation. The | ||
| // default expressionMemberChain path produces `<importVar>.a.foo` | ||
| // whose `.a` getter eagerly requires (and thus evaluates) the | ||
| // deferred module. For top-level `ns.foo = value`, walk only the | ||
| // bare `ns` identifier so it gets replaced with the deferred | ||
| // namespace proxy (whose set trap returns false), and leave the | ||
| // `.foo = value` part as plain code. | ||
| parser.hooks.assignMemberChain | ||
| .for(harmonySpecifierTag) | ||
| .tap(PLUGIN_NAME, (expression, members) => { | ||
| const settings = /** @type {HarmonySettings} */ (parser.currentTagData); | ||
| if (!ImportPhaseUtils.isDefer(settings.phase)) return; | ||
| if (expression.operator !== "=") return; | ||
| if (members.length !== 1) return; | ||
| const left = /** @type {MemberExpression} */ (expression.left); | ||
| if (left.object.type !== "Identifier") return; | ||
| parser.walkExpression(expression.right); | ||
| parser.walkExpression(left.object); | ||
| return true; | ||
| }); | ||
| const { hotAcceptCallback, hotAcceptWithoutCallback } = | ||
@@ -419,0 +440,0 @@ HotModuleReplacementPlugin.getParserHooks(parser); |
@@ -30,3 +30,3 @@ /* | ||
| /** @typedef {import("../ModuleGraphConnection").ConnectionState} ConnectionState */ | ||
| /** @typedef {import("../WebpackError")} WebpackError */ | ||
| /** @typedef {import("../errors/WebpackError")} WebpackError */ | ||
| /** @typedef {import("../javascript/JavascriptParser").DestructuringAssignmentProperties} DestructuringAssignmentProperties */ | ||
@@ -33,0 +33,0 @@ /** @typedef {import("../javascript/JavascriptParser").ImportAttributes} ImportAttributes */ |
@@ -8,3 +8,3 @@ /* | ||
| const WebpackError = require("../WebpackError"); | ||
| const WebpackError = require("../errors/WebpackError"); | ||
| const { | ||
@@ -11,0 +11,0 @@ evaluateToIdentifier |
@@ -9,4 +9,4 @@ /* | ||
| const AsyncDependenciesBlock = require("../AsyncDependenciesBlock"); | ||
| const CommentCompilationWarning = require("../CommentCompilationWarning"); | ||
| const UnsupportedFeatureWarning = require("../UnsupportedFeatureWarning"); | ||
| const CommentCompilationWarning = require("../errors/CommentCompilationWarning"); | ||
| const UnsupportedFeatureWarning = require("../errors/UnsupportedFeatureWarning"); | ||
| const { | ||
@@ -13,0 +13,0 @@ VariableInfo, |
@@ -11,3 +11,3 @@ /* | ||
| const getCommentCompilationWarning = memoize(() => | ||
| require("../CommentCompilationWarning") | ||
| require("../errors/CommentCompilationWarning") | ||
| ); | ||
@@ -14,0 +14,0 @@ |
@@ -8,3 +8,3 @@ /* | ||
| const WebpackError = require("../WebpackError"); | ||
| const WebpackError = require("../errors/WebpackError"); | ||
| const { | ||
@@ -11,0 +11,0 @@ evaluateToString, |
@@ -13,3 +13,3 @@ /* | ||
| const RuntimeGlobals = require("../RuntimeGlobals"); | ||
| const WebpackError = require("../WebpackError"); | ||
| const WebpackError = require("../errors/WebpackError"); | ||
| const { | ||
@@ -16,0 +16,0 @@ evaluateToString, |
@@ -15,3 +15,3 @@ /* | ||
| /** @typedef {import("../ModuleGraph")} ModuleGraph */ | ||
| /** @typedef {import("../WebpackError")} WebpackError */ | ||
| /** @typedef {import("../errors/WebpackError")} WebpackError */ | ||
| /** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ | ||
@@ -18,0 +18,0 @@ /** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ |
@@ -10,3 +10,2 @@ /* | ||
| const AsyncDependenciesBlock = require("../AsyncDependenciesBlock"); | ||
| const CommentCompilationWarning = require("../CommentCompilationWarning"); | ||
| const { | ||
@@ -16,3 +15,4 @@ JAVASCRIPT_MODULE_TYPE_AUTO, | ||
| } = require("../ModuleTypeConstants"); | ||
| const UnsupportedFeatureWarning = require("../UnsupportedFeatureWarning"); | ||
| const CommentCompilationWarning = require("../errors/CommentCompilationWarning"); | ||
| const UnsupportedFeatureWarning = require("../errors/UnsupportedFeatureWarning"); | ||
| const EnableChunkLoadingPlugin = require("../javascript/EnableChunkLoadingPlugin"); | ||
@@ -19,0 +19,0 @@ const { equals } = require("../util/ArrayHelpers"); |
+22
-1
@@ -17,3 +17,3 @@ /* | ||
| /** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */ | ||
| /** @typedef {import("./WebpackError")} WebpackError */ | ||
| /** @typedef {import("./errors/WebpackError")} WebpackError */ | ||
| /** @typedef {import("./serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ | ||
@@ -330,2 +330,10 @@ /** @typedef {import("./serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ | ||
| /** | ||
| * Returns true if this dependency can be concatenated | ||
| * @returns {boolean} true if this dependency can be concatenated | ||
| */ | ||
| canConcatenate() { | ||
| return false; | ||
| } | ||
| /** | ||
| * Serializes this instance into the provided serializer context. | ||
@@ -399,2 +407,15 @@ * @param {ObjectSerializerContext} context context | ||
| // TODO in webpack 6, call canConcatenate() directly on the dependency instance instead of using this static method. | ||
| /** | ||
| * Returns true if the dependency can be concatenated (scope hoisting). | ||
| * @param {Dependency} dependency dep | ||
| * @returns {boolean} true if this dependency supports concatenation | ||
| */ | ||
| Dependency.canConcatenate = (dependency) => { | ||
| if (typeof dependency.canConcatenate === "function") { | ||
| return dependency.canConcatenate(); | ||
| } | ||
| return false; | ||
| }; | ||
| // TODO remove in webpack 6 | ||
@@ -401,0 +422,0 @@ Object.defineProperty(Dependency.prototype, "disconnect", { |
@@ -55,2 +55,3 @@ /* | ||
| * @property {Map<string, string>} exports the css exports | ||
| * @property {Map<string, { line: number, column: number }>=} exportLocs source position (line is 1-based, column is 0-based) of each export's defining identifier in the original CSS, used to emit fine-grained JS-to-CSS source mappings | ||
| */ | ||
@@ -71,3 +72,3 @@ | ||
| apply(dependency, source, templateContext) { | ||
| const AbstractMethodError = require("./AbstractMethodError"); | ||
| const AbstractMethodError = require("./errors/AbstractMethodError"); | ||
@@ -74,0 +75,0 @@ throw new AbstractMethodError(); |
@@ -9,3 +9,3 @@ /* | ||
| const DefinePlugin = require("./DefinePlugin"); | ||
| const WebpackError = require("./WebpackError"); | ||
| const WebpackError = require("./errors/WebpackError"); | ||
@@ -12,0 +12,0 @@ /** @typedef {import("./Compiler")} Compiler */ |
@@ -8,3 +8,3 @@ /* | ||
| const WebpackError = require("../WebpackError"); | ||
| const WebpackError = require("./WebpackError"); | ||
@@ -11,0 +11,0 @@ /** @typedef {import("../Module")} Module */ |
@@ -106,13 +106,8 @@ /* | ||
| if (m instanceof NormalModule) { | ||
| const module = /** @type {NormalModule} */ (m); | ||
| if (!matchModule(module.resource)) { | ||
| if (!matchModule(m.resource)) { | ||
| return result(source); | ||
| } | ||
| } else if (m instanceof ConcatenatedModule) { | ||
| const concatModule = /** @type {ConcatenatedModule} */ (m); | ||
| if (concatModule.rootModule instanceof NormalModule) { | ||
| const module = /** @type {NormalModule} */ ( | ||
| concatModule.rootModule | ||
| ); | ||
| if (!matchModule(module.resource)) { | ||
| if (m.rootModule instanceof NormalModule) { | ||
| if (!matchModule(m.rootModule.resource)) { | ||
| return result(source); | ||
@@ -150,5 +145,9 @@ } | ||
| const root = compiler.root; | ||
| const cachedAbsolutify = makePathsAbsolute.bindContextCache( | ||
| context, | ||
| root | ||
| ); | ||
| const modules = sourceMap.sources.map((source) => { | ||
| if (!source.startsWith("webpack://")) return source; | ||
| source = makePathsAbsolute(context, source.slice(10), root); | ||
| source = cachedAbsolutify(source.slice(10)); | ||
| const module = compilation.findModule(source); | ||
@@ -155,0 +154,0 @@ return module || source; |
+76
-15
@@ -11,3 +11,2 @@ /* | ||
| const ConcatenationScope = require("./ConcatenationScope"); | ||
| const EnvironmentNotSupportAsyncWarning = require("./EnvironmentNotSupportAsyncWarning"); | ||
| const { UsageState } = require("./ExportsInfo"); | ||
@@ -26,3 +25,5 @@ const InitFragment = require("./InitFragment"); | ||
| const { DEFAULTS } = require("./config/defaults"); | ||
| const { ImportPhaseUtils } = require("./dependencies/ImportPhase"); | ||
| const StaticExportsDependency = require("./dependencies/StaticExportsDependency"); | ||
| const EnvironmentNotSupportAsyncWarning = require("./errors/EnvironmentNotSupportAsyncWarning"); | ||
| const createHash = require("./util/createHash"); | ||
@@ -67,2 +68,3 @@ const extractUrlAndGlobal = require("./util/extractUrlAndGlobal"); | ||
| /** @typedef {import("./javascript/JavascriptParser").ImportAttributes} ImportAttributes */ | ||
| /** @typedef {import("./dependencies/ImportPhase").ImportPhaseType} ImportPhaseType */ | ||
| /** @typedef {import("./serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ | ||
@@ -74,3 +76,3 @@ /** @typedef {import("./serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ | ||
| /** @typedef {{ attributes?: ImportAttributes, externalType: "import" | "module" | undefined }} ImportDependencyMeta */ | ||
| /** @typedef {{ attributes?: ImportAttributes, phase?: ImportPhaseType, externalType: "import" | "module" | undefined }} ImportDependencyMeta */ | ||
| /** @typedef {{ layer?: string, supports?: string, media?: string }} CssImportDependencyMeta */ | ||
@@ -209,6 +211,6 @@ /** @typedef {{ sourceType: "css-url" }} AssetDependencyMeta */ | ||
| ) => { | ||
| const importName = runtimeTemplate.outputOptions.importFunctionName; | ||
| const baseImportName = runtimeTemplate.outputOptions.importFunctionName; | ||
| if ( | ||
| !runtimeTemplate.supportsDynamicImport() && | ||
| (importName === "import" || importName === "module-import") | ||
| (baseImportName === "import" || baseImportName === "module-import") | ||
| ) { | ||
@@ -219,2 +221,12 @@ throw new Error( | ||
| } | ||
| const phase = dependencyMeta && dependencyMeta.phase; | ||
| // `import.defer(…)` and `import.source(…)` are only valid forms of the | ||
| // native `import(…)` function, so we only emit the phase suffix when the | ||
| // importFunctionName is the default `"import"`. | ||
| const importName = | ||
| baseImportName === "import" && ImportPhaseUtils.isDefer(phase) | ||
| ? "import.defer" | ||
| : baseImportName === "import" && ImportPhaseUtils.isSource(phase) | ||
| ? "import.source" | ||
| : baseImportName; | ||
| const attributes = | ||
@@ -302,3 +314,5 @@ dependencyMeta && dependencyMeta.attributes | ||
| 0, | ||
| `external module import ${ident} ${imported === true ? imported : imported.join(" ")}` | ||
| `external module import ${ident} ${ | ||
| imported === true ? imported : imported.join(" ") | ||
| }` | ||
| ); | ||
@@ -342,4 +356,3 @@ this._ident = ident; | ||
| dependencyMeta && dependencyMeta.attributes | ||
| ? dependencyMeta.attributes._isLegacyAssert && | ||
| dependencyMeta.attributes._isLegacyAssert | ||
| ? dependencyMeta.attributes._isLegacyAssert | ||
| ? ` assert ${JSON.stringify( | ||
@@ -351,11 +364,23 @@ dependencyMeta.attributes, | ||
| : ""; | ||
| const phase = dependencyMeta && dependencyMeta.phase; | ||
| let content = ""; | ||
| if (imported === true) { | ||
| // namespace | ||
| content = `import * as ${identifier} from ${JSON.stringify(request)}${ | ||
| attributes | ||
| };\n`; | ||
| const phaseKeyword = ImportPhaseUtils.isDefer(phase) ? "defer " : ""; | ||
| content = `import ${phaseKeyword}* as ${identifier} from ${JSON.stringify( | ||
| request | ||
| )}${attributes};\n`; | ||
| } else if (imported.length === 0) { | ||
| // just import, no use | ||
| content = `import ${JSON.stringify(request)}${attributes};\n`; | ||
| } else if ( | ||
| ImportPhaseUtils.isSource(phase) && | ||
| imported.length === 1 && | ||
| imported[0][0] === "default" | ||
| ) { | ||
| // `import source x from "…"` — the source-phase form binds the source | ||
| // object directly to a single identifier (no namespace, no destructuring). | ||
| content = `import source ${imported[0][1]} from ${JSON.stringify( | ||
| request | ||
| )}${attributes};\n`; | ||
| } else { | ||
@@ -481,2 +506,3 @@ content = `import { ${imported | ||
| ) => { | ||
| const phase = dependencyMeta && dependencyMeta.phase; | ||
| /** @type {Imported} */ | ||
@@ -510,2 +536,10 @@ let imported = true; | ||
| // `import defer …` is only valid as `import defer * as ns from "…"`, so | ||
| // keep the namespace form even if usage analysis would otherwise narrow | ||
| // the import down to specific names. Defer + concatenation is semantically | ||
| // at odds (lazy vs. eager), so we preserve the user-written shape here. | ||
| if (ImportPhaseUtils.isDefer(phase)) { | ||
| imported = true; | ||
| } | ||
| const initFragment = new ModuleExternalInitFragment( | ||
@@ -765,3 +799,17 @@ moduleAndSpecifiers[0], | ||
| identifier() { | ||
| return `external ${this._resolveExternalType(this.externalType)} ${JSON.stringify(this.request)}`; | ||
| let id = `external ${this._resolveExternalType( | ||
| this.externalType | ||
| )} ${JSON.stringify(this.request)}`; | ||
| const meta = /** @type {ImportDependencyMeta | undefined} */ ( | ||
| this.dependencyMeta | ||
| ); | ||
| if (meta) { | ||
| if (meta.phase) { | ||
| id += `|phase=${ImportPhaseUtils.stringify(meta.phase)}`; | ||
| } | ||
| if (meta.attributes) { | ||
| id += `|attributes=${JSON.stringify(meta.attributes)}`; | ||
| } | ||
| } | ||
| return id; | ||
| } | ||
@@ -1141,3 +1189,5 @@ | ||
| } else if (concatenationScope) { | ||
| sourceString = `${runtimeTemplate.renderConst()} ${ConcatenationScope.NAMESPACE_OBJECT_EXPORT} = ${sourceString};`; | ||
| sourceString = `${runtimeTemplate.renderConst()} ${ | ||
| ConcatenationScope.NAMESPACE_OBJECT_EXPORT | ||
| } = ${sourceString};`; | ||
| concatenationScope.registerNamespaceExport( | ||
@@ -1210,6 +1260,17 @@ ConcatenationScope.NAMESPACE_OBJECT_EXPORT | ||
| hash.update( | ||
| `${this._resolveExternalType(this.externalType)}${JSON.stringify(this.request)}${this.isOptional( | ||
| chunkGraph.moduleGraph | ||
| )}` | ||
| `${this._resolveExternalType(this.externalType)}${JSON.stringify( | ||
| this.request | ||
| )}${this.isOptional(chunkGraph.moduleGraph)}` | ||
| ); | ||
| const meta = /** @type {ImportDependencyMeta | undefined} */ ( | ||
| this.dependencyMeta | ||
| ); | ||
| if (meta) { | ||
| if (meta.phase) { | ||
| hash.update(`|phase=${ImportPhaseUtils.stringify(meta.phase)}`); | ||
| } | ||
| if (meta.attributes) { | ||
| hash.update(`|attributes=${JSON.stringify(meta.attributes)}`); | ||
| } | ||
| } | ||
| super.updateHash(hash, context); | ||
@@ -1216,0 +1277,0 @@ } |
@@ -196,2 +196,7 @@ /* | ||
| attributes: dependency.attributes, | ||
| phase: | ||
| dependency instanceof HarmonyImportDependency || | ||
| dependency instanceof ImportDependency | ||
| ? dependency.phase | ||
| : undefined, | ||
| externalType | ||
@@ -198,0 +203,0 @@ }; |
+3
-3
@@ -77,3 +77,3 @@ /* | ||
| getTypes(module) { | ||
| const AbstractMethodError = require("./AbstractMethodError"); | ||
| const AbstractMethodError = require("./errors/AbstractMethodError"); | ||
@@ -92,3 +92,3 @@ throw new AbstractMethodError(); | ||
| getSize(module, type) { | ||
| const AbstractMethodError = require("./AbstractMethodError"); | ||
| const AbstractMethodError = require("./errors/AbstractMethodError"); | ||
@@ -110,3 +110,3 @@ throw new AbstractMethodError(); | ||
| ) { | ||
| const AbstractMethodError = require("./AbstractMethodError"); | ||
| const AbstractMethodError = require("./errors/AbstractMethodError"); | ||
@@ -113,0 +113,0 @@ throw new AbstractMethodError(); |
@@ -21,3 +21,2 @@ /* | ||
| const RuntimeGlobals = require("./RuntimeGlobals"); | ||
| const WebpackError = require("./WebpackError"); | ||
| const { chunkHasCss } = require("./css/CssModulesPlugin"); | ||
@@ -29,2 +28,3 @@ const ConstDependency = require("./dependencies/ConstDependency"); | ||
| const ModuleHotDeclineDependency = require("./dependencies/ModuleHotDeclineDependency"); | ||
| const WebpackError = require("./errors/WebpackError"); | ||
| const HotModuleReplacementRuntimeModule = require("./hmr/HotModuleReplacementRuntimeModule"); | ||
@@ -35,2 +35,3 @@ const JavascriptParser = require("./javascript/JavascriptParser"); | ||
| } = require("./javascript/JavascriptParserHelpers"); | ||
| const ConcatenatedModule = require("./optimize/ConcatenatedModule"); | ||
| const { find, isSubset } = require("./util/SetHelpers"); | ||
@@ -395,9 +396,26 @@ const TupleSet = require("./util/TupleSet"); | ||
| records.chunkModuleIds[chunkId] = Array.from( | ||
| chunkGraph.getOrderedChunkModulesIterable( | ||
| chunk, | ||
| compareModulesById(chunkGraph) | ||
| ), | ||
| (m) => /** @type {ModuleId} */ (chunkGraph.getModuleId(m)) | ||
| ); | ||
| /** @type {ModuleId[]} */ | ||
| const moduleIds = []; | ||
| for (const m of chunkGraph.getOrderedChunkModulesIterable( | ||
| chunk, | ||
| compareModulesById(chunkGraph) | ||
| )) { | ||
| moduleIds.push( | ||
| /** @type {ModuleId} */ (chunkGraph.getModuleId(m)) | ||
| ); | ||
| if (m instanceof ConcatenatedModule && m.modules) { | ||
| for (const innerModule of m.modules) { | ||
| if ( | ||
| innerModule.buildMeta && | ||
| innerModule.buildMeta.needIdInConcatenation | ||
| ) { | ||
| const innerId = chunkGraph.getModuleId(innerModule); | ||
| if (innerId !== null) { | ||
| moduleIds.push(innerId); | ||
| } | ||
| } | ||
| } | ||
| } | ||
| } | ||
| records.chunkModuleIds[chunkId] = moduleIds; | ||
| } | ||
@@ -404,0 +422,0 @@ }); |
@@ -266,3 +266,4 @@ /* | ||
| // CSS modules need IDs even when not in chunks, for generating CSS class names(i.e. [id]-[local]) | ||
| /** @type {BuildMeta} */ (module.buildMeta).isCSSModule) | ||
| /** @type {BuildMeta} */ (module.buildMeta).isCssModule || | ||
| /** @type {BuildMeta} */ (module.buildMeta).needIdInConcatenation) | ||
| ) { | ||
@@ -269,0 +270,0 @@ modules.push(module); |
@@ -69,3 +69,4 @@ /* | ||
| compiler.validate( | ||
| require("../schemas/plugins/IgnorePlugin.json"), | ||
| /** @type {EXPECTED_ANY} */ | ||
| (require("../schemas/plugins/IgnorePlugin.json")), | ||
| this.options, | ||
@@ -72,0 +73,0 @@ { |
+34
-15
@@ -163,3 +163,5 @@ /* | ||
| const validateSchema = require("./validateSchema"); | ||
| const webpackOptionsSchema = require("../schemas/WebpackOptions.json"); | ||
| const webpackOptionsSchema = | ||
| /** @type {EXPECTED_ANY} */ | ||
| (require("../schemas/WebpackOptions.json")); | ||
@@ -226,14 +228,5 @@ return (options) => validateSchema(webpackOptionsSchema, options); | ||
| }, | ||
| get DelegatedPlugin() { | ||
| return require("./DelegatedPlugin"); | ||
| }, | ||
| get Dependency() { | ||
| return require("./Dependency"); | ||
| }, | ||
| get DllPlugin() { | ||
| return require("./DllPlugin"); | ||
| }, | ||
| get DllReferencePlugin() { | ||
| return require("./DllReferencePlugin"); | ||
| }, | ||
| get DynamicEntryPlugin() { | ||
@@ -288,5 +281,2 @@ return require("./DynamicEntryPlugin"); | ||
| }, | ||
| get LibManifestPlugin() { | ||
| return require("./LibManifestPlugin"); | ||
| }, | ||
| get LibraryTemplatePlugin() { | ||
@@ -382,3 +372,3 @@ return util.deprecate( | ||
| get WebpackError() { | ||
| return require("./WebpackError"); | ||
| return require("./errors/WebpackError"); | ||
| }, | ||
@@ -395,3 +385,3 @@ get WebpackOptionsApply() { | ||
| }, | ||
| // TODO webpack 6 deprecate | ||
| // TODO webpack 6 remove | ||
| get WebpackOptionsValidationError() { | ||
@@ -612,2 +602,31 @@ return require("schema-utils").ValidationError; | ||
| // TODO remove in webpack 6 in favor of `dll` scope | ||
| get DelegatedPlugin() { | ||
| return require("./dll/DelegatedPlugin"); | ||
| }, | ||
| get DllPlugin() { | ||
| return require("./dll/DllPlugin"); | ||
| }, | ||
| get DllReferencePlugin() { | ||
| return require("./dll/DllReferencePlugin"); | ||
| }, | ||
| get LibManifestPlugin() { | ||
| return require("./dll/LibManifestPlugin"); | ||
| }, | ||
| dll: { | ||
| get DelegatedPlugin() { | ||
| return require("./dll/DelegatedPlugin"); | ||
| }, | ||
| get DllPlugin() { | ||
| return require("./dll/DllPlugin"); | ||
| }, | ||
| get DllReferencePlugin() { | ||
| return require("./dll/DllReferencePlugin"); | ||
| }, | ||
| get LibManifestPlugin() { | ||
| return require("./dll/LibManifestPlugin"); | ||
| } | ||
| }, | ||
| container: { | ||
@@ -614,0 +633,0 @@ get ContainerPlugin() { |
@@ -8,4 +8,4 @@ /* | ||
| const UnsupportedFeatureWarning = require("../UnsupportedFeatureWarning"); | ||
| const ConstDependency = require("../dependencies/ConstDependency"); | ||
| const UnsupportedFeatureWarning = require("../errors/UnsupportedFeatureWarning"); | ||
| const BasicEvaluatedExpression = require("./BasicEvaluatedExpression"); | ||
@@ -12,0 +12,0 @@ |
@@ -13,3 +13,3 @@ /* | ||
| /** @typedef {import("../../declarations/plugins/JsonModulesPluginParser").JsonModulesPluginParserOptions} JsonModulesPluginParserOptions */ | ||
| /** @typedef {import("../../declarations/WebpackOptions").JsonParserOptions} JsonParserOptions */ | ||
| /** @typedef {import("../Module").BuildInfo} BuildInfo */ | ||
@@ -32,7 +32,7 @@ /** @typedef {import("../Module").BuildMeta} BuildMeta */ | ||
| * Creates an instance of JsonParser. | ||
| * @param {JsonModulesPluginParserOptions} options parser options | ||
| * @param {JsonParserOptions} options parser options | ||
| */ | ||
| constructor(options = {}) { | ||
| super(); | ||
| /** @type {JsonModulesPluginParserOptions} */ | ||
| /** @type {JsonParserOptions} */ | ||
| this.options = options; | ||
@@ -52,18 +52,9 @@ } | ||
| /** @type {typeof parseJson} */ | ||
| const parseFn = | ||
| typeof this.options.parse === "function" ? this.options.parse : parseJson; | ||
| /** @type {Buffer | JsonValue | undefined} */ | ||
| let data; | ||
| try { | ||
| data = | ||
| typeof source === "object" | ||
| ? source | ||
| : parseFn(source[0] === "\uFEFF" ? source.slice(1) : source); | ||
| } catch (err) { | ||
| throw new Error( | ||
| `Cannot parse JSON: ${/** @type {Error} */ (err).message}`, | ||
| { cause: err } | ||
| ); | ||
| } | ||
| const data = | ||
| typeof source === "object" | ||
| ? source | ||
| : parseFn(source[0] === "\uFEFF" ? source.slice(1) : source); | ||
| const jsonData = new JsonData(/** @type {Buffer | JsonValue} */ (data)); | ||
@@ -70,0 +61,0 @@ const buildInfo = /** @type {BuildInfo} */ (state.module.buildInfo); |
@@ -252,3 +252,3 @@ /* | ||
| parseOptions(library) { | ||
| const AbstractMethodError = require("../AbstractMethodError"); | ||
| const AbstractMethodError = require("../errors/AbstractMethodError"); | ||
@@ -255,0 +255,0 @@ throw new AbstractMethodError(); |
@@ -252,3 +252,3 @@ /* | ||
| (compilation) => { | ||
| const FalseIIFEUmdWarning = require("../FalseIIFEUmdWarning"); | ||
| const FalseIIFEUmdWarning = require("./FalseIIFEUmdWarning"); | ||
@@ -255,0 +255,0 @@ compilation.warnings.push(new FalseIIFEUmdWarning()); |
@@ -14,2 +14,3 @@ /* | ||
| const HarmonyExportImportedSpecifierDependency = require("../dependencies/HarmonyExportImportedSpecifierDependency"); | ||
| const JavascriptModulesPlugin = require("../javascript/JavascriptModulesPlugin"); | ||
| const ConcatenatedModule = require("../optimize/ConcatenatedModule"); | ||
@@ -84,2 +85,4 @@ const { propertyAccess } = require("../util/property"); | ||
| ConcatenatedModule.getCompilationHooks(compilation); | ||
| const javascriptHooks = | ||
| JavascriptModulesPlugin.getCompilationHooks(compilation); | ||
| onDemandExportsGeneration.tap( | ||
@@ -110,2 +113,73 @@ PLUGIN_NAME, | ||
| ); | ||
| // `ModuleLibraryPlugin` stashes the on-demand exports source via | ||
| // `onDemandExportsGeneration` and only re-emits it when the | ||
| // module is wrapped in an IIFE/factory. When a single concatenated | ||
| // entry is inlined directly, the stashed source — and the | ||
| // `definePropertyGetters` / `requireScope` runtime helpers it | ||
| // pulled in — never make it into the output. Drop those helpers | ||
| // from the chunk's set in that simple shape so the bundle stays | ||
| // clean. | ||
| compilation.hooks.additionalChunkRuntimeRequirements.tap( | ||
| PLUGIN_NAME, | ||
| (chunk, set, { chunkGraph, codeGenerationResults }) => { | ||
| if (!set.has(RuntimeGlobals.definePropertyGetters)) return; | ||
| // Only handle the simple "single concatenated entry" | ||
| // shape. Anything else (additional modules, multiple | ||
| // entries, sibling runtime chunks, or chunk-level | ||
| // requirements that disable inline startup) forces the | ||
| // module through factory/IIFE rendering, which re-emits | ||
| // the source. | ||
| if (chunkGraph.getNumberOfChunkModules(chunk) !== 1) return; | ||
| if (chunkGraph.getNumberOfEntryModules(chunk) !== 1) return; | ||
| if (chunkGraph.hasChunkEntryDependentChunks(chunk)) return; | ||
| if ( | ||
| set.has(RuntimeGlobals.moduleFactories) || | ||
| set.has(RuntimeGlobals.moduleCache) || | ||
| set.has(RuntimeGlobals.interceptModuleExecution) || | ||
| set.has(RuntimeGlobals.module) || | ||
| set.has(RuntimeGlobals.thisAsExports) | ||
| ) { | ||
| return; | ||
| } | ||
| // Anyone tapping `inlineInRuntimeBailout` may force factory | ||
| // rendering at render time, so conservatively bail out. | ||
| if (javascriptHooks.inlineInRuntimeBailout.isUsed()) return; | ||
| const [module] = chunkGraph.getChunkEntryModulesIterable(chunk); | ||
| const exportsSourceByRuntime = | ||
| module.buildMeta && module.buildMeta.exportsSourceByRuntime; | ||
| if ( | ||
| !exportsSourceByRuntime || | ||
| !exportsSourceByRuntime.has(getRuntimeKey(chunk.runtime)) | ||
| ) { | ||
| return; | ||
| } | ||
| // If the generated source references any | ||
| // `__webpack_require__.<helper>` (the on-demand `.d(...)` | ||
| // is stashed, but `.r(__webpack_exports__)` from the ESM | ||
| // compat flag, namespace objects, deferred externals, ... | ||
| // stay in the result) the helpers and the require scope | ||
| // they live in are still needed. The dot in the substring | ||
| // avoids matching the bare `"__webpack_require__"` string | ||
| // literals that some test fixtures include. | ||
| const codeGenResult = codeGenerationResults.get( | ||
| module, | ||
| chunk.runtime | ||
| ); | ||
| const jsSource = | ||
| codeGenResult && codeGenResult.sources.get("javascript"); | ||
| if ( | ||
| jsSource && | ||
| String(jsSource.source()).includes(`${RuntimeGlobals.require}.`) | ||
| ) { | ||
| return; | ||
| } | ||
| set.delete(RuntimeGlobals.definePropertyGetters); | ||
| set.delete(RuntimeGlobals.exports); | ||
| set.delete(RuntimeGlobals.requireScope); | ||
| } | ||
| ); | ||
| }); | ||
@@ -112,0 +186,0 @@ } |
+19
-18
@@ -54,3 +54,3 @@ /* | ||
| */ | ||
| /** @typedef {import("./WebpackError")} WebpackError */ | ||
| /** @typedef {import("./errors/WebpackError")} WebpackError */ | ||
| /** @typedef {import("./json/JsonData")} JsonData */ | ||
@@ -133,3 +133,3 @@ /** @typedef {import("./serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ | ||
| * @template {string} K | ||
| * @typedef {K extends keyof AllCodeGenerationSchemas ? AllCodeGenerationSchemas[K] : EXPECTED_ANY} CodeGenValue | ||
| * @typedef {K extends (keyof AllCodeGenerationSchemas) ? AllCodeGenerationSchemas[K] : EXPECTED_ANY} CodeGenValue | ||
| */ | ||
@@ -178,3 +178,4 @@ | ||
| * @property {boolean=} sideEffectFree | ||
| * @property {boolean=} isCSSModule | ||
| * @property {boolean=} isCssModule | ||
| * @property {boolean=} needIdInConcatenation | ||
| * @property {Record<string, string>=} jsIncompatibleExports | ||
@@ -309,5 +310,5 @@ * @property {Map<string, Record<string, string>>=} exportsFinalNameByRuntime | ||
| // Info from Build | ||
| /** @type {WebpackError[] | undefined} */ | ||
| /** @type {Error[] | undefined} */ | ||
| this._warnings = undefined; | ||
| /** @type {WebpackError[] | undefined} */ | ||
| /** @type {Error[] | undefined} */ | ||
| this._errors = undefined; | ||
@@ -789,3 +790,3 @@ /** @type {BuildMeta | undefined} */ | ||
| * Adds the provided warning to the module. | ||
| * @param {WebpackError} warning the warning | ||
| * @param {Error} warning the warning | ||
| * @returns {void} | ||
@@ -802,3 +803,3 @@ */ | ||
| * Returns list of warnings if any. | ||
| * @returns {Iterable<WebpackError> | undefined} list of warnings if any | ||
| * @returns {Error[] | undefined} list of warnings if any | ||
| */ | ||
@@ -819,3 +820,3 @@ getWarnings() { | ||
| * Adds the provided error to the module. | ||
| * @param {WebpackError} error the error | ||
| * @param {Error} error the error | ||
| * @returns {void} | ||
@@ -832,3 +833,3 @@ */ | ||
| * Returns list of errors if any. | ||
| * @returns {Iterable<WebpackError> | undefined} list of errors if any | ||
| * @returns {Error[] | undefined} list of errors if any | ||
| */ | ||
@@ -1038,3 +1039,3 @@ getErrors() { | ||
| identifier() { | ||
| const AbstractMethodError = require("./AbstractMethodError"); | ||
| const AbstractMethodError = require("./errors/AbstractMethodError"); | ||
@@ -1052,3 +1053,3 @@ throw new AbstractMethodError(); | ||
| readableIdentifier(requestShortener) { | ||
| const AbstractMethodError = require("./AbstractMethodError"); | ||
| const AbstractMethodError = require("./errors/AbstractMethodError"); | ||
@@ -1070,3 +1071,3 @@ throw new AbstractMethodError(); | ||
| build(options, compilation, resolver, fs, callback) { | ||
| const AbstractMethodError = require("./AbstractMethodError"); | ||
| const AbstractMethodError = require("./errors/AbstractMethodError"); | ||
@@ -1113,3 +1114,3 @@ throw new AbstractMethodError(); | ||
| if (this.codeGeneration === Module.prototype.codeGeneration) { | ||
| const AbstractMethodError = require("./AbstractMethodError"); | ||
| const AbstractMethodError = require("./errors/AbstractMethodError"); | ||
@@ -1150,3 +1151,3 @@ throw new AbstractMethodError(); | ||
| size(type) { | ||
| const AbstractMethodError = require("./AbstractMethodError"); | ||
| const AbstractMethodError = require("./errors/AbstractMethodError"); | ||
@@ -1409,3 +1410,3 @@ throw new AbstractMethodError(); | ||
| * @deprecated | ||
| * @returns {WebpackError[]} errors | ||
| * @returns {Error[]} errors | ||
| */ | ||
@@ -1416,3 +1417,3 @@ get: util.deprecate( | ||
| * @this {Module} | ||
| * @returns {WebpackError[]} errors | ||
| * @returns {Error[]} errors | ||
| */ | ||
@@ -1435,3 +1436,3 @@ function errors() { | ||
| * @deprecated | ||
| * @returns {WebpackError[]} warnings | ||
| * @returns {Error[]} warnings | ||
| */ | ||
@@ -1442,3 +1443,3 @@ get: util.deprecate( | ||
| * @this {Module} | ||
| * @returns {WebpackError[]} warnings | ||
| * @returns {Error[]} warnings | ||
| */ | ||
@@ -1445,0 +1446,0 @@ function warnings() { |
@@ -56,3 +56,3 @@ /* | ||
| create(data, callback) { | ||
| const AbstractMethodError = require("./AbstractMethodError"); | ||
| const AbstractMethodError = require("./errors/AbstractMethodError"); | ||
@@ -59,0 +59,0 @@ throw new AbstractMethodError(); |
@@ -44,2 +44,12 @@ /* | ||
| /** | ||
| * @type {Readonly<"css-text">} | ||
| */ | ||
| const CSS_TEXT_TYPE = "css-text"; | ||
| /** | ||
| * @type {Readonly<"html">} | ||
| */ | ||
| const HTML_TYPE = "html"; | ||
| /** | ||
| * @type {Readonly<"share-init">} | ||
@@ -66,3 +76,3 @@ */ | ||
| * Defines the all types type used by this module. | ||
| * @typedef {JAVASCRIPT_TYPE | RUNTIME_TYPE | WEBASSEMBLY_TYPE | ASSET_TYPE | CSS_TYPE | CSS_IMPORT_TYPE | CSS_URL_TYPE | SHARED_INIT_TYPE | REMOTE_GENERATOR_TYPE | CONSUME_SHARED_GENERATOR_TYPE | UNKNOWN_TYPE} AllTypes | ||
| * @typedef {JAVASCRIPT_TYPE | RUNTIME_TYPE | WEBASSEMBLY_TYPE | ASSET_TYPE | CSS_TYPE | CSS_IMPORT_TYPE | CSS_URL_TYPE | CSS_TEXT_TYPE | HTML_TYPE | SHARED_INIT_TYPE | REMOTE_GENERATOR_TYPE | CONSUME_SHARED_GENERATOR_TYPE | UNKNOWN_TYPE} AllTypes | ||
| */ | ||
@@ -123,3 +133,13 @@ | ||
| const CSS_URL_TYPES = new Set([CSS_URL_TYPE]); | ||
| /** | ||
| * @type {ReadonlySet<"css-text">} | ||
| */ | ||
| const CSS_TEXT_TYPES = new Set([CSS_TEXT_TYPE]); | ||
| /** | ||
| * @type {ReadonlySet<"javascript" | "css-text">} | ||
| */ | ||
| const JAVASCRIPT_AND_CSS_TEXT_TYPES = new Set([JAVASCRIPT_TYPE, CSS_TEXT_TYPE]); | ||
| /** | ||
| * @type {ReadonlySet<"css-import">} | ||
@@ -130,2 +150,7 @@ */ | ||
| /** | ||
| * @type {ReadonlySet<"html">} | ||
| */ | ||
| const HTML_TYPES = new Set([HTML_TYPE]); | ||
| /** | ||
| * @type {ReadonlySet<"webassembly">} | ||
@@ -167,2 +192,4 @@ */ | ||
| module.exports.CSS_IMPORT_TYPES = CSS_IMPORT_TYPES; | ||
| module.exports.CSS_TEXT_TYPE = CSS_TEXT_TYPE; | ||
| module.exports.CSS_TEXT_TYPES = CSS_TEXT_TYPES; | ||
| module.exports.CSS_TYPE = CSS_TYPE; | ||
@@ -173,2 +200,5 @@ module.exports.CSS_TYPE = CSS_TYPE; | ||
| module.exports.CSS_URL_TYPES = CSS_URL_TYPES; | ||
| module.exports.HTML_TYPE = HTML_TYPE; | ||
| module.exports.HTML_TYPES = HTML_TYPES; | ||
| module.exports.JAVASCRIPT_AND_CSS_TEXT_TYPES = JAVASCRIPT_AND_CSS_TEXT_TYPES; | ||
| module.exports.JAVASCRIPT_AND_CSS_TYPES = JAVASCRIPT_AND_CSS_TYPES; | ||
@@ -175,0 +205,0 @@ module.exports.JAVASCRIPT_AND_CSS_URL_TYPES = JAVASCRIPT_AND_CSS_URL_TYPES; |
@@ -69,2 +69,9 @@ /* | ||
| /** | ||
| * @type {Readonly<"html">} | ||
| * This is the module type used for HTML files when `experiments.html` is enabled. | ||
| * HTML modules are emitted as HTML assets and can be used as entry points. | ||
| */ | ||
| const HTML_MODULE_TYPE = "html"; | ||
| /** | ||
| * @type {Readonly<"asset">} | ||
@@ -144,7 +151,8 @@ * This is the module type used for automatically choosing between `asset/inline`, `asset/resource` based on asset size limit (8096). | ||
| /** @typedef {"webassembly/async" | "webassembly/sync"} WebAssemblyModuleTypes */ | ||
| /** @typedef {"css" | "css/global" | "css/module" | "css/auto"} CSSModuleTypes */ | ||
| /** @typedef {"css" | "css/global" | "css/module" | "css/auto"} CssModuleTypes */ | ||
| /** @typedef {"html"} HTMLModuleType */ | ||
| /** @typedef {"asset" | "asset/inline" | "asset/resource" | "asset/source" | "asset/raw-data-url"} AssetModuleTypes */ | ||
| /** @typedef {"runtime" | "fallback-module" | "remote-module" | "provide-module" | "consume-shared-module" | "lazy-compilation-proxy"} WebpackModuleTypes */ | ||
| /** @typedef {string} UnknownModuleTypes */ | ||
| /** @typedef {JavaScriptModuleTypes | JSONModuleType | WebAssemblyModuleTypes | CSSModuleTypes | AssetModuleTypes | WebpackModuleTypes | UnknownModuleTypes} ModuleTypes */ | ||
| /** @typedef {JavaScriptModuleTypes | JSONModuleType | WebAssemblyModuleTypes | CssModuleTypes | HTMLModuleType | AssetModuleTypes | WebpackModuleTypes | UnknownModuleTypes} ModuleTypes */ | ||
@@ -157,3 +165,3 @@ module.exports.ASSET_MODULE_TYPE = ASSET_MODULE_TYPE; | ||
| module.exports.ASSET_MODULE_TYPE_SOURCE = ASSET_MODULE_TYPE_SOURCE; | ||
| /** @type {CSSModuleTypes[]} */ | ||
| /** @type {CssModuleTypes[]} */ | ||
| module.exports.CSS_MODULES = [ | ||
@@ -169,2 +177,3 @@ CSS_MODULE_TYPE, | ||
| module.exports.CSS_MODULE_TYPE_MODULE = CSS_MODULE_TYPE_MODULE; | ||
| module.exports.HTML_MODULE_TYPE = HTML_MODULE_TYPE; | ||
| /** @type {JavaScriptModuleTypes[]} */ | ||
@@ -171,0 +180,0 @@ module.exports.JAVASCRIPT_MODULES = [ |
@@ -11,6 +11,6 @@ /* | ||
| const ConcurrentCompilationError = require("./ConcurrentCompilationError"); | ||
| const MultiStats = require("./MultiStats"); | ||
| const MultiWatching = require("./MultiWatching"); | ||
| const WebpackError = require("./WebpackError"); | ||
| const ConcurrentCompilationError = require("./errors/ConcurrentCompilationError"); | ||
| const WebpackError = require("./errors/WebpackError"); | ||
| const ArrayQueue = require("./util/ArrayQueue"); | ||
@@ -17,0 +17,0 @@ |
+113
-64
@@ -10,6 +10,42 @@ /* | ||
| const truncateArgs = require("../logging/truncateArgs"); | ||
| const memoize = require("../util/memoize"); | ||
| const getCli = memoize(() => require("../cli")); | ||
| const ESC = "\u001B["; | ||
| const CURSOR_UP = `${ESC}1A`; | ||
| const CLEAR_LINE = `${ESC}2K\r`; | ||
| /** @typedef {import("../Compiler")} Compiler */ | ||
| /** @typedef {import("../config/defaults").InfrastructureLoggingNormalizedWithDefaults} InfrastructureLoggingNormalizedWithDefaults */ | ||
| /** @typedef {import("../logging/createConsoleLogger").LoggerConsole} LoggerConsole */ | ||
| /** | ||
| * @typedef {object} StatusMessageState | ||
| * @property {string[] | undefined} currentMessage current status message | ||
| * @property {number} currentLines current status message rows | ||
| */ | ||
| /** @type {WeakMap<Compiler, StatusMessageState>} */ | ||
| const logStatusStateByCompiler = new WeakMap(); | ||
| /** @type {Set<StatusMessageState>} */ | ||
| const logStatusStates = new Set(); | ||
| /** | ||
| * Returns status state | ||
| * @param {Compiler} compiler compiler | ||
| * @returns {StatusMessageState} status state | ||
| */ | ||
| const getLogStatusState = (compiler) => { | ||
| let state = logStatusStateByCompiler.get(compiler); | ||
| if (state === undefined) { | ||
| state = { | ||
| currentMessage: undefined, | ||
| currentLines: 0 | ||
| }; | ||
| logStatusStateByCompiler.set(compiler, state); | ||
| logStatusStates.add(state); | ||
| } | ||
| return state; | ||
| }; | ||
| /* eslint-disable no-console */ | ||
@@ -23,8 +59,9 @@ | ||
| * @param {InfrastructureLoggingNormalizedWithDefaults["stream"]} options.stream stream | ||
| * @param {Compiler} options.compiler compiler | ||
| * @returns {LoggerConsole} logger function | ||
| */ | ||
| module.exports = ({ colors, appendOnly, stream }) => { | ||
| /** @type {string[] | undefined} */ | ||
| let currentStatusMessage; | ||
| let hasStatusMessage = false; | ||
| module.exports = ({ colors, appendOnly, stream, compiler }) => { | ||
| const c = getCli().createColors({ useColor: Boolean(colors) }); | ||
| const logStatusState = getLogStatusState(compiler); | ||
| let currentIndent = ""; | ||
@@ -37,57 +74,82 @@ let currentCollapsed = 0; | ||
| * @param {string} prefix prefix | ||
| * @param {string} colorPrefix color prefix | ||
| * @param {string} colorSuffix color suffix | ||
| * @param {(line: string) => string} colorFn color function | ||
| * @returns {string} indented string | ||
| */ | ||
| const indent = (str, prefix, colorPrefix, colorSuffix) => { | ||
| const indent = (str, prefix, colorFn) => { | ||
| if (str === "") return str; | ||
| prefix = currentIndent + prefix; | ||
| if (colors) { | ||
| return ( | ||
| prefix + | ||
| colorPrefix + | ||
| str.replace(/\n/g, `${colorSuffix}\n${prefix}${colorPrefix}`) + | ||
| colorSuffix | ||
| ); | ||
| } | ||
| return prefix + str.replace(/\n/g, `\n${prefix}`); | ||
| return ( | ||
| prefix + | ||
| str | ||
| .split("\n") | ||
| .map((line) => colorFn(line)) | ||
| .join(`\n${prefix}`) | ||
| ); | ||
| }; | ||
| const clearStatusMessage = () => { | ||
| if (hasStatusMessage) { | ||
| stream.write("\u001B[2K\r"); | ||
| hasStatusMessage = false; | ||
| let lines = 0; | ||
| for (const state of logStatusStates) { | ||
| if (state.currentLines) { | ||
| lines += state.currentLines; | ||
| state.currentLines = 0; | ||
| } | ||
| } | ||
| for (let i = 0; i < lines; i++) { | ||
| if (i > 0) stream.write(CURSOR_UP); | ||
| stream.write(CLEAR_LINE); | ||
| } | ||
| }; | ||
| const writeStatusMessage = () => { | ||
| if (!currentStatusMessage) return; | ||
| const l = stream.columns || 40; | ||
| const args = truncateArgs(currentStatusMessage, l - 1); | ||
| const str = args.join(" "); | ||
| const coloredStr = `\u001B[1m${str}\u001B[39m\u001B[22m`; | ||
| stream.write(`\u001B[2K\r${coloredStr}`); | ||
| hasStatusMessage = true; | ||
| const column = stream.columns || 40; | ||
| /** @type {string[]} */ | ||
| const all = []; | ||
| for (const state of logStatusStates) { | ||
| if (!state.currentMessage) continue; | ||
| /** @type {string[][]} */ | ||
| const lines = [[]]; | ||
| for (const item of state.currentMessage) { | ||
| const parts = item.split("\n"); | ||
| lines[lines.length - 1].push(parts[0]); | ||
| for (let i = 1; i < parts.length; i++) { | ||
| lines.push([parts[i]]); | ||
| } | ||
| } | ||
| const truncateLines = lines.map((args) => | ||
| truncateArgs(args, column - 1).join(" ") | ||
| ); | ||
| state.currentLines = truncateLines.length; | ||
| for (const line of truncateLines) all.push(line); | ||
| } | ||
| if (all.length === 0) return; | ||
| const coloredLines = all.map((str) => c.bold(str)); | ||
| stream.write(`${CLEAR_LINE}${coloredLines.join(`\n${CLEAR_LINE}`)}`); | ||
| }; | ||
| /** | ||
| * @param {EXPECTED_ANY[]} statusMessage status message | ||
| * @returns {void} | ||
| */ | ||
| const setStatusMessage = (statusMessage) => { | ||
| clearStatusMessage(); | ||
| logStatusState.currentMessage = statusMessage.map((item) => `${item}`); | ||
| writeStatusMessage(); | ||
| }; | ||
| /** | ||
| * Returns function to write with colors. | ||
| * @template T | ||
| * @param {string} prefix prefix | ||
| * @param {string} colorPrefix color prefix | ||
| * @param {string} colorSuffix color suffix | ||
| * @param {(line: string) => string} colorFn color function | ||
| * @returns {(...args: T[]) => void} function to write with colors | ||
| */ | ||
| const writeColored = | ||
| (prefix, colorPrefix, colorSuffix) => | ||
| (prefix, colorFn) => | ||
| (...args) => { | ||
| if (currentCollapsed > 0) return; | ||
| clearStatusMessage(); | ||
| const str = indent( | ||
| util.format(...args), | ||
| prefix, | ||
| colorPrefix, | ||
| colorSuffix | ||
| ); | ||
| const str = indent(util.format(...args), prefix, colorFn); | ||
| stream.write(`${str}\n`); | ||
@@ -98,13 +160,7 @@ writeStatusMessage(); | ||
| /** @type {<T extends unknown[]>(...args: T) => void} */ | ||
| const writeGroupMessage = writeColored( | ||
| "<-> ", | ||
| "\u001B[1m\u001B[36m", | ||
| "\u001B[39m\u001B[22m" | ||
| ); | ||
| const writeGroupMessage = writeColored("<-> ", (str) => c.bold(c.cyan(str))); | ||
| /** @type {<T extends unknown[]>(...args: T) => void} */ | ||
| const writeGroupCollapsedMessage = writeColored( | ||
| "<+> ", | ||
| "\u001B[1m\u001B[36m", | ||
| "\u001B[39m\u001B[22m" | ||
| const writeGroupCollapsedMessage = writeColored("<+> ", (str) => | ||
| c.bold(c.cyan(str)) | ||
| ); | ||
@@ -114,19 +170,15 @@ | ||
| /** @type {LoggerConsole["log"]} */ | ||
| log: writeColored(" ", "\u001B[1m", "\u001B[22m"), | ||
| log: writeColored(" ", c.bold), | ||
| /** @type {LoggerConsole["debug"]} */ | ||
| debug: writeColored(" ", "", ""), | ||
| debug: writeColored(" ", String), | ||
| /** @type {LoggerConsole["trace"]} */ | ||
| trace: writeColored(" ", "", ""), | ||
| trace: writeColored(" ", String), | ||
| /** @type {LoggerConsole["info"]} */ | ||
| info: writeColored("<i> ", "\u001B[1m\u001B[32m", "\u001B[39m\u001B[22m"), | ||
| info: writeColored("<i> ", (str) => c.bold(c.green(str))), | ||
| /** @type {LoggerConsole["warn"]} */ | ||
| warn: writeColored("<w> ", "\u001B[1m\u001B[33m", "\u001B[39m\u001B[22m"), | ||
| warn: writeColored("<w> ", (str) => c.bold(c.yellow(str))), | ||
| /** @type {LoggerConsole["error"]} */ | ||
| error: writeColored("<e> ", "\u001B[1m\u001B[31m", "\u001B[39m\u001B[22m"), | ||
| error: writeColored("<e> ", (str) => c.bold(c.red(str))), | ||
| /** @type {LoggerConsole["logTime"]} */ | ||
| logTime: writeColored( | ||
| "<t> ", | ||
| "\u001B[1m\u001B[35m", | ||
| "\u001B[39m\u001B[22m" | ||
| ), | ||
| logTime: writeColored("<t> ", (str) => c.bold(c.magenta(str))), | ||
| /** @type {LoggerConsole["group"]} */ | ||
@@ -172,3 +224,3 @@ group: (...args) => { | ||
| status: appendOnly | ||
| ? writeColored("<s> ", "", "") | ||
| ? writeColored("<s> ", String) | ||
| : (name, ...args) => { | ||
@@ -178,3 +230,3 @@ args = args.filter(Boolean); | ||
| clearStatusMessage(); | ||
| currentStatusMessage = undefined; | ||
| logStatusState.currentMessage = undefined; | ||
| } else if ( | ||
@@ -184,10 +236,7 @@ typeof name === "string" && | ||
| ) { | ||
| currentStatusMessage = [name.slice(19), ...args]; | ||
| writeStatusMessage(); | ||
| setStatusMessage([name.slice(19), ...args]); | ||
| } else if (name === "[webpack.Progress]") { | ||
| currentStatusMessage = [...args]; | ||
| writeStatusMessage(); | ||
| setStatusMessage([...args]); | ||
| } else { | ||
| currentStatusMessage = [name, ...args]; | ||
| writeStatusMessage(); | ||
| setStatusMessage([name, ...args]); | ||
| } | ||
@@ -194,0 +243,0 @@ } |
@@ -8,3 +8,3 @@ /* | ||
| const CachedInputFileSystem = require("enhanced-resolve").CachedInputFileSystem; | ||
| const { CachedInputFileSystem } = require("enhanced-resolve"); | ||
| const fs = require("graceful-fs"); | ||
@@ -54,5 +54,7 @@ const createConsoleLogger = require("../logging/createConsoleLogger"); | ||
| /** @type {NodeJS.WritableStream} */ | ||
| (infrastructureLogging.stream) | ||
| (infrastructureLogging.stream), | ||
| compiler | ||
| }) | ||
| }); | ||
| // @ts-expect-error need to fix on enhanced-resolve side | ||
| compiler.inputFileSystem = new CachedInputFileSystem(fs, 60000); | ||
@@ -59,0 +61,0 @@ const inputFileSystem = |
@@ -13,3 +13,2 @@ /* | ||
| } = require("./ModuleTypeConstants"); | ||
| const NodeStuffInWebError = require("./NodeStuffInWebError"); | ||
| const RuntimeGlobals = require("./RuntimeGlobals"); | ||
@@ -21,2 +20,3 @@ const CachedConstDependency = require("./dependencies/CachedConstDependency"); | ||
| const ImportMetaPlugin = require("./dependencies/ImportMetaPlugin"); | ||
| const NodeStuffInWebError = require("./errors/NodeStuffInWebError"); | ||
| const { evaluateToString } = require("./javascript/JavascriptParserHelpers"); | ||
@@ -23,0 +23,0 @@ const { relative } = require("./util/fs"); |
+13
-31
@@ -23,14 +23,13 @@ /* | ||
| const Compilation = require("./Compilation"); | ||
| const HookWebpackError = require("./HookWebpackError"); | ||
| const Module = require("./Module"); | ||
| const ModuleBuildError = require("./ModuleBuildError"); | ||
| const ModuleError = require("./ModuleError"); | ||
| const ModuleGraphConnection = require("./ModuleGraphConnection"); | ||
| const ModuleParseError = require("./ModuleParseError"); | ||
| const { JAVASCRIPT_MODULE_TYPE_AUTO } = require("./ModuleTypeConstants"); | ||
| const ModuleWarning = require("./ModuleWarning"); | ||
| const RuntimeGlobals = require("./RuntimeGlobals"); | ||
| const UnhandledSchemeError = require("./UnhandledSchemeError"); | ||
| const WebpackError = require("./WebpackError"); | ||
| const formatLocation = require("./formatLocation"); | ||
| const HookWebpackError = require("./errors/HookWebpackError"); | ||
| const ModuleBuildError = require("./errors/ModuleBuildError"); | ||
| const ModuleError = require("./errors/ModuleError"); | ||
| const ModuleParseError = require("./errors/ModuleParseError"); | ||
| const ModuleWarning = require("./errors/ModuleWarning"); | ||
| const NonErrorEmittedError = require("./errors/NonErrorEmittedError"); | ||
| const UnhandledSchemeError = require("./errors/UnhandledSchemeError"); | ||
| const LazySet = require("./util/LazySet"); | ||
@@ -48,2 +47,3 @@ const { isSubset } = require("./util/SetHelpers"); | ||
| const { createFakeHook } = require("./util/deprecation"); | ||
| const formatLocation = require("./util/formatLocation"); | ||
| const { join } = require("./util/fs"); | ||
@@ -124,3 +124,3 @@ const { | ||
| const getInvalidDependenciesModuleWarning = memoize(() => | ||
| require("./InvalidDependenciesModuleWarning") | ||
| require("./errors/InvalidDependenciesModuleWarning") | ||
| ); | ||
@@ -213,20 +213,2 @@ | ||
| class NonErrorEmittedError extends WebpackError { | ||
| /** | ||
| * @param {EXPECTED_ANY} error value which is not an instance of Error | ||
| */ | ||
| constructor(error) { | ||
| super(); | ||
| this.name = "NonErrorEmittedError"; | ||
| this.message = `(Emitted value instead of an instance of Error) ${error}`; | ||
| } | ||
| } | ||
| makeSerializable( | ||
| NonErrorEmittedError, | ||
| "webpack/lib/NormalModule", | ||
| "NonErrorEmittedError" | ||
| ); | ||
| /** @typedef {[string | Buffer, string | RawSourceMap | undefined, PreparsedAst | undefined]} Result */ | ||
@@ -401,3 +383,3 @@ | ||
| // Info from Build | ||
| /** @type {WebpackError | null} */ | ||
| /** @type {Error | null} */ | ||
| this.error = null; | ||
@@ -1184,3 +1166,3 @@ /** | ||
| /** | ||
| * @param {WebpackError} error the error | ||
| * @param {Error} error the error | ||
| * @returns {void} | ||
@@ -1337,3 +1319,3 @@ */ | ||
| } catch (err) { | ||
| this.markModuleAsErrored(/** @type {WebpackError} */ (err)); | ||
| this.markModuleAsErrored(/** @type {Error} */ (err)); | ||
| return callback(); | ||
@@ -1430,3 +1412,3 @@ } | ||
| } catch (err) { | ||
| this.markModuleAsErrored(/** @type {WebpackError} */ (err)); | ||
| this.markModuleAsErrored(/** @type {Error} */ (err)); | ||
| this._initBuildHash(compilation); | ||
@@ -1433,0 +1415,0 @@ return callback(); |
@@ -34,2 +34,3 @@ /* | ||
| const { | ||
| escapeHashInPathRequest, | ||
| parseResource, | ||
@@ -136,4 +137,5 @@ parseResourceWithoutFragment | ||
| /** @typedef {import("./ModuleTypeConstants").CSS_MODULE_TYPE_AUTO} CSS_MODULE_TYPE_AUTO */ | ||
| /** @typedef {import("./ModuleTypeConstants").HTML_MODULE_TYPE} HTML_MODULE_TYPE */ | ||
| /** @typedef {JAVASCRIPT_MODULE_TYPE_AUTO | JAVASCRIPT_MODULE_TYPE_DYNAMIC | JAVASCRIPT_MODULE_TYPE_ESM | JSON_MODULE_TYPE | ASSET_MODULE_TYPE | ASSET_MODULE_TYPE_INLINE | ASSET_MODULE_TYPE_RESOURCE | ASSET_MODULE_TYPE_SOURCE | WEBASSEMBLY_MODULE_TYPE_ASYNC | WEBASSEMBLY_MODULE_TYPE_SYNC | CSS_MODULE_TYPE | CSS_MODULE_TYPE_GLOBAL | CSS_MODULE_TYPE_MODULE | CSS_MODULE_TYPE_AUTO} KnownNormalModuleTypes */ | ||
| /** @typedef {JAVASCRIPT_MODULE_TYPE_AUTO | JAVASCRIPT_MODULE_TYPE_DYNAMIC | JAVASCRIPT_MODULE_TYPE_ESM | JSON_MODULE_TYPE | ASSET_MODULE_TYPE | ASSET_MODULE_TYPE_INLINE | ASSET_MODULE_TYPE_RESOURCE | ASSET_MODULE_TYPE_SOURCE | WEBASSEMBLY_MODULE_TYPE_ASYNC | WEBASSEMBLY_MODULE_TYPE_SYNC | CSS_MODULE_TYPE | CSS_MODULE_TYPE_GLOBAL | CSS_MODULE_TYPE_MODULE | CSS_MODULE_TYPE_AUTO | HTML_MODULE_TYPE} KnownNormalModuleTypes */ | ||
| /** @typedef {KnownNormalModuleTypes | string} NormalModuleTypes */ | ||
@@ -324,2 +326,7 @@ | ||
| /** @typedef {import("./html/HtmlParser")} HtmlParser */ | ||
| /** @typedef {import("../declarations/WebpackOptions").EmptyParserOptions} HtmlParserOptions */ | ||
| /** @typedef {import("./html/HtmlGenerator")} HtmlGenerator */ | ||
| /** @typedef {import("../declarations/WebpackOptions").EmptyGeneratorOptions} HtmlGeneratorOptions */ | ||
| /* eslint-disable jsdoc/type-formatting */ | ||
@@ -344,2 +351,3 @@ /** | ||
| * [CSS_MODULE_TYPE_GLOBAL, CssParser, CssModuleParserOptions, CssGenerator, CssModuleGeneratorOptions], | ||
| * [HTML_MODULE_TYPE, HtmlParser, HtmlParserOptions, HtmlGenerator, HtmlGeneratorOptions], | ||
| * [string, Parser, ParserOptions, Generator, GeneratorOptions], | ||
@@ -917,3 +925,3 @@ * ]} ParsersAndGeneratorsByTypes | ||
| context, | ||
| unresolvedResource, | ||
| escapeHashInPathRequest(unresolvedResource), | ||
| normalResolver, | ||
@@ -920,0 +928,0 @@ resolveContext, |
@@ -148,3 +148,3 @@ /* | ||
| const exportsInfo = moduleGraph.getExportsInfo(selfModule); | ||
| return (connections, runtime) => { | ||
| return (_connections, runtime) => { | ||
| for (const exportName of usedByExports) { | ||
@@ -151,0 +151,0 @@ if (exportsInfo.getUsed(exportName, runtime) !== UsageState.Unused) { |
@@ -12,2 +12,3 @@ /* | ||
| } = require("../ModuleTypeConstants"); | ||
| const RuntimeGlobals = require("../RuntimeGlobals"); | ||
| const PureExpressionDependency = require("../dependencies/PureExpressionDependency"); | ||
@@ -33,2 +34,3 @@ const InnerGraph = require("./InnerGraph"); | ||
| const PLUGIN_NAME = "InnerGraphPlugin"; | ||
| const impureVariableDeclarationKinds = new Set(["using", "await using"]); | ||
@@ -205,4 +207,5 @@ class InnerGraphPlugin { | ||
| parser.hooks.preDeclarator.tap(PLUGIN_NAME, (decl, _statement) => { | ||
| parser.hooks.preDeclarator.tap(PLUGIN_NAME, (decl, statement) => { | ||
| if (!InnerGraph.isEnabled(parser.state)) return; | ||
| if (impureVariableDeclarationKinds.has(statement.kind)) return; | ||
| if ( | ||
@@ -214,3 +217,10 @@ parser.scope.topLevelScope === true && | ||
| const name = decl.id.name; | ||
| // Skip webpack runtime variables handled by CompatibilityPlugin | ||
| if ( | ||
| name === RuntimeGlobals.require || | ||
| name === RuntimeGlobals.exports | ||
| ) { | ||
| return; | ||
| } | ||
| if ( | ||
| decl.init.type === "ClassExpression" && | ||
@@ -217,0 +227,0 @@ parser.isPure( |
@@ -8,4 +8,4 @@ /* | ||
| const SizeFormatHelpers = require("../SizeFormatHelpers"); | ||
| const WebpackError = require("../WebpackError"); | ||
| const WebpackError = require("../errors/WebpackError"); | ||
| const formatSize = require("../util/formatSize"); | ||
@@ -30,4 +30,4 @@ class MinMaxSizeWarning extends WebpackError { | ||
| `${keysMessage}\n` + | ||
| `Configured minSize (${SizeFormatHelpers.formatSize(minSize)}) is ` + | ||
| `bigger than maxSize (${SizeFormatHelpers.formatSize(maxSize)}).\n` + | ||
| `Configured minSize (${formatSize(minSize)}) is ` + | ||
| `bigger than maxSize (${formatSize(maxSize)}).\n` + | ||
| "This seem to be a invalid optimization.splitChunks configuration." | ||
@@ -34,0 +34,0 @@ ); |
@@ -10,6 +10,7 @@ /* | ||
| const ChunkGraph = require("../ChunkGraph"); | ||
| const Dependency = require("../Dependency"); | ||
| const Module = require("../Module"); | ||
| const ModuleGraph = require("../ModuleGraph"); | ||
| const { JAVASCRIPT_TYPE } = require("../ModuleSourceTypeConstants"); | ||
| const { STAGE_DEFAULT } = require("../OptimizationStages"); | ||
| const HarmonyImportDependency = require("../dependencies/HarmonyImportDependency"); | ||
| const { compareModulesByIdentifier } = require("../util/comparators"); | ||
@@ -27,3 +28,2 @@ const { | ||
| /** @typedef {import("../Compiler")} Compiler */ | ||
| /** @typedef {import("../Module")} Module */ | ||
| /** @typedef {import("../Module").BuildInfo} BuildInfo */ | ||
@@ -233,2 +233,8 @@ /** @typedef {import("../RequestShortener")} RequestShortener */ | ||
| // TODO: ConcatenatedModule.getSourceTypes only javascript now | ||
| const basicTypes = Module.getSourceBasicTypes(module); | ||
| if (basicTypes.size !== 1 || !basicTypes.has(JAVASCRIPT_TYPE)) { | ||
| canBeRoot = false; | ||
| } | ||
| // Module must not be an entry point | ||
@@ -466,3 +472,4 @@ if (chunkGraph.isEntryModule(module)) { | ||
| !( | ||
| c.dependency instanceof HarmonyImportDependency && | ||
| c.dependency && | ||
| Dependency.canConcatenate(c.dependency) && | ||
| modules.has(c.module) | ||
@@ -510,3 +517,4 @@ ) | ||
| const innerConnection = | ||
| c.dependency instanceof HarmonyImportDependency && | ||
| c.dependency && | ||
| Dependency.canConcatenate(c.dependency) && | ||
| modules.has(/** @type {Module} */ (otherModule)); | ||
@@ -546,4 +554,4 @@ return !innerConnection; | ||
| for (const dep of module.dependencies) { | ||
| // Get reference info only for harmony Dependencies | ||
| if (!(dep instanceof HarmonyImportDependency)) continue; | ||
| // Get reference info only for dependencies that support concatenation | ||
| if (!Dependency.canConcatenate(dep)) continue; | ||
@@ -766,3 +774,3 @@ const connection = moduleGraph.getConnection(dep); | ||
| !connection.dependency || | ||
| !(connection.dependency instanceof HarmonyImportDependency) | ||
| !Dependency.canConcatenate(connection.dependency) | ||
| ); | ||
@@ -769,0 +777,0 @@ if (selected.length > 0) { |
@@ -11,3 +11,3 @@ /* | ||
| const Compilation = require("../Compilation"); | ||
| const WebpackError = require("../WebpackError"); | ||
| const WebpackError = require("../errors/WebpackError"); | ||
| const { compareSelect, compareStrings } = require("../util/comparators"); | ||
@@ -50,20 +50,73 @@ const createHash = require("../util/createHash"); | ||
| /** | ||
| * Map and deduplicate buffers. | ||
| * Compares two non-empty buffer chunk arrays for byte-equality without | ||
| * allocating a concatenated buffer. | ||
| * @param {Buffer[]} a first chunk array | ||
| * @param {Buffer[]} b second chunk array | ||
| * @returns {boolean} true if the concatenations are byte-equal | ||
| */ | ||
| const bufferArraysEqual = (a, b) => { | ||
| let aIdx = 0; | ||
| let aOff = 0; | ||
| let bIdx = 0; | ||
| let bOff = 0; | ||
| while (aIdx < a.length && bIdx < b.length) { | ||
| const aBuf = a[aIdx]; | ||
| const bBuf = b[bIdx]; | ||
| const len = Math.min(aBuf.length - aOff, bBuf.length - bOff); | ||
| if (aBuf.compare(bBuf, bOff, bOff + len, aOff, aOff + len) !== 0) { | ||
| return false; | ||
| } | ||
| aOff += len; | ||
| bOff += len; | ||
| if (aOff === aBuf.length) { | ||
| aIdx++; | ||
| aOff = 0; | ||
| } | ||
| if (bOff === bBuf.length) { | ||
| bIdx++; | ||
| bOff = 0; | ||
| } | ||
| } | ||
| return aIdx === a.length && bIdx === b.length; | ||
| }; | ||
| /** | ||
| * Map sources to their buffer chunks and deduplicate by total byte content, | ||
| * grouping by total length first to avoid full comparisons. | ||
| * @template T | ||
| * @param {T[]} input list | ||
| * @param {(item: T) => Buffer} fn map function | ||
| * @returns {Buffer[]} buffers without duplicates | ||
| * @param {(item: T) => Source} fn map function returning a Source | ||
| * @returns {Buffer[][]} unique chunk arrays | ||
| */ | ||
| const mapAndDeduplicateBuffers = (input, fn) => { | ||
| // Buffer.equals compares size first so this should be efficient enough | ||
| // If it becomes a performance problem we can use a map and group by size | ||
| // instead of looping over all assets. | ||
| /** @type {Buffer[]} */ | ||
| const mapAndDeduplicateSourceBuffers = (input, fn) => { | ||
| /** @type {Map<number, Buffer[][]>} */ | ||
| const bySize = new Map(); | ||
| /** @type {Buffer[][]} */ | ||
| const result = []; | ||
| outer: for (const value of input) { | ||
| const buf = fn(value); | ||
| for (const other of result) { | ||
| if (buf.equals(other)) continue outer; | ||
| for (const value of input) { | ||
| const source = fn(value); | ||
| // TODO webpack 6: drop the `buffers` check, require webpack-sources >= 3.4 | ||
| // and call `source.buffers()` unconditionally. | ||
| const chunks = | ||
| // TODO remove in webpack 6, this is protection against authors who directly use `webpack-sources` outdated version | ||
| typeof source.buffers === "function" | ||
| ? source.buffers() | ||
| : [source.buffer()]; | ||
| let total = 0; | ||
| for (const c of chunks) total += c.length; | ||
| const sameSize = bySize.get(total); | ||
| if (sameSize) { | ||
| let duplicate = false; | ||
| for (const other of sameSize) { | ||
| if (bufferArraysEqual(chunks, other)) { | ||
| duplicate = true; | ||
| break; | ||
| } | ||
| } | ||
| if (duplicate) continue; | ||
| sameSize.push(chunks); | ||
| } else { | ||
| bySize.set(total, [chunks]); | ||
| } | ||
| result.push(buf); | ||
| result.push(chunks); | ||
| } | ||
@@ -442,13 +495,23 @@ return result; | ||
| ); | ||
| const assetsContent = mapAndDeduplicateBuffers(assets, (asset) => { | ||
| if (/** @type {Hashes} */ (asset.ownHashes).has(oldHash)) { | ||
| return asset.newSourceWithoutOwn | ||
| ? asset.newSourceWithoutOwn.buffer() | ||
| : asset.source.buffer(); | ||
| const uniqueChunkArrays = mapAndDeduplicateSourceBuffers( | ||
| assets, | ||
| (asset) => { | ||
| if (/** @type {Hashes} */ (asset.ownHashes).has(oldHash)) { | ||
| return asset.newSourceWithoutOwn || asset.source; | ||
| } | ||
| return asset.newSource || asset.source; | ||
| } | ||
| return asset.newSource | ||
| ? asset.newSource.buffer() | ||
| : asset.source.buffer(); | ||
| }); | ||
| let newHash = hooks.updateHash.call(assetsContent, oldHash); | ||
| ); | ||
| /** @type {string | undefined} */ | ||
| let newHash; | ||
| // Only materialize the public `Buffer[]` (one entry per unique | ||
| // asset) when something is tapped; otherwise the hot path feeds | ||
| // chunks into the hash directly, avoiding per-asset Buffer.concat. | ||
| if (hooks.updateHash.isUsed()) { | ||
| const assetsContent = uniqueChunkArrays.map((chunks) => | ||
| chunks.length === 1 ? chunks[0] : Buffer.concat(chunks) | ||
| ); | ||
| newHash = | ||
| hooks.updateHash.call(assetsContent, oldHash) || undefined; | ||
| } | ||
| if (!newHash) { | ||
@@ -459,4 +522,4 @@ const hash = createHash(this._hashFunction); | ||
| } | ||
| for (const content of assetsContent) { | ||
| hash.update(content); | ||
| for (const chunks of uniqueChunkArrays) { | ||
| for (const c of chunks) hash.update(c); | ||
| } | ||
@@ -463,0 +526,0 @@ const digest = hash.digest(this._hashDigest); |
@@ -17,3 +17,4 @@ /* | ||
| const HarmonyImportSpecifierDependency = require("../dependencies/HarmonyImportSpecifierDependency"); | ||
| const formatLocation = require("../formatLocation"); | ||
| const formatLocation = require("../util/formatLocation"); | ||
| const { CompilerHintNotationRegExp } = require("../util/magicComment"); | ||
@@ -24,2 +25,3 @@ /** @typedef {import("estree").MaybeNamedClassDeclaration} MaybeNamedClassDeclaration */ | ||
| /** @typedef {import("estree").Statement} Statement */ | ||
| /** @typedef {import("estree").CallExpression} CallExpression */ | ||
| /** @typedef {import("../Compiler")} Compiler */ | ||
@@ -68,2 +70,20 @@ /** @typedef {import("../Dependency").DependencyLocation} DependencyLocation */ | ||
| /** | ||
| * @param {JavascriptParser} parser parser | ||
| * @param {number} start start position | ||
| * @param {number} end end position | ||
| * @returns {boolean} if annotation is found in the range | ||
| */ | ||
| const hasNoSideEffectsNotation = (parser, start, end) => { | ||
| // Fast path | ||
| if (end - start < 18) return false; | ||
| const comments = parser.getComments([start, end]); | ||
| return comments.some( | ||
| (c) => | ||
| c.type === "Block" && | ||
| CompilerHintNotationRegExp.NoSideEffects.test(c.value) | ||
| ); | ||
| }; | ||
| const PLUGIN_NAME = "SideEffectsFlagPlugin"; | ||
@@ -135,3 +155,3 @@ | ||
| */ | ||
| const parserHandler = (parser) => { | ||
| const applySideEffectsStmtHandler = (parser) => { | ||
| /** @type {undefined | Statement | ModuleDeclaration | MaybeNamedFunctionDeclaration | MaybeNamedClassDeclaration} */ | ||
@@ -267,2 +287,87 @@ let sideEffectsStatement; | ||
| }; | ||
| /** | ||
| * @param {JavascriptParser} parser the parser | ||
| * @returns {void} | ||
| */ | ||
| const applyNoSideEffectsNotationHandler = (parser) => { | ||
| /** @type {Set<string>} */ | ||
| let noSideEffectsFnNames; | ||
| parser.hooks.program.tap(PLUGIN_NAME, () => { | ||
| noSideEffectsFnNames = new Set(); | ||
| }); | ||
| // Detect on function declarations | ||
| // Covers: | ||
| // 1. function foo | ||
| // 2. export function foo | ||
| // 3. export default function foo | ||
| parser.hooks.preStatement.tap(PLUGIN_NAME, (statement) => { | ||
| if (parser.scope.topLevelScope !== true) return; | ||
| if (statement.type !== "FunctionDeclaration" || !statement.id) { | ||
| return; | ||
| } | ||
| const commentsStart = parser.prevStatement | ||
| ? /** @type {Range} */ (parser.prevStatement.range)[1] | ||
| : 0; | ||
| if ( | ||
| hasNoSideEffectsNotation( | ||
| parser, | ||
| commentsStart, | ||
| /** @type {Range} */ (statement.range)[0] | ||
| ) | ||
| ) { | ||
| noSideEffectsFnNames.add(statement.id.name); | ||
| } | ||
| }); | ||
| // Detect on variable declarations with function init | ||
| parser.hooks.preDeclarator.tap(PLUGIN_NAME, (decl, statement) => { | ||
| if (parser.scope.topLevelScope !== true) return; | ||
| if (!decl.init || decl.id.type !== "Identifier") return; | ||
| if (!decl.init.type.endsWith("FunctionExpression")) return; | ||
| let hasAnnotation = false; | ||
| // Before the VariableDeclaration (only for const) | ||
| if (statement.kind === "const") { | ||
| const commentsStart = parser.prevStatement | ||
| ? /** @type {Range} */ (parser.prevStatement.range)[1] | ||
| : 0; | ||
| hasAnnotation = hasNoSideEffectsNotation( | ||
| parser, | ||
| commentsStart, | ||
| /** @type {Range} */ (statement.range)[0] | ||
| ); | ||
| } | ||
| if (!hasAnnotation) { | ||
| hasAnnotation = hasNoSideEffectsNotation( | ||
| parser, | ||
| /** @type {Range} */ (decl.id.range)[1], | ||
| /** @type {Range} */ (decl.init.range)[0] | ||
| ); | ||
| } | ||
| if (hasAnnotation) { | ||
| noSideEffectsFnNames.add(decl.id.name); | ||
| } | ||
| }); | ||
| // Mark calls to annotated functions as pure | ||
| parser.hooks.isPure | ||
| .for("CallExpression") | ||
| .tap(PLUGIN_NAME, (expression, commentsStartPos) => { | ||
| const expr = /** @type {CallExpression} */ (expression); | ||
| if (expr.callee.type !== "Identifier") return; | ||
| if (!noSideEffectsFnNames.has(expr.callee.name)) return; | ||
| commentsStartPos = /** @type {Range} */ (expr.callee.range)[1]; | ||
| for (const arg of expr.arguments) { | ||
| if (arg.type === "SpreadElement") return; | ||
| if (!parser.isPure(arg, commentsStartPos)) return; | ||
| commentsStartPos = /** @type {Range} */ (arg.range)[1]; | ||
| } | ||
| return true; | ||
| }); | ||
| }; | ||
| for (const key of [ | ||
@@ -275,3 +380,6 @@ JAVASCRIPT_MODULE_TYPE_AUTO, | ||
| .for(key) | ||
| .tap(PLUGIN_NAME, parserHandler); | ||
| .tap(PLUGIN_NAME, (parser) => { | ||
| applyNoSideEffectsNotationHandler(parser); | ||
| applySideEffectsStmtHandler(parser); | ||
| }); | ||
| } | ||
@@ -278,0 +386,0 @@ } |
@@ -10,3 +10,3 @@ /* | ||
| const { STAGE_ADVANCED } = require("../OptimizationStages"); | ||
| const WebpackError = require("../WebpackError"); | ||
| const WebpackError = require("../errors/WebpackError"); | ||
| const { requestToId } = require("../ids/IdHelpers"); | ||
@@ -13,0 +13,0 @@ const { isSubset } = require("../util/SetHelpers"); |
+1
-1
@@ -36,3 +36,3 @@ /* | ||
| parse(source, state) { | ||
| const AbstractMethodError = require("./AbstractMethodError"); | ||
| const AbstractMethodError = require("./errors/AbstractMethodError"); | ||
@@ -39,0 +39,0 @@ throw new AbstractMethodError(); |
@@ -8,4 +8,4 @@ /* | ||
| const { formatSize } = require("../SizeFormatHelpers"); | ||
| const WebpackError = require("../WebpackError"); | ||
| const WebpackError = require("../errors/WebpackError"); | ||
| const formatSize = require("../util/formatSize"); | ||
@@ -12,0 +12,0 @@ /** @typedef {import("./SizeLimitsPlugin").AssetDetails} AssetDetails */ |
@@ -8,4 +8,4 @@ /* | ||
| const { formatSize } = require("../SizeFormatHelpers"); | ||
| const WebpackError = require("../WebpackError"); | ||
| const WebpackError = require("../errors/WebpackError"); | ||
| const formatSize = require("../util/formatSize"); | ||
@@ -12,0 +12,0 @@ /** @typedef {import("./SizeLimitsPlugin").EntrypointDetails} EntrypointDetails */ |
@@ -8,5 +8,5 @@ /* | ||
| const WebpackError = require("../WebpackError"); | ||
| const WebpackError = require("../errors/WebpackError"); | ||
| module.exports = class NoAsyncChunksWarning extends WebpackError { | ||
| class NoAsyncChunksWarning extends WebpackError { | ||
| constructor() { | ||
@@ -22,2 +22,4 @@ super( | ||
| } | ||
| }; | ||
| } | ||
| module.exports = NoAsyncChunksWarning; |
@@ -19,3 +19,3 @@ /* | ||
| /** @typedef {import("../Entrypoint")} Entrypoint */ | ||
| /** @typedef {import("../WebpackError")} WebpackError */ | ||
| /** @typedef {import("../errors/WebpackError")} WebpackError */ | ||
@@ -22,0 +22,0 @@ /** |
@@ -42,6 +42,9 @@ /* | ||
| }.prefetch = ${runtimeTemplate.expressionFunction( | ||
| // Prefetch is best-effort; silence rejections so a failed chunk | ||
| // load (e.g. chunkLoadTimeout) doesn't surface as an unhandled | ||
| // rejection through this dangling Promise.all chain. | ||
| `Promise.all(promises).then(${runtimeTemplate.basicFunction( | ||
| "", | ||
| body | ||
| )})`, | ||
| )}, ${runtimeTemplate.basicFunction("", "")})`, | ||
| "chunkId, promises" | ||
@@ -48,0 +51,0 @@ )};` |
+129
-56
@@ -12,3 +12,14 @@ /* | ||
| const { contextify } = require("./util/identifier"); | ||
| const memoize = require("./util/memoize"); | ||
| const getColors = memoize(() => { | ||
| const cli = require("./cli"); | ||
| return cli.createColors({ useColor: cli.isColorSupported() }); | ||
| }); | ||
| const BAR_LENGTH = 25; | ||
| const BLOCK_CHAR = "━"; | ||
| const BULLET_ICON = "●"; | ||
| /** @typedef {import("tapable").Tap} Tap */ | ||
@@ -28,2 +39,3 @@ /** | ||
| /** @typedef {import("./logging/Logger").Logger} Logger */ | ||
| /** @typedef {import("./cli").Colors} Colors */ | ||
@@ -55,8 +67,94 @@ /** | ||
| /** | ||
| * @param {Logger} logger logger | ||
| * @param {{ value: string | undefined, time: number }[]} lastStateInfo mutable state | ||
| * @param {number} percentage percentage | ||
| * @param {string} msg msg | ||
| * @param {string[]} args args | ||
| */ | ||
| const reportProfile = (logger, lastStateInfo, percentage, msg, args) => { | ||
| if (percentage === 0) { | ||
| lastStateInfo.length = 0; | ||
| } | ||
| const fullState = [msg, ...args]; | ||
| const state = fullState.map((s) => s.replace(/\d+\/\d+ /g, "")); | ||
| const now = Date.now(); | ||
| const len = Math.max(state.length, lastStateInfo.length); | ||
| for (let i = len; i >= 0; i--) { | ||
| const stateItem = i < state.length ? state[i] : undefined; | ||
| const lastStateItem = | ||
| i < lastStateInfo.length ? lastStateInfo[i] : undefined; | ||
| if (lastStateItem) { | ||
| if (stateItem !== lastStateItem.value) { | ||
| const diff = now - lastStateItem.time; | ||
| if (lastStateItem.value) { | ||
| let reportState = lastStateItem.value; | ||
| if (i > 0) { | ||
| reportState = `${lastStateInfo[i - 1].value} > ${reportState}`; | ||
| } | ||
| const stateMsg = `${" | ".repeat(i)}${diff} ms ${reportState}`; | ||
| const d = diff; | ||
| // This depends on timing so we ignore it for coverage | ||
| /* eslint-disable no-lone-blocks */ | ||
| /* istanbul ignore next */ | ||
| { | ||
| if (d > 10000) { | ||
| logger.error(stateMsg); | ||
| } else if (d > 1000) { | ||
| logger.warn(stateMsg); | ||
| } else if (d > 10) { | ||
| logger.info(stateMsg); | ||
| } else if (d > 5) { | ||
| logger.log(stateMsg); | ||
| } else { | ||
| logger.debug(stateMsg); | ||
| } | ||
| } | ||
| /* eslint-enable no-lone-blocks */ | ||
| } | ||
| if (stateItem === undefined) { | ||
| lastStateInfo.length = i; | ||
| } else { | ||
| lastStateItem.value = stateItem; | ||
| lastStateItem.time = now; | ||
| lastStateInfo.length = i + 1; | ||
| } | ||
| } | ||
| } else { | ||
| lastStateInfo[i] = { | ||
| value: stateItem, | ||
| time: now | ||
| }; | ||
| } | ||
| } | ||
| }; | ||
| /** | ||
| * @param {string} name progress bar name | ||
| * @param {string} color progress bar color | ||
| * @returns {(percentage: number) => string} bar renderer | ||
| */ | ||
| const createReportBar = (name, color) => { | ||
| const c = getColors(); | ||
| return (percentage) => { | ||
| const w = Math.round(percentage * BAR_LENGTH); | ||
| const filled = BLOCK_CHAR.repeat(w); | ||
| const empty = BLOCK_CHAR.repeat(BAR_LENGTH - w); | ||
| const colorFn = | ||
| color in c ? c[/** @type {keyof Colors} */ (color)] : c.green; | ||
| return `${[BULLET_ICON, name, filled].map(colorFn).join(" ")}${c.white(empty)}`; | ||
| }; | ||
| }; | ||
| /** @typedef {Required<Exclude<NonNullable<ProgressPluginOptions["progressBar"]>, boolean>>} ProgressBarOptions */ | ||
| /** | ||
| * Creates a default handler. | ||
| * @param {boolean | null | undefined} profile need profile | ||
| * @param {Logger} logger logger | ||
| * @param {ProgressBarOptions | false} progressBar render bar | ||
| * @returns {HandlerFn} default handler | ||
| */ | ||
| const createDefaultHandler = (profile, logger) => { | ||
| const createDefaultHandler = (profile, logger, progressBar) => { | ||
| /** @type {{ value: string | undefined, time: number }[]} */ | ||
@@ -68,57 +166,24 @@ const lastStateInfo = []; | ||
| if (profile) { | ||
| if (percentage === 0) { | ||
| lastStateInfo.length = 0; | ||
| reportProfile(logger, lastStateInfo, percentage, msg, args); | ||
| } | ||
| if (progressBar) { | ||
| const reportBar = createReportBar(progressBar.name, progressBar.color); | ||
| const c = getColors(); | ||
| /** @type {string} */ | ||
| const currentBar = reportBar(percentage); | ||
| if (percentage === 1) { | ||
| logger.status(); | ||
| } else if (msg) { | ||
| logger.status( | ||
| `${currentBar} (${Math.floor(percentage * 100)}%)`, | ||
| `\n${[msg, ...args].map(c.gray).join(" ")}` | ||
| ); | ||
| } else { | ||
| logger.status(`${currentBar} (${Math.floor(percentage * 100)}%)`); | ||
| } | ||
| const fullState = [msg, ...args]; | ||
| const state = fullState.map((s) => s.replace(/\d+\/\d+ /g, "")); | ||
| const now = Date.now(); | ||
| const len = Math.max(state.length, lastStateInfo.length); | ||
| for (let i = len; i >= 0; i--) { | ||
| const stateItem = i < state.length ? state[i] : undefined; | ||
| const lastStateItem = | ||
| i < lastStateInfo.length ? lastStateInfo[i] : undefined; | ||
| if (lastStateItem) { | ||
| if (stateItem !== lastStateItem.value) { | ||
| const diff = now - lastStateItem.time; | ||
| if (lastStateItem.value) { | ||
| let reportState = lastStateItem.value; | ||
| if (i > 0) { | ||
| reportState = `${lastStateInfo[i - 1].value} > ${reportState}`; | ||
| } | ||
| const stateMsg = `${" | ".repeat(i)}${diff} ms ${reportState}`; | ||
| const d = diff; | ||
| // This depends on timing so we ignore it for coverage | ||
| /* eslint-disable no-lone-blocks */ | ||
| /* istanbul ignore next */ | ||
| { | ||
| if (d > 10000) { | ||
| logger.error(stateMsg); | ||
| } else if (d > 1000) { | ||
| logger.warn(stateMsg); | ||
| } else if (d > 10) { | ||
| logger.info(stateMsg); | ||
| } else if (d > 5) { | ||
| logger.log(stateMsg); | ||
| } else { | ||
| logger.debug(stateMsg); | ||
| } | ||
| } | ||
| /* eslint-enable no-lone-blocks */ | ||
| } | ||
| if (stateItem === undefined) { | ||
| lastStateInfo.length = i; | ||
| } else { | ||
| lastStateItem.value = stateItem; | ||
| lastStateItem.time = now; | ||
| lastStateInfo.length = i + 1; | ||
| } | ||
| } | ||
| } else { | ||
| lastStateInfo[i] = { | ||
| value: stateItem, | ||
| time: now | ||
| }; | ||
| } | ||
| } | ||
| return; | ||
| } | ||
| logger.status(`${Math.floor(percentage * 100)}%`, msg, ...args); | ||
@@ -155,3 +220,4 @@ if (percentage === 1 || (!msg && args.length === 0)) logger.status(); | ||
| entries: true, | ||
| percentBy: null | ||
| percentBy: null, | ||
| progressBar: false | ||
| }; | ||
@@ -193,2 +259,8 @@ | ||
| this.percentBy = merged.percentBy; | ||
| const progressBar = merged.progressBar === true ? {} : merged.progressBar; | ||
| /** @type {ProgressBarOptions | false} */ | ||
| this.progressBar = progressBar | ||
| ? { name: "Build", color: "green", ...progressBar } | ||
| : false; | ||
| } | ||
@@ -206,3 +278,4 @@ | ||
| this.profile, | ||
| compiler.getInfrastructureLogger("webpack.Progress") | ||
| compiler.getInfrastructureLogger("webpack.Progress"), | ||
| this.progressBar | ||
| ); | ||
@@ -209,0 +282,0 @@ if (compiler instanceof MultiCompiler) { |
@@ -16,2 +16,3 @@ /* | ||
| /** @typedef {import("../../declarations/WebpackOptions").RuleSetUseItem} RuleSetUseItem */ | ||
| /** @typedef {import("../../declarations/WebpackOptions").RuleSetUseFunction} RuleSetUseFunction */ | ||
| /** @typedef {import("./RuleSetCompiler")} RuleSetCompiler */ | ||
@@ -86,3 +87,3 @@ /** @typedef {import("./RuleSetCompiler").Effect} Effect */ | ||
| * @param {string} defaultIdent default ident when none is provided | ||
| * @param {Exclude<NonNullable<RuleSetUseItem>, EXPECTED_FUNCTION>} item user provided use value | ||
| * @param {Exclude<NonNullable<RuleSetUseItem>, RuleSetUseFunction>} item user provided use value | ||
| * @returns {Effect} effect | ||
@@ -137,3 +138,3 @@ */ | ||
| "[[missing ident]]", | ||
| /** @type {Exclude<RuleSetUseItem, EXPECTED_FUNCTION>} */ | ||
| /** @type {Exclude<RuleSetUseItem, RuleSetUseFunction>} */ | ||
| (item) | ||
@@ -147,3 +148,3 @@ ) | ||
| "[[missing ident]]", | ||
| /** @type {Exclude<RuleSetUseItem, EXPECTED_FUNCTION>} */ | ||
| /** @type {Exclude<RuleSetUseItem, RuleSetUseFunction>} */ | ||
| (items) | ||
@@ -150,0 +151,0 @@ ) |
@@ -124,4 +124,30 @@ /* | ||
| return `${fn} = ${runtimeTemplate.basicFunction("moduleId, mode", [ | ||
| // Per the TC39 import-defer spec, deferred namespaces are | ||
| // distinct from their eager counterparts and the same module | ||
| // referenced from multiple defer-import sites must yield the | ||
| // same object. Cache the Proxy / fake namespace per-moduleId so | ||
| // repeated calls (including across files) share identity. | ||
| // | ||
| // Bit 16 (`createFakeNamespaceObject`'s "return value when | ||
| // it's Promise-like" flag added by | ||
| // `RuntimeTemplate.moduleNamespacePromise` for dynamic | ||
| // imports) is irrelevant for deferred namespaces — the value | ||
| // passed into `createFakeNamespaceObject` here is always the | ||
| // resolved module exports (after unwrapping the async-module | ||
| // export symbol when present), never a Promise. Strip it | ||
| // once so all downstream behavior, the cache key, and the | ||
| // `createFakeNamespaceObject` call below see the same shape | ||
| // mode. This keeps static defer (mode 8) and dynamic | ||
| // `await import.defer` (mode 8 | 16) sharing the same | ||
| // Deferred Module Namespace object, while still keying by | ||
| // `(moduleId, mode)` so distinct exports-type shapes | ||
| // (e.g. one importer treats a CJS module as | ||
| // "default-with-named", another as "namespace") get | ||
| // distinct cache entries. | ||
| "mode &= ~16;", | ||
| "var byMode = __webpack_module_deferred_namespace_cache__[moduleId];", | ||
| "if (byMode && byMode[mode] !== undefined) return byMode[mode];", | ||
| "if (!byMode) byMode = __webpack_module_deferred_namespace_cache__[moduleId] = {};", | ||
| "var cachedModule = __webpack_module_cache__[moduleId];", | ||
| "if (cachedModule && cachedModule.error === undefined) {", | ||
| "if (cachedModule && cachedModule.error === undefined && !(mode & 8)) {", | ||
| Template.indent([ | ||
@@ -132,4 +158,3 @@ "var exports = cachedModule.exports;", | ||
| : "", | ||
| "if (mode & 8) return exports;", | ||
| `return ${RuntimeGlobals.createFakeNamespaceObject}(exports, mode);` | ||
| `return byMode[mode] = ${RuntimeGlobals.createFakeNamespaceObject}(exports, mode);` | ||
| ]), | ||
@@ -146,5 +171,19 @@ "}", | ||
| Template.indent([ | ||
| "delete handler.defineProperty;", | ||
| "delete handler.deleteProperty;", | ||
| "delete handler.set;", | ||
| // Drop only the read-side traps after init: with the | ||
| // resolved namespace's own keys mirrored onto | ||
| // `ns_target` below, the default `Reflect` behavior | ||
| // returns the right values via the live-binding | ||
| // getters, so we no longer need to intercept `get` / | ||
| // `has` / `ownKeys` / `getOwnPropertyDescriptor`. | ||
| // | ||
| // The mutation traps (`set`, `deleteProperty`, | ||
| // `defineProperty`) are kept because per the TC39 | ||
| // import-defer spec, `[[Set]]` / `[[Delete]]` / | ||
| // `[[DefineOwnProperty]]` on a Deferred Module | ||
| // Namespace Exotic Object never succeed — and the | ||
| // proxy target itself remains extensible | ||
| // (architecturally we cannot freeze it up-front), | ||
| // so without these traps `ns.notExported = "x"` | ||
| // after evaluation would silently create a property | ||
| // on the target instead of returning false. | ||
| "delete handler.get;", | ||
@@ -159,9 +198,54 @@ "delete handler.has;", | ||
| ]), | ||
| "}", | ||
| // Mirror own properties from the resolved namespace onto the proxy | ||
| // target so that proxy invariants hold for callers that structurally | ||
| // introspect via `Object.keys` / `Object.getOwnPropertyNames` / | ||
| // `Object.getOwnPropertyDescriptor`: when our trap reports a | ||
| // non-configurable descriptor for a key, the target must also have | ||
| // that key with a matching descriptor. | ||
| // | ||
| // `__esModule` and `Symbol.toStringTag` are intentionally skipped: | ||
| // the proxy synthesizes "Deferred Module" / true regardless of what | ||
| // the underlying namespace exposes (per the TC39 import-defer | ||
| // proposal, the [[StringTag]] of a Deferred Module Namespace | ||
| // Exotic Object is "Deferred Module"), and the target was already | ||
| // pre-populated with those values below. | ||
| "var keys = Reflect.ownKeys(ns);", | ||
| "for (var i = 0; i < keys.length; i++) {", | ||
| Template.indent([ | ||
| "var k = keys[i];", | ||
| 'if (k === "__esModule" || k === Symbol.toStringTag) continue;', | ||
| "if (!Object.prototype.hasOwnProperty.call(ns_target, k)) {", | ||
| Template.indent([ | ||
| "try { Object.defineProperty(ns_target, k, Reflect.getOwnPropertyDescriptor(ns, k)); } catch (_) {}" | ||
| ]), | ||
| "}" | ||
| ]), | ||
| "}" | ||
| ])};`, | ||
| "", | ||
| "var ns = __webpack_module_deferred_exports__[moduleId] || (__webpack_module_deferred_exports__[moduleId] = { __proto__: null });", | ||
| // The proxy target is a fresh placeholder, separate from | ||
| // `__webpack_module_deferred_exports__[moduleId]` (which is reused | ||
| // by `__webpack_require__` as `module.exports` for deferred-loaded | ||
| // modules and would conflict with our pre-populated synthetic | ||
| // `__esModule` / `Symbol.toStringTag` non-configurable properties). | ||
| // Using a dedicated target keeps the proxy invariant-compliant | ||
| // without interfering with the module's own exports object. | ||
| "var ns_target = { __proto__: null };", | ||
| // Pre-populate the synthetic deferred-namespace properties with | ||
| // fully non-configurable, non-writable, non-enumerable descriptors | ||
| // (matching the TC39 import-defer spec for Module Namespace | ||
| // Exotic Objects). The trap returns the same descriptors below. | ||
| 'Object.defineProperty(ns_target, "__esModule", { value: true });', | ||
| 'Object.defineProperty(ns_target, Symbol.toStringTag, { value: "Deferred Module" });', | ||
| "var ns = ns_target;", | ||
| "var handler = {", | ||
| Template.indent([ | ||
| "__proto__: null,", | ||
| // Per the TC39 import-defer proposal, `IsSymbolLikeNamespaceKey` | ||
| // returns true for any Symbol-keyed access (and for "then"); such | ||
| // accesses go through `OrdinaryGetOwnProperty` and must not | ||
| // trigger evaluation of the deferred module. The Symbol checks | ||
| // below short-circuit to the pre-populated target without | ||
| // running `init()`. | ||
| `get: ${runtimeTemplate.basicFunction("_, name", [ | ||
@@ -175,2 +259,3 @@ "switch (name) {", | ||
| "}", | ||
| 'if (typeof name === "symbol") return ns_target[name];', | ||
| init, | ||
@@ -194,2 +279,3 @@ "return ns[name];" | ||
| "}", | ||
| 'if (typeof name === "symbol") return name in ns_target;', | ||
| init, | ||
@@ -206,7 +292,12 @@ "return name in ns;" | ||
| Template.indent([ | ||
| 'case "__esModule": return { value: true, configurable: !(mode & 8) };', | ||
| 'case Symbol.toStringTag: return { value: "Deferred Module", configurable: !(mode & 8) };', | ||
| // Match the descriptors actually defined on `ns_target` | ||
| // (non-configurable, non-writable, non-enumerable) so the | ||
| // proxy invariant holds for both the trap result and any | ||
| // post-init forwarding via the deleted-handler path. | ||
| 'case "__esModule": return { value: true, writable: false, enumerable: false, configurable: false };', | ||
| 'case Symbol.toStringTag: return { value: "Deferred Module", writable: false, enumerable: false, configurable: false };', | ||
| 'case "then": return undefined;' | ||
| ]), | ||
| "}", | ||
| 'if (typeof name === "symbol") return Reflect.getOwnPropertyDescriptor(ns_target, name);', | ||
| init, | ||
@@ -219,9 +310,24 @@ "var desc = Reflect.getOwnPropertyDescriptor(ns, name);", | ||
| ])},`, | ||
| // `defineProperty` always rejects, but per the TC39 spec it | ||
| // must still trigger evaluation for string keys (the spec | ||
| // algorithm calls `[[GetOwnProperty]]` first, which forces | ||
| // evaluation on a deferred namespace). Symbol keys go through | ||
| // OrdinaryDefineOwnProperty and do not trigger eval. | ||
| `defineProperty: ${runtimeTemplate.basicFunction("_, name", [ | ||
| 'if (typeof name === "symbol" || name === "then") return false;', | ||
| init, | ||
| // Note: This behavior does not match the spec one, but since webpack does not do it either | ||
| // for a normal Module Namespace object (in MakeNamespaceObjectRuntimeModule), let's keep it simple. | ||
| "return false;" | ||
| ])},`, | ||
| `deleteProperty: ${runtimeTemplate.returningFunction("false")},`, | ||
| // `deleteProperty` rejects, but per the TC39 spec it must | ||
| // still trigger evaluation for string keys (the spec | ||
| // algorithm calls `GetModuleExportsList` for non-symbol-like | ||
| // keys, forcing evaluation on a deferred namespace). | ||
| `deleteProperty: ${runtimeTemplate.basicFunction("_, name", [ | ||
| 'if (typeof name === "symbol" || name === "then") return false;', | ||
| init, | ||
| "return false;" | ||
| ])},`, | ||
| // `set` always returns false without triggering evaluation — | ||
| // the spec [[Set]] algorithm for Module Namespaces is just | ||
| // "return false" (no [[GetOwnProperty]], no eval). | ||
| `set: ${runtimeTemplate.returningFunction("false")},` | ||
@@ -231,3 +337,3 @@ ]), | ||
| // we don't fully emulate ES Module semantics in this Proxy to align with normal webpack esm namespace object. | ||
| "return new Proxy(ns, handler);" | ||
| "return byMode[mode] = new Proxy(ns_target, handler);" | ||
| ])};`; | ||
@@ -234,0 +340,0 @@ } |
@@ -86,8 +86,3 @@ /* | ||
| /** | ||
| * merge multiple CSS stylesheets (CSSStyleSheet or string) into one CSS text string | ||
| * Arguments: (sheets: Array<CSSStyleSheet | string> | CSSStyleSheet | string) => string | ||
| */ | ||
| module.exports.cssInjectStyle = "__webpack_require__.is"; | ||
| module.exports.cssMergeStyleSheets = "__webpack_require__.mcs"; | ||
@@ -396,2 +391,7 @@ /** | ||
| /** | ||
| * set .name to "default" for anonymous default exports per ES spec | ||
| */ | ||
| module.exports.setAnonymousDefaultName = "__webpack_require__.dn"; | ||
| /** | ||
| * an object with all share scopes | ||
@@ -398,0 +398,0 @@ */ |
@@ -132,8 +132,10 @@ /* | ||
| try { | ||
| if (this.fullHash || this.dependentHash) { | ||
| // Do not use getGeneratedCode here, because i. e. compilation hash might be not | ||
| // ready at this point. We will cache it later instead. | ||
| hash.update(/** @type {string} */ (this.generate())); | ||
| } else { | ||
| hash.update(/** @type {string} */ (this.getGeneratedCode())); | ||
| const code = | ||
| this.fullHash || this.dependentHash | ||
| ? // Do not use getGeneratedCode here, because i. e. compilation hash might be not | ||
| // ready at this point. We will cache it later instead. | ||
| this.generate() | ||
| : this.getGeneratedCode(); | ||
| if (code !== null && code !== undefined) { | ||
| hash.update(code); | ||
| } | ||
@@ -211,3 +213,3 @@ } catch (err) { | ||
| generate() { | ||
| const AbstractMethodError = require("./AbstractMethodError"); | ||
| const AbstractMethodError = require("./errors/AbstractMethodError"); | ||
@@ -214,0 +216,0 @@ throw new AbstractMethodError(); |
+11
-0
@@ -37,2 +37,3 @@ /* | ||
| const RuntimeIdRuntimeModule = require("./runtime/RuntimeIdRuntimeModule"); | ||
| const SetAnonymousDefaultNameRuntimeModule = require("./runtime/SetAnonymousDefaultNameRuntimeModule"); | ||
| const SystemContextRuntimeModule = require("./runtime/SystemContextRuntimeModule"); | ||
@@ -83,2 +84,3 @@ const ToBinaryRuntimeModule = require("./runtime/ToBinaryRuntimeModule"); | ||
| RuntimeGlobals.loadScript, | ||
| RuntimeGlobals.setAnonymousDefaultName, | ||
| RuntimeGlobals.systemContext, | ||
@@ -244,2 +246,11 @@ RuntimeGlobals.onChunksLoaded, | ||
| compilation.hooks.runtimeRequirementInTree | ||
| .for(RuntimeGlobals.setAnonymousDefaultName) | ||
| .tap(PLUGIN_NAME, (chunk) => { | ||
| compilation.addRuntimeModule( | ||
| chunk, | ||
| new SetAnonymousDefaultNameRuntimeModule() | ||
| ); | ||
| return true; | ||
| }); | ||
| compilation.hooks.runtimeRequirementInTree | ||
| .for(RuntimeGlobals.runtimeId) | ||
@@ -246,0 +257,0 @@ .tap(PLUGIN_NAME, (chunk) => { |
@@ -27,3 +27,3 @@ /* | ||
| .for("data") | ||
| .tap(PLUGIN_NAME, (resourceData) => { | ||
| .tap(PLUGIN_NAME, (resourceData, resolveData) => { | ||
| const match = URIRegEx.exec(resourceData.resource); | ||
@@ -38,2 +38,14 @@ if (match) { | ||
| } | ||
| // Inherit the issuer's resolution context so any nested | ||
| // dependencies discovered while parsing the data URI's body | ||
| // (e.g. `url(...)` / `@import` inside an inline CSS data | ||
| // URI) resolve relative to where the URI was referenced | ||
| // from, instead of against the synthetic `data:.../` path | ||
| // that `getContext("data:…")` would otherwise infer. | ||
| if ( | ||
| resourceData.context === undefined && | ||
| resolveData.context !== undefined | ||
| ) { | ||
| resourceData.context = resolveData.context; | ||
| } | ||
| }); | ||
@@ -40,0 +52,0 @@ |
@@ -10,4 +10,4 @@ /* | ||
| const ModuleNotFoundError = require("../ModuleNotFoundError"); | ||
| const NormalModule = require("../NormalModule"); | ||
| const ModuleNotFoundError = require("../errors/ModuleNotFoundError"); | ||
| const { isAbsolute, join } = require("../util/fs"); | ||
@@ -14,0 +14,0 @@ const { parseResourceWithoutFragment } = require("../util/identifier"); |
@@ -40,3 +40,3 @@ /* | ||
| serialize(data, context) { | ||
| const AbstractMethodError = require("../AbstractMethodError"); | ||
| const AbstractMethodError = require("../errors/AbstractMethodError"); | ||
@@ -55,3 +55,3 @@ throw new AbstractMethodError(); | ||
| deserialize(data, context) { | ||
| const AbstractMethodError = require("../AbstractMethodError"); | ||
| const AbstractMethodError = require("../errors/AbstractMethodError"); | ||
@@ -58,0 +58,0 @@ throw new AbstractMethodError(); |
@@ -8,6 +8,6 @@ /* | ||
| const ModuleNotFoundError = require("../ModuleNotFoundError"); | ||
| const RuntimeGlobals = require("../RuntimeGlobals"); | ||
| const WebpackError = require("../WebpackError"); | ||
| const { parseOptions } = require("../container/options"); | ||
| const ModuleNotFoundError = require("../errors/ModuleNotFoundError"); | ||
| const WebpackError = require("../errors/WebpackError"); | ||
| const LazySet = require("../util/LazySet"); | ||
@@ -14,0 +14,0 @@ const { parseRange } = require("../util/semver"); |
@@ -11,2 +11,3 @@ /* | ||
| const Template = require("../Template"); | ||
| const { compareModulesById } = require("../util/comparators"); | ||
| const { | ||
@@ -75,8 +76,10 @@ parseVersionRuntimeCode, | ||
| }; | ||
| const byId = compareModulesById(chunkGraph); | ||
| for (const chunk of /** @type {Chunk} */ ( | ||
| this.chunk | ||
| ).getAllReferencedChunks()) { | ||
| const modules = chunkGraph.getChunkModulesIterableBySourceType( | ||
| const modules = chunkGraph.getOrderedChunkModulesIterableBySourceType( | ||
| chunk, | ||
| "consume-shared" | ||
| "consume-shared", | ||
| byId | ||
| ); | ||
@@ -93,5 +96,6 @@ if (!modules) continue; | ||
| ).getAllInitialChunks()) { | ||
| const modules = chunkGraph.getChunkModulesIterableBySourceType( | ||
| const modules = chunkGraph.getOrderedChunkModulesIterableBySourceType( | ||
| chunk, | ||
| "consume-shared" | ||
| "consume-shared", | ||
| byId | ||
| ); | ||
@@ -98,0 +102,0 @@ if (!modules) continue; |
@@ -57,3 +57,3 @@ /* | ||
| identifier() { | ||
| return `provide module (${this._shareScope}) ${this._name}@${this._version} = ${this._request}`; | ||
| return `provide module (${this._shareScope}) ${this._name}@${this._version}|${this._request}`; | ||
| } | ||
@@ -60,0 +60,0 @@ |
@@ -8,4 +8,4 @@ /* | ||
| const WebpackError = require("../WebpackError"); | ||
| const { parseOptions } = require("../container/options"); | ||
| const WebpackError = require("../errors/WebpackError"); | ||
| const ProvideForSharedDependency = require("./ProvideForSharedDependency"); | ||
@@ -12,0 +12,0 @@ const ProvideSharedDependency = require("./ProvideSharedDependency"); |
@@ -8,3 +8,3 @@ /* | ||
| const ModuleNotFoundError = require("../ModuleNotFoundError"); | ||
| const ModuleNotFoundError = require("../errors/ModuleNotFoundError"); | ||
| const LazySet = require("../util/LazySet"); | ||
@@ -11,0 +11,0 @@ |
@@ -34,3 +34,3 @@ /* | ||
| /** @typedef {{ [Key in Exclude<StatsValue, boolean | EXPECTED_OBJECT | "normal">]: StatsOptions }} NamedPresets */ | ||
| /** @typedef {{ [Key in Exclude<StatsValue, boolean | StatsOptions | "normal">]: StatsOptions }} NamedPresets */ | ||
@@ -37,0 +37,0 @@ /** @type {NamedPresets} */ |
@@ -1513,3 +1513,3 @@ /* | ||
| formatLayer: (layer) => `(in ${layer})`, | ||
| formatSize: require("../SizeFormatHelpers").formatSize, | ||
| formatSize: require("../util/formatSize"), | ||
| formatDateTime: (dateTime, { bold }) => { | ||
@@ -1516,0 +1516,0 @@ const d = new Date(dateTime); |
@@ -21,3 +21,3 @@ /* | ||
| /** @typedef {import("../ModuleGraphConnection")} ModuleGraphConnection */ | ||
| /** @typedef {import("../WebpackError")} WebpackError */ | ||
| /** @typedef {import("../errors/WebpackError")} WebpackError */ | ||
| /** @typedef {import("../util/comparators").Comparator<EXPECTED_ANY>} Comparator */ | ||
@@ -24,0 +24,0 @@ /** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ |
@@ -9,5 +9,3 @@ /* | ||
| const { pathToFileURL } = require("url"); | ||
| const CommentCompilationWarning = require("../CommentCompilationWarning"); | ||
| const RuntimeGlobals = require("../RuntimeGlobals"); | ||
| const UnsupportedFeatureWarning = require("../UnsupportedFeatureWarning"); | ||
| const ConstDependency = require("../dependencies/ConstDependency"); | ||
@@ -17,2 +15,4 @@ const ContextDependencyHelpers = require("../dependencies/ContextDependencyHelpers"); | ||
| const URLDependency = require("../dependencies/URLDependency"); | ||
| const CommentCompilationWarning = require("../errors/CommentCompilationWarning"); | ||
| const UnsupportedFeatureWarning = require("../errors/UnsupportedFeatureWarning"); | ||
| const BasicEvaluatedExpression = require("../javascript/BasicEvaluatedExpression"); | ||
@@ -19,0 +19,0 @@ const { approve } = require("../javascript/JavascriptParserHelpers"); |
@@ -9,4 +9,4 @@ /* | ||
| const { AsyncSeriesHook, SyncHook } = require("tapable"); | ||
| const { makeWebpackError } = require("../HookWebpackError"); | ||
| const WebpackError = require("../WebpackError"); | ||
| const { makeWebpackError } = require("../errors/HookWebpackError"); | ||
| const WebpackError = require("../errors/WebpackError"); | ||
| const ArrayQueue = require("./ArrayQueue"); | ||
@@ -13,0 +13,0 @@ |
@@ -135,6 +135,6 @@ /* | ||
| const cachedParseObject = (obj) => { | ||
| const entry = parseCache.get(/** @type {EXPECTED_OBJECT} */ (obj)); | ||
| const entry = parseCache.get(obj); | ||
| if (entry !== undefined) return entry; | ||
| const result = parseObject(obj); | ||
| parseCache.set(/** @type {EXPECTED_OBJECT} */ (obj), result); | ||
| parseCache.set(obj, result); | ||
| return result; | ||
@@ -141,0 +141,0 @@ }; |
@@ -59,6 +59,6 @@ /* | ||
| const createCachedParameterizedComparator = (fn) => { | ||
| /** @type {WeakMap<EXPECTED_OBJECT, Comparator<T>>} */ | ||
| /** @type {WeakMap<TArg, Comparator<T>>} */ | ||
| const map = new WeakMap(); | ||
| return (arg) => { | ||
| const cachedResult = map.get(/** @type {EXPECTED_OBJECT} */ (arg)); | ||
| const cachedResult = map.get(arg); | ||
| if (cachedResult !== undefined) return cachedResult; | ||
@@ -72,3 +72,3 @@ /** | ||
| const result = fn.bind(null, arg); | ||
| map.set(/** @type {EXPECTED_OBJECT} */ (arg), result); | ||
| map.set(arg, result); | ||
| return result; | ||
@@ -75,0 +75,0 @@ }; |
@@ -10,6 +10,6 @@ /* | ||
| /** @typedef {import("eslint-scope").Scope} Scope */ | ||
| /** @typedef {import("eslint-scope").Reference} Reference */ | ||
| /** @typedef {import("eslint-scope").Variable} Variable */ | ||
| /** @typedef {import("estree").Node} Node */ | ||
| /** @typedef {import("../javascript/JavascriptModulesPlugin").Scope} Scope */ | ||
| /** @typedef {import("../javascript/JavascriptModulesPlugin").Reference} Reference */ | ||
| /** @typedef {import("../javascript/JavascriptModulesPlugin").Variable} Variable */ | ||
| /** @typedef {import("../javascript/JavascriptParser").Range} Range */ | ||
@@ -16,0 +16,0 @@ /** @typedef {Set<string>} UsedNames */ |
@@ -84,2 +84,22 @@ /* | ||
| /** | ||
| * Safely stringify an arbitrary value for an error message — falls back to | ||
| * `String(...)` when JSON.stringify would throw (BigInt, circular, etc.). | ||
| * @param {EXPECTED_ANY} value value to stringify | ||
| * @returns {string} stringified value | ||
| */ | ||
| const safeStringify = (value) => { | ||
| try { | ||
| const json = JSON.stringify(value); | ||
| if (json !== undefined) return json; | ||
| } catch (_err) { | ||
| // fall through to String fallback | ||
| } | ||
| try { | ||
| return String(value); | ||
| } catch (_err) { | ||
| return "[value cannot be converted to string]"; | ||
| } | ||
| }; | ||
| /** | ||
| * Returns results. | ||
@@ -94,3 +114,24 @@ * @param {string} input input | ||
| if (typeof convention === "function") { | ||
| set.add(convention(input)); | ||
| const result = convention(input); | ||
| const validate = (/** @type {string} */ name) => { | ||
| if (typeof name !== "string" || name.length === 0) { | ||
| throw new Error( | ||
| `exportsConvention function must return a non-empty string or an array of non-empty strings, got ${safeStringify(result)}` | ||
| ); | ||
| } | ||
| }; | ||
| if (Array.isArray(result)) { | ||
| if (result.length === 0) { | ||
| throw new Error( | ||
| "exportsConvention function returned an empty array; it must return at least one name" | ||
| ); | ||
| } | ||
| for (const name of result) { | ||
| validate(name); | ||
| set.add(name); | ||
| } | ||
| } else { | ||
| validate(result); | ||
| set.add(result); | ||
| } | ||
| } else { | ||
@@ -97,0 +138,0 @@ switch (convention) { |
+8
-8
@@ -247,8 +247,8 @@ /* | ||
| * @typedef {{ | ||
| * (path: PathLike, options?: undefined): IStats, | ||
| * (path: PathLike): IStats, | ||
| * (path: PathLike, options?: StatSyncOptions & { bigint?: false | undefined, throwIfNoEntry?: true | undefined }): IStats, | ||
| * (path: PathLike, options: StatSyncOptions & { bigint: true, throwIfNoEntry?: true | undefined }): IBigIntStats, | ||
| * (path: PathLike, options?: StatSyncOptions & { bigint?: false | undefined, throwIfNoEntry: false }): IStats | undefined, | ||
| * (path: PathLike, options: StatSyncOptions & { bigint: true, throwIfNoEntry: false }): IBigIntStats | undefined, | ||
| * (path: PathLike, options?: StatSyncOptions & { bigint?: false | undefined }): IStats, | ||
| * (path: PathLike, options: StatSyncOptions & { bigint: true }): IBigIntStats, | ||
| * (path: PathLike, options: StatSyncOptions & { bigint: boolean, throwIfNoEntry?: false | undefined }): IStats | IBigIntStats, | ||
| * (path: PathLike, options: StatSyncOptions & { bigint: boolean, throwIfNoEntry?: true | undefined }): IStats | IBigIntStats, | ||
| * (path: PathLike, options?: StatSyncOptions): IStats | IBigIntStats | undefined, | ||
@@ -271,8 +271,8 @@ * }} StatSync | ||
| * @typedef {{ | ||
| * (path: PathLike, options?: undefined): IStats, | ||
| * (path: PathLike): IStats, | ||
| * (path: PathLike, options?: StatSyncOptions & { bigint?: false | undefined, throwIfNoEntry?: true | undefined }): IStats, | ||
| * (path: PathLike, options: StatSyncOptions & { bigint: true, throwIfNoEntry?: true | undefined }): IBigIntStats, | ||
| * (path: PathLike, options?: StatSyncOptions & { bigint?: false | undefined, throwIfNoEntry: false }): IStats | undefined, | ||
| * (path: PathLike, options: StatSyncOptions & { bigint: true, throwIfNoEntry: false }): IBigIntStats | undefined, | ||
| * (path: PathLike, options?: StatSyncOptions & { bigint?: false | undefined }): IStats, | ||
| * (path: PathLike, options: StatSyncOptions & { bigint: true }): IBigIntStats, | ||
| * (path: PathLike, options: StatSyncOptions & { bigint: boolean, throwIfNoEntry?: false | undefined }): IStats | IBigIntStats, | ||
| * (path: PathLike, options: StatSyncOptions & { bigint: boolean, throwIfNoEntry?: true | undefined }): IStats | IBigIntStats, | ||
| * (path: PathLike, options?: StatSyncOptions): IStats | IBigIntStats | undefined, | ||
@@ -279,0 +279,0 @@ * }} LStatSync |
+2
-2
@@ -36,3 +36,3 @@ /* | ||
| update(data, inputEncoding) { | ||
| const AbstractMethodError = require("../AbstractMethodError"); | ||
| const AbstractMethodError = require("../errors/AbstractMethodError"); | ||
@@ -63,3 +63,3 @@ throw new AbstractMethodError(); | ||
| digest(encoding) { | ||
| const AbstractMethodError = require("../AbstractMethodError"); | ||
| const AbstractMethodError = require("../errors/AbstractMethodError"); | ||
@@ -66,0 +66,0 @@ throw new AbstractMethodError(); |
@@ -14,3 +14,3 @@ /* | ||
| // 2150 bytes | ||
| "AGFzbQEAAAABCAJgAX8AYAAAAwUEAQAAAAUDAQABBhoFfwFBAAt/AUEAC38BQQALfwFBAAt/AUEACwciBARpbml0AAAGdXBkYXRlAAIFZmluYWwAAwZtZW1vcnkCAAqFEAQmAEGBxpS6BiQBQYnXtv5+JAJB/rnrxXkkA0H2qMmBASQEQQAkAAvQCgEZfyMBIQUjAiECIwMhAyMEIQQDQCAAIAFLBEAgASgCBCIOIAQgAyABKAIAIg8gBSAEIAIgAyAEc3FzampBA3ciCCACIANzcXNqakEHdyEJIAEoAgwiBiACIAggASgCCCIQIAMgAiAJIAIgCHNxc2pqQQt3IgogCCAJc3FzampBE3chCyABKAIUIgcgCSAKIAEoAhAiESAIIAkgCyAJIApzcXNqakEDdyIMIAogC3Nxc2pqQQd3IQ0gASgCHCIJIAsgDCABKAIYIgggCiALIA0gCyAMc3FzampBC3ciEiAMIA1zcXNqakETdyETIAEoAiQiFCANIBIgASgCICIVIAwgDSATIA0gEnNxc2pqQQN3IgwgEiATc3FzampBB3chDSABKAIsIgsgEyAMIAEoAigiCiASIBMgDSAMIBNzcXNqakELdyISIAwgDXNxc2pqQRN3IRMgASgCNCIWIA0gEiABKAIwIhcgDCANIBMgDSASc3FzampBA3ciGCASIBNzcXNqakEHdyEZIBggASgCPCINIBMgGCABKAI4IgwgEiATIBkgEyAYc3FzampBC3ciEiAYIBlzcXNqakETdyITIBIgGXJxIBIgGXFyaiAPakGZ84nUBWpBA3ciGCATIBIgGSAYIBIgE3JxIBIgE3FyaiARakGZ84nUBWpBBXciEiATIBhycSATIBhxcmogFWpBmfOJ1AVqQQl3IhMgEiAYcnEgEiAYcXJqIBdqQZnzidQFakENdyIYIBIgE3JxIBIgE3FyaiAOakGZ84nUBWpBA3ciGSAYIBMgEiAZIBMgGHJxIBMgGHFyaiAHakGZ84nUBWpBBXciEiAYIBlycSAYIBlxcmogFGpBmfOJ1AVqQQl3IhMgEiAZcnEgEiAZcXJqIBZqQZnzidQFakENdyIYIBIgE3JxIBIgE3FyaiAQakGZ84nUBWpBA3ciGSAYIBMgEiAZIBMgGHJxIBMgGHFyaiAIakGZ84nUBWpBBXciEiAYIBlycSAYIBlxcmogCmpBmfOJ1AVqQQl3IhMgEiAZcnEgEiAZcXJqIAxqQZnzidQFakENdyIYIBIgE3JxIBIgE3FyaiAGakGZ84nUBWpBA3ciGSAYIBMgEiAZIBMgGHJxIBMgGHFyaiAJakGZ84nUBWpBBXciEiAYIBlycSAYIBlxcmogC2pBmfOJ1AVqQQl3IhMgEiAZcnEgEiAZcXJqIA1qQZnzidQFakENdyIYIBNzIBJzaiAPakGh1+f2BmpBA3ciDyAYIBMgEiAPIBhzIBNzaiAVakGh1+f2BmpBCXciEiAPcyAYc2ogEWpBodfn9gZqQQt3IhEgEnMgD3NqIBdqQaHX5/YGakEPdyIPIBFzIBJzaiAQakGh1+f2BmpBA3ciECAPIBEgEiAPIBBzIBFzaiAKakGh1+f2BmpBCXciCiAQcyAPc2ogCGpBodfn9gZqQQt3IgggCnMgEHNqIAxqQaHX5/YGakEPdyIMIAhzIApzaiAOakGh1+f2BmpBA3ciDiAMIAggCiAMIA5zIAhzaiAUakGh1+f2BmpBCXciCCAOcyAMc2ogB2pBodfn9gZqQQt3IgcgCHMgDnNqIBZqQaHX5/YGakEPdyIKIAdzIAhzaiAGakGh1+f2BmpBA3ciBiAFaiEFIAIgCiAHIAggBiAKcyAHc2ogC2pBodfn9gZqQQl3IgcgBnMgCnNqIAlqQaHX5/YGakELdyIIIAdzIAZzaiANakGh1+f2BmpBD3dqIQIgAyAIaiEDIAQgB2ohBCABQUBrIQEMAQsLIAUkASACJAIgAyQDIAQkBAsNACAAEAEjACAAaiQAC/sEAgN/AX4jACAAaq1CA4YhBCAAQcgAakFAcSICQQhrIAAiAUEBaiEAIAFBgAE6AAADQCAAIAJJQQAgAEEHcRsEQCAAQQA6AAAgAEEBaiEADAELCwNAIAAgAkkEQCAAQgA3AwAgAEEIaiEADAELCyAENwMAIAIQAUEAIwGtIgRC//8DgyAEQoCA/P8Pg0IQhoQiBEL/gYCA8B+DIARCgP6DgIDgP4NCCIaEIgRCj4C8gPCBwAeDQgiGIARC8IHAh4CegPgAg0IEiIQiBEKGjJiw4MCBgwZ8QgSIQoGChIiQoMCAAYNCJ34gBEKw4MCBg4aMmDCEfDcDAEEIIwKtIgRC//8DgyAEQoCA/P8Pg0IQhoQiBEL/gYCA8B+DIARCgP6DgIDgP4NCCIaEIgRCj4C8gPCBwAeDQgiGIARC8IHAh4CegPgAg0IEiIQiBEKGjJiw4MCBgwZ8QgSIQoGChIiQoMCAAYNCJ34gBEKw4MCBg4aMmDCEfDcDAEEQIwOtIgRC//8DgyAEQoCA/P8Pg0IQhoQiBEL/gYCA8B+DIARCgP6DgIDgP4NCCIaEIgRCj4C8gPCBwAeDQgiGIARC8IHAh4CegPgAg0IEiIQiBEKGjJiw4MCBgwZ8QgSIQoGChIiQoMCAAYNCJ34gBEKw4MCBg4aMmDCEfDcDAEEYIwStIgRC//8DgyAEQoCA/P8Pg0IQhoQiBEL/gYCA8B+DIARCgP6DgIDgP4NCCIaEIgRCj4C8gPCBwAeDQgiGIARC8IHAh4CegPgAg0IEiIQiBEKGjJiw4MCBgwZ8QgSIQoGChIiQoMCAAYNCJ34gBEKw4MCBg4aMmDCEfDcDAAs=", | ||
| "AGFzbQEAAAABCAJgAX8AYAAAAwUEAAABAAUDAQABBhoFfwFBAAt/AUEAC38BQQALfwFBAAt/AUEACwciBARpbml0AAIGdXBkYXRlAAEFZmluYWwAAwZtZW1vcnkCAAqFEATQCgEZfyMBIQUjAiECIwMhAyMEIQQDQCAAIAFLBEAgASgCBCIOIAQgAyABKAIAIg8gBSAEIAIgAyAEc3FzampBA3ciCCACIANzcXNqakEHdyEJIAEoAgwiBiACIAggASgCCCIQIAMgAiAJIAIgCHNxc2pqQQt3IgogCCAJc3FzampBE3chCyABKAIUIgcgCSAKIAEoAhAiESAIIAkgCyAJIApzcXNqakEDdyIMIAogC3Nxc2pqQQd3IQ0gASgCHCIJIAsgDCABKAIYIgggCiALIA0gCyAMc3FzampBC3ciEiAMIA1zcXNqakETdyETIAEoAiQiFCANIBIgASgCICIVIAwgDSATIA0gEnNxc2pqQQN3IgwgEiATc3FzampBB3chDSABKAIsIgsgEyAMIAEoAigiCiASIBMgDSAMIBNzcXNqakELdyISIAwgDXNxc2pqQRN3IRMgASgCNCIWIA0gEiABKAIwIhcgDCANIBMgDSASc3FzampBA3ciGCASIBNzcXNqakEHdyEZIBggASgCPCINIBMgGCABKAI4IgwgEiATIBkgEyAYc3FzampBC3ciEiAYIBlzcXNqakETdyITIBIgGXJxIBIgGXFyaiAPakGZ84nUBWpBA3ciGCATIBIgGSAYIBIgE3JxIBIgE3FyaiARakGZ84nUBWpBBXciEiATIBhycSATIBhxcmogFWpBmfOJ1AVqQQl3IhMgEiAYcnEgEiAYcXJqIBdqQZnzidQFakENdyIYIBIgE3JxIBIgE3FyaiAOakGZ84nUBWpBA3ciGSAYIBMgEiAZIBMgGHJxIBMgGHFyaiAHakGZ84nUBWpBBXciEiAYIBlycSAYIBlxcmogFGpBmfOJ1AVqQQl3IhMgEiAZcnEgEiAZcXJqIBZqQZnzidQFakENdyIYIBIgE3JxIBIgE3FyaiAQakGZ84nUBWpBA3ciGSAYIBMgEiAZIBMgGHJxIBMgGHFyaiAIakGZ84nUBWpBBXciEiAYIBlycSAYIBlxcmogCmpBmfOJ1AVqQQl3IhMgEiAZcnEgEiAZcXJqIAxqQZnzidQFakENdyIYIBIgE3JxIBIgE3FyaiAGakGZ84nUBWpBA3ciGSAYIBMgEiAZIBMgGHJxIBMgGHFyaiAJakGZ84nUBWpBBXciEiAYIBlycSAYIBlxcmogC2pBmfOJ1AVqQQl3IhMgEiAZcnEgEiAZcXJqIA1qQZnzidQFakENdyIYIBNzIBJzaiAPakGh1+f2BmpBA3ciDyAYIBMgEiAPIBhzIBNzaiAVakGh1+f2BmpBCXciEiAPcyAYc2ogEWpBodfn9gZqQQt3IhEgEnMgD3NqIBdqQaHX5/YGakEPdyIPIBFzIBJzaiAQakGh1+f2BmpBA3ciECAPIBEgEiAPIBBzIBFzaiAKakGh1+f2BmpBCXciCiAQcyAPc2ogCGpBodfn9gZqQQt3IgggCnMgEHNqIAxqQaHX5/YGakEPdyIMIAhzIApzaiAOakGh1+f2BmpBA3ciDiAMIAggCiAMIA5zIAhzaiAUakGh1+f2BmpBCXciCCAOcyAMc2ogB2pBodfn9gZqQQt3IgcgCHMgDnNqIBZqQaHX5/YGakEPdyIKIAdzIAhzaiAGakGh1+f2BmpBA3ciBiAFaiEFIAIgCiAHIAggBiAKcyAHc2ogC2pBodfn9gZqQQl3IgcgBnMgCnNqIAlqQaHX5/YGakELdyIIIAdzIAZzaiANakGh1+f2BmpBD3dqIQIgAyAIaiEDIAQgB2ohBCABQUBrIQEMAQsLIAUkASACJAIgAyQDIAQkBAsNACAAEAAjACAAaiQACyYAQYHGlLoGJAFBide2/n4kAkH+uevFeSQDQfaoyYEBJARBACQAC/sEAgN/AX4jACAAaq1CA4YhBCAAQcgAakFAcSICQQhrIAAiAUEBaiEAIAFBgAE6AAADQCAAIAJJQQAgAEEHcRsEQCAAQQA6AAAgAEEBaiEADAELCwNAIAAgAkkEQCAAQgA3AwAgAEEIaiEADAELCyAENwMAIAIQAEEAIwGtIgRC//8DgyAEQoCA/P8Pg0IQhoQiBEL/gYCA8B+DIARCgP6DgIDgP4NCCIaEIgRCj4C8gPCBwAeDQgiGIARC8IHAh4CegPgAg0IEiIQiBEKGjJiw4MCBgwZ8QgSIQoGChIiQoMCAAYNCJ34gBEKw4MCBg4aMmDCEfDcDAEEIIwKtIgRC//8DgyAEQoCA/P8Pg0IQhoQiBEL/gYCA8B+DIARCgP6DgIDgP4NCCIaEIgRCj4C8gPCBwAeDQgiGIARC8IHAh4CegPgAg0IEiIQiBEKGjJiw4MCBgwZ8QgSIQoGChIiQoMCAAYNCJ34gBEKw4MCBg4aMmDCEfDcDAEEQIwOtIgRC//8DgyAEQoCA/P8Pg0IQhoQiBEL/gYCA8B+DIARCgP6DgIDgP4NCCIaEIgRCj4C8gPCBwAeDQgiGIARC8IHAh4CegPgAg0IEiIQiBEKGjJiw4MCBgwZ8QgSIQoGChIiQoMCAAYNCJ34gBEKw4MCBg4aMmDCEfDcDAEEYIwStIgRC//8DgyAEQoCA/P8Pg0IQhoQiBEL/gYCA8B+DIARCgP6DgIDgP4NCCIaEIgRCj4C8gPCBwAeDQgiGIARC8IHAh4CegPgAg0IEiIQiBEKGjJiw4MCBgwZ8QgSIQoGChIiQoMCAAYNCJ34gBEKw4MCBg4aMmDCEfDcDAAs=", | ||
| "base64" | ||
@@ -17,0 +17,0 @@ ) |
@@ -14,3 +14,3 @@ /* | ||
| // 1160 bytes | ||
| "AGFzbQEAAAABCAJgAX8AYAAAAwQDAQAABQMBAAEGGgV+AUIAC34BQgALfgFCAAt+AUIAC34BQgALByIEBGluaXQAAAZ1cGRhdGUAAQVmaW5hbAACBm1lbW9yeQIACqgIAzAAQtbrgu7q/Yn14AAkAELP1tO+0ser2UIkAUIAJAJC+erQ0OfJoeThACQDQgAkBAvUAQIBfwR+IABFBEAPCyMEIACtfCQEIwAhAiMBIQMjAiEEIwMhBQNAIAIgASkDAELP1tO+0ser2UJ+fEIfiUKHla+vmLbem55/fiECIAMgASkDCELP1tO+0ser2UJ+fEIfiUKHla+vmLbem55/fiEDIAQgASkDEELP1tO+0ser2UJ+fEIfiUKHla+vmLbem55/fiEEIAUgASkDGELP1tO+0ser2UJ+fEIfiUKHla+vmLbem55/fiEFIAFBIGoiASAASQ0ACyACJAAgAyQBIAQkAiAFJAMLngYCAn8CfiMEQgBSBH4jAEIBiSMBQgeJfCMCQgyJfCMDQhKJfCMAQs/W077Sx6vZQn5CH4lCh5Wvr5i23puef36FQoeVr6+Ytt6bnn9+Qp2jteqDsY2K+gB9IwFCz9bTvtLHq9lCfkIfiUKHla+vmLbem55/foVCh5Wvr5i23puef35CnaO16oOxjYr6AH0jAkLP1tO+0ser2UJ+Qh+JQoeVr6+Ytt6bnn9+hUKHla+vmLbem55/fkKdo7Xqg7GNivoAfSMDQs/W077Sx6vZQn5CH4lCh5Wvr5i23puef36FQoeVr6+Ytt6bnn9+Qp2jteqDsY2K+gB9BULFz9my8eW66icLIwQgAK18fCEDA0AgAUEIaiICIABNBEAgAyABKQMAQs/W077Sx6vZQn5CH4lCh5Wvr5i23puef36FQhuJQoeVr6+Ytt6bnn9+Qp2jteqDsY2K+gB9IQMgAiEBDAELCyABQQRqIgIgAE0EQCADIAE1AgBCh5Wvr5i23puef36FQheJQs/W077Sx6vZQn5C+fPd8Zn2masWfCEDIAIhAQsDQCAAIAFHBEAgAyABMQAAQsXP2bLx5brqJ36FQguJQoeVr6+Ytt6bnn9+IQMgAUEBaiEBDAELC0EAIAMgA0IhiIVCz9bTvtLHq9lCfiIDQh2IIAOFQvnz3fGZ9pmrFn4iA0IgiCADhSIDQiCIIgRC//8Dg0IghiAEQoCA/P8Pg0IQiIQiBEL/gYCA8B+DQhCGIARCgP6DgIDgP4NCCIiEIgRCj4C8gPCBwAeDQgiGIARC8IHAh4CegPgAg0IEiIQiBEKGjJiw4MCBgwZ8QgSIQoGChIiQoMCAAYNCJ34gBEKw4MCBg4aMmDCEfDcDAEEIIANC/////w+DIgNC//8Dg0IghiADQoCA/P8Pg0IQiIQiA0L/gYCA8B+DQhCGIANCgP6DgIDgP4NCCIiEIgNCj4C8gPCBwAeDQgiGIANC8IHAh4CegPgAg0IEiIQiA0KGjJiw4MCBgwZ8QgSIQoGChIiQoMCAAYNCJ34gA0Kw4MCBg4aMmDCEfDcDAAs=", | ||
| "AGFzbQEAAAABCAJgAX8AYAAAAwQDAAEABQMBAAEGGgV+AUIAC34BQgALfgFCAAt+AUIAC34BQgALByIEBGluaXQAAQZ1cGRhdGUAAAVmaW5hbAACBm1lbW9yeQIACqgIA9QBAgF/BH4gAEUEQA8LIwQgAK18JAQjACECIwEhAyMCIQQjAyEFA0AgAiABKQMAQs/W077Sx6vZQn58Qh+JQoeVr6+Ytt6bnn9+IQIgAyABKQMIQs/W077Sx6vZQn58Qh+JQoeVr6+Ytt6bnn9+IQMgBCABKQMQQs/W077Sx6vZQn58Qh+JQoeVr6+Ytt6bnn9+IQQgBSABKQMYQs/W077Sx6vZQn58Qh+JQoeVr6+Ytt6bnn9+IQUgAUEgaiIBIABJDQALIAIkACADJAEgBCQCIAUkAwswAELW64Lu6v2J9eAAJABCz9bTvtLHq9lCJAFCACQCQvnq0NDnyaHk4QAkA0IAJAQLngYCAn8CfiMEQgBSBH4jAEIBiSMBQgeJfCMCQgyJfCMDQhKJfCMAQs/W077Sx6vZQn5CH4lCh5Wvr5i23puef36FQoeVr6+Ytt6bnn9+Qp2jteqDsY2K+gB9IwFCz9bTvtLHq9lCfkIfiUKHla+vmLbem55/foVCh5Wvr5i23puef35CnaO16oOxjYr6AH0jAkLP1tO+0ser2UJ+Qh+JQoeVr6+Ytt6bnn9+hUKHla+vmLbem55/fkKdo7Xqg7GNivoAfSMDQs/W077Sx6vZQn5CH4lCh5Wvr5i23puef36FQoeVr6+Ytt6bnn9+Qp2jteqDsY2K+gB9BULFz9my8eW66icLIwQgAK18fCEDA0AgAUEIaiICIABNBEAgAyABKQMAQs/W077Sx6vZQn5CH4lCh5Wvr5i23puef36FQhuJQoeVr6+Ytt6bnn9+Qp2jteqDsY2K+gB9IQMgAiEBDAELCyABQQRqIgIgAE0EQCADIAE1AgBCh5Wvr5i23puef36FQheJQs/W077Sx6vZQn5C+fPd8Zn2masWfCEDIAIhAQsDQCAAIAFHBEAgAyABMQAAQsXP2bLx5brqJ36FQguJQoeVr6+Ytt6bnn9+IQMgAUEBaiEBDAELC0EAIAMgA0IhiIVCz9bTvtLHq9lCfiIDQh2IIAOFQvnz3fGZ9pmrFn4iA0IgiCADhSIDQiCIIgRC//8Dg0IghiAEQoCA/P8Pg0IQiIQiBEL/gYCA8B+DQhCGIARCgP6DgIDgP4NCCIiEIgRCj4C8gPCBwAeDQgiGIARC8IHAh4CegPgAg0IEiIQiBEKGjJiw4MCBgwZ8QgSIQoGChIiQoMCAAYNCJ34gBEKw4MCBg4aMmDCEfDcDAEEIIANC/////w+DIgNC//8Dg0IghiADQoCA/P8Pg0IQiIQiA0L/gYCA8B+DQhCGIANCgP6DgIDgP4NCCIiEIgNCj4C8gPCBwAeDQgiGIANC8IHAh4CegPgAg0IEiIQiA0KGjJiw4MCBgwZ8QgSIQoGChIiQoMCAAYNCJ34gA0Kw4MCBg4aMmDCEfDcDAAs=", | ||
| "base64" | ||
@@ -17,0 +17,0 @@ ) |
@@ -482,5 +482,53 @@ /* | ||
| const HASH_REGEXP = /(?<!\0)#/g; | ||
| /** | ||
| * Escape `#` characters that appear inside a path request's directory portion | ||
| * with the `\0#` escape recognized by enhanced-resolve, so a project located at | ||
| * a path like `/home/user/proj#1/` (or `./proj#1/`) resolves correctly. Applies | ||
| * to absolute paths (Unix or Windows) and relative paths (starting with `./` or | ||
| * `../`). Only triggers when a query string is present, because that is the case | ||
| * where the resolver's parseIdentifier fails (without a `?`, the resolver | ||
| * handles directory `#` via its own fallback). A `#` after the last path | ||
| * separator is left alone so that explicit fragment requests like | ||
| * `/abs/path/file.js#fragment` still behave the same. Bare module specifiers | ||
| * are not touched. Already-escaped `\0#` sequences are preserved so the | ||
| * explicit opt-out remains stable. | ||
| * @param {string} request request to potentially escape | ||
| * @returns {string} request with directory `#` characters escaped | ||
| */ | ||
| const escapeHashInPathRequest = (request) => { | ||
| if (request.length === 0) return request; | ||
| const queryStart = request.indexOf("?"); | ||
| if (queryStart < 0) return request; | ||
| const hashStart = request.indexOf("#"); | ||
| if (hashStart < 0 || hashStart >= queryStart) return request; | ||
| const c0 = request.charCodeAt(0); | ||
| const isAbsolute = | ||
| c0 === 47 /* "/" */ || WINDOWS_ABS_PATH_REGEXP.test(request); | ||
| let isRelative = false; | ||
| if (!isAbsolute && c0 === 46 /* "." */) { | ||
| const c1 = request.charCodeAt(1); | ||
| if (c1 === 47 || c1 === 92 /* "/" or "\" */) { | ||
| isRelative = true; | ||
| } else if (c1 === 46 /* "." */) { | ||
| const c2 = request.charCodeAt(2); | ||
| if (c2 === 47 || c2 === 92) isRelative = true; | ||
| } | ||
| } | ||
| if (!isAbsolute && !isRelative) return request; | ||
| const lastSep = Math.max( | ||
| request.lastIndexOf("/", queryStart - 1), | ||
| request.lastIndexOf("\\", queryStart - 1) | ||
| ); | ||
| if (hashStart >= lastSep) return request; | ||
| const pathPart = request.slice(0, lastSep); | ||
| return pathPart.replace(HASH_REGEXP, "\0#") + request.slice(lastSep); | ||
| }; | ||
| module.exports.absolutify = absolutify; | ||
| module.exports.contextify = contextify; | ||
| module.exports.escapeHashInPathRequest = escapeHashInPathRequest; | ||
| module.exports.getUndoPath = getUndoPath; | ||
| module.exports.makeCacheable = makeCacheable; | ||
| module.exports.makePathsAbsolute = makeCacheableWithContext(_makePathsAbsolute); | ||
@@ -487,0 +535,0 @@ module.exports.makePathsRelative = makeCacheableWithContext(_makePathsRelative); |
@@ -15,3 +15,2 @@ /* | ||
| AsyncDependenciesBlock: () => require("../AsyncDependenciesBlock"), | ||
| CommentCompilationWarning: () => require("../CommentCompilationWarning"), | ||
| ContextModule: () => require("../ContextModule"), | ||
@@ -113,2 +112,10 @@ "cache/PackFileCacheStrategy": () => | ||
| require("../dependencies/HarmonyEvaluatedImportSpecifierDependency"), | ||
| "dependencies/HtmlInlineScriptDependency": () => | ||
| require("../dependencies/HtmlInlineScriptDependency"), | ||
| "dependencies/HtmlInlineStyleDependency": () => | ||
| require("../dependencies/HtmlInlineStyleDependency"), | ||
| "dependencies/HtmlScriptSrcDependency": () => | ||
| require("../dependencies/HtmlScriptSrcDependency"), | ||
| "dependencies/HtmlSourceDependency": () => | ||
| require("../dependencies/HtmlSourceDependency"), | ||
| "dependencies/ImportContextDependency": () => | ||
@@ -184,19 +191,10 @@ require("../dependencies/ImportContextDependency"), | ||
| require("../optimize/ConcatenatedModule"), | ||
| DelegatedModule: () => require("../DelegatedModule"), | ||
| DependenciesBlock: () => require("../DependenciesBlock"), | ||
| DllModule: () => require("../DllModule"), | ||
| ExternalModule: () => require("../ExternalModule"), | ||
| FileSystemInfo: () => require("../FileSystemInfo"), | ||
| InitFragment: () => require("../InitFragment"), | ||
| InvalidDependenciesModuleWarning: () => | ||
| require("../InvalidDependenciesModuleWarning"), | ||
| Module: () => require("../Module"), | ||
| ModuleBuildError: () => require("../ModuleBuildError"), | ||
| ModuleDependencyWarning: () => require("../ModuleDependencyWarning"), | ||
| ModuleError: () => require("../ModuleError"), | ||
| ModuleGraph: () => require("../ModuleGraph"), | ||
| ModuleParseError: () => require("../ModuleParseError"), | ||
| ModuleWarning: () => require("../ModuleWarning"), | ||
| NormalModule: () => require("../NormalModule"), | ||
| CssModule: () => require("../CssModule"), | ||
| CssModule: () => require("../css/CssModule"), | ||
| RawDataUrlModule: () => require("../asset/RawDataUrlModule"), | ||
@@ -214,10 +212,28 @@ RawModule: () => require("../RawModule"), | ||
| require("../sharing/ProvideForSharedDependency"), | ||
| UnsupportedFeatureWarning: () => require("../UnsupportedFeatureWarning"), | ||
| "errors/WebpackError": () => require("../errors/WebpackError"), | ||
| "errors/InvalidDependenciesModuleWarning": () => | ||
| require("../errors/InvalidDependenciesModuleWarning"), | ||
| "errors/Module": () => require("../Module"), | ||
| "errors/ModuleParseError": () => require("../errors/ModuleParseError"), | ||
| "errors/ModuleWarning": () => require("../errors/ModuleWarning"), | ||
| "errors/ModuleBuildError": () => require("../errors/ModuleBuildError"), | ||
| "errors/ModuleDependencyWarning": () => | ||
| require("../errors/ModuleDependencyWarning"), | ||
| "errors/ModuleError": () => require("../errors/ModuleError"), | ||
| "errors/UnhandledSchemeError": () => | ||
| require("../errors/UnhandledSchemeError"), | ||
| "errors/UnsupportedFeatureWarning": () => | ||
| require("../errors/UnsupportedFeatureWarning"), | ||
| "errors/EnvironmentNotSupportAsyncWarning": () => | ||
| require("../errors/EnvironmentNotSupportAsyncWarning"), | ||
| "errors/CommentCompilationWarning": () => | ||
| require("../errors/CommentCompilationWarning"), | ||
| "errors/NodeStuffInWebError": () => require("../errors/NodeStuffInWebError"), | ||
| "errors/JSONParseError": () => require("../errors/JSONParseError"), | ||
| "dll/DelegatedModule": () => require("../dll/DelegatedModule"), | ||
| "dll/DllModule": () => require("../dll/DllModule"), | ||
| "util/LazySet": () => require("../util/LazySet"), | ||
| UnhandledSchemeError: () => require("../UnhandledSchemeError"), | ||
| NodeStuffInWebError: () => require("../NodeStuffInWebError"), | ||
| EnvironmentNotSupportAsyncWarning: () => | ||
| require("../EnvironmentNotSupportAsyncWarning"), | ||
| WebpackError: () => require("../WebpackError"), | ||
| "util/registerExternalSerializer": () => { | ||
@@ -224,0 +240,0 @@ // already registered |
@@ -12,3 +12,11 @@ /* | ||
| // regexp to match at least one "magic comment" | ||
| module.exports.CompilerHintNotationRegExp = Object.freeze({ | ||
| Pure: /^\s*(?:#|@)__PURE__\s*$/, | ||
| NoSideEffects: /^\s*[#@]__NO_SIDE_EFFECTS__\s*$/ | ||
| }); | ||
| /** | ||
| * regexp to match at least one "magic comment" | ||
| * @returns {import("vm").Context} magic comment context | ||
| */ | ||
| module.exports.createMagicCommentContext = () => | ||
@@ -19,10 +27,5 @@ getVm().createContext(undefined, { | ||
| }); | ||
| module.exports.webpackCommentRegExp = new RegExp( | ||
| /(^|\W)webpack[A-Z][A-Za-z]+:/ | ||
| ); | ||
| // regexp to match at least one "magic comment" | ||
| /** | ||
| * Returns magic comment context. | ||
| * @returns {import("vm").Context} magic comment context | ||
| */ |
@@ -7,2 +7,4 @@ /* | ||
| const JSONParseError = require("../errors/JSONParseError"); | ||
| /** @typedef {import("../util/fs").JsonValue} JsonValue */ | ||
@@ -21,75 +23,2 @@ | ||
| class JSONParseError extends SyntaxError { | ||
| /** | ||
| * @param {Error} err err | ||
| * @param {EXPECTED_ANY} raw raw | ||
| * @param {string} txt text | ||
| * @param {number=} context context | ||
| * @param {EXPECTED_FUNCTION=} caller caller | ||
| */ | ||
| constructor(err, raw, txt, context = 20, caller = parseJson) { | ||
| let originalMessage = err.message; | ||
| /** @type {string} */ | ||
| let message; | ||
| /** @type {number} */ | ||
| let position; | ||
| if (typeof raw !== "string") { | ||
| message = `Cannot parse ${Array.isArray(raw) && raw.length === 0 ? "an empty array" : String(raw)}`; | ||
| position = 0; | ||
| } else if (!txt) { | ||
| message = `${originalMessage} while parsing empty string`; | ||
| position = 0; | ||
| } else { | ||
| // Node 20 puts single quotes around the token and a comma after it | ||
| const UNEXPECTED_TOKEN = /^Unexpected token '?(.)'?(,)? /i; | ||
| const badTokenMatch = originalMessage.match(UNEXPECTED_TOKEN); | ||
| const badIndexMatch = originalMessage.match(/ position\s+(\d+)/i); | ||
| if (badTokenMatch) { | ||
| const h = badTokenMatch[1].charCodeAt(0).toString(16).toUpperCase(); | ||
| const hex = `0x${h.length % 2 ? "0" : ""}${h}`; | ||
| originalMessage = originalMessage.replace( | ||
| UNEXPECTED_TOKEN, | ||
| `Unexpected token ${JSON.stringify(badTokenMatch[1])} (${hex})$2 ` | ||
| ); | ||
| } | ||
| /** @type {number | undefined} */ | ||
| let errIdx; | ||
| if (badIndexMatch) { | ||
| errIdx = Number(badIndexMatch[1]); | ||
| } else if ( | ||
| // doesn't happen in Node 22+ | ||
| /^Unexpected end of JSON.*/i.test(originalMessage) | ||
| ) { | ||
| errIdx = txt.length - 1; | ||
| } | ||
| if (errIdx === undefined) { | ||
| message = `${originalMessage} while parsing '${txt.slice(0, context * 2)}'`; | ||
| position = 0; | ||
| } else { | ||
| const start = errIdx <= context ? 0 : errIdx - context; | ||
| const end = | ||
| errIdx + context >= txt.length ? txt.length : errIdx + context; | ||
| const slice = `${start ? "..." : ""}${txt.slice(start, end)}${end === txt.length ? "" : "..."}`; | ||
| message = `${originalMessage} while parsing ${txt === slice ? "" : "near "}${JSON.stringify(slice)}`; | ||
| position = errIdx; | ||
| } | ||
| } | ||
| super(message); | ||
| this.name = "JSONParseError"; | ||
| this.systemError = err; | ||
| this.position = position; | ||
| Error.captureStackTrace(this, caller || this.constructor); | ||
| } | ||
| } | ||
| /** | ||
@@ -96,0 +25,0 @@ * @template [R=JsonValue] |
@@ -111,3 +111,3 @@ /* | ||
| * Get data from cache | ||
| * @template {EXPECTED_ANY} R | ||
| * @template R | ||
| * @param {(set: SortableSet<T>) => R} fn function to calculate value | ||
@@ -114,0 +114,0 @@ * @returns {R} returns result of fn(this), cached until set changes |
+21
-0
@@ -9,2 +9,3 @@ /* | ||
| /** @typedef {import("webpack-sources").Source} Source */ | ||
| /** @typedef {import("./Hash")} Hash */ | ||
@@ -65,2 +66,22 @@ /** @type {WeakMap<Source, WeakMap<Source, boolean>>} */ | ||
| // TODO remove in webpack 6, this is protection against authors who directly use `webpack-sources` outdated version | ||
| /** | ||
| * Feeds the Source's content into a Hash without forcing a single | ||
| * concatenated Buffer. Uses webpack-sources >= 3.4.0 `buffers()` when | ||
| * available so `ConcatSource` can stream its children directly. | ||
| * @param {Hash} hash hash to update | ||
| * @param {Source} source source whose bytes are appended | ||
| * @returns {void} | ||
| */ | ||
| const updateHashFromSource = (hash, source) => { | ||
| // TODO webpack 6: drop the `buffers` check, require webpack-sources >= 3.4 | ||
| // and call `source.buffers()` unconditionally. | ||
| if (typeof source.buffers === "function") { | ||
| for (const buf of source.buffers()) hash.update(buf); | ||
| } else { | ||
| hash.update(source.buffer()); | ||
| } | ||
| }; | ||
| module.exports.isSourceEqual = isSourceEqual; | ||
| module.exports.updateHashFromSource = updateHashFromSource; |
@@ -8,8 +8,76 @@ /* | ||
| const CaseSensitiveModulesWarning = require("./CaseSensitiveModulesWarning"); | ||
| /** @typedef {import("./Compiler")} Compiler */ | ||
| /** @typedef {import("./Module")} Module */ | ||
| /** @typedef {import("./ModuleGraph")} ModuleGraph */ | ||
| /** @typedef {import("./NormalModule")} NormalModule */ | ||
| const WebpackError = require("./errors/WebpackError"); | ||
| /** | ||
| * Sorts the conflicting modules by identifier to keep warning output stable. | ||
| * @param {Module[]} modules the modules to be sorted | ||
| * @returns {Module[]} sorted version of original modules | ||
| */ | ||
| const sortModules = (modules) => | ||
| modules.sort((a, b) => { | ||
| const aIdent = a.identifier(); | ||
| const bIdent = b.identifier(); | ||
| /* istanbul ignore next */ | ||
| if (aIdent < bIdent) return -1; | ||
| /* istanbul ignore next */ | ||
| if (aIdent > bIdent) return 1; | ||
| /* istanbul ignore next */ | ||
| return 0; | ||
| }); | ||
| /** | ||
| * Formats the conflicting modules and one representative incoming reason for | ||
| * each module into the warning body. | ||
| * @param {Module[]} modules each module from throw | ||
| * @param {ModuleGraph} moduleGraph the module graph | ||
| * @returns {string} each message from provided modules | ||
| */ | ||
| const createModulesListMessage = (modules, moduleGraph) => | ||
| modules | ||
| .map((m) => { | ||
| let message = `* ${m.identifier()}`; | ||
| const validReasons = [ | ||
| ...moduleGraph.getIncomingConnectionsByOriginModule(m).keys() | ||
| ].filter(Boolean); | ||
| if (validReasons.length > 0) { | ||
| message += `\n Used by ${validReasons.length} module(s), i. e.`; | ||
| message += `\n ${ | ||
| /** @type {Module[]} */ (validReasons)[0].identifier() | ||
| }`; | ||
| } | ||
| return message; | ||
| }) | ||
| .join("\n"); | ||
| /** | ||
| * Warning emitted when webpack finds modules whose identifiers differ only by | ||
| * letter casing, which can behave inconsistently across filesystems. | ||
| */ | ||
| class CaseSensitiveModulesWarning extends WebpackError { | ||
| /** | ||
| * Builds a warning message that lists the case-conflicting modules and | ||
| * representative importers that caused them to be included. | ||
| * @param {Iterable<Module>} modules modules that were detected | ||
| * @param {ModuleGraph} moduleGraph the module graph | ||
| */ | ||
| constructor(modules, moduleGraph) { | ||
| const sortedModules = sortModules([...modules]); | ||
| const modulesList = createModulesListMessage(sortedModules, moduleGraph); | ||
| super(`There are multiple modules with names that only differ in casing. | ||
| This can lead to unexpected behavior when compiling on a filesystem with other case-semantic. | ||
| Use equal casing. Compare these module identifiers: | ||
| ${modulesList}`); | ||
| /** @type {string} */ | ||
| this.name = "CaseSensitiveModulesWarning"; | ||
| this.module = sortedModules[0]; | ||
| } | ||
| } | ||
| const PLUGIN_NAME = "WarnCaseSensitiveModulesPlugin"; | ||
@@ -16,0 +84,0 @@ |
@@ -8,3 +8,3 @@ /* | ||
| const WebpackError = require("./WebpackError"); | ||
| const WebpackError = require("./errors/WebpackError"); | ||
@@ -11,0 +11,0 @@ /** @typedef {import("./Compiler")} Compiler */ |
@@ -8,4 +8,19 @@ /* | ||
| const NoModeWarning = require("./NoModeWarning"); | ||
| const WebpackError = require("./errors/WebpackError"); | ||
| class NoModeWarning extends WebpackError { | ||
| constructor() { | ||
| super(); | ||
| /** @type {string} */ | ||
| this.name = "NoModeWarning"; | ||
| this.message = | ||
| "configuration\n" + | ||
| "The 'mode' option has not been set, webpack will fallback to 'production' for this value.\n" + | ||
| "Set 'mode' option to 'development' or 'production' to enable defaults for each environment.\n" + | ||
| "You can also set it to 'none' to disable any default behavior. " + | ||
| "Learn more: https://webpack.js.org/configuration/mode/"; | ||
| } | ||
| } | ||
| /** @typedef {import("./Compiler")} Compiler */ | ||
@@ -12,0 +27,0 @@ |
@@ -11,6 +11,6 @@ /* | ||
| const Generator = require("../Generator"); | ||
| const { tryRunOrWebpackError } = require("../HookWebpackError"); | ||
| const { WEBASSEMBLY_MODULE_TYPE_ASYNC } = require("../ModuleTypeConstants"); | ||
| const NormalModule = require("../NormalModule"); | ||
| const WebAssemblyImportDependency = require("../dependencies/WebAssemblyImportDependency"); | ||
| const { tryRunOrWebpackError } = require("../errors/HookWebpackError"); | ||
| const { compareModulesByFullName } = require("../util/comparators"); | ||
@@ -31,3 +31,3 @@ const makeSerializable = require("../util/makeSerializable"); | ||
| /** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ | ||
| /** @typedef {import("../WebpackError")} WebpackError */ | ||
| /** @typedef {import("../errors/WebpackError")} WebpackError */ | ||
| /** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ | ||
@@ -34,0 +34,0 @@ /** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ |
@@ -10,6 +10,6 @@ /* | ||
| const { decode } = require("@webassemblyjs/wasm-parser"); | ||
| const EnvironmentNotSupportAsyncWarning = require("../EnvironmentNotSupportAsyncWarning"); | ||
| const Parser = require("../Parser"); | ||
| const StaticExportsDependency = require("../dependencies/StaticExportsDependency"); | ||
| const WebAssemblyImportDependency = require("../dependencies/WebAssemblyImportDependency"); | ||
| const EnvironmentNotSupportAsyncWarning = require("../errors/EnvironmentNotSupportAsyncWarning"); | ||
@@ -16,0 +16,0 @@ /** @typedef {import("./AsyncWebAssemblyModulesPlugin").AsyncWasmModuleClass} AsyncWasmModule */ |
@@ -7,5 +7,5 @@ /* | ||
| const WebpackError = require("../WebpackError"); | ||
| const WebpackError = require("../errors/WebpackError"); | ||
| module.exports = class UnsupportedWebAssemblyFeatureError extends WebpackError { | ||
| class UnsupportedWebAssemblyFeatureError extends WebpackError { | ||
| /** | ||
@@ -22,2 +22,4 @@ * Creates an instance of UnsupportedWebAssemblyFeatureError. | ||
| } | ||
| }; | ||
| } | ||
| module.exports = UnsupportedWebAssemblyFeatureError; |
@@ -8,3 +8,3 @@ /* | ||
| const formatLocation = require("../formatLocation"); | ||
| const formatLocation = require("../util/formatLocation"); | ||
| const UnsupportedWebAssemblyFeatureError = require("./UnsupportedWebAssemblyFeatureError"); | ||
@@ -11,0 +11,0 @@ |
@@ -7,3 +7,3 @@ /* | ||
| const WebpackError = require("../WebpackError"); | ||
| const WebpackError = require("../errors/WebpackError"); | ||
@@ -87,3 +87,3 @@ /** @typedef {import("../ChunkGraph")} ChunkGraph */ | ||
| module.exports = class WebAssemblyInInitialChunkError extends WebpackError { | ||
| class WebAssemblyInInitialChunkError extends WebpackError { | ||
| /** | ||
@@ -115,2 +115,4 @@ * Creates an instance of WebAssemblyInInitialChunkError. | ||
| } | ||
| }; | ||
| } | ||
| module.exports = WebAssemblyInInitialChunkError; |
+2
-3
@@ -14,3 +14,2 @@ /* | ||
| /** @typedef {import("./Compiler").ErrorCallback} ErrorCallback */ | ||
| /** @typedef {import("./WebpackError")} WebpackError */ | ||
| /** @typedef {import("./logging/Logger").Logger} Logger */ | ||
@@ -484,3 +483,3 @@ /** @typedef {import("./util/fs").TimeInfoEntries} TimeInfoEntries */ | ||
| * Processes the provided err. | ||
| * @param {WebpackError | null} err error if any | ||
| * @param {Error | null} err error if any | ||
| * @param {Compilation=} compilation compilation if any | ||
@@ -500,3 +499,3 @@ */ | ||
| * Processes the provided err. | ||
| * @param {WebpackError | null} err error if any | ||
| * @param {Error | null} err error if any | ||
| */ | ||
@@ -503,0 +502,0 @@ const shutdown = (err) => { |
+3
-1
@@ -10,3 +10,5 @@ /* | ||
| const webpackOptionsSchemaCheck = require("../schemas/WebpackOptions.check"); | ||
| const webpackOptionsSchema = require("../schemas/WebpackOptions.json"); | ||
| const webpackOptionsSchema = | ||
| /** @type {EXPECTED_ANY} */ | ||
| (require("../schemas/WebpackOptions.json")); | ||
| const Compiler = require("./Compiler"); | ||
@@ -13,0 +15,0 @@ const MultiCompiler = require("./MultiCompiler"); |
+3
-77
@@ -8,78 +8,4 @@ /* | ||
| const inspect = require("util").inspect.custom; | ||
| const makeSerializable = require("./util/makeSerializable"); | ||
| /** @typedef {import("./Chunk")} Chunk */ | ||
| /** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ | ||
| /** @typedef {import("./Module")} Module */ | ||
| /** @typedef {import("./serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ | ||
| /** @typedef {import("./serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ | ||
| class WebpackError extends Error { | ||
| /** | ||
| * Creates an instance of WebpackError. | ||
| * @param {string=} message error message | ||
| * @param {{ cause?: unknown }} options error options | ||
| */ | ||
| constructor(message, options = {}) { | ||
| super(message, options); | ||
| /** @type {string=} */ | ||
| this.details = undefined; | ||
| /** @type {(Module | null)=} */ | ||
| this.module = undefined; | ||
| /** @type {DependencyLocation=} */ | ||
| this.loc = undefined; | ||
| /** @type {boolean=} */ | ||
| this.hideStack = undefined; | ||
| /** @type {Chunk=} */ | ||
| this.chunk = undefined; | ||
| /** @type {string=} */ | ||
| this.file = undefined; | ||
| } | ||
| /** | ||
| * Returns inspect message. | ||
| * @returns {string} inspect message | ||
| */ | ||
| [inspect]() { | ||
| return ( | ||
| this.stack + | ||
| (this.details ? `\n${this.details}` : "") + | ||
| (this.cause ? `\n${this.cause}` : "") | ||
| ); | ||
| } | ||
| /** | ||
| * Serializes this instance into the provided serializer context. | ||
| * @param {ObjectSerializerContext} context context | ||
| */ | ||
| serialize({ write }) { | ||
| write(this.name); | ||
| write(this.message); | ||
| write(this.stack); | ||
| write(this.cause); | ||
| write(this.details); | ||
| write(this.loc); | ||
| write(this.hideStack); | ||
| } | ||
| /** | ||
| * Restores this instance from the provided deserializer context. | ||
| * @param {ObjectDeserializerContext} context context | ||
| */ | ||
| deserialize({ read }) { | ||
| this.name = read(); | ||
| this.message = read(); | ||
| this.stack = read(); | ||
| this.cause = read(); | ||
| this.details = read(); | ||
| this.loc = read(); | ||
| this.hideStack = read(); | ||
| } | ||
| } | ||
| makeSerializable(WebpackError, "webpack/lib/WebpackError"); | ||
| /** @type {typeof WebpackError} */ | ||
| module.exports = WebpackError; | ||
| // TODO remove in webpack 6 | ||
| // Some old plugins use `require("webpack/lib/WebpackError")`, in webpack@6 developer should migrate to `compiler.webpack.WebpackError` | ||
| module.exports = require("./errors/WebpackError"); |
@@ -8,3 +8,2 @@ /* | ||
| const IgnoreErrorModuleFactory = require("./IgnoreErrorModuleFactory"); | ||
| const { | ||
@@ -16,2 +15,3 @@ JAVASCRIPT_MODULE_TYPE_AUTO, | ||
| const WebpackIsIncludedDependency = require("./dependencies/WebpackIsIncludedDependency"); | ||
| const IgnoreErrorModuleFactory = require("./errors/IgnoreErrorModuleFactory"); | ||
| const { | ||
@@ -18,0 +18,0 @@ toConstantDependency |
@@ -428,2 +428,14 @@ /* | ||
| if (options.experiments.html) { | ||
| const HtmlModulesPlugin = require("./html/HtmlModulesPlugin"); | ||
| new HtmlModulesPlugin().apply(compiler); | ||
| } | ||
| if (options.experiments.typescript) { | ||
| const TypeScriptPlugin = require("./typescript/TypeScriptPlugin"); | ||
| new TypeScriptPlugin().apply(compiler); | ||
| } | ||
| if (options.experiments.lazyCompilation) { | ||
@@ -521,3 +533,3 @@ const LazyCompilationPlugin = require("./hmr/LazyCompilationPlugin"); | ||
| const AMDPlugin = require("./dependencies/AMDPlugin"); | ||
| const RequireJsStuffPlugin = require("./RequireJsStuffPlugin"); | ||
| const RequireJsStuffPlugin = require("./dependencies/RequireJsStuffPlugin"); | ||
@@ -524,0 +536,0 @@ new AMDPlugin(options.amd || {}).apply(compiler); |
+22
-20
| { | ||
| "name": "webpack", | ||
| "version": "5.106.2", | ||
| "version": "5.107.0", | ||
| "description": "Packs ECMAScript/CommonJs/AMD modules for the browser. Allows you to split your codebase into multiple bundles, which can be loaded on demand. Supports loaders to preprocess files, i.e. json, jsx, es7, css, less, ... and your custom stuff.", | ||
@@ -61,2 +61,4 @@ "homepage": "https://github.com/webpack/webpack", | ||
| "test:integration": "yarn test:base --testMatch \"<rootDir>/test/*.{basictest,longtest,test}.js\"", | ||
| "test:integration:a": "yarn test:base --testMatch \"<rootDir>/test/*.{basictest,test}.js\"", | ||
| "test:integration:b": "yarn test:base --testMatch \"<rootDir>/test/*.longtest.js\"", | ||
| "test:test262": "yarn test:base --testMatch \"<rootDir>/test/*.spectest.js\"", | ||
@@ -90,3 +92,2 @@ "test:base:deno": "deno --allow-read --allow-env --allow-sys --allow-ffi --allow-write --allow-run --v8-flags='--max-old-space-size=4096' ./node_modules/jest-cli/bin/jest.js --logHeapUsage", | ||
| "dependencies": { | ||
| "@types/eslint-scope": "^3.7.7", | ||
| "@types/estree": "^1.0.8", | ||
@@ -101,4 +102,4 @@ "@types/json-schema": "^7.0.15", | ||
| "chrome-trace-event": "^1.0.2", | ||
| "enhanced-resolve": "^5.20.0", | ||
| "es-module-lexer": "^2.0.0", | ||
| "enhanced-resolve": "^5.21.4", | ||
| "es-module-lexer": "^2.1.0", | ||
| "eslint-scope": "5.1.1", | ||
@@ -108,3 +109,3 @@ "events": "^3.2.0", | ||
| "graceful-fs": "^4.2.11", | ||
| "loader-runner": "^4.3.1", | ||
| "loader-runner": "^4.3.2", | ||
| "mime-db": "^1.54.0", | ||
@@ -114,5 +115,5 @@ "neo-async": "^2.6.2", | ||
| "tapable": "^2.3.0", | ||
| "terser-webpack-plugin": "^5.3.17", | ||
| "terser-webpack-plugin": "^5.5.0", | ||
| "watchpack": "^2.5.1", | ||
| "webpack-sources": "^3.3.4" | ||
| "webpack-sources": "^3.4.1" | ||
| }, | ||
@@ -124,3 +125,4 @@ "devDependencies": { | ||
| "@changesets/get-github-info": "^0.8.0", | ||
| "@codspeed/core": "^5.2.0", | ||
| "@codspeed/core": "^5.4.0", | ||
| "@types/eslint-scope": "^3.7.7", | ||
| "@types/glob-to-regexp": "^0.4.4", | ||
@@ -134,3 +136,3 @@ "@types/graceful-fs": "^4.1.9", | ||
| "@webdiscus/pug-loader": "^2.11.1", | ||
| "assemblyscript": "^0.28.9", | ||
| "assemblyscript": "^0.28.17", | ||
| "babel-loader": "^10.0.0", | ||
@@ -143,3 +145,3 @@ "bundle-loader": "^0.5.6", | ||
| "css-loader": "^7.1.2", | ||
| "date-fns": "^4.0.0", | ||
| "date-fns": "^4.2.1", | ||
| "es5-ext": "^0.10.53", | ||
@@ -151,3 +153,3 @@ "es6-promise-polyfill": "^1.2.0", | ||
| "fork-ts-checker-webpack-plugin": "^9.0.2", | ||
| "globals": "^17.0.0", | ||
| "globals": "^17.6.0", | ||
| "hash-wasm": "^4.9.0", | ||
@@ -163,3 +165,3 @@ "html-loader": "^5.1.0", | ||
| "jest-snapshot": "^30.3.0", | ||
| "jest-junit": "^16.0.0", | ||
| "jest-junit": "^17.0.0", | ||
| "json-loader": "^0.5.7", | ||
@@ -169,3 +171,3 @@ "json5": "^2.1.3", | ||
| "less-loader": "^12.3.2", | ||
| "lint-staged": "^16.2.3", | ||
| "lint-staged": "^17.0.5", | ||
| "lodash": "^4.17.19", | ||
@@ -180,4 +182,4 @@ "lodash-es": "^4.17.15", | ||
| "open-cli": "^9.0.0", | ||
| "oxc-parser": "^0.125.0", | ||
| "pkg-pr-new": "^0.0.66", | ||
| "oxc-parser": "^0.132.0", | ||
| "pkg-pr-new": "^0.0.75", | ||
| "prettier": "^3.8.2", | ||
@@ -200,9 +202,9 @@ "prettier-2": "npm:prettier@^2", | ||
| "style-loader": "^4.0.0", | ||
| "terser": "^5.43.1", | ||
| "three": "^0.183.1", | ||
| "tinybench": "^6.0.0", | ||
| "terser": "^5.46.2", | ||
| "three": "^0.184.0", | ||
| "tinybench": "^6.0.1", | ||
| "toml": "^4.1.1", | ||
| "tooling": "webpack/tooling#v1.26.1", | ||
| "tooling": "webpack/tooling#v1.26.2", | ||
| "ts-loader": "^9.5.7", | ||
| "typescript": "^5.9.3", | ||
| "typescript": "^6.0.3", | ||
| "unified": "^11.0.5", | ||
@@ -209,0 +211,0 @@ "url-loader": "^4.1.0", |
@@ -6,2 +6,2 @@ /* | ||
| */ | ||
| "use strict";module.exports=t,module.exports.default=t;const e={type:"object",additionalProperties:!1,properties:{activeModules:{type:"boolean"},dependencies:{type:"boolean"},dependenciesCount:{type:"number"},entries:{type:"boolean"},handler:{oneOf:[{$ref:"#/definitions/HandlerFunction"}]},modules:{type:"boolean"},modulesCount:{type:"number"},percentBy:{enum:["entries","modules","dependencies",null]},profile:{enum:[!0,!1,null]}}},r=Object.prototype.hasOwnProperty;function n(t,{instancePath:o="",parentData:s,parentDataProperty:a,rootData:l=t}={}){let i=null,p=0;if(0===p){if(!t||"object"!=typeof t||Array.isArray(t))return n.errors=[{params:{type:"object"}}],!1;{const o=p;for(const o in t)if(!r.call(e.properties,o))return n.errors=[{params:{additionalProperty:o}}],!1;if(o===p){if(void 0!==t.activeModules){const e=p;if("boolean"!=typeof t.activeModules)return n.errors=[{params:{type:"boolean"}}],!1;var u=e===p}else u=!0;if(u){if(void 0!==t.dependencies){const e=p;if("boolean"!=typeof t.dependencies)return n.errors=[{params:{type:"boolean"}}],!1;u=e===p}else u=!0;if(u){if(void 0!==t.dependenciesCount){const e=p;if("number"!=typeof t.dependenciesCount)return n.errors=[{params:{type:"number"}}],!1;u=e===p}else u=!0;if(u){if(void 0!==t.entries){const e=p;if("boolean"!=typeof t.entries)return n.errors=[{params:{type:"boolean"}}],!1;u=e===p}else u=!0;if(u){if(void 0!==t.handler){const e=p,r=p;let o=!1,s=null;const a=p;if(!(t.handler instanceof Function)){const e={params:{}};null===i?i=[e]:i.push(e),p++}if(a===p&&(o=!0,s=0),!o){const e={params:{passingSchemas:s}};return null===i?i=[e]:i.push(e),p++,n.errors=i,!1}p=r,null!==i&&(r?i.length=r:i=null),u=e===p}else u=!0;if(u){if(void 0!==t.modules){const e=p;if("boolean"!=typeof t.modules)return n.errors=[{params:{type:"boolean"}}],!1;u=e===p}else u=!0;if(u){if(void 0!==t.modulesCount){const e=p;if("number"!=typeof t.modulesCount)return n.errors=[{params:{type:"number"}}],!1;u=e===p}else u=!0;if(u){if(void 0!==t.percentBy){let e=t.percentBy;const r=p;if("entries"!==e&&"modules"!==e&&"dependencies"!==e&&null!==e)return n.errors=[{params:{}}],!1;u=r===p}else u=!0;if(u)if(void 0!==t.profile){let e=t.profile;const r=p;if(!0!==e&&!1!==e&&null!==e)return n.errors=[{params:{}}],!1;u=r===p}else u=!0}}}}}}}}}}return n.errors=i,0===p}function t(e,{instancePath:r="",parentData:o,parentDataProperty:s,rootData:a=e}={}){let l=null,i=0;const p=i;let u=!1;const c=i;n(e,{instancePath:r,parentData:o,parentDataProperty:s,rootData:a})||(l=null===l?n.errors:l.concat(n.errors),i=l.length);var f=c===i;if(u=u||f,!u){const r=i;if(!(e instanceof Function)){const e={params:{}};null===l?l=[e]:l.push(e),i++}f=r===i,u=u||f}if(!u){const e={params:{}};return null===l?l=[e]:l.push(e),i++,t.errors=l,!1}return i=p,null!==l&&(p?l.length=p:l=null),t.errors=l,0===i} | ||
| "use strict";module.exports=o,module.exports.default=o;const e={type:"object",additionalProperties:!1,properties:{activeModules:{type:"boolean"},dependencies:{type:"boolean"},dependenciesCount:{type:"number"},entries:{type:"boolean"},handler:{oneOf:[{$ref:"#/definitions/HandlerFunction"}]},modules:{type:"boolean"},modulesCount:{type:"number"},percentBy:{enum:["entries","modules","dependencies",null]},profile:{enum:[!0,!1,null]},progressBar:{anyOf:[{type:"boolean"},{type:"object",additionalProperties:!1,properties:{color:{type:"string"},name:{type:"string"}}}]}}},r=Object.prototype.hasOwnProperty;function n(o,{instancePath:t="",parentData:s,parentDataProperty:a,rootData:l=o}={}){let i=null,p=0;if(0===p){if(!o||"object"!=typeof o||Array.isArray(o))return n.errors=[{params:{type:"object"}}],!1;{const t=p;for(const t in o)if(!r.call(e.properties,t))return n.errors=[{params:{additionalProperty:t}}],!1;if(t===p){if(void 0!==o.activeModules){const e=p;if("boolean"!=typeof o.activeModules)return n.errors=[{params:{type:"boolean"}}],!1;var u=e===p}else u=!0;if(u){if(void 0!==o.dependencies){const e=p;if("boolean"!=typeof o.dependencies)return n.errors=[{params:{type:"boolean"}}],!1;u=e===p}else u=!0;if(u){if(void 0!==o.dependenciesCount){const e=p;if("number"!=typeof o.dependenciesCount)return n.errors=[{params:{type:"number"}}],!1;u=e===p}else u=!0;if(u){if(void 0!==o.entries){const e=p;if("boolean"!=typeof o.entries)return n.errors=[{params:{type:"boolean"}}],!1;u=e===p}else u=!0;if(u){if(void 0!==o.handler){const e=p,r=p;let t=!1,s=null;const a=p;if(!(o.handler instanceof Function)){const e={params:{}};null===i?i=[e]:i.push(e),p++}if(a===p&&(t=!0,s=0),!t){const e={params:{passingSchemas:s}};return null===i?i=[e]:i.push(e),p++,n.errors=i,!1}p=r,null!==i&&(r?i.length=r:i=null),u=e===p}else u=!0;if(u){if(void 0!==o.modules){const e=p;if("boolean"!=typeof o.modules)return n.errors=[{params:{type:"boolean"}}],!1;u=e===p}else u=!0;if(u){if(void 0!==o.modulesCount){const e=p;if("number"!=typeof o.modulesCount)return n.errors=[{params:{type:"number"}}],!1;u=e===p}else u=!0;if(u){if(void 0!==o.percentBy){let e=o.percentBy;const r=p;if("entries"!==e&&"modules"!==e&&"dependencies"!==e&&null!==e)return n.errors=[{params:{}}],!1;u=r===p}else u=!0;if(u){if(void 0!==o.profile){let e=o.profile;const r=p;if(!0!==e&&!1!==e&&null!==e)return n.errors=[{params:{}}],!1;u=r===p}else u=!0;if(u)if(void 0!==o.progressBar){let e=o.progressBar;const r=p,t=p;let s=!1;const a=p;if("boolean"!=typeof e){const e={params:{type:"boolean"}};null===i?i=[e]:i.push(e),p++}var c=a===p;if(s=s||c,!s){const r=p;if(p===r)if(e&&"object"==typeof e&&!Array.isArray(e)){const r=p;for(const r in e)if("color"!==r&&"name"!==r){const e={params:{additionalProperty:r}};null===i?i=[e]:i.push(e),p++;break}if(r===p){if(void 0!==e.color){const r=p;if("string"!=typeof e.color){const e={params:{type:"string"}};null===i?i=[e]:i.push(e),p++}var f=r===p}else f=!0;if(f)if(void 0!==e.name){const r=p;if("string"!=typeof e.name){const e={params:{type:"string"}};null===i?i=[e]:i.push(e),p++}f=r===p}else f=!0}}else{const e={params:{type:"object"}};null===i?i=[e]:i.push(e),p++}c=r===p,s=s||c}if(!s){const e={params:{}};return null===i?i=[e]:i.push(e),p++,n.errors=i,!1}p=t,null!==i&&(t?i.length=t:i=null),u=r===p}else u=!0}}}}}}}}}}}return n.errors=i,0===p}function o(e,{instancePath:r="",parentData:t,parentDataProperty:s,rootData:a=e}={}){let l=null,i=0;const p=i;let u=!1;const c=i;n(e,{instancePath:r,parentData:t,parentDataProperty:s,rootData:a})||(l=null===l?n.errors:l.concat(n.errors),i=l.length);var f=c===i;if(u=u||f,!u){const r=i;if(!(e instanceof Function)){const e={params:{}};null===l?l=[e]:l.push(e),i++}f=r===i,u=u||f}if(!u){const e={params:{}};return null===l?l=[e]:l.push(e),i++,o.errors=l,!1}return i=p,null!==l&&(p?l.length=p:l=null),o.errors=l,0===i} |
@@ -52,2 +52,24 @@ { | ||
| "enum": [true, false, null] | ||
| }, | ||
| "progressBar": { | ||
| "description": "Generate progress bar. Default: false.", | ||
| "anyOf": [ | ||
| { | ||
| "type": "boolean" | ||
| }, | ||
| { | ||
| "type": "object", | ||
| "additionalProperties": false, | ||
| "properties": { | ||
| "color": { | ||
| "description": "Color used for the filled portion of the bar.", | ||
| "type": "string" | ||
| }, | ||
| "name": { | ||
| "description": "Name shown before the progress bar.", | ||
| "type": "string" | ||
| } | ||
| } | ||
| } | ||
| ] | ||
| } | ||
@@ -54,0 +76,0 @@ } |
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| Author Ivan Kopeykin @vankop | ||
| */ | ||
| "use strict"; | ||
| const WebpackError = require("./WebpackError"); | ||
| const CURRENT_METHOD_REGEXP = /at ([a-zA-Z0-9_.]*)/; | ||
| /** | ||
| * Creates the error message shown when an abstract API is called without | ||
| * being implemented by a subclass. | ||
| * @param {string=} method method name | ||
| * @returns {string} message | ||
| */ | ||
| function createMessage(method) { | ||
| return `Abstract method${method ? ` ${method}` : ""}. Must be overridden.`; | ||
| } | ||
| /** | ||
| * Captures a stack trace so the calling method name can be folded into the | ||
| * final abstract-method error message. | ||
| * @constructor | ||
| */ | ||
| function Message() { | ||
| /** @type {string | undefined} */ | ||
| this.stack = undefined; | ||
| Error.captureStackTrace(this); | ||
| /** @type {RegExpMatchArray | null} */ | ||
| const match = | ||
| /** @type {string} */ | ||
| (/** @type {unknown} */ (this.stack)) | ||
| .split("\n")[3] | ||
| .match(CURRENT_METHOD_REGEXP); | ||
| this.message = match && match[1] ? createMessage(match[1]) : createMessage(); | ||
| } | ||
| /** | ||
| * Error thrown when code reaches a method that is intended to be overridden by | ||
| * a subclass. | ||
| * @example | ||
| * ```js | ||
| * class FooClass { | ||
| * abstractMethod() { | ||
| * throw new AbstractMethodError(); // error message: Abstract method FooClass.abstractMethod. Must be overridden. | ||
| * } | ||
| * } | ||
| * ``` | ||
| */ | ||
| class AbstractMethodError extends WebpackError { | ||
| /** | ||
| * Creates an error whose message points at the abstract method that was | ||
| * invoked. | ||
| */ | ||
| constructor() { | ||
| super(new Message().message); | ||
| /** @type {string} */ | ||
| this.name = "AbstractMethodError"; | ||
| } | ||
| } | ||
| module.exports = AbstractMethodError; |
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| Author Sean Larkin @thelarkinn | ||
| */ | ||
| "use strict"; | ||
| const WebpackError = require("./WebpackError"); | ||
| /** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ | ||
| /** @typedef {import("./Module")} Module */ | ||
| /** | ||
| * Error raised when webpack detects an attempt to lazy-load a chunk name that | ||
| * is already claimed by an entrypoint's initial chunk. | ||
| */ | ||
| class AsyncDependencyToInitialChunkError extends WebpackError { | ||
| /** | ||
| * Captures the chunk name, originating module, and source location for an | ||
| * invalid async dependency targeting an initial chunk. | ||
| * @param {string} chunkName Name of Chunk | ||
| * @param {Module} module module tied to dependency | ||
| * @param {DependencyLocation} loc location of dependency | ||
| */ | ||
| constructor(chunkName, module, loc) { | ||
| super( | ||
| `It's not allowed to load an initial chunk on demand. The chunk name "${chunkName}" is already used by an entrypoint.` | ||
| ); | ||
| /** @type {string} */ | ||
| this.name = "AsyncDependencyToInitialChunkError"; | ||
| /** @type {Module} */ | ||
| this.module = module; | ||
| /** @type {DependencyLocation} */ | ||
| this.loc = loc; | ||
| } | ||
| } | ||
| module.exports = AsyncDependencyToInitialChunkError; |
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| Author Tobias Koppers @sokra | ||
| */ | ||
| "use strict"; | ||
| const WebpackError = require("./WebpackError"); | ||
| /** @typedef {import("./Module")} Module */ | ||
| /** @typedef {import("./ModuleGraph")} ModuleGraph */ | ||
| /** | ||
| * Sorts the conflicting modules by identifier to keep warning output stable. | ||
| * @param {Module[]} modules the modules to be sorted | ||
| * @returns {Module[]} sorted version of original modules | ||
| */ | ||
| const sortModules = (modules) => | ||
| modules.sort((a, b) => { | ||
| const aIdent = a.identifier(); | ||
| const bIdent = b.identifier(); | ||
| /* istanbul ignore next */ | ||
| if (aIdent < bIdent) return -1; | ||
| /* istanbul ignore next */ | ||
| if (aIdent > bIdent) return 1; | ||
| /* istanbul ignore next */ | ||
| return 0; | ||
| }); | ||
| /** | ||
| * Formats the conflicting modules and one representative incoming reason for | ||
| * each module into the warning body. | ||
| * @param {Module[]} modules each module from throw | ||
| * @param {ModuleGraph} moduleGraph the module graph | ||
| * @returns {string} each message from provided modules | ||
| */ | ||
| const createModulesListMessage = (modules, moduleGraph) => | ||
| modules | ||
| .map((m) => { | ||
| let message = `* ${m.identifier()}`; | ||
| const validReasons = [ | ||
| ...moduleGraph.getIncomingConnectionsByOriginModule(m).keys() | ||
| ].filter(Boolean); | ||
| if (validReasons.length > 0) { | ||
| message += `\n Used by ${validReasons.length} module(s), i. e.`; | ||
| message += `\n ${ | ||
| /** @type {Module[]} */ (validReasons)[0].identifier() | ||
| }`; | ||
| } | ||
| return message; | ||
| }) | ||
| .join("\n"); | ||
| /** | ||
| * Warning emitted when webpack finds modules whose identifiers differ only by | ||
| * letter casing, which can behave inconsistently across filesystems. | ||
| */ | ||
| class CaseSensitiveModulesWarning extends WebpackError { | ||
| /** | ||
| * Builds a warning message that lists the case-conflicting modules and | ||
| * representative importers that caused them to be included. | ||
| * @param {Iterable<Module>} modules modules that were detected | ||
| * @param {ModuleGraph} moduleGraph the module graph | ||
| */ | ||
| constructor(modules, moduleGraph) { | ||
| const sortedModules = sortModules([...modules]); | ||
| const modulesList = createModulesListMessage(sortedModules, moduleGraph); | ||
| super(`There are multiple modules with names that only differ in casing. | ||
| This can lead to unexpected behavior when compiling on a filesystem with other case-semantic. | ||
| Use equal casing. Compare these module identifiers: | ||
| ${modulesList}`); | ||
| /** @type {string} */ | ||
| this.name = "CaseSensitiveModulesWarning"; | ||
| this.module = sortedModules[0]; | ||
| } | ||
| } | ||
| module.exports = CaseSensitiveModulesWarning; |
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| Author Tobias Koppers @sokra | ||
| */ | ||
| "use strict"; | ||
| const WebpackError = require("./WebpackError"); | ||
| /** @typedef {import("./Chunk")} Chunk */ | ||
| class ChunkRenderError extends WebpackError { | ||
| /** | ||
| * Create a new ChunkRenderError | ||
| * @param {Chunk} chunk A chunk | ||
| * @param {string} file Related file | ||
| * @param {Error} error Original error | ||
| */ | ||
| constructor(chunk, file, error) { | ||
| super(); | ||
| /** @type {string} */ | ||
| this.name = "ChunkRenderError"; | ||
| /** @type {Chunk} */ | ||
| this.chunk = chunk; | ||
| /** @type {string} */ | ||
| this.file = file; | ||
| /** @type {Error} */ | ||
| this.error = error; | ||
| /** @type {string} */ | ||
| this.message = error.message; | ||
| /** @type {string} */ | ||
| this.details = error.stack; | ||
| } | ||
| } | ||
| /** @type {typeof ChunkRenderError} */ | ||
| module.exports = ChunkRenderError; |
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| Author Tobias Koppers @sokra | ||
| */ | ||
| "use strict"; | ||
| const WebpackError = require("./WebpackError"); | ||
| /** @typedef {import("./Module")} Module */ | ||
| class CodeGenerationError extends WebpackError { | ||
| /** | ||
| * Create a new CodeGenerationError | ||
| * @param {Module} module related module | ||
| * @param {Error} error Original error | ||
| */ | ||
| constructor(module, error) { | ||
| super(); | ||
| /** @type {string} */ | ||
| this.name = "CodeGenerationError"; | ||
| /** @type {Module} */ | ||
| this.module = module; | ||
| /** @type {Error} */ | ||
| this.error = error; | ||
| /** @type {string} */ | ||
| this.message = error.message; | ||
| /** @type {string} */ | ||
| this.details = error.stack; | ||
| } | ||
| } | ||
| /** @type {typeof CodeGenerationError} */ | ||
| module.exports = CodeGenerationError; |
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| Author Tobias Koppers @sokra | ||
| */ | ||
| "use strict"; | ||
| const WebpackError = require("./WebpackError"); | ||
| const makeSerializable = require("./util/makeSerializable"); | ||
| /** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ | ||
| /** | ||
| * Warning used for comment-related compilation issues, such as malformed magic | ||
| * comments that webpack can parse but wants to report. | ||
| */ | ||
| class CommentCompilationWarning extends WebpackError { | ||
| /** | ||
| * Captures a warning message together with the dependency location that | ||
| * triggered it. | ||
| * @param {string} message warning message | ||
| * @param {DependencyLocation} loc affected lines of code | ||
| */ | ||
| constructor(message, loc) { | ||
| super(message); | ||
| /** @type {string} */ | ||
| this.name = "CommentCompilationWarning"; | ||
| /** @type {DependencyLocation} */ | ||
| this.loc = loc; | ||
| } | ||
| } | ||
| makeSerializable( | ||
| CommentCompilationWarning, | ||
| "webpack/lib/CommentCompilationWarning" | ||
| ); | ||
| module.exports = CommentCompilationWarning; |
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| Author Maksim Nazarjev @acupofspirt | ||
| */ | ||
| "use strict"; | ||
| const WebpackError = require("./WebpackError"); | ||
| module.exports = class ConcurrentCompilationError extends WebpackError { | ||
| constructor() { | ||
| super( | ||
| "You ran Webpack twice. Each instance only supports a single concurrent compilation at a time." | ||
| ); | ||
| this.name = "ConcurrentCompilationError"; | ||
| } | ||
| }; |
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| Author Natsu @xiaoxiaojx | ||
| */ | ||
| "use strict"; | ||
| const RuntimeGlobals = require("../RuntimeGlobals"); | ||
| const RuntimeModule = require("../RuntimeModule"); | ||
| const Template = require("../Template"); | ||
| /** @typedef {import("../Chunk")} Chunk */ | ||
| class CssMergeStyleSheetsRuntimeModule extends RuntimeModule { | ||
| constructor() { | ||
| super("css merge stylesheets"); | ||
| } | ||
| /** | ||
| * Generates runtime code for this runtime module. | ||
| * @returns {string | null} runtime code | ||
| */ | ||
| generate() { | ||
| const { runtimeTemplate } = /** @type {import("../Compilation")} */ ( | ||
| this.compilation | ||
| ); | ||
| return Template.asString([ | ||
| `${RuntimeGlobals.cssMergeStyleSheets} = ${runtimeTemplate.basicFunction( | ||
| "sheets", | ||
| [ | ||
| "var sheetsArray = Array.isArray(sheets) ? sheets : [sheets];", | ||
| "var cssTexts = [];", | ||
| "for (var i = 0; i < sheetsArray.length; i++) {", | ||
| Template.indent([ | ||
| "var s = sheetsArray[i];", | ||
| "if (!s) continue;", | ||
| "if (typeof s === 'string') {", | ||
| Template.indent("cssTexts.push(s);"), | ||
| "} else if (s.cssRules) {", | ||
| Template.indent([ | ||
| "var rules = s.cssRules;", | ||
| "for (var j = 0; j < rules.length; j++) {", | ||
| Template.indent("cssTexts.push(rules[j].cssText);"), | ||
| "}" | ||
| ]), | ||
| "}" | ||
| ]), | ||
| "}", | ||
| "return cssTexts.join('');" | ||
| ] | ||
| )};` | ||
| ]); | ||
| } | ||
| } | ||
| module.exports = CssMergeStyleSheetsRuntimeModule; |
-200
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| Author Alexander Akait @alexander-akait | ||
| */ | ||
| "use strict"; | ||
| const NormalModule = require("./NormalModule"); | ||
| const makeSerializable = require("./util/makeSerializable"); | ||
| /** @typedef {import("./Module")} Module */ | ||
| /** @typedef {import("./NormalModule").NormalModuleCreateData} NormalModuleCreateData */ | ||
| /** @typedef {import("./RequestShortener")} RequestShortener */ | ||
| /** @typedef {import("./serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ | ||
| /** @typedef {import("./serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ | ||
| /** @typedef {import("../declarations/WebpackOptions").CssParserExportType} CssParserExportType */ | ||
| /** @typedef {string | undefined} CssLayer */ | ||
| /** @typedef {string | undefined} Supports */ | ||
| /** @typedef {string | undefined} Media */ | ||
| /** @typedef {[CssLayer, Supports, Media]} InheritanceItem */ | ||
| /** @typedef {InheritanceItem[]} Inheritance */ | ||
| /** @typedef {NormalModuleCreateData & { cssLayer: CssLayer, supports: Supports, media: Media, inheritance?: Inheritance, exportType?: CssParserExportType }} CSSModuleCreateData */ | ||
| class CssModule extends NormalModule { | ||
| /** | ||
| * Creates an instance of CssModule. | ||
| * @param {CSSModuleCreateData} options options object | ||
| */ | ||
| constructor(options) { | ||
| super(options); | ||
| // Avoid override `layer` for `Module` class, because it is a feature to run module in specific layer | ||
| /** @type {CSSModuleCreateData['cssLayer']} */ | ||
| this.cssLayer = options.cssLayer; | ||
| /** @type {CSSModuleCreateData['supports']} */ | ||
| this.supports = options.supports; | ||
| /** @type {CSSModuleCreateData['media']} */ | ||
| this.media = options.media; | ||
| /** @type {CSSModuleCreateData['inheritance']} */ | ||
| this.inheritance = options.inheritance; | ||
| /** @type {CSSModuleCreateData['exportType']} */ | ||
| this.exportType = options.exportType; | ||
| } | ||
| /** | ||
| * Returns the unique identifier used to reference this module. | ||
| * @returns {string} a unique identifier of the module | ||
| */ | ||
| identifier() { | ||
| let identifier = super.identifier(); | ||
| if (this.cssLayer) { | ||
| identifier += `|${this.cssLayer}`; | ||
| } | ||
| if (this.supports) { | ||
| identifier += `|${this.supports}`; | ||
| } | ||
| if (this.media) { | ||
| identifier += `|${this.media}`; | ||
| } | ||
| if (this.inheritance) { | ||
| const inheritance = this.inheritance.map( | ||
| (item, index) => | ||
| `inheritance_${index}|${item[0] || ""}|${item[1] || ""}|${ | ||
| item[2] || "" | ||
| }` | ||
| ); | ||
| identifier += `|${inheritance.join("|")}`; | ||
| } | ||
| if (this.exportType) { | ||
| identifier += `|${this.exportType}`; | ||
| } | ||
| // We generate extra code for HMR, so we need to invalidate the module | ||
| if (this.hot) { | ||
| identifier += `|${this.hot}`; | ||
| } | ||
| return identifier; | ||
| } | ||
| /** | ||
| * Returns a human-readable identifier for this module. | ||
| * @param {RequestShortener} requestShortener the request shortener | ||
| * @returns {string} a user readable identifier of the module | ||
| */ | ||
| readableIdentifier(requestShortener) { | ||
| const readableIdentifier = super.readableIdentifier(requestShortener); | ||
| let identifier = `css ${readableIdentifier}`; | ||
| if (this.cssLayer) { | ||
| identifier += ` (layer: ${this.cssLayer})`; | ||
| } | ||
| if (this.supports) { | ||
| identifier += ` (supports: ${this.supports})`; | ||
| } | ||
| if (this.media) { | ||
| identifier += ` (media: ${this.media})`; | ||
| } | ||
| if (this.exportType) { | ||
| identifier += ` (exportType: ${this.exportType})`; | ||
| } | ||
| return identifier; | ||
| } | ||
| /** | ||
| * Assuming this module is in the cache. Update the (cached) module with | ||
| * the fresh module from the factory. Usually updates internal references | ||
| * and properties. | ||
| * @param {Module} module fresh module | ||
| * @returns {void} | ||
| */ | ||
| updateCacheModule(module) { | ||
| super.updateCacheModule(module); | ||
| const m = /** @type {CssModule} */ (module); | ||
| this.cssLayer = m.cssLayer; | ||
| this.supports = m.supports; | ||
| this.media = m.media; | ||
| this.inheritance = m.inheritance; | ||
| this.exportType = m.exportType; | ||
| } | ||
| /** | ||
| * Serializes this instance into the provided serializer context. | ||
| * @param {ObjectSerializerContext} context context | ||
| */ | ||
| serialize(context) { | ||
| const { write } = context; | ||
| write(this.cssLayer); | ||
| write(this.supports); | ||
| write(this.media); | ||
| write(this.inheritance); | ||
| write(this.exportType); | ||
| super.serialize(context); | ||
| } | ||
| /** | ||
| * Restores this instance from the provided deserializer context. | ||
| * @param {ObjectDeserializerContext} context context | ||
| * @returns {CssModule} the deserialized object | ||
| */ | ||
| static deserialize(context) { | ||
| const obj = new CssModule({ | ||
| // will be deserialized by Module | ||
| layer: /** @type {EXPECTED_ANY} */ (null), | ||
| type: "", | ||
| // will be filled by updateCacheModule | ||
| resource: "", | ||
| context: "", | ||
| request: /** @type {EXPECTED_ANY} */ (null), | ||
| userRequest: /** @type {EXPECTED_ANY} */ (null), | ||
| rawRequest: /** @type {EXPECTED_ANY} */ (null), | ||
| loaders: /** @type {EXPECTED_ANY} */ (null), | ||
| matchResource: /** @type {EXPECTED_ANY} */ (null), | ||
| parser: /** @type {EXPECTED_ANY} */ (null), | ||
| parserOptions: /** @type {EXPECTED_ANY} */ (null), | ||
| generator: /** @type {EXPECTED_ANY} */ (null), | ||
| generatorOptions: /** @type {EXPECTED_ANY} */ (null), | ||
| resolveOptions: /** @type {EXPECTED_ANY} */ (null), | ||
| cssLayer: /** @type {EXPECTED_ANY} */ (null), | ||
| supports: /** @type {EXPECTED_ANY} */ (null), | ||
| media: /** @type {EXPECTED_ANY} */ (null), | ||
| inheritance: /** @type {EXPECTED_ANY} */ (null), | ||
| extractSourceMap: /** @type {EXPECTED_ANY} */ (null), | ||
| exportType: /** @type {EXPECTED_ANY} */ (null) | ||
| }); | ||
| obj.deserialize(context); | ||
| return obj; | ||
| } | ||
| /** | ||
| * Restores this instance from the provided deserializer context. | ||
| * @param {ObjectDeserializerContext} context context | ||
| */ | ||
| deserialize(context) { | ||
| const { read } = context; | ||
| this.cssLayer = read(); | ||
| this.supports = read(); | ||
| this.media = read(); | ||
| this.inheritance = read(); | ||
| this.exportType = read(); | ||
| super.deserialize(context); | ||
| } | ||
| } | ||
| makeSerializable(CssModule, "webpack/lib/CssModule"); | ||
| module.exports = CssModule; |
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| Author Tobias Koppers @sokra | ||
| */ | ||
| "use strict"; | ||
| const { OriginalSource, RawSource } = require("webpack-sources"); | ||
| const Module = require("./Module"); | ||
| const { | ||
| JAVASCRIPT_TYPE, | ||
| JAVASCRIPT_TYPES | ||
| } = require("./ModuleSourceTypeConstants"); | ||
| const { JAVASCRIPT_MODULE_TYPE_DYNAMIC } = require("./ModuleTypeConstants"); | ||
| const RuntimeGlobals = require("./RuntimeGlobals"); | ||
| const DelegatedSourceDependency = require("./dependencies/DelegatedSourceDependency"); | ||
| const StaticExportsDependency = require("./dependencies/StaticExportsDependency"); | ||
| const makeSerializable = require("./util/makeSerializable"); | ||
| /** @typedef {import("../declarations/plugins/DllReferencePlugin").DllReferencePluginOptions} DllReferencePluginOptions */ | ||
| /** @typedef {import("./config/defaults").WebpackOptionsNormalizedWithDefaults} WebpackOptions */ | ||
| /** @typedef {import("./Compilation")} Compilation */ | ||
| /** @typedef {import("./Dependency").UpdateHashContext} UpdateHashContext */ | ||
| /** @typedef {import("./Generator").SourceTypes} SourceTypes */ | ||
| /** @typedef {import("./LibManifestPlugin").ManifestModuleData} ManifestModuleData */ | ||
| /** @typedef {import("./Module").ModuleId} ModuleId */ | ||
| /** @typedef {import("./Module").BuildCallback} BuildCallback */ | ||
| /** @typedef {import("./Module").BuildMeta} BuildMeta */ | ||
| /** @typedef {import("./Module").CodeGenerationContext} CodeGenerationContext */ | ||
| /** @typedef {import("./Module").CodeGenerationResult} CodeGenerationResult */ | ||
| /** @typedef {import("./Module").LibIdentOptions} LibIdentOptions */ | ||
| /** @typedef {import("./Module").LibIdent} LibIdent */ | ||
| /** @typedef {import("./Module").NeedBuildCallback} NeedBuildCallback */ | ||
| /** @typedef {import("./Module").NeedBuildContext} NeedBuildContext */ | ||
| /** @typedef {import("./Module").Sources} Sources */ | ||
| /** @typedef {import("./Module").RuntimeRequirements} RuntimeRequirements */ | ||
| /** @typedef {import("./RequestShortener")} RequestShortener */ | ||
| /** @typedef {import("./ResolverFactory").ResolverWithOptions} ResolverWithOptions */ | ||
| /** @typedef {import("./serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ | ||
| /** @typedef {import("./serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ | ||
| /** @typedef {import("./dependencies/StaticExportsDependency").Exports} Exports */ | ||
| /** @typedef {import("./util/Hash")} Hash */ | ||
| /** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */ | ||
| /** @typedef {string} DelegatedModuleSourceRequest */ | ||
| /** @typedef {NonNullable<DllReferencePluginOptions["type"]>} DelegatedModuleType */ | ||
| /** | ||
| * Defines the delegated module data type used by this module. | ||
| * @typedef {object} DelegatedModuleData | ||
| * @property {BuildMeta=} buildMeta build meta | ||
| * @property {Exports=} exports exports | ||
| * @property {ModuleId} id module id | ||
| */ | ||
| const RUNTIME_REQUIREMENTS = new Set([ | ||
| RuntimeGlobals.module, | ||
| RuntimeGlobals.require | ||
| ]); | ||
| class DelegatedModule extends Module { | ||
| /** | ||
| * Creates an instance of DelegatedModule. | ||
| * @param {DelegatedModuleSourceRequest} sourceRequest source request | ||
| * @param {DelegatedModuleData} data data | ||
| * @param {DelegatedModuleType} type type | ||
| * @param {string} userRequest user request | ||
| * @param {string | Module} originalRequest original request | ||
| */ | ||
| constructor(sourceRequest, data, type, userRequest, originalRequest) { | ||
| super(JAVASCRIPT_MODULE_TYPE_DYNAMIC, null); | ||
| // Info from Factory | ||
| this.sourceRequest = sourceRequest; | ||
| this.request = data.id; | ||
| this.delegationType = type; | ||
| this.userRequest = userRequest; | ||
| this.originalRequest = originalRequest; | ||
| this.delegateData = data; | ||
| // Build info | ||
| /** @type {undefined | DelegatedSourceDependency} */ | ||
| this.delegatedSourceDependency = undefined; | ||
| } | ||
| /** | ||
| * Returns the source types this module can generate. | ||
| * @returns {SourceTypes} types available (do not mutate) | ||
| */ | ||
| getSourceTypes() { | ||
| return JAVASCRIPT_TYPES; | ||
| } | ||
| /** | ||
| * Gets the library identifier. | ||
| * @param {LibIdentOptions} options options | ||
| * @returns {LibIdent | null} an identifier for library inclusion | ||
| */ | ||
| libIdent(options) { | ||
| return typeof this.originalRequest === "string" | ||
| ? this.originalRequest | ||
| : this.originalRequest.libIdent(options); | ||
| } | ||
| /** | ||
| * Returns the unique identifier used to reference this module. | ||
| * @returns {string} a unique identifier of the module | ||
| */ | ||
| identifier() { | ||
| return `delegated ${JSON.stringify(this.request)} from ${ | ||
| this.sourceRequest | ||
| }`; | ||
| } | ||
| /** | ||
| * Returns a human-readable identifier for this module. | ||
| * @param {RequestShortener} requestShortener the request shortener | ||
| * @returns {string} a user readable identifier of the module | ||
| */ | ||
| readableIdentifier(requestShortener) { | ||
| return `delegated ${this.userRequest} from ${this.sourceRequest}`; | ||
| } | ||
| /** | ||
| * Checks whether the module needs to be rebuilt for the current build state. | ||
| * @param {NeedBuildContext} context context info | ||
| * @param {NeedBuildCallback} callback callback function, returns true, if the module needs a rebuild | ||
| * @returns {void} | ||
| */ | ||
| needBuild(context, callback) { | ||
| return callback(null, !this.buildMeta); | ||
| } | ||
| /** | ||
| * Builds the module using the provided compilation context. | ||
| * @param {WebpackOptions} options webpack options | ||
| * @param {Compilation} compilation the compilation | ||
| * @param {ResolverWithOptions} resolver the resolver | ||
| * @param {InputFileSystem} fs the file system | ||
| * @param {BuildCallback} callback callback function | ||
| * @returns {void} | ||
| */ | ||
| build(options, compilation, resolver, fs, callback) { | ||
| const delegateData = /** @type {ManifestModuleData} */ (this.delegateData); | ||
| this.buildMeta = { ...delegateData.buildMeta }; | ||
| this.buildInfo = {}; | ||
| this.dependencies.length = 0; | ||
| this.delegatedSourceDependency = new DelegatedSourceDependency( | ||
| this.sourceRequest | ||
| ); | ||
| this.addDependency(this.delegatedSourceDependency); | ||
| this.addDependency( | ||
| new StaticExportsDependency(delegateData.exports || true, false) | ||
| ); | ||
| callback(); | ||
| } | ||
| /** | ||
| * Generates code and runtime requirements for this module. | ||
| * @param {CodeGenerationContext} context context for code generation | ||
| * @returns {CodeGenerationResult} result | ||
| */ | ||
| codeGeneration({ runtimeTemplate, moduleGraph, chunkGraph }) { | ||
| const dep = /** @type {DelegatedSourceDependency} */ (this.dependencies[0]); | ||
| const sourceModule = moduleGraph.getModule(dep); | ||
| /** @type {string} */ | ||
| let str; | ||
| if (!sourceModule) { | ||
| str = runtimeTemplate.throwMissingModuleErrorBlock({ | ||
| request: this.sourceRequest | ||
| }); | ||
| } else { | ||
| str = `module.exports = (${runtimeTemplate.moduleExports({ | ||
| module: sourceModule, | ||
| chunkGraph, | ||
| request: dep.request, | ||
| /** @type {RuntimeRequirements} */ | ||
| runtimeRequirements: new Set() | ||
| })})`; | ||
| switch (this.delegationType) { | ||
| case "require": | ||
| str += `(${JSON.stringify(this.request)})`; | ||
| break; | ||
| case "object": | ||
| str += `[${JSON.stringify(this.request)}]`; | ||
| break; | ||
| } | ||
| str += ";"; | ||
| } | ||
| /** @type {Sources} */ | ||
| const sources = new Map(); | ||
| if (this.useSourceMap || this.useSimpleSourceMap) { | ||
| sources.set(JAVASCRIPT_TYPE, new OriginalSource(str, this.identifier())); | ||
| } else { | ||
| sources.set(JAVASCRIPT_TYPE, new RawSource(str)); | ||
| } | ||
| return { | ||
| sources, | ||
| runtimeRequirements: RUNTIME_REQUIREMENTS | ||
| }; | ||
| } | ||
| /** | ||
| * Returns the estimated size for the requested source type. | ||
| * @param {string=} type the source type for which the size should be estimated | ||
| * @returns {number} the estimated size of the module (must be non-zero) | ||
| */ | ||
| size(type) { | ||
| return 42; | ||
| } | ||
| /** | ||
| * Updates the hash with the data contributed by this instance. | ||
| * @param {Hash} hash the hash used to track dependencies | ||
| * @param {UpdateHashContext} context context | ||
| * @returns {void} | ||
| */ | ||
| updateHash(hash, context) { | ||
| hash.update(this.delegationType); | ||
| hash.update(JSON.stringify(this.request)); | ||
| super.updateHash(hash, context); | ||
| } | ||
| /** | ||
| * Serializes this instance into the provided serializer context. | ||
| * @param {ObjectSerializerContext} context context | ||
| */ | ||
| serialize(context) { | ||
| const { write } = context; | ||
| // constructor | ||
| write(this.sourceRequest); | ||
| write(this.delegateData); | ||
| write(this.delegationType); | ||
| write(this.userRequest); | ||
| write(this.originalRequest); | ||
| super.serialize(context); | ||
| } | ||
| /** | ||
| * Restores this instance from the provided deserializer context. | ||
| * @param {ObjectDeserializerContext} context context\ | ||
| * @returns {DelegatedModule} DelegatedModule | ||
| */ | ||
| static deserialize(context) { | ||
| const { read } = context; | ||
| const obj = new DelegatedModule( | ||
| read(), // sourceRequest | ||
| read(), // delegateData | ||
| read(), // delegationType | ||
| read(), // userRequest | ||
| read() // originalRequest | ||
| ); | ||
| obj.deserialize(context); | ||
| return obj; | ||
| } | ||
| /** | ||
| * Assuming this module is in the cache. Update the (cached) module with | ||
| * the fresh module from the factory. Usually updates internal references | ||
| * and properties. | ||
| * @param {Module} module fresh module | ||
| * @returns {void} | ||
| */ | ||
| updateCacheModule(module) { | ||
| super.updateCacheModule(module); | ||
| const m = /** @type {DelegatedModule} */ (module); | ||
| this.delegationType = m.delegationType; | ||
| this.userRequest = m.userRequest; | ||
| this.originalRequest = m.originalRequest; | ||
| this.delegateData = m.delegateData; | ||
| } | ||
| /** | ||
| * Assuming this module is in the cache. Remove internal references to allow freeing some memory. | ||
| */ | ||
| cleanupForCache() { | ||
| super.cleanupForCache(); | ||
| this.delegateData = | ||
| /** @type {EXPECTED_ANY} */ | ||
| (undefined); | ||
| } | ||
| } | ||
| makeSerializable(DelegatedModule, "webpack/lib/DelegatedModule"); | ||
| module.exports = DelegatedModule; |
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| Author Tobias Koppers @sokra | ||
| */ | ||
| "use strict"; | ||
| const DelegatedModule = require("./DelegatedModule"); | ||
| /** @typedef {import("../declarations/plugins/DllReferencePlugin").DllReferencePluginOptions} DllReferencePluginOptions */ | ||
| /** @typedef {import("../declarations/plugins/DllReferencePlugin").DllReferencePluginOptionsContent} DllReferencePluginOptionsContent */ | ||
| /** @typedef {import("./DelegatedModule").DelegatedModuleData} DelegatedModuleData */ | ||
| /** @typedef {import("./DelegatedModule").DelegatedModuleSourceRequest} DelegatedModuleSourceRequest */ | ||
| /** @typedef {import("./DelegatedModule").DelegatedModuleType} DelegatedModuleType */ | ||
| /** @typedef {import("./NormalModuleFactory")} NormalModuleFactory */ | ||
| /** @typedef {import("./util/identifier").AssociatedObjectForCache} AssociatedObjectForCache */ | ||
| /** | ||
| * Defines the options type used by this module. | ||
| * @typedef {object} Options | ||
| * @property {DelegatedModuleSourceRequest} source source | ||
| * @property {NonNullable<DllReferencePluginOptions["context"]>} context absolute context path to which lib ident is relative to | ||
| * @property {DllReferencePluginOptionsContent} content content | ||
| * @property {DllReferencePluginOptions["type"]} type type | ||
| * @property {DllReferencePluginOptions["extensions"]} extensions extensions | ||
| * @property {DllReferencePluginOptions["scope"]} scope scope | ||
| * @property {AssociatedObjectForCache=} associatedObjectForCache object for caching | ||
| */ | ||
| const PLUGIN_NAME = "DelegatedModuleFactoryPlugin"; | ||
| class DelegatedModuleFactoryPlugin { | ||
| /** | ||
| * Creates an instance of DelegatedModuleFactoryPlugin. | ||
| * @param {Options} options options | ||
| */ | ||
| constructor(options) { | ||
| this.options = options; | ||
| options.type = options.type || "require"; | ||
| options.extensions = options.extensions || ["", ".js", ".json", ".wasm"]; | ||
| } | ||
| /** | ||
| * Applies the plugin by registering its hooks on the compiler. | ||
| * @param {NormalModuleFactory} normalModuleFactory the normal module factory | ||
| * @returns {void} | ||
| */ | ||
| apply(normalModuleFactory) { | ||
| const scope = this.options.scope; | ||
| if (scope) { | ||
| normalModuleFactory.hooks.factorize.tapAsync( | ||
| PLUGIN_NAME, | ||
| (data, callback) => { | ||
| const [dependency] = data.dependencies; | ||
| const { request } = dependency; | ||
| if (request && request.startsWith(`${scope}/`)) { | ||
| const innerRequest = `.${request.slice(scope.length)}`; | ||
| /** @type {undefined | DelegatedModuleData} */ | ||
| let resolved; | ||
| if (innerRequest in this.options.content) { | ||
| resolved = this.options.content[innerRequest]; | ||
| return callback( | ||
| null, | ||
| new DelegatedModule( | ||
| this.options.source, | ||
| resolved, | ||
| /** @type {DelegatedModuleType} */ | ||
| (this.options.type), | ||
| innerRequest, | ||
| request | ||
| ) | ||
| ); | ||
| } | ||
| const extensions = | ||
| /** @type {string[]} */ | ||
| (this.options.extensions); | ||
| for (let i = 0; i < extensions.length; i++) { | ||
| const extension = extensions[i]; | ||
| const requestPlusExt = innerRequest + extension; | ||
| if (requestPlusExt in this.options.content) { | ||
| resolved = this.options.content[requestPlusExt]; | ||
| return callback( | ||
| null, | ||
| new DelegatedModule( | ||
| this.options.source, | ||
| resolved, | ||
| /** @type {DelegatedModuleType} */ | ||
| (this.options.type), | ||
| requestPlusExt, | ||
| request + extension | ||
| ) | ||
| ); | ||
| } | ||
| } | ||
| } | ||
| return callback(); | ||
| } | ||
| ); | ||
| } else { | ||
| normalModuleFactory.hooks.module.tap(PLUGIN_NAME, (module) => { | ||
| const request = module.libIdent(this.options); | ||
| if (request && request in this.options.content) { | ||
| const resolved = this.options.content[request]; | ||
| return new DelegatedModule( | ||
| this.options.source, | ||
| resolved, | ||
| /** @type {DelegatedModuleType} */ | ||
| (this.options.type), | ||
| request, | ||
| module | ||
| ); | ||
| } | ||
| return module; | ||
| }); | ||
| } | ||
| } | ||
| } | ||
| module.exports = DelegatedModuleFactoryPlugin; |
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| Author Tobias Koppers @sokra | ||
| */ | ||
| "use strict"; | ||
| const DelegatedModuleFactoryPlugin = require("./DelegatedModuleFactoryPlugin"); | ||
| const DelegatedSourceDependency = require("./dependencies/DelegatedSourceDependency"); | ||
| /** @typedef {import("./Compiler")} Compiler */ | ||
| /** @typedef {import("./DelegatedModuleFactoryPlugin").Options} Options */ | ||
| const PLUGIN_NAME = "DelegatedPlugin"; | ||
| class DelegatedPlugin { | ||
| /** | ||
| * Creates an instance of DelegatedPlugin. | ||
| * @param {Options} options options | ||
| */ | ||
| constructor(options) { | ||
| this.options = options; | ||
| } | ||
| /** | ||
| * Applies the plugin by registering its hooks on the compiler. | ||
| * @param {Compiler} compiler the compiler instance | ||
| * @returns {void} | ||
| */ | ||
| apply(compiler) { | ||
| compiler.hooks.compilation.tap( | ||
| PLUGIN_NAME, | ||
| (compilation, { normalModuleFactory }) => { | ||
| compilation.dependencyFactories.set( | ||
| DelegatedSourceDependency, | ||
| normalModuleFactory | ||
| ); | ||
| } | ||
| ); | ||
| compiler.hooks.compile.tap(PLUGIN_NAME, ({ normalModuleFactory }) => { | ||
| new DelegatedModuleFactoryPlugin({ | ||
| associatedObjectForCache: compiler.root, | ||
| ...this.options | ||
| }).apply(normalModuleFactory); | ||
| }); | ||
| } | ||
| } | ||
| module.exports = DelegatedPlugin; |
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| Author Tobias Koppers @sokra | ||
| */ | ||
| "use strict"; | ||
| const DllModuleFactory = require("./DllModuleFactory"); | ||
| const DllEntryDependency = require("./dependencies/DllEntryDependency"); | ||
| const EntryDependency = require("./dependencies/EntryDependency"); | ||
| /** @typedef {import("./Compiler")} Compiler */ | ||
| /** @typedef {import("./Entrypoint").EntryOptions} EntryOptions */ | ||
| /** @typedef {string[]} Entries */ | ||
| /** @typedef {EntryOptions & { name: string }} Options */ | ||
| const PLUGIN_NAME = "DllEntryPlugin"; | ||
| class DllEntryPlugin { | ||
| /** | ||
| * Creates an instance of DllEntryPlugin. | ||
| * @param {string} context context | ||
| * @param {Entries} entries entry names | ||
| * @param {Options} options options | ||
| */ | ||
| constructor(context, entries, options) { | ||
| this.context = context; | ||
| this.entries = entries; | ||
| this.options = options; | ||
| } | ||
| /** | ||
| * Applies the plugin by registering its hooks on the compiler. | ||
| * @param {Compiler} compiler the compiler instance | ||
| * @returns {void} | ||
| */ | ||
| apply(compiler) { | ||
| compiler.hooks.compilation.tap( | ||
| PLUGIN_NAME, | ||
| (compilation, { normalModuleFactory }) => { | ||
| const dllModuleFactory = new DllModuleFactory(); | ||
| compilation.dependencyFactories.set( | ||
| DllEntryDependency, | ||
| dllModuleFactory | ||
| ); | ||
| compilation.dependencyFactories.set( | ||
| EntryDependency, | ||
| normalModuleFactory | ||
| ); | ||
| } | ||
| ); | ||
| compiler.hooks.make.tapAsync(PLUGIN_NAME, (compilation, callback) => { | ||
| compilation.addEntry( | ||
| this.context, | ||
| new DllEntryDependency( | ||
| this.entries.map((e, idx) => { | ||
| const dep = new EntryDependency(e); | ||
| dep.loc = { | ||
| name: this.options.name, | ||
| index: idx | ||
| }; | ||
| return dep; | ||
| }), | ||
| this.options.name | ||
| ), | ||
| this.options, | ||
| (error) => { | ||
| if (error) return callback(error); | ||
| callback(); | ||
| } | ||
| ); | ||
| }); | ||
| } | ||
| } | ||
| module.exports = DllEntryPlugin; |
-186
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| Author Tobias Koppers @sokra | ||
| */ | ||
| "use strict"; | ||
| const { RawSource } = require("webpack-sources"); | ||
| const Module = require("./Module"); | ||
| const { | ||
| JAVASCRIPT_TYPE, | ||
| JAVASCRIPT_TYPES | ||
| } = require("./ModuleSourceTypeConstants"); | ||
| const { JAVASCRIPT_MODULE_TYPE_DYNAMIC } = require("./ModuleTypeConstants"); | ||
| const RuntimeGlobals = require("./RuntimeGlobals"); | ||
| const makeSerializable = require("./util/makeSerializable"); | ||
| /** @typedef {import("./config/defaults").WebpackOptionsNormalizedWithDefaults} WebpackOptions */ | ||
| /** @typedef {import("./Compilation")} Compilation */ | ||
| /** @typedef {import("./Dependency")} Dependency */ | ||
| /** @typedef {import("./Dependency").UpdateHashContext} UpdateHashContext */ | ||
| /** @typedef {import("./Generator").SourceTypes} SourceTypes */ | ||
| /** @typedef {import("./Module").BuildCallback} BuildCallback */ | ||
| /** @typedef {import("./Module").CodeGenerationContext} CodeGenerationContext */ | ||
| /** @typedef {import("./Module").CodeGenerationResult} CodeGenerationResult */ | ||
| /** @typedef {import("./Module").NeedBuildCallback} NeedBuildCallback */ | ||
| /** @typedef {import("./Module").NeedBuildContext} NeedBuildContext */ | ||
| /** @typedef {import("./Module").Sources} Sources */ | ||
| /** @typedef {import("./RequestShortener")} RequestShortener */ | ||
| /** @typedef {import("./ResolverFactory").ResolverWithOptions} ResolverWithOptions */ | ||
| /** @typedef {import("./serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ | ||
| /** @typedef {import("./serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ | ||
| /** @typedef {import("./util/Hash")} Hash */ | ||
| /** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */ | ||
| const RUNTIME_REQUIREMENTS = new Set([ | ||
| RuntimeGlobals.require, | ||
| RuntimeGlobals.module | ||
| ]); | ||
| class DllModule extends Module { | ||
| /** | ||
| * Creates an instance of DllModule. | ||
| * @param {string} context context path | ||
| * @param {Dependency[]} dependencies dependencies | ||
| * @param {string} name name | ||
| */ | ||
| constructor(context, dependencies, name) { | ||
| super(JAVASCRIPT_MODULE_TYPE_DYNAMIC, context); | ||
| // Info from Factory | ||
| /** @type {Dependency[]} */ | ||
| this.dependencies = dependencies; | ||
| this.name = name; | ||
| } | ||
| /** | ||
| * Returns the source types this module can generate. | ||
| * @returns {SourceTypes} types available (do not mutate) | ||
| */ | ||
| getSourceTypes() { | ||
| return JAVASCRIPT_TYPES; | ||
| } | ||
| /** | ||
| * Returns the unique identifier used to reference this module. | ||
| * @returns {string} a unique identifier of the module | ||
| */ | ||
| identifier() { | ||
| return `dll ${this.name}`; | ||
| } | ||
| /** | ||
| * Returns a human-readable identifier for this module. | ||
| * @param {RequestShortener} requestShortener the request shortener | ||
| * @returns {string} a user readable identifier of the module | ||
| */ | ||
| readableIdentifier(requestShortener) { | ||
| return `dll ${this.name}`; | ||
| } | ||
| /** | ||
| * Builds the module using the provided compilation context. | ||
| * @param {WebpackOptions} options webpack options | ||
| * @param {Compilation} compilation the compilation | ||
| * @param {ResolverWithOptions} resolver the resolver | ||
| * @param {InputFileSystem} fs the file system | ||
| * @param {BuildCallback} callback callback function | ||
| * @returns {void} | ||
| */ | ||
| build(options, compilation, resolver, fs, callback) { | ||
| this.buildMeta = {}; | ||
| this.buildInfo = {}; | ||
| return callback(); | ||
| } | ||
| /** | ||
| * Generates code and runtime requirements for this module. | ||
| * @param {CodeGenerationContext} context context for code generation | ||
| * @returns {CodeGenerationResult} result | ||
| */ | ||
| codeGeneration(context) { | ||
| /** @type {Sources} */ | ||
| const sources = new Map(); | ||
| sources.set( | ||
| JAVASCRIPT_TYPE, | ||
| new RawSource(`module.exports = ${RuntimeGlobals.require};`) | ||
| ); | ||
| return { | ||
| sources, | ||
| runtimeRequirements: RUNTIME_REQUIREMENTS | ||
| }; | ||
| } | ||
| /** | ||
| * Checks whether the module needs to be rebuilt for the current build state. | ||
| * @param {NeedBuildContext} context context info | ||
| * @param {NeedBuildCallback} callback callback function, returns true, if the module needs a rebuild | ||
| * @returns {void} | ||
| */ | ||
| needBuild(context, callback) { | ||
| return callback(null, !this.buildMeta); | ||
| } | ||
| /** | ||
| * Returns the estimated size for the requested source type. | ||
| * @param {string=} type the source type for which the size should be estimated | ||
| * @returns {number} the estimated size of the module (must be non-zero) | ||
| */ | ||
| size(type) { | ||
| return 12; | ||
| } | ||
| /** | ||
| * Updates the hash with the data contributed by this instance. | ||
| * @param {Hash} hash the hash used to track dependencies | ||
| * @param {UpdateHashContext} context context | ||
| * @returns {void} | ||
| */ | ||
| updateHash(hash, context) { | ||
| hash.update(`dll module${this.name || ""}`); | ||
| super.updateHash(hash, context); | ||
| } | ||
| /** | ||
| * Serializes this instance into the provided serializer context. | ||
| * @param {ObjectSerializerContext} context context | ||
| */ | ||
| serialize(context) { | ||
| context.write(this.name); | ||
| super.serialize(context); | ||
| } | ||
| /** | ||
| * Restores this instance from the provided deserializer context. | ||
| * @param {ObjectDeserializerContext} context context | ||
| */ | ||
| deserialize(context) { | ||
| this.name = context.read(); | ||
| super.deserialize(context); | ||
| } | ||
| /** | ||
| * Assuming this module is in the cache. Update the (cached) module with | ||
| * the fresh module from the factory. Usually updates internal references | ||
| * and properties. | ||
| * @param {Module} module fresh module | ||
| * @returns {void} | ||
| */ | ||
| updateCacheModule(module) { | ||
| super.updateCacheModule(module); | ||
| this.dependencies = module.dependencies; | ||
| } | ||
| /** | ||
| * Assuming this module is in the cache. Remove internal references to allow freeing some memory. | ||
| */ | ||
| cleanupForCache() { | ||
| super.cleanupForCache(); | ||
| this.dependencies = /** @type {EXPECTED_ANY} */ (undefined); | ||
| } | ||
| } | ||
| makeSerializable(DllModule, "webpack/lib/DllModule"); | ||
| module.exports = DllModule; |
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| Author Tobias Koppers @sokra | ||
| */ | ||
| "use strict"; | ||
| const DllModule = require("./DllModule"); | ||
| const ModuleFactory = require("./ModuleFactory"); | ||
| /** @typedef {import("./ModuleFactory").ModuleFactoryCallback} ModuleFactoryCallback */ | ||
| /** @typedef {import("./ModuleFactory").ModuleFactoryCreateData} ModuleFactoryCreateData */ | ||
| /** @typedef {import("./dependencies/DllEntryDependency")} DllEntryDependency */ | ||
| class DllModuleFactory extends ModuleFactory { | ||
| constructor() { | ||
| super(); | ||
| this.hooks = Object.freeze({}); | ||
| } | ||
| /** | ||
| * Processes the provided data. | ||
| * @param {ModuleFactoryCreateData} data data object | ||
| * @param {ModuleFactoryCallback} callback callback | ||
| * @returns {void} | ||
| */ | ||
| create(data, callback) { | ||
| const dependency = /** @type {DllEntryDependency} */ (data.dependencies[0]); | ||
| callback(null, { | ||
| module: new DllModule( | ||
| data.context, | ||
| dependency.dependencies, | ||
| dependency.name | ||
| ) | ||
| }); | ||
| } | ||
| } | ||
| module.exports = DllModuleFactory; |
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| Author Tobias Koppers @sokra | ||
| */ | ||
| "use strict"; | ||
| const DllEntryPlugin = require("./DllEntryPlugin"); | ||
| const FlagAllModulesAsUsedPlugin = require("./FlagAllModulesAsUsedPlugin"); | ||
| const LibManifestPlugin = require("./LibManifestPlugin"); | ||
| /** @typedef {import("../declarations/plugins/DllPlugin").DllPluginOptions} DllPluginOptions */ | ||
| /** @typedef {import("./Compiler")} Compiler */ | ||
| /** @typedef {import("./DllEntryPlugin").Entries} Entries */ | ||
| /** @typedef {import("./DllEntryPlugin").Options} Options */ | ||
| const PLUGIN_NAME = "DllPlugin"; | ||
| class DllPlugin { | ||
| /** | ||
| * Creates an instance of DllPlugin. | ||
| * @param {DllPluginOptions} options options object | ||
| */ | ||
| constructor(options) { | ||
| /** @type {DllPluginOptions} */ | ||
| this.options = options; | ||
| } | ||
| /** | ||
| * Applies the plugin by registering its hooks on the compiler. | ||
| * @param {Compiler} compiler the compiler instance | ||
| * @returns {void} | ||
| */ | ||
| apply(compiler) { | ||
| compiler.hooks.validate.tap(PLUGIN_NAME, () => { | ||
| compiler.validate( | ||
| () => require("../schemas/plugins/DllPlugin.json"), | ||
| this.options, | ||
| { | ||
| name: "Dll Plugin", | ||
| baseDataPath: "options" | ||
| }, | ||
| (options) => require("../schemas/plugins/DllPlugin.check")(options) | ||
| ); | ||
| }); | ||
| const entryOnly = this.options.entryOnly !== false; | ||
| compiler.hooks.entryOption.tap(PLUGIN_NAME, (context, entry) => { | ||
| if (typeof entry !== "function") { | ||
| for (const name of Object.keys(entry)) { | ||
| /** @type {Options} */ | ||
| const options = { name }; | ||
| new DllEntryPlugin( | ||
| context, | ||
| /** @type {Entries} */ | ||
| (entry[name].import), | ||
| options | ||
| ).apply(compiler); | ||
| } | ||
| } else { | ||
| throw new Error( | ||
| `${PLUGIN_NAME} doesn't support dynamic entry (function) yet` | ||
| ); | ||
| } | ||
| return true; | ||
| }); | ||
| new LibManifestPlugin({ ...this.options, entryOnly }).apply(compiler); | ||
| if (!entryOnly) { | ||
| new FlagAllModulesAsUsedPlugin(PLUGIN_NAME).apply(compiler); | ||
| } | ||
| } | ||
| } | ||
| module.exports = DllPlugin; |
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| Author Tobias Koppers @sokra | ||
| */ | ||
| "use strict"; | ||
| const DelegatedModuleFactoryPlugin = require("./DelegatedModuleFactoryPlugin"); | ||
| const ExternalModuleFactoryPlugin = require("./ExternalModuleFactoryPlugin"); | ||
| const WebpackError = require("./WebpackError"); | ||
| const DelegatedSourceDependency = require("./dependencies/DelegatedSourceDependency"); | ||
| const { makePathsRelative } = require("./util/identifier"); | ||
| const parseJson = require("./util/parseJson"); | ||
| /** @typedef {import("../declarations/WebpackOptions").Externals} Externals */ | ||
| /** @typedef {import("../declarations/plugins/DllReferencePlugin").DllReferencePluginOptions} DllReferencePluginOptions */ | ||
| /** @typedef {import("../declarations/plugins/DllReferencePlugin").DllReferencePluginOptionsContent} DllReferencePluginOptionsContent */ | ||
| /** @typedef {import("../declarations/plugins/DllReferencePlugin").DllReferencePluginOptionsManifest} DllReferencePluginOptionsManifest */ | ||
| /** @typedef {import("./Compiler")} Compiler */ | ||
| /** @typedef {import("./Compiler").CompilationParams} CompilationParams */ | ||
| /** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */ | ||
| /** @typedef {{ path: string, data: DllReferencePluginOptionsManifest | undefined, error: Error | undefined }} CompilationDataItem */ | ||
| const PLUGIN_NAME = "DllReferencePlugin"; | ||
| class DllReferencePlugin { | ||
| /** | ||
| * Creates an instance of DllReferencePlugin. | ||
| * @param {DllReferencePluginOptions} options options object | ||
| */ | ||
| constructor(options) { | ||
| this.options = options; | ||
| } | ||
| /** | ||
| * Applies the plugin by registering its hooks on the compiler. | ||
| * @param {Compiler} compiler the compiler instance | ||
| * @returns {void} | ||
| */ | ||
| apply(compiler) { | ||
| compiler.hooks.validate.tap(PLUGIN_NAME, () => { | ||
| compiler.validate( | ||
| () => require("../schemas/plugins/DllReferencePlugin.json"), | ||
| this.options, | ||
| { | ||
| name: "Dll Reference Plugin", | ||
| baseDataPath: "options" | ||
| }, | ||
| (options) => | ||
| require("../schemas/plugins/DllReferencePlugin.check")(options) | ||
| ); | ||
| }); | ||
| compiler.hooks.compilation.tap( | ||
| PLUGIN_NAME, | ||
| (compilation, { normalModuleFactory }) => { | ||
| compilation.dependencyFactories.set( | ||
| DelegatedSourceDependency, | ||
| normalModuleFactory | ||
| ); | ||
| } | ||
| ); | ||
| /** @type {WeakMap<CompilationParams, CompilationDataItem>} */ | ||
| const compilationData = new WeakMap(); | ||
| compiler.hooks.beforeCompile.tapAsync(PLUGIN_NAME, (params, callback) => { | ||
| if ("manifest" in this.options) { | ||
| const manifest = this.options.manifest; | ||
| if (typeof manifest === "string") { | ||
| /** @type {InputFileSystem} */ | ||
| (compiler.inputFileSystem).readFile(manifest, (err, result) => { | ||
| if (err) return callback(err); | ||
| /** @type {CompilationDataItem} */ | ||
| const data = { | ||
| path: manifest, | ||
| data: undefined, | ||
| error: undefined | ||
| }; | ||
| // Catch errors parsing the manifest so that blank | ||
| // or malformed manifest files don't kill the process. | ||
| try { | ||
| data.data = | ||
| /** @type {DllReferencePluginOptionsManifest} */ | ||
| ( | ||
| /** @type {unknown} */ | ||
| (parseJson(/** @type {Buffer} */ (result).toString("utf8"))) | ||
| ); | ||
| } catch (parseErr) { | ||
| // Store the error in the params so that it can | ||
| // be added as a compilation error later on. | ||
| const manifestPath = makePathsRelative( | ||
| compiler.context, | ||
| manifest, | ||
| compiler.root | ||
| ); | ||
| data.error = new DllManifestError( | ||
| manifestPath, | ||
| /** @type {Error} */ (parseErr).message | ||
| ); | ||
| } | ||
| compilationData.set(params, data); | ||
| return callback(); | ||
| }); | ||
| return; | ||
| } | ||
| } | ||
| return callback(); | ||
| }); | ||
| compiler.hooks.compile.tap(PLUGIN_NAME, (params) => { | ||
| let name = this.options.name; | ||
| let sourceType = this.options.sourceType; | ||
| let resolvedContent = | ||
| "content" in this.options ? this.options.content : undefined; | ||
| if ("manifest" in this.options) { | ||
| const manifestParameter = this.options.manifest; | ||
| /** @type {undefined | DllReferencePluginOptionsManifest} */ | ||
| let manifest; | ||
| if (typeof manifestParameter === "string") { | ||
| const data = | ||
| /** @type {CompilationDataItem} */ | ||
| (compilationData.get(params)); | ||
| // If there was an error parsing the manifest | ||
| // file, exit now because the error will be added | ||
| // as a compilation error in the "compilation" hook. | ||
| if (data.error) { | ||
| return; | ||
| } | ||
| manifest = data.data; | ||
| } else { | ||
| manifest = manifestParameter; | ||
| } | ||
| if (manifest) { | ||
| if (!name) name = manifest.name; | ||
| if (!sourceType) sourceType = manifest.type; | ||
| if (!resolvedContent) resolvedContent = manifest.content; | ||
| } | ||
| } | ||
| /** @type {Externals} */ | ||
| const externals = {}; | ||
| const source = `dll-reference ${name}`; | ||
| externals[source] = /** @type {string} */ (name); | ||
| const normalModuleFactory = params.normalModuleFactory; | ||
| new ExternalModuleFactoryPlugin(sourceType || "var", externals).apply( | ||
| normalModuleFactory | ||
| ); | ||
| new DelegatedModuleFactoryPlugin({ | ||
| source, | ||
| type: this.options.type, | ||
| scope: this.options.scope, | ||
| context: this.options.context || compiler.context, | ||
| content: | ||
| /** @type {DllReferencePluginOptionsContent} */ | ||
| (resolvedContent), | ||
| extensions: this.options.extensions, | ||
| associatedObjectForCache: compiler.root | ||
| }).apply(normalModuleFactory); | ||
| }); | ||
| compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation, params) => { | ||
| if ("manifest" in this.options) { | ||
| const manifest = this.options.manifest; | ||
| if (typeof manifest === "string") { | ||
| const data = | ||
| /** @type {CompilationDataItem} */ | ||
| (compilationData.get(params)); | ||
| // If there was an error parsing the manifest file, add the | ||
| // error as a compilation error to make the compilation fail. | ||
| if (data.error) { | ||
| compilation.errors.push( | ||
| /** @type {DllManifestError} */ (data.error) | ||
| ); | ||
| } | ||
| compilation.fileDependencies.add(manifest); | ||
| } | ||
| } | ||
| }); | ||
| } | ||
| } | ||
| class DllManifestError extends WebpackError { | ||
| /** | ||
| * Creates an instance of DllManifestError. | ||
| * @param {string} filename filename of the manifest | ||
| * @param {string} message error message | ||
| */ | ||
| constructor(filename, message) { | ||
| super(); | ||
| this.name = "DllManifestError"; | ||
| this.message = `Dll manifest ${filename}\n${message}`; | ||
| } | ||
| } | ||
| module.exports = DllReferencePlugin; |
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| Author Gengkun He @ahabhgk | ||
| */ | ||
| "use strict"; | ||
| const WebpackError = require("./WebpackError"); | ||
| const makeSerializable = require("./util/makeSerializable"); | ||
| /** @typedef {import("./Module")} Module */ | ||
| /** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */ | ||
| /** @typedef {"asyncWebAssembly" | "topLevelAwait" | "external promise" | "external script" | "external import" | "external module"} Feature */ | ||
| class EnvironmentNotSupportAsyncWarning extends WebpackError { | ||
| /** | ||
| * Creates an instance of EnvironmentNotSupportAsyncWarning. | ||
| * @param {Module} module module | ||
| * @param {Feature} feature feature | ||
| */ | ||
| constructor(module, feature) { | ||
| const message = `The generated code contains 'async/await' because this module is using "${feature}". | ||
| However, your target environment does not appear to support 'async/await'. | ||
| As a result, the code may not run as expected or may cause runtime errors.`; | ||
| super(message); | ||
| /** @type {string} */ | ||
| this.name = "EnvironmentNotSupportAsyncWarning"; | ||
| /** @type {Module} */ | ||
| this.module = module; | ||
| } | ||
| /** | ||
| * Creates an instance of EnvironmentNotSupportAsyncWarning. | ||
| * @param {Module} module module | ||
| * @param {RuntimeTemplate} runtimeTemplate compilation | ||
| * @param {Feature} feature feature | ||
| */ | ||
| static check(module, runtimeTemplate, feature) { | ||
| if (!runtimeTemplate.supportsAsyncFunction()) { | ||
| module.addWarning(new EnvironmentNotSupportAsyncWarning(module, feature)); | ||
| } | ||
| } | ||
| } | ||
| makeSerializable( | ||
| EnvironmentNotSupportAsyncWarning, | ||
| "webpack/lib/EnvironmentNotSupportAsyncWarning" | ||
| ); | ||
| module.exports = EnvironmentNotSupportAsyncWarning; |
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| Author Arka Pratim Chaudhuri @arkapratimc | ||
| */ | ||
| "use strict"; | ||
| const WebpackError = require("./WebpackError"); | ||
| class FalseIIFEUmdWarning extends WebpackError { | ||
| constructor() { | ||
| super(); | ||
| /** @type {string} */ | ||
| this.name = "FalseIIFEUmdWarning"; | ||
| this.message = | ||
| "Configuration:\nSetting 'output.iife' to 'false' is incompatible with 'output.library.type' set to 'umd'. This configuration may cause unexpected behavior, as UMD libraries are expected to use an IIFE (Immediately Invoked Function Expression) to support various module formats. Consider setting 'output.iife' to 'true' or choosing a different 'library.type' to ensure compatibility.\nLearn more: https://webpack.js.org/configuration/output/"; | ||
| } | ||
| } | ||
| module.exports = FalseIIFEUmdWarning; |
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| Author Tobias Koppers @sokra | ||
| */ | ||
| "use strict"; | ||
| /** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ | ||
| /** @typedef {import("./Dependency").SourcePosition} SourcePosition */ | ||
| /** | ||
| * Returns formatted position. | ||
| * @param {SourcePosition} pos position | ||
| * @returns {string} formatted position | ||
| */ | ||
| const formatPosition = (pos) => { | ||
| if (pos && typeof pos === "object") { | ||
| if ("line" in pos && "column" in pos) { | ||
| return `${pos.line}:${pos.column}`; | ||
| } else if ("line" in pos) { | ||
| return `${pos.line}:?`; | ||
| } | ||
| } | ||
| return ""; | ||
| }; | ||
| /** | ||
| * Returns formatted location. | ||
| * @param {DependencyLocation} loc location | ||
| * @returns {string} formatted location | ||
| */ | ||
| const formatLocation = (loc) => { | ||
| if (loc && typeof loc === "object") { | ||
| if ("start" in loc && loc.start && "end" in loc && loc.end) { | ||
| if ( | ||
| typeof loc.start === "object" && | ||
| typeof loc.start.line === "number" && | ||
| typeof loc.end === "object" && | ||
| typeof loc.end.line === "number" && | ||
| typeof loc.end.column === "number" && | ||
| loc.start.line === loc.end.line | ||
| ) { | ||
| return `${formatPosition(loc.start)}-${loc.end.column}`; | ||
| } else if ( | ||
| typeof loc.start === "object" && | ||
| typeof loc.start.line === "number" && | ||
| typeof loc.start.column !== "number" && | ||
| typeof loc.end === "object" && | ||
| typeof loc.end.line === "number" && | ||
| typeof loc.end.column !== "number" | ||
| ) { | ||
| return `${loc.start.line}-${loc.end.line}`; | ||
| } | ||
| return `${formatPosition(loc.start)}-${formatPosition(loc.end)}`; | ||
| } | ||
| if ("start" in loc && loc.start) { | ||
| return formatPosition(loc.start); | ||
| } | ||
| if ("name" in loc && "index" in loc) { | ||
| return `${loc.name}[${loc.index}]`; | ||
| } | ||
| if ("name" in loc) { | ||
| return loc.name; | ||
| } | ||
| } | ||
| return ""; | ||
| }; | ||
| module.exports = formatLocation; |
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| Author Tobias Koppers @sokra | ||
| */ | ||
| "use strict"; | ||
| /** @typedef {import("./Chunk")} Chunk */ | ||
| /** @typedef {import("./ChunkGroup")} ChunkGroup */ | ||
| /** @typedef {import(".").Entrypoint} Entrypoint */ | ||
| /** | ||
| * Connects chunk group and chunk. | ||
| * @param {ChunkGroup} chunkGroup the ChunkGroup to connect | ||
| * @param {Chunk} chunk chunk to tie to ChunkGroup | ||
| * @returns {void} | ||
| */ | ||
| const connectChunkGroupAndChunk = (chunkGroup, chunk) => { | ||
| if (chunkGroup.pushChunk(chunk)) { | ||
| chunk.addGroup(chunkGroup); | ||
| } | ||
| }; | ||
| /** | ||
| * Connects chunk group parent and child. | ||
| * @param {ChunkGroup} parent parent ChunkGroup to connect | ||
| * @param {ChunkGroup} child child ChunkGroup to connect | ||
| * @returns {void} | ||
| */ | ||
| const connectChunkGroupParentAndChild = (parent, child) => { | ||
| if (parent.addChild(child)) { | ||
| child.addParent(parent); | ||
| } | ||
| }; | ||
| /** | ||
| * Connects entrypoint and depend on. | ||
| * @param {Entrypoint} entrypoint the entrypoint | ||
| * @param {Entrypoint} dependOnEntrypoint the dependOnEntrypoint | ||
| * @returns {void} | ||
| */ | ||
| const connectEntrypointAndDependOn = (entrypoint, dependOnEntrypoint) => { | ||
| entrypoint.addDependOn(dependOnEntrypoint); | ||
| }; | ||
| module.exports.connectChunkGroupAndChunk = connectChunkGroupAndChunk; | ||
| module.exports.connectChunkGroupParentAndChild = | ||
| connectChunkGroupParentAndChild; | ||
| module.exports.connectEntrypointAndDependOn = connectEntrypointAndDependOn; |
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| */ | ||
| "use strict"; | ||
| const WebpackError = require("./WebpackError"); | ||
| module.exports = class HarmonyLinkingError extends WebpackError { | ||
| /** @param {string} message Error message */ | ||
| constructor(message) { | ||
| super(message); | ||
| /** @type {string} */ | ||
| this.name = "HarmonyLinkingError"; | ||
| this.hideStack = true; | ||
| } | ||
| }; |
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| Author Sean Larkin @thelarkinn | ||
| */ | ||
| "use strict"; | ||
| const WebpackError = require("./WebpackError"); | ||
| const makeSerializable = require("./util/makeSerializable"); | ||
| /** @typedef {import("./serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ | ||
| /** @typedef {import("./serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ | ||
| /** | ||
| * Defines the callback callback. | ||
| * @template T | ||
| * @callback Callback | ||
| * @param {Error | null} err | ||
| * @param {T=} stats | ||
| * @returns {void} | ||
| */ | ||
| class HookWebpackError extends WebpackError { | ||
| /** | ||
| * Creates an instance of HookWebpackError. | ||
| * @param {Error} error inner error | ||
| * @param {string} hook name of hook | ||
| */ | ||
| constructor(error, hook) { | ||
| super(error ? error.message : undefined, error ? { cause: error } : {}); | ||
| this.hook = hook; | ||
| this.error = error; | ||
| /** @type {string} */ | ||
| this.name = "HookWebpackError"; | ||
| this.hideStack = true; | ||
| this.stack += `\n-- inner error --\n${error ? error.stack : ""}`; | ||
| this.details = `caused by plugins in ${hook}\n${error ? error.stack : ""}`; | ||
| } | ||
| /** | ||
| * Serializes this instance into the provided serializer context. | ||
| * @param {ObjectSerializerContext} context context | ||
| */ | ||
| serialize(context) { | ||
| const { write } = context; | ||
| write(this.error); | ||
| write(this.hook); | ||
| super.serialize(context); | ||
| } | ||
| /** | ||
| * Restores this instance from the provided deserializer context. | ||
| * @param {ObjectDeserializerContext} context context | ||
| */ | ||
| deserialize(context) { | ||
| const { read } = context; | ||
| this.error = read(); | ||
| this.hook = read(); | ||
| super.deserialize(context); | ||
| } | ||
| } | ||
| makeSerializable(HookWebpackError, "webpack/lib/HookWebpackError"); | ||
| module.exports = HookWebpackError; | ||
| /** | ||
| * Creates webpack error. | ||
| * @param {Error} error an error | ||
| * @param {string} hook name of the hook | ||
| * @returns {WebpackError} a webpack error | ||
| */ | ||
| const makeWebpackError = (error, hook) => { | ||
| if (error instanceof WebpackError) return error; | ||
| return new HookWebpackError(error, hook); | ||
| }; | ||
| module.exports.makeWebpackError = makeWebpackError; | ||
| /** | ||
| * Creates webpack error callback. | ||
| * @template T | ||
| * @param {(err: WebpackError | null, result?: T) => void} callback webpack error callback | ||
| * @param {string} hook name of hook | ||
| * @returns {Callback<T>} generic callback | ||
| */ | ||
| const makeWebpackErrorCallback = (callback, hook) => (err, result) => { | ||
| if (err) { | ||
| if (err instanceof WebpackError) { | ||
| callback(err); | ||
| return; | ||
| } | ||
| callback(new HookWebpackError(err, hook)); | ||
| return; | ||
| } | ||
| callback(null, result); | ||
| }; | ||
| module.exports.makeWebpackErrorCallback = makeWebpackErrorCallback; | ||
| /** | ||
| * Try run or webpack error. | ||
| * @template T | ||
| * @param {() => T} fn function which will be wrapping in try catch | ||
| * @param {string} hook name of hook | ||
| * @returns {T} the result | ||
| */ | ||
| const tryRunOrWebpackError = (fn, hook) => { | ||
| /** @type {T} */ | ||
| let r; | ||
| try { | ||
| r = fn(); | ||
| } catch (err) { | ||
| if (err instanceof WebpackError) { | ||
| throw err; | ||
| } | ||
| throw new HookWebpackError(/** @type {Error} */ (err), hook); | ||
| } | ||
| return r; | ||
| }; | ||
| module.exports.tryRunOrWebpackError = tryRunOrWebpackError; |
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| Author Ivan Kopeykin @vankop | ||
| */ | ||
| "use strict"; | ||
| const ModuleFactory = require("./ModuleFactory"); | ||
| /** @typedef {import("./ModuleFactory").ModuleFactoryCallback} ModuleFactoryCallback */ | ||
| /** @typedef {import("./ModuleFactory").ModuleFactoryCreateData} ModuleFactoryCreateData */ | ||
| /** @typedef {import("./NormalModuleFactory")} NormalModuleFactory */ | ||
| /** | ||
| * Ignores error when module is unresolved | ||
| */ | ||
| class IgnoreErrorModuleFactory extends ModuleFactory { | ||
| /** | ||
| * Creates an instance of IgnoreErrorModuleFactory. | ||
| * @param {NormalModuleFactory} normalModuleFactory normalModuleFactory instance | ||
| */ | ||
| constructor(normalModuleFactory) { | ||
| super(); | ||
| this.normalModuleFactory = normalModuleFactory; | ||
| } | ||
| /** | ||
| * Processes the provided data. | ||
| * @param {ModuleFactoryCreateData} data data object | ||
| * @param {ModuleFactoryCallback} callback callback | ||
| * @returns {void} | ||
| */ | ||
| create(data, callback) { | ||
| this.normalModuleFactory.create(data, (err, result) => | ||
| callback(null, result) | ||
| ); | ||
| } | ||
| } | ||
| module.exports = IgnoreErrorModuleFactory; |
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| Author Tobias Koppers @sokra | ||
| */ | ||
| "use strict"; | ||
| const WebpackError = require("./WebpackError"); | ||
| const makeSerializable = require("./util/makeSerializable"); | ||
| /** @typedef {import("./Module")} Module */ | ||
| class InvalidDependenciesModuleWarning extends WebpackError { | ||
| /** | ||
| * Creates an instance of InvalidDependenciesModuleWarning. | ||
| * @param {Module} module module tied to dependency | ||
| * @param {Iterable<string>} deps invalid dependencies | ||
| */ | ||
| constructor(module, deps) { | ||
| const orderedDeps = deps ? [...deps].sort() : []; | ||
| const depsList = orderedDeps.map((dep) => ` * ${JSON.stringify(dep)}`); | ||
| super(`Invalid dependencies have been reported by plugins or loaders for this module. All reported dependencies need to be absolute paths. | ||
| Invalid dependencies may lead to broken watching and caching. | ||
| As best effort we try to convert all invalid values to absolute paths and converting globs into context dependencies, but this is deprecated behavior. | ||
| Loaders: Pass absolute paths to this.addDependency (existing files), this.addMissingDependency (not existing files), and this.addContextDependency (directories). | ||
| Plugins: Pass absolute paths to fileDependencies (existing files), missingDependencies (not existing files), and contextDependencies (directories). | ||
| Globs: They are not supported. Pass absolute path to the directory as context dependencies. | ||
| The following invalid values have been reported: | ||
| ${depsList.slice(0, 3).join("\n")}${ | ||
| depsList.length > 3 ? "\n * and more ..." : "" | ||
| }`); | ||
| /** @type {string} */ | ||
| this.name = "InvalidDependenciesModuleWarning"; | ||
| this.details = depsList.slice(3).join("\n"); | ||
| this.module = module; | ||
| } | ||
| } | ||
| makeSerializable( | ||
| InvalidDependenciesModuleWarning, | ||
| "webpack/lib/InvalidDependenciesModuleWarning" | ||
| ); | ||
| module.exports = InvalidDependenciesModuleWarning; |
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| Author Tobias Koppers @sokra | ||
| */ | ||
| "use strict"; | ||
| const asyncLib = require("neo-async"); | ||
| const EntryDependency = require("./dependencies/EntryDependency"); | ||
| const { someInIterable } = require("./util/IterableHelpers"); | ||
| const { compareModulesById } = require("./util/comparators"); | ||
| const { dirname, mkdirp } = require("./util/fs"); | ||
| /** @typedef {import("./ChunkGraph").ModuleId} ModuleId */ | ||
| /** @typedef {import("./Compiler")} Compiler */ | ||
| /** @typedef {import("./Compiler").IntermediateFileSystem} IntermediateFileSystem */ | ||
| /** @typedef {import("./Module").BuildMeta} BuildMeta */ | ||
| /** @typedef {import("./ExportsInfo").ExportInfoName} ExportInfoName */ | ||
| /** | ||
| * Defines the manifest module data type used by this module. | ||
| * @typedef {object} ManifestModuleData | ||
| * @property {ModuleId} id | ||
| * @property {BuildMeta=} buildMeta | ||
| * @property {ExportInfoName[]=} exports | ||
| */ | ||
| /** | ||
| * Defines the lib manifest plugin options type used by this module. | ||
| * @typedef {object} LibManifestPluginOptions | ||
| * @property {string=} context Context of requests in the manifest file (defaults to the webpack context). | ||
| * @property {boolean=} entryOnly If true, only entry points will be exposed (default: true). | ||
| * @property {boolean=} format If true, manifest json file (output) will be formatted. | ||
| * @property {string=} name Name of the exposed dll function (external name, use value of 'output.library'). | ||
| * @property {string} path Absolute path to the manifest json file (output). | ||
| * @property {string=} type Type of the dll bundle (external type, use value of 'output.libraryTarget'). | ||
| */ | ||
| const PLUGIN_NAME = "LibManifestPlugin"; | ||
| class LibManifestPlugin { | ||
| /** | ||
| * Creates an instance of LibManifestPlugin. | ||
| * @param {LibManifestPluginOptions} options the options | ||
| */ | ||
| constructor(options) { | ||
| this.options = options; | ||
| } | ||
| /** | ||
| * Applies the plugin by registering its hooks on the compiler. | ||
| * @param {Compiler} compiler the compiler instance | ||
| * @returns {void} | ||
| */ | ||
| apply(compiler) { | ||
| compiler.hooks.emit.tapAsync( | ||
| { name: PLUGIN_NAME, stage: 110 }, | ||
| (compilation, callback) => { | ||
| const moduleGraph = compilation.moduleGraph; | ||
| // store used paths to detect issue and output an error. #18200 | ||
| /** @type {Set<string>} */ | ||
| const usedPaths = new Set(); | ||
| asyncLib.each( | ||
| [...compilation.chunks], | ||
| (chunk, callback) => { | ||
| if (!chunk.canBeInitial()) { | ||
| callback(); | ||
| return; | ||
| } | ||
| const chunkGraph = compilation.chunkGraph; | ||
| const targetPath = compilation.getPath(this.options.path, { | ||
| chunk | ||
| }); | ||
| if (usedPaths.has(targetPath)) { | ||
| callback(new Error("each chunk must have a unique path")); | ||
| return; | ||
| } | ||
| usedPaths.add(targetPath); | ||
| const name = | ||
| this.options.name && | ||
| compilation.getPath(this.options.name, { | ||
| chunk, | ||
| contentHashType: "javascript" | ||
| }); | ||
| const content = Object.create(null); | ||
| for (const module of chunkGraph.getOrderedChunkModulesIterable( | ||
| chunk, | ||
| compareModulesById(chunkGraph) | ||
| )) { | ||
| if ( | ||
| this.options.entryOnly && | ||
| !someInIterable( | ||
| moduleGraph.getIncomingConnections(module), | ||
| (c) => c.dependency instanceof EntryDependency | ||
| ) | ||
| ) { | ||
| continue; | ||
| } | ||
| const ident = module.libIdent({ | ||
| context: this.options.context || compiler.context, | ||
| associatedObjectForCache: compiler.root | ||
| }); | ||
| if (ident) { | ||
| const exportsInfo = moduleGraph.getExportsInfo(module); | ||
| const providedExports = exportsInfo.getProvidedExports(); | ||
| /** @type {ManifestModuleData} */ | ||
| const data = { | ||
| id: /** @type {ModuleId} */ (chunkGraph.getModuleId(module)), | ||
| buildMeta: /** @type {BuildMeta} */ (module.buildMeta), | ||
| exports: Array.isArray(providedExports) | ||
| ? providedExports | ||
| : undefined | ||
| }; | ||
| content[ident] = data; | ||
| } | ||
| } | ||
| const manifest = { | ||
| name, | ||
| type: this.options.type, | ||
| content | ||
| }; | ||
| // Apply formatting to content if format flag is true; | ||
| const manifestContent = this.options.format | ||
| ? JSON.stringify(manifest, null, 2) | ||
| : JSON.stringify(manifest); | ||
| const buffer = Buffer.from(manifestContent, "utf8"); | ||
| const intermediateFileSystem = | ||
| /** @type {IntermediateFileSystem} */ ( | ||
| compiler.intermediateFileSystem | ||
| ); | ||
| mkdirp( | ||
| intermediateFileSystem, | ||
| dirname(intermediateFileSystem, targetPath), | ||
| (err) => { | ||
| if (err) return callback(err); | ||
| intermediateFileSystem.writeFile(targetPath, buffer, callback); | ||
| } | ||
| ); | ||
| }, | ||
| callback | ||
| ); | ||
| } | ||
| ); | ||
| } | ||
| } | ||
| module.exports = LibManifestPlugin; |
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| Author Tobias Koppers @sokra | ||
| */ | ||
| "use strict"; | ||
| const { cutOffLoaderExecution } = require("./ErrorHelpers"); | ||
| const WebpackError = require("./WebpackError"); | ||
| const makeSerializable = require("./util/makeSerializable"); | ||
| /** @typedef {import("./serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ | ||
| /** @typedef {import("./serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ | ||
| /** @typedef {Error & { hideStack?: boolean }} ErrorWithHideStack */ | ||
| class ModuleBuildError extends WebpackError { | ||
| /** | ||
| * Creates an instance of ModuleBuildError. | ||
| * @param {string | ErrorWithHideStack} err error thrown | ||
| * @param {{ from?: string | null }} info additional info | ||
| */ | ||
| constructor(err, { from = null } = {}) { | ||
| let message = "Module build failed"; | ||
| /** @type {undefined | string} */ | ||
| let details; | ||
| message += from ? ` (from ${from}):\n` : ": "; | ||
| if (err !== null && typeof err === "object") { | ||
| if (typeof err.stack === "string" && err.stack) { | ||
| const stack = cutOffLoaderExecution(err.stack); | ||
| if (!err.hideStack) { | ||
| message += stack; | ||
| } else { | ||
| details = stack; | ||
| message += | ||
| typeof err.message === "string" && err.message ? err.message : err; | ||
| } | ||
| } else if (typeof err.message === "string" && err.message) { | ||
| message += err.message; | ||
| } else { | ||
| message += String(err); | ||
| } | ||
| } else { | ||
| message += String(err); | ||
| } | ||
| super(message); | ||
| /** @type {string} */ | ||
| this.name = "ModuleBuildError"; | ||
| this.details = details; | ||
| this.error = err; | ||
| } | ||
| /** | ||
| * Serializes this instance into the provided serializer context. | ||
| * @param {ObjectSerializerContext} context context | ||
| */ | ||
| serialize(context) { | ||
| const { write } = context; | ||
| write(this.error); | ||
| super.serialize(context); | ||
| } | ||
| /** | ||
| * Restores this instance from the provided deserializer context. | ||
| * @param {ObjectDeserializerContext} context context | ||
| */ | ||
| deserialize(context) { | ||
| const { read } = context; | ||
| this.error = read(); | ||
| super.deserialize(context); | ||
| } | ||
| } | ||
| makeSerializable(ModuleBuildError, "webpack/lib/ModuleBuildError"); | ||
| module.exports = ModuleBuildError; |
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| Author Tobias Koppers @sokra | ||
| */ | ||
| "use strict"; | ||
| const WebpackError = require("./WebpackError"); | ||
| /** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ | ||
| /** @typedef {import("./Module")} Module */ | ||
| /** @typedef {import("./ModuleBuildError").ErrorWithHideStack} ErrorWithHideStack */ | ||
| class ModuleDependencyError extends WebpackError { | ||
| /** | ||
| * Creates an instance of ModuleDependencyError. | ||
| * @param {Module} module module tied to dependency | ||
| * @param {ErrorWithHideStack} err error thrown | ||
| * @param {DependencyLocation} loc location of dependency | ||
| */ | ||
| constructor(module, err, loc) { | ||
| super(err.message); | ||
| /** @type {string} */ | ||
| this.name = "ModuleDependencyError"; | ||
| this.details = | ||
| err && !err.hideStack | ||
| ? /** @type {string} */ (err.stack).split("\n").slice(1).join("\n") | ||
| : undefined; | ||
| this.module = module; | ||
| this.loc = loc; | ||
| /** error is not (de)serialized, so it might be undefined after deserialization */ | ||
| this.error = err; | ||
| if (err && err.hideStack && err.stack) { | ||
| this.stack = /** @type {string} */ `${err.stack | ||
| .split("\n") | ||
| .slice(1) | ||
| .join("\n")}\n\n${this.stack}`; | ||
| } | ||
| } | ||
| } | ||
| module.exports = ModuleDependencyError; |
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| Author Tobias Koppers @sokra | ||
| */ | ||
| "use strict"; | ||
| const WebpackError = require("./WebpackError"); | ||
| const makeSerializable = require("./util/makeSerializable"); | ||
| /** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ | ||
| /** @typedef {import("./Module")} Module */ | ||
| /** @typedef {import("./ModuleDependencyError").ErrorWithHideStack} ErrorWithHideStack */ | ||
| class ModuleDependencyWarning extends WebpackError { | ||
| /** | ||
| * Creates an instance of ModuleDependencyWarning. | ||
| * @param {Module} module module tied to dependency | ||
| * @param {ErrorWithHideStack} err error thrown | ||
| * @param {DependencyLocation} loc location of dependency | ||
| */ | ||
| constructor(module, err, loc) { | ||
| super(err ? err.message : ""); | ||
| /** @type {string} */ | ||
| this.name = "ModuleDependencyWarning"; | ||
| this.details = | ||
| err && !err.hideStack | ||
| ? /** @type {string} */ (err.stack).split("\n").slice(1).join("\n") | ||
| : undefined; | ||
| this.module = module; | ||
| this.loc = loc; | ||
| /** error is not (de)serialized, so it might be undefined after deserialization */ | ||
| this.error = err; | ||
| if (err && err.hideStack && err.stack) { | ||
| this.stack = /** @type {string} */ `${err.stack | ||
| .split("\n") | ||
| .slice(1) | ||
| .join("\n")}\n\n${this.stack}`; | ||
| } | ||
| } | ||
| } | ||
| makeSerializable( | ||
| ModuleDependencyWarning, | ||
| "webpack/lib/ModuleDependencyWarning" | ||
| ); | ||
| module.exports = ModuleDependencyWarning; |
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| Author Tobias Koppers @sokra | ||
| */ | ||
| "use strict"; | ||
| const { cleanUp } = require("./ErrorHelpers"); | ||
| const WebpackError = require("./WebpackError"); | ||
| const makeSerializable = require("./util/makeSerializable"); | ||
| /** @typedef {import("./serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ | ||
| /** @typedef {import("./serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ | ||
| class ModuleError extends WebpackError { | ||
| /** | ||
| * @param {Error} err error thrown | ||
| * @param {{ from?: string | null }} info additional info | ||
| */ | ||
| constructor(err, { from = null } = {}) { | ||
| let message = "Module Error"; | ||
| message += from ? ` (from ${from}):\n` : ": "; | ||
| if (err && typeof err === "object" && err.message) { | ||
| message += err.message; | ||
| } else if (err) { | ||
| message += err; | ||
| } | ||
| super(message); | ||
| /** @type {string} */ | ||
| this.name = "ModuleError"; | ||
| /** @type {Error} */ | ||
| this.error = err; | ||
| /** @type {string | undefined} */ | ||
| this.details = | ||
| err && typeof err === "object" && err.stack | ||
| ? cleanUp(err.stack, this.message) | ||
| : undefined; | ||
| } | ||
| /** | ||
| * Serializes this instance into the provided serializer context. | ||
| * @param {ObjectSerializerContext} context context | ||
| */ | ||
| serialize(context) { | ||
| const { write } = context; | ||
| write(this.error); | ||
| super.serialize(context); | ||
| } | ||
| /** | ||
| * Restores this instance from the provided deserializer context. | ||
| * @param {ObjectDeserializerContext} context context | ||
| */ | ||
| deserialize(context) { | ||
| const { read } = context; | ||
| this.error = read(); | ||
| super.deserialize(context); | ||
| } | ||
| } | ||
| makeSerializable(ModuleError, "webpack/lib/ModuleError"); | ||
| module.exports = ModuleError; |
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| Author Tobias Koppers @sokra | ||
| */ | ||
| "use strict"; | ||
| const WebpackError = require("./WebpackError"); | ||
| /** @typedef {import("./Module")} Module */ | ||
| class ModuleHashingError extends WebpackError { | ||
| /** | ||
| * Create a new ModuleHashingError | ||
| * @param {Module} module related module | ||
| * @param {Error} error Original error | ||
| */ | ||
| constructor(module, error) { | ||
| super(); | ||
| /** @type {string} */ | ||
| this.name = "ModuleHashingError"; | ||
| this.error = error; | ||
| this.message = error.message; | ||
| this.details = error.stack; | ||
| this.module = module; | ||
| } | ||
| } | ||
| /** @type {typeof ModuleHashingError} */ | ||
| module.exports = ModuleHashingError; |
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| Author Tobias Koppers @sokra | ||
| */ | ||
| "use strict"; | ||
| const WebpackError = require("./WebpackError"); | ||
| /** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ | ||
| /** @typedef {import("./Module")} Module */ | ||
| const previouslyPolyfilledBuiltinModules = { | ||
| assert: "assert/", | ||
| buffer: "buffer/", | ||
| console: "console-browserify", | ||
| constants: "constants-browserify", | ||
| crypto: "crypto-browserify", | ||
| domain: "domain-browser", | ||
| events: "events/", | ||
| http: "stream-http", | ||
| https: "https-browserify", | ||
| os: "os-browserify/browser", | ||
| path: "path-browserify", | ||
| punycode: "punycode/", | ||
| process: "process/browser", | ||
| querystring: "querystring-es3", | ||
| stream: "stream-browserify", | ||
| _stream_duplex: "readable-stream/duplex", | ||
| _stream_passthrough: "readable-stream/passthrough", | ||
| _stream_readable: "readable-stream/readable", | ||
| _stream_transform: "readable-stream/transform", | ||
| _stream_writable: "readable-stream/writable", | ||
| string_decoder: "string_decoder/", | ||
| sys: "util/", | ||
| timers: "timers-browserify", | ||
| tty: "tty-browserify", | ||
| url: "url/", | ||
| util: "util/", | ||
| vm: "vm-browserify", | ||
| zlib: "browserify-zlib" | ||
| }; | ||
| class ModuleNotFoundError extends WebpackError { | ||
| /** | ||
| * Creates an instance of ModuleNotFoundError. | ||
| * @param {Module | null} module module tied to dependency | ||
| * @param {Error & { details?: string }} err error thrown | ||
| * @param {DependencyLocation} loc location of dependency | ||
| */ | ||
| constructor(module, err, loc) { | ||
| let message = `Module not found: ${err.toString()}`; | ||
| // TODO remove in webpack 6 | ||
| const match = err.message.match(/Can't resolve '([^']+)'/); | ||
| if (match) { | ||
| const request = match[1]; | ||
| const alias = | ||
| previouslyPolyfilledBuiltinModules[ | ||
| /** @type {keyof previouslyPolyfilledBuiltinModules} */ (request) | ||
| ]; | ||
| if (alias) { | ||
| const pathIndex = alias.indexOf("/"); | ||
| const dependency = pathIndex > 0 ? alias.slice(0, pathIndex) : alias; | ||
| message += | ||
| "\n\n" + | ||
| "BREAKING CHANGE: " + | ||
| "webpack < 5 used to include polyfills for node.js core modules by default.\n" + | ||
| "This is no longer the case. Verify if you need this module and configure a polyfill for it.\n\n"; | ||
| message += | ||
| "If you want to include a polyfill, you need to:\n" + | ||
| `\t- add a fallback 'resolve.fallback: { "${request}": require.resolve("${alias}") }'\n` + | ||
| `\t- install '${dependency}'\n`; | ||
| message += | ||
| "If you don't want to include a polyfill, you can use an empty module like this:\n" + | ||
| `\tresolve.fallback: { "${request}": false }`; | ||
| } | ||
| } | ||
| super(message); | ||
| /** @type {string} */ | ||
| this.name = "ModuleNotFoundError"; | ||
| this.details = err.details; | ||
| this.module = module; | ||
| this.error = err; | ||
| this.loc = loc; | ||
| } | ||
| } | ||
| module.exports = ModuleNotFoundError; |
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| Author Tobias Koppers @sokra | ||
| */ | ||
| "use strict"; | ||
| const WebpackError = require("./WebpackError"); | ||
| const makeSerializable = require("./util/makeSerializable"); | ||
| /** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ | ||
| /** @typedef {import("./Dependency").SourcePosition} SourcePosition */ | ||
| /** @typedef {import("./serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ | ||
| /** @typedef {import("./serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ | ||
| const WASM_HEADER = Buffer.from([0x00, 0x61, 0x73, 0x6d]); | ||
| class ModuleParseError extends WebpackError { | ||
| /** | ||
| * Creates an instance of ModuleParseError. | ||
| * @param {string | Buffer} source source code | ||
| * @param {Error & { loc?: SourcePosition }} err the parse error | ||
| * @param {string[]} loaders the loaders used | ||
| * @param {string} type module type | ||
| */ | ||
| constructor(source, err, loaders, type) { | ||
| let message = `Module parse failed: ${err && err.message}`; | ||
| /** @type {undefined | DependencyLocation} */ | ||
| let loc; | ||
| if ( | ||
| ((Buffer.isBuffer(source) && source.subarray(0, 4).equals(WASM_HEADER)) || | ||
| (typeof source === "string" && /^\0asm/.test(source))) && | ||
| !type.startsWith("webassembly") | ||
| ) { | ||
| message += | ||
| "\nThe module seem to be a WebAssembly module, but module is not flagged as WebAssembly module for webpack."; | ||
| message += | ||
| "\nBREAKING CHANGE: Since webpack 5 WebAssembly is not enabled by default and flagged as experimental feature."; | ||
| message += | ||
| "\nYou need to enable one of the WebAssembly experiments via 'experiments.asyncWebAssembly: true' (based on async modules) or 'experiments.syncWebAssembly: true' (like webpack 4, deprecated)."; | ||
| message += | ||
| "\nFor files that transpile to WebAssembly, make sure to set the module type in the 'module.rules' section of the config (e. g. 'type: \"webassembly/async\"')."; | ||
| } else if (!loaders) { | ||
| message += | ||
| "\nYou may need an appropriate loader to handle this file type. " + | ||
| "See https://webpack.js.org/concepts/loaders"; | ||
| } else if (loaders.length >= 1) { | ||
| message += `\nFile was processed with these loaders:${loaders | ||
| .map((loader) => `\n * ${loader}`) | ||
| .join("")}`; | ||
| message += | ||
| "\nYou may need an additional loader to handle the result of these loaders."; | ||
| } else { | ||
| message += | ||
| "\nYou may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders"; | ||
| } | ||
| if ( | ||
| err && | ||
| err.loc && | ||
| typeof err.loc === "object" && | ||
| typeof err.loc.line === "number" | ||
| ) { | ||
| const lineNumber = err.loc.line; | ||
| if ( | ||
| Buffer.isBuffer(source) || | ||
| // eslint-disable-next-line no-control-regex | ||
| /[\0\u0001\u0002\u0003\u0004\u0005\u0006\u0007]/.test(source) | ||
| ) { | ||
| // binary file | ||
| message += "\n(Source code omitted for this binary file)"; | ||
| } else { | ||
| const sourceLines = source.split(/\r?\n/); | ||
| const start = Math.max(0, lineNumber - 3); | ||
| const linesBefore = sourceLines.slice(start, lineNumber - 1); | ||
| const theLine = sourceLines[lineNumber - 1]; | ||
| const linesAfter = sourceLines.slice(lineNumber, lineNumber + 2); | ||
| message += `${linesBefore | ||
| .map((l) => `\n| ${l}`) | ||
| .join( | ||
| "" | ||
| )}\n> ${theLine}${linesAfter.map((l) => `\n| ${l}`).join("")}`; | ||
| } | ||
| loc = { start: err.loc }; | ||
| } else if (err && err.stack) { | ||
| message += `\n${err.stack}`; | ||
| } | ||
| super(message); | ||
| /** @type {string} */ | ||
| this.name = "ModuleParseError"; | ||
| this.loc = loc; | ||
| this.error = err; | ||
| } | ||
| /** | ||
| * Serializes this instance into the provided serializer context. | ||
| * @param {ObjectSerializerContext} context context | ||
| */ | ||
| serialize(context) { | ||
| const { write } = context; | ||
| write(this.error); | ||
| super.serialize(context); | ||
| } | ||
| /** | ||
| * Restores this instance from the provided deserializer context. | ||
| * @param {ObjectDeserializerContext} context context | ||
| */ | ||
| deserialize(context) { | ||
| const { read } = context; | ||
| this.error = read(); | ||
| super.deserialize(context); | ||
| } | ||
| } | ||
| makeSerializable(ModuleParseError, "webpack/lib/ModuleParseError"); | ||
| module.exports = ModuleParseError; |
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| Author Tobias Koppers @sokra | ||
| */ | ||
| "use strict"; | ||
| const WebpackError = require("./WebpackError"); | ||
| /** @typedef {import("./Module")} Module */ | ||
| class ModuleRestoreError extends WebpackError { | ||
| /** | ||
| * Creates an instance of ModuleRestoreError. | ||
| * @param {Module} module module tied to dependency | ||
| * @param {string | Error} err error thrown | ||
| */ | ||
| constructor(module, err) { | ||
| let message = "Module restore failed: "; | ||
| /** @type {string | undefined} */ | ||
| const details = undefined; | ||
| if (err !== null && typeof err === "object") { | ||
| if (typeof err.stack === "string" && err.stack) { | ||
| const stack = err.stack; | ||
| message += stack; | ||
| } else if (typeof err.message === "string" && err.message) { | ||
| message += err.message; | ||
| } else { | ||
| message += err; | ||
| } | ||
| } else { | ||
| message += String(err); | ||
| } | ||
| super(message); | ||
| /** @type {string} */ | ||
| this.name = "ModuleRestoreError"; | ||
| /** @type {string | undefined} */ | ||
| this.details = details; | ||
| this.module = module; | ||
| this.error = err; | ||
| } | ||
| } | ||
| /** @type {typeof ModuleRestoreError} */ | ||
| module.exports = ModuleRestoreError; |
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| Author Tobias Koppers @sokra | ||
| */ | ||
| "use strict"; | ||
| const WebpackError = require("./WebpackError"); | ||
| /** @typedef {import("./Module")} Module */ | ||
| class ModuleStoreError extends WebpackError { | ||
| /** | ||
| * Creates an instance of ModuleStoreError. | ||
| * @param {Module} module module tied to dependency | ||
| * @param {string | Error} err error thrown | ||
| */ | ||
| constructor(module, err) { | ||
| let message = "Module storing failed: "; | ||
| /** @type {string | undefined} */ | ||
| const details = undefined; | ||
| if (err !== null && typeof err === "object") { | ||
| if (typeof err.stack === "string" && err.stack) { | ||
| const stack = err.stack; | ||
| message += stack; | ||
| } else if (typeof err.message === "string" && err.message) { | ||
| message += err.message; | ||
| } else { | ||
| message += err; | ||
| } | ||
| } else { | ||
| message += String(err); | ||
| } | ||
| super(message); | ||
| /** @type {string} */ | ||
| this.name = "ModuleStoreError"; | ||
| this.details = /** @type {string | undefined} */ (details); | ||
| this.module = module; | ||
| this.error = err; | ||
| } | ||
| } | ||
| /** @type {typeof ModuleStoreError} */ | ||
| module.exports = ModuleStoreError; |
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| Author Tobias Koppers @sokra | ||
| */ | ||
| "use strict"; | ||
| const { cleanUp } = require("./ErrorHelpers"); | ||
| const WebpackError = require("./WebpackError"); | ||
| const makeSerializable = require("./util/makeSerializable"); | ||
| /** @typedef {import("./serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ | ||
| /** @typedef {import("./serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ | ||
| class ModuleWarning extends WebpackError { | ||
| /** | ||
| * Creates an instance of ModuleWarning. | ||
| * @param {Error} warning error thrown | ||
| * @param {{ from?: string | null }} info additional info | ||
| */ | ||
| constructor(warning, { from = null } = {}) { | ||
| let message = "Module Warning"; | ||
| message += from ? ` (from ${from}):\n` : ": "; | ||
| if (warning && typeof warning === "object" && warning.message) { | ||
| message += warning.message; | ||
| } else if (warning) { | ||
| message += String(warning); | ||
| } | ||
| super(message); | ||
| /** @type {string} */ | ||
| this.name = "ModuleWarning"; | ||
| this.warning = warning; | ||
| this.details = | ||
| warning && typeof warning === "object" && warning.stack | ||
| ? cleanUp(warning.stack, this.message) | ||
| : undefined; | ||
| } | ||
| /** | ||
| * Serializes this instance into the provided serializer context. | ||
| * @param {ObjectSerializerContext} context context | ||
| */ | ||
| serialize(context) { | ||
| const { write } = context; | ||
| write(this.warning); | ||
| super.serialize(context); | ||
| } | ||
| /** | ||
| * Restores this instance from the provided deserializer context. | ||
| * @param {ObjectDeserializerContext} context context | ||
| */ | ||
| deserialize(context) { | ||
| const { read } = context; | ||
| this.warning = read(); | ||
| super.deserialize(context); | ||
| } | ||
| } | ||
| makeSerializable(ModuleWarning, "webpack/lib/ModuleWarning"); | ||
| /** @type {typeof ModuleWarning} */ | ||
| module.exports = ModuleWarning; |
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| Author Ivan Kopeykin @vankop | ||
| */ | ||
| "use strict"; | ||
| const WebpackError = require("./WebpackError"); | ||
| const makeSerializable = require("./util/makeSerializable"); | ||
| /** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ | ||
| class NodeStuffInWebError extends WebpackError { | ||
| /** | ||
| * Creates an instance of NodeStuffInWebError. | ||
| * @param {DependencyLocation} loc loc | ||
| * @param {string} expression expression | ||
| * @param {string} description description | ||
| */ | ||
| constructor(loc, expression, description) { | ||
| super( | ||
| `${JSON.stringify( | ||
| expression | ||
| )} has been used, it will be undefined in next major version. | ||
| ${description}` | ||
| ); | ||
| /** @type {string} */ | ||
| this.name = "NodeStuffInWebError"; | ||
| this.loc = loc; | ||
| } | ||
| } | ||
| makeSerializable(NodeStuffInWebError, "webpack/lib/NodeStuffInWebError"); | ||
| module.exports = NodeStuffInWebError; |
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| Author Tobias Koppers @sokra | ||
| */ | ||
| "use strict"; | ||
| const WebpackError = require("./WebpackError"); | ||
| module.exports = class NoModeWarning extends WebpackError { | ||
| constructor() { | ||
| super(); | ||
| /** @type {string} */ | ||
| this.name = "NoModeWarning"; | ||
| this.message = | ||
| "configuration\n" + | ||
| "The 'mode' option has not been set, webpack will fallback to 'production' for this value.\n" + | ||
| "Set 'mode' option to 'development' or 'production' to enable defaults for each environment.\n" + | ||
| "You can also set it to 'none' to disable any default behavior. " + | ||
| "Learn more: https://webpack.js.org/configuration/mode/"; | ||
| } | ||
| }; |
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| Author Tobias Koppers @sokra | ||
| */ | ||
| "use strict"; | ||
| const { | ||
| JAVASCRIPT_MODULE_TYPE_AUTO, | ||
| JAVASCRIPT_MODULE_TYPE_DYNAMIC | ||
| } = require("./ModuleTypeConstants"); | ||
| const RuntimeGlobals = require("./RuntimeGlobals"); | ||
| const ConstDependency = require("./dependencies/ConstDependency"); | ||
| const { | ||
| toConstantDependency | ||
| } = require("./javascript/JavascriptParserHelpers"); | ||
| /** @typedef {import("../declarations/WebpackOptions").JavascriptParserOptions} JavascriptParserOptions */ | ||
| /** @typedef {import("./Compiler")} Compiler */ | ||
| /** @typedef {import("./javascript/JavascriptParser")} JavascriptParser */ | ||
| const PLUGIN_NAME = "RequireJsStuffPlugin"; | ||
| module.exports = class RequireJsStuffPlugin { | ||
| /** | ||
| * Applies the plugin by registering its hooks on the compiler. | ||
| * @param {Compiler} compiler the compiler instance | ||
| * @returns {void} | ||
| */ | ||
| apply(compiler) { | ||
| compiler.hooks.compilation.tap( | ||
| PLUGIN_NAME, | ||
| (compilation, { normalModuleFactory }) => { | ||
| compilation.dependencyTemplates.set( | ||
| ConstDependency, | ||
| new ConstDependency.Template() | ||
| ); | ||
| /** | ||
| * Handles the hook callback for this code path. | ||
| * @param {JavascriptParser} parser the parser | ||
| * @param {JavascriptParserOptions} parserOptions options | ||
| * @returns {void} | ||
| */ | ||
| const handler = (parser, parserOptions) => { | ||
| if ( | ||
| parserOptions.requireJs === undefined || | ||
| !parserOptions.requireJs | ||
| ) { | ||
| return; | ||
| } | ||
| parser.hooks.call | ||
| .for("require.config") | ||
| .tap(PLUGIN_NAME, toConstantDependency(parser, "undefined")); | ||
| parser.hooks.call | ||
| .for("requirejs.config") | ||
| .tap(PLUGIN_NAME, toConstantDependency(parser, "undefined")); | ||
| parser.hooks.expression | ||
| .for("require.version") | ||
| .tap( | ||
| PLUGIN_NAME, | ||
| toConstantDependency(parser, JSON.stringify("0.0.0")) | ||
| ); | ||
| parser.hooks.expression | ||
| .for("requirejs.onError") | ||
| .tap( | ||
| PLUGIN_NAME, | ||
| toConstantDependency( | ||
| parser, | ||
| RuntimeGlobals.uncaughtErrorHandler, | ||
| [RuntimeGlobals.uncaughtErrorHandler] | ||
| ) | ||
| ); | ||
| }; | ||
| normalModuleFactory.hooks.parser | ||
| .for(JAVASCRIPT_MODULE_TYPE_AUTO) | ||
| .tap(PLUGIN_NAME, handler); | ||
| normalModuleFactory.hooks.parser | ||
| .for(JAVASCRIPT_MODULE_TYPE_DYNAMIC) | ||
| .tap(PLUGIN_NAME, handler); | ||
| } | ||
| ); | ||
| } | ||
| }; |
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| Author Sean Larkin @thelarkinn | ||
| */ | ||
| "use strict"; | ||
| /** | ||
| * Returns the formatted size. | ||
| * @param {number=} size the size in bytes | ||
| * @returns {string} the formatted size | ||
| */ | ||
| module.exports.formatSize = (size) => { | ||
| if (typeof size !== "number" || Number.isNaN(size) === true) { | ||
| return "unknown size"; | ||
| } | ||
| if (size <= 0) { | ||
| return "0 bytes"; | ||
| } | ||
| const abbreviations = ["bytes", "KiB", "MiB", "GiB"]; | ||
| const index = Math.floor(Math.log(size) / Math.log(1024)); | ||
| return `${Number((size / 1024 ** index).toPrecision(3))} ${abbreviations[index]}`; | ||
| }; |
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| Author Ivan Kopeykin @vankop | ||
| */ | ||
| "use strict"; | ||
| const WebpackError = require("./WebpackError"); | ||
| const makeSerializable = require("./util/makeSerializable"); | ||
| /** | ||
| * Error raised when webpack encounters a resource URI scheme that no installed | ||
| * plugin knows how to read. | ||
| */ | ||
| class UnhandledSchemeError extends WebpackError { | ||
| /** | ||
| * Creates an error explaining that the current resource scheme is not | ||
| * supported by the active plugin set. | ||
| * @param {string} scheme scheme | ||
| * @param {string} resource resource | ||
| */ | ||
| constructor(scheme, resource) { | ||
| super( | ||
| `Reading from "${resource}" is not handled by plugins (Unhandled scheme).` + | ||
| '\nWebpack supports "data:" and "file:" URIs by default.' + | ||
| `\nYou may need an additional plugin to handle "${scheme}:" URIs.` | ||
| ); | ||
| this.file = resource; | ||
| /** @type {string} */ | ||
| this.name = "UnhandledSchemeError"; | ||
| } | ||
| } | ||
| makeSerializable( | ||
| UnhandledSchemeError, | ||
| "webpack/lib/UnhandledSchemeError", | ||
| "UnhandledSchemeError" | ||
| ); | ||
| module.exports = UnhandledSchemeError; |
| /* | ||
| MIT License http://www.opensource.org/licenses/mit-license.php | ||
| Author Tobias Koppers @sokra | ||
| */ | ||
| "use strict"; | ||
| const WebpackError = require("./WebpackError"); | ||
| const makeSerializable = require("./util/makeSerializable"); | ||
| /** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ | ||
| class UnsupportedFeatureWarning extends WebpackError { | ||
| /** | ||
| * Creates an instance of UnsupportedFeatureWarning. | ||
| * @param {string} message description of warning | ||
| * @param {DependencyLocation} loc location start and end positions of the module | ||
| */ | ||
| constructor(message, loc) { | ||
| super(message); | ||
| /** @type {string} */ | ||
| this.name = "UnsupportedFeatureWarning"; | ||
| /** @type {DependencyLocation} */ | ||
| this.loc = loc; | ||
| /** @type {boolean} */ | ||
| this.hideStack = true; | ||
| } | ||
| } | ||
| makeSerializable( | ||
| UnsupportedFeatureWarning, | ||
| "webpack/lib/UnsupportedFeatureWarning" | ||
| ); | ||
| module.exports = UnsupportedFeatureWarning; |
| /* | ||
| * This file was automatically generated. | ||
| * DO NOT MODIFY BY HAND. | ||
| * Run `yarn fix:special` to update | ||
| */ | ||
| declare const check: (options: import("../../declarations/plugins/DllPlugin").DllPluginOptions) => boolean; | ||
| export = check; |
| /* | ||
| * This file was automatically generated. | ||
| * DO NOT MODIFY BY HAND. | ||
| * Run `yarn fix:special` to update | ||
| */ | ||
| "use strict";function r(e,{instancePath:t="",parentData:o,parentDataProperty:n,rootData:a=e}={}){if(!e||"object"!=typeof e||Array.isArray(e))return r.errors=[{params:{type:"object"}}],!1;{let t;if(void 0===e.path&&(t="path"))return r.errors=[{params:{missingProperty:t}}],!1;{const t=0;for(const t in e)if("context"!==t&&"entryOnly"!==t&&"format"!==t&&"name"!==t&&"path"!==t&&"type"!==t)return r.errors=[{params:{additionalProperty:t}}],!1;if(0===t){if(void 0!==e.context){let t=e.context;const o=0;if(0===o){if("string"!=typeof t)return r.errors=[{params:{type:"string"}}],!1;if(t.length<1)return r.errors=[{params:{}}],!1}var s=0===o}else s=!0;if(s){if(void 0!==e.entryOnly){const t=0;if("boolean"!=typeof e.entryOnly)return r.errors=[{params:{type:"boolean"}}],!1;s=0===t}else s=!0;if(s){if(void 0!==e.format){const t=0;if("boolean"!=typeof e.format)return r.errors=[{params:{type:"boolean"}}],!1;s=0===t}else s=!0;if(s){if(void 0!==e.name){let t=e.name;const o=0;if(0===o){if("string"!=typeof t)return r.errors=[{params:{type:"string"}}],!1;if(t.length<1)return r.errors=[{params:{}}],!1}s=0===o}else s=!0;if(s){if(void 0!==e.path){let t=e.path;const o=0;if(0===o){if("string"!=typeof t)return r.errors=[{params:{type:"string"}}],!1;if(t.length<1)return r.errors=[{params:{}}],!1}s=0===o}else s=!0;if(s)if(void 0!==e.type){let t=e.type;const o=0;if(0===o){if("string"!=typeof t)return r.errors=[{params:{type:"string"}}],!1;if(t.length<1)return r.errors=[{params:{}}],!1}s=0===o}else s=!0}}}}}}}return r.errors=null,!0}module.exports=r,module.exports.default=r; |
| { | ||
| "title": "DllPluginOptions", | ||
| "type": "object", | ||
| "additionalProperties": false, | ||
| "properties": { | ||
| "context": { | ||
| "description": "Context of requests in the manifest file (defaults to the webpack context).", | ||
| "type": "string", | ||
| "minLength": 1 | ||
| }, | ||
| "entryOnly": { | ||
| "description": "If true, only entry points will be exposed (default: true).", | ||
| "type": "boolean" | ||
| }, | ||
| "format": { | ||
| "description": "If true, manifest json file (output) will be formatted.", | ||
| "type": "boolean" | ||
| }, | ||
| "name": { | ||
| "description": "Name of the exposed dll function (external name, use value of 'output.library').", | ||
| "type": "string", | ||
| "minLength": 1 | ||
| }, | ||
| "path": { | ||
| "description": "Absolute path to the manifest json file (output).", | ||
| "type": "string", | ||
| "minLength": 1 | ||
| }, | ||
| "type": { | ||
| "description": "Type of the dll bundle (external type, use value of 'output.libraryTarget').", | ||
| "type": "string", | ||
| "minLength": 1 | ||
| } | ||
| }, | ||
| "required": ["path"] | ||
| } |
| /* | ||
| * This file was automatically generated. | ||
| * DO NOT MODIFY BY HAND. | ||
| * Run `yarn fix:special` to update | ||
| */ | ||
| declare const check: (options: import("../../declarations/plugins/DllReferencePlugin").DllReferencePluginOptions) => boolean; | ||
| export = check; |
| /* | ||
| * This file was automatically generated. | ||
| * DO NOT MODIFY BY HAND. | ||
| * Run `yarn fix:special` to update | ||
| */ | ||
| const s=/^(?:[A-Za-z]:[\\/]|\\\\|\/)/;function t(s,{instancePath:e="",parentData:n,parentDataProperty:l,rootData:o=s}={}){let r=null,i=0;if(0===i){if(!s||"object"!=typeof s||Array.isArray(s))return t.errors=[{params:{type:"object"}}],!1;{let e;if(void 0===s.content&&(e="content"))return t.errors=[{params:{missingProperty:e}}],!1;{const e=i;for(const e in s)if("content"!==e&&"name"!==e&&"type"!==e)return t.errors=[{params:{additionalProperty:e}}],!1;if(e===i){if(void 0!==s.content){let e=s.content;const n=i,l=i;let o=!1,f=null;const m=i;if(i==i)if(e&&"object"==typeof e&&!Array.isArray(e))if(Object.keys(e).length<1){const s={params:{limit:1}};null===r?r=[s]:r.push(s),i++}else for(const s in e){let t=e[s];const n=i;if(i===n)if(t&&"object"==typeof t&&!Array.isArray(t)){let s;if(void 0===t.id&&(s="id")){const t={params:{missingProperty:s}};null===r?r=[t]:r.push(t),i++}else{const s=i;for(const s in t)if("buildMeta"!==s&&"exports"!==s&&"id"!==s){const t={params:{additionalProperty:s}};null===r?r=[t]:r.push(t),i++;break}if(s===i){if(void 0!==t.buildMeta){let s=t.buildMeta;const e=i;if(!s||"object"!=typeof s||Array.isArray(s)){const s={params:{type:"object"}};null===r?r=[s]:r.push(s),i++}var a=e===i}else a=!0;if(a){if(void 0!==t.exports){let s=t.exports;const e=i,n=i;let l=!1;const o=i;if(i===o)if(Array.isArray(s)){const t=s.length;for(let e=0;e<t;e++){let t=s[e];const n=i;if(i===n)if("string"==typeof t){if(t.length<1){const s={params:{}};null===r?r=[s]:r.push(s),i++}}else{const s={params:{type:"string"}};null===r?r=[s]:r.push(s),i++}if(n!==i)break}}else{const s={params:{type:"array"}};null===r?r=[s]:r.push(s),i++}var p=o===i;if(l=l||p,!l){const t=i;if(!0!==s){const s={params:{}};null===r?r=[s]:r.push(s),i++}p=t===i,l=l||p}if(l)i=n,null!==r&&(n?r.length=n:r=null);else{const s={params:{}};null===r?r=[s]:r.push(s),i++}a=e===i}else a=!0;if(a)if(void 0!==t.id){let s=t.id;const e=i,n=i;let l=!1;const o=i;if("number"!=typeof s){const s={params:{type:"number"}};null===r?r=[s]:r.push(s),i++}var u=o===i;if(l=l||u,!l){const t=i;if(i===t)if("string"==typeof s){if(s.length<1){const s={params:{}};null===r?r=[s]:r.push(s),i++}}else{const s={params:{type:"string"}};null===r?r=[s]:r.push(s),i++}u=t===i,l=l||u}if(l)i=n,null!==r&&(n?r.length=n:r=null);else{const s={params:{}};null===r?r=[s]:r.push(s),i++}a=e===i}else a=!0}}}}else{const s={params:{type:"object"}};null===r?r=[s]:r.push(s),i++}if(n!==i)break}else{const s={params:{type:"object"}};null===r?r=[s]:r.push(s),i++}if(m===i&&(o=!0,f=0),!o){const s={params:{passingSchemas:f}};return null===r?r=[s]:r.push(s),i++,t.errors=r,!1}i=l,null!==r&&(l?r.length=l:r=null);var c=n===i}else c=!0;if(c){if(void 0!==s.name){let e=s.name;const n=i;if(i===n){if("string"!=typeof e)return t.errors=[{params:{type:"string"}}],!1;if(e.length<1)return t.errors=[{params:{}}],!1}c=n===i}else c=!0;if(c)if(void 0!==s.type){let e=s.type;const n=i,l=i;let o=!1,a=null;const p=i;if("var"!==e&&"assign"!==e&&"this"!==e&&"window"!==e&&"global"!==e&&"commonjs"!==e&&"commonjs2"!==e&&"commonjs-module"!==e&&"amd"!==e&&"amd-require"!==e&&"umd"!==e&&"umd2"!==e&&"jsonp"!==e&&"system"!==e){const s={params:{}};null===r?r=[s]:r.push(s),i++}if(p===i&&(o=!0,a=0),!o){const s={params:{passingSchemas:a}};return null===r?r=[s]:r.push(s),i++,t.errors=r,!1}i=l,null!==r&&(l?r.length=l:r=null),c=n===i}else c=!0}}}}}return t.errors=r,0===i}function e(n,{instancePath:l="",parentData:o,parentDataProperty:r,rootData:i=n}={}){let a=null,p=0;const u=p;let c=!1;const f=p;if(p===f)if(n&&"object"==typeof n&&!Array.isArray(n)){let e;if(void 0===n.manifest&&(e="manifest")){const s={params:{missingProperty:e}};null===a?a=[s]:a.push(s),p++}else{const e=p;for(const s in n)if("context"!==s&&"extensions"!==s&&"manifest"!==s&&"name"!==s&&"scope"!==s&&"sourceType"!==s&&"type"!==s){const t={params:{additionalProperty:s}};null===a?a=[t]:a.push(t),p++;break}if(e===p){if(void 0!==n.context){let t=n.context;const e=p;if(p===e)if("string"==typeof t){if(t.includes("!")||!0!==s.test(t)){const s={params:{}};null===a?a=[s]:a.push(s),p++}}else{const s={params:{type:"string"}};null===a?a=[s]:a.push(s),p++}var m=e===p}else m=!0;if(m){if(void 0!==n.extensions){let s=n.extensions;const t=p;if(p===t)if(Array.isArray(s)){const t=s.length;for(let e=0;e<t;e++){const t=p;if("string"!=typeof s[e]){const s={params:{type:"string"}};null===a?a=[s]:a.push(s),p++}if(t!==p)break}}else{const s={params:{type:"array"}};null===a?a=[s]:a.push(s),p++}m=t===p}else m=!0;if(m){if(void 0!==n.manifest){let e=n.manifest;const o=p,r=p;let u=!1;const c=p;if(p===c)if("string"==typeof e){if(e.includes("!")||!0!==s.test(e)){const s={params:{}};null===a?a=[s]:a.push(s),p++}}else{const s={params:{type:"string"}};null===a?a=[s]:a.push(s),p++}var y=c===p;if(u=u||y,!u){const s=p;t(e,{instancePath:l+"/manifest",parentData:n,parentDataProperty:"manifest",rootData:i})||(a=null===a?t.errors:a.concat(t.errors),p=a.length),y=s===p,u=u||y}if(u)p=r,null!==a&&(r?a.length=r:a=null);else{const s={params:{}};null===a?a=[s]:a.push(s),p++}m=o===p}else m=!0;if(m){if(void 0!==n.name){let s=n.name;const t=p;if(p===t)if("string"==typeof s){if(s.length<1){const s={params:{}};null===a?a=[s]:a.push(s),p++}}else{const s={params:{type:"string"}};null===a?a=[s]:a.push(s),p++}m=t===p}else m=!0;if(m){if(void 0!==n.scope){let s=n.scope;const t=p;if(p===t)if("string"==typeof s){if(s.length<1){const s={params:{}};null===a?a=[s]:a.push(s),p++}}else{const s={params:{type:"string"}};null===a?a=[s]:a.push(s),p++}m=t===p}else m=!0;if(m){if(void 0!==n.sourceType){let s=n.sourceType;const t=p,e=p;let l=!1,o=null;const r=p;if("var"!==s&&"assign"!==s&&"this"!==s&&"window"!==s&&"global"!==s&&"commonjs"!==s&&"commonjs2"!==s&&"commonjs-module"!==s&&"amd"!==s&&"amd-require"!==s&&"umd"!==s&&"umd2"!==s&&"jsonp"!==s&&"system"!==s){const s={params:{}};null===a?a=[s]:a.push(s),p++}if(r===p&&(l=!0,o=0),l)p=e,null!==a&&(e?a.length=e:a=null);else{const s={params:{passingSchemas:o}};null===a?a=[s]:a.push(s),p++}m=t===p}else m=!0;if(m)if(void 0!==n.type){let s=n.type;const t=p;if("require"!==s&&"object"!==s){const s={params:{}};null===a?a=[s]:a.push(s),p++}m=t===p}else m=!0}}}}}}}}else{const s={params:{type:"object"}};null===a?a=[s]:a.push(s),p++}var h=f===p;if(c=c||h,!c){const t=p;if(p===t)if(n&&"object"==typeof n&&!Array.isArray(n)){let t;if(void 0===n.content&&(t="content")||void 0===n.name&&(t="name")){const s={params:{missingProperty:t}};null===a?a=[s]:a.push(s),p++}else{const t=p;for(const s in n)if("content"!==s&&"context"!==s&&"extensions"!==s&&"name"!==s&&"scope"!==s&&"sourceType"!==s&&"type"!==s){const t={params:{additionalProperty:s}};null===a?a=[t]:a.push(t),p++;break}if(t===p){if(void 0!==n.content){let s=n.content;const t=p,e=p;let l=!1,o=null;const r=p;if(p==p)if(s&&"object"==typeof s&&!Array.isArray(s))if(Object.keys(s).length<1){const s={params:{limit:1}};null===a?a=[s]:a.push(s),p++}else for(const t in s){let e=s[t];const n=p;if(p===n)if(e&&"object"==typeof e&&!Array.isArray(e)){let s;if(void 0===e.id&&(s="id")){const t={params:{missingProperty:s}};null===a?a=[t]:a.push(t),p++}else{const s=p;for(const s in e)if("buildMeta"!==s&&"exports"!==s&&"id"!==s){const t={params:{additionalProperty:s}};null===a?a=[t]:a.push(t),p++;break}if(s===p){if(void 0!==e.buildMeta){let s=e.buildMeta;const t=p;if(!s||"object"!=typeof s||Array.isArray(s)){const s={params:{type:"object"}};null===a?a=[s]:a.push(s),p++}var d=t===p}else d=!0;if(d){if(void 0!==e.exports){let s=e.exports;const t=p,n=p;let l=!1;const o=p;if(p===o)if(Array.isArray(s)){const t=s.length;for(let e=0;e<t;e++){let t=s[e];const n=p;if(p===n)if("string"==typeof t){if(t.length<1){const s={params:{}};null===a?a=[s]:a.push(s),p++}}else{const s={params:{type:"string"}};null===a?a=[s]:a.push(s),p++}if(n!==p)break}}else{const s={params:{type:"array"}};null===a?a=[s]:a.push(s),p++}var g=o===p;if(l=l||g,!l){const t=p;if(!0!==s){const s={params:{}};null===a?a=[s]:a.push(s),p++}g=t===p,l=l||g}if(l)p=n,null!==a&&(n?a.length=n:a=null);else{const s={params:{}};null===a?a=[s]:a.push(s),p++}d=t===p}else d=!0;if(d)if(void 0!==e.id){let s=e.id;const t=p,n=p;let l=!1;const o=p;if("number"!=typeof s){const s={params:{type:"number"}};null===a?a=[s]:a.push(s),p++}var b=o===p;if(l=l||b,!l){const t=p;if(p===t)if("string"==typeof s){if(s.length<1){const s={params:{}};null===a?a=[s]:a.push(s),p++}}else{const s={params:{type:"string"}};null===a?a=[s]:a.push(s),p++}b=t===p,l=l||b}if(l)p=n,null!==a&&(n?a.length=n:a=null);else{const s={params:{}};null===a?a=[s]:a.push(s),p++}d=t===p}else d=!0}}}}else{const s={params:{type:"object"}};null===a?a=[s]:a.push(s),p++}if(n!==p)break}else{const s={params:{type:"object"}};null===a?a=[s]:a.push(s),p++}if(r===p&&(l=!0,o=0),l)p=e,null!==a&&(e?a.length=e:a=null);else{const s={params:{passingSchemas:o}};null===a?a=[s]:a.push(s),p++}var v=t===p}else v=!0;if(v){if(void 0!==n.context){let t=n.context;const e=p;if(p===e)if("string"==typeof t){if(t.includes("!")||!0!==s.test(t)){const s={params:{}};null===a?a=[s]:a.push(s),p++}}else{const s={params:{type:"string"}};null===a?a=[s]:a.push(s),p++}v=e===p}else v=!0;if(v){if(void 0!==n.extensions){let s=n.extensions;const t=p;if(p===t)if(Array.isArray(s)){const t=s.length;for(let e=0;e<t;e++){const t=p;if("string"!=typeof s[e]){const s={params:{type:"string"}};null===a?a=[s]:a.push(s),p++}if(t!==p)break}}else{const s={params:{type:"array"}};null===a?a=[s]:a.push(s),p++}v=t===p}else v=!0;if(v){if(void 0!==n.name){let s=n.name;const t=p;if(p===t)if("string"==typeof s){if(s.length<1){const s={params:{}};null===a?a=[s]:a.push(s),p++}}else{const s={params:{type:"string"}};null===a?a=[s]:a.push(s),p++}v=t===p}else v=!0;if(v){if(void 0!==n.scope){let s=n.scope;const t=p;if(p===t)if("string"==typeof s){if(s.length<1){const s={params:{}};null===a?a=[s]:a.push(s),p++}}else{const s={params:{type:"string"}};null===a?a=[s]:a.push(s),p++}v=t===p}else v=!0;if(v){if(void 0!==n.sourceType){let s=n.sourceType;const t=p,e=p;let l=!1,o=null;const r=p;if("var"!==s&&"assign"!==s&&"this"!==s&&"window"!==s&&"global"!==s&&"commonjs"!==s&&"commonjs2"!==s&&"commonjs-module"!==s&&"amd"!==s&&"amd-require"!==s&&"umd"!==s&&"umd2"!==s&&"jsonp"!==s&&"system"!==s){const s={params:{}};null===a?a=[s]:a.push(s),p++}if(r===p&&(l=!0,o=0),l)p=e,null!==a&&(e?a.length=e:a=null);else{const s={params:{passingSchemas:o}};null===a?a=[s]:a.push(s),p++}v=t===p}else v=!0;if(v)if(void 0!==n.type){let s=n.type;const t=p;if("require"!==s&&"object"!==s){const s={params:{}};null===a?a=[s]:a.push(s),p++}v=t===p}else v=!0}}}}}}}}else{const s={params:{type:"object"}};null===a?a=[s]:a.push(s),p++}h=t===p,c=c||h}if(!c){const s={params:{}};return null===a?a=[s]:a.push(s),p++,e.errors=a,!1}return p=u,null!==a&&(u?a.length=u:a=null),e.errors=a,0===p}module.exports=e,module.exports.default=e; |
| { | ||
| "definitions": { | ||
| "DllReferencePluginOptionsContent": { | ||
| "description": "The mappings from request to module info.", | ||
| "type": "object", | ||
| "additionalProperties": { | ||
| "description": "Module info.", | ||
| "type": "object", | ||
| "additionalProperties": false, | ||
| "properties": { | ||
| "buildMeta": { | ||
| "description": "Meta information about the module.", | ||
| "type": "object" | ||
| }, | ||
| "exports": { | ||
| "description": "Information about the provided exports of the module.", | ||
| "anyOf": [ | ||
| { | ||
| "description": "List of provided exports of the module.", | ||
| "type": "array", | ||
| "items": { | ||
| "description": "Name of the export.", | ||
| "type": "string", | ||
| "minLength": 1 | ||
| } | ||
| }, | ||
| { | ||
| "description": "Exports unknown/dynamic.", | ||
| "enum": [true] | ||
| } | ||
| ] | ||
| }, | ||
| "id": { | ||
| "description": "Module ID.", | ||
| "anyOf": [ | ||
| { | ||
| "type": "number" | ||
| }, | ||
| { | ||
| "type": "string", | ||
| "minLength": 1 | ||
| } | ||
| ] | ||
| } | ||
| }, | ||
| "required": ["id"] | ||
| }, | ||
| "minProperties": 1 | ||
| }, | ||
| "DllReferencePluginOptionsManifest": { | ||
| "description": "An object containing content, name and type.", | ||
| "type": "object", | ||
| "additionalProperties": false, | ||
| "properties": { | ||
| "content": { | ||
| "description": "The mappings from request to module info.", | ||
| "oneOf": [ | ||
| { | ||
| "$ref": "#/definitions/DllReferencePluginOptionsContent" | ||
| } | ||
| ] | ||
| }, | ||
| "name": { | ||
| "description": "The name where the dll is exposed (external name).", | ||
| "type": "string", | ||
| "minLength": 1 | ||
| }, | ||
| "type": { | ||
| "description": "The type how the dll is exposed (external type).", | ||
| "oneOf": [ | ||
| { | ||
| "$ref": "#/definitions/DllReferencePluginOptionsSourceType" | ||
| } | ||
| ] | ||
| } | ||
| }, | ||
| "required": ["content"] | ||
| }, | ||
| "DllReferencePluginOptionsSourceType": { | ||
| "description": "The type how the dll is exposed (external type).", | ||
| "enum": [ | ||
| "var", | ||
| "assign", | ||
| "this", | ||
| "window", | ||
| "global", | ||
| "commonjs", | ||
| "commonjs2", | ||
| "commonjs-module", | ||
| "amd", | ||
| "amd-require", | ||
| "umd", | ||
| "umd2", | ||
| "jsonp", | ||
| "system" | ||
| ] | ||
| } | ||
| }, | ||
| "title": "DllReferencePluginOptions", | ||
| "anyOf": [ | ||
| { | ||
| "type": "object", | ||
| "additionalProperties": false, | ||
| "properties": { | ||
| "context": { | ||
| "description": "Context of requests in the manifest (or content property) as absolute path.", | ||
| "type": "string", | ||
| "absolutePath": true | ||
| }, | ||
| "extensions": { | ||
| "description": "Extensions used to resolve modules in the dll bundle (only used when using 'scope').", | ||
| "type": "array", | ||
| "items": { | ||
| "description": "An extension.", | ||
| "type": "string" | ||
| } | ||
| }, | ||
| "manifest": { | ||
| "description": "An object containing content and name or a string to the absolute path of the JSON manifest to be loaded upon compilation.", | ||
| "anyOf": [ | ||
| { | ||
| "type": "string", | ||
| "absolutePath": true | ||
| }, | ||
| { | ||
| "$ref": "#/definitions/DllReferencePluginOptionsManifest" | ||
| } | ||
| ] | ||
| }, | ||
| "name": { | ||
| "description": "The name where the dll is exposed (external name, defaults to manifest.name).", | ||
| "type": "string", | ||
| "minLength": 1 | ||
| }, | ||
| "scope": { | ||
| "description": "Prefix which is used for accessing the content of the dll.", | ||
| "type": "string", | ||
| "minLength": 1 | ||
| }, | ||
| "sourceType": { | ||
| "description": "How the dll is exposed (libraryTarget, defaults to manifest.type).", | ||
| "oneOf": [ | ||
| { | ||
| "$ref": "#/definitions/DllReferencePluginOptionsSourceType" | ||
| } | ||
| ] | ||
| }, | ||
| "type": { | ||
| "description": "The way how the export of the dll bundle is used.", | ||
| "enum": ["require", "object"] | ||
| } | ||
| }, | ||
| "required": ["manifest"] | ||
| }, | ||
| { | ||
| "type": "object", | ||
| "additionalProperties": false, | ||
| "properties": { | ||
| "content": { | ||
| "description": "The mappings from request to module info.", | ||
| "oneOf": [ | ||
| { | ||
| "$ref": "#/definitions/DllReferencePluginOptionsContent" | ||
| } | ||
| ] | ||
| }, | ||
| "context": { | ||
| "description": "Context of requests in the manifest (or content property) as absolute path.", | ||
| "type": "string", | ||
| "absolutePath": true | ||
| }, | ||
| "extensions": { | ||
| "description": "Extensions used to resolve modules in the dll bundle (only used when using 'scope').", | ||
| "type": "array", | ||
| "items": { | ||
| "description": "An extension.", | ||
| "type": "string" | ||
| } | ||
| }, | ||
| "name": { | ||
| "description": "The name where the dll is exposed (external name).", | ||
| "type": "string", | ||
| "minLength": 1 | ||
| }, | ||
| "scope": { | ||
| "description": "Prefix which is used for accessing the content of the dll.", | ||
| "type": "string", | ||
| "minLength": 1 | ||
| }, | ||
| "sourceType": { | ||
| "description": "How the dll is exposed (libraryTarget).", | ||
| "oneOf": [ | ||
| { | ||
| "$ref": "#/definitions/DllReferencePluginOptionsSourceType" | ||
| } | ||
| ] | ||
| }, | ||
| "type": { | ||
| "description": "The way how the export of the dll bundle is used.", | ||
| "enum": ["require", "object"] | ||
| } | ||
| }, | ||
| "required": ["content", "name"] | ||
| } | ||
| ] | ||
| } |
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Network access
Supply chain riskThis module accesses the network.
Found 4 instances in 1 package
Shell access
Supply chain riskThis module accesses the system shell. Accessing the system shell increases the risk of executing arbitrary code.
Found 1 instance in 1 package
Uses eval
Supply chain riskPackage uses dynamic code execution (e.g., eval()), which is a dangerous practice. This can prevent the code from running in certain environments and increases the risk that the code may contain exploits or malicious behavior.
Found 2 instances in 1 package
Debug access
Supply chain riskUses debug, reflection and dynamic code execution features.
Found 3 instances in 1 package
Dynamic require
Supply chain riskDynamic require can indicate the package is performing dangerous or unsafe dynamic code execution.
Found 1 instance in 1 package
Environment variable access
Supply chain riskPackage accesses environment variables, which may be a sign of credential stuffing or data theft.
Found 5 instances in 1 package
Filesystem access
Supply chain riskAccesses the file system, and could potentially read sensitive data.
Found 1 instance in 1 package
AI-detected potential code anomaly
Supply chain riskAI has identified unusual behaviors that may pose a security risk.
Found 2 instances in 1 package
Long strings
Supply chain riskContains long string literals, which may be a sign of obfuscated or packed code.
Found 1 instance in 1 package
Minified code
QualityThis package contains minified code. This may be harmless in some cases where minified code is included in packaged libraries, however packages on npm should not minify code.
Found 2 instances in 1 package
URL strings
Supply chain riskPackage contains fragments of external URLs or IP addresses, which the package may be accessing at runtime.
Found 1 instance in 1 package
Network access
Supply chain riskThis module accesses the network.
Found 4 instances in 1 package
Shell access
Supply chain riskThis module accesses the system shell. Accessing the system shell increases the risk of executing arbitrary code.
Found 1 instance in 1 package
Uses eval
Supply chain riskPackage uses dynamic code execution (e.g., eval()), which is a dangerous practice. This can prevent the code from running in certain environments and increases the risk that the code may contain exploits or malicious behavior.
Found 2 instances in 1 package
Debug access
Supply chain riskUses debug, reflection and dynamic code execution features.
Found 3 instances in 1 package
Dynamic require
Supply chain riskDynamic require can indicate the package is performing dangerous or unsafe dynamic code execution.
Found 1 instance in 1 package
Environment variable access
Supply chain riskPackage accesses environment variables, which may be a sign of credential stuffing or data theft.
Found 5 instances in 1 package
Filesystem access
Supply chain riskAccesses the file system, and could potentially read sensitive data.
Found 1 instance in 1 package
AI-detected potential code anomaly
Supply chain riskAI has identified unusual behaviors that may pose a security risk.
Found 1 instance in 1 package
Long strings
Supply chain riskContains long string literals, which may be a sign of obfuscated or packed code.
Found 1 instance in 1 package
URL strings
Supply chain riskPackage contains fragments of external URLs or IP addresses, which the package may be accessing at runtime.
Found 1 instance in 1 package
6478083
5.76%23
-4.17%729
2.53%185132
5.29%88
1.15%38
5.56%360
28.57%- Removed
- Removed
- Removed
Updated
Updated
Updated
Updated
Updated