rollup 3.1.0 → 3.2.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 v3.1.0
4
- Wed, 12 Oct 2022 08:54:50 GMT - commit f7b768992209a970c240799cdff12a4fa437c0d4
3
+ Rollup.js v3.2.0
4
+ Sat, 15 Oct 2022 04:47:20 GMT - commit 585de6d1bc569c4f1d49654cae1044cefa277fb7
5
5
 
6
6
  https://github.com/rollup/rollup
7
7
 
@@ -9,13 +9,14 @@
9
9
  */
10
10
  import { resolve, basename, extname, dirname, relative as relative$1 } from 'node:path';
11
11
  import require$$0$1, { win32, posix, isAbsolute as isAbsolute$1, resolve as resolve$1 } from 'path';
12
- import process$1 from 'node:process';
12
+ import process$1, { env as env$1 } from 'node:process';
13
13
  import { performance } from 'node:perf_hooks';
14
14
  import { createHash as createHash$1 } from 'node:crypto';
15
15
  import { promises } from 'node:fs';
16
16
  import { EventEmitter } from 'node:events';
17
+ import * as tty from 'tty';
17
18
 
18
- var version$1 = "3.1.0";
19
+ var version$1 = "3.2.0";
19
20
 
20
21
  var charToInteger = {};
21
22
  var chars$1 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
@@ -1582,16 +1583,16 @@ function relative(from, to) {
1582
1583
  return toParts.join('/');
1583
1584
  }
1584
1585
 
1585
- const needsEscapeRegEx = /[\\'\r\n\u2028\u2029]/;
1586
- const quoteNewlineRegEx = /(['\r\n\u2028\u2029])/g;
1586
+ const needsEscapeRegEx = /[\n\r'\\\u2028\u2029]/;
1587
+ const quoteNewlineRegEx = /([\n\r'\u2028\u2029])/g;
1587
1588
  const backSlashRegEx = /\\/g;
1588
1589
  function escapeId(id) {
1589
- if (!id.match(needsEscapeRegEx))
1590
+ if (!needsEscapeRegEx.test(id))
1590
1591
  return id;
1591
1592
  return id.replace(backSlashRegEx, '\\\\').replace(quoteNewlineRegEx, '\\$1');
1592
1593
  }
1593
1594
 
1594
- const ABSOLUTE_PATH_REGEX = /^(?:\/|(?:[A-Za-z]:)?[\\|/])/;
1595
+ const ABSOLUTE_PATH_REGEX = /^(?:\/|(?:[A-Za-z]:)?[/\\|])/;
1595
1596
  const RELATIVE_PATH_REGEX = /^\.?\.(\/|$)/;
1596
1597
  function isAbsolute(path) {
1597
1598
  return ABSOLUTE_PATH_REGEX.test(path);
@@ -1606,7 +1607,7 @@ function normalize(path) {
1606
1607
 
1607
1608
  function getAliasName(id) {
1608
1609
  const base = basename(id);
1609
- return base.substring(0, base.length - extname(id).length);
1610
+ return base.slice(0, Math.max(0, base.length - extname(id).length));
1610
1611
  }
1611
1612
  function relativeId(id) {
1612
1613
  if (!isAbsolute(id))
@@ -1627,10 +1628,7 @@ function getImportPath(importerId, targetPath, stripJsExtension, ensureFileName)
1627
1628
  if (relativePath === '')
1628
1629
  return '../' + basename(targetPath);
1629
1630
  if (UPPER_DIR_REGEX.test(relativePath)) {
1630
- return relativePath
1631
- .split('/')
1632
- .concat(['..', basename(targetPath)])
1633
- .join('/');
1631
+ return [...relativePath.split('/'), '..', basename(targetPath)].join('/');
1634
1632
  }
1635
1633
  }
1636
1634
  return !relativePath ? '.' : relativePath.startsWith('..') ? relativePath : './' + relativePath;
@@ -1675,7 +1673,7 @@ function formatAssertions$1(assertions, { getObject }) {
1675
1673
  return null;
1676
1674
  }
1677
1675
  const assertionEntries = Object.entries(assertions).map(([key, value]) => [key, `'${value}'`]);
1678
- if (assertionEntries.length) {
1676
+ if (assertionEntries.length > 0) {
1679
1677
  return getObject(assertionEntries, { lineBreakIndent: null });
1680
1678
  }
1681
1679
  return null;
@@ -1786,9 +1784,9 @@ class ExpressionEntity {
1786
1784
  include(_context, _includeChildrenRecursively, _options) {
1787
1785
  this.included = true;
1788
1786
  }
1789
- includeCallArguments(context, args) {
1790
- for (const arg of args) {
1791
- arg.include(context, false);
1787
+ includeCallArguments(context, parameters) {
1788
+ for (const argument of parameters) {
1789
+ argument.include(context, false);
1792
1790
  }
1793
1791
  }
1794
1792
  shouldBeIncluded(_context) {
@@ -1934,14 +1932,14 @@ function locate(source, search, options) {
1934
1932
  return getLocator(source, options)(search, options && options.startIndex);
1935
1933
  }
1936
1934
 
1937
- function spaces(i) {
1935
+ function spaces(index) {
1938
1936
  let result = '';
1939
- while (i--)
1937
+ while (index--)
1940
1938
  result += ' ';
1941
1939
  return result;
1942
1940
  }
1943
- function tabsToSpaces(str) {
1944
- return str.replace(/^\t+/, match => match.split('\t').join(' '));
1941
+ function tabsToSpaces(value) {
1942
+ return value.replace(/^\t+/, match => match.split('\t').join(' '));
1945
1943
  }
1946
1944
  function getCodeFrame(source, line, column) {
1947
1945
  let lines = source.split('\n');
@@ -1954,16 +1952,16 @@ function getCodeFrame(source, line, column) {
1954
1952
  }
1955
1953
  const digits = String(frameEnd).length;
1956
1954
  return lines
1957
- .map((str, i) => {
1958
- const isErrorLine = frameStart + i + 1 === line;
1959
- let lineNum = String(i + frameStart + 1);
1960
- while (lineNum.length < digits)
1961
- lineNum = ` ${lineNum}`;
1955
+ .map((sourceLine, index) => {
1956
+ const isErrorLine = frameStart + index + 1 === line;
1957
+ let lineNumber = String(index + frameStart + 1);
1958
+ while (lineNumber.length < digits)
1959
+ lineNumber = ` ${lineNumber}`;
1962
1960
  if (isErrorLine) {
1963
- const indicator = spaces(digits + 2 + tabsToSpaces(str.slice(0, column)).length) + '^';
1964
- return `${lineNum}: ${tabsToSpaces(str)}\n${indicator}`;
1961
+ const indicator = spaces(digits + 2 + tabsToSpaces(sourceLine.slice(0, column)).length) + '^';
1962
+ return `${lineNumber}: ${tabsToSpaces(sourceLine)}\n${indicator}`;
1965
1963
  }
1966
- return `${lineNum}: ${tabsToSpaces(str)}`;
1964
+ return `${lineNumber}: ${tabsToSpaces(sourceLine)}`;
1967
1965
  })
1968
1966
  .join('\n');
1969
1967
  }
@@ -1987,38 +1985,38 @@ function error(base) {
1987
1985
  }
1988
1986
  throw base;
1989
1987
  }
1990
- function augmentCodeLocation(props, pos, source, id) {
1988
+ function augmentCodeLocation(properties, pos, source, id) {
1991
1989
  if (typeof pos === 'object') {
1992
1990
  const { line, column } = pos;
1993
- props.loc = { column, file: id, line };
1991
+ properties.loc = { column, file: id, line };
1994
1992
  }
1995
1993
  else {
1996
- props.pos = pos;
1994
+ properties.pos = pos;
1997
1995
  const { line, column } = locate(source, pos, { offsetLine: 1 });
1998
- props.loc = { column, file: id, line };
1996
+ properties.loc = { column, file: id, line };
1999
1997
  }
2000
- if (props.frame === undefined) {
2001
- const { line, column } = props.loc;
2002
- props.frame = getCodeFrame(source, line, column);
1998
+ if (properties.frame === undefined) {
1999
+ const { line, column } = properties.loc;
2000
+ properties.frame = getCodeFrame(source, line, column);
2003
2001
  }
2004
2002
  }
2005
2003
  // Error codes should be sorted alphabetically while errors should be sorted by
2006
2004
  // error code below
2007
2005
  const ADDON_ERROR = 'ADDON_ERROR', ALREADY_CLOSED = 'ALREADY_CLOSED', AMBIGUOUS_EXTERNAL_NAMESPACES = 'AMBIGUOUS_EXTERNAL_NAMESPACES', ANONYMOUS_PLUGIN_CACHE = 'ANONYMOUS_PLUGIN_CACHE', ASSET_NOT_FINALISED = 'ASSET_NOT_FINALISED', ASSET_NOT_FOUND = 'ASSET_NOT_FOUND', ASSET_SOURCE_ALREADY_SET = 'ASSET_SOURCE_ALREADY_SET', ASSET_SOURCE_MISSING = 'ASSET_SOURCE_MISSING', BAD_LOADER = 'BAD_LOADER', CANNOT_CALL_NAMESPACE = 'CANNOT_CALL_NAMESPACE', CANNOT_EMIT_FROM_OPTIONS_HOOK = 'CANNOT_EMIT_FROM_OPTIONS_HOOK', CHUNK_NOT_GENERATED = 'CHUNK_NOT_GENERATED', CHUNK_INVALID = 'CHUNK_INVALID', CIRCULAR_DEPENDENCY = 'CIRCULAR_DEPENDENCY', CIRCULAR_REEXPORT = 'CIRCULAR_REEXPORT', CYCLIC_CROSS_CHUNK_REEXPORT = 'CYCLIC_CROSS_CHUNK_REEXPORT', DEPRECATED_FEATURE = 'DEPRECATED_FEATURE', DUPLICATE_PLUGIN_NAME = 'DUPLICATE_PLUGIN_NAME', EMPTY_BUNDLE = 'EMPTY_BUNDLE', EVAL = 'EVAL', EXTERNAL_SYNTHETIC_EXPORTS = 'EXTERNAL_SYNTHETIC_EXPORTS', FILE_NAME_CONFLICT = 'FILE_NAME_CONFLICT', FILE_NOT_FOUND = 'FILE_NOT_FOUND', ILLEGAL_IDENTIFIER_AS_NAME = 'ILLEGAL_IDENTIFIER_AS_NAME', ILLEGAL_REASSIGNMENT = 'ILLEGAL_REASSIGNMENT', INCONSISTENT_IMPORT_ASSERTIONS = 'INCONSISTENT_IMPORT_ASSERTIONS', INPUT_HOOK_IN_OUTPUT_PLUGIN = 'INPUT_HOOK_IN_OUTPUT_PLUGIN', INVALID_CHUNK = 'INVALID_CHUNK', INVALID_EXPORT_OPTION = 'INVALID_EXPORT_OPTION', INVALID_EXTERNAL_ID = 'INVALID_EXTERNAL_ID', INVALID_OPTION = 'INVALID_OPTION', INVALID_PLUGIN_HOOK = 'INVALID_PLUGIN_HOOK', INVALID_ROLLUP_PHASE = 'INVALID_ROLLUP_PHASE', INVALID_SETASSETSOURCE = 'INVALID_SETASSETSOURCE', INVALID_TLA_FORMAT = 'INVALID_TLA_FORMAT', MISSING_EXPORT = 'MISSING_EXPORT', MISSING_GLOBAL_NAME = 'MISSING_GLOBAL_NAME', MISSING_IMPLICIT_DEPENDANT = 'MISSING_IMPLICIT_DEPENDANT', MISSING_NAME_OPTION_FOR_IIFE_EXPORT = 'MISSING_NAME_OPTION_FOR_IIFE_EXPORT', MISSING_NODE_BUILTINS = 'MISSING_NODE_BUILTINS', MISSING_OPTION = 'MISSING_OPTION', MIXED_EXPORTS = 'MIXED_EXPORTS', MODULE_LEVEL_DIRECTIVE = 'MODULE_LEVEL_DIRECTIVE', NAMESPACE_CONFLICT = 'NAMESPACE_CONFLICT', NO_TRANSFORM_MAP_OR_AST_WITHOUT_CODE = 'NO_TRANSFORM_MAP_OR_AST_WITHOUT_CODE', PARSE_ERROR = 'PARSE_ERROR', PLUGIN_ERROR = 'PLUGIN_ERROR', SHIMMED_EXPORT = 'SHIMMED_EXPORT', SOURCEMAP_BROKEN = 'SOURCEMAP_BROKEN', SOURCEMAP_ERROR = 'SOURCEMAP_ERROR', SYNTHETIC_NAMED_EXPORTS_NEED_NAMESPACE_EXPORT = 'SYNTHETIC_NAMED_EXPORTS_NEED_NAMESPACE_EXPORT', THIS_IS_UNDEFINED = 'THIS_IS_UNDEFINED', UNEXPECTED_NAMED_IMPORT = 'UNEXPECTED_NAMED_IMPORT', UNKNOWN_OPTION = 'UNKNOWN_OPTION', UNRESOLVED_ENTRY = 'UNRESOLVED_ENTRY', UNRESOLVED_IMPORT = 'UNRESOLVED_IMPORT', UNUSED_EXTERNAL_IMPORT = 'UNUSED_EXTERNAL_IMPORT', VALIDATION_ERROR = 'VALIDATION_ERROR';
2008
- function errAddonNotGenerated(message, hook, plugin) {
2006
+ function errorAddonNotGenerated(message, hook, plugin) {
2009
2007
  return {
2010
2008
  code: ADDON_ERROR,
2011
2009
  message: `Could not retrieve "${hook}". Check configuration of plugin "${plugin}".
2012
2010
  \tError Message: ${message}`
2013
2011
  };
2014
2012
  }
2015
- function errAlreadyClosed() {
2013
+ function errorAlreadyClosed() {
2016
2014
  return {
2017
2015
  code: ALREADY_CLOSED,
2018
2016
  message: 'Bundle is already closed, no more calls to "generate" or "write" are allowed.'
2019
2017
  };
2020
2018
  }
2021
- function errAmbiguousExternalNamespaces(binding, reexportingModule, usedModule, sources) {
2019
+ function errorAmbiguousExternalNamespaces(binding, reexportingModule, usedModule, sources) {
2022
2020
  return {
2023
2021
  binding,
2024
2022
  code: AMBIGUOUS_EXTERNAL_NAMESPACES,
@@ -2027,83 +2025,83 @@ function errAmbiguousExternalNamespaces(binding, reexportingModule, usedModule,
2027
2025
  reexporter: reexportingModule
2028
2026
  };
2029
2027
  }
2030
- function errAnonymousPluginCache() {
2028
+ function errorAnonymousPluginCache() {
2031
2029
  return {
2032
2030
  code: ANONYMOUS_PLUGIN_CACHE,
2033
2031
  message: 'A plugin is trying to use the Rollup cache but is not declaring a plugin name or cacheKey.'
2034
2032
  };
2035
2033
  }
2036
- function errAssetNotFinalisedForFileName(name) {
2034
+ function errorAssetNotFinalisedForFileName(name) {
2037
2035
  return {
2038
2036
  code: ASSET_NOT_FINALISED,
2039
2037
  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.`
2040
2038
  };
2041
2039
  }
2042
- function errAssetReferenceIdNotFoundForSetSource(assetReferenceId) {
2040
+ function errorAssetReferenceIdNotFoundForSetSource(assetReferenceId) {
2043
2041
  return {
2044
2042
  code: ASSET_NOT_FOUND,
2045
2043
  message: `Plugin error - Unable to set the source for unknown asset "${assetReferenceId}".`
2046
2044
  };
2047
2045
  }
2048
- function errAssetSourceAlreadySet(name) {
2046
+ function errorAssetSourceAlreadySet(name) {
2049
2047
  return {
2050
2048
  code: ASSET_SOURCE_ALREADY_SET,
2051
2049
  message: `Unable to set the source for asset "${name}", source already set.`
2052
2050
  };
2053
2051
  }
2054
- function errNoAssetSourceSet(assetName) {
2052
+ function errorNoAssetSourceSet(assetName) {
2055
2053
  return {
2056
2054
  code: ASSET_SOURCE_MISSING,
2057
2055
  message: `Plugin error creating asset "${assetName}" - no asset source set.`
2058
2056
  };
2059
2057
  }
2060
- function errBadLoader(id) {
2058
+ function errorBadLoader(id) {
2061
2059
  return {
2062
2060
  code: BAD_LOADER,
2063
2061
  message: `Error loading "${relativeId(id)}": plugin load hook should return a string, a { code, map } object, or nothing/null.`
2064
2062
  };
2065
2063
  }
2066
- function errCannotCallNamespace(name) {
2064
+ function errorCannotCallNamespace(name) {
2067
2065
  return {
2068
2066
  code: CANNOT_CALL_NAMESPACE,
2069
2067
  message: `Cannot call a namespace ("${name}").`
2070
2068
  };
2071
2069
  }
2072
- function errCannotEmitFromOptionsHook() {
2070
+ function errorCannotEmitFromOptionsHook() {
2073
2071
  return {
2074
2072
  code: CANNOT_EMIT_FROM_OPTIONS_HOOK,
2075
2073
  message: `Cannot emit files or set asset sources in the "outputOptions" hook, use the "renderStart" hook instead.`
2076
2074
  };
2077
2075
  }
2078
- function errChunkNotGeneratedForFileName(name) {
2076
+ function errorChunkNotGeneratedForFileName(name) {
2079
2077
  return {
2080
2078
  code: CHUNK_NOT_GENERATED,
2081
2079
  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.`
2082
2080
  };
2083
2081
  }
2084
- function errChunkInvalid({ fileName, code }, exception) {
2085
- const errorProps = {
2082
+ function errorChunkInvalid({ fileName, code }, exception) {
2083
+ const errorProperties = {
2086
2084
  code: CHUNK_INVALID,
2087
2085
  message: `Chunk "${fileName}" is not valid JavaScript: ${exception.message}.`
2088
2086
  };
2089
- augmentCodeLocation(errorProps, exception.loc, code, fileName);
2090
- return errorProps;
2087
+ augmentCodeLocation(errorProperties, exception.loc, code, fileName);
2088
+ return errorProperties;
2091
2089
  }
2092
- function errCircularDependency(cyclePath) {
2090
+ function errorCircularDependency(cyclePath) {
2093
2091
  return {
2094
2092
  code: CIRCULAR_DEPENDENCY,
2095
2093
  ids: cyclePath,
2096
2094
  message: `Circular dependency: ${cyclePath.map(relativeId).join(' -> ')}`
2097
2095
  };
2098
2096
  }
2099
- function errCircularReexport(exportName, exporter) {
2097
+ function errorCircularReexport(exportName, exporter) {
2100
2098
  return {
2101
2099
  code: CIRCULAR_REEXPORT,
2102
2100
  exporter,
2103
2101
  message: `"${exportName}" cannot be exported from "${relativeId(exporter)}" as it is a reexport that references itself.`
2104
2102
  };
2105
2103
  }
2106
- function errCyclicCrossChunkReexport(exportName, exporter, reexporter, importer) {
2104
+ function errorCyclicCrossChunkReexport(exportName, exporter, reexporter, importer) {
2107
2105
  return {
2108
2106
  code: CYCLIC_CROSS_CHUNK_REEXPORT,
2109
2107
  exporter,
@@ -2112,26 +2110,26 @@ function errCyclicCrossChunkReexport(exportName, exporter, reexporter, importer)
2112
2110
  reexporter
2113
2111
  };
2114
2112
  }
2115
- function errDeprecation(deprecation) {
2113
+ function errorDeprecation(deprecation) {
2116
2114
  return {
2117
2115
  code: DEPRECATED_FEATURE,
2118
2116
  ...(typeof deprecation === 'string' ? { message: deprecation } : deprecation)
2119
2117
  };
2120
2118
  }
2121
- function errDuplicatePluginName(plugin) {
2119
+ function errorDuplicatePluginName(plugin) {
2122
2120
  return {
2123
2121
  code: DUPLICATE_PLUGIN_NAME,
2124
2122
  message: `The plugin name ${plugin} is being used twice in the same build. Plugin names must be distinct or provide a cacheKey (please post an issue to the plugin if you are a plugin user).`
2125
2123
  };
2126
2124
  }
2127
- function errEmptyChunk(chunkName) {
2125
+ function errorEmptyChunk(chunkName) {
2128
2126
  return {
2129
2127
  code: EMPTY_BUNDLE,
2130
2128
  message: `Generated an empty chunk: "${chunkName}".`,
2131
2129
  names: [chunkName]
2132
2130
  };
2133
2131
  }
2134
- function errEval(id) {
2132
+ function errorEval(id) {
2135
2133
  return {
2136
2134
  code: EVAL,
2137
2135
  id,
@@ -2139,39 +2137,39 @@ function errEval(id) {
2139
2137
  url: 'https://rollupjs.org/guide/en/#avoiding-eval'
2140
2138
  };
2141
2139
  }
2142
- function errExternalSyntheticExports(id, importer) {
2140
+ function errorExternalSyntheticExports(id, importer) {
2143
2141
  return {
2144
2142
  code: EXTERNAL_SYNTHETIC_EXPORTS,
2145
2143
  exporter: id,
2146
2144
  message: `External "${id}" cannot have "syntheticNamedExports" enabled (imported by "${relativeId(importer)}").`
2147
2145
  };
2148
2146
  }
2149
- function errFileNameConflict(fileName) {
2147
+ function errorFileNameConflict(fileName) {
2150
2148
  return {
2151
2149
  code: FILE_NAME_CONFLICT,
2152
2150
  message: `The emitted file "${fileName}" overwrites a previously emitted file of the same name.`
2153
2151
  };
2154
2152
  }
2155
- function errFileReferenceIdNotFoundForFilename(assetReferenceId) {
2153
+ function errorFileReferenceIdNotFoundForFilename(assetReferenceId) {
2156
2154
  return {
2157
2155
  code: FILE_NOT_FOUND,
2158
2156
  message: `Plugin error - Unable to get file name for unknown file "${assetReferenceId}".`
2159
2157
  };
2160
2158
  }
2161
- function errIllegalIdentifierAsName(name) {
2159
+ function errorIllegalIdentifierAsName(name) {
2162
2160
  return {
2163
2161
  code: ILLEGAL_IDENTIFIER_AS_NAME,
2164
2162
  message: `Given name "${name}" is not a legal JS identifier. If you need this, you can try "output.extend: true".`,
2165
2163
  url: 'https://rollupjs.org/guide/en/#outputextend'
2166
2164
  };
2167
2165
  }
2168
- function errIllegalImportReassignment(name, importingId) {
2166
+ function errorIllegalImportReassignment(name, importingId) {
2169
2167
  return {
2170
2168
  code: ILLEGAL_REASSIGNMENT,
2171
2169
  message: `Illegal reassignment of import "${name}" in "${relativeId(importingId)}".`
2172
2170
  };
2173
2171
  }
2174
- function errInconsistentImportAssertions(existingAssertions, newAssertions, source, importer) {
2172
+ function errorInconsistentImportAssertions(existingAssertions, newAssertions, source, importer) {
2175
2173
  return {
2176
2174
  code: INCONSISTENT_IMPORT_ASSERTIONS,
2177
2175
  message: `Module "${relativeId(importer)}" tried to import "${relativeId(source)}" with ${formatAssertions(newAssertions)} assertions, but it was already imported elsewhere with ${formatAssertions(existingAssertions)} assertions. Please ensure that import assertions for the same module are always consistent.`
@@ -2183,46 +2181,46 @@ const formatAssertions = (assertions) => {
2183
2181
  return 'no';
2184
2182
  return entries.map(([key, value]) => `"${key}": "${value}"`).join(', ');
2185
2183
  };
2186
- function errInputHookInOutputPlugin(pluginName, hookName) {
2184
+ function errorInputHookInOutputPlugin(pluginName, hookName) {
2187
2185
  return {
2188
2186
  code: INPUT_HOOK_IN_OUTPUT_PLUGIN,
2189
2187
  message: `The "${hookName}" hook used by the output plugin ${pluginName} is a build time hook and will not be run for that plugin. Either this plugin cannot be used as an output plugin, or it should have an option to configure it as an output plugin.`
2190
2188
  };
2191
2189
  }
2192
- function errCannotAssignModuleToChunk(moduleId, assignToAlias, currentAlias) {
2190
+ function errorCannotAssignModuleToChunk(moduleId, assignToAlias, currentAlias) {
2193
2191
  return {
2194
2192
  code: INVALID_CHUNK,
2195
2193
  message: `Cannot assign "${relativeId(moduleId)}" to the "${assignToAlias}" chunk as it is already in the "${currentAlias}" chunk.`
2196
2194
  };
2197
2195
  }
2198
- function errInvalidExportOptionValue(optionValue) {
2196
+ function errorInvalidExportOptionValue(optionValue) {
2199
2197
  return {
2200
2198
  code: INVALID_EXPORT_OPTION,
2201
2199
  message: `"output.exports" must be "default", "named", "none", "auto", or left unspecified (defaults to "auto"), received "${optionValue}".`,
2202
2200
  url: `https://rollupjs.org/guide/en/#outputexports`
2203
2201
  };
2204
2202
  }
2205
- function errIncompatibleExportOptionValue(optionValue, keys, entryModule) {
2203
+ function errorIncompatibleExportOptionValue(optionValue, keys, entryModule) {
2206
2204
  return {
2207
2205
  code: INVALID_EXPORT_OPTION,
2208
2206
  message: `"${optionValue}" was specified for "output.exports", but entry module "${relativeId(entryModule)}" has the following exports: ${printQuotedStringList(keys)}`,
2209
2207
  url: 'https://rollupjs.org/guide/en/#outputexports'
2210
2208
  };
2211
2209
  }
2212
- function errInternalIdCannotBeExternal(source, importer) {
2210
+ function errorInternalIdCannotBeExternal(source, importer) {
2213
2211
  return {
2214
2212
  code: INVALID_EXTERNAL_ID,
2215
2213
  message: `"${source}" is imported as an external by "${relativeId(importer)}", but is already an existing non-external module id.`
2216
2214
  };
2217
2215
  }
2218
- function errInvalidOption(option, urlHash, explanation, value) {
2216
+ function errorInvalidOption(option, urlHash, explanation, value) {
2219
2217
  return {
2220
2218
  code: INVALID_OPTION,
2221
2219
  message: `Invalid value ${value !== undefined ? `${JSON.stringify(value)} ` : ''}for option "${option}" - ${explanation}.`,
2222
2220
  url: `https://rollupjs.org/guide/en/#${urlHash}`
2223
2221
  };
2224
2222
  }
2225
- function errInvalidAddonPluginHook(hook, plugin) {
2223
+ function errorInvalidAddonPluginHook(hook, plugin) {
2226
2224
  return {
2227
2225
  code: INVALID_PLUGIN_HOOK,
2228
2226
  hook,
@@ -2230,7 +2228,7 @@ function errInvalidAddonPluginHook(hook, plugin) {
2230
2228
  plugin
2231
2229
  };
2232
2230
  }
2233
- function errInvalidFunctionPluginHook(hook, plugin) {
2231
+ function errorInvalidFunctionPluginHook(hook, plugin) {
2234
2232
  return {
2235
2233
  code: INVALID_PLUGIN_HOOK,
2236
2234
  hook,
@@ -2238,32 +2236,32 @@ function errInvalidFunctionPluginHook(hook, plugin) {
2238
2236
  plugin
2239
2237
  };
2240
2238
  }
2241
- function errInvalidRollupPhaseForAddWatchFile() {
2239
+ function errorInvalidRollupPhaseForAddWatchFile() {
2242
2240
  return {
2243
2241
  code: INVALID_ROLLUP_PHASE,
2244
2242
  message: `Cannot call "addWatchFile" after the build has finished.`
2245
2243
  };
2246
2244
  }
2247
- function errInvalidRollupPhaseForChunkEmission() {
2245
+ function errorInvalidRollupPhaseForChunkEmission() {
2248
2246
  return {
2249
2247
  code: INVALID_ROLLUP_PHASE,
2250
2248
  message: `Cannot emit chunks after module loading has finished.`
2251
2249
  };
2252
2250
  }
2253
- function errInvalidSetAssetSourceCall() {
2251
+ function errorInvalidSetAssetSourceCall() {
2254
2252
  return {
2255
2253
  code: INVALID_SETASSETSOURCE,
2256
2254
  message: `setAssetSource cannot be called in transform for caching reasons. Use emitFile with a source, or call setAssetSource in another hook.`
2257
2255
  };
2258
2256
  }
2259
- function errInvalidFormatForTopLevelAwait(id, format) {
2257
+ function errorInvalidFormatForTopLevelAwait(id, format) {
2260
2258
  return {
2261
2259
  code: INVALID_TLA_FORMAT,
2262
2260
  id,
2263
2261
  message: `Module format "${format}" does not support top-level await. Use the "es" or "system" output formats rather.`
2264
2262
  };
2265
2263
  }
2266
- function errMissingExport(binding, importingModule, exporter) {
2264
+ function errorMissingExport(binding, importingModule, exporter) {
2267
2265
  return {
2268
2266
  binding,
2269
2267
  code: MISSING_EXPORT,
@@ -2273,7 +2271,7 @@ function errMissingExport(binding, importingModule, exporter) {
2273
2271
  url: `https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module`
2274
2272
  };
2275
2273
  }
2276
- function errMissingGlobalName(externalId, guess) {
2274
+ function errorMissingGlobalName(externalId, guess) {
2277
2275
  return {
2278
2276
  code: MISSING_GLOBAL_NAME,
2279
2277
  id: externalId,
@@ -2282,54 +2280,57 @@ function errMissingGlobalName(externalId, guess) {
2282
2280
  url: 'https://rollupjs.org/guide/en/#outputglobals'
2283
2281
  };
2284
2282
  }
2285
- function errImplicitDependantCannotBeExternal(unresolvedId, implicitlyLoadedBefore) {
2283
+ function errorImplicitDependantCannotBeExternal(unresolvedId, implicitlyLoadedBefore) {
2286
2284
  return {
2287
2285
  code: MISSING_IMPLICIT_DEPENDANT,
2288
2286
  message: `Module "${relativeId(unresolvedId)}" that should be implicitly loaded before "${relativeId(implicitlyLoadedBefore)}" cannot be external.`
2289
2287
  };
2290
2288
  }
2291
- function errUnresolvedImplicitDependant(unresolvedId, implicitlyLoadedBefore) {
2289
+ function errorUnresolvedImplicitDependant(unresolvedId, implicitlyLoadedBefore) {
2292
2290
  return {
2293
2291
  code: MISSING_IMPLICIT_DEPENDANT,
2294
2292
  message: `Module "${relativeId(unresolvedId)}" that should be implicitly loaded before "${relativeId(implicitlyLoadedBefore)}" could not be resolved.`
2295
2293
  };
2296
2294
  }
2297
- function errImplicitDependantIsNotIncluded(module) {
2298
- const implicitDependencies = Array.from(module.implicitlyLoadedBefore, dependency => relativeId(dependency.id)).sort();
2295
+ function errorImplicitDependantIsNotIncluded(module) {
2296
+ const implicitDependencies = [...module.implicitlyLoadedBefore]
2297
+ .map(dependency => relativeId(dependency.id))
2298
+ .sort();
2299
2299
  return {
2300
2300
  code: MISSING_IMPLICIT_DEPENDANT,
2301
2301
  message: `Module "${relativeId(module.id)}" that should be implicitly loaded before ${printQuotedStringList(implicitDependencies)} is not included in the module graph. Either it was not imported by an included module or only via a tree-shaken dynamic import, or no imported bindings were used and it had otherwise no side-effects.`
2302
2302
  };
2303
2303
  }
2304
- function errMissingNameOptionForIifeExport() {
2304
+ function errorMissingNameOptionForIifeExport() {
2305
2305
  return {
2306
2306
  code: MISSING_NAME_OPTION_FOR_IIFE_EXPORT,
2307
2307
  message: `If you do not supply "output.name", you may not be able to access the exports of an IIFE bundle.`,
2308
2308
  url: 'https://rollupjs.org/guide/en/#outputname'
2309
2309
  };
2310
2310
  }
2311
- function errMissingNameOptionForUmdExport() {
2311
+ function errorMissingNameOptionForUmdExport() {
2312
2312
  return {
2313
2313
  code: MISSING_NAME_OPTION_FOR_IIFE_EXPORT,
2314
2314
  message: 'You must supply "output.name" for UMD bundles that have exports so that the exports are accessible in environments without a module loader.',
2315
2315
  url: 'https://rollupjs.org/guide/en/#outputname'
2316
2316
  };
2317
2317
  }
2318
- function errMissingNodeBuiltins(externalBuiltins) {
2318
+ function errorMissingNodeBuiltins(externalBuiltins) {
2319
2319
  return {
2320
2320
  code: MISSING_NODE_BUILTINS,
2321
2321
  ids: externalBuiltins,
2322
2322
  message: `Creating a browser bundle that depends on Node.js built-in modules (${printQuotedStringList(externalBuiltins)}). You might need to include https://github.com/FredKSchott/rollup-plugin-polyfill-node`
2323
2323
  };
2324
2324
  }
2325
- function errMissingFileOrDirOption() {
2325
+ // eslint-disable-next-line unicorn/prevent-abbreviations
2326
+ function errorMissingFileOrDirOption() {
2326
2327
  return {
2327
2328
  code: MISSING_OPTION,
2328
2329
  message: 'You must specify "output.file" or "output.dir" for the build.',
2329
2330
  url: 'https://rollupjs.org/guide/en/#outputdir'
2330
2331
  };
2331
2332
  }
2332
- function errMixedExport(facadeModuleId, name) {
2333
+ function errorMixedExport(facadeModuleId, name) {
2333
2334
  return {
2334
2335
  code: MIXED_EXPORTS,
2335
2336
  id: facadeModuleId,
@@ -2337,14 +2338,14 @@ function errMixedExport(facadeModuleId, name) {
2337
2338
  url: `https://rollupjs.org/guide/en/#outputexports`
2338
2339
  };
2339
2340
  }
2340
- function errModuleLevelDirective(directive, id) {
2341
+ function errorModuleLevelDirective(directive, id) {
2341
2342
  return {
2342
2343
  code: MODULE_LEVEL_DIRECTIVE,
2343
2344
  id,
2344
2345
  message: `Module level directives cause errors when bundled, "${directive}" in "${relativeId(id)}" was ignored.`
2345
2346
  };
2346
2347
  }
2347
- function errNamespaceConflict(binding, reexportingModuleId, sources) {
2348
+ function errorNamespaceConflict(binding, reexportingModuleId, sources) {
2348
2349
  return {
2349
2350
  binding,
2350
2351
  code: NAMESPACE_CONFLICT,
@@ -2353,14 +2354,14 @@ function errNamespaceConflict(binding, reexportingModuleId, sources) {
2353
2354
  reexporter: reexportingModuleId
2354
2355
  };
2355
2356
  }
2356
- function errNoTransformMapOrAstWithoutCode(pluginName) {
2357
+ function errorNoTransformMapOrAstWithoutCode(pluginName) {
2357
2358
  return {
2358
2359
  code: NO_TRANSFORM_MAP_OR_AST_WITHOUT_CODE,
2359
2360
  message: `The plugin "${pluginName}" returned a "map" or "ast" without returning ` +
2360
2361
  'a "code". This will be ignored.'
2361
2362
  };
2362
2363
  }
2363
- function errParseError(error, moduleId) {
2364
+ function errorParseError(error, moduleId) {
2364
2365
  let message = error.message.replace(/ \(\d+:\d+\)$/, '');
2365
2366
  if (moduleId.endsWith('.json')) {
2366
2367
  message += ' (Note that you need @rollup/plugin-json to import JSON files)';
@@ -2375,7 +2376,7 @@ function errParseError(error, moduleId) {
2375
2376
  message
2376
2377
  };
2377
2378
  }
2378
- function errPluginError(error, plugin, { hook, id } = {}) {
2379
+ function errorPluginError(error, plugin, { hook, id } = {}) {
2379
2380
  if (typeof error === 'string')
2380
2381
  error = { message: error };
2381
2382
  if (error.code && error.code !== PLUGIN_ERROR) {
@@ -2391,7 +2392,7 @@ function errPluginError(error, plugin, { hook, id } = {}) {
2391
2392
  }
2392
2393
  return error;
2393
2394
  }
2394
- function errShimmedExport(id, binding) {
2395
+ function errorShimmedExport(id, binding) {
2395
2396
  return {
2396
2397
  binding,
2397
2398
  code: SHIMMED_EXPORT,
@@ -2399,7 +2400,7 @@ function errShimmedExport(id, binding) {
2399
2400
  message: `Missing export "${binding}" has been shimmed in module "${relativeId(id)}".`
2400
2401
  };
2401
2402
  }
2402
- function errSourcemapBroken(plugin) {
2403
+ function errorSourcemapBroken(plugin) {
2403
2404
  return {
2404
2405
  code: SOURCEMAP_BROKEN,
2405
2406
  message: `Sourcemap is likely to be incorrect: a plugin (${plugin}) was used to transform files, but didn't generate a sourcemap for the transformation. Consult the plugin documentation for help`,
@@ -2407,7 +2408,7 @@ function errSourcemapBroken(plugin) {
2407
2408
  url: `https://rollupjs.org/guide/en/#warning-sourcemap-is-likely-to-be-incorrect`
2408
2409
  };
2409
2410
  }
2410
- function errInvalidSourcemapForError(error, id, column, line, pos) {
2411
+ function errorInvalidSourcemapForError(error, id, column, line, pos) {
2411
2412
  return {
2412
2413
  cause: error,
2413
2414
  code: SOURCEMAP_ERROR,
@@ -2421,7 +2422,7 @@ function errInvalidSourcemapForError(error, id, column, line, pos) {
2421
2422
  pos
2422
2423
  };
2423
2424
  }
2424
- function errSyntheticNamedExportsNeedNamespaceExport(id, syntheticNamedExportsOption) {
2425
+ function errorSyntheticNamedExportsNeedNamespaceExport(id, syntheticNamedExportsOption) {
2425
2426
  return {
2426
2427
  code: SYNTHETIC_NAMED_EXPORTS_NEED_NAMESPACE_EXPORT,
2427
2428
  exporter: id,
@@ -2430,14 +2431,14 @@ function errSyntheticNamedExportsNeedNamespaceExport(id, syntheticNamedExportsOp
2430
2431
  : 'a default export'} that does not reexport an unresolved named export of the same module.`
2431
2432
  };
2432
2433
  }
2433
- function errThisIsUndefined() {
2434
+ function errorThisIsUndefined() {
2434
2435
  return {
2435
2436
  code: THIS_IS_UNDEFINED,
2436
2437
  message: `The 'this' keyword is equivalent to 'undefined' at the top level of an ES module, and has been rewritten`,
2437
2438
  url: `https://rollupjs.org/guide/en/#error-this-is-undefined`
2438
2439
  };
2439
2440
  }
2440
- function errUnexpectedNamedImport(id, imported, isReexport) {
2441
+ function errorUnexpectedNamedImport(id, imported, isReexport) {
2441
2442
  const importType = isReexport ? 'reexport' : 'import';
2442
2443
  return {
2443
2444
  code: UNEXPECTED_NAMED_IMPORT,
@@ -2446,7 +2447,7 @@ function errUnexpectedNamedImport(id, imported, isReexport) {
2446
2447
  url: 'https://rollupjs.org/guide/en/#outputinterop'
2447
2448
  };
2448
2449
  }
2449
- function errUnexpectedNamespaceReexport(id) {
2450
+ function errorUnexpectedNamespaceReexport(id) {
2450
2451
  return {
2451
2452
  code: UNEXPECTED_NAMED_IMPORT,
2452
2453
  exporter: id,
@@ -2454,25 +2455,25 @@ function errUnexpectedNamespaceReexport(id) {
2454
2455
  url: 'https://rollupjs.org/guide/en/#outputinterop'
2455
2456
  };
2456
2457
  }
2457
- function errUnknownOption(optionType, unknownOptions, validOptions) {
2458
+ function errorUnknownOption(optionType, unknownOptions, validOptions) {
2458
2459
  return {
2459
2460
  code: UNKNOWN_OPTION,
2460
2461
  message: `Unknown ${optionType}: ${unknownOptions.join(', ')}. Allowed options: ${validOptions.join(', ')}`
2461
2462
  };
2462
2463
  }
2463
- function errEntryCannotBeExternal(unresolvedId) {
2464
+ function errorEntryCannotBeExternal(unresolvedId) {
2464
2465
  return {
2465
2466
  code: UNRESOLVED_ENTRY,
2466
2467
  message: `Entry module "${relativeId(unresolvedId)}" cannot be external.`
2467
2468
  };
2468
2469
  }
2469
- function errUnresolvedEntry(unresolvedId) {
2470
+ function errorUnresolvedEntry(unresolvedId) {
2470
2471
  return {
2471
2472
  code: UNRESOLVED_ENTRY,
2472
2473
  message: `Could not resolve entry module "${relativeId(unresolvedId)}".`
2473
2474
  };
2474
2475
  }
2475
- function errUnresolvedImport(source, importer) {
2476
+ function errorUnresolvedImport(source, importer) {
2476
2477
  return {
2477
2478
  code: UNRESOLVED_IMPORT,
2478
2479
  exporter: source,
@@ -2480,7 +2481,7 @@ function errUnresolvedImport(source, importer) {
2480
2481
  message: `Could not resolve "${source}" from "${relativeId(importer)}"`
2481
2482
  };
2482
2483
  }
2483
- function errUnresolvedImportTreatedAsExternal(source, importer) {
2484
+ function errorUnresolvedImportTreatedAsExternal(source, importer) {
2484
2485
  return {
2485
2486
  code: UNRESOLVED_IMPORT,
2486
2487
  exporter: source,
@@ -2489,7 +2490,7 @@ function errUnresolvedImportTreatedAsExternal(source, importer) {
2489
2490
  url: 'https://rollupjs.org/guide/en/#warning-treating-module-as-external-dependency'
2490
2491
  };
2491
2492
  }
2492
- function errUnusedExternalImports(externalId, names, importers) {
2493
+ function errorUnusedExternalImports(externalId, names, importers) {
2493
2494
  return {
2494
2495
  code: UNUSED_EXTERNAL_IMPORT,
2495
2496
  exporter: externalId,
@@ -2501,7 +2502,7 @@ function errUnusedExternalImports(externalId, names, importers) {
2501
2502
  names
2502
2503
  };
2503
2504
  }
2504
- function errFailedValidation(message) {
2505
+ function errorFailedValidation(message) {
2505
2506
  return {
2506
2507
  code: VALIDATION_ERROR,
2507
2508
  message
@@ -2512,7 +2513,7 @@ function warnDeprecation(deprecation, activeDeprecation, options) {
2512
2513
  }
2513
2514
  function warnDeprecationWithOptions(deprecation, activeDeprecation, warn, strictDeprecations) {
2514
2515
  if (activeDeprecation || strictDeprecations) {
2515
- const warning = errDeprecation(deprecation);
2516
+ const warning = errorDeprecation(deprecation);
2516
2517
  if (strictDeprecations) {
2517
2518
  return error(warning);
2518
2519
  }
@@ -2573,20 +2574,22 @@ const RESERVED_NAMES = new Set([
2573
2574
  ]);
2574
2575
  const RESERVED_NAMES$1 = RESERVED_NAMES;
2575
2576
 
2576
- const illegalCharacters = /[^$_a-zA-Z0-9]/g;
2577
- const startsWithDigit = (str) => /\d/.test(str[0]);
2578
- const needsEscape = (str) => startsWithDigit(str) || RESERVED_NAMES$1.has(str) || str === 'arguments';
2579
- function isLegal(str) {
2580
- if (needsEscape(str)) {
2577
+ const illegalCharacters = /[^\w$]/g;
2578
+ const startsWithDigit = (value) => /\d/.test(value[0]);
2579
+ const needsEscape = (value) => startsWithDigit(value) || RESERVED_NAMES$1.has(value) || value === 'arguments';
2580
+ function isLegal(value) {
2581
+ if (needsEscape(value)) {
2581
2582
  return false;
2582
2583
  }
2583
- return !illegalCharacters.test(str);
2584
+ return !illegalCharacters.test(value);
2584
2585
  }
2585
- function makeLegal(str) {
2586
- str = str.replace(/-(\w)/g, (_, letter) => letter.toUpperCase()).replace(illegalCharacters, '_');
2587
- if (needsEscape(str))
2588
- str = `_${str}`;
2589
- return str || '_';
2586
+ function makeLegal(value) {
2587
+ value = value
2588
+ .replace(/-(\w)/g, (_, letter) => letter.toUpperCase())
2589
+ .replace(illegalCharacters, '_');
2590
+ if (needsEscape(value))
2591
+ value = `_${value}`;
2592
+ return value || '_';
2590
2593
  }
2591
2594
 
2592
2595
  class ExternalModule {
@@ -2603,7 +2606,7 @@ class ExternalModule {
2603
2606
  this.declarations = new Map();
2604
2607
  this.mostCommonSuggestion = 0;
2605
2608
  this.nameSuggestions = new Map();
2606
- this.suggestedVariableName = makeLegal(id.split(/[\\/]/).pop());
2609
+ this.suggestedVariableName = makeLegal(id.split(/[/\\]/).pop());
2607
2610
  const { importers, dynamicImporters } = this;
2608
2611
  const info = (this.info = {
2609
2612
  assertions,
@@ -2657,7 +2660,7 @@ class ExternalModule {
2657
2660
  }
2658
2661
  }
2659
2662
  warnUnusedImports() {
2660
- const unused = Array.from(this.declarations)
2663
+ const unused = [...this.declarations]
2661
2664
  .filter(([name, declaration]) => name !== '*' && !declaration.included && !this.reexported && !declaration.referenced)
2662
2665
  .map(([name]) => name);
2663
2666
  if (unused.length === 0)
@@ -2669,7 +2672,7 @@ class ExternalModule {
2669
2672
  }
2670
2673
  }
2671
2674
  const importersArray = [...importersSet];
2672
- this.options.onwarn(errUnusedExternalImports(this.id, unused, importersArray));
2675
+ this.options.onwarn(errorUnusedExternalImports(this.id, unused, importersArray));
2673
2676
  }
2674
2677
  }
2675
2678
 
@@ -4986,12 +4989,12 @@ const returnsString = {
4986
4989
  const stringReplace = {
4987
4990
  value: {
4988
4991
  hasEffectsWhenCalled({ args }, context) {
4989
- const arg1 = args[1];
4992
+ const argument1 = args[1];
4990
4993
  return (args.length < 2 ||
4991
- (typeof arg1.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, {
4994
+ (typeof argument1.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, {
4992
4995
  deoptimizeCache() { }
4993
4996
  }) === 'symbol' &&
4994
- arg1.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, context)));
4997
+ argument1.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, context)));
4995
4998
  },
4996
4999
  returns: UNKNOWN_LITERAL_STRING
4997
5000
  }
@@ -5066,12 +5069,15 @@ const literalStringMembers = assembleMemberDescriptions({
5066
5069
  }, objectMembers);
5067
5070
  function getLiteralMembersForValue(value) {
5068
5071
  switch (typeof value) {
5069
- case 'boolean':
5072
+ case 'boolean': {
5070
5073
  return literalBooleanMembers;
5071
- case 'number':
5074
+ }
5075
+ case 'number': {
5072
5076
  return literalNumberMembers;
5073
- case 'string':
5077
+ }
5078
+ case 'string': {
5074
5079
  return literalStringMembers;
5080
+ }
5075
5081
  }
5076
5082
  return Object.create(null);
5077
5083
  }
@@ -5379,14 +5385,16 @@ const SOURCEMAPPING_URL_RE = new RegExp(`^#${whiteSpaceNoNewline}+${SOURCEMAPPIN
5379
5385
  const ANNOTATION_KEY = '_rollupAnnotations';
5380
5386
  const INVALID_COMMENT_KEY = '_rollupRemoved';
5381
5387
  function handlePureAnnotationsOfNode(node, state, type = node.type) {
5382
- const { annotations } = state;
5388
+ const { annotations, code } = state;
5389
+ // eslint-disable-next-line unicorn/consistent-destructuring
5383
5390
  let comment = annotations[state.annotationIndex];
5384
5391
  while (comment && node.start >= comment.end) {
5385
- markPureNode(node, comment, state.code);
5392
+ markPureNode(node, comment, code);
5386
5393
  comment = annotations[++state.annotationIndex];
5387
5394
  }
5388
5395
  if (comment && comment.end <= node.end) {
5389
5396
  base$1[type](node, state, handlePureAnnotationsOfNode);
5397
+ // eslint-disable-next-line unicorn/consistent-destructuring
5390
5398
  while ((comment = annotations[state.annotationIndex]) && comment.end <= node.end) {
5391
5399
  ++state.annotationIndex;
5392
5400
  annotateNode(node, comment, false);
@@ -5405,10 +5413,11 @@ function markPureNode(node, comment, code) {
5405
5413
  annotatedNodes.push(node);
5406
5414
  switch (node.type) {
5407
5415
  case ExpressionStatement$1:
5408
- case ChainExpression$1:
5416
+ case ChainExpression$1: {
5409
5417
  node = node.expression;
5410
5418
  continue;
5411
- case SequenceExpression$1:
5419
+ }
5420
+ case SequenceExpression$1: {
5412
5421
  // if there are parentheses, the annotation would apply to the entire expression
5413
5422
  if (doesNotMatchOutsideComment(code.slice(parentStart, node.start), noWhitespace)) {
5414
5423
  node = node.expressions[0];
@@ -5416,7 +5425,8 @@ function markPureNode(node, comment, code) {
5416
5425
  }
5417
5426
  invalidAnnotation = true;
5418
5427
  break;
5419
- case ConditionalExpression$1:
5428
+ }
5429
+ case ConditionalExpression$1: {
5420
5430
  // if there are parentheses, the annotation would apply to the entire expression
5421
5431
  if (doesNotMatchOutsideComment(code.slice(parentStart, node.start), noWhitespace)) {
5422
5432
  node = node.test;
@@ -5424,8 +5434,9 @@ function markPureNode(node, comment, code) {
5424
5434
  }
5425
5435
  invalidAnnotation = true;
5426
5436
  break;
5437
+ }
5427
5438
  case LogicalExpression$1:
5428
- case BinaryExpression$1:
5439
+ case BinaryExpression$1: {
5429
5440
  // if there are parentheses, the annotation would apply to the entire expression
5430
5441
  if (doesNotMatchOutsideComment(code.slice(parentStart, node.start), noWhitespace)) {
5431
5442
  node = node.left;
@@ -5433,11 +5444,14 @@ function markPureNode(node, comment, code) {
5433
5444
  }
5434
5445
  invalidAnnotation = true;
5435
5446
  break;
5447
+ }
5436
5448
  case CallExpression$1:
5437
- case NewExpression$1:
5449
+ case NewExpression$1: {
5438
5450
  break;
5439
- default:
5451
+ }
5452
+ default: {
5440
5453
  invalidAnnotation = true;
5454
+ }
5441
5455
  }
5442
5456
  break;
5443
5457
  }
@@ -5473,7 +5487,7 @@ function doesNotMatchOutsideComment(code, forbiddenChars) {
5473
5487
  }
5474
5488
  return true;
5475
5489
  }
5476
- const pureCommentRegex = /[@#]__PURE__/;
5490
+ const pureCommentRegex = /[#@]__PURE__/;
5477
5491
  function addAnnotations(comments, esTreeAst, code) {
5478
5492
  const annotations = [];
5479
5493
  const sourceMappingComments = [];
@@ -5739,13 +5753,14 @@ class Method extends ExpressionEntity {
5739
5753
  return true;
5740
5754
  }
5741
5755
  if (type === INTERACTION_CALLED) {
5756
+ const { args, thisArg } = interaction;
5742
5757
  if (this.description.mutatesSelfAsArray === true &&
5743
- interaction.thisArg?.hasEffectsOnInteractionAtPath(UNKNOWN_INTEGER_PATH, NODE_INTERACTION_UNKNOWN_ASSIGNMENT, context)) {
5758
+ thisArg?.hasEffectsOnInteractionAtPath(UNKNOWN_INTEGER_PATH, NODE_INTERACTION_UNKNOWN_ASSIGNMENT, context)) {
5744
5759
  return true;
5745
5760
  }
5746
5761
  if (this.description.callsArgs) {
5747
- for (const argIndex of this.description.callsArgs) {
5748
- if (interaction.args[argIndex]?.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, context)) {
5762
+ for (const argumentIndex of this.description.callsArgs) {
5763
+ if (args[argumentIndex]?.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, context)) {
5749
5764
  return true;
5750
5765
  }
5751
5766
  }
@@ -5831,7 +5846,10 @@ class ObjectEntity extends ExpressionEntity {
5831
5846
  if (isDeoptimized) {
5832
5847
  return;
5833
5848
  }
5834
- for (const properties of Object.values(this.propertiesAndGettersByKey).concat(Object.values(this.settersByKey))) {
5849
+ for (const properties of [
5850
+ ...Object.values(this.propertiesAndGettersByKey),
5851
+ ...Object.values(this.settersByKey)
5852
+ ]) {
5835
5853
  for (const property of properties) {
5836
5854
  property.deoptimizePath(UNKNOWN_PATH);
5837
5855
  }
@@ -5883,7 +5901,10 @@ class ObjectEntity extends ExpressionEntity {
5883
5901
  }
5884
5902
  const subPath = path.length === 1 ? UNKNOWN_PATH : path.slice(1);
5885
5903
  for (const property of typeof key === 'string'
5886
- ? (this.propertiesAndGettersByKey[key] || this.unmatchablePropertiesAndGetters).concat(this.settersByKey[key] || this.unmatchableSetters)
5904
+ ? [
5905
+ ...(this.propertiesAndGettersByKey[key] || this.unmatchablePropertiesAndGetters),
5906
+ ...(this.settersByKey[key] || this.unmatchableSetters)
5907
+ ]
5887
5908
  : this.allProperties) {
5888
5909
  property.deoptimizePath(subPath);
5889
5910
  }
@@ -5931,9 +5952,10 @@ class ObjectEntity extends ExpressionEntity {
5931
5952
  }
5932
5953
  }
5933
5954
  else {
5934
- for (const properties of Object.values(relevantPropertiesByKey).concat([
5955
+ for (const properties of [
5956
+ ...Object.values(relevantPropertiesByKey),
5935
5957
  relevantUnmatchableProperties
5936
- ])) {
5958
+ ]) {
5937
5959
  for (const property of properties) {
5938
5960
  property.deoptimizeThisOnInteractionAtPath(interaction, subPath, recursionTracker);
5939
5961
  }
@@ -5980,7 +6002,7 @@ class ObjectEntity extends ExpressionEntity {
5980
6002
  }
5981
6003
  hasEffectsOnInteractionAtPath(path, interaction, context) {
5982
6004
  const [key, ...subPath] = path;
5983
- if (subPath.length || interaction.type === INTERACTION_CALLED) {
6005
+ if (subPath.length > 0 || interaction.type === INTERACTION_CALLED) {
5984
6006
  const expressionAtPath = this.getMemberExpression(key);
5985
6007
  if (expressionAtPath) {
5986
6008
  return expressionAtPath.hasEffectsOnInteractionAtPath(subPath, interaction, context);
@@ -6015,7 +6037,7 @@ class ObjectEntity extends ExpressionEntity {
6015
6037
  }
6016
6038
  }
6017
6039
  else {
6018
- for (const accessors of Object.values(accessorsByKey).concat([unmatchableAccessors])) {
6040
+ for (const accessors of [...Object.values(accessorsByKey), unmatchableAccessors]) {
6019
6041
  for (const accessor of accessors) {
6020
6042
  if (accessor.hasEffectsOnInteractionAtPath(subPath, interaction, context))
6021
6043
  return true;
@@ -6107,7 +6129,7 @@ class ObjectEntity extends ExpressionEntity {
6107
6129
  }
6108
6130
  if (properties ||
6109
6131
  this.unmatchablePropertiesAndGetters.length > 0 ||
6110
- (this.unknownIntegerProps.length && INTEGER_REG_EXP.test(key))) {
6132
+ (this.unknownIntegerProps.length > 0 && INTEGER_REG_EXP.test(key))) {
6111
6133
  return UNKNOWN_EXPRESSION;
6112
6134
  }
6113
6135
  return null;
@@ -6126,7 +6148,7 @@ class ObjectEntity extends ExpressionEntity {
6126
6148
  }
6127
6149
  }
6128
6150
 
6129
- const isInteger = (prop) => typeof prop === 'string' && /^\d+$/.test(prop);
6151
+ const isInteger = (property) => typeof property === 'string' && /^\d+$/.test(property);
6130
6152
  // This makes sure unknown properties are not handled as "undefined" but as
6131
6153
  // "unknown" but without access side effects. An exception is done for numeric
6132
6154
  // properties as we do not expect new builtin properties to be numbers, this
@@ -6315,11 +6337,9 @@ class ArrayExpression extends NodeBase {
6315
6337
  let hasSpread = false;
6316
6338
  for (let index = 0; index < this.elements.length; index++) {
6317
6339
  const element = this.elements[index];
6318
- if (element) {
6319
- if (hasSpread || element instanceof SpreadElement) {
6320
- hasSpread = true;
6321
- element.deoptimizePath(UNKNOWN_PATH);
6322
- }
6340
+ if (element && (hasSpread || element instanceof SpreadElement)) {
6341
+ hasSpread = true;
6342
+ element.deoptimizePath(UNKNOWN_PATH);
6323
6343
  }
6324
6344
  }
6325
6345
  this.context.requestTreeshakingPass();
@@ -6459,13 +6479,14 @@ class LocalVariable extends Variable {
6459
6479
  }
6460
6480
  hasEffectsOnInteractionAtPath(path, interaction, context) {
6461
6481
  switch (interaction.type) {
6462
- case INTERACTION_ACCESSED:
6482
+ case INTERACTION_ACCESSED: {
6463
6483
  if (this.isReassigned)
6464
6484
  return true;
6465
6485
  return (this.init &&
6466
6486
  !context.accessed.trackEntityAtPathAndGetIfTracked(path, this) &&
6467
6487
  this.init.hasEffectsOnInteractionAtPath(path, interaction, context));
6468
- case INTERACTION_ASSIGNED:
6488
+ }
6489
+ case INTERACTION_ASSIGNED: {
6469
6490
  if (this.included)
6470
6491
  return true;
6471
6492
  if (path.length === 0)
@@ -6475,12 +6496,14 @@ class LocalVariable extends Variable {
6475
6496
  return (this.init &&
6476
6497
  !context.assigned.trackEntityAtPathAndGetIfTracked(path, this) &&
6477
6498
  this.init.hasEffectsOnInteractionAtPath(path, interaction, context));
6478
- case INTERACTION_CALLED:
6499
+ }
6500
+ case INTERACTION_CALLED: {
6479
6501
  if (this.isReassigned)
6480
6502
  return true;
6481
6503
  return (this.init &&
6482
6504
  !(interaction.withNew ? context.instantiated : context.called).trackEntityAtPathAndGetIfTracked(path, interaction.args, this) &&
6483
6505
  this.init.hasEffectsOnInteractionAtPath(path, interaction, context));
6506
+ }
6484
6507
  }
6485
6508
  }
6486
6509
  include() {
@@ -6502,15 +6525,15 @@ class LocalVariable extends Variable {
6502
6525
  }
6503
6526
  }
6504
6527
  }
6505
- includeCallArguments(context, args) {
6528
+ includeCallArguments(context, parameters) {
6506
6529
  if (this.isReassigned || (this.init && context.includedCallArguments.has(this.init))) {
6507
- for (const arg of args) {
6508
- arg.include(context, false);
6530
+ for (const argument of parameters) {
6531
+ argument.include(context, false);
6509
6532
  }
6510
6533
  }
6511
6534
  else if (this.init) {
6512
6535
  context.includedCallArguments.add(this.init);
6513
- this.init.includeCallArguments(context, args);
6536
+ this.init.includeCallArguments(context, parameters);
6514
6537
  context.includedCallArguments.delete(this.init);
6515
6538
  }
6516
6539
  }
@@ -6529,14 +6552,14 @@ class LocalVariable extends Variable {
6529
6552
 
6530
6553
  const chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$';
6531
6554
  const base = 64;
6532
- function toBase64(num) {
6533
- let outStr = '';
6555
+ function toBase64(value) {
6556
+ let outString = '';
6534
6557
  do {
6535
- const curDigit = num % base;
6536
- num = (num / base) | 0;
6537
- outStr = chars[curDigit] + outStr;
6538
- } while (num !== 0);
6539
- return outStr;
6558
+ const currentDigit = value % base;
6559
+ value = (value / base) | 0;
6560
+ outString = chars[currentDigit] + outString;
6561
+ } while (value !== 0);
6562
+ return outString;
6540
6563
  }
6541
6564
 
6542
6565
  function getSafeName(baseName, usedNames) {
@@ -6689,31 +6712,31 @@ class ParameterScope extends ChildScope {
6689
6712
  }
6690
6713
  this.hasRest = hasRest;
6691
6714
  }
6692
- includeCallArguments(context, args) {
6715
+ includeCallArguments(context, parameters) {
6693
6716
  let calledFromTryStatement = false;
6694
- let argIncluded = false;
6695
- const restParam = this.hasRest && this.parameters[this.parameters.length - 1];
6696
- for (const checkedArg of args) {
6697
- if (checkedArg instanceof SpreadElement) {
6698
- for (const arg of args) {
6699
- arg.include(context, false);
6717
+ let argumentIncluded = false;
6718
+ const restParameter = this.hasRest && this.parameters[this.parameters.length - 1];
6719
+ for (const checkedArgument of parameters) {
6720
+ if (checkedArgument instanceof SpreadElement) {
6721
+ for (const argument of parameters) {
6722
+ argument.include(context, false);
6700
6723
  }
6701
6724
  break;
6702
6725
  }
6703
6726
  }
6704
- for (let index = args.length - 1; index >= 0; index--) {
6705
- const paramVars = this.parameters[index] || restParam;
6706
- const arg = args[index];
6707
- if (paramVars) {
6727
+ for (let index = parameters.length - 1; index >= 0; index--) {
6728
+ const parameterVariables = this.parameters[index] || restParameter;
6729
+ const argument = parameters[index];
6730
+ if (parameterVariables) {
6708
6731
  calledFromTryStatement = false;
6709
- if (paramVars.length === 0) {
6732
+ if (parameterVariables.length === 0) {
6710
6733
  // handle empty destructuring
6711
- argIncluded = true;
6734
+ argumentIncluded = true;
6712
6735
  }
6713
6736
  else {
6714
- for (const variable of paramVars) {
6737
+ for (const variable of parameterVariables) {
6715
6738
  if (variable.included) {
6716
- argIncluded = true;
6739
+ argumentIncluded = true;
6717
6740
  }
6718
6741
  if (variable.calledFromTryStatement) {
6719
6742
  calledFromTryStatement = true;
@@ -6721,11 +6744,11 @@ class ParameterScope extends ChildScope {
6721
6744
  }
6722
6745
  }
6723
6746
  }
6724
- if (!argIncluded && arg.shouldBeIncluded(context)) {
6725
- argIncluded = true;
6747
+ if (!argumentIncluded && argument.shouldBeIncluded(context)) {
6748
+ argumentIncluded = true;
6726
6749
  }
6727
- if (argIncluded) {
6728
- arg.include(context, calledFromTryStatement);
6750
+ if (argumentIncluded) {
6751
+ argument.include(context, calledFromTryStatement);
6729
6752
  }
6730
6753
  }
6731
6754
  }
@@ -6839,7 +6862,7 @@ const MUTATES_ARG_WITHOUT_ACCESSOR = {
6839
6862
  [ValueProperties]: {
6840
6863
  getLiteralValue: getTruthyLiteralValue,
6841
6864
  hasEffectsWhenCalled({ args }, context) {
6842
- return (!args.length ||
6865
+ return (args.length === 0 ||
6843
6866
  args[0].hasEffectsOnInteractionAtPath(UNKNOWN_NON_ACCESSOR_PATH, NODE_INTERACTION_UNKNOWN_ASSIGNMENT, context));
6844
6867
  }
6845
6868
  }
@@ -7693,14 +7716,16 @@ class GlobalVariable extends Variable {
7693
7716
  }
7694
7717
  hasEffectsOnInteractionAtPath(path, interaction, context) {
7695
7718
  switch (interaction.type) {
7696
- case INTERACTION_ACCESSED:
7719
+ case INTERACTION_ACCESSED: {
7697
7720
  if (path.length === 0) {
7698
7721
  // Technically, "undefined" is a global variable of sorts
7699
7722
  return this.name !== 'undefined' && !getGlobalAtPath([this.name]);
7700
7723
  }
7701
7724
  return !getGlobalAtPath([this.name, ...path].slice(0, -1));
7702
- case INTERACTION_ASSIGNED:
7725
+ }
7726
+ case INTERACTION_ASSIGNED: {
7703
7727
  return true;
7728
+ }
7704
7729
  case INTERACTION_CALLED: {
7705
7730
  const globalAtPath = getGlobalAtPath([this.name, ...path]);
7706
7731
  return !globalAtPath || globalAtPath.hasEffectsWhenCalled(interaction, context);
@@ -7737,29 +7762,34 @@ class Identifier extends NodeBase {
7737
7762
  let variable;
7738
7763
  const { treeshake } = this.context.options;
7739
7764
  switch (kind) {
7740
- case 'var':
7765
+ case 'var': {
7741
7766
  variable = this.scope.addDeclaration(this, this.context, init, true);
7742
7767
  if (treeshake && treeshake.correctVarValueBeforeDeclaration) {
7743
7768
  // Necessary to make sure the init is deoptimized. We cannot call deoptimizePath here.
7744
7769
  variable.markInitializersForDeoptimization();
7745
7770
  }
7746
7771
  break;
7747
- case 'function':
7772
+ }
7773
+ case 'function': {
7748
7774
  // in strict mode, functions are only hoisted within a scope but not across block scopes
7749
7775
  variable = this.scope.addDeclaration(this, this.context, init, false);
7750
7776
  break;
7777
+ }
7751
7778
  case 'let':
7752
7779
  case 'const':
7753
- case 'class':
7780
+ case 'class': {
7754
7781
  variable = this.scope.addDeclaration(this, this.context, init, false);
7755
7782
  break;
7756
- case 'parameter':
7783
+ }
7784
+ case 'parameter': {
7757
7785
  variable = this.scope.addParameterDeclaration(this);
7758
7786
  break;
7787
+ }
7759
7788
  /* istanbul ignore next */
7760
- default:
7789
+ default: {
7761
7790
  /* istanbul ignore next */
7762
7791
  throw new Error(`Internal Error: Unexpected identifier kind ${kind}.`);
7792
+ }
7763
7793
  }
7764
7794
  variable.kind = kind;
7765
7795
  return [(this.variable = variable)];
@@ -7793,13 +7823,16 @@ class Identifier extends NodeBase {
7793
7823
  }
7794
7824
  hasEffectsOnInteractionAtPath(path, interaction, context) {
7795
7825
  switch (interaction.type) {
7796
- case INTERACTION_ACCESSED:
7826
+ case INTERACTION_ACCESSED: {
7797
7827
  return (this.variable !== null &&
7798
7828
  this.getVariableRespectingTDZ().hasEffectsOnInteractionAtPath(path, interaction, context));
7799
- case INTERACTION_ASSIGNED:
7829
+ }
7830
+ case INTERACTION_ASSIGNED: {
7800
7831
  return (path.length > 0 ? this.getVariableRespectingTDZ() : this.variable).hasEffectsOnInteractionAtPath(path, interaction, context);
7801
- case INTERACTION_CALLED:
7832
+ }
7833
+ case INTERACTION_CALLED: {
7802
7834
  return this.getVariableRespectingTDZ().hasEffectsOnInteractionAtPath(path, interaction, context);
7835
+ }
7803
7836
  }
7804
7837
  }
7805
7838
  include() {
@@ -7812,8 +7845,8 @@ class Identifier extends NodeBase {
7812
7845
  }
7813
7846
  }
7814
7847
  }
7815
- includeCallArguments(context, args) {
7816
- this.variable.includeCallArguments(context, args);
7848
+ includeCallArguments(context, parameters) {
7849
+ this.variable.includeCallArguments(context, parameters);
7817
7850
  }
7818
7851
  isPossibleTDZ() {
7819
7852
  // return cached value to avoid issues with the next tree-shaking pass
@@ -7872,7 +7905,7 @@ class Identifier extends NodeBase {
7872
7905
  }
7873
7906
  }
7874
7907
  disallowImportReassignment() {
7875
- return this.context.error(errIllegalImportReassignment(this.name, this.context.module.id), this.start);
7908
+ return this.context.error(errorIllegalImportReassignment(this.name, this.context.module.id), this.start);
7876
7909
  }
7877
7910
  getVariableRespectingTDZ() {
7878
7911
  if (this.isPossibleTDZ()) {
@@ -7998,10 +8031,9 @@ function renderStatementList(statements, code, start, end, options) {
7998
8031
  // This assumes that the first character is not part of the first node
7999
8032
  function getCommaSeparatedNodesWithBoundaries(nodes, code, start, end) {
8000
8033
  const splitUpNodes = [];
8001
- let node, nextNode, nextNodeStart, contentEnd, char;
8034
+ let node, nextNodeStart, contentEnd, char;
8002
8035
  let separator = start - 1;
8003
- for (let nextIndex = 0; nextIndex < nodes.length; nextIndex++) {
8004
- nextNode = nodes[nextIndex];
8036
+ for (const nextNode of nodes) {
8005
8037
  if (node !== undefined) {
8006
8038
  separator =
8007
8039
  node.end +
@@ -8068,7 +8100,7 @@ class ExpressionStatement extends NodeBase {
8068
8100
  this.parent.type === Program$1) {
8069
8101
  this.context.warn(
8070
8102
  // This is necessary, because either way (deleting or not) can lead to errors.
8071
- errModuleLevelDirective(this.directive, this.context.module.id), this.start);
8103
+ errorModuleLevelDirective(this.directive, this.context.module.id), this.start);
8072
8104
  }
8073
8105
  }
8074
8106
  render(code, options) {
@@ -8130,7 +8162,7 @@ class BlockStatement extends NodeBase {
8130
8162
  firstBodyStatement.directive === 'use asm';
8131
8163
  }
8132
8164
  render(code, options) {
8133
- if (this.body.length) {
8165
+ if (this.body.length > 0) {
8134
8166
  renderStatementList(this.body, code, this.start + 1, this.end - 1, options);
8135
8167
  }
8136
8168
  else {
@@ -8221,8 +8253,8 @@ class FunctionBase extends NodeBase {
8221
8253
  return true;
8222
8254
  }
8223
8255
  }
8224
- for (const param of this.params) {
8225
- if (param.hasEffects(context))
8256
+ for (const parameter of this.params) {
8257
+ if (parameter.hasEffects(context))
8226
8258
  return true;
8227
8259
  }
8228
8260
  return false;
@@ -8236,11 +8268,11 @@ class FunctionBase extends NodeBase {
8236
8268
  this.body.include(context, includeChildrenRecursively);
8237
8269
  context.brokenFlow = brokenFlow;
8238
8270
  }
8239
- includeCallArguments(context, args) {
8240
- this.scope.includeCallArguments(context, args);
8271
+ includeCallArguments(context, parameters) {
8272
+ this.scope.includeCallArguments(context, parameters);
8241
8273
  }
8242
8274
  initialise() {
8243
- this.scope.addParameterVariables(this.params.map(param => param.declare('parameter', UNKNOWN_EXPRESSION)), this.params[this.params.length - 1] instanceof RestElement);
8275
+ this.scope.addParameterVariables(this.params.map(parameter => parameter.declare('parameter', UNKNOWN_EXPRESSION)), this.params[this.params.length - 1] instanceof RestElement);
8244
8276
  if (this.body instanceof BlockStatement) {
8245
8277
  this.body.addImplicitReturnExpressionToScope();
8246
8278
  }
@@ -8291,9 +8323,9 @@ class ArrowFunctionExpression extends FunctionBase {
8291
8323
  }
8292
8324
  include(context, includeChildrenRecursively) {
8293
8325
  super.include(context, includeChildrenRecursively);
8294
- for (const param of this.params) {
8295
- if (!(param instanceof Identifier)) {
8296
- param.include(context, includeChildrenRecursively);
8326
+ for (const parameter of this.params) {
8327
+ if (!(parameter instanceof Identifier)) {
8328
+ parameter.include(context, includeChildrenRecursively);
8297
8329
  }
8298
8330
  }
8299
8331
  }
@@ -8391,12 +8423,12 @@ class ObjectPattern extends NodeBase {
8391
8423
 
8392
8424
  class AssignmentExpression extends NodeBase {
8393
8425
  hasEffects(context) {
8394
- const { deoptimized, left, right } = this;
8426
+ const { deoptimized, left, operator, right } = this;
8395
8427
  if (!deoptimized)
8396
8428
  this.applyDeoptimizations();
8397
8429
  // MemberExpressions do not access the property before assignments if the
8398
8430
  // operator is '='.
8399
- return (right.hasEffects(context) || left.hasEffectsAsAssignmentTarget(context, this.operator !== '='));
8431
+ return (right.hasEffects(context) || left.hasEffectsAsAssignmentTarget(context, operator !== '='));
8400
8432
  }
8401
8433
  hasEffectsOnInteractionAtPath(path, interaction, context) {
8402
8434
  return this.right.hasEffectsOnInteractionAtPath(path, interaction, context);
@@ -8567,12 +8599,12 @@ class FunctionScope extends ReturnValueScope {
8567
8599
  findLexicalBoundary() {
8568
8600
  return this;
8569
8601
  }
8570
- includeCallArguments(context, args) {
8571
- super.includeCallArguments(context, args);
8602
+ includeCallArguments(context, parameters) {
8603
+ super.includeCallArguments(context, parameters);
8572
8604
  if (this.argumentsVariable.included) {
8573
- for (const arg of args) {
8574
- if (!arg.included) {
8575
- arg.include(context, false);
8605
+ for (const argument of parameters) {
8606
+ if (!argument.included) {
8607
+ argument.include(context, false);
8576
8608
  }
8577
8609
  }
8578
8610
  }
@@ -8606,7 +8638,7 @@ class FunctionNode extends FunctionBase {
8606
8638
  context.replacedVariableInits.set(this.scope.thisVariable, interaction.withNew
8607
8639
  ? new ObjectEntity(Object.create(null), OBJECT_PROTOTYPE)
8608
8640
  : UNKNOWN_EXPRESSION);
8609
- const { brokenFlow, ignore } = context;
8641
+ const { brokenFlow, ignore, replacedVariableInits } = context;
8610
8642
  context.ignore = {
8611
8643
  breaks: false,
8612
8644
  continues: false,
@@ -8617,10 +8649,10 @@ class FunctionNode extends FunctionBase {
8617
8649
  return true;
8618
8650
  context.brokenFlow = brokenFlow;
8619
8651
  if (thisInit) {
8620
- context.replacedVariableInits.set(this.scope.thisVariable, thisInit);
8652
+ replacedVariableInits.set(this.scope.thisVariable, thisInit);
8621
8653
  }
8622
8654
  else {
8623
- context.replacedVariableInits.delete(this.scope.thisVariable);
8655
+ replacedVariableInits.delete(this.scope.thisVariable);
8624
8656
  }
8625
8657
  context.ignore = ignore;
8626
8658
  }
@@ -8630,9 +8662,9 @@ class FunctionNode extends FunctionBase {
8630
8662
  super.include(context, includeChildrenRecursively);
8631
8663
  this.id?.include();
8632
8664
  const hasArguments = this.scope.argumentsVariable.included;
8633
- for (const param of this.params) {
8634
- if (!(param instanceof Identifier) || hasArguments) {
8635
- param.include(context, includeChildrenRecursively);
8665
+ for (const parameter of this.params) {
8666
+ if (!(parameter instanceof Identifier) || hasArguments) {
8667
+ parameter.include(context, includeChildrenRecursively);
8636
8668
  }
8637
8669
  }
8638
8670
  }
@@ -8715,10 +8747,10 @@ class BinaryExpression extends NodeBase {
8715
8747
  const rightValue = this.right.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
8716
8748
  if (typeof rightValue === 'symbol')
8717
8749
  return UnknownValue;
8718
- const operatorFn = binaryOperators[this.operator];
8719
- if (!operatorFn)
8750
+ const operatorFunction = binaryOperators[this.operator];
8751
+ if (!operatorFunction)
8720
8752
  return UnknownValue;
8721
- return operatorFn(leftValue, rightValue);
8753
+ return operatorFunction(leftValue, rightValue);
8722
8754
  }
8723
8755
  hasEffects(context) {
8724
8756
  // support some implicit type coercion runtime errors
@@ -8766,8 +8798,8 @@ class BreakStatement extends NodeBase {
8766
8798
  function renderCallArguments(code, options, node) {
8767
8799
  if (node.arguments.length > 0) {
8768
8800
  if (node.arguments[node.arguments.length - 1].included) {
8769
- for (const arg of node.arguments) {
8770
- arg.render(code, options);
8801
+ for (const argument of node.arguments) {
8802
+ argument.render(code, options);
8771
8803
  }
8772
8804
  }
8773
8805
  else {
@@ -8808,13 +8840,16 @@ class Literal extends NodeBase {
8808
8840
  }
8809
8841
  hasEffectsOnInteractionAtPath(path, interaction, context) {
8810
8842
  switch (interaction.type) {
8811
- case INTERACTION_ACCESSED:
8843
+ case INTERACTION_ACCESSED: {
8812
8844
  return path.length > (this.value === null ? 0 : 1);
8813
- case INTERACTION_ASSIGNED:
8845
+ }
8846
+ case INTERACTION_ASSIGNED: {
8814
8847
  return true;
8815
- case INTERACTION_CALLED:
8848
+ }
8849
+ case INTERACTION_CALLED: {
8816
8850
  return (path.length !== 1 ||
8817
8851
  hasMemberEffectWhenCalled(this.members, path[0], interaction, context));
8852
+ }
8818
8853
  }
8819
8854
  }
8820
8855
  initialise() {
@@ -8914,14 +8949,12 @@ class MemberExpression extends NodeBase {
8914
8949
  if (this.variable) {
8915
8950
  this.variable.deoptimizePath(path);
8916
8951
  }
8917
- else if (!this.isUndefined) {
8918
- if (path.length < MAX_PATH_DEPTH) {
8919
- const propertyKey = this.getPropertyKey();
8920
- this.object.deoptimizePath([
8921
- propertyKey === UnknownKey ? UnknownNonAccessorKey : propertyKey,
8922
- ...path
8923
- ]);
8924
- }
8952
+ else if (!this.isUndefined && path.length < MAX_PATH_DEPTH) {
8953
+ const propertyKey = this.getPropertyKey();
8954
+ this.object.deoptimizePath([
8955
+ propertyKey === UnknownKey ? UnknownNonAccessorKey : propertyKey,
8956
+ ...path
8957
+ ]);
8925
8958
  }
8926
8959
  }
8927
8960
  deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
@@ -9007,12 +9040,12 @@ class MemberExpression extends NodeBase {
9007
9040
  this.includeProperties(context, includeChildrenRecursively);
9008
9041
  }
9009
9042
  }
9010
- includeCallArguments(context, args) {
9043
+ includeCallArguments(context, parameters) {
9011
9044
  if (this.variable) {
9012
- this.variable.includeCallArguments(context, args);
9045
+ this.variable.includeCallArguments(context, parameters);
9013
9046
  }
9014
9047
  else {
9015
- super.includeCallArguments(context, args);
9048
+ super.includeCallArguments(context, parameters);
9016
9049
  }
9017
9050
  }
9018
9051
  initialise() {
@@ -9079,7 +9112,7 @@ class MemberExpression extends NodeBase {
9079
9112
  if (this.variable) {
9080
9113
  this.context.includeVariableInModule(this.variable);
9081
9114
  }
9082
- this.context.warn(errIllegalImportReassignment(this.object.name, this.context.module.id), this.start);
9115
+ this.context.warn(errorIllegalImportReassignment(this.object.name, this.context.module.id), this.start);
9083
9116
  }
9084
9117
  }
9085
9118
  }
@@ -9124,7 +9157,7 @@ function resolveNamespaceVariables(baseVariable, path, astContext) {
9124
9157
  const variable = baseVariable.context.traceExport(exportName);
9125
9158
  if (!variable) {
9126
9159
  const fileName = baseVariable.context.fileName;
9127
- astContext.warn(errMissingExport(exportName, astContext.module.id, fileName), path[0].pos);
9160
+ astContext.warn(errorMissingExport(exportName, astContext.module.id, fileName), path[0].pos);
9128
9161
  return 'undefined';
9129
9162
  }
9130
9163
  return resolveNamespaceVariables(variable, path.slice(1), astContext);
@@ -9167,7 +9200,7 @@ class CallExpressionBase extends NodeBase {
9167
9200
  recursionTracker.withTrackedEntityAtPath(path, returnExpression, () => {
9168
9201
  this.expressionsToBeDeoptimized.add(interaction.thisArg);
9169
9202
  returnExpression.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
9170
- }, undefined);
9203
+ }, null);
9171
9204
  }
9172
9205
  }
9173
9206
  getLiteralValueAtPath(path, recursionTracker, origin) {
@@ -9193,9 +9226,8 @@ class CallExpressionBase extends NodeBase {
9193
9226
  hasEffectsOnInteractionAtPath(path, interaction, context) {
9194
9227
  const { type } = interaction;
9195
9228
  if (type === INTERACTION_CALLED) {
9196
- if ((interaction.withNew
9197
- ? context.instantiated
9198
- : context.called).trackEntityAtPathAndGetIfTracked(path, interaction.args, this)) {
9229
+ const { args, withNew } = interaction;
9230
+ if ((withNew ? context.instantiated : context.called).trackEntityAtPathAndGetIfTracked(path, args, this)) {
9199
9231
  return false;
9200
9232
  }
9201
9233
  }
@@ -9214,10 +9246,10 @@ class CallExpression extends CallExpressionBase {
9214
9246
  if (this.callee instanceof Identifier) {
9215
9247
  const variable = this.scope.findVariable(this.callee.name);
9216
9248
  if (variable.isNamespace) {
9217
- this.context.warn(errCannotCallNamespace(this.callee.name), this.start);
9249
+ this.context.warn(errorCannotCallNamespace(this.callee.name), this.start);
9218
9250
  }
9219
9251
  if (this.callee.name === 'eval') {
9220
- this.context.warn(errEval(this.context.module.id), this.start);
9252
+ this.context.warn(errorEval(this.context.module.id), this.start);
9221
9253
  }
9222
9254
  }
9223
9255
  this.interaction = {
@@ -9490,16 +9522,13 @@ class ClassNode extends NodeBase {
9490
9522
  return initEffect || super.hasEffects(context);
9491
9523
  }
9492
9524
  hasEffectsOnInteractionAtPath(path, interaction, context) {
9493
- if (interaction.type === INTERACTION_CALLED && path.length === 0) {
9494
- return (!interaction.withNew ||
9525
+ return interaction.type === INTERACTION_CALLED && path.length === 0
9526
+ ? !interaction.withNew ||
9495
9527
  (this.classConstructor !== null
9496
9528
  ? this.classConstructor.hasEffectsOnInteractionAtPath(path, interaction, context)
9497
9529
  : this.superClass?.hasEffectsOnInteractionAtPath(path, interaction, context)) ||
9498
- false);
9499
- }
9500
- else {
9501
- return this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
9502
- }
9530
+ false
9531
+ : this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
9503
9532
  }
9504
9533
  include(context, includeChildrenRecursively) {
9505
9534
  if (!this.deoptimized)
@@ -9706,14 +9735,14 @@ class ConditionalExpression extends NodeBase {
9706
9735
  usedBranch.include(context, includeChildrenRecursively);
9707
9736
  }
9708
9737
  }
9709
- includeCallArguments(context, args) {
9738
+ includeCallArguments(context, parameters) {
9710
9739
  const usedBranch = this.getUsedBranch();
9711
9740
  if (!usedBranch) {
9712
- this.consequent.includeCallArguments(context, args);
9713
- this.alternate.includeCallArguments(context, args);
9741
+ this.consequent.includeCallArguments(context, parameters);
9742
+ this.alternate.includeCallArguments(context, parameters);
9714
9743
  }
9715
9744
  else {
9716
- usedBranch.includeCallArguments(context, args);
9745
+ usedBranch.includeCallArguments(context, parameters);
9717
9746
  }
9718
9747
  }
9719
9748
  render(code, options, { isCalleeOfRenderedParent, preventASI, renderedParentType, renderedSurroundingElement } = BLANK) {
@@ -9785,13 +9814,14 @@ class DoWhileStatement extends NodeBase {
9785
9814
  hasEffects(context) {
9786
9815
  if (this.test.hasEffects(context))
9787
9816
  return true;
9788
- const { brokenFlow, ignore: { breaks, continues } } = context;
9789
- context.ignore.breaks = true;
9790
- context.ignore.continues = true;
9817
+ const { brokenFlow, ignore } = context;
9818
+ const { breaks, continues } = ignore;
9819
+ ignore.breaks = true;
9820
+ ignore.continues = true;
9791
9821
  if (this.body.hasEffects(context))
9792
9822
  return true;
9793
- context.ignore.breaks = breaks;
9794
- context.ignore.continues = continues;
9823
+ ignore.breaks = breaks;
9824
+ ignore.continues = continues;
9795
9825
  context.brokenFlow = brokenFlow;
9796
9826
  return false;
9797
9827
  }
@@ -9961,18 +9991,19 @@ class ForInStatement extends NodeBase {
9961
9991
  this.scope = new BlockScope(parentScope);
9962
9992
  }
9963
9993
  hasEffects(context) {
9964
- const { deoptimized, left, right } = this;
9994
+ const { body, deoptimized, left, right } = this;
9965
9995
  if (!deoptimized)
9966
9996
  this.applyDeoptimizations();
9967
9997
  if (left.hasEffectsAsAssignmentTarget(context, false) || right.hasEffects(context))
9968
9998
  return true;
9969
- const { brokenFlow, ignore: { breaks, continues } } = context;
9970
- context.ignore.breaks = true;
9971
- context.ignore.continues = true;
9972
- if (this.body.hasEffects(context))
9999
+ const { brokenFlow, ignore } = context;
10000
+ const { breaks, continues } = ignore;
10001
+ ignore.breaks = true;
10002
+ ignore.continues = true;
10003
+ if (body.hasEffects(context))
9973
10004
  return true;
9974
- context.ignore.breaks = breaks;
9975
- context.ignore.continues = continues;
10005
+ ignore.breaks = breaks;
10006
+ ignore.continues = continues;
9976
10007
  context.brokenFlow = brokenFlow;
9977
10008
  return false;
9978
10009
  }
@@ -10055,13 +10086,14 @@ class ForStatement extends NodeBase {
10055
10086
  this.test?.hasEffects(context) ||
10056
10087
  this.update?.hasEffects(context))
10057
10088
  return true;
10058
- const { brokenFlow, ignore: { breaks, continues } } = context;
10059
- context.ignore.breaks = true;
10060
- context.ignore.continues = true;
10089
+ const { brokenFlow, ignore } = context;
10090
+ const { breaks, continues } = ignore;
10091
+ ignore.breaks = true;
10092
+ ignore.continues = true;
10061
10093
  if (this.body.hasEffects(context))
10062
10094
  return true;
10063
- context.ignore.breaks = breaks;
10064
- context.ignore.continues = continues;
10095
+ ignore.breaks = breaks;
10096
+ ignore.continues = continues;
10065
10097
  context.brokenFlow = brokenFlow;
10066
10098
  return false;
10067
10099
  }
@@ -10121,6 +10153,7 @@ class IfStatement extends NodeBase {
10121
10153
  const { brokenFlow } = context;
10122
10154
  if (this.consequent.hasEffects(context))
10123
10155
  return true;
10156
+ // eslint-disable-next-line unicorn/consistent-destructuring
10124
10157
  const consequentBrokenFlow = context.brokenFlow;
10125
10158
  context.brokenFlow = brokenFlow;
10126
10159
  if (this.alternate === null)
@@ -10128,6 +10161,7 @@ class IfStatement extends NodeBase {
10128
10161
  if (this.alternate.hasEffects(context))
10129
10162
  return true;
10130
10163
  context.brokenFlow =
10164
+ // eslint-disable-next-line unicorn/consistent-destructuring
10131
10165
  context.brokenFlow < consequentBrokenFlow ? context.brokenFlow : consequentBrokenFlow;
10132
10166
  return false;
10133
10167
  }
@@ -10230,17 +10264,19 @@ class IfStatement extends NodeBase {
10230
10264
  let consequentBrokenFlow = BROKEN_FLOW_NONE;
10231
10265
  if (this.consequent.shouldBeIncluded(context)) {
10232
10266
  this.consequent.include(context, false, { asSingleStatement: true });
10267
+ // eslint-disable-next-line unicorn/consistent-destructuring
10233
10268
  consequentBrokenFlow = context.brokenFlow;
10234
10269
  context.brokenFlow = brokenFlow;
10235
10270
  }
10236
10271
  if (this.alternate?.shouldBeIncluded(context)) {
10237
10272
  this.alternate.include(context, false, { asSingleStatement: true });
10238
10273
  context.brokenFlow =
10274
+ // eslint-disable-next-line unicorn/consistent-destructuring
10239
10275
  context.brokenFlow < consequentBrokenFlow ? context.brokenFlow : consequentBrokenFlow;
10240
10276
  }
10241
10277
  }
10242
10278
  renderHoistedDeclarations(hoistedDeclarations, code, getPropertyAccess) {
10243
- const hoistedVars = [
10279
+ const hoistedVariables = [
10244
10280
  ...new Set(hoistedDeclarations.map(identifier => {
10245
10281
  const variable = identifier.variable;
10246
10282
  return variable.included ? variable.getName(getPropertyAccess) : '';
@@ -10248,10 +10284,10 @@ class IfStatement extends NodeBase {
10248
10284
  ]
10249
10285
  .filter(Boolean)
10250
10286
  .join(', ');
10251
- if (hoistedVars) {
10287
+ if (hoistedVariables) {
10252
10288
  const parentType = this.parent.type;
10253
10289
  const needsBraces = parentType !== Program$1 && parentType !== BlockStatement$1;
10254
- code.prependRight(this.start, `${needsBraces ? '{ ' : ''}var ${hoistedVars}; `);
10290
+ code.prependRight(this.start, `${needsBraces ? '{ ' : ''}var ${hoistedVariables}; `);
10255
10291
  if (needsBraces) {
10256
10292
  code.appendLeft(this.end, ` }`);
10257
10293
  }
@@ -10419,21 +10455,21 @@ const HELPER_GENERATORS = {
10419
10455
  const getDefaultLiveBinding = ({ _, getObject }) => `e${_}:${_}${getObject([['default', 'e']], { lineBreakIndent: null })}`;
10420
10456
  const getDefaultStatic = ({ _, getPropertyAccess }) => `e${getPropertyAccess('default')}${_}:${_}e`;
10421
10457
  const getIsCompatNamespace = ({ _ }) => `e${_}&&${_}typeof e${_}===${_}'object'${_}&&${_}'default'${_}in e`;
10422
- const createNamespaceObject = (t, i, snippets, liveBindings, freeze, namespaceToStringTag) => {
10458
+ const createNamespaceObject = (t, index, snippets, liveBindings, freeze, namespaceToStringTag) => {
10423
10459
  const { _, cnst, getObject, getPropertyAccess, n, s } = snippets;
10424
10460
  const copyProperty = `{${n}` +
10425
- (liveBindings ? copyNonDefaultOwnPropertyLiveBinding : copyPropertyStatic)(t, i + t + t, snippets) +
10426
- `${i}${t}}`;
10427
- return (`${i}${cnst} n${_}=${_}Object.create(null${namespaceToStringTag
10461
+ (liveBindings ? copyNonDefaultOwnPropertyLiveBinding : copyPropertyStatic)(t, index + t + t, snippets) +
10462
+ `${index}${t}}`;
10463
+ return (`${index}${cnst} n${_}=${_}Object.create(null${namespaceToStringTag
10428
10464
  ? `,${_}{${_}[Symbol.toStringTag]:${_}${getToStringTagValue(getObject)}${_}}`
10429
10465
  : ''});${n}` +
10430
- `${i}if${_}(e)${_}{${n}` +
10431
- `${i}${t}${loopOverKeys(copyProperty, !liveBindings, snippets)}${n}` +
10432
- `${i}}${n}` +
10433
- `${i}n${getPropertyAccess('default')}${_}=${_}e;${n}` +
10434
- `${i}return ${getFrozen(freeze, 'n')}${s}${n}`);
10466
+ `${index}if${_}(e)${_}{${n}` +
10467
+ `${index}${t}${loopOverKeys(copyProperty, !liveBindings, snippets)}${n}` +
10468
+ `${index}}${n}` +
10469
+ `${index}n${getPropertyAccess('default')}${_}=${_}e;${n}` +
10470
+ `${index}return ${getFrozen(freeze, 'n')}${s}${n}`);
10435
10471
  };
10436
- const loopOverKeys = (body, allowVarLoopVariable, { _, cnst, getFunctionIntro, s }) => cnst !== 'var' || allowVarLoopVariable
10472
+ const loopOverKeys = (body, allowVariableLoopVariable, { _, cnst, getFunctionIntro, s }) => cnst !== 'var' || allowVariableLoopVariable
10437
10473
  ? `for${_}(${cnst} k in e)${_}${body}`
10438
10474
  : `Object.keys(e).forEach(${getFunctionIntro(['k'], {
10439
10475
  isAsync: false,
@@ -10456,39 +10492,39 @@ const loopOverNamespaces = (body, useForEach, t, { _, cnst, getDirectReturnFunct
10456
10492
  `${t}${t}${cnst} e${_}=${_}m[i];${n}` +
10457
10493
  `${t}${t}if${_}(typeof e${_}!==${_}'string'${_}&&${_}!Array.isArray(e))${_}{${_}for${_}(${cnst} k in e)${_}${body}${_}}${n}${t}}`);
10458
10494
  };
10459
- const copyNonDefaultOwnPropertyLiveBinding = (t, i, snippets) => {
10495
+ const copyNonDefaultOwnPropertyLiveBinding = (t, index, snippets) => {
10460
10496
  const { _, n } = snippets;
10461
- return (`${i}if${_}(k${_}!==${_}'default')${_}{${n}` +
10462
- copyOwnPropertyLiveBinding(t, i + t, snippets) +
10463
- `${i}}${n}`);
10497
+ return (`${index}if${_}(k${_}!==${_}'default')${_}{${n}` +
10498
+ copyOwnPropertyLiveBinding(t, index + t, snippets) +
10499
+ `${index}}${n}`);
10464
10500
  };
10465
- const copyOwnPropertyLiveBinding = (t, i, { _, cnst, getDirectReturnFunction, n }) => {
10501
+ const copyOwnPropertyLiveBinding = (t, index, { _, cnst, getDirectReturnFunction, n }) => {
10466
10502
  const [left, right] = getDirectReturnFunction([], {
10467
10503
  functionReturn: true,
10468
10504
  lineBreakIndent: null,
10469
10505
  name: null
10470
10506
  });
10471
- return (`${i}${cnst} d${_}=${_}Object.getOwnPropertyDescriptor(e,${_}k);${n}` +
10472
- `${i}Object.defineProperty(n,${_}k,${_}d.get${_}?${_}d${_}:${_}{${n}` +
10473
- `${i}${t}enumerable:${_}true,${n}` +
10474
- `${i}${t}get:${_}${left}e[k]${right}${n}` +
10475
- `${i}});${n}`);
10507
+ return (`${index}${cnst} d${_}=${_}Object.getOwnPropertyDescriptor(e,${_}k);${n}` +
10508
+ `${index}Object.defineProperty(n,${_}k,${_}d.get${_}?${_}d${_}:${_}{${n}` +
10509
+ `${index}${t}enumerable:${_}true,${n}` +
10510
+ `${index}${t}get:${_}${left}e[k]${right}${n}` +
10511
+ `${index}});${n}`);
10476
10512
  };
10477
- const copyPropertyLiveBinding = (t, i, { _, cnst, getDirectReturnFunction, n }) => {
10513
+ const copyPropertyLiveBinding = (t, index, { _, cnst, getDirectReturnFunction, n }) => {
10478
10514
  const [left, right] = getDirectReturnFunction([], {
10479
10515
  functionReturn: true,
10480
10516
  lineBreakIndent: null,
10481
10517
  name: null
10482
10518
  });
10483
- return (`${i}${cnst} d${_}=${_}Object.getOwnPropertyDescriptor(e,${_}k);${n}` +
10484
- `${i}if${_}(d)${_}{${n}` +
10485
- `${i}${t}Object.defineProperty(n,${_}k,${_}d.get${_}?${_}d${_}:${_}{${n}` +
10486
- `${i}${t}${t}enumerable:${_}true,${n}` +
10487
- `${i}${t}${t}get:${_}${left}e[k]${right}${n}` +
10488
- `${i}${t}});${n}` +
10489
- `${i}}${n}`);
10490
- };
10491
- const copyPropertyStatic = (_t, i, { _, n }) => `${i}n[k]${_}=${_}e[k];${n}`;
10519
+ return (`${index}${cnst} d${_}=${_}Object.getOwnPropertyDescriptor(e,${_}k);${n}` +
10520
+ `${index}if${_}(d)${_}{${n}` +
10521
+ `${index}${t}Object.defineProperty(n,${_}k,${_}d.get${_}?${_}d${_}:${_}{${n}` +
10522
+ `${index}${t}${t}enumerable:${_}true,${n}` +
10523
+ `${index}${t}${t}get:${_}${left}e[k]${right}${n}` +
10524
+ `${index}${t}});${n}` +
10525
+ `${index}}${n}`);
10526
+ };
10527
+ const copyPropertyStatic = (_t, index, { _, n }) => `${index}n[k]${_}=${_}e[k];${n}`;
10492
10528
  const getFrozen = (freeze, fragment) => freeze ? `Object.freeze(${fragment})` : fragment;
10493
10529
  const getWithToStringTag = (namespaceToStringTag, fragment, { _, getObject }) => namespaceToStringTag
10494
10530
  ? `Object.defineProperty(${fragment},${_}Symbol.toStringTag,${_}${getToStringTagValue(getObject)})`
@@ -10667,7 +10703,7 @@ class ImportExpression extends NodeBase {
10667
10703
  mechanism: { left, right }
10668
10704
  };
10669
10705
  }
10670
- case 'system':
10706
+ case 'system': {
10671
10707
  return {
10672
10708
  helper: null,
10673
10709
  mechanism: {
@@ -10675,7 +10711,8 @@ class ImportExpression extends NodeBase {
10675
10711
  right: ')'
10676
10712
  }
10677
10713
  };
10678
- case 'es':
10714
+ }
10715
+ case 'es': {
10679
10716
  if (dynamicImportFunction) {
10680
10717
  return {
10681
10718
  helper: null,
@@ -10685,6 +10722,7 @@ class ImportExpression extends NodeBase {
10685
10722
  }
10686
10723
  };
10687
10724
  }
10725
+ }
10688
10726
  }
10689
10727
  return { helper: null, mechanism: null };
10690
10728
  }
@@ -10886,7 +10924,7 @@ class MetaProperty extends NodeBase {
10886
10924
  getReferencedFileName(outputPluginDriver) {
10887
10925
  const { metaProperty } = this;
10888
10926
  if (metaProperty?.startsWith(FILE_PREFIX)) {
10889
- return outputPluginDriver.getFileName(metaProperty.substring(FILE_PREFIX.length));
10927
+ return outputPluginDriver.getFileName(metaProperty.slice(FILE_PREFIX.length));
10890
10928
  }
10891
10929
  return null;
10892
10930
  }
@@ -10907,44 +10945,33 @@ class MetaProperty extends NodeBase {
10907
10945
  ? parent.propertyKey
10908
10946
  : null);
10909
10947
  if (metaProperty?.startsWith(FILE_PREFIX)) {
10910
- this.referenceId = metaProperty.substring(FILE_PREFIX.length);
10948
+ this.referenceId = metaProperty.slice(FILE_PREFIX.length);
10911
10949
  }
10912
10950
  }
10913
10951
  }
10914
10952
  }
10915
10953
  render(code, { format, pluginDriver, snippets }) {
10916
- const { metaProperty, parent, referenceId } = this;
10917
- const chunkId = this.preliminaryChunkId;
10954
+ const { context: { module: { id: moduleId } }, metaProperty, parent, preliminaryChunkId, referenceId, start, end } = this;
10955
+ const chunkId = preliminaryChunkId;
10918
10956
  if (referenceId) {
10919
10957
  const fileName = pluginDriver.getFileName(referenceId);
10920
10958
  const relativePath = normalize(relative$1(dirname(chunkId), fileName));
10921
10959
  const replacement = pluginDriver.hookFirstSync('resolveFileUrl', [
10922
- {
10923
- chunkId,
10924
- fileName,
10925
- format,
10926
- moduleId: this.context.module.id,
10927
- referenceId,
10928
- relativePath
10929
- }
10960
+ { chunkId, fileName, format, moduleId, referenceId, relativePath }
10930
10961
  ]) || relativeUrlMechanisms[format](relativePath);
10931
10962
  code.overwrite(parent.start, parent.end, replacement, { contentOnly: true });
10932
10963
  return;
10933
10964
  }
10934
10965
  const replacement = pluginDriver.hookFirstSync('resolveImportMeta', [
10935
10966
  metaProperty,
10936
- {
10937
- chunkId,
10938
- format,
10939
- moduleId: this.context.module.id
10940
- }
10967
+ { chunkId, format, moduleId }
10941
10968
  ]) || importMetaMechanisms[format]?.(metaProperty, { chunkId, snippets });
10942
10969
  if (typeof replacement === 'string') {
10943
10970
  if (parent instanceof MemberExpression) {
10944
10971
  code.overwrite(parent.start, parent.end, replacement, { contentOnly: true });
10945
10972
  }
10946
10973
  else {
10947
- code.overwrite(this.start, this.end, replacement, { contentOnly: true });
10974
+ code.overwrite(start, end, replacement, { contentOnly: true });
10948
10975
  }
10949
10976
  }
10950
10977
  }
@@ -10974,11 +11001,11 @@ const accessedFileUrlGlobals = {
10974
11001
  };
10975
11002
  const getResolveUrl = (path, URL = 'URL') => `new ${URL}(${path}).href`;
10976
11003
  const getRelativeUrlFromDocument = (relativePath, umd = false) => getResolveUrl(`'${relativePath}', ${umd ? `typeof document === 'undefined' ? location.href : ` : ''}document.currentScript && document.currentScript.src || document.baseURI`);
10977
- const getGenericImportMetaMechanism = (getUrl) => (prop, { chunkId }) => {
11004
+ const getGenericImportMetaMechanism = (getUrl) => (property, { chunkId }) => {
10978
11005
  const urlMechanism = getUrl(chunkId);
10979
- return prop === null
11006
+ return property === null
10980
11007
  ? `({ url: ${urlMechanism} })`
10981
- : prop === 'url'
11008
+ : property === 'url'
10982
11009
  ? urlMechanism
10983
11010
  : 'undefined';
10984
11011
  };
@@ -10999,7 +11026,7 @@ const importMetaMechanisms = {
10999
11026
  amd: getGenericImportMetaMechanism(() => getResolveUrl(`module.uri, document.baseURI`)),
11000
11027
  cjs: getGenericImportMetaMechanism(chunkId => `(typeof document === 'undefined' ? ${getResolveUrl(`'file:' + __filename`, `(require('u' + 'rl').URL)`)} : ${getUrlFromDocument(chunkId)})`),
11001
11028
  iife: getGenericImportMetaMechanism(chunkId => getUrlFromDocument(chunkId)),
11002
- system: (prop, { snippets: { getPropertyAccess } }) => prop === null ? `module.meta` : `module.meta${getPropertyAccess(prop)}`,
11029
+ system: (property, { snippets: { getPropertyAccess } }) => property === null ? `module.meta` : `module.meta${getPropertyAccess(property)}`,
11003
11030
  umd: getGenericImportMetaMechanism(chunkId => `(typeof document === 'undefined' && typeof location === 'undefined' ? ${getResolveUrl(`'file:' + __filename`, `(require('u' + 'rl').URL)`)} : ${getUrlFromDocument(chunkId, true)})`)
11004
11031
  };
11005
11032
 
@@ -11160,7 +11187,7 @@ class Program extends NodeBase {
11160
11187
  }
11161
11188
  }
11162
11189
  render(code, options) {
11163
- if (this.body.length) {
11190
+ if (this.body.length > 0) {
11164
11191
  renderStatementList(this.body, code, this.start, this.end, options);
11165
11192
  }
11166
11193
  else {
@@ -11338,7 +11365,7 @@ class StaticBlock extends NodeBase {
11338
11365
  }
11339
11366
  }
11340
11367
  render(code, options) {
11341
- if (this.body.length) {
11368
+ if (this.body.length > 0) {
11342
11369
  renderStatementList(this.body, code, this.start + 1, this.end - 1, options);
11343
11370
  }
11344
11371
  else {
@@ -11386,7 +11413,7 @@ class SwitchCase extends NodeBase {
11386
11413
  }
11387
11414
  }
11388
11415
  render(code, options, nodeRenderOptions) {
11389
- if (this.consequent.length) {
11416
+ if (this.consequent.length > 0) {
11390
11417
  this.test && this.test.render(code, options);
11391
11418
  const testEnd = this.test
11392
11419
  ? this.test.end
@@ -11408,19 +11435,21 @@ class SwitchStatement extends NodeBase {
11408
11435
  hasEffects(context) {
11409
11436
  if (this.discriminant.hasEffects(context))
11410
11437
  return true;
11411
- const { brokenFlow, ignore: { breaks } } = context;
11438
+ const { brokenFlow, ignore } = context;
11439
+ const { breaks } = ignore;
11412
11440
  let minBrokenFlow = Infinity;
11413
- context.ignore.breaks = true;
11441
+ ignore.breaks = true;
11414
11442
  for (const switchCase of this.cases) {
11415
11443
  if (switchCase.hasEffects(context))
11416
11444
  return true;
11445
+ // eslint-disable-next-line unicorn/consistent-destructuring
11417
11446
  minBrokenFlow = context.brokenFlow < minBrokenFlow ? context.brokenFlow : minBrokenFlow;
11418
11447
  context.brokenFlow = brokenFlow;
11419
11448
  }
11420
11449
  if (this.defaultCase !== null && !(minBrokenFlow === BROKEN_FLOW_BREAK_CONTINUE)) {
11421
11450
  context.brokenFlow = minBrokenFlow;
11422
11451
  }
11423
- context.ignore.breaks = breaks;
11452
+ ignore.breaks = breaks;
11424
11453
  return false;
11425
11454
  }
11426
11455
  include(context, includeChildrenRecursively) {
@@ -11442,6 +11471,7 @@ class SwitchStatement extends NodeBase {
11442
11471
  }
11443
11472
  if (isCaseIncluded) {
11444
11473
  switchCase.include(context, includeChildrenRecursively);
11474
+ // eslint-disable-next-line unicorn/consistent-destructuring
11445
11475
  minBrokenFlow = minBrokenFlow < context.brokenFlow ? minBrokenFlow : context.brokenFlow;
11446
11476
  context.brokenFlow = brokenFlow;
11447
11477
  }
@@ -11479,7 +11509,7 @@ class TaggedTemplateExpression extends CallExpressionBase {
11479
11509
  const name = this.tag.name;
11480
11510
  const variable = this.scope.findVariable(name);
11481
11511
  if (variable.isNamespace) {
11482
- this.context.warn(errCannotCallNamespace(name), this.start);
11512
+ this.context.warn(errorCannotCallNamespace(name), this.start);
11483
11513
  }
11484
11514
  }
11485
11515
  }
@@ -11626,12 +11656,7 @@ class ExportDefaultVariable extends LocalVariable {
11626
11656
  }
11627
11657
  getBaseVariableName() {
11628
11658
  const original = this.getOriginalVariable();
11629
- if (original === this) {
11630
- return super.getBaseVariableName();
11631
- }
11632
- else {
11633
- return original.getBaseVariableName();
11634
- }
11659
+ return original === this ? super.getBaseVariableName() : original.getBaseVariableName();
11635
11660
  }
11636
11661
  getDirectOriginalVariable() {
11637
11662
  return this.originalId &&
@@ -11646,12 +11671,9 @@ class ExportDefaultVariable extends LocalVariable {
11646
11671
  }
11647
11672
  getName(getPropertyAccess) {
11648
11673
  const original = this.getOriginalVariable();
11649
- if (original === this) {
11650
- return super.getName(getPropertyAccess);
11651
- }
11652
- else {
11653
- return original.getName(getPropertyAccess);
11654
- }
11674
+ return original === this
11675
+ ? super.getName(getPropertyAccess)
11676
+ : original.getName(getPropertyAccess);
11655
11677
  }
11656
11678
  getOriginalVariable() {
11657
11679
  if (this.originalVariable)
@@ -11729,7 +11751,7 @@ class ThisExpression extends NodeBase {
11729
11751
  this.alias =
11730
11752
  this.scope.findLexicalBoundary() instanceof ModuleScope ? this.context.moduleContext : null;
11731
11753
  if (this.alias === 'undefined') {
11732
- this.context.warn(errThisIsUndefined(), this.start);
11754
+ this.context.warn(errorThisIsUndefined(), this.start);
11733
11755
  }
11734
11756
  }
11735
11757
  render(code) {
@@ -11773,19 +11795,19 @@ class TryStatement extends NodeBase {
11773
11795
  include(context, includeChildrenRecursively) {
11774
11796
  const tryCatchDeoptimization = this.context.options.treeshake
11775
11797
  ?.tryCatchDeoptimization;
11776
- const { brokenFlow } = context;
11798
+ const { brokenFlow, includedLabels } = context;
11777
11799
  if (!this.directlyIncluded || !tryCatchDeoptimization) {
11778
11800
  this.included = true;
11779
11801
  this.directlyIncluded = true;
11780
11802
  this.block.include(context, tryCatchDeoptimization ? INCLUDE_PARAMETERS : includeChildrenRecursively);
11781
- if (context.includedLabels.size > 0) {
11782
- this.includedLabelsAfterBlock = [...context.includedLabels];
11803
+ if (includedLabels.size > 0) {
11804
+ this.includedLabelsAfterBlock = [...includedLabels];
11783
11805
  }
11784
11806
  context.brokenFlow = brokenFlow;
11785
11807
  }
11786
11808
  else if (this.includedLabelsAfterBlock) {
11787
11809
  for (const label of this.includedLabelsAfterBlock) {
11788
- context.includedLabels.add(label);
11810
+ includedLabels.add(label);
11789
11811
  }
11790
11812
  }
11791
11813
  if (this.handler !== null) {
@@ -12120,13 +12142,14 @@ class WhileStatement extends NodeBase {
12120
12142
  hasEffects(context) {
12121
12143
  if (this.test.hasEffects(context))
12122
12144
  return true;
12123
- const { brokenFlow, ignore: { breaks, continues } } = context;
12124
- context.ignore.breaks = true;
12125
- context.ignore.continues = true;
12145
+ const { brokenFlow, ignore } = context;
12146
+ const { breaks, continues } = ignore;
12147
+ ignore.breaks = true;
12148
+ ignore.continues = true;
12126
12149
  if (this.body.hasEffects(context))
12127
12150
  return true;
12128
- context.ignore.breaks = breaks;
12129
- context.ignore.continues = continues;
12151
+ ignore.breaks = breaks;
12152
+ ignore.continues = continues;
12130
12153
  context.brokenFlow = brokenFlow;
12131
12154
  return false;
12132
12155
  }
@@ -12265,7 +12288,7 @@ class NamespaceVariable extends Variable {
12265
12288
  return this.memberVariables;
12266
12289
  }
12267
12290
  const memberVariables = Object.create(null);
12268
- for (const name of this.context.getExports().concat(this.context.getReexports())) {
12291
+ for (const name of [...this.context.getExports(), ...this.context.getReexports()]) {
12269
12292
  if (name[0] !== '*' && name !== this.module.info.syntheticNamedExports) {
12270
12293
  const exportedVariable = this.context.traceExport(name);
12271
12294
  if (exportedVariable) {
@@ -12302,8 +12325,8 @@ class NamespaceVariable extends Variable {
12302
12325
  members.unshift([null, `__proto__:${_}null`]);
12303
12326
  let output = getObject(members, { lineBreakIndent: { base: '', t } });
12304
12327
  if (this.mergedNamespaces.length > 0) {
12305
- const assignmentArgs = this.mergedNamespaces.map(variable => variable.getName(getPropertyAccess));
12306
- output = `/*#__PURE__*/${MERGE_NAMESPACES_VARIABLE}(${output},${_}[${assignmentArgs.join(`,${_}`)}])`;
12328
+ const assignmentArguments = this.mergedNamespaces.map(variable => variable.getName(getPropertyAccess));
12329
+ output = `/*#__PURE__*/${MERGE_NAMESPACES_VARIABLE}(${output},${_}[${assignmentArguments.join(`,${_}`)}])`;
12307
12330
  }
12308
12331
  else {
12309
12332
  // The helper to merge namespaces will also take care of freezing and toStringTag
@@ -12451,14 +12474,18 @@ const NOOP = () => { };
12451
12474
  let timers = new Map();
12452
12475
  function getPersistedLabel(label, level) {
12453
12476
  switch (level) {
12454
- case 1:
12477
+ case 1: {
12455
12478
  return `# ${label}`;
12456
- case 2:
12479
+ }
12480
+ case 2: {
12457
12481
  return `## ${label}`;
12458
- case 3:
12482
+ }
12483
+ case 3: {
12459
12484
  return label;
12460
- default:
12485
+ }
12486
+ default: {
12461
12487
  return `${' '.repeat(level - 4)}- ${label}`;
12488
+ }
12462
12489
  }
12463
12490
  }
12464
12491
  function timeStartImpl(label, level = 3) {
@@ -12527,10 +12554,10 @@ function getPluginWithTimers(plugin, index) {
12527
12554
  timerLabel += ` (${plugin.name})`;
12528
12555
  }
12529
12556
  timerLabel += ` - ${hook}`;
12530
- const func = plugin[hook];
12531
- plugin[hook] = function (...args) {
12557
+ const hookFunction = plugin[hook];
12558
+ plugin[hook] = function (...parameters) {
12532
12559
  timeStart(timerLabel, 4);
12533
- const result = func.apply(this, args);
12560
+ const result = hookFunction.apply(this, parameters);
12534
12561
  timeEnd(timerLabel, 4);
12535
12562
  return result;
12536
12563
  };
@@ -12577,7 +12604,7 @@ function getVariableForExportNameRecursive(target, name, importerForSideEffects,
12577
12604
  const searchedModules = searchedNamesAndModules.get(name);
12578
12605
  if (searchedModules) {
12579
12606
  if (searchedModules.has(target)) {
12580
- return isExportAllSearch ? [null] : error(errCircularReexport(name, target.id));
12607
+ return isExportAllSearch ? [null] : error(errorCircularReexport(name, target.id));
12581
12608
  }
12582
12609
  searchedModules.add(target);
12583
12610
  }
@@ -12693,17 +12720,21 @@ class Module {
12693
12720
  },
12694
12721
  id,
12695
12722
  get implicitlyLoadedAfterOneOf() {
12723
+ // eslint-disable-next-line unicorn/prefer-spread
12696
12724
  return Array.from(implicitlyLoadedAfter, getId).sort();
12697
12725
  },
12698
12726
  get implicitlyLoadedBefore() {
12727
+ // eslint-disable-next-line unicorn/prefer-spread
12699
12728
  return Array.from(implicitlyLoadedBefore, getId).sort();
12700
12729
  },
12701
12730
  get importedIdResolutions() {
12731
+ // eslint-disable-next-line unicorn/prefer-spread
12702
12732
  return Array.from(sourcesWithAssertions.keys(), source => module.resolvedIds[source]).filter(Boolean);
12703
12733
  },
12704
12734
  get importedIds() {
12705
12735
  // We cannot use this.dependencies because this is needed before
12706
12736
  // dependencies are populated
12737
+ // eslint-disable-next-line unicorn/prefer-spread
12707
12738
  return Array.from(sourcesWithAssertions.keys(), source => module.resolvedIds[source]?.id).filter(Boolean);
12708
12739
  },
12709
12740
  get importers() {
@@ -12722,21 +12753,22 @@ class Module {
12722
12753
  syntheticNamedExports
12723
12754
  };
12724
12755
  // Hide the deprecated key so that it only warns when accessed explicitly
12756
+ // eslint-disable-next-line unicorn/consistent-destructuring
12725
12757
  Object.defineProperty(this.info, 'hasModuleSideEffects', {
12726
12758
  enumerable: false
12727
12759
  });
12728
12760
  }
12729
12761
  basename() {
12730
12762
  const base = basename(this.id);
12731
- const ext = extname(this.id);
12732
- return makeLegal(ext ? base.slice(0, -ext.length) : base);
12763
+ const extension = extname(this.id);
12764
+ return makeLegal(extension ? base.slice(0, -extension.length) : base);
12733
12765
  }
12734
12766
  bindReferences() {
12735
12767
  this.ast.bind();
12736
12768
  }
12737
- error(props, pos) {
12738
- this.addLocationToLogProps(props, pos);
12739
- return error(props);
12769
+ error(properties, pos) {
12770
+ this.addLocationToLogProps(properties, pos);
12771
+ return error(properties);
12740
12772
  }
12741
12773
  getAllExportNames() {
12742
12774
  if (this.allExportNames) {
@@ -12831,7 +12863,7 @@ class Module {
12831
12863
  return (this.exportNamesByVariable = exportNamesByVariable);
12832
12864
  }
12833
12865
  getExports() {
12834
- return Array.from(this.exports.keys());
12866
+ return [...this.exports.keys()];
12835
12867
  }
12836
12868
  getReexports() {
12837
12869
  if (this.transitiveReexports) {
@@ -12871,7 +12903,7 @@ class Module {
12871
12903
  : 'default', { onlyExplicit: true });
12872
12904
  }
12873
12905
  if (!this.syntheticNamespace) {
12874
- return error(errSyntheticNamedExportsNeedNamespaceExport(this.id, this.info.syntheticNamedExports));
12906
+ return error(errorSyntheticNamedExportsNeedNamespaceExport(this.id, this.info.syntheticNamedExports));
12875
12907
  }
12876
12908
  return this.syntheticNamespace;
12877
12909
  }
@@ -12890,7 +12922,7 @@ class Module {
12890
12922
  if (reexportDeclaration) {
12891
12923
  const [variable] = getVariableForExportNameRecursive(reexportDeclaration.module, reexportDeclaration.localName, importerForSideEffects, false, searchedNamesAndModules);
12892
12924
  if (!variable) {
12893
- return this.error(errMissingExport(reexportDeclaration.localName, this.id, reexportDeclaration.module.id), reexportDeclaration.start);
12925
+ return this.error(errorMissingExport(reexportDeclaration.localName, this.id, reexportDeclaration.module.id), reexportDeclaration.start);
12894
12926
  }
12895
12927
  if (importerForSideEffects) {
12896
12928
  setAlternativeExporterIfCyclic(variable, importerForSideEffects, this);
@@ -12931,11 +12963,9 @@ class Module {
12931
12963
  }
12932
12964
  // we don't want to create shims when we are just
12933
12965
  // probing export * modules for exports
12934
- if (!isExportAllSearch) {
12935
- if (this.options.shimMissingExports) {
12936
- this.shimMissingExport(name);
12937
- return [this.exportShimVariable];
12938
- }
12966
+ if (!isExportAllSearch && this.options.shimMissingExports) {
12967
+ this.shimMissingExport(name);
12968
+ return [this.exportShimVariable];
12939
12969
  }
12940
12970
  return [null];
12941
12971
  }
@@ -13005,7 +13035,7 @@ class Module {
13005
13035
  source.trim();
13006
13036
  const { usesTopLevelAwait } = this.astContext;
13007
13037
  if (usesTopLevelAwait && options.format !== 'es' && options.format !== 'system') {
13008
- return error(errInvalidFormatForTopLevelAwait(this.id, options.format));
13038
+ return error(errorInvalidFormatForTopLevelAwait(this.id, options.format));
13009
13039
  }
13010
13040
  return { source, usesTopLevelAwait };
13011
13041
  }
@@ -13074,6 +13104,7 @@ class Module {
13074
13104
  ast: this.ast.esTreeNode,
13075
13105
  code: this.info.code,
13076
13106
  customTransformCache: this.customTransformCache,
13107
+ // eslint-disable-next-line unicorn/prefer-spread
13077
13108
  dependencies: Array.from(this.dependencies, getId),
13078
13109
  id: this.id,
13079
13110
  meta: this.info.meta,
@@ -13100,7 +13131,7 @@ class Module {
13100
13131
  }
13101
13132
  const [declaration] = getVariableForExportNameRecursive(otherModule, importDeclaration.name, importerForSideEffects || this, isExportAllSearch, searchedNamesAndModules);
13102
13133
  if (!declaration) {
13103
- return this.error(errMissingExport(importDeclaration.name, this.id, otherModule.id), importDeclaration.start);
13134
+ return this.error(errorMissingExport(importDeclaration.name, this.id, otherModule.id), importDeclaration.start);
13104
13135
  }
13105
13136
  return declaration;
13106
13137
  }
@@ -13110,8 +13141,8 @@ class Module {
13110
13141
  try {
13111
13142
  return this.graph.contextParse(this.info.code);
13112
13143
  }
13113
- catch (err) {
13114
- return this.error(errParseError(err, this.id), err.pos);
13144
+ catch (error_) {
13145
+ return this.error(errorParseError(error_, this.id), error_.pos);
13115
13146
  }
13116
13147
  }
13117
13148
  updateOptions({ meta, moduleSideEffects, syntheticNamedExports }) {
@@ -13125,9 +13156,9 @@ class Module {
13125
13156
  Object.assign(this.info.meta, meta);
13126
13157
  }
13127
13158
  }
13128
- warn(props, pos) {
13129
- this.addLocationToLogProps(props, pos);
13130
- this.options.onwarn(props);
13159
+ warn(properties, pos) {
13160
+ this.addLocationToLogProps(properties, pos);
13161
+ this.options.onwarn(properties);
13131
13162
  }
13132
13163
  addDynamicImport(node) {
13133
13164
  let argument = node.source;
@@ -13225,9 +13256,9 @@ class Module {
13225
13256
  addImportMeta(node) {
13226
13257
  this.importMetas.push(node);
13227
13258
  }
13228
- addLocationToLogProps(props, pos) {
13229
- props.id = this.id;
13230
- props.pos = pos;
13259
+ addLocationToLogProps(properties, pos) {
13260
+ properties.id = this.id;
13261
+ properties.pos = pos;
13231
13262
  let code = this.info.code;
13232
13263
  const location = locate(code, pos, { offsetLine: 1 });
13233
13264
  if (location) {
@@ -13236,10 +13267,10 @@ class Module {
13236
13267
  ({ column, line } = getOriginalLocation(this.sourcemapChain, { column, line }));
13237
13268
  code = this.originalCode;
13238
13269
  }
13239
- catch (err) {
13240
- this.options.onwarn(errInvalidSourcemapForError(err, this.id, column, line, pos));
13270
+ catch (error_) {
13271
+ this.options.onwarn(errorInvalidSourcemapForError(error_, this.id, column, line, pos));
13241
13272
  }
13242
- augmentCodeLocation(props, { column, line }, code, this.id);
13273
+ augmentCodeLocation(properties, { column, line }, code, this.id);
13243
13274
  }
13244
13275
  }
13245
13276
  addModulesToImportDescriptions(importDescription) {
@@ -13278,7 +13309,7 @@ class Module {
13278
13309
  const existingAssertions = this.sourcesWithAssertions.get(source);
13279
13310
  if (existingAssertions) {
13280
13311
  if (doAssertionsDiffer(existingAssertions, parsedAssertions)) {
13281
- this.warn(errInconsistentImportAssertions(existingAssertions, parsedAssertions, source, this.id), declaration.start);
13312
+ this.warn(errorInconsistentImportAssertions(existingAssertions, parsedAssertions, source, this.id), declaration.start);
13282
13313
  }
13283
13314
  }
13284
13315
  else {
@@ -13316,7 +13347,7 @@ class Module {
13316
13347
  if (foundDeclarationList.length === 1) {
13317
13348
  return [usedDeclaration];
13318
13349
  }
13319
- this.options.onwarn(errNamespaceConflict(name, this.id, foundDeclarationList.map(([, module]) => module.id)));
13350
+ this.options.onwarn(errorNamespaceConflict(name, this.id, foundDeclarationList.map(([, module]) => module.id)));
13320
13351
  // TODO we are pretending it was not found while it should behave like "undefined"
13321
13352
  return [null];
13322
13353
  }
@@ -13324,7 +13355,7 @@ class Module {
13324
13355
  const foundDeclarationList = [...foundExternalDeclarations];
13325
13356
  const usedDeclaration = foundDeclarationList[0];
13326
13357
  if (foundDeclarationList.length > 1) {
13327
- this.options.onwarn(errAmbiguousExternalNamespaces(name, this.id, usedDeclaration.module.id, foundDeclarationList.map(declaration => declaration.module.id)));
13358
+ this.options.onwarn(errorAmbiguousExternalNamespaces(name, this.id, usedDeclaration.module.id, foundDeclarationList.map(declaration => declaration.module.id)));
13328
13359
  }
13329
13360
  return [usedDeclaration, true];
13330
13361
  }
@@ -13387,7 +13418,7 @@ class Module {
13387
13418
  }
13388
13419
  }
13389
13420
  shimMissingExport(name) {
13390
- this.options.onwarn(errShimmedExport(this.id, name));
13421
+ this.options.onwarn(errorShimmedExport(this.id, name));
13391
13422
  this.exports.set(name, MISSING_EXPORT_SHIM_DESCRIPTION);
13392
13423
  }
13393
13424
  }
@@ -13409,6 +13440,7 @@ function setAlternativeExporterIfCyclic(variable, importer, reexporter) {
13409
13440
  }
13410
13441
  }
13411
13442
  const copyNameToModulesMap = (searchedNamesAndModules) => searchedNamesAndModules &&
13443
+ // eslint-disable-next-line unicorn/prefer-spread
13412
13444
  new Map(Array.from(searchedNamesAndModules, ([name, modules]) => [name, new Set(modules)]));
13413
13445
 
13414
13446
  function removeJsExtension(name) {
@@ -13598,12 +13630,10 @@ function getInteropBlock(dependencies, interop, externalLiveBindings, freeze, na
13598
13630
  }
13599
13631
  }
13600
13632
  }
13601
- else if (imported === '*' && reexported !== '*') {
13602
- if (!hasNamespace) {
13603
- hasNamespace = true;
13604
- helper = namespaceInteropHelpersByInteropType[moduleInterop];
13605
- variableName = namespaceVariableName;
13606
- }
13633
+ else if (imported === '*' && reexported !== '*' && !hasNamespace) {
13634
+ hasNamespace = true;
13635
+ helper = namespaceInteropHelpersByInteropType[moduleInterop];
13636
+ variableName = namespaceVariableName;
13607
13637
  }
13608
13638
  if (helper) {
13609
13639
  addInteropStatement(variableName, helper, name);
@@ -13655,31 +13685,31 @@ function warnOnBuiltins(warn, dependencies) {
13655
13685
  const externalBuiltins = dependencies
13656
13686
  .map(({ importPath }) => importPath)
13657
13687
  .filter(importPath => importPath in builtins || importPath.startsWith('node:'));
13658
- if (!externalBuiltins.length)
13688
+ if (externalBuiltins.length === 0)
13659
13689
  return;
13660
- warn(errMissingNodeBuiltins(externalBuiltins));
13690
+ warn(errorMissingNodeBuiltins(externalBuiltins));
13661
13691
  }
13662
13692
 
13663
13693
  function amd(magicString, { accessedGlobals, dependencies, exports, hasDefaultExport, hasExports, id, indent: t, intro, isEntryFacade, isModuleFacade, namedExportsMode, outro, snippets, onwarn }, { amd, esModule, externalLiveBindings, freeze, interop, namespaceToStringTag, strict }) {
13664
13694
  warnOnBuiltins(onwarn, dependencies);
13665
13695
  const deps = dependencies.map(m => `'${updateExtensionForRelativeAmdId(m.importPath, amd.forceJsExtensionForImports)}'`);
13666
- const args = dependencies.map(m => m.name);
13696
+ const parameters = dependencies.map(m => m.name);
13667
13697
  const { n, getNonArrowFunctionIntro, _ } = snippets;
13668
13698
  if (namedExportsMode && hasExports) {
13669
- args.unshift(`exports`);
13699
+ parameters.unshift(`exports`);
13670
13700
  deps.unshift(`'exports'`);
13671
13701
  }
13672
13702
  if (accessedGlobals.has('require')) {
13673
- args.unshift('require');
13703
+ parameters.unshift('require');
13674
13704
  deps.unshift(`'require'`);
13675
13705
  }
13676
13706
  if (accessedGlobals.has('module')) {
13677
- args.unshift('module');
13707
+ parameters.unshift('module');
13678
13708
  deps.unshift(`'module'`);
13679
13709
  }
13680
13710
  const completeAmdId = getCompleteAmdId(amd, id);
13681
- const params = (completeAmdId ? `'${completeAmdId}',${_}` : ``) +
13682
- (deps.length ? `[${deps.join(`,${_}`)}],${_}` : ``);
13711
+ const defineParameters = (completeAmdId ? `'${completeAmdId}',${_}` : ``) +
13712
+ (deps.length > 0 ? `[${deps.join(`,${_}`)}],${_}` : ``);
13683
13713
  const useStrict = strict ? `${_}'use strict';` : '';
13684
13714
  magicString.prepend(`${intro}${getInteropBlock(dependencies, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, t, snippets)}`);
13685
13715
  const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings);
@@ -13692,7 +13722,7 @@ function amd(magicString, { accessedGlobals, dependencies, exports, hasDefaultEx
13692
13722
  .indent(t)
13693
13723
  // factory function should be wrapped by parentheses to avoid lazy parsing,
13694
13724
  // cf. https://v8.dev/blog/preparser#pife
13695
- .prepend(`${amd.define}(${params}(${getNonArrowFunctionIntro(args, {
13725
+ .prepend(`${amd.define}(${defineParameters}(${getNonArrowFunctionIntro(parameters, {
13696
13726
  isAsync: false,
13697
13727
  name: null
13698
13728
  })}{${useStrict}${n}${n}`)
@@ -13744,7 +13774,7 @@ function es(magicString, { accessedGlobals, indent: t, intro, outro, dependencie
13744
13774
  if (intro)
13745
13775
  magicString.prepend(intro);
13746
13776
  const exportBlock = getExportBlock(exports, snippets);
13747
- if (exportBlock.length)
13777
+ if (exportBlock.length > 0)
13748
13778
  magicString.append(n + n + exportBlock.join(n).trim());
13749
13779
  if (outro)
13750
13780
  magicString.append(outro);
@@ -13783,12 +13813,9 @@ function getImportBlock(dependencies, { _ }) {
13783
13813
  else if (importedNames.length > 0) {
13784
13814
  importBlock.push(`import ${defaultImport ? `${defaultImport.local},${_}` : ''}{${_}${importedNames
13785
13815
  .map(specifier => {
13786
- if (specifier.imported === specifier.local) {
13787
- return specifier.imported;
13788
- }
13789
- else {
13790
- return `${specifier.imported} as ${specifier.local}`;
13791
- }
13816
+ return specifier.imported === specifier.local
13817
+ ? specifier.imported
13818
+ : `${specifier.imported} as ${specifier.local}`;
13792
13819
  })
13793
13820
  .join(`,${_}`)}${_}}${_}from${_}${pathWithAssertion}`);
13794
13821
  }
@@ -13823,12 +13850,9 @@ function getImportBlock(dependencies, { _ }) {
13823
13850
  if (namedReexports.length > 0) {
13824
13851
  importBlock.push(`export${_}{${_}${namedReexports
13825
13852
  .map(specifier => {
13826
- if (specifier.imported === specifier.reexported) {
13827
- return specifier.imported;
13828
- }
13829
- else {
13830
- return `${specifier.imported} as ${specifier.reexported}`;
13831
- }
13853
+ return specifier.imported === specifier.reexported
13854
+ ? specifier.imported
13855
+ : `${specifier.imported} as ${specifier.reexported}`;
13832
13856
  })
13833
13857
  .join(`,${_}`)}${_}}${_}from${_}${pathWithAssertion}`);
13834
13858
  }
@@ -13847,7 +13871,7 @@ function getExportBlock(exports, { _, cnst }) {
13847
13871
  ? specifier.local
13848
13872
  : `${specifier.local} as ${specifier.exported}`);
13849
13873
  }
13850
- if (exportDeclaration.length) {
13874
+ if (exportDeclaration.length > 0) {
13851
13875
  exportBlock.push(`export${_}{${_}${exportDeclaration.join(`,${_}`)}${_}};`);
13852
13876
  }
13853
13877
  return exportBlock;
@@ -13865,20 +13889,20 @@ function setupNamespace(name, root, globals, { _, getPropertyAccess, s }, compac
13865
13889
  propertyPath += getPropertyAccess(part);
13866
13890
  return `${propertyPath}${_}=${_}${propertyPath}${_}||${_}{}${s}`;
13867
13891
  })
13868
- .join(compact ? ',' : '\n') + (compact && parts.length ? ';' : '\n'));
13892
+ .join(compact ? ',' : '\n') + (compact && parts.length > 0 ? ';' : '\n'));
13869
13893
  }
13870
13894
  function assignToDeepVariable(deepName, root, globals, assignment, { _, getPropertyAccess }) {
13871
13895
  const parts = deepName.split('.');
13872
13896
  parts[0] = (typeof globals === 'function' ? globals(parts[0]) : globals[parts[0]]) || parts[0];
13873
13897
  const last = parts.pop();
13874
13898
  let propertyPath = root;
13875
- let deepAssignment = parts
13876
- .map(part => {
13877
- propertyPath += getPropertyAccess(part);
13878
- return `${propertyPath}${_}=${_}${propertyPath}${_}||${_}{}`;
13879
- })
13880
- .concat(`${propertyPath}${getPropertyAccess(last)}`)
13881
- .join(`,${_}`) + `${_}=${_}${assignment}`;
13899
+ let deepAssignment = [
13900
+ ...parts.map(part => {
13901
+ propertyPath += getPropertyAccess(part);
13902
+ return `${propertyPath}${_}=${_}${propertyPath}${_}||${_}{}`;
13903
+ }),
13904
+ `${propertyPath}${getPropertyAccess(last)}`
13905
+ ].join(`,${_}`) + `${_}=${_}${assignment}`;
13882
13906
  if (parts.length > 0) {
13883
13907
  deepAssignment = `(${deepAssignment})`;
13884
13908
  }
@@ -13886,11 +13910,11 @@ function assignToDeepVariable(deepName, root, globals, assignment, { _, getPrope
13886
13910
  }
13887
13911
 
13888
13912
  function trimEmptyImports(dependencies) {
13889
- let i = dependencies.length;
13890
- while (i--) {
13891
- const { imports, reexports } = dependencies[i];
13913
+ let index = dependencies.length;
13914
+ while (index--) {
13915
+ const { imports, reexports } = dependencies[index];
13892
13916
  if (imports || reexports) {
13893
- return dependencies.slice(0, i + 1);
13917
+ return dependencies.slice(0, index + 1);
13894
13918
  }
13895
13919
  }
13896
13920
  return [];
@@ -13901,29 +13925,29 @@ function iife(magicString, { accessedGlobals, dependencies, exports, hasDefaultE
13901
13925
  const isNamespaced = name && name.includes('.');
13902
13926
  const useVariableAssignment = !extend && !isNamespaced;
13903
13927
  if (name && useVariableAssignment && !isLegal(name)) {
13904
- return error(errIllegalIdentifierAsName(name));
13928
+ return error(errorIllegalIdentifierAsName(name));
13905
13929
  }
13906
13930
  warnOnBuiltins(onwarn, dependencies);
13907
13931
  const external = trimEmptyImports(dependencies);
13908
13932
  const deps = external.map(dep => dep.globalName || 'null');
13909
- const args = external.map(m => m.name);
13933
+ const parameters = external.map(m => m.name);
13910
13934
  if (hasExports && !name) {
13911
- onwarn(errMissingNameOptionForIifeExport());
13935
+ onwarn(errorMissingNameOptionForIifeExport());
13912
13936
  }
13913
13937
  if (namedExportsMode && hasExports) {
13914
13938
  if (extend) {
13915
13939
  deps.unshift(`this${keypath(name, getPropertyAccess)}${_}=${_}this${keypath(name, getPropertyAccess)}${_}||${_}{}`);
13916
- args.unshift('exports');
13940
+ parameters.unshift('exports');
13917
13941
  }
13918
13942
  else {
13919
13943
  deps.unshift('{}');
13920
- args.unshift('exports');
13944
+ parameters.unshift('exports');
13921
13945
  }
13922
13946
  }
13923
13947
  const useStrict = strict ? `${t}'use strict';${n}` : '';
13924
13948
  const interopBlock = getInteropBlock(dependencies, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, t, snippets);
13925
13949
  magicString.prepend(`${intro}${interopBlock}`);
13926
- let wrapperIntro = `(${getNonArrowFunctionIntro(args, {
13950
+ let wrapperIntro = `(${getNonArrowFunctionIntro(parameters, {
13927
13951
  isAsync: false,
13928
13952
  name: null
13929
13953
  })}{${n}${useStrict}${n}`;
@@ -13957,7 +13981,7 @@ function system(magicString, { accessedGlobals, dependencies, exports, hasExport
13957
13981
  const { _, getFunctionIntro, getNonArrowFunctionIntro, n, s } = snippets;
13958
13982
  const { importBindings, setters, starExcludes } = analyzeDependencies(dependencies, exports, t, snippets);
13959
13983
  const registeredName = name ? `'${name}',${_}` : '';
13960
- const wrapperParams = accessedGlobals.has('module')
13984
+ const wrapperParameters = accessedGlobals.has('module')
13961
13985
  ? ['exports', 'module']
13962
13986
  : hasExports
13963
13987
  ? ['exports']
@@ -13966,10 +13990,13 @@ function system(magicString, { accessedGlobals, dependencies, exports, hasExport
13966
13990
  // cf. https://v8.dev/blog/preparser#pife
13967
13991
  let wrapperStart = `System.register(${registeredName}[` +
13968
13992
  dependencies.map(({ importPath }) => `'${importPath}'`).join(`,${_}`) +
13969
- `],${_}(${getNonArrowFunctionIntro(wrapperParams, { isAsync: false, name: null })}{${n}${t}${strict ? "'use strict';" : ''}` +
13993
+ `],${_}(${getNonArrowFunctionIntro(wrapperParameters, {
13994
+ isAsync: false,
13995
+ name: null
13996
+ })}{${n}${t}${strict ? "'use strict';" : ''}` +
13970
13997
  getStarExcludesBlock(starExcludes, t, snippets) +
13971
13998
  getImportBindingsBlock(importBindings, t, snippets) +
13972
- `${n}${t}return${_}{${setters.length
13999
+ `${n}${t}return${_}{${setters.length > 0
13973
14000
  ? `${n}${t}${t}setters:${_}[${setters
13974
14001
  .map(setter => setter
13975
14002
  ? `${getFunctionIntro(['module'], {
@@ -14063,9 +14090,9 @@ const getStarExcludes = ({ dependencies, exports }) => {
14063
14090
  return starExcludes;
14064
14091
  };
14065
14092
  const getStarExcludesBlock = (starExcludes, t, { _, cnst, getObject, n }) => starExcludes
14066
- ? `${n}${t}${cnst} _starExcludes${_}=${_}${getObject([...starExcludes].map(prop => [prop, '1']), { lineBreakIndent: { base: t, t } })};`
14093
+ ? `${n}${t}${cnst} _starExcludes${_}=${_}${getObject([...starExcludes].map(property => [property, '1']), { lineBreakIndent: { base: t, t } })};`
14067
14094
  : '';
14068
- const getImportBindingsBlock = (importBindings, t, { _, n }) => (importBindings.length ? `${n}${t}var ${importBindings.join(`,${_}`)};` : '');
14095
+ const getImportBindingsBlock = (importBindings, t, { _, n }) => (importBindings.length > 0 ? `${n}${t}var ${importBindings.join(`,${_}`)};` : '');
14069
14096
  const getHoistedExportsBlock = (exports, t, snippets) => getExportsBlock(exports.filter(expt => expt.hoisted).map(expt => ({ name: expt.exported, value: expt.local })), t, snippets);
14070
14097
  function getExportsBlock(exports, t, { _, n }) {
14071
14098
  if (exports.length === 0) {
@@ -14085,13 +14112,13 @@ const getMissingExportsBlock = (exports, t, snippets) => getExportsBlock(exports
14085
14112
  .filter(expt => expt.local === MISSING_EXPORT_SHIM_VARIABLE)
14086
14113
  .map(expt => ({ name: expt.exported, value: MISSING_EXPORT_SHIM_VARIABLE })), t, snippets);
14087
14114
 
14088
- function globalProp(name, globalVar, getPropertyAccess) {
14115
+ function globalProperty(name, globalVariable, getPropertyAccess) {
14089
14116
  if (!name)
14090
14117
  return 'null';
14091
- return `${globalVar}${keypath(name, getPropertyAccess)}`;
14118
+ return `${globalVariable}${keypath(name, getPropertyAccess)}`;
14092
14119
  }
14093
- function safeAccess(name, globalVar, { _, getPropertyAccess }) {
14094
- let propertyPath = globalVar;
14120
+ function safeAccess(name, globalVariable, { _, getPropertyAccess }) {
14121
+ let propertyPath = globalVariable;
14095
14122
  return name
14096
14123
  .split('.')
14097
14124
  .map(part => (propertyPath += getPropertyAccess(part)))
@@ -14099,80 +14126,80 @@ function safeAccess(name, globalVar, { _, getPropertyAccess }) {
14099
14126
  }
14100
14127
  function umd(magicString, { accessedGlobals, dependencies, exports, hasDefaultExport, hasExports, id, indent: t, intro, namedExportsMode, outro, snippets, onwarn }, { amd, compact, esModule, extend, externalLiveBindings, freeze, interop, name, namespaceToStringTag, globals, noConflict, strict }) {
14101
14128
  const { _, cnst, getFunctionIntro, getNonArrowFunctionIntro, getPropertyAccess, n, s } = snippets;
14102
- const factoryVar = compact ? 'f' : 'factory';
14103
- const globalVar = compact ? 'g' : 'global';
14129
+ const factoryVariable = compact ? 'f' : 'factory';
14130
+ const globalVariable = compact ? 'g' : 'global';
14104
14131
  if (hasExports && !name) {
14105
- return error(errMissingNameOptionForUmdExport());
14132
+ return error(errorMissingNameOptionForUmdExport());
14106
14133
  }
14107
14134
  warnOnBuiltins(onwarn, dependencies);
14108
14135
  const amdDeps = dependencies.map(m => `'${updateExtensionForRelativeAmdId(m.importPath, amd.forceJsExtensionForImports)}'`);
14109
14136
  const cjsDeps = dependencies.map(m => `require('${m.importPath}')`);
14110
14137
  const trimmedImports = trimEmptyImports(dependencies);
14111
- const globalDeps = trimmedImports.map(module => globalProp(module.globalName, globalVar, getPropertyAccess));
14112
- const factoryParams = trimmedImports.map(m => m.name);
14138
+ const globalDeps = trimmedImports.map(module => globalProperty(module.globalName, globalVariable, getPropertyAccess));
14139
+ const factoryParameters = trimmedImports.map(m => m.name);
14113
14140
  if (namedExportsMode && (hasExports || noConflict)) {
14114
14141
  amdDeps.unshift(`'exports'`);
14115
14142
  cjsDeps.unshift(`exports`);
14116
- globalDeps.unshift(assignToDeepVariable(name, globalVar, globals, `${extend ? `${globalProp(name, globalVar, getPropertyAccess)}${_}||${_}` : ''}{}`, snippets));
14117
- factoryParams.unshift('exports');
14143
+ globalDeps.unshift(assignToDeepVariable(name, globalVariable, globals, `${extend ? `${globalProperty(name, globalVariable, getPropertyAccess)}${_}||${_}` : ''}{}`, snippets));
14144
+ factoryParameters.unshift('exports');
14118
14145
  }
14119
14146
  const completeAmdId = getCompleteAmdId(amd, id);
14120
- const amdParams = (completeAmdId ? `'${completeAmdId}',${_}` : ``) +
14121
- (amdDeps.length ? `[${amdDeps.join(`,${_}`)}],${_}` : ``);
14147
+ const amdParameters = (completeAmdId ? `'${completeAmdId}',${_}` : ``) +
14148
+ (amdDeps.length > 0 ? `[${amdDeps.join(`,${_}`)}],${_}` : ``);
14122
14149
  const define = amd.define;
14123
14150
  const cjsExport = !namedExportsMode && hasExports ? `module.exports${_}=${_}` : ``;
14124
14151
  const useStrict = strict ? `${_}'use strict';${n}` : ``;
14125
14152
  let iifeExport;
14126
14153
  if (noConflict) {
14127
- const noConflictExportsVar = compact ? 'e' : 'exports';
14154
+ const noConflictExportsVariable = compact ? 'e' : 'exports';
14128
14155
  let factory;
14129
14156
  if (!namedExportsMode && hasExports) {
14130
- factory = `${cnst} ${noConflictExportsVar}${_}=${_}${assignToDeepVariable(name, globalVar, globals, `${factoryVar}(${globalDeps.join(`,${_}`)})`, snippets)};`;
14157
+ factory = `${cnst} ${noConflictExportsVariable}${_}=${_}${assignToDeepVariable(name, globalVariable, globals, `${factoryVariable}(${globalDeps.join(`,${_}`)})`, snippets)};`;
14131
14158
  }
14132
14159
  else {
14133
14160
  const module = globalDeps.shift();
14134
14161
  factory =
14135
- `${cnst} ${noConflictExportsVar}${_}=${_}${module};${n}` +
14136
- `${t}${t}${factoryVar}(${[noConflictExportsVar].concat(globalDeps).join(`,${_}`)});`;
14162
+ `${cnst} ${noConflictExportsVariable}${_}=${_}${module};${n}` +
14163
+ `${t}${t}${factoryVariable}(${[noConflictExportsVariable, ...globalDeps].join(`,${_}`)});`;
14137
14164
  }
14138
14165
  iifeExport =
14139
14166
  `(${getFunctionIntro([], { isAsync: false, name: null })}{${n}` +
14140
- `${t}${t}${cnst} current${_}=${_}${safeAccess(name, globalVar, snippets)};${n}` +
14167
+ `${t}${t}${cnst} current${_}=${_}${safeAccess(name, globalVariable, snippets)};${n}` +
14141
14168
  `${t}${t}${factory}${n}` +
14142
- `${t}${t}${noConflictExportsVar}.noConflict${_}=${_}${getFunctionIntro([], {
14169
+ `${t}${t}${noConflictExportsVariable}.noConflict${_}=${_}${getFunctionIntro([], {
14143
14170
  isAsync: false,
14144
14171
  name: null
14145
14172
  })}{${_}` +
14146
- `${globalProp(name, globalVar, getPropertyAccess)}${_}=${_}current;${_}return ${noConflictExportsVar}${s}${_}};${n}` +
14173
+ `${globalProperty(name, globalVariable, getPropertyAccess)}${_}=${_}current;${_}return ${noConflictExportsVariable}${s}${_}};${n}` +
14147
14174
  `${t}})()`;
14148
14175
  }
14149
14176
  else {
14150
- iifeExport = `${factoryVar}(${globalDeps.join(`,${_}`)})`;
14177
+ iifeExport = `${factoryVariable}(${globalDeps.join(`,${_}`)})`;
14151
14178
  if (!namedExportsMode && hasExports) {
14152
- iifeExport = assignToDeepVariable(name, globalVar, globals, iifeExport, snippets);
14179
+ iifeExport = assignToDeepVariable(name, globalVariable, globals, iifeExport, snippets);
14153
14180
  }
14154
14181
  }
14155
14182
  const iifeNeedsGlobal = hasExports || (noConflict && namedExportsMode) || globalDeps.length > 0;
14156
- const wrapperParams = [factoryVar];
14183
+ const wrapperParameters = [factoryVariable];
14157
14184
  if (iifeNeedsGlobal) {
14158
- wrapperParams.unshift(globalVar);
14185
+ wrapperParameters.unshift(globalVariable);
14159
14186
  }
14160
- const globalArg = iifeNeedsGlobal ? `this,${_}` : '';
14187
+ const globalArgument = iifeNeedsGlobal ? `this,${_}` : '';
14161
14188
  const iifeStart = iifeNeedsGlobal
14162
- ? `(${globalVar}${_}=${_}typeof globalThis${_}!==${_}'undefined'${_}?${_}globalThis${_}:${_}${globalVar}${_}||${_}self,${_}`
14189
+ ? `(${globalVariable}${_}=${_}typeof globalThis${_}!==${_}'undefined'${_}?${_}globalThis${_}:${_}${globalVariable}${_}||${_}self,${_}`
14163
14190
  : '';
14164
14191
  const iifeEnd = iifeNeedsGlobal ? ')' : '';
14165
14192
  const cjsIntro = iifeNeedsGlobal
14166
14193
  ? `${t}typeof exports${_}===${_}'object'${_}&&${_}typeof module${_}!==${_}'undefined'${_}?` +
14167
- `${_}${cjsExport}${factoryVar}(${cjsDeps.join(`,${_}`)})${_}:${n}`
14194
+ `${_}${cjsExport}${factoryVariable}(${cjsDeps.join(`,${_}`)})${_}:${n}`
14168
14195
  : '';
14169
- const wrapperIntro = `(${getNonArrowFunctionIntro(wrapperParams, { isAsync: false, name: null })}{${n}` +
14196
+ const wrapperIntro = `(${getNonArrowFunctionIntro(wrapperParameters, { isAsync: false, name: null })}{${n}` +
14170
14197
  cjsIntro +
14171
- `${t}typeof ${define}${_}===${_}'function'${_}&&${_}${define}.amd${_}?${_}${define}(${amdParams}${factoryVar})${_}:${n}` +
14198
+ `${t}typeof ${define}${_}===${_}'function'${_}&&${_}${define}.amd${_}?${_}${define}(${amdParameters}${factoryVariable})${_}:${n}` +
14172
14199
  `${t}${iifeStart}${iifeExport}${iifeEnd};${n}` +
14173
14200
  // factory function should be wrapped by parentheses to avoid lazy parsing,
14174
14201
  // cf. https://v8.dev/blog/preparser#pife
14175
- `})(${globalArg}(${getNonArrowFunctionIntro(factoryParams, {
14202
+ `})(${globalArgument}(${getNonArrowFunctionIntro(factoryParameters, {
14176
14203
  isAsync: false,
14177
14204
  name: null
14178
14205
  })}{${useStrict}${n}`;
@@ -14193,15 +14220,15 @@ function umd(magicString, { accessedGlobals, dependencies, exports, hasDefaultEx
14193
14220
 
14194
14221
  const finalisers = { amd, cjs, es, iife, system, umd };
14195
14222
 
14196
- const concatSep = (out, next) => (next ? `${out}\n${next}` : out);
14197
- const concatDblSep = (out, next) => (next ? `${out}\n\n${next}` : out);
14223
+ const concatSeparator = (out, next) => (next ? `${out}\n${next}` : out);
14224
+ const concatDblSeparator = (out, next) => (next ? `${out}\n\n${next}` : out);
14198
14225
  async function createAddons(options, outputPluginDriver, chunk) {
14199
14226
  try {
14200
14227
  let [banner, footer, intro, outro] = await Promise.all([
14201
- outputPluginDriver.hookReduceValue('banner', options.banner(chunk), [chunk], concatSep),
14202
- outputPluginDriver.hookReduceValue('footer', options.footer(chunk), [chunk], concatSep),
14203
- outputPluginDriver.hookReduceValue('intro', options.intro(chunk), [chunk], concatDblSep),
14204
- outputPluginDriver.hookReduceValue('outro', options.outro(chunk), [chunk], concatDblSep)
14228
+ outputPluginDriver.hookReduceValue('banner', options.banner(chunk), [chunk], concatSeparator),
14229
+ outputPluginDriver.hookReduceValue('footer', options.footer(chunk), [chunk], concatSeparator),
14230
+ outputPluginDriver.hookReduceValue('intro', options.intro(chunk), [chunk], concatDblSeparator),
14231
+ outputPluginDriver.hookReduceValue('outro', options.outro(chunk), [chunk], concatDblSeparator)
14205
14232
  ]);
14206
14233
  if (intro)
14207
14234
  intro += '\n\n';
@@ -14213,8 +14240,8 @@ async function createAddons(options, outputPluginDriver, chunk) {
14213
14240
  footer = '\n' + footer;
14214
14241
  return { banner, footer, intro, outro };
14215
14242
  }
14216
- catch (err) {
14217
- return error(errAddonNotGenerated(err.message, err.hook, err.plugin));
14243
+ catch (error_) {
14244
+ return error(errorAddonNotGenerated(error_.message, error_.hook, error_.plugin));
14218
14245
  }
14219
14246
  }
14220
14247
 
@@ -14227,7 +14254,7 @@ const DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT = {
14227
14254
  umd: deconflictImportsOther
14228
14255
  };
14229
14256
  function deconflictChunk(modules, dependenciesToBeDeconflicted, imports, usedNames, format, interop, preserveModules, externalLiveBindings, chunkByModule, externalChunkByModule, syntheticExports, exportNamesByVariable, accessedGlobalsByScope, includedNamespaces) {
14230
- const reversedModules = modules.slice().reverse();
14257
+ const reversedModules = [...modules].reverse();
14231
14258
  for (const module of reversedModules) {
14232
14259
  module.scope.addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope);
14233
14260
  }
@@ -14273,13 +14300,11 @@ function deconflictImportsOther(usedNames, imports, { deconflictedDefault, decon
14273
14300
  chunk.namespaceVariableName = getSafeName(`${chunk.suggestedVariableName}__namespace`, usedNames);
14274
14301
  }
14275
14302
  for (const externalModule of deconflictedDefault) {
14276
- if (deconflictedNamespace.has(externalModule) &&
14277
- canDefaultBeTakenFromNamespace(interop(externalModule.id), externalLiveBindings)) {
14278
- externalModule.defaultVariableName = externalModule.namespaceVariableName;
14279
- }
14280
- else {
14281
- externalModule.defaultVariableName = getSafeName(`${externalModule.suggestedVariableName}__default`, usedNames);
14282
- }
14303
+ externalModule.defaultVariableName =
14304
+ deconflictedNamespace.has(externalModule) &&
14305
+ canDefaultBeTakenFromNamespace(interop(externalModule.id), externalLiveBindings)
14306
+ ? externalModule.namespaceVariableName
14307
+ : getSafeName(`${externalModule.suggestedVariableName}__default`, usedNames);
14283
14308
  }
14284
14309
  for (const variable of imports) {
14285
14310
  const module = variable.module;
@@ -14373,11 +14398,11 @@ function getExportMode(chunk, { exports: exportMode, name, format }, facadeModul
14373
14398
  const exportKeys = chunk.getExportNames();
14374
14399
  if (exportMode === 'default') {
14375
14400
  if (exportKeys.length !== 1 || exportKeys[0] !== 'default') {
14376
- return error(errIncompatibleExportOptionValue('default', exportKeys, facadeModuleId));
14401
+ return error(errorIncompatibleExportOptionValue('default', exportKeys, facadeModuleId));
14377
14402
  }
14378
14403
  }
14379
- else if (exportMode === 'none' && exportKeys.length) {
14380
- return error(errIncompatibleExportOptionValue('none', exportKeys, facadeModuleId));
14404
+ else if (exportMode === 'none' && exportKeys.length > 0) {
14405
+ return error(errorIncompatibleExportOptionValue('none', exportKeys, facadeModuleId));
14381
14406
  }
14382
14407
  if (exportMode === 'auto') {
14383
14408
  if (exportKeys.length === 0) {
@@ -14388,7 +14413,7 @@ function getExportMode(chunk, { exports: exportMode, name, format }, facadeModul
14388
14413
  }
14389
14414
  else {
14390
14415
  if (format !== 'es' && format !== 'system' && exportKeys.includes('default')) {
14391
- warn(errMixedExport(facadeModuleId, name));
14416
+ warn(errorMixedExport(facadeModuleId, name));
14392
14417
  }
14393
14418
  exportMode = 'named';
14394
14419
  }
@@ -14411,10 +14436,10 @@ function guessIndentString(code) {
14411
14436
  }
14412
14437
  // Otherwise, we need to guess the multiple
14413
14438
  const min = spaced.reduce((previous, current) => {
14414
- const numSpaces = /^ +/.exec(current)[0].length;
14415
- return Math.min(numSpaces, previous);
14439
+ const numberSpaces = /^ +/.exec(current)[0].length;
14440
+ return Math.min(numberSpaces, previous);
14416
14441
  }, Infinity);
14417
- return new Array(min + 1).join(' ');
14442
+ return ' '.repeat(min);
14418
14443
  }
14419
14444
  function getIndentString(modules, options) {
14420
14445
  if (options.indent !== true)
@@ -14476,11 +14501,11 @@ const getHashPlaceholderGenerator = () => {
14476
14501
  let nextIndex = 0;
14477
14502
  return (optionName, hashSize = defaultHashSize) => {
14478
14503
  if (hashSize > maxHashSize) {
14479
- return error(errFailedValidation(`Hashes cannot be longer than ${maxHashSize} characters, received ${hashSize}. Check the "${optionName}" option.`));
14504
+ return error(errorFailedValidation(`Hashes cannot be longer than ${maxHashSize} characters, received ${hashSize}. Check the "${optionName}" option.`));
14480
14505
  }
14481
14506
  const placeholder = `${hashPlaceholderLeft}${toBase64(++nextIndex).padStart(hashSize - hashPlaceholderOverhead, '0')}${hashPlaceholderRight}`;
14482
14507
  if (placeholder.length > hashSize) {
14483
- 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.`));
14508
+ return error(errorFailedValidation(`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.`));
14484
14509
  }
14485
14510
  return placeholder;
14486
14511
  };
@@ -14530,36 +14555,45 @@ const getOutputBundle = (outputBundleBase) => {
14530
14555
 
14531
14556
  function renderNamePattern(pattern, patternName, replacements) {
14532
14557
  if (isPathFragment(pattern))
14533
- return error(errFailedValidation(`Invalid pattern "${pattern}" for "${patternName}", patterns can be neither absolute nor relative paths. If you want your files to be stored in a subdirectory, write its name without a leading slash like this: subdirectory/pattern.`));
14558
+ return error(errorFailedValidation(`Invalid pattern "${pattern}" for "${patternName}", patterns can be neither absolute nor relative paths. If you want your files to be stored in a subdirectory, write its name without a leading slash like this: subdirectory/pattern.`));
14534
14559
  return pattern.replace(/\[(\w+)(:\d+)?]/g, (_match, type, size) => {
14535
14560
  if (!replacements.hasOwnProperty(type) || (size && type !== 'hash')) {
14536
- return error(errFailedValidation(`"[${type}${size || ''}]" is not a valid placeholder in the "${patternName}" pattern.`));
14561
+ return error(errorFailedValidation(`"[${type}${size || ''}]" is not a valid placeholder in the "${patternName}" pattern.`));
14537
14562
  }
14538
- const replacement = replacements[type](size && parseInt(size.slice(1)));
14563
+ const replacement = replacements[type](size && Number.parseInt(size.slice(1)));
14539
14564
  if (isPathFragment(replacement))
14540
- return error(errFailedValidation(`Invalid substitution "${replacement}" for placeholder "[${type}]" in "${patternName}" pattern, can be neither absolute nor relative path.`));
14565
+ return error(errorFailedValidation(`Invalid substitution "${replacement}" for placeholder "[${type}]" in "${patternName}" pattern, can be neither absolute nor relative path.`));
14541
14566
  return replacement;
14542
14567
  });
14543
14568
  }
14544
14569
  function makeUnique(name, { [lowercaseBundleKeys]: reservedLowercaseBundleKeys }) {
14545
14570
  if (!reservedLowercaseBundleKeys.has(name.toLowerCase()))
14546
14571
  return name;
14547
- const ext = extname(name);
14548
- name = name.substring(0, name.length - ext.length);
14572
+ const extension = extname(name);
14573
+ name = name.slice(0, Math.max(0, name.length - extension.length));
14549
14574
  let uniqueName, uniqueIndex = 1;
14550
- while (reservedLowercaseBundleKeys.has((uniqueName = name + ++uniqueIndex + ext).toLowerCase()))
14575
+ while (reservedLowercaseBundleKeys.has((uniqueName = name + ++uniqueIndex + extension).toLowerCase()))
14551
14576
  ;
14552
14577
  return uniqueName;
14553
14578
  }
14554
14579
 
14555
- const NON_ASSET_EXTENSIONS = ['.js', '.jsx', '.ts', '.tsx', '.mjs', '.mts', '.cjs', '.cts'];
14580
+ const NON_ASSET_EXTENSIONS = new Set([
14581
+ '.js',
14582
+ '.jsx',
14583
+ '.ts',
14584
+ '.tsx',
14585
+ '.mjs',
14586
+ '.mts',
14587
+ '.cjs',
14588
+ '.cts'
14589
+ ]);
14556
14590
  function getGlobalName(chunk, globals, hasExports, warn) {
14557
14591
  const globalName = typeof globals === 'function' ? globals(chunk.id) : globals[chunk.id];
14558
14592
  if (globalName) {
14559
14593
  return globalName;
14560
14594
  }
14561
14595
  if (hasExports) {
14562
- warn(errMissingGlobalName(chunk.id, chunk.variableName));
14596
+ warn(errorMissingGlobalName(chunk.id, chunk.variableName));
14563
14597
  return chunk.variableName;
14564
14598
  }
14565
14599
  }
@@ -14709,6 +14743,7 @@ class Chunk {
14709
14743
  }
14710
14744
  }
14711
14745
  for (const module of entryModules) {
14746
+ // eslint-disable-next-line unicorn/prefer-spread
14712
14747
  const requiredFacades = Array.from(new Set(module.chunkNames.filter(({ isUserDefined }) => isUserDefined).map(({ name }) => name)),
14713
14748
  // mapping must run after Set 'name' dedupe
14714
14749
  name => ({
@@ -14717,6 +14752,7 @@ class Chunk {
14717
14752
  if (requiredFacades.length === 0 && module.isUserDefinedEntryPoint) {
14718
14753
  requiredFacades.push({});
14719
14754
  }
14755
+ // eslint-disable-next-line unicorn/prefer-spread
14720
14756
  requiredFacades.push(...Array.from(module.chunkFileNames, fileName => ({ fileName })));
14721
14757
  if (requiredFacades.length === 0) {
14722
14758
  requiredFacades.push({});
@@ -14724,7 +14760,7 @@ class Chunk {
14724
14760
  if (!this.facadeModule) {
14725
14761
  const needsStrictFacade = module.preserveSignature === 'strict' ||
14726
14762
  (module.preserveSignature === 'exports-only' &&
14727
- module.getExportNamesByVariable().size !== 0);
14763
+ module.getExportNamesByVariable().size > 0);
14728
14764
  if (!needsStrictFacade ||
14729
14765
  this.outputOptions.preserveModules ||
14730
14766
  this.canModuleBeFacade(module, exposedVariables)) {
@@ -14786,7 +14822,7 @@ class Chunk {
14786
14822
  return (this.name ?? (this.name = this.outputOptions.sanitizeFileName(this.getFallbackChunkName())));
14787
14823
  }
14788
14824
  getExportNames() {
14789
- return (this.sortedExportNames ?? (this.sortedExportNames = Array.from(this.exportsByName.keys()).sort()));
14825
+ return (this.sortedExportNames ?? (this.sortedExportNames = [...this.exportsByName.keys()].sort()));
14790
14826
  }
14791
14827
  getFileName() {
14792
14828
  return this.preliminaryFileName?.fileName || this.getPreliminaryFileName().fileName;
@@ -14830,13 +14866,14 @@ class Chunk {
14830
14866
  if (this.renderedChunkInfo) {
14831
14867
  return this.renderedChunkInfo;
14832
14868
  }
14833
- const resolveFileName = (dependency) => dependency.getFileName();
14834
14869
  return (this.renderedChunkInfo = {
14835
14870
  ...this.getPreRenderedChunkInfo(),
14836
14871
  dynamicImports: this.getDynamicDependencies().map(resolveFileName),
14837
14872
  fileName: this.getFileName(),
14873
+ // eslint-disable-next-line unicorn/prefer-spread
14838
14874
  implicitlyLoadedBefore: Array.from(this.implicitlyLoadedBefore, resolveFileName),
14839
14875
  importedBindings: getImportedBindingsPerDependency(this.getRenderedDependencies(), resolveFileName),
14876
+ // eslint-disable-next-line unicorn/prefer-spread
14840
14877
  imports: Array.from(this.dependencies, resolveFileName),
14841
14878
  modules: this.renderedModules,
14842
14879
  referencedFiles: this.getReferencedFiles()
@@ -14870,7 +14907,7 @@ class Chunk {
14870
14907
  const { accessedGlobals, indent, magicString, renderedSource, usedModules, usesTopLevelAwait } = this.renderModules(preliminaryFileName.fileName);
14871
14908
  const renderedDependencies = [...this.getRenderedDependencies().values()];
14872
14909
  const renderedExports = exportMode === 'none' ? [] : this.getChunkExportDeclarations(format);
14873
- let hasExports = renderedExports.length !== 0;
14910
+ let hasExports = renderedExports.length > 0;
14874
14911
  let hasDefaultExport = false;
14875
14912
  for (const { reexports } of renderedDependencies) {
14876
14913
  if (reexports?.length) {
@@ -14919,9 +14956,9 @@ class Chunk {
14919
14956
  };
14920
14957
  }
14921
14958
  addImplicitlyLoadedBeforeFromModule(baseModule) {
14922
- const { implicitlyLoadedBefore } = this;
14959
+ const { chunkByModule, implicitlyLoadedBefore } = this;
14923
14960
  for (const module of baseModule.implicitlyLoadedBefore) {
14924
- const chunk = this.chunkByModule.get(module);
14961
+ const chunk = chunkByModule.get(module);
14925
14962
  if (chunk && chunk !== this) {
14926
14963
  implicitlyLoadedBefore.add(chunk);
14927
14964
  }
@@ -14957,7 +14994,7 @@ class Chunk {
14957
14994
  if (alternativeReexportModule) {
14958
14995
  const exportingChunk = this.chunkByModule.get(alternativeReexportModule);
14959
14996
  if (exportingChunk && exportingChunk !== exportChunk) {
14960
- this.inputOptions.onwarn(errCyclicCrossChunkReexport(variableModule.getExportNamesByVariable().get(variable)[0], variableModule.id, alternativeReexportModule.id, importingModule.id));
14997
+ this.inputOptions.onwarn(errorCyclicCrossChunkReexport(variableModule.getExportNamesByVariable().get(variable)[0], variableModule.id, alternativeReexportModule.id, importingModule.id));
14961
14998
  }
14962
14999
  importingModule = alternativeReexportModule;
14963
15000
  }
@@ -14987,7 +15024,7 @@ class Chunk {
14987
15024
  }
14988
15025
  }
14989
15026
  }
14990
- if (includedReexports.length) {
15027
+ if (includedReexports.length > 0) {
14991
15028
  this.includedReexportsByModule.set(module, includedReexports);
14992
15029
  }
14993
15030
  }
@@ -15059,10 +15096,9 @@ class Chunk {
15059
15096
  deconflictedDefault.add(chunk);
15060
15097
  }
15061
15098
  }
15062
- else if (variable.name === '*') {
15063
- if (namespaceInteropHelpersByInteropType[interop(module.id)]) {
15064
- deconflictedNamespace.add(chunk);
15065
- }
15099
+ else if (variable.name === '*' &&
15100
+ namespaceInteropHelpersByInteropType[interop(module.id)]) {
15101
+ deconflictedNamespace.add(chunk);
15066
15102
  }
15067
15103
  }
15068
15104
  }
@@ -15128,7 +15164,7 @@ class Chunk {
15128
15164
  dependency = this.externalChunkByModule.get(module);
15129
15165
  imported = variable.name;
15130
15166
  if (imported !== 'default' && imported !== '*' && interop(module.id) === 'defaultOnly') {
15131
- return error(errUnexpectedNamedImport(module.id, imported, false));
15167
+ return error(errorUnexpectedNamedImport(module.id, imported, false));
15132
15168
  }
15133
15169
  }
15134
15170
  else {
@@ -15177,14 +15213,14 @@ class Chunk {
15177
15213
  if (this.preRenderedChunkInfo) {
15178
15214
  return this.preRenderedChunkInfo;
15179
15215
  }
15180
- const { facadeModule } = this;
15216
+ const { dynamicEntryModules, facadeModule, implicitEntryModules, orderedModules } = this;
15181
15217
  return (this.preRenderedChunkInfo = {
15182
15218
  exports: this.getExportNames(),
15183
15219
  facadeModuleId: facadeModule && facadeModule.id,
15184
- isDynamicEntry: this.dynamicEntryModules.length > 0,
15220
+ isDynamicEntry: dynamicEntryModules.length > 0,
15185
15221
  isEntry: !!facadeModule?.info.isEntry,
15186
- isImplicitEntry: this.implicitEntryModules.length > 0,
15187
- moduleIds: this.orderedModules.map(({ id }) => id),
15222
+ isImplicitEntry: implicitEntryModules.length > 0,
15223
+ moduleIds: orderedModules.map(({ id }) => id),
15188
15224
  name: this.getChunkName(),
15189
15225
  type: 'chunk'
15190
15226
  });
@@ -15195,13 +15231,13 @@ class Chunk {
15195
15231
  return predefinedChunkName;
15196
15232
  const { preserveModulesRoot, sanitizeFileName } = this.outputOptions;
15197
15233
  const sanitizedId = sanitizeFileName(module.id.split(QUERY_HASH_REGEX, 1)[0]);
15198
- const extName = extname(sanitizedId);
15199
- const idWithoutExtension = NON_ASSET_EXTENSIONS.includes(extName)
15200
- ? sanitizedId.slice(0, -extName.length)
15234
+ const extensionName = extname(sanitizedId);
15235
+ const idWithoutExtension = NON_ASSET_EXTENSIONS.has(extensionName)
15236
+ ? sanitizedId.slice(0, -extensionName.length)
15201
15237
  : sanitizedId;
15202
15238
  if (isAbsolute(idWithoutExtension)) {
15203
15239
  return preserveModulesRoot && resolve(idWithoutExtension).startsWith(preserveModulesRoot)
15204
- ? idWithoutExtension.slice(preserveModulesRoot.length).replace(/^[\\/]/, '')
15240
+ ? idWithoutExtension.slice(preserveModulesRoot.length).replace(/^[/\\]/, '')
15205
15241
  : relative(this.inputBase, idWithoutExtension);
15206
15242
  }
15207
15243
  else {
@@ -15216,9 +15252,9 @@ class Chunk {
15216
15252
  let imported;
15217
15253
  let needsLiveBinding = false;
15218
15254
  if (exportName[0] === '*') {
15219
- const id = exportName.substring(1);
15255
+ const id = exportName.slice(1);
15220
15256
  if (interop(id) === 'defaultOnly') {
15221
- this.inputOptions.onwarn(errUnexpectedNamespaceReexport(id));
15257
+ this.inputOptions.onwarn(errorUnexpectedNamespaceReexport(id));
15222
15258
  }
15223
15259
  needsLiveBinding = externalLiveBindings;
15224
15260
  dependency = this.externalChunkByModule.get(this.modulesById.get(id));
@@ -15240,7 +15276,7 @@ class Chunk {
15240
15276
  dependency = this.externalChunkByModule.get(module);
15241
15277
  imported = variable.name;
15242
15278
  if (imported !== 'default' && imported !== '*' && interop(module.id) === 'defaultOnly') {
15243
- return error(errUnexpectedNamedImport(module.id, imported, true));
15279
+ return error(errorUnexpectedNamedImport(module.id, imported, true));
15244
15280
  }
15245
15281
  needsLiveBinding =
15246
15282
  externalLiveBindings &&
@@ -15309,9 +15345,9 @@ class Chunk {
15309
15345
  }
15310
15346
  // This method changes properties on the AST before rendering and must not be async
15311
15347
  renderModules(fileName) {
15312
- const { dependencies, exportNamesByVariable, includedNamespaces, inputOptions: { onwarn }, isEmpty, orderedModules, outputOptions, pluginDriver, renderedModules, snippets } = this;
15348
+ const { accessedGlobalsByScope, dependencies, exportNamesByVariable, includedNamespaces, inputOptions: { onwarn }, isEmpty, orderedModules, outputOptions, pluginDriver, renderedModules, snippets } = this;
15313
15349
  const { compact, dynamicImportFunction, format, freeze, namespaceToStringTag, preserveModules } = outputOptions;
15314
- const { _, n } = snippets;
15350
+ const { _, cnst, n } = snippets;
15315
15351
  this.setDynamicImportResolutions(fileName);
15316
15352
  this.setImportMetaResolutions(fileName);
15317
15353
  this.setIdentifierRenderResolutions();
@@ -15355,7 +15391,7 @@ class Chunk {
15355
15391
  else
15356
15392
  magicString.addSource(new MagicString(rendered));
15357
15393
  }
15358
- const accessedGlobalVariables = this.accessedGlobalsByScope.get(module.scope);
15394
+ const accessedGlobalVariables = accessedGlobalsByScope.get(module.scope);
15359
15395
  if (accessedGlobalVariables) {
15360
15396
  for (const name of accessedGlobalVariables) {
15361
15397
  accessedGlobals.add(name);
@@ -15375,12 +15411,13 @@ class Chunk {
15375
15411
  }
15376
15412
  if (hoistedSource)
15377
15413
  magicString.prepend(hoistedSource + n + n);
15414
+ // eslint-disable-next-line unicorn/consistent-destructuring
15378
15415
  if (this.needsExportsShim) {
15379
- magicString.prepend(`${n}${snippets.cnst} ${MISSING_EXPORT_SHIM_VARIABLE}${_}=${_}void 0;${n}${n}`);
15416
+ magicString.prepend(`${n}${cnst} ${MISSING_EXPORT_SHIM_VARIABLE}${_}=${_}void 0;${n}${n}`);
15380
15417
  }
15381
15418
  const renderedSource = compact ? magicString : magicString.trim();
15382
15419
  if (isEmpty && this.getExportNames().length === 0 && dependencies.size === 0) {
15383
- onwarn(errEmptyChunk(this.getChunkName()));
15420
+ onwarn(errorEmptyChunk(this.getChunkName()));
15384
15421
  }
15385
15422
  return { accessedGlobals, indent, magicString, renderedSource, usedModules, usesTopLevelAwait };
15386
15423
  }
@@ -15397,14 +15434,14 @@ class Chunk {
15397
15434
  }
15398
15435
  }
15399
15436
  else {
15400
- const { resolution } = resolvedDynamicImport;
15437
+ const { node, resolution } = resolvedDynamicImport;
15401
15438
  const [resolutionString, assertions] = this.getDynamicImportStringAndAssertions(resolution, fileName);
15402
- resolvedDynamicImport.node.setExternalResolution('external', resolution, outputOptions, snippets, pluginDriver, accessedGlobalsByScope, resolutionString, false, assertions);
15439
+ node.setExternalResolution('external', resolution, outputOptions, snippets, pluginDriver, accessedGlobalsByScope, resolutionString, false, assertions);
15403
15440
  }
15404
15441
  }
15405
15442
  }
15406
15443
  setIdentifierRenderResolutions() {
15407
- const { format, interop, namespaceToStringTag } = this.outputOptions;
15444
+ const { format, interop, namespaceToStringTag, preserveModules, externalLiveBindings } = this.outputOptions;
15408
15445
  const syntheticExports = new Set();
15409
15446
  for (const exportName of this.getExportNames()) {
15410
15447
  const exportVariable = this.exportsByName.get(exportName);
@@ -15435,25 +15472,29 @@ class Chunk {
15435
15472
  usedNames.add('Symbol');
15436
15473
  }
15437
15474
  switch (format) {
15438
- case 'system':
15475
+ case 'system': {
15439
15476
  usedNames.add('module').add('exports');
15440
15477
  break;
15441
- case 'es':
15478
+ }
15479
+ case 'es': {
15442
15480
  break;
15443
- case 'cjs':
15481
+ }
15482
+ case 'cjs': {
15444
15483
  usedNames.add('module').add('require').add('__filename').add('__dirname');
15484
+ }
15445
15485
  // fallthrough
15446
- default:
15486
+ default: {
15447
15487
  usedNames.add('exports');
15448
15488
  for (const helper of HELPER_NAMES) {
15449
15489
  usedNames.add(helper);
15450
15490
  }
15491
+ }
15451
15492
  }
15452
- 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);
15493
+ deconflictChunk(this.orderedModules, this.getDependenciesToBeDeconflicted(format !== 'es' && format !== 'system', format === 'amd' || format === 'umd' || format === 'iife', interop), this.imports, usedNames, format, interop, preserveModules, externalLiveBindings, this.chunkByModule, this.externalChunkByModule, syntheticExports, this.exportNamesByVariable, this.accessedGlobalsByScope, this.includedNamespaces);
15453
15494
  }
15454
15495
  setImportMetaResolutions(fileName) {
15455
- const { accessedGlobalsByScope, includedNamespaces, outputOptions: { format, preserveModules } } = this;
15456
- for (const module of this.orderedModules) {
15496
+ const { accessedGlobalsByScope, includedNamespaces, orderedModules, outputOptions: { format, preserveModules } } = this;
15497
+ for (const module of orderedModules) {
15457
15498
  for (const importMeta of module.importMetas) {
15458
15499
  importMeta.setResolution(format, accessedGlobalsByScope, fileName);
15459
15500
  }
@@ -15466,12 +15507,10 @@ class Chunk {
15466
15507
  const moduleImports = new Set(module.includedImports);
15467
15508
  // when we are not preserving modules, we need to make all namespace variables available for
15468
15509
  // rendering the namespace object
15469
- if (!this.outputOptions.preserveModules) {
15470
- if (this.includedNamespaces.has(module)) {
15471
- const memberVariables = module.namespace.getMemberVariables();
15472
- for (const variable of Object.values(memberVariables)) {
15473
- moduleImports.add(variable);
15474
- }
15510
+ if (!this.outputOptions.preserveModules && this.includedNamespaces.has(module)) {
15511
+ const memberVariables = module.namespace.getMemberVariables();
15512
+ for (const variable of Object.values(memberVariables)) {
15513
+ moduleImports.add(variable);
15475
15514
  }
15476
15515
  }
15477
15516
  for (let variable of moduleImports) {
@@ -15531,7 +15570,8 @@ function getImportedBindingsPerDependency(renderedDependencies, resolveFileName)
15531
15570
  }
15532
15571
  return importedBindingsPerDependency;
15533
15572
  }
15534
- const QUERY_HASH_REGEX = /[?#]/;
15573
+ const QUERY_HASH_REGEX = /[#?]/;
15574
+ const resolveFileName = (dependency) => dependency.getFileName();
15535
15575
 
15536
15576
  function getChunkAssignments(entryModules, manualChunkAliasByEntry) {
15537
15577
  const chunkDefinitions = [];
@@ -15677,11 +15717,11 @@ function commondir(files) {
15677
15717
  return dirname(files[0]);
15678
15718
  const commonSegments = files.slice(1).reduce((commonSegments, file) => {
15679
15719
  const pathSegements = file.split(/\/+|\\+/);
15680
- let i;
15681
- for (i = 0; commonSegments[i] === pathSegements[i] &&
15682
- i < Math.min(commonSegments.length, pathSegements.length); i++)
15720
+ let index;
15721
+ for (index = 0; commonSegments[index] === pathSegements[index] &&
15722
+ index < Math.min(commonSegments.length, pathSegements.length); index++)
15683
15723
  ;
15684
- return commonSegments.slice(0, i);
15724
+ return commonSegments.slice(0, index);
15685
15725
  }, files[0].split(/\/+|\\+/));
15686
15726
  // Windows correctly handles paths with forward-slashes
15687
15727
  return commonSegments.length > 1 ? commonSegments.join('/') : '/';
@@ -15723,16 +15763,16 @@ function analyseModuleExecution(entryModules) {
15723
15763
  module.execIndex = nextExecIndex++;
15724
15764
  analysedModules.add(module);
15725
15765
  };
15726
- for (const curEntry of entryModules) {
15727
- if (!parents.has(curEntry)) {
15728
- parents.set(curEntry, null);
15729
- analyseModule(curEntry);
15766
+ for (const currentEntry of entryModules) {
15767
+ if (!parents.has(currentEntry)) {
15768
+ parents.set(currentEntry, null);
15769
+ analyseModule(currentEntry);
15730
15770
  }
15731
15771
  }
15732
- for (const curEntry of dynamicImports) {
15733
- if (!parents.has(curEntry)) {
15734
- parents.set(curEntry, null);
15735
- analyseModule(curEntry);
15772
+ for (const currentEntry of dynamicImports) {
15773
+ if (!parents.has(currentEntry)) {
15774
+ parents.set(currentEntry, null);
15775
+ analyseModule(currentEntry);
15736
15776
  }
15737
15777
  }
15738
15778
  return { cyclePaths, orderedModules };
@@ -15755,16 +15795,16 @@ function getCyclePath(module, parent, parents) {
15755
15795
  function getGenerateCodeSnippets({ compact, generatedCode: { arrowFunctions, constBindings, objectShorthand, reservedNamesAsProps } }) {
15756
15796
  const { _, n, s } = compact ? { _: '', n: '', s: '' } : { _: ' ', n: '\n', s: ';' };
15757
15797
  const cnst = constBindings ? 'const' : 'var';
15758
- const getNonArrowFunctionIntro = (params, { isAsync, name }) => `${isAsync ? `async ` : ''}function${name ? ` ${name}` : ''}${_}(${params.join(`,${_}`)})${_}`;
15798
+ const getNonArrowFunctionIntro = (parameters, { isAsync, name }) => `${isAsync ? `async ` : ''}function${name ? ` ${name}` : ''}${_}(${parameters.join(`,${_}`)})${_}`;
15759
15799
  const getFunctionIntro = arrowFunctions
15760
- ? (params, { isAsync, name }) => {
15761
- const singleParam = params.length === 1;
15762
- const asyncString = isAsync ? `async${singleParam ? ' ' : _}` : '';
15763
- return `${name ? `${cnst} ${name}${_}=${_}` : ''}${asyncString}${singleParam ? params[0] : `(${params.join(`,${_}`)})`}${_}=>${_}`;
15800
+ ? (parameters, { isAsync, name }) => {
15801
+ const singleParameter = parameters.length === 1;
15802
+ const asyncString = isAsync ? `async${singleParameter ? ' ' : _}` : '';
15803
+ return `${name ? `${cnst} ${name}${_}=${_}` : ''}${asyncString}${singleParameter ? parameters[0] : `(${parameters.join(`,${_}`)})`}${_}=>${_}`;
15764
15804
  }
15765
15805
  : getNonArrowFunctionIntro;
15766
- const getDirectReturnFunction = (params, { functionReturn, lineBreakIndent, name }) => [
15767
- `${getFunctionIntro(params, {
15806
+ const getDirectReturnFunction = (parameters, { functionReturn, lineBreakIndent, name }) => [
15807
+ `${getFunctionIntro(parameters, {
15768
15808
  isAsync: false,
15769
15809
  name
15770
15810
  })}${arrowFunctions
@@ -15776,15 +15816,15 @@ function getGenerateCodeSnippets({ compact, generatedCode: { arrowFunctions, con
15776
15816
  ? `${name ? ';' : ''}${lineBreakIndent ? `${n}${lineBreakIndent.base}` : ''}`
15777
15817
  : `${s}${lineBreakIndent ? `${n}${lineBreakIndent.base}` : _}}`
15778
15818
  ];
15779
- const isValidPropName = reservedNamesAsProps
15780
- ? (name) => validPropName.test(name)
15781
- : (name) => !RESERVED_NAMES$1.has(name) && validPropName.test(name);
15819
+ const isValidPropertyName = reservedNamesAsProps
15820
+ ? (name) => validPropertyName.test(name)
15821
+ : (name) => !RESERVED_NAMES$1.has(name) && validPropertyName.test(name);
15782
15822
  return {
15783
15823
  _,
15784
15824
  cnst,
15785
15825
  getDirectReturnFunction,
15786
- getDirectReturnIifeLeft: (params, returned, { needsArrowReturnParens, needsWrappedFunction }) => {
15787
- const [left, right] = getDirectReturnFunction(params, {
15826
+ getDirectReturnIifeLeft: (parameters, returned, { needsArrowReturnParens, needsWrappedFunction }) => {
15827
+ const [left, right] = getDirectReturnFunction(parameters, {
15788
15828
  functionReturn: true,
15789
15829
  lineBreakIndent: null,
15790
15830
  name: null
@@ -15799,20 +15839,20 @@ function getGenerateCodeSnippets({ compact, generatedCode: { arrowFunctions, con
15799
15839
  .map(([key, value]) => {
15800
15840
  if (key === null)
15801
15841
  return `${prefix}${value}`;
15802
- const needsQuotes = !isValidPropName(key);
15842
+ const needsQuotes = !isValidPropertyName(key);
15803
15843
  return key === value && objectShorthand && !needsQuotes
15804
15844
  ? prefix + key
15805
15845
  : `${prefix}${needsQuotes ? `'${key}'` : key}:${_}${value}`;
15806
15846
  })
15807
15847
  .join(`,`)}${fields.length === 0 ? '' : lineBreakIndent ? `${n}${lineBreakIndent.base}` : _}}`;
15808
15848
  },
15809
- getPropertyAccess: (name) => isValidPropName(name) ? `.${name}` : `[${JSON.stringify(name)}]`,
15849
+ getPropertyAccess: (name) => isValidPropertyName(name) ? `.${name}` : `[${JSON.stringify(name)}]`,
15810
15850
  n,
15811
15851
  s
15812
15852
  };
15813
15853
  }
15814
15854
  const wrapIfNeeded = (code, needsParens) => needsParens ? `(${code})` : code;
15815
- const validPropName = /^(?!\d)[\w$]+$/;
15855
+ const validPropertyName = /^(?!\d)[\w$]+$/;
15816
15856
 
15817
15857
  class Source {
15818
15858
  constructor(filename, content) {
@@ -15916,7 +15956,7 @@ function getLinkMap(warn) {
15916
15956
  if (map.mappings) {
15917
15957
  return new Link(map, [source]);
15918
15958
  }
15919
- warn(errSourcemapBroken(map.plugin));
15959
+ warn(errorSourcemapBroken(map.plugin));
15920
15960
  return new Link({
15921
15961
  mappings: [],
15922
15962
  names: []
@@ -15933,7 +15973,7 @@ function getCollapsedSourcemap(id, originalCode, originalSourcemap, sourcemapCha
15933
15973
  const sourcesContent = originalSourcemap.sourcesContent || [];
15934
15974
  const directory = dirname(id) || '.';
15935
15975
  const sourceRoot = originalSourcemap.sourceRoot || '.';
15936
- const baseSources = sources.map((source, i) => new Source(resolve(directory, sourceRoot, source), sourcesContent[i]));
15976
+ const baseSources = sources.map((source, index) => new Source(resolve(directory, sourceRoot, source), sourcesContent[index]));
15937
15977
  source = new Link(originalSourcemap, baseSources);
15938
15978
  }
15939
15979
  return sourcemapChain.reduce(linkMap, source);
@@ -15955,7 +15995,7 @@ function collapseSourcemaps(file, map, modules, bundleSourcemapChain, excludeCon
15955
15995
  return new SourceMap({ file, mappings, names, sources, sourcesContent });
15956
15996
  }
15957
15997
  function collapseSourcemap(id, originalCode, originalSourcemap, sourcemapChain, warn) {
15958
- if (!sourcemapChain.length) {
15998
+ if (sourcemapChain.length === 0) {
15959
15999
  return originalSourcemap;
15960
16000
  }
15961
16001
  const source = getCollapsedSourcemap(id, originalCode, originalSourcemap, sourcemapChain, getLinkMap(warn));
@@ -16027,26 +16067,26 @@ async function transformChunk(magicString, fileName, usedModules, chunkGraph, op
16027
16067
  }
16028
16068
  return result.code;
16029
16069
  });
16030
- const { compact, sourcemap, sourcemapPathTransform } = options;
16070
+ const { compact, dir, file, sourcemap, sourcemapExcludeSources, sourcemapFile, sourcemapPathTransform } = options;
16031
16071
  if (!compact && code[code.length - 1] !== '\n')
16032
16072
  code += '\n';
16033
16073
  if (sourcemap) {
16034
16074
  timeStart('sourcemaps', 3);
16035
- let file;
16036
- if (options.file)
16037
- file = resolve(options.sourcemapFile || options.file);
16038
- else if (options.dir)
16039
- file = resolve(options.dir, fileName);
16075
+ let resultingFile;
16076
+ if (file)
16077
+ resultingFile = resolve(sourcemapFile || file);
16078
+ else if (dir)
16079
+ resultingFile = resolve(dir, fileName);
16040
16080
  else
16041
- file = resolve(fileName);
16081
+ resultingFile = resolve(fileName);
16042
16082
  const decodedMap = magicString.generateDecodedMap({});
16043
- map = collapseSourcemaps(file, decodedMap, usedModules, sourcemapChain, options.sourcemapExcludeSources, onwarn);
16083
+ map = collapseSourcemaps(resultingFile, decodedMap, usedModules, sourcemapChain, sourcemapExcludeSources, onwarn);
16044
16084
  map.sources = map.sources
16045
16085
  .map(sourcePath => {
16046
16086
  if (sourcemapPathTransform) {
16047
- const newSourcePath = sourcemapPathTransform(sourcePath, `${file}.map`);
16087
+ const newSourcePath = sourcemapPathTransform(sourcePath, `${resultingFile}.map`);
16048
16088
  if (typeof newSourcePath !== 'string') {
16049
- error(errFailedValidation(`sourcemapPathTransform function must return a string.`));
16089
+ error(errorFailedValidation(`sourcemapPathTransform function must return a string.`));
16050
16090
  }
16051
16091
  return newSourcePath;
16052
16092
  }
@@ -16147,9 +16187,7 @@ function addChunksToBundle(renderedChunksByPlaceholder, hashesByPlaceholder, bun
16147
16187
  bundle[finalFileName] = chunk.generateOutputChunk(updatedCode, map, hashesByPlaceholder);
16148
16188
  }
16149
16189
  for (const { chunk, code, fileName, map } of nonHashedChunksWithPlaceholders) {
16150
- let updatedCode = hashesByPlaceholder.size
16151
- ? replacePlaceholders(code, hashesByPlaceholder)
16152
- : code;
16190
+ let updatedCode = hashesByPlaceholder.size > 0 ? replacePlaceholders(code, hashesByPlaceholder) : code;
16153
16191
  if (map) {
16154
16192
  updatedCode += emitSourceMapAndGetComment(fileName, map, pluginDriver, options);
16155
16193
  }
@@ -16203,9 +16241,9 @@ class Bundle {
16203
16241
  timeEnd('generate chunks', 2);
16204
16242
  await renderChunks(chunks, outputBundle, this.pluginDriver, this.outputOptions, this.inputOptions.onwarn);
16205
16243
  }
16206
- catch (err) {
16207
- await this.pluginDriver.hookParallel('renderError', [err]);
16208
- throw err;
16244
+ catch (error_) {
16245
+ await this.pluginDriver.hookParallel('renderError', [error_]);
16246
+ throw error_;
16209
16247
  }
16210
16248
  timeStart('generate bundle', 2);
16211
16249
  await this.pluginDriver.hookSeq('generateBundle', [
@@ -16232,6 +16270,7 @@ class Bundle {
16232
16270
  return manualChunkAliasByEntry;
16233
16271
  }
16234
16272
  assignManualChunks(getManualChunk) {
16273
+ // eslint-disable-next-line unicorn/prefer-module
16235
16274
  const manualChunkAliasesWithEntry = [];
16236
16275
  const manualChunksApi = {
16237
16276
  getModuleIds: () => this.graph.modulesById.keys(),
@@ -16262,8 +16301,8 @@ class Bundle {
16262
16301
  ecmaVersion: 'latest'
16263
16302
  });
16264
16303
  }
16265
- catch (err) {
16266
- this.inputOptions.onwarn(errChunkInvalid(file, err));
16304
+ catch (error_) {
16305
+ this.inputOptions.onwarn(errorChunkInvalid(file, error_));
16267
16306
  }
16268
16307
  }
16269
16308
  }
@@ -16302,13 +16341,13 @@ class Bundle {
16302
16341
  }
16303
16342
  function validateOptionsForMultiChunkOutput(outputOptions, onWarn) {
16304
16343
  if (outputOptions.format === 'umd' || outputOptions.format === 'iife')
16305
- return error(errInvalidOption('output.format', 'outputformat', 'UMD and IIFE output formats are not supported for code-splitting builds', outputOptions.format));
16344
+ return error(errorInvalidOption('output.format', 'outputformat', 'UMD and IIFE output formats are not supported for code-splitting builds', outputOptions.format));
16306
16345
  if (typeof outputOptions.file === 'string')
16307
- return error(errInvalidOption('output.file', 'outputdir', 'when building multiple chunks, the "output.dir" option must be used, not "output.file". To inline dynamic imports, set the "inlineDynamicImports" option'));
16346
+ return error(errorInvalidOption('output.file', 'outputdir', 'when building multiple chunks, the "output.dir" option must be used, not "output.file". To inline dynamic imports, set the "inlineDynamicImports" option'));
16308
16347
  if (outputOptions.sourcemapFile)
16309
- return error(errInvalidOption('output.sourcemapFile', 'outputsourcemapfile', '"output.sourcemapFile" is only supported for single-file builds'));
16348
+ return error(errorInvalidOption('output.sourcemapFile', 'outputsourcemapfile', '"output.sourcemapFile" is only supported for single-file builds'));
16310
16349
  if (!outputOptions.amd.autoId && outputOptions.amd.id)
16311
- 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'));
16350
+ onWarn(errorInvalidOption('output.amd.id', 'outputamd', 'this option is only properly supported for single-file builds. Use "output.amd.autoId" and "output.amd.basePath" instead'));
16312
16351
  }
16313
16352
  function getIncludedModules(modulesById) {
16314
16353
  const includedModules = [];
@@ -16341,7 +16380,7 @@ function getExternalChunkByModule(modulesById, outputOptions, inputBase) {
16341
16380
  function addModuleToManualChunk(alias, module, manualChunkAliasByEntry) {
16342
16381
  const existingAlias = manualChunkAliasByEntry.get(module);
16343
16382
  if (typeof existingAlias === 'string' && existingAlias !== alias) {
16344
- return error(errCannotAssignModuleToChunk(module.id, alias, existingAlias));
16383
+ return error(errorCannotAssignModuleToChunk(module.id, alias, existingAlias));
16345
16384
  }
16346
16385
  manualChunkAliasByEntry.set(module, alias);
16347
16386
  }
@@ -22013,7 +22052,7 @@ function createPluginCache(cache) {
22013
22052
  get(id) {
22014
22053
  const item = cache[id];
22015
22054
  if (!item)
22016
- return undefined;
22055
+ return;
22017
22056
  item[0] = 0;
22018
22057
  return item[1];
22019
22058
  },
@@ -22064,9 +22103,9 @@ const NO_CACHE = {
22064
22103
  function uncacheablePluginError(pluginName) {
22065
22104
  if (pluginName.startsWith(ANONYMOUS_PLUGIN_PREFIX) ||
22066
22105
  pluginName.startsWith(ANONYMOUS_OUTPUT_PLUGIN_PREFIX)) {
22067
- return error(errAnonymousPluginCache());
22106
+ return error(errorAnonymousPluginCache());
22068
22107
  }
22069
- return error(errDuplicatePluginName(pluginName));
22108
+ return error(errorDuplicatePluginName(pluginName));
22070
22109
  }
22071
22110
  function getCacheForUncacheablePlugin(pluginName) {
22072
22111
  return {
@@ -22096,7 +22135,7 @@ async function transform(source, module, pluginDriver, warn) {
22096
22135
  let customTransformCache = false;
22097
22136
  const useCustomTransformCache = () => (customTransformCache = true);
22098
22137
  let pluginName = '';
22099
- const curSource = source.code;
22138
+ const currentSource = source.code;
22100
22139
  function transformReducer(previousCode, result, plugin) {
22101
22140
  let code;
22102
22141
  let map;
@@ -22107,7 +22146,7 @@ async function transform(source, module, pluginDriver, warn) {
22107
22146
  module.updateOptions(result);
22108
22147
  if (result.code == null) {
22109
22148
  if (result.map || result.ast) {
22110
- warn(errNoTransformMapOrAstWithoutCode(plugin.name));
22149
+ warn(errorNoTransformMapOrAstWithoutCode(plugin.name));
22111
22150
  }
22112
22151
  return previousCode;
22113
22152
  }
@@ -22128,7 +22167,7 @@ async function transform(source, module, pluginDriver, warn) {
22128
22167
  }
22129
22168
  let code;
22130
22169
  try {
22131
- code = await pluginDriver.hookReduceArg0('transform', [curSource, id], transformReducer, (pluginContext, plugin) => {
22170
+ code = await pluginDriver.hookReduceArg0('transform', [currentSource, id], transformReducer, (pluginContext, plugin) => {
22132
22171
  pluginName = plugin.name;
22133
22172
  return {
22134
22173
  ...pluginContext,
@@ -22143,14 +22182,14 @@ async function transform(source, module, pluginDriver, warn) {
22143
22182
  emittedFiles.push(emittedFile);
22144
22183
  return pluginDriver.emitFile(emittedFile);
22145
22184
  },
22146
- error(err, pos) {
22147
- if (typeof err === 'string')
22148
- err = { message: err };
22185
+ error(error_, pos) {
22186
+ if (typeof error_ === 'string')
22187
+ error_ = { message: error_ };
22149
22188
  if (pos)
22150
- augmentCodeLocation(err, pos, curSource, id);
22151
- err.id = id;
22152
- err.hook = 'transform';
22153
- return pluginContext.error(err);
22189
+ augmentCodeLocation(error_, pos, currentSource, id);
22190
+ error_.id = id;
22191
+ error_.hook = 'transform';
22192
+ return pluginContext.error(error_);
22154
22193
  },
22155
22194
  getCombinedSourcemap() {
22156
22195
  const combinedMap = collapseSourcemap(id, originalCode, originalSourcemap, sourcemapChain, warn);
@@ -22169,13 +22208,13 @@ async function transform(source, module, pluginDriver, warn) {
22169
22208
  });
22170
22209
  },
22171
22210
  setAssetSource() {
22172
- return this.error(errInvalidSetAssetSourceCall());
22211
+ return this.error(errorInvalidSetAssetSourceCall());
22173
22212
  },
22174
22213
  warn(warning, pos) {
22175
22214
  if (typeof warning === 'string')
22176
22215
  warning = { message: warning };
22177
22216
  if (pos)
22178
- augmentCodeLocation(warning, pos, curSource, id);
22217
+ augmentCodeLocation(warning, pos, currentSource, id);
22179
22218
  warning.id = id;
22180
22219
  warning.hook = 'transform';
22181
22220
  pluginContext.warn(warning);
@@ -22183,14 +22222,12 @@ async function transform(source, module, pluginDriver, warn) {
22183
22222
  };
22184
22223
  });
22185
22224
  }
22186
- catch (err) {
22187
- return error(errPluginError(err, pluginName, { hook: 'transform', id }));
22188
- }
22189
- if (!customTransformCache) {
22190
- // files emitted by a transform hook need to be emitted again if the hook is skipped
22191
- if (emittedFiles.length)
22192
- module.transformFiles = emittedFiles;
22225
+ catch (error_) {
22226
+ return error(errorPluginError(error_, pluginName, { hook: 'transform', id }));
22193
22227
  }
22228
+ if (!customTransformCache && // files emitted by a transform hook need to be emitted again if the hook is skipped
22229
+ emittedFiles.length > 0)
22230
+ module.transformFiles = emittedFiles;
22194
22231
  return {
22195
22232
  ast,
22196
22233
  code,
@@ -22234,8 +22271,7 @@ class ModuleLoader {
22234
22271
  const firstChunkNamePriority = this.nextChunkNamePriority;
22235
22272
  this.nextChunkNamePriority += unresolvedEntryModules.length;
22236
22273
  const newEntryModules = await this.extendLoadModulesPromise(Promise.all(unresolvedEntryModules.map(({ id, importer }) => this.loadEntryModule(id, true, importer, null))).then(entryModules => {
22237
- for (let index = 0; index < entryModules.length; index++) {
22238
- const entryModule = entryModules[index];
22274
+ for (const [index, entryModule] of entryModules.entries()) {
22239
22275
  entryModule.isUserDefinedEntryPoint =
22240
22276
  entryModule.isUserDefinedEntryPoint || isUserDefined;
22241
22277
  addChunkNamesToModule(entryModule, unresolvedEntryModules[index], isUserDefined, firstChunkNamePriority + index);
@@ -22301,19 +22337,19 @@ class ModuleLoader {
22301
22337
  try {
22302
22338
  source = await this.graph.fileOperationQueue.run(async () => (await this.pluginDriver.hookFirst('load', [id])) ?? (await promises.readFile(id, 'utf8')));
22303
22339
  }
22304
- catch (err) {
22305
- let msg = `Could not load ${id}`;
22340
+ catch (error_) {
22341
+ let message = `Could not load ${id}`;
22306
22342
  if (importer)
22307
- msg += ` (imported by ${relativeId(importer)})`;
22308
- msg += `: ${err.message}`;
22309
- err.message = msg;
22310
- throw err;
22343
+ message += ` (imported by ${relativeId(importer)})`;
22344
+ message += `: ${error_.message}`;
22345
+ error_.message = message;
22346
+ throw error_;
22311
22347
  }
22312
22348
  const sourceDescription = typeof source === 'string'
22313
22349
  ? { code: source }
22314
22350
  : source != null && typeof source === 'object' && typeof source.code === 'string'
22315
22351
  ? source
22316
- : error(errBadLoader(id));
22352
+ : error(errorBadLoader(id));
22317
22353
  const cachedModule = this.graph.cachedModules.get(id);
22318
22354
  if (cachedModule &&
22319
22355
  !cachedModule.customTransformCache &&
@@ -22383,7 +22419,7 @@ class ModuleLoader {
22383
22419
  const existingModule = this.modulesById.get(id);
22384
22420
  if (existingModule instanceof Module) {
22385
22421
  if (importer && doAssertionsDiffer(assertions, existingModule.info.assertions)) {
22386
- this.options.onwarn(errInconsistentImportAssertions(existingModule.info.assertions, assertions, id, importer));
22422
+ this.options.onwarn(errorInconsistentImportAssertions(existingModule.info.assertions, assertions, id, importer));
22387
22423
  }
22388
22424
  await this.handleExistingModule(existingModule, isEntry, isPreload);
22389
22425
  return existingModule;
@@ -22432,10 +22468,10 @@ class ModuleLoader {
22432
22468
  this.modulesById.set(id, externalModule);
22433
22469
  }
22434
22470
  else if (!(externalModule instanceof ExternalModule)) {
22435
- return error(errInternalIdCannotBeExternal(source, importer));
22471
+ return error(errorInternalIdCannotBeExternal(source, importer));
22436
22472
  }
22437
22473
  else if (doAssertionsDiffer(externalModule.info.assertions, assertions)) {
22438
- this.options.onwarn(errInconsistentImportAssertions(externalModule.info.assertions, assertions, source, importer));
22474
+ this.options.onwarn(errorInconsistentImportAssertions(externalModule.info.assertions, assertions, source, importer));
22439
22475
  }
22440
22476
  return Promise.resolve(externalModule);
22441
22477
  }
@@ -22502,6 +22538,7 @@ class ModuleLoader {
22502
22538
  });
22503
22539
  }
22504
22540
  getResolveStaticDependencyPromises(module) {
22541
+ // eslint-disable-next-line unicorn/prefer-spread
22505
22542
  return Array.from(module.sourcesWithAssertions, async ([source, assertions]) => [
22506
22543
  source,
22507
22544
  (module.resolvedIds[source] =
@@ -22543,9 +22580,9 @@ class ModuleLoader {
22543
22580
  handleInvalidResolvedId(resolvedId, source, importer, assertions) {
22544
22581
  if (resolvedId === null) {
22545
22582
  if (isRelative(source)) {
22546
- return error(errUnresolvedImport(source, importer));
22583
+ return error(errorUnresolvedImport(source, importer));
22547
22584
  }
22548
- this.options.onwarn(errUnresolvedImportTreatedAsExternal(source, importer));
22585
+ this.options.onwarn(errorUnresolvedImportTreatedAsExternal(source, importer));
22549
22586
  return {
22550
22587
  assertions,
22551
22588
  external: true,
@@ -22556,7 +22593,7 @@ class ModuleLoader {
22556
22593
  };
22557
22594
  }
22558
22595
  else if (resolvedId.external && resolvedId.syntheticNamedExports) {
22559
- this.options.onwarn(errExternalSyntheticExports(source, importer));
22596
+ this.options.onwarn(errorExternalSyntheticExports(source, importer));
22560
22597
  }
22561
22598
  return resolvedId;
22562
22599
  }
@@ -22564,14 +22601,14 @@ class ModuleLoader {
22564
22601
  const resolveIdResult = await resolveId(unresolvedId, importer, this.options.preserveSymlinks, this.pluginDriver, this.resolveId, null, EMPTY_OBJECT, true, EMPTY_OBJECT);
22565
22602
  if (resolveIdResult == null) {
22566
22603
  return error(implicitlyLoadedBefore === null
22567
- ? errUnresolvedEntry(unresolvedId)
22568
- : errUnresolvedImplicitDependant(unresolvedId, implicitlyLoadedBefore));
22604
+ ? errorUnresolvedEntry(unresolvedId)
22605
+ : errorUnresolvedImplicitDependant(unresolvedId, implicitlyLoadedBefore));
22569
22606
  }
22570
22607
  if (resolveIdResult === false ||
22571
22608
  (typeof resolveIdResult === 'object' && resolveIdResult.external)) {
22572
22609
  return error(implicitlyLoadedBefore === null
22573
- ? errEntryCannotBeExternal(unresolvedId)
22574
- : errImplicitDependantCannotBeExternal(unresolvedId, implicitlyLoadedBefore));
22610
+ ? errorEntryCannotBeExternal(unresolvedId)
22611
+ : errorImplicitDependantCannotBeExternal(unresolvedId, implicitlyLoadedBefore));
22575
22612
  }
22576
22613
  return this.fetchModule(this.getResolvedIdWithDefaults(typeof resolveIdResult === 'object'
22577
22614
  ? resolveIdResult
@@ -22596,7 +22633,7 @@ class ModuleLoader {
22596
22633
  const existingResolution = module.resolvedIds[specifier];
22597
22634
  if (existingResolution) {
22598
22635
  if (doAssertionsDiffer(existingResolution.assertions, assertions)) {
22599
- this.options.onwarn(errInconsistentImportAssertions(existingResolution.assertions, assertions, specifier, importer));
22636
+ this.options.onwarn(errorInconsistentImportAssertions(existingResolution.assertions, assertions, specifier, importer));
22600
22637
  }
22601
22638
  return existingResolution;
22602
22639
  }
@@ -22655,18 +22692,18 @@ function generateAssetFileName(name, source, outputOptions, bundle) {
22655
22692
  return makeUnique(renderNamePattern(typeof outputOptions.assetFileNames === 'function'
22656
22693
  ? outputOptions.assetFileNames({ name, source, type: 'asset' })
22657
22694
  : outputOptions.assetFileNames, 'output.assetFileNames', {
22658
- ext: () => extname(emittedName).substring(1),
22695
+ ext: () => extname(emittedName).slice(1),
22659
22696
  extname: () => extname(emittedName),
22660
22697
  hash: size => createHash()
22661
22698
  .update(source)
22662
22699
  .digest('hex')
22663
- .substring(0, size || defaultHashSize),
22664
- name: () => emittedName.substring(0, emittedName.length - extname(emittedName).length)
22700
+ .slice(0, Math.max(0, size || defaultHashSize)),
22701
+ name: () => emittedName.slice(0, Math.max(0, emittedName.length - extname(emittedName).length))
22665
22702
  }), bundle);
22666
22703
  }
22667
22704
  function reserveFileNameInBundle(fileName, { bundle }, warn) {
22668
22705
  if (bundle[lowercaseBundleKeys].has(fileName.toLowerCase())) {
22669
- warn(errFileNameConflict(fileName));
22706
+ warn(errorFileNameConflict(fileName));
22670
22707
  }
22671
22708
  else {
22672
22709
  bundle[fileName] = FILE_PLACEHOLDER;
@@ -22684,13 +22721,13 @@ function hasValidName(emittedFile) {
22684
22721
  function getValidSource(source, emittedFile, fileReferenceId) {
22685
22722
  if (!(typeof source === 'string' || source instanceof Uint8Array)) {
22686
22723
  const assetName = emittedFile.fileName || emittedFile.name || fileReferenceId;
22687
- 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.`));
22724
+ return error(errorFailedValidation(`Could not set source for ${typeof assetName === 'string' ? `asset "${assetName}"` : 'unnamed asset'}, asset source needs to be a string, Uint8Array or Buffer.`));
22688
22725
  }
22689
22726
  return source;
22690
22727
  }
22691
22728
  function getAssetFileName(file, referenceId) {
22692
22729
  if (typeof file.fileName !== 'string') {
22693
- return error(errAssetNotFinalisedForFileName(file.name || referenceId));
22730
+ return error(errorAssetNotFinalisedForFileName(file.name || referenceId));
22694
22731
  }
22695
22732
  return file.fileName;
22696
22733
  }
@@ -22702,7 +22739,7 @@ function getChunkFileName(file, facadeChunkByModule) {
22702
22739
  const chunk = facadeChunkByModule.get(file.module);
22703
22740
  return chunk.id || chunk.getFileName();
22704
22741
  }
22705
- return error(errChunkNotGeneratedForFileName(file.fileName || file.name));
22742
+ return error(errorChunkNotGeneratedForFileName(file.fileName || file.name));
22706
22743
  }
22707
22744
  class FileEmitter {
22708
22745
  constructor(graph, options, baseFileEmitter) {
@@ -22713,10 +22750,10 @@ class FileEmitter {
22713
22750
  this.output = null;
22714
22751
  this.emitFile = (emittedFile) => {
22715
22752
  if (!hasValidType(emittedFile)) {
22716
- return error(errFailedValidation(`Emitted files must be of type "asset" or "chunk", received "${emittedFile && emittedFile.type}".`));
22753
+ return error(errorFailedValidation(`Emitted files must be of type "asset" or "chunk", received "${emittedFile && emittedFile.type}".`));
22717
22754
  }
22718
22755
  if (!hasValidName(emittedFile)) {
22719
- 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}".`));
22756
+ return error(errorFailedValidation(`The "fileName" or "name" properties of emitted files must be strings that are neither absolute nor relative paths, received "${emittedFile.fileName || emittedFile.name}".`));
22720
22757
  }
22721
22758
  if (emittedFile.type === 'chunk') {
22722
22759
  return this.emitChunk(emittedFile);
@@ -22726,13 +22763,13 @@ class FileEmitter {
22726
22763
  this.finaliseAssets = () => {
22727
22764
  for (const [referenceId, emittedFile] of this.filesByReferenceId) {
22728
22765
  if (emittedFile.type === 'asset' && typeof emittedFile.fileName !== 'string')
22729
- return error(errNoAssetSourceSet(emittedFile.name || referenceId));
22766
+ return error(errorNoAssetSourceSet(emittedFile.name || referenceId));
22730
22767
  }
22731
22768
  };
22732
22769
  this.getFileName = (fileReferenceId) => {
22733
22770
  const emittedFile = this.filesByReferenceId.get(fileReferenceId);
22734
22771
  if (!emittedFile)
22735
- return error(errFileReferenceIdNotFoundForFilename(fileReferenceId));
22772
+ return error(errorFileReferenceIdNotFoundForFilename(fileReferenceId));
22736
22773
  if (emittedFile.type === 'chunk') {
22737
22774
  return getChunkFileName(emittedFile, this.facadeChunkByModule);
22738
22775
  }
@@ -22741,12 +22778,12 @@ class FileEmitter {
22741
22778
  this.setAssetSource = (referenceId, requestedSource) => {
22742
22779
  const consumedFile = this.filesByReferenceId.get(referenceId);
22743
22780
  if (!consumedFile)
22744
- return error(errAssetReferenceIdNotFoundForSetSource(referenceId));
22781
+ return error(errorAssetReferenceIdNotFoundForSetSource(referenceId));
22745
22782
  if (consumedFile.type !== 'asset') {
22746
- return error(errFailedValidation(`Asset sources can only be set for emitted assets but "${referenceId}" is an emitted chunk.`));
22783
+ return error(errorFailedValidation(`Asset sources can only be set for emitted assets but "${referenceId}" is an emitted chunk.`));
22747
22784
  }
22748
22785
  if (consumedFile.source !== undefined) {
22749
- return error(errAssetSourceAlreadySet(consumedFile.name || referenceId));
22786
+ return error(errorAssetSourceAlreadySet(consumedFile.name || referenceId));
22750
22787
  }
22751
22788
  const source = getValidSource(requestedSource, consumedFile, referenceId);
22752
22789
  if (this.output) {
@@ -22786,7 +22823,7 @@ class FileEmitter {
22786
22823
  referenceId = createHash()
22787
22824
  .update(referenceId || idBase)
22788
22825
  .digest('hex')
22789
- .substring(0, 8);
22826
+ .slice(0, 8);
22790
22827
  } while (this.filesByReferenceId.has(referenceId));
22791
22828
  this.filesByReferenceId.set(referenceId, file);
22792
22829
  return referenceId;
@@ -22814,10 +22851,10 @@ class FileEmitter {
22814
22851
  }
22815
22852
  emitChunk(emittedChunk) {
22816
22853
  if (this.graph.phase > BuildPhase.LOAD_AND_PARSE) {
22817
- return error(errInvalidRollupPhaseForChunkEmission());
22854
+ return error(errorInvalidRollupPhaseForChunkEmission());
22818
22855
  }
22819
22856
  if (typeof emittedChunk.id !== 'string') {
22820
- return error(errFailedValidation(`Emitted chunks need to have a valid string id, received "${emittedChunk.id}"`));
22857
+ return error(errorFailedValidation(`Emitted chunks need to have a valid string id, received "${emittedChunk.id}"`));
22821
22858
  }
22822
22859
  const consumedChunk = {
22823
22860
  fileName: emittedChunk.fileName,
@@ -22879,14 +22916,14 @@ function getPluginContext(plugin, pluginCache, graph, options, fileEmitter, exis
22879
22916
  return {
22880
22917
  addWatchFile(id) {
22881
22918
  if (graph.phase >= BuildPhase.GENERATE) {
22882
- return this.error(errInvalidRollupPhaseForAddWatchFile());
22919
+ return this.error(errorInvalidRollupPhaseForAddWatchFile());
22883
22920
  }
22884
22921
  graph.watchFiles[id] = true;
22885
22922
  },
22886
22923
  cache: cacheInstance,
22887
22924
  emitFile: fileEmitter.emitFile.bind(fileEmitter),
22888
- error(err) {
22889
- return error(errPluginError(err, plugin.name));
22925
+ error(error_) {
22926
+ return error(errorPluginError(error_, plugin.name));
22890
22927
  },
22891
22928
  getFileName: fileEmitter.getFileName,
22892
22929
  getModuleIds: () => graph.modulesById.keys(),
@@ -22957,7 +22994,7 @@ class PluginDriver {
22957
22994
  this.finaliseAssets = this.fileEmitter.finaliseAssets.bind(this.fileEmitter);
22958
22995
  this.setChunkInformation = this.fileEmitter.setChunkInformation.bind(this.fileEmitter);
22959
22996
  this.setOutputBundle = this.fileEmitter.setOutputBundle.bind(this.fileEmitter);
22960
- this.plugins = (basePluginDriver ? basePluginDriver.plugins : []).concat(userPlugins);
22997
+ this.plugins = [...(basePluginDriver ? basePluginDriver.plugins : []), ...userPlugins];
22961
22998
  const existingPluginNames = new Set();
22962
22999
  this.pluginContexts = new Map(this.plugins.map(plugin => [
22963
23000
  plugin,
@@ -22967,7 +23004,7 @@ class PluginDriver {
22967
23004
  for (const plugin of userPlugins) {
22968
23005
  for (const hook of inputHooks) {
22969
23006
  if (hook in plugin) {
22970
- options.onwarn(errInputHookInOutputPlugin(plugin.name, hook));
23007
+ options.onwarn(errorInputHookInOutputPlugin(plugin.name, hook));
22971
23008
  }
22972
23009
  }
22973
23010
  }
@@ -22980,7 +23017,7 @@ class PluginDriver {
22980
23017
  return this.unfulfilledActions;
22981
23018
  }
22982
23019
  // chains, first non-null result stops and returns
22983
- hookFirst(hookName, args, replaceContext, skipped) {
23020
+ hookFirst(hookName, parameters, replaceContext, skipped) {
22984
23021
  let promise = Promise.resolve(null);
22985
23022
  for (const plugin of this.getSortedPlugins(hookName)) {
22986
23023
  if (skipped && skipped.has(plugin))
@@ -22988,83 +23025,83 @@ class PluginDriver {
22988
23025
  promise = promise.then(result => {
22989
23026
  if (result != null)
22990
23027
  return result;
22991
- return this.runHook(hookName, args, plugin, replaceContext);
23028
+ return this.runHook(hookName, parameters, plugin, replaceContext);
22992
23029
  });
22993
23030
  }
22994
23031
  return promise;
22995
23032
  }
22996
23033
  // chains synchronously, first non-null result stops and returns
22997
- hookFirstSync(hookName, args, replaceContext) {
23034
+ hookFirstSync(hookName, parameters, replaceContext) {
22998
23035
  for (const plugin of this.getSortedPlugins(hookName)) {
22999
- const result = this.runHookSync(hookName, args, plugin, replaceContext);
23036
+ const result = this.runHookSync(hookName, parameters, plugin, replaceContext);
23000
23037
  if (result != null)
23001
23038
  return result;
23002
23039
  }
23003
23040
  return null;
23004
23041
  }
23005
23042
  // parallel, ignores returns
23006
- async hookParallel(hookName, args, replaceContext) {
23043
+ async hookParallel(hookName, parameters, replaceContext) {
23007
23044
  const parallelPromises = [];
23008
23045
  for (const plugin of this.getSortedPlugins(hookName)) {
23009
23046
  if (plugin[hookName].sequential) {
23010
23047
  await Promise.all(parallelPromises);
23011
23048
  parallelPromises.length = 0;
23012
- await this.runHook(hookName, args, plugin, replaceContext);
23049
+ await this.runHook(hookName, parameters, plugin, replaceContext);
23013
23050
  }
23014
23051
  else {
23015
- parallelPromises.push(this.runHook(hookName, args, plugin, replaceContext));
23052
+ parallelPromises.push(this.runHook(hookName, parameters, plugin, replaceContext));
23016
23053
  }
23017
23054
  }
23018
23055
  await Promise.all(parallelPromises);
23019
23056
  }
23020
23057
  // chains, reduces returned value, handling the reduced value as the first hook argument
23021
- hookReduceArg0(hookName, [arg0, ...rest], reduce, replaceContext) {
23022
- let promise = Promise.resolve(arg0);
23058
+ hookReduceArg0(hookName, [argument0, ...rest], reduce, replaceContext) {
23059
+ let promise = Promise.resolve(argument0);
23023
23060
  for (const plugin of this.getSortedPlugins(hookName)) {
23024
- promise = promise.then(arg0 => this.runHook(hookName, [arg0, ...rest], plugin, replaceContext).then(result => reduce.call(this.pluginContexts.get(plugin), arg0, result, plugin)));
23061
+ promise = promise.then(argument0 => this.runHook(hookName, [argument0, ...rest], plugin, replaceContext).then(result => reduce.call(this.pluginContexts.get(plugin), argument0, result, plugin)));
23025
23062
  }
23026
23063
  return promise;
23027
23064
  }
23028
23065
  // chains synchronously, reduces returned value, handling the reduced value as the first hook argument
23029
- hookReduceArg0Sync(hookName, [arg0, ...rest], reduce, replaceContext) {
23066
+ hookReduceArg0Sync(hookName, [argument0, ...rest], reduce, replaceContext) {
23030
23067
  for (const plugin of this.getSortedPlugins(hookName)) {
23031
- const args = [arg0, ...rest];
23032
- const result = this.runHookSync(hookName, args, plugin, replaceContext);
23033
- arg0 = reduce.call(this.pluginContexts.get(plugin), arg0, result, plugin);
23068
+ const parameters = [argument0, ...rest];
23069
+ const result = this.runHookSync(hookName, parameters, plugin, replaceContext);
23070
+ argument0 = reduce.call(this.pluginContexts.get(plugin), argument0, result, plugin);
23034
23071
  }
23035
- return arg0;
23072
+ return argument0;
23036
23073
  }
23037
23074
  // chains, reduces returned value to type string, handling the reduced value separately. permits hooks as values.
23038
- async hookReduceValue(hookName, initialValue, args, reducer) {
23075
+ async hookReduceValue(hookName, initialValue, parameters, reducer) {
23039
23076
  const results = [];
23040
23077
  const parallelResults = [];
23041
23078
  for (const plugin of this.getSortedPlugins(hookName, validateAddonPluginHandler)) {
23042
23079
  if (plugin[hookName].sequential) {
23043
23080
  results.push(...(await Promise.all(parallelResults)));
23044
23081
  parallelResults.length = 0;
23045
- results.push(await this.runHook(hookName, args, plugin));
23082
+ results.push(await this.runHook(hookName, parameters, plugin));
23046
23083
  }
23047
23084
  else {
23048
- parallelResults.push(this.runHook(hookName, args, plugin));
23085
+ parallelResults.push(this.runHook(hookName, parameters, plugin));
23049
23086
  }
23050
23087
  }
23051
23088
  results.push(...(await Promise.all(parallelResults)));
23052
23089
  return results.reduce(reducer, await initialValue);
23053
23090
  }
23054
23091
  // chains synchronously, reduces returned value to type T, handling the reduced value separately. permits hooks as values.
23055
- hookReduceValueSync(hookName, initialValue, args, reduce, replaceContext) {
23056
- let acc = initialValue;
23092
+ hookReduceValueSync(hookName, initialValue, parameters, reduce, replaceContext) {
23093
+ let accumulator = initialValue;
23057
23094
  for (const plugin of this.getSortedPlugins(hookName)) {
23058
- const result = this.runHookSync(hookName, args, plugin, replaceContext);
23059
- acc = reduce.call(this.pluginContexts.get(plugin), acc, result, plugin);
23095
+ const result = this.runHookSync(hookName, parameters, plugin, replaceContext);
23096
+ accumulator = reduce.call(this.pluginContexts.get(plugin), accumulator, result, plugin);
23060
23097
  }
23061
- return acc;
23098
+ return accumulator;
23062
23099
  }
23063
23100
  // chains, ignores returns
23064
- hookSeq(hookName, args, replaceContext) {
23101
+ hookSeq(hookName, parameters, replaceContext) {
23065
23102
  let promise = Promise.resolve();
23066
23103
  for (const plugin of this.getSortedPlugins(hookName)) {
23067
- promise = promise.then(() => this.runHook(hookName, args, plugin, replaceContext));
23104
+ promise = promise.then(() => this.runHook(hookName, parameters, plugin, replaceContext));
23068
23105
  }
23069
23106
  return promise.then(noReturn);
23070
23107
  }
@@ -23072,7 +23109,7 @@ class PluginDriver {
23072
23109
  return getOrCreate(this.sortedPlugins, hookName, () => getSortedValidatedPlugins(hookName, this.plugins, validateHandler));
23073
23110
  }
23074
23111
  // Implementation signature
23075
- runHook(hookName, args, plugin, replaceContext) {
23112
+ runHook(hookName, parameters, plugin, replaceContext) {
23076
23113
  // We always filter for plugins that support the hook before running it
23077
23114
  const hook = plugin[hookName];
23078
23115
  const handler = typeof hook === 'object' ? hook.handler : hook;
@@ -23087,7 +23124,7 @@ class PluginDriver {
23087
23124
  return handler;
23088
23125
  }
23089
23126
  // eslint-disable-next-line @typescript-eslint/ban-types
23090
- const hookResult = handler.apply(context, args);
23127
+ const hookResult = handler.apply(context, parameters);
23091
23128
  if (!hookResult?.then) {
23092
23129
  // short circuit for non-thenables and non-Promises
23093
23130
  return hookResult;
@@ -23096,7 +23133,7 @@ class PluginDriver {
23096
23133
  // unfulfilled promises cause rollup to abruptly and confusingly
23097
23134
  // exit with a successful 0 return code but without producing any
23098
23135
  // output, errors or warnings.
23099
- action = [plugin.name, hookName, args];
23136
+ action = [plugin.name, hookName, parameters];
23100
23137
  this.unfulfilledActions.add(action);
23101
23138
  // Although it would be more elegant to just return hookResult here
23102
23139
  // and put the .then() handler just above the .catch() handler below,
@@ -23108,12 +23145,12 @@ class PluginDriver {
23108
23145
  return result;
23109
23146
  });
23110
23147
  })
23111
- .catch(err => {
23148
+ .catch(error_ => {
23112
23149
  if (action !== null) {
23113
23150
  // action considered to be fulfilled since error being handled
23114
23151
  this.unfulfilledActions.delete(action);
23115
23152
  }
23116
- return error(errPluginError(err, plugin.name, { hook: hookName }));
23153
+ return error(errorPluginError(error_, plugin.name, { hook: hookName }));
23117
23154
  });
23118
23155
  }
23119
23156
  /**
@@ -23123,7 +23160,7 @@ class PluginDriver {
23123
23160
  * @param plugin The acutal plugin
23124
23161
  * @param replaceContext When passed, the plugin context can be overridden.
23125
23162
  */
23126
- runHookSync(hookName, args, plugin, replaceContext) {
23163
+ runHookSync(hookName, parameters, plugin, replaceContext) {
23127
23164
  const hook = plugin[hookName];
23128
23165
  const handler = typeof hook === 'object' ? hook.handler : hook;
23129
23166
  let context = this.pluginContexts.get(plugin);
@@ -23132,10 +23169,10 @@ class PluginDriver {
23132
23169
  }
23133
23170
  try {
23134
23171
  // eslint-disable-next-line @typescript-eslint/ban-types
23135
- return handler.apply(context, args);
23172
+ return handler.apply(context, parameters);
23136
23173
  }
23137
- catch (err) {
23138
- return error(errPluginError(err, plugin.name, { hook: hookName }));
23174
+ catch (error_) {
23175
+ return error(errorPluginError(error_, plugin.name, { hook: hookName }));
23139
23176
  }
23140
23177
  }
23141
23178
  }
@@ -23167,12 +23204,12 @@ function getSortedValidatedPlugins(hookName, plugins, validateHandler = validate
23167
23204
  }
23168
23205
  function validateFunctionPluginHandler(handler, hookName, plugin) {
23169
23206
  if (typeof handler !== 'function') {
23170
- error(errInvalidFunctionPluginHook(hookName, plugin.name));
23207
+ error(errorInvalidFunctionPluginHook(hookName, plugin.name));
23171
23208
  }
23172
23209
  }
23173
23210
  function validateAddonPluginHandler(handler, hookName, plugin) {
23174
23211
  if (typeof handler !== 'string' && typeof handler !== 'function') {
23175
- return error(errInvalidAddonPluginHook(hookName, plugin.name));
23212
+ return error(errorInvalidAddonPluginHook(hookName, plugin.name));
23176
23213
  }
23177
23214
  }
23178
23215
  function noReturn() { }
@@ -23200,8 +23237,8 @@ class Queue {
23200
23237
  const result = await task();
23201
23238
  resolve(result);
23202
23239
  }
23203
- catch (err) {
23204
- reject(err);
23240
+ catch (error) {
23241
+ reject(error);
23205
23242
  }
23206
23243
  }
23207
23244
  this.workerCount--;
@@ -23262,7 +23299,7 @@ class Graph {
23262
23299
  }
23263
23300
  if (watcher) {
23264
23301
  this.watchMode = true;
23265
- const handleChange = (...args) => this.pluginDriver.hookParallel('watchChange', args);
23302
+ const handleChange = (...parameters) => this.pluginDriver.hookParallel('watchChange', parameters);
23266
23303
  const handleClose = () => this.pluginDriver.hookParallel('closeWatcher', []);
23267
23304
  watcher.onCurrentRun('change', handleChange);
23268
23305
  watcher.onCurrentRun('close', handleClose);
@@ -23288,15 +23325,13 @@ class Graph {
23288
23325
  contextParse(code, options = {}) {
23289
23326
  const onCommentOrig = options.onComment;
23290
23327
  const comments = [];
23291
- if (onCommentOrig && typeof onCommentOrig == 'function') {
23292
- options.onComment = (block, text, start, end, ...args) => {
23293
- comments.push({ end, start, type: block ? 'Block' : 'Line', value: text });
23294
- return onCommentOrig.call(options, block, text, start, end, ...args);
23295
- };
23296
- }
23297
- else {
23298
- options.onComment = comments;
23299
- }
23328
+ options.onComment =
23329
+ onCommentOrig && typeof onCommentOrig == 'function'
23330
+ ? (block, text, start, end, ...parameters) => {
23331
+ comments.push({ end, start, type: block ? 'Block' : 'Line', value: text });
23332
+ return onCommentOrig.call(options, block, text, start, end, ...parameters);
23333
+ }
23334
+ : comments;
23300
23335
  const ast = this.acornParser.parse(code, {
23301
23336
  ...this.options.acorn,
23302
23337
  ...options
@@ -23383,7 +23418,7 @@ class Graph {
23383
23418
  for (const module of this.implicitEntryModules) {
23384
23419
  for (const dependant of module.implicitlyLoadedAfter) {
23385
23420
  if (!(dependant.info.isEntry || dependant.isIncluded())) {
23386
- error(errImplicitDependantIsNotIncluded(dependant));
23421
+ error(errorImplicitDependantIsNotIncluded(dependant));
23387
23422
  }
23388
23423
  }
23389
23424
  }
@@ -23391,7 +23426,7 @@ class Graph {
23391
23426
  sortModules() {
23392
23427
  const { orderedModules, cyclePaths } = analyseModuleExecution(this.entryModules);
23393
23428
  for (const cyclePath of cyclePaths) {
23394
- this.options.onwarn(errCircularDependency(cyclePath));
23429
+ this.options.onwarn(errorCircularDependency(cyclePath));
23395
23430
  }
23396
23431
  this.modules = orderedModules;
23397
23432
  for (const module of this.modules) {
@@ -23404,37 +23439,32 @@ class Graph {
23404
23439
  for (const importDescription of module.importDescriptions.values()) {
23405
23440
  if (importDescription.name !== '*' &&
23406
23441
  !importDescription.module.getVariableForExportName(importDescription.name)[0]) {
23407
- module.warn(errMissingExport(importDescription.name, module.id, importDescription.module.id), importDescription.start);
23442
+ module.warn(errorMissingExport(importDescription.name, module.id, importDescription.module.id), importDescription.start);
23408
23443
  }
23409
23444
  }
23410
23445
  }
23411
23446
  }
23412
23447
  }
23413
23448
 
23414
- function ensureArray(items) {
23415
- if (Array.isArray(items)) {
23416
- return items.filter(Boolean);
23417
- }
23418
- if (items) {
23419
- return [items];
23420
- }
23421
- return [];
23422
- }
23423
-
23424
- function formatAction([pluginName, hookName, args]) {
23449
+ function formatAction([pluginName, hookName, parameters]) {
23425
23450
  const action = `(${pluginName}) ${hookName}`;
23426
23451
  const s = JSON.stringify;
23427
23452
  switch (hookName) {
23428
- case 'resolveId':
23429
- return `${action} ${s(args[0])} ${s(args[1])}`;
23430
- case 'load':
23431
- return `${action} ${s(args[0])}`;
23432
- case 'transform':
23433
- return `${action} ${s(args[1])}`;
23434
- case 'shouldTransformCachedModule':
23435
- return `${action} ${s(args[0].id)}`;
23436
- case 'moduleParsed':
23437
- return `${action} ${s(args[0].id)}`;
23453
+ case 'resolveId': {
23454
+ return `${action} ${s(parameters[0])} ${s(parameters[1])}`;
23455
+ }
23456
+ case 'load': {
23457
+ return `${action} ${s(parameters[0])}`;
23458
+ }
23459
+ case 'transform': {
23460
+ return `${action} ${s(parameters[1])}`;
23461
+ }
23462
+ case 'shouldTransformCachedModule': {
23463
+ return `${action} ${s(parameters[0].id)}`;
23464
+ }
23465
+ case 'moduleParsed': {
23466
+ return `${action} ${s(parameters[0].id)}`;
23467
+ }
23438
23468
  }
23439
23469
  return action;
23440
23470
  }
@@ -23748,12 +23778,29 @@ function importAssertions(Parser) {
23748
23778
  };
23749
23779
  }
23750
23780
 
23781
+ function ensureArray(items) {
23782
+ if (Array.isArray(items)) {
23783
+ return items.filter(Boolean);
23784
+ }
23785
+ if (items) {
23786
+ return [items];
23787
+ }
23788
+ return [];
23789
+ }
23790
+
23791
+ async function asyncFlatten(array) {
23792
+ do {
23793
+ array = (await Promise.all(array)).flat(Infinity);
23794
+ } while (array.some((v) => v?.then));
23795
+ return array;
23796
+ }
23797
+
23751
23798
  const defaultOnWarn = warning => console.warn(warning.message || warning);
23752
23799
  function warnUnknownOptions(passedOptions, validOptions, optionType, warn, ignoredKeys = /$./) {
23753
23800
  const validOptionSet = new Set(validOptions);
23754
23801
  const unknownOptions = Object.keys(passedOptions).filter(key => !(validOptionSet.has(key) || ignoredKeys.test(key)));
23755
23802
  if (unknownOptions.length > 0) {
23756
- warn(errUnknownOption(optionType, unknownOptions, [...validOptionSet].sort()));
23803
+ warn(errorUnknownOption(optionType, unknownOptions, [...validOptionSet].sort()));
23757
23804
  }
23758
23805
  }
23759
23806
  const treeshakePresets = {
@@ -23805,7 +23852,7 @@ const objectifyOptionWithPresets = (presets, optionName, additionalValues) => (v
23805
23852
  if (preset) {
23806
23853
  return preset;
23807
23854
  }
23808
- error(errInvalidOption(optionName, getHashFromObjectOption(optionName), `valid values are ${additionalValues}${printQuotedStringList(Object.keys(presets))}. You can also supply an object for more fine-grained control`, value));
23855
+ error(errorInvalidOption(optionName, getHashFromObjectOption(optionName), `valid values are ${additionalValues}${printQuotedStringList(Object.keys(presets))}. You can also supply an object for more fine-grained control`, value));
23809
23856
  }
23810
23857
  return objectifyOption(value);
23811
23858
  };
@@ -23817,15 +23864,15 @@ const getOptionWithPreset = (value, presets, optionName, additionalValues) => {
23817
23864
  return { ...preset, ...value };
23818
23865
  }
23819
23866
  else {
23820
- error(errInvalidOption(`${optionName}.preset`, getHashFromObjectOption(optionName), `valid values are ${printQuotedStringList(Object.keys(presets))}`, presetName));
23867
+ error(errorInvalidOption(`${optionName}.preset`, getHashFromObjectOption(optionName), `valid values are ${printQuotedStringList(Object.keys(presets))}`, presetName));
23821
23868
  }
23822
23869
  }
23823
23870
  return objectifyOptionWithPresets(presets, optionName, additionalValues)(value);
23824
23871
  };
23825
23872
  const getHashFromObjectOption = (optionName) => optionName.split('.').join('').toLowerCase();
23826
- const normalizePluginOption = (plugins) => [plugins].flat(Infinity).filter(Boolean);
23873
+ const normalizePluginOption = async (plugins) => (await asyncFlatten([plugins])).filter(Boolean);
23827
23874
 
23828
- function normalizeInputOptions(config) {
23875
+ async function normalizeInputOptions(config) {
23829
23876
  // These are options that may trigger special warnings or behaviour later
23830
23877
  // if the user did not select an explicit value
23831
23878
  const unsetOptions = new Set();
@@ -23849,7 +23896,7 @@ function normalizeInputOptions(config) {
23849
23896
  moduleContext: getModuleContext(config, context),
23850
23897
  onwarn,
23851
23898
  perf: config.perf || false,
23852
- plugins: normalizePluginOption(config.plugins),
23899
+ plugins: await normalizePluginOption(config.plugins),
23853
23900
  preserveEntrySignatures: config.preserveEntrySignatures ?? 'exports-only',
23854
23901
  preserveModules: getPreserveModules$1(config, onwarn, strictDeprecations),
23855
23902
  preserveSymlinks: config.preserveSymlinks || false,
@@ -23865,13 +23912,13 @@ const getOnwarn = (config) => {
23865
23912
  return onwarn
23866
23913
  ? warning => {
23867
23914
  warning.toString = () => {
23868
- let str = '';
23915
+ let warningString = '';
23869
23916
  if (warning.plugin)
23870
- str += `(${warning.plugin} plugin) `;
23917
+ warningString += `(${warning.plugin} plugin) `;
23871
23918
  if (warning.loc)
23872
- str += `${relativeId(warning.loc.file)} (${warning.loc.line}:${warning.loc.column}) `;
23873
- str += warning.message;
23874
- return str;
23919
+ warningString += `${relativeId(warning.loc.file)} (${warning.loc.line}:${warning.loc.column}) `;
23920
+ warningString += warning.message;
23921
+ return warningString;
23875
23922
  };
23876
23923
  onwarn(warning, defaultOnWarn);
23877
23924
  }
@@ -23894,7 +23941,7 @@ const getIdMatcher = (option) => {
23894
23941
  return () => true;
23895
23942
  }
23896
23943
  if (typeof option === 'function') {
23897
- return (id, ...args) => (!id.startsWith('\0') && option(id, ...args)) || false;
23944
+ return (id, ...parameters) => (!id.startsWith('\0') && option(id, ...parameters)) || false;
23898
23945
  }
23899
23946
  if (option) {
23900
23947
  const ids = new Set();
@@ -23907,7 +23954,7 @@ const getIdMatcher = (option) => {
23907
23954
  ids.add(value);
23908
23955
  }
23909
23956
  }
23910
- return (id, ..._args) => ids.has(id) || matchers.some(matcher => matcher.test(id));
23957
+ return (id, ..._arguments) => ids.has(id) || matchers.some(matcher => matcher.test(id));
23911
23958
  }
23912
23959
  return () => false;
23913
23960
  };
@@ -23995,34 +24042,34 @@ const getHasModuleSideEffects = (moduleSideEffectsOption) => {
23995
24042
  return id => ids.has(id);
23996
24043
  }
23997
24044
  if (moduleSideEffectsOption) {
23998
- error(errInvalidOption('treeshake.moduleSideEffects', 'treeshake', 'please use one of false, "no-external", a function or an array'));
24045
+ error(errorInvalidOption('treeshake.moduleSideEffects', 'treeshake', 'please use one of false, "no-external", a function or an array'));
23999
24046
  }
24000
24047
  return () => true;
24001
24048
  };
24002
24049
 
24003
24050
  // https://datatracker.ietf.org/doc/html/rfc2396
24004
24051
  // eslint-disable-next-line no-control-regex
24005
- const INVALID_CHAR_REGEX = /[\x00-\x1F\x7F<>*#"{}|^[\]`;?:&=+$,]/g;
24052
+ const INVALID_CHAR_REGEX = /[\u0000-\u001F"#$&*+,:;<=>?[\]^`{|}\u007F]/g;
24006
24053
  const DRIVE_LETTER_REGEX = /^[a-z]:/i;
24007
24054
  function sanitizeFileName(name) {
24008
24055
  const match = DRIVE_LETTER_REGEX.exec(name);
24009
24056
  const driveLetter = match ? match[0] : '';
24010
24057
  // A `:` is only allowed as part of a windows drive letter (ex: C:\foo)
24011
24058
  // Otherwise, avoid them because they can refer to NTFS alternate data streams.
24012
- return driveLetter + name.substr(driveLetter.length).replace(INVALID_CHAR_REGEX, '_');
24059
+ return driveLetter + name.slice(driveLetter.length).replace(INVALID_CHAR_REGEX, '_');
24013
24060
  }
24014
24061
 
24015
24062
  function isValidUrl(url) {
24016
24063
  try {
24017
24064
  new URL(url);
24018
24065
  }
24019
- catch (_) {
24066
+ catch {
24020
24067
  return false;
24021
24068
  }
24022
24069
  return true;
24023
24070
  }
24024
24071
 
24025
- function normalizeOutputOptions(config, inputOptions, unsetInputOptions) {
24072
+ async function normalizeOutputOptions(config, inputOptions, unsetInputOptions) {
24026
24073
  // These are options that may trigger special warnings or behaviour later
24027
24074
  // if the user did not select an explicit value
24028
24075
  const unsetOptions = new Set(unsetInputOptions);
@@ -24066,7 +24113,7 @@ function normalizeOutputOptions(config, inputOptions, unsetInputOptions) {
24066
24113
  noConflict: config.noConflict || false,
24067
24114
  outro: getAddon(config, 'outro'),
24068
24115
  paths: config.paths || {},
24069
- plugins: normalizePluginOption(config.plugins),
24116
+ plugins: await normalizePluginOption(config.plugins),
24070
24117
  preferConst,
24071
24118
  preserveModules,
24072
24119
  preserveModulesRoot: getPreserveModulesRoot(config),
@@ -24091,10 +24138,10 @@ const getFile = (config, preserveModules, inputOptions) => {
24091
24138
  const { file } = config;
24092
24139
  if (typeof file === 'string') {
24093
24140
  if (preserveModules) {
24094
- return error(errInvalidOption('output.file', 'outputdir', 'you must set "output.dir" instead of "output.file" when using the "output.preserveModules" option'));
24141
+ return error(errorInvalidOption('output.file', 'outputdir', 'you must set "output.dir" instead of "output.file" when using the "output.preserveModules" option'));
24095
24142
  }
24096
24143
  if (!Array.isArray(inputOptions.input))
24097
- return error(errInvalidOption('output.file', 'outputdir', 'you must set "output.dir" instead of "output.file" when providing named inputs'));
24144
+ return error(errorInvalidOption('output.file', 'outputdir', 'you must set "output.dir" instead of "output.file" when providing named inputs'));
24098
24145
  }
24099
24146
  return file;
24100
24147
  };
@@ -24104,30 +24151,35 @@ const getFormat = (config) => {
24104
24151
  case undefined:
24105
24152
  case 'es':
24106
24153
  case 'esm':
24107
- case 'module':
24154
+ case 'module': {
24108
24155
  return 'es';
24156
+ }
24109
24157
  case 'cjs':
24110
- case 'commonjs':
24158
+ case 'commonjs': {
24111
24159
  return 'cjs';
24160
+ }
24112
24161
  case 'system':
24113
- case 'systemjs':
24162
+ case 'systemjs': {
24114
24163
  return 'system';
24164
+ }
24115
24165
  case 'amd':
24116
24166
  case 'iife':
24117
- case 'umd':
24167
+ case 'umd': {
24118
24168
  return configFormat;
24119
- default:
24169
+ }
24170
+ default: {
24120
24171
  return error({
24121
24172
  message: `You must specify "output.format", which can be one of "amd", "cjs", "system", "es", "iife" or "umd".`,
24122
24173
  url: `https://rollupjs.org/guide/en/#outputformat`
24123
24174
  });
24175
+ }
24124
24176
  }
24125
24177
  };
24126
24178
  const getInlineDynamicImports = (config, inputOptions) => {
24127
24179
  const inlineDynamicImports = (config.inlineDynamicImports ?? inputOptions.inlineDynamicImports) || false;
24128
24180
  const { input } = inputOptions;
24129
24181
  if (inlineDynamicImports && (Array.isArray(input) ? input : Object.keys(input)).length > 1) {
24130
- return error(errInvalidOption('output.inlineDynamicImports', 'outputinlinedynamicimports', 'multiple inputs are not supported when "output.inlineDynamicImports" is true'));
24182
+ return error(errorInvalidOption('output.inlineDynamicImports', 'outputinlinedynamicimports', 'multiple inputs are not supported when "output.inlineDynamicImports" is true'));
24131
24183
  }
24132
24184
  return inlineDynamicImports;
24133
24185
  };
@@ -24135,10 +24187,10 @@ const getPreserveModules = (config, inlineDynamicImports, inputOptions) => {
24135
24187
  const preserveModules = (config.preserveModules ?? inputOptions.preserveModules) || false;
24136
24188
  if (preserveModules) {
24137
24189
  if (inlineDynamicImports) {
24138
- return error(errInvalidOption('output.inlineDynamicImports', 'outputinlinedynamicimports', `this option is not supported for "output.preserveModules"`));
24190
+ return error(errorInvalidOption('output.inlineDynamicImports', 'outputinlinedynamicimports', `this option is not supported for "output.preserveModules"`));
24139
24191
  }
24140
24192
  if (inputOptions.preserveEntrySignatures === false) {
24141
- return error(errInvalidOption('preserveEntrySignatures', 'preserveentrysignatures', 'setting this option to false is not supported for "output.preserveModules"'));
24193
+ return error(errorInvalidOption('preserveEntrySignatures', 'preserveentrysignatures', 'setting this option to false is not supported for "output.preserveModules"'));
24142
24194
  }
24143
24195
  }
24144
24196
  return preserveModules;
@@ -24166,29 +24218,24 @@ const getAmd = (config) => {
24166
24218
  ...config.amd
24167
24219
  };
24168
24220
  if ((mergedOption.autoId || mergedOption.basePath) && mergedOption.id) {
24169
- return error(errInvalidOption('output.amd.id', 'outputamd', 'this option cannot be used together with "output.amd.autoId"/"output.amd.basePath"'));
24221
+ return error(errorInvalidOption('output.amd.id', 'outputamd', 'this option cannot be used together with "output.amd.autoId"/"output.amd.basePath"'));
24170
24222
  }
24171
24223
  if (mergedOption.basePath && !mergedOption.autoId) {
24172
- return error(errInvalidOption('output.amd.basePath', 'outputamd', 'this option only works with "output.amd.autoId"'));
24224
+ return error(errorInvalidOption('output.amd.basePath', 'outputamd', 'this option only works with "output.amd.autoId"'));
24173
24225
  }
24174
- let normalized;
24175
- if (mergedOption.autoId) {
24176
- normalized = {
24226
+ return mergedOption.autoId
24227
+ ? {
24177
24228
  autoId: true,
24178
24229
  basePath: mergedOption.basePath,
24179
24230
  define: mergedOption.define,
24180
24231
  forceJsExtensionForImports: mergedOption.forceJsExtensionForImports
24181
- };
24182
- }
24183
- else {
24184
- normalized = {
24232
+ }
24233
+ : {
24185
24234
  autoId: false,
24186
24235
  define: mergedOption.define,
24187
24236
  forceJsExtensionForImports: mergedOption.forceJsExtensionForImports,
24188
24237
  id: mergedOption.id
24189
24238
  };
24190
- }
24191
- return normalized;
24192
24239
  };
24193
24240
  const getAddon = (config, name) => {
24194
24241
  const configAddon = config[name];
@@ -24197,10 +24244,11 @@ const getAddon = (config, name) => {
24197
24244
  }
24198
24245
  return () => configAddon || '';
24199
24246
  };
24247
+ // eslint-disable-next-line unicorn/prevent-abbreviations
24200
24248
  const getDir = (config, file) => {
24201
24249
  const { dir } = config;
24202
24250
  if (typeof dir === 'string' && typeof file === 'string') {
24203
- return error(errInvalidOption('output.dir', 'outputdir', 'you must set either "output.file" for a single-file build or "output.dir" when generating multiple chunks'));
24251
+ return error(errorInvalidOption('output.dir', 'outputdir', 'you must set either "output.file" for a single-file build or "output.dir" when generating multiple chunks'));
24204
24252
  }
24205
24253
  return dir;
24206
24254
  };
@@ -24209,7 +24257,7 @@ const getDynamicImportFunction = (config, inputOptions, format) => {
24209
24257
  if (configDynamicImportFunction) {
24210
24258
  warnDeprecation(`The "output.dynamicImportFunction" option is deprecated. Use the "renderDynamicImport" plugin hook instead.`, true, inputOptions);
24211
24259
  if (format !== 'es') {
24212
- inputOptions.onwarn(errInvalidOption('output.dynamicImportFunction', 'outputdynamicImportFunction', 'this option is ignored for formats other than "es"'));
24260
+ inputOptions.onwarn(errorInvalidOption('output.dynamicImportFunction', 'outputdynamicImportFunction', 'this option is ignored for formats other than "es"'));
24213
24261
  }
24214
24262
  }
24215
24263
  return configDynamicImportFunction;
@@ -24227,7 +24275,7 @@ function getExports(config, unsetOptions) {
24227
24275
  unsetOptions.add('exports');
24228
24276
  }
24229
24277
  else if (!['default', 'named', 'none', 'auto'].includes(configExports)) {
24230
- return error(errInvalidExportOptionValue(configExports));
24278
+ return error(errorInvalidExportOptionValue(configExports));
24231
24279
  }
24232
24280
  return configExports || 'auto';
24233
24281
  }
@@ -24257,12 +24305,6 @@ const ALLOWED_INTEROP_TYPES = new Set([
24257
24305
  ]);
24258
24306
  const getInterop = (config) => {
24259
24307
  const configInterop = config.interop;
24260
- const validateInterop = (interop) => {
24261
- if (!ALLOWED_INTEROP_TYPES.has(interop)) {
24262
- return error(errInvalidOption('output.interop', 'outputinterop', `use one of ${Array.from(ALLOWED_INTEROP_TYPES, value => JSON.stringify(value)).join(', ')}`, interop));
24263
- }
24264
- return interop;
24265
- };
24266
24308
  if (typeof configInterop === 'function') {
24267
24309
  const interopPerId = Object.create(null);
24268
24310
  let defaultInterop = null;
@@ -24274,14 +24316,22 @@ const getInterop = (config) => {
24274
24316
  }
24275
24317
  return configInterop === undefined ? () => 'default' : () => validateInterop(configInterop);
24276
24318
  };
24319
+ const validateInterop = (interop) => {
24320
+ if (!ALLOWED_INTEROP_TYPES.has(interop)) {
24321
+ return error(errorInvalidOption('output.interop', 'outputinterop',
24322
+ // eslint-disable-next-line unicorn/prefer-spread
24323
+ `use one of ${Array.from(ALLOWED_INTEROP_TYPES, value => JSON.stringify(value)).join(', ')}`, interop));
24324
+ }
24325
+ return interop;
24326
+ };
24277
24327
  const getManualChunks = (config, inlineDynamicImports, preserveModules, inputOptions) => {
24278
24328
  const configManualChunks = config.manualChunks || inputOptions.manualChunks;
24279
24329
  if (configManualChunks) {
24280
24330
  if (inlineDynamicImports) {
24281
- return error(errInvalidOption('output.manualChunks', 'outputmanualchunks', 'this option is not supported for "output.inlineDynamicImports"'));
24331
+ return error(errorInvalidOption('output.manualChunks', 'outputmanualchunks', 'this option is not supported for "output.inlineDynamicImports"'));
24282
24332
  }
24283
24333
  if (preserveModules) {
24284
- return error(errInvalidOption('output.manualChunks', 'outputmanualchunks', 'this option is not supported for "output.preserveModules"'));
24334
+ return error(errorInvalidOption('output.manualChunks', 'outputmanualchunks', 'this option is not supported for "output.preserveModules"'));
24285
24335
  }
24286
24336
  }
24287
24337
  return configManualChunks || {};
@@ -24301,7 +24351,7 @@ const getSourcemapBaseUrl = (config) => {
24301
24351
  if (isValidUrl(sourcemapBaseUrl)) {
24302
24352
  return sourcemapBaseUrl;
24303
24353
  }
24304
- return error(errInvalidOption('output.sourcemapBaseUrl', 'outputsourcemapbaseurl', `must be a valid URL, received ${JSON.stringify(sourcemapBaseUrl)}`));
24354
+ return error(errorInvalidOption('output.sourcemapBaseUrl', 'outputsourcemapbaseurl', `must be a valid URL, received ${JSON.stringify(sourcemapBaseUrl)}`));
24305
24355
  }
24306
24356
  };
24307
24357
 
@@ -24324,14 +24374,14 @@ async function rollupInternal(rawInputOptions, watcher) {
24324
24374
  timeEnd('initialize', 2);
24325
24375
  await graph.build();
24326
24376
  }
24327
- catch (err) {
24377
+ catch (error_) {
24328
24378
  const watchFiles = Object.keys(graph.watchFiles);
24329
24379
  if (watchFiles.length > 0) {
24330
- err.watchFiles = watchFiles;
24380
+ error_.watchFiles = watchFiles;
24331
24381
  }
24332
- await graph.pluginDriver.hookParallel('buildEnd', [err]);
24382
+ await graph.pluginDriver.hookParallel('buildEnd', [error_]);
24333
24383
  await graph.pluginDriver.hookParallel('closeBundle', []);
24334
- throw err;
24384
+ throw error_;
24335
24385
  }
24336
24386
  await graph.pluginDriver.hookParallel('buildEnd', []);
24337
24387
  });
@@ -24347,13 +24397,13 @@ async function rollupInternal(rawInputOptions, watcher) {
24347
24397
  closed: false,
24348
24398
  async generate(rawOutputOptions) {
24349
24399
  if (result.closed)
24350
- return error(errAlreadyClosed());
24400
+ return error(errorAlreadyClosed());
24351
24401
  return handleGenerateWrite(false, inputOptions, unsetInputOptions, rawOutputOptions, graph);
24352
24402
  },
24353
24403
  watchFiles: Object.keys(graph.watchFiles),
24354
24404
  async write(rawOutputOptions) {
24355
24405
  if (result.closed)
24356
- return error(errAlreadyClosed());
24406
+ return error(errorAlreadyClosed());
24357
24407
  return handleGenerateWrite(true, inputOptions, unsetInputOptions, rawOutputOptions, graph);
24358
24408
  }
24359
24409
  };
@@ -24365,33 +24415,34 @@ async function getInputOptions(rawInputOptions, watchMode) {
24365
24415
  if (!rawInputOptions) {
24366
24416
  throw new Error('You must supply an options object to rollup');
24367
24417
  }
24368
- const rawPlugins = getSortedValidatedPlugins('options', ensureArray(rawInputOptions.plugins));
24369
- const { options, unsetOptions } = normalizeInputOptions(await rawPlugins.reduce(applyOptionHook(watchMode), Promise.resolve(rawInputOptions)));
24418
+ const rawPlugins = getSortedValidatedPlugins('options', await normalizePluginOption(rawInputOptions.plugins));
24419
+ const { options, unsetOptions } = await normalizeInputOptions(await rawPlugins.reduce(applyOptionHook(watchMode), Promise.resolve(rawInputOptions)));
24370
24420
  normalizePlugins(options.plugins, ANONYMOUS_PLUGIN_PREFIX);
24371
24421
  return { options, unsetOptions };
24372
24422
  }
24373
24423
  function applyOptionHook(watchMode) {
24374
24424
  return async (inputOptions, plugin) => {
24375
24425
  const handler = 'handler' in plugin.options ? plugin.options.handler : plugin.options;
24376
- return ((await handler.call({ meta: { rollupVersion: version$1, watchMode } }, await inputOptions)) || inputOptions);
24426
+ return ((await handler.call({ meta: { rollupVersion: version$1, watchMode } }, await inputOptions)) ||
24427
+ inputOptions);
24377
24428
  };
24378
24429
  }
24379
24430
  function normalizePlugins(plugins, anonymousPrefix) {
24380
- plugins.forEach((plugin, index) => {
24431
+ for (const [index, plugin] of plugins.entries()) {
24381
24432
  if (!plugin.name) {
24382
24433
  plugin.name = `${anonymousPrefix}${index + 1}`;
24383
24434
  }
24384
- });
24435
+ }
24385
24436
  }
24386
- function handleGenerateWrite(isWrite, inputOptions, unsetInputOptions, rawOutputOptions, graph) {
24387
- const { options: outputOptions, outputPluginDriver, unsetOptions } = getOutputOptionsAndPluginDriver(rawOutputOptions, graph.pluginDriver, inputOptions, unsetInputOptions);
24437
+ async function handleGenerateWrite(isWrite, inputOptions, unsetInputOptions, rawOutputOptions, graph) {
24438
+ const { options: outputOptions, outputPluginDriver, unsetOptions } = await getOutputOptionsAndPluginDriver(rawOutputOptions, graph.pluginDriver, inputOptions, unsetInputOptions);
24388
24439
  return catchUnfinishedHookActions(outputPluginDriver, async () => {
24389
24440
  const bundle = new Bundle(outputOptions, unsetOptions, inputOptions, outputPluginDriver, graph);
24390
24441
  const generated = await bundle.generate(isWrite);
24391
24442
  if (isWrite) {
24392
24443
  timeStart('WRITE', 1);
24393
24444
  if (!outputOptions.dir && !outputOptions.file) {
24394
- return error(errMissingFileOrDirOption());
24445
+ return error(errorMissingFileOrDirOption());
24395
24446
  }
24396
24447
  await Promise.all(Object.values(generated).map(chunk => graph.fileOperationQueue.run(() => writeOutputFile(chunk, outputOptions))));
24397
24448
  await outputPluginDriver.hookParallel('writeBundle', [outputOptions, generated]);
@@ -24400,21 +24451,21 @@ function handleGenerateWrite(isWrite, inputOptions, unsetInputOptions, rawOutput
24400
24451
  return createOutput(generated);
24401
24452
  });
24402
24453
  }
24403
- function getOutputOptionsAndPluginDriver(rawOutputOptions, inputPluginDriver, inputOptions, unsetInputOptions) {
24454
+ async function getOutputOptionsAndPluginDriver(rawOutputOptions, inputPluginDriver, inputOptions, unsetInputOptions) {
24404
24455
  if (!rawOutputOptions) {
24405
24456
  throw new Error('You must supply an options object');
24406
24457
  }
24407
- const rawPlugins = ensureArray(rawOutputOptions.plugins);
24458
+ const rawPlugins = await normalizePluginOption(rawOutputOptions.plugins);
24408
24459
  normalizePlugins(rawPlugins, ANONYMOUS_OUTPUT_PLUGIN_PREFIX);
24409
24460
  const outputPluginDriver = inputPluginDriver.createOutputPluginDriver(rawPlugins);
24410
24461
  return {
24411
- ...getOutputOptions(inputOptions, unsetInputOptions, rawOutputOptions, outputPluginDriver),
24462
+ ...(await getOutputOptions(inputOptions, unsetInputOptions, rawOutputOptions, outputPluginDriver)),
24412
24463
  outputPluginDriver
24413
24464
  };
24414
24465
  }
24415
24466
  function getOutputOptions(inputOptions, unsetInputOptions, rawOutputOptions, outputPluginDriver) {
24416
- return normalizeOutputOptions(outputPluginDriver.hookReduceArg0Sync('outputOptions', [rawOutputOptions.output || rawOutputOptions], (outputOptions, result) => result || outputOptions, pluginContext => {
24417
- const emitError = () => pluginContext.error(errCannotEmitFromOptionsHook());
24467
+ return normalizeOutputOptions(outputPluginDriver.hookReduceArg0Sync('outputOptions', [rawOutputOptions], (outputOptions, result) => result || outputOptions, pluginContext => {
24468
+ const emitError = () => pluginContext.error(errorCannotEmitFromOptionsHook());
24418
24469
  return {
24419
24470
  ...pluginContext,
24420
24471
  emitFile: emitError,
@@ -24457,6 +24508,321 @@ function defineConfig(options) {
24457
24508
  return options;
24458
24509
  }
24459
24510
 
24511
+ const {
24512
+ env = {},
24513
+ argv = [],
24514
+ platform = "",
24515
+ } = typeof process === "undefined" ? {} : process;
24516
+
24517
+ const isDisabled = "NO_COLOR" in env || argv.includes("--no-color");
24518
+ const isForced = "FORCE_COLOR" in env || argv.includes("--color");
24519
+ const isWindows = platform === "win32";
24520
+ const isDumbTerminal = env.TERM === "dumb";
24521
+
24522
+ const isCompatibleTerminal =
24523
+ tty && tty.isatty && tty.isatty(1) && env.TERM && !isDumbTerminal;
24524
+
24525
+ const isCI =
24526
+ "CI" in env &&
24527
+ ("GITHUB_ACTIONS" in env || "GITLAB_CI" in env || "CIRCLECI" in env);
24528
+
24529
+ const isColorSupported =
24530
+ !isDisabled &&
24531
+ (isForced || (isWindows && !isDumbTerminal) || isCompatibleTerminal || isCI);
24532
+
24533
+ const replaceClose = (
24534
+ index,
24535
+ string,
24536
+ close,
24537
+ replace,
24538
+ head = string.substring(0, index) + replace,
24539
+ tail = string.substring(index + close.length),
24540
+ next = tail.indexOf(close)
24541
+ ) => head + (next < 0 ? tail : replaceClose(next, tail, close, replace));
24542
+
24543
+ const clearBleed = (index, string, open, close, replace) =>
24544
+ index < 0
24545
+ ? open + string + close
24546
+ : open + replaceClose(index, string, close, replace) + close;
24547
+
24548
+ const filterEmpty =
24549
+ (open, close, replace = open, at = open.length + 1) =>
24550
+ (string) =>
24551
+ string || !(string === "" || string === undefined)
24552
+ ? clearBleed(
24553
+ ("" + string).indexOf(close, at),
24554
+ string,
24555
+ open,
24556
+ close,
24557
+ replace
24558
+ )
24559
+ : "";
24560
+
24561
+ const init = (open, close, replace) =>
24562
+ filterEmpty(`\x1b[${open}m`, `\x1b[${close}m`, replace);
24563
+
24564
+ const colors = {
24565
+ reset: init(0, 0),
24566
+ bold: init(1, 22, "\x1b[22m\x1b[1m"),
24567
+ dim: init(2, 22, "\x1b[22m\x1b[2m"),
24568
+ italic: init(3, 23),
24569
+ underline: init(4, 24),
24570
+ inverse: init(7, 27),
24571
+ hidden: init(8, 28),
24572
+ strikethrough: init(9, 29),
24573
+ black: init(30, 39),
24574
+ red: init(31, 39),
24575
+ green: init(32, 39),
24576
+ yellow: init(33, 39),
24577
+ blue: init(34, 39),
24578
+ magenta: init(35, 39),
24579
+ cyan: init(36, 39),
24580
+ white: init(37, 39),
24581
+ gray: init(90, 39),
24582
+ bgBlack: init(40, 49),
24583
+ bgRed: init(41, 49),
24584
+ bgGreen: init(42, 49),
24585
+ bgYellow: init(43, 49),
24586
+ bgBlue: init(44, 49),
24587
+ bgMagenta: init(45, 49),
24588
+ bgCyan: init(46, 49),
24589
+ bgWhite: init(47, 49),
24590
+ blackBright: init(90, 39),
24591
+ redBright: init(91, 39),
24592
+ greenBright: init(92, 39),
24593
+ yellowBright: init(93, 39),
24594
+ blueBright: init(94, 39),
24595
+ magentaBright: init(95, 39),
24596
+ cyanBright: init(96, 39),
24597
+ whiteBright: init(97, 39),
24598
+ bgBlackBright: init(100, 49),
24599
+ bgRedBright: init(101, 49),
24600
+ bgGreenBright: init(102, 49),
24601
+ bgYellowBright: init(103, 49),
24602
+ bgBlueBright: init(104, 49),
24603
+ bgMagentaBright: init(105, 49),
24604
+ bgCyanBright: init(106, 49),
24605
+ bgWhiteBright: init(107, 49),
24606
+ };
24607
+
24608
+ const createColors = ({ useColor = isColorSupported } = {}) =>
24609
+ useColor
24610
+ ? colors
24611
+ : Object.keys(colors).reduce(
24612
+ (colors, key) => ({ ...colors, [key]: String }),
24613
+ {}
24614
+ );
24615
+
24616
+ createColors();
24617
+
24618
+ // @see https://no-color.org
24619
+ // @see https://www.npmjs.com/package/chalk
24620
+ const { bold, cyan, dim, gray, green, red, underline, yellow } = createColors({
24621
+ useColor: env$1.FORCE_COLOR !== '0' && !env$1.NO_COLOR
24622
+ });
24623
+
24624
+ // log to stderr to keep `rollup main.js > bundle.js` from breaking
24625
+ const stderr = (...parameters) => process$1.stderr.write(`${parameters.join('')}\n`);
24626
+ function handleError(error, recover = false) {
24627
+ const name = error.name || error.cause?.name;
24628
+ const nameSection = name ? `${name}: ` : '';
24629
+ const pluginSection = error.plugin ? `(plugin ${error.plugin}) ` : '';
24630
+ const message = `${pluginSection}${nameSection}${error.message}`;
24631
+ stderr(bold(red(`[!] ${bold(message.toString())}`)));
24632
+ if (error.url) {
24633
+ stderr(cyan(error.url));
24634
+ }
24635
+ if (error.loc) {
24636
+ stderr(`${relativeId((error.loc.file || error.id))} (${error.loc.line}:${error.loc.column})`);
24637
+ }
24638
+ else if (error.id) {
24639
+ stderr(relativeId(error.id));
24640
+ }
24641
+ if (error.frame) {
24642
+ stderr(dim(error.frame));
24643
+ }
24644
+ if (error.stack) {
24645
+ stderr(dim(error.stack));
24646
+ }
24647
+ stderr('');
24648
+ // eslint-disable-next-line unicorn/no-process-exit
24649
+ if (!recover)
24650
+ process$1.exit(1);
24651
+ }
24652
+
24653
+ const commandAliases = {
24654
+ c: 'config',
24655
+ d: 'dir',
24656
+ e: 'external',
24657
+ f: 'format',
24658
+ g: 'globals',
24659
+ h: 'help',
24660
+ i: 'input',
24661
+ m: 'sourcemap',
24662
+ n: 'name',
24663
+ o: 'file',
24664
+ p: 'plugin',
24665
+ v: 'version',
24666
+ w: 'watch'
24667
+ };
24668
+ const EMPTY_COMMAND_OPTIONS = { external: [], globals: undefined };
24669
+ async function mergeOptions(config, rawCommandOptions = EMPTY_COMMAND_OPTIONS, defaultOnWarnHandler = defaultOnWarn) {
24670
+ const command = getCommandOptions(rawCommandOptions);
24671
+ const inputOptions = await mergeInputOptions(config, command, defaultOnWarnHandler);
24672
+ const warn = inputOptions.onwarn;
24673
+ if (command.output) {
24674
+ Object.assign(command, command.output);
24675
+ }
24676
+ const outputOptionsArray = ensureArray(config.output);
24677
+ if (outputOptionsArray.length === 0)
24678
+ outputOptionsArray.push({});
24679
+ const outputOptions = await Promise.all(outputOptionsArray.map(singleOutputOptions => mergeOutputOptions(singleOutputOptions, command, warn)));
24680
+ warnUnknownOptions(command, [
24681
+ ...Object.keys(inputOptions),
24682
+ ...Object.keys(outputOptions[0]).filter(option => option !== 'sourcemapPathTransform'),
24683
+ ...Object.keys(commandAliases),
24684
+ 'bundleConfigAsCjs',
24685
+ 'config',
24686
+ 'environment',
24687
+ 'plugin',
24688
+ 'silent',
24689
+ 'failAfterWarnings',
24690
+ 'stdin',
24691
+ 'waitForBundleInput',
24692
+ 'configPlugin'
24693
+ ], 'CLI flags', warn, /^_$|output$|config/);
24694
+ inputOptions.output = outputOptions;
24695
+ return inputOptions;
24696
+ }
24697
+ function getCommandOptions(rawCommandOptions) {
24698
+ const external = rawCommandOptions.external && typeof rawCommandOptions.external === 'string'
24699
+ ? rawCommandOptions.external.split(',')
24700
+ : [];
24701
+ return {
24702
+ ...rawCommandOptions,
24703
+ external,
24704
+ globals: typeof rawCommandOptions.globals === 'string'
24705
+ ? rawCommandOptions.globals.split(',').reduce((globals, globalDefinition) => {
24706
+ const [id, variableName] = globalDefinition.split(':');
24707
+ globals[id] = variableName;
24708
+ if (!external.includes(id)) {
24709
+ external.push(id);
24710
+ }
24711
+ return globals;
24712
+ }, Object.create(null))
24713
+ : undefined
24714
+ };
24715
+ }
24716
+ async function mergeInputOptions(config, overrides, defaultOnWarnHandler) {
24717
+ const getOption = (name) => overrides[name] ?? config[name];
24718
+ const inputOptions = {
24719
+ acorn: getOption('acorn'),
24720
+ acornInjectPlugins: config.acornInjectPlugins,
24721
+ cache: config.cache,
24722
+ context: getOption('context'),
24723
+ experimentalCacheExpiry: getOption('experimentalCacheExpiry'),
24724
+ external: getExternal(config, overrides),
24725
+ inlineDynamicImports: getOption('inlineDynamicImports'),
24726
+ input: getOption('input') || [],
24727
+ makeAbsoluteExternalsRelative: getOption('makeAbsoluteExternalsRelative'),
24728
+ manualChunks: getOption('manualChunks'),
24729
+ maxParallelFileOps: getOption('maxParallelFileOps'),
24730
+ maxParallelFileReads: getOption('maxParallelFileReads'),
24731
+ moduleContext: getOption('moduleContext'),
24732
+ onwarn: getOnWarn(config, defaultOnWarnHandler),
24733
+ perf: getOption('perf'),
24734
+ plugins: await normalizePluginOption(config.plugins),
24735
+ preserveEntrySignatures: getOption('preserveEntrySignatures'),
24736
+ preserveModules: getOption('preserveModules'),
24737
+ preserveSymlinks: getOption('preserveSymlinks'),
24738
+ shimMissingExports: getOption('shimMissingExports'),
24739
+ strictDeprecations: getOption('strictDeprecations'),
24740
+ treeshake: getObjectOption(config, overrides, 'treeshake', objectifyOptionWithPresets(treeshakePresets, 'treeshake', 'false, true, ')),
24741
+ watch: getWatch(config, overrides)
24742
+ };
24743
+ warnUnknownOptions(config, Object.keys(inputOptions), 'input options', inputOptions.onwarn, /^output$/);
24744
+ return inputOptions;
24745
+ }
24746
+ const getExternal = (config, overrides) => {
24747
+ const configExternal = config.external;
24748
+ return typeof configExternal === 'function'
24749
+ ? (source, importer, isResolved) => configExternal(source, importer, isResolved) || overrides.external.includes(source)
24750
+ : [...ensureArray(configExternal), ...overrides.external];
24751
+ };
24752
+ const getOnWarn = (config, defaultOnWarnHandler) => config.onwarn
24753
+ ? warning => config.onwarn(warning, defaultOnWarnHandler)
24754
+ : defaultOnWarnHandler;
24755
+ const getObjectOption = (config, overrides, name, objectifyValue = objectifyOption) => {
24756
+ const commandOption = normalizeObjectOptionValue(overrides[name], objectifyValue);
24757
+ const configOption = normalizeObjectOptionValue(config[name], objectifyValue);
24758
+ if (commandOption !== undefined) {
24759
+ return commandOption && { ...configOption, ...commandOption };
24760
+ }
24761
+ return configOption;
24762
+ };
24763
+ const getWatch = (config, overrides) => config.watch !== false && getObjectOption(config, overrides, 'watch');
24764
+ const normalizeObjectOptionValue = (optionValue, objectifyValue) => {
24765
+ if (!optionValue) {
24766
+ return optionValue;
24767
+ }
24768
+ if (Array.isArray(optionValue)) {
24769
+ return optionValue.reduce((result, value) => value && result && { ...result, ...objectifyValue(value) }, {});
24770
+ }
24771
+ return objectifyValue(optionValue);
24772
+ };
24773
+ async function mergeOutputOptions(config, overrides, warn) {
24774
+ const getOption = (name) => overrides[name] ?? config[name];
24775
+ const outputOptions = {
24776
+ amd: getObjectOption(config, overrides, 'amd'),
24777
+ assetFileNames: getOption('assetFileNames'),
24778
+ banner: getOption('banner'),
24779
+ chunkFileNames: getOption('chunkFileNames'),
24780
+ compact: getOption('compact'),
24781
+ dir: getOption('dir'),
24782
+ dynamicImportFunction: getOption('dynamicImportFunction'),
24783
+ dynamicImportInCjs: getOption('dynamicImportInCjs'),
24784
+ entryFileNames: getOption('entryFileNames'),
24785
+ esModule: getOption('esModule'),
24786
+ exports: getOption('exports'),
24787
+ extend: getOption('extend'),
24788
+ externalImportAssertions: getOption('externalImportAssertions'),
24789
+ externalLiveBindings: getOption('externalLiveBindings'),
24790
+ file: getOption('file'),
24791
+ footer: getOption('footer'),
24792
+ format: getOption('format'),
24793
+ freeze: getOption('freeze'),
24794
+ generatedCode: getObjectOption(config, overrides, 'generatedCode', objectifyOptionWithPresets(generatedCodePresets, 'output.generatedCode', '')),
24795
+ globals: getOption('globals'),
24796
+ hoistTransitiveImports: getOption('hoistTransitiveImports'),
24797
+ indent: getOption('indent'),
24798
+ inlineDynamicImports: getOption('inlineDynamicImports'),
24799
+ interop: getOption('interop'),
24800
+ intro: getOption('intro'),
24801
+ manualChunks: getOption('manualChunks'),
24802
+ minifyInternalExports: getOption('minifyInternalExports'),
24803
+ name: getOption('name'),
24804
+ namespaceToStringTag: getOption('namespaceToStringTag'),
24805
+ noConflict: getOption('noConflict'),
24806
+ outro: getOption('outro'),
24807
+ paths: getOption('paths'),
24808
+ plugins: await normalizePluginOption(config.plugins),
24809
+ preferConst: getOption('preferConst'),
24810
+ preserveModules: getOption('preserveModules'),
24811
+ preserveModulesRoot: getOption('preserveModulesRoot'),
24812
+ sanitizeFileName: getOption('sanitizeFileName'),
24813
+ sourcemap: getOption('sourcemap'),
24814
+ sourcemapBaseUrl: getOption('sourcemapBaseUrl'),
24815
+ sourcemapExcludeSources: getOption('sourcemapExcludeSources'),
24816
+ sourcemapFile: getOption('sourcemapFile'),
24817
+ sourcemapPathTransform: getOption('sourcemapPathTransform'),
24818
+ strict: getOption('strict'),
24819
+ systemNullSetters: getOption('systemNullSetters'),
24820
+ validate: getOption('validate')
24821
+ };
24822
+ warnUnknownOptions(config, Object.keys(outputOptions), 'output options', warn);
24823
+ return outputOptions;
24824
+ }
24825
+
24460
24826
  class WatchEmitter {
24461
24827
  constructor() {
24462
24828
  this.currentHandlers = Object.create(null);
@@ -24464,10 +24830,8 @@ class WatchEmitter {
24464
24830
  }
24465
24831
  // Will be overwritten by Rollup
24466
24832
  async close() { }
24467
- emit(event, ...args) {
24468
- return Promise.all(this.getCurrentHandlers(event)
24469
- .concat(this.getPersistentHandlers(event))
24470
- .map(handler => handler(...args)));
24833
+ emit(event, ...parameters) {
24834
+ return Promise.all([...this.getCurrentHandlers(event), ...this.getPersistentHandlers(event)].map(handler => handler(...parameters)));
24471
24835
  }
24472
24836
  off(event, listener) {
24473
24837
  const listeners = this.persistentHandlers[event];
@@ -24488,9 +24852,9 @@ class WatchEmitter {
24488
24852
  return this;
24489
24853
  }
24490
24854
  once(event, listener) {
24491
- const selfRemovingListener = (...args) => {
24855
+ const selfRemovingListener = (...parameters) => {
24492
24856
  this.off(event, selfRemovingListener);
24493
- return listener(...args);
24857
+ return listener(...parameters);
24494
24858
  };
24495
24859
  this.on(event, selfRemovingListener);
24496
24860
  return this;
@@ -24518,8 +24882,8 @@ async function loadFsEvents() {
24518
24882
  try {
24519
24883
  ({ default: fsEvents } = await import('fsevents'));
24520
24884
  }
24521
- catch (err) {
24522
- fsEventsImportError = err;
24885
+ catch (error) {
24886
+ fsEventsImportError = error;
24523
24887
  }
24524
24888
  }
24525
24889
  // A call to this function will be injected into the chokidar code
@@ -24537,15 +24901,20 @@ const fseventsImporter = /*#__PURE__*/Object.defineProperty({
24537
24901
 
24538
24902
  function watch(configs) {
24539
24903
  const emitter = new WatchEmitter();
24540
- const configArray = ensureArray(configs);
24541
- const watchConfigs = configArray.filter(config => config.watch !== false);
24542
- if (watchConfigs.length === 0) {
24543
- return error(errInvalidOption('watch', 'watch', 'there must be at least one config where "watch" is not set to "false"'));
24544
- }
24545
- loadFsEvents()
24546
- .then(() => import('./watch.js'))
24547
- .then(({ Watcher }) => new Watcher(watchConfigs, emitter));
24904
+ watchInternal(configs, emitter).catch(error => {
24905
+ handleError(error);
24906
+ });
24548
24907
  return emitter;
24549
24908
  }
24909
+ async function watchInternal(configs, emitter) {
24910
+ const optionsList = await Promise.all(ensureArray(configs).map(config => mergeOptions(config)));
24911
+ const watchOptionsList = optionsList.filter(config => config.watch !== false);
24912
+ if (watchOptionsList.length === 0) {
24913
+ return error(errorInvalidOption('watch', 'watch', 'there must be at least one config where "watch" is not set to "false"'));
24914
+ }
24915
+ await loadFsEvents();
24916
+ const { Watcher } = await import('./watch.js');
24917
+ new Watcher(watchOptionsList, emitter);
24918
+ }
24550
24919
 
24551
- export { createFilter, defaultOnWarn, defineConfig, ensureArray, fseventsImporter, generatedCodePresets, getAugmentedNamespace, normalizePluginOption, objectifyOption, objectifyOptionWithPresets, picomatch$1 as picomatch, rollup, rollupInternal, treeshakePresets, version$1 as version, warnUnknownOptions, watch };
24920
+ export { createFilter, defineConfig, fseventsImporter, getAugmentedNamespace, picomatch$1 as picomatch, rollup, rollupInternal, version$1 as version, watch };