/
Bundle.js
661 lines (533 loc) · 19.8 KB
/
Bundle.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
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
import { timeStart, timeEnd } from './utils/flushTime.js';
import { decode } from 'sourcemap-codec';
import { Bundle as MagicStringBundle } from 'magic-string';
import first from './utils/first.js';
import { find } from './utils/array.js';
import { blank, forOwn, keys } from './utils/object.js';
import Module from './Module.js';
import ExternalModule from './ExternalModule.js';
import finalisers from './finalisers/index.js';
import ensureArray from './utils/ensureArray.js';
import { load, makeOnwarn, resolveId } from './utils/defaults.js';
import getExportMode from './utils/getExportMode.js';
import getIndentString from './utils/getIndentString.js';
import { mapSequence } from './utils/promise.js';
import transform from './utils/transform.js';
import transformBundle from './utils/transformBundle.js';
import collapseSourcemaps from './utils/collapseSourcemaps.js';
import callIfFunction from './utils/callIfFunction.js';
import relativeId from './utils/relativeId.js';
import error from './utils/error.js';
import { dirname, isRelative, isAbsolute, normalize, relative, resolve } from './utils/path.js';
import BundleScope from './ast/scopes/BundleScope.js';
export default class Bundle {
constructor ( options ) {
this.cachedModules = new Map();
if ( options.cache ) {
options.cache.modules.forEach( module => {
this.cachedModules.set( module.id, module );
} );
}
this.plugins = ensureArray( options.plugins );
options = this.plugins.reduce( ( acc, plugin ) => {
if ( plugin.options ) return plugin.options( acc ) || acc;
return acc;
}, options );
if ( !options.entry ) {
throw new Error( 'You must supply options.entry to rollup' );
}
this.entry = options.entry;
this.entryId = null;
this.entryModule = null;
this.treeshake = options.treeshake !== false;
if ( options.pureExternalModules === true ) {
this.isPureExternalModule = () => true;
} else if ( typeof options.pureExternalModules === 'function' ) {
this.isPureExternalModule = options.pureExternalModules;
} else if ( Array.isArray( options.pureExternalModules ) ) {
const pureExternalModules = new Set( options.pureExternalModules );
this.isPureExternalModule = id => pureExternalModules.has( id );
} else {
this.isPureExternalModule = () => false;
}
this.resolveId = first(
[ id => this.isExternal( id ) ? false : null ]
.concat( this.plugins.map( plugin => plugin.resolveId ).filter( Boolean ) )
.concat( resolveId )
);
const loaders = this.plugins
.map( plugin => plugin.load )
.filter( Boolean );
this.hasLoaders = loaders.length !== 0;
this.load = first( loaders.concat( load ) );
const optionsPaths = options.paths;
this.getPath = typeof optionsPaths === 'function' ?
( id => optionsPaths( id ) || this.getPathRelativeToEntryDirname( id ) ) :
optionsPaths ?
( id => optionsPaths.hasOwnProperty( id ) ? optionsPaths[ id ] : this.getPathRelativeToEntryDirname( id ) ) :
id => this.getPathRelativeToEntryDirname( id );
this.scope = new BundleScope();
// TODO strictly speaking, this only applies with non-ES6, non-default-only bundles
[ 'module', 'exports', '_interopDefault' ].forEach( name => {
this.scope.findDeclaration( name ); // creates global declaration as side-effect
} );
this.moduleById = new Map();
this.modules = [];
this.externalModules = [];
this.context = String( options.context );
const optionsModuleContext = options.moduleContext;
if ( typeof optionsModuleContext === 'function' ) {
this.getModuleContext = id => optionsModuleContext( id ) || this.context;
} else if ( typeof optionsModuleContext === 'object' ) {
const moduleContext = new Map();
Object.keys( optionsModuleContext ).forEach( key => {
moduleContext.set( resolve( key ), optionsModuleContext[ key ] );
} );
this.getModuleContext = id => moduleContext.get( id ) || this.context;
} else {
this.getModuleContext = () => this.context;
}
if ( typeof options.external === 'function' ) {
this.isExternal = options.external;
} else {
const ids = ensureArray( options.external );
this.isExternal = id => ids.indexOf( id ) !== -1;
}
this.onwarn = options.onwarn || makeOnwarn();
this.varOrConst = options.preferConst ? 'const' : 'var';
this.legacy = options.legacy;
this.acornOptions = options.acorn || {};
this.dependentExpressions = [];
}
build () {
// Phase 1 – discovery. We load the entry module and find which
// modules it imports, and import those, until we have all
// of the entry module's dependencies
return this.resolveId( this.entry, undefined )
.then( id => {
if ( id === false ) {
error( {
code: 'UNRESOLVED_ENTRY',
message: `Entry module cannot be external`
} );
}
if ( id == null ) {
error( {
code: 'UNRESOLVED_ENTRY',
message: `Could not resolve entry (${this.entry})`
} );
}
this.entryId = id;
return this.fetchModule( id, undefined );
} )
.then( entryModule => {
this.entryModule = entryModule;
// Phase 2 – binding. We link references to their declarations
// to generate a complete picture of the bundle
timeStart( 'phase 2' );
this.modules.forEach( module => module.bindImportSpecifiers() );
this.modules.forEach( module => module.bindReferences() );
timeEnd( 'phase 2' );
// Phase 3 – marking. We 'run' each statement to see which ones
// need to be included in the generated bundle
timeStart( 'phase 3' );
// mark all export statements
entryModule.getExports().forEach( name => {
const declaration = entryModule.traceExport( name );
declaration.exportName = name;
declaration.activate();
if ( declaration.isNamespace ) {
declaration.needsNamespaceBlock = true;
}
} );
// mark statements that should appear in the bundle
if ( this.treeshake ) {
this.modules.forEach( module => {
module.run();
} );
let settled = false;
while ( !settled ) {
settled = true;
let i = this.dependentExpressions.length;
while ( i-- ) {
const expression = this.dependentExpressions[ i ];
let statement = expression;
while ( statement.parent && !/Function/.test( statement.parent.type ) ) statement = statement.parent;
if ( !statement || statement.ran ) {
this.dependentExpressions.splice( i, 1 );
} else if ( expression.isUsedByBundle() ) {
settled = false;
statement.run();
this.dependentExpressions.splice( i, 1 );
}
}
}
}
timeEnd( 'phase 3' );
// Phase 4 – final preparation. We order the modules with an
// enhanced topological sort that accounts for cycles, then
// ensure that names are deconflicted throughout the bundle
timeStart( 'phase 4' );
// while we're here, check for unused external imports
this.externalModules.forEach( module => {
const unused = Object.keys( module.declarations )
.filter( name => name !== '*' )
.filter( name => !module.declarations[ name ].activated );
if ( unused.length === 0 ) return;
const names = unused.length === 1 ?
`'${unused[0]}' is` :
`${unused.slice( 0, -1 ).map( name => `'${name}'` ).join( ', ' )} and '${unused.slice( -1 )}' are`;
this.warn( {
code: 'UNUSED_EXTERNAL_IMPORT',
source: module.id,
names: unused,
message: `${names} imported from external module '${module.id}' but never used`
} );
} );
// prune unused external imports
this.externalModules = this.externalModules.filter( module => {
return module.used || !this.isPureExternalModule( module.id );
} );
this.orderedModules = this.sort();
this.deconflict();
timeEnd( 'phase 4' );
} );
}
deconflict () {
const used = blank();
// ensure no conflicts with globals
keys( this.scope.declarations ).forEach( name => used[ name ] = 1 );
function getSafeName ( name ) {
while ( used[ name ] ) {
name += `$${used[ name ]++}`;
}
used[ name ] = 1;
return name;
}
const toDeshadow = new Set();
this.externalModules.forEach( module => {
const safeName = getSafeName( module.name );
toDeshadow.add( safeName );
module.name = safeName;
// ensure we don't shadow named external imports, if
// we're creating an ES6 bundle
forOwn( module.declarations, ( declaration, name ) => {
const safeName = getSafeName( name );
toDeshadow.add( safeName );
declaration.setSafeName( safeName );
} );
} );
this.modules.forEach( module => {
forOwn( module.scope.declarations, ( declaration ) => {
if ( declaration.isDefault && declaration.declaration.id ) {
return;
}
declaration.name = getSafeName( declaration.name );
} );
// deconflict reified namespaces
const namespace = module.namespace();
if ( namespace.needsNamespaceBlock ) {
namespace.name = getSafeName( namespace.name );
}
} );
this.scope.deshadow( toDeshadow );
}
fetchModule ( id, importer ) {
// short-circuit cycles
if ( this.moduleById.has( id ) ) return null;
this.moduleById.set( id, null );
return this.load( id )
.catch( err => {
let msg = `Could not load ${id}`;
if ( importer ) msg += ` (imported by ${importer})`;
msg += `: ${err.message}`;
throw new Error( msg );
} )
.then( source => {
if ( typeof source === 'string' ) return source;
if ( source && typeof source === 'object' && source.code ) return source;
// TODO report which plugin failed
error( {
code: 'BAD_LOADER',
message: `Error loading ${relativeId( id )}: plugin load hook should return a string, a { code, map } object, or nothing/null`
} );
} )
.then( source => {
if ( typeof source === 'string' ) {
source = {
code: source,
ast: null
};
}
if ( this.cachedModules.has( id ) && this.cachedModules.get( id ).originalCode === source.code ) {
return this.cachedModules.get( id );
}
return transform( this, source, id, this.plugins );
} )
.then( source => {
const { code, originalCode, originalSourceMap, ast, sourceMapChain, resolvedIds } = source;
const module = new Module( {
id,
code,
originalCode,
originalSourceMap,
ast,
sourceMapChain,
resolvedIds,
bundle: this
} );
this.modules.push( module );
this.moduleById.set( id, module );
return this.fetchAllDependencies( module ).then( () => {
keys( module.exports ).forEach( name => {
if ( name !== 'default' ) {
module.exportsAll[ name ] = module.id;
}
} );
module.exportAllSources.forEach( source => {
const id = module.resolvedIds[ source ] || module.resolvedExternalIds[ source ];
const exportAllModule = this.moduleById.get( id );
if ( exportAllModule.isExternal ) return;
keys( exportAllModule.exportsAll ).forEach( name => {
if ( name in module.exportsAll ) {
this.warn( {
code: 'NAMESPACE_CONFLICT',
reexporter: module.id,
name,
sources: [ module.exportsAll[ name ], exportAllModule.exportsAll[ name ] ],
message: `Conflicting namespaces: ${relativeId( module.id )} re-exports '${name}' from both ${relativeId( module.exportsAll[ name ] )} and ${relativeId( exportAllModule.exportsAll[ name ] )} (will be ignored)`
} );
} else {
module.exportsAll[ name ] = exportAllModule.exportsAll[ name ];
}
} );
} );
return module;
} );
} );
}
fetchAllDependencies ( module ) {
return mapSequence( module.sources, source => {
const resolvedId = module.resolvedIds[ source ];
return ( resolvedId ? Promise.resolve( resolvedId ) : this.resolveId( source, module.id ) )
.then( resolvedId => {
const externalId = resolvedId || (
isRelative( source ) ? resolve( module.id, '..', source ) : source
);
let isExternal = this.isExternal( externalId );
if ( !resolvedId && !isExternal ) {
if ( isRelative( source ) ) {
error( {
code: 'UNRESOLVED_IMPORT',
message: `Could not resolve '${source}' from ${relativeId( module.id )}`
} );
}
this.warn( {
code: 'UNRESOLVED_IMPORT',
source,
importer: relativeId( module.id ),
message: `'${source}' is imported by ${relativeId( module.id )}, but could not be resolved – treating it as an external dependency`,
url: 'https://github.com/rollup/rollup/wiki/Troubleshooting#treating-module-as-external-dependency'
} );
isExternal = true;
}
if ( isExternal ) {
module.resolvedExternalIds[ source ] = externalId;
if ( !this.moduleById.has( externalId ) ) {
const module = new ExternalModule( externalId, this.getPath( externalId ) );
this.externalModules.push( module );
this.moduleById.set( externalId, module );
}
const externalModule = this.moduleById.get( externalId );
// add external declarations so we can detect which are never used
Object.keys( module.imports ).forEach( name => {
const importDeclaration = module.imports[ name ];
if ( importDeclaration.source !== source ) return;
externalModule.traceExport( importDeclaration.name );
} );
} else {
if ( resolvedId === module.id ) {
// need to find the actual import declaration, so we can provide
// a useful error message. Bit hoop-jumpy but what can you do
const declaration = module.ast.body.find( node => {
return node.isImportDeclaration && node.source.value === source;
} );
module.error( {
code: 'CANNOT_IMPORT_SELF',
message: `A module cannot import itself`
}, declaration.start );
}
module.resolvedIds[ source ] = resolvedId;
return this.fetchModule( resolvedId, module.id );
}
} );
} );
}
getPathRelativeToEntryDirname ( resolvedId ) {
if ( isRelative( resolvedId ) || isAbsolute( resolvedId ) ) {
const entryDirname = dirname( this.entryId );
const relativeToEntry = normalize( relative( entryDirname, resolvedId ) );
return isRelative( relativeToEntry ) ? relativeToEntry : `./${relativeToEntry}`;
}
return resolvedId;
}
render ( options = {} ) {
return Promise.resolve().then( () => {
// Determine export mode - 'default', 'named', 'none'
const exportMode = getExportMode( this, options );
let magicString = new MagicStringBundle( { separator: '\n\n' } );
const usedModules = [];
timeStart( 'render modules' );
this.orderedModules.forEach( module => {
const source = module.render( options.format === 'es', this.legacy );
if ( source.toString().length ) {
magicString.addSource( source );
usedModules.push( module );
}
} );
if ( !magicString.toString().trim() && this.entryModule.getExports().length === 0 ) {
this.warn( {
code: 'EMPTY_BUNDLE',
message: 'Generated an empty bundle'
} );
}
timeEnd( 'render modules' );
let intro = [ options.intro ]
.concat(
this.plugins.map( plugin => plugin.intro && plugin.intro() )
)
.filter( Boolean )
.join( '\n\n' );
if ( intro ) intro += '\n\n';
let outro = [ options.outro ]
.concat(
this.plugins.map( plugin => plugin.outro && plugin.outro() )
)
.filter( Boolean )
.join( '\n\n' );
if ( outro ) outro = `\n\n${outro}`;
const indentString = getIndentString( magicString, options );
const finalise = finalisers[ options.format ];
if ( !finalise ) {
error({
code: 'INVALID_OPTION',
message: `Invalid format: ${options.format} - valid options are ${keys( finalisers ).join( ', ' )}`
});
}
timeStart( 'render format' );
magicString = finalise( this, magicString.trim(), { exportMode, indentString, intro, outro }, options );
timeEnd( 'render format' );
const banner = [ options.banner ]
.concat( this.plugins.map( plugin => plugin.banner ) )
.map( callIfFunction )
.filter( Boolean )
.join( '\n' );
const footer = [ options.footer ]
.concat( this.plugins.map( plugin => plugin.footer ) )
.map( callIfFunction )
.filter( Boolean )
.join( '\n' );
if ( banner ) magicString.prepend( banner + '\n' );
if ( footer ) magicString.append( '\n' + footer );
const prevCode = magicString.toString();
let map = null;
const bundleSourcemapChain = [];
return transformBundle( prevCode, this.plugins, bundleSourcemapChain, options ).then( code => {
if ( options.sourceMap ) {
timeStart( 'sourceMap' );
let file = options.sourceMapFile || options.dest;
if ( file ) file = resolve( typeof process !== 'undefined' ? process.cwd() : '', file );
if ( this.hasLoaders || find( this.plugins, plugin => plugin.transform || plugin.transformBundle ) ) {
map = magicString.generateMap( {} );
if ( typeof map.mappings === 'string' ) {
map.mappings = decode( map.mappings );
}
map = collapseSourcemaps( this, file, map, usedModules, bundleSourcemapChain );
} else {
map = magicString.generateMap( { file, includeContent: true } );
}
map.sources = map.sources.map( normalize );
timeEnd( 'sourceMap' );
}
if ( code[ code.length - 1 ] !== '\n' ) code += '\n';
return { code, map };
} );
} );
}
sort () {
let hasCycles;
const seen = {};
const ordered = [];
const stronglyDependsOn = blank();
const dependsOn = blank();
this.modules.forEach( module => {
stronglyDependsOn[ module.id ] = blank();
dependsOn[ module.id ] = blank();
} );
this.modules.forEach( module => {
function processStrongDependency ( dependency ) {
if ( dependency === module || stronglyDependsOn[ module.id ][ dependency.id ] ) return;
stronglyDependsOn[ module.id ][ dependency.id ] = true;
dependency.strongDependencies.forEach( processStrongDependency );
}
function processDependency ( dependency ) {
if ( dependency === module || dependsOn[ module.id ][ dependency.id ] ) return;
dependsOn[ module.id ][ dependency.id ] = true;
dependency.dependencies.forEach( processDependency );
}
module.strongDependencies.forEach( processStrongDependency );
module.dependencies.forEach( processDependency );
} );
const visit = module => {
if ( seen[ module.id ] ) {
hasCycles = true;
return;
}
seen[ module.id ] = true;
module.dependencies.forEach( visit );
ordered.push( module );
};
visit( this.entryModule );
if ( hasCycles ) {
ordered.forEach( ( a, i ) => {
for ( i += 1; i < ordered.length; i += 1 ) {
const b = ordered[ i ];
// TODO reinstate this! it no longer works
if ( stronglyDependsOn[ a.id ][ b.id ] ) {
// somewhere, there is a module that imports b before a. Because
// b imports a, a is placed before b. We need to find the module
// in question, so we can provide a useful error message
let parent = '[[unknown]]';
const visited = {};
const findParent = module => {
if ( dependsOn[ module.id ][ a.id ] && dependsOn[ module.id ][ b.id ] ) {
parent = module.id;
return true;
}
visited[ module.id ] = true;
for ( let i = 0; i < module.dependencies.length; i += 1 ) {
const dependency = module.dependencies[ i ];
if ( !visited[ dependency.id ] && findParent( dependency ) ) return true;
}
};
findParent( this.entryModule );
this.onwarn(
`Module ${a.id} may be unable to evaluate without ${b.id}, but is included first due to a cyclical dependency. Consider swapping the import statements in ${parent} to ensure correct ordering`
);
}
}
} );
}
return ordered;
}
warn ( warning ) {
warning.toString = () => {
let str = '';
if ( warning.plugin ) str += `(${warning.plugin} plugin) `;
if ( warning.loc ) str += `${relativeId( warning.loc.file )} (${warning.loc.line}:${warning.loc.column}) `;
str += warning.message;
return str;
};
this.onwarn( warning );
}
}