rollup 2.75.7 → 3.0.0-0

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.
@@ -1,7 +1,7 @@
1
1
  /*
2
2
  @license
3
- Rollup.js v2.75.7
4
- Mon, 20 Jun 2022 07:24:02 GMT - commit 057171c2d3bc2092b7f543fc05ead01f12595f12
3
+ Rollup.js v3.0.0-0
4
+ Tue, 05 Jul 2022 04:32:12 GMT - commit 7a8316af2262c390e7ed72586cb83add1286dec2
5
5
 
6
6
  https://github.com/rollup/rollup
7
7
 
@@ -27,7 +27,7 @@ function _interopNamespaceDefault(e) {
27
27
  return n;
28
28
  }
29
29
 
30
- var version$1 = "2.75.7";
30
+ var version$1 = "3.0.0-0";
31
31
 
32
32
  function ensureArray$1(items) {
33
33
  if (Array.isArray(items)) {
@@ -215,6 +215,7 @@ function augmentCodeLocation(props, pos, source, id) {
215
215
  }
216
216
  var Errors;
217
217
  (function (Errors) {
218
+ Errors["ADDON_ERROR"] = "ADDON_ERROR";
218
219
  Errors["ALREADY_CLOSED"] = "ALREADY_CLOSED";
219
220
  Errors["ASSET_NOT_FINALISED"] = "ASSET_NOT_FINALISED";
220
221
  Errors["ASSET_NOT_FOUND"] = "ASSET_NOT_FOUND";
@@ -237,6 +238,7 @@ var Errors;
237
238
  Errors["INVALID_OPTION"] = "INVALID_OPTION";
238
239
  Errors["INVALID_PLUGIN_HOOK"] = "INVALID_PLUGIN_HOOK";
239
240
  Errors["INVALID_ROLLUP_PHASE"] = "INVALID_ROLLUP_PHASE";
241
+ Errors["INVALID_TLA_FORMAT"] = "INVALID_TLA_FORMAT";
240
242
  Errors["MISSING_EXPORT"] = "MISSING_EXPORT";
241
243
  Errors["MISSING_IMPLICIT_DEPENDANT"] = "MISSING_IMPLICIT_DEPENDANT";
242
244
  Errors["MIXED_EXPORTS"] = "MIXED_EXPORTS";
@@ -251,10 +253,17 @@ var Errors;
251
253
  Errors["UNRESOLVED_IMPORT"] = "UNRESOLVED_IMPORT";
252
254
  Errors["VALIDATION_ERROR"] = "VALIDATION_ERROR";
253
255
  })(Errors || (Errors = {}));
256
+ function errAddonNotGenerated(message, hook, plugin) {
257
+ return {
258
+ code: Errors.ADDON_ERROR,
259
+ message: `Could not retrieve ${hook}. Check configuration of plugin ${plugin}.
260
+ \tError Message: ${message}`
261
+ };
262
+ }
254
263
  function errAssetNotFinalisedForFileName(name) {
255
264
  return {
256
265
  code: Errors.ASSET_NOT_FINALISED,
257
- message: `Plugin error - Unable to get file name for asset "${name}". Ensure that the source is set and that generate is called first.`
266
+ message: `Plugin error - Unable to get file name for asset "${name}". Ensure that the source is set and that generate is called first. If you reference assets via import.meta.ROLLUP_FILE_URL_<referenceId>, you need to either have set their source after "renderStart" or need to provide an explicit "fileName" when emitting them.`
258
267
  };
259
268
  }
260
269
  function errCannotEmitFromOptionsHook() {
@@ -266,7 +275,7 @@ function errCannotEmitFromOptionsHook() {
266
275
  function errChunkNotGeneratedForFileName(name) {
267
276
  return {
268
277
  code: Errors.CHUNK_NOT_GENERATED,
269
- message: `Plugin error - Unable to get file name for chunk "${name}". Ensure that generate is called first.`
278
+ message: `Plugin error - Unable to get file name for emitted chunk "${name}". You can only get file names once chunks have been generated after the "renderStart" hook.`
270
279
  };
271
280
  }
272
281
  function errChunkInvalid({ fileName, code }, exception) {
@@ -385,6 +394,13 @@ function errInvalidRollupPhaseForChunkEmission() {
385
394
  message: `Cannot emit chunks after module loading has finished.`
386
395
  };
387
396
  }
397
+ function errInvalidFormatForTopLevelAwait(id, format) {
398
+ return {
399
+ code: Errors.INVALID_TLA_FORMAT,
400
+ id,
401
+ message: `Module format ${format} does not support top-level await. Use the "es" or "system" output formats rather.`
402
+ };
403
+ }
388
404
  function errMissingExport(exportName, importingModule, importedModule) {
389
405
  return {
390
406
  code: Errors.MISSING_EXPORT,
@@ -645,33 +661,6 @@ const fseventsImporter = /*#__PURE__*/Object.defineProperty({
645
661
  getFsEvents
646
662
  }, Symbol.toStringTag, { value: 'Module' });
647
663
 
648
- var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
649
-
650
- function getDefaultExportFromCjs (x) {
651
- return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
652
- }
653
-
654
- function getAugmentedNamespace(n) {
655
- var f = n.default;
656
- if (typeof f == "function") {
657
- var a = function () {
658
- return f.apply(this, arguments);
659
- };
660
- a.prototype = f.prototype;
661
- } else a = {};
662
- Object.defineProperty(a, '__esModule', {value: true});
663
- Object.keys(n).forEach(function (k) {
664
- var d = Object.getOwnPropertyDescriptor(n, k);
665
- Object.defineProperty(a, k, d.get ? d : {
666
- enumerable: true,
667
- get: function () {
668
- return n[k];
669
- }
670
- });
671
- });
672
- return a;
673
- }
674
-
675
664
  var charToInteger = {};
676
665
  var chars$1 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
677
666
  for (var i$1 = 0; i$1 < chars$1.length; i$1++) {
@@ -2144,6 +2133,43 @@ class Bundle$1 {
2144
2133
  }
2145
2134
  }
2146
2135
 
2136
+ const needsEscapeRegEx = /[\\'\r\n\u2028\u2029]/;
2137
+ const quoteNewlineRegEx = /(['\r\n\u2028\u2029])/g;
2138
+ const backSlashRegEx = /\\/g;
2139
+ function escapeId(id) {
2140
+ if (!id.match(needsEscapeRegEx))
2141
+ return id;
2142
+ return id.replace(backSlashRegEx, '\\\\').replace(quoteNewlineRegEx, '\\$1');
2143
+ }
2144
+
2145
+ class ExternalChunk {
2146
+ constructor(module, options, inputBase) {
2147
+ this.options = options;
2148
+ this.inputBase = inputBase;
2149
+ this.defaultVariableName = '';
2150
+ this.namespaceVariableName = '';
2151
+ this.variableName = '';
2152
+ this.fileName = null;
2153
+ this.id = module.id;
2154
+ this.renormalizeRenderPath = module.renormalizeRenderPath;
2155
+ this.suggestedVariableName = module.suggestedVariableName;
2156
+ }
2157
+ getFileName() {
2158
+ if (this.fileName) {
2159
+ return this.fileName;
2160
+ }
2161
+ const { paths } = this.options;
2162
+ return (this.fileName =
2163
+ (typeof paths === 'function' ? paths(this.id) : paths[this.id]) ||
2164
+ (this.renormalizeRenderPath ? normalize(require$$0.relative(this.inputBase, this.id)) : this.id));
2165
+ }
2166
+ getImportPath(importer) {
2167
+ return escapeId(this.renormalizeRenderPath
2168
+ ? getImportPath(importer, this.getFileName(), this.options.format === 'amd', false)
2169
+ : this.getFileName());
2170
+ }
2171
+ }
2172
+
2147
2173
  function getOrCreate(map, key, init) {
2148
2174
  const existing = map.get(key);
2149
2175
  if (existing) {
@@ -2428,19 +2454,15 @@ class ExternalModule {
2428
2454
  this.options = options;
2429
2455
  this.id = id;
2430
2456
  this.renormalizeRenderPath = renormalizeRenderPath;
2431
- this.declarations = new Map();
2432
- this.defaultVariableName = '';
2433
2457
  this.dynamicImporters = [];
2434
2458
  this.execIndex = Infinity;
2435
2459
  this.exportedVariables = new Map();
2436
2460
  this.importers = [];
2437
- this.mostCommonSuggestion = 0;
2438
- this.nameSuggestions = new Map();
2439
- this.namespaceVariableName = '';
2440
2461
  this.reexported = false;
2441
- this.renderPath = undefined;
2442
2462
  this.used = false;
2443
- this.variableName = '';
2463
+ this.declarations = new Map();
2464
+ this.mostCommonSuggestion = 0;
2465
+ this.nameSuggestions = new Map();
2444
2466
  this.suggestedVariableName = makeLegal(id.split(/[\\/]/).pop());
2445
2467
  const { importers, dynamicImporters } = this;
2446
2468
  const info = (this.info = {
@@ -2453,7 +2475,7 @@ class ExternalModule {
2453
2475
  },
2454
2476
  hasDefaultExport: null,
2455
2477
  get hasModuleSideEffects() {
2456
- warnDeprecation('Accessing ModuleInfo.hasModuleSideEffects from plugins is deprecated. Please use ModuleInfo.moduleSideEffects instead.', false, options);
2478
+ warnDeprecation('Accessing ModuleInfo.hasModuleSideEffects from plugins is deprecated. Please use ModuleInfo.moduleSideEffects instead.', true, options);
2457
2479
  return info.moduleSideEffects;
2458
2480
  },
2459
2481
  id,
@@ -2485,15 +2507,6 @@ class ExternalModule {
2485
2507
  this.exportedVariables.set(externalVariable, name);
2486
2508
  return [externalVariable];
2487
2509
  }
2488
- setRenderPath(options, inputBase) {
2489
- this.renderPath =
2490
- typeof options.paths === 'function' ? options.paths(this.id) : options.paths[this.id];
2491
- if (!this.renderPath) {
2492
- this.renderPath = this.renormalizeRenderPath
2493
- ? normalize(require$$0.relative(inputBase, this.id))
2494
- : this.id;
2495
- }
2496
- }
2497
2510
  suggestName(name) {
2498
2511
  var _a;
2499
2512
  const value = ((_a = this.nameSuggestions.get(name)) !== null && _a !== void 0 ? _a : 0) + 1;
@@ -2526,6 +2539,33 @@ class ExternalModule {
2526
2539
  }
2527
2540
  }
2528
2541
 
2542
+ var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
2543
+
2544
+ function getDefaultExportFromCjs (x) {
2545
+ return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
2546
+ }
2547
+
2548
+ function getAugmentedNamespace(n) {
2549
+ var f = n.default;
2550
+ if (typeof f == "function") {
2551
+ var a = function () {
2552
+ return f.apply(this, arguments);
2553
+ };
2554
+ a.prototype = f.prototype;
2555
+ } else a = {};
2556
+ Object.defineProperty(a, '__esModule', {value: true});
2557
+ Object.keys(n).forEach(function (k) {
2558
+ var d = Object.getOwnPropertyDescriptor(n, k);
2559
+ Object.defineProperty(a, k, d.get ? d : {
2560
+ enumerable: true,
2561
+ get: function () {
2562
+ return n[k];
2563
+ }
2564
+ });
2565
+ });
2566
+ return a;
2567
+ }
2568
+
2529
2569
  var picomatch$1 = {exports: {}};
2530
2570
 
2531
2571
  var utils$3 = {};
@@ -10357,7 +10397,9 @@ class ImportExpression extends NodeBase {
10357
10397
  super(...arguments);
10358
10398
  this.inlineNamespace = null;
10359
10399
  this.mechanism = null;
10400
+ this.namespaceExportName = undefined;
10360
10401
  this.resolution = null;
10402
+ this.resolutionString = null;
10361
10403
  }
10362
10404
  hasEffects() {
10363
10405
  return true;
@@ -10374,8 +10416,8 @@ class ImportExpression extends NodeBase {
10374
10416
  this.context.addDynamicImport(this);
10375
10417
  }
10376
10418
  render(code, options) {
10419
+ const { snippets: { getDirectReturnFunction, getPropertyAccess } } = options;
10377
10420
  if (this.inlineNamespace) {
10378
- const { snippets: { getDirectReturnFunction, getPropertyAccess } } = options;
10379
10421
  const [left, right] = getDirectReturnFunction([], {
10380
10422
  functionReturn: true,
10381
10423
  lineBreakIndent: null,
@@ -10388,22 +10430,26 @@ class ImportExpression extends NodeBase {
10388
10430
  code.overwrite(this.start, findFirstOccurrenceOutsideComment(code.original, '(', this.start + 6) + 1, this.mechanism.left, { contentOnly: true });
10389
10431
  code.overwrite(this.end - 1, this.end, this.mechanism.right, { contentOnly: true });
10390
10432
  }
10391
- this.source.render(code, options);
10392
- }
10393
- renderFinalResolution(code, resolution, namespaceExportName, { getDirectReturnFunction }) {
10394
- code.overwrite(this.source.start, this.source.end, resolution);
10395
- if (namespaceExportName) {
10396
- const [left, right] = getDirectReturnFunction(['n'], {
10397
- functionReturn: true,
10398
- lineBreakIndent: null,
10399
- name: null
10400
- });
10401
- code.prependLeft(this.end, `.then(${left}n.${namespaceExportName}${right})`);
10433
+ if (this.resolutionString) {
10434
+ code.overwrite(this.source.start, this.source.end, this.resolutionString);
10435
+ if (this.namespaceExportName) {
10436
+ const [left, right] = getDirectReturnFunction(['n'], {
10437
+ functionReturn: true,
10438
+ lineBreakIndent: null,
10439
+ name: null
10440
+ });
10441
+ code.prependLeft(this.end, `.then(${left}n.${this.namespaceExportName}${right})`);
10442
+ }
10443
+ }
10444
+ else {
10445
+ this.source.render(code, options);
10402
10446
  }
10403
10447
  }
10404
- setExternalResolution(exportMode, resolution, options, snippets, pluginDriver, accessedGlobalsByScope) {
10448
+ setExternalResolution(exportMode, resolution, options, snippets, pluginDriver, accessedGlobalsByScope, resolutionString, namespaceExportName) {
10405
10449
  const { format } = options;
10406
10450
  this.resolution = resolution;
10451
+ this.resolutionString = resolutionString;
10452
+ this.namespaceExportName = namespaceExportName;
10407
10453
  const accessedGlobals = [...(accessedImportGlobals[format] || [])];
10408
10454
  let helper;
10409
10455
  ({ helper, mechanism: this.mechanism } = this.getDynamicImportMechanismAndHelper(resolution, exportMode, options, snippets, pluginDriver));
@@ -10698,25 +10744,17 @@ class LogicalExpression extends NodeBase {
10698
10744
  }
10699
10745
  }
10700
10746
 
10701
- const ASSET_PREFIX = 'ROLLUP_ASSET_URL_';
10702
- const CHUNK_PREFIX = 'ROLLUP_CHUNK_URL_';
10703
10747
  const FILE_PREFIX = 'ROLLUP_FILE_URL_';
10704
10748
  class MetaProperty extends NodeBase {
10705
- addAccessedGlobals(format, accessedGlobalsByScope) {
10706
- const metaProperty = this.metaProperty;
10707
- const accessedGlobals = (metaProperty &&
10708
- (metaProperty.startsWith(FILE_PREFIX) ||
10709
- metaProperty.startsWith(ASSET_PREFIX) ||
10710
- metaProperty.startsWith(CHUNK_PREFIX))
10711
- ? accessedFileUrlGlobals
10712
- : accessedMetaUrlGlobals)[format];
10713
- if (accessedGlobals.length > 0) {
10714
- this.scope.addAccessedGlobals(accessedGlobals, accessedGlobalsByScope);
10715
- }
10749
+ constructor() {
10750
+ super(...arguments);
10751
+ this.metaProperty = null;
10752
+ this.preliminaryChunkId = null;
10753
+ this.referenceId = null;
10716
10754
  }
10717
10755
  getReferencedFileName(outputPluginDriver) {
10718
- const metaProperty = this.metaProperty;
10719
- if (metaProperty && metaProperty.startsWith(FILE_PREFIX)) {
10756
+ const { metaProperty } = this;
10757
+ if (metaProperty === null || metaProperty === void 0 ? void 0 : metaProperty.startsWith(FILE_PREFIX)) {
10720
10758
  return outputPluginDriver.getFileName(metaProperty.substring(FILE_PREFIX.length));
10721
10759
  }
10722
10760
  return null;
@@ -10733,71 +10771,37 @@ class MetaProperty extends NodeBase {
10733
10771
  if (this.meta.name === 'import') {
10734
10772
  this.context.addImportMeta(this);
10735
10773
  const parent = this.parent;
10736
- this.metaProperty =
10774
+ const metaProperty = (this.metaProperty =
10737
10775
  parent instanceof MemberExpression && typeof parent.propertyKey === 'string'
10738
10776
  ? parent.propertyKey
10739
- : null;
10777
+ : null);
10778
+ if (metaProperty === null || metaProperty === void 0 ? void 0 : metaProperty.startsWith(FILE_PREFIX)) {
10779
+ this.referenceId = metaProperty.substring(FILE_PREFIX.length);
10780
+ }
10740
10781
  }
10741
10782
  }
10742
10783
  }
10743
- renderFinalMechanism(code, chunkId, format, snippets, outputPluginDriver) {
10784
+ render(code, { format, pluginDriver, snippets }) {
10744
10785
  var _a;
10745
- const parent = this.parent;
10746
- const metaProperty = this.metaProperty;
10747
- if (metaProperty &&
10748
- (metaProperty.startsWith(FILE_PREFIX) ||
10749
- metaProperty.startsWith(ASSET_PREFIX) ||
10750
- metaProperty.startsWith(CHUNK_PREFIX))) {
10751
- let referenceId = null;
10752
- let assetReferenceId = null;
10753
- let chunkReferenceId = null;
10754
- let fileName;
10755
- if (metaProperty.startsWith(FILE_PREFIX)) {
10756
- referenceId = metaProperty.substring(FILE_PREFIX.length);
10757
- fileName = outputPluginDriver.getFileName(referenceId);
10758
- }
10759
- else if (metaProperty.startsWith(ASSET_PREFIX)) {
10760
- warnDeprecation(`Using the "${ASSET_PREFIX}" prefix to reference files is deprecated. Use the "${FILE_PREFIX}" prefix instead.`, true, this.context.options);
10761
- assetReferenceId = metaProperty.substring(ASSET_PREFIX.length);
10762
- fileName = outputPluginDriver.getFileName(assetReferenceId);
10763
- }
10764
- else {
10765
- warnDeprecation(`Using the "${CHUNK_PREFIX}" prefix to reference files is deprecated. Use the "${FILE_PREFIX}" prefix instead.`, true, this.context.options);
10766
- chunkReferenceId = metaProperty.substring(CHUNK_PREFIX.length);
10767
- fileName = outputPluginDriver.getFileName(chunkReferenceId);
10768
- }
10786
+ const { metaProperty, parent, referenceId } = this;
10787
+ const chunkId = this.preliminaryChunkId;
10788
+ if (referenceId) {
10789
+ const fileName = pluginDriver.getFileName(referenceId);
10769
10790
  const relativePath = normalize(require$$0.relative(require$$0.dirname(chunkId), fileName));
10770
- let replacement;
10771
- if (assetReferenceId !== null) {
10772
- replacement = outputPluginDriver.hookFirstSync('resolveAssetUrl', [
10773
- {
10774
- assetFileName: fileName,
10775
- chunkId,
10776
- format,
10777
- moduleId: this.context.module.id,
10778
- relativeAssetPath: relativePath
10779
- }
10780
- ]);
10781
- }
10782
- if (!replacement) {
10783
- replacement =
10784
- outputPluginDriver.hookFirstSync('resolveFileUrl', [
10785
- {
10786
- assetReferenceId,
10787
- chunkId,
10788
- chunkReferenceId,
10789
- fileName,
10790
- format,
10791
- moduleId: this.context.module.id,
10792
- referenceId: referenceId || assetReferenceId || chunkReferenceId,
10793
- relativePath
10794
- }
10795
- ]) || relativeUrlMechanisms[format](relativePath);
10796
- }
10791
+ const replacement = pluginDriver.hookFirstSync('resolveFileUrl', [
10792
+ {
10793
+ chunkId,
10794
+ fileName,
10795
+ format,
10796
+ moduleId: this.context.module.id,
10797
+ referenceId,
10798
+ relativePath
10799
+ }
10800
+ ]) || relativeUrlMechanisms[format](relativePath);
10797
10801
  code.overwrite(parent.start, parent.end, replacement, { contentOnly: true });
10798
10802
  return;
10799
10803
  }
10800
- const replacement = outputPluginDriver.hookFirstSync('resolveImportMeta', [
10804
+ const replacement = pluginDriver.hookFirstSync('resolveImportMeta', [
10801
10805
  metaProperty,
10802
10806
  {
10803
10807
  chunkId,
@@ -10814,6 +10818,14 @@ class MetaProperty extends NodeBase {
10814
10818
  }
10815
10819
  }
10816
10820
  }
10821
+ setResolution(format, accessedGlobalsByScope, preliminaryChunkId) {
10822
+ var _a;
10823
+ this.preliminaryChunkId = preliminaryChunkId;
10824
+ const accessedGlobals = (((_a = this.metaProperty) === null || _a === void 0 ? void 0 : _a.startsWith(FILE_PREFIX)) ? accessedFileUrlGlobals : accessedMetaUrlGlobals)[format];
10825
+ if (accessedGlobals.length > 0) {
10826
+ this.scope.addAccessedGlobals(accessedGlobals, accessedGlobalsByScope);
10827
+ }
10828
+ }
10817
10829
  }
10818
10830
  const accessedMetaUrlGlobals = {
10819
10831
  amd: ['document', 'module', 'URL'],
@@ -12459,7 +12471,6 @@ class Module {
12459
12471
  this.needsExportShim = false;
12460
12472
  this.sideEffectDependenciesByVariable = new Map();
12461
12473
  this.sources = new Set();
12462
- this.usesTopLevelAwait = false;
12463
12474
  this.allExportNames = null;
12464
12475
  this.ast = null;
12465
12476
  this.exportAllModules = [];
@@ -12504,7 +12515,7 @@ class Module {
12504
12515
  return module.exports.has('default') || reexportDescriptions.has('default');
12505
12516
  },
12506
12517
  get hasModuleSideEffects() {
12507
- warnDeprecation('Accessing ModuleInfo.hasModuleSideEffects from plugins is deprecated. Please use ModuleInfo.moduleSideEffects instead.', false, options);
12518
+ warnDeprecation('Accessing ModuleInfo.hasModuleSideEffects from plugins is deprecated. Please use ModuleInfo.moduleSideEffects instead.', true, options);
12508
12519
  return this.moduleSideEffects;
12509
12520
  },
12510
12521
  id,
@@ -12816,10 +12827,14 @@ class Module {
12816
12827
  this.exportAllModules.push(...externalExportAllModules);
12817
12828
  }
12818
12829
  render(options) {
12819
- const magicString = this.magicString.clone();
12820
- this.ast.render(magicString, options);
12821
- this.usesTopLevelAwait = this.astContext.usesTopLevelAwait;
12822
- return magicString;
12830
+ const source = this.magicString.clone();
12831
+ this.ast.render(source, options);
12832
+ source.trim();
12833
+ const { usesTopLevelAwait } = this.astContext;
12834
+ if (usesTopLevelAwait && options.format !== 'es' && options.format !== 'system') {
12835
+ return error(errInvalidFormatForTopLevelAwait(this.id, options.format));
12836
+ }
12837
+ return { source, usesTopLevelAwait };
12823
12838
  }
12824
12839
  setSource({ ast, code, customTransformCache, originalCode, originalSourcemap, resolvedIds, sourcemapChain, transformDependencies, transformFiles, ...moduleOptions }) {
12825
12840
  this.info.code = code;
@@ -13253,11 +13268,11 @@ function getExportBlock$1(exports, dependencies, namedExportsMode, interop, snip
13253
13268
  return `${n}${n}${mechanism}${getSingleDefaultExport(exports, dependencies, interop, externalLiveBindings, getPropertyAccess)};`;
13254
13269
  }
13255
13270
  let exportBlock = '';
13256
- for (const { defaultVariableName, id, isChunk, name, namedExportsMode: depNamedExportsMode, namespaceVariableName, reexports } of dependencies) {
13271
+ for (const { defaultVariableName, importPath, isChunk, name, namedExportsMode: depNamedExportsMode, namespaceVariableName, reexports } of dependencies) {
13257
13272
  if (reexports && namedExportsMode) {
13258
13273
  for (const specifier of reexports) {
13259
13274
  if (specifier.reexported !== '*') {
13260
- const importName = getReexportedImportName(name, specifier.imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, id, externalLiveBindings, getPropertyAccess);
13275
+ const importName = getReexportedImportName(name, specifier.imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, importPath, externalLiveBindings, getPropertyAccess);
13261
13276
  if (exportBlock)
13262
13277
  exportBlock += n;
13263
13278
  if (specifier.imported !== '*' && specifier.needsLiveBinding) {
@@ -13315,9 +13330,9 @@ function getSingleDefaultExport(exports, dependencies, interop, externalLiveBind
13315
13330
  return exports[0].local;
13316
13331
  }
13317
13332
  else {
13318
- for (const { defaultVariableName, id, isChunk, name, namedExportsMode: depNamedExportsMode, namespaceVariableName, reexports } of dependencies) {
13333
+ for (const { defaultVariableName, importPath, isChunk, name, namedExportsMode: depNamedExportsMode, namespaceVariableName, reexports } of dependencies) {
13319
13334
  if (reexports) {
13320
- return getReexportedImportName(name, reexports[0].imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, id, externalLiveBindings, getPropertyAccess);
13335
+ return getReexportedImportName(name, reexports[0].imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, importPath, externalLiveBindings, getPropertyAccess);
13321
13336
  }
13322
13337
  }
13323
13338
  }
@@ -13392,7 +13407,7 @@ function getInteropBlock(dependencies, interop, externalLiveBindings, freeze, na
13392
13407
  neededInteropHelpers.add(helper);
13393
13408
  interopStatements.push(`${cnst} ${helperVariableName}${_}=${_}/*#__PURE__*/${helper}(${dependencyVariableName});`);
13394
13409
  };
13395
- for (const { defaultVariableName, imports, id, isChunk, name, namedExportsMode, namespaceVariableName, reexports } of dependencies) {
13410
+ for (const { defaultVariableName, imports, importPath, isChunk, name, namedExportsMode, namespaceVariableName, reexports } of dependencies) {
13396
13411
  if (isChunk) {
13397
13412
  for (const { imported, reexported } of [
13398
13413
  ...(imports || []),
@@ -13407,7 +13422,7 @@ function getInteropBlock(dependencies, interop, externalLiveBindings, freeze, na
13407
13422
  }
13408
13423
  }
13409
13424
  else {
13410
- const moduleInterop = String(interop(id));
13425
+ const moduleInterop = String(interop(importPath));
13411
13426
  let hasDefault = false;
13412
13427
  let hasNamespace = false;
13413
13428
  for (const { imported, reexported } of [
@@ -13472,7 +13487,9 @@ const builtins = {
13472
13487
  zlib: true
13473
13488
  };
13474
13489
  function warnOnBuiltins(warn, dependencies) {
13475
- const externalBuiltins = dependencies.map(({ id }) => id).filter(id => id in builtins);
13490
+ const externalBuiltins = dependencies
13491
+ .map(({ importPath }) => importPath)
13492
+ .filter(importPath => importPath in builtins);
13476
13493
  if (!externalBuiltins.length)
13477
13494
  return;
13478
13495
  warn({
@@ -13482,9 +13499,9 @@ function warnOnBuiltins(warn, dependencies) {
13482
13499
  });
13483
13500
  }
13484
13501
 
13485
- function amd(magicString, { accessedGlobals, dependencies, exports, hasExports, id, indent: t, intro, isEntryFacade, isModuleFacade, namedExportsMode, outro, snippets, warn }, { amd, esModule, externalLiveBindings, freeze, interop, namespaceToStringTag, strict }) {
13486
- warnOnBuiltins(warn, dependencies);
13487
- const deps = dependencies.map(m => `'${removeExtensionFromRelativeAmdId(m.id)}'`);
13502
+ function amd(magicString, { accessedGlobals, dependencies, exports, hasExports, id, indent: t, intro, isEntryFacade, isModuleFacade, namedExportsMode, outro, snippets, onwarn }, { amd, esModule, externalLiveBindings, freeze, interop, namespaceToStringTag, strict }) {
13503
+ warnOnBuiltins(onwarn, dependencies);
13504
+ const deps = dependencies.map(m => `'${removeExtensionFromRelativeAmdId(m.importPath)}'`);
13488
13505
  const args = dependencies.map(m => m.name);
13489
13506
  const { n, getNonArrowFunctionIntro, _ } = snippets;
13490
13507
  if (namedExportsMode && hasExports) {
@@ -13509,8 +13526,8 @@ function amd(magicString, { accessedGlobals, dependencies, exports, hasExports,
13509
13526
  if (namespaceMarkers) {
13510
13527
  namespaceMarkers = n + n + namespaceMarkers;
13511
13528
  }
13512
- magicString.append(`${exportBlock}${namespaceMarkers}${outro}`);
13513
- return (magicString
13529
+ magicString
13530
+ .append(`${exportBlock}${namespaceMarkers}${outro}`)
13514
13531
  .indent(t)
13515
13532
  // factory function should be wrapped by parentheses to avoid lazy parsing,
13516
13533
  // cf. https://v8.dev/blog/preparser#pife
@@ -13518,7 +13535,7 @@ function amd(magicString, { accessedGlobals, dependencies, exports, hasExports,
13518
13535
  isAsync: false,
13519
13536
  name: null
13520
13537
  })}{${useStrict}${n}${n}`)
13521
- .append(`${n}${n}}));`));
13538
+ .append(`${n}${n}}));`);
13522
13539
  }
13523
13540
 
13524
13541
  function cjs(magicString, { accessedGlobals, dependencies, exports, hasExports, indent: t, intro, isEntryFacade, isModuleFacade, namedExportsMode, outro, snippets }, { compact, esModule, externalLiveBindings, freeze, interop, namespaceToStringTag, strict }) {
@@ -13532,23 +13549,23 @@ function cjs(magicString, { accessedGlobals, dependencies, exports, hasExports,
13532
13549
  const interopBlock = getInteropBlock(dependencies, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, t, snippets);
13533
13550
  magicString.prepend(`${useStrict}${intro}${namespaceMarkers}${importBlock}${interopBlock}`);
13534
13551
  const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings, `module.exports${_}=${_}`);
13535
- return magicString.append(`${exportBlock}${outro}`);
13552
+ magicString.append(`${exportBlock}${outro}`);
13536
13553
  }
13537
13554
  function getImportBlock$1(dependencies, { _, cnst, n }, compact) {
13538
13555
  let importBlock = '';
13539
13556
  let definingVariable = false;
13540
- for (const { id, name, reexports, imports } of dependencies) {
13557
+ for (const { importPath, name, reexports, imports } of dependencies) {
13541
13558
  if (!reexports && !imports) {
13542
13559
  if (importBlock) {
13543
13560
  importBlock += compact && !definingVariable ? ',' : `;${n}`;
13544
13561
  }
13545
13562
  definingVariable = false;
13546
- importBlock += `require('${id}')`;
13563
+ importBlock += `require('${importPath}')`;
13547
13564
  }
13548
13565
  else {
13549
13566
  importBlock += compact && definingVariable ? ',' : `${importBlock ? `;${n}` : ''}${cnst} `;
13550
13567
  definingVariable = true;
13551
- importBlock += `${name}${_}=${_}require('${id}')`;
13568
+ importBlock += `${name}${_}=${_}require('${importPath}')`;
13552
13569
  }
13553
13570
  }
13554
13571
  if (importBlock) {
@@ -13570,13 +13587,13 @@ function es(magicString, { accessedGlobals, indent: t, intro, outro, dependencie
13570
13587
  magicString.append(n + n + exportBlock.join(n).trim());
13571
13588
  if (outro)
13572
13589
  magicString.append(outro);
13573
- return magicString.trim();
13590
+ magicString.trim();
13574
13591
  }
13575
13592
  function getImportBlock(dependencies, _) {
13576
13593
  const importBlock = [];
13577
- for (const { id, reexports, imports, name } of dependencies) {
13594
+ for (const { importPath, reexports, imports, name } of dependencies) {
13578
13595
  if (!reexports && !imports) {
13579
- importBlock.push(`import${_}'${id}';`);
13596
+ importBlock.push(`import${_}'${importPath}';`);
13580
13597
  continue;
13581
13598
  }
13582
13599
  if (imports) {
@@ -13595,10 +13612,10 @@ function getImportBlock(dependencies, _) {
13595
13612
  }
13596
13613
  }
13597
13614
  if (starImport) {
13598
- importBlock.push(`import${_}*${_}as ${starImport.local} from${_}'${id}';`);
13615
+ importBlock.push(`import${_}*${_}as ${starImport.local} from${_}'${importPath}';`);
13599
13616
  }
13600
13617
  if (defaultImport && importedNames.length === 0) {
13601
- importBlock.push(`import ${defaultImport.local} from${_}'${id}';`);
13618
+ importBlock.push(`import ${defaultImport.local} from${_}'${importPath}';`);
13602
13619
  }
13603
13620
  else if (importedNames.length > 0) {
13604
13621
  importBlock.push(`import ${defaultImport ? `${defaultImport.local},${_}` : ''}{${_}${importedNames
@@ -13610,7 +13627,7 @@ function getImportBlock(dependencies, _) {
13610
13627
  return `${specifier.imported} as ${specifier.local}`;
13611
13628
  }
13612
13629
  })
13613
- .join(`,${_}`)}${_}}${_}from${_}'${id}';`);
13630
+ .join(`,${_}`)}${_}}${_}from${_}'${importPath}';`);
13614
13631
  }
13615
13632
  }
13616
13633
  if (reexports) {
@@ -13629,12 +13646,12 @@ function getImportBlock(dependencies, _) {
13629
13646
  }
13630
13647
  }
13631
13648
  if (starExport) {
13632
- importBlock.push(`export${_}*${_}from${_}'${id}';`);
13649
+ importBlock.push(`export${_}*${_}from${_}'${importPath}';`);
13633
13650
  }
13634
13651
  if (namespaceReexports.length > 0) {
13635
13652
  if (!imports ||
13636
13653
  !imports.some(specifier => specifier.imported === '*' && specifier.local === name)) {
13637
- importBlock.push(`import${_}*${_}as ${name} from${_}'${id}';`);
13654
+ importBlock.push(`import${_}*${_}as ${name} from${_}'${importPath}';`);
13638
13655
  }
13639
13656
  for (const specifier of namespaceReexports) {
13640
13657
  importBlock.push(`export${_}{${_}${name === specifier.reexported ? name : `${name} as ${specifier.reexported}`} };`);
@@ -13650,7 +13667,7 @@ function getImportBlock(dependencies, _) {
13650
13667
  return `${specifier.imported} as ${specifier.reexported}`;
13651
13668
  }
13652
13669
  })
13653
- .join(`,${_}`)}${_}}${_}from${_}'${id}';`);
13670
+ .join(`,${_}`)}${_}}${_}from${_}'${importPath}';`);
13654
13671
  }
13655
13672
  }
13656
13673
  }
@@ -13716,7 +13733,7 @@ function trimEmptyImports(dependencies) {
13716
13733
  return [];
13717
13734
  }
13718
13735
 
13719
- function iife(magicString, { accessedGlobals, dependencies, exports, hasExports, indent: t, intro, namedExportsMode, outro, snippets, warn }, { compact, esModule, extend, freeze, externalLiveBindings, globals, interop, name, namespaceToStringTag, strict }) {
13736
+ function iife(magicString, { accessedGlobals, dependencies, exports, hasExports, indent: t, intro, namedExportsMode, outro, snippets, onwarn }, { compact, esModule, extend, freeze, externalLiveBindings, globals, interop, name, namespaceToStringTag, strict }) {
13720
13737
  const { _, cnst, getNonArrowFunctionIntro, getPropertyAccess, n } = snippets;
13721
13738
  const isNamespaced = name && name.includes('.');
13722
13739
  const useVariableAssignment = !extend && !isNamespaced;
@@ -13726,12 +13743,12 @@ function iife(magicString, { accessedGlobals, dependencies, exports, hasExports,
13726
13743
  message: `Given name "${name}" is not a legal JS identifier. If you need this, you can try "output.extend: true".`
13727
13744
  });
13728
13745
  }
13729
- warnOnBuiltins(warn, dependencies);
13746
+ warnOnBuiltins(onwarn, dependencies);
13730
13747
  const external = trimEmptyImports(dependencies);
13731
13748
  const deps = external.map(dep => dep.globalName || 'null');
13732
13749
  const args = external.map(m => m.name);
13733
13750
  if (hasExports && !name) {
13734
- warn({
13751
+ onwarn({
13735
13752
  code: 'MISSING_NAME_OPTION_FOR_IIFE_EXPORT',
13736
13753
  message: `If you do not supply "output.name", you may not be able to access the exports of an IIFE bundle.`
13737
13754
  });
@@ -13772,8 +13789,11 @@ function iife(magicString, { accessedGlobals, dependencies, exports, hasExports,
13772
13789
  if (namespaceMarkers) {
13773
13790
  namespaceMarkers = n + n + namespaceMarkers;
13774
13791
  }
13775
- magicString.append(`${exportBlock}${namespaceMarkers}${outro}`);
13776
- return magicString.indent(t).prepend(wrapperIntro).append(wrapperOutro);
13792
+ magicString
13793
+ .append(`${exportBlock}${namespaceMarkers}${outro}`)
13794
+ .indent(t)
13795
+ .prepend(wrapperIntro)
13796
+ .append(wrapperOutro);
13777
13797
  }
13778
13798
 
13779
13799
  function system(magicString, { accessedGlobals, dependencies, exports, hasExports, indent: t, intro, snippets, outro, usesTopLevelAwait }, { externalLiveBindings, freeze, name, namespaceToStringTag, strict, systemNullSetters }) {
@@ -13788,7 +13808,7 @@ function system(magicString, { accessedGlobals, dependencies, exports, hasExport
13788
13808
  // factory function should be wrapped by parentheses to avoid lazy parsing,
13789
13809
  // cf. https://v8.dev/blog/preparser#pife
13790
13810
  let wrapperStart = `System.register(${registeredName}[` +
13791
- dependencies.map(({ id }) => `'${id}'`).join(`,${_}`) +
13811
+ dependencies.map(({ importPath }) => `'${importPath}'`).join(`,${_}`) +
13792
13812
  `],${_}(${getNonArrowFunctionIntro(wrapperParams, { isAsync: false, name: null })}{${n}${t}${strict ? "'use strict';" : ''}` +
13793
13813
  getStarExcludesBlock(starExcludes, t, snippets) +
13794
13814
  getImportBindingsBlock(importBindings, t, snippets) +
@@ -13809,13 +13829,16 @@ function system(magicString, { accessedGlobals, dependencies, exports, hasExport
13809
13829
  name: null
13810
13830
  })}{${n}${n}`;
13811
13831
  const wrapperEnd = `${t}${t}})${n}${t}}${s}${n}}));`;
13812
- magicString.prepend(intro +
13832
+ magicString
13833
+ .prepend(intro +
13813
13834
  getHelpersBlock(null, accessedGlobals, t, snippets, externalLiveBindings, freeze, namespaceToStringTag) +
13814
- getHoistedExportsBlock(exports, t, snippets));
13815
- magicString.append(`${outro}${n}${n}` +
13835
+ getHoistedExportsBlock(exports, t, snippets))
13836
+ .append(`${outro}${n}${n}` +
13816
13837
  getSyntheticExportsBlock(exports, t, snippets) +
13817
- getMissingExportsBlock(exports, t, snippets));
13818
- return magicString.indent(`${t}${t}${t}`).append(wrapperEnd).prepend(wrapperStart);
13838
+ getMissingExportsBlock(exports, t, snippets))
13839
+ .indent(`${t}${t}${t}`)
13840
+ .append(wrapperEnd)
13841
+ .prepend(wrapperStart);
13819
13842
  }
13820
13843
  function analyzeDependencies(dependencies, exports, t, { _, cnst, getObject, getPropertyAccess, n }) {
13821
13844
  const importBindings = [];
@@ -13917,7 +13940,7 @@ function safeAccess(name, globalVar, { _, getPropertyAccess }) {
13917
13940
  .map(part => (propertyPath += getPropertyAccess(part)))
13918
13941
  .join(`${_}&&${_}`);
13919
13942
  }
13920
- function umd(magicString, { accessedGlobals, dependencies, exports, hasExports, id, indent: t, intro, namedExportsMode, outro, snippets, warn }, { amd, compact, esModule, extend, externalLiveBindings, freeze, interop, name, namespaceToStringTag, globals, noConflict, strict }) {
13943
+ function umd(magicString, { accessedGlobals, dependencies, exports, hasExports, id, indent: t, intro, namedExportsMode, outro, snippets, onwarn }, { amd, compact, esModule, extend, externalLiveBindings, freeze, interop, name, namespaceToStringTag, globals, noConflict, strict }) {
13921
13944
  const { _, cnst, getFunctionIntro, getNonArrowFunctionIntro, getPropertyAccess, n, s } = snippets;
13922
13945
  const factoryVar = compact ? 'f' : 'factory';
13923
13946
  const globalVar = compact ? 'g' : 'global';
@@ -13927,9 +13950,9 @@ function umd(magicString, { accessedGlobals, dependencies, exports, hasExports,
13927
13950
  message: 'You must supply "output.name" for UMD bundles that have exports so that the exports are accessible in environments without a module loader.'
13928
13951
  });
13929
13952
  }
13930
- warnOnBuiltins(warn, dependencies);
13931
- const amdDeps = dependencies.map(m => `'${removeExtensionFromRelativeAmdId(m.id)}'`);
13932
- const cjsDeps = dependencies.map(m => `require('${m.id}')`);
13953
+ warnOnBuiltins(onwarn, dependencies);
13954
+ const amdDeps = dependencies.map(m => `'${removeExtensionFromRelativeAmdId(m.importPath)}'`);
13955
+ const cjsDeps = dependencies.map(m => `require('${m.importPath}')`);
13933
13956
  const trimmedImports = trimEmptyImports(dependencies);
13934
13957
  const globalDeps = trimmedImports.map(module => globalProp(module.globalName, globalVar, getPropertyAccess));
13935
13958
  const factoryParams = trimmedImports.map(m => m.name);
@@ -14006,169 +14029,328 @@ function umd(magicString, { accessedGlobals, dependencies, exports, hasExports,
14006
14029
  if (namespaceMarkers) {
14007
14030
  namespaceMarkers = n + n + namespaceMarkers;
14008
14031
  }
14009
- magicString.append(`${exportBlock}${namespaceMarkers}${outro}`);
14010
- return magicString.trim().indent(t).append(wrapperOutro).prepend(wrapperIntro);
14032
+ magicString
14033
+ .append(`${exportBlock}${namespaceMarkers}${outro}`)
14034
+ .trim()
14035
+ .indent(t)
14036
+ .append(wrapperOutro)
14037
+ .prepend(wrapperIntro);
14011
14038
  }
14012
14039
 
14013
14040
  const finalisers = { amd, cjs, es, iife, system, umd };
14014
14041
 
14015
- class Source {
14016
- constructor(filename, content) {
14017
- this.isOriginal = true;
14018
- this.filename = filename;
14019
- this.content = content;
14020
- }
14021
- traceSegment(line, column, name) {
14022
- return { column, line, name, source: this };
14042
+ const createHash = () => crypto.createHash('sha256');
14043
+
14044
+ // Four random characters from the private use area to minimize risk of conflicts
14045
+ const hashPlaceholderLeft = '\uf7f9\ue4d3';
14046
+ const hashPlaceholderRight = '\ue3cc\uf1fe';
14047
+ const hashPlaceholderOverhead = hashPlaceholderLeft.length + hashPlaceholderRight.length;
14048
+ // This is the size of a sha256
14049
+ const maxHashSize = 64;
14050
+ const defaultHashSize = 8;
14051
+ const getHashPlaceholderGenerator = () => {
14052
+ let nextIndex = 0;
14053
+ return (optionName, hashSize = defaultHashSize) => {
14054
+ if (hashSize > maxHashSize) {
14055
+ return error(errFailedValidation(`Hashes cannot be longer than ${maxHashSize} characters, received ${hashSize}. Check the "${optionName}" option.`));
14056
+ }
14057
+ const placeholder = `${hashPlaceholderLeft}${String(++nextIndex).padStart(hashSize - hashPlaceholderOverhead, '0')}${hashPlaceholderRight}`;
14058
+ if (placeholder.length > hashSize) {
14059
+ return error(errFailedValidation(`To generate hashes for this number of chunks (currently ${nextIndex}), you need a minimum hash size of ${placeholder.length}, received ${hashSize}. Check the "${optionName}" option.`));
14060
+ }
14061
+ nextIndex++;
14062
+ return placeholder;
14063
+ };
14064
+ };
14065
+ const REPLACER_REGEX = new RegExp(`${hashPlaceholderLeft}\\d{1,${maxHashSize - hashPlaceholderOverhead}}${hashPlaceholderRight}`, 'g');
14066
+ const replacePlaceholders = (code, hashesByPlaceholder) => code.replace(REPLACER_REGEX, placeholder => hashesByPlaceholder.get(placeholder) || placeholder);
14067
+ const replaceSinglePlaceholder = (code, placeholder, value) => code.replace(REPLACER_REGEX, match => (match === placeholder ? value : match));
14068
+ const replacePlaceholdersWithDefaultAndGetContainedPlaceholders = (code, placeholders) => {
14069
+ const containedPlaceholders = new Set();
14070
+ const transformedCode = code.replace(REPLACER_REGEX, placeholder => {
14071
+ if (placeholders.has(placeholder)) {
14072
+ containedPlaceholders.add(placeholder);
14073
+ return `${hashPlaceholderLeft}${'0'.repeat(placeholder.length - hashPlaceholderOverhead)}${hashPlaceholderRight}`;
14074
+ }
14075
+ return placeholder;
14076
+ });
14077
+ return { containedPlaceholders, transformedCode };
14078
+ };
14079
+
14080
+ function renderNamePattern(pattern, patternName, replacements) {
14081
+ if (isPathFragment(pattern))
14082
+ return error(errFailedValidation(`Invalid pattern "${pattern}" for "${patternName}", patterns can be neither absolute nor relative paths.`));
14083
+ return pattern.replace(/\[(\w+)(:\d+)?]/g, (_match, type, size) => {
14084
+ if (!replacements.hasOwnProperty(type) || (size && type !== 'hash')) {
14085
+ return error(errFailedValidation(`"[${type}${size || ''}]" is not a valid placeholder in the "${patternName}" pattern.`));
14086
+ }
14087
+ const replacement = replacements[type](size && parseInt(size.slice(1)));
14088
+ if (isPathFragment(replacement))
14089
+ return error(errFailedValidation(`Invalid substitution "${replacement}" for placeholder "[${type}]" in "${patternName}" pattern, can be neither absolute nor relative path.`));
14090
+ return replacement;
14091
+ });
14092
+ }
14093
+ function makeUnique(name, existingNames) {
14094
+ const existingNamesLowercase = new Set(Object.keys(existingNames).map(key => key.toLowerCase()));
14095
+ if (!existingNamesLowercase.has(name.toLocaleLowerCase()))
14096
+ return name;
14097
+ const ext = require$$0.extname(name);
14098
+ name = name.substring(0, name.length - ext.length);
14099
+ let uniqueName, uniqueIndex = 1;
14100
+ while (existingNamesLowercase.has((uniqueName = name + ++uniqueIndex + ext).toLowerCase()))
14101
+ ;
14102
+ return uniqueName;
14103
+ }
14104
+
14105
+ function generateAssetFileName(name, source, outputOptions, bundle) {
14106
+ const emittedName = outputOptions.sanitizeFileName(name || 'asset');
14107
+ return makeUnique(renderNamePattern(typeof outputOptions.assetFileNames === 'function'
14108
+ ? outputOptions.assetFileNames({ name, source, type: 'asset' })
14109
+ : outputOptions.assetFileNames, 'output.assetFileNames', {
14110
+ ext: () => require$$0.extname(emittedName).substring(1),
14111
+ extname: () => require$$0.extname(emittedName),
14112
+ hash: size => createHash()
14113
+ .update(source)
14114
+ .digest('hex')
14115
+ .substring(0, size || defaultHashSize),
14116
+ name: () => emittedName.substring(0, emittedName.length - require$$0.extname(emittedName).length)
14117
+ }), bundle);
14118
+ }
14119
+ function reserveFileNameInBundle(fileName, bundle, warn) {
14120
+ if (fileName in bundle) {
14121
+ warn(errFileNameConflict(fileName));
14023
14122
  }
14123
+ bundle[fileName] = FILE_PLACEHOLDER;
14024
14124
  }
14025
- class Link {
14026
- constructor(map, sources) {
14027
- this.sources = sources;
14028
- this.names = map.names;
14029
- this.mappings = map.mappings;
14125
+ const FILE_PLACEHOLDER = {
14126
+ type: 'placeholder'
14127
+ };
14128
+ function hasValidType(emittedFile) {
14129
+ return Boolean(emittedFile &&
14130
+ (emittedFile.type === 'asset' ||
14131
+ emittedFile.type === 'chunk'));
14132
+ }
14133
+ function hasValidName(emittedFile) {
14134
+ const validatedName = emittedFile.fileName || emittedFile.name;
14135
+ return !validatedName || (typeof validatedName === 'string' && !isPathFragment(validatedName));
14136
+ }
14137
+ function getValidSource(source, emittedFile, fileReferenceId) {
14138
+ if (!(typeof source === 'string' || source instanceof Uint8Array)) {
14139
+ const assetName = emittedFile.fileName || emittedFile.name || fileReferenceId;
14140
+ return error(errFailedValidation(`Could not set source for ${typeof assetName === 'string' ? `asset "${assetName}"` : 'unnamed asset'}, asset source needs to be a string, Uint8Array or Buffer.`));
14030
14141
  }
14031
- traceMappings() {
14032
- const sources = [];
14033
- const sourceIndexMap = new Map();
14034
- const sourcesContent = [];
14035
- const names = [];
14036
- const nameIndexMap = new Map();
14037
- const mappings = [];
14038
- for (const line of this.mappings) {
14039
- const tracedLine = [];
14040
- for (const segment of line) {
14041
- if (segment.length === 1)
14042
- continue;
14043
- const source = this.sources[segment[1]];
14044
- if (!source)
14045
- continue;
14046
- const traced = source.traceSegment(segment[2], segment[3], segment.length === 5 ? this.names[segment[4]] : '');
14047
- if (traced) {
14048
- const { column, line, name, source: { content, filename } } = traced;
14049
- let sourceIndex = sourceIndexMap.get(filename);
14050
- if (sourceIndex === undefined) {
14051
- sourceIndex = sources.length;
14052
- sources.push(filename);
14053
- sourceIndexMap.set(filename, sourceIndex);
14054
- sourcesContent[sourceIndex] = content;
14055
- }
14056
- else if (sourcesContent[sourceIndex] == null) {
14057
- sourcesContent[sourceIndex] = content;
14058
- }
14059
- else if (content != null && sourcesContent[sourceIndex] !== content) {
14060
- return error({
14061
- message: `Multiple conflicting contents for sourcemap source ${filename}`
14062
- });
14063
- }
14064
- const tracedSegment = [segment[0], sourceIndex, line, column];
14065
- if (name) {
14066
- let nameIndex = nameIndexMap.get(name);
14067
- if (nameIndex === undefined) {
14068
- nameIndex = names.length;
14069
- names.push(name);
14070
- nameIndexMap.set(name, nameIndex);
14071
- }
14072
- tracedSegment[4] = nameIndex;
14073
- }
14074
- tracedLine.push(tracedSegment);
14075
- }
14076
- }
14077
- mappings.push(tracedLine);
14078
- }
14079
- return { mappings, names, sources, sourcesContent };
14142
+ return source;
14143
+ }
14144
+ function getAssetFileName(file, referenceId) {
14145
+ if (typeof file.fileName !== 'string') {
14146
+ return error(errAssetNotFinalisedForFileName(file.name || referenceId));
14080
14147
  }
14081
- traceSegment(line, column, name) {
14082
- const segments = this.mappings[line];
14083
- if (!segments)
14084
- return null;
14085
- // binary search through segments for the given column
14086
- let searchStart = 0;
14087
- let searchEnd = segments.length - 1;
14088
- while (searchStart <= searchEnd) {
14089
- const m = (searchStart + searchEnd) >> 1;
14090
- const segment = segments[m];
14091
- // If a sourcemap does not have sufficient resolution to contain a
14092
- // necessary mapping, e.g. because it only contains line information, we
14093
- // use the best approximation we could find
14094
- if (segment[0] === column || searchStart === searchEnd) {
14095
- if (segment.length == 1)
14096
- return null;
14097
- const source = this.sources[segment[1]];
14098
- if (!source)
14099
- return null;
14100
- return source.traceSegment(segment[2], segment[3], segment.length === 5 ? this.names[segment[4]] : name);
14148
+ return file.fileName;
14149
+ }
14150
+ function getChunkFileName(file, facadeChunkByModule) {
14151
+ if (file.fileName) {
14152
+ return file.fileName;
14153
+ }
14154
+ if (facadeChunkByModule) {
14155
+ const chunk = facadeChunkByModule.get(file.module);
14156
+ return chunk.id || chunk.getFileName();
14157
+ }
14158
+ return error(errChunkNotGeneratedForFileName(file.fileName || file.name));
14159
+ }
14160
+ class FileEmitter {
14161
+ constructor(graph, options, baseFileEmitter) {
14162
+ this.graph = graph;
14163
+ this.options = options;
14164
+ this.bundle = null;
14165
+ this.facadeChunkByModule = null;
14166
+ this.outputOptions = null;
14167
+ this.emitFile = (emittedFile) => {
14168
+ if (!hasValidType(emittedFile)) {
14169
+ return error(errFailedValidation(`Emitted files must be of type "asset" or "chunk", received "${emittedFile && emittedFile.type}".`));
14101
14170
  }
14102
- if (segment[0] > column) {
14103
- searchEnd = m - 1;
14171
+ if (!hasValidName(emittedFile)) {
14172
+ return error(errFailedValidation(`The "fileName" or "name" properties of emitted files must be strings that are neither absolute nor relative paths, received "${emittedFile.fileName || emittedFile.name}".`));
14173
+ }
14174
+ if (emittedFile.type === 'chunk') {
14175
+ return this.emitChunk(emittedFile);
14176
+ }
14177
+ return this.emitAsset(emittedFile);
14178
+ };
14179
+ this.finaliseAssets = () => {
14180
+ for (const [referenceId, emittedFile] of this.filesByReferenceId) {
14181
+ if (emittedFile.type === 'asset' && typeof emittedFile.fileName !== 'string')
14182
+ return error(errNoAssetSourceSet(emittedFile.name || referenceId));
14183
+ }
14184
+ };
14185
+ this.getFileName = (fileReferenceId) => {
14186
+ const emittedFile = this.filesByReferenceId.get(fileReferenceId);
14187
+ if (!emittedFile)
14188
+ return error(errFileReferenceIdNotFoundForFilename(fileReferenceId));
14189
+ if (emittedFile.type === 'chunk') {
14190
+ return getChunkFileName(emittedFile, this.facadeChunkByModule);
14191
+ }
14192
+ return getAssetFileName(emittedFile, fileReferenceId);
14193
+ };
14194
+ this.setAssetSource = (referenceId, requestedSource) => {
14195
+ const consumedFile = this.filesByReferenceId.get(referenceId);
14196
+ if (!consumedFile)
14197
+ return error(errAssetReferenceIdNotFoundForSetSource(referenceId));
14198
+ if (consumedFile.type !== 'asset') {
14199
+ return error(errFailedValidation(`Asset sources can only be set for emitted assets but "${referenceId}" is an emitted chunk.`));
14200
+ }
14201
+ if (consumedFile.source !== undefined) {
14202
+ return error(errAssetSourceAlreadySet(consumedFile.name || referenceId));
14203
+ }
14204
+ const source = getValidSource(requestedSource, consumedFile, referenceId);
14205
+ if (this.bundle) {
14206
+ this.finalizeAsset(consumedFile, source, referenceId, this.bundle);
14104
14207
  }
14105
14208
  else {
14106
- searchStart = m + 1;
14209
+ consumedFile.source = source;
14210
+ }
14211
+ };
14212
+ this.setChunkInformation = (facadeChunkByModule) => {
14213
+ this.facadeChunkByModule = facadeChunkByModule;
14214
+ };
14215
+ this.setOutputBundle = (outputBundle, outputOptions) => {
14216
+ this.outputOptions = outputOptions;
14217
+ this.bundle = outputBundle;
14218
+ for (const emittedFile of this.filesByReferenceId.values()) {
14219
+ if (emittedFile.fileName) {
14220
+ reserveFileNameInBundle(emittedFile.fileName, this.bundle, this.options.onwarn);
14221
+ }
14222
+ }
14223
+ for (const [referenceId, consumedFile] of this.filesByReferenceId) {
14224
+ if (consumedFile.type === 'asset' && consumedFile.source !== undefined) {
14225
+ this.finalizeAsset(consumedFile, consumedFile.source, referenceId, this.bundle);
14226
+ }
14227
+ }
14228
+ };
14229
+ this.filesByReferenceId = baseFileEmitter
14230
+ ? new Map(baseFileEmitter.filesByReferenceId)
14231
+ : new Map();
14232
+ }
14233
+ assignReferenceId(file, idBase) {
14234
+ let referenceId;
14235
+ do {
14236
+ referenceId = createHash()
14237
+ .update(referenceId || idBase)
14238
+ .digest('hex')
14239
+ .substring(0, 8);
14240
+ } while (this.filesByReferenceId.has(referenceId));
14241
+ this.filesByReferenceId.set(referenceId, file);
14242
+ return referenceId;
14243
+ }
14244
+ emitAsset(emittedAsset) {
14245
+ const source = typeof emittedAsset.source !== 'undefined'
14246
+ ? getValidSource(emittedAsset.source, emittedAsset, null)
14247
+ : undefined;
14248
+ const consumedAsset = {
14249
+ fileName: emittedAsset.fileName,
14250
+ name: emittedAsset.name,
14251
+ source,
14252
+ type: 'asset'
14253
+ };
14254
+ const referenceId = this.assignReferenceId(consumedAsset, emittedAsset.fileName || emittedAsset.name || emittedAsset.type);
14255
+ if (this.bundle) {
14256
+ if (emittedAsset.fileName) {
14257
+ reserveFileNameInBundle(emittedAsset.fileName, this.bundle, this.options.onwarn);
14258
+ }
14259
+ if (source !== undefined) {
14260
+ this.finalizeAsset(consumedAsset, source, referenceId, this.bundle);
14107
14261
  }
14108
14262
  }
14109
- return null;
14263
+ return referenceId;
14110
14264
  }
14111
- }
14112
- function getLinkMap(warn) {
14113
- return function linkMap(source, map) {
14114
- if (map.mappings) {
14115
- return new Link(map, [source]);
14265
+ emitChunk(emittedChunk) {
14266
+ if (this.graph.phase > BuildPhase.LOAD_AND_PARSE) {
14267
+ return error(errInvalidRollupPhaseForChunkEmission());
14116
14268
  }
14117
- warn({
14118
- code: 'SOURCEMAP_BROKEN',
14119
- message: `Sourcemap is likely to be incorrect: a plugin (${map.plugin}) was used to transform ` +
14120
- "files, but didn't generate a sourcemap for the transformation. Consult the plugin " +
14121
- 'documentation for help',
14122
- plugin: map.plugin,
14123
- url: `https://rollupjs.org/guide/en/#warning-sourcemap-is-likely-to-be-incorrect`
14269
+ if (typeof emittedChunk.id !== 'string') {
14270
+ return error(errFailedValidation(`Emitted chunks need to have a valid string id, received "${emittedChunk.id}"`));
14271
+ }
14272
+ const consumedChunk = {
14273
+ fileName: emittedChunk.fileName,
14274
+ module: null,
14275
+ name: emittedChunk.name || emittedChunk.id,
14276
+ type: 'chunk'
14277
+ };
14278
+ this.graph.moduleLoader
14279
+ .emitChunk(emittedChunk)
14280
+ .then(module => (consumedChunk.module = module))
14281
+ .catch(() => {
14282
+ // Avoid unhandled Promise rejection as the error will be thrown later
14283
+ // once module loading has finished
14124
14284
  });
14125
- return new Link({
14126
- mappings: [],
14127
- names: []
14128
- }, [source]);
14129
- };
14130
- }
14131
- function getCollapsedSourcemap(id, originalCode, originalSourcemap, sourcemapChain, linkMap) {
14132
- let source;
14133
- if (!originalSourcemap) {
14134
- source = new Source(id, originalCode);
14285
+ return this.assignReferenceId(consumedChunk, emittedChunk.id);
14135
14286
  }
14136
- else {
14137
- const sources = originalSourcemap.sources;
14138
- const sourcesContent = originalSourcemap.sourcesContent || [];
14139
- const directory = require$$0.dirname(id) || '.';
14140
- const sourceRoot = originalSourcemap.sourceRoot || '.';
14141
- const baseSources = sources.map((source, i) => new Source(require$$0.resolve(directory, sourceRoot, source), sourcesContent[i]));
14142
- source = new Link(originalSourcemap, baseSources);
14287
+ finalizeAsset(consumedFile, source, referenceId, bundle) {
14288
+ const fileName = consumedFile.fileName ||
14289
+ findExistingAssetFileNameWithSource(bundle, source) ||
14290
+ generateAssetFileName(consumedFile.name, source, this.outputOptions, bundle);
14291
+ // We must not modify the original assets to avoid interaction between outputs
14292
+ const assetWithFileName = { ...consumedFile, fileName, source };
14293
+ this.filesByReferenceId.set(referenceId, assetWithFileName);
14294
+ bundle[fileName] = {
14295
+ fileName,
14296
+ name: consumedFile.name,
14297
+ source,
14298
+ type: 'asset'
14299
+ };
14143
14300
  }
14144
- return sourcemapChain.reduce(linkMap, source);
14145
14301
  }
14146
- function collapseSourcemaps(file, map, modules, bundleSourcemapChain, excludeContent, warn) {
14147
- const linkMap = getLinkMap(warn);
14148
- const moduleSources = modules
14149
- .filter(module => !module.excludeFromSourcemap)
14150
- .map(module => getCollapsedSourcemap(module.id, module.originalCode, module.originalSourcemap, module.sourcemapChain, linkMap));
14151
- const link = new Link(map, moduleSources);
14152
- const source = bundleSourcemapChain.reduce(linkMap, link);
14153
- let { sources, sourcesContent, names, mappings } = source.traceMappings();
14154
- if (file) {
14155
- const directory = require$$0.dirname(file);
14156
- sources = sources.map((source) => require$$0.relative(directory, source));
14157
- file = require$$0.basename(file);
14302
+ function findExistingAssetFileNameWithSource(bundle, source) {
14303
+ for (const [fileName, outputFile] of Object.entries(bundle)) {
14304
+ if (outputFile.type === 'asset' && areSourcesEqual(source, outputFile.source))
14305
+ return fileName;
14158
14306
  }
14159
- sourcesContent = (excludeContent ? null : sourcesContent);
14160
- return new SourceMap({ file, mappings, names, sources, sourcesContent });
14307
+ return null;
14161
14308
  }
14162
- function collapseSourcemap(id, originalCode, originalSourcemap, sourcemapChain, warn) {
14163
- if (!sourcemapChain.length) {
14164
- return originalSourcemap;
14309
+ function areSourcesEqual(sourceA, sourceB) {
14310
+ if (typeof sourceA === 'string') {
14311
+ return sourceA === sourceB;
14165
14312
  }
14166
- const source = getCollapsedSourcemap(id, originalCode, originalSourcemap, sourcemapChain, getLinkMap(warn));
14167
- const map = source.traceMappings();
14168
- return { version: 3, ...map };
14313
+ if (typeof sourceB === 'string') {
14314
+ return false;
14315
+ }
14316
+ if ('equals' in sourceA) {
14317
+ return sourceA.equals(sourceB);
14318
+ }
14319
+ if (sourceA.length !== sourceB.length) {
14320
+ return false;
14321
+ }
14322
+ for (let index = 0; index < sourceA.length; index++) {
14323
+ if (sourceA[index] !== sourceB[index]) {
14324
+ return false;
14325
+ }
14326
+ }
14327
+ return true;
14169
14328
  }
14170
14329
 
14171
- const createHash = () => crypto.createHash('sha256');
14330
+ const concatSep = (out, next) => (next ? `${out}\n${next}` : out);
14331
+ const concatDblSep = (out, next) => (next ? `${out}\n\n${next}` : out);
14332
+ async function createAddons(options, outputPluginDriver, chunk) {
14333
+ try {
14334
+ let [banner, footer, intro, outro] = await Promise.all([
14335
+ outputPluginDriver.hookReduceValue('banner', options.banner(chunk), [chunk], concatSep),
14336
+ outputPluginDriver.hookReduceValue('footer', options.footer(chunk), [chunk], concatSep),
14337
+ outputPluginDriver.hookReduceValue('intro', options.intro(chunk), [chunk], concatDblSep),
14338
+ outputPluginDriver.hookReduceValue('outro', options.outro(chunk), [chunk], concatDblSep)
14339
+ ]);
14340
+ if (intro)
14341
+ intro += '\n\n';
14342
+ if (outro)
14343
+ outro = `\n\n${outro}`;
14344
+ if (banner)
14345
+ banner += '\n';
14346
+ if (footer)
14347
+ footer = '\n' + footer;
14348
+ return { banner, footer, intro, outro };
14349
+ }
14350
+ catch (err) {
14351
+ return error(errAddonNotGenerated(err.message, err.hook, err.plugin));
14352
+ }
14353
+ }
14172
14354
 
14173
14355
  const DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT = {
14174
14356
  amd: deconflictImportsOther,
@@ -14178,21 +14360,21 @@ const DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT = {
14178
14360
  system: deconflictImportsEsmOrSystem,
14179
14361
  umd: deconflictImportsOther
14180
14362
  };
14181
- function deconflictChunk(modules, dependenciesToBeDeconflicted, imports, usedNames, format, interop, preserveModules, externalLiveBindings, chunkByModule, syntheticExports, exportNamesByVariable, accessedGlobalsByScope, includedNamespaces) {
14363
+ function deconflictChunk(modules, dependenciesToBeDeconflicted, imports, usedNames, format, interop, preserveModules, externalLiveBindings, chunkByModule, externalChunkByModule, syntheticExports, exportNamesByVariable, accessedGlobalsByScope, includedNamespaces) {
14182
14364
  const reversedModules = modules.slice().reverse();
14183
14365
  for (const module of reversedModules) {
14184
14366
  module.scope.addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope);
14185
14367
  }
14186
14368
  deconflictTopLevelVariables(usedNames, reversedModules, includedNamespaces);
14187
- DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT[format](usedNames, imports, dependenciesToBeDeconflicted, interop, preserveModules, externalLiveBindings, chunkByModule, syntheticExports);
14369
+ DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT[format](usedNames, imports, dependenciesToBeDeconflicted, interop, preserveModules, externalLiveBindings, chunkByModule, externalChunkByModule, syntheticExports);
14188
14370
  for (const module of reversedModules) {
14189
14371
  module.scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
14190
14372
  }
14191
14373
  }
14192
- function deconflictImportsEsmOrSystem(usedNames, imports, dependenciesToBeDeconflicted, _interop, preserveModules, _externalLiveBindings, chunkByModule, syntheticExports) {
14374
+ function deconflictImportsEsmOrSystem(usedNames, imports, dependenciesToBeDeconflicted, _interop, preserveModules, _externalLiveBindings, chunkByModule, externalChunkByModule, syntheticExports) {
14193
14375
  // This is needed for namespace reexports
14194
14376
  for (const dependency of dependenciesToBeDeconflicted.dependencies) {
14195
- if (preserveModules || dependency instanceof ExternalModule) {
14377
+ if (preserveModules || dependency instanceof ExternalChunk) {
14196
14378
  dependency.variableName = getSafeName(dependency.suggestedVariableName, usedNames);
14197
14379
  }
14198
14380
  }
@@ -14200,7 +14382,9 @@ function deconflictImportsEsmOrSystem(usedNames, imports, dependenciesToBeDeconf
14200
14382
  const module = variable.module;
14201
14383
  const name = variable.name;
14202
14384
  if (variable.isNamespace && (preserveModules || module instanceof ExternalModule)) {
14203
- variable.setRenderNames(null, (module instanceof ExternalModule ? module : chunkByModule.get(module)).variableName);
14385
+ variable.setRenderNames(null, (module instanceof ExternalModule
14386
+ ? externalChunkByModule.get(module)
14387
+ : chunkByModule.get(module)).variableName);
14204
14388
  }
14205
14389
  else if (module instanceof ExternalModule && name === 'default') {
14206
14390
  variable.setRenderNames(null, getSafeName([...module.exportedVariables].some(([exportedVariable, exportedName]) => exportedName === '*' && exportedVariable.included)
@@ -14215,12 +14399,12 @@ function deconflictImportsEsmOrSystem(usedNames, imports, dependenciesToBeDeconf
14215
14399
  variable.setRenderNames(null, getSafeName(variable.name, usedNames));
14216
14400
  }
14217
14401
  }
14218
- function deconflictImportsOther(usedNames, imports, { deconflictedDefault, deconflictedNamespace, dependencies }, interop, preserveModules, externalLiveBindings, chunkByModule) {
14219
- for (const chunkOrExternalModule of dependencies) {
14220
- chunkOrExternalModule.variableName = getSafeName(chunkOrExternalModule.suggestedVariableName, usedNames);
14402
+ function deconflictImportsOther(usedNames, imports, { deconflictedDefault, deconflictedNamespace, dependencies }, interop, preserveModules, externalLiveBindings, chunkByModule, externalChunkByModule) {
14403
+ for (const chunk of dependencies) {
14404
+ chunk.variableName = getSafeName(chunk.suggestedVariableName, usedNames);
14221
14405
  }
14222
- for (const externalModuleOrChunk of deconflictedNamespace) {
14223
- externalModuleOrChunk.namespaceVariableName = getSafeName(`${externalModuleOrChunk.suggestedVariableName}__namespace`, usedNames);
14406
+ for (const chunk of deconflictedNamespace) {
14407
+ chunk.namespaceVariableName = getSafeName(`${chunk.suggestedVariableName}__namespace`, usedNames);
14224
14408
  }
14225
14409
  for (const externalModule of deconflictedDefault) {
14226
14410
  if (deconflictedNamespace.has(externalModule) &&
@@ -14234,12 +14418,13 @@ function deconflictImportsOther(usedNames, imports, { deconflictedDefault, decon
14234
14418
  for (const variable of imports) {
14235
14419
  const module = variable.module;
14236
14420
  if (module instanceof ExternalModule) {
14421
+ const chunk = externalChunkByModule.get(module);
14237
14422
  const name = variable.name;
14238
14423
  if (name === 'default') {
14239
14424
  const moduleInterop = String(interop(module.id));
14240
14425
  const variableName = defaultInteropHelpersByInteropType[moduleInterop]
14241
- ? module.defaultVariableName
14242
- : module.variableName;
14426
+ ? chunk.defaultVariableName
14427
+ : chunk.variableName;
14243
14428
  if (isDefaultAProperty(moduleInterop, externalLiveBindings)) {
14244
14429
  variable.setRenderNames(variableName, 'default');
14245
14430
  }
@@ -14249,12 +14434,12 @@ function deconflictImportsOther(usedNames, imports, { deconflictedDefault, decon
14249
14434
  }
14250
14435
  else if (name === '*') {
14251
14436
  variable.setRenderNames(null, namespaceInteropHelpersByInteropType[String(interop(module.id))]
14252
- ? module.namespaceVariableName
14253
- : module.variableName);
14437
+ ? chunk.namespaceVariableName
14438
+ : chunk.variableName);
14254
14439
  }
14255
14440
  else {
14256
14441
  // if the second parameter is `null`, it uses its "name" for the property name
14257
- variable.setRenderNames(module.variableName, null);
14442
+ variable.setRenderNames(chunk.variableName, null);
14258
14443
  }
14259
14444
  }
14260
14445
  else {
@@ -14288,15 +14473,6 @@ function deconflictTopLevelVariables(usedNames, modules, includedNamespaces) {
14288
14473
  }
14289
14474
  }
14290
14475
 
14291
- const needsEscapeRegEx = /[\\'\r\n\u2028\u2029]/;
14292
- const quoteNewlineRegEx = /(['\r\n\u2028\u2029])/g;
14293
- const backSlashRegEx = /\\/g;
14294
- function escapeId(id) {
14295
- if (!id.match(needsEscapeRegEx))
14296
- return id;
14297
- return id.replace(backSlashRegEx, '\\\\').replace(quoteNewlineRegEx, '\\$1');
14298
- }
14299
-
14300
14476
  function assignExportsToMangledNames(exports, exportsByName, exportNamesByVariable) {
14301
14477
  let nameIndex = 0;
14302
14478
  for (const variable of exports) {
@@ -14388,14 +14564,14 @@ function getIndentString(modules, options) {
14388
14564
  return '\t';
14389
14565
  }
14390
14566
 
14391
- function getStaticDependencies(chunk, orderedModules, chunkByModule) {
14567
+ function getStaticDependencies(chunk, orderedModules, chunkByModule, externalChunkByModule) {
14392
14568
  const staticDependencyBlocks = [];
14393
14569
  const handledDependencies = new Set();
14394
14570
  for (let modulePos = orderedModules.length - 1; modulePos >= 0; modulePos--) {
14395
14571
  const module = orderedModules[modulePos];
14396
14572
  if (!handledDependencies.has(module)) {
14397
14573
  const staticDependencies = [];
14398
- addStaticDependencies(module, staticDependencies, handledDependencies, chunk, chunkByModule);
14574
+ addStaticDependencies(module, staticDependencies, handledDependencies, chunk, chunkByModule, externalChunkByModule);
14399
14575
  staticDependencyBlocks.unshift(staticDependencies);
14400
14576
  }
14401
14577
  }
@@ -14407,11 +14583,11 @@ function getStaticDependencies(chunk, orderedModules, chunkByModule) {
14407
14583
  }
14408
14584
  return dependencies;
14409
14585
  }
14410
- function addStaticDependencies(module, staticDependencies, handledModules, chunk, chunkByModule) {
14586
+ function addStaticDependencies(module, staticDependencies, handledModules, chunk, chunkByModule, externalChunkByModule) {
14411
14587
  const dependencies = module.getDependenciesToBeIncluded();
14412
14588
  for (const dependency of dependencies) {
14413
14589
  if (dependency instanceof ExternalModule) {
14414
- staticDependencies.push(dependency);
14590
+ staticDependencies.push(externalChunkByModule.get(dependency));
14415
14591
  continue;
14416
14592
  }
14417
14593
  const dependencyChunk = chunkByModule.get(dependency);
@@ -14421,91 +14597,29 @@ function addStaticDependencies(module, staticDependencies, handledModules, chunk
14421
14597
  }
14422
14598
  if (!handledModules.has(dependency)) {
14423
14599
  handledModules.add(dependency);
14424
- addStaticDependencies(dependency, staticDependencies, handledModules, chunk, chunkByModule);
14600
+ addStaticDependencies(dependency, staticDependencies, handledModules, chunk, chunkByModule, externalChunkByModule);
14425
14601
  }
14426
14602
  }
14427
14603
  }
14428
14604
 
14429
- function decodedSourcemap(map) {
14430
- if (!map)
14431
- return null;
14432
- if (typeof map === 'string') {
14433
- map = JSON.parse(map);
14434
- }
14435
- if (map.mappings === '') {
14436
- return {
14437
- mappings: [],
14438
- names: [],
14439
- sources: [],
14440
- version: 3
14441
- };
14442
- }
14443
- const mappings = typeof map.mappings === 'string' ? decode(map.mappings) : map.mappings;
14444
- return { ...map, mappings };
14445
- }
14446
-
14447
- function renderChunk({ code, options, outputPluginDriver, renderChunk, sourcemapChain }) {
14448
- const renderChunkReducer = (code, result, plugin) => {
14449
- if (result == null)
14450
- return code;
14451
- if (typeof result === 'string')
14452
- result = {
14453
- code: result,
14454
- map: undefined
14455
- };
14456
- // strict null check allows 'null' maps to not be pushed to the chain, while 'undefined' gets the missing map warning
14457
- if (result.map !== null) {
14458
- const map = decodedSourcemap(result.map);
14459
- sourcemapChain.push(map || { missing: true, plugin: plugin.name });
14460
- }
14461
- return result.code;
14462
- };
14463
- return outputPluginDriver.hookReduceArg0('renderChunk', [code, renderChunk, options], renderChunkReducer);
14464
- }
14465
-
14466
- function renderNamePattern(pattern, patternName, replacements) {
14467
- if (isPathFragment(pattern))
14468
- return error(errFailedValidation(`Invalid pattern "${pattern}" for "${patternName}", patterns can be neither absolute nor relative paths.`));
14469
- return pattern.replace(/\[(\w+)\]/g, (_match, type) => {
14470
- if (!replacements.hasOwnProperty(type)) {
14471
- return error(errFailedValidation(`"[${type}]" is not a valid placeholder in "${patternName}" pattern.`));
14472
- }
14473
- const replacement = replacements[type]();
14474
- if (isPathFragment(replacement))
14475
- return error(errFailedValidation(`Invalid substitution "${replacement}" for placeholder "[${type}]" in "${patternName}" pattern, can be neither absolute nor relative path.`));
14476
- return replacement;
14477
- });
14478
- }
14479
- function makeUnique(name, existingNames) {
14480
- const existingNamesLowercase = new Set(Object.keys(existingNames).map(key => key.toLowerCase()));
14481
- if (!existingNamesLowercase.has(name.toLocaleLowerCase()))
14482
- return name;
14483
- const ext = require$$0.extname(name);
14484
- name = name.substring(0, name.length - ext.length);
14485
- let uniqueName, uniqueIndex = 1;
14486
- while (existingNamesLowercase.has((uniqueName = name + ++uniqueIndex + ext).toLowerCase()))
14487
- ;
14488
- return uniqueName;
14489
- }
14490
-
14491
14605
  const NON_ASSET_EXTENSIONS = ['.js', '.jsx', '.ts', '.tsx'];
14492
- function getGlobalName(module, globals, hasExports, warn) {
14493
- const globalName = typeof globals === 'function' ? globals(module.id) : globals[module.id];
14606
+ function getGlobalName(chunk, globals, hasExports, warn) {
14607
+ const globalName = typeof globals === 'function' ? globals(chunk.id) : globals[chunk.id];
14494
14608
  if (globalName) {
14495
14609
  return globalName;
14496
14610
  }
14497
14611
  if (hasExports) {
14498
14612
  warn({
14499
14613
  code: 'MISSING_GLOBAL_NAME',
14500
- guess: module.variableName,
14501
- message: `No name was provided for external module '${module.id}' in output.globals – guessing '${module.variableName}'`,
14502
- source: module.id
14614
+ guess: chunk.variableName,
14615
+ message: `No name was provided for external module '${chunk.id}' in output.globals – guessing '${chunk.variableName}'`,
14616
+ source: chunk.id
14503
14617
  });
14504
- return module.variableName;
14618
+ return chunk.variableName;
14505
14619
  }
14506
14620
  }
14507
14621
  class Chunk {
14508
- constructor(orderedModules, inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, facadeChunkByModule, includedNamespaces, manualChunkAlias) {
14622
+ constructor(orderedModules, inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, externalChunkByModule, facadeChunkByModule, includedNamespaces, manualChunkAlias, getPlaceholder, bundle, inputBase, snippets) {
14509
14623
  this.orderedModules = orderedModules;
14510
14624
  this.inputOptions = inputOptions;
14511
14625
  this.outputOptions = outputOptions;
@@ -14513,19 +14627,22 @@ class Chunk {
14513
14627
  this.pluginDriver = pluginDriver;
14514
14628
  this.modulesById = modulesById;
14515
14629
  this.chunkByModule = chunkByModule;
14630
+ this.externalChunkByModule = externalChunkByModule;
14516
14631
  this.facadeChunkByModule = facadeChunkByModule;
14517
14632
  this.includedNamespaces = includedNamespaces;
14518
14633
  this.manualChunkAlias = manualChunkAlias;
14634
+ this.getPlaceholder = getPlaceholder;
14635
+ this.bundle = bundle;
14636
+ this.inputBase = inputBase;
14637
+ this.snippets = snippets;
14519
14638
  this.entryModules = [];
14520
14639
  this.exportMode = 'named';
14521
14640
  this.facadeModule = null;
14522
14641
  this.id = null;
14523
14642
  this.namespaceVariableName = '';
14524
- this.needsExportsShim = false;
14525
14643
  this.variableName = '';
14526
14644
  this.accessedGlobalsByScope = new Map();
14527
14645
  this.dependencies = new Set();
14528
- this.dynamicDependencies = new Set();
14529
14646
  this.dynamicEntryModules = [];
14530
14647
  this.dynamicName = null;
14531
14648
  this.exportNamesByVariable = new Map();
@@ -14535,23 +14652,23 @@ class Chunk {
14535
14652
  this.implicitEntryModules = [];
14536
14653
  this.implicitlyLoadedBefore = new Set();
14537
14654
  this.imports = new Set();
14655
+ this.includedDynamicImports = null;
14538
14656
  this.includedReexportsByModule = new Map();
14539
- this.indentString = undefined;
14540
- // This may only be updated in the constructor
14657
+ // This may be updated in the constructor
14541
14658
  this.isEmpty = true;
14542
14659
  this.name = null;
14660
+ this.needsExportsShim = false;
14661
+ this.preRenderedChunkInfo = null;
14662
+ this.preliminaryFileName = null;
14663
+ this.renderedChunkInfo = null;
14543
14664
  this.renderedDependencies = null;
14544
- this.renderedExports = null;
14545
- this.renderedHash = undefined;
14546
- this.renderedModuleSources = new Map();
14547
14665
  this.renderedModules = Object.create(null);
14548
- this.renderedSource = null;
14549
14666
  this.sortedExportNames = null;
14550
14667
  this.strictFacade = false;
14551
- this.usedModules = undefined;
14552
14668
  this.execIndex = orderedModules.length > 0 ? orderedModules[0].execIndex : Infinity;
14553
14669
  const chunkModules = new Set(orderedModules);
14554
14670
  for (const module of orderedModules) {
14671
+ chunkByModule.set(module, this);
14555
14672
  if (module.namespace.included) {
14556
14673
  includedNamespaces.add(module);
14557
14674
  }
@@ -14577,14 +14694,16 @@ class Chunk {
14577
14694
  }
14578
14695
  this.suggestedVariableName = makeLegal(this.generateVariableName());
14579
14696
  }
14580
- static generateFacade(inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, facadeChunkByModule, includedNamespaces, facadedModule, facadeName) {
14581
- const chunk = new Chunk([], inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, facadeChunkByModule, includedNamespaces, null);
14697
+ static generateFacade(inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, externalChunkByModule, facadeChunkByModule, includedNamespaces, facadedModule, facadeName, getPlaceholder, bundle, inputBase, snippets) {
14698
+ const chunk = new Chunk([], inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, externalChunkByModule, facadeChunkByModule, includedNamespaces, null, getPlaceholder, bundle, inputBase, snippets);
14582
14699
  chunk.assignFacadeName(facadeName, facadedModule);
14583
14700
  if (!facadeChunkByModule.has(facadedModule)) {
14584
14701
  facadeChunkByModule.set(facadedModule, chunk);
14585
14702
  }
14586
14703
  for (const dependency of facadedModule.getDependenciesToBeIncluded()) {
14587
- chunk.dependencies.add(dependency instanceof Module ? chunkByModule.get(dependency) : dependency);
14704
+ chunk.dependencies.add(dependency instanceof Module
14705
+ ? chunkByModule.get(dependency)
14706
+ : externalChunkByModule.get(dependency));
14588
14707
  }
14589
14708
  if (!chunk.dependencies.has(chunkByModule.get(facadedModule)) &&
14590
14709
  facadedModule.info.moduleSideEffects &&
@@ -14685,7 +14804,7 @@ class Chunk {
14685
14804
  }
14686
14805
  }
14687
14806
  for (const facadeName of requiredFacades) {
14688
- facades.push(Chunk.generateFacade(this.inputOptions, this.outputOptions, this.unsetOptions, this.pluginDriver, this.modulesById, this.chunkByModule, this.facadeChunkByModule, this.includedNamespaces, module, facadeName));
14807
+ facades.push(Chunk.generateFacade(this.inputOptions, this.outputOptions, this.unsetOptions, this.pluginDriver, this.modulesById, this.chunkByModule, this.externalChunkByModule, this.facadeChunkByModule, this.includedNamespaces, module, facadeName, this.getPlaceholder, this.bundle, this.inputBase, this.snippets));
14689
14808
  }
14690
14809
  }
14691
14810
  for (const module of this.dynamicEntryModules) {
@@ -14712,89 +14831,24 @@ class Chunk {
14712
14831
  }
14713
14832
  return facades;
14714
14833
  }
14715
- generateId(addons, options, existingNames, includeHash) {
14716
- if (this.fileName !== null) {
14717
- return this.fileName;
14718
- }
14719
- const [pattern, patternName] = this.facadeModule && this.facadeModule.isUserDefinedEntryPoint
14720
- ? [options.entryFileNames, 'output.entryFileNames']
14721
- : [options.chunkFileNames, 'output.chunkFileNames'];
14722
- return makeUnique(renderNamePattern(typeof pattern === 'function' ? pattern(this.getChunkInfo()) : pattern, patternName, {
14723
- format: () => options.format,
14724
- hash: () => includeHash
14725
- ? this.computeContentHashWithDependencies(addons, options, existingNames)
14726
- : '[hash]',
14727
- name: () => this.getChunkName()
14728
- }), existingNames);
14729
- }
14730
- generateIdPreserveModules(preserveModulesRelativeDir, options, existingNames, unsetOptions) {
14731
- const [{ id }] = this.orderedModules;
14732
- const sanitizedId = this.outputOptions.sanitizeFileName(id.split(QUERY_HASH_REGEX, 1)[0]);
14733
- let path;
14734
- const patternOpt = unsetOptions.has('entryFileNames')
14735
- ? '[name][assetExtname].js'
14736
- : options.entryFileNames;
14737
- const pattern = typeof patternOpt === 'function' ? patternOpt(this.getChunkInfo()) : patternOpt;
14738
- if (isAbsolute(sanitizedId)) {
14739
- const currentDir = require$$0.dirname(sanitizedId);
14740
- const extension = require$$0.extname(sanitizedId);
14741
- const fileName = renderNamePattern(pattern, 'output.entryFileNames', {
14742
- assetExtname: () => (NON_ASSET_EXTENSIONS.includes(extension) ? '' : extension),
14743
- ext: () => extension.substring(1),
14744
- extname: () => extension,
14745
- format: () => options.format,
14746
- name: () => this.getChunkName()
14747
- });
14748
- const currentPath = `${currentDir}/${fileName}`;
14749
- const { preserveModulesRoot } = options;
14750
- if (preserveModulesRoot && currentPath.startsWith(preserveModulesRoot)) {
14751
- path = currentPath.slice(preserveModulesRoot.length).replace(/^[\\/]/, '');
14752
- }
14753
- else {
14754
- path = relative(preserveModulesRelativeDir, currentPath);
14755
- }
14756
- }
14757
- else {
14758
- const extension = require$$0.extname(sanitizedId);
14759
- const fileName = renderNamePattern(pattern, 'output.entryFileNames', {
14760
- assetExtname: () => (NON_ASSET_EXTENSIONS.includes(extension) ? '' : extension),
14761
- ext: () => extension.substring(1),
14762
- extname: () => extension,
14763
- format: () => options.format,
14764
- name: () => getAliasName(sanitizedId)
14765
- });
14766
- path = `_virtual/${fileName}`;
14767
- }
14768
- return makeUnique(normalize(path), existingNames);
14769
- }
14770
- getChunkInfo() {
14771
- const facadeModule = this.facadeModule;
14772
- const getChunkName = this.getChunkName.bind(this);
14834
+ generateOutputChunk(code, map, hashesByPlaceholder) {
14835
+ const renderedChunkInfo = this.getRenderedChunkInfo();
14836
+ const finalize = (code) => replacePlaceholders(code, hashesByPlaceholder);
14773
14837
  return {
14774
- exports: this.getExportNames(),
14775
- facadeModuleId: facadeModule && facadeModule.id,
14776
- isDynamicEntry: this.dynamicEntryModules.length > 0,
14777
- isEntry: facadeModule !== null && facadeModule.info.isEntry,
14778
- isImplicitEntry: this.implicitEntryModules.length > 0,
14779
- modules: this.renderedModules,
14780
- get name() {
14781
- return getChunkName();
14782
- },
14783
- type: 'chunk'
14838
+ ...renderedChunkInfo,
14839
+ code,
14840
+ dynamicImports: renderedChunkInfo.dynamicImports.map(finalize),
14841
+ fileName: finalize(renderedChunkInfo.fileName),
14842
+ implicitlyLoadedBefore: renderedChunkInfo.implicitlyLoadedBefore.map(finalize),
14843
+ importedBindings: Object.fromEntries(Object.entries(renderedChunkInfo.importedBindings).map(([fileName, bindings]) => [
14844
+ finalize(fileName),
14845
+ bindings
14846
+ ])),
14847
+ imports: renderedChunkInfo.imports.map(finalize),
14848
+ map,
14849
+ referencedFiles: renderedChunkInfo.referencedFiles.map(finalize)
14784
14850
  };
14785
14851
  }
14786
- getChunkInfoWithFileNames() {
14787
- return Object.assign(this.getChunkInfo(), {
14788
- code: undefined,
14789
- dynamicImports: Array.from(this.dynamicDependencies, getId),
14790
- fileName: this.id,
14791
- implicitlyLoadedBefore: Array.from(this.implicitlyLoadedBefore, getId),
14792
- importedBindings: this.getImportedBindingsPerDependency(),
14793
- imports: Array.from(this.dependencies, getId),
14794
- map: undefined,
14795
- referencedFiles: this.getReferencedFiles()
14796
- });
14797
- }
14798
14852
  getChunkName() {
14799
14853
  var _a;
14800
14854
  return ((_a = this.name) !== null && _a !== void 0 ? _a : (this.name = this.outputOptions.sanitizeFileName(this.getFallbackChunkName())));
@@ -14803,25 +14857,63 @@ class Chunk {
14803
14857
  var _a;
14804
14858
  return ((_a = this.sortedExportNames) !== null && _a !== void 0 ? _a : (this.sortedExportNames = Array.from(this.exportsByName.keys()).sort()));
14805
14859
  }
14806
- getRenderedHash() {
14807
- if (this.renderedHash)
14808
- return this.renderedHash;
14809
- const hash = createHash();
14810
- const hashAugmentation = this.pluginDriver.hookReduceValueSync('augmentChunkHash', '', [this.getChunkInfo()], (augmentation, pluginHash) => {
14811
- if (pluginHash) {
14812
- augmentation += pluginHash;
14860
+ getFileName() {
14861
+ var _a;
14862
+ return ((_a = this.preliminaryFileName) === null || _a === void 0 ? void 0 : _a.fileName) || this.getPreliminaryFileName().fileName;
14863
+ }
14864
+ getImportPath(importer) {
14865
+ return escapeId(getImportPath(importer, this.getFileName(), this.outputOptions.format === 'amd', true));
14866
+ }
14867
+ getPreliminaryFileName() {
14868
+ if (this.preliminaryFileName) {
14869
+ return this.preliminaryFileName;
14870
+ }
14871
+ let fileName;
14872
+ let hashPlaceholder = null;
14873
+ const { chunkFileNames, entryFileNames, file, format, preserveModules } = this.outputOptions;
14874
+ if (file) {
14875
+ fileName = require$$0.basename(file);
14876
+ }
14877
+ else if (preserveModules) {
14878
+ fileName = this.generateIdPreserveModules();
14879
+ }
14880
+ else if (this.fileName !== null) {
14881
+ fileName = this.fileName;
14882
+ }
14883
+ else {
14884
+ const [pattern, patternName] = this.facadeModule && this.facadeModule.isUserDefinedEntryPoint
14885
+ ? [entryFileNames, 'output.entryFileNames']
14886
+ : [chunkFileNames, 'output.chunkFileNames'];
14887
+ fileName = renderNamePattern(typeof pattern === 'function' ? pattern(this.getPreRenderedChunkInfo()) : pattern, patternName, {
14888
+ format: () => format,
14889
+ hash: size => hashPlaceholder || (hashPlaceholder = this.getPlaceholder(patternName, size)),
14890
+ name: () => this.getChunkName()
14891
+ });
14892
+ if (!hashPlaceholder) {
14893
+ fileName = makeUnique(fileName, this.bundle);
14813
14894
  }
14814
- return augmentation;
14895
+ }
14896
+ if (!hashPlaceholder) {
14897
+ this.bundle[fileName] = FILE_PLACEHOLDER;
14898
+ }
14899
+ // Caching is essential to not conflict with the file name reservation above
14900
+ return (this.preliminaryFileName = { fileName, hashPlaceholder });
14901
+ }
14902
+ getRenderedChunkInfo() {
14903
+ if (this.renderedChunkInfo) {
14904
+ return this.renderedChunkInfo;
14905
+ }
14906
+ const resolveFileName = (dependency) => dependency.getFileName();
14907
+ return (this.renderedChunkInfo = {
14908
+ ...this.getPreRenderedChunkInfo(),
14909
+ dynamicImports: this.getDynamicDependencies().map(resolveFileName),
14910
+ fileName: this.getFileName(),
14911
+ implicitlyLoadedBefore: Array.from(this.implicitlyLoadedBefore, resolveFileName),
14912
+ importedBindings: getImportedBindingsPerDependency(this.getRenderedDependencies(), resolveFileName),
14913
+ imports: Array.from(this.dependencies, resolveFileName),
14914
+ modules: this.renderedModules,
14915
+ referencedFiles: this.getReferencedFiles()
14815
14916
  });
14816
- hash.update(hashAugmentation);
14817
- hash.update(this.renderedSource.toString());
14818
- hash.update(this.getExportNames()
14819
- .map(exportName => {
14820
- const variable = this.exportsByName.get(exportName);
14821
- return `${relativeId(variable.module.id).replace(/\\/g, '/')}:${variable.name}:${exportName}`;
14822
- })
14823
- .join(','));
14824
- return (this.renderedHash = hash.digest('hex'));
14825
14917
  }
14826
14918
  getVariableExportName(variable) {
14827
14919
  if (this.outputOptions.preserveModules && variable instanceof NamespaceVariable) {
@@ -14830,225 +14922,67 @@ class Chunk {
14830
14922
  return this.exportNamesByVariable.get(variable)[0];
14831
14923
  }
14832
14924
  link() {
14833
- this.dependencies = getStaticDependencies(this, this.orderedModules, this.chunkByModule);
14925
+ this.dependencies = getStaticDependencies(this, this.orderedModules, this.chunkByModule, this.externalChunkByModule);
14834
14926
  for (const module of this.orderedModules) {
14835
- this.addDependenciesToChunk(module.dynamicDependencies, this.dynamicDependencies);
14836
- this.addDependenciesToChunk(module.implicitlyLoadedBefore, this.implicitlyLoadedBefore);
14927
+ this.addImplicitlyLoadedBeforeFromModule(module);
14837
14928
  this.setUpChunkImportsAndExportsForModule(module);
14838
14929
  }
14839
14930
  }
14840
- // prerender allows chunk hashes and names to be generated before finalizing
14841
- preRender(options, inputBase, snippets) {
14842
- const { _, getPropertyAccess, n } = snippets;
14843
- const magicString = new Bundle$1({ separator: `${n}${n}` });
14844
- this.usedModules = [];
14845
- this.indentString = getIndentString(this.orderedModules, options);
14846
- const renderOptions = {
14847
- dynamicImportFunction: options.dynamicImportFunction,
14848
- exportNamesByVariable: this.exportNamesByVariable,
14849
- format: options.format,
14850
- freeze: options.freeze,
14851
- indent: this.indentString,
14852
- namespaceToStringTag: options.namespaceToStringTag,
14853
- outputPluginDriver: this.pluginDriver,
14854
- snippets
14855
- };
14856
- // for static and dynamic entry points, inline the execution list to avoid loading latency
14857
- if (options.hoistTransitiveImports &&
14858
- !this.outputOptions.preserveModules &&
14859
- this.facadeModule !== null) {
14860
- for (const dep of this.dependencies) {
14931
+ async render() {
14932
+ const { dependencies, exportMode, facadeModule, inputOptions: { onwarn }, outputOptions, pluginDriver, snippets } = this;
14933
+ const { format, hoistTransitiveImports, preserveModules } = outputOptions;
14934
+ // for static and dynamic entry points, add transitive dependencies to this
14935
+ // chunk's dependencies to avoid loading latency
14936
+ if (hoistTransitiveImports && !preserveModules && facadeModule !== null) {
14937
+ for (const dep of dependencies) {
14861
14938
  if (dep instanceof Chunk)
14862
14939
  this.inlineChunkDependencies(dep);
14863
14940
  }
14864
14941
  }
14865
- this.prepareModulesForRendering(snippets);
14866
- this.setIdentifierRenderResolutions(options);
14867
- let hoistedSource = '';
14868
- const renderedModules = this.renderedModules;
14869
- for (const module of this.orderedModules) {
14870
- let renderedLength = 0;
14871
- if (module.isIncluded() || this.includedNamespaces.has(module)) {
14872
- const source = module.render(renderOptions).trim();
14873
- renderedLength = source.length();
14874
- if (renderedLength) {
14875
- if (options.compact && source.lastLine().includes('//'))
14876
- source.append('\n');
14877
- this.renderedModuleSources.set(module, source);
14878
- magicString.addSource(source);
14879
- this.usedModules.push(module);
14880
- }
14881
- const namespace = module.namespace;
14882
- if (this.includedNamespaces.has(module) && !this.outputOptions.preserveModules) {
14883
- const rendered = namespace.renderBlock(renderOptions);
14884
- if (namespace.renderFirst())
14885
- hoistedSource += n + rendered;
14886
- else
14887
- magicString.addSource(new MagicString(rendered));
14888
- }
14889
- }
14890
- const { renderedExports, removedExports } = module.getRenderedExports();
14891
- const { renderedModuleSources } = this;
14892
- renderedModules[module.id] = {
14893
- get code() {
14894
- var _a, _b;
14895
- return (_b = (_a = renderedModuleSources.get(module)) === null || _a === void 0 ? void 0 : _a.toString()) !== null && _b !== void 0 ? _b : null;
14896
- },
14897
- originalLength: module.originalCode.length,
14898
- removedExports,
14899
- renderedExports,
14900
- renderedLength
14901
- };
14902
- }
14903
- if (hoistedSource)
14904
- magicString.prepend(hoistedSource + n + n);
14905
- if (this.needsExportsShim) {
14906
- magicString.prepend(`${n}${snippets.cnst} ${MISSING_EXPORT_SHIM_VARIABLE}${_}=${_}void 0;${n}${n}`);
14907
- }
14908
- if (options.compact) {
14909
- this.renderedSource = magicString;
14910
- }
14911
- else {
14912
- this.renderedSource = magicString.trim();
14913
- }
14914
- this.renderedHash = undefined;
14915
- if (this.isEmpty && this.getExportNames().length === 0 && this.dependencies.size === 0) {
14916
- const chunkName = this.getChunkName();
14917
- this.inputOptions.onwarn({
14918
- chunkName,
14919
- code: 'EMPTY_BUNDLE',
14920
- message: `Generated an empty chunk: "${chunkName}"`
14921
- });
14922
- }
14923
- this.setExternalRenderPaths(options, inputBase);
14924
- this.renderedDependencies = this.getChunkDependencyDeclarations(options, getPropertyAccess);
14925
- this.renderedExports =
14926
- this.exportMode === 'none'
14927
- ? []
14928
- : this.getChunkExportDeclarations(options.format, getPropertyAccess);
14929
- }
14930
- async render(options, addons, outputChunk, snippets) {
14942
+ const preliminaryFileName = this.getPreliminaryFileName();
14943
+ const { accessedGlobals, indent, magicString, renderedSource, usedModules, usesTopLevelAwait } = this.renderModules(preliminaryFileName.fileName);
14931
14944
  timeStart('render format', 2);
14932
- const format = options.format;
14933
- const finalise = finalisers[format];
14934
- if (options.dynamicImportFunction && format !== 'es') {
14935
- this.inputOptions.onwarn(errInvalidOption('output.dynamicImportFunction', 'outputdynamicImportFunction', 'this option is ignored for formats other than "es"'));
14936
- }
14937
- // populate ids in the rendered declarations only here
14938
- // as chunk ids known only after prerender
14939
- for (const dependency of this.dependencies) {
14940
- const renderedDependency = this.renderedDependencies.get(dependency);
14941
- if (dependency instanceof ExternalModule) {
14942
- const originalId = dependency.renderPath;
14943
- renderedDependency.id = escapeId(dependency.renormalizeRenderPath
14944
- ? getImportPath(this.id, originalId, false, false)
14945
- : originalId);
14946
- }
14947
- else {
14948
- renderedDependency.namedExportsMode = dependency.exportMode !== 'default';
14949
- renderedDependency.id = escapeId(getImportPath(this.id, dependency.id, false, true));
14950
- }
14951
- }
14952
- this.finaliseDynamicImports(options, snippets);
14953
- this.finaliseImportMetas(format, snippets);
14954
- const hasExports = this.renderedExports.length !== 0 ||
14955
- [...this.renderedDependencies.values()].some(dep => (dep.reexports && dep.reexports.length !== 0));
14956
- let topLevelAwaitModule = null;
14957
- const accessedGlobals = new Set();
14958
- for (const module of this.orderedModules) {
14959
- if (module.usesTopLevelAwait) {
14960
- topLevelAwaitModule = module.id;
14961
- }
14962
- const accessedGlobalVariables = this.accessedGlobalsByScope.get(module.scope);
14963
- if (accessedGlobalVariables) {
14964
- for (const name of accessedGlobalVariables) {
14965
- accessedGlobals.add(name);
14966
- }
14967
- }
14968
- }
14969
- if (topLevelAwaitModule !== null && format !== 'es' && format !== 'system') {
14970
- return error({
14971
- code: 'INVALID_TLA_FORMAT',
14972
- id: topLevelAwaitModule,
14973
- message: `Module format ${format} does not support top-level await. Use the "es" or "system" output formats rather.`
14974
- });
14975
- }
14976
- /* istanbul ignore next */
14977
- if (!this.id) {
14978
- throw new Error('Internal Error: expecting chunk id');
14979
- }
14980
- const magicString = finalise(this.renderedSource, {
14945
+ const renderedDependencies = [...this.getRenderedDependencies().values()];
14946
+ const renderedExports = exportMode === 'none' ? [] : this.getChunkExportDeclarations(format);
14947
+ const hasExports = renderedExports.length !== 0 ||
14948
+ renderedDependencies.some(dep => (dep.reexports && dep.reexports.length !== 0));
14949
+ // TODO Lukas Note: Mention in docs, that users/plugins are responsible to do their own caching
14950
+ // TODO Lukas adapt plugin hook graphs and order in docs
14951
+ const { intro, outro, banner, footer } = await createAddons(outputOptions, pluginDriver, this.getRenderedChunkInfo());
14952
+ finalisers[format](renderedSource, {
14981
14953
  accessedGlobals,
14982
- dependencies: [...this.renderedDependencies.values()],
14983
- exports: this.renderedExports,
14954
+ dependencies: renderedDependencies,
14955
+ exports: renderedExports,
14984
14956
  hasExports,
14985
- id: this.id,
14986
- indent: this.indentString,
14987
- intro: addons.intro,
14988
- isEntryFacade: this.outputOptions.preserveModules ||
14989
- (this.facadeModule !== null && this.facadeModule.info.isEntry),
14990
- isModuleFacade: this.facadeModule !== null,
14991
- namedExportsMode: this.exportMode !== 'default',
14992
- outro: addons.outro,
14957
+ id: preliminaryFileName.fileName,
14958
+ indent,
14959
+ intro,
14960
+ isEntryFacade: preserveModules || (facadeModule !== null && facadeModule.info.isEntry),
14961
+ isModuleFacade: facadeModule !== null,
14962
+ namedExportsMode: exportMode !== 'default',
14963
+ onwarn,
14964
+ outro,
14993
14965
  snippets,
14994
- usesTopLevelAwait: topLevelAwaitModule !== null,
14995
- warn: this.inputOptions.onwarn
14996
- }, options);
14997
- if (addons.banner)
14998
- magicString.prepend(addons.banner);
14999
- if (addons.footer)
15000
- magicString.append(addons.footer);
15001
- const prevCode = magicString.toString();
14966
+ usesTopLevelAwait
14967
+ }, outputOptions);
14968
+ if (banner)
14969
+ magicString.prepend(banner);
14970
+ if (footer)
14971
+ magicString.append(footer);
15002
14972
  timeEnd('render format', 2);
15003
- let map = null;
15004
- const chunkSourcemapChain = [];
15005
- let code = await renderChunk({
15006
- code: prevCode,
15007
- options,
15008
- outputPluginDriver: this.pluginDriver,
15009
- renderChunk: outputChunk,
15010
- sourcemapChain: chunkSourcemapChain
15011
- });
15012
- if (options.sourcemap) {
15013
- timeStart('sourcemap', 2);
15014
- let file;
15015
- if (options.file)
15016
- file = require$$0.resolve(options.sourcemapFile || options.file);
15017
- else if (options.dir)
15018
- file = require$$0.resolve(options.dir, this.id);
15019
- else
15020
- file = require$$0.resolve(this.id);
15021
- const decodedMap = magicString.generateDecodedMap({});
15022
- map = collapseSourcemaps(file, decodedMap, this.usedModules, chunkSourcemapChain, options.sourcemapExcludeSources, this.inputOptions.onwarn);
15023
- map.sources = map.sources
15024
- .map(sourcePath => {
15025
- const { sourcemapPathTransform } = options;
15026
- if (sourcemapPathTransform) {
15027
- const newSourcePath = sourcemapPathTransform(sourcePath, `${file}.map`);
15028
- if (typeof newSourcePath !== 'string') {
15029
- error(errFailedValidation(`sourcemapPathTransform function must return a string.`));
15030
- }
15031
- return newSourcePath;
15032
- }
15033
- return sourcePath;
15034
- })
15035
- .map(normalize);
15036
- timeEnd('sourcemap', 2);
15037
- }
15038
- if (!options.compact && code[code.length - 1] !== '\n')
15039
- code += '\n';
15040
- return { code, map };
14973
+ return {
14974
+ chunk: this,
14975
+ magicString,
14976
+ preliminaryFileName,
14977
+ usedModules
14978
+ };
15041
14979
  }
15042
- addDependenciesToChunk(moduleDependencies, chunkDependencies) {
15043
- for (const module of moduleDependencies) {
15044
- if (module instanceof Module) {
15045
- const chunk = this.chunkByModule.get(module);
15046
- if (chunk && chunk !== this) {
15047
- chunkDependencies.add(chunk);
15048
- }
15049
- }
15050
- else {
15051
- chunkDependencies.add(module);
14980
+ addImplicitlyLoadedBeforeFromModule(baseModule) {
14981
+ const { implicitlyLoadedBefore } = this;
14982
+ for (const module of baseModule.implicitlyLoadedBefore) {
14983
+ const chunk = this.chunkByModule.get(module);
14984
+ if (chunk && chunk !== this) {
14985
+ implicitlyLoadedBefore.add(chunk);
15052
14986
  }
15053
14987
  }
15054
14988
  }
@@ -15086,27 +15020,6 @@ class Chunk {
15086
15020
  } while (alternativeReexportModule);
15087
15021
  }
15088
15022
  }
15089
- computeContentHashWithDependencies(addons, options, existingNames) {
15090
- const hash = createHash();
15091
- hash.update([addons.intro, addons.outro, addons.banner, addons.footer].join(':'));
15092
- hash.update(options.format);
15093
- const dependenciesForHashing = new Set([this]);
15094
- for (const current of dependenciesForHashing) {
15095
- if (current instanceof ExternalModule) {
15096
- hash.update(`:${current.renderPath}`);
15097
- }
15098
- else {
15099
- hash.update(current.getRenderedHash());
15100
- hash.update(current.generateId(addons, options, existingNames, false));
15101
- }
15102
- if (current instanceof ExternalModule)
15103
- continue;
15104
- for (const dependency of [...current.dependencies, ...current.dynamicDependencies]) {
15105
- dependenciesForHashing.add(dependency);
15106
- }
15107
- }
15108
- return hash.digest('hex').substr(0, 8);
15109
- }
15110
15023
  ensureReexportsAreAvailableForModule(module) {
15111
15024
  const includedReexports = [];
15112
15025
  const map = module.getExportNamesByVariable();
@@ -15134,34 +15047,45 @@ class Chunk {
15134
15047
  this.includedReexportsByModule.set(module, includedReexports);
15135
15048
  }
15136
15049
  }
15137
- finaliseDynamicImports(options, snippets) {
15138
- const stripKnownJsExtensions = options.format === 'amd';
15139
- for (const [module, code] of this.renderedModuleSources) {
15140
- for (const { node, resolution } of module.dynamicImports) {
15141
- const chunk = this.chunkByModule.get(resolution);
15142
- const facadeChunk = this.facadeChunkByModule.get(resolution);
15143
- if (!resolution || !node.included || chunk === this) {
15144
- continue;
15145
- }
15146
- const renderedResolution = resolution instanceof Module
15147
- ? `'${escapeId(getImportPath(this.id, (facadeChunk || chunk).id, stripKnownJsExtensions, true))}'`
15148
- : resolution instanceof ExternalModule
15149
- ? `'${escapeId(resolution.renormalizeRenderPath
15150
- ? getImportPath(this.id, resolution.renderPath, stripKnownJsExtensions, false)
15151
- : resolution.renderPath)}'`
15152
- : resolution;
15153
- node.renderFinalResolution(code, renderedResolution, resolution instanceof Module &&
15154
- !(facadeChunk === null || facadeChunk === void 0 ? void 0 : facadeChunk.strictFacade) &&
15155
- chunk.exportNamesByVariable.get(resolution.namespace)[0], snippets);
15050
+ generateIdPreserveModules() {
15051
+ const [{ id }] = this.orderedModules;
15052
+ const { entryFileNames, format, preserveModulesRoot, sanitizeFileName } = this.outputOptions;
15053
+ const sanitizedId = sanitizeFileName(id.split(QUERY_HASH_REGEX, 1)[0]);
15054
+ let path;
15055
+ const patternOpt = this.unsetOptions.has('entryFileNames')
15056
+ ? '[name][assetExtname].js'
15057
+ : entryFileNames;
15058
+ const pattern = typeof patternOpt === 'function' ? patternOpt(this.getPreRenderedChunkInfo()) : patternOpt;
15059
+ if (isAbsolute(sanitizedId)) {
15060
+ const currentDir = require$$0.dirname(sanitizedId);
15061
+ const extension = require$$0.extname(sanitizedId);
15062
+ const fileName = renderNamePattern(pattern, 'output.entryFileNames', {
15063
+ assetExtname: () => (NON_ASSET_EXTENSIONS.includes(extension) ? '' : extension),
15064
+ ext: () => extension.substring(1),
15065
+ extname: () => extension,
15066
+ format: () => format,
15067
+ name: () => this.getChunkName()
15068
+ });
15069
+ const currentPath = `${currentDir}/${fileName}`;
15070
+ if (preserveModulesRoot && currentPath.startsWith(preserveModulesRoot)) {
15071
+ path = currentPath.slice(preserveModulesRoot.length).replace(/^[\\/]/, '');
15156
15072
  }
15157
- }
15158
- }
15159
- finaliseImportMetas(format, snippets) {
15160
- for (const [module, code] of this.renderedModuleSources) {
15161
- for (const importMeta of module.importMetas) {
15162
- importMeta.renderFinalMechanism(code, this.id, format, snippets, this.pluginDriver);
15073
+ else {
15074
+ path = relative(this.inputBase, currentPath);
15163
15075
  }
15164
15076
  }
15077
+ else {
15078
+ const extension = require$$0.extname(sanitizedId);
15079
+ const fileName = renderNamePattern(pattern, 'output.entryFileNames', {
15080
+ assetExtname: () => (NON_ASSET_EXTENSIONS.includes(extension) ? '' : extension),
15081
+ ext: () => extension.substring(1),
15082
+ extname: () => extension,
15083
+ format: () => format,
15084
+ name: () => getAliasName(sanitizedId)
15085
+ });
15086
+ path = `_virtual/${fileName}`;
15087
+ }
15088
+ return makeUnique(normalize(path), this.bundle);
15165
15089
  }
15166
15090
  generateVariableName() {
15167
15091
  if (this.manualChunkAlias) {
@@ -15176,31 +15100,7 @@ class Chunk {
15176
15100
  }
15177
15101
  return 'chunk';
15178
15102
  }
15179
- getChunkDependencyDeclarations(options, getPropertyAccess) {
15180
- const importSpecifiers = this.getImportSpecifiers(getPropertyAccess);
15181
- const reexportSpecifiers = this.getReexportSpecifiers();
15182
- const dependencyDeclaration = new Map();
15183
- for (const dep of this.dependencies) {
15184
- const imports = importSpecifiers.get(dep) || null;
15185
- const reexports = reexportSpecifiers.get(dep) || null;
15186
- const namedExportsMode = dep instanceof ExternalModule || dep.exportMode !== 'default';
15187
- dependencyDeclaration.set(dep, {
15188
- defaultVariableName: dep.defaultVariableName,
15189
- globalName: (dep instanceof ExternalModule &&
15190
- (options.format === 'umd' || options.format === 'iife') &&
15191
- getGlobalName(dep, options.globals, (imports || reexports) !== null, this.inputOptions.onwarn)),
15192
- id: undefined,
15193
- imports,
15194
- isChunk: dep instanceof Chunk,
15195
- name: dep.variableName,
15196
- namedExportsMode,
15197
- namespaceVariableName: dep.namespaceVariableName,
15198
- reexports
15199
- });
15200
- }
15201
- return dependencyDeclaration;
15202
- }
15203
- getChunkExportDeclarations(format, getPropertyAccess) {
15103
+ getChunkExportDeclarations(format) {
15204
15104
  const exports = [];
15205
15105
  for (const exportName of this.getExportNames()) {
15206
15106
  if (exportName[0] === '*')
@@ -15213,7 +15113,7 @@ class Chunk {
15213
15113
  }
15214
15114
  let expression = null;
15215
15115
  let hoisted = false;
15216
- let local = variable.getName(getPropertyAccess);
15116
+ let local = variable.getName(this.snippets.getPropertyAccess);
15217
15117
  if (variable instanceof LocalVariable) {
15218
15118
  for (const declaration of variable.declarations) {
15219
15119
  if (declaration.parent instanceof FunctionDeclaration ||
@@ -15247,16 +15147,17 @@ class Chunk {
15247
15147
  if (addNonNamespacesAndInteropHelpers || variable.isNamespace) {
15248
15148
  const module = variable.module;
15249
15149
  if (module instanceof ExternalModule) {
15250
- dependencies.add(module);
15150
+ const chunk = this.externalChunkByModule.get(module);
15151
+ dependencies.add(chunk);
15251
15152
  if (addNonNamespacesAndInteropHelpers) {
15252
15153
  if (variable.name === 'default') {
15253
15154
  if (defaultInteropHelpersByInteropType[String(interop(module.id))]) {
15254
- deconflictedDefault.add(module);
15155
+ deconflictedDefault.add(chunk);
15255
15156
  }
15256
15157
  }
15257
15158
  else if (variable.name === '*') {
15258
15159
  if (namespaceInteropHelpersByInteropType[String(interop(module.id))]) {
15259
- deconflictedNamespace.add(module);
15160
+ deconflictedNamespace.add(chunk);
15260
15161
  }
15261
15162
  }
15262
15163
  }
@@ -15281,6 +15182,15 @@ class Chunk {
15281
15182
  }
15282
15183
  return { deconflictedDefault, deconflictedNamespace, dependencies };
15283
15184
  }
15185
+ getDynamicDependencies() {
15186
+ return this.getIncludedDynamicImports()
15187
+ .map(resolvedDynamicImport => resolvedDynamicImport.facadeChunk ||
15188
+ resolvedDynamicImport.chunk ||
15189
+ resolvedDynamicImport.externalChunk ||
15190
+ resolvedDynamicImport.resolution)
15191
+ .filter((resolution) => resolution !== this &&
15192
+ (resolution instanceof Chunk || resolution instanceof ExternalChunk));
15193
+ }
15284
15194
  getFallbackChunkName() {
15285
15195
  if (this.manualChunkAlias) {
15286
15196
  return this.manualChunkAlias;
@@ -15293,7 +15203,7 @@ class Chunk {
15293
15203
  }
15294
15204
  return getAliasName(this.orderedModules[this.orderedModules.length - 1].id);
15295
15205
  }
15296
- getImportSpecifiers(getPropertyAccess) {
15206
+ getImportSpecifiers() {
15297
15207
  const { interop } = this.outputOptions;
15298
15208
  const importsByDependency = new Map();
15299
15209
  for (const variable of this.imports) {
@@ -15301,7 +15211,7 @@ class Chunk {
15301
15211
  let dependency;
15302
15212
  let imported;
15303
15213
  if (module instanceof ExternalModule) {
15304
- dependency = module;
15214
+ dependency = this.externalChunkByModule.get(module);
15305
15215
  imported = variable.name;
15306
15216
  if (imported !== 'default' && imported !== '*' && interop(module.id) === 'defaultOnly') {
15307
15217
  return error(errUnexpectedNamedImport(module.id, imported, false));
@@ -15313,30 +15223,59 @@ class Chunk {
15313
15223
  }
15314
15224
  getOrCreate(importsByDependency, dependency, () => []).push({
15315
15225
  imported,
15316
- local: variable.getName(getPropertyAccess)
15226
+ local: variable.getName(this.snippets.getPropertyAccess)
15317
15227
  });
15318
15228
  }
15319
15229
  return importsByDependency;
15320
15230
  }
15321
- getImportedBindingsPerDependency() {
15322
- const importSpecifiers = {};
15323
- for (const [dependency, declaration] of this.renderedDependencies) {
15324
- const specifiers = new Set();
15325
- if (declaration.imports) {
15326
- for (const { imported } of declaration.imports) {
15327
- specifiers.add(imported);
15328
- }
15329
- }
15330
- if (declaration.reexports) {
15331
- for (const { imported } of declaration.reexports) {
15332
- specifiers.add(imported);
15231
+ getIncludedDynamicImports() {
15232
+ if (this.includedDynamicImports) {
15233
+ return this.includedDynamicImports;
15234
+ }
15235
+ const includedDynamicImports = [];
15236
+ for (const module of this.orderedModules) {
15237
+ for (const { node, resolution } of module.dynamicImports) {
15238
+ if (!node.included) {
15239
+ continue;
15333
15240
  }
15241
+ includedDynamicImports.push(resolution instanceof Module
15242
+ ? {
15243
+ chunk: this.chunkByModule.get(resolution),
15244
+ externalChunk: null,
15245
+ facadeChunk: this.facadeChunkByModule.get(resolution),
15246
+ node,
15247
+ resolution
15248
+ }
15249
+ : resolution instanceof ExternalModule
15250
+ ? {
15251
+ chunk: null,
15252
+ externalChunk: this.externalChunkByModule.get(resolution),
15253
+ facadeChunk: null,
15254
+ node,
15255
+ resolution
15256
+ }
15257
+ : { chunk: null, externalChunk: null, facadeChunk: null, node, resolution });
15334
15258
  }
15335
- importSpecifiers[dependency.id] = [...specifiers];
15336
15259
  }
15337
- return importSpecifiers;
15260
+ return (this.includedDynamicImports = includedDynamicImports);
15338
15261
  }
15339
- getReexportSpecifiers() {
15262
+ getPreRenderedChunkInfo() {
15263
+ if (this.preRenderedChunkInfo) {
15264
+ return this.preRenderedChunkInfo;
15265
+ }
15266
+ const { facadeModule } = this;
15267
+ return (this.preRenderedChunkInfo = {
15268
+ exports: this.getExportNames(),
15269
+ facadeModuleId: facadeModule && facadeModule.id,
15270
+ isDynamicEntry: this.dynamicEntryModules.length > 0,
15271
+ isEntry: !!(facadeModule === null || facadeModule === void 0 ? void 0 : facadeModule.info.isEntry),
15272
+ isImplicitEntry: this.implicitEntryModules.length > 0,
15273
+ moduleIds: this.orderedModules.map(({ id }) => id),
15274
+ name: this.getChunkName(),
15275
+ type: 'chunk'
15276
+ });
15277
+ }
15278
+ getReexportSpecifiers() {
15340
15279
  const { externalLiveBindings, interop } = this.outputOptions;
15341
15280
  const reexportSpecifiers = new Map();
15342
15281
  for (let exportName of this.getExportNames()) {
@@ -15349,7 +15288,7 @@ class Chunk {
15349
15288
  this.inputOptions.onwarn(errUnexpectedNamespaceReexport(id));
15350
15289
  }
15351
15290
  needsLiveBinding = externalLiveBindings;
15352
- dependency = this.modulesById.get(id);
15291
+ dependency = this.externalChunkByModule.get(this.modulesById.get(id));
15353
15292
  imported = exportName = '*';
15354
15293
  }
15355
15294
  else {
@@ -15365,7 +15304,7 @@ class Chunk {
15365
15304
  needsLiveBinding = variable.isReassigned;
15366
15305
  }
15367
15306
  else {
15368
- dependency = module;
15307
+ dependency = this.externalChunkByModule.get(module);
15369
15308
  imported = variable.name;
15370
15309
  if (imported !== 'default' && imported !== '*' && interop(module.id) === 'defaultOnly') {
15371
15310
  return error(errUnexpectedNamedImport(module.id, imported, true));
@@ -15384,16 +15323,45 @@ class Chunk {
15384
15323
  return reexportSpecifiers;
15385
15324
  }
15386
15325
  getReferencedFiles() {
15387
- const referencedFiles = [];
15326
+ const referencedFiles = new Set();
15388
15327
  for (const module of this.orderedModules) {
15389
15328
  for (const meta of module.importMetas) {
15390
15329
  const fileName = meta.getReferencedFileName(this.pluginDriver);
15391
15330
  if (fileName) {
15392
- referencedFiles.push(fileName);
15331
+ referencedFiles.add(fileName);
15393
15332
  }
15394
15333
  }
15395
15334
  }
15396
- return referencedFiles;
15335
+ return [...referencedFiles];
15336
+ }
15337
+ getRenderedDependencies() {
15338
+ if (this.renderedDependencies) {
15339
+ return this.renderedDependencies;
15340
+ }
15341
+ const importSpecifiers = this.getImportSpecifiers();
15342
+ const reexportSpecifiers = this.getReexportSpecifiers();
15343
+ const renderedDependencies = new Map();
15344
+ const fileName = this.getFileName();
15345
+ for (const dep of this.dependencies) {
15346
+ const imports = importSpecifiers.get(dep) || null;
15347
+ const reexports = reexportSpecifiers.get(dep) || null;
15348
+ const namedExportsMode = dep instanceof ExternalChunk || dep.exportMode !== 'default';
15349
+ const importPath = dep.getImportPath(fileName);
15350
+ renderedDependencies.set(dep, {
15351
+ defaultVariableName: dep.defaultVariableName,
15352
+ globalName: dep instanceof ExternalChunk &&
15353
+ (this.outputOptions.format === 'umd' || this.outputOptions.format === 'iife') &&
15354
+ getGlobalName(dep, this.outputOptions.globals, (imports || reexports) !== null, this.inputOptions.onwarn),
15355
+ importPath,
15356
+ imports,
15357
+ isChunk: dep instanceof Chunk,
15358
+ name: dep.variableName,
15359
+ namedExportsMode,
15360
+ namespaceVariableName: dep.namespaceVariableName,
15361
+ reexports
15362
+ });
15363
+ }
15364
+ return (this.renderedDependencies = renderedDependencies);
15397
15365
  }
15398
15366
  inlineChunkDependencies(chunk) {
15399
15367
  for (const dep of chunk.dependencies) {
@@ -15405,42 +15373,111 @@ class Chunk {
15405
15373
  }
15406
15374
  }
15407
15375
  }
15408
- prepareModulesForRendering(snippets) {
15409
- var _a;
15410
- const accessedGlobalsByScope = this.accessedGlobalsByScope;
15411
- for (const module of this.orderedModules) {
15412
- for (const { node, resolution } of module.dynamicImports) {
15413
- if (node.included) {
15414
- if (resolution instanceof Module) {
15415
- const chunk = this.chunkByModule.get(resolution);
15416
- if (chunk === this) {
15417
- node.setInternalResolution(resolution.namespace);
15418
- }
15419
- else {
15420
- node.setExternalResolution(((_a = this.facadeChunkByModule.get(resolution)) === null || _a === void 0 ? void 0 : _a.exportMode) || chunk.exportMode, resolution, this.outputOptions, snippets, this.pluginDriver, accessedGlobalsByScope);
15421
- }
15422
- }
15423
- else {
15424
- node.setExternalResolution('external', resolution, this.outputOptions, snippets, this.pluginDriver, accessedGlobalsByScope);
15376
+ // This method changes properties on the AST before rendering and must not be async
15377
+ renderModules(fileName) {
15378
+ const { dependencies, exportNamesByVariable, includedNamespaces, inputOptions: { onwarn }, isEmpty, orderedModules, outputOptions, pluginDriver, renderedModules, snippets } = this;
15379
+ const { compact, dynamicImportFunction, format, freeze, namespaceToStringTag, preserveModules } = outputOptions;
15380
+ const { _, n } = snippets;
15381
+ this.setDynamicImportResolutions(fileName);
15382
+ this.setImportMetaResolutions(fileName);
15383
+ this.setIdentifierRenderResolutions();
15384
+ const magicString = new Bundle$1({ separator: `${n}${n}` });
15385
+ const indent = getIndentString(orderedModules, outputOptions);
15386
+ const usedModules = [];
15387
+ let hoistedSource = '';
15388
+ const accessedGlobals = new Set();
15389
+ const renderedModuleSources = new Map();
15390
+ const renderOptions = {
15391
+ dynamicImportFunction,
15392
+ exportNamesByVariable,
15393
+ format,
15394
+ freeze,
15395
+ indent,
15396
+ namespaceToStringTag,
15397
+ pluginDriver,
15398
+ snippets
15399
+ };
15400
+ let usesTopLevelAwait = false;
15401
+ for (const module of orderedModules) {
15402
+ let renderedLength = 0;
15403
+ let source;
15404
+ if (module.isIncluded() || includedNamespaces.has(module)) {
15405
+ const rendered = module.render(renderOptions);
15406
+ ({ source } = rendered);
15407
+ usesTopLevelAwait || (usesTopLevelAwait = rendered.usesTopLevelAwait);
15408
+ renderedLength = source.length();
15409
+ if (renderedLength) {
15410
+ if (compact && source.lastLine().includes('//'))
15411
+ source.append('\n');
15412
+ renderedModuleSources.set(module, source);
15413
+ magicString.addSource(source);
15414
+ usedModules.push(module);
15415
+ }
15416
+ const namespace = module.namespace;
15417
+ if (includedNamespaces.has(module) && !preserveModules) {
15418
+ const rendered = namespace.renderBlock(renderOptions);
15419
+ if (namespace.renderFirst())
15420
+ hoistedSource += n + rendered;
15421
+ else
15422
+ magicString.addSource(new MagicString(rendered));
15423
+ }
15424
+ const accessedGlobalVariables = this.accessedGlobalsByScope.get(module.scope);
15425
+ if (accessedGlobalVariables) {
15426
+ for (const name of accessedGlobalVariables) {
15427
+ accessedGlobals.add(name);
15425
15428
  }
15426
15429
  }
15427
15430
  }
15428
- for (const importMeta of module.importMetas) {
15429
- importMeta.addAccessedGlobals(this.outputOptions.format, accessedGlobalsByScope);
15430
- }
15431
- if (this.includedNamespaces.has(module) && !this.outputOptions.preserveModules) {
15432
- module.namespace.prepare(accessedGlobalsByScope);
15433
- }
15431
+ const { renderedExports, removedExports } = module.getRenderedExports();
15432
+ renderedModules[module.id] = {
15433
+ get code() {
15434
+ var _a;
15435
+ return (_a = source === null || source === void 0 ? void 0 : source.toString()) !== null && _a !== void 0 ? _a : null;
15436
+ },
15437
+ originalLength: module.originalCode.length,
15438
+ removedExports,
15439
+ renderedExports,
15440
+ renderedLength
15441
+ };
15442
+ }
15443
+ if (hoistedSource)
15444
+ magicString.prepend(hoistedSource + n + n);
15445
+ if (this.needsExportsShim) {
15446
+ magicString.prepend(`${n}${snippets.cnst} ${MISSING_EXPORT_SHIM_VARIABLE}${_}=${_}void 0;${n}${n}`);
15447
+ }
15448
+ const renderedSource = compact ? magicString : magicString.trim();
15449
+ if (isEmpty && this.getExportNames().length === 0 && dependencies.size === 0) {
15450
+ const chunkName = this.getChunkName();
15451
+ onwarn({
15452
+ chunkName,
15453
+ code: 'EMPTY_BUNDLE',
15454
+ message: `Generated an empty chunk: "${chunkName}"`
15455
+ });
15434
15456
  }
15457
+ return { accessedGlobals, indent, magicString, renderedSource, usedModules, usesTopLevelAwait };
15435
15458
  }
15436
- setExternalRenderPaths(options, inputBase) {
15437
- for (const dependency of [...this.dependencies, ...this.dynamicDependencies]) {
15438
- if (dependency instanceof ExternalModule) {
15439
- dependency.setRenderPath(options, inputBase);
15459
+ setDynamicImportResolutions(fileName) {
15460
+ const { accessedGlobalsByScope, outputOptions, pluginDriver, snippets } = this;
15461
+ for (const resolvedDynamicImport of this.getIncludedDynamicImports()) {
15462
+ if (resolvedDynamicImport.chunk) {
15463
+ const { chunk, facadeChunk, node, resolution } = resolvedDynamicImport;
15464
+ if (chunk === this) {
15465
+ node.setInternalResolution(resolution.namespace);
15466
+ }
15467
+ else {
15468
+ node.setExternalResolution((facadeChunk || chunk).exportMode, resolution, outputOptions, snippets, pluginDriver, accessedGlobalsByScope, `'${(facadeChunk || chunk).getImportPath(fileName)}'`, !(facadeChunk === null || facadeChunk === void 0 ? void 0 : facadeChunk.strictFacade) && chunk.exportNamesByVariable.get(resolution.namespace)[0]);
15469
+ }
15470
+ }
15471
+ else {
15472
+ const { resolution } = resolvedDynamicImport;
15473
+ resolvedDynamicImport.node.setExternalResolution('external', resolution, outputOptions, snippets, pluginDriver, accessedGlobalsByScope, resolution instanceof ExternalModule
15474
+ ? `'${this.externalChunkByModule.get(resolution).getImportPath(fileName)}'`
15475
+ : resolution || '', false);
15440
15476
  }
15441
15477
  }
15442
15478
  }
15443
- setIdentifierRenderResolutions({ format, interop, namespaceToStringTag }) {
15479
+ setIdentifierRenderResolutions() {
15480
+ const { format, interop, namespaceToStringTag } = this.outputOptions;
15444
15481
  const syntheticExports = new Set();
15445
15482
  for (const exportName of this.getExportNames()) {
15446
15483
  const exportVariable = this.exportsByName.get(exportName);
@@ -15485,7 +15522,18 @@ class Chunk {
15485
15522
  usedNames.add(helper);
15486
15523
  }
15487
15524
  }
15488
- deconflictChunk(this.orderedModules, this.getDependenciesToBeDeconflicted(format !== 'es' && format !== 'system', format === 'amd' || format === 'umd' || format === 'iife', interop), this.imports, usedNames, format, interop, this.outputOptions.preserveModules, this.outputOptions.externalLiveBindings, this.chunkByModule, syntheticExports, this.exportNamesByVariable, this.accessedGlobalsByScope, this.includedNamespaces);
15525
+ deconflictChunk(this.orderedModules, this.getDependenciesToBeDeconflicted(format !== 'es' && format !== 'system', format === 'amd' || format === 'umd' || format === 'iife', interop), this.imports, usedNames, format, interop, this.outputOptions.preserveModules, this.outputOptions.externalLiveBindings, this.chunkByModule, this.externalChunkByModule, syntheticExports, this.exportNamesByVariable, this.accessedGlobalsByScope, this.includedNamespaces);
15526
+ }
15527
+ setImportMetaResolutions(fileName) {
15528
+ const { accessedGlobalsByScope, includedNamespaces, outputOptions: { format, preserveModules } } = this;
15529
+ for (const module of this.orderedModules) {
15530
+ for (const importMeta of module.importMetas) {
15531
+ importMeta.setResolution(format, accessedGlobalsByScope, fileName);
15532
+ }
15533
+ if (includedNamespaces.has(module) && !preserveModules) {
15534
+ module.namespace.prepare(accessedGlobalsByScope);
15535
+ }
15536
+ }
15489
15537
  }
15490
15538
  setUpChunkImportsAndExportsForModule(module) {
15491
15539
  const moduleImports = new Set(module.includedImports);
@@ -15536,318 +15584,78 @@ function getChunkNameFromModule(module) {
15536
15584
  var _a, _b, _c, _d;
15537
15585
  return ((_d = (_b = (_a = module.chunkNames.find(({ isUserDefined }) => isUserDefined)) === null || _a === void 0 ? void 0 : _a.name) !== null && _b !== void 0 ? _b : (_c = module.chunkNames[0]) === null || _c === void 0 ? void 0 : _c.name) !== null && _d !== void 0 ? _d : getAliasName(module.id));
15538
15586
  }
15539
- const QUERY_HASH_REGEX = /[?#]/;
15540
-
15541
- function generateAssetFileName(name, source, outputOptions, bundle) {
15542
- const emittedName = outputOptions.sanitizeFileName(name || 'asset');
15543
- return makeUnique(renderNamePattern(typeof outputOptions.assetFileNames === 'function'
15544
- ? outputOptions.assetFileNames({ name, source, type: 'asset' })
15545
- : outputOptions.assetFileNames, 'output.assetFileNames', {
15546
- ext: () => require$$0.extname(emittedName).substring(1),
15547
- extname: () => require$$0.extname(emittedName),
15548
- hash() {
15549
- return createHash()
15550
- .update(emittedName)
15551
- .update(':')
15552
- .update(source)
15553
- .digest('hex')
15554
- .substring(0, 8);
15555
- },
15556
- name: () => emittedName.substring(0, emittedName.length - require$$0.extname(emittedName).length)
15557
- }), bundle);
15558
- }
15559
- function reserveFileNameInBundle(fileName, bundle, warn) {
15560
- if (fileName in bundle) {
15561
- warn(errFileNameConflict(fileName));
15587
+ function getImportedBindingsPerDependency(renderedDependencies, resolveFileName) {
15588
+ const importedBindingsPerDependency = {};
15589
+ for (const [dependency, declaration] of renderedDependencies) {
15590
+ const specifiers = new Set();
15591
+ if (declaration.imports) {
15592
+ for (const { imported } of declaration.imports) {
15593
+ specifiers.add(imported);
15594
+ }
15595
+ }
15596
+ if (declaration.reexports) {
15597
+ for (const { imported } of declaration.reexports) {
15598
+ specifiers.add(imported);
15599
+ }
15600
+ }
15601
+ importedBindingsPerDependency[resolveFileName(dependency)] = [...specifiers];
15562
15602
  }
15563
- bundle[fileName] = FILE_PLACEHOLDER;
15603
+ return importedBindingsPerDependency;
15564
15604
  }
15565
- const FILE_PLACEHOLDER = {
15566
- type: 'placeholder'
15567
- };
15568
- function hasValidType(emittedFile) {
15569
- return Boolean(emittedFile &&
15570
- (emittedFile.type === 'asset' ||
15571
- emittedFile.type === 'chunk'));
15572
- }
15573
- function hasValidName(emittedFile) {
15574
- const validatedName = emittedFile.fileName || emittedFile.name;
15575
- return !validatedName || (typeof validatedName === 'string' && !isPathFragment(validatedName));
15576
- }
15577
- function getValidSource(source, emittedFile, fileReferenceId) {
15578
- if (!(typeof source === 'string' || source instanceof Uint8Array)) {
15579
- const assetName = emittedFile.fileName || emittedFile.name || fileReferenceId;
15580
- return error(errFailedValidation(`Could not set source for ${typeof assetName === 'string' ? `asset "${assetName}"` : 'unnamed asset'}, asset source needs to be a string, Uint8Array or Buffer.`));
15605
+ const QUERY_HASH_REGEX = /[?#]/;
15606
+
15607
+ function getChunkAssignments(entryModules, manualChunkAliasByEntry) {
15608
+ const chunkDefinitions = [];
15609
+ const modulesInManualChunks = new Set(manualChunkAliasByEntry.keys());
15610
+ const manualChunkModulesByAlias = Object.create(null);
15611
+ for (const [entry, alias] of manualChunkAliasByEntry) {
15612
+ const chunkModules = (manualChunkModulesByAlias[alias] =
15613
+ manualChunkModulesByAlias[alias] || []);
15614
+ addStaticDependenciesToManualChunk(entry, chunkModules, modulesInManualChunks);
15581
15615
  }
15582
- return source;
15583
- }
15584
- function getAssetFileName(file, referenceId) {
15585
- if (typeof file.fileName !== 'string') {
15586
- return error(errAssetNotFinalisedForFileName(file.name || referenceId));
15616
+ for (const [alias, modules] of Object.entries(manualChunkModulesByAlias)) {
15617
+ chunkDefinitions.push({ alias, modules });
15587
15618
  }
15588
- return file.fileName;
15589
- }
15590
- function getChunkFileName(file, facadeChunkByModule) {
15591
- var _a;
15592
- const fileName = file.fileName || (file.module && ((_a = facadeChunkByModule === null || facadeChunkByModule === void 0 ? void 0 : facadeChunkByModule.get(file.module)) === null || _a === void 0 ? void 0 : _a.id));
15593
- if (!fileName)
15594
- return error(errChunkNotGeneratedForFileName(file.fileName || file.name));
15595
- return fileName;
15596
- }
15597
- class FileEmitter {
15598
- constructor(graph, options, baseFileEmitter) {
15599
- this.graph = graph;
15600
- this.options = options;
15601
- this.bundle = null;
15602
- this.facadeChunkByModule = null;
15603
- this.outputOptions = null;
15604
- this.assertAssetsFinalized = () => {
15605
- for (const [referenceId, emittedFile] of this.filesByReferenceId) {
15606
- if (emittedFile.type === 'asset' && typeof emittedFile.fileName !== 'string')
15607
- return error(errNoAssetSourceSet(emittedFile.name || referenceId));
15608
- }
15609
- };
15610
- this.emitFile = (emittedFile) => {
15611
- if (!hasValidType(emittedFile)) {
15612
- return error(errFailedValidation(`Emitted files must be of type "asset" or "chunk", received "${emittedFile && emittedFile.type}".`));
15613
- }
15614
- if (!hasValidName(emittedFile)) {
15615
- return error(errFailedValidation(`The "fileName" or "name" properties of emitted files must be strings that are neither absolute nor relative paths, received "${emittedFile.fileName || emittedFile.name}".`));
15616
- }
15617
- if (emittedFile.type === 'chunk') {
15618
- return this.emitChunk(emittedFile);
15619
- }
15620
- return this.emitAsset(emittedFile);
15621
- };
15622
- this.getFileName = (fileReferenceId) => {
15623
- const emittedFile = this.filesByReferenceId.get(fileReferenceId);
15624
- if (!emittedFile)
15625
- return error(errFileReferenceIdNotFoundForFilename(fileReferenceId));
15626
- if (emittedFile.type === 'chunk') {
15627
- return getChunkFileName(emittedFile, this.facadeChunkByModule);
15628
- }
15629
- return getAssetFileName(emittedFile, fileReferenceId);
15630
- };
15631
- this.setAssetSource = (referenceId, requestedSource) => {
15632
- const consumedFile = this.filesByReferenceId.get(referenceId);
15633
- if (!consumedFile)
15634
- return error(errAssetReferenceIdNotFoundForSetSource(referenceId));
15635
- if (consumedFile.type !== 'asset') {
15636
- return error(errFailedValidation(`Asset sources can only be set for emitted assets but "${referenceId}" is an emitted chunk.`));
15637
- }
15638
- if (consumedFile.source !== undefined) {
15639
- return error(errAssetSourceAlreadySet(consumedFile.name || referenceId));
15640
- }
15641
- const source = getValidSource(requestedSource, consumedFile, referenceId);
15642
- if (this.bundle) {
15643
- this.finalizeAsset(consumedFile, source, referenceId, this.bundle);
15619
+ const assignedEntryPointsByModule = new Map();
15620
+ const { dependentEntryPointsByModule, dynamicEntryModules } = analyzeModuleGraph(entryModules);
15621
+ const dynamicallyDependentEntryPointsByDynamicEntry = getDynamicDependentEntryPoints(dependentEntryPointsByModule, dynamicEntryModules);
15622
+ const staticEntries = new Set(entryModules);
15623
+ function assignEntryToStaticDependencies(entry, dynamicDependentEntryPoints) {
15624
+ const modulesToHandle = new Set([entry]);
15625
+ for (const module of modulesToHandle) {
15626
+ const assignedEntryPoints = getOrCreate(assignedEntryPointsByModule, module, () => new Set());
15627
+ if (dynamicDependentEntryPoints &&
15628
+ areEntryPointsContainedOrDynamicallyDependent(dynamicDependentEntryPoints, dependentEntryPointsByModule.get(module))) {
15629
+ continue;
15644
15630
  }
15645
15631
  else {
15646
- consumedFile.source = source;
15632
+ assignedEntryPoints.add(entry);
15647
15633
  }
15648
- };
15649
- this.setOutputBundle = (outputBundle, outputOptions, facadeChunkByModule) => {
15650
- this.outputOptions = outputOptions;
15651
- this.bundle = outputBundle;
15652
- this.facadeChunkByModule = facadeChunkByModule;
15653
- for (const emittedFile of this.filesByReferenceId.values()) {
15654
- if (emittedFile.fileName) {
15655
- reserveFileNameInBundle(emittedFile.fileName, this.bundle, this.options.onwarn);
15634
+ for (const dependency of module.getDependenciesToBeIncluded()) {
15635
+ if (!(dependency instanceof ExternalModule || modulesInManualChunks.has(dependency))) {
15636
+ modulesToHandle.add(dependency);
15656
15637
  }
15657
15638
  }
15658
- for (const [referenceId, consumedFile] of this.filesByReferenceId) {
15659
- if (consumedFile.type === 'asset' && consumedFile.source !== undefined) {
15660
- this.finalizeAsset(consumedFile, consumedFile.source, referenceId, this.bundle);
15639
+ }
15640
+ }
15641
+ function areEntryPointsContainedOrDynamicallyDependent(entryPoints, containedIn) {
15642
+ const entriesToCheck = new Set(entryPoints);
15643
+ for (const entry of entriesToCheck) {
15644
+ if (!containedIn.has(entry)) {
15645
+ if (staticEntries.has(entry))
15646
+ return false;
15647
+ const dynamicallyDependentEntryPoints = dynamicallyDependentEntryPointsByDynamicEntry.get(entry);
15648
+ for (const dependentEntry of dynamicallyDependentEntryPoints) {
15649
+ entriesToCheck.add(dependentEntry);
15661
15650
  }
15662
15651
  }
15663
- };
15664
- this.filesByReferenceId = baseFileEmitter
15665
- ? new Map(baseFileEmitter.filesByReferenceId)
15666
- : new Map();
15652
+ }
15653
+ return true;
15667
15654
  }
15668
- assignReferenceId(file, idBase) {
15669
- let referenceId;
15670
- do {
15671
- referenceId = createHash()
15672
- .update(referenceId || idBase)
15673
- .digest('hex')
15674
- .substring(0, 8);
15675
- } while (this.filesByReferenceId.has(referenceId));
15676
- this.filesByReferenceId.set(referenceId, file);
15677
- return referenceId;
15678
- }
15679
- emitAsset(emittedAsset) {
15680
- const source = typeof emittedAsset.source !== 'undefined'
15681
- ? getValidSource(emittedAsset.source, emittedAsset, null)
15682
- : undefined;
15683
- const consumedAsset = {
15684
- fileName: emittedAsset.fileName,
15685
- name: emittedAsset.name,
15686
- source,
15687
- type: 'asset'
15688
- };
15689
- const referenceId = this.assignReferenceId(consumedAsset, emittedAsset.fileName || emittedAsset.name || emittedAsset.type);
15690
- if (this.bundle) {
15691
- if (emittedAsset.fileName) {
15692
- reserveFileNameInBundle(emittedAsset.fileName, this.bundle, this.options.onwarn);
15693
- }
15694
- if (source !== undefined) {
15695
- this.finalizeAsset(consumedAsset, source, referenceId, this.bundle);
15696
- }
15697
- }
15698
- return referenceId;
15699
- }
15700
- emitChunk(emittedChunk) {
15701
- if (this.graph.phase > BuildPhase.LOAD_AND_PARSE) {
15702
- return error(errInvalidRollupPhaseForChunkEmission());
15703
- }
15704
- if (typeof emittedChunk.id !== 'string') {
15705
- return error(errFailedValidation(`Emitted chunks need to have a valid string id, received "${emittedChunk.id}"`));
15706
- }
15707
- const consumedChunk = {
15708
- fileName: emittedChunk.fileName,
15709
- module: null,
15710
- name: emittedChunk.name || emittedChunk.id,
15711
- type: 'chunk'
15712
- };
15713
- this.graph.moduleLoader
15714
- .emitChunk(emittedChunk)
15715
- .then(module => (consumedChunk.module = module))
15716
- .catch(() => {
15717
- // Avoid unhandled Promise rejection as the error will be thrown later
15718
- // once module loading has finished
15719
- });
15720
- return this.assignReferenceId(consumedChunk, emittedChunk.id);
15721
- }
15722
- finalizeAsset(consumedFile, source, referenceId, bundle) {
15723
- const fileName = consumedFile.fileName ||
15724
- findExistingAssetFileNameWithSource(bundle, source) ||
15725
- generateAssetFileName(consumedFile.name, source, this.outputOptions, bundle);
15726
- // We must not modify the original assets to avoid interaction between outputs
15727
- const assetWithFileName = { ...consumedFile, fileName, source };
15728
- this.filesByReferenceId.set(referenceId, assetWithFileName);
15729
- const { options } = this;
15730
- bundle[fileName] = {
15731
- fileName,
15732
- get isAsset() {
15733
- warnDeprecation('Accessing "isAsset" on files in the bundle is deprecated, please use "type === \'asset\'" instead', true, options);
15734
- return true;
15735
- },
15736
- name: consumedFile.name,
15737
- source,
15738
- type: 'asset'
15739
- };
15740
- }
15741
- }
15742
- function findExistingAssetFileNameWithSource(bundle, source) {
15743
- for (const [fileName, outputFile] of Object.entries(bundle)) {
15744
- if (outputFile.type === 'asset' && areSourcesEqual(source, outputFile.source))
15745
- return fileName;
15746
- }
15747
- return null;
15748
- }
15749
- function areSourcesEqual(sourceA, sourceB) {
15750
- if (typeof sourceA === 'string') {
15751
- return sourceA === sourceB;
15752
- }
15753
- if (typeof sourceB === 'string') {
15754
- return false;
15755
- }
15756
- if ('equals' in sourceA) {
15757
- return sourceA.equals(sourceB);
15758
- }
15759
- if (sourceA.length !== sourceB.length) {
15760
- return false;
15761
- }
15762
- for (let index = 0; index < sourceA.length; index++) {
15763
- if (sourceA[index] !== sourceB[index]) {
15764
- return false;
15765
- }
15766
- }
15767
- return true;
15768
- }
15769
-
15770
- const concatSep = (out, next) => (next ? `${out}\n${next}` : out);
15771
- const concatDblSep = (out, next) => (next ? `${out}\n\n${next}` : out);
15772
- async function createAddons(options, outputPluginDriver) {
15773
- try {
15774
- let [banner, footer, intro, outro] = await Promise.all([
15775
- outputPluginDriver.hookReduceValue('banner', options.banner(), [], concatSep),
15776
- outputPluginDriver.hookReduceValue('footer', options.footer(), [], concatSep),
15777
- outputPluginDriver.hookReduceValue('intro', options.intro(), [], concatDblSep),
15778
- outputPluginDriver.hookReduceValue('outro', options.outro(), [], concatDblSep)
15779
- ]);
15780
- if (intro)
15781
- intro += '\n\n';
15782
- if (outro)
15783
- outro = `\n\n${outro}`;
15784
- if (banner.length)
15785
- banner += '\n';
15786
- if (footer.length)
15787
- footer = '\n' + footer;
15788
- return { banner, footer, intro, outro };
15789
- }
15790
- catch (err) {
15791
- return error({
15792
- code: 'ADDON_ERROR',
15793
- message: `Could not retrieve ${err.hook}. Check configuration of plugin ${err.plugin}.
15794
- \tError Message: ${err.message}`
15795
- });
15796
- }
15797
- }
15798
-
15799
- function getChunkAssignments(entryModules, manualChunkAliasByEntry) {
15800
- const chunkDefinitions = [];
15801
- const modulesInManualChunks = new Set(manualChunkAliasByEntry.keys());
15802
- const manualChunkModulesByAlias = Object.create(null);
15803
- for (const [entry, alias] of manualChunkAliasByEntry) {
15804
- const chunkModules = (manualChunkModulesByAlias[alias] =
15805
- manualChunkModulesByAlias[alias] || []);
15806
- addStaticDependenciesToManualChunk(entry, chunkModules, modulesInManualChunks);
15807
- }
15808
- for (const [alias, modules] of Object.entries(manualChunkModulesByAlias)) {
15809
- chunkDefinitions.push({ alias, modules });
15810
- }
15811
- const assignedEntryPointsByModule = new Map();
15812
- const { dependentEntryPointsByModule, dynamicEntryModules } = analyzeModuleGraph(entryModules);
15813
- const dynamicallyDependentEntryPointsByDynamicEntry = getDynamicDependentEntryPoints(dependentEntryPointsByModule, dynamicEntryModules);
15814
- const staticEntries = new Set(entryModules);
15815
- function assignEntryToStaticDependencies(entry, dynamicDependentEntryPoints) {
15816
- const modulesToHandle = new Set([entry]);
15817
- for (const module of modulesToHandle) {
15818
- const assignedEntryPoints = getOrCreate(assignedEntryPointsByModule, module, () => new Set());
15819
- if (dynamicDependentEntryPoints &&
15820
- areEntryPointsContainedOrDynamicallyDependent(dynamicDependentEntryPoints, dependentEntryPointsByModule.get(module))) {
15821
- continue;
15822
- }
15823
- else {
15824
- assignedEntryPoints.add(entry);
15825
- }
15826
- for (const dependency of module.getDependenciesToBeIncluded()) {
15827
- if (!(dependency instanceof ExternalModule || modulesInManualChunks.has(dependency))) {
15828
- modulesToHandle.add(dependency);
15829
- }
15830
- }
15831
- }
15832
- }
15833
- function areEntryPointsContainedOrDynamicallyDependent(entryPoints, containedIn) {
15834
- const entriesToCheck = new Set(entryPoints);
15835
- for (const entry of entriesToCheck) {
15836
- if (!containedIn.has(entry)) {
15837
- if (staticEntries.has(entry))
15838
- return false;
15839
- const dynamicallyDependentEntryPoints = dynamicallyDependentEntryPointsByDynamicEntry.get(entry);
15840
- for (const dependentEntry of dynamicallyDependentEntryPoints) {
15841
- entriesToCheck.add(dependentEntry);
15842
- }
15843
- }
15844
- }
15845
- return true;
15846
- }
15847
- for (const entry of entryModules) {
15848
- if (!modulesInManualChunks.has(entry)) {
15849
- assignEntryToStaticDependencies(entry, null);
15850
- }
15655
+ for (const entry of entryModules) {
15656
+ if (!modulesInManualChunks.has(entry)) {
15657
+ assignEntryToStaticDependencies(entry, null);
15658
+ }
15851
15659
  }
15852
15660
  for (const entry of dynamicEntryModules) {
15853
15661
  if (!modulesInManualChunks.has(entry)) {
@@ -15894,188 +15702,528 @@ function analyzeModuleGraph(entryModules) {
15894
15702
  }
15895
15703
  }
15896
15704
  }
15897
- return { dependentEntryPointsByModule, dynamicEntryModules };
15705
+ return { dependentEntryPointsByModule, dynamicEntryModules };
15706
+ }
15707
+ function getDynamicDependentEntryPoints(dependentEntryPointsByModule, dynamicEntryModules) {
15708
+ const dynamicallyDependentEntryPointsByDynamicEntry = new Map();
15709
+ for (const dynamicEntry of dynamicEntryModules) {
15710
+ const dynamicDependentEntryPoints = getOrCreate(dynamicallyDependentEntryPointsByDynamicEntry, dynamicEntry, () => new Set());
15711
+ for (const importer of [
15712
+ ...dynamicEntry.includedDynamicImporters,
15713
+ ...dynamicEntry.implicitlyLoadedAfter
15714
+ ]) {
15715
+ for (const entryPoint of dependentEntryPointsByModule.get(importer)) {
15716
+ dynamicDependentEntryPoints.add(entryPoint);
15717
+ }
15718
+ }
15719
+ }
15720
+ return dynamicallyDependentEntryPointsByDynamicEntry;
15721
+ }
15722
+ function createChunks(allEntryPoints, assignedEntryPointsByModule) {
15723
+ const chunkModules = Object.create(null);
15724
+ for (const [module, assignedEntryPoints] of assignedEntryPointsByModule) {
15725
+ let chunkSignature = '';
15726
+ for (const entry of allEntryPoints) {
15727
+ chunkSignature += assignedEntryPoints.has(entry) ? 'X' : '_';
15728
+ }
15729
+ const chunk = chunkModules[chunkSignature];
15730
+ if (chunk) {
15731
+ chunk.push(module);
15732
+ }
15733
+ else {
15734
+ chunkModules[chunkSignature] = [module];
15735
+ }
15736
+ }
15737
+ return Object.values(chunkModules).map(modules => ({
15738
+ alias: null,
15739
+ modules
15740
+ }));
15741
+ }
15742
+
15743
+ // ported from https://github.com/substack/node-commondir
15744
+ function commondir(files) {
15745
+ if (files.length === 0)
15746
+ return '/';
15747
+ if (files.length === 1)
15748
+ return require$$0.dirname(files[0]);
15749
+ const commonSegments = files.slice(1).reduce((commonSegments, file) => {
15750
+ const pathSegements = file.split(/\/+|\\+/);
15751
+ let i;
15752
+ for (i = 0; commonSegments[i] === pathSegements[i] &&
15753
+ i < Math.min(commonSegments.length, pathSegements.length); i++)
15754
+ ;
15755
+ return commonSegments.slice(0, i);
15756
+ }, files[0].split(/\/+|\\+/));
15757
+ // Windows correctly handles paths with forward-slashes
15758
+ return commonSegments.length > 1 ? commonSegments.join('/') : '/';
15759
+ }
15760
+
15761
+ const compareExecIndex = (unitA, unitB) => unitA.execIndex > unitB.execIndex ? 1 : -1;
15762
+ function sortByExecutionOrder(units) {
15763
+ units.sort(compareExecIndex);
15764
+ }
15765
+ function analyseModuleExecution(entryModules) {
15766
+ let nextExecIndex = 0;
15767
+ const cyclePaths = [];
15768
+ const analysedModules = new Set();
15769
+ const dynamicImports = new Set();
15770
+ const parents = new Map();
15771
+ const orderedModules = [];
15772
+ const analyseModule = (module) => {
15773
+ if (module instanceof Module) {
15774
+ for (const dependency of module.dependencies) {
15775
+ if (parents.has(dependency)) {
15776
+ if (!analysedModules.has(dependency)) {
15777
+ cyclePaths.push(getCyclePath(dependency, module, parents));
15778
+ }
15779
+ continue;
15780
+ }
15781
+ parents.set(dependency, module);
15782
+ analyseModule(dependency);
15783
+ }
15784
+ for (const dependency of module.implicitlyLoadedBefore) {
15785
+ dynamicImports.add(dependency);
15786
+ }
15787
+ for (const { resolution } of module.dynamicImports) {
15788
+ if (resolution instanceof Module) {
15789
+ dynamicImports.add(resolution);
15790
+ }
15791
+ }
15792
+ orderedModules.push(module);
15793
+ }
15794
+ module.execIndex = nextExecIndex++;
15795
+ analysedModules.add(module);
15796
+ };
15797
+ for (const curEntry of entryModules) {
15798
+ if (!parents.has(curEntry)) {
15799
+ parents.set(curEntry, null);
15800
+ analyseModule(curEntry);
15801
+ }
15802
+ }
15803
+ for (const curEntry of dynamicImports) {
15804
+ if (!parents.has(curEntry)) {
15805
+ parents.set(curEntry, null);
15806
+ analyseModule(curEntry);
15807
+ }
15808
+ }
15809
+ return { cyclePaths, orderedModules };
15810
+ }
15811
+ function getCyclePath(module, parent, parents) {
15812
+ const cycleSymbol = Symbol(module.id);
15813
+ const path = [relativeId(module.id)];
15814
+ let nextModule = parent;
15815
+ module.cycles.add(cycleSymbol);
15816
+ while (nextModule !== module) {
15817
+ nextModule.cycles.add(cycleSymbol);
15818
+ path.push(relativeId(nextModule.id));
15819
+ nextModule = parents.get(nextModule);
15820
+ }
15821
+ path.push(path[0]);
15822
+ path.reverse();
15823
+ return path;
15824
+ }
15825
+
15826
+ function getGenerateCodeSnippets({ compact, generatedCode: { arrowFunctions, constBindings, objectShorthand, reservedNamesAsProps } }) {
15827
+ const { _, n, s } = compact ? { _: '', n: '', s: '' } : { _: ' ', n: '\n', s: ';' };
15828
+ const cnst = constBindings ? 'const' : 'var';
15829
+ const getNonArrowFunctionIntro = (params, { isAsync, name }) => `${isAsync ? `async ` : ''}function${name ? ` ${name}` : ''}${_}(${params.join(`,${_}`)})${_}`;
15830
+ const getFunctionIntro = arrowFunctions
15831
+ ? (params, { isAsync, name }) => {
15832
+ const singleParam = params.length === 1;
15833
+ const asyncString = isAsync ? `async${singleParam ? ' ' : _}` : '';
15834
+ return `${name ? `${cnst} ${name}${_}=${_}` : ''}${asyncString}${singleParam ? params[0] : `(${params.join(`,${_}`)})`}${_}=>${_}`;
15835
+ }
15836
+ : getNonArrowFunctionIntro;
15837
+ const getDirectReturnFunction = (params, { functionReturn, lineBreakIndent, name }) => [
15838
+ `${getFunctionIntro(params, {
15839
+ isAsync: false,
15840
+ name
15841
+ })}${arrowFunctions
15842
+ ? lineBreakIndent
15843
+ ? `${n}${lineBreakIndent.base}${lineBreakIndent.t}`
15844
+ : ''
15845
+ : `{${lineBreakIndent ? `${n}${lineBreakIndent.base}${lineBreakIndent.t}` : _}${functionReturn ? 'return ' : ''}`}`,
15846
+ arrowFunctions
15847
+ ? `${name ? ';' : ''}${lineBreakIndent ? `${n}${lineBreakIndent.base}` : ''}`
15848
+ : `${s}${lineBreakIndent ? `${n}${lineBreakIndent.base}` : _}}`
15849
+ ];
15850
+ const isValidPropName = reservedNamesAsProps
15851
+ ? (name) => validPropName.test(name)
15852
+ : (name) => !RESERVED_NAMES$1.has(name) && validPropName.test(name);
15853
+ return {
15854
+ _,
15855
+ cnst,
15856
+ getDirectReturnFunction,
15857
+ getDirectReturnIifeLeft: (params, returned, { needsArrowReturnParens, needsWrappedFunction }) => {
15858
+ const [left, right] = getDirectReturnFunction(params, {
15859
+ functionReturn: true,
15860
+ lineBreakIndent: null,
15861
+ name: null
15862
+ });
15863
+ return `${wrapIfNeeded(`${left}${wrapIfNeeded(returned, arrowFunctions && needsArrowReturnParens)}${right}`, arrowFunctions || needsWrappedFunction)}(`;
15864
+ },
15865
+ getFunctionIntro,
15866
+ getNonArrowFunctionIntro,
15867
+ getObject(fields, { lineBreakIndent }) {
15868
+ const prefix = lineBreakIndent ? `${n}${lineBreakIndent.base}${lineBreakIndent.t}` : _;
15869
+ return `{${fields
15870
+ .map(([key, value]) => {
15871
+ if (key === null)
15872
+ return `${prefix}${value}`;
15873
+ const needsQuotes = !isValidPropName(key);
15874
+ return key === value && objectShorthand && !needsQuotes
15875
+ ? prefix + key
15876
+ : `${prefix}${needsQuotes ? `'${key}'` : key}:${_}${value}`;
15877
+ })
15878
+ .join(`,`)}${fields.length === 0 ? '' : lineBreakIndent ? `${n}${lineBreakIndent.base}` : _}}`;
15879
+ },
15880
+ getPropertyAccess: (name) => isValidPropName(name) ? `.${name}` : `[${JSON.stringify(name)}]`,
15881
+ n,
15882
+ s
15883
+ };
15884
+ }
15885
+ const wrapIfNeeded = (code, needsParens) => needsParens ? `(${code})` : code;
15886
+ const validPropName = /^(?!\d)[\w$]+$/;
15887
+
15888
+ class Source {
15889
+ constructor(filename, content) {
15890
+ this.isOriginal = true;
15891
+ this.filename = filename;
15892
+ this.content = content;
15893
+ }
15894
+ traceSegment(line, column, name) {
15895
+ return { column, line, name, source: this };
15896
+ }
15897
+ }
15898
+ class Link {
15899
+ constructor(map, sources) {
15900
+ this.sources = sources;
15901
+ this.names = map.names;
15902
+ this.mappings = map.mappings;
15903
+ }
15904
+ traceMappings() {
15905
+ const sources = [];
15906
+ const sourceIndexMap = new Map();
15907
+ const sourcesContent = [];
15908
+ const names = [];
15909
+ const nameIndexMap = new Map();
15910
+ const mappings = [];
15911
+ for (const line of this.mappings) {
15912
+ const tracedLine = [];
15913
+ for (const segment of line) {
15914
+ if (segment.length === 1)
15915
+ continue;
15916
+ const source = this.sources[segment[1]];
15917
+ if (!source)
15918
+ continue;
15919
+ const traced = source.traceSegment(segment[2], segment[3], segment.length === 5 ? this.names[segment[4]] : '');
15920
+ if (traced) {
15921
+ const { column, line, name, source: { content, filename } } = traced;
15922
+ let sourceIndex = sourceIndexMap.get(filename);
15923
+ if (sourceIndex === undefined) {
15924
+ sourceIndex = sources.length;
15925
+ sources.push(filename);
15926
+ sourceIndexMap.set(filename, sourceIndex);
15927
+ sourcesContent[sourceIndex] = content;
15928
+ }
15929
+ else if (sourcesContent[sourceIndex] == null) {
15930
+ sourcesContent[sourceIndex] = content;
15931
+ }
15932
+ else if (content != null && sourcesContent[sourceIndex] !== content) {
15933
+ return error({
15934
+ message: `Multiple conflicting contents for sourcemap source ${filename}`
15935
+ });
15936
+ }
15937
+ const tracedSegment = [segment[0], sourceIndex, line, column];
15938
+ if (name) {
15939
+ let nameIndex = nameIndexMap.get(name);
15940
+ if (nameIndex === undefined) {
15941
+ nameIndex = names.length;
15942
+ names.push(name);
15943
+ nameIndexMap.set(name, nameIndex);
15944
+ }
15945
+ tracedSegment[4] = nameIndex;
15946
+ }
15947
+ tracedLine.push(tracedSegment);
15948
+ }
15949
+ }
15950
+ mappings.push(tracedLine);
15951
+ }
15952
+ return { mappings, names, sources, sourcesContent };
15953
+ }
15954
+ traceSegment(line, column, name) {
15955
+ const segments = this.mappings[line];
15956
+ if (!segments)
15957
+ return null;
15958
+ // binary search through segments for the given column
15959
+ let searchStart = 0;
15960
+ let searchEnd = segments.length - 1;
15961
+ while (searchStart <= searchEnd) {
15962
+ const m = (searchStart + searchEnd) >> 1;
15963
+ const segment = segments[m];
15964
+ // If a sourcemap does not have sufficient resolution to contain a
15965
+ // necessary mapping, e.g. because it only contains line information, we
15966
+ // use the best approximation we could find
15967
+ if (segment[0] === column || searchStart === searchEnd) {
15968
+ if (segment.length == 1)
15969
+ return null;
15970
+ const source = this.sources[segment[1]];
15971
+ if (!source)
15972
+ return null;
15973
+ return source.traceSegment(segment[2], segment[3], segment.length === 5 ? this.names[segment[4]] : name);
15974
+ }
15975
+ if (segment[0] > column) {
15976
+ searchEnd = m - 1;
15977
+ }
15978
+ else {
15979
+ searchStart = m + 1;
15980
+ }
15981
+ }
15982
+ return null;
15983
+ }
15984
+ }
15985
+ function getLinkMap(warn) {
15986
+ return function linkMap(source, map) {
15987
+ if (map.mappings) {
15988
+ return new Link(map, [source]);
15989
+ }
15990
+ warn({
15991
+ code: 'SOURCEMAP_BROKEN',
15992
+ message: `Sourcemap is likely to be incorrect: a plugin (${map.plugin}) was used to transform ` +
15993
+ "files, but didn't generate a sourcemap for the transformation. Consult the plugin " +
15994
+ 'documentation for help',
15995
+ plugin: map.plugin,
15996
+ url: `https://rollupjs.org/guide/en/#warning-sourcemap-is-likely-to-be-incorrect`
15997
+ });
15998
+ return new Link({
15999
+ mappings: [],
16000
+ names: []
16001
+ }, [source]);
16002
+ };
16003
+ }
16004
+ function getCollapsedSourcemap(id, originalCode, originalSourcemap, sourcemapChain, linkMap) {
16005
+ let source;
16006
+ if (!originalSourcemap) {
16007
+ source = new Source(id, originalCode);
16008
+ }
16009
+ else {
16010
+ const sources = originalSourcemap.sources;
16011
+ const sourcesContent = originalSourcemap.sourcesContent || [];
16012
+ const directory = require$$0.dirname(id) || '.';
16013
+ const sourceRoot = originalSourcemap.sourceRoot || '.';
16014
+ const baseSources = sources.map((source, i) => new Source(require$$0.resolve(directory, sourceRoot, source), sourcesContent[i]));
16015
+ source = new Link(originalSourcemap, baseSources);
16016
+ }
16017
+ return sourcemapChain.reduce(linkMap, source);
16018
+ }
16019
+ function collapseSourcemaps(file, map, modules, bundleSourcemapChain, excludeContent, warn) {
16020
+ const linkMap = getLinkMap(warn);
16021
+ const moduleSources = modules
16022
+ .filter(module => !module.excludeFromSourcemap)
16023
+ .map(module => getCollapsedSourcemap(module.id, module.originalCode, module.originalSourcemap, module.sourcemapChain, linkMap));
16024
+ const link = new Link(map, moduleSources);
16025
+ const source = bundleSourcemapChain.reduce(linkMap, link);
16026
+ let { sources, sourcesContent, names, mappings } = source.traceMappings();
16027
+ if (file) {
16028
+ const directory = require$$0.dirname(file);
16029
+ sources = sources.map((source) => require$$0.relative(directory, source));
16030
+ file = require$$0.basename(file);
16031
+ }
16032
+ sourcesContent = (excludeContent ? null : sourcesContent);
16033
+ return new SourceMap({ file, mappings, names, sources, sourcesContent });
16034
+ }
16035
+ function collapseSourcemap(id, originalCode, originalSourcemap, sourcemapChain, warn) {
16036
+ if (!sourcemapChain.length) {
16037
+ return originalSourcemap;
16038
+ }
16039
+ const source = getCollapsedSourcemap(id, originalCode, originalSourcemap, sourcemapChain, getLinkMap(warn));
16040
+ const map = source.traceMappings();
16041
+ return { version: 3, ...map };
16042
+ }
16043
+
16044
+ function decodedSourcemap(map) {
16045
+ if (!map)
16046
+ return null;
16047
+ if (typeof map === 'string') {
16048
+ map = JSON.parse(map);
16049
+ }
16050
+ if (map.mappings === '') {
16051
+ return {
16052
+ mappings: [],
16053
+ names: [],
16054
+ sources: [],
16055
+ version: 3
16056
+ };
16057
+ }
16058
+ const mappings = typeof map.mappings === 'string' ? decode(map.mappings) : map.mappings;
16059
+ return { ...map, mappings };
15898
16060
  }
15899
- function getDynamicDependentEntryPoints(dependentEntryPointsByModule, dynamicEntryModules) {
15900
- const dynamicallyDependentEntryPointsByDynamicEntry = new Map();
15901
- for (const dynamicEntry of dynamicEntryModules) {
15902
- const dynamicDependentEntryPoints = getOrCreate(dynamicallyDependentEntryPointsByDynamicEntry, dynamicEntry, () => new Set());
15903
- for (const importer of [
15904
- ...dynamicEntry.includedDynamicImporters,
15905
- ...dynamicEntry.implicitlyLoadedAfter
15906
- ]) {
15907
- for (const entryPoint of dependentEntryPointsByModule.get(importer)) {
15908
- dynamicDependentEntryPoints.add(entryPoint);
15909
- }
15910
- }
15911
- }
15912
- return dynamicallyDependentEntryPointsByDynamicEntry;
16061
+
16062
+ async function renderChunks(chunks, outputBundle, pluginDriver, outputOptions, onwarn) {
16063
+ reserveEntryChunksInBundle(chunks);
16064
+ const renderedChunks = await Promise.all(chunks.map(chunk => chunk.render()));
16065
+ const chunkGraph = getChunkGraph(chunks);
16066
+ const { nonHashedChunksWithPlaceholders, renderedChunksByPlaceholder, hashDependenciesByPlaceholder } = await transformChunksAndGenerateContentHashes(renderedChunks, chunkGraph, outputOptions, pluginDriver, onwarn);
16067
+ const hashesByPlaceholder = generateFinalHashes(renderedChunksByPlaceholder, hashDependenciesByPlaceholder, outputBundle);
16068
+ addChunksToBundle(renderedChunksByPlaceholder, hashesByPlaceholder, outputBundle, nonHashedChunksWithPlaceholders);
15913
16069
  }
15914
- function createChunks(allEntryPoints, assignedEntryPointsByModule) {
15915
- const chunkModules = Object.create(null);
15916
- for (const [module, assignedEntryPoints] of assignedEntryPointsByModule) {
15917
- let chunkSignature = '';
15918
- for (const entry of allEntryPoints) {
15919
- chunkSignature += assignedEntryPoints.has(entry) ? 'X' : '_';
15920
- }
15921
- const chunk = chunkModules[chunkSignature];
15922
- if (chunk) {
15923
- chunk.push(module);
15924
- }
15925
- else {
15926
- chunkModules[chunkSignature] = [module];
16070
+ function reserveEntryChunksInBundle(chunks) {
16071
+ for (const chunk of chunks) {
16072
+ if (chunk.facadeModule && chunk.facadeModule.isUserDefinedEntryPoint) {
16073
+ // reserves name in bundle as side effect if it does not contain a hash
16074
+ chunk.getPreliminaryFileName();
15927
16075
  }
15928
16076
  }
15929
- return Object.values(chunkModules).map(modules => ({
15930
- alias: null,
15931
- modules
15932
- }));
15933
- }
15934
-
15935
- // ported from https://github.com/substack/node-commondir
15936
- function commondir(files) {
15937
- if (files.length === 0)
15938
- return '/';
15939
- if (files.length === 1)
15940
- return require$$0.dirname(files[0]);
15941
- const commonSegments = files.slice(1).reduce((commonSegments, file) => {
15942
- const pathSegements = file.split(/\/+|\\+/);
15943
- let i;
15944
- for (i = 0; commonSegments[i] === pathSegements[i] &&
15945
- i < Math.min(commonSegments.length, pathSegements.length); i++)
15946
- ;
15947
- return commonSegments.slice(0, i);
15948
- }, files[0].split(/\/+|\\+/));
15949
- // Windows correctly handles paths with forward-slashes
15950
- return commonSegments.length > 1 ? commonSegments.join('/') : '/';
15951
16077
  }
15952
-
15953
- const compareExecIndex = (unitA, unitB) => unitA.execIndex > unitB.execIndex ? 1 : -1;
15954
- function sortByExecutionOrder(units) {
15955
- units.sort(compareExecIndex);
16078
+ function getChunkGraph(chunks) {
16079
+ return Object.fromEntries(chunks.map(chunk => {
16080
+ const renderedChunkInfo = chunk.getRenderedChunkInfo();
16081
+ return [renderedChunkInfo.fileName, renderedChunkInfo];
16082
+ }));
15956
16083
  }
15957
- function analyseModuleExecution(entryModules) {
15958
- let nextExecIndex = 0;
15959
- const cyclePaths = [];
15960
- const analysedModules = new Set();
15961
- const dynamicImports = new Set();
15962
- const parents = new Map();
15963
- const orderedModules = [];
15964
- const analyseModule = (module) => {
15965
- if (module instanceof Module) {
15966
- for (const dependency of module.dependencies) {
15967
- if (parents.has(dependency)) {
15968
- if (!analysedModules.has(dependency)) {
15969
- cyclePaths.push(getCyclePath(dependency, module, parents));
15970
- }
15971
- continue;
16084
+ async function transformChunk(magicString, fileName, usedModules, chunkGraph, options, outputPluginDriver, onwarn) {
16085
+ let map = null;
16086
+ const sourcemapChain = [];
16087
+ let code = await outputPluginDriver.hookReduceArg0('renderChunk', [magicString.toString(), chunkGraph[fileName], options, { chunks: chunkGraph }], (code, result, plugin) => {
16088
+ if (result == null)
16089
+ return code;
16090
+ if (typeof result === 'string')
16091
+ result = {
16092
+ code: result,
16093
+ map: undefined
16094
+ };
16095
+ // strict null check allows 'null' maps to not be pushed to the chain, while 'undefined' gets the missing map warning
16096
+ if (result.map !== null) {
16097
+ const map = decodedSourcemap(result.map);
16098
+ sourcemapChain.push(map || { missing: true, plugin: plugin.name });
16099
+ }
16100
+ return result.code;
16101
+ });
16102
+ const { compact, sourcemap, sourcemapPathTransform } = options;
16103
+ if (!compact && code[code.length - 1] !== '\n')
16104
+ code += '\n';
16105
+ if (sourcemap) {
16106
+ timeStart('sourcemap', 2);
16107
+ let file;
16108
+ if (options.file)
16109
+ file = require$$0.resolve(options.sourcemapFile || options.file);
16110
+ else if (options.dir)
16111
+ file = require$$0.resolve(options.dir, fileName);
16112
+ else
16113
+ file = require$$0.resolve(fileName);
16114
+ const decodedMap = magicString.generateDecodedMap({});
16115
+ map = collapseSourcemaps(file, decodedMap, usedModules, sourcemapChain, options.sourcemapExcludeSources, onwarn);
16116
+ map.sources = map.sources
16117
+ .map(sourcePath => {
16118
+ if (sourcemapPathTransform) {
16119
+ const newSourcePath = sourcemapPathTransform(sourcePath, `${file}.map`);
16120
+ if (typeof newSourcePath !== 'string') {
16121
+ error(errFailedValidation(`sourcemapPathTransform function must return a string.`));
15972
16122
  }
15973
- parents.set(dependency, module);
15974
- analyseModule(dependency);
16123
+ return newSourcePath;
15975
16124
  }
15976
- for (const dependency of module.implicitlyLoadedBefore) {
15977
- dynamicImports.add(dependency);
15978
- }
15979
- for (const { resolution } of module.dynamicImports) {
15980
- if (resolution instanceof Module) {
15981
- dynamicImports.add(resolution);
16125
+ return sourcePath;
16126
+ })
16127
+ .map(normalize);
16128
+ timeEnd('sourcemap', 2);
16129
+ }
16130
+ return {
16131
+ code,
16132
+ map
16133
+ };
16134
+ }
16135
+ async function transformChunksAndGenerateContentHashes(renderedChunks, chunkGraph, outputOptions, pluginDriver, onwarn) {
16136
+ const nonHashedChunksWithPlaceholders = [];
16137
+ const renderedChunksByPlaceholder = new Map();
16138
+ const hashDependenciesByPlaceholder = new Map();
16139
+ const placeholders = new Set();
16140
+ for (const { preliminaryFileName: { hashPlaceholder } } of renderedChunks) {
16141
+ if (hashPlaceholder)
16142
+ placeholders.add(hashPlaceholder);
16143
+ }
16144
+ await Promise.all(renderedChunks.map(async ({ chunk, preliminaryFileName: { fileName, hashPlaceholder }, magicString, usedModules }) => {
16145
+ const transformedChunk = {
16146
+ chunk,
16147
+ fileName,
16148
+ ...(await transformChunk(magicString, fileName, usedModules, chunkGraph, outputOptions, pluginDriver, onwarn))
16149
+ };
16150
+ const { code } = transformedChunk;
16151
+ if (hashPlaceholder) {
16152
+ const hash = createHash();
16153
+ // To create a reproducible content-only hash, all placeholders are
16154
+ // replaced with the same value before hashing
16155
+ const { containedPlaceholders, transformedCode } = replacePlaceholdersWithDefaultAndGetContainedPlaceholders(code, placeholders);
16156
+ hash.update(transformedCode);
16157
+ const hashAugmentation = pluginDriver.hookReduceValueSync('augmentChunkHash', '', [chunk.getRenderedChunkInfo()], (augmentation, pluginHash) => {
16158
+ if (pluginHash) {
16159
+ augmentation += pluginHash;
15982
16160
  }
16161
+ return augmentation;
16162
+ });
16163
+ if (hashAugmentation) {
16164
+ hash.update(hashAugmentation);
15983
16165
  }
15984
- orderedModules.push(module);
15985
- }
15986
- module.execIndex = nextExecIndex++;
15987
- analysedModules.add(module);
15988
- };
15989
- for (const curEntry of entryModules) {
15990
- if (!parents.has(curEntry)) {
15991
- parents.set(curEntry, null);
15992
- analyseModule(curEntry);
16166
+ renderedChunksByPlaceholder.set(hashPlaceholder, transformedChunk);
16167
+ hashDependenciesByPlaceholder.set(hashPlaceholder, {
16168
+ containedPlaceholders,
16169
+ contentHash: hash.digest('hex')
16170
+ });
15993
16171
  }
15994
- }
15995
- for (const curEntry of dynamicImports) {
15996
- if (!parents.has(curEntry)) {
15997
- parents.set(curEntry, null);
15998
- analyseModule(curEntry);
16172
+ else {
16173
+ nonHashedChunksWithPlaceholders.push(transformedChunk);
15999
16174
  }
16000
- }
16001
- return { cyclePaths, orderedModules };
16175
+ }));
16176
+ return {
16177
+ hashDependenciesByPlaceholder,
16178
+ nonHashedChunksWithPlaceholders,
16179
+ renderedChunksByPlaceholder
16180
+ };
16002
16181
  }
16003
- function getCyclePath(module, parent, parents) {
16004
- const cycleSymbol = Symbol(module.id);
16005
- const path = [relativeId(module.id)];
16006
- let nextModule = parent;
16007
- module.cycles.add(cycleSymbol);
16008
- while (nextModule !== module) {
16009
- nextModule.cycles.add(cycleSymbol);
16010
- path.push(relativeId(nextModule.id));
16011
- nextModule = parents.get(nextModule);
16182
+ function generateFinalHashes(renderedChunksByPlaceholder, hashDependenciesByPlaceholder, outputBundle) {
16183
+ const hashesByPlaceholder = new Map();
16184
+ for (const [placeholder, { fileName }] of renderedChunksByPlaceholder) {
16185
+ let hash = createHash();
16186
+ const hashDependencyPlaceholders = new Set([placeholder]);
16187
+ for (const dependencyPlaceholder of hashDependencyPlaceholders) {
16188
+ const { containedPlaceholders, contentHash } = hashDependenciesByPlaceholder.get(dependencyPlaceholder);
16189
+ hash.update(contentHash);
16190
+ for (const containedPlaceholder of containedPlaceholders) {
16191
+ // When looping over a map, setting an entry only causes a new iteration if the key is new
16192
+ hashDependencyPlaceholders.add(containedPlaceholder);
16193
+ }
16194
+ }
16195
+ let finalFileName;
16196
+ let finalHash;
16197
+ do {
16198
+ // In case of a hash collision, create a hash of the hash
16199
+ if (finalHash) {
16200
+ hash = createHash();
16201
+ hash.update(finalHash);
16202
+ }
16203
+ finalHash = hash.digest('hex').slice(0, placeholder.length);
16204
+ finalFileName = replaceSinglePlaceholder(fileName, placeholder, finalHash);
16205
+ } while (outputBundle[finalFileName]);
16206
+ outputBundle[finalFileName] = FILE_PLACEHOLDER;
16207
+ hashesByPlaceholder.set(placeholder, finalHash.slice(0, placeholder.length));
16012
16208
  }
16013
- path.push(path[0]);
16014
- path.reverse();
16015
- return path;
16209
+ return hashesByPlaceholder;
16016
16210
  }
16017
-
16018
- function getGenerateCodeSnippets({ compact, generatedCode: { arrowFunctions, constBindings, objectShorthand, reservedNamesAsProps } }) {
16019
- const { _, n, s } = compact ? { _: '', n: '', s: '' } : { _: ' ', n: '\n', s: ';' };
16020
- const cnst = constBindings ? 'const' : 'var';
16021
- const getNonArrowFunctionIntro = (params, { isAsync, name }) => `${isAsync ? `async ` : ''}function${name ? ` ${name}` : ''}${_}(${params.join(`,${_}`)})${_}`;
16022
- const getFunctionIntro = arrowFunctions
16023
- ? (params, { isAsync, name }) => {
16024
- const singleParam = params.length === 1;
16025
- const asyncString = isAsync ? `async${singleParam ? ' ' : _}` : '';
16026
- return `${name ? `${cnst} ${name}${_}=${_}` : ''}${asyncString}${singleParam ? params[0] : `(${params.join(`,${_}`)})`}${_}=>${_}`;
16211
+ function addChunksToBundle(renderedChunksByPlaceholder, hashesByPlaceholder, outputBundle, nonHashedChunksWithPlaceholders) {
16212
+ for (const { chunk, code, fileName, map } of renderedChunksByPlaceholder.values()) {
16213
+ const updatedCode = replacePlaceholders(code, hashesByPlaceholder);
16214
+ const finalFileName = replacePlaceholders(fileName, hashesByPlaceholder);
16215
+ if (map) {
16216
+ map.file = replacePlaceholders(map.file, hashesByPlaceholder);
16027
16217
  }
16028
- : getNonArrowFunctionIntro;
16029
- const getDirectReturnFunction = (params, { functionReturn, lineBreakIndent, name }) => [
16030
- `${getFunctionIntro(params, {
16031
- isAsync: false,
16032
- name
16033
- })}${arrowFunctions
16034
- ? lineBreakIndent
16035
- ? `${n}${lineBreakIndent.base}${lineBreakIndent.t}`
16036
- : ''
16037
- : `{${lineBreakIndent ? `${n}${lineBreakIndent.base}${lineBreakIndent.t}` : _}${functionReturn ? 'return ' : ''}`}`,
16038
- arrowFunctions
16039
- ? `${name ? ';' : ''}${lineBreakIndent ? `${n}${lineBreakIndent.base}` : ''}`
16040
- : `${s}${lineBreakIndent ? `${n}${lineBreakIndent.base}` : _}}`
16041
- ];
16042
- const isValidPropName = reservedNamesAsProps
16043
- ? (name) => validPropName.test(name)
16044
- : (name) => !RESERVED_NAMES$1.has(name) && validPropName.test(name);
16045
- return {
16046
- _,
16047
- cnst,
16048
- getDirectReturnFunction,
16049
- getDirectReturnIifeLeft: (params, returned, { needsArrowReturnParens, needsWrappedFunction }) => {
16050
- const [left, right] = getDirectReturnFunction(params, {
16051
- functionReturn: true,
16052
- lineBreakIndent: null,
16053
- name: null
16054
- });
16055
- return `${wrapIfNeeded(`${left}${wrapIfNeeded(returned, arrowFunctions && needsArrowReturnParens)}${right}`, arrowFunctions || needsWrappedFunction)}(`;
16056
- },
16057
- getFunctionIntro,
16058
- getNonArrowFunctionIntro,
16059
- getObject(fields, { lineBreakIndent }) {
16060
- const prefix = lineBreakIndent ? `${n}${lineBreakIndent.base}${lineBreakIndent.t}` : _;
16061
- return `{${fields
16062
- .map(([key, value]) => {
16063
- if (key === null)
16064
- return `${prefix}${value}`;
16065
- const needsQuotes = !isValidPropName(key);
16066
- return key === value && objectShorthand && !needsQuotes
16067
- ? prefix + key
16068
- : `${prefix}${needsQuotes ? `'${key}'` : key}:${_}${value}`;
16069
- })
16070
- .join(`,`)}${fields.length === 0 ? '' : lineBreakIndent ? `${n}${lineBreakIndent.base}` : _}}`;
16071
- },
16072
- getPropertyAccess: (name) => isValidPropName(name) ? `.${name}` : `[${JSON.stringify(name)}]`,
16073
- n,
16074
- s
16075
- };
16218
+ outputBundle[finalFileName] = chunk.generateOutputChunk(updatedCode, map, hashesByPlaceholder);
16219
+ }
16220
+ for (const { chunk, code, fileName, map } of nonHashedChunksWithPlaceholders) {
16221
+ const updatedCode = hashesByPlaceholder.size
16222
+ ? replacePlaceholders(code, hashesByPlaceholder)
16223
+ : code;
16224
+ outputBundle[fileName] = chunk.generateOutputChunk(updatedCode, map, hashesByPlaceholder);
16225
+ }
16076
16226
  }
16077
- const wrapIfNeeded = (code, needsParens) => needsParens ? `(${code})` : code;
16078
- const validPropName = /^(?!\d)[\w$]+$/;
16079
16227
 
16080
16228
  class Bundle {
16081
16229
  constructor(outputOptions, unsetOptions, inputOptions, pluginDriver, graph) {
@@ -16090,24 +16238,24 @@ class Bundle {
16090
16238
  async generate(isWrite) {
16091
16239
  timeStart('GENERATE', 1);
16092
16240
  const outputBundle = Object.create(null);
16093
- this.pluginDriver.setOutputBundle(outputBundle, this.outputOptions, this.facadeChunkByModule);
16241
+ this.pluginDriver.setOutputBundle(outputBundle, this.outputOptions);
16242
+ // TODO Lukas rethink time measuring points
16094
16243
  try {
16095
16244
  await this.pluginDriver.hookParallel('renderStart', [this.outputOptions, this.inputOptions]);
16096
16245
  timeStart('generate chunks', 2);
16097
- const chunks = await this.generateChunks();
16246
+ const getHashPlaceholder = getHashPlaceholderGenerator();
16247
+ const chunks = await this.generateChunks(outputBundle, getHashPlaceholder);
16098
16248
  if (chunks.length > 1) {
16099
16249
  validateOptionsForMultiChunkOutput(this.outputOptions, this.inputOptions.onwarn);
16100
16250
  }
16101
- const inputBase = commondir(getAbsoluteEntryModulePaths(chunks));
16251
+ this.pluginDriver.setChunkInformation(this.facadeChunkByModule);
16102
16252
  timeEnd('generate chunks', 2);
16103
- timeStart('render modules', 2);
16104
- // We need to create addons before prerender because at the moment, there
16105
- // can be no async code between prerender and render due to internal state
16106
- const addons = await createAddons(this.outputOptions, this.pluginDriver);
16107
- const snippets = getGenerateCodeSnippets(this.outputOptions);
16108
- this.prerenderChunks(chunks, inputBase, snippets);
16109
- timeEnd('render modules', 2);
16110
- await this.addFinalizedChunksToBundle(chunks, inputBase, addons, outputBundle, snippets);
16253
+ timeStart('render chunks', 2);
16254
+ for (const chunk of chunks) {
16255
+ chunk.generateExports();
16256
+ }
16257
+ await renderChunks(chunks, outputBundle, this.pluginDriver, this.outputOptions, this.inputOptions.onwarn);
16258
+ timeEnd('render chunks', 2);
16111
16259
  }
16112
16260
  catch (err) {
16113
16261
  await this.pluginDriver.hookParallel('renderError', [err]);
@@ -16122,16 +16270,6 @@ class Bundle {
16122
16270
  timeEnd('GENERATE', 1);
16123
16271
  return outputBundle;
16124
16272
  }
16125
- async addFinalizedChunksToBundle(chunks, inputBase, addons, outputBundle, snippets) {
16126
- this.assignChunkIds(chunks, inputBase, addons, outputBundle);
16127
- for (const chunk of chunks) {
16128
- outputBundle[chunk.id] = chunk.getChunkInfoWithFileNames();
16129
- }
16130
- await Promise.all(chunks.map(async (chunk) => {
16131
- const outputChunk = outputBundle[chunk.id];
16132
- Object.assign(outputChunk, await chunk.render(this.outputOptions, addons, outputChunk, snippets));
16133
- }));
16134
- }
16135
16273
  async addManualChunks(manualChunks) {
16136
16274
  const manualChunkAliasByEntry = new Map();
16137
16275
  const chunkEntries = await Promise.all(Object.entries(manualChunks).map(async ([alias, files]) => ({
@@ -16145,29 +16283,6 @@ class Bundle {
16145
16283
  }
16146
16284
  return manualChunkAliasByEntry;
16147
16285
  }
16148
- assignChunkIds(chunks, inputBase, addons, bundle) {
16149
- const entryChunks = [];
16150
- const otherChunks = [];
16151
- for (const chunk of chunks) {
16152
- (chunk.facadeModule && chunk.facadeModule.isUserDefinedEntryPoint
16153
- ? entryChunks
16154
- : otherChunks).push(chunk);
16155
- }
16156
- // make sure entry chunk names take precedence with regard to deconflicting
16157
- const chunksForNaming = entryChunks.concat(otherChunks);
16158
- for (const chunk of chunksForNaming) {
16159
- if (this.outputOptions.file) {
16160
- chunk.id = require$$0.basename(this.outputOptions.file);
16161
- }
16162
- else if (this.outputOptions.preserveModules) {
16163
- chunk.id = chunk.generateIdPreserveModules(inputBase, this.outputOptions, bundle, this.unsetOptions);
16164
- }
16165
- else {
16166
- chunk.id = chunk.generateId(addons, this.outputOptions, bundle, true);
16167
- }
16168
- bundle[chunk.id] = FILE_PLACEHOLDER;
16169
- }
16170
- }
16171
16286
  assignManualChunks(getManualChunk) {
16172
16287
  const manualChunkAliasesWithEntry = [];
16173
16288
  const manualChunksApi = {
@@ -16191,10 +16306,6 @@ class Bundle {
16191
16306
  }
16192
16307
  finaliseAssets(outputBundle) {
16193
16308
  for (const file of Object.values(outputBundle)) {
16194
- if (!file.type) {
16195
- warnDeprecation('A plugin is directly adding properties to the bundle object in the "generateBundle" hook. This is deprecated and will be removed in a future Rollup version, please use "this.emitFile" instead.', true, this.inputOptions);
16196
- file.type = 'asset';
16197
- }
16198
16309
  if (this.outputOptions.validate && 'code' in file) {
16199
16310
  try {
16200
16311
  this.graph.contextParse(file.code, {
@@ -16209,27 +16320,25 @@ class Bundle {
16209
16320
  }
16210
16321
  this.pluginDriver.finaliseAssets();
16211
16322
  }
16212
- async generateChunks() {
16213
- const { manualChunks } = this.outputOptions;
16323
+ async generateChunks(bundle, getHashPlaceholder) {
16324
+ const { inlineDynamicImports, manualChunks, preserveModules } = this.outputOptions;
16214
16325
  const manualChunkAliasByEntry = typeof manualChunks === 'object'
16215
16326
  ? await this.addManualChunks(manualChunks)
16216
16327
  : this.assignManualChunks(manualChunks);
16328
+ const snippets = getGenerateCodeSnippets(this.outputOptions);
16329
+ const includedModules = getIncludedModules(this.graph.modulesById);
16330
+ const inputBase = commondir(getAbsoluteEntryModulePaths(includedModules, preserveModules));
16331
+ const externalChunkByModule = getExternalChunkByModule(this.graph.modulesById, this.outputOptions, inputBase);
16217
16332
  const chunks = [];
16218
16333
  const chunkByModule = new Map();
16219
- for (const { alias, modules } of this.outputOptions.inlineDynamicImports
16220
- ? [{ alias: null, modules: getIncludedModules(this.graph.modulesById) }]
16221
- : this.outputOptions.preserveModules
16222
- ? getIncludedModules(this.graph.modulesById).map(module => ({
16223
- alias: null,
16224
- modules: [module]
16225
- }))
16334
+ for (const { alias, modules } of inlineDynamicImports
16335
+ ? [{ alias: null, modules: includedModules }]
16336
+ : preserveModules
16337
+ ? includedModules.map(module => ({ alias: null, modules: [module] }))
16226
16338
  : getChunkAssignments(this.graph.entryModules, manualChunkAliasByEntry)) {
16227
16339
  sortByExecutionOrder(modules);
16228
- const chunk = new Chunk(modules, this.inputOptions, this.outputOptions, this.unsetOptions, this.pluginDriver, this.graph.modulesById, chunkByModule, this.facadeChunkByModule, this.includedNamespaces, alias);
16340
+ const chunk = new Chunk(modules, this.inputOptions, this.outputOptions, this.unsetOptions, this.pluginDriver, this.graph.modulesById, chunkByModule, externalChunkByModule, this.facadeChunkByModule, this.includedNamespaces, alias, getHashPlaceholder, bundle, inputBase, snippets);
16229
16341
  chunks.push(chunk);
16230
- for (const module of modules) {
16231
- chunkByModule.set(module, chunk);
16232
- }
16233
16342
  }
16234
16343
  for (const chunk of chunks) {
16235
16344
  chunk.link();
@@ -16240,25 +16349,6 @@ class Bundle {
16240
16349
  }
16241
16350
  return [...chunks, ...facades];
16242
16351
  }
16243
- prerenderChunks(chunks, inputBase, snippets) {
16244
- for (const chunk of chunks) {
16245
- chunk.generateExports();
16246
- }
16247
- for (const chunk of chunks) {
16248
- chunk.preRender(this.outputOptions, inputBase, snippets);
16249
- }
16250
- }
16251
- }
16252
- function getAbsoluteEntryModulePaths(chunks) {
16253
- const absoluteEntryModulePaths = [];
16254
- for (const chunk of chunks) {
16255
- for (const entryModule of chunk.entryModules) {
16256
- if (isAbsolute(entryModule.id)) {
16257
- absoluteEntryModulePaths.push(entryModule.id);
16258
- }
16259
- }
16260
- }
16261
- return absoluteEntryModulePaths;
16262
16352
  }
16263
16353
  function validateOptionsForMultiChunkOutput(outputOptions, onWarn) {
16264
16354
  if (outputOptions.format === 'umd' || outputOptions.format === 'iife')
@@ -16271,8 +16361,32 @@ function validateOptionsForMultiChunkOutput(outputOptions, onWarn) {
16271
16361
  onWarn(errInvalidOption('output.amd.id', 'outputamd', 'this option is only properly supported for single-file builds. Use "output.amd.autoId" and "output.amd.basePath" instead'));
16272
16362
  }
16273
16363
  function getIncludedModules(modulesById) {
16274
- return [...modulesById.values()].filter((module) => module instanceof Module &&
16275
- (module.isIncluded() || module.info.isEntry || module.includedDynamicImporters.length > 0));
16364
+ const includedModules = [];
16365
+ for (const module of modulesById.values()) {
16366
+ if (module instanceof Module &&
16367
+ (module.isIncluded() || module.info.isEntry || module.includedDynamicImporters.length > 0)) {
16368
+ includedModules.push(module);
16369
+ }
16370
+ }
16371
+ return includedModules;
16372
+ }
16373
+ function getAbsoluteEntryModulePaths(includedModules, preserveModules) {
16374
+ const absoluteEntryModulePaths = [];
16375
+ for (const module of includedModules) {
16376
+ if ((module.info.isEntry || preserveModules) && isAbsolute(module.id)) {
16377
+ absoluteEntryModulePaths.push(module.id);
16378
+ }
16379
+ }
16380
+ return absoluteEntryModulePaths;
16381
+ }
16382
+ function getExternalChunkByModule(modulesById, outputOptions, inputBase) {
16383
+ const externalChunkByModule = new Map();
16384
+ for (const module of modulesById.values()) {
16385
+ if (module instanceof ExternalModule) {
16386
+ externalChunkByModule.set(module, new ExternalChunk(module, outputOptions, inputBase));
16387
+ }
16388
+ }
16389
+ return externalChunkByModule;
16276
16390
  }
16277
16391
  function addModuleToManualChunk(alias, module, manualChunkAliasByEntry) {
16278
16392
  const existingAlias = manualChunkAliasByEntry.get(module);
@@ -21914,7 +22028,7 @@ async function findFile(file, preserveSymlinks) {
21914
22028
  return file;
21915
22029
  }
21916
22030
  }
21917
- catch (_a) {
22031
+ catch {
21918
22032
  // suppress
21919
22033
  }
21920
22034
  }
@@ -21937,21 +22051,6 @@ function throwPluginError(err, plugin, { hook, id } = {}) {
21937
22051
  }
21938
22052
  return error(err);
21939
22053
  }
21940
- const deprecatedHooks = [
21941
- { active: true, deprecated: 'resolveAssetUrl', replacement: 'resolveFileUrl' }
21942
- ];
21943
- function warnDeprecatedHooks(plugins, options) {
21944
- for (const { active, deprecated, replacement } of deprecatedHooks) {
21945
- for (const plugin of plugins) {
21946
- if (deprecated in plugin) {
21947
- warnDeprecation({
21948
- message: `The "${deprecated}" hook used by plugin ${plugin.name} is deprecated. The "${replacement}" hook should be used instead.`,
21949
- plugin: plugin.name
21950
- }, active, options);
21951
- }
21952
- }
21953
- }
21954
- }
21955
22054
 
21956
22055
  function createPluginCache(cache) {
21957
22056
  return {
@@ -22093,14 +22192,6 @@ async function transform(source, module, pluginDriver, warn) {
22093
22192
  cache: customTransformCache
22094
22193
  ? pluginContext.cache
22095
22194
  : getTrackedPluginCache(pluginContext.cache, useCustomTransformCache),
22096
- emitAsset(name, source) {
22097
- emittedFiles.push({ name, source, type: 'asset' });
22098
- return pluginContext.emitAsset(name, source);
22099
- },
22100
- emitChunk(id, options) {
22101
- emittedFiles.push({ id, name: options && options.name, type: 'chunk' });
22102
- return pluginContext.emitChunk(id, options);
22103
- },
22104
22195
  emitFile(emittedFile) {
22105
22196
  emittedFiles.push(emittedFile);
22106
22197
  return pluginDriver.emitFile(emittedFile);
@@ -22610,19 +22701,6 @@ class GlobalScope extends Scope$1 {
22610
22701
  }
22611
22702
  }
22612
22703
 
22613
- function getDeprecatedContextHandler(handler, handlerName, newHandlerName, pluginName, activeDeprecation, options) {
22614
- let deprecationWarningShown = false;
22615
- return ((...args) => {
22616
- if (!deprecationWarningShown) {
22617
- deprecationWarningShown = true;
22618
- warnDeprecation({
22619
- message: `The "this.${handlerName}" plugin context function used by plugin ${pluginName} is deprecated. The "this.${newHandlerName}" plugin context function should be used instead.`,
22620
- plugin: pluginName
22621
- }, activeDeprecation, options);
22622
- }
22623
- return handler(...args);
22624
- });
22625
- }
22626
22704
  function getPluginContext(plugin, pluginCache, graph, options, fileEmitter, existingPluginNames) {
22627
22705
  let cacheable = true;
22628
22706
  if (typeof plugin.cacheKey !== 'string') {
@@ -22654,19 +22732,14 @@ function getPluginContext(plugin, pluginCache, graph, options, fileEmitter, exis
22654
22732
  graph.watchFiles[id] = true;
22655
22733
  },
22656
22734
  cache: cacheInstance,
22657
- emitAsset: getDeprecatedContextHandler((name, source) => fileEmitter.emitFile({ name, source, type: 'asset' }), 'emitAsset', 'emitFile', plugin.name, true, options),
22658
- emitChunk: getDeprecatedContextHandler((id, options) => fileEmitter.emitFile({ id, name: options && options.name, type: 'chunk' }), 'emitChunk', 'emitFile', plugin.name, true, options),
22659
22735
  emitFile: fileEmitter.emitFile.bind(fileEmitter),
22660
22736
  error(err) {
22661
22737
  return throwPluginError(err, plugin.name);
22662
22738
  },
22663
- getAssetFileName: getDeprecatedContextHandler(fileEmitter.getFileName, 'getAssetFileName', 'getFileName', plugin.name, true, options),
22664
- getChunkFileName: getDeprecatedContextHandler(fileEmitter.getFileName, 'getChunkFileName', 'getFileName', plugin.name, true, options),
22665
22739
  getFileName: fileEmitter.getFileName,
22666
22740
  getModuleIds: () => graph.modulesById.keys(),
22667
22741
  getModuleInfo: graph.getModuleInfo,
22668
22742
  getWatchFiles: () => Object.keys(graph.watchFiles),
22669
- isExternal: getDeprecatedContextHandler((id, parentId, isResolved = false) => options.external(id, parentId, isResolved), 'isExternal', 'resolve', plugin.name, true, options),
22670
22743
  load(resolvedId) {
22671
22744
  return graph.moduleLoader.preloadModule(resolvedId);
22672
22745
  },
@@ -22680,7 +22753,7 @@ function getPluginContext(plugin, pluginCache, graph, options, fileEmitter, exis
22680
22753
  warnDeprecation({
22681
22754
  message: `Accessing "this.moduleIds" on the plugin context by plugin ${plugin.name} is deprecated. The "this.getModuleIds" plugin context function should be used instead.`,
22682
22755
  plugin: plugin.name
22683
- }, false, options);
22756
+ }, true, options);
22684
22757
  yield* moduleIds;
22685
22758
  }
22686
22759
  const moduleIds = graph.modulesById.keys();
@@ -22690,9 +22763,6 @@ function getPluginContext(plugin, pluginCache, graph, options, fileEmitter, exis
22690
22763
  resolve(source, importer, { custom, isEntry, skipSelf } = BLANK) {
22691
22764
  return graph.moduleLoader.resolveId(source, importer, custom, isEntry, skipSelf ? [{ importer, plugin, source }] : null);
22692
22765
  },
22693
- resolveId: getDeprecatedContextHandler((source, importer) => graph.moduleLoader
22694
- .resolveId(source, importer, BLANK, undefined)
22695
- .then(resolveId => resolveId && resolveId.id), 'resolveId', 'resolve', plugin.name, true, options),
22696
22766
  setAssetSource: fileEmitter.setAssetSource,
22697
22767
  warn(warning) {
22698
22768
  if (typeof warning === 'string')
@@ -22733,12 +22803,12 @@ class PluginDriver {
22733
22803
  this.graph = graph;
22734
22804
  this.options = options;
22735
22805
  this.unfulfilledActions = new Set();
22736
- warnDeprecatedHooks(userPlugins, options);
22737
22806
  this.pluginCache = pluginCache;
22738
22807
  this.fileEmitter = new FileEmitter(graph, options, basePluginDriver && basePluginDriver.fileEmitter);
22739
22808
  this.emitFile = this.fileEmitter.emitFile.bind(this.fileEmitter);
22740
22809
  this.getFileName = this.fileEmitter.getFileName.bind(this.fileEmitter);
22741
- this.finaliseAssets = this.fileEmitter.assertAssetsFinalized.bind(this.fileEmitter);
22810
+ this.finaliseAssets = this.fileEmitter.finaliseAssets.bind(this.fileEmitter);
22811
+ this.setChunkInformation = this.fileEmitter.setChunkInformation.bind(this.fileEmitter);
22742
22812
  this.setOutputBundle = this.fileEmitter.setOutputBundle.bind(this.fileEmitter);
22743
22813
  this.plugins = userPlugins.concat(basePluginDriver ? basePluginDriver.plugins : []);
22744
22814
  const existingPluginNames = new Set();
@@ -23205,7 +23275,7 @@ function normalizeInputOptions(config) {
23205
23275
  preserveSymlinks: config.preserveSymlinks || false,
23206
23276
  shimMissingExports: config.shimMissingExports || false,
23207
23277
  strictDeprecations,
23208
- treeshake: getTreeshake(config, onwarn, strictDeprecations)
23278
+ treeshake: getTreeshake(config)
23209
23279
  };
23210
23280
  warnUnknownOptions(config, [...Object.keys(options), 'watch'], 'input options', options.onwarn, /^(output)$/);
23211
23281
  return { options, unsetOptions };
@@ -23261,7 +23331,7 @@ const getIdMatcher = (option) => {
23261
23331
  const getInlineDynamicImports$1 = (config, warn, strictDeprecations) => {
23262
23332
  const configInlineDynamicImports = config.inlineDynamicImports;
23263
23333
  if (configInlineDynamicImports) {
23264
- warnDeprecationWithOptions('The "inlineDynamicImports" option is deprecated. Use the "output.inlineDynamicImports" option instead.', false, warn, strictDeprecations);
23334
+ warnDeprecationWithOptions('The "inlineDynamicImports" option is deprecated. Use the "output.inlineDynamicImports" option instead.', true, warn, strictDeprecations);
23265
23335
  }
23266
23336
  return configInlineDynamicImports;
23267
23337
  };
@@ -23272,7 +23342,7 @@ const getInput = (config) => {
23272
23342
  const getManualChunks$1 = (config, warn, strictDeprecations) => {
23273
23343
  const configManualChunks = config.manualChunks;
23274
23344
  if (configManualChunks) {
23275
- warnDeprecationWithOptions('The "manualChunks" option is deprecated. Use the "output.manualChunks" option instead.', false, warn, strictDeprecations);
23345
+ warnDeprecationWithOptions('The "manualChunks" option is deprecated. Use the "output.manualChunks" option instead.', true, warn, strictDeprecations);
23276
23346
  }
23277
23347
  return configManualChunks;
23278
23348
  };
@@ -23309,25 +23379,20 @@ const getPreserveEntrySignatures = (config, unsetOptions) => {
23309
23379
  const getPreserveModules$1 = (config, warn, strictDeprecations) => {
23310
23380
  const configPreserveModules = config.preserveModules;
23311
23381
  if (configPreserveModules) {
23312
- warnDeprecationWithOptions('The "preserveModules" option is deprecated. Use the "output.preserveModules" option instead.', false, warn, strictDeprecations);
23382
+ warnDeprecationWithOptions('The "preserveModules" option is deprecated. Use the "output.preserveModules" option instead.', true, warn, strictDeprecations);
23313
23383
  }
23314
23384
  return configPreserveModules;
23315
23385
  };
23316
- const getTreeshake = (config, warn, strictDeprecations) => {
23386
+ const getTreeshake = (config) => {
23317
23387
  const configTreeshake = config.treeshake;
23318
23388
  if (configTreeshake === false) {
23319
23389
  return false;
23320
23390
  }
23321
23391
  const configWithPreset = getOptionWithPreset(config.treeshake, treeshakePresets, 'treeshake', 'false, true, ');
23322
- if (typeof configWithPreset.pureExternalModules !== 'undefined') {
23323
- warnDeprecationWithOptions(`The "treeshake.pureExternalModules" option is deprecated. The "treeshake.moduleSideEffects" option should be used instead. "treeshake.pureExternalModules: true" is equivalent to "treeshake.moduleSideEffects: 'no-external'"`, true, warn, strictDeprecations);
23324
- }
23325
23392
  return {
23326
23393
  annotations: configWithPreset.annotations !== false,
23327
23394
  correctVarValueBeforeDeclaration: configWithPreset.correctVarValueBeforeDeclaration === true,
23328
- moduleSideEffects: typeof configTreeshake === 'object' && configTreeshake.pureExternalModules
23329
- ? getHasModuleSideEffects(configTreeshake.moduleSideEffects, configTreeshake.pureExternalModules)
23330
- : getHasModuleSideEffects(configWithPreset.moduleSideEffects, undefined),
23395
+ moduleSideEffects: getHasModuleSideEffects(configWithPreset.moduleSideEffects),
23331
23396
  propertyReadSideEffects: configWithPreset.propertyReadSideEffects === 'always'
23332
23397
  ? 'always'
23333
23398
  : configWithPreset.propertyReadSideEffects !== false,
@@ -23335,7 +23400,7 @@ const getTreeshake = (config, warn, strictDeprecations) => {
23335
23400
  unknownGlobalSideEffects: configWithPreset.unknownGlobalSideEffects !== false
23336
23401
  };
23337
23402
  };
23338
- const getHasModuleSideEffects = (moduleSideEffectsOption, pureExternalModules) => {
23403
+ const getHasModuleSideEffects = (moduleSideEffectsOption) => {
23339
23404
  if (typeof moduleSideEffectsOption === 'boolean') {
23340
23405
  return () => moduleSideEffectsOption;
23341
23406
  }
@@ -23352,8 +23417,7 @@ const getHasModuleSideEffects = (moduleSideEffectsOption, pureExternalModules) =
23352
23417
  if (moduleSideEffectsOption) {
23353
23418
  error(errInvalidOption('treeshake.moduleSideEffects', 'treeshake', 'please use one of false, "no-external", a function or an array'));
23354
23419
  }
23355
- const isPureExternalModule = getIdMatcher(pureExternalModules);
23356
- return (id, external) => !(external && isPureExternalModule(id));
23420
+ return () => true;
23357
23421
  };
23358
23422
 
23359
23423
  // https://datatracker.ietf.org/doc/html/rfc2396
@@ -23387,7 +23451,7 @@ function normalizeOutputOptions(config, inputOptions, unsetInputOptions) {
23387
23451
  chunkFileNames: (_b = config.chunkFileNames) !== null && _b !== void 0 ? _b : '[name]-[hash].js',
23388
23452
  compact,
23389
23453
  dir: getDir(config, file),
23390
- dynamicImportFunction: getDynamicImportFunction(config, inputOptions),
23454
+ dynamicImportFunction: getDynamicImportFunction(config, inputOptions, format),
23391
23455
  entryFileNames: getEntryFileNames(config, unsetOptions),
23392
23456
  esModule: (_c = config.esModule) !== null && _c !== void 0 ? _c : true,
23393
23457
  exports: getExports(config, unsetOptions),
@@ -23492,7 +23556,7 @@ const getPreserveModules = (config, inlineDynamicImports, inputOptions) => {
23492
23556
  const getPreferConst = (config, inputOptions) => {
23493
23557
  const configPreferConst = config.preferConst;
23494
23558
  if (configPreferConst != null) {
23495
- warnDeprecation(`The "output.preferConst" option is deprecated. Use the "output.generatedCode.constBindings" option instead.`, false, inputOptions);
23559
+ warnDeprecation(`The "output.preferConst" option is deprecated. Use the "output.generatedCode.constBindings" option instead.`, true, inputOptions);
23496
23560
  }
23497
23561
  return !!configPreferConst;
23498
23562
  };
@@ -23547,10 +23611,13 @@ const getDir = (config, file) => {
23547
23611
  }
23548
23612
  return dir;
23549
23613
  };
23550
- const getDynamicImportFunction = (config, inputOptions) => {
23614
+ const getDynamicImportFunction = (config, inputOptions, format) => {
23551
23615
  const configDynamicImportFunction = config.dynamicImportFunction;
23552
23616
  if (configDynamicImportFunction) {
23553
- warnDeprecation(`The "output.dynamicImportFunction" option is deprecated. Use the "renderDynamicImport" plugin hook instead.`, false, inputOptions);
23617
+ warnDeprecation(`The "output.dynamicImportFunction" option is deprecated. Use the "renderDynamicImport" plugin hook instead.`, true, inputOptions);
23618
+ if (format !== 'es') {
23619
+ inputOptions.onwarn(errInvalidOption('output.dynamicImportFunction', 'outputdynamicImportFunction', 'this option is ignored for formats other than "es"'));
23620
+ }
23554
23621
  }
23555
23622
  return configDynamicImportFunction;
23556
23623
  };
@@ -23609,7 +23676,7 @@ const getInterop = (config, inputOptions) => {
23609
23676
  warnDeprecation({
23610
23677
  message: `The boolean value "${interop}" for the "output.interop" option is deprecated. Use ${interop ? '"auto"' : '"esModule", "default" or "defaultOnly"'} instead.`,
23611
23678
  url: 'https://rollupjs.org/guide/en/#outputinterop'
23612
- }, false, inputOptions);
23679
+ }, true, inputOptions);
23613
23680
  }
23614
23681
  }
23615
23682
  return interop;
@@ -23641,7 +23708,7 @@ const getMinifyInternalExports = (config, format, compact) => { var _a; return (
23641
23708
  const getNamespaceToStringTag = (config, generatedCode, inputOptions) => {
23642
23709
  const configNamespaceToStringTag = config.namespaceToStringTag;
23643
23710
  if (configNamespaceToStringTag != null) {
23644
- warnDeprecation(`The "output.namespaceToStringTag" option is deprecated. Use the "output.generatedCode.symbols" option instead.`, false, inputOptions);
23711
+ warnDeprecation(`The "output.namespaceToStringTag" option is deprecated. Use the "output.generatedCode.symbols" option instead.`, true, inputOptions);
23645
23712
  return configNamespaceToStringTag;
23646
23713
  }
23647
23714
  return generatedCode.symbols || false;