/
JSConcatPackager.js
596 lines (509 loc) Β· 15.9 KB
/
JSConcatPackager.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
const Packager = require('./Packager');
const path = require('path');
const fs = require('fs');
const concat = require('../scope-hoisting/concat');
const urlJoin = require('../utils/urlJoin');
const walk = require('babylon-walk');
const babylon = require('babylon');
const t = require('babel-types');
const prelude = {
source: fs
.readFileSync(path.join(__dirname, '../builtins/prelude2.js'), 'utf8')
.trim(),
minified: fs
.readFileSync(path.join(__dirname, '../builtins/prelude2.min.js'), 'utf8')
.trim()
.replace(/;$/, '')
};
const helpers =
fs
.readFileSync(path.join(__dirname, '../builtins/helpers.js'), 'utf8')
.trim() + '\n';
class JSConcatPackager extends Packager {
async start() {
this.addedAssets = new Set();
this.assets = new Map();
this.exposedModules = new Set();
this.externalModules = new Set();
this.size = 0;
this.needsPrelude = false;
this.statements = [];
this.assetPostludes = new Map();
for (let asset of this.bundle.assets) {
// If this module is referenced by another JS bundle, it needs to be exposed externally.
let isExposed = !Array.from(asset.parentDeps).every(dep => {
let depAsset = this.bundler.loadedAssets.get(dep.parent);
return this.bundle.assets.has(depAsset) || depAsset.type !== 'js';
});
if (
isExposed ||
(this.bundle.entryAsset === asset &&
this.bundle.parentBundle &&
this.bundle.parentBundle.childBundles.size !== 1)
) {
this.exposedModules.add(asset);
this.needsPrelude = true;
}
this.assets.set(asset.id, asset);
for (let mod of asset.depAssets.values()) {
if (
!this.bundle.assets.has(mod) &&
this.options.bundleLoaders[asset.type]
) {
this.needsPrelude = true;
break;
}
}
}
if (this.bundle.entryAsset) {
this.markUsedExports(this.bundle.entryAsset);
}
if (this.needsPrelude) {
if (
this.bundle.entryAsset &&
this.options.bundleLoaders[this.bundle.entryAsset.type]
) {
this.exposedModules.add(this.bundle.entryAsset);
}
}
this.write(helpers);
}
write(string) {
this.statements.push(...this.parse(string));
}
getSize() {
return this.size;
}
markUsedExports(asset) {
if (asset.usedExports) {
return;
}
asset.usedExports = new Set();
for (let identifier in asset.cacheData.imports) {
let [source, name] = asset.cacheData.imports[identifier];
let dep = asset.depAssets.get(asset.dependencies.get(source));
if (name === '*') {
this.markUsedExports(dep);
}
this.markUsed(dep, name);
}
}
markUsed(mod, name) {
let {id} = this.findExportModule(mod.id, name);
mod = this.assets.get(id);
if (!mod) {
return;
}
let exp = mod.cacheData.exports[name];
if (Array.isArray(exp)) {
let depMod = mod.depAssets.get(mod.dependencies.get(exp[0]));
return this.markUsed(depMod, exp[1]);
}
this.markUsedExports(mod);
mod.usedExports.add(name);
}
getExportIdentifier(asset) {
let id = '$' + asset.id + '$exports';
if (this.shouldWrap(asset)) {
return `($${asset.id}$init(), ${id})`;
}
return id;
}
async addAsset(asset) {
if (this.addedAssets.has(asset)) {
return;
}
this.addedAssets.add(asset);
let {js} = asset.generated;
// If the asset's package has the sideEffects: false flag set, and there are no used
// exports marked, exclude the asset from the bundle.
if (
asset.cacheData.sideEffects === false &&
(!asset.usedExports || asset.usedExports.size === 0)
) {
return;
}
for (let [dep, mod] of asset.depAssets) {
if (dep.dynamic && this.bundle.childBundles.has(mod.parentBundle)) {
for (let child of mod.parentBundle.siblingBundles) {
if (!child.isEmpty) {
await this.addBundleLoader(child.type, asset);
}
}
await this.addBundleLoader(mod.type, asset, true);
} else {
// If the dep isn't in this bundle, add it to the list of external modules to preload.
// Only do this if this is the root JS bundle, otherwise they will have already been
// loaded in parallel with this bundle as part of a dynamic import.
if (
!this.bundle.assets.has(mod) &&
(!this.bundle.parentBundle ||
this.bundle.parentBundle.type !== 'js') &&
this.options.bundleLoaders[mod.type]
) {
this.externalModules.add(mod);
await this.addBundleLoader(mod.type, asset);
}
}
}
// if (this.bundle.entryAsset === asset && this.externalModules.size > 0) {
// js = `
// function $parcel$entry() {
// ${js.trim()}
// }
// `;
// }
// js = js.trim() + '\n';
this.size += js.length;
}
shouldWrap(asset) {
if (!asset) {
return false;
}
if (asset.cacheData.shouldWrap != null) {
return asset.cacheData.shouldWrap;
}
// Set to false initially so circular deps work
asset.cacheData.shouldWrap = false;
// We need to wrap if any of the deps are marked by the hoister, e.g.
// when the dep is required inside a function or conditional.
// We also need to wrap if any of the parents are wrapped - transitive requires
// shouldn't be evaluated until their parents are.
let shouldWrap = [...asset.parentDeps].some(
dep =>
dep.shouldWrap ||
this.shouldWrap(this.bundler.loadedAssets.get(dep.parent))
);
asset.cacheData.shouldWrap = shouldWrap;
return shouldWrap;
}
addDeps(asset, included) {
if (!this.bundle.assets.has(asset) || included.has(asset)) {
return [];
}
included.add(asset);
let depAsts = new Map();
for (let depAsset of asset.depAssets.values()) {
let depAst = this.addDeps(depAsset, included);
depAsts.set(depAsset, depAst);
}
let statements;
if (
asset.cacheData.sideEffects === false &&
(!asset.usedExports || asset.usedExports.size === 0)
) {
statements = [];
} else {
statements = this.parse(asset.generated.js, asset.name);
}
if (this.shouldWrap(asset)) {
statements = this.wrapModule(asset, statements);
}
if (statements[0]) {
if (!statements[0].leadingComments) {
statements[0].leadingComments = [];
}
statements[0].leadingComments.push({
type: 'CommentLine',
value: ` ASSET: ${path.relative(this.options.rootDir, asset.name)}`
});
}
let statementIndices = new Map();
for (let i = 0; i < statements.length; i++) {
let statement = statements[i];
if (t.isExpressionStatement(statement)) {
for (let depAsset of this.findRequires(asset, statement)) {
if (!statementIndices.has(depAsset)) {
statementIndices.set(depAsset, i);
}
}
}
}
let reverseDeps = [...asset.depAssets.values()].reverse();
for (let dep of reverseDeps) {
let index = statementIndices.has(dep) ? statementIndices.get(dep) : 0;
statements.splice(index, 0, ...depAsts.get(dep));
}
if (this.assetPostludes.has(asset)) {
statements.push(...this.parse(this.assetPostludes.get(asset)));
}
return statements;
}
wrapModule(asset, statements) {
let body = [];
let decls = [];
let fns = [];
for (let node of statements) {
// Hoist all declarations out of the function wrapper
// so that they can be referenced by other modules directly.
if (t.isVariableDeclaration(node)) {
for (let decl of node.declarations) {
decls.push(t.variableDeclarator(decl.id));
if (decl.init) {
body.push(
t.expressionStatement(
t.assignmentExpression(
'=',
t.identifier(decl.id.name),
decl.init
)
)
);
}
}
} else if (t.isFunctionDeclaration(node)) {
// Function declarations can be hoisted out of the module initialization function
fns.push(node);
} else if (t.isClassDeclaration(node)) {
// Class declarations are not hoisted. We declare a variable outside the
// function convert to a class expression assignment.
decls.push(t.variableDeclarator(t.identifier(node.id.name)));
body.push(
t.expressionStatement(
t.assignmentExpression(
'=',
t.identifier(node.id.name),
t.toExpression(node)
)
)
);
} else {
body.push(node);
}
}
let executed = `$${asset.id}$executed`;
decls.push(
t.variableDeclarator(t.identifier(executed), t.booleanLiteral(false))
);
let init = t.functionDeclaration(
t.identifier(`$${asset.id}$init`),
[],
t.blockStatement([
t.ifStatement(t.identifier(executed), t.returnStatement()),
t.expressionStatement(
t.assignmentExpression(
'=',
t.identifier(executed),
t.booleanLiteral(true)
)
),
...body
])
);
return [t.variableDeclaration('var', decls), ...fns, init];
}
parse(code, filename) {
let ast = babylon.parse(code, {
sourceFilename: filename,
allowReturnOutsideFunction: true
});
return ast.program.body;
}
findRequires(asset, ast) {
let result = [];
walk.simple(ast, {
CallExpression(node) {
let {arguments: args, callee} = node;
if (!t.isIdentifier(callee)) {
return;
}
if (callee.name === '$parcel$require') {
result.push(
asset.depAssets.get(asset.dependencies.get(args[1].value))
);
}
}
});
return result;
}
getBundleSpecifier(bundle) {
let name = path.basename(bundle.name);
if (bundle.entryAsset) {
return [name, bundle.entryAsset.id];
}
return name;
}
async addAssetToBundle(asset) {
if (this.bundle.assets.has(asset)) {
return;
}
this.bundle.addAsset(asset);
if (!asset.parentBundle) {
asset.parentBundle = this.bundle;
}
// Add all dependencies as well
for (let child of asset.depAssets.values()) {
await this.addAssetToBundle(child, this.bundle);
}
await this.addAsset(asset);
}
async addBundleLoader(bundleType, parentAsset, dynamic) {
let loader = this.options.bundleLoaders[bundleType];
if (!loader) {
return;
}
let bundleLoader = this.bundler.loadedAssets.get(
require.resolve('../builtins/bundle-loader')
);
if (!bundleLoader && !dynamic) {
bundleLoader = await this.bundler.getAsset('_bundle_loader');
}
if (bundleLoader) {
// parentAsset.depAssets.set({name: '_bundle_loader'}, bundleLoader);
await this.addAssetToBundle(bundleLoader);
} else {
return;
}
let target = this.options.target === 'node' ? 'node' : 'browser';
let asset = await this.bundler.getAsset(loader[target]);
if (!this.bundle.assets.has(asset)) {
let dep = {name: asset.name};
asset.parentDeps.add(dep);
parentAsset.dependencies.set(dep.name, dep);
parentAsset.depAssets.set(dep, asset);
this.assetPostludes.set(
asset,
`${this.getExportIdentifier(bundleLoader)}.register(${JSON.stringify(
bundleType
)},${this.getExportIdentifier(asset)});\n`
);
await this.addAssetToBundle(asset);
}
}
async end() {
let included = new Set();
for (let asset of this.bundle.assets) {
this.statements.push(...this.addDeps(asset, included));
}
// Preload external modules before running entry point if needed
if (this.externalModules.size > 0) {
let bundleLoader = this.bundler.loadedAssets.get(
require.resolve('../builtins/bundle-loader')
);
let preload = [];
for (let mod of this.externalModules) {
// Find the bundle that has the module as its entry point
let bundle = Array.from(mod.bundles).find(b => b.entryAsset === mod);
if (bundle) {
preload.push([path.basename(bundle.name), mod.id]);
}
}
let loads = `${this.getExportIdentifier(
bundleLoader
)}.load(${JSON.stringify(preload)})`;
if (this.bundle.entryAsset) {
loads += '.then($parcel$entry)';
}
loads += ';';
this.write(loads);
}
let entryExports =
this.bundle.entryAsset &&
this.getExportIdentifier(this.bundle.entryAsset);
if (
entryExports &&
this.bundle.entryAsset.generated.js.includes(entryExports)
) {
this.write(`
if (typeof exports === "object" && typeof module !== "undefined") {
// CommonJS
module.exports = ${entryExports};
} else if (typeof define === "function" && define.amd) {
// RequireJS
define(function () {
return ${entryExports};
});
} ${
this.options.global
? `else {
// <script>
this[${JSON.stringify(this.options.global)}] = ${entryExports};
}`
: ''
}
`);
}
if (this.needsPrelude) {
let exposed = [];
let prepareModule = [];
for (let m of this.exposedModules) {
if (m.cacheData.isES6Module) {
prepareModule.push(
`${this.getExportIdentifier(m)}.__esModule = true;`
);
}
exposed.push(`${m.id}: ${this.getExportIdentifier(m)}`);
}
this.write(`
${prepareModule.join('\n')}
return {${exposed.join(', ')}};
`);
}
let ast = t.file(t.program(this.statements));
let {code: output} = concat(this, ast);
if (!this.options.minify) {
output = '\n' + output + '\n';
}
let preludeCode = this.options.minify ? prelude.minified : prelude.source;
if (this.needsPrelude) {
output = preludeCode + '(function (require) {' + output + '});';
} else {
output = '(function () {' + output + '})();';
}
this.size = output.length;
let {sourceMaps} = this.options;
if (sourceMaps) {
// Add source map url if a map bundle exists
let mapBundle = this.bundle.siblingBundlesMap.get('map');
if (mapBundle) {
output += `\n//# sourceMappingURL=${urlJoin(
this.options.publicURL,
path.basename(mapBundle.name)
)}`;
}
}
await super.write(output);
}
resolveModule(id, name) {
let module = this.assets.get(+id);
return module.depAssets.get(module.dependencies.get(name));
}
findExportModule(id, name, replacements) {
let asset = this.assets.get(+id);
let exp =
asset &&
Object.prototype.hasOwnProperty.call(asset.cacheData.exports, name)
? asset.cacheData.exports[name]
: null;
// If this is a re-export, find the original module.
if (Array.isArray(exp)) {
let mod = this.resolveModule(id, exp[0]);
return this.findExportModule(mod.id, exp[1], replacements);
}
// If this module exports wildcards, resolve the original module.
// Default exports are excluded from wildcard exports.
let wildcards = asset && asset.cacheData.wildcards;
if (wildcards && name !== 'default' && name !== '*') {
for (let source of wildcards) {
let mod = this.resolveModule(id, source);
let m = this.findExportModule(mod.id, name, replacements);
if (m.identifier) {
return m;
}
}
}
// If this is a wildcard import, resolve to the exports object.
if (asset && name === '*') {
exp = `$${id}$exports`;
}
if (replacements && replacements.has(exp)) {
exp = replacements.get(exp);
}
return {
identifier: exp,
name,
id
};
}
}
module.exports = JSConcatPackager;