@atlaspack/packager-js 2.21.4-dev-export-func-removal-960dd335d.0 → 2.22.1

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,32 @@
1
1
  # @atlaspack/packager-js
2
2
 
3
+ ## 2.22.1
4
+
5
+ ### Patch Changes
6
+
7
+ - [#763](https://github.com/atlassian-labs/atlaspack/pull/763) [`830261d`](https://github.com/atlassian-labs/atlaspack/commit/830261dcf4a40293090b61cab52fd75d5683c73f) Thanks [@benjervis](https://github.com/benjervis)! - Fixes scope hoisting by iterating from the main entry asset of a bundle when packaging. Behind the feature flag `applyScopeHoistingImprovementsV2`.
8
+
9
+ - Updated dependencies [[`830261d`](https://github.com/atlassian-labs/atlaspack/commit/830261dcf4a40293090b61cab52fd75d5683c73f), [`53dd47b`](https://github.com/atlassian-labs/atlaspack/commit/53dd47bd6d23cd47f87297347f03a609ab38a03d)]:
10
+ - @atlaspack/feature-flags@2.24.1
11
+ - @atlaspack/rust@3.7.0
12
+ - @atlaspack/utils@2.19.1
13
+ - @atlaspack/plugin@2.14.29
14
+ - @atlaspack/types@2.15.19
15
+
16
+ ## 2.22.0
17
+
18
+ ### Minor Changes
19
+
20
+ - [#762](https://github.com/atlassian-labs/atlaspack/pull/762) [`a5081c3`](https://github.com/atlassian-labs/atlaspack/commit/a5081c3f9207d28716ee4edd3841de1830ea4b80) Thanks [@JakeLane](https://github.com/JakeLane)! - Add feature flag 'useNewPrelude' which enables a micro-optimisation removing a 'for in' call and replacing with undefined check
21
+
22
+ ### Patch Changes
23
+
24
+ - Updated dependencies [[`f0349a6`](https://github.com/atlassian-labs/atlaspack/commit/f0349a6b9b04755088f121095ca6301a2ada3767), [`a5081c3`](https://github.com/atlassian-labs/atlaspack/commit/a5081c3f9207d28716ee4edd3841de1830ea4b80), [`f930003`](https://github.com/atlassian-labs/atlaspack/commit/f930003364fdc31e5487520ebe256f1a9389f579), [`f930003`](https://github.com/atlassian-labs/atlaspack/commit/f930003364fdc31e5487520ebe256f1a9389f579), [`8843980`](https://github.com/atlassian-labs/atlaspack/commit/88439807be20025fd3433380204ff1205079729e)]:
25
+ - @atlaspack/feature-flags@2.24.0
26
+ - @atlaspack/utils@2.19.0
27
+ - @atlaspack/plugin@2.14.28
28
+ - @atlaspack/types@2.15.18
29
+
3
30
  ## 2.21.3
4
31
 
5
32
  ### Patch Changes
@@ -105,9 +105,11 @@ class ScopeHoistingPackager {
105
105
  seenAssets = new Set();
106
106
  wrappedAssets = new Set();
107
107
  hoistedRequires = new Map();
108
+ seenHoistedRequires = new Set();
108
109
  needsPrelude = false;
109
110
  usedHelpers = new Set();
110
111
  externalAssets = new Set();
112
+ useBothScopeHoistingImprovements = (0, _featureFlags().getFeatureFlag)('applyScopeHoistingImprovementV2') || (0, _featureFlags().getFeatureFlag)('applyScopeHoistingImprovement');
111
113
  constructor(options, bundleGraph, bundle, parcelRequireName, useAsyncBundleRuntime, logger) {
112
114
  this.options = options;
113
115
  this.bundleGraph = bundleGraph;
@@ -145,7 +147,9 @@ class ScopeHoistingPackager {
145
147
  // @ts-expect-error TS7034
146
148
  let sourceMap = null;
147
149
  let processAsset = asset => {
150
+ this.seenHoistedRequires.clear();
148
151
  let [content, map, lines] = this.visitAsset(asset);
152
+
149
153
  // @ts-expect-error TS7005
150
154
  if (sourceMap && map) {
151
155
  sourceMap.addSourceMap(map, lineCount);
@@ -155,7 +159,7 @@ class ScopeHoistingPackager {
155
159
  res += content + '\n';
156
160
  lineCount += lines + 1;
157
161
  };
158
- if ((0, _featureFlags().getFeatureFlag)('inlineConstOptimisationFix') || (0, _featureFlags().getFeatureFlag)('applyScopeHoistingImprovement')) {
162
+ if ((0, _featureFlags().getFeatureFlag)('inlineConstOptimisationFix') || this.useBothScopeHoistingImprovements) {
159
163
  // Write out all constant modules used by this bundle
160
164
  for (let asset of constantAssets) {
161
165
  if (!this.seenAssets.has(asset.id)) {
@@ -190,7 +194,7 @@ class ScopeHoistingPackager {
190
194
  let entries = this.bundle.getEntryAssets();
191
195
  let mainEntry = this.bundle.getMainEntry();
192
196
  if (this.isAsyncBundle) {
193
- if ((0, _featureFlags().getFeatureFlag)('applyScopeHoistingImprovement') || (0, _featureFlags().getFeatureFlag)('supportWebpackChunkName')) {
197
+ if (this.useBothScopeHoistingImprovements || (0, _featureFlags().getFeatureFlag)('supportWebpackChunkName')) {
194
198
  // Generally speaking, async bundles should not be executed on load, as
195
199
  // they're just collections of assets that other assets require.
196
200
  // However, there are some special cases where a runtime asset needs to be
@@ -317,25 +321,38 @@ class ScopeHoistingPackager {
317
321
  if (!asset.meta.isConstantModule || this.bundleGraph.getIncomingDependencies(asset).some(dep => dep.priority === 'lazy')) {
318
322
  this.wrappedAssets.add(asset.id);
319
323
  wrapped.push(asset);
320
- } else if (((0, _featureFlags().getFeatureFlag)('inlineConstOptimisationFix') || (0, _featureFlags().getFeatureFlag)('applyScopeHoistingImprovement')) && asset.meta.isConstantModule) {
324
+ } else if (((0, _featureFlags().getFeatureFlag)('inlineConstOptimisationFix') || this.useBothScopeHoistingImprovements) && asset.meta.isConstantModule) {
321
325
  constant.push(asset);
322
326
  }
323
327
  }
324
328
  });
325
- if ((0, _featureFlags().getFeatureFlag)('applyScopeHoistingImprovement')) {
326
- // Make all entry assets wrapped, to avoid any top level hoisting
327
- for (let entryAsset of this.bundle.getEntryAssets()) {
328
- if (!this.wrappedAssets.has(entryAsset.id)) {
329
- this.wrappedAssets.add(entryAsset.id);
330
- wrapped.push(entryAsset);
331
- }
332
- }
333
-
329
+ if (this.useBothScopeHoistingImprovements) {
334
330
  // Tracks which assets have been assigned to a wrap group
335
331
  let assignedAssets = new Set();
336
- for (let wrappedAsset of wrapped) {
332
+
333
+ // In V2 scope hoisting, we iterate from the main entry, rather than
334
+ // wrapping the entry assets
335
+ if (!(0, _featureFlags().getFeatureFlag)('applyScopeHoistingImprovementV2')) {
336
+ // Make all entry assets wrapped, to avoid any top level hoisting
337
+ for (let entryAsset of this.bundle.getEntryAssets()) {
338
+ if (!this.wrappedAssets.has(entryAsset.id)) {
339
+ this.wrappedAssets.add(entryAsset.id);
340
+ wrapped.push(entryAsset);
341
+ }
342
+ }
343
+ }
344
+ let moduleGroupParents = [...wrapped];
345
+ if ((0, _featureFlags().getFeatureFlag)('applyScopeHoistingImprovementV2')) {
346
+ // The main entry needs to be check to find assets that would have gone in
347
+ // the top level scope
348
+ let mainEntry = this.bundle.getMainEntry();
349
+ if (mainEntry) {
350
+ moduleGroupParents.unshift(mainEntry);
351
+ }
352
+ }
353
+ for (let moduleGroupParentAsset of moduleGroupParents) {
337
354
  this.bundle.traverseAssets((asset, _, actions) => {
338
- if (asset === wrappedAsset) {
355
+ if (asset === moduleGroupParentAsset) {
339
356
  return;
340
357
  }
341
358
  if (this.wrappedAssets.has(asset.id)) {
@@ -345,11 +362,15 @@ class ScopeHoistingPackager {
345
362
  if (!asset.meta.isConstantModule && (assignedAssets.has(asset) || this.isReExported(asset))) {
346
363
  wrapped.push(asset);
347
364
  this.wrappedAssets.add(asset.id);
365
+
366
+ // This also needs to be added to the traversal so that we iterate
367
+ // it during this check.
368
+ moduleGroupParents.push(asset);
348
369
  actions.skipChildren();
349
370
  return;
350
371
  }
351
372
  assignedAssets.add(asset);
352
- }, wrappedAsset);
373
+ }, moduleGroupParentAsset);
353
374
  }
354
375
  } else {
355
376
  for (let wrappedAssetRoot of [...wrapped]) {
@@ -568,14 +589,18 @@ class ScopeHoistingPackager {
568
589
  // after the dependency is declared. This handles the case where the resulting asset
569
590
  // is wrapped, but the dependency in this asset is not marked as wrapped. This means
570
591
  // that it was imported/required at the top-level, so its side effects should run immediately.
571
- let [res, lines] = this.getHoistedParcelRequires(asset, dep, resolved);
592
+ let res = '';
593
+ let lines = 0;
572
594
  let map;
595
+ if (!(0, _featureFlags().getFeatureFlag)('applyScopeHoistingImprovementV2')) {
596
+ [res, lines] = this.getHoistedParcelRequires(asset, dep, resolved);
597
+ }
573
598
  if (this.bundle.hasAsset(resolved) && !this.seenAssets.has(resolved.id)) {
574
599
  // If this asset is wrapped, we need to hoist the code for the dependency
575
600
  // outside our parcelRequire.register wrapper. This is safe because all
576
601
  // assets referenced by this asset will also be wrapped. Otherwise, inline the
577
602
  // asset content where the import statement was.
578
- if ((0, _featureFlags().getFeatureFlag)('applyScopeHoistingImprovement')) {
603
+ if (this.useBothScopeHoistingImprovements) {
579
604
  if (!resolved.meta.isConstantModule && !this.wrappedAssets.has(resolved.id)) {
580
605
  let [depCode, depMap, depLines] = this.visitAsset(resolved);
581
606
  if (_utils().debugTools['asset-file-names-in-output']) {
@@ -604,6 +629,13 @@ class ScopeHoistingPackager {
604
629
  }
605
630
  }
606
631
  }
632
+ if ((0, _featureFlags().getFeatureFlag)('applyScopeHoistingImprovementV2')) {
633
+ let [requiresCode, requiresLines] = this.getHoistedParcelRequires(asset, dep, resolved);
634
+ if (requiresCode) {
635
+ res = requiresCode + '\n' + res;
636
+ lines += requiresLines + 1;
637
+ }
638
+ }
607
639
 
608
640
  // Push this asset's source mappings down by the number of lines in the dependency
609
641
  // plus the number of hoisted parcelRequires. Then insert the source map for the dependency.
@@ -1020,8 +1052,17 @@ ${code}
1020
1052
  }
1021
1053
  if (hoisted) {
1022
1054
  this.needsPrelude = true;
1023
- res += '\n' + [...hoisted.values()].join('\n');
1024
- lineCount += hoisted.size;
1055
+ if ((0, _featureFlags().getFeatureFlag)('applyScopeHoistingImprovementV2')) {
1056
+ let hoistedValues = [...hoisted.values()].filter(val => !this.seenHoistedRequires.has(val));
1057
+ for (let val of hoistedValues) {
1058
+ this.seenHoistedRequires.add(val);
1059
+ }
1060
+ res += '\n' + hoistedValues.join('\n');
1061
+ lineCount += hoisted.size;
1062
+ } else {
1063
+ res += '\n' + [...hoisted.values()].join('\n');
1064
+ lineCount += hoisted.size;
1065
+ }
1025
1066
  }
1026
1067
  return [res, lineCount];
1027
1068
  }
@@ -1144,11 +1185,9 @@ ${code}
1144
1185
  symbol, undefined, replacements);
1145
1186
  let get = this.buildFunctionExpression([], resolvedSymbol);
1146
1187
  let set = asset.meta.hasCJSExports ? ', ' + this.buildFunctionExpression(['v'], `${resolvedSymbol} = v`) : '';
1147
- // prepend += `$parcel$export($${assetId}$exports, ${JSON.stringify(
1148
- // symbol,
1149
- // )}, ${get}${set});\n`;
1150
- // this.usedHelpers.add('$parcel$export');
1151
- append += `$${assetId}$exports[${JSON.stringify(symbol)}] = ${resolvedSymbol};\n`;
1188
+ prepend += `$parcel$export($${assetId}$exports, ${JSON.stringify(symbol)}, ${get}${set});\n`;
1189
+ this.usedHelpers.add('$parcel$export');
1190
+ prependLineCount++;
1152
1191
  }
1153
1192
  }
1154
1193
  }
@@ -1186,7 +1225,7 @@ ${code}
1186
1225
  // for the symbol so that when the value changes the object property also changes. This is
1187
1226
  // required to simulate ESM live bindings. It's easier to do it this way rather than inserting
1188
1227
  // additional assignments after each mutation of the original binding.
1189
- append += `\n${usedExports.map(exp => {
1228
+ prepend += `\n${usedExports.map(exp => {
1190
1229
  var _asset$symbols$get2;
1191
1230
  let resolved = this.getSymbolResolution(asset, asset,
1192
1231
  // @ts-expect-error TS2345
@@ -1194,16 +1233,12 @@ ${code}
1194
1233
  let get = this.buildFunctionExpression([], resolved);
1195
1234
  let isEsmExport = !!((_asset$symbols$get2 = asset.symbols.get(exp)) !== null && _asset$symbols$get2 !== void 0 && (_asset$symbols$get2 = _asset$symbols$get2.meta) !== null && _asset$symbols$get2 !== void 0 && _asset$symbols$get2.isEsm);
1196
1235
  let set = !isEsmExport && asset.meta.hasCJSExports ? ', ' + this.buildFunctionExpression(['v'], `${resolved} = v`) : '';
1197
- // return `$parcel$export($${assetId}$exports, ${JSON.stringify(
1198
- // exp,
1199
- // )}, ${get}${set});`;
1200
- return `$${assetId}$exports[${JSON.stringify(exp)}] = ${resolved};\n`;
1236
+ return `$parcel$export($${assetId}$exports, ${JSON.stringify(exp)}, ${get}${set});`;
1201
1237
  }).join('\n')}\n`;
1202
- // this.usedHelpers.add('$parcel$export');
1203
- // prependLineCount += 1 + usedExports.length;
1238
+ this.usedHelpers.add('$parcel$export');
1239
+ prependLineCount += 1 + usedExports.length;
1204
1240
  }
1205
1241
  }
1206
-
1207
1242
  return [prepend, prependLineCount, append];
1208
1243
  }
1209
1244
  buildBundlePrelude() {
@@ -1251,7 +1286,7 @@ ${code}
1251
1286
  // Conditional deps may be loaded before entrypoints on the server
1252
1287
  this.hasConditionalDependency();
1253
1288
  if (mightBeFirstJS) {
1254
- let preludeCode = (0, _helpers.prelude)(this.parcelRequireName);
1289
+ let preludeCode = ((0, _featureFlags().getFeatureFlag)('useNewPrelude') ? _helpers.preludeNew : _helpers.preludeOld)(this.parcelRequireName);
1255
1290
  res += preludeCode;
1256
1291
  if (enableSourceMaps) {
1257
1292
  lines += (0, _utils().countLines)(preludeCode) - 1;
package/lib/helpers.js CHANGED
@@ -3,8 +3,8 @@
3
3
  Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
- exports.prelude = exports.helpers = exports.fnExpr = exports.bundleQueuePrelude = void 0;
7
- const prelude = parcelRequireName => `
6
+ exports.preludeOld = exports.preludeNew = exports.helpers = exports.fnExpr = exports.bundleQueuePrelude = void 0;
7
+ const preludeOld = parcelRequireName => `
8
8
  var $parcel$modules = {};
9
9
  var $parcel$inits = {};
10
10
 
@@ -37,7 +37,42 @@ if (parcelRequire == null) {
37
37
 
38
38
  var parcelRegister = parcelRequire.register;
39
39
  `;
40
- exports.prelude = prelude;
40
+ exports.preludeOld = preludeOld;
41
+ const preludeNew = parcelRequireName => `
42
+ var $parcel$modules = {};
43
+ var $parcel$inits = {};
44
+
45
+ var parcelRequire = $parcel$global[${JSON.stringify(parcelRequireName)}];
46
+
47
+ if (parcelRequire == null) {
48
+ parcelRequire = function(id) {
49
+ var mod = $parcel$modules[id];
50
+ if (mod !== undefined) {
51
+ return mod.exports;
52
+ }
53
+ var init = $parcel$inits[id];
54
+ if (init !== undefined) {
55
+ delete $parcel$inits[id];
56
+ var module = {id: id, exports: {}};
57
+ $parcel$modules[id] = module;
58
+ init.call(module.exports, module, module.exports);
59
+ return module.exports;
60
+ }
61
+ var err = new Error("Cannot find module '" + id + "'");
62
+ err.code = 'MODULE_NOT_FOUND';
63
+ throw err;
64
+ };
65
+
66
+ parcelRequire.register = function register(id, init) {
67
+ $parcel$inits[id] = init;
68
+ };
69
+
70
+ $parcel$global[${JSON.stringify(parcelRequireName)}] = parcelRequire;
71
+ }
72
+
73
+ var parcelRegister = parcelRequire.register;
74
+ `;
75
+ exports.preludeNew = preludeNew;
41
76
  const fnExpr = (env, params, body) => {
42
77
  let block = `{ ${body.join(' ')} }`;
43
78
  if (env.supports('arrow-functions')) {
@@ -28,10 +28,12 @@ export declare class ScopeHoistingPackager {
28
28
  seenAssets: Set<string>;
29
29
  wrappedAssets: Set<string>;
30
30
  hoistedRequires: Map<string, Map<string, string>>;
31
+ seenHoistedRequires: Set<string>;
31
32
  needsPrelude: boolean;
32
33
  usedHelpers: Set<string>;
33
34
  externalAssets: Set<Asset>;
34
35
  logger: PluginLogger;
36
+ useBothScopeHoistingImprovements: boolean;
35
37
  constructor(options: PluginOptions, bundleGraph: BundleGraph<NamedBundle>, bundle: NamedBundle, parcelRequireName: string, useAsyncBundleRuntime: boolean, logger: PluginLogger);
36
38
  package(): Promise<{
37
39
  contents: string;
@@ -1,5 +1,6 @@
1
1
  import type { Environment } from '@atlaspack/types';
2
- export declare const prelude: (parcelRequireName: string) => string;
2
+ export declare const preludeOld: (parcelRequireName: string) => string;
3
+ export declare const preludeNew: (parcelRequireName: string) => string;
3
4
  export declare const fnExpr: (env: Environment, params: Array<string>, body: Array<string>) => string;
4
5
  export declare const bundleQueuePrelude: (env: Environment) => string;
5
6
  export declare const helpers: {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@atlaspack/packager-js",
3
- "version": "2.21.4-dev-export-func-removal-960dd335d.0",
3
+ "version": "2.22.1",
4
4
  "license": "(MIT OR Apache-2.0)",
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -16,13 +16,13 @@
16
16
  "node": ">= 16.0.0"
17
17
  },
18
18
  "dependencies": {
19
- "@atlaspack/diagnostic": "2.14.4-dev-export-func-removal-960dd335d.0",
20
- "@atlaspack/feature-flags": "2.23.3-dev-export-func-removal-960dd335d.0",
21
- "@atlaspack/plugin": "2.14.28-dev-export-func-removal-960dd335d.0",
22
- "@atlaspack/rust": "3.6.3-dev-export-func-removal-960dd335d.0",
23
- "@atlaspack/types": "2.15.18-dev-export-func-removal-960dd335d.0",
24
- "@atlaspack/utils": "2.18.5-dev-export-func-removal-960dd335d.0",
19
+ "@atlaspack/diagnostic": "2.14.3",
20
+ "@atlaspack/feature-flags": "2.24.1",
21
+ "@atlaspack/plugin": "2.14.29",
22
+ "@atlaspack/rust": "3.7.0",
25
23
  "@parcel/source-map": "^2.1.1",
24
+ "@atlaspack/types": "2.15.19",
25
+ "@atlaspack/utils": "2.19.1",
26
26
  "globals": "^13.2.0",
27
27
  "nullthrows": "^1.1.1",
28
28
  "outdent": "^0.8.0"
@@ -31,6 +31,5 @@
31
31
  "scripts": {
32
32
  "check-ts": "tsc --emitDeclarationOnly --rootDir src",
33
33
  "build:lib": "gulp build --gulpfile ../../../gulpfile.js --cwd ."
34
- },
35
- "gitHead": "960dd335d08a04220a07b36f4bb83cd7e130903e"
34
+ }
36
35
  }
@@ -29,7 +29,13 @@ import {outdent} from 'outdent';
29
29
  import {ESMOutputFormat} from './ESMOutputFormat';
30
30
  import {CJSOutputFormat} from './CJSOutputFormat';
31
31
  import {GlobalOutputFormat} from './GlobalOutputFormat';
32
- import {prelude, helpers, bundleQueuePrelude, fnExpr} from './helpers';
32
+ import {
33
+ preludeOld,
34
+ preludeNew,
35
+ helpers,
36
+ bundleQueuePrelude,
37
+ fnExpr,
38
+ } from './helpers';
33
39
  import {
34
40
  replaceScriptDependencies,
35
41
  getSpecifier,
@@ -106,10 +112,14 @@ export class ScopeHoistingPackager {
106
112
  seenAssets: Set<string> = new Set();
107
113
  wrappedAssets: Set<string> = new Set();
108
114
  hoistedRequires: Map<string, Map<string, string>> = new Map();
115
+ seenHoistedRequires: Set<string> = new Set();
109
116
  needsPrelude: boolean = false;
110
117
  usedHelpers: Set<string> = new Set();
111
118
  externalAssets: Set<Asset> = new Set();
112
119
  logger: PluginLogger;
120
+ useBothScopeHoistingImprovements: boolean =
121
+ getFeatureFlag('applyScopeHoistingImprovementV2') ||
122
+ getFeatureFlag('applyScopeHoistingImprovement');
113
123
 
114
124
  constructor(
115
125
  options: PluginOptions,
@@ -167,7 +177,9 @@ export class ScopeHoistingPackager {
167
177
  // @ts-expect-error TS7034
168
178
  let sourceMap = null;
169
179
  let processAsset = (asset: Asset) => {
180
+ this.seenHoistedRequires.clear();
170
181
  let [content, map, lines] = this.visitAsset(asset);
182
+
171
183
  // @ts-expect-error TS7005
172
184
  if (sourceMap && map) {
173
185
  sourceMap.addSourceMap(map, lineCount);
@@ -181,7 +193,7 @@ export class ScopeHoistingPackager {
181
193
 
182
194
  if (
183
195
  getFeatureFlag('inlineConstOptimisationFix') ||
184
- getFeatureFlag('applyScopeHoistingImprovement')
196
+ this.useBothScopeHoistingImprovements
185
197
  ) {
186
198
  // Write out all constant modules used by this bundle
187
199
  for (let asset of constantAssets) {
@@ -221,7 +233,7 @@ export class ScopeHoistingPackager {
221
233
  let mainEntry = this.bundle.getMainEntry();
222
234
  if (this.isAsyncBundle) {
223
235
  if (
224
- getFeatureFlag('applyScopeHoistingImprovement') ||
236
+ this.useBothScopeHoistingImprovements ||
225
237
  getFeatureFlag('supportWebpackChunkName')
226
238
  ) {
227
239
  // Generally speaking, async bundles should not be executed on load, as
@@ -427,7 +439,7 @@ export class ScopeHoistingPackager {
427
439
  wrapped.push(asset);
428
440
  } else if (
429
441
  (getFeatureFlag('inlineConstOptimisationFix') ||
430
- getFeatureFlag('applyScopeHoistingImprovement')) &&
442
+ this.useBothScopeHoistingImprovements) &&
431
443
  asset.meta.isConstantModule
432
444
  ) {
433
445
  constant.push(asset);
@@ -435,21 +447,36 @@ export class ScopeHoistingPackager {
435
447
  }
436
448
  });
437
449
 
438
- if (getFeatureFlag('applyScopeHoistingImprovement')) {
439
- // Make all entry assets wrapped, to avoid any top level hoisting
440
- for (let entryAsset of this.bundle.getEntryAssets()) {
441
- if (!this.wrappedAssets.has(entryAsset.id)) {
442
- this.wrappedAssets.add(entryAsset.id);
443
- wrapped.push(entryAsset);
450
+ if (this.useBothScopeHoistingImprovements) {
451
+ // Tracks which assets have been assigned to a wrap group
452
+ let assignedAssets = new Set<Asset>();
453
+
454
+ // In V2 scope hoisting, we iterate from the main entry, rather than
455
+ // wrapping the entry assets
456
+ if (!getFeatureFlag('applyScopeHoistingImprovementV2')) {
457
+ // Make all entry assets wrapped, to avoid any top level hoisting
458
+ for (let entryAsset of this.bundle.getEntryAssets()) {
459
+ if (!this.wrappedAssets.has(entryAsset.id)) {
460
+ this.wrappedAssets.add(entryAsset.id);
461
+ wrapped.push(entryAsset);
462
+ }
444
463
  }
445
464
  }
446
465
 
447
- // Tracks which assets have been assigned to a wrap group
448
- let assignedAssets = new Set<Asset>();
466
+ let moduleGroupParents = [...wrapped];
449
467
 
450
- for (let wrappedAsset of wrapped) {
468
+ if (getFeatureFlag('applyScopeHoistingImprovementV2')) {
469
+ // The main entry needs to be check to find assets that would have gone in
470
+ // the top level scope
471
+ let mainEntry = this.bundle.getMainEntry();
472
+ if (mainEntry) {
473
+ moduleGroupParents.unshift(mainEntry);
474
+ }
475
+ }
476
+
477
+ for (let moduleGroupParentAsset of moduleGroupParents) {
451
478
  this.bundle.traverseAssets((asset, _, actions) => {
452
- if (asset === wrappedAsset) {
479
+ if (asset === moduleGroupParentAsset) {
453
480
  return;
454
481
  }
455
482
 
@@ -465,12 +492,16 @@ export class ScopeHoistingPackager {
465
492
  wrapped.push(asset);
466
493
  this.wrappedAssets.add(asset.id);
467
494
 
495
+ // This also needs to be added to the traversal so that we iterate
496
+ // it during this check.
497
+ moduleGroupParents.push(asset);
498
+
468
499
  actions.skipChildren();
469
500
  return;
470
501
  }
471
502
 
472
503
  assignedAssets.add(asset);
473
- }, wrappedAsset);
504
+ }, moduleGroupParentAsset);
474
505
  }
475
506
  } else {
476
507
  for (let wrappedAssetRoot of [...wrapped]) {
@@ -746,12 +777,18 @@ export class ScopeHoistingPackager {
746
777
  // after the dependency is declared. This handles the case where the resulting asset
747
778
  // is wrapped, but the dependency in this asset is not marked as wrapped. This means
748
779
  // that it was imported/required at the top-level, so its side effects should run immediately.
749
- let [res, lines] = this.getHoistedParcelRequires(
750
- asset,
751
- dep,
752
- resolved,
753
- );
780
+ let res = '';
781
+ let lines = 0;
754
782
  let map;
783
+
784
+ if (!getFeatureFlag('applyScopeHoistingImprovementV2')) {
785
+ [res, lines] = this.getHoistedParcelRequires(
786
+ asset,
787
+ dep,
788
+ resolved,
789
+ );
790
+ }
791
+
755
792
  if (
756
793
  this.bundle.hasAsset(resolved) &&
757
794
  !this.seenAssets.has(resolved.id)
@@ -760,7 +797,7 @@ export class ScopeHoistingPackager {
760
797
  // outside our parcelRequire.register wrapper. This is safe because all
761
798
  // assets referenced by this asset will also be wrapped. Otherwise, inline the
762
799
  // asset content where the import statement was.
763
- if (getFeatureFlag('applyScopeHoistingImprovement')) {
800
+ if (this.useBothScopeHoistingImprovements) {
764
801
  if (
765
802
  !resolved.meta.isConstantModule &&
766
803
  !this.wrappedAssets.has(resolved.id)
@@ -795,6 +832,16 @@ export class ScopeHoistingPackager {
795
832
  }
796
833
  }
797
834
 
835
+ if (getFeatureFlag('applyScopeHoistingImprovementV2')) {
836
+ let [requiresCode, requiresLines] =
837
+ this.getHoistedParcelRequires(asset, dep, resolved);
838
+
839
+ if (requiresCode) {
840
+ res = requiresCode + '\n' + res;
841
+ lines += requiresLines + 1;
842
+ }
843
+ }
844
+
798
845
  // Push this asset's source mappings down by the number of lines in the dependency
799
846
  // plus the number of hoisted parcelRequires. Then insert the source map for the dependency.
800
847
  if (sourceMap) {
@@ -1363,8 +1410,22 @@ ${code}
1363
1410
 
1364
1411
  if (hoisted) {
1365
1412
  this.needsPrelude = true;
1366
- res += '\n' + [...hoisted.values()].join('\n');
1367
- lineCount += hoisted.size;
1413
+
1414
+ if (getFeatureFlag('applyScopeHoistingImprovementV2')) {
1415
+ let hoistedValues = [...hoisted.values()].filter(
1416
+ (val) => !this.seenHoistedRequires.has(val),
1417
+ );
1418
+
1419
+ for (let val of hoistedValues) {
1420
+ this.seenHoistedRequires.add(val);
1421
+ }
1422
+
1423
+ res += '\n' + hoistedValues.join('\n');
1424
+ lineCount += hoisted.size;
1425
+ } else {
1426
+ res += '\n' + [...hoisted.values()].join('\n');
1427
+ lineCount += hoisted.size;
1428
+ }
1368
1429
  }
1369
1430
 
1370
1431
  return [res, lineCount];
@@ -1543,13 +1604,11 @@ ${code}
1543
1604
  ? ', ' +
1544
1605
  this.buildFunctionExpression(['v'], `${resolvedSymbol} = v`)
1545
1606
  : '';
1546
- // prepend += `$parcel$export($${assetId}$exports, ${JSON.stringify(
1547
- // symbol,
1548
- // )}, ${get}${set});\n`;
1549
- // this.usedHelpers.add('$parcel$export');
1550
- append += `$${assetId}$exports[${JSON.stringify(
1607
+ prepend += `$parcel$export($${assetId}$exports, ${JSON.stringify(
1551
1608
  symbol,
1552
- )}] = ${resolvedSymbol};\n`;
1609
+ )}, ${get}${set});\n`;
1610
+ this.usedHelpers.add('$parcel$export');
1611
+ prependLineCount++;
1553
1612
  }
1554
1613
  }
1555
1614
  }
@@ -1589,7 +1648,7 @@ ${code}
1589
1648
  // for the symbol so that when the value changes the object property also changes. This is
1590
1649
  // required to simulate ESM live bindings. It's easier to do it this way rather than inserting
1591
1650
  // additional assignments after each mutation of the original binding.
1592
- append += `\n${usedExports
1651
+ prepend += `\n${usedExports
1593
1652
  .map((exp) => {
1594
1653
  let resolved = this.getSymbolResolution(
1595
1654
  asset,
@@ -1605,16 +1664,13 @@ ${code}
1605
1664
  !isEsmExport && asset.meta.hasCJSExports
1606
1665
  ? ', ' + this.buildFunctionExpression(['v'], `${resolved} = v`)
1607
1666
  : '';
1608
- // return `$parcel$export($${assetId}$exports, ${JSON.stringify(
1609
- // exp,
1610
- // )}, ${get}${set});`;
1611
- return `$${assetId}$exports[${JSON.stringify(
1667
+ return `$parcel$export($${assetId}$exports, ${JSON.stringify(
1612
1668
  exp,
1613
- )}] = ${resolved};\n`;
1669
+ )}, ${get}${set});`;
1614
1670
  })
1615
1671
  .join('\n')}\n`;
1616
- // this.usedHelpers.add('$parcel$export');
1617
- // prependLineCount += 1 + usedExports.length;
1672
+ this.usedHelpers.add('$parcel$export');
1673
+ prependLineCount += 1 + usedExports.length;
1618
1674
  }
1619
1675
  }
1620
1676
 
@@ -1682,7 +1738,9 @@ ${code}
1682
1738
  this.hasConditionalDependency();
1683
1739
 
1684
1740
  if (mightBeFirstJS) {
1685
- let preludeCode = prelude(this.parcelRequireName);
1741
+ let preludeCode = (
1742
+ getFeatureFlag('useNewPrelude') ? preludeNew : preludeOld
1743
+ )(this.parcelRequireName);
1686
1744
  res += preludeCode;
1687
1745
  if (enableSourceMaps) {
1688
1746
  lines += countLines(preludeCode) - 1;
package/src/helpers.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import type {Environment} from '@atlaspack/types';
2
2
 
3
- export const prelude = (parcelRequireName: string): string => `
3
+ export const preludeOld = (parcelRequireName: string): string => `
4
4
  var $parcel$modules = {};
5
5
  var $parcel$inits = {};
6
6
 
@@ -34,6 +34,41 @@ if (parcelRequire == null) {
34
34
  var parcelRegister = parcelRequire.register;
35
35
  `;
36
36
 
37
+ export const preludeNew = (parcelRequireName: string): string => `
38
+ var $parcel$modules = {};
39
+ var $parcel$inits = {};
40
+
41
+ var parcelRequire = $parcel$global[${JSON.stringify(parcelRequireName)}];
42
+
43
+ if (parcelRequire == null) {
44
+ parcelRequire = function(id) {
45
+ var mod = $parcel$modules[id];
46
+ if (mod !== undefined) {
47
+ return mod.exports;
48
+ }
49
+ var init = $parcel$inits[id];
50
+ if (init !== undefined) {
51
+ delete $parcel$inits[id];
52
+ var module = {id: id, exports: {}};
53
+ $parcel$modules[id] = module;
54
+ init.call(module.exports, module, module.exports);
55
+ return module.exports;
56
+ }
57
+ var err = new Error("Cannot find module '" + id + "'");
58
+ err.code = 'MODULE_NOT_FOUND';
59
+ throw err;
60
+ };
61
+
62
+ parcelRequire.register = function register(id, init) {
63
+ $parcel$inits[id] = init;
64
+ };
65
+
66
+ $parcel$global[${JSON.stringify(parcelRequireName)}] = parcelRequire;
67
+ }
68
+
69
+ var parcelRegister = parcelRequire.register;
70
+ `;
71
+
37
72
  export const fnExpr = (
38
73
  env: Environment,
39
74
  params: Array<string>,
package/LICENSE DELETED
@@ -1,201 +0,0 @@
1
- Apache License
2
- Version 2.0, January 2004
3
- http://www.apache.org/licenses/
4
-
5
- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
-
7
- 1. Definitions.
8
-
9
- "License" shall mean the terms and conditions for use, reproduction,
10
- and distribution as defined by Sections 1 through 9 of this document.
11
-
12
- "Licensor" shall mean the copyright owner or entity authorized by
13
- the copyright owner that is granting the License.
14
-
15
- "Legal Entity" shall mean the union of the acting entity and all
16
- other entities that control, are controlled by, or are under common
17
- control with that entity. For the purposes of this definition,
18
- "control" means (i) the power, direct or indirect, to cause the
19
- direction or management of such entity, whether by contract or
20
- otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
- outstanding shares, or (iii) beneficial ownership of such entity.
22
-
23
- "You" (or "Your") shall mean an individual or Legal Entity
24
- exercising permissions granted by this License.
25
-
26
- "Source" form shall mean the preferred form for making modifications,
27
- including but not limited to software source code, documentation
28
- source, and configuration files.
29
-
30
- "Object" form shall mean any form resulting from mechanical
31
- transformation or translation of a Source form, including but
32
- not limited to compiled object code, generated documentation,
33
- and conversions to other media types.
34
-
35
- "Work" shall mean the work of authorship, whether in Source or
36
- Object form, made available under the License, as indicated by a
37
- copyright notice that is included in or attached to the work
38
- (an example is provided in the Appendix below).
39
-
40
- "Derivative Works" shall mean any work, whether in Source or Object
41
- form, that is based on (or derived from) the Work and for which the
42
- editorial revisions, annotations, elaborations, or other modifications
43
- represent, as a whole, an original work of authorship. For the purposes
44
- of this License, Derivative Works shall not include works that remain
45
- separable from, or merely link (or bind by name) to the interfaces of,
46
- the Work and Derivative Works thereof.
47
-
48
- "Contribution" shall mean any work of authorship, including
49
- the original version of the Work and any modifications or additions
50
- to that Work or Derivative Works thereof, that is intentionally
51
- submitted to Licensor for inclusion in the Work by the copyright owner
52
- or by an individual or Legal Entity authorized to submit on behalf of
53
- the copyright owner. For the purposes of this definition, "submitted"
54
- means any form of electronic, verbal, or written communication sent
55
- to the Licensor or its representatives, including but not limited to
56
- communication on electronic mailing lists, source code control systems,
57
- and issue tracking systems that are managed by, or on behalf of, the
58
- Licensor for the purpose of discussing and improving the Work, but
59
- excluding communication that is conspicuously marked or otherwise
60
- designated in writing by the copyright owner as "Not a Contribution."
61
-
62
- "Contributor" shall mean Licensor and any individual or Legal Entity
63
- on behalf of whom a Contribution has been received by Licensor and
64
- subsequently incorporated within the Work.
65
-
66
- 2. Grant of Copyright License. Subject to the terms and conditions of
67
- this License, each Contributor hereby grants to You a perpetual,
68
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
- copyright license to reproduce, prepare Derivative Works of,
70
- publicly display, publicly perform, sublicense, and distribute the
71
- Work and such Derivative Works in Source or Object form.
72
-
73
- 3. Grant of Patent License. Subject to the terms and conditions of
74
- this License, each Contributor hereby grants to You a perpetual,
75
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
- (except as stated in this section) patent license to make, have made,
77
- use, offer to sell, sell, import, and otherwise transfer the Work,
78
- where such license applies only to those patent claims licensable
79
- by such Contributor that are necessarily infringed by their
80
- Contribution(s) alone or by combination of their Contribution(s)
81
- with the Work to which such Contribution(s) was submitted. If You
82
- institute patent litigation against any entity (including a
83
- cross-claim or counterclaim in a lawsuit) alleging that the Work
84
- or a Contribution incorporated within the Work constitutes direct
85
- or contributory patent infringement, then any patent licenses
86
- granted to You under this License for that Work shall terminate
87
- as of the date such litigation is filed.
88
-
89
- 4. Redistribution. You may reproduce and distribute copies of the
90
- Work or Derivative Works thereof in any medium, with or without
91
- modifications, and in Source or Object form, provided that You
92
- meet the following conditions:
93
-
94
- (a) You must give any other recipients of the Work or
95
- Derivative Works a copy of this License; and
96
-
97
- (b) You must cause any modified files to carry prominent notices
98
- stating that You changed the files; and
99
-
100
- (c) You must retain, in the Source form of any Derivative Works
101
- that You distribute, all copyright, patent, trademark, and
102
- attribution notices from the Source form of the Work,
103
- excluding those notices that do not pertain to any part of
104
- the Derivative Works; and
105
-
106
- (d) If the Work includes a "NOTICE" text file as part of its
107
- distribution, then any Derivative Works that You distribute must
108
- include a readable copy of the attribution notices contained
109
- within such NOTICE file, excluding those notices that do not
110
- pertain to any part of the Derivative Works, in at least one
111
- of the following places: within a NOTICE text file distributed
112
- as part of the Derivative Works; within the Source form or
113
- documentation, if provided along with the Derivative Works; or,
114
- within a display generated by the Derivative Works, if and
115
- wherever such third-party notices normally appear. The contents
116
- of the NOTICE file are for informational purposes only and
117
- do not modify the License. You may add Your own attribution
118
- notices within Derivative Works that You distribute, alongside
119
- or as an addendum to the NOTICE text from the Work, provided
120
- that such additional attribution notices cannot be construed
121
- as modifying the License.
122
-
123
- You may add Your own copyright statement to Your modifications and
124
- may provide additional or different license terms and conditions
125
- for use, reproduction, or distribution of Your modifications, or
126
- for any such Derivative Works as a whole, provided Your use,
127
- reproduction, and distribution of the Work otherwise complies with
128
- the conditions stated in this License.
129
-
130
- 5. Submission of Contributions. Unless You explicitly state otherwise,
131
- any Contribution intentionally submitted for inclusion in the Work
132
- by You to the Licensor shall be under the terms and conditions of
133
- this License, without any additional terms or conditions.
134
- Notwithstanding the above, nothing herein shall supersede or modify
135
- the terms of any separate license agreement you may have executed
136
- with Licensor regarding such Contributions.
137
-
138
- 6. Trademarks. This License does not grant permission to use the trade
139
- names, trademarks, service marks, or product names of the Licensor,
140
- except as required for reasonable and customary use in describing the
141
- origin of the Work and reproducing the content of the NOTICE file.
142
-
143
- 7. Disclaimer of Warranty. Unless required by applicable law or
144
- agreed to in writing, Licensor provides the Work (and each
145
- Contributor provides its Contributions) on an "AS IS" BASIS,
146
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
- implied, including, without limitation, any warranties or conditions
148
- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
- PARTICULAR PURPOSE. You are solely responsible for determining the
150
- appropriateness of using or redistributing the Work and assume any
151
- risks associated with Your exercise of permissions under this License.
152
-
153
- 8. Limitation of Liability. In no event and under no legal theory,
154
- whether in tort (including negligence), contract, or otherwise,
155
- unless required by applicable law (such as deliberate and grossly
156
- negligent acts) or agreed to in writing, shall any Contributor be
157
- liable to You for damages, including any direct, indirect, special,
158
- incidental, or consequential damages of any character arising as a
159
- result of this License or out of the use or inability to use the
160
- Work (including but not limited to damages for loss of goodwill,
161
- work stoppage, computer failure or malfunction, or any and all
162
- other commercial damages or losses), even if such Contributor
163
- has been advised of the possibility of such damages.
164
-
165
- 9. Accepting Warranty or Additional Liability. While redistributing
166
- the Work or Derivative Works thereof, You may choose to offer,
167
- and charge a fee for, acceptance of support, warranty, indemnity,
168
- or other liability obligations and/or rights consistent with this
169
- License. However, in accepting such obligations, You may act only
170
- on Your own behalf and on Your sole responsibility, not on behalf
171
- of any other Contributor, and only if You agree to indemnify,
172
- defend, and hold each Contributor harmless for any liability
173
- incurred by, or claims asserted against, such Contributor by reason
174
- of your accepting any such warranty or additional liability.
175
-
176
- END OF TERMS AND CONDITIONS
177
-
178
- APPENDIX: How to apply the Apache License to your work.
179
-
180
- To apply the Apache License to your work, attach the following
181
- boilerplate notice, with the fields enclosed by brackets "[]"
182
- replaced with your own identifying information. (Don't include
183
- the brackets!) The text should be enclosed in the appropriate
184
- comment syntax for the file format. We also recommend that a
185
- file or class name and description of purpose be included on the
186
- same "printed page" as the copyright notice for easier
187
- identification within third-party archives.
188
-
189
- Copyright (c) 2024 Atlassian US., Inc.
190
-
191
- Licensed under the Apache License, Version 2.0 (the "License");
192
- you may not use this file except in compliance with the License.
193
- You may obtain a copy of the License at
194
-
195
- http://www.apache.org/licenses/LICENSE-2.0
196
-
197
- Unless required by applicable law or agreed to in writing, software
198
- distributed under the License is distributed on an "AS IS" BASIS,
199
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
- See the License for the specific language governing permissions and
201
- limitations under the License.