rollup 5.0.0-0 → 5.0.0-2

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 (48) hide show
  1. package/LICENSE.md +0 -17
  2. package/dist/bin/rollup +119 -108
  3. package/dist/es/getLogFilter.js +2 -2
  4. package/dist/es/parseAst.js +2 -2
  5. package/dist/es/rollup.js +2 -2
  6. package/dist/es/shared/node-entry.js +1637 -1092
  7. package/dist/es/shared/parseAst.js +123 -31
  8. package/dist/es/shared/watch.js +3204 -1008
  9. package/dist/getLogFilter.js +2 -2
  10. package/dist/loadConfigFile.js +2 -2
  11. package/dist/native.js +6 -1
  12. package/dist/parseAst.js +2 -2
  13. package/dist/rollup.android-arm-eabi.node +0 -0
  14. package/dist/rollup.android-arm64.node +0 -0
  15. package/dist/rollup.android-x64.node +0 -0
  16. package/dist/rollup.d.ts +23 -9
  17. package/dist/rollup.darwin-arm64.node +0 -0
  18. package/dist/rollup.darwin-x64.node +0 -0
  19. package/dist/rollup.freebsd-arm64.node +0 -0
  20. package/dist/rollup.freebsd-x64.node +0 -0
  21. package/dist/rollup.js +2 -2
  22. package/dist/rollup.linux-arm-gnueabihf.node +0 -0
  23. package/dist/rollup.linux-arm-musleabihf.node +0 -0
  24. package/dist/rollup.linux-arm64-gnu.node +0 -0
  25. package/dist/rollup.linux-arm64-musl.node +0 -0
  26. package/dist/rollup.linux-loong64-gnu.node +0 -0
  27. package/dist/rollup.linux-loong64-musl.node +0 -0
  28. package/dist/rollup.linux-ppc64-gnu.node +0 -0
  29. package/dist/rollup.linux-ppc64-musl.node +0 -0
  30. package/dist/rollup.linux-riscv64-gnu.node +0 -0
  31. package/dist/rollup.linux-riscv64-musl.node +0 -0
  32. package/dist/rollup.linux-s390x-gnu.node +0 -0
  33. package/dist/rollup.linux-x64-gnu.node +0 -0
  34. package/dist/rollup.linux-x64-musl.node +0 -0
  35. package/dist/rollup.openbsd-x64.node +0 -0
  36. package/dist/rollup.openharmony-arm64.node +0 -0
  37. package/dist/rollup.win32-arm64-msvc.node +0 -0
  38. package/dist/rollup.win32-ia32-msvc.node +0 -0
  39. package/dist/rollup.win32-x64-gnu.node +0 -0
  40. package/dist/rollup.win32-x64-msvc.node +0 -0
  41. package/dist/shared/index.js +3198 -1002
  42. package/dist/shared/loadConfigFile.js +2 -2
  43. package/dist/shared/node-entry.js +2 -2
  44. package/dist/shared/parseAst.js +129 -37
  45. package/dist/shared/rollup.js +1594 -1049
  46. package/dist/shared/watch-cli.js +2 -2
  47. package/dist/shared/watch.js +2 -2
  48. package/package.json +54 -51
@@ -1,7 +1,7 @@
1
1
  /*
2
2
  @license
3
- Rollup.js v5.0.0-0
4
- Tue, 06 Oct 2026 08:24:44 GMT - commit d78bf6bee48e411672e05d8977473f76e6758c35
3
+ Rollup.js v5.0.0-2
4
+ Sun, 01 Nov 2026 08:56:25 GMT - commit 4009894760dbcbff5ba6cefa494787cc54ffaa62
5
5
 
6
6
  https://github.com/rollup/rollup
7
7
 
@@ -42,7 +42,7 @@ function _mergeNamespaces(n, m) {
42
42
 
43
43
  const promises__namespace = /*#__PURE__*/_interopNamespaceDefault(promises);
44
44
 
45
- var version = "5.0.0-0";
45
+ var version = "5.0.0-2";
46
46
  const package_ = {
47
47
  version: version};
48
48
 
@@ -392,22 +392,20 @@ function makeUnique(name, { [lowercaseBundleKeys]: reservedLowercaseBundleKeys }
392
392
  function generateAssetFileName(name, names, source, originalFileName, originalFileNames, sourceHash, outputOptions, bundle, inputOptions) {
393
393
  const emittedName = outputOptions.sanitizeFileName(name || 'asset');
394
394
  return makeUnique(renderNamePattern(typeof outputOptions.assetFileNames === 'function'
395
- ? outputOptions.assetFileNames({
396
- // Additionally, this should be non-enumerable in the next major
395
+ ? outputOptions.assetFileNames(makeDeprecatedAssetPropertiesNonEnumerable({
397
396
  get name() {
398
- parseAst_js.warnDeprecation('Accessing the "name" property of emitted assets when generating the file name is deprecated. Use the "names" property instead.', parseAst_js.URL_GENERATEBUNDLE, false, inputOptions);
397
+ parseAst_js.warnDeprecation('Accessing the "name" property of emitted assets when generating the file name is deprecated. Use the "names" property instead.', parseAst_js.URL_GENERATEBUNDLE, true, inputOptions);
399
398
  return name;
400
399
  },
401
400
  names,
402
- // Additionally, this should be non-enumerable in the next major
403
401
  get originalFileName() {
404
- parseAst_js.warnDeprecation('Accessing the "originalFileName" property of emitted assets when generating the file name is deprecated. Use the "originalFileNames" property instead.', parseAst_js.URL_GENERATEBUNDLE, false, inputOptions);
402
+ parseAst_js.warnDeprecation('Accessing the "originalFileName" property of emitted assets when generating the file name is deprecated. Use the "originalFileNames" property instead.', parseAst_js.URL_GENERATEBUNDLE, true, inputOptions);
405
403
  return originalFileName;
406
404
  },
407
405
  originalFileNames,
408
406
  source,
409
407
  type: 'asset'
410
- })
408
+ }))
411
409
  : outputOptions.assetFileNames, 'output.assetFileNames', {
412
410
  ext: () => sp.extname(emittedName).slice(1),
413
411
  extname: () => sp.extname(emittedName),
@@ -697,50 +695,44 @@ class FileEmitter {
697
695
  const existingAsset = bundle[fileName];
698
696
  if (existingAsset?.type === 'asset') {
699
697
  existingAsset.needsCodeReference &&= needsCodeReference;
700
- if (name) {
698
+ if (name && !existingAsset.names.includes(name)) {
701
699
  existingAsset.names.push(name);
702
700
  }
703
- if (originalFileName) {
701
+ if (originalFileName && !existingAsset.originalFileNames.includes(originalFileName)) {
704
702
  existingAsset.originalFileNames.push(originalFileName);
705
703
  }
706
704
  }
707
705
  else {
708
706
  const { options } = this;
709
- bundle[fileName] = {
707
+ bundle[fileName] = makeDeprecatedAssetPropertiesNonEnumerable({
710
708
  fileName,
711
709
  get name() {
712
- // Additionally, this should be non-enumerable in the next major
713
- parseAst_js.warnDeprecation('Accessing the "name" property of emitted assets in the bundle is deprecated. Use the "names" property instead.', parseAst_js.URL_GENERATEBUNDLE, false, options);
710
+ parseAst_js.warnDeprecation('Accessing the "name" property of emitted assets in the bundle is deprecated. Use the "names" property instead.', parseAst_js.URL_GENERATEBUNDLE, true, options);
714
711
  return name;
715
712
  },
716
713
  names: name ? [name] : [],
717
714
  needsCodeReference,
718
715
  get originalFileName() {
719
- // Additionally, this should be non-enumerable in the next major
720
- parseAst_js.warnDeprecation('Accessing the "originalFileName" property of emitted assets in the bundle is deprecated. Use the "originalFileNames" property instead.', parseAst_js.URL_GENERATEBUNDLE, false, options);
716
+ parseAst_js.warnDeprecation('Accessing the "originalFileName" property of emitted assets in the bundle is deprecated. Use the "originalFileNames" property instead.', parseAst_js.URL_GENERATEBUNDLE, true, options);
721
717
  return originalFileName;
722
718
  },
723
719
  originalFileNames: originalFileName ? [originalFileName] : [],
724
720
  source,
725
721
  type: 'asset'
726
- };
722
+ });
727
723
  }
728
724
  }
729
725
  finalizeAssetsWithSameSource(consumedFiles, sourceHash, { bundle, fileNamesBySourceHash, outputOptions }) {
730
726
  const { names, originalFileNames } = getNamesFromAssets(consumedFiles);
731
- let fileName = '';
732
- let usedConsumedFile;
727
+ let representative = consumedFiles[0];
733
728
  let needsCodeReference = true;
734
729
  for (const consumedFile of consumedFiles) {
735
730
  needsCodeReference &&= consumedFile.needsCodeReference;
736
- const assetFileName = generateAssetFileName(consumedFile.name, names, consumedFile.source, consumedFile.originalFileName, originalFileNames, sourceHash, outputOptions, bundle, this.options);
737
- if (!fileName ||
738
- assetFileName.length < fileName.length ||
739
- (assetFileName.length === fileName.length && assetFileName < fileName)) {
740
- fileName = assetFileName;
741
- usedConsumedFile = consumedFile;
731
+ if (compareConsumedAssets(consumedFile, representative) < 0) {
732
+ representative = consumedFile;
742
733
  }
743
734
  }
735
+ const fileName = generateAssetFileName(representative.name, names, representative.source, representative.originalFileName, originalFileNames, sourceHash, outputOptions, bundle, this.options);
744
736
  fileNamesBySourceHash.set(sourceHash, fileName);
745
737
  for (const consumedFile of consumedFiles) {
746
738
  // We must not modify the original assets to avoid interaction between outputs
@@ -748,42 +740,53 @@ class FileEmitter {
748
740
  this.filesByReferenceId.set(consumedFile.referenceId, assetWithFileName);
749
741
  }
750
742
  const { options } = this;
751
- bundle[fileName] = {
743
+ bundle[fileName] = makeDeprecatedAssetPropertiesNonEnumerable({
752
744
  fileName,
753
745
  get name() {
754
- // Additionally, this should be non-enumerable in the next major
755
- parseAst_js.warnDeprecation('Accessing the "name" property of emitted assets in the bundle is deprecated. Use the "names" property instead.', parseAst_js.URL_GENERATEBUNDLE, false, options);
756
- return usedConsumedFile.name;
746
+ parseAst_js.warnDeprecation('Accessing the "name" property of emitted assets in the bundle is deprecated. Use the "names" property instead.', parseAst_js.URL_GENERATEBUNDLE, true, options);
747
+ return representative.name;
757
748
  },
758
749
  names,
759
750
  needsCodeReference,
760
751
  get originalFileName() {
761
- // Additionally, this should be non-enumerable in the next major
762
- parseAst_js.warnDeprecation('Accessing the "originalFileName" property of emitted assets in the bundle is deprecated. Use the "originalFileNames" property instead.', parseAst_js.URL_GENERATEBUNDLE, false, options);
763
- return usedConsumedFile.originalFileName;
752
+ parseAst_js.warnDeprecation('Accessing the "originalFileName" property of emitted assets in the bundle is deprecated. Use the "originalFileNames" property instead.', parseAst_js.URL_GENERATEBUNDLE, true, options);
753
+ return representative.originalFileName;
764
754
  },
765
755
  originalFileNames,
766
- source: usedConsumedFile.source,
756
+ source: representative.source,
767
757
  type: 'asset'
768
- };
758
+ });
759
+ }
760
+ }
761
+ function makeDeprecatedAssetPropertiesNonEnumerable(asset) {
762
+ for (const property of ['name', 'originalFileName']) {
763
+ const descriptor = Object.getOwnPropertyDescriptor(asset, property);
764
+ Object.defineProperty(asset, property, { ...descriptor, enumerable: false });
769
765
  }
766
+ return asset;
770
767
  }
768
+ const compareNames = (a, b) => a.length - b.length || (a < b ? -1 : a > b ? 1 : 0);
769
+ const compareOptionalNames = (a, b) => a === b ? 0 : a == null ? 1 : b == null ? -1 : a < b ? -1 : 1;
770
+ const compareSourceTypes = (a, b) => typeof a === 'string' ? (typeof b === 'string' ? 0 : -1) : typeof b === 'string' ? 1 : 0;
771
+ const compareConsumedAssets = (a, b) => compareNames(a.name || 'asset', b.name || 'asset') ||
772
+ compareOptionalNames(a.originalFileName, b.originalFileName) ||
773
+ compareOptionalNames(a.name, b.name) ||
774
+ compareSourceTypes(a.source, b.source);
771
775
  function getNamesFromAssets(consumedFiles) {
772
- const names = [];
773
- const originalFileNames = [];
776
+ const names = new Set();
777
+ const originalFileNames = new Set();
774
778
  for (const { name, originalFileName } of consumedFiles) {
775
779
  if (typeof name === 'string') {
776
- names.push(name);
780
+ names.add(name);
777
781
  }
778
782
  if (originalFileName) {
779
- originalFileNames.push(originalFileName);
783
+ originalFileNames.add(originalFileName);
780
784
  }
781
785
  }
782
- originalFileNames.sort();
783
- // Sort by length first and then alphabetically so that the order is stable
784
- // and the shortest names come first
785
- names.sort((a, b) => a.length - b.length || (a > b ? 1 : a === b ? 0 : -1));
786
- return { names, originalFileNames };
786
+ return {
787
+ names: [...names].sort(compareNames),
788
+ originalFileNames: [...originalFileNames].sort()
789
+ };
787
790
  }
788
791
 
789
792
  function getLogHandler(level, code, logger, pluginName, logLevel) {
@@ -4078,7 +4081,6 @@ async function mergeOutputOptions(config, overrides, log) {
4078
4081
  experimentalMinChunkSize: getOption('experimentalMinChunkSize'),
4079
4082
  exports: getOption('exports'),
4080
4083
  extend: getOption('extend'),
4081
- externalImportAssertions: getOption('externalImportAssertions'),
4082
4084
  externalImportAttributes: getOption('externalImportAttributes'),
4083
4085
  externalLiveBindings: getOption('externalLiveBindings'),
4084
4086
  file: getOption('file'),
@@ -4458,6 +4460,17 @@ var BitSet = class BitSet {
4458
4460
  has(n) {
4459
4461
  return !!(this.bits[n >> 5] & 1 << (n & 31));
4460
4462
  }
4463
+ forEach(fn) {
4464
+ const bits = this.bits;
4465
+ for (let w = 0; w < bits.length; w++) {
4466
+ let word = bits[w];
4467
+ while (word) {
4468
+ const lowest = word & -word;
4469
+ fn((w << 5) + 31 - Math.clz32(lowest));
4470
+ word ^= lowest;
4471
+ }
4472
+ }
4473
+ }
4461
4474
  };
4462
4475
  //#endregion
4463
4476
  //#region src/Chunk.ts
@@ -4471,6 +4484,8 @@ var Chunk$1 = class Chunk {
4471
4484
  this.content = content;
4472
4485
  this.storeName = false;
4473
4486
  this.edited = false;
4487
+ this.replacesUntil = -1;
4488
+ this.replacedFrom = -1;
4474
4489
  this.previous = null;
4475
4490
  this.next = null;
4476
4491
  }
@@ -4487,6 +4502,8 @@ var Chunk$1 = class Chunk {
4487
4502
  chunk.content = this.content;
4488
4503
  chunk.storeName = this.storeName;
4489
4504
  chunk.edited = this.edited;
4505
+ chunk.replacesUntil = this.replacesUntil;
4506
+ chunk.replacedFrom = this.replacedFrom;
4490
4507
  return chunk;
4491
4508
  }
4492
4509
  contains(index) {
@@ -4527,6 +4544,8 @@ var Chunk$1 = class Chunk {
4527
4544
  reset() {
4528
4545
  this.intro = "";
4529
4546
  this.outro = "";
4547
+ this.replacesUntil = -1;
4548
+ this.replacedFrom = -1;
4530
4549
  if (this.edited) {
4531
4550
  this.content = this.original;
4532
4551
  this.storeName = false;
@@ -4544,7 +4563,7 @@ var Chunk$1 = class Chunk {
4544
4563
  this.end = index;
4545
4564
  if (this.edited) {
4546
4565
  newChunk.edit("", false, true);
4547
- this.content = "";
4566
+ newChunk.replacedFrom = this.replacedFrom;
4548
4567
  } else this.content = originalBefore;
4549
4568
  newChunk.next = this.next;
4550
4569
  if (newChunk.next) newChunk.next.previous = newChunk;
@@ -4808,8 +4827,8 @@ var Mappings = class {
4808
4827
  this.generatedCodeColumn = 0;
4809
4828
  this.raw = [];
4810
4829
  this.rawSegments = this.raw[this.generatedCodeLine] = [];
4811
- this.rawRangeMappings = [];
4812
- this.rawRangeMappingsIndices = this.rawRangeMappings[this.generatedCodeLine] = [];
4830
+ this.rawRangeMappingsIndices = [];
4831
+ this.rawRangeMappings = hires === "experimental-range" ? [this.rawRangeMappingsIndices] : void 0;
4813
4832
  this.encoder = encoder;
4814
4833
  }
4815
4834
  nextLine() {
@@ -4822,7 +4841,28 @@ var Mappings = class {
4822
4841
  this.generatedCodeLine += 1;
4823
4842
  }
4824
4843
  this.generatedCodeColumn = 0;
4825
- this.rawRangeMappings[this.generatedCodeLine] = this.rawRangeMappingsIndices = [];
4844
+ if (this.rawRangeMappings) this.rawRangeMappings[this.generatedCodeLine] = this.rawRangeMappingsIndices = [];
4845
+ }
4846
+ /**
4847
+ * Emits the mappings for one MagicString: its intro, every chunk (with the
4848
+ * chunk's own intro/outro) and its outro. `sourceIndex === -1` means the
4849
+ * string has no source of its own, so its content only advances the
4850
+ * generated position without mapping anything.
4851
+ */
4852
+ addMagicString(magicString, sourceIndex, nameIndex) {
4853
+ const { original } = magicString;
4854
+ const locate = getLocator(original);
4855
+ if (magicString.intro) this.advance(magicString.intro);
4856
+ magicString.firstChunk.eachNext((chunk) => {
4857
+ if (chunk.intro.length) this.advance(chunk.intro);
4858
+ if (sourceIndex === -1) this.advance(chunk.content);
4859
+ else if (chunk.edited) {
4860
+ const name = chunk.storeName ? nameIndex.get(original.slice(chunk.start, chunk.replacesUntil)) : void 0;
4861
+ this.addEdit(sourceIndex, chunk.content, locate(chunk.start), name ?? -1);
4862
+ } else this.addUneditedChunk(sourceIndex, chunk, original, locate(chunk.start), magicString.sourcemapLocations);
4863
+ if (chunk.outro.length) this.advance(chunk.outro);
4864
+ });
4865
+ if (magicString.outro) this.advance(magicString.outro);
4826
4866
  }
4827
4867
  addEdit(sourceIndex, content, loc, nameIndex) {
4828
4868
  if (content.length) {
@@ -5037,6 +5077,9 @@ function expandReplacement(replacement, matched, position, str, captures, namedC
5037
5077
  return result;
5038
5078
  }
5039
5079
  var MagicString = class MagicString {
5080
+ /**
5081
+ * Wraps `string` for editing; every index passed to the editing methods refers to this original string.
5082
+ */
5040
5083
  constructor(string, options = {}) {
5041
5084
  const chunk = new Chunk$1(0, string.length, string);
5042
5085
  Object.defineProperties(this, {
@@ -5086,7 +5129,7 @@ var MagicString = class MagicString {
5086
5129
  },
5087
5130
  storedNames: {
5088
5131
  writable: true,
5089
- value: {}
5132
+ value: /* @__PURE__ */ new Set()
5090
5133
  },
5091
5134
  indentStr: {
5092
5135
  writable: true,
@@ -5126,7 +5169,8 @@ var MagicString = class MagicString {
5126
5169
  * See also `s.prependLeft(...)`.
5127
5170
  */
5128
5171
  appendLeft(index, content) {
5129
- index = index + this.offset;
5172
+ index = this._resolveIndex(index);
5173
+ if (index < 0 || index > this.original.length) throw new MagicStringError(`index ${index} is out of bounds`);
5130
5174
  if (typeof content !== "string") throw new MagicStringError(`content must be a string, got ${typeof content}`);
5131
5175
  this._split(index);
5132
5176
  const chunk = this.byEnd.get(index);
@@ -5140,7 +5184,8 @@ var MagicString = class MagicString {
5140
5184
  * See also `s.prependRight(...)`.
5141
5185
  */
5142
5186
  appendRight(index, content) {
5143
- index = index + this.offset;
5187
+ index = this._resolveIndex(index);
5188
+ if (index < 0 || index > this.original.length) throw new MagicStringError(`index ${index} is out of bounds`);
5144
5189
  if (typeof content !== "string") throw new MagicStringError(`content must be a string, got ${typeof content}`);
5145
5190
  this._split(index);
5146
5191
  const chunk = this.byStart.get(index);
@@ -5149,7 +5194,10 @@ var MagicString = class MagicString {
5149
5194
  return this;
5150
5195
  }
5151
5196
  /**
5152
- * Does what you'd expect.
5197
+ * Returns an independent copy: the chunk list, string-level intro/outro,
5198
+ * sourcemap locations, stored names, indent exclusion ranges, `offset`,
5199
+ * `filename` and `ignoreList` are all copied; later edits to either string
5200
+ * do not affect the other.
5153
5201
  */
5154
5202
  clone() {
5155
5203
  const cloned = new MagicString(this.original, {
@@ -5174,7 +5222,7 @@ var MagicString = class MagicString {
5174
5222
  cloned.lastChunk = clonedChunk;
5175
5223
  if (this.indentExclusionRanges) cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
5176
5224
  cloned.sourcemapLocations = new BitSet(this.sourcemapLocations);
5177
- cloned.storedNames = { ...this.storedNames };
5225
+ cloned.storedNames = new Set(this.storedNames);
5178
5226
  cloned.intro = this.intro;
5179
5227
  cloned.outro = this.outro;
5180
5228
  cloned.hasMovedChunks = this.hasMovedChunks;
@@ -5210,18 +5258,8 @@ var MagicString = class MagicString {
5210
5258
  }
5211
5259
  /** @internal */
5212
5260
  _generateMappings(mappings) {
5213
- const sourceIndex = 0;
5214
- const names = Object.keys(this.storedNames);
5215
- const locate = getLocator(this.original);
5216
- if (this.intro) mappings.advance(this.intro);
5217
- this.firstChunk.eachNext((chunk) => {
5218
- const loc = locate(chunk.start);
5219
- if (chunk.intro.length) mappings.advance(chunk.intro);
5220
- if (chunk.edited) mappings.addEdit(sourceIndex, chunk.content, loc, chunk.storeName ? names.indexOf(chunk.original) : -1);
5221
- else mappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations);
5222
- if (chunk.outro.length) mappings.advance(chunk.outro);
5223
- });
5224
- if (this.outro) mappings.advance(this.outro);
5261
+ const names = [...this.storedNames];
5262
+ mappings.addMagicString(this, 0, new Map(names.map((name, i) => [name, i])));
5225
5263
  return names;
5226
5264
  }
5227
5265
  /** @internal */
@@ -5243,9 +5281,13 @@ var MagicString = class MagicString {
5243
5281
  this._ensureindentStr();
5244
5282
  return this.indentStr;
5245
5283
  }
5284
+ /**
5285
+ * Returns the indentation string guessed from the original content, falling back to a single tab character.
5286
+ * This is the value `s.indent()` uses when no prefix is supplied.
5287
+ */
5246
5288
  getIndentString() {
5247
5289
  this._ensureindentStr();
5248
- return this.indentStr === null ? " " : this.indentStr;
5290
+ return this.indentStr ?? " ";
5249
5291
  }
5250
5292
  indent(indentStr, options) {
5251
5293
  const pattern = /^[^\r\n]/gm;
@@ -5260,9 +5302,9 @@ var MagicString = class MagicString {
5260
5302
  if (indentStr === "") return this;
5261
5303
  const resolvedIndentStr = indentStr;
5262
5304
  options = options || {};
5263
- const isExcluded = {};
5305
+ const isExcluded = new BitSet();
5264
5306
  if (options.exclude) (typeof options.exclude[0] === "number" ? [options.exclude] : options.exclude).forEach((exclusion) => {
5265
- for (let i = exclusion[0]; i < exclusion[1]; i += 1) isExcluded[i] = true;
5307
+ for (let i = exclusion[0]; i < exclusion[1]; i += 1) isExcluded.add(i);
5266
5308
  });
5267
5309
  let shouldIndentNextCharacter = options.indentStart !== false;
5268
5310
  const indentPiece = (str) => {
@@ -5285,13 +5327,14 @@ var MagicString = class MagicString {
5285
5327
  };
5286
5328
  while (chunk) {
5287
5329
  const end = chunk.end;
5288
- if (!isExcluded[chunk.start]) chunk.intro = indentPiece(chunk.intro);
5330
+ if (!isExcluded.has(chunk.start)) chunk.intro = indentPiece(chunk.intro);
5289
5331
  if (chunk.edited) {
5290
- if (!isExcluded[charIndex]) chunk.content = indentPiece(chunk.content);
5332
+ if (!isExcluded.has(chunk.start)) chunk.content = indentPiece(chunk.content);
5333
+ else if (chunk.content) shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === "\n";
5291
5334
  } else if (options.exclude) {
5292
5335
  charIndex = chunk.start;
5293
5336
  while (charIndex < end) {
5294
- if (!isExcluded[charIndex]) {
5337
+ if (!isExcluded.has(charIndex)) {
5295
5338
  const char = this.original.charCodeAt(charIndex);
5296
5339
  if (char === NEWLINE_CHAR) shouldIndentNextCharacter = true;
5297
5340
  else if (char !== CR_CHAR && shouldIndentNextCharacter) indentAt(charIndex);
@@ -5317,7 +5360,7 @@ var MagicString = class MagicString {
5317
5360
  charIndex += 1;
5318
5361
  }
5319
5362
  }
5320
- if (!isExcluded[chunk.end - 1]) chunk.outro = indentPiece(chunk.outro);
5363
+ if (!isExcluded.has(chunk.end - 1)) chunk.outro = indentPiece(chunk.outro);
5321
5364
  charIndex = chunk.end;
5322
5365
  chunk = chunk.next;
5323
5366
  }
@@ -5354,16 +5397,19 @@ var MagicString = class MagicString {
5354
5397
  * mirroring the `appendLeft`/`appendRight` distinction.
5355
5398
  */
5356
5399
  move(start, end, index, affinity = "right") {
5357
- start = start + this.offset;
5358
- end = end + this.offset;
5359
- index = index + this.offset;
5400
+ start = this._resolveIndex(start);
5401
+ end = this._resolveIndex(end);
5402
+ index = this._resolveIndex(index);
5360
5403
  if (start === end) return this;
5404
+ if (start < 0 || end > this.original.length || index < 0 || index > this.original.length) throw new MagicStringError(`range ${start}–${end} is out of bounds`);
5405
+ if (start > end) throw new MagicStringError(`end must be greater than start (start: ${start}, end: ${end})`);
5361
5406
  if (index >= start && index <= end) throw new MagicStringError("cannot move a selection inside itself");
5362
5407
  this._split(start);
5363
5408
  this._split(end);
5364
5409
  this._split(index);
5365
5410
  const first = this.byStart.get(start);
5366
5411
  const last = this.byEnd.get(end);
5412
+ if (!first || !last) throw new MagicStringError(`range ${start}–${end} is out of bounds`);
5367
5413
  if (this.hasMovedChunks) {
5368
5414
  let cursor = first;
5369
5415
  while (cursor !== last) {
@@ -5398,9 +5444,9 @@ var MagicString = class MagicString {
5398
5444
  if (oldRight) oldRight.previous = oldLeft;
5399
5445
  if (newLeft) newLeft.next = first;
5400
5446
  if (newRight) newRight.previous = last;
5401
- if (!first.previous) this.firstChunk = last.next;
5402
- if (!last.next) {
5403
- this.lastChunk = first.previous;
5447
+ if (!oldLeft) this.firstChunk = oldRight;
5448
+ if (!oldRight) {
5449
+ this.lastChunk = oldLeft;
5404
5450
  this.lastChunk.next = null;
5405
5451
  }
5406
5452
  first.previous = newLeft;
@@ -5421,6 +5467,16 @@ var MagicString = class MagicString {
5421
5467
  * It may be preferred to use `s.update(...)` instead if you wish to avoid overwriting the appended/prepended content.
5422
5468
  */
5423
5469
  overwrite(start, end, content, options) {
5470
+ if (options === true) {
5471
+ if (!warned.storeName) {
5472
+ console.warn("The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string");
5473
+ warned.storeName = true;
5474
+ }
5475
+ return this.update(start, end, content, {
5476
+ storeName: true,
5477
+ overwrite: true
5478
+ });
5479
+ }
5424
5480
  const optionObject = typeof options === "object" && options ? options : {};
5425
5481
  return this.update(start, end, content, {
5426
5482
  ...optionObject,
@@ -5435,13 +5491,9 @@ var MagicString = class MagicString {
5435
5491
  * the content is overwritten, or anything that was appended/prepended to the range as well.
5436
5492
  */
5437
5493
  update(start, end, content, options) {
5438
- start = start + this.offset;
5439
- end = end + this.offset;
5494
+ start = this._resolveIndex(start);
5495
+ end = this._resolveIndex(end);
5440
5496
  if (typeof content !== "string") throw new MagicStringError(`content must be a string, got ${typeof content}`);
5441
- if (this.original.length !== 0) {
5442
- if (start < 0) start = Math.max(0, start + this.original.length);
5443
- if (end < 0) end = Math.max(0, end + this.original.length);
5444
- }
5445
5497
  if (start < 0) throw new MagicStringError(`start ${start} is out of bounds`);
5446
5498
  if (end > this.original.length) throw new MagicStringError(`end ${end} is out of bounds`);
5447
5499
  if (start === end) throw new MagicStringError(`cannot overwrite a zero-length range at ${start}, use appendLeft() or prependRight()`);
@@ -5458,30 +5510,21 @@ var MagicString = class MagicString {
5458
5510
  const optionObject = typeof options === "object" && options ? options : {};
5459
5511
  const storeName = optionObject.storeName || false;
5460
5512
  const overwrite = optionObject.overwrite || false;
5461
- if (storeName) {
5462
- const original = this.original.slice(start, end);
5463
- Object.defineProperty(this.storedNames, original, {
5464
- writable: true,
5465
- value: true,
5466
- enumerable: true
5467
- });
5468
- }
5513
+ if (storeName) this.storedNames.add(this.original.slice(start, end));
5469
5514
  const first = this.byStart.get(start);
5470
- const last = this.byEnd.get(end);
5471
- /* v8 ignore else -- unreachable: a valid start/end always yields a `first` chunk */
5472
- if (first) {
5473
- let chunk = first;
5474
- while (chunk !== last) {
5475
- if (chunk.next !== this.byStart.get(chunk.end)) throw new MagicStringError("cannot overwrite across a split point");
5476
- chunk = chunk.next;
5477
- chunk.edit("", false);
5478
- }
5479
- first.edit(content, storeName, !overwrite);
5480
- } else {
5481
- const newChunk = new Chunk$1(start, end, "").edit(content, storeName);
5482
- last.next = newChunk;
5483
- newChunk.previous = last;
5515
+ for (let chunk = first; chunk.end < end;) {
5516
+ const next = chunk.next;
5517
+ if (next === null || next !== this.byStart.get(chunk.end)) throw new MagicStringError("cannot overwrite across a split point");
5518
+ chunk = next;
5519
+ }
5520
+ for (let chunk = first.next; chunk !== null && chunk.start < end; chunk = chunk.next) {
5521
+ chunk.edit("", false, !overwrite);
5522
+ chunk.replacesUntil = -1;
5523
+ chunk.replacedFrom = start;
5484
5524
  }
5525
+ first.edit(content, storeName, !overwrite);
5526
+ first.replacesUntil = end;
5527
+ first.replacedFrom = -1;
5485
5528
  return this;
5486
5529
  }
5487
5530
  /**
@@ -5496,7 +5539,8 @@ var MagicString = class MagicString {
5496
5539
  * Same as `s.appendLeft(...)`, except that the inserted content will go *before* any previous appends or prepends at index
5497
5540
  */
5498
5541
  prependLeft(index, content) {
5499
- index = index + this.offset;
5542
+ index = this._resolveIndex(index);
5543
+ if (index < 0 || index > this.original.length) throw new MagicStringError(`index ${index} is out of bounds`);
5500
5544
  if (typeof content !== "string") throw new MagicStringError(`content must be a string, got ${typeof content}`);
5501
5545
  this._split(index);
5502
5546
  const chunk = this.byEnd.get(index);
@@ -5508,7 +5552,8 @@ var MagicString = class MagicString {
5508
5552
  * Same as `s.appendRight(...)`, except that the inserted content will go *before* any previous appends or prepends at `index`
5509
5553
  */
5510
5554
  prependRight(index, content) {
5511
- index = index + this.offset;
5555
+ index = this._resolveIndex(index);
5556
+ if (index < 0 || index > this.original.length) throw new MagicStringError(`index ${index} is out of bounds`);
5512
5557
  if (typeof content !== "string") throw new MagicStringError(`content must be a string, got ${typeof content}`);
5513
5558
  this._split(index);
5514
5559
  const chunk = this.byStart.get(index);
@@ -5524,12 +5569,8 @@ var MagicString = class MagicString {
5524
5569
  * Repeated removals and removals with partially overlapping ranges are allowed.
5525
5570
  */
5526
5571
  remove(start, end) {
5527
- start = start + this.offset;
5528
- end = end + this.offset;
5529
- if (this.original.length !== 0) {
5530
- if (start < 0) start = Math.max(0, start + this.original.length);
5531
- if (end < 0) end = Math.max(0, end + this.original.length);
5532
- }
5572
+ start = this._resolveIndex(start);
5573
+ end = this._resolveIndex(end);
5533
5574
  if (start === end) return this;
5534
5575
  if (start < 0 || end > this.original.length) throw new MagicStringError(`range ${start}–${end} is out of bounds`);
5535
5576
  if (start > end) throw new MagicStringError(`end must be greater than start (start: ${start}, end: ${end})`);
@@ -5540,7 +5581,9 @@ var MagicString = class MagicString {
5540
5581
  if (chunk.start > start) chunk.intro = "";
5541
5582
  if (chunk.end < end) chunk.outro = "";
5542
5583
  chunk.edit("", false, true);
5543
- chunk = end > chunk.end ? this.byStart.get(chunk.end) : null;
5584
+ chunk.replacesUntil = -1;
5585
+ chunk.replacedFrom = -1;
5586
+ chunk = end > chunk.end ? this.byStart.get(chunk.end) : void 0;
5544
5587
  }
5545
5588
  return this;
5546
5589
  }
@@ -5548,12 +5591,8 @@ var MagicString = class MagicString {
5548
5591
  * Reset the modified characters from `start` to `end` (of the original string, **not** the generated string).
5549
5592
  */
5550
5593
  reset(start, end) {
5551
- start = start + this.offset;
5552
- end = end + this.offset;
5553
- if (this.original.length !== 0) {
5554
- if (start < 0) start = Math.max(0, start + this.original.length);
5555
- if (end < 0) end = Math.max(0, end + this.original.length);
5556
- }
5594
+ start = this._resolveIndex(start);
5595
+ end = this._resolveIndex(end);
5557
5596
  if (start === end) return this;
5558
5597
  if (start < 0 || end > this.original.length) throw new MagicStringError(`range ${start}–${end} is out of bounds`);
5559
5598
  if (start > end) throw new MagicStringError(`end must be greater than start (start: ${start}, end: ${end})`);
@@ -5562,10 +5601,13 @@ var MagicString = class MagicString {
5562
5601
  let chunk = this.byStart.get(start);
5563
5602
  while (chunk) {
5564
5603
  chunk.reset();
5565
- chunk = end > chunk.end ? this.byStart.get(chunk.end) : null;
5604
+ chunk = end > chunk.end ? this.byStart.get(chunk.end) : void 0;
5566
5605
  }
5567
5606
  return this;
5568
5607
  }
5608
+ /**
5609
+ * Returns the last character of the generated string, or `''` if it is empty.
5610
+ */
5569
5611
  lastChar() {
5570
5612
  if (this.outro.length) return this.outro[this.outro.length - 1];
5571
5613
  let chunk = this.lastChunk;
@@ -5578,49 +5620,57 @@ var MagicString = class MagicString {
5578
5620
  if (this.intro.length) return this.intro[this.intro.length - 1];
5579
5621
  return "";
5580
5622
  }
5623
+ /**
5624
+ * Returns everything after the last newline in the generated string, or the whole string if there is no newline.
5625
+ */
5581
5626
  lastLine() {
5582
5627
  let lineIndex = this.outro.lastIndexOf(n);
5583
- if (lineIndex !== -1) return this.outro.substr(lineIndex + 1);
5628
+ if (lineIndex !== -1) return this.outro.slice(lineIndex + 1);
5584
5629
  let lineStr = this.outro;
5585
5630
  let chunk = this.lastChunk;
5586
5631
  while (chunk) {
5587
5632
  if (chunk.outro.length > 0) {
5588
5633
  lineIndex = chunk.outro.lastIndexOf(n);
5589
- if (lineIndex !== -1) return chunk.outro.substr(lineIndex + 1) + lineStr;
5634
+ if (lineIndex !== -1) return chunk.outro.slice(lineIndex + 1) + lineStr;
5590
5635
  lineStr = chunk.outro + lineStr;
5591
5636
  }
5592
5637
  if (chunk.content.length > 0) {
5593
5638
  lineIndex = chunk.content.lastIndexOf(n);
5594
- if (lineIndex !== -1) return chunk.content.substr(lineIndex + 1) + lineStr;
5639
+ if (lineIndex !== -1) return chunk.content.slice(lineIndex + 1) + lineStr;
5595
5640
  lineStr = chunk.content + lineStr;
5596
5641
  }
5597
5642
  if (chunk.intro.length > 0) {
5598
5643
  lineIndex = chunk.intro.lastIndexOf(n);
5599
- if (lineIndex !== -1) return chunk.intro.substr(lineIndex + 1) + lineStr;
5644
+ if (lineIndex !== -1) return chunk.intro.slice(lineIndex + 1) + lineStr;
5600
5645
  lineStr = chunk.intro + lineStr;
5601
5646
  }
5602
5647
  chunk = chunk.previous;
5603
5648
  }
5604
5649
  lineIndex = this.intro.lastIndexOf(n);
5605
- if (lineIndex !== -1) return this.intro.substr(lineIndex + 1) + lineStr;
5650
+ if (lineIndex !== -1) return this.intro.slice(lineIndex + 1) + lineStr;
5606
5651
  return this.intro + lineStr;
5607
5652
  }
5608
5653
  /**
5609
- * Returns the content of the generated string that corresponds to the slice between `start` and `end` of the original string.
5610
- * Throws error if the indices are for characters that were already removed.
5654
+ * Returns the content of the generated string that corresponds to the slice
5655
+ * between `start` and `end` of the original string, walking the generated
5656
+ * string from the chunk holding `start` to the chunk holding `end`. Throws
5657
+ * if either index falls inside replaced content. After `move()`, a range
5658
+ * whose end now comes before its start in the output yields `''`.
5611
5659
  */
5612
5660
  slice(start = 0, end = this.original.length - this.offset) {
5613
- start = start + this.offset;
5614
- end = end + this.offset;
5615
- if (this.original.length !== 0) {
5616
- if (start < 0) start = Math.max(0, start + this.original.length);
5617
- if (end < 0) end = Math.max(0, end + this.original.length);
5618
- }
5661
+ start = this._resolveIndex(start);
5662
+ end = this._resolveIndex(end);
5619
5663
  let result = "";
5620
- let chunk = this.firstChunk;
5621
- while (chunk && (chunk.start > start || chunk.end <= start)) {
5622
- if (chunk.start < end && chunk.end >= end || end === 0 && chunk.start === 0) return result;
5623
- chunk = chunk.next;
5664
+ let chunk;
5665
+ if (this.hasMovedChunks) {
5666
+ chunk = this.firstChunk;
5667
+ while (chunk && (chunk.start > start || chunk.end <= start)) {
5668
+ if (chunk.start < end && chunk.end >= end || end === 0 && chunk.start === 0) return result;
5669
+ chunk = chunk.next;
5670
+ }
5671
+ } else {
5672
+ if (start >= end) return result;
5673
+ chunk = this._chunkAt(start);
5624
5674
  }
5625
5675
  if (chunk && chunk.edited && chunk.start !== start) throw new MagicStringError(`cannot use edited character ${start} as slice start anchor`);
5626
5676
  const startChunk = chunk;
@@ -5643,10 +5693,39 @@ var MagicString = class MagicString {
5643
5693
  */
5644
5694
  snip(start, end) {
5645
5695
  const clone = this.clone();
5646
- clone.remove(0, start);
5647
- clone.remove(end, clone.original.length);
5696
+ clone.remove(-clone.offset, start);
5697
+ clone.remove(end, clone.original.length - clone.offset);
5648
5698
  return clone;
5649
5699
  }
5700
+ /**
5701
+ * Applies `offset`, resolves a negative index from the end of `original` as
5702
+ * `update`/`remove` always have, and rejects anything that is not an integer.
5703
+ * Bounds are checked by the caller, because the methods report them differently.
5704
+ *
5705
+ * @internal
5706
+ */
5707
+ _resolveIndex(index) {
5708
+ const resolved = index + this.offset;
5709
+ if (!Number.isInteger(resolved)) throw new MagicStringError(`index must be an integer, got ${index}`);
5710
+ if (resolved < 0 && this.original.length !== 0) return Math.max(0, resolved + this.original.length);
5711
+ return resolved;
5712
+ }
5713
+ /**
5714
+ * The chunk whose original range holds `index` (`chunk.start <= index < chunk.end`),
5715
+ * or `undefined` when `index` is at or past the end. Searches from the last
5716
+ * visited chunk so that scans over nearby indices stay cheap.
5717
+ *
5718
+ * @internal
5719
+ */
5720
+ _chunkAt(index) {
5721
+ let chunk = this.byStart.get(index);
5722
+ if (chunk) return chunk;
5723
+ chunk = this.lastSearchedChunk;
5724
+ const searchForward = index >= chunk.end;
5725
+ while (chunk && !chunk.contains(index)) chunk = searchForward ? this.byStart.get(chunk.end) : this.byEnd.get(chunk.start);
5726
+ if (chunk) this.lastSearchedChunk = chunk;
5727
+ return chunk;
5728
+ }
5650
5729
  /** @internal */
5651
5730
  _split(index) {
5652
5731
  if (this.byStart.get(index) || this.byEnd.get(index)) return;
@@ -5699,6 +5778,11 @@ var MagicString = class MagicString {
5699
5778
  if (this.outro.length && this.outro.trim()) return false;
5700
5779
  return true;
5701
5780
  }
5781
+ /**
5782
+ * Returns the length of the generated string, counting only content attached to the original characters.
5783
+ * Content outside the string body (`s.prepend()`/`s.append()`, and inserts before the first or after the last
5784
+ * character) is not counted, so this can differ from `s.toString().length`.
5785
+ */
5702
5786
  length() {
5703
5787
  let chunk = this.firstChunk;
5704
5788
  let length = 0;
@@ -5730,10 +5814,11 @@ var MagicString = class MagicString {
5730
5814
  const end = chunk.end;
5731
5815
  const aborted = chunk.trimEnd(rx);
5732
5816
  if (chunk.end !== end) {
5733
- if (this.lastChunk === chunk) this.lastChunk = chunk.next;
5817
+ const next = chunk.next;
5818
+ if (this.lastChunk === chunk) this.lastChunk = next;
5734
5819
  this.byEnd.set(chunk.end, chunk);
5735
- this.byStart.set(chunk.next.start, chunk.next);
5736
- this.byEnd.set(chunk.next.end, chunk.next);
5820
+ this.byStart.set(next.start, next);
5821
+ this.byEnd.set(next.end, next);
5737
5822
  }
5738
5823
  if (aborted) return true;
5739
5824
  chunk = chunk.previous;
@@ -5758,10 +5843,11 @@ var MagicString = class MagicString {
5758
5843
  const end = chunk.end;
5759
5844
  const aborted = chunk.trimStart(rx);
5760
5845
  if (chunk.end !== end) {
5761
- if (chunk === this.lastChunk) this.lastChunk = chunk.next;
5846
+ const next = chunk.next;
5847
+ if (chunk === this.lastChunk) this.lastChunk = next;
5762
5848
  this.byEnd.set(chunk.end, chunk);
5763
- this.byStart.set(chunk.next.start, chunk.next);
5764
- this.byEnd.set(chunk.next.end, chunk.next);
5849
+ this.byStart.set(next.start, next);
5850
+ this.byEnd.set(next.end, next);
5765
5851
  }
5766
5852
  if (aborted) return true;
5767
5853
  chunk = chunk.next;
@@ -5803,33 +5889,32 @@ var MagicString = class MagicString {
5803
5889
  * @internal
5804
5890
  */
5805
5891
  _hasRemovedContent(start, end) {
5806
- let chunk = this.byStart.get(start);
5807
- if (!chunk) {
5808
- chunk = this.lastSearchedChunk;
5809
- const searchForward = start >= chunk.end;
5810
- while (chunk && !chunk.contains(start)) chunk = searchForward ? this.byStart.get(chunk.end) : this.byEnd.get(chunk.start);
5811
- if (chunk) this.lastSearchedChunk = chunk;
5892
+ const atBoundary = this.byStart.get(start);
5893
+ if (atBoundary && start === end) {
5894
+ const previous = this.byEnd.get(start);
5895
+ return !!previous && previous.content === "" && atBoundary.content === "";
5812
5896
  }
5897
+ let chunk = this._chunkAt(start);
5813
5898
  while (chunk && chunk.start < end) {
5814
- if (chunk.content === "") return true;
5899
+ if (chunk.content === "" && (chunk.replacedFrom < start || this.byStart.get(chunk.replacedFrom).replacesUntil < chunk.end)) return true;
5815
5900
  chunk = this.byStart.get(chunk.end);
5816
5901
  }
5817
5902
  return false;
5818
5903
  }
5819
5904
  /** @internal */
5820
5905
  _replaceRegexp(searchValue, replacement) {
5821
- function getReplacement(match, str) {
5822
- if (typeof replacement === "string") return expandReplacement(replacement, match[0], match.index, str, match.slice(1), match.groups);
5823
- else return match.groups === void 0 ? replacement(match[0], ...match.slice(1), match.index, str) : replacement(match[0], ...match.slice(1), match.index, str, match.groups);
5906
+ function getReplacement(match, index, str) {
5907
+ if (typeof replacement === "string") return expandReplacement(replacement, match[0], index, str, match.slice(1), match.groups);
5908
+ else return match.groups === void 0 ? replacement(match[0], ...match.slice(1), index, str) : replacement(match[0], ...match.slice(1), index, str, match.groups);
5824
5909
  }
5825
5910
  const replaceMatch = (match) => {
5826
5911
  /* v8 ignore next 2 -- `match.index` is always defined for matches from `matchAll` */
5827
5912
  if (match.index == null) return false;
5828
5913
  if (this._hasRemovedContent(match.index, match.index + match[0].length)) return false;
5829
- const replacement = getReplacement(match, this.original);
5914
+ const replacement = getReplacement(match, match.index, this.original);
5830
5915
  if (replacement === match[0]) return true;
5831
- if (match[0].length === 0) this.appendRight(match.index, replacement);
5832
- else this.overwrite(match.index, match.index + match[0].length, replacement);
5916
+ if (match[0].length === 0) this.appendRight(match.index - this.offset, replacement);
5917
+ else this.overwrite(match.index - this.offset, match.index + match[0].length - this.offset, replacement);
5833
5918
  return true;
5834
5919
  };
5835
5920
  if (searchValue.global) {
@@ -5856,8 +5941,8 @@ var MagicString = class MagicString {
5856
5941
  if (typeof replacement === "function") replacement = replacement(string, index, original);
5857
5942
  else replacement = expandReplacement(replacement, string, index, original, [], void 0);
5858
5943
  if (string !== replacement) {
5859
- if (string.length === 0) this.appendRight(index, replacement);
5860
- else this.overwrite(index, index + string.length, replacement);
5944
+ if (string.length === 0) this.appendRight(index - this.offset, replacement);
5945
+ else this.overwrite(index - this.offset, index + string.length - this.offset, replacement);
5861
5946
  }
5862
5947
  break;
5863
5948
  }
@@ -5878,7 +5963,7 @@ var MagicString = class MagicString {
5878
5963
  for (let index = 0; index <= original.length; index += 1) {
5879
5964
  if (this._hasRemovedContent(index, index)) continue;
5880
5965
  const _replacement = typeof replacement === "function" ? replacement("", index, original) : expandReplacement(replacement, "", index, original, [], void 0);
5881
- if (_replacement !== "") this.appendRight(index, _replacement);
5966
+ if (_replacement !== "") this.appendRight(index - this.offset, _replacement);
5882
5967
  }
5883
5968
  return this;
5884
5969
  }
@@ -5886,7 +5971,7 @@ var MagicString = class MagicString {
5886
5971
  if (this._hasRemovedContent(index, index + stringLength)) continue;
5887
5972
  const previous = original.slice(index, index + stringLength);
5888
5973
  const _replacement = typeof replacement === "function" ? replacement(previous, index, original) : expandReplacement(replacement, previous, index, original, [], void 0);
5889
- if (previous !== _replacement) this.overwrite(index, index + stringLength, _replacement);
5974
+ if (previous !== _replacement) this.overwrite(index - this.offset, index + stringLength - this.offset, _replacement);
5890
5975
  }
5891
5976
  return this;
5892
5977
  }
@@ -5908,7 +5993,7 @@ var Bundle$1 = class Bundle {
5908
5993
  this.separator = options.separator !== void 0 ? options.separator : "\n";
5909
5994
  this.sources = [];
5910
5995
  this.uniqueSources = [];
5911
- this.uniqueSourceIndexByFilename = {};
5996
+ this.uniqueSourceIndexByFilename = /* @__PURE__ */ new Map();
5912
5997
  }
5913
5998
  /**
5914
5999
  * Adds the specified source to the bundle, which can either be a `MagicString` object directly,
@@ -5927,30 +6012,31 @@ var Bundle$1 = class Bundle {
5927
6012
  separator: this.separator
5928
6013
  });
5929
6014
  if (!isObject(source) || !source.content) throw new MagicStringError("addSource() requires a `content` property that is a MagicString");
5930
- [
5931
- "filename",
5932
- "ignoreList",
5933
- "indentExclusionRanges",
5934
- "separator"
5935
- ].forEach((option) => {
5936
- if (!hasOwnProp.call(source, option)) source[option] = source.content[option];
5937
- });
5938
- if (source.separator === void 0) source.separator = this.separator;
5939
- if (source.filename) {
5940
- if (!hasOwnProp.call(this.uniqueSourceIndexByFilename, source.filename)) {
5941
- this.uniqueSourceIndexByFilename[source.filename] = this.uniqueSources.length;
6015
+ const content = source.content;
6016
+ const record = {
6017
+ content,
6018
+ filename: hasOwnProp.call(source, "filename") ? source.filename : content.filename,
6019
+ ignoreList: hasOwnProp.call(source, "ignoreList") ? source.ignoreList : content.ignoreList,
6020
+ indentExclusionRanges: hasOwnProp.call(source, "indentExclusionRanges") ? source.indentExclusionRanges : content.indentExclusionRanges,
6021
+ separator: source.separator ?? this.separator
6022
+ };
6023
+ if (record.filename) {
6024
+ const index = this.uniqueSourceIndexByFilename.get(record.filename);
6025
+ if (index === void 0) {
6026
+ this.uniqueSourceIndexByFilename.set(record.filename, this.uniqueSources.length);
5942
6027
  this.uniqueSources.push({
5943
- filename: source.filename,
5944
- content: source.content.original
6028
+ filename: record.filename,
6029
+ content: content.original
5945
6030
  });
5946
- } else {
5947
- const uniqueSource = this.uniqueSources[this.uniqueSourceIndexByFilename[source.filename]];
5948
- if (source.content.original !== uniqueSource.content) throw new MagicStringError(`duplicate filename "${source.filename}" with different content, use unique filenames`);
5949
- }
6031
+ } else if (content.original !== this.uniqueSources[index].content) throw new MagicStringError(`duplicate filename "${record.filename}" with different content, use unique filenames`);
5950
6032
  }
5951
- this.sources.push(source);
6033
+ this.sources.push(record);
5952
6034
  return this;
5953
6035
  }
6036
+ /**
6037
+ * Appends `str` as a new source without a filename. Only `options.separator` is read, and it defaults to `''`
6038
+ * rather than to the bundle separator.
6039
+ */
5954
6040
  append(str, options) {
5955
6041
  this.addSource({
5956
6042
  content: new MagicString(str),
@@ -5958,6 +6044,10 @@ var Bundle$1 = class Bundle {
5958
6044
  });
5959
6045
  return this;
5960
6046
  }
6047
+ /**
6048
+ * Returns an independent copy of the bundle: every source's `MagicString` is cloned, so later edits to either
6049
+ * bundle do not affect the other.
6050
+ */
5961
6051
  clone() {
5962
6052
  const bundle = new Bundle({
5963
6053
  intro: this.intro,
@@ -5993,12 +6083,12 @@ var Bundle$1 = class Bundle {
5993
6083
  const byStart = /* @__PURE__ */ new Map();
5994
6084
  const byEnd = /* @__PURE__ */ new Map();
5995
6085
  let hasMovedChunks = false;
5996
- this.sources.forEach((source, i) => {
6086
+ for (const [i, source] of this.sources.entries()) {
5997
6087
  const magicString = source.content;
5998
- const separator = i > 0 ? source.separator !== void 0 ? source.separator : this.separator : "";
6088
+ const separator = i > 0 ? source.separator : "";
5999
6089
  if (magicString.original.length === 0) {
6000
6090
  pending += separator + magicString.toString();
6001
- return;
6091
+ continue;
6002
6092
  }
6003
6093
  pending += separator + magicString.intro;
6004
6094
  let sourceFirst = null;
@@ -6008,6 +6098,8 @@ var Bundle$1 = class Bundle {
6008
6098
  const chunk = originalChunk.clone();
6009
6099
  chunk.start += offset;
6010
6100
  chunk.end += offset;
6101
+ if (chunk.replacesUntil !== -1) chunk.replacesUntil += offset;
6102
+ if (chunk.replacedFrom !== -1) chunk.replacedFrom += offset;
6011
6103
  chunk.previous = previous;
6012
6104
  chunk.next = null;
6013
6105
  if (previous) previous.next = chunk;
@@ -6026,18 +6118,14 @@ var Bundle$1 = class Bundle {
6026
6118
  sourceFirst.previous = last;
6027
6119
  } else first = sourceFirst;
6028
6120
  last = sourceLast;
6029
- for (let index = 0; index < magicString.original.length; index += 1) if (magicString.sourcemapLocations.has(index)) combined.sourcemapLocations.add(index + offset);
6030
- Object.keys(magicString.storedNames).forEach((name) => {
6031
- Object.defineProperty(combined.storedNames, name, {
6032
- writable: true,
6033
- value: true,
6034
- enumerable: true
6035
- });
6121
+ magicString.sourcemapLocations.forEach((index) => {
6122
+ if (index < magicString.original.length) combined.sourcemapLocations.add(index + offset);
6036
6123
  });
6124
+ magicString.storedNames.forEach((name) => combined.storedNames.add(name));
6037
6125
  if (magicString.hasMovedChunks) hasMovedChunks = true;
6038
6126
  offset += magicString.original.length;
6039
- });
6040
- if (!first) {
6127
+ }
6128
+ if (!first || !last) {
6041
6129
  combined.intro = pending;
6042
6130
  return combined;
6043
6131
  }
@@ -6050,6 +6138,10 @@ var Bundle$1 = class Bundle {
6050
6138
  combined.hasMovedChunks = hasMovedChunks;
6051
6139
  return combined;
6052
6140
  }
6141
+ /**
6142
+ * Generates a sourcemap object with raw mappings in array form, rather than encoded as a string.
6143
+ * Takes the same options as `generateMap`.
6144
+ */
6053
6145
  generateDecodedMap(options = {}) {
6054
6146
  const mappings = new Mappings(options.hires);
6055
6147
  const { names, x_google_ignoreList } = this._generateMappings(mappings);
@@ -6059,6 +6151,10 @@ var Bundle$1 = class Bundle {
6059
6151
  rangeMappings: mappings.rawRangeMappings
6060
6152
  };
6061
6153
  }
6154
+ /**
6155
+ * Generates a version 3 sourcemap covering every source that has a `filename`.
6156
+ * Options are as per `MagicString#generateMap`, except that `includeContent` can also be a per-source function.
6157
+ */
6062
6158
  generateMap(options = {}) {
6063
6159
  const encoder = new MappingsEncoder();
6064
6160
  const mappings = new Mappings(options.hires, encoder);
@@ -6071,32 +6167,16 @@ var Bundle$1 = class Bundle {
6071
6167
  }
6072
6168
  /** @internal */
6073
6169
  _generateMappings(mappings) {
6074
- const names = [];
6075
6170
  let x_google_ignoreList;
6076
- this.sources.forEach((source) => {
6077
- Object.keys(source.content.storedNames).forEach((name) => {
6078
- if (!names.includes(name)) names.push(name);
6079
- });
6080
- });
6171
+ const storedNames = /* @__PURE__ */ new Set();
6172
+ this.sources.forEach((source) => source.content.storedNames.forEach((name) => storedNames.add(name)));
6173
+ const names = [...storedNames];
6174
+ const nameIndex = new Map(names.map((name, i) => [name, i]));
6081
6175
  if (this.intro) mappings.advance(this.intro);
6082
6176
  this.sources.forEach((source, i) => {
6083
- if (i > 0)
6084
- /* v8 ignore next -- addSource always normalizes source.separator */
6085
- mappings.advance(source.separator !== void 0 ? source.separator : this.separator);
6086
- const sourceIndex = source.filename ? this.uniqueSourceIndexByFilename[source.filename] : -1;
6087
- const magicString = source.content;
6088
- const locate = getLocator(magicString.original);
6089
- if (magicString.intro) mappings.advance(magicString.intro);
6090
- magicString.firstChunk.eachNext((chunk) => {
6091
- const loc = locate(chunk.start);
6092
- if (chunk.intro.length) mappings.advance(chunk.intro);
6093
- if (source.filename) {
6094
- if (chunk.edited) mappings.addEdit(sourceIndex, chunk.content, loc, chunk.storeName ? names.indexOf(chunk.original) : -1);
6095
- else mappings.addUneditedChunk(sourceIndex, chunk, magicString.original, loc, magicString.sourcemapLocations);
6096
- } else mappings.advance(chunk.content);
6097
- if (chunk.outro.length) mappings.advance(chunk.outro);
6098
- });
6099
- if (magicString.outro) mappings.advance(magicString.outro);
6177
+ if (i > 0) mappings.advance(source.separator);
6178
+ const sourceIndex = source.filename ? this.uniqueSourceIndexByFilename.get(source.filename) ?? -1 : -1;
6179
+ mappings.addMagicString(source.content, sourceIndex, nameIndex);
6100
6180
  if (source.ignoreList && sourceIndex !== -1) {
6101
6181
  if (x_google_ignoreList === void 0) x_google_ignoreList = [];
6102
6182
  x_google_ignoreList.push(sourceIndex);
@@ -6121,91 +6201,111 @@ var Bundle$1 = class Bundle {
6121
6201
  x_google_ignoreList
6122
6202
  };
6123
6203
  }
6204
+ /**
6205
+ * Returns the most common indent string among the sources, falling back to a tab.
6206
+ */
6124
6207
  getIndentString() {
6125
- const indentStringCounts = {};
6208
+ const indentStringCounts = /* @__PURE__ */ new Map();
6126
6209
  this.sources.forEach((source) => {
6127
6210
  const indentStr = source.content._getRawIndentString();
6128
- if (indentStr === null) return;
6129
- if (!indentStringCounts[indentStr]) indentStringCounts[indentStr] = 0;
6130
- indentStringCounts[indentStr] += 1;
6211
+ if (indentStr == null) return;
6212
+ indentStringCounts.set(indentStr, (indentStringCounts.get(indentStr) ?? 0) + 1);
6131
6213
  });
6132
- return Object.keys(indentStringCounts).sort((a, b) => {
6133
- return indentStringCounts[b] - indentStringCounts[a];
6134
- })[0] || " ";
6214
+ return [...indentStringCounts.entries()].sort(([, a], [, b]) => b - a)[0]?.[0] ?? " ";
6135
6215
  }
6216
+ /**
6217
+ * Prefixes each line of every source and of the intro with `indentStr`, guessed with `getIndentString()`
6218
+ * when not supplied. Each source's `indentExclusionRanges` are left unindented.
6219
+ */
6136
6220
  indent(indentStr) {
6137
6221
  if (!arguments.length) indentStr = this.getIndentString();
6138
6222
  if (indentStr === "") return this;
6139
6223
  let trailingNewline = !this.intro || this.intro.slice(-1) === "\n";
6140
6224
  this.sources.forEach((source, i) => {
6141
- /* v8 ignore next -- addSource always normalizes source.separator */
6142
- const separator = source.separator !== void 0 ? source.separator : this.separator;
6143
- const indentStart = trailingNewline || i > 0 && /\r?\n$/.test(separator);
6225
+ const indentStart = trailingNewline || i > 0 && /\r?\n$/.test(source.separator);
6144
6226
  source.content.indent(indentStr, {
6145
6227
  exclude: source.indentExclusionRanges,
6146
6228
  indentStart
6147
6229
  });
6148
6230
  trailingNewline = source.content.lastChar() === "\n";
6149
6231
  });
6150
- if (this.intro) this.intro = indentStr + this.intro.replace(/^[^\n]/gm, (match, index) => {
6232
+ if (this.intro) this.intro = indentStr + this.intro.replace(/^[^\r\n]/gm, (match, index) => {
6151
6233
  return index > 0 ? indentStr + match : match;
6152
6234
  });
6153
6235
  return this;
6154
6236
  }
6237
+ /**
6238
+ * Prepends `str` to the bundle's intro.
6239
+ */
6155
6240
  prepend(str) {
6156
6241
  this.intro = str + this.intro;
6157
6242
  return this;
6158
6243
  }
6244
+ /**
6245
+ * Returns the intro followed by every source's generated string, joined by their separators.
6246
+ */
6159
6247
  toString() {
6160
6248
  const body = this.sources.map((source, i) => {
6161
- /* v8 ignore next -- addSource always normalizes source.separator */
6162
- const separator = source.separator !== void 0 ? source.separator : this.separator;
6163
- return (i > 0 ? separator : "") + source.content.toString();
6249
+ return (i > 0 ? source.separator : "") + source.content.toString();
6164
6250
  }).join("");
6165
6251
  return this.intro + body;
6166
6252
  }
6253
+ /**
6254
+ * Returns true if the bundle's output is empty (disregarding white space).
6255
+ */
6167
6256
  isEmpty() {
6168
6257
  if (this.intro.length && this.intro.trim()) return false;
6169
6258
  if (this.sources.some((source, i) => {
6170
- /* v8 ignore next -- addSource always normalizes source.separator */
6171
- const separator = source.separator !== void 0 ? source.separator : this.separator;
6172
- return i > 0 && separator.trim() !== "" || !source.content.isEmpty();
6259
+ return i > 0 && source.separator.trim() !== "" || !source.content.isEmpty();
6173
6260
  })) return false;
6174
6261
  return true;
6175
6262
  }
6263
+ /**
6264
+ * Returns the length of the bundle's output; unlike `MagicString#length`, this equals `bundle.toString().length`.
6265
+ */
6176
6266
  length() {
6177
6267
  return this.sources.reduce((length, source, i) => {
6178
- /* v8 ignore next -- addSource always normalizes source.separator */
6179
- const separator = source.separator !== void 0 ? source.separator : this.separator;
6180
- return length + (i > 0 ? separator.length : 0) + source.content.toString().length;
6268
+ return length + (i > 0 ? source.separator.length : 0) + source.content.length() + source.content.intro.length + source.content.outro.length;
6181
6269
  }, this.intro.length);
6182
6270
  }
6271
+ /**
6272
+ * Removes empty lines from the start and end.
6273
+ */
6183
6274
  trimLines() {
6184
6275
  return this.trim("[\\r\\n]");
6185
6276
  }
6277
+ /**
6278
+ * Trims content matching `charType` (defaults to `\s`, i.e. whitespace) from the start and end.
6279
+ */
6186
6280
  trim(charType) {
6187
6281
  return this.trimStart(charType).trimEnd(charType);
6188
6282
  }
6283
+ /**
6284
+ * Trims content matching `charType` (defaults to `\s`, i.e. whitespace) from the start.
6285
+ */
6189
6286
  trimStart(charType) {
6190
6287
  const rx = new RegExp(`^${charType || "\\s"}+`);
6191
6288
  this.intro = this.intro.replace(rx, "");
6192
6289
  if (!this.intro) for (let i = 0; i < this.sources.length; i += 1) {
6193
6290
  const source = this.sources[i];
6194
6291
  if (i > 0) {
6195
- source.separator = (source.separator !== void 0 ? source.separator : this.separator).replace(rx, "");
6292
+ source.separator = source.separator.replace(rx, "");
6196
6293
  if (source.separator) break;
6197
6294
  }
6198
6295
  if (source.content.trimStartAborted(charType)) break;
6199
6296
  }
6200
6297
  return this;
6201
6298
  }
6299
+ /**
6300
+ * Trims content matching `charType` (defaults to `\s`, i.e. whitespace) from the end.
6301
+ */
6202
6302
  trimEnd(charType) {
6203
6303
  const rx = new RegExp(`${charType || "\\s"}+$`);
6204
6304
  for (let i = this.sources.length - 1; i >= 0; i -= 1) {
6205
6305
  const source = this.sources[i];
6206
6306
  if (source.content.trimEndAborted(charType)) return this;
6207
6307
  if (i > 0) {
6208
- source.separator = (source.separator !== void 0 ? source.separator : this.separator).replace(rx, "");
6308
+ source.separator = source.separator.replace(rx, "");
6209
6309
  if (source.separator) return this;
6210
6310
  }
6211
6311
  }
@@ -6424,8 +6524,8 @@ const UnknownNonAccessorKey = Symbol('Unknown Non-Accessor Key');
6424
6524
  const UnknownInteger = Symbol('Unknown Integer');
6425
6525
  const UnknownWellKnown = Symbol('Unknown Well-Known');
6426
6526
  const SymbolToStringTag = Symbol('Symbol.toStringTag');
6427
- const SymbolDispose = Symbol('Symbol.asyncDispose');
6428
- const SymbolAsyncDispose = Symbol('Symbol.dispose');
6527
+ const SymbolDispose = Symbol('Symbol.dispose');
6528
+ const SymbolAsyncDispose = Symbol('Symbol.asyncDispose');
6429
6529
  const SymbolHasInstance = Symbol('Symbol.hasInstance');
6430
6530
  const WELL_KNOWN_SYMBOLS_LIST = [
6431
6531
  SymbolToStringTag,
@@ -6532,6 +6632,25 @@ class IncludedFullPathTracker {
6532
6632
  }
6533
6633
  return included;
6534
6634
  }
6635
+ includeAllPaths(entity, context, basePath) {
6636
+ if (this.includedPaths) {
6637
+ includeAllSubPaths(entity, context, basePath, this.includedPaths);
6638
+ }
6639
+ }
6640
+ }
6641
+ function includeAllSubPaths(entity, context, path, includedPaths) {
6642
+ if (includedPaths[UnknownKey]) {
6643
+ entity.includePath([...path, UnknownKey], context);
6644
+ return;
6645
+ }
6646
+ const keys = Reflect.ownKeys(includedPaths);
6647
+ if (keys.length === 0) {
6648
+ entity.includePath(path, context);
6649
+ return;
6650
+ }
6651
+ for (const key of keys) {
6652
+ includeAllSubPaths(entity, context, [...path, key], includedPaths[key]);
6653
+ }
6535
6654
  }
6536
6655
  const UNKNOWN_INCLUDED_TOP_LEVEL_PATH = Object.freeze({
6537
6656
  [UnknownKey]: true
@@ -6575,13 +6694,15 @@ class IncludedTopLevelPathTracker {
6575
6694
  entity.includePath([...basePath, UnknownKey], context);
6576
6695
  }
6577
6696
  else {
6578
- const inclusionEntries = Object.entries(includedPaths);
6579
- if (inclusionEntries.length === 0) {
6697
+ const keys = Reflect.ownKeys(includedPaths);
6698
+ if (keys.length === 0) {
6580
6699
  entity.includePath(basePath, context);
6581
6700
  }
6582
6701
  else {
6583
- for (const [key, value] of inclusionEntries) {
6584
- entity.includePath(value === UnknownKey ? [...basePath, key, UnknownKey] : [...basePath, key], context);
6702
+ for (const key of keys) {
6703
+ entity.includePath(includedPaths[key] === UnknownKey
6704
+ ? [...basePath, key, UnknownKey]
6705
+ : [...basePath, key], context);
6585
6706
  }
6586
6707
  }
6587
6708
  }
@@ -6613,6 +6734,9 @@ class ExpressionEntity {
6613
6734
  deoptimizeInteraction(interaction);
6614
6735
  }
6615
6736
  deoptimizePath(_path) { }
6737
+ getKnownFunctionAtPath(_path, _recursionTracker, _origin) {
6738
+ return null;
6739
+ }
6616
6740
  /**
6617
6741
  * If possible it returns a stringifyable literal value for this node that
6618
6742
  * can be used for inlining or comparing values. Otherwise, it should return
@@ -6758,228 +6882,343 @@ function getSafeName(baseName, usedNames, forbiddenNames) {
6758
6882
  return safeName;
6759
6883
  }
6760
6884
 
6761
- // To avoid infinite recursions
6762
- const MAX_PATH_DEPTH = 6;
6763
- // If a path is longer than MAX_PATH_DEPTH, it is truncated so that it is at
6764
- // most MAX_PATH_DEPTH long. The last element is always UnknownKey
6765
- const limitConcatenatedPathDepth = (path1, path2) => {
6766
- const { length: length1 } = path1;
6767
- const { length: length2 } = path2;
6768
- return length1 === 0
6769
- ? path2
6770
- : length2 === 0
6771
- ? path1
6772
- : length1 + length2 > MAX_PATH_DEPTH
6773
- ? [...path1, ...path2.slice(0, MAX_PATH_DEPTH - 1 - path1.length), 'UnknownKey']
6774
- : [...path1, ...path2];
6885
+ // This file is generated by scripts/generate-child-node-keys.ts.
6886
+ // Do not edit this file directly.
6887
+ const childNodeKeys = {
6888
+ ArrayExpression: ['elements'],
6889
+ ArrayPattern: ['elements'],
6890
+ ArrowFunctionExpression: ['params', 'body'],
6891
+ AssignmentExpression: ['left', 'right'],
6892
+ AssignmentPattern: ['left', 'right'],
6893
+ AwaitExpression: ['argument'],
6894
+ BinaryExpression: ['left', 'right'],
6895
+ BlockStatement: ['body'],
6896
+ BreakStatement: ['label'],
6897
+ CallExpression: ['callee', 'arguments'],
6898
+ CatchClause: ['param', 'body'],
6899
+ ChainExpression: ['expression'],
6900
+ ClassBody: ['body'],
6901
+ ClassDeclaration: ['decorators', 'id', 'superClass', 'body'],
6902
+ ClassExpression: ['decorators', 'id', 'superClass', 'body'],
6903
+ ConditionalExpression: ['test', 'consequent', 'alternate'],
6904
+ ContinueStatement: ['label'],
6905
+ DebuggerStatement: [],
6906
+ Decorator: ['expression'],
6907
+ DoWhileStatement: ['body', 'test'],
6908
+ EmptyStatement: [],
6909
+ ExportAllDeclaration: ['exported', 'source', 'attributes'],
6910
+ ExportDefaultDeclaration: ['declaration'],
6911
+ ExportNamedDeclaration: ['specifiers', 'source', 'attributes', 'declaration'],
6912
+ ExportSpecifier: ['local', 'exported'],
6913
+ ExpressionStatement: ['expression'],
6914
+ ForInStatement: ['left', 'right', 'body'],
6915
+ ForOfStatement: ['left', 'right', 'body'],
6916
+ ForStatement: ['init', 'test', 'update', 'body'],
6917
+ FunctionDeclaration: ['id', 'params', 'body'],
6918
+ FunctionExpression: ['id', 'params', 'body'],
6919
+ Identifier: [],
6920
+ IfStatement: ['test', 'consequent', 'alternate'],
6921
+ ImportAttribute: ['key', 'value'],
6922
+ ImportDeclaration: ['specifiers', 'source', 'attributes'],
6923
+ ImportDefaultSpecifier: ['local'],
6924
+ ImportExpression: ['source', 'options'],
6925
+ ImportNamespaceSpecifier: ['local'],
6926
+ ImportSpecifier: ['imported', 'local'],
6927
+ JSXAttribute: ['name', 'value'],
6928
+ JSXClosingElement: ['name'],
6929
+ JSXClosingFragment: [],
6930
+ JSXElement: ['openingElement', 'children', 'closingElement'],
6931
+ JSXEmptyExpression: [],
6932
+ JSXExpressionContainer: ['expression'],
6933
+ JSXFragment: ['openingFragment', 'children', 'closingFragment'],
6934
+ JSXIdentifier: [],
6935
+ JSXMemberExpression: ['object', 'property'],
6936
+ JSXNamespacedName: ['namespace', 'name'],
6937
+ JSXOpeningElement: ['name', 'attributes'],
6938
+ JSXOpeningFragment: [],
6939
+ JSXSpreadAttribute: ['argument'],
6940
+ JSXSpreadChild: ['expression'],
6941
+ JSXText: [],
6942
+ LabeledStatement: ['label', 'body'],
6943
+ Literal: [],
6944
+ LogicalExpression: ['left', 'right'],
6945
+ MemberExpression: ['object', 'property'],
6946
+ MetaProperty: ['meta', 'property'],
6947
+ MethodDefinition: ['decorators', 'key', 'value'],
6948
+ NewExpression: ['callee', 'arguments'],
6949
+ ObjectExpression: ['properties'],
6950
+ ObjectPattern: ['properties'],
6951
+ PanicError: [],
6952
+ ParseError: [],
6953
+ PrivateIdentifier: [],
6954
+ Program: ['body'],
6955
+ Property: ['key', 'value'],
6956
+ PropertyDefinition: ['decorators', 'key', 'value'],
6957
+ RestElement: ['argument'],
6958
+ ReturnStatement: ['argument'],
6959
+ SequenceExpression: ['expressions'],
6960
+ SpreadElement: ['argument'],
6961
+ StaticBlock: ['body'],
6962
+ Super: [],
6963
+ SwitchCase: ['test', 'consequent'],
6964
+ SwitchStatement: ['discriminant', 'cases'],
6965
+ TaggedTemplateExpression: ['tag', 'quasi'],
6966
+ TemplateElement: [],
6967
+ TemplateLiteral: ['quasis', 'expressions'],
6968
+ ThisExpression: [],
6969
+ ThrowStatement: ['argument'],
6970
+ TryStatement: ['block', 'handler', 'finalizer'],
6971
+ UnaryExpression: ['argument'],
6972
+ UpdateExpression: ['argument'],
6973
+ VariableDeclaration: ['declarations'],
6974
+ VariableDeclarator: ['id', 'init'],
6975
+ WhileStatement: ['test', 'body'],
6976
+ YieldExpression: ['argument']
6775
6977
  };
6776
6978
 
6777
- function assembleMemberDescriptions(memberDescriptions, inheritedDescriptions = null) {
6778
- return Object.create(inheritedDescriptions, memberDescriptions);
6979
+ function createInclusionContext() {
6980
+ return {
6981
+ brokenFlow: false,
6982
+ hasBreak: false,
6983
+ hasContinue: false,
6984
+ includedCallArguments: new Set(),
6985
+ includedLabels: new Set()
6986
+ };
6779
6987
  }
6780
- const UNDEFINED_EXPRESSION = new (class UndefinedExpression extends ExpressionEntity {
6781
- getLiteralValueAtPath(path) {
6782
- return path.length > 0 ? UnknownValue : undefined;
6783
- }
6784
- })();
6785
- const returnsUnknown = {
6786
- value: {
6787
- hasEffectsWhenCalled: null,
6788
- returns: UNKNOWN_EXPRESSION
6789
- }
6790
- };
6791
- const UNKNOWN_LITERAL_BOOLEAN = new (class UnknownBoolean extends ExpressionEntity {
6792
- getReturnExpressionWhenCalledAtPath(path) {
6793
- if (path.length === 1) {
6794
- return getMemberReturnExpressionWhenCalled(literalBooleanMembers, path[0]);
6795
- }
6796
- return UNKNOWN_RETURN_EXPRESSION;
6988
+ function createHasEffectsContext() {
6989
+ return {
6990
+ accessed: new EntityPathTracker(),
6991
+ assigned: new EntityPathTracker(),
6992
+ brokenFlow: false,
6993
+ called: new DiscriminatedPathTracker(),
6994
+ hasBreak: false,
6995
+ hasContinue: false,
6996
+ ignore: {
6997
+ breaks: false,
6998
+ continues: false,
6999
+ labels: new Set(),
7000
+ returnYield: false,
7001
+ this: false
7002
+ },
7003
+ includedLabels: new Set(),
7004
+ instantiated: new DiscriminatedPathTracker(),
7005
+ replacedVariableInits: new Map()
7006
+ };
7007
+ }
7008
+
7009
+ const INCLUDE_PARAMETERS = 'variables';
7010
+ const IS_SKIPPED_CHAIN = Symbol('IS_SKIPPED_CHAIN');
7011
+ class NodeBase extends ExpressionEntity {
7012
+ /**
7013
+ * Nodes can apply custom deoptimizations once they become part of the
7014
+ * executed code. To do this, they must initialize this as false, implement
7015
+ * applyDeoptimizations and call this from include and hasEffects if they have
7016
+ * custom handlers
7017
+ */
7018
+ get deoptimized() {
7019
+ return isFlagSet(this.flags, 2 /* Flag.deoptimized */);
6797
7020
  }
6798
- hasEffectsOnInteractionAtPath(path, interaction, context) {
6799
- if (interaction.type === INTERACTION_ACCESSED) {
6800
- return path.length > 1;
6801
- }
6802
- if (interaction.type === INTERACTION_CALLED && path.length === 1) {
6803
- return hasMemberEffectWhenCalled(literalBooleanMembers, path[0], interaction, context);
7021
+ set deoptimized(value) {
7022
+ this.flags = setFlag(this.flags, 2 /* Flag.deoptimized */, value);
7023
+ }
7024
+ constructor(parent, parentScope) {
7025
+ super();
7026
+ this.parent = parent;
7027
+ this.scope = parentScope;
7028
+ this.createScope(parentScope);
7029
+ }
7030
+ addExportedVariables(_variables, _exportNamesByVariable) { }
7031
+ /**
7032
+ * Override this to bind assignments to variables and do any initialisations
7033
+ * that require the scopes to be populated with variables.
7034
+ */
7035
+ bind() {
7036
+ for (const key of childNodeKeys[this.type]) {
7037
+ const value = this[key];
7038
+ if (Array.isArray(value)) {
7039
+ for (const child of value) {
7040
+ child?.bind();
7041
+ }
7042
+ }
7043
+ else if (value) {
7044
+ value.bind();
7045
+ }
6804
7046
  }
6805
- return true;
6806
7047
  }
6807
- })();
6808
- const returnsBoolean = {
6809
- value: {
6810
- hasEffectsWhenCalled: null,
6811
- returns: UNKNOWN_LITERAL_BOOLEAN
7048
+ /**
7049
+ * Override if this node should receive a different scope than the parent
7050
+ * scope.
7051
+ */
7052
+ createScope(parentScope) {
7053
+ this.scope = parentScope;
6812
7054
  }
6813
- };
6814
- const UNKNOWN_LITERAL_NUMBER = new (class UnknownNumber extends ExpressionEntity {
6815
- getReturnExpressionWhenCalledAtPath(path) {
6816
- if (path.length === 1) {
6817
- return getMemberReturnExpressionWhenCalled(literalNumberMembers, path[0]);
7055
+ hasEffects(context) {
7056
+ if (!this.deoptimized)
7057
+ this.applyDeoptimizations();
7058
+ for (const key of childNodeKeys[this.type]) {
7059
+ const value = this[key];
7060
+ if (value === null)
7061
+ continue;
7062
+ if (Array.isArray(value)) {
7063
+ for (const child of value) {
7064
+ if (child?.hasEffects(context))
7065
+ return true;
7066
+ }
7067
+ }
7068
+ else if (value.hasEffects(context))
7069
+ return true;
6818
7070
  }
6819
- return UNKNOWN_RETURN_EXPRESSION;
7071
+ return false;
6820
7072
  }
6821
- hasEffectsOnInteractionAtPath(path, interaction, context) {
6822
- if (interaction.type === INTERACTION_ACCESSED) {
6823
- return path.length > 1;
7073
+ hasEffectsAsAssignmentTarget(context, _checkAccess) {
7074
+ return (this.hasEffects(context) ||
7075
+ this.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.assignmentInteraction, context));
7076
+ }
7077
+ include(context, includeChildrenRecursively, _options) {
7078
+ if (!this.included)
7079
+ this.includeNode(context);
7080
+ for (const key of childNodeKeys[this.type]) {
7081
+ const value = this[key];
7082
+ if (value === null)
7083
+ continue;
7084
+ if (Array.isArray(value)) {
7085
+ for (const child of value) {
7086
+ child?.include(context, includeChildrenRecursively);
7087
+ }
7088
+ }
7089
+ else {
7090
+ value.include(context, includeChildrenRecursively);
7091
+ }
6824
7092
  }
6825
- if (interaction.type === INTERACTION_CALLED && path.length === 1) {
6826
- return hasMemberEffectWhenCalled(literalNumberMembers, path[0], interaction, context);
7093
+ }
7094
+ includeNode(context) {
7095
+ this.included = true;
7096
+ if (!this.deoptimized)
7097
+ this.applyDeoptimizations();
7098
+ for (const key of childNodeKeys[this.type]) {
7099
+ const value = this[key];
7100
+ if (value === null)
7101
+ continue;
7102
+ if (Array.isArray(value)) {
7103
+ for (const child of value) {
7104
+ child?.includePath(UNKNOWN_PATH, context);
7105
+ }
7106
+ }
7107
+ else {
7108
+ value.includePath(UNKNOWN_PATH, context);
7109
+ }
6827
7110
  }
6828
- return true;
6829
7111
  }
6830
- })();
6831
- const returnsNumber = {
6832
- value: {
6833
- hasEffectsWhenCalled: null,
6834
- returns: UNKNOWN_LITERAL_NUMBER
7112
+ includeAsAssignmentTarget(context, includeChildrenRecursively, _deoptimizeAccess) {
7113
+ this.include(context, includeChildrenRecursively);
6835
7114
  }
6836
- };
6837
- const UNKNOWN_LITERAL_STRING = new (class UnknownString extends ExpressionEntity {
6838
- getReturnExpressionWhenCalledAtPath(path) {
6839
- if (path.length === 1) {
6840
- return getMemberReturnExpressionWhenCalled(literalStringMembers, path[0]);
6841
- }
6842
- return UNKNOWN_RETURN_EXPRESSION;
7115
+ /**
7116
+ * Override to perform special initialisation steps after the scope is
7117
+ * initialised
7118
+ */
7119
+ initialise() {
7120
+ this.scope.context.magicString.addSourcemapLocation(this.start);
7121
+ this.scope.context.magicString.addSourcemapLocation(this.end);
6843
7122
  }
6844
- hasEffectsOnInteractionAtPath(path, interaction, context) {
6845
- if (interaction.type === INTERACTION_ACCESSED) {
6846
- return path.length > 1;
7123
+ removeAnnotations(code) {
7124
+ if (this.annotations) {
7125
+ for (const annotation of this.annotations) {
7126
+ code.remove(annotation.start, annotation.end);
7127
+ }
6847
7128
  }
6848
- if (interaction.type === INTERACTION_CALLED && path.length === 1) {
6849
- return hasMemberEffectWhenCalled(literalStringMembers, path[0], interaction, context);
7129
+ }
7130
+ render(code, options) {
7131
+ for (const key of childNodeKeys[this.type]) {
7132
+ const value = this[key];
7133
+ if (value === null)
7134
+ continue;
7135
+ if (Array.isArray(value)) {
7136
+ for (const child of value) {
7137
+ child?.render(code, options);
7138
+ }
7139
+ }
7140
+ else {
7141
+ value.render(code, options);
7142
+ }
6850
7143
  }
6851
- return true;
6852
7144
  }
6853
- })();
6854
- const returnsString = {
6855
- value: {
6856
- hasEffectsWhenCalled: null,
6857
- returns: UNKNOWN_LITERAL_STRING
7145
+ setAssignedValue(value) {
7146
+ this.assignmentInteraction = { args: [null, value], type: INTERACTION_ASSIGNED };
6858
7147
  }
6859
- };
6860
- const stringReplace = {
6861
- value: {
6862
- hasEffectsWhenCalled({ args }, context) {
6863
- const argument1 = args[2];
6864
- return (args.length < 3 ||
6865
- (typeof argument1.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, {
6866
- deoptimizeCache() { }
6867
- }) === 'symbol' &&
6868
- argument1.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, context)));
6869
- },
6870
- returns: UNKNOWN_LITERAL_STRING
7148
+ shouldBeIncluded(context) {
7149
+ return this.included || (!context.brokenFlow && this.hasEffects(createHasEffectsContext()));
6871
7150
  }
6872
- };
6873
- const objectMembers = assembleMemberDescriptions({
6874
- hasOwnProperty: returnsBoolean,
6875
- isPrototypeOf: returnsBoolean,
6876
- propertyIsEnumerable: returnsBoolean,
6877
- toLocaleString: returnsString,
6878
- toString: returnsString,
6879
- valueOf: returnsUnknown
6880
- });
6881
- const literalBooleanMembers = assembleMemberDescriptions({
6882
- valueOf: returnsBoolean
6883
- }, objectMembers);
6884
- const literalNumberMembers = assembleMemberDescriptions({
6885
- toExponential: returnsString,
6886
- toFixed: returnsString,
6887
- toLocaleString: returnsString,
6888
- toPrecision: returnsString,
6889
- valueOf: returnsNumber
6890
- }, objectMembers);
6891
- /**
6892
- * RegExp are stateful when they have the global or sticky flags set.
6893
- * But if we actually don't use them, the side effect does not matter.
6894
- * the check logic in `hasEffectsOnInteractionAtPath`.
6895
- */
6896
- const literalRegExpMembers = assembleMemberDescriptions({
6897
- exec: returnsUnknown,
6898
- test: returnsBoolean
6899
- }, objectMembers);
6900
- const literalStringMembers = assembleMemberDescriptions({
6901
- anchor: returnsString,
6902
- at: returnsUnknown,
6903
- big: returnsString,
6904
- blink: returnsString,
6905
- bold: returnsString,
6906
- charAt: returnsString,
6907
- charCodeAt: returnsNumber,
6908
- codePointAt: returnsUnknown,
6909
- concat: returnsString,
6910
- endsWith: returnsBoolean,
6911
- fixed: returnsString,
6912
- fontcolor: returnsString,
6913
- fontsize: returnsString,
6914
- includes: returnsBoolean,
6915
- indexOf: returnsNumber,
6916
- italics: returnsString,
6917
- lastIndexOf: returnsNumber,
6918
- link: returnsString,
6919
- localeCompare: returnsNumber,
6920
- match: returnsUnknown,
6921
- matchAll: returnsUnknown,
6922
- normalize: returnsString,
6923
- padEnd: returnsString,
6924
- padStart: returnsString,
6925
- repeat: returnsString,
6926
- replace: stringReplace,
6927
- replaceAll: stringReplace,
6928
- search: returnsNumber,
6929
- slice: returnsString,
6930
- small: returnsString,
6931
- split: returnsUnknown,
6932
- startsWith: returnsBoolean,
6933
- strike: returnsString,
6934
- sub: returnsString,
6935
- substr: returnsString,
6936
- substring: returnsString,
6937
- sup: returnsString,
6938
- toLocaleLowerCase: returnsString,
6939
- toLocaleUpperCase: returnsString,
6940
- toLowerCase: returnsString,
6941
- toString: returnsString, // overrides the toString() method of the Object object; it does not inherit Object.prototype.toString()
6942
- toUpperCase: returnsString,
6943
- trim: returnsString,
6944
- trimEnd: returnsString,
6945
- trimLeft: returnsString,
6946
- trimRight: returnsString,
6947
- trimStart: returnsString,
6948
- valueOf: returnsString
6949
- }, objectMembers);
6950
- function getLiteralMembersForValue(value) {
6951
- if (value instanceof RegExp) {
6952
- return literalRegExpMembers;
6953
- }
6954
- switch (typeof value) {
6955
- case 'boolean': {
6956
- return literalBooleanMembers;
6957
- }
6958
- case 'number': {
6959
- return literalNumberMembers;
6960
- }
6961
- case 'string': {
6962
- return literalStringMembers;
7151
+ /**
7152
+ * Just deoptimize everything by default so that when e.g. we do not track
7153
+ * something properly, it is deoptimized.
7154
+ * @protected
7155
+ */
7156
+ applyDeoptimizations() {
7157
+ this.deoptimized = true;
7158
+ for (const key of childNodeKeys[this.type]) {
7159
+ const value = this[key];
7160
+ if (value === null)
7161
+ continue;
7162
+ if (Array.isArray(value)) {
7163
+ for (const child of value) {
7164
+ child?.deoptimizePath(UNKNOWN_PATH);
7165
+ }
7166
+ }
7167
+ else {
7168
+ value.deoptimizePath(UNKNOWN_PATH);
7169
+ }
6963
7170
  }
7171
+ this.scope.context.requestTreeshakingPass();
6964
7172
  }
6965
- return Object.create(null);
6966
7173
  }
6967
- function hasMemberEffectWhenCalled(members, memberName, interaction, context) {
6968
- if (typeof memberName !== 'string' || !members[memberName]) {
6969
- return true;
6970
- }
6971
- return members[memberName].hasEffectsWhenCalled?.(interaction, context) || false;
7174
+ function onlyIncludeSelf() {
7175
+ this.included = true;
7176
+ if (!this.deoptimized)
7177
+ this.applyDeoptimizations();
6972
7178
  }
6973
- function getMemberReturnExpressionWhenCalled(members, memberName) {
6974
- if (typeof memberName !== 'string' || !members[memberName])
6975
- return UNKNOWN_RETURN_EXPRESSION;
6976
- return [members[memberName].returns, false];
7179
+ function onlyIncludeSelfNoDeoptimize() {
7180
+ this.included = true;
7181
+ }
7182
+ function doNotDeoptimize() {
7183
+ this.deoptimized = true;
7184
+ }
7185
+
7186
+ function isObjectExpressionNode(node) {
7187
+ return node instanceof NodeBase && node.type === parseAst_js.ObjectExpression;
7188
+ }
7189
+ function isArrowFunctionExpressionNode(node) {
7190
+ return node instanceof NodeBase && node.type === parseAst_js.ArrowFunctionExpression;
6977
7191
  }
7192
+ function isFunctionExpressionNode(node) {
7193
+ return node instanceof NodeBase && node.type === parseAst_js.FunctionExpression;
7194
+ }
7195
+ function isIdentifierNode(node) {
7196
+ return node instanceof NodeBase && node.type === parseAst_js.Identifier;
7197
+ }
7198
+
7199
+ // To avoid infinite recursions
7200
+ const MAX_PATH_DEPTH = 6;
7201
+ // If a path is longer than MAX_PATH_DEPTH, it is truncated so that it is at
7202
+ // most MAX_PATH_DEPTH long. The last element is always UnknownKey
7203
+ const limitConcatenatedPathDepth = (path1, path2) => {
7204
+ const { length: length1 } = path1;
7205
+ const { length: length2 } = path2;
7206
+ return length1 === 0
7207
+ ? path2
7208
+ : length2 === 0
7209
+ ? path1
7210
+ : length1 + length2 > MAX_PATH_DEPTH
7211
+ ? [...path1, ...path2.slice(0, MAX_PATH_DEPTH - 1 - path1.length), 'UnknownKey']
7212
+ : [...path1, ...path2];
7213
+ };
6978
7214
 
6979
7215
  class Variable extends ExpressionEntity {
6980
7216
  markReassigned() {
6981
7217
  this.isReassigned = true;
6982
7218
  }
7219
+ markTargetOfAssignment() {
7220
+ this.isTargetOfAssignment = true;
7221
+ }
6983
7222
  constructor(name) {
6984
7223
  super();
6985
7224
  this.name = name;
@@ -6992,6 +7231,9 @@ class Variable extends ExpressionEntity {
6992
7231
  this.renderBaseName = null;
6993
7232
  this.renderName = null;
6994
7233
  this.isReassigned = false;
7234
+ // Unlike isReassigned, set eagerly during binding for every assignment,
7235
+ // including ones that are never included
7236
+ this.isTargetOfAssignment = false;
6995
7237
  this.onlyFunctionCallUsed = true;
6996
7238
  }
6997
7239
  /**
@@ -7080,10 +7322,9 @@ class LocalVariable extends Variable {
7080
7322
  this.kind = kind;
7081
7323
  this.calledFromTryStatement = false;
7082
7324
  this.additionalInitializers = null;
7083
- // A possibly incomplete list of values assigned to this variable after its
7084
- // declaration; as it is incomplete, it must never be used for value queries
7085
- // but only to forward call arguments to possible values
7086
- this.reassignedValues = null;
7325
+ // A possibly incomplete list of functions assigned to this variable; only used
7326
+ // to retain call arguments of assigned try-catch helpers, never for value queries
7327
+ this.assignedFunctions = null;
7087
7328
  this.includedPathTracker = new IncludedFullPathTracker();
7088
7329
  this.expressionsToBeDeoptimized = [];
7089
7330
  this.declarations = declarator ? [declarator] : [];
@@ -7128,6 +7369,15 @@ class LocalVariable extends Variable {
7128
7369
  this.init.deoptimizePath(limitConcatenatedPathDepth(this.initPath, path));
7129
7370
  }
7130
7371
  }
7372
+ getKnownFunctionAtPath(path, recursionTracker, origin) {
7373
+ if (this.isReassigned || path.length + this.initPath.length > MAX_PATH_DEPTH) {
7374
+ return null;
7375
+ }
7376
+ return recursionTracker.withTrackedEntityAtPath(path, this.init, () => {
7377
+ this.expressionsToBeDeoptimized.push(origin);
7378
+ return this.init.getKnownFunctionAtPath([...this.initPath, ...path], recursionTracker, origin);
7379
+ }, null);
7380
+ }
7131
7381
  getLiteralValueAtPath(path, recursionTracker, origin) {
7132
7382
  if (this.isReassigned || path.length + this.initPath.length > MAX_PATH_DEPTH) {
7133
7383
  return UnknownValue;
@@ -7209,16 +7459,12 @@ class LocalVariable extends Variable {
7209
7459
  }
7210
7460
  includeCallArgumentsWhenCalledAtPath(path, interaction, context) {
7211
7461
  if (this.isReassigned) {
7212
- // Even when the value is unknown, it may be one of the assigned values;
7213
- // forwarding to all of them retains the arguments of try-catch helpers
7462
+ // The value may still be one of the assigned functions, whose try-catch
7463
+ // helpers need their call arguments retained
7214
7464
  includeInteraction(interaction, context);
7215
- // Each possible value is visited at most once per path and call
7216
- // per traversal so that dense assignment graphs do not repeat work
7217
- // for every simple path
7218
- const previousTracker = context.includedCallArgumentsOfPossibleValues;
7219
- context.includedCallArgumentsOfPossibleValues ??= new DiscriminatedPathTracker();
7220
- this.includeCallArgumentsOfPossibleValues(path, interaction, context, context.includedCallArgumentsOfPossibleValues);
7221
- context.includedCallArgumentsOfPossibleValues = previousTracker;
7465
+ if (path.length === 0) {
7466
+ this.includeCallArgumentsOfAssignedTryCatchHelpers(interaction, context);
7467
+ }
7222
7468
  return;
7223
7469
  }
7224
7470
  if (context.includedCallArguments.has(this.init) ||
@@ -7230,25 +7476,25 @@ class LocalVariable extends Variable {
7230
7476
  this.init.includeCallArgumentsWhenCalledAtPath([...this.initPath, ...path], interaction, context);
7231
7477
  context.includedCallArguments.delete(this.init);
7232
7478
  }
7233
- includeCallArgumentsOfPossibleValues(path, interaction, context, tracker) {
7234
- if (this.reassignedValues === null || path.length + this.initPath.length > MAX_PATH_DEPTH) {
7235
- return;
7479
+ includeCallArgumentsOfAssignedTryCatchHelpers(interaction, context) {
7480
+ if (this.initPath.length === 0) {
7481
+ this.includeCallArgumentsOfTryCatchHelper(this.init, interaction, context);
7236
7482
  }
7237
- this.includeCallArgumentsOfPossibleValue(this.init, [...this.initPath, ...path], interaction, context, tracker);
7238
- for (const entity of this.reassignedValues) {
7239
- this.includeCallArgumentsOfPossibleValue(entity, path, interaction, context, tracker);
7483
+ for (const assignedFunction of this.assignedFunctions ?? parseAst_js.EMPTY_ARRAY) {
7484
+ this.includeCallArgumentsOfTryCatchHelper(assignedFunction, interaction, context);
7240
7485
  }
7241
7486
  }
7242
- includeCallArgumentsOfPossibleValue(entity, path, interaction, context, tracker) {
7243
- if (entity === UNKNOWN_EXPRESSION ||
7244
- entity === UNDEFINED_EXPRESSION ||
7245
- tracker.trackEntityAtPathAndGetIfTracked(path, interaction, entity)) {
7246
- return;
7487
+ includeCallArgumentsOfTryCatchHelper(value, interaction, context) {
7488
+ if (isArrowFunctionExpressionNode(value) || isFunctionExpressionNode(value)) {
7489
+ if (value.scope.hasParameterCalledFromTryStatement()) {
7490
+ value.scope.includeCallArguments(interaction, context);
7491
+ }
7247
7492
  }
7248
- entity.includeCallArgumentsWhenCalledAtPath(path, interaction, context);
7249
7493
  }
7250
7494
  addReassignedValue(value) {
7251
- (this.reassignedValues ??= []).push(value);
7495
+ if (isArrowFunctionExpressionNode(value) || isFunctionExpressionNode(value)) {
7496
+ (this.assignedFunctions ??= []).push(value);
7497
+ }
7252
7498
  }
7253
7499
  markCalledFromTryStatement() {
7254
7500
  this.calledFromTryStatement = true;
@@ -7461,37 +7707,6 @@ function is_reference(node, parent) {
7461
7707
  }
7462
7708
  }
7463
7709
 
7464
- function createInclusionContext() {
7465
- return {
7466
- brokenFlow: false,
7467
- hasBreak: false,
7468
- hasContinue: false,
7469
- includedCallArguments: new Set(),
7470
- includedCallArgumentsOfPossibleValues: null,
7471
- includedLabels: new Set()
7472
- };
7473
- }
7474
- function createHasEffectsContext() {
7475
- return {
7476
- accessed: new EntityPathTracker(),
7477
- assigned: new EntityPathTracker(),
7478
- brokenFlow: false,
7479
- called: new DiscriminatedPathTracker(),
7480
- hasBreak: false,
7481
- hasContinue: false,
7482
- ignore: {
7483
- breaks: false,
7484
- continues: false,
7485
- labels: new Set(),
7486
- returnYield: false,
7487
- this: false
7488
- },
7489
- includedLabels: new Set(),
7490
- instantiated: new DiscriminatedPathTracker(),
7491
- replacedVariableInits: new Map()
7492
- };
7493
- }
7494
-
7495
7710
  const PureFunctionKey = Symbol('PureFunction');
7496
7711
  const getPureFunctions = ({ treeshake }) => {
7497
7712
  const pureFunctions = Object.create(null);
@@ -7693,288 +7908,206 @@ function markModuleAndImpureDependenciesAsExecuted(baseModule) {
7693
7908
  }
7694
7909
  }
7695
7910
 
7696
- // This file is generated by scripts/generate-child-node-keys.ts.
7697
- // Do not edit this file directly.
7698
- const childNodeKeys = {
7699
- ArrayExpression: ['elements'],
7700
- ArrayPattern: ['elements'],
7701
- ArrowFunctionExpression: ['params', 'body'],
7702
- AssignmentExpression: ['left', 'right'],
7703
- AssignmentPattern: ['left', 'right'],
7704
- AwaitExpression: ['argument'],
7705
- BinaryExpression: ['left', 'right'],
7706
- BlockStatement: ['body'],
7707
- BreakStatement: ['label'],
7708
- CallExpression: ['callee', 'arguments'],
7709
- CatchClause: ['param', 'body'],
7710
- ChainExpression: ['expression'],
7711
- ClassBody: ['body'],
7712
- ClassDeclaration: ['decorators', 'id', 'superClass', 'body'],
7713
- ClassExpression: ['decorators', 'id', 'superClass', 'body'],
7714
- ConditionalExpression: ['test', 'consequent', 'alternate'],
7715
- ContinueStatement: ['label'],
7716
- DebuggerStatement: [],
7717
- Decorator: ['expression'],
7718
- DoWhileStatement: ['body', 'test'],
7719
- EmptyStatement: [],
7720
- ExportAllDeclaration: ['exported', 'source', 'attributes'],
7721
- ExportDefaultDeclaration: ['declaration'],
7722
- ExportNamedDeclaration: ['specifiers', 'source', 'attributes', 'declaration'],
7723
- ExportSpecifier: ['local', 'exported'],
7724
- ExpressionStatement: ['expression'],
7725
- ForInStatement: ['left', 'right', 'body'],
7726
- ForOfStatement: ['left', 'right', 'body'],
7727
- ForStatement: ['init', 'test', 'update', 'body'],
7728
- FunctionDeclaration: ['id', 'params', 'body'],
7729
- FunctionExpression: ['id', 'params', 'body'],
7730
- Identifier: [],
7731
- IfStatement: ['test', 'consequent', 'alternate'],
7732
- ImportAttribute: ['key', 'value'],
7733
- ImportDeclaration: ['specifiers', 'source', 'attributes'],
7734
- ImportDefaultSpecifier: ['local'],
7735
- ImportExpression: ['source', 'options'],
7736
- ImportNamespaceSpecifier: ['local'],
7737
- ImportSpecifier: ['imported', 'local'],
7738
- JSXAttribute: ['name', 'value'],
7739
- JSXClosingElement: ['name'],
7740
- JSXClosingFragment: [],
7741
- JSXElement: ['openingElement', 'children', 'closingElement'],
7742
- JSXEmptyExpression: [],
7743
- JSXExpressionContainer: ['expression'],
7744
- JSXFragment: ['openingFragment', 'children', 'closingFragment'],
7745
- JSXIdentifier: [],
7746
- JSXMemberExpression: ['object', 'property'],
7747
- JSXNamespacedName: ['namespace', 'name'],
7748
- JSXOpeningElement: ['name', 'attributes'],
7749
- JSXOpeningFragment: [],
7750
- JSXSpreadAttribute: ['argument'],
7751
- JSXSpreadChild: ['expression'],
7752
- JSXText: [],
7753
- LabeledStatement: ['label', 'body'],
7754
- Literal: [],
7755
- LogicalExpression: ['left', 'right'],
7756
- MemberExpression: ['object', 'property'],
7757
- MetaProperty: ['meta', 'property'],
7758
- MethodDefinition: ['decorators', 'key', 'value'],
7759
- NewExpression: ['callee', 'arguments'],
7760
- ObjectExpression: ['properties'],
7761
- ObjectPattern: ['properties'],
7762
- PanicError: [],
7763
- ParseError: [],
7764
- PrivateIdentifier: [],
7765
- Program: ['body'],
7766
- Property: ['key', 'value'],
7767
- PropertyDefinition: ['decorators', 'key', 'value'],
7768
- RestElement: ['argument'],
7769
- ReturnStatement: ['argument'],
7770
- SequenceExpression: ['expressions'],
7771
- SpreadElement: ['argument'],
7772
- StaticBlock: ['body'],
7773
- Super: [],
7774
- SwitchCase: ['test', 'consequent'],
7775
- SwitchStatement: ['discriminant', 'cases'],
7776
- TaggedTemplateExpression: ['tag', 'quasi'],
7777
- TemplateElement: [],
7778
- TemplateLiteral: ['quasis', 'expressions'],
7779
- ThisExpression: [],
7780
- ThrowStatement: ['argument'],
7781
- TryStatement: ['block', 'handler', 'finalizer'],
7782
- UnaryExpression: ['argument'],
7783
- UpdateExpression: ['argument'],
7784
- VariableDeclaration: ['declarations'],
7785
- VariableDeclarator: ['id', 'init'],
7786
- WhileStatement: ['test', 'body'],
7787
- YieldExpression: ['argument']
7788
- };
7789
-
7790
- const INCLUDE_PARAMETERS = 'variables';
7791
- const IS_SKIPPED_CHAIN = Symbol('IS_SKIPPED_CHAIN');
7792
- class NodeBase extends ExpressionEntity {
7793
- /**
7794
- * Nodes can apply custom deoptimizations once they become part of the
7795
- * executed code. To do this, they must initialize this as false, implement
7796
- * applyDeoptimizations and call this from include and hasEffects if they have
7797
- * custom handlers
7798
- */
7799
- get deoptimized() {
7800
- return isFlagSet(this.flags, 2 /* Flag.deoptimized */);
7911
+ function assembleMemberDescriptions(memberDescriptions, inheritedDescriptions = null) {
7912
+ return Object.create(inheritedDescriptions, memberDescriptions);
7913
+ }
7914
+ const UNDEFINED_EXPRESSION = new (class UndefinedExpression extends ExpressionEntity {
7915
+ getLiteralValueAtPath(path) {
7916
+ return path.length > 0 ? UnknownValue : undefined;
7801
7917
  }
7802
- set deoptimized(value) {
7803
- this.flags = setFlag(this.flags, 2 /* Flag.deoptimized */, value);
7918
+ })();
7919
+ const returnsUnknown = {
7920
+ value: {
7921
+ hasEffectsWhenCalled: null,
7922
+ returns: UNKNOWN_EXPRESSION
7804
7923
  }
7805
- constructor(parent, parentScope) {
7806
- super();
7807
- this.parent = parent;
7808
- this.scope = parentScope;
7809
- this.createScope(parentScope);
7924
+ };
7925
+ const UNKNOWN_LITERAL_BOOLEAN = new (class UnknownBoolean extends ExpressionEntity {
7926
+ getReturnExpressionWhenCalledAtPath(path) {
7927
+ if (path.length === 1) {
7928
+ return getMemberReturnExpressionWhenCalled(literalBooleanMembers, path[0]);
7929
+ }
7930
+ return UNKNOWN_RETURN_EXPRESSION;
7810
7931
  }
7811
- addExportedVariables(_variables, _exportNamesByVariable) { }
7812
- /**
7813
- * Override this to bind assignments to variables and do any initialisations
7814
- * that require the scopes to be populated with variables.
7815
- */
7816
- bind() {
7817
- for (const key of childNodeKeys[this.type]) {
7818
- const value = this[key];
7819
- if (Array.isArray(value)) {
7820
- for (const child of value) {
7821
- child?.bind();
7822
- }
7823
- }
7824
- else if (value) {
7825
- value.bind();
7826
- }
7932
+ hasEffectsOnInteractionAtPath(path, interaction, context) {
7933
+ if (interaction.type === INTERACTION_ACCESSED) {
7934
+ return path.length > 1;
7827
7935
  }
7936
+ if (interaction.type === INTERACTION_CALLED && path.length === 1) {
7937
+ return hasMemberEffectWhenCalled(literalBooleanMembers, path[0], interaction, context);
7938
+ }
7939
+ return true;
7828
7940
  }
7829
- /**
7830
- * Override if this node should receive a different scope than the parent
7831
- * scope.
7832
- */
7833
- createScope(parentScope) {
7834
- this.scope = parentScope;
7941
+ })();
7942
+ const returnsBoolean = {
7943
+ value: {
7944
+ hasEffectsWhenCalled: null,
7945
+ returns: UNKNOWN_LITERAL_BOOLEAN
7835
7946
  }
7836
- hasEffects(context) {
7837
- if (!this.deoptimized)
7838
- this.applyDeoptimizations();
7839
- for (const key of childNodeKeys[this.type]) {
7840
- const value = this[key];
7841
- if (value === null)
7842
- continue;
7843
- if (Array.isArray(value)) {
7844
- for (const child of value) {
7845
- if (child?.hasEffects(context))
7846
- return true;
7847
- }
7848
- }
7849
- else if (value.hasEffects(context))
7850
- return true;
7947
+ };
7948
+ const UNKNOWN_LITERAL_NUMBER = new (class UnknownNumber extends ExpressionEntity {
7949
+ getReturnExpressionWhenCalledAtPath(path) {
7950
+ if (path.length === 1) {
7951
+ return getMemberReturnExpressionWhenCalled(literalNumberMembers, path[0]);
7851
7952
  }
7852
- return false;
7953
+ return UNKNOWN_RETURN_EXPRESSION;
7853
7954
  }
7854
- hasEffectsAsAssignmentTarget(context, _checkAccess) {
7855
- return (this.hasEffects(context) ||
7856
- this.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.assignmentInteraction, context));
7955
+ hasEffectsOnInteractionAtPath(path, interaction, context) {
7956
+ if (interaction.type === INTERACTION_ACCESSED) {
7957
+ return path.length > 1;
7958
+ }
7959
+ if (interaction.type === INTERACTION_CALLED && path.length === 1) {
7960
+ return hasMemberEffectWhenCalled(literalNumberMembers, path[0], interaction, context);
7961
+ }
7962
+ return true;
7857
7963
  }
7858
- include(context, includeChildrenRecursively, _options) {
7859
- if (!this.included)
7860
- this.includeNode(context);
7861
- for (const key of childNodeKeys[this.type]) {
7862
- const value = this[key];
7863
- if (value === null)
7864
- continue;
7865
- if (Array.isArray(value)) {
7866
- for (const child of value) {
7867
- child?.include(context, includeChildrenRecursively);
7868
- }
7869
- }
7870
- else {
7871
- value.include(context, includeChildrenRecursively);
7872
- }
7964
+ })();
7965
+ const returnsNumber = {
7966
+ value: {
7967
+ hasEffectsWhenCalled: null,
7968
+ returns: UNKNOWN_LITERAL_NUMBER
7969
+ }
7970
+ };
7971
+ const UNKNOWN_LITERAL_STRING = new (class UnknownString extends ExpressionEntity {
7972
+ getReturnExpressionWhenCalledAtPath(path) {
7973
+ if (path.length === 1) {
7974
+ return getMemberReturnExpressionWhenCalled(literalStringMembers, path[0]);
7873
7975
  }
7976
+ return UNKNOWN_RETURN_EXPRESSION;
7874
7977
  }
7875
- includeNode(context) {
7876
- this.included = true;
7877
- if (!this.deoptimized)
7878
- this.applyDeoptimizations();
7879
- for (const key of childNodeKeys[this.type]) {
7880
- const value = this[key];
7881
- if (value === null)
7882
- continue;
7883
- if (Array.isArray(value)) {
7884
- for (const child of value) {
7885
- child?.includePath(UNKNOWN_PATH, context);
7886
- }
7887
- }
7888
- else {
7889
- value.includePath(UNKNOWN_PATH, context);
7890
- }
7978
+ hasEffectsOnInteractionAtPath(path, interaction, context) {
7979
+ if (interaction.type === INTERACTION_ACCESSED) {
7980
+ return path.length > 1;
7891
7981
  }
7982
+ if (interaction.type === INTERACTION_CALLED && path.length === 1) {
7983
+ return hasMemberEffectWhenCalled(literalStringMembers, path[0], interaction, context);
7984
+ }
7985
+ return true;
7892
7986
  }
7893
- includeAsAssignmentTarget(context, includeChildrenRecursively, _deoptimizeAccess) {
7894
- this.include(context, includeChildrenRecursively);
7987
+ })();
7988
+ const returnsString = {
7989
+ value: {
7990
+ hasEffectsWhenCalled: null,
7991
+ returns: UNKNOWN_LITERAL_STRING
7895
7992
  }
7896
- /**
7897
- * Override to perform special initialisation steps after the scope is
7898
- * initialised
7899
- */
7900
- initialise() {
7901
- this.scope.context.magicString.addSourcemapLocation(this.start);
7902
- this.scope.context.magicString.addSourcemapLocation(this.end);
7993
+ };
7994
+ const stringReplace = {
7995
+ value: {
7996
+ hasEffectsWhenCalled({ args }, context) {
7997
+ const argument1 = args[2];
7998
+ return (args.length < 3 ||
7999
+ (typeof argument1.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, {
8000
+ deoptimizeCache() { }
8001
+ }) === 'symbol' &&
8002
+ argument1.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, context)));
8003
+ },
8004
+ returns: UNKNOWN_LITERAL_STRING
8005
+ }
8006
+ };
8007
+ const objectMembers = assembleMemberDescriptions({
8008
+ hasOwnProperty: returnsBoolean,
8009
+ isPrototypeOf: returnsBoolean,
8010
+ propertyIsEnumerable: returnsBoolean,
8011
+ toLocaleString: returnsString,
8012
+ toString: returnsString,
8013
+ valueOf: returnsUnknown
8014
+ });
8015
+ const literalBooleanMembers = assembleMemberDescriptions({
8016
+ valueOf: returnsBoolean
8017
+ }, objectMembers);
8018
+ const literalNumberMembers = assembleMemberDescriptions({
8019
+ toExponential: returnsString,
8020
+ toFixed: returnsString,
8021
+ toLocaleString: returnsString,
8022
+ toPrecision: returnsString,
8023
+ valueOf: returnsNumber
8024
+ }, objectMembers);
8025
+ /**
8026
+ * RegExp are stateful when they have the global or sticky flags set.
8027
+ * But if we actually don't use them, the side effect does not matter.
8028
+ * the check logic in `hasEffectsOnInteractionAtPath`.
8029
+ */
8030
+ const literalRegExpMembers = assembleMemberDescriptions({
8031
+ exec: returnsUnknown,
8032
+ test: returnsBoolean
8033
+ }, objectMembers);
8034
+ const literalStringMembers = assembleMemberDescriptions({
8035
+ anchor: returnsString,
8036
+ at: returnsUnknown,
8037
+ big: returnsString,
8038
+ blink: returnsString,
8039
+ bold: returnsString,
8040
+ charAt: returnsString,
8041
+ charCodeAt: returnsNumber,
8042
+ codePointAt: returnsUnknown,
8043
+ concat: returnsString,
8044
+ endsWith: returnsBoolean,
8045
+ fixed: returnsString,
8046
+ fontcolor: returnsString,
8047
+ fontsize: returnsString,
8048
+ includes: returnsBoolean,
8049
+ indexOf: returnsNumber,
8050
+ italics: returnsString,
8051
+ lastIndexOf: returnsNumber,
8052
+ link: returnsString,
8053
+ localeCompare: returnsNumber,
8054
+ match: returnsUnknown,
8055
+ matchAll: returnsUnknown,
8056
+ normalize: returnsString,
8057
+ padEnd: returnsString,
8058
+ padStart: returnsString,
8059
+ repeat: returnsString,
8060
+ replace: stringReplace,
8061
+ replaceAll: stringReplace,
8062
+ search: returnsNumber,
8063
+ slice: returnsString,
8064
+ small: returnsString,
8065
+ split: returnsUnknown,
8066
+ startsWith: returnsBoolean,
8067
+ strike: returnsString,
8068
+ sub: returnsString,
8069
+ substr: returnsString,
8070
+ substring: returnsString,
8071
+ sup: returnsString,
8072
+ toLocaleLowerCase: returnsString,
8073
+ toLocaleUpperCase: returnsString,
8074
+ toLowerCase: returnsString,
8075
+ toString: returnsString, // overrides the toString() method of the Object object; it does not inherit Object.prototype.toString()
8076
+ toUpperCase: returnsString,
8077
+ trim: returnsString,
8078
+ trimEnd: returnsString,
8079
+ trimLeft: returnsString,
8080
+ trimRight: returnsString,
8081
+ trimStart: returnsString,
8082
+ valueOf: returnsString
8083
+ }, objectMembers);
8084
+ function getLiteralMembersForValue(value) {
8085
+ if (value instanceof RegExp) {
8086
+ return literalRegExpMembers;
7903
8087
  }
7904
- removeAnnotations(code) {
7905
- if (this.annotations) {
7906
- for (const annotation of this.annotations) {
7907
- code.remove(annotation.start, annotation.end);
7908
- }
8088
+ switch (typeof value) {
8089
+ case 'boolean': {
8090
+ return literalBooleanMembers;
7909
8091
  }
7910
- }
7911
- render(code, options) {
7912
- for (const key of childNodeKeys[this.type]) {
7913
- const value = this[key];
7914
- if (value === null)
7915
- continue;
7916
- if (Array.isArray(value)) {
7917
- for (const child of value) {
7918
- child?.render(code, options);
7919
- }
7920
- }
7921
- else {
7922
- value.render(code, options);
7923
- }
8092
+ case 'number': {
8093
+ return literalNumberMembers;
7924
8094
  }
7925
- }
7926
- setAssignedValue(value) {
7927
- this.assignmentInteraction = { args: [null, value], type: INTERACTION_ASSIGNED };
7928
- }
7929
- shouldBeIncluded(context) {
7930
- return this.included || (!context.brokenFlow && this.hasEffects(createHasEffectsContext()));
7931
- }
7932
- /**
7933
- * Just deoptimize everything by default so that when e.g. we do not track
7934
- * something properly, it is deoptimized.
7935
- * @protected
7936
- */
7937
- applyDeoptimizations() {
7938
- this.deoptimized = true;
7939
- for (const key of childNodeKeys[this.type]) {
7940
- const value = this[key];
7941
- if (value === null)
7942
- continue;
7943
- if (Array.isArray(value)) {
7944
- for (const child of value) {
7945
- child?.deoptimizePath(UNKNOWN_PATH);
7946
- }
7947
- }
7948
- else {
7949
- value.deoptimizePath(UNKNOWN_PATH);
7950
- }
8095
+ case 'string': {
8096
+ return literalStringMembers;
7951
8097
  }
7952
- this.scope.context.requestTreeshakingPass();
7953
8098
  }
8099
+ return Object.create(null);
7954
8100
  }
7955
- function onlyIncludeSelf() {
7956
- this.included = true;
7957
- if (!this.deoptimized)
7958
- this.applyDeoptimizations();
7959
- }
7960
- function onlyIncludeSelfNoDeoptimize() {
7961
- this.included = true;
7962
- }
7963
- function doNotDeoptimize() {
7964
- this.deoptimized = true;
7965
- }
7966
-
7967
- function isObjectExpressionNode(node) {
7968
- return node instanceof NodeBase && node.type === parseAst_js.ObjectExpression;
7969
- }
7970
- function isArrowFunctionExpressionNode(node) {
7971
- return node instanceof NodeBase && node.type === parseAst_js.ArrowFunctionExpression;
7972
- }
7973
- function isFunctionExpressionNode(node) {
7974
- return node instanceof NodeBase && node.type === parseAst_js.FunctionExpression;
8101
+ function hasMemberEffectWhenCalled(members, memberName, interaction, context) {
8102
+ if (typeof memberName !== 'string' || !members[memberName]) {
8103
+ return true;
8104
+ }
8105
+ return members[memberName].hasEffectsWhenCalled?.(interaction, context) || false;
7975
8106
  }
7976
- function isIdentifierNode(node) {
7977
- return node instanceof NodeBase && node.type === parseAst_js.Identifier;
8107
+ function getMemberReturnExpressionWhenCalled(members, memberName) {
8108
+ if (typeof memberName !== 'string' || !members[memberName])
8109
+ return UNKNOWN_RETURN_EXPRESSION;
8110
+ return [members[memberName].returns, false];
7978
8111
  }
7979
8112
 
7980
8113
  class Method extends ExpressionEntity {
@@ -8257,6 +8390,17 @@ class ObjectEntity extends ExpressionEntity {
8257
8390
  }
8258
8391
  this.prototypeExpression?.deoptimizePath(path.length === 1 ? [path[0], UnknownKey] : path);
8259
8392
  }
8393
+ getKnownFunctionAtPath(path, recursionTracker, origin) {
8394
+ const key = path[0];
8395
+ // Setters can shadow data properties or inherited methods without appearing in the getter map.
8396
+ if (!isConcreteKey(key) || this.settersByKey.has(key) || this.unmatchableSetters.length > 0) {
8397
+ return null;
8398
+ }
8399
+ const expressionAtPath = this.getMemberExpressionAndTrackDeopt(key, origin);
8400
+ return expressionAtPath
8401
+ ? expressionAtPath.getKnownFunctionAtPath(path.slice(1), recursionTracker, origin)
8402
+ : this.prototypeExpression?.getKnownFunctionAtPath(path, recursionTracker, origin) || null;
8403
+ }
8260
8404
  getLiteralValueAtPath(path, recursionTracker, origin) {
8261
8405
  if (path.length === 0) {
8262
8406
  // This should actually be "UnknownTruthyValue". However, this currently
@@ -8513,22 +8657,25 @@ class ObjectEntity extends ExpressionEntity {
8513
8657
  }
8514
8658
  }
8515
8659
 
8516
- const isInteger = (property) => typeof property === 'string' && /^\d+$/.test(property);
8660
+ const isKnownToBeMissing = (property) => property === SymbolDispose ||
8661
+ property === SymbolAsyncDispose ||
8662
+ (typeof property === 'string' && /^\d+$/.test(property));
8517
8663
  // This makes sure unknown properties are not handled as "undefined" but as
8518
8664
  // "unknown" but without access side effects. An exception is done for numeric
8519
8665
  // properties as we do not expect new builtin properties to be numbers, this
8520
- // will improve tree-shaking for out-of-bounds array properties
8666
+ // will improve tree-shaking for out-of-bounds array properties. Disposal
8667
+ // methods are also known to be missing so that "await using" can rely on the
8668
+ // fallback to Symbol.dispose for plain objects.
8521
8669
  const OBJECT_PROTOTYPE_FALLBACK = new (class ObjectPrototypeFallbackExpression extends ExpressionEntity {
8522
8670
  deoptimizeArgumentsOnInteractionAtPath(interaction, path) {
8523
- if (interaction.type === INTERACTION_CALLED && path.length === 1 && !isInteger(path[0])) {
8671
+ if (interaction.type === INTERACTION_CALLED &&
8672
+ path.length === 1 &&
8673
+ !isKnownToBeMissing(path[0])) {
8524
8674
  deoptimizeInteraction(interaction);
8525
8675
  }
8526
8676
  }
8527
8677
  getLiteralValueAtPath(path) {
8528
- // We ignore number properties as we do not expect new properties to be
8529
- // numbers and also want to keep handling out-of-bound array elements as
8530
- // "undefined"
8531
- return path.length === 1 && isInteger(path[0]) ? undefined : UnknownValue;
8678
+ return path.length === 1 && isKnownToBeMissing(path[0]) ? undefined : UnknownValue;
8532
8679
  }
8533
8680
  hasEffectsOnInteractionAtPath(path, { type }) {
8534
8681
  return path.length > 1 || type === INTERACTION_CALLED;
@@ -8542,6 +8689,9 @@ const OBJECT_PROTOTYPE = new ObjectEntity(new Map([
8542
8689
  ['toString', METHOD_RETURNS_STRING],
8543
8690
  ['valueOf', METHOD_RETURNS_UNKNOWN]
8544
8691
  ]), OBJECT_PROTOTYPE_FALLBACK, true);
8692
+ // Generator prototypes inherit disposal methods from the iterator prototypes
8693
+ const GENERATOR_PROTOTYPE = new ObjectEntity([{ key: SymbolDispose, kind: 'init', property: UNKNOWN_EXPRESSION }], OBJECT_PROTOTYPE, true);
8694
+ const ASYNC_GENERATOR_PROTOTYPE = new ObjectEntity([{ key: SymbolAsyncDispose, kind: 'init', property: UNKNOWN_EXPRESSION }], OBJECT_PROTOTYPE, true);
8545
8695
 
8546
8696
  const NEW_ARRAY_PROPERTIES = [
8547
8697
  { key: UnknownInteger, kind: 'init', property: UNKNOWN_EXPRESSION },
@@ -8686,7 +8836,8 @@ const ARRAY_PROTOTYPE = new ObjectEntity(new Map([
8686
8836
 
8687
8837
  class SpreadElement extends NodeBase {
8688
8838
  deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
8689
- if (path.length > 0) {
8839
+ // Spread values are copied as data properties, so only calling them can still reach the argument
8840
+ if (path.length > 0 || interaction.type === INTERACTION_CALLED) {
8690
8841
  this.argument.deoptimizeArgumentsOnInteractionAtPath(interaction, UNKNOWN_PATH, recursionTracker);
8691
8842
  }
8692
8843
  }
@@ -8814,6 +8965,18 @@ const PURE_WITH_ARRAY = {
8814
8965
  return args.length > 1 && !(args[1] instanceof ArrayExpression);
8815
8966
  }
8816
8967
  };
8968
+ const PURE_WITH_ARRAY_OR_LENGTH = {
8969
+ deoptimizeArgumentsOnCall: doNothing,
8970
+ getLiteralValue: getUnknownValue,
8971
+ hasEffectsWhenCalled({ args }) {
8972
+ const [_thisArgument, firstArgument] = args;
8973
+ return (firstArgument !== undefined &&
8974
+ !(firstArgument instanceof ArrayExpression) &&
8975
+ typeof firstArgument.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, {
8976
+ deoptimizeCache: doNothing
8977
+ }) !== 'number');
8978
+ }
8979
+ };
8817
8980
  const GETTER_ACCESS = {
8818
8981
  deoptimizeArgumentsOnCall: doNothing,
8819
8982
  getLiteralValue: getUnknownValue,
@@ -8872,7 +9035,7 @@ const PC_WITH_ARRAY = {
8872
9035
  };
8873
9036
  const ARRAY_TYPE = {
8874
9037
  __proto__: null,
8875
- [ValueProperties]: PURE,
9038
+ [ValueProperties]: PURE_WITH_ARRAY_OR_LENGTH,
8876
9039
  from: O,
8877
9040
  of: PF,
8878
9041
  prototype: O
@@ -9849,6 +10012,9 @@ class IdentifierBase extends NodeBase {
9849
10012
  // Identifier as property that might be deoptimized by default
9850
10013
  this.variable?.deoptimizePath(path);
9851
10014
  }
10015
+ getKnownFunctionAtPath(path, recursionTracker, origin) {
10016
+ return this.getVariableRespectingTDZ().getKnownFunctionAtPath(path, recursionTracker, origin);
10017
+ }
9852
10018
  getLiteralValueAtPath(path, recursionTracker, origin) {
9853
10019
  return this.getVariableRespectingTDZ().getLiteralValueAtPath(path, recursionTracker, origin);
9854
10020
  }
@@ -10040,6 +10206,9 @@ class Identifier extends IdentifierBase {
10040
10206
  this.variable = this.scope.findVariable(this.name);
10041
10207
  this.variable.addReference(this);
10042
10208
  this.isVariableReference = true;
10209
+ if (this.assignmentInteraction) {
10210
+ this.variable.markTargetOfAssignment();
10211
+ }
10043
10212
  }
10044
10213
  }
10045
10214
  declare(kind, destructuredInitPath, init) {
@@ -10157,6 +10326,11 @@ class PropertyBase extends NodeBase {
10157
10326
  deoptimizePath(path) {
10158
10327
  this.getAccessedValue()[0].deoptimizePath(path);
10159
10328
  }
10329
+ getKnownFunctionAtPath(path, recursionTracker, origin) {
10330
+ return this.kind === 'get' || this.kind === 'set'
10331
+ ? null
10332
+ : this.value.getKnownFunctionAtPath(path, recursionTracker, origin);
10333
+ }
10160
10334
  getLiteralValueAtPath(path, recursionTracker, origin) {
10161
10335
  return this.getAccessedValue()[0].getLiteralValueAtPath(path, recursionTracker, origin);
10162
10336
  }
@@ -10206,9 +10380,51 @@ class MethodDefinition extends PropertyBase {
10206
10380
  }
10207
10381
  }
10208
10382
 
10383
+ class PropertyDefinition extends NodeBase {
10384
+ get computed() {
10385
+ return isFlagSet(this.flags, 1024 /* Flag.computed */);
10386
+ }
10387
+ set computed(value) {
10388
+ this.flags = setFlag(this.flags, 1024 /* Flag.computed */, value);
10389
+ }
10390
+ deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
10391
+ this.value?.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
10392
+ }
10393
+ deoptimizePath(path) {
10394
+ this.value?.deoptimizePath(path);
10395
+ }
10396
+ getLiteralValueAtPath(path, recursionTracker, origin) {
10397
+ return this.value
10398
+ ? this.value.getLiteralValueAtPath(path, recursionTracker, origin)
10399
+ : UnknownValue;
10400
+ }
10401
+ getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
10402
+ return this.value
10403
+ ? this.value.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)
10404
+ : UNKNOWN_RETURN_EXPRESSION;
10405
+ }
10406
+ hasEffects(context) {
10407
+ return (this.key.hasEffects(context) ||
10408
+ (this.static && !!this.value?.hasEffects(context)) ||
10409
+ checkEffectForNodes(this.decorators, context));
10410
+ }
10411
+ hasEffectsOnInteractionAtPath(path, interaction, context) {
10412
+ return !this.value || this.value.hasEffectsOnInteractionAtPath(path, interaction, context);
10413
+ }
10414
+ includeNode(context) {
10415
+ this.included = true;
10416
+ this.value?.includePath(UNKNOWN_PATH, context);
10417
+ for (const decorator of this.decorators) {
10418
+ decorator.includePath(UNKNOWN_PATH, context);
10419
+ }
10420
+ }
10421
+ }
10422
+ PropertyDefinition.prototype.applyDeoptimizations = doNotDeoptimize;
10423
+
10209
10424
  class ClassNode extends NodeBase {
10210
10425
  constructor() {
10211
10426
  super(...arguments);
10427
+ this.instanceFieldValues = null;
10212
10428
  this.objectEntity = null;
10213
10429
  }
10214
10430
  createScope(parentScope) {
@@ -10242,7 +10458,7 @@ class ClassNode extends NodeBase {
10242
10458
  (this.classConstructor === null
10243
10459
  ? this.superClass?.hasEffectsOnInteractionAtPath(path, interaction, context)
10244
10460
  : this.classConstructor.hasEffectsOnInteractionAtPath(path, interaction, context)) ||
10245
- false
10461
+ this.hasEffectsOnInstanceFieldInitialization(context)
10246
10462
  : this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
10247
10463
  }
10248
10464
  include(context, includeChildrenRecursively) {
@@ -10260,6 +10476,10 @@ class ClassNode extends NodeBase {
10260
10476
  initialise() {
10261
10477
  super.initialise();
10262
10478
  this.id?.declare('class', EMPTY_PATH, this);
10479
+ this.instanceEntity = new ObjectEntity(new Map(), new ObjectMember(this, ['prototype']));
10480
+ // This makes sure that all deoptimizations of "this" are applied to the
10481
+ // instance entity, even if the class is only instantiated by unknown code.
10482
+ this.body.scope.instanceThisVariable.addArgumentForDeoptimization(this.instanceEntity);
10263
10483
  for (const method of this.body.body) {
10264
10484
  if (method instanceof MethodDefinition && method.kind === 'constructor') {
10265
10485
  this.classConstructor = method;
@@ -10280,6 +10500,36 @@ class ClassNode extends NodeBase {
10280
10500
  }
10281
10501
  this.scope.context.requestTreeshakingPass();
10282
10502
  }
10503
+ hasEffectsOnInstanceFieldInitialization(context) {
10504
+ const fieldValues = this.getInstanceFieldValues();
10505
+ if (fieldValues.length === 0)
10506
+ return false;
10507
+ const { replacedVariableInits } = context;
10508
+ const thisVariable = this.body.scope.instanceThisVariable;
10509
+ const thisInit = replacedVariableInits.get(thisVariable);
10510
+ replacedVariableInits.set(thisVariable, this.instanceEntity);
10511
+ const hasEffects = fieldValues.some(value => value.hasEffects(context));
10512
+ if (thisInit) {
10513
+ replacedVariableInits.set(thisVariable, thisInit);
10514
+ }
10515
+ else {
10516
+ replacedVariableInits.delete(thisVariable);
10517
+ }
10518
+ return hasEffects;
10519
+ }
10520
+ getInstanceFieldValues() {
10521
+ if (this.instanceFieldValues === null) {
10522
+ this.instanceFieldValues = [];
10523
+ for (const definition of this.body.body) {
10524
+ if (definition instanceof PropertyDefinition &&
10525
+ !definition.static &&
10526
+ definition.value !== null) {
10527
+ this.instanceFieldValues.push(definition.value);
10528
+ }
10529
+ }
10530
+ }
10531
+ return this.instanceFieldValues;
10532
+ }
10283
10533
  getObjectEntity() {
10284
10534
  if (this.objectEntity !== null) {
10285
10535
  return this.objectEntity;
@@ -10594,12 +10844,39 @@ class ParameterVariable extends LocalVariable {
10594
10844
  class ThisVariable extends ParameterVariable {
10595
10845
  constructor(context) {
10596
10846
  super('this', null, EMPTY_PATH, context);
10847
+ // Unlike parameters, track nested paths so receivers only keep what is accessed via "this"
10848
+ this.includedPathTracker = new IncludedFullPathTracker();
10597
10849
  }
10598
10850
  hasEffectsOnInteractionAtPath(path, interaction, context) {
10599
10851
  return (context.replacedVariableInits.get(this) || UNKNOWN_EXPRESSION).hasEffectsOnInteractionAtPath(path, interaction, context);
10600
10852
  }
10601
10853
  }
10602
10854
 
10855
+ /**
10856
+ * Represents the return value of a function where all return statements return
10857
+ * the same variable that is the target of an assignment. As the assigned value
10858
+ * may replace the declaration initializer before the function returns, value
10859
+ * queries resolve to unknown, and call arguments are deoptimized directly
10860
+ * instead of being forwarded to the initializer alone.
10861
+ */
10862
+ class ReturnedIdentifier extends ExpressionEntity {
10863
+ constructor(returnedIdentifier) {
10864
+ super();
10865
+ this.returnedIdentifier = returnedIdentifier;
10866
+ }
10867
+ deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
10868
+ // The initializer may never be the value that is returned
10869
+ deoptimizeInteraction(interaction);
10870
+ this.returnedIdentifier.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
10871
+ }
10872
+ deoptimizePath(path) {
10873
+ this.returnedIdentifier.deoptimizePath(path);
10874
+ }
10875
+ includeCallArgumentsWhenCalledAtPath(path, interaction, context) {
10876
+ this.returnedIdentifier.includeCallArgumentsWhenCalledAtPath(path, interaction, context);
10877
+ }
10878
+ }
10879
+
10603
10880
  class CatchBodyScope extends ChildScope {
10604
10881
  constructor(parent) {
10605
10882
  super(parent, parent.context);
@@ -10708,6 +10985,9 @@ class ParameterScope extends ChildScope {
10708
10985
  }
10709
10986
  this.hasRest = hasRest;
10710
10987
  }
10988
+ hasParameterCalledFromTryStatement() {
10989
+ return this.parameters.some(parameterVariables => parameterVariables.some(variable => variable.calledFromTryStatement));
10990
+ }
10711
10991
  includeCallArguments({ args }, context) {
10712
10992
  let calledFromTryStatement = false;
10713
10993
  let argumentIncluded = false;
@@ -10831,21 +11111,21 @@ class ReturnValueScope extends ParameterScope {
10831
11111
  addArgumentToBeDeoptimized(_argument) { }
10832
11112
  updateReturnExpression() {
10833
11113
  const { returnExpressions } = this;
10834
- if (returnExpressions.length === 1) {
10835
- this.returnExpression = returnExpressions[0];
11114
+ const [firstExpression] = returnExpressions;
11115
+ // A single return, or the same variable returned on all paths, can be
11116
+ // resolved to that variable
11117
+ if (firstExpression && this.returnExpressionsResolveToSameVariable(firstExpression)) {
11118
+ this.returnExpression = firstExpression.variable.isTargetOfAssignment
11119
+ ? new ReturnedIdentifier(firstExpression)
11120
+ : firstExpression;
11121
+ }
11122
+ else if (returnExpressions.length === 1) {
11123
+ this.returnExpression = firstExpression;
10836
11124
  }
10837
11125
  else {
10838
- // Returning the same variable on all paths is equivalent to a single
10839
- // return, so the return expression can be resolved to that variable
10840
- const [firstExpression] = returnExpressions;
10841
- if (firstExpression && this.returnExpressionsResolveToSameVariable(firstExpression)) {
10842
- this.returnExpression = firstExpression;
10843
- }
10844
- else {
10845
- this.returnExpression = UNKNOWN_EXPRESSION;
10846
- for (const expression of returnExpressions) {
10847
- expression.deoptimizePath(UNKNOWN_PATH);
10848
- }
11126
+ this.returnExpression = UNKNOWN_EXPRESSION;
11127
+ for (const expression of returnExpressions) {
11128
+ expression.deoptimizePath(UNKNOWN_PATH);
10849
11129
  }
10850
11130
  }
10851
11131
  }
@@ -10870,8 +11150,11 @@ class FunctionScope extends ReturnValueScope {
10870
11150
  }
10871
11151
  includeCallArguments(interaction, context) {
10872
11152
  super.includeCallArguments(interaction, context);
11153
+ const { args } = interaction;
11154
+ if (args[0]) {
11155
+ this.thisVariable.includeArgumentPaths(args[0], context);
11156
+ }
10873
11157
  if (this.argumentsVariable.included) {
10874
- const { args } = interaction;
10875
11158
  for (let argumentIndex = 1; argumentIndex < args.length; argumentIndex++) {
10876
11159
  const argument = args[argumentIndex];
10877
11160
  if (argument) {
@@ -11056,6 +11339,11 @@ class FunctionBase extends NodeBase {
11056
11339
  this.scope.deoptimizeAllParameters();
11057
11340
  }
11058
11341
  }
11342
+ getKnownFunctionAtPath(path, recursionTracker, origin) {
11343
+ return path.length === 0
11344
+ ? this
11345
+ : this.getObjectEntity().getKnownFunctionAtPath(path, recursionTracker, origin);
11346
+ }
11059
11347
  getLiteralValueAtPath(path, recursionTracker, origin) {
11060
11348
  return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
11061
11349
  }
@@ -11063,7 +11351,7 @@ class FunctionBase extends NodeBase {
11063
11351
  if (path.length > 0) {
11064
11352
  return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
11065
11353
  }
11066
- if (this.async) {
11354
+ if (this.async || this.generator) {
11067
11355
  if (!this.deoptimizedReturn) {
11068
11356
  this.deoptimizedReturn = true;
11069
11357
  this.scope.getReturnExpression().deoptimizePath(UNKNOWN_PATH);
@@ -11248,10 +11536,15 @@ class FunctionNode extends FunctionBase {
11248
11536
  {
11249
11537
  key: 'prototype',
11250
11538
  kind: 'init',
11251
- property: new ObjectEntity([], OBJECT_PROTOTYPE)
11539
+ property: new ObjectEntity([], this.getPrototypeOfPrototype())
11252
11540
  }
11253
11541
  ], OBJECT_PROTOTYPE));
11254
11542
  }
11543
+ getPrototypeOfPrototype() {
11544
+ if (!this.generator)
11545
+ return OBJECT_PROTOTYPE;
11546
+ return this.async ? ASYNC_GENERATOR_PROTOTYPE : GENERATOR_PROTOTYPE;
11547
+ }
11255
11548
  }
11256
11549
 
11257
11550
  class FunctionDeclaration extends FunctionNode {
@@ -11383,12 +11676,19 @@ ExportDefaultDeclaration.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
11383
11676
  ExportDefaultDeclaration.prototype.applyDeoptimizations = doNotDeoptimize;
11384
11677
 
11385
11678
  const needsEscapeRegEx = /[\n\r'\\\u2028\u2029]/;
11386
- const quoteNewlineRegEx = /([\n\r'\u2028\u2029])/g;
11387
- const backSlashRegEx = /\\/g;
11679
+ const escapeRegEx = /[\n\r'\\\u2028\u2029]/g;
11680
+ const escapeReplacements = {
11681
+ '\n': '\\n',
11682
+ '\r': '\\r',
11683
+ "'": "\\'",
11684
+ '\\': '\\\\',
11685
+ '\u2028': '\\u2028',
11686
+ '\u2029': '\\u2029'
11687
+ };
11388
11688
  function escapeId(id) {
11389
11689
  if (!needsEscapeRegEx.test(id))
11390
11690
  return id;
11391
- return id.replace(backSlashRegEx, '\\\\').replace(quoteNewlineRegEx, '\\$1');
11691
+ return id.replace(escapeRegEx, character => escapeReplacements[character]);
11392
11692
  }
11393
11693
 
11394
11694
  const INTEROP_DEFAULT_VARIABLE = '_interopDefault';
@@ -11804,6 +12104,20 @@ class MemberExpression extends NodeBase {
11804
12104
  ]);
11805
12105
  }
11806
12106
  }
12107
+ getKnownFunctionAtPath(path, recursionTracker, origin) {
12108
+ if (this.variable) {
12109
+ return this.variable.getKnownFunctionAtPath(path, recursionTracker, origin);
12110
+ }
12111
+ if (this.isUndefined)
12112
+ return null;
12113
+ const propertyKey = this.getDynamicPropertyKey();
12114
+ if (propertyKey !== UnknownKey && path.length < MAX_PATH_DEPTH) {
12115
+ if (propertyKey !== this.propertyKey)
12116
+ this.expressionsToBeDeoptimized.push(origin);
12117
+ return this.object.getKnownFunctionAtPath([propertyKey, ...path], recursionTracker, origin);
12118
+ }
12119
+ return null;
12120
+ }
11807
12121
  getLiteralValueAtPath(path, recursionTracker, origin) {
11808
12122
  if (this.variable) {
11809
12123
  return this.variable.getLiteralValueAtPath(path, recursionTracker, origin);
@@ -12591,7 +12905,7 @@ function getCompleteAmdId(options, chunkId) {
12591
12905
  }
12592
12906
 
12593
12907
  function getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings, reexportProtoFromExternal, mechanism = 'return ') {
12594
- const { _, getDirectReturnFunction, getFunctionIntro, getPropertyAccess, n, s } = snippets;
12908
+ const { _, getFunctionIntro, getPropertyAccess, n, s } = snippets;
12595
12909
  if (!namedExportsMode) {
12596
12910
  return `${n}${n}${mechanism}${getSingleDefaultExport(exports, dependencies, interop, externalLiveBindings, getPropertyAccess)};`;
12597
12911
  }
@@ -12607,15 +12921,7 @@ function getExportBlock$1(exports, dependencies, namedExportsMode, interop, snip
12607
12921
  if (exportBlock)
12608
12922
  exportBlock += n;
12609
12923
  if (specifier.imported !== '*' && specifier.needsLiveBinding) {
12610
- const [left, right] = getDirectReturnFunction([], {
12611
- functionReturn: true,
12612
- lineBreakIndent: null,
12613
- name: null
12614
- });
12615
- exportBlock +=
12616
- `Object.defineProperty(exports,${_}${JSON.stringify(specifier.reexported)},${_}{${n}` +
12617
- `${t}enumerable:${_}true,${n}` +
12618
- `${t}get:${_}${left}${importName}${right}${n}});`;
12924
+ exportBlock += `Object.defineProperty(exports,${_}${JSON.stringify(specifier.reexported)},${_}${getGetter(importName, false, t, snippets)});`;
12619
12925
  }
12620
12926
  else if (specifier.reexported === '__proto__') {
12621
12927
  exportBlock +=
@@ -12630,12 +12936,16 @@ function getExportBlock$1(exports, dependencies, namedExportsMode, interop, snip
12630
12936
  }
12631
12937
  }
12632
12938
  }
12633
- for (const { exported, local } of exports) {
12939
+ for (const { exported, local, needsLiveBinding } of exports) {
12634
12940
  const lhs = `exports${getPropertyAccess(exported)}`;
12635
12941
  const rhs = local;
12636
12942
  if (lhs !== rhs) {
12637
12943
  if (exportBlock)
12638
12944
  exportBlock += n;
12945
+ if (needsLiveBinding) {
12946
+ exportBlock += `Object.defineProperty(exports,${_}${JSON.stringify(exported)},${_}${getGetter(rhs, true, t, snippets)});`;
12947
+ continue;
12948
+ }
12639
12949
  exportBlock +=
12640
12950
  exported === '__proto__'
12641
12951
  ? `Object.defineProperty(exports,${_}"__proto__",${_}{${n}` +
@@ -12737,19 +13047,27 @@ function getNamespaceMarkers(hasNamedExports, addEsModule, addNamespaceToStringT
12737
13047
  }
12738
13048
  return '';
12739
13049
  }
12740
- const getDefineProperty = (name, needsLiveBinding, t, { _, getDirectReturnFunction, n }) => {
13050
+ const getDefineProperty = (name, needsLiveBinding, t, snippets) => {
13051
+ const { _ } = snippets;
12741
13052
  if (needsLiveBinding) {
12742
- const [left, right] = getDirectReturnFunction([], {
12743
- functionReturn: true,
12744
- lineBreakIndent: null,
12745
- name: null
12746
- });
12747
- return (`Object.defineProperty(exports,${_}k,${_}{${n}` +
12748
- `${t}${t}enumerable:${_}true,${n}` +
12749
- `${t}${t}get:${_}${left}${name}[k]${right}${n}${t}})`);
13053
+ return `Object.defineProperty(exports,${_}k,${_}${getGetter(`${name}[k]`, false, t, snippets, t)})`;
12750
13054
  }
12751
13055
  return `exports[k]${_}=${_}${name}[k]`;
12752
13056
  };
13057
+ const getGetter = (expression, configurable, t, { getDirectReturnFunction, getObject }, base = '') => {
13058
+ const [left, right] = getDirectReturnFunction([], {
13059
+ functionReturn: true,
13060
+ lineBreakIndent: null,
13061
+ name: null
13062
+ });
13063
+ const fields = [
13064
+ ['enumerable', 'true'],
13065
+ ['get', `${left}${expression}${right}`]
13066
+ ];
13067
+ if (configurable)
13068
+ fields.unshift(['configurable', 'true']);
13069
+ return getObject(fields, { lineBreakIndent: { base, t } });
13070
+ };
12753
13071
 
12754
13072
  function getInteropBlock(dependencies, interop, externalLiveBindings, freeze, symbols, accessedGlobals, indent, snippets) {
12755
13073
  const { _, cnst, n } = snippets;
@@ -13602,17 +13920,29 @@ function getMatcherString(id, resolutionBase) {
13602
13920
  }
13603
13921
  const createFilter = function createFilter(include, exclude, options) {
13604
13922
  const resolutionBase = options && options.resolve;
13605
- const getMatcher = (id) => id instanceof RegExp
13606
- ? id
13607
- : {
13923
+ const getMatcher = (id) => {
13924
+ if (id instanceof RegExp) {
13925
+ return id;
13926
+ }
13927
+ // Compiling a pattern costs far more than matching against it, so only recompile when the cwd it resolves against changes
13928
+ const compile = () => pm(getMatcherString(id, resolutionBase), { dot: true });
13929
+ // These patterns never resolve against the cwd, so there is no need to read or track it
13930
+ if (resolutionBase === false || path.isAbsolute(id) || id.startsWith('**')) {
13931
+ return { test: compile() };
13932
+ }
13933
+ let compiledCwd = process.cwd();
13934
+ let fn = compile();
13935
+ return {
13608
13936
  test: (what) => {
13609
- // this refactor is a tad overly verbose but makes for easy debugging
13610
- const pattern = getMatcherString(id, resolutionBase);
13611
- const fn = pm(pattern, { dot: true });
13612
- const result = fn(what);
13613
- return result;
13937
+ const cwd = process.cwd();
13938
+ if (cwd !== compiledCwd) {
13939
+ compiledCwd = cwd;
13940
+ fn = compile();
13941
+ }
13942
+ return fn(what);
13614
13943
  }
13615
13944
  };
13945
+ };
13616
13946
  const includeMatchers = ensureArray(include).map(getMatcher);
13617
13947
  const excludeMatchers = ensureArray(exclude).map(getMatcher);
13618
13948
  if (!includeMatchers.length && !excludeMatchers.length)
@@ -13725,6 +14055,14 @@ class ArrayPattern extends NodeBase {
13725
14055
  }
13726
14056
  }
13727
14057
  }
14058
+ setAssignedValue(value) {
14059
+ super.setAssignedValue(value);
14060
+ // Destructuring assigns each target only some subpath of the assigned
14061
+ // value, which is not tracked
14062
+ for (const element of this.elements) {
14063
+ element?.setAssignedValue(UNKNOWN_EXPRESSION);
14064
+ }
14065
+ }
13728
14066
  markDeclarationReached() {
13729
14067
  for (const element of this.elements) {
13730
14068
  element?.markDeclarationReached();
@@ -13894,6 +14232,14 @@ class ObjectPattern extends NodeBase {
13894
14232
  }
13895
14233
  }
13896
14234
  }
14235
+ setAssignedValue(value) {
14236
+ super.setAssignedValue(value);
14237
+ // Destructuring assigns each target only some subpath of the assigned
14238
+ // value, which is not tracked
14239
+ for (const property of this.properties) {
14240
+ property.setAssignedValue(UNKNOWN_EXPRESSION);
14241
+ }
14242
+ }
13897
14243
  }
13898
14244
  ObjectPattern.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
13899
14245
  ObjectPattern.prototype.applyDeoptimizations = doNotDeoptimize;
@@ -14058,6 +14404,9 @@ class AssignmentPattern extends NodeBase {
14058
14404
  this.left.render(code, options, { isShorthandProperty });
14059
14405
  this.right.render(code, options);
14060
14406
  }
14407
+ setAssignedValue(value) {
14408
+ this.left.setAssignedValue(value);
14409
+ }
14061
14410
  applyDeoptimizations() {
14062
14411
  this.deoptimized = true;
14063
14412
  this.left.deoptimizePath(EMPTY_PATH);
@@ -14066,6 +14415,22 @@ class AssignmentPattern extends NodeBase {
14066
14415
  }
14067
14416
  }
14068
14417
 
14418
+ function markTopLevelAwait(node) {
14419
+ if (node.scope.context.usesTopLevelAwait)
14420
+ return;
14421
+ let parent = node.parent;
14422
+ while (parent) {
14423
+ const { type } = parent;
14424
+ if (type === parseAst_js.ArrowFunctionExpression ||
14425
+ type === parseAst_js.FunctionExpression ||
14426
+ type === parseAst_js.FunctionDeclaration) {
14427
+ return;
14428
+ }
14429
+ parent = parent.parent;
14430
+ }
14431
+ node.scope.context.usesTopLevelAwait = true;
14432
+ }
14433
+
14069
14434
  class AwaitExpression extends NodeBase {
14070
14435
  deoptimizePath(path) {
14071
14436
  this.argument.deoptimizePath(path);
@@ -14077,16 +14442,7 @@ class AwaitExpression extends NodeBase {
14077
14442
  }
14078
14443
  initialise() {
14079
14444
  super.initialise();
14080
- let parent = this.parent;
14081
- do {
14082
- const { type } = parent;
14083
- if (type === parseAst_js.ArrowFunctionExpression ||
14084
- type === parseAst_js.FunctionExpression ||
14085
- type === parseAst_js.FunctionDeclaration) {
14086
- return;
14087
- }
14088
- } while ((parent = parent.parent));
14089
- this.scope.context.usesTopLevelAwait = true;
14445
+ markTopLevelAwait(this);
14090
14446
  }
14091
14447
  include(context, includeChildrenRecursively) {
14092
14448
  if (!this.included)
@@ -14567,7 +14923,8 @@ class ClassBodyScope extends ChildScope {
14567
14923
  super(parent, context);
14568
14924
  this.variables.set('this', (this.thisVariable = new LocalVariable('this', null, classNode, EMPTY_PATH, context, 'other')));
14569
14925
  this.instanceScope = new ChildScope(this, context);
14570
- this.instanceScope.variables.set('this', new ThisVariable(context));
14926
+ this.instanceThisVariable = new ThisVariable(context);
14927
+ this.instanceScope.variables.set('this', this.instanceThisVariable);
14571
14928
  }
14572
14929
  findLexicalBoundary() {
14573
14930
  return this;
@@ -15059,6 +15416,8 @@ class ForOfStatement extends NodeBase {
15059
15416
  }
15060
15417
  initialise() {
15061
15418
  super.initialise();
15419
+ if (this.await)
15420
+ markTopLevelAwait(this);
15062
15421
  this.left.setAssignedValue(UNKNOWN_EXPRESSION);
15063
15422
  }
15064
15423
  render(code, options) {
@@ -15763,19 +16122,17 @@ class JSXAttribute extends NodeBase {
15763
16122
  }
15764
16123
  if (value) {
15765
16124
  code.overwrite(name.end, value.start, ': ', { contentOnly: true });
15766
- // foo="aa \n aa"
15767
- if (value instanceof Literal &&
15768
- typeof value.value === 'string' &&
15769
- value.value.includes('\n')) {
15770
- code.overwrite(value.start, value.end, JSON.stringify(value.value), {
15771
- contentOnly: true
15772
- });
15773
- }
15774
16125
  }
15775
16126
  else {
15776
16127
  code.appendLeft(name.end, ': true');
15777
16128
  }
15778
16129
  }
16130
+ // JSX strings contain HTML entities but no escape sequences
16131
+ if (value instanceof Literal && typeof value.value === 'string') {
16132
+ code.overwrite(value.start, value.end, JSON.stringify(value.value), {
16133
+ contentOnly: true
16134
+ });
16135
+ }
15779
16136
  }
15780
16137
  }
15781
16138
  }
@@ -16560,6 +16917,9 @@ class ObjectExpression extends NodeBase {
16560
16917
  deoptimizePath(path) {
16561
16918
  this.getObjectEntity().deoptimizePath(path);
16562
16919
  }
16920
+ getKnownFunctionAtPath(path, recursionTracker, origin) {
16921
+ return this.getObjectEntity().getKnownFunctionAtPath(path, recursionTracker, origin);
16922
+ }
16563
16923
  getLiteralValueAtPath(path, recursionTracker, origin) {
16564
16924
  return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
16565
16925
  }
@@ -16815,6 +17175,9 @@ class Property extends PropertyBase {
16815
17175
  }
16816
17176
  this.value.render(code, options, { isShorthandProperty: this.shorthand });
16817
17177
  }
17178
+ setAssignedValue(value) {
17179
+ this.value.setAssignedValue(value);
17180
+ }
16818
17181
  getPathInProperty(destructuredInitPath) {
16819
17182
  return destructuredInitPath.at(-1) === UnknownKey
16820
17183
  ? destructuredInitPath
@@ -16830,47 +17193,6 @@ class Property extends PropertyBase {
16830
17193
  Property.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
16831
17194
  Property.prototype.applyDeoptimizations = doNotDeoptimize;
16832
17195
 
16833
- class PropertyDefinition extends NodeBase {
16834
- get computed() {
16835
- return isFlagSet(this.flags, 1024 /* Flag.computed */);
16836
- }
16837
- set computed(value) {
16838
- this.flags = setFlag(this.flags, 1024 /* Flag.computed */, value);
16839
- }
16840
- deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
16841
- this.value?.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
16842
- }
16843
- deoptimizePath(path) {
16844
- this.value?.deoptimizePath(path);
16845
- }
16846
- getLiteralValueAtPath(path, recursionTracker, origin) {
16847
- return this.value
16848
- ? this.value.getLiteralValueAtPath(path, recursionTracker, origin)
16849
- : UnknownValue;
16850
- }
16851
- getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
16852
- return this.value
16853
- ? this.value.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)
16854
- : UNKNOWN_RETURN_EXPRESSION;
16855
- }
16856
- hasEffects(context) {
16857
- return (this.key.hasEffects(context) ||
16858
- (this.static && !!this.value?.hasEffects(context)) ||
16859
- checkEffectForNodes(this.decorators, context));
16860
- }
16861
- hasEffectsOnInteractionAtPath(path, interaction, context) {
16862
- return !this.value || this.value.hasEffectsOnInteractionAtPath(path, interaction, context);
16863
- }
16864
- includeNode(context) {
16865
- this.included = true;
16866
- this.value?.includePath(UNKNOWN_PATH, context);
16867
- for (const decorator of this.decorators) {
16868
- decorator.includePath(UNKNOWN_PATH, context);
16869
- }
16870
- }
16871
- }
16872
- PropertyDefinition.prototype.applyDeoptimizations = doNotDeoptimize;
16873
-
16874
17196
  class RestElement extends NodeBase {
16875
17197
  constructor() {
16876
17198
  super(...arguments);
@@ -16915,6 +17237,9 @@ class RestElement extends NodeBase {
16915
17237
  markDeclarationReached() {
16916
17238
  this.argument.markDeclarationReached();
16917
17239
  }
17240
+ setAssignedValue(value) {
17241
+ this.argument.setAssignedValue(value);
17242
+ }
16918
17243
  applyDeoptimizations() {
16919
17244
  this.deoptimized = true;
16920
17245
  if (this.declarationInit !== null) {
@@ -17678,6 +18003,8 @@ class VariableDeclaration extends NodeBase {
17678
18003
  }
17679
18004
  initialise() {
17680
18005
  super.initialise();
18006
+ if (this.kind === 'await using')
18007
+ markTopLevelAwait(this);
17681
18008
  for (const declarator of this.declarations) {
17682
18009
  declarator.declareDeclarator(this.kind);
17683
18010
  }
@@ -17843,6 +18170,14 @@ class VariableDeclarator extends NodeBase {
17843
18170
  deoptimizePath(path) {
17844
18171
  this.id.deoptimizePath(path);
17845
18172
  }
18173
+ deoptimizeCache() {
18174
+ if (!this.hasDeoptimizedDisposal && this.init) {
18175
+ this.hasDeoptimizedDisposal = true;
18176
+ this.init.deoptimizePath(UNKNOWN_PATH);
18177
+ this.init.includePath(UNKNOWN_PATH, createInclusionContext());
18178
+ this.scope.context.requestTreeshakingPass();
18179
+ }
18180
+ }
17846
18181
  hasEffects(context) {
17847
18182
  const initEffect = this.init?.hasEffects(context);
17848
18183
  this.id.markDeclarationReached();
@@ -17858,6 +18193,11 @@ class VariableDeclarator extends NodeBase {
17858
18193
  const { id, init } = this;
17859
18194
  if (!this.included)
17860
18195
  this.includeNode(context);
18196
+ const { disposalCall, disposalFunction } = this;
18197
+ // Before including init so that newly included receiver paths are included in this pass
18198
+ if (disposalFunction && disposalCall) {
18199
+ disposalFunction.includeCallArgumentsWhenCalledAtPath(EMPTY_PATH, disposalCall, context);
18200
+ }
17861
18201
  init?.include(context, includeChildrenRecursively);
17862
18202
  id.markDeclarationReached();
17863
18203
  if (includeChildrenRecursively) {
@@ -17899,11 +18239,16 @@ class VariableDeclarator extends NodeBase {
17899
18239
  this.included = true;
17900
18240
  const { id, init } = this;
17901
18241
  if (init) {
17902
- if (this.isUsingDeclaration) {
17903
- init.includePath(SYMBOL_DISPOSE_PATH, context);
17904
- }
17905
- else if (this.isAsyncUsingDeclaration) {
17906
- init.includePath(SYMBOL_ASYNC_DISPOSE_PATH, context);
18242
+ if (this.isUsingDeclaration || this.isAsyncUsingDeclaration) {
18243
+ const disposalInteractions = {
18244
+ access: { args: [init], type: INTERACTION_ACCESSED },
18245
+ call: { args: [init], type: INTERACTION_CALLED, withNew: false }
18246
+ };
18247
+ if (this.isUsingDeclaration ||
18248
+ !this.includeDisposalMethodAndCheckIfKnownFunction(init, SYMBOL_ASYNC_DISPOSE_PATH, disposalInteractions, context)) {
18249
+ this.includeDisposalMethodAndCheckIfKnownFunction(init, SYMBOL_DISPOSE_PATH, disposalInteractions, context);
18250
+ }
18251
+ this.scope.context.requestTreeshakingPass();
17907
18252
  }
17908
18253
  if (id instanceof Identifier && init instanceof ClassExpression && !init.id) {
17909
18254
  const { name, variable } = id;
@@ -17915,6 +18260,23 @@ class VariableDeclarator extends NodeBase {
17915
18260
  }
17916
18261
  }
17917
18262
  }
18263
+ includeDisposalMethodAndCheckIfKnownFunction(init, path, { access, call }, context) {
18264
+ init.deoptimizeArgumentsOnInteractionAtPath(access, path, SHARED_RECURSION_TRACKER);
18265
+ const disposalFunction = init.getKnownFunctionAtPath(path, SHARED_RECURSION_TRACKER, this);
18266
+ init.includePath(path, context);
18267
+ if (!disposalFunction) {
18268
+ const disposalValue = init.getLiteralValueAtPath(path, SHARED_RECURSION_TRACKER, this);
18269
+ if (disposalValue !== null && disposalValue !== undefined) {
18270
+ init.deoptimizeArgumentsOnInteractionAtPath(call, path, SHARED_RECURSION_TRACKER);
18271
+ init.includeCallArgumentsWhenCalledAtPath(path, call, context);
18272
+ }
18273
+ return false;
18274
+ }
18275
+ this.disposalFunction = disposalFunction;
18276
+ this.disposalCall = call;
18277
+ disposalFunction.deoptimizeArgumentsOnInteractionAtPath(call, EMPTY_PATH, SHARED_RECURSION_TRACKER);
18278
+ return true;
18279
+ }
17918
18280
  }
17919
18281
  VariableDeclarator.prototype.applyDeoptimizations = doNotDeoptimize;
17920
18282
  const SYMBOL_DISPOSE_PATH = [SymbolDispose];
@@ -18446,7 +18808,7 @@ const bufferParsers = [
18446
18808
  function literalNumber(node, position, buffer) {
18447
18809
  const rawPosition = buffer[position];
18448
18810
  node.raw = rawPosition === 0 ? undefined : buffer.convertString(rawPosition);
18449
- node.value = new DataView(buffer.buffer).getFloat64((position + 1) << 2, true);
18811
+ node.value = buffer.convertFloat64(position + 1);
18450
18812
  },
18451
18813
  function literalRegExp(node, position, buffer) {
18452
18814
  const flags = buffer.convertString(buffer[position]);
@@ -18708,6 +19070,9 @@ function decodedSourcemap(map) {
18708
19070
  if (typeof map === 'string') {
18709
19071
  map = JSON.parse(map);
18710
19072
  }
19073
+ if ('sections' in map) {
19074
+ map = flattenIndexSourceMap(map);
19075
+ }
18711
19076
  if (!map.mappings) {
18712
19077
  return {
18713
19078
  mappings: [],
@@ -18743,6 +19108,74 @@ function decodedSourcemap(map) {
18743
19108
  sourceMapCache.set(decodedMap, cache);
18744
19109
  return decodedMap;
18745
19110
  }
19111
+ function flattenIndexSourceMap({ file, sections }) {
19112
+ const mappings = [];
19113
+ const names = [];
19114
+ const sources = [];
19115
+ const sourcesContent = [];
19116
+ // As when collapsing sourcemaps, sources with the same name are shared unless their contents differ
19117
+ const sourceIndicesByName = new Map();
19118
+ for (const { map, offset } of sections) {
19119
+ const section = decodedSourcemap(map);
19120
+ const { sourceRoot } = section;
19121
+ const sourcePrefix = sourceRoot
19122
+ ? sourceRoot.endsWith('/')
19123
+ ? sourceRoot
19124
+ : `${sourceRoot}/`
19125
+ : '';
19126
+ const sourceIndices = section.sources.map((source, index) => {
19127
+ const name = source == null || parseAst_js.isAbsolute(source) ? source : sourcePrefix + source;
19128
+ const content = section.sourcesContent?.[index] ?? null;
19129
+ let indices = sourceIndicesByName.get(name);
19130
+ if (!indices) {
19131
+ sourceIndicesByName.set(name, (indices = []));
19132
+ }
19133
+ let sourceIndex = indices.find(candidate => content == null ||
19134
+ sourcesContent[candidate] == null ||
19135
+ sourcesContent[candidate] === content);
19136
+ if (sourceIndex === undefined) {
19137
+ sourceIndex = sources.push(name) - 1;
19138
+ sourcesContent.push(content);
19139
+ indices.push(sourceIndex);
19140
+ }
19141
+ else {
19142
+ sourcesContent[sourceIndex] ??= content;
19143
+ }
19144
+ return sourceIndex;
19145
+ });
19146
+ const namesOffset = names.length;
19147
+ for (const name of section.names ?? []) {
19148
+ names.push(name);
19149
+ }
19150
+ for (const [lineIndex, line] of section.mappings.entries()) {
19151
+ const generatedLine = offset.line + lineIndex;
19152
+ while (mappings.length <= generatedLine) {
19153
+ mappings.push([]);
19154
+ }
19155
+ // Only the first line of a section starts at the column offset
19156
+ const columnOffset = lineIndex === 0 ? offset.column : 0;
19157
+ for (const segment of line) {
19158
+ const flatSegment = segment.slice();
19159
+ flatSegment[0] += columnOffset;
19160
+ if (flatSegment.length !== 1) {
19161
+ flatSegment[1] = sourceIndices[flatSegment[1]];
19162
+ if (flatSegment.length === 5) {
19163
+ flatSegment[4] += namesOffset;
19164
+ }
19165
+ }
19166
+ mappings[generatedLine].push(flatSegment);
19167
+ }
19168
+ }
19169
+ }
19170
+ return {
19171
+ file,
19172
+ mappings,
19173
+ names,
19174
+ sources,
19175
+ sourcesContent,
19176
+ version: 3
19177
+ };
19178
+ }
18746
19179
 
18747
19180
  function getId(m) {
18748
19181
  return m.id;
@@ -18759,7 +19192,7 @@ function getOriginalLocation(sourcemapChain, location) {
18759
19192
  let previousSegment = filteredLine[0];
18760
19193
  for (let segment of filteredLine) {
18761
19194
  if (segment[0] >= location.column || segment === lastSegment) {
18762
- const notMatched = segment[0] !== location.column;
19195
+ const notMatched = segment[0] > location.column;
18763
19196
  segment = notMatched ? previousSegment : segment;
18764
19197
  location = {
18765
19198
  column: segment[3],
@@ -19389,6 +19822,9 @@ class Module {
19389
19822
  hasEffects() {
19390
19823
  return this.info.moduleSideEffects === 'no-treeshake' || this.ast.hasCachedEffects();
19391
19824
  }
19825
+ hasTopLevelAwait() {
19826
+ return this.astContext.usesTopLevelAwait;
19827
+ }
19392
19828
  include() {
19393
19829
  const context = createInclusionContext();
19394
19830
  if (this.ast.shouldBeIncluded(context))
@@ -20003,7 +20439,8 @@ function deconflictImportsEsmOrSystem(usedNames, imports, dependenciesToBeDeconf
20003
20439
  for (const variable of imports) {
20004
20440
  const module = variable.module;
20005
20441
  const name = variable.name;
20006
- if (variable.isNamespace && (preserveModules || module instanceof ExternalModule)) {
20442
+ if (variable.isNamespace &&
20443
+ (module instanceof ExternalModule || (preserveModules && !module.info.syntheticNamedExports))) {
20007
20444
  variable.setRenderNames(null, (module instanceof ExternalModule
20008
20445
  ? externalChunkByModule.get(module)
20009
20446
  : chunkByModule.get(module)).variableName);
@@ -20067,7 +20504,7 @@ function deconflictImportsOther(usedNames, imports, { deconflictedDefault, decon
20067
20504
  }
20068
20505
  else {
20069
20506
  const chunk = chunkByModule.get(module);
20070
- if (preserveModules && variable.isNamespace) {
20507
+ if (preserveModules && variable.isNamespace && !module.info.syntheticNamedExports) {
20071
20508
  variable.setRenderNames(null, chunk.exportMode === 'default' ? chunk.namespaceVariableName : chunk.variableName);
20072
20509
  }
20073
20510
  else if (chunk.exportMode === 'default') {
@@ -20327,7 +20764,8 @@ class Chunk {
20327
20764
  const chunkModules = new Set(orderedModules);
20328
20765
  for (const module of orderedModules) {
20329
20766
  chunkByModule.set(module, this);
20330
- if (module.namespace.included && !outputOptions.preserveModules) {
20767
+ if (module.namespace.included &&
20768
+ (!outputOptions.preserveModules || module.info.syntheticNamedExports)) {
20331
20769
  includedNamespaces.add(module);
20332
20770
  }
20333
20771
  if (this.isEmpty && module.isIncluded()) {
@@ -20631,11 +21069,16 @@ class Chunk {
20631
21069
  });
20632
21070
  }
20633
21071
  getVariableExportName(variable) {
20634
- if (this.outputOptions.preserveModules && variable instanceof NamespaceVariable) {
21072
+ if (this.isNativeNamespace(variable)) {
20635
21073
  return '*';
20636
21074
  }
20637
21075
  return this.exportNamesByVariable.get(variable)[0];
20638
21076
  }
21077
+ isNativeNamespace(variable) {
21078
+ return (this.outputOptions.preserveModules &&
21079
+ variable instanceof NamespaceVariable &&
21080
+ !variable.module.info.syntheticNamedExports);
21081
+ }
20639
21082
  link() {
20640
21083
  this.dependencies = getStaticDependencies(this, this.orderedModules, this.chunkByModule, this.externalChunkByModule);
20641
21084
  for (const module of this.orderedModules) {
@@ -20663,6 +21106,7 @@ class Chunk {
20663
21106
  const { accessedGlobals, indent, magicString, renderedSource, usedModules, usesTopLevelAwait } = this.renderModules(preliminaryFileName.fileName);
20664
21107
  const renderedDependencies = [...this.getRenderedDependencies().values()];
20665
21108
  const renderedExports = exportMode === 'none' ? [] : this.getChunkExportDeclarations(format);
21109
+ const renderedExportNames = format === 'es' && new Set(renderedExports.map(({ exported }) => exported));
20666
21110
  let hasExports = renderedExports.length > 0;
20667
21111
  let hasDefaultExport = false;
20668
21112
  for (const renderedDependency of renderedDependencies) {
@@ -20672,8 +21116,8 @@ class Chunk {
20672
21116
  if (!hasDefaultExport && reexports.some(reexport => reexport.reexported === 'default')) {
20673
21117
  hasDefaultExport = true;
20674
21118
  }
20675
- if (format === 'es') {
20676
- renderedDependency.reexports = reexports.filter(({ reexported }) => !renderedExports.find(({ exported }) => exported === reexported));
21119
+ if (renderedExportNames) {
21120
+ renderedDependency.reexports = reexports.filter(({ reexported }) => !renderedExportNames.has(reexported));
20677
21121
  }
20678
21122
  }
20679
21123
  }
@@ -20777,8 +21221,9 @@ class Chunk {
20777
21221
  const importedVariable = isSynthetic ? exportedVariable.getBaseVariable() : exportedVariable;
20778
21222
  this.checkCircularDependencyImport(importedVariable, module);
20779
21223
  // When preserving modules, we do not create namespace objects but directly
20780
- // use the actual namespaces, which would be broken by this logic.
20781
- if (!(importedVariable instanceof NamespaceVariable && this.outputOptions.preserveModules)) {
21224
+ // use the actual namespaces, which would be broken by this logic. Modules with
21225
+ // synthetic named exports still need a namespace object.
21226
+ if (!this.isNativeNamespace(importedVariable)) {
20782
21227
  const exportingModule = importedVariable.module;
20783
21228
  if (exportingModule instanceof Module) {
20784
21229
  const chunk = this.chunkByModule.get(exportingModule);
@@ -20862,7 +21307,8 @@ class Chunk {
20862
21307
  exported: exportName,
20863
21308
  expression,
20864
21309
  hoisted,
20865
- local
21310
+ local,
21311
+ needsLiveBinding: variable.isReassigned && this.exportNamesByVariable.get(variable).length > 1
20866
21312
  });
20867
21313
  }
20868
21314
  return exports;
@@ -21349,9 +21795,8 @@ class Chunk {
21349
21795
  }
21350
21796
  setUpChunkImportsAndExportsForModule(module) {
21351
21797
  const moduleImports = new Set(module.includedImports);
21352
- // when we are not preserving modules, we need to make all namespace variables available for
21353
- // rendering the namespace object
21354
- if (!this.outputOptions.preserveModules && this.includedNamespaces.has(module)) {
21798
+ // we need to make all namespace variables available for rendering the namespace object
21799
+ if (this.includedNamespaces.has(module)) {
21355
21800
  for (const variable of module.getExportedVariablesByName().values()) {
21356
21801
  if (variable.included) {
21357
21802
  moduleImports.add(variable);
@@ -21371,8 +21816,9 @@ class Chunk {
21371
21816
  if (variable.module instanceof Module) {
21372
21817
  this.checkCircularDependencyImport(variable, module);
21373
21818
  // When preserving modules, we do not create namespace objects but directly
21374
- // use the actual namespaces, which would be broken by this logic.
21375
- if (!(variable instanceof NamespaceVariable && this.outputOptions.preserveModules)) {
21819
+ // use the actual namespaces, which would be broken by this logic. Modules with
21820
+ // synthetic named exports still need a namespace object.
21821
+ if (!this.isNativeNamespace(variable)) {
21376
21822
  chunk.exports.add(variable);
21377
21823
  }
21378
21824
  }
@@ -21565,7 +22011,8 @@ function getChunkAssignments(entries, manualChunkAliasByEntry, minChunkSize, log
21565
22011
  // Warning: This will consume dynamicallyDependentEntriesByDynamicEntry.
21566
22012
  // If we no longer want this, we should make a copy here.
21567
22013
  const alreadyLoadedAtomsByEntry = getAlreadyLoadedAtomsByEntry(staticDependencyAtomsByEntry, dynamicallyDependentEntriesByDynamicEntry, dynamicImportsByEntry, entriesAndManualChunksCount);
21568
- const awaitedAlreadyLoadedAtomsByEntry = getAlreadyLoadedAtomsByEntry(staticDependencyAtomsByEntry, dynamicallyDependentEntriesByAwaitedDynamicEntry, awaitedDynamicImportsByEntry, entriesAndManualChunksCount);
22014
+ // Warning: This will consume dynamicallyDependentEntriesByAwaitedDynamicEntry.
22015
+ const awaitedAlreadyLoadedAtomsByEntry = getAwaitedAlreadyLoadedAtomsByEntry(staticDependencyAtomsByEntry, dynamicallyDependentEntriesByAwaitedDynamicEntry, awaitedDynamicImportsByEntry, entriesAndManualChunksCount);
21569
22016
  // A manual chunk only behaves like a dynamic entry if its whole member atom
21570
22017
  // is not already loaded whenever any entry dynamically loads it. Otherwise
21571
22018
  // there is nothing to gain (and cycles could be created) and the manual
@@ -21668,9 +22115,11 @@ function analyzeModuleGraph(entries, manualChunks, manualChunkByModule, manualCh
21668
22115
  dynamicManualChunksForCurrentEntry;
21669
22116
  awaitedLoadedManualChunksByEntry[entryOrManualChunkIndex] = awaitedManualChunksForCurrentEntry;
21670
22117
  const staticDependencies = new Set(currentEntryModules);
22118
+ let hasTopLevelAwait = false;
21671
22119
  // If we have a very large manual chunk, tracking if it is already added to the dependencies will improve performance
21672
22120
  const addedManualChunks = new Set();
21673
22121
  for (const module of staticDependencies) {
22122
+ hasTopLevelAwait ||= module.hasTopLevelAwait();
21674
22123
  getOrCreate(dependentEntriesByModule, module, (getNewSet)).add(entryOrManualChunkIndex);
21675
22124
  const manualChunk = manualChunkByModule.get(module);
21676
22125
  if (manualChunk && !addedManualChunks.has(manualChunk)) {
@@ -21685,7 +22134,6 @@ function analyzeModuleGraph(entries, manualChunks, manualChunkByModule, manualCh
21685
22134
  }
21686
22135
  }
21687
22136
  for (const { node: { resolution } } of module.dynamicImports) {
21688
- let manuallyLoadedChunk = null;
21689
22137
  if (resolution instanceof Module && resolution.includedDynamicImporters.length > 0) {
21690
22138
  if (!allEntriesSet.has(resolution)) {
21691
22139
  dynamicEntryModules.add(resolution);
@@ -21693,25 +22141,13 @@ function analyzeModuleGraph(entries, manualChunks, manualChunkByModule, manualCh
21693
22141
  allEntriesAndManualChunks.push([resolution]);
21694
22142
  }
21695
22143
  else if (!dynamicEntryModules.has(resolution)) {
21696
- manuallyLoadedChunk = manualChunkByModule.get(resolution) ?? null;
22144
+ const manuallyLoadedChunk = manualChunkByModule.get(resolution);
21697
22145
  if (!manuallyLoadedChunk) {
21698
22146
  continue;
21699
22147
  }
21700
22148
  dynamicManualChunksForCurrentEntry.add(manuallyLoadedChunk);
21701
22149
  }
21702
22150
  dynamicImportsForCurrentEntry.add(resolution);
21703
- for (const includedTopLevelAwaitingDynamicImporter of resolution.includedTopLevelAwaitingDynamicImporters) {
21704
- if (staticDependencies.has(includedTopLevelAwaitingDynamicImporter)) {
21705
- awaitedDynamicImportsForCurrentEntry.add(resolution);
21706
- if (manuallyLoadedChunk) {
21707
- awaitedManualChunksForCurrentEntry.add(manuallyLoadedChunk);
21708
- }
21709
- else {
21710
- awaitedDynamicEntryModules.add(resolution);
21711
- }
21712
- break;
21713
- }
21714
- }
21715
22151
  }
21716
22152
  }
21717
22153
  for (const dependency of module.implicitlyLoadedBefore) {
@@ -21729,13 +22165,30 @@ function analyzeModuleGraph(entries, manualChunks, manualChunkByModule, manualCh
21729
22165
  }
21730
22166
  }
21731
22167
  }
22168
+ // A dynamic import can be awaited indirectly through a static dependency:
22169
+ // if any module of this entry uses a top-level await, the entry may
22170
+ // still be evaluating when any of its dynamic imports runs, so all of
22171
+ // them are awaited. This includes manual chunks that are loaded
22172
+ // dynamically or implicitly, which behave like dynamic entries here.
22173
+ if (hasTopLevelAwait) {
22174
+ for (const dynamicImportTarget of dynamicImportsForCurrentEntry) {
22175
+ const manualChunk = manualChunkByModule.get(dynamicImportTarget);
22176
+ if (manualChunk) {
22177
+ awaitedManualChunksForCurrentEntry.add(manualChunk);
22178
+ }
22179
+ else {
22180
+ awaitedDynamicEntryModules.add(dynamicImportTarget);
22181
+ }
22182
+ awaitedDynamicImportsForCurrentEntry.add(dynamicImportTarget);
22183
+ }
22184
+ }
21732
22185
  entryOrManualChunkIndex++;
21733
22186
  }
21734
22187
  const { awaitedDynamicEntries, awaitedDynamicImportsByEntry, dynamicEntries, dynamicImportsByEntry } = getDynamicEntries(allEntriesAndManualChunks, dynamicEntryModules, dynamicImportModulesByEntry, awaitedDynamicEntryModules, awaitedDynamicImportModulesByEntry, dynamicallyLoadedManualChunksByEntry, awaitedLoadedManualChunksByEntry, manualChunkIndexByChunk);
21735
22188
  return {
21736
22189
  awaitedDynamicImportsByEntry,
21737
22190
  dependentEntriesByModule,
21738
- dynamicallyDependentEntriesByAwaitedDynamicEntry: getDynamicallyDependentEntriesByDynamicEntry(dependentEntriesByModule, awaitedDynamicEntries, allEntriesAndManualChunks, dynamicEntry => dynamicEntry.includedTopLevelAwaitingDynamicImporters),
22191
+ dynamicallyDependentEntriesByAwaitedDynamicEntry: addAwaitingEntries(getDynamicallyDependentEntriesByDynamicEntry(dependentEntriesByModule, awaitedDynamicEntries, allEntriesAndManualChunks, dynamicEntry => dynamicEntry.includedTopLevelAwaitingDynamicImporters), awaitedDynamicImportsByEntry),
21739
22192
  dynamicallyDependentEntriesByDynamicEntry: getDynamicallyDependentEntriesByDynamicEntry(dependentEntriesByModule, dynamicEntries, allEntriesAndManualChunks, dynamicEntry => dynamicEntry.includedDynamicImporters),
21740
22193
  dynamicImportsByEntry,
21741
22194
  entriesAndManualChunksCount: allEntriesAndManualChunks.length
@@ -21789,6 +22242,18 @@ function getDynamicImportsByEntry(dynamicImportModulesByEntry, entryIndexByModul
21789
22242
  }
21790
22243
  return dynamicImportsByEntry;
21791
22244
  }
22245
+ // A dynamic entry can be awaited by an entry even if the importing module does
22246
+ // not have a top-level await itself, e.g. if the import is inside a function
22247
+ // that is awaited in the entry. In that case, the entry is still evaluating
22248
+ // when the dynamic entry is executed, so we add all awaiting entries here.
22249
+ function addAwaitingEntries(dynamicallyDependentEntriesByAwaitedDynamicEntry, awaitedDynamicImportsByEntry) {
22250
+ for (const [entryIndex, awaitedDynamicImports] of awaitedDynamicImportsByEntry.entries()) {
22251
+ for (const dynamicEntryIndex of awaitedDynamicImports) {
22252
+ getOrCreate(dynamicallyDependentEntriesByAwaitedDynamicEntry, dynamicEntryIndex, (getNewSet)).add(entryIndex);
22253
+ }
22254
+ }
22255
+ return dynamicallyDependentEntriesByAwaitedDynamicEntry;
22256
+ }
21792
22257
  function getDynamicallyDependentEntriesByDynamicEntry(dependentEntriesByModule, dynamicEntries, allEntriesAndManualChunks, getDynamicImporters) {
21793
22258
  const dynamicallyDependentEntriesByDynamicEntry = new Map();
21794
22259
  for (const dynamicEntryIndex of dynamicEntries) {
@@ -21884,6 +22349,34 @@ function getAlreadyLoadedAtomsByEntry(staticDependencyAtomsByEntry, dynamicallyD
21884
22349
  }
21885
22350
  return alreadyLoadedAtomsByEntry;
21886
22351
  }
22352
+ // Warning: This will consume dynamicallyDependentEntriesByAwaitedDynamicEntry.
22353
+ function getAwaitedAlreadyLoadedAtomsByEntry(staticDependencyAtomsByEntry, dynamicallyDependentEntriesByAwaitedDynamicEntry, awaitedDynamicImportsByEntry, allEntriesCount) {
22354
+ // Unlike already loaded atoms, this is a union and not an intersection: If
22355
+ // any importer that is still evaluating while it awaits a dynamic entry has
22356
+ // loaded an atom, merging that atom into the chunk of this importer would
22357
+ // create a cycle. Entries that are not awaited have no such atoms.
22358
+ const awaitedAlreadyLoadedAtomsByEntry = new Array(allEntriesCount).fill(0n);
22359
+ for (const [dynamicEntryIndex, dynamicallyDependentEntries] of dynamicallyDependentEntriesByAwaitedDynamicEntry) {
22360
+ // We delete here so that they can be added again if necessary to be handled
22361
+ // again by the loop
22362
+ dynamicallyDependentEntriesByAwaitedDynamicEntry.delete(dynamicEntryIndex);
22363
+ const knownLoadedAtoms = awaitedAlreadyLoadedAtomsByEntry[dynamicEntryIndex];
22364
+ let updatedLoadedAtoms = knownLoadedAtoms;
22365
+ for (const entryIndex of dynamicallyDependentEntries) {
22366
+ updatedLoadedAtoms |=
22367
+ staticDependencyAtomsByEntry[entryIndex] | awaitedAlreadyLoadedAtomsByEntry[entryIndex];
22368
+ }
22369
+ // If the knownLoadedAtoms changed, all awaited dynamic imports of this
22370
+ // entry need to be updated again
22371
+ if (updatedLoadedAtoms !== knownLoadedAtoms) {
22372
+ awaitedAlreadyLoadedAtomsByEntry[dynamicEntryIndex] = updatedLoadedAtoms;
22373
+ for (const dynamicImport of awaitedDynamicImportsByEntry[dynamicEntryIndex]) {
22374
+ getOrCreate(dynamicallyDependentEntriesByAwaitedDynamicEntry, dynamicImport, (getNewSet)).add(dynamicEntryIndex);
22375
+ }
22376
+ }
22377
+ }
22378
+ return awaitedAlreadyLoadedAtomsByEntry;
22379
+ }
21887
22380
  /**
21888
22381
  * Manual chunks whose member atom is already loaded in every context that
21889
22382
  * dynamically loads them must not be treated like dynamic entries as that
@@ -22521,7 +23014,10 @@ function getCollapsedSourcemap(id, originalCode, originalSourcemap, sourcemapCha
22521
23014
  const sourcesContent = originalSourcemap.sourcesContent || [];
22522
23015
  const directory = sp.dirname(id) || '.';
22523
23016
  const sourceRoot = originalSourcemap.sourceRoot || '.';
22524
- const baseSources = sources.map((source, index) => new Source(sp.resolve(directory, sourceRoot, source), sourcesContent[index]));
23017
+ // A source whose name is not known is null, and mappings to it are treated as unmapped
23018
+ const baseSources = sources.map((source, index) => source == null
23019
+ ? null
23020
+ : new Source(sp.resolve(directory, sourceRoot, source), sourcesContent[index]));
22525
23021
  source = new Link(originalSourcemap, baseSources);
22526
23022
  }
22527
23023
  else {
@@ -22554,13 +23050,17 @@ function collapseSourcemaps(file, map, modules, bundleSourcemapChain, excludeCon
22554
23050
  });
22555
23051
  }
22556
23052
  function collapseSourcemap(id, originalCode, originalSourcemap, sourcemapChain, log) {
22557
- if (sourcemapChain.length === 0) {
23053
+ if (sourcemapChain.length === 0 &&
23054
+ (!originalSourcemap || hasOnlyNamedSources(originalSourcemap))) {
22558
23055
  return originalSourcemap;
22559
23056
  }
22560
23057
  const source = getCollapsedSourcemap(id, originalCode, originalSourcemap, sourcemapChain, getLinkMap(log));
22561
23058
  const map = source.traceMappings();
22562
23059
  return decodedSourcemap({ version: 3, ...map });
22563
23060
  }
23061
+ function hasOnlyNamedSources(map) {
23062
+ return map.sources.every(source => source != null);
23063
+ }
22564
23064
 
22565
23065
  // this looks ridiculous, but it prevents sourcemap tooling from mistaking
22566
23066
  // this for an actual sourceMappingURL
@@ -22575,8 +23075,8 @@ async function renderChunks(chunks, bundle, pluginDriver, outputOptions, log) {
22575
23075
  timeStart('transform chunks', 2);
22576
23076
  const getHash = hasherByType[outputOptions.hashCharacters];
22577
23077
  const chunkGraph = getChunkGraph(chunks);
22578
- const { hashDependenciesByPlaceholder, initialHashesByPlaceholder, nonHashedChunksWithPlaceholders, placeholders, renderedChunksByPlaceholder } = await transformChunksAndGenerateContentHashes(renderedChunks, chunkGraph, outputOptions, pluginDriver, getHash, log);
22579
- const hashesByPlaceholder = generateFinalHashes(renderedChunksByPlaceholder, hashDependenciesByPlaceholder, initialHashesByPlaceholder, placeholders, bundle, getHash);
23078
+ const { hashDependenciesByPlaceholder, initialHashesByPlaceholder, nonHashedChunksWithPlaceholders, placeholders, renderedChunksByPlaceholder, usedFileNames } = await transformChunksAndGenerateContentHashes(renderedChunks, chunkGraph, outputOptions, pluginDriver, getHash, log, bundle);
23079
+ const hashesByPlaceholder = generateFinalHashes(renderedChunksByPlaceholder, hashDependenciesByPlaceholder, initialHashesByPlaceholder, placeholders, bundle, usedFileNames, getHash);
22580
23080
  addChunksToBundle(renderedChunksByPlaceholder, hashesByPlaceholder, bundle, nonHashedChunksWithPlaceholders, pluginDriver, outputOptions);
22581
23081
  timeEnd('transform chunks', 2);
22582
23082
  }
@@ -22656,7 +23156,7 @@ async function transformChunk(magicString, fileName, usedModules, chunkGraph, op
22656
23156
  map
22657
23157
  };
22658
23158
  }
22659
- async function transformChunksAndGenerateContentHashes(renderedChunks, chunkGraph, outputOptions, pluginDriver, getHash, log) {
23159
+ async function transformChunksAndGenerateContentHashes(renderedChunks, chunkGraph, outputOptions, pluginDriver, getHash, log, bundle) {
22660
23160
  const nonHashedChunksWithPlaceholders = [];
22661
23161
  const renderedChunksByPlaceholder = new Map();
22662
23162
  const hashDependenciesByPlaceholder = new Map();
@@ -22666,51 +23166,93 @@ async function transformChunksAndGenerateContentHashes(renderedChunks, chunkGrap
22666
23166
  if (hashPlaceholder)
22667
23167
  placeholders.add(hashPlaceholder);
22668
23168
  }
22669
- await Promise.all(renderedChunks.map(async ({ chunk, preliminaryFileName: { fileName, hashPlaceholder }, preliminarySourcemapFileName, magicString, usedModules }) => {
23169
+ const transformedChunks = await Promise.all(renderedChunks.map(async ({ chunk, preliminaryFileName: { fileName, hashPlaceholder }, preliminarySourcemapFileName, magicString, usedModules }) => {
22670
23170
  const transformedChunk = {
22671
23171
  chunk,
22672
23172
  fileName,
22673
23173
  sourcemapFileName: preliminarySourcemapFileName?.fileName ?? null,
22674
23174
  ...(await transformChunk(magicString, fileName, usedModules, chunkGraph, outputOptions, pluginDriver, log))
22675
23175
  };
22676
- const { code, map } = transformedChunk;
23176
+ const hashAugmentation = hashPlaceholder
23177
+ ? pluginDriver.hookReduceValueSync('augmentChunkHash', '', [chunk.getRenderedChunkInfo()], (augmentation, pluginHash) => augmentation + (pluginHash || ''))
23178
+ : '';
23179
+ return {
23180
+ hashAugmentation,
23181
+ hashPlaceholder,
23182
+ preliminarySourcemapFileName,
23183
+ transformedChunk
23184
+ };
23185
+ }));
23186
+ const usedFileNames = new Set(bundle[lowercaseBundleKeys]);
23187
+ for (const { transformedChunk, hashPlaceholder, preliminarySourcemapFileName, hashAugmentation } of transformedChunks) {
23188
+ const { map } = transformedChunk;
23189
+ const sourcemapHashPlaceholder = preliminarySourcemapFileName?.hashPlaceholder;
23190
+ if (map && sourcemapHashPlaceholder) {
23191
+ const { transformedCode: normalizedSourcemap } = replacePlaceholdersWithDefaultAndGetContainedPlaceholders(map.toString(), placeholders);
23192
+ initialHashesByPlaceholder.set(sourcemapHashPlaceholder, outputOptions.sourcemap === 'inline'
23193
+ ? getHash(normalizedSourcemap).slice(0, sourcemapHashPlaceholder.length)
23194
+ : getUniqueHash(normalizedSourcemap, preliminarySourcemapFileName.fileName, sourcemapHashPlaceholder, usedFileNames, getHash));
23195
+ }
22677
23196
  if (hashPlaceholder) {
22678
- // To create a reproducible content-only hash, all placeholders are
22679
- // replaced with the same value before hashing
22680
- const { containedPlaceholders, transformedCode } = replacePlaceholdersWithDefaultAndGetContainedPlaceholders(code, placeholders);
22681
- let contentToHash = transformedCode;
22682
- const hashAugmentation = pluginDriver.hookReduceValueSync('augmentChunkHash', '', [chunk.getRenderedChunkInfo()], (augmentation, pluginHash) => {
22683
- if (pluginHash) {
22684
- augmentation += pluginHash;
22685
- }
22686
- return augmentation;
22687
- });
22688
- if (hashAugmentation) {
22689
- contentToHash += hashAugmentation;
22690
- }
22691
23197
  renderedChunksByPlaceholder.set(hashPlaceholder, transformedChunk);
22692
- hashDependenciesByPlaceholder.set(hashPlaceholder, {
22693
- containedPlaceholders,
22694
- contentHash: getHash(contentToHash)
22695
- });
23198
+ hashDependenciesByPlaceholder.set(hashPlaceholder, getChunkHash(transformedChunk, outputOptions, getHash, placeholders, initialHashesByPlaceholder, hashAugmentation));
22696
23199
  }
22697
23200
  else {
22698
23201
  nonHashedChunksWithPlaceholders.push(transformedChunk);
22699
23202
  }
22700
- const sourcemapHashPlaceholder = preliminarySourcemapFileName?.hashPlaceholder;
22701
- if (map && sourcemapHashPlaceholder) {
22702
- initialHashesByPlaceholder.set(preliminarySourcemapFileName.hashPlaceholder, getHash(map.toString()).slice(0, preliminarySourcemapFileName.hashPlaceholder.length));
22703
- }
22704
- }));
23203
+ }
22705
23204
  return {
22706
23205
  hashDependenciesByPlaceholder,
22707
23206
  initialHashesByPlaceholder,
22708
23207
  nonHashedChunksWithPlaceholders,
22709
23208
  placeholders,
22710
- renderedChunksByPlaceholder
23209
+ renderedChunksByPlaceholder,
23210
+ usedFileNames
22711
23211
  };
22712
23212
  }
22713
- function generateFinalHashes(renderedChunksByPlaceholder, hashDependenciesByPlaceholder, initialHashesByPlaceholder, placeholders, bundle, getHash) {
23213
+ function getChunkHash({ code, map, fileName, sourcemapFileName }, outputOptions, getHash, placeholders, initialHashesByPlaceholder, hashAugmentation) {
23214
+ // To create a reproducible content-only hash, all placeholders are
23215
+ // replaced with the same value before hashing
23216
+ const { containedPlaceholders, transformedCode } = replacePlaceholdersWithDefaultAndGetContainedPlaceholders(code, placeholders);
23217
+ let contentToHash = transformedCode;
23218
+ if (map && outputOptions.sourcemap !== 'hidden') {
23219
+ // Normalize raw map data and file names before base64 or URL encoding
23220
+ // can hide placeholders and make hashes depend on chunk order.
23221
+ let sourcemapPlaceholders;
23222
+ if (outputOptions.sourcemap === 'inline') {
23223
+ const { containedPlaceholders: inlinePlaceholders, transformedCode: sourcemapJson } = replacePlaceholdersWithDefaultAndGetContainedPlaceholders(map.toString(), placeholders);
23224
+ sourcemapPlaceholders = inlinePlaceholders;
23225
+ contentToHash += `//# ${SOURCEMAPPING_URL}=data:application/json,${sourcemapJson}\n`;
23226
+ }
23227
+ else {
23228
+ const { containedPlaceholders: externalPlaceholders, transformedCode: normalizedFileName } = replacePlaceholdersWithDefaultAndGetContainedPlaceholders(replacePlaceholders(sourcemapFileName ?? `${fileName}.map`, initialHashesByPlaceholder), placeholders);
23229
+ sourcemapPlaceholders = externalPlaceholders;
23230
+ contentToHash += getSourceMapComment(normalizedFileName, map, outputOptions.sourcemap, outputOptions.sourcemapBaseUrl);
23231
+ }
23232
+ for (const placeholder of sourcemapPlaceholders) {
23233
+ containedPlaceholders.add(placeholder);
23234
+ }
23235
+ }
23236
+ if (hashAugmentation) {
23237
+ contentToHash += hashAugmentation;
23238
+ }
23239
+ return { containedPlaceholders, contentHash: getHash(contentToHash) };
23240
+ }
23241
+ function getUniqueHash(contentToHash, fileName, placeholder, usedFileNames, getHash) {
23242
+ let finalFileName;
23243
+ let finalHash;
23244
+ do {
23245
+ // In case of a hash collision, create a hash of the hash
23246
+ if (finalHash) {
23247
+ contentToHash = finalHash;
23248
+ }
23249
+ finalHash = getHash(contentToHash).slice(0, placeholder.length);
23250
+ finalFileName = replaceSinglePlaceholder(fileName, placeholder, finalHash).toLowerCase();
23251
+ } while (usedFileNames.has(finalFileName));
23252
+ usedFileNames.add(finalFileName);
23253
+ return finalHash;
23254
+ }
23255
+ function generateFinalHashes(renderedChunksByPlaceholder, hashDependenciesByPlaceholder, initialHashesByPlaceholder, placeholders, bundle, usedFileNames, getHash) {
22714
23256
  const hashesByPlaceholder = new Map(initialHashesByPlaceholder);
22715
23257
  for (const placeholder of placeholders) {
22716
23258
  const { fileName } = renderedChunksByPlaceholder.get(placeholder);
@@ -22724,17 +23266,8 @@ function generateFinalHashes(renderedChunksByPlaceholder, hashDependenciesByPlac
22724
23266
  hashDependencyPlaceholders.add(containedPlaceholder);
22725
23267
  }
22726
23268
  }
22727
- let finalFileName;
22728
- let finalHash;
22729
- do {
22730
- // In case of a hash collision, create a hash of the hash
22731
- if (finalHash) {
22732
- contentToHash = finalHash;
22733
- }
22734
- finalHash = getHash(contentToHash).slice(0, placeholder.length);
22735
- finalFileName = replaceSinglePlaceholder(fileName, placeholder, finalHash);
22736
- } while (bundle[lowercaseBundleKeys].has(finalFileName.toLowerCase()));
22737
- bundle[finalFileName] = FILE_PLACEHOLDER;
23269
+ const finalHash = getUniqueHash(contentToHash, fileName, placeholder, usedFileNames, getHash);
23270
+ bundle[replaceSinglePlaceholder(fileName, placeholder, finalHash)] = FILE_PLACEHOLDER;
22738
23271
  hashesByPlaceholder.set(placeholder, finalHash);
22739
23272
  }
22740
23273
  return hashesByPlaceholder;
@@ -22772,15 +23305,7 @@ function addChunksToBundle(renderedChunksByPlaceholder, hashesByPlaceholder, bun
22772
23305
  }
22773
23306
  }
22774
23307
  function emitSourceMapAndGetComment(fileName, map, pluginDriver, { sourcemap, sourcemapBaseUrl }) {
22775
- let url;
22776
- if (sourcemap === 'inline') {
22777
- url = map.toUrl();
22778
- }
22779
- else {
22780
- const sourcemapFileName = sp.basename(fileName);
22781
- url = sourcemapBaseUrl
22782
- ? new URL(sourcemapFileName, sourcemapBaseUrl).toString()
22783
- : sourcemapFileName;
23308
+ if (sourcemap !== 'inline') {
22784
23309
  pluginDriver.emitFile({
22785
23310
  fileName,
22786
23311
  originalFileName: null,
@@ -22788,6 +23313,14 @@ function emitSourceMapAndGetComment(fileName, map, pluginDriver, { sourcemap, so
22788
23313
  type: 'asset'
22789
23314
  });
22790
23315
  }
23316
+ return getSourceMapComment(fileName, map, sourcemap, sourcemapBaseUrl);
23317
+ }
23318
+ function getSourceMapComment(fileName, map, sourcemap, sourcemapBaseUrl) {
23319
+ const url = sourcemap === 'inline'
23320
+ ? map.toUrl()
23321
+ : sourcemapBaseUrl
23322
+ ? new URL(sp.basename(fileName), sourcemapBaseUrl).toString()
23323
+ : sp.basename(fileName);
22791
23324
  return sourcemap === 'hidden' ? '' : `//# ${SOURCEMAPPING_URL}=${url}\n`;
22792
23325
  }
22793
23326
  function calculateDebugIdAndGetComment(code, map) {
@@ -22837,7 +23370,12 @@ class Bundle {
22837
23370
  await renderChunks(chunks, outputBundle, this.pluginDriver, this.outputOptions, this.inputOptions.onLog);
22838
23371
  }
22839
23372
  catch (error_) {
22840
- await this.pluginDriver.hookParallel('renderError', [error_]);
23373
+ try {
23374
+ await this.pluginDriver.hookParallel('renderError', [error_]);
23375
+ }
23376
+ catch (hookError) {
23377
+ parseAst_js.error(parseAst_js.logErrorInHook(error_, hookError, 'renderError'));
23378
+ }
22841
23379
  throw error_;
22842
23380
  }
22843
23381
  removeUnreferencedAssets(outputBundle);
@@ -23207,7 +23745,7 @@ async function transform(source, module, pluginDriver, options) {
23207
23745
  }
23208
23746
  const getLogHandler = (handler) => (log, pos) => {
23209
23747
  log = normalizeLog(log);
23210
- if (pos)
23748
+ if (pos != null)
23211
23749
  parseAst_js.augmentCodeLocation(log, pos, currentSource, id);
23212
23750
  log.id = id;
23213
23751
  log.hook = 'transform';
@@ -23241,7 +23779,7 @@ async function transform(source, module, pluginDriver, options) {
23241
23779
  error(error_, pos) {
23242
23780
  if (typeof error_ === 'string')
23243
23781
  error_ = { message: error_ };
23244
- if (pos)
23782
+ if (pos != null)
23245
23783
  parseAst_js.augmentCodeLocation(error_, pos, currentSource, id);
23246
23784
  error_.id = id;
23247
23785
  error_.hook = 'transform';
@@ -23393,37 +23931,7 @@ class ModuleLoader {
23393
23931
  }));
23394
23932
  }
23395
23933
  async addModuleSource(id, importer, module) {
23396
- let source;
23397
- try {
23398
- source = await this.graph.fileOperationQueue.run(async () => {
23399
- const content = await this.pluginDriver.hookFirst('load', [
23400
- id,
23401
- { attributes: module.info.attributes, rawId: module.info.rawId }
23402
- ]);
23403
- if (content !== null) {
23404
- if (typeof content === 'object' && content.attributes) {
23405
- parseAst_js.warnDeprecation('Returning attributes from the "load" hook is deprecated.', parseAst_js.URL_LOAD, true, this.options);
23406
- }
23407
- return content;
23408
- }
23409
- this.graph.watchFiles[module.info.rawId] = true;
23410
- return (await this.options.fs.readFile(module.info.rawId, { encoding: 'utf8' }));
23411
- });
23412
- }
23413
- catch (error_) {
23414
- let message = `Could not load ${id}`;
23415
- if (importer)
23416
- message += ` (imported by ${parseAst_js.relativeId(importer)})`;
23417
- message += `: ${error_.message}`;
23418
- error_.message = message;
23419
- throw error_;
23420
- }
23421
- const sourceDescription = typeof source === 'string'
23422
- ? { code: source }
23423
- : source != null && typeof source === 'object' && typeof source.code === 'string'
23424
- ? source
23425
- : parseAst_js.error(parseAst_js.logBadLoader(id));
23426
- sourceDescription.code = stripBom(sourceDescription.code);
23934
+ const sourceDescription = await this.loadSourceDescription(id, importer, module);
23427
23935
  const cachedModule = this.graph.cachedModules.get(id);
23428
23936
  if (cachedModule &&
23429
23937
  !cachedModule.customTransformCache &&
@@ -23736,6 +24244,37 @@ class ModuleLoader {
23736
24244
  ? resolveIdResult
23737
24245
  : { id: resolveIdResult }, attributes)), undefined, isEntry, false);
23738
24246
  }
24247
+ async loadSourceDescription(id, importer, module) {
24248
+ let source;
24249
+ try {
24250
+ source = await this.pluginDriver.hookFirst('load', [
24251
+ id,
24252
+ { attributes: module.info.attributes, rawId: module.info.rawId }
24253
+ ]);
24254
+ if (source === null) {
24255
+ this.graph.watchFiles[module.info.rawId] = true;
24256
+ source = await this.options.fs.readFile(module.info.rawId, { encoding: 'utf8' });
24257
+ }
24258
+ else if (typeof source === 'object' && source.attributes) {
24259
+ parseAst_js.warnDeprecation('Returning attributes from the "load" hook is deprecated.', parseAst_js.URL_LOAD, true, this.options);
24260
+ }
24261
+ }
24262
+ catch (error_) {
24263
+ let message = `Could not load ${id}`;
24264
+ if (importer)
24265
+ message += ` (imported by ${parseAst_js.relativeId(importer)})`;
24266
+ message += `: ${error_.message}`;
24267
+ error_.message = message;
24268
+ throw error_;
24269
+ }
24270
+ const sourceDescription = typeof source === 'string'
24271
+ ? { code: source }
24272
+ : source != null && typeof source === 'object' && typeof source.code === 'string'
24273
+ ? source
24274
+ : parseAst_js.error(parseAst_js.logBadLoader(id));
24275
+ sourceDescription.code = stripBom(sourceDescription.code);
24276
+ return sourceDescription;
24277
+ }
23739
24278
  toModuleResolvedId(resolveIdResult) {
23740
24279
  const { id, attributes } = resolveIdResult;
23741
24280
  return {
@@ -23798,37 +24337,6 @@ async function waitForDependencyResolution(loadPromise) {
23798
24337
  return Promise.all([...resolveStaticDependencyPromises, ...resolveDynamicImportPromises]);
23799
24338
  }
23800
24339
 
23801
- class Queue {
23802
- constructor(maxParallel) {
23803
- this.maxParallel = maxParallel;
23804
- this.queue = [];
23805
- this.workerCount = 0;
23806
- }
23807
- run(task) {
23808
- return new Promise((resolve, reject) => {
23809
- this.queue.push({ reject, resolve, task });
23810
- this.work();
23811
- });
23812
- }
23813
- async work() {
23814
- if (this.workerCount >= this.maxParallel)
23815
- return;
23816
- this.workerCount++;
23817
- let entry;
23818
- while ((entry = this.queue.shift())) {
23819
- const { reject, resolve, task } = entry;
23820
- try {
23821
- const result = await task();
23822
- resolve(result);
23823
- }
23824
- catch (error) {
23825
- reject(error);
23826
- }
23827
- }
23828
- this.workerCount--;
23829
- }
23830
- }
23831
-
23832
24340
  function normalizeEntryModules(entryModules) {
23833
24341
  if (Array.isArray(entryModules)) {
23834
24342
  return entryModules.map(id => ({
@@ -23892,7 +24400,6 @@ class Graph {
23892
24400
  }
23893
24401
  this.pluginDriver = new PluginDriver(this, options, options.plugins, this.pluginCache);
23894
24402
  this.moduleLoader = new ModuleLoader(this, this.modulesById, this.options, this.pluginDriver);
23895
- this.fileOperationQueue = new Queue(options.maxParallelFileOps);
23896
24403
  this.pureFunctions = getPureFunctions(options);
23897
24404
  }
23898
24405
  async build() {
@@ -24075,6 +24582,55 @@ async function catchUnfinishedHookActions(pluginDriver, callback) {
24075
24582
 
24076
24583
  async function initWasm() { }
24077
24584
 
24585
+ class FileOperationQueue {
24586
+ constructor(maxParallel) {
24587
+ this.maxParallel = maxParallel;
24588
+ this.queue = [];
24589
+ this.workerCount = 0;
24590
+ }
24591
+ run(task) {
24592
+ return new Promise((resolve, reject) => {
24593
+ this.queue.push({ reject, resolve, task });
24594
+ this.work();
24595
+ });
24596
+ }
24597
+ async work() {
24598
+ if (this.workerCount >= this.maxParallel)
24599
+ return;
24600
+ this.workerCount++;
24601
+ let entry;
24602
+ while ((entry = this.queue.shift())) {
24603
+ const { reject, resolve, task } = entry;
24604
+ try {
24605
+ resolve(await task());
24606
+ }
24607
+ catch (error) {
24608
+ reject(error);
24609
+ }
24610
+ }
24611
+ this.workerCount--;
24612
+ }
24613
+ }
24614
+ function createLimitedFs(fs, maxParallelFileOps) {
24615
+ const queue = new FileOperationQueue(maxParallelFileOps);
24616
+ const limit = (method) => ((...parameters) => queue.run(() => Reflect.apply(fs[method], fs, parameters)));
24617
+ return {
24618
+ appendFile: limit('appendFile'),
24619
+ copyFile: limit('copyFile'),
24620
+ lstat: limit('lstat'),
24621
+ mkdir: limit('mkdir'),
24622
+ mkdtemp: limit('mkdtemp'),
24623
+ readdir: limit('readdir'),
24624
+ readFile: limit('readFile'),
24625
+ realpath: limit('realpath'),
24626
+ rename: limit('rename'),
24627
+ rmdir: limit('rmdir'),
24628
+ stat: limit('stat'),
24629
+ unlink: limit('unlink'),
24630
+ writeFile: limit('writeFile')
24631
+ };
24632
+ }
24633
+
24078
24634
  const fs = /*#__PURE__*/_mergeNamespaces({
24079
24635
  __proto__: null
24080
24636
  }, [promises__namespace]);
@@ -24095,7 +24651,7 @@ async function normalizeInputOptions(config, watchMode) {
24095
24651
  experimentalCacheExpiry: config.experimentalCacheExpiry ?? 10,
24096
24652
  experimentalLogSideEffects: config.experimentalLogSideEffects || false,
24097
24653
  external: getIdMatcher(config.external),
24098
- fs: config.fs ?? fs,
24654
+ fs: createLimitedFs(config.fs ?? fs, maxParallelFileOps),
24099
24655
  input: getInput(config),
24100
24656
  jsx: getJsx(config),
24101
24657
  logLevel,
@@ -24135,7 +24691,8 @@ const getIdMatcher = (option) => {
24135
24691
  ids.add(value);
24136
24692
  }
24137
24693
  }
24138
- return (id, ..._arguments) => ids.has(id) || matchers.some(matcher => matcher.test(id));
24694
+ return (id, ..._arguments) => ids.has(id) ||
24695
+ matchers.some(matcher => matcher.global || matcher.sticky ? id.search(matcher) !== -1 : matcher.test(id));
24139
24696
  }
24140
24697
  return () => false;
24141
24698
  };
@@ -24266,7 +24823,6 @@ async function normalizeOutputOptions(config, inputOptions, unsetInputOptions) {
24266
24823
  const preserveModules = getPreserveModules(config, inlineDynamicImports, inputOptions);
24267
24824
  const file = getFile(config, preserveModules, inputOptions);
24268
24825
  const generatedCode = getGeneratedCode(config);
24269
- const externalImportAttributes = getExternalImportAttributes(config, inputOptions);
24270
24826
  const outputOptions = {
24271
24827
  amd: getAmd(config),
24272
24828
  assetFileNames: config.assetFileNames ?? 'assets/[name]-[hash][extname]',
@@ -24280,8 +24836,7 @@ async function normalizeOutputOptions(config, inputOptions, unsetInputOptions) {
24280
24836
  experimentalMinChunkSize: config.experimentalMinChunkSize ?? 1,
24281
24837
  exports: getExports(config, unsetOptions),
24282
24838
  extend: config.extend || false,
24283
- externalImportAssertions: externalImportAttributes,
24284
- externalImportAttributes,
24839
+ externalImportAttributes: config.externalImportAttributes ?? true,
24285
24840
  externalLiveBindings: config.externalLiveBindings ?? true,
24286
24841
  file,
24287
24842
  footer: getAddon(config, 'footer'),
@@ -24456,12 +25011,6 @@ function getExports(config, unsetOptions) {
24456
25011
  }
24457
25012
  return configExports || 'auto';
24458
25013
  }
24459
- const getExternalImportAttributes = (config, inputOptions) => {
24460
- if (config.externalImportAssertions != undefined) {
24461
- parseAst_js.warnDeprecation(`The "output.externalImportAssertions" option is deprecated. Use the "output.externalImportAttributes" option instead.`, parseAst_js.URL_OUTPUT_EXTERNALIMPORTATTRIBUTES, true, inputOptions);
24462
- }
24463
- return config.externalImportAttributes ?? config.externalImportAssertions ?? true;
24464
- };
24465
25014
  const getGeneratedCode = (config) => {
24466
25015
  const configWithPreset = getOptionWithPreset(config.generatedCode, generatedCodePresets, 'output.generatedCode', parseAst_js.URL_OUTPUT_GENERATEDCODE, '');
24467
25016
  return {
@@ -24575,22 +25124,18 @@ async function rollupInternal(rawInputOptions, registerWatchHooks) {
24575
25124
  await graph.pluginDriver.hookParallel('buildEnd', [error_]);
24576
25125
  }
24577
25126
  catch (buildEndError) {
24578
- // Create a compound error object to include both errors, based on the original error
24579
- const compoundError = parseAst_js.getRollupError({
24580
- ...error_,
24581
- message: `There was an error during the build:\n ${error_.message}\nAdditionally, handling the error in the 'buildEnd' hook caused the following error:\n ${buildEndError.message}`
24582
- });
24583
- await graph.pluginDriver.hookParallel('closeBundle', [compoundError]);
25127
+ const compoundError = parseAst_js.getRollupError(parseAst_js.logErrorInHook(error_, buildEndError, 'buildEnd'));
25128
+ await graph.pluginDriver.hookParallel('closeBundle', [compoundError]).catch(() => { });
24584
25129
  throw compoundError;
24585
25130
  }
24586
- await graph.pluginDriver.hookParallel('closeBundle', [error_]);
25131
+ await graph.pluginDriver.hookParallel('closeBundle', [error_]).catch(() => { });
24587
25132
  throw error_;
24588
25133
  }
24589
25134
  try {
24590
25135
  await graph.pluginDriver.hookParallel('buildEnd', []);
24591
25136
  }
24592
25137
  catch (buildEndError) {
24593
- await graph.pluginDriver.hookParallel('closeBundle', [buildEndError]);
25138
+ await graph.pluginDriver.hookParallel('closeBundle', [buildEndError]).catch(() => { });
24594
25139
  throw buildEndError;
24595
25140
  }
24596
25141
  });
@@ -24673,7 +25218,7 @@ async function handleGenerateWrite(isWrite, inputOptions, unsetInputOptions, raw
24673
25218
  if (!outputOptions.dir && !outputOptions.file) {
24674
25219
  return parseAst_js.error(parseAst_js.logMissingFileOrDirOption());
24675
25220
  }
24676
- await Promise.all(Object.values(generated).map(chunk => graph.fileOperationQueue.run(() => writeOutputFile(chunk, outputOptions, inputOptions))));
25221
+ await Promise.all(Object.values(generated).map(chunk => writeOutputFile(chunk, outputOptions, inputOptions)));
24677
25222
  await outputPluginDriver.hookParallel('writeBundle', [outputOptions, generated]);
24678
25223
  timeEnd('WRITE', 1);
24679
25224
  }