This repository has been archived by the owner on Aug 31, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 667
/
Bundler.ts
427 lines (369 loc) · 10.6 KB
/
Bundler.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
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
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import {Master, MasterRequest} from "@romejs/core";
import {Reporter} from "@romejs/cli-reporter";
import {
BundleResult,
BundleResultBundle,
BundlerConfig,
BundlerFiles,
BundlerMode,
} from "../../common/types/bundler";
import DependencyGraph from "../dependencies/DependencyGraph";
import BundleRequest, {BundleOptions} from "./BundleRequest";
import {AbsoluteFilePath, createUnknownFilePath} from "@romejs/path";
import {
JSONManifest,
ManifestDefinition,
convertManifestToJSON,
} from "@romejs/codec-js-manifest";
import {WorkerCompileResult} from "../../common/bridges/WorkerBridge";
import {Dict} from "@romejs/typescript-helpers";
import {readFile} from "@romejs/fs";
import {flipPathPatterns} from "@romejs/path-match";
import {markup} from "@romejs/string-markup";
import Locker from "@romejs/core/common/utils/Locker";
import {stringifyJSON} from "@romejs/codec-json";
export type BundlerEntryResoluton = {
manifestDef: undefined | ManifestDefinition;
resolvedEntry: AbsoluteFilePath;
};
export default class Bundler {
constructor(req: MasterRequest, config: BundlerConfig) {
this.config = config;
this.master = req.master;
this.reporter = req.reporter;
this.request = req;
this.entries = [];
this.compileLocker = new Locker();
this.graph = new DependencyGraph(req, config.resolver);
}
compileLocker: Locker<string>;
graph: DependencyGraph;
master: Master;
request: MasterRequest;
reporter: Reporter;
entries: Array<AbsoluteFilePath>;
config: BundlerConfig;
static createFromMasterRequest(req: MasterRequest): Bundler {
return new Bundler(req, req.getBundlerConfigFromFlags());
}
async getResolvedEntry(
unresolvedEntry: string,
): Promise<BundlerEntryResoluton> {
const {cwd} = this.config;
const res = await this.master.resolver.resolveEntryAssert({
...this.config.resolver,
origin: cwd,
source: createUnknownFilePath(unresolvedEntry),
});
const {master} = this;
const resolvedEntry = res.path;
// Now do the same resolver request but with a package
const manifestRootResolved = master.resolver.resolveLocal({
...this.config.resolver,
origin: cwd,
requestedType: "package",
source: createUnknownFilePath(unresolvedEntry),
});
const manifestRoot: undefined | AbsoluteFilePath =
manifestRootResolved.type === "FOUND"
? manifestRootResolved.path
: undefined;
let manifestDef;
if (manifestRoot !== undefined) {
const def = master.memoryFs.getManifestDefinition(manifestRoot);
if (def !== undefined) {
manifestDef = def;
}
}
return {manifestDef, resolvedEntry};
}
createBundleRequest(
resolvedEntry: AbsoluteFilePath,
options: BundleOptions,
reporter: Reporter,
): BundleRequest {
const project = this.master.projectManager.assertProjectExisting(
resolvedEntry,
);
const mode: BundlerMode = project.config.bundler.mode;
this.entries.push(resolvedEntry);
return new BundleRequest({
bundler: this,
mode,
resolvedEntry,
options,
reporter,
});
}
async compile(path: AbsoluteFilePath): Promise<WorkerCompileResult> {
const bundleRequest = this.createBundleRequest(path, {}, this.reporter);
await bundleRequest.stepAnalyze();
bundleRequest.diagnostics.maybeThrowDiagnosticsError();
return await bundleRequest.compileJS(path);
}
// This will take multiple entry points and do some magic to make them more efficient to build in parallel
async bundleMultiple(
entries: Array<AbsoluteFilePath>,
options: BundleOptions = {},
): Promise<Map<AbsoluteFilePath, BundleResult>> {
// Clone so we can mess with it
entries = [...entries];
// Seed the dependency graph with all the entries at the same time
const processor = this.request.createDiagnosticsProcessor({
origins: [
{
category: "Bundler",
message: "Analyzing dependencies for bundleMultiple",
},
],
});
const entryUids = entries.map((entry) =>
this.master.projectManager.getUid(entry)
);
const analyzeProgress = this.reporter.progress({
name: `bundler:analyze:${entryUids.join(",")}`,
title: "Analyzing",
});
processor.setThrowAfter(100);
await this.graph.seed({
paths: entries,
diagnosticsProcessor: processor,
analyzeProgress,
validate: false,
});
analyzeProgress.end();
processor.maybeThrowDiagnosticsError();
// Now actually bundle them
const map: Map<AbsoluteFilePath, BundleResult> = new Map();
const progress = this.reporter.progress({title: "Bundling"});
progress.setTotal(entries.length);
const silentReporter = this.reporter.fork({
streams: [],
});
const promises: Set<Promise<void>> = new Set();
// Could maybe do some of this in parallel?
while (entries.length > 0) {
const entry = entries.shift()!;
const promise = (async () => {
const text = markup`<filelink target="${entry.join()}" />`;
progress.pushText(text);
map.set(entry, await this.bundle(entry, options, silentReporter));
progress.popText(text);
progress.tick();
})();
promise.then(() => {
promises.delete(promise);
});
promises.add(promise);
if (promises.size > 5) {
await Promise.race(Array.from(promises));
}
}
await Promise.all(Array.from(promises));
progress.end();
return map;
}
async bundleManifest({resolvedEntry, manifestDef}: BundlerEntryResoluton) {
let bundles: Array<BundleResultBundle> = [];
const files: BundlerFiles = new Map();
const createBundle = async (
resolvedSegment: AbsoluteFilePath,
options: BundleOptions,
): Promise<BundleResultBundle> => {
const bundle = await this.bundle(resolvedSegment, options);
for (const [path, content] of bundle.files) {
files.set(path, content);
}
bundles = bundles.concat(bundle.bundles);
return bundle.entry;
};
const entryBundle = await createBundle(resolvedEntry, {});
//
const bundleBuddyStats = this.graph.getBundleBuddyStats(this.entries);
files.set(
"bundlebuddy.json",
{
kind: "stats",
content: () => stringifyJSON(bundleBuddyStats),
},
);
// TODO ensure that __dirname is relative to the project root
if (manifestDef !== undefined) {
const newManifest = await this.deriveManifest(
manifestDef,
entryBundle,
createBundle,
(relative, buffer) => {
if (!files.has(relative)) {
files.set(
relative,
{
kind: "file",
content: () => buffer,
},
);
}
},
);
// If we have a `files` array then set it to all the newly added files
// This will have included files already there that we copied
if (newManifest.files !== undefined) {
newManifest.files = Array.from(files.keys());
}
// Add a package.json with updated values
files.set(
"package.json",
{
kind: "manifest",
content: () => stringifyJSON(newManifest),
},
);
}
return {
files,
bundles,
entry: entryBundle,
};
}
async deriveManifest(
manifestDef: ManifestDefinition,
entryBundle: BundleResultBundle,
createBundle: (
resolvedSegment: AbsoluteFilePath,
options: BundleOptions,
) => Promise<BundleResultBundle>,
addFile: (relative: string, buffer: Buffer | string) => void,
): Promise<JSONManifest> {
// TODO figure out some way to use bundleMultiple here
const manifest = manifestDef.manifest;
const newManifest: JSONManifest = {
...convertManifestToJSON(manifest),
main: entryBundle.js.path,
};
// TODO inherit some manifest properties from project configs
const project = this.master.projectManager.findProjectExisting(
manifestDef.folder,
);
if (project !== undefined) {
if (newManifest.name === undefined) {
newManifest.name = project.config.name;
}
}
// TODO remove dependencies fields, probably?
// TODO Compile a index.d.ts
// Copy manifest.files
if (manifest.files !== undefined) {
const paths = await this.master.memoryFs.glob(
manifestDef.folder,
{
overrideIgnore: flipPathPatterns(manifest.files),
},
);
for (const path of paths) {
const relative = manifestDef.folder.relative(path).join();
const buffer = await readFile(path);
addFile(relative, buffer);
}
}
// Compile manifest.bin files
const bin = manifest.bin;
if (bin !== undefined) {
const newBin: Dict<string> = {};
newManifest.bin = newBin;
const binConsumer = manifestDef.consumer.get("bin");
const isBinShorthand = typeof binConsumer.asUnknown() === "string";
for (const [binName, relative] of manifest.bin) {
const location = (isBinShorthand
? binConsumer
: binConsumer.get(binName)).getDiagnosticLocation("inner-value");
const absolute = await this.master.resolver.resolveAssert(
{
...this.config.resolver,
origin: manifestDef.folder,
source: createUnknownFilePath(relative).toExplicitRelative(),
},
{
location,
},
);
const res = await createBundle(
absolute.path,
{
prefix: `bin/${binName}`,
interpreter: "/usr/bin/env node",
},
);
newBin[binName] = res.js.path;
}
}
// TODO `{type: "module"}` will always fail since we've produced CJS bundles
// rome-ignore lint/js/noDelete
delete newManifest.type;
return newManifest;
}
async bundle(
resolvedEntry: AbsoluteFilePath,
options: BundleOptions = {},
reporter: Reporter = this.reporter,
): Promise<BundleResult> {
reporter.info(
markup`Bundling <filelink emphasis target="${resolvedEntry.join()}" />`,
);
const req = this.createBundleRequest(resolvedEntry, options, reporter);
const res = await req.bundle();
const processor = this.request.createDiagnosticsProcessor();
processor.addDiagnostics(res.diagnostics);
processor.maybeThrowDiagnosticsError();
if (res.cached) {
reporter.warn("Bundle was built completely from cache");
}
const prefix = options.prefix === undefined ? "" : `${options.prefix}/`;
const jsPath = `${prefix}index.js`;
const mapPath = `${jsPath}.map`;
const files: BundlerFiles = new Map();
files.set(
jsPath,
{
kind: "entry",
content: () => res.content,
},
);
files.set(
mapPath,
{
kind: "sourcemap",
content: () => res.sourceMap.toJSON(),
},
);
for (const [relative, buffer] of res.assets) {
files.set(
relative,
{
kind: "asset",
content: () => buffer,
},
);
}
const bundle: BundleResultBundle = {
js: {
path: jsPath,
content: res.content,
},
sourceMap: {
path: mapPath,
map: res.sourceMap,
},
};
return {
entry: bundle,
bundles: [bundle],
files,
};
}
}