webpack 5.40.0 → 5.42.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.

Potentially problematic release.


This version of webpack might be problematic. Click here for more details.

Files changed (50) hide show
  1. package/README.md +3 -3
  2. package/bin/webpack.js +0 -0
  3. package/lib/Compiler.js +14 -1
  4. package/lib/ConditionalInitFragment.js +15 -12
  5. package/lib/DependencyTemplate.js +3 -2
  6. package/lib/ExternalModule.js +213 -33
  7. package/lib/ExternalModuleFactoryPlugin.js +2 -1
  8. package/lib/InitFragment.js +10 -7
  9. package/lib/MainTemplate.js +1 -1
  10. package/lib/ModuleTemplate.js +0 -9
  11. package/lib/NormalModuleFactory.js +13 -2
  12. package/lib/RuntimeTemplate.js +8 -0
  13. package/lib/Template.js +3 -2
  14. package/lib/TemplatedPathPlugin.js +24 -26
  15. package/lib/Watching.js +2 -1
  16. package/lib/WebpackOptionsApply.js +12 -8
  17. package/lib/asset/AssetGenerator.js +2 -2
  18. package/lib/async-modules/AwaitDependenciesInitFragment.js +4 -1
  19. package/lib/cache/IdleFileCachePlugin.js +60 -13
  20. package/lib/cache/PackFileCacheStrategy.js +26 -15
  21. package/lib/config/defaults.js +54 -12
  22. package/lib/config/normalization.js +2 -0
  23. package/lib/dependencies/HarmonyExportInitFragment.js +4 -1
  24. package/lib/dependencies/WorkerPlugin.js +25 -10
  25. package/lib/electron/ElectronTargetPlugin.js +3 -3
  26. package/lib/esm/ModuleChunkFormatPlugin.js +97 -0
  27. package/lib/esm/ModuleChunkLoadingPlugin.js +63 -0
  28. package/lib/esm/ModuleChunkLoadingRuntimeModule.js +208 -0
  29. package/lib/hmr/lazyCompilationBackend.js +17 -1
  30. package/lib/javascript/EnableChunkLoadingPlugin.js +5 -3
  31. package/lib/javascript/JavascriptModulesPlugin.js +80 -17
  32. package/lib/javascript/JavascriptParser.js +2 -1
  33. package/lib/json/JsonGenerator.js +2 -2
  34. package/lib/node/NodeTargetPlugin.js +1 -1
  35. package/lib/node/ReadFileCompileAsyncWasmPlugin.js +44 -22
  36. package/lib/optimize/ModuleConcatenationPlugin.js +1 -1
  37. package/lib/runtime/AsyncModuleRuntimeModule.js +8 -4
  38. package/lib/serialization/BinaryMiddleware.js +50 -35
  39. package/lib/serialization/FileMiddleware.js +112 -12
  40. package/lib/wasm/EnableWasmLoadingPlugin.js +10 -1
  41. package/lib/wasm-sync/WebAssemblyModulesPlugin.js +1 -1
  42. package/package.json +15 -15
  43. package/schemas/WebpackOptions.check.js +1 -1
  44. package/schemas/WebpackOptions.json +22 -8
  45. package/schemas/plugins/container/ContainerReferencePlugin.check.js +1 -1
  46. package/schemas/plugins/container/ContainerReferencePlugin.json +2 -1
  47. package/schemas/plugins/container/ExternalsType.check.js +1 -1
  48. package/schemas/plugins/container/ModuleFederationPlugin.check.js +1 -1
  49. package/schemas/plugins/container/ModuleFederationPlugin.json +2 -1
  50. package/types.d.ts +105 -151
@@ -17,6 +17,7 @@ const {
17
17
  const Compilation = require("../Compilation");
18
18
  const { tryRunOrWebpackError } = require("../HookWebpackError");
19
19
  const HotUpdateChunk = require("../HotUpdateChunk");
20
+ const InitFragment = require("../InitFragment");
20
21
  const RuntimeGlobals = require("../RuntimeGlobals");
21
22
  const Template = require("../Template");
22
23
  const { last, someInIterable } = require("../util/IterableHelpers");
@@ -84,6 +85,17 @@ const printGeneratedCodeForStack = (module, code) => {
84
85
  * @property {string} hash hash to be used for render call
85
86
  */
86
87
 
88
+ /**
89
+ * @typedef {Object} ChunkRenderContext
90
+ * @property {Chunk} chunk the chunk
91
+ * @property {DependencyTemplates} dependencyTemplates the dependency templates
92
+ * @property {RuntimeTemplate} runtimeTemplate the runtime template
93
+ * @property {ModuleGraph} moduleGraph the module graph
94
+ * @property {ChunkGraph} chunkGraph the chunk graph
95
+ * @property {CodeGenerationResults} codeGenerationResults results of code generation
96
+ * @property {InitFragment<ChunkRenderContext>[]} chunkInitFragments init fragments for the chunk
97
+ */
98
+
87
99
  /**
88
100
  * @typedef {Object} RenderBootstrapContext
89
101
  * @property {Chunk} chunk the chunk
@@ -97,11 +109,12 @@ const printGeneratedCodeForStack = (module, code) => {
97
109
 
98
110
  /**
99
111
  * @typedef {Object} CompilationHooks
100
- * @property {SyncWaterfallHook<[Source, Module, RenderContext]>} renderModuleContent
101
- * @property {SyncWaterfallHook<[Source, Module, RenderContext]>} renderModuleContainer
102
- * @property {SyncWaterfallHook<[Source, Module, RenderContext]>} renderModulePackage
112
+ * @property {SyncWaterfallHook<[Source, Module, ChunkRenderContext]>} renderModuleContent
113
+ * @property {SyncWaterfallHook<[Source, Module, ChunkRenderContext]>} renderModuleContainer
114
+ * @property {SyncWaterfallHook<[Source, Module, ChunkRenderContext]>} renderModulePackage
103
115
  * @property {SyncWaterfallHook<[Source, RenderContext]>} renderChunk
104
116
  * @property {SyncWaterfallHook<[Source, RenderContext]>} renderMain
117
+ * @property {SyncWaterfallHook<[Source, RenderContext]>} renderContent
105
118
  * @property {SyncWaterfallHook<[Source, RenderContext]>} render
106
119
  * @property {SyncWaterfallHook<[Source, Module, StartupRenderContext]>} renderStartup
107
120
  * @property {SyncWaterfallHook<[string, RenderBootstrapContext]>} renderRequire
@@ -145,6 +158,7 @@ class JavascriptModulesPlugin {
145
158
  "renderContext"
146
159
  ]),
147
160
  render: new SyncWaterfallHook(["source", "renderContext"]),
161
+ renderContent: new SyncWaterfallHook(["source", "renderContext"]),
148
162
  renderStartup: new SyncWaterfallHook([
149
163
  "source",
150
164
  "module",
@@ -462,7 +476,7 @@ class JavascriptModulesPlugin {
462
476
 
463
477
  /**
464
478
  * @param {Module} module the rendered module
465
- * @param {RenderContext} renderContext options object
479
+ * @param {ChunkRenderContext} renderContext options object
466
480
  * @param {CompilationHooks} hooks hooks
467
481
  * @param {boolean | "strict"} factory true: renders as factory method, "strict": renders as factory method already in strict scope, false: pure module content
468
482
  * @returns {Source} the newly generated source from rendering
@@ -471,12 +485,16 @@ class JavascriptModulesPlugin {
471
485
  const { chunk, chunkGraph, runtimeTemplate, codeGenerationResults } =
472
486
  renderContext;
473
487
  try {
474
- const moduleSource = codeGenerationResults.getSource(
475
- module,
476
- chunk.runtime,
477
- "javascript"
478
- );
488
+ const codeGenResult = codeGenerationResults.get(module, chunk.runtime);
489
+ const moduleSource = codeGenResult.sources.get("javascript");
479
490
  if (!moduleSource) return null;
491
+ if (codeGenResult.data !== undefined) {
492
+ const chunkInitFragments = codeGenResult.data.get("chunkInitFragments");
493
+ if (chunkInitFragments) {
494
+ for (const i of chunkInitFragments)
495
+ renderContext.chunkInitFragments.push(i);
496
+ }
497
+ }
480
498
  const moduleSourcePostContent = tryRunOrWebpackError(
481
499
  () =>
482
500
  hooks.renderModuleContent.call(moduleSource, module, renderContext),
@@ -580,20 +598,44 @@ class JavascriptModulesPlugin {
580
598
  "javascript",
581
599
  compareModulesByIdentifier
582
600
  );
601
+ /** @type {ChunkRenderContext} */
602
+ const chunkRenderContext = {
603
+ ...renderContext,
604
+ chunkInitFragments: []
605
+ };
583
606
  const moduleSources =
584
607
  Template.renderChunkModules(
585
- renderContext,
608
+ chunkRenderContext,
586
609
  modules ? Array.from(modules) : [],
587
- module => this.renderModule(module, renderContext, hooks, true)
610
+ module => this.renderModule(module, chunkRenderContext, hooks, true)
588
611
  ) || new RawSource("{}");
589
612
  let source = tryRunOrWebpackError(
590
- () => hooks.renderChunk.call(moduleSources, renderContext),
613
+ () => hooks.renderChunk.call(moduleSources, chunkRenderContext),
591
614
  "JavascriptModulesPlugin.getCompilationHooks().renderChunk"
592
615
  );
593
616
  source = tryRunOrWebpackError(
594
- () => hooks.render.call(source, renderContext),
617
+ () => hooks.renderContent.call(source, chunkRenderContext),
618
+ "JavascriptModulesPlugin.getCompilationHooks().renderContent"
619
+ );
620
+ if (!source) {
621
+ throw new Error(
622
+ "JavascriptModulesPlugin error: JavascriptModulesPlugin.getCompilationHooks().renderContent plugins should return something"
623
+ );
624
+ }
625
+ source = InitFragment.addToSource(
626
+ source,
627
+ chunkRenderContext.chunkInitFragments,
628
+ chunkRenderContext
629
+ );
630
+ source = tryRunOrWebpackError(
631
+ () => hooks.render.call(source, chunkRenderContext),
595
632
  "JavascriptModulesPlugin.getCompilationHooks().render"
596
633
  );
634
+ if (!source) {
635
+ throw new Error(
636
+ "JavascriptModulesPlugin error: JavascriptModulesPlugin.getCompilationHooks().render plugins should return something"
637
+ );
638
+ }
597
639
  chunk.rendered = true;
598
640
  return new ConcatSource(source, ";");
599
641
  }
@@ -607,6 +649,12 @@ class JavascriptModulesPlugin {
607
649
  renderMain(renderContext, hooks, compilation) {
608
650
  const { chunk, chunkGraph, runtimeTemplate } = renderContext;
609
651
 
652
+ /** @type {ChunkRenderContext} */
653
+ const chunkRenderContext = {
654
+ ...renderContext,
655
+ chunkInitFragments: []
656
+ };
657
+
610
658
  const runtimeRequirements = chunkGraph.getTreeRuntimeRequirements(chunk);
611
659
  const iife = runtimeTemplate.isIIFE();
612
660
 
@@ -654,14 +702,14 @@ class JavascriptModulesPlugin {
654
702
  }
655
703
 
656
704
  const chunkModules = Template.renderChunkModules(
657
- renderContext,
705
+ chunkRenderContext,
658
706
  inlinedModules
659
707
  ? allModules.filter(m => !inlinedModules.has(m))
660
708
  : allModules,
661
709
  module =>
662
710
  this.renderModule(
663
711
  module,
664
- renderContext,
712
+ chunkRenderContext,
665
713
  hooks,
666
714
  allStrict ? "strict" : true
667
715
  ),
@@ -670,7 +718,8 @@ class JavascriptModulesPlugin {
670
718
  if (
671
719
  chunkModules ||
672
720
  runtimeRequirements.has(RuntimeGlobals.moduleFactories) ||
673
- runtimeRequirements.has(RuntimeGlobals.moduleFactoriesAddOnly)
721
+ runtimeRequirements.has(RuntimeGlobals.moduleFactoriesAddOnly) ||
722
+ runtimeRequirements.has(RuntimeGlobals.require)
674
723
  ) {
675
724
  source.add(prefix + "var __webpack_modules__ = (");
676
725
  source.add(chunkModules || "{}");
@@ -731,7 +780,7 @@ class JavascriptModulesPlugin {
731
780
  for (const m of inlinedModules) {
732
781
  const renderedModule = this.renderModule(
733
782
  m,
734
- renderContext,
783
+ chunkRenderContext,
735
784
  hooks,
736
785
  false
737
786
  );
@@ -852,6 +901,20 @@ class JavascriptModulesPlugin {
852
901
  "JavascriptModulesPlugin error: JavascriptModulesPlugin.getCompilationHooks().renderMain plugins should return something"
853
902
  );
854
903
  }
904
+ finalSource = tryRunOrWebpackError(
905
+ () => hooks.renderContent.call(finalSource, renderContext),
906
+ "JavascriptModulesPlugin.getCompilationHooks().renderContent"
907
+ );
908
+ if (!finalSource) {
909
+ throw new Error(
910
+ "JavascriptModulesPlugin error: JavascriptModulesPlugin.getCompilationHooks().renderContent plugins should return something"
911
+ );
912
+ }
913
+ finalSource = InitFragment.addToSource(
914
+ finalSource,
915
+ chunkRenderContext.chunkInitFragments,
916
+ chunkRenderContext
917
+ );
855
918
  finalSource = tryRunOrWebpackError(
856
919
  () => hooks.render.call(finalSource, renderContext),
857
920
  "JavascriptModulesPlugin.getCompilationHooks().render"
@@ -25,6 +25,8 @@ const BasicEvaluatedExpression = require("./BasicEvaluatedExpression");
25
25
  /** @typedef {import("estree").Comment} CommentNode */
26
26
  /** @typedef {import("estree").ConditionalExpression} ConditionalExpressionNode */
27
27
  /** @typedef {import("estree").Declaration} DeclarationNode */
28
+ /** @typedef {import("estree").PrivateIdentifier} PrivateIdentifierNode */
29
+ /** @typedef {import("estree").PropertyDefinition} PropertyDefinitionNode */
28
30
  /** @typedef {import("estree").Expression} ExpressionNode */
29
31
  /** @typedef {import("estree").Identifier} IdentifierNode */
30
32
  /** @typedef {import("estree").IfStatement} IfStatementNode */
@@ -128,7 +130,6 @@ const defaultParserOptions = {
128
130
  locations: true,
129
131
  ecmaVersion: "latest",
130
132
  sourceType: "module",
131
- allowAwaitOutsideFunction: true,
132
133
  onComment: null
133
134
  };
134
135
 
@@ -116,7 +116,7 @@ class JsonGenerator extends Generator {
116
116
  * @returns {number} estimate size of the module
117
117
  */
118
118
  getSize(module, type) {
119
- let data = module.buildInfo.jsonData;
119
+ let data = module.buildInfo && module.buildInfo.jsonData;
120
120
  if (!data) return 0;
121
121
  return stringifySafe(data).length + 10;
122
122
  }
@@ -145,7 +145,7 @@ class JsonGenerator extends Generator {
145
145
  concatenationScope
146
146
  }
147
147
  ) {
148
- const data = module.buildInfo.jsonData;
148
+ const data = module.buildInfo && module.buildInfo.jsonData;
149
149
  if (data === undefined) {
150
150
  return new RawSource(
151
151
  runtimeTemplate.missingModuleStatement({
@@ -69,7 +69,7 @@ class NodeTargetPlugin {
69
69
  * @returns {void}
70
70
  */
71
71
  apply(compiler) {
72
- new ExternalsPlugin("commonjs", builtins).apply(compiler);
72
+ new ExternalsPlugin("node-commonjs", builtins).apply(compiler);
73
73
  }
74
74
  }
75
75
 
@@ -12,6 +12,10 @@ const AsyncWasmChunkLoadingRuntimeModule = require("../wasm-async/AsyncWasmChunk
12
12
  /** @typedef {import("../Compiler")} Compiler */
13
13
 
14
14
  class ReadFileCompileAsyncWasmPlugin {
15
+ constructor({ type = "async-node", import: useImport = false } = {}) {
16
+ this._type = type;
17
+ this._import = useImport;
18
+ }
15
19
  /**
16
20
  * Apply the plugin
17
21
  * @param {Compiler} compiler the compiler instance
@@ -28,32 +32,50 @@ class ReadFileCompileAsyncWasmPlugin {
28
32
  options && options.wasmLoading !== undefined
29
33
  ? options.wasmLoading
30
34
  : globalWasmLoading;
31
- return wasmLoading === "async-node";
35
+ return wasmLoading === this._type;
32
36
  };
33
- const generateLoadBinaryCode = path =>
34
- Template.asString([
35
- "new Promise(function (resolve, reject) {",
36
- Template.indent([
37
- "var { readFile } = require('fs');",
38
- "var { join } = require('path');",
39
- "",
40
- "try {",
41
- Template.indent([
42
- `readFile(join(__dirname, ${path}), function(err, buffer){`,
37
+ const generateLoadBinaryCode = this._import
38
+ ? path =>
39
+ Template.asString([
40
+ "Promise.all([import('fs'), import('url')]).then(([{ readFile }, { URL }]) => new Promise((resolve, reject) => {",
43
41
  Template.indent([
44
- "if (err) return reject(err);",
45
- "",
46
- "// Fake fetch response",
47
- "resolve({",
48
- Template.indent(["arrayBuffer() { return buffer; }"]),
42
+ `readFile(new URL(${path}, import.meta.url), (err, buffer) => {`,
43
+ Template.indent([
44
+ "if (err) return reject(err);",
45
+ "",
46
+ "// Fake fetch response",
47
+ "resolve({",
48
+ Template.indent(["arrayBuffer() { return buffer; }"]),
49
+ "});"
50
+ ]),
49
51
  "});"
50
52
  ]),
51
- "});"
52
- ]),
53
- "} catch (err) { reject(err); }"
54
- ]),
55
- "})"
56
- ]);
53
+ "}))"
54
+ ])
55
+ : path =>
56
+ Template.asString([
57
+ "new Promise(function (resolve, reject) {",
58
+ Template.indent([
59
+ "try {",
60
+ Template.indent([
61
+ "var { readFile } = require('fs');",
62
+ "var { join } = require('path');",
63
+ "",
64
+ `readFile(join(__dirname, ${path}), function(err, buffer){`,
65
+ Template.indent([
66
+ "if (err) return reject(err);",
67
+ "",
68
+ "// Fake fetch response",
69
+ "resolve({",
70
+ Template.indent(["arrayBuffer() { return buffer; }"]),
71
+ "});"
72
+ ]),
73
+ "});"
74
+ ]),
75
+ "} catch (err) { reject(err); }"
76
+ ]),
77
+ "})"
78
+ ]);
57
79
 
58
80
  compilation.hooks.runtimeRequirementInTree
59
81
  .for(RuntimeGlobals.instantiateWasm)
@@ -450,7 +450,7 @@ class ModuleConcatenationPlugin {
450
450
  },
451
451
  err => {
452
452
  logger.timeEnd("create concatenated modules");
453
- process.nextTick(() => callback(err));
453
+ process.nextTick(callback.bind(null, err));
454
454
  }
455
455
  );
456
456
  }
@@ -57,19 +57,23 @@ class AsyncModuleRuntimeModule extends HelperRuntimeModule {
57
57
  "completeQueue(queue);",
58
58
  "queue = 0;"
59
59
  ])});`,
60
- `var obj = { [webpackThen]: ${runtimeTemplate.expressionFunction(
60
+ `var obj = {};
61
+ obj[webpackThen] = ${runtimeTemplate.expressionFunction(
61
62
  "queueFunction(queue, fn), dep.catch(reject)",
62
63
  "fn, reject"
63
- )} };`,
64
+ )};`,
64
65
  "return obj;"
65
66
  ]),
66
67
  "}"
67
68
  ]),
68
69
  "}",
69
- `return { [webpackThen]: ${runtimeTemplate.expressionFunction(
70
+ `var ret = {};
71
+ ret[webpackThen] = ${runtimeTemplate.expressionFunction(
70
72
  "completeFunction(fn)",
71
73
  "fn"
72
- )}, [webpackExports]: dep };`
74
+ )};
75
+ ret[webpackExports] = dep;
76
+ return ret;`
73
77
  ])})`,
74
78
  "deps"
75
79
  )};`,
@@ -165,12 +165,23 @@ class BinaryMiddleware extends SerializerMiddleware {
165
165
  };
166
166
  const flush = () => {
167
167
  if (currentBuffer !== null) {
168
- buffers.push(currentBuffer.slice(0, currentPosition));
168
+ buffers.push(
169
+ Buffer.from(
170
+ currentBuffer.buffer,
171
+ currentBuffer.byteOffset,
172
+ currentPosition
173
+ )
174
+ );
169
175
  if (
170
176
  !leftOverBuffer ||
171
177
  leftOverBuffer.length < currentBuffer.length - currentPosition
172
- )
173
- leftOverBuffer = currentBuffer.slice(currentPosition);
178
+ ) {
179
+ leftOverBuffer = Buffer.from(
180
+ currentBuffer.buffer,
181
+ currentBuffer.byteOffset + currentPosition,
182
+ currentBuffer.byteLength - currentPosition
183
+ );
184
+ }
174
185
  currentBuffer = null;
175
186
  buffersTotalLength += currentPosition;
176
187
  currentPosition = 0;
@@ -537,12 +548,7 @@ class BinaryMiddleware extends SerializerMiddleware {
537
548
  const isInCurrentBuffer = n => {
538
549
  return currentIsBuffer && n + currentPosition <= currentBuffer.length;
539
550
  };
540
- /**
541
- * Reads n bytes
542
- * @param {number} n amount of bytes to read
543
- * @returns {Buffer} buffer with bytes
544
- */
545
- const read = n => {
551
+ const ensureBuffer = () => {
546
552
  if (!currentIsBuffer) {
547
553
  throw new Error(
548
554
  currentBuffer === null
@@ -550,14 +556,34 @@ class BinaryMiddleware extends SerializerMiddleware {
550
556
  : "Unexpected lazy element in stream"
551
557
  );
552
558
  }
559
+ };
560
+ /**
561
+ * Reads n bytes
562
+ * @param {number} n amount of bytes to read
563
+ * @returns {Buffer} buffer with bytes
564
+ */
565
+ const read = n => {
566
+ ensureBuffer();
553
567
  const rem = currentBuffer.length - currentPosition;
554
568
  if (rem < n) {
555
- return Buffer.concat([read(rem), read(n - rem)]);
569
+ const buffers = [read(rem)];
570
+ n -= rem;
571
+ ensureBuffer();
572
+ while (currentBuffer.length < n) {
573
+ const b = /** @type {Buffer} */ (currentBuffer);
574
+ buffers.push(b);
575
+ n -= b.length;
576
+ currentDataItem++;
577
+ currentBuffer =
578
+ currentDataItem < data.length ? data[currentDataItem] : null;
579
+ currentIsBuffer = Buffer.isBuffer(currentBuffer);
580
+ ensureBuffer();
581
+ }
582
+ buffers.push(read(n));
583
+ return Buffer.concat(buffers);
556
584
  }
557
- const res = /** @type {Buffer} */ (currentBuffer).slice(
558
- currentPosition,
559
- currentPosition + n
560
- );
585
+ const b = /** @type {Buffer} */ (currentBuffer);
586
+ const res = Buffer.from(b.buffer, b.byteOffset + currentPosition, n);
561
587
  currentPosition += n;
562
588
  checkOverflow();
563
589
  return res;
@@ -568,33 +594,19 @@ class BinaryMiddleware extends SerializerMiddleware {
568
594
  * @returns {Buffer} buffer with bytes
569
595
  */
570
596
  const readUpTo = n => {
571
- if (!currentIsBuffer) {
572
- throw new Error(
573
- currentBuffer === null
574
- ? "Unexpected end of stream"
575
- : "Unexpected lazy element in stream"
576
- );
577
- }
597
+ ensureBuffer();
578
598
  const rem = currentBuffer.length - currentPosition;
579
599
  if (rem < n) {
580
600
  n = rem;
581
601
  }
582
- const res = /** @type {Buffer} */ (currentBuffer).slice(
583
- currentPosition,
584
- currentPosition + n
585
- );
602
+ const b = /** @type {Buffer} */ (currentBuffer);
603
+ const res = Buffer.from(b.buffer, b.byteOffset + currentPosition, n);
586
604
  currentPosition += n;
587
605
  checkOverflow();
588
606
  return res;
589
607
  };
590
608
  const readU8 = () => {
591
- if (!currentIsBuffer) {
592
- throw new Error(
593
- currentBuffer === null
594
- ? "Unexpected end of stream"
595
- : "Unexpected lazy element in stream"
596
- );
597
- }
609
+ ensureBuffer();
598
610
  /**
599
611
  * There is no need to check remaining buffer size here
600
612
  * since {@link checkOverflow} guarantees at least one byte remaining
@@ -735,7 +747,7 @@ class BinaryMiddleware extends SerializerMiddleware {
735
747
  case STRING_HEADER:
736
748
  return () => {
737
749
  const len = readU32();
738
- if (isInCurrentBuffer(len)) {
750
+ if (isInCurrentBuffer(len) && currentPosition + len < 0x7fffffff) {
739
751
  result.push(
740
752
  currentBuffer.toString(
741
753
  undefined,
@@ -753,7 +765,7 @@ class BinaryMiddleware extends SerializerMiddleware {
753
765
  return () => result.push("");
754
766
  case SHORT_STRING_HEADER | 1:
755
767
  return () => {
756
- if (currentIsBuffer) {
768
+ if (currentIsBuffer && currentPosition < 0x7ffffffe) {
757
769
  result.push(
758
770
  currentBuffer.toString(
759
771
  "latin1",
@@ -785,7 +797,10 @@ class BinaryMiddleware extends SerializerMiddleware {
785
797
  } else if ((header & SHORT_STRING_HEADER) === SHORT_STRING_HEADER) {
786
798
  const len = header & SHORT_STRING_LENGTH_MASK;
787
799
  return () => {
788
- if (isInCurrentBuffer(len)) {
800
+ if (
801
+ isInCurrentBuffer(len) &&
802
+ currentPosition + len < 0x7fffffff
803
+ ) {
789
804
  result.push(
790
805
  currentBuffer.toString(
791
806
  "latin1",