@rollup/wasm-node 5.0.0-1 → 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 +716 -375
  7. package/dist/es/shared/parseAst.js +12 -4
  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/parseAst.js +2 -2
  12. package/dist/rollup.android-arm-eabi.node +0 -0
  13. package/dist/rollup.android-arm64.node +0 -0
  14. package/dist/rollup.android-x64.node +0 -0
  15. package/dist/rollup.d.ts +23 -9
  16. package/dist/rollup.darwin-arm64.node +0 -0
  17. package/dist/rollup.darwin-x64.node +0 -0
  18. package/dist/rollup.freebsd-arm64.node +0 -0
  19. package/dist/rollup.freebsd-x64.node +0 -0
  20. package/dist/rollup.js +2 -2
  21. package/dist/rollup.linux-arm-gnueabihf.node +0 -0
  22. package/dist/rollup.linux-arm-musleabihf.node +0 -0
  23. package/dist/rollup.linux-arm64-gnu.node +0 -0
  24. package/dist/rollup.linux-arm64-musl.node +0 -0
  25. package/dist/rollup.linux-loong64-gnu.node +0 -0
  26. package/dist/rollup.linux-loong64-musl.node +0 -0
  27. package/dist/rollup.linux-ppc64-gnu.node +0 -0
  28. package/dist/rollup.linux-ppc64-musl.node +0 -0
  29. package/dist/rollup.linux-riscv64-gnu.node +0 -0
  30. package/dist/rollup.linux-riscv64-musl.node +0 -0
  31. package/dist/rollup.linux-s390x-gnu.node +0 -0
  32. package/dist/rollup.linux-x64-gnu.node +0 -0
  33. package/dist/rollup.linux-x64-musl.node +0 -0
  34. package/dist/rollup.openbsd-x64.node +0 -0
  35. package/dist/rollup.openharmony-arm64.node +0 -0
  36. package/dist/rollup.win32-arm64-msvc.node +0 -0
  37. package/dist/rollup.win32-ia32-msvc.node +0 -0
  38. package/dist/rollup.win32-x64-gnu.node +0 -0
  39. package/dist/rollup.win32-x64-msvc.node +0 -0
  40. package/dist/shared/index.js +3198 -1002
  41. package/dist/shared/loadConfigFile.js +2 -2
  42. package/dist/shared/node-entry.js +2 -2
  43. package/dist/shared/parseAst.js +12 -4
  44. package/dist/shared/rollup.js +714 -373
  45. package/dist/shared/watch-cli.js +2 -2
  46. package/dist/shared/watch.js +2 -2
  47. package/dist/wasm-node/bindings_wasm_bg.wasm +0 -0
  48. package/package.json +17 -17
@@ -1,7 +1,7 @@
1
1
  /*
2
2
  @license
3
- Rollup.js v5.0.0-1
4
- Sun, 18 Oct 2026 06:06:25 GMT - commit ed75a6895d5bc62fdbff91b9d48e22e6e281e3bc
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-1";
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, !overwrite);
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,30 +5889,29 @@ 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
5916
  if (match[0].length === 0) this.appendRight(match.index - this.offset, replacement);
5832
5917
  else this.overwrite(match.index - this.offset, match.index + match[0].length - this.offset, replacement);
@@ -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
@@ -7245,6 +7369,15 @@ class LocalVariable extends Variable {
7245
7369
  this.init.deoptimizePath(limitConcatenatedPathDepth(this.initPath, path));
7246
7370
  }
7247
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
+ }
7248
7381
  getLiteralValueAtPath(path, recursionTracker, origin) {
7249
7382
  if (this.isReassigned || path.length + this.initPath.length > MAX_PATH_DEPTH) {
7250
7383
  return UnknownValue;
@@ -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
  }
@@ -9861,6 +10012,9 @@ class IdentifierBase extends NodeBase {
9861
10012
  // Identifier as property that might be deoptimized by default
9862
10013
  this.variable?.deoptimizePath(path);
9863
10014
  }
10015
+ getKnownFunctionAtPath(path, recursionTracker, origin) {
10016
+ return this.getVariableRespectingTDZ().getKnownFunctionAtPath(path, recursionTracker, origin);
10017
+ }
9864
10018
  getLiteralValueAtPath(path, recursionTracker, origin) {
9865
10019
  return this.getVariableRespectingTDZ().getLiteralValueAtPath(path, recursionTracker, origin);
9866
10020
  }
@@ -10172,6 +10326,11 @@ class PropertyBase extends NodeBase {
10172
10326
  deoptimizePath(path) {
10173
10327
  this.getAccessedValue()[0].deoptimizePath(path);
10174
10328
  }
10329
+ getKnownFunctionAtPath(path, recursionTracker, origin) {
10330
+ return this.kind === 'get' || this.kind === 'set'
10331
+ ? null
10332
+ : this.value.getKnownFunctionAtPath(path, recursionTracker, origin);
10333
+ }
10175
10334
  getLiteralValueAtPath(path, recursionTracker, origin) {
10176
10335
  return this.getAccessedValue()[0].getLiteralValueAtPath(path, recursionTracker, origin);
10177
10336
  }
@@ -10685,6 +10844,8 @@ class ParameterVariable extends LocalVariable {
10685
10844
  class ThisVariable extends ParameterVariable {
10686
10845
  constructor(context) {
10687
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();
10688
10849
  }
10689
10850
  hasEffectsOnInteractionAtPath(path, interaction, context) {
10690
10851
  return (context.replacedVariableInits.get(this) || UNKNOWN_EXPRESSION).hasEffectsOnInteractionAtPath(path, interaction, context);
@@ -10989,8 +11150,11 @@ class FunctionScope extends ReturnValueScope {
10989
11150
  }
10990
11151
  includeCallArguments(interaction, context) {
10991
11152
  super.includeCallArguments(interaction, context);
11153
+ const { args } = interaction;
11154
+ if (args[0]) {
11155
+ this.thisVariable.includeArgumentPaths(args[0], context);
11156
+ }
10992
11157
  if (this.argumentsVariable.included) {
10993
- const { args } = interaction;
10994
11158
  for (let argumentIndex = 1; argumentIndex < args.length; argumentIndex++) {
10995
11159
  const argument = args[argumentIndex];
10996
11160
  if (argument) {
@@ -11175,6 +11339,11 @@ class FunctionBase extends NodeBase {
11175
11339
  this.scope.deoptimizeAllParameters();
11176
11340
  }
11177
11341
  }
11342
+ getKnownFunctionAtPath(path, recursionTracker, origin) {
11343
+ return path.length === 0
11344
+ ? this
11345
+ : this.getObjectEntity().getKnownFunctionAtPath(path, recursionTracker, origin);
11346
+ }
11178
11347
  getLiteralValueAtPath(path, recursionTracker, origin) {
11179
11348
  return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
11180
11349
  }
@@ -11182,7 +11351,7 @@ class FunctionBase extends NodeBase {
11182
11351
  if (path.length > 0) {
11183
11352
  return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
11184
11353
  }
11185
- if (this.async) {
11354
+ if (this.async || this.generator) {
11186
11355
  if (!this.deoptimizedReturn) {
11187
11356
  this.deoptimizedReturn = true;
11188
11357
  this.scope.getReturnExpression().deoptimizePath(UNKNOWN_PATH);
@@ -11367,10 +11536,15 @@ class FunctionNode extends FunctionBase {
11367
11536
  {
11368
11537
  key: 'prototype',
11369
11538
  kind: 'init',
11370
- property: new ObjectEntity([], OBJECT_PROTOTYPE)
11539
+ property: new ObjectEntity([], this.getPrototypeOfPrototype())
11371
11540
  }
11372
11541
  ], OBJECT_PROTOTYPE));
11373
11542
  }
11543
+ getPrototypeOfPrototype() {
11544
+ if (!this.generator)
11545
+ return OBJECT_PROTOTYPE;
11546
+ return this.async ? ASYNC_GENERATOR_PROTOTYPE : GENERATOR_PROTOTYPE;
11547
+ }
11374
11548
  }
11375
11549
 
11376
11550
  class FunctionDeclaration extends FunctionNode {
@@ -11502,12 +11676,19 @@ ExportDefaultDeclaration.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
11502
11676
  ExportDefaultDeclaration.prototype.applyDeoptimizations = doNotDeoptimize;
11503
11677
 
11504
11678
  const needsEscapeRegEx = /[\n\r'\\\u2028\u2029]/;
11505
- const quoteNewlineRegEx = /([\n\r'\u2028\u2029])/g;
11506
- 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
+ };
11507
11688
  function escapeId(id) {
11508
11689
  if (!needsEscapeRegEx.test(id))
11509
11690
  return id;
11510
- return id.replace(backSlashRegEx, '\\\\').replace(quoteNewlineRegEx, '\\$1');
11691
+ return id.replace(escapeRegEx, character => escapeReplacements[character]);
11511
11692
  }
11512
11693
 
11513
11694
  const INTEROP_DEFAULT_VARIABLE = '_interopDefault';
@@ -11923,6 +12104,20 @@ class MemberExpression extends NodeBase {
11923
12104
  ]);
11924
12105
  }
11925
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
+ }
11926
12121
  getLiteralValueAtPath(path, recursionTracker, origin) {
11927
12122
  if (this.variable) {
11928
12123
  return this.variable.getLiteralValueAtPath(path, recursionTracker, origin);
@@ -13725,17 +13920,29 @@ function getMatcherString(id, resolutionBase) {
13725
13920
  }
13726
13921
  const createFilter = function createFilter(include, exclude, options) {
13727
13922
  const resolutionBase = options && options.resolve;
13728
- const getMatcher = (id) => id instanceof RegExp
13729
- ? id
13730
- : {
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 {
13731
13936
  test: (what) => {
13732
- // this refactor is a tad overly verbose but makes for easy debugging
13733
- const pattern = getMatcherString(id, resolutionBase);
13734
- const fn = pm(pattern, { dot: true });
13735
- const result = fn(what);
13736
- return result;
13937
+ const cwd = process.cwd();
13938
+ if (cwd !== compiledCwd) {
13939
+ compiledCwd = cwd;
13940
+ fn = compile();
13941
+ }
13942
+ return fn(what);
13737
13943
  }
13738
13944
  };
13945
+ };
13739
13946
  const includeMatchers = ensureArray(include).map(getMatcher);
13740
13947
  const excludeMatchers = ensureArray(exclude).map(getMatcher);
13741
13948
  if (!includeMatchers.length && !excludeMatchers.length)
@@ -15915,19 +16122,17 @@ class JSXAttribute extends NodeBase {
15915
16122
  }
15916
16123
  if (value) {
15917
16124
  code.overwrite(name.end, value.start, ': ', { contentOnly: true });
15918
- // foo="aa \n aa"
15919
- if (value instanceof Literal &&
15920
- typeof value.value === 'string' &&
15921
- value.value.includes('\n')) {
15922
- code.overwrite(value.start, value.end, JSON.stringify(value.value), {
15923
- contentOnly: true
15924
- });
15925
- }
15926
16125
  }
15927
16126
  else {
15928
16127
  code.appendLeft(name.end, ': true');
15929
16128
  }
15930
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
+ }
15931
16136
  }
15932
16137
  }
15933
16138
  }
@@ -16712,6 +16917,9 @@ class ObjectExpression extends NodeBase {
16712
16917
  deoptimizePath(path) {
16713
16918
  this.getObjectEntity().deoptimizePath(path);
16714
16919
  }
16920
+ getKnownFunctionAtPath(path, recursionTracker, origin) {
16921
+ return this.getObjectEntity().getKnownFunctionAtPath(path, recursionTracker, origin);
16922
+ }
16715
16923
  getLiteralValueAtPath(path, recursionTracker, origin) {
16716
16924
  return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
16717
16925
  }
@@ -17962,6 +18170,14 @@ class VariableDeclarator extends NodeBase {
17962
18170
  deoptimizePath(path) {
17963
18171
  this.id.deoptimizePath(path);
17964
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
+ }
17965
18181
  hasEffects(context) {
17966
18182
  const initEffect = this.init?.hasEffects(context);
17967
18183
  this.id.markDeclarationReached();
@@ -17977,6 +18193,11 @@ class VariableDeclarator extends NodeBase {
17977
18193
  const { id, init } = this;
17978
18194
  if (!this.included)
17979
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
+ }
17980
18201
  init?.include(context, includeChildrenRecursively);
17981
18202
  id.markDeclarationReached();
17982
18203
  if (includeChildrenRecursively) {
@@ -18018,11 +18239,16 @@ class VariableDeclarator extends NodeBase {
18018
18239
  this.included = true;
18019
18240
  const { id, init } = this;
18020
18241
  if (init) {
18021
- if (this.isUsingDeclaration) {
18022
- init.includePath(SYMBOL_DISPOSE_PATH, context);
18023
- }
18024
- else if (this.isAsyncUsingDeclaration) {
18025
- 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();
18026
18252
  }
18027
18253
  if (id instanceof Identifier && init instanceof ClassExpression && !init.id) {
18028
18254
  const { name, variable } = id;
@@ -18034,6 +18260,23 @@ class VariableDeclarator extends NodeBase {
18034
18260
  }
18035
18261
  }
18036
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
+ }
18037
18280
  }
18038
18281
  VariableDeclarator.prototype.applyDeoptimizations = doNotDeoptimize;
18039
18282
  const SYMBOL_DISPOSE_PATH = [SymbolDispose];
@@ -18827,6 +19070,9 @@ function decodedSourcemap(map) {
18827
19070
  if (typeof map === 'string') {
18828
19071
  map = JSON.parse(map);
18829
19072
  }
19073
+ if ('sections' in map) {
19074
+ map = flattenIndexSourceMap(map);
19075
+ }
18830
19076
  if (!map.mappings) {
18831
19077
  return {
18832
19078
  mappings: [],
@@ -18862,6 +19108,74 @@ function decodedSourcemap(map) {
18862
19108
  sourceMapCache.set(decodedMap, cache);
18863
19109
  return decodedMap;
18864
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
+ }
18865
19179
 
18866
19180
  function getId(m) {
18867
19181
  return m.id;
@@ -18878,7 +19192,7 @@ function getOriginalLocation(sourcemapChain, location) {
18878
19192
  let previousSegment = filteredLine[0];
18879
19193
  for (let segment of filteredLine) {
18880
19194
  if (segment[0] >= location.column || segment === lastSegment) {
18881
- const notMatched = segment[0] !== location.column;
19195
+ const notMatched = segment[0] > location.column;
18882
19196
  segment = notMatched ? previousSegment : segment;
18883
19197
  location = {
18884
19198
  column: segment[3],
@@ -20125,7 +20439,8 @@ function deconflictImportsEsmOrSystem(usedNames, imports, dependenciesToBeDeconf
20125
20439
  for (const variable of imports) {
20126
20440
  const module = variable.module;
20127
20441
  const name = variable.name;
20128
- if (variable.isNamespace && (preserveModules || module instanceof ExternalModule)) {
20442
+ if (variable.isNamespace &&
20443
+ (module instanceof ExternalModule || (preserveModules && !module.info.syntheticNamedExports))) {
20129
20444
  variable.setRenderNames(null, (module instanceof ExternalModule
20130
20445
  ? externalChunkByModule.get(module)
20131
20446
  : chunkByModule.get(module)).variableName);
@@ -20189,7 +20504,7 @@ function deconflictImportsOther(usedNames, imports, { deconflictedDefault, decon
20189
20504
  }
20190
20505
  else {
20191
20506
  const chunk = chunkByModule.get(module);
20192
- if (preserveModules && variable.isNamespace) {
20507
+ if (preserveModules && variable.isNamespace && !module.info.syntheticNamedExports) {
20193
20508
  variable.setRenderNames(null, chunk.exportMode === 'default' ? chunk.namespaceVariableName : chunk.variableName);
20194
20509
  }
20195
20510
  else if (chunk.exportMode === 'default') {
@@ -20449,7 +20764,8 @@ class Chunk {
20449
20764
  const chunkModules = new Set(orderedModules);
20450
20765
  for (const module of orderedModules) {
20451
20766
  chunkByModule.set(module, this);
20452
- if (module.namespace.included && !outputOptions.preserveModules) {
20767
+ if (module.namespace.included &&
20768
+ (!outputOptions.preserveModules || module.info.syntheticNamedExports)) {
20453
20769
  includedNamespaces.add(module);
20454
20770
  }
20455
20771
  if (this.isEmpty && module.isIncluded()) {
@@ -20753,11 +21069,16 @@ class Chunk {
20753
21069
  });
20754
21070
  }
20755
21071
  getVariableExportName(variable) {
20756
- if (this.outputOptions.preserveModules && variable instanceof NamespaceVariable) {
21072
+ if (this.isNativeNamespace(variable)) {
20757
21073
  return '*';
20758
21074
  }
20759
21075
  return this.exportNamesByVariable.get(variable)[0];
20760
21076
  }
21077
+ isNativeNamespace(variable) {
21078
+ return (this.outputOptions.preserveModules &&
21079
+ variable instanceof NamespaceVariable &&
21080
+ !variable.module.info.syntheticNamedExports);
21081
+ }
20761
21082
  link() {
20762
21083
  this.dependencies = getStaticDependencies(this, this.orderedModules, this.chunkByModule, this.externalChunkByModule);
20763
21084
  for (const module of this.orderedModules) {
@@ -20900,8 +21221,9 @@ class Chunk {
20900
21221
  const importedVariable = isSynthetic ? exportedVariable.getBaseVariable() : exportedVariable;
20901
21222
  this.checkCircularDependencyImport(importedVariable, module);
20902
21223
  // When preserving modules, we do not create namespace objects but directly
20903
- // use the actual namespaces, which would be broken by this logic.
20904
- 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)) {
20905
21227
  const exportingModule = importedVariable.module;
20906
21228
  if (exportingModule instanceof Module) {
20907
21229
  const chunk = this.chunkByModule.get(exportingModule);
@@ -21473,9 +21795,8 @@ class Chunk {
21473
21795
  }
21474
21796
  setUpChunkImportsAndExportsForModule(module) {
21475
21797
  const moduleImports = new Set(module.includedImports);
21476
- // when we are not preserving modules, we need to make all namespace variables available for
21477
- // rendering the namespace object
21478
- 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)) {
21479
21800
  for (const variable of module.getExportedVariablesByName().values()) {
21480
21801
  if (variable.included) {
21481
21802
  moduleImports.add(variable);
@@ -21495,8 +21816,9 @@ class Chunk {
21495
21816
  if (variable.module instanceof Module) {
21496
21817
  this.checkCircularDependencyImport(variable, module);
21497
21818
  // When preserving modules, we do not create namespace objects but directly
21498
- // use the actual namespaces, which would be broken by this logic.
21499
- 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)) {
21500
21822
  chunk.exports.add(variable);
21501
21823
  }
21502
21824
  }
@@ -22692,7 +23014,10 @@ function getCollapsedSourcemap(id, originalCode, originalSourcemap, sourcemapCha
22692
23014
  const sourcesContent = originalSourcemap.sourcesContent || [];
22693
23015
  const directory = sp.dirname(id) || '.';
22694
23016
  const sourceRoot = originalSourcemap.sourceRoot || '.';
22695
- 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]));
22696
23021
  source = new Link(originalSourcemap, baseSources);
22697
23022
  }
22698
23023
  else {
@@ -22725,13 +23050,17 @@ function collapseSourcemaps(file, map, modules, bundleSourcemapChain, excludeCon
22725
23050
  });
22726
23051
  }
22727
23052
  function collapseSourcemap(id, originalCode, originalSourcemap, sourcemapChain, log) {
22728
- if (sourcemapChain.length === 0) {
23053
+ if (sourcemapChain.length === 0 &&
23054
+ (!originalSourcemap || hasOnlyNamedSources(originalSourcemap))) {
22729
23055
  return originalSourcemap;
22730
23056
  }
22731
23057
  const source = getCollapsedSourcemap(id, originalCode, originalSourcemap, sourcemapChain, getLinkMap(log));
22732
23058
  const map = source.traceMappings();
22733
23059
  return decodedSourcemap({ version: 3, ...map });
22734
23060
  }
23061
+ function hasOnlyNamedSources(map) {
23062
+ return map.sources.every(source => source != null);
23063
+ }
22735
23064
 
22736
23065
  // this looks ridiculous, but it prevents sourcemap tooling from mistaking
22737
23066
  // this for an actual sourceMappingURL
@@ -23041,7 +23370,12 @@ class Bundle {
23041
23370
  await renderChunks(chunks, outputBundle, this.pluginDriver, this.outputOptions, this.inputOptions.onLog);
23042
23371
  }
23043
23372
  catch (error_) {
23044
- 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
+ }
23045
23379
  throw error_;
23046
23380
  }
23047
23381
  removeUnreferencedAssets(outputBundle);
@@ -23411,7 +23745,7 @@ async function transform(source, module, pluginDriver, options) {
23411
23745
  }
23412
23746
  const getLogHandler = (handler) => (log, pos) => {
23413
23747
  log = normalizeLog(log);
23414
- if (pos)
23748
+ if (pos != null)
23415
23749
  parseAst_js.augmentCodeLocation(log, pos, currentSource, id);
23416
23750
  log.id = id;
23417
23751
  log.hook = 'transform';
@@ -23445,7 +23779,7 @@ async function transform(source, module, pluginDriver, options) {
23445
23779
  error(error_, pos) {
23446
23780
  if (typeof error_ === 'string')
23447
23781
  error_ = { message: error_ };
23448
- if (pos)
23782
+ if (pos != null)
23449
23783
  parseAst_js.augmentCodeLocation(error_, pos, currentSource, id);
23450
23784
  error_.id = id;
23451
23785
  error_.hook = 'transform';
@@ -23597,37 +23931,7 @@ class ModuleLoader {
23597
23931
  }));
23598
23932
  }
23599
23933
  async addModuleSource(id, importer, module) {
23600
- let source;
23601
- try {
23602
- source = await this.graph.fileOperationQueue.run(async () => {
23603
- const content = await this.pluginDriver.hookFirst('load', [
23604
- id,
23605
- { attributes: module.info.attributes, rawId: module.info.rawId }
23606
- ]);
23607
- if (content !== null) {
23608
- if (typeof content === 'object' && content.attributes) {
23609
- parseAst_js.warnDeprecation('Returning attributes from the "load" hook is deprecated.', parseAst_js.URL_LOAD, true, this.options);
23610
- }
23611
- return content;
23612
- }
23613
- this.graph.watchFiles[module.info.rawId] = true;
23614
- return (await this.options.fs.readFile(module.info.rawId, { encoding: 'utf8' }));
23615
- });
23616
- }
23617
- catch (error_) {
23618
- let message = `Could not load ${id}`;
23619
- if (importer)
23620
- message += ` (imported by ${parseAst_js.relativeId(importer)})`;
23621
- message += `: ${error_.message}`;
23622
- error_.message = message;
23623
- throw error_;
23624
- }
23625
- const sourceDescription = typeof source === 'string'
23626
- ? { code: source }
23627
- : source != null && typeof source === 'object' && typeof source.code === 'string'
23628
- ? source
23629
- : parseAst_js.error(parseAst_js.logBadLoader(id));
23630
- sourceDescription.code = stripBom(sourceDescription.code);
23934
+ const sourceDescription = await this.loadSourceDescription(id, importer, module);
23631
23935
  const cachedModule = this.graph.cachedModules.get(id);
23632
23936
  if (cachedModule &&
23633
23937
  !cachedModule.customTransformCache &&
@@ -23940,6 +24244,37 @@ class ModuleLoader {
23940
24244
  ? resolveIdResult
23941
24245
  : { id: resolveIdResult }, attributes)), undefined, isEntry, false);
23942
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
+ }
23943
24278
  toModuleResolvedId(resolveIdResult) {
23944
24279
  const { id, attributes } = resolveIdResult;
23945
24280
  return {
@@ -24002,37 +24337,6 @@ async function waitForDependencyResolution(loadPromise) {
24002
24337
  return Promise.all([...resolveStaticDependencyPromises, ...resolveDynamicImportPromises]);
24003
24338
  }
24004
24339
 
24005
- class Queue {
24006
- constructor(maxParallel) {
24007
- this.maxParallel = maxParallel;
24008
- this.queue = [];
24009
- this.workerCount = 0;
24010
- }
24011
- run(task) {
24012
- return new Promise((resolve, reject) => {
24013
- this.queue.push({ reject, resolve, task });
24014
- this.work();
24015
- });
24016
- }
24017
- async work() {
24018
- if (this.workerCount >= this.maxParallel)
24019
- return;
24020
- this.workerCount++;
24021
- let entry;
24022
- while ((entry = this.queue.shift())) {
24023
- const { reject, resolve, task } = entry;
24024
- try {
24025
- const result = await task();
24026
- resolve(result);
24027
- }
24028
- catch (error) {
24029
- reject(error);
24030
- }
24031
- }
24032
- this.workerCount--;
24033
- }
24034
- }
24035
-
24036
24340
  function normalizeEntryModules(entryModules) {
24037
24341
  if (Array.isArray(entryModules)) {
24038
24342
  return entryModules.map(id => ({
@@ -24096,7 +24400,6 @@ class Graph {
24096
24400
  }
24097
24401
  this.pluginDriver = new PluginDriver(this, options, options.plugins, this.pluginCache);
24098
24402
  this.moduleLoader = new ModuleLoader(this, this.modulesById, this.options, this.pluginDriver);
24099
- this.fileOperationQueue = new Queue(options.maxParallelFileOps);
24100
24403
  this.pureFunctions = getPureFunctions(options);
24101
24404
  }
24102
24405
  async build() {
@@ -24279,6 +24582,55 @@ async function catchUnfinishedHookActions(pluginDriver, callback) {
24279
24582
 
24280
24583
  async function initWasm() { }
24281
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
+
24282
24634
  const fs = /*#__PURE__*/_mergeNamespaces({
24283
24635
  __proto__: null
24284
24636
  }, [promises__namespace]);
@@ -24299,7 +24651,7 @@ async function normalizeInputOptions(config, watchMode) {
24299
24651
  experimentalCacheExpiry: config.experimentalCacheExpiry ?? 10,
24300
24652
  experimentalLogSideEffects: config.experimentalLogSideEffects || false,
24301
24653
  external: getIdMatcher(config.external),
24302
- fs: config.fs ?? fs,
24654
+ fs: createLimitedFs(config.fs ?? fs, maxParallelFileOps),
24303
24655
  input: getInput(config),
24304
24656
  jsx: getJsx(config),
24305
24657
  logLevel,
@@ -24339,7 +24691,8 @@ const getIdMatcher = (option) => {
24339
24691
  ids.add(value);
24340
24692
  }
24341
24693
  }
24342
- 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));
24343
24696
  }
24344
24697
  return () => false;
24345
24698
  };
@@ -24470,7 +24823,6 @@ async function normalizeOutputOptions(config, inputOptions, unsetInputOptions) {
24470
24823
  const preserveModules = getPreserveModules(config, inlineDynamicImports, inputOptions);
24471
24824
  const file = getFile(config, preserveModules, inputOptions);
24472
24825
  const generatedCode = getGeneratedCode(config);
24473
- const externalImportAttributes = getExternalImportAttributes(config, inputOptions);
24474
24826
  const outputOptions = {
24475
24827
  amd: getAmd(config),
24476
24828
  assetFileNames: config.assetFileNames ?? 'assets/[name]-[hash][extname]',
@@ -24484,8 +24836,7 @@ async function normalizeOutputOptions(config, inputOptions, unsetInputOptions) {
24484
24836
  experimentalMinChunkSize: config.experimentalMinChunkSize ?? 1,
24485
24837
  exports: getExports(config, unsetOptions),
24486
24838
  extend: config.extend || false,
24487
- externalImportAssertions: externalImportAttributes,
24488
- externalImportAttributes,
24839
+ externalImportAttributes: config.externalImportAttributes ?? true,
24489
24840
  externalLiveBindings: config.externalLiveBindings ?? true,
24490
24841
  file,
24491
24842
  footer: getAddon(config, 'footer'),
@@ -24660,12 +25011,6 @@ function getExports(config, unsetOptions) {
24660
25011
  }
24661
25012
  return configExports || 'auto';
24662
25013
  }
24663
- const getExternalImportAttributes = (config, inputOptions) => {
24664
- if (config.externalImportAssertions != undefined) {
24665
- parseAst_js.warnDeprecation(`The "output.externalImportAssertions" option is deprecated. Use the "output.externalImportAttributes" option instead.`, parseAst_js.URL_OUTPUT_EXTERNALIMPORTATTRIBUTES, true, inputOptions);
24666
- }
24667
- return config.externalImportAttributes ?? config.externalImportAssertions ?? true;
24668
- };
24669
25014
  const getGeneratedCode = (config) => {
24670
25015
  const configWithPreset = getOptionWithPreset(config.generatedCode, generatedCodePresets, 'output.generatedCode', parseAst_js.URL_OUTPUT_GENERATEDCODE, '');
24671
25016
  return {
@@ -24779,11 +25124,7 @@ async function rollupInternal(rawInputOptions, registerWatchHooks) {
24779
25124
  await graph.pluginDriver.hookParallel('buildEnd', [error_]);
24780
25125
  }
24781
25126
  catch (buildEndError) {
24782
- // Create a compound error object to include both errors, based on the original error
24783
- const compoundError = parseAst_js.getRollupError({
24784
- ...error_,
24785
- 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}`
24786
- });
25127
+ const compoundError = parseAst_js.getRollupError(parseAst_js.logErrorInHook(error_, buildEndError, 'buildEnd'));
24787
25128
  await graph.pluginDriver.hookParallel('closeBundle', [compoundError]).catch(() => { });
24788
25129
  throw compoundError;
24789
25130
  }
@@ -24877,7 +25218,7 @@ async function handleGenerateWrite(isWrite, inputOptions, unsetInputOptions, raw
24877
25218
  if (!outputOptions.dir && !outputOptions.file) {
24878
25219
  return parseAst_js.error(parseAst_js.logMissingFileOrDirOption());
24879
25220
  }
24880
- 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)));
24881
25222
  await outputPluginDriver.hookParallel('writeBundle', [outputOptions, generated]);
24882
25223
  timeEnd('WRITE', 1);
24883
25224
  }