forked from rollup/rollup
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Bundle.ts
314 lines (292 loc) · 9.65 KB
/
Bundle.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
import Chunk from './Chunk';
import ExternalChunk from './ExternalChunk';
import ExternalModule from './ExternalModule';
import type Graph from './Graph';
import Module from './Module';
import type {
GetManualChunk,
LogHandler,
NormalizedInputOptions,
NormalizedOutputOptions,
OutputBundle
} from './rollup/types';
import { getChunkAssignments } from './utils/chunkAssignment';
import commondir from './utils/commondir';
import { sortByExecutionOrder } from './utils/executionOrder';
import { getGenerateCodeSnippets } from './utils/generateCodeSnippets';
import type { HashPlaceholderGenerator } from './utils/hashPlaceholders';
import { getHashPlaceholderGenerator } from './utils/hashPlaceholders';
import { LOGLEVEL_WARN } from './utils/logging';
import {
error,
logCannotAssignModuleToChunk,
logChunkInvalid,
logInvalidOption
} from './utils/logs';
import type { OutputBundleWithPlaceholders } from './utils/outputBundle';
import { getOutputBundle, removeUnreferencedAssets } from './utils/outputBundle';
import { parseAst } from './utils/parseAst';
import { isAbsolute } from './utils/path';
import type { PluginDriver } from './utils/PluginDriver';
import { renderChunks } from './utils/renderChunks';
import { timeEnd, timeStart } from './utils/timers';
import {
URL_OUTPUT_AMD_ID,
URL_OUTPUT_DIR,
URL_OUTPUT_FORMAT,
URL_OUTPUT_SOURCEMAPFILE
} from './utils/urls';
export default class Bundle {
private readonly facadeChunkByModule = new Map<Module, Chunk>();
private readonly includedNamespaces = new Set<Module>();
constructor(
private readonly outputOptions: NormalizedOutputOptions,
private readonly unsetOptions: ReadonlySet<string>,
private readonly inputOptions: NormalizedInputOptions,
private readonly pluginDriver: PluginDriver,
private readonly graph: Graph
) {}
async generate(isWrite: boolean): Promise<OutputBundle> {
timeStart('GENERATE', 1);
const outputBundleBase: OutputBundle = Object.create(null);
const outputBundle = getOutputBundle(outputBundleBase);
this.pluginDriver.setOutputBundle(outputBundle, this.outputOptions);
try {
timeStart('initialize render', 2);
await this.pluginDriver.hookParallel('renderStart', [this.outputOptions, this.inputOptions]);
timeEnd('initialize render', 2);
timeStart('generate chunks', 2);
const getHashPlaceholder = getHashPlaceholderGenerator();
const chunks = await this.generateChunks(outputBundle, getHashPlaceholder);
if (chunks.length > 1) {
validateOptionsForMultiChunkOutput(this.outputOptions, this.inputOptions.onLog);
}
this.pluginDriver.setChunkInformation(this.facadeChunkByModule);
for (const chunk of chunks) {
chunk.generateExports();
}
timeEnd('generate chunks', 2);
await renderChunks(
chunks,
outputBundle,
this.pluginDriver,
this.outputOptions,
this.inputOptions.onLog
);
} catch (error_: any) {
await this.pluginDriver.hookParallel('renderError', [error_]);
throw error_;
}
removeUnreferencedAssets(outputBundle);
timeStart('generate bundle', 2);
await this.pluginDriver.hookSeq('generateBundle', [
this.outputOptions,
outputBundle as OutputBundle,
isWrite
]);
this.finaliseAssets(outputBundle);
timeEnd('generate bundle', 2);
timeEnd('GENERATE', 1);
return outputBundleBase;
}
private async addManualChunks(
manualChunks: Record<string, readonly string[]>
): Promise<Map<Module, string>> {
const manualChunkAliasByEntry = new Map<Module, string>();
const chunkEntries = await Promise.all(
Object.entries(manualChunks).map(async ([alias, files]) => ({
alias,
entries: await this.graph.moduleLoader.addAdditionalModules(files, true)
}))
);
for (const { alias, entries } of chunkEntries) {
for (const entry of entries) {
addModuleToManualChunk(alias, entry, manualChunkAliasByEntry);
}
}
return manualChunkAliasByEntry;
}
private assignManualChunks(getManualChunk: GetManualChunk): Map<Module, string> {
const manualChunkAliasesWithEntry: [alias: string, module: Module][] = [];
const manualChunksApi = {
getModuleIds: () => this.graph.modulesById.keys(),
getModuleInfo: this.graph.getModuleInfo
};
for (const module of this.graph.modulesById.values()) {
if (module instanceof Module) {
const manualChunkAlias = getManualChunk(module.id, manualChunksApi);
if (typeof manualChunkAlias === 'string') {
manualChunkAliasesWithEntry.push([manualChunkAlias, module]);
}
}
}
manualChunkAliasesWithEntry.sort(([aliasA], [aliasB]) =>
aliasA > aliasB ? 1 : aliasA < aliasB ? -1 : 0
);
const manualChunkAliasByEntry = new Map<Module, string>();
for (const [alias, module] of manualChunkAliasesWithEntry) {
addModuleToManualChunk(alias, module, manualChunkAliasByEntry);
}
return manualChunkAliasByEntry;
}
private finaliseAssets(bundle: OutputBundleWithPlaceholders): void {
if (this.outputOptions.validate) {
for (const file of Object.values(bundle)) {
if ('code' in file) {
try {
parseAst(file.code, { jsx: this.inputOptions.jsx !== false });
} catch (error_: any) {
this.inputOptions.onLog(LOGLEVEL_WARN, logChunkInvalid(file, error_));
}
}
}
}
this.pluginDriver.finaliseAssets();
}
private async generateChunks(
bundle: OutputBundleWithPlaceholders,
getHashPlaceholder: HashPlaceholderGenerator
): Promise<Chunk[]> {
const { experimentalMinChunkSize, inlineDynamicImports, manualChunks, preserveModules } =
this.outputOptions;
const manualChunkAliasByEntry =
typeof manualChunks === 'object'
? await this.addManualChunks(manualChunks)
: this.assignManualChunks(manualChunks);
const snippets = getGenerateCodeSnippets(this.outputOptions);
const includedModules = getIncludedModules(this.graph.modulesById);
const inputBase = commondir(getAbsoluteEntryModulePaths(includedModules, preserveModules));
const externalChunkByModule = getExternalChunkByModule(
this.graph.modulesById,
this.outputOptions,
inputBase
);
const chunks: Chunk[] = [];
const chunkByModule = new Map<Module, Chunk>();
for (const { alias, modules } of inlineDynamicImports
? [{ alias: null, modules: includedModules }]
: preserveModules
? includedModules.map(module => ({ alias: null, modules: [module] }))
: getChunkAssignments(
this.graph.entryModules,
manualChunkAliasByEntry,
experimentalMinChunkSize,
this.inputOptions.onLog
)) {
sortByExecutionOrder(modules);
const chunk = new Chunk(
modules,
this.inputOptions,
this.outputOptions,
this.unsetOptions,
this.pluginDriver,
this.graph.modulesById,
chunkByModule,
externalChunkByModule,
this.facadeChunkByModule,
this.includedNamespaces,
alias,
getHashPlaceholder,
bundle,
inputBase,
snippets
);
chunks.push(chunk);
}
for (const chunk of chunks) {
chunk.link();
}
const facades: Chunk[] = [];
for (const chunk of chunks) {
facades.push(...chunk.generateFacades());
}
return [...chunks, ...facades];
}
}
function validateOptionsForMultiChunkOutput(
outputOptions: NormalizedOutputOptions,
log: LogHandler
) {
if (outputOptions.format === 'umd' || outputOptions.format === 'iife')
return error(
logInvalidOption(
'output.format',
URL_OUTPUT_FORMAT,
'UMD and IIFE output formats are not supported for code-splitting builds',
outputOptions.format
)
);
if (typeof outputOptions.file === 'string')
return error(
logInvalidOption(
'output.file',
URL_OUTPUT_DIR,
'when building multiple chunks, the "output.dir" option must be used, not "output.file". To inline dynamic imports, set the "inlineDynamicImports" option'
)
);
if (outputOptions.sourcemapFile)
return error(
logInvalidOption(
'output.sourcemapFile',
URL_OUTPUT_SOURCEMAPFILE,
'"output.sourcemapFile" is only supported for single-file builds'
)
);
if (!outputOptions.amd.autoId && outputOptions.amd.id)
log(
LOGLEVEL_WARN,
logInvalidOption(
'output.amd.id',
URL_OUTPUT_AMD_ID,
'this option is only properly supported for single-file builds. Use "output.amd.autoId" and "output.amd.basePath" instead'
)
);
}
function getIncludedModules(modulesById: ReadonlyMap<string, Module | ExternalModule>): Module[] {
const includedModules: Module[] = [];
for (const module of modulesById.values()) {
if (
module instanceof Module &&
(module.isIncluded() || module.info.isEntry || module.includedDynamicImporters.length > 0)
) {
includedModules.push(module);
}
}
return includedModules;
}
function getAbsoluteEntryModulePaths(
includedModules: readonly Module[],
preserveModules: boolean
): string[] {
const absoluteEntryModulePaths: string[] = [];
for (const module of includedModules) {
if ((module.info.isEntry || preserveModules) && isAbsolute(module.id)) {
absoluteEntryModulePaths.push(module.id);
}
}
return absoluteEntryModulePaths;
}
function getExternalChunkByModule(
modulesById: ReadonlyMap<string, Module | ExternalModule>,
outputOptions: NormalizedOutputOptions,
inputBase: string
): Map<ExternalModule, ExternalChunk> {
const externalChunkByModule = new Map<ExternalModule, ExternalChunk>();
for (const module of modulesById.values()) {
if (module instanceof ExternalModule) {
externalChunkByModule.set(module, new ExternalChunk(module, outputOptions, inputBase));
}
}
return externalChunkByModule;
}
function addModuleToManualChunk(
alias: string,
module: Module,
manualChunkAliasByEntry: Map<Module, string>
): void {
const existingAlias = manualChunkAliasByEntry.get(module);
if (typeof existingAlias === 'string' && existingAlias !== alias) {
return error(logCannotAssignModuleToChunk(module.id, alias, existingAlias));
}
manualChunkAliasByEntry.set(module, alias);
}