webpack 5.111.0 → 5.111.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (144) hide show
  1. package/lib/APIPlugin.js +3 -4
  2. package/lib/CompatibilityPlugin.js +3 -4
  3. package/lib/Compilation.js +16 -35
  4. package/lib/Compiler.js +4 -5
  5. package/lib/ConstPlugin.js +16 -132
  6. package/lib/DependencyTemplate.js +2 -1
  7. package/lib/DotenvPlugin.js +24 -28
  8. package/lib/ErrorHelpers.js +113 -0
  9. package/lib/ExportsInfo.js +20 -16
  10. package/lib/ExternalModule.js +6 -8
  11. package/lib/FlagDependencyExportsPlugin.js +8 -13
  12. package/lib/FlagDependencyUsagePlugin.js +9 -13
  13. package/lib/Generator.js +24 -2
  14. package/lib/HotModuleReplacementPlugin.js +2 -0
  15. package/lib/IgnorePlugin.js +1 -1
  16. package/lib/LoaderOptionsPlugin.js +1 -1
  17. package/lib/Module.js +3 -3
  18. package/lib/ModuleGraph.js +6 -9
  19. package/lib/MultiCompiler.js +6 -16
  20. package/lib/NormalModule.js +96 -44
  21. package/lib/RuntimeTemplate.js +33 -43
  22. package/lib/SourceMapDevToolPlugin.js +53 -103
  23. package/lib/TemplatedPathPlugin.js +16 -59
  24. package/lib/asset/AssetBytesGenerator.js +7 -1
  25. package/lib/asset/AssetGenerator.js +25 -16
  26. package/lib/asset/AssetSourceGenerator.js +7 -1
  27. package/lib/buildChunkGraph.js +11 -15
  28. package/lib/cache/MemoryCachePlugin.js +4 -4
  29. package/lib/cache/MemoryWithGcCachePlugin.js +7 -8
  30. package/lib/cache/PackFileCacheStrategy.js +3 -18
  31. package/lib/cache/getLazyHashedEtag.js +3 -5
  32. package/lib/config/browserslistTargetHandler.js +2 -8
  33. package/lib/config/defaults.js +52 -78
  34. package/lib/config/getClaimedAssetTypes.js +10 -11
  35. package/lib/config/target.js +3 -4
  36. package/lib/{ContextExclusionPlugin.js → context/ContextExclusionPlugin.js} +1 -1
  37. package/lib/{ContextModule.js → context/ContextModule.js} +37 -34
  38. package/lib/{ContextModuleFactory.js → context/ContextModuleFactory.js} +19 -21
  39. package/lib/{ContextReplacementPlugin.js → context/ContextReplacementPlugin.js} +4 -4
  40. package/lib/css/CssGenerator.js +19 -11
  41. package/lib/css/CssParser.js +18 -20
  42. package/lib/css/cssMinify.js +32 -29
  43. package/lib/css/data.js +797 -288
  44. package/lib/css/syntax.js +2250 -934
  45. package/lib/debug/ProfilingPlugin.js +3 -4
  46. package/lib/dependencies/CommonJsExportRequireDependency.js +10 -11
  47. package/lib/dependencies/CommonJsImportsParserPlugin.js +4 -5
  48. package/lib/dependencies/CommonJsSelfReferenceDependency.js +2 -4
  49. package/lib/dependencies/ContextDependency.js +1 -1
  50. package/lib/dependencies/ContextDependencyHelpers.js +3 -9
  51. package/lib/dependencies/ContextElementDependency.js +1 -1
  52. package/lib/dependencies/CssIcssExportDependency.js +6 -8
  53. package/lib/dependencies/CssIcssImportDependency.js +3 -6
  54. package/lib/dependencies/CssUrlDependency.js +3 -5
  55. package/lib/dependencies/HarmonyCompatibilityDependency.js +11 -20
  56. package/lib/dependencies/HarmonyDetectionParserPlugin.js +3 -4
  57. package/lib/dependencies/HarmonyExportDependencyParserPlugin.js +2 -4
  58. package/lib/dependencies/HarmonyExportExpressionDependency.js +3 -4
  59. package/lib/dependencies/HarmonyExportImportedSpecifierDependency.js +3 -4
  60. package/lib/dependencies/HarmonyExportInitFragment.js +26 -19
  61. package/lib/dependencies/HarmonyExportSpecifierDependency.js +7 -28
  62. package/lib/dependencies/HarmonyImportDependencyParserPlugin.js +103 -16
  63. package/lib/dependencies/HarmonyImportSideEffectDependency.js +3 -4
  64. package/lib/dependencies/HarmonyImportSpecifierDependency.js +16 -2
  65. package/lib/dependencies/HtmlEntryDependency.js +74 -102
  66. package/lib/dependencies/HtmlInlineScriptDependency.js +3 -4
  67. package/lib/dependencies/HtmlInlineStyleDependency.js +3 -4
  68. package/lib/dependencies/ImportMetaContextDependencyParserPlugin.js +1 -1
  69. package/lib/dependencies/ImportMetaGlobHelpers.js +1 -1
  70. package/lib/dependencies/ImportMetaPlugin.js +8 -10
  71. package/lib/dependencies/ImportParserPlugin.js +1 -1
  72. package/lib/dependencies/LoaderPlugin.js +26 -1
  73. package/lib/dependencies/RequireContextDependencyParserPlugin.js +1 -1
  74. package/lib/dependencies/URLContextDependency.js +1 -1
  75. package/lib/dependencies/URLDependency.js +6 -5
  76. package/lib/dependencies/WorkerAndWorkletPlugin.js +15 -21
  77. package/lib/dependencies/WorkerDependency.js +6 -5
  78. package/lib/dependencies/WorkletDependency.js +6 -9
  79. package/lib/errors/HookWebpackError.js +3 -2
  80. package/lib/hmr/LazyCompilationPlugin.js +3 -5
  81. package/lib/html/HtmlGenerator.js +61 -82
  82. package/lib/html/HtmlModulesPlugin.js +88 -139
  83. package/lib/html/HtmlParser.js +97 -141
  84. package/lib/html/data.js +21 -0
  85. package/lib/html/htmlMinify.js +10 -11
  86. package/lib/html/syntax.js +883 -993
  87. package/lib/index.js +46 -3
  88. package/lib/javascript/ChunkFormatHelpers.js +4 -3
  89. package/lib/javascript/JavascriptGenerator.js +8 -1
  90. package/lib/javascript/JavascriptModulesPlugin.js +21 -48
  91. package/lib/javascript/JavascriptParser.js +721 -178
  92. package/lib/javascript/parser.js +6 -0
  93. package/lib/javascript/syntax.js +420 -92
  94. package/lib/json/JsonGenerator.js +7 -1
  95. package/lib/library/ModuleLibraryPlugin.js +64 -136
  96. package/lib/loaders/LoaderRunner.js +137 -9
  97. package/lib/node/NodeWatchFileSystem.js +3 -9
  98. package/lib/optimize/AggressiveMergingPlugin.js +3 -5
  99. package/lib/optimize/ConcatenatedModule.js +81 -100
  100. package/lib/optimize/FlagIncludedChunksPlugin.js +3 -11
  101. package/lib/optimize/InnerGraphPlugin.js +7 -13
  102. package/lib/optimize/LimitChunkCountPlugin.js +5 -8
  103. package/lib/optimize/MangleExportsPlugin.js +3 -4
  104. package/lib/optimize/ModuleConcatenationPlugin.js +3 -4
  105. package/lib/optimize/SideEffectsFlagPlugin.js +7 -19
  106. package/lib/optimize/SplitChunksPlugin.js +2 -4
  107. package/lib/performance/BroadContextsPlugin.js +1 -1
  108. package/lib/performance/CacheEffectivenessPlugin.js +3 -4
  109. package/lib/performance/SizeLimitsPlugin.js +2 -4
  110. package/lib/prefetch/ChunkPrefetchPreloadPlugin.js +6 -8
  111. package/lib/prefetch/ResourceHintPlugin.js +17 -21
  112. package/lib/prefetch/StartupAssetHintRuntimeModule.js +7 -10
  113. package/lib/runtime/AsyncModuleRuntimeModule.js +3 -5
  114. package/lib/runtime/GetChunkFilenameRuntimeModule.js +3 -4
  115. package/lib/runtime/GlobalRuntimeModule.js +2 -4
  116. package/lib/runtime/MakeDeferredNamespaceObjectRuntime.js +55 -85
  117. package/lib/schemes/DataUriPlugin.js +3 -6
  118. package/lib/schemes/VirtualUrlPlugin.js +1 -1
  119. package/lib/serialization/BinaryMiddleware.js +9 -9
  120. package/lib/serialization/FileMiddleware.js +16 -16
  121. package/lib/serialization/ObjectMiddleware.js +30 -33
  122. package/lib/stats/DefaultStatsFactoryPlugin.js +3 -4
  123. package/lib/typescript/TypeScriptPlugin.js +2 -3
  124. package/lib/url/URLParserPlugin.js +6 -8
  125. package/lib/util/LocConverter.js +4 -7
  126. package/lib/util/SourceProcessor.js +15 -22
  127. package/lib/util/chainedImports.js +3 -4
  128. package/lib/util/concatenate.js +4 -4
  129. package/lib/util/createHooksRegistry.js +1 -2
  130. package/lib/util/dataURL.js +2 -3
  131. package/lib/util/deterministicGrouping.js +8 -13
  132. package/lib/util/findGraphRoots.js +6 -13
  133. package/lib/util/globUtils.js +1 -1
  134. package/lib/util/hash/wasm-hash.js +3 -4
  135. package/lib/util/internalSerializables.js +1 -1
  136. package/lib/util/semver.js +5 -3
  137. package/lib/wasm-async/AsyncWebAssemblyGenerator.js +6 -1
  138. package/lib/wasm-async/AsyncWebAssemblyJavascriptGenerator.js +5 -1
  139. package/lib/wasm-sync/WasmChunkLoadingRuntimeModule.js +3 -4
  140. package/lib/wasm-sync/WebAssemblyGenerator.js +6 -1
  141. package/lib/wasm-sync/WebAssemblyJavascriptGenerator.js +5 -1
  142. package/lib/wasm-sync/WebAssemblyUtils.js +2 -4
  143. package/package.json +30 -23
  144. package/types.d.ts +299 -280
@@ -385,10 +385,9 @@ const collectEntrypointHints = (compilation, entryName, hints) => {
385
385
  if (dep.fetchPriority) h.fetchPriority = dep.fetchPriority;
386
386
  push(h);
387
387
  }
388
- // `hostType`: `"html"` iff the entrypoint has an extracted HTML page
389
- // (any `HtmlEntryDependency` with elementKind `script`/`script-module` on
390
- // any HTML module points at this entryName); SSR frameworks reading
391
- // `stats.entrypoints[name].resourceHints` see `"js"`.
388
+ // `hostType` is `"html"` only where the entrypoint has an extracted page, that
389
+ // is where some HTML module's script dependency names this entry. An SSR
390
+ // framework reading the stats sees `"js"`.
392
391
  let hostType = /** @type {"html" | "js"} */ ("js");
393
392
 
394
393
  outer: for (const module of compilation.modules) {
@@ -737,15 +736,14 @@ class ResourceHintPlugin {
737
736
  const hints = this._hints;
738
737
 
739
738
  compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
740
- // Lazy-computed on first access — walk every HTML module's
741
- // `HtmlEntryDependency`s, resolve each named entry, and collect
742
- // every URL asset dep target reachable from its ordered chunks.
743
- // One pass produces two views: a per-entry list (consumed by
744
- // `HtmlEntryDependency.Template` to emit `<link>` tags) and a
745
- // global `WeakSet` (consumed by `StartupAssetHintRuntimeModule`
746
- // to skip the JS runtime `<link>` for the same asset).
747
- // Deterministic (module graph is fixed by seal time) and cheap
748
- // (only fires when a JS chunk actually produces hints).
739
+ // WHY: computed on first access. One walk of every HTML module's
740
+ // `HtmlEntryDependency`s — resolving each named entry and collecting every
741
+ // URL asset dep reachable from its ordered chunks — yields both views: a
742
+ // per-entry list, which `HtmlEntryDependency.Template` emits the `<link>`
743
+ // tags from, and a global `WeakSet`, which `StartupAssetHintRuntimeModule`
744
+ // reads to skip the JS runtime `<link>` for the same asset. Deterministic,
745
+ // the module graph being fixed by seal time, and cheap, since it only fires
746
+ // when a JS chunk actually produces hints.
749
747
  /** @type {Map<string, HtmlHintedAsset[]> | undefined} */
750
748
  let perEntry;
751
749
  /** @type {WeakSet<Module> | undefined} */
@@ -773,10 +771,9 @@ class ResourceHintPlugin {
773
771
  }
774
772
  const entrypoint = compilation.entrypoints.get(dep.entryName);
775
773
  if (!entrypoint) continue;
776
- // Mirror `getEntrypointChunksInLoadOrder`: entry chunk +
777
- // runtime chunk + all initial siblings (`entrypoint.chunks`
778
- // includes splitChunks output). Async `import()` chunks
779
- // stay on the on-demand runtime and are NOT HTML-hinted.
774
+ // Mirrors `getEntrypointChunksInLoadOrder`: the entry, runtime and
775
+ // every initial sibling. An async `import()` chunk stays on the
776
+ // on-demand runtime and is never HTML-hinted.
780
777
  /** @type {Set<import("../Chunk")>} */
781
778
  const chunks = new Set(entrypoint.chunks);
782
779
  const entry = entrypoint.getEntrypointChunk();
@@ -864,10 +861,9 @@ class ResourceHintPlugin {
864
861
  });
865
862
  }
866
863
 
867
- // SSR manifest: serialize each entrypoint's resolved hints to a JSON
868
- // asset (the same descriptors as `stats.entrypoints[].resourceHints`)
869
- // so an SSR server can inject the `<link>` tags itself. `"none"`
870
- // yields empty lists (via `collectEntrypointHints`).
864
+ // The SSR manifest serializes each entrypoint's resolved hints to a JSON
865
+ // asset, the same descriptors the stats carry, so an SSR server can inject
866
+ // the tags itself. `"none"` yields empty lists.
871
867
  const rhOptions = compilation.outputOptions.resourceHints;
872
868
  const manifestPath = rhOptions && rhOptions.manifest;
873
869
  if (manifestPath) {
@@ -47,16 +47,13 @@ class StartupAssetHintRuntimeModule extends RuntimeModule {
47
47
  const compilation = /** @type {Compilation} */ (this.compilation);
48
48
  const lines = this._lines;
49
49
  if (lines.length === 0) return null;
50
- // `__webpack_nonce__` set inside the entry module is too late — the
51
- // entry hasn't run yet. Read the nonce off the `<script>` tag that
52
- // loaded the bundle, so prefetch / preload links match a CSP that
53
- // demands the same nonce as the script.
54
- //
55
- // - For classic script output, `document.currentScript` is the
56
- // loading `<script>` element while the runtime executes.
57
- // - For ESM output (`output.module: true`), `document.currentScript`
58
- // is `null`; locate the loading `<script type="module">` by
59
- // matching `script.src` against `import.meta.url`.
50
+ // `__webpack_nonce__` set in the entry module comes too late, the entry not
51
+ // having run, so the nonce is read off the `<script>` that loaded the bundle
52
+ // and the links match a CSP demanding the script's own.
53
+
54
+ // Classic output finds it on `document.currentScript`. ESM output leaves that
55
+ // null, so the loading `<script type="module">` is found by matching its
56
+ // `src` against `import.meta.url`.
60
57
  const { module: isModule, importMetaName } = compilation.outputOptions;
61
58
  const nonceSetup = isModule
62
59
  ? [
@@ -239,11 +239,9 @@ class AsyncModuleRuntimeModule extends HelperRuntimeModule {
239
239
  }`,
240
240
  "err"
241
241
  )}`,
242
- // Track the async body's whole lifetime (evaluating +
243
- // evaluating-async states) with a dedicated flag — the sync require
244
- // wrapper clears `module.evaluating` as soon as `.a` returns, so a
245
- // deferred namespace reaching this module through a cycle relies on
246
- // `evaluatingAsync` to keep throwing until it is fully evaluated.
242
+ // The sync require wrapper clears `module.evaluating` the moment `.a`
243
+ // returns, so a deferred namespace reaching this module through a cycle
244
+ // needs `evaluatingAsync` to keep throwing until evaluation ends.
247
245
  defer ? "module.evaluatingAsync = true;" : "",
248
246
  "body(handle, done);",
249
247
  `${runtimeTemplate.optionalChaining("queue", "d < 0")} && (queue.d = 0);`
@@ -105,10 +105,9 @@ class GetChunkFilenameRuntimeModule extends RuntimeModule {
105
105
  return length ? hash.slice(0, length) : hash;
106
106
  };
107
107
 
108
- // `[fullhash:<digest>]`/`[hash:<digest>]` would resolve to a runtime
109
- // `getFullHash()` expression that can't be re-encoded; instead this module is
110
- // flagged `fullHash` and re-rendered after hashing, so we inline the
111
- // re-encoded full hash here — byte-identical to the statically emitted file.
108
+ // A digest cannot be re-encoded from the runtime `getFullHash()` expression,
109
+ // so this module is flagged `fullHash` and re-rendered after hashing: the
110
+ // inlined value is byte-identical to the statically emitted file.
112
111
  /** @type {HashWithDigestFunction} */
113
112
  const fullHashWithDigest = (digest, length) => {
114
113
  const fullHash = compilation.fullHash;
@@ -62,10 +62,8 @@ class GlobalRuntimeModule extends RuntimeModule {
62
62
  "if (typeof window === 'object') return window;"
63
63
  ),
64
64
  "}"
65
- // It can still be `undefined`, but nothing to do about it...
66
- // We return `undefined`, instead of nothing here, so it's
67
- // easier to handle this case:
68
- // if (!global) { … }
65
+ // It can still be `undefined`, and nothing here can help that. Returning
66
+ // `undefined` rather than nothing keeps `if (!global)` working.
69
67
  ]),
70
68
  "})();"
71
69
  ]);
@@ -263,11 +263,9 @@ class MakeOptimizedDeferredNamespaceObjectRuntimeModule extends HelperRuntimeMod
263
263
  Template.indent([
264
264
  "get a() {",
265
265
  Template.indent([
266
- // Forcing evaluation of a module that is currently evaluating
267
- // (a cycle reached through a deferred import) must throw rather
268
- // than expose its partial exports. `syncDeps` (present only for
269
- // cyclic deferred modules) carries the transitive static closure,
270
- // so an evaluating dependency is caught before any evaluation.
266
+ // Forcing a module that is already evaluating, a cycle reached
267
+ // through a deferred import, must throw rather than expose partial
268
+ // exports. `syncDeps` carries the closure that catches it first.
271
269
  `${cst} cachedModule = __webpack_module_cache__[moduleId];`,
272
270
  'if (cachedModule !== undefined && (cachedModule.evaluating || cachedModule.evaluatingAsync)) throw new TypeError("Cannot access a deferred module namespace while the module is being evaluated");',
273
271
  "if (syncDeps) for (var i = 0; i < syncDeps.length; i++) {",
@@ -354,28 +352,20 @@ class MakeDeferredNamespaceObjectRuntimeModule extends HelperRuntimeModule {
354
352
  return `${fn} = ${runtimeTemplate.basicFunction(
355
353
  "moduleId, mode, exportNames",
356
354
  [
357
- // Per the TC39 import-defer spec, deferred namespaces are
358
- // distinct from their eager counterparts and the same module
359
- // referenced from multiple defer-import sites must yield the
360
- // same object. Cache the Proxy / fake namespace per-moduleId so
361
- // repeated calls (including across files) share identity.
355
+ // WHY: the TC39 import-defer spec makes a deferred namespace distinct
356
+ // from its eager counterpart, and one module reached from several defer
357
+ // sites must yield the same object, so the Proxy is cached per moduleId.
362
358
  //
363
- // Bit 16 (`createFakeNamespaceObject`'s "return value when
364
- // it's Promise-like" flag added by
365
- // `RuntimeTemplate.moduleNamespacePromise` for dynamic
366
- // imports) is irrelevant for deferred namespaces — the value
367
- // passed into `createFakeNamespaceObject` here is always the
368
- // resolved module exports (after unwrapping the async-module
369
- // export symbol when present), never a Promise. Strip it
370
- // once so all downstream behavior, the cache key, and the
371
- // `createFakeNamespaceObject` call below see the same shape
372
- // mode. This keeps static defer (mode 8) and dynamic
373
- // `await import.defer` (mode 8 | 16) sharing the same
374
- // Deferred Module Namespace object, while still keying by
375
- // `(moduleId, mode)` so distinct exports-type shapes
376
- // (e.g. one importer treats a CJS module as
377
- // "default-with-named", another as "namespace") get
378
- // distinct cache entries.
359
+ // Bit 16 is `createFakeNamespaceObject`'s "return value when it's
360
+ // Promise-like" flag, which `RuntimeTemplate.moduleNamespacePromise` adds
361
+ // for a dynamic import. It is irrelevant here: what is passed in is
362
+ // always the resolved module exports, after unwrapping the async-module
363
+ // export symbol where there is one, and never a Promise. Stripping it
364
+ // once leaves the cache key, the call below and everything downstream on
365
+ // one shape mode, so static defer (mode 8) and `await import.defer`
366
+ // (mode 8 | 16) share the same object. The key stays `(moduleId, mode)`
367
+ // so two importers reading one CJS module differently — as
368
+ // "default-with-named" against "namespace" — still get distinct entries.
379
369
  "mode &= ~16;",
380
370
  // Only a real ES module namespace has the spec's exotic shape; a
381
371
  // synthesized one (JSON, asset, CommonJS interop) keeps the old form.
@@ -417,23 +407,16 @@ class MakeDeferredNamespaceObjectRuntimeModule extends HelperRuntimeModule {
417
407
  ? "if (mode & 8 || mode & 4 && ns.__esModule && typeof ns === 'object') {"
418
408
  : "",
419
409
  Template.indent([
420
- // Drop only the read-side traps after init: with the
421
- // resolved namespace's own keys mirrored onto
422
- // `ns_target` below, the default `Reflect` behavior
423
- // returns the right values via the live-binding
424
- // getters, so we no longer need to intercept `get` /
425
- // `has` / `ownKeys` / `getOwnPropertyDescriptor`.
426
- //
427
- // The mutation traps (`set`, `deleteProperty`,
428
- // `defineProperty`) are kept because per the TC39
429
- // import-defer spec, `[[Set]]` / `[[Delete]]` /
430
- // `[[DefineOwnProperty]]` on a Deferred Module
431
- // Namespace Exotic Object never succeed — and the
432
- // proxy target itself remains extensible
433
- // (architecturally we cannot freeze it up-front),
434
- // so without these traps `ns.notExported = "x"`
435
- // after evaluation would silently create a property
436
- // on the target instead of returning false.
410
+ // Drop only the read traps after init: with the namespace's own keys
411
+ // mirrored onto `ns_target`, default `Reflect` behavior already
412
+ // returns the right values through the live-binding getters.
413
+
414
+ // WHY: the spec makes `[[Set]]`, `[[Delete]]` and
415
+ // `[[DefineOwnProperty]]` on a Deferred Module Namespace always
416
+ // fail, yet the target stays extensible because it cannot be frozen
417
+ // up front — so without the mutation traps `ns.notExported = "x"`
418
+ // would silently create a property instead of returning false.
419
+
437
420
  // A sealed target holds placeholder values, so the read traps stay to
438
421
  // keep the live bindings visible.
439
422
  sealed && synthesized ? "if (!exportNames) {" : "",
@@ -454,18 +437,12 @@ class MakeDeferredNamespaceObjectRuntimeModule extends HelperRuntimeModule {
454
437
  ])
455
438
  : "",
456
439
  synthesized ? "}" : "",
457
- // Mirror own properties from the resolved namespace onto the proxy
458
- // target so that proxy invariants hold for callers that structurally
459
- // introspect via `Object.keys` / `Object.getOwnPropertyNames` /
460
- // `Object.getOwnPropertyDescriptor`: when our trap reports a
461
- // non-configurable descriptor for a key, the target must also have
462
- // that key with a matching descriptor.
463
- //
464
- // `__esModule` and `Symbol.toStringTag` are intentionally skipped:
465
- // the proxy synthesizes "Deferred Module" / true regardless of what
466
- // the underlying namespace exposes (per the TC39 import-defer
467
- // proposal, the [[StringTag]] of a Deferred Module Namespace
468
- // Exotic Object is "Deferred Module"), and the target was already
440
+ // Mirror the resolved namespace's own properties onto the target, or
441
+ // the proxy invariants break: where a trap reports a non-configurable
442
+ // descriptor, the target must carry a matching one.
443
+
444
+ // `__esModule` and `Symbol.toStringTag` are skipped: the proxy
445
+ // synthesizes them whatever the namespace exposes, and the target is
469
446
  // pre-populated with those values below.
470
447
  synthesized
471
448
  ? `${cst} keys = ${sealed ? "exportNames ? [] : " : ""}Reflect.ownKeys(ns);`
@@ -485,23 +462,23 @@ class MakeDeferredNamespaceObjectRuntimeModule extends HelperRuntimeModule {
485
462
  synthesized ? "}" : ""
486
463
  ])};`,
487
464
  "",
488
- // The proxy target is a fresh placeholder, separate from
489
- // `__webpack_module_deferred_exports__[moduleId]` (which is reused
490
- // by `__webpack_require__` as `module.exports` for deferred-loaded
491
- // modules and would conflict with our pre-populated synthetic
492
- // `__esModule` / `Symbol.toStringTag` non-configurable properties).
493
- // Using a dedicated target keeps the proxy invariant-compliant
494
- // without interfering with the module's own exports object.
465
+ // WHY: the proxy target is a fresh placeholder, separate from
466
+ // `__webpack_module_deferred_exports__[moduleId]`, which
467
+ // `__webpack_require__` reuses as `module.exports` for a deferred-loaded
468
+ // module and would conflict with the pre-populated synthetic `__esModule`
469
+ // and `Symbol.toStringTag` non-configurable properties. A dedicated
470
+ // target keeps the proxy invariant-compliant without interfering with the
471
+ // module's own exports object.
495
472
  `${cst} ns_target = { __proto__: null };`,
496
473
  // With the export list known at build time the target carries the spec's
497
474
  // keys and is sealed, so `[[IsExtensible]]` is false up front.
498
475
  sealed
499
476
  ? `${synthesized ? "if (exportNames) " : ""}for (var e = 0; e < exportNames.length; e++) ns_target[exportNames[e]] = undefined;`
500
477
  : "",
501
- // Pre-populate the synthetic deferred-namespace properties with
502
- // fully non-configurable, non-writable, non-enumerable descriptors
503
- // (matching the TC39 import-defer spec for Module Namespace
504
- // Exotic Objects). The trap returns the same descriptors below.
478
+ // Pre-populate the synthetic properties with the non-configurable,
479
+ // non-writable, non-enumerable descriptors the spec gives a Module
480
+ // Namespace, which the trap below returns unchanged.
481
+
505
482
  // `__esModule` is not one of the spec's keys, so a sealed namespace omits
506
483
  // it; the synthesized form keeps it for interop.
507
484
  synthesized
@@ -515,12 +492,9 @@ class MakeDeferredNamespaceObjectRuntimeModule extends HelperRuntimeModule {
515
492
  `${cst} handler = {`,
516
493
  Template.indent([
517
494
  "__proto__: null,",
518
- // Per the TC39 import-defer proposal, `IsSymbolLikeNamespaceKey`
519
- // returns true for any Symbol-keyed access (and for "then"); such
520
- // accesses go through `OrdinaryGetOwnProperty` and must not
521
- // trigger evaluation of the deferred module. The Symbol checks
522
- // below short-circuit to the pre-populated target without
523
- // running `init()`.
495
+ // `IsSymbolLikeNamespaceKey` holds for any Symbol key and for `then`,
496
+ // and such a read must not evaluate the deferred module, so the checks
497
+ // below reach the pre-populated target without running `init()`.
524
498
  `${runtimeTemplate.method("get", "_, name", [
525
499
  "switch (name) {",
526
500
  Template.indent([
@@ -589,10 +563,9 @@ class MakeDeferredNamespaceObjectRuntimeModule extends HelperRuntimeModule {
589
563
  `${runtimeTemplate.method("getOwnPropertyDescriptor", "_, name", [
590
564
  "switch (name) {",
591
565
  Template.indent([
592
- // Match the descriptors actually defined on `ns_target`
593
- // (non-configurable, non-writable, non-enumerable) so the
594
- // proxy invariant holds for both the trap result and any
595
- // post-init forwarding via the deleted-handler path.
566
+ // Match the descriptors actually defined on `ns_target`, so the
567
+ // proxy invariant holds both for this result and for the
568
+ // post-init forwarding through the deleted-handler path.
596
569
  synthesized
597
570
  ? `case "__esModule": ${sealed ? "if (!exportNames) " : ""}return { value: true, writable: false, enumerable: false, configurable: false };${sealed ? " break;" : ""}`
598
571
  : "",
@@ -617,20 +590,17 @@ class MakeDeferredNamespaceObjectRuntimeModule extends HelperRuntimeModule {
617
590
  synthesized ? "}" : "",
618
591
  synthesized ? "return desc;" : ""
619
592
  ])},`,
620
- // `defineProperty` always rejects, but per the TC39 spec it
621
- // must still trigger evaluation for string keys (the spec
622
- // algorithm calls `[[GetOwnProperty]]` first, which forces
623
- // evaluation on a deferred namespace). Symbol keys go through
624
- // OrdinaryDefineOwnProperty and do not trigger eval.
593
+ // `defineProperty` always rejects, yet must still evaluate on a string
594
+ // key, since the spec calls `[[GetOwnProperty]]` first. A Symbol key
595
+ // takes OrdinaryDefineOwnProperty and evaluates nothing.
625
596
  `${runtimeTemplate.method("defineProperty", "_, name", [
626
597
  'if (typeof name === "symbol" || name === "then") return false;',
627
598
  init,
628
599
  "return false;"
629
600
  ])},`,
630
- // `deleteProperty` rejects, but per the TC39 spec it must
631
- // still trigger evaluation for string keys (the spec
632
- // algorithm calls `GetModuleExportsList` for non-symbol-like
633
- // keys, forcing evaluation on a deferred namespace).
601
+ // `deleteProperty` rejects too, and likewise still evaluates on a
602
+ // string key: the spec calls `GetModuleExportsList` for every
603
+ // non-symbol-like key.
634
604
  `${runtimeTemplate.method("deleteProperty", "_, name", [
635
605
  'if (typeof name === "symbol" || name === "then") return false;',
636
606
  init,
@@ -34,12 +34,9 @@ class DataUriPlugin {
34
34
  );
35
35
  resourceData.data.encodedContent = match[4] || "";
36
36
  }
37
- // Inherit the issuer's resolution context so any nested
38
- // dependencies discovered while parsing the data URI's body
39
- // (e.g. `url(...)` / `@import` inside an inline CSS data
40
- // URI) resolve relative to where the URI was referenced
41
- // from, instead of against the synthetic `data:.../` path
42
- // that `getContext("data:…")` would otherwise infer.
37
+ // Inherit the issuer's resolution context, so a dependency found
38
+ // inside the data URI's body resolves against where the URI was
39
+ // referenced, not the synthetic `data:…` path.
43
40
  if (
44
41
  resourceData.context === undefined &&
45
42
  resolveData.context !== undefined
@@ -36,7 +36,7 @@ const PLUGIN_NAME = "VirtualUrlPlugin";
36
36
  /**
37
37
  * Defines the loader context type used by this module.
38
38
  * @template T
39
- * @typedef {import("../../declarations/LoaderContext").LoaderContext<T>} LoaderContext
39
+ * @typedef {import("../NormalModule").LoaderContext<T>} LoaderContext
40
40
  */
41
41
 
42
42
  /**
@@ -2,15 +2,6 @@
2
2
  MIT License http://www.opensource.org/licenses/mit-license.php
3
3
  */
4
4
 
5
- "use strict";
6
-
7
- const { deserialize: v8Deserialize, serialize: v8Serialize } = require("v8");
8
- const memoize = require("../util/memoize");
9
- const SerializerMiddleware = require("./SerializerMiddleware");
10
-
11
- /** @typedef {import("./types").PrimitiveSerializableType} PrimitiveSerializableType */
12
- /** @import { BufferSerializableType } from "./types" */
13
-
14
5
  /*
15
6
  Format:
16
7
 
@@ -28,6 +19,15 @@ ValuesHeaderByte -> 0xf1
28
19
  LazyHeaderByte -> 0xf2
29
20
  */
30
21
 
22
+ "use strict";
23
+
24
+ const { deserialize: v8Deserialize, serialize: v8Serialize } = require("v8");
25
+ const memoize = require("../util/memoize");
26
+ const SerializerMiddleware = require("./SerializerMiddleware");
27
+
28
+ /** @typedef {import("./types").PrimitiveSerializableType} PrimitiveSerializableType */
29
+ /** @import { BufferSerializableType } from "./types" */
30
+
31
31
  const VALUES_HEADER = 0xf1;
32
32
  const LAZY_HEADER = 0xf2;
33
33
 
@@ -2,6 +2,22 @@
2
2
  MIT License http://www.opensource.org/licenses/mit-license.php
3
3
  */
4
4
 
5
+ /*
6
+ Format:
7
+
8
+ File -> Header Section*
9
+
10
+ Version -> u32
11
+ AmountOfSections -> u32
12
+ SectionSize -> i32 (if less than zero represents lazy value)
13
+
14
+ Header -> Version AmountOfSections SectionSize*
15
+
16
+ Buffer -> n bytes
17
+ Section -> Buffer
18
+
19
+ */
20
+
5
21
  "use strict";
6
22
 
7
23
  const { constants } = require("buffer");
@@ -35,22 +51,6 @@ const SerializerMiddleware = require("./SerializerMiddleware");
35
51
  /** @import { IStats, IntermediateFileSystem } from "../util/fs" */
36
52
  /** @import { BufferSerializableType } from "./types" */
37
53
 
38
- /*
39
- Format:
40
-
41
- File -> Header Section*
42
-
43
- Version -> u32
44
- AmountOfSections -> u32
45
- SectionSize -> i32 (if less than zero represents lazy value)
46
-
47
- Header -> Version AmountOfSections SectionSize*
48
-
49
- Buffer -> n bytes
50
- Section -> Buffer
51
-
52
- */
53
-
54
54
  // "wpc" + 1 in little-endian
55
55
  const VERSION = 0x01637077;
56
56
  const WRITE_LIMIT_TOTAL = 0x7fff0000;
@@ -2,6 +2,28 @@
2
2
  MIT License http://www.opensource.org/licenses/mit-license.php
3
3
  */
4
4
 
5
+ /*
6
+
7
+ Format:
8
+
9
+ File -> Section*
10
+ Section -> ObjectSection | ReferenceSection | EscapeSection | OtherSection
11
+
12
+ ObjectSection -> ESCAPE (
13
+ number:relativeOffset (number > 0) |
14
+ string:request (string|null):export
15
+ ) Section:value* ESCAPE ESCAPE_END_OBJECT
16
+ ReferenceSection -> ESCAPE number:relativeOffset (number < 0)
17
+ EscapeSection -> ESCAPE ESCAPE_ESCAPE_VALUE (escaped value ESCAPE)
18
+ EscapeSection -> ESCAPE ESCAPE_UNDEFINED (escaped value ESCAPE)
19
+ OtherSection -> any (except ESCAPE)
20
+
21
+ Why using null as escape value?
22
+ Multiple null values can merged by the BinaryMiddleware, which makes it very efficient
23
+ Technically any value can be used.
24
+
25
+ */
26
+
5
27
  "use strict";
6
28
 
7
29
  const { DEFAULTS } = require("../config/defaults");
@@ -29,28 +51,6 @@ const SetObjectSerializer = require("./SetObjectSerializer");
29
51
 
30
52
  /** @typedef {new (...params: EXPECTED_ANY[]) => EXPECTED_ANY} Constructor */
31
53
 
32
- /*
33
-
34
- Format:
35
-
36
- File -> Section*
37
- Section -> ObjectSection | ReferenceSection | EscapeSection | OtherSection
38
-
39
- ObjectSection -> ESCAPE (
40
- number:relativeOffset (number > 0) |
41
- string:request (string|null):export
42
- ) Section:value* ESCAPE ESCAPE_END_OBJECT
43
- ReferenceSection -> ESCAPE number:relativeOffset (number < 0)
44
- EscapeSection -> ESCAPE ESCAPE_ESCAPE_VALUE (escaped value ESCAPE)
45
- EscapeSection -> ESCAPE ESCAPE_UNDEFINED (escaped value ESCAPE)
46
- OtherSection -> any (except ESCAPE)
47
-
48
- Why using null as escape value?
49
- Multiple null values can merged by the BinaryMiddleware, which makes it very efficient
50
- Technically any value can be used.
51
-
52
- */
53
-
54
54
  /**
55
55
  * Defines the object serializer snapshot type used by this module.
56
56
  * @typedef {object} ObjectSerializerSnapshot
@@ -183,9 +183,8 @@ if (typeof AggregateError !== "undefined") {
183
183
  );
184
184
  }
185
185
 
186
- // If in a sandboxed environment (e.g. jest), this escapes the sandbox and registers
187
- // real Object and Array types to. These types may occur in the wild too, e.g. when
188
- // using Structured Clone in postMessage.
186
+ // In a sandboxed environment such as jest, this escapes the sandbox to register
187
+ // the real Object and Array too, which reach us through a structured clone.
189
188
  // eslint-disable-next-line n/exports-style
190
189
  if (exports.constructor !== Object) {
191
190
  // eslint-disable-next-line n/exports-style
@@ -772,10 +771,9 @@ class ObjectMiddleware extends SerializerMiddleware {
772
771
 
773
772
  throw err;
774
773
  } finally {
775
- // Get rid of these references to avoid leaking memory
776
- // This happens because the optimized code v8 generates
777
- // is optimized for our "ctx.write" method so it will reference
778
- // it from e. g. Dependency.prototype.serialize -(IC)-> ctx.write
774
+ // Drop these references, which would otherwise leak: v8 optimizes the
775
+ // generated code for this `ctx.write`, so an inline cache on
776
+ // `Dependency.prototype.serialize` keeps pointing at it.
779
777
  data =
780
778
  result =
781
779
  referenceable =
@@ -974,10 +972,9 @@ class ObjectMiddleware extends SerializerMiddleware {
974
972
  }
975
973
  return result;
976
974
  } finally {
977
- // Get rid of these references to avoid leaking memory
978
- // This happens because the optimized code v8 generates
979
- // is optimized for our "ctx.read" method so it will reference
980
- // it from e. g. Dependency.prototype.deserialize -(IC)-> ctx.read
975
+ // Drop these references, which would otherwise leak: v8 optimizes the
976
+ // generated code for this `ctx.read`, so an inline cache on
977
+ // `Dependency.prototype.deserialize` keeps pointing at it.
981
978
  result =
982
979
  referenceable =
983
980
  data =
@@ -1274,10 +1274,9 @@ const SIMPLE_EXTRACTORS = {
1274
1274
  { name, chunkGroup },
1275
1275
  { compilation }
1276
1276
  ) => {
1277
- // SSR frameworks consume this to inject the initial-chunk +
1278
- // URL-asset `<link>` tags into their server-rendered HTML without
1279
- // having to walk the chunk graph themselves. Only entrypoints
1280
- // carry hints; split-chunk / async chunk groups are skipped.
1277
+ // An SSR framework reads this to inject the `<link>` tags into its own
1278
+ // HTML without walking the chunk graph. Only entrypoints carry hints, so
1279
+ // split-chunk and async groups are skipped.
1281
1280
  if (!compilation.entrypoints.get(name)) return;
1282
1281
 
1283
1282
  const ResourceHintPlugin = require("../prefetch/ResourceHintPlugin");
@@ -122,9 +122,8 @@ const composeWithLoaderSourceMap = (
122
122
  */
123
123
  const stripTypes = (input) => {
124
124
  try {
125
- // Pass only `mode`. `sourceUrl` would emit a `//# sourceURL=…` pragma
126
- // into the output (V8 debugger hint), and `sourceMap: true` is
127
- // rejected in strip mode — we build the source map by hand instead.
125
+ // Only `mode`: `sourceUrl` would emit a `//# sourceURL=` pragma, and
126
+ // `sourceMap: true` is rejected in strip mode, so the map is built by hand.
128
127
  // eslint-disable-next-line n/no-unsupported-features/node-builtins
129
128
  return mod.stripTypeScriptTypes(input, { mode: "strip" });
130
129
  } catch (err) {
@@ -257,10 +257,9 @@ class URLParserPlugin {
257
257
  relative
258
258
  );
259
259
  dep.loc = parser.getLocation(expr);
260
- // `parser.javascript.urlHints` provides project-wide defaults
261
- // (resolved per-request, with `test` / `include` / `exclude`
262
- // matching); a per-URL magic comment for the same hint wins
263
- // when both are set.
260
+ // `parser.javascript.urlHints` gives the project-wide defaults,
261
+ // resolved per request; a per-URL magic comment for the same hint
262
+ // wins where both are set.
264
263
  ResourceHintPlugin.applyResourceHints(
265
264
  dep,
266
265
  this.options.urlHints,
@@ -270,10 +269,9 @@ class URLParserPlugin {
270
269
  parser.getLocation(expr)
271
270
  );
272
271
  parser.state.current.addDependency(dep);
273
- // For ESM module output the template embeds the asset's resolved
274
- // filename, so the asset must be code-generated first. Only added in
275
- // that mode — a code-gen dependency on an asset that a later watch
276
- // rebuild leaves unaffected can otherwise deadlock the scheduler.
272
+ // The ESM template embeds the asset's resolved filename, so the asset
273
+ // must be code-generated first. Added in that mode only: elsewhere the
274
+ // extra code-gen dependency can deadlock a watch rebuild.
277
275
  if (parser.state.compilation.options.output.module) {
278
276
  parser.state.module.addCodeGenerationDependency(dep);
279
277
  }