/
Graph.ts
234 lines (217 loc) · 7.23 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
import * as acorn from 'acorn';
import GlobalScope from './ast/scopes/GlobalScope';
import { PathTracker } from './ast/utils/PathTracker';
import ExternalModule from './ExternalModule';
import Module from './Module';
import { ModuleLoader, UnresolvedModule } from './ModuleLoader';
import {
ModuleInfo,
ModuleJSON,
NormalizedInputOptions,
RollupCache,
RollupWatcher,
SerializablePluginCache
} from './rollup/types';
import { BuildPhase } from './utils/buildPhase';
import { errImplicitDependantIsNotIncluded, error } from './utils/error';
import { analyseModuleExecution } from './utils/executionOrder';
import { PluginDriver } from './utils/PluginDriver';
import relativeId from './utils/relativeId';
import { timeEnd, timeStart } from './utils/timers';
import { markModuleAndImpureDependenciesAsExecuted } from './utils/traverseStaticDependencies';
function normalizeEntryModules(
entryModules: string[] | Record<string, string>
): UnresolvedModule[] {
if (Array.isArray(entryModules)) {
return entryModules.map(id => ({
fileName: null,
id,
implicitlyLoadedAfter: [],
importer: undefined,
name: null
}));
}
return Object.keys(entryModules).map(name => ({
fileName: null,
id: entryModules[name],
implicitlyLoadedAfter: [],
importer: undefined,
name
}));
}
export default class Graph {
acornParser: typeof acorn.Parser;
cachedModules: Map<string, ModuleJSON>;
contextParse: (code: string, acornOptions?: acorn.Options) => acorn.Node;
deoptimizationTracker: PathTracker;
entryModules: Module[] = [];
moduleLoader: ModuleLoader;
modulesById = new Map<string, Module | ExternalModule>();
needsTreeshakingPass = false;
phase: BuildPhase = BuildPhase.LOAD_AND_PARSE;
pluginDriver: PluginDriver;
scope: GlobalScope;
watchFiles: Record<string, true> = Object.create(null);
watchMode = false;
private externalModules: ExternalModule[] = [];
private implicitEntryModules: Module[] = [];
private modules: Module[] = [];
private pluginCache?: Record<string, SerializablePluginCache>;
constructor(private readonly options: NormalizedInputOptions, watcher: RollupWatcher | null) {
this.deoptimizationTracker = new PathTracker();
this.cachedModules = new Map();
if (options.cache !== false) {
if (options.cache?.modules) {
for (const module of options.cache.modules) this.cachedModules.set(module.id, module);
}
this.pluginCache = 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.contextParse = (code: string, options: Partial<acorn.Options> = {}) =>
this.acornParser.parse(code, {
...(this.options.acorn as acorn.Options),
...options
});
if (watcher) {
this.watchMode = true;
const handleChange = (id: string) => this.pluginDriver.hookSeqSync('watchChange', [id]);
watcher.on('change', handleChange);
watcher.once('restart', () => {
watcher.removeListener('change', handleChange);
});
}
this.pluginDriver = new PluginDriver(this, options, options.plugins, this.pluginCache);
this.scope = new GlobalScope();
this.acornParser = acorn.Parser.extend(...(options.acornInjectPlugins as any));
this.moduleLoader = new ModuleLoader(this, this.modulesById, this.options, this.pluginDriver);
}
async build(): Promise<void> {
timeStart('generate module graph', 2);
await this.generateModuleGraph();
timeEnd('generate module graph', 2);
timeStart('sort modules', 2);
this.phase = BuildPhase.ANALYSE;
this.sortModules();
timeEnd('sort modules', 2);
timeStart('mark included statements', 2);
this.includeStatements();
timeEnd('mark included statements', 2);
this.phase = BuildPhase.GENERATE;
}
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.options.experimentalCacheExpiry) delete cache[key];
else allDeleted = false;
}
if (allDeleted) delete this.pluginCache[name];
}
return {
modules: this.modules.map(module => module.toJSON()),
plugins: this.pluginCache
};
}
getModuleInfo = (moduleId: string): ModuleInfo | null => {
const foundModule = this.modulesById.get(moduleId);
if (!foundModule) return null;
return foundModule.info;
};
private async generateModuleGraph(): Promise<void> {
({
entryModules: this.entryModules,
implicitEntryModules: this.implicitEntryModules
} = await this.moduleLoader.addEntryModules(normalizeEntryModules(this.options.input), true));
if (this.entryModules.length === 0) {
throw new Error('You must supply options.input to rollup');
}
for (const module of this.modulesById.values()) {
if (module instanceof Module) {
this.modules.push(module);
} else {
this.externalModules.push(module);
}
}
}
private includeStatements() {
for (const module of [...this.entryModules, ...this.implicitEntryModules]) {
if (module.preserveSignature !== false) {
module.includeAllExports(false);
} else {
markModuleAndImpureDependenciesAsExecuted(module);
}
}
if (this.options.treeshake) {
let treeshakingPass = 1;
do {
timeStart(`treeshaking pass ${treeshakingPass}`, 3);
this.needsTreeshakingPass = false;
for (const module of this.modules) {
if (module.isExecuted) {
if (module.info.hasModuleSideEffects === 'no-treeshake') {
module.includeAllInBundle();
} else {
module.include();
}
}
}
timeEnd(`treeshaking pass ${treeshakingPass++}`, 3);
} while (this.needsTreeshakingPass);
} else {
for (const module of this.modules) module.includeAllInBundle();
}
for (const externalModule of this.externalModules) externalModule.warnUnusedImports();
for (const module of this.implicitEntryModules) {
for (const dependant of module.implicitlyLoadedAfter) {
if (!(dependant.info.isEntry || dependant.isIncluded())) {
error(errImplicitDependantIsNotIncluded(dependant));
}
}
}
}
private sortModules() {
const { orderedModules, cyclePaths } = analyseModuleExecution(this.entryModules);
for (const cyclePath of cyclePaths) {
this.options.onwarn({
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
);
}
}
}
}
}