-
Notifications
You must be signed in to change notification settings - Fork 2.8k
/
javascript.zig
3131 lines (2699 loc) · 123 KB
/
javascript.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 ErrorableString = bun.JSC.ErrorableString;
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("../bun_dev_http_server.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 String = bun.String;
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 IPC = @import("ipc.zig");
const ModuleLoader = JSC.ModuleLoader;
const FetchFlags = JSC.FetchFlags;
const TaggedPointerUnion = @import("../tagged_pointer.zig").TaggedPointerUnion;
const Task = JSC.Task;
const Blob = @import("../blob.zig");
pub const Buffer = MarkedArrayBuffer;
const Lock = @import("../lock.zig").Lock;
const BuildMessage = JSC.BuildMessage;
const ResolveMessage = JSC.ResolveMessage;
pub const OpaqueCallback = *const fn (current: ?*anyopaque) callconv(.C) void;
pub fn OpaqueWrap(comptime Context: type, comptime Function: fn (this: *Context) void) OpaqueCallback {
return struct {
pub fn callback(ctx: ?*anyopaque) callconv(.C) void {
var context: *Context = @as(*Context, @ptrCast(@alignCast(ctx.?)));
@call(.auto, Function, .{context});
}
}.callback;
}
pub const bun_file_import_path = "/node_modules.server.bun";
const SourceMap = @import("../sourcemap/sourcemap.zig");
const ParsedSourceMap = SourceMap.Mapping.ParsedSourceMap;
const MappingList = SourceMap.Mapping.List;
pub const SavedSourceMap = struct {
pub const vlq_offset = 24;
// For bun.js, we store the number of mappings and how many bytes the final list is at the beginning of the array
// The first 8 bytes are the length of the array
// The second 8 bytes are the number of mappings
pub const SavedMappings = struct {
data: [*]u8,
pub fn vlq(this: SavedMappings) []u8 {
return this.data[vlq_offset..this.len()];
}
pub inline fn len(this: SavedMappings) usize {
return @as(u64, @bitCast(this.data[0..8].*));
}
pub fn deinit(this: SavedMappings) void {
default_allocator.free(this.data[0..this.len()]);
}
pub fn toMapping(this: SavedMappings, allocator: Allocator, path: string) anyerror!ParsedSourceMap {
const result = SourceMap.Mapping.parse(
allocator,
this.data[vlq_offset..this.len()],
@as(usize, @bitCast(this.data[8..16].*)),
1,
@as(usize, @bitCast(this.data[16..24].*)),
);
switch (result) {
.fail => |fail| {
if (Output.enable_ansi_colors_stderr) {
try fail.toData(path).writeFormat(
Output.errorWriter(),
logger.Kind.warn,
true,
false,
);
} else {
try fail.toData(path).writeFormat(
Output.errorWriter(),
logger.Kind.warn,
false,
false,
);
}
return fail.err;
},
.success => |success| {
return success;
},
}
}
};
pub const Value = TaggedPointerUnion(.{ ParsedSourceMap, SavedMappings });
pub const HashTable = std.HashMap(u64, *anyopaque, IdentityContext(u64), 80);
/// This is a pointer to the map located on the VirtualMachine struct
map: *HashTable,
mutex: bun.Lock = bun.Lock.init(),
pub fn onSourceMapChunk(this: *SavedSourceMap, chunk: SourceMap.Chunk, source: logger.Source) anyerror!void {
try this.putMappings(source, chunk.buffer);
}
pub const SourceMapHandler = js_printer.SourceMapHandler.For(SavedSourceMap, onSourceMapChunk);
pub fn deinit(this: *SavedSourceMap) void {
{
this.mutex.lock();
var iter = this.map.valueIterator();
while (iter.next()) |val| {
var value = Value.from(val.*);
if (value.get(ParsedSourceMap)) |source_map_| {
var source_map: *ParsedSourceMap = source_map_;
source_map.deinit(default_allocator);
} else if (value.get(SavedMappings)) |saved_mappings| {
var saved = SavedMappings{ .data = @as([*]u8, @ptrCast(saved_mappings)) };
saved.deinit();
}
}
this.mutex.unlock();
}
this.map.deinit();
}
pub fn putMappings(this: *SavedSourceMap, source: logger.Source, mappings: MutableString) !void {
this.mutex.lock();
defer this.mutex.unlock();
var entry = try this.map.getOrPut(bun.hash(source.path.text));
if (entry.found_existing) {
var value = Value.from(entry.value_ptr.*);
if (value.get(ParsedSourceMap)) |source_map_| {
var source_map: *ParsedSourceMap = source_map_;
source_map.deinit(default_allocator);
} else if (value.get(SavedMappings)) |saved_mappings| {
var saved = SavedMappings{ .data = @as([*]u8, @ptrCast(saved_mappings)) };
saved.deinit();
}
}
entry.value_ptr.* = Value.init(bun.cast(*SavedMappings, mappings.list.items.ptr)).ptr();
}
pub fn get(this: *SavedSourceMap, path: string) ?ParsedSourceMap {
var mapping = this.map.getEntry(bun.hash(path)) orelse return null;
switch (Value.from(mapping.value_ptr.*).tag()) {
Value.Tag.ParsedSourceMap => {
return Value.from(mapping.value_ptr.*).as(ParsedSourceMap).*;
},
Value.Tag.SavedMappings => {
var saved = SavedMappings{ .data = @as([*]u8, @ptrCast(Value.from(mapping.value_ptr.*).as(ParsedSourceMap))) };
defer saved.deinit();
var result = default_allocator.create(ParsedSourceMap) catch unreachable;
result.* = saved.toMapping(default_allocator, path) catch {
_ = this.map.remove(mapping.key_ptr.*);
return null;
};
mapping.value_ptr.* = Value.init(result).ptr();
return result.*;
},
else => return null,
}
}
pub fn resolveMapping(
this: *SavedSourceMap,
path: []const u8,
line: i32,
column: i32,
) ?SourceMap.Mapping {
this.mutex.lock();
defer this.mutex.unlock();
const parsed_mappings = this.get(path) orelse return null;
return SourceMap.Mapping.find(parsed_mappings.mappings, line, column);
}
};
const uws = @import("root").bun.uws;
pub export fn Bun__getDefaultGlobal() *JSGlobalObject {
return JSC.VirtualMachine.get().global;
}
pub export fn Bun__getVM() *JSC.VirtualMachine {
return JSC.VirtualMachine.get();
}
pub export fn Bun__drainMicrotasks() void {
JSC.VirtualMachine.get().eventLoop().tick();
}
export fn Bun__readOriginTimer(vm: *JSC.VirtualMachine) u64 {
return vm.origin_timer.read();
}
export fn Bun__readOriginTimerStart(vm: *JSC.VirtualMachine) f64 {
// timespce to milliseconds
return @as(f64, @floatCast((@as(f64, @floatFromInt(vm.origin_timestamp)) + JSC.VirtualMachine.origin_relative_epoch) / 1_000_000.0));
}
pub export fn Bun__GlobalObject__hasIPC(global: *JSC.JSGlobalObject) bool {
return global.bunVM().ipc != null;
}
pub export fn Bun__Process__send(
globalObject: *JSGlobalObject,
callFrame: *JSC.CallFrame,
) JSValue {
JSC.markBinding(@src());
if (callFrame.argumentsCount() < 1) {
globalObject.throwInvalidArguments("process.send requires at least one argument", .{});
return .zero;
}
var vm = globalObject.bunVM();
if (vm.ipc) |ipc| {
const fd = ipc.socket.fd();
const success = IPC.serializeJSValueForSubprocess(
globalObject,
callFrame.argument(0),
fd,
);
return if (success) .undefined else .zero;
} else {
globalObject.throw("IPC Socket is no longer open.", .{});
return .zero;
}
}
pub export fn Bun__Process__disconnect(
globalObject: *JSGlobalObject,
callFrame: *JSC.CallFrame,
) JSValue {
_ = callFrame;
_ = globalObject;
return .undefined;
}
/// This function is called on the main thread
/// The bunVM() call will assert this
pub export fn Bun__queueTask(global: *JSGlobalObject, task: *JSC.CppTask) void {
global.bunVM().eventLoop().enqueueTask(Task.init(task));
}
pub export fn Bun__queueTaskWithTimeout(global: *JSGlobalObject, task: *JSC.CppTask, milliseconds: i32) void {
global.bunVM().eventLoop().enqueueTaskWithTimeout(Task.init(task), milliseconds);
}
pub export fn Bun__reportUnhandledError(globalObject: *JSGlobalObject, value: JSValue) callconv(.C) JSValue {
var jsc_vm = globalObject.bunVM();
jsc_vm.onUnhandledError(globalObject, value);
return JSC.JSValue.jsUndefined();
}
/// This function is called on another thread
/// The main difference: we need to allocate the task & wakeup the thread
/// We can avoid that if we run it from the main thread.
pub export fn Bun__queueTaskConcurrently(global: *JSGlobalObject, task: *JSC.CppTask) void {
var concurrent = bun.default_allocator.create(JSC.ConcurrentTask) catch unreachable;
concurrent.* = JSC.ConcurrentTask{
.task = Task.init(task),
.auto_delete = true,
};
global.bunVMConcurrently().eventLoop().enqueueTaskConcurrent(concurrent);
}
pub export fn Bun__handleRejectedPromise(global: *JSGlobalObject, promise: *JSC.JSPromise) void {
const result = promise.result(global.vm());
var jsc_vm = global.bunVM();
// this seems to happen in some cases when GC is running
if (result == .zero)
return;
jsc_vm.onUnhandledError(global, result);
jsc_vm.autoGarbageCollect();
}
pub export fn Bun__onDidAppendPlugin(jsc_vm: *VirtualMachine, globalObject: *JSGlobalObject) void {
if (jsc_vm.plugin_runner != null) {
return;
}
jsc_vm.plugin_runner = PluginRunner{
.global_object = globalObject,
.allocator = jsc_vm.allocator,
};
jsc_vm.bundler.linker.plugin_runner = &jsc_vm.plugin_runner.?;
}
pub const ExitHandler = struct {
exit_code: u8 = 0,
pub export fn Bun__getExitCode(vm: *VirtualMachine) u8 {
return vm.exit_handler.exit_code;
}
pub export fn Bun__setExitCode(vm: *VirtualMachine, code: u8) void {
vm.exit_handler.exit_code = code;
}
extern fn Process__dispatchOnBeforeExit(*JSC.JSGlobalObject, code: u8) void;
extern fn Process__dispatchOnExit(*JSC.JSGlobalObject, code: u8) void;
extern fn Bun__closeAllSQLiteDatabasesForTermination() void;
pub fn dispatchOnExit(this: *ExitHandler) void {
JSC.markBinding(@src());
var vm = @fieldParentPtr(VirtualMachine, "exit_handler", this);
Process__dispatchOnExit(vm.global, this.exit_code);
if (vm.isMainThread())
Bun__closeAllSQLiteDatabasesForTermination();
}
pub fn dispatchOnBeforeExit(this: *ExitHandler) void {
JSC.markBinding(@src());
var vm = @fieldParentPtr(VirtualMachine, "exit_handler", this);
Process__dispatchOnBeforeExit(vm.global, this.exit_code);
}
};
pub const WebWorker = @import("./web_worker.zig").WebWorker;
/// TODO: rename this to ScriptExecutionContext
/// This is the shared global state for a single JS instance execution
/// Today, Bun is one VM per thread, so the name "VirtualMachine" sort of makes sense
/// However, that may change in the future
pub const VirtualMachine = struct {
global: *JSGlobalObject,
allocator: std.mem.Allocator,
has_loaded_constructors: bool = false,
bundler: Bundler,
bun_dev_watcher: ?*http.Watcher = null,
bun_watcher: ?*JSC.Watcher = null,
console: *ZigConsoleClient,
log: *logger.Log,
main: string = "",
main_hash: u32 = 0,
process: js.JSObjectRef = null,
blobs: ?*Blob.Group = null,
flush_list: std.ArrayList(string),
entry_point: ServerEntryPoint = undefined,
origin: URL = URL{},
node_fs: ?*Node.NodeFS = null,
timer: Bun.Timer = Bun.Timer{},
event_loop_handle: ?*uws.Loop = null,
pending_unref_counter: i32 = 0,
preload: []const string = &[_][]const u8{},
unhandled_pending_rejection_to_capture: ?*JSC.JSValue = null,
standalone_module_graph: ?*bun.StandaloneModuleGraph = null,
hot_reload: bun.CLI.Command.HotReload = .none,
jsc: *JSC.VM = undefined,
/// hide bun:wrap from stack traces
/// bun:wrap is very noisy
hide_bun_stackframes: bool = true,
is_printing_plugin: bool = false,
plugin_runner: ?PluginRunner = null,
is_main_thread: bool = false,
last_reported_error_for_dedupe: JSValue = .zero,
exit_handler: ExitHandler = .{},
/// Do not access this field directly
/// It exists in the VirtualMachine struct so that
/// we don't accidentally make a stack copy of it
/// only use it through
/// source_mappings
saved_source_map_table: SavedSourceMap.HashTable = undefined,
arena: *Arena = undefined,
has_loaded: bool = false,
transpiled_count: usize = 0,
resolved_count: usize = 0,
had_errors: bool = false,
macros: MacroMap,
macro_entry_points: std.AutoArrayHashMap(i32, *MacroEntryPoint),
macro_mode: bool = false,
no_macros: bool = false,
has_any_macro_remappings: bool = false,
is_from_devserver: bool = false,
has_enabled_macro_mode: bool = false,
/// Used by bun:test to set global hooks for beforeAll, beforeEach, etc.
is_in_preload: bool = false,
transpiler_store: JSC.RuntimeTranspilerStore,
after_event_loop_callback_ctx: ?*anyopaque = null,
after_event_loop_callback: ?OpaqueCallback = null,
/// The arguments used to launch the process _after_ the script name and bun and any flags applied to Bun
/// "bun run foo --bar"
/// ["--bar"]
/// "bun run foo baz --bar"
/// ["baz", "--bar"]
/// "bun run foo
/// []
/// "bun foo --bar"
/// ["--bar"]
/// "bun foo baz --bar"
/// ["baz", "--bar"]
/// "bun foo
/// []
argv: []const []const u8 = &[_][]const u8{"bun"},
origin_timer: std.time.Timer = undefined,
origin_timestamp: u64 = 0,
macro_event_loop: EventLoop = EventLoop{},
regular_event_loop: EventLoop = EventLoop{},
event_loop: *EventLoop = undefined,
ref_strings: JSC.RefString.Map = undefined,
ref_strings_mutex: Lock = undefined,
file_blobs: JSC.WebCore.Blob.Store.Map,
source_mappings: SavedSourceMap = undefined,
active_tasks: usize = 0,
rare_data: ?*JSC.RareData = null,
is_us_loop_entered: bool = false,
pending_internal_promise: *JSC.JSInternalPromise = undefined,
auto_install_dependencies: bool = false,
onUnhandledRejection: *const OnUnhandledRejection = defaultOnUnhandledRejection,
onUnhandledRejectionCtx: ?*anyopaque = null,
unhandled_error_counter: usize = 0,
on_exception: ?*const OnException = null,
modules: ModuleLoader.AsyncModule.Queue = .{},
aggressive_garbage_collection: GCLevel = GCLevel.none,
parser_arena: ?@import("root").bun.ArenaAllocator = null,
gc_controller: JSC.GarbageCollectionController = .{},
worker: ?*JSC.WebWorker = null,
ipc: ?*IPCInstance = null,
debugger: ?Debugger = null,
has_started_debugger: bool = false,
pub const OnUnhandledRejection = fn (*VirtualMachine, globalObject: *JSC.JSGlobalObject, JSC.JSValue) void;
pub const OnException = fn (*ZigException) void;
pub fn isMainThread(this: *const VirtualMachine) bool {
return this.worker == null;
}
pub fn isInspectorEnabled(this: *const VirtualMachine) bool {
return this.debugger != null;
}
pub fn setOnException(this: *VirtualMachine, callback: *const OnException) void {
this.on_exception = callback;
}
pub fn clearOnException(this: *VirtualMachine) void {
this.on_exception = null;
}
const VMHolder = struct {
pub threadlocal var vm: ?*VirtualMachine = null;
};
pub inline fn get() *VirtualMachine {
return VMHolder.vm.?;
}
pub fn mimeType(this: *VirtualMachine, str: []const u8) ?bun.HTTP.MimeType {
return this.rareData().mimeTypeFromString(this.allocator, str);
}
pub fn onAfterEventLoop(this: *VirtualMachine) void {
if (this.after_event_loop_callback) |cb| {
var ctx = this.after_event_loop_callback_ctx;
this.after_event_loop_callback = null;
this.after_event_loop_callback_ctx = null;
cb(ctx);
}
}
pub fn isEventLoopAlive(vm: *const VirtualMachine) bool {
return vm.active_tasks > 0 or
vm.event_loop_handle.?.active > 0 or
vm.event_loop.tasks.count > 0;
}
const SourceMapHandlerGetter = struct {
vm: *VirtualMachine,
printer: *js_printer.BufferPrinter,
pub fn get(this: *SourceMapHandlerGetter) js_printer.SourceMapHandler {
if (this.vm.debugger == null) {
return SavedSourceMap.SourceMapHandler.init(&this.vm.source_mappings);
}
return js_printer.SourceMapHandler.For(SourceMapHandlerGetter, onChunk).init(this);
}
/// When the inspector is enabled, we want to generate an inline sourcemap.
/// And, for now, we also store it in source_mappings like normal
/// This is hideously expensive memory-wise...
pub fn onChunk(this: *SourceMapHandlerGetter, chunk: SourceMap.Chunk, source: logger.Source) anyerror!void {
var temp_json_buffer = bun.MutableString.initEmpty(bun.default_allocator);
defer temp_json_buffer.deinit();
temp_json_buffer = try chunk.printSourceMapContentsAtOffset(source, temp_json_buffer, true, SavedSourceMap.vlq_offset, true);
const source_map_url_prefix_start = "//# sourceMappingURL=data:application/json;base64,";
// TODO: do we need to %-encode the path?
const source_url_len = source.path.text.len;
const source_mapping_url = "\n//# sourceURL=";
const prefix_len = source_map_url_prefix_start.len + source_mapping_url.len + source_url_len;
try this.vm.source_mappings.putMappings(source, chunk.buffer);
const encode_len = bun.base64.encodeLen(temp_json_buffer.list.items);
try this.printer.ctx.buffer.growIfNeeded(encode_len + prefix_len + 2);
this.printer.ctx.buffer.appendAssumeCapacity("\n" ++ source_map_url_prefix_start);
_ = bun.base64.encode(this.printer.ctx.buffer.list.items.ptr[this.printer.ctx.buffer.len()..this.printer.ctx.buffer.list.capacity], temp_json_buffer.list.items);
this.printer.ctx.buffer.list.items.len += encode_len;
this.printer.ctx.buffer.appendAssumeCapacity(source_mapping_url);
// TODO: do we need to %-encode the path?
this.printer.ctx.buffer.appendAssumeCapacity(source.path.text);
try this.printer.ctx.buffer.append("\n");
}
};
pub inline fn sourceMapHandler(this: *VirtualMachine, printer: *js_printer.BufferPrinter) SourceMapHandlerGetter {
return SourceMapHandlerGetter{
.vm = this,
.printer = printer,
};
}
pub const GCLevel = enum(u3) {
none = 0,
mild = 1,
aggressive = 2,
};
pub threadlocal var is_main_thread_vm: bool = false;
pub const UnhandledRejectionScope = struct {
ctx: ?*anyopaque = null,
onUnhandledRejection: *const OnUnhandledRejection = undefined,
count: usize = 0,
pub fn apply(this: *UnhandledRejectionScope, vm: *JSC.VirtualMachine) void {
vm.onUnhandledRejection = this.onUnhandledRejection;
vm.onUnhandledRejectionCtx = this.ctx;
vm.unhandled_error_counter = this.count;
}
};
pub fn onQuietUnhandledRejectionHandler(this: *VirtualMachine, _: *JSC.JSGlobalObject, _: JSC.JSValue) void {
this.unhandled_error_counter += 1;
}
pub fn onQuietUnhandledRejectionHandlerCaptureValue(this: *VirtualMachine, _: *JSC.JSGlobalObject, value: JSC.JSValue) void {
this.unhandled_error_counter += 1;
value.ensureStillAlive();
if (this.unhandled_pending_rejection_to_capture) |ptr| {
ptr.* = value;
}
}
pub fn unhandledRejectionScope(this: *VirtualMachine) UnhandledRejectionScope {
return .{
.onUnhandledRejection = this.onUnhandledRejection,
.ctx = this.onUnhandledRejectionCtx,
.count = this.unhandled_error_counter,
};
}
pub fn resetUnhandledRejection(this: *VirtualMachine) void {
this.onUnhandledRejection = defaultOnUnhandledRejection;
}
pub fn loadExtraEnv(this: *VirtualMachine) void {
var map = this.bundler.env.map;
if (map.get("BUN_SHOW_BUN_STACKFRAMES") != null) {
this.hide_bun_stackframes = false;
}
if (map.map.fetchSwapRemove("BUN_INTERNAL_IPC_FD")) |kv| {
if (std.fmt.parseInt(i32, kv.value.value, 10) catch null) |fd| {
this.initIPCInstance(fd);
} else {
Output.printErrorln("Failed to parse BUN_INTERNAL_IPC_FD", .{});
}
}
if (map.get("BUN_GARBAGE_COLLECTOR_LEVEL")) |gc_level| {
if (strings.eqlComptime(gc_level, "1")) {
this.aggressive_garbage_collection = .mild;
} else if (strings.eqlComptime(gc_level, "2")) {
this.aggressive_garbage_collection = .aggressive;
}
}
}
pub fn onUnhandledError(this: *JSC.VirtualMachine, globalObject: *JSC.JSGlobalObject, value: JSC.JSValue) void {
this.unhandled_error_counter += 1;
this.onUnhandledRejection(this, globalObject, value);
}
pub fn defaultOnUnhandledRejection(this: *JSC.VirtualMachine, _: *JSC.JSGlobalObject, value: JSC.JSValue) void {
this.runErrorHandler(value, null);
}
pub inline fn packageManager(this: *VirtualMachine) *PackageManager {
return this.bundler.getPackageManager();
}
pub fn garbageCollect(this: *const VirtualMachine, sync: bool) JSValue {
@setCold(true);
Global.mimalloc_cleanup(false);
if (sync)
return this.global.vm().runGC(true);
this.global.vm().collectAsync();
return JSValue.jsNumber(this.global.vm().heapSize());
}
pub inline fn autoGarbageCollect(this: *const VirtualMachine) void {
if (this.aggressive_garbage_collection != .none) {
_ = this.garbageCollect(this.aggressive_garbage_collection == .aggressive);
}
}
pub fn reload(this: *VirtualMachine) void {
Output.debug("Reloading...", .{});
if (this.hot_reload == .watch) {
Output.flush();
bun.reloadProcess(bun.default_allocator, !strings.eqlComptime(this.bundler.env.map.get("BUN_CONFIG_NO_CLEAR_TERMINAL_ON_RELOAD") orelse "0", "true"));
}
if (!strings.eqlComptime(this.bundler.env.map.get("BUN_CONFIG_NO_CLEAR_TERMINAL_ON_RELOAD") orelse "0", "true")) {
Output.flush();
Output.disableBuffering();
Output.resetTerminalAll();
Output.enableBuffering();
}
this.global.reload();
this.pending_internal_promise = this.reloadEntryPoint(this.main) catch @panic("Failed to reload");
}
pub fn io(this: *VirtualMachine) *IO {
if (this.io_ == null) {
this.io_ = IO.init(this) catch @panic("Failed to initialize IO");
}
return &this.io_.?;
}
pub inline fn nodeFS(this: *VirtualMachine) *Node.NodeFS {
return this.node_fs orelse brk: {
this.node_fs = bun.default_allocator.create(Node.NodeFS) catch unreachable;
this.node_fs.?.* = Node.NodeFS{
// only used when standalone module graph is enabled
.vm = if (this.standalone_module_graph != null) this else null,
};
break :brk this.node_fs.?;
};
}
pub inline fn rareData(this: *VirtualMachine) *JSC.RareData {
return this.rare_data orelse brk: {
this.rare_data = this.allocator.create(JSC.RareData) catch unreachable;
this.rare_data.?.* = .{};
break :brk this.rare_data.?;
};
}
pub inline fn eventLoop(this: *VirtualMachine) *EventLoop {
return this.event_loop;
}
pub fn prepareLoop(_: *VirtualMachine) void {}
pub fn enterUWSLoop(this: *VirtualMachine) void {
var loop = this.event_loop_handle.?;
loop.run();
}
pub fn onBeforeExit(this: *VirtualMachine) void {
this.exit_handler.dispatchOnBeforeExit();
var dispatch = false;
while (true) {
while (this.isEventLoopAlive()) : (dispatch = true) {
this.tick();
this.eventLoop().autoTickActive();
}
if (dispatch) {
this.exit_handler.dispatchOnBeforeExit();
dispatch = false;
if (this.isEventLoopAlive()) continue;
}
break;
}
}
pub fn onExit(this: *VirtualMachine) void {
this.exit_handler.dispatchOnExit();
var rare_data = this.rare_data orelse return;
var hook = rare_data.cleanup_hook orelse return;
hook.execute();
while (hook.next) |next| {
next.execute();
hook = next;
}
}
pub fn nextAsyncTaskID(this: *VirtualMachine) u64 {
var debugger: *Debugger = &(this.debugger orelse return 0);
debugger.next_debugger_id +%= 1;
return debugger.next_debugger_id;
}
pub fn hotMap(this: *VirtualMachine) ?*JSC.RareData.HotMap {
if (this.hot_reload != .hot) {
return null;
}
return this.rareData().hotMap(this.allocator);
}
pub var has_created_debugger: bool = false;
pub const Debugger = struct {
path_or_port: ?[]const u8 = null,
unix: []const u8 = "",
script_execution_context_id: u32 = 0,
next_debugger_id: u64 = 1,
poll_ref: JSC.PollRef = .{},
wait_for_connection: bool = false,
set_breakpoint_on_first_line: bool = false,
const debug = Output.scoped(.DEBUGGER, false);
extern "C" fn Bun__createJSDebugger(*JSC.JSGlobalObject) u32;
extern "C" fn Bun__ensureDebugger(u32, bool) void;
extern "C" fn Bun__startJSDebuggerThread(*JSC.JSGlobalObject, u32, *bun.String) void;
var futex_atomic: std.atomic.Atomic(u32) = undefined;
pub fn create(this: *VirtualMachine, globalObject: *JSGlobalObject) !void {
debug("create", .{});
JSC.markBinding(@src());
if (has_created_debugger) return;
has_created_debugger = true;
var debugger = &this.debugger.?;
debugger.script_execution_context_id = Bun__createJSDebugger(globalObject);
if (!this.has_started_debugger) {
this.has_started_debugger = true;
futex_atomic = std.atomic.Atomic(u32).init(0);
var thread = try std.Thread.spawn(.{}, startJSDebuggerThread, .{this});
thread.detach();
}
this.eventLoop().ensureWaker();
if (debugger.wait_for_connection) {
debugger.poll_ref.ref(this);
}
debug("spin", .{});
while (futex_atomic.load(.Monotonic) > 0) std.Thread.Futex.wait(&futex_atomic, 1);
if (comptime Environment.allow_assert)
debug("waitForDebugger: {}", .{Output.ElapsedFormatter{
.colors = Output.enable_ansi_colors_stderr,
.duration_ns = @truncate(@as(u128, @intCast(std.time.nanoTimestamp() - bun.CLI.start_time))),
}});
Bun__ensureDebugger(debugger.script_execution_context_id, debugger.wait_for_connection);
while (debugger.wait_for_connection) {
this.eventLoop().tick();
if (debugger.wait_for_connection)
this.eventLoop().autoTickActive();
}
}
pub fn startJSDebuggerThread(other_vm: *VirtualMachine) void {
var arena = bun.MimallocArena.init() catch unreachable;
Output.Source.configureNamedThread("Debugger");
debug("startJSDebuggerThread", .{});
JSC.markBinding(@src());
var vm = JSC.VirtualMachine.init(.{
.allocator = arena.allocator(),
.args = std.mem.zeroes(Api.TransformOptions),
.store_fd = false,
}) catch @panic("Failed to create Debugger VM");
vm.allocator = arena.allocator();
vm.arena = &arena;
vm.bundler.configureDefines() catch @panic("Failed to configure defines");
vm.is_main_thread = false;
vm.eventLoop().ensureWaker();
vm.global.vm().holdAPILock(other_vm, @ptrCast(&start));
}
pub export fn Debugger__didConnect() void {
var this = VirtualMachine.get();
std.debug.assert(this.debugger.?.wait_for_connection);
this.debugger.?.wait_for_connection = false;
this.debugger.?.poll_ref.unref(this);
}
fn start(other_vm: *VirtualMachine) void {
JSC.markBinding(@src());
var this = VirtualMachine.get();
var debugger = other_vm.debugger.?;
if (debugger.unix.len > 0) {
var url = bun.String.create(debugger.unix);
Bun__startJSDebuggerThread(this.global, debugger.script_execution_context_id, &url);
}
if (debugger.path_or_port) |path_or_port| {
var url = bun.String.create(path_or_port);
Bun__startJSDebuggerThread(this.global, debugger.script_execution_context_id, &url);
}
this.global.handleRejectedPromises();
if (this.log.msgs.items.len > 0) {
if (Output.enable_ansi_colors) {
this.log.printForLogLevelWithEnableAnsiColors(Output.errorWriter(), true) catch {};
} else {
this.log.printForLogLevelWithEnableAnsiColors(Output.errorWriter(), false) catch {};
}
Output.prettyErrorln("\n", .{});
Output.flush();
}
debug("wake", .{});
futex_atomic.store(0, .Monotonic);
std.Thread.Futex.wake(&futex_atomic, 1);
this.eventLoop().tick();
while (true) {
while (this.isEventLoopAlive()) {
this.tick();
this.eventLoop().autoTickActive();
}
this.eventLoop().tickPossiblyForever();
}
}
};
pub inline fn enqueueTask(this: *VirtualMachine, task: Task) void {
this.eventLoop().enqueueTask(task);
}
pub inline fn enqueueTaskConcurrent(this: *VirtualMachine, task: *JSC.ConcurrentTask) void {
this.eventLoop().enqueueTaskConcurrent(task);
}
pub fn tick(this: *VirtualMachine) void {
this.eventLoop().tick();
}
pub fn waitFor(this: *VirtualMachine, cond: *bool) void {
while (!cond.*) {
this.eventLoop().tick();
if (!cond.*) {
this.eventLoop().autoTick();
}
}
}
pub fn waitForPromise(this: *VirtualMachine, promise: JSC.AnyPromise) void {
this.eventLoop().waitForPromise(promise);
}
pub fn waitForPromiseWithTimeout(this: *VirtualMachine, promise: JSC.AnyPromise, timeout: u32) bool {
return this.eventLoop().waitForPromiseWithTimeout(promise, timeout);
}
pub fn waitForTasks(this: *VirtualMachine) void {
this.eventLoop().waitForTasks();
}
pub const MacroMap = std.AutoArrayHashMap(i32, js.JSObjectRef);
pub fn enableMacroMode(this: *VirtualMachine) void {
if (!this.has_enabled_macro_mode) {
this.has_enabled_macro_mode = true;
this.macro_event_loop.tasks = EventLoop.Queue.init(default_allocator);
this.macro_event_loop.tasks.ensureTotalCapacity(16) catch unreachable;
this.macro_event_loop.global = this.global;
this.macro_event_loop.virtual_machine = this;
this.macro_event_loop.concurrent_tasks = .{};
}
this.bundler.options.target = .bun_macro;
this.bundler.resolver.caches.fs.use_alternate_source_cache = true;
this.macro_mode = true;
this.event_loop = &this.macro_event_loop;
Analytics.Features.macros = true;
this.transpiler_store.enabled = false;
}
pub fn disableMacroMode(this: *VirtualMachine) void {