forked from oven-sh/bun
-
Notifications
You must be signed in to change notification settings - Fork 0
/
module_loader.zig
2545 lines (2302 loc) · 110 KB
/
module_loader.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 std = @import("std");
const is_bindgen: bool = std.meta.globalOption("bindgen", bool) orelse false;
const StaticExport = @import("./bindings/static_export.zig");
const bun = @import("root").bun;
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 Arena = @import("../mimalloc_arena.zig").Arena;
const C = bun.C;
const NetworkThread = @import("root").bun.HTTP.NetworkThread;
const IO = @import("root").bun.AsyncIO;
const Allocator = std.mem.Allocator;
const IdentityContext = @import("../identity_context.zig").IdentityContext;
const Fs = @import("../fs.zig");
const Resolver = @import("../resolver/resolver.zig");
const ast = @import("../import_record.zig");
const MacroEntryPoint = bun.bundler.MacroEntryPoint;
const ParseResult = bun.bundler.ParseResult;
const logger = @import("root").bun.logger;
const Api = @import("../api/schema.zig").Api;
const options = @import("../options.zig");
const Bundler = bun.Bundler;
const PluginRunner = bun.bundler.PluginRunner;
const ServerEntryPoint = bun.bundler.ServerEntryPoint;
const js_printer = bun.js_printer;
const js_parser = bun.js_parser;
const js_ast = bun.JSAst;
const http = @import("../http.zig");
const NodeFallbackModules = @import("../node_fallbacks.zig");
const ImportKind = ast.ImportKind;
const Analytics = @import("../analytics/analytics_thread.zig");
const ZigString = @import("root").bun.JSC.ZigString;
const Runtime = @import("../runtime.zig");
const Router = @import("./api/filesystem_router.zig");
const ImportRecord = ast.ImportRecord;
const DotEnv = @import("../env_loader.zig");
const PackageJSON = @import("../resolver/package_json.zig").PackageJSON;
const MacroRemap = @import("../resolver/package_json.zig").MacroMap;
const WebCore = @import("root").bun.JSC.WebCore;
const Request = WebCore.Request;
const Response = WebCore.Response;
const Headers = WebCore.Headers;
const Fetch = WebCore.Fetch;
const FetchEvent = WebCore.FetchEvent;
const js = @import("root").bun.JSC.C;
const JSC = @import("root").bun.JSC;
const JSError = @import("./base.zig").JSError;
const d = @import("./base.zig").d;
const MarkedArrayBuffer = @import("./base.zig").MarkedArrayBuffer;
const getAllocator = @import("./base.zig").getAllocator;
const JSValue = @import("root").bun.JSC.JSValue;
const NewClass = @import("./base.zig").NewClass;
const Microtask = @import("root").bun.JSC.Microtask;
const JSGlobalObject = @import("root").bun.JSC.JSGlobalObject;
const ExceptionValueRef = @import("root").bun.JSC.ExceptionValueRef;
const JSPrivateDataPtr = @import("root").bun.JSC.JSPrivateDataPtr;
const ZigConsoleClient = @import("root").bun.JSC.ZigConsoleClient;
const Node = @import("root").bun.JSC.Node;
const ZigException = @import("root").bun.JSC.ZigException;
const ZigStackTrace = @import("root").bun.JSC.ZigStackTrace;
const ErrorableResolvedSource = @import("root").bun.JSC.ErrorableResolvedSource;
const ResolvedSource = @import("root").bun.JSC.ResolvedSource;
const JSPromise = @import("root").bun.JSC.JSPromise;
const JSInternalPromise = @import("root").bun.JSC.JSInternalPromise;
const JSModuleLoader = @import("root").bun.JSC.JSModuleLoader;
const JSPromiseRejectionOperation = @import("root").bun.JSC.JSPromiseRejectionOperation;
const Exception = @import("root").bun.JSC.Exception;
const ErrorableZigString = @import("root").bun.JSC.ErrorableZigString;
const ZigGlobalObject = @import("root").bun.JSC.ZigGlobalObject;
const VM = @import("root").bun.JSC.VM;
const JSFunction = @import("root").bun.JSC.JSFunction;
const Config = @import("./config.zig");
const URL = @import("../url.zig").URL;
const Bun = JSC.API.Bun;
const EventLoop = JSC.EventLoop;
const PendingResolution = @import("../resolver/resolver.zig").PendingResolution;
const ThreadSafeFunction = JSC.napi.ThreadSafeFunction;
const PackageManager = @import("../install/install.zig").PackageManager;
const Install = @import("../install/install.zig");
const VirtualMachine = JSC.VirtualMachine;
const Dependency = @import("../install/dependency.zig");
const String = bun.String;
// Setting BUN_OVERRIDE_MODULE_PATH to the path to the bun repo will make it so modules are loaded
// from there instead of the ones embedded into the binary.
// In debug mode, this is set automatically for you, using the path relative to this file.
fn jsModuleFromFile(from_path: string, comptime input: string) string {
// `modules_dev` is not minified or committed. Later we could also try loading source maps for it too.
const moduleFolder = if (comptime Environment.isDebug) "modules_dev" else "modules";
const Holder = struct {
pub const file = @embedFile("../js/out/" ++ moduleFolder ++ "/" ++ input);
};
if ((comptime !Environment.allow_assert) and from_path.len == 0) {
return Holder.file;
}
var file: std.fs.File = undefined;
if ((comptime Environment.allow_assert) and from_path.len == 0) {
const absolute_path = comptime (Environment.base_path ++ (std.fs.path.dirname(std.fs.path.dirname(@src().file).?).?) ++ "/js/out/" ++ moduleFolder ++ "/" ++ input);
file = std.fs.openFileAbsoluteZ(absolute_path, .{ .mode = .read_only }) catch {
const WarnOnce = struct {
pub var warned = false;
};
if (!WarnOnce.warned) {
WarnOnce.warned = true;
Output.prettyErrorln("Could not find file: " ++ absolute_path ++ " - using embedded version", .{});
}
return Holder.file;
};
} else {
var parts = [_]string{ from_path, "src/js/out/" ++ moduleFolder ++ "/" ++ input };
var buf: [bun.MAX_PATH_BYTES]u8 = undefined;
var absolute_path_to_use = Fs.FileSystem.instance.absBuf(&parts, &buf);
buf[absolute_path_to_use.len] = 0;
file = std.fs.openFileAbsoluteZ(absolute_path_to_use[0..absolute_path_to_use.len :0], .{ .mode = .read_only }) catch {
const WarnOnce = struct {
pub var warned = false;
};
if (!WarnOnce.warned) {
WarnOnce.warned = true;
Output.prettyErrorln("Could not find file: {s}, so using embedded version", .{absolute_path_to_use});
}
return Holder.file;
};
}
var contents = file.readToEndAlloc(bun.default_allocator, std.math.maxInt(usize)) catch @panic("Cannot read file " ++ input);
file.close();
return contents;
}
inline fn jsSyntheticModule(comptime name: ResolvedSource.Tag, specifier: String) ResolvedSource {
return ResolvedSource{
.allocator = null,
.source_code = bun.String.empty,
.specifier = specifier,
.source_url = ZigString.init(@tagName(name)),
.hash = 0,
.tag = name,
};
}
const BunDebugHolder = struct {
pub var dir: ?std.fs.IterableDir = null;
pub var lock: bun.Lock = undefined;
};
fn dumpSource(specifier: string, printer: anytype) !void {
if (BunDebugHolder.dir == null) {
BunDebugHolder.dir = try std.fs.cwd().makeOpenPathIterable("/tmp/bun-debug-src/", .{});
BunDebugHolder.lock = bun.Lock.init();
}
BunDebugHolder.lock.lock();
defer BunDebugHolder.lock.unlock();
if (std.fs.path.dirname(specifier)) |dir_path| {
var parent = try BunDebugHolder.dir.?.dir.makeOpenPathIterable(dir_path[1..], .{});
defer parent.close();
try parent.dir.writeFile(std.fs.path.basename(specifier), printer.ctx.getWritten());
} else {
try BunDebugHolder.dir.?.dir.writeFile(std.fs.path.basename(specifier), printer.ctx.getWritten());
}
}
pub const RuntimeTranspilerStore = struct {
const debug = Output.scoped(.compile, false);
generation_number: std.atomic.Atomic(u32) = std.atomic.Atomic(u32).init(0),
store: TranspilerJob.Store,
enabled: bool = true,
pub fn init(allocator: std.mem.Allocator) RuntimeTranspilerStore {
return RuntimeTranspilerStore{
.store = TranspilerJob.Store.init(allocator),
};
}
pub fn transpile(
this: *RuntimeTranspilerStore,
vm: *JSC.VirtualMachine,
globalObject: *JSC.JSGlobalObject,
path: Fs.Path,
referrer: []const u8,
) *anyopaque {
debug("transpile({s})", .{path.text});
var job: *TranspilerJob = this.store.get();
var owned_path = Fs.Path.init(bun.default_allocator.dupe(u8, path.text) catch unreachable);
var promise = JSC.JSInternalPromise.create(globalObject);
job.* = TranspilerJob{
.path = owned_path,
.globalThis = globalObject,
.referrer = bun.default_allocator.dupe(u8, referrer) catch unreachable,
.vm = vm,
.log = logger.Log.init(bun.default_allocator),
.loader = vm.bundler.options.loader(owned_path.name.ext),
.promise = JSC.Strong.create(JSC.JSValue.fromCell(promise), globalObject),
.poll_ref = .{},
.fetcher = TranspilerJob.Fetcher{
.file = {},
},
};
job.schedule();
return promise;
}
pub const TranspilerJob = struct {
path: Fs.Path,
referrer: []const u8,
loader: options.Loader,
promise: JSC.Strong = .{},
vm: *JSC.VirtualMachine,
globalThis: *JSC.JSGlobalObject,
fetcher: Fetcher,
poll_ref: JSC.PollRef = .{},
generation_number: u32 = 0,
log: logger.Log,
parse_error: ?anyerror = null,
resolved_source: ResolvedSource = ResolvedSource{},
work_task: JSC.WorkPoolTask = .{ .callback = runFromWorkerThread },
pub const Store = bun.HiveArray(TranspilerJob, 64).Fallback;
pub const Fetcher = union(enum) {
virtual_module: bun.String,
file: void,
pub fn deinit(this: *@This()) void {
if (this.* == .virtual_module) {
this.virtual_module.deref();
}
}
};
pub fn deinit(this: *TranspilerJob) void {
bun.default_allocator.free(this.path.text);
bun.default_allocator.free(this.referrer);
this.poll_ref.disable();
this.fetcher.deinit();
this.loader = options.Loader.file;
this.path = Fs.Path.empty;
this.log.deinit();
this.promise.deinit();
this.globalThis = undefined;
}
threadlocal var ast_memory_store: ?*js_ast.ASTMemoryAllocator = null;
threadlocal var source_code_printer: ?*js_printer.BufferPrinter = null;
pub fn dispatchToMainThread(this: *TranspilerJob) void {
this.vm.eventLoop().enqueueTaskConcurrent(
JSC.ConcurrentTask.fromCallback(this, runFromJSThread),
);
}
pub fn runFromJSThread(this: *TranspilerJob) void {
var vm = this.vm;
var promise = this.promise.swap();
var globalThis = this.globalThis;
this.poll_ref.unref(vm);
var specifier = if (this.parse_error == null) this.resolved_source.specifier else bun.String.create(this.path.text);
var referrer = bun.String.create(this.referrer);
var log = this.log;
this.log = logger.Log.init(bun.default_allocator);
var resolved_source = this.resolved_source;
resolved_source.source_url = specifier.toZigString();
resolved_source.tag = brk: {
if (resolved_source.commonjs_exports_len > 0) {
var actual_package_json: *PackageJSON = brk2: {
// this should already be cached virtually always so it's fine to do this
var dir_info = (vm.bundler.resolver.readDirInfo(this.path.name.dir) catch null) orelse
break :brk .javascript;
break :brk2 dir_info.package_json orelse dir_info.enclosing_package_json;
} orelse break :brk .javascript;
if (actual_package_json.module_type == .esm) {
break :brk ResolvedSource.Tag.package_json_type_module;
}
}
break :brk ResolvedSource.Tag.javascript;
};
const parse_error = this.parse_error;
if (!vm.transpiler_store.store.hive.in(this)) {
this.promise.deinit();
}
this.deinit();
_ = vm.transpiler_store.store.hive.put(this);
ModuleLoader.AsyncModule.fulfill(globalThis, promise, resolved_source, parse_error, specifier, referrer, &log);
}
pub fn schedule(this: *TranspilerJob) void {
this.poll_ref.ref(this.vm);
JSC.WorkPool.schedule(&this.work_task);
}
pub fn runFromWorkerThread(work_task: *JSC.WorkPoolTask) void {
@fieldParentPtr(TranspilerJob, "work_task", work_task).run();
}
pub fn run(this: *TranspilerJob) void {
var arena = bun.ArenaAllocator.init(bun.default_allocator);
defer arena.deinit();
defer this.dispatchToMainThread();
if (this.generation_number != this.vm.transpiler_store.generation_number.load(.Monotonic)) {
this.parse_error = error.TranspilerJobGenerationMismatch;
return;
}
if (ast_memory_store == null) {
ast_memory_store = bun.default_allocator.create(js_ast.ASTMemoryAllocator) catch @panic("out of memory!");
ast_memory_store.?.* = js_ast.ASTMemoryAllocator{
.allocator = arena.allocator(),
.previous = null,
};
}
ast_memory_store.?.reset();
ast_memory_store.?.allocator = arena.allocator();
ast_memory_store.?.push();
const path = this.path;
const specifier = this.path.text;
const loader = this.loader;
this.log = logger.Log.init(bun.default_allocator);
var vm = this.vm;
var bundler: bun.Bundler = undefined;
bundler = vm.bundler;
var allocator = arena.allocator();
bundler.setAllocator(allocator);
bundler.setLog(&this.log);
bundler.resolver.opts = bundler.options;
bundler.macro_context = null;
bundler.linker.resolver = &bundler.resolver;
var fd: ?StoredFileDescriptorType = null;
var package_json: ?*PackageJSON = null;
const hash = JSC.Watcher.getHash(path.text);
if (vm.bun_dev_watcher) |watcher| {
if (watcher.indexOf(hash)) |index| {
const _fd = watcher.watchlist.items(.fd)[index];
fd = if (_fd > 0) _fd else null;
package_json = watcher.watchlist.items(.package_json)[index];
}
} else if (vm.bun_watcher) |watcher| {
if (watcher.indexOf(hash)) |index| {
const _fd = watcher.watchlist.items(.fd)[index];
fd = if (_fd > 0) _fd else null;
package_json = watcher.watchlist.items(.package_json)[index];
}
}
// this should be a cheap lookup because 24 bytes == 8 * 3 so it's read 3 machine words
const is_node_override = strings.hasPrefixComptime(specifier, "/bun-vfs/node_modules/");
const macro_remappings = if (vm.macro_mode or !vm.has_any_macro_remappings or is_node_override)
MacroRemap{}
else
bundler.options.macro_remap;
var fallback_source: logger.Source = undefined;
// Usually, we want to close the input file automatically.
//
// If we're re-using the file descriptor from the fs watcher
// Do not close it because that will break the kqueue-based watcher
//
var should_close_input_file_fd = fd == null;
var input_file_fd: StoredFileDescriptorType = 0;
var parse_options = Bundler.ParseOptions{
.allocator = allocator,
.path = path,
.loader = loader,
.dirname_fd = 0,
.file_descriptor = fd,
.file_fd_ptr = &input_file_fd,
.file_hash = hash,
.macro_remappings = macro_remappings,
.jsx = bundler.options.jsx,
.virtual_source = null,
.dont_bundle_twice = true,
.allow_commonjs = true,
.inject_jest_globals = bundler.options.rewrite_jest_for_tests and
vm.main.len == path.text.len and
vm.main_hash == hash and
strings.eqlLong(vm.main, path.text, false),
.set_breakpoint_on_first_line = vm.debugger != null and vm.debugger.?.set_breakpoint_on_first_line and strings.eqlLong(vm.main, path.text, true),
};
defer {
if (should_close_input_file_fd and input_file_fd != 0) {
_ = bun.JSC.Node.Syscall.close(input_file_fd);
input_file_fd = 0;
}
}
if (is_node_override) {
if (NodeFallbackModules.contentsFromPath(specifier)) |code| {
const fallback_path = Fs.Path.initWithNamespace(specifier, "node");
fallback_source = logger.Source{ .path = fallback_path, .contents = code, .key_path = fallback_path };
parse_options.virtual_source = &fallback_source;
}
}
var parse_result: bun.bundler.ParseResult = bundler.parseMaybeReturnFileOnlyAllowSharedBuffer(
parse_options,
null,
false,
false,
) orelse {
if (vm.isWatcherEnabled()) {
if (input_file_fd != 0) {
if (vm.bun_watcher != null and !is_node_override and std.fs.path.isAbsolute(path.text) and !strings.contains(path.text, "node_modules")) {
should_close_input_file_fd = false;
vm.bun_watcher.?.addFile(
input_file_fd,
path.text,
hash,
loader,
0,
package_json,
true,
) catch {};
}
}
}
this.parse_error = error.ParseError;
return;
};
if (vm.isWatcherEnabled()) {
if (input_file_fd != 0) {
if (vm.bun_watcher != null and !is_node_override and
std.fs.path.isAbsolute(path.text) and !strings.contains(path.text, "node_modules"))
{
should_close_input_file_fd = false;
vm.bun_watcher.?.addFile(
input_file_fd,
path.text,
hash,
loader,
0,
package_json,
true,
) catch {};
}
}
}
if (parse_result.already_bundled) {
this.resolved_source = ResolvedSource{
.allocator = null,
.source_code = bun.String.createLatin1(parse_result.source.contents),
.specifier = String.create(specifier),
.source_url = ZigString.init(path.text),
// // TODO: change hash to a bitfield
// .hash = 1,
// having JSC own the memory causes crashes
.hash = 0,
};
return;
}
for (parse_result.ast.import_records.slice()) |*import_record_| {
var import_record: *bun.ImportRecord = import_record_;
if (JSC.HardcodedModule.Aliases.get(import_record.path.text, bundler.options.target)) |replacement| {
import_record.path.text = replacement.path;
import_record.tag = replacement.tag;
continue;
}
if (bundler.options.rewrite_jest_for_tests) {
if (strings.eqlComptime(
import_record.path.text,
"@jest/globals",
) or strings.eqlComptime(
import_record.path.text,
"vitest",
)) {
import_record.path.namespace = "bun";
import_record.tag = .bun_test;
import_record.path.text = "test";
continue;
}
}
if (strings.hasPrefixComptime(import_record.path.text, "bun:")) {
import_record.path = Fs.Path.init(import_record.path.text["bun:".len..]);
import_record.path.namespace = "bun";
if (strings.eqlComptime(import_record.path.text, "test")) {
import_record.tag = .bun_test;
}
}
}
if (source_code_printer == null) {
var writer = try js_printer.BufferWriter.init(bun.default_allocator);
source_code_printer = bun.default_allocator.create(js_printer.BufferPrinter) catch unreachable;
source_code_printer.?.* = js_printer.BufferPrinter.init(writer);
source_code_printer.?.ctx.append_null_byte = false;
}
var printer = source_code_printer.?.*;
printer.ctx.reset();
{
var mapper = vm.sourceMapHandler(&printer);
defer source_code_printer.?.* = printer;
_ = bundler.printWithSourceMap(
parse_result,
@TypeOf(&printer),
&printer,
.esm_ascii,
mapper.get(),
) catch |err| {
this.parse_error = err;
return;
};
}
if (comptime Environment.dump_source) {
dumpSource(specifier, &printer) catch {};
}
this.resolved_source = ResolvedSource{
.allocator = null,
.source_code = bun.String.createLatin1(printer.ctx.getWritten()),
.specifier = String.create(specifier),
.source_url = ZigString.init(path.text),
.commonjs_exports = null,
.commonjs_exports_len = if (parse_result.ast.exports_kind == .cjs)
std.math.maxInt(u32)
else
0,
.hash = 0,
};
}
};
};
pub const ModuleLoader = struct {
const debug = Output.scoped(.ModuleLoader, true);
pub const AsyncModule = struct {
// This is all the state used by the printer to print the module
parse_result: ParseResult,
// stmt_blocks: []*js_ast.Stmt.Data.Store.All.Block = &[_]*js_ast.Stmt.Data.Store.All.Block{},
// expr_blocks: []*js_ast.Expr.Data.Store.All.Block = &[_]*js_ast.Expr.Data.Store.All.Block{},
promise: JSC.Strong = .{},
path: Fs.Path,
specifier: string = "",
referrer: string = "",
string_buf: []u8 = &[_]u8{},
fd: ?StoredFileDescriptorType = null,
package_json: ?*PackageJSON = null,
loader: Api.Loader,
hash: u32 = std.math.maxInt(u32),
globalThis: *JSC.JSGlobalObject = undefined,
arena: bun.ArenaAllocator,
// This is the specific state for making it async
poll_ref: JSC.PollRef = .{},
any_task: JSC.AnyTask = undefined,
pub const Id = u32;
const PackageDownloadError = struct {
name: []const u8,
resolution: Install.Resolution,
err: anyerror,
url: []const u8,
};
const PackageResolveError = struct {
name: []const u8,
err: anyerror,
url: []const u8,
version: Dependency.Version,
};
pub const Queue = struct {
map: Map = .{},
scheduled: u32 = 0,
concurrent_task_count: std.atomic.Atomic(u32) = std.atomic.Atomic(u32).init(0),
const DeferredDependencyError = struct {
dependency: Dependency,
root_dependency_id: Install.DependencyID,
err: anyerror,
};
pub const Map = std.ArrayListUnmanaged(AsyncModule);
pub fn enqueue(this: *Queue, globalObject: *JSC.JSGlobalObject, opts: anytype) void {
debug("enqueue: {s}", .{opts.specifier});
var module = AsyncModule.init(opts, globalObject) catch unreachable;
module.poll_ref.ref(this.vm());
this.map.append(this.vm().allocator, module) catch unreachable;
this.vm().packageManager().drainDependencyList();
}
pub fn onDependencyError(ctx: *anyopaque, dependency: Dependency, root_dependency_id: Install.DependencyID, err: anyerror) void {
var this = bun.cast(*Queue, ctx);
debug("onDependencyError: {s}", .{this.vm().packageManager().lockfile.str(&dependency.name)});
var modules: []AsyncModule = this.map.items;
var i: usize = 0;
outer: for (modules) |module_| {
var module = module_;
const root_dependency_ids = module.parse_result.pending_imports.items(.root_dependency_id);
for (root_dependency_ids, 0..) |dep, dep_i| {
if (dep != root_dependency_id) continue;
module.resolveError(
this.vm(),
module.parse_result.pending_imports.items(.import_record_id)[dep_i],
.{
.name = this.vm().packageManager().lockfile.str(&dependency.name),
.err = err,
.url = "",
.version = dependency.version,
},
) catch unreachable;
continue :outer;
}
modules[i] = module;
i += 1;
}
this.map.items.len = i;
}
pub fn onWakeHandler(ctx: *anyopaque, _: *PackageManager) void {
debug("onWake", .{});
var this = bun.cast(*Queue, ctx);
var concurrent_task = bun.default_allocator.create(JSC.ConcurrentTask) catch @panic("OOM");
concurrent_task.* = .{
.task = JSC.Task.init(this),
.auto_delete = true,
};
this.vm().enqueueTaskConcurrent(concurrent_task);
}
pub fn onPoll(this: *Queue) void {
debug("onPoll", .{});
this.runTasks();
this.pollModules();
}
pub fn runTasks(this: *Queue) void {
var pm = this.vm().packageManager();
if (Output.enable_ansi_colors_stderr) {
pm.startProgressBarIfNone();
pm.runTasks(
*Queue,
this,
.{
.onExtract = {},
.onResolve = onResolve,
.onPackageManifestError = onPackageManifestError,
.onPackageDownloadError = onPackageDownloadError,
.progress_bar = true,
},
PackageManager.Options.LogLevel.default,
) catch unreachable;
} else {
pm.runTasks(
*Queue,
this,
.{
.onExtract = {},
.onResolve = onResolve,
.onPackageManifestError = onPackageManifestError,
.onPackageDownloadError = onPackageDownloadError,
},
PackageManager.Options.LogLevel.default_no_progress,
) catch unreachable;
}
}
pub fn onResolve(_: *Queue) void {
debug("onResolve", .{});
}
pub fn onPackageManifestError(
this: *Queue,
name: []const u8,
err: anyerror,
url: []const u8,
) void {
debug("onPackageManifestError: {s}", .{name});
var modules: []AsyncModule = this.map.items;
var i: usize = 0;
outer: for (modules) |module_| {
var module = module_;
var tags = module.parse_result.pending_imports.items(.tag);
for (tags, 0..) |tag, tag_i| {
if (tag == .resolve) {
var esms = module.parse_result.pending_imports.items(.esm);
const esm = esms[tag_i];
var string_bufs = module.parse_result.pending_imports.items(.string_buf);
if (!strings.eql(esm.name.slice(string_bufs[tag_i]), name)) continue;
var versions = module.parse_result.pending_imports.items(.dependency);
module.resolveError(
this.vm(),
module.parse_result.pending_imports.items(.import_record_id)[tag_i],
.{
.name = name,
.err = err,
.url = url,
.version = versions[tag_i],
},
) catch unreachable;
continue :outer;
}
}
modules[i] = module;
i += 1;
}
this.map.items.len = i;
}
pub fn onPackageDownloadError(
this: *Queue,
package_id: Install.PackageID,
name: []const u8,
resolution: Install.Resolution,
err: anyerror,
url: []const u8,
) void {
debug("onPackageDownloadError: {s}", .{name});
const resolution_ids = this.vm().packageManager().lockfile.buffers.resolutions.items;
var modules: []AsyncModule = this.map.items;
var i: usize = 0;
outer: for (modules) |module_| {
var module = module_;
const record_ids = module.parse_result.pending_imports.items(.import_record_id);
const root_dependency_ids = module.parse_result.pending_imports.items(.root_dependency_id);
for (root_dependency_ids, 0..) |dependency_id, import_id| {
if (resolution_ids[dependency_id] != package_id) continue;
module.downloadError(
this.vm(),
record_ids[import_id],
.{
.name = name,
.resolution = resolution,
.err = err,
.url = url,
},
) catch unreachable;
continue :outer;
}
modules[i] = module;
i += 1;
}
this.map.items.len = i;
}
pub fn pollModules(this: *Queue) void {
var pm = this.vm().packageManager();
if (pm.pending_tasks > 0) return;
var modules: []AsyncModule = this.map.items;
var i: usize = 0;
for (modules) |mod| {
var module = mod;
var tags = module.parse_result.pending_imports.items(.tag);
const root_dependency_ids = module.parse_result.pending_imports.items(.root_dependency_id);
// var esms = module.parse_result.pending_imports.items(.esm);
// var versions = module.parse_result.pending_imports.items(.dependency);
var done_count: usize = 0;
for (tags, 0..) |tag, tag_i| {
const root_id = root_dependency_ids[tag_i];
const resolution_ids = pm.lockfile.buffers.resolutions.items;
if (root_id >= resolution_ids.len) continue;
const package_id = resolution_ids[root_id];
switch (tag) {
.resolve => {
if (package_id == Install.invalid_package_id) {
continue;
}
// if we get here, the package has already been resolved.
tags[tag_i] = .download;
},
.download => {
if (package_id == Install.invalid_package_id) {
unreachable;
}
},
.done => {
done_count += 1;
continue;
},
}
if (package_id == Install.invalid_package_id) {
continue;
}
const package = pm.lockfile.packages.get(package_id);
std.debug.assert(package.resolution.tag != .root);
switch (pm.determinePreinstallState(package, pm.lockfile)) {
.done => {
// we are only truly done if all the dependencies are done.
const current_tasks = pm.total_tasks;
// so if enqueuing all the dependencies produces no new tasks, we are done.
pm.enqueueDependencyList(package.dependencies);
if (current_tasks == pm.total_tasks) {
tags[tag_i] = .done;
done_count += 1;
}
},
.extracting => {
// we are extracting the package
// we need to wait for the next poll
continue;
},
.extract => {},
else => {},
}
}
if (done_count == tags.len) {
module.done(this.vm());
} else {
modules[i] = module;
i += 1;
}
}
this.map.items.len = i;
if (i == 0) {
// ensure we always end the progress bar
this.vm().packageManager().endProgressBar();
}
}
pub fn vm(this: *Queue) *VirtualMachine {
return @fieldParentPtr(VirtualMachine, "modules", this);
}
};
pub fn init(opts: anytype, globalObject: *JSC.JSGlobalObject) !AsyncModule {
var promise = JSC.Strong{};
// var stmt_blocks = js_ast.Stmt.Data.toOwnedSlice();
// var expr_blocks = js_ast.Expr.Data.toOwnedSlice();
const this_promise = JSValue.createInternalPromise(globalObject);
promise.set(globalObject, this_promise);
var buf = bun.StringBuilder{};
buf.count(opts.referrer);
buf.count(opts.specifier);
buf.count(opts.path.text);
try buf.allocate(bun.default_allocator);
opts.promise_ptr.?.* = this_promise.asInternalPromise().?;
const referrer = buf.append(opts.referrer);
const specifier = buf.append(opts.specifier);
const path = Fs.Path.init(buf.append(opts.path.text));
return AsyncModule{
.parse_result = opts.parse_result,
.promise = promise,
.path = path,
.specifier = specifier,
.referrer = referrer,
.fd = opts.fd,
.package_json = opts.package_json,
.loader = opts.loader.toAPI(),
.string_buf = buf.allocatedSlice(),
// .stmt_blocks = stmt_blocks,
// .expr_blocks = expr_blocks,
.globalThis = globalObject,
.arena = opts.arena,
};
}
pub fn done(this: *AsyncModule, jsc_vm: *JSC.VirtualMachine) void {
var clone = jsc_vm.allocator.create(AsyncModule) catch unreachable;
clone.* = this.*;
jsc_vm.modules.scheduled += 1;
clone.any_task = JSC.AnyTask.New(AsyncModule, onDone).init(clone);
jsc_vm.enqueueTask(JSC.Task.init(&clone.any_task));
}
pub fn onDone(this: *AsyncModule) void {
JSC.markBinding(@src());
var jsc_vm = this.globalThis.bunVM();
jsc_vm.modules.scheduled -= 1;
if (jsc_vm.modules.scheduled == 0) {
jsc_vm.packageManager().endProgressBar();
}
var log = logger.Log.init(jsc_vm.allocator);
defer log.deinit();
var errorable: ErrorableResolvedSource = undefined;
this.poll_ref.unref(jsc_vm);
outer: {
errorable = ErrorableResolvedSource.ok(this.resumeLoadingModule(&log) catch |err| {
JSC.VirtualMachine.processFetchLog(
this.globalThis,
bun.String.init(this.specifier),
bun.String.init(this.referrer),
&log,
&errorable,
err,
);
break :outer;
});
}
var spec = bun.String.init(ZigString.init(this.specifier).withEncoding());
var ref = bun.String.init(ZigString.init(this.referrer).withEncoding());
Bun__onFulfillAsyncModule(
this.promise.get().?,
&errorable,
&spec,
&ref,
);
this.deinit();
jsc_vm.allocator.destroy(this);
}
pub fn fulfill(
globalThis: *JSC.JSGlobalObject,
promise: JSC.JSValue,
resolved_source: ResolvedSource,
err: ?anyerror,
specifier_: bun.String,
referrer_: bun.String,
log: *logger.Log,
) void {
JSC.markBinding(@src());
var specifier = specifier_;
var referrer = referrer_;
defer {
specifier.deref();
referrer.deref();
}
var errorable: ErrorableResolvedSource = undefined;
if (err) |e| {
JSC.VirtualMachine.processFetchLog(
globalThis,
specifier,
referrer,
log,
&errorable,
e,
);
} else {
errorable = ErrorableResolvedSource.ok(resolved_source);
}
log.deinit();
Bun__onFulfillAsyncModule(
promise,
&errorable,
&specifier,
&referrer,
);
}
pub fn resolveError(this: *AsyncModule, vm: *JSC.VirtualMachine, import_record_id: u32, result: PackageResolveError) !void {
var globalThis = this.globalThis;
var msg: []u8 = try switch (result.err) {
error.PackageManifestHTTP400 => std.fmt.allocPrint(