/
Graph.ts
401 lines (357 loc) · 12.9 KB
/
Graph.ts
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
import * as acorn from 'acorn';
import injectExportNsFrom from 'acorn-export-ns-from';
import injectImportMeta from 'acorn-import-meta';
import * as ESTree from 'estree';
import GlobalScope from './ast/scopes/GlobalScope';
import { PathTracker } from './ast/utils/PathTracker';
import Chunk, { isChunkRendered } from './Chunk';
import ExternalModule from './ExternalModule';
import Module, { defaultAcornOptions } from './Module';
import { ModuleLoader, UnresolvedModule } from './ModuleLoader';
import {
GetManualChunk,
InputOptions,
ManualChunksOption,
ModuleJSON,
RollupCache,
RollupWarning,
RollupWatcher,
SerializablePluginCache,
TreeshakingOptions,
WarningHandler
} from './rollup/types';
import { BuildPhase } from './utils/buildPhase';
import { assignChunkColouringHashes } from './utils/chunkColouring';
import { Uint8ArrayToHexString } from './utils/entryHashing';
import { errDeprecation, error } from './utils/error';
import { analyseModuleExecution, sortByExecutionOrder } from './utils/executionOrder';
import { resolve } from './utils/path';
import { PluginDriver } from './utils/PluginDriver';
import relativeId from './utils/relativeId';
import { timeEnd, timeStart } from './utils/timers';
function normalizeEntryModules(
entryModules: string | string[] | Record<string, string>
): UnresolvedModule[] {
if (typeof entryModules === 'string') {
return [{ fileName: null, name: null, id: entryModules }];
}
if (Array.isArray(entryModules)) {
return entryModules.map(id => ({ fileName: null, name: null, id }));
}
return Object.keys(entryModules).map(name => ({
fileName: null,
id: entryModules[name],
name
}));
}
export default class Graph {
acornOptions: acorn.Options;
acornParser: typeof acorn.Parser;
cachedModules: Map<string, ModuleJSON>;
contextParse: (code: string, acornOptions?: acorn.Options) => ESTree.Program;
deoptimizationTracker: PathTracker;
getModuleContext: (id: string) => string;
moduleById = new Map<string, Module | ExternalModule>();
moduleLoader: ModuleLoader;
needsTreeshakingPass = false;
phase: BuildPhase = BuildPhase.LOAD_AND_PARSE;
pluginDriver: PluginDriver;
preserveModules: boolean;
scope: GlobalScope;
shimMissingExports: boolean;
treeshakingOptions?: TreeshakingOptions;
watchFiles: Record<string, true> = Object.create(null);
private cacheExpiry: number;
private context: string;
private externalModules: ExternalModule[] = [];
private modules: Module[] = [];
private onwarn: WarningHandler;
private pluginCache?: Record<string, SerializablePluginCache>;
private strictDeprecations: boolean;
constructor(options: InputOptions, watcher: RollupWatcher | null) {
this.onwarn = options.onwarn as WarningHandler;
this.deoptimizationTracker = new PathTracker();
this.cachedModules = new Map();
if (options.cache) {
if (options.cache.modules)
for (const module of options.cache.modules) this.cachedModules.set(module.id, module);
}
if (options.cache !== false) {
this.pluginCache = (options.cache && options.cache.plugins) || Object.create(null);
// increment access counter
for (const name in this.pluginCache) {
const cache = this.pluginCache[name];
for (const key of Object.keys(cache)) cache[key][0]++;
}
}
this.preserveModules = options.preserveModules!;
this.strictDeprecations = options.strictDeprecations!;
this.cacheExpiry = options.experimentalCacheExpiry!;
if (options.treeshake !== false) {
this.treeshakingOptions =
options.treeshake && options.treeshake !== true
? {
annotations: options.treeshake.annotations !== false,
moduleSideEffects: options.treeshake.moduleSideEffects,
propertyReadSideEffects: options.treeshake.propertyReadSideEffects !== false,
pureExternalModules: options.treeshake.pureExternalModules,
tryCatchDeoptimization: options.treeshake.tryCatchDeoptimization !== false,
unknownGlobalSideEffects: options.treeshake.unknownGlobalSideEffects !== false
}
: {
annotations: true,
moduleSideEffects: true,
propertyReadSideEffects: true,
tryCatchDeoptimization: true,
unknownGlobalSideEffects: true
};
if (typeof this.treeshakingOptions.pureExternalModules !== 'undefined') {
this.warnDeprecation(
`The "treeshake.pureExternalModules" option is deprecated. The "treeshake.moduleSideEffects" option should be used instead. "treeshake.pureExternalModules: true" is equivalent to "treeshake.moduleSideEffects: 'no-external'"`,
true
);
}
}
this.contextParse = (code: string, options: acorn.Options = {}) =>
this.acornParser.parse(code, {
...defaultAcornOptions,
...options,
...this.acornOptions
}) as any;
this.pluginDriver = new PluginDriver(
this,
options.plugins!,
this.pluginCache,
options.preserveSymlinks === true
);
if (watcher) {
const handleChange = (id: string) => this.pluginDriver.hookSeqSync('watchChange', [id]);
watcher.on('change', handleChange);
watcher.once('restart', () => {
watcher.removeListener('change', handleChange);
});
}
this.shimMissingExports = options.shimMissingExports as boolean;
this.scope = new GlobalScope();
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();
for (const key in optionsModuleContext) {
moduleContext.set(resolve(key), optionsModuleContext[key]);
}
this.getModuleContext = id => moduleContext.get(id) || this.context;
} else {
this.getModuleContext = () => this.context;
}
this.acornOptions = options.acorn ? { ...options.acorn } : {};
const acornPluginsToInject = [];
acornPluginsToInject.push(injectImportMeta, injectExportNsFrom);
(this.acornOptions as any).allowAwaitOutsideFunction = true;
const acornInjectPlugins = options.acornInjectPlugins;
acornPluginsToInject.push(
...(Array.isArray(acornInjectPlugins)
? acornInjectPlugins
: acornInjectPlugins
? [acornInjectPlugins]
: [])
);
this.acornParser = acorn.Parser.extend(...acornPluginsToInject);
this.moduleLoader = new ModuleLoader(
this,
this.moduleById,
this.pluginDriver,
options.external!,
(typeof options.manualChunks === 'function' && options.manualChunks) as GetManualChunk | null,
(this.treeshakingOptions ? this.treeshakingOptions.moduleSideEffects : null)!,
(this.treeshakingOptions ? this.treeshakingOptions.pureExternalModules : false)!
);
}
build(
entryModules: string | string[] | Record<string, string>,
manualChunks: ManualChunksOption | void,
inlineDynamicImports: boolean
): Promise<Chunk[]> {
// 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
timeStart('parse modules', 2);
return Promise.all([
this.moduleLoader.addEntryModules(normalizeEntryModules(entryModules), true),
(manualChunks &&
typeof manualChunks === 'object' &&
this.moduleLoader.addManualChunks(manualChunks)) as Promise<void>
]).then(([{ entryModules, manualChunkModulesByAlias }]) => {
if (entryModules.length === 0) {
throw new Error('You must supply options.input to rollup');
}
for (const module of this.moduleById.values()) {
if (module instanceof Module) {
this.modules.push(module);
} else {
this.externalModules.push(module);
}
}
timeEnd('parse modules', 2);
this.phase = BuildPhase.ANALYSE;
// Phase 2 - linking. We populate the module dependency links and
// determine the topological execution order for the bundle
timeStart('analyse dependency graph', 2);
this.link(entryModules);
timeEnd('analyse dependency graph', 2);
// Phase 3 – marking. We include all statements that should be included
timeStart('mark included statements', 2);
for (const module of entryModules) {
module.includeAllExports();
}
this.includeMarked(this.modules);
// check for unused external imports
for (const externalModule of this.externalModules) externalModule.warnUnusedImports();
timeEnd('mark included statements', 2);
// Phase 4 – we construct the chunks, working out the optimal chunking using
// entry point graph colouring, before generating the import and export facades
timeStart('generate chunks', 2);
if (!this.preserveModules && !inlineDynamicImports) {
assignChunkColouringHashes(entryModules, manualChunkModulesByAlias);
}
// TODO: there is one special edge case unhandled here and that is that any module
// exposed as an unresolvable export * (to a graph external export *,
// either as a namespace import reexported or top-level export *)
// should be made to be its own entry point module before chunking
let chunks: Chunk[] = [];
if (this.preserveModules) {
for (const module of this.modules) {
const chunk = new Chunk(this, [module]);
if (module.isEntryPoint || !chunk.isEmpty) {
chunk.entryModules = [module];
}
chunks.push(chunk);
}
} else {
const chunkModules: { [entryHashSum: string]: Module[] } = {};
for (const module of this.modules) {
const entryPointsHashStr = Uint8ArrayToHexString(module.entryPointsHash);
const curChunk = chunkModules[entryPointsHashStr];
if (curChunk) {
curChunk.push(module);
} else {
chunkModules[entryPointsHashStr] = [module];
}
}
for (const entryHashSum in chunkModules) {
const chunkModulesOrdered = chunkModules[entryHashSum];
sortByExecutionOrder(chunkModulesOrdered);
const chunk = new Chunk(this, chunkModulesOrdered);
chunks.push(chunk);
}
}
for (const chunk of chunks) {
chunk.link();
}
chunks = chunks.filter(isChunkRendered);
const facades: Chunk[] = [];
for (const chunk of chunks) {
facades.push(...chunk.generateFacades());
}
timeEnd('generate chunks', 2);
this.phase = BuildPhase.GENERATE;
return chunks.concat(facades);
});
}
getCache(): RollupCache {
// handle plugin cache eviction
for (const name in this.pluginCache) {
const cache = this.pluginCache[name];
let allDeleted = true;
for (const key of Object.keys(cache)) {
if (cache[key][0] >= this.cacheExpiry) delete cache[key];
else allDeleted = false;
}
if (allDeleted) delete this.pluginCache[name];
}
return {
modules: this.modules.map(module => module.toJSON()),
plugins: this.pluginCache
};
}
includeMarked(modules: Module[]) {
if (this.treeshakingOptions) {
let treeshakingPass = 1;
do {
timeStart(`treeshaking pass ${treeshakingPass}`, 3);
this.needsTreeshakingPass = false;
for (const module of modules) {
if (module.isExecuted) module.include();
}
timeEnd(`treeshaking pass ${treeshakingPass++}`, 3);
} while (this.needsTreeshakingPass);
} else {
// Necessary to properly replace namespace imports
for (const module of modules) module.includeAllInBundle();
}
}
warn(warning: RollupWarning) {
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);
}
warnDeprecation(deprecation: string | RollupWarning, activeDeprecation: boolean): void {
if (activeDeprecation || this.strictDeprecations) {
const warning = errDeprecation(deprecation);
if (this.strictDeprecations) {
return error(warning);
}
this.warn(warning);
}
}
private link(entryModules: Module[]) {
for (const module of this.modules) {
module.linkDependencies();
}
const { orderedModules, cyclePaths } = analyseModuleExecution(entryModules);
for (const cyclePath of cyclePaths) {
this.warn({
code: 'CIRCULAR_DEPENDENCY',
cycle: cyclePath,
importer: cyclePath[0],
message: `Circular dependency: ${cyclePath.join(' -> ')}`
});
}
this.modules = orderedModules;
for (const module of this.modules) {
module.bindReferences();
}
this.warnForMissingExports();
}
private warnForMissingExports() {
for (const module of this.modules) {
for (const importName of Object.keys(module.importDescriptions)) {
const importDescription = module.importDescriptions[importName];
if (
importDescription.name !== '*' &&
!(importDescription.module as Module).getVariableForExportName(importDescription.name)
) {
module.warn(
{
code: 'NON_EXISTENT_EXPORT',
message: `Non-existent export '${
importDescription.name
}' is imported from ${relativeId((importDescription.module as Module).id)}`,
name: importDescription.name,
source: (importDescription.module as Module).id
},
importDescription.start
);
}
}
}
}
}