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
 
@@ -14,7 +14,7 @@ import { createHash as createHash$1 } from 'crypto';
14
14
  import { promises } from 'fs';
15
15
  import { EventEmitter } from 'events';
16
16
 
17
- var version$1 = "2.75.7";
17
+ var version$1 = "3.0.0-0";
18
18
 
19
19
  var charToInteger = {};
20
20
  var chars$1 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
@@ -1510,6 +1510,88 @@ function relative(from, to) {
1510
1510
  return toParts.join('/');
1511
1511
  }
1512
1512
 
1513
+ const needsEscapeRegEx = /[\\'\r\n\u2028\u2029]/;
1514
+ const quoteNewlineRegEx = /(['\r\n\u2028\u2029])/g;
1515
+ const backSlashRegEx = /\\/g;
1516
+ function escapeId(id) {
1517
+ if (!id.match(needsEscapeRegEx))
1518
+ return id;
1519
+ return id.replace(backSlashRegEx, '\\\\').replace(quoteNewlineRegEx, '\\$1');
1520
+ }
1521
+
1522
+ const ABSOLUTE_PATH_REGEX = /^(?:\/|(?:[A-Za-z]:)?[\\|/])/;
1523
+ const RELATIVE_PATH_REGEX = /^\.?\.(\/|$)/;
1524
+ function isAbsolute(path) {
1525
+ return ABSOLUTE_PATH_REGEX.test(path);
1526
+ }
1527
+ function isRelative(path) {
1528
+ return RELATIVE_PATH_REGEX.test(path);
1529
+ }
1530
+ const BACKSLASH_REGEX = /\\/g;
1531
+ function normalize(path) {
1532
+ return path.replace(BACKSLASH_REGEX, '/');
1533
+ }
1534
+
1535
+ function getAliasName(id) {
1536
+ const base = basename(id);
1537
+ return base.substring(0, base.length - extname(id).length);
1538
+ }
1539
+ function relativeId(id) {
1540
+ if (!isAbsolute(id))
1541
+ return id;
1542
+ return relative(resolve(), id);
1543
+ }
1544
+ function isPathFragment(name) {
1545
+ // starting with "/", "./", "../", "C:/"
1546
+ return (name[0] === '/' || (name[0] === '.' && (name[1] === '/' || name[1] === '.')) || isAbsolute(name));
1547
+ }
1548
+ const UPPER_DIR_REGEX = /^(\.\.\/)*\.\.$/;
1549
+ function getImportPath(importerId, targetPath, stripJsExtension, ensureFileName) {
1550
+ let relativePath = normalize(relative(dirname(importerId), targetPath));
1551
+ if (stripJsExtension && relativePath.endsWith('.js')) {
1552
+ relativePath = relativePath.slice(0, -3);
1553
+ }
1554
+ if (ensureFileName) {
1555
+ if (relativePath === '')
1556
+ return '../' + basename(targetPath);
1557
+ if (UPPER_DIR_REGEX.test(relativePath)) {
1558
+ return relativePath
1559
+ .split('/')
1560
+ .concat(['..', basename(targetPath)])
1561
+ .join('/');
1562
+ }
1563
+ }
1564
+ return !relativePath ? '.' : relativePath.startsWith('..') ? relativePath : './' + relativePath;
1565
+ }
1566
+
1567
+ class ExternalChunk {
1568
+ constructor(module, options, inputBase) {
1569
+ this.options = options;
1570
+ this.inputBase = inputBase;
1571
+ this.defaultVariableName = '';
1572
+ this.namespaceVariableName = '';
1573
+ this.variableName = '';
1574
+ this.fileName = null;
1575
+ this.id = module.id;
1576
+ this.renormalizeRenderPath = module.renormalizeRenderPath;
1577
+ this.suggestedVariableName = module.suggestedVariableName;
1578
+ }
1579
+ getFileName() {
1580
+ if (this.fileName) {
1581
+ return this.fileName;
1582
+ }
1583
+ const { paths } = this.options;
1584
+ return (this.fileName =
1585
+ (typeof paths === 'function' ? paths(this.id) : paths[this.id]) ||
1586
+ (this.renormalizeRenderPath ? normalize(relative$1(this.inputBase, this.id)) : this.id));
1587
+ }
1588
+ getImportPath(importer) {
1589
+ return escapeId(this.renormalizeRenderPath
1590
+ ? getImportPath(importer, this.getFileName(), this.options.format === 'amd', false)
1591
+ : this.getFileName());
1592
+ }
1593
+ }
1594
+
1513
1595
  function getOrCreate(map, key, init) {
1514
1596
  const existing = map.get(key);
1515
1597
  if (existing) {
@@ -1808,51 +1890,6 @@ function printQuotedStringList(list, verbs) {
1808
1890
  return output;
1809
1891
  }
1810
1892
 
1811
- const ABSOLUTE_PATH_REGEX = /^(?:\/|(?:[A-Za-z]:)?[\\|/])/;
1812
- const RELATIVE_PATH_REGEX = /^\.?\.(\/|$)/;
1813
- function isAbsolute(path) {
1814
- return ABSOLUTE_PATH_REGEX.test(path);
1815
- }
1816
- function isRelative(path) {
1817
- return RELATIVE_PATH_REGEX.test(path);
1818
- }
1819
- const BACKSLASH_REGEX = /\\/g;
1820
- function normalize(path) {
1821
- return path.replace(BACKSLASH_REGEX, '/');
1822
- }
1823
-
1824
- function getAliasName(id) {
1825
- const base = basename(id);
1826
- return base.substring(0, base.length - extname(id).length);
1827
- }
1828
- function relativeId(id) {
1829
- if (!isAbsolute(id))
1830
- return id;
1831
- return relative(resolve(), id);
1832
- }
1833
- function isPathFragment(name) {
1834
- // starting with "/", "./", "../", "C:/"
1835
- return (name[0] === '/' || (name[0] === '.' && (name[1] === '/' || name[1] === '.')) || isAbsolute(name));
1836
- }
1837
- const UPPER_DIR_REGEX = /^(\.\.\/)*\.\.$/;
1838
- function getImportPath(importerId, targetPath, stripJsExtension, ensureFileName) {
1839
- let relativePath = normalize(relative(dirname(importerId), targetPath));
1840
- if (stripJsExtension && relativePath.endsWith('.js')) {
1841
- relativePath = relativePath.slice(0, -3);
1842
- }
1843
- if (ensureFileName) {
1844
- if (relativePath === '')
1845
- return '../' + basename(targetPath);
1846
- if (UPPER_DIR_REGEX.test(relativePath)) {
1847
- return relativePath
1848
- .split('/')
1849
- .concat(['..', basename(targetPath)])
1850
- .join('/');
1851
- }
1852
- }
1853
- return !relativePath ? '.' : relativePath.startsWith('..') ? relativePath : './' + relativePath;
1854
- }
1855
-
1856
1893
  function error(base) {
1857
1894
  if (!(base instanceof Error))
1858
1895
  base = Object.assign(new Error(base.message), base);
@@ -1875,6 +1912,7 @@ function augmentCodeLocation(props, pos, source, id) {
1875
1912
  }
1876
1913
  var Errors;
1877
1914
  (function (Errors) {
1915
+ Errors["ADDON_ERROR"] = "ADDON_ERROR";
1878
1916
  Errors["ALREADY_CLOSED"] = "ALREADY_CLOSED";
1879
1917
  Errors["ASSET_NOT_FINALISED"] = "ASSET_NOT_FINALISED";
1880
1918
  Errors["ASSET_NOT_FOUND"] = "ASSET_NOT_FOUND";
@@ -1897,6 +1935,7 @@ var Errors;
1897
1935
  Errors["INVALID_OPTION"] = "INVALID_OPTION";
1898
1936
  Errors["INVALID_PLUGIN_HOOK"] = "INVALID_PLUGIN_HOOK";
1899
1937
  Errors["INVALID_ROLLUP_PHASE"] = "INVALID_ROLLUP_PHASE";
1938
+ Errors["INVALID_TLA_FORMAT"] = "INVALID_TLA_FORMAT";
1900
1939
  Errors["MISSING_EXPORT"] = "MISSING_EXPORT";
1901
1940
  Errors["MISSING_IMPLICIT_DEPENDANT"] = "MISSING_IMPLICIT_DEPENDANT";
1902
1941
  Errors["MIXED_EXPORTS"] = "MIXED_EXPORTS";
@@ -1911,10 +1950,17 @@ var Errors;
1911
1950
  Errors["UNRESOLVED_IMPORT"] = "UNRESOLVED_IMPORT";
1912
1951
  Errors["VALIDATION_ERROR"] = "VALIDATION_ERROR";
1913
1952
  })(Errors || (Errors = {}));
1953
+ function errAddonNotGenerated(message, hook, plugin) {
1954
+ return {
1955
+ code: Errors.ADDON_ERROR,
1956
+ message: `Could not retrieve ${hook}. Check configuration of plugin ${plugin}.
1957
+ \tError Message: ${message}`
1958
+ };
1959
+ }
1914
1960
  function errAssetNotFinalisedForFileName(name) {
1915
1961
  return {
1916
1962
  code: Errors.ASSET_NOT_FINALISED,
1917
- message: `Plugin error - Unable to get file name for asset "${name}". Ensure that the source is set and that generate is called first.`
1963
+ 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.`
1918
1964
  };
1919
1965
  }
1920
1966
  function errCannotEmitFromOptionsHook() {
@@ -1926,7 +1972,7 @@ function errCannotEmitFromOptionsHook() {
1926
1972
  function errChunkNotGeneratedForFileName(name) {
1927
1973
  return {
1928
1974
  code: Errors.CHUNK_NOT_GENERATED,
1929
- message: `Plugin error - Unable to get file name for chunk "${name}". Ensure that generate is called first.`
1975
+ 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.`
1930
1976
  };
1931
1977
  }
1932
1978
  function errChunkInvalid({ fileName, code }, exception) {
@@ -2045,6 +2091,13 @@ function errInvalidRollupPhaseForChunkEmission() {
2045
2091
  message: `Cannot emit chunks after module loading has finished.`
2046
2092
  };
2047
2093
  }
2094
+ function errInvalidFormatForTopLevelAwait(id, format) {
2095
+ return {
2096
+ code: Errors.INVALID_TLA_FORMAT,
2097
+ id,
2098
+ message: `Module format ${format} does not support top-level await. Use the "es" or "system" output formats rather.`
2099
+ };
2100
+ }
2048
2101
  function errMissingExport(exportName, importingModule, importedModule) {
2049
2102
  return {
2050
2103
  code: Errors.MISSING_EXPORT,
@@ -2272,19 +2325,15 @@ class ExternalModule {
2272
2325
  this.options = options;
2273
2326
  this.id = id;
2274
2327
  this.renormalizeRenderPath = renormalizeRenderPath;
2275
- this.declarations = new Map();
2276
- this.defaultVariableName = '';
2277
2328
  this.dynamicImporters = [];
2278
2329
  this.execIndex = Infinity;
2279
2330
  this.exportedVariables = new Map();
2280
2331
  this.importers = [];
2281
- this.mostCommonSuggestion = 0;
2282
- this.nameSuggestions = new Map();
2283
- this.namespaceVariableName = '';
2284
2332
  this.reexported = false;
2285
- this.renderPath = undefined;
2286
2333
  this.used = false;
2287
- this.variableName = '';
2334
+ this.declarations = new Map();
2335
+ this.mostCommonSuggestion = 0;
2336
+ this.nameSuggestions = new Map();
2288
2337
  this.suggestedVariableName = makeLegal(id.split(/[\\/]/).pop());
2289
2338
  const { importers, dynamicImporters } = this;
2290
2339
  const info = (this.info = {
@@ -2297,7 +2346,7 @@ class ExternalModule {
2297
2346
  },
2298
2347
  hasDefaultExport: null,
2299
2348
  get hasModuleSideEffects() {
2300
- warnDeprecation('Accessing ModuleInfo.hasModuleSideEffects from plugins is deprecated. Please use ModuleInfo.moduleSideEffects instead.', false, options);
2349
+ warnDeprecation('Accessing ModuleInfo.hasModuleSideEffects from plugins is deprecated. Please use ModuleInfo.moduleSideEffects instead.', true, options);
2301
2350
  return info.moduleSideEffects;
2302
2351
  },
2303
2352
  id,
@@ -2329,15 +2378,6 @@ class ExternalModule {
2329
2378
  this.exportedVariables.set(externalVariable, name);
2330
2379
  return [externalVariable];
2331
2380
  }
2332
- setRenderPath(options, inputBase) {
2333
- this.renderPath =
2334
- typeof options.paths === 'function' ? options.paths(this.id) : options.paths[this.id];
2335
- if (!this.renderPath) {
2336
- this.renderPath = this.renormalizeRenderPath
2337
- ? normalize(relative$1(inputBase, this.id))
2338
- : this.id;
2339
- }
2340
- }
2341
2381
  suggestName(name) {
2342
2382
  var _a;
2343
2383
  const value = ((_a = this.nameSuggestions.get(name)) !== null && _a !== void 0 ? _a : 0) + 1;
@@ -10226,7 +10266,9 @@ class ImportExpression extends NodeBase {
10226
10266
  super(...arguments);
10227
10267
  this.inlineNamespace = null;
10228
10268
  this.mechanism = null;
10269
+ this.namespaceExportName = undefined;
10229
10270
  this.resolution = null;
10271
+ this.resolutionString = null;
10230
10272
  }
10231
10273
  hasEffects() {
10232
10274
  return true;
@@ -10243,8 +10285,8 @@ class ImportExpression extends NodeBase {
10243
10285
  this.context.addDynamicImport(this);
10244
10286
  }
10245
10287
  render(code, options) {
10288
+ const { snippets: { getDirectReturnFunction, getPropertyAccess } } = options;
10246
10289
  if (this.inlineNamespace) {
10247
- const { snippets: { getDirectReturnFunction, getPropertyAccess } } = options;
10248
10290
  const [left, right] = getDirectReturnFunction([], {
10249
10291
  functionReturn: true,
10250
10292
  lineBreakIndent: null,
@@ -10257,22 +10299,26 @@ class ImportExpression extends NodeBase {
10257
10299
  code.overwrite(this.start, findFirstOccurrenceOutsideComment(code.original, '(', this.start + 6) + 1, this.mechanism.left, { contentOnly: true });
10258
10300
  code.overwrite(this.end - 1, this.end, this.mechanism.right, { contentOnly: true });
10259
10301
  }
10260
- this.source.render(code, options);
10261
- }
10262
- renderFinalResolution(code, resolution, namespaceExportName, { getDirectReturnFunction }) {
10263
- code.overwrite(this.source.start, this.source.end, resolution);
10264
- if (namespaceExportName) {
10265
- const [left, right] = getDirectReturnFunction(['n'], {
10266
- functionReturn: true,
10267
- lineBreakIndent: null,
10268
- name: null
10269
- });
10270
- code.prependLeft(this.end, `.then(${left}n.${namespaceExportName}${right})`);
10302
+ if (this.resolutionString) {
10303
+ code.overwrite(this.source.start, this.source.end, this.resolutionString);
10304
+ if (this.namespaceExportName) {
10305
+ const [left, right] = getDirectReturnFunction(['n'], {
10306
+ functionReturn: true,
10307
+ lineBreakIndent: null,
10308
+ name: null
10309
+ });
10310
+ code.prependLeft(this.end, `.then(${left}n.${this.namespaceExportName}${right})`);
10311
+ }
10312
+ }
10313
+ else {
10314
+ this.source.render(code, options);
10271
10315
  }
10272
10316
  }
10273
- setExternalResolution(exportMode, resolution, options, snippets, pluginDriver, accessedGlobalsByScope) {
10317
+ setExternalResolution(exportMode, resolution, options, snippets, pluginDriver, accessedGlobalsByScope, resolutionString, namespaceExportName) {
10274
10318
  const { format } = options;
10275
10319
  this.resolution = resolution;
10320
+ this.resolutionString = resolutionString;
10321
+ this.namespaceExportName = namespaceExportName;
10276
10322
  const accessedGlobals = [...(accessedImportGlobals[format] || [])];
10277
10323
  let helper;
10278
10324
  ({ helper, mechanism: this.mechanism } = this.getDynamicImportMechanismAndHelper(resolution, exportMode, options, snippets, pluginDriver));
@@ -10567,25 +10613,17 @@ class LogicalExpression extends NodeBase {
10567
10613
  }
10568
10614
  }
10569
10615
 
10570
- const ASSET_PREFIX = 'ROLLUP_ASSET_URL_';
10571
- const CHUNK_PREFIX = 'ROLLUP_CHUNK_URL_';
10572
10616
  const FILE_PREFIX = 'ROLLUP_FILE_URL_';
10573
10617
  class MetaProperty extends NodeBase {
10574
- addAccessedGlobals(format, accessedGlobalsByScope) {
10575
- const metaProperty = this.metaProperty;
10576
- const accessedGlobals = (metaProperty &&
10577
- (metaProperty.startsWith(FILE_PREFIX) ||
10578
- metaProperty.startsWith(ASSET_PREFIX) ||
10579
- metaProperty.startsWith(CHUNK_PREFIX))
10580
- ? accessedFileUrlGlobals
10581
- : accessedMetaUrlGlobals)[format];
10582
- if (accessedGlobals.length > 0) {
10583
- this.scope.addAccessedGlobals(accessedGlobals, accessedGlobalsByScope);
10584
- }
10618
+ constructor() {
10619
+ super(...arguments);
10620
+ this.metaProperty = null;
10621
+ this.preliminaryChunkId = null;
10622
+ this.referenceId = null;
10585
10623
  }
10586
10624
  getReferencedFileName(outputPluginDriver) {
10587
- const metaProperty = this.metaProperty;
10588
- if (metaProperty && metaProperty.startsWith(FILE_PREFIX)) {
10625
+ const { metaProperty } = this;
10626
+ if (metaProperty === null || metaProperty === void 0 ? void 0 : metaProperty.startsWith(FILE_PREFIX)) {
10589
10627
  return outputPluginDriver.getFileName(metaProperty.substring(FILE_PREFIX.length));
10590
10628
  }
10591
10629
  return null;
@@ -10602,71 +10640,37 @@ class MetaProperty extends NodeBase {
10602
10640
  if (this.meta.name === 'import') {
10603
10641
  this.context.addImportMeta(this);
10604
10642
  const parent = this.parent;
10605
- this.metaProperty =
10643
+ const metaProperty = (this.metaProperty =
10606
10644
  parent instanceof MemberExpression && typeof parent.propertyKey === 'string'
10607
10645
  ? parent.propertyKey
10608
- : null;
10646
+ : null);
10647
+ if (metaProperty === null || metaProperty === void 0 ? void 0 : metaProperty.startsWith(FILE_PREFIX)) {
10648
+ this.referenceId = metaProperty.substring(FILE_PREFIX.length);
10649
+ }
10609
10650
  }
10610
10651
  }
10611
10652
  }
10612
- renderFinalMechanism(code, chunkId, format, snippets, outputPluginDriver) {
10653
+ render(code, { format, pluginDriver, snippets }) {
10613
10654
  var _a;
10614
- const parent = this.parent;
10615
- const metaProperty = this.metaProperty;
10616
- if (metaProperty &&
10617
- (metaProperty.startsWith(FILE_PREFIX) ||
10618
- metaProperty.startsWith(ASSET_PREFIX) ||
10619
- metaProperty.startsWith(CHUNK_PREFIX))) {
10620
- let referenceId = null;
10621
- let assetReferenceId = null;
10622
- let chunkReferenceId = null;
10623
- let fileName;
10624
- if (metaProperty.startsWith(FILE_PREFIX)) {
10625
- referenceId = metaProperty.substring(FILE_PREFIX.length);
10626
- fileName = outputPluginDriver.getFileName(referenceId);
10627
- }
10628
- else if (metaProperty.startsWith(ASSET_PREFIX)) {
10629
- warnDeprecation(`Using the "${ASSET_PREFIX}" prefix to reference files is deprecated. Use the "${FILE_PREFIX}" prefix instead.`, true, this.context.options);
10630
- assetReferenceId = metaProperty.substring(ASSET_PREFIX.length);
10631
- fileName = outputPluginDriver.getFileName(assetReferenceId);
10632
- }
10633
- else {
10634
- warnDeprecation(`Using the "${CHUNK_PREFIX}" prefix to reference files is deprecated. Use the "${FILE_PREFIX}" prefix instead.`, true, this.context.options);
10635
- chunkReferenceId = metaProperty.substring(CHUNK_PREFIX.length);
10636
- fileName = outputPluginDriver.getFileName(chunkReferenceId);
10637
- }
10655
+ const { metaProperty, parent, referenceId } = this;
10656
+ const chunkId = this.preliminaryChunkId;
10657
+ if (referenceId) {
10658
+ const fileName = pluginDriver.getFileName(referenceId);
10638
10659
  const relativePath = normalize(relative$1(dirname(chunkId), fileName));
10639
- let replacement;
10640
- if (assetReferenceId !== null) {
10641
- replacement = outputPluginDriver.hookFirstSync('resolveAssetUrl', [
10642
- {
10643
- assetFileName: fileName,
10644
- chunkId,
10645
- format,
10646
- moduleId: this.context.module.id,
10647
- relativeAssetPath: relativePath
10648
- }
10649
- ]);
10650
- }
10651
- if (!replacement) {
10652
- replacement =
10653
- outputPluginDriver.hookFirstSync('resolveFileUrl', [
10654
- {
10655
- assetReferenceId,
10656
- chunkId,
10657
- chunkReferenceId,
10658
- fileName,
10659
- format,
10660
- moduleId: this.context.module.id,
10661
- referenceId: referenceId || assetReferenceId || chunkReferenceId,
10662
- relativePath
10663
- }
10664
- ]) || relativeUrlMechanisms[format](relativePath);
10665
- }
10660
+ const replacement = pluginDriver.hookFirstSync('resolveFileUrl', [
10661
+ {
10662
+ chunkId,
10663
+ fileName,
10664
+ format,
10665
+ moduleId: this.context.module.id,
10666
+ referenceId,
10667
+ relativePath
10668
+ }
10669
+ ]) || relativeUrlMechanisms[format](relativePath);
10666
10670
  code.overwrite(parent.start, parent.end, replacement, { contentOnly: true });
10667
10671
  return;
10668
10672
  }
10669
- const replacement = outputPluginDriver.hookFirstSync('resolveImportMeta', [
10673
+ const replacement = pluginDriver.hookFirstSync('resolveImportMeta', [
10670
10674
  metaProperty,
10671
10675
  {
10672
10676
  chunkId,
@@ -10683,6 +10687,14 @@ class MetaProperty extends NodeBase {
10683
10687
  }
10684
10688
  }
10685
10689
  }
10690
+ setResolution(format, accessedGlobalsByScope, preliminaryChunkId) {
10691
+ var _a;
10692
+ this.preliminaryChunkId = preliminaryChunkId;
10693
+ const accessedGlobals = (((_a = this.metaProperty) === null || _a === void 0 ? void 0 : _a.startsWith(FILE_PREFIX)) ? accessedFileUrlGlobals : accessedMetaUrlGlobals)[format];
10694
+ if (accessedGlobals.length > 0) {
10695
+ this.scope.addAccessedGlobals(accessedGlobals, accessedGlobalsByScope);
10696
+ }
10697
+ }
10686
10698
  }
10687
10699
  const accessedMetaUrlGlobals = {
10688
10700
  amd: ['document', 'module', 'URL'],
@@ -12328,7 +12340,6 @@ class Module {
12328
12340
  this.needsExportShim = false;
12329
12341
  this.sideEffectDependenciesByVariable = new Map();
12330
12342
  this.sources = new Set();
12331
- this.usesTopLevelAwait = false;
12332
12343
  this.allExportNames = null;
12333
12344
  this.ast = null;
12334
12345
  this.exportAllModules = [];
@@ -12373,7 +12384,7 @@ class Module {
12373
12384
  return module.exports.has('default') || reexportDescriptions.has('default');
12374
12385
  },
12375
12386
  get hasModuleSideEffects() {
12376
- warnDeprecation('Accessing ModuleInfo.hasModuleSideEffects from plugins is deprecated. Please use ModuleInfo.moduleSideEffects instead.', false, options);
12387
+ warnDeprecation('Accessing ModuleInfo.hasModuleSideEffects from plugins is deprecated. Please use ModuleInfo.moduleSideEffects instead.', true, options);
12377
12388
  return this.moduleSideEffects;
12378
12389
  },
12379
12390
  id,
@@ -12685,10 +12696,14 @@ class Module {
12685
12696
  this.exportAllModules.push(...externalExportAllModules);
12686
12697
  }
12687
12698
  render(options) {
12688
- const magicString = this.magicString.clone();
12689
- this.ast.render(magicString, options);
12690
- this.usesTopLevelAwait = this.astContext.usesTopLevelAwait;
12691
- return magicString;
12699
+ const source = this.magicString.clone();
12700
+ this.ast.render(source, options);
12701
+ source.trim();
12702
+ const { usesTopLevelAwait } = this.astContext;
12703
+ if (usesTopLevelAwait && options.format !== 'es' && options.format !== 'system') {
12704
+ return error(errInvalidFormatForTopLevelAwait(this.id, options.format));
12705
+ }
12706
+ return { source, usesTopLevelAwait };
12692
12707
  }
12693
12708
  setSource({ ast, code, customTransformCache, originalCode, originalSourcemap, resolvedIds, sourcemapChain, transformDependencies, transformFiles, ...moduleOptions }) {
12694
12709
  this.info.code = code;
@@ -13122,11 +13137,11 @@ function getExportBlock$1(exports, dependencies, namedExportsMode, interop, snip
13122
13137
  return `${n}${n}${mechanism}${getSingleDefaultExport(exports, dependencies, interop, externalLiveBindings, getPropertyAccess)};`;
13123
13138
  }
13124
13139
  let exportBlock = '';
13125
- for (const { defaultVariableName, id, isChunk, name, namedExportsMode: depNamedExportsMode, namespaceVariableName, reexports } of dependencies) {
13140
+ for (const { defaultVariableName, importPath, isChunk, name, namedExportsMode: depNamedExportsMode, namespaceVariableName, reexports } of dependencies) {
13126
13141
  if (reexports && namedExportsMode) {
13127
13142
  for (const specifier of reexports) {
13128
13143
  if (specifier.reexported !== '*') {
13129
- const importName = getReexportedImportName(name, specifier.imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, id, externalLiveBindings, getPropertyAccess);
13144
+ const importName = getReexportedImportName(name, specifier.imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, importPath, externalLiveBindings, getPropertyAccess);
13130
13145
  if (exportBlock)
13131
13146
  exportBlock += n;
13132
13147
  if (specifier.imported !== '*' && specifier.needsLiveBinding) {
@@ -13184,9 +13199,9 @@ function getSingleDefaultExport(exports, dependencies, interop, externalLiveBind
13184
13199
  return exports[0].local;
13185
13200
  }
13186
13201
  else {
13187
- for (const { defaultVariableName, id, isChunk, name, namedExportsMode: depNamedExportsMode, namespaceVariableName, reexports } of dependencies) {
13202
+ for (const { defaultVariableName, importPath, isChunk, name, namedExportsMode: depNamedExportsMode, namespaceVariableName, reexports } of dependencies) {
13188
13203
  if (reexports) {
13189
- return getReexportedImportName(name, reexports[0].imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, id, externalLiveBindings, getPropertyAccess);
13204
+ return getReexportedImportName(name, reexports[0].imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, importPath, externalLiveBindings, getPropertyAccess);
13190
13205
  }
13191
13206
  }
13192
13207
  }
@@ -13261,7 +13276,7 @@ function getInteropBlock(dependencies, interop, externalLiveBindings, freeze, na
13261
13276
  neededInteropHelpers.add(helper);
13262
13277
  interopStatements.push(`${cnst} ${helperVariableName}${_}=${_}/*#__PURE__*/${helper}(${dependencyVariableName});`);
13263
13278
  };
13264
- for (const { defaultVariableName, imports, id, isChunk, name, namedExportsMode, namespaceVariableName, reexports } of dependencies) {
13279
+ for (const { defaultVariableName, imports, importPath, isChunk, name, namedExportsMode, namespaceVariableName, reexports } of dependencies) {
13265
13280
  if (isChunk) {
13266
13281
  for (const { imported, reexported } of [
13267
13282
  ...(imports || []),
@@ -13276,7 +13291,7 @@ function getInteropBlock(dependencies, interop, externalLiveBindings, freeze, na
13276
13291
  }
13277
13292
  }
13278
13293
  else {
13279
- const moduleInterop = String(interop(id));
13294
+ const moduleInterop = String(interop(importPath));
13280
13295
  let hasDefault = false;
13281
13296
  let hasNamespace = false;
13282
13297
  for (const { imported, reexported } of [
@@ -13341,7 +13356,9 @@ const builtins = {
13341
13356
  zlib: true
13342
13357
  };
13343
13358
  function warnOnBuiltins(warn, dependencies) {
13344
- const externalBuiltins = dependencies.map(({ id }) => id).filter(id => id in builtins);
13359
+ const externalBuiltins = dependencies
13360
+ .map(({ importPath }) => importPath)
13361
+ .filter(importPath => importPath in builtins);
13345
13362
  if (!externalBuiltins.length)
13346
13363
  return;
13347
13364
  warn({
@@ -13351,9 +13368,9 @@ function warnOnBuiltins(warn, dependencies) {
13351
13368
  });
13352
13369
  }
13353
13370
 
13354
- function amd(magicString, { accessedGlobals, dependencies, exports, hasExports, id, indent: t, intro, isEntryFacade, isModuleFacade, namedExportsMode, outro, snippets, warn }, { amd, esModule, externalLiveBindings, freeze, interop, namespaceToStringTag, strict }) {
13355
- warnOnBuiltins(warn, dependencies);
13356
- const deps = dependencies.map(m => `'${removeExtensionFromRelativeAmdId(m.id)}'`);
13371
+ function amd(magicString, { accessedGlobals, dependencies, exports, hasExports, id, indent: t, intro, isEntryFacade, isModuleFacade, namedExportsMode, outro, snippets, onwarn }, { amd, esModule, externalLiveBindings, freeze, interop, namespaceToStringTag, strict }) {
13372
+ warnOnBuiltins(onwarn, dependencies);
13373
+ const deps = dependencies.map(m => `'${removeExtensionFromRelativeAmdId(m.importPath)}'`);
13357
13374
  const args = dependencies.map(m => m.name);
13358
13375
  const { n, getNonArrowFunctionIntro, _ } = snippets;
13359
13376
  if (namedExportsMode && hasExports) {
@@ -13378,8 +13395,8 @@ function amd(magicString, { accessedGlobals, dependencies, exports, hasExports,
13378
13395
  if (namespaceMarkers) {
13379
13396
  namespaceMarkers = n + n + namespaceMarkers;
13380
13397
  }
13381
- magicString.append(`${exportBlock}${namespaceMarkers}${outro}`);
13382
- return (magicString
13398
+ magicString
13399
+ .append(`${exportBlock}${namespaceMarkers}${outro}`)
13383
13400
  .indent(t)
13384
13401
  // factory function should be wrapped by parentheses to avoid lazy parsing,
13385
13402
  // cf. https://v8.dev/blog/preparser#pife
@@ -13387,7 +13404,7 @@ function amd(magicString, { accessedGlobals, dependencies, exports, hasExports,
13387
13404
  isAsync: false,
13388
13405
  name: null
13389
13406
  })}{${useStrict}${n}${n}`)
13390
- .append(`${n}${n}}));`));
13407
+ .append(`${n}${n}}));`);
13391
13408
  }
13392
13409
 
13393
13410
  function cjs(magicString, { accessedGlobals, dependencies, exports, hasExports, indent: t, intro, isEntryFacade, isModuleFacade, namedExportsMode, outro, snippets }, { compact, esModule, externalLiveBindings, freeze, interop, namespaceToStringTag, strict }) {
@@ -13401,23 +13418,23 @@ function cjs(magicString, { accessedGlobals, dependencies, exports, hasExports,
13401
13418
  const interopBlock = getInteropBlock(dependencies, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, t, snippets);
13402
13419
  magicString.prepend(`${useStrict}${intro}${namespaceMarkers}${importBlock}${interopBlock}`);
13403
13420
  const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings, `module.exports${_}=${_}`);
13404
- return magicString.append(`${exportBlock}${outro}`);
13421
+ magicString.append(`${exportBlock}${outro}`);
13405
13422
  }
13406
13423
  function getImportBlock$1(dependencies, { _, cnst, n }, compact) {
13407
13424
  let importBlock = '';
13408
13425
  let definingVariable = false;
13409
- for (const { id, name, reexports, imports } of dependencies) {
13426
+ for (const { importPath, name, reexports, imports } of dependencies) {
13410
13427
  if (!reexports && !imports) {
13411
13428
  if (importBlock) {
13412
13429
  importBlock += compact && !definingVariable ? ',' : `;${n}`;
13413
13430
  }
13414
13431
  definingVariable = false;
13415
- importBlock += `require('${id}')`;
13432
+ importBlock += `require('${importPath}')`;
13416
13433
  }
13417
13434
  else {
13418
13435
  importBlock += compact && definingVariable ? ',' : `${importBlock ? `;${n}` : ''}${cnst} `;
13419
13436
  definingVariable = true;
13420
- importBlock += `${name}${_}=${_}require('${id}')`;
13437
+ importBlock += `${name}${_}=${_}require('${importPath}')`;
13421
13438
  }
13422
13439
  }
13423
13440
  if (importBlock) {
@@ -13439,13 +13456,13 @@ function es(magicString, { accessedGlobals, indent: t, intro, outro, dependencie
13439
13456
  magicString.append(n + n + exportBlock.join(n).trim());
13440
13457
  if (outro)
13441
13458
  magicString.append(outro);
13442
- return magicString.trim();
13459
+ magicString.trim();
13443
13460
  }
13444
13461
  function getImportBlock(dependencies, _) {
13445
13462
  const importBlock = [];
13446
- for (const { id, reexports, imports, name } of dependencies) {
13463
+ for (const { importPath, reexports, imports, name } of dependencies) {
13447
13464
  if (!reexports && !imports) {
13448
- importBlock.push(`import${_}'${id}';`);
13465
+ importBlock.push(`import${_}'${importPath}';`);
13449
13466
  continue;
13450
13467
  }
13451
13468
  if (imports) {
@@ -13464,10 +13481,10 @@ function getImportBlock(dependencies, _) {
13464
13481
  }
13465
13482
  }
13466
13483
  if (starImport) {
13467
- importBlock.push(`import${_}*${_}as ${starImport.local} from${_}'${id}';`);
13484
+ importBlock.push(`import${_}*${_}as ${starImport.local} from${_}'${importPath}';`);
13468
13485
  }
13469
13486
  if (defaultImport && importedNames.length === 0) {
13470
- importBlock.push(`import ${defaultImport.local} from${_}'${id}';`);
13487
+ importBlock.push(`import ${defaultImport.local} from${_}'${importPath}';`);
13471
13488
  }
13472
13489
  else if (importedNames.length > 0) {
13473
13490
  importBlock.push(`import ${defaultImport ? `${defaultImport.local},${_}` : ''}{${_}${importedNames
@@ -13479,7 +13496,7 @@ function getImportBlock(dependencies, _) {
13479
13496
  return `${specifier.imported} as ${specifier.local}`;
13480
13497
  }
13481
13498
  })
13482
- .join(`,${_}`)}${_}}${_}from${_}'${id}';`);
13499
+ .join(`,${_}`)}${_}}${_}from${_}'${importPath}';`);
13483
13500
  }
13484
13501
  }
13485
13502
  if (reexports) {
@@ -13498,12 +13515,12 @@ function getImportBlock(dependencies, _) {
13498
13515
  }
13499
13516
  }
13500
13517
  if (starExport) {
13501
- importBlock.push(`export${_}*${_}from${_}'${id}';`);
13518
+ importBlock.push(`export${_}*${_}from${_}'${importPath}';`);
13502
13519
  }
13503
13520
  if (namespaceReexports.length > 0) {
13504
13521
  if (!imports ||
13505
13522
  !imports.some(specifier => specifier.imported === '*' && specifier.local === name)) {
13506
- importBlock.push(`import${_}*${_}as ${name} from${_}'${id}';`);
13523
+ importBlock.push(`import${_}*${_}as ${name} from${_}'${importPath}';`);
13507
13524
  }
13508
13525
  for (const specifier of namespaceReexports) {
13509
13526
  importBlock.push(`export${_}{${_}${name === specifier.reexported ? name : `${name} as ${specifier.reexported}`} };`);
@@ -13519,7 +13536,7 @@ function getImportBlock(dependencies, _) {
13519
13536
  return `${specifier.imported} as ${specifier.reexported}`;
13520
13537
  }
13521
13538
  })
13522
- .join(`,${_}`)}${_}}${_}from${_}'${id}';`);
13539
+ .join(`,${_}`)}${_}}${_}from${_}'${importPath}';`);
13523
13540
  }
13524
13541
  }
13525
13542
  }
@@ -13585,7 +13602,7 @@ function trimEmptyImports(dependencies) {
13585
13602
  return [];
13586
13603
  }
13587
13604
 
13588
- function iife(magicString, { accessedGlobals, dependencies, exports, hasExports, indent: t, intro, namedExportsMode, outro, snippets, warn }, { compact, esModule, extend, freeze, externalLiveBindings, globals, interop, name, namespaceToStringTag, strict }) {
13605
+ function iife(magicString, { accessedGlobals, dependencies, exports, hasExports, indent: t, intro, namedExportsMode, outro, snippets, onwarn }, { compact, esModule, extend, freeze, externalLiveBindings, globals, interop, name, namespaceToStringTag, strict }) {
13589
13606
  const { _, cnst, getNonArrowFunctionIntro, getPropertyAccess, n } = snippets;
13590
13607
  const isNamespaced = name && name.includes('.');
13591
13608
  const useVariableAssignment = !extend && !isNamespaced;
@@ -13595,12 +13612,12 @@ function iife(magicString, { accessedGlobals, dependencies, exports, hasExports,
13595
13612
  message: `Given name "${name}" is not a legal JS identifier. If you need this, you can try "output.extend: true".`
13596
13613
  });
13597
13614
  }
13598
- warnOnBuiltins(warn, dependencies);
13615
+ warnOnBuiltins(onwarn, dependencies);
13599
13616
  const external = trimEmptyImports(dependencies);
13600
13617
  const deps = external.map(dep => dep.globalName || 'null');
13601
13618
  const args = external.map(m => m.name);
13602
13619
  if (hasExports && !name) {
13603
- warn({
13620
+ onwarn({
13604
13621
  code: 'MISSING_NAME_OPTION_FOR_IIFE_EXPORT',
13605
13622
  message: `If you do not supply "output.name", you may not be able to access the exports of an IIFE bundle.`
13606
13623
  });
@@ -13641,8 +13658,11 @@ function iife(magicString, { accessedGlobals, dependencies, exports, hasExports,
13641
13658
  if (namespaceMarkers) {
13642
13659
  namespaceMarkers = n + n + namespaceMarkers;
13643
13660
  }
13644
- magicString.append(`${exportBlock}${namespaceMarkers}${outro}`);
13645
- return magicString.indent(t).prepend(wrapperIntro).append(wrapperOutro);
13661
+ magicString
13662
+ .append(`${exportBlock}${namespaceMarkers}${outro}`)
13663
+ .indent(t)
13664
+ .prepend(wrapperIntro)
13665
+ .append(wrapperOutro);
13646
13666
  }
13647
13667
 
13648
13668
  function system(magicString, { accessedGlobals, dependencies, exports, hasExports, indent: t, intro, snippets, outro, usesTopLevelAwait }, { externalLiveBindings, freeze, name, namespaceToStringTag, strict, systemNullSetters }) {
@@ -13657,7 +13677,7 @@ function system(magicString, { accessedGlobals, dependencies, exports, hasExport
13657
13677
  // factory function should be wrapped by parentheses to avoid lazy parsing,
13658
13678
  // cf. https://v8.dev/blog/preparser#pife
13659
13679
  let wrapperStart = `System.register(${registeredName}[` +
13660
- dependencies.map(({ id }) => `'${id}'`).join(`,${_}`) +
13680
+ dependencies.map(({ importPath }) => `'${importPath}'`).join(`,${_}`) +
13661
13681
  `],${_}(${getNonArrowFunctionIntro(wrapperParams, { isAsync: false, name: null })}{${n}${t}${strict ? "'use strict';" : ''}` +
13662
13682
  getStarExcludesBlock(starExcludes, t, snippets) +
13663
13683
  getImportBindingsBlock(importBindings, t, snippets) +
@@ -13678,13 +13698,16 @@ function system(magicString, { accessedGlobals, dependencies, exports, hasExport
13678
13698
  name: null
13679
13699
  })}{${n}${n}`;
13680
13700
  const wrapperEnd = `${t}${t}})${n}${t}}${s}${n}}));`;
13681
- magicString.prepend(intro +
13701
+ magicString
13702
+ .prepend(intro +
13682
13703
  getHelpersBlock(null, accessedGlobals, t, snippets, externalLiveBindings, freeze, namespaceToStringTag) +
13683
- getHoistedExportsBlock(exports, t, snippets));
13684
- magicString.append(`${outro}${n}${n}` +
13704
+ getHoistedExportsBlock(exports, t, snippets))
13705
+ .append(`${outro}${n}${n}` +
13685
13706
  getSyntheticExportsBlock(exports, t, snippets) +
13686
- getMissingExportsBlock(exports, t, snippets));
13687
- return magicString.indent(`${t}${t}${t}`).append(wrapperEnd).prepend(wrapperStart);
13707
+ getMissingExportsBlock(exports, t, snippets))
13708
+ .indent(`${t}${t}${t}`)
13709
+ .append(wrapperEnd)
13710
+ .prepend(wrapperStart);
13688
13711
  }
13689
13712
  function analyzeDependencies(dependencies, exports, t, { _, cnst, getObject, getPropertyAccess, n }) {
13690
13713
  const importBindings = [];
@@ -13786,7 +13809,7 @@ function safeAccess(name, globalVar, { _, getPropertyAccess }) {
13786
13809
  .map(part => (propertyPath += getPropertyAccess(part)))
13787
13810
  .join(`${_}&&${_}`);
13788
13811
  }
13789
- 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 }) {
13812
+ 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 }) {
13790
13813
  const { _, cnst, getFunctionIntro, getNonArrowFunctionIntro, getPropertyAccess, n, s } = snippets;
13791
13814
  const factoryVar = compact ? 'f' : 'factory';
13792
13815
  const globalVar = compact ? 'g' : 'global';
@@ -13796,9 +13819,9 @@ function umd(magicString, { accessedGlobals, dependencies, exports, hasExports,
13796
13819
  message: 'You must supply "output.name" for UMD bundles that have exports so that the exports are accessible in environments without a module loader.'
13797
13820
  });
13798
13821
  }
13799
- warnOnBuiltins(warn, dependencies);
13800
- const amdDeps = dependencies.map(m => `'${removeExtensionFromRelativeAmdId(m.id)}'`);
13801
- const cjsDeps = dependencies.map(m => `require('${m.id}')`);
13822
+ warnOnBuiltins(onwarn, dependencies);
13823
+ const amdDeps = dependencies.map(m => `'${removeExtensionFromRelativeAmdId(m.importPath)}'`);
13824
+ const cjsDeps = dependencies.map(m => `require('${m.importPath}')`);
13802
13825
  const trimmedImports = trimEmptyImports(dependencies);
13803
13826
  const globalDeps = trimmedImports.map(module => globalProp(module.globalName, globalVar, getPropertyAccess));
13804
13827
  const factoryParams = trimmedImports.map(m => m.name);
@@ -13875,193 +13898,352 @@ function umd(magicString, { accessedGlobals, dependencies, exports, hasExports,
13875
13898
  if (namespaceMarkers) {
13876
13899
  namespaceMarkers = n + n + namespaceMarkers;
13877
13900
  }
13878
- magicString.append(`${exportBlock}${namespaceMarkers}${outro}`);
13879
- return magicString.trim().indent(t).append(wrapperOutro).prepend(wrapperIntro);
13901
+ magicString
13902
+ .append(`${exportBlock}${namespaceMarkers}${outro}`)
13903
+ .trim()
13904
+ .indent(t)
13905
+ .append(wrapperOutro)
13906
+ .prepend(wrapperIntro);
13880
13907
  }
13881
13908
 
13882
13909
  const finalisers = { amd, cjs, es, iife, system, umd };
13883
13910
 
13884
- class Source {
13885
- constructor(filename, content) {
13886
- this.isOriginal = true;
13887
- this.filename = filename;
13888
- this.content = content;
13911
+ const createHash = () => createHash$1('sha256');
13912
+
13913
+ // Four random characters from the private use area to minimize risk of conflicts
13914
+ const hashPlaceholderLeft = '\uf7f9\ue4d3';
13915
+ const hashPlaceholderRight = '\ue3cc\uf1fe';
13916
+ const hashPlaceholderOverhead = hashPlaceholderLeft.length + hashPlaceholderRight.length;
13917
+ // This is the size of a sha256
13918
+ const maxHashSize = 64;
13919
+ const defaultHashSize = 8;
13920
+ const getHashPlaceholderGenerator = () => {
13921
+ let nextIndex = 0;
13922
+ return (optionName, hashSize = defaultHashSize) => {
13923
+ if (hashSize > maxHashSize) {
13924
+ return error(errFailedValidation(`Hashes cannot be longer than ${maxHashSize} characters, received ${hashSize}. Check the "${optionName}" option.`));
13925
+ }
13926
+ const placeholder = `${hashPlaceholderLeft}${String(++nextIndex).padStart(hashSize - hashPlaceholderOverhead, '0')}${hashPlaceholderRight}`;
13927
+ if (placeholder.length > hashSize) {
13928
+ 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.`));
13929
+ }
13930
+ nextIndex++;
13931
+ return placeholder;
13932
+ };
13933
+ };
13934
+ const REPLACER_REGEX = new RegExp(`${hashPlaceholderLeft}\\d{1,${maxHashSize - hashPlaceholderOverhead}}${hashPlaceholderRight}`, 'g');
13935
+ const replacePlaceholders = (code, hashesByPlaceholder) => code.replace(REPLACER_REGEX, placeholder => hashesByPlaceholder.get(placeholder) || placeholder);
13936
+ const replaceSinglePlaceholder = (code, placeholder, value) => code.replace(REPLACER_REGEX, match => (match === placeholder ? value : match));
13937
+ const replacePlaceholdersWithDefaultAndGetContainedPlaceholders = (code, placeholders) => {
13938
+ const containedPlaceholders = new Set();
13939
+ const transformedCode = code.replace(REPLACER_REGEX, placeholder => {
13940
+ if (placeholders.has(placeholder)) {
13941
+ containedPlaceholders.add(placeholder);
13942
+ return `${hashPlaceholderLeft}${'0'.repeat(placeholder.length - hashPlaceholderOverhead)}${hashPlaceholderRight}`;
13943
+ }
13944
+ return placeholder;
13945
+ });
13946
+ return { containedPlaceholders, transformedCode };
13947
+ };
13948
+
13949
+ function renderNamePattern(pattern, patternName, replacements) {
13950
+ if (isPathFragment(pattern))
13951
+ return error(errFailedValidation(`Invalid pattern "${pattern}" for "${patternName}", patterns can be neither absolute nor relative paths.`));
13952
+ return pattern.replace(/\[(\w+)(:\d+)?]/g, (_match, type, size) => {
13953
+ if (!replacements.hasOwnProperty(type) || (size && type !== 'hash')) {
13954
+ return error(errFailedValidation(`"[${type}${size || ''}]" is not a valid placeholder in the "${patternName}" pattern.`));
13955
+ }
13956
+ const replacement = replacements[type](size && parseInt(size.slice(1)));
13957
+ if (isPathFragment(replacement))
13958
+ return error(errFailedValidation(`Invalid substitution "${replacement}" for placeholder "[${type}]" in "${patternName}" pattern, can be neither absolute nor relative path.`));
13959
+ return replacement;
13960
+ });
13961
+ }
13962
+ function makeUnique(name, existingNames) {
13963
+ const existingNamesLowercase = new Set(Object.keys(existingNames).map(key => key.toLowerCase()));
13964
+ if (!existingNamesLowercase.has(name.toLocaleLowerCase()))
13965
+ return name;
13966
+ const ext = extname(name);
13967
+ name = name.substring(0, name.length - ext.length);
13968
+ let uniqueName, uniqueIndex = 1;
13969
+ while (existingNamesLowercase.has((uniqueName = name + ++uniqueIndex + ext).toLowerCase()))
13970
+ ;
13971
+ return uniqueName;
13972
+ }
13973
+
13974
+ function generateAssetFileName(name, source, outputOptions, bundle) {
13975
+ const emittedName = outputOptions.sanitizeFileName(name || 'asset');
13976
+ return makeUnique(renderNamePattern(typeof outputOptions.assetFileNames === 'function'
13977
+ ? outputOptions.assetFileNames({ name, source, type: 'asset' })
13978
+ : outputOptions.assetFileNames, 'output.assetFileNames', {
13979
+ ext: () => extname(emittedName).substring(1),
13980
+ extname: () => extname(emittedName),
13981
+ hash: size => createHash()
13982
+ .update(source)
13983
+ .digest('hex')
13984
+ .substring(0, size || defaultHashSize),
13985
+ name: () => emittedName.substring(0, emittedName.length - extname(emittedName).length)
13986
+ }), bundle);
13987
+ }
13988
+ function reserveFileNameInBundle(fileName, bundle, warn) {
13989
+ if (fileName in bundle) {
13990
+ warn(errFileNameConflict(fileName));
13889
13991
  }
13890
- traceSegment(line, column, name) {
13891
- return { column, line, name, source: this };
13992
+ bundle[fileName] = FILE_PLACEHOLDER;
13993
+ }
13994
+ const FILE_PLACEHOLDER = {
13995
+ type: 'placeholder'
13996
+ };
13997
+ function hasValidType(emittedFile) {
13998
+ return Boolean(emittedFile &&
13999
+ (emittedFile.type === 'asset' ||
14000
+ emittedFile.type === 'chunk'));
14001
+ }
14002
+ function hasValidName(emittedFile) {
14003
+ const validatedName = emittedFile.fileName || emittedFile.name;
14004
+ return !validatedName || (typeof validatedName === 'string' && !isPathFragment(validatedName));
14005
+ }
14006
+ function getValidSource(source, emittedFile, fileReferenceId) {
14007
+ if (!(typeof source === 'string' || source instanceof Uint8Array)) {
14008
+ const assetName = emittedFile.fileName || emittedFile.name || fileReferenceId;
14009
+ 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.`));
13892
14010
  }
14011
+ return source;
13893
14012
  }
13894
- class Link {
13895
- constructor(map, sources) {
13896
- this.sources = sources;
13897
- this.names = map.names;
13898
- this.mappings = map.mappings;
14013
+ function getAssetFileName(file, referenceId) {
14014
+ if (typeof file.fileName !== 'string') {
14015
+ return error(errAssetNotFinalisedForFileName(file.name || referenceId));
13899
14016
  }
13900
- traceMappings() {
13901
- const sources = [];
13902
- const sourceIndexMap = new Map();
13903
- const sourcesContent = [];
13904
- const names = [];
13905
- const nameIndexMap = new Map();
13906
- const mappings = [];
13907
- for (const line of this.mappings) {
13908
- const tracedLine = [];
13909
- for (const segment of line) {
13910
- if (segment.length === 1)
13911
- continue;
13912
- const source = this.sources[segment[1]];
13913
- if (!source)
13914
- continue;
13915
- const traced = source.traceSegment(segment[2], segment[3], segment.length === 5 ? this.names[segment[4]] : '');
13916
- if (traced) {
13917
- const { column, line, name, source: { content, filename } } = traced;
13918
- let sourceIndex = sourceIndexMap.get(filename);
13919
- if (sourceIndex === undefined) {
13920
- sourceIndex = sources.length;
13921
- sources.push(filename);
13922
- sourceIndexMap.set(filename, sourceIndex);
13923
- sourcesContent[sourceIndex] = content;
13924
- }
13925
- else if (sourcesContent[sourceIndex] == null) {
13926
- sourcesContent[sourceIndex] = content;
13927
- }
13928
- else if (content != null && sourcesContent[sourceIndex] !== content) {
13929
- return error({
13930
- message: `Multiple conflicting contents for sourcemap source ${filename}`
13931
- });
13932
- }
13933
- const tracedSegment = [segment[0], sourceIndex, line, column];
13934
- if (name) {
13935
- let nameIndex = nameIndexMap.get(name);
13936
- if (nameIndex === undefined) {
13937
- nameIndex = names.length;
13938
- names.push(name);
13939
- nameIndexMap.set(name, nameIndex);
13940
- }
13941
- tracedSegment[4] = nameIndex;
13942
- }
13943
- tracedLine.push(tracedSegment);
13944
- }
13945
- }
13946
- mappings.push(tracedLine);
13947
- }
13948
- return { mappings, names, sources, sourcesContent };
14017
+ return file.fileName;
14018
+ }
14019
+ function getChunkFileName(file, facadeChunkByModule) {
14020
+ if (file.fileName) {
14021
+ return file.fileName;
13949
14022
  }
13950
- traceSegment(line, column, name) {
13951
- const segments = this.mappings[line];
13952
- if (!segments)
13953
- return null;
13954
- // binary search through segments for the given column
13955
- let searchStart = 0;
13956
- let searchEnd = segments.length - 1;
13957
- while (searchStart <= searchEnd) {
13958
- const m = (searchStart + searchEnd) >> 1;
13959
- const segment = segments[m];
13960
- // If a sourcemap does not have sufficient resolution to contain a
13961
- // necessary mapping, e.g. because it only contains line information, we
13962
- // use the best approximation we could find
13963
- if (segment[0] === column || searchStart === searchEnd) {
13964
- if (segment.length == 1)
13965
- return null;
13966
- const source = this.sources[segment[1]];
13967
- if (!source)
13968
- return null;
13969
- return source.traceSegment(segment[2], segment[3], segment.length === 5 ? this.names[segment[4]] : name);
14023
+ if (facadeChunkByModule) {
14024
+ const chunk = facadeChunkByModule.get(file.module);
14025
+ return chunk.id || chunk.getFileName();
14026
+ }
14027
+ return error(errChunkNotGeneratedForFileName(file.fileName || file.name));
14028
+ }
14029
+ class FileEmitter {
14030
+ constructor(graph, options, baseFileEmitter) {
14031
+ this.graph = graph;
14032
+ this.options = options;
14033
+ this.bundle = null;
14034
+ this.facadeChunkByModule = null;
14035
+ this.outputOptions = null;
14036
+ this.emitFile = (emittedFile) => {
14037
+ if (!hasValidType(emittedFile)) {
14038
+ return error(errFailedValidation(`Emitted files must be of type "asset" or "chunk", received "${emittedFile && emittedFile.type}".`));
13970
14039
  }
13971
- if (segment[0] > column) {
13972
- searchEnd = m - 1;
14040
+ if (!hasValidName(emittedFile)) {
14041
+ 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}".`));
14042
+ }
14043
+ if (emittedFile.type === 'chunk') {
14044
+ return this.emitChunk(emittedFile);
14045
+ }
14046
+ return this.emitAsset(emittedFile);
14047
+ };
14048
+ this.finaliseAssets = () => {
14049
+ for (const [referenceId, emittedFile] of this.filesByReferenceId) {
14050
+ if (emittedFile.type === 'asset' && typeof emittedFile.fileName !== 'string')
14051
+ return error(errNoAssetSourceSet(emittedFile.name || referenceId));
14052
+ }
14053
+ };
14054
+ this.getFileName = (fileReferenceId) => {
14055
+ const emittedFile = this.filesByReferenceId.get(fileReferenceId);
14056
+ if (!emittedFile)
14057
+ return error(errFileReferenceIdNotFoundForFilename(fileReferenceId));
14058
+ if (emittedFile.type === 'chunk') {
14059
+ return getChunkFileName(emittedFile, this.facadeChunkByModule);
14060
+ }
14061
+ return getAssetFileName(emittedFile, fileReferenceId);
14062
+ };
14063
+ this.setAssetSource = (referenceId, requestedSource) => {
14064
+ const consumedFile = this.filesByReferenceId.get(referenceId);
14065
+ if (!consumedFile)
14066
+ return error(errAssetReferenceIdNotFoundForSetSource(referenceId));
14067
+ if (consumedFile.type !== 'asset') {
14068
+ return error(errFailedValidation(`Asset sources can only be set for emitted assets but "${referenceId}" is an emitted chunk.`));
14069
+ }
14070
+ if (consumedFile.source !== undefined) {
14071
+ return error(errAssetSourceAlreadySet(consumedFile.name || referenceId));
14072
+ }
14073
+ const source = getValidSource(requestedSource, consumedFile, referenceId);
14074
+ if (this.bundle) {
14075
+ this.finalizeAsset(consumedFile, source, referenceId, this.bundle);
13973
14076
  }
13974
14077
  else {
13975
- searchStart = m + 1;
14078
+ consumedFile.source = source;
14079
+ }
14080
+ };
14081
+ this.setChunkInformation = (facadeChunkByModule) => {
14082
+ this.facadeChunkByModule = facadeChunkByModule;
14083
+ };
14084
+ this.setOutputBundle = (outputBundle, outputOptions) => {
14085
+ this.outputOptions = outputOptions;
14086
+ this.bundle = outputBundle;
14087
+ for (const emittedFile of this.filesByReferenceId.values()) {
14088
+ if (emittedFile.fileName) {
14089
+ reserveFileNameInBundle(emittedFile.fileName, this.bundle, this.options.onwarn);
14090
+ }
14091
+ }
14092
+ for (const [referenceId, consumedFile] of this.filesByReferenceId) {
14093
+ if (consumedFile.type === 'asset' && consumedFile.source !== undefined) {
14094
+ this.finalizeAsset(consumedFile, consumedFile.source, referenceId, this.bundle);
14095
+ }
14096
+ }
14097
+ };
14098
+ this.filesByReferenceId = baseFileEmitter
14099
+ ? new Map(baseFileEmitter.filesByReferenceId)
14100
+ : new Map();
14101
+ }
14102
+ assignReferenceId(file, idBase) {
14103
+ let referenceId;
14104
+ do {
14105
+ referenceId = createHash()
14106
+ .update(referenceId || idBase)
14107
+ .digest('hex')
14108
+ .substring(0, 8);
14109
+ } while (this.filesByReferenceId.has(referenceId));
14110
+ this.filesByReferenceId.set(referenceId, file);
14111
+ return referenceId;
14112
+ }
14113
+ emitAsset(emittedAsset) {
14114
+ const source = typeof emittedAsset.source !== 'undefined'
14115
+ ? getValidSource(emittedAsset.source, emittedAsset, null)
14116
+ : undefined;
14117
+ const consumedAsset = {
14118
+ fileName: emittedAsset.fileName,
14119
+ name: emittedAsset.name,
14120
+ source,
14121
+ type: 'asset'
14122
+ };
14123
+ const referenceId = this.assignReferenceId(consumedAsset, emittedAsset.fileName || emittedAsset.name || emittedAsset.type);
14124
+ if (this.bundle) {
14125
+ if (emittedAsset.fileName) {
14126
+ reserveFileNameInBundle(emittedAsset.fileName, this.bundle, this.options.onwarn);
14127
+ }
14128
+ if (source !== undefined) {
14129
+ this.finalizeAsset(consumedAsset, source, referenceId, this.bundle);
13976
14130
  }
13977
14131
  }
13978
- return null;
14132
+ return referenceId;
13979
14133
  }
13980
- }
13981
- function getLinkMap(warn) {
13982
- return function linkMap(source, map) {
13983
- if (map.mappings) {
13984
- return new Link(map, [source]);
14134
+ emitChunk(emittedChunk) {
14135
+ if (this.graph.phase > BuildPhase.LOAD_AND_PARSE) {
14136
+ return error(errInvalidRollupPhaseForChunkEmission());
13985
14137
  }
13986
- warn({
13987
- code: 'SOURCEMAP_BROKEN',
13988
- message: `Sourcemap is likely to be incorrect: a plugin (${map.plugin}) was used to transform ` +
13989
- "files, but didn't generate a sourcemap for the transformation. Consult the plugin " +
13990
- 'documentation for help',
13991
- plugin: map.plugin,
13992
- url: `https://rollupjs.org/guide/en/#warning-sourcemap-is-likely-to-be-incorrect`
14138
+ if (typeof emittedChunk.id !== 'string') {
14139
+ return error(errFailedValidation(`Emitted chunks need to have a valid string id, received "${emittedChunk.id}"`));
14140
+ }
14141
+ const consumedChunk = {
14142
+ fileName: emittedChunk.fileName,
14143
+ module: null,
14144
+ name: emittedChunk.name || emittedChunk.id,
14145
+ type: 'chunk'
14146
+ };
14147
+ this.graph.moduleLoader
14148
+ .emitChunk(emittedChunk)
14149
+ .then(module => (consumedChunk.module = module))
14150
+ .catch(() => {
14151
+ // Avoid unhandled Promise rejection as the error will be thrown later
14152
+ // once module loading has finished
13993
14153
  });
13994
- return new Link({
13995
- mappings: [],
13996
- names: []
13997
- }, [source]);
13998
- };
13999
- }
14000
- function getCollapsedSourcemap(id, originalCode, originalSourcemap, sourcemapChain, linkMap) {
14001
- let source;
14002
- if (!originalSourcemap) {
14003
- source = new Source(id, originalCode);
14154
+ return this.assignReferenceId(consumedChunk, emittedChunk.id);
14004
14155
  }
14005
- else {
14006
- const sources = originalSourcemap.sources;
14007
- const sourcesContent = originalSourcemap.sourcesContent || [];
14008
- const directory = dirname(id) || '.';
14009
- const sourceRoot = originalSourcemap.sourceRoot || '.';
14010
- const baseSources = sources.map((source, i) => new Source(resolve(directory, sourceRoot, source), sourcesContent[i]));
14011
- source = new Link(originalSourcemap, baseSources);
14156
+ finalizeAsset(consumedFile, source, referenceId, bundle) {
14157
+ const fileName = consumedFile.fileName ||
14158
+ findExistingAssetFileNameWithSource(bundle, source) ||
14159
+ generateAssetFileName(consumedFile.name, source, this.outputOptions, bundle);
14160
+ // We must not modify the original assets to avoid interaction between outputs
14161
+ const assetWithFileName = { ...consumedFile, fileName, source };
14162
+ this.filesByReferenceId.set(referenceId, assetWithFileName);
14163
+ bundle[fileName] = {
14164
+ fileName,
14165
+ name: consumedFile.name,
14166
+ source,
14167
+ type: 'asset'
14168
+ };
14012
14169
  }
14013
- return sourcemapChain.reduce(linkMap, source);
14014
14170
  }
14015
- function collapseSourcemaps(file, map, modules, bundleSourcemapChain, excludeContent, warn) {
14016
- const linkMap = getLinkMap(warn);
14017
- const moduleSources = modules
14018
- .filter(module => !module.excludeFromSourcemap)
14019
- .map(module => getCollapsedSourcemap(module.id, module.originalCode, module.originalSourcemap, module.sourcemapChain, linkMap));
14020
- const link = new Link(map, moduleSources);
14021
- const source = bundleSourcemapChain.reduce(linkMap, link);
14022
- let { sources, sourcesContent, names, mappings } = source.traceMappings();
14023
- if (file) {
14024
- const directory = dirname(file);
14025
- sources = sources.map((source) => relative$1(directory, source));
14026
- file = basename(file);
14171
+ function findExistingAssetFileNameWithSource(bundle, source) {
14172
+ for (const [fileName, outputFile] of Object.entries(bundle)) {
14173
+ if (outputFile.type === 'asset' && areSourcesEqual(source, outputFile.source))
14174
+ return fileName;
14027
14175
  }
14028
- sourcesContent = (excludeContent ? null : sourcesContent);
14029
- return new SourceMap({ file, mappings, names, sources, sourcesContent });
14176
+ return null;
14030
14177
  }
14031
- function collapseSourcemap(id, originalCode, originalSourcemap, sourcemapChain, warn) {
14032
- if (!sourcemapChain.length) {
14033
- return originalSourcemap;
14178
+ function areSourcesEqual(sourceA, sourceB) {
14179
+ if (typeof sourceA === 'string') {
14180
+ return sourceA === sourceB;
14034
14181
  }
14035
- const source = getCollapsedSourcemap(id, originalCode, originalSourcemap, sourcemapChain, getLinkMap(warn));
14036
- const map = source.traceMappings();
14037
- return { version: 3, ...map };
14038
- }
14039
-
14040
- const createHash = () => createHash$1('sha256');
14041
-
14042
- const DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT = {
14043
- amd: deconflictImportsOther,
14182
+ if (typeof sourceB === 'string') {
14183
+ return false;
14184
+ }
14185
+ if ('equals' in sourceA) {
14186
+ return sourceA.equals(sourceB);
14187
+ }
14188
+ if (sourceA.length !== sourceB.length) {
14189
+ return false;
14190
+ }
14191
+ for (let index = 0; index < sourceA.length; index++) {
14192
+ if (sourceA[index] !== sourceB[index]) {
14193
+ return false;
14194
+ }
14195
+ }
14196
+ return true;
14197
+ }
14198
+
14199
+ const concatSep = (out, next) => (next ? `${out}\n${next}` : out);
14200
+ const concatDblSep = (out, next) => (next ? `${out}\n\n${next}` : out);
14201
+ async function createAddons(options, outputPluginDriver, chunk) {
14202
+ try {
14203
+ let [banner, footer, intro, outro] = await Promise.all([
14204
+ outputPluginDriver.hookReduceValue('banner', options.banner(chunk), [chunk], concatSep),
14205
+ outputPluginDriver.hookReduceValue('footer', options.footer(chunk), [chunk], concatSep),
14206
+ outputPluginDriver.hookReduceValue('intro', options.intro(chunk), [chunk], concatDblSep),
14207
+ outputPluginDriver.hookReduceValue('outro', options.outro(chunk), [chunk], concatDblSep)
14208
+ ]);
14209
+ if (intro)
14210
+ intro += '\n\n';
14211
+ if (outro)
14212
+ outro = `\n\n${outro}`;
14213
+ if (banner)
14214
+ banner += '\n';
14215
+ if (footer)
14216
+ footer = '\n' + footer;
14217
+ return { banner, footer, intro, outro };
14218
+ }
14219
+ catch (err) {
14220
+ return error(errAddonNotGenerated(err.message, err.hook, err.plugin));
14221
+ }
14222
+ }
14223
+
14224
+ const DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT = {
14225
+ amd: deconflictImportsOther,
14044
14226
  cjs: deconflictImportsOther,
14045
14227
  es: deconflictImportsEsmOrSystem,
14046
14228
  iife: deconflictImportsOther,
14047
14229
  system: deconflictImportsEsmOrSystem,
14048
14230
  umd: deconflictImportsOther
14049
14231
  };
14050
- function deconflictChunk(modules, dependenciesToBeDeconflicted, imports, usedNames, format, interop, preserveModules, externalLiveBindings, chunkByModule, syntheticExports, exportNamesByVariable, accessedGlobalsByScope, includedNamespaces) {
14232
+ function deconflictChunk(modules, dependenciesToBeDeconflicted, imports, usedNames, format, interop, preserveModules, externalLiveBindings, chunkByModule, externalChunkByModule, syntheticExports, exportNamesByVariable, accessedGlobalsByScope, includedNamespaces) {
14051
14233
  const reversedModules = modules.slice().reverse();
14052
14234
  for (const module of reversedModules) {
14053
14235
  module.scope.addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope);
14054
14236
  }
14055
14237
  deconflictTopLevelVariables(usedNames, reversedModules, includedNamespaces);
14056
- DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT[format](usedNames, imports, dependenciesToBeDeconflicted, interop, preserveModules, externalLiveBindings, chunkByModule, syntheticExports);
14238
+ DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT[format](usedNames, imports, dependenciesToBeDeconflicted, interop, preserveModules, externalLiveBindings, chunkByModule, externalChunkByModule, syntheticExports);
14057
14239
  for (const module of reversedModules) {
14058
14240
  module.scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
14059
14241
  }
14060
14242
  }
14061
- function deconflictImportsEsmOrSystem(usedNames, imports, dependenciesToBeDeconflicted, _interop, preserveModules, _externalLiveBindings, chunkByModule, syntheticExports) {
14243
+ function deconflictImportsEsmOrSystem(usedNames, imports, dependenciesToBeDeconflicted, _interop, preserveModules, _externalLiveBindings, chunkByModule, externalChunkByModule, syntheticExports) {
14062
14244
  // This is needed for namespace reexports
14063
14245
  for (const dependency of dependenciesToBeDeconflicted.dependencies) {
14064
- if (preserveModules || dependency instanceof ExternalModule) {
14246
+ if (preserveModules || dependency instanceof ExternalChunk) {
14065
14247
  dependency.variableName = getSafeName(dependency.suggestedVariableName, usedNames);
14066
14248
  }
14067
14249
  }
@@ -14069,7 +14251,9 @@ function deconflictImportsEsmOrSystem(usedNames, imports, dependenciesToBeDeconf
14069
14251
  const module = variable.module;
14070
14252
  const name = variable.name;
14071
14253
  if (variable.isNamespace && (preserveModules || module instanceof ExternalModule)) {
14072
- variable.setRenderNames(null, (module instanceof ExternalModule ? module : chunkByModule.get(module)).variableName);
14254
+ variable.setRenderNames(null, (module instanceof ExternalModule
14255
+ ? externalChunkByModule.get(module)
14256
+ : chunkByModule.get(module)).variableName);
14073
14257
  }
14074
14258
  else if (module instanceof ExternalModule && name === 'default') {
14075
14259
  variable.setRenderNames(null, getSafeName([...module.exportedVariables].some(([exportedVariable, exportedName]) => exportedName === '*' && exportedVariable.included)
@@ -14084,12 +14268,12 @@ function deconflictImportsEsmOrSystem(usedNames, imports, dependenciesToBeDeconf
14084
14268
  variable.setRenderNames(null, getSafeName(variable.name, usedNames));
14085
14269
  }
14086
14270
  }
14087
- function deconflictImportsOther(usedNames, imports, { deconflictedDefault, deconflictedNamespace, dependencies }, interop, preserveModules, externalLiveBindings, chunkByModule) {
14088
- for (const chunkOrExternalModule of dependencies) {
14089
- chunkOrExternalModule.variableName = getSafeName(chunkOrExternalModule.suggestedVariableName, usedNames);
14271
+ function deconflictImportsOther(usedNames, imports, { deconflictedDefault, deconflictedNamespace, dependencies }, interop, preserveModules, externalLiveBindings, chunkByModule, externalChunkByModule) {
14272
+ for (const chunk of dependencies) {
14273
+ chunk.variableName = getSafeName(chunk.suggestedVariableName, usedNames);
14090
14274
  }
14091
- for (const externalModuleOrChunk of deconflictedNamespace) {
14092
- externalModuleOrChunk.namespaceVariableName = getSafeName(`${externalModuleOrChunk.suggestedVariableName}__namespace`, usedNames);
14275
+ for (const chunk of deconflictedNamespace) {
14276
+ chunk.namespaceVariableName = getSafeName(`${chunk.suggestedVariableName}__namespace`, usedNames);
14093
14277
  }
14094
14278
  for (const externalModule of deconflictedDefault) {
14095
14279
  if (deconflictedNamespace.has(externalModule) &&
@@ -14103,12 +14287,13 @@ function deconflictImportsOther(usedNames, imports, { deconflictedDefault, decon
14103
14287
  for (const variable of imports) {
14104
14288
  const module = variable.module;
14105
14289
  if (module instanceof ExternalModule) {
14290
+ const chunk = externalChunkByModule.get(module);
14106
14291
  const name = variable.name;
14107
14292
  if (name === 'default') {
14108
14293
  const moduleInterop = String(interop(module.id));
14109
14294
  const variableName = defaultInteropHelpersByInteropType[moduleInterop]
14110
- ? module.defaultVariableName
14111
- : module.variableName;
14295
+ ? chunk.defaultVariableName
14296
+ : chunk.variableName;
14112
14297
  if (isDefaultAProperty(moduleInterop, externalLiveBindings)) {
14113
14298
  variable.setRenderNames(variableName, 'default');
14114
14299
  }
@@ -14118,12 +14303,12 @@ function deconflictImportsOther(usedNames, imports, { deconflictedDefault, decon
14118
14303
  }
14119
14304
  else if (name === '*') {
14120
14305
  variable.setRenderNames(null, namespaceInteropHelpersByInteropType[String(interop(module.id))]
14121
- ? module.namespaceVariableName
14122
- : module.variableName);
14306
+ ? chunk.namespaceVariableName
14307
+ : chunk.variableName);
14123
14308
  }
14124
14309
  else {
14125
14310
  // if the second parameter is `null`, it uses its "name" for the property name
14126
- variable.setRenderNames(module.variableName, null);
14311
+ variable.setRenderNames(chunk.variableName, null);
14127
14312
  }
14128
14313
  }
14129
14314
  else {
@@ -14157,15 +14342,6 @@ function deconflictTopLevelVariables(usedNames, modules, includedNamespaces) {
14157
14342
  }
14158
14343
  }
14159
14344
 
14160
- const needsEscapeRegEx = /[\\'\r\n\u2028\u2029]/;
14161
- const quoteNewlineRegEx = /(['\r\n\u2028\u2029])/g;
14162
- const backSlashRegEx = /\\/g;
14163
- function escapeId(id) {
14164
- if (!id.match(needsEscapeRegEx))
14165
- return id;
14166
- return id.replace(backSlashRegEx, '\\\\').replace(quoteNewlineRegEx, '\\$1');
14167
- }
14168
-
14169
14345
  function assignExportsToMangledNames(exports, exportsByName, exportNamesByVariable) {
14170
14346
  let nameIndex = 0;
14171
14347
  for (const variable of exports) {
@@ -14257,14 +14433,14 @@ function getIndentString(modules, options) {
14257
14433
  return '\t';
14258
14434
  }
14259
14435
 
14260
- function getStaticDependencies(chunk, orderedModules, chunkByModule) {
14436
+ function getStaticDependencies(chunk, orderedModules, chunkByModule, externalChunkByModule) {
14261
14437
  const staticDependencyBlocks = [];
14262
14438
  const handledDependencies = new Set();
14263
14439
  for (let modulePos = orderedModules.length - 1; modulePos >= 0; modulePos--) {
14264
14440
  const module = orderedModules[modulePos];
14265
14441
  if (!handledDependencies.has(module)) {
14266
14442
  const staticDependencies = [];
14267
- addStaticDependencies(module, staticDependencies, handledDependencies, chunk, chunkByModule);
14443
+ addStaticDependencies(module, staticDependencies, handledDependencies, chunk, chunkByModule, externalChunkByModule);
14268
14444
  staticDependencyBlocks.unshift(staticDependencies);
14269
14445
  }
14270
14446
  }
@@ -14276,11 +14452,11 @@ function getStaticDependencies(chunk, orderedModules, chunkByModule) {
14276
14452
  }
14277
14453
  return dependencies;
14278
14454
  }
14279
- function addStaticDependencies(module, staticDependencies, handledModules, chunk, chunkByModule) {
14455
+ function addStaticDependencies(module, staticDependencies, handledModules, chunk, chunkByModule, externalChunkByModule) {
14280
14456
  const dependencies = module.getDependenciesToBeIncluded();
14281
14457
  for (const dependency of dependencies) {
14282
14458
  if (dependency instanceof ExternalModule) {
14283
- staticDependencies.push(dependency);
14459
+ staticDependencies.push(externalChunkByModule.get(dependency));
14284
14460
  continue;
14285
14461
  }
14286
14462
  const dependencyChunk = chunkByModule.get(dependency);
@@ -14290,91 +14466,29 @@ function addStaticDependencies(module, staticDependencies, handledModules, chunk
14290
14466
  }
14291
14467
  if (!handledModules.has(dependency)) {
14292
14468
  handledModules.add(dependency);
14293
- addStaticDependencies(dependency, staticDependencies, handledModules, chunk, chunkByModule);
14469
+ addStaticDependencies(dependency, staticDependencies, handledModules, chunk, chunkByModule, externalChunkByModule);
14294
14470
  }
14295
14471
  }
14296
14472
  }
14297
14473
 
14298
- function decodedSourcemap(map) {
14299
- if (!map)
14300
- return null;
14301
- if (typeof map === 'string') {
14302
- map = JSON.parse(map);
14303
- }
14304
- if (map.mappings === '') {
14305
- return {
14306
- mappings: [],
14307
- names: [],
14308
- sources: [],
14309
- version: 3
14310
- };
14311
- }
14312
- const mappings = typeof map.mappings === 'string' ? decode(map.mappings) : map.mappings;
14313
- return { ...map, mappings };
14314
- }
14315
-
14316
- function renderChunk({ code, options, outputPluginDriver, renderChunk, sourcemapChain }) {
14317
- const renderChunkReducer = (code, result, plugin) => {
14318
- if (result == null)
14319
- return code;
14320
- if (typeof result === 'string')
14321
- result = {
14322
- code: result,
14323
- map: undefined
14324
- };
14325
- // strict null check allows 'null' maps to not be pushed to the chain, while 'undefined' gets the missing map warning
14326
- if (result.map !== null) {
14327
- const map = decodedSourcemap(result.map);
14328
- sourcemapChain.push(map || { missing: true, plugin: plugin.name });
14329
- }
14330
- return result.code;
14331
- };
14332
- return outputPluginDriver.hookReduceArg0('renderChunk', [code, renderChunk, options], renderChunkReducer);
14333
- }
14334
-
14335
- function renderNamePattern(pattern, patternName, replacements) {
14336
- if (isPathFragment(pattern))
14337
- return error(errFailedValidation(`Invalid pattern "${pattern}" for "${patternName}", patterns can be neither absolute nor relative paths.`));
14338
- return pattern.replace(/\[(\w+)\]/g, (_match, type) => {
14339
- if (!replacements.hasOwnProperty(type)) {
14340
- return error(errFailedValidation(`"[${type}]" is not a valid placeholder in "${patternName}" pattern.`));
14341
- }
14342
- const replacement = replacements[type]();
14343
- if (isPathFragment(replacement))
14344
- return error(errFailedValidation(`Invalid substitution "${replacement}" for placeholder "[${type}]" in "${patternName}" pattern, can be neither absolute nor relative path.`));
14345
- return replacement;
14346
- });
14347
- }
14348
- function makeUnique(name, existingNames) {
14349
- const existingNamesLowercase = new Set(Object.keys(existingNames).map(key => key.toLowerCase()));
14350
- if (!existingNamesLowercase.has(name.toLocaleLowerCase()))
14351
- return name;
14352
- const ext = extname(name);
14353
- name = name.substring(0, name.length - ext.length);
14354
- let uniqueName, uniqueIndex = 1;
14355
- while (existingNamesLowercase.has((uniqueName = name + ++uniqueIndex + ext).toLowerCase()))
14356
- ;
14357
- return uniqueName;
14358
- }
14359
-
14360
14474
  const NON_ASSET_EXTENSIONS = ['.js', '.jsx', '.ts', '.tsx'];
14361
- function getGlobalName(module, globals, hasExports, warn) {
14362
- const globalName = typeof globals === 'function' ? globals(module.id) : globals[module.id];
14475
+ function getGlobalName(chunk, globals, hasExports, warn) {
14476
+ const globalName = typeof globals === 'function' ? globals(chunk.id) : globals[chunk.id];
14363
14477
  if (globalName) {
14364
14478
  return globalName;
14365
14479
  }
14366
14480
  if (hasExports) {
14367
14481
  warn({
14368
14482
  code: 'MISSING_GLOBAL_NAME',
14369
- guess: module.variableName,
14370
- message: `No name was provided for external module '${module.id}' in output.globals – guessing '${module.variableName}'`,
14371
- source: module.id
14483
+ guess: chunk.variableName,
14484
+ message: `No name was provided for external module '${chunk.id}' in output.globals – guessing '${chunk.variableName}'`,
14485
+ source: chunk.id
14372
14486
  });
14373
- return module.variableName;
14487
+ return chunk.variableName;
14374
14488
  }
14375
14489
  }
14376
14490
  class Chunk {
14377
- constructor(orderedModules, inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, facadeChunkByModule, includedNamespaces, manualChunkAlias) {
14491
+ constructor(orderedModules, inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, externalChunkByModule, facadeChunkByModule, includedNamespaces, manualChunkAlias, getPlaceholder, bundle, inputBase, snippets) {
14378
14492
  this.orderedModules = orderedModules;
14379
14493
  this.inputOptions = inputOptions;
14380
14494
  this.outputOptions = outputOptions;
@@ -14382,19 +14496,22 @@ class Chunk {
14382
14496
  this.pluginDriver = pluginDriver;
14383
14497
  this.modulesById = modulesById;
14384
14498
  this.chunkByModule = chunkByModule;
14499
+ this.externalChunkByModule = externalChunkByModule;
14385
14500
  this.facadeChunkByModule = facadeChunkByModule;
14386
14501
  this.includedNamespaces = includedNamespaces;
14387
14502
  this.manualChunkAlias = manualChunkAlias;
14503
+ this.getPlaceholder = getPlaceholder;
14504
+ this.bundle = bundle;
14505
+ this.inputBase = inputBase;
14506
+ this.snippets = snippets;
14388
14507
  this.entryModules = [];
14389
14508
  this.exportMode = 'named';
14390
14509
  this.facadeModule = null;
14391
14510
  this.id = null;
14392
14511
  this.namespaceVariableName = '';
14393
- this.needsExportsShim = false;
14394
14512
  this.variableName = '';
14395
14513
  this.accessedGlobalsByScope = new Map();
14396
14514
  this.dependencies = new Set();
14397
- this.dynamicDependencies = new Set();
14398
14515
  this.dynamicEntryModules = [];
14399
14516
  this.dynamicName = null;
14400
14517
  this.exportNamesByVariable = new Map();
@@ -14404,23 +14521,23 @@ class Chunk {
14404
14521
  this.implicitEntryModules = [];
14405
14522
  this.implicitlyLoadedBefore = new Set();
14406
14523
  this.imports = new Set();
14524
+ this.includedDynamicImports = null;
14407
14525
  this.includedReexportsByModule = new Map();
14408
- this.indentString = undefined;
14409
- // This may only be updated in the constructor
14526
+ // This may be updated in the constructor
14410
14527
  this.isEmpty = true;
14411
14528
  this.name = null;
14529
+ this.needsExportsShim = false;
14530
+ this.preRenderedChunkInfo = null;
14531
+ this.preliminaryFileName = null;
14532
+ this.renderedChunkInfo = null;
14412
14533
  this.renderedDependencies = null;
14413
- this.renderedExports = null;
14414
- this.renderedHash = undefined;
14415
- this.renderedModuleSources = new Map();
14416
14534
  this.renderedModules = Object.create(null);
14417
- this.renderedSource = null;
14418
14535
  this.sortedExportNames = null;
14419
14536
  this.strictFacade = false;
14420
- this.usedModules = undefined;
14421
14537
  this.execIndex = orderedModules.length > 0 ? orderedModules[0].execIndex : Infinity;
14422
14538
  const chunkModules = new Set(orderedModules);
14423
14539
  for (const module of orderedModules) {
14540
+ chunkByModule.set(module, this);
14424
14541
  if (module.namespace.included) {
14425
14542
  includedNamespaces.add(module);
14426
14543
  }
@@ -14446,14 +14563,16 @@ class Chunk {
14446
14563
  }
14447
14564
  this.suggestedVariableName = makeLegal(this.generateVariableName());
14448
14565
  }
14449
- static generateFacade(inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, facadeChunkByModule, includedNamespaces, facadedModule, facadeName) {
14450
- const chunk = new Chunk([], inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, facadeChunkByModule, includedNamespaces, null);
14566
+ static generateFacade(inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, externalChunkByModule, facadeChunkByModule, includedNamespaces, facadedModule, facadeName, getPlaceholder, bundle, inputBase, snippets) {
14567
+ const chunk = new Chunk([], inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, externalChunkByModule, facadeChunkByModule, includedNamespaces, null, getPlaceholder, bundle, inputBase, snippets);
14451
14568
  chunk.assignFacadeName(facadeName, facadedModule);
14452
14569
  if (!facadeChunkByModule.has(facadedModule)) {
14453
14570
  facadeChunkByModule.set(facadedModule, chunk);
14454
14571
  }
14455
14572
  for (const dependency of facadedModule.getDependenciesToBeIncluded()) {
14456
- chunk.dependencies.add(dependency instanceof Module ? chunkByModule.get(dependency) : dependency);
14573
+ chunk.dependencies.add(dependency instanceof Module
14574
+ ? chunkByModule.get(dependency)
14575
+ : externalChunkByModule.get(dependency));
14457
14576
  }
14458
14577
  if (!chunk.dependencies.has(chunkByModule.get(facadedModule)) &&
14459
14578
  facadedModule.info.moduleSideEffects &&
@@ -14554,7 +14673,7 @@ class Chunk {
14554
14673
  }
14555
14674
  }
14556
14675
  for (const facadeName of requiredFacades) {
14557
- facades.push(Chunk.generateFacade(this.inputOptions, this.outputOptions, this.unsetOptions, this.pluginDriver, this.modulesById, this.chunkByModule, this.facadeChunkByModule, this.includedNamespaces, module, facadeName));
14676
+ 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));
14558
14677
  }
14559
14678
  }
14560
14679
  for (const module of this.dynamicEntryModules) {
@@ -14581,89 +14700,24 @@ class Chunk {
14581
14700
  }
14582
14701
  return facades;
14583
14702
  }
14584
- generateId(addons, options, existingNames, includeHash) {
14585
- if (this.fileName !== null) {
14586
- return this.fileName;
14587
- }
14588
- const [pattern, patternName] = this.facadeModule && this.facadeModule.isUserDefinedEntryPoint
14589
- ? [options.entryFileNames, 'output.entryFileNames']
14590
- : [options.chunkFileNames, 'output.chunkFileNames'];
14591
- return makeUnique(renderNamePattern(typeof pattern === 'function' ? pattern(this.getChunkInfo()) : pattern, patternName, {
14592
- format: () => options.format,
14593
- hash: () => includeHash
14594
- ? this.computeContentHashWithDependencies(addons, options, existingNames)
14595
- : '[hash]',
14596
- name: () => this.getChunkName()
14597
- }), existingNames);
14598
- }
14599
- generateIdPreserveModules(preserveModulesRelativeDir, options, existingNames, unsetOptions) {
14600
- const [{ id }] = this.orderedModules;
14601
- const sanitizedId = this.outputOptions.sanitizeFileName(id.split(QUERY_HASH_REGEX, 1)[0]);
14602
- let path;
14603
- const patternOpt = unsetOptions.has('entryFileNames')
14604
- ? '[name][assetExtname].js'
14605
- : options.entryFileNames;
14606
- const pattern = typeof patternOpt === 'function' ? patternOpt(this.getChunkInfo()) : patternOpt;
14607
- if (isAbsolute(sanitizedId)) {
14608
- const currentDir = dirname(sanitizedId);
14609
- const extension = extname(sanitizedId);
14610
- const fileName = renderNamePattern(pattern, 'output.entryFileNames', {
14611
- assetExtname: () => (NON_ASSET_EXTENSIONS.includes(extension) ? '' : extension),
14612
- ext: () => extension.substring(1),
14613
- extname: () => extension,
14614
- format: () => options.format,
14615
- name: () => this.getChunkName()
14616
- });
14617
- const currentPath = `${currentDir}/${fileName}`;
14618
- const { preserveModulesRoot } = options;
14619
- if (preserveModulesRoot && currentPath.startsWith(preserveModulesRoot)) {
14620
- path = currentPath.slice(preserveModulesRoot.length).replace(/^[\\/]/, '');
14621
- }
14622
- else {
14623
- path = relative(preserveModulesRelativeDir, currentPath);
14624
- }
14625
- }
14626
- else {
14627
- const extension = extname(sanitizedId);
14628
- const fileName = renderNamePattern(pattern, 'output.entryFileNames', {
14629
- assetExtname: () => (NON_ASSET_EXTENSIONS.includes(extension) ? '' : extension),
14630
- ext: () => extension.substring(1),
14631
- extname: () => extension,
14632
- format: () => options.format,
14633
- name: () => getAliasName(sanitizedId)
14634
- });
14635
- path = `_virtual/${fileName}`;
14636
- }
14637
- return makeUnique(normalize(path), existingNames);
14638
- }
14639
- getChunkInfo() {
14640
- const facadeModule = this.facadeModule;
14641
- const getChunkName = this.getChunkName.bind(this);
14703
+ generateOutputChunk(code, map, hashesByPlaceholder) {
14704
+ const renderedChunkInfo = this.getRenderedChunkInfo();
14705
+ const finalize = (code) => replacePlaceholders(code, hashesByPlaceholder);
14642
14706
  return {
14643
- exports: this.getExportNames(),
14644
- facadeModuleId: facadeModule && facadeModule.id,
14645
- isDynamicEntry: this.dynamicEntryModules.length > 0,
14646
- isEntry: facadeModule !== null && facadeModule.info.isEntry,
14647
- isImplicitEntry: this.implicitEntryModules.length > 0,
14648
- modules: this.renderedModules,
14649
- get name() {
14650
- return getChunkName();
14651
- },
14652
- type: 'chunk'
14707
+ ...renderedChunkInfo,
14708
+ code,
14709
+ dynamicImports: renderedChunkInfo.dynamicImports.map(finalize),
14710
+ fileName: finalize(renderedChunkInfo.fileName),
14711
+ implicitlyLoadedBefore: renderedChunkInfo.implicitlyLoadedBefore.map(finalize),
14712
+ importedBindings: Object.fromEntries(Object.entries(renderedChunkInfo.importedBindings).map(([fileName, bindings]) => [
14713
+ finalize(fileName),
14714
+ bindings
14715
+ ])),
14716
+ imports: renderedChunkInfo.imports.map(finalize),
14717
+ map,
14718
+ referencedFiles: renderedChunkInfo.referencedFiles.map(finalize)
14653
14719
  };
14654
14720
  }
14655
- getChunkInfoWithFileNames() {
14656
- return Object.assign(this.getChunkInfo(), {
14657
- code: undefined,
14658
- dynamicImports: Array.from(this.dynamicDependencies, getId),
14659
- fileName: this.id,
14660
- implicitlyLoadedBefore: Array.from(this.implicitlyLoadedBefore, getId),
14661
- importedBindings: this.getImportedBindingsPerDependency(),
14662
- imports: Array.from(this.dependencies, getId),
14663
- map: undefined,
14664
- referencedFiles: this.getReferencedFiles()
14665
- });
14666
- }
14667
14721
  getChunkName() {
14668
14722
  var _a;
14669
14723
  return ((_a = this.name) !== null && _a !== void 0 ? _a : (this.name = this.outputOptions.sanitizeFileName(this.getFallbackChunkName())));
@@ -14672,25 +14726,63 @@ class Chunk {
14672
14726
  var _a;
14673
14727
  return ((_a = this.sortedExportNames) !== null && _a !== void 0 ? _a : (this.sortedExportNames = Array.from(this.exportsByName.keys()).sort()));
14674
14728
  }
14675
- getRenderedHash() {
14676
- if (this.renderedHash)
14677
- return this.renderedHash;
14678
- const hash = createHash();
14679
- const hashAugmentation = this.pluginDriver.hookReduceValueSync('augmentChunkHash', '', [this.getChunkInfo()], (augmentation, pluginHash) => {
14680
- if (pluginHash) {
14681
- augmentation += pluginHash;
14729
+ getFileName() {
14730
+ var _a;
14731
+ return ((_a = this.preliminaryFileName) === null || _a === void 0 ? void 0 : _a.fileName) || this.getPreliminaryFileName().fileName;
14732
+ }
14733
+ getImportPath(importer) {
14734
+ return escapeId(getImportPath(importer, this.getFileName(), this.outputOptions.format === 'amd', true));
14735
+ }
14736
+ getPreliminaryFileName() {
14737
+ if (this.preliminaryFileName) {
14738
+ return this.preliminaryFileName;
14739
+ }
14740
+ let fileName;
14741
+ let hashPlaceholder = null;
14742
+ const { chunkFileNames, entryFileNames, file, format, preserveModules } = this.outputOptions;
14743
+ if (file) {
14744
+ fileName = basename(file);
14745
+ }
14746
+ else if (preserveModules) {
14747
+ fileName = this.generateIdPreserveModules();
14748
+ }
14749
+ else if (this.fileName !== null) {
14750
+ fileName = this.fileName;
14751
+ }
14752
+ else {
14753
+ const [pattern, patternName] = this.facadeModule && this.facadeModule.isUserDefinedEntryPoint
14754
+ ? [entryFileNames, 'output.entryFileNames']
14755
+ : [chunkFileNames, 'output.chunkFileNames'];
14756
+ fileName = renderNamePattern(typeof pattern === 'function' ? pattern(this.getPreRenderedChunkInfo()) : pattern, patternName, {
14757
+ format: () => format,
14758
+ hash: size => hashPlaceholder || (hashPlaceholder = this.getPlaceholder(patternName, size)),
14759
+ name: () => this.getChunkName()
14760
+ });
14761
+ if (!hashPlaceholder) {
14762
+ fileName = makeUnique(fileName, this.bundle);
14682
14763
  }
14683
- return augmentation;
14764
+ }
14765
+ if (!hashPlaceholder) {
14766
+ this.bundle[fileName] = FILE_PLACEHOLDER;
14767
+ }
14768
+ // Caching is essential to not conflict with the file name reservation above
14769
+ return (this.preliminaryFileName = { fileName, hashPlaceholder });
14770
+ }
14771
+ getRenderedChunkInfo() {
14772
+ if (this.renderedChunkInfo) {
14773
+ return this.renderedChunkInfo;
14774
+ }
14775
+ const resolveFileName = (dependency) => dependency.getFileName();
14776
+ return (this.renderedChunkInfo = {
14777
+ ...this.getPreRenderedChunkInfo(),
14778
+ dynamicImports: this.getDynamicDependencies().map(resolveFileName),
14779
+ fileName: this.getFileName(),
14780
+ implicitlyLoadedBefore: Array.from(this.implicitlyLoadedBefore, resolveFileName),
14781
+ importedBindings: getImportedBindingsPerDependency(this.getRenderedDependencies(), resolveFileName),
14782
+ imports: Array.from(this.dependencies, resolveFileName),
14783
+ modules: this.renderedModules,
14784
+ referencedFiles: this.getReferencedFiles()
14684
14785
  });
14685
- hash.update(hashAugmentation);
14686
- hash.update(this.renderedSource.toString());
14687
- hash.update(this.getExportNames()
14688
- .map(exportName => {
14689
- const variable = this.exportsByName.get(exportName);
14690
- return `${relativeId(variable.module.id).replace(/\\/g, '/')}:${variable.name}:${exportName}`;
14691
- })
14692
- .join(','));
14693
- return (this.renderedHash = hash.digest('hex'));
14694
14786
  }
14695
14787
  getVariableExportName(variable) {
14696
14788
  if (this.outputOptions.preserveModules && variable instanceof NamespaceVariable) {
@@ -14699,225 +14791,67 @@ class Chunk {
14699
14791
  return this.exportNamesByVariable.get(variable)[0];
14700
14792
  }
14701
14793
  link() {
14702
- this.dependencies = getStaticDependencies(this, this.orderedModules, this.chunkByModule);
14794
+ this.dependencies = getStaticDependencies(this, this.orderedModules, this.chunkByModule, this.externalChunkByModule);
14703
14795
  for (const module of this.orderedModules) {
14704
- this.addDependenciesToChunk(module.dynamicDependencies, this.dynamicDependencies);
14705
- this.addDependenciesToChunk(module.implicitlyLoadedBefore, this.implicitlyLoadedBefore);
14796
+ this.addImplicitlyLoadedBeforeFromModule(module);
14706
14797
  this.setUpChunkImportsAndExportsForModule(module);
14707
14798
  }
14708
14799
  }
14709
- // prerender allows chunk hashes and names to be generated before finalizing
14710
- preRender(options, inputBase, snippets) {
14711
- const { _, getPropertyAccess, n } = snippets;
14712
- const magicString = new Bundle$1({ separator: `${n}${n}` });
14713
- this.usedModules = [];
14714
- this.indentString = getIndentString(this.orderedModules, options);
14715
- const renderOptions = {
14716
- dynamicImportFunction: options.dynamicImportFunction,
14717
- exportNamesByVariable: this.exportNamesByVariable,
14718
- format: options.format,
14719
- freeze: options.freeze,
14720
- indent: this.indentString,
14721
- namespaceToStringTag: options.namespaceToStringTag,
14722
- outputPluginDriver: this.pluginDriver,
14723
- snippets
14724
- };
14725
- // for static and dynamic entry points, inline the execution list to avoid loading latency
14726
- if (options.hoistTransitiveImports &&
14727
- !this.outputOptions.preserveModules &&
14728
- this.facadeModule !== null) {
14729
- for (const dep of this.dependencies) {
14800
+ async render() {
14801
+ const { dependencies, exportMode, facadeModule, inputOptions: { onwarn }, outputOptions, pluginDriver, snippets } = this;
14802
+ const { format, hoistTransitiveImports, preserveModules } = outputOptions;
14803
+ // for static and dynamic entry points, add transitive dependencies to this
14804
+ // chunk's dependencies to avoid loading latency
14805
+ if (hoistTransitiveImports && !preserveModules && facadeModule !== null) {
14806
+ for (const dep of dependencies) {
14730
14807
  if (dep instanceof Chunk)
14731
14808
  this.inlineChunkDependencies(dep);
14732
14809
  }
14733
14810
  }
14734
- this.prepareModulesForRendering(snippets);
14735
- this.setIdentifierRenderResolutions(options);
14736
- let hoistedSource = '';
14737
- const renderedModules = this.renderedModules;
14738
- for (const module of this.orderedModules) {
14739
- let renderedLength = 0;
14740
- if (module.isIncluded() || this.includedNamespaces.has(module)) {
14741
- const source = module.render(renderOptions).trim();
14742
- renderedLength = source.length();
14743
- if (renderedLength) {
14744
- if (options.compact && source.lastLine().includes('//'))
14745
- source.append('\n');
14746
- this.renderedModuleSources.set(module, source);
14747
- magicString.addSource(source);
14748
- this.usedModules.push(module);
14749
- }
14750
- const namespace = module.namespace;
14751
- if (this.includedNamespaces.has(module) && !this.outputOptions.preserveModules) {
14752
- const rendered = namespace.renderBlock(renderOptions);
14753
- if (namespace.renderFirst())
14754
- hoistedSource += n + rendered;
14755
- else
14756
- magicString.addSource(new MagicString(rendered));
14757
- }
14758
- }
14759
- const { renderedExports, removedExports } = module.getRenderedExports();
14760
- const { renderedModuleSources } = this;
14761
- renderedModules[module.id] = {
14762
- get code() {
14763
- var _a, _b;
14764
- return (_b = (_a = renderedModuleSources.get(module)) === null || _a === void 0 ? void 0 : _a.toString()) !== null && _b !== void 0 ? _b : null;
14765
- },
14766
- originalLength: module.originalCode.length,
14767
- removedExports,
14768
- renderedExports,
14769
- renderedLength
14770
- };
14771
- }
14772
- if (hoistedSource)
14773
- magicString.prepend(hoistedSource + n + n);
14774
- if (this.needsExportsShim) {
14775
- magicString.prepend(`${n}${snippets.cnst} ${MISSING_EXPORT_SHIM_VARIABLE}${_}=${_}void 0;${n}${n}`);
14776
- }
14777
- if (options.compact) {
14778
- this.renderedSource = magicString;
14779
- }
14780
- else {
14781
- this.renderedSource = magicString.trim();
14782
- }
14783
- this.renderedHash = undefined;
14784
- if (this.isEmpty && this.getExportNames().length === 0 && this.dependencies.size === 0) {
14785
- const chunkName = this.getChunkName();
14786
- this.inputOptions.onwarn({
14787
- chunkName,
14788
- code: 'EMPTY_BUNDLE',
14789
- message: `Generated an empty chunk: "${chunkName}"`
14790
- });
14791
- }
14792
- this.setExternalRenderPaths(options, inputBase);
14793
- this.renderedDependencies = this.getChunkDependencyDeclarations(options, getPropertyAccess);
14794
- this.renderedExports =
14795
- this.exportMode === 'none'
14796
- ? []
14797
- : this.getChunkExportDeclarations(options.format, getPropertyAccess);
14798
- }
14799
- async render(options, addons, outputChunk, snippets) {
14811
+ const preliminaryFileName = this.getPreliminaryFileName();
14812
+ const { accessedGlobals, indent, magicString, renderedSource, usedModules, usesTopLevelAwait } = this.renderModules(preliminaryFileName.fileName);
14800
14813
  timeStart('render format', 2);
14801
- const format = options.format;
14802
- const finalise = finalisers[format];
14803
- if (options.dynamicImportFunction && format !== 'es') {
14804
- this.inputOptions.onwarn(errInvalidOption('output.dynamicImportFunction', 'outputdynamicImportFunction', 'this option is ignored for formats other than "es"'));
14805
- }
14806
- // populate ids in the rendered declarations only here
14807
- // as chunk ids known only after prerender
14808
- for (const dependency of this.dependencies) {
14809
- const renderedDependency = this.renderedDependencies.get(dependency);
14810
- if (dependency instanceof ExternalModule) {
14811
- const originalId = dependency.renderPath;
14812
- renderedDependency.id = escapeId(dependency.renormalizeRenderPath
14813
- ? getImportPath(this.id, originalId, false, false)
14814
- : originalId);
14815
- }
14816
- else {
14817
- renderedDependency.namedExportsMode = dependency.exportMode !== 'default';
14818
- renderedDependency.id = escapeId(getImportPath(this.id, dependency.id, false, true));
14819
- }
14820
- }
14821
- this.finaliseDynamicImports(options, snippets);
14822
- this.finaliseImportMetas(format, snippets);
14823
- const hasExports = this.renderedExports.length !== 0 ||
14824
- [...this.renderedDependencies.values()].some(dep => (dep.reexports && dep.reexports.length !== 0));
14825
- let topLevelAwaitModule = null;
14826
- const accessedGlobals = new Set();
14827
- for (const module of this.orderedModules) {
14828
- if (module.usesTopLevelAwait) {
14829
- topLevelAwaitModule = module.id;
14830
- }
14831
- const accessedGlobalVariables = this.accessedGlobalsByScope.get(module.scope);
14832
- if (accessedGlobalVariables) {
14833
- for (const name of accessedGlobalVariables) {
14834
- accessedGlobals.add(name);
14835
- }
14836
- }
14837
- }
14838
- if (topLevelAwaitModule !== null && format !== 'es' && format !== 'system') {
14839
- return error({
14840
- code: 'INVALID_TLA_FORMAT',
14841
- id: topLevelAwaitModule,
14842
- message: `Module format ${format} does not support top-level await. Use the "es" or "system" output formats rather.`
14843
- });
14844
- }
14845
- /* istanbul ignore next */
14846
- if (!this.id) {
14847
- throw new Error('Internal Error: expecting chunk id');
14848
- }
14849
- const magicString = finalise(this.renderedSource, {
14814
+ const renderedDependencies = [...this.getRenderedDependencies().values()];
14815
+ const renderedExports = exportMode === 'none' ? [] : this.getChunkExportDeclarations(format);
14816
+ const hasExports = renderedExports.length !== 0 ||
14817
+ renderedDependencies.some(dep => (dep.reexports && dep.reexports.length !== 0));
14818
+ // TODO Lukas Note: Mention in docs, that users/plugins are responsible to do their own caching
14819
+ // TODO Lukas adapt plugin hook graphs and order in docs
14820
+ const { intro, outro, banner, footer } = await createAddons(outputOptions, pluginDriver, this.getRenderedChunkInfo());
14821
+ finalisers[format](renderedSource, {
14850
14822
  accessedGlobals,
14851
- dependencies: [...this.renderedDependencies.values()],
14852
- exports: this.renderedExports,
14823
+ dependencies: renderedDependencies,
14824
+ exports: renderedExports,
14853
14825
  hasExports,
14854
- id: this.id,
14855
- indent: this.indentString,
14856
- intro: addons.intro,
14857
- isEntryFacade: this.outputOptions.preserveModules ||
14858
- (this.facadeModule !== null && this.facadeModule.info.isEntry),
14859
- isModuleFacade: this.facadeModule !== null,
14860
- namedExportsMode: this.exportMode !== 'default',
14861
- outro: addons.outro,
14826
+ id: preliminaryFileName.fileName,
14827
+ indent,
14828
+ intro,
14829
+ isEntryFacade: preserveModules || (facadeModule !== null && facadeModule.info.isEntry),
14830
+ isModuleFacade: facadeModule !== null,
14831
+ namedExportsMode: exportMode !== 'default',
14832
+ onwarn,
14833
+ outro,
14862
14834
  snippets,
14863
- usesTopLevelAwait: topLevelAwaitModule !== null,
14864
- warn: this.inputOptions.onwarn
14865
- }, options);
14866
- if (addons.banner)
14867
- magicString.prepend(addons.banner);
14868
- if (addons.footer)
14869
- magicString.append(addons.footer);
14870
- const prevCode = magicString.toString();
14835
+ usesTopLevelAwait
14836
+ }, outputOptions);
14837
+ if (banner)
14838
+ magicString.prepend(banner);
14839
+ if (footer)
14840
+ magicString.append(footer);
14871
14841
  timeEnd('render format', 2);
14872
- let map = null;
14873
- const chunkSourcemapChain = [];
14874
- let code = await renderChunk({
14875
- code: prevCode,
14876
- options,
14877
- outputPluginDriver: this.pluginDriver,
14878
- renderChunk: outputChunk,
14879
- sourcemapChain: chunkSourcemapChain
14880
- });
14881
- if (options.sourcemap) {
14882
- timeStart('sourcemap', 2);
14883
- let file;
14884
- if (options.file)
14885
- file = resolve(options.sourcemapFile || options.file);
14886
- else if (options.dir)
14887
- file = resolve(options.dir, this.id);
14888
- else
14889
- file = resolve(this.id);
14890
- const decodedMap = magicString.generateDecodedMap({});
14891
- map = collapseSourcemaps(file, decodedMap, this.usedModules, chunkSourcemapChain, options.sourcemapExcludeSources, this.inputOptions.onwarn);
14892
- map.sources = map.sources
14893
- .map(sourcePath => {
14894
- const { sourcemapPathTransform } = options;
14895
- if (sourcemapPathTransform) {
14896
- const newSourcePath = sourcemapPathTransform(sourcePath, `${file}.map`);
14897
- if (typeof newSourcePath !== 'string') {
14898
- error(errFailedValidation(`sourcemapPathTransform function must return a string.`));
14899
- }
14900
- return newSourcePath;
14901
- }
14902
- return sourcePath;
14903
- })
14904
- .map(normalize);
14905
- timeEnd('sourcemap', 2);
14906
- }
14907
- if (!options.compact && code[code.length - 1] !== '\n')
14908
- code += '\n';
14909
- return { code, map };
14842
+ return {
14843
+ chunk: this,
14844
+ magicString,
14845
+ preliminaryFileName,
14846
+ usedModules
14847
+ };
14910
14848
  }
14911
- addDependenciesToChunk(moduleDependencies, chunkDependencies) {
14912
- for (const module of moduleDependencies) {
14913
- if (module instanceof Module) {
14914
- const chunk = this.chunkByModule.get(module);
14915
- if (chunk && chunk !== this) {
14916
- chunkDependencies.add(chunk);
14917
- }
14918
- }
14919
- else {
14920
- chunkDependencies.add(module);
14849
+ addImplicitlyLoadedBeforeFromModule(baseModule) {
14850
+ const { implicitlyLoadedBefore } = this;
14851
+ for (const module of baseModule.implicitlyLoadedBefore) {
14852
+ const chunk = this.chunkByModule.get(module);
14853
+ if (chunk && chunk !== this) {
14854
+ implicitlyLoadedBefore.add(chunk);
14921
14855
  }
14922
14856
  }
14923
14857
  }
@@ -14955,27 +14889,6 @@ class Chunk {
14955
14889
  } while (alternativeReexportModule);
14956
14890
  }
14957
14891
  }
14958
- computeContentHashWithDependencies(addons, options, existingNames) {
14959
- const hash = createHash();
14960
- hash.update([addons.intro, addons.outro, addons.banner, addons.footer].join(':'));
14961
- hash.update(options.format);
14962
- const dependenciesForHashing = new Set([this]);
14963
- for (const current of dependenciesForHashing) {
14964
- if (current instanceof ExternalModule) {
14965
- hash.update(`:${current.renderPath}`);
14966
- }
14967
- else {
14968
- hash.update(current.getRenderedHash());
14969
- hash.update(current.generateId(addons, options, existingNames, false));
14970
- }
14971
- if (current instanceof ExternalModule)
14972
- continue;
14973
- for (const dependency of [...current.dependencies, ...current.dynamicDependencies]) {
14974
- dependenciesForHashing.add(dependency);
14975
- }
14976
- }
14977
- return hash.digest('hex').substr(0, 8);
14978
- }
14979
14892
  ensureReexportsAreAvailableForModule(module) {
14980
14893
  const includedReexports = [];
14981
14894
  const map = module.getExportNamesByVariable();
@@ -15003,38 +14916,49 @@ class Chunk {
15003
14916
  this.includedReexportsByModule.set(module, includedReexports);
15004
14917
  }
15005
14918
  }
15006
- finaliseDynamicImports(options, snippets) {
15007
- const stripKnownJsExtensions = options.format === 'amd';
15008
- for (const [module, code] of this.renderedModuleSources) {
15009
- for (const { node, resolution } of module.dynamicImports) {
15010
- const chunk = this.chunkByModule.get(resolution);
15011
- const facadeChunk = this.facadeChunkByModule.get(resolution);
15012
- if (!resolution || !node.included || chunk === this) {
15013
- continue;
15014
- }
15015
- const renderedResolution = resolution instanceof Module
15016
- ? `'${escapeId(getImportPath(this.id, (facadeChunk || chunk).id, stripKnownJsExtensions, true))}'`
15017
- : resolution instanceof ExternalModule
15018
- ? `'${escapeId(resolution.renormalizeRenderPath
15019
- ? getImportPath(this.id, resolution.renderPath, stripKnownJsExtensions, false)
15020
- : resolution.renderPath)}'`
15021
- : resolution;
15022
- node.renderFinalResolution(code, renderedResolution, resolution instanceof Module &&
15023
- !(facadeChunk === null || facadeChunk === void 0 ? void 0 : facadeChunk.strictFacade) &&
15024
- chunk.exportNamesByVariable.get(resolution.namespace)[0], snippets);
15025
- }
15026
- }
15027
- }
15028
- finaliseImportMetas(format, snippets) {
15029
- for (const [module, code] of this.renderedModuleSources) {
15030
- for (const importMeta of module.importMetas) {
15031
- importMeta.renderFinalMechanism(code, this.id, format, snippets, this.pluginDriver);
15032
- }
15033
- }
15034
- }
15035
- generateVariableName() {
15036
- if (this.manualChunkAlias) {
15037
- return this.manualChunkAlias;
14919
+ generateIdPreserveModules() {
14920
+ const [{ id }] = this.orderedModules;
14921
+ const { entryFileNames, format, preserveModulesRoot, sanitizeFileName } = this.outputOptions;
14922
+ const sanitizedId = sanitizeFileName(id.split(QUERY_HASH_REGEX, 1)[0]);
14923
+ let path;
14924
+ const patternOpt = this.unsetOptions.has('entryFileNames')
14925
+ ? '[name][assetExtname].js'
14926
+ : entryFileNames;
14927
+ const pattern = typeof patternOpt === 'function' ? patternOpt(this.getPreRenderedChunkInfo()) : patternOpt;
14928
+ if (isAbsolute(sanitizedId)) {
14929
+ const currentDir = dirname(sanitizedId);
14930
+ const extension = extname(sanitizedId);
14931
+ const fileName = renderNamePattern(pattern, 'output.entryFileNames', {
14932
+ assetExtname: () => (NON_ASSET_EXTENSIONS.includes(extension) ? '' : extension),
14933
+ ext: () => extension.substring(1),
14934
+ extname: () => extension,
14935
+ format: () => format,
14936
+ name: () => this.getChunkName()
14937
+ });
14938
+ const currentPath = `${currentDir}/${fileName}`;
14939
+ if (preserveModulesRoot && currentPath.startsWith(preserveModulesRoot)) {
14940
+ path = currentPath.slice(preserveModulesRoot.length).replace(/^[\\/]/, '');
14941
+ }
14942
+ else {
14943
+ path = relative(this.inputBase, currentPath);
14944
+ }
14945
+ }
14946
+ else {
14947
+ const extension = extname(sanitizedId);
14948
+ const fileName = renderNamePattern(pattern, 'output.entryFileNames', {
14949
+ assetExtname: () => (NON_ASSET_EXTENSIONS.includes(extension) ? '' : extension),
14950
+ ext: () => extension.substring(1),
14951
+ extname: () => extension,
14952
+ format: () => format,
14953
+ name: () => getAliasName(sanitizedId)
14954
+ });
14955
+ path = `_virtual/${fileName}`;
14956
+ }
14957
+ return makeUnique(normalize(path), this.bundle);
14958
+ }
14959
+ generateVariableName() {
14960
+ if (this.manualChunkAlias) {
14961
+ return this.manualChunkAlias;
15038
14962
  }
15039
14963
  const moduleForNaming = this.entryModules[0] ||
15040
14964
  this.implicitEntryModules[0] ||
@@ -15045,31 +14969,7 @@ class Chunk {
15045
14969
  }
15046
14970
  return 'chunk';
15047
14971
  }
15048
- getChunkDependencyDeclarations(options, getPropertyAccess) {
15049
- const importSpecifiers = this.getImportSpecifiers(getPropertyAccess);
15050
- const reexportSpecifiers = this.getReexportSpecifiers();
15051
- const dependencyDeclaration = new Map();
15052
- for (const dep of this.dependencies) {
15053
- const imports = importSpecifiers.get(dep) || null;
15054
- const reexports = reexportSpecifiers.get(dep) || null;
15055
- const namedExportsMode = dep instanceof ExternalModule || dep.exportMode !== 'default';
15056
- dependencyDeclaration.set(dep, {
15057
- defaultVariableName: dep.defaultVariableName,
15058
- globalName: (dep instanceof ExternalModule &&
15059
- (options.format === 'umd' || options.format === 'iife') &&
15060
- getGlobalName(dep, options.globals, (imports || reexports) !== null, this.inputOptions.onwarn)),
15061
- id: undefined,
15062
- imports,
15063
- isChunk: dep instanceof Chunk,
15064
- name: dep.variableName,
15065
- namedExportsMode,
15066
- namespaceVariableName: dep.namespaceVariableName,
15067
- reexports
15068
- });
15069
- }
15070
- return dependencyDeclaration;
15071
- }
15072
- getChunkExportDeclarations(format, getPropertyAccess) {
14972
+ getChunkExportDeclarations(format) {
15073
14973
  const exports = [];
15074
14974
  for (const exportName of this.getExportNames()) {
15075
14975
  if (exportName[0] === '*')
@@ -15082,7 +14982,7 @@ class Chunk {
15082
14982
  }
15083
14983
  let expression = null;
15084
14984
  let hoisted = false;
15085
- let local = variable.getName(getPropertyAccess);
14985
+ let local = variable.getName(this.snippets.getPropertyAccess);
15086
14986
  if (variable instanceof LocalVariable) {
15087
14987
  for (const declaration of variable.declarations) {
15088
14988
  if (declaration.parent instanceof FunctionDeclaration ||
@@ -15116,16 +15016,17 @@ class Chunk {
15116
15016
  if (addNonNamespacesAndInteropHelpers || variable.isNamespace) {
15117
15017
  const module = variable.module;
15118
15018
  if (module instanceof ExternalModule) {
15119
- dependencies.add(module);
15019
+ const chunk = this.externalChunkByModule.get(module);
15020
+ dependencies.add(chunk);
15120
15021
  if (addNonNamespacesAndInteropHelpers) {
15121
15022
  if (variable.name === 'default') {
15122
15023
  if (defaultInteropHelpersByInteropType[String(interop(module.id))]) {
15123
- deconflictedDefault.add(module);
15024
+ deconflictedDefault.add(chunk);
15124
15025
  }
15125
15026
  }
15126
15027
  else if (variable.name === '*') {
15127
15028
  if (namespaceInteropHelpersByInteropType[String(interop(module.id))]) {
15128
- deconflictedNamespace.add(module);
15029
+ deconflictedNamespace.add(chunk);
15129
15030
  }
15130
15031
  }
15131
15032
  }
@@ -15150,6 +15051,15 @@ class Chunk {
15150
15051
  }
15151
15052
  return { deconflictedDefault, deconflictedNamespace, dependencies };
15152
15053
  }
15054
+ getDynamicDependencies() {
15055
+ return this.getIncludedDynamicImports()
15056
+ .map(resolvedDynamicImport => resolvedDynamicImport.facadeChunk ||
15057
+ resolvedDynamicImport.chunk ||
15058
+ resolvedDynamicImport.externalChunk ||
15059
+ resolvedDynamicImport.resolution)
15060
+ .filter((resolution) => resolution !== this &&
15061
+ (resolution instanceof Chunk || resolution instanceof ExternalChunk));
15062
+ }
15153
15063
  getFallbackChunkName() {
15154
15064
  if (this.manualChunkAlias) {
15155
15065
  return this.manualChunkAlias;
@@ -15162,7 +15072,7 @@ class Chunk {
15162
15072
  }
15163
15073
  return getAliasName(this.orderedModules[this.orderedModules.length - 1].id);
15164
15074
  }
15165
- getImportSpecifiers(getPropertyAccess) {
15075
+ getImportSpecifiers() {
15166
15076
  const { interop } = this.outputOptions;
15167
15077
  const importsByDependency = new Map();
15168
15078
  for (const variable of this.imports) {
@@ -15170,7 +15080,7 @@ class Chunk {
15170
15080
  let dependency;
15171
15081
  let imported;
15172
15082
  if (module instanceof ExternalModule) {
15173
- dependency = module;
15083
+ dependency = this.externalChunkByModule.get(module);
15174
15084
  imported = variable.name;
15175
15085
  if (imported !== 'default' && imported !== '*' && interop(module.id) === 'defaultOnly') {
15176
15086
  return error(errUnexpectedNamedImport(module.id, imported, false));
@@ -15182,28 +15092,57 @@ class Chunk {
15182
15092
  }
15183
15093
  getOrCreate(importsByDependency, dependency, () => []).push({
15184
15094
  imported,
15185
- local: variable.getName(getPropertyAccess)
15095
+ local: variable.getName(this.snippets.getPropertyAccess)
15186
15096
  });
15187
15097
  }
15188
15098
  return importsByDependency;
15189
15099
  }
15190
- getImportedBindingsPerDependency() {
15191
- const importSpecifiers = {};
15192
- for (const [dependency, declaration] of this.renderedDependencies) {
15193
- const specifiers = new Set();
15194
- if (declaration.imports) {
15195
- for (const { imported } of declaration.imports) {
15196
- specifiers.add(imported);
15197
- }
15198
- }
15199
- if (declaration.reexports) {
15200
- for (const { imported } of declaration.reexports) {
15201
- specifiers.add(imported);
15100
+ getIncludedDynamicImports() {
15101
+ if (this.includedDynamicImports) {
15102
+ return this.includedDynamicImports;
15103
+ }
15104
+ const includedDynamicImports = [];
15105
+ for (const module of this.orderedModules) {
15106
+ for (const { node, resolution } of module.dynamicImports) {
15107
+ if (!node.included) {
15108
+ continue;
15202
15109
  }
15110
+ includedDynamicImports.push(resolution instanceof Module
15111
+ ? {
15112
+ chunk: this.chunkByModule.get(resolution),
15113
+ externalChunk: null,
15114
+ facadeChunk: this.facadeChunkByModule.get(resolution),
15115
+ node,
15116
+ resolution
15117
+ }
15118
+ : resolution instanceof ExternalModule
15119
+ ? {
15120
+ chunk: null,
15121
+ externalChunk: this.externalChunkByModule.get(resolution),
15122
+ facadeChunk: null,
15123
+ node,
15124
+ resolution
15125
+ }
15126
+ : { chunk: null, externalChunk: null, facadeChunk: null, node, resolution });
15203
15127
  }
15204
- importSpecifiers[dependency.id] = [...specifiers];
15205
15128
  }
15206
- return importSpecifiers;
15129
+ return (this.includedDynamicImports = includedDynamicImports);
15130
+ }
15131
+ getPreRenderedChunkInfo() {
15132
+ if (this.preRenderedChunkInfo) {
15133
+ return this.preRenderedChunkInfo;
15134
+ }
15135
+ const { facadeModule } = this;
15136
+ return (this.preRenderedChunkInfo = {
15137
+ exports: this.getExportNames(),
15138
+ facadeModuleId: facadeModule && facadeModule.id,
15139
+ isDynamicEntry: this.dynamicEntryModules.length > 0,
15140
+ isEntry: !!(facadeModule === null || facadeModule === void 0 ? void 0 : facadeModule.info.isEntry),
15141
+ isImplicitEntry: this.implicitEntryModules.length > 0,
15142
+ moduleIds: this.orderedModules.map(({ id }) => id),
15143
+ name: this.getChunkName(),
15144
+ type: 'chunk'
15145
+ });
15207
15146
  }
15208
15147
  getReexportSpecifiers() {
15209
15148
  const { externalLiveBindings, interop } = this.outputOptions;
@@ -15218,7 +15157,7 @@ class Chunk {
15218
15157
  this.inputOptions.onwarn(errUnexpectedNamespaceReexport(id));
15219
15158
  }
15220
15159
  needsLiveBinding = externalLiveBindings;
15221
- dependency = this.modulesById.get(id);
15160
+ dependency = this.externalChunkByModule.get(this.modulesById.get(id));
15222
15161
  imported = exportName = '*';
15223
15162
  }
15224
15163
  else {
@@ -15234,7 +15173,7 @@ class Chunk {
15234
15173
  needsLiveBinding = variable.isReassigned;
15235
15174
  }
15236
15175
  else {
15237
- dependency = module;
15176
+ dependency = this.externalChunkByModule.get(module);
15238
15177
  imported = variable.name;
15239
15178
  if (imported !== 'default' && imported !== '*' && interop(module.id) === 'defaultOnly') {
15240
15179
  return error(errUnexpectedNamedImport(module.id, imported, true));
@@ -15253,16 +15192,45 @@ class Chunk {
15253
15192
  return reexportSpecifiers;
15254
15193
  }
15255
15194
  getReferencedFiles() {
15256
- const referencedFiles = [];
15195
+ const referencedFiles = new Set();
15257
15196
  for (const module of this.orderedModules) {
15258
15197
  for (const meta of module.importMetas) {
15259
15198
  const fileName = meta.getReferencedFileName(this.pluginDriver);
15260
15199
  if (fileName) {
15261
- referencedFiles.push(fileName);
15200
+ referencedFiles.add(fileName);
15262
15201
  }
15263
15202
  }
15264
15203
  }
15265
- return referencedFiles;
15204
+ return [...referencedFiles];
15205
+ }
15206
+ getRenderedDependencies() {
15207
+ if (this.renderedDependencies) {
15208
+ return this.renderedDependencies;
15209
+ }
15210
+ const importSpecifiers = this.getImportSpecifiers();
15211
+ const reexportSpecifiers = this.getReexportSpecifiers();
15212
+ const renderedDependencies = new Map();
15213
+ const fileName = this.getFileName();
15214
+ for (const dep of this.dependencies) {
15215
+ const imports = importSpecifiers.get(dep) || null;
15216
+ const reexports = reexportSpecifiers.get(dep) || null;
15217
+ const namedExportsMode = dep instanceof ExternalChunk || dep.exportMode !== 'default';
15218
+ const importPath = dep.getImportPath(fileName);
15219
+ renderedDependencies.set(dep, {
15220
+ defaultVariableName: dep.defaultVariableName,
15221
+ globalName: dep instanceof ExternalChunk &&
15222
+ (this.outputOptions.format === 'umd' || this.outputOptions.format === 'iife') &&
15223
+ getGlobalName(dep, this.outputOptions.globals, (imports || reexports) !== null, this.inputOptions.onwarn),
15224
+ importPath,
15225
+ imports,
15226
+ isChunk: dep instanceof Chunk,
15227
+ name: dep.variableName,
15228
+ namedExportsMode,
15229
+ namespaceVariableName: dep.namespaceVariableName,
15230
+ reexports
15231
+ });
15232
+ }
15233
+ return (this.renderedDependencies = renderedDependencies);
15266
15234
  }
15267
15235
  inlineChunkDependencies(chunk) {
15268
15236
  for (const dep of chunk.dependencies) {
@@ -15274,42 +15242,111 @@ class Chunk {
15274
15242
  }
15275
15243
  }
15276
15244
  }
15277
- prepareModulesForRendering(snippets) {
15278
- var _a;
15279
- const accessedGlobalsByScope = this.accessedGlobalsByScope;
15280
- for (const module of this.orderedModules) {
15281
- for (const { node, resolution } of module.dynamicImports) {
15282
- if (node.included) {
15283
- if (resolution instanceof Module) {
15284
- const chunk = this.chunkByModule.get(resolution);
15285
- if (chunk === this) {
15286
- node.setInternalResolution(resolution.namespace);
15287
- }
15288
- else {
15289
- node.setExternalResolution(((_a = this.facadeChunkByModule.get(resolution)) === null || _a === void 0 ? void 0 : _a.exportMode) || chunk.exportMode, resolution, this.outputOptions, snippets, this.pluginDriver, accessedGlobalsByScope);
15290
- }
15291
- }
15292
- else {
15293
- node.setExternalResolution('external', resolution, this.outputOptions, snippets, this.pluginDriver, accessedGlobalsByScope);
15245
+ // This method changes properties on the AST before rendering and must not be async
15246
+ renderModules(fileName) {
15247
+ const { dependencies, exportNamesByVariable, includedNamespaces, inputOptions: { onwarn }, isEmpty, orderedModules, outputOptions, pluginDriver, renderedModules, snippets } = this;
15248
+ const { compact, dynamicImportFunction, format, freeze, namespaceToStringTag, preserveModules } = outputOptions;
15249
+ const { _, n } = snippets;
15250
+ this.setDynamicImportResolutions(fileName);
15251
+ this.setImportMetaResolutions(fileName);
15252
+ this.setIdentifierRenderResolutions();
15253
+ const magicString = new Bundle$1({ separator: `${n}${n}` });
15254
+ const indent = getIndentString(orderedModules, outputOptions);
15255
+ const usedModules = [];
15256
+ let hoistedSource = '';
15257
+ const accessedGlobals = new Set();
15258
+ const renderedModuleSources = new Map();
15259
+ const renderOptions = {
15260
+ dynamicImportFunction,
15261
+ exportNamesByVariable,
15262
+ format,
15263
+ freeze,
15264
+ indent,
15265
+ namespaceToStringTag,
15266
+ pluginDriver,
15267
+ snippets
15268
+ };
15269
+ let usesTopLevelAwait = false;
15270
+ for (const module of orderedModules) {
15271
+ let renderedLength = 0;
15272
+ let source;
15273
+ if (module.isIncluded() || includedNamespaces.has(module)) {
15274
+ const rendered = module.render(renderOptions);
15275
+ ({ source } = rendered);
15276
+ usesTopLevelAwait || (usesTopLevelAwait = rendered.usesTopLevelAwait);
15277
+ renderedLength = source.length();
15278
+ if (renderedLength) {
15279
+ if (compact && source.lastLine().includes('//'))
15280
+ source.append('\n');
15281
+ renderedModuleSources.set(module, source);
15282
+ magicString.addSource(source);
15283
+ usedModules.push(module);
15284
+ }
15285
+ const namespace = module.namespace;
15286
+ if (includedNamespaces.has(module) && !preserveModules) {
15287
+ const rendered = namespace.renderBlock(renderOptions);
15288
+ if (namespace.renderFirst())
15289
+ hoistedSource += n + rendered;
15290
+ else
15291
+ magicString.addSource(new MagicString(rendered));
15292
+ }
15293
+ const accessedGlobalVariables = this.accessedGlobalsByScope.get(module.scope);
15294
+ if (accessedGlobalVariables) {
15295
+ for (const name of accessedGlobalVariables) {
15296
+ accessedGlobals.add(name);
15294
15297
  }
15295
15298
  }
15296
15299
  }
15297
- for (const importMeta of module.importMetas) {
15298
- importMeta.addAccessedGlobals(this.outputOptions.format, accessedGlobalsByScope);
15299
- }
15300
- if (this.includedNamespaces.has(module) && !this.outputOptions.preserveModules) {
15301
- module.namespace.prepare(accessedGlobalsByScope);
15302
- }
15300
+ const { renderedExports, removedExports } = module.getRenderedExports();
15301
+ renderedModules[module.id] = {
15302
+ get code() {
15303
+ var _a;
15304
+ return (_a = source === null || source === void 0 ? void 0 : source.toString()) !== null && _a !== void 0 ? _a : null;
15305
+ },
15306
+ originalLength: module.originalCode.length,
15307
+ removedExports,
15308
+ renderedExports,
15309
+ renderedLength
15310
+ };
15311
+ }
15312
+ if (hoistedSource)
15313
+ magicString.prepend(hoistedSource + n + n);
15314
+ if (this.needsExportsShim) {
15315
+ magicString.prepend(`${n}${snippets.cnst} ${MISSING_EXPORT_SHIM_VARIABLE}${_}=${_}void 0;${n}${n}`);
15316
+ }
15317
+ const renderedSource = compact ? magicString : magicString.trim();
15318
+ if (isEmpty && this.getExportNames().length === 0 && dependencies.size === 0) {
15319
+ const chunkName = this.getChunkName();
15320
+ onwarn({
15321
+ chunkName,
15322
+ code: 'EMPTY_BUNDLE',
15323
+ message: `Generated an empty chunk: "${chunkName}"`
15324
+ });
15303
15325
  }
15326
+ return { accessedGlobals, indent, magicString, renderedSource, usedModules, usesTopLevelAwait };
15304
15327
  }
15305
- setExternalRenderPaths(options, inputBase) {
15306
- for (const dependency of [...this.dependencies, ...this.dynamicDependencies]) {
15307
- if (dependency instanceof ExternalModule) {
15308
- dependency.setRenderPath(options, inputBase);
15328
+ setDynamicImportResolutions(fileName) {
15329
+ const { accessedGlobalsByScope, outputOptions, pluginDriver, snippets } = this;
15330
+ for (const resolvedDynamicImport of this.getIncludedDynamicImports()) {
15331
+ if (resolvedDynamicImport.chunk) {
15332
+ const { chunk, facadeChunk, node, resolution } = resolvedDynamicImport;
15333
+ if (chunk === this) {
15334
+ node.setInternalResolution(resolution.namespace);
15335
+ }
15336
+ else {
15337
+ 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]);
15338
+ }
15339
+ }
15340
+ else {
15341
+ const { resolution } = resolvedDynamicImport;
15342
+ resolvedDynamicImport.node.setExternalResolution('external', resolution, outputOptions, snippets, pluginDriver, accessedGlobalsByScope, resolution instanceof ExternalModule
15343
+ ? `'${this.externalChunkByModule.get(resolution).getImportPath(fileName)}'`
15344
+ : resolution || '', false);
15309
15345
  }
15310
15346
  }
15311
15347
  }
15312
- setIdentifierRenderResolutions({ format, interop, namespaceToStringTag }) {
15348
+ setIdentifierRenderResolutions() {
15349
+ const { format, interop, namespaceToStringTag } = this.outputOptions;
15313
15350
  const syntheticExports = new Set();
15314
15351
  for (const exportName of this.getExportNames()) {
15315
15352
  const exportVariable = this.exportsByName.get(exportName);
@@ -15354,7 +15391,18 @@ class Chunk {
15354
15391
  usedNames.add(helper);
15355
15392
  }
15356
15393
  }
15357
- 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);
15394
+ 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);
15395
+ }
15396
+ setImportMetaResolutions(fileName) {
15397
+ const { accessedGlobalsByScope, includedNamespaces, outputOptions: { format, preserveModules } } = this;
15398
+ for (const module of this.orderedModules) {
15399
+ for (const importMeta of module.importMetas) {
15400
+ importMeta.setResolution(format, accessedGlobalsByScope, fileName);
15401
+ }
15402
+ if (includedNamespaces.has(module) && !preserveModules) {
15403
+ module.namespace.prepare(accessedGlobalsByScope);
15404
+ }
15405
+ }
15358
15406
  }
15359
15407
  setUpChunkImportsAndExportsForModule(module) {
15360
15408
  const moduleImports = new Set(module.includedImports);
@@ -15405,546 +15453,646 @@ function getChunkNameFromModule(module) {
15405
15453
  var _a, _b, _c, _d;
15406
15454
  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));
15407
15455
  }
15408
- const QUERY_HASH_REGEX = /[?#]/;
15409
-
15410
- function generateAssetFileName(name, source, outputOptions, bundle) {
15411
- const emittedName = outputOptions.sanitizeFileName(name || 'asset');
15412
- return makeUnique(renderNamePattern(typeof outputOptions.assetFileNames === 'function'
15413
- ? outputOptions.assetFileNames({ name, source, type: 'asset' })
15414
- : outputOptions.assetFileNames, 'output.assetFileNames', {
15415
- ext: () => extname(emittedName).substring(1),
15416
- extname: () => extname(emittedName),
15417
- hash() {
15418
- return createHash()
15419
- .update(emittedName)
15420
- .update(':')
15421
- .update(source)
15422
- .digest('hex')
15423
- .substring(0, 8);
15424
- },
15425
- name: () => emittedName.substring(0, emittedName.length - extname(emittedName).length)
15426
- }), bundle);
15427
- }
15428
- function reserveFileNameInBundle(fileName, bundle, warn) {
15429
- if (fileName in bundle) {
15430
- warn(errFileNameConflict(fileName));
15456
+ function getImportedBindingsPerDependency(renderedDependencies, resolveFileName) {
15457
+ const importedBindingsPerDependency = {};
15458
+ for (const [dependency, declaration] of renderedDependencies) {
15459
+ const specifiers = new Set();
15460
+ if (declaration.imports) {
15461
+ for (const { imported } of declaration.imports) {
15462
+ specifiers.add(imported);
15463
+ }
15464
+ }
15465
+ if (declaration.reexports) {
15466
+ for (const { imported } of declaration.reexports) {
15467
+ specifiers.add(imported);
15468
+ }
15469
+ }
15470
+ importedBindingsPerDependency[resolveFileName(dependency)] = [...specifiers];
15431
15471
  }
15432
- bundle[fileName] = FILE_PLACEHOLDER;
15433
- }
15434
- const FILE_PLACEHOLDER = {
15435
- type: 'placeholder'
15436
- };
15437
- function hasValidType(emittedFile) {
15438
- return Boolean(emittedFile &&
15439
- (emittedFile.type === 'asset' ||
15440
- emittedFile.type === 'chunk'));
15472
+ return importedBindingsPerDependency;
15441
15473
  }
15442
- function hasValidName(emittedFile) {
15443
- const validatedName = emittedFile.fileName || emittedFile.name;
15444
- return !validatedName || (typeof validatedName === 'string' && !isPathFragment(validatedName));
15445
- }
15446
- function getValidSource(source, emittedFile, fileReferenceId) {
15447
- if (!(typeof source === 'string' || source instanceof Uint8Array)) {
15448
- const assetName = emittedFile.fileName || emittedFile.name || fileReferenceId;
15449
- 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.`));
15474
+ const QUERY_HASH_REGEX = /[?#]/;
15475
+
15476
+ function getChunkAssignments(entryModules, manualChunkAliasByEntry) {
15477
+ const chunkDefinitions = [];
15478
+ const modulesInManualChunks = new Set(manualChunkAliasByEntry.keys());
15479
+ const manualChunkModulesByAlias = Object.create(null);
15480
+ for (const [entry, alias] of manualChunkAliasByEntry) {
15481
+ const chunkModules = (manualChunkModulesByAlias[alias] =
15482
+ manualChunkModulesByAlias[alias] || []);
15483
+ addStaticDependenciesToManualChunk(entry, chunkModules, modulesInManualChunks);
15450
15484
  }
15451
- return source;
15452
- }
15453
- function getAssetFileName(file, referenceId) {
15454
- if (typeof file.fileName !== 'string') {
15455
- return error(errAssetNotFinalisedForFileName(file.name || referenceId));
15485
+ for (const [alias, modules] of Object.entries(manualChunkModulesByAlias)) {
15486
+ chunkDefinitions.push({ alias, modules });
15456
15487
  }
15457
- return file.fileName;
15458
- }
15459
- function getChunkFileName(file, facadeChunkByModule) {
15460
- var _a;
15461
- 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));
15462
- if (!fileName)
15463
- return error(errChunkNotGeneratedForFileName(file.fileName || file.name));
15464
- return fileName;
15465
- }
15466
- class FileEmitter {
15467
- constructor(graph, options, baseFileEmitter) {
15468
- this.graph = graph;
15469
- this.options = options;
15470
- this.bundle = null;
15471
- this.facadeChunkByModule = null;
15472
- this.outputOptions = null;
15473
- this.assertAssetsFinalized = () => {
15474
- for (const [referenceId, emittedFile] of this.filesByReferenceId) {
15475
- if (emittedFile.type === 'asset' && typeof emittedFile.fileName !== 'string')
15476
- return error(errNoAssetSourceSet(emittedFile.name || referenceId));
15488
+ const assignedEntryPointsByModule = new Map();
15489
+ const { dependentEntryPointsByModule, dynamicEntryModules } = analyzeModuleGraph(entryModules);
15490
+ const dynamicallyDependentEntryPointsByDynamicEntry = getDynamicDependentEntryPoints(dependentEntryPointsByModule, dynamicEntryModules);
15491
+ const staticEntries = new Set(entryModules);
15492
+ function assignEntryToStaticDependencies(entry, dynamicDependentEntryPoints) {
15493
+ const modulesToHandle = new Set([entry]);
15494
+ for (const module of modulesToHandle) {
15495
+ const assignedEntryPoints = getOrCreate(assignedEntryPointsByModule, module, () => new Set());
15496
+ if (dynamicDependentEntryPoints &&
15497
+ areEntryPointsContainedOrDynamicallyDependent(dynamicDependentEntryPoints, dependentEntryPointsByModule.get(module))) {
15498
+ continue;
15477
15499
  }
15478
- };
15479
- this.emitFile = (emittedFile) => {
15480
- if (!hasValidType(emittedFile)) {
15481
- return error(errFailedValidation(`Emitted files must be of type "asset" or "chunk", received "${emittedFile && emittedFile.type}".`));
15500
+ else {
15501
+ assignedEntryPoints.add(entry);
15482
15502
  }
15483
- if (!hasValidName(emittedFile)) {
15484
- 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}".`));
15503
+ for (const dependency of module.getDependenciesToBeIncluded()) {
15504
+ if (!(dependency instanceof ExternalModule || modulesInManualChunks.has(dependency))) {
15505
+ modulesToHandle.add(dependency);
15506
+ }
15485
15507
  }
15486
- if (emittedFile.type === 'chunk') {
15487
- return this.emitChunk(emittedFile);
15508
+ }
15509
+ }
15510
+ function areEntryPointsContainedOrDynamicallyDependent(entryPoints, containedIn) {
15511
+ const entriesToCheck = new Set(entryPoints);
15512
+ for (const entry of entriesToCheck) {
15513
+ if (!containedIn.has(entry)) {
15514
+ if (staticEntries.has(entry))
15515
+ return false;
15516
+ const dynamicallyDependentEntryPoints = dynamicallyDependentEntryPointsByDynamicEntry.get(entry);
15517
+ for (const dependentEntry of dynamicallyDependentEntryPoints) {
15518
+ entriesToCheck.add(dependentEntry);
15519
+ }
15488
15520
  }
15489
- return this.emitAsset(emittedFile);
15490
- };
15491
- this.getFileName = (fileReferenceId) => {
15492
- const emittedFile = this.filesByReferenceId.get(fileReferenceId);
15493
- if (!emittedFile)
15494
- return error(errFileReferenceIdNotFoundForFilename(fileReferenceId));
15495
- if (emittedFile.type === 'chunk') {
15496
- return getChunkFileName(emittedFile, this.facadeChunkByModule);
15497
- }
15498
- return getAssetFileName(emittedFile, fileReferenceId);
15499
- };
15500
- this.setAssetSource = (referenceId, requestedSource) => {
15501
- const consumedFile = this.filesByReferenceId.get(referenceId);
15502
- if (!consumedFile)
15503
- return error(errAssetReferenceIdNotFoundForSetSource(referenceId));
15504
- if (consumedFile.type !== 'asset') {
15505
- return error(errFailedValidation(`Asset sources can only be set for emitted assets but "${referenceId}" is an emitted chunk.`));
15506
- }
15507
- if (consumedFile.source !== undefined) {
15508
- return error(errAssetSourceAlreadySet(consumedFile.name || referenceId));
15509
- }
15510
- const source = getValidSource(requestedSource, consumedFile, referenceId);
15511
- if (this.bundle) {
15512
- this.finalizeAsset(consumedFile, source, referenceId, this.bundle);
15513
- }
15514
- else {
15515
- consumedFile.source = source;
15521
+ }
15522
+ return true;
15523
+ }
15524
+ for (const entry of entryModules) {
15525
+ if (!modulesInManualChunks.has(entry)) {
15526
+ assignEntryToStaticDependencies(entry, null);
15527
+ }
15528
+ }
15529
+ for (const entry of dynamicEntryModules) {
15530
+ if (!modulesInManualChunks.has(entry)) {
15531
+ assignEntryToStaticDependencies(entry, dynamicallyDependentEntryPointsByDynamicEntry.get(entry));
15532
+ }
15533
+ }
15534
+ chunkDefinitions.push(...createChunks([...entryModules, ...dynamicEntryModules], assignedEntryPointsByModule));
15535
+ return chunkDefinitions;
15536
+ }
15537
+ function addStaticDependenciesToManualChunk(entry, manualChunkModules, modulesInManualChunks) {
15538
+ const modulesToHandle = new Set([entry]);
15539
+ for (const module of modulesToHandle) {
15540
+ modulesInManualChunks.add(module);
15541
+ manualChunkModules.push(module);
15542
+ for (const dependency of module.dependencies) {
15543
+ if (!(dependency instanceof ExternalModule || modulesInManualChunks.has(dependency))) {
15544
+ modulesToHandle.add(dependency);
15516
15545
  }
15517
- };
15518
- this.setOutputBundle = (outputBundle, outputOptions, facadeChunkByModule) => {
15519
- this.outputOptions = outputOptions;
15520
- this.bundle = outputBundle;
15521
- this.facadeChunkByModule = facadeChunkByModule;
15522
- for (const emittedFile of this.filesByReferenceId.values()) {
15523
- if (emittedFile.fileName) {
15524
- reserveFileNameInBundle(emittedFile.fileName, this.bundle, this.options.onwarn);
15546
+ }
15547
+ }
15548
+ }
15549
+ function analyzeModuleGraph(entryModules) {
15550
+ const dynamicEntryModules = new Set();
15551
+ const dependentEntryPointsByModule = new Map();
15552
+ const entriesToHandle = new Set(entryModules);
15553
+ for (const currentEntry of entriesToHandle) {
15554
+ const modulesToHandle = new Set([currentEntry]);
15555
+ for (const module of modulesToHandle) {
15556
+ getOrCreate(dependentEntryPointsByModule, module, () => new Set()).add(currentEntry);
15557
+ for (const dependency of module.getDependenciesToBeIncluded()) {
15558
+ if (!(dependency instanceof ExternalModule)) {
15559
+ modulesToHandle.add(dependency);
15525
15560
  }
15526
15561
  }
15527
- for (const [referenceId, consumedFile] of this.filesByReferenceId) {
15528
- if (consumedFile.type === 'asset' && consumedFile.source !== undefined) {
15529
- this.finalizeAsset(consumedFile, consumedFile.source, referenceId, this.bundle);
15562
+ for (const { resolution } of module.dynamicImports) {
15563
+ if (resolution instanceof Module && resolution.includedDynamicImporters.length > 0) {
15564
+ dynamicEntryModules.add(resolution);
15565
+ entriesToHandle.add(resolution);
15530
15566
  }
15531
15567
  }
15532
- };
15533
- this.filesByReferenceId = baseFileEmitter
15534
- ? new Map(baseFileEmitter.filesByReferenceId)
15535
- : new Map();
15536
- }
15537
- assignReferenceId(file, idBase) {
15538
- let referenceId;
15539
- do {
15540
- referenceId = createHash()
15541
- .update(referenceId || idBase)
15542
- .digest('hex')
15543
- .substring(0, 8);
15544
- } while (this.filesByReferenceId.has(referenceId));
15545
- this.filesByReferenceId.set(referenceId, file);
15546
- return referenceId;
15547
- }
15548
- emitAsset(emittedAsset) {
15549
- const source = typeof emittedAsset.source !== 'undefined'
15550
- ? getValidSource(emittedAsset.source, emittedAsset, null)
15551
- : undefined;
15552
- const consumedAsset = {
15553
- fileName: emittedAsset.fileName,
15554
- name: emittedAsset.name,
15555
- source,
15556
- type: 'asset'
15557
- };
15558
- const referenceId = this.assignReferenceId(consumedAsset, emittedAsset.fileName || emittedAsset.name || emittedAsset.type);
15559
- if (this.bundle) {
15560
- if (emittedAsset.fileName) {
15561
- reserveFileNameInBundle(emittedAsset.fileName, this.bundle, this.options.onwarn);
15568
+ for (const dependency of module.implicitlyLoadedBefore) {
15569
+ dynamicEntryModules.add(dependency);
15570
+ entriesToHandle.add(dependency);
15562
15571
  }
15563
- if (source !== undefined) {
15564
- this.finalizeAsset(consumedAsset, source, referenceId, this.bundle);
15572
+ }
15573
+ }
15574
+ return { dependentEntryPointsByModule, dynamicEntryModules };
15575
+ }
15576
+ function getDynamicDependentEntryPoints(dependentEntryPointsByModule, dynamicEntryModules) {
15577
+ const dynamicallyDependentEntryPointsByDynamicEntry = new Map();
15578
+ for (const dynamicEntry of dynamicEntryModules) {
15579
+ const dynamicDependentEntryPoints = getOrCreate(dynamicallyDependentEntryPointsByDynamicEntry, dynamicEntry, () => new Set());
15580
+ for (const importer of [
15581
+ ...dynamicEntry.includedDynamicImporters,
15582
+ ...dynamicEntry.implicitlyLoadedAfter
15583
+ ]) {
15584
+ for (const entryPoint of dependentEntryPointsByModule.get(importer)) {
15585
+ dynamicDependentEntryPoints.add(entryPoint);
15565
15586
  }
15566
15587
  }
15567
- return referenceId;
15568
15588
  }
15569
- emitChunk(emittedChunk) {
15570
- if (this.graph.phase > BuildPhase.LOAD_AND_PARSE) {
15571
- return error(errInvalidRollupPhaseForChunkEmission());
15589
+ return dynamicallyDependentEntryPointsByDynamicEntry;
15590
+ }
15591
+ function createChunks(allEntryPoints, assignedEntryPointsByModule) {
15592
+ const chunkModules = Object.create(null);
15593
+ for (const [module, assignedEntryPoints] of assignedEntryPointsByModule) {
15594
+ let chunkSignature = '';
15595
+ for (const entry of allEntryPoints) {
15596
+ chunkSignature += assignedEntryPoints.has(entry) ? 'X' : '_';
15572
15597
  }
15573
- if (typeof emittedChunk.id !== 'string') {
15574
- return error(errFailedValidation(`Emitted chunks need to have a valid string id, received "${emittedChunk.id}"`));
15598
+ const chunk = chunkModules[chunkSignature];
15599
+ if (chunk) {
15600
+ chunk.push(module);
15601
+ }
15602
+ else {
15603
+ chunkModules[chunkSignature] = [module];
15575
15604
  }
15576
- const consumedChunk = {
15577
- fileName: emittedChunk.fileName,
15578
- module: null,
15579
- name: emittedChunk.name || emittedChunk.id,
15580
- type: 'chunk'
15581
- };
15582
- this.graph.moduleLoader
15583
- .emitChunk(emittedChunk)
15584
- .then(module => (consumedChunk.module = module))
15585
- .catch(() => {
15586
- // Avoid unhandled Promise rejection as the error will be thrown later
15587
- // once module loading has finished
15588
- });
15589
- return this.assignReferenceId(consumedChunk, emittedChunk.id);
15590
- }
15591
- finalizeAsset(consumedFile, source, referenceId, bundle) {
15592
- const fileName = consumedFile.fileName ||
15593
- findExistingAssetFileNameWithSource(bundle, source) ||
15594
- generateAssetFileName(consumedFile.name, source, this.outputOptions, bundle);
15595
- // We must not modify the original assets to avoid interaction between outputs
15596
- const assetWithFileName = { ...consumedFile, fileName, source };
15597
- this.filesByReferenceId.set(referenceId, assetWithFileName);
15598
- const { options } = this;
15599
- bundle[fileName] = {
15600
- fileName,
15601
- get isAsset() {
15602
- warnDeprecation('Accessing "isAsset" on files in the bundle is deprecated, please use "type === \'asset\'" instead', true, options);
15603
- return true;
15604
- },
15605
- name: consumedFile.name,
15606
- source,
15607
- type: 'asset'
15608
- };
15609
15605
  }
15606
+ return Object.values(chunkModules).map(modules => ({
15607
+ alias: null,
15608
+ modules
15609
+ }));
15610
15610
  }
15611
- function findExistingAssetFileNameWithSource(bundle, source) {
15612
- for (const [fileName, outputFile] of Object.entries(bundle)) {
15613
- if (outputFile.type === 'asset' && areSourcesEqual(source, outputFile.source))
15614
- return fileName;
15615
- }
15616
- return null;
15611
+
15612
+ // ported from https://github.com/substack/node-commondir
15613
+ function commondir(files) {
15614
+ if (files.length === 0)
15615
+ return '/';
15616
+ if (files.length === 1)
15617
+ return dirname(files[0]);
15618
+ const commonSegments = files.slice(1).reduce((commonSegments, file) => {
15619
+ const pathSegements = file.split(/\/+|\\+/);
15620
+ let i;
15621
+ for (i = 0; commonSegments[i] === pathSegements[i] &&
15622
+ i < Math.min(commonSegments.length, pathSegements.length); i++)
15623
+ ;
15624
+ return commonSegments.slice(0, i);
15625
+ }, files[0].split(/\/+|\\+/));
15626
+ // Windows correctly handles paths with forward-slashes
15627
+ return commonSegments.length > 1 ? commonSegments.join('/') : '/';
15617
15628
  }
15618
- function areSourcesEqual(sourceA, sourceB) {
15619
- if (typeof sourceA === 'string') {
15620
- return sourceA === sourceB;
15621
- }
15622
- if (typeof sourceB === 'string') {
15623
- return false;
15629
+
15630
+ const compareExecIndex = (unitA, unitB) => unitA.execIndex > unitB.execIndex ? 1 : -1;
15631
+ function sortByExecutionOrder(units) {
15632
+ units.sort(compareExecIndex);
15633
+ }
15634
+ function analyseModuleExecution(entryModules) {
15635
+ let nextExecIndex = 0;
15636
+ const cyclePaths = [];
15637
+ const analysedModules = new Set();
15638
+ const dynamicImports = new Set();
15639
+ const parents = new Map();
15640
+ const orderedModules = [];
15641
+ const analyseModule = (module) => {
15642
+ if (module instanceof Module) {
15643
+ for (const dependency of module.dependencies) {
15644
+ if (parents.has(dependency)) {
15645
+ if (!analysedModules.has(dependency)) {
15646
+ cyclePaths.push(getCyclePath(dependency, module, parents));
15647
+ }
15648
+ continue;
15649
+ }
15650
+ parents.set(dependency, module);
15651
+ analyseModule(dependency);
15652
+ }
15653
+ for (const dependency of module.implicitlyLoadedBefore) {
15654
+ dynamicImports.add(dependency);
15655
+ }
15656
+ for (const { resolution } of module.dynamicImports) {
15657
+ if (resolution instanceof Module) {
15658
+ dynamicImports.add(resolution);
15659
+ }
15660
+ }
15661
+ orderedModules.push(module);
15662
+ }
15663
+ module.execIndex = nextExecIndex++;
15664
+ analysedModules.add(module);
15665
+ };
15666
+ for (const curEntry of entryModules) {
15667
+ if (!parents.has(curEntry)) {
15668
+ parents.set(curEntry, null);
15669
+ analyseModule(curEntry);
15670
+ }
15624
15671
  }
15625
- if ('equals' in sourceA) {
15626
- return sourceA.equals(sourceB);
15672
+ for (const curEntry of dynamicImports) {
15673
+ if (!parents.has(curEntry)) {
15674
+ parents.set(curEntry, null);
15675
+ analyseModule(curEntry);
15676
+ }
15627
15677
  }
15628
- if (sourceA.length !== sourceB.length) {
15629
- return false;
15678
+ return { cyclePaths, orderedModules };
15679
+ }
15680
+ function getCyclePath(module, parent, parents) {
15681
+ const cycleSymbol = Symbol(module.id);
15682
+ const path = [relativeId(module.id)];
15683
+ let nextModule = parent;
15684
+ module.cycles.add(cycleSymbol);
15685
+ while (nextModule !== module) {
15686
+ nextModule.cycles.add(cycleSymbol);
15687
+ path.push(relativeId(nextModule.id));
15688
+ nextModule = parents.get(nextModule);
15630
15689
  }
15631
- for (let index = 0; index < sourceA.length; index++) {
15632
- if (sourceA[index] !== sourceB[index]) {
15633
- return false;
15690
+ path.push(path[0]);
15691
+ path.reverse();
15692
+ return path;
15693
+ }
15694
+
15695
+ function getGenerateCodeSnippets({ compact, generatedCode: { arrowFunctions, constBindings, objectShorthand, reservedNamesAsProps } }) {
15696
+ const { _, n, s } = compact ? { _: '', n: '', s: '' } : { _: ' ', n: '\n', s: ';' };
15697
+ const cnst = constBindings ? 'const' : 'var';
15698
+ const getNonArrowFunctionIntro = (params, { isAsync, name }) => `${isAsync ? `async ` : ''}function${name ? ` ${name}` : ''}${_}(${params.join(`,${_}`)})${_}`;
15699
+ const getFunctionIntro = arrowFunctions
15700
+ ? (params, { isAsync, name }) => {
15701
+ const singleParam = params.length === 1;
15702
+ const asyncString = isAsync ? `async${singleParam ? ' ' : _}` : '';
15703
+ return `${name ? `${cnst} ${name}${_}=${_}` : ''}${asyncString}${singleParam ? params[0] : `(${params.join(`,${_}`)})`}${_}=>${_}`;
15634
15704
  }
15635
- }
15636
- return true;
15705
+ : getNonArrowFunctionIntro;
15706
+ const getDirectReturnFunction = (params, { functionReturn, lineBreakIndent, name }) => [
15707
+ `${getFunctionIntro(params, {
15708
+ isAsync: false,
15709
+ name
15710
+ })}${arrowFunctions
15711
+ ? lineBreakIndent
15712
+ ? `${n}${lineBreakIndent.base}${lineBreakIndent.t}`
15713
+ : ''
15714
+ : `{${lineBreakIndent ? `${n}${lineBreakIndent.base}${lineBreakIndent.t}` : _}${functionReturn ? 'return ' : ''}`}`,
15715
+ arrowFunctions
15716
+ ? `${name ? ';' : ''}${lineBreakIndent ? `${n}${lineBreakIndent.base}` : ''}`
15717
+ : `${s}${lineBreakIndent ? `${n}${lineBreakIndent.base}` : _}}`
15718
+ ];
15719
+ const isValidPropName = reservedNamesAsProps
15720
+ ? (name) => validPropName.test(name)
15721
+ : (name) => !RESERVED_NAMES$1.has(name) && validPropName.test(name);
15722
+ return {
15723
+ _,
15724
+ cnst,
15725
+ getDirectReturnFunction,
15726
+ getDirectReturnIifeLeft: (params, returned, { needsArrowReturnParens, needsWrappedFunction }) => {
15727
+ const [left, right] = getDirectReturnFunction(params, {
15728
+ functionReturn: true,
15729
+ lineBreakIndent: null,
15730
+ name: null
15731
+ });
15732
+ return `${wrapIfNeeded(`${left}${wrapIfNeeded(returned, arrowFunctions && needsArrowReturnParens)}${right}`, arrowFunctions || needsWrappedFunction)}(`;
15733
+ },
15734
+ getFunctionIntro,
15735
+ getNonArrowFunctionIntro,
15736
+ getObject(fields, { lineBreakIndent }) {
15737
+ const prefix = lineBreakIndent ? `${n}${lineBreakIndent.base}${lineBreakIndent.t}` : _;
15738
+ return `{${fields
15739
+ .map(([key, value]) => {
15740
+ if (key === null)
15741
+ return `${prefix}${value}`;
15742
+ const needsQuotes = !isValidPropName(key);
15743
+ return key === value && objectShorthand && !needsQuotes
15744
+ ? prefix + key
15745
+ : `${prefix}${needsQuotes ? `'${key}'` : key}:${_}${value}`;
15746
+ })
15747
+ .join(`,`)}${fields.length === 0 ? '' : lineBreakIndent ? `${n}${lineBreakIndent.base}` : _}}`;
15748
+ },
15749
+ getPropertyAccess: (name) => isValidPropName(name) ? `.${name}` : `[${JSON.stringify(name)}]`,
15750
+ n,
15751
+ s
15752
+ };
15637
15753
  }
15754
+ const wrapIfNeeded = (code, needsParens) => needsParens ? `(${code})` : code;
15755
+ const validPropName = /^(?!\d)[\w$]+$/;
15638
15756
 
15639
- const concatSep = (out, next) => (next ? `${out}\n${next}` : out);
15640
- const concatDblSep = (out, next) => (next ? `${out}\n\n${next}` : out);
15641
- async function createAddons(options, outputPluginDriver) {
15642
- try {
15643
- let [banner, footer, intro, outro] = await Promise.all([
15644
- outputPluginDriver.hookReduceValue('banner', options.banner(), [], concatSep),
15645
- outputPluginDriver.hookReduceValue('footer', options.footer(), [], concatSep),
15646
- outputPluginDriver.hookReduceValue('intro', options.intro(), [], concatDblSep),
15647
- outputPluginDriver.hookReduceValue('outro', options.outro(), [], concatDblSep)
15648
- ]);
15649
- if (intro)
15650
- intro += '\n\n';
15651
- if (outro)
15652
- outro = `\n\n${outro}`;
15653
- if (banner.length)
15654
- banner += '\n';
15655
- if (footer.length)
15656
- footer = '\n' + footer;
15657
- return { banner, footer, intro, outro };
15757
+ class Source {
15758
+ constructor(filename, content) {
15759
+ this.isOriginal = true;
15760
+ this.filename = filename;
15761
+ this.content = content;
15658
15762
  }
15659
- catch (err) {
15660
- return error({
15661
- code: 'ADDON_ERROR',
15662
- message: `Could not retrieve ${err.hook}. Check configuration of plugin ${err.plugin}.
15663
- \tError Message: ${err.message}`
15664
- });
15763
+ traceSegment(line, column, name) {
15764
+ return { column, line, name, source: this };
15665
15765
  }
15666
15766
  }
15667
-
15668
- function getChunkAssignments(entryModules, manualChunkAliasByEntry) {
15669
- const chunkDefinitions = [];
15670
- const modulesInManualChunks = new Set(manualChunkAliasByEntry.keys());
15671
- const manualChunkModulesByAlias = Object.create(null);
15672
- for (const [entry, alias] of manualChunkAliasByEntry) {
15673
- const chunkModules = (manualChunkModulesByAlias[alias] =
15674
- manualChunkModulesByAlias[alias] || []);
15675
- addStaticDependenciesToManualChunk(entry, chunkModules, modulesInManualChunks);
15676
- }
15677
- for (const [alias, modules] of Object.entries(manualChunkModulesByAlias)) {
15678
- chunkDefinitions.push({ alias, modules });
15767
+ class Link {
15768
+ constructor(map, sources) {
15769
+ this.sources = sources;
15770
+ this.names = map.names;
15771
+ this.mappings = map.mappings;
15679
15772
  }
15680
- const assignedEntryPointsByModule = new Map();
15681
- const { dependentEntryPointsByModule, dynamicEntryModules } = analyzeModuleGraph(entryModules);
15682
- const dynamicallyDependentEntryPointsByDynamicEntry = getDynamicDependentEntryPoints(dependentEntryPointsByModule, dynamicEntryModules);
15683
- const staticEntries = new Set(entryModules);
15684
- function assignEntryToStaticDependencies(entry, dynamicDependentEntryPoints) {
15685
- const modulesToHandle = new Set([entry]);
15686
- for (const module of modulesToHandle) {
15687
- const assignedEntryPoints = getOrCreate(assignedEntryPointsByModule, module, () => new Set());
15688
- if (dynamicDependentEntryPoints &&
15689
- areEntryPointsContainedOrDynamicallyDependent(dynamicDependentEntryPoints, dependentEntryPointsByModule.get(module))) {
15690
- continue;
15691
- }
15692
- else {
15693
- assignedEntryPoints.add(entry);
15694
- }
15695
- for (const dependency of module.getDependenciesToBeIncluded()) {
15696
- if (!(dependency instanceof ExternalModule || modulesInManualChunks.has(dependency))) {
15697
- modulesToHandle.add(dependency);
15773
+ traceMappings() {
15774
+ const sources = [];
15775
+ const sourceIndexMap = new Map();
15776
+ const sourcesContent = [];
15777
+ const names = [];
15778
+ const nameIndexMap = new Map();
15779
+ const mappings = [];
15780
+ for (const line of this.mappings) {
15781
+ const tracedLine = [];
15782
+ for (const segment of line) {
15783
+ if (segment.length === 1)
15784
+ continue;
15785
+ const source = this.sources[segment[1]];
15786
+ if (!source)
15787
+ continue;
15788
+ const traced = source.traceSegment(segment[2], segment[3], segment.length === 5 ? this.names[segment[4]] : '');
15789
+ if (traced) {
15790
+ const { column, line, name, source: { content, filename } } = traced;
15791
+ let sourceIndex = sourceIndexMap.get(filename);
15792
+ if (sourceIndex === undefined) {
15793
+ sourceIndex = sources.length;
15794
+ sources.push(filename);
15795
+ sourceIndexMap.set(filename, sourceIndex);
15796
+ sourcesContent[sourceIndex] = content;
15797
+ }
15798
+ else if (sourcesContent[sourceIndex] == null) {
15799
+ sourcesContent[sourceIndex] = content;
15800
+ }
15801
+ else if (content != null && sourcesContent[sourceIndex] !== content) {
15802
+ return error({
15803
+ message: `Multiple conflicting contents for sourcemap source ${filename}`
15804
+ });
15805
+ }
15806
+ const tracedSegment = [segment[0], sourceIndex, line, column];
15807
+ if (name) {
15808
+ let nameIndex = nameIndexMap.get(name);
15809
+ if (nameIndex === undefined) {
15810
+ nameIndex = names.length;
15811
+ names.push(name);
15812
+ nameIndexMap.set(name, nameIndex);
15813
+ }
15814
+ tracedSegment[4] = nameIndex;
15815
+ }
15816
+ tracedLine.push(tracedSegment);
15698
15817
  }
15699
15818
  }
15819
+ mappings.push(tracedLine);
15700
15820
  }
15821
+ return { mappings, names, sources, sourcesContent };
15701
15822
  }
15702
- function areEntryPointsContainedOrDynamicallyDependent(entryPoints, containedIn) {
15703
- const entriesToCheck = new Set(entryPoints);
15704
- for (const entry of entriesToCheck) {
15705
- if (!containedIn.has(entry)) {
15706
- if (staticEntries.has(entry))
15707
- return false;
15708
- const dynamicallyDependentEntryPoints = dynamicallyDependentEntryPointsByDynamicEntry.get(entry);
15709
- for (const dependentEntry of dynamicallyDependentEntryPoints) {
15710
- entriesToCheck.add(dependentEntry);
15711
- }
15823
+ traceSegment(line, column, name) {
15824
+ const segments = this.mappings[line];
15825
+ if (!segments)
15826
+ return null;
15827
+ // binary search through segments for the given column
15828
+ let searchStart = 0;
15829
+ let searchEnd = segments.length - 1;
15830
+ while (searchStart <= searchEnd) {
15831
+ const m = (searchStart + searchEnd) >> 1;
15832
+ const segment = segments[m];
15833
+ // If a sourcemap does not have sufficient resolution to contain a
15834
+ // necessary mapping, e.g. because it only contains line information, we
15835
+ // use the best approximation we could find
15836
+ if (segment[0] === column || searchStart === searchEnd) {
15837
+ if (segment.length == 1)
15838
+ return null;
15839
+ const source = this.sources[segment[1]];
15840
+ if (!source)
15841
+ return null;
15842
+ return source.traceSegment(segment[2], segment[3], segment.length === 5 ? this.names[segment[4]] : name);
15843
+ }
15844
+ if (segment[0] > column) {
15845
+ searchEnd = m - 1;
15846
+ }
15847
+ else {
15848
+ searchStart = m + 1;
15712
15849
  }
15713
15850
  }
15714
- return true;
15851
+ return null;
15715
15852
  }
15716
- for (const entry of entryModules) {
15717
- if (!modulesInManualChunks.has(entry)) {
15718
- assignEntryToStaticDependencies(entry, null);
15853
+ }
15854
+ function getLinkMap(warn) {
15855
+ return function linkMap(source, map) {
15856
+ if (map.mappings) {
15857
+ return new Link(map, [source]);
15719
15858
  }
15859
+ warn({
15860
+ code: 'SOURCEMAP_BROKEN',
15861
+ message: `Sourcemap is likely to be incorrect: a plugin (${map.plugin}) was used to transform ` +
15862
+ "files, but didn't generate a sourcemap for the transformation. Consult the plugin " +
15863
+ 'documentation for help',
15864
+ plugin: map.plugin,
15865
+ url: `https://rollupjs.org/guide/en/#warning-sourcemap-is-likely-to-be-incorrect`
15866
+ });
15867
+ return new Link({
15868
+ mappings: [],
15869
+ names: []
15870
+ }, [source]);
15871
+ };
15872
+ }
15873
+ function getCollapsedSourcemap(id, originalCode, originalSourcemap, sourcemapChain, linkMap) {
15874
+ let source;
15875
+ if (!originalSourcemap) {
15876
+ source = new Source(id, originalCode);
15720
15877
  }
15721
- for (const entry of dynamicEntryModules) {
15722
- if (!modulesInManualChunks.has(entry)) {
15723
- assignEntryToStaticDependencies(entry, dynamicallyDependentEntryPointsByDynamicEntry.get(entry));
15724
- }
15878
+ else {
15879
+ const sources = originalSourcemap.sources;
15880
+ const sourcesContent = originalSourcemap.sourcesContent || [];
15881
+ const directory = dirname(id) || '.';
15882
+ const sourceRoot = originalSourcemap.sourceRoot || '.';
15883
+ const baseSources = sources.map((source, i) => new Source(resolve(directory, sourceRoot, source), sourcesContent[i]));
15884
+ source = new Link(originalSourcemap, baseSources);
15725
15885
  }
15726
- chunkDefinitions.push(...createChunks([...entryModules, ...dynamicEntryModules], assignedEntryPointsByModule));
15727
- return chunkDefinitions;
15886
+ return sourcemapChain.reduce(linkMap, source);
15728
15887
  }
15729
- function addStaticDependenciesToManualChunk(entry, manualChunkModules, modulesInManualChunks) {
15730
- const modulesToHandle = new Set([entry]);
15731
- for (const module of modulesToHandle) {
15732
- modulesInManualChunks.add(module);
15733
- manualChunkModules.push(module);
15734
- for (const dependency of module.dependencies) {
15735
- if (!(dependency instanceof ExternalModule || modulesInManualChunks.has(dependency))) {
15736
- modulesToHandle.add(dependency);
15737
- }
15738
- }
15888
+ function collapseSourcemaps(file, map, modules, bundleSourcemapChain, excludeContent, warn) {
15889
+ const linkMap = getLinkMap(warn);
15890
+ const moduleSources = modules
15891
+ .filter(module => !module.excludeFromSourcemap)
15892
+ .map(module => getCollapsedSourcemap(module.id, module.originalCode, module.originalSourcemap, module.sourcemapChain, linkMap));
15893
+ const link = new Link(map, moduleSources);
15894
+ const source = bundleSourcemapChain.reduce(linkMap, link);
15895
+ let { sources, sourcesContent, names, mappings } = source.traceMappings();
15896
+ if (file) {
15897
+ const directory = dirname(file);
15898
+ sources = sources.map((source) => relative$1(directory, source));
15899
+ file = basename(file);
15739
15900
  }
15901
+ sourcesContent = (excludeContent ? null : sourcesContent);
15902
+ return new SourceMap({ file, mappings, names, sources, sourcesContent });
15740
15903
  }
15741
- function analyzeModuleGraph(entryModules) {
15742
- const dynamicEntryModules = new Set();
15743
- const dependentEntryPointsByModule = new Map();
15744
- const entriesToHandle = new Set(entryModules);
15745
- for (const currentEntry of entriesToHandle) {
15746
- const modulesToHandle = new Set([currentEntry]);
15747
- for (const module of modulesToHandle) {
15748
- getOrCreate(dependentEntryPointsByModule, module, () => new Set()).add(currentEntry);
15749
- for (const dependency of module.getDependenciesToBeIncluded()) {
15750
- if (!(dependency instanceof ExternalModule)) {
15751
- modulesToHandle.add(dependency);
15752
- }
15753
- }
15754
- for (const { resolution } of module.dynamicImports) {
15755
- if (resolution instanceof Module && resolution.includedDynamicImporters.length > 0) {
15756
- dynamicEntryModules.add(resolution);
15757
- entriesToHandle.add(resolution);
15758
- }
15759
- }
15760
- for (const dependency of module.implicitlyLoadedBefore) {
15761
- dynamicEntryModules.add(dependency);
15762
- entriesToHandle.add(dependency);
15763
- }
15764
- }
15904
+ function collapseSourcemap(id, originalCode, originalSourcemap, sourcemapChain, warn) {
15905
+ if (!sourcemapChain.length) {
15906
+ return originalSourcemap;
15907
+ }
15908
+ const source = getCollapsedSourcemap(id, originalCode, originalSourcemap, sourcemapChain, getLinkMap(warn));
15909
+ const map = source.traceMappings();
15910
+ return { version: 3, ...map };
15911
+ }
15912
+
15913
+ function decodedSourcemap(map) {
15914
+ if (!map)
15915
+ return null;
15916
+ if (typeof map === 'string') {
15917
+ map = JSON.parse(map);
15918
+ }
15919
+ if (map.mappings === '') {
15920
+ return {
15921
+ mappings: [],
15922
+ names: [],
15923
+ sources: [],
15924
+ version: 3
15925
+ };
15765
15926
  }
15766
- return { dependentEntryPointsByModule, dynamicEntryModules };
15927
+ const mappings = typeof map.mappings === 'string' ? decode(map.mappings) : map.mappings;
15928
+ return { ...map, mappings };
15767
15929
  }
15768
- function getDynamicDependentEntryPoints(dependentEntryPointsByModule, dynamicEntryModules) {
15769
- const dynamicallyDependentEntryPointsByDynamicEntry = new Map();
15770
- for (const dynamicEntry of dynamicEntryModules) {
15771
- const dynamicDependentEntryPoints = getOrCreate(dynamicallyDependentEntryPointsByDynamicEntry, dynamicEntry, () => new Set());
15772
- for (const importer of [
15773
- ...dynamicEntry.includedDynamicImporters,
15774
- ...dynamicEntry.implicitlyLoadedAfter
15775
- ]) {
15776
- for (const entryPoint of dependentEntryPointsByModule.get(importer)) {
15777
- dynamicDependentEntryPoints.add(entryPoint);
15778
- }
15779
- }
15780
- }
15781
- return dynamicallyDependentEntryPointsByDynamicEntry;
15930
+
15931
+ async function renderChunks(chunks, outputBundle, pluginDriver, outputOptions, onwarn) {
15932
+ reserveEntryChunksInBundle(chunks);
15933
+ const renderedChunks = await Promise.all(chunks.map(chunk => chunk.render()));
15934
+ const chunkGraph = getChunkGraph(chunks);
15935
+ const { nonHashedChunksWithPlaceholders, renderedChunksByPlaceholder, hashDependenciesByPlaceholder } = await transformChunksAndGenerateContentHashes(renderedChunks, chunkGraph, outputOptions, pluginDriver, onwarn);
15936
+ const hashesByPlaceholder = generateFinalHashes(renderedChunksByPlaceholder, hashDependenciesByPlaceholder, outputBundle);
15937
+ addChunksToBundle(renderedChunksByPlaceholder, hashesByPlaceholder, outputBundle, nonHashedChunksWithPlaceholders);
15782
15938
  }
15783
- function createChunks(allEntryPoints, assignedEntryPointsByModule) {
15784
- const chunkModules = Object.create(null);
15785
- for (const [module, assignedEntryPoints] of assignedEntryPointsByModule) {
15786
- let chunkSignature = '';
15787
- for (const entry of allEntryPoints) {
15788
- chunkSignature += assignedEntryPoints.has(entry) ? 'X' : '_';
15789
- }
15790
- const chunk = chunkModules[chunkSignature];
15791
- if (chunk) {
15792
- chunk.push(module);
15793
- }
15794
- else {
15795
- chunkModules[chunkSignature] = [module];
15939
+ function reserveEntryChunksInBundle(chunks) {
15940
+ for (const chunk of chunks) {
15941
+ if (chunk.facadeModule && chunk.facadeModule.isUserDefinedEntryPoint) {
15942
+ // reserves name in bundle as side effect if it does not contain a hash
15943
+ chunk.getPreliminaryFileName();
15796
15944
  }
15797
15945
  }
15798
- return Object.values(chunkModules).map(modules => ({
15799
- alias: null,
15800
- modules
15801
- }));
15802
- }
15803
-
15804
- // ported from https://github.com/substack/node-commondir
15805
- function commondir(files) {
15806
- if (files.length === 0)
15807
- return '/';
15808
- if (files.length === 1)
15809
- return dirname(files[0]);
15810
- const commonSegments = files.slice(1).reduce((commonSegments, file) => {
15811
- const pathSegements = file.split(/\/+|\\+/);
15812
- let i;
15813
- for (i = 0; commonSegments[i] === pathSegements[i] &&
15814
- i < Math.min(commonSegments.length, pathSegements.length); i++)
15815
- ;
15816
- return commonSegments.slice(0, i);
15817
- }, files[0].split(/\/+|\\+/));
15818
- // Windows correctly handles paths with forward-slashes
15819
- return commonSegments.length > 1 ? commonSegments.join('/') : '/';
15820
15946
  }
15821
-
15822
- const compareExecIndex = (unitA, unitB) => unitA.execIndex > unitB.execIndex ? 1 : -1;
15823
- function sortByExecutionOrder(units) {
15824
- units.sort(compareExecIndex);
15947
+ function getChunkGraph(chunks) {
15948
+ return Object.fromEntries(chunks.map(chunk => {
15949
+ const renderedChunkInfo = chunk.getRenderedChunkInfo();
15950
+ return [renderedChunkInfo.fileName, renderedChunkInfo];
15951
+ }));
15825
15952
  }
15826
- function analyseModuleExecution(entryModules) {
15827
- let nextExecIndex = 0;
15828
- const cyclePaths = [];
15829
- const analysedModules = new Set();
15830
- const dynamicImports = new Set();
15831
- const parents = new Map();
15832
- const orderedModules = [];
15833
- const analyseModule = (module) => {
15834
- if (module instanceof Module) {
15835
- for (const dependency of module.dependencies) {
15836
- if (parents.has(dependency)) {
15837
- if (!analysedModules.has(dependency)) {
15838
- cyclePaths.push(getCyclePath(dependency, module, parents));
15839
- }
15840
- continue;
15953
+ async function transformChunk(magicString, fileName, usedModules, chunkGraph, options, outputPluginDriver, onwarn) {
15954
+ let map = null;
15955
+ const sourcemapChain = [];
15956
+ let code = await outputPluginDriver.hookReduceArg0('renderChunk', [magicString.toString(), chunkGraph[fileName], options, { chunks: chunkGraph }], (code, result, plugin) => {
15957
+ if (result == null)
15958
+ return code;
15959
+ if (typeof result === 'string')
15960
+ result = {
15961
+ code: result,
15962
+ map: undefined
15963
+ };
15964
+ // strict null check allows 'null' maps to not be pushed to the chain, while 'undefined' gets the missing map warning
15965
+ if (result.map !== null) {
15966
+ const map = decodedSourcemap(result.map);
15967
+ sourcemapChain.push(map || { missing: true, plugin: plugin.name });
15968
+ }
15969
+ return result.code;
15970
+ });
15971
+ const { compact, sourcemap, sourcemapPathTransform } = options;
15972
+ if (!compact && code[code.length - 1] !== '\n')
15973
+ code += '\n';
15974
+ if (sourcemap) {
15975
+ timeStart('sourcemap', 2);
15976
+ let file;
15977
+ if (options.file)
15978
+ file = resolve(options.sourcemapFile || options.file);
15979
+ else if (options.dir)
15980
+ file = resolve(options.dir, fileName);
15981
+ else
15982
+ file = resolve(fileName);
15983
+ const decodedMap = magicString.generateDecodedMap({});
15984
+ map = collapseSourcemaps(file, decodedMap, usedModules, sourcemapChain, options.sourcemapExcludeSources, onwarn);
15985
+ map.sources = map.sources
15986
+ .map(sourcePath => {
15987
+ if (sourcemapPathTransform) {
15988
+ const newSourcePath = sourcemapPathTransform(sourcePath, `${file}.map`);
15989
+ if (typeof newSourcePath !== 'string') {
15990
+ error(errFailedValidation(`sourcemapPathTransform function must return a string.`));
15841
15991
  }
15842
- parents.set(dependency, module);
15843
- analyseModule(dependency);
15992
+ return newSourcePath;
15844
15993
  }
15845
- for (const dependency of module.implicitlyLoadedBefore) {
15846
- dynamicImports.add(dependency);
15847
- }
15848
- for (const { resolution } of module.dynamicImports) {
15849
- if (resolution instanceof Module) {
15850
- dynamicImports.add(resolution);
15994
+ return sourcePath;
15995
+ })
15996
+ .map(normalize);
15997
+ timeEnd('sourcemap', 2);
15998
+ }
15999
+ return {
16000
+ code,
16001
+ map
16002
+ };
16003
+ }
16004
+ async function transformChunksAndGenerateContentHashes(renderedChunks, chunkGraph, outputOptions, pluginDriver, onwarn) {
16005
+ const nonHashedChunksWithPlaceholders = [];
16006
+ const renderedChunksByPlaceholder = new Map();
16007
+ const hashDependenciesByPlaceholder = new Map();
16008
+ const placeholders = new Set();
16009
+ for (const { preliminaryFileName: { hashPlaceholder } } of renderedChunks) {
16010
+ if (hashPlaceholder)
16011
+ placeholders.add(hashPlaceholder);
16012
+ }
16013
+ await Promise.all(renderedChunks.map(async ({ chunk, preliminaryFileName: { fileName, hashPlaceholder }, magicString, usedModules }) => {
16014
+ const transformedChunk = {
16015
+ chunk,
16016
+ fileName,
16017
+ ...(await transformChunk(magicString, fileName, usedModules, chunkGraph, outputOptions, pluginDriver, onwarn))
16018
+ };
16019
+ const { code } = transformedChunk;
16020
+ if (hashPlaceholder) {
16021
+ const hash = createHash();
16022
+ // To create a reproducible content-only hash, all placeholders are
16023
+ // replaced with the same value before hashing
16024
+ const { containedPlaceholders, transformedCode } = replacePlaceholdersWithDefaultAndGetContainedPlaceholders(code, placeholders);
16025
+ hash.update(transformedCode);
16026
+ const hashAugmentation = pluginDriver.hookReduceValueSync('augmentChunkHash', '', [chunk.getRenderedChunkInfo()], (augmentation, pluginHash) => {
16027
+ if (pluginHash) {
16028
+ augmentation += pluginHash;
15851
16029
  }
16030
+ return augmentation;
16031
+ });
16032
+ if (hashAugmentation) {
16033
+ hash.update(hashAugmentation);
15852
16034
  }
15853
- orderedModules.push(module);
15854
- }
15855
- module.execIndex = nextExecIndex++;
15856
- analysedModules.add(module);
15857
- };
15858
- for (const curEntry of entryModules) {
15859
- if (!parents.has(curEntry)) {
15860
- parents.set(curEntry, null);
15861
- analyseModule(curEntry);
16035
+ renderedChunksByPlaceholder.set(hashPlaceholder, transformedChunk);
16036
+ hashDependenciesByPlaceholder.set(hashPlaceholder, {
16037
+ containedPlaceholders,
16038
+ contentHash: hash.digest('hex')
16039
+ });
15862
16040
  }
15863
- }
15864
- for (const curEntry of dynamicImports) {
15865
- if (!parents.has(curEntry)) {
15866
- parents.set(curEntry, null);
15867
- analyseModule(curEntry);
16041
+ else {
16042
+ nonHashedChunksWithPlaceholders.push(transformedChunk);
15868
16043
  }
15869
- }
15870
- return { cyclePaths, orderedModules };
16044
+ }));
16045
+ return {
16046
+ hashDependenciesByPlaceholder,
16047
+ nonHashedChunksWithPlaceholders,
16048
+ renderedChunksByPlaceholder
16049
+ };
15871
16050
  }
15872
- function getCyclePath(module, parent, parents) {
15873
- const cycleSymbol = Symbol(module.id);
15874
- const path = [relativeId(module.id)];
15875
- let nextModule = parent;
15876
- module.cycles.add(cycleSymbol);
15877
- while (nextModule !== module) {
15878
- nextModule.cycles.add(cycleSymbol);
15879
- path.push(relativeId(nextModule.id));
15880
- nextModule = parents.get(nextModule);
16051
+ function generateFinalHashes(renderedChunksByPlaceholder, hashDependenciesByPlaceholder, outputBundle) {
16052
+ const hashesByPlaceholder = new Map();
16053
+ for (const [placeholder, { fileName }] of renderedChunksByPlaceholder) {
16054
+ let hash = createHash();
16055
+ const hashDependencyPlaceholders = new Set([placeholder]);
16056
+ for (const dependencyPlaceholder of hashDependencyPlaceholders) {
16057
+ const { containedPlaceholders, contentHash } = hashDependenciesByPlaceholder.get(dependencyPlaceholder);
16058
+ hash.update(contentHash);
16059
+ for (const containedPlaceholder of containedPlaceholders) {
16060
+ // When looping over a map, setting an entry only causes a new iteration if the key is new
16061
+ hashDependencyPlaceholders.add(containedPlaceholder);
16062
+ }
16063
+ }
16064
+ let finalFileName;
16065
+ let finalHash;
16066
+ do {
16067
+ // In case of a hash collision, create a hash of the hash
16068
+ if (finalHash) {
16069
+ hash = createHash();
16070
+ hash.update(finalHash);
16071
+ }
16072
+ finalHash = hash.digest('hex').slice(0, placeholder.length);
16073
+ finalFileName = replaceSinglePlaceholder(fileName, placeholder, finalHash);
16074
+ } while (outputBundle[finalFileName]);
16075
+ outputBundle[finalFileName] = FILE_PLACEHOLDER;
16076
+ hashesByPlaceholder.set(placeholder, finalHash.slice(0, placeholder.length));
15881
16077
  }
15882
- path.push(path[0]);
15883
- path.reverse();
15884
- return path;
16078
+ return hashesByPlaceholder;
15885
16079
  }
15886
-
15887
- function getGenerateCodeSnippets({ compact, generatedCode: { arrowFunctions, constBindings, objectShorthand, reservedNamesAsProps } }) {
15888
- const { _, n, s } = compact ? { _: '', n: '', s: '' } : { _: ' ', n: '\n', s: ';' };
15889
- const cnst = constBindings ? 'const' : 'var';
15890
- const getNonArrowFunctionIntro = (params, { isAsync, name }) => `${isAsync ? `async ` : ''}function${name ? ` ${name}` : ''}${_}(${params.join(`,${_}`)})${_}`;
15891
- const getFunctionIntro = arrowFunctions
15892
- ? (params, { isAsync, name }) => {
15893
- const singleParam = params.length === 1;
15894
- const asyncString = isAsync ? `async${singleParam ? ' ' : _}` : '';
15895
- return `${name ? `${cnst} ${name}${_}=${_}` : ''}${asyncString}${singleParam ? params[0] : `(${params.join(`,${_}`)})`}${_}=>${_}`;
16080
+ function addChunksToBundle(renderedChunksByPlaceholder, hashesByPlaceholder, outputBundle, nonHashedChunksWithPlaceholders) {
16081
+ for (const { chunk, code, fileName, map } of renderedChunksByPlaceholder.values()) {
16082
+ const updatedCode = replacePlaceholders(code, hashesByPlaceholder);
16083
+ const finalFileName = replacePlaceholders(fileName, hashesByPlaceholder);
16084
+ if (map) {
16085
+ map.file = replacePlaceholders(map.file, hashesByPlaceholder);
15896
16086
  }
15897
- : getNonArrowFunctionIntro;
15898
- const getDirectReturnFunction = (params, { functionReturn, lineBreakIndent, name }) => [
15899
- `${getFunctionIntro(params, {
15900
- isAsync: false,
15901
- name
15902
- })}${arrowFunctions
15903
- ? lineBreakIndent
15904
- ? `${n}${lineBreakIndent.base}${lineBreakIndent.t}`
15905
- : ''
15906
- : `{${lineBreakIndent ? `${n}${lineBreakIndent.base}${lineBreakIndent.t}` : _}${functionReturn ? 'return ' : ''}`}`,
15907
- arrowFunctions
15908
- ? `${name ? ';' : ''}${lineBreakIndent ? `${n}${lineBreakIndent.base}` : ''}`
15909
- : `${s}${lineBreakIndent ? `${n}${lineBreakIndent.base}` : _}}`
15910
- ];
15911
- const isValidPropName = reservedNamesAsProps
15912
- ? (name) => validPropName.test(name)
15913
- : (name) => !RESERVED_NAMES$1.has(name) && validPropName.test(name);
15914
- return {
15915
- _,
15916
- cnst,
15917
- getDirectReturnFunction,
15918
- getDirectReturnIifeLeft: (params, returned, { needsArrowReturnParens, needsWrappedFunction }) => {
15919
- const [left, right] = getDirectReturnFunction(params, {
15920
- functionReturn: true,
15921
- lineBreakIndent: null,
15922
- name: null
15923
- });
15924
- return `${wrapIfNeeded(`${left}${wrapIfNeeded(returned, arrowFunctions && needsArrowReturnParens)}${right}`, arrowFunctions || needsWrappedFunction)}(`;
15925
- },
15926
- getFunctionIntro,
15927
- getNonArrowFunctionIntro,
15928
- getObject(fields, { lineBreakIndent }) {
15929
- const prefix = lineBreakIndent ? `${n}${lineBreakIndent.base}${lineBreakIndent.t}` : _;
15930
- return `{${fields
15931
- .map(([key, value]) => {
15932
- if (key === null)
15933
- return `${prefix}${value}`;
15934
- const needsQuotes = !isValidPropName(key);
15935
- return key === value && objectShorthand && !needsQuotes
15936
- ? prefix + key
15937
- : `${prefix}${needsQuotes ? `'${key}'` : key}:${_}${value}`;
15938
- })
15939
- .join(`,`)}${fields.length === 0 ? '' : lineBreakIndent ? `${n}${lineBreakIndent.base}` : _}}`;
15940
- },
15941
- getPropertyAccess: (name) => isValidPropName(name) ? `.${name}` : `[${JSON.stringify(name)}]`,
15942
- n,
15943
- s
15944
- };
16087
+ outputBundle[finalFileName] = chunk.generateOutputChunk(updatedCode, map, hashesByPlaceholder);
16088
+ }
16089
+ for (const { chunk, code, fileName, map } of nonHashedChunksWithPlaceholders) {
16090
+ const updatedCode = hashesByPlaceholder.size
16091
+ ? replacePlaceholders(code, hashesByPlaceholder)
16092
+ : code;
16093
+ outputBundle[fileName] = chunk.generateOutputChunk(updatedCode, map, hashesByPlaceholder);
16094
+ }
15945
16095
  }
15946
- const wrapIfNeeded = (code, needsParens) => needsParens ? `(${code})` : code;
15947
- const validPropName = /^(?!\d)[\w$]+$/;
15948
16096
 
15949
16097
  class Bundle {
15950
16098
  constructor(outputOptions, unsetOptions, inputOptions, pluginDriver, graph) {
@@ -15959,24 +16107,24 @@ class Bundle {
15959
16107
  async generate(isWrite) {
15960
16108
  timeStart('GENERATE', 1);
15961
16109
  const outputBundle = Object.create(null);
15962
- this.pluginDriver.setOutputBundle(outputBundle, this.outputOptions, this.facadeChunkByModule);
16110
+ this.pluginDriver.setOutputBundle(outputBundle, this.outputOptions);
16111
+ // TODO Lukas rethink time measuring points
15963
16112
  try {
15964
16113
  await this.pluginDriver.hookParallel('renderStart', [this.outputOptions, this.inputOptions]);
15965
16114
  timeStart('generate chunks', 2);
15966
- const chunks = await this.generateChunks();
16115
+ const getHashPlaceholder = getHashPlaceholderGenerator();
16116
+ const chunks = await this.generateChunks(outputBundle, getHashPlaceholder);
15967
16117
  if (chunks.length > 1) {
15968
16118
  validateOptionsForMultiChunkOutput(this.outputOptions, this.inputOptions.onwarn);
15969
16119
  }
15970
- const inputBase = commondir(getAbsoluteEntryModulePaths(chunks));
16120
+ this.pluginDriver.setChunkInformation(this.facadeChunkByModule);
15971
16121
  timeEnd('generate chunks', 2);
15972
- timeStart('render modules', 2);
15973
- // We need to create addons before prerender because at the moment, there
15974
- // can be no async code between prerender and render due to internal state
15975
- const addons = await createAddons(this.outputOptions, this.pluginDriver);
15976
- const snippets = getGenerateCodeSnippets(this.outputOptions);
15977
- this.prerenderChunks(chunks, inputBase, snippets);
15978
- timeEnd('render modules', 2);
15979
- await this.addFinalizedChunksToBundle(chunks, inputBase, addons, outputBundle, snippets);
16122
+ timeStart('render chunks', 2);
16123
+ for (const chunk of chunks) {
16124
+ chunk.generateExports();
16125
+ }
16126
+ await renderChunks(chunks, outputBundle, this.pluginDriver, this.outputOptions, this.inputOptions.onwarn);
16127
+ timeEnd('render chunks', 2);
15980
16128
  }
15981
16129
  catch (err) {
15982
16130
  await this.pluginDriver.hookParallel('renderError', [err]);
@@ -15991,16 +16139,6 @@ class Bundle {
15991
16139
  timeEnd('GENERATE', 1);
15992
16140
  return outputBundle;
15993
16141
  }
15994
- async addFinalizedChunksToBundle(chunks, inputBase, addons, outputBundle, snippets) {
15995
- this.assignChunkIds(chunks, inputBase, addons, outputBundle);
15996
- for (const chunk of chunks) {
15997
- outputBundle[chunk.id] = chunk.getChunkInfoWithFileNames();
15998
- }
15999
- await Promise.all(chunks.map(async (chunk) => {
16000
- const outputChunk = outputBundle[chunk.id];
16001
- Object.assign(outputChunk, await chunk.render(this.outputOptions, addons, outputChunk, snippets));
16002
- }));
16003
- }
16004
16142
  async addManualChunks(manualChunks) {
16005
16143
  const manualChunkAliasByEntry = new Map();
16006
16144
  const chunkEntries = await Promise.all(Object.entries(manualChunks).map(async ([alias, files]) => ({
@@ -16014,29 +16152,6 @@ class Bundle {
16014
16152
  }
16015
16153
  return manualChunkAliasByEntry;
16016
16154
  }
16017
- assignChunkIds(chunks, inputBase, addons, bundle) {
16018
- const entryChunks = [];
16019
- const otherChunks = [];
16020
- for (const chunk of chunks) {
16021
- (chunk.facadeModule && chunk.facadeModule.isUserDefinedEntryPoint
16022
- ? entryChunks
16023
- : otherChunks).push(chunk);
16024
- }
16025
- // make sure entry chunk names take precedence with regard to deconflicting
16026
- const chunksForNaming = entryChunks.concat(otherChunks);
16027
- for (const chunk of chunksForNaming) {
16028
- if (this.outputOptions.file) {
16029
- chunk.id = basename(this.outputOptions.file);
16030
- }
16031
- else if (this.outputOptions.preserveModules) {
16032
- chunk.id = chunk.generateIdPreserveModules(inputBase, this.outputOptions, bundle, this.unsetOptions);
16033
- }
16034
- else {
16035
- chunk.id = chunk.generateId(addons, this.outputOptions, bundle, true);
16036
- }
16037
- bundle[chunk.id] = FILE_PLACEHOLDER;
16038
- }
16039
- }
16040
16155
  assignManualChunks(getManualChunk) {
16041
16156
  const manualChunkAliasesWithEntry = [];
16042
16157
  const manualChunksApi = {
@@ -16060,10 +16175,6 @@ class Bundle {
16060
16175
  }
16061
16176
  finaliseAssets(outputBundle) {
16062
16177
  for (const file of Object.values(outputBundle)) {
16063
- if (!file.type) {
16064
- 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);
16065
- file.type = 'asset';
16066
- }
16067
16178
  if (this.outputOptions.validate && 'code' in file) {
16068
16179
  try {
16069
16180
  this.graph.contextParse(file.code, {
@@ -16078,27 +16189,25 @@ class Bundle {
16078
16189
  }
16079
16190
  this.pluginDriver.finaliseAssets();
16080
16191
  }
16081
- async generateChunks() {
16082
- const { manualChunks } = this.outputOptions;
16192
+ async generateChunks(bundle, getHashPlaceholder) {
16193
+ const { inlineDynamicImports, manualChunks, preserveModules } = this.outputOptions;
16083
16194
  const manualChunkAliasByEntry = typeof manualChunks === 'object'
16084
16195
  ? await this.addManualChunks(manualChunks)
16085
16196
  : this.assignManualChunks(manualChunks);
16197
+ const snippets = getGenerateCodeSnippets(this.outputOptions);
16198
+ const includedModules = getIncludedModules(this.graph.modulesById);
16199
+ const inputBase = commondir(getAbsoluteEntryModulePaths(includedModules, preserveModules));
16200
+ const externalChunkByModule = getExternalChunkByModule(this.graph.modulesById, this.outputOptions, inputBase);
16086
16201
  const chunks = [];
16087
16202
  const chunkByModule = new Map();
16088
- for (const { alias, modules } of this.outputOptions.inlineDynamicImports
16089
- ? [{ alias: null, modules: getIncludedModules(this.graph.modulesById) }]
16090
- : this.outputOptions.preserveModules
16091
- ? getIncludedModules(this.graph.modulesById).map(module => ({
16092
- alias: null,
16093
- modules: [module]
16094
- }))
16203
+ for (const { alias, modules } of inlineDynamicImports
16204
+ ? [{ alias: null, modules: includedModules }]
16205
+ : preserveModules
16206
+ ? includedModules.map(module => ({ alias: null, modules: [module] }))
16095
16207
  : getChunkAssignments(this.graph.entryModules, manualChunkAliasByEntry)) {
16096
16208
  sortByExecutionOrder(modules);
16097
- const chunk = new Chunk(modules, this.inputOptions, this.outputOptions, this.unsetOptions, this.pluginDriver, this.graph.modulesById, chunkByModule, this.facadeChunkByModule, this.includedNamespaces, alias);
16209
+ 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);
16098
16210
  chunks.push(chunk);
16099
- for (const module of modules) {
16100
- chunkByModule.set(module, chunk);
16101
- }
16102
16211
  }
16103
16212
  for (const chunk of chunks) {
16104
16213
  chunk.link();
@@ -16109,25 +16218,6 @@ class Bundle {
16109
16218
  }
16110
16219
  return [...chunks, ...facades];
16111
16220
  }
16112
- prerenderChunks(chunks, inputBase, snippets) {
16113
- for (const chunk of chunks) {
16114
- chunk.generateExports();
16115
- }
16116
- for (const chunk of chunks) {
16117
- chunk.preRender(this.outputOptions, inputBase, snippets);
16118
- }
16119
- }
16120
- }
16121
- function getAbsoluteEntryModulePaths(chunks) {
16122
- const absoluteEntryModulePaths = [];
16123
- for (const chunk of chunks) {
16124
- for (const entryModule of chunk.entryModules) {
16125
- if (isAbsolute(entryModule.id)) {
16126
- absoluteEntryModulePaths.push(entryModule.id);
16127
- }
16128
- }
16129
- }
16130
- return absoluteEntryModulePaths;
16131
16221
  }
16132
16222
  function validateOptionsForMultiChunkOutput(outputOptions, onWarn) {
16133
16223
  if (outputOptions.format === 'umd' || outputOptions.format === 'iife')
@@ -16140,8 +16230,32 @@ function validateOptionsForMultiChunkOutput(outputOptions, onWarn) {
16140
16230
  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'));
16141
16231
  }
16142
16232
  function getIncludedModules(modulesById) {
16143
- return [...modulesById.values()].filter((module) => module instanceof Module &&
16144
- (module.isIncluded() || module.info.isEntry || module.includedDynamicImporters.length > 0));
16233
+ const includedModules = [];
16234
+ for (const module of modulesById.values()) {
16235
+ if (module instanceof Module &&
16236
+ (module.isIncluded() || module.info.isEntry || module.includedDynamicImporters.length > 0)) {
16237
+ includedModules.push(module);
16238
+ }
16239
+ }
16240
+ return includedModules;
16241
+ }
16242
+ function getAbsoluteEntryModulePaths(includedModules, preserveModules) {
16243
+ const absoluteEntryModulePaths = [];
16244
+ for (const module of includedModules) {
16245
+ if ((module.info.isEntry || preserveModules) && isAbsolute(module.id)) {
16246
+ absoluteEntryModulePaths.push(module.id);
16247
+ }
16248
+ }
16249
+ return absoluteEntryModulePaths;
16250
+ }
16251
+ function getExternalChunkByModule(modulesById, outputOptions, inputBase) {
16252
+ const externalChunkByModule = new Map();
16253
+ for (const module of modulesById.values()) {
16254
+ if (module instanceof ExternalModule) {
16255
+ externalChunkByModule.set(module, new ExternalChunk(module, outputOptions, inputBase));
16256
+ }
16257
+ }
16258
+ return externalChunkByModule;
16145
16259
  }
16146
16260
  function addModuleToManualChunk(alias, module, manualChunkAliasByEntry) {
16147
16261
  const existingAlias = manualChunkAliasByEntry.get(module);
@@ -21783,7 +21897,7 @@ async function findFile(file, preserveSymlinks) {
21783
21897
  return file;
21784
21898
  }
21785
21899
  }
21786
- catch (_a) {
21900
+ catch {
21787
21901
  // suppress
21788
21902
  }
21789
21903
  }
@@ -21806,21 +21920,6 @@ function throwPluginError(err, plugin, { hook, id } = {}) {
21806
21920
  }
21807
21921
  return error(err);
21808
21922
  }
21809
- const deprecatedHooks = [
21810
- { active: true, deprecated: 'resolveAssetUrl', replacement: 'resolveFileUrl' }
21811
- ];
21812
- function warnDeprecatedHooks(plugins, options) {
21813
- for (const { active, deprecated, replacement } of deprecatedHooks) {
21814
- for (const plugin of plugins) {
21815
- if (deprecated in plugin) {
21816
- warnDeprecation({
21817
- message: `The "${deprecated}" hook used by plugin ${plugin.name} is deprecated. The "${replacement}" hook should be used instead.`,
21818
- plugin: plugin.name
21819
- }, active, options);
21820
- }
21821
- }
21822
- }
21823
- }
21824
21923
 
21825
21924
  function createPluginCache(cache) {
21826
21925
  return {
@@ -21962,14 +22061,6 @@ async function transform(source, module, pluginDriver, warn) {
21962
22061
  cache: customTransformCache
21963
22062
  ? pluginContext.cache
21964
22063
  : getTrackedPluginCache(pluginContext.cache, useCustomTransformCache),
21965
- emitAsset(name, source) {
21966
- emittedFiles.push({ name, source, type: 'asset' });
21967
- return pluginContext.emitAsset(name, source);
21968
- },
21969
- emitChunk(id, options) {
21970
- emittedFiles.push({ id, name: options && options.name, type: 'chunk' });
21971
- return pluginContext.emitChunk(id, options);
21972
- },
21973
22064
  emitFile(emittedFile) {
21974
22065
  emittedFiles.push(emittedFile);
21975
22066
  return pluginDriver.emitFile(emittedFile);
@@ -22479,19 +22570,6 @@ class GlobalScope extends Scope$1 {
22479
22570
  }
22480
22571
  }
22481
22572
 
22482
- function getDeprecatedContextHandler(handler, handlerName, newHandlerName, pluginName, activeDeprecation, options) {
22483
- let deprecationWarningShown = false;
22484
- return ((...args) => {
22485
- if (!deprecationWarningShown) {
22486
- deprecationWarningShown = true;
22487
- warnDeprecation({
22488
- message: `The "this.${handlerName}" plugin context function used by plugin ${pluginName} is deprecated. The "this.${newHandlerName}" plugin context function should be used instead.`,
22489
- plugin: pluginName
22490
- }, activeDeprecation, options);
22491
- }
22492
- return handler(...args);
22493
- });
22494
- }
22495
22573
  function getPluginContext(plugin, pluginCache, graph, options, fileEmitter, existingPluginNames) {
22496
22574
  let cacheable = true;
22497
22575
  if (typeof plugin.cacheKey !== 'string') {
@@ -22523,19 +22601,14 @@ function getPluginContext(plugin, pluginCache, graph, options, fileEmitter, exis
22523
22601
  graph.watchFiles[id] = true;
22524
22602
  },
22525
22603
  cache: cacheInstance,
22526
- emitAsset: getDeprecatedContextHandler((name, source) => fileEmitter.emitFile({ name, source, type: 'asset' }), 'emitAsset', 'emitFile', plugin.name, true, options),
22527
- emitChunk: getDeprecatedContextHandler((id, options) => fileEmitter.emitFile({ id, name: options && options.name, type: 'chunk' }), 'emitChunk', 'emitFile', plugin.name, true, options),
22528
22604
  emitFile: fileEmitter.emitFile.bind(fileEmitter),
22529
22605
  error(err) {
22530
22606
  return throwPluginError(err, plugin.name);
22531
22607
  },
22532
- getAssetFileName: getDeprecatedContextHandler(fileEmitter.getFileName, 'getAssetFileName', 'getFileName', plugin.name, true, options),
22533
- getChunkFileName: getDeprecatedContextHandler(fileEmitter.getFileName, 'getChunkFileName', 'getFileName', plugin.name, true, options),
22534
22608
  getFileName: fileEmitter.getFileName,
22535
22609
  getModuleIds: () => graph.modulesById.keys(),
22536
22610
  getModuleInfo: graph.getModuleInfo,
22537
22611
  getWatchFiles: () => Object.keys(graph.watchFiles),
22538
- isExternal: getDeprecatedContextHandler((id, parentId, isResolved = false) => options.external(id, parentId, isResolved), 'isExternal', 'resolve', plugin.name, true, options),
22539
22612
  load(resolvedId) {
22540
22613
  return graph.moduleLoader.preloadModule(resolvedId);
22541
22614
  },
@@ -22549,7 +22622,7 @@ function getPluginContext(plugin, pluginCache, graph, options, fileEmitter, exis
22549
22622
  warnDeprecation({
22550
22623
  message: `Accessing "this.moduleIds" on the plugin context by plugin ${plugin.name} is deprecated. The "this.getModuleIds" plugin context function should be used instead.`,
22551
22624
  plugin: plugin.name
22552
- }, false, options);
22625
+ }, true, options);
22553
22626
  yield* moduleIds;
22554
22627
  }
22555
22628
  const moduleIds = graph.modulesById.keys();
@@ -22559,9 +22632,6 @@ function getPluginContext(plugin, pluginCache, graph, options, fileEmitter, exis
22559
22632
  resolve(source, importer, { custom, isEntry, skipSelf } = BLANK) {
22560
22633
  return graph.moduleLoader.resolveId(source, importer, custom, isEntry, skipSelf ? [{ importer, plugin, source }] : null);
22561
22634
  },
22562
- resolveId: getDeprecatedContextHandler((source, importer) => graph.moduleLoader
22563
- .resolveId(source, importer, BLANK, undefined)
22564
- .then(resolveId => resolveId && resolveId.id), 'resolveId', 'resolve', plugin.name, true, options),
22565
22635
  setAssetSource: fileEmitter.setAssetSource,
22566
22636
  warn(warning) {
22567
22637
  if (typeof warning === 'string')
@@ -22602,12 +22672,12 @@ class PluginDriver {
22602
22672
  this.graph = graph;
22603
22673
  this.options = options;
22604
22674
  this.unfulfilledActions = new Set();
22605
- warnDeprecatedHooks(userPlugins, options);
22606
22675
  this.pluginCache = pluginCache;
22607
22676
  this.fileEmitter = new FileEmitter(graph, options, basePluginDriver && basePluginDriver.fileEmitter);
22608
22677
  this.emitFile = this.fileEmitter.emitFile.bind(this.fileEmitter);
22609
22678
  this.getFileName = this.fileEmitter.getFileName.bind(this.fileEmitter);
22610
- this.finaliseAssets = this.fileEmitter.assertAssetsFinalized.bind(this.fileEmitter);
22679
+ this.finaliseAssets = this.fileEmitter.finaliseAssets.bind(this.fileEmitter);
22680
+ this.setChunkInformation = this.fileEmitter.setChunkInformation.bind(this.fileEmitter);
22611
22681
  this.setOutputBundle = this.fileEmitter.setOutputBundle.bind(this.fileEmitter);
22612
22682
  this.plugins = userPlugins.concat(basePluginDriver ? basePluginDriver.plugins : []);
22613
22683
  const existingPluginNames = new Set();
@@ -23167,7 +23237,7 @@ function normalizeInputOptions(config) {
23167
23237
  preserveSymlinks: config.preserveSymlinks || false,
23168
23238
  shimMissingExports: config.shimMissingExports || false,
23169
23239
  strictDeprecations,
23170
- treeshake: getTreeshake(config, onwarn, strictDeprecations)
23240
+ treeshake: getTreeshake(config)
23171
23241
  };
23172
23242
  warnUnknownOptions(config, [...Object.keys(options), 'watch'], 'input options', options.onwarn, /^(output)$/);
23173
23243
  return { options, unsetOptions };
@@ -23223,7 +23293,7 @@ const getIdMatcher = (option) => {
23223
23293
  const getInlineDynamicImports$1 = (config, warn, strictDeprecations) => {
23224
23294
  const configInlineDynamicImports = config.inlineDynamicImports;
23225
23295
  if (configInlineDynamicImports) {
23226
- warnDeprecationWithOptions('The "inlineDynamicImports" option is deprecated. Use the "output.inlineDynamicImports" option instead.', false, warn, strictDeprecations);
23296
+ warnDeprecationWithOptions('The "inlineDynamicImports" option is deprecated. Use the "output.inlineDynamicImports" option instead.', true, warn, strictDeprecations);
23227
23297
  }
23228
23298
  return configInlineDynamicImports;
23229
23299
  };
@@ -23234,7 +23304,7 @@ const getInput = (config) => {
23234
23304
  const getManualChunks$1 = (config, warn, strictDeprecations) => {
23235
23305
  const configManualChunks = config.manualChunks;
23236
23306
  if (configManualChunks) {
23237
- warnDeprecationWithOptions('The "manualChunks" option is deprecated. Use the "output.manualChunks" option instead.', false, warn, strictDeprecations);
23307
+ warnDeprecationWithOptions('The "manualChunks" option is deprecated. Use the "output.manualChunks" option instead.', true, warn, strictDeprecations);
23238
23308
  }
23239
23309
  return configManualChunks;
23240
23310
  };
@@ -23271,25 +23341,20 @@ const getPreserveEntrySignatures = (config, unsetOptions) => {
23271
23341
  const getPreserveModules$1 = (config, warn, strictDeprecations) => {
23272
23342
  const configPreserveModules = config.preserveModules;
23273
23343
  if (configPreserveModules) {
23274
- warnDeprecationWithOptions('The "preserveModules" option is deprecated. Use the "output.preserveModules" option instead.', false, warn, strictDeprecations);
23344
+ warnDeprecationWithOptions('The "preserveModules" option is deprecated. Use the "output.preserveModules" option instead.', true, warn, strictDeprecations);
23275
23345
  }
23276
23346
  return configPreserveModules;
23277
23347
  };
23278
- const getTreeshake = (config, warn, strictDeprecations) => {
23348
+ const getTreeshake = (config) => {
23279
23349
  const configTreeshake = config.treeshake;
23280
23350
  if (configTreeshake === false) {
23281
23351
  return false;
23282
23352
  }
23283
23353
  const configWithPreset = getOptionWithPreset(config.treeshake, treeshakePresets, 'treeshake', 'false, true, ');
23284
- if (typeof configWithPreset.pureExternalModules !== 'undefined') {
23285
- 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);
23286
- }
23287
23354
  return {
23288
23355
  annotations: configWithPreset.annotations !== false,
23289
23356
  correctVarValueBeforeDeclaration: configWithPreset.correctVarValueBeforeDeclaration === true,
23290
- moduleSideEffects: typeof configTreeshake === 'object' && configTreeshake.pureExternalModules
23291
- ? getHasModuleSideEffects(configTreeshake.moduleSideEffects, configTreeshake.pureExternalModules)
23292
- : getHasModuleSideEffects(configWithPreset.moduleSideEffects, undefined),
23357
+ moduleSideEffects: getHasModuleSideEffects(configWithPreset.moduleSideEffects),
23293
23358
  propertyReadSideEffects: configWithPreset.propertyReadSideEffects === 'always'
23294
23359
  ? 'always'
23295
23360
  : configWithPreset.propertyReadSideEffects !== false,
@@ -23297,7 +23362,7 @@ const getTreeshake = (config, warn, strictDeprecations) => {
23297
23362
  unknownGlobalSideEffects: configWithPreset.unknownGlobalSideEffects !== false
23298
23363
  };
23299
23364
  };
23300
- const getHasModuleSideEffects = (moduleSideEffectsOption, pureExternalModules) => {
23365
+ const getHasModuleSideEffects = (moduleSideEffectsOption) => {
23301
23366
  if (typeof moduleSideEffectsOption === 'boolean') {
23302
23367
  return () => moduleSideEffectsOption;
23303
23368
  }
@@ -23314,8 +23379,7 @@ const getHasModuleSideEffects = (moduleSideEffectsOption, pureExternalModules) =
23314
23379
  if (moduleSideEffectsOption) {
23315
23380
  error(errInvalidOption('treeshake.moduleSideEffects', 'treeshake', 'please use one of false, "no-external", a function or an array'));
23316
23381
  }
23317
- const isPureExternalModule = getIdMatcher(pureExternalModules);
23318
- return (id, external) => !(external && isPureExternalModule(id));
23382
+ return () => true;
23319
23383
  };
23320
23384
 
23321
23385
  // https://datatracker.ietf.org/doc/html/rfc2396
@@ -23349,7 +23413,7 @@ function normalizeOutputOptions(config, inputOptions, unsetInputOptions) {
23349
23413
  chunkFileNames: (_b = config.chunkFileNames) !== null && _b !== void 0 ? _b : '[name]-[hash].js',
23350
23414
  compact,
23351
23415
  dir: getDir(config, file),
23352
- dynamicImportFunction: getDynamicImportFunction(config, inputOptions),
23416
+ dynamicImportFunction: getDynamicImportFunction(config, inputOptions, format),
23353
23417
  entryFileNames: getEntryFileNames(config, unsetOptions),
23354
23418
  esModule: (_c = config.esModule) !== null && _c !== void 0 ? _c : true,
23355
23419
  exports: getExports(config, unsetOptions),
@@ -23454,7 +23518,7 @@ const getPreserveModules = (config, inlineDynamicImports, inputOptions) => {
23454
23518
  const getPreferConst = (config, inputOptions) => {
23455
23519
  const configPreferConst = config.preferConst;
23456
23520
  if (configPreferConst != null) {
23457
- warnDeprecation(`The "output.preferConst" option is deprecated. Use the "output.generatedCode.constBindings" option instead.`, false, inputOptions);
23521
+ warnDeprecation(`The "output.preferConst" option is deprecated. Use the "output.generatedCode.constBindings" option instead.`, true, inputOptions);
23458
23522
  }
23459
23523
  return !!configPreferConst;
23460
23524
  };
@@ -23509,10 +23573,13 @@ const getDir = (config, file) => {
23509
23573
  }
23510
23574
  return dir;
23511
23575
  };
23512
- const getDynamicImportFunction = (config, inputOptions) => {
23576
+ const getDynamicImportFunction = (config, inputOptions, format) => {
23513
23577
  const configDynamicImportFunction = config.dynamicImportFunction;
23514
23578
  if (configDynamicImportFunction) {
23515
- warnDeprecation(`The "output.dynamicImportFunction" option is deprecated. Use the "renderDynamicImport" plugin hook instead.`, false, inputOptions);
23579
+ warnDeprecation(`The "output.dynamicImportFunction" option is deprecated. Use the "renderDynamicImport" plugin hook instead.`, true, inputOptions);
23580
+ if (format !== 'es') {
23581
+ inputOptions.onwarn(errInvalidOption('output.dynamicImportFunction', 'outputdynamicImportFunction', 'this option is ignored for formats other than "es"'));
23582
+ }
23516
23583
  }
23517
23584
  return configDynamicImportFunction;
23518
23585
  };
@@ -23571,7 +23638,7 @@ const getInterop = (config, inputOptions) => {
23571
23638
  warnDeprecation({
23572
23639
  message: `The boolean value "${interop}" for the "output.interop" option is deprecated. Use ${interop ? '"auto"' : '"esModule", "default" or "defaultOnly"'} instead.`,
23573
23640
  url: 'https://rollupjs.org/guide/en/#outputinterop'
23574
- }, false, inputOptions);
23641
+ }, true, inputOptions);
23575
23642
  }
23576
23643
  }
23577
23644
  return interop;
@@ -23603,7 +23670,7 @@ const getMinifyInternalExports = (config, format, compact) => { var _a; return (
23603
23670
  const getNamespaceToStringTag = (config, generatedCode, inputOptions) => {
23604
23671
  const configNamespaceToStringTag = config.namespaceToStringTag;
23605
23672
  if (configNamespaceToStringTag != null) {
23606
- warnDeprecation(`The "output.namespaceToStringTag" option is deprecated. Use the "output.generatedCode.symbols" option instead.`, false, inputOptions);
23673
+ warnDeprecation(`The "output.namespaceToStringTag" option is deprecated. Use the "output.generatedCode.symbols" option instead.`, true, inputOptions);
23607
23674
  return configNamespaceToStringTag;
23608
23675
  }
23609
23676
  return generatedCode.symbols || false;