@atlaspack/packager-js 2.14.5-dev.73 → 2.14.5-dev.95

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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,52 @@
1
1
  # @atlaspack/packager-js
2
2
 
3
+ ## 2.16.1
4
+
5
+ ### Patch Changes
6
+
7
+ - Updated dependencies [[`644b157`](https://github.com/atlassian-labs/atlaspack/commit/644b157dee72a871acc2d0facf0b87b8eea51956)]:
8
+ - @atlaspack/feature-flags@2.18.2
9
+ - @atlaspack/utils@2.15.2
10
+ - @atlaspack/types@2.15.4
11
+ - @atlaspack/plugin@2.14.14
12
+
13
+ ## 2.16.0
14
+
15
+ ### Minor Changes
16
+
17
+ - [#644](https://github.com/atlassian-labs/atlaspack/pull/644) [`fc59be7`](https://github.com/atlassian-labs/atlaspack/commit/fc59be71f43dd87d3e6fb7f3f50c424d2b664858) Thanks [@marcins](https://github.com/marcins)! - Removes the unused unstable `forceSkipWrapAssets` feature
18
+
19
+ ### Patch Changes
20
+
21
+ - [#633](https://github.com/atlassian-labs/atlaspack/pull/633) [`26aa9c5`](https://github.com/atlassian-labs/atlaspack/commit/26aa9c599d2be45ce1438a74c5fa22f39b9b554b) Thanks [@sbhuiyan-atlassian](https://github.com/sbhuiyan-atlassian)! - Ported various HMR changes from Parcel
22
+
23
+ - Updated dependencies [[`26aa9c5`](https://github.com/atlassian-labs/atlaspack/commit/26aa9c599d2be45ce1438a74c5fa22f39b9b554b), [`0501255`](https://github.com/atlassian-labs/atlaspack/commit/05012550da35b05ce7d356a8cc29311e7f9afdca)]:
24
+ - @atlaspack/feature-flags@2.18.1
25
+ - @atlaspack/types@2.15.3
26
+ - @atlaspack/utils@2.15.1
27
+ - @atlaspack/plugin@2.14.13
28
+
29
+ ## 2.15.0
30
+
31
+ ### Minor Changes
32
+
33
+ - [#627](https://github.com/atlassian-labs/atlaspack/pull/627) [`85c52d3`](https://github.com/atlassian-labs/atlaspack/commit/85c52d3f7717b3c84a118d18ab98cfbfd71dcbd2) Thanks [@benjervis](https://github.com/benjervis)! - Expands the situations where scope hoisting may be applied to include assets with no dependencies, regardless of whether if they have a wrapped ancestor.
34
+
35
+ Can be enabled with the `applyScopeHoistingImprovement` feature flag.
36
+
37
+ ### Patch Changes
38
+
39
+ - [#632](https://github.com/atlassian-labs/atlaspack/pull/632) [`10fbcfb`](https://github.com/atlassian-labs/atlaspack/commit/10fbcfbfa49c7a83da5d7c40983e36e87f524a75) Thanks [@marcins](https://github.com/marcins)! - Added a new feature flag `inlineConstOptimisationFix` which when enabled changes the behaviour for output of constant modules. This fixes two issues with constant modules:
40
+
41
+ - Previously constant modules, if they needed a namespace anywhere, would have a namespace everywhere, with this change they only have a namespace in the bundles where needed.
42
+ - Previously in the case of wrapped assets, a constant module dependnecy of that wrapped asset would be rendered after the module - which meant the minifier would not be able to inline the constants safely. With this flag all constant modules are rendered at the top of the bundle.
43
+
44
+ - Updated dependencies [[`10fbcfb`](https://github.com/atlassian-labs/atlaspack/commit/10fbcfbfa49c7a83da5d7c40983e36e87f524a75), [`85c52d3`](https://github.com/atlassian-labs/atlaspack/commit/85c52d3f7717b3c84a118d18ab98cfbfd71dcbd2), [`e39c6cf`](https://github.com/atlassian-labs/atlaspack/commit/e39c6cf05f7e95ce5420dbcea66f401b1cbd397c)]:
45
+ - @atlaspack/feature-flags@2.18.0
46
+ - @atlaspack/utils@2.15.0
47
+ - @atlaspack/types@2.15.2
48
+ - @atlaspack/plugin@2.14.12
49
+
3
50
  ## 2.14.11
4
51
 
5
52
  ### Patch Changes
@@ -18,6 +18,13 @@ function _sourceMap() {
18
18
  };
19
19
  return data;
20
20
  }
21
+ function _featureFlags() {
22
+ const data = require("@atlaspack/feature-flags");
23
+ _featureFlags = function () {
24
+ return data;
25
+ };
26
+ return data;
27
+ }
21
28
  function _assert() {
22
29
  const data = _interopRequireDefault(require("assert"));
23
30
  _assert = function () {
@@ -108,6 +115,17 @@ class DevPackager {
108
115
  deps[specifier] = dep.specifier;
109
116
  }
110
117
  }
118
+ if ((0, _featureFlags().getFeatureFlag)('hmrImprovements')) {
119
+ // Add dependencies for parcelRequire calls added by runtimes
120
+ // so that the HMR runtime can correctly traverse parents.
121
+ let hmrDeps = asset.meta.hmrDeps;
122
+ if (this.options.hmrOptions && Array.isArray(hmrDeps)) {
123
+ for (let id of hmrDeps) {
124
+ (0, _assert().default)(typeof id === 'string');
125
+ deps[id] = id;
126
+ }
127
+ }
128
+ }
111
129
  let {
112
130
  code,
113
131
  mapBuffer
@@ -99,14 +99,12 @@ class ScopeHoistingPackager {
99
99
  needsPrelude = false;
100
100
  usedHelpers = new Set();
101
101
  externalAssets = new Set();
102
- forceSkipWrapAssets = [];
103
- constructor(options, bundleGraph, bundle, parcelRequireName, useAsyncBundleRuntime, forceSkipWrapAssets, logger) {
102
+ constructor(options, bundleGraph, bundle, parcelRequireName, useAsyncBundleRuntime, logger) {
104
103
  this.options = options;
105
104
  this.bundleGraph = bundleGraph;
106
105
  this.bundle = bundle;
107
106
  this.parcelRequireName = parcelRequireName;
108
107
  this.useAsyncBundleRuntime = useAsyncBundleRuntime;
109
- this.forceSkipWrapAssets = forceSkipWrapAssets ?? [];
110
108
  this.logger = logger;
111
109
  let OutputFormat = OUTPUT_FORMATS[this.bundle.env.outputFormat];
112
110
  this.outputFormat = new OutputFormat(this);
@@ -115,7 +113,10 @@ class ScopeHoistingPackager {
115
113
  }
116
114
  async package() {
117
115
  var _sourceMap;
118
- let wrappedAssets = await this.loadAssets();
116
+ let {
117
+ wrapped: wrappedAssets,
118
+ constant: constantAssets
119
+ } = await this.loadAssets();
119
120
  this.buildExportedSymbols();
120
121
 
121
122
  // If building a library, the target is actually another bundler rather
@@ -143,6 +144,14 @@ class ScopeHoistingPackager {
143
144
  res += content + '\n';
144
145
  lineCount += lines + 1;
145
146
  };
147
+ if ((0, _featureFlags().getFeatureFlag)('inlineConstOptimisationFix') || (0, _featureFlags().getFeatureFlag)('applyScopeHoistingImprovement')) {
148
+ // Write out all constant modules used by this bundle
149
+ for (let asset of constantAssets) {
150
+ if (!this.seenAssets.has(asset.id)) {
151
+ processAsset(asset);
152
+ }
153
+ }
154
+ }
146
155
 
147
156
  // Hoist wrapped asset to the top of the bundle to ensure that they are registered
148
157
  // before they are used.
@@ -265,6 +274,7 @@ class ScopeHoistingPackager {
265
274
  maxConcurrent: 32
266
275
  });
267
276
  let wrapped = [];
277
+ let constant = [];
268
278
  this.bundle.traverseAssets(asset => {
269
279
  queue.add(async () => {
270
280
  let [code, map] = await Promise.all([asset.getCode(), this.bundle.env.sourceMap ? asset.getMapBuffer() : null]);
@@ -278,38 +288,64 @@ class ScopeHoistingPackager {
278
288
  if (!asset.meta.isConstantModule || this.bundleGraph.getIncomingDependencies(asset).some(dep => dep.priority === 'lazy')) {
279
289
  this.wrappedAssets.add(asset.id);
280
290
  wrapped.push(asset);
291
+ } else if (((0, _featureFlags().getFeatureFlag)('inlineConstOptimisationFix') || (0, _featureFlags().getFeatureFlag)('applyScopeHoistingImprovement')) && asset.meta.isConstantModule) {
292
+ constant.push(asset);
281
293
  }
282
294
  }
283
295
  });
284
- for (let wrappedAssetRoot of [...wrapped]) {
285
- this.bundle.traverseAssets((asset, _, actions) => {
286
- if (asset === wrappedAssetRoot) {
287
- return;
288
- }
289
- if (this.wrappedAssets.has(asset.id)) {
290
- actions.skipChildren();
291
- return;
292
- }
293
- // This prevents children of a wrapped asset also being wrapped - it's an "unsafe" optimisation
294
- // that should only be used when you know (or think you know) what you're doing.
295
- //
296
- // In particular this can force an async bundle to be scope hoisted where it previously would not be
297
- // due to the entry asset being wrapped.
298
- if (this.forceSkipWrapAssets.length > 0 && this.forceSkipWrapAssets.some(p => p === _path().default.relative(this.options.projectRoot, asset.filePath))) {
299
- this.logger.verbose({
300
- message: `Force skipping wrapping of ${_path().default.relative(this.options.projectRoot, asset.filePath)}`
301
- });
302
- actions.skipChildren();
303
- return;
304
- }
305
- if (!asset.meta.isConstantModule) {
306
- this.wrappedAssets.add(asset.id);
307
- wrapped.push(asset);
308
- }
309
- }, wrappedAssetRoot);
296
+ if ((0, _featureFlags().getFeatureFlag)('applyScopeHoistingImprovement')) {
297
+ // Tracks which assets have been assigned to a wrap group
298
+ let assignedAssets = new Set();
299
+ for (let wrappedAsset of wrapped) {
300
+ this.bundle.traverseAssets((asset, _, actions) => {
301
+ if (asset === wrappedAsset) {
302
+ return;
303
+ }
304
+ if (this.wrappedAssets.has(asset.id)) {
305
+ actions.skipChildren();
306
+ return;
307
+ }
308
+ if (!asset.meta.isConstantModule && (assignedAssets.has(asset) || this.isReExported(asset))) {
309
+ wrapped.push(asset);
310
+ this.wrappedAssets.add(asset.id);
311
+ actions.skipChildren();
312
+ return;
313
+ }
314
+ assignedAssets.add(asset);
315
+ }, wrappedAsset);
316
+ }
317
+ } else {
318
+ for (let wrappedAssetRoot of [...wrapped]) {
319
+ this.bundle.traverseAssets((asset, _, actions) => {
320
+ if (asset === wrappedAssetRoot) {
321
+ return;
322
+ }
323
+ if (this.wrappedAssets.has(asset.id)) {
324
+ actions.skipChildren();
325
+ return;
326
+ }
327
+ if (!asset.meta.isConstantModule) {
328
+ this.wrappedAssets.add(asset.id);
329
+ wrapped.push(asset);
330
+ }
331
+ }, wrappedAssetRoot);
332
+ }
310
333
  }
311
334
  this.assetOutputs = new Map(await queue.run());
312
- return wrapped;
335
+ return {
336
+ wrapped,
337
+ constant
338
+ };
339
+ }
340
+ isReExported(asset) {
341
+ let parentSymbols = this.bundleGraph.getIncomingDependencies(asset).map(dep => this.bundleGraph.getAssetWithDependency(dep)).flatMap(parent => {
342
+ if (parent == null) {
343
+ return [];
344
+ }
345
+ return this.bundleGraph.getExportedSymbols(parent, this.bundle);
346
+ });
347
+ let assetSymbols = this.bundleGraph.getExportedSymbols(asset, this.bundle);
348
+ return assetSymbols.some(assetSymbol => parentSymbols.some(parentSymbol => parentSymbol.symbol === assetSymbol.symbol));
313
349
  }
314
350
  buildExportedSymbols() {
315
351
  if (!this.bundle.env.isLibrary || this.bundle.env.outputFormat !== 'esmodule') {
@@ -489,13 +525,22 @@ class ScopeHoistingPackager {
489
525
  // outside our parcelRequire.register wrapper. This is safe because all
490
526
  // assets referenced by this asset will also be wrapped. Otherwise, inline the
491
527
  // asset content where the import statement was.
492
- if (shouldWrap) {
493
- depContent.push(this.visitAsset(resolved));
528
+ if ((0, _featureFlags().getFeatureFlag)('applyScopeHoistingImprovement')) {
529
+ if (!resolved.meta.isConstantModule && !this.wrappedAssets.has(resolved.id)) {
530
+ let [depCode, depMap, depLines] = this.visitAsset(resolved);
531
+ res = depCode + '\n' + res;
532
+ lines += 1 + depLines;
533
+ map = depMap;
534
+ }
494
535
  } else {
495
- let [depCode, depMap, depLines] = this.visitAsset(resolved);
496
- res = depCode + '\n' + res;
497
- lines += 1 + depLines;
498
- map = depMap;
536
+ if (shouldWrap) {
537
+ depContent.push(this.visitAsset(resolved));
538
+ } else {
539
+ let [depCode, depMap, depLines] = this.visitAsset(resolved);
540
+ res = depCode + '\n' + res;
541
+ lines += 1 + depLines;
542
+ map = depMap;
543
+ }
499
544
  }
500
545
  }
501
546
 
@@ -874,20 +919,26 @@ ${code}
874
919
  // If there's no __esModule flag, and default is a used symbol, we need
875
920
  // to insert an interop helper.
876
921
  let defaultInterop = asset.symbols.hasExportSymbol('*') && usedSymbols.has('default') && !asset.symbols.hasExportSymbol('__esModule');
877
- let usedNamespace =
878
- // If the asset has * in its used symbols, we might need the exports namespace.
879
- // The one case where this isn't true is in ESM library entries, where the only
880
- // dependency on * is the entry dependency. In this case, we will use ESM exports
881
- // instead of the namespace object.
882
- usedSymbols.has('*') && (this.bundle.env.outputFormat !== 'esmodule' || !this.bundle.env.isLibrary || asset !== this.bundle.getMainEntry() || this.bundleGraph.getIncomingDependencies(asset).some(dep => !dep.isEntry && this.bundle.hasDependency(dep) && (0, _nullthrows().default)(this.bundleGraph.getUsedSymbols(dep)).has('*'))) ||
883
- // If a symbol is imported (used) from a CJS asset but isn't listed in the symbols,
884
- // we fallback on the namespace object.
885
- asset.symbols.hasExportSymbol('*') && [...usedSymbols].some(s => !asset.symbols.hasExportSymbol(s)) ||
886
- // If the exports has this asset's namespace (e.g. ESM output from CJS input),
887
- // include the namespace object for the default export.
888
- this.exportedSymbols.has(`$${assetId}$exports`) ||
889
- // CommonJS library bundle entries always need a namespace.
890
- this.bundle.env.isLibrary && this.bundle.env.outputFormat === 'commonjs' && asset === this.bundle.getMainEntry();
922
+ let usedNamespace;
923
+ if ((0, _featureFlags().getFeatureFlag)('inlineConstOptimisationFix') && asset.meta.isConstantModule) {
924
+ // Only set usedNamespace if there is an incoming dependency in the current bundle that uses '*'
925
+ usedNamespace = this.bundleGraph.getIncomingDependencies(asset).some(dep => this.bundle.hasDependency(dep) && (0, _nullthrows().default)(this.bundleGraph.getUsedSymbols(dep)).has('*'));
926
+ } else {
927
+ usedNamespace =
928
+ // If the asset has * in its used symbols, we might need the exports namespace.
929
+ // The one case where this isn't true is in ESM library entries, where the only
930
+ // dependency on * is the entry dependency. In this case, we will use ESM exports
931
+ // instead of the namespace object.
932
+ usedSymbols.has('*') && (this.bundle.env.outputFormat !== 'esmodule' || !this.bundle.env.isLibrary || asset !== this.bundle.getMainEntry() || this.bundleGraph.getIncomingDependencies(asset).some(dep => !dep.isEntry && this.bundle.hasDependency(dep) && (0, _nullthrows().default)(this.bundleGraph.getUsedSymbols(dep)).has('*'))) ||
933
+ // If a symbol is imported (used) from a CJS asset but isn't listed in the symbols,
934
+ // we fallback on the namespace object.
935
+ asset.symbols.hasExportSymbol('*') && [...usedSymbols].some(s => !asset.symbols.hasExportSymbol(s)) ||
936
+ // If the exports has this asset's namespace (e.g. ESM output from CJS input),
937
+ // include the namespace object for the default export.
938
+ this.exportedSymbols.has(`$${assetId}$exports`) ||
939
+ // CommonJS library bundle entries always need a namespace.
940
+ this.bundle.env.isLibrary && this.bundle.env.outputFormat === 'commonjs' && asset === this.bundle.getMainEntry();
941
+ }
891
942
 
892
943
  // If the asset doesn't have static exports, should wrap, the namespace is used,
893
944
  // or we need default interop, then we need to synthesize a namespace object for
package/lib/index.js CHANGED
@@ -47,12 +47,6 @@ const CONFIG_SCHEMA = {
47
47
  properties: {
48
48
  unstable_asyncBundleRuntime: {
49
49
  type: 'boolean'
50
- },
51
- unstable_forceSkipWrapAssets: {
52
- type: 'array',
53
- items: {
54
- type: 'string'
55
- }
56
50
  }
57
51
  },
58
52
  additionalProperties: false
@@ -62,7 +56,7 @@ var _default = exports.default = new (_plugin().Packager)({
62
56
  config,
63
57
  options
64
58
  }) {
65
- var _conf$contents, _conf$contents2;
59
+ var _conf$contents;
66
60
  let packageKey = '@atlaspack/packager-js';
67
61
  let conf = await config.getConfigFrom(options.projectRoot + '/index', [], {
68
62
  packageKey
@@ -84,8 +78,7 @@ var _default = exports.default = new (_plugin().Packager)({
84
78
  let name = (packageName === null || packageName === void 0 ? void 0 : packageName.contents) ?? '';
85
79
  return {
86
80
  parcelRequireName: 'parcelRequire' + (0, _rust().hashString)(name).slice(-4),
87
- unstable_asyncBundleRuntime: Boolean(conf === null || conf === void 0 || (_conf$contents = conf.contents) === null || _conf$contents === void 0 ? void 0 : _conf$contents.unstable_asyncBundleRuntime),
88
- unstable_forceSkipWrapAssets: (conf === null || conf === void 0 || (_conf$contents2 = conf.contents) === null || _conf$contents2 === void 0 ? void 0 : _conf$contents2.unstable_forceSkipWrapAssets) ?? []
81
+ unstable_asyncBundleRuntime: Boolean(conf === null || conf === void 0 || (_conf$contents = conf.contents) === null || _conf$contents === void 0 ? void 0 : _conf$contents.unstable_asyncBundleRuntime)
89
82
  };
90
83
  },
91
84
  async package({
@@ -108,7 +101,7 @@ var _default = exports.default = new (_plugin().Packager)({
108
101
  }
109
102
  }
110
103
  if (contents == null) {
111
- let packager = bundle.env.shouldScopeHoist ? new _ScopeHoistingPackager.ScopeHoistingPackager(options, bundleGraph, bundle, (0, _nullthrows().default)(config).parcelRequireName, (0, _nullthrows().default)(config).unstable_asyncBundleRuntime, (0, _nullthrows().default)(config).unstable_forceSkipWrapAssets, logger) : new _DevPackager.DevPackager(options, bundleGraph, bundle, (0, _nullthrows().default)(config).parcelRequireName);
104
+ let packager = bundle.env.shouldScopeHoist ? new _ScopeHoistingPackager.ScopeHoistingPackager(options, bundleGraph, bundle, (0, _nullthrows().default)(config).parcelRequireName, (0, _nullthrows().default)(config).unstable_asyncBundleRuntime, logger) : new _DevPackager.DevPackager(options, bundleGraph, bundle, (0, _nullthrows().default)(config).parcelRequireName);
112
105
  ({
113
106
  contents,
114
107
  map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@atlaspack/packager-js",
3
- "version": "2.14.5-dev.73+84eec3484",
3
+ "version": "2.14.5-dev.95+d8e35a83e",
4
4
  "license": "(MIT OR Apache-2.0)",
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -15,16 +15,16 @@
15
15
  "node": ">= 16.0.0"
16
16
  },
17
17
  "dependencies": {
18
- "@atlaspack/diagnostic": "2.14.1-dev.141+84eec3484",
19
- "@atlaspack/feature-flags": "2.14.1-dev.141+84eec3484",
20
- "@atlaspack/plugin": "2.14.5-dev.73+84eec3484",
21
- "@atlaspack/rust": "3.2.1-dev.73+84eec3484",
22
- "@atlaspack/types": "2.14.5-dev.73+84eec3484",
23
- "@atlaspack/utils": "2.14.5-dev.73+84eec3484",
18
+ "@atlaspack/diagnostic": "2.14.1-dev.163+d8e35a83e",
19
+ "@atlaspack/feature-flags": "2.14.1-dev.163+d8e35a83e",
20
+ "@atlaspack/plugin": "2.14.5-dev.95+d8e35a83e",
21
+ "@atlaspack/rust": "3.2.1-dev.95+d8e35a83e",
22
+ "@atlaspack/types": "2.14.5-dev.95+d8e35a83e",
23
+ "@atlaspack/utils": "2.14.5-dev.95+d8e35a83e",
24
24
  "@parcel/source-map": "^2.1.1",
25
25
  "globals": "^13.2.0",
26
26
  "nullthrows": "^1.1.1"
27
27
  },
28
28
  "type": "commonjs",
29
- "gitHead": "84eec348413c647de4872f902c4bc8ff54c347f3"
29
+ "gitHead": "d8e35a83e480e0811b63a319e88ffe9a2cd509e6"
30
30
  }
@@ -8,6 +8,7 @@ import {
8
8
  normalizeSeparators,
9
9
  } from '@atlaspack/utils';
10
10
  import SourceMap from '@parcel/source-map';
11
+ import {getFeatureFlag} from '@atlaspack/feature-flags';
11
12
  import invariant from 'assert';
12
13
  import path from 'path';
13
14
  import fs from 'fs';
@@ -112,6 +113,18 @@ export class DevPackager {
112
113
  }
113
114
  }
114
115
 
116
+ if (getFeatureFlag('hmrImprovements')) {
117
+ // Add dependencies for parcelRequire calls added by runtimes
118
+ // so that the HMR runtime can correctly traverse parents.
119
+ let hmrDeps = asset.meta.hmrDeps;
120
+ if (this.options.hmrOptions && Array.isArray(hmrDeps)) {
121
+ for (let id of hmrDeps) {
122
+ invariant(typeof id === 'string');
123
+ deps[id] = id;
124
+ }
125
+ }
126
+ }
127
+
115
128
  let {code, mapBuffer} = results[i];
116
129
  let output = code || '';
117
130
  wrapped +=
@@ -102,7 +102,6 @@ export class ScopeHoistingPackager {
102
102
  needsPrelude: boolean = false;
103
103
  usedHelpers: Set<string> = new Set();
104
104
  externalAssets: Set<Asset> = new Set();
105
- forceSkipWrapAssets: Array<string> = [];
106
105
  logger: PluginLogger;
107
106
 
108
107
  constructor(
@@ -111,7 +110,6 @@ export class ScopeHoistingPackager {
111
110
  bundle: NamedBundle,
112
111
  parcelRequireName: string,
113
112
  useAsyncBundleRuntime: boolean,
114
- forceSkipWrapAssets: Array<string>,
115
113
  logger: PluginLogger,
116
114
  ) {
117
115
  this.options = options;
@@ -119,7 +117,6 @@ export class ScopeHoistingPackager {
119
117
  this.bundle = bundle;
120
118
  this.parcelRequireName = parcelRequireName;
121
119
  this.useAsyncBundleRuntime = useAsyncBundleRuntime;
122
- this.forceSkipWrapAssets = forceSkipWrapAssets ?? [];
123
120
  this.logger = logger;
124
121
 
125
122
  let OutputFormat = OUTPUT_FORMATS[this.bundle.env.outputFormat];
@@ -134,7 +131,8 @@ export class ScopeHoistingPackager {
134
131
  }
135
132
 
136
133
  async package(): Promise<{|contents: string, map: ?SourceMap|}> {
137
- let wrappedAssets = await this.loadAssets();
134
+ let {wrapped: wrappedAssets, constant: constantAssets} =
135
+ await this.loadAssets();
138
136
  this.buildExportedSymbols();
139
137
 
140
138
  // If building a library, the target is actually another bundler rather
@@ -168,6 +166,18 @@ export class ScopeHoistingPackager {
168
166
  lineCount += lines + 1;
169
167
  };
170
168
 
169
+ if (
170
+ getFeatureFlag('inlineConstOptimisationFix') ||
171
+ getFeatureFlag('applyScopeHoistingImprovement')
172
+ ) {
173
+ // Write out all constant modules used by this bundle
174
+ for (let asset of constantAssets) {
175
+ if (!this.seenAssets.has(asset.id)) {
176
+ processAsset(asset);
177
+ }
178
+ }
179
+ }
180
+
171
181
  // Hoist wrapped asset to the top of the bundle to ensure that they are registered
172
182
  // before they are used.
173
183
  for (let asset of wrappedAssets) {
@@ -354,15 +364,20 @@ export class ScopeHoistingPackager {
354
364
  return `$parcel$global.rwr(${params.join(', ')});`;
355
365
  }
356
366
 
357
- async loadAssets(): Promise<Array<Asset>> {
367
+ async loadAssets(): Promise<{|
368
+ wrapped: Array<Asset>,
369
+ constant: Array<Asset>,
370
+ |}> {
358
371
  let queue = new PromiseQueue({maxConcurrent: 32});
359
372
  let wrapped = [];
373
+ let constant = [];
360
374
  this.bundle.traverseAssets((asset) => {
361
375
  queue.add(async () => {
362
376
  let [code, map] = await Promise.all([
363
377
  asset.getCode(),
364
378
  this.bundle.env.sourceMap ? asset.getMapBuffer() : null,
365
379
  ]);
380
+
366
381
  return [asset.id, {code, map}];
367
382
  });
368
383
 
@@ -383,50 +398,87 @@ export class ScopeHoistingPackager {
383
398
  ) {
384
399
  this.wrappedAssets.add(asset.id);
385
400
  wrapped.push(asset);
401
+ } else if (
402
+ (getFeatureFlag('inlineConstOptimisationFix') ||
403
+ getFeatureFlag('applyScopeHoistingImprovement')) &&
404
+ asset.meta.isConstantModule
405
+ ) {
406
+ constant.push(asset);
386
407
  }
387
408
  }
388
409
  });
389
410
 
390
- for (let wrappedAssetRoot of [...wrapped]) {
391
- this.bundle.traverseAssets((asset, _, actions) => {
392
- if (asset === wrappedAssetRoot) {
393
- return;
394
- }
411
+ if (getFeatureFlag('applyScopeHoistingImprovement')) {
412
+ // Tracks which assets have been assigned to a wrap group
413
+ let assignedAssets = new Set<Asset>();
395
414
 
396
- if (this.wrappedAssets.has(asset.id)) {
397
- actions.skipChildren();
398
- return;
399
- }
400
- // This prevents children of a wrapped asset also being wrapped - it's an "unsafe" optimisation
401
- // that should only be used when you know (or think you know) what you're doing.
402
- //
403
- // In particular this can force an async bundle to be scope hoisted where it previously would not be
404
- // due to the entry asset being wrapped.
405
- if (
406
- this.forceSkipWrapAssets.length > 0 &&
407
- this.forceSkipWrapAssets.some(
408
- (p) =>
409
- p === path.relative(this.options.projectRoot, asset.filePath),
410
- )
411
- ) {
412
- this.logger.verbose({
413
- message: `Force skipping wrapping of ${path.relative(
414
- this.options.projectRoot,
415
- asset.filePath,
416
- )}`,
417
- });
418
- actions.skipChildren();
419
- return;
420
- }
421
- if (!asset.meta.isConstantModule) {
422
- this.wrappedAssets.add(asset.id);
423
- wrapped.push(asset);
424
- }
425
- }, wrappedAssetRoot);
415
+ for (let wrappedAsset of wrapped) {
416
+ this.bundle.traverseAssets((asset, _, actions) => {
417
+ if (asset === wrappedAsset) {
418
+ return;
419
+ }
420
+
421
+ if (this.wrappedAssets.has(asset.id)) {
422
+ actions.skipChildren();
423
+ return;
424
+ }
425
+
426
+ if (
427
+ !asset.meta.isConstantModule &&
428
+ (assignedAssets.has(asset) || this.isReExported(asset))
429
+ ) {
430
+ wrapped.push(asset);
431
+ this.wrappedAssets.add(asset.id);
432
+
433
+ actions.skipChildren();
434
+ return;
435
+ }
436
+
437
+ assignedAssets.add(asset);
438
+ }, wrappedAsset);
439
+ }
440
+ } else {
441
+ for (let wrappedAssetRoot of [...wrapped]) {
442
+ this.bundle.traverseAssets((asset, _, actions) => {
443
+ if (asset === wrappedAssetRoot) {
444
+ return;
445
+ }
446
+
447
+ if (this.wrappedAssets.has(asset.id)) {
448
+ actions.skipChildren();
449
+ return;
450
+ }
451
+
452
+ if (!asset.meta.isConstantModule) {
453
+ this.wrappedAssets.add(asset.id);
454
+ wrapped.push(asset);
455
+ }
456
+ }, wrappedAssetRoot);
457
+ }
426
458
  }
427
459
 
428
460
  this.assetOutputs = new Map(await queue.run());
429
- return wrapped;
461
+ return {wrapped, constant};
462
+ }
463
+
464
+ isReExported(asset: Asset): boolean {
465
+ let parentSymbols = this.bundleGraph
466
+ .getIncomingDependencies(asset)
467
+ .map((dep) => this.bundleGraph.getAssetWithDependency(dep))
468
+ .flatMap((parent) => {
469
+ if (parent == null) {
470
+ return [];
471
+ }
472
+ return this.bundleGraph.getExportedSymbols(parent, this.bundle);
473
+ });
474
+
475
+ let assetSymbols = this.bundleGraph.getExportedSymbols(asset, this.bundle);
476
+
477
+ return assetSymbols.some((assetSymbol) =>
478
+ parentSymbols.some(
479
+ (parentSymbol) => parentSymbol.symbol === assetSymbol.symbol,
480
+ ),
481
+ );
430
482
  }
431
483
 
432
484
  buildExportedSymbols() {
@@ -661,13 +713,27 @@ export class ScopeHoistingPackager {
661
713
  // outside our parcelRequire.register wrapper. This is safe because all
662
714
  // assets referenced by this asset will also be wrapped. Otherwise, inline the
663
715
  // asset content where the import statement was.
664
- if (shouldWrap) {
665
- depContent.push(this.visitAsset(resolved));
716
+ if (getFeatureFlag('applyScopeHoistingImprovement')) {
717
+ if (
718
+ !resolved.meta.isConstantModule &&
719
+ !this.wrappedAssets.has(resolved.id)
720
+ ) {
721
+ let [depCode, depMap, depLines] =
722
+ this.visitAsset(resolved);
723
+ res = depCode + '\n' + res;
724
+ lines += 1 + depLines;
725
+ map = depMap;
726
+ }
666
727
  } else {
667
- let [depCode, depMap, depLines] = this.visitAsset(resolved);
668
- res = depCode + '\n' + res;
669
- lines += 1 + depLines;
670
- map = depMap;
728
+ if (shouldWrap) {
729
+ depContent.push(this.visitAsset(resolved));
730
+ } else {
731
+ let [depCode, depMap, depLines] =
732
+ this.visitAsset(resolved);
733
+ res = depCode + '\n' + res;
734
+ lines += 1 + depLines;
735
+ map = depMap;
736
+ }
671
737
  }
672
738
  }
673
739
 
@@ -1220,34 +1286,49 @@ ${code}
1220
1286
  usedSymbols.has('default') &&
1221
1287
  !asset.symbols.hasExportSymbol('__esModule');
1222
1288
 
1223
- let usedNamespace =
1224
- // If the asset has * in its used symbols, we might need the exports namespace.
1225
- // The one case where this isn't true is in ESM library entries, where the only
1226
- // dependency on * is the entry dependency. In this case, we will use ESM exports
1227
- // instead of the namespace object.
1228
- (usedSymbols.has('*') &&
1229
- (this.bundle.env.outputFormat !== 'esmodule' ||
1230
- !this.bundle.env.isLibrary ||
1231
- asset !== this.bundle.getMainEntry() ||
1232
- this.bundleGraph
1233
- .getIncomingDependencies(asset)
1234
- .some(
1235
- (dep) =>
1236
- !dep.isEntry &&
1237
- this.bundle.hasDependency(dep) &&
1238
- nullthrows(this.bundleGraph.getUsedSymbols(dep)).has('*'),
1239
- ))) ||
1240
- // If a symbol is imported (used) from a CJS asset but isn't listed in the symbols,
1241
- // we fallback on the namespace object.
1242
- (asset.symbols.hasExportSymbol('*') &&
1243
- [...usedSymbols].some((s) => !asset.symbols.hasExportSymbol(s))) ||
1244
- // If the exports has this asset's namespace (e.g. ESM output from CJS input),
1245
- // include the namespace object for the default export.
1246
- this.exportedSymbols.has(`$${assetId}$exports`) ||
1247
- // CommonJS library bundle entries always need a namespace.
1248
- (this.bundle.env.isLibrary &&
1249
- this.bundle.env.outputFormat === 'commonjs' &&
1250
- asset === this.bundle.getMainEntry());
1289
+ let usedNamespace;
1290
+ if (
1291
+ getFeatureFlag('inlineConstOptimisationFix') &&
1292
+ asset.meta.isConstantModule
1293
+ ) {
1294
+ // Only set usedNamespace if there is an incoming dependency in the current bundle that uses '*'
1295
+ usedNamespace = this.bundleGraph
1296
+ .getIncomingDependencies(asset)
1297
+ .some(
1298
+ (dep) =>
1299
+ this.bundle.hasDependency(dep) &&
1300
+ nullthrows(this.bundleGraph.getUsedSymbols(dep)).has('*'),
1301
+ );
1302
+ } else {
1303
+ usedNamespace =
1304
+ // If the asset has * in its used symbols, we might need the exports namespace.
1305
+ // The one case where this isn't true is in ESM library entries, where the only
1306
+ // dependency on * is the entry dependency. In this case, we will use ESM exports
1307
+ // instead of the namespace object.
1308
+ (usedSymbols.has('*') &&
1309
+ (this.bundle.env.outputFormat !== 'esmodule' ||
1310
+ !this.bundle.env.isLibrary ||
1311
+ asset !== this.bundle.getMainEntry() ||
1312
+ this.bundleGraph
1313
+ .getIncomingDependencies(asset)
1314
+ .some(
1315
+ (dep) =>
1316
+ !dep.isEntry &&
1317
+ this.bundle.hasDependency(dep) &&
1318
+ nullthrows(this.bundleGraph.getUsedSymbols(dep)).has('*'),
1319
+ ))) ||
1320
+ // If a symbol is imported (used) from a CJS asset but isn't listed in the symbols,
1321
+ // we fallback on the namespace object.
1322
+ (asset.symbols.hasExportSymbol('*') &&
1323
+ [...usedSymbols].some((s) => !asset.symbols.hasExportSymbol(s))) ||
1324
+ // If the exports has this asset's namespace (e.g. ESM output from CJS input),
1325
+ // include the namespace object for the default export.
1326
+ this.exportedSymbols.has(`$${assetId}$exports`) ||
1327
+ // CommonJS library bundle entries always need a namespace.
1328
+ (this.bundle.env.isLibrary &&
1329
+ this.bundle.env.outputFormat === 'commonjs' &&
1330
+ asset === this.bundle.getMainEntry());
1331
+ }
1251
1332
 
1252
1333
  // If the asset doesn't have static exports, should wrap, the namespace is used,
1253
1334
  // or we need default interop, then we need to synthesize a namespace object for
package/src/index.js CHANGED
@@ -17,7 +17,6 @@ import {ScopeHoistingPackager} from './ScopeHoistingPackager';
17
17
  type JSPackagerConfig = {|
18
18
  parcelRequireName: string,
19
19
  unstable_asyncBundleRuntime: boolean,
20
- unstable_forceSkipWrapAssets: Array<string>,
21
20
  |};
22
21
 
23
22
  const CONFIG_SCHEMA: SchemaEntity = {
@@ -26,12 +25,6 @@ const CONFIG_SCHEMA: SchemaEntity = {
26
25
  unstable_asyncBundleRuntime: {
27
26
  type: 'boolean',
28
27
  },
29
- unstable_forceSkipWrapAssets: {
30
- type: 'array',
31
- items: {
32
- type: 'string',
33
- },
34
- },
35
28
  },
36
29
  additionalProperties: false,
37
30
  };
@@ -73,8 +66,6 @@ export default (new Packager({
73
66
  unstable_asyncBundleRuntime: Boolean(
74
67
  conf?.contents?.unstable_asyncBundleRuntime,
75
68
  ),
76
- unstable_forceSkipWrapAssets:
77
- conf?.contents?.unstable_forceSkipWrapAssets ?? [],
78
69
  };
79
70
  },
80
71
  async package({
@@ -108,7 +99,6 @@ export default (new Packager({
108
99
  bundle,
109
100
  nullthrows(config).parcelRequireName,
110
101
  nullthrows(config).unstable_asyncBundleRuntime,
111
- nullthrows(config).unstable_forceSkipWrapAssets,
112
102
  logger,
113
103
  )
114
104
  : new DevPackager(