-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
bundler.zig
3649 lines (3222 loc) · 168 KB
/
bundler.zig
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
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const bun = @import("global.zig");
const string = bun.string;
const Output = bun.Output;
const Global = bun.Global;
const Environment = bun.Environment;
const strings = bun.strings;
const MutableString = bun.MutableString;
const stringZ = bun.stringZ;
const default_allocator = bun.default_allocator;
const StoredFileDescriptorType = bun.StoredFileDescriptorType;
const FeatureFlags = bun.FeatureFlags;
const C = bun.C;
const std = @import("std");
const lex = @import("js_lexer.zig");
const logger = @import("logger.zig");
const options = @import("options.zig");
const js_parser = @import("js_parser.zig");
const json_parser = @import("json_parser.zig");
const js_printer = @import("js_printer.zig");
const js_ast = @import("js_ast.zig");
const linker = @import("linker.zig");
const Ref = @import("ast/base.zig").Ref;
const Define = @import("defines.zig").Define;
const DebugOptions = @import("./cli.zig").Command.DebugOptions;
const ThreadPoolLib = @import("./thread_pool.zig");
const panicky = @import("panic_handler.zig");
const Fs = @import("fs.zig");
const schema = @import("api/schema.zig");
const Api = schema.Api;
const _resolver = @import("./resolver/resolver.zig");
const sync = @import("sync.zig");
const ImportRecord = @import("./import_record.zig").ImportRecord;
const allocators = @import("./allocators.zig");
const MimeType = @import("./http/mime_type.zig");
const resolve_path = @import("./resolver/resolve_path.zig");
const runtime = @import("./runtime.zig");
const Timer = @import("./timer.zig");
const hash_map = @import("hash_map.zig");
const PackageJSON = @import("./resolver/package_json.zig").PackageJSON;
const MacroRemap = @import("./resolver/package_json.zig").MacroMap;
const DebugLogs = _resolver.DebugLogs;
const NodeModuleBundle = @import("./node_module_bundle.zig").NodeModuleBundle;
const Router = @import("./router.zig");
const isPackagePath = _resolver.isPackagePath;
const Css = @import("css_scanner.zig");
const DotEnv = @import("./env_loader.zig");
const Lock = @import("./lock.zig").Lock;
const NodeFallbackModules = @import("./node_fallbacks.zig");
const CacheEntry = @import("./cache.zig").FsCacheEntry;
const Analytics = @import("./analytics/analytics_thread.zig");
const URL = @import("./url.zig").URL;
const Report = @import("./report.zig");
const Linker = linker.Linker;
const Resolver = _resolver.Resolver;
const TOML = @import("./toml/toml_parser.zig").TOML;
const EntryPoints = @import("./bundler/entry_points.zig");
pub usingnamespace EntryPoints;
// How it works end-to-end
// 1. Resolve a file path from input using the resolver
// 2. Look at the extension of that file path, and determine a loader
// 3. If the loader is .js, .jsx, .ts, .tsx, or .json, run it through our JavaScript Parser
// IF serving via HTTP and it's parsed without errors:
// 4. If parsed without errors, generate a strong ETag & write the output to a buffer that sends to the in the Printer.
// 4. Else, write any errors to error page (which doesn't exist yet)
// IF writing to disk AND it's parsed without errors:
// 4. Write the output to a temporary file.
// Why? Two reasons.
// 1. At this point, we don't know what the best output path is.
// Most of the time, you want the shortest common path, which you can't know until you've
// built & resolved all paths.
// Consider this directory tree:
// - /Users/jarred/Code/app/src/index.tsx
// - /Users/jarred/Code/app/src/Button.tsx
// - /Users/jarred/Code/app/assets/logo.png
// - /Users/jarred/Code/app/src/Button.css
// - /Users/jarred/Code/app/node_modules/react/index.js
// - /Users/jarred/Code/app/node_modules/react/cjs/react.development.js
// Remember that we cannot know which paths need to be resolved without parsing the JavaScript.
// If we stopped here: /Users/jarred/Code/app/src/Button.tsx
// We would choose /Users/jarred/Code/app/src/ as the directory
// Then, that would result in a directory structure like this:
// - /Users/jarred/Code/app/src/Users/jarred/Code/app/node_modules/react/cjs/react.development.js
// Which is absolutely insane
//
// 2. We will need to write to disk at some point!
// - If we delay writing to disk, we need to print & allocate a potentially quite large
// buffer (react-dom.development.js is 550 KB)
// ^ This is how it used to work!
// - If we delay printing, we need to keep the AST around. Which breaks all our
// memory-saving recycling logic since that could be many many ASTs.
// 5. Once all files are written, determine the shortest common path
// 6. Move all the temporary files to their intended destinations
// IF writing to disk AND it's a file-like loader
// 4. Hash the contents
// - rewrite_paths.put(absolute_path, hash(file(absolute_path)))
// 5. Resolve any imports of this file to that hash(file(absolute_path))
// 6. Append to the files array with the new filename
// 7. When parsing & resolving is over, just copy the file.
// - on macOS, ensure it does an APFS shallow clone so that doesn't use disk space (only possible if file doesn't already exist)
// fclonefile
// IF serving via HTTP AND it's a file-like loader:
// 4. Use os.sendfile so copying/reading the file happens in the kernel instead of in bun.
// This unfortunately means content hashing for HTTP server is unsupported, but metadata etags work
// For each imported file, GOTO 1.
pub const ParseResult = struct {
source: logger.Source,
loader: options.Loader,
ast: js_ast.Ast,
input_fd: ?StoredFileDescriptorType = null,
empty: bool = false,
};
const cache_files = false;
pub const Bundler = struct {
const ThisBundler = @This();
options: options.BundleOptions,
log: *logger.Log,
allocator: std.mem.Allocator,
result: options.TransformResult = undefined,
resolver: Resolver,
fs: *Fs.FileSystem,
// thread_pool: *ThreadPool,
output_files: std.ArrayList(options.OutputFile),
resolve_results: *ResolveResults,
resolve_queue: ResolveQueue,
elapsed: u64 = 0,
needs_runtime: bool = false,
router: ?Router = null,
linker: Linker,
timer: std.time.Timer = undefined,
env: *DotEnv.Loader,
macro_context: ?js_ast.Macro.MacroContext = null,
pub const isCacheEnabled = cache_files;
pub fn clone(this: *ThisBundler, allocator: std.mem.Allocator, to: *ThisBundler) !void {
to.* = this.*;
to.setAllocator(allocator);
to.log = try allocator.create(logger.Log);
to.log.* = logger.Log.init(allocator);
to.setLog(to.log);
to.macro_context = null;
}
pub fn setLog(this: *ThisBundler, log: *logger.Log) void {
this.log = log;
this.linker.log = log;
this.resolver.log = log;
}
pub fn setAllocator(this: *ThisBundler, allocator: std.mem.Allocator) void {
this.allocator = allocator;
this.linker.allocator = allocator;
this.resolver.allocator = allocator;
}
pub inline fn resolveEntryPoint(bundler: *ThisBundler, entry_point: string) !_resolver.Result {
return bundler.resolver.resolve(bundler.fs.top_level_dir, entry_point, .entry_point) catch |err| {
const has_dot_slash_form = !strings.hasPrefix(entry_point, "./") and brk: {
_ = bundler.resolver.resolve(bundler.fs.top_level_dir, try strings.append(bundler.allocator, "./", entry_point), .entry_point) catch break :brk false;
break :brk true;
};
if (has_dot_slash_form) {
bundler.log.addErrorFmt(null, logger.Loc.Empty, bundler.allocator, "{s} resolving \"{s}\". Did you mean: \"./{s}\"", .{
@errorName(err),
entry_point,
entry_point,
}) catch unreachable;
} else {
bundler.log.addErrorFmt(null, logger.Loc.Empty, bundler.allocator, "{s} resolving \"{s}\" (entry point)", .{ @errorName(err), entry_point }) catch unreachable;
}
return err;
};
}
// to_bundle:
// thread_pool: *ThreadPool,
pub fn init(
allocator: std.mem.Allocator,
log: *logger.Log,
opts: Api.TransformOptions,
existing_bundle: ?*NodeModuleBundle,
env_loader_: ?*DotEnv.Loader,
) !ThisBundler {
js_ast.Expr.Data.Store.create(allocator);
js_ast.Stmt.Data.Store.create(allocator);
var fs = try Fs.FileSystem.init1(
allocator,
opts.absolute_working_dir,
);
const bundle_options = try options.BundleOptions.fromApi(
allocator,
fs,
log,
opts,
existing_bundle,
);
var env_loader = env_loader_ orelse brk: {
var map = try allocator.create(DotEnv.Map);
map.* = DotEnv.Map.init(allocator);
var loader = try allocator.create(DotEnv.Loader);
loader.* = DotEnv.Loader.init(map, allocator);
break :brk loader;
};
DotEnv.instance = env_loader;
// var pool = try allocator.create(ThreadPool);
// try pool.init(ThreadPool.InitConfig{
// .allocator = allocator,
// });
var resolve_results = try allocator.create(ResolveResults);
resolve_results.* = ResolveResults.init(allocator);
return ThisBundler{
.options = bundle_options,
.fs = fs,
.allocator = allocator,
.timer = std.time.Timer.start() catch @panic("Timer fail"),
.resolver = Resolver.init1(allocator, log, fs, bundle_options),
.log = log,
// .thread_pool = pool,
.linker = undefined,
.result = options.TransformResult{ .outbase = bundle_options.output_dir },
.resolve_results = resolve_results,
.resolve_queue = ResolveQueue.init(allocator),
.output_files = std.ArrayList(options.OutputFile).init(allocator),
.env = env_loader,
};
}
pub fn configureLinkerWithAutoJSX(bundler: *ThisBundler, auto_jsx: bool) void {
bundler.linker = Linker.init(
bundler.allocator,
bundler.log,
&bundler.resolve_queue,
&bundler.options,
&bundler.resolver,
bundler.resolve_results,
bundler.fs,
);
if (auto_jsx) {
// If we don't explicitly pass JSX, try to get it from the root tsconfig
if (bundler.options.transform_options.jsx == null) {
// Most of the time, this will already be cached
if (bundler.resolver.readDirInfo(bundler.fs.top_level_dir) catch null) |root_dir| {
if (root_dir.tsconfig_json) |tsconfig| {
bundler.options.jsx = tsconfig.jsx;
}
}
}
}
}
pub fn configureLinker(bundler: *ThisBundler) void {
bundler.configureLinkerWithAutoJSX(true);
}
pub fn runEnvLoader(this: *ThisBundler) !void {
switch (this.options.env.behavior) {
.prefix, .load_all => {
// Step 1. Load the project root.
var dir: *Fs.FileSystem.DirEntry = ((this.resolver.readDirInfo(this.fs.top_level_dir) catch return) orelse return).getEntries() orelse return;
// Process always has highest priority.
this.env.loadProcess();
if (this.options.production) {
try this.env.load(&this.fs.fs, dir, false);
} else {
try this.env.load(&this.fs.fs, dir, true);
}
},
.disable => {
this.env.loadProcess();
},
else => {},
}
if (this.env.map.get("DISABLE_BUN_ANALYTICS")) |should_disable| {
if (strings.eqlComptime(should_disable, "1")) {
Analytics.disabled = true;
}
}
if (this.env.map.get("CI") orelse
this.env.map.get("TDDIUM") orelse
this.env.map.get("JENKINS_URL") orelse
this.env.map.get("bamboo.buildKey")) |_|
{
Analytics.is_ci = true;
}
Analytics.disabled = Analytics.disabled or this.env.map.get("HYPERFINE_RANDOMIZED_ENVIRONMENT_OFFSET") != null;
}
// This must be run after a framework is configured, if a framework is enabled
pub fn configureDefines(this: *ThisBundler) !void {
if (this.options.defines_loaded) {
return;
}
if (this.options.platform == .bun_macro) {
this.options.env.behavior = .prefix;
this.options.env.prefix = "BUN_";
}
try this.runEnvLoader();
js_ast.Expr.Data.Store.create(this.allocator);
js_ast.Stmt.Data.Store.create(this.allocator);
defer js_ast.Expr.Data.Store.reset();
defer js_ast.Stmt.Data.Store.reset();
if (this.options.framework) |framework| {
if (this.options.platform.isClient()) {
try this.options.loadDefines(this.allocator, this.env, &framework.client.env);
} else {
try this.options.loadDefines(this.allocator, this.env, &framework.server.env);
}
} else {
try this.options.loadDefines(this.allocator, this.env, &this.options.env);
}
}
pub fn configureFramework(
this: *ThisBundler,
comptime load_defines: bool,
) !void {
if (this.options.framework) |*framework| {
if (framework.needsResolveFromPackage()) {
var route_config = this.options.routes;
var pair = PackageJSON.FrameworkRouterPair{ .framework = framework, .router = &route_config };
if (framework.development) {
try this.resolver.resolveFramework(framework.package, &pair, .development, load_defines);
} else {
try this.resolver.resolveFramework(framework.package, &pair, .production, load_defines);
}
if (this.options.areDefinesUnset()) {
if (this.options.platform.isClient()) {
this.options.env = framework.client.env;
} else {
this.options.env = framework.server.env;
}
}
if (pair.loaded_routes) {
this.options.routes = route_config;
}
framework.resolved = true;
this.options.framework = framework.*;
} else if (!framework.resolved) {
Global.panic("directly passing framework path is not implemented yet!", .{});
}
}
}
pub fn configureFrameworkWithResolveResult(this: *ThisBundler, comptime client: bool) !?_resolver.Result {
if (this.options.framework != null) {
try this.configureFramework(true);
if (comptime client) {
if (this.options.framework.?.client.isEnabled()) {
return try this.resolver.resolve(this.fs.top_level_dir, this.options.framework.?.client.path, .stmt);
}
if (this.options.framework.?.fallback.isEnabled()) {
return try this.resolver.resolve(this.fs.top_level_dir, this.options.framework.?.fallback.path, .stmt);
}
} else {
if (this.options.framework.?.server.isEnabled()) {
return try this.resolver.resolve(this.fs.top_level_dir, this.options.framework.?.server, .stmt);
}
}
}
return null;
}
pub fn configureRouter(this: *ThisBundler, comptime load_defines: bool) !void {
try this.configureFramework(load_defines);
defer {
if (load_defines) {
this.configureDefines() catch {};
}
}
// if you pass just a directory, activate the router configured for the pages directory
// for now:
// - "." is not supported
// - multiple pages directories is not supported
if (!this.options.routes.routes_enabled and this.options.entry_points.len == 1 and !this.options.serve) {
// When inferring:
// - pages directory with a file extension is not supported. e.g. "pages.app/" won't work.
// This is a premature optimization to avoid this magical auto-detection we do here from meaningfully increasing startup time if you're just passing a file
// readDirInfo is a recursive lookup, top-down instead of bottom-up. It opens each folder handle and potentially reads the package.jsons
// So it is not fast! Unless it's already cached.
var paths = [_]string{std.mem.trimLeft(u8, this.options.entry_points[0], "./")};
if (std.mem.indexOfScalar(u8, paths[0], '.') == null) {
var pages_dir_buf: [bun.MAX_PATH_BYTES]u8 = undefined;
var entry = this.fs.absBuf(&paths, &pages_dir_buf);
if (std.fs.path.extension(entry).len == 0) {
bun.constStrToU8(entry).ptr[entry.len] = '/';
// Only throw if they actually passed in a route config and the directory failed to load
var dir_info_ = this.resolver.readDirInfo(entry) catch return;
var dir_info = dir_info_ orelse return;
this.options.routes.dir = dir_info.abs_path;
this.options.routes.extensions = std.mem.span(&options.RouteConfig.DefaultExtensions);
this.options.routes.routes_enabled = true;
this.router = try Router.init(this.fs, this.allocator, this.options.routes);
try this.router.?.loadRoutes(
this.log,
dir_info,
Resolver,
&this.resolver,
);
this.router.?.routes.client_framework_enabled = this.options.isFrontendFrameworkEnabled();
return;
}
}
} else if (this.options.routes.routes_enabled) {
var dir_info_ = try this.resolver.readDirInfo(this.options.routes.dir);
var dir_info = dir_info_ orelse return error.MissingRoutesDir;
this.options.routes.dir = dir_info.abs_path;
this.router = try Router.init(this.fs, this.allocator, this.options.routes);
try this.router.?.loadRoutes(this.log, dir_info, Resolver, &this.resolver);
this.router.?.routes.client_framework_enabled = this.options.isFrontendFrameworkEnabled();
return;
}
// If we get this far, it means they're trying to run the bundler without a preconfigured router
if (this.options.entry_points.len > 0) {
this.options.routes.routes_enabled = false;
}
if (this.router) |*router| {
router.routes.client_framework_enabled = this.options.isFrontendFrameworkEnabled();
}
}
pub fn resetStore(_: *const ThisBundler) void {
js_ast.Expr.Data.Store.reset();
js_ast.Stmt.Data.Store.reset();
}
pub noinline fn dumpEnvironmentVariables(bundler: *const ThisBundler) void {
@setCold(true);
const opts = std.json.StringifyOptions{
.whitespace = std.json.StringifyOptions.Whitespace{
.separator = true,
},
};
Output.flush();
std.json.stringify(bundler.env.map.*, opts, Output.writer()) catch unreachable;
Output.flush();
}
pub const GenerateNodeModuleBundle = struct {
const BunQueue = sync.Channel(PendingImports, .Dynamic);
pub const ThreadPool = struct {
pool: ThreadPoolLib = undefined,
// Hardcode 512 as max number of threads for now.
workers: [512]Worker = undefined,
workers_used: std.atomic.Atomic(u32) = std.atomic.Atomic(u32).init(0),
cpu_count: u32 = 0,
started_workers: std.atomic.Atomic(u32) = std.atomic.Atomic(u32).init(0),
stopped_workers: std.atomic.Atomic(u32) = std.atomic.Atomic(u32).init(0),
completed_count: std.atomic.Atomic(u32) = std.atomic.Atomic(u32).init(0),
pending_count: std.atomic.Atomic(u32) = std.atomic.Atomic(u32).init(0),
generator: *GenerateNodeModuleBundle = undefined,
pub fn start(this: *ThreadPool, generator: *GenerateNodeModuleBundle) !void {
generator.bundler.env.loadProcess();
this.generator = generator;
this.cpu_count = @truncate(u32, @divFloor((try std.Thread.getCpuCount()) + 1, 2));
if (generator.bundler.env.map.get("GOMAXPROCS")) |max_procs| {
if (std.fmt.parseInt(u32, max_procs, 10)) |cpu_count| {
this.cpu_count = std.math.min(this.cpu_count, cpu_count);
} else |_| {}
}
this.pool = ThreadPoolLib.init(.{
.max_threads = this.cpu_count,
});
this.pool.on_thread_spawn = Worker.onSpawn;
this.pool.threadpool_context = this;
var workers_used: u32 = 0;
while (workers_used < this.cpu_count) : (workers_used += 1) {
try this.workers[workers_used].init(generator);
}
if (workers_used > 0)
this.pool.forceSpawn();
}
pub fn wait(this: *ThreadPool, generator: *GenerateNodeModuleBundle) !void {
while (true) {
while (this.generator.queue.tryReadItem() catch null) |queue| {
var iter = queue.iterator();
var batch = ThreadPoolLib.Batch{};
var count: u32 = 0;
while (iter.next()) |entry| {
const module_id: u32 = entry.key_ptr.*;
const exists = generator.enqueued_map.getOrPut(module_id) catch unreachable;
if (exists.found_existing) {
continue;
}
batch.push(ThreadPoolLib.Batch.from(&entry.value_ptr.*.task));
count += 1;
}
_ = this.pending_count.fetchAdd(count, .Monotonic);
this.pool.schedule(batch);
}
if (this.completed_count.load(.Monotonic) > 0 and this.completed_count.load(.Monotonic) == this.pending_count.load(.Monotonic)) {
break;
}
std.atomic.spinLoopHint();
}
const workers: []const Worker = this.workers[0..this.workers_used.loadUnchecked()];
for (workers) |worker| {
this.generator.estimated_input_lines_of_code += worker.data.estimated_input_lines_of_code;
try worker.data.log.appendTo(this.generator.log);
}
}
pub const Task = struct {
result: _resolver.Result,
generator: *GenerateNodeModuleBundle,
};
pub const Worker = struct {
thread_id: std.Thread.Id,
thread: std.Thread,
allocator: std.mem.Allocator,
generator: *GenerateNodeModuleBundle,
data: *WorkerData = undefined,
quit: bool = false,
has_notify_started: bool = false,
pub const WorkerData = struct {
shared_buffer: MutableString = undefined,
scan_pass_result: js_parser.ScanPassResult = undefined,
log: *logger.Log,
estimated_input_lines_of_code: usize = 0,
macro_context: js_ast.Macro.MacroContext,
bundler: Bundler = undefined,
pub fn deinit(this: *WorkerData, allocator: std.mem.Allocator) void {
this.shared_buffer.deinit();
this.scan_pass_result.named_imports.deinit();
this.scan_pass_result.import_records.deinit();
allocator.destroy(this);
}
};
pub fn init(worker: *Worker, generator: *GenerateNodeModuleBundle) !void {
worker.generator = generator;
worker.allocator = generator.allocator;
}
pub fn onSpawn(ctx: ?*anyopaque) ?*anyopaque {
var pool = @ptrCast(*ThreadPool, @alignCast(@alignOf(*ThreadPool), ctx.?));
const id = pool.workers_used.fetchAdd(1, .Monotonic);
pool.workers[id].run();
return &pool.workers[id];
}
pub fn notifyStarted(this: *Worker) void {
if (!this.has_notify_started) {
this.has_notify_started = true;
_ = this.generator.pool.started_workers.fetchAdd(1, .Release);
std.Thread.Futex.wake(&this.generator.pool.started_workers, std.math.maxInt(u32));
}
}
pub fn run(this: *Worker) void {
Output.Source.configureThread();
this.thread_id = std.Thread.getCurrentId();
if (Environment.isDebug) {
Output.prettyln("Thread started.\n", .{});
}
js_ast.Expr.Data.Store.create(this.generator.allocator);
js_ast.Stmt.Data.Store.create(this.generator.allocator);
this.data = this.generator.allocator.create(WorkerData) catch unreachable;
this.data.* = WorkerData{
.log = this.generator.allocator.create(logger.Log) catch unreachable,
.estimated_input_lines_of_code = 0,
.macro_context = js_ast.Macro.MacroContext.init(this.generator.bundler),
};
this.data.log.* = logger.Log.init(this.generator.allocator);
this.data.shared_buffer = MutableString.init(this.generator.allocator, 0) catch unreachable;
this.data.scan_pass_result = js_parser.ScanPassResult.init(this.generator.allocator);
this.data.bundler = this.generator.bundler.*;
var bundler_ptr = &this.data.bundler;
const CacheSet = @import("./cache.zig");
// no funny business mr. cache
bundler_ptr.resolver.caches = CacheSet.Set.init(this.allocator);
bundler_ptr.linker.resolver = &bundler_ptr.resolver;
bundler_ptr.log = this.data.log;
bundler_ptr.linker.log = this.data.log;
bundler_ptr.linker.resolver.log = this.data.log;
}
pub const ProcessFileTask = struct {
resolution: _resolver.Result,
task: ThreadPoolLib.Task = .{ .callback = callback },
pub fn callback(task: *ThreadPoolLib.Task) void {
var worker = @ptrCast(
*ThreadPool.Worker,
@alignCast(
@alignOf(*ThreadPool.Worker),
ThreadPoolLib.Thread.current.?.ctx.?,
),
);
var process: *ProcessFileTask = @fieldParentPtr(ProcessFileTask, "task", task);
worker.generator.processFile(
worker,
&worker.data.bundler,
process.resolution,
) catch {};
_ = worker.generator.pool.completed_count.fetchAdd(1, .Monotonic);
}
};
};
};
write_lock: Lock,
log_lock: Lock = Lock.init(),
module_list: std.ArrayList(Api.JavascriptBundledModule),
package_list: std.ArrayList(Api.JavascriptBundledPackage),
header_string_buffer: MutableString,
// Just need to know if we've already enqueued this one
package_list_map: std.AutoHashMap(u64, u32),
enqueued_map: std.AutoHashMap(u32, void),
queue: BunQueue,
bundler: *ThisBundler,
allocator: std.mem.Allocator,
tmpfile: std.fs.File,
log: *logger.Log,
pool: *ThreadPool,
tmpfile_byte_offset: u32 = 0,
code_end_byte_offset: u32 = 0,
has_jsx: bool = false,
estimated_input_lines_of_code: usize = 0,
work_waiter: std.atomic.Atomic(u32) = std.atomic.Atomic(u32).init(0),
list_lock: Lock = Lock.init(),
dynamic_import_file_size_store: U32Map,
dynamic_import_file_size_store_lock: Lock,
always_bundled_package_hashes: []u32 = &[_]u32{},
always_bundled_package_jsons: []*const PackageJSON = &.{},
always_bundled_booleans: []bool = &.{},
package_bundle_map: options.BundlePackage.Map = options.BundlePackage.Map{},
const U32Map = std.AutoHashMap(u32, u32);
pub const current_version: u32 = 1;
const dist_index_js_string_pointer = Api.StringPointer{ .length = "dist/index.js".len };
const index_js_string_pointer = Api.StringPointer{ .length = "index.js".len, .offset = "dist/".len };
fn upsert(this: *GenerateNodeModuleBundle, module_id: u32, resolve: _resolver.Result) !void {
var dedupe = try this.enqueued_map.getOrPut(module_id);
if (dedupe.found_existing) return;
var task = try this.allocator.create(ThreadPool.Worker.ProcessFileTask);
task.* = ThreadPool.Worker.ProcessFileTask{
.resolution = resolve,
};
_ = this.pool.pending_count.fetchAdd(1, .Monotonic);
this.pool.pool.schedule(ThreadPoolLib.Batch.from(&task.task));
}
pub fn ensurePathIsAllocated(this: *GenerateNodeModuleBundle, path_: ?*Fs.Path) !void {
var path = path_ orelse return;
const loader = this.bundler.options.loaders.get(path.name.ext) orelse .file;
if (!loader.isJavaScriptLikeOrJSON()) return;
path.* = try path.dupeAlloc(this.allocator);
}
pub fn enqueueItem(this: *GenerateNodeModuleBundle, resolve: _resolver.Result) !void {
var result = resolve;
var path = result.path() orelse return;
const loader = this.bundler.options.loaders.get(path.name.ext) orelse .file;
if (!loader.isJavaScriptLikeOrJSON()) return;
path.* = try path.dupeAlloc(this.allocator);
if (BundledModuleData.get(this, &result)) |mod| {
try this.upsert(mod.module_id, result);
} else {
try this.upsert(result.hash(this.bundler.fs.top_level_dir, loader), result);
}
}
// The bun Bundle Format
// All the node_modules your app uses in a single compact file with metadata
// A binary JavaScript bundle format prioritizing generation time and deserialization time
pub const magic_bytes = "#!/usr/bin/env bun\n\n";
// This makes it possible to do ./path-to-bundle on posix systems so you can see the raw JS contents
// https://en.wikipedia.org/wiki/Magic_number_(programming)#In_files
// Immediately after the magic bytes, the next character is a uint32 followed by a newline
// 0x00000000\n
// That uint32 denotes the byte offset in the file where the code for the bundle ends
// - If the value is 0, that means the file did not finish writing or there are no modules
// - This imposes a maximum bundle size of around 4,294,967,295 bytes. If your JS is more than 4 GB, it won't work.
// The raw JavaScript is encoded as a UTF-8 string starting from the current position + 1 until the above byte offset.
// This uint32 is useful for HTTP servers to separate:
// - Which part of the bundle is the JS code?
// - Which part is the metadata?
// Without needing to do a full pass through the file, or necessarily care about the metadata.
// The metadata is at the bottom of the file instead of the top because the metadata is written after all JS code in the bundle is written.
// The rationale there is:
// 1. We cannot prepend to a file without rewriting the entire file
// 2. The metadata is variable-length and that format will change often.
// 3. We won't have all the metadata until after all JS is finished writing
// If you have 32 MB of JavaScript dependencies, you really want to avoid reading the code in memory.
// - This lets you seek to the specific position in the file.
// - HTTP servers should use sendfile() instead of copying the file to userspace memory.
// So instead, we append metadata to the file after printing each node_module
// When there are no more modules to process, we generate the metadata
// To find the metadata, you look at the byte offset: initial_header[magic_bytes.len..initial_header.len - 1]
// Then, you add that number to initial_header.len
const initial_header = brk: {
var buf = std.mem.zeroes([magic_bytes.len + 5]u8);
std.mem.copy(u8, &buf, magic_bytes);
var remainder = buf[magic_bytes.len..];
// Write an invalid byte offset to be updated after we finish generating the code
std.mem.writeIntNative(u32, remainder[0 .. remainder.len - 1], 0);
buf[buf.len - 1] = '\n';
break :brk buf;
};
const code_start_byte_offset: u32 = initial_header.len;
// The specifics of the metadata is not documented here. You can find it in src/api/schema.peechy.
pub fn appendHeaderString(generator: *GenerateNodeModuleBundle, str: string) !Api.StringPointer {
// This is so common we might as well just reuse it
// Plus this is one machine word so it's a quick comparison
if (strings.eqlComptime(str, "index.js")) {
return index_js_string_pointer;
} else if (strings.eqlComptime(str, "dist/index.js")) {
return dist_index_js_string_pointer;
}
var offset = generator.header_string_buffer.list.items.len;
try generator.header_string_buffer.append(str);
return Api.StringPointer{
.offset = @truncate(u32, offset),
.length = @truncate(u32, str.len),
};
}
pub fn generate(
bundler: *ThisBundler,
allocator: std.mem.Allocator,
framework_config: ?Api.LoadedFramework,
route_config: ?Api.LoadedRouteConfig,
destination: [*:0]const u8,
estimated_input_lines_of_code: *usize,
package_bundle_map: options.BundlePackage.Map,
) !?Api.JavascriptBundleContainer {
_ = try bundler.fs.fs.openTmpDir();
var tmpname_buf: [64]u8 = undefined;
bundler.resetStore();
try bundler.configureDefines();
const tmpname = try bundler.fs.tmpname(
".bun",
std.mem.span(&tmpname_buf),
std.hash.Wyhash.hash(@intCast(usize, std.time.milliTimestamp()) % std.math.maxInt(u32), std.mem.span(destination)),
);
var tmpfile = Fs.FileSystem.RealFS.Tmpfile{};
try tmpfile.create(&bundler.fs.fs, tmpname);
errdefer tmpfile.closeAndDelete(tmpname);
var generator = try allocator.create(GenerateNodeModuleBundle);
var queue = BunQueue.init(allocator);
defer allocator.destroy(generator);
generator.* = GenerateNodeModuleBundle{
.module_list = std.ArrayList(Api.JavascriptBundledModule).init(allocator),
.package_list = std.ArrayList(Api.JavascriptBundledPackage).init(allocator),
.header_string_buffer = try MutableString.init(allocator, "dist/index.js".len),
.allocator = allocator,
.enqueued_map = std.AutoHashMap(u32, void).init(allocator),
.queue = queue,
.estimated_input_lines_of_code = 0,
// .resolve_queue = queue,
.bundler = bundler,
.tmpfile = tmpfile.file(),
.dynamic_import_file_size_store = U32Map.init(allocator),
.dynamic_import_file_size_store_lock = Lock.init(),
.log = bundler.log,
.package_list_map = std.AutoHashMap(u64, u32).init(allocator),
.pool = undefined,
.write_lock = Lock.init(),
.package_bundle_map = package_bundle_map,
};
// dist/index.js appears more common than /index.js
// but this means we can store both "dist/index.js" and "index.js" in one.
try generator.header_string_buffer.append("dist/index.js");
try generator.package_list_map.ensureTotalCapacity(128);
var pool = try allocator.create(ThreadPool);
pool.* = ThreadPool{};
generator.pool = pool;
var this = generator;
// Always inline the runtime into the bundle
try generator.appendBytes(&initial_header);
if (bundler.log.level == .verbose) {
bundler.resolver.debug_logs = try DebugLogs.init(allocator);
}
Analytics.Features.bun_bun = true;
always_bundled: {
const root_package_json_resolved: _resolver.Result = bundler.resolver.resolve(bundler.fs.top_level_dir, "./package.json", .stmt) catch {
generator.log.addWarning(null, logger.Loc.Empty, "Please run `bun bun` from a directory containing a package.json.") catch unreachable;
break :always_bundled;
};
const root_package_json = root_package_json_resolved.package_json orelse brk: {
const read_dir = (bundler.resolver.readDirInfo(bundler.fs.top_level_dir) catch unreachable).?;
Analytics.Features.tsconfig = Analytics.Features.tsconfig or read_dir.tsconfig_json != null;
break :brk read_dir.package_json.?;
};
Analytics.setProjectID(std.fs.path.dirname(root_package_json.source.path.text) orelse "/", root_package_json.name);
if (bundler.macro_context) |macro_ctx| {
Analytics.Features.macros = macro_ctx.remap.count() > 0;
}
const bundle_keys = package_bundle_map.keys();
const do_always_bundle = package_bundle_map.values();
var always_bundle_count: u32 = @truncate(u32, bundle_keys.len);
if (always_bundle_count != 0) {
Analytics.Features.always_bundle = true;
var always_bundled_package_jsons = bundler.allocator.alloc(*PackageJSON, always_bundle_count) catch unreachable;
var always_bundled_package_hashes = bundler.allocator.alloc(u32, always_bundle_count) catch unreachable;
var always_bundled_booleans = bundler.allocator.alloc(bool, always_bundle_count) catch unreachable;
var i: u16 = 0;
inner: for (bundle_keys) |name, k| {
std.mem.copy(u8, &tmp_buildfile_buf, name);
std.mem.copy(u8, tmp_buildfile_buf[name.len..], "/package.json");
const package_json_import = tmp_buildfile_buf[0 .. name.len + "/package.json".len];
const result = bundler.resolver.resolve(bundler.fs.top_level_dir, package_json_import, .stmt) catch |err| {
generator.log.addErrorFmt(null, logger.Loc.Empty, bundler.allocator, "{s} resolving always bundled module \"{s}\"", .{ @errorName(err), name }) catch unreachable;
continue :inner;
};
var package_json: *PackageJSON = result.package_json orelse brk: {
const read_dir = (bundler.resolver.readDirInfo(package_json_import) catch unreachable).?;
if (read_dir.package_json == null) {
generator.log.addWarningFmt(null, logger.Loc.Empty, bundler.allocator, "{s} missing package.json. It will not be bundled", .{name}) catch unreachable;
continue :inner;
}
break :brk read_dir.package_json.?;
};
package_json.source.key_path = result.path_pair.primary;
// if (!strings.contains(result.path_pair.primary.text, package_json.name)) {
// generator.log.addErrorFmt(
// null,
// logger.Loc.Empty,
// bundler.allocator,
// "Bundling \"{s}\" is not supported because the package isn.\n To fix this, move the package's code to a directory containing the name.\n Location: \"{s}\"",
// .{
// name,
// name,
// result.path_pair.primary.text,
// },
// ) catch unreachable;
// continue :inner;
// }
always_bundled_package_jsons[i] = package_json;
always_bundled_package_hashes[i] = package_json.hash;
always_bundled_booleans[i] = do_always_bundle[k] == .always;
i += 1;
}
generator.always_bundled_package_hashes = always_bundled_package_hashes[0..i];
generator.always_bundled_package_jsons = always_bundled_package_jsons[0..i];
generator.always_bundled_booleans = always_bundled_booleans[0..i];
}
}
if (generator.log.errors > 0) return error.BundleFailed;
this.bundler.macro_context = js_ast.Macro.MacroContext.init(bundler);
const include_refresh_runtime =
!this.bundler.options.production and
this.bundler.options.jsx.supports_fast_refresh and
bundler.options.platform.isWebLike();
if (framework_config != null) {
defer this.bundler.resetStore();
try this.bundler.configureFramework(true);
if (bundler.options.framework) |framework| {
Analytics.Features.framework = true;
if (framework.override_modules.keys.len > 0) {
bundler.options.framework.?.override_modules_hashes = allocator.alloc(u64, framework.override_modules.keys.len) catch unreachable;
for (framework.override_modules.keys) |key, i| {
bundler.options.framework.?.override_modules_hashes[i] = std.hash.Wyhash.hash(0, key);
}
}
}
} else {}
this.pool.start(this) catch |err| {
Analytics.enqueue(Analytics.EventName.bundle_fail);
return err;
};
// The ordering matters here The runtime must appear at the top of
// the file But, we don't know which version of the runtime is
// necessary until we know if they'll use JSX and if they'll use
// react refresh
var _new_jsx_runtime_resolve_result: ?_resolver.Result = null;
var fast_refresh_resolve_result: ?_resolver.Result = null;
// Normally, this is automatic
// However, since we only do the parsing pass, it may not get imported automatically.
if (bundler.options.jsx.parse) {
defer this.bundler.resetStore();
if (this.bundler.resolver.resolve(
this.bundler.fs.top_level_dir,
this.bundler.options.jsx.import_source,
.require,
)) |new_jsx_runtime| {
_new_jsx_runtime_resolve_result = new_jsx_runtime;
this.ensurePathIsAllocated(_new_jsx_runtime_resolve_result.?.path()) catch unreachable;
Analytics.Features.jsx = true;
} else |_| {}
}
const include_fast_refresh_in_bundle = Analytics.Features.jsx and
include_refresh_runtime and
!Analytics.Features.fast_refresh and !bundler.options.platform.isServerSide();
var refresh_runtime_module_id: u32 = 0;
if (include_refresh_runtime) {
defer this.bundler.resetStore();
if (this.bundler.resolver.resolve(
this.bundler.fs.top_level_dir,
this.bundler.options.jsx.refresh_runtime,
.require,
)) |refresh_runtime| {
fast_refresh_resolve_result = refresh_runtime;
this.ensurePathIsAllocated(fast_refresh_resolve_result.?.path()) catch unreachable;
Analytics.Features.fast_refresh = true;
if (BundledModuleData.get(this, &refresh_runtime)) |mod| {
refresh_runtime_module_id = mod.module_id;
}
} else |_| {}
}
if (Environment.isDebug) {
switch (bundler.options.platform) {
.node => try generator.appendBytes(runtime.Runtime.sourceContentNode()),
.bun_macro, .bun => try generator.appendBytes(runtime.Runtime.sourceContentBun()),
else => try generator.appendBytes(runtime.Runtime.sourceContent(include_fast_refresh_in_bundle)),
}