@parcel/packager-js 2.0.0-nightly.92 → 2.0.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.
@@ -0,0 +1,985 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.ScopeHoistingPackager = void 0;
7
+
8
+ function _utils() {
9
+ const data = require("@parcel/utils");
10
+
11
+ _utils = function () {
12
+ return data;
13
+ };
14
+
15
+ return data;
16
+ }
17
+
18
+ function _sourceMap2() {
19
+ const data = _interopRequireDefault(require("@parcel/source-map"));
20
+
21
+ _sourceMap2 = function () {
22
+ return data;
23
+ };
24
+
25
+ return data;
26
+ }
27
+
28
+ function _nullthrows() {
29
+ const data = _interopRequireDefault(require("nullthrows"));
30
+
31
+ _nullthrows = function () {
32
+ return data;
33
+ };
34
+
35
+ return data;
36
+ }
37
+
38
+ function _assert() {
39
+ const data = _interopRequireDefault(require("assert"));
40
+
41
+ _assert = function () {
42
+ return data;
43
+ };
44
+
45
+ return data;
46
+ }
47
+
48
+ function _diagnostic() {
49
+ const data = _interopRequireDefault(require("@parcel/diagnostic"));
50
+
51
+ _diagnostic = function () {
52
+ return data;
53
+ };
54
+
55
+ return data;
56
+ }
57
+
58
+ function _globals() {
59
+ const data = _interopRequireDefault(require("globals"));
60
+
61
+ _globals = function () {
62
+ return data;
63
+ };
64
+
65
+ return data;
66
+ }
67
+
68
+ var _ESMOutputFormat = require("./ESMOutputFormat");
69
+
70
+ var _CJSOutputFormat = require("./CJSOutputFormat");
71
+
72
+ var _GlobalOutputFormat = require("./GlobalOutputFormat");
73
+
74
+ var _helpers = require("./helpers");
75
+
76
+ var _utils2 = require("./utils");
77
+
78
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
79
+
80
+ // https://262.ecma-international.org/6.0/#sec-names-and-keywords
81
+ const IDENTIFIER_RE = /^[$_\p{ID_Start}][$_\u200C\u200D\p{ID_Continue}]*$/u;
82
+ const ID_START_RE = /^[$_\p{ID_Start}]/u;
83
+ const NON_ID_CONTINUE_RE = /[^$_\u200C\u200D\p{ID_Continue}]/gu; // General regex used to replace imports with the resolved code, references with resolutions,
84
+ // and count the number of newlines in the file for source maps.
85
+
86
+ const REPLACEMENT_RE = /\n|import\s+"([0-9a-f]{16}:.+?)";|(?:\$[0-9a-f]{16}\$exports)|(?:\$[0-9a-f]{16}\$(?:import|importAsync|require)\$[0-9a-f]+(?:\$[0-9a-f]+)?)/g;
87
+ const BUILTINS = Object.keys(_globals().default.builtin);
88
+ const GLOBALS_BY_CONTEXT = {
89
+ browser: new Set([...BUILTINS, ...Object.keys(_globals().default.browser)]),
90
+ 'web-worker': new Set([...BUILTINS, ...Object.keys(_globals().default.worker)]),
91
+ 'service-worker': new Set([...BUILTINS, ...Object.keys(_globals().default.serviceworker)]),
92
+ worklet: new Set([...BUILTINS]),
93
+ node: new Set([...BUILTINS, ...Object.keys(_globals().default.node)]),
94
+ 'electron-main': new Set([...BUILTINS, ...Object.keys(_globals().default.node)]),
95
+ 'electron-renderer': new Set([...BUILTINS, ...Object.keys(_globals().default.node), ...Object.keys(_globals().default.browser)])
96
+ };
97
+ const OUTPUT_FORMATS = {
98
+ esmodule: _ESMOutputFormat.ESMOutputFormat,
99
+ commonjs: _CJSOutputFormat.CJSOutputFormat,
100
+ global: _GlobalOutputFormat.GlobalOutputFormat
101
+ };
102
+
103
+ class ScopeHoistingPackager {
104
+ exportedSymbols = new Map();
105
+ externals = new Map();
106
+ topLevelNames = new Map();
107
+ seenAssets = new Set();
108
+ wrappedAssets = new Set();
109
+ hoistedRequires = new Map();
110
+ needsPrelude = false;
111
+ usedHelpers = new Set();
112
+
113
+ constructor(options, bundleGraph, bundle, parcelRequireName) {
114
+ this.options = options;
115
+ this.bundleGraph = bundleGraph;
116
+ this.bundle = bundle;
117
+ this.parcelRequireName = parcelRequireName;
118
+ let OutputFormat = OUTPUT_FORMATS[this.bundle.env.outputFormat];
119
+ this.outputFormat = new OutputFormat(this);
120
+ this.isAsyncBundle = this.bundleGraph.hasParentBundleOfType(this.bundle, 'js') && !this.bundle.env.isIsolated() && this.bundle.bundleBehavior !== 'isolated';
121
+ this.globalNames = GLOBALS_BY_CONTEXT[bundle.env.context];
122
+ }
123
+
124
+ async package() {
125
+ var _sourceMap;
126
+
127
+ await this.loadAssets();
128
+ this.buildExportedSymbols(); // If building a library, the target is actually another bundler rather
129
+ // than the final output that could be loaded in a browser. So, loader
130
+ // runtimes are excluded, and instead we add imports into the entry bundle
131
+ // of each bundle group pointing at the sibling bundles. These can be
132
+ // picked up by another bundler later at which point runtimes will be added.
133
+
134
+ if (this.bundle.env.isLibrary || this.bundle.env.outputFormat === 'commonjs') {
135
+ let bundles = this.bundleGraph.getReferencedBundles(this.bundle);
136
+
137
+ for (let b of bundles) {
138
+ this.externals.set((0, _utils().relativeBundlePath)(this.bundle, b), new Map());
139
+ }
140
+ } // Add each asset that is directly connected to the bundle. Dependencies will be handled
141
+ // by replacing `import` statements in the code.
142
+
143
+
144
+ let res = '';
145
+ let lineCount = 0;
146
+ let sourceMap = null;
147
+ this.bundle.traverseAssets((asset, _, actions) => {
148
+ if (this.seenAssets.has(asset.id)) {
149
+ actions.skipChildren();
150
+ return;
151
+ }
152
+
153
+ let [content, map, lines] = this.visitAsset(asset);
154
+
155
+ if (sourceMap && map) {
156
+ sourceMap.addSourceMap(map, lineCount);
157
+ } else if (this.bundle.env.sourceMap) {
158
+ sourceMap = map;
159
+ }
160
+
161
+ res += content + '\n';
162
+ lineCount += lines + 1;
163
+ actions.skipChildren();
164
+ });
165
+ let [prelude, preludeLines] = this.buildBundlePrelude();
166
+ res = prelude + res;
167
+ lineCount += preludeLines;
168
+ (_sourceMap = sourceMap) === null || _sourceMap === void 0 ? void 0 : _sourceMap.offsetLines(1, preludeLines);
169
+ let entries = this.bundle.getEntryAssets();
170
+ let mainEntry = this.bundle.getMainEntry();
171
+
172
+ if (this.isAsyncBundle) {
173
+ // In async bundles we don't want the main entry to execute until we require it
174
+ // as there might be dependencies in a sibling bundle that hasn't loaded yet.
175
+ entries = entries.filter(a => {
176
+ var _mainEntry;
177
+
178
+ return a.id !== ((_mainEntry = mainEntry) === null || _mainEntry === void 0 ? void 0 : _mainEntry.id);
179
+ });
180
+ mainEntry = null;
181
+ } // If any of the entry assets are wrapped, call parcelRequire so they are executed.
182
+
183
+
184
+ for (let entry of entries) {
185
+ if (this.wrappedAssets.has(entry.id) && !this.isScriptEntry(entry)) {
186
+ var _entry$symbols$get;
187
+
188
+ let parcelRequire = `parcelRequire(${JSON.stringify(this.bundleGraph.getAssetPublicId(entry))});\n`;
189
+ let entryExports = (_entry$symbols$get = entry.symbols.get('*')) === null || _entry$symbols$get === void 0 ? void 0 : _entry$symbols$get.local;
190
+
191
+ if (entryExports && entry === mainEntry && this.exportedSymbols.has(entryExports)) {
192
+ res += `\nvar ${entryExports} = ${parcelRequire}`;
193
+ } else {
194
+ res += `\n${parcelRequire}`;
195
+ }
196
+
197
+ lineCount += 2;
198
+ }
199
+ }
200
+
201
+ let [postlude, postludeLines] = this.outputFormat.buildBundlePostlude();
202
+ res += postlude;
203
+ lineCount += postludeLines; // The entry asset of a script bundle gets hoisted outside the bundle wrapper so that
204
+ // its top-level variables become globals like a real browser script. We need to replace
205
+ // all dependency references for runtimes with a parcelRequire call.
206
+
207
+ if (this.bundle.env.outputFormat === 'global' && this.bundle.env.sourceType === 'script') {
208
+ res += '\n';
209
+ lineCount++;
210
+ let mainEntry = (0, _nullthrows().default)(this.bundle.getMainEntry());
211
+ let {
212
+ code,
213
+ map: mapBuffer
214
+ } = (0, _nullthrows().default)(this.assetOutputs.get(mainEntry.id));
215
+ let map;
216
+
217
+ if (mapBuffer) {
218
+ map = new (_sourceMap2().default)(this.options.projectRoot, mapBuffer);
219
+ }
220
+
221
+ res += (0, _utils2.replaceScriptDependencies)(this.bundleGraph, this.bundle, code, map, this.parcelRequireName);
222
+
223
+ if (sourceMap && map) {
224
+ sourceMap.addSourceMap(map, lineCount);
225
+ }
226
+ }
227
+
228
+ return {
229
+ contents: res,
230
+ map: sourceMap
231
+ };
232
+ }
233
+
234
+ async loadAssets() {
235
+ let queue = new (_utils().PromiseQueue)({
236
+ maxConcurrent: 32
237
+ });
238
+ this.bundle.traverseAssets((asset, shouldWrap) => {
239
+ queue.add(async () => {
240
+ let [code, map] = await Promise.all([asset.getCode(), this.bundle.env.sourceMap ? asset.getMapBuffer() : null]);
241
+ return [asset.id, {
242
+ code,
243
+ map
244
+ }];
245
+ });
246
+
247
+ if (shouldWrap || asset.meta.shouldWrap || this.isAsyncBundle || this.bundle.env.sourceType === 'script' || this.bundleGraph.isAssetReferenced(this.bundle, asset) || this.bundleGraph.getIncomingDependencies(asset).some(dep => dep.meta.shouldWrap && dep.specifierType !== 'url')) {
248
+ this.wrappedAssets.add(asset.id);
249
+ return true;
250
+ }
251
+ });
252
+ this.assetOutputs = new Map(await queue.run());
253
+ }
254
+
255
+ buildExportedSymbols() {
256
+ if (this.isAsyncBundle || !this.bundle.env.isLibrary || this.bundle.env.outputFormat !== 'esmodule') {
257
+ return;
258
+ } // TODO: handle ESM exports of wrapped entry assets...
259
+
260
+
261
+ let entry = this.bundle.getMainEntry();
262
+
263
+ if (entry && !this.wrappedAssets.has(entry.id)) {
264
+ for (let {
265
+ asset,
266
+ exportAs,
267
+ symbol,
268
+ exportSymbol
269
+ } of this.bundleGraph.getExportedSymbols(entry)) {
270
+ if (typeof symbol === 'string') {
271
+ var _this$exportedSymbols, _entry$symbols$get2;
272
+
273
+ let symbols = (_this$exportedSymbols = this.exportedSymbols.get(symbol === '*' ? (0, _nullthrows().default)((_entry$symbols$get2 = entry.symbols.get('*')) === null || _entry$symbols$get2 === void 0 ? void 0 : _entry$symbols$get2.local) : symbol)) === null || _this$exportedSymbols === void 0 ? void 0 : _this$exportedSymbols.exportAs;
274
+
275
+ if (!symbols) {
276
+ symbols = [];
277
+ this.exportedSymbols.set(symbol, {
278
+ asset,
279
+ exportSymbol,
280
+ local: symbol,
281
+ exportAs: symbols
282
+ });
283
+ }
284
+
285
+ if (exportAs === '*') {
286
+ exportAs = 'default';
287
+ }
288
+
289
+ symbols.push(exportAs);
290
+ } else if (symbol === null) {// TODO `meta.exportsIdentifier[exportSymbol]` should be exported
291
+ // let relativePath = relative(options.projectRoot, asset.filePath);
292
+ // throw getThrowableDiagnosticForNode(
293
+ // md`${relativePath} couldn't be statically analyzed when importing '${exportSymbol}'`,
294
+ // entry.filePath,
295
+ // loc,
296
+ // );
297
+ } else if (symbol !== false) {// let relativePath = relative(options.projectRoot, asset.filePath);
298
+ // throw getThrowableDiagnosticForNode(
299
+ // md`${relativePath} does not export '${exportSymbol}'`,
300
+ // entry.filePath,
301
+ // loc,
302
+ // );
303
+ }
304
+ }
305
+ }
306
+ }
307
+
308
+ getTopLevelName(name) {
309
+ name = name.replace(NON_ID_CONTINUE_RE, '');
310
+
311
+ if (!ID_START_RE.test(name) || this.globalNames.has(name)) {
312
+ name = '_' + name;
313
+ }
314
+
315
+ let count = this.topLevelNames.get(name);
316
+
317
+ if (count == null) {
318
+ this.topLevelNames.set(name, 1);
319
+ return name;
320
+ }
321
+
322
+ this.topLevelNames.set(name, count + 1);
323
+ return name + count;
324
+ }
325
+
326
+ getPropertyAccess(obj, property) {
327
+ if (IDENTIFIER_RE.test(property)) {
328
+ return `${obj}.${property}`;
329
+ }
330
+
331
+ return `${obj}[${JSON.stringify(property)}]`;
332
+ }
333
+
334
+ visitAsset(asset) {
335
+ (0, _assert().default)(!this.seenAssets.has(asset.id), 'Already visited asset');
336
+ this.seenAssets.add(asset.id);
337
+ let {
338
+ code,
339
+ map
340
+ } = (0, _nullthrows().default)(this.assetOutputs.get(asset.id));
341
+ return this.buildAsset(asset, code, map);
342
+ }
343
+
344
+ buildAsset(asset, code, map) {
345
+ let shouldWrap = this.wrappedAssets.has(asset.id);
346
+ let deps = this.bundleGraph.getDependencies(asset);
347
+ let sourceMap = this.bundle.env.sourceMap && map ? new (_sourceMap2().default)(this.options.projectRoot, map) : null; // If this asset is skipped, just add dependencies and not the asset's content.
348
+
349
+ if (this.shouldSkipAsset(asset)) {
350
+ let depCode = '';
351
+ let lineCount = 0;
352
+
353
+ for (let dep of deps) {
354
+ let resolved = this.bundleGraph.getResolvedAsset(dep, this.bundle);
355
+ let skipped = this.bundleGraph.isDependencySkipped(dep);
356
+
357
+ if (!resolved || skipped) {
358
+ continue;
359
+ }
360
+
361
+ if (this.bundle.hasAsset(resolved) && !this.seenAssets.has(resolved.id)) {
362
+ let [code, map, lines] = this.visitAsset(resolved);
363
+ depCode += code + '\n';
364
+
365
+ if (sourceMap && map) {
366
+ sourceMap.addSourceMap(map, lineCount);
367
+ }
368
+
369
+ lineCount += lines + 1;
370
+ }
371
+ }
372
+
373
+ return [depCode, sourceMap, lineCount];
374
+ } // TODO: maybe a meta prop?
375
+
376
+
377
+ if (code.includes('$parcel$global')) {
378
+ this.usedHelpers.add('$parcel$global');
379
+ }
380
+
381
+ let [depMap, replacements] = this.buildReplacements(asset, deps);
382
+ let [prepend, prependLines, append] = this.buildAssetPrelude(asset, deps);
383
+
384
+ if (prependLines > 0) {
385
+ sourceMap === null || sourceMap === void 0 ? void 0 : sourceMap.offsetLines(1, prependLines);
386
+ code = prepend + code;
387
+ }
388
+
389
+ code += append;
390
+ let lineCount = 0;
391
+ let depContent = [];
392
+
393
+ if (depMap.size === 0 && replacements.size === 0) {
394
+ // If there are no dependencies or replacements, use a simple function to count the number of lines.
395
+ lineCount = (0, _utils().countLines)(code) - 1;
396
+ } else {
397
+ // Otherwise, use a regular expression to perform replacements.
398
+ // We need to track how many newlines there are for source maps, replace
399
+ // all import statements with dependency code, and perform inline replacements
400
+ // of all imported symbols with their resolved export symbols. This is all done
401
+ // in a single regex so that we only do one pass over the whole code.
402
+ let offset = 0;
403
+ let columnStartIndex = 0;
404
+ code = code.replace(REPLACEMENT_RE, (m, d, i) => {
405
+ var _replacements$get;
406
+
407
+ if (m === '\n') {
408
+ columnStartIndex = i + offset + 1;
409
+ lineCount++;
410
+ return '\n';
411
+ } // If we matched an import, replace with the source code for the dependency.
412
+
413
+
414
+ if (d != null) {
415
+ let dep = depMap.get(d);
416
+
417
+ if (!dep) {
418
+ return m;
419
+ }
420
+
421
+ let resolved = this.bundleGraph.getResolvedAsset(dep, this.bundle);
422
+ let skipped = this.bundleGraph.isDependencySkipped(dep);
423
+
424
+ if (resolved && !skipped) {
425
+ // Hoist variable declarations for the referenced parcelRequire dependencies
426
+ // after the dependency is declared. This handles the case where the resulting asset
427
+ // is wrapped, but the dependency in this asset is not marked as wrapped. This means
428
+ // that it was imported/required at the top-level, so its side effects should run immediately.
429
+ let [res, lines] = this.getHoistedParcelRequires(asset, dep, resolved);
430
+ let map;
431
+
432
+ if (this.bundle.hasAsset(resolved) && !this.seenAssets.has(resolved.id)) {
433
+ // If this asset is wrapped, we need to hoist the code for the dependency
434
+ // outside our parcelRequire.register wrapper. This is safe because all
435
+ // assets referenced by this asset will also be wrapped. Otherwise, inline the
436
+ // asset content where the import statement was.
437
+ if (shouldWrap) {
438
+ depContent.push(this.visitAsset(resolved));
439
+ } else {
440
+ let [depCode, depMap, depLines] = this.visitAsset(resolved);
441
+ res = depCode + '\n' + res;
442
+ lines += 1 + depLines;
443
+ map = depMap;
444
+ }
445
+ } // Push this asset's source mappings down by the number of lines in the dependency
446
+ // plus the number of hoisted parcelRequires. Then insert the source map for the dependency.
447
+
448
+
449
+ if (sourceMap) {
450
+ if (lines > 0) {
451
+ sourceMap.offsetLines(lineCount + 1, lines);
452
+ }
453
+
454
+ if (map) {
455
+ sourceMap.addSourceMap(map, lineCount);
456
+ }
457
+ }
458
+
459
+ lineCount += lines;
460
+ return res;
461
+ }
462
+
463
+ return '';
464
+ } // If it wasn't a dependency, then it was an inline replacement (e.g. $id$import$foo -> $id$export$foo).
465
+
466
+
467
+ let replacement = (_replacements$get = replacements.get(m)) !== null && _replacements$get !== void 0 ? _replacements$get : m;
468
+
469
+ if (sourceMap) {
470
+ // Offset the source map columns for this line if the replacement was a different length.
471
+ // This assumes that the match and replacement both do not contain any newlines.
472
+ let lengthDifference = replacement.length - m.length;
473
+
474
+ if (lengthDifference !== 0) {
475
+ sourceMap.offsetColumns(lineCount + 1, i + offset - columnStartIndex + m.length, lengthDifference);
476
+ offset += lengthDifference;
477
+ }
478
+ }
479
+
480
+ return replacement;
481
+ });
482
+ } // If the asset is wrapped, we need to insert the dependency code outside the parcelRequire.register
483
+ // wrapper. Dependencies must be inserted AFTER the asset is registered so that circular dependencies work.
484
+
485
+
486
+ if (shouldWrap) {
487
+ // Offset by one line for the parcelRequire.register wrapper.
488
+ sourceMap === null || sourceMap === void 0 ? void 0 : sourceMap.offsetLines(1, 1);
489
+ lineCount++;
490
+ code = `parcelRequire.register(${JSON.stringify(this.bundleGraph.getAssetPublicId(asset))}, function(module, exports) {
491
+ ${code}
492
+ });
493
+ `;
494
+ lineCount += 2;
495
+
496
+ for (let [depCode, map, lines] of depContent) {
497
+ if (!depCode) continue;
498
+ code += depCode + '\n';
499
+
500
+ if (sourceMap && map) {
501
+ sourceMap.addSourceMap(map, lineCount);
502
+ }
503
+
504
+ lineCount += lines + 1;
505
+ }
506
+
507
+ this.needsPrelude = true;
508
+ }
509
+
510
+ return [code, sourceMap, lineCount];
511
+ }
512
+
513
+ buildReplacements(asset, deps) {
514
+ let assetId = asset.meta.id;
515
+ (0, _assert().default)(typeof assetId === 'string'); // Build two maps: one of import specifiers, and one of imported symbols to replace.
516
+ // These will be used to build a regex below.
517
+
518
+ let depMap = new Map();
519
+ let replacements = new Map();
520
+
521
+ for (let dep of deps) {
522
+ depMap.set(`${assetId}:${(0, _utils2.getSpecifier)(dep)}`, dep);
523
+ let asyncResolution = this.bundleGraph.resolveAsyncDependency(dep, this.bundle);
524
+ let resolved = (asyncResolution === null || asyncResolution === void 0 ? void 0 : asyncResolution.type) === 'asset' ? // Prefer the underlying asset over a runtime to load it. It will
525
+ // be wrapped in Promise.resolve() later.
526
+ asyncResolution.value : this.bundleGraph.getResolvedAsset(dep, this.bundle);
527
+
528
+ if (!resolved && !dep.isOptional && !this.bundleGraph.isDependencySkipped(dep)) {
529
+ let external = this.addExternal(dep);
530
+
531
+ for (let [imported, {
532
+ local
533
+ }] of dep.symbols) {
534
+ // If already imported, just add the already renamed variable to the mapping.
535
+ let renamed = external.get(imported);
536
+
537
+ if (renamed && local !== '*') {
538
+ replacements.set(local, renamed);
539
+ continue;
540
+ } // For CJS output, always use a property lookup so that exports remain live.
541
+ // For ESM output, use named imports which are always live.
542
+
543
+
544
+ if (this.bundle.env.outputFormat === 'commonjs') {
545
+ renamed = external.get('*');
546
+
547
+ if (!renamed) {
548
+ renamed = this.getTopLevelName(`$${this.bundle.publicId}$${dep.specifier}`);
549
+ external.set('*', renamed);
550
+ }
551
+
552
+ if (local !== '*') {
553
+ let replacement;
554
+
555
+ if (imported === '*') {
556
+ replacement = renamed;
557
+ } else if (imported === 'default') {
558
+ replacement = `($parcel$interopDefault(${renamed}))`;
559
+ this.usedHelpers.add('$parcel$interopDefault');
560
+ } else {
561
+ replacement = this.getPropertyAccess(renamed, imported);
562
+ }
563
+
564
+ replacements.set(local, replacement);
565
+ }
566
+ } else {
567
+ // Rename the specifier so that multiple local imports of the same imported specifier
568
+ // are deduplicated. We have to prefix the imported name with the bundle id so that
569
+ // local variables do not shadow it.
570
+ if (this.exportedSymbols.has(local)) {
571
+ renamed = local;
572
+ } else if (imported === 'default' || imported === '*') {
573
+ renamed = this.getTopLevelName(`$${this.bundle.publicId}$${dep.specifier}`);
574
+ } else {
575
+ renamed = this.getTopLevelName(`$${this.bundle.publicId}$${imported}`);
576
+ }
577
+
578
+ external.set(imported, renamed);
579
+
580
+ if (local !== '*') {
581
+ replacements.set(local, renamed);
582
+ }
583
+ }
584
+ }
585
+ }
586
+
587
+ if (!resolved) {
588
+ continue;
589
+ }
590
+
591
+ for (let [imported, {
592
+ local
593
+ }] of dep.symbols) {
594
+ if (local === '*') {
595
+ continue;
596
+ }
597
+
598
+ let symbol = this.getSymbolResolution(asset, resolved, imported, dep);
599
+ replacements.set(local, // If this was an internalized async asset, wrap in a Promise.resolve.
600
+ (asyncResolution === null || asyncResolution === void 0 ? void 0 : asyncResolution.type) === 'asset' ? `Promise.resolve(${symbol})` : symbol);
601
+ } // Async dependencies need a namespace object even if all used symbols were statically analyzed.
602
+ // This is recorded in the promiseSymbol meta property set by the transformer rather than in
603
+ // symbols so that we don't mark all symbols as used.
604
+
605
+
606
+ if (dep.priority === 'lazy' && dep.meta.promiseSymbol) {
607
+ let promiseSymbol = dep.meta.promiseSymbol;
608
+ (0, _assert().default)(typeof promiseSymbol === 'string');
609
+ let symbol = this.getSymbolResolution(asset, resolved, '*', dep);
610
+ replacements.set(promiseSymbol, (asyncResolution === null || asyncResolution === void 0 ? void 0 : asyncResolution.type) === 'asset' ? `Promise.resolve(${symbol})` : symbol);
611
+ }
612
+ } // If this asset is wrapped, we need to replace the exports namespace with `module.exports`,
613
+ // which will be provided to us by the wrapper.
614
+
615
+
616
+ if (this.wrappedAssets.has(asset.id) || this.bundle.env.outputFormat === 'commonjs' && asset === this.bundle.getMainEntry()) {
617
+ var _asset$symbols$get;
618
+
619
+ let exportsName = ((_asset$symbols$get = asset.symbols.get('*')) === null || _asset$symbols$get === void 0 ? void 0 : _asset$symbols$get.local) || `$${assetId}$exports`;
620
+ replacements.set(exportsName, 'module.exports');
621
+ }
622
+
623
+ return [depMap, replacements];
624
+ }
625
+
626
+ addExternal(dep) {
627
+ if (this.bundle.env.outputFormat === 'global') {
628
+ throw new (_diagnostic().default)({
629
+ diagnostic: {
630
+ message: 'External modules are not supported when building for browser',
631
+ codeFrames: [{
632
+ filePath: (0, _nullthrows().default)(dep.sourcePath),
633
+ codeHighlights: dep.loc ? [{
634
+ start: dep.loc.start,
635
+ end: dep.loc.end
636
+ }] : []
637
+ }]
638
+ }
639
+ });
640
+ } // Map of DependencySpecifier -> Map<ExportedSymbol, Identifier>>
641
+
642
+
643
+ let external = this.externals.get(dep.specifier);
644
+
645
+ if (!external) {
646
+ external = new Map();
647
+ this.externals.set(dep.specifier, external);
648
+ }
649
+
650
+ return external;
651
+ }
652
+
653
+ getSymbolResolution(parentAsset, resolved, imported, dep) {
654
+ var _resolvedAsset$symbol;
655
+
656
+ let {
657
+ asset: resolvedAsset,
658
+ exportSymbol,
659
+ symbol
660
+ } = this.bundleGraph.getSymbolResolution(resolved, imported, this.bundle);
661
+
662
+ if (resolvedAsset.type !== 'js') {
663
+ // Graceful fallback for non-js imports
664
+ return '{}';
665
+ }
666
+
667
+ let isWrapped = !this.bundle.hasAsset(resolvedAsset) || this.wrappedAssets.has(resolvedAsset.id) && resolvedAsset !== parentAsset;
668
+ let staticExports = resolvedAsset.meta.staticExports !== false;
669
+ let publicId = this.bundleGraph.getAssetPublicId(resolvedAsset); // If the rsolved asset is wrapped, but imported at the top-level by this asset,
670
+ // then we hoist parcelRequire calls to the top of this asset so side effects run immediately.
671
+
672
+ if (isWrapped && dep && !(dep !== null && dep !== void 0 && dep.meta.shouldWrap) && symbol !== false) {
673
+ let hoisted = this.hoistedRequires.get(dep.id);
674
+
675
+ if (!hoisted) {
676
+ hoisted = new Map();
677
+ this.hoistedRequires.set(dep.id, hoisted);
678
+ }
679
+
680
+ hoisted.set(resolvedAsset.id, `var $${publicId} = parcelRequire(${JSON.stringify(publicId)});`);
681
+ }
682
+
683
+ if (isWrapped) {
684
+ this.needsPrelude = true;
685
+ } // If this is an ESM default import of a CJS module with a `default` symbol,
686
+ // and no __esModule flag, we need to resolve to the namespace instead.
687
+
688
+
689
+ let isDefaultInterop = exportSymbol === 'default' && staticExports && !isWrapped && ((dep === null || dep === void 0 ? void 0 : dep.meta.kind) === 'Import' || (dep === null || dep === void 0 ? void 0 : dep.meta.kind) === 'Export') && resolvedAsset.symbols.hasExportSymbol('*') && resolvedAsset.symbols.hasExportSymbol('default') && !resolvedAsset.symbols.hasExportSymbol('__esModule'); // Find the namespace object for the resolved module. If wrapped and this
690
+ // is an inline require (not top-level), use a parcelRequire call, otherwise
691
+ // the hoisted variable declared above. Otherwise, if not wrapped, use the
692
+ // namespace export symbol.
693
+
694
+ let assetId = resolvedAsset.meta.id;
695
+ (0, _assert().default)(typeof assetId === 'string');
696
+ let obj = isWrapped && (!dep || dep !== null && dep !== void 0 && dep.meta.shouldWrap) ? // Wrap in extra parenthesis to not change semantics, e.g.`new (parcelRequire("..."))()`.
697
+ `(parcelRequire(${JSON.stringify(publicId)}))` : isWrapped && dep ? `$${publicId}` : ((_resolvedAsset$symbol = resolvedAsset.symbols.get('*')) === null || _resolvedAsset$symbol === void 0 ? void 0 : _resolvedAsset$symbol.local) || `$${assetId}$exports`;
698
+
699
+ if (imported === '*' || exportSymbol === '*' || isDefaultInterop) {
700
+ // Resolve to the namespace object if requested or this is a CJS default interop reqiure.
701
+ return obj;
702
+ } else if ((!staticExports || isWrapped || !symbol) && resolvedAsset !== parentAsset) {
703
+ // If the resolved asset is wrapped or has non-static exports,
704
+ // we need to use a member access off the namespace object rather
705
+ // than a direct reference. If importing default from a CJS module,
706
+ // use a helper to check the __esModule flag at runtime.
707
+ let kind = dep === null || dep === void 0 ? void 0 : dep.meta.kind;
708
+
709
+ if ((!dep || kind === 'Import' || kind === 'Export') && exportSymbol === 'default' && resolvedAsset.symbols.hasExportSymbol('*') && this.needsDefaultInterop(resolvedAsset)) {
710
+ this.usedHelpers.add('$parcel$interopDefault');
711
+ return `(/*@__PURE__*/$parcel$interopDefault(${obj}))`;
712
+ } else {
713
+ return this.getPropertyAccess(obj, exportSymbol);
714
+ }
715
+ } else if (!symbol) {
716
+ (0, _assert().default)(false, 'Asset was skipped or not found.');
717
+ } else {
718
+ return symbol;
719
+ }
720
+ }
721
+
722
+ getHoistedParcelRequires(parentAsset, dep, resolved) {
723
+ if (resolved.type !== 'js') {
724
+ return ['', 0];
725
+ }
726
+
727
+ let hoisted = this.hoistedRequires.get(dep.id);
728
+ let res = '';
729
+ let lineCount = 0;
730
+ let isWrapped = !this.bundle.hasAsset(resolved) || this.wrappedAssets.has(resolved.id) && resolved !== parentAsset; // If the resolved asset is wrapped and is imported in the top-level by this asset,
731
+ // we need to run side effects when this asset runs. If the resolved asset is not
732
+ // the first one in the hoisted requires, we need to insert a parcelRequire here
733
+ // so it runs first.
734
+
735
+ if (isWrapped && !dep.meta.shouldWrap && (!hoisted || hoisted.keys().next().value !== resolved.id) && !this.bundleGraph.isDependencySkipped(dep) && !this.shouldSkipAsset(resolved)) {
736
+ this.needsPrelude = true;
737
+ res += `parcelRequire(${JSON.stringify(this.bundleGraph.getAssetPublicId(resolved))});`;
738
+ }
739
+
740
+ if (hoisted) {
741
+ this.needsPrelude = true;
742
+ res += '\n' + [...hoisted.values()].join('\n');
743
+ lineCount += hoisted.size;
744
+ }
745
+
746
+ return [res, lineCount];
747
+ }
748
+
749
+ buildAssetPrelude(asset, deps) {
750
+ let prepend = '';
751
+ let prependLineCount = 0;
752
+ let append = '';
753
+ let shouldWrap = this.wrappedAssets.has(asset.id);
754
+ let usedSymbols = (0, _nullthrows().default)(this.bundleGraph.getUsedSymbols(asset));
755
+ let assetId = asset.meta.id;
756
+ (0, _assert().default)(typeof assetId === 'string'); // If the asset has a namespace export symbol, it is CommonJS.
757
+ // If there's no __esModule flag, and default is a used symbol, we need
758
+ // to insert an interop helper.
759
+
760
+ let defaultInterop = asset.symbols.hasExportSymbol('*') && usedSymbols.has('default') && !asset.symbols.hasExportSymbol('__esModule');
761
+ let usedNamespace = // If the asset has * in its used symbols, we might need the exports namespace.
762
+ // The one case where this isn't true is in ESM library entries, where the only
763
+ // dependency on * is the entry dependency. In this case, we will use ESM exports
764
+ // instead of the namespace object.
765
+ usedSymbols.has('*') && (this.bundle.env.outputFormat !== 'esmodule' || !this.bundle.env.isLibrary || asset !== this.bundle.getMainEntry() || this.bundleGraph.getIncomingDependencies(asset).some(dep => !dep.isEntry && (0, _nullthrows().default)(this.bundleGraph.getUsedSymbols(dep)).has('*'))) || // If a symbol is imported (used) from a CJS asset but isn't listed in the symbols,
766
+ // we fallback on the namespace object.
767
+ asset.symbols.hasExportSymbol('*') && [...usedSymbols].some(s => !asset.symbols.hasExportSymbol(s)) || // If the exports has this asset's namespace (e.g. ESM output from CJS input),
768
+ // include the namespace object for the default export.
769
+ this.exportedSymbols.has(`$${assetId}$exports`); // If the asset doesn't have static exports, should wrap, the namespace is used,
770
+ // or we need default interop, then we need to synthesize a namespace object for
771
+ // this asset.
772
+
773
+ if (asset.meta.staticExports === false || shouldWrap || usedNamespace || defaultInterop) {
774
+ // Insert a declaration for the exports namespace object. If the asset is wrapped
775
+ // we don't need to do this, because we'll use the `module.exports` object provided
776
+ // by the wrapper instead. This is also true of CommonJS entry assets, which will use
777
+ // the `module.exports` object provided by CJS.
778
+ if (!shouldWrap && (this.bundle.env.outputFormat !== 'commonjs' || asset !== this.bundle.getMainEntry())) {
779
+ prepend += `var $${assetId}$exports = {};\n`;
780
+ prependLineCount++;
781
+ } // Insert the __esModule interop flag for this module if it has a `default` export
782
+ // and the namespace symbol is used.
783
+ // TODO: only if required by CJS?
784
+
785
+
786
+ if (asset.symbols.hasExportSymbol('default') && usedSymbols.has('*')) {
787
+ prepend += `\n$parcel$defineInteropFlag($${assetId}$exports);\n`;
788
+ prependLineCount += 2;
789
+ this.usedHelpers.add('$parcel$defineInteropFlag');
790
+ } // Find the used exports of this module. This is based on the used symbols of
791
+ // incoming dependencies rather than the asset's own used exports so that we include
792
+ // re-exported symbols rather than only symbols declared in this asset.
793
+
794
+
795
+ let incomingDeps = this.bundleGraph.getIncomingDependencies(asset);
796
+ let usedExports = [...asset.symbols.exportSymbols()].filter(symbol => {
797
+ if (symbol === '*') {
798
+ return false;
799
+ } // If we need default interop, then all symbols are needed because the `default`
800
+ // symbol really maps to the whole namespace.
801
+
802
+
803
+ if (defaultInterop) {
804
+ return true;
805
+ }
806
+
807
+ let unused = incomingDeps.every(d => {
808
+ let symbols = (0, _nullthrows().default)(this.bundleGraph.getUsedSymbols(d));
809
+ return !symbols.has(symbol) && !symbols.has('*');
810
+ });
811
+ return !unused;
812
+ });
813
+
814
+ if (usedExports.length > 0) {
815
+ // Insert $parcel$export calls for each of the used exports. This creates a getter/setter
816
+ // for the symbol so that when the value changes the object property also changes. This is
817
+ // required to simulate ESM live bindings. It's easier to do it this way rather than inserting
818
+ // additional assignments after each mutation of the original binding.
819
+ prepend += `\n${usedExports.map(exp => {
820
+ let resolved = this.getSymbolResolution(asset, asset, exp);
821
+ let get = this.buildFunctionExpression([], resolved);
822
+ let set = asset.meta.hasCJSExports ? ', ' + this.buildFunctionExpression(['v'], `${resolved} = v`) : '';
823
+ return `$parcel$export($${assetId}$exports, ${JSON.stringify(exp)}, ${get}${set});`;
824
+ }).join('\n')}\n`;
825
+ this.usedHelpers.add('$parcel$export');
826
+ prependLineCount += 1 + usedExports.length;
827
+ } // Find wildcard re-export dependencies, and make sure their exports are also included in ours.
828
+
829
+
830
+ for (let dep of deps) {
831
+ let resolved = this.bundleGraph.getResolvedAsset(dep, this.bundle);
832
+
833
+ if (dep.isOptional || this.bundleGraph.isDependencySkipped(dep)) {
834
+ continue;
835
+ }
836
+
837
+ let isWrapped = resolved && resolved.meta.shouldWrap;
838
+
839
+ for (let [imported, {
840
+ local
841
+ }] of dep.symbols) {
842
+ if (imported === '*' && local === '*') {
843
+ if (!resolved) {
844
+ // Re-exporting an external module. This should have already been handled in buildReplacements.
845
+ let external = (0, _nullthrows().default)((0, _nullthrows().default)(this.externals.get(dep.specifier)).get('*'));
846
+ append += `$parcel$exportWildcard($${assetId}$exports, ${external});\n`;
847
+ this.usedHelpers.add('$parcel$exportWildcard');
848
+ continue;
849
+ } // If the resolved asset has an exports object, use the $parcel$exportWildcard helper
850
+ // to re-export all symbols. Otherwise, if there's no namespace object available, add
851
+ // $parcel$export calls for each used symbol of the dependency.
852
+
853
+
854
+ if (isWrapped || resolved.meta.staticExports === false || (0, _nullthrows().default)(this.bundleGraph.getUsedSymbols(resolved)).has('*') || // an empty asset
855
+ !resolved.meta.hasCJSExports && resolved.symbols.hasExportSymbol('*')) {
856
+ let obj = this.getSymbolResolution(asset, resolved, '*', dep);
857
+ append += `$parcel$exportWildcard($${assetId}$exports, ${obj});\n`;
858
+ this.usedHelpers.add('$parcel$exportWildcard');
859
+ } else {
860
+ for (let symbol of (0, _nullthrows().default)(this.bundleGraph.getUsedSymbols(dep))) {
861
+ if (symbol === 'default' || // `export * as ...` does not include the default export
862
+ symbol === '__esModule') {
863
+ continue;
864
+ }
865
+
866
+ let resolvedSymbol = this.getSymbolResolution(asset, resolved, symbol);
867
+ let get = this.buildFunctionExpression([], resolvedSymbol);
868
+ let set = asset.meta.hasCJSExports ? ', ' + this.buildFunctionExpression(['v'], `${resolvedSymbol} = v`) : '';
869
+ prepend += `$parcel$export($${assetId}$exports, ${JSON.stringify(symbol)}, ${get}${set});\n`;
870
+ this.usedHelpers.add('$parcel$export');
871
+ prependLineCount++;
872
+ }
873
+ }
874
+ }
875
+ }
876
+ }
877
+ }
878
+
879
+ return [prepend, prependLineCount, append];
880
+ }
881
+
882
+ buildBundlePrelude() {
883
+ let enableSourceMaps = this.bundle.env.sourceMap;
884
+ let res = '';
885
+ let lines = 0; // Add hashbang if the entry asset recorded an interpreter.
886
+
887
+ let mainEntry = this.bundle.getMainEntry();
888
+
889
+ if (mainEntry && !this.isAsyncBundle && !this.bundle.target.env.isBrowser()) {
890
+ let interpreter = mainEntry.meta.interpreter;
891
+ (0, _assert().default)(interpreter == null || typeof interpreter === 'string');
892
+
893
+ if (interpreter != null) {
894
+ res += `#!${interpreter}\n`;
895
+ lines++;
896
+ }
897
+ } // The output format may have specific things to add at the start of the bundle (e.g. imports).
898
+
899
+
900
+ let [outputFormatPrelude, outputFormatLines] = this.outputFormat.buildBundlePrelude();
901
+ res += outputFormatPrelude;
902
+ lines += outputFormatLines; // Add used helpers.
903
+
904
+ if (this.needsPrelude) {
905
+ this.usedHelpers.add('$parcel$global');
906
+ }
907
+
908
+ for (let helper of this.usedHelpers) {
909
+ res += _helpers.helpers[helper];
910
+
911
+ if (enableSourceMaps) {
912
+ lines += (0, _utils().countLines)(_helpers.helpers[helper]) - 1;
913
+ }
914
+ }
915
+
916
+ if (this.needsPrelude) {
917
+ // Add the prelude if this is potentially the first JS bundle to load in a
918
+ // particular context (e.g. entry scripts in HTML, workers, etc.).
919
+ let parentBundles = this.bundleGraph.getParentBundles(this.bundle);
920
+ 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';
921
+
922
+ if (mightBeFirstJS) {
923
+ let preludeCode = (0, _helpers.prelude)(this.parcelRequireName);
924
+ res += preludeCode;
925
+
926
+ if (enableSourceMaps) {
927
+ lines += (0, _utils().countLines)(preludeCode) - 1;
928
+ }
929
+ } else {
930
+ // Otherwise, get the current parcelRequire global.
931
+ res += `var parcelRequire = $parcel$global[${JSON.stringify(this.parcelRequireName)}];\n`;
932
+ lines++;
933
+ }
934
+ } // Add importScripts for sibling bundles in workers.
935
+
936
+
937
+ if (this.bundle.env.isWorker() || this.bundle.env.isWorklet()) {
938
+ let importScripts = '';
939
+ let bundles = this.bundleGraph.getReferencedBundles(this.bundle);
940
+
941
+ for (let b of bundles) {
942
+ if (this.bundle.env.outputFormat === 'esmodule') {
943
+ // importScripts() is not allowed in native ES module workers.
944
+ importScripts += `import "${(0, _utils().relativeBundlePath)(this.bundle, b)}";\n`;
945
+ } else {
946
+ importScripts += `importScripts("${(0, _utils().relativeBundlePath)(this.bundle, b)}");\n`;
947
+ }
948
+ }
949
+
950
+ res += importScripts;
951
+ lines += bundles.length;
952
+ }
953
+
954
+ return [res, lines];
955
+ }
956
+
957
+ needsDefaultInterop(asset) {
958
+ if (asset.symbols.hasExportSymbol('*') && !asset.symbols.hasExportSymbol('default')) {
959
+ let deps = this.bundleGraph.getIncomingDependencies(asset);
960
+ return deps.some(dep => this.bundle.hasDependency(dep) && // dep.meta.isES6Module &&
961
+ dep.symbols.hasExportSymbol('default'));
962
+ }
963
+
964
+ return false;
965
+ }
966
+
967
+ shouldSkipAsset(asset) {
968
+ if (this.isScriptEntry(asset)) {
969
+ return true;
970
+ }
971
+
972
+ return asset.sideEffects === false && (0, _nullthrows().default)(this.bundleGraph.getUsedSymbols(asset)).size == 0 && !this.bundleGraph.isAssetReferenced(this.bundle, asset);
973
+ }
974
+
975
+ isScriptEntry(asset) {
976
+ return this.bundle.env.outputFormat === 'global' && this.bundle.env.sourceType === 'script' && asset === this.bundle.getMainEntry();
977
+ }
978
+
979
+ buildFunctionExpression(args, expr) {
980
+ return this.bundle.env.supports('arrow-functions', true) ? `(${args.join(', ')}) => ${expr}` : `function (${args.join(', ')}) { return ${expr}; }`;
981
+ }
982
+
983
+ }
984
+
985
+ exports.ScopeHoistingPackager = ScopeHoistingPackager;