@rollup/wasm-node 4.64.0 → 5.0.0-0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/LICENSE.md +3 -304
  2. package/dist/ast-types.d.ts +896 -0
  3. package/dist/bin/rollup +21 -22
  4. package/dist/es/getLogFilter.js +2 -2
  5. package/dist/es/parseAst.js +3 -3
  6. package/dist/es/rollup.js +2 -2
  7. package/dist/es/shared/node-entry.js +1870 -2006
  8. package/dist/es/shared/parseAst.js +3542 -276
  9. package/dist/es/shared/watch.js +1765 -9600
  10. package/dist/getLogFilter.js +2 -2
  11. package/dist/loadConfigFile.js +3 -3
  12. package/dist/native.js +9 -1
  13. package/dist/parseAst.d.ts +13 -1
  14. package/dist/parseAst.js +8 -2
  15. package/dist/rollup.android-arm-eabi.node +0 -0
  16. package/dist/rollup.android-arm64.node +0 -0
  17. package/dist/rollup.d.ts +157 -105
  18. package/dist/rollup.darwin-arm64.node +0 -0
  19. package/dist/rollup.darwin-x64.node +0 -0
  20. package/dist/rollup.freebsd-arm64.node +0 -0
  21. package/dist/rollup.freebsd-x64.node +0 -0
  22. package/dist/rollup.js +2 -3
  23. package/dist/rollup.linux-arm-gnueabihf.node +0 -0
  24. package/dist/rollup.linux-arm-musleabihf.node +0 -0
  25. package/dist/rollup.linux-arm64-gnu.node +0 -0
  26. package/dist/rollup.linux-arm64-musl.node +0 -0
  27. package/dist/rollup.linux-loong64-gnu.node +0 -0
  28. package/dist/rollup.linux-loong64-musl.node +0 -0
  29. package/dist/rollup.linux-ppc64-gnu.node +0 -0
  30. package/dist/rollup.linux-ppc64-musl.node +0 -0
  31. package/dist/rollup.linux-riscv64-gnu.node +0 -0
  32. package/dist/rollup.linux-riscv64-musl.node +0 -0
  33. package/dist/rollup.linux-s390x-gnu.node +0 -0
  34. package/dist/rollup.linux-x64-gnu.node +0 -0
  35. package/dist/rollup.linux-x64-musl.node +0 -0
  36. package/dist/rollup.openbsd-x64.node +0 -0
  37. package/dist/rollup.openharmony-arm64.node +0 -0
  38. package/dist/rollup.win32-arm64-msvc.node +0 -0
  39. package/dist/rollup.win32-ia32-msvc.node +0 -0
  40. package/dist/rollup.win32-x64-gnu.node +0 -0
  41. package/dist/rollup.win32-x64-msvc.node +0 -0
  42. package/dist/shared/index.js +1775 -9597
  43. package/dist/shared/loadConfigFile.js +9 -9
  44. package/dist/shared/node-entry.js +2 -4
  45. package/dist/shared/parseAst.js +3579 -303
  46. package/dist/shared/rollup.js +1670 -1784
  47. package/dist/shared/watch-cli.js +10 -9
  48. package/dist/shared/watch.js +7 -11
  49. package/dist/wasm-node/bindings_wasm.js +45 -0
  50. package/dist/wasm-node/bindings_wasm_bg.wasm +0 -0
  51. package/package.json +19 -22
  52. package/dist/shared/fsevents-importer.js +0 -37
@@ -1,7 +1,7 @@
1
1
  /*
2
2
  @license
3
- Rollup.js v4.64.0
4
- Fri, 02 Oct 2026 15:38:16 GMT - commit 77773bf8ee9130c4edbde14c017855c41e500692
3
+ Rollup.js v5.0.0-0
4
+ Tue, 06 Oct 2026 08:24:44 GMT - commit d78bf6bee48e411672e05d8977473f76e6758c35
5
5
 
6
6
  https://github.com/rollup/rollup
7
7
 
@@ -11,10 +11,10 @@
11
11
 
12
12
  const parseAst_js = require('./parseAst.js');
13
13
  const process$1 = require('node:process');
14
- const path = require('node:path');
15
- const require$$0 = require('path');
16
- const native_js = require('../native.js');
14
+ const sp = require('node:path');
15
+ const path = require('path');
17
16
  const node_perf_hooks = require('node:perf_hooks');
17
+ const native_js = require('../native.js');
18
18
  const promises = require('node:fs/promises');
19
19
 
20
20
  function _interopNamespaceDefault(e) {
@@ -42,7 +42,7 @@ function _mergeNamespaces(n, m) {
42
42
 
43
43
  const promises__namespace = /*#__PURE__*/_interopNamespaceDefault(promises);
44
44
 
45
- var version = "4.64.0";
45
+ var version = "5.0.0-0";
46
46
  const package_ = {
47
47
  version: version};
48
48
 
@@ -409,10 +409,10 @@ function generateAssetFileName(name, names, source, originalFileName, originalFi
409
409
  type: 'asset'
410
410
  })
411
411
  : outputOptions.assetFileNames, 'output.assetFileNames', {
412
- ext: () => path.extname(emittedName).slice(1),
413
- extname: () => path.extname(emittedName),
412
+ ext: () => sp.extname(emittedName).slice(1),
413
+ extname: () => sp.extname(emittedName),
414
414
  hash: size => sourceHash.slice(0, Math.min(Math.max(0, size || DEFAULT_HASH_SIZE), MAX_HASH_SIZE)),
415
- name: () => emittedName.slice(0, Math.max(0, emittedName.length - path.extname(emittedName).length))
415
+ name: () => emittedName.slice(0, Math.max(0, emittedName.length - sp.extname(emittedName).length))
416
416
  }), bundle);
417
417
  }
418
418
  function reserveFileNameInBundle(fileName, { bundle }, log) {
@@ -577,7 +577,9 @@ class FileEmitter {
577
577
  code: prebuiltChunk.code,
578
578
  dynamicImports: [],
579
579
  exports: prebuiltChunk.exports || [],
580
+ facadeModuleAttributes: {},
580
581
  facadeModuleId: null,
582
+ facadeModuleRawId: null,
581
583
  fileName: prebuiltChunk.fileName,
582
584
  implicitlyLoadedBefore: [],
583
585
  importedBindings: {},
@@ -802,6 +804,48 @@ function getLogHandler(level, code, logger, pluginName, logLevel) {
802
804
  };
803
805
  }
804
806
 
807
+ const ATTRIBUTES_MARKER_LENGTH = '&attributes='.length;
808
+ function generateIdByRawIdAndAttributes(rawId, attributes) {
809
+ if (!attributes || Object.keys(attributes).length === 0) {
810
+ return rawId;
811
+ }
812
+ const sortedAttributes = Object.fromEntries(Object.entries(attributes).sort(([firstKey], [secondKey]) => firstKey < secondKey ? -1 : firstKey > secondKey ? 1 : 0));
813
+ return `${rawId}${rawId.includes('?') ? '&' : '?'}attributes=${encodeURIComponent(JSON.stringify(sortedAttributes))}`;
814
+ }
815
+ function normalizeModuleId(moduleId) {
816
+ if (typeof moduleId === 'object') {
817
+ return generateIdByRawIdAndAttributes(moduleId.rawId, moduleId.attributes);
818
+ }
819
+ return moduleId;
820
+ }
821
+ function normalizeModuleIdToObject(moduleId) {
822
+ if (typeof moduleId === 'object') {
823
+ return {
824
+ ...moduleId,
825
+ id: generateIdByRawIdAndAttributes(moduleId.rawId, moduleId.attributes)
826
+ };
827
+ }
828
+ const { rawId, attributes } = getRawIdAndAttributes(moduleId);
829
+ return { attributes, id: moduleId, rawId };
830
+ }
831
+ function getRawIdAndAttributes(id) {
832
+ const attributesMarkerIndex = Math.max(id.lastIndexOf('?attributes='), id.lastIndexOf('&attributes='));
833
+ if (attributesMarkerIndex === -1) {
834
+ return { rawId: id };
835
+ }
836
+ try {
837
+ const rawId = id.slice(0, attributesMarkerIndex);
838
+ const attributes = JSON.parse(decodeURIComponent(id.slice(attributesMarkerIndex + ATTRIBUTES_MARKER_LENGTH)));
839
+ if (generateIdByRawIdAndAttributes(rawId, attributes) === id) {
840
+ return { attributes, rawId };
841
+ }
842
+ }
843
+ catch {
844
+ // fall through to treat the id as opaque
845
+ }
846
+ return { rawId: id };
847
+ }
848
+
805
849
  const ANONYMOUS_PLUGIN_PREFIX = 'at position ';
806
850
  const ANONYMOUS_OUTPUT_PLUGIN_PREFIX = 'at output position ';
807
851
 
@@ -886,6 +930,20 @@ function getCacheForUncacheablePlugin(pluginName) {
886
930
  }
887
931
 
888
932
  const rollupVersion$2 = package_.version;
933
+ function getNormalizedImporter(importer, deprecatedImporterAttributes, pluginName, options) {
934
+ const normalizedImporter = normalizeModuleIdToObject(importer);
935
+ const hasDeprecatedImporterAttributes = !!deprecatedImporterAttributes && Object.keys(deprecatedImporterAttributes).length > 0;
936
+ if (typeof importer === 'string' &&
937
+ !normalizedImporter.attributes &&
938
+ hasDeprecatedImporterAttributes) {
939
+ parseAst_js.warnDeprecation('The "importerAttributes" option is deprecated. Provide a UniqueModuleId for "importer" instead.', parseAst_js.URL_THIS_RESOLVE, true, options, pluginName);
940
+ return normalizeModuleIdToObject({
941
+ attributes: deprecatedImporterAttributes,
942
+ rawId: importer
943
+ });
944
+ }
945
+ return normalizedImporter;
946
+ }
889
947
  function getPluginContext(plugin, pluginCache, graph, options, fileEmitter, existingPluginNames) {
890
948
  const { logLevel, onLog } = options;
891
949
  let cacheable = true;
@@ -927,16 +985,23 @@ function getPluginContext(plugin, pluginCache, graph, options, fileEmitter, exis
927
985
  getWatchFiles: () => Object.keys(graph.watchFiles),
928
986
  info: getLogHandler(parseAst_js.LOGLEVEL_INFO, 'PLUGIN_LOG', onLog, plugin.name, logLevel),
929
987
  load(resolvedId) {
930
- return graph.moduleLoader.preloadModule(resolvedId);
988
+ return graph.moduleLoader.preloadModule({
989
+ ...resolvedId,
990
+ ...normalizeModuleIdToObject(resolvedId.id)
991
+ });
931
992
  },
932
993
  meta: {
933
994
  rollupVersion: rollupVersion$2,
934
995
  watchMode: graph.watchMode
935
996
  },
936
997
  parse: parseAst_js.parseAst,
937
- resolve(source, importer, { attributes, custom, isEntry, skipSelf, importerAttributes } = parseAst_js.BLANK) {
998
+ parseAndWalk: parseAst_js.parseAndWalk,
999
+ resolve(source, importer, { attributes, custom, importerAttributes: deprecatedImporterAttributes, isEntry, skipSelf } = parseAst_js.BLANK) {
938
1000
  skipSelf ??= true;
939
- return graph.moduleLoader.resolveId(source, importer, custom, isEntry, attributes || parseAst_js.EMPTY_OBJECT, importerAttributes, skipSelf ? [{ importer, plugin, source }] : null);
1001
+ const { id: importerId, attributes: importerAttributes, rawId: importerRawId } = importer
1002
+ ? getNormalizedImporter(importer, deprecatedImporterAttributes, plugin.name, options)
1003
+ : parseAst_js.BLANK;
1004
+ return graph.moduleLoader.resolveId(source, importerId, custom, isEntry, attributes || parseAst_js.EMPTY_OBJECT, importerAttributes || parseAst_js.EMPTY_OBJECT, importerRawId, skipSelf ? [{ importer: importerId, plugin, source }] : null);
940
1005
  },
941
1006
  setAssetSource: fileEmitter.setAssetSource,
942
1007
  warn: getLogHandler(parseAst_js.LOGLEVEL_WARN, 'PLUGIN_WARNING', onLog, plugin.name, logLevel)
@@ -947,35 +1012,6 @@ function getDefaultExportFromCjs (x) {
947
1012
  return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
948
1013
  }
949
1014
 
950
- function getAugmentedNamespace(n) {
951
- if (Object.prototype.hasOwnProperty.call(n, '__esModule')) return n;
952
- var f = n.default;
953
- if (typeof f == "function") {
954
- var a = function a () {
955
- var isInstance = false;
956
- try {
957
- isInstance = this instanceof a;
958
- } catch (e) {}
959
- if (isInstance) {
960
- return Reflect.construct(f, arguments, this.constructor);
961
- }
962
- return f.apply(this, arguments);
963
- };
964
- a.prototype = f.prototype;
965
- } else a = {};
966
- Object.defineProperty(a, '__esModule', {value: true});
967
- Object.keys(n).forEach(function (k) {
968
- var d = Object.getOwnPropertyDescriptor(n, k);
969
- Object.defineProperty(a, k, d.get ? d : {
970
- enumerable: true,
971
- get: function () {
972
- return n[k];
973
- }
974
- });
975
- });
976
- return a;
977
- }
978
-
979
1015
  var utils = {};
980
1016
 
981
1017
  var constants;
@@ -3490,7 +3526,7 @@ function getMatcherString$1(glob, cwd) {
3490
3526
  if (glob.startsWith('**') || parseAst_js.isAbsolute(glob)) {
3491
3527
  return parseAst_js.normalize(glob);
3492
3528
  }
3493
- const resolved = path.resolve(cwd, glob);
3529
+ const resolved = sp.resolve(cwd, glob);
3494
3530
  return parseAst_js.normalize(resolved);
3495
3531
  }
3496
3532
  function patternToIdFilter(pattern) {
@@ -4000,7 +4036,7 @@ function mergeInputOptions(config, overrides, plugins, log, onLog) {
4000
4036
  const getExternal = (config, overrides) => {
4001
4037
  const configExternal = config.external;
4002
4038
  return typeof configExternal === 'function'
4003
- ? (source, importer, isResolved) => configExternal(source, importer, isResolved) || overrides.external.includes(source)
4039
+ ? (source, importer, isResolved, options) => configExternal(source, importer, isResolved, options) || overrides.external.includes(source)
4004
4040
  : [...ensureArray$1(configExternal), ...overrides.external];
4005
4041
  };
4006
4042
  const getObjectOption = (config, overrides, name, objectifyValue = objectifyOption) => {
@@ -6553,89 +6589,6 @@ class IncludedTopLevelPathTracker {
6553
6589
  }
6554
6590
  }
6555
6591
 
6556
- /** @import { Node } from 'estree' */
6557
-
6558
- /**
6559
- * @param {Node} node
6560
- * @param {Node} parent
6561
- * @returns {boolean}
6562
- */
6563
- function is_reference(node, parent) {
6564
- if (node.type === 'MemberExpression') {
6565
- return !node.computed && is_reference(node.object, node);
6566
- }
6567
-
6568
- if (node.type !== 'Identifier') return false;
6569
-
6570
- switch (parent?.type) {
6571
- // disregard `bar` in `foo.bar`
6572
- case 'MemberExpression':
6573
- return parent.computed || node === parent.object;
6574
-
6575
- // disregard the `foo` in `class {foo(){}}` but keep it in `class {[foo](){}}`
6576
- case 'MethodDefinition':
6577
- return parent.computed;
6578
-
6579
- // disregard the `meta` in `import.meta`
6580
- case 'MetaProperty':
6581
- return parent.meta === node;
6582
-
6583
- // disregard the `foo` in `class {foo=bar}` but keep it in `class {[foo]=bar}` and `class {bar=foo}`
6584
- case 'PropertyDefinition':
6585
- return parent.computed || node === parent.value;
6586
-
6587
- // disregard the `bar` in `{ bar: foo }`, but keep it in `{ [bar]: foo }`
6588
- case 'Property':
6589
- return parent.computed || node === parent.value;
6590
-
6591
- // disregard the `bar` in `export { foo as bar }` or
6592
- // the foo in `import { foo as bar }`
6593
- case 'ExportSpecifier':
6594
- case 'ImportSpecifier':
6595
- return node === parent.local;
6596
-
6597
- // disregard the `foo` in `foo: while (...) { ... break foo; ... continue foo;}`
6598
- case 'LabeledStatement':
6599
- case 'BreakStatement':
6600
- case 'ContinueStatement':
6601
- return false;
6602
-
6603
- default:
6604
- return true;
6605
- }
6606
- }
6607
-
6608
- function createInclusionContext() {
6609
- return {
6610
- brokenFlow: false,
6611
- hasBreak: false,
6612
- hasContinue: false,
6613
- includedCallArguments: new Set(),
6614
- includedCallArgumentsOfPossibleValues: null,
6615
- includedLabels: new Set()
6616
- };
6617
- }
6618
- function createHasEffectsContext() {
6619
- return {
6620
- accessed: new EntityPathTracker(),
6621
- assigned: new EntityPathTracker(),
6622
- brokenFlow: false,
6623
- called: new DiscriminatedPathTracker(),
6624
- hasBreak: false,
6625
- hasContinue: false,
6626
- ignore: {
6627
- breaks: false,
6628
- continues: false,
6629
- labels: new Set(),
6630
- returnYield: false,
6631
- this: false
6632
- },
6633
- includedLabels: new Set(),
6634
- instantiated: new DiscriminatedPathTracker(),
6635
- replacedVariableInits: new Map()
6636
- };
6637
- }
6638
-
6639
6592
  function isFlagSet(flags, flag) {
6640
6593
  return (flags & flag) !== 0;
6641
6594
  }
@@ -6743,153 +6696,6 @@ const NODE_INTERACTION_UNKNOWN_CALL = {
6743
6696
  withNew: false
6744
6697
  };
6745
6698
 
6746
- const PureFunctionKey = Symbol('PureFunction');
6747
- const getPureFunctions = ({ treeshake }) => {
6748
- const pureFunctions = Object.create(null);
6749
- for (const functionName of treeshake ? treeshake.manualPureFunctions : []) {
6750
- let currentFunctions = pureFunctions;
6751
- for (const pathSegment of functionName.split('.')) {
6752
- currentFunctions = currentFunctions[pathSegment] ||= Object.create(null);
6753
- }
6754
- currentFunctions[PureFunctionKey] = true;
6755
- }
6756
- return pureFunctions;
6757
- };
6758
-
6759
- class Variable extends ExpressionEntity {
6760
- markReassigned() {
6761
- this.isReassigned = true;
6762
- }
6763
- constructor(name) {
6764
- super();
6765
- this.name = name;
6766
- this.alwaysRendered = false;
6767
- this.forbiddenNames = null;
6768
- this.globalName = null;
6769
- this.initReached = false;
6770
- this.isId = false;
6771
- this.kind = null;
6772
- this.renderBaseName = null;
6773
- this.renderName = null;
6774
- this.isReassigned = false;
6775
- this.onlyFunctionCallUsed = true;
6776
- }
6777
- /**
6778
- * Binds identifiers that reference this variable to this variable.
6779
- * Necessary to be able to change variable names.
6780
- */
6781
- addReference(_identifier) { }
6782
- /**
6783
- * Check if the identifier variable is only used as function call
6784
- * @returns true if the variable is only used as function call
6785
- */
6786
- getOnlyFunctionCallUsed() {
6787
- return this.onlyFunctionCallUsed;
6788
- }
6789
- /**
6790
- * Collect the places where the identifier variable is used
6791
- * @param usedPlace Where the variable is used
6792
- */
6793
- addUsedPlace(usedPlace) {
6794
- const isFunctionCall = usedPlace.parent.type === parseAst_js.CallExpression &&
6795
- usedPlace.parent.callee === usedPlace;
6796
- if (!isFunctionCall && usedPlace.parent.type !== parseAst_js.ExportDefaultDeclaration) {
6797
- this.onlyFunctionCallUsed = false;
6798
- }
6799
- }
6800
- /**
6801
- * Prevent this variable from being renamed to this name to avoid name
6802
- * collisions
6803
- */
6804
- forbidName(name) {
6805
- (this.forbiddenNames ||= new Set()).add(name);
6806
- }
6807
- getBaseVariableName() {
6808
- return (this.renderedLikeHoisted?.getBaseVariableName() ||
6809
- this.renderBaseName ||
6810
- this.renderName ||
6811
- this.name);
6812
- }
6813
- getName(getPropertyAccess, useOriginalName) {
6814
- if (this.globalName) {
6815
- return this.globalName;
6816
- }
6817
- if (useOriginalName?.(this)) {
6818
- return this.name;
6819
- }
6820
- if (this.renderedLikeHoisted) {
6821
- return this.renderedLikeHoisted.getName(getPropertyAccess, useOriginalName);
6822
- }
6823
- const name = this.renderName || this.name;
6824
- return this.renderBaseName ? `${this.renderBaseName}${getPropertyAccess(name)}` : name;
6825
- }
6826
- hasEffectsOnInteractionAtPath(path, { type }, _context) {
6827
- return type !== INTERACTION_ACCESSED || path.length > 0;
6828
- }
6829
- /**
6830
- * Marks this variable as being part of the bundle, which is usually the case
6831
- * when one of its identifiers becomes part of the bundle. Returns true if it
6832
- * has not been included previously. Once a variable is included, it should
6833
- * take care all its declarations are included.
6834
- */
6835
- includePath(path, context) {
6836
- this.included = true;
6837
- this.renderedLikeHoisted?.includePath(path, context);
6838
- }
6839
- /**
6840
- * Links the rendered name of this variable to another variable and includes
6841
- * this variable if the other variable is included.
6842
- */
6843
- renderLikeHoisted(variable) {
6844
- this.renderedLikeHoisted = variable;
6845
- }
6846
- markCalledFromTryStatement() { }
6847
- addReassignedValue(_value) { }
6848
- setRenderNames(baseName, name) {
6849
- this.renderBaseName = baseName;
6850
- this.renderName = name;
6851
- }
6852
- }
6853
-
6854
- /** Synthetic import name for source phase imports, similar to '*' for namespaces */
6855
- const SOURCE_PHASE_IMPORT = '*source';
6856
- class ExternalVariable extends Variable {
6857
- constructor(module, name) {
6858
- super(name);
6859
- this.referenced = false;
6860
- this.module = module;
6861
- this.isNamespace = name === '*';
6862
- this.isSourcePhase = name === SOURCE_PHASE_IMPORT;
6863
- }
6864
- addReference(identifier) {
6865
- this.referenced = true;
6866
- if (this.name === 'default' || this.name === '*') {
6867
- this.module.suggestName(identifier.name);
6868
- }
6869
- }
6870
- hasEffectsOnInteractionAtPath(path, { type }) {
6871
- return type !== INTERACTION_ACCESSED || path.length > (this.isNamespace ? 1 : 0);
6872
- }
6873
- includePath(path, context) {
6874
- super.includePath(path, context);
6875
- this.module.used = true;
6876
- }
6877
- }
6878
-
6879
- function cacheObjectGetters(object, getterProperties) {
6880
- for (const property of getterProperties) {
6881
- const propertyGetter = Object.getOwnPropertyDescriptor(object, property).get;
6882
- Object.defineProperty(object, property, {
6883
- get() {
6884
- const value = propertyGetter.call(object);
6885
- // This replaces the getter with a fixed value for subsequent calls
6886
- Object.defineProperty(object, property, { value });
6887
- return value;
6888
- }
6889
- });
6890
- }
6891
- }
6892
-
6893
6699
  const RESERVED_NAMES = new Set([
6894
6700
  'await',
6895
6701
  'break',
@@ -6942,6 +6748,802 @@ const RESERVED_NAMES = new Set([
6942
6748
  'yield'
6943
6749
  ]);
6944
6750
 
6751
+ function getSafeName(baseName, usedNames, forbiddenNames) {
6752
+ let safeName = baseName;
6753
+ let count = 1;
6754
+ while (usedNames.has(safeName) || RESERVED_NAMES.has(safeName) || forbiddenNames?.has(safeName)) {
6755
+ safeName = `${baseName}$${toBase64(count++)}`;
6756
+ }
6757
+ usedNames.add(safeName);
6758
+ return safeName;
6759
+ }
6760
+
6761
+ // To avoid infinite recursions
6762
+ const MAX_PATH_DEPTH = 6;
6763
+ // If a path is longer than MAX_PATH_DEPTH, it is truncated so that it is at
6764
+ // most MAX_PATH_DEPTH long. The last element is always UnknownKey
6765
+ const limitConcatenatedPathDepth = (path1, path2) => {
6766
+ const { length: length1 } = path1;
6767
+ const { length: length2 } = path2;
6768
+ return length1 === 0
6769
+ ? path2
6770
+ : length2 === 0
6771
+ ? path1
6772
+ : length1 + length2 > MAX_PATH_DEPTH
6773
+ ? [...path1, ...path2.slice(0, MAX_PATH_DEPTH - 1 - path1.length), 'UnknownKey']
6774
+ : [...path1, ...path2];
6775
+ };
6776
+
6777
+ function assembleMemberDescriptions(memberDescriptions, inheritedDescriptions = null) {
6778
+ return Object.create(inheritedDescriptions, memberDescriptions);
6779
+ }
6780
+ const UNDEFINED_EXPRESSION = new (class UndefinedExpression extends ExpressionEntity {
6781
+ getLiteralValueAtPath(path) {
6782
+ return path.length > 0 ? UnknownValue : undefined;
6783
+ }
6784
+ })();
6785
+ const returnsUnknown = {
6786
+ value: {
6787
+ hasEffectsWhenCalled: null,
6788
+ returns: UNKNOWN_EXPRESSION
6789
+ }
6790
+ };
6791
+ const UNKNOWN_LITERAL_BOOLEAN = new (class UnknownBoolean extends ExpressionEntity {
6792
+ getReturnExpressionWhenCalledAtPath(path) {
6793
+ if (path.length === 1) {
6794
+ return getMemberReturnExpressionWhenCalled(literalBooleanMembers, path[0]);
6795
+ }
6796
+ return UNKNOWN_RETURN_EXPRESSION;
6797
+ }
6798
+ hasEffectsOnInteractionAtPath(path, interaction, context) {
6799
+ if (interaction.type === INTERACTION_ACCESSED) {
6800
+ return path.length > 1;
6801
+ }
6802
+ if (interaction.type === INTERACTION_CALLED && path.length === 1) {
6803
+ return hasMemberEffectWhenCalled(literalBooleanMembers, path[0], interaction, context);
6804
+ }
6805
+ return true;
6806
+ }
6807
+ })();
6808
+ const returnsBoolean = {
6809
+ value: {
6810
+ hasEffectsWhenCalled: null,
6811
+ returns: UNKNOWN_LITERAL_BOOLEAN
6812
+ }
6813
+ };
6814
+ const UNKNOWN_LITERAL_NUMBER = new (class UnknownNumber extends ExpressionEntity {
6815
+ getReturnExpressionWhenCalledAtPath(path) {
6816
+ if (path.length === 1) {
6817
+ return getMemberReturnExpressionWhenCalled(literalNumberMembers, path[0]);
6818
+ }
6819
+ return UNKNOWN_RETURN_EXPRESSION;
6820
+ }
6821
+ hasEffectsOnInteractionAtPath(path, interaction, context) {
6822
+ if (interaction.type === INTERACTION_ACCESSED) {
6823
+ return path.length > 1;
6824
+ }
6825
+ if (interaction.type === INTERACTION_CALLED && path.length === 1) {
6826
+ return hasMemberEffectWhenCalled(literalNumberMembers, path[0], interaction, context);
6827
+ }
6828
+ return true;
6829
+ }
6830
+ })();
6831
+ const returnsNumber = {
6832
+ value: {
6833
+ hasEffectsWhenCalled: null,
6834
+ returns: UNKNOWN_LITERAL_NUMBER
6835
+ }
6836
+ };
6837
+ const UNKNOWN_LITERAL_STRING = new (class UnknownString extends ExpressionEntity {
6838
+ getReturnExpressionWhenCalledAtPath(path) {
6839
+ if (path.length === 1) {
6840
+ return getMemberReturnExpressionWhenCalled(literalStringMembers, path[0]);
6841
+ }
6842
+ return UNKNOWN_RETURN_EXPRESSION;
6843
+ }
6844
+ hasEffectsOnInteractionAtPath(path, interaction, context) {
6845
+ if (interaction.type === INTERACTION_ACCESSED) {
6846
+ return path.length > 1;
6847
+ }
6848
+ if (interaction.type === INTERACTION_CALLED && path.length === 1) {
6849
+ return hasMemberEffectWhenCalled(literalStringMembers, path[0], interaction, context);
6850
+ }
6851
+ return true;
6852
+ }
6853
+ })();
6854
+ const returnsString = {
6855
+ value: {
6856
+ hasEffectsWhenCalled: null,
6857
+ returns: UNKNOWN_LITERAL_STRING
6858
+ }
6859
+ };
6860
+ const stringReplace = {
6861
+ value: {
6862
+ hasEffectsWhenCalled({ args }, context) {
6863
+ const argument1 = args[2];
6864
+ return (args.length < 3 ||
6865
+ (typeof argument1.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, {
6866
+ deoptimizeCache() { }
6867
+ }) === 'symbol' &&
6868
+ argument1.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, context)));
6869
+ },
6870
+ returns: UNKNOWN_LITERAL_STRING
6871
+ }
6872
+ };
6873
+ const objectMembers = assembleMemberDescriptions({
6874
+ hasOwnProperty: returnsBoolean,
6875
+ isPrototypeOf: returnsBoolean,
6876
+ propertyIsEnumerable: returnsBoolean,
6877
+ toLocaleString: returnsString,
6878
+ toString: returnsString,
6879
+ valueOf: returnsUnknown
6880
+ });
6881
+ const literalBooleanMembers = assembleMemberDescriptions({
6882
+ valueOf: returnsBoolean
6883
+ }, objectMembers);
6884
+ const literalNumberMembers = assembleMemberDescriptions({
6885
+ toExponential: returnsString,
6886
+ toFixed: returnsString,
6887
+ toLocaleString: returnsString,
6888
+ toPrecision: returnsString,
6889
+ valueOf: returnsNumber
6890
+ }, objectMembers);
6891
+ /**
6892
+ * RegExp are stateful when they have the global or sticky flags set.
6893
+ * But if we actually don't use them, the side effect does not matter.
6894
+ * the check logic in `hasEffectsOnInteractionAtPath`.
6895
+ */
6896
+ const literalRegExpMembers = assembleMemberDescriptions({
6897
+ exec: returnsUnknown,
6898
+ test: returnsBoolean
6899
+ }, objectMembers);
6900
+ const literalStringMembers = assembleMemberDescriptions({
6901
+ anchor: returnsString,
6902
+ at: returnsUnknown,
6903
+ big: returnsString,
6904
+ blink: returnsString,
6905
+ bold: returnsString,
6906
+ charAt: returnsString,
6907
+ charCodeAt: returnsNumber,
6908
+ codePointAt: returnsUnknown,
6909
+ concat: returnsString,
6910
+ endsWith: returnsBoolean,
6911
+ fixed: returnsString,
6912
+ fontcolor: returnsString,
6913
+ fontsize: returnsString,
6914
+ includes: returnsBoolean,
6915
+ indexOf: returnsNumber,
6916
+ italics: returnsString,
6917
+ lastIndexOf: returnsNumber,
6918
+ link: returnsString,
6919
+ localeCompare: returnsNumber,
6920
+ match: returnsUnknown,
6921
+ matchAll: returnsUnknown,
6922
+ normalize: returnsString,
6923
+ padEnd: returnsString,
6924
+ padStart: returnsString,
6925
+ repeat: returnsString,
6926
+ replace: stringReplace,
6927
+ replaceAll: stringReplace,
6928
+ search: returnsNumber,
6929
+ slice: returnsString,
6930
+ small: returnsString,
6931
+ split: returnsUnknown,
6932
+ startsWith: returnsBoolean,
6933
+ strike: returnsString,
6934
+ sub: returnsString,
6935
+ substr: returnsString,
6936
+ substring: returnsString,
6937
+ sup: returnsString,
6938
+ toLocaleLowerCase: returnsString,
6939
+ toLocaleUpperCase: returnsString,
6940
+ toLowerCase: returnsString,
6941
+ toString: returnsString, // overrides the toString() method of the Object object; it does not inherit Object.prototype.toString()
6942
+ toUpperCase: returnsString,
6943
+ trim: returnsString,
6944
+ trimEnd: returnsString,
6945
+ trimLeft: returnsString,
6946
+ trimRight: returnsString,
6947
+ trimStart: returnsString,
6948
+ valueOf: returnsString
6949
+ }, objectMembers);
6950
+ function getLiteralMembersForValue(value) {
6951
+ if (value instanceof RegExp) {
6952
+ return literalRegExpMembers;
6953
+ }
6954
+ switch (typeof value) {
6955
+ case 'boolean': {
6956
+ return literalBooleanMembers;
6957
+ }
6958
+ case 'number': {
6959
+ return literalNumberMembers;
6960
+ }
6961
+ case 'string': {
6962
+ return literalStringMembers;
6963
+ }
6964
+ }
6965
+ return Object.create(null);
6966
+ }
6967
+ function hasMemberEffectWhenCalled(members, memberName, interaction, context) {
6968
+ if (typeof memberName !== 'string' || !members[memberName]) {
6969
+ return true;
6970
+ }
6971
+ return members[memberName].hasEffectsWhenCalled?.(interaction, context) || false;
6972
+ }
6973
+ function getMemberReturnExpressionWhenCalled(members, memberName) {
6974
+ if (typeof memberName !== 'string' || !members[memberName])
6975
+ return UNKNOWN_RETURN_EXPRESSION;
6976
+ return [members[memberName].returns, false];
6977
+ }
6978
+
6979
+ class Variable extends ExpressionEntity {
6980
+ markReassigned() {
6981
+ this.isReassigned = true;
6982
+ }
6983
+ constructor(name) {
6984
+ super();
6985
+ this.name = name;
6986
+ this.alwaysRendered = false;
6987
+ this.forbiddenNames = null;
6988
+ this.globalName = null;
6989
+ this.initReached = false;
6990
+ this.isId = false;
6991
+ this.kind = null;
6992
+ this.renderBaseName = null;
6993
+ this.renderName = null;
6994
+ this.isReassigned = false;
6995
+ this.onlyFunctionCallUsed = true;
6996
+ }
6997
+ /**
6998
+ * Binds identifiers that reference this variable to this variable.
6999
+ * Necessary to be able to change variable names.
7000
+ */
7001
+ addReference(_identifier) { }
7002
+ /**
7003
+ * Check if the identifier variable is only used as function call
7004
+ * @returns true if the variable is only used as function call
7005
+ */
7006
+ getOnlyFunctionCallUsed() {
7007
+ return this.onlyFunctionCallUsed;
7008
+ }
7009
+ /**
7010
+ * Collect the places where the identifier variable is used
7011
+ * @param usedPlace Where the variable is used
7012
+ */
7013
+ addUsedPlace(usedPlace) {
7014
+ const isFunctionCall = usedPlace.parent.type === parseAst_js.CallExpression && usedPlace.parent.callee === usedPlace;
7015
+ if (!isFunctionCall && usedPlace.parent.type !== parseAst_js.ExportDefaultDeclaration) {
7016
+ this.onlyFunctionCallUsed = false;
7017
+ }
7018
+ }
7019
+ /**
7020
+ * Prevent this variable from being renamed to this name to avoid name
7021
+ * collisions
7022
+ */
7023
+ forbidName(name) {
7024
+ (this.forbiddenNames ||= new Set()).add(name);
7025
+ }
7026
+ getBaseVariableName() {
7027
+ return (this.renderedLikeHoisted?.getBaseVariableName() ||
7028
+ this.renderBaseName ||
7029
+ this.renderName ||
7030
+ this.name);
7031
+ }
7032
+ getName(getPropertyAccess, useOriginalName) {
7033
+ if (this.globalName) {
7034
+ return this.globalName;
7035
+ }
7036
+ if (useOriginalName?.(this)) {
7037
+ return this.name;
7038
+ }
7039
+ if (this.renderedLikeHoisted) {
7040
+ return this.renderedLikeHoisted.getName(getPropertyAccess, useOriginalName);
7041
+ }
7042
+ const name = this.renderName || this.name;
7043
+ return this.renderBaseName ? `${this.renderBaseName}${getPropertyAccess(name)}` : name;
7044
+ }
7045
+ hasEffectsOnInteractionAtPath(path, { type }, _context) {
7046
+ return type !== INTERACTION_ACCESSED || path.length > 0;
7047
+ }
7048
+ /**
7049
+ * Marks this variable as being part of the bundle, which is usually the case
7050
+ * when one of its identifiers becomes part of the bundle. Returns true if it
7051
+ * has not been included previously. Once a variable is included, it should
7052
+ * take care all its declarations are included.
7053
+ */
7054
+ includePath(path, context) {
7055
+ this.included = true;
7056
+ this.renderedLikeHoisted?.includePath(path, context);
7057
+ }
7058
+ /**
7059
+ * Links the rendered name of this variable to another variable and includes
7060
+ * this variable if the other variable is included.
7061
+ */
7062
+ renderLikeHoisted(variable) {
7063
+ this.renderedLikeHoisted = variable;
7064
+ }
7065
+ markCalledFromTryStatement() { }
7066
+ addReassignedValue(_value) { }
7067
+ setRenderNames(baseName, name) {
7068
+ this.renderBaseName = baseName;
7069
+ this.renderName = name;
7070
+ }
7071
+ }
7072
+
7073
+ class LocalVariable extends Variable {
7074
+ constructor(name, declarator, init,
7075
+ /** if this is non-empty, the actual init is this path of this.init */
7076
+ initPath, context, kind) {
7077
+ super(name);
7078
+ this.init = init;
7079
+ this.initPath = initPath;
7080
+ this.kind = kind;
7081
+ this.calledFromTryStatement = false;
7082
+ this.additionalInitializers = null;
7083
+ // A possibly incomplete list of values assigned to this variable after its
7084
+ // declaration; as it is incomplete, it must never be used for value queries
7085
+ // but only to forward call arguments to possible values
7086
+ this.reassignedValues = null;
7087
+ this.includedPathTracker = new IncludedFullPathTracker();
7088
+ this.expressionsToBeDeoptimized = [];
7089
+ this.declarations = declarator ? [declarator] : [];
7090
+ this.deoptimizationTracker = context.deoptimizationTracker;
7091
+ this.module = context.module;
7092
+ }
7093
+ addDeclaration(identifier, init) {
7094
+ this.declarations.push(identifier);
7095
+ this.markInitializersForDeoptimization().push(init);
7096
+ }
7097
+ consolidateInitializers() {
7098
+ if (this.additionalInitializers) {
7099
+ for (const initializer of this.additionalInitializers) {
7100
+ initializer.deoptimizePath(UNKNOWN_PATH);
7101
+ }
7102
+ }
7103
+ }
7104
+ deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
7105
+ if (this.isReassigned || path.length + this.initPath.length > MAX_PATH_DEPTH) {
7106
+ deoptimizeInteraction(interaction);
7107
+ return;
7108
+ }
7109
+ recursionTracker.withTrackedEntityAtPath(path, this.init, () => {
7110
+ this.init.deoptimizeArgumentsOnInteractionAtPath(interaction, [...this.initPath, ...path], recursionTracker);
7111
+ }, undefined);
7112
+ }
7113
+ deoptimizePath(path) {
7114
+ if (this.isReassigned ||
7115
+ this.deoptimizationTracker.trackEntityAtPathAndGetIfTracked(path, this)) {
7116
+ return;
7117
+ }
7118
+ if (path.length === 0) {
7119
+ this.markReassigned();
7120
+ const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized;
7121
+ this.expressionsToBeDeoptimized = parseAst_js.EMPTY_ARRAY;
7122
+ for (const expression of expressionsToBeDeoptimized) {
7123
+ expression.deoptimizeCache();
7124
+ }
7125
+ this.init.deoptimizePath([...this.initPath, UnknownKey]);
7126
+ }
7127
+ else {
7128
+ this.init.deoptimizePath(limitConcatenatedPathDepth(this.initPath, path));
7129
+ }
7130
+ }
7131
+ getLiteralValueAtPath(path, recursionTracker, origin) {
7132
+ if (this.isReassigned || path.length + this.initPath.length > MAX_PATH_DEPTH) {
7133
+ return UnknownValue;
7134
+ }
7135
+ return recursionTracker.withTrackedEntityAtPath(path, this.init, () => {
7136
+ this.expressionsToBeDeoptimized.push(origin);
7137
+ return this.init.getLiteralValueAtPath([...this.initPath, ...path], recursionTracker, origin);
7138
+ }, UnknownValue);
7139
+ }
7140
+ getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
7141
+ if (this.isReassigned || path.length + this.initPath.length > MAX_PATH_DEPTH) {
7142
+ return UNKNOWN_RETURN_EXPRESSION;
7143
+ }
7144
+ return recursionTracker.withTrackedEntityAtPath(path, this.init, () => {
7145
+ this.expressionsToBeDeoptimized.push(origin);
7146
+ return this.init.getReturnExpressionWhenCalledAtPath([...this.initPath, ...path], interaction, recursionTracker, origin);
7147
+ }, UNKNOWN_RETURN_EXPRESSION);
7148
+ }
7149
+ hasEffectsOnInteractionAtPath(path, interaction, context) {
7150
+ if (path.length + this.initPath.length > MAX_PATH_DEPTH) {
7151
+ return true;
7152
+ }
7153
+ switch (interaction.type) {
7154
+ case INTERACTION_ACCESSED: {
7155
+ if (this.isReassigned)
7156
+ return true;
7157
+ return (!context.accessed.trackEntityAtPathAndGetIfTracked(path, this) &&
7158
+ this.init.hasEffectsOnInteractionAtPath([...this.initPath, ...path], interaction, context));
7159
+ }
7160
+ case INTERACTION_ASSIGNED: {
7161
+ if (this.included)
7162
+ return true;
7163
+ if (path.length === 0)
7164
+ return false;
7165
+ // if (this.isReassigned || this.init.included) return true;
7166
+ if (this.isReassigned)
7167
+ return true;
7168
+ return (!context.assigned.trackEntityAtPathAndGetIfTracked(path, this) &&
7169
+ this.init.hasEffectsOnInteractionAtPath([...this.initPath, ...path], interaction, context));
7170
+ }
7171
+ case INTERACTION_CALLED: {
7172
+ if (this.isReassigned)
7173
+ return true;
7174
+ return (!(interaction.withNew ? context.instantiated : context.called).trackEntityAtPathAndGetIfTracked(path, interaction.args, this) &&
7175
+ this.init.hasEffectsOnInteractionAtPath([...this.initPath, ...path], interaction, context));
7176
+ }
7177
+ }
7178
+ }
7179
+ includePath(path, context) {
7180
+ if (!this.includedPathTracker.includePathAndGetIfIncluded(path)) {
7181
+ this.module.scope.context.requestTreeshakingPass();
7182
+ if (!this.included) {
7183
+ // This will reduce the number of tree-shaking passes by eagerly
7184
+ // including inits. By pushing this here instead of directly including
7185
+ // we avoid deep call stacks.
7186
+ this.module.scope.context.newlyIncludedVariableInits.add(this.init);
7187
+ }
7188
+ super.includePath(path, context);
7189
+ for (const declaration of this.declarations) {
7190
+ // If node is a default export, it can save a tree-shaking run to include the full declaration now
7191
+ if (!declaration.included)
7192
+ declaration.include(context, false);
7193
+ let node = declaration.parent;
7194
+ while (!node.included) {
7195
+ // We do not want to properly include parents in case they are part of a dead branch
7196
+ // in which case .include() might pull in more dead code
7197
+ node.includeNode(context);
7198
+ if (node.type === parseAst_js.Program)
7199
+ break;
7200
+ node = node.parent;
7201
+ }
7202
+ }
7203
+ // We need to make sure we include the correct path of the init
7204
+ if (path.length > 0) {
7205
+ this.init.includePath(limitConcatenatedPathDepth(this.initPath, path), context);
7206
+ this.additionalInitializers?.forEach(initializer => initializer.includePath(UNKNOWN_PATH, context));
7207
+ }
7208
+ }
7209
+ }
7210
+ includeCallArgumentsWhenCalledAtPath(path, interaction, context) {
7211
+ if (this.isReassigned) {
7212
+ // Even when the value is unknown, it may be one of the assigned values;
7213
+ // forwarding to all of them retains the arguments of try-catch helpers
7214
+ includeInteraction(interaction, context);
7215
+ // Each possible value is visited at most once per path and call
7216
+ // per traversal so that dense assignment graphs do not repeat work
7217
+ // for every simple path
7218
+ const previousTracker = context.includedCallArgumentsOfPossibleValues;
7219
+ context.includedCallArgumentsOfPossibleValues ??= new DiscriminatedPathTracker();
7220
+ this.includeCallArgumentsOfPossibleValues(path, interaction, context, context.includedCallArgumentsOfPossibleValues);
7221
+ context.includedCallArgumentsOfPossibleValues = previousTracker;
7222
+ return;
7223
+ }
7224
+ if (context.includedCallArguments.has(this.init) ||
7225
+ path.length + this.initPath.length > MAX_PATH_DEPTH) {
7226
+ includeInteraction(interaction, context);
7227
+ return;
7228
+ }
7229
+ context.includedCallArguments.add(this.init);
7230
+ this.init.includeCallArgumentsWhenCalledAtPath([...this.initPath, ...path], interaction, context);
7231
+ context.includedCallArguments.delete(this.init);
7232
+ }
7233
+ includeCallArgumentsOfPossibleValues(path, interaction, context, tracker) {
7234
+ if (this.reassignedValues === null || path.length + this.initPath.length > MAX_PATH_DEPTH) {
7235
+ return;
7236
+ }
7237
+ this.includeCallArgumentsOfPossibleValue(this.init, [...this.initPath, ...path], interaction, context, tracker);
7238
+ for (const entity of this.reassignedValues) {
7239
+ this.includeCallArgumentsOfPossibleValue(entity, path, interaction, context, tracker);
7240
+ }
7241
+ }
7242
+ includeCallArgumentsOfPossibleValue(entity, path, interaction, context, tracker) {
7243
+ if (entity === UNKNOWN_EXPRESSION ||
7244
+ entity === UNDEFINED_EXPRESSION ||
7245
+ tracker.trackEntityAtPathAndGetIfTracked(path, interaction, entity)) {
7246
+ return;
7247
+ }
7248
+ entity.includeCallArgumentsWhenCalledAtPath(path, interaction, context);
7249
+ }
7250
+ addReassignedValue(value) {
7251
+ (this.reassignedValues ??= []).push(value);
7252
+ }
7253
+ markCalledFromTryStatement() {
7254
+ this.calledFromTryStatement = true;
7255
+ }
7256
+ markInitializersForDeoptimization() {
7257
+ if (this.additionalInitializers === null) {
7258
+ this.additionalInitializers = [this.init];
7259
+ this.init = UNKNOWN_EXPRESSION;
7260
+ this.markReassigned();
7261
+ }
7262
+ return this.additionalInitializers;
7263
+ }
7264
+ }
7265
+
7266
+ class Scope {
7267
+ constructor() {
7268
+ this.children = [];
7269
+ this.variables = new Map();
7270
+ }
7271
+ /*
7272
+ Redeclaration rules:
7273
+ - var can redeclare var
7274
+ - in function scopes, function and var can redeclare function and var
7275
+ - var is hoisted across scopes, function remains in the scope it is declared
7276
+ - var and function can redeclare function parameters, but parameters cannot redeclare parameters
7277
+ - function cannot redeclare catch scope parameters
7278
+ - var can redeclare catch scope parameters in a way
7279
+ - if the parameter is an identifier and not a pattern
7280
+ - then the variable is still declared in the hoisted outer scope, but the initializer is assigned to the parameter
7281
+ - const, let, class, and function except in the cases above cannot redeclare anything
7282
+ */
7283
+ addDeclaration(identifier, context, init, destructuredInitPath, kind) {
7284
+ const name = identifier.name;
7285
+ const existingVariable = this.hoistedVariables?.get(name) || this.variables.get(name);
7286
+ if (existingVariable) {
7287
+ if (kind === 'var' && existingVariable.kind === 'var') {
7288
+ existingVariable.addDeclaration(identifier, init);
7289
+ return existingVariable;
7290
+ }
7291
+ context.error(parseAst_js.logRedeclarationError(name), identifier.start);
7292
+ }
7293
+ const newVariable = new LocalVariable(identifier.name, identifier, init, destructuredInitPath, context, kind);
7294
+ this.variables.set(name, newVariable);
7295
+ return newVariable;
7296
+ }
7297
+ addHoistedVariable(name, variable) {
7298
+ (this.hoistedVariables ||= new Map()).set(name, variable);
7299
+ }
7300
+ contains(name) {
7301
+ return this.variables.has(name);
7302
+ }
7303
+ findVariable(_name) {
7304
+ /* istanbul ignore next */
7305
+ throw new Error('Internal Error: findVariable needs to be implemented by a subclass');
7306
+ }
7307
+ }
7308
+
7309
+ class ChildScope extends Scope {
7310
+ constructor(parent, context) {
7311
+ super();
7312
+ this.parent = parent;
7313
+ this.context = context;
7314
+ this.accessedOutsideVariables = new Map();
7315
+ parent.children.push(this);
7316
+ }
7317
+ addAccessedDynamicImport(importExpression) {
7318
+ (this.accessedDynamicImports || (this.accessedDynamicImports = new Set())).add(importExpression);
7319
+ if (this.parent instanceof ChildScope) {
7320
+ this.parent.addAccessedDynamicImport(importExpression);
7321
+ }
7322
+ }
7323
+ addAccessedGlobals(globals, accessedGlobalsByScope) {
7324
+ const accessedGlobals = accessedGlobalsByScope.get(this) || new Set();
7325
+ for (const name of globals) {
7326
+ accessedGlobals.add(name);
7327
+ }
7328
+ accessedGlobalsByScope.set(this, accessedGlobals);
7329
+ if (this.parent instanceof ChildScope) {
7330
+ this.parent.addAccessedGlobals(globals, accessedGlobalsByScope);
7331
+ }
7332
+ }
7333
+ addNamespaceMemberAccess(name, variable) {
7334
+ this.accessedOutsideVariables.set(name, variable);
7335
+ this.parent.addNamespaceMemberAccess(name, variable);
7336
+ }
7337
+ addReturnExpression(expression) {
7338
+ if (this.parent instanceof ChildScope) {
7339
+ this.parent.addReturnExpression(expression);
7340
+ }
7341
+ }
7342
+ addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope) {
7343
+ for (const variable of this.accessedOutsideVariables.values()) {
7344
+ if (variable.included) {
7345
+ usedNames.add(variable.getBaseVariableName());
7346
+ // In system format, exported variables are assigned via `exports(name, value)`.
7347
+ // Any scope that references such a variable must treat `exports` as used so
7348
+ // that a nested binding of the same name does not shadow the system wrapper's
7349
+ // `exports` argument.
7350
+ if (format === 'system' && exportNamesByVariable.has(variable)) {
7351
+ usedNames.add('exports');
7352
+ }
7353
+ }
7354
+ }
7355
+ const accessedGlobals = accessedGlobalsByScope.get(this);
7356
+ if (accessedGlobals) {
7357
+ for (const name of accessedGlobals) {
7358
+ usedNames.add(name);
7359
+ }
7360
+ }
7361
+ }
7362
+ contains(name) {
7363
+ return this.variables.has(name) || this.parent.contains(name);
7364
+ }
7365
+ deconflict(format, exportNamesByVariable, accessedGlobalsByScope) {
7366
+ const usedNames = new Set();
7367
+ this.addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope);
7368
+ if (this.accessedDynamicImports) {
7369
+ for (const importExpression of this.accessedDynamicImports) {
7370
+ if (importExpression.inlineNamespace) {
7371
+ usedNames.add(importExpression.inlineNamespace.getBaseVariableName());
7372
+ }
7373
+ }
7374
+ }
7375
+ for (const [name, variable] of this.variables) {
7376
+ if (variable.included || variable.alwaysRendered) {
7377
+ variable.setRenderNames(null, getSafeName(name, usedNames, variable.forbiddenNames));
7378
+ }
7379
+ }
7380
+ for (const scope of this.children) {
7381
+ scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
7382
+ }
7383
+ }
7384
+ findLexicalBoundary() {
7385
+ return this.parent.findLexicalBoundary();
7386
+ }
7387
+ findGlobal(name) {
7388
+ const variable = this.parent.findVariable(name);
7389
+ this.accessedOutsideVariables.set(name, variable);
7390
+ return variable;
7391
+ }
7392
+ findVariable(name) {
7393
+ const knownVariable = this.variables.get(name) || this.accessedOutsideVariables.get(name);
7394
+ if (knownVariable) {
7395
+ return knownVariable;
7396
+ }
7397
+ const variable = this.parent.findVariable(name);
7398
+ this.accessedOutsideVariables.set(name, variable);
7399
+ return variable;
7400
+ }
7401
+ }
7402
+
7403
+ function checkEffectForNodes(nodes, context) {
7404
+ for (const node of nodes) {
7405
+ if (node.hasEffects(context)) {
7406
+ return true;
7407
+ }
7408
+ }
7409
+ return false;
7410
+ }
7411
+
7412
+ /** @import { Node } from 'estree' */
7413
+
7414
+ /**
7415
+ * @param {Node} node
7416
+ * @param {Node} parent
7417
+ * @returns {boolean}
7418
+ */
7419
+ function is_reference(node, parent) {
7420
+ if (node.type === 'MemberExpression') {
7421
+ return !node.computed && is_reference(node.object, node);
7422
+ }
7423
+
7424
+ if (node.type !== 'Identifier') return false;
7425
+
7426
+ switch (parent?.type) {
7427
+ // disregard `bar` in `foo.bar`
7428
+ case 'MemberExpression':
7429
+ return parent.computed || node === parent.object;
7430
+
7431
+ // disregard the `foo` in `class {foo(){}}` but keep it in `class {[foo](){}}`
7432
+ case 'MethodDefinition':
7433
+ return parent.computed;
7434
+
7435
+ // disregard the `meta` in `import.meta`
7436
+ case 'MetaProperty':
7437
+ return parent.meta === node;
7438
+
7439
+ // disregard the `foo` in `class {foo=bar}` but keep it in `class {[foo]=bar}` and `class {bar=foo}`
7440
+ case 'PropertyDefinition':
7441
+ return parent.computed || node === parent.value;
7442
+
7443
+ // disregard the `bar` in `{ bar: foo }`, but keep it in `{ [bar]: foo }`
7444
+ case 'Property':
7445
+ return parent.computed || node === parent.value;
7446
+
7447
+ // disregard the `bar` in `export { foo as bar }` or
7448
+ // the foo in `import { foo as bar }`
7449
+ case 'ExportSpecifier':
7450
+ case 'ImportSpecifier':
7451
+ return node === parent.local;
7452
+
7453
+ // disregard the `foo` in `foo: while (...) { ... break foo; ... continue foo;}`
7454
+ case 'LabeledStatement':
7455
+ case 'BreakStatement':
7456
+ case 'ContinueStatement':
7457
+ return false;
7458
+
7459
+ default:
7460
+ return true;
7461
+ }
7462
+ }
7463
+
7464
+ function createInclusionContext() {
7465
+ return {
7466
+ brokenFlow: false,
7467
+ hasBreak: false,
7468
+ hasContinue: false,
7469
+ includedCallArguments: new Set(),
7470
+ includedCallArgumentsOfPossibleValues: null,
7471
+ includedLabels: new Set()
7472
+ };
7473
+ }
7474
+ function createHasEffectsContext() {
7475
+ return {
7476
+ accessed: new EntityPathTracker(),
7477
+ assigned: new EntityPathTracker(),
7478
+ brokenFlow: false,
7479
+ called: new DiscriminatedPathTracker(),
7480
+ hasBreak: false,
7481
+ hasContinue: false,
7482
+ ignore: {
7483
+ breaks: false,
7484
+ continues: false,
7485
+ labels: new Set(),
7486
+ returnYield: false,
7487
+ this: false
7488
+ },
7489
+ includedLabels: new Set(),
7490
+ instantiated: new DiscriminatedPathTracker(),
7491
+ replacedVariableInits: new Map()
7492
+ };
7493
+ }
7494
+
7495
+ const PureFunctionKey = Symbol('PureFunction');
7496
+ const getPureFunctions = ({ treeshake }) => {
7497
+ const pureFunctions = Object.create(null);
7498
+ for (const functionName of treeshake ? treeshake.manualPureFunctions : []) {
7499
+ let currentFunctions = pureFunctions;
7500
+ for (const pathSegment of functionName.split('.')) {
7501
+ currentFunctions = currentFunctions[pathSegment] ||= Object.create(null);
7502
+ }
7503
+ currentFunctions[PureFunctionKey] = true;
7504
+ }
7505
+ return pureFunctions;
7506
+ };
7507
+
7508
+ /** Synthetic import name for source phase imports, similar to '*' for namespaces */
7509
+ const SOURCE_PHASE_IMPORT = '*source';
7510
+ class ExternalVariable extends Variable {
7511
+ constructor(module, name) {
7512
+ super(name);
7513
+ this.referenced = false;
7514
+ this.module = module;
7515
+ this.isNamespace = name === '*';
7516
+ this.isSourcePhase = name === SOURCE_PHASE_IMPORT;
7517
+ }
7518
+ addReference(identifier) {
7519
+ this.referenced = true;
7520
+ if (this.name === 'default' || this.name === '*') {
7521
+ this.module.suggestName(identifier.name);
7522
+ }
7523
+ }
7524
+ hasEffectsOnInteractionAtPath(path, { type }) {
7525
+ return type !== INTERACTION_ACCESSED || path.length > (this.isNamespace ? 1 : 0);
7526
+ }
7527
+ includePath(path, context) {
7528
+ super.includePath(path, context);
7529
+ this.module.used = true;
7530
+ }
7531
+ }
7532
+
7533
+ function cacheObjectGetters(object, getterProperties) {
7534
+ for (const property of getterProperties) {
7535
+ const propertyGetter = Object.getOwnPropertyDescriptor(object, property).get;
7536
+ Object.defineProperty(object, property, {
7537
+ get() {
7538
+ const value = propertyGetter.call(object);
7539
+ // This replaces the getter with a fixed value for subsequent calls
7540
+ Object.defineProperty(object, property, { value });
7541
+ return value;
7542
+ }
7543
+ });
7544
+ }
7545
+ }
7546
+
6945
7547
  const illegalCharacters = /[^\w$]/g;
6946
7548
  const illegalCharacter = /[^\w$]/;
6947
7549
  const startsWithDigit = (value) => /\d/.test(value[0]);
@@ -6979,9 +7581,10 @@ function stringifyIdentifierIfNeeded(key) {
6979
7581
  }
6980
7582
 
6981
7583
  class ExternalModule {
6982
- constructor(options, id, moduleSideEffects, meta, renormalizeRenderPath, attributes) {
7584
+ constructor(options, id, rawId, moduleSideEffects, meta, renormalizeRenderPath, attributes) {
6983
7585
  this.options = options;
6984
7586
  this.id = id;
7587
+ this.rawId = rawId;
6985
7588
  this.renormalizeRenderPath = renormalizeRenderPath;
6986
7589
  this.dynamicImporters = [];
6987
7590
  this.execIndex = Infinity;
@@ -6993,7 +7596,11 @@ class ExternalModule {
6993
7596
  this.importersByExportedName = new Map();
6994
7597
  this.mostCommonSuggestion = 0;
6995
7598
  this.nameSuggestions = new Map();
6996
- this.suggestedVariableName = makeLegal(id.split(/[/\\]/).pop());
7599
+ const nameAttributes = new URLSearchParams(attributes);
7600
+ nameAttributes.sort();
7601
+ const attributesString = nameAttributes.toString();
7602
+ const attributesSuffix = attributesString ? `?${attributesString}` : '';
7603
+ this.suggestedVariableName = makeLegal(`${rawId.split(/[/\\]/).pop()}${attributesSuffix}`);
6997
7604
  const { importers, dynamicImporters } = this;
6998
7605
  this.info = {
6999
7606
  ast: null,
@@ -7020,6 +7627,7 @@ class ExternalModule {
7020
7627
  isIncluded: null,
7021
7628
  meta,
7022
7629
  moduleSideEffects,
7630
+ rawId,
7023
7631
  safeVariableNames: null,
7024
7632
  syntheticNamedExports: false
7025
7633
  };
@@ -7085,7 +7693,7 @@ function markModuleAndImpureDependenciesAsExecuted(baseModule) {
7085
7693
  }
7086
7694
  }
7087
7695
 
7088
- // This file is generated by scripts/generate-child-node-keys.js.
7696
+ // This file is generated by scripts/generate-child-node-keys.ts.
7089
7697
  // Do not edit this file directly.
7090
7698
  const childNodeKeys = {
7091
7699
  ArrayExpression: ['elements'],
@@ -7293,44 +7901,6 @@ class NodeBase extends ExpressionEntity {
7293
7901
  this.scope.context.magicString.addSourcemapLocation(this.start);
7294
7902
  this.scope.context.magicString.addSourcemapLocation(this.end);
7295
7903
  }
7296
- parseNode(esTreeNode) {
7297
- for (const [key, value] of Object.entries(esTreeNode)) {
7298
- // Skip properties defined on the class already.
7299
- // This way, we can override this function to add custom initialisation and then call super.parseNode
7300
- // Note: this doesn't skip properties with defined getters/setters which we use to pack wrap booleans
7301
- // in bitfields. Those are still assigned from the value in the esTreeNode.
7302
- if (this.hasOwnProperty(key))
7303
- continue;
7304
- if (key.charCodeAt(0) === 95 /* _ */) {
7305
- if (key === parseAst_js.ANNOTATION_KEY) {
7306
- this.annotations = value;
7307
- }
7308
- else if (key === parseAst_js.INVALID_ANNOTATION_KEY) {
7309
- this.invalidAnnotations = value;
7310
- }
7311
- }
7312
- else if (typeof value !== 'object' || value === null) {
7313
- this[key] = value;
7314
- }
7315
- else if (Array.isArray(value)) {
7316
- this[key] = new Array(value.length);
7317
- let index = 0;
7318
- for (const child of value) {
7319
- this[key][index++] =
7320
- child === null
7321
- ? null
7322
- : new (this.scope.context.getNodeConstructor(child.type))(this, this.scope).parseNode(child);
7323
- }
7324
- }
7325
- else {
7326
- this[key] = new (this.scope.context.getNodeConstructor(value.type))(this, this.scope).parseNode(value);
7327
- }
7328
- }
7329
- // extend child keys for unknown node types
7330
- childNodeKeys[esTreeNode.type] ||= createChildNodeKeysForNode(esTreeNode);
7331
- this.initialise();
7332
- return this;
7333
- }
7334
7904
  removeAnnotations(code) {
7335
7905
  if (this.annotations) {
7336
7906
  for (const annotation of this.annotations) {
@@ -7371,260 +7941,40 @@ class NodeBase extends ExpressionEntity {
7371
7941
  if (value === null)
7372
7942
  continue;
7373
7943
  if (Array.isArray(value)) {
7374
- for (const child of value) {
7375
- child?.deoptimizePath(UNKNOWN_PATH);
7376
- }
7377
- }
7378
- else {
7379
- value.deoptimizePath(UNKNOWN_PATH);
7380
- }
7381
- }
7382
- this.scope.context.requestTreeshakingPass();
7383
- }
7384
- }
7385
- function createChildNodeKeysForNode(esTreeNode) {
7386
- return Object.keys(esTreeNode).filter(key => typeof esTreeNode[key] === 'object' && key.charCodeAt(0) !== 95 /* _ */);
7387
- }
7388
- function onlyIncludeSelf() {
7389
- this.included = true;
7390
- if (!this.deoptimized)
7391
- this.applyDeoptimizations();
7392
- }
7393
- function onlyIncludeSelfNoDeoptimize() {
7394
- this.included = true;
7395
- }
7396
- function doNotDeoptimize() {
7397
- this.deoptimized = true;
7398
- }
7399
-
7400
- function isObjectExpressionNode(node) {
7401
- return node instanceof NodeBase && node.type === parseAst_js.ObjectExpression;
7402
- }
7403
- function isPropertyNode(node) {
7404
- return node instanceof NodeBase && node.type === parseAst_js.Property;
7405
- }
7406
- function isArrowFunctionExpressionNode(node) {
7407
- return node instanceof NodeBase && node.type === parseAst_js.ArrowFunctionExpression;
7408
- }
7409
- function isFunctionExpressionNode(node) {
7410
- return node instanceof NodeBase && node.type === parseAst_js.FunctionExpression;
7411
- }
7412
- function isCallExpressionNode(node) {
7413
- return node instanceof NodeBase && node.type === parseAst_js.CallExpression;
7414
- }
7415
- function isMemberExpressionNode(node) {
7416
- return node instanceof NodeBase && node.type === parseAst_js.MemberExpression;
7417
- }
7418
- function isAwaitExpressionNode(node) {
7419
- return node instanceof NodeBase && node.type === parseAst_js.AwaitExpression;
7420
- }
7421
- function isIdentifierNode(node) {
7422
- return node instanceof NodeBase && node.type === parseAst_js.Identifier;
7423
- }
7424
- function isExpressionStatementNode(node) {
7425
- return node instanceof NodeBase && node.type === parseAst_js.ExpressionStatement;
7426
- }
7427
-
7428
- function assembleMemberDescriptions(memberDescriptions, inheritedDescriptions = null) {
7429
- return Object.create(inheritedDescriptions, memberDescriptions);
7430
- }
7431
- const UNDEFINED_EXPRESSION = new (class UndefinedExpression extends ExpressionEntity {
7432
- getLiteralValueAtPath(path) {
7433
- return path.length > 0 ? UnknownValue : undefined;
7434
- }
7435
- })();
7436
- const returnsUnknown = {
7437
- value: {
7438
- hasEffectsWhenCalled: null,
7439
- returns: UNKNOWN_EXPRESSION
7440
- }
7441
- };
7442
- const UNKNOWN_LITERAL_BOOLEAN = new (class UnknownBoolean extends ExpressionEntity {
7443
- getReturnExpressionWhenCalledAtPath(path) {
7444
- if (path.length === 1) {
7445
- return getMemberReturnExpressionWhenCalled(literalBooleanMembers, path[0]);
7446
- }
7447
- return UNKNOWN_RETURN_EXPRESSION;
7448
- }
7449
- hasEffectsOnInteractionAtPath(path, interaction, context) {
7450
- if (interaction.type === INTERACTION_ACCESSED) {
7451
- return path.length > 1;
7452
- }
7453
- if (interaction.type === INTERACTION_CALLED && path.length === 1) {
7454
- return hasMemberEffectWhenCalled(literalBooleanMembers, path[0], interaction, context);
7455
- }
7456
- return true;
7457
- }
7458
- })();
7459
- const returnsBoolean = {
7460
- value: {
7461
- hasEffectsWhenCalled: null,
7462
- returns: UNKNOWN_LITERAL_BOOLEAN
7463
- }
7464
- };
7465
- const UNKNOWN_LITERAL_NUMBER = new (class UnknownNumber extends ExpressionEntity {
7466
- getReturnExpressionWhenCalledAtPath(path) {
7467
- if (path.length === 1) {
7468
- return getMemberReturnExpressionWhenCalled(literalNumberMembers, path[0]);
7469
- }
7470
- return UNKNOWN_RETURN_EXPRESSION;
7471
- }
7472
- hasEffectsOnInteractionAtPath(path, interaction, context) {
7473
- if (interaction.type === INTERACTION_ACCESSED) {
7474
- return path.length > 1;
7475
- }
7476
- if (interaction.type === INTERACTION_CALLED && path.length === 1) {
7477
- return hasMemberEffectWhenCalled(literalNumberMembers, path[0], interaction, context);
7478
- }
7479
- return true;
7480
- }
7481
- })();
7482
- const returnsNumber = {
7483
- value: {
7484
- hasEffectsWhenCalled: null,
7485
- returns: UNKNOWN_LITERAL_NUMBER
7486
- }
7487
- };
7488
- const UNKNOWN_LITERAL_STRING = new (class UnknownString extends ExpressionEntity {
7489
- getReturnExpressionWhenCalledAtPath(path) {
7490
- if (path.length === 1) {
7491
- return getMemberReturnExpressionWhenCalled(literalStringMembers, path[0]);
7492
- }
7493
- return UNKNOWN_RETURN_EXPRESSION;
7494
- }
7495
- hasEffectsOnInteractionAtPath(path, interaction, context) {
7496
- if (interaction.type === INTERACTION_ACCESSED) {
7497
- return path.length > 1;
7498
- }
7499
- if (interaction.type === INTERACTION_CALLED && path.length === 1) {
7500
- return hasMemberEffectWhenCalled(literalStringMembers, path[0], interaction, context);
7501
- }
7502
- return true;
7503
- }
7504
- })();
7505
- const returnsString = {
7506
- value: {
7507
- hasEffectsWhenCalled: null,
7508
- returns: UNKNOWN_LITERAL_STRING
7509
- }
7510
- };
7511
- const stringReplace = {
7512
- value: {
7513
- hasEffectsWhenCalled({ args }, context) {
7514
- const argument1 = args[2];
7515
- return (args.length < 3 ||
7516
- (typeof argument1.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, {
7517
- deoptimizeCache() { }
7518
- }) === 'symbol' &&
7519
- argument1.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, context)));
7520
- },
7521
- returns: UNKNOWN_LITERAL_STRING
7522
- }
7523
- };
7524
- const objectMembers = assembleMemberDescriptions({
7525
- hasOwnProperty: returnsBoolean,
7526
- isPrototypeOf: returnsBoolean,
7527
- propertyIsEnumerable: returnsBoolean,
7528
- toLocaleString: returnsString,
7529
- toString: returnsString,
7530
- valueOf: returnsUnknown
7531
- });
7532
- const literalBooleanMembers = assembleMemberDescriptions({
7533
- valueOf: returnsBoolean
7534
- }, objectMembers);
7535
- const literalNumberMembers = assembleMemberDescriptions({
7536
- toExponential: returnsString,
7537
- toFixed: returnsString,
7538
- toLocaleString: returnsString,
7539
- toPrecision: returnsString,
7540
- valueOf: returnsNumber
7541
- }, objectMembers);
7542
- /**
7543
- * RegExp are stateful when they have the global or sticky flags set.
7544
- * But if we actually don't use them, the side effect does not matter.
7545
- * the check logic in `hasEffectsOnInteractionAtPath`.
7546
- */
7547
- const literalRegExpMembers = assembleMemberDescriptions({
7548
- exec: returnsUnknown,
7549
- test: returnsBoolean
7550
- }, objectMembers);
7551
- const literalStringMembers = assembleMemberDescriptions({
7552
- anchor: returnsString,
7553
- at: returnsUnknown,
7554
- big: returnsString,
7555
- blink: returnsString,
7556
- bold: returnsString,
7557
- charAt: returnsString,
7558
- charCodeAt: returnsNumber,
7559
- codePointAt: returnsUnknown,
7560
- concat: returnsString,
7561
- endsWith: returnsBoolean,
7562
- fixed: returnsString,
7563
- fontcolor: returnsString,
7564
- fontsize: returnsString,
7565
- includes: returnsBoolean,
7566
- indexOf: returnsNumber,
7567
- italics: returnsString,
7568
- lastIndexOf: returnsNumber,
7569
- link: returnsString,
7570
- localeCompare: returnsNumber,
7571
- match: returnsUnknown,
7572
- matchAll: returnsUnknown,
7573
- normalize: returnsString,
7574
- padEnd: returnsString,
7575
- padStart: returnsString,
7576
- repeat: returnsString,
7577
- replace: stringReplace,
7578
- replaceAll: stringReplace,
7579
- search: returnsNumber,
7580
- slice: returnsString,
7581
- small: returnsString,
7582
- split: returnsUnknown,
7583
- startsWith: returnsBoolean,
7584
- strike: returnsString,
7585
- sub: returnsString,
7586
- substr: returnsString,
7587
- substring: returnsString,
7588
- sup: returnsString,
7589
- toLocaleLowerCase: returnsString,
7590
- toLocaleUpperCase: returnsString,
7591
- toLowerCase: returnsString,
7592
- toString: returnsString, // overrides the toString() method of the Object object; it does not inherit Object.prototype.toString()
7593
- toUpperCase: returnsString,
7594
- trim: returnsString,
7595
- trimEnd: returnsString,
7596
- trimLeft: returnsString,
7597
- trimRight: returnsString,
7598
- trimStart: returnsString,
7599
- valueOf: returnsString
7600
- }, objectMembers);
7601
- function getLiteralMembersForValue(value) {
7602
- if (value instanceof RegExp) {
7603
- return literalRegExpMembers;
7604
- }
7605
- switch (typeof value) {
7606
- case 'boolean': {
7607
- return literalBooleanMembers;
7608
- }
7609
- case 'number': {
7610
- return literalNumberMembers;
7611
- }
7612
- case 'string': {
7613
- return literalStringMembers;
7944
+ for (const child of value) {
7945
+ child?.deoptimizePath(UNKNOWN_PATH);
7946
+ }
7947
+ }
7948
+ else {
7949
+ value.deoptimizePath(UNKNOWN_PATH);
7950
+ }
7614
7951
  }
7952
+ this.scope.context.requestTreeshakingPass();
7615
7953
  }
7616
- return Object.create(null);
7617
7954
  }
7618
- function hasMemberEffectWhenCalled(members, memberName, interaction, context) {
7619
- if (typeof memberName !== 'string' || !members[memberName]) {
7620
- return true;
7621
- }
7622
- return members[memberName].hasEffectsWhenCalled?.(interaction, context) || false;
7955
+ function onlyIncludeSelf() {
7956
+ this.included = true;
7957
+ if (!this.deoptimized)
7958
+ this.applyDeoptimizations();
7623
7959
  }
7624
- function getMemberReturnExpressionWhenCalled(members, memberName) {
7625
- if (typeof memberName !== 'string' || !members[memberName])
7626
- return UNKNOWN_RETURN_EXPRESSION;
7627
- return [members[memberName].returns, false];
7960
+ function onlyIncludeSelfNoDeoptimize() {
7961
+ this.included = true;
7962
+ }
7963
+ function doNotDeoptimize() {
7964
+ this.deoptimized = true;
7965
+ }
7966
+
7967
+ function isObjectExpressionNode(node) {
7968
+ return node instanceof NodeBase && node.type === parseAst_js.ObjectExpression;
7969
+ }
7970
+ function isArrowFunctionExpressionNode(node) {
7971
+ return node instanceof NodeBase && node.type === parseAst_js.ArrowFunctionExpression;
7972
+ }
7973
+ function isFunctionExpressionNode(node) {
7974
+ return node instanceof NodeBase && node.type === parseAst_js.FunctionExpression;
7975
+ }
7976
+ function isIdentifierNode(node) {
7977
+ return node instanceof NodeBase && node.type === parseAst_js.Identifier;
7628
7978
  }
7629
7979
 
7630
7980
  class Method extends ExpressionEntity {
@@ -8694,7 +9044,7 @@ const knownGlobals = {
8694
9044
  [ValueProperties]: {
8695
9045
  deoptimizeArgumentsOnCall: ({ args: [, target, parameter] }) => {
8696
9046
  if (isObjectExpressionNode(parameter)) {
8697
- const hasSpreadElement = parameter.properties.some(property => !isPropertyNode(property));
9047
+ const hasSpreadElement = parameter.properties.some(property => property.type !== parseAst_js.Property);
8698
9048
  if (!hasSpreadElement) {
8699
9049
  for (const property of parameter.properties) {
8700
9050
  property.deoptimizeArgumentsOnInteractionAtPath({
@@ -9447,236 +9797,27 @@ class GlobalVariable extends Variable {
9447
9797
  }
9448
9798
  }
9449
9799
  }
9450
- getLiteralValueAtPath(path, _recursionTracker, _origin) {
9451
- const globalAtPath = getGlobalAtPath([this.name, ...path]);
9452
- return globalAtPath ? globalAtPath.getLiteralValue() : UnknownValue;
9453
- }
9454
- hasEffectsOnInteractionAtPath(path, interaction, context) {
9455
- switch (interaction.type) {
9456
- case INTERACTION_ACCESSED: {
9457
- if (path.length === 0) {
9458
- // Technically, "undefined" is a global variable of sorts
9459
- return this.name !== 'undefined' && !getGlobalAtPath([this.name]);
9460
- }
9461
- return !getGlobalAtPath([this.name, ...path].slice(0, -1));
9462
- }
9463
- case INTERACTION_ASSIGNED: {
9464
- return true;
9465
- }
9466
- case INTERACTION_CALLED: {
9467
- const globalAtPath = getGlobalAtPath([this.name, ...path]);
9468
- return !globalAtPath || globalAtPath.hasEffectsWhenCalled(interaction, context);
9469
- }
9470
- }
9471
- }
9472
- }
9473
-
9474
- // To avoid infinite recursions
9475
- const MAX_PATH_DEPTH = 6;
9476
- // If a path is longer than MAX_PATH_DEPTH, it is truncated so that it is at
9477
- // most MAX_PATH_DEPTH long. The last element is always UnknownKey
9478
- const limitConcatenatedPathDepth = (path1, path2) => {
9479
- const { length: length1 } = path1;
9480
- const { length: length2 } = path2;
9481
- return length1 === 0
9482
- ? path2
9483
- : length2 === 0
9484
- ? path1
9485
- : length1 + length2 > MAX_PATH_DEPTH
9486
- ? [...path1, ...path2.slice(0, MAX_PATH_DEPTH - 1 - path1.length), 'UnknownKey']
9487
- : [...path1, ...path2];
9488
- };
9489
-
9490
- class LocalVariable extends Variable {
9491
- constructor(name, declarator, init,
9492
- /** if this is non-empty, the actual init is this path of this.init */
9493
- initPath, context, kind) {
9494
- super(name);
9495
- this.init = init;
9496
- this.initPath = initPath;
9497
- this.kind = kind;
9498
- this.calledFromTryStatement = false;
9499
- this.additionalInitializers = null;
9500
- // A possibly incomplete list of values assigned to this variable after its
9501
- // declaration; as it is incomplete, it must never be used for value queries
9502
- // but only to forward call arguments to possible values
9503
- this.reassignedValues = null;
9504
- this.includedPathTracker = new IncludedFullPathTracker();
9505
- this.expressionsToBeDeoptimized = [];
9506
- this.declarations = declarator ? [declarator] : [];
9507
- this.deoptimizationTracker = context.deoptimizationTracker;
9508
- this.module = context.module;
9509
- }
9510
- addDeclaration(identifier, init) {
9511
- this.declarations.push(identifier);
9512
- this.markInitializersForDeoptimization().push(init);
9513
- }
9514
- consolidateInitializers() {
9515
- if (this.additionalInitializers) {
9516
- for (const initializer of this.additionalInitializers) {
9517
- initializer.deoptimizePath(UNKNOWN_PATH);
9518
- }
9519
- }
9520
- }
9521
- deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
9522
- if (this.isReassigned || path.length + this.initPath.length > MAX_PATH_DEPTH) {
9523
- deoptimizeInteraction(interaction);
9524
- return;
9525
- }
9526
- recursionTracker.withTrackedEntityAtPath(path, this.init, () => {
9527
- this.init.deoptimizeArgumentsOnInteractionAtPath(interaction, [...this.initPath, ...path], recursionTracker);
9528
- }, undefined);
9529
- }
9530
- deoptimizePath(path) {
9531
- if (this.isReassigned ||
9532
- this.deoptimizationTracker.trackEntityAtPathAndGetIfTracked(path, this)) {
9533
- return;
9534
- }
9535
- if (path.length === 0) {
9536
- this.markReassigned();
9537
- const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized;
9538
- this.expressionsToBeDeoptimized = parseAst_js.EMPTY_ARRAY;
9539
- for (const expression of expressionsToBeDeoptimized) {
9540
- expression.deoptimizeCache();
9541
- }
9542
- this.init.deoptimizePath([...this.initPath, UnknownKey]);
9543
- }
9544
- else {
9545
- this.init.deoptimizePath(limitConcatenatedPathDepth(this.initPath, path));
9546
- }
9547
- }
9548
- getLiteralValueAtPath(path, recursionTracker, origin) {
9549
- if (this.isReassigned || path.length + this.initPath.length > MAX_PATH_DEPTH) {
9550
- return UnknownValue;
9551
- }
9552
- return recursionTracker.withTrackedEntityAtPath(path, this.init, () => {
9553
- this.expressionsToBeDeoptimized.push(origin);
9554
- return this.init.getLiteralValueAtPath([...this.initPath, ...path], recursionTracker, origin);
9555
- }, UnknownValue);
9556
- }
9557
- getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
9558
- if (this.isReassigned || path.length + this.initPath.length > MAX_PATH_DEPTH) {
9559
- return UNKNOWN_RETURN_EXPRESSION;
9560
- }
9561
- return recursionTracker.withTrackedEntityAtPath(path, this.init, () => {
9562
- this.expressionsToBeDeoptimized.push(origin);
9563
- return this.init.getReturnExpressionWhenCalledAtPath([...this.initPath, ...path], interaction, recursionTracker, origin);
9564
- }, UNKNOWN_RETURN_EXPRESSION);
9565
- }
9566
- hasEffectsOnInteractionAtPath(path, interaction, context) {
9567
- if (path.length + this.initPath.length > MAX_PATH_DEPTH) {
9568
- return true;
9569
- }
9570
- switch (interaction.type) {
9571
- case INTERACTION_ACCESSED: {
9572
- if (this.isReassigned)
9573
- return true;
9574
- return (!context.accessed.trackEntityAtPathAndGetIfTracked(path, this) &&
9575
- this.init.hasEffectsOnInteractionAtPath([...this.initPath, ...path], interaction, context));
9576
- }
9577
- case INTERACTION_ASSIGNED: {
9578
- if (this.included)
9579
- return true;
9580
- if (path.length === 0)
9581
- return false;
9582
- // if (this.isReassigned || this.init.included) return true;
9583
- if (this.isReassigned)
9584
- return true;
9585
- return (!context.assigned.trackEntityAtPathAndGetIfTracked(path, this) &&
9586
- this.init.hasEffectsOnInteractionAtPath([...this.initPath, ...path], interaction, context));
9587
- }
9588
- case INTERACTION_CALLED: {
9589
- if (this.isReassigned)
9590
- return true;
9591
- return (!(interaction.withNew ? context.instantiated : context.called).trackEntityAtPathAndGetIfTracked(path, interaction.args, this) &&
9592
- this.init.hasEffectsOnInteractionAtPath([...this.initPath, ...path], interaction, context));
9593
- }
9594
- }
9595
- }
9596
- includePath(path, context) {
9597
- if (!this.includedPathTracker.includePathAndGetIfIncluded(path)) {
9598
- this.module.scope.context.requestTreeshakingPass();
9599
- if (!this.included) {
9600
- // This will reduce the number of tree-shaking passes by eagerly
9601
- // including inits. By pushing this here instead of directly including
9602
- // we avoid deep call stacks.
9603
- this.module.scope.context.newlyIncludedVariableInits.add(this.init);
9604
- }
9605
- super.includePath(path, context);
9606
- for (const declaration of this.declarations) {
9607
- // If node is a default export, it can save a tree-shaking run to include the full declaration now
9608
- if (!declaration.included)
9609
- declaration.include(context, false);
9610
- let node = declaration.parent;
9611
- while (!node.included) {
9612
- // We do not want to properly include parents in case they are part of a dead branch
9613
- // in which case .include() might pull in more dead code
9614
- node.includeNode(context);
9615
- if (node.type === parseAst_js.Program)
9616
- break;
9617
- node = node.parent;
9618
- }
9619
- }
9620
- // We need to make sure we include the correct path of the init
9621
- if (path.length > 0) {
9622
- this.init.includePath(limitConcatenatedPathDepth(this.initPath, path), context);
9623
- this.additionalInitializers?.forEach(initializer => initializer.includePath(UNKNOWN_PATH, context));
9624
- }
9625
- }
9626
- }
9627
- includeCallArgumentsWhenCalledAtPath(path, interaction, context) {
9628
- if (this.isReassigned) {
9629
- // Even when the value is unknown, it may be one of the assigned values;
9630
- // forwarding to all of them retains the arguments of try-catch helpers
9631
- includeInteraction(interaction, context);
9632
- // Each possible value is visited at most once per path and call
9633
- // per traversal so that dense assignment graphs do not repeat work
9634
- // for every simple path
9635
- const previousTracker = context.includedCallArgumentsOfPossibleValues;
9636
- context.includedCallArgumentsOfPossibleValues ??= new DiscriminatedPathTracker();
9637
- this.includeCallArgumentsOfPossibleValues(path, interaction, context, context.includedCallArgumentsOfPossibleValues);
9638
- context.includedCallArgumentsOfPossibleValues = previousTracker;
9639
- return;
9640
- }
9641
- if (context.includedCallArguments.has(this.init) ||
9642
- path.length + this.initPath.length > MAX_PATH_DEPTH) {
9643
- includeInteraction(interaction, context);
9644
- return;
9645
- }
9646
- context.includedCallArguments.add(this.init);
9647
- this.init.includeCallArgumentsWhenCalledAtPath([...this.initPath, ...path], interaction, context);
9648
- context.includedCallArguments.delete(this.init);
9649
- }
9650
- includeCallArgumentsOfPossibleValues(path, interaction, context, tracker) {
9651
- if (this.reassignedValues === null || path.length + this.initPath.length > MAX_PATH_DEPTH) {
9652
- return;
9653
- }
9654
- this.includeCallArgumentsOfPossibleValue(this.init, [...this.initPath, ...path], interaction, context, tracker);
9655
- for (const entity of this.reassignedValues) {
9656
- this.includeCallArgumentsOfPossibleValue(entity, path, interaction, context, tracker);
9657
- }
9658
- }
9659
- includeCallArgumentsOfPossibleValue(entity, path, interaction, context, tracker) {
9660
- if (entity === UNKNOWN_EXPRESSION ||
9661
- entity === UNDEFINED_EXPRESSION ||
9662
- tracker.trackEntityAtPathAndGetIfTracked(path, interaction, entity)) {
9663
- return;
9664
- }
9665
- entity.includeCallArgumentsWhenCalledAtPath(path, interaction, context);
9666
- }
9667
- addReassignedValue(value) {
9668
- (this.reassignedValues ??= []).push(value);
9669
- }
9670
- markCalledFromTryStatement() {
9671
- this.calledFromTryStatement = true;
9800
+ getLiteralValueAtPath(path, _recursionTracker, _origin) {
9801
+ const globalAtPath = getGlobalAtPath([this.name, ...path]);
9802
+ return globalAtPath ? globalAtPath.getLiteralValue() : UnknownValue;
9672
9803
  }
9673
- markInitializersForDeoptimization() {
9674
- if (this.additionalInitializers === null) {
9675
- this.additionalInitializers = [this.init];
9676
- this.init = UNKNOWN_EXPRESSION;
9677
- this.markReassigned();
9804
+ hasEffectsOnInteractionAtPath(path, interaction, context) {
9805
+ switch (interaction.type) {
9806
+ case INTERACTION_ACCESSED: {
9807
+ if (path.length === 0) {
9808
+ // Technically, "undefined" is a global variable of sorts
9809
+ return this.name !== 'undefined' && !getGlobalAtPath([this.name]);
9810
+ }
9811
+ return !getGlobalAtPath([this.name, ...path].slice(0, -1));
9812
+ }
9813
+ case INTERACTION_ASSIGNED: {
9814
+ return true;
9815
+ }
9816
+ case INTERACTION_CALLED: {
9817
+ const globalAtPath = getGlobalAtPath([this.name, ...path]);
9818
+ return !globalAtPath || globalAtPath.hasEffectsWhenCalled(interaction, context);
9819
+ }
9678
9820
  }
9679
- return this.additionalInitializers;
9680
9821
  }
9681
9822
  }
9682
9823
 
@@ -9979,163 +10120,7 @@ class Identifier extends IdentifierBase {
9979
10120
  }
9980
10121
  }
9981
10122
 
9982
- function getSafeName(baseName, usedNames, forbiddenNames) {
9983
- let safeName = baseName;
9984
- let count = 1;
9985
- while (usedNames.has(safeName) || RESERVED_NAMES.has(safeName) || forbiddenNames?.has(safeName)) {
9986
- safeName = `${baseName}$${toBase64(count++)}`;
9987
- }
9988
- usedNames.add(safeName);
9989
- return safeName;
9990
- }
9991
-
9992
- class Scope {
9993
- constructor() {
9994
- this.children = [];
9995
- this.variables = new Map();
9996
- }
9997
- /*
9998
- Redeclaration rules:
9999
- - var can redeclare var
10000
- - in function scopes, function and var can redeclare function and var
10001
- - var is hoisted across scopes, function remains in the scope it is declared
10002
- - var and function can redeclare function parameters, but parameters cannot redeclare parameters
10003
- - function cannot redeclare catch scope parameters
10004
- - var can redeclare catch scope parameters in a way
10005
- - if the parameter is an identifier and not a pattern
10006
- - then the variable is still declared in the hoisted outer scope, but the initializer is assigned to the parameter
10007
- - const, let, class, and function except in the cases above cannot redeclare anything
10008
- */
10009
- addDeclaration(identifier, context, init, destructuredInitPath, kind) {
10010
- const name = identifier.name;
10011
- const existingVariable = this.hoistedVariables?.get(name) || this.variables.get(name);
10012
- if (existingVariable) {
10013
- if (kind === 'var' && existingVariable.kind === 'var') {
10014
- existingVariable.addDeclaration(identifier, init);
10015
- return existingVariable;
10016
- }
10017
- context.error(parseAst_js.logRedeclarationError(name), identifier.start);
10018
- }
10019
- const newVariable = new LocalVariable(identifier.name, identifier, init, destructuredInitPath, context, kind);
10020
- this.variables.set(name, newVariable);
10021
- return newVariable;
10022
- }
10023
- addHoistedVariable(name, variable) {
10024
- (this.hoistedVariables ||= new Map()).set(name, variable);
10025
- }
10026
- contains(name) {
10027
- return this.variables.has(name);
10028
- }
10029
- findVariable(_name) {
10030
- /* istanbul ignore next */
10031
- throw new Error('Internal Error: findVariable needs to be implemented by a subclass');
10032
- }
10033
- }
10034
-
10035
- class ChildScope extends Scope {
10036
- constructor(parent, context) {
10037
- super();
10038
- this.parent = parent;
10039
- this.context = context;
10040
- this.accessedOutsideVariables = new Map();
10041
- parent.children.push(this);
10042
- }
10043
- addAccessedDynamicImport(importExpression) {
10044
- (this.accessedDynamicImports || (this.accessedDynamicImports = new Set())).add(importExpression);
10045
- if (this.parent instanceof ChildScope) {
10046
- this.parent.addAccessedDynamicImport(importExpression);
10047
- }
10048
- }
10049
- addAccessedGlobals(globals, accessedGlobalsByScope) {
10050
- const accessedGlobals = accessedGlobalsByScope.get(this) || new Set();
10051
- for (const name of globals) {
10052
- accessedGlobals.add(name);
10053
- }
10054
- accessedGlobalsByScope.set(this, accessedGlobals);
10055
- if (this.parent instanceof ChildScope) {
10056
- this.parent.addAccessedGlobals(globals, accessedGlobalsByScope);
10057
- }
10058
- }
10059
- addNamespaceMemberAccess(name, variable) {
10060
- this.accessedOutsideVariables.set(name, variable);
10061
- this.parent.addNamespaceMemberAccess(name, variable);
10062
- }
10063
- addReturnExpression(expression) {
10064
- if (this.parent instanceof ChildScope) {
10065
- this.parent.addReturnExpression(expression);
10066
- }
10067
- }
10068
- addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope) {
10069
- for (const variable of this.accessedOutsideVariables.values()) {
10070
- if (variable.included) {
10071
- usedNames.add(variable.getBaseVariableName());
10072
- // In system format, exported variables are assigned via `exports(name, value)`.
10073
- // Any scope that references such a variable must treat `exports` as used so
10074
- // that a nested binding of the same name does not shadow the system wrapper's
10075
- // `exports` argument.
10076
- if (format === 'system' && exportNamesByVariable.has(variable)) {
10077
- usedNames.add('exports');
10078
- }
10079
- }
10080
- }
10081
- const accessedGlobals = accessedGlobalsByScope.get(this);
10082
- if (accessedGlobals) {
10083
- for (const name of accessedGlobals) {
10084
- usedNames.add(name);
10085
- }
10086
- }
10087
- }
10088
- contains(name) {
10089
- return this.variables.has(name) || this.parent.contains(name);
10090
- }
10091
- deconflict(format, exportNamesByVariable, accessedGlobalsByScope) {
10092
- const usedNames = new Set();
10093
- this.addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope);
10094
- if (this.accessedDynamicImports) {
10095
- for (const importExpression of this.accessedDynamicImports) {
10096
- if (importExpression.inlineNamespace) {
10097
- usedNames.add(importExpression.inlineNamespace.getBaseVariableName());
10098
- }
10099
- }
10100
- }
10101
- for (const [name, variable] of this.variables) {
10102
- if (variable.included || variable.alwaysRendered) {
10103
- variable.setRenderNames(null, getSafeName(name, usedNames, variable.forbiddenNames));
10104
- }
10105
- }
10106
- for (const scope of this.children) {
10107
- scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
10108
- }
10109
- }
10110
- findLexicalBoundary() {
10111
- return this.parent.findLexicalBoundary();
10112
- }
10113
- findGlobal(name) {
10114
- const variable = this.parent.findVariable(name);
10115
- this.accessedOutsideVariables.set(name, variable);
10116
- return variable;
10117
- }
10118
- findVariable(name) {
10119
- const knownVariable = this.variables.get(name) || this.accessedOutsideVariables.get(name);
10120
- if (knownVariable) {
10121
- return knownVariable;
10122
- }
10123
- const variable = this.parent.findVariable(name);
10124
- this.accessedOutsideVariables.set(name, variable);
10125
- return variable;
10126
- }
10127
- }
10128
-
10129
- function checkEffectForNodes(nodes, context) {
10130
- for (const node of nodes) {
10131
- if (node.hasEffects(context)) {
10132
- return true;
10133
- }
10134
- }
10135
- return false;
10136
- }
10137
-
10138
- class MethodBase extends NodeBase {
10123
+ class PropertyBase extends NodeBase {
10139
10124
  constructor() {
10140
10125
  super(...arguments);
10141
10126
  this.accessedValue = null;
@@ -10175,112 +10160,50 @@ class MethodBase extends NodeBase {
10175
10160
  getLiteralValueAtPath(path, recursionTracker, origin) {
10176
10161
  return this.getAccessedValue()[0].getLiteralValueAtPath(path, recursionTracker, origin);
10177
10162
  }
10178
- getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
10179
- return this.getAccessedValue()[0].getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
10180
- }
10181
- hasEffects(context) {
10182
- return this.key.hasEffects(context);
10183
- }
10184
- hasEffectsOnInteractionAtPath(path, interaction, context) {
10185
- if (this.kind === 'get' && interaction.type === INTERACTION_ACCESSED && path.length === 0) {
10186
- return this.value.hasEffectsOnInteractionAtPath(EMPTY_PATH, {
10187
- args: interaction.args,
10188
- type: INTERACTION_CALLED,
10189
- withNew: false
10190
- }, context);
10191
- }
10192
- // setters are only called for empty paths
10193
- if (this.kind === 'set' && interaction.type === INTERACTION_ASSIGNED) {
10194
- return this.value.hasEffectsOnInteractionAtPath(EMPTY_PATH, {
10195
- args: interaction.args,
10196
- type: INTERACTION_CALLED,
10197
- withNew: false
10198
- }, context);
10199
- }
10200
- return this.getAccessedValue()[0].hasEffectsOnInteractionAtPath(path, interaction, context);
10201
- }
10202
- getAccessedValue() {
10203
- if (this.accessedValue === null) {
10204
- if (this.kind === 'get') {
10205
- this.accessedValue = UNKNOWN_RETURN_EXPRESSION;
10206
- return (this.accessedValue = this.value.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, SHARED_RECURSION_TRACKER, this));
10207
- }
10208
- else {
10209
- return (this.accessedValue = [this.value, false]);
10210
- }
10211
- }
10212
- return this.accessedValue;
10213
- }
10214
- }
10215
- MethodBase.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
10216
- MethodBase.prototype.applyDeoptimizations = doNotDeoptimize;
10217
-
10218
- class MethodDefinition extends MethodBase {
10219
- hasEffects(context) {
10220
- return super.hasEffects(context) || checkEffectForNodes(this.decorators, context);
10221
- }
10222
- }
10223
-
10224
- class BlockScope extends ChildScope {
10225
- constructor(parent) {
10226
- super(parent, parent.context);
10227
- }
10228
- addDeclaration(identifier, context, init, destructuredInitPath, kind) {
10229
- if (kind === 'var') {
10230
- const name = identifier.name;
10231
- const existingVariable = this.hoistedVariables?.get(name) || this.variables.get(name);
10232
- if (existingVariable) {
10233
- if (existingVariable.kind === 'var' ||
10234
- (kind === 'var' && existingVariable.kind === 'parameter')) {
10235
- existingVariable.addDeclaration(identifier, init);
10236
- return existingVariable;
10237
- }
10238
- return context.error(parseAst_js.logRedeclarationError(name), identifier.start);
10239
- }
10240
- const declaredVariable = this.parent.addDeclaration(identifier, context, init, destructuredInitPath, kind);
10241
- // Necessary to make sure the init is deoptimized for conditional declarations.
10242
- // We cannot call deoptimizePath here.
10243
- declaredVariable.markInitializersForDeoptimization();
10244
- // We add the variable to this and all parent scopes to reliably detect conflicts
10245
- this.addHoistedVariable(name, declaredVariable);
10246
- return declaredVariable;
10247
- }
10248
- return super.addDeclaration(identifier, context, init, destructuredInitPath, kind);
10249
- }
10250
- }
10251
-
10252
- class StaticBlock extends NodeBase {
10253
- createScope(parentScope) {
10254
- this.scope = new BlockScope(parentScope);
10163
+ getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
10164
+ return this.getAccessedValue()[0].getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
10255
10165
  }
10256
10166
  hasEffects(context) {
10257
- for (const node of this.body) {
10258
- if (node.hasEffects(context))
10259
- return true;
10260
- }
10261
- return false;
10167
+ return this.key.hasEffects(context);
10262
10168
  }
10263
- include(context, includeChildrenRecursively) {
10264
- this.included = true;
10265
- for (const node of this.body) {
10266
- if (includeChildrenRecursively || node.shouldBeIncluded(context))
10267
- node.include(context, includeChildrenRecursively);
10169
+ hasEffectsOnInteractionAtPath(path, interaction, context) {
10170
+ if (this.kind === 'get' && interaction.type === INTERACTION_ACCESSED && path.length === 0) {
10171
+ return this.value.hasEffectsOnInteractionAtPath(EMPTY_PATH, {
10172
+ args: interaction.args,
10173
+ type: INTERACTION_CALLED,
10174
+ withNew: false
10175
+ }, context);
10268
10176
  }
10269
- }
10270
- render(code, options) {
10271
- if (this.body.length > 0) {
10272
- const bodyStartPos = findFirstOccurrenceOutsideComment(code.original.slice(this.start, this.end), '{') + 1;
10273
- renderStatementList(this.body, code, this.start + bodyStartPos, this.end - 1, options);
10177
+ // setters are only called for empty paths
10178
+ if (this.kind === 'set' && interaction.type === INTERACTION_ASSIGNED) {
10179
+ return this.value.hasEffectsOnInteractionAtPath(EMPTY_PATH, {
10180
+ args: interaction.args,
10181
+ type: INTERACTION_CALLED,
10182
+ withNew: false
10183
+ }, context);
10274
10184
  }
10275
- else {
10276
- super.render(code, options);
10185
+ return this.getAccessedValue()[0].hasEffectsOnInteractionAtPath(path, interaction, context);
10186
+ }
10187
+ getAccessedValue() {
10188
+ if (this.accessedValue === null) {
10189
+ if (this.kind === 'get') {
10190
+ this.accessedValue = UNKNOWN_RETURN_EXPRESSION;
10191
+ return (this.accessedValue = this.value.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, SHARED_RECURSION_TRACKER, this));
10192
+ }
10193
+ else {
10194
+ return (this.accessedValue = [this.value, false]);
10195
+ }
10277
10196
  }
10197
+ return this.accessedValue;
10278
10198
  }
10279
10199
  }
10280
- StaticBlock.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
10281
- StaticBlock.prototype.applyDeoptimizations = doNotDeoptimize;
10282
- function isStaticBlock(statement) {
10283
- return statement.type === parseAst_js.StaticBlock;
10200
+ PropertyBase.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
10201
+ PropertyBase.prototype.applyDeoptimizations = doNotDeoptimize;
10202
+
10203
+ class MethodDefinition extends PropertyBase {
10204
+ hasEffects(context) {
10205
+ return super.hasEffects(context) || checkEffectForNodes(this.decorators, context);
10206
+ }
10284
10207
  }
10285
10208
 
10286
10209
  class ClassNode extends NodeBase {
@@ -10348,7 +10271,7 @@ class ClassNode extends NodeBase {
10348
10271
  applyDeoptimizations() {
10349
10272
  this.deoptimized = true;
10350
10273
  for (const definition of this.body.body) {
10351
- if (!isStaticBlock(definition) &&
10274
+ if (definition.type !== parseAst_js.StaticBlock &&
10352
10275
  !(definition.static ||
10353
10276
  (definition instanceof MethodDefinition && definition.kind === 'constructor'))) {
10354
10277
  // Calls to methods are not tracked, ensure that the return value is deoptimized
@@ -10364,7 +10287,7 @@ class ClassNode extends NodeBase {
10364
10287
  const staticProperties = [];
10365
10288
  const dynamicMethods = [];
10366
10289
  for (const definition of this.body.body) {
10367
- if (isStaticBlock(definition))
10290
+ if (definition.type === parseAst_js.StaticBlock)
10368
10291
  continue;
10369
10292
  const properties = definition.static ? staticProperties : dynamicMethods;
10370
10293
  const definitionKind = definition.kind;
@@ -10412,12 +10335,6 @@ class ClassDeclaration extends ClassNode {
10412
10335
  this.id.variable.isId = true;
10413
10336
  }
10414
10337
  }
10415
- parseNode(esTreeNode) {
10416
- if (esTreeNode.id !== null) {
10417
- this.id = new Identifier(this, this.scope.parent).parseNode(esTreeNode.id);
10418
- }
10419
- return super.parseNode(esTreeNode);
10420
- }
10421
10338
  render(code, options) {
10422
10339
  const { exportNamesByVariable, format, snippets: { _, getPropertyAccess } } = options;
10423
10340
  if (this.id) {
@@ -10969,6 +10886,34 @@ class FunctionScope extends ReturnValueScope {
10969
10886
  }
10970
10887
  }
10971
10888
 
10889
+ class BlockScope extends ChildScope {
10890
+ constructor(parent) {
10891
+ super(parent, parent.context);
10892
+ }
10893
+ addDeclaration(identifier, context, init, destructuredInitPath, kind) {
10894
+ if (kind === 'var') {
10895
+ const name = identifier.name;
10896
+ const existingVariable = this.hoistedVariables?.get(name) || this.variables.get(name);
10897
+ if (existingVariable) {
10898
+ if (existingVariable.kind === 'var' ||
10899
+ (kind === 'var' && existingVariable.kind === 'parameter')) {
10900
+ existingVariable.addDeclaration(identifier, init);
10901
+ return existingVariable;
10902
+ }
10903
+ return context.error(parseAst_js.logRedeclarationError(name), identifier.start);
10904
+ }
10905
+ const declaredVariable = this.parent.addDeclaration(identifier, context, init, destructuredInitPath, kind);
10906
+ // Necessary to make sure the init is deoptimized for conditional declarations.
10907
+ // We cannot call deoptimizePath here.
10908
+ declaredVariable.markInitializersForDeoptimization();
10909
+ // We add the variable to this and all parent scopes to reliably detect conflicts
10910
+ this.addHoistedVariable(name, declaredVariable);
10911
+ return declaredVariable;
10912
+ }
10913
+ return super.addDeclaration(identifier, context, init, destructuredInitPath, kind);
10914
+ }
10915
+ }
10916
+
10972
10917
  class ExpressionStatement extends NodeBase {
10973
10918
  initialise() {
10974
10919
  super.initialise();
@@ -11065,63 +11010,6 @@ class BlockStatement extends NodeBase {
11065
11010
  BlockStatement.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
11066
11011
  BlockStatement.prototype.applyDeoptimizations = doNotDeoptimize;
11067
11012
 
11068
- class RestElement extends NodeBase {
11069
- constructor() {
11070
- super(...arguments);
11071
- this.declarationInit = null;
11072
- }
11073
- addExportedVariables(variables, exportNamesByVariable) {
11074
- this.argument.addExportedVariables(variables, exportNamesByVariable);
11075
- }
11076
- declare(kind, destructuredInitPath, init) {
11077
- this.declarationInit = init;
11078
- return this.argument.declare(kind, getIncludedPatternPath$1(destructuredInitPath), init);
11079
- }
11080
- deoptimizeAssignment(destructuredInitPath, init) {
11081
- this.argument.deoptimizeAssignment(getIncludedPatternPath$1(destructuredInitPath), init);
11082
- }
11083
- deoptimizePath(path) {
11084
- if (path.length === 0) {
11085
- this.argument.deoptimizePath(EMPTY_PATH);
11086
- }
11087
- }
11088
- hasEffectsOnInteractionAtPath(path, interaction, context) {
11089
- return (path.length > 0 ||
11090
- this.argument.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context));
11091
- }
11092
- hasEffectsWhenDestructuring(context, destructuredInitPath, init) {
11093
- return this.argument.hasEffectsWhenDestructuring(context, getIncludedPatternPath$1(destructuredInitPath), init);
11094
- }
11095
- includeDestructuredIfNecessary(context, destructuredInitPath, init) {
11096
- const included = this.argument.includeDestructuredIfNecessary(context, getIncludedPatternPath$1(destructuredInitPath), init);
11097
- if (!this.included && included) {
11098
- this.includeNode(context);
11099
- }
11100
- return this.included;
11101
- }
11102
- include(context, includeChildrenRecursively) {
11103
- if (!this.included)
11104
- this.includeNode(context);
11105
- // This should just include the identifier, its properties should be
11106
- // included where the variable is used.
11107
- this.argument.include(context, includeChildrenRecursively);
11108
- }
11109
- markDeclarationReached() {
11110
- this.argument.markDeclarationReached();
11111
- }
11112
- applyDeoptimizations() {
11113
- this.deoptimized = true;
11114
- if (this.declarationInit !== null) {
11115
- this.declarationInit.deoptimizePath([UnknownKey, UnknownKey]);
11116
- this.scope.context.requestTreeshakingPass();
11117
- }
11118
- }
11119
- }
11120
- RestElement.prototype.includeNode = onlyIncludeSelf;
11121
- const getIncludedPatternPath$1 = (destructuredInitPath) => destructuredInitPath.at(-1) === UnknownKey
11122
- ? destructuredInitPath
11123
- : [...destructuredInitPath, UnknownKey];
11124
-
11125
11013
  class FunctionBase extends NodeBase {
11126
11014
  constructor() {
11127
11015
  super(...arguments);
@@ -11222,11 +11110,12 @@ class FunctionBase extends NodeBase {
11222
11110
  */
11223
11111
  onlyFunctionCallUsed() {
11224
11112
  let variable = null;
11225
- if (this.parent.type === parseAst_js.VariableDeclarator) {
11226
- variable = this.parent.id.variable ?? null;
11113
+ const { parent } = this;
11114
+ if (parent.type === parseAst_js.VariableDeclarator) {
11115
+ variable = parent.id.variable ?? null;
11227
11116
  }
11228
- if (this.parent.type === parseAst_js.ExportDefaultDeclaration) {
11229
- variable = this.parent.variable;
11117
+ else if (parent.type === parseAst_js.ExportDefaultDeclaration) {
11118
+ variable = parent.variable;
11230
11119
  }
11231
11120
  return variable?.getOnlyFunctionCallUsed() ?? false;
11232
11121
  }
@@ -11263,18 +11152,6 @@ class FunctionBase extends NodeBase {
11263
11152
  this.annotationNoSideEffects = this.annotations.some(comment => comment.type === 'noSideEffects');
11264
11153
  }
11265
11154
  }
11266
- parseNode(esTreeNode) {
11267
- const { body, params } = esTreeNode;
11268
- const { scope } = this;
11269
- const { bodyScope, context } = scope;
11270
- // We need to ensure that parameters are declared before the body is parsed
11271
- // so that the scope already knows all parameters and can detect conflicts
11272
- // when parsing the body.
11273
- const parameters = (this.params = params.map((parameter) => new (context.getNodeConstructor(parameter.type))(this, scope).parseNode(parameter)));
11274
- scope.addParameterVariables(parameters.map(parameter => parameter.declare('parameter', EMPTY_PATH, UNKNOWN_EXPRESSION)), parameters[parameters.length - 1] instanceof RestElement);
11275
- this.body = new (context.getNodeConstructor(body.type))(this, bodyScope).parseNode(body);
11276
- return super.parseNode(esTreeNode);
11277
- }
11278
11155
  }
11279
11156
  FunctionBase.prototype.preventChildBlockScope = true;
11280
11157
  FunctionBase.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
@@ -11388,12 +11265,6 @@ class FunctionDeclaration extends FunctionNode {
11388
11265
  // call super.onlyFunctionCallUsed for export default anonymous function
11389
11266
  return this.id?.variable.getOnlyFunctionCallUsed() ?? super.onlyFunctionCallUsed();
11390
11267
  }
11391
- parseNode(esTreeNode) {
11392
- if (esTreeNode.id !== null) {
11393
- this.id = new Identifier(this, this.scope.parent).parseNode(esTreeNode.id);
11394
- }
11395
- return super.parseNode(esTreeNode);
11396
- }
11397
11268
  }
11398
11269
 
11399
11270
  // The header ends at the first non-white-space after "default"
@@ -11768,11 +11639,6 @@ class Literal extends NodeBase {
11768
11639
  super.initialise();
11769
11640
  this.members = getLiteralMembersForValue(this.value);
11770
11641
  }
11771
- parseNode(esTreeNode) {
11772
- this.value = esTreeNode.value;
11773
- this.regex = esTreeNode.regex;
11774
- return super.parseNode(esTreeNode);
11775
- }
11776
11642
  render() {
11777
11643
  if (typeof this.value === 'string') {
11778
11644
  this.scope.context.addIndentExclusionRange([this.start + 1, this.end - 1]);
@@ -12270,23 +12136,32 @@ class MetaProperty extends NodeBase {
12270
12136
  render(code, renderOptions) {
12271
12137
  const { format, pluginDriver, snippets } = renderOptions;
12272
12138
  const { scope: { context: { module } }, meta: { name }, metaProperty, parent, preliminaryChunkId, referenceId, start, end } = this;
12273
- const { id: moduleId, info: { attributes } } = module;
12139
+ const { id: moduleId, rawId: moduleRawId, info: { attributes: moduleAttributes } } = module;
12274
12140
  if (name !== IMPORT)
12275
12141
  return;
12276
12142
  const chunkId = preliminaryChunkId;
12277
12143
  if (referenceId) {
12278
12144
  const fileName = pluginDriver.getFileName(referenceId);
12279
- const relativePath = parseAst_js.normalize(path.relative(path.dirname(chunkId), fileName));
12145
+ const relativePath = parseAst_js.normalize(sp.relative(sp.dirname(chunkId), fileName));
12280
12146
  const isUrlObject = !!metaProperty?.startsWith(FILE_OBJ_PREFIX);
12281
12147
  const replacement = pluginDriver.hookFirstSync('resolveFileUrl', [
12282
- { attributes, chunkId, fileName, format, moduleId, referenceId, relativePath }
12148
+ {
12149
+ chunkId,
12150
+ fileName,
12151
+ format,
12152
+ moduleAttributes,
12153
+ moduleId,
12154
+ moduleRawId,
12155
+ referenceId,
12156
+ relativePath
12157
+ }
12283
12158
  ]) || relativeUrlMechanisms[format](relativePath, isUrlObject);
12284
12159
  code.overwrite(parent.start, parent.end, replacement, { contentOnly: true });
12285
12160
  return;
12286
12161
  }
12287
12162
  let replacement = pluginDriver.hookFirstSync('resolveImportMeta', [
12288
12163
  metaProperty,
12289
- { attributes, chunkId, format, moduleId }
12164
+ { chunkId, format, moduleAttributes, moduleId, moduleRawId }
12290
12165
  ]);
12291
12166
  if (!replacement) {
12292
12167
  replacement = importMetaMechanisms[format]?.(metaProperty, { chunkId, snippets });
@@ -12673,9 +12548,14 @@ class ExternalChunk {
12673
12548
  return this.fileName;
12674
12549
  }
12675
12550
  const { paths } = this.options;
12551
+ const rawId = this.moduleInfo.rawId;
12676
12552
  return (this.fileName =
12677
- (typeof paths === 'function' ? paths(this.id) : paths[this.id]) ||
12678
- (this.renormalizeRenderPath ? parseAst_js.normalize(path.relative(this.inputBase, this.id)) : this.id));
12553
+ (typeof paths === 'function'
12554
+ ? paths(rawId, {
12555
+ attributes: this.moduleInfo.attributes
12556
+ })
12557
+ : paths[rawId]) ||
12558
+ (this.renormalizeRenderPath ? parseAst_js.normalize(sp.relative(this.inputBase, rawId)) : rawId));
12679
12559
  }
12680
12560
  getImportAttributes(snippets) {
12681
12561
  return (this.importAttributes ||= formatAttributes(['es', 'cjs'].includes(this.options.format) &&
@@ -13282,7 +13162,7 @@ function setupNamespace(name, root, globals, { _, getPropertyAccess, s }, compac
13282
13162
  }
13283
13163
  parts[0] =
13284
13164
  (typeof globals === 'function'
13285
- ? globals(parts[0])
13165
+ ? globals(parts[0], { attributes: {} })
13286
13166
  : isReserved
13287
13167
  ? parts[0]
13288
13168
  : globals[parts[0]]) || parts[0];
@@ -13304,7 +13184,7 @@ function assignToDeepVariable(deepName, root, globals, assignment, { _, getPrope
13304
13184
  }
13305
13185
  parts[0] =
13306
13186
  (typeof globals === 'function'
13307
- ? globals(parts[0])
13187
+ ? globals(parts[0], { attributes: {} })
13308
13188
  : isReserved
13309
13189
  ? parts[0]
13310
13190
  : globals[parts[0]]) || parts[0];
@@ -13701,24 +13581,24 @@ function ensureArray(thing) {
13701
13581
  return [thing];
13702
13582
  }
13703
13583
 
13704
- const normalizePathRegExp = new RegExp(`\\${require$$0.win32.sep}`, 'g');
13584
+ const normalizePathRegExp = new RegExp(`\\${path.win32.sep}`, 'g');
13705
13585
  const normalizePath = function normalizePath(filename) {
13706
- return filename.replace(normalizePathRegExp, require$$0.posix.sep);
13586
+ return filename.replace(normalizePathRegExp, path.posix.sep);
13707
13587
  };
13708
13588
 
13709
13589
  function getMatcherString(id, resolutionBase) {
13710
- if (resolutionBase === false || require$$0.isAbsolute(id) || id.startsWith('**')) {
13590
+ if (resolutionBase === false || path.isAbsolute(id) || id.startsWith('**')) {
13711
13591
  return normalizePath(id);
13712
13592
  }
13713
13593
  // resolve('') is valid and will default to process.cwd()
13714
- const basePath = normalizePath(require$$0.resolve(resolutionBase || ''))
13594
+ const basePath = normalizePath(path.resolve(resolutionBase || ''))
13715
13595
  // escape all possible (posix + win) path characters that might interfere with regex
13716
13596
  .replace(/[-^$*+?.()|[\]{}]/g, '\\$&');
13717
13597
  // Note that we use posix.join because:
13718
13598
  // 1. the basePath has been normalized to use /
13719
13599
  // 2. the incoming glob (id) matcher, also uses /
13720
13600
  // otherwise Node will force backslash (\) on windows
13721
- return require$$0.posix.join(basePath, normalizePath(id));
13601
+ return path.posix.join(basePath, normalizePath(id));
13722
13602
  }
13723
13603
  const createFilter = function createFilter(include, exclude, options) {
13724
13604
  const resolutionBase = options && options.resolve;
@@ -13776,7 +13656,7 @@ class ArrayPattern extends NodeBase {
13776
13656
  }
13777
13657
  declare(kind, destructuredInitPath, init) {
13778
13658
  const variables = [];
13779
- const includedPatternPath = getIncludedPatternPath(destructuredInitPath);
13659
+ const includedPatternPath = getIncludedPatternPath$1(destructuredInitPath);
13780
13660
  for (const element of this.elements) {
13781
13661
  if (element !== null) {
13782
13662
  variables.push(...element.declare(kind, includedPatternPath, init));
@@ -13785,7 +13665,7 @@ class ArrayPattern extends NodeBase {
13785
13665
  return variables;
13786
13666
  }
13787
13667
  deoptimizeAssignment(destructuredInitPath, init) {
13788
- const includedPatternPath = getIncludedPatternPath(destructuredInitPath);
13668
+ const includedPatternPath = getIncludedPatternPath$1(destructuredInitPath);
13789
13669
  for (const element of this.elements) {
13790
13670
  element?.deoptimizeAssignment(includedPatternPath, init);
13791
13671
  }
@@ -13797,7 +13677,7 @@ class ArrayPattern extends NodeBase {
13797
13677
  }
13798
13678
  }
13799
13679
  hasEffectsWhenDestructuring(context, destructuredInitPath, init) {
13800
- const includedPatternPath = getIncludedPatternPath(destructuredInitPath);
13680
+ const includedPatternPath = getIncludedPatternPath$1(destructuredInitPath);
13801
13681
  for (const element of this.elements) {
13802
13682
  if (element?.hasEffectsWhenDestructuring(context, includedPatternPath, init)) {
13803
13683
  return true;
@@ -13815,7 +13695,7 @@ class ArrayPattern extends NodeBase {
13815
13695
  }
13816
13696
  includeDestructuredIfNecessary(context, destructuredInitPath, init) {
13817
13697
  let included = false;
13818
- const includedPatternPath = getIncludedPatternPath(destructuredInitPath);
13698
+ const includedPatternPath = getIncludedPatternPath$1(destructuredInitPath);
13819
13699
  for (const element of [...this.elements].reverse()) {
13820
13700
  if (element) {
13821
13701
  if (included && !element.included) {
@@ -13852,7 +13732,7 @@ class ArrayPattern extends NodeBase {
13852
13732
  }
13853
13733
  }
13854
13734
  ArrayPattern.prototype.includeNode = onlyIncludeSelf;
13855
- const getIncludedPatternPath = (destructuredInitPath) => destructuredInitPath.at(-1) === UnknownKey
13735
+ const getIncludedPatternPath$1 = (destructuredInitPath) => destructuredInitPath.at(-1) === UnknownKey
13856
13736
  ? destructuredInitPath
13857
13737
  : [...destructuredInitPath, UnknownInteger];
13858
13738
 
@@ -13899,8 +13779,7 @@ class ArrowFunctionExpression extends FunctionBase {
13899
13779
  return false;
13900
13780
  }
13901
13781
  onlyFunctionCallUsed() {
13902
- const isIIFE = this.parent.type === parseAst_js.CallExpression &&
13903
- this.parent.callee === this;
13782
+ const isIIFE = this.parent.type === parseAst_js.CallExpression && this.parent.callee === this;
13904
13783
  return isIIFE || super.onlyFunctionCallUsed();
13905
13784
  }
13906
13785
  include(context, includeChildrenRecursively) {
@@ -14200,8 +14079,12 @@ class AwaitExpression extends NodeBase {
14200
14079
  super.initialise();
14201
14080
  let parent = this.parent;
14202
14081
  do {
14203
- if (parent instanceof FunctionNode || parent instanceof ArrowFunctionExpression)
14082
+ const { type } = parent;
14083
+ if (type === parseAst_js.ArrowFunctionExpression ||
14084
+ type === parseAst_js.FunctionExpression ||
14085
+ type === parseAst_js.FunctionDeclaration) {
14204
14086
  return;
14087
+ }
14205
14088
  } while ((parent = parent.parent));
14206
14089
  this.scope.context.usesTopLevelAwait = true;
14207
14090
  }
@@ -14275,10 +14158,9 @@ const binaryOperators = {
14275
14158
  '>>': (left, right) => left >> right,
14276
14159
  '>>>': (left, right) => left >>> right,
14277
14160
  '^': (left, right) => left ^ right,
14161
+ in: () => UnknownValue,
14162
+ instanceof: () => UnknownValue,
14278
14163
  '|': (left, right) => left | right
14279
- // We use the fallback for cases where we return something unknown
14280
- // in: () => UnknownValue,
14281
- // instanceof: () => UnknownValue,
14282
14164
  };
14283
14165
  const UNASSIGNED$1 = Symbol('Unassigned');
14284
14166
  class BinaryExpression extends NodeBase {
@@ -14296,7 +14178,9 @@ class BinaryExpression extends NodeBase {
14296
14178
  if (typeof leftValue === 'symbol')
14297
14179
  return UnknownValue;
14298
14180
  // Optimize `'export' in namespace`
14299
- if (this.operator === 'in' && this.right.variable instanceof NamespaceVariable) {
14181
+ if (this.operator === 'in' &&
14182
+ 'variable' in this.right &&
14183
+ this.right.variable instanceof NamespaceVariable) {
14300
14184
  const [variable] = this.right.variable.context.traceExport(String(leftValue));
14301
14185
  if (variable instanceof ExternalVariable)
14302
14186
  return UnknownValue;
@@ -14307,14 +14191,13 @@ class BinaryExpression extends NodeBase {
14307
14191
  const rightValue = this.right.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
14308
14192
  if (typeof rightValue === 'symbol')
14309
14193
  return UnknownValue;
14310
- const operatorFunction = binaryOperators[this.operator];
14311
- if (!operatorFunction)
14312
- return UnknownValue;
14313
- return operatorFunction(leftValue, rightValue);
14194
+ return binaryOperators[this.operator](leftValue, rightValue);
14314
14195
  }
14315
14196
  getRenderedLiteralValue() {
14316
14197
  // Only optimize `'export' in ns`
14317
- if (this.operator !== 'in' || !(this.right.variable instanceof NamespaceVariable)) {
14198
+ if (!(this.operator === 'in' &&
14199
+ 'variable' in this.right &&
14200
+ this.right.variable instanceof NamespaceVariable)) {
14318
14201
  return UnknownValue;
14319
14202
  }
14320
14203
  if (this.renderedLiteralValue !== UNASSIGNED$1)
@@ -14653,16 +14536,6 @@ class CatchClause extends NodeBase {
14653
14536
  createScope(parentScope) {
14654
14537
  this.scope = new ParameterScope(parentScope, true);
14655
14538
  }
14656
- parseNode(esTreeNode) {
14657
- const { body, param, type } = esTreeNode;
14658
- this.type = type;
14659
- if (param) {
14660
- this.param = new (this.scope.context.getNodeConstructor(param.type))(this, this.scope).parseNode(param);
14661
- this.param.declare('parameter', EMPTY_PATH, UNKNOWN_EXPRESSION);
14662
- }
14663
- this.body = new BlockStatement(this, this.scope.bodyScope).parseNode(body);
14664
- return super.parseNode(esTreeNode);
14665
- }
14666
14539
  }
14667
14540
  CatchClause.prototype.preventChildBlockScope = true;
14668
14541
  CatchClause.prototype.includeNode = onlyIncludeSelf;
@@ -14712,14 +14585,6 @@ class ClassBody extends NodeBase {
14712
14585
  definition.include(context, includeChildrenRecursively);
14713
14586
  }
14714
14587
  }
14715
- parseNode(esTreeNode) {
14716
- const body = (this.body = new Array(esTreeNode.body.length));
14717
- let index = 0;
14718
- for (const definition of esTreeNode.body) {
14719
- body[index++] = new (this.scope.context.getNodeConstructor(definition.type))(this, definition.static ? this.scope : this.scope.instanceScope).parseNode(definition);
14720
- }
14721
- return super.parseNode(esTreeNode);
14722
- }
14723
14588
  }
14724
14589
  ClassBody.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
14725
14590
  ClassBody.prototype.applyDeoptimizations = doNotDeoptimize;
@@ -15248,12 +15113,6 @@ class FunctionExpression extends FunctionNode {
15248
15113
  createScope(parentScope) {
15249
15114
  super.createScope((this.idScope = new ChildScope(parentScope, parentScope.context)));
15250
15115
  }
15251
- parseNode(esTreeNode) {
15252
- if (esTreeNode.id !== null) {
15253
- this.id = new Identifier(this, this.idScope).parseNode(esTreeNode.id);
15254
- }
15255
- return super.parseNode(esTreeNode);
15256
- }
15257
15116
  onlyFunctionCallUsed() {
15258
15117
  const isIIFE = this.parent.type === parseAst_js.CallExpression &&
15259
15118
  this.parent.callee === this &&
@@ -15269,17 +15128,6 @@ class FunctionExpression extends FunctionNode {
15269
15128
  }
15270
15129
  }
15271
15130
 
15272
- class TrackingScope extends BlockScope {
15273
- constructor() {
15274
- super(...arguments);
15275
- this.hoistedDeclarations = [];
15276
- }
15277
- addDeclaration(identifier, context, init, destructuredInitPath, kind) {
15278
- this.hoistedDeclarations.push(identifier);
15279
- return super.addDeclaration(identifier, context, init, destructuredInitPath, kind);
15280
- }
15281
- }
15282
-
15283
15131
  const unset = Symbol('unset');
15284
15132
  class IfStatement extends NodeBase {
15285
15133
  constructor() {
@@ -15324,13 +15172,6 @@ class IfStatement extends NodeBase {
15324
15172
  }
15325
15173
  }
15326
15174
  }
15327
- parseNode(esTreeNode) {
15328
- this.consequent = new (this.scope.context.getNodeConstructor(esTreeNode.consequent.type))(this, (this.consequentScope = new TrackingScope(this.scope))).parseNode(esTreeNode.consequent);
15329
- if (esTreeNode.alternate) {
15330
- this.alternate = new (this.scope.context.getNodeConstructor(esTreeNode.alternate.type))(this, (this.alternateScope = new TrackingScope(this.scope))).parseNode(esTreeNode.alternate);
15331
- }
15332
- return super.parseNode(esTreeNode);
15333
- }
15334
15175
  render(code, options) {
15335
15176
  const { snippets: { getPropertyAccess } } = options;
15336
15177
  // Note that unknown test values are always included
@@ -15432,10 +15273,10 @@ class IfStatement extends NodeBase {
15432
15273
  shouldKeepAlternateBranch() {
15433
15274
  let currentParent = this.parent;
15434
15275
  do {
15435
- if (currentParent instanceof IfStatement && currentParent.alternate) {
15276
+ if (currentParent.type === parseAst_js.IfStatement && currentParent.alternate) {
15436
15277
  return true;
15437
15278
  }
15438
- if (currentParent instanceof BlockStatement) {
15279
+ if (currentParent.type === parseAst_js.BlockStatement) {
15439
15280
  return false;
15440
15281
  }
15441
15282
  currentParent = currentParent.parent;
@@ -15540,11 +15381,11 @@ class ImportExpression extends NodeBase {
15540
15381
  // * import('foo'); // as statement
15541
15382
  // * await import('foo') // use as awaited expression in any way
15542
15383
  // * import('foo').then(n => {...}) // only if .then is called directly on the import()
15543
- if (isExpressionStatementNode(parent) || isAwaitExpressionNode(parent)) {
15384
+ if (parent.type === parseAst_js.ExpressionStatement || parent.type === parseAst_js.AwaitExpression) {
15544
15385
  this.localResolution = { resolution, tracked: true };
15545
15386
  return;
15546
15387
  }
15547
- if (!isMemberExpressionNode(parent)) {
15388
+ if (parent.type !== parseAst_js.MemberExpression) {
15548
15389
  this.localResolution = { resolution, tracked: false };
15549
15390
  return;
15550
15391
  }
@@ -15554,8 +15395,8 @@ class ImportExpression extends NodeBase {
15554
15395
  while (true) {
15555
15396
  if (currentParent.computed ||
15556
15397
  currentParent.object !== callExpression ||
15557
- !isIdentifierNode(currentParent.property) ||
15558
- !isCallExpressionNode(currentParent.parent)) {
15398
+ currentParent.property.type !== parseAst_js.Identifier ||
15399
+ currentParent.parent.type !== parseAst_js.CallExpression) {
15559
15400
  break;
15560
15401
  }
15561
15402
  const propertyName = currentParent.property.name;
@@ -15563,20 +15404,20 @@ class ImportExpression extends NodeBase {
15563
15404
  if (propertyName === 'then') {
15564
15405
  const firstArgument = callExpression.arguments[0];
15565
15406
  if (firstArgument === undefined ||
15566
- isFunctionExpressionNode(firstArgument) ||
15567
- isArrowFunctionExpressionNode(firstArgument)) {
15407
+ firstArgument.type === parseAst_js.FunctionExpression ||
15408
+ firstArgument.type === parseAst_js.ArrowFunctionExpression) {
15568
15409
  currentParent.promiseHandler = new ObjectPromiseHandler(getDynamicNamespaceVariable(resolution.namespace));
15569
15410
  this.localResolution = { resolution, tracked: true };
15570
15411
  return;
15571
15412
  }
15572
15413
  }
15573
15414
  else if (propertyName === 'catch' || propertyName === 'finally') {
15574
- if (isMemberExpressionNode(callExpression.parent)) {
15415
+ if (callExpression.parent.type === parseAst_js.MemberExpression) {
15575
15416
  currentParent.promiseHandler = new EmptyPromiseHandler();
15576
15417
  currentParent = callExpression.parent;
15577
15418
  continue;
15578
15419
  }
15579
- if (isExpressionStatementNode(callExpression.parent)) {
15420
+ if (callExpression.parent.type === parseAst_js.ExpressionStatement) {
15580
15421
  currentParent.promiseHandler = new EmptyPromiseHandler();
15581
15422
  this.localResolution = { resolution, tracked: true };
15582
15423
  return;
@@ -15629,10 +15470,6 @@ class ImportExpression extends NodeBase {
15629
15470
  super.initialise();
15630
15471
  this.scope.context.addDynamicImport(this);
15631
15472
  }
15632
- parseNode(esTreeNode) {
15633
- this.sourceAstNode = esTreeNode.source;
15634
- return super.parseNode(esTreeNode);
15635
- }
15636
15473
  render(code, options) {
15637
15474
  const { snippets: { _, getDirectReturnFunction, getObject, getPropertyAccess }, importAttributesKey } = options;
15638
15475
  if (this.inlineNamespace) {
@@ -15724,10 +15561,13 @@ class ImportExpression extends NodeBase {
15724
15561
  }
15725
15562
  return chunkInfos;
15726
15563
  },
15564
+ moduleAttributes: scope.context.module.info.attributes,
15727
15565
  moduleId: scope.context.module.id,
15566
+ moduleRawId: scope.context.module.rawId,
15728
15567
  targetChunk: targetChunk ? getChunkInfoWithPath(targetChunk) : null,
15729
15568
  targetModuleAttributes: resolution && typeof resolution !== 'string' ? resolution.info.attributes : {},
15730
- targetModuleId: resolution && typeof resolution !== 'string' ? resolution.id : null
15569
+ targetModuleId: resolution && typeof resolution !== 'string' ? resolution.id : null,
15570
+ targetModuleRawId: resolution && typeof resolution !== 'string' ? resolution.info.rawId : null
15731
15571
  }
15732
15572
  ]);
15733
15573
  if (mechanism) {
@@ -15896,16 +15736,14 @@ class JSXIdentifier extends IdentifierBase {
15896
15736
  : 1 /* IdentifierType.NativeElementName */;
15897
15737
  }
15898
15738
  case 'JSXMemberExpression': {
15899
- return this.parent.object === this
15900
- ? 0 /* IdentifierType.Reference */
15901
- : 2 /* IdentifierType.Other */;
15739
+ return this.parent.object === this ? 0 /* IdentifierType.Reference */ : 2 /* IdentifierType.Other */;
15902
15740
  }
15903
15741
  case 'JSXAttribute':
15904
15742
  case 'JSXNamespacedName': {
15905
15743
  return 2 /* IdentifierType.Other */;
15906
15744
  }
15907
15745
  default: {
15908
- /* istanbul ignore next */
15746
+ /* istanbul ignore next */ // @ts-expect-error There should be no valid parent type
15909
15747
  throw new Error(`Unexpected parent node type for JSXIdentifier: ${this.parent.type}`);
15910
15748
  }
15911
15749
  }
@@ -16915,7 +16753,7 @@ class Program extends NodeBase {
16915
16753
  Program.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
16916
16754
  Program.prototype.applyDeoptimizations = doNotDeoptimize;
16917
16755
 
16918
- class Property extends MethodBase {
16756
+ class Property extends PropertyBase {
16919
16757
  //declare method: boolean;
16920
16758
  get method() {
16921
16759
  return isFlagSet(this.flags, 262144 /* Flag.method */);
@@ -16944,8 +16782,7 @@ class Property extends MethodBase {
16944
16782
  }
16945
16783
  includeDestructuredIfNecessary(context, destructuredInitPath, init) {
16946
16784
  const path = this.getPathInProperty(destructuredInitPath);
16947
- let included = this.value.includeDestructuredIfNecessary(context, path, init) ||
16948
- this.included;
16785
+ let included = this.value.includeDestructuredIfNecessary(context, path, init) || this.included;
16949
16786
  if ((included ||= this.key.hasEffects(createHasEffectsContext()))) {
16950
16787
  this.key.include(context, false);
16951
16788
  if (!this.value.included) {
@@ -17034,6 +16871,63 @@ class PropertyDefinition extends NodeBase {
17034
16871
  }
17035
16872
  PropertyDefinition.prototype.applyDeoptimizations = doNotDeoptimize;
17036
16873
 
16874
+ class RestElement extends NodeBase {
16875
+ constructor() {
16876
+ super(...arguments);
16877
+ this.declarationInit = null;
16878
+ }
16879
+ addExportedVariables(variables, exportNamesByVariable) {
16880
+ this.argument.addExportedVariables(variables, exportNamesByVariable);
16881
+ }
16882
+ declare(kind, destructuredInitPath, init) {
16883
+ this.declarationInit = init;
16884
+ return this.argument.declare(kind, getIncludedPatternPath(destructuredInitPath), init);
16885
+ }
16886
+ deoptimizeAssignment(destructuredInitPath, init) {
16887
+ this.argument.deoptimizeAssignment(getIncludedPatternPath(destructuredInitPath), init);
16888
+ }
16889
+ deoptimizePath(path) {
16890
+ if (path.length === 0) {
16891
+ this.argument.deoptimizePath(EMPTY_PATH);
16892
+ }
16893
+ }
16894
+ hasEffectsOnInteractionAtPath(path, interaction, context) {
16895
+ return (path.length > 0 ||
16896
+ this.argument.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context));
16897
+ }
16898
+ hasEffectsWhenDestructuring(context, destructuredInitPath, init) {
16899
+ return this.argument.hasEffectsWhenDestructuring(context, getIncludedPatternPath(destructuredInitPath), init);
16900
+ }
16901
+ includeDestructuredIfNecessary(context, destructuredInitPath, init) {
16902
+ const included = this.argument.includeDestructuredIfNecessary(context, getIncludedPatternPath(destructuredInitPath), init);
16903
+ if (!this.included && included) {
16904
+ this.includeNode(context);
16905
+ }
16906
+ return this.included;
16907
+ }
16908
+ include(context, includeChildrenRecursively) {
16909
+ if (!this.included)
16910
+ this.includeNode(context);
16911
+ // This should just include the identifier, its properties should be
16912
+ // included where the variable is used.
16913
+ this.argument.include(context, includeChildrenRecursively);
16914
+ }
16915
+ markDeclarationReached() {
16916
+ this.argument.markDeclarationReached();
16917
+ }
16918
+ applyDeoptimizations() {
16919
+ this.deoptimized = true;
16920
+ if (this.declarationInit !== null) {
16921
+ this.declarationInit.deoptimizePath([UnknownKey, UnknownKey]);
16922
+ this.scope.context.requestTreeshakingPass();
16923
+ }
16924
+ }
16925
+ }
16926
+ RestElement.prototype.includeNode = onlyIncludeSelf;
16927
+ const getIncludedPatternPath = (destructuredInitPath) => destructuredInitPath.at(-1) === UnknownKey
16928
+ ? destructuredInitPath
16929
+ : [...destructuredInitPath, UnknownKey];
16930
+
17037
16931
  class ReturnStatement extends NodeBase {
17038
16932
  hasEffects(context) {
17039
16933
  if (!context.ignore.returnYield || this.argument?.hasEffects(context))
@@ -17135,8 +17029,39 @@ class SequenceExpression extends NodeBase {
17135
17029
  }
17136
17030
  }
17137
17031
  }
17138
- SequenceExpression.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
17139
- SequenceExpression.prototype.applyDeoptimizations = doNotDeoptimize;
17032
+ SequenceExpression.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
17033
+ SequenceExpression.prototype.applyDeoptimizations = doNotDeoptimize;
17034
+
17035
+ class StaticBlock extends NodeBase {
17036
+ createScope(parentScope) {
17037
+ this.scope = new BlockScope(parentScope);
17038
+ }
17039
+ hasEffects(context) {
17040
+ for (const node of this.body) {
17041
+ if (node.hasEffects(context))
17042
+ return true;
17043
+ }
17044
+ return false;
17045
+ }
17046
+ include(context, includeChildrenRecursively) {
17047
+ this.included = true;
17048
+ for (const node of this.body) {
17049
+ if (includeChildrenRecursively || node.shouldBeIncluded(context))
17050
+ node.include(context, includeChildrenRecursively);
17051
+ }
17052
+ }
17053
+ render(code, options) {
17054
+ if (this.body.length > 0) {
17055
+ const bodyStartPos = findFirstOccurrenceOutsideComment(code.original.slice(this.start, this.end), '{') + 1;
17056
+ renderStatementList(this.body, code, this.start + bodyStartPos, this.end - 1, options);
17057
+ }
17058
+ else {
17059
+ super.render(code, options);
17060
+ }
17061
+ }
17062
+ }
17063
+ StaticBlock.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
17064
+ StaticBlock.prototype.applyDeoptimizations = doNotDeoptimize;
17140
17065
 
17141
17066
  class Super extends NodeBase {
17142
17067
  bind() {
@@ -17270,10 +17195,6 @@ class SwitchStatement extends NodeBase {
17270
17195
  }
17271
17196
  this.defaultCase = null;
17272
17197
  }
17273
- parseNode(esTreeNode) {
17274
- this.discriminant = new (this.scope.context.getNodeConstructor(esTreeNode.discriminant.type))(this, this.parentScope).parseNode(esTreeNode.discriminant);
17275
- return super.parseNode(esTreeNode);
17276
- }
17277
17198
  render(code, options) {
17278
17199
  this.discriminant.render(code, options);
17279
17200
  if (this.cases.length > 0) {
@@ -17330,7 +17251,7 @@ class TaggedTemplateExpression extends CallExpressionBase {
17330
17251
  this.quasi.render(code, options);
17331
17252
  if (!this.hasCheckedForWarnings && this.tag.type === parseAst_js.Identifier) {
17332
17253
  this.hasCheckedForWarnings = true;
17333
- const name = this.tag.name;
17254
+ const { name } = this.tag;
17334
17255
  const variable = this.scope.findVariable(name);
17335
17256
  if (variable.isNamespace) {
17336
17257
  this.scope.context.log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logCannotCallNamespace(name), this.start);
@@ -17364,10 +17285,6 @@ class TemplateElement extends NodeBase {
17364
17285
  hasEffects() {
17365
17286
  return false;
17366
17287
  }
17367
- parseNode(esTreeNode) {
17368
- this.value = esTreeNode.value;
17369
- return super.parseNode(esTreeNode);
17370
- }
17371
17288
  render() { }
17372
17289
  }
17373
17290
  TemplateElement.prototype.includeNode = onlyIncludeSelf;
@@ -18044,109 +17961,23 @@ class YieldExpression extends NodeBase {
18044
17961
  }
18045
17962
  }
18046
17963
 
18047
- // This file is generated by scripts/generate-buffer-parsers.js.
17964
+ class TrackingScope extends BlockScope {
17965
+ constructor() {
17966
+ super(...arguments);
17967
+ this.hoistedDeclarations = [];
17968
+ }
17969
+ addDeclaration(identifier, context, init, destructuredInitPath, kind) {
17970
+ this.hoistedDeclarations.push(identifier);
17971
+ return super.addDeclaration(identifier, context, init, destructuredInitPath, kind);
17972
+ }
17973
+ }
17974
+
17975
+ // This file is generated by scripts/generate-buffer-parsers.ts.
18048
17976
  // Do not edit this file directly.
18049
17977
  function convertProgram(buffer, parent, parentScope) {
18050
17978
  return convertNode(parent, parentScope, 0, parseAst_js.getAstBuffer(buffer));
18051
17979
  }
18052
- const nodeTypeStrings = [
18053
- 'PanicError',
18054
- 'ParseError',
18055
- 'ArrayExpression',
18056
- 'ArrayPattern',
18057
- 'ArrowFunctionExpression',
18058
- 'AssignmentExpression',
18059
- 'AssignmentPattern',
18060
- 'AwaitExpression',
18061
- 'BinaryExpression',
18062
- 'BlockStatement',
18063
- 'BreakStatement',
18064
- 'CallExpression',
18065
- 'CatchClause',
18066
- 'ChainExpression',
18067
- 'ClassBody',
18068
- 'ClassDeclaration',
18069
- 'ClassExpression',
18070
- 'ConditionalExpression',
18071
- 'ContinueStatement',
18072
- 'DebuggerStatement',
18073
- 'Decorator',
18074
- 'ExpressionStatement',
18075
- 'DoWhileStatement',
18076
- 'EmptyStatement',
18077
- 'ExportAllDeclaration',
18078
- 'ExportDefaultDeclaration',
18079
- 'ExportNamedDeclaration',
18080
- 'ExportSpecifier',
18081
- 'ExpressionStatement',
18082
- 'ForInStatement',
18083
- 'ForOfStatement',
18084
- 'ForStatement',
18085
- 'FunctionDeclaration',
18086
- 'FunctionExpression',
18087
- 'Identifier',
18088
- 'IfStatement',
18089
- 'ImportAttribute',
18090
- 'ImportDeclaration',
18091
- 'ImportDefaultSpecifier',
18092
- 'ImportExpression',
18093
- 'ImportNamespaceSpecifier',
18094
- 'ImportSpecifier',
18095
- 'JSXAttribute',
18096
- 'JSXClosingElement',
18097
- 'JSXClosingFragment',
18098
- 'JSXElement',
18099
- 'JSXEmptyExpression',
18100
- 'JSXExpressionContainer',
18101
- 'JSXFragment',
18102
- 'JSXIdentifier',
18103
- 'JSXMemberExpression',
18104
- 'JSXNamespacedName',
18105
- 'JSXOpeningElement',
18106
- 'JSXOpeningFragment',
18107
- 'JSXSpreadAttribute',
18108
- 'JSXSpreadChild',
18109
- 'JSXText',
18110
- 'LabeledStatement',
18111
- 'Literal',
18112
- 'Literal',
18113
- 'Literal',
18114
- 'Literal',
18115
- 'Literal',
18116
- 'Literal',
18117
- 'LogicalExpression',
18118
- 'MemberExpression',
18119
- 'MetaProperty',
18120
- 'MethodDefinition',
18121
- 'NewExpression',
18122
- 'ObjectExpression',
18123
- 'ObjectPattern',
18124
- 'PrivateIdentifier',
18125
- 'Program',
18126
- 'Property',
18127
- 'PropertyDefinition',
18128
- 'RestElement',
18129
- 'ReturnStatement',
18130
- 'SequenceExpression',
18131
- 'SpreadElement',
18132
- 'StaticBlock',
18133
- 'Super',
18134
- 'SwitchCase',
18135
- 'SwitchStatement',
18136
- 'TaggedTemplateExpression',
18137
- 'TemplateElement',
18138
- 'TemplateLiteral',
18139
- 'ThisExpression',
18140
- 'ThrowStatement',
18141
- 'TryStatement',
18142
- 'UnaryExpression',
18143
- 'UpdateExpression',
18144
- 'VariableDeclaration',
18145
- 'VariableDeclarator',
18146
- 'WhileStatement',
18147
- 'YieldExpression'
18148
- ];
18149
- const nodeConstructors$1 = [
17980
+ const nodeConstructors = [
18150
17981
  PanicError,
18151
17982
  ParseError,
18152
17983
  ArrayExpression,
@@ -18493,8 +18324,11 @@ const bufferParsers = [
18493
18324
  node.specifiers = convertNodeList(node, scope, buffer[position], buffer);
18494
18325
  node.source = convertNode(node, scope, buffer[position + 1], buffer);
18495
18326
  node.attributes = convertNodeList(node, scope, buffer[position + 2], buffer);
18496
- const phaseIndex = buffer[position + 3];
18497
- node.phase = phaseIndex === 0 ? undefined : parseAst_js.FIXED_STRINGS[phaseIndex];
18327
+ const phasePosition = buffer[position + 3];
18328
+ node.phase =
18329
+ phasePosition === 0
18330
+ ? undefined
18331
+ : parseAst_js.FIXED_STRINGS[buffer[position + 3]];
18498
18332
  },
18499
18333
  function importDefaultSpecifier(node, position, buffer) {
18500
18334
  const { scope } = node;
@@ -18506,8 +18340,11 @@ const bufferParsers = [
18506
18340
  node.sourceAstNode = parseAst_js.convertNode(buffer[position], buffer);
18507
18341
  const optionsPosition = buffer[position + 1];
18508
18342
  node.options = optionsPosition === 0 ? null : convertNode(node, scope, optionsPosition, buffer);
18509
- const phaseIndex = buffer[position + 2];
18510
- node.phase = phaseIndex === 0 ? undefined : parseAst_js.FIXED_STRINGS[phaseIndex];
18343
+ const phasePosition = buffer[position + 2];
18344
+ node.phase =
18345
+ phasePosition === 0
18346
+ ? undefined
18347
+ : parseAst_js.FIXED_STRINGS[buffer[position + 2]];
18511
18348
  },
18512
18349
  function importNamespaceSpecifier(node, position, buffer) {
18513
18350
  const { scope } = node;
@@ -18738,7 +18575,7 @@ const bufferParsers = [
18738
18575
  const flags = buffer[position];
18739
18576
  node.tail = (flags & 1) === 1;
18740
18577
  const cookedPosition = buffer[position + 1];
18741
- const cooked = cookedPosition === 0 ? null : buffer.convertString(cookedPosition);
18578
+ const cooked = cookedPosition === 0 ? undefined : buffer.convertString(cookedPosition);
18742
18579
  const raw = buffer.convertString(buffer[position + 2]);
18743
18580
  node.value = { cooked, raw };
18744
18581
  },
@@ -18800,14 +18637,14 @@ const bufferParsers = [
18800
18637
  ];
18801
18638
  function convertNode(parent, parentScope, position, buffer) {
18802
18639
  const nodeType = buffer[position];
18803
- const NodeConstructor = nodeConstructors$1[nodeType];
18640
+ const NodeConstructor = nodeConstructors[nodeType];
18804
18641
  /* istanbul ignore if: This should never be executed but is a safeguard against faulty buffers */
18805
18642
  if (!NodeConstructor) {
18806
18643
  console.trace();
18807
18644
  throw new Error(`Unknown node type: ${nodeType}`);
18808
18645
  }
18809
18646
  const node = new NodeConstructor(parent, parentScope);
18810
- node.type = nodeTypeStrings[nodeType];
18647
+ node.type = parseAst_js.nodeTypeStrings[nodeType];
18811
18648
  node.start = buffer[position + 1];
18812
18649
  node.end = buffer[position + 2];
18813
18650
  bufferParsers[nodeType](node, position + 3, buffer);
@@ -18826,110 +18663,6 @@ function convertNodeList(parent, parentScope, position, buffer) {
18826
18663
  return list;
18827
18664
  }
18828
18665
 
18829
- class UnknownNode extends NodeBase {
18830
- hasEffects() {
18831
- return true;
18832
- }
18833
- include(context) {
18834
- super.include(context, true);
18835
- }
18836
- }
18837
-
18838
- // This file is generated by scripts/generate-node-index.js.
18839
- // Do not edit this file directly.
18840
- const nodeConstructors = {
18841
- ArrayExpression,
18842
- ArrayPattern,
18843
- ArrowFunctionExpression,
18844
- AssignmentExpression,
18845
- AssignmentPattern,
18846
- AwaitExpression,
18847
- BinaryExpression,
18848
- BlockStatement,
18849
- BreakStatement,
18850
- CallExpression,
18851
- CatchClause,
18852
- ChainExpression,
18853
- ClassBody,
18854
- ClassDeclaration,
18855
- ClassExpression,
18856
- ConditionalExpression,
18857
- ContinueStatement,
18858
- DebuggerStatement,
18859
- Decorator,
18860
- DoWhileStatement,
18861
- EmptyStatement,
18862
- ExportAllDeclaration,
18863
- ExportDefaultDeclaration,
18864
- ExportNamedDeclaration,
18865
- ExportSpecifier,
18866
- ExpressionStatement,
18867
- ForInStatement,
18868
- ForOfStatement,
18869
- ForStatement,
18870
- FunctionDeclaration,
18871
- FunctionExpression,
18872
- Identifier,
18873
- IfStatement,
18874
- ImportAttribute,
18875
- ImportDeclaration,
18876
- ImportDefaultSpecifier,
18877
- ImportExpression,
18878
- ImportNamespaceSpecifier,
18879
- ImportSpecifier,
18880
- JSXAttribute,
18881
- JSXClosingElement,
18882
- JSXClosingFragment,
18883
- JSXElement,
18884
- JSXEmptyExpression,
18885
- JSXExpressionContainer,
18886
- JSXFragment,
18887
- JSXIdentifier,
18888
- JSXMemberExpression,
18889
- JSXNamespacedName,
18890
- JSXOpeningElement,
18891
- JSXOpeningFragment,
18892
- JSXSpreadAttribute,
18893
- JSXSpreadChild,
18894
- JSXText,
18895
- LabeledStatement,
18896
- Literal,
18897
- LogicalExpression,
18898
- MemberExpression,
18899
- MetaProperty,
18900
- MethodDefinition,
18901
- NewExpression,
18902
- ObjectExpression,
18903
- ObjectPattern,
18904
- PanicError,
18905
- ParseError,
18906
- PrivateIdentifier,
18907
- Program,
18908
- Property,
18909
- PropertyDefinition,
18910
- RestElement,
18911
- ReturnStatement,
18912
- SequenceExpression,
18913
- SpreadElement,
18914
- StaticBlock,
18915
- Super,
18916
- SwitchCase,
18917
- SwitchStatement,
18918
- TaggedTemplateExpression,
18919
- TemplateElement,
18920
- TemplateLiteral,
18921
- ThisExpression,
18922
- ThrowStatement,
18923
- TryStatement,
18924
- UnaryExpression,
18925
- UnknownNode,
18926
- UpdateExpression,
18927
- VariableDeclaration,
18928
- VariableDeclarator,
18929
- WhileStatement,
18930
- YieldExpression
18931
- };
18932
-
18933
18666
  class ExportShimVariable extends Variable {
18934
18667
  constructor(module) {
18935
18668
  super(MISSING_EXPORT_SHIM_VARIABLE);
@@ -19261,10 +18994,12 @@ function getAndExtendSideEffectModules(variable, module) {
19261
18994
  return sideEffectModules;
19262
18995
  }
19263
18996
  class Module {
19264
- constructor(graph, id, options, isEntry, moduleSideEffects, syntheticNamedExports, meta, attributes) {
18997
+ constructor(graph, id, rawId, options, isEntry, moduleSideEffects, syntheticNamedExports, meta, attributes) {
19265
18998
  this.graph = graph;
19266
18999
  this.id = id;
19000
+ this.rawId = rawId;
19267
19001
  this.options = options;
19002
+ this.attributes = attributes;
19268
19003
  this.alternativeReexportModules = new Map();
19269
19004
  this.chunkFileNames = new Set();
19270
19005
  this.chunkNames = [];
@@ -19289,11 +19024,11 @@ class Module {
19289
19024
  this.needsExportShim = false;
19290
19025
  this.sideEffectDependenciesByVariable = new Map();
19291
19026
  this.sourcePhaseSources = new Set();
19292
- this.sourcesWithAttributes = new Map();
19027
+ this.sourcesWithAttributesList = new Map();
19293
19028
  this.allExportsIncluded = false;
19294
19029
  this.ast = null;
19295
19030
  this.exportAllModules = [];
19296
- this.exportAllSources = new Set();
19031
+ this.exportAllSourcesWithAttributesList = new Map();
19297
19032
  this.exportDescriptions = new Map();
19298
19033
  this.exportedVariablesByName = null;
19299
19034
  this.exportNamesByVariable = null;
@@ -19310,7 +19045,7 @@ class Module {
19310
19045
  this.preserveSignature = this.options.preserveEntrySignatures;
19311
19046
  // eslint-disable-next-line @typescript-eslint/no-this-alias
19312
19047
  const module = this;
19313
- const { dynamicImports, dynamicImporters, exportAllSources, exportDescriptions, implicitlyLoadedAfter, implicitlyLoadedBefore, importers, reexportDescriptions, sourcesWithAttributes } = this;
19048
+ const { dynamicImports, dynamicImporters, exportAllSourcesWithAttributesList, exportDescriptions, implicitlyLoadedAfter, implicitlyLoadedBefore, importers, reexportDescriptions, sourcesWithAttributesList } = this;
19314
19049
  this.info = {
19315
19050
  ast: null,
19316
19051
  attributes,
@@ -19330,11 +19065,13 @@ class Module {
19330
19065
  },
19331
19066
  get exportedBindings() {
19332
19067
  const exportBindings = { '.': [...exportDescriptions.keys()] };
19333
- for (const [name, { source }] of reexportDescriptions) {
19334
- (exportBindings[source] ??= []).push(name);
19068
+ for (const [name, { source, attributes }] of reexportDescriptions) {
19069
+ (exportBindings[generateIdByRawIdAndAttributes(source, attributes)] ??= []).push(name);
19335
19070
  }
19336
- for (const source of exportAllSources) {
19337
- (exportBindings[source] ??= []).push('*');
19071
+ for (const [source, attributesList] of exportAllSourcesWithAttributesList) {
19072
+ for (const attributes of attributesList) {
19073
+ (exportBindings[generateIdByRawIdAndAttributes(source, attributes)] ??= []).push('*');
19074
+ }
19338
19075
  }
19339
19076
  return exportBindings;
19340
19077
  },
@@ -19342,7 +19079,7 @@ class Module {
19342
19079
  return [
19343
19080
  ...exportDescriptions.keys(),
19344
19081
  ...reexportDescriptions.keys(),
19345
- ...[...exportAllSources].map(() => '*')
19082
+ ...[...exportAllSourcesWithAttributesList].map(() => '*')
19346
19083
  ];
19347
19084
  },
19348
19085
  get hasDefaultExport() {
@@ -19360,12 +19097,16 @@ class Module {
19360
19097
  return Array.from(implicitlyLoadedBefore, getId).sort();
19361
19098
  },
19362
19099
  get importedIdResolutions() {
19363
- return Array.from(sourcesWithAttributes.keys(), source => module.resolvedIds[source]).filter(Boolean);
19100
+ return Array.from(sourcesWithAttributesList.entries(), ([source, attributesList]) => attributesList.map(attributes => module.resolvedIds[generateIdByRawIdAndAttributes(source, attributes)]))
19101
+ .flat()
19102
+ .filter(Boolean);
19364
19103
  },
19365
19104
  get importedIds() {
19366
19105
  // We cannot use this.dependencies because this is needed before
19367
19106
  // dependencies are populated
19368
- return Array.from(sourcesWithAttributes.keys(), source => module.resolvedIds[source]?.id).filter(Boolean);
19107
+ return Array.from(sourcesWithAttributesList.entries(), ([source, attributesList]) => attributesList.map(attributes => module.resolvedIds[generateIdByRawIdAndAttributes(source, attributes)]?.id))
19108
+ .flat()
19109
+ .filter(Boolean);
19369
19110
  },
19370
19111
  get importers() {
19371
19112
  return importers.sort();
@@ -19380,13 +19121,14 @@ class Module {
19380
19121
  },
19381
19122
  meta: { ...meta },
19382
19123
  moduleSideEffects,
19124
+ rawId,
19383
19125
  safeVariableNames: null,
19384
19126
  syntheticNamedExports
19385
19127
  };
19386
19128
  }
19387
19129
  basename() {
19388
- const base = path.basename(this.id);
19389
- const extension = path.extname(this.id);
19130
+ const base = sp.basename(this.id);
19131
+ const extension = sp.extname(this.id);
19390
19132
  return makeLegal(extension ? base.slice(0, -extension.length) : base);
19391
19133
  }
19392
19134
  bindReferences() {
@@ -19685,17 +19427,25 @@ class Module {
19685
19427
  this.importedFromNotTreeshaken ||
19686
19428
  this.exportShimVariable.included));
19687
19429
  }
19430
+ isEmitted() {
19431
+ return (this.isIncluded() ||
19432
+ this.info.isEntry ||
19433
+ this.includedDynamicImporters.length > 0 ||
19434
+ this.implicitlyLoadedAfter.size > 0);
19435
+ }
19688
19436
  linkImports() {
19689
19437
  this.addModulesToImportDescriptions(this.importDescriptions);
19690
19438
  this.addModulesToImportDescriptions(this.reexportDescriptions);
19691
19439
  const externalExportAllModules = [];
19692
- for (const source of this.exportAllSources) {
19693
- const module = this.graph.modulesById.get(this.resolvedIds[source].id);
19694
- if (module instanceof ExternalModule) {
19695
- externalExportAllModules.push(module);
19696
- continue;
19440
+ for (const [source, attributesList] of this.exportAllSourcesWithAttributesList) {
19441
+ for (const attributes of attributesList) {
19442
+ const module = this.graph.modulesById.get(this.resolvedIds[generateIdByRawIdAndAttributes(source, attributes)].id);
19443
+ if (module instanceof ExternalModule) {
19444
+ externalExportAllModules.push(module);
19445
+ continue;
19446
+ }
19447
+ this.exportAllModules.push(module);
19697
19448
  }
19698
- this.exportAllModules.push(module);
19699
19449
  }
19700
19450
  this.exportAllModules.push(...externalExportAllModules);
19701
19451
  }
@@ -19714,7 +19464,7 @@ class Module {
19714
19464
  }
19715
19465
  return { indentExclusionRanges: this.indentExclusionRanges, source, usesTopLevelAwait };
19716
19466
  }
19717
- async setSource({ ast, code, customTransformCache, originalCode, originalSourcemap, resolvedIds, sourcemapChain, transformDependencies, transformFiles, safeVariableNames, ...moduleOptions }) {
19467
+ setSource({ astBuffer, code, customTransformCache, originalCode, originalSourcemap, resolvedIds, sourcemapChain, transformDependencies, transformFiles, safeVariableNames, ...moduleOptions }) {
19718
19468
  timeStart('generate ast', 3);
19719
19469
  if (code.startsWith('#!')) {
19720
19470
  const shebangEndPosition = code.indexOf('\n');
@@ -19757,7 +19507,6 @@ class Module {
19757
19507
  getImportedJsxFactoryVariable: this.getImportedJsxFactoryVariable.bind(this),
19758
19508
  getModuleExecIndex: () => this.execIndex,
19759
19509
  getModuleName: this.basename.bind(this),
19760
- getNodeConstructor: (name) => nodeConstructors[name] || nodeConstructors.UnknownNode,
19761
19510
  importDescriptions: this.importDescriptions,
19762
19511
  includeDynamicImport: this.includeDynamicImport.bind(this),
19763
19512
  includeVariableInModule: this.includeVariableInModule.bind(this),
@@ -19775,46 +19524,21 @@ class Module {
19775
19524
  };
19776
19525
  this.scope = new ModuleScope(this.graph.scope, this.astContext, this.importDescriptions);
19777
19526
  this.namespace = new NamespaceVariable(this.astContext);
19778
- const programParent = { context: this.astContext, type: 'Module' };
19779
- if (ast) {
19780
- this.ast = new nodeConstructors[ast.type](programParent, this.scope).parseNode(ast);
19781
- this.info.ast = ast;
19782
- }
19783
- else {
19784
- // Measuring asynchronous code does not provide reasonable results
19785
- timeEnd('generate ast', 3);
19786
- const astBuffer = await native_js.parseAsync(code, false, this.options.jsx !== false);
19787
- timeStart('generate ast', 3);
19788
- this.ast = convertProgram(astBuffer, programParent, this.scope);
19789
- // Make lazy and apply LRU cache to not hog the memory
19790
- Object.defineProperty(this.info, 'ast', {
19791
- get: () => {
19792
- if (this.graph.astLru.has(fileName)) {
19793
- return this.graph.astLru.get(fileName);
19794
- }
19795
- else {
19796
- const parsedAst = this.tryParse();
19797
- // If the cache is not disabled, we need to keep the AST in memory
19798
- // until the end when the cache is generated
19799
- if (this.options.cache !== false) {
19800
- Object.defineProperty(this.info, 'ast', {
19801
- value: parsedAst
19802
- });
19803
- return parsedAst;
19804
- }
19805
- // Otherwise, we keep it in a small LRU cache to not hog too much
19806
- // memory but allow the same AST to be requested several times.
19807
- this.graph.astLru.set(fileName, parsedAst);
19808
- return parsedAst;
19809
- }
19810
- }
19811
- });
19812
- }
19527
+ this.astBuffer = astBuffer;
19528
+ // When the AST is walked, this data structure will grow as getters are
19529
+ // replaced with fixed properties. By making this a getter, we avoid keeping
19530
+ // a reference to the full AST to conserve memory at the potential cost of
19531
+ // creating AST nodes repeatedly.
19532
+ Object.defineProperty(this.info, 'ast', {
19533
+ enumerable: true,
19534
+ get: () => this.tryParseLazy(this.astBuffer)
19535
+ });
19536
+ this.ast = convertProgram(this.astBuffer, null, this.scope);
19813
19537
  timeEnd('generate ast', 3);
19814
19538
  }
19815
19539
  toJSON() {
19816
19540
  return {
19817
- ast: this.info.ast,
19541
+ astBuffer: this.astBuffer,
19818
19542
  attributes: this.info.attributes,
19819
19543
  code: this.info.code,
19820
19544
  customTransformCache: this.customTransformCache,
@@ -19824,6 +19548,7 @@ class Module {
19824
19548
  moduleSideEffects: this.info.moduleSideEffects,
19825
19549
  originalCode: this.originalCode,
19826
19550
  originalSourcemap: this.originalSourcemap,
19551
+ rawId: this.rawId,
19827
19552
  resolvedIds: this.resolvedIds,
19828
19553
  safeVariableNames: this.info.safeVariableNames,
19829
19554
  sourcemapChain: this.sourcemapChain,
@@ -19870,13 +19595,11 @@ class Module {
19870
19595
  addDynamicImport(node) {
19871
19596
  let argument = node.sourceAstNode;
19872
19597
  if (argument.type === parseAst_js.TemplateLiteral) {
19873
- if (argument.quasis.length === 1 &&
19874
- typeof argument.quasis[0].value.cooked === 'string') {
19598
+ if (argument.quasis.length === 1 && typeof argument.quasis[0].value.cooked === 'string') {
19875
19599
  argument = argument.quasis[0].value.cooked;
19876
19600
  }
19877
19601
  }
19878
- else if (argument.type === parseAst_js.Literal &&
19879
- typeof argument.value === 'string') {
19602
+ else if (argument.type === parseAst_js.Literal && typeof argument.value === 'string') {
19880
19603
  argument = argument.value;
19881
19604
  }
19882
19605
  this.dynamicImports.push({ argument, id: null, node });
@@ -19903,6 +19626,7 @@ class Module {
19903
19626
  const name = node.exported instanceof Literal ? node.exported.value : node.exported.name;
19904
19627
  this.assertUniqueExportName(name, node.exported.start);
19905
19628
  this.reexportDescriptions.set(name, {
19629
+ attributes: getAttributesFromImportExportDeclaration(node.attributes),
19906
19630
  localName: '*',
19907
19631
  module: null, // filled in later,
19908
19632
  source,
@@ -19911,7 +19635,16 @@ class Module {
19911
19635
  }
19912
19636
  else {
19913
19637
  // export * from './other'
19914
- this.exportAllSources.add(source);
19638
+ const existingAttributesList = this.exportAllSourcesWithAttributesList.get(source);
19639
+ const parsedAttributes = getAttributesFromImportExportDeclaration(node.attributes);
19640
+ if (existingAttributesList) {
19641
+ if (!existingAttributesList.find(attributes => !doAttributesDiffer(attributes, parsedAttributes))) {
19642
+ existingAttributesList.push(parsedAttributes);
19643
+ }
19644
+ }
19645
+ else {
19646
+ this.exportAllSourcesWithAttributesList.set(source, [parsedAttributes]);
19647
+ }
19915
19648
  }
19916
19649
  }
19917
19650
  else if (node.source instanceof Literal) {
@@ -19922,6 +19655,7 @@ class Module {
19922
19655
  const name = exported instanceof Literal ? exported.value : exported.name;
19923
19656
  this.assertUniqueExportName(name, start);
19924
19657
  this.reexportDescriptions.set(name, {
19658
+ attributes: getAttributesFromImportExportDeclaration(node.attributes),
19925
19659
  localName: local instanceof Literal ? local.value : local.name,
19926
19660
  module: null, // filled in later,
19927
19661
  source,
@@ -19977,6 +19711,7 @@ class Module {
19977
19711
  ? specifier.imported.name
19978
19712
  : specifier.imported.value;
19979
19713
  this.importDescriptions.set(localName, {
19714
+ attributes: getAttributesFromImportExportDeclaration(node.attributes),
19980
19715
  module: null, // filled in later
19981
19716
  name,
19982
19717
  phase: node.phase === 'source' ? 'source' : 'instance',
@@ -19986,8 +19721,8 @@ class Module {
19986
19721
  }
19987
19722
  }
19988
19723
  addImportSource(importSource) {
19989
- if (importSource && !this.sourcesWithAttributes.has(importSource)) {
19990
- this.sourcesWithAttributes.set(importSource, parseAst_js.EMPTY_OBJECT);
19724
+ if (importSource && !this.sourcesWithAttributesList.has(importSource)) {
19725
+ this.sourcesWithAttributesList.set(importSource, [parseAst_js.EMPTY_OBJECT]);
19991
19726
  }
19992
19727
  }
19993
19728
  addImportMeta(node) {
@@ -20012,7 +19747,7 @@ class Module {
20012
19747
  }
20013
19748
  addModulesToImportDescriptions(importDescription) {
20014
19749
  for (const specifier of importDescription.values()) {
20015
- const { id } = this.resolvedIds[specifier.source];
19750
+ const { id } = this.resolvedIds[generateIdByRawIdAndAttributes(specifier.source, specifier.attributes)];
20016
19751
  specifier.module = this.graph.modulesById.get(id);
20017
19752
  }
20018
19753
  }
@@ -20043,14 +19778,14 @@ class Module {
20043
19778
  }
20044
19779
  addSource(source, declaration) {
20045
19780
  const parsedAttributes = getAttributesFromImportExportDeclaration(declaration.attributes);
20046
- const existingAttributes = this.sourcesWithAttributes.get(source);
20047
- if (existingAttributes) {
20048
- if (doAttributesDiffer(existingAttributes, parsedAttributes)) {
20049
- this.log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logInconsistentImportAttributes(existingAttributes, parsedAttributes, source, this.id), declaration.start);
19781
+ const existingAttributesList = this.sourcesWithAttributesList.get(source);
19782
+ if (existingAttributesList) {
19783
+ if (!existingAttributesList.some(attributes => !doAttributesDiffer(attributes, parsedAttributes))) {
19784
+ existingAttributesList.push(parsedAttributes);
20050
19785
  }
20051
19786
  }
20052
19787
  else {
20053
- this.sourcesWithAttributes.set(source, parsedAttributes);
19788
+ this.sourcesWithAttributesList.set(source, [parsedAttributes]);
20054
19789
  }
20055
19790
  if (declaration.phase === 'source') {
20056
19791
  this.sourcePhaseSources.add(source);
@@ -20184,9 +19919,9 @@ class Module {
20184
19919
  this.options.onLog(parseAst_js.LOGLEVEL_WARN, parseAst_js.logShimmedExport(this.id, name));
20185
19920
  this.exportDescriptions.set(name, MISSING_EXPORT_SHIM_DESCRIPTION);
20186
19921
  }
20187
- tryParse() {
19922
+ tryParseLazy(astBuffer) {
20188
19923
  try {
20189
- return parseAst_js.parseAst(this.info.code, { jsx: this.options.jsx !== false });
19924
+ return parseAst_js.deserializeLazyAst(astBuffer);
20190
19925
  }
20191
19926
  catch (error_) {
20192
19927
  return this.error(parseAst_js.logModuleParseError(error_, this.id), error_.pos);
@@ -20517,9 +20252,13 @@ const NON_ASSET_EXTENSIONS = new Set([
20517
20252
  '.cjs',
20518
20253
  '.cts'
20519
20254
  ]);
20520
- function getGlobalName(chunk, globals, hasExports, log) {
20521
- const globalName = typeof globals === 'function' ? globals(chunk.id) : globals[chunk.id];
20255
+ function getGlobalName(chunk, globals, hasExports, boundVariantsByRawId, log) {
20256
+ const { attributes, rawId } = chunk.moduleInfo;
20257
+ const globalName = typeof globals === 'function' ? globals(rawId, { attributes }) : globals[rawId];
20522
20258
  if (globalName) {
20259
+ if (hasExports && typeof globals === 'object') {
20260
+ warnIfAmbiguousGlobalName(rawId, globalName, boundVariantsByRawId, log);
20261
+ }
20523
20262
  return globalName;
20524
20263
  }
20525
20264
  if (hasExports) {
@@ -20527,6 +20266,13 @@ function getGlobalName(chunk, globals, hasExports, log) {
20527
20266
  return chunk.variableName;
20528
20267
  }
20529
20268
  }
20269
+ function warnIfAmbiguousGlobalName(rawId, globalName, boundVariantsByRawId, log) {
20270
+ const boundVariants = boundVariantsByRawId.get(rawId) ?? 0;
20271
+ if (boundVariants === 1) {
20272
+ log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logAmbiguousGlobalName(rawId, globalName));
20273
+ }
20274
+ boundVariantsByRawId.set(rawId, boundVariants + 1);
20275
+ }
20530
20276
  class Chunk {
20531
20277
  constructor(orderedModules, inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, externalChunkByModule, facadeChunkByModule, includedNamespaces, manualChunkAlias, getPlaceholder, bundle, inputBase, snippets) {
20532
20278
  this.orderedModules = orderedModules;
@@ -20818,7 +20564,7 @@ class Chunk {
20818
20564
  let hashPlaceholder = null;
20819
20565
  const { chunkFileNames, entryFileNames, file, format, preserveModules } = this.outputOptions;
20820
20566
  if (file) {
20821
- fileName = path.basename(file);
20567
+ fileName = sp.basename(file);
20822
20568
  }
20823
20569
  else if (this.fileName === null) {
20824
20570
  const [pattern, patternName] = preserveModules || this.facadeModule?.isUserDefinedEntryPoint
@@ -21279,7 +21025,9 @@ class Chunk {
21279
21025
  const { dynamicEntryModules, facadeModule, implicitEntryModules, orderedModules } = this;
21280
21026
  return (this.preRenderedChunkInfo = {
21281
21027
  exports: this.getExportNames(),
21028
+ facadeModuleAttributes: facadeModule ? facadeModule.info.attributes : {},
21282
21029
  facadeModuleId: facadeModule && facadeModule.id,
21030
+ facadeModuleRawId: facadeModule ? facadeModule.info.rawId : null,
21283
21031
  isDynamicEntry: dynamicEntryModules.length > 0,
21284
21032
  isEntry: !!facadeModule?.info.isEntry,
21285
21033
  isImplicitEntry: implicitEntryModules.length > 0,
@@ -21298,12 +21046,12 @@ class Chunk {
21298
21046
  // comparing paths; otherwise ids containing sanitized characters escape the
21299
21047
  // base via "../" and trip the placeholder validation (#5446).
21300
21048
  const sanitizedBase = sanitizeFileName(this.inputBase);
21301
- const extensionName = path.extname(sanitizedId);
21049
+ const extensionName = sp.extname(sanitizedId);
21302
21050
  const idWithoutExtension = NON_ASSET_EXTENSIONS.has(extensionName)
21303
21051
  ? sanitizedId.slice(0, -extensionName.length)
21304
21052
  : sanitizedId;
21305
21053
  if (parseAst_js.isAbsolute(idWithoutExtension)) {
21306
- if (preserveModulesRoot && path.resolve(idWithoutExtension).startsWith(preserveModulesRoot)) {
21054
+ if (preserveModulesRoot && sp.resolve(idWithoutExtension).startsWith(preserveModulesRoot)) {
21307
21055
  return idWithoutExtension.slice(preserveModulesRoot.length).replace(/^[/\\]/, '');
21308
21056
  }
21309
21057
  else {
@@ -21315,7 +21063,7 @@ class Chunk {
21315
21063
  }
21316
21064
  }
21317
21065
  else {
21318
- return (this.outputOptions.virtualDirname.replace(/\/$/, '') + '/' + path.basename(idWithoutExtension));
21066
+ return (this.outputOptions.virtualDirname.replace(/\/$/, '') + '/' + sp.basename(idWithoutExtension));
21319
21067
  }
21320
21068
  }
21321
21069
  getReexportSpecifiers() {
@@ -21385,6 +21133,9 @@ class Chunk {
21385
21133
  const reexportSpecifiers = this.getReexportSpecifiers();
21386
21134
  const renderedDependencies = new Map();
21387
21135
  const fileName = this.getFileName();
21136
+ const boundVariantsByRawId = this.outputOptions.format === 'iife' || this.outputOptions.format === 'umd'
21137
+ ? new Map()
21138
+ : undefined;
21388
21139
  for (const dependency of this.dependencies) {
21389
21140
  const imports = importSpecifiers.get(dependency) || null;
21390
21141
  const reexports = reexportSpecifiers.get(dependency) || null;
@@ -21400,31 +21151,32 @@ class Chunk {
21400
21151
  // side effect import, see https://github.com/rollup/rollup/issues/6111
21401
21152
  continue;
21402
21153
  }
21403
- const namedExportsMode = dependency instanceof ExternalChunk || dependency.exportMode !== 'default';
21404
- const importPath = dependency.getImportPath(fileName);
21405
- // Separate source-phase imports from regular imports
21406
- const sourcePhaseImport = imports?.find(index => index.phase === 'source');
21407
- const instanceImports = imports?.filter(index => index.phase !== 'source') ?? null;
21408
- renderedDependencies.set(dependency, {
21409
- attributes: dependency instanceof ExternalChunk
21410
- ? dependency.getImportAttributes(this.snippets)
21411
- : null,
21412
- defaultVariableName: dependency.defaultVariableName,
21413
- globalName: dependency instanceof ExternalChunk &&
21414
- (this.outputOptions.format === 'umd' || this.outputOptions.format === 'iife') &&
21415
- getGlobalName(dependency, this.outputOptions.globals, (imports || reexports) !== null, this.inputOptions.onLog),
21416
- importPath,
21417
- imports: instanceImports && instanceImports.length > 0 ? instanceImports : null,
21418
- isChunk: dependency instanceof Chunk,
21419
- name: dependency.variableName,
21420
- namedExportsMode,
21421
- namespaceVariableName: dependency.namespaceVariableName,
21422
- reexports,
21423
- sourcePhaseImport: sourcePhaseImport?.local
21424
- });
21154
+ renderedDependencies.set(dependency, this.getRenderedDependency(dependency, imports, reexports, fileName, boundVariantsByRawId));
21425
21155
  }
21426
21156
  return (this.renderedDependencies = renderedDependencies);
21427
21157
  }
21158
+ getRenderedDependency(dependency, imports, reexports, fileName, boundVariantsByRawId) {
21159
+ const namedExportsMode = dependency instanceof ExternalChunk || dependency.exportMode !== 'default';
21160
+ const importPath = dependency.getImportPath(fileName);
21161
+ // Separate source-phase imports from regular imports
21162
+ const sourcePhaseImport = imports?.find(index => index.phase === 'source');
21163
+ const instanceImports = imports?.filter(index => index.phase !== 'source') ?? null;
21164
+ return {
21165
+ attributes: dependency instanceof ExternalChunk ? dependency.getImportAttributes(this.snippets) : null,
21166
+ defaultVariableName: dependency.defaultVariableName,
21167
+ globalName: boundVariantsByRawId &&
21168
+ dependency instanceof ExternalChunk &&
21169
+ getGlobalName(dependency, this.outputOptions.globals, (imports || reexports) !== null, boundVariantsByRawId, this.inputOptions.onLog),
21170
+ importPath,
21171
+ imports: instanceImports && instanceImports.length > 0 ? instanceImports : null,
21172
+ isChunk: dependency instanceof Chunk,
21173
+ name: dependency.variableName,
21174
+ namedExportsMode,
21175
+ namespaceVariableName: dependency.namespaceVariableName,
21176
+ reexports,
21177
+ sourcePhaseImport: sourcePhaseImport?.local
21178
+ };
21179
+ }
21428
21180
  inlineChunkDependencies(chunk) {
21429
21181
  for (const dependency of chunk.dependencies) {
21430
21182
  if (this.dependencies.has(dependency))
@@ -21500,10 +21252,12 @@ class Chunk {
21500
21252
  }
21501
21253
  const { renderedExports, removedExports } = module.getRenderedExports();
21502
21254
  renderedModules[module.id] = {
21255
+ attributes: module.info.attributes,
21503
21256
  get code() {
21504
21257
  return source?.toString() ?? null;
21505
21258
  },
21506
21259
  originalLength: module.originalCode.length,
21260
+ rawId: module.info.rawId,
21507
21261
  removedExports,
21508
21262
  renderedExports,
21509
21263
  renderedLength
@@ -21687,6 +21441,14 @@ function* concatLazy(iterables) {
21687
21441
  * Then we group all modules with the same dependent entry points into chunks
21688
21442
  * as those modules will always be loaded together.
21689
21443
  *
21444
+ * Manual chunks act as additional entry points whose entry modules are the
21445
+ * set of their member modules. When analyzing the module graph, reaching one
21446
+ * member means reaching all members of that manual chunk, so all members
21447
+ * share the same dependent entries and each manual chunk forms exactly one
21448
+ * chunk. In entry mode (`onlyExplicitManualChunks: false`), that
21449
+ * chunk also takes over modules whose dependent entries match its own, while
21450
+ * in explicit mode nothing joins it.
21451
+ *
21690
21452
  * One non-trivial optimization we can apply is that dynamic entries are
21691
21453
  * different from static entries in so far as when a dynamic import occurs,
21692
21454
  * some modules are already in memory. If some of these modules are also
@@ -21789,90 +21551,131 @@ function* concatLazy(iterables) {
21789
21551
  * those chunks that are already loaded for that dynamic entry and create
21790
21552
  * another round of chunks.
21791
21553
  */
21792
- function getChunkAssignments(entries, manualChunkAliasByEntry, minChunkSize, log, isManualChunksFunctionForm, onlyExplicitManualChunks) {
21793
- const { chunkDefinitions, manualChunkModules, manualChunkModulesByModule } = getChunkDefinitionsFromManualChunks(manualChunkAliasByEntry, isManualChunksFunctionForm, onlyExplicitManualChunks);
21794
- const { entriesAndManualChunksCount, dependentEntriesByModule, dynamicallyDependentEntriesByDynamicEntry, dynamicImportsByEntry, dynamicallyDependentEntriesByAwaitedDynamicEntry, awaitedDynamicImportsByEntry } = analyzeModuleGraph(entries, manualChunkModules, manualChunkModulesByModule);
21554
+ function getChunkAssignments(entries, manualChunkAliasByEntry, minChunkSize, log, onlyExplicitManualChunks) {
21555
+ const { manualChunkByModule, manualChunks } = getManualChunkMemberships(manualChunkAliasByEntry, log);
21556
+ const manualChunkIndexByChunk = new Map();
21557
+ manualChunks.forEach((manualChunk, index) => {
21558
+ manualChunkIndexByChunk.set(manualChunk, entries.length + index);
21559
+ });
21560
+ const { entriesAndManualChunksCount, dependentEntriesByModule, dynamicallyDependentEntriesByDynamicEntry, dynamicImportsByEntry, dynamicallyDependentEntriesByAwaitedDynamicEntry, awaitedDynamicImportsByEntry } = analyzeModuleGraph(entries, manualChunks, manualChunkByModule, manualChunkIndexByChunk);
21561
+ const { modulesWithDependentEntries, topLevelAwaitingCycleSingletons } = getModulesWithDependentEntries(dependentEntriesByModule, manualChunkByModule);
21795
21562
  // Each chunk is identified by its position in this array
21796
- const chunkAtoms = getChunksWithSameDependentEntries(getModulesWithDependentEntriesAndHandleTLACycles(dependentEntriesByModule, manualChunkModulesByModule, chunkDefinitions));
21563
+ const chunkAtoms = getChunkAtoms(modulesWithDependentEntries, onlyExplicitManualChunks);
21797
21564
  const staticDependencyAtomsByEntry = getStaticDependencyAtomsByEntry(entriesAndManualChunksCount, chunkAtoms);
21798
21565
  // Warning: This will consume dynamicallyDependentEntriesByDynamicEntry.
21799
21566
  // If we no longer want this, we should make a copy here.
21800
21567
  const alreadyLoadedAtomsByEntry = getAlreadyLoadedAtomsByEntry(staticDependencyAtomsByEntry, dynamicallyDependentEntriesByDynamicEntry, dynamicImportsByEntry, entriesAndManualChunksCount);
21801
21568
  const awaitedAlreadyLoadedAtomsByEntry = getAlreadyLoadedAtomsByEntry(staticDependencyAtomsByEntry, dynamicallyDependentEntriesByAwaitedDynamicEntry, awaitedDynamicImportsByEntry, entriesAndManualChunksCount);
21569
+ // A manual chunk only behaves like a dynamic entry if its whole member atom
21570
+ // is not already loaded whenever any entry dynamically loads it. Otherwise
21571
+ // there is nothing to gain (and cycles could be created) and the manual
21572
+ // chunk keeps behaving like a static pseudo-entry.
21573
+ keepAlreadyLoadedManualChunksStatic(manualChunkIndexByChunk, chunkAtoms, alreadyLoadedAtomsByEntry);
21802
21574
  // This mutates the dependentEntries in chunkAtoms
21803
21575
  removeUnnecessaryDependentEntries(chunkAtoms, alreadyLoadedAtomsByEntry, awaitedAlreadyLoadedAtomsByEntry);
21804
- const { chunks, sideEffectAtoms, sizeByAtom } = getChunksWithSameDependentEntriesAndCorrelatedAtoms(chunkAtoms, staticDependencyAtomsByEntry, alreadyLoadedAtomsByEntry, minChunkSize);
21805
- chunkDefinitions.push(...getOptimizedChunks(chunks, minChunkSize, sideEffectAtoms, sizeByAtom, log).map(({ modules }) => ({
21806
- alias: null,
21807
- modules
21808
- })));
21809
- return chunkDefinitions;
21810
- }
21811
- function getChunkDefinitionsFromManualChunks(manualChunkAliasByEntry, isManualChunksFunctionForm, onlyExplicitManualChunks) {
21812
- const modulesInManualChunks = new Set(manualChunkAliasByEntry.keys());
21813
- const manualChunkModulesByAlias = Object.create(null);
21576
+ const { chunks, sideEffectAtoms, sizeByAtom } = getChunksFromAtoms(chunkAtoms, staticDependencyAtomsByEntry, alreadyLoadedAtomsByEntry, minChunkSize, onlyExplicitManualChunks);
21577
+ return [
21578
+ ...topLevelAwaitingCycleSingletons,
21579
+ ...getOptimizedChunks(chunks, minChunkSize, sideEffectAtoms, sizeByAtom, log).map(({ alias, modules }) => ({
21580
+ alias,
21581
+ modules
21582
+ }))
21583
+ ];
21584
+ }
21585
+ function getManualChunkMemberships(manualChunkAliasByEntry, log) {
21586
+ const modulesByAlias = Object.create(null);
21814
21587
  const sortedEntriesWithAlias = [...manualChunkAliasByEntry].sort(([entryA], [entryB]) => entryA.execIndex - entryB.execIndex);
21815
21588
  for (const [entry, alias] of sortedEntriesWithAlias) {
21816
- const chunkModules = (manualChunkModulesByAlias[alias] ||= []);
21817
- if (isManualChunksFunctionForm && onlyExplicitManualChunks) {
21818
- chunkModules.push(entry);
21819
- }
21820
- else {
21821
- addStaticDependenciesToManualChunk(entry, chunkModules, modulesInManualChunks);
21589
+ (modulesByAlias[alias] ||= []).push(entry);
21590
+ }
21591
+ const manualChunks = [];
21592
+ const manualChunkByModule = new Map();
21593
+ for (const [alias, modules] of Object.entries(modulesByAlias)) {
21594
+ const includedModules = modules.filter(module => module.isEmitted());
21595
+ if (includedModules.length === 0) {
21596
+ log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logEmptyManualChunk(alias));
21597
+ continue;
21822
21598
  }
21823
- }
21824
- const manualChunks = Object.entries(manualChunkModulesByAlias);
21825
- const manualChunkModules = new Array(manualChunks.length);
21826
- const chunkDefinitions = new Array(manualChunks.length);
21827
- const manualChunkModulesByModule = new Map();
21828
- let index = 0;
21829
- for (const [alias, modules] of manualChunks) {
21830
- chunkDefinitions[index] = { alias, modules };
21831
- manualChunkModules[index] = modules;
21832
- for (const module of modules) {
21833
- manualChunkModulesByModule.set(module, modules);
21599
+ const manualChunk = { alias, modules: includedModules };
21600
+ manualChunks.push(manualChunk);
21601
+ for (const module of includedModules) {
21602
+ manualChunkByModule.set(module, manualChunk);
21834
21603
  }
21835
- index++;
21836
21604
  }
21837
- return { chunkDefinitions, manualChunkModules, manualChunkModulesByModule };
21605
+ return { manualChunkByModule, manualChunks };
21838
21606
  }
21839
- function addStaticDependenciesToManualChunk(entry, manualChunkModules, modulesInManualChunks) {
21840
- const modulesToHandle = new Set([entry]);
21841
- for (const module of modulesToHandle) {
21842
- modulesInManualChunks.add(module);
21843
- manualChunkModules.push(module);
21844
- for (const dependency of module.dependencies) {
21845
- if (!(dependency instanceof ExternalModule || modulesInManualChunks.has(dependency))) {
21846
- modulesToHandle.add(dependency);
21847
- }
21607
+ /**
21608
+ * The keys are shared by both grouping stages. Non-members join a manual
21609
+ * chunk only in entry mode and only if exactly one manual chunk has their
21610
+ * signature.
21611
+ */
21612
+ function getChunkKeys(aliasesWithDependentEntries, onlyExplicitManualChunks) {
21613
+ const signatureKeys = new Array(aliasesWithDependentEntries.length);
21614
+ // A value of null means that several manual chunks share this signature, so
21615
+ // no unambiguous alias can be assigned
21616
+ const uniqueAliasBySignatureKey = onlyExplicitManualChunks
21617
+ ? null
21618
+ : new Map();
21619
+ for (const [index, { dependentEntries, alias }] of aliasesWithDependentEntries.entries()) {
21620
+ let signature = 0n;
21621
+ for (const entryIndex of dependentEntries) {
21622
+ signature |= 1n << BigInt(entryIndex);
21623
+ }
21624
+ const signatureKey = String(signature);
21625
+ signatureKeys[index] = signatureKey;
21626
+ if (uniqueAliasBySignatureKey && alias !== null) {
21627
+ const existingAlias = uniqueAliasBySignatureKey.get(signatureKey);
21628
+ uniqueAliasBySignatureKey.set(signatureKey, existingAlias === undefined || existingAlias === alias ? alias : null);
21848
21629
  }
21849
21630
  }
21631
+ // As there is exactly one manual chunk group per alias, manual chunk members
21632
+ // are identified by their alias alone
21633
+ return aliasesWithDependentEntries.map(({ alias }, index) => {
21634
+ const chunkAlias = alias ?? uniqueAliasBySignatureKey?.get(signatureKeys[index]) ?? null;
21635
+ return {
21636
+ alias: chunkAlias,
21637
+ key: chunkAlias === null ? signatureKeys[index] : `manual:${chunkAlias}`
21638
+ };
21639
+ });
21850
21640
  }
21851
- function analyzeModuleGraph(entries, manualChunkModules, manualChunkModulesByModule) {
21641
+ function analyzeModuleGraph(entries, manualChunks, manualChunkByModule, manualChunkIndexByChunk) {
21852
21642
  const dynamicEntryModules = new Set();
21853
21643
  const awaitedDynamicEntryModules = new Set();
21854
21644
  const dependentEntriesByModule = new Map();
21645
+ const manualChunkModules = manualChunks.map(chunk => chunk.modules);
21855
21646
  const allEntriesSet = new Set(entries);
21647
+ for (const modules of manualChunkModules) {
21648
+ for (const module of modules) {
21649
+ allEntriesSet.add(module);
21650
+ }
21651
+ }
21856
21652
  // Each entry is defined by its position in this array
21857
21653
  const allEntriesAndManualChunks = entries.map(module => [module]).concat(manualChunkModules);
21858
21654
  const dynamicImportModulesByEntry = new Array(allEntriesAndManualChunks.length);
21859
21655
  const awaitedDynamicImportModulesByEntry = new Array(allEntriesAndManualChunks.length);
21656
+ const dynamicallyLoadedManualChunksByEntry = new Array(allEntriesAndManualChunks.length);
21657
+ const awaitedLoadedManualChunksByEntry = new Array(allEntriesAndManualChunks.length);
21860
21658
  let entryOrManualChunkIndex = 0;
21861
21659
  for (const currentEntryModules of allEntriesAndManualChunks) {
21862
21660
  const dynamicImportsForCurrentEntry = new Set();
21863
21661
  const awaitedDynamicImportsForCurrentEntry = new Set();
21662
+ const dynamicManualChunksForCurrentEntry = new Set();
21663
+ const awaitedManualChunksForCurrentEntry = new Set();
21864
21664
  dynamicImportModulesByEntry[entryOrManualChunkIndex] = dynamicImportsForCurrentEntry;
21865
21665
  awaitedDynamicImportModulesByEntry[entryOrManualChunkIndex] =
21866
21666
  awaitedDynamicImportsForCurrentEntry;
21667
+ dynamicallyLoadedManualChunksByEntry[entryOrManualChunkIndex] =
21668
+ dynamicManualChunksForCurrentEntry;
21669
+ awaitedLoadedManualChunksByEntry[entryOrManualChunkIndex] = awaitedManualChunksForCurrentEntry;
21867
21670
  const staticDependencies = new Set(currentEntryModules);
21868
21671
  // If we have a very large manual chunk, tracking if it is already added to the dependencies will improve performance
21869
21672
  const addedManualChunks = new Set();
21870
21673
  for (const module of staticDependencies) {
21871
21674
  getOrCreate(dependentEntriesByModule, module, (getNewSet)).add(entryOrManualChunkIndex);
21872
- const manualChunkMembers = manualChunkModulesByModule.get(module);
21873
- if (manualChunkMembers && !addedManualChunks.has(manualChunkMembers)) {
21874
- addedManualChunks.add(manualChunkMembers);
21875
- for (const manualChunkMember of manualChunkMembers) {
21675
+ const manualChunk = manualChunkByModule.get(module);
21676
+ if (manualChunk && !addedManualChunks.has(manualChunk)) {
21677
+ addedManualChunks.add(manualChunk);
21678
+ for (const manualChunkMember of manualChunk.modules) {
21876
21679
  staticDependencies.add(manualChunkMember);
21877
21680
  }
21878
21681
  }
@@ -21882,17 +21685,30 @@ function analyzeModuleGraph(entries, manualChunkModules, manualChunkModulesByMod
21882
21685
  }
21883
21686
  }
21884
21687
  for (const { node: { resolution } } of module.dynamicImports) {
21885
- if (resolution instanceof Module &&
21886
- resolution.includedDynamicImporters.length > 0 &&
21887
- !allEntriesSet.has(resolution)) {
21888
- dynamicEntryModules.add(resolution);
21889
- allEntriesSet.add(resolution);
21890
- allEntriesAndManualChunks.push([resolution]);
21688
+ let manuallyLoadedChunk = null;
21689
+ if (resolution instanceof Module && resolution.includedDynamicImporters.length > 0) {
21690
+ if (!allEntriesSet.has(resolution)) {
21691
+ dynamicEntryModules.add(resolution);
21692
+ allEntriesSet.add(resolution);
21693
+ allEntriesAndManualChunks.push([resolution]);
21694
+ }
21695
+ else if (!dynamicEntryModules.has(resolution)) {
21696
+ manuallyLoadedChunk = manualChunkByModule.get(resolution) ?? null;
21697
+ if (!manuallyLoadedChunk) {
21698
+ continue;
21699
+ }
21700
+ dynamicManualChunksForCurrentEntry.add(manuallyLoadedChunk);
21701
+ }
21891
21702
  dynamicImportsForCurrentEntry.add(resolution);
21892
21703
  for (const includedTopLevelAwaitingDynamicImporter of resolution.includedTopLevelAwaitingDynamicImporters) {
21893
21704
  if (staticDependencies.has(includedTopLevelAwaitingDynamicImporter)) {
21894
- awaitedDynamicEntryModules.add(resolution);
21895
21705
  awaitedDynamicImportsForCurrentEntry.add(resolution);
21706
+ if (manuallyLoadedChunk) {
21707
+ awaitedManualChunksForCurrentEntry.add(manuallyLoadedChunk);
21708
+ }
21709
+ else {
21710
+ awaitedDynamicEntryModules.add(resolution);
21711
+ }
21896
21712
  break;
21897
21713
  }
21898
21714
  }
@@ -21904,11 +21720,18 @@ function analyzeModuleGraph(entries, manualChunkModules, manualChunkModulesByMod
21904
21720
  allEntriesSet.add(dependency);
21905
21721
  allEntriesAndManualChunks.push([dependency]);
21906
21722
  }
21723
+ else {
21724
+ const manuallyLoadedChunk = manualChunkByModule.get(dependency);
21725
+ if (manuallyLoadedChunk) {
21726
+ dynamicManualChunksForCurrentEntry.add(manuallyLoadedChunk);
21727
+ dynamicImportsForCurrentEntry.add(dependency);
21728
+ }
21729
+ }
21907
21730
  }
21908
21731
  }
21909
21732
  entryOrManualChunkIndex++;
21910
21733
  }
21911
- const { awaitedDynamicEntries, awaitedDynamicImportsByEntry, dynamicEntries, dynamicImportsByEntry } = getDynamicEntries(allEntriesAndManualChunks, dynamicEntryModules, dynamicImportModulesByEntry, awaitedDynamicEntryModules, awaitedDynamicImportModulesByEntry);
21734
+ const { awaitedDynamicEntries, awaitedDynamicImportsByEntry, dynamicEntries, dynamicImportsByEntry } = getDynamicEntries(allEntriesAndManualChunks, dynamicEntryModules, dynamicImportModulesByEntry, awaitedDynamicEntryModules, awaitedDynamicImportModulesByEntry, dynamicallyLoadedManualChunksByEntry, awaitedLoadedManualChunksByEntry, manualChunkIndexByChunk);
21912
21735
  return {
21913
21736
  awaitedDynamicImportsByEntry,
21914
21737
  dependentEntriesByModule,
@@ -21918,12 +21741,14 @@ function analyzeModuleGraph(entries, manualChunkModules, manualChunkModulesByMod
21918
21741
  entriesAndManualChunksCount: allEntriesAndManualChunks.length
21919
21742
  };
21920
21743
  }
21921
- function getDynamicEntries(allEntriesAndManualChunks, dynamicEntryModules, dynamicImportModulesByEntry, awaitedDynamicEntryModules, awaitedDynamicImportModulesByEntry) {
21744
+ function getDynamicEntries(allEntriesAndManualChunks, dynamicEntryModules, dynamicImportModulesByEntry, awaitedDynamicEntryModules, awaitedDynamicImportModulesByEntry, dynamicallyLoadedManualChunksByEntry, awaitedLoadedManualChunksByEntry, manualChunkIndexByChunk) {
21922
21745
  const entryIndexByModule = new Map();
21923
21746
  const dynamicEntries = new Set();
21924
21747
  const awaitedDynamicEntries = new Set();
21925
21748
  for (const [entryIndex, entryModules] of allEntriesAndManualChunks.entries()) {
21926
21749
  for (const entryModule of entryModules) {
21750
+ // Manual chunk members and in particular members that are also static
21751
+ // entries map to their manual chunk for dynamic-edge bookkeeping
21927
21752
  entryIndexByModule.set(entryModule, entryIndex);
21928
21753
  if (dynamicEntryModules.has(entryModule)) {
21929
21754
  dynamicEntries.add(entryIndex);
@@ -21933,6 +21758,16 @@ function getDynamicEntries(allEntriesAndManualChunks, dynamicEntryModules, dynam
21933
21758
  }
21934
21759
  }
21935
21760
  }
21761
+ for (const dynamicallyLoadedManualChunks of dynamicallyLoadedManualChunksByEntry) {
21762
+ for (const manuallyLoadedChunk of dynamicallyLoadedManualChunks) {
21763
+ dynamicEntries.add(manualChunkIndexByChunk.get(manuallyLoadedChunk));
21764
+ }
21765
+ }
21766
+ for (const awaitedLoadedManualChunks of awaitedLoadedManualChunksByEntry) {
21767
+ for (const awaitedLoadedChunk of awaitedLoadedManualChunks) {
21768
+ awaitedDynamicEntries.add(manualChunkIndexByChunk.get(awaitedLoadedChunk));
21769
+ }
21770
+ }
21936
21771
  const dynamicImportsByEntry = getDynamicImportsByEntry(dynamicImportModulesByEntry, entryIndexByModule);
21937
21772
  const awaitedDynamicImportsByEntry = getDynamicImportsByEntry(awaitedDynamicImportModulesByEntry, entryIndexByModule);
21938
21773
  return {
@@ -21976,33 +21811,34 @@ function getDynamicallyDependentEntriesByDynamicEntry(dependentEntriesByModule,
21976
21811
  }
21977
21812
  return dynamicallyDependentEntriesByDynamicEntry;
21978
21813
  }
21979
- function getChunksWithSameDependentEntries(moduleWithDependentEntries) {
21814
+ function getChunkAtoms(modulesWithDependentEntries, onlyExplicitManualChunks) {
21815
+ const chunkKeys = getChunkKeys(modulesWithDependentEntries, onlyExplicitManualChunks);
21980
21816
  const chunkModules = Object.create(null);
21981
- for (const { dependentEntries, module } of moduleWithDependentEntries) {
21982
- let chunkSignature = 0n;
21983
- for (const entryIndex of dependentEntries) {
21984
- chunkSignature |= 1n << BigInt(entryIndex);
21985
- }
21986
- (chunkModules[String(chunkSignature)] ||= {
21817
+ for (const [index, { dependentEntries, module }] of modulesWithDependentEntries.entries()) {
21818
+ const { alias, key } = chunkKeys[index];
21819
+ (chunkModules[key] ||= {
21820
+ alias,
21987
21821
  dependentEntries: new Set(dependentEntries),
21988
21822
  modules: []
21989
21823
  }).modules.push(module);
21990
21824
  }
21991
21825
  return Object.values(chunkModules);
21992
21826
  }
21993
- function* getModulesWithDependentEntriesAndHandleTLACycles(dependentEntriesByModule, modulesInManualChunks, chunkDefinitions) {
21827
+ function getModulesWithDependentEntries(dependentEntriesByModule, manualChunkByModule) {
21828
+ const modulesWithDependentEntries = [];
21829
+ const topLevelAwaitingCycleSingletons = [];
21994
21830
  for (const [module, dependentEntries] of dependentEntriesByModule) {
21995
- if (!modulesInManualChunks.has(module)) {
21996
- if (module.cycles.size > 0 && module.includedTopLevelAwaitingDynamicImporters.size > 0) {
21997
- chunkDefinitions.push({
21998
- alias: null,
21999
- modules: [module]
22000
- });
22001
- continue;
22002
- }
22003
- yield { dependentEntries, module };
21831
+ const alias = manualChunkByModule.get(module)?.alias ?? null;
21832
+ if (alias === null &&
21833
+ module.cycles.size > 0 &&
21834
+ module.includedTopLevelAwaitingDynamicImporters.size > 0) {
21835
+ topLevelAwaitingCycleSingletons.push({ alias: null, modules: [module] });
21836
+ }
21837
+ else {
21838
+ modulesWithDependentEntries.push({ alias, dependentEntries, module });
22004
21839
  }
22005
21840
  }
21841
+ return { modulesWithDependentEntries, topLevelAwaitingCycleSingletons };
22006
21842
  }
22007
21843
  function getStaticDependencyAtomsByEntry(entriesAndManualChunksCount, chunkAtoms) {
22008
21844
  // The indices correspond to the indices in allEntries. The atoms correspond
@@ -22048,6 +21884,28 @@ function getAlreadyLoadedAtomsByEntry(staticDependencyAtomsByEntry, dynamicallyD
22048
21884
  }
22049
21885
  return alreadyLoadedAtomsByEntry;
22050
21886
  }
21887
+ /**
21888
+ * Manual chunks whose member atom is already loaded in every context that
21889
+ * dynamically loads them must not be treated like dynamic entries as that
21890
+ * would only cause unnecessary chunk cycles. The all-or-nothing rule resets
21891
+ * their already loaded atoms so that pruning behaves exactly as if they were
21892
+ * static pseudo-entries.
21893
+ */
21894
+ function keepAlreadyLoadedManualChunksStatic(manualChunkIndexByChunk, chunkAtoms, alreadyLoadedAtomsByEntry) {
21895
+ const memberAtomMaskByAlias = new Map();
21896
+ for (const [index, { alias }] of chunkAtoms.entries()) {
21897
+ if (alias !== null) {
21898
+ memberAtomMaskByAlias.set(alias, 1n << BigInt(index));
21899
+ }
21900
+ }
21901
+ for (const [manualChunk, manualChunkIndex] of manualChunkIndexByChunk) {
21902
+ const memberAtomMask = memberAtomMaskByAlias.get(manualChunk.alias);
21903
+ const alreadyLoadedAtoms = alreadyLoadedAtomsByEntry[manualChunkIndex];
21904
+ if (memberAtomMask !== undefined && (alreadyLoadedAtoms & memberAtomMask) === memberAtomMask) {
21905
+ alreadyLoadedAtomsByEntry[manualChunkIndex] = 0n;
21906
+ }
21907
+ }
21908
+ }
22051
21909
  /**
22052
21910
  * This removes all unnecessary dynamic entries from the dependentEntries in its
22053
21911
  * first argument if a chunk is already loaded without that entry.
@@ -22067,25 +21925,25 @@ function removeUnnecessaryDependentEntries(chunkAtoms, alreadyLoadedAtomsByEntry
22067
21925
  chunkMask <<= 1n;
22068
21926
  }
22069
21927
  }
22070
- function getChunksWithSameDependentEntriesAndCorrelatedAtoms(chunkAtoms, staticDependencyAtomsByEntry, alreadyLoadedAtomsByEntry, minChunkSize) {
22071
- const chunksBySignature = Object.create(null);
21928
+ function getChunksFromAtoms(chunkAtoms, staticDependencyAtomsByEntry, alreadyLoadedAtomsByEntry, minChunkSize, onlyExplicitManualChunks) {
21929
+ const chunkKeys = getChunkKeys(chunkAtoms, onlyExplicitManualChunks);
21930
+ const chunksByKey = Object.create(null);
22072
21931
  const chunkByModule = new Map();
22073
21932
  const sizeByAtom = new Array(chunkAtoms.length);
22074
21933
  let sideEffectAtoms = 0n;
22075
21934
  let atomMask = 1n;
22076
- let index = 0;
22077
- for (const { dependentEntries, modules } of chunkAtoms) {
22078
- let chunkSignature = 0n;
21935
+ for (const [atomIndex, { dependentEntries, modules }] of chunkAtoms.entries()) {
22079
21936
  let correlatedAtoms = -1n;
22080
21937
  for (const entryIndex of dependentEntries) {
22081
- chunkSignature |= 1n << BigInt(entryIndex);
22082
21938
  // Correlated atoms are the atoms that are guaranteed to be loaded as
22083
21939
  // well when a given atom is loaded. It is the intersection of the already
22084
21940
  // loaded modules of each chunk merged with its static dependencies.
22085
21941
  correlatedAtoms &=
22086
21942
  staticDependencyAtomsByEntry[entryIndex] | alreadyLoadedAtomsByEntry[entryIndex];
22087
21943
  }
22088
- const chunk = (chunksBySignature[String(chunkSignature)] ||= {
21944
+ const { alias, key } = chunkKeys[atomIndex];
21945
+ const chunk = (chunksByKey[key] ||= {
21946
+ alias,
22089
21947
  containedAtoms: 0n,
22090
21948
  correlatedAtoms,
22091
21949
  dependencies: new Set(),
@@ -22111,14 +21969,14 @@ function getChunksWithSameDependentEntriesAndCorrelatedAtoms(chunkAtoms, staticD
22111
21969
  if (!pure) {
22112
21970
  sideEffectAtoms |= atomMask;
22113
21971
  }
22114
- sizeByAtom[index++] = atomSize;
21972
+ sizeByAtom[atomIndex] = atomSize;
22115
21973
  chunk.containedAtoms |= atomMask;
22116
21974
  chunk.modules.push(...modules);
22117
21975
  chunk.pure &&= pure;
22118
21976
  chunk.size += atomSize;
22119
21977
  atomMask <<= 1n;
22120
21978
  }
22121
- const chunks = Object.values(chunksBySignature);
21979
+ const chunks = Object.values(chunksByKey);
22122
21980
  sideEffectAtoms |= addChunkDependenciesAndGetExternalSideEffectAtoms(chunks, chunkByModule, atomMask);
22123
21981
  return { chunks, sideEffectAtoms, sizeByAtom };
22124
21982
  }
@@ -22241,16 +22099,22 @@ function getOptimizedChunks(chunks, minChunkSize, sideEffectAtoms, sizeByAtom, l
22241
22099
  }
22242
22100
  mergeChunks(chunkPartition, minChunkSize, sideEffectAtoms, sizeByAtom);
22243
22101
  if (minChunkSize > 1) {
22244
- log('info', parseAst_js.logOptimizeChunkStatus(chunkPartition.small.size + chunkPartition.big.size, chunkPartition.small.size, 'After merging chunks'));
22102
+ log('info', parseAst_js.logOptimizeChunkStatus(chunkPartition.small.size + chunkPartition.big.size + chunkPartition.fixed.size, chunkPartition.small.size, 'After merging chunks'));
22245
22103
  }
22246
22104
  timeEnd('optimize chunks', 3);
22247
- return [...chunkPartition.small, ...chunkPartition.big];
22105
+ return [...chunkPartition.small, ...chunkPartition.big, ...chunkPartition.fixed];
22248
22106
  }
22249
22107
  function getPartitionedChunks(chunks, minChunkSize) {
22250
22108
  const smallChunks = [];
22251
22109
  const bigChunks = [];
22110
+ const fixedChunks = [];
22252
22111
  for (const chunk of chunks) {
22253
- (chunk.size < minChunkSize ? smallChunks : bigChunks).push(chunk);
22112
+ if (chunk.alias !== null) {
22113
+ fixedChunks.push(chunk);
22114
+ }
22115
+ else {
22116
+ (chunk.size < minChunkSize ? smallChunks : bigChunks).push(chunk);
22117
+ }
22254
22118
  }
22255
22119
  if (smallChunks.length === 0) {
22256
22120
  return null;
@@ -22259,6 +22123,7 @@ function getPartitionedChunks(chunks, minChunkSize) {
22259
22123
  bigChunks.sort(compareChunkSize);
22260
22124
  return {
22261
22125
  big: new Set(bigChunks),
22126
+ fixed: new Set(fixedChunks),
22262
22127
  small: new Set(smallChunks)
22263
22128
  };
22264
22129
  }
@@ -22382,7 +22247,7 @@ function commondir(files) {
22382
22247
  if (files.length === 0)
22383
22248
  return '/';
22384
22249
  if (files.length === 1)
22385
- return path.dirname(files[0]);
22250
+ return sp.dirname(files[0]);
22386
22251
  const commonSegments = files.slice(1).reduce((commonSegments, file) => {
22387
22252
  const pathSegments = file.split(/\/+|\\+/);
22388
22253
  let index;
@@ -22654,9 +22519,9 @@ function getCollapsedSourcemap(id, originalCode, originalSourcemap, sourcemapCha
22654
22519
  if (originalSourcemap) {
22655
22520
  const sources = originalSourcemap.sources;
22656
22521
  const sourcesContent = originalSourcemap.sourcesContent || [];
22657
- const directory = path.dirname(id) || '.';
22522
+ const directory = sp.dirname(id) || '.';
22658
22523
  const sourceRoot = originalSourcemap.sourceRoot || '.';
22659
- const baseSources = sources.map((source, index) => new Source(path.resolve(directory, sourceRoot, source), sourcesContent[index]));
22524
+ const baseSources = sources.map((source, index) => new Source(sp.resolve(directory, sourceRoot, source), sourcesContent[index]));
22660
22525
  source = new Link(originalSourcemap, baseSources);
22661
22526
  }
22662
22527
  else {
@@ -22673,9 +22538,9 @@ function collapseSourcemaps(file, map, modules, bundleSourcemapChain, excludeCon
22673
22538
  const source = bundleSourcemapChain.reduce(linkMap, link);
22674
22539
  let { sources, sourcesContent, names, mappings } = source.traceMappings();
22675
22540
  if (file) {
22676
- const directory = path.dirname(file);
22677
- sources = sources.map((source) => path.relative(directory, source));
22678
- file = path.basename(file);
22541
+ const directory = sp.dirname(file);
22542
+ sources = sources.map((source) => sp.relative(directory, source));
22543
+ file = sp.basename(file);
22679
22544
  }
22680
22545
  for (const module of modules) {
22681
22546
  resetSourcemapCache(module.originalSourcemap, module.sourcemapChain);
@@ -22754,11 +22619,11 @@ async function transformChunk(magicString, fileName, usedModules, chunkGraph, op
22754
22619
  timeStart('sourcemaps', 3);
22755
22620
  let resultingFile;
22756
22621
  if (file)
22757
- resultingFile = path.resolve(sourcemapFile || file);
22622
+ resultingFile = sp.resolve(sourcemapFile || file);
22758
22623
  else if (dir)
22759
- resultingFile = path.resolve(dir, fileName);
22624
+ resultingFile = sp.resolve(dir, fileName);
22760
22625
  else
22761
- resultingFile = path.resolve(fileName);
22626
+ resultingFile = sp.resolve(fileName);
22762
22627
  const decodedMap = magicString.generateDecodedMap({});
22763
22628
  map = collapseSourcemaps(resultingFile, decodedMap, usedModules, sourcemapChain, sourcemapExcludeSources, log);
22764
22629
  for (let sourcesIndex = 0; sourcesIndex < map.sources.length; ++sourcesIndex) {
@@ -22912,7 +22777,7 @@ function emitSourceMapAndGetComment(fileName, map, pluginDriver, { sourcemap, so
22912
22777
  url = map.toUrl();
22913
22778
  }
22914
22779
  else {
22915
- const sourcemapFileName = path.basename(fileName);
22780
+ const sourcemapFileName = sp.basename(fileName);
22916
22781
  url = sourcemapBaseUrl
22917
22782
  ? new URL(sourcemapFileName, sourcemapBaseUrl).toString()
22918
22783
  : sourcemapFileName;
@@ -23045,7 +22910,7 @@ class Bundle {
23045
22910
  ? [{ alias: null, modules: includedModules }]
23046
22911
  : preserveModules
23047
22912
  ? includedModules.map(module => ({ alias: null, modules: [module] }))
23048
- : getChunkAssignments(this.graph.entryModules, manualChunkAliasByEntry, experimentalMinChunkSize, this.inputOptions.onLog, typeof manualChunks === 'function', onlyExplicitManualChunks);
22913
+ : getChunkAssignments(this.graph.entryModules, manualChunkAliasByEntry, experimentalMinChunkSize, this.inputOptions.onLog, onlyExplicitManualChunks);
23049
22914
  const chunks = new Array(executableModule.length);
23050
22915
  const chunkByModule = new Map();
23051
22916
  let index = 0;
@@ -23058,7 +22923,7 @@ class Bundle {
23058
22923
  chunk.link();
23059
22924
  }
23060
22925
  if (!inlineDynamicImports && !preserveModules) {
23061
- this.checkCircularChunks(chunks);
22926
+ this.checkCircularChunks(chunks, onlyExplicitManualChunks);
23062
22927
  }
23063
22928
  const facades = [];
23064
22929
  for (const chunk of chunks) {
@@ -23066,23 +22931,29 @@ class Bundle {
23066
22931
  }
23067
22932
  return [...chunks, ...facades];
23068
22933
  }
23069
- checkCircularChunks(chunks) {
22934
+ checkCircularChunks(chunks, onlyExplicitManualChunks) {
23070
22935
  const visited = new Set();
23071
22936
  const parents = new Map();
23072
22937
  const handleDependency = (chunk, parent) => {
23073
22938
  if (parents.has(chunk)) {
23074
22939
  if (!visited.has(chunk)) {
23075
22940
  const path = [chunk.getChunkName()];
23076
- let isManualChunkConflict = chunk.isManualChunk;
22941
+ const cycleChunks = [chunk];
23077
22942
  let nextChunk = parent;
23078
22943
  while (nextChunk !== chunk && nextChunk) {
23079
22944
  path.push(nextChunk.getChunkName());
23080
- isManualChunkConflict &&= nextChunk.isManualChunk;
22945
+ cycleChunks.push(nextChunk);
23081
22946
  nextChunk = parents.get(nextChunk);
23082
22947
  }
22948
+ const manualChunkNames = cycleChunks
22949
+ .filter(cycleChunk => cycleChunk.isManualChunk)
22950
+ .map(cycleChunk => cycleChunk.getChunkName());
22951
+ const nonManualChunkName = cycleChunks
22952
+ .find(cycleChunk => !cycleChunk.isManualChunk)
22953
+ ?.getChunkName();
23083
22954
  path.push(path[0]);
23084
22955
  path.reverse();
23085
- this.inputOptions.onLog(parseAst_js.LOGLEVEL_WARN, parseAst_js.logCircularChunk(path, isManualChunkConflict));
22956
+ this.inputOptions.onLog(parseAst_js.LOGLEVEL_WARN, parseAst_js.logCircularChunk(path, manualChunkNames, nonManualChunkName, onlyExplicitManualChunks));
23086
22957
  }
23087
22958
  return;
23088
22959
  }
@@ -23117,8 +22988,7 @@ function validateOptionsForMultiChunkOutput(outputOptions, log) {
23117
22988
  function getIncludedModules(modulesById) {
23118
22989
  const includedModules = [];
23119
22990
  for (const module of modulesById.values()) {
23120
- if (module instanceof Module &&
23121
- (module.isIncluded() || module.info.isEntry || module.includedDynamicImporters.length > 0)) {
22991
+ if (module instanceof Module && module.isEmitted()) {
23122
22992
  includedModules.push(module);
23123
22993
  }
23124
22994
  }
@@ -23152,7 +23022,7 @@ function addModuleToManualChunk(alias, module, manualChunkAliasByEntry) {
23152
23022
  function isFileNameOutsideOutputDirectory(fileName) {
23153
23023
  // Use join() to normalize ".." segments, then replace backslashes so the
23154
23024
  // string checks below work identically on Windows and POSIX.
23155
- const normalized = path.join(fileName).replaceAll('\\', '/');
23025
+ const normalized = sp.join(fileName).replaceAll('\\', '/');
23156
23026
  return (normalized === '..' ||
23157
23027
  normalized.startsWith('../') ||
23158
23028
  normalized === '.' ||
@@ -23172,50 +23042,6 @@ function validateOutputBundleFileNames(bundle) {
23172
23042
  }
23173
23043
  }
23174
23044
 
23175
- function flru (max) {
23176
- var num, curr, prev;
23177
- var limit = max;
23178
-
23179
- function keep(key, value) {
23180
- if (++num > limit) {
23181
- prev = curr;
23182
- reset(1);
23183
- ++num;
23184
- }
23185
- curr[key] = value;
23186
- }
23187
-
23188
- function reset(isPartial) {
23189
- num = 0;
23190
- curr = Object.create(null);
23191
- isPartial || (prev=Object.create(null));
23192
- }
23193
-
23194
- reset();
23195
-
23196
- return {
23197
- clear: reset,
23198
- has: function (key) {
23199
- return curr[key] !== void 0 || prev[key] !== void 0;
23200
- },
23201
- get: function (key) {
23202
- var val = curr[key];
23203
- if (val !== void 0) return val;
23204
- if ((val=prev[key]) !== void 0) {
23205
- keep(key, val);
23206
- return val;
23207
- }
23208
- },
23209
- set: function (key, value) {
23210
- if (curr[key] !== void 0) {
23211
- curr[key] = value;
23212
- } else {
23213
- keep(key, value);
23214
- }
23215
- }
23216
- };
23217
- }
23218
-
23219
23045
  class GlobalScope extends Scope {
23220
23046
  constructor() {
23221
23047
  super();
@@ -23232,7 +23058,7 @@ class GlobalScope extends Scope {
23232
23058
  }
23233
23059
  }
23234
23060
 
23235
- function resolveIdViaPlugins(source, importer, pluginDriver, moduleLoaderResolveId, skip, customOptions, isEntry, attributes, importerAttributes) {
23061
+ function resolveIdViaPlugins(source, importer, pluginDriver, moduleLoaderResolveId, skip, customOptions, isEntry, attributes, importerAttributes, importerRawId, inputOptions) {
23236
23062
  let skipped = null;
23237
23063
  let replaceContext = null;
23238
23064
  if (skip) {
@@ -23244,39 +23070,52 @@ function resolveIdViaPlugins(source, importer, pluginDriver, moduleLoaderResolve
23244
23070
  }
23245
23071
  replaceContext = (pluginContext, plugin) => ({
23246
23072
  ...pluginContext,
23247
- resolve: (source, importer, { attributes, custom, isEntry, skipSelf, importerAttributes } = parseAst_js.BLANK) => {
23073
+ resolve: (source, importer, { attributes, custom, importerAttributes: deprecatedImporterAttributes, isEntry, skipSelf } = parseAst_js.BLANK) => {
23248
23074
  skipSelf ??= true;
23075
+ const { id: importerId, attributes: importerAttributes, rawId: importerRawId } = importer
23076
+ ? getNormalizedImporter(importer, deprecatedImporterAttributes, plugin.name, inputOptions)
23077
+ : parseAst_js.BLANK;
23249
23078
  if (skipSelf &&
23250
23079
  skip.findIndex(skippedCall => {
23251
23080
  return (skippedCall.plugin === plugin &&
23252
23081
  skippedCall.source === source &&
23253
- skippedCall.importer === importer);
23082
+ skippedCall.importer === importerId);
23254
23083
  }) !== -1) {
23255
23084
  // This means that the plugin recursively called itself
23256
23085
  // Thus returning Promise.resolve(null) in purpose of fallback to default behavior of `resolveId` plugin hook.
23257
23086
  return Promise.resolve(null);
23258
23087
  }
23259
- return moduleLoaderResolveId(source, importer, custom, isEntry, attributes || parseAst_js.EMPTY_OBJECT, importerAttributes, skipSelf ? [...skip, { importer, plugin, source }] : skip);
23088
+ return moduleLoaderResolveId(source, importerId, custom, isEntry, attributes || parseAst_js.EMPTY_OBJECT, importerAttributes || parseAst_js.EMPTY_OBJECT, importerRawId, skipSelf ? [...skip, { importer: importerId, plugin, source }] : skip);
23260
23089
  }
23261
23090
  });
23262
23091
  }
23263
- return pluginDriver.hookFirstAndGetPlugin('resolveId', [source, importer, { attributes, custom: customOptions, importerAttributes, isEntry }], replaceContext, skipped);
23092
+ return pluginDriver.hookFirstAndGetPlugin('resolveId', [
23093
+ source,
23094
+ importer,
23095
+ {
23096
+ attributes,
23097
+ custom: customOptions,
23098
+ importerAttributes: importerAttributes || parseAst_js.EMPTY_OBJECT,
23099
+ importerRawId,
23100
+ isEntry
23101
+ }
23102
+ ], replaceContext, skipped);
23264
23103
  }
23265
23104
 
23266
- async function resolveId(source, importer, preserveSymlinks, pluginDriver, moduleLoaderResolveId, skip, customOptions, isEntry, attributes, importerAttributes, fs) {
23267
- const pluginResult = await resolveIdViaPlugins(source, importer, pluginDriver, moduleLoaderResolveId, skip, customOptions, isEntry, attributes, importerAttributes);
23105
+ async function resolveId(source, importer, pluginDriver, moduleLoaderResolveId, skip, customOptions, isEntry, attributes, importerAttributes, importerRawId, inputOptions) {
23106
+ const pluginResult = await resolveIdViaPlugins(source, importer, pluginDriver, moduleLoaderResolveId, skip, customOptions, isEntry, attributes, importerAttributes, importerRawId, inputOptions);
23268
23107
  if (pluginResult != null) {
23269
23108
  const [resolveIdResult, plugin] = pluginResult;
23270
- if (typeof resolveIdResult === 'object' && !resolveIdResult.resolvedBy) {
23109
+ if (typeof resolveIdResult === 'string') {
23271
23110
  return {
23272
- ...resolveIdResult,
23111
+ id: resolveIdResult,
23273
23112
  resolvedBy: plugin.name
23274
23113
  };
23275
23114
  }
23276
- if (typeof resolveIdResult === 'string') {
23115
+ if (typeof resolveIdResult === 'object') {
23277
23116
  return {
23278
- id: resolveIdResult,
23279
- resolvedBy: plugin.name
23117
+ ...resolveIdResult,
23118
+ resolvedBy: resolveIdResult.resolvedBy || plugin.name
23280
23119
  };
23281
23120
  }
23282
23121
  return resolveIdResult;
@@ -23289,7 +23128,7 @@ async function resolveId(source, importer, preserveSymlinks, pluginDriver, modul
23289
23128
  // absolute path is created. Absolute importees therefore shortcircuit the
23290
23129
  // resolve call and require no special handing on our part.
23291
23130
  // See https://nodejs.org/api/path.html#path_path_resolve_paths
23292
- return addJsExtensionIfNecessary(importer ? path.resolve(path.dirname(importer), source) : path.resolve(source), preserveSymlinks, fs);
23131
+ return addJsExtensionIfNecessary(importer ? sp.resolve(sp.dirname(importer), source) : sp.resolve(source), inputOptions.preserveSymlinks, inputOptions.fs);
23293
23132
  }
23294
23133
  async function addJsExtensionIfNecessary(file, preserveSymlinks, fs) {
23295
23134
  return ((await findFile(file, preserveSymlinks, fs)) ??
@@ -23303,8 +23142,8 @@ async function findFile(file, preserveSymlinks, fs) {
23303
23142
  return await findFile(await fs.realpath(file), preserveSymlinks, fs);
23304
23143
  if ((preserveSymlinks && stats.isSymbolicLink()) || stats.isFile()) {
23305
23144
  // check case
23306
- const name = path.basename(file);
23307
- const files = await fs.readdir(path.dirname(file));
23145
+ const name = sp.basename(file);
23146
+ const files = await fs.readdir(sp.dirname(file));
23308
23147
  if (files.includes(name))
23309
23148
  return file;
23310
23149
  }
@@ -23348,7 +23187,7 @@ async function transform(source, module, pluginDriver, options) {
23348
23187
  return previousCode;
23349
23188
  }
23350
23189
  if (result.attributes) {
23351
- parseAst_js.warnDeprecation('Returning attributes from the "transform" hook is forbidden.', parseAst_js.URL_TRANSFORM, false, options);
23190
+ parseAst_js.warnDeprecation('Returning attributes from the "transform" hook is deprecated.', parseAst_js.URL_TRANSFORM, true, options);
23352
23191
  }
23353
23192
  ({ code, map, ast } = result);
23354
23193
  }
@@ -23380,7 +23219,8 @@ async function transform(source, module, pluginDriver, options) {
23380
23219
  currentSource,
23381
23220
  id,
23382
23221
  {
23383
- attributes: module.info.attributes
23222
+ attributes: module.info.attributes,
23223
+ rawId: module.info.rawId
23384
23224
  }
23385
23225
  ], transformReducer, (pluginContext, plugin) => {
23386
23226
  pluginName = plugin.name;
@@ -23434,10 +23274,12 @@ async function transform(source, module, pluginDriver, options) {
23434
23274
  return parseAst_js.error(parseAst_js.logPluginError(error_, pluginName, { hook: 'transform', id }));
23435
23275
  }
23436
23276
  if (!customTransformCache && // files emitted by a transform hook need to be emitted again if the hook is skipped
23437
- emittedFiles.length > 0)
23277
+ emittedFiles.length > 0) {
23438
23278
  module.transformFiles = emittedFiles;
23279
+ }
23280
+ const astBuffer = ast ? parseAst_js.serializeAst(ast) : await native_js.parseAsync(code, false, options.jsx !== false);
23439
23281
  return {
23440
- ast,
23282
+ astBuffer,
23441
23283
  code,
23442
23284
  customTransformCache,
23443
23285
  originalCode,
@@ -23461,20 +23303,24 @@ class ModuleLoader {
23461
23303
  this.latestLoadModulesPromise = Promise.resolve();
23462
23304
  this.moduleLoadPromises = new Map();
23463
23305
  this.modulesWithLoadedDependencies = new Set();
23464
- this.resolveId = async (source, importer, customOptions, isEntry, attributes, importerAttributes, skip = null) => this.getResolvedIdWithDefaults(this.getNormalizedResolvedIdWithoutDefaults(this.options.external(source, importer, false)
23306
+ this.resolveId = async (source, importer, customOptions, isEntry, attributes, importerAttributes, importerRawId, skip = null) => this.getResolvedIdWithDefaults(this.getNormalizedResolvedIdWithoutDefaults(this.options.external(source, importer, false, {
23307
+ attributes,
23308
+ importerAttributes,
23309
+ importerRawId
23310
+ })
23465
23311
  ? false
23466
- : await resolveId(source, importer, this.options.preserveSymlinks, this.pluginDriver, this.resolveId, skip, customOptions, typeof isEntry === 'boolean' ? isEntry : !importer, attributes, importerAttributes, this.options.fs), importer, source), attributes);
23312
+ : await resolveId(source, importer, this.pluginDriver, this.resolveId, skip, customOptions, typeof isEntry === 'boolean' ? isEntry : !importer, attributes, importerAttributes, importerRawId, this.options), importer, source, attributes, importerAttributes, importerRawId), attributes);
23467
23313
  this.hasModuleSideEffects = options.treeshake
23468
23314
  ? options.treeshake.moduleSideEffects
23469
23315
  : () => true;
23470
23316
  }
23471
23317
  async addAdditionalModules(unresolvedModules, isAddForManualChunks) {
23472
- const result = this.extendLoadModulesPromise(Promise.all(unresolvedModules.map(id => this.loadEntryModule(id, false, undefined, null, isAddForManualChunks, undefined))));
23318
+ const result = this.extendLoadModulesPromise(Promise.all(unresolvedModules.map(id => this.loadEntryModule(id, false, undefined, null, isAddForManualChunks))));
23473
23319
  await this.awaitLoadModulesPromise();
23474
23320
  return result;
23475
23321
  }
23476
23322
  async addEntryModules(unresolvedEntryModules, isUserDefined) {
23477
- const newEntryModules = await this.extendLoadModulesPromise(Promise.all(unresolvedEntryModules.map(({ id, importer }) => this.loadEntryModule(id, true, importer, null, undefined, undefined))).then(entryModules => {
23323
+ const newEntryModules = await this.extendLoadModulesPromise(Promise.all(unresolvedEntryModules.map(({ id, importer, attributes }) => this.loadEntryModule(id, true, importer, null, undefined, attributes))).then(entryModules => {
23478
23324
  let shouldReorder = false;
23479
23325
  for (const [index, entryModule] of entryModules.entries()) {
23480
23326
  entryModule.isUserDefinedEntryPoint =
@@ -23498,11 +23344,12 @@ class ModuleLoader {
23498
23344
  newEntryModules
23499
23345
  };
23500
23346
  }
23501
- async emitChunk({ fileName, id, importer, name, implicitlyLoadedAfterOneOf, preserveSignature }) {
23347
+ async emitChunk({ fileName, id, importer, name, implicitlyLoadedAfterOneOf, preserveSignature, attributes }) {
23502
23348
  const unresolvedModule = {
23349
+ attributes,
23503
23350
  fileName: fileName || null,
23504
23351
  id,
23505
- importer,
23352
+ importer: importer && normalizeModuleId(importer),
23506
23353
  name: name || null
23507
23354
  };
23508
23355
  const module = implicitlyLoadedAfterOneOf
@@ -23514,14 +23361,20 @@ class ModuleLoader {
23514
23361
  return module;
23515
23362
  }
23516
23363
  async preloadModule(resolvedId) {
23517
- const module = await this.fetchModule(this.getResolvedIdWithDefaults(resolvedId, parseAst_js.EMPTY_OBJECT), undefined, false, resolvedId.resolveDependencies ? RESOLVE_DEPENDENCIES : true);
23364
+ const module = await this.fetchModule({
23365
+ ...this.getResolvedIdWithDefaults(resolvedId, parseAst_js.EMPTY_OBJECT),
23366
+ rawId: resolvedId.rawId
23367
+ }, undefined, false, resolvedId.resolveDependencies ? RESOLVE_DEPENDENCIES : true);
23518
23368
  return module.info;
23519
23369
  }
23520
23370
  addEntryWithImplicitDependants(unresolvedModule, implicitlyLoadedAfter) {
23521
- return this.extendLoadModulesPromise(this.loadEntryModule(unresolvedModule.id, false, unresolvedModule.importer, null, undefined, undefined).then(async (entryModule) => {
23371
+ return this.extendLoadModulesPromise(this.loadEntryModule(unresolvedModule.id, false, unresolvedModule.importer, null).then(async (entryModule) => {
23522
23372
  addChunkNamesToModule(entryModule, unresolvedModule, false);
23523
23373
  if (!entryModule.info.isEntry) {
23524
- const implicitlyLoadedAfterModules = await Promise.all(implicitlyLoadedAfter.map(id => this.loadEntryModule(id, false, unresolvedModule.importer, entryModule.id, undefined, undefined)));
23374
+ const implicitlyLoadedAfterModules = await Promise.all(implicitlyLoadedAfter.map(id => {
23375
+ const normalizedId = normalizeModuleIdToObject(id);
23376
+ return this.loadEntryModule(normalizedId.id, false, unresolvedModule.importer, entryModule.id, undefined, normalizedId.attributes);
23377
+ }));
23525
23378
  // We need to check again if this is still an entry module as these
23526
23379
  // changes need to be performed atomically to avoid race conditions
23527
23380
  // if the same module is re-emitted as an entry module.
@@ -23545,16 +23398,16 @@ class ModuleLoader {
23545
23398
  source = await this.graph.fileOperationQueue.run(async () => {
23546
23399
  const content = await this.pluginDriver.hookFirst('load', [
23547
23400
  id,
23548
- { attributes: module.info.attributes }
23401
+ { attributes: module.info.attributes, rawId: module.info.rawId }
23549
23402
  ]);
23550
23403
  if (content !== null) {
23551
23404
  if (typeof content === 'object' && content.attributes) {
23552
- parseAst_js.warnDeprecation('Returning attributes from the "load" hook is forbidden.', parseAst_js.URL_LOAD, false, this.options);
23405
+ parseAst_js.warnDeprecation('Returning attributes from the "load" hook is deprecated.', parseAst_js.URL_LOAD, true, this.options);
23553
23406
  }
23554
23407
  return content;
23555
23408
  }
23556
- this.graph.watchFiles[id] = true;
23557
- return (await this.options.fs.readFile(id, { encoding: 'utf8' }));
23409
+ this.graph.watchFiles[module.info.rawId] = true;
23410
+ return (await this.options.fs.readFile(module.info.rawId, { encoding: 'utf8' }));
23558
23411
  });
23559
23412
  }
23560
23413
  catch (error_) {
@@ -23583,12 +23436,13 @@ class ModuleLoader {
23583
23436
  module.updateOptions(cachedModule);
23584
23437
  if (await this.pluginDriver.hookFirst('shouldTransformCachedModule', [
23585
23438
  {
23586
- ast: cachedModule.ast,
23439
+ ast: parseAst_js.deserializeLazyAst(cachedModule.astBuffer),
23587
23440
  attributes: cachedModule.attributes,
23588
23441
  code: cachedModule.code,
23589
23442
  id: cachedModule.id,
23590
23443
  meta: cachedModule.meta,
23591
23444
  moduleSideEffects: cachedModule.moduleSideEffects,
23445
+ rawId: cachedModule.rawId,
23592
23446
  resolvedSources: cachedModule.resolvedIds,
23593
23447
  syntheticNamedExports: cachedModule.syntheticNamedExports
23594
23448
  }
@@ -23649,19 +23503,16 @@ class ModuleLoader {
23649
23503
  // Otherwise, if the module does not exist, it waits for the module and all
23650
23504
  // its dependencies to be loaded.
23651
23505
  // Otherwise, it returns immediately.
23652
- async fetchModule({ attributes, id, meta, moduleSideEffects, syntheticNamedExports }, importer, isEntry, isPreload) {
23506
+ async fetchModule({ attributes, id, rawId, meta, moduleSideEffects, syntheticNamedExports }, importer, isEntry, isPreload) {
23653
23507
  const existingModule = this.modulesById.get(id);
23654
23508
  if (existingModule instanceof Module) {
23655
- if (importer && doAttributesDiffer(attributes, existingModule.info.attributes)) {
23656
- this.options.onLog(parseAst_js.LOGLEVEL_WARN, parseAst_js.logInconsistentImportAttributes(existingModule.info.attributes, attributes, id, importer));
23657
- }
23658
23509
  await this.handleExistingModule(existingModule, isEntry, isPreload);
23659
23510
  return existingModule;
23660
23511
  }
23661
23512
  if (existingModule instanceof ExternalModule) {
23662
23513
  return parseAst_js.error(parseAst_js.logExternalModulesCannotBeTransformedToModules(existingModule.id));
23663
23514
  }
23664
- const module = new Module(this.graph, id, this.options, isEntry, moduleSideEffects, syntheticNamedExports, meta, attributes);
23515
+ const module = new Module(this.graph, id, rawId, this.options, isEntry, moduleSideEffects, syntheticNamedExports, meta, attributes);
23665
23516
  this.modulesById.set(id, module);
23666
23517
  const loadPromise = this.addModuleSource(id, importer, module).then(() => [
23667
23518
  this.getResolveStaticDependencyPromises(module),
@@ -23697,18 +23548,15 @@ class ModuleLoader {
23697
23548
  }
23698
23549
  fetchResolvedDependency(source, importer, resolvedId) {
23699
23550
  if (resolvedId.external) {
23700
- const { attributes, external, id, moduleSideEffects, meta } = resolvedId;
23551
+ const { attributes, external, id, rawId, moduleSideEffects, meta } = resolvedId;
23701
23552
  let externalModule = this.modulesById.get(id);
23702
23553
  if (!externalModule) {
23703
- externalModule = new ExternalModule(this.options, id, moduleSideEffects, meta, external !== 'absolute' && parseAst_js.isAbsolute(id), attributes);
23554
+ externalModule = new ExternalModule(this.options, id, rawId, moduleSideEffects, meta, external !== 'absolute' && parseAst_js.isAbsolute(id), attributes);
23704
23555
  this.modulesById.set(id, externalModule);
23705
23556
  }
23706
23557
  else if (!(externalModule instanceof ExternalModule)) {
23707
23558
  return parseAst_js.error(parseAst_js.logInternalIdCannotBeExternal(source, importer));
23708
23559
  }
23709
- else if (doAttributesDiffer(externalModule.info.attributes, attributes)) {
23710
- this.options.onLog(parseAst_js.LOGLEVEL_WARN, parseAst_js.logInconsistentImportAttributes(externalModule.info.attributes, attributes, source, importer));
23711
- }
23712
23560
  return Promise.resolve(externalModule);
23713
23561
  }
23714
23562
  return this.fetchModule(resolvedId, importer, false, false);
@@ -23731,11 +23579,16 @@ class ModuleLoader {
23731
23579
  }
23732
23580
  }
23733
23581
  }
23734
- getNormalizedResolvedIdWithoutDefaults(resolveIdResult, importer, source) {
23582
+ getNormalizedResolvedIdWithoutDefaults(resolveIdResult, importer, source, attributes, importerAttributes, importerRawId) {
23735
23583
  const { makeAbsoluteExternalsRelative } = this.options;
23736
23584
  if (resolveIdResult) {
23737
23585
  if (typeof resolveIdResult === 'object') {
23738
- const external = resolveIdResult.external || this.options.external(resolveIdResult.id, importer, true);
23586
+ const external = resolveIdResult.external ||
23587
+ this.options.external(resolveIdResult.id, importer, true, {
23588
+ attributes: resolveIdResult.attributes || attributes,
23589
+ importerAttributes,
23590
+ importerRawId
23591
+ });
23739
23592
  return {
23740
23593
  ...resolveIdResult,
23741
23594
  external: external &&
@@ -23746,7 +23599,11 @@ class ModuleLoader {
23746
23599
  'absolute')
23747
23600
  };
23748
23601
  }
23749
- const external = this.options.external(resolveIdResult, importer, true);
23602
+ const external = this.options.external(resolveIdResult, importer, true, {
23603
+ attributes,
23604
+ importerAttributes,
23605
+ importerRawId
23606
+ });
23750
23607
  return {
23751
23608
  external: external &&
23752
23609
  (isNotAbsoluteExternal(resolveIdResult, source, makeAbsoluteExternalsRelative) ||
@@ -23759,7 +23616,12 @@ class ModuleLoader {
23759
23616
  const id = makeAbsoluteExternalsRelative
23760
23617
  ? normalizeRelativeExternalId(source, importer)
23761
23618
  : source;
23762
- if (resolveIdResult !== false && !this.options.external(id, importer, true)) {
23619
+ if (resolveIdResult !== false &&
23620
+ !this.options.external(id, importer, true, {
23621
+ attributes,
23622
+ importerAttributes,
23623
+ importerRawId
23624
+ })) {
23763
23625
  return null;
23764
23626
  }
23765
23627
  return {
@@ -23772,6 +23634,7 @@ class ModuleLoader {
23772
23634
  const resolvedId = await this.resolveDynamicImport(module, dynamicImport.argument, module.id, getAttributesFromImportExpression(dynamicImport.node));
23773
23635
  if (!resolvedId || typeof resolvedId === 'string') {
23774
23636
  dynamicImport.node.shouldIncludeDynamicAttributes = true;
23637
+ return [dynamicImport, resolvedId];
23775
23638
  }
23776
23639
  else {
23777
23640
  dynamicImport.node.shouldIncludeDynamicAttributes = !!resolvedId.external;
@@ -23781,12 +23644,19 @@ class ModuleLoader {
23781
23644
  });
23782
23645
  }
23783
23646
  getResolveStaticDependencyPromises(module) {
23784
- return Array.from(module.sourcesWithAttributes, async ([source, attributes]) => [
23785
- source,
23786
- (module.resolvedIds[source] =
23787
- module.resolvedIds[source] ||
23788
- this.handleInvalidResolvedId(await this.resolveId(source, module.id, parseAst_js.EMPTY_OBJECT, false, attributes, module.info.attributes), source, module.id, attributes))
23789
- ]);
23647
+ return Array.from(module.sourcesWithAttributesList)
23648
+ .map(([source, attributesList]) => attributesList.map(attributes => [source, attributes]))
23649
+ .flat()
23650
+ .map(async ([source, attributes]) => {
23651
+ const id = generateIdByRawIdAndAttributes(source, attributes);
23652
+ const existingResolution = module.resolvedIds[id];
23653
+ if (existingResolution) {
23654
+ return [source, existingResolution];
23655
+ }
23656
+ const resolution = this.toModuleResolvedId(this.handleInvalidResolvedId(await this.resolveId(source, module.id, parseAst_js.EMPTY_OBJECT, false, attributes, module.info.attributes, module.info.rawId), source, module.id, attributes));
23657
+ module.resolvedIds[id] = resolution;
23658
+ return [source, resolution];
23659
+ });
23790
23660
  }
23791
23661
  getResolvedIdWithDefaults(resolvedId, attributes) {
23792
23662
  if (!resolvedId) {
@@ -23843,30 +23713,42 @@ class ModuleLoader {
23843
23713
  }
23844
23714
  return resolvedId;
23845
23715
  }
23846
- async loadEntryModule(unresolvedId, isEntry, importer, implicitlyLoadedBefore, isLoadForManualChunks = false, importerAttributes) {
23847
- const resolveIdResult = await resolveId(unresolvedId, importer, this.options.preserveSymlinks, this.pluginDriver, this.resolveId, null, parseAst_js.EMPTY_OBJECT, true, parseAst_js.EMPTY_OBJECT, importerAttributes, this.options.fs);
23716
+ async loadEntryModule(unresolvedId, isEntry, importer, implicitlyLoadedBefore, isLoadForManualChunks = false, attributes = parseAst_js.EMPTY_OBJECT) {
23717
+ const implicitlyLoadedBeforeId = implicitlyLoadedBefore
23718
+ ? normalizeModuleId(implicitlyLoadedBefore)
23719
+ : null;
23720
+ const { attributes: importerAttributes, rawId: importerRawId, id: importerId } = importer ? normalizeModuleIdToObject(importer) : parseAst_js.BLANK;
23721
+ const resolveIdResult = await resolveId(unresolvedId, importerId, this.pluginDriver, this.resolveId, null, parseAst_js.EMPTY_OBJECT, true, attributes, importerAttributes, importerRawId, this.options);
23848
23722
  if (resolveIdResult == null) {
23849
- return parseAst_js.error(implicitlyLoadedBefore === null
23723
+ return parseAst_js.error(implicitlyLoadedBeforeId === null
23850
23724
  ? parseAst_js.logUnresolvedEntry(unresolvedId)
23851
- : parseAst_js.logUnresolvedImplicitDependant(unresolvedId, implicitlyLoadedBefore));
23725
+ : parseAst_js.logUnresolvedImplicitDependant(unresolvedId, implicitlyLoadedBeforeId));
23852
23726
  }
23853
23727
  const isExternalModules = typeof resolveIdResult === 'object' && resolveIdResult.external;
23854
23728
  if (resolveIdResult === false || isExternalModules) {
23855
- return parseAst_js.error(implicitlyLoadedBefore === null
23729
+ return parseAst_js.error(implicitlyLoadedBeforeId === null
23856
23730
  ? isExternalModules && isLoadForManualChunks
23857
23731
  ? parseAst_js.logExternalModulesCannotBeIncludedInManualChunks(unresolvedId)
23858
23732
  : parseAst_js.logEntryCannotBeExternal(unresolvedId)
23859
- : parseAst_js.logImplicitDependantCannotBeExternal(unresolvedId, implicitlyLoadedBefore));
23733
+ : parseAst_js.logImplicitDependantCannotBeExternal(unresolvedId, implicitlyLoadedBeforeId));
23860
23734
  }
23861
- return this.fetchModule(this.getResolvedIdWithDefaults(typeof resolveIdResult === 'object'
23735
+ return this.fetchModule(this.toModuleResolvedId(this.getResolvedIdWithDefaults(typeof resolveIdResult === 'object'
23862
23736
  ? resolveIdResult
23863
- : { id: resolveIdResult }, parseAst_js.EMPTY_OBJECT), undefined, isEntry, false);
23737
+ : { id: resolveIdResult }, attributes)), undefined, isEntry, false);
23738
+ }
23739
+ toModuleResolvedId(resolveIdResult) {
23740
+ const { id, attributes } = resolveIdResult;
23741
+ return {
23742
+ ...resolveIdResult,
23743
+ id: generateIdByRawIdAndAttributes(id, attributes),
23744
+ rawId: id
23745
+ };
23864
23746
  }
23865
23747
  async resolveDynamicImport(module, specifier, importer, attributes) {
23866
23748
  const resolution = await this.pluginDriver.hookFirst('resolveDynamicImport', [
23867
23749
  specifier,
23868
23750
  importer,
23869
- { attributes, importerAttributes: module.info.attributes }
23751
+ { attributes, importerAttributes: module.info.attributes, importerRawId: module.info.rawId }
23870
23752
  ]);
23871
23753
  if (typeof specifier !== 'string') {
23872
23754
  if (typeof resolution === 'string') {
@@ -23875,26 +23757,26 @@ class ModuleLoader {
23875
23757
  if (!resolution) {
23876
23758
  return null;
23877
23759
  }
23878
- return this.getResolvedIdWithDefaults(resolution, attributes);
23760
+ return this.toModuleResolvedId(this.getResolvedIdWithDefaults(resolution, attributes));
23879
23761
  }
23880
23762
  if (resolution == null) {
23881
- const existingResolution = module.resolvedIds[specifier];
23763
+ const id = generateIdByRawIdAndAttributes(specifier, attributes);
23764
+ const existingResolution = module.resolvedIds[id];
23882
23765
  if (existingResolution) {
23883
- if (doAttributesDiffer(existingResolution.attributes, attributes)) {
23884
- this.options.onLog(parseAst_js.LOGLEVEL_WARN, parseAst_js.logInconsistentImportAttributes(existingResolution.attributes, attributes, specifier, importer));
23885
- }
23886
23766
  return existingResolution;
23887
23767
  }
23888
- return (module.resolvedIds[specifier] = this.handleInvalidResolvedId(await this.resolveId(specifier, module.id, parseAst_js.EMPTY_OBJECT, false, attributes, module.info.attributes), specifier, module.id, attributes));
23768
+ const resolution = this.handleInvalidResolvedId(await this.resolveId(specifier, module.id, parseAst_js.EMPTY_OBJECT, false, attributes, module.info.attributes, module.info.rawId), specifier, module.id, attributes);
23769
+ module.resolvedIds[id] = this.toModuleResolvedId(resolution);
23770
+ return module.resolvedIds[id];
23889
23771
  }
23890
- return this.handleInvalidResolvedId(this.getResolvedIdWithDefaults(this.getNormalizedResolvedIdWithoutDefaults(resolution, importer, specifier), attributes), specifier, importer, attributes);
23772
+ return this.toModuleResolvedId(this.handleInvalidResolvedId(this.getResolvedIdWithDefaults(this.getNormalizedResolvedIdWithoutDefaults(resolution, importer, specifier, attributes, module.info.attributes, module.info.rawId), attributes), specifier, importer, attributes));
23891
23773
  }
23892
23774
  }
23893
23775
  function normalizeRelativeExternalId(source, importer) {
23894
23776
  return parseAst_js.isRelative(source)
23895
23777
  ? importer
23896
- ? path.resolve(importer, '..', source)
23897
- : path.resolve(source)
23778
+ ? sp.resolve(importer, '..', source)
23779
+ : sp.resolve(source)
23898
23780
  : source;
23899
23781
  }
23900
23782
  function addChunkNamesToModule(module, { fileName, name }, isUserDefined) {
@@ -23968,7 +23850,6 @@ function normalizeEntryModules(entryModules) {
23968
23850
  class Graph {
23969
23851
  constructor(options, registerWatchHooks) {
23970
23852
  this.options = options;
23971
- this.astLru = flru(5);
23972
23853
  this.cachedModules = new Map();
23973
23854
  this.deoptimizationTracker = new EntityPathTracker();
23974
23855
  this.entryModules = [];
@@ -23983,7 +23864,8 @@ class Graph {
23983
23864
  this.implicitEntryModules = [];
23984
23865
  this.modules = [];
23985
23866
  this.getModuleInfo = (moduleId) => {
23986
- const foundModule = this.modulesById.get(moduleId);
23867
+ const normalizedModuleId = normalizeModuleId(moduleId);
23868
+ const foundModule = this.modulesById.get(normalizedModuleId);
23987
23869
  if (!foundModule)
23988
23870
  return null;
23989
23871
  return foundModule.info;
@@ -24318,7 +24200,7 @@ const getModuleContext = (config, context) => {
24318
24200
  if (configModuleContext) {
24319
24201
  const contextByModuleId = Object.create(null);
24320
24202
  for (const [key, moduleContext] of Object.entries(configModuleContext)) {
24321
- contextByModuleId[path.resolve(key)] = moduleContext;
24203
+ contextByModuleId[sp.resolve(key)] = moduleContext;
24322
24204
  }
24323
24205
  return id => contextByModuleId[id] ?? context;
24324
24206
  }
@@ -24409,7 +24291,7 @@ async function normalizeOutputOptions(config, inputOptions, unsetInputOptions) {
24409
24291
  globals: config.globals || {},
24410
24292
  hashCharacters: config.hashCharacters ?? 'base64',
24411
24293
  hoistTransitiveImports: config.hoistTransitiveImports ?? true,
24412
- importAttributesKey: config.importAttributesKey ?? 'assert',
24294
+ importAttributesKey: getImportAttributesKey(config, inputOptions),
24413
24295
  indent: getIndent(config, compact),
24414
24296
  inlineDynamicImports,
24415
24297
  interop: getInterop(config),
@@ -24418,7 +24300,7 @@ async function normalizeOutputOptions(config, inputOptions, unsetInputOptions) {
24418
24300
  minifyInternalExports: getMinifyInternalExports(config, format, compact),
24419
24301
  name: config.name,
24420
24302
  noConflict: config.noConflict || false,
24421
- onlyExplicitManualChunks: config.onlyExplicitManualChunks || false,
24303
+ onlyExplicitManualChunks: config.onlyExplicitManualChunks ?? typeof config.manualChunks === 'function',
24422
24304
  outro: getAddon(config, 'outro'),
24423
24305
  paths: config.paths || {},
24424
24306
  plugins: await normalizePluginOption(config.plugins),
@@ -24513,7 +24395,7 @@ const getPreserveModulesRoot = (config) => {
24513
24395
  if (preserveModulesRoot === null || preserveModulesRoot === undefined) {
24514
24396
  return undefined;
24515
24397
  }
24516
- return path.resolve(preserveModulesRoot);
24398
+ return sp.resolve(preserveModulesRoot);
24517
24399
  };
24518
24400
  const getAmd = (config) => {
24519
24401
  const mergedOption = {
@@ -24590,6 +24472,12 @@ const getGeneratedCode = (config) => {
24590
24472
  symbols: configWithPreset.symbols === true
24591
24473
  };
24592
24474
  };
24475
+ const getImportAttributesKey = (config, inputOptions) => {
24476
+ if (config.importAttributesKey != undefined) {
24477
+ parseAst_js.warnDeprecation(`The "output.importAttributesKey" option is deprecated and will be removed in a future version of Rollup. Only use it if you need to support environments that do not understand the "with" keyword.`, parseAst_js.URL_OUTPUT_IMPORTATTRIBUTESKEY, false, inputOptions);
24478
+ }
24479
+ return config.importAttributesKey ?? 'with';
24480
+ };
24593
24481
  const getIndent = (config, compact) => {
24594
24482
  if (compact) {
24595
24483
  return '';
@@ -24835,9 +24723,9 @@ function getSortingFileType(file) {
24835
24723
  return SortingFileType.SECONDARY_CHUNK;
24836
24724
  }
24837
24725
  async function writeOutputFile(outputFile, outputOptions, { fs: { mkdir, writeFile } }) {
24838
- const fileName = path.resolve(outputOptions.dir || path.dirname(outputOptions.file), outputFile.fileName);
24726
+ const fileName = sp.resolve(outputOptions.dir || sp.dirname(outputOptions.file), outputFile.fileName);
24839
24727
  // 'recursive: true' does not throw if the folder structure, or parts of it, already exist
24840
- await mkdir(path.dirname(fileName), { recursive: true });
24728
+ await mkdir(sp.dirname(fileName), { recursive: true });
24841
24729
  return writeFile(fileName, outputFile.type === 'asset' ? outputFile.source : outputFile.code);
24842
24730
  }
24843
24731
  /**
@@ -24856,8 +24744,6 @@ exports.createFilter = createFilter;
24856
24744
  exports.cyan = cyan;
24857
24745
  exports.defineConfig = defineConfig;
24858
24746
  exports.ensureArray = ensureArray$1;
24859
- exports.getAugmentedNamespace = getAugmentedNamespace;
24860
- exports.getDefaultExportFromCjs = getDefaultExportFromCjs;
24861
24747
  exports.getNewArray = getNewArray;
24862
24748
  exports.getOrCreate = getOrCreate;
24863
24749
  exports.gray = gray;