@atlaspack/packager-js 2.14.5-canary.28 → 2.14.5-canary.280

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.
@@ -60,6 +60,13 @@ function _featureFlags() {
60
60
  };
61
61
  return data;
62
62
  }
63
+ function _outdent() {
64
+ const data = require("outdent");
65
+ _outdent = function () {
66
+ return data;
67
+ };
68
+ return data;
69
+ }
63
70
  var _ESMOutputFormat = require("./ESMOutputFormat");
64
71
  var _CJSOutputFormat = require("./CJSOutputFormat");
65
72
  var _GlobalOutputFormat = require("./GlobalOutputFormat");
@@ -70,7 +77,6 @@ function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e;
70
77
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
71
78
  // General regex used to replace imports with the resolved code, references with resolutions,
72
79
  // and count the number of newlines in the file for source maps.
73
- //
74
80
  // For conditional bundling the only difference in this regex is adding `importCond` where we have `importAsync` etc..
75
81
  const REPLACEMENT_RE_CONDITIONAL = /\n|import\s+"([0-9a-f]{16,20}:.+?)";|(?:\$[0-9a-f]{16,20}\$exports)|(?:\$[0-9a-f]{16,20}\$(?:import|importAsync|require|importCond)\$[0-9a-f]+(?:\$[0-9a-f]+)?)/g;
76
82
  const REPLACEMENT_RE = /\n|import\s+"([0-9a-f]{16,20}:.+?)";|(?:\$[0-9a-f]{16,20}\$exports)|(?:\$[0-9a-f]{16,20}\$(?:import|importAsync|require)\$[0-9a-f]+(?:\$[0-9a-f]+)?)/g;
@@ -80,6 +86,7 @@ const GLOBALS_BY_CONTEXT = {
80
86
  'web-worker': new Set([...BUILTINS, ...Object.keys(_globals().default.worker)]),
81
87
  'service-worker': new Set([...BUILTINS, ...Object.keys(_globals().default.serviceworker)]),
82
88
  worklet: new Set([...BUILTINS]),
89
+ tesseract: new Set([...BUILTINS, ...Object.keys(_globals().default.worker)]),
83
90
  node: new Set([...BUILTINS, ...Object.keys(_globals().default.node)]),
84
91
  'electron-main': new Set([...BUILTINS, ...Object.keys(_globals().default.node)]),
85
92
  'electron-renderer': new Set([...BUILTINS, ...Object.keys(_globals().default.node), ...Object.keys(_globals().default.browser)])
@@ -90,32 +97,35 @@ const OUTPUT_FORMATS = {
90
97
  global: _GlobalOutputFormat.GlobalOutputFormat
91
98
  };
92
99
  class ScopeHoistingPackager {
100
+ assetOutputs = new Map();
93
101
  exportedSymbols = new Map();
94
102
  externals = new Map();
95
103
  topLevelNames = new Map();
96
104
  seenAssets = new Set();
97
105
  wrappedAssets = new Set();
106
+ constantAssets = new Set();
98
107
  hoistedRequires = new Map();
108
+ seenHoistedRequires = new Set();
99
109
  needsPrelude = false;
100
110
  usedHelpers = new Set();
101
111
  externalAssets = new Set();
102
- forceSkipWrapAssets = [];
103
- constructor(options, bundleGraph, bundle, parcelRequireName, useAsyncBundleRuntime, forceSkipWrapAssets, logger) {
112
+ useBothScopeHoistingImprovements = (0, _featureFlags().getFeatureFlag)('applyScopeHoistingImprovementV2') || (0, _featureFlags().getFeatureFlag)('applyScopeHoistingImprovement');
113
+ constructor(options, bundleGraph, bundle, parcelRequireName, useAsyncBundleRuntime, manualStaticBindingExports, logger) {
104
114
  this.options = options;
105
115
  this.bundleGraph = bundleGraph;
106
116
  this.bundle = bundle;
107
117
  this.parcelRequireName = parcelRequireName;
108
118
  this.useAsyncBundleRuntime = useAsyncBundleRuntime;
109
- this.forceSkipWrapAssets = forceSkipWrapAssets ?? [];
119
+ this.manualStaticBindingExports = (manualStaticBindingExports === null || manualStaticBindingExports === void 0 ? void 0 : manualStaticBindingExports.map(glob => (0, _utils().globToRegex)(glob))) ?? null;
110
120
  this.logger = logger;
111
121
  let OutputFormat = OUTPUT_FORMATS[this.bundle.env.outputFormat];
112
122
  this.outputFormat = new OutputFormat(this);
113
- this.isAsyncBundle = this.bundleGraph.hasParentBundleOfType(this.bundle, 'js') && !this.bundle.env.isIsolated() && this.bundle.bundleBehavior !== 'isolated';
123
+ this.isAsyncBundle = this.bundleGraph.hasParentBundleOfType(this.bundle, 'js') && !this.bundle.env.isIsolated() && this.bundle.bundleBehavior !== 'isolated' && this.bundle.bundleBehavior !== 'inlineIsolated';
114
124
  this.globalNames = GLOBALS_BY_CONTEXT[bundle.env.context];
115
125
  }
116
126
  async package() {
117
127
  var _sourceMap;
118
- let wrappedAssets = await this.loadAssets();
128
+ await this.loadAssets();
119
129
  this.buildExportedSymbols();
120
130
 
121
131
  // If building a library, the target is actually another bundler rather
@@ -134,8 +144,10 @@ class ScopeHoistingPackager {
134
144
  let lineCount = 0;
135
145
  let sourceMap = null;
136
146
  let processAsset = asset => {
147
+ this.seenHoistedRequires.clear();
137
148
  let [content, map, lines] = this.visitAsset(asset);
138
149
  if (sourceMap && map) {
150
+ // @ts-expect-error TS2551 - addSourceMap method exists but missing from @parcel/source-map type definitions
139
151
  sourceMap.addSourceMap(map, lineCount);
140
152
  } else if (this.bundle.env.sourceMap) {
141
153
  sourceMap = map;
@@ -143,11 +155,19 @@ class ScopeHoistingPackager {
143
155
  res += content + '\n';
144
156
  lineCount += lines + 1;
145
157
  };
158
+ if ((0, _featureFlags().getFeatureFlag)('inlineConstOptimisationFix') || this.useBothScopeHoistingImprovements) {
159
+ // Write out all constant modules used by this bundle
160
+ for (let asset of this.constantAssets) {
161
+ if (!this.seenAssets.has(asset)) {
162
+ processAsset(asset);
163
+ }
164
+ }
165
+ }
146
166
 
147
167
  // Hoist wrapped asset to the top of the bundle to ensure that they are registered
148
168
  // before they are used.
149
- for (let asset of wrappedAssets) {
150
- if (!this.seenAssets.has(asset.id)) {
169
+ for (let asset of this.wrappedAssets) {
170
+ if (!this.seenAssets.has(asset)) {
151
171
  processAsset(asset);
152
172
  }
153
173
  }
@@ -155,7 +175,7 @@ class ScopeHoistingPackager {
155
175
  // Add each asset that is directly connected to the bundle. Dependencies will be handled
156
176
  // by replacing `import` statements in the code.
157
177
  this.bundle.traverseAssets((asset, _, actions) => {
158
- if (this.seenAssets.has(asset.id)) {
178
+ if (this.seenAssets.has(asset)) {
159
179
  actions.skipChildren();
160
180
  return;
161
181
  }
@@ -165,23 +185,35 @@ class ScopeHoistingPackager {
165
185
  let [prelude, preludeLines] = this.buildBundlePrelude();
166
186
  res = prelude + res;
167
187
  lineCount += preludeLines;
188
+ // @ts-expect-error TS2339 - offsetLines method exists but missing from @parcel/source-map type definitions
168
189
  (_sourceMap = sourceMap) === null || _sourceMap === void 0 || _sourceMap.offsetLines(1, preludeLines);
169
190
  let entries = this.bundle.getEntryAssets();
170
191
  let mainEntry = this.bundle.getMainEntry();
171
192
  if (this.isAsyncBundle) {
172
- // In async bundles we don't want the main entry to execute until we require it
173
- // as there might be dependencies in a sibling bundle that hasn't loaded yet.
174
- entries = entries.filter(a => {
175
- var _mainEntry;
176
- return a.id !== ((_mainEntry = mainEntry) === null || _mainEntry === void 0 ? void 0 : _mainEntry.id);
177
- });
193
+ if (this.useBothScopeHoistingImprovements || (0, _featureFlags().getFeatureFlag)('supportWebpackChunkName')) {
194
+ // Generally speaking, async bundles should not be executed on load, as
195
+ // they're just collections of assets that other assets require.
196
+ // However, there are some special cases where a runtime asset needs to be
197
+ // injected, but no other asset will require it (mostly the bundle
198
+ // manifest).
199
+ // In this case, those assets need to be required on load.
200
+ entries = entries.filter(a => {
201
+ var _a$meta;
202
+ return (_a$meta = a.meta) === null || _a$meta === void 0 ? void 0 : _a$meta.runtimeAssetRequiringExecutionOnLoad;
203
+ });
204
+ } else {
205
+ entries = entries.filter(a => {
206
+ var _mainEntry;
207
+ return a.id !== ((_mainEntry = mainEntry) === null || _mainEntry === void 0 ? void 0 : _mainEntry.id);
208
+ });
209
+ }
178
210
  mainEntry = null;
179
211
  }
180
212
  let needsBundleQueue = this.shouldBundleQueue(this.bundle);
181
213
 
182
214
  // If any of the entry assets are wrapped, call parcelRequire so they are executed.
183
215
  for (let entry of entries) {
184
- if (this.wrappedAssets.has(entry.id) && !this.isScriptEntry(entry)) {
216
+ if (this.wrappedAssets.has(entry) && !this.isScriptEntry(entry)) {
185
217
  var _entry$symbols$get;
186
218
  let parcelRequire = `parcelRequire(${JSON.stringify(this.bundleGraph.getAssetPublicId(entry))});\n`;
187
219
  let entryExports = (_entry$symbols$get = entry.symbols.get('*')) === null || _entry$symbols$get === void 0 ? void 0 : _entry$symbols$get.local;
@@ -211,38 +243,46 @@ class ScopeHoistingPackager {
211
243
  let {
212
244
  code,
213
245
  map: mapBuffer
214
- } = (0, _nullthrows().default)(this.assetOutputs.get(mainEntry.id));
246
+ } = (0, _nullthrows().default)(this.assetOutputs.get(mainEntry));
215
247
  let map;
216
248
  if (mapBuffer) {
217
249
  map = new (_sourceMap2().default)(this.options.projectRoot, mapBuffer);
218
250
  }
219
251
  res += (0, _utils2.replaceScriptDependencies)(this.bundleGraph, this.bundle, code, map, this.parcelRequireName);
220
252
  if (sourceMap && map) {
253
+ // @ts-expect-error TS2339 - addSourceMap method exists but missing from @parcel/source-map type definitions
221
254
  sourceMap.addSourceMap(map, lineCount);
222
255
  }
223
256
  }
224
- return {
257
+ const result = {
225
258
  contents: res,
226
259
  map: sourceMap
227
260
  };
261
+ if (_utils().debugTools['scope-hoisting-stats']) {
262
+ result.scopeHoistingStats = {
263
+ totalAssets: this.assetOutputs.size,
264
+ wrappedAssets: this.wrappedAssets.size
265
+ };
266
+ }
267
+ return result;
228
268
  }
229
269
  shouldBundleQueue(bundle) {
230
270
  let referencingBundles = this.bundleGraph.getReferencingBundles(bundle);
231
271
  let hasHtmlReference = referencingBundles.some(b => b.type === 'html');
232
272
  let hasConditionalReference = false;
233
273
  let isConditionalBundle = false;
234
- if ((0, _featureFlags().getFeatureFlag)('conditionalBundlingApi') && (0, _featureFlags().getFeatureFlag)('conditionalBundlingAsyncRuntime')) {
274
+ if ((0, _featureFlags().getFeatureFlag)('conditionalBundlingApi')) {
235
275
  // If the bundle has a conditional bundle reference (has an importCond)
236
276
  hasConditionalReference = this.bundleGraph.getReferencedConditionalBundles(bundle).length > 0;
237
277
  // If the bundle is a conditional bundle
238
278
  isConditionalBundle = this.hasConditionalDependency();
239
279
  }
240
- return this.useAsyncBundleRuntime && bundle.type === 'js' && bundle.bundleBehavior !== 'inline' && bundle.env.outputFormat === 'esmodule' && !bundle.env.isIsolated() && bundle.bundleBehavior !== 'isolated' && (hasHtmlReference || hasConditionalReference || isConditionalBundle);
280
+ return this.useAsyncBundleRuntime && bundle.type === 'js' && bundle.bundleBehavior !== 'inline' && bundle.bundleBehavior !== 'inlineIsolated' && bundle.env.outputFormat === 'esmodule' && !bundle.env.isIsolated() && bundle.bundleBehavior !== 'isolated' && (hasHtmlReference || hasConditionalReference || isConditionalBundle);
241
281
  }
242
282
  runWhenReady(bundle, codeToRun) {
243
283
  let deps = this.bundleGraph.getReferencedBundles(bundle).filter(b => this.shouldBundleQueue(b)).map(b => b.publicId);
244
284
  const conditions = [];
245
- if ((0, _featureFlags().getFeatureFlag)('conditionalBundlingApi') && (0, _featureFlags().getFeatureFlag)('conditionalBundlingAsyncRuntime')) {
285
+ if ((0, _featureFlags().getFeatureFlag)('conditionalBundlingApi')) {
246
286
  const conditionSet = this.bundleGraph.getConditionalBundleMapping().get(bundle.id);
247
287
  for (const [key, {
248
288
  ifTrueBundles,
@@ -264,11 +304,10 @@ class ScopeHoistingPackager {
264
304
  let queue = new (_utils().PromiseQueue)({
265
305
  maxConcurrent: 32
266
306
  });
267
- let wrapped = [];
268
307
  this.bundle.traverseAssets(asset => {
269
308
  queue.add(async () => {
270
309
  let [code, map] = await Promise.all([asset.getCode(), this.bundle.env.sourceMap ? asset.getMapBuffer() : null]);
271
- return [asset.id, {
310
+ return [asset, {
272
311
  code,
273
312
  map
274
313
  }];
@@ -276,40 +315,86 @@ class ScopeHoistingPackager {
276
315
  if (asset.meta.shouldWrap || this.bundle.env.sourceType === 'script' || this.bundleGraph.isAssetReferenced(this.bundle, asset) || this.bundleGraph.getIncomingDependencies(asset).some(dep => dep.meta.shouldWrap && dep.specifierType !== 'url')) {
277
316
  // Don't wrap constant "entry" modules _except_ if they are referenced by any lazy dependency
278
317
  if (!asset.meta.isConstantModule || this.bundleGraph.getIncomingDependencies(asset).some(dep => dep.priority === 'lazy')) {
279
- this.wrappedAssets.add(asset.id);
280
- wrapped.push(asset);
318
+ this.wrappedAssets.add(asset);
319
+ } else if (((0, _featureFlags().getFeatureFlag)('inlineConstOptimisationFix') || this.useBothScopeHoistingImprovements) && asset.meta.isConstantModule) {
320
+ this.constantAssets.add(asset);
281
321
  }
282
322
  }
283
323
  });
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;
324
+ if (this.useBothScopeHoistingImprovements) {
325
+ // Tracks which assets have been assigned to a wrap group
326
+ let assignedAssets = new Set();
327
+
328
+ // In V2 scope hoisting, we iterate from the main entry, rather than
329
+ // wrapping the entry assets
330
+ if (!(0, _featureFlags().getFeatureFlag)('applyScopeHoistingImprovementV2')) {
331
+ // Make all entry assets wrapped, to avoid any top level hoisting
332
+ for (let entryAsset of this.bundle.getEntryAssets()) {
333
+ if (!this.wrappedAssets.has(entryAsset)) {
334
+ this.wrappedAssets.add(entryAsset);
335
+ }
304
336
  }
305
- if (!asset.meta.isConstantModule) {
306
- this.wrappedAssets.add(asset.id);
307
- wrapped.push(asset);
337
+ }
338
+
339
+ // We need to make a new copy here so that we can add to the list and
340
+ // iterate the newly added items, without mutating the wrappedAssets set
341
+ let moduleGroupParents = [...this.wrappedAssets.values()];
342
+ if ((0, _featureFlags().getFeatureFlag)('applyScopeHoistingImprovementV2')) {
343
+ // The main entry needs to be check to find assets that would have gone in
344
+ // the top level scope
345
+ let mainEntry = this.bundle.getMainEntry();
346
+ if (mainEntry && !this.wrappedAssets.has(mainEntry)) {
347
+ moduleGroupParents.unshift(mainEntry);
308
348
  }
309
- }, wrappedAssetRoot);
349
+ }
350
+ for (let moduleGroupParentAsset of moduleGroupParents) {
351
+ this.bundle.traverseAssets((asset, _, actions) => {
352
+ if (asset === moduleGroupParentAsset) {
353
+ return;
354
+ }
355
+ if (this.wrappedAssets.has(asset)) {
356
+ actions.skipChildren();
357
+ return;
358
+ }
359
+ if (!asset.meta.isConstantModule && (assignedAssets.has(asset) || this.isReExported(asset))) {
360
+ this.wrappedAssets.add(asset);
361
+
362
+ // This also needs to be added to the traversal so that we iterate
363
+ // it during this check.
364
+ moduleGroupParents.push(asset);
365
+ actions.skipChildren();
366
+ return;
367
+ }
368
+ assignedAssets.add(asset);
369
+ }, moduleGroupParentAsset);
370
+ }
371
+ } else {
372
+ for (let wrappedAssetRoot of this.wrappedAssets) {
373
+ this.bundle.traverseAssets((asset, _, actions) => {
374
+ if (asset === wrappedAssetRoot) {
375
+ return;
376
+ }
377
+ if (this.wrappedAssets.has(asset)) {
378
+ actions.skipChildren();
379
+ return;
380
+ }
381
+ if (!asset.meta.isConstantModule) {
382
+ this.wrappedAssets.add(asset);
383
+ }
384
+ }, wrappedAssetRoot);
385
+ }
310
386
  }
311
387
  this.assetOutputs = new Map(await queue.run());
312
- return wrapped;
388
+ }
389
+ isReExported(asset) {
390
+ let parentSymbols = this.bundleGraph.getIncomingDependencies(asset).map(dep => this.bundleGraph.getAssetWithDependency(dep)).flatMap(parent => {
391
+ if (parent == null) {
392
+ return [];
393
+ }
394
+ return this.bundleGraph.getExportedSymbols(parent, this.bundle);
395
+ });
396
+ let assetSymbols = this.bundleGraph.getExportedSymbols(asset, this.bundle);
397
+ return assetSymbols.some(assetSymbol => parentSymbols.some(parentSymbol => parentSymbol.symbol === assetSymbol.symbol));
313
398
  }
314
399
  buildExportedSymbols() {
315
400
  if (!this.bundle.env.isLibrary || this.bundle.env.outputFormat !== 'esmodule') {
@@ -318,7 +403,7 @@ class ScopeHoistingPackager {
318
403
 
319
404
  // TODO: handle ESM exports of wrapped entry assets...
320
405
  let entry = this.bundle.getMainEntry();
321
- if (entry && !this.wrappedAssets.has(entry.id)) {
406
+ if (entry && !this.wrappedAssets.has(entry)) {
322
407
  let hasNamespace = entry.symbols.hasExportSymbol('*');
323
408
  for (let {
324
409
  asset,
@@ -387,16 +472,19 @@ class ScopeHoistingPackager {
387
472
  return `${obj}[${JSON.stringify(property)}]`;
388
473
  }
389
474
  visitAsset(asset) {
390
- (0, _assert().default)(!this.seenAssets.has(asset.id), 'Already visited asset');
391
- this.seenAssets.add(asset.id);
475
+ (0, _assert().default)(!this.seenAssets.has(asset), 'Already visited asset');
476
+ this.seenAssets.add(asset);
392
477
  let {
393
478
  code,
394
479
  map
395
- } = (0, _nullthrows().default)(this.assetOutputs.get(asset.id));
480
+ } = (0, _nullthrows().default)(this.assetOutputs.get(asset));
396
481
  return this.buildAsset(asset, code, map);
397
482
  }
483
+ getAssetFilePath(asset) {
484
+ return _path().default.relative(this.options.projectRoot, asset.filePath);
485
+ }
398
486
  buildAsset(asset, code, map) {
399
- let shouldWrap = this.wrappedAssets.has(asset.id);
487
+ let shouldWrap = this.wrappedAssets.has(asset);
400
488
  let deps = this.bundleGraph.getDependencies(asset);
401
489
  let sourceMap = this.bundle.env.sourceMap && map ? new (_sourceMap2().default)(this.options.projectRoot, map) : null;
402
490
 
@@ -416,13 +504,27 @@ class ScopeHoistingPackager {
416
504
  }
417
505
  continue;
418
506
  }
419
- if (this.bundle.hasAsset(resolved) && !this.seenAssets.has(resolved.id)) {
420
- let [code, map, lines] = this.visitAsset(resolved);
421
- depCode += code + '\n';
422
- if (sourceMap && map) {
423
- sourceMap.addSourceMap(map, lineCount);
507
+ if (this.bundle.hasAsset(resolved) && !this.seenAssets.has(resolved)) {
508
+ if (this.useBothScopeHoistingImprovements && this.wrappedAssets.has(resolved)) {
509
+ if (this.wrappedAssets.has(asset)) {
510
+ // If both the asset and the dep are wrapped there's no need to
511
+ // drop a side-effect require. This is an extremely rare case.
512
+ continue;
513
+ }
514
+
515
+ // When the dep is wrapped then we just need to drop a side effect
516
+ // require instead of inlining
517
+ depCode += `parcelRequire("${this.bundleGraph.getAssetPublicId(resolved)}");\n`;
518
+ lineCount += 1;
519
+ } else {
520
+ let [code, map, lines] = this.visitAsset(resolved);
521
+ depCode += code + '\n';
522
+ if (sourceMap && map) {
523
+ // @ts-expect-error TS2551 - addSourceMap method exists but missing from @parcel/source-map type definitions
524
+ sourceMap.addSourceMap(map, lineCount);
525
+ }
526
+ lineCount += lines + 1;
424
527
  }
425
- lineCount += lines + 1;
426
528
  }
427
529
  }
428
530
  return [depCode, sourceMap, lineCount];
@@ -482,20 +584,51 @@ class ScopeHoistingPackager {
482
584
  // after the dependency is declared. This handles the case where the resulting asset
483
585
  // is wrapped, but the dependency in this asset is not marked as wrapped. This means
484
586
  // that it was imported/required at the top-level, so its side effects should run immediately.
485
- let [res, lines] = this.getHoistedParcelRequires(asset, dep, resolved);
587
+ let res = '';
588
+ let lines = 0;
486
589
  let map;
487
- if (this.bundle.hasAsset(resolved) && !this.seenAssets.has(resolved.id)) {
590
+ if (!(0, _featureFlags().getFeatureFlag)('applyScopeHoistingImprovementV2')) {
591
+ [res, lines] = this.getHoistedParcelRequires(asset, dep, resolved);
592
+ }
593
+ if (this.bundle.hasAsset(resolved) && !this.seenAssets.has(resolved)) {
488
594
  // If this asset is wrapped, we need to hoist the code for the dependency
489
595
  // outside our parcelRequire.register wrapper. This is safe because all
490
596
  // assets referenced by this asset will also be wrapped. Otherwise, inline the
491
597
  // asset content where the import statement was.
492
- if (shouldWrap) {
493
- depContent.push(this.visitAsset(resolved));
598
+ if (this.useBothScopeHoistingImprovements) {
599
+ if (!resolved.meta.isConstantModule && !this.wrappedAssets.has(resolved)) {
600
+ let [depCode, depMap, depLines] = this.visitAsset(resolved);
601
+ if (_utils().debugTools['asset-file-names-in-output']) {
602
+ let resolvedPath = this.getAssetFilePath(resolved);
603
+ res = (0, _outdent().outdent)`
604
+ /* Scope hoisted asset: ${resolvedPath} */
605
+ ${depCode}
606
+ /* End: ${resolvedPath} */
607
+ ${res}
608
+ `;
609
+ lines += 3 + depLines;
610
+ } else {
611
+ res = depCode + '\n' + res;
612
+ lines += 1 + depLines;
613
+ }
614
+ map = depMap;
615
+ }
494
616
  } else {
495
- let [depCode, depMap, depLines] = this.visitAsset(resolved);
496
- res = depCode + '\n' + res;
497
- lines += 1 + depLines;
498
- map = depMap;
617
+ if (shouldWrap) {
618
+ depContent.push(this.visitAsset(resolved));
619
+ } else {
620
+ let [depCode, depMap, depLines] = this.visitAsset(resolved);
621
+ res = depCode + '\n' + res;
622
+ lines += 1 + depLines;
623
+ map = depMap;
624
+ }
625
+ }
626
+ }
627
+ if ((0, _featureFlags().getFeatureFlag)('applyScopeHoistingImprovementV2')) {
628
+ let [requiresCode, requiresLines] = this.getHoistedParcelRequires(asset, dep, resolved);
629
+ if (requiresCode) {
630
+ res = requiresCode + '\n' + res;
631
+ lines += requiresLines + 1;
499
632
  }
500
633
  }
501
634
 
@@ -506,6 +639,7 @@ class ScopeHoistingPackager {
506
639
  sourceMap.offsetLines(lineCount + 1, lines);
507
640
  }
508
641
  if (map) {
642
+ // @ts-expect-error TS2551 - addSourceMap method exists but missing from @parcel/source-map type definitions
509
643
  sourceMap.addSourceMap(map, lineCount);
510
644
  }
511
645
  }
@@ -542,10 +676,15 @@ ${code}
542
676
  });
543
677
  `;
544
678
  lineCount += 2;
679
+ if (_utils().debugTools['asset-file-names-in-output']) {
680
+ code = `/* ${this.getAssetFilePath(asset)} */\n` + code;
681
+ lineCount += 1;
682
+ }
545
683
  for (let [depCode, map, lines] of depContent) {
546
684
  if (!depCode) continue;
547
685
  code += depCode + '\n';
548
686
  if (sourceMap && map) {
687
+ // @ts-expect-error TS2551 - addSourceMap method exists but missing from @parcel/source-map type definitions
549
688
  sourceMap.addSourceMap(map, lineCount);
550
689
  }
551
690
  lineCount += lines + 1;
@@ -614,7 +753,7 @@ ${code}
614
753
 
615
754
  // If this asset is wrapped, we need to replace the exports namespace with `module.exports`,
616
755
  // which will be provided to us by the wrapper.
617
- if (this.wrappedAssets.has(asset.id) || this.bundle.env.outputFormat === 'commonjs' && asset === this.bundle.getMainEntry()) {
756
+ if (this.wrappedAssets.has(asset) || this.bundle.env.outputFormat === 'commonjs' && asset === this.bundle.getMainEntry()) {
618
757
  var _asset$symbols$get;
619
758
  let exportsName = ((_asset$symbols$get = asset.symbols.get('*')) === null || _asset$symbols$get === void 0 ? void 0 : _asset$symbols$get.local) || `$${assetId}$exports`;
620
759
  replacements.set(exportsName, 'module.exports');
@@ -648,6 +787,7 @@ ${code}
648
787
  local
649
788
  }] of dep.symbols) {
650
789
  // If already imported, just add the already renamed variable to the mapping.
790
+
651
791
  let renamed = external.get(imported);
652
792
  if (renamed && local !== '*' && replacements) {
653
793
  replacements.set(local, renamed);
@@ -711,7 +851,7 @@ ${code}
711
851
  continue;
712
852
  }
713
853
  }
714
- renamed = this.bundleGraph.getSymbolResolution(entry, imported, this.bundle).symbol;
854
+ renamed = this.bundleGraph.getSymbolResolution(entry, imported, this.bundle).symbol || undefined;
715
855
  }
716
856
  }
717
857
 
@@ -752,7 +892,7 @@ ${code}
752
892
  }
753
893
  return false;
754
894
  }
755
- return !this.bundle.hasAsset(resolved) && !this.externalAssets.has(resolved) || this.wrappedAssets.has(resolved.id) && resolved !== parentAsset;
895
+ return !this.bundle.hasAsset(resolved) && !this.externalAssets.has(resolved) || this.wrappedAssets.has(resolved) && resolved !== parentAsset;
756
896
  }
757
897
  getSymbolResolution(parentAsset, resolved, imported, dep, replacements) {
758
898
  let {
@@ -779,12 +919,12 @@ ${code}
779
919
  // Only do this if the asset is part of a different bundle (so it was definitely
780
920
  // parcelRequire.register'ed there), or if it is indeed registered in this bundle.
781
921
  !this.bundle.hasAsset(resolvedAsset) || !this.shouldSkipAsset(resolvedAsset))) {
782
- let hoisted = this.hoistedRequires.get(dep.id);
922
+ let hoisted = this.hoistedRequires.get(dep);
783
923
  if (!hoisted) {
784
924
  hoisted = new Map();
785
- this.hoistedRequires.set(dep.id, hoisted);
925
+ this.hoistedRequires.set(dep, hoisted);
786
926
  }
787
- hoisted.set(resolvedAsset.id, `var $${publicId} = parcelRequire(${JSON.stringify(publicId)});`);
927
+ hoisted.set(resolvedAsset, `var $${publicId} = parcelRequire(${JSON.stringify(publicId)});`);
788
928
  }
789
929
  if (isWrapped) {
790
930
  this.needsPrelude = true;
@@ -813,7 +953,7 @@ ${code}
813
953
  }
814
954
  if (imported === '*' || exportSymbol === '*' || isDefaultInterop) {
815
955
  // Resolve to the namespace object if requested or this is a CJS default interop reqiure.
816
- if (parentAsset === resolvedAsset && this.wrappedAssets.has(resolvedAsset.id)) {
956
+ if (parentAsset === resolvedAsset && this.wrappedAssets.has(resolvedAsset)) {
817
957
  // Directly use module.exports for wrapped assets importing themselves.
818
958
  return 'module.exports';
819
959
  } else {
@@ -841,7 +981,7 @@ ${code}
841
981
  if (resolved.type !== 'js') {
842
982
  return ['', 0];
843
983
  }
844
- let hoisted = this.hoistedRequires.get(dep.id);
984
+ let hoisted = this.hoistedRequires.get(dep);
845
985
  let res = '';
846
986
  let lineCount = 0;
847
987
  let isWrapped = this.isWrapped(resolved, parentAsset);
@@ -850,14 +990,23 @@ ${code}
850
990
  // we need to run side effects when this asset runs. If the resolved asset is not
851
991
  // the first one in the hoisted requires, we need to insert a parcelRequire here
852
992
  // so it runs first.
853
- if (isWrapped && !dep.meta.shouldWrap && (!hoisted || hoisted.keys().next().value !== resolved.id) && !this.bundleGraph.isDependencySkipped(dep) && !this.shouldSkipAsset(resolved)) {
993
+ if (isWrapped && !dep.meta.shouldWrap && (!hoisted || hoisted.keys().next().value !== resolved) && !this.bundleGraph.isDependencySkipped(dep) && !this.shouldSkipAsset(resolved)) {
854
994
  this.needsPrelude = true;
855
995
  res += `parcelRequire(${JSON.stringify(this.bundleGraph.getAssetPublicId(resolved))});`;
856
996
  }
857
997
  if (hoisted) {
858
998
  this.needsPrelude = true;
859
- res += '\n' + [...hoisted.values()].join('\n');
860
- lineCount += hoisted.size;
999
+ if ((0, _featureFlags().getFeatureFlag)('applyScopeHoistingImprovementV2')) {
1000
+ let hoistedValues = [...hoisted.values()].filter(val => !this.seenHoistedRequires.has(val));
1001
+ for (let val of hoistedValues) {
1002
+ this.seenHoistedRequires.add(val);
1003
+ }
1004
+ res += '\n' + hoistedValues.join('\n');
1005
+ lineCount += hoisted.size;
1006
+ } else {
1007
+ res += '\n' + [...hoisted.values()].join('\n');
1008
+ lineCount += hoisted.size;
1009
+ }
861
1010
  }
862
1011
  return [res, lineCount];
863
1012
  }
@@ -865,7 +1014,7 @@ ${code}
865
1014
  let prepend = '';
866
1015
  let prependLineCount = 0;
867
1016
  let append = '';
868
- let shouldWrap = this.wrappedAssets.has(asset.id);
1017
+ let shouldWrap = this.wrappedAssets.has(asset);
869
1018
  let usedSymbols = (0, _nullthrows().default)(this.bundleGraph.getUsedSymbols(asset));
870
1019
  let assetId = asset.meta.id;
871
1020
  (0, _assert().default)(typeof assetId === 'string');
@@ -874,20 +1023,28 @@ ${code}
874
1023
  // If there's no __esModule flag, and default is a used symbol, we need
875
1024
  // to insert an interop helper.
876
1025
  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();
1026
+ let usedNamespace;
1027
+ if ((0, _featureFlags().getFeatureFlag)('inlineConstOptimisationFix') && asset.meta.isConstantModule) {
1028
+ // Only set usedNamespace if there is an incoming dependency in the current bundle that uses '*'
1029
+ usedNamespace = this.bundleGraph.getIncomingDependencies(asset).some(dep => this.bundle.hasDependency(dep) && (0, _nullthrows().default)(this.bundleGraph.getUsedSymbols(dep)).has('*'));
1030
+ } else {
1031
+ usedNamespace =
1032
+ // If the asset has * in its used symbols, we might need the exports namespace.
1033
+ // The one case where this isn't true is in ESM library entries, where the only
1034
+ // dependency on * is the entry dependency. In this case, we will use ESM exports
1035
+ // instead of the namespace object.
1036
+
1037
+ 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('*'))) ||
1038
+ // If a symbol is imported (used) from a CJS asset but isn't listed in the symbols,
1039
+ // we fallback on the namespace object.
1040
+
1041
+ asset.symbols.hasExportSymbol('*') && [...usedSymbols].some(s => !asset.symbols.hasExportSymbol(s)) ||
1042
+ // If the exports has this asset's namespace (e.g. ESM output from CJS input),
1043
+ // include the namespace object for the default export.
1044
+ this.exportedSymbols.has(`$${assetId}$exports`) ||
1045
+ // CommonJS library bundle entries always need a namespace.
1046
+ this.bundle.env.isLibrary && this.bundle.env.outputFormat === 'commonjs' && asset === this.bundle.getMainEntry();
1047
+ }
891
1048
 
892
1049
  // If the asset doesn't have static exports, should wrap, the namespace is used,
893
1050
  // or we need default interop, then we need to synthesize a namespace object for
@@ -905,6 +1062,7 @@ ${code}
905
1062
  // Insert the __esModule interop flag for this module if it has a `default` export
906
1063
  // and the namespace symbol is used.
907
1064
  // TODO: only if required by CJS?
1065
+
908
1066
  if (asset.symbols.hasExportSymbol('default') && usedSymbols.has('*')) {
909
1067
  prepend += `\n$parcel$defineInteropFlag($${assetId}$exports);\n`;
910
1068
  prependLineCount += 2;
@@ -988,16 +1146,22 @@ ${code}
988
1146
  // for the symbol so that when the value changes the object property also changes. This is
989
1147
  // required to simulate ESM live bindings. It's easier to do it this way rather than inserting
990
1148
  // additional assignments after each mutation of the original binding.
991
- prepend += `\n${usedExports.map(exp => {
992
- var _asset$symbols$get2;
1149
+ for (let exp of usedExports) {
1150
+ var _asset$symbols$get2, _this$manualStaticBin;
993
1151
  let resolved = this.getSymbolResolution(asset, asset, exp, undefined, replacements);
994
- let get = this.buildFunctionExpression([], resolved);
995
- 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);
996
- let set = !isEsmExport && asset.meta.hasCJSExports ? ', ' + this.buildFunctionExpression(['v'], `${resolved} = v`) : '';
997
- return `$parcel$export($${assetId}$exports, ${JSON.stringify(exp)}, ${get}${set});`;
998
- }).join('\n')}\n`;
999
- this.usedHelpers.add('$parcel$export');
1000
- prependLineCount += 1 + usedExports.length;
1152
+ const meta = (_asset$symbols$get2 = asset.symbols.get(exp)) === null || _asset$symbols$get2 === void 0 ? void 0 : _asset$symbols$get2.meta;
1153
+ if ((0, _featureFlags().getFeatureFlag)('exportsRebindingOptimisation') && (meta !== null && meta !== void 0 && meta.isStaticBindingSafe || (_this$manualStaticBin = this.manualStaticBindingExports) !== null && _this$manualStaticBin !== void 0 && _this$manualStaticBin.some(regex => regex.test(asset.filePath)))) {
1154
+ append += `$${assetId}$exports[${JSON.stringify(exp)}] = ${resolved};\n`;
1155
+ } else {
1156
+ var _asset$symbols$get3;
1157
+ let get = this.buildFunctionExpression([], resolved);
1158
+ let isEsmExport = !!((_asset$symbols$get3 = asset.symbols.get(exp)) !== null && _asset$symbols$get3 !== void 0 && (_asset$symbols$get3 = _asset$symbols$get3.meta) !== null && _asset$symbols$get3 !== void 0 && _asset$symbols$get3.isEsm);
1159
+ let set = !isEsmExport && asset.meta.hasCJSExports ? ', ' + this.buildFunctionExpression(['v'], `${resolved} = v`) : '';
1160
+ prepend += `$parcel$export($${assetId}$exports, ${JSON.stringify(exp)}, ${get}${set});\n`;
1161
+ this.usedHelpers.add('$parcel$export');
1162
+ prependLineCount += 1 + usedExports.length;
1163
+ }
1164
+ }
1001
1165
  }
1002
1166
  }
1003
1167
  return [prepend, prependLineCount, append];
@@ -1041,11 +1205,11 @@ ${code}
1041
1205
  // Add the prelude if this is potentially the first JS bundle to load in a
1042
1206
  // particular context (e.g. entry scripts in HTML, workers, etc.).
1043
1207
  let parentBundles = this.bundleGraph.getParentBundles(this.bundle);
1044
- let mightBeFirstJS = parentBundles.length === 0 || parentBundles.some(b => b.type !== 'js') || this.bundleGraph.getBundleGroupsContainingBundle(this.bundle).some(g => this.bundleGraph.isEntryBundleGroup(g)) || this.bundle.env.isIsolated() || this.bundle.bundleBehavior === 'isolated' ||
1208
+ let mightBeFirstJS = parentBundles.length === 0 || parentBundles.some(b => b.type !== 'js') || this.bundleGraph.getBundleGroupsContainingBundle(this.bundle).some(g => this.bundleGraph.isEntryBundleGroup(g)) || this.bundle.env.isIsolated() || this.bundle.bundleBehavior === 'isolated' || this.bundle.bundleBehavior === 'inlineIsolated' ||
1045
1209
  // Conditional deps may be loaded before entrypoints on the server
1046
1210
  this.hasConditionalDependency();
1047
1211
  if (mightBeFirstJS) {
1048
- let preludeCode = (0, _helpers.prelude)(this.parcelRequireName);
1212
+ let preludeCode = ((0, _featureFlags().getFeatureFlag)('useNewPrelude') ? _helpers.preludeNew : _helpers.preludeOld)(this.parcelRequireName);
1049
1213
  res += preludeCode;
1050
1214
  if (enableSourceMaps) {
1051
1215
  lines += (0, _utils().countLines)(preludeCode) - 1;
@@ -1068,7 +1232,7 @@ ${code}
1068
1232
  }
1069
1233
 
1070
1234
  // Add importScripts for sibling bundles in workers.
1071
- if (this.bundle.env.isWorker() || this.bundle.env.isWorklet()) {
1235
+ if (this.bundle.env.isWorker() || this.bundle.env.isTesseract() || this.bundle.env.isWorklet()) {
1072
1236
  let importScripts = '';
1073
1237
  let bundles = this.bundleGraph.getReferencedBundles(this.bundle);
1074
1238
  for (let b of bundles) {