diff --git a/cmake/sources/BakeRuntimeSources.txt b/cmake/sources/BakeRuntimeSources.txt index b6a49b4d4b..05f3cbb50b 100644 --- a/cmake/sources/BakeRuntimeSources.txt +++ b/cmake/sources/BakeRuntimeSources.txt @@ -1,4 +1,3 @@ -src/bake/bake.bind.ts src/bake/bake.d.ts src/bake/bake.private.d.ts src/bake/bun-framework-react/index.ts diff --git a/cmake/sources/BindgenSources.txt b/cmake/sources/BindgenSources.txt index e77ca92105..c1819b83f0 100644 --- a/cmake/sources/BindgenSources.txt +++ b/cmake/sources/BindgenSources.txt @@ -1,4 +1,4 @@ -src/bake/bake.bind.ts +src/bake.bind.ts src/bake/DevServer.bind.ts src/bun.js/api/BunObject.bind.ts src/bun.js/bindgen_test.bind.ts diff --git a/cmake/sources/ZigSources.txt b/cmake/sources/ZigSources.txt index 6700c9b7f6..40887a6c51 100644 --- a/cmake/sources/ZigSources.txt +++ b/cmake/sources/ZigSources.txt @@ -1,15 +1,16 @@ src/allocators.zig src/allocators/AllocationScope.zig -src/allocators/linux_memfd_allocator.zig -src/allocators/max_heap_allocator.zig -src/allocators/memory_allocator.zig +src/allocators/basic.zig +src/allocators/LinuxMemFdAllocator.zig +src/allocators/MaxHeapAllocator.zig src/allocators/MemoryReportingAllocator.zig -src/allocators/mimalloc_arena.zig src/allocators/mimalloc.zig +src/allocators/MimallocArena.zig src/allocators/NullableAllocator.zig -src/analytics/analytics_schema.zig -src/analytics/analytics_thread.zig +src/analytics.zig +src/analytics/schema.zig src/api/schema.zig +src/ast.zig src/ast/Ast.zig src/ast/ASTMemoryAllocator.zig src/ast/B.zig @@ -33,20 +34,18 @@ src/ast/UseDirective.zig src/async/posix_event_loop.zig src/async/stub_event_loop.zig src/async/windows_event_loop.zig -src/baby_list.zig -src/bake/bake.zig +src/bake.zig src/bake/DevServer.zig src/bake/FrameworkRouter.zig src/bake/production.zig src/base64/base64.zig -src/bit_set.zig src/bits.zig src/boringssl.zig src/brotli.zig src/btjs.zig -src/bun_js.zig +src/bun.js.zig src/bun.js/api.zig -src/bun.js/api/bun/dns_resolver.zig +src/bun.js/api/bun/dns.zig src/bun.js/api/bun/h2_frame_parser.zig src/bun.js/api/bun/lshpack.zig src/bun.js/api/bun/process.zig @@ -96,6 +95,7 @@ src/bun.js/api/Timer/EventLoopTimer.zig src/bun.js/api/Timer/ImmediateObject.zig src/bun.js/api/Timer/TimeoutObject.zig src/bun.js/api/Timer/TimerObjectInternals.zig +src/bun.js/api/Timer/WTFTimer.zig src/bun.js/api/TOMLObject.zig src/bun.js/api/UnsafeObject.zig src/bun.js/bindgen_test.zig @@ -280,7 +280,6 @@ src/bun.js/webcore/streams.zig src/bun.js/webcore/TextDecoder.zig src/bun.js/webcore/TextEncoder.zig src/bun.js/webcore/TextEncoderStreamEncoder.zig -src/bun.js/WTFTimer.zig src/bun.zig src/bundler/AstBuilder.zig src/bundler/bundle_v2.zig @@ -361,6 +360,11 @@ src/cli/update_interactive_command.zig src/cli/upgrade_command.zig src/cli/why_command.zig src/codegen/process_windows_translate_c.zig +src/collections.zig +src/collections/baby_list.zig +src/collections/bit_set.zig +src/collections/hive_array.zig +src/collections/multi_array_list.zig src/compile_target.zig src/comptime_string_map.zig src/copy_file.zig @@ -509,7 +513,6 @@ src/env.zig src/errno/darwin_errno.zig src/errno/linux_errno.zig src/errno/windows_errno.zig -src/exact_size_matcher.zig src/fd.zig src/feature_flags.zig src/fmt.zig @@ -521,10 +524,8 @@ src/glob.zig src/glob/GlobWalker.zig src/glob/match.zig src/Global.zig -src/grapheme.zig src/heap_breakdown.zig src/highway.zig -src/hive_array.zig src/hmac.zig src/HTMLScanner.zig src/http.zig @@ -619,6 +620,10 @@ src/install/resolvers/folder_resolver.zig src/install/versioned_url.zig src/install/windows-shim/BinLinkingShim.zig src/install/windows-shim/bun_shim_impl.zig +src/interchange.zig +src/interchange/json.zig +src/interchange/toml.zig +src/interchange/toml/lexer.zig src/io/heap.zig src/io/io.zig src/io/MaxBuf.zig @@ -627,14 +632,12 @@ src/io/PipeReader.zig src/io/pipes.zig src/io/PipeWriter.zig src/io/source.zig -src/js_ast.zig src/js_lexer_tables.zig src/js_lexer.zig src/js_lexer/identifier.zig src/js_parser.zig src/js_printer.zig src/jsc_stub.zig -src/json_parser.zig src/libarchive/libarchive-bindings.zig src/libarchive/libarchive.zig src/linear_fifo.zig @@ -646,7 +649,6 @@ src/main_test.zig src/main_wasm.zig src/main.zig src/meta.zig -src/multi_array_list.zig src/napi/napi.zig src/node_fallbacks.zig src/open.zig @@ -821,19 +823,20 @@ src/sql/postgres/types/PostgresString.zig src/sql/postgres/types/Tag.zig src/StandaloneModuleGraph.zig src/StaticHashMap.zig -src/string_immutable.zig -src/string_types.zig src/string.zig -src/string/escapeHTML.zig src/string/HashedString.zig +src/string/immutable.zig +src/string/immutable/escapeHTML.zig +src/string/immutable/exact_size_matcher.zig +src/string/immutable/grapheme.zig +src/string/immutable/paths.zig +src/string/immutable/unicode.zig +src/string/immutable/visible.zig src/string/MutableString.zig -src/string/paths.zig src/string/PathString.zig src/string/SmolStr.zig src/string/StringBuilder.zig src/string/StringJoiner.zig -src/string/unicode.zig -src/string/visible.zig src/string/WTFStringImpl.zig src/sys_uv.zig src/sys.zig @@ -850,8 +853,6 @@ src/threading/ThreadPool.zig src/threading/unbounded_queue.zig src/threading/WaitGroup.zig src/tmp.zig -src/toml/toml_lexer.zig -src/toml/toml_parser.zig src/tracy.zig src/trait.zig src/transpiler.zig diff --git a/docs/project/bindgen.md b/docs/project/bindgen.md index 7952b497c7..3fc91622cf 100644 --- a/docs/project/bindgen.md +++ b/docs/project/bindgen.md @@ -20,7 +20,7 @@ this one: Given a file implementing a simple function, such as `add` ```zig#src/bun.js/math.zig -pub fn add(global: *JSC.JSGlobalObject, a: i32, b: i32) !i32 { +pub fn add(global: *jsc.JSGlobalObject, a: i32, b: i32) !i32 { return std.math.add(i32, a, b) catch { // Binding functions can return `error.OutOfMemory` and `error.JSError`. // Others like `error.Overflow` from `std.math.add` must be converted. @@ -33,7 +33,7 @@ const gen = bun.gen.math; // "math" being this file's basename const std = @import("std"); const bun = @import("bun"); -const JSC = bun.JSC; +const jsc = bun.jsc; ``` Then describe the API schema using a `.bind.ts` function. The binding file goes next to the Zig file. diff --git a/misctools/features.zig b/misctools/features.zig index 2a2f3be834..392391dfa0 100644 --- a/misctools/features.zig +++ b/misctools/features.zig @@ -2,16 +2,15 @@ const std = @import("std"); const path_handler = @import("../src/resolver/resolve_path.zig"); const bun = @import("bun"); -const string = bun.string; +const string = []const u8; 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 stringZ = [:0]const u8; const default_allocator = bun.default_allocator; -const C = bun.C; -const Features = @import("../src/analytics/analytics_thread.zig").Features; +const Features = bun.analytics.Features; // zig run --main-pkg-path ../ ./features.zig pub fn main() anyerror!void { diff --git a/misctools/http_bench.zig b/misctools/http_bench.zig index 8acdb085b0..64853e3d43 100644 --- a/misctools/http_bench.zig +++ b/misctools/http_bench.zig @@ -1,14 +1,13 @@ const std = @import("std"); const bun = @import("bun"); -const string = bun.string; +const string = []const u8; 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 stringZ = [:0]const u8; const default_allocator = bun.default_allocator; -const C = bun.C; const clap = @import("../src/deps/zig-clap/clap.zig"); const URL = @import("../src/url.zig").URL; diff --git a/misctools/machbench.zig b/misctools/machbench.zig index 4e4b1549a8..18146b8106 100644 --- a/misctools/machbench.zig +++ b/misctools/machbench.zig @@ -1,15 +1,14 @@ // most of this file is copy pasted from other files in misctools const std = @import("std"); const bun = @import("bun"); -const string = bun.string; +const string = []const u8; 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 stringZ = [:0]const u8; const default_allocator = bun.default_allocator; -const C = bun.C; const clap = @import("../src/deps/zig-clap/clap.zig"); const URL = @import("../src/url.zig").URL; diff --git a/misctools/readlink-getfd.zig b/misctools/readlink-getfd.zig index 60edaaa5e6..6321f6c149 100644 --- a/misctools/readlink-getfd.zig +++ b/misctools/readlink-getfd.zig @@ -2,15 +2,14 @@ const std = @import("std"); const path_handler = @import("../src/resolver/resolve_path.zig"); const bun = @import("bun"); -const string = bun.string; +const string = []const u8; 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 stringZ = [:0]const u8; const default_allocator = bun.default_allocator; -const C = bun.C; // zig build-exe -Doptimize=ReleaseFast --main-pkg-path ../ ./readlink-getfd.zig pub fn main() anyerror!void { diff --git a/misctools/readlink-realpath.zig b/misctools/readlink-realpath.zig index 243b13af4b..0cc0496839 100644 --- a/misctools/readlink-realpath.zig +++ b/misctools/readlink-realpath.zig @@ -2,15 +2,14 @@ const std = @import("std"); const path_handler = @import("../src/resolver/resolve_path.zig"); const bun = @import("bun"); -const string = bun.string; +const string = []const u8; 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 stringZ = [:0]const u8; const default_allocator = bun.default_allocator; -const C = bun.C; // zig build-exe -Doptimize=ReleaseFast --main-pkg-path ../ ./readlink-getfd.zig pub fn main() anyerror!void { diff --git a/misctools/tgz.zig b/misctools/tgz.zig index 9ddfeeb2ca..d3dd482d57 100644 --- a/misctools/tgz.zig +++ b/misctools/tgz.zig @@ -2,15 +2,14 @@ const std = @import("std"); const path_handler = @import("../src/resolver/resolve_path.zig"); const bun = @import("bun"); -const string = bun.string; +const string = []const u8; 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 stringZ = [:0]const u8; const default_allocator = bun.default_allocator; -const C = bun.C; const Archive = @import("../src/libarchive/libarchive.zig").Archive; const Zlib = @import("../src/zlib.zig"); diff --git a/src/Global.zig b/src/Global.zig index f1550e27db..c330d4da44 100644 --- a/src/Global.zig +++ b/src/Global.zig @@ -166,10 +166,10 @@ pub const versions = @import("./generated_versions_list.zig"); // 2. if I want to configure allocator later pub inline fn configureAllocator(_: AllocatorConfiguration) void { // if (comptime !use_mimalloc) return; - // const Mimalloc = @import("./allocators/mimalloc.zig"); - // Mimalloc.mi_option_set_enabled(Mimalloc.mi_option_verbose, config.verbose); - // Mimalloc.mi_option_set_enabled(Mimalloc.mi_option_large_os_pages, config.long_running); - // if (!config.long_running) Mimalloc.mi_option_set(Mimalloc.mi_option_reset_delay, 0); + // const mimalloc = bun.mimalloc; + // mimalloc.mi_option_set_enabled(mimalloc.mi_option_verbose, config.verbose); + // mimalloc.mi_option_set_enabled(mimalloc.mi_option_large_os_pages, config.long_running); + // if (!config.long_running) mimalloc.mi_option_set(mimalloc.mi_option_reset_delay, 0); } pub fn notimpl() noreturn { @@ -185,15 +185,15 @@ pub fn crash() noreturn { pub const BunInfo = struct { bun_version: string, - platform: Analytics.GenerateHeader.GeneratePlatform.Platform, + platform: analytics.GenerateHeader.GeneratePlatform.Platform, - const Analytics = @import("./analytics/analytics_thread.zig"); - const JSON = bun.JSON; - const JSAst = bun.JSAst; + const analytics = bun.analytics; + const JSON = bun.json; + const JSAst = bun.ast; pub fn generate(comptime Bundler: type, _: Bundler, allocator: std.mem.Allocator) !JSAst.Expr { const info = BunInfo{ .bun_version = Global.package_json_version, - .platform = Analytics.GenerateHeader.GeneratePlatform.forOS(), + .platform = analytics.GenerateHeader.GeneratePlatform.forOS(), }; return try JSON.toAST(allocator, BunInfo, info); @@ -208,7 +208,7 @@ comptime { } pub export fn Bun__onExit() void { - bun.JSC.Node.FSEvents.closeAndWait(); + bun.jsc.Node.FSEvents.closeAndWait(); runExitCallbacks(); Output.flush(); @@ -221,6 +221,8 @@ comptime { _ = Bun__onExit; } +const string = []const u8; + const Output = @import("./output.zig"); const std = @import("std"); @@ -228,6 +230,5 @@ const Environment = @import("./env.zig"); const version_string = Environment.version_string; const bun = @import("bun"); -const Mimalloc = bun.Mimalloc; -const string = bun.string; +const Mimalloc = bun.mimalloc; const use_mimalloc = bun.use_mimalloc; diff --git a/src/OutputFile.zig b/src/OutputFile.zig index d15a33c022..3ae4011238 100644 --- a/src/OutputFile.zig +++ b/src/OutputFile.zig @@ -15,7 +15,7 @@ hash: u64 = 0, is_executable: bool = false, source_map_index: u32 = std.math.maxInt(u32), bytecode_index: u32 = std.math.maxInt(u32), -output_kind: JSC.API.BuildArtifact.OutputKind, +output_kind: jsc.API.BuildArtifact.OutputKind, /// Relative dest_path: []const u8 = "", side: ?bun.bake.Side, @@ -154,14 +154,14 @@ pub const Value = union(Kind) { pub const SavedFile = struct { pub fn toJS( - globalThis: *JSC.JSGlobalObject, + globalThis: *jsc.JSGlobalObject, path: []const u8, byte_size: usize, - ) JSC.JSValue { + ) jsc.JSValue { const mime_type = globalThis.bunVM().mimeType(path); - const store = JSC.WebCore.Blob.Store.initFile( - JSC.Node.PathOrFileDescriptor{ - .path = JSC.Node.PathLike{ + const store = jsc.WebCore.Blob.Store.initFile( + jsc.Node.PathOrFileDescriptor{ + .path = jsc.Node.PathLike{ .string = bun.PathString.init(path), }, }, @@ -169,12 +169,12 @@ pub const SavedFile = struct { bun.default_allocator, ) catch unreachable; - var blob = bun.default_allocator.create(JSC.WebCore.Blob) catch unreachable; - blob.* = JSC.WebCore.Blob.initWithStore(store, globalThis); + var blob = bun.default_allocator.create(jsc.WebCore.Blob) catch unreachable; + blob.* = jsc.WebCore.Blob.initWithStore(store, globalThis); if (mime_type) |mime| { blob.content_type = mime.value; } - blob.size = @as(JSC.WebCore.Blob.SizeType, @truncate(byte_size)); + blob.size = @as(jsc.WebCore.Blob.SizeType, @truncate(byte_size)); blob.allocator = bun.default_allocator; return blob.toJS(globalThis); } @@ -215,7 +215,7 @@ pub const Options = struct { size: ?usize = null, input_path: []const u8 = "", display_size: u32 = 0, - output_kind: JSC.API.BuildArtifact.OutputKind, + output_kind: jsc.API.BuildArtifact.OutputKind, is_executable: bool, data: union(enum) { buffer: struct { @@ -289,7 +289,7 @@ pub fn writeToDisk(f: OutputFile, root_dir: std.fs.Dir, root_dir_path: []const u } var path_buf: bun.PathBuffer = undefined; - _ = try JSC.Node.fs.NodeFS.writeFileWithPathBuffer(&path_buf, .{ + _ = try jsc.Node.fs.NodeFS.writeFileWithPathBuffer(&path_buf, .{ .data = .{ .buffer = .{ .buffer = .{ .ptr = @constCast(value.bytes.ptr), @@ -344,20 +344,20 @@ pub fn copyTo(file: *const OutputFile, _: string, rel_path: []const u8, dir: Fil pub fn toJS( this: *OutputFile, owned_pathname: ?[]const u8, - globalObject: *JSC.JSGlobalObject, -) bun.JSC.JSValue { + globalObject: *jsc.JSGlobalObject, +) bun.jsc.JSValue { return switch (this.value) { .move, .pending => @panic("Unexpected pending output file"), .noop => .js_undefined, .copy => |copy| brk: { - const file_blob = JSC.WebCore.Blob.Store.initFile( + const file_blob = jsc.WebCore.Blob.Store.initFile( if (copy.fd.isValid()) - JSC.Node.PathOrFileDescriptor{ + jsc.Node.PathOrFileDescriptor{ .fd = copy.fd, } else - JSC.Node.PathOrFileDescriptor{ - .path = JSC.Node.PathLike{ .string = bun.PathString.init(globalObject.allocator().dupe(u8, copy.pathname) catch unreachable) }, + jsc.Node.PathOrFileDescriptor{ + .path = jsc.Node.PathLike{ .string = bun.PathString.init(globalObject.allocator().dupe(u8, copy.pathname) catch unreachable) }, }, this.loader.toMimeType(&.{owned_pathname orelse ""}), globalObject.allocator(), @@ -365,8 +365,8 @@ pub fn toJS( Output.panic("error: Unable to create file blob: \"{s}\"", .{@errorName(err)}); }; - var build_output = bun.new(JSC.API.BuildArtifact, .{ - .blob = JSC.WebCore.Blob.initWithStore(file_blob, globalObject), + var build_output = bun.new(jsc.API.BuildArtifact, .{ + .blob = jsc.WebCore.Blob.initWithStore(file_blob, globalObject), .hash = this.hash, .loader = this.input_loader, .output_kind = this.output_kind, @@ -383,12 +383,12 @@ pub fn toJS( break :brk build_output.toJS(globalObject); }, .saved => brk: { - var build_output = bun.default_allocator.create(JSC.API.BuildArtifact) catch @panic("Unable to allocate Artifact"); + var build_output = bun.default_allocator.create(jsc.API.BuildArtifact) catch @panic("Unable to allocate Artifact"); const path_to_use = owned_pathname orelse this.src_path.text; - const file_blob = JSC.WebCore.Blob.Store.initFile( - JSC.Node.PathOrFileDescriptor{ - .path = JSC.Node.PathLike{ .string = bun.PathString.init(owned_pathname orelse (bun.default_allocator.dupe(u8, this.src_path.text) catch unreachable)) }, + const file_blob = jsc.WebCore.Blob.Store.initFile( + jsc.Node.PathOrFileDescriptor{ + .path = jsc.Node.PathLike{ .string = bun.PathString.init(owned_pathname orelse (bun.default_allocator.dupe(u8, this.src_path.text) catch unreachable)) }, }, this.loader.toMimeType(&.{owned_pathname orelse ""}), globalObject.allocator(), @@ -403,8 +403,8 @@ pub fn toJS( }, }; - build_output.* = JSC.API.BuildArtifact{ - .blob = JSC.WebCore.Blob.initWithStore(file_blob, globalObject), + build_output.* = jsc.API.BuildArtifact{ + .blob = jsc.WebCore.Blob.initWithStore(file_blob, globalObject), .hash = this.hash, .loader = this.input_loader, .output_kind = this.output_kind, @@ -414,7 +414,7 @@ pub fn toJS( break :brk build_output.toJS(globalObject); }, .buffer => |buffer| brk: { - var blob = JSC.WebCore.Blob.init(@constCast(buffer.bytes), buffer.allocator, globalObject); + var blob = jsc.WebCore.Blob.init(@constCast(buffer.bytes), buffer.allocator, globalObject); if (blob.store) |store| { store.mime_type = this.loader.toMimeType(&.{owned_pathname orelse ""}); blob.content_type = store.mime_type.value; @@ -422,10 +422,10 @@ pub fn toJS( blob.content_type = this.loader.toMimeType(&.{owned_pathname orelse ""}).value; } - blob.size = @as(JSC.WebCore.Blob.SizeType, @truncate(buffer.bytes.len)); + blob.size = @as(jsc.WebCore.Blob.SizeType, @truncate(buffer.bytes.len)); - var build_output = bun.default_allocator.create(JSC.API.BuildArtifact) catch @panic("Unable to allocate Artifact"); - build_output.* = JSC.API.BuildArtifact{ + var build_output = bun.default_allocator.create(jsc.API.BuildArtifact) catch @panic("Unable to allocate Artifact"); + build_output.* = jsc.API.BuildArtifact{ .blob = blob, .hash = this.hash, .loader = this.input_loader, @@ -448,20 +448,20 @@ pub fn toJS( pub fn toBlob( this: *OutputFile, allocator: std.mem.Allocator, - globalThis: *JSC.JSGlobalObject, -) !JSC.WebCore.Blob { + globalThis: *jsc.JSGlobalObject, +) !jsc.WebCore.Blob { return switch (this.value) { .move, .pending => @panic("Unexpected pending output file"), .noop => @panic("Cannot convert noop output file to blob"), .copy => |copy| brk: { - const file_blob = try JSC.WebCore.Blob.Store.initFile( + const file_blob = try jsc.WebCore.Blob.Store.initFile( if (copy.fd.isValid()) - JSC.Node.PathOrFileDescriptor{ + jsc.Node.PathOrFileDescriptor{ .fd = copy.fd, } else - JSC.Node.PathOrFileDescriptor{ - .path = JSC.Node.PathLike{ .string = bun.PathString.init(allocator.dupe(u8, copy.pathname) catch unreachable) }, + jsc.Node.PathOrFileDescriptor{ + .path = jsc.Node.PathLike{ .string = bun.PathString.init(allocator.dupe(u8, copy.pathname) catch unreachable) }, }, this.loader.toMimeType(&.{ this.dest_path, this.src_path.text }), allocator, @@ -474,12 +474,12 @@ pub fn toBlob( }, }; - break :brk JSC.WebCore.Blob.initWithStore(file_blob, globalThis); + break :brk jsc.WebCore.Blob.initWithStore(file_blob, globalThis); }, .saved => brk: { - const file_blob = try JSC.WebCore.Blob.Store.initFile( - JSC.Node.PathOrFileDescriptor{ - .path = JSC.Node.PathLike{ .string = bun.PathString.init(allocator.dupe(u8, this.src_path.text) catch unreachable) }, + const file_blob = try jsc.WebCore.Blob.Store.initFile( + jsc.Node.PathOrFileDescriptor{ + .path = jsc.Node.PathLike{ .string = bun.PathString.init(allocator.dupe(u8, this.src_path.text) catch unreachable) }, }, this.loader.toMimeType(&.{ this.dest_path, this.src_path.text }), allocator, @@ -492,10 +492,10 @@ pub fn toBlob( }, }; - break :brk JSC.WebCore.Blob.initWithStore(file_blob, globalThis); + break :brk jsc.WebCore.Blob.initWithStore(file_blob, globalThis); }, .buffer => |buffer| brk: { - var blob = JSC.WebCore.Blob.init(@constCast(buffer.bytes), buffer.allocator, globalThis); + var blob = jsc.WebCore.Blob.init(@constCast(buffer.bytes), buffer.allocator, globalThis); if (blob.store) |store| { store.mime_type = this.loader.toMimeType(&.{ this.dest_path, this.src_path.text }); blob.content_type = store.mime_type.value; @@ -510,7 +510,7 @@ pub fn toBlob( }, }; - blob.size = @as(JSC.WebCore.Blob.SizeType, @truncate(buffer.bytes.len)); + blob.size = @as(jsc.WebCore.Blob.SizeType, @truncate(buffer.bytes.len)); break :brk blob; }, }; @@ -522,10 +522,10 @@ const resolve_path = @import("./resolver/resolve_path.zig"); const resolver = @import("./resolver/resolver.zig"); const std = @import("std"); const Loader = @import("./options.zig").Loader; -const Output = @import("./Global.zig").Output; const bun = @import("bun"); const Environment = bun.Environment; const FileDescriptorType = bun.FileDescriptor; const Fs = bun.fs; -const JSC = bun.JSC; +const jsc = bun.jsc; +const Output = bun.Global.Output; diff --git a/src/StandaloneModuleGraph.zig b/src/StandaloneModuleGraph.zig index 7b2e96a42d..ead0edb774 100644 --- a/src/StandaloneModuleGraph.zig +++ b/src/StandaloneModuleGraph.zig @@ -182,7 +182,7 @@ pub const StandaloneModuleGraph = struct { return this.wtf_string.dupeRef(); } - pub fn blob(this: *File, globalObject: *bun.JSC.JSGlobalObject) *bun.webcore.Blob { + pub fn blob(this: *File, globalObject: *bun.jsc.JSGlobalObject) *bun.webcore.Blob { if (this.cached_blob == null) { const store = bun.webcore.Blob.Store.init(@constCast(this.contents), bun.default_allocator); // make it never free @@ -1226,13 +1226,13 @@ pub const StandaloneModuleGraph = struct { // the allocator given to the JS parser is not respected for all parts // of the parse, so we need to remember to reset the ast store - bun.JSAst.Expr.Data.Store.reset(); - bun.JSAst.Stmt.Data.Store.reset(); + bun.ast.Expr.Data.Store.reset(); + bun.ast.Stmt.Data.Store.reset(); defer { - bun.JSAst.Expr.Data.Store.reset(); - bun.JSAst.Stmt.Data.Store.reset(); + bun.ast.Expr.Data.Store.reset(); + bun.ast.Stmt.Data.Store.reset(); } - var json = bun.JSON.parse(&json_src, &log, arena, false) catch + var json = bun.json.parse(&json_src, &log, arena, false) catch return error.InvalidSourceMap; const mappings_str = json.get("mappings") orelse @@ -1324,4 +1324,4 @@ const Syscall = bun.sys; const macho = bun.macho; const pe = bun.pe; const strings = bun.strings; -const Schema = bun.Schema.Api; +const Schema = bun.schema.api; diff --git a/src/Watcher.zig b/src/Watcher.zig index ff717d4808..ab7b72a6ac 100644 --- a/src/Watcher.zig +++ b/src/Watcher.zig @@ -289,7 +289,7 @@ pub fn flushEvictions(this: *Watcher) void { } } -fn watchLoop(this: *Watcher) bun.JSC.Maybe(void) { +fn watchLoop(this: *Watcher) bun.jsc.Maybe(void) { while (this.running) { // individual platform implementation will call onFileUpdate switch (Platform.watchLoopCycle(this)) { @@ -309,7 +309,7 @@ fn appendFileAssumeCapacity( parent_hash: HashType, package_json: ?*PackageJSON, comptime clone_file_path: bool, -) bun.JSC.Maybe(void) { +) bun.jsc.Maybe(void) { if (comptime Environment.isWindows) { // on windows we can only watch items that are in the directory tree of the top level dir const rel = bun.path.isParentOrEqual(this.fs.top_level_dir, file_path); @@ -390,7 +390,7 @@ fn appendDirectoryAssumeCapacity( file_path: string, hash: HashType, comptime clone_file_path: bool, -) bun.JSC.Maybe(WatchItemIndex) { +) bun.jsc.Maybe(WatchItemIndex) { if (comptime Environment.isWindows) { // on windows we can only watch items that are in the directory tree of the top level dir const rel = bun.path.isParentOrEqual(this.fs.top_level_dir, file_path); @@ -501,7 +501,7 @@ pub fn appendFileMaybeLock( package_json: ?*PackageJSON, comptime clone_file_path: bool, comptime lock: bool, -) bun.JSC.Maybe(void) { +) bun.jsc.Maybe(void) { if (comptime lock) this.mutex.lock(); defer if (comptime lock) this.mutex.unlock(); bun.assert(file_path.len > 1); @@ -577,7 +577,7 @@ pub fn appendFile( dir_fd: bun.FileDescriptor, package_json: ?*PackageJSON, comptime clone_file_path: bool, -) bun.JSC.Maybe(void) { +) bun.jsc.Maybe(void) { return appendFileMaybeLock(this, fd, file_path, hash, loader, dir_fd, package_json, clone_file_path, true); } @@ -587,7 +587,7 @@ pub fn addDirectory( file_path: string, hash: HashType, comptime clone_file_path: bool, -) bun.JSC.Maybe(WatchItemIndex) { +) bun.jsc.Maybe(WatchItemIndex) { this.mutex.lock(); defer this.mutex.unlock(); @@ -609,7 +609,7 @@ pub fn addFile( dir_fd: bun.FileDescriptor, package_json: ?*PackageJSON, comptime clone_file_path: bool, -) bun.JSC.Maybe(void) { +) bun.jsc.Maybe(void) { // This must lock due to concurrent transpiler this.mutex.lock(); defer this.mutex.unlock(); @@ -674,6 +674,8 @@ pub fn onMaybeWatchDirectory(watch: *Watcher, file_path: string, dir_fd: bun.Sto } } +const string = []const u8; + const WindowsWatcher = @import("./watcher/WindowsWatcher.zig"); const options = @import("./options.zig"); const std = @import("std"); @@ -684,5 +686,4 @@ const Environment = bun.Environment; const FeatureFlags = bun.FeatureFlags; const Mutex = bun.Mutex; const Output = bun.Output; -const string = bun.string; const strings = bun.strings; diff --git a/src/allocators.zig b/src/allocators.zig index 6bfe2087d8..6e21740d50 100644 --- a/src/allocators.zig +++ b/src/allocators.zig @@ -1,3 +1,13 @@ +pub const c_allocator = @import("./allocators/basic.zig").c_allocator; +pub const z_allocator = @import("./allocators/basic.zig").z_allocator; +pub const mimalloc = @import("./allocators/mimalloc.zig"); +pub const MimallocArena = @import("./allocators/MimallocArena.zig"); +pub const AllocationScope = @import("./allocators/AllocationScope.zig"); +pub const NullableAllocator = @import("./allocators/NullableAllocator.zig"); +pub const MaxHeapAllocator = @import("./allocators/MaxHeapAllocator.zig"); +pub const MemoryReportingAllocator = @import("./allocators/MemoryReportingAllocator.zig"); +pub const LinuxMemFdAllocator = @import("./allocators/LinuxMemFdAllocator.zig"); + pub fn isSliceInBufferT(comptime T: type, slice: []const T, buffer: []const T) bool { return (@intFromPtr(buffer.ptr) <= @intFromPtr(slice.ptr) and (@intFromPtr(slice.ptr) + slice.len * @sizeOf(T)) <= (@intFromPtr(buffer.ptr) + buffer.len * @sizeOf(T))); @@ -766,5 +776,5 @@ const Environment = @import("./env.zig"); const std = @import("std"); const bun = @import("bun"); -const Mutex = bun.Mutex; const OOM = bun.OOM; +const Mutex = bun.threading.Mutex; diff --git a/src/allocators/LinuxMemFdAllocator.zig b/src/allocators/LinuxMemFdAllocator.zig new file mode 100644 index 0000000000..e0c4585b73 --- /dev/null +++ b/src/allocators/LinuxMemFdAllocator.zig @@ -0,0 +1,189 @@ +//! When cloning large amounts of data potentially multiple times, we can +//! leverage copy-on-write memory to avoid actually copying the data. To do that +//! on Linux, we need to use a memfd, which is a Linux-specific feature. +//! +//! The steps are roughly: +//! +//! 1. Create a memfd +//! 2. Write the data to the memfd +//! 3. Map the memfd into memory +//! +//! Then, to clone the data later, we can just call `mmap` again. +//! +//! The big catch is that mmap(), memfd_create(), write() all have overhead. And +//! often we will re-use virtual memory within the process. This does not reuse +//! the virtual memory. So we should only really use this for large blobs of +//! data that we expect to be cloned multiple times. Such as Blob in FormData. + +const Self = @This(); + +const RefCount = bun.ptr.ThreadSafeRefCount(@This(), "ref_count", deinit, .{}); + +pub const new = bun.TrivialNew(@This()); +pub const ref = RefCount.ref; +pub const deref = RefCount.deref; + +ref_count: RefCount, +fd: bun.FileDescriptor = .invalid, +size: usize = 0, + +var memfd_counter = std.atomic.Value(usize).init(0); + +fn deinit(self: *Self) void { + self.fd.close(); + bun.destroy(self); +} + +pub fn allocator(self: *Self) std.mem.Allocator { + return .{ + .ptr = self, + .vtable = AllocatorInterface.VTable, + }; +} + +pub fn from(allocator_: std.mem.Allocator) ?*Self { + if (allocator_.vtable == AllocatorInterface.VTable) { + return @alignCast(@ptrCast(allocator_.ptr)); + } + + return null; +} + +const AllocatorInterface = struct { + fn alloc(_: *anyopaque, _: usize, _: std.mem.Alignment, _: usize) ?[*]u8 { + // it should perform no allocations or resizes + return null; + } + + fn free( + ptr: *anyopaque, + buf: []u8, + _: std.mem.Alignment, + _: usize, + ) void { + var self: *Self = @alignCast(@ptrCast(ptr)); + defer self.deref(); + bun.sys.munmap(@alignCast(@ptrCast(buf))).unwrap() catch |err| { + bun.Output.debugWarn("Failed to munmap memfd: {}", .{err}); + }; + } + + pub const VTable = &std.mem.Allocator.VTable{ + .alloc = &AllocatorInterface.alloc, + .resize = &std.mem.Allocator.noResize, + .remap = &std.mem.Allocator.noRemap, + .free = &free, + }; +}; + +pub fn alloc(self: *Self, len: usize, offset: usize, flags: std.posix.MAP) bun.jsc.Maybe(bun.webcore.Blob.Store.Bytes) { + var size = len; + + // size rounded up to nearest page + size = std.mem.alignForward(usize, size, std.heap.pageSize()); + + var flags_mut = flags; + flags_mut.TYPE = .SHARED; + + switch (bun.sys.mmap( + null, + @min(size, self.size), + std.posix.PROT.READ | std.posix.PROT.WRITE, + flags_mut, + self.fd, + offset, + )) { + .result => |slice| { + return .{ + .result = bun.webcore.Blob.Store.Bytes{ + .cap = @truncate(slice.len), + .ptr = slice.ptr, + .len = @truncate(len), + .allocator = self.allocator(), + }, + }; + }, + .err => |errno| { + return .{ .err = errno }; + }, + } +} + +pub fn shouldUse(bytes: []const u8) bool { + if (comptime !bun.Environment.isLinux) { + return false; + } + + if (bun.jsc.VirtualMachine.is_smol_mode) { + return bytes.len >= 1024 * 1024 * 1; + } + + // This is a net 2x - 4x slowdown to new Blob([huge]) + // so we must be careful + return bytes.len >= 1024 * 1024 * 8; +} + +pub fn create(bytes: []const u8) bun.jsc.Maybe(bun.webcore.Blob.Store.Bytes) { + if (comptime !bun.Environment.isLinux) { + unreachable; + } + + var label_buf: [128]u8 = undefined; + const label = std.fmt.bufPrintZ(&label_buf, "memfd-num-{d}", .{memfd_counter.fetchAdd(1, .monotonic)}) catch ""; + + // Using huge pages was slower. + const fd = switch (bun.sys.memfd_create(label, std.os.linux.MFD.CLOEXEC)) { + .err => |err| return .{ .err = bun.sys.Error.fromCode(err.getErrno(), .open) }, + .result => |fd| fd, + }; + + if (bytes.len > 0) + // Hint at the size of the file + _ = bun.sys.ftruncate(fd, @intCast(bytes.len)); + + // Dump all the bytes in there + var written: isize = 0; + + var remain = bytes; + while (remain.len > 0) { + switch (bun.sys.pwrite(fd, remain, written)) { + .err => |err| { + if (err.getErrno() == .AGAIN) { + continue; + } + + bun.Output.debugWarn("Failed to write to memfd: {}", .{err}); + fd.close(); + return .{ .err = err }; + }, + .result => |result| { + if (result == 0) { + bun.Output.debugWarn("Failed to write to memfd: EOF", .{}); + fd.close(); + return .{ .err = bun.sys.Error.fromCode(.NOMEM, .write) }; + } + written += @intCast(result); + remain = remain[result..]; + }, + } + } + + var linux_memfd_allocator = Self.new(.{ + .fd = fd, + .ref_count = .init(), + .size = bytes.len, + }); + + switch (linux_memfd_allocator.alloc(bytes.len, 0, .{ .TYPE = .SHARED })) { + .result => |res| { + return .{ .result = res }; + }, + .err => |err| { + linux_memfd_allocator.deref(); + return .{ .err = err }; + }, + } +} + +const bun = @import("bun"); +const std = @import("std"); diff --git a/src/allocators/MaxHeapAllocator.zig b/src/allocators/MaxHeapAllocator.zig new file mode 100644 index 0000000000..3ec22f120c --- /dev/null +++ b/src/allocators/MaxHeapAllocator.zig @@ -0,0 +1,54 @@ +//! Single allocation only. + +const Self = @This(); + +array_list: std.ArrayListAligned(u8, @alignOf(std.c.max_align_t)), + +fn alloc(ptr: *anyopaque, len: usize, alignment: std.mem.Alignment, _: usize) ?[*]u8 { + bun.assert(alignment.toByteUnits() <= @alignOf(std.c.max_align_t)); + var self = bun.cast(*Self, ptr); + self.array_list.items.len = 0; + self.array_list.ensureTotalCapacity(len) catch return null; + self.array_list.items.len = len; + return self.array_list.items.ptr; +} + +fn resize(_: *anyopaque, buf: []u8, _: std.mem.Alignment, new_len: usize, _: usize) bool { + _ = new_len; + _ = buf; + @panic("not implemented"); +} + +fn free( + _: *anyopaque, + _: []u8, + _: std.mem.Alignment, + _: usize, +) void {} + +pub fn reset(self: *Self) void { + self.array_list.items.len = 0; +} + +pub fn deinit(self: *Self) void { + self.array_list.deinit(); +} + +const vtable = std.mem.Allocator.VTable{ + .alloc = &alloc, + .free = &free, + .resize = &resize, + .remap = &std.mem.Allocator.noRemap, +}; + +pub fn init(self: *Self, allocator: std.mem.Allocator) std.mem.Allocator { + self.array_list = .init(allocator); + + return std.mem.Allocator{ + .ptr = self, + .vtable = &vtable, + }; +} + +const bun = @import("bun"); +const std = @import("std"); diff --git a/src/allocators/MimallocArena.zig b/src/allocators/MimallocArena.zig new file mode 100644 index 0000000000..0432a29d4b --- /dev/null +++ b/src/allocators/MimallocArena.zig @@ -0,0 +1,172 @@ +const Self = @This(); + +heap: ?*mimalloc.Heap = null, + +const log = bun.Output.scoped(.mimalloc, true); + +/// Internally, mimalloc calls mi_heap_get_default() +/// to get the default heap. +/// It uses pthread_getspecific to do that. +/// We can save those extra calls if we just do it once in here +pub fn getThreadlocalDefault() Allocator { + return Allocator{ .ptr = mimalloc.mi_heap_get_default(), .vtable = &c_allocator_vtable }; +} + +pub fn backingAllocator(self: Self) Allocator { + var arena = Self{ .heap = self.heap.?.backing() }; + return arena.allocator(); +} + +pub fn allocator(self: Self) Allocator { + @setRuntimeSafety(false); + return Allocator{ .ptr = self.heap.?, .vtable = &c_allocator_vtable }; +} + +pub fn dumpThreadStats(self: *Self) void { + _ = self; + const dump_fn = struct { + pub fn dump(textZ: [*:0]const u8, _: ?*anyopaque) callconv(.C) void { + const text = bun.span(textZ); + bun.Output.errorWriter().writeAll(text) catch {}; + } + }.dump; + mimalloc.mi_thread_stats_print_out(dump_fn, null); + bun.Output.flush(); +} + +pub fn dumpStats(self: *Self) void { + _ = self; + const dump_fn = struct { + pub fn dump(textZ: [*:0]const u8, _: ?*anyopaque) callconv(.C) void { + const text = bun.span(textZ); + bun.Output.errorWriter().writeAll(text) catch {}; + } + }.dump; + mimalloc.mi_stats_print_out(dump_fn, null); + bun.Output.flush(); +} + +pub fn deinit(self: *Self) void { + mimalloc.mi_heap_destroy(bun.take(&self.heap).?); +} +pub fn init() !Self { + return .{ .heap = mimalloc.mi_heap_new() orelse return error.OutOfMemory }; +} + +pub fn gc(self: Self) void { + mimalloc.mi_heap_collect(self.heap orelse return, false); +} + +pub inline fn helpCatchMemoryIssues(self: Self) void { + if (comptime FeatureFlags.help_catch_memory_issues) { + self.gc(); + bun.mimalloc.mi_collect(false); + } +} + +pub fn ownsPtr(self: Self, ptr: *const anyopaque) bool { + return mimalloc.mi_heap_check_owned(self.heap.?, ptr); +} +pub const supports_posix_memalign = true; + +fn alignedAlloc(heap: *mimalloc.Heap, len: usize, alignment: mem.Alignment) ?[*]u8 { + log("Malloc: {d}\n", .{len}); + + const ptr: ?*anyopaque = if (mimalloc.canUseAlignedAlloc(len, alignment.toByteUnits())) + mimalloc.mi_heap_malloc_aligned(heap, len, alignment.toByteUnits()) + else + mimalloc.mi_heap_malloc(heap, len); + + if (comptime Environment.isDebug) { + const usable = mimalloc.mi_malloc_usable_size(ptr); + if (usable < len) { + std.debug.panic("mimalloc: allocated size is too small: {d} < {d}", .{ usable, len }); + } + } + + return if (ptr) |p| + @as([*]u8, @ptrCast(p)) + else + null; +} + +fn alignedAllocSize(ptr: [*]u8) usize { + return mimalloc.mi_malloc_usable_size(ptr); +} + +fn alloc(arena: *anyopaque, len: usize, alignment: mem.Alignment, _: usize) ?[*]u8 { + const self = bun.cast(*mimalloc.Heap, arena); + + return alignedAlloc( + self, + len, + alignment, + ); +} + +fn resize(_: *anyopaque, buf: []u8, _: mem.Alignment, new_len: usize, _: usize) bool { + return mimalloc.mi_expand(buf.ptr, new_len) != null; +} + +fn free( + _: *anyopaque, + buf: []u8, + alignment: mem.Alignment, + _: usize, +) void { + // mi_free_size internally just asserts the size + // so it's faster if we don't pass that value through + // but its good to have that assertion + if (comptime Environment.isDebug) { + assert(mimalloc.mi_is_in_heap_region(buf.ptr)); + if (mimalloc.canUseAlignedAlloc(buf.len, alignment.toByteUnits())) + mimalloc.mi_free_size_aligned(buf.ptr, buf.len, alignment.toByteUnits()) + else + mimalloc.mi_free_size(buf.ptr, buf.len); + } else { + mimalloc.mi_free(buf.ptr); + } +} + +/// Attempt to expand or shrink memory, allowing relocation. +/// +/// `memory.len` must equal the length requested from the most recent +/// successful call to `alloc`, `resize`, or `remap`. `alignment` must +/// equal the same value that was passed as the `alignment` parameter to +/// the original `alloc` call. +/// +/// A non-`null` return value indicates the resize was successful. The +/// allocation may have same address, or may have been relocated. In either +/// case, the allocation now has size of `new_len`. A `null` return value +/// indicates that the resize would be equivalent to allocating new memory, +/// copying the bytes from the old memory, and then freeing the old memory. +/// In such case, it is more efficient for the caller to perform the copy. +/// +/// `new_len` must be greater than zero. +/// +/// `ret_addr` is optionally provided as the first return address of the +/// allocation call stack. If the value is `0` it means no return address +/// has been provided. +fn remap(self: *anyopaque, buf: []u8, alignment: mem.Alignment, new_len: usize, _: usize) ?[*]u8 { + const aligned_size = alignment.toByteUnits(); + const value = mimalloc.mi_heap_realloc_aligned(@ptrCast(self), buf.ptr, new_len, aligned_size); + return @ptrCast(value); +} + +const c_allocator_vtable = Allocator.VTable{ + .alloc = &Self.alloc, + .resize = &Self.resize, + .remap = &Self.remap, + .free = &Self.free, +}; + +const Environment = @import("../env.zig"); +const FeatureFlags = @import("../feature_flags.zig"); +const std = @import("std"); + +const bun = @import("bun"); +const assert = bun.assert; +const mimalloc = bun.mimalloc; + +const mem = std.mem; +const Allocator = mem.Allocator; diff --git a/src/allocators/memory_allocator.zig b/src/allocators/basic.zig similarity index 99% rename from src/allocators/memory_allocator.zig rename to src/allocators/basic.zig index 89bd9d98c5..44a4b99998 100644 --- a/src/allocators/memory_allocator.zig +++ b/src/allocators/basic.zig @@ -145,11 +145,11 @@ const z_allocator_vtable = Allocator.VTable{ }; const Environment = @import("../env.zig"); -const mimalloc = @import("./mimalloc.zig"); const std = @import("std"); const bun = @import("bun"); const assert = bun.assert; +const mimalloc = bun.mimalloc; const mem = @import("std").mem; const Allocator = mem.Allocator; diff --git a/src/allocators/linux_memfd_allocator.zig b/src/allocators/linux_memfd_allocator.zig deleted file mode 100644 index 1f30f92bf9..0000000000 --- a/src/allocators/linux_memfd_allocator.zig +++ /dev/null @@ -1,187 +0,0 @@ -/// When cloning large amounts of data potentially multiple times, we can -/// leverage copy-on-write memory to avoid actually copying the data. To do that -/// on Linux, we need to use a memfd, which is a Linux-specific feature. -/// -/// The steps are roughly: -/// -/// 1. Create a memfd -/// 2. Write the data to the memfd -/// 3. Map the memfd into memory -/// -/// Then, to clone the data later, we can just call `mmap` again. -/// -/// The big catch is that mmap(), memfd_create(), write() all have overhead. And -/// often we will re-use virtual memory within the process. This does not reuse -/// the virtual memory. So we should only really use this for large blobs of -/// data that we expect to be cloned multiple times. Such as Blob in FormData. -pub const LinuxMemFdAllocator = struct { - const RefCount = bun.ptr.ThreadSafeRefCount(@This(), "ref_count", deinit, .{}); - pub const new = bun.TrivialNew(@This()); - pub const ref = RefCount.ref; - pub const deref = RefCount.deref; - - ref_count: RefCount, - fd: bun.FileDescriptor = .invalid, - size: usize = 0, - - var memfd_counter = std.atomic.Value(usize).init(0); - - fn deinit(this: *LinuxMemFdAllocator) void { - this.fd.close(); - bun.destroy(this); - } - - pub fn allocator(this: *LinuxMemFdAllocator) std.mem.Allocator { - return .{ - .ptr = this, - .vtable = AllocatorInterface.VTable, - }; - } - - pub fn from(allocator_: std.mem.Allocator) ?*LinuxMemFdAllocator { - if (allocator_.vtable == AllocatorInterface.VTable) { - return @alignCast(@ptrCast(allocator_.ptr)); - } - - return null; - } - - const AllocatorInterface = struct { - fn alloc(_: *anyopaque, _: usize, _: std.mem.Alignment, _: usize) ?[*]u8 { - // it should perform no allocations or resizes - return null; - } - - fn free( - ptr: *anyopaque, - buf: []u8, - _: std.mem.Alignment, - _: usize, - ) void { - var this: *LinuxMemFdAllocator = @alignCast(@ptrCast(ptr)); - defer this.deref(); - bun.sys.munmap(@alignCast(@ptrCast(buf))).unwrap() catch |err| { - bun.Output.debugWarn("Failed to munmap memfd: {}", .{err}); - }; - } - - pub const VTable = &std.mem.Allocator.VTable{ - .alloc = &AllocatorInterface.alloc, - .resize = &std.mem.Allocator.noResize, - .remap = &std.mem.Allocator.noRemap, - .free = &free, - }; - }; - - pub fn alloc(this: *LinuxMemFdAllocator, len: usize, offset: usize, flags: std.posix.MAP) bun.JSC.Maybe(bun.webcore.Blob.Store.Bytes) { - var size = len; - - // size rounded up to nearest page - size = std.mem.alignForward(usize, size, std.heap.pageSize()); - - var flags_mut = flags; - flags_mut.TYPE = .SHARED; - - switch (bun.sys.mmap( - null, - @min(size, this.size), - std.posix.PROT.READ | std.posix.PROT.WRITE, - flags_mut, - this.fd, - offset, - )) { - .result => |slice| { - return .{ - .result = bun.webcore.Blob.Store.Bytes{ - .cap = @truncate(slice.len), - .ptr = slice.ptr, - .len = @truncate(len), - .allocator = this.allocator(), - }, - }; - }, - .err => |errno| { - return .{ .err = errno }; - }, - } - } - - pub fn shouldUse(bytes: []const u8) bool { - if (comptime !bun.Environment.isLinux) { - return false; - } - - if (bun.JSC.VirtualMachine.is_smol_mode) { - return bytes.len >= 1024 * 1024 * 1; - } - - // This is a net 2x - 4x slowdown to new Blob([huge]) - // so we must be careful - return bytes.len >= 1024 * 1024 * 8; - } - - pub fn create(bytes: []const u8) bun.JSC.Maybe(bun.webcore.Blob.Store.Bytes) { - if (comptime !bun.Environment.isLinux) { - unreachable; - } - - var label_buf: [128]u8 = undefined; - const label = std.fmt.bufPrintZ(&label_buf, "memfd-num-{d}", .{memfd_counter.fetchAdd(1, .monotonic)}) catch ""; - - // Using huge pages was slower. - const fd = switch (bun.sys.memfd_create(label, std.os.linux.MFD.CLOEXEC)) { - .err => |err| return .{ .err = bun.sys.Error.fromCode(err.getErrno(), .open) }, - .result => |fd| fd, - }; - - if (bytes.len > 0) - // Hint at the size of the file - _ = bun.sys.ftruncate(fd, @intCast(bytes.len)); - - // Dump all the bytes in there - var written: isize = 0; - - var remain = bytes; - while (remain.len > 0) { - switch (bun.sys.pwrite(fd, remain, written)) { - .err => |err| { - if (err.getErrno() == .AGAIN) { - continue; - } - - bun.Output.debugWarn("Failed to write to memfd: {}", .{err}); - fd.close(); - return .{ .err = err }; - }, - .result => |result| { - if (result == 0) { - bun.Output.debugWarn("Failed to write to memfd: EOF", .{}); - fd.close(); - return .{ .err = bun.sys.Error.fromCode(.NOMEM, .write) }; - } - written += @intCast(result); - remain = remain[result..]; - }, - } - } - - var linux_memfd_allocator = LinuxMemFdAllocator.new(.{ - .fd = fd, - .ref_count = .init(), - .size = bytes.len, - }); - - switch (linux_memfd_allocator.alloc(bytes.len, 0, .{ .TYPE = .SHARED })) { - .result => |res| { - return .{ .result = res }; - }, - .err => |err| { - linux_memfd_allocator.deref(); - return .{ .err = err }; - }, - } - } -}; - -const bun = @import("bun"); -const std = @import("std"); diff --git a/src/allocators/max_heap_allocator.zig b/src/allocators/max_heap_allocator.zig deleted file mode 100644 index 8a22197f0b..0000000000 --- a/src/allocators/max_heap_allocator.zig +++ /dev/null @@ -1,53 +0,0 @@ -/// Single allocation only. -/// -pub const MaxHeapAllocator = struct { - array_list: std.ArrayListAligned(u8, @alignOf(std.c.max_align_t)), - - fn alloc(ptr: *anyopaque, len: usize, alignment: std.mem.Alignment, _: usize) ?[*]u8 { - bun.assert(alignment.toByteUnits() <= @alignOf(std.c.max_align_t)); - var this = bun.cast(*MaxHeapAllocator, ptr); - this.array_list.items.len = 0; - this.array_list.ensureTotalCapacity(len) catch return null; - this.array_list.items.len = len; - return this.array_list.items.ptr; - } - - fn resize(_: *anyopaque, buf: []u8, _: std.mem.Alignment, new_len: usize, _: usize) bool { - _ = new_len; - _ = buf; - @panic("not implemented"); - } - - fn free( - _: *anyopaque, - _: []u8, - _: std.mem.Alignment, - _: usize, - ) void {} - - pub fn reset(this: *MaxHeapAllocator) void { - this.array_list.items.len = 0; - } - - pub fn deinit(this: *MaxHeapAllocator) void { - this.array_list.deinit(); - } - - const vtable = std.mem.Allocator.VTable{ - .alloc = &alloc, - .free = &free, - .resize = &resize, - .remap = &std.mem.Allocator.noRemap, - }; - pub fn init(this: *MaxHeapAllocator, allocator: std.mem.Allocator) std.mem.Allocator { - this.array_list = .init(allocator); - - return std.mem.Allocator{ - .ptr = this, - .vtable = &vtable, - }; - } -}; - -const bun = @import("bun"); -const std = @import("std"); diff --git a/src/allocators/mimalloc_arena.zig b/src/allocators/mimalloc_arena.zig deleted file mode 100644 index 52aab6800c..0000000000 --- a/src/allocators/mimalloc_arena.zig +++ /dev/null @@ -1,171 +0,0 @@ -const log = bun.Output.scoped(.mimalloc, true); - -pub const Arena = struct { - heap: ?*mimalloc.Heap = null, - - /// Internally, mimalloc calls mi_heap_get_default() - /// to get the default heap. - /// It uses pthread_getspecific to do that. - /// We can save those extra calls if we just do it once in here - pub fn getThreadlocalDefault() Allocator { - return Allocator{ .ptr = mimalloc.mi_heap_get_default(), .vtable = &c_allocator_vtable }; - } - - pub fn backingAllocator(this: Arena) Allocator { - var arena = Arena{ .heap = this.heap.?.backing() }; - return arena.allocator(); - } - - pub fn allocator(this: Arena) Allocator { - @setRuntimeSafety(false); - return Allocator{ .ptr = this.heap.?, .vtable = &c_allocator_vtable }; - } - - pub fn dumpThreadStats(_: *Arena) void { - const dump_fn = struct { - pub fn dump(textZ: [*:0]const u8, _: ?*anyopaque) callconv(.C) void { - const text = bun.span(textZ); - bun.Output.errorWriter().writeAll(text) catch {}; - } - }.dump; - mimalloc.mi_thread_stats_print_out(dump_fn, null); - bun.Output.flush(); - } - - pub fn dumpStats(_: *Arena) void { - const dump_fn = struct { - pub fn dump(textZ: [*:0]const u8, _: ?*anyopaque) callconv(.C) void { - const text = bun.span(textZ); - bun.Output.errorWriter().writeAll(text) catch {}; - } - }.dump; - mimalloc.mi_stats_print_out(dump_fn, null); - bun.Output.flush(); - } - - pub fn deinit(this: *Arena) void { - mimalloc.mi_heap_destroy(bun.take(&this.heap).?); - } - pub fn init() !Arena { - const arena = Arena{ .heap = mimalloc.mi_heap_new() orelse return error.OutOfMemory }; - return arena; - } - - pub fn gc(this: Arena) void { - mimalloc.mi_heap_collect(this.heap orelse return, false); - } - - pub inline fn helpCatchMemoryIssues(this: Arena) void { - if (comptime FeatureFlags.help_catch_memory_issues) { - this.gc(); - bun.Mimalloc.mi_collect(false); - } - } - - pub fn ownsPtr(this: Arena, ptr: *const anyopaque) bool { - return mimalloc.mi_heap_check_owned(this.heap.?, ptr); - } - pub const supports_posix_memalign = true; - - fn alignedAlloc(heap: *mimalloc.Heap, len: usize, alignment: mem.Alignment) ?[*]u8 { - log("Malloc: {d}\n", .{len}); - - const ptr: ?*anyopaque = if (mimalloc.canUseAlignedAlloc(len, alignment.toByteUnits())) - mimalloc.mi_heap_malloc_aligned(heap, len, alignment.toByteUnits()) - else - mimalloc.mi_heap_malloc(heap, len); - - if (comptime Environment.isDebug) { - const usable = mimalloc.mi_malloc_usable_size(ptr); - if (usable < len) { - std.debug.panic("mimalloc: allocated size is too small: {d} < {d}", .{ usable, len }); - } - } - - return if (ptr) |p| - @as([*]u8, @ptrCast(p)) - else - null; - } - - fn alignedAllocSize(ptr: [*]u8) usize { - return mimalloc.mi_malloc_usable_size(ptr); - } - - fn alloc(arena: *anyopaque, len: usize, alignment: mem.Alignment, _: usize) ?[*]u8 { - const this = bun.cast(*mimalloc.Heap, arena); - - return alignedAlloc( - this, - len, - alignment, - ); - } - - fn resize(_: *anyopaque, buf: []u8, _: mem.Alignment, new_len: usize, _: usize) bool { - return mimalloc.mi_expand(buf.ptr, new_len) != null; - } - - fn free( - _: *anyopaque, - buf: []u8, - alignment: mem.Alignment, - _: usize, - ) void { - // mi_free_size internally just asserts the size - // so it's faster if we don't pass that value through - // but its good to have that assertion - if (comptime Environment.isDebug) { - assert(mimalloc.mi_is_in_heap_region(buf.ptr)); - if (mimalloc.canUseAlignedAlloc(buf.len, alignment.toByteUnits())) - mimalloc.mi_free_size_aligned(buf.ptr, buf.len, alignment.toByteUnits()) - else - mimalloc.mi_free_size(buf.ptr, buf.len); - } else { - mimalloc.mi_free(buf.ptr); - } - } - - /// Attempt to expand or shrink memory, allowing relocation. - /// - /// `memory.len` must equal the length requested from the most recent - /// successful call to `alloc`, `resize`, or `remap`. `alignment` must - /// equal the same value that was passed as the `alignment` parameter to - /// the original `alloc` call. - /// - /// A non-`null` return value indicates the resize was successful. The - /// allocation may have same address, or may have been relocated. In either - /// case, the allocation now has size of `new_len`. A `null` return value - /// indicates that the resize would be equivalent to allocating new memory, - /// copying the bytes from the old memory, and then freeing the old memory. - /// In such case, it is more efficient for the caller to perform the copy. - /// - /// `new_len` must be greater than zero. - /// - /// `ret_addr` is optionally provided as the first return address of the - /// allocation call stack. If the value is `0` it means no return address - /// has been provided. - fn remap(this: *anyopaque, buf: []u8, alignment: mem.Alignment, new_len: usize, _: usize) ?[*]u8 { - const aligned_size = alignment.toByteUnits(); - const value = mimalloc.mi_heap_realloc_aligned(@ptrCast(this), buf.ptr, new_len, aligned_size); - return @ptrCast(value); - } -}; - -const c_allocator_vtable = Allocator.VTable{ - .alloc = &Arena.alloc, - .resize = &Arena.resize, - .remap = &Arena.remap, - .free = &Arena.free, -}; - -const Environment = @import("../env.zig"); -const FeatureFlags = @import("../feature_flags.zig"); -const mimalloc = @import("./mimalloc.zig"); -const std = @import("std"); - -const bun = @import("bun"); -const assert = bun.assert; - -const mem = @import("std").mem; -const Allocator = mem.Allocator; diff --git a/src/analytics/analytics_thread.zig b/src/analytics.zig similarity index 95% rename from src/analytics/analytics_thread.zig rename to src/analytics.zig index c56221a742..2be3b4872d 100644 --- a/src/analytics/analytics_thread.zig +++ b/src/analytics.zig @@ -254,7 +254,7 @@ pub const EventName = enum(u8) { var random: std.rand.DefaultPrng = undefined; -const platform_arch = if (Environment.isAarch64) Analytics.Architecture.arm else Analytics.Architecture.x64; +const platform_arch = if (Environment.isAarch64) analytics.Architecture.arm else analytics.Architecture.x64; // TODO: move this code somewhere more appropriate, and remove it from "analytics" // The following code is not currently even used for analytics, just feature-detection @@ -262,10 +262,10 @@ const platform_arch = if (Environment.isAarch64) Analytics.Architecture.arm else pub const GenerateHeader = struct { pub const GeneratePlatform = struct { var osversion_name: [32]u8 = undefined; - fn forMac() Analytics.Platform { + fn forMac() analytics.Platform { @memset(&osversion_name, 0); - var platform = Analytics.Platform{ .os = Analytics.OperatingSystem.macos, .version = &[_]u8{}, .arch = platform_arch }; + var platform = analytics.Platform{ .os = analytics.OperatingSystem.macos, .version = &[_]u8{}, .arch = platform_arch }; var len = osversion_name.len - 1; // this previously used "kern.osrelease", which was the darwin xnu kernel version // That is less useful than "kern.osproductversion", which is the macOS version @@ -276,8 +276,8 @@ pub const GenerateHeader = struct { } pub var linux_os_name: std.c.utsname = undefined; - var platform_: Analytics.Platform = undefined; - pub const Platform = Analytics.Platform; + var platform_: analytics.Platform = undefined; + pub const Platform = analytics.Platform; var linux_kernel_version: Semver.Version = undefined; var run_once = std.once(struct { fn run() void { @@ -292,7 +292,7 @@ pub const GenerateHeader = struct { linux_kernel_version = result.version.min(); } else if (Environment.isWindows) { platform_ = Platform{ - .os = Analytics.OperatingSystem.windows, + .os = analytics.OperatingSystem.windows, .version = &[_]u8{}, .arch = platform_arch, }; @@ -300,7 +300,7 @@ pub const GenerateHeader = struct { } }.run); - pub fn forOS() Analytics.Platform { + pub fn forOS() analytics.Platform { run_once.call(); return platform_; } @@ -350,7 +350,7 @@ pub const GenerateHeader = struct { }; } - fn forLinux() Analytics.Platform { + fn forLinux() analytics.Platform { linux_os_name = std.mem.zeroes(@TypeOf(linux_os_name)); _ = std.c.uname(&linux_os_name); @@ -360,16 +360,16 @@ pub const GenerateHeader = struct { // Linux DESKTOP-P4LCIEM 5.10.16.3-microsoft-standard-WSL2 #1 SMP Fri Apr 2 22:23:49 UTC 2021 x86_64 x86_64 x86_64 GNU/Linux if (std.mem.indexOf(u8, release, "microsoft") != null) { - return Analytics.Platform{ .os = Analytics.OperatingSystem.wsl, .version = release, .arch = platform_arch }; + return analytics.Platform{ .os = analytics.OperatingSystem.wsl, .version = release, .arch = platform_arch }; } - return Analytics.Platform{ .os = Analytics.OperatingSystem.linux, .version = release, .arch = platform_arch }; + return analytics.Platform{ .os = analytics.OperatingSystem.linux, .version = release, .arch = platform_arch }; } }; }; const std = @import("std"); -const Analytics = @import("./analytics_schema.zig").analytics; +const analytics = @import("./analytics/schema.zig").analytics; const bun = @import("bun"); const Environment = bun.Environment; diff --git a/src/analytics/analytics_schema.zig b/src/analytics/schema.zig similarity index 100% rename from src/analytics/analytics_schema.zig rename to src/analytics/schema.zig diff --git a/src/api/schema.peechy b/src/api/schema.peechy index bc048e5078..14338e3d66 100644 --- a/src/api/schema.peechy +++ b/src/api/schema.peechy @@ -1,4 +1,4 @@ -package Api; +package api; smol Loader { jsx = 1; @@ -64,7 +64,7 @@ struct StackTrace { message JSException { string name = 1; string message = 2; - + uint16 runtime_type = 3; uint8 code = 4; @@ -103,7 +103,7 @@ message FallbackMessageContainer { Problems problems = 4; string cwd = 5; } - + smol ResolveMode { disable = 1; @@ -178,18 +178,18 @@ struct JavascriptBundle { // These are sorted alphabetically so you can do binary search JavascriptBundledModule[] modules; JavascriptBundledPackage[] packages; - + // This is ASCII-encoded so you can send it directly over HTTP byte[] etag; uint32 generated_at; - + // generated by hashing all ${name}@${version} in sorted order byte[] app_package_json_dependencies_hash; byte[] import_from_name; - // This is what StringPointer refers to + // This is what StringPointer refers to byte[] manifest_string; } @@ -359,7 +359,7 @@ smol SourceMapMode { struct FileHandle { string path; uint size; - uint fd; + uint fd; } message Transform { @@ -462,7 +462,7 @@ struct Log { smol Reloader { disable = 1; - // equivalent of CMD + R + // equivalent of CMD + R live = 2; // React Fast Refresh fast_refresh = 3; @@ -534,7 +534,7 @@ struct WebsocketMessageBuildSuccess { Loader loader; string module_path; - + // This is the length of the blob that immediately follows this message. uint32 blob_length; } @@ -630,4 +630,4 @@ struct TestResponseItem { struct GetTestsResponse { TestResponseItem[] tests; byte[] contents; -} \ No newline at end of file +} diff --git a/src/api/schema.zig b/src/api/schema.zig index 3916d18de5..fffa54a0cb 100644 --- a/src/api/schema.zig +++ b/src/api/schema.zig @@ -320,7 +320,7 @@ pub fn Writer(comptime WritableStream: type) type { pub const ByteWriter = Writer(*std.io.FixedBufferStream([]u8)); pub const FileWriter = Writer(std.fs.File); -pub const Api = struct { +pub const api = struct { pub const Loader = enum(u8) { _none, jsx, @@ -421,7 +421,7 @@ pub const Api = struct { } }; - pub const StackFramePosition = bun.JSC.ZigStackFramePosition; + pub const StackFramePosition = bun.jsc.ZigStackFramePosition; pub const SourceLine = struct { /// line @@ -1951,7 +1951,7 @@ pub const Api = struct { _, - pub fn fromJS(global: *bun.JSC.JSGlobalObject, value: bun.JSC.JSValue) bun.JSError!?SourceMapMode { + pub fn fromJS(global: *bun.jsc.JSGlobalObject, value: bun.jsc.JSValue) bun.JSError!?SourceMapMode { if (value.isString()) { const str = try value.toSliceOrNull(global); defer str.deinit(); @@ -2875,13 +2875,13 @@ pub const Api = struct { } } - pub fn parseRegistryURLString(this: *Parser, str: *js_ast.E.String) OOM!Api.NpmRegistry { + pub fn parseRegistryURLString(this: *Parser, str: *js_ast.E.String) OOM!api.NpmRegistry { return try this.parseRegistryURLStringImpl(str.data); } - pub fn parseRegistryURLStringImpl(this: *Parser, str: []const u8) OOM!Api.NpmRegistry { + pub fn parseRegistryURLStringImpl(this: *Parser, str: []const u8) OOM!api.NpmRegistry { const url = bun.URL.parse(str); - var registry = std.mem.zeroes(Api.NpmRegistry); + var registry = std.mem.zeroes(api.NpmRegistry); // Token if (url.username.len == 0 and url.password.len > 0) { @@ -2900,8 +2900,8 @@ pub const Api = struct { return registry; } - fn parseRegistryObject(this: *Parser, obj: *js_ast.E.Object) !Api.NpmRegistry { - var registry = std.mem.zeroes(Api.NpmRegistry); + fn parseRegistryObject(this: *Parser, obj: *js_ast.E.Object) !api.NpmRegistry { + var registry = std.mem.zeroes(api.NpmRegistry); if (obj.get("url")) |url| { try this.expectString(url); @@ -2928,7 +2928,7 @@ pub const Api = struct { return registry; } - pub fn parseRegistry(this: *Parser, expr: js_ast.Expr) !Api.NpmRegistry { + pub fn parseRegistry(this: *Parser, expr: js_ast.Expr) !api.NpmRegistry { switch (expr.data) { .e_string => |str| { return this.parseRegistryURLString(str); @@ -2938,7 +2938,7 @@ pub const Api = struct { }, else => { try this.addError(expr.loc, "Expected registry to be a URL string or an object"); - return std.mem.zeroes(Api.NpmRegistry); + return std.mem.zeroes(api.NpmRegistry); }, } } @@ -3370,4 +3370,4 @@ const std = @import("std"); const bun = @import("bun"); const OOM = bun.OOM; -const js_ast = bun.JSAst; +const js_ast = bun.ast; diff --git a/src/js_ast.zig b/src/ast.zig similarity index 99% rename from src/js_ast.zig rename to src/ast.zig index 89883b80b5..d51e38b335 100644 --- a/src/js_ast.zig +++ b/src/ast.zig @@ -681,10 +681,13 @@ pub const TSNamespaceScope = TS.TSNamespaceScope; pub const Index = @import("./ast/base.zig").Index; pub const Ref = @import("./ast/base.zig").Ref; +pub const RefCtx = @import("./ast/base.zig").RefCtx; pub const RefHashCtx = @import("./ast/base.zig").RefHashCtx; pub const BabyList = bun.BabyList; +const string = []const u8; + const std = @import("std"); const TypeScript = @import("./js_parser.zig").TypeScript; @@ -692,5 +695,4 @@ const bun = @import("bun"); const Environment = bun.Environment; const Output = bun.Output; const logger = bun.logger; -const string = bun.string; const strings = bun.strings; diff --git a/src/ast/ASTMemoryAllocator.zig b/src/ast/ASTMemoryAllocator.zig index 09e5f1ea59..aef846f05c 100644 --- a/src/ast/ASTMemoryAllocator.zig +++ b/src/ast/ASTMemoryAllocator.zig @@ -88,7 +88,7 @@ pub fn initWithoutStack(this: *ASTMemoryAllocator, arena: std.mem.Allocator) voi const bun = @import("bun"); const std = @import("std"); -const js_ast = bun.js_ast; +const js_ast = bun.ast; const ASTMemoryAllocator = js_ast.ASTMemoryAllocator; const Expr = js_ast.Expr; const Stmt = js_ast.Stmt; diff --git a/src/ast/Ast.zig b/src/ast/Ast.zig index a266ded95f..9f619e4a60 100644 --- a/src/ast/Ast.zig +++ b/src/ast/Ast.zig @@ -114,6 +114,8 @@ pub fn deinit(this: *Ast) void { pub const Class = G.Class; +const string = []const u8; + const std = @import("std"); const Runtime = @import("../runtime.zig").Runtime; @@ -121,9 +123,8 @@ const bun = @import("bun"); const BabyList = bun.BabyList; const ImportRecord = bun.ImportRecord; const logger = bun.logger; -const string = bun.string; -const js_ast = bun.js_ast; +const js_ast = bun.ast; const Ast = js_ast.Ast; const CharFreq = js_ast.CharFreq; const ExportsKind = js_ast.ExportsKind; diff --git a/src/ast/B.zig b/src/ast/B.zig index 9a531326e7..d31d90be51 100644 --- a/src/ast/B.zig +++ b/src/ast/B.zig @@ -94,7 +94,7 @@ const std = @import("std"); const bun = @import("bun"); const writeAnyToHasher = bun.writeAnyToHasher; -const js_ast = bun.js_ast; +const js_ast = bun.ast; const ArrayBinding = js_ast.ArrayBinding; const Binding = js_ast.Binding; const Expr = js_ast.Expr; diff --git a/src/ast/Binding.zig b/src/ast/Binding.zig index 00afdba64d..1b484725c7 100644 --- a/src/ast/Binding.zig +++ b/src/ast/Binding.zig @@ -147,13 +147,14 @@ pub fn alloc(allocator: std.mem.Allocator, t: anytype, loc: logger.Loc) Binding } } +const string = []const u8; + const std = @import("std"); const bun = @import("bun"); const logger = bun.logger; -const string = bun.string; -const js_ast = bun.js_ast; +const js_ast = bun.ast; const B = js_ast.B; const Binding = js_ast.Binding; const E = js_ast.E; diff --git a/src/ast/BundledAst.zig b/src/ast/BundledAst.zig index 76a209cae2..340e57ba3a 100644 --- a/src/ast/BundledAst.zig +++ b/src/ast/BundledAst.zig @@ -207,16 +207,17 @@ pub const NamedExports = Ast.NamedExports; pub const NamedImports = Ast.NamedImports; pub const TopLevelSymbolToParts = Ast.TopLevelSymbolToParts; +const string = []const u8; + const std = @import("std"); const bun = @import("bun"); const ImportRecord = bun.ImportRecord; const logger = bun.logger; -const string = bun.string; const strings = bun.strings; const MimeType = bun.http.MimeType; -const js_ast = bun.js_ast; +const js_ast = bun.ast; const Ast = js_ast.Ast; const BundledAst = js_ast.BundledAst; const CharFreq = js_ast.CharFreq; diff --git a/src/ast/CharFreq.zig b/src/ast/CharFreq.zig index 7d80de0026..815450f4db 100644 --- a/src/ast/CharFreq.zig +++ b/src/ast/CharFreq.zig @@ -126,12 +126,12 @@ pub fn compile(this: *const CharFreq, allocator: std.mem.Allocator) NameMinifier pub const Class = G.Class; -const std = @import("std"); +const string = []const u8; const bun = @import("bun"); -const string = bun.string; +const std = @import("std"); -const js_ast = bun.js_ast; +const js_ast = bun.ast; const CharFreq = js_ast.CharFreq; const G = js_ast.G; const NameMinifier = js_ast.NameMinifier; diff --git a/src/ast/E.zig b/src/ast/E.zig index aa631d7960..0f7c94089a 100644 --- a/src/ast/E.zig +++ b/src/ast/E.zig @@ -66,9 +66,9 @@ pub const Array = struct { return ExprNodeList.init(out[0 .. out.len - remain.len]); } - pub fn toJS(this: @This(), allocator: std.mem.Allocator, globalObject: *JSC.JSGlobalObject) ToJSError!JSC.JSValue { + pub fn toJS(this: @This(), allocator: std.mem.Allocator, globalObject: *jsc.JSGlobalObject) ToJSError!jsc.JSValue { const items = this.items.slice(); - var array = try JSC.JSValue.createEmptyArray(globalObject, items.len); + var array = try jsc.JSValue.createEmptyArray(globalObject, items.len); array.protect(); defer array.unprotect(); for (items, 0..) |expr, j| { @@ -108,8 +108,8 @@ pub const Binary = struct { pub const Boolean = struct { value: bool, - pub fn toJS(this: @This(), ctx: *JSC.JSGlobalObject) JSC.C.JSValueRef { - return JSC.C.JSValueMakeBoolean(ctx, this.value); + pub fn toJS(this: @This(), ctx: *jsc.JSGlobalObject) jsc.C.JSValueRef { + return jsc.C.JSValueMakeBoolean(ctx, this.value); } }; pub const Super = struct {}; @@ -466,8 +466,8 @@ pub const Number = struct { return try writer.write(self.value); } - pub fn toJS(this: @This()) JSC.JSValue { - return JSC.JSValue.jsNumber(this.value); + pub fn toJS(this: @This()) jsc.JSValue { + return jsc.JSValue.jsNumber(this.value); } }; @@ -480,9 +480,9 @@ pub const BigInt = struct { return try writer.write(self.value); } - pub fn toJS(_: @This()) JSC.JSValue { + pub fn toJS(_: @This()) jsc.JSValue { // TODO: - return JSC.JSValue.jsNumber(0); + return jsc.JSValue.jsNumber(0); } }; @@ -515,8 +515,8 @@ pub const Object = struct { return if (asProperty(self, key)) |query| query.expr else @as(?Expr, null); } - pub fn toJS(this: *Object, allocator: std.mem.Allocator, globalObject: *JSC.JSGlobalObject) ToJSError!JSC.JSValue { - var obj = JSC.JSValue.createEmptyObject(globalObject, this.properties.len); + pub fn toJS(this: *Object, allocator: std.mem.Allocator, globalObject: *jsc.JSGlobalObject) ToJSError!jsc.JSValue { + var obj = jsc.JSValue.createEmptyObject(globalObject, this.properties.len); obj.protect(); defer obj.unprotect(); const props: []const G.Property = this.properties.slice(); @@ -955,7 +955,7 @@ pub const String = struct { }; } - pub fn cloneSliceIfNecessary(str: *const String, allocator: std.mem.Allocator) !bun.string { + pub fn cloneSliceIfNecessary(str: *const String, allocator: std.mem.Allocator) ![]const u8 { if (str.isUTF8()) { return allocator.dupe(u8, str.string(allocator) catch unreachable); } @@ -1005,7 +1005,7 @@ pub const String = struct { return strings.utf16EqlString(other.slice16(), s.data); } }, - bun.string => { + []const u8 => { return strings.eqlLong(s.data, other, true); }, []u16, []const u16 => { @@ -1024,7 +1024,7 @@ pub const String = struct { return std.mem.eql(u16, other.slice16(), s.slice16()); } }, - bun.string => { + []const u8 => { return strings.utf16EqlString(s.slice16(), other); }, []u16, []const u16 => { @@ -1055,7 +1055,7 @@ pub const String = struct { strings.eqlComptimeUTF16(s.slice16()[0..value.len], value); } - pub fn string(s: *const String, allocator: std.mem.Allocator) OOM!bun.string { + pub fn string(s: *const String, allocator: std.mem.Allocator) OOM![]const u8 { if (s.isUTF8()) { return s.data; } else { @@ -1063,7 +1063,7 @@ pub const String = struct { } } - pub fn stringZ(s: *const String, allocator: std.mem.Allocator) OOM!bun.stringZ { + pub fn stringZ(s: *const String, allocator: std.mem.Allocator) OOM![:0]const u8 { if (s.isUTF8()) { return allocator.dupeZ(u8, s.data); } else { @@ -1071,7 +1071,7 @@ pub const String = struct { } } - pub fn stringCloned(s: *const String, allocator: std.mem.Allocator) OOM!bun.string { + pub fn stringCloned(s: *const String, allocator: std.mem.Allocator) OOM![]const u8 { if (s.isUTF8()) { return allocator.dupe(u8, s.data); } else { @@ -1091,7 +1091,7 @@ pub const String = struct { } } - pub fn toJS(s: *String, allocator: std.mem.Allocator, globalObject: *JSC.JSGlobalObject) !JSC.JSValue { + pub fn toJS(s: *String, allocator: std.mem.Allocator, globalObject: *jsc.JSGlobalObject) !jsc.JSValue { s.resolveRopeIfNeeded(allocator); if (!s.isPresent()) { var emp = bun.String.empty; @@ -1115,11 +1115,11 @@ pub const String = struct { } } - pub fn toZigString(s: *String, allocator: std.mem.Allocator) JSC.ZigString { + pub fn toZigString(s: *String, allocator: std.mem.Allocator) jsc.ZigString { if (s.isUTF8()) { - return JSC.ZigString.fromUTF8(s.slice(allocator)); + return jsc.ZigString.fromUTF8(s.slice(allocator)); } else { - return JSC.ZigString.initUTF16(s.slice16()); + return jsc.ZigString.initUTF16(s.slice16()); } } @@ -1418,21 +1418,22 @@ pub const Import = struct { pub const Class = G.Class; +const string = []const u8; +const stringZ = [:0]const u8; + const std = @import("std"); const bun = @import("bun"); const ComptimeStringMap = bun.ComptimeStringMap; const Environment = bun.Environment; const ImportRecord = bun.ImportRecord; -const JSC = bun.JSC; const OOM = bun.OOM; +const jsc = bun.jsc; const logger = bun.logger; -const string = bun.string; -const stringZ = bun.stringZ; const strings = bun.strings; const Loader = bun.options.Loader; -const js_ast = bun.js_ast; +const js_ast = bun.ast; const E = js_ast.E; const Expr = js_ast.Expr; const ExprNodeIndex = js_ast.ExprNodeIndex; diff --git a/src/ast/Expr.zig b/src/ast/Expr.zig index 9382990da1..dba9ac27dd 100644 --- a/src/ast/Expr.zig +++ b/src/ast/Expr.zig @@ -64,7 +64,7 @@ pub fn unwrapInlined(expr: Expr) Expr { } pub fn fromBlob( - blob: *const JSC.WebCore.Blob, + blob: *const jsc.WebCore.Blob, allocator: std.mem.Allocator, mime_type_: ?MimeType, log: *logger.Log, @@ -108,7 +108,7 @@ pub fn fromBlob( return Expr.init( E.String, E.String{ - .data = try JSC.ZigString.init(bytes).toBase64DataURL(allocator), + .data = try jsc.ZigString.init(bytes).toBase64DataURL(allocator), }, loc, ); @@ -147,7 +147,7 @@ pub fn hasAnyPropertyNamed(expr: *const Expr, comptime names: []const string) bo return false; } -pub fn toJS(this: Expr, allocator: std.mem.Allocator, globalObject: *JSC.JSGlobalObject) ToJSError!JSC.JSValue { +pub fn toJS(this: Expr, allocator: std.mem.Allocator, globalObject: *jsc.JSGlobalObject) ToJSError!jsc.JSValue { return this.data.toJS(allocator, globalObject); } @@ -3072,17 +3072,17 @@ pub const Data = union(Tag) { return Equality.unknown; } - pub fn toJS(this: Data, allocator: std.mem.Allocator, globalObject: *JSC.JSGlobalObject) ToJSError!JSC.JSValue { + pub fn toJS(this: Data, allocator: std.mem.Allocator, globalObject: *jsc.JSGlobalObject) ToJSError!jsc.JSValue { return switch (this) { .e_array => |e| e.toJS(allocator, globalObject), .e_object => |e| e.toJS(allocator, globalObject), .e_string => |e| e.toJS(allocator, globalObject), - .e_null => JSC.JSValue.null, + .e_null => jsc.JSValue.null, .e_undefined => .js_undefined, .e_boolean => |boolean| if (boolean.value) - JSC.JSValue.true + jsc.JSValue.true else - JSC.JSValue.false, + jsc.JSValue.false, .e_number => |e| e.toJS(), // .e_big_int => |e| e.toJS(ctx, exception), @@ -3097,7 +3097,7 @@ pub const Data = union(Tag) { // brk: { // // var node = try allocator.create(Macro.JSNode); // // node.* = Macro.JSNode.initExpr(Expr{ .data = this, .loc = logger.Loc.Empty }); - // // break :brk JSC.JSValue.c(Macro.JSNode.Class.make(globalObject, node)); + // // break :brk jsc.JSValue.c(Macro.JSNode.Class.make(globalObject, node)); // }, else => { @@ -3209,25 +3209,26 @@ fn stringToEquivalentNumberValue(str: []const u8) f64 { return bun.cpp.JSC__jsToNumber(str.ptr, str.len); } +const string = []const u8; +const stringZ = [:0]const u8; + const JSPrinter = @import("../js_printer.zig"); const std = @import("std"); const bun = @import("bun"); const BabyList = bun.BabyList; const Environment = bun.Environment; -const JSC = bun.JSC; -const JSONParser = bun.JSON; +const JSONParser = bun.json; const MutableString = bun.MutableString; const OOM = bun.OOM; const default_allocator = bun.default_allocator; +const jsc = bun.jsc; const logger = bun.logger; -const string = bun.string; -const stringZ = bun.stringZ; const strings = bun.strings; const writeAnyToHasher = bun.writeAnyToHasher; const MimeType = bun.http.MimeType; -const js_ast = bun.js_ast; +const js_ast = bun.ast; const ASTMemoryAllocator = js_ast.ASTMemoryAllocator; const E = js_ast.E; const Expr = js_ast.Expr; diff --git a/src/ast/G.zig b/src/ast/G.zig index 99889cfd94..41f141ef23 100644 --- a/src/ast/G.zig +++ b/src/ast/G.zig @@ -208,15 +208,16 @@ pub const Arg = struct { } }; +const string = []const u8; + const std = @import("std"); const bun = @import("bun"); const BabyList = bun.BabyList; const logger = bun.logger; -const string = bun.string; const TypeScript = bun.js_parser.TypeScript; -const js_ast = bun.js_ast; +const js_ast = bun.ast; const BindingNodeIndex = js_ast.BindingNodeIndex; const Expr = js_ast.Expr; const ExprNodeIndex = js_ast.ExprNodeIndex; diff --git a/src/ast/Macro.zig b/src/ast/Macro.zig index 35c72afccd..b4b3f6dbd4 100644 --- a/src/ast/Macro.zig +++ b/src/ast/Macro.zig @@ -12,7 +12,7 @@ pub const MacroContext = struct { env: *DotEnv.Loader, macros: MacroMap, remap: MacroRemap, - javascript_object: JSC.JSValue = JSC.JSValue.zero, + javascript_object: jsc.JSValue = jsc.JSValue.zero, pub fn getRemap(this: MacroContext, path: string) ?MacroRemapEntry { if (this.remap.entries.len == 0) return null; @@ -51,7 +51,7 @@ pub const MacroContext = struct { bun.assert(!isMacroPath(import_record_path_without_macro_prefix)); const input_specifier = brk: { - if (JSC.ModuleLoader.HardcodedModule.Alias.get(import_record_path, .bun)) |replacement| { + if (jsc.ModuleLoader.HardcodedModule.Alias.get(import_record_path, .bun)) |replacement| { break :brk replacement.path; } @@ -176,7 +176,7 @@ pub fn init( defer resolver.opts.transform_options = old_transform_options; // JSC needs to be initialized if building from CLI - JSC.initialize(false); + jsc.initialize(false); var _vm = try JavaScript.VirtualMachine.init(.{ .allocator = default_allocator, @@ -198,7 +198,7 @@ pub fn init( const loaded_result = try vm.loadMacroEntryPoint(input_specifier, function_name, specifier, hash); - switch (loaded_result.unwrap(vm.jsc, .leave_unhandled)) { + switch (loaded_result.unwrap(vm.jsc_vm, .leave_unhandled)) { .rejected => |result| { vm.unhandledRejection(vm.global, result, loaded_result.asValue()); vm.disableMacroMode(); @@ -214,17 +214,17 @@ pub fn init( } pub const Runner = struct { - const VisitMap = std.AutoHashMapUnmanaged(JSC.JSValue, Expr); + const VisitMap = std.AutoHashMapUnmanaged(jsc.JSValue, Expr); threadlocal var args_buf: [3]js.JSObjectRef = undefined; - threadlocal var exception_holder: JSC.ZigException.Holder = undefined; + threadlocal var exception_holder: jsc.ZigException.Holder = undefined; pub const MacroError = error{ MacroFailed, OutOfMemory } || ToJSError || bun.JSError; pub const Run = struct { caller: Expr, function_name: string, macro: *const Macro, - global: *JSC.JSGlobalObject, + global: *jsc.JSGlobalObject, allocator: std.mem.Allocator, id: i32, log: *logger.Log, @@ -238,7 +238,7 @@ pub const Runner = struct { allocator: std.mem.Allocator, function_name: string, caller: Expr, - args: []JSC.JSValue, + args: []jsc.JSValue, source: *const logger.Source, id: i32, ) MacroError!Expr { @@ -273,9 +273,9 @@ pub const Runner = struct { pub fn run( this: *Run, - value: JSC.JSValue, + value: jsc.JSValue, ) MacroError!Expr { - return switch ((try JSC.ConsoleObject.Formatter.Tag.get(value, this.global)).tag) { + return switch ((try jsc.ConsoleObject.Formatter.Tag.get(value, this.global)).tag) { .Error => this.coerce(value, .Error), .Undefined => this.coerce(value, .Undefined), .Null => this.coerce(value, .Null), @@ -305,8 +305,8 @@ pub const Runner = struct { pub fn coerce( this: *Run, - value: JSC.JSValue, - comptime tag: JSC.ConsoleObject.Formatter.Tag, + value: jsc.JSValue, + comptime tag: jsc.ConsoleObject.Formatter.Tag, ) MacroError!Expr { switch (comptime tag) { .Error => { @@ -325,15 +325,15 @@ pub const Runner = struct { return _entry.value_ptr.*; } - var blob_: ?JSC.WebCore.Blob = null; + var blob_: ?jsc.WebCore.Blob = null; const mime_type: ?MimeType = null; if (value.jsType() == .DOMWrapper) { - if (value.as(JSC.WebCore.Response)) |resp| { + if (value.as(jsc.WebCore.Response)) |resp| { return this.run(try resp.getBlobWithoutCallFrame(this.global)); - } else if (value.as(JSC.WebCore.Request)) |resp| { + } else if (value.as(jsc.WebCore.Request)) |resp| { return this.run(try resp.getBlobWithoutCallFrame(this.global)); - } else if (value.as(JSC.WebCore.Blob)) |resp| { + } else if (value.as(jsc.WebCore.Blob)) |resp| { blob_ = resp.*; blob_.?.allocator = null; } else if (value.as(bun.api.ResolveMessage) != null or value.as(bun.api.BuildMessage) != null) { @@ -366,7 +366,7 @@ pub const Runner = struct { .Boolean => { return Expr{ .data = .{ .e_boolean = .{ .value = value.toBoolean() } }, .loc = this.caller.loc }; }, - JSC.ConsoleObject.Formatter.Tag.Array => { + jsc.ConsoleObject.Formatter.Tag.Array => { this.is_top_level = false; const _entry = this.visited.getOrPut(this.allocator, value) catch unreachable; @@ -381,7 +381,7 @@ pub const Runner = struct { return _entry.value_ptr.*; } - var iter = try JSC.JSArrayIterator.init(value, this.global); + var iter = try jsc.JSArrayIterator.init(value, this.global); if (iter.len == 0) { const result = Expr.init( E.Array, @@ -418,7 +418,7 @@ pub const Runner = struct { return out; }, // TODO: optimize this - JSC.ConsoleObject.Formatter.Tag.Object => { + jsc.ConsoleObject.Formatter.Tag.Object => { this.is_top_level = false; const _entry = this.visited.getOrPut(this.allocator, value) catch unreachable; if (_entry.found_existing) { @@ -433,7 +433,7 @@ pub const Runner = struct { } // SAFETY: tag ensures `value` is an object. const obj = value.getObject() orelse unreachable; - var object_iter = try JSC.JSPropertyIterator(.{ + var object_iter = try jsc.JSPropertyIterator(.{ .skip_empty_name = false, .include_value = true, }).init(this.global, obj); @@ -466,7 +466,7 @@ pub const Runner = struct { // if (console_tag.cell == .JSDate) { // // in the code for printing dates, it never exceeds this amount // var iso_string_buf = this.allocator.alloc(u8, 36) catch unreachable; - // var str = JSC.ZigString.init(""); + // var str = jsc.ZigString.init(""); // value.jsonStringify(this.global, 0, &str); // var out_buf: []const u8 = std.fmt.bufPrint(iso_string_buf, "{}", .{str}) catch ""; // if (out_buf.len > 2) { @@ -502,8 +502,8 @@ pub const Runner = struct { this.macro.vm.waitForPromise(promise); - const promise_result = promise.result(this.macro.vm.jsc); - const rejected = promise.status(this.macro.vm.jsc) == .rejected; + const promise_result = promise.result(this.macro.vm.jsc_vm); + const rejected = promise.status(this.macro.vm.jsc_vm) == .rejected; if (promise_result.isUndefined() and this.is_top_level) { this.is_top_level = false; @@ -542,12 +542,12 @@ pub const Runner = struct { caller: Expr, source: *const logger.Source, id: i32, - javascript_object: JSC.JSValue, + javascript_object: jsc.JSValue, ) MacroError!Expr { if (comptime Environment.isDebug) Output.prettyln("[macro] call {s}", .{function_name}); - exception_holder = JSC.ZigException.Holder.init(); - var js_args: []JSC.JSValue = &.{}; + exception_holder = jsc.ZigException.Holder.init(); + var js_args: []jsc.JSValue = &.{}; var js_processed_args_len: usize = 0; defer { for (js_args[0..js_processed_args_len -| @as(usize, @intFromBool(javascript_object != .zero))]) |arg| { @@ -557,12 +557,12 @@ pub const Runner = struct { allocator.free(js_args); } - const globalObject = JSC.VirtualMachine.get().global; + const globalObject = jsc.VirtualMachine.get().global; switch (caller.data) { .e_call => |call| { const call_args: []Expr = call.args.slice(); - js_args = try allocator.alloc(JSC.JSValue, call_args.len + @as(usize, @intFromBool(javascript_object != .zero))); + js_args = try allocator.alloc(jsc.JSValue, call_args.len + @as(usize, @intFromBool(javascript_object != .zero))); js_processed_args_len = js_args.len; for (0.., call_args, js_args[0..call_args.len]) |i, in, *out| { @@ -589,7 +589,7 @@ pub const Runner = struct { if (javascript_object != .zero) { if (js_args.len == 0) { - js_args = try allocator.alloc(JSC.JSValue, 1); + js_args = try allocator.alloc(jsc.JSValue, 1); } js_args[js_args.len - 1] = javascript_object; @@ -601,9 +601,9 @@ pub const Runner = struct { threadlocal var call_args: CallArgs = undefined; threadlocal var result: MacroError!Expr = undefined; pub fn callWrapper(args: CallArgs) MacroError!Expr { - JSC.markBinding(@src()); + jsc.markBinding(@src()); call_args = args; - Bun__startMacro(&call, JSC.VirtualMachine.get().global); + Bun__startMacro(&call, jsc.VirtualMachine.get().global); return result; } @@ -631,6 +631,8 @@ pub const Runner = struct { extern "c" fn Bun__startMacro(function: *const anyopaque, *anyopaque) void; }; +const string = []const u8; + const DotEnv = @import("../env_loader.zig"); const std = @import("std"); @@ -648,17 +650,12 @@ const Output = bun.Output; const Transpiler = bun.Transpiler; const default_allocator = bun.default_allocator; const logger = bun.logger; -const string = bun.string; const strings = bun.strings; const Loader = bun.options.Loader; const MimeType = bun.http.MimeType; const MacroEntryPoint = bun.transpiler.EntryPoints.MacroEntryPoint; -const JSC = bun.JSC; -const JavaScript = bun.JSC; -const js = bun.JSC.C; - -const js_ast = bun.js_ast; +const js_ast = bun.ast; const E = js_ast.E; const Expr = js_ast.Expr; const ExprNodeList = js_ast.ExprNodeList; @@ -667,3 +664,7 @@ const Macro = js_ast.Macro; const S = js_ast.S; const Stmt = js_ast.Stmt; const ToJSError = js_ast.ToJSError; + +const JavaScript = bun.jsc; +const jsc = bun.jsc; +const js = bun.jsc.C; diff --git a/src/ast/Op.zig b/src/ast/Op.zig index bfe188a4aa..7c25998747 100644 --- a/src/ast/Op.zig +++ b/src/ast/Op.zig @@ -281,11 +281,11 @@ pub const Table = brk: { break :brk table; }; -const std = @import("std"); +const string = []const u8; const bun = @import("bun"); -const string = bun.string; +const std = @import("std"); -const js_ast = bun.js_ast; +const js_ast = bun.ast; const AssignTarget = js_ast.AssignTarget; const Op = js_ast.Op; diff --git a/src/ast/S.zig b/src/ast/S.zig index 62150bd735..5a7cd52b62 100644 --- a/src/ast/S.zig +++ b/src/ast/S.zig @@ -212,11 +212,12 @@ pub const Continue = struct { label: ?LocRef = null, }; +const string = []const u8; + const bun = @import("bun"); const logger = bun.logger; -const string = bun.string; -const js_ast = bun.js_ast; +const js_ast = bun.ast; const Case = js_ast.Case; const Catch = js_ast.Catch; const ClauseItem = js_ast.ClauseItem; diff --git a/src/ast/Scope.zig b/src/ast/Scope.zig index 680dfdf8c2..d9e3a0b6da 100644 --- a/src/ast/Scope.zig +++ b/src/ast/Scope.zig @@ -211,7 +211,7 @@ const bun = @import("bun"); const BabyList = bun.BabyList; const logger = bun.logger; -const js_ast = bun.js_ast; +const js_ast = bun.ast; const Ref = js_ast.Ref; const Scope = js_ast.Scope; const StrictModeKind = js_ast.StrictModeKind; diff --git a/src/ast/ServerComponentBoundary.zig b/src/ast/ServerComponentBoundary.zig index 39caa9368b..568db9477f 100644 --- a/src/ast/ServerComponentBoundary.zig +++ b/src/ast/ServerComponentBoundary.zig @@ -115,7 +115,7 @@ pub const List = struct { const bun = @import("bun"); const std = @import("std"); -const js_ast = bun.js_ast; +const js_ast = bun.ast; const Index = js_ast.Index; const ServerComponentBoundary = js_ast.ServerComponentBoundary; const UseDirective = js_ast.UseDirective; diff --git a/src/ast/Stmt.zig b/src/ast/Stmt.zig index 2d74b681d5..49317adf90 100644 --- a/src/ast/Stmt.zig +++ b/src/ast/Stmt.zig @@ -406,14 +406,15 @@ pub fn caresAboutScope(self: *Stmt) bool { }; } +const string = []const u8; + const std = @import("std"); const bun = @import("bun"); const Environment = bun.Environment; const logger = bun.logger; -const string = bun.string; -const js_ast = bun.js_ast; +const js_ast = bun.ast; const ASTMemoryAllocator = js_ast.ASTMemoryAllocator; const Expr = js_ast.Expr; const NewBatcher = js_ast.NewBatcher; diff --git a/src/ast/Symbol.zig b/src/ast/Symbol.zig index 03fc777c34..eada199e7d 100644 --- a/src/ast/Symbol.zig +++ b/src/ast/Symbol.zig @@ -479,7 +479,7 @@ const bun = @import("bun"); const BabyList = bun.BabyList; const Output = bun.Output; -const js_ast = bun.js_ast; +const js_ast = bun.ast; const DeclaredSymbol = js_ast.DeclaredSymbol; const G = js_ast.G; const ImportItemStatus = js_ast.ImportItemStatus; diff --git a/src/ast/TS.zig b/src/ast/TS.zig index d71a79256e..5eba8b444d 100644 --- a/src/ast/TS.zig +++ b/src/ast/TS.zig @@ -133,7 +133,7 @@ const std = @import("std"); const bun = @import("bun"); const logger = bun.logger; -const js_ast = bun.js_ast; +const js_ast = bun.ast; const E = js_ast.E; const G = js_ast.G; const Ref = js_ast.Ref; diff --git a/src/ast/UseDirective.zig b/src/ast/UseDirective.zig index 31c4de34c1..12552cd24d 100644 --- a/src/ast/UseDirective.zig +++ b/src/ast/UseDirective.zig @@ -60,5 +60,5 @@ const std = @import("std"); const bun = @import("bun"); const strings = bun.strings; -const js_ast = bun.js_ast; +const js_ast = bun.ast; const Flags = js_ast.Flags; diff --git a/src/ast/base.zig b/src/ast/base.zig index 1abc3e6188..7ee8e1347f 100644 --- a/src/ast/base.zig +++ b/src/ast/base.zig @@ -1,6 +1,3 @@ -pub const NodeIndex = u32; -pub const NodeIndexNone = 4294967293; - // TODO: figure out if we actually need this pub const RefHashCtx = struct { @@ -152,7 +149,7 @@ pub const Ref = packed struct(u64) { } }; } - fn dumpImpl(data: struct { ref: Ref, symbol: *js_ast.Symbol }, comptime _: []const u8, _: std.fmt.FormatOptions, writer: anytype) !void { + fn dumpImpl(data: struct { ref: Ref, symbol: *ast.Symbol }, comptime _: []const u8, _: std.fmt.FormatOptions, writer: anytype) !void { try std.fmt.format( writer, "Ref[inner={d}, src={d}, .{s}; original_name={s}, uses={d}]", @@ -217,15 +214,15 @@ pub const Ref = packed struct(u64) { return try writer.write([2]u32{ self.sourceIndex(), self.innerIndex() }); } - pub fn getSymbol(ref: Ref, symbol_table: anytype) *js_ast.Symbol { + pub fn getSymbol(ref: Ref, symbol_table: anytype) *ast.Symbol { // Different parts of the bundler use different formats of the symbol table // In the parser you only have one array, and .sourceIndex() is ignored. // In the bundler, you have a 2D array where both parts of the ref are used. const resolved_symbol_table = switch (@TypeOf(symbol_table)) { - *const std.ArrayList(js_ast.Symbol) => symbol_table.items, - *std.ArrayList(js_ast.Symbol) => symbol_table.items, - []js_ast.Symbol => symbol_table, - *js_ast.Symbol.Map => return symbol_table.get(ref) orelse + *const std.ArrayList(ast.Symbol) => symbol_table.items, + *std.ArrayList(ast.Symbol) => symbol_table.items, + []ast.Symbol => symbol_table, + *ast.Symbol.Map => return symbol_table.get(ref) orelse unreachable, // ref must exist within symbol table else => |T| @compileError("Unsupported type to Ref.getSymbol: " ++ @typeName(T)), }; @@ -236,4 +233,4 @@ pub const Ref = packed struct(u64) { const std = @import("std"); const bun = @import("bun"); -const js_ast = bun.JSAst; +const ast = bun.ast; diff --git a/src/async/posix_event_loop.zig b/src/async/posix_event_loop.zig index 57ea176236..4470d79651 100644 --- a/src/async/posix_event_loop.zig +++ b/src/async/posix_event_loop.zig @@ -15,7 +15,7 @@ pub const KeepAlive = struct { /// Make calling ref() on this poll into a no-op. pub fn disable(this: *KeepAlive) void { - this.unref(JSC.VirtualMachine.get()); + this.unref(jsc.VirtualMachine.get()); this.status = .done; } @@ -47,16 +47,16 @@ pub const KeepAlive = struct { return; this.status = .inactive; - if (comptime @TypeOf(event_loop_ctx_) == JSC.EventLoopHandle) { + if (comptime @TypeOf(event_loop_ctx_) == jsc.EventLoopHandle) { event_loop_ctx_.loop().unref(); return; } - const event_loop_ctx = JSC.AbstractVM(event_loop_ctx_); + const event_loop_ctx = jsc.AbstractVM(event_loop_ctx_); event_loop_ctx.platformEventLoop().unref(); } /// From another thread, Prevent a poll from keeping the process alive. - pub fn unrefConcurrently(this: *KeepAlive, vm: *JSC.VirtualMachine) void { + pub fn unrefConcurrently(this: *KeepAlive, vm: *jsc.VirtualMachine) void { if (this.status != .active) return; this.status = .inactive; @@ -65,7 +65,7 @@ pub const KeepAlive = struct { /// Prevent a poll from keeping the process alive on the next tick. pub fn unrefOnNextTick(this: *KeepAlive, event_loop_ctx_: anytype) void { - const event_loop_ctx = JSC.AbstractVM(event_loop_ctx_); + const event_loop_ctx = jsc.AbstractVM(event_loop_ctx_); if (this.status != .active) return; this.status = .inactive; @@ -74,7 +74,7 @@ pub const KeepAlive = struct { } /// From another thread, prevent a poll from keeping the process alive on the next tick. - pub fn unrefOnNextTickConcurrently(this: *KeepAlive, vm: *JSC.VirtualMachine) void { + pub fn unrefOnNextTickConcurrently(this: *KeepAlive, vm: *jsc.VirtualMachine) void { if (this.status != .active) return; this.status = .inactive; @@ -88,27 +88,27 @@ pub const KeepAlive = struct { this.status = .active; const EventLoopContext = @TypeOf(event_loop_ctx_); - if (comptime EventLoopContext == JSC.EventLoopHandle) { + if (comptime EventLoopContext == jsc.EventLoopHandle) { event_loop_ctx_.ref(); return; } - const event_loop_ctx = JSC.AbstractVM(event_loop_ctx_); + const event_loop_ctx = jsc.AbstractVM(event_loop_ctx_); event_loop_ctx.platformEventLoop().ref(); } /// Allow a poll to keep the process alive. - pub fn refConcurrently(this: *KeepAlive, vm: *JSC.VirtualMachine) void { + pub fn refConcurrently(this: *KeepAlive, vm: *jsc.VirtualMachine) void { if (this.status != .inactive) return; this.status = .active; vm.event_loop.refConcurrently(); } - pub fn refConcurrentlyFromEventLoop(this: *KeepAlive, loop: *JSC.EventLoop) void { + pub fn refConcurrentlyFromEventLoop(this: *KeepAlive, loop: *jsc.EventLoop) void { this.refConcurrently(loop.virtual_machine); } - pub fn unrefConcurrentlyFromEventLoop(this: *KeepAlive, loop: *JSC.EventLoop) void { + pub fn unrefConcurrentlyFromEventLoop(this: *KeepAlive, loop: *jsc.EventLoop) void { this.unrefConcurrently(loop.virtual_machine); } }; @@ -134,9 +134,9 @@ pub const FilePoll = struct { const ShellBufferedWriter = bun.shell.Interpreter.IOWriter.Poll; // const ShellBufferedWriter = bun.shell.Interpreter.WriterImpl; - const FileReader = JSC.WebCore.FileReader; - // const FIFO = JSC.WebCore.FIFO; - // const FIFOMini = JSC.WebCore.FIFOMini; + const FileReader = jsc.WebCore.FileReader; + // const FIFO = jsc.WebCore.FIFO; + // const FIFOMini = jsc.WebCore.FIFOMini; // const ShellBufferedWriterMini = bun.shell.InterpreterMini.BufferedWriter; // const ShellBufferedInput = bun.shell.ShellSubprocess.BufferedInput; @@ -146,13 +146,13 @@ pub const FilePoll = struct { // const ShellBufferedOutput = bun.shell.Subprocess.BufferedOutput; // const ShellBufferedOutputMini = bun.shell.SubprocessMini.BufferedOutput; const Process = bun.spawn.Process; - const Subprocess = JSC.Subprocess; + const Subprocess = jsc.Subprocess; const StaticPipeWriter = Subprocess.StaticPipeWriter.Poll; const ShellStaticPipeWriter = bun.shell.ShellSubprocess.StaticPipeWriter.Poll; - const FileSink = JSC.WebCore.FileSink.Poll; - const DNSResolver = bun.api.DNS.DNSResolver; - const GetAddrInfoRequest = bun.api.DNS.GetAddrInfoRequest; - const Request = bun.api.DNS.InternalDNS.Request; + const FileSink = jsc.WebCore.FileSink.Poll; + const DNSResolver = bun.api.dns.Resolver; + const GetAddrInfoRequest = bun.api.dns.GetAddrInfoRequest; + const Request = bun.api.dns.internal.Request; const LifecycleScriptSubprocessOutputReader = bun.install.LifecycleScriptSubprocess.OutputReader; const BufferedReader = bun.io.BufferedReader; @@ -265,16 +265,16 @@ pub const FilePoll = struct { pub fn deinit(this: *FilePoll) void { switch (this.allocator_type) { .js => { - const vm = JSC.VirtualMachine.get(); - const handle = JSC.AbstractVM(vm); + const vm = jsc.VirtualMachine.get(); + const handle = jsc.AbstractVM(vm); // const loop = vm.event_loop_handle.?; const loop = handle.platformEventLoop(); const file_polls = handle.filePolls(); this.deinitPossiblyDefer(vm, loop, file_polls, false); }, .mini => { - const vm = JSC.MiniEventLoop.global; - const handle = JSC.AbstractVM(vm); + const vm = jsc.MiniEventLoop.global; + const handle = jsc.AbstractVM(vm); // const loop = vm.event_loop_handle.?; const loop = handle.platformEventLoop(); const file_polls = handle.filePolls(); @@ -286,12 +286,12 @@ pub const FilePoll = struct { pub fn deinitForceUnregister(this: *FilePoll) void { switch (this.allocator_type) { .js => { - var vm = JSC.VirtualMachine.get(); + var vm = jsc.VirtualMachine.get(); const loop = vm.event_loop_handle.?; this.deinitPossiblyDefer(vm, loop, vm.rareData().filePolls(vm), true); }, .mini => { - var vm = JSC.MiniEventLoop.global; + var vm = jsc.MiniEventLoop.global; const loop = vm.loop; this.deinitPossiblyDefer(vm, loop, vm.filePolls(), true); }, @@ -309,7 +309,7 @@ pub const FilePoll = struct { } pub fn deinitWithVM(this: *FilePoll, vm_: anytype) void { - const vm = JSC.AbstractVM(vm_); + const vm = jsc.AbstractVM(vm_); // const loop = vm.event_loop_handle.?; const loop = vm.platformEventLoop(); this.deinitPossiblyDefer(vm_, loop, vm.filePolls(), false); @@ -586,8 +586,8 @@ pub const FilePoll = struct { poll.flags.insert(.ignore_updates); this.pending_free_tail = poll; - const callback = JSC.OpaqueWrap(Store, processDeferredFrees); - bun.assert(vm.after_event_loop_callback == null or vm.after_event_loop_callback == @as(?JSC.OpaqueCallback, callback)); + const callback = jsc.OpaqueWrap(Store, processDeferredFrees); + bun.assert(vm.after_event_loop_callback == null or vm.after_event_loop_callback == @as(?jsc.OpaqueCallback, callback)); vm.after_event_loop_callback = callback; vm.after_event_loop_callback_ctx = this; } @@ -606,15 +606,15 @@ pub const FilePoll = struct { /// This decrements the active counter if it was previously incremented /// "active" controls whether or not the event loop should potentially idle pub fn disableKeepingProcessAlive(this: *FilePoll, event_loop_ctx_: anytype) void { - if (comptime @TypeOf(event_loop_ctx_) == *JSC.EventLoop) { - disableKeepingProcessAlive(this, JSC.EventLoopHandle.init(event_loop_ctx_)); + if (comptime @TypeOf(event_loop_ctx_) == *jsc.EventLoop) { + disableKeepingProcessAlive(this, jsc.EventLoopHandle.init(event_loop_ctx_)); return; } - if (comptime @TypeOf(event_loop_ctx_) == JSC.EventLoopHandle) { + if (comptime @TypeOf(event_loop_ctx_) == jsc.EventLoopHandle) { event_loop_ctx_.loop().subActive(@as(u32, @intFromBool(this.flags.contains(.has_incremented_active_count)))); } else { - const event_loop_ctx = JSC.AbstractVM(event_loop_ctx_); + const event_loop_ctx = jsc.AbstractVM(event_loop_ctx_); // log("{x} disableKeepingProcessAlive", .{@intFromPtr(this)}); // vm.event_loop_handle.?.subActive(@as(u32, @intFromBool(this.flags.contains(.has_incremented_active_count)))); event_loop_ctx.platformEventLoop().subActive(@as(u32, @intFromBool(this.flags.contains(.has_incremented_active_count)))); @@ -636,18 +636,18 @@ pub const FilePoll = struct { } } pub fn enableKeepingProcessAlive(this: *FilePoll, event_loop_ctx_: anytype) void { - if (comptime @TypeOf(event_loop_ctx_) == *JSC.EventLoop) { - enableKeepingProcessAlive(this, JSC.EventLoopHandle.init(event_loop_ctx_)); + if (comptime @TypeOf(event_loop_ctx_) == *jsc.EventLoop) { + enableKeepingProcessAlive(this, jsc.EventLoopHandle.init(event_loop_ctx_)); return; } if (this.flags.contains(.closed)) return; - if (comptime @TypeOf(event_loop_ctx_) == JSC.EventLoopHandle) { + if (comptime @TypeOf(event_loop_ctx_) == jsc.EventLoopHandle) { event_loop_ctx_.loop().addActive(@as(u32, @intFromBool(!this.flags.contains(.has_incremented_active_count)))); } else { - const event_loop_ctx = JSC.AbstractVM(event_loop_ctx_); + const event_loop_ctx = jsc.AbstractVM(event_loop_ctx_); event_loop_ctx.platformEventLoop().addActive(@as(u32, @intFromBool(!this.flags.contains(.has_incremented_active_count)))); } @@ -680,10 +680,10 @@ pub const FilePoll = struct { pub fn init(vm: anytype, fd: bun.FileDescriptor, flags: Flags.Struct, comptime Type: type, owner: *Type) *FilePoll { if (comptime @TypeOf(vm) == *bun.install.PackageManager) { - return init(JSC.EventLoopHandle.init(&vm.event_loop), fd, flags, Type, owner); + return init(jsc.EventLoopHandle.init(&vm.event_loop), fd, flags, Type, owner); } - if (comptime @TypeOf(vm) == JSC.EventLoopHandle) { + if (comptime @TypeOf(vm) == jsc.EventLoopHandle) { var poll = vm.filePolls().get(); poll.fd = fd; poll.flags = Flags.Set.init(flags); @@ -703,13 +703,13 @@ pub const FilePoll = struct { } pub fn initWithOwner(vm_: anytype, fd: bun.FileDescriptor, flags: Flags.Struct, owner: Owner) *FilePoll { - const vm = JSC.AbstractVM(vm_); + const vm = jsc.AbstractVM(vm_); var poll = vm.allocFilePoll(); poll.fd = fd; poll.flags = Flags.Set.init(flags); poll.owner = owner; poll.next_to_free = null; - poll.allocator_type = if (comptime @TypeOf(vm_) == *JSC.VirtualMachine) .js else .mini; + poll.allocator_type = if (comptime @TypeOf(vm_) == *jsc.VirtualMachine) .js else .mini; if (KQueueGenerationNumber != u0) { max_generation_number +%= 1; @@ -748,7 +748,7 @@ pub const FilePoll = struct { } pub fn onEnded(this: *FilePoll, event_loop_ctx_: anytype) void { - const event_loop_ctx = JSC.AbstractVM(event_loop_ctx_); + const event_loop_ctx = jsc.AbstractVM(event_loop_ctx_); this.flags.remove(.keeps_event_loop_alive); this.flags.insert(.closed); // this.deactivate(vm.event_loop_handle.?); @@ -786,11 +786,11 @@ pub const FilePoll = struct { pub const OneShotFlag = enum { dispatch, one_shot, none }; - pub fn register(this: *FilePoll, loop: *Loop, flag: Flags, one_shot: bool) JSC.Maybe(void) { + pub fn register(this: *FilePoll, loop: *Loop, flag: Flags, one_shot: bool) jsc.Maybe(void) { return registerWithFd(this, loop, flag, if (one_shot) .one_shot else .none, this.fd); } - pub fn registerWithFd(this: *FilePoll, loop: *Loop, flag: Flags, one_shot: OneShotFlag, fd: bun.FileDescriptor) JSC.Maybe(void) { + pub fn registerWithFd(this: *FilePoll, loop: *Loop, flag: Flags, one_shot: OneShotFlag, fd: bun.FileDescriptor) jsc.Maybe(void) { const watcher_fd = loop.fd; log("register: FilePoll(0x{x}, generation_number={d}) {s} ({})", .{ @intFromPtr(this), this.generation_number, @tagName(flag), fd }); @@ -823,7 +823,7 @@ pub const FilePoll = struct { &event, ); this.flags.insert(.was_ever_registered); - if (JSC.Maybe(void).errnoSys(ctl, .epoll_ctl)) |errno| { + if (jsc.Maybe(void).errnoSys(ctl, .epoll_ctl)) |errno| { this.deactivate(loop); return errno; } @@ -909,7 +909,7 @@ pub const FilePoll = struct { // in the eventlist, then the event will be placed in the eventlist // with EV_ERROR set in flags and the system error in data. if (changelist[0].flags == std.c.EV.ERROR and changelist[0].data != 0) { - return JSC.Maybe(void).errnoSys(changelist[0].data, .kevent).?; + return jsc.Maybe(void).errnoSys(changelist[0].data, .kevent).?; // Otherwise, -1 will be returned, and errno will be set to // indicate the error condition. } @@ -918,7 +918,7 @@ pub const FilePoll = struct { if (errno != .SUCCESS) { this.deactivate(loop); - return JSC.Maybe(void){ + return jsc.Maybe(void){ .err = bun.sys.Error.fromCode(errno, .kqueue), }; } @@ -935,7 +935,7 @@ pub const FilePoll = struct { }); this.flags.remove(.needs_rearm); - return JSC.Maybe(void).success; + return jsc.Maybe(void).success; } const invalid_fd = bun.invalid_fd; @@ -944,11 +944,11 @@ pub const FilePoll = struct { return @intCast(this.fd); } - pub fn unregister(this: *FilePoll, loop: *Loop, force_unregister: bool) JSC.Maybe(void) { + pub fn unregister(this: *FilePoll, loop: *Loop, force_unregister: bool) jsc.Maybe(void) { return this.unregisterWithFd(loop, this.fd, force_unregister); } - pub fn unregisterWithFd(this: *FilePoll, loop: *Loop, fd: bun.FileDescriptor, force_unregister: bool) JSC.Maybe(void) { + pub fn unregisterWithFd(this: *FilePoll, loop: *Loop, fd: bun.FileDescriptor, force_unregister: bool) jsc.Maybe(void) { if (Environment.allow_assert) { bun.assert(fd.native() >= 0 and fd != bun.invalid_fd); } @@ -957,7 +957,7 @@ pub const FilePoll = struct { if (!(this.flags.contains(.poll_readable) or this.flags.contains(.poll_writable) or this.flags.contains(.poll_process) or this.flags.contains(.poll_machport))) { // no-op - return JSC.Maybe(void).success; + return jsc.Maybe(void).success; } bun.assert(fd != invalid_fd); @@ -972,7 +972,7 @@ pub const FilePoll = struct { if (this.flags.contains(.poll_machport)) break :brk .machport; - return JSC.Maybe(void).success; + return jsc.Maybe(void).success; }; if (this.flags.contains(.needs_rearm) and !force_unregister) { @@ -981,7 +981,7 @@ pub const FilePoll = struct { this.flags.remove(.poll_readable); this.flags.remove(.poll_process); this.flags.remove(.poll_machport); - return JSC.Maybe(void).success; + return jsc.Maybe(void).success; } log("unregister: FilePoll(0x{x}, generation_number={d}) {s} ({})", .{ @intFromPtr(this), this.generation_number, @tagName(flag), fd }); @@ -994,7 +994,7 @@ pub const FilePoll = struct { null, ); - if (JSC.Maybe(void).errnoSys(ctl, .epoll_ctl)) |errno| { + if (jsc.Maybe(void).errnoSys(ctl, .epoll_ctl)) |errno| { return errno; } } else if (comptime Environment.isMac) { @@ -1061,14 +1061,14 @@ pub const FilePoll = struct { // in the eventlist, then the event will be placed in the eventlist // with EV_ERROR set in flags and the system error in data. if (changelist[0].flags == std.c.EV.ERROR) { - return JSC.Maybe(void).errnoSys(changelist[0].data, .kevent).?; + return jsc.Maybe(void).errnoSys(changelist[0].data, .kevent).?; // Otherwise, -1 will be returned, and errno will be set to // indicate the error condition. } const errno = bun.sys.getErrno(rc); switch (rc) { - std.math.minInt(@TypeOf(rc))...-1 => return JSC.Maybe(void).errnoSys(@intFromEnum(errno), .kevent).?, + std.math.minInt(@TypeOf(rc))...-1 => return jsc.Maybe(void).errnoSys(@intFromEnum(errno), .kevent).?, else => {}, } } else { @@ -1084,7 +1084,7 @@ pub const FilePoll = struct { this.flags.remove(.poll_process); this.flags.remove(.poll_machport); - return JSC.Maybe(void).success; + return jsc.Maybe(void).success; } }; @@ -1134,7 +1134,7 @@ pub const KEventWaker = struct { const Kevent64 = std.posix.system.kevent64_s; pub fn wake(this: *Waker) void { - bun.JSC.markBinding(@src()); + bun.jsc.markBinding(@src()); if (io_darwin_schedule_wakeup(this.machport)) { this.has_pending_wake = false; @@ -1152,7 +1152,7 @@ pub const KEventWaker = struct { return; } - bun.JSC.markBinding(@src()); + bun.jsc.markBinding(@src()); var events = zeroed; _ = std.posix.system.kevent64( @@ -1181,7 +1181,7 @@ pub const KEventWaker = struct { } pub fn initWithFileDescriptor(allocator: std.mem.Allocator, kq: i32) !Waker { - bun.JSC.markBinding(@src()); + bun.jsc.markBinding(@src()); bun.assert(kq > -1); const machport_buf = try allocator.alloc(u8, 1024); const machport = io_darwin_create_machport( @@ -1203,7 +1203,7 @@ pub const KEventWaker = struct { pub const Closer = struct { fd: bun.FileDescriptor, - task: JSC.WorkPoolTask = .{ .callback = &onClose }, + task: jsc.WorkPoolTask = .{ .callback = &onClose }, pub const new = bun.TrivialNew(@This()); @@ -1213,10 +1213,10 @@ pub const Closer = struct { _: void, ) void { bun.assert(fd.isValid()); - JSC.WorkPool.schedule(&Closer.new(.{ .fd = fd }).task); + jsc.WorkPool.schedule(&Closer.new(.{ .fd = fd }).task); } - fn onClose(task: *JSC.WorkPoolTask) void { + fn onClose(task: *jsc.WorkPoolTask) void { const closer: *Closer = @fieldParentPtr("task", task); defer bun.destroy(closer); closer.fd.close(); @@ -1227,6 +1227,6 @@ const std = @import("std"); const bun = @import("bun"); const Environment = bun.Environment; -const JSC = bun.JSC; const Output = bun.Output; +const jsc = bun.jsc; const uws = bun.uws; diff --git a/src/async/windows_event_loop.zig b/src/async/windows_event_loop.zig index 0aeb730bef..537a10b577 100644 --- a/src/async/windows_event_loop.zig +++ b/src/async/windows_event_loop.zig @@ -14,7 +14,7 @@ pub const KeepAlive = struct { /// Make calling ref() on this poll into a no-op. pub fn disable(this: *KeepAlive) void { if (this.status == .active) { - this.unref(JSC.VirtualMachine.get()); + this.unref(jsc.VirtualMachine.get()); } this.status = .done; @@ -47,16 +47,16 @@ pub const KeepAlive = struct { if (this.status != .active) return; this.status = .inactive; - if (comptime @TypeOf(event_loop_ctx_) == JSC.EventLoopHandle) { + if (comptime @TypeOf(event_loop_ctx_) == jsc.EventLoopHandle) { event_loop_ctx_.loop().subActive(1); return; } - const event_loop_ctx = JSC.AbstractVM(event_loop_ctx_); + const event_loop_ctx = jsc.AbstractVM(event_loop_ctx_); event_loop_ctx.platformEventLoop().subActive(1); } /// From another thread, Prevent a poll from keeping the process alive. - pub fn unrefConcurrently(this: *KeepAlive, vm: *JSC.VirtualMachine) void { + pub fn unrefConcurrently(this: *KeepAlive, vm: *jsc.VirtualMachine) void { // _ = vm; if (this.status != .active) return; @@ -65,7 +65,7 @@ pub const KeepAlive = struct { } /// Prevent a poll from keeping the process alive on the next tick. - pub fn unrefOnNextTick(this: *KeepAlive, vm: *JSC.VirtualMachine) void { + pub fn unrefOnNextTick(this: *KeepAlive, vm: *jsc.VirtualMachine) void { if (this.status != .active) return; this.status = .inactive; @@ -73,7 +73,7 @@ pub const KeepAlive = struct { } /// From another thread, prevent a poll from keeping the process alive on the next tick. - pub fn unrefOnNextTickConcurrently(this: *KeepAlive, vm: *JSC.VirtualMachine) void { + pub fn unrefOnNextTickConcurrently(this: *KeepAlive, vm: *jsc.VirtualMachine) void { if (this.status != .active) return; this.status = .inactive; @@ -87,27 +87,27 @@ pub const KeepAlive = struct { return; this.status = .active; const EventLoopContext = @TypeOf(event_loop_ctx_); - if (comptime EventLoopContext == JSC.EventLoopHandle) { + if (comptime EventLoopContext == jsc.EventLoopHandle) { event_loop_ctx_.ref(); return; } - const event_loop_ctx = JSC.AbstractVM(event_loop_ctx_); + const event_loop_ctx = jsc.AbstractVM(event_loop_ctx_); event_loop_ctx.platformEventLoop().ref(); } /// Allow a poll to keep the process alive. - pub fn refConcurrently(this: *KeepAlive, vm: *JSC.VirtualMachine) void { + pub fn refConcurrently(this: *KeepAlive, vm: *jsc.VirtualMachine) void { if (this.status != .inactive) return; this.status = .active; vm.event_loop.refConcurrently(); } - pub fn refConcurrentlyFromEventLoop(this: *KeepAlive, loop: *JSC.EventLoop) void { + pub fn refConcurrentlyFromEventLoop(this: *KeepAlive, loop: *jsc.EventLoop) void { this.refConcurrently(loop.virtual_machine); } - pub fn unrefConcurrentlyFromEventLoop(this: *KeepAlive, loop: *JSC.EventLoop) void { + pub fn unrefConcurrentlyFromEventLoop(this: *KeepAlive, loop: *jsc.EventLoop) void { this.unrefConcurrently(loop.virtual_machine); } }; @@ -140,9 +140,9 @@ pub const FilePoll = struct { } /// Make calling ref() on this poll into a no-op. - // pub fn disableKeepingProcessAlive(this: *FilePoll, vm: *JSC.VirtualMachine) void { + // pub fn disableKeepingProcessAlive(this: *FilePoll, vm: *jsc.VirtualMachine) void { pub fn disableKeepingProcessAlive(this: *FilePoll, abstract_vm: anytype) void { - const vm = JSC.AbstractVM(abstract_vm); + const vm = jsc.AbstractVM(abstract_vm); if (this.flags.contains(.closed)) return; this.flags.insert(.closed); @@ -151,11 +151,11 @@ pub const FilePoll = struct { // vm.event_loop_handle.?.active_handles -= @as(u32, @intFromBool(this.flags.contains(.has_incremented_poll_count))); } - pub fn init(vm: *JSC.VirtualMachine, fd: bun.FileDescriptor, flags: Flags.Struct, comptime Type: type, owner: *Type) *FilePoll { + pub fn init(vm: *jsc.VirtualMachine, fd: bun.FileDescriptor, flags: Flags.Struct, comptime Type: type, owner: *Type) *FilePoll { return initWithOwner(vm, fd, flags, Owner.init(owner)); } - pub fn initWithOwner(vm: *JSC.VirtualMachine, fd: bun.FileDescriptor, flags: Flags.Struct, owner: Owner) *FilePoll { + pub fn initWithOwner(vm: *jsc.VirtualMachine, fd: bun.FileDescriptor, flags: Flags.Struct, owner: Owner) *FilePoll { var poll = vm.rareData().filePolls(vm).get(); poll.fd = fd; poll.flags = Flags.Set.init(flags); @@ -166,7 +166,7 @@ pub const FilePoll = struct { } pub fn deinit(this: *FilePoll) void { - const vm = JSC.VirtualMachine.get(); + const vm = jsc.VirtualMachine.get(); this.deinitWithVM(vm); } @@ -185,7 +185,7 @@ pub const FilePoll = struct { return true; } - fn deinitPossiblyDefer(this: *FilePoll, vm: *JSC.VirtualMachine, loop: *Loop, polls: *FilePoll.Store) void { + fn deinitPossiblyDefer(this: *FilePoll, vm: *jsc.VirtualMachine, loop: *Loop, polls: *FilePoll.Store) void { if (this.isRegistered()) { _ = this.unregister(loop); } @@ -224,13 +224,13 @@ pub const FilePoll = struct { return readable; } - pub fn deinitWithVM(this: *FilePoll, vm: *JSC.VirtualMachine) void { + pub fn deinitWithVM(this: *FilePoll, vm: *jsc.VirtualMachine) void { const loop = vm.event_loop_handle.?; this.deinitPossiblyDefer(vm, loop, vm.rareData().filePolls(vm)); } pub fn enableKeepingProcessAlive(this: *FilePoll, abstract_vm: anytype) void { - const vm = JSC.AbstractVM(abstract_vm); + const vm = jsc.AbstractVM(abstract_vm); if (!this.flags.contains(.closed)) return; this.flags.remove(.closed); @@ -270,7 +270,7 @@ pub const FilePoll = struct { } pub fn onEnded(this: *FilePoll, event_loop_ctx_: anytype) void { - const event_loop_ctx = JSC.AbstractVM(event_loop_ctx_); + const event_loop_ctx = jsc.AbstractVM(event_loop_ctx_); this.flags.remove(.keeps_event_loop_alive); this.flags.insert(.closed); // this.deactivate(vm.event_loop_handle.?); @@ -279,7 +279,7 @@ pub const FilePoll = struct { /// Prevent a poll from keeping the process alive. pub fn unref(this: *FilePoll, abstract_vm: anytype) void { - const vm = JSC.AbstractVM(abstract_vm); + const vm = jsc.AbstractVM(abstract_vm); if (!this.canUnref()) return; log("unref", .{}); @@ -288,13 +288,13 @@ pub const FilePoll = struct { } /// Allow a poll to keep the process alive. - // pub fn ref(this: *FilePoll, vm: *JSC.VirtualMachine) void { + // pub fn ref(this: *FilePoll, vm: *jsc.VirtualMachine) void { pub fn ref(this: *FilePoll, event_loop_ctx_: anytype) void { if (this.canRef()) return; log("ref", .{}); // this.activate(vm.event_loop_handle.?); - const event_loop_ctx = JSC.AbstractVM(event_loop_ctx_); + const event_loop_ctx = jsc.AbstractVM(event_loop_ctx_); this.activate(event_loop_ctx.platformEventLoop()); } @@ -328,7 +328,7 @@ pub const FilePoll = struct { this.pending_free_tail = null; } - pub fn put(this: *Store, poll: *FilePoll, vm: *JSC.VirtualMachine, ever_registered: bool) void { + pub fn put(this: *Store, poll: *FilePoll, vm: *jsc.VirtualMachine, ever_registered: bool) void { if (!ever_registered) { this.hive.put(poll); return; @@ -350,8 +350,8 @@ pub const FilePoll = struct { poll.flags.insert(.ignore_updates); this.pending_free_tail = poll; - const callback = JSC.OpaqueWrap(Store, processDeferredFrees); - bun.assert(vm.after_event_loop_callback == null or vm.after_event_loop_callback == @as(?JSC.OpaqueCallback, callback)); + const callback = jsc.OpaqueWrap(Store, processDeferredFrees); + bun.assert(vm.after_event_loop_callback == null or vm.after_event_loop_callback == @as(?jsc.OpaqueCallback, callback)); vm.after_event_loop_callback = callback; vm.after_event_loop_callback_ctx = this; } @@ -416,7 +416,7 @@ const std = @import("std"); const bun = @import("bun"); const Environment = bun.Environment; -const JSC = bun.JSC; const Output = bun.Output; +const jsc = bun.jsc; const uws = bun.uws; const uv = bun.windows.libuv; diff --git a/src/bake/bake.bind.ts b/src/bake.bind.ts similarity index 100% rename from src/bake/bake.bind.ts rename to src/bake.bind.ts diff --git a/src/bake/bake.zig b/src/bake.zig similarity index 96% rename from src/bake/bake.zig rename to src/bake.zig index eedf981572..ac5f5c2997 100644 --- a/src/bake/bake.zig +++ b/src/bake.zig @@ -2,9 +2,9 @@ //! combines `Bun.build` and `Bun.serve`, providing a hot-reloading development //! server, server components, and other integrations. Instead of taking the //! role as a framework, Bake is tool for frameworks to build on top of. -pub const production = @import("./production.zig"); -pub const DevServer = @import("./DevServer.zig"); -pub const FrameworkRouter = @import("./FrameworkRouter.zig"); +pub const production = @import("./bake/production.zig"); +pub const DevServer = @import("./bake/DevServer.zig"); +pub const FrameworkRouter = @import("./bake/FrameworkRouter.zig"); /// export default { app: ... }; pub const api_name = "app"; @@ -26,7 +26,7 @@ pub const UserOptions = struct { } /// Currently, this function must run at the top of the event loop. - pub fn fromJS(config: JSValue, global: *JSC.JSGlobalObject) !UserOptions { + pub fn fromJS(config: JSValue, global: *jsc.JSGlobalObject) !UserOptions { if (!config.isObject()) { return global.throwInvalidArguments("'" ++ api_name ++ "' is not an object", .{}); } @@ -116,7 +116,7 @@ pub const SplitBundlerOptions = struct { .ssr = .{}, }; - pub fn parsePluginArray(opts: *SplitBundlerOptions, plugin_array: JSValue, global: *JSC.JSGlobalObject) bun.JSError!void { + pub fn parsePluginArray(opts: *SplitBundlerOptions, plugin_array: JSValue, global: *jsc.JSGlobalObject) bun.JSError!void { const plugin = opts.plugin orelse Plugin.create(global, .bun); opts.plugin = plugin; const empty_object = JSValue.createEmptyObject(global, 0); @@ -160,29 +160,29 @@ pub const SplitBundlerOptions = struct { }; const BuildConfigSubset = struct { - loader: ?bun.Schema.Api.LoaderMap = null, + loader: ?bun.schema.api.LoaderMap = null, ignoreDCEAnnotations: ?bool = null, conditions: bun.StringArrayHashMapUnmanaged(void) = .{}, drop: bun.StringArrayHashMapUnmanaged(void) = .{}, - env: bun.Schema.Api.DotEnvBehavior = ._none, + env: bun.schema.api.DotEnvBehavior = ._none, env_prefix: ?[]const u8 = null, - define: bun.Schema.Api.StringMap = .{ .keys = &.{}, .values = &.{} }, - source_map: bun.Schema.Api.SourceMapMode = .external, + define: bun.schema.api.StringMap = .{ .keys = &.{}, .values = &.{} }, + source_map: bun.schema.api.SourceMapMode = .external, minify_syntax: ?bool = null, minify_identifiers: ?bool = null, minify_whitespace: ?bool = null, - pub fn fromJS(global: *JSC.JSGlobalObject, js_options: JSValue) bun.JSError!BuildConfigSubset { + pub fn fromJS(global: *jsc.JSGlobalObject, js_options: JSValue) bun.JSError!BuildConfigSubset { var options = BuildConfigSubset{}; if (try js_options.getOptional(global, "sourcemap", JSValue)) |val| brk: { - if (try bun.Schema.Api.SourceMapMode.fromJS(global, val)) |sourcemap| { + if (try bun.schema.api.SourceMapMode.fromJS(global, val)) |sourcemap| { options.source_map = sourcemap; break :brk; } - return bun.JSC.Node.validators.throwErrInvalidArgType(global, "sourcemap", .{}, "\"inline\" | \"external\" | \"linked\"", val); + return bun.jsc.Node.validators.throwErrInvalidArgType(global, "sourcemap", .{}, "\"inline\" | \"external\" | \"linked\"", val); } if (try js_options.getOptional(global, "minify", JSValue)) |minify_options| brk: { @@ -253,9 +253,9 @@ pub const Framework = struct { "bun-framework-react/server.tsx", "bun-framework-react/ssr.tsx", }, if (Environment.codegen_embed) &.{ - .{ .code = @embedFile("./bun-framework-react/client.tsx") }, - .{ .code = @embedFile("./bun-framework-react/server.tsx") }, - .{ .code = @embedFile("./bun-framework-react/ssr.tsx") }, + .{ .code = @embedFile("./bake/bun-framework-react/client.tsx") }, + .{ .code = @embedFile("./bake/bun-framework-react/server.tsx") }, + .{ .code = @embedFile("./bake/bun-framework-react/ssr.tsx") }, } else &.{ // Cannot use .import because resolution must happen from the user's POV .{ .code = bun.runtimeEmbedFile(.src, "bake/bun-framework-react/client.tsx") }, @@ -406,7 +406,7 @@ pub const Framework = struct { fn fromJS( opts: JSValue, - global: *JSC.JSGlobalObject, + global: *jsc.JSGlobalObject, refs: *StringRefList, bundler_options: *SplitBundlerOptions, arena: Allocator, @@ -677,7 +677,7 @@ pub const Framework = struct { minify_syntax: ?bool, minify_identifiers: ?bool, ) !void { - const JSAst = bun.JSAst; + const JSAst = bun.ast; var ast_memory_allocator: JSAst.ASTMemoryAllocator = undefined; ast_memory_allocator.initWithoutStack(arena); @@ -691,7 +691,7 @@ pub const Framework = struct { out.* = try bun.Transpiler.init( arena, log, - std.mem.zeroes(bun.Schema.Api.TransformOptions), + std.mem.zeroes(bun.schema.api.TransformOptions), null, ); @@ -793,7 +793,7 @@ pub const Framework = struct { fn getOptionalString( target: JSValue, - global: *JSC.JSGlobalObject, + global: *jsc.JSGlobalObject, property: []const u8, allocations: *StringRefList, arena: Allocator, @@ -905,13 +905,13 @@ pub fn addImportMetaDefines( pub const server_virtual_source: bun.logger.Source = .{ .path = bun.fs.Path.initForKitBuiltIn("bun", "bake/server"), .contents = "", // Virtual - .index = bun.JSAst.Index.bake_server_data, + .index = bun.ast.Index.bake_server_data, }; pub const client_virtual_source: bun.logger.Source = .{ .path = bun.fs.Path.initForKitBuiltIn("bun", "bake/client"), .contents = "", // Virtual - .index = bun.JSAst.Index.bake_client_data, + .index = bun.ast.Index.bake_client_data, }; /// Stack-allocated structure that is written to from end to start. @@ -971,7 +971,7 @@ const Allocator = std.mem.Allocator; const bun = @import("bun"); const Environment = bun.Environment; -const JSC = bun.JSC; -const JSValue = JSC.JSValue; -const ZigString = JSC.ZigString; -const Plugin = JSC.API.JSBundler.Plugin; +const jsc = bun.jsc; +const JSValue = jsc.JSValue; +const ZigString = jsc.ZigString; +const Plugin = jsc.API.JSBundler.Plugin; diff --git a/src/bake/DevServer.zig b/src/bake/DevServer.zig index fe56d9a564..63e88a66f4 100644 --- a/src/bake/DevServer.zig +++ b/src/bake/DevServer.zig @@ -58,7 +58,7 @@ vm: *VirtualMachine, /// May be `null` if not attached to an HTTP server yet. When no server is /// available, functions taking in requests and responses are unavailable. /// However, a lot of testing in this mode is missing, so it may hit assertions. -server: ?bun.JSC.API.AnyServer, +server: ?bun.jsc.API.AnyServer, /// Contains the tree of routes. This structure contains FileIndex router: FrameworkRouter, /// Every navigatable route has bundling state here. @@ -103,8 +103,8 @@ has_tailwind_plugin_hack: ?bun.StringArrayHashMapUnmanaged(void) = null, // These values are handles to the functions in `hmr-runtime-server.ts`. // For type definitions, see `./bake.private.d.ts` -server_fetch_function_callback: JSC.Strong.Optional, -server_register_update_callback: JSC.Strong.Optional, +server_fetch_function_callback: jsc.Strong.Optional, +server_register_update_callback: jsc.Strong.Optional, // Watching bun_watcher: *bun.Watcher, @@ -283,13 +283,13 @@ pub const RouteBundle = struct { /// Cached to avoid re-creating the array every request. /// TODO: Invalidated when a layout is added or removed from this route. - cached_module_list: JSC.Strong.Optional, + cached_module_list: jsc.Strong.Optional, /// Cached to avoid re-creating the string every request. /// TODO: Invalidated when any client file associated with the route is updated. - cached_client_bundle_url: JSC.Strong.Optional, + cached_client_bundle_url: jsc.Strong.Optional, /// Cached to avoid re-creating the array every request. /// Invalidated when the list of CSS files changes. - cached_css_file_array: JSC.Strong.Optional, + cached_css_file_array: jsc.Strong.Optional, /// When state == .evaluation_failure, this is populated with the route /// evaluation error mirrored in the dev server hash map @@ -391,7 +391,7 @@ pub const RouteBundle = struct { if (rb.client_bundle) |bundle| cost += bundle.memoryCost(); switch (rb.data) { .framework => { - // the JSC.Strong.Optional children do not support memoryCost. likely not needed + // the jsc.Strong.Optional children do not support memoryCost. likely not needed // .evaluate_failure is not owned }, .html => |*html| { @@ -1089,7 +1089,7 @@ fn scanInitialRoutes(dev: *DevServer) !void { /// Returns true if a catch-all handler was attached. pub fn setRoutes(dev: *DevServer, server: anytype) !bool { // TODO: all paths here must be prefixed with publicPath if set. - dev.server = bun.JSC.API.AnyServer.from(server); + dev.server = bun.jsc.API.AnyServer.from(server); const app = server.app.?; const is_ssl = @typeInfo(@TypeOf(app)).pointer.child.is_ssl; @@ -1528,7 +1528,7 @@ fn appendRouteEntryPointsIfNotStale(dev: *DevServer, entry_points: *EntryPointLi fn onFrameworkRequestWithBundle( dev: *DevServer, route_bundle_index: RouteBundle.Index, - req: bun.JSC.API.SavedRequest.Union, + req: bun.jsc.API.SavedRequest.Union, resp: AnyResponse, ) bun.JSError!void { const route_bundle = dev.routeBundlePtr(route_bundle_index); @@ -1773,7 +1773,7 @@ fn generateHTMLPayload(dev: *DevServer, route_bundle_index: RouteBundle.Index, r fn generateJavaScriptCodeForHTMLFile( dev: *DevServer, - index: bun.JSAst.Index, + index: bun.ast.Index, import_records: []bun.BabyList(bun.ImportRecord), input_file_sources: []bun.logger.Source, loaders: []bun.options.Loader, @@ -1851,7 +1851,7 @@ pub fn onSrcRequest(dev: *DevServer, req: *uws.Request, resp: anytype) void { _ = dev; // const ctx = &dev.vm.rareData().editor_context; - // ctx.autoDetectEditor(JSC.VirtualMachine.get().transpiler.env); + // ctx.autoDetectEditor(jsc.VirtualMachine.get().transpiler.env); // const line: ?[]const u8 = req.header("editor-line"); // const column: ?[]const u8 = req.header("editor-column"); @@ -1889,7 +1889,7 @@ const DeferredRequest = struct { const Handler = union(enum) { /// For a .framework route. This says to call and render the page. - server_handler: bun.JSC.API.SavedRequest, + server_handler: bun.jsc.API.SavedRequest, /// For a .html route. Serve the bundled HTML page. bundled_html_page: ResponseAndMethod, /// Do nothing and free this node. To simplify lifetimes, @@ -1973,10 +1973,10 @@ fn startAsyncBundle( // Ref server to keep it from closing. if (dev.server) |server| server.onPendingRequest(); - var heap = try ThreadlocalArena.init(); + var heap = try ThreadLocalArena.init(); errdefer heap.deinit(); const allocator = heap.allocator(); - const ast_memory_allocator = try allocator.create(bun.JSAst.ASTMemoryAllocator); + const ast_memory_allocator = try allocator.create(bun.ast.ASTMemoryAllocator); var ast_scope = ast_memory_allocator.enter(allocator); defer ast_scope.exit(); @@ -1991,7 +1991,7 @@ fn startAsyncBundle( allocator, .{ .js = dev.vm.eventLoop() }, false, // watching is handled separately - JSC.WorkPool.get(), + jsc.WorkPool.get(), heap, ); bv2.bun_watcher = dev.bun_watcher; @@ -2183,8 +2183,8 @@ fn generateClientBundle(dev: *DevServer, route_bundle: *RouteBundle) bun.OOM![]u return client_bundle; } -fn generateCssJSArray(dev: *DevServer, route_bundle: *RouteBundle) bun.JSError!JSC.JSValue { - assert(route_bundle.data == .framework); // a JSC.JSValue has no purpose, and therefore isn't implemented. +fn generateCssJSArray(dev: *DevServer, route_bundle: *RouteBundle) bun.JSError!jsc.JSValue { + assert(route_bundle.data == .framework); // a jsc.JSValue has no purpose, and therefore isn't implemented. if (Environment.allow_assert) assert(!route_bundle.data.framework.cached_css_file_array.has()); assert(route_bundle.server_state == .loaded); // page is unfit to load @@ -2203,7 +2203,7 @@ fn generateCssJSArray(dev: *DevServer, route_bundle: *RouteBundle) bun.JSError!J try dev.traceAllRouteImports(route_bundle, >s, .find_css); const names = dev.client_graph.current_css_files.items; - const arr = try JSC.JSArray.createEmpty(dev.vm.global, names.len); + const arr = try jsc.JSArray.createEmpty(dev.vm.global, names.len); for (names, 0..) |item, i| { var buf: [asset_prefix.len + @sizeOf(u64) * 2 + "/.css".len]u8 = undefined; const path = std.fmt.bufPrint(&buf, asset_prefix ++ "/{s}.css", .{ @@ -2247,9 +2247,9 @@ fn traceAllRouteImports(dev: *DevServer, route_bundle: *RouteBundle, gts: *Graph } } -fn makeArrayForServerComponentsPatch(dev: *DevServer, global: *JSC.JSGlobalObject, items: []const IncrementalGraph(.server).FileIndex) bun.JSError!JSValue { +fn makeArrayForServerComponentsPatch(dev: *DevServer, global: *jsc.JSGlobalObject, items: []const IncrementalGraph(.server).FileIndex) bun.JSError!JSValue { if (items.len == 0) return .null; - const arr = try JSC.JSArray.createEmpty(global, items.len); + const arr = try jsc.JSArray.createEmpty(global, items.len); const names = dev.server_graph.bundled_files.keys(); for (items, 0..) |item, i| { const str = bun.String.cloneUTF8(dev.relativePath(names[item.get()])); @@ -2266,7 +2266,7 @@ pub const HotUpdateContext = struct { /// bundle_v2.Graph.ast.items(.import_records) import_records: []bun.ImportRecord.List, /// bundle_v2.Graph.server_component_boundaries.slice() - scbs: bun.JSAst.ServerComponentBoundary.List.Slice, + scbs: bun.ast.ServerComponentBoundary.List.Slice, /// bundle_v2.Graph.input_files.items(.loader) loaders: []bun.options.Loader, /// Which files have a server-component boundary. @@ -2287,7 +2287,7 @@ pub const HotUpdateContext = struct { pub fn getCachedIndex( rc: *const HotUpdateContext, comptime side: bake.Side, - i: bun.JSAst.Index, + i: bun.ast.Index, ) *IncrementalGraph(side).FileIndex.Optional { const start = switch (side) { .client => 0, @@ -2433,7 +2433,7 @@ pub fn finalizeBundle( for (result.cssChunks(), result.css_file_list.values()) |*chunk, metadata| { assert(chunk.content == .css); - const index = bun.JSAst.Index.init(chunk.entry_point.source_index); + const index = bun.ast.Index.init(chunk.entry_point.source_index); const code = try chunk.intermediate_output.code( dev.allocator, @@ -2497,7 +2497,7 @@ pub fn finalizeBundle( } for (result.htmlChunks()) |*chunk| { - const index = bun.JSAst.Index.init(chunk.entry_point.source_index); + const index = bun.ast.Index.init(chunk.entry_point.source_index); const compile_result = chunk.compile_results_for_chunk[0].html; const generated_js = try dev.generateJavaScriptCodeForHTMLFile( index, @@ -2557,11 +2557,11 @@ pub fn finalizeBundle( } } for (result.htmlChunks()) |*chunk| { - const index = bun.JSAst.Index.init(chunk.entry_point.source_index); + const index = bun.ast.Index.init(chunk.entry_point.source_index); try dev.client_graph.processChunkDependencies(&ctx, .normal, index, bv2.graph.allocator); } for (result.cssChunks()) |*chunk| { - const entry_index = bun.JSAst.Index.init(chunk.entry_point.source_index); + const entry_index = bun.ast.Index.init(chunk.entry_point.source_index); try dev.client_graph.processChunkDependencies(&ctx, .css, entry_index, bv2.graph.allocator); } @@ -3867,7 +3867,7 @@ pub fn IncrementalGraph(side: bake.Side) type { pub fn receiveChunk( g: *@This(), ctx: *HotUpdateContext, - index: bun.JSAst.Index, + index: bun.ast.Index, content: union(enum) { js: struct { code: []const u8, @@ -4085,7 +4085,7 @@ pub fn IncrementalGraph(side: bake.Side) type { g: *@This(), ctx: *HotUpdateContext, comptime mode: enum { normal, css }, - bundle_graph_index: bun.JSAst.Index, + bundle_graph_index: bun.ast.Index, temp_alloc: Allocator, ) bun.OOM!void { const log = bun.Output.scoped(.processChunkDependencies, false); @@ -4140,7 +4140,7 @@ pub fn IncrementalGraph(side: bake.Side) type { // const ssr_index = ctx.scbs.getSSRIndex(bundle_graph_index.get()) orelse { // @panic("Unexpected missing server-component-boundary entry"); // }; - // try g.processChunkImportRecords(ctx, &quick_lookup, &new_imports, file_index, bun.JSAst.Index.init(ssr_index)); + // try g.processChunkImportRecords(ctx, &quick_lookup, &new_imports, file_index, bun.ast.Index.init(ssr_index)); } } @@ -4201,17 +4201,17 @@ pub fn IncrementalGraph(side: bake.Side) type { quick_lookup: *TempLookup.HashTable, new_imports: *EdgeIndex.Optional, file_index: FileIndex, - bundler_index: bun.JSAst.Index, + bundler_index: bun.ast.Index, ) !void { bun.assert(bundler_index.isValid()); bun.assert(ctx.loaders[bundler_index.get()].isCSS()); - var sfb = std.heap.stackFallback(@sizeOf(bun.JSAst.Index) * 64, temp_alloc); + var sfb = std.heap.stackFallback(@sizeOf(bun.ast.Index) * 64, temp_alloc); const queue_alloc = sfb.get(); // This queue avoids stack overflow. // Infinite loop is prevented by the tracing bits in `processEdgeAttachment`. - var queue: ArrayListUnmanaged(bun.JSAst.Index) = .empty; + var queue: ArrayListUnmanaged(bun.ast.Index) = .empty; defer queue.deinit(queue_alloc); for (ctx.import_records[bundler_index.get()].slice()) |import_record| { @@ -4361,7 +4361,7 @@ pub fn IncrementalGraph(side: bake.Side) type { quick_lookup: *TempLookup.HashTable, new_imports: *EdgeIndex.Optional, file_index: FileIndex, - index: bun.JSAst.Index, + index: bun.ast.Index, ) !void { bun.assert(index.isValid()); // don't call this function for CSS sources @@ -4727,7 +4727,7 @@ pub fn IncrementalGraph(side: bake.Side) type { /// Server CSS files are just used to be targets for graph traversal. /// Its content lives only on the client. - pub fn insertCssFileOnServer(g: *@This(), ctx: *HotUpdateContext, index: bun.JSAst.Index, abs_path: []const u8) bun.OOM!void { + pub fn insertCssFileOnServer(g: *@This(), ctx: *HotUpdateContext, index: bun.ast.Index, abs_path: []const u8) bun.OOM!void { g.owner().graph_safety_lock.assertLocked(); const dev_allocator = g.owner().allocator; @@ -5875,7 +5875,7 @@ pub const SerializedFailure = struct { try w.writeAll(data); } - // fn writeJsValue(value: JSValue, global: *JSC.JSGlobalObject, w: *Writer) !void { + // fn writeJsValue(value: JSValue, global: *jsc.JSGlobalObject, w: *Writer) !void { // if (value.isAggregateError(global)) { // // // } @@ -6595,15 +6595,15 @@ pub fn routeToBundleIndexSlow(dev: *DevServer, pattern: []const u8) ?RouteBundle const c = struct { // BakeSourceProvider.cpp - extern fn BakeGetDefaultExportFromModule(global: *JSC.JSGlobalObject, module: JSValue) JSValue; + extern fn BakeGetDefaultExportFromModule(global: *jsc.JSGlobalObject, module: JSValue) JSValue; - fn BakeLoadServerHmrPatch(global: *JSC.JSGlobalObject, code: bun.String) bun.JSError!JSValue { - const f = @extern(*const fn (*JSC.JSGlobalObject, bun.String) callconv(.c) JSValue, .{ .name = "BakeLoadServerHmrPatch" }).*; + fn BakeLoadServerHmrPatch(global: *jsc.JSGlobalObject, code: bun.String) bun.JSError!JSValue { + const f = @extern(*const fn (*jsc.JSGlobalObject, bun.String) callconv(.c) JSValue, .{ .name = "BakeLoadServerHmrPatch" }).*; return bun.jsc.fromJSHostCall(global, @src(), f, .{ global, code }); } - fn BakeLoadInitialServerCode(global: *JSC.JSGlobalObject, code: bun.String, separate_ssr_graph: bool) bun.JSError!JSValue { - const f = @extern(*const fn (*JSC.JSGlobalObject, bun.String, bool) callconv(.c) JSValue, .{ .name = "BakeLoadInitialServerCode" }).*; + fn BakeLoadInitialServerCode(global: *jsc.JSGlobalObject, code: bun.String, separate_ssr_graph: bool) bun.JSError!JSValue { + const f = @extern(*const fn (*jsc.JSGlobalObject, bun.String, bool) callconv(.c) JSValue, .{ .name = "BakeLoadInitialServerCode" }).*; return bun.jsc.fromJSHostCall(global, @src(), f, .{ global, code, separate_ssr_graph }); } }; @@ -6677,7 +6677,7 @@ pub const HotReloadEvent = struct { owner: *DevServer, /// Initialized in WatcherAtomics.watcherReleaseAndSubmitEvent - concurrent_task: JSC.ConcurrentTask, + concurrent_task: jsc.ConcurrentTask, /// The watcher is not able to peek into IncrementalGraph to know what files /// to invalidate, so the watch events are de-duplicated and passed along. /// The keys are owned by the file watcher. @@ -6998,7 +6998,7 @@ const WatcherAtomics = struct { ev.concurrent_task = .{ .auto_delete = false, .next = null, - .task = JSC.Task.init(ev), + .task = jsc.Task.init(ev), }; ev.contention_indicator.store(0, .seq_cst); ev.owner.vm.event_loop.enqueueTaskConcurrent(&ev.concurrent_task); @@ -8128,7 +8128,7 @@ const ErrorReportRequest = struct { defer temp_alloc.free(message); const browser_url = try readString32(reader, temp_alloc); defer temp_alloc.free(browser_url); - var frames: ArrayListUnmanaged(JSC.ZigStackFrame) = .empty; + var frames: ArrayListUnmanaged(jsc.ZigStackFrame) = .empty; defer frames.deinit(temp_alloc); const stack_count = @min(try reader.readInt(u32, .little), 255); // does not support more than 255 try frames.ensureTotalCapacity(temp_alloc, stack_count); @@ -8171,7 +8171,7 @@ const ErrorReportRequest = struct { var runtime_lines: ?[5][]const u8 = null; var first_line_of_interest: usize = 0; - var top_frame_position: JSC.ZigStackFramePosition = undefined; + var top_frame_position: jsc.ZigStackFramePosition = undefined; var region_of_interest_line: u32 = 0; for (frames.items) |*frame| { const source_url = frame.source_url.value.ZigString.slice(); @@ -8273,7 +8273,7 @@ const ErrorReportRequest = struct { frames.items.len = i; } - var exception: JSC.ZigException = .{ + var exception: jsc.ZigException = .{ .type = .Error, .runtime_type = .Nothing, .name = .init(name), @@ -8400,7 +8400,7 @@ const ErrorReportRequest = struct { // This function expects but does not assume the escape sequences // given are valid, and does not bubble errors up. var log = Log.init(arena); - var l: @import("../toml/toml_lexer.zig").Lexer = .{ + var l: bun.interchange.toml.Lexer = .{ .log = &log, .source = .initEmptyFile(""), .allocator = arena, @@ -8523,8 +8523,6 @@ pub fn getDeinitCountForTesting() usize { return dev_server_deinit_count_for_testing; } -const ThreadlocalArena = @import("../allocators/mimalloc_arena.zig").Arena; - const bun = @import("bun"); const AllocationScope = bun.AllocationScope; const Environment = bun.Environment; @@ -8539,19 +8537,10 @@ const DynamicBitSetUnmanaged = bun.bit_set.DynamicBitSetUnmanaged; const Log = bun.logger.Log; const MimeType = bun.http.MimeType; const RefPtr = bun.ptr.RefPtr; -const StaticRoute = bun.server.StaticRoute; +const ThreadLocalArena = bun.allocators.MimallocArena; const Transpiler = bun.transpiler.Transpiler; const EventLoopTimer = bun.api.Timer.EventLoopTimer; - -const JSC = bun.JSC; -const JSValue = JSC.JSValue; -const VirtualMachine = JSC.VirtualMachine; -const HTMLBundle = JSC.API.HTMLBundle; -const AnyBlob = JSC.WebCore.Blob.Any; -const Plugin = JSC.API.JSBundler.Plugin; - -const BunFrontendDevServerAgent = JSC.Debugger.BunFrontendDevServerAgent; -const DebuggerId = JSC.Debugger.DebuggerId; +const StaticRoute = bun.api.server.StaticRoute; const FrameworkRouter = bake.FrameworkRouter; const OpaqueFileId = FrameworkRouter.OpaqueFileId; @@ -8561,6 +8550,16 @@ const BundleV2 = bun.bundle_v2.BundleV2; const Chunk = bun.bundle_v2.Chunk; const ContentHasher = bun.bundle_v2.ContentHasher; +const jsc = bun.jsc; +const JSValue = jsc.JSValue; +const VirtualMachine = jsc.VirtualMachine; +const HTMLBundle = jsc.API.HTMLBundle; +const AnyBlob = jsc.WebCore.Blob.Any; +const Plugin = jsc.API.JSBundler.Plugin; + +const BunFrontendDevServerAgent = jsc.Debugger.BunFrontendDevServerAgent; +const DebuggerId = jsc.Debugger.DebuggerId; + const SourceMap = bun.sourcemap; const VLQ = SourceMap.VLQ; diff --git a/src/bake/FrameworkRouter.zig b/src/bake/FrameworkRouter.zig index 32e6041fef..87bfabd4e7 100644 --- a/src/bake/FrameworkRouter.zig +++ b/src/bake/FrameworkRouter.zig @@ -111,7 +111,7 @@ pub const Type = struct { /// `FrameworkRouter` itself does not use this value. server_file: OpaqueFileId, /// `FrameworkRouter` itself does not use this value. - server_file_string: JSC.Strong.Optional, + server_file_string: jsc.Strong.Optional, pub fn rootRouteIndex(type_index: Index) Route.Index { return Route.Index.init(type_index.get()); @@ -461,7 +461,7 @@ pub const Style = union(enum) { nextjs_pages, nextjs_app_ui, nextjs_app_routes, - javascript_defined: JSC.Strong.Optional, + javascript_defined: jsc.Strong.Optional, pub const map = bun.ComptimeStringMap(Style, .{ .{ "nextjs-pages", .nextjs_pages }, @@ -470,7 +470,7 @@ pub const Style = union(enum) { }); pub const error_message = "'style' must be either \"nextjs-pages\", \"nextjs-app-ui\", \"nextjs-app-routes\", or a function."; - pub fn fromJS(value: JSValue, global: *JSC.JSGlobalObject) !Style { + pub fn fromJS(value: JSValue, global: *jsc.JSGlobalObject) !Style { if (value.isString()) { const bun_string = try value.toBunString(global); var sfa = std.heap.stackFallback(4096, bun.default_allocator); @@ -1129,7 +1129,7 @@ fn scanInner( /// production usage. It uses a slower but easier to use pattern for object /// creation. A production-grade JS api would be able to re-use objects. pub const JSFrameworkRouter = struct { - pub const js = JSC.Codegen.JSFrameworkFileSystemRouter; + pub const js = jsc.Codegen.JSFrameworkFileSystemRouter; pub const toJS = js.toJS; pub const fromJS = js.fromJS; @@ -1141,16 +1141,16 @@ pub const JSFrameworkRouter = struct { log: TinyLog, }), - const validators = bun.JSC.Node.validators; + const validators = bun.jsc.Node.validators; - pub fn getBindings(global: *JSC.JSGlobalObject) bun.JSError!JSC.JSValue { - return (try JSC.JSObject.create(.{ + pub fn getBindings(global: *jsc.JSGlobalObject) bun.JSError!jsc.JSValue { + return (try jsc.JSObject.create(.{ .parseRoutePattern = global.createHostFunction("parseRoutePattern", parseRoutePattern, 1), .FrameworkRouter = js.getConstructor(global), }, global)).toJS(); } - pub fn constructor(global: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!*JSFrameworkRouter { + pub fn constructor(global: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!*JSFrameworkRouter { const opts = callframe.argumentsAsArray(1)[0]; if (!opts.isObject()) return global.throwInvalidArguments("FrameworkRouter needs an object as it's first argument", .{}); @@ -1210,7 +1210,7 @@ pub const JSFrameworkRouter = struct { return jsfr; } - pub fn match(jsfr: *JSFrameworkRouter, global: *JSGlobalObject, callframe: *JSC.CallFrame) !JSValue { + pub fn match(jsfr: *JSFrameworkRouter, global: *JSGlobalObject, callframe: *jsc.CallFrame) !JSValue { const path_js = callframe.argumentsAsArray(1)[0]; const path_str = try path_js.toBunString(global); defer path_str.deref(); @@ -1222,7 +1222,7 @@ pub const JSFrameworkRouter = struct { var sfb = std.heap.stackFallback(4096, bun.default_allocator); const alloc = sfb.get(); - return (try JSC.JSObject.create(.{ + return (try jsc.JSObject.create(.{ .params = if (params_out.params.len > 0) params: { const obj = JSValue.createEmptyObject(global, params_out.params.len); for (params_out.params.slice()) |param| { @@ -1239,7 +1239,7 @@ pub const JSFrameworkRouter = struct { return .null; } - pub fn toJSON(jsfr: *JSFrameworkRouter, global: *JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { + pub fn toJSON(jsfr: *JSFrameworkRouter, global: *JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { _ = callframe; var sfb = std.heap.stackFallback(4096, bun.default_allocator); @@ -1250,7 +1250,7 @@ pub const JSFrameworkRouter = struct { fn routeToJson(jsfr: *JSFrameworkRouter, global: *JSGlobalObject, route_index: Route.Index, allocator: Allocator) !JSValue { const route = jsfr.router.routePtr(route_index); - return (try JSC.JSObject.create(.{ + return (try jsc.JSObject.create(.{ .part = try partToJS(global, route.part, allocator), .page = jsfr.fileIdToJS(global, route.file_page), .layout = jsfr.fileIdToJS(global, route.file_layout), @@ -1274,7 +1274,7 @@ pub const JSFrameworkRouter = struct { fn routeToJsonInverse(jsfr: *JSFrameworkRouter, global: *JSGlobalObject, route_index: Route.Index, allocator: Allocator) !JSValue { const route = jsfr.router.routePtr(route_index); - return (try JSC.JSObject.create(.{ + return (try jsc.JSObject.create(.{ .part = try partToJS(global, route.part, allocator), .page = jsfr.fileIdToJS(global, route.file_page), .layout = jsfr.fileIdToJS(global, route.file_layout), @@ -1368,10 +1368,10 @@ const std = @import("std"); const bun = @import("bun"); const strings = bun.strings; -const JSC = bun.JSC; -const CallFrame = JSC.CallFrame; -const JSGlobalObject = JSC.JSGlobalObject; -const JSValue = JSC.JSValue; +const jsc = bun.jsc; +const CallFrame = jsc.CallFrame; +const JSGlobalObject = jsc.JSGlobalObject; +const JSValue = jsc.JSValue; const DirInfo = bun.resolver.DirInfo; const Resolver = bun.resolver.Resolver; diff --git a/src/bake/production.zig b/src/bake/production.zig index a5dffd479f..9129faeb1a 100644 --- a/src/bake/production.zig +++ b/src/bake/production.zig @@ -1,7 +1,7 @@ //! Implements building a Bake application to production const log = bun.Output.scoped(.production, false); -pub fn buildCommand(ctx: bun.CLI.Command.Context) !void { +pub fn buildCommand(ctx: bun.cli.Command.Context) !void { bun.bake.printWarning(); if (ctx.args.entry_points.len > 1) { @@ -22,9 +22,9 @@ pub fn buildCommand(ctx: bun.CLI.Command.Context) !void { // Create a VM + global for loading the config file, plugins, and // performing build time prerendering. - bun.JSC.initialize(false); - bun.JSAst.Expr.Data.Store.create(); - bun.JSAst.Stmt.Data.Store.create(); + bun.jsc.initialize(false); + bun.ast.Expr.Data.Store.create(); + bun.ast.Stmt.Data.Store.create(); var arena = try bun.MimallocArena.init(); defer arena.deinit(); @@ -76,9 +76,9 @@ pub fn buildCommand(ctx: bun.CLI.Command.Context) !void { bun.http.AsyncHTTP.loadEnv(vm.allocator, vm.log, b.env); vm.loadExtraEnvAndSourceCodePrinter(); vm.is_main_thread = true; - JSC.VirtualMachine.is_main_thread_vm = true; + jsc.VirtualMachine.is_main_thread_vm = true; - const api_lock = vm.jsc.getAPILock(); + const api_lock = vm.jsc_vm.getAPILock(); defer api_lock.release(); var pt: PerThread = .{ @@ -135,7 +135,7 @@ pub fn writeSourcemapToDisk( ); } -pub fn buildWithVm(ctx: bun.CLI.Command.Context, cwd: []const u8, vm: *VirtualMachine, pt: *PerThread) !void { +pub fn buildWithVm(ctx: bun.cli.Command.Context, cwd: []const u8, vm: *VirtualMachine, pt: *PerThread) !void { // Load and evaluate the configuration module const global = vm.global; const b = &vm.transpiler; @@ -170,14 +170,14 @@ pub fn buildWithVm(ctx: bun.CLI.Command.Context, cwd: []const u8, vm: *VirtualMa const config_entry_point_string = bun.String.cloneUTF8(config_entry_point.pathConst().?.text); defer config_entry_point_string.deref(); - const config_promise = bun.JSC.JSModuleLoader.loadAndEvaluateModule(global, &config_entry_point_string) orelse { + const config_promise = bun.jsc.JSModuleLoader.loadAndEvaluateModule(global, &config_entry_point_string) orelse { bun.assert(global.hasException()); return error.JSError; }; - config_promise.setHandled(vm.jsc); + config_promise.setHandled(vm.jsc_vm); vm.waitForPromise(.{ .internal = config_promise }); - var options = switch (config_promise.unwrap(vm.jsc, .mark_handled)) { + var options = switch (config_promise.unwrap(vm.jsc_vm, .mark_handled)) { .pending => unreachable, .fulfilled => |resolved| config: { bun.assert(resolved.isUndefined()); @@ -674,9 +674,9 @@ pub fn buildWithVm(ctx: bun.CLI.Command.Context, cwd: []const u8, vm: *VirtualMa route_param_info, route_style_references, ); - render_promise.setHandled(vm.jsc); + render_promise.setHandled(vm.jsc_vm); vm.waitForPromise(.{ .normal = render_promise }); - switch (render_promise.unwrap(vm.jsc, .mark_handled)) { + switch (render_promise.unwrap(vm.jsc_vm, .mark_handled)) { .pending => unreachable, .fulfilled => { Output.prettyln("done", .{}); @@ -691,9 +691,9 @@ pub fn buildWithVm(ctx: bun.CLI.Command.Context, cwd: []const u8, vm: *VirtualMa /// unsafe function, must be run outside of the event loop /// quits the process on exception -fn loadModule(vm: *VirtualMachine, global: *JSC.JSGlobalObject, key: JSValue) !JSValue { +fn loadModule(vm: *VirtualMachine, global: *jsc.JSGlobalObject, key: JSValue) !JSValue { const promise = BakeLoadModuleByKey(global, key).asAnyPromise().?.internal; - promise.setHandled(vm.jsc); + promise.setHandled(vm.jsc_vm); vm.waitForPromise(.{ .internal = promise }); // TODO: Specially draining microtasks here because `waitForPromise` has a // bug which forgets to do it, but I don't want to fix it right now as it @@ -701,7 +701,7 @@ fn loadModule(vm: *VirtualMachine, global: *JSC.JSGlobalObject, key: JSValue) !J vm.eventLoop().drainMicrotasks() catch { bun.Global.crash(); }; - switch (promise.unwrap(vm.jsc, .mark_handled)) { + switch (promise.unwrap(vm.jsc_vm, .mark_handled)) { .pending => unreachable, .fulfilled => |val| { bun.assert(val.isUndefined()); @@ -716,12 +716,12 @@ fn loadModule(vm: *VirtualMachine, global: *JSC.JSGlobalObject, key: JSValue) !J // extern apis: // TODO: Dedupe -extern fn BakeGetDefaultExportFromModule(global: *JSC.JSGlobalObject, key: JSValue) JSValue; -extern fn BakeGetModuleNamespace(global: *JSC.JSGlobalObject, key: JSValue) JSValue; -extern fn BakeLoadModuleByKey(global: *JSC.JSGlobalObject, key: JSValue) JSValue; +extern fn BakeGetDefaultExportFromModule(global: *jsc.JSGlobalObject, key: JSValue) JSValue; +extern fn BakeGetModuleNamespace(global: *jsc.JSGlobalObject, key: JSValue) JSValue; +extern fn BakeLoadModuleByKey(global: *jsc.JSGlobalObject, key: JSValue) JSValue; -fn BakeGetOnModuleNamespace(global: *JSC.JSGlobalObject, module: JSValue, property: []const u8) ?JSValue { - const f = @extern(*const fn (*JSC.JSGlobalObject, JSValue, [*]const u8, usize) callconv(.C) JSValue, .{ +fn BakeGetOnModuleNamespace(global: *jsc.JSGlobalObject, module: JSValue, property: []const u8) ?JSValue { + const f = @extern(*const fn (*jsc.JSGlobalObject, JSValue, [*]const u8, usize) callconv(.C) JSValue, .{ .name = "BakeGetOnModuleNamespace", }); const result: JSValue = f(global, module, property.ptr, property.len); @@ -731,7 +731,7 @@ fn BakeGetOnModuleNamespace(global: *JSC.JSGlobalObject, module: JSValue, proper /// Renders all routes for static site generation by calling the JavaScript implementation. extern fn BakeRenderRoutesForProdStatic( - *JSC.JSGlobalObject, + *jsc.JSGlobalObject, /// Output directory path (e.g., "./dist") out_base: bun.String, /// Server module paths (e.g., ["bake://page.js", "bake://layout.js"]) @@ -754,12 +754,12 @@ extern fn BakeRenderRoutesForProdStatic( param_information: JSValue, /// CSS URLs per route (e.g., [["/main.css"], ["/main.css", "/blog.css"]]) styles: JSValue, -) *JSC.JSPromise; +) *jsc.JSPromise; /// The result of this function is a JSValue that wont be garbage collected, as /// it will always have at least one reference by the module loader. -fn BakeRegisterProductionChunk(global: *JSC.JSGlobalObject, key: bun.String, source_code: bun.String) bun.JSError!JSValue { - const f = @extern(*const fn (*JSC.JSGlobalObject, bun.String, bun.String) callconv(.C) JSValue, .{ +fn BakeRegisterProductionChunk(global: *jsc.JSGlobalObject, key: bun.String, source_code: bun.String) bun.JSError!JSValue { + const f = @extern(*const fn (*jsc.JSGlobalObject, bun.String, bun.String) callconv(.C) JSValue, .{ .name = "BakeRegisterProductionChunk", }); const result: JSValue = f(global, key, source_code); @@ -783,14 +783,14 @@ pub export fn BakeToWindowsPath(input: bun.String) callconv(.C) bun.String { return bun.String.cloneUTF16(output_slice); } -pub export fn BakeProdResolve(global: *JSC.JSGlobalObject, a_str: bun.String, specifier_str: bun.String) callconv(.C) bun.String { +pub export fn BakeProdResolve(global: *jsc.JSGlobalObject, a_str: bun.String, specifier_str: bun.String) callconv(.C) bun.String { var sfa = std.heap.stackFallback(@sizeOf(bun.PathBuffer) * 2, bun.default_allocator); const alloc = sfa.get(); const specifier = specifier_str.toUTF8(alloc); defer specifier.deinit(); - if (JSC.ModuleLoader.HardcodedModule.Alias.get(specifier.slice(), .bun)) |alias| { + if (jsc.ModuleLoader.HardcodedModule.Alias.get(specifier.slice(), .bun)) |alias| { return bun.String.static(alias.path); } @@ -902,11 +902,11 @@ pub const PerThread = struct { source_maps: bun.StringArrayHashMapUnmanaged(OutputFile.Index), // Thread-local - vm: *JSC.VirtualMachine, + vm: *jsc.VirtualMachine, /// Indexed by entry point index (OpaqueFileId) loaded_files: bun.bit_set.AutoBitSet, /// JSArray of JSString, indexed by entry point index (OpaqueFileId) - all_server_files: JSC.JSValue, + all_server_files: jsc.JSValue, /// Sent to other threads for rendering pub const Options = struct { @@ -921,7 +921,7 @@ pub const PerThread = struct { source_maps: bun.StringArrayHashMapUnmanaged(OutputFile.Index), }; - extern fn BakeGlobalObject__attachPerThreadData(global: *JSC.JSGlobalObject, pt: ?*PerThread) void; + extern fn BakeGlobalObject__attachPerThreadData(global: *jsc.JSGlobalObject, pt: ?*PerThread) void; /// After initializing, call `attach` pub fn init(vm: *VirtualMachine, opts: Options) !PerThread { @@ -1043,9 +1043,9 @@ const Output = bun.Output; const bake = bun.bake; const OutputFile = bun.options.OutputFile; -const JSC = bun.JSC; -const JSValue = JSC.JSValue; -const VirtualMachine = JSC.VirtualMachine; - const FrameworkRouter = bake.FrameworkRouter; const OpaqueFileId = FrameworkRouter.OpaqueFileId; + +const jsc = bun.jsc; +const JSValue = jsc.JSValue; +const VirtualMachine = jsc.VirtualMachine; diff --git a/src/base64/base64.zig b/src/base64/base64.zig index 74806e403b..5ce27780b2 100644 --- a/src/base64/base64.zig +++ b/src/base64/base64.zig @@ -99,7 +99,7 @@ pub fn urlSafeEncodeLen(source: anytype) usize { } extern fn WTF__base64URLEncode(input: [*]const u8, input_len: usize, output: [*]u8, output_len: usize) usize; pub fn encodeURLSafe(dest: []u8, source: []const u8) usize { - bun.JSC.markBinding(@src()); + bun.jsc.markBinding(@src()); return WTF__base64URLEncode(source.ptr, source.len, dest.ptr, dest.len); } diff --git a/src/boringssl.zig b/src/boringssl.zig index 19baecda0a..16e2d500d7 100644 --- a/src/boringssl.zig +++ b/src/boringssl.zig @@ -59,18 +59,18 @@ pub fn initClient() *boring.SSL { // may result in deadlocks, crashes, or memory corruption. export fn OPENSSL_memory_alloc(size: usize) ?*anyopaque { - return bun.Mimalloc.mi_malloc(size); + return bun.mimalloc.mi_malloc(size); } // BoringSSL always expects memory to be zero'd export fn OPENSSL_memory_free(ptr: *anyopaque) void { - const len = bun.Mimalloc.mi_usable_size(ptr); + const len = bun.mimalloc.mi_usable_size(ptr); @memset(@as([*]u8, @ptrCast(ptr))[0..len], 0); - bun.Mimalloc.mi_free(ptr); + bun.mimalloc.mi_free(ptr); } export fn OPENSSL_memory_get_size(ptr: ?*const anyopaque) usize { - return bun.Mimalloc.mi_usable_size(ptr); + return bun.mimalloc.mi_usable_size(ptr); } const INET6_ADDRSTRLEN = if (bun.Environment.isWindows) 65 else 46; @@ -203,7 +203,7 @@ pub fn checkServerIdentity( return false; } -pub fn ERR_toJS(globalThis: *JSC.JSGlobalObject, err_code: u32) JSC.JSValue { +pub fn ERR_toJS(globalThis: *jsc.JSGlobalObject, err_code: u32) jsc.JSValue { var outbuf: [128 + 1 + "BoringSSL ".len]u8 = undefined; @memset(&outbuf, 0); outbuf[0.."BoringSSL ".len].* = "BoringSSL ".*; @@ -226,5 +226,5 @@ const c_ares = @import("./deps/c_ares.zig"); const std = @import("std"); const bun = @import("bun"); -const JSC = bun.JSC; +const jsc = bun.jsc; const strings = bun.strings; diff --git a/src/brotli.zig b/src/brotli.zig index 3895a7e9dc..29619839cb 100644 --- a/src/brotli.zig +++ b/src/brotli.zig @@ -282,4 +282,4 @@ pub const BrotliCompressionStream = struct { const std = @import("std"); const bun = @import("bun"); -const mimalloc = bun.Mimalloc; +const mimalloc = bun.mimalloc; diff --git a/src/btjs.zig b/src/btjs.zig index 0881a784dc..7f1f6c0b48 100644 --- a/src/btjs.zig +++ b/src/btjs.zig @@ -89,9 +89,9 @@ fn printSourceAtAddress(debug_info: *std.debug.SelfInfo, out_stream: anytype, ad } const do_llint = probably_llint and allow_llint; - const frame: *const bun.JSC.CallFrame = @ptrFromInt(fp); + const frame: *const bun.jsc.CallFrame = @ptrFromInt(fp); if (do_llint) { - const srcloc = frame.getCallerSrcLoc(bun.JSC.VirtualMachine.get().global); + const srcloc = frame.getCallerSrcLoc(bun.jsc.VirtualMachine.get().global); try tty_config.setColor(out_stream, .bold); try out_stream.print("{s}:{d}:{d}: ", .{ srcloc.str, srcloc.line, srcloc.column }); try tty_config.setColor(out_stream, .reset); diff --git a/src/bun_js.zig b/src/bun.js.zig similarity index 90% rename from src/bun_js.zig rename to src/bun.js.zig index 66a0d0d453..d05a6818ea 100644 --- a/src/bun_js.zig +++ b/src/bun.js.zig @@ -1,4 +1,7 @@ -var run: Run = undefined; +pub const jsc = @import("./bun.js/jsc.zig"); +pub const webcore = @import("./bun.js/webcore.zig"); +pub const api = @import("./bun.js/api.zig"); + pub const Run = struct { ctx: Command.Context, vm: *VirtualMachine, @@ -7,10 +10,12 @@ pub const Run = struct { any_unhandled: bool = false, is_html_entrypoint: bool = false, + var run: Run = undefined; + pub fn bootStandalone(ctx: Command.Context, entry_path: string, graph: bun.StandaloneModuleGraph) !void { - JSC.markBinding(@src()); - bun.JSC.initialize(false); - bun.Analytics.Features.standalone_executable += 1; + jsc.markBinding(@src()); + bun.jsc.initialize(false); + bun.analytics.Features.standalone_executable += 1; const graph_ptr = try bun.default_allocator.create(bun.StandaloneModuleGraph); graph_ptr.* = graph; @@ -21,7 +26,7 @@ pub const Run = struct { var arena = try Arena.init(); if (!ctx.debug.loaded_bunfig) { - try bun.CLI.Arguments.loadConfigPath(ctx.allocator, true, "bunfig.toml", ctx, .RunCommand); + try bun.cli.Arguments.loadConfigPath(ctx.allocator, true, "bunfig.toml", ctx, .RunCommand); } run = .{ @@ -86,7 +91,7 @@ pub const Run = struct { vm.loadExtraEnvAndSourceCodePrinter(); vm.is_main_thread = true; - JSC.VirtualMachine.is_main_thread_vm = true; + jsc.VirtualMachine.is_main_thread_vm = true; doPreconnect(ctx.runtime_options.preconnect); @@ -131,16 +136,16 @@ pub const Run = struct { null, ); try bundle.runEnvLoader(false); - const mini = JSC.MiniEventLoop.initGlobal(bundle.env); + const mini = jsc.MiniEventLoop.initGlobal(bundle.env); mini.top_level_dir = ctx.args.absolute_working_dir orelse ""; return bun.shell.Interpreter.initAndRunFromFile(ctx, mini, entry_path); } pub fn boot(ctx: Command.Context, entry_path: string, loader: ?bun.options.Loader) !void { - JSC.markBinding(@src()); + jsc.markBinding(@src()); if (!ctx.debug.loaded_bunfig) { - try bun.CLI.Arguments.loadConfigPath(ctx.allocator, true, "bunfig.toml", ctx, .RunCommand); + try bun.cli.Arguments.loadConfigPath(ctx.allocator, true, "bunfig.toml", ctx, .RunCommand); } // The shell does not need to initialize JSC. @@ -151,7 +156,7 @@ pub const Run = struct { return; } - bun.JSC.initialize(ctx.runtime_options.eval.eval_and_print); + bun.jsc.initialize(ctx.runtime_options.eval.eval_and_print); js_ast.Expr.Data.Store.create(); js_ast.Stmt.Data.Store.create(); @@ -231,12 +236,12 @@ pub const Run = struct { vm.loadExtraEnvAndSourceCodePrinter(); vm.is_main_thread = true; - JSC.VirtualMachine.is_main_thread_vm = true; + jsc.VirtualMachine.is_main_thread_vm = true; // Allow setting a custom timezone if (vm.transpiler.env.get("TZ")) |tz| { if (tz.len > 0) { - _ = vm.global.setTimeZone(&JSC.ZigString.init(tz)); + _ = vm.global.setTimeZone(&jsc.ZigString.init(tz)); } } @@ -250,7 +255,7 @@ pub const Run = struct { vm.global.vm().holdAPILock(&run, callback); } - fn onUnhandledRejectionBeforeClose(this: *JSC.VirtualMachine, _: *JSC.JSGlobalObject, value: JSC.JSValue) void { + fn onUnhandledRejectionBeforeClose(this: *jsc.VirtualMachine, _: *jsc.JSGlobalObject, value: jsc.JSValue) void { this.runErrorHandler(value, this.onUnhandledRejectionExceptionList); run.any_unhandled = true; } @@ -307,8 +312,8 @@ pub const Run = struct { } switch (this.ctx.debug.hot_reload) { - .hot => JSC.hot_reloader.HotReloader.enableHotModuleReloading(vm), - .watch => JSC.hot_reloader.WatchReloader.enableHotModuleReloading(vm), + .hot => jsc.hot_reloader.HotReloader.enableHotModuleReloading(vm), + .watch => jsc.hot_reloader.WatchReloader.enableHotModuleReloading(vm), else => {}, } @@ -332,7 +337,7 @@ pub const Run = struct { if (run.any_unhandled) { printed_sourcemap_warning_and_version = true; - bun.JSC.SavedSourceMap.MissingSourceMapNoteInfo.print(); + bun.jsc.SavedSourceMap.MissingSourceMapNoteInfo.print(); Output.prettyErrorln( "\n{s}", @@ -363,7 +368,7 @@ pub const Run = struct { vm.onExit(); if (run.any_unhandled) { printed_sourcemap_warning_and_version = true; - bun.JSC.SavedSourceMap.MissingSourceMapNoteInfo.print(); + bun.jsc.SavedSourceMap.MissingSourceMapNoteInfo.print(); Output.prettyErrorln( "\n{s}", @@ -411,9 +416,9 @@ pub const Run = struct { if (this.ctx.runtime_options.eval.eval_and_print) { const to_print = brk: { - const result: JSC.JSValue = vm.entry_point_result.value.get() orelse .js_undefined; + const result: jsc.JSValue = vm.entry_point_result.value.get() orelse .js_undefined; if (result.asAnyPromise()) |promise| { - switch (promise.status(vm.jsc)) { + switch (promise.status(vm.jsc_vm)) { .pending => { result._then2(vm.global, .js_undefined, Bun__onResolveEntryPointResult, Bun__onRejectEntryPointResult); @@ -427,7 +432,7 @@ pub const Run = struct { break :brk result; }, - else => break :brk promise.result(vm.jsc), + else => break :brk promise.result(vm.jsc_vm), } } @@ -453,7 +458,7 @@ pub const Run = struct { if (this.any_unhandled and !printed_sourcemap_warning_and_version) { this.vm.exit_handler.exit_code = 1; - bun.JSC.SavedSourceMap.MissingSourceMapNoteInfo.print(); + bun.jsc.SavedSourceMap.MissingSourceMapNoteInfo.print(); Output.prettyErrorln( "\n{s}", @@ -479,7 +484,7 @@ pub const Run = struct { } }; -pub export fn Bun__onResolveEntryPointResult(global: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) callconv(JSC.conv) noreturn { +pub export fn Bun__onResolveEntryPointResult(global: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) callconv(jsc.conv) noreturn { const arguments = callframe.arguments_old(1).slice(); const result = arguments[0]; result.print(global, .Log, .Log); @@ -487,7 +492,7 @@ pub export fn Bun__onResolveEntryPointResult(global: *JSC.JSGlobalObject, callfr return .js_undefined; } -pub export fn Bun__onRejectEntryPointResult(global: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) callconv(JSC.conv) noreturn { +pub export fn Bun__onRejectEntryPointResult(global: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) callconv(jsc.conv) noreturn { const arguments = callframe.arguments_old(1).slice(); const result = arguments[0]; result.print(global, .Log, .Log); @@ -495,7 +500,7 @@ pub export fn Bun__onRejectEntryPointResult(global: *JSC.JSGlobalObject, callfra return .js_undefined; } -noinline fn dumpBuildError(vm: *JSC.VirtualMachine) void { +noinline fn dumpBuildError(vm: *jsc.VirtualMachine) void { @branchHint(.cold); Output.flush(); @@ -511,30 +516,30 @@ noinline fn dumpBuildError(vm: *JSC.VirtualMachine) void { vm.log.print(writer) catch {}; } -pub noinline fn failWithBuildError(vm: *JSC.VirtualMachine) noreturn { +pub noinline fn failWithBuildError(vm: *jsc.VirtualMachine) noreturn { @branchHint(.cold); dumpBuildError(vm); Global.exit(1); } +const OpaqueWrap = jsc.OpaqueWrap; +const VirtualMachine = jsc.VirtualMachine; + +const string = []const u8; + const options = @import("./options.zig"); const std = @import("std"); -const Arena = @import("./allocators/mimalloc_arena.zig").Arena; const Command = @import("./cli.zig").Command; -const DNSResolver = @import("./bun.js/api/bun/dns_resolver.zig").DNSResolver; const which = @import("./which.zig").which; const bun = @import("bun"); const Global = bun.Global; const Output = bun.Output; const default_allocator = bun.default_allocator; -const js_ast = bun.JSAst; +const js_ast = bun.ast; const logger = bun.logger; -const string = bun.string; const strings = bun.strings; const transpiler = bun.transpiler; +const Arena = bun.allocators.MimallocArena; const AsyncHTTP = bun.http.AsyncHTTP; - -const JSC = bun.JSC; -const OpaqueWrap = JSC.OpaqueWrap; -const VirtualMachine = JSC.VirtualMachine; +const DNSResolver = bun.api.dns.Resolver; diff --git a/src/bun.js/BuildMessage.zig b/src/bun.js/BuildMessage.zig index 2a3f0e5151..8855b9ef38 100644 --- a/src/bun.js/BuildMessage.zig +++ b/src/bun.js/BuildMessage.zig @@ -1,5 +1,5 @@ pub const BuildMessage = struct { - pub const js = JSC.Codegen.JSBuildMessage; + pub const js = jsc.Codegen.JSBuildMessage; pub const toJS = js.toJS; pub const fromJS = js.fromJS; pub const fromJSDirect = js.fromJSDirect; @@ -9,13 +9,13 @@ pub const BuildMessage = struct { allocator: std.mem.Allocator, logged: bool = false, - pub fn constructor(globalThis: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!*BuildMessage { + pub fn constructor(globalThis: *jsc.JSGlobalObject, _: *jsc.CallFrame) bun.JSError!*BuildMessage { return globalThis.throw("BuildMessage is not constructable", .{}); } - pub fn getNotes(this: *BuildMessage, globalThis: *JSC.JSGlobalObject) bun.JSError!JSC.JSValue { + pub fn getNotes(this: *BuildMessage, globalThis: *jsc.JSGlobalObject) bun.JSError!jsc.JSValue { const notes = this.msg.notes; - const array = try JSC.JSValue.createEmptyArray(globalThis, notes.len); + const array = try jsc.JSValue.createEmptyArray(globalThis, notes.len); for (notes, 0..) |note, i| { const cloned = try note.clone(bun.default_allocator); try array.putIndex( @@ -28,7 +28,7 @@ pub const BuildMessage = struct { return array; } - pub fn toStringFn(this: *BuildMessage, globalThis: *JSC.JSGlobalObject) JSC.JSValue { + pub fn toStringFn(this: *BuildMessage, globalThis: *jsc.JSGlobalObject) jsc.JSValue { const text = std.fmt.allocPrint(default_allocator, "BuildMessage: {s}", .{this.msg.data.text}) catch { return globalThis.throwOutOfMemoryValue(); }; @@ -44,11 +44,11 @@ pub const BuildMessage = struct { } pub fn create( - globalThis: *JSC.JSGlobalObject, + globalThis: *jsc.JSGlobalObject, allocator: std.mem.Allocator, msg: logger.Msg, // resolve_result: *const Resolver.Result, - ) bun.OOM!JSC.JSValue { + ) bun.OOM!jsc.JSValue { var build_error = try allocator.create(BuildMessage); build_error.* = BuildMessage{ .msg = try msg.clone(allocator), @@ -61,22 +61,22 @@ pub const BuildMessage = struct { pub fn toString( this: *BuildMessage, - globalThis: *JSC.JSGlobalObject, - _: *JSC.CallFrame, - ) bun.JSError!JSC.JSValue { + globalThis: *jsc.JSGlobalObject, + _: *jsc.CallFrame, + ) bun.JSError!jsc.JSValue { return this.toStringFn(globalThis); } pub fn toPrimitive( this: *BuildMessage, - globalThis: *JSC.JSGlobalObject, - callframe: *JSC.CallFrame, - ) bun.JSError!JSC.JSValue { + globalThis: *jsc.JSGlobalObject, + callframe: *jsc.CallFrame, + ) bun.JSError!jsc.JSValue { const args_ = callframe.arguments_old(1); const args = args_.ptr[0..args_.len]; if (args.len > 0) { if (!args[0].isString()) { - return JSC.JSValue.jsNull(); + return jsc.JSValue.jsNull(); } const str = try args[0].getZigString(globalThis); @@ -85,15 +85,15 @@ pub const BuildMessage = struct { } } - return JSC.JSValue.jsNull(); + return jsc.JSValue.jsNull(); } pub fn toJSON( this: *BuildMessage, - globalThis: *JSC.JSGlobalObject, - _: *JSC.CallFrame, - ) bun.JSError!JSC.JSValue { - var object = JSC.JSValue.createEmptyObject(globalThis, 4); + globalThis: *jsc.JSGlobalObject, + _: *jsc.CallFrame, + ) bun.JSError!jsc.JSValue { + var object = jsc.JSValue.createEmptyObject(globalThis, 4); object.put(globalThis, ZigString.static("name"), bun.String.static("BuildMessage").toJS(globalThis)); object.put(globalThis, ZigString.static("position"), this.getPosition(globalThis)); object.put(globalThis, ZigString.static("message"), this.getMessage(globalThis)); @@ -101,9 +101,9 @@ pub const BuildMessage = struct { return object; } - pub fn generatePositionObject(msg: logger.Msg, globalThis: *JSC.JSGlobalObject) JSC.JSValue { - const location = msg.data.location orelse return JSC.JSValue.jsNull(); - var object = JSC.JSValue.createEmptyObject(globalThis, 7); + pub fn generatePositionObject(msg: logger.Msg, globalThis: *jsc.JSGlobalObject) jsc.JSValue { + const location = msg.data.location orelse return jsc.JSValue.jsNull(); + var object = jsc.JSValue.createEmptyObject(globalThis, 7); object.put( globalThis, @@ -145,40 +145,40 @@ pub const BuildMessage = struct { } // https://github.com/oven-sh/bun/issues/2375#issuecomment-2121530202 - pub fn getColumn(this: *BuildMessage, _: *JSC.JSGlobalObject) JSC.JSValue { + pub fn getColumn(this: *BuildMessage, _: *jsc.JSGlobalObject) jsc.JSValue { if (this.msg.data.location) |location| { - return JSC.JSValue.jsNumber(@max(location.column - 1, 0)); + return jsc.JSValue.jsNumber(@max(location.column - 1, 0)); } - return JSC.JSValue.jsNumber(@as(i32, 0)); + return jsc.JSValue.jsNumber(@as(i32, 0)); } - pub fn getLine(this: *BuildMessage, _: *JSC.JSGlobalObject) JSC.JSValue { + pub fn getLine(this: *BuildMessage, _: *jsc.JSGlobalObject) jsc.JSValue { if (this.msg.data.location) |location| { - return JSC.JSValue.jsNumber(@max(location.line - 1, 0)); + return jsc.JSValue.jsNumber(@max(location.line - 1, 0)); } - return JSC.JSValue.jsNumber(@as(i32, 0)); + return jsc.JSValue.jsNumber(@as(i32, 0)); } pub fn getPosition( this: *BuildMessage, - globalThis: *JSC.JSGlobalObject, - ) JSC.JSValue { + globalThis: *jsc.JSGlobalObject, + ) jsc.JSValue { return BuildMessage.generatePositionObject(this.msg, globalThis); } pub fn getMessage( this: *BuildMessage, - globalThis: *JSC.JSGlobalObject, - ) JSC.JSValue { + globalThis: *jsc.JSGlobalObject, + ) jsc.JSValue { return ZigString.init(this.msg.data.text).toJS(globalThis); } pub fn getLevel( this: *BuildMessage, - globalThis: *JSC.JSGlobalObject, - ) JSC.JSValue { + globalThis: *jsc.JSGlobalObject, + ) jsc.JSValue { return ZigString.init(this.msg.kind.string()).toJS(globalThis); } @@ -187,15 +187,16 @@ pub const BuildMessage = struct { } }; +const string = []const u8; + const std = @import("std"); const Resolver = @import("../resolver//resolver.zig").Resolver; const bun = @import("bun"); const default_allocator = bun.default_allocator; const logger = bun.logger; -const string = bun.string; -const JSC = bun.JSC; -const JSGlobalObject = JSC.JSGlobalObject; -const JSValue = JSC.JSValue; -const ZigString = JSC.ZigString; +const jsc = bun.jsc; +const JSGlobalObject = jsc.JSGlobalObject; +const JSValue = jsc.JSValue; +const ZigString = jsc.ZigString; diff --git a/src/bun.js/ConsoleObject.zig b/src/bun.js/ConsoleObject.zig index b861deee97..7de4672170 100644 --- a/src/bun.js/ConsoleObject.zig +++ b/src/bun.js/ConsoleObject.zig @@ -66,7 +66,7 @@ pub fn messageWithTypeAndLevel( global: *JSGlobalObject, vals: [*]const JSValue, len: usize, -) callconv(JSC.conv) void { +) callconv(jsc.conv) void { messageWithTypeAndLevel_(ctype, message_type, level, global, vals, len) catch |err| switch (err) { error.JSError => {}, error.OutOfMemory => global.throwOutOfMemory() catch {}, // TODO: properly propagate exception upwards @@ -362,7 +362,7 @@ pub const TablePrinter = struct { } } } else { - var cols_iter = try JSC.JSPropertyIterator(.{ + var cols_iter = try jsc.JSPropertyIterator(.{ .skip_empty_name = false, .include_value = true, }).init(this.globalObject, obj); @@ -523,7 +523,7 @@ pub const TablePrinter = struct { // if the "properties" arg was provided, pre-populate the columns if (!this.properties.isUndefined()) { - var properties_iter = try JSC.JSArrayIterator.init(this.properties, globalObject); + var properties_iter = try jsc.JSArrayIterator.init(this.properties, globalObject); while (try properties_iter.next()) |value| { try columns.append(.{ .name = try value.toBunString(globalObject), @@ -536,7 +536,7 @@ pub const TablePrinter = struct { if (this.is_iterable) { var ctx_: struct { this: *TablePrinter, columns: *@TypeOf(columns), idx: u32 = 0, err: bool = false } = .{ .this = this, .columns = &columns }; try this.tabular_data.forEachWithContext(globalObject, &ctx_, struct { - fn callback(_: *JSC.VM, _: *JSGlobalObject, ctx: *@TypeOf(ctx_), value: JSValue) callconv(.C) void { + fn callback(_: *jsc.VM, _: *JSGlobalObject, ctx: *@TypeOf(ctx_), value: JSValue) callconv(.C) void { updateColumnsForRow(ctx.this, ctx.columns, .{ .num = ctx.idx }, value) catch { ctx.err = true; }; @@ -546,7 +546,7 @@ pub const TablePrinter = struct { if (ctx_.err) return error.JSError; } else { const tabular_obj = try this.tabular_data.toObject(globalObject); - var rows_iter = try JSC.JSPropertyIterator(.{ + var rows_iter = try jsc.JSPropertyIterator(.{ .skip_empty_name = false, .include_value = true, }).init(globalObject, tabular_obj); @@ -610,7 +610,7 @@ pub const TablePrinter = struct { if (this.is_iterable) { var ctx_: struct { this: *TablePrinter, columns: *@TypeOf(columns), writer: Writer, idx: u32 = 0, err: bool = false } = .{ .this = this, .columns = &columns, .writer = writer }; try this.tabular_data.forEachWithContext(globalObject, &ctx_, struct { - fn callback(_: *JSC.VM, _: *JSGlobalObject, ctx: *@TypeOf(ctx_), value: JSValue) callconv(.C) void { + fn callback(_: *jsc.VM, _: *JSGlobalObject, ctx: *@TypeOf(ctx_), value: JSValue) callconv(.C) void { printRow(ctx.this, Writer, ctx.writer, enable_ansi_colors, ctx.columns, .{ .num = ctx.idx }, value) catch { ctx.err = true; }; @@ -622,7 +622,7 @@ pub const TablePrinter = struct { const cell = this.tabular_data.toCell() orelse { return globalObject.throwTypeError("tabular_data must be an object or array", .{}); }; - var rows_iter = try JSC.JSPropertyIterator(.{ + var rows_iter = try jsc.JSPropertyIterator(.{ .skip_empty_name = false, .include_value = true, }).init(globalObject, cell.toObject(globalObject)); @@ -746,7 +746,7 @@ pub const FormatOptions = struct { } }; - pub fn fromJS(formatOptions: *FormatOptions, globalThis: *JSC.JSGlobalObject, arguments: []const JSC.JSValue) bun.JSError!void { + pub fn fromJS(formatOptions: *FormatOptions, globalThis: *jsc.JSGlobalObject, arguments: []const jsc.JSValue) bun.JSError!void { const arg1 = arguments[0]; if (arg1.isObject()) { @@ -1271,7 +1271,7 @@ pub const Formatter = struct { if (js_type == .GlobalProxy) { if (!opts.hide_global) { return Tag.get( - JSC.JSValue.c(JSC.C.JSObjectGetProxyTarget(value.asObjectRef())), + jsc.JSValue.c(jsc.C.JSObjectGetProxyTarget(value.asObjectRef())), globalThis, ); } @@ -1397,7 +1397,7 @@ pub const Formatter = struct { } }; - const CellType = JSC.C.CellType; + const CellType = jsc.C.CellType; threadlocal var name_buf: [512]u8 = undefined; /// https://console.spec.whatwg.org/#formatter @@ -1747,7 +1747,7 @@ pub const Formatter = struct { formatter: *ConsoleObject.Formatter, writer: Writer, count: usize = 0, - pub fn forEach(_: *JSC.VM, globalObject: *JSGlobalObject, ctx: ?*anyopaque, nextValue: JSValue) callconv(.C) void { + pub fn forEach(_: *jsc.VM, globalObject: *JSGlobalObject, ctx: ?*anyopaque, nextValue: JSValue) callconv(.C) void { var this: *@This() = bun.cast(*@This(), ctx orelse return); if (this.formatter.failed) return; if (single_line and this.count > 0) { @@ -1821,7 +1821,7 @@ pub const Formatter = struct { formatter: *ConsoleObject.Formatter, writer: Writer, is_first: bool = true, - pub fn forEach(_: *JSC.VM, globalObject: *JSGlobalObject, ctx: ?*anyopaque, nextValue: JSValue) callconv(.C) void { + pub fn forEach(_: *jsc.VM, globalObject: *JSGlobalObject, ctx: ?*anyopaque, nextValue: JSValue) callconv(.C) void { var this: *@This() = bun.cast(*@This(), ctx orelse return); if (this.formatter.failed) return; if (single_line) { @@ -1863,7 +1863,7 @@ pub const Formatter = struct { always_newline: bool = false, parent: JSValue, const enable_ansi_colors = enable_ansi_colors_; - pub fn handleFirstProperty(this: *@This(), globalThis: *JSC.JSGlobalObject, value: JSValue) bun.JSError!void { + pub fn handleFirstProperty(this: *@This(), globalThis: *jsc.JSGlobalObject, value: JSValue) bun.JSError!void { if (value.isCell() and !value.jsType().isFunction()) { var writer = WrappedWriter(Writer){ .ctx = this.writer, @@ -2015,7 +2015,7 @@ pub const Formatter = struct { }; } - fn getObjectName(globalThis: *JSC.JSGlobalObject, value: JSValue) bun.JSError!?ZigString { + fn getObjectName(globalThis: *jsc.JSGlobalObject, value: JSValue) bun.JSError!?ZigString { var name_str = ZigString.init(""); try value.getClassName(globalThis, &name_str); if (!name_str.eqlComptime("Object")) { @@ -2027,7 +2027,7 @@ pub const Formatter = struct { } extern fn JSC__JSValue__callCustomInspectFunction( - *JSC.JSGlobalObject, + *jsc.JSGlobalObject, JSValue, JSValue, depth: u32, @@ -2535,19 +2535,19 @@ pub const Formatter = struct { } }, .Private => { - if (value.as(JSC.WebCore.Response)) |response| { + if (value.as(jsc.WebCore.Response)) |response| { response.writeFormat(ConsoleObject.Formatter, this, writer_, enable_ansi_colors) catch {}; return; - } else if (value.as(JSC.WebCore.Request)) |request| { + } else if (value.as(jsc.WebCore.Request)) |request| { request.writeFormat(value, ConsoleObject.Formatter, this, writer_, enable_ansi_colors) catch {}; return; - } else if (value.as(JSC.API.BuildArtifact)) |build| { + } else if (value.as(jsc.API.BuildArtifact)) |build| { build.writeFormat(ConsoleObject.Formatter, this, writer_, enable_ansi_colors) catch {}; return; - } else if (value.as(JSC.WebCore.Blob)) |blob| { + } else if (value.as(jsc.WebCore.Blob)) |blob| { blob.writeFormat(ConsoleObject.Formatter, this, writer_, enable_ansi_colors) catch {}; return; - } else if (value.as(JSC.WebCore.S3Client)) |s3client| { + } else if (value.as(jsc.WebCore.S3Client)) |s3client| { s3client.writeFormat(ConsoleObject.Formatter, this, writer_, enable_ansi_colors) catch {}; return; } else if (value.as(bun.webcore.FetchHeaders) != null) { @@ -2568,7 +2568,7 @@ pub const Formatter = struct { enable_ansi_colors, ); } - } else if (value.as(JSC.DOMFormData) != null) { + } else if (value.as(jsc.DOMFormData) != null) { if (try value.get(this.globalThis, "toJSON")) |toJSONFunction| { const prev_quote_keys = this.quote_keys; this.quote_keys = true; @@ -2685,7 +2685,7 @@ pub const Formatter = struct { writer.writeAll(comptime Output.prettyFmt("" ++ fmt ++ "", enable_ansi_colors)); }, .Map => { - const length_value = try value.get(this.globalThis, "size") orelse JSC.JSValue.jsNumberFromInt32(0); + const length_value = try value.get(this.globalThis, "size") orelse jsc.JSValue.jsNumberFromInt32(0); const length = length_value.toInt32(); const prev_quote_strings = this.quote_strings; @@ -2792,7 +2792,7 @@ pub const Formatter = struct { writer.writeAll("}"); }, .Set => { - const length_value = try value.get(this.globalThis, "size") orelse JSC.JSValue.jsNumberFromInt32(0); + const length_value = try value.get(this.globalThis, "size") orelse jsc.JSValue.jsNumberFromInt32(0); const length = length_value.toInt32(); const prev_quote_strings = this.quote_strings; @@ -3069,7 +3069,7 @@ pub const Formatter = struct { // SAFETY: JSX props are always objects const props_obj = props.getObject().?; - var props_iter = try JSC.JSPropertyIterator(.{ + var props_iter = try jsc.JSPropertyIterator(.{ .skip_empty_name = true, .include_value = true, }).init(this.globalThis, props_obj); @@ -3505,7 +3505,7 @@ pub fn count( ptr: [*]const u8, // len len: usize, -) callconv(JSC.conv) void { +) callconv(jsc.conv) void { var this = globalThis.bunVM().console; const slice = ptr[0..len]; const hash = bun.hash(slice); @@ -3531,7 +3531,7 @@ pub fn countReset( ptr: [*]const u8, // len len: usize, -) callconv(JSC.conv) void { +) callconv(jsc.conv) void { var this = globalThis.bunVM().console; const slice = ptr[0..len]; const hash = bun.hash(slice); @@ -3551,7 +3551,7 @@ pub fn time( _: *JSGlobalObject, chars: [*]const u8, len: usize, -) callconv(JSC.conv) void { +) callconv(jsc.conv) void { const id = bun.hash(chars[0..len]); if (!pending_time_logs_loaded) { pending_time_logs = PendingTimers.init(default_allocator); @@ -3571,7 +3571,7 @@ pub fn timeEnd( _: *JSGlobalObject, chars: [*]const u8, len: usize, -) callconv(JSC.conv) void { +) callconv(jsc.conv) void { if (!pending_time_logs_loaded) { return; } @@ -3602,7 +3602,7 @@ pub fn timeLog( // args args: [*]JSValue, args_len: usize, -) callconv(JSC.conv) void { +) callconv(jsc.conv) void { if (!pending_time_logs_loaded) { return; } @@ -3655,7 +3655,7 @@ pub fn profile( _: [*]const u8, // len _: usize, -) callconv(JSC.conv) void {} +) callconv(jsc.conv) void {} pub fn profileEnd( // console _: *ConsoleObject, @@ -3665,7 +3665,7 @@ pub fn profileEnd( _: [*]const u8, // len _: usize, -) callconv(JSC.conv) void {} +) callconv(jsc.conv) void {} pub fn takeHeapSnapshot( // console _: *ConsoleObject, @@ -3675,7 +3675,7 @@ pub fn takeHeapSnapshot( _: [*]const u8, // len _: usize, -) callconv(JSC.conv) void { +) callconv(jsc.conv) void { // TODO: this does an extra JSONStringify and we don't need it to! var snapshot: [1]JSValue = .{globalThis.generateHeapSnapshot()}; ConsoleObject.messageWithTypeAndLevel(undefined, MessageType.Log, MessageLevel.Debug, globalThis, &snapshot, 1); @@ -3687,7 +3687,7 @@ pub fn timeStamp( _: *JSGlobalObject, // args _: *ScriptArguments, -) callconv(JSC.conv) void {} +) callconv(jsc.conv) void {} pub fn record( // console _: *ConsoleObject, @@ -3695,7 +3695,7 @@ pub fn record( _: *JSGlobalObject, // args _: *ScriptArguments, -) callconv(JSC.conv) void {} +) callconv(jsc.conv) void {} pub fn recordEnd( // console _: *ConsoleObject, @@ -3703,7 +3703,7 @@ pub fn recordEnd( _: *JSGlobalObject, // args _: *ScriptArguments, -) callconv(JSC.conv) void {} +) callconv(jsc.conv) void {} pub fn screenshot( // console _: *ConsoleObject, @@ -3711,7 +3711,7 @@ pub fn screenshot( _: *JSGlobalObject, // args _: *ScriptArguments, -) callconv(JSC.conv) void {} +) callconv(jsc.conv) void {} comptime { @export(&messageWithTypeAndLevel, .{ .name = "Bun__ConsoleObject__messageWithTypeAndLevel" }); @@ -3729,6 +3729,8 @@ comptime { @export(&screenshot, .{ .name = "Bun__ConsoleObject__screenshot" }); } +const string = []const u8; + const std = @import("std"); const CLI = @import("../cli.zig").Command; const JestPrettyFormat = @import("./test/pretty_format.zig").JestPrettyFormat; @@ -3740,14 +3742,13 @@ const JSPrinter = bun.js_printer; const Output = bun.Output; const String = bun.String; const default_allocator = bun.default_allocator; -const string = bun.string; const strings = bun.strings; -const JSC = bun.JSC; -const EventType = JSC.EventType; -const JSGlobalObject = JSC.JSGlobalObject; -const JSPromise = JSC.JSPromise; -const JSValue = JSC.JSValue; -const VirtualMachine = JSC.VirtualMachine; -const ZigException = JSC.ZigException; -const ZigString = JSC.ZigString; +const jsc = bun.jsc; +const EventType = jsc.EventType; +const JSGlobalObject = jsc.JSGlobalObject; +const JSPromise = jsc.JSPromise; +const JSValue = jsc.JSValue; +const VirtualMachine = jsc.VirtualMachine; +const ZigException = jsc.ZigException; +const ZigString = jsc.ZigString; diff --git a/src/bun.js/Counters.zig b/src/bun.js/Counters.zig index 3cf79e0262..52a10cc5cf 100644 --- a/src/bun.js/Counters.zig +++ b/src/bun.js/Counters.zig @@ -7,11 +7,11 @@ pub fn mark(this: *Counters, comptime tag: Field) void { @field(this, @tagName(tag)) +|= 1; } -pub fn toJS(this: *const Counters, globalObject: *JSC.JSGlobalObject) bun.JSError!JSC.JSValue { - return (try JSC.JSObject.create(this.*, globalObject)).toJS(); +pub fn toJS(this: *const Counters, globalObject: *jsc.JSGlobalObject) bun.JSError!jsc.JSValue { + return (try jsc.JSObject.create(this.*, globalObject)).toJS(); } -pub fn createCountersObject(globalObject: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!JSC.JSValue { +pub fn createCountersObject(globalObject: *jsc.JSGlobalObject, _: *jsc.CallFrame) bun.JSError!jsc.JSValue { return globalObject.bunVM().counters.toJS(globalObject); } @@ -20,4 +20,4 @@ const Field = std.meta.FieldEnum(Counters); const std = @import("std"); const bun = @import("bun"); -const JSC = bun.JSC; +const jsc = bun.jsc; diff --git a/src/bun.js/Debugger.zig b/src/bun.js/Debugger.zig index 51f779dd5c..ceb584d00c 100644 --- a/src/bun.js/Debugger.zig +++ b/src/bun.js/Debugger.zig @@ -42,7 +42,7 @@ pub fn waitForDebuggerIfNecessary(this: *VirtualMachine) void { if (comptime Environment.enable_logs) Debugger.log("waitForDebugger: {}", .{Output.ElapsedFormatter{ .colors = Output.enable_ansi_colors_stderr, - .duration_ns = @truncate(@as(u128, @intCast(std.time.nanoTimestamp() - bun.CLI.start_time))), + .duration_ns = @truncate(@as(u128, @intCast(std.time.nanoTimestamp() - bun.cli.start_time))), }}); Bun__ensureDebugger(debugger.script_execution_context_id, debugger.wait_for_connection != .off); @@ -82,7 +82,7 @@ pub fn waitForDebuggerIfNecessary(this: *VirtualMachine) void { this.eventLoop().autoTickActive(); if (comptime Environment.enable_logs) - log("waited: {}", .{std.fmt.fmtDuration(@intCast(@as(i64, @truncate(std.time.nanoTimestamp() - bun.CLI.start_time))))}); + log("waited: {}", .{std.fmt.fmtDuration(@intCast(@as(i64, @truncate(std.time.nanoTimestamp() - bun.cli.start_time))))}); }, .shortly => { // Handle .incrementRefConcurrently @@ -97,7 +97,7 @@ pub fn waitForDebuggerIfNecessary(this: *VirtualMachine) void { this.uwsLoop().tickWithTimeout(&deadline); if (comptime Environment.enable_logs) - log("waited: {}", .{std.fmt.fmtDuration(@intCast(@as(i64, @truncate(std.time.nanoTimestamp() - bun.CLI.start_time))))}); + log("waited: {}", .{std.fmt.fmtDuration(@intCast(@as(i64, @truncate(std.time.nanoTimestamp() - bun.cli.start_time))))}); const elapsed = bun.timespec.now(); if (elapsed.order(&deadline) != .lt) { @@ -148,7 +148,7 @@ pub fn startJSDebuggerThread(other_vm: *VirtualMachine) void { var vm = VirtualMachine.init(.{ .allocator = arena.allocator(), - .args = std.mem.zeroes(bun.Schema.Api.TransformOptions), + .args = std.mem.zeroes(bun.schema.api.TransformOptions), .store_fd = false, }) catch @panic("Failed to create Debugger VM"); vm.allocator = arena.allocator(); diff --git a/src/bun.js/ModuleLoader.zig b/src/bun.js/ModuleLoader.zig index 79bc439905..ce17b569cc 100644 --- a/src/bun.js/ModuleLoader.zig +++ b/src/bun.js/ModuleLoader.zig @@ -69,21 +69,21 @@ pub fn resolveEmbeddedFile(vm: *VirtualMachine, input_path: []const u8, extname: pub const AsyncModule = struct { // This is all the state used by the printer to print the module parse_result: ParseResult, - promise: JSC.Strong.Optional = .empty, + promise: jsc.Strong.Optional = .empty, path: Fs.Path, specifier: string = "", referrer: string = "", string_buf: []u8 = &[_]u8{}, fd: ?StoredFileDescriptorType = null, package_json: ?*PackageJSON = null, - loader: Api.Loader, + loader: api.Loader, hash: u32 = std.math.maxInt(u32), globalThis: *JSGlobalObject = undefined, arena: *bun.ArenaAllocator, // This is the specific state for making it async poll_ref: Async.KeepAlive = .{}, - any_task: JSC.AnyTask = undefined, + any_task: jsc.AnyTask = undefined, pub const Id = u32; @@ -155,7 +155,7 @@ pub const AsyncModule = struct { pub fn onWakeHandler(ctx: *anyopaque, _: *PackageManager) void { debug("onWake", .{}); var this = bun.cast(*Queue, ctx); - this.vm().enqueueTaskConcurrent(JSC.ConcurrentTask.createFrom(this)); + this.vm().enqueueTaskConcurrent(jsc.ConcurrentTask.createFrom(this)); } pub fn onPoll(this: *Queue) void { @@ -376,7 +376,7 @@ pub const AsyncModule = struct { // var stmt_blocks = js_ast.Stmt.Data.toOwnedSlice(); // var expr_blocks = js_ast.Expr.Data.toOwnedSlice(); const this_promise = JSValue.createInternalPromise(globalObject); - const promise = JSC.Strong.Optional.create(this_promise, globalObject); + const promise = jsc.Strong.Optional.create(this_promise, globalObject); var buf = bun.StringBuilder{}; buf.count(opts.referrer); @@ -410,12 +410,12 @@ pub const AsyncModule = struct { 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)); + 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()); + jsc.markBinding(@src()); var jsc_vm = this.globalThis.bunVM(); jsc_vm.modules.scheduled -= 1; if (jsc_vm.modules.scheduled == 0) { @@ -423,10 +423,10 @@ pub const AsyncModule = struct { } var log = logger.Log.init(jsc_vm.allocator); defer log.deinit(); - var errorable: JSC.ErrorableResolvedSource = undefined; + var errorable: jsc.ErrorableResolvedSource = undefined; this.poll_ref.unref(jsc_vm); outer: { - errorable = JSC.ErrorableResolvedSource.ok(this.resumeLoadingModule(&log) catch |err| { + errorable = jsc.ErrorableResolvedSource.ok(this.resumeLoadingModule(&log) catch |err| { switch (err) { error.JSError => { errorable = .err(error.JSError, this.globalThis.takeError(error.JSError)); @@ -469,10 +469,10 @@ pub const AsyncModule = struct { referrer_: bun.String, log: *logger.Log, ) bun.JSError!void { - JSC.markBinding(@src()); + jsc.markBinding(@src()); var specifier = specifier_; var referrer = referrer_; - var scope: JSC.CatchScope = undefined; + var scope: jsc.CatchScope = undefined; scope.init(globalThis, @src()); defer { specifier.deref(); @@ -480,7 +480,7 @@ pub const AsyncModule = struct { scope.deinit(); } - var errorable: JSC.ErrorableResolvedSource = undefined; + var errorable: jsc.ErrorableResolvedSource = undefined; if (err) |e| { defer { if (resolved_source.source_code_needs_deref) { @@ -490,7 +490,7 @@ pub const AsyncModule = struct { } if (e == error.JSError) { - errorable = JSC.ErrorableResolvedSource.err(error.JSError, globalThis.takeError(error.JSError)); + errorable = jsc.ErrorableResolvedSource.err(error.JSError, globalThis.takeError(error.JSError)); } else { VirtualMachine.processFetchLog( globalThis, @@ -502,7 +502,7 @@ pub const AsyncModule = struct { ); } } else { - errorable = JSC.ErrorableResolvedSource.ok(resolved_source.*); + errorable = jsc.ErrorableResolvedSource.ok(resolved_source.*); } log.deinit(); @@ -799,19 +799,19 @@ pub const AsyncModule = struct { extern "c" fn Bun__onFulfillAsyncModule( globalObject: *JSGlobalObject, promiseValue: JSValue, - res: *JSC.ErrorableResolvedSource, + res: *jsc.ErrorableResolvedSource, specifier: *bun.String, referrer: *bun.String, ) void; }; -pub export fn Bun__getDefaultLoader(global: *JSGlobalObject, str: *const bun.String) Api.Loader { +pub export fn Bun__getDefaultLoader(global: *JSGlobalObject, str: *const bun.String) api.Loader { var jsc_vm = global.bunVM(); const filename = str.toUTF8(jsc_vm.allocator); defer filename.deinit(); const loader = jsc_vm.transpiler.options.loader(Fs.PathName.init(filename.slice()).ext).toAPI(); if (loader == .file) { - return Api.Loader.js; + return api.Loader.js; } return loader; @@ -827,7 +827,7 @@ pub fn transpileSourceCode( module_type: options.ModuleType, log: *logger.Log, virtual_source: ?*const logger.Source, - promise_ptr: ?*?*JSC.JSInternalPromise, + promise_ptr: ?*?*jsc.JSInternalPromise, source_code_printer: *js_printer.BufferPrinter, globalObject: ?*JSGlobalObject, comptime flags: FetchFlags, @@ -910,7 +910,7 @@ pub fn transpileSourceCode( package_json = jsc_vm.bun_watcher.watchlist().items(.package_json)[index]; } - var cache = JSC.RuntimeTranspilerCache{ + var cache = jsc.RuntimeTranspilerCache{ .output_code_allocator = allocator, .sourcemap_allocator = bun.default_allocator, }; @@ -978,7 +978,7 @@ pub fn transpileSourceCode( jsc_vm.debugger != null and jsc_vm.debugger.?.set_breakpoint_on_first_line and setBreakPointOnFirstLine(), - .runtime_transpiler_cache = if (!disable_transpilying and !JSC.RuntimeTranspilerCache.is_disabled) &cache else null, + .runtime_transpiler_cache = if (!disable_transpilying and !jsc.RuntimeTranspilerCache.is_disabled) &cache else null, .remove_cjs_module_wrapper = is_main and jsc_vm.module_loader.eval_source != null, }; defer { @@ -1350,14 +1350,14 @@ pub fn transpileSourceCode( if (virtual_source) |source| { if (globalObject) |globalThis| { // attempt to avoid reading the WASM file twice. - const encoded = JSC.EncodedJSValue{ + const encoded = jsc.EncodedJSValue{ .asPtr = globalThis, }; const globalValue = @as(JSValue, @enumFromInt(encoded.asInt64)); globalValue.put( globalThis, ZigString.static("wasmSourceBytes"), - try JSC.ArrayBuffer.create(globalThis, source.contents, .Uint8Array), + try jsc.ArrayBuffer.create(globalThis, source.contents, .Uint8Array), ); } } @@ -1444,7 +1444,7 @@ pub fn transpileSourceCode( return error.NotSupported; } - const html_bundle = try JSC.API.HTMLBundle.init(globalObject.?, path.text); + const html_bundle = try jsc.API.HTMLBundle.init(globalObject.?, path.text); return ResolvedSource{ .allocator = &jsc_vm.allocator, .jsvalue_for_export = html_bundle.toJS(globalObject.?), @@ -1520,7 +1520,7 @@ pub fn transpileSourceCode( var buf = MutableString.init2048(jsc_vm.allocator) catch bun.outOfMemory(); defer buf.deinit(); var writer = buf.writer(); - JSC.API.Bun.getPublicPath(specifier, jsc_vm.origin, @TypeOf(&writer), &writer); + jsc.API.Bun.getPublicPath(specifier, jsc_vm.origin, @TypeOf(&writer), &writer); break :brk try bun.String.createUTF8ForJS(globalObject.?, buf.slice()); } @@ -1541,9 +1541,9 @@ pub fn transpileSourceCode( pub export fn Bun__resolveAndFetchBuiltinModule( jsc_vm: *VirtualMachine, specifier: *bun.String, - ret: *JSC.ErrorableResolvedSource, + ret: *jsc.ErrorableResolvedSource, ) bool { - JSC.markBinding(@src()); + jsc.markBinding(@src()); var log = logger.Log.init(jsc_vm.transpiler.allocator); defer log.deinit(); @@ -1565,9 +1565,9 @@ pub export fn Bun__fetchBuiltinModule( globalObject: *JSGlobalObject, specifier: *bun.String, referrer: *bun.String, - ret: *JSC.ErrorableResolvedSource, + ret: *jsc.ErrorableResolvedSource, ) bool { - JSC.markBinding(@src()); + jsc.markBinding(@src()); var log = logger.Log.init(jsc_vm.transpiler.allocator); defer log.deinit(); @@ -1582,7 +1582,7 @@ pub export fn Bun__fetchBuiltinModule( VirtualMachine.processFetchLog(globalObject, specifier.*, referrer.*, &log, ret, err); return true; }) |builtin| { - ret.* = JSC.ErrorableResolvedSource.ok(builtin); + ret.* = jsc.ErrorableResolvedSource.ok(builtin); return true; } else { return false; @@ -1597,12 +1597,12 @@ pub export fn Bun__transpileFile( specifier_ptr: *bun.String, referrer: *bun.String, type_attribute: ?*const bun.String, - ret: *JSC.ErrorableResolvedSource, + ret: *jsc.ErrorableResolvedSource, allow_promise: bool, is_commonjs_require: bool, force_loader_type: bun.options.Loader.Optional, ) ?*anyopaque { - JSC.markBinding(@src()); + jsc.markBinding(@src()); var log = logger.Log.init(jsc_vm.transpiler.allocator); defer log.deinit(); @@ -1617,9 +1617,9 @@ pub export fn Bun__transpileFile( }; var virtual_source_to_use: ?logger.Source = null; - var blob_to_deinit: ?JSC.WebCore.Blob = null; + var blob_to_deinit: ?jsc.WebCore.Blob = null; var lr = options.getLoaderAndVirtualSource(_specifier.slice(), jsc_vm, &virtual_source_to_use, &blob_to_deinit, type_attribute_str) catch { - ret.* = JSC.ErrorableResolvedSource.err(error.JSErrorObject, globalObject.ERR(.MODULE_NOT_FOUND, "Blob not found", .{}).toJS()); + ret.* = jsc.ErrorableResolvedSource.err(error.JSErrorObject, globalObject.ERR(.MODULE_NOT_FOUND, "Blob not found", .{}).toJS()); return null; }; defer if (blob_to_deinit) |*blob| blob.deinit(); @@ -1636,7 +1636,7 @@ pub export fn Bun__transpileFile( lr.loader = loader; }, .custom => |strong| { - ret.* = JSC.ErrorableResolvedSource.ok(ResolvedSource{ + ret.* = jsc.ErrorableResolvedSource.ok(ResolvedSource{ .allocator = null, .source_code = bun.String.empty, .specifier = .empty, @@ -1761,7 +1761,7 @@ pub export fn Bun__transpileFile( switch (entry) { .loader => |loader| break :loader loader, .custom => |strong| { - ret.* = JSC.ErrorableResolvedSource.ok(ResolvedSource{ + ret.* = jsc.ErrorableResolvedSource.ok(ResolvedSource{ .allocator = null, .source_code = bun.String.empty, .specifier = .empty, @@ -1794,8 +1794,8 @@ pub export fn Bun__transpileFile( defer jsc_vm.module_loader.resetArena(jsc_vm); - var promise: ?*JSC.JSInternalPromise = null; - ret.* = JSC.ErrorableResolvedSource.ok( + var promise: ?*jsc.JSInternalPromise = null; + ret.* = jsc.ErrorableResolvedSource.ok( ModuleLoader.transpileSourceCode( jsc_vm, lr.specifier, @@ -1818,7 +1818,7 @@ pub export fn Bun__transpileFile( }, error.PluginError => return null, error.JSError => { - ret.* = JSC.ErrorableResolvedSource.err(error.JSError, globalObject.takeError(error.JSError)); + ret.* = jsc.ErrorableResolvedSource.err(error.JSError, globalObject.takeError(error.JSError)); return null; }, else => { @@ -1832,7 +1832,7 @@ pub export fn Bun__transpileFile( } export fn Bun__runVirtualModule(globalObject: *JSGlobalObject, specifier_ptr: *const bun.String) JSValue { - JSC.markBinding(@src()); + jsc.markBinding(@src()); if (globalObject.bunVM().plugin_runner == null) return JSValue.zero; const specifier_slice = specifier_ptr.toUTF8(bun.default_allocator); @@ -1855,7 +1855,7 @@ export fn Bun__runVirtualModule(globalObject: *JSGlobalObject, specifier_ptr: *c } fn getHardcodedModule(jsc_vm: *VirtualMachine, specifier: bun.String, hardcoded: HardcodedModule) ?ResolvedSource { - Analytics.Features.builtin_modules.insert(hardcoded); + analytics.Features.builtin_modules.insert(hardcoded); return switch (hardcoded) { .@"bun:main" => .{ .allocator = null, @@ -1942,10 +1942,10 @@ export fn Bun__transpileVirtualModule( specifier_ptr: *const bun.String, referrer_ptr: *const bun.String, source_code: *ZigString, - loader_: Api.Loader, - ret: *JSC.ErrorableResolvedSource, + loader_: api.Loader, + ret: *jsc.ErrorableResolvedSource, ) bool { - JSC.markBinding(@src()); + jsc.markBinding(@src()); const jsc_vm = globalObject.bunVM(); bun.assert(jsc_vm.plugin_runner != null); @@ -1975,7 +1975,7 @@ export fn Bun__transpileVirtualModule( defer log.deinit(); defer jsc_vm.module_loader.resetArena(jsc_vm); - ret.* = JSC.ErrorableResolvedSource.ok( + ret.* = jsc.ErrorableResolvedSource.ok( ModuleLoader.transpileSourceCode( jsc_vm, specifier_slice.slice(), @@ -1994,7 +1994,7 @@ export fn Bun__transpileVirtualModule( switch (err) { error.PluginError => return true, error.JSError => { - ret.* = JSC.ErrorableResolvedSource.err(error.JSError, globalObject.takeError(error.JSError)); + ret.* = jsc.ErrorableResolvedSource.err(error.JSError, globalObject.takeError(error.JSError)); return true; }, else => { @@ -2004,7 +2004,7 @@ export fn Bun__transpileVirtualModule( } }, ); - Analytics.Features.virtual_modules += 1; + analytics.Features.virtual_modules += 1; return true; } @@ -2142,9 +2142,9 @@ pub const RuntimeTranspilerStore = struct { }; } - pub fn runFromJSThread(this: *RuntimeTranspilerStore, event_loop: *JSC.EventLoop, global: *JSC.JSGlobalObject, vm: *JSC.VirtualMachine) void { + pub fn runFromJSThread(this: *RuntimeTranspilerStore, event_loop: *jsc.EventLoop, global: *jsc.JSGlobalObject, vm: *jsc.VirtualMachine) void { var batch = this.queue.popBatch(); - const jsc_vm = vm.jsc; + const jsc_vm = vm.jsc_vm; var iter = batch.iterator(); if (iter.next()) |job| { // we run just one job first to see if there are more @@ -2173,7 +2173,7 @@ pub const RuntimeTranspilerStore = struct { ) *anyopaque { var job: *TranspilerJob = this.store.get(); const owned_path = Fs.Path.init(bun.default_allocator.dupe(u8, path.text) catch unreachable); - const promise = JSC.JSInternalPromise.create(globalObject); + const promise = jsc.JSInternalPromise.create(globalObject); // NOTE: DirInfo should already be cached since module loading happens // after module resolution, so this should be cheap @@ -2215,7 +2215,7 @@ pub const RuntimeTranspilerStore = struct { non_threadsafe_input_specifier: String, non_threadsafe_referrer: String, loader: options.Loader, - promise: JSC.Strong.Optional = .empty, + promise: jsc.Strong.Optional = .empty, vm: *VirtualMachine, globalThis: *JSGlobalObject, fetcher: Fetcher, @@ -2224,7 +2224,7 @@ pub const RuntimeTranspilerStore = struct { log: logger.Log, parse_error: ?anyerror = null, resolved_source: ResolvedSource = ResolvedSource{}, - work_task: JSC.WorkPoolTask = .{ .callback = runFromWorkerThread }, + work_task: jsc.WorkPoolTask = .{ .callback = runFromWorkerThread }, next: ?*TranspilerJob = null, pub const Store = bun.HiveArray(TranspilerJob, if (bun.heap_breakdown.enabled) 0 else 64).Fallback; @@ -2259,7 +2259,7 @@ pub const RuntimeTranspilerStore = struct { pub fn dispatchToMainThread(this: *TranspilerJob) void { this.vm.transpiler_store.queue.push(this); - this.vm.eventLoop().enqueueTaskConcurrent(JSC.ConcurrentTask.createFrom(&this.vm.transpiler_store)); + this.vm.eventLoop().enqueueTaskConcurrent(jsc.ConcurrentTask.createFrom(&this.vm.transpiler_store)); } pub fn runFromJSThread(this: *TranspilerJob) bun.JSError!void { @@ -2300,10 +2300,10 @@ pub const RuntimeTranspilerStore = struct { pub fn schedule(this: *TranspilerJob) void { this.poll_ref.ref(this.vm); - JSC.WorkPool.schedule(&this.work_task); + jsc.WorkPool.schedule(&this.work_task); } - pub fn runFromWorkerThread(work_task: *JSC.WorkPoolTask) void { + pub fn runFromWorkerThread(work_task: *jsc.WorkPoolTask) void { @as(*TranspilerJob, @fieldParentPtr("work_task", work_task)).run(); } @@ -2333,7 +2333,7 @@ pub const RuntimeTranspilerStore = struct { const specifier = this.path.text; const loader = this.loader; - var cache = JSC.RuntimeTranspilerCache{ + var cache = jsc.RuntimeTranspilerCache{ .output_code_allocator = allocator, .sourcemap_allocator = bun.default_allocator, }; @@ -2414,7 +2414,7 @@ pub const RuntimeTranspilerStore = struct { vm.debugger.?.set_breakpoint_on_first_line and is_main and setBreakPointOnFirstLine(), - .runtime_transpiler_cache = if (!JSC.RuntimeTranspilerCache.is_disabled) &cache else null, + .runtime_transpiler_cache = if (!jsc.RuntimeTranspilerCache.is_disabled) &cache else null, .remove_cjs_module_wrapper = is_main and vm.module_loader.eval_source != null, .module_type = module_type, .allow_bytecode_cache = true, @@ -2528,7 +2528,7 @@ pub const RuntimeTranspilerStore = struct { for (parse_result.ast.import_records.slice()) |*import_record_| { var import_record: *bun.ImportRecord = import_record_; - if (JSC.ModuleLoader.HardcodedModule.Alias.get(import_record.path.text, transpiler.options.target)) |replacement| { + if (jsc.ModuleLoader.HardcodedModule.Alias.get(import_record.path.text, transpiler.options.target)) |replacement| { import_record.path.text = replacement.path; import_record.tag = replacement.tag; import_record.is_external_without_side_effects = true; @@ -3061,14 +3061,13 @@ export fn ModuleLoader__isBuiltin(data: [*]const u8, len: usize) bool { const debug = Output.scoped(.ModuleLoader, true); -const Analytics = @import("../analytics/analytics_thread.zig"); +const string = []const u8; + const Dependency = @import("../install/dependency.zig"); const Fs = @import("../fs.zig"); const Runtime = @import("../runtime.zig"); const node_module_module = @import("./bindings/NodeModuleModule.zig"); const std = @import("std"); -const Api = @import("../api/schema.zig").Api; -const Arena = @import("../allocators/mimalloc_arena.zig").Arena; const panic = std.debug.panic; const ast = @import("../import_record.zig"); @@ -3091,19 +3090,21 @@ const Output = bun.Output; const StoredFileDescriptorType = bun.StoredFileDescriptorType; const String = bun.String; const Transpiler = bun.Transpiler; -const js_ast = bun.JSAst; +const analytics = bun.analytics; +const js_ast = bun.ast; const js_printer = bun.js_printer; const logger = bun.logger; -const string = bun.string; const strings = bun.strings; +const Arena = bun.allocators.MimallocArena; +const api = bun.schema.api; -const JSC = bun.JSC; -const JSGlobalObject = bun.JSC.JSGlobalObject; -const JSValue = bun.JSC.JSValue; -const ResolvedSource = bun.JSC.ResolvedSource; -const VirtualMachine = bun.JSC.VirtualMachine; -const ZigString = bun.JSC.ZigString; -const Bun = JSC.API.Bun; +const jsc = bun.jsc; +const JSGlobalObject = bun.jsc.JSGlobalObject; +const JSValue = bun.jsc.JSValue; +const ResolvedSource = bun.jsc.ResolvedSource; +const VirtualMachine = bun.jsc.VirtualMachine; +const ZigString = bun.jsc.ZigString; +const Bun = jsc.API.Bun; const ParseResult = bun.transpiler.ParseResult; const PluginRunner = bun.transpiler.PluginRunner; diff --git a/src/bun.js/ResolveMessage.zig b/src/bun.js/ResolveMessage.zig index c20d143bc2..bec9fa3b40 100644 --- a/src/bun.js/ResolveMessage.zig +++ b/src/bun.js/ResolveMessage.zig @@ -1,5 +1,5 @@ pub const ResolveMessage = struct { - pub const js = JSC.Codegen.JSResolveMessage; + pub const js = jsc.Codegen.JSResolveMessage; pub const toJS = js.toJS; pub const fromJS = js.fromJS; pub const fromJSDirect = js.fromJSDirect; @@ -9,11 +9,11 @@ pub const ResolveMessage = struct { referrer: ?Fs.Path = null, logged: bool = false, - pub fn constructor(globalThis: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!*ResolveMessage { + pub fn constructor(globalThis: *jsc.JSGlobalObject, _: *jsc.CallFrame) bun.JSError!*ResolveMessage { return globalThis.throw("ResolveMessage is not constructable", .{}); } - pub fn getCode(this: *ResolveMessage, globalObject: *JSC.JSGlobalObject) JSC.JSValue { + pub fn getCode(this: *ResolveMessage, globalObject: *jsc.JSGlobalObject) jsc.JSValue { switch (this.msg.metadata) { .resolve => |resolve| { const code: []const u8 = brk: { @@ -54,20 +54,20 @@ pub const ResolveMessage = struct { } // https://github.com/oven-sh/bun/issues/2375#issuecomment-2121530202 - pub fn getColumn(this: *ResolveMessage, _: *JSC.JSGlobalObject) JSC.JSValue { + pub fn getColumn(this: *ResolveMessage, _: *jsc.JSGlobalObject) jsc.JSValue { if (this.msg.data.location) |location| { - return JSC.JSValue.jsNumber(@max(location.column - 1, 0)); + return jsc.JSValue.jsNumber(@max(location.column - 1, 0)); } - return JSC.JSValue.jsNumber(@as(i32, 0)); + return jsc.JSValue.jsNumber(@as(i32, 0)); } - pub fn getLine(this: *ResolveMessage, _: *JSC.JSGlobalObject) JSC.JSValue { + pub fn getLine(this: *ResolveMessage, _: *jsc.JSGlobalObject) jsc.JSValue { if (this.msg.data.location) |location| { - return JSC.JSValue.jsNumber(@max(location.line - 1, 0)); + return jsc.JSValue.jsNumber(@max(location.line - 1, 0)); } - return JSC.JSValue.jsNumber(@as(i32, 0)); + return jsc.JSValue.jsNumber(@as(i32, 0)); } pub fn fmt(allocator: std.mem.Allocator, specifier: string, referrer: string, err: anyerror, import_kind: bun.ImportKind) !string { @@ -102,7 +102,7 @@ pub const ResolveMessage = struct { } } - pub fn toStringFn(this: *ResolveMessage, globalThis: *JSC.JSGlobalObject) JSC.JSValue { + pub fn toStringFn(this: *ResolveMessage, globalThis: *jsc.JSGlobalObject) jsc.JSValue { const text = std.fmt.allocPrint(default_allocator, "ResolveMessage: {s}", .{this.msg.data.text}) catch { return globalThis.throwOutOfMemoryValue(); }; @@ -120,22 +120,22 @@ pub const ResolveMessage = struct { pub fn toString( // this this: *ResolveMessage, - globalThis: *JSC.JSGlobalObject, - _: *JSC.CallFrame, - ) bun.JSError!JSC.JSValue { + globalThis: *jsc.JSGlobalObject, + _: *jsc.CallFrame, + ) bun.JSError!jsc.JSValue { return this.toStringFn(globalThis); } pub fn toPrimitive( this: *ResolveMessage, - globalThis: *JSC.JSGlobalObject, - callframe: *JSC.CallFrame, - ) bun.JSError!JSC.JSValue { + globalThis: *jsc.JSGlobalObject, + callframe: *jsc.CallFrame, + ) bun.JSError!jsc.JSValue { const args_ = callframe.arguments_old(1); const args = args_.ptr[0..args_.len]; if (args.len > 0) { if (!args[0].isString()) { - return JSC.JSValue.jsNull(); + return jsc.JSValue.jsNull(); } const str = try args[0].getZigString(globalThis); @@ -144,15 +144,15 @@ pub const ResolveMessage = struct { } } - return JSC.JSValue.jsNull(); + return jsc.JSValue.jsNull(); } pub fn toJSON( this: *ResolveMessage, - globalThis: *JSC.JSGlobalObject, - _: *JSC.CallFrame, - ) bun.JSError!JSC.JSValue { - var object = JSC.JSValue.createEmptyObject(globalThis, 7); + globalThis: *jsc.JSGlobalObject, + _: *jsc.CallFrame, + ) bun.JSError!jsc.JSValue { + var object = jsc.JSValue.createEmptyObject(globalThis, 7); object.put(globalThis, ZigString.static("name"), bun.String.static("ResolveMessage").toJS(globalThis)); object.put(globalThis, ZigString.static("position"), this.getPosition(globalThis)); object.put(globalThis, ZigString.static("message"), this.getMessage(globalThis)); @@ -168,7 +168,7 @@ pub const ResolveMessage = struct { allocator: std.mem.Allocator, msg: logger.Msg, referrer: string, - ) bun.OOM!JSC.JSValue { + ) bun.OOM!jsc.JSValue { var resolve_error = try allocator.create(ResolveMessage); resolve_error.* = ResolveMessage{ .msg = try msg.clone(allocator), @@ -180,47 +180,47 @@ pub const ResolveMessage = struct { pub fn getPosition( this: *ResolveMessage, - globalThis: *JSC.JSGlobalObject, - ) JSC.JSValue { + globalThis: *jsc.JSGlobalObject, + ) jsc.JSValue { return bun.api.BuildMessage.generatePositionObject(this.msg, globalThis); } pub fn getMessage( this: *ResolveMessage, - globalThis: *JSC.JSGlobalObject, - ) JSC.JSValue { + globalThis: *jsc.JSGlobalObject, + ) jsc.JSValue { return ZigString.init(this.msg.data.text).toJS(globalThis); } pub fn getLevel( this: *ResolveMessage, - globalThis: *JSC.JSGlobalObject, - ) JSC.JSValue { + globalThis: *jsc.JSGlobalObject, + ) jsc.JSValue { return ZigString.init(this.msg.kind.string()).toJS(globalThis); } pub fn getSpecifier( this: *ResolveMessage, - globalThis: *JSC.JSGlobalObject, - ) JSC.JSValue { + globalThis: *jsc.JSGlobalObject, + ) jsc.JSValue { return ZigString.init(this.msg.metadata.resolve.specifier.slice(this.msg.data.text)).toJS(globalThis); } pub fn getImportKind( this: *ResolveMessage, - globalThis: *JSC.JSGlobalObject, - ) JSC.JSValue { + globalThis: *jsc.JSGlobalObject, + ) jsc.JSValue { return ZigString.init(this.msg.metadata.resolve.import_kind.label()).toJS(globalThis); } pub fn getReferrer( this: *ResolveMessage, - globalThis: *JSC.JSGlobalObject, - ) JSC.JSValue { + globalThis: *jsc.JSGlobalObject, + ) jsc.JSValue { if (this.referrer) |referrer| { return ZigString.init(referrer.text).toJS(globalThis); } else { - return JSC.JSValue.jsNull(); + return jsc.JSValue.jsNull(); } } @@ -229,6 +229,8 @@ pub const ResolveMessage = struct { } }; +const string = []const u8; + const Resolver = @import("../resolver//resolver.zig"); const std = @import("std"); @@ -236,9 +238,8 @@ const bun = @import("bun"); const Fs = bun.fs; const default_allocator = bun.default_allocator; const logger = bun.logger; -const string = bun.string; const strings = bun.strings; -const JSC = bun.JSC; -const JSGlobalObject = JSC.JSGlobalObject; -const ZigString = JSC.ZigString; +const jsc = bun.jsc; +const JSGlobalObject = jsc.JSGlobalObject; +const ZigString = jsc.ZigString; diff --git a/src/bun.js/RuntimeTranspilerCache.zig b/src/bun.js/RuntimeTranspilerCache.zig index 6c9baa3fd7..989ad5fce6 100644 --- a/src/bun.js/RuntimeTranspilerCache.zig +++ b/src/bun.js/RuntimeTranspilerCache.zig @@ -24,7 +24,7 @@ pub const RuntimeTranspilerCache = struct { input_hash: ?u64 = null, input_byte_length: ?u64 = null, features_hash: ?u64 = null, - exports_kind: bun.JSAst.ExportsKind = .none, + exports_kind: bun.ast.ExportsKind = .none, output_code: ?bun.String = null, entry: ?Entry = null, @@ -155,7 +155,7 @@ pub const RuntimeTranspilerCache = struct { features_hash: u64, sourcemap: []const u8, output_code: OutputCode, - exports_kind: bun.JSAst.ExportsKind, + exports_kind: bun.ast.ExportsKind, ) !void { var tracer = bun.perf.trace("RuntimeTranspilerCache.save"); defer tracer.end(); @@ -526,7 +526,7 @@ pub const RuntimeTranspilerCache = struct { features_hash: u64, sourcemap: []const u8, source_code: bun.String, - exports_kind: bun.JSAst.ExportsKind, + exports_kind: bun.ast.ExportsKind, ) !void { var tracer = bun.perf.trace("RuntimeTranspilerCache.toFile"); defer tracer.end(); @@ -608,7 +608,7 @@ pub const RuntimeTranspilerCache = struct { debug("get(\"{s}\") = {d} bytes, ignored for debug build", .{ source.path.text, this.entry.?.output_code.byteSlice().len }); } } - bun.Analytics.Features.transpiler_cache += 1; + bun.analytics.Features.transpiler_cache += 1; if (comptime bun.Environment.isDebug) { if (!bun_debug_restore_from_cache) { diff --git a/src/bun.js/Strong.zig b/src/bun.js/Strong.zig index 6979385345..32406eff85 100644 --- a/src/bun.js/Strong.zig +++ b/src/bun.js/Strong.zig @@ -7,7 +7,7 @@ const Strong = @This(); impl: *Impl, /// Hold a strong reference to a JavaScript value. Release with `deinit` or `clear` -pub fn create(value: JSC.JSValue, global: *JSC.JSGlobalObject) Strong { +pub fn create(value: jsc.JSValue, global: *jsc.JSGlobalObject) Strong { if (bun.Environment.allow_assert) bun.assert(value != .zero); return .{ .impl = .init(global, value) }; } @@ -19,20 +19,20 @@ pub fn deinit(strong: *Strong) void { strong.* = undefined; } -pub fn get(strong: *const Strong) JSC.JSValue { +pub fn get(strong: *const Strong) jsc.JSValue { const result = strong.impl.get(); if (bun.Environment.allow_assert) bun.assert(result != .zero); return result; } /// Set a new value for the strong reference. -pub fn set(strong: *Strong, global: *JSC.JSGlobalObject, new_value: JSC.JSValue) void { +pub fn set(strong: *Strong, global: *jsc.JSGlobalObject, new_value: jsc.JSValue) void { if (bun.Environment.allow_assert) bun.assert(new_value != .zero); strong.impl.set(global, new_value); } /// Swap a new value for the strong reference. -pub fn swap(strong: *Strong, global: *JSC.JSGlobalObject, new_value: JSC.JSValue) JSC.JSValue { +pub fn swap(strong: *Strong, global: *jsc.JSGlobalObject, new_value: jsc.JSValue) jsc.JSValue { const result = strong.impl.get(); strong.set(global, new_value); return result; @@ -46,7 +46,7 @@ pub const Optional = struct { pub const empty: Optional = .{ .impl = null }; /// Hold a strong reference to a JavaScript value. Release with `deinit` or `clear` - pub fn create(value: JSC.JSValue, global: *JSC.JSGlobalObject) Optional { + pub fn create(value: jsc.JSValue, global: *jsc.JSGlobalObject) Optional { return if (value != .zero) .{ .impl = .init(global, value) } else @@ -66,12 +66,12 @@ pub const Optional = struct { ref.clear(); } - pub fn call(this: *Optional, global: *JSC.JSGlobalObject, args: []const JSC.JSValue) JSC.JSValue { + pub fn call(this: *Optional, global: *jsc.JSGlobalObject, args: []const jsc.JSValue) jsc.JSValue { const function = this.trySwap() orelse return .zero; return function.call(global, args); } - pub fn get(this: *const Optional) ?JSC.JSValue { + pub fn get(this: *const Optional) ?jsc.JSValue { const impl = this.impl orelse return null; const result = impl.get(); if (result == .zero) { @@ -80,7 +80,7 @@ pub const Optional = struct { return result; } - pub fn swap(strong: *Optional) JSC.JSValue { + pub fn swap(strong: *Optional) jsc.JSValue { const impl = strong.impl orelse return .zero; const result = impl.get(); if (result == .zero) { @@ -95,7 +95,7 @@ pub const Optional = struct { return ref.get() != .zero; } - pub fn trySwap(this: *Optional) ?JSC.JSValue { + pub fn trySwap(this: *Optional) ?jsc.JSValue { const result = this.swap(); if (result == .zero) { return null; @@ -104,7 +104,7 @@ pub const Optional = struct { return result; } - pub fn set(strong: *Optional, global: *JSC.JSGlobalObject, value: JSC.JSValue) void { + pub fn set(strong: *Optional, global: *jsc.JSGlobalObject, value: jsc.JSValue) void { const ref: *Impl = strong.impl orelse { if (value == .zero) return; strong.impl = Impl.init(global, value); @@ -115,37 +115,37 @@ pub const Optional = struct { }; const Impl = opaque { - pub fn init(global: *JSC.JSGlobalObject, value: JSC.JSValue) *Impl { - JSC.markBinding(@src()); + pub fn init(global: *jsc.JSGlobalObject, value: jsc.JSValue) *Impl { + jsc.markBinding(@src()); return Bun__StrongRef__new(global, value); } - pub fn get(this: *Impl) JSC.JSValue { - JSC.markBinding(@src()); + pub fn get(this: *Impl) jsc.JSValue { + jsc.markBinding(@src()); return Bun__StrongRef__get(this); } - pub fn set(this: *Impl, global: *JSC.JSGlobalObject, value: JSC.JSValue) void { - JSC.markBinding(@src()); + pub fn set(this: *Impl, global: *jsc.JSGlobalObject, value: jsc.JSValue) void { + jsc.markBinding(@src()); Bun__StrongRef__set(this, global, value); } pub fn clear(this: *Impl) void { - JSC.markBinding(@src()); + jsc.markBinding(@src()); Bun__StrongRef__clear(this); } pub fn deinit(this: *Impl) void { - JSC.markBinding(@src()); + jsc.markBinding(@src()); Bun__StrongRef__delete(this); } extern fn Bun__StrongRef__delete(this: *Impl) void; - extern fn Bun__StrongRef__new(*JSC.JSGlobalObject, JSC.JSValue) *Impl; - extern fn Bun__StrongRef__get(this: *Impl) JSC.JSValue; - extern fn Bun__StrongRef__set(this: *Impl, *JSC.JSGlobalObject, JSC.JSValue) void; + extern fn Bun__StrongRef__new(*jsc.JSGlobalObject, jsc.JSValue) *Impl; + extern fn Bun__StrongRef__get(this: *Impl) jsc.JSValue; + extern fn Bun__StrongRef__set(this: *Impl, *jsc.JSGlobalObject, jsc.JSValue) void; extern fn Bun__StrongRef__clear(this: *Impl) void; }; const bun = @import("bun"); -const JSC = bun.JSC; +const jsc = bun.jsc; diff --git a/src/bun.js/VirtualMachine.zig b/src/bun.js/VirtualMachine.zig index 7431f1e8d3..c308939765 100644 --- a/src/bun.js/VirtualMachine.zig +++ b/src/bun.js/VirtualMachine.zig @@ -38,7 +38,7 @@ entry_point: ServerEntryPoint = undefined, origin: URL = URL{}, node_fs: ?*bun.api.node.fs.NodeFS = null, timer: bun.api.Timer.All, -event_loop_handle: ?*JSC.PlatformEventLoop = null, +event_loop_handle: ?*jsc.PlatformEventLoop = null, pending_unref_counter: i32 = 0, preload: []const []const u8 = &.{}, unhandled_pending_rejection_to_capture: ?*JSValue = null, @@ -47,8 +47,8 @@ smol: bool = false, dns_result_order: DNSResolver.Order = .verbatim, counters: Counters = .{}, -hot_reload: bun.CLI.Command.HotReload = .none, -jsc: *VM = undefined, +hot_reload: bun.cli.Command.HotReload = .none, +jsc_vm: *VM = undefined, /// hide bun:wrap from stack traces /// bun:wrap is very noisy @@ -97,7 +97,7 @@ has_patched_run_main: bool = false, transpiler_store: ModuleLoader.RuntimeTranspilerStore, after_event_loop_callback_ctx: ?*anyopaque = null, -after_event_loop_callback: ?JSC.OpaqueCallback = null, +after_event_loop_callback: ?jsc.OpaqueCallback = null, remap_stack_frames_mutex: bun.Mutex = .{}, @@ -122,16 +122,16 @@ macro_event_loop: EventLoop = EventLoop{}, regular_event_loop: EventLoop = EventLoop{}, event_loop: *EventLoop = undefined, -ref_strings: JSC.RefString.Map = undefined, +ref_strings: jsc.RefString.Map = undefined, ref_strings_mutex: bun.Mutex = undefined, active_tasks: usize = 0, -rare_data: ?*JSC.RareData = null, +rare_data: ?*jsc.RareData = null, is_us_loop_entered: bool = false, pending_internal_promise: ?*JSInternalPromise = null, entry_point_result: struct { - value: JSC.Strong.Optional = .empty, + value: jsc.Strong.Optional = .empty, cjs_set_value: bool = false, } = .{}, @@ -149,12 +149,12 @@ aggressive_garbage_collection: GCLevel = GCLevel.none, module_loader: ModuleLoader = .{}, -gc_controller: JSC.GarbageCollectionController = .{}, +gc_controller: jsc.GarbageCollectionController = .{}, worker: ?*webcore.WebWorker = null, ipc: ?IPCInstanceUnion = null, hot_reload_counter: u32 = 0, -debugger: ?JSC.Debugger = null, +debugger: ?jsc.Debugger = null, has_started_debugger: bool = false, has_terminated: bool = false, @@ -202,14 +202,14 @@ pub fn allowAddons(this: *VirtualMachine) callconv(.c) bool { pub fn allowRejectionHandledWarning(this: *VirtualMachine) callconv(.C) bool { return this.unhandledRejectionsMode() != .bun; } -pub fn unhandledRejectionsMode(this: *VirtualMachine) Api.UnhandledRejections { +pub fn unhandledRejectionsMode(this: *VirtualMachine) api.UnhandledRejections { return this.transpiler.options.transform_options.unhandled_rejections orelse switch (bun.FeatureFlags.breaking_changes_1_3) { false => .bun, true => .throw, }; } -pub fn initRequestBodyValue(this: *VirtualMachine, body: JSC.WebCore.Body.Value) !*Body.Value.HiveRef { +pub fn initRequestBodyValue(this: *VirtualMachine, body: jsc.WebCore.Body.Value) !*Body.Value.HiveRef { return .init(body, &this.body_value_hive_allocator); } @@ -404,7 +404,7 @@ pub const UnhandledRejectionScope = struct { onUnhandledRejection: *const OnUnhandledRejection = undefined, count: usize = 0, - pub fn apply(this: *UnhandledRejectionScope, vm: *JSC.VirtualMachine) void { + pub fn apply(this: *UnhandledRejectionScope, vm: *jsc.VirtualMachine) void { vm.onUnhandledRejection = this.onUnhandledRejection; vm.onUnhandledRejectionCtx = this.ctx; vm.unhandled_error_counter = this.count; @@ -512,10 +512,10 @@ extern fn Bun__wrapUnhandledRejectionErrorForUncaughtException(*JSGlobalObject, extern fn Bun__emitHandledPromiseEvent(*JSGlobalObject, promise: JSValue) bool; extern fn Bun__promises__isErrorLike(*JSGlobalObject, reason: JSValue) bool; extern fn Bun__promises__emitUnhandledRejectionWarning(*JSGlobalObject, reason: JSValue, promise: JSValue) void; -extern fn Bun__noSideEffectsToString(vm: *JSC.VM, globalObject: *JSGlobalObject, reason: JSValue) JSValue; +extern fn Bun__noSideEffectsToString(vm: *jsc.VM, globalObject: *JSGlobalObject, reason: JSValue) JSValue; fn isErrorLike(globalObject: *JSGlobalObject, reason: JSValue) bun.JSError!bool { - return bun.jsc.fromJSHostCallGeneric(globalObject, @src(), Bun__promises__isErrorLike, .{ globalObject, reason }); + return jsc.fromJSHostCallGeneric(globalObject, @src(), Bun__promises__isErrorLike, .{ globalObject, reason }); } fn wrapUnhandledRejectionErrorForUncaughtException(globalObject: *JSGlobalObject, reason: JSValue) JSValue { @@ -524,7 +524,7 @@ fn wrapUnhandledRejectionErrorForUncaughtException(globalObject: *JSGlobalObject break :blk false; }) return reason; const reasonStr = blk: { - var scope: bun.jsc.CatchScope = undefined; + var scope: jsc.CatchScope = undefined; scope.init(globalObject, @src()); defer scope.deinit(); defer if (scope.exception()) |_| scope.clearException(); @@ -540,7 +540,7 @@ fn wrapUnhandledRejectionErrorForUncaughtException(globalObject: *JSGlobalObject return globalObject.ERR(.UNHANDLED_REJECTION, msg, .{"undefined"}).toJS(); } -pub fn unhandledRejection(this: *JSC.VirtualMachine, globalObject: *JSGlobalObject, reason: JSValue, promise: JSValue) void { +pub fn unhandledRejection(this: *jsc.VirtualMachine, globalObject: *JSGlobalObject, reason: JSValue, promise: JSValue) void { if (this.isShuttingDown()) { Output.debugWarn("unhandledRejection during shutdown.", .{}); return; @@ -569,7 +569,7 @@ pub fn unhandledRejection(this: *JSC.VirtualMachine, globalObject: *JSGlobalObje error.JSExecutionTerminated => {}, // we are returning anyway }; _ = Bun__handleUnhandledRejection(globalObject, reason, promise); - bun.jsc.fromJSHostCallGeneric(globalObject, @src(), Bun__promises__emitUnhandledRejectionWarning, .{ globalObject, reason, promise }) catch |err| { + jsc.fromJSHostCallGeneric(globalObject, @src(), Bun__promises__emitUnhandledRejectionWarning, .{ globalObject, reason, promise }) catch |err| { _ = globalObject.reportUncaughtException(globalObject.takeException(err).asException(globalObject.vm()).?); }; return; @@ -579,7 +579,7 @@ pub fn unhandledRejection(this: *JSC.VirtualMachine, globalObject: *JSGlobalObje error.JSExecutionTerminated => {}, // we are returning anyway }; if (Bun__handleUnhandledRejection(globalObject, reason, promise) > 0) return; - bun.jsc.fromJSHostCallGeneric(globalObject, @src(), Bun__promises__emitUnhandledRejectionWarning, .{ globalObject, reason, promise }) catch |err| { + jsc.fromJSHostCallGeneric(globalObject, @src(), Bun__promises__emitUnhandledRejectionWarning, .{ globalObject, reason, promise }) catch |err| { _ = globalObject.reportUncaughtException(globalObject.takeException(err).asException(globalObject.vm()).?); }; this.exit_handler.exit_code = 1; @@ -592,7 +592,7 @@ pub fn unhandledRejection(this: *JSC.VirtualMachine, globalObject: *JSGlobalObje const wrapped_reason = wrapUnhandledRejectionErrorForUncaughtException(globalObject, reason); _ = this.uncaughtException(globalObject, wrapped_reason, true); if (Bun__handleUnhandledRejection(globalObject, reason, promise) > 0) return; - bun.jsc.fromJSHostCallGeneric(globalObject, @src(), Bun__promises__emitUnhandledRejectionWarning, .{ globalObject, reason, promise }) catch |err| { + jsc.fromJSHostCallGeneric(globalObject, @src(), Bun__promises__emitUnhandledRejectionWarning, .{ globalObject, reason, promise }) catch |err| { _ = globalObject.reportUncaughtException(globalObject.takeException(err).asException(globalObject.vm()).?); }; return; @@ -622,7 +622,7 @@ pub fn unhandledRejection(this: *JSC.VirtualMachine, globalObject: *JSGlobalObje return; } -pub fn handledPromise(this: *JSC.VirtualMachine, globalObject: *JSGlobalObject, promise: JSValue) bool { +pub fn handledPromise(this: *jsc.VirtualMachine, globalObject: *JSGlobalObject, promise: JSValue) bool { if (this.isShuttingDown()) { return true; } @@ -630,7 +630,7 @@ pub fn handledPromise(this: *JSC.VirtualMachine, globalObject: *JSGlobalObject, return Bun__emitHandledPromiseEvent(globalObject, promise); } -pub fn uncaughtException(this: *JSC.VirtualMachine, globalObject: *JSGlobalObject, err: JSValue, is_rejection: bool) bool { +pub fn uncaughtException(this: *jsc.VirtualMachine, globalObject: *JSGlobalObject, err: JSValue, is_rejection: bool) bool { if (this.isShuttingDown()) { return true; } @@ -663,7 +663,7 @@ pub fn uncaughtException(this: *JSC.VirtualMachine, globalObject: *JSGlobalObjec return handled; } -pub fn handlePendingInternalPromiseRejection(this: *JSC.VirtualMachine) void { +pub fn handlePendingInternalPromiseRejection(this: *jsc.VirtualMachine) void { var promise = this.pending_internal_promise.?; if (promise.status(this.global.vm()) == .rejected and !promise.isHandled(this.global.vm())) { this.unhandledRejection(this.global, promise.result(this.global.vm()), promise.asValue()); @@ -671,7 +671,7 @@ pub fn handlePendingInternalPromiseRejection(this: *JSC.VirtualMachine) void { } } -pub fn defaultOnUnhandledRejection(this: *JSC.VirtualMachine, _: *JSGlobalObject, value: JSValue) void { +pub fn defaultOnUnhandledRejection(this: *jsc.VirtualMachine, _: *JSGlobalObject, value: JSValue) void { this.runErrorHandler(value, this.onUnhandledRejectionExceptionList); } @@ -730,9 +730,9 @@ pub inline fn nodeFS(this: *VirtualMachine) *Node.fs.NodeFS { }; } -pub inline fn rareData(this: *VirtualMachine) *JSC.RareData { +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 = this.allocator.create(jsc.RareData) catch unreachable; this.rare_data.?.* = .{}; break :brk this.rare_data.?; }; @@ -769,7 +769,7 @@ pub fn onBeforeExit(this: *VirtualMachine) void { } } -pub fn scriptExecutionStatus(this: *const VirtualMachine) callconv(.C) JSC.ScriptExecutionStatus { +pub fn scriptExecutionStatus(this: *const VirtualMachine) callconv(.C) jsc.ScriptExecutionStatus { if (this.is_shutting_down) { return .stopped; } @@ -835,12 +835,12 @@ pub fn globalExit(this: *VirtualMachine) noreturn { } pub fn nextAsyncTaskID(this: *VirtualMachine) u64 { - var debugger: *JSC.Debugger = &(this.debugger orelse return 0); + var debugger: *jsc.Debugger = &(this.debugger orelse return 0); debugger.next_debugger_id +%= 1; return debugger.next_debugger_id; } -pub fn hotMap(this: *VirtualMachine) ?*JSC.RareData.HotMap { +pub fn hotMap(this: *VirtualMachine) ?*jsc.RareData.HotMap { if (this.hot_reload != .hot) { return null; } @@ -848,7 +848,7 @@ pub fn hotMap(this: *VirtualMachine) ?*JSC.RareData.HotMap { return this.rareData().hotMap(this.allocator); } -pub inline fn enqueueTask(this: *VirtualMachine, task: JSC.Task) void { +pub inline fn enqueueTask(this: *VirtualMachine, task: jsc.Task) void { this.eventLoop().enqueueTask(task); } @@ -856,7 +856,7 @@ pub inline fn enqueueImmediateTask(this: *VirtualMachine, task: *bun.api.Timer.I this.eventLoop().enqueueImmediateTask(task); } -pub inline fn enqueueTaskConcurrent(this: *VirtualMachine, task: *JSC.ConcurrentTask) void { +pub inline fn enqueueTaskConcurrent(this: *VirtualMachine, task: *jsc.ConcurrentTask) void { this.eventLoop().enqueueTaskConcurrent(task); } @@ -874,7 +874,7 @@ pub fn waitFor(this: *VirtualMachine, cond: *bool) void { } } -pub fn waitForPromise(this: *VirtualMachine, promise: JSC.AnyPromise) void { +pub fn waitForPromise(this: *VirtualMachine, promise: jsc.AnyPromise) void { this.eventLoop().waitForPromise(promise); } @@ -888,10 +888,10 @@ pub fn waitForTasks(this: *VirtualMachine) void { } } -pub const MacroMap = std.AutoArrayHashMap(i32, JSC.C.JSObjectRef); +pub const MacroMap = std.AutoArrayHashMap(i32, jsc.C.JSObjectRef); pub fn enableMacroMode(this: *VirtualMachine) void { - JSC.markBinding(@src()); + jsc.markBinding(@src()); if (!this.has_enabled_macro_mode) { this.has_enabled_macro_mode = true; @@ -907,7 +907,7 @@ pub fn enableMacroMode(this: *VirtualMachine) void { this.transpiler.resolver.caches.fs.use_alternate_source_cache = true; this.macro_mode = true; this.event_loop = &this.macro_event_loop; - bun.Analytics.Features.macros += 1; + bun.analytics.Features.macros += 1; this.transpiler_store.enabled = false; } @@ -946,7 +946,7 @@ pub inline fn isLoaded() bool { pub fn initWithModuleGraph( opts: Options, ) !*VirtualMachine { - JSC.markBinding(@src()); + jsc.markBinding(@src()); const allocator = opts.allocator; VMHolder.vm = try allocator.create(VirtualMachine); const console = try allocator.create(ConsoleObject); @@ -976,7 +976,7 @@ pub fn initWithModuleGraph( .macro_entry_points = @TypeOf(vm.macro_entry_points).init(allocator), .origin_timer = std.time.Timer.start() catch @panic("Timers are not supported on this system."), .origin_timestamp = getOriginTimestamp(), - .ref_strings = JSC.RefString.Map.init(allocator), + .ref_strings = jsc.RefString.Map.init(allocator), .ref_strings_mutex = .{}, .standalone_module_graph = opts.graph.?, .debug_thread_id = if (Environment.allow_assert) std.Thread.getCurrentId(), @@ -1019,11 +1019,11 @@ pub fn initWithModuleGraph( null, ); vm.regular_event_loop.global = vm.global; - vm.jsc = vm.global.vm(); - uws.Loop.get().internal_loop_data.jsc_vm = vm.jsc; + vm.jsc_vm = vm.global.vm(); + uws.Loop.get().internal_loop_data.jsc_vm = vm.jsc_vm; vm.configureDebugger(opts.debugger); - vm.body_value_hive_allocator = Body.Value.HiveAllocator.init(bun.typedAllocator(JSC.WebCore.Body.Value)); + vm.body_value_hive_allocator = Body.Value.HiveAllocator.init(bun.typedAllocator(jsc.WebCore.Body.Value)); return vm; } @@ -1034,7 +1034,7 @@ export fn Bun__isMainThreadVM() callconv(.C) bool { pub const Options = struct { allocator: std.mem.Allocator, - args: Api.TransformOptions, + args: api.TransformOptions, log: ?*logger.Log = null, env_loader: ?*DotEnv.Loader = null, store_fd: bool = false, @@ -1045,7 +1045,7 @@ pub const Options = struct { eval: bool = false, graph: ?*bun.StandaloneModuleGraph = null, - debugger: bun.CLI.Command.Debugger = .{ .unspecified = {} }, + debugger: bun.cli.Command.Debugger = .{ .unspecified = {} }, is_main_thread: bool = false, /// Whether this VM should be destroyed after it exits, even if it is the main thread's VM. /// Worker VMs are always destroyed on exit, regardless of this setting. Setting this to @@ -1056,7 +1056,7 @@ pub const Options = struct { pub var is_smol_mode = false; pub fn init(opts: Options) !*VirtualMachine { - JSC.markBinding(@src()); + jsc.markBinding(@src()); const allocator = opts.allocator; var log: *logger.Log = undefined; if (opts.log) |__log| { @@ -1098,7 +1098,7 @@ pub fn init(opts: Options) !*VirtualMachine { .macro_entry_points = @TypeOf(vm.macro_entry_points).init(allocator), .origin_timer = std.time.Timer.start() catch @panic("Please don't mess with timers."), .origin_timestamp = getOriginTimestamp(), - .ref_strings = JSC.RefString.Map.init(allocator), + .ref_strings = jsc.RefString.Map.init(allocator), .ref_strings_mutex = .{}, .debug_thread_id = if (Environment.allow_assert) std.Thread.getCurrentId(), .destruct_main_thread_on_exit = opts.destruct_main_thread_on_exit, @@ -1137,8 +1137,8 @@ pub fn init(opts: Options) !*VirtualMachine { null, ); vm.regular_event_loop.global = vm.global; - vm.jsc = vm.global.vm(); - uws.Loop.get().internal_loop_data.jsc_vm = vm.jsc; + vm.jsc_vm = vm.global.vm(); + uws.Loop.get().internal_loop_data.jsc_vm = vm.jsc_vm; vm.smol = opts.smol; vm.dns_result_order = opts.dns_result_order; @@ -1146,7 +1146,7 @@ pub fn init(opts: Options) !*VirtualMachine { is_smol_mode = opts.smol; vm.configureDebugger(opts.debugger); - vm.body_value_hive_allocator = Body.Value.HiveAllocator.init(bun.typedAllocator(JSC.WebCore.Body.Value)); + vm.body_value_hive_allocator = Body.Value.HiveAllocator.init(bun.typedAllocator(jsc.WebCore.Body.Value)); return vm; } @@ -1159,7 +1159,7 @@ pub inline fn assertOnJSThread(vm: *const VirtualMachine) void { } } -fn configureDebugger(this: *VirtualMachine, cli_flag: bun.CLI.Command.Debugger) void { +fn configureDebugger(this: *VirtualMachine, cli_flag: bun.cli.Command.Debugger) void { if (bun.getenvZ("HYPERFINE_RANDOMIZED_ENVIRONMENT_OFFSET") != null) { return; } @@ -1170,7 +1170,7 @@ fn configureDebugger(this: *VirtualMachine, cli_flag: bun.CLI.Command.Debugger) const set_breakpoint_on_first_line = unix.len > 0 and strings.endsWith(unix, "?break=1"); // If we should set a breakpoint on the first line const wait_for_debugger = unix.len > 0 and strings.endsWith(unix, "?wait=1"); // If we should wait for the debugger to connect before starting the event loop - const wait_for_connection: JSC.Debugger.Wait = if (set_breakpoint_on_first_line or wait_for_debugger) .forever else .off; + const wait_for_connection: jsc.Debugger.Wait = if (set_breakpoint_on_first_line or wait_for_debugger) .forever else .off; switch (cli_flag) { .unspecified => { @@ -1215,7 +1215,7 @@ pub fn initWorker( worker: *webcore.WebWorker, opts: Options, ) anyerror!*VirtualMachine { - JSC.markBinding(@src()); + jsc.markBinding(@src()); var log: *logger.Log = undefined; const allocator = opts.allocator; if (opts.log) |__log| { @@ -1254,7 +1254,7 @@ pub fn initWorker( .macro_entry_points = @TypeOf(vm.macro_entry_points).init(allocator), .origin_timer = std.time.Timer.start() catch @panic("Please don't mess with timers."), .origin_timestamp = getOriginTimestamp(), - .ref_strings = JSC.RefString.Map.init(allocator), + .ref_strings = jsc.RefString.Map.init(allocator), .ref_strings_mutex = .{}, .standalone_module_graph = worker.parent.standalone_module_graph, .worker = worker, @@ -1300,18 +1300,18 @@ pub fn initWorker( worker.cpp_worker, ); vm.regular_event_loop.global = vm.global; - vm.jsc = vm.global.vm(); - uws.Loop.get().internal_loop_data.jsc_vm = vm.jsc; + vm.jsc_vm = vm.global.vm(); + uws.Loop.get().internal_loop_data.jsc_vm = vm.jsc_vm; vm.transpiler.setAllocator(allocator); - vm.body_value_hive_allocator = Body.Value.HiveAllocator.init(bun.typedAllocator(JSC.WebCore.Body.Value)); + vm.body_value_hive_allocator = Body.Value.HiveAllocator.init(bun.typedAllocator(jsc.WebCore.Body.Value)); return vm; } -extern fn BakeCreateProdGlobal(console_ptr: *anyopaque) *JSC.JSGlobalObject; +extern fn BakeCreateProdGlobal(console_ptr: *anyopaque) *jsc.JSGlobalObject; pub fn initBake(opts: Options) anyerror!*VirtualMachine { - JSC.markBinding(@src()); + jsc.markBinding(@src()); const allocator = opts.allocator; var log: *logger.Log = undefined; if (opts.log) |__log| { @@ -1348,7 +1348,7 @@ pub fn initBake(opts: Options) anyerror!*VirtualMachine { .macro_entry_points = @TypeOf(vm.macro_entry_points).init(allocator), .origin_timer = std.time.Timer.start() catch @panic("Please don't mess with timers."), .origin_timestamp = getOriginTimestamp(), - .ref_strings = JSC.RefString.Map.init(allocator), + .ref_strings = jsc.RefString.Map.init(allocator), .ref_strings_mutex = .{}, .debug_thread_id = if (Environment.allow_assert) std.Thread.getCurrentId(), .destruct_main_thread_on_exit = opts.destruct_main_thread_on_exit, @@ -1365,11 +1365,11 @@ pub fn initBake(opts: Options) anyerror!*VirtualMachine { if (comptime bun.Environment.isWindows) { vm.eventLoop().ensureWaker(); vm.global = BakeCreateProdGlobal(vm.console); - vm.jsc = vm.global.vm(); - uws.Loop.get().internal_loop_data.jsc_vm = vm.jsc; + vm.jsc_vm = vm.global.vm(); + uws.Loop.get().internal_loop_data.jsc_vm = vm.jsc_vm; } else { vm.global = BakeCreateProdGlobal(vm.console); - vm.jsc = vm.global.vm(); + vm.jsc_vm = vm.global.vm(); vm.eventLoop().ensureWaker(); } @@ -1393,14 +1393,14 @@ pub fn initBake(opts: Options) anyerror!*VirtualMachine { is_smol_mode = opts.smol; vm.configureDebugger(opts.debugger); - vm.body_value_hive_allocator = Body.Value.HiveAllocator.init(bun.typedAllocator(JSC.WebCore.Body.Value)); + vm.body_value_hive_allocator = Body.Value.HiveAllocator.init(bun.typedAllocator(jsc.WebCore.Body.Value)); return vm; } pub threadlocal var source_code_printer: ?*js_printer.BufferPrinter = null; -pub fn clearRefString(_: *anyopaque, ref_string: *JSC.RefString) void { +pub fn clearRefString(_: *anyopaque, ref_string: *jsc.RefString) void { _ = VirtualMachine.get().ref_strings.remove(ref_string.hash); } @@ -1430,10 +1430,10 @@ pub fn refCountedResolvedSource(this: *VirtualMachine, code: []const u8, specifi }; } -fn refCountedStringWithWasNew(this: *VirtualMachine, new: *bool, input_: []const u8, hash_: ?u32, comptime dupe: bool) *JSC.RefString { - JSC.markBinding(@src()); +fn refCountedStringWithWasNew(this: *VirtualMachine, new: *bool, input_: []const u8, hash_: ?u32, comptime dupe: bool) *jsc.RefString { + jsc.markBinding(@src()); bun.assert(input_.len > 0); - const hash = hash_ orelse JSC.RefString.computeHash(input_); + const hash = hash_ orelse jsc.RefString.computeHash(input_); this.ref_strings_mutex.lock(); defer this.ref_strings_mutex.unlock(); @@ -1444,12 +1444,12 @@ fn refCountedStringWithWasNew(this: *VirtualMachine, new: *bool, input_: []const else input_; - const ref = this.allocator.create(JSC.RefString) catch unreachable; - ref.* = JSC.RefString{ + const ref = this.allocator.create(jsc.RefString) catch unreachable; + ref.* = jsc.RefString{ .allocator = this.allocator, .ptr = input.ptr, .len = input.len, - .impl = bun.String.createExternal(*JSC.RefString, input, true, ref, &freeRefString).value.WTFStringImpl, + .impl = bun.String.createExternal(*jsc.RefString, input, true, ref, &freeRefString).value.WTFStringImpl, .hash = hash, .ctx = this, .onBeforeDeinit = VirtualMachine.clearRefString, @@ -1460,11 +1460,11 @@ fn refCountedStringWithWasNew(this: *VirtualMachine, new: *bool, input_: []const return entry.value_ptr.*; } -fn freeRefString(str: *JSC.RefString, _: *anyopaque, _: u32) callconv(.C) void { +fn freeRefString(str: *jsc.RefString, _: *anyopaque, _: u32) callconv(.C) void { str.deinit(); } -pub fn refCountedString(this: *VirtualMachine, input_: []const u8, hash_: ?u32, comptime dupe: bool) *JSC.RefString { +pub fn refCountedString(this: *VirtualMachine, input_: []const u8, hash_: ?u32, comptime dupe: bool) *jsc.RefString { bun.assert(input_.len > 0); var _was_new = false; return this.refCountedStringWithWasNew(&_was_new, input_, hash_, comptime dupe); @@ -1490,7 +1490,7 @@ pub fn fetchWithoutOnLoadPlugins( defer referrer_clone.deinit(); var virtual_source_to_use: ?logger.Source = null; - var blob_to_deinit: ?JSC.WebCore.Blob = null; + var blob_to_deinit: ?jsc.WebCore.Blob = null; defer if (blob_to_deinit) |*blob| blob.deinit(); const lr = options.getLoaderAndVirtualSource(specifier_clone.slice(), jsc_vm, &virtual_source_to_use, &blob_to_deinit, null) catch { return error.ModuleNotFound; @@ -1561,7 +1561,7 @@ fn _resolve( ret.result = null; ret.path = specifier; return; - } else if (JSC.ModuleLoader.HardcodedModule.Alias.get(specifier, .bun)) |result| { + } else if (jsc.ModuleLoader.HardcodedModule.Alias.get(specifier, .bun)) |result| { ret.result = null; ret.path = result.path; return; @@ -1574,7 +1574,7 @@ fn _resolve( return; } else if (strings.hasPrefixComptime(specifier, "blob:")) { ret.result = null; - if (JSC.WebCore.ObjectURLRegistry.singleton().has(specifier["blob:".len..])) { + if (jsc.WebCore.ObjectURLRegistry.singleton().has(specifier["blob:".len..])) { ret.path = specifier; return; } else { @@ -1732,7 +1732,7 @@ pub fn resolveMaybeNeedsTrailingSlash( } } - if (JSC.ModuleLoader.HardcodedModule.Alias.get(specifier_utf8.slice(), .bun)) |hardcoded| { + if (jsc.ModuleLoader.HardcodedModule.Alias.get(specifier_utf8.slice(), .bun)) |hardcoded| { res.* = ErrorableString.ok( if (is_user_require_resolve and hardcoded.node_builtin) specifier @@ -1811,7 +1811,7 @@ pub fn resolveMaybeNeedsTrailingSlash( pub const main_file_name: string = "bun:main"; -pub export fn Bun__drainMicrotasksFromJS(globalObject: *JSGlobalObject, callframe: *JSC.CallFrame) callconv(JSC.conv) JSValue { +pub export fn Bun__drainMicrotasksFromJS(globalObject: *JSGlobalObject, callframe: *jsc.CallFrame) callconv(jsc.conv) JSValue { _ = callframe; // autofix globalObject.bunVM().drainMicrotasks(); return .js_undefined; @@ -1909,7 +1909,7 @@ pub fn deinit(this: *VirtualMachine) void { this.has_terminated = true; } -pub const ExceptionList = std.ArrayList(Api.JsException); +pub const ExceptionList = std.ArrayList(api.JsException); pub fn printException( this: *VirtualMachine, @@ -1957,7 +1957,7 @@ pub noinline fn runErrorHandler(this: *VirtualMachine, result: JSValue, exceptio const writer = buffered_writer.writer(); - if (result.asException(this.jsc)) |exception| { + if (result.asException(this.jsc_vm)) |exception| { this.printException( exception, exception_list, @@ -2054,7 +2054,7 @@ fn loadPreloads(this: *VirtualMachine) !?*JSInternalPromise { } } else { this.eventLoop().performGC(); - this.waitForPromise(JSC.AnyPromise{ + this.waitForPromise(jsc.AnyPromise{ .internal = promise, }); } @@ -2071,10 +2071,10 @@ fn loadPreloads(this: *VirtualMachine) !?*JSInternalPromise { pub fn ensureDebugger(this: *VirtualMachine, block_until_connected: bool) !void { if (this.debugger != null) { - try JSC.Debugger.create(this, this.global); + try jsc.Debugger.create(this, this.global); if (block_until_connected) { - JSC.Debugger.waitForDebuggerIfNecessary(this); + jsc.Debugger.waitForDebuggerIfNecessary(this); } } } @@ -2111,7 +2111,7 @@ pub fn reloadEntryPoint(this: *VirtualMachine, entry_path: []const u8) !*JSInter if (this.has_patched_run_main) { @branchHint(.cold); this.pending_internal_promise = null; - const ret = try bun.jsc.fromJSHostCall(this.global, @src(), NodeModuleModule__callOverriddenRunMain, .{ this.global, try bun.String.createUTF8ForJS(this.global, main_file_name) }); + const ret = try jsc.fromJSHostCall(this.global, @src(), NodeModuleModule__callOverriddenRunMain, .{ this.global, try bun.String.createUTF8ForJS(this.global, main_file_name) }); if (this.pending_internal_promise == prev or this.pending_internal_promise == null) { this.pending_internal_promise = JSInternalPromise.resolvedPromise(this.global, ret); return this.pending_internal_promise.?; @@ -2123,7 +2123,7 @@ pub fn reloadEntryPoint(this: *VirtualMachine, entry_path: []const u8) !*JSInter const promise = if (!this.main_is_html_entrypoint) JSModuleLoader.loadAndEvaluateModule(this.global, &String.init(main_file_name)) orelse return error.JSError else - try bun.jsc.fromJSHostCallGeneric(this.global, @src(), Bun__loadHTMLEntryPoint, .{this.global}); + try jsc.fromJSHostCallGeneric(this.global, @src(), Bun__loadHTMLEntryPoint, .{this.global}); this.pending_internal_promise = promise; JSValue.fromCell(promise).ensureStillAlive(); @@ -2179,7 +2179,7 @@ pub fn reloadEntryPointForTestRunner(this: *VirtualMachine, entry_path: []const pub fn loadEntryPointForWebWorker(this: *VirtualMachine, entry_path: string) anyerror!*JSInternalPromise { const promise = try this.reloadEntryPoint(entry_path); this.eventLoop().performGC(); - this.eventLoop().waitForPromiseWithTermination(JSC.AnyPromise{ + this.eventLoop().waitForPromiseWithTermination(jsc.AnyPromise{ .internal = promise, }); if (this.worker) |worker| { @@ -2291,7 +2291,7 @@ pub fn loadMacroEntryPoint(this: *VirtualMachine, entry_path: string, function_n /// and it is not safe to copy the lock itself /// So we have to wrap entry points to & from JavaScript with an API lock that calls out to C++ pub inline fn runWithAPILock(this: *VirtualMachine, comptime Context: type, ctx: *Context, comptime function: fn (ctx: *Context) void) void { - this.global.vm().holdAPILock(ctx, JSC.OpaqueWrap(Context, function)); + this.global.vm().holdAPILock(ctx, jsc.OpaqueWrap(Context, function)); } const MacroEntryPointLoader = struct { @@ -2306,7 +2306,7 @@ pub inline fn _loadMacroEntryPoint(this: *VirtualMachine, entry_path: string) ?* var promise: *JSInternalPromise = undefined; promise = JSModuleLoader.loadAndEvaluateModule(this.global, &String.init(entry_path)) orelse return null; - this.waitForPromise(JSC.AnyPromise{ + this.waitForPromise(jsc.AnyPromise{ .internal = promise, }); @@ -2559,13 +2559,13 @@ pub fn printStackTrace(comptime Writer: type, writer: Writer, trace: ZigStackTra } } -pub export fn Bun__remapStackFramePositions(vm: *JSC.VirtualMachine, frames: [*]JSC.ZigStackFrame, frames_count: usize) void { +pub export fn Bun__remapStackFramePositions(vm: *jsc.VirtualMachine, frames: [*]jsc.ZigStackFrame, frames_count: usize) void { // **Warning** this method can be called in the heap collector thread!! // https://github.com/oven-sh/bun/issues/17087 vm.remapStackFramePositions(frames, frames_count); } -pub fn remapStackFramePositions(this: *VirtualMachine, frames: [*]JSC.ZigStackFrame, frames_count: usize) void { +pub fn remapStackFramePositions(this: *VirtualMachine, frames: [*]jsc.ZigStackFrame, frames_count: usize) void { for (frames[0..frames_count]) |*frame| { if (frame.position.isInvalid() or frame.remapped) continue; var sourceURL = frame.source_url.toUTF8(bun.default_allocator); @@ -2636,7 +2636,7 @@ pub fn remapZigException( .{"processTicksAndRejections"}, }); - var frames: []JSC.ZigStackFrame = exception.stack.frames_ptr[0..exception.stack.frames_len]; + var frames: []jsc.ZigStackFrame = exception.stack.frames_ptr[0..exception.stack.frames_len]; if (this.hide_bun_stackframes) { var start_index: ?usize = null; for (frames, 0..) |frame, i| { @@ -2945,7 +2945,7 @@ fn printErrorInstance( const is_error_instance = mode == .js and (error_instance != .zero and error_instance.jsType() == .ErrorInstance); const code: ?[]const u8 = if (is_error_instance) code: { - if (error_instance.uncheckedPtrCast(JSC.JSObject).getCodePropertyVMInquiry(this.global)) |code_value| { + if (error_instance.uncheckedPtrCast(jsc.JSObject).getCodePropertyVMInquiry(this.global)) |code_value| { if (code_value.isString()) { const code_string = code_value.toBunString(this.global) catch { // JSC::JSString to WTF::String can only fail on out of memory. @@ -3067,7 +3067,7 @@ fn printErrorInstance( if (is_error_instance) { var saw_cause = false; - const Iterator = JSC.JSPropertyIterator(.{ + const Iterator = jsc.JSPropertyIterator(.{ .include_value = true, .skip_empty_name = true, .own_properties_only = true, @@ -3135,7 +3135,7 @@ fn printErrorInstance( } formatter.format( - try JSC.Formatter.Tag.getAdvanced( + try jsc.Formatter.Tag.getAdvanced( value, this.global, .{ .disable_inspect_custom = true, .hide_global = true }, @@ -3185,7 +3185,7 @@ fn printErrorInstance( } } else if (mode == .js and error_instance != .zero) { // If you do reportError([1,2,3]] we should still show something at least. - const tag = try JSC.Formatter.Tag.getAdvanced( + const tag = try jsc.Formatter.Tag.getAdvanced( error_instance, this.global, .{ .disable_inspect_custom = true, .hide_global = true }, @@ -3474,9 +3474,9 @@ pub const IPCInstance = struct { } pub fn handleIPCMessage(this: *IPCInstance, message: IPC.DecodedIPCMessage, handle: JSValue) void { - JSC.markBinding(@src()); + jsc.markBinding(@src()); const globalThis = this.globalThis; - const event_loop = JSC.VirtualMachine.get().eventLoop(); + const event_loop = jsc.VirtualMachine.get().eventLoop(); switch (message) { // In future versions we can read this in order to detect version mismatches, @@ -3615,7 +3615,7 @@ pub const ExitHandler = struct { extern fn Bun__closeAllSQLiteDatabasesForTermination() void; pub fn dispatchOnExit(this: *ExitHandler) void { - JSC.markBinding(@src()); + jsc.markBinding(@src()); const vm: *VirtualMachine = @alignCast(@fieldParentPtr("exit_handler", this)); Process__dispatchOnExit(vm.global, this.exit_code); if (vm.isMainThread()) { @@ -3624,9 +3624,9 @@ pub const ExitHandler = struct { } pub fn dispatchOnBeforeExit(this: *ExitHandler) void { - JSC.markBinding(@src()); + jsc.markBinding(@src()); const vm: *VirtualMachine = @alignCast(@fieldParentPtr("exit_handler", this)); - bun.jsc.fromJSHostCallGeneric(vm.global, @src(), Process__dispatchOnBeforeExit, .{ vm.global, this.exit_code }) catch return; + jsc.fromJSHostCallGeneric(vm.global, @src(), Process__dispatchOnBeforeExit, .{ vm.global, this.exit_code }) catch return; } }; @@ -3640,9 +3640,6 @@ const Resolver = @import("../resolver/resolver.zig"); const Runtime = @import("../runtime.zig"); const node_module_module = @import("./bindings/NodeModuleModule.zig"); const std = @import("std"); -const Api = @import("../api/schema.zig").Api; -const Arena = @import("../allocators/mimalloc_arena.zig").Arena; -const DNSResolver = @import("./api/bun/dns_resolver.zig").DNSResolver; const PackageManager = @import("../install/install.zig").PackageManager; const URL = @import("../url.zig").URL; const Allocator = std.mem.Allocator; @@ -3660,40 +3657,43 @@ const String = bun.String; const Transpiler = bun.Transpiler; const Watcher = bun.Watcher; const default_allocator = bun.default_allocator; -const js_ast = bun.JSAst; +const js_ast = bun.ast; const js_printer = bun.js_printer; const logger = bun.logger; const options = bun.options; const strings = bun.strings; const uws = bun.uws; +const Arena = bun.allocators.MimallocArena; const PluginRunner = bun.transpiler.PluginRunner; +const api = bun.schema.api; +const DNSResolver = bun.api.dns.Resolver; -const JSC = bun.jsc; -const ConsoleObject = JSC.ConsoleObject; -const ErrorableResolvedSource = JSC.ErrorableResolvedSource; -const ErrorableString = JSC.ErrorableString; -const EventLoop = JSC.EventLoop; -const Exception = JSC.Exception; -const JSGlobalObject = JSC.JSGlobalObject; -const JSInternalPromise = JSC.JSInternalPromise; -const JSModuleLoader = JSC.JSModuleLoader; -const JSValue = JSC.JSValue; -const Node = JSC.Node; -const ResolvedSource = JSC.ResolvedSource; -const SavedSourceMap = JSC.SavedSourceMap; -const VM = JSC.VM; -const ZigException = JSC.ZigException; -const ZigStackTrace = JSC.ZigStackTrace; -const ZigString = JSC.ZigString; -const Bun = JSC.API.Bun; +const jsc = bun.jsc; +const ConsoleObject = jsc.ConsoleObject; +const ErrorableResolvedSource = jsc.ErrorableResolvedSource; +const ErrorableString = jsc.ErrorableString; +const EventLoop = jsc.EventLoop; +const Exception = jsc.Exception; +const JSGlobalObject = jsc.JSGlobalObject; +const JSInternalPromise = jsc.JSInternalPromise; +const JSModuleLoader = jsc.JSModuleLoader; +const JSValue = jsc.JSValue; +const Node = jsc.Node; +const ResolvedSource = jsc.ResolvedSource; +const SavedSourceMap = jsc.SavedSourceMap; +const VM = jsc.VM; +const ZigException = jsc.ZigException; +const ZigStackTrace = jsc.ZigStackTrace; +const ZigString = jsc.ZigString; +const Bun = jsc.API.Bun; -const ModuleLoader = JSC.ModuleLoader; +const ModuleLoader = jsc.ModuleLoader; const FetchFlags = ModuleLoader.FetchFlags; -const RuntimeTranspilerStore = JSC.ModuleLoader.RuntimeTranspilerStore; +const RuntimeTranspilerStore = jsc.ModuleLoader.RuntimeTranspilerStore; const node_fallbacks = ModuleLoader.node_fallbacks; -const HotReloader = JSC.hot_reloader.HotReloader; -const ImportWatcher = JSC.hot_reloader.ImportWatcher; +const HotReloader = jsc.hot_reloader.HotReloader; +const ImportWatcher = jsc.hot_reloader.ImportWatcher; const MacroEntryPoint = bun.transpiler.EntryPoints.MacroEntryPoint; const ServerEntryPoint = bun.transpiler.EntryPoints.ServerEntryPoint; diff --git a/src/bun.js/Weak.zig b/src/bun.js/Weak.zig index ce926e00d9..f3009b10b7 100644 --- a/src/bun.js/Weak.zig +++ b/src/bun.js/Weak.zig @@ -4,38 +4,38 @@ pub const WeakRefType = enum(u32) { PostgreSQLQueryClient = 2, }; const WeakImpl = opaque { - pub fn init(globalThis: *JSC.JSGlobalObject, value: JSC.JSValue, refType: WeakRefType, ctx: ?*anyopaque) *WeakImpl { - JSC.markBinding(@src()); + pub fn init(globalThis: *jsc.JSGlobalObject, value: jsc.JSValue, refType: WeakRefType, ctx: ?*anyopaque) *WeakImpl { + jsc.markBinding(@src()); return Bun__WeakRef__new(globalThis, value, refType, ctx); } - pub fn get(this: *WeakImpl) JSC.JSValue { - JSC.markBinding(@src()); + pub fn get(this: *WeakImpl) jsc.JSValue { + jsc.markBinding(@src()); return Bun__WeakRef__get(this); } pub fn clear(this: *WeakImpl) void { - JSC.markBinding(@src()); + jsc.markBinding(@src()); Bun__WeakRef__clear(this); } pub fn deinit( this: *WeakImpl, ) void { - JSC.markBinding(@src()); + jsc.markBinding(@src()); Bun__WeakRef__delete(this); } extern fn Bun__WeakRef__delete(this: *WeakImpl) void; - extern fn Bun__WeakRef__new(*JSC.JSGlobalObject, JSC.JSValue, refType: WeakRefType, ctx: ?*anyopaque) *WeakImpl; - extern fn Bun__WeakRef__get(this: *WeakImpl) JSC.JSValue; + extern fn Bun__WeakRef__new(*jsc.JSGlobalObject, jsc.JSValue, refType: WeakRefType, ctx: ?*anyopaque) *WeakImpl; + extern fn Bun__WeakRef__get(this: *WeakImpl) jsc.JSValue; extern fn Bun__WeakRef__clear(this: *WeakImpl) void; }; pub fn Weak(comptime T: type) type { return struct { ref: ?*WeakImpl = null, - globalThis: ?*JSC.JSGlobalObject = null, + globalThis: ?*jsc.JSGlobalObject = null, const WeakType = @This(); pub fn init() WeakType { @@ -44,15 +44,15 @@ pub fn Weak(comptime T: type) type { pub fn call( this: *WeakType, - args: []const JSC.JSValue, - ) JSC.JSValue { + args: []const jsc.JSValue, + ) jsc.JSValue { const function = this.trySwap() orelse return .zero; return function.call(this.globalThis.?, args); } pub fn create( - value: JSC.JSValue, - globalThis: *JSC.JSGlobalObject, + value: jsc.JSValue, + globalThis: *jsc.JSGlobalObject, refType: WeakRefType, ctx: *T, ) WeakType { @@ -63,7 +63,7 @@ pub fn Weak(comptime T: type) type { return .{ .globalThis = globalThis }; } - pub fn get(this: *const WeakType) ?JSC.JSValue { + pub fn get(this: *const WeakType) ?jsc.JSValue { var ref = this.ref orelse return null; const result = ref.get(); if (result == .zero) { @@ -73,7 +73,7 @@ pub fn Weak(comptime T: type) type { return result; } - pub fn swap(this: *WeakType) JSC.JSValue { + pub fn swap(this: *WeakType) jsc.JSValue { var ref = this.ref orelse return .zero; const result = ref.get(); if (result == .zero) { @@ -89,7 +89,7 @@ pub fn Weak(comptime T: type) type { return ref.get() != .zero; } - pub fn trySwap(this: *WeakType) ?JSC.JSValue { + pub fn trySwap(this: *WeakType) ?jsc.JSValue { const result = this.swap(); if (result == .zero) { return null; @@ -112,4 +112,4 @@ pub fn Weak(comptime T: type) type { } const bun = @import("bun"); -const JSC = bun.JSC; +const jsc = bun.jsc; diff --git a/src/bun.js/api.zig b/src/bun.js/api.zig index 19e921e83a..fd1f1b66e6 100644 --- a/src/bun.js/api.zig +++ b/src/bun.js/api.zig @@ -3,49 +3,52 @@ /// `globalThis.Bun` pub const Bun = @import("./api/BunObject.zig"); +pub const server = @import("./api/server.zig"); +pub const AnyRequestContext = server.AnyRequestContext; +pub const AnyServer = server.AnyServer; +pub const DebugHTTPSServer = server.DebugHTTPSServer; +pub const DebugHTTPServer = server.DebugHTTPServer; +pub const HTMLBundle = server.HTMLBundle; +pub const HTTPSServer = server.HTTPSServer; +pub const HTTPServer = server.HTTPServer; +pub const NodeHTTPResponse = server.NodeHTTPResponse; +pub const SavedRequest = server.SavedRequest; +pub const ServerConfig = server.ServerConfig; +pub const ServerWebSocket = server.ServerWebSocket; + +pub const socket = @import("./api/bun/socket.zig"); +pub const Listener = @import("./api/bun/socket.zig").Listener; +pub const SocketAddress = @import("./api/bun/socket.zig").SocketAddress; +pub const TCPSocket = @import("./api/bun/socket.zig").TCPSocket; +pub const TLSSocket = @import("./api/bun/socket.zig").TLSSocket; +pub const SocketHandlers = @import("./api/bun/socket.zig").Handlers; + pub const Subprocess = @import("./api/bun/subprocess.zig"); pub const HashObject = @import("./api/HashObject.zig"); pub const UnsafeObject = @import("./api/UnsafeObject.zig"); pub const TOMLObject = @import("./api/TOMLObject.zig"); pub const Timer = @import("./api/Timer.zig"); pub const FFIObject = @import("./api/FFIObject.zig"); -pub const AnyRequestContext = @import("./api/server.zig").AnyRequestContext; -pub const AnyServer = @import("./api/server.zig").AnyServer; pub const BuildArtifact = @import("./api/JSBundler.zig").BuildArtifact; pub const BuildMessage = @import("./BuildMessage.zig").BuildMessage; -pub const DNS = @import("./api/bun/dns_resolver.zig"); -pub const DebugHTTPSServer = @import("./api/server.zig").DebugHTTPSServer; -pub const DebugHTTPServer = @import("./api/server.zig").DebugHTTPServer; +pub const dns = @import("./api/bun/dns.zig"); pub const FFI = @import("./api/ffi.zig").FFI; pub const HTMLRewriter = @import("./api/html_rewriter.zig"); pub const FileSystemRouter = @import("./api/filesystem_router.zig").FileSystemRouter; pub const Glob = @import("./api/glob.zig"); pub const H2FrameParser = @import("./api/bun/h2_frame_parser.zig").H2FrameParser; -pub const HTMLBundle = @import("./api/server/HTMLBundle.zig"); -pub const HTTPSServer = @import("./api/server.zig").HTTPSServer; -pub const HTTPServer = @import("./api/server.zig").HTTPServer; pub const JSBundler = @import("./api/JSBundler.zig").JSBundler; pub const JSTranspiler = @import("./api/JSTranspiler.zig"); -pub const Listener = @import("./api/bun/socket.zig").Listener; pub const MatchedRoute = @import("./api/filesystem_router.zig").MatchedRoute; pub const NativeBrotli = @import("./node/zlib/NativeBrotli.zig"); pub const NativeZlib = @import("./node/zlib/NativeZlib.zig"); -pub const NodeHTTPResponse = @import("./api/server.zig").NodeHTTPResponse; pub const Postgres = @import("../sql/postgres.zig"); pub const ResolveMessage = @import("./ResolveMessage.zig").ResolveMessage; -pub const SavedRequest = @import("./api/server.zig").SavedRequest; -pub const ServerConfig = @import("./api/server.zig").ServerConfig; -pub const ServerWebSocket = @import("./api/server.zig").ServerWebSocket; pub const Shell = @import("../shell/shell.zig"); -pub const SocketAddress = @import("./api/bun/socket.zig").SocketAddress; -pub const TCPSocket = @import("./api/bun/socket.zig").TCPSocket; -pub const TLSSocket = @import("./api/bun/socket.zig").TLSSocket; -pub const SocketHandlers = @import("./api/bun/socket.zig").Handlers; pub const UDPSocket = @import("./api/bun/udp_socket.zig").UDPSocket; pub const Valkey = @import("../valkey/js_valkey.zig").JSValkeyClient; pub const BlockList = @import("./node/net/BlockList.zig"); pub const NativeZstd = @import("./node/zlib/NativeZstd.zig"); pub const napi = @import("../napi/napi.zig"); - pub const node = @import("./node.zig"); diff --git a/src/bun.js/api/BunObject.zig b/src/bun.js/api/BunObject.zig index e76d4212d5..b7f593046d 100644 --- a/src/bun.js/api/BunObject.zig +++ b/src/bun.js/api/BunObject.zig @@ -39,7 +39,7 @@ pub const BunObject = struct { pub const spawnSync = toJSCallback(host_fn.wrapStaticMethod(api.Subprocess, "spawnSync", false)); pub const udpSocket = toJSCallback(host_fn.wrapStaticMethod(api.UDPSocket, "udpSocket", false)); pub const which = toJSCallback(Bun.which); - pub const write = toJSCallback(JSC.WebCore.Blob.writeFile); + pub const write = toJSCallback(jsc.WebCore.Blob.writeFile); pub const zstdCompressSync = toJSCallback(JSZstd.compressSync); pub const zstdDecompressSync = toJSCallback(JSZstd.decompressSync); pub const zstdCompress = toJSCallback(JSZstd.compress); @@ -90,13 +90,13 @@ pub const BunObject = struct { return "BunObject_callback_" ++ baseName; } - const toJSCallback = JSC.toJSHostFn; + const toJSCallback = jsc.toJSHostFn; - const LazyPropertyCallback = fn (*JSC.JSGlobalObject, *JSC.JSObject) callconv(JSC.conv) JSValue; + const LazyPropertyCallback = fn (*jsc.JSGlobalObject, *jsc.JSObject) callconv(jsc.conv) JSValue; fn toJSGetter(comptime getter: anytype) LazyPropertyCallback { return struct { - pub fn callback(this: *JSC.JSGlobalObject, object: *JSC.JSObject) callconv(JSC.conv) JSValue { + pub fn callback(this: *jsc.JSGlobalObject, object: *jsc.JSObject) callconv(jsc.conv) JSValue { return bun.jsc.toJSHostCall(this, @src(), getter, .{ this, object }); } }.callback; @@ -182,7 +182,7 @@ pub const BunObject = struct { } }; -pub fn shellEscape(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { +pub fn shellEscape(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const arguments = callframe.arguments_old(1); if (arguments.len < 1) { return globalThis.throw("shell escape expected at least 1 argument", .{}); @@ -208,7 +208,7 @@ pub fn shellEscape(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) b return jsval; } -pub fn braces(global: *JSC.JSGlobalObject, brace_str: bun.String, opts: gen.BracesOptions) bun.JSError!JSC.JSValue { +pub fn braces(global: *jsc.JSGlobalObject, brace_str: bun.String, opts: gen.BracesOptions) bun.JSError!jsc.JSValue { const brace_slice = brace_str.toUTF8(bun.default_allocator); defer brace_slice.deinit(); @@ -269,11 +269,11 @@ pub fn braces(global: *JSC.JSGlobalObject, brace_str: bun.String, opts: gen.Brac return bun.String.toJSArray(global, out_strings[0..]); } -pub fn which(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { +pub fn which(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const arguments_ = callframe.arguments_old(2); const path_buf = bun.path_buffer_pool.get(); defer bun.path_buffer_pool.put(path_buf); - var arguments = JSC.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), arguments_.slice()); + var arguments = jsc.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), arguments_.slice()); defer arguments.deinit(); const path_arg = arguments.nextEat() orelse { return globalThis.throw("which: expected 1 argument, got 0", .{}); @@ -289,7 +289,7 @@ pub fn which(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSE } if (path_arg.isEmptyOrUndefinedOrNull()) { - return JSC.JSValue.jsNull(); + return jsc.JSValue.jsNull(); } bin_str = try path_arg.toSlice(globalThis, globalThis.bunVM().allocator); @@ -302,7 +302,7 @@ pub fn which(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSE } if (bin_str.len == 0) { - return JSC.JSValue.jsNull(); + return jsc.JSValue.jsNull(); } path_str = ZigString.Slice.fromUTF8NeverFree( @@ -333,10 +333,10 @@ pub fn which(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSE return ZigString.init(bin_path).withEncoding().toJS(globalThis); } - return JSC.JSValue.jsNull(); + return jsc.JSValue.jsNull(); } -pub fn inspectTable(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { +pub fn inspectTable(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { var args_buf = callframe.argumentsUndef(5); var all_arguments = args_buf.mut(); if (all_arguments[0].isUndefinedOrNull() or !all_arguments[0].isObject()) @@ -404,7 +404,7 @@ pub fn inspectTable(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) return bun.String.createUTF8ForJS(globalThis, array.slice()); } -pub fn inspect(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { +pub fn inspect(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const arguments = callframe.arguments_old(4).slice(); if (arguments.len == 0) return bun.String.empty.toJS(globalThis); @@ -495,15 +495,15 @@ export fn Bun__inspect_singleline(globalThis: *JSGlobalObject, value: JSValue) b return bun.String.cloneUTF8(array.slice()); } -pub fn getInspect(globalObject: *JSC.JSGlobalObject, _: *JSC.JSObject) JSC.JSValue { - const fun = JSC.createCallback(globalObject, ZigString.static("inspect"), 2, inspect); +pub fn getInspect(globalObject: *jsc.JSGlobalObject, _: *jsc.JSObject) jsc.JSValue { + const fun = jsc.createCallback(globalObject, ZigString.static("inspect"), 2, inspect); var str = ZigString.init("nodejs.util.inspect.custom"); - fun.put(globalObject, ZigString.static("custom"), JSC.JSValue.symbolFor(globalObject, &str)); - fun.put(globalObject, ZigString.static("table"), JSC.createCallback(globalObject, ZigString.static("table"), 3, inspectTable)); + fun.put(globalObject, ZigString.static("custom"), jsc.JSValue.symbolFor(globalObject, &str)); + fun.put(globalObject, ZigString.static("table"), jsc.createCallback(globalObject, ZigString.static("table"), 3, inspectTable)); return fun; } -pub fn registerMacro(globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { +pub fn registerMacro(globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const arguments_ = callframe.arguments_old(2); const arguments = arguments_.slice(); if (arguments.len != 2 or !arguments[0].isNumber()) { @@ -530,53 +530,53 @@ pub fn registerMacro(globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFram return .js_undefined; } -pub fn getCWD(globalThis: *JSC.JSGlobalObject, _: *JSC.JSObject) JSC.JSValue { +pub fn getCWD(globalThis: *jsc.JSGlobalObject, _: *jsc.JSObject) jsc.JSValue { return ZigString.init(VirtualMachine.get().transpiler.fs.top_level_dir).toJS(globalThis); } -pub fn getOrigin(globalThis: *JSC.JSGlobalObject, _: *JSC.JSObject) JSC.JSValue { +pub fn getOrigin(globalThis: *jsc.JSGlobalObject, _: *jsc.JSObject) jsc.JSValue { return ZigString.init(VirtualMachine.get().origin.origin).toJS(globalThis); } -pub fn getStdin(globalThis: *JSC.JSGlobalObject, _: *JSC.JSObject) JSC.JSValue { +pub fn getStdin(globalThis: *jsc.JSGlobalObject, _: *jsc.JSObject) jsc.JSValue { var rare_data = globalThis.bunVM().rareData(); var store = rare_data.stdin(); store.ref(); - var blob = JSC.WebCore.Blob.new( - JSC.WebCore.Blob.initWithStore(store, globalThis), + var blob = jsc.WebCore.Blob.new( + jsc.WebCore.Blob.initWithStore(store, globalThis), ); blob.allocator = bun.default_allocator; return blob.toJS(globalThis); } -pub fn getStderr(globalThis: *JSC.JSGlobalObject, _: *JSC.JSObject) JSC.JSValue { +pub fn getStderr(globalThis: *jsc.JSGlobalObject, _: *jsc.JSObject) jsc.JSValue { var rare_data = globalThis.bunVM().rareData(); var store = rare_data.stderr(); store.ref(); - var blob = JSC.WebCore.Blob.new( - JSC.WebCore.Blob.initWithStore(store, globalThis), + var blob = jsc.WebCore.Blob.new( + jsc.WebCore.Blob.initWithStore(store, globalThis), ); blob.allocator = bun.default_allocator; return blob.toJS(globalThis); } -pub fn getStdout(globalThis: *JSC.JSGlobalObject, _: *JSC.JSObject) JSC.JSValue { +pub fn getStdout(globalThis: *jsc.JSGlobalObject, _: *jsc.JSObject) jsc.JSValue { var rare_data = globalThis.bunVM().rareData(); var store = rare_data.stdout(); store.ref(); - var blob = JSC.WebCore.Blob.new( - JSC.WebCore.Blob.initWithStore(store, globalThis), + var blob = jsc.WebCore.Blob.new( + jsc.WebCore.Blob.initWithStore(store, globalThis), ); blob.allocator = bun.default_allocator; return blob.toJS(globalThis); } -pub fn enableANSIColors(globalThis: *JSC.JSGlobalObject, _: *JSC.JSObject) JSC.JSValue { +pub fn enableANSIColors(globalThis: *jsc.JSGlobalObject, _: *jsc.JSObject) jsc.JSValue { _ = globalThis; return JSValue.jsBoolean(Output.enable_ansi_colors); } -pub fn getMain(globalThis: *JSC.JSGlobalObject, _: *JSC.JSObject) JSC.JSValue { +pub fn getMain(globalThis: *jsc.JSGlobalObject, _: *jsc.JSObject) jsc.JSValue { const vm = globalThis.bunVM(); // Attempt to use the resolved filesystem path @@ -626,14 +626,14 @@ pub fn getMain(globalThis: *JSC.JSGlobalObject, _: *JSC.JSObject) JSC.JSValue { return ZigString.init(vm.main).toJS(globalThis); } -pub fn getArgv(globalThis: *JSC.JSGlobalObject, _: *JSC.JSObject) JSC.JSValue { +pub fn getArgv(globalThis: *jsc.JSGlobalObject, _: *jsc.JSObject) jsc.JSValue { return node.process.getArgv(globalThis); } -pub fn openInEditor(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { +pub fn openInEditor(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { var edit = &VirtualMachine.get().rareData().editor_context; const args = callframe.arguments_old(4); - var arguments = JSC.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), args.slice()); + var arguments = jsc.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), args.slice()); defer arguments.deinit(); var path: string = ""; var editor_choice: ?Editor = null; @@ -744,7 +744,7 @@ pub fn getPublicPathWithAssetPrefix( } } -pub fn sleepSync(globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { +pub fn sleepSync(globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const arguments = callframe.arguments_old(1); // Expect at least one argument. We allow more than one but ignore them; this @@ -769,20 +769,20 @@ pub fn sleepSync(globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) b return .js_undefined; } -pub fn gc(vm: *JSC.VirtualMachine, sync: bool) usize { +pub fn gc(vm: *jsc.VirtualMachine, sync: bool) usize { return vm.garbageCollect(sync); } -export fn Bun__gc(vm: *JSC.VirtualMachine, sync: bool) callconv(.C) usize { +export fn Bun__gc(vm: *jsc.VirtualMachine, sync: bool) callconv(.C) usize { return @call(.always_inline, gc, .{ vm, sync }); } -pub fn shrink(globalObject: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!JSC.JSValue { +pub fn shrink(globalObject: *jsc.JSGlobalObject, _: *jsc.CallFrame) bun.JSError!jsc.JSValue { globalObject.vm().shrinkFootprint(); return .js_undefined; } -fn doResolve(globalThis: *JSC.JSGlobalObject, arguments: []const JSValue) bun.JSError!JSC.JSValue { - var args = JSC.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), arguments); +fn doResolve(globalThis: *jsc.JSGlobalObject, arguments: []const JSValue) bun.JSError!jsc.JSValue { + var args = jsc.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), arguments); defer args.deinit(); const specifier = args.protectEatNext() orelse { return globalThis.throwInvalidArguments("Expected a specifier and a from path", .{}); @@ -823,12 +823,12 @@ fn doResolve(globalThis: *JSC.JSGlobalObject, arguments: []const JSValue) bun.JS ); } -fn doResolveWithArgs(ctx: *JSC.JSGlobalObject, specifier: bun.String, from: bun.String, is_esm: bool, comptime is_file_path: bool, is_user_require_resolve: bool) bun.JSError!JSC.JSValue { +fn doResolveWithArgs(ctx: *jsc.JSGlobalObject, specifier: bun.String, from: bun.String, is_esm: bool, comptime is_file_path: bool, is_user_require_resolve: bool) bun.JSError!jsc.JSValue { var errorable: ErrorableString = undefined; var query_string = ZigString.Empty; const specifier_decoded = if (specifier.hasPrefixComptime("file://")) - bun.JSC.URL.pathFromFileURL(specifier) + bun.jsc.URL.pathFromFileURL(specifier) else specifier.dupeRef(); defer specifier_decoded.deref(); @@ -864,20 +864,20 @@ fn doResolveWithArgs(ctx: *JSC.JSGlobalObject, specifier: bun.String, from: bun. return errorable.result.value.toJS(ctx); } -pub fn resolveSync(globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { +pub fn resolveSync(globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { return try doResolve(globalObject, callframe.arguments()); } -pub fn resolve(globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { +pub fn resolve(globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const arguments = callframe.arguments_old(3); const value = doResolve(globalObject, arguments.slice()) catch { const err = globalObject.tryTakeException().?; - return JSC.JSPromise.dangerouslyCreateRejectedPromiseValueWithoutNotifyingVM(globalObject, err); + return jsc.JSPromise.dangerouslyCreateRejectedPromiseValueWithoutNotifyingVM(globalObject, err); }; - return JSC.JSPromise.resolvedPromiseValue(globalObject, value); + return jsc.JSPromise.resolvedPromiseValue(globalObject, value); } -export fn Bun__resolve(global: *JSGlobalObject, specifier: JSValue, source: JSValue, is_esm: bool) JSC.JSValue { +export fn Bun__resolve(global: *JSGlobalObject, specifier: JSValue, source: JSValue, is_esm: bool) jsc.JSValue { const specifier_str = specifier.toBunString(global) catch return .zero; defer specifier_str.deref(); @@ -886,13 +886,13 @@ export fn Bun__resolve(global: *JSGlobalObject, specifier: JSValue, source: JSVa const value = doResolveWithArgs(global, specifier_str, source_str, is_esm, true, false) catch { const err = global.tryTakeException().?; - return JSC.JSPromise.dangerouslyCreateRejectedPromiseValueWithoutNotifyingVM(global, err); + return jsc.JSPromise.dangerouslyCreateRejectedPromiseValueWithoutNotifyingVM(global, err); }; - return JSC.JSPromise.resolvedPromiseValue(global, value); + return jsc.JSPromise.resolvedPromiseValue(global, value); } -export fn Bun__resolveSync(global: *JSGlobalObject, specifier: JSValue, source: JSValue, is_esm: bool, is_user_require_resolve: bool) JSC.JSValue { +export fn Bun__resolveSync(global: *JSGlobalObject, specifier: JSValue, source: JSValue, is_esm: bool, is_user_require_resolve: bool) jsc.JSValue { const specifier_str = specifier.toBunString(global) catch return .zero; defer specifier_str.deref(); @@ -903,7 +903,7 @@ export fn Bun__resolveSync(global: *JSGlobalObject, specifier: JSValue, source: const source_str = source.toBunString(global) catch return .zero; defer source_str.deref(); - return JSC.toJSHostCall(global, @src(), doResolveWithArgs, .{ global, specifier_str, source_str, is_esm, true, is_user_require_resolve }); + return jsc.toJSHostCall(global, @src(), doResolveWithArgs, .{ global, specifier_str, source_str, is_esm, true, is_user_require_resolve }); } export fn Bun__resolveSyncWithPaths( @@ -914,7 +914,7 @@ export fn Bun__resolveSyncWithPaths( is_user_require_resolve: bool, paths_ptr: ?[*]const bun.String, paths_len: usize, -) JSC.JSValue { +) jsc.JSValue { const paths: []const bun.String = if (paths_len == 0) &.{} else paths_ptr.?[0..paths_len]; const specifier_str = specifier.toBunString(global) catch return .zero; @@ -932,32 +932,32 @@ export fn Bun__resolveSyncWithPaths( bun_vm.transpiler.resolver.custom_dir_paths = paths; defer bun_vm.transpiler.resolver.custom_dir_paths = null; - return JSC.toJSHostCall(global, @src(), doResolveWithArgs, .{ global, specifier_str, source_str, is_esm, true, is_user_require_resolve }); + return jsc.toJSHostCall(global, @src(), doResolveWithArgs, .{ global, specifier_str, source_str, is_esm, true, is_user_require_resolve }); } -export fn Bun__resolveSyncWithStrings(global: *JSGlobalObject, specifier: *bun.String, source: *bun.String, is_esm: bool) JSC.JSValue { +export fn Bun__resolveSyncWithStrings(global: *JSGlobalObject, specifier: *bun.String, source: *bun.String, is_esm: bool) jsc.JSValue { Output.scoped(.importMetaResolve, false)("source: {s}, specifier: {s}", .{ source.*, specifier.* }); - return JSC.toJSHostCall(global, @src(), doResolveWithArgs, .{ global, specifier.*, source.*, is_esm, true, false }); + return jsc.toJSHostCall(global, @src(), doResolveWithArgs, .{ global, specifier.*, source.*, is_esm, true, false }); } -export fn Bun__resolveSyncWithSource(global: *JSGlobalObject, specifier: JSValue, source: *bun.String, is_esm: bool, is_user_require_resolve: bool) JSC.JSValue { +export fn Bun__resolveSyncWithSource(global: *JSGlobalObject, specifier: JSValue, source: *bun.String, is_esm: bool, is_user_require_resolve: bool) jsc.JSValue { const specifier_str = specifier.toBunString(global) catch return .zero; defer specifier_str.deref(); if (specifier_str.length() == 0) { return global.ERR(.INVALID_ARG_VALUE, "The argument 'id' must be a non-empty string. Received ''", .{}).throw() catch .zero; } - return JSC.toJSHostCall(global, @src(), doResolveWithArgs, .{ global, specifier_str, source.*, is_esm, true, is_user_require_resolve }); + return jsc.toJSHostCall(global, @src(), doResolveWithArgs, .{ global, specifier_str, source.*, is_esm, true, is_user_require_resolve }); } -pub fn indexOfLine(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { +pub fn indexOfLine(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const arguments_ = callframe.arguments_old(2); const arguments = arguments_.slice(); if (arguments.len == 0) { - return JSC.JSValue.jsNumberFromInt32(-1); + return jsc.JSValue.jsNumberFromInt32(-1); } var buffer = arguments[0].asArrayBuffer(globalThis) orelse { - return JSC.JSValue.jsNumberFromInt32(-1); + return jsc.JSValue.jsNumberFromInt32(-1); }; var offset: usize = 0; @@ -984,7 +984,7 @@ pub fn indexOfLine(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) b } if (byte == '\n') { - return JSC.JSValue.jsNumber(i); + return jsc.JSValue.jsNumber(i); } current_offset = i + 1; @@ -993,23 +993,23 @@ pub fn indexOfLine(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) b } } - return JSC.JSValue.jsNumberFromInt32(-1); + return jsc.JSValue.jsNumberFromInt32(-1); } pub const Crypto = @import("./crypto.zig"); -pub fn nanoseconds(globalThis: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!JSC.JSValue { +pub fn nanoseconds(globalThis: *jsc.JSGlobalObject, _: *jsc.CallFrame) bun.JSError!jsc.JSValue { const ns = globalThis.bunVM().origin_timer.read(); - return JSC.JSValue.jsNumberFromUint64(ns); + return jsc.JSValue.jsNumberFromUint64(ns); } -pub fn serve(globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { +pub fn serve(globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const arguments = callframe.arguments_old(2).slice(); - var config: JSC.API.ServerConfig = brk: { - var args = JSC.CallFrame.ArgumentsSlice.init(globalObject.bunVM(), arguments); - var config: JSC.API.ServerConfig = .{}; + var config: jsc.API.ServerConfig = brk: { + var args = jsc.CallFrame.ArgumentsSlice.init(globalObject.bunVM(), arguments); + var config: jsc.API.ServerConfig = .{}; - try JSC.API.ServerConfig.fromJS( + try jsc.API.ServerConfig.fromJS( globalObject, &config, &args, @@ -1038,23 +1038,23 @@ pub fn serve(globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.J if (hot.getEntry(config.id)) |entry| { switch (entry.tag()) { - @field(@TypeOf(entry.tag()), @typeName(JSC.API.HTTPServer)) => { - var server: *JSC.API.HTTPServer = entry.as(JSC.API.HTTPServer); + @field(@TypeOf(entry.tag()), @typeName(jsc.API.HTTPServer)) => { + var server: *jsc.API.HTTPServer = entry.as(jsc.API.HTTPServer); server.onReloadFromZig(&config, globalObject); return server.js_value.get() orelse .js_undefined; }, - @field(@TypeOf(entry.tag()), @typeName(JSC.API.DebugHTTPServer)) => { - var server: *JSC.API.DebugHTTPServer = entry.as(JSC.API.DebugHTTPServer); + @field(@TypeOf(entry.tag()), @typeName(jsc.API.DebugHTTPServer)) => { + var server: *jsc.API.DebugHTTPServer = entry.as(jsc.API.DebugHTTPServer); server.onReloadFromZig(&config, globalObject); return server.js_value.get() orelse .js_undefined; }, - @field(@TypeOf(entry.tag()), @typeName(JSC.API.DebugHTTPSServer)) => { - var server: *JSC.API.DebugHTTPSServer = entry.as(JSC.API.DebugHTTPSServer); + @field(@TypeOf(entry.tag()), @typeName(jsc.API.DebugHTTPSServer)) => { + var server: *jsc.API.DebugHTTPSServer = entry.as(jsc.API.DebugHTTPSServer); server.onReloadFromZig(&config, globalObject); return server.js_value.get() orelse .js_undefined; }, - @field(@TypeOf(entry.tag()), @typeName(JSC.API.HTTPSServer)) => { - var server: *JSC.API.HTTPSServer = entry.as(JSC.API.HTTPSServer); + @field(@TypeOf(entry.tag()), @typeName(jsc.API.HTTPSServer)) => { + var server: *jsc.API.HTTPSServer = entry.as(jsc.API.HTTPSServer); server.onReloadFromZig(&config, globalObject); return server.js_value.get() orelse .js_undefined; }, @@ -1070,12 +1070,12 @@ pub fn serve(globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.J inline else => |development| { const ServerType = comptime switch (development) { true => switch (has_ssl_config) { - true => JSC.API.DebugHTTPSServer, - false => JSC.API.DebugHTTPServer, + true => jsc.API.DebugHTTPSServer, + false => jsc.API.DebugHTTPServer, }, false => switch (has_ssl_config) { - true => JSC.API.HTTPSServer, - false => JSC.API.HTTPServer, + true => jsc.API.HTTPSServer, + false => jsc.API.HTTPServer, }, }; @@ -1101,10 +1101,10 @@ pub fn serve(globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.J if (vm.debugger) |*debugger| { debugger.http_server_agent.notifyServerStarted( - JSC.API.AnyServer.from(server), + jsc.API.AnyServer.from(server), ); debugger.http_server_agent.notifyServerRoutesUpdated( - JSC.API.AnyServer.from(server), + jsc.API.AnyServer.from(server), ) catch bun.outOfMemory(); } @@ -1115,7 +1115,7 @@ pub fn serve(globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.J } } -pub export fn Bun__escapeHTML16(globalObject: *JSC.JSGlobalObject, input_value: JSValue, ptr: [*]const u16, len: usize) JSValue { +pub export fn Bun__escapeHTML16(globalObject: *jsc.JSGlobalObject, input_value: JSValue, ptr: [*]const u16, len: usize) JSValue { assert(len > 0); const input_slice = ptr[0..len]; const escaped = strings.escapeHTMLForUTF16Input(globalObject.bunVM().allocator, input_slice) catch { @@ -1129,7 +1129,7 @@ pub export fn Bun__escapeHTML16(globalObject: *JSC.JSGlobalObject, input_value: }; } -pub export fn Bun__escapeHTML8(globalObject: *JSC.JSGlobalObject, input_value: JSValue, ptr: [*]const u8, len: usize) JSValue { +pub export fn Bun__escapeHTML8(globalObject: *jsc.JSGlobalObject, input_value: JSValue, ptr: [*]const u8, len: usize) JSValue { assert(len > 0); const input_slice = ptr[0..len]; @@ -1176,22 +1176,22 @@ comptime { _ = Bun__escapeHTML16; } -pub fn allocUnsafe(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { +pub fn allocUnsafe(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const arguments = callframe.arguments_old(1); const size = arguments.ptr[0]; if (!size.isUInt32AsAnyInt()) { return globalThis.throwInvalidArguments("Expected a positive number", .{}); } - return JSC.JSValue.createUninitializedUint8Array(globalThis, size.toUInt64NoTruncate()); + return jsc.JSValue.createUninitializedUint8Array(globalThis, size.toUInt64NoTruncate()); } -pub fn mmapFile(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { +pub fn mmapFile(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { if (comptime Environment.isWindows) { return globalThis.throwTODO("mmapFile is not supported on Windows"); } const arguments_ = callframe.arguments_old(2); - var args = JSC.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), arguments_.slice()); + var args = jsc.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), arguments_.slice()); defer args.deinit(); var buf: bun.PathBuffer = undefined; @@ -1258,35 +1258,35 @@ pub fn mmapFile(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun. return bun.jsc.array_buffer.makeTypedArrayWithBytesNoCopy(globalThis, .TypeUint8, map.ptr, map.len, S.x, @ptrFromInt(map.len)); } -pub fn getTranspilerConstructor(globalThis: *JSC.JSGlobalObject, _: *JSC.JSObject) JSC.JSValue { - return JSC.API.JSTranspiler.js.getConstructor(globalThis); +pub fn getTranspilerConstructor(globalThis: *jsc.JSGlobalObject, _: *jsc.JSObject) jsc.JSValue { + return jsc.API.JSTranspiler.js.getConstructor(globalThis); } -pub fn getFileSystemRouter(globalThis: *JSC.JSGlobalObject, _: *JSC.JSObject) JSC.JSValue { - return JSC.API.FileSystemRouter.js.getConstructor(globalThis); +pub fn getFileSystemRouter(globalThis: *jsc.JSGlobalObject, _: *jsc.JSObject) jsc.JSValue { + return jsc.API.FileSystemRouter.js.getConstructor(globalThis); } -pub fn getHashObject(globalThis: *JSC.JSGlobalObject, _: *JSC.JSObject) JSC.JSValue { +pub fn getHashObject(globalThis: *jsc.JSGlobalObject, _: *jsc.JSObject) jsc.JSValue { return HashObject.create(globalThis); } -pub fn getTOMLObject(globalThis: *JSC.JSGlobalObject, _: *JSC.JSObject) JSC.JSValue { +pub fn getTOMLObject(globalThis: *jsc.JSGlobalObject, _: *jsc.JSObject) jsc.JSValue { return TOMLObject.create(globalThis); } -pub fn getGlobConstructor(globalThis: *JSC.JSGlobalObject, _: *JSC.JSObject) JSC.JSValue { - return JSC.API.Glob.js.getConstructor(globalThis); +pub fn getGlobConstructor(globalThis: *jsc.JSGlobalObject, _: *jsc.JSObject) jsc.JSValue { + return jsc.API.Glob.js.getConstructor(globalThis); } -pub fn getS3ClientConstructor(globalThis: *JSC.JSGlobalObject, _: *JSC.JSObject) JSC.JSValue { - return JSC.WebCore.S3Client.js.getConstructor(globalThis); +pub fn getS3ClientConstructor(globalThis: *jsc.JSGlobalObject, _: *jsc.JSObject) jsc.JSValue { + return jsc.WebCore.S3Client.js.getConstructor(globalThis); } -pub fn getS3DefaultClient(globalThis: *JSC.JSGlobalObject, _: *JSC.JSObject) JSC.JSValue { +pub fn getS3DefaultClient(globalThis: *jsc.JSGlobalObject, _: *jsc.JSObject) jsc.JSValue { return globalThis.bunVM().rareData().s3DefaultClient(globalThis); } -pub fn getValkeyDefaultClient(globalThis: *JSC.JSGlobalObject, _: *JSC.JSObject) JSC.JSValue { - const valkey = JSC.API.Valkey.create(globalThis, &.{.js_undefined}) catch |err| { +pub fn getValkeyDefaultClient(globalThis: *jsc.JSGlobalObject, _: *jsc.JSObject) jsc.JSValue { + const valkey = jsc.API.Valkey.create(globalThis, &.{.js_undefined}) catch |err| { if (err != error.JSError) { _ = globalThis.throwError(err, "Failed to create Redis client") catch {}; return .zero; @@ -1297,13 +1297,13 @@ pub fn getValkeyDefaultClient(globalThis: *JSC.JSGlobalObject, _: *JSC.JSObject) return valkey.toJS(globalThis); } -pub fn getValkeyClientConstructor(globalThis: *JSC.JSGlobalObject, _: *JSC.JSObject) JSC.JSValue { - return JSC.API.Valkey.js.getConstructor(globalThis); +pub fn getValkeyClientConstructor(globalThis: *jsc.JSGlobalObject, _: *jsc.JSObject) jsc.JSValue { + return jsc.API.Valkey.js.getConstructor(globalThis); } -pub fn getEmbeddedFiles(globalThis: *JSC.JSGlobalObject, _: *JSC.JSObject) bun.JSError!JSC.JSValue { +pub fn getEmbeddedFiles(globalThis: *jsc.JSGlobalObject, _: *jsc.JSObject) bun.JSError!jsc.JSValue { const vm = globalThis.bunVM(); - const graph = vm.standalone_module_graph orelse return try JSC.JSValue.createEmptyArray(globalThis, 0); + const graph = vm.standalone_module_graph orelse return try jsc.JSValue.createEmptyArray(globalThis, 0); const unsorted_files = graph.files.values(); var sort_indices = std.ArrayList(u32).initCapacity(bun.default_allocator, unsorted_files.len) catch bun.outOfMemory(); @@ -1318,13 +1318,13 @@ pub fn getEmbeddedFiles(globalThis: *JSC.JSGlobalObject, _: *JSC.JSObject) bun.J } var i: u32 = 0; - var array = try JSC.JSValue.createEmptyArray(globalThis, sort_indices.items.len); + var array = try jsc.JSValue.createEmptyArray(globalThis, sort_indices.items.len); std.mem.sort(u32, sort_indices.items, unsorted_files, bun.StandaloneModuleGraph.File.lessThanByIndex); for (sort_indices.items) |index| { const file = &unsorted_files[index]; // We call .dupe() on this to ensure that we don't return a blob that might get freed later. const input_blob = file.blob(globalThis); - const blob = JSC.WebCore.Blob.new(input_blob.dupeWithContentType(true)); + const blob = jsc.WebCore.Blob.new(input_blob.dupeWithContentType(true)); blob.allocator = bun.default_allocator; blob.name = input_blob.name.dupeRef(); try array.putIndex(globalThis, i, blob.toJS(globalThis)); @@ -1334,11 +1334,11 @@ pub fn getEmbeddedFiles(globalThis: *JSC.JSGlobalObject, _: *JSC.JSObject) bun.J return array; } -pub fn getSemver(globalThis: *JSC.JSGlobalObject, _: *JSC.JSObject) JSC.JSValue { +pub fn getSemver(globalThis: *jsc.JSGlobalObject, _: *jsc.JSObject) jsc.JSValue { return SemverObject.create(globalThis); } -pub fn getUnsafe(globalThis: *JSC.JSGlobalObject, _: *JSC.JSObject) JSC.JSValue { +pub fn getUnsafe(globalThis: *jsc.JSGlobalObject, _: *jsc.JSObject) jsc.JSValue { return UnsafeObject.create(globalThis); } @@ -1354,24 +1354,24 @@ pub fn stringWidth(str: bun.String, opts: gen.StringWidthOptions) usize { /// EnvironmentVariables is runtime defined. /// Also, you can't iterate over process.env normally since it only exists at build-time otherwise -pub fn getCSRFObject(globalObject: *JSC.JSGlobalObject, _: *JSC.JSObject) JSC.JSValue { +pub fn getCSRFObject(globalObject: *jsc.JSGlobalObject, _: *jsc.JSObject) jsc.JSValue { return CSRFObject.create(globalObject); } const CSRFObject = struct { - pub fn create(globalThis: *JSC.JSGlobalObject) JSC.JSValue { + pub fn create(globalThis: *jsc.JSGlobalObject) jsc.JSValue { const object = JSValue.createEmptyObject(globalThis, 2); object.put( globalThis, ZigString.static("generate"), - JSC.createCallback(globalThis, ZigString.static("generate"), 1, @import("../../csrf.zig").csrf__generate), + jsc.createCallback(globalThis, ZigString.static("generate"), 1, @import("../../csrf.zig").csrf__generate), ); object.put( globalThis, ZigString.static("verify"), - JSC.createCallback(globalThis, ZigString.static("verify"), 1, @import("../../csrf.zig").csrf__verify), + jsc.createCallback(globalThis, ZigString.static("verify"), 1, @import("../../csrf.zig").csrf__verify), ); return object; @@ -1380,7 +1380,7 @@ const CSRFObject = struct { // This is aliased to Bun.env pub const EnvironmentVariables = struct { - pub export fn Bun__getEnvCount(globalObject: *JSC.JSGlobalObject, ptr: *[*][]const u8) usize { + pub export fn Bun__getEnvCount(globalObject: *jsc.JSGlobalObject, ptr: *[*][]const u8) usize { const bunVM = globalObject.bunVM(); ptr.* = bunVM.transpiler.env.map.map.keys().ptr; return bunVM.transpiler.env.map.map.unmanaged.entries.len; @@ -1392,7 +1392,7 @@ pub const EnvironmentVariables = struct { return item.len; } - pub export fn Bun__getEnvValue(globalObject: *JSC.JSGlobalObject, name: *ZigString, value: *ZigString) bool { + pub export fn Bun__getEnvValue(globalObject: *jsc.JSGlobalObject, name: *ZigString, value: *ZigString) bool { if (getEnvValue(globalObject, name.*)) |val| { value.* = val; return true; @@ -1401,7 +1401,7 @@ pub const EnvironmentVariables = struct { return false; } - pub fn getEnvNames(globalObject: *JSC.JSGlobalObject, names: []ZigString) usize { + pub fn getEnvNames(globalObject: *jsc.JSGlobalObject, names: []ZigString) usize { var vm = globalObject.bunVM(); const keys = vm.transpiler.env.map.map.keys(); const len = @min(names.len, keys.len); @@ -1411,7 +1411,7 @@ pub const EnvironmentVariables = struct { return len; } - pub fn getEnvValue(globalObject: *JSC.JSGlobalObject, name: ZigString) ?ZigString { + pub fn getEnvValue(globalObject: *jsc.JSGlobalObject, name: ZigString) ?ZigString { var vm = globalObject.bunVM(); var sliced = name.toSlice(vm.allocator); defer sliced.deinit(); @@ -1420,8 +1420,8 @@ pub const EnvironmentVariables = struct { } }; -export fn Bun__reportError(globalObject: *JSGlobalObject, err: JSC.JSValue) void { - _ = JSC.VirtualMachine.get().uncaughtException(globalObject, err, false); +export fn Bun__reportError(globalObject: *JSGlobalObject, err: jsc.JSValue) void { + _ = jsc.VirtualMachine.get().uncaughtException(globalObject, err, false); } comptime { @@ -1439,7 +1439,7 @@ pub const JSZlib = struct { } export fn global_deallocator(_: ?*anyopaque, ctx: ?*anyopaque) void { comptime assert(bun.use_mimalloc); - bun.Mimalloc.mi_free(ctx); + bun.mimalloc.mi_free(ctx); } export fn compressor_deallocator(_: ?*anyopaque, ctx: ?*anyopaque) void { var compressor: *zlib.ZlibCompressorArrayList = bun.cast(*zlib.ZlibCompressorArrayList, ctx.?); @@ -1455,7 +1455,7 @@ pub const JSZlib = struct { }; // This has to be `inline` due to the callframe. - inline fn getOptions(globalThis: *JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!struct { JSC.Node.StringOrBuffer, ?JSValue } { + inline fn getOptions(globalThis: *JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!struct { jsc.Node.StringOrBuffer, ?JSValue } { const arguments = callframe.arguments_old(2).slice(); const buffer_value: JSValue = if (arguments.len > 0) arguments[0] else .js_undefined; const options_val: ?JSValue = @@ -1465,38 +1465,38 @@ pub const JSZlib = struct { return globalThis.throwInvalidArguments("Expected options to be an object", .{}); } else null; - if (try JSC.Node.StringOrBuffer.fromJS(globalThis, bun.default_allocator, buffer_value)) |buffer| { + if (try jsc.Node.StringOrBuffer.fromJS(globalThis, bun.default_allocator, buffer_value)) |buffer| { return .{ buffer, options_val }; } return globalThis.throwInvalidArguments("Expected buffer to be a string or buffer", .{}); } - pub fn gzipSync(globalThis: *JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { + pub fn gzipSync(globalThis: *JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { const buffer, const options_val = try getOptions(globalThis, callframe); defer buffer.deinit(); return gzipOrDeflateSync(globalThis, buffer, options_val, true); } - pub fn inflateSync(globalThis: *JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { + pub fn inflateSync(globalThis: *JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { const buffer, const options_val = try getOptions(globalThis, callframe); defer buffer.deinit(); return gunzipOrInflateSync(globalThis, buffer, options_val, false); } - pub fn deflateSync(globalThis: *JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { + pub fn deflateSync(globalThis: *JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { const buffer, const options_val = try getOptions(globalThis, callframe); defer buffer.deinit(); return gzipOrDeflateSync(globalThis, buffer, options_val, false); } - pub fn gunzipSync(globalThis: *JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { + pub fn gunzipSync(globalThis: *JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { const buffer, const options_val = try getOptions(globalThis, callframe); defer buffer.deinit(); return gunzipOrInflateSync(globalThis, buffer, options_val, true); } - pub fn gunzipOrInflateSync(globalThis: *JSGlobalObject, buffer: JSC.Node.StringOrBuffer, options_val_: ?JSValue, is_gzip: bool) bun.JSError!JSValue { + pub fn gunzipOrInflateSync(globalThis: *JSGlobalObject, buffer: jsc.Node.StringOrBuffer, options_val_: ?JSValue, is_gzip: bool) bun.JSError!JSValue { var opts = zlib.Options{ .gzip = is_gzip, .windowBits = if (is_gzip) 31 else -15, @@ -1537,7 +1537,7 @@ pub const JSZlib = struct { if (globalThis.hasException()) return .zero; const compressed = buffer.slice(); - const allocator = JSC.VirtualMachine.get().allocator; + const allocator = jsc.VirtualMachine.get().allocator; var list = brk: { if (is_gzip and compressed.len > 64) { @@ -1577,7 +1577,7 @@ pub const JSZlib = struct { reader.list.capacity = reader.list.items.len; reader.list_ptr = &reader.list; - var array_buffer = JSC.ArrayBuffer.fromBytes(reader.list.items, .Uint8Array); + var array_buffer = jsc.ArrayBuffer.fromBytes(reader.list.items, .Uint8Array); return array_buffer.toJSWithContext(globalThis, reader, reader_deallocator); }, .libdeflate => { @@ -1613,7 +1613,7 @@ pub const JSZlib = struct { return globalThis.throw("libdeflate returned an error: {s}", .{@tagName(result.status)}); } - var array_buffer = JSC.ArrayBuffer.fromBytes(list.items, .Uint8Array); + var array_buffer = jsc.ArrayBuffer.fromBytes(list.items, .Uint8Array); return array_buffer.toJSWithContext(globalThis, list.items.ptr, global_deallocator); }, } @@ -1621,7 +1621,7 @@ pub const JSZlib = struct { pub fn gzipOrDeflateSync( globalThis: *JSGlobalObject, - buffer: JSC.Node.StringOrBuffer, + buffer: jsc.Node.StringOrBuffer, options_val_: ?JSValue, is_gzip: bool, ) bun.JSError!JSValue { @@ -1684,7 +1684,7 @@ pub const JSZlib = struct { reader.list.capacity = reader.list.items.len; reader.list_ptr = &reader.list; - var array_buffer = JSC.ArrayBuffer.fromBytes(reader.list.items, .Uint8Array); + var array_buffer = jsc.ArrayBuffer.fromBytes(reader.list.items, .Uint8Array); return array_buffer.toJSWithContext(globalThis, reader, reader_deallocator); }, .libdeflate => { @@ -1714,7 +1714,7 @@ pub const JSZlib = struct { return globalThis.throw("libdeflate error: {s}", .{@tagName(result.status)}); } - var array_buffer = JSC.ArrayBuffer.fromBytes(list.items, .Uint8Array); + var array_buffer = jsc.ArrayBuffer.fromBytes(list.items, .Uint8Array); return array_buffer.toJSWithContext(globalThis, list.items.ptr, global_deallocator); }, } @@ -1724,10 +1724,10 @@ pub const JSZlib = struct { pub const JSZstd = struct { export fn deallocator(_: ?*anyopaque, ctx: ?*anyopaque) void { comptime assert(bun.use_mimalloc); - bun.Mimalloc.mi_free(ctx); + bun.mimalloc.mi_free(ctx); } - inline fn getOptions(globalThis: *JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!struct { JSC.Node.StringOrBuffer, ?JSValue } { + inline fn getOptions(globalThis: *JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!struct { jsc.Node.StringOrBuffer, ?JSValue } { const arguments = callframe.arguments(); const buffer_value: JSValue = if (arguments.len > 0) arguments[0] else .js_undefined; const options_val: ?JSValue = @@ -1737,7 +1737,7 @@ pub const JSZstd = struct { return globalThis.throwInvalidArguments("Expected options to be an object", .{}); } else null; - if (try JSC.Node.StringOrBuffer.fromJS(globalThis, bun.default_allocator, buffer_value)) |buffer| { + if (try jsc.Node.StringOrBuffer.fromJS(globalThis, bun.default_allocator, buffer_value)) |buffer| { return .{ buffer, options_val }; } @@ -1761,7 +1761,7 @@ pub const JSZstd = struct { return 3; } - inline fn getOptionsAsync(globalThis: *JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!struct { JSC.Node.StringOrBuffer, ?JSValue, i32 } { + inline fn getOptionsAsync(globalThis: *JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!struct { jsc.Node.StringOrBuffer, ?JSValue, i32 } { const arguments = callframe.arguments(); const buffer_value: JSValue = if (arguments.len > 0) arguments[0] else .js_undefined; const options_val: ?JSValue = @@ -1774,14 +1774,14 @@ pub const JSZstd = struct { const level = try getLevel(globalThis, options_val); const allow_string_object = true; - if (try JSC.Node.StringOrBuffer.fromJSMaybeAsync(globalThis, bun.default_allocator, buffer_value, true, allow_string_object)) |buffer| { + if (try jsc.Node.StringOrBuffer.fromJSMaybeAsync(globalThis, bun.default_allocator, buffer_value, true, allow_string_object)) |buffer| { return .{ buffer, options_val, level }; } return globalThis.throwInvalidArguments("Expected buffer to be a string or buffer", .{}); } - pub fn compressSync(globalThis: *JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { + pub fn compressSync(globalThis: *JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { const buffer, const options_val = try getOptions(globalThis, callframe); defer buffer.deinit(); @@ -1808,10 +1808,10 @@ pub const JSZstd = struct { output = try allocator.realloc(output, compressed_size); } - return JSC.JSValue.createBuffer(globalThis, output, bun.default_allocator); + return jsc.JSValue.createBuffer(globalThis, output, bun.default_allocator); } - pub fn decompressSync(globalThis: *JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { + pub fn decompressSync(globalThis: *JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { const buffer, _ = try getOptions(globalThis, callframe); defer buffer.deinit(); @@ -1843,28 +1843,28 @@ pub const JSZstd = struct { // mimalloc doesn't care about the self-reported size of the slice. output.len = actual_size; - return JSC.JSValue.createBuffer(globalThis, output, bun.default_allocator); + return jsc.JSValue.createBuffer(globalThis, output, bun.default_allocator); } // --- Async versions --- pub const ZstdJob = struct { - buffer: JSC.Node.StringOrBuffer = JSC.Node.StringOrBuffer.empty, + buffer: jsc.Node.StringOrBuffer = jsc.Node.StringOrBuffer.empty, is_compress: bool = true, level: i32 = 3, - task: JSC.WorkPoolTask = .{ .callback = &runTask }, - promise: JSC.JSPromise.Strong = .{}, - vm: *JSC.VirtualMachine, + task: jsc.WorkPoolTask = .{ .callback = &runTask }, + promise: jsc.JSPromise.Strong = .{}, + vm: *jsc.VirtualMachine, output: []u8 = &[_]u8{}, error_message: ?[]const u8 = null, - any_task: JSC.AnyTask = undefined, + any_task: jsc.AnyTask = undefined, poll: Async.KeepAlive = .{}, pub const new = bun.TrivialNew(@This()); - pub fn runTask(task: *JSC.WorkPoolTask) void { + pub fn runTask(task: *jsc.WorkPoolTask) void { const job: *ZstdJob = @fieldParentPtr("task", task); - defer job.vm.enqueueTaskConcurrent(JSC.ConcurrentTask.create(job.any_task.task())); + defer job.vm.enqueueTaskConcurrent(jsc.ConcurrentTask.create(job.any_task.task())); const input = job.buffer.slice(); const allocator = bun.default_allocator; @@ -1945,7 +1945,7 @@ pub const JSZstd = struct { } const output_slice = this.output; - const buffer_value = JSC.JSValue.createBuffer(globalThis, output_slice, bun.default_allocator); + const buffer_value = jsc.JSValue.createBuffer(globalThis, output_slice, bun.default_allocator); this.output = &[_]u8{}; promise.resolve(globalThis, buffer_value); } @@ -1958,7 +1958,7 @@ pub const JSZstd = struct { bun.destroy(this); } - pub fn create(vm: *JSC.VirtualMachine, globalThis: *JSC.JSGlobalObject, buffer: JSC.Node.StringOrBuffer, is_compress: bool, level: i32) *ZstdJob { + pub fn create(vm: *jsc.VirtualMachine, globalThis: *jsc.JSGlobalObject, buffer: jsc.Node.StringOrBuffer, is_compress: bool, level: i32) *ZstdJob { var job = ZstdJob.new(.{ .buffer = buffer, .is_compress = is_compress, @@ -1967,16 +1967,16 @@ pub const JSZstd = struct { .any_task = undefined, }); - job.promise = JSC.JSPromise.Strong.init(globalThis); - job.any_task = JSC.AnyTask.New(@This(), &runFromJS).init(job); + job.promise = jsc.JSPromise.Strong.init(globalThis); + job.any_task = jsc.AnyTask.New(@This(), &runFromJS).init(job); job.poll.ref(vm); - JSC.WorkPool.schedule(&job.task); + jsc.WorkPool.schedule(&job.task); return job; } }; - pub fn compress(globalThis: *JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { + pub fn compress(globalThis: *JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { const buffer, _, const level = try getOptionsAsync(globalThis, callframe); const vm = globalThis.bunVM(); @@ -1984,7 +1984,7 @@ pub const JSZstd = struct { return job.promise.value(); } - pub fn decompress(globalThis: *JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { + pub fn decompress(globalThis: *JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { const buffer, _, _ = try getOptionsAsync(globalThis, callframe); const vm = globalThis.bunVM(); @@ -1994,7 +1994,7 @@ pub const JSZstd = struct { }; // const InternalTestingAPIs = struct { -// pub fn BunInternalFunction__syntaxHighlighter(globalThis: *JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { +// pub fn BunInternalFunction__syntaxHighlighter(globalThis: *JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { // const args = callframe.arguments_old(1); // if (args.len < 1) { // globalThis.throwNotEnoughArguments("code", 1, 0); @@ -2027,6 +2027,8 @@ comptime { BunObject.exportAll(); } +const string = []const u8; + const Braces = @import("../../shell/braces.zig"); const Which = @import("../../which.zig"); const options = @import("../../options.zig"); @@ -2043,24 +2045,9 @@ const MutableString = bun.MutableString; const Output = bun.Output; const assert = bun.assert; const default_allocator = bun.default_allocator; -const string = bun.string; const strings = bun.strings; const SemverObject = bun.Semver.SemverObject; const gen = bun.gen.BunObject; -const host_fn = bun.jsc.host_fn; - -const JSC = bun.JSC; -const ConsoleObject = bun.JSC.ConsoleObject; -const ErrorableString = JSC.ErrorableString; -const JSGlobalObject = bun.JSC.JSGlobalObject; -const JSPromise = bun.JSC.JSPromise; -const JSValue = bun.JSC.JSValue; -const VirtualMachine = JSC.VirtualMachine; -const WebCore = bun.JSC.WebCore; -const ZigString = bun.JSC.ZigString; - -const JSBundler = bun.JSC.API.JSBundler; -const Transpiler = bun.JSC.API.JSTranspiler; const api = bun.api; const FFIObject = bun.api.FFIObject; @@ -2068,3 +2055,17 @@ const HashObject = bun.api.HashObject; const TOMLObject = bun.api.TOMLObject; const UnsafeObject = bun.api.UnsafeObject; const node = bun.api.node; + +const jsc = bun.jsc; +const ConsoleObject = bun.jsc.ConsoleObject; +const ErrorableString = jsc.ErrorableString; +const JSGlobalObject = bun.jsc.JSGlobalObject; +const JSPromise = bun.jsc.JSPromise; +const JSValue = bun.jsc.JSValue; +const VirtualMachine = jsc.VirtualMachine; +const WebCore = bun.jsc.WebCore; +const ZigString = bun.jsc.ZigString; +const host_fn = bun.jsc.host_fn; + +const JSBundler = bun.jsc.API.JSBundler; +const Transpiler = bun.jsc.API.JSTranspiler; diff --git a/src/bun.js/api/FFIObject.zig b/src/bun.js/api/FFIObject.zig index 94a2a67139..0cdc3c54b8 100644 --- a/src/bun.js/api/FFIObject.zig +++ b/src/bun.js/api/FFIObject.zig @@ -1,6 +1,6 @@ const FFIObject = @This(); -pub fn newCString(globalThis: *JSGlobalObject, value: JSValue, byteOffset: ?JSValue, lengthValue: ?JSValue) bun.JSError!JSC.JSValue { +pub fn newCString(globalThis: *JSGlobalObject, value: JSValue, byteOffset: ?JSValue, lengthValue: ?JSValue) bun.JSError!jsc.JSValue { switch (FFIObject.getPtrSlice(globalThis, value, byteOffset, lengthValue)) { .err => |err| { return err; @@ -13,13 +13,13 @@ pub fn newCString(globalThis: *JSGlobalObject, value: JSValue, byteOffset: ?JSVa pub const dom_call = DOMCall("FFI", @This(), "ptr", DOMEffect.forRead(.TypedArrayProperties)); -pub fn toJS(globalObject: *JSC.JSGlobalObject) JSC.JSValue { - const object = JSC.JSValue.createEmptyObject(globalObject, comptime std.meta.fieldNames(@TypeOf(fields)).len + 2); +pub fn toJS(globalObject: *jsc.JSGlobalObject) jsc.JSValue { + const object = jsc.JSValue.createEmptyObject(globalObject, comptime std.meta.fieldNames(@TypeOf(fields)).len + 2); inline for (comptime std.meta.fieldNames(@TypeOf(fields))) |field| { object.put( globalObject, comptime ZigString.static(field), - JSC.createCallback(globalObject, comptime ZigString.static(field), 1, comptime @field(fields, field)), + jsc.createCallback(globalObject, comptime ZigString.static(field), 1, comptime @field(fields, field)), ); } @@ -45,8 +45,8 @@ pub const Reader = struct { .f64 = DOMCall("Reader", @This(), "f64", DOMEffect.forRead(.World)), }; - pub fn toJS(globalThis: *JSC.JSGlobalObject) JSC.JSValue { - const obj = JSC.JSValue.createEmptyObject(globalThis, std.meta.fieldNames(@TypeOf(Reader.dom_calls)).len); + pub fn toJS(globalThis: *jsc.JSGlobalObject) jsc.JSValue { + const obj = jsc.JSValue.createEmptyObject(globalThis, std.meta.fieldNames(@TypeOf(Reader.dom_calls)).len); inline for (comptime std.meta.fieldNames(@TypeOf(Reader.dom_calls))) |field| { @field(Reader.dom_calls, field).put(globalThis, obj); @@ -209,7 +209,7 @@ pub const Reader = struct { _: *anyopaque, raw_addr: i64, offset: i32, - ) callconv(JSC.conv) JSValue { + ) callconv(jsc.conv) JSValue { const addr = @as(usize, @intCast(raw_addr)) + @as(usize, @intCast(offset)); const value = @as(*align(1) u8, @ptrFromInt(addr)).*; return JSValue.jsNumber(value); @@ -219,7 +219,7 @@ pub const Reader = struct { _: *anyopaque, raw_addr: i64, offset: i32, - ) callconv(JSC.conv) JSValue { + ) callconv(jsc.conv) JSValue { const addr = @as(usize, @intCast(raw_addr)) + @as(usize, @intCast(offset)); const value = @as(*align(1) u16, @ptrFromInt(addr)).*; return JSValue.jsNumber(value); @@ -229,7 +229,7 @@ pub const Reader = struct { _: *anyopaque, raw_addr: i64, offset: i32, - ) callconv(JSC.conv) JSValue { + ) callconv(jsc.conv) JSValue { const addr = @as(usize, @intCast(raw_addr)) + @as(usize, @intCast(offset)); const value = @as(*align(1) u32, @ptrFromInt(addr)).*; return JSValue.jsNumber(value); @@ -239,7 +239,7 @@ pub const Reader = struct { _: *anyopaque, raw_addr: i64, offset: i32, - ) callconv(JSC.conv) JSValue { + ) callconv(jsc.conv) JSValue { const addr = @as(usize, @intCast(raw_addr)) + @as(usize, @intCast(offset)); const value = @as(*align(1) u64, @ptrFromInt(addr)).*; return JSValue.jsNumber(value); @@ -249,7 +249,7 @@ pub const Reader = struct { _: *anyopaque, raw_addr: i64, offset: i32, - ) callconv(JSC.conv) JSValue { + ) callconv(jsc.conv) JSValue { const addr = @as(usize, @intCast(raw_addr)) + @as(usize, @intCast(offset)); const value = @as(*align(1) i8, @ptrFromInt(addr)).*; return JSValue.jsNumber(value); @@ -259,7 +259,7 @@ pub const Reader = struct { _: *anyopaque, raw_addr: i64, offset: i32, - ) callconv(JSC.conv) JSValue { + ) callconv(jsc.conv) JSValue { const addr = @as(usize, @intCast(raw_addr)) + @as(usize, @intCast(offset)); const value = @as(*align(1) i16, @ptrFromInt(addr)).*; return JSValue.jsNumber(value); @@ -269,7 +269,7 @@ pub const Reader = struct { _: *anyopaque, raw_addr: i64, offset: i32, - ) callconv(JSC.conv) JSValue { + ) callconv(jsc.conv) JSValue { const addr = @as(usize, @intCast(raw_addr)) + @as(usize, @intCast(offset)); const value = @as(*align(1) i32, @ptrFromInt(addr)).*; return JSValue.jsNumber(value); @@ -279,7 +279,7 @@ pub const Reader = struct { _: *anyopaque, raw_addr: i64, offset: i32, - ) callconv(JSC.conv) JSValue { + ) callconv(jsc.conv) JSValue { const addr = @as(usize, @intCast(raw_addr)) + @as(usize, @intCast(offset)); const value = @as(*align(1) i64, @ptrFromInt(addr)).*; return JSValue.jsNumber(value); @@ -290,7 +290,7 @@ pub const Reader = struct { _: *anyopaque, raw_addr: i64, offset: i32, - ) callconv(JSC.conv) JSValue { + ) callconv(jsc.conv) JSValue { const addr = @as(usize, @intCast(raw_addr)) + @as(usize, @intCast(offset)); const value = @as(*align(1) f32, @ptrFromInt(addr)).*; return JSValue.jsNumber(value); @@ -301,7 +301,7 @@ pub const Reader = struct { _: *anyopaque, raw_addr: i64, offset: i32, - ) callconv(JSC.conv) JSValue { + ) callconv(jsc.conv) JSValue { const addr = @as(usize, @intCast(raw_addr)) + @as(usize, @intCast(offset)); const value = @as(*align(1) f64, @ptrFromInt(addr)).*; return JSValue.jsNumber(value); @@ -312,7 +312,7 @@ pub const Reader = struct { _: *anyopaque, raw_addr: i64, offset: i32, - ) callconv(JSC.conv) JSValue { + ) callconv(jsc.conv) JSValue { const addr = @as(usize, @intCast(raw_addr)) + @as(usize, @intCast(offset)); const value = @as(*align(1) u64, @ptrFromInt(addr)).*; return JSValue.fromUInt64NoTruncate(global, value); @@ -323,7 +323,7 @@ pub const Reader = struct { _: *anyopaque, raw_addr: i64, offset: i32, - ) callconv(JSC.conv) JSValue { + ) callconv(jsc.conv) JSValue { const addr = @as(usize, @intCast(raw_addr)) + @as(usize, @intCast(offset)); const value = @as(*align(1) i64, @ptrFromInt(addr)).*; return JSValue.fromInt64NoTruncate(global, value); @@ -345,8 +345,8 @@ pub fn ptr( pub fn ptrWithoutTypeChecks( _: *JSGlobalObject, _: *anyopaque, - array: *JSC.JSUint8Array, -) callconv(JSC.conv) JSValue { + array: *jsc.JSUint8Array, +) callconv(jsc.conv) JSValue { return JSValue.fromPtrAddress(@intFromPtr(array.ptr())); } @@ -356,7 +356,7 @@ fn ptr_( byteOffset: ?JSValue, ) JSValue { if (value == .zero) { - return JSC.JSValue.jsNull(); + return jsc.JSValue.jsNull(); } const array_buffer = value.asArrayBuffer(globalThis) orelse { @@ -403,10 +403,10 @@ fn ptr_( } if (comptime Environment.allow_assert) { - assert(JSC.JSValue.fromPtrAddress(addr).asPtrAddress() == addr); + assert(jsc.JSValue.fromPtrAddress(addr).asPtrAddress() == addr); } - return JSC.JSValue.fromPtrAddress(addr); + return jsc.JSValue.fromPtrAddress(addr); } const ValueOrError = union(enum) { @@ -506,17 +506,17 @@ pub fn toArrayBuffer( valueLength: ?JSValue, finalizationCtxOrPtr: ?JSValue, finalizationCallback: ?JSValue, -) bun.JSError!JSC.JSValue { +) bun.JSError!jsc.JSValue { switch (getPtrSlice(globalThis, value, byteOffset, valueLength)) { .err => |erro| { return erro; }, .slice => |slice| { - var callback: JSC.C.JSTypedArrayBytesDeallocator = null; + var callback: jsc.C.JSTypedArrayBytesDeallocator = null; var ctx: ?*anyopaque = null; if (finalizationCallback) |callback_value| { if (getCPtr(callback_value)) |callback_ptr| { - callback = @as(JSC.C.JSTypedArrayBytesDeallocator, @ptrFromInt(callback_ptr)); + callback = @as(jsc.C.JSTypedArrayBytesDeallocator, @ptrFromInt(callback_ptr)); if (finalizationCtxOrPtr) |ctx_value| { if (getCPtr(ctx_value)) |ctx_ptr| { @@ -530,13 +530,13 @@ pub fn toArrayBuffer( } } else if (finalizationCtxOrPtr) |callback_value| { if (getCPtr(callback_value)) |callback_ptr| { - callback = @as(JSC.C.JSTypedArrayBytesDeallocator, @ptrFromInt(callback_ptr)); + callback = @as(jsc.C.JSTypedArrayBytesDeallocator, @ptrFromInt(callback_ptr)); } else if (!callback_value.isEmptyOrUndefinedOrNull()) { return globalThis.toInvalidArguments("Expected callback to be a C pointer (number or BigInt)", .{}); } } - return JSC.ArrayBuffer.fromBytes(slice, JSC.JSValue.JSType.ArrayBuffer).toJSWithContext(globalThis, ctx, callback); + return jsc.ArrayBuffer.fromBytes(slice, jsc.JSValue.JSType.ArrayBuffer).toJSWithContext(globalThis, ctx, callback); }, } } @@ -548,17 +548,17 @@ pub fn toBuffer( valueLength: ?JSValue, finalizationCtxOrPtr: ?JSValue, finalizationCallback: ?JSValue, -) bun.JSError!JSC.JSValue { +) bun.JSError!jsc.JSValue { switch (getPtrSlice(globalThis, value, byteOffset, valueLength)) { .err => |err| { return err; }, .slice => |slice| { - var callback: JSC.C.JSTypedArrayBytesDeallocator = null; + var callback: jsc.C.JSTypedArrayBytesDeallocator = null; var ctx: ?*anyopaque = null; if (finalizationCallback) |callback_value| { if (getCPtr(callback_value)) |callback_ptr| { - callback = @as(JSC.C.JSTypedArrayBytesDeallocator, @ptrFromInt(callback_ptr)); + callback = @as(jsc.C.JSTypedArrayBytesDeallocator, @ptrFromInt(callback_ptr)); if (finalizationCtxOrPtr) |ctx_value| { if (getCPtr(ctx_value)) |ctx_ptr| { @@ -572,17 +572,17 @@ pub fn toBuffer( } } else if (finalizationCtxOrPtr) |callback_value| { if (getCPtr(callback_value)) |callback_ptr| { - callback = @as(JSC.C.JSTypedArrayBytesDeallocator, @ptrFromInt(callback_ptr)); + callback = @as(jsc.C.JSTypedArrayBytesDeallocator, @ptrFromInt(callback_ptr)); } else if (!callback_value.isEmptyOrUndefinedOrNull()) { return globalThis.toInvalidArguments("Expected callback to be a C pointer (number or BigInt)", .{}); } } if (callback != null or ctx != null) { - return JSC.JSValue.createBufferWithCtx(globalThis, slice, ctx, callback); + return jsc.JSValue.createBufferWithCtx(globalThis, slice, ctx, callback); } - return JSC.JSValue.createBuffer(globalThis, slice, null); + return jsc.JSValue.createBuffer(globalThis, slice, null); }, } } @@ -592,33 +592,33 @@ pub fn toCStringBuffer( value: JSValue, byteOffset: ?JSValue, valueLength: ?JSValue, -) JSC.JSValue { +) jsc.JSValue { switch (getPtrSlice(globalThis, value, byteOffset, valueLength)) { .err => |err| { return err; }, .slice => |slice| { - return JSC.JSValue.createBuffer(globalThis, slice, null); + return jsc.JSValue.createBuffer(globalThis, slice, null); }, } } pub fn getter( - globalObject: *JSC.JSGlobalObject, - _: *JSC.JSObject, -) JSC.JSValue { + globalObject: *jsc.JSGlobalObject, + _: *jsc.JSObject, +) jsc.JSValue { return FFIObject.toJS(globalObject); } const fields = .{ - .viewSource = JSC.host_fn.wrapStaticMethod(bun.api.FFI, "print", false), - .dlopen = JSC.host_fn.wrapStaticMethod(bun.api.FFI, "open", false), - .callback = JSC.host_fn.wrapStaticMethod(bun.api.FFI, "callback", false), - .linkSymbols = JSC.host_fn.wrapStaticMethod(bun.api.FFI, "linkSymbols", false), - .toBuffer = JSC.host_fn.wrapStaticMethod(@This(), "toBuffer", false), - .toArrayBuffer = JSC.host_fn.wrapStaticMethod(@This(), "toArrayBuffer", false), - .closeCallback = JSC.host_fn.wrapStaticMethod(bun.api.FFI, "closeCallback", false), - .CString = JSC.host_fn.wrapStaticMethod(bun.api.FFIObject, "newCString", false), + .viewSource = jsc.host_fn.wrapStaticMethod(bun.api.FFI, "print", false), + .dlopen = jsc.host_fn.wrapStaticMethod(bun.api.FFI, "open", false), + .callback = jsc.host_fn.wrapStaticMethod(bun.api.FFI, "callback", false), + .linkSymbols = jsc.host_fn.wrapStaticMethod(bun.api.FFI, "linkSymbols", false), + .toBuffer = jsc.host_fn.wrapStaticMethod(@This(), "toBuffer", false), + .toArrayBuffer = jsc.host_fn.wrapStaticMethod(@This(), "toArrayBuffer", false), + .closeCallback = jsc.host_fn.wrapStaticMethod(bun.api.FFI, "closeCallback", false), + .CString = jsc.host_fn.wrapStaticMethod(bun.api.FFIObject, "newCString", false), }; const max_addressable_memory = std.math.maxInt(u56); @@ -628,12 +628,12 @@ const bun = @import("bun"); const Environment = bun.Environment; const assert = bun.assert; -const JSC = bun.JSC; -const JSGlobalObject = JSC.JSGlobalObject; -const JSObject = JSC.JSObject; -const JSValue = JSC.JSValue; -const ZigString = JSC.ZigString; -const Bun = JSC.API.Bun; +const jsc = bun.jsc; +const JSGlobalObject = jsc.JSGlobalObject; +const JSObject = jsc.JSObject; +const JSValue = jsc.JSValue; +const ZigString = jsc.ZigString; +const Bun = jsc.API.Bun; -const DOMCall = JSC.host_fn.DOMCall; -const DOMEffect = JSC.host_fn.DOMEffect; +const DOMCall = jsc.host_fn.DOMCall; +const DOMEffect = jsc.host_fn.DOMEffect; diff --git a/src/bun.js/api/HashObject.zig b/src/bun.js/api/HashObject.zig index ae4bd07d38..a8cc484e05 100644 --- a/src/bun.js/api/HashObject.zig +++ b/src/bun.js/api/HashObject.zig @@ -31,8 +31,8 @@ pub const murmur32v3 = hashWrap(std.hash.murmur.Murmur3_32); pub const murmur64v2 = hashWrap(std.hash.murmur.Murmur2_64); pub const rapidhash = hashWrap(std.hash.RapidHash); -pub fn create(globalThis: *JSC.JSGlobalObject) JSC.JSValue { - const function = JSC.createCallback(globalThis, ZigString.static("hash"), 1, wyhash); +pub fn create(globalThis: *jsc.JSGlobalObject) jsc.JSValue { + const function = jsc.createCallback(globalThis, ZigString.static("hash"), 1, wyhash); const fns = comptime .{ "wyhash", "adler32", @@ -48,7 +48,7 @@ pub fn create(globalThis: *JSC.JSGlobalObject) JSC.JSValue { "rapidhash", }; inline for (fns) |name| { - const value = JSC.createCallback( + const value = jsc.createCallback( globalThis, ZigString.static(name), 1, @@ -60,19 +60,19 @@ pub fn create(globalThis: *JSC.JSGlobalObject) JSC.JSValue { return function; } -fn hashWrap(comptime Hasher_: anytype) JSC.JSHostFnZig { +fn hashWrap(comptime Hasher_: anytype) jsc.JSHostFnZig { return struct { const Hasher = Hasher_; - pub fn hash(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { + pub fn hash(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const arguments = callframe.arguments_old(2).slice(); - var args = JSC.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), arguments); + var args = jsc.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), arguments); defer args.deinit(); var input: []const u8 = ""; var input_slice = ZigString.Slice.empty; defer input_slice.deinit(); if (args.nextEat()) |arg| { - if (arg.as(JSC.WebCore.Blob)) |blob| { + if (arg.as(jsc.WebCore.Blob)) |blob| { // TODO: files input = blob.sharedView(); } else { @@ -110,7 +110,7 @@ fn hashWrap(comptime Hasher_: anytype) JSC.JSHostFnZig { const Function = if (@hasDecl(Hasher, "hashWithSeed")) Hasher.hashWithSeed else Hasher.hash; var function_args: std.meta.ArgsTuple(@TypeOf(Function)) = undefined; if (comptime std.meta.fields(std.meta.ArgsTuple(@TypeOf(Function))).len == 1) { - return JSC.JSValue.jsNumber(Function(input)); + return jsc.JSValue.jsNumber(Function(input)); } else { var seed: u64 = 0; if (args.nextEat()) |arg| { @@ -129,9 +129,9 @@ fn hashWrap(comptime Hasher_: anytype) JSC.JSHostFnZig { const value = @call(.auto, Function, function_args); if (@TypeOf(value) == u32) { - return JSC.JSValue.jsNumber(@as(u32, @bitCast(value))); + return jsc.JSValue.jsNumber(@as(u32, @bitCast(value))); } - return JSC.JSValue.fromUInt64NoTruncate(globalThis, value); + return jsc.JSValue.fromUInt64NoTruncate(globalThis, value); } } }.hash; @@ -140,7 +140,7 @@ fn hashWrap(comptime Hasher_: anytype) JSC.JSHostFnZig { const bun = @import("bun"); const std = @import("std"); -const JSC = bun.JSC; -const JSGlobalObject = JSC.JSGlobalObject; -const JSValue = JSC.JSValue; -const ZigString = JSC.ZigString; +const jsc = bun.jsc; +const JSGlobalObject = jsc.JSGlobalObject; +const JSValue = jsc.JSValue; +const ZigString = jsc.ZigString; diff --git a/src/bun.js/api/JSBundler.zig b/src/bun.js/api/JSBundler.zig index 3ffd9522f7..86d9366066 100644 --- a/src/bun.js/api/JSBundler.zig +++ b/src/bun.js/api/JSBundler.zig @@ -8,7 +8,7 @@ pub const JSBundler = struct { entry_points: bun.StringSet = bun.StringSet.init(bun.default_allocator), hot: bool = false, define: bun.StringMap = bun.StringMap.init(bun.default_allocator, false), - loaders: ?Api.LoaderMap = null, + loaders: ?api.LoaderMap = null, dir: OwnedString = OwnedString.initEmpty(bun.default_allocator), outdir: OwnedString = OwnedString.initEmpty(bun.default_allocator), rootdir: OwnedString = OwnedString.initEmpty(bun.default_allocator), @@ -34,13 +34,13 @@ pub const JSBundler = struct { drop: bun.StringSet = bun.StringSet.init(bun.default_allocator), has_any_on_before_parse: bool = false, throw_on_error: bool = true, - env_behavior: Api.DotEnvBehavior = .disable, + env_behavior: api.DotEnvBehavior = .disable, env_prefix: OwnedString = OwnedString.initEmpty(bun.default_allocator), tsconfig_override: OwnedString = OwnedString.initEmpty(bun.default_allocator), pub const List = bun.StringArrayHashMapUnmanaged(Config); - pub fn fromJS(globalThis: *JSC.JSGlobalObject, config: JSC.JSValue, plugins: *?*Plugin, allocator: std.mem.Allocator) JSError!Config { + pub fn fromJS(globalThis: *jsc.JSGlobalObject, config: jsc.JSValue, plugins: *?*Plugin, allocator: std.mem.Allocator) JSError!Config { var this = Config{ .entry_points = bun.StringSet.init(allocator), .external = bun.StringSet.init(allocator), @@ -91,8 +91,8 @@ pub const JSBundler = struct { plugins.* = Plugin.create( globalThis, switch (this.target) { - .bun, .bun_macro => JSC.JSGlobalObject.BunPluginTarget.bun, - .node => JSC.JSGlobalObject.BunPluginTarget.node, + .bun, .bun_macro => jsc.JSGlobalObject.BunPluginTarget.bun, + .node => jsc.JSGlobalObject.BunPluginTarget.node, else => .browser, }, ); @@ -383,7 +383,7 @@ pub const JSBundler = struct { } if (try config.getOwnObject(globalThis, "define")) |define| { - var define_iter = try JSC.JSPropertyIterator(.{ + var define_iter = try jsc.JSPropertyIterator(.{ .skip_empty_name = true, .include_value = true, }).init(globalThis, define); @@ -397,10 +397,10 @@ pub const JSBundler = struct { return globalThis.throwInvalidArguments("define \"{s}\" must be a JSON string", .{prop}); } - var val = JSC.ZigString.init(""); + var val = jsc.ZigString.init(""); try property_value.toZigString(&val, globalThis); if (val.len == 0) { - val = JSC.ZigString.fromUTF8("\"\""); + val = jsc.ZigString.fromUTF8("\"\""); } const key = try prop.toOwnedSlice(bun.default_allocator); @@ -415,7 +415,7 @@ pub const JSBundler = struct { } if (try config.getOwnObject(globalThis, "loader")) |loaders| { - var loader_iter = try JSC.JSPropertyIterator(.{ + var loader_iter = try jsc.JSPropertyIterator(.{ .skip_empty_name = true, .include_value = true, }).init(globalThis, loaders); @@ -423,7 +423,7 @@ pub const JSBundler = struct { var loader_names = try allocator.alloc(string, loader_iter.len); errdefer allocator.free(loader_names); - var loader_values = try allocator.alloc(Api.Loader, loader_iter.len); + var loader_values = try allocator.alloc(api.Loader, loader_iter.len); errdefer allocator.free(loader_values); while (try loader_iter.next()) |prop| { @@ -434,13 +434,13 @@ pub const JSBundler = struct { loader_values[loader_iter.i] = try loader_iter.value.toEnumFromMap( globalThis, "loader", - Api.Loader, + api.Loader, options.Loader.api_names, ); loader_names[loader_iter.i] = try prop.toOwnedSlice(bun.default_allocator); } - this.loaders = Api.LoaderMap{ + this.loaders = api.LoaderMap{ .extensions = loader_names, .loaders = loader_values, }; @@ -513,9 +513,9 @@ pub const JSBundler = struct { }; fn build( - globalThis: *JSC.JSGlobalObject, - arguments: []const JSC.JSValue, - ) bun.JSError!JSC.JSValue { + globalThis: *jsc.JSGlobalObject, + arguments: []const jsc.JSValue, + ) bun.JSError!jsc.JSValue { if (arguments.len == 0 or !arguments[0].isObject()) { return globalThis.throwInvalidArguments("Expected a config object to be passed to Bun.build", .{}); } @@ -534,9 +534,9 @@ pub const JSBundler = struct { /// `Bun.build(config)` pub fn buildFn( - globalThis: *JSC.JSGlobalObject, - callframe: *JSC.CallFrame, - ) bun.JSError!JSC.JSValue { + globalThis: *jsc.JSGlobalObject, + callframe: *jsc.CallFrame, + ) bun.JSError!jsc.JSValue { const arguments = callframe.arguments_old(1); return build(globalThis, arguments.slice()); } @@ -546,8 +546,8 @@ pub const JSBundler = struct { import_record: MiniImportRecord, value: Value, - js_task: JSC.AnyTask, - task: JSC.AnyEventLoop.Task, + js_task: jsc.AnyTask, + task: jsc.AnyEventLoop.Task, pub const MiniImportRecord = struct { kind: bun.ImportKind, @@ -616,11 +616,11 @@ pub const JSBundler = struct { bun.default_allocator.destroy(this); } - const AnyTask = JSC.AnyTask.New(@This(), runOnJSThread); + const AnyTask = jsc.AnyTask.New(@This(), runOnJSThread); pub fn dispatch(this: *Resolve) void { this.js_task = AnyTask.init(this); - this.bv2.jsLoopForPlugins().enqueueTaskConcurrent(JSC.ConcurrentTask.create(this.js_task.task())); + this.bv2.jsLoopForPlugins().enqueueTaskConcurrent(jsc.ConcurrentTask.create(this.js_task.task())); } pub fn runOnJSThread(this: *Resolve) void { @@ -674,8 +674,8 @@ pub const JSBundler = struct { namespace: []const u8, value: Value, - js_task: JSC.AnyTask, - task: JSC.AnyEventLoop.Task, + js_task: jsc.AnyTask, + task: jsc.AnyEventLoop.Task, parse_task: *bun.ParseTask, /// Faster path: skip the extra threadpool dispatch when the file is not found was_file: bool, @@ -743,7 +743,7 @@ pub const JSBundler = struct { this.value.deinit(); } - const AnyTask = JSC.AnyTask.New(@This(), runOnJSThread); + const AnyTask = jsc.AnyTask.New(@This(), runOnJSThread); pub fn runOnJSThread(load: *Load) void { load.bv2.plugins.?.matchOnLoad( @@ -757,14 +757,14 @@ pub const JSBundler = struct { pub fn dispatch(this: *Load) void { this.js_task = AnyTask.init(this); - const concurrent_task = JSC.ConcurrentTask.createFrom(&this.js_task); + const concurrent_task = jsc.ConcurrentTask.createFrom(&this.js_task); this.bv2.jsLoopForPlugins().enqueueTaskConcurrent(concurrent_task); } - export fn JSBundlerPlugin__onDefer(load: *Load, global: *JSC.JSGlobalObject) JSValue { - return JSC.toJSHostCall(global, @src(), Load.onDefer, .{ load, global }); + export fn JSBundlerPlugin__onDefer(load: *Load, global: *jsc.JSGlobalObject) JSValue { + return jsc.toJSHostCall(global, @src(), Load.onDefer, .{ load, global }); } - fn onDefer(this: *Load, globalObject: *JSC.JSGlobalObject) bun.JSError!JSValue { + fn onDefer(this: *Load, globalObject: *jsc.JSGlobalObject) bun.JSError!JSValue { if (this.called_defer) { return globalObject.throw("Can't call .defer() more than once within an onLoad plugin", .{}); } @@ -776,7 +776,7 @@ pub const JSBundler = struct { // the pending item counter and increment the deferred counter. switch (this.parse_task.ctx.loop().*) { .js => |jsc_event_loop| { - jsc_event_loop.enqueueTaskConcurrent(JSC.ConcurrentTask.fromCallback(this.parse_task.ctx, BundleV2.onNotifyDefer)); + jsc_event_loop.enqueueTaskConcurrent(jsc.ConcurrentTask.fromCallback(this.parse_task.ctx, BundleV2.onNotifyDefer)); }, .mini => |*mini| { mini.enqueueTaskConcurrentWithExtraCtx( @@ -798,7 +798,7 @@ pub const JSBundler = struct { source_code_value: JSValue, loader_as_int: JSValue, ) void { - JSC.markBinding(@src()); + jsc.markBinding(@src()); if (source_code_value.isEmptyOrUndefinedOrNull() or loader_as_int.isEmptyOrUndefinedOrNull()) { this.value = .{ .no_match = {} }; @@ -809,9 +809,9 @@ pub const JSBundler = struct { return; } } else { - const loader: Api.Loader = @enumFromInt(loader_as_int.to(u8)); + const loader: api.Loader = @enumFromInt(loader_as_int.to(u8)); const global = this.bv2.plugins.?.globalObject(); - const source_code = JSC.Node.StringOrBuffer.fromJSToOwnedSlice(global, source_code_value, bun.default_allocator) catch |err| { + const source_code = jsc.Node.StringOrBuffer.fromJSToOwnedSlice(global, source_code_value, bun.default_allocator) catch |err| { switch (err) { error.OutOfMemory => { bun.outOfMemory(); @@ -838,11 +838,11 @@ pub const JSBundler = struct { }; pub const Plugin = opaque { - extern fn JSBundlerPlugin__create(*JSC.JSGlobalObject, JSC.JSGlobalObject.BunPluginTarget) *Plugin; - pub fn create(global: *JSC.JSGlobalObject, target: JSC.JSGlobalObject.BunPluginTarget) *Plugin { - JSC.markBinding(@src()); + extern fn JSBundlerPlugin__create(*jsc.JSGlobalObject, jsc.JSGlobalObject.BunPluginTarget) *Plugin; + pub fn create(global: *jsc.JSGlobalObject, target: jsc.JSGlobalObject.BunPluginTarget) *Plugin { + jsc.markBinding(@src()); const plugin = JSBundlerPlugin__create(global, target); - JSC.JSValue.fromCell(plugin).protect(); + jsc.JSValue.fromCell(plugin).protect(); return plugin; } @@ -867,12 +867,12 @@ pub const JSBundler = struct { extern fn JSBundlerPlugin__tombstone(*Plugin) void; pub fn deinit(this: *Plugin) void { - JSC.markBinding(@src()); + jsc.markBinding(@src()); JSBundlerPlugin__tombstone(this); - JSC.JSValue.fromCell(this).unprotect(); + jsc.JSValue.fromCell(this).unprotect(); } - extern fn JSBundlerPlugin__globalObject(*Plugin) *JSC.JSGlobalObject; + extern fn JSBundlerPlugin__globalObject(*Plugin) *jsc.JSGlobalObject; pub const globalObject = JSBundlerPlugin__globalObject; extern fn JSBundlerPlugin__anyMatches( @@ -909,7 +909,7 @@ pub const JSBundler = struct { path: *const Fs.Path, is_onLoad: bool, ) bool { - JSC.markBinding(@src()); + jsc.markBinding(@src()); const tracer = bun.perf.trace("JSBundler.hasAnyMatches"); defer tracer.end(); @@ -931,7 +931,7 @@ pub const JSBundler = struct { default_loader: options.Loader, is_server_side: bool, ) void { - JSC.markBinding(@src()); + jsc.markBinding(@src()); const tracer = bun.perf.trace("JSBundler.matchOnLoad"); defer tracer.end(); debug("JSBundler.matchOnLoad(0x{x}, {s}, {s})", .{ @intFromPtr(this), namespace, path }); @@ -953,7 +953,7 @@ pub const JSBundler = struct { context: *anyopaque, import_record_kind: bun.ImportKind, ) void { - JSC.markBinding(@src()); + jsc.markBinding(@src()); const tracer = bun.perf.trace("JSBundler.matchOnResolve"); defer tracer.end(); const namespace_string = if (strings.eqlComptime(namespace, "file")) @@ -970,13 +970,13 @@ pub const JSBundler = struct { pub fn addPlugin( this: *Plugin, - object: JSC.JSValue, - config: JSC.JSValue, - onstart_promises_array: JSC.JSValue, + object: jsc.JSValue, + config: jsc.JSValue, + onstart_promises_array: jsc.JSValue, is_last: bool, is_bake: bool, ) !JSValue { - JSC.markBinding(@src()); + jsc.markBinding(@src()); const tracer = bun.perf.trace("JSBundler.addPlugin"); defer tracer.end(); return bun.jsc.fromJSHostCall(globalObject(this), @src(), JSBundlerPlugin__runSetupFunction, .{ @@ -994,7 +994,7 @@ pub const JSBundler = struct { } pub fn setConfig(this: *Plugin, config: *anyopaque) void { - JSC.markBinding(@src()); + jsc.markBinding(@src()); JSBundlerPlugin__setConfig(this, config); } @@ -1002,11 +1002,11 @@ pub const JSBundler = struct { extern fn JSBundlerPlugin__runSetupFunction( *Plugin, - JSC.JSValue, - JSC.JSValue, - JSC.JSValue, - JSC.JSValue, - JSC.JSValue, + jsc.JSValue, + jsc.JSValue, + jsc.JSValue, + jsc.JSValue, + jsc.JSValue, ) JSValue; pub export fn JSBundlerPlugin__addError( @@ -1047,17 +1047,17 @@ pub const JSBundler = struct { }; pub const BuildArtifact = struct { - pub const js = JSC.Codegen.JSBuildArtifact; + pub const js = jsc.Codegen.JSBuildArtifact; pub const toJS = js.toJS; pub const fromJS = js.fromJS; pub const fromJSDirect = js.fromJSDirect; - blob: JSC.WebCore.Blob, + blob: jsc.WebCore.Blob, loader: options.Loader = .file, path: []const u8 = "", hash: u64 = std.math.maxInt(u64), output_kind: OutputKind, - sourcemap: JSC.Strong.Optional = .empty, + sourcemap: jsc.Strong.Optional = .empty, pub const OutputKind = enum { chunk, @@ -1080,44 +1080,44 @@ pub const BuildArtifact = struct { pub fn getText( this: *BuildArtifact, - globalThis: *JSC.JSGlobalObject, - callframe: *JSC.CallFrame, - ) bun.JSError!JSC.JSValue { + globalThis: *jsc.JSGlobalObject, + callframe: *jsc.CallFrame, + ) bun.JSError!jsc.JSValue { return @call(bun.callmod_inline, Blob.getText, .{ &this.blob, globalThis, callframe }); } pub fn getJSON( this: *BuildArtifact, - globalThis: *JSC.JSGlobalObject, - callframe: *JSC.CallFrame, - ) bun.JSError!JSC.JSValue { + globalThis: *jsc.JSGlobalObject, + callframe: *jsc.CallFrame, + ) bun.JSError!jsc.JSValue { return @call(bun.callmod_inline, Blob.getJSON, .{ &this.blob, globalThis, callframe }); } pub fn getArrayBuffer( this: *BuildArtifact, - globalThis: *JSC.JSGlobalObject, - callframe: *JSC.CallFrame, + globalThis: *jsc.JSGlobalObject, + callframe: *jsc.CallFrame, ) bun.JSError!JSValue { return @call(bun.callmod_inline, Blob.getArrayBuffer, .{ &this.blob, globalThis, callframe }); } pub fn getSlice( this: *BuildArtifact, - globalThis: *JSC.JSGlobalObject, - callframe: *JSC.CallFrame, - ) bun.JSError!JSC.JSValue { + globalThis: *jsc.JSGlobalObject, + callframe: *jsc.CallFrame, + ) bun.JSError!jsc.JSValue { return @call(bun.callmod_inline, Blob.getSlice, .{ &this.blob, globalThis, callframe }); } pub fn getType( this: *BuildArtifact, - globalThis: *JSC.JSGlobalObject, + globalThis: *jsc.JSGlobalObject, ) JSValue { return @call(bun.callmod_inline, Blob.getType, .{ &this.blob, globalThis }); } pub fn getStream( this: *BuildArtifact, - globalThis: *JSC.JSGlobalObject, - callframe: *JSC.CallFrame, + globalThis: *jsc.JSGlobalObject, + callframe: *jsc.CallFrame, ) bun.JSError!JSValue { return @call(bun.callmod_inline, Blob.getStream, .{ &this.blob, @@ -1128,45 +1128,45 @@ pub const BuildArtifact = struct { pub fn getPath( this: *BuildArtifact, - globalThis: *JSC.JSGlobalObject, + globalThis: *jsc.JSGlobalObject, ) JSValue { return ZigString.fromUTF8(this.path).toJS(globalThis); } pub fn getLoader( this: *BuildArtifact, - globalThis: *JSC.JSGlobalObject, + globalThis: *jsc.JSGlobalObject, ) JSValue { return ZigString.fromUTF8(@tagName(this.loader)).toJS(globalThis); } pub fn getHash( this: *BuildArtifact, - globalThis: *JSC.JSGlobalObject, + globalThis: *jsc.JSGlobalObject, ) JSValue { var buf: [512]u8 = undefined; const out = std.fmt.bufPrint(&buf, "{any}", .{bun.fmt.truncatedHash32(this.hash)}) catch @panic("Unexpected"); return ZigString.init(out).toJS(globalThis); } - pub fn getSize(this: *BuildArtifact, globalObject: *JSC.JSGlobalObject) JSValue { + pub fn getSize(this: *BuildArtifact, globalObject: *jsc.JSGlobalObject) JSValue { return @call(bun.callmod_inline, Blob.getSize, .{ &this.blob, globalObject }); } - pub fn getMimeType(this: *BuildArtifact, globalObject: *JSC.JSGlobalObject) JSValue { + pub fn getMimeType(this: *BuildArtifact, globalObject: *jsc.JSGlobalObject) JSValue { return @call(bun.callmod_inline, Blob.getType, .{ &this.blob, globalObject }); } - pub fn getOutputKind(this: *BuildArtifact, globalObject: *JSC.JSGlobalObject) JSValue { + pub fn getOutputKind(this: *BuildArtifact, globalObject: *jsc.JSGlobalObject) JSValue { return ZigString.init(@tagName(this.output_kind)).toJS(globalObject); } - pub fn getSourceMap(this: *BuildArtifact, _: *JSC.JSGlobalObject) JSValue { + pub fn getSourceMap(this: *BuildArtifact, _: *jsc.JSGlobalObject) JSValue { if (this.sourcemap.get()) |value| { return value; } - return JSC.JSValue.jsNull(); + return jsc.JSValue.jsNull(); } pub fn finalize(this: *BuildArtifact) callconv(.C) void { @@ -1279,11 +1279,11 @@ pub const BuildArtifact = struct { } }; +const string = []const u8; + const Fs = @import("../../fs.zig"); const resolve_path = @import("../../resolver/resolve_path.zig"); const std = @import("std"); -const Api = @import("../../api/schema.zig").Api; -const Index = @import("../../ast/base.zig").Index; const options = @import("../../options.zig"); const Loader = options.Loader; @@ -1296,12 +1296,13 @@ const String = bun.String; const Transpiler = bun.transpiler; const WebCore = bun.webcore; const logger = bun.logger; -const string = bun.string; const strings = bun.strings; const BundleV2 = bun.bundle_v2.BundleV2; +const Index = bun.ast.Index; +const api = bun.schema.api; -const JSC = bun.JSC; -const JSGlobalObject = JSC.JSGlobalObject; -const JSValue = bun.JSC.JSValue; -const ZigString = JSC.ZigString; -const Blob = JSC.WebCore.Blob; +const jsc = bun.jsc; +const JSGlobalObject = jsc.JSGlobalObject; +const JSValue = bun.jsc.JSValue; +const ZigString = jsc.ZigString; +const Blob = jsc.WebCore.Blob; diff --git a/src/bun.js/api/JSTranspiler.zig b/src/bun.js/api/JSTranspiler.zig index c9215d762d..93151d186a 100644 --- a/src/bun.js/api/JSTranspiler.zig +++ b/src/bun.js/api/JSTranspiler.zig @@ -1,6 +1,6 @@ const JSTranspiler = @This(); -pub const js = JSC.Codegen.JSTranspiler; +pub const js = jsc.Codegen.JSTranspiler; pub const toJS = js.toJS; pub const fromJS = js.fromJS; pub const fromJSDirect = js.fromJSDirect; @@ -12,15 +12,15 @@ scan_pass_result: ScanPassResult, buffer_writer: ?JSPrinter.BufferWriter = null, log_level: logger.Log.Level = .err, -const default_transform_options: Api.TransformOptions = brk: { - var opts = std.mem.zeroes(Api.TransformOptions); +const default_transform_options: api.TransformOptions = brk: { + var opts = std.mem.zeroes(api.TransformOptions); opts.disable_hmr = true; - opts.target = Api.Target.browser; + opts.target = api.Target.browser; break :brk opts; }; const TranspilerOptions = struct { - transform: Api.TransformOptions = default_transform_options, + transform: api.TransformOptions = default_transform_options, default_loader: options.Loader = options.Loader.jsx, macro_map: MacroMap = MacroMap{}, tsconfig: ?*TSConfigJSON = null, @@ -45,7 +45,7 @@ const TranspilerOptions = struct { // This is going to be hard to not leak pub const TransformTask = struct { - input_code: JSC.Node.StringOrBuffer = JSC.Node.StringOrBuffer{ .buffer = .{} }, + input_code: jsc.Node.StringOrBuffer = jsc.Node.StringOrBuffer{ .buffer = .{} }, output_code: bun.String = bun.String.empty, transpiler: Transpiler.Transpiler = undefined, log: logger.Log, @@ -58,10 +58,10 @@ pub const TransformTask = struct { pub const new = bun.TrivialNew(@This()); - pub const AsyncTransformTask = JSC.ConcurrentPromiseTask(TransformTask); + pub const AsyncTransformTask = jsc.ConcurrentPromiseTask(TransformTask); pub const AsyncTransformEventLoopTask = AsyncTransformTask.EventLoopTask; - pub fn create(transpiler: *JSTranspiler, input_code: bun.JSC.Node.StringOrBuffer, globalThis: *JSGlobalObject, loader: Loader) !*AsyncTransformTask { + pub fn create(transpiler: *JSTranspiler, input_code: bun.jsc.Node.StringOrBuffer, globalThis: *JSGlobalObject, loader: Loader) !*AsyncTransformTask { var transform_task = TransformTask.new(.{ .input_code = input_code, .transpiler = undefined, @@ -85,7 +85,7 @@ pub const TransformTask = struct { const name = this.loader.stdinName(); const source = logger.Source.initPathString(name, this.input_code.slice()); - var arena = Mimalloc.Arena.init() catch unreachable; + var arena = MimallocArena.init() catch unreachable; defer arena.deinit(); const allocator = arena.allocator(); @@ -148,7 +148,7 @@ pub const TransformTask = struct { } } - pub fn then(this: *TransformTask, promise: *JSC.JSPromise) void { + pub fn then(this: *TransformTask, promise: *jsc.JSPromise) void { if (this.log.hasAny() or this.err != null) { const error_value: bun.OOM!JSValue = brk: { if (this.err) |err| { @@ -178,7 +178,7 @@ pub const TransformTask = struct { finish(code, global, promise); } - noinline fn finish(code: bun.String, global: *JSGlobalObject, promise: *JSC.JSPromise) void { + noinline fn finish(code: bun.String, global: *JSGlobalObject, promise: *jsc.JSPromise) void { promise.resolve(global, code.toJS(global)); code.deref(); } @@ -250,7 +250,7 @@ fn exportReplacementValue(value: JSValue, globalThis: *JSGlobalObject) bun.JSErr return null; } -fn transformOptionsFromJSC(globalObject: *JSC.JSGlobalObject, temp_allocator: std.mem.Allocator, args: *JSC.CallFrame.ArgumentsSlice) (bun.JSError || bun.OOM)!TranspilerOptions { +fn transformOptionsFromJSC(globalObject: *jsc.JSGlobalObject, temp_allocator: std.mem.Allocator, args: *jsc.CallFrame.ArgumentsSlice) (bun.JSError || bun.OOM)!TranspilerOptions { const globalThis = globalObject; const object = args.next() orelse return TranspilerOptions{ .log = logger.Log.init(temp_allocator) }; if (object.isUndefinedOrNull()) return TranspilerOptions{ .log = logger.Log.init(temp_allocator) }; @@ -278,7 +278,7 @@ fn transformOptionsFromJSC(globalObject: *JSC.JSGlobalObject, temp_allocator: st return globalObject.throwInvalidArguments("define must be an object", .{}); }; - var define_iter = try JSC.JSPropertyIterator(.{ + var define_iter = try jsc.JSPropertyIterator(.{ .skip_empty_name = true, .include_value = true, @@ -300,15 +300,15 @@ fn transformOptionsFromJSC(globalObject: *JSC.JSGlobalObject, temp_allocator: st } names[define_iter.i] = prop.toOwnedSlice(allocator) catch unreachable; - var val = JSC.ZigString.init(""); + var val = jsc.ZigString.init(""); try property_value.toZigString(&val, globalThis); if (val.len == 0) { - val = JSC.ZigString.init("\"\""); + val = jsc.ZigString.init("\"\""); } values[define_iter.i] = std.fmt.allocPrint(allocator, "{}", .{val}) catch unreachable; } - transpiler.transform.define = Api.StringMap{ + transpiler.transform.define = api.StringMap{ .keys = names, .values = values, }; @@ -321,7 +321,7 @@ fn transformOptionsFromJSC(globalObject: *JSC.JSGlobalObject, temp_allocator: st const toplevel_type = external.jsType(); if (toplevel_type.isStringLike()) { - var zig_str = JSC.ZigString.init(""); + var zig_str = jsc.ZigString.init(""); try external.toZigString(&zig_str, globalThis); if (zig_str.len == 0) break :external; var single_external = allocator.alloc(string, 1) catch unreachable; @@ -339,7 +339,7 @@ fn transformOptionsFromJSC(globalObject: *JSC.JSGlobalObject, temp_allocator: st return globalObject.throwInvalidArguments("external must be a string or string[]", .{}); } - var zig_str = JSC.ZigString.init(""); + var zig_str = jsc.ZigString.init(""); try entry.toZigString(&zig_str, globalThis); if (zig_str.len == 0) continue; externals[i] = std.fmt.allocPrint(allocator, "{}", .{external}) catch unreachable; @@ -394,7 +394,7 @@ fn transformOptionsFromJSC(globalObject: *JSC.JSGlobalObject, temp_allocator: st allocator, &transpiler.log, &logger.Source.initPathString("tsconfig.json", transpiler.tsconfig_buf), - &JSC.VirtualMachine.get().transpiler.resolver.caches.json, + &jsc.VirtualMachine.get().transpiler.resolver.caches.json, ) catch null) |parsed_tsconfig| { transpiler.tsconfig = parsed_tsconfig; } @@ -428,7 +428,7 @@ fn transformOptionsFromJSC(globalObject: *JSC.JSGlobalObject, temp_allocator: st if (out.isEmpty()) break :macros; transpiler.macros_buf = out.toOwnedSlice(allocator) catch bun.outOfMemory(); const source = &logger.Source.initPathString("macros.json", transpiler.macros_buf); - const json = (JSC.VirtualMachine.get().transpiler.resolver.caches.json.parseJSON( + const json = (jsc.VirtualMachine.get().transpiler.resolver.caches.json.parseJSON( &transpiler.log, source, allocator, @@ -524,7 +524,7 @@ fn transformOptionsFromJSC(globalObject: *JSC.JSGlobalObject, temp_allocator: st var total_name_buf_len: u32 = 0; var string_count: u32 = 0; - const iter = try JSC.JSArrayIterator.init(eliminate, globalThis); + const iter = try jsc.JSArrayIterator.init(eliminate, globalThis); { var length_iter = iter; while (try length_iter.next()) |value| { @@ -562,7 +562,7 @@ fn transformOptionsFromJSC(globalObject: *JSC.JSGlobalObject, temp_allocator: st return globalObject.throwInvalidArguments("replace must be an object", .{}); }; - var iter = try JSC.JSPropertyIterator(.{ + var iter = try jsc.JSPropertyIterator(.{ .skip_empty_name = true, .include_value = true, }).init(globalThis, replace_obj); @@ -643,10 +643,10 @@ fn transformOptionsFromJSC(globalObject: *JSC.JSGlobalObject, temp_allocator: st return transpiler; } -pub fn constructor(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!*JSTranspiler { +pub fn constructor(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!*JSTranspiler { var temp = bun.ArenaAllocator.init(bun.default_allocator); const arguments = callframe.arguments_old(3); - var args = JSC.CallFrame.ArgumentsSlice.init( + var args = jsc.CallFrame.ArgumentsSlice.init( globalThis.bunVM(), arguments.slice(), ); @@ -673,7 +673,7 @@ pub fn constructor(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) b allocator, log, transpiler_options.transform, - JSC.VirtualMachine.get().transpiler.env, + jsc.VirtualMachine.get().transpiler.env, ) catch |err| { if ((log.warnings + log.errors) > 0) { return globalThis.throwValue(try log.toJS(globalThis, allocator, "Failed to create transpiler")); @@ -738,7 +738,7 @@ pub fn finalize(this: *JSTranspiler) void { // bun.default_allocator.free(this.transpiler_options.tsconfig_buf); // bun.default_allocator.free(this.transpiler_options.macros_buf); this.arena.deinit(); - JSC.VirtualMachine.get().allocator.destroy(this); + jsc.VirtualMachine.get().allocator.destroy(this); } fn getParseResult(this: *JSTranspiler, allocator: std.mem.Allocator, code: []const u8, loader: ?Loader, macro_js_ctx: Transpiler.MacroJSValueType) ?Transpiler.ParseResult { @@ -767,16 +767,16 @@ fn getParseResult(this: *JSTranspiler, allocator: std.mem.Allocator, code: []con return this.transpiler.parse(parse_options, null); } -pub fn scan(this: *JSTranspiler, globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { - JSC.markBinding(@src()); +pub fn scan(this: *JSTranspiler, globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { + jsc.markBinding(@src()); const arguments = callframe.arguments_old(3); - var args = JSC.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), arguments.slice()); + var args = jsc.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), arguments.slice()); defer args.deinit(); const code_arg = args.next() orelse { return globalThis.throwInvalidArgumentType("scan", "code", "string or Uint8Array"); }; - const code_holder = try JSC.Node.StringOrBuffer.fromJS(globalThis, args.arena.allocator(), code_arg) orelse { + const code_holder = try jsc.Node.StringOrBuffer.fromJS(globalThis, args.arena.allocator(), code_arg) orelse { return globalThis.throwInvalidArgumentType("scan", "code", "string or Uint8Array"); }; defer code_holder.deinit(); @@ -796,7 +796,7 @@ pub fn scan(this: *JSTranspiler, globalThis: *JSC.JSGlobalObject, callframe: *JS return .zero; } - var arena = Mimalloc.Arena.init() catch unreachable; + var arena = MimallocArena.init() catch unreachable; const prev_allocator = this.transpiler.allocator; const allocator = arena.allocator(); this.transpiler.setAllocator(allocator); @@ -824,8 +824,8 @@ pub fn scan(this: *JSTranspiler, globalThis: *JSC.JSGlobalObject, callframe: *JS return globalThis.throwValue(try this.transpiler.log.toJS(globalThis, globalThis.allocator(), "Parse error")); } - const exports_label = JSC.ZigString.static("exports"); - const imports_label = JSC.ZigString.static("imports"); + const exports_label = jsc.ZigString.static("exports"); + const imports_label = jsc.ZigString.static("imports"); const named_imports_value = try namedImportsToJS( globalThis, parse_result.ast.import_records.slice(), @@ -835,20 +835,20 @@ pub fn scan(this: *JSTranspiler, globalThis: *JSC.JSGlobalObject, callframe: *JS globalThis, &parse_result.ast.named_exports, ); - return JSC.JSValue.createObject2(globalThis, imports_label, exports_label, named_imports_value, named_exports_value); + return jsc.JSValue.createObject2(globalThis, imports_label, exports_label, named_imports_value, named_exports_value); } -pub fn transform(this: *JSTranspiler, globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { - JSC.markBinding(@src()); +pub fn transform(this: *JSTranspiler, globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { + jsc.markBinding(@src()); const arguments = callframe.arguments_old(3); - var args = JSC.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), arguments.slice()); + var args = jsc.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), arguments.slice()); defer args.arena.deinit(); const code_arg = args.next() orelse { return globalThis.throwInvalidArgumentType("transform", "code", "string or Uint8Array"); }; const allow_string_object = true; - var code = try JSC.Node.StringOrBuffer.fromJSWithEncodingMaybeAsync(globalThis, bun.default_allocator, code_arg, .utf8, true, allow_string_object) orelse { + var code = try jsc.Node.StringOrBuffer.fromJSWithEncodingMaybeAsync(globalThis, bun.default_allocator, code_arg, .utf8, true, allow_string_object) orelse { return globalThis.throwInvalidArgumentType("transform", "code", "string or Uint8Array"); }; errdefer code.deinit(); @@ -884,21 +884,21 @@ pub fn transform(this: *JSTranspiler, globalThis: *JSC.JSGlobalObject, callframe pub fn transformSync( this: *JSTranspiler, - globalThis: *JSC.JSGlobalObject, - callframe: *JSC.CallFrame, -) bun.JSError!JSC.JSValue { - JSC.markBinding(@src()); + globalThis: *jsc.JSGlobalObject, + callframe: *jsc.CallFrame, +) bun.JSError!jsc.JSValue { + jsc.markBinding(@src()); const arguments = callframe.arguments_old(3); - var args = JSC.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), arguments.slice()); + var args = jsc.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), arguments.slice()); defer args.arena.deinit(); const code_arg = args.next() orelse { return globalThis.throwInvalidArgumentType("transformSync", "code", "string or Uint8Array"); }; - var arena = Mimalloc.Arena.init() catch unreachable; + var arena = MimallocArena.init() catch unreachable; defer arena.deinit(); - const code_holder = try JSC.Node.StringOrBuffer.fromJS(globalThis, arena.allocator(), code_arg) orelse { + const code_holder = try jsc.Node.StringOrBuffer.fromJS(globalThis, arena.allocator(), code_arg) orelse { return globalThis.throwInvalidArgumentType("transformSync", "code", "string or Uint8Array"); }; defer code_holder.deinit(); @@ -907,7 +907,7 @@ pub fn transformSync( defer arguments.ptr[0].ensureStillAlive(); args.eat(); - var js_ctx_value: JSC.JSValue = JSC.JSValue.zero; + var js_ctx_value: jsc.JSValue = jsc.JSValue.zero; const loader: ?Loader = brk: { if (args.next()) |arg| { args.eat(); @@ -995,13 +995,13 @@ pub fn transformSync( // TODO: benchmark if pooling this way is faster or moving is faster buffer_writer = printer.ctx; - var out = JSC.ZigString.init(buffer_writer.written); + var out = jsc.ZigString.init(buffer_writer.written); out.setOutputEncoding(); return out.toJS(globalThis); } -fn namedExportsToJS(global: *JSGlobalObject, named_exports: *JSAst.Ast.NamedExports) bun.JSError!JSC.JSValue { +fn namedExportsToJS(global: *JSGlobalObject, named_exports: *JSAst.Ast.NamedExports) bun.JSError!jsc.JSValue { if (named_exports.count() == 0) return JSValue.createEmptyArray(global, 0); @@ -1024,35 +1024,35 @@ fn namedExportsToJS(global: *JSGlobalObject, named_exports: *JSAst.Ast.NamedExpo return bun.String.toJSArray(global, names); } -fn namedImportsToJS(global: *JSGlobalObject, import_records: []const ImportRecord) bun.JSError!JSC.JSValue { - const path_label = JSC.ZigString.static("path"); - const kind_label = JSC.ZigString.static("kind"); +fn namedImportsToJS(global: *JSGlobalObject, import_records: []const ImportRecord) bun.JSError!jsc.JSValue { + const path_label = jsc.ZigString.static("path"); + const kind_label = jsc.ZigString.static("kind"); - const array = try JSC.JSValue.createEmptyArray(global, import_records.len); + const array = try jsc.JSValue.createEmptyArray(global, import_records.len); array.ensureStillAlive(); for (import_records, 0..) |record, i| { if (record.is_internal) continue; array.ensureStillAlive(); - const path = JSC.ZigString.init(record.path.text).toJS(global); - const kind = JSC.ZigString.init(record.kind.label()).toJS(global); - try array.putIndex(global, @as(u32, @truncate(i)), try JSC.JSValue.createObject2(global, path_label, kind_label, path, kind)); + const path = jsc.ZigString.init(record.path.text).toJS(global); + const kind = jsc.ZigString.init(record.kind.label()).toJS(global); + try array.putIndex(global, @as(u32, @truncate(i)), try jsc.JSValue.createObject2(global, path_label, kind_label, path, kind)); } return array; } -pub fn scanImports(this: *JSTranspiler, globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { +pub fn scanImports(this: *JSTranspiler, globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const arguments = callframe.arguments_old(2); - var args = JSC.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), arguments.slice()); + var args = jsc.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), arguments.slice()); defer args.deinit(); const code_arg = args.next() orelse { return globalThis.throwInvalidArgumentType("scanImports", "code", "string or Uint8Array"); }; - const code_holder = try JSC.Node.StringOrBuffer.fromJS(globalThis, args.arena.allocator(), code_arg) orelse { + const code_holder = try jsc.Node.StringOrBuffer.fromJS(globalThis, args.arena.allocator(), code_arg) orelse { if (!globalThis.hasException()) { return globalThis.throwInvalidArgumentType("scanImports", "code", "string or Uint8Array"); } @@ -1074,7 +1074,7 @@ pub fn scanImports(this: *JSTranspiler, globalThis: *JSC.JSGlobalObject, callfra return globalThis.throwInvalidArguments("Only JavaScript-like files support this fast path", .{}); } - var arena = Mimalloc.Arena.init() catch unreachable; + var arena = MimallocArena.init() catch unreachable; const prev_allocator = this.transpiler.allocator; const allocator = arena.allocator(); var ast_memory_allocator = allocator.create(JSAst.ASTMemoryAllocator) catch bun.outOfMemory(); @@ -1133,9 +1133,9 @@ pub fn scanImports(this: *JSTranspiler, globalThis: *JSC.JSGlobalObject, callfra return named_imports_value; } -const Mimalloc = @import("../../allocators/mimalloc_arena.zig"); +const string = []const u8; + const std = @import("std"); -const Api = @import("../../api/schema.zig").Api; const ImportRecord = @import("../../import_record.zig").ImportRecord; const Runtime = @import("../../runtime.zig").Runtime; const TSConfigJSON = @import("../../resolver/tsconfig_json.zig").TSConfigJSON; @@ -1152,16 +1152,17 @@ const JSLexer = bun.js_lexer; const JSPrinter = bun.js_printer; const Transpiler = bun.transpiler; const logger = bun.logger; -const string = bun.string; const strings = bun.strings; +const MimallocArena = bun.allocators.MimallocArena; +const api = bun.schema.api; -const JSAst = bun.JSAst; +const JSAst = bun.ast; const Expr = JSAst.Expr; -const JSC = bun.JSC; -const JSGlobalObject = JSC.JSGlobalObject; -const JSValue = bun.JSC.JSValue; -const ZigString = JSC.ZigString; - const JSParser = bun.js_parser; const ScanPassResult = JSParser.ScanPassResult; + +const jsc = bun.jsc; +const JSGlobalObject = jsc.JSGlobalObject; +const JSValue = bun.jsc.JSValue; +const ZigString = jsc.ZigString; diff --git a/src/bun.js/api/TOMLObject.zig b/src/bun.js/api/TOMLObject.zig index 6d0a8ff040..8b3d414d9e 100644 --- a/src/bun.js/api/TOMLObject.zig +++ b/src/bun.js/api/TOMLObject.zig @@ -1,9 +1,9 @@ -pub fn create(globalThis: *JSC.JSGlobalObject) JSC.JSValue { +pub fn create(globalThis: *jsc.JSGlobalObject) jsc.JSValue { const object = JSValue.createEmptyObject(globalThis, 1); object.put( globalThis, ZigString.static("parse"), - JSC.createCallback( + jsc.createCallback( globalThis, ZigString.static("parse"), 1, @@ -15,9 +15,9 @@ pub fn create(globalThis: *JSC.JSGlobalObject) JSC.JSValue { } pub fn parse( - globalThis: *JSC.JSGlobalObject, - callframe: *JSC.CallFrame, -) bun.JSError!JSC.JSValue { + globalThis: *jsc.JSGlobalObject, + callframe: *jsc.CallFrame, +) bun.JSError!jsc.JSValue { var arena = bun.ArenaAllocator.init(globalThis.allocator()); const allocator = arena.allocator(); defer arena.deinit(); @@ -30,7 +30,7 @@ pub fn parse( var input_slice = try arguments[0].toSlice(globalThis, bun.default_allocator); defer input_slice.deinit(); const source = &logger.Source.initPathString("input.toml", input_slice.slice()); - const parse_result = TOMLParser.parse(source, &log, allocator, false) catch { + const parse_result = TOML.parse(source, &log, allocator, false) catch { return globalThis.throwValue(try log.toJS(globalThis, default_allocator, "Failed to parse toml")); }; @@ -56,14 +56,13 @@ pub fn parse( return out.toJSByParseJSON(globalThis); } -const TOMLParser = @import("../../toml/toml_parser.zig").TOML; - const bun = @import("bun"); const default_allocator = bun.default_allocator; const js_printer = bun.js_printer; const logger = bun.logger; +const TOML = bun.interchange.toml.TOML; -const JSC = bun.JSC; -const JSGlobalObject = JSC.JSGlobalObject; -const JSValue = JSC.JSValue; -const ZigString = JSC.ZigString; +const jsc = bun.jsc; +const JSGlobalObject = jsc.JSGlobalObject; +const JSValue = jsc.JSValue; +const ZigString = jsc.ZigString; diff --git a/src/bun.js/api/Timer.zig b/src/bun.js/api/Timer.zig index b6e62ab695..9108af69b8 100644 --- a/src/bun.js/api/Timer.zig +++ b/src/bun.js/api/Timer.zig @@ -168,7 +168,7 @@ pub const All = struct { } pub fn incrementTimerRef(this: *All, delta: i32) void { - const vm: *JSC.VirtualMachine = @alignCast(@fieldParentPtr("timer", this)); + const vm: *jsc.VirtualMachine = @alignCast(@fieldParentPtr("timer", this)); const old = this.active_timer_count; const new = old + delta; @@ -365,7 +365,7 @@ pub const All = struct { promise: JSValue, countdown: JSValue, ) JSError!JSValue { - JSC.markBinding(@src()); + jsc.markBinding(@src()); bun.debugAssert(promise != .zero and countdown != .zero); const vm = global.bunVM(); const id = vm.timer.last_id; @@ -381,7 +381,7 @@ pub const All = struct { callback: JSValue, arguments: JSValue, ) JSError!JSValue { - JSC.markBinding(@src()); + jsc.markBinding(@src()); bun.debugAssert(callback != .zero and arguments != .zero); const vm = global.bunVM(); const id = vm.timer.last_id; @@ -397,7 +397,7 @@ pub const All = struct { arguments: JSValue, countdown: JSValue, ) JSError!JSValue { - JSC.markBinding(@src()); + jsc.markBinding(@src()); bun.debugAssert(callback != .zero and arguments != .zero and countdown != .zero); const vm = global.bunVM(); const id = vm.timer.last_id; @@ -413,7 +413,7 @@ pub const All = struct { arguments: JSValue, countdown: JSValue, ) JSError!JSValue { - JSC.markBinding(@src()); + jsc.markBinding(@src()); bun.debugAssert(callback != .zero and arguments != .zero and countdown != .zero); const vm = global.bunVM(); const id = vm.timer.last_id; @@ -435,7 +435,7 @@ pub const All = struct { } pub fn clearTimer(timer_id_value: JSValue, globalThis: *JSGlobalObject, kind: Kind) JSError!void { - JSC.markBinding(@src()); + jsc.markBinding(@src()); const vm = globalThis.bunVM(); @@ -498,7 +498,7 @@ pub const All = struct { globalThis: *JSGlobalObject, id: JSValue, ) JSError!JSValue { - JSC.markBinding(@src()); + jsc.markBinding(@src()); try clearTimer(id, globalThis, .setImmediate); return .js_undefined; } @@ -506,7 +506,7 @@ pub const All = struct { globalThis: *JSGlobalObject, id: JSValue, ) JSError!JSValue { - JSC.markBinding(@src()); + jsc.markBinding(@src()); try clearTimer(id, globalThis, .setTimeout); return .js_undefined; } @@ -514,19 +514,19 @@ pub const All = struct { globalThis: *JSGlobalObject, id: JSValue, ) JSError!JSValue { - JSC.markBinding(@src()); + jsc.markBinding(@src()); try clearTimer(id, globalThis, .setInterval); return .js_undefined; } comptime { - @export(&JSC.host_fn.wrap3(setImmediate), .{ .name = "Bun__Timer__setImmediate" }); - @export(&JSC.host_fn.wrap3(sleep), .{ .name = "Bun__Timer__sleep" }); - @export(&JSC.host_fn.wrap4(setTimeout), .{ .name = "Bun__Timer__setTimeout" }); - @export(&JSC.host_fn.wrap4(setInterval), .{ .name = "Bun__Timer__setInterval" }); - @export(&JSC.host_fn.wrap2(clearImmediate), .{ .name = "Bun__Timer__clearImmediate" }); - @export(&JSC.host_fn.wrap2(clearTimeout), .{ .name = "Bun__Timer__clearTimeout" }); - @export(&JSC.host_fn.wrap2(clearInterval), .{ .name = "Bun__Timer__clearInterval" }); + @export(&jsc.host_fn.wrap3(setImmediate), .{ .name = "Bun__Timer__setImmediate" }); + @export(&jsc.host_fn.wrap3(sleep), .{ .name = "Bun__Timer__sleep" }); + @export(&jsc.host_fn.wrap4(setTimeout), .{ .name = "Bun__Timer__setTimeout" }); + @export(&jsc.host_fn.wrap4(setInterval), .{ .name = "Bun__Timer__setInterval" }); + @export(&jsc.host_fn.wrap2(clearImmediate), .{ .name = "Bun__Timer__clearImmediate" }); + @export(&jsc.host_fn.wrap2(clearTimeout), .{ .name = "Bun__Timer__clearTimeout" }); + @export(&jsc.host_fn.wrap2(clearInterval), .{ .name = "Bun__Timer__clearInterval" }); @export(&getNextID, .{ .name = "Bun__Timer__getNextID" }); } }; @@ -569,7 +569,7 @@ pub const ID = extern struct { }; /// A timer created by WTF code and invoked by Bun's event loop -pub const WTFTimer = @import("../WTFTimer.zig"); +pub const WTFTimer = @import("./Timer/WTFTimer.zig"); pub const internal_bindings = struct { /// Node.js has some tests that check whether timers fire at the right time. They check this @@ -583,7 +583,7 @@ pub const internal_bindings = struct { /// thinking that the timing is wrong (this also happens when I run the modified test in /// Node.js). So the best course of action is for Bun to also expose a function that reveals the /// clock that is used to schedule timers. - pub fn timerClockMs(globalThis: *JSC.JSGlobalObject, callFrame: *JSC.CallFrame) bun.JSError!JSValue { + pub fn timerClockMs(globalThis: *jsc.JSGlobalObject, callFrame: *jsc.CallFrame) bun.JSError!JSValue { _ = globalThis; _ = callFrame; const now = timespec.now().ms(); @@ -601,7 +601,7 @@ const timespec = bun.timespec; const heap = bun.io.heap; const uv = bun.windows.libuv; -const JSC = bun.JSC; -const JSGlobalObject = JSC.JSGlobalObject; -const JSValue = JSC.JSValue; -const VirtualMachine = JSC.VirtualMachine; +const jsc = bun.jsc; +const JSGlobalObject = jsc.JSGlobalObject; +const JSValue = jsc.JSValue; +const VirtualMachine = jsc.VirtualMachine; diff --git a/src/bun.js/api/Timer/EventLoopTimer.zig b/src/bun.js/api/Timer/EventLoopTimer.zig index da4e38f648..005940e302 100644 --- a/src/bun.js/api/Timer/EventLoopTimer.zig +++ b/src/bun.js/api/Timer/EventLoopTimer.zig @@ -1,20 +1,20 @@ -const EventLoopTimer = @This(); +const Self = @This(); /// The absolute time to fire this timer next. next: timespec, state: State = .PENDING, tag: Tag, /// Internal heap fields. -heap: bun.io.heap.IntrusiveField(EventLoopTimer) = .{}, +heap: bun.io.heap.IntrusiveField(Self) = .{}, -pub fn initPaused(tag: Tag) EventLoopTimer { +pub fn initPaused(tag: Tag) Self { return .{ .next = .epoch, .tag = tag, }; } -pub fn less(_: void, a: *const EventLoopTimer, b: *const EventLoopTimer) bool { +pub fn less(_: void, a: *const Self, b: *const Self) bool { const sec_order = std.math.order(a.next.sec, b.next.sec); if (sec_order != .eq) return sec_order == .lt; @@ -70,17 +70,17 @@ pub const Tag = if (Environment.isWindows) enum { .TimerCallback => TimerCallback, .TimeoutObject => TimeoutObject, .ImmediateObject => ImmediateObject, - .TestRunner => JSC.Jest.TestRunner, + .TestRunner => jsc.Jest.TestRunner, .StatWatcherScheduler => StatWatcherScheduler, .UpgradedDuplex => uws.UpgradedDuplex, .DNSResolver => DNSResolver, .WindowsNamedPipe => uws.WindowsNamedPipe, .WTFTimer => WTFTimer, - .PostgresSQLConnectionTimeout => JSC.Postgres.PostgresSQLConnection, - .PostgresSQLConnectionMaxLifetime => JSC.Postgres.PostgresSQLConnection, - .SubprocessTimeout => JSC.Subprocess, - .ValkeyConnectionReconnect => JSC.API.Valkey, - .ValkeyConnectionTimeout => JSC.API.Valkey, + .PostgresSQLConnectionTimeout => jsc.Postgres.PostgresSQLConnection, + .PostgresSQLConnectionMaxLifetime => jsc.Postgres.PostgresSQLConnection, + .SubprocessTimeout => jsc.Subprocess, + .ValkeyConnectionReconnect => jsc.API.Valkey, + .ValkeyConnectionTimeout => jsc.API.Valkey, .DevServerSweepSourceMaps, .DevServerMemoryVisualizerTick, => bun.bake.DevServer, @@ -108,16 +108,16 @@ pub const Tag = if (Environment.isWindows) enum { .TimerCallback => TimerCallback, .TimeoutObject => TimeoutObject, .ImmediateObject => ImmediateObject, - .TestRunner => JSC.Jest.TestRunner, + .TestRunner => jsc.Jest.TestRunner, .StatWatcherScheduler => StatWatcherScheduler, .UpgradedDuplex => uws.UpgradedDuplex, .WTFTimer => WTFTimer, .DNSResolver => DNSResolver, - .PostgresSQLConnectionTimeout => JSC.Postgres.PostgresSQLConnection, - .PostgresSQLConnectionMaxLifetime => JSC.Postgres.PostgresSQLConnection, - .ValkeyConnectionTimeout => JSC.API.Valkey, - .ValkeyConnectionReconnect => JSC.API.Valkey, - .SubprocessTimeout => JSC.Subprocess, + .PostgresSQLConnectionTimeout => jsc.Postgres.PostgresSQLConnection, + .PostgresSQLConnectionMaxLifetime => jsc.Postgres.PostgresSQLConnection, + .ValkeyConnectionTimeout => jsc.API.Valkey, + .ValkeyConnectionReconnect => jsc.API.Valkey, + .SubprocessTimeout => jsc.Subprocess, .DevServerSweepSourceMaps, .DevServerMemoryVisualizerTick, => bun.bake.DevServer, @@ -128,7 +128,7 @@ pub const Tag = if (Environment.isWindows) enum { const TimerCallback = struct { callback: *const fn (*TimerCallback) Arm, ctx: *anyopaque, - event_loop_timer: EventLoopTimer, + event_loop_timer: Self, }; pub const State = enum { @@ -148,15 +148,15 @@ pub const State = enum { /// If self was created by set{Immediate,Timeout,Interval}, get a pointer to the common data /// for all those kinds of timers pub fn jsTimerInternals(self: anytype) switch (@TypeOf(self)) { - *EventLoopTimer => ?*TimerObjectInternals, - *const EventLoopTimer => ?*const TimerObjectInternals, + *Self => ?*TimerObjectInternals, + *const Self => ?*const TimerObjectInternals, else => |T| @compileError("wrong type " ++ @typeName(T) ++ " passed to jsTimerInternals"), } { switch (self.tag) { inline .TimeoutObject, .ImmediateObject => |tag| { const parent: switch (@TypeOf(self)) { - *EventLoopTimer => *tag.Type(), - *const EventLoopTimer => *const tag.Type(), + *Self => *tag.Type(), + *const Self => *const tag.Type(), else => unreachable, } = @fieldParentPtr("event_loop_timer", self); return &parent.internals; @@ -165,7 +165,7 @@ pub fn jsTimerInternals(self: anytype) switch (@TypeOf(self)) { } } -fn ns(self: *const EventLoopTimer) u64 { +fn ns(self: *const Self) u64 { return self.next.ns(); } @@ -174,19 +174,19 @@ pub const Arm = union(enum) { disarm, }; -pub fn fire(this: *EventLoopTimer, now: *const timespec, vm: *VirtualMachine) Arm { - switch (this.tag) { - .PostgresSQLConnectionTimeout => return @as(*api.Postgres.PostgresSQLConnection, @alignCast(@fieldParentPtr("timer", this))).onConnectionTimeout(), - .PostgresSQLConnectionMaxLifetime => return @as(*api.Postgres.PostgresSQLConnection, @alignCast(@fieldParentPtr("max_lifetime_timer", this))).onMaxLifetimeTimeout(), - .ValkeyConnectionTimeout => return @as(*api.Valkey, @alignCast(@fieldParentPtr("timer", this))).onConnectionTimeout(), - .ValkeyConnectionReconnect => return @as(*api.Valkey, @alignCast(@fieldParentPtr("reconnect_timer", this))).onReconnectTimer(), - .DevServerMemoryVisualizerTick => return bun.bake.DevServer.emitMemoryVisualizerMessageTimer(this, now), - .DevServerSweepSourceMaps => return bun.bake.DevServer.SourceMapStore.sweepWeakRefs(this, now), +pub fn fire(self: *Self, now: *const timespec, vm: *VirtualMachine) Arm { + switch (self.tag) { + .PostgresSQLConnectionTimeout => return @as(*api.Postgres.PostgresSQLConnection, @alignCast(@fieldParentPtr("timer", self))).onConnectionTimeout(), + .PostgresSQLConnectionMaxLifetime => return @as(*api.Postgres.PostgresSQLConnection, @alignCast(@fieldParentPtr("max_lifetime_timer", self))).onMaxLifetimeTimeout(), + .ValkeyConnectionTimeout => return @as(*api.Valkey, @alignCast(@fieldParentPtr("timer", self))).onConnectionTimeout(), + .ValkeyConnectionReconnect => return @as(*api.Valkey, @alignCast(@fieldParentPtr("reconnect_timer", self))).onReconnectTimer(), + .DevServerMemoryVisualizerTick => return bun.bake.DevServer.emitMemoryVisualizerMessageTimer(self, now), + .DevServerSweepSourceMaps => return bun.bake.DevServer.SourceMapStore.sweepWeakRefs(self, now), inline else => |t| { - if (@FieldType(t.Type(), "event_loop_timer") != EventLoopTimer) { + if (@FieldType(t.Type(), "event_loop_timer") != Self) { @compileError(@typeName(t.Type()) ++ " has wrong type for 'event_loop_timer'"); } - var container: *t.Type() = @alignCast(@fieldParentPtr("event_loop_timer", this)); + var container: *t.Type() = @alignCast(@fieldParentPtr("event_loop_timer", self)); if (comptime t.Type() == TimeoutObject or t.Type() == ImmediateObject) { return container.internals.fire(now, vm); } @@ -207,7 +207,7 @@ pub fn fire(this: *EventLoopTimer, now: *const timespec, vm: *VirtualMachine) Ar } } - if (comptime t.Type() == JSC.Jest.TestRunner) { + if (comptime t.Type() == jsc.Jest.TestRunner) { container.onTestTimeout(now, vm); return .disarm; } @@ -216,7 +216,7 @@ pub fn fire(this: *EventLoopTimer, now: *const timespec, vm: *VirtualMachine) Ar return container.checkTimeouts(now, vm); } - if (comptime t.Type() == JSC.Subprocess) { + if (comptime t.Type() == jsc.Subprocess) { return container.timeoutCallback(); } @@ -225,24 +225,24 @@ pub fn fire(this: *EventLoopTimer, now: *const timespec, vm: *VirtualMachine) Ar } } -pub fn deinit(_: *EventLoopTimer) void {} +pub fn deinit(_: *Self) void {} /// A timer created by WTF code and invoked by Bun's event loop -const WTFTimer = @import("../../WTFTimer.zig"); +const WTFTimer = bun.api.Timer.WTFTimer; const std = @import("std"); -const DNSResolver = @import("../bun/dns_resolver.zig").DNSResolver; const StatWatcherScheduler = @import("../../node/node_fs_stat_watcher.zig").StatWatcherScheduler; -const ImmediateObject = @import("../Timer.zig").ImmediateObject; -const TimeoutObject = @import("../Timer.zig").TimeoutObject; -const TimerObjectInternals = @import("../Timer.zig").TimerObjectInternals; - const bun = @import("bun"); const Environment = bun.Environment; const timespec = bun.timespec; const uws = bun.uws; +const DNSResolver = bun.api.dns.Resolver; -const JSC = bun.JSC; -const VirtualMachine = JSC.VirtualMachine; -const api = JSC.API; +const ImmediateObject = bun.api.Timer.ImmediateObject; +const TimeoutObject = bun.api.Timer.TimeoutObject; +const TimerObjectInternals = bun.api.Timer.TimerObjectInternals; + +const jsc = bun.jsc; +const VirtualMachine = jsc.VirtualMachine; +const api = jsc.API; diff --git a/src/bun.js/api/Timer/ImmediateObject.zig b/src/bun.js/api/Timer/ImmediateObject.zig index 69af245db9..f0fb9daa91 100644 --- a/src/bun.js/api/Timer/ImmediateObject.zig +++ b/src/bun.js/api/Timer/ImmediateObject.zig @@ -1,10 +1,10 @@ -const ImmediateObject = @This(); +const Self = @This(); const RefCount = bun.ptr.RefCount(@This(), "ref_count", deinit, .{}); pub const ref = RefCount.ref; pub const deref = RefCount.deref; -pub const js = JSC.Codegen.JSImmediate; +pub const js = jsc.Codegen.JSImmediate; pub const toJS = js.toJS; pub const fromJS = js.fromJS; pub const fromJSDirect = js.fromJSDirect; @@ -23,7 +23,7 @@ pub fn init( arguments: JSValue, ) JSValue { // internals are initialized by init() - const immediate = bun.new(ImmediateObject, .{ .ref_count = .init(), .internals = undefined }); + const immediate = bun.new(Self, .{ .ref_count = .init(), .internals = undefined }); const js_value = immediate.toJS(globalThis); defer js_value.ensureStillAlive(); immediate.internals.init( @@ -48,59 +48,59 @@ pub fn init( return js_value; } -fn deinit(this: *ImmediateObject) void { - this.internals.deinit(); - bun.destroy(this); +fn deinit(self: *Self) void { + self.internals.deinit(); + bun.destroy(self); } -pub fn constructor(globalObject: *JSC.JSGlobalObject, callFrame: *JSC.CallFrame) !*ImmediateObject { +pub fn constructor(globalObject: *jsc.JSGlobalObject, callFrame: *jsc.CallFrame) !*Self { _ = callFrame; return globalObject.throw("Immediate is not constructible", .{}); } /// returns true if an exception was thrown -pub fn runImmediateTask(this: *ImmediateObject, vm: *VirtualMachine) bool { - return this.internals.runImmediateTask(vm); +pub fn runImmediateTask(self: *Self, vm: *VirtualMachine) bool { + return self.internals.runImmediateTask(vm); } -pub fn toPrimitive(this: *ImmediateObject, _: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!JSValue { - return this.internals.toPrimitive(); +pub fn toPrimitive(self: *Self, _: *jsc.JSGlobalObject, _: *jsc.CallFrame) bun.JSError!JSValue { + return self.internals.toPrimitive(); } -pub fn doRef(this: *ImmediateObject, globalThis: *JSGlobalObject, callFrame: *JSC.CallFrame) bun.JSError!JSValue { - return this.internals.doRef(globalThis, callFrame.this()); +pub fn doRef(self: *Self, globalThis: *JSGlobalObject, callFrame: *jsc.CallFrame) bun.JSError!JSValue { + return self.internals.doRef(globalThis, callFrame.this()); } -pub fn doUnref(this: *ImmediateObject, globalThis: *JSGlobalObject, callFrame: *JSC.CallFrame) bun.JSError!JSValue { - return this.internals.doUnref(globalThis, callFrame.this()); +pub fn doUnref(self: *Self, globalThis: *JSGlobalObject, callFrame: *jsc.CallFrame) bun.JSError!JSValue { + return self.internals.doUnref(globalThis, callFrame.this()); } -pub fn hasRef(this: *ImmediateObject, _: *JSGlobalObject, _: *JSC.CallFrame) bun.JSError!JSValue { - return this.internals.hasRef(); +pub fn hasRef(self: *Self, _: *JSGlobalObject, _: *jsc.CallFrame) bun.JSError!JSValue { + return self.internals.hasRef(); } -pub fn finalize(this: *ImmediateObject) void { - this.internals.finalize(); +pub fn finalize(self: *Self) void { + self.internals.finalize(); } -pub fn getDestroyed(this: *ImmediateObject, globalThis: *JSGlobalObject) JSValue { +pub fn getDestroyed(self: *Self, globalThis: *JSGlobalObject) JSValue { _ = globalThis; - return .jsBoolean(this.internals.getDestroyed()); + return .jsBoolean(self.internals.getDestroyed()); } -pub fn dispose(this: *ImmediateObject, globalThis: *JSGlobalObject, _: *JSC.CallFrame) bun.JSError!JSValue { - this.internals.cancel(globalThis.bunVM()); +pub fn dispose(self: *Self, globalThis: *JSGlobalObject, _: *jsc.CallFrame) bun.JSError!JSValue { + self.internals.cancel(globalThis.bunVM()); return .js_undefined; } const Debugger = @import("../../Debugger.zig"); const bun = @import("bun"); -const EventLoopTimer = @import("../Timer.zig").EventLoopTimer; -const ID = @import("../Timer.zig").ID; -const TimerObjectInternals = @import("../Timer.zig").TimerObjectInternals; +const EventLoopTimer = bun.api.Timer.EventLoopTimer; +const ID = bun.api.Timer.ID; +const TimerObjectInternals = bun.api.Timer.TimerObjectInternals; -const JSC = bun.JSC; -const JSGlobalObject = JSC.JSGlobalObject; -const JSValue = JSC.JSValue; -const VirtualMachine = JSC.VirtualMachine; +const jsc = bun.jsc; +const JSGlobalObject = jsc.JSGlobalObject; +const JSValue = jsc.JSValue; +const VirtualMachine = jsc.VirtualMachine; diff --git a/src/bun.js/api/Timer/TimeoutObject.zig b/src/bun.js/api/Timer/TimeoutObject.zig index ae6399ff4a..fb344d0579 100644 --- a/src/bun.js/api/Timer/TimeoutObject.zig +++ b/src/bun.js/api/Timer/TimeoutObject.zig @@ -1,10 +1,10 @@ -const TimeoutObject = @This(); +const Self = @This(); const RefCount = bun.ptr.RefCount(@This(), "ref_count", deinit, .{}); pub const ref = RefCount.ref; pub const deref = RefCount.deref; -pub const js = JSC.Codegen.JSTimeout; +pub const js = jsc.Codegen.JSTimeout; pub const toJS = js.toJS; pub const fromJS = js.fromJS; pub const fromJSDirect = js.fromJSDirect; @@ -25,7 +25,7 @@ pub fn init( arguments: JSValue, ) JSValue { // internals are initialized by init() - const timeout = bun.new(TimeoutObject, .{ .ref_count = .init(), .internals = undefined }); + const timeout = bun.new(Self, .{ .ref_count = .init(), .internals = undefined }); const js_value = timeout.toJS(globalThis); defer js_value.ensureStillAlive(); timeout.internals.init( @@ -50,87 +50,87 @@ pub fn init( return js_value; } -fn deinit(this: *TimeoutObject) void { - this.internals.deinit(); - bun.destroy(this); +fn deinit(self: *Self) void { + self.internals.deinit(); + bun.destroy(self); } -pub fn constructor(globalObject: *JSC.JSGlobalObject, callFrame: *JSC.CallFrame) !*TimeoutObject { +pub fn constructor(globalObject: *jsc.JSGlobalObject, callFrame: *jsc.CallFrame) !*Self { _ = callFrame; return globalObject.throw("Timeout is not constructible", .{}); } -pub fn toPrimitive(this: *TimeoutObject, _: *JSGlobalObject, _: *JSC.CallFrame) bun.JSError!JSValue { - return this.internals.toPrimitive(); +pub fn toPrimitive(self: *Self, _: *JSGlobalObject, _: *jsc.CallFrame) bun.JSError!JSValue { + return self.internals.toPrimitive(); } -pub fn doRef(this: *TimeoutObject, globalThis: *JSGlobalObject, callFrame: *JSC.CallFrame) bun.JSError!JSValue { - return this.internals.doRef(globalThis, callFrame.this()); +pub fn doRef(self: *Self, globalThis: *JSGlobalObject, callFrame: *jsc.CallFrame) bun.JSError!JSValue { + return self.internals.doRef(globalThis, callFrame.this()); } -pub fn doUnref(this: *TimeoutObject, globalThis: *JSGlobalObject, callFrame: *JSC.CallFrame) bun.JSError!JSValue { - return this.internals.doUnref(globalThis, callFrame.this()); +pub fn doUnref(self: *Self, globalThis: *JSGlobalObject, callFrame: *jsc.CallFrame) bun.JSError!JSValue { + return self.internals.doUnref(globalThis, callFrame.this()); } -pub fn doRefresh(this: *TimeoutObject, globalThis: *JSGlobalObject, callFrame: *JSC.CallFrame) bun.JSError!JSValue { - return this.internals.doRefresh(globalThis, callFrame.this()); +pub fn doRefresh(self: *Self, globalThis: *JSGlobalObject, callFrame: *jsc.CallFrame) bun.JSError!JSValue { + return self.internals.doRefresh(globalThis, callFrame.this()); } -pub fn hasRef(this: *TimeoutObject, _: *JSGlobalObject, _: *JSC.CallFrame) bun.JSError!JSValue { - return this.internals.hasRef(); +pub fn hasRef(self: *Self, _: *JSGlobalObject, _: *jsc.CallFrame) bun.JSError!JSValue { + return self.internals.hasRef(); } -pub fn finalize(this: *TimeoutObject) void { - this.internals.finalize(); +pub fn finalize(self: *Self) void { + self.internals.finalize(); } -pub fn getDestroyed(this: *TimeoutObject, globalThis: *JSGlobalObject) JSValue { +pub fn getDestroyed(self: *Self, globalThis: *JSGlobalObject) JSValue { _ = globalThis; - return .jsBoolean(this.internals.getDestroyed()); + return .jsBoolean(self.internals.getDestroyed()); } -pub fn close(this: *TimeoutObject, globalThis: *JSGlobalObject, callFrame: *JSC.CallFrame) JSValue { - this.internals.cancel(globalThis.bunVM()); +pub fn close(self: *Self, globalThis: *JSGlobalObject, callFrame: *jsc.CallFrame) JSValue { + self.internals.cancel(globalThis.bunVM()); return callFrame.this(); } -pub fn get_onTimeout(_: *TimeoutObject, thisValue: JSValue, _: *JSGlobalObject) JSValue { - return TimeoutObject.js.callbackGetCached(thisValue).?; +pub fn get_onTimeout(_: *Self, thisValue: JSValue, _: *JSGlobalObject) JSValue { + return Self.js.callbackGetCached(thisValue).?; } -pub fn set_onTimeout(_: *TimeoutObject, thisValue: JSValue, globalThis: *JSGlobalObject, value: JSValue) void { - TimeoutObject.js.callbackSetCached(thisValue, globalThis, value); +pub fn set_onTimeout(_: *Self, thisValue: JSValue, globalThis: *JSGlobalObject, value: JSValue) void { + Self.js.callbackSetCached(thisValue, globalThis, value); } -pub fn get_idleTimeout(_: *TimeoutObject, thisValue: JSValue, _: *JSGlobalObject) JSValue { - return TimeoutObject.js.idleTimeoutGetCached(thisValue).?; +pub fn get_idleTimeout(_: *Self, thisValue: JSValue, _: *JSGlobalObject) JSValue { + return Self.js.idleTimeoutGetCached(thisValue).?; } -pub fn set_idleTimeout(_: *TimeoutObject, thisValue: JSValue, globalThis: *JSGlobalObject, value: JSValue) void { - TimeoutObject.js.idleTimeoutSetCached(thisValue, globalThis, value); +pub fn set_idleTimeout(_: *Self, thisValue: JSValue, globalThis: *JSGlobalObject, value: JSValue) void { + Self.js.idleTimeoutSetCached(thisValue, globalThis, value); } -pub fn get_repeat(_: *TimeoutObject, thisValue: JSValue, _: *JSGlobalObject) JSValue { - return TimeoutObject.js.repeatGetCached(thisValue).?; +pub fn get_repeat(_: *Self, thisValue: JSValue, _: *JSGlobalObject) JSValue { + return Self.js.repeatGetCached(thisValue).?; } -pub fn set_repeat(_: *TimeoutObject, thisValue: JSValue, globalThis: *JSGlobalObject, value: JSValue) void { - TimeoutObject.js.repeatSetCached(thisValue, globalThis, value); +pub fn set_repeat(_: *Self, thisValue: JSValue, globalThis: *JSGlobalObject, value: JSValue) void { + Self.js.repeatSetCached(thisValue, globalThis, value); } -pub fn dispose(this: *TimeoutObject, globalThis: *JSGlobalObject, _: *JSC.CallFrame) bun.JSError!JSValue { - this.internals.cancel(globalThis.bunVM()); +pub fn dispose(self: *Self, globalThis: *JSGlobalObject, _: *jsc.CallFrame) bun.JSError!JSValue { + self.internals.cancel(globalThis.bunVM()); return .js_undefined; } const Debugger = @import("../../Debugger.zig"); const bun = @import("bun"); -const EventLoopTimer = @import("../Timer.zig").EventLoopTimer; -const ID = @import("../Timer.zig").ID; -const Kind = @import("../Timer.zig").Kind; -const TimerObjectInternals = @import("../Timer.zig").TimerObjectInternals; +const EventLoopTimer = bun.api.Timer.EventLoopTimer; +const ID = bun.api.Timer.ID; +const Kind = bun.api.Timer.Kind; +const TimerObjectInternals = bun.api.Timer.TimerObjectInternals; -const JSC = bun.JSC; -const JSGlobalObject = JSC.JSGlobalObject; -const JSValue = JSC.JSValue; +const jsc = bun.jsc; +const JSGlobalObject = jsc.JSGlobalObject; +const JSValue = jsc.JSValue; diff --git a/src/bun.js/api/Timer/TimerObjectInternals.zig b/src/bun.js/api/Timer/TimerObjectInternals.zig index c8dee8614e..41d1ab69be 100644 --- a/src/bun.js/api/Timer/TimerObjectInternals.zig +++ b/src/bun.js/api/Timer/TimerObjectInternals.zig @@ -4,7 +4,7 @@ const TimerObjectInternals = @This(); /// Identifier for this timer that is exposed to JavaScript (by `+timer`) id: i32 = -1, interval: u31 = 0, -strong_this: JSC.Strong.Optional = .empty, +strong_this: jsc.Strong.Optional = .empty, flags: Flags = .{}, const Flags = packed struct(u32) { @@ -61,7 +61,7 @@ fn deref(this: *TimerObjectInternals) void { } } -extern "c" fn Bun__JSTimeout__call(globalObject: *JSC.JSGlobalObject, timer: JSValue, callback: JSValue, arguments: JSValue) bool; +extern "c" fn Bun__JSTimeout__call(globalObject: *jsc.JSGlobalObject, timer: JSValue, callback: JSValue, arguments: JSValue) bool; /// returns true if an exception was thrown pub fn runImmediateTask(this: *TimerObjectInternals, vm: *VirtualMachine) bool { @@ -105,7 +105,7 @@ pub fn asyncID(this: *const TimerObjectInternals) u64 { return ID.asyncID(.{ .id = this.id, .kind = this.flags.kind.big() }); } -pub fn fire(this: *TimerObjectInternals, _: *const timespec, vm: *JSC.VirtualMachine) EventLoopTimer.Arm { +pub fn fire(this: *TimerObjectInternals, _: *const timespec, vm: *jsc.VirtualMachine) EventLoopTimer.Arm { const id = this.id; const kind = this.flags.kind.big(); const async_id: ID = .{ .id = id, .kind = kind }; @@ -241,7 +241,7 @@ fn convertToInterval(this: *TimerObjectInternals, global: *JSGlobalObject, timer this.reschedule(timer, vm); } -pub fn run(this: *TimerObjectInternals, globalThis: *JSC.JSGlobalObject, timer: JSValue, callback: JSValue, arguments: JSValue, async_id: u64, vm: *JSC.VirtualMachine) bool { +pub fn run(this: *TimerObjectInternals, globalThis: *jsc.JSGlobalObject, timer: JSValue, callback: JSValue, arguments: JSValue, async_id: u64, vm: *jsc.VirtualMachine) bool { if (vm.isInspectorEnabled()) { Debugger.willDispatchAsyncCall(globalThis, .DOMTimer, async_id); } @@ -286,8 +286,8 @@ pub fn init( } else { TimeoutObject.js.argumentsSetCached(timer, global, arguments); TimeoutObject.js.callbackSetCached(timer, global, callback); - TimeoutObject.js.idleTimeoutSetCached(timer, global, JSC.jsNumber(interval)); - TimeoutObject.js.repeatSetCached(timer, global, if (kind == .setInterval) JSC.jsNumber(interval) else .null); + TimeoutObject.js.idleTimeoutSetCached(timer, global, jsc.jsNumber(interval)); + TimeoutObject.js.repeatSetCached(timer, global, if (kind == .setInterval) jsc.jsNumber(interval) else .null); // this increments the refcount this.reschedule(timer, vm); @@ -296,7 +296,7 @@ pub fn init( this.strong_this.set(global, timer); } -pub fn doRef(this: *TimerObjectInternals, _: *JSC.JSGlobalObject, this_value: JSValue) JSValue { +pub fn doRef(this: *TimerObjectInternals, _: *jsc.JSGlobalObject, this_value: JSValue) JSValue { this_value.ensureStillAlive(); const did_have_js_ref = this.flags.has_js_ref; @@ -306,13 +306,13 @@ pub fn doRef(this: *TimerObjectInternals, _: *JSC.JSGlobalObject, this_value: JS // and // https://github.com/nodejs/node/blob/a7cbb904745591c9a9d047a364c2c188e5470047/lib/internal/timers.js#L685-L687 if (!did_have_js_ref and !this.flags.has_cleared_timer) { - this.setEnableKeepingEventLoopAlive(JSC.VirtualMachine.get(), true); + this.setEnableKeepingEventLoopAlive(jsc.VirtualMachine.get(), true); } return this_value; } -pub fn doRefresh(this: *TimerObjectInternals, globalObject: *JSC.JSGlobalObject, this_value: JSValue) JSValue { +pub fn doRefresh(this: *TimerObjectInternals, globalObject: *jsc.JSGlobalObject, this_value: JSValue) JSValue { // Immediates do not have a refresh function, and our binding generator should not let this // function be reached even if you override the `this` value calling a Timeout object's // `refresh` method @@ -329,14 +329,14 @@ pub fn doRefresh(this: *TimerObjectInternals, globalObject: *JSC.JSGlobalObject, return this_value; } -pub fn doUnref(this: *TimerObjectInternals, _: *JSC.JSGlobalObject, this_value: JSValue) JSValue { +pub fn doUnref(this: *TimerObjectInternals, _: *jsc.JSGlobalObject, this_value: JSValue) JSValue { this_value.ensureStillAlive(); const did_have_js_ref = this.flags.has_js_ref; this.flags.has_js_ref = false; if (did_have_js_ref) { - this.setEnableKeepingEventLoopAlive(JSC.VirtualMachine.get(), false); + this.setEnableKeepingEventLoopAlive(jsc.VirtualMachine.get(), false); } return this_value; @@ -472,19 +472,20 @@ pub fn deinit(this: *TimerObjectInternals) void { const Debugger = @import("../../Debugger.zig"); const std = @import("std"); -const EventLoopTimer = @import("../Timer.zig").EventLoopTimer; -const ID = @import("../Timer.zig").ID; -const ImmediateObject = @import("../Timer.zig").ImmediateObject; -const Kind = @import("../Timer.zig").Kind; -const TimeoutMap = @import("../Timer.zig").TimeoutMap; -const TimeoutObject = @import("../Timer.zig").TimeoutObject; - const bun = @import("bun"); const Environment = bun.Environment; const assert = bun.assert; const timespec = bun.timespec; -const JSC = bun.JSC; -const JSGlobalObject = JSC.JSGlobalObject; -const JSValue = JSC.JSValue; -const VirtualMachine = JSC.VirtualMachine; +const Timer = bun.api.Timer; +const EventLoopTimer = Timer.EventLoopTimer; +const ID = Timer.ID; +const ImmediateObject = Timer.ImmediateObject; +const Kind = Timer.Kind; +const TimeoutMap = Timer.TimeoutMap; +const TimeoutObject = Timer.TimeoutObject; + +const jsc = bun.jsc; +const JSGlobalObject = jsc.JSGlobalObject; +const JSValue = jsc.JSValue; +const VirtualMachine = jsc.VirtualMachine; diff --git a/src/bun.js/WTFTimer.zig b/src/bun.js/api/Timer/WTFTimer.zig similarity index 100% rename from src/bun.js/WTFTimer.zig rename to src/bun.js/api/Timer/WTFTimer.zig diff --git a/src/bun.js/api/UnsafeObject.zig b/src/bun.js/api/UnsafeObject.zig index 564c949345..f42fcb29a2 100644 --- a/src/bun.js/api/UnsafeObject.zig +++ b/src/bun.js/api/UnsafeObject.zig @@ -1,4 +1,4 @@ -pub fn create(globalThis: *JSC.JSGlobalObject) JSC.JSValue { +pub fn create(globalThis: *jsc.JSGlobalObject) jsc.JSValue { const object = JSValue.createEmptyObject(globalThis, 3); const fields = comptime .{ .gcAggressionLevel = gcAggressionLevel, @@ -9,16 +9,16 @@ pub fn create(globalThis: *JSC.JSGlobalObject) JSC.JSValue { object.put( globalThis, comptime ZigString.static(name), - JSC.createCallback(globalThis, comptime ZigString.static(name), 1, comptime @field(fields, name)), + jsc.createCallback(globalThis, comptime ZigString.static(name), 1, comptime @field(fields, name)), ); } return object; } pub fn gcAggressionLevel( - globalThis: *JSC.JSGlobalObject, - callframe: *JSC.CallFrame, -) bun.JSError!JSC.JSValue { + globalThis: *jsc.JSGlobalObject, + callframe: *jsc.CallFrame, +) bun.JSError!jsc.JSValue { const ret = JSValue.jsNumber(@as(i32, @intFromEnum(globalThis.bunVM().aggressive_garbage_collection))); const value = callframe.arguments_old(1).ptr[0]; @@ -34,15 +34,15 @@ pub fn gcAggressionLevel( } pub fn arrayBufferToString( - globalThis: *JSC.JSGlobalObject, - callframe: *JSC.CallFrame, -) bun.JSError!JSC.JSValue { + globalThis: *jsc.JSGlobalObject, + callframe: *jsc.CallFrame, +) bun.JSError!jsc.JSValue { const args = callframe.arguments_old(2).slice(); if (args.len < 1 or !args[0].isCell() or !args[0].jsType().isTypedArrayOrArrayBuffer()) { return globalThis.throwInvalidArguments("Expected an ArrayBuffer", .{}); } - const array_buffer = JSC.ArrayBuffer.fromTypedArray(globalThis, args[0]); + const array_buffer = jsc.ArrayBuffer.fromTypedArray(globalThis, args[0]); switch (array_buffer.typed_array_type) { .Uint16Array, .Int16Array => { var zig_str = ZigString.init(""); @@ -59,7 +59,7 @@ pub fn arrayBufferToString( extern fn dump_zone_malloc_stats() void; -fn dump_mimalloc(globalObject: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!JSC.JSValue { +fn dump_mimalloc(globalObject: *jsc.JSGlobalObject, _: *jsc.CallFrame) bun.JSError!jsc.JSValue { globalObject.bunVM().arena.dumpStats(); if (bun.heap_breakdown.enabled) { dump_zone_malloc_stats(); @@ -70,7 +70,7 @@ fn dump_mimalloc(globalObject: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSErr const bun = @import("bun"); const std = @import("std"); -const JSC = bun.JSC; -const JSGlobalObject = JSC.JSGlobalObject; -const JSValue = JSC.JSValue; -const ZigString = JSC.ZigString; +const jsc = bun.jsc; +const JSGlobalObject = jsc.JSGlobalObject; +const JSValue = jsc.JSValue; +const ZigString = jsc.ZigString; diff --git a/src/bun.js/api/bun/dns_resolver.zig b/src/bun.js/api/bun/dns.zig similarity index 89% rename from src/bun.js/api/bun/dns_resolver.zig rename to src/bun.js/api/bun/dns.zig index cf727c08a9..c3117f480d 100644 --- a/src/bun.js/api/bun/dns_resolver.zig +++ b/src/bun.js/api/bun/dns.zig @@ -1,3 +1,5 @@ +const dns = @This(); + const GetAddrInfoAsyncCallback = fn (i32, ?*std.c.addrinfo, ?*anyopaque) callconv(.C) void; const INET6_ADDRSTRLEN = if (bun.Environment.isWindows) 65 else 46; const IANA_DNS_PORT = 53; @@ -50,7 +52,7 @@ const LibInfo = struct { return bun.C.dlsymWithHandle(*const GetaddrinfoAsyncCancel, "getaddrinfo_async_cancel", getHandle); } - pub fn lookup(this: *DNSResolver, query: GetAddrInfo, globalThis: *JSC.JSGlobalObject) JSC.JSValue { + pub fn lookup(this: *Resolver, query: GetAddrInfo, globalThis: *jsc.JSGlobalObject) jsc.JSValue { bun.Environment.onlyMac(); const getaddrinfo_async_start_ = LibInfo.getaddrinfo_async_start() orelse return LibC.lookup(this, query, globalThis); @@ -126,7 +128,7 @@ const LibInfo = struct { }; const LibC = struct { - pub fn lookup(this: *DNSResolver, query_init: GetAddrInfo, globalThis: *JSC.JSGlobalObject) JSC.JSValue { + pub fn lookup(this: *Resolver, query_init: GetAddrInfo, globalThis: *jsc.JSGlobalObject) jsc.JSValue { if (Environment.isWindows) { @compileError("Do not use this path on Windows"); } @@ -171,7 +173,7 @@ const LibUVBackend = struct { const this: *GetAddrInfoRequest = @alignCast(@ptrCast(uv_info.data)); const Holder = struct { uv_info: *libuv.uv_getaddrinfo_t, - task: JSC.AnyTask, + task: jsc.AnyTask, pub fn run(held: *@This()) void { defer bun.default_allocator.destroy(held); @@ -184,12 +186,12 @@ const LibUVBackend = struct { .uv_info = uv_info, .task = undefined, }; - holder.task = JSC.AnyTask.New(Holder, Holder.run).init(holder); + holder.task = jsc.AnyTask.New(Holder, Holder.run).init(holder); - this.head.globalThis.bunVM().enqueueTask(JSC.Task.init(&holder.task)); + this.head.globalThis.bunVM().enqueueTask(jsc.Task.init(&holder.task)); } - pub fn lookup(this: *DNSResolver, query: GetAddrInfo, globalThis: *JSC.JSGlobalObject) !JSC.JSValue { + pub fn lookup(this: *Resolver, query: GetAddrInfo, globalThis: *jsc.JSGlobalObject) !jsc.JSValue { const key = GetAddrInfoRequest.PendingCacheKey.init(query); var cache = this.getOrPutIntoPendingCache(key, .pending_host_cache_native); @@ -267,17 +269,17 @@ pub fn ResolveInfoRequest(comptime cares_type: type, comptime type_name: []const const log = Output.scoped(.ResolveInfoRequest, true); - resolver_for_caching: ?*DNSResolver = null, + resolver_for_caching: ?*Resolver = null, hash: u64 = 0, cache: @This().CacheConfig = @This().CacheConfig{}, head: CAresLookup(cares_type, type_name), tail: *CAresLookup(cares_type, type_name) = undefined, pub fn init( - cache: DNSResolver.LookupCacheHit(@This()), - resolver: ?*DNSResolver, + cache: Resolver.LookupCacheHit(@This()), + resolver: ?*Resolver, name: []const u8, - globalThis: *JSC.JSGlobalObject, + globalThis: *jsc.JSGlobalObject, comptime cache_field: []const u8, ) !*@This() { var request = try globalThis.allocator().create(@This()); @@ -294,7 +296,7 @@ pub fn ResolveInfoRequest(comptime cares_type: type, comptime type_name: []const .resolver = resolver, .poll_ref = poll_ref, .globalThis = globalThis, - .promise = JSC.JSPromise.Strong.init(globalThis), + .promise = jsc.JSPromise.Strong.init(globalThis), .allocated = false, .name = name, }, @@ -373,17 +375,17 @@ pub const GetHostByAddrInfoRequest = struct { const log = Output.scoped(@This(), false); - resolver_for_caching: ?*DNSResolver = null, + resolver_for_caching: ?*Resolver = null, hash: u64 = 0, cache: @This().CacheConfig = @This().CacheConfig{}, head: CAresReverse, tail: *CAresReverse = undefined, pub fn init( - cache: DNSResolver.LookupCacheHit(@This()), - resolver: ?*DNSResolver, + cache: Resolver.LookupCacheHit(@This()), + resolver: ?*Resolver, name: []const u8, - globalThis: *JSC.JSGlobalObject, + globalThis: *jsc.JSGlobalObject, comptime cache_field: []const u8, ) !*@This() { var request = try globalThis.allocator().create(@This()); @@ -400,7 +402,7 @@ pub const GetHostByAddrInfoRequest = struct { .resolver = resolver, .poll_ref = poll_ref, .globalThis = globalThis, - .promise = JSC.JSPromise.Strong.init(globalThis), + .promise = jsc.JSPromise.Strong.init(globalThis), .allocated = false, .name = name, }, @@ -472,20 +474,20 @@ pub const GetHostByAddrInfoRequest = struct { pub const CAresNameInfo = struct { const log = Output.scoped(.CAresNameInfo, true); - globalThis: *JSC.JSGlobalObject, - promise: JSC.JSPromise.Strong, + globalThis: *jsc.JSGlobalObject, + promise: jsc.JSPromise.Strong, poll_ref: bun.Async.KeepAlive, allocated: bool = false, next: ?*@This() = null, name: []const u8, - pub fn init(globalThis: *JSC.JSGlobalObject, allocator: std.mem.Allocator, name: []const u8) !*@This() { + pub fn init(globalThis: *jsc.JSGlobalObject, allocator: std.mem.Allocator, name: []const u8) !*@This() { const this = try allocator.create(@This()); var poll_ref = bun.Async.KeepAlive.init(); poll_ref.ref(globalThis.bunVM()); this.* = .{ .globalThis = globalThis, - .promise = JSC.JSPromise.Strong.init(globalThis), + .promise = jsc.JSPromise.Strong.init(globalThis), .poll_ref = poll_ref, .allocated = true, .name = name, @@ -510,7 +512,7 @@ pub const CAresNameInfo = struct { return; } - pub fn onComplete(this: *@This(), result: JSC.JSValue) void { + pub fn onComplete(this: *@This(), result: jsc.JSValue) void { var promise = this.promise; const globalThis = this.globalThis; this.promise = .{}; @@ -534,17 +536,17 @@ pub const GetNameInfoRequest = struct { const log = Output.scoped(@This(), false); - resolver_for_caching: ?*DNSResolver = null, + resolver_for_caching: ?*Resolver = null, hash: u64 = 0, cache: @This().CacheConfig = @This().CacheConfig{}, head: CAresNameInfo, tail: *CAresNameInfo = undefined, pub fn init( - cache: DNSResolver.LookupCacheHit(@This()), - resolver: ?*DNSResolver, + cache: Resolver.LookupCacheHit(@This()), + resolver: ?*Resolver, name: []const u8, - globalThis: *JSC.JSGlobalObject, + globalThis: *jsc.JSGlobalObject, comptime cache_field: []const u8, ) !*@This() { var request = try globalThis.allocator().create(@This()); @@ -556,7 +558,7 @@ pub const GetNameInfoRequest = struct { request.* = .{ .resolver_for_caching = resolver, .hash = hash, - .head = .{ .poll_ref = poll_ref, .globalThis = globalThis, .promise = JSC.JSPromise.Strong.init(globalThis), .allocated = false, .name = name }, + .head = .{ .poll_ref = poll_ref, .globalThis = globalThis, .promise = jsc.JSPromise.Strong.init(globalThis), .allocated = false, .name = name }, }; request.tail = &request.head; if (cache == .new) { @@ -627,7 +629,7 @@ pub const GetAddrInfoRequest = struct { const log = Output.scoped(.GetAddrInfoRequest, false); backend: Backend = undefined, - resolver_for_caching: ?*DNSResolver = null, + resolver_for_caching: ?*Resolver = null, hash: u64 = 0, cache: CacheConfig = CacheConfig{}, head: DNSLookup, @@ -635,11 +637,11 @@ pub const GetAddrInfoRequest = struct { task: bun.ThreadPool.Task = undefined, pub fn init( - cache: DNSResolver.CacheHit, + cache: Resolver.CacheHit, backend: Backend, - resolver: ?*DNSResolver, + resolver: ?*Resolver, query: GetAddrInfo, - globalThis: *JSC.JSGlobalObject, + globalThis: *jsc.JSGlobalObject, comptime cache_field: []const u8, ) !*GetAddrInfoRequest { log("init", .{}); @@ -655,7 +657,7 @@ pub const GetAddrInfoRequest = struct { .resolver = resolver, .globalThis = globalThis, .poll_ref = poll_ref, - .promise = JSC.JSPromise.Strong.init(globalThis), + .promise = jsc.JSPromise.Strong.init(globalThis), .allocated = false, }, }; @@ -673,7 +675,7 @@ pub const GetAddrInfoRequest = struct { return request; } - pub const Task = bun.JSC.WorkTask(GetAddrInfoRequest); + pub const Task = bun.jsc.WorkTask(GetAddrInfoRequest); pub const CacheConfig = packed struct(u16) { pending_cache: bool = false, @@ -786,13 +788,13 @@ pub const GetAddrInfoRequest = struct { file_poll: ?*bun.Async.FilePoll = null, machport: bun.mach_port = 0, - extern fn getaddrinfo_send_reply(bun.mach_port, *const bun.api.DNS.LibInfo.GetaddrinfoAsyncHandleReply) bool; + extern fn getaddrinfo_send_reply(bun.mach_port, *const dns.LibInfo.GetaddrinfoAsyncHandleReply) bool; pub fn onMachportChange(this: *GetAddrInfoRequest) void { if (comptime !Environment.isMac) unreachable; - bun.JSC.markBinding(@src()); + bun.jsc.markBinding(@src()); - if (!getaddrinfo_send_reply(this.backend.libinfo.machport, bun.api.DNS.LibInfo.getaddrinfo_async_handle_reply().?)) { + if (!getaddrinfo_send_reply(this.backend.libinfo.machport, dns.LibInfo.getaddrinfo_async_handle_reply().?)) { log("onMachportChange: getaddrinfo_send_reply failed", .{}); getAddrInfoAsyncCallback(-1, null, this); } @@ -807,7 +809,7 @@ pub const GetAddrInfoRequest = struct { task.onFinish(); } - pub fn then(this: *GetAddrInfoRequest, _: *JSC.JSGlobalObject) void { + pub fn then(this: *GetAddrInfoRequest, _: *jsc.JSGlobalObject) void { log("then", .{}); switch (this.backend.libc) { .success => |result| { @@ -882,15 +884,15 @@ pub const GetAddrInfoRequest = struct { pub const CAresReverse = struct { const log = Output.scoped(.CAresReverse, false); - resolver: ?*DNSResolver, - globalThis: *JSC.JSGlobalObject, - promise: JSC.JSPromise.Strong, + resolver: ?*Resolver, + globalThis: *jsc.JSGlobalObject, + promise: jsc.JSPromise.Strong, poll_ref: Async.KeepAlive, allocated: bool = false, next: ?*@This() = null, name: []const u8, - pub fn init(resolver: ?*DNSResolver, globalThis: *JSC.JSGlobalObject, allocator: std.mem.Allocator, name: []const u8) !*@This() { + pub fn init(resolver: ?*Resolver, globalThis: *jsc.JSGlobalObject, allocator: std.mem.Allocator, name: []const u8) !*@This() { if (resolver) |resolver_| { resolver_.ref(); } @@ -901,7 +903,7 @@ pub const CAresReverse = struct { this.* = .{ .resolver = resolver, .globalThis = globalThis, - .promise = JSC.JSPromise.Strong.init(globalThis), + .promise = jsc.JSPromise.Strong.init(globalThis), .poll_ref = poll_ref, .allocated = true, .name = name, @@ -926,7 +928,7 @@ pub const CAresReverse = struct { return; } - pub fn onComplete(this: *@This(), result: JSC.JSValue) void { + pub fn onComplete(this: *@This(), result: jsc.JSValue) void { var promise = this.promise; const globalThis = this.globalThis; this.promise = .{}; @@ -955,9 +957,9 @@ pub fn CAresLookup(comptime cares_type: type, comptime type_name: []const u8) ty return struct { const log = Output.scoped(.CAresLookup, true); - resolver: ?*DNSResolver, - globalThis: *JSC.JSGlobalObject, - promise: JSC.JSPromise.Strong, + resolver: ?*Resolver, + globalThis: *jsc.JSGlobalObject, + promise: jsc.JSPromise.Strong, poll_ref: Async.KeepAlive, allocated: bool = false, next: ?*@This() = null, @@ -968,7 +970,7 @@ pub fn CAresLookup(comptime cares_type: type, comptime type_name: []const u8) ty return bun.new(@This(), data); } - pub fn init(resolver: ?*DNSResolver, globalThis: *JSC.JSGlobalObject, _: std.mem.Allocator, name: []const u8) !*@This() { + pub fn init(resolver: ?*Resolver, globalThis: *jsc.JSGlobalObject, _: std.mem.Allocator, name: []const u8) !*@This() { if (resolver) |resolver_| { resolver_.ref(); } @@ -979,7 +981,7 @@ pub fn CAresLookup(comptime cares_type: type, comptime type_name: []const u8) ty .{ .resolver = resolver, .globalThis = globalThis, - .promise = JSC.JSPromise.Strong.init(globalThis), + .promise = jsc.JSPromise.Strong.init(globalThis), .poll_ref = poll_ref, .allocated = true, .name = name, @@ -1007,7 +1009,7 @@ pub fn CAresLookup(comptime cares_type: type, comptime type_name: []const u8) ty return; } - pub fn onComplete(this: *@This(), result: JSC.JSValue) void { + pub fn onComplete(this: *@This(), result: jsc.JSValue) void { var promise = this.promise; const globalThis = this.globalThis; this.promise = .{}; @@ -1036,14 +1038,14 @@ pub fn CAresLookup(comptime cares_type: type, comptime type_name: []const u8) ty pub const DNSLookup = struct { const log = Output.scoped(.DNSLookup, false); - resolver: ?*DNSResolver, - globalThis: *JSC.JSGlobalObject = undefined, - promise: JSC.JSPromise.Strong, + resolver: ?*Resolver, + globalThis: *jsc.JSGlobalObject = undefined, + promise: jsc.JSPromise.Strong, allocated: bool = false, next: ?*DNSLookup = null, poll_ref: Async.KeepAlive, - pub fn init(resolver: *DNSResolver, globalThis: *JSC.JSGlobalObject, allocator: std.mem.Allocator) !*DNSLookup { + pub fn init(resolver: *Resolver, globalThis: *jsc.JSGlobalObject, allocator: std.mem.Allocator) !*DNSLookup { log("init", .{}); resolver.ref(); @@ -1055,7 +1057,7 @@ pub const DNSLookup = struct { .resolver = resolver, .globalThis = globalThis, .poll_ref = poll_ref, - .promise = JSC.JSPromise.Strong.init(globalThis), + .promise = jsc.JSPromise.Strong.init(globalThis), .allocated = true, }; return this; @@ -1100,7 +1102,7 @@ pub const DNSLookup = struct { this.onCompleteWithArray(array); } - pub fn onCompleteWithArray(this: *DNSLookup, result: JSC.JSValue) void { + pub fn onCompleteWithArray(this: *DNSLookup, result: jsc.JSValue) void { log("onCompleteWithArray", .{}); var promise = this.promise; @@ -1128,19 +1130,19 @@ pub const DNSLookup = struct { }; pub const GlobalData = struct { - resolver: DNSResolver, + resolver: Resolver, - pub fn init(allocator: std.mem.Allocator, vm: *JSC.VirtualMachine) *GlobalData { + pub fn init(allocator: std.mem.Allocator, vm: *jsc.VirtualMachine) *GlobalData { const global = allocator.create(GlobalData) catch bun.outOfMemory(); global.* = .{ - .resolver = DNSResolver.setup(allocator, vm), + .resolver = Resolver.setup(allocator, vm), }; return global; } }; -pub const InternalDNS = struct { +pub const internal = struct { const log = Output.scoped(.dns, true); var __max_dns_time_to_live_seconds: ?u32 = null; @@ -1213,7 +1215,7 @@ pub const InternalDNS = struct { file_poll: ?*bun.Async.FilePoll = null, machport: bun.mach_port = 0, - extern fn getaddrinfo_send_reply(bun.mach_port, *const bun.api.DNS.LibInfo.GetaddrinfoAsyncHandleReply) bool; + extern fn getaddrinfo_send_reply(bun.mach_port, *const dns.LibInfo.GetaddrinfoAsyncHandleReply) bool; pub fn onMachportChange(this: *Request) void { if (!getaddrinfo_send_reply(this.libinfo.machport, LibInfo.getaddrinfo_async_handle_reply().?)) { libinfoCallback(@intFromEnum(std.c.E.NOSYS), null, this); @@ -1579,7 +1581,7 @@ pub const InternalDNS = struct { } } - pub fn lookupLibinfo(req: *Request, loop: JSC.EventLoopHandle) bool { + pub fn lookupLibinfo(req: *Request, loop: jsc.EventLoopHandle) bool { const getaddrinfo_async_start_ = LibInfo.getaddrinfo_async_start() orelse return false; var machport: bun.mach_port = 0; @@ -1665,14 +1667,14 @@ pub const InternalDNS = struct { var dns_cache_errors: usize = 0; var getaddrinfo_calls: usize = 0; - pub fn getDNSCacheStats(globalObject: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!JSC.JSValue { - const object = JSC.JSValue.createEmptyObject(globalObject, 6); - object.put(globalObject, JSC.ZigString.static("cacheHitsCompleted"), JSC.JSValue.jsNumber(@atomicLoad(usize, &dns_cache_hits_completed, .monotonic))); - object.put(globalObject, JSC.ZigString.static("cacheHitsInflight"), JSC.JSValue.jsNumber(@atomicLoad(usize, &dns_cache_hits_inflight, .monotonic))); - object.put(globalObject, JSC.ZigString.static("cacheMisses"), JSC.JSValue.jsNumber(@atomicLoad(usize, &dns_cache_misses, .monotonic))); - object.put(globalObject, JSC.ZigString.static("size"), JSC.JSValue.jsNumber(@atomicLoad(usize, &dns_cache_size, .monotonic))); - object.put(globalObject, JSC.ZigString.static("errors"), JSC.JSValue.jsNumber(@atomicLoad(usize, &dns_cache_errors, .monotonic))); - object.put(globalObject, JSC.ZigString.static("totalCount"), JSC.JSValue.jsNumber(@atomicLoad(usize, &getaddrinfo_calls, .monotonic))); + pub fn getDNSCacheStats(globalObject: *jsc.JSGlobalObject, _: *jsc.CallFrame) bun.JSError!jsc.JSValue { + const object = jsc.JSValue.createEmptyObject(globalObject, 6); + object.put(globalObject, jsc.ZigString.static("cacheHitsCompleted"), jsc.JSValue.jsNumber(@atomicLoad(usize, &dns_cache_hits_completed, .monotonic))); + object.put(globalObject, jsc.ZigString.static("cacheHitsInflight"), jsc.JSValue.jsNumber(@atomicLoad(usize, &dns_cache_hits_inflight, .monotonic))); + object.put(globalObject, jsc.ZigString.static("cacheMisses"), jsc.JSValue.jsNumber(@atomicLoad(usize, &dns_cache_misses, .monotonic))); + object.put(globalObject, jsc.ZigString.static("size"), jsc.JSValue.jsNumber(@atomicLoad(usize, &dns_cache_size, .monotonic))); + object.put(globalObject, jsc.ZigString.static("errors"), jsc.JSValue.jsNumber(@atomicLoad(usize, &dns_cache_errors, .monotonic))); + object.put(globalObject, jsc.ZigString.static("totalCount"), jsc.JSValue.jsNumber(@atomicLoad(usize, &getaddrinfo_calls, .monotonic))); return object; } @@ -1732,11 +1734,11 @@ pub const InternalDNS = struct { log("getaddrinfo({s}) = cache miss (libc)", .{host orelse ""}); // schedule the request to be executed on the work pool - bun.JSC.WorkPool.go(bun.default_allocator, *Request, req, workPoolCallback) catch bun.outOfMemory(); + bun.jsc.WorkPool.go(bun.default_allocator, *Request, req, workPoolCallback) catch bun.outOfMemory(); return req; } - pub fn prefetchFromJS(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { + pub fn prefetchFromJS(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const arguments = callframe.arguments(); if (arguments.len < 1) { @@ -1745,7 +1747,7 @@ pub const InternalDNS = struct { const hostname_or_url = arguments[0]; - var hostname_slice = JSC.ZigString.Slice.empty; + var hostname_slice = jsc.ZigString.Slice.empty; defer hostname_slice.deinit(); if (hostname_or_url.isString()) { @@ -1765,7 +1767,7 @@ pub const InternalDNS = struct { } }; - prefetch(JSC.VirtualMachine.get().uwsLoop(), hostname_z, port); + prefetch(jsc.VirtualMachine.get().uwsLoop(), hostname_z, port); return .js_undefined; } @@ -1819,24 +1821,24 @@ pub const InternalDNS = struct { } }; -pub const InternalDNSRequest = InternalDNS.Request; +pub const InternalDNSRequest = internal.Request; comptime { - @export(&InternalDNS.us_getaddrinfo_set, .{ + @export(&internal.us_getaddrinfo_set, .{ .name = "Bun__addrinfo_set", }); - @export(&InternalDNS.us_getaddrinfo, .{ + @export(&internal.us_getaddrinfo, .{ .name = "Bun__addrinfo_get", }); - @export(&InternalDNS.freeaddrinfo, .{ + @export(&internal.freeaddrinfo, .{ .name = "Bun__addrinfo_freeRequest", }); - @export(&InternalDNS.getRequestResult, .{ + @export(&internal.getRequestResult, .{ .name = "Bun__addrinfo_getRequestResult", }); } -pub const DNSResolver = struct { +pub const Resolver = struct { const RefCount = bun.ptr.RefCount(@This(), "ref_count", deinit, .{}); pub const ref = RefCount.ref; pub const deref = RefCount.deref; @@ -1845,7 +1847,7 @@ pub const DNSResolver = struct { ref_count: RefCount, channel: ?*c_ares.Channel = null, - vm: *JSC.VirtualMachine, + vm: *jsc.VirtualMachine, polls: PollsMap, options: c_ares.ChannelOptions = .{}, @@ -1871,7 +1873,7 @@ pub const DNSResolver = struct { pending_addr_cache_cares: AddrPendingCache, pending_nameinfo_cache_cares: NameInfoPendingCache, - pub const js = JSC.Codegen.JSDNSResolver; + pub const js = jsc.Codegen.JSDNSResolver; pub const toJS = js.toJS; pub const fromJS = js.fromJS; pub const fromJSDirect = js.fromJSDirect; @@ -1887,7 +1889,7 @@ pub const DNSResolver = struct { pub const new = bun.TrivialNew(@This()); pub const destroy = bun.TrivialDeinit(@This()); - parent: *DNSResolver, + parent: *Resolver, socket: c_ares.ares_socket_t, poll: bun.windows.libuv.uv_poll_t, @@ -1896,11 +1898,11 @@ pub const DNSResolver = struct { } }; - pub fn setup(allocator: std.mem.Allocator, vm: *JSC.VirtualMachine) DNSResolver { + pub fn setup(allocator: std.mem.Allocator, vm: *jsc.VirtualMachine) Resolver { return .{ .ref_count = .init(), .vm = vm, - .polls = DNSResolver.PollsMap.init(allocator), + .polls = Resolver.PollsMap.init(allocator), .pending_host_cache_cares = PendingCache.empty, .pending_host_cache_native = PendingCache.empty, .pending_srv_cache_cares = SrvPendingCache.empty, @@ -1920,16 +1922,16 @@ pub const DNSResolver = struct { }; } - pub fn init(allocator: std.mem.Allocator, vm: *JSC.VirtualMachine) *DNSResolver { + pub fn init(allocator: std.mem.Allocator, vm: *jsc.VirtualMachine) *Resolver { log("init", .{}); - return bun.new(DNSResolver, .setup(allocator, vm)); + return bun.new(Resolver, .setup(allocator, vm)); } - pub fn finalize(this: *DNSResolver) void { + pub fn finalize(this: *Resolver) void { this.deref(); } - fn deinit(this: *DNSResolver) void { + fn deinit(this: *Resolver) void { if (this.channel) |channel| { channel.deinit(); } @@ -1953,8 +1955,8 @@ pub const DNSResolver = struct { .{ "6", .ipv6first }, }); - pub fn toJS(this: Order, globalThis: *JSC.JSGlobalObject) bun.JSError!JSC.JSValue { - return JSC.ZigString.init(@tagName(this)).toJS(globalThis); + pub fn toJS(this: Order, globalThis: *jsc.JSGlobalObject) bun.JSError!jsc.JSValue { + return jsc.ZigString.init(@tagName(this)).toJS(globalThis); } pub fn fromString(order: []const u8) ?Order { @@ -1985,7 +1987,7 @@ pub const DNSResolver = struct { const AddrPendingCache = bun.HiveArray(GetHostByAddrInfoRequest.PendingCacheKey, 32); const NameInfoPendingCache = bun.HiveArray(GetNameInfoRequest.PendingCacheKey, 32); - pub fn checkTimeouts(this: *DNSResolver, now: *const timespec, vm: *JSC.VirtualMachine) EventLoopTimer.Arm { + pub fn checkTimeouts(this: *Resolver, now: *const timespec, vm: *jsc.VirtualMachine) EventLoopTimer.Arm { defer { vm.timer.incrementTimerRef(-1); this.deref(); @@ -2005,8 +2007,8 @@ pub const DNSResolver = struct { return .disarm; } - fn anyRequestsPending(this: *DNSResolver) bool { - inline for (@typeInfo(DNSResolver).@"struct".fields) |field| { + fn anyRequestsPending(this: *Resolver) bool { + inline for (@typeInfo(Resolver).@"struct".fields) |field| { if (comptime std.mem.startsWith(u8, field.name, "pending_")) { const set = &@field(this, field.name).used; if (set.findFirstSet() != null) { @@ -2017,11 +2019,11 @@ pub const DNSResolver = struct { return false; } - fn requestSent(this: *DNSResolver, _: *JSC.VirtualMachine) void { + fn requestSent(this: *Resolver, _: *jsc.VirtualMachine) void { _ = this.addTimer(null); } - fn requestCompleted(this: *DNSResolver) void { + fn requestCompleted(this: *Resolver) void { if (this.anyRequestsPending()) { _ = this.addTimer(null); } else { @@ -2029,7 +2031,7 @@ pub const DNSResolver = struct { } } - fn addTimer(this: *DNSResolver, now: ?*const timespec) bool { + fn addTimer(this: *Resolver, now: ?*const timespec) bool { if (this.event_loop_timer.state == .ACTIVE) { return false; } @@ -2041,7 +2043,7 @@ pub const DNSResolver = struct { return true; } - fn removeTimer(this: *DNSResolver) void { + fn removeTimer(this: *Resolver) void { if (this.event_loop_timer.state != .ACTIVE) { return; } @@ -2055,7 +2057,7 @@ pub const DNSResolver = struct { this.vm.timer.remove(&this.event_loop_timer); } - fn getKey(this: *DNSResolver, index: u8, comptime cache_name: []const u8, comptime request_type: type) request_type.PendingCacheKey { + fn getKey(this: *Resolver, index: u8, comptime cache_name: []const u8, comptime request_type: type) request_type.PendingCacheKey { var cache = &@field(this, cache_name); bun.assert(cache.used.isSet(index)); const entry = cache.buffer[index]; @@ -2068,7 +2070,7 @@ pub const DNSResolver = struct { return entry; } - pub fn drainPendingCares(this: *DNSResolver, index: u8, err: ?c_ares.Error, timeout: i32, comptime request_type: type, comptime cares_type: type, comptime lookup_name: []const u8, result: ?*cares_type) void { + pub fn drainPendingCares(this: *Resolver, index: u8, err: ?c_ares.Error, timeout: i32, comptime request_type: type, comptime cares_type: type, comptime lookup_name: []const u8, result: ?*cares_type) void { const cache_name = comptime std.fmt.comptimePrint("pending_{s}_cache_cares", .{lookup_name}); this.ref(); @@ -2114,7 +2116,7 @@ pub const DNSResolver = struct { } } - pub fn drainPendingHostCares(this: *DNSResolver, index: u8, err: ?c_ares.Error, timeout: i32, result: ?*c_ares.AddrInfo) void { + pub fn drainPendingHostCares(this: *Resolver, index: u8, err: ?c_ares.Error, timeout: i32, result: ?*c_ares.AddrInfo) void { const key = this.getKey(index, "pending_host_cache_cares", GetAddrInfoRequest); this.ref(); @@ -2159,7 +2161,7 @@ pub const DNSResolver = struct { } } - pub fn drainPendingHostNative(this: *DNSResolver, index: u8, globalObject: *JSC.JSGlobalObject, err: i32, result: GetAddrInfo.Result.Any) void { + pub fn drainPendingHostNative(this: *Resolver, index: u8, globalObject: *jsc.JSGlobalObject, err: i32, result: GetAddrInfo.Result.Any) void { log("drainPendingHostNative", .{}); const key = this.getKey(index, "pending_host_cache_native", GetAddrInfoRequest); @@ -2207,7 +2209,7 @@ pub const DNSResolver = struct { } } - pub fn drainPendingAddrCares(this: *DNSResolver, index: u8, err: ?c_ares.Error, timeout: i32, result: ?*c_ares.struct_hostent) void { + pub fn drainPendingAddrCares(this: *Resolver, index: u8, err: ?c_ares.Error, timeout: i32, result: ?*c_ares.struct_hostent) void { const key = this.getKey(index, "pending_addr_cache_cares", GetHostByAddrInfoRequest); this.ref(); @@ -2253,7 +2255,7 @@ pub const DNSResolver = struct { } } - pub fn drainPendingNameInfoCares(this: *DNSResolver, index: u8, err: ?c_ares.Error, timeout: i32, result: ?c_ares.struct_nameinfo) void { + pub fn drainPendingNameInfoCares(this: *Resolver, index: u8, err: ?c_ares.Error, timeout: i32, result: ?c_ares.struct_nameinfo) void { const key = this.getKey(index, "pending_nameinfo_cache_cares", GetNameInfoRequest); this.ref(); @@ -2312,7 +2314,7 @@ pub const DNSResolver = struct { } pub fn getOrPutIntoResolvePendingCache( - this: *DNSResolver, + this: *Resolver, comptime request_type: type, key: request_type.PendingCacheKey, comptime field: []const u8, @@ -2341,9 +2343,9 @@ pub const DNSResolver = struct { } pub fn getOrPutIntoPendingCache( - this: *DNSResolver, + this: *Resolver, key: GetAddrInfoRequest.PendingCacheKey, - comptime field: std.meta.FieldEnum(DNSResolver), + comptime field: std.meta.FieldEnum(Resolver), ) CacheHit { var cache: *PendingCache = &@field(this, @tagName(field)); var inflight_iter = cache.used.iterator( @@ -2372,9 +2374,9 @@ pub const DNSResolver = struct { err: c_ares.Error, result: *c_ares.Channel, }; - pub fn getChannel(this: *DNSResolver) ChannelResult { + pub fn getChannel(this: *Resolver) ChannelResult { if (this.channel == null) { - if (c_ares.Channel.init(DNSResolver, this, this.options)) |err| { + if (c_ares.Channel.init(Resolver, this, this.options)) |err| { return .{ .err = err }; } } @@ -2382,17 +2384,17 @@ pub const DNSResolver = struct { return .{ .result = this.channel.? }; } - fn getChannelFromVM(globalThis: *JSC.JSGlobalObject) bun.JSError!*c_ares.Channel { + fn getChannelFromVM(globalThis: *jsc.JSGlobalObject) bun.JSError!*c_ares.Channel { var vm = globalThis.bunVM(); var resolver = vm.rareData().globalDNSResolver(vm); return resolver.getChannelOrError(globalThis); } - pub fn getChannelOrError(this: *DNSResolver, globalThis: *JSC.JSGlobalObject) bun.JSError!*c_ares.Channel { + pub fn getChannelOrError(this: *Resolver, globalThis: *jsc.JSGlobalObject) bun.JSError!*c_ares.Channel { switch (this.getChannel()) { .result => |result| return result, .err => |err| { - const system_error = JSC.SystemError{ + const system_error = jsc.SystemError{ .errno = -1, .code = bun.String.static(err.code()), .message = bun.String.static(err.label()), @@ -2431,7 +2433,7 @@ pub const DNSResolver = struct { } pub fn onDNSPoll( - this: *DNSResolver, + this: *Resolver, poll: *Async.FilePoll, ) void { var vm = this.vm; @@ -2454,7 +2456,7 @@ pub const DNSResolver = struct { } pub fn onDNSSocketState( - this: *DNSResolver, + this: *Resolver, fd: c_ares.ares_socket_t, readable: bool, writable: bool, @@ -2508,7 +2510,7 @@ pub const DNSResolver = struct { const poll_entry = this.polls.getOrPut(fd) catch unreachable; if (!poll_entry.found_existing) { - poll_entry.value_ptr.* = Async.FilePoll.init(vm, .fromNative(fd), .{}, DNSResolver, this); + poll_entry.value_ptr.* = Async.FilePoll.init(vm, .fromNative(fd), .{}, Resolver, this); } var poll = poll_entry.value_ptr.*; @@ -2522,7 +2524,7 @@ pub const DNSResolver = struct { } const DNSQuery = struct { - name: JSC.ZigString.Slice, + name: jsc.ZigString.Slice, record_type: RecordType, ttl: i32 = 0, @@ -2569,13 +2571,13 @@ pub const DNSResolver = struct { }); }; - pub fn globalResolve(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { + pub fn globalResolve(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const vm = globalThis.bunVM(); const resolver = vm.rareData().globalDNSResolver(vm); return resolver.resolve(globalThis, callframe); } - pub fn resolve(this: *DNSResolver, globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { + pub fn resolve(this: *Resolver, globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const arguments = callframe.arguments_old(3); if (arguments.len < 1) { return globalThis.throwNotEnoughArguments("resolve", 3, arguments.len); @@ -2594,7 +2596,7 @@ pub const DNSResolver = struct { break :brk RecordType.default; } - break :brk RecordType.map.getWithEql(record_type_str.getZigString(globalThis), JSC.ZigString.eqlComptime) orelse { + break :brk RecordType.map.getWithEql(record_type_str.getZigString(globalThis), jsc.ZigString.eqlComptime) orelse { return globalThis.throwInvalidArgumentPropertyValue("record", "one of: A, AAAA, ANY, CAA, CNAME, MX, NS, PTR, SOA, SRV, TXT", record_type_value); }; }; @@ -2649,13 +2651,13 @@ pub const DNSResolver = struct { } } - pub fn globalReverse(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { + pub fn globalReverse(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const vm = globalThis.bunVM(); const resolver = vm.rareData().globalDNSResolver(vm); return resolver.reverse(globalThis, callframe); } - pub fn reverse(this: *DNSResolver, globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { + pub fn reverse(this: *Resolver, globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const arguments = callframe.arguments_old(2); if (arguments.len < 1) { return globalThis.throwNotEnoughArguments("reverse", 1, arguments.len); @@ -2712,7 +2714,7 @@ pub const DNSResolver = struct { return promise; } - pub fn globalLookup(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { + pub fn globalLookup(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const arguments = callframe.arguments_old(2); if (arguments.len < 1) { return globalThis.throwNotEnoughArguments("lookup", 2, arguments.len); @@ -2764,7 +2766,7 @@ pub const DNSResolver = struct { return resolver.doLookup(name.slice(), port, options, globalThis); } - pub fn doLookup(this: *DNSResolver, name: []const u8, port: u16, options: GetAddrInfo.Options, globalThis: *JSC.JSGlobalObject) bun.JSError!JSC.JSValue { + pub fn doLookup(this: *Resolver, name: []const u8, port: u16, options: GetAddrInfo.Options, globalThis: *jsc.JSGlobalObject) bun.JSError!jsc.JSValue { var opts = options; var backend = opts.backend; const normalized = normalizeDNSName(name, &backend); @@ -2787,13 +2789,13 @@ pub const DNSResolver = struct { }; } - pub fn globalResolveSrv(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { + pub fn globalResolveSrv(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const vm = globalThis.bunVM(); const resolver = vm.rareData().globalDNSResolver(vm); return resolver.resolveSrv(globalThis, callframe); } - pub fn resolveSrv(this: *DNSResolver, globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { + pub fn resolveSrv(this: *Resolver, globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const arguments = callframe.arguments_old(2); if (arguments.len < 1) { return globalThis.throwNotEnoughArguments("resolveSrv", 1, arguments.len); @@ -2814,13 +2816,13 @@ pub const DNSResolver = struct { return this.doResolveCAres(c_ares.struct_ares_srv_reply, "srv", name.slice(), globalThis); } - pub fn globalResolveSoa(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { + pub fn globalResolveSoa(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const vm = globalThis.bunVM(); const resolver = vm.rareData().globalDNSResolver(vm); return resolver.resolveSoa(globalThis, callframe); } - pub fn resolveSoa(this: *DNSResolver, globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { + pub fn resolveSoa(this: *Resolver, globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const arguments = callframe.arguments_old(2); if (arguments.len < 1) { return globalThis.throwNotEnoughArguments("resolveSoa", 1, arguments.len); @@ -2837,13 +2839,13 @@ pub const DNSResolver = struct { return this.doResolveCAres(c_ares.struct_ares_soa_reply, "soa", name.slice(), globalThis); } - pub fn globalResolveCaa(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { + pub fn globalResolveCaa(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const vm = globalThis.bunVM(); const resolver = vm.rareData().globalDNSResolver(vm); return resolver.resolveCaa(globalThis, callframe); } - pub fn resolveCaa(this: *DNSResolver, globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { + pub fn resolveCaa(this: *Resolver, globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const arguments = callframe.arguments_old(2); if (arguments.len < 1) { return globalThis.throwNotEnoughArguments("resolveCaa", 1, arguments.len); @@ -2864,13 +2866,13 @@ pub const DNSResolver = struct { return this.doResolveCAres(c_ares.struct_ares_caa_reply, "caa", name.slice(), globalThis); } - pub fn globalResolveNs(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { + pub fn globalResolveNs(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const vm = globalThis.bunVM(); const resolver = vm.rareData().globalDNSResolver(vm); return resolver.resolveNs(globalThis, callframe); } - pub fn resolveNs(this: *DNSResolver, globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { + pub fn resolveNs(this: *Resolver, globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const arguments = callframe.arguments_old(2); if (arguments.len < 1) { return globalThis.throwNotEnoughArguments("resolveNs", 1, arguments.len); @@ -2888,13 +2890,13 @@ pub const DNSResolver = struct { return this.doResolveCAres(c_ares.struct_hostent, "ns", name.slice(), globalThis); } - pub fn globalResolvePtr(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { + pub fn globalResolvePtr(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const vm = globalThis.bunVM(); const resolver = vm.rareData().globalDNSResolver(vm); return resolver.resolvePtr(globalThis, callframe); } - pub fn resolvePtr(this: *DNSResolver, globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { + pub fn resolvePtr(this: *Resolver, globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const arguments = callframe.arguments_old(2); if (arguments.len < 1) { return globalThis.throwNotEnoughArguments("resolvePtr", 1, arguments.len); @@ -2915,13 +2917,13 @@ pub const DNSResolver = struct { return this.doResolveCAres(c_ares.struct_hostent, "ptr", name.slice(), globalThis); } - pub fn globalResolveCname(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { + pub fn globalResolveCname(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const vm = globalThis.bunVM(); const resolver = vm.rareData().globalDNSResolver(vm); return resolver.resolveCname(globalThis, callframe); } - pub fn resolveCname(this: *DNSResolver, globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { + pub fn resolveCname(this: *Resolver, globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const arguments = callframe.arguments_old(2); if (arguments.len < 1) { return globalThis.throwNotEnoughArguments("resolveCname", 1, arguments.len); @@ -2942,13 +2944,13 @@ pub const DNSResolver = struct { return this.doResolveCAres(c_ares.struct_hostent, "cname", name.slice(), globalThis); } - pub fn globalResolveMx(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { + pub fn globalResolveMx(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const vm = globalThis.bunVM(); const resolver = vm.rareData().globalDNSResolver(vm); return resolver.resolveMx(globalThis, callframe); } - pub fn resolveMx(this: *DNSResolver, globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { + pub fn resolveMx(this: *Resolver, globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const arguments = callframe.arguments_old(2); if (arguments.len < 1) { return globalThis.throwNotEnoughArguments("resolveMx", 1, arguments.len); @@ -2969,13 +2971,13 @@ pub const DNSResolver = struct { return this.doResolveCAres(c_ares.struct_ares_mx_reply, "mx", name.slice(), globalThis); } - pub fn globalResolveNaptr(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { + pub fn globalResolveNaptr(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const vm = globalThis.bunVM(); const resolver = vm.rareData().globalDNSResolver(vm); return resolver.resolveNaptr(globalThis, callframe); } - pub fn resolveNaptr(this: *DNSResolver, globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { + pub fn resolveNaptr(this: *Resolver, globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const arguments = callframe.arguments_old(2); if (arguments.len < 1) { return globalThis.throwNotEnoughArguments("resolveNaptr", 1, arguments.len); @@ -2996,13 +2998,13 @@ pub const DNSResolver = struct { return this.doResolveCAres(c_ares.struct_ares_naptr_reply, "naptr", name.slice(), globalThis); } - pub fn globalResolveTxt(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { + pub fn globalResolveTxt(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const vm = globalThis.bunVM(); const resolver = vm.rareData().globalDNSResolver(vm); return resolver.resolveTxt(globalThis, callframe); } - pub fn resolveTxt(this: *DNSResolver, globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { + pub fn resolveTxt(this: *Resolver, globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const arguments = callframe.arguments_old(1); if (arguments.len < 1) { return globalThis.throwNotEnoughArguments("resolveTxt", 1, arguments.len); @@ -3023,13 +3025,13 @@ pub const DNSResolver = struct { return this.doResolveCAres(c_ares.struct_ares_txt_reply, "txt", name.slice(), globalThis); } - pub fn globalResolveAny(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { + pub fn globalResolveAny(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const vm = globalThis.bunVM(); const resolver = vm.rareData().globalDNSResolver(vm); return resolver.resolveAny(globalThis, callframe); } - pub fn resolveAny(this: *DNSResolver, globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { + pub fn resolveAny(this: *Resolver, globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const arguments = callframe.arguments_old(1); if (arguments.len < 1) { return globalThis.throwNotEnoughArguments("resolveAny", 1, arguments.len); @@ -3050,7 +3052,7 @@ pub const DNSResolver = struct { return this.doResolveCAres(c_ares.struct_any_reply, "any", name.slice(), globalThis); } - pub fn doResolveCAres(this: *DNSResolver, comptime cares_type: type, comptime type_name: []const u8, name: []const u8, globalThis: *JSC.JSGlobalObject) bun.JSError!JSC.JSValue { + pub fn doResolveCAres(this: *Resolver, comptime cares_type: type, comptime type_name: []const u8, name: []const u8, globalThis: *jsc.JSGlobalObject) bun.JSError!jsc.JSValue { var channel: *c_ares.Channel = switch (this.getChannel()) { .result => |res| res, .err => |err| { @@ -3091,14 +3093,14 @@ pub const DNSResolver = struct { this.requestSent(globalThis.bunVM()); return promise; } - pub fn c_aresLookupWithNormalizedName(this: *DNSResolver, query: GetAddrInfo, globalThis: *JSC.JSGlobalObject) bun.JSError!JSC.JSValue { + pub fn c_aresLookupWithNormalizedName(this: *Resolver, query: GetAddrInfo, globalThis: *jsc.JSGlobalObject) bun.JSError!jsc.JSValue { var channel: *c_ares.Channel = switch (this.getChannel()) { .result => |res| res, .err => |err| { const syscall = bun.String.createAtomASCII(query.name); defer syscall.deref(); - const system_error = JSC.SystemError{ + const system_error = jsc.SystemError{ .errno = -1, .code = bun.String.static(err.code()), .message = bun.String.static(err.label()), @@ -3142,7 +3144,7 @@ pub const DNSResolver = struct { return promise; } - fn getChannelServers(channel: *c_ares.Channel, globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { + fn getChannelServers(channel: *c_ares.Channel, globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { _ = callframe; var servers: ?*c_ares.struct_ares_addr_port_node = null; const r = c_ares.ares_get_servers_ports(channel, &servers); @@ -3152,7 +3154,7 @@ pub const DNSResolver = struct { } defer c_ares.ares_free_data(servers); - const values = try JSC.JSValue.createEmptyArray(globalThis, 0); + const values = try jsc.JSValue.createEmptyArray(globalThis, 0); var i: u32 = 0; var cur = servers; @@ -3186,16 +3188,16 @@ pub const DNSResolver = struct { const size = bun.len(bun.cast([*:0]u8, buf[1..])) + 1; if (port == IANA_DNS_PORT) { - try values.putIndex(globalThis, i, JSC.ZigString.init(buf[1..size]).withEncoding().toJS(globalThis)); + try values.putIndex(globalThis, i, jsc.ZigString.init(buf[1..size]).withEncoding().toJS(globalThis)); } else { if (family == std.posix.AF.INET6) { buf[0] = '['; buf[size] = ']'; const port_slice = std.fmt.bufPrint(buf[size + 1 ..], ":{d}", .{port}) catch unreachable; - try values.putIndex(globalThis, i, JSC.ZigString.init(buf[0 .. size + 1 + port_slice.len]).withEncoding().toJS(globalThis)); + try values.putIndex(globalThis, i, jsc.ZigString.init(buf[0 .. size + 1 + port_slice.len]).withEncoding().toJS(globalThis)); } else { const port_slice = std.fmt.bufPrint(buf[size..], ":{d}", .{port}) catch unreachable; - try values.putIndex(globalThis, i, JSC.ZigString.init(buf[1 .. size + port_slice.len]).withEncoding().toJS(globalThis)); + try values.putIndex(globalThis, i, jsc.ZigString.init(buf[1 .. size + port_slice.len]).withEncoding().toJS(globalThis)); } } } @@ -3203,19 +3205,19 @@ pub const DNSResolver = struct { return values; } - pub fn getGlobalServers(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { + pub fn getGlobalServers(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { return getChannelServers(try getChannelFromVM(globalThis), globalThis, callframe); } - pub fn getServers(this: *DNSResolver, globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { + pub fn getServers(this: *Resolver, globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { return getChannelServers(try this.getChannelOrError(globalThis), globalThis, callframe); } - pub fn setLocalAddress(this: *DNSResolver, globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { + pub fn setLocalAddress(this: *Resolver, globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { return setChannelLocalAddresses(try this.getChannelOrError(globalThis), globalThis, callframe); } - fn setChannelLocalAddresses(channel: *c_ares.Channel, globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { + fn setChannelLocalAddresses(channel: *c_ares.Channel, globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const arguments = callframe.arguments(); if (arguments.len == 0) { return globalThis.throwNotEnoughArguments("setLocalAddress", 1, 0); @@ -3240,7 +3242,7 @@ pub const DNSResolver = struct { } } - fn setChannelLocalAddress(channel: *c_ares.Channel, globalThis: *JSC.JSGlobalObject, value: JSC.JSValue) bun.JSError!c_int { + fn setChannelLocalAddress(channel: *c_ares.Channel, globalThis: *jsc.JSGlobalObject, value: jsc.JSValue) bun.JSError!c_int { const str = try value.toBunString(globalThis); defer str.deref(); @@ -3263,10 +3265,10 @@ pub const DNSResolver = struct { return c_ares.AF.INET6; } - return JSC.Error.INVALID_IP_ADDRESS.throw(globalThis, "Invalid IP address: \"{s}\"", .{slice}); + return jsc.Error.INVALID_IP_ADDRESS.throw(globalThis, "Invalid IP address: \"{s}\"", .{slice}); } - fn setChannelServers(channel: *c_ares.Channel, globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { + fn setChannelServers(channel: *c_ares.Channel, globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { // It's okay to call dns.setServers with active queries, but not dns.Resolver.setServers if (channel != try getChannelFromVM(globalThis) and c_ares.ares_queue_active_queries(channel) != 0) { return globalThis.ERR(.DNS_SET_SERVERS_FAILED, "Failed to set servers: there are pending queries", .{}).throw(); @@ -3335,7 +3337,7 @@ pub const DNSResolver = struct { }; if (c_ares.ares_inet_pton(af, addressBuffer.ptr, &entries[i].addr) != 1) { - return JSC.Error.INVALID_IP_ADDRESS.throw(globalThis, "Invalid IP address: \"{s}\"", .{addressSlice}); + return jsc.Error.INVALID_IP_ADDRESS.throw(globalThis, "Invalid IP address: \"{s}\"", .{addressSlice}); } if (i > 0) { @@ -3352,16 +3354,16 @@ pub const DNSResolver = struct { return .js_undefined; } - pub fn setGlobalServers(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { + pub fn setGlobalServers(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { return setChannelServers(try getChannelFromVM(globalThis), globalThis, callframe); } - pub fn setServers(this: *DNSResolver, globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { + pub fn setServers(this: *Resolver, globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { return setChannelServers(try this.getChannelOrError(globalThis), globalThis, callframe); } - pub fn newResolver(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { - const resolver = DNSResolver.init(globalThis.allocator(), globalThis.bunVM()); + pub fn newResolver(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { + const resolver = Resolver.init(globalThis.allocator(), globalThis.bunVM()); const options = callframe.argument(0); if (options.isObject()) { @@ -3377,7 +3379,7 @@ pub const DNSResolver = struct { return resolver.toJS(globalThis); } - pub fn cancel(this: *DNSResolver, globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { + pub fn cancel(this: *Resolver, globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { _ = callframe; const channel = try this.getChannelOrError(globalThis); c_ares.ares_cancel(channel); @@ -3387,7 +3389,7 @@ pub const DNSResolver = struct { // Resolves the given address and port into a host name and service using the operating system's underlying getnameinfo implementation. // If address is not a valid IP address, a TypeError will be thrown. The port will be coerced to a number. // If it is not a legal port, a TypeError will be thrown. - pub fn globalLookupService(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { + pub fn globalLookupService(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const arguments = callframe.arguments_old(2); if (arguments.len < 2) { return globalThis.throwNotEnoughArguments("lookupService", 2, arguments.len); @@ -3452,50 +3454,52 @@ pub const DNSResolver = struct { return promise; } - pub fn getRuntimeDefaultResultOrderOption(globalThis: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!JSC.JSValue { + pub fn getRuntimeDefaultResultOrderOption(globalThis: *jsc.JSGlobalObject, _: *jsc.CallFrame) bun.JSError!jsc.JSValue { return globalThis.bunVM().dns_result_order.toJS(globalThis); } comptime { - const js_resolve = JSC.toJSHostFn(globalResolve); + const js_resolve = jsc.toJSHostFn(globalResolve); @export(&js_resolve, .{ .name = "Bun__DNS__resolve" }); - const js_lookup = JSC.toJSHostFn(globalLookup); + const js_lookup = jsc.toJSHostFn(globalLookup); @export(&js_lookup, .{ .name = "Bun__DNS__lookup" }); - const js_resolveTxt = JSC.toJSHostFn(globalResolveTxt); + const js_resolveTxt = jsc.toJSHostFn(globalResolveTxt); @export(&js_resolveTxt, .{ .name = "Bun__DNS__resolveTxt" }); - const js_resolveSoa = JSC.toJSHostFn(globalResolveSoa); + const js_resolveSoa = jsc.toJSHostFn(globalResolveSoa); @export(&js_resolveSoa, .{ .name = "Bun__DNS__resolveSoa" }); - const js_resolveMx = JSC.toJSHostFn(globalResolveMx); + const js_resolveMx = jsc.toJSHostFn(globalResolveMx); @export(&js_resolveMx, .{ .name = "Bun__DNS__resolveMx" }); - const js_resolveNaptr = JSC.toJSHostFn(globalResolveNaptr); + const js_resolveNaptr = jsc.toJSHostFn(globalResolveNaptr); @export(&js_resolveNaptr, .{ .name = "Bun__DNS__resolveNaptr" }); - const js_resolveSrv = JSC.toJSHostFn(globalResolveSrv); + const js_resolveSrv = jsc.toJSHostFn(globalResolveSrv); @export(&js_resolveSrv, .{ .name = "Bun__DNS__resolveSrv" }); - const js_resolveCaa = JSC.toJSHostFn(globalResolveCaa); + const js_resolveCaa = jsc.toJSHostFn(globalResolveCaa); @export(&js_resolveCaa, .{ .name = "Bun__DNS__resolveCaa" }); - const js_resolveNs = JSC.toJSHostFn(globalResolveNs); + const js_resolveNs = jsc.toJSHostFn(globalResolveNs); @export(&js_resolveNs, .{ .name = "Bun__DNS__resolveNs" }); - const js_resolvePtr = JSC.toJSHostFn(globalResolvePtr); + const js_resolvePtr = jsc.toJSHostFn(globalResolvePtr); @export(&js_resolvePtr, .{ .name = "Bun__DNS__resolvePtr" }); - const js_resolveCname = JSC.toJSHostFn(globalResolveCname); + const js_resolveCname = jsc.toJSHostFn(globalResolveCname); @export(&js_resolveCname, .{ .name = "Bun__DNS__resolveCname" }); - const js_resolveAny = JSC.toJSHostFn(globalResolveAny); + const js_resolveAny = jsc.toJSHostFn(globalResolveAny); @export(&js_resolveAny, .{ .name = "Bun__DNS__resolveAny" }); - const js_getGlobalServers = JSC.toJSHostFn(getGlobalServers); + const js_getGlobalServers = jsc.toJSHostFn(getGlobalServers); @export(&js_getGlobalServers, .{ .name = "Bun__DNS__getServers" }); - const js_setGlobalServers = JSC.toJSHostFn(setGlobalServers); + const js_setGlobalServers = jsc.toJSHostFn(setGlobalServers); @export(&js_setGlobalServers, .{ .name = "Bun__DNS__setServers" }); - const js_reverse = JSC.toJSHostFn(globalReverse); + const js_reverse = jsc.toJSHostFn(globalReverse); @export(&js_reverse, .{ .name = "Bun__DNS__reverse" }); - const js_lookupService = JSC.toJSHostFn(globalLookupService); + const js_lookupService = jsc.toJSHostFn(globalLookupService); @export(&js_lookupService, .{ .name = "Bun__DNS__lookupService" }); - const js_prefetchFromJS = JSC.toJSHostFn(InternalDNS.prefetchFromJS); + const js_prefetchFromJS = jsc.toJSHostFn(internal.prefetchFromJS); @export(&js_prefetchFromJS, .{ .name = "Bun__DNS__prefetch" }); - const js_getDNSCacheStats = JSC.toJSHostFn(InternalDNS.getDNSCacheStats); + const js_getDNSCacheStats = jsc.toJSHostFn(internal.getDNSCacheStats); @export(&js_getDNSCacheStats, .{ .name = "Bun__DNS__getCacheStats" }); } }; +const string = []const u8; + const std = @import("std"); const Allocator = std.mem.Allocator; @@ -3506,13 +3510,12 @@ const Global = bun.Global; const Output = bun.Output; const c_ares = bun.c_ares; const default_allocator = bun.default_allocator; -const string = bun.string; const strings = bun.strings; const timespec = bun.timespec; const GetAddrInfo = bun.dns.GetAddrInfo; const libuv = bun.windows.libuv; const EventLoopTimer = bun.api.Timer.EventLoopTimer; -const JSC = bun.JSC; -const JSGlobalObject = JSC.JSGlobalObject; -const JSValue = JSC.JSValue; +const jsc = bun.jsc; +const JSGlobalObject = jsc.JSGlobalObject; +const JSValue = jsc.JSValue; diff --git a/src/bun.js/api/bun/h2_frame_parser.zig b/src/bun.js/api/bun/h2_frame_parser.zig index 28baf03f70..1be8c8afee 100644 --- a/src/bun.js/api/bun/h2_frame_parser.zig +++ b/src/bun.js/api/bun/h2_frame_parser.zig @@ -6,9 +6,9 @@ const BunSocket = union(enum) { tcp: *TCPSocket, tcp_writeonly: *TCPSocket, }; -extern fn JSC__JSGlobalObject__getHTTP2CommonString(globalObject: *JSC.JSGlobalObject, hpack_index: u32) JSC.JSValue; +extern fn JSC__JSGlobalObject__getHTTP2CommonString(globalObject: *jsc.JSGlobalObject, hpack_index: u32) jsc.JSValue; -pub fn getHTTP2CommonString(globalObject: *JSC.JSGlobalObject, hpack_index: u32) ?JSC.JSValue { +pub fn getHTTP2CommonString(globalObject: *jsc.JSGlobalObject, hpack_index: u32) ?jsc.JSValue { if (hpack_index == 255) return null; const value = JSC__JSGlobalObject__getHTTP2CommonString(globalObject, hpack_index); if (value.isEmptyOrUndefinedOrNull()) return null; @@ -195,18 +195,18 @@ const FullSettingsPayload = packed struct(u288) { _maxHeaderListSizeType: u16 = @intFromEnum(SettingsType.SETTINGS_MAX_HEADER_LIST_SIZE), maxHeaderListSize: u32 = 65535, pub const byteSize: usize = 36; - pub fn toJS(this: *FullSettingsPayload, globalObject: *JSC.JSGlobalObject) JSC.JSValue { + pub fn toJS(this: *FullSettingsPayload, globalObject: *jsc.JSGlobalObject) jsc.JSValue { var result = JSValue.createEmptyObject(globalObject, 8); - result.put(globalObject, JSC.ZigString.static("headerTableSize"), JSC.JSValue.jsNumber(this.headerTableSize)); - result.put(globalObject, JSC.ZigString.static("enablePush"), JSC.JSValue.jsBoolean(this.enablePush > 0)); - result.put(globalObject, JSC.ZigString.static("maxConcurrentStreams"), JSC.JSValue.jsNumber(this.maxConcurrentStreams)); - result.put(globalObject, JSC.ZigString.static("initialWindowSize"), JSC.JSValue.jsNumber(this.initialWindowSize)); - result.put(globalObject, JSC.ZigString.static("maxFrameSize"), JSC.JSValue.jsNumber(this.maxFrameSize)); - result.put(globalObject, JSC.ZigString.static("maxHeaderListSize"), JSC.JSValue.jsNumber(this.maxHeaderListSize)); - result.put(globalObject, JSC.ZigString.static("maxHeaderSize"), JSC.JSValue.jsNumber(this.maxHeaderListSize)); + result.put(globalObject, jsc.ZigString.static("headerTableSize"), jsc.JSValue.jsNumber(this.headerTableSize)); + result.put(globalObject, jsc.ZigString.static("enablePush"), jsc.JSValue.jsBoolean(this.enablePush > 0)); + result.put(globalObject, jsc.ZigString.static("maxConcurrentStreams"), jsc.JSValue.jsNumber(this.maxConcurrentStreams)); + result.put(globalObject, jsc.ZigString.static("initialWindowSize"), jsc.JSValue.jsNumber(this.initialWindowSize)); + result.put(globalObject, jsc.ZigString.static("maxFrameSize"), jsc.JSValue.jsNumber(this.maxFrameSize)); + result.put(globalObject, jsc.ZigString.static("maxHeaderListSize"), jsc.JSValue.jsNumber(this.maxHeaderListSize)); + result.put(globalObject, jsc.ZigString.static("maxHeaderSize"), jsc.JSValue.jsNumber(this.maxHeaderListSize)); // TODO: we dont support this setting yet see https://nodejs.org/api/http2.html#settings-object // we should also support customSettings - result.put(globalObject, JSC.ZigString.static("enableConnectProtocol"), JSC.JSValue.jsBoolean(false)); + result.put(globalObject, jsc.ZigString.static("enableConnectProtocol"), jsc.JSValue.jsBoolean(false)); return result; } @@ -284,8 +284,8 @@ const SingleValueHeaders = bun.ComptimeStringMap(void, .{ .{"x-content-type-options"}, }); -pub fn jsGetUnpackedSettings(globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { - JSC.markBinding(@src()); +pub fn jsGetUnpackedSettings(globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { + jsc.markBinding(@src()); var settings: FullSettingsPayload = .{}; const args_list = callframe.arguments_old(1); @@ -317,7 +317,7 @@ pub fn jsGetUnpackedSettings(globalObject: *JSC.JSGlobalObject, callframe: *JSC. } } -pub fn jsAssertSettings(globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { +pub fn jsAssertSettings(globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const args_list = callframe.arguments_old(1); if (args_list.len < 1) { return globalObject.throw("Expected settings to be a object", .{}); @@ -404,7 +404,7 @@ pub fn jsAssertSettings(globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallF return .js_undefined; } -pub fn jsGetPackedSettings(globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { +pub fn jsGetPackedSettings(globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { var settings: FullSettingsPayload = .{}; const args_list = callframe.arguments_old(1); @@ -503,28 +503,28 @@ pub fn jsGetPackedSettings(globalObject: *JSC.JSGlobalObject, callframe: *JSC.Ca } const Handlers = struct { - onError: JSC.JSValue = .zero, - onWrite: JSC.JSValue = .zero, - onStreamError: JSC.JSValue = .zero, - onStreamStart: JSC.JSValue = .zero, - onStreamHeaders: JSC.JSValue = .zero, - onStreamEnd: JSC.JSValue = .zero, - onStreamData: JSC.JSValue = .zero, - onRemoteSettings: JSC.JSValue = .zero, - onLocalSettings: JSC.JSValue = .zero, - onWantTrailers: JSC.JSValue = .zero, - onPing: JSC.JSValue = .zero, - onEnd: JSC.JSValue = .zero, - onGoAway: JSC.JSValue = .zero, - onAborted: JSC.JSValue = .zero, - onAltSvc: JSC.JSValue = .zero, - onOrigin: JSC.JSValue = .zero, - onFrameError: JSC.JSValue = .zero, // Added for frameError events + onError: jsc.JSValue = .zero, + onWrite: jsc.JSValue = .zero, + onStreamError: jsc.JSValue = .zero, + onStreamStart: jsc.JSValue = .zero, + onStreamHeaders: jsc.JSValue = .zero, + onStreamEnd: jsc.JSValue = .zero, + onStreamData: jsc.JSValue = .zero, + onRemoteSettings: jsc.JSValue = .zero, + onLocalSettings: jsc.JSValue = .zero, + onWantTrailers: jsc.JSValue = .zero, + onPing: jsc.JSValue = .zero, + onEnd: jsc.JSValue = .zero, + onGoAway: jsc.JSValue = .zero, + onAborted: jsc.JSValue = .zero, + onAltSvc: jsc.JSValue = .zero, + onOrigin: jsc.JSValue = .zero, + onFrameError: jsc.JSValue = .zero, // Added for frameError events binary_type: BinaryType = .Buffer, - vm: *JSC.VirtualMachine, - globalObject: *JSC.JSGlobalObject, - strong_ctx: JSC.Strong.Optional = .empty, + vm: *jsc.VirtualMachine, + globalObject: *jsc.JSGlobalObject, + strong_ctx: jsc.Strong.Optional = .empty, pub fn callEventHandler(this: *Handlers, comptime event: @Type(.enum_literal), thisValue: JSValue, data: []const JSValue) bool { const callback = @field(this, @tagName(event)); @@ -536,7 +536,7 @@ const Handlers = struct { return true; } - pub fn callWriteCallback(this: *Handlers, callback: JSC.JSValue, data: []const JSValue) bool { + pub fn callWriteCallback(this: *Handlers, callback: jsc.JSValue, data: []const JSValue) bool { if (!callback.isCallable()) return false; this.vm.eventLoop().runCallback(callback, this.globalObject, .js_undefined, data); return true; @@ -545,13 +545,13 @@ const Handlers = struct { pub fn callEventHandlerWithResult(this: *Handlers, comptime event: @Type(.enum_literal), thisValue: JSValue, data: []const JSValue) JSValue { const callback = @field(this, @tagName(event)); if (callback == .zero) { - return JSC.JSValue.zero; + return jsc.JSValue.zero; } return this.vm.eventLoop().runCallbackWithResult(callback, this.globalObject, thisValue, data); } - pub fn fromJS(globalObject: *JSC.JSGlobalObject, opts: JSC.JSValue) bun.JSError!Handlers { + pub fn fromJS(globalObject: *jsc.JSGlobalObject, opts: jsc.JSValue) bun.JSError!Handlers { var handlers = Handlers{ .vm = globalObject.bunVM(), .globalObject = globalObject, @@ -645,7 +645,7 @@ pub const H2FrameParserConstructor = H2FrameParser.js.getConstructor; pub const H2FrameParser = struct { pub const log = Output.scoped(.H2FrameParser, false); const Self = @This(); - pub const js = JSC.Codegen.JSH2FrameParser; + pub const js = jsc.Codegen.JSH2FrameParser; pub const toJS = js.toJS; pub const fromJS = js.fromJS; pub const fromJSDirect = js.fromJSDirect; @@ -664,8 +664,8 @@ pub const H2FrameParser = struct { const H2FrameParserHiveAllocator = bun.HiveArray(H2FrameParser, 256).Fallback; pub threadlocal var pool: if (ENABLE_ALLOCATOR_POOL) ?*H2FrameParserHiveAllocator else u0 = if (ENABLE_ALLOCATOR_POOL) null else 0; - strong_ctx: JSC.Strong.Optional = .empty, - globalThis: *JSC.JSGlobalObject, + strong_ctx: jsc.Strong.Optional = .empty, + globalThis: *jsc.JSGlobalObject, allocator: Allocator, handlers: Handlers, native_socket: BunSocket = .{ .none = {} }, @@ -757,7 +757,7 @@ pub const H2FrameParser = struct { HALF_CLOSED_REMOTE = 6, CLOSED = 7, } = .IDLE, - jsContext: JSC.Strong.Optional = .empty, + jsContext: jsc.Strong.Optional = .empty, waitForTrailers: bool = false, closeAfterDrain: bool = false, endAfterHeaders: bool = false, @@ -781,7 +781,7 @@ pub const H2FrameParser = struct { // when we have backpressure we queue the data e round robin the Streams dataFrameQueue: PendingQueue, const SignalRef = struct { - signal: *JSC.WebCore.AbortSignal, + signal: *jsc.WebCore.AbortSignal, parser: *H2FrameParser, stream_id: u32, @@ -878,7 +878,7 @@ pub const H2FrameParser = struct { len: u32 = 0, // actually payload size offset: u32 = 0, // offset into the buffer (if partial flush due to flow control) buffer: []u8 = "", // allocated buffer if len > 0 - callback: JSC.Strong.Optional = .empty, // JSCallback for done + callback: jsc.Strong.Optional = .empty, // JSCallback for done pub fn deinit(this: *PendingFrame, allocator: Allocator) void { if (this.buffer.len > 0) { @@ -939,7 +939,7 @@ pub const H2FrameParser = struct { } else { this.state = .HALF_CLOSED_LOCAL; } - client.dispatchWithExtra(.onStreamEnd, identifier, JSC.JSValue.jsNumber(@intFromEnum(this.state))); + client.dispatchWithExtra(.onStreamEnd, identifier, jsc.JSValue.jsNumber(@intFromEnum(this.state))); } } } @@ -1041,7 +1041,7 @@ pub const H2FrameParser = struct { return .no_action; } - pub fn queueFrame(this: *Stream, client: *H2FrameParser, bytes: []const u8, callback: JSC.JSValue, end_stream: bool) void { + pub fn queueFrame(this: *Stream, client: *H2FrameParser, bytes: []const u8, callback: jsc.JSValue, end_stream: bool) void { const globalThis = client.globalThis; if (this.dataFrameQueue.peekLast()) |last_frame| { @@ -1096,7 +1096,7 @@ pub const H2FrameParser = struct { .len = @intCast(bytes.len), // we need to clone this data to send it later .buffer = if (bytes.len == 0) "" else client.allocator.alloc(u8, MAX_PAYLOAD_SIZE_WITHOUT_FRAME) catch bun.outOfMemory(), - .callback = if (callback.isCallable()) JSC.Strong.Optional.create(callback, globalThis) else .empty, + .callback = if (callback.isCallable()) jsc.Strong.Optional.create(callback, globalThis) else .empty, }; if (bytes.len > 0) { @memcpy(frame.buffer[0..bytes.len], bytes); @@ -1135,17 +1135,17 @@ pub const H2FrameParser = struct { }; } - pub fn setContext(this: *Stream, value: JSValue, globalObject: *JSC.JSGlobalObject) void { + pub fn setContext(this: *Stream, value: JSValue, globalObject: *jsc.JSGlobalObject) void { var context = this.jsContext; defer context.deinit(); this.jsContext = .create(value, globalObject); } pub fn getIdentifier(this: *const Stream) JSValue { - return this.jsContext.get() orelse return JSC.JSValue.jsNumber(this.id); + return this.jsContext.get() orelse return jsc.JSValue.jsNumber(this.id); } - pub fn attachSignal(this: *Stream, parser: *H2FrameParser, signal: *JSC.WebCore.AbortSignal) void { + pub fn attachSignal(this: *Stream, parser: *H2FrameParser, signal: *jsc.WebCore.AbortSignal) void { // we need a stable pointer to know what signal points to what stream_id + parser var signal_ref = SignalRef.new(.{ .signal = signal, @@ -1192,7 +1192,7 @@ pub const H2FrameParser = struct { } // unsafe to ask GC to run if we are already inside GC if (!finalizing) { - JSC.VirtualMachine.get().eventLoop().processGCTimer(); + jsc.VirtualMachine.get().eventLoop().processGCTimer(); } } }; @@ -1280,7 +1280,7 @@ pub const H2FrameParser = struct { return true; } - pub fn abortStream(this: *H2FrameParser, stream: *Stream, abortReason: JSC.JSValue) void { + pub fn abortStream(this: *H2FrameParser, stream: *Stream, abortReason: jsc.JSValue) void { log("HTTP_FRAME_RST_STREAM id: {} code: CANCEL", .{stream.id}); abortReason.ensureStillAlive(); @@ -1305,7 +1305,7 @@ pub const H2FrameParser = struct { const identifier = stream.getIdentifier(); identifier.ensureStillAlive(); stream.freeResources(this, false); - this.dispatchWith2Extra(.onAborted, identifier, abortReason, JSC.JSValue.jsNumber(@intFromEnum(old_state))); + this.dispatchWith2Extra(.onAborted, identifier, abortReason, jsc.JSValue.jsNumber(@intFromEnum(old_state))); _ = this.write(&buffer); } @@ -1336,9 +1336,9 @@ pub const H2FrameParser = struct { identifier.ensureStillAlive(); stream.freeResources(this, false); if (rstCode == .NO_ERROR) { - this.dispatchWithExtra(.onStreamEnd, identifier, JSC.JSValue.jsNumber(@intFromEnum(stream.state))); + this.dispatchWithExtra(.onStreamEnd, identifier, jsc.JSValue.jsNumber(@intFromEnum(stream.state))); } else { - this.dispatchWithExtra(.onStreamError, identifier, JSC.JSValue.jsNumber(@intFromEnum(rstCode))); + this.dispatchWithExtra(.onStreamError, identifier, jsc.JSValue.jsNumber(@intFromEnum(rstCode))); } _ = this.write(&buffer); @@ -1375,9 +1375,9 @@ pub const H2FrameParser = struct { if (emitError) { if (rstCode != .NO_ERROR) { - this.dispatchWith2Extra(.onError, JSC.JSValue.jsNumber(@intFromEnum(rstCode)), JSC.JSValue.jsNumber(this.lastStreamID), chunk); + this.dispatchWith2Extra(.onError, jsc.JSValue.jsNumber(@intFromEnum(rstCode)), jsc.JSValue.jsNumber(this.lastStreamID), chunk); } - this.dispatchWithExtra(.onEnd, JSC.JSValue.jsNumber(this.lastStreamID), chunk); + this.dispatchWithExtra(.onEnd, jsc.JSValue.jsNumber(this.lastStreamID), chunk); } } @@ -1480,53 +1480,53 @@ pub const H2FrameParser = struct { _ = this.write(&buffer); } - pub fn dispatch(this: *H2FrameParser, comptime event: @Type(.enum_literal), value: JSC.JSValue) void { - JSC.markBinding(@src()); + pub fn dispatch(this: *H2FrameParser, comptime event: @Type(.enum_literal), value: jsc.JSValue) void { + jsc.markBinding(@src()); const ctx_value = this.strong_ctx.get() orelse return; value.ensureStillAlive(); - _ = this.handlers.callEventHandler(event, ctx_value, &[_]JSC.JSValue{ ctx_value, value }); + _ = this.handlers.callEventHandler(event, ctx_value, &[_]jsc.JSValue{ ctx_value, value }); } - pub fn call(this: *H2FrameParser, comptime event: @Type(.enum_literal), value: JSC.JSValue) JSValue { - JSC.markBinding(@src()); + pub fn call(this: *H2FrameParser, comptime event: @Type(.enum_literal), value: jsc.JSValue) JSValue { + jsc.markBinding(@src()); const ctx_value = this.strong_ctx.get() orelse return .zero; value.ensureStillAlive(); - return this.handlers.callEventHandlerWithResult(event, ctx_value, &[_]JSC.JSValue{ ctx_value, value }); + return this.handlers.callEventHandlerWithResult(event, ctx_value, &[_]jsc.JSValue{ ctx_value, value }); } - pub fn dispatchWriteCallback(this: *H2FrameParser, callback: JSC.JSValue) void { - JSC.markBinding(@src()); + pub fn dispatchWriteCallback(this: *H2FrameParser, callback: jsc.JSValue) void { + jsc.markBinding(@src()); - _ = this.handlers.callWriteCallback(callback, &[_]JSC.JSValue{}); + _ = this.handlers.callWriteCallback(callback, &[_]jsc.JSValue{}); } - pub fn dispatchWithExtra(this: *H2FrameParser, comptime event: @Type(.enum_literal), value: JSC.JSValue, extra: JSC.JSValue) void { - JSC.markBinding(@src()); + pub fn dispatchWithExtra(this: *H2FrameParser, comptime event: @Type(.enum_literal), value: jsc.JSValue, extra: jsc.JSValue) void { + jsc.markBinding(@src()); const ctx_value = this.strong_ctx.get() orelse return; value.ensureStillAlive(); extra.ensureStillAlive(); - _ = this.handlers.callEventHandler(event, ctx_value, &[_]JSC.JSValue{ ctx_value, value, extra }); + _ = this.handlers.callEventHandler(event, ctx_value, &[_]jsc.JSValue{ ctx_value, value, extra }); } - pub fn dispatchWith2Extra(this: *H2FrameParser, comptime event: @Type(.enum_literal), value: JSC.JSValue, extra: JSC.JSValue, extra2: JSC.JSValue) void { - JSC.markBinding(@src()); + pub fn dispatchWith2Extra(this: *H2FrameParser, comptime event: @Type(.enum_literal), value: jsc.JSValue, extra: jsc.JSValue, extra2: jsc.JSValue) void { + jsc.markBinding(@src()); const ctx_value = this.strong_ctx.get() orelse return; value.ensureStillAlive(); extra.ensureStillAlive(); extra2.ensureStillAlive(); - _ = this.handlers.callEventHandler(event, ctx_value, &[_]JSC.JSValue{ ctx_value, value, extra, extra2 }); + _ = this.handlers.callEventHandler(event, ctx_value, &[_]jsc.JSValue{ ctx_value, value, extra, extra2 }); } - pub fn dispatchWith3Extra(this: *H2FrameParser, comptime event: @Type(.enum_literal), value: JSC.JSValue, extra: JSC.JSValue, extra2: JSC.JSValue, extra3: JSC.JSValue) void { - JSC.markBinding(@src()); + pub fn dispatchWith3Extra(this: *H2FrameParser, comptime event: @Type(.enum_literal), value: jsc.JSValue, extra: jsc.JSValue, extra2: jsc.JSValue, extra3: jsc.JSValue) void { + jsc.markBinding(@src()); const ctx_value = this.strong_ctx.get() orelse return; value.ensureStillAlive(); extra.ensureStillAlive(); extra2.ensureStillAlive(); extra3.ensureStillAlive(); - _ = this.handlers.callEventHandler(event, ctx_value, &[_]JSC.JSValue{ ctx_value, value, extra, extra2, extra3 }); + _ = this.handlers.callEventHandler(event, ctx_value, &[_]jsc.JSValue{ ctx_value, value, extra, extra2, extra3 }); } fn cork(this: *H2FrameParser) void { if (CORKED_H2) |corked| { @@ -1772,7 +1772,7 @@ pub const H2FrameParser = struct { } pub fn write(this: *H2FrameParser, bytes: []const u8) bool { - JSC.markBinding(@src()); + jsc.markBinding(@src()); log("write {}", .{bytes.len}); if (comptime ENABLE_AUTO_CORK) { this.cork(); @@ -1872,7 +1872,7 @@ pub const H2FrameParser = struct { } const stream_id = stream.id; - const headers = try JSC.JSValue.createEmptyArray(globalObject, 0); + const headers = try jsc.JSValue.createEmptyArray(globalObject, 0); headers.ensureStillAlive(); var sensitiveHeaders: JSValue = .js_undefined; @@ -1905,7 +1905,7 @@ pub const H2FrameParser = struct { try headers.push(globalObject, try bun.String.createUTF8ForJS(globalObject, header.value)); if (header.never_index) { if (sensitiveHeaders.isUndefined()) { - sensitiveHeaders = try JSC.JSValue.createEmptyArray(globalObject, 0); + sensitiveHeaders = try jsc.JSValue.createEmptyArray(globalObject, 0); sensitiveHeaders.ensureStillAlive(); } try sensitiveHeaders.push(globalObject, js_header_name); @@ -1916,7 +1916,7 @@ pub const H2FrameParser = struct { if (header.never_index) { if (sensitiveHeaders.isUndefined()) { - sensitiveHeaders = try JSC.JSValue.createEmptyArray(globalObject, 0); + sensitiveHeaders = try jsc.JSValue.createEmptyArray(globalObject, 0); sensitiveHeaders.ensureStillAlive(); } try sensitiveHeaders.push(globalObject, js_header_name); @@ -1934,7 +1934,7 @@ pub const H2FrameParser = struct { } } - this.dispatchWith3Extra(.onStreamHeaders, stream.getIdentifier(), headers, sensitiveHeaders, JSC.JSValue.jsNumber(flags)); + this.dispatchWith3Extra(.onStreamHeaders, stream.getIdentifier(), headers, sensitiveHeaders, jsc.JSValue.jsNumber(flags)); // callbacks can change the Stream ptr in this case we always return the new one if (this.streams.getEntry(stream_id)) |entry| return entry.value_ptr; return null; @@ -2013,7 +2013,7 @@ pub const H2FrameParser = struct { } else { stream.state = .HALF_CLOSED_REMOTE; } - this.dispatchWithExtra(.onStreamEnd, identifier, JSC.JSValue.jsNumber(@intFromEnum(stream.state))); + this.dispatchWithExtra(.onStreamEnd, identifier, jsc.JSValue.jsNumber(@intFromEnum(stream.state))); } } @@ -2037,13 +2037,13 @@ pub const H2FrameParser = struct { const error_code = u32FromBytes(payload[4..8]); const chunk = this.handlers.binary_type.toJS(payload[8..], this.handlers.globalObject) catch .zero; // TODO: properly propagate exception upwards this.readBuffer.reset(); - this.dispatchWith2Extra(.onGoAway, JSC.JSValue.jsNumber(error_code), JSC.JSValue.jsNumber(this.lastStreamID), chunk); + this.dispatchWith2Extra(.onGoAway, jsc.JSValue.jsNumber(error_code), jsc.JSValue.jsNumber(this.lastStreamID), chunk); return content.end; } return data.len; } - fn stringOrEmptyToJS(this: *H2FrameParser, payload: []const u8) bun.JSError!JSC.JSValue { + fn stringOrEmptyToJS(this: *H2FrameParser, payload: []const u8) bun.JSError!jsc.JSValue { if (payload.len == 0) { return bun.String.empty.toJS(this.handlers.globalObject); } @@ -2085,7 +2085,7 @@ pub const H2FrameParser = struct { originValue.ensureStillAlive(); } else if (count == 1) { // need to create an array - const array = try JSC.JSValue.createEmptyArray(this.handlers.globalObject, 0); + const array = try jsc.JSValue.createEmptyArray(this.handlers.globalObject, 0); array.ensureStillAlive(); try array.push(this.handlers.globalObject, originValue); try array.push(this.handlers.globalObject, try this.stringOrEmptyToJS(origin_str)); @@ -2132,7 +2132,7 @@ pub const H2FrameParser = struct { return content.end; } - this.dispatchWith2Extra(.onAltSvc, try this.stringOrEmptyToJS(origin_and_value[0..origin_length]), try this.stringOrEmptyToJS(origin_and_value[origin_length..]), JSC.JSValue.jsNumber(frame.streamIdentifier)); + this.dispatchWith2Extra(.onAltSvc, try this.stringOrEmptyToJS(origin_and_value[0..origin_length]), try this.stringOrEmptyToJS(origin_and_value[origin_length..]), jsc.JSValue.jsNumber(frame.streamIdentifier)); return content.end; } return data.len; @@ -2164,9 +2164,9 @@ pub const H2FrameParser = struct { identifier.ensureStillAlive(); stream.freeResources(this, false); if (rst_code == @intFromEnum(ErrorCode.NO_ERROR)) { - this.dispatchWithExtra(.onStreamEnd, identifier, JSC.JSValue.jsNumber(@intFromEnum(stream.state))); + this.dispatchWithExtra(.onStreamEnd, identifier, jsc.JSValue.jsNumber(@intFromEnum(stream.state))); } else { - this.dispatchWithExtra(.onStreamError, identifier, JSC.JSValue.jsNumber(rst_code)); + this.dispatchWithExtra(.onStreamError, identifier, jsc.JSValue.jsNumber(rst_code)); } return content.end; } @@ -2195,7 +2195,7 @@ pub const H2FrameParser = struct { this.outStandingPings -|= 1; } const buffer = this.handlers.binary_type.toJS(payload, this.handlers.globalObject) catch .zero; // TODO: properly propagate exception upwards - this.dispatchWithExtra(.onPing, buffer, JSC.JSValue.jsBoolean(!isNotACK)); + this.dispatchWithExtra(.onPing, buffer, jsc.JSValue.jsBoolean(!isNotACK)); return content.end; } return data.len; @@ -2261,7 +2261,7 @@ pub const H2FrameParser = struct { } else { stream.state = .HALF_CLOSED_LOCAL; } - this.dispatchWithExtra(.onStreamEnd, identifier, JSC.JSValue.jsNumber(@intFromEnum(stream.state))); + this.dispatchWithExtra(.onStreamEnd, identifier, jsc.JSValue.jsNumber(@intFromEnum(stream.state))); } } @@ -2330,7 +2330,7 @@ pub const H2FrameParser = struct { stream.state = .HALF_CLOSED_REMOTE; } } - this.dispatchWithExtra(.onStreamEnd, identifier, JSC.JSValue.jsNumber(@intFromEnum(stream.state))); + this.dispatchWithExtra(.onStreamEnd, identifier, jsc.JSValue.jsNumber(@intFromEnum(stream.state))); } return content.end; } @@ -2447,7 +2447,7 @@ pub const H2FrameParser = struct { const callback = this.handlers.onStreamStart; if (callback != .zero) { // we assume that onStreamStart will never mutate the stream hash map - _ = callback.call(this.handlers.globalObject, ctx_value, &[_]JSC.JSValue{ ctx_value, JSC.JSValue.jsNumber(streamIdentifier) }) catch |err| + _ = callback.call(this.handlers.globalObject, ctx_value, &[_]jsc.JSValue{ ctx_value, jsc.JSValue.jsNumber(streamIdentifier) }) catch |err| this.handlers.globalObject.reportActiveExceptionAsUnhandled(err); } return entry.value_ptr; @@ -2584,21 +2584,21 @@ pub const H2FrameParser = struct { return DirectWriterStruct{ .writer = this }; } - pub fn setEncoding(this: *H2FrameParser, globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { - JSC.markBinding(@src()); + pub fn setEncoding(this: *H2FrameParser, globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { + jsc.markBinding(@src()); const args_list = callframe.arguments_old(1); if (args_list.len < 1) { return globalObject.throw("Expected encoding argument", .{}); } this.handlers.binary_type = BinaryType.fromJSValue(globalObject, args_list.ptr[0]) orelse { - const err = JSC.toInvalidArguments("Expected 'binaryType' to be 'arraybuffer', 'uint8array', 'buffer'", .{}, globalObject).asObjectRef(); + const err = jsc.toInvalidArguments("Expected 'binaryType' to be 'arraybuffer', 'uint8array', 'buffer'", .{}, globalObject).asObjectRef(); return globalObject.throwValue(err); }; return .js_undefined; } - pub fn loadSettingsFromJSValue(this: *H2FrameParser, globalObject: *JSC.JSGlobalObject, options: JSC.JSValue) bun.JSError!void { + pub fn loadSettingsFromJSValue(this: *H2FrameParser, globalObject: *jsc.JSGlobalObject, options: jsc.JSValue) bun.JSError!void { if (options.isEmptyOrUndefinedOrNull() or !options.isObject()) { return globalObject.throw("Expected settings to be a object", .{}); } @@ -2686,8 +2686,8 @@ pub const H2FrameParser = struct { return; } - pub fn updateSettings(this: *H2FrameParser, globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { - JSC.markBinding(@src()); + pub fn updateSettings(this: *H2FrameParser, globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { + jsc.markBinding(@src()); const args_list = callframe.arguments_old(1); if (args_list.len < 1) { return globalObject.throw("Expected settings argument", .{}); @@ -2700,8 +2700,8 @@ pub const H2FrameParser = struct { return JSValue.jsBoolean(this.setSettings(this.localSettings)); } - pub fn setLocalWindowSize(this: *H2FrameParser, globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { - JSC.markBinding(@src()); + pub fn setLocalWindowSize(this: *H2FrameParser, globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { + jsc.markBinding(@src()); const args_list = callframe.arguments_old(1); if (args_list.len < 1) { return globalObject.throwInvalidArguments("Expected windowSize argument", .{}); @@ -2728,24 +2728,24 @@ pub const H2FrameParser = struct { return .js_undefined; } - pub fn getCurrentState(this: *H2FrameParser, globalObject: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!JSValue { - JSC.markBinding(@src()); + pub fn getCurrentState(this: *H2FrameParser, globalObject: *jsc.JSGlobalObject, _: *jsc.CallFrame) bun.JSError!JSValue { + jsc.markBinding(@src()); var result = JSValue.createEmptyObject(globalObject, 9); - result.put(globalObject, JSC.ZigString.static("effectiveLocalWindowSize"), JSC.JSValue.jsNumber(this.windowSize)); - result.put(globalObject, JSC.ZigString.static("effectiveRecvDataLength"), JSC.JSValue.jsNumber(this.windowSize - this.usedWindowSize)); - result.put(globalObject, JSC.ZigString.static("nextStreamID"), JSC.JSValue.jsNumber(this.getNextStreamID())); - result.put(globalObject, JSC.ZigString.static("lastProcStreamID"), JSC.JSValue.jsNumber(this.lastStreamID)); + result.put(globalObject, jsc.ZigString.static("effectiveLocalWindowSize"), jsc.JSValue.jsNumber(this.windowSize)); + result.put(globalObject, jsc.ZigString.static("effectiveRecvDataLength"), jsc.JSValue.jsNumber(this.windowSize - this.usedWindowSize)); + result.put(globalObject, jsc.ZigString.static("nextStreamID"), jsc.JSValue.jsNumber(this.getNextStreamID())); + result.put(globalObject, jsc.ZigString.static("lastProcStreamID"), jsc.JSValue.jsNumber(this.lastStreamID)); const settings: FullSettingsPayload = this.remoteSettings orelse .{}; - result.put(globalObject, JSC.ZigString.static("remoteWindowSize"), JSC.JSValue.jsNumber(settings.initialWindowSize)); - result.put(globalObject, JSC.ZigString.static("localWindowSize"), JSC.JSValue.jsNumber(this.localSettings.initialWindowSize)); - result.put(globalObject, JSC.ZigString.static("deflateDynamicTableSize"), JSC.JSValue.jsNumber(this.localSettings.headerTableSize)); - result.put(globalObject, JSC.ZigString.static("inflateDynamicTableSize"), JSC.JSValue.jsNumber(this.localSettings.headerTableSize)); - result.put(globalObject, JSC.ZigString.static("outboundQueueSize"), JSC.JSValue.jsNumber(this.outboundQueueSize)); + result.put(globalObject, jsc.ZigString.static("remoteWindowSize"), jsc.JSValue.jsNumber(settings.initialWindowSize)); + result.put(globalObject, jsc.ZigString.static("localWindowSize"), jsc.JSValue.jsNumber(this.localSettings.initialWindowSize)); + result.put(globalObject, jsc.ZigString.static("deflateDynamicTableSize"), jsc.JSValue.jsNumber(this.localSettings.headerTableSize)); + result.put(globalObject, jsc.ZigString.static("inflateDynamicTableSize"), jsc.JSValue.jsNumber(this.localSettings.headerTableSize)); + result.put(globalObject, jsc.ZigString.static("outboundQueueSize"), jsc.JSValue.jsNumber(this.outboundQueueSize)); return result; } - pub fn goaway(this: *H2FrameParser, globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { - JSC.markBinding(@src()); + pub fn goaway(this: *H2FrameParser, globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { + jsc.markBinding(@src()); const args_list = callframe.arguments_old(3); if (args_list.len < 1) { return globalObject.throw("Expected errorCode argument", .{}); @@ -2790,8 +2790,8 @@ pub const H2FrameParser = struct { return .js_undefined; } - pub fn ping(this: *H2FrameParser, globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { - JSC.markBinding(@src()); + pub fn ping(this: *H2FrameParser, globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { + jsc.markBinding(@src()); const args_list = callframe.arguments_old(1); if (args_list.len < 1) { return globalObject.throw("Expected payload argument", .{}); @@ -2811,8 +2811,8 @@ pub const H2FrameParser = struct { return globalObject.throw("Expected payload to be a Buffer", .{}); } - pub fn origin(this: *H2FrameParser, globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { - JSC.markBinding(@src()); + pub fn origin(this: *H2FrameParser, globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { + jsc.markBinding(@src()); const origin_arg = callframe.argument(0); if (origin_arg.isEmptyOrUndefinedOrNull()) { // empty origin frame @@ -2898,8 +2898,8 @@ pub const H2FrameParser = struct { return .js_undefined; } - pub fn altsvc(this: *H2FrameParser, globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { - JSC.markBinding(@src()); + pub fn altsvc(this: *H2FrameParser, globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { + jsc.markBinding(@src()); var origin_slice: ?bun.String.Slice = null; var value_slice: ?bun.String.Slice = null; defer { @@ -2950,8 +2950,8 @@ pub const H2FrameParser = struct { return .js_undefined; } - pub fn getEndAfterHeaders(this: *H2FrameParser, globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { - JSC.markBinding(@src()); + pub fn getEndAfterHeaders(this: *H2FrameParser, globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { + jsc.markBinding(@src()); const args_list = callframe.arguments_old(1); if (args_list.len < 1) { return globalObject.throw("Expected stream argument", .{}); @@ -2971,11 +2971,11 @@ pub const H2FrameParser = struct { return globalObject.throw("Invalid stream id", .{}); }; - return JSC.JSValue.jsBoolean(stream.endAfterHeaders); + return jsc.JSValue.jsBoolean(stream.endAfterHeaders); } - pub fn isStreamAborted(this: *H2FrameParser, globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { - JSC.markBinding(@src()); + pub fn isStreamAborted(this: *H2FrameParser, globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { + jsc.markBinding(@src()); const args_list = callframe.arguments_old(1); if (args_list.len < 1) { return globalObject.throw("Expected stream argument", .{}); @@ -2996,13 +2996,13 @@ pub const H2FrameParser = struct { }; if (stream.signal) |signal_ref| { - return JSC.JSValue.jsBoolean(signal_ref.isAborted()); + return jsc.JSValue.jsBoolean(signal_ref.isAborted()); } // closed with cancel = aborted - return JSC.JSValue.jsBoolean(stream.state == .CLOSED and stream.rstCode == @intFromEnum(ErrorCode.CANCEL)); + return jsc.JSValue.jsBoolean(stream.state == .CLOSED and stream.rstCode == @intFromEnum(ErrorCode.CANCEL)); } - pub fn getStreamState(this: *H2FrameParser, globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { - JSC.markBinding(@src()); + pub fn getStreamState(this: *H2FrameParser, globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { + jsc.markBinding(@src()); const args_list = callframe.arguments_old(1); if (args_list.len < 1) { return globalObject.throw("Expected stream argument", .{}); @@ -3021,21 +3021,21 @@ pub const H2FrameParser = struct { var stream = this.streams.getPtr(stream_id) orelse { return globalObject.throw("Invalid stream id", .{}); }; - var state = JSC.JSValue.createEmptyObject(globalObject, 7); + var state = jsc.JSValue.createEmptyObject(globalObject, 7); - state.put(globalObject, JSC.ZigString.static("localWindowSize"), JSC.JSValue.jsNumber(stream.windowSize)); - state.put(globalObject, JSC.ZigString.static("state"), JSC.JSValue.jsNumber(@intFromEnum(stream.state))); - state.put(globalObject, JSC.ZigString.static("localClose"), JSC.JSValue.jsNumber(@as(i32, if (stream.canSendData()) 0 else 1))); - state.put(globalObject, JSC.ZigString.static("remoteClose"), JSC.JSValue.jsNumber(@as(i32, if (stream.canReceiveData()) 0 else 1))); + state.put(globalObject, jsc.ZigString.static("localWindowSize"), jsc.JSValue.jsNumber(stream.windowSize)); + state.put(globalObject, jsc.ZigString.static("state"), jsc.JSValue.jsNumber(@intFromEnum(stream.state))); + state.put(globalObject, jsc.ZigString.static("localClose"), jsc.JSValue.jsNumber(@as(i32, if (stream.canSendData()) 0 else 1))); + state.put(globalObject, jsc.ZigString.static("remoteClose"), jsc.JSValue.jsNumber(@as(i32, if (stream.canReceiveData()) 0 else 1))); // TODO: sumDependencyWeight - state.put(globalObject, JSC.ZigString.static("sumDependencyWeight"), JSC.JSValue.jsNumber(0)); - state.put(globalObject, JSC.ZigString.static("weight"), JSC.JSValue.jsNumber(stream.weight)); + state.put(globalObject, jsc.ZigString.static("sumDependencyWeight"), jsc.JSValue.jsNumber(0)); + state.put(globalObject, jsc.ZigString.static("weight"), jsc.JSValue.jsNumber(stream.weight)); return state; } - pub fn setStreamPriority(this: *H2FrameParser, globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { - JSC.markBinding(@src()); + pub fn setStreamPriority(this: *H2FrameParser, globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { + jsc.markBinding(@src()); const args_list = callframe.arguments_old(2); if (args_list.len < 2) { return globalObject.throw("Expected stream and options arguments", .{}); @@ -3057,7 +3057,7 @@ pub const H2FrameParser = struct { }; if (!stream.canSendData() and !stream.canReceiveData()) { - return JSC.JSValue.jsBoolean(false); + return jsc.JSValue.jsBoolean(false); } if (!options.isObject()) { @@ -3100,7 +3100,7 @@ pub const H2FrameParser = struct { } if (parent_id == stream.id) { this.sendGoAway(stream.id, ErrorCode.PROTOCOL_ERROR, "Stream with self dependency", this.lastStreamID, true); - return JSC.JSValue.jsBoolean(false); + return jsc.JSValue.jsBoolean(false); } stream.streamDependency = parent_id; @@ -3128,11 +3128,11 @@ pub const H2FrameParser = struct { _ = frame.write(@TypeOf(writer), writer); _ = priority.write(@TypeOf(writer), writer); } - return JSC.JSValue.jsBoolean(true); + return jsc.JSValue.jsBoolean(true); } - pub fn rstStream(this: *H2FrameParser, globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { + pub fn rstStream(this: *H2FrameParser, globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { log("rstStream", .{}); - JSC.markBinding(@src()); + jsc.markBinding(@src()); const args_list = callframe.arguments_old(2); if (args_list.len < 2) { return globalObject.throw("Expected stream and code arguments", .{}); @@ -3160,7 +3160,7 @@ pub const H2FrameParser = struct { this.endStream(stream, @enumFromInt(error_code)); - return JSC.JSValue.jsBoolean(true); + return jsc.JSValue.jsBoolean(true); } const MemoryWriter = struct { @@ -3182,12 +3182,12 @@ pub const H2FrameParser = struct { return (this.writeBuffer.len + this.queuedDataSize) / 1024 / 1024; } // get memory in bytes - pub fn getBufferSize(this: *H2FrameParser, _: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!JSValue { - JSC.markBinding(@src()); - return JSC.JSValue.jsNumber(this.writeBuffer.len + this.queuedDataSize); + pub fn getBufferSize(this: *H2FrameParser, _: *jsc.JSGlobalObject, _: *jsc.CallFrame) bun.JSError!JSValue { + jsc.markBinding(@src()); + return jsc.JSValue.jsNumber(this.writeBuffer.len + this.queuedDataSize); } - fn sendData(this: *H2FrameParser, stream: *Stream, payload: []const u8, close: bool, callback: JSC.JSValue) void { + fn sendData(this: *H2FrameParser, stream: *Stream, payload: []const u8, close: bool, callback: jsc.JSValue) void { log("HTTP_FRAME_DATA {s} sendData({}, {}, {})", .{ if (this.isServer) "server" else "client", stream.id, payload.len, close }); const writer = this.toWriter(); @@ -3210,7 +3210,7 @@ pub const H2FrameParser = struct { } else { stream.state = .HALF_CLOSED_LOCAL; } - this.dispatchWithExtra(.onStreamEnd, identifier, JSC.JSValue.jsNumber(@intFromEnum(stream.state))); + this.dispatchWithExtra(.onStreamEnd, identifier, jsc.JSValue.jsNumber(@intFromEnum(stream.state))); } } } @@ -3282,8 +3282,8 @@ pub const H2FrameParser = struct { } } } - pub fn noTrailers(this: *H2FrameParser, globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { - JSC.markBinding(@src()); + pub fn noTrailers(this: *H2FrameParser, globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { + jsc.markBinding(@src()); const args_list = callframe.arguments_old(1); if (args_list.len < 1) { return globalObject.throw("Expected stream, headers and sensitiveHeaders arguments", .{}); @@ -3315,7 +3315,7 @@ pub const H2FrameParser = struct { } else { stream.state = .HALF_CLOSED_LOCAL; } - this.dispatchWithExtra(.onStreamEnd, identifier, JSC.JSValue.jsNumber(@intFromEnum(stream.state))); + this.dispatchWithExtra(.onStreamEnd, identifier, jsc.JSValue.jsNumber(@intFromEnum(stream.state))); return .js_undefined; } /// validate header name and convert to lowecase if needed @@ -3357,8 +3357,8 @@ pub const H2FrameParser = struct { return if (any) out[0..in.len] else in; } - pub fn sendTrailers(this: *H2FrameParser, globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { - JSC.markBinding(@src()); + pub fn sendTrailers(this: *H2FrameParser, globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { + jsc.markBinding(@src()); const args_list = callframe.arguments_old(3); if (args_list.len < 3) { return globalObject.throw("Expected stream, headers and sensitiveHeaders arguments", .{}); @@ -3396,7 +3396,7 @@ pub const H2FrameParser = struct { var name_buffer: [4096]u8 = undefined; @memset(&name_buffer, 0); - var iter = try JSC.JSPropertyIterator(.{ + var iter = try jsc.JSPropertyIterator(.{ .skip_empty_name = false, .include_value = true, }).init(globalObject, headers_obj); @@ -3468,10 +3468,10 @@ pub const H2FrameParser = struct { this.dispatchWith2Extra( .onFrameError, identifier, - JSC.JSValue.jsNumber(@intFromEnum(FrameType.HTTP_FRAME_HEADERS)), - JSC.JSValue.jsNumber(@intFromEnum(ErrorCode.FRAME_SIZE_ERROR)), + jsc.JSValue.jsNumber(@intFromEnum(FrameType.HTTP_FRAME_HEADERS)), + jsc.JSValue.jsNumber(@intFromEnum(ErrorCode.FRAME_SIZE_ERROR)), ); - this.dispatchWithExtra(.onStreamError, identifier, JSC.JSValue.jsNumber(stream.rstCode)); + this.dispatchWithExtra(.onStreamError, identifier, jsc.JSValue.jsNumber(stream.rstCode)); return .js_undefined; }; } @@ -3505,11 +3505,11 @@ pub const H2FrameParser = struct { this.dispatchWith2Extra( .onFrameError, identifier, - JSC.JSValue.jsNumber(@intFromEnum(FrameType.HTTP_FRAME_HEADERS)), - JSC.JSValue.jsNumber(@intFromEnum(ErrorCode.FRAME_SIZE_ERROR)), + jsc.JSValue.jsNumber(@intFromEnum(FrameType.HTTP_FRAME_HEADERS)), + jsc.JSValue.jsNumber(@intFromEnum(ErrorCode.FRAME_SIZE_ERROR)), ); - this.dispatchWithExtra(.onStreamError, identifier, JSC.JSValue.jsNumber(stream.rstCode)); + this.dispatchWithExtra(.onStreamError, identifier, jsc.JSValue.jsNumber(stream.rstCode)); return .js_undefined; }; @@ -3535,11 +3535,11 @@ pub const H2FrameParser = struct { } else { stream.state = .HALF_CLOSED_LOCAL; } - this.dispatchWithExtra(.onStreamEnd, identifier, JSC.JSValue.jsNumber(@intFromEnum(stream.state))); + this.dispatchWithExtra(.onStreamEnd, identifier, jsc.JSValue.jsNumber(@intFromEnum(stream.state))); return .js_undefined; } - pub fn writeStream(this: *H2FrameParser, globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { - JSC.markBinding(@src()); + pub fn writeStream(this: *H2FrameParser, globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { + jsc.markBinding(@src()); const args = callframe.argumentsUndef(5); const stream_arg, const data_arg, const encoding_arg, const close_arg, const callback_arg = args.ptr; @@ -3558,10 +3558,10 @@ pub const H2FrameParser = struct { }; if (!stream.canSendData()) { this.dispatchWriteCallback(callback_arg); - return JSC.JSValue.jsBoolean(false); + return jsc.JSValue.jsBoolean(false); } - const encoding: JSC.Node.Encoding = brk: { + const encoding: jsc.Node.Encoding = brk: { if (encoding_arg.isUndefined()) { break :brk .utf8; } @@ -3570,12 +3570,12 @@ pub const H2FrameParser = struct { return globalObject.throwInvalidArgumentTypeValue("write", "encoding", encoding_arg); } - break :brk try JSC.Node.Encoding.fromJS(encoding_arg, globalObject) orelse { + break :brk try jsc.Node.Encoding.fromJS(encoding_arg, globalObject) orelse { return globalObject.throwInvalidArgumentTypeValue("write", "encoding", encoding_arg); }; }; - var buffer: JSC.Node.StringOrBuffer = try JSC.Node.StringOrBuffer.fromJSWithEncoding( + var buffer: jsc.Node.StringOrBuffer = try jsc.Node.StringOrBuffer.fromJSWithEncoding( globalObject, bun.default_allocator, data_arg, @@ -3587,7 +3587,7 @@ pub const H2FrameParser = struct { this.sendData(stream, buffer.slice(), close, callback_arg); - return JSC.JSValue.jsBoolean(true); + return jsc.JSValue.jsBoolean(true); } fn getNextStreamID(this: *H2FrameParser) u32 { @@ -3610,8 +3610,8 @@ pub const H2FrameParser = struct { return stream_id; } - pub fn setNextStreamID(this: *H2FrameParser, _: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { - JSC.markBinding(@src()); + pub fn setNextStreamID(this: *H2FrameParser, _: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { + jsc.markBinding(@src()); const args_list = callframe.arguments(); bun.debugAssert(args_list.len >= 1); const stream_id_arg = args_list.ptr[0]; @@ -3636,26 +3636,26 @@ pub const H2FrameParser = struct { return .js_undefined; } - pub fn hasNativeRead(this: *H2FrameParser, _: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!JSValue { - return JSC.JSValue.jsBoolean(this.native_socket == .tcp or this.native_socket == .tls); + pub fn hasNativeRead(this: *H2FrameParser, _: *jsc.JSGlobalObject, _: *jsc.CallFrame) bun.JSError!JSValue { + return jsc.JSValue.jsBoolean(this.native_socket == .tcp or this.native_socket == .tls); } - pub fn getNextStream(this: *H2FrameParser, _: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!JSValue { - JSC.markBinding(@src()); + pub fn getNextStream(this: *H2FrameParser, _: *jsc.JSGlobalObject, _: *jsc.CallFrame) bun.JSError!JSValue { + jsc.markBinding(@src()); const id = this.getNextStreamID(); if (id > MAX_STREAM_ID) { - return JSC.JSValue.jsNumber(-1); + return jsc.JSValue.jsNumber(-1); } _ = this.handleReceivedStreamID(id) orelse { - return JSC.JSValue.jsNumber(-1); + return jsc.JSValue.jsNumber(-1); }; - return JSC.JSValue.jsNumber(id); + return jsc.JSValue.jsNumber(id); } - pub fn getStreamContext(this: *H2FrameParser, globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { - JSC.markBinding(@src()); + pub fn getStreamContext(this: *H2FrameParser, globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { + jsc.markBinding(@src()); const args_list = callframe.arguments_old(1); if (args_list.len < 1) { return globalObject.throw("Expected stream_id argument", .{}); @@ -3673,8 +3673,8 @@ pub const H2FrameParser = struct { return stream.jsContext.get() orelse .js_undefined; } - pub fn setStreamContext(this: *H2FrameParser, globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { - JSC.markBinding(@src()); + pub fn setStreamContext(this: *H2FrameParser, globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { + jsc.markBinding(@src()); const args_list = callframe.arguments_old(2); if (args_list.len < 2) { return globalObject.throw("Expected stream_id and context arguments", .{}); @@ -3696,8 +3696,8 @@ pub const H2FrameParser = struct { return .js_undefined; } - pub fn forEachStream(this: *H2FrameParser, globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { - JSC.markBinding(@src()); + pub fn forEachStream(this: *H2FrameParser, globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { + jsc.markBinding(@src()); const args = callframe.arguments(); if (args.len < 1 or !args[0].isCallable()) { return .js_undefined; @@ -3708,14 +3708,14 @@ pub const H2FrameParser = struct { var it = this.streams.valueIterator(); while (it.next()) |stream| { const value = stream.jsContext.get() orelse continue; - this.handlers.vm.eventLoop().runCallback(callback, globalObject, thisValue, &[_]JSC.JSValue{value}); + this.handlers.vm.eventLoop().runCallback(callback, globalObject, thisValue, &[_]jsc.JSValue{value}); count += 1; } return .js_undefined; } - pub fn emitAbortToAllStreams(this: *H2FrameParser, _: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!JSC.JSValue { - JSC.markBinding(@src()); + pub fn emitAbortToAllStreams(this: *H2FrameParser, _: *jsc.JSGlobalObject, _: *jsc.CallFrame) bun.JSError!jsc.JSValue { + jsc.markBinding(@src()); var it = StreamResumableIterator.init(this); while (it.next()) |stream| { @@ -3730,14 +3730,14 @@ pub const H2FrameParser = struct { const identifier = stream.getIdentifier(); identifier.ensureStillAlive(); stream.freeResources(this, false); - this.dispatchWith2Extra(.onAborted, identifier, .js_undefined, JSC.JSValue.jsNumber(@intFromEnum(old_state))); + this.dispatchWith2Extra(.onAborted, identifier, .js_undefined, jsc.JSValue.jsNumber(@intFromEnum(old_state))); } } return .js_undefined; } - pub fn emitErrorToAllStreams(this: *H2FrameParser, globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { - JSC.markBinding(@src()); + pub fn emitErrorToAllStreams(this: *H2FrameParser, globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { + jsc.markBinding(@src()); const args_list = callframe.arguments_old(1); if (args_list.len < 1) { @@ -3761,14 +3761,14 @@ pub const H2FrameParser = struct { return .js_undefined; } - pub fn flushFromJS(this: *H2FrameParser, _: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!JSValue { - JSC.markBinding(@src()); + pub fn flushFromJS(this: *H2FrameParser, _: *jsc.JSGlobalObject, _: *jsc.CallFrame) bun.JSError!JSValue { + jsc.markBinding(@src()); - return JSC.JSValue.jsNumber(this.flush()); + return jsc.JSValue.jsNumber(this.flush()); } - pub fn request(this: *H2FrameParser, globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { - JSC.markBinding(@src()); + pub fn request(this: *H2FrameParser, globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { + jsc.markBinding(@src()); log("request", .{}); const args_list = callframe.arguments_old(5); @@ -3797,11 +3797,11 @@ pub const H2FrameParser = struct { @memset(&name_buffer, 0); const stream_id: u32 = if (!stream_id_arg.isEmptyOrUndefinedOrNull() and stream_id_arg.isNumber()) stream_id_arg.to(u32) else this.getNextStreamID(); if (stream_id > MAX_STREAM_ID) { - return JSC.JSValue.jsNumber(-1); + return jsc.JSValue.jsNumber(-1); } // we iterate twice, because pseudo headers must be sent first, but can appear anywhere in the headers object - var iter = try JSC.JSPropertyIterator(.{ + var iter = try jsc.JSPropertyIterator(.{ .skip_empty_name = false, .include_value = true, }).init(globalObject, headers_obj); @@ -3825,7 +3825,7 @@ pub const H2FrameParser = struct { if (this.maxHeaderListPairs < header_count) { this.rejectedStreams += 1; const stream = this.handleReceivedStreamID(stream_id) orelse { - return JSC.JSValue.jsNumber(-1); + return jsc.JSValue.jsNumber(-1); }; if (!stream_ctx_arg.isEmptyOrUndefinedOrNull() and stream_ctx_arg.isObject()) { stream.setContext(stream_ctx_arg, globalObject); @@ -3835,8 +3835,8 @@ pub const H2FrameParser = struct { const identifier = stream.getIdentifier(); identifier.ensureStillAlive(); stream.freeResources(this, false); - this.dispatchWithExtra(.onStreamError, identifier, JSC.JSValue.jsNumber(stream.rstCode)); - return JSC.JSValue.jsNumber(stream_id); + this.dispatchWithExtra(.onStreamError, identifier, jsc.JSValue.jsNumber(stream.rstCode)); + return jsc.JSValue.jsNumber(stream_id); } const validated_name = toValidHeaderName(name, name_buffer[0..name.len]) catch { const exception = globalObject.toTypeError(.INVALID_HTTP_TOKEN, "The arguments Header name is invalid. Received \"{s}\"", .{name}); @@ -3909,14 +3909,14 @@ pub const H2FrameParser = struct { encoded_size += this.encode(buffer, encoded_size, validated_name, value, never_index) catch { const stream = this.handleReceivedStreamID(stream_id) orelse { - return JSC.JSValue.jsNumber(-1); + return jsc.JSValue.jsNumber(-1); }; if (!stream_ctx_arg.isEmptyOrUndefinedOrNull() and stream_ctx_arg.isObject()) { stream.setContext(stream_ctx_arg, globalObject); } stream.state = .CLOSED; stream.rstCode = @intFromEnum(ErrorCode.COMPRESSION_ERROR); - this.dispatchWithExtra(.onStreamError, stream.getIdentifier(), JSC.JSValue.jsNumber(stream.rstCode)); + this.dispatchWithExtra(.onStreamError, stream.getIdentifier(), jsc.JSValue.jsNumber(stream.rstCode)); return .js_undefined; }; } @@ -3943,21 +3943,21 @@ pub const H2FrameParser = struct { encoded_size += this.encode(buffer, encoded_size, validated_name, value, never_index) catch { const stream = this.handleReceivedStreamID(stream_id) orelse { - return JSC.JSValue.jsNumber(-1); + return jsc.JSValue.jsNumber(-1); }; stream.state = .CLOSED; if (!stream_ctx_arg.isEmptyOrUndefinedOrNull() and stream_ctx_arg.isObject()) { stream.setContext(stream_ctx_arg, globalObject); } stream.rstCode = @intFromEnum(ErrorCode.COMPRESSION_ERROR); - this.dispatchWithExtra(.onStreamError, stream.getIdentifier(), JSC.JSValue.jsNumber(stream.rstCode)); - return JSC.JSValue.jsNumber(stream_id); + this.dispatchWithExtra(.onStreamError, stream.getIdentifier(), jsc.JSValue.jsNumber(stream.rstCode)); + return jsc.JSValue.jsNumber(stream_id); }; } } } const stream = this.handleReceivedStreamID(stream_id) orelse { - return JSC.JSValue.jsNumber(-1); + return jsc.JSValue.jsNumber(-1); }; if (!stream_ctx_arg.isEmptyOrUndefinedOrNull() and stream_ctx_arg.isObject()) { stream.setContext(stream_ctx_arg, globalObject); @@ -3975,8 +3975,8 @@ pub const H2FrameParser = struct { if (!options.isObject()) { stream.state = .CLOSED; stream.rstCode = @intFromEnum(ErrorCode.INTERNAL_ERROR); - this.dispatchWithExtra(.onStreamError, stream.getIdentifier(), JSC.JSValue.jsNumber(stream.rstCode)); - return JSC.JSValue.jsNumber(stream_id); + this.dispatchWithExtra(.onStreamError, stream.getIdentifier(), jsc.JSValue.jsNumber(stream.rstCode)); + return jsc.JSValue.jsNumber(stream_id); } if (try options.get(globalObject, "paddingStrategy")) |padding_js| { @@ -4037,8 +4037,8 @@ pub const H2FrameParser = struct { if (parent <= 0 or parent > MAX_STREAM_ID) { stream.state = .CLOSED; stream.rstCode = @intFromEnum(ErrorCode.INTERNAL_ERROR); - this.dispatchWithExtra(.onStreamError, stream.getIdentifier(), JSC.JSValue.jsNumber(stream.rstCode)); - return JSC.JSValue.jsNumber(stream.id); + this.dispatchWithExtra(.onStreamError, stream.getIdentifier(), jsc.JSValue.jsNumber(stream.rstCode)); + return jsc.JSValue.jsNumber(stream.id); } stream.streamDependency = @intCast(parent); } else { @@ -4053,8 +4053,8 @@ pub const H2FrameParser = struct { if (weight < 1 or weight > std.math.maxInt(u8)) { stream.state = .CLOSED; stream.rstCode = @intFromEnum(ErrorCode.INTERNAL_ERROR); - this.dispatchWithExtra(.onStreamError, stream.getIdentifier(), JSC.JSValue.jsNumber(stream.rstCode)); - return JSC.JSValue.jsNumber(stream_id); + this.dispatchWithExtra(.onStreamError, stream.getIdentifier(), jsc.JSValue.jsNumber(stream.rstCode)); + return jsc.JSValue.jsNumber(stream_id); } stream.weight = @intCast(weight); } else { @@ -4064,19 +4064,19 @@ pub const H2FrameParser = struct { if (weight < 1 or weight > std.math.maxInt(u8)) { stream.state = .CLOSED; stream.rstCode = @intFromEnum(ErrorCode.INTERNAL_ERROR); - this.dispatchWithExtra(.onStreamError, stream.getIdentifier(), JSC.JSValue.jsNumber(stream.rstCode)); - return JSC.JSValue.jsNumber(stream_id); + this.dispatchWithExtra(.onStreamError, stream.getIdentifier(), jsc.JSValue.jsNumber(stream.rstCode)); + return jsc.JSValue.jsNumber(stream_id); } stream.weight = @intCast(weight); } if (try options.get(globalObject, "signal")) |signal_arg| { - if (signal_arg.as(JSC.WebCore.AbortSignal)) |signal_| { + if (signal_arg.as(jsc.WebCore.AbortSignal)) |signal_| { if (signal_.aborted()) { stream.state = .IDLE; this.abortStream(stream, Bun__wrapAbortError(globalObject, signal_.abortReason())); - return JSC.JSValue.jsNumber(stream_id); + return jsc.JSValue.jsNumber(stream_id); } stream.attachSignal(this, signal_); } else { @@ -4090,12 +4090,12 @@ pub const H2FrameParser = struct { stream.state = .CLOSED; stream.rstCode = @intFromEnum(ErrorCode.ENHANCE_YOUR_CALM); this.rejectedStreams += 1; - this.dispatchWithExtra(.onStreamError, stream.getIdentifier(), JSC.JSValue.jsNumber(stream.rstCode)); + this.dispatchWithExtra(.onStreamError, stream.getIdentifier(), jsc.JSValue.jsNumber(stream.rstCode)); if (this.rejectedStreams >= this.maxRejectedStreams) { const chunk = try this.handlers.binary_type.toJS("ENHANCE_YOUR_CALM", this.handlers.globalObject); - this.dispatchWith2Extra(.onError, JSC.JSValue.jsNumber(@intFromEnum(ErrorCode.ENHANCE_YOUR_CALM)), JSC.JSValue.jsNumber(this.lastStreamID), chunk); + this.dispatchWith2Extra(.onError, jsc.JSValue.jsNumber(@intFromEnum(ErrorCode.ENHANCE_YOUR_CALM)), jsc.JSValue.jsNumber(this.lastStreamID), chunk); } - return JSC.JSValue.jsNumber(stream_id); + return jsc.JSValue.jsNumber(stream_id); } var length: usize = encoded_size; if (has_priority) { @@ -4113,12 +4113,12 @@ pub const H2FrameParser = struct { this.dispatchWith2Extra( .onFrameError, stream.getIdentifier(), - JSC.JSValue.jsNumber(@intFromEnum(FrameType.HTTP_FRAME_HEADERS)), - JSC.JSValue.jsNumber(@intFromEnum(ErrorCode.FRAME_SIZE_ERROR)), + jsc.JSValue.jsNumber(@intFromEnum(FrameType.HTTP_FRAME_HEADERS)), + jsc.JSValue.jsNumber(@intFromEnum(ErrorCode.FRAME_SIZE_ERROR)), ); - this.dispatchWithExtra(.onStreamError, stream.getIdentifier(), JSC.JSValue.jsNumber(stream.rstCode)); - return JSC.JSValue.jsNumber(stream_id); + this.dispatchWithExtra(.onStreamError, stream.getIdentifier(), jsc.JSValue.jsNumber(stream.rstCode)); + return jsc.JSValue.jsNumber(stream_id); } const padding = stream.getPadding(encoded_size, buffer.len - 1); @@ -4161,7 +4161,7 @@ pub const H2FrameParser = struct { if (waitForTrailers) { this.dispatch(.onWantTrailers, stream.getIdentifier()); - return JSC.JSValue.jsNumber(stream_id); + return jsc.JSValue.jsNumber(stream_id); } } else { stream.waitForTrailers = waitForTrailers; @@ -4171,11 +4171,11 @@ pub const H2FrameParser = struct { // TODO: should we make use of this in the future? We validate it. } - return JSC.JSValue.jsNumber(stream_id); + return jsc.JSValue.jsNumber(stream_id); } - pub fn read(this: *H2FrameParser, globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { - JSC.markBinding(@src()); + pub fn read(this: *H2FrameParser, globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { + jsc.markBinding(@src()); const args_list = callframe.arguments_old(1); if (args_list.len < 1) { return globalObject.throw("Expected 1 argument", .{}); @@ -4216,8 +4216,8 @@ pub const H2FrameParser = struct { this.detachNativeSocket(); } - pub fn setNativeSocketFromJS(this: *H2FrameParser, globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { - JSC.markBinding(@src()); + pub fn setNativeSocketFromJS(this: *H2FrameParser, globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { + jsc.markBinding(@src()); const args_list = callframe.arguments_old(1); if (args_list.len < 1) { return globalObject.throw("Expected socket argument", .{}); @@ -4269,7 +4269,7 @@ pub const H2FrameParser = struct { } } - pub fn constructor(globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!*H2FrameParser { + pub fn constructor(globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!*H2FrameParser { const args_list = callframe.arguments_old(1); if (args_list.len < 1) { return globalObject.throw("Expected 1 argument", .{}); @@ -4283,7 +4283,7 @@ pub const H2FrameParser = struct { const context_obj = try options.get(globalObject, "context") orelse { return globalObject.throw("Expected \"context\" option", .{}); }; - var handler_js = JSC.JSValue.zero; + var handler_js = jsc.JSValue.zero; if (try options.get(globalObject, "handlers")) |handlers_| { handler_js = handlers_; } @@ -4417,8 +4417,8 @@ pub const H2FrameParser = struct { } return this; } - pub fn detachFromJS(this: *H2FrameParser, _: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!JSValue { - JSC.markBinding(@src()); + pub fn detachFromJS(this: *H2FrameParser, _: *jsc.JSGlobalObject, _: *jsc.CallFrame) bun.JSError!JSValue { + jsc.markBinding(@src()); var it = this.streams.valueIterator(); while (it.next()) |stream| { stream.freeResources(this, false); @@ -4474,24 +4474,24 @@ pub const H2FrameParser = struct { } }; -extern fn Bun__wrapAbortError(globalObject: *JSC.JSGlobalObject, cause: JSC.JSValue) JSC.JSValue; +extern fn Bun__wrapAbortError(globalObject: *jsc.JSGlobalObject, cause: jsc.JSValue) jsc.JSValue; const lshpack = @import("./lshpack.zig"); const std = @import("std"); const Allocator = std.mem.Allocator; -const TCPSocket = @import("./socket.zig").TCPSocket; -const TLSSocket = @import("./socket.zig").TLSSocket; - const bun = @import("bun"); const MutableString = bun.MutableString; const Output = bun.Output; const strings = bun.strings; -const JSC = bun.JSC; -const JSValue = JSC.JSValue; -const AutoFlusher = JSC.WebCore.AutoFlusher; -const BinaryType = JSC.ArrayBuffer.BinaryType; +const TCPSocket = bun.api.socket.TCPSocket; +const TLSSocket = bun.api.socket.TLSSocket; -const JSTCPSocket = JSC.Codegen.JSTCPSocket; -const JSTLSSocket = JSC.Codegen.JSTLSSocket; +const jsc = bun.jsc; +const JSValue = jsc.JSValue; +const AutoFlusher = jsc.WebCore.AutoFlusher; +const BinaryType = jsc.ArrayBuffer.BinaryType; + +const JSTCPSocket = jsc.Codegen.JSTCPSocket; +const JSTLSSocket = jsc.Codegen.JSTLSSocket; diff --git a/src/bun.js/api/bun/lshpack.zig b/src/bun.js/api/bun/lshpack.zig index 1879948c1a..c8fde68e5d 100644 --- a/src/bun.js/api/bun/lshpack.zig +++ b/src/bun.js/api/bun/lshpack.zig @@ -11,8 +11,6 @@ const lshpack_header = extern struct { pub const HPACK = extern struct { self: *anyopaque, - const mimalloc = @import("../../../allocators/mimalloc.zig"); - pub const DecodeResult = struct { name: []const u8, value: []const u8, @@ -65,3 +63,4 @@ extern fn lshpack_wrapper_decode(self: *HPACK, src: [*]const u8, src_len: usize, extern fn lshpack_wrapper_encode(self: *HPACK, name: [*]const u8, name_len: usize, value: [*]const u8, value_len: usize, never_index: c_int, buffer: [*]u8, buffer_len: usize, buffer_offset: usize) usize; const bun = @import("bun"); +const mimalloc = bun.mimalloc; diff --git a/src/bun.js/api/bun/process.zig b/src/bun.js/api/bun/process.zig index 55ba9eb2f6..47fec46409 100644 --- a/src/bun.js/api/bun/process.zig +++ b/src/bun.js/api/bun/process.zig @@ -145,7 +145,7 @@ pub const Process = struct { ref_count: RefCount, exit_handler: ProcessExitHandler = ProcessExitHandler{}, sync: bool = false, - event_loop: JSC.EventLoopHandle, + event_loop: jsc.EventLoopHandle, pub fn memoryCost(_: *const Process) usize { return @sizeOf(@This()); @@ -172,7 +172,7 @@ pub const Process = struct { .ref_count = .init(), .pid = posix.pid, .pidfd = posix.pidfd orelse 0, - .event_loop = JSC.EventLoopHandle.init(event_loop), + .event_loop = jsc.EventLoopHandle.init(event_loop), .sync = sync_, .poller = .{ .detached = {} }, .status = brk: { @@ -230,7 +230,7 @@ pub const Process = struct { } else if (comptime Environment.isWindows) {} } - pub fn onWaitPidFromWaiterThread(this: *Process, waitpid_result: *const JSC.Maybe(PosixSpawn.WaitPidResult), rusage: *const Rusage) void { + pub fn onWaitPidFromWaiterThread(this: *Process, waitpid_result: *const jsc.Maybe(PosixSpawn.WaitPidResult), rusage: *const Rusage) void { if (comptime Environment.isWindows) { @compileError("not implemented on this platform"); } @@ -250,7 +250,7 @@ pub const Process = struct { this.deref(); } - fn onWaitPid(this: *Process, waitpid_result: *const JSC.Maybe(PosixSpawn.WaitPidResult), rusage: *const Rusage) void { + fn onWaitPid(this: *Process, waitpid_result: *const jsc.Maybe(PosixSpawn.WaitPidResult), rusage: *const Rusage) void { if (comptime !Environment.isPosix) { @compileError("not implemented on this platform"); } @@ -289,7 +289,7 @@ pub const Process = struct { this.onExit(status, &rusage_result); } - pub fn watchOrReap(this: *Process) JSC.Maybe(bool) { + pub fn watchOrReap(this: *Process) jsc.Maybe(bool) { if (this.hasExited()) { this.onExit(this.status, &std.mem.zeroes(Rusage)); return .{ .result = true }; @@ -310,10 +310,10 @@ pub const Process = struct { } } - pub fn watch(this: *Process) JSC.Maybe(void) { + pub fn watch(this: *Process) jsc.Maybe(void) { if (comptime Environment.isWindows) { this.poller.uv.ref(); - return JSC.Maybe(void){ .result = {} }; + return jsc.Maybe(void){ .result = {} }; } if (WaiterThread.shouldUseWaiterThread()) { @@ -321,7 +321,7 @@ pub const Process = struct { this.poller.waiter_thread.ref(this.event_loop); this.ref(); WaiterThread.append(this); - return JSC.Maybe(void){ .result = {} }; + return jsc.Maybe(void){ .result = {} }; } const watchfd = if (comptime Environment.isLinux) this.pidfd else this.pid; @@ -340,7 +340,7 @@ pub const Process = struct { )) { .result => { this.ref(); - return JSC.Maybe(void){ .result = {} }; + return jsc.Maybe(void){ .result = {} }; }, .err => |err| { this.poller.fd.disableKeepingProcessAlive(this.event_loop); @@ -352,14 +352,14 @@ pub const Process = struct { unreachable; } - pub fn rewatchPosix(this: *Process) JSC.Maybe(void) { + pub fn rewatchPosix(this: *Process) jsc.Maybe(void) { if (WaiterThread.shouldUseWaiterThread()) { if (this.poller != .waiter_thread) this.poller = .{ .waiter_thread = .{} }; this.poller.waiter_thread.ref(this.event_loop); this.ref(); WaiterThread.append(this); - return JSC.Maybe(void){ .result = {} }; + return jsc.Maybe(void){ .result = {} }; } if (this.poller == .fd) { @@ -635,7 +635,7 @@ pub const PollerPosix = union(enum) { } } - pub fn enableKeepingEventLoopAlive(this: *Poller, event_loop: JSC.EventLoopHandle) void { + pub fn enableKeepingEventLoopAlive(this: *Poller, event_loop: jsc.EventLoopHandle) void { switch (this.*) { .fd => |poll| { poll.enableKeepingProcessAlive(event_loop); @@ -647,7 +647,7 @@ pub const PollerPosix = union(enum) { } } - pub fn disableKeepingEventLoopAlive(this: *PollerPosix, event_loop: JSC.EventLoopHandle) void { + pub fn disableKeepingEventLoopAlive(this: *PollerPosix, event_loop: jsc.EventLoopHandle) void { switch (this.*) { .fd => |poll| { poll.disableKeepingProcessAlive(event_loop); @@ -680,7 +680,7 @@ pub const PollerWindows = union(enum) { } } - pub fn enableKeepingEventLoopAlive(this: *PollerWindows, event_loop: JSC.EventLoopHandle) void { + pub fn enableKeepingEventLoopAlive(this: *PollerWindows, event_loop: jsc.EventLoopHandle) void { _ = event_loop; // autofix switch (this.*) { .uv => |*process| { @@ -690,7 +690,7 @@ pub const PollerWindows = union(enum) { } } - pub fn disableKeepingEventLoopAlive(this: *PollerWindows, event_loop: JSC.EventLoopHandle) void { + pub fn disableKeepingEventLoopAlive(this: *PollerWindows, event_loop: jsc.EventLoopHandle) void { _ = event_loop; // autofix // This is disabled on Windows @@ -749,7 +749,7 @@ const WaiterThreadPosix = struct { pub const ConcurrentQueue = bun.UnboundedQueue(TaskQueueEntry, .next); pub const ResultTask = struct { - result: JSC.Maybe(PosixSpawn.WaitPidResult), + result: jsc.Maybe(PosixSpawn.WaitPidResult), subprocess: *T, rusage: Rusage, @@ -771,9 +771,9 @@ const WaiterThreadPosix = struct { }; pub const ResultTaskMini = struct { - result: JSC.Maybe(PosixSpawn.WaitPidResult), + result: jsc.Maybe(PosixSpawn.WaitPidResult), subprocess: *T, - task: JSC.AnyTaskWithExtraContext = .{}, + task: jsc.AnyTaskWithExtraContext = .{}, pub const new = bun.TrivialNew(@This()); @@ -831,7 +831,7 @@ const WaiterThreadPosix = struct { switch (process.event_loop) { .js => |event_loop| { event_loop.enqueueTaskConcurrent( - JSC.ConcurrentTask.create(JSC.Task.init( + jsc.ConcurrentTask.create(jsc.Task.init( ResultTask.new( .{ .result = result, @@ -843,7 +843,7 @@ const WaiterThreadPosix = struct { ); }, .mini => |mini| { - const AnyTask = JSC.AnyTaskWithExtraContext.New(ResultTaskMini, void, ResultTaskMini.runFromMainThreadMini); + const AnyTask = jsc.AnyTaskWithExtraContext.New(ResultTaskMini, void, ResultTaskMini.runFromMainThreadMini); const out = ResultTaskMini.new( .{ .result = result, @@ -995,7 +995,7 @@ pub const PosixSpawnOptions = struct { ipc: void, pipe: bun.FileDescriptor, // TODO: remove this entry, it doesn't seem to be used - dup2: struct { out: bun.JSC.Subprocess.StdioKind, to: bun.JSC.Subprocess.StdioKind }, + dup2: struct { out: bun.jsc.Subprocess.StdioKind, to: bun.jsc.Subprocess.StdioKind }, }; pub fn deinit(_: *const PosixSpawnOptions) void { @@ -1057,7 +1057,7 @@ pub const WindowsSpawnOptions = struct { pub const WindowsOptions = struct { verbatim_arguments: bool = false, hide_window: bool = true, - loop: JSC.EventLoopHandle = undefined, + loop: jsc.EventLoopHandle = undefined, }; pub const Stdio = union(enum) { @@ -1067,7 +1067,7 @@ pub const WindowsSpawnOptions = struct { buffer: *bun.windows.libuv.Pipe, ipc: *bun.windows.libuv.Pipe, pipe: bun.FileDescriptor, - dup2: struct { out: bun.JSC.Subprocess.StdioKind, to: bun.JSC.Subprocess.StdioKind }, + dup2: struct { out: bun.jsc.Subprocess.StdioKind, to: bun.jsc.Subprocess.StdioKind }, pub fn deinit(this: *const Stdio) void { if (this.* == .buffer) { @@ -1130,7 +1130,7 @@ pub const PosixSpawnResult = struct { 0; } - pub fn pifdFromPid(this: *PosixSpawnResult) JSC.Maybe(PidFDType) { + pub fn pifdFromPid(this: *PosixSpawnResult) jsc.Maybe(PidFDType) { if (!Environment.isLinux or WaiterThread.shouldUseWaiterThread()) { return .{ .err = bun.sys.Error.fromCode(.NOSYS, .pidfd_open) }; } @@ -1204,7 +1204,7 @@ pub fn spawnProcess( options: *const SpawnOptions, argv: [*:null]?[*:0]const u8, envp: [*:null]?[*:0]const u8, -) !JSC.Maybe(SpawnProcessResult) { +) !jsc.Maybe(SpawnProcessResult) { if (comptime Environment.isPosix) { return spawnProcessPosix( options, @@ -1223,8 +1223,8 @@ pub fn spawnProcessPosix( options: *const PosixSpawnOptions, argv: [*:null]?[*:0]const u8, envp: [*:null]?[*:0]const u8, -) !JSC.Maybe(PosixSpawnResult) { - bun.Analytics.Features.spawn += 1; +) !jsc.Maybe(PosixSpawnResult) { + bun.analytics.Features.spawn += 1; var actions = try PosixSpawn.Actions.init(); defer actions.deinit(); @@ -1524,9 +1524,9 @@ pub fn spawnProcessWindows( options: *const WindowsSpawnOptions, argv: [*:null]?[*:0]const u8, envp: [*:null]?[*:0]const u8, -) !JSC.Maybe(WindowsSpawnResult) { +) !jsc.Maybe(WindowsSpawnResult) { bun.markWindowsOnly(); - bun.Analytics.Features.spawn += 1; + bun.analytics.Features.spawn += 1; var uv_process_options = std.mem.zeroes(uv.uv_process_options_t); @@ -1977,7 +1977,7 @@ pub const sync = struct { argv: [*:null]?[*:0]const u8, envp: [*:null]?[*:0]const u8, ) !Maybe(Result) { - var loop: JSC.EventLoopHandle = options.windows.loop; + var loop: jsc.EventLoopHandle = options.windows.loop; var spawned = switch (try spawnProcessWindows(&options.toSpawnOptions(), argv, envp)) { .err => |err| return .{ .err = err }, .result => |process| process, @@ -2246,6 +2246,6 @@ const LifecycleScriptSubprocess = bun.install.LifecycleScriptSubprocess; const ShellSubprocess = bun.shell.ShellSubprocess; const uv = bun.windows.libuv; -const JSC = bun.JSC; -const Maybe = JSC.Maybe; -const Subprocess = JSC.Subprocess; +const jsc = bun.jsc; +const Maybe = jsc.Maybe; +const Subprocess = jsc.Subprocess; diff --git a/src/bun.js/api/bun/socket.zig b/src/bun.js/api/bun/socket.zig index c203d974bb..06896e4f8c 100644 --- a/src/bun.js/api/bun/socket.zig +++ b/src/bun.js/api/bun/socket.zig @@ -8,9 +8,9 @@ const WrappedType = enum { fn JSSocketType(comptime ssl: bool) type { if (!ssl) { - return JSC.Codegen.JSTCPSocket; + return jsc.Codegen.JSTCPSocket; } else { - return JSC.Codegen.JSTLSSocket; + return jsc.Codegen.JSTLSSocket; } } @@ -41,7 +41,7 @@ pub const WindowsNamedPipeContext = if (Environment.isWindows) @import("./socket pub fn NewSocket(comptime ssl: bool) type { return struct { const This = @This(); - pub const js = if (!ssl) JSC.Codegen.JSTCPSocket else JSC.Codegen.JSTLSSocket; + pub const js = if (!ssl) jsc.Codegen.JSTCPSocket else jsc.Codegen.JSTLSSocket; pub const toJS = js.toJS; pub const fromJS = js.fromJS; pub const fromJSDirect = js.fromJSDirect; @@ -62,7 +62,7 @@ pub fn NewSocket(comptime ssl: bool) type { wrapped: WrappedType = .none, // TODO: make this optional handlers: *Handlers, - this_value: JSC.JSValue = .zero, + this_value: jsc.JSValue = .zero, poll_ref: Async.KeepAlive = Async.KeepAlive.init(), ref_pollref_on_connect: bool = true, connection: ?Listener.UnixOrHost = null, @@ -139,12 +139,12 @@ pub fn NewSocket(comptime ssl: bool) type { } } - pub fn constructor(globalObject: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!*This { + pub fn constructor(globalObject: *jsc.JSGlobalObject, _: *jsc.CallFrame) bun.JSError!*This { return globalObject.throw("Cannot construct Socket", .{}); } - pub fn resumeFromJS(this: *This, _: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!JSValue { - JSC.markBinding(@src()); + pub fn resumeFromJS(this: *This, _: *jsc.JSGlobalObject, _: *jsc.CallFrame) bun.JSError!JSValue { + jsc.markBinding(@src()); if (this.socket.isDetached()) return .js_undefined; log("resume", .{}); @@ -155,8 +155,8 @@ pub fn NewSocket(comptime ssl: bool) type { return .js_undefined; } - pub fn pauseFromJS(this: *This, _: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!JSValue { - JSC.markBinding(@src()); + pub fn pauseFromJS(this: *This, _: *jsc.JSGlobalObject, _: *jsc.CallFrame) bun.JSError!JSValue { + jsc.markBinding(@src()); if (this.socket.isDetached()) return .js_undefined; log("pause", .{}); @@ -168,8 +168,8 @@ pub fn NewSocket(comptime ssl: bool) type { return .js_undefined; } - pub fn setKeepAlive(this: *This, globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { - JSC.markBinding(@src()); + pub fn setKeepAlive(this: *This, globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { + jsc.markBinding(@src()); const args = callframe.arguments_old(2); const enabled: bool = brk: { @@ -190,8 +190,8 @@ pub fn NewSocket(comptime ssl: bool) type { return JSValue.jsBoolean(this.socket.setKeepAlive(enabled, initialDelay)); } - pub fn setNoDelay(this: *This, globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { - JSC.markBinding(@src()); + pub fn setNoDelay(this: *This, globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { + jsc.markBinding(@src()); _ = globalThis; const args = callframe.arguments_old(1); @@ -206,7 +206,7 @@ pub fn NewSocket(comptime ssl: bool) type { return JSValue.jsBoolean(this.socket.setNoDelay(enabled)); } - pub fn handleError(this: *This, err_value: JSC.JSValue) void { + pub fn handleError(this: *This, err_value: jsc.JSValue) void { log("handleError", .{}); const handlers = this.handlers; var vm = handlers.vm; @@ -223,7 +223,7 @@ pub fn NewSocket(comptime ssl: bool) type { } pub fn onWritable(this: *This, _: Socket) void { - JSC.markBinding(@src()); + jsc.markBinding(@src()); if (this.socket.isDetached()) return; if (this.native_callback.onWritable()) return; const handlers = this.handlers; @@ -254,7 +254,7 @@ pub fn NewSocket(comptime ssl: bool) type { } pub fn onTimeout(this: *This, _: Socket) void { - JSC.markBinding(@src()); + jsc.markBinding(@src()); if (this.socket.isDetached()) return; log("onTimeout {s}", .{if (this.handlers.is_server) "S" else "C"}); const handlers = this.handlers; @@ -303,7 +303,7 @@ pub fn NewSocket(comptime ssl: bool) type { const callback = handlers.onConnectError; const globalObject = handlers.globalObject; - const err = JSC.SystemError{ + const err = jsc.SystemError{ .errno = -errno_, .message = bun.String.static("Failed to connect"), .syscall = bun.String.static("connect"), @@ -351,7 +351,7 @@ pub fn NewSocket(comptime ssl: bool) type { } pub fn onConnectError(this: *This, _: Socket, errno: c_int) void { - JSC.markBinding(@src()); + jsc.markBinding(@src()); this.handleConnectError(errno); } @@ -401,7 +401,7 @@ pub fn NewSocket(comptime ssl: bool) type { // update the internal socket instance to the one that was just connected // This socket must be replaced because the previous one is a connecting socket not a uSockets socket this.socket = socket; - JSC.markBinding(@src()); + jsc.markBinding(@src()); // Add SNI support for TLS (mongodb and others requires this) if (comptime ssl) { @@ -479,7 +479,7 @@ pub fn NewSocket(comptime ssl: bool) type { } } - pub fn getThisValue(this: *This, globalObject: *JSC.JSGlobalObject) JSValue { + pub fn getThisValue(this: *This, globalObject: *jsc.JSGlobalObject) JSValue { if (this.this_value == .zero) { const value = this.toJS(globalObject); value.ensureStillAlive(); @@ -491,7 +491,7 @@ pub fn NewSocket(comptime ssl: bool) type { } pub fn onEnd(this: *This, _: Socket) void { - JSC.markBinding(@src()); + jsc.markBinding(@src()); if (this.socket.isDetached()) return; log("onEnd {s}", .{if (this.handlers.is_server) "S" else "C"}); // Ensure the socket remains alive until this is finished @@ -522,7 +522,7 @@ pub fn NewSocket(comptime ssl: bool) type { } pub fn onHandshake(this: *This, _: Socket, success: i32, ssl_error: uws.us_bun_verify_error_t) void { - JSC.markBinding(@src()); + jsc.markBinding(@src()); this.flags.handshake_complete = true; if (this.socket.isDetached()) return; log("onHandshake {s} ({d})", .{ if (this.handlers.is_server) "S" else "C", success }); @@ -556,7 +556,7 @@ pub fn NewSocket(comptime ssl: bool) type { const globalObject = handlers.globalObject; const this_value = this.getThisValue(globalObject); - var result: JSC.JSValue = JSC.JSValue.zero; + var result: jsc.JSValue = jsc.JSValue.zero; // open callback only have 1 parameters and its the socket // you should use getAuthorizationError and authorized getter to get those values in this case if (is_open) { @@ -590,7 +590,7 @@ pub fn NewSocket(comptime ssl: bool) type { } pub fn onClose(this: *This, _: Socket, err: c_int, _: ?*anyopaque) void { - JSC.markBinding(@src()); + jsc.markBinding(@src()); log("onClose {s}", .{if (this.handlers.is_server) "S" else "C"}); this.detachNativeCallback(); this.socket.detach(); @@ -636,7 +636,7 @@ pub fn NewSocket(comptime ssl: bool) type { } pub fn onData(this: *This, _: Socket, data: []const u8) void { - JSC.markBinding(@src()); + jsc.markBinding(@src()); if (this.socket.isDetached()) return; log("onData {s} ({d})", .{ if (this.handlers.is_server) "S" else "C", data.len }); if (this.native_callback.onData(data)) return; @@ -669,17 +669,17 @@ pub fn NewSocket(comptime ssl: bool) type { }; } - pub fn getData(_: *This, _: *JSC.JSGlobalObject) JSValue { + pub fn getData(_: *This, _: *jsc.JSGlobalObject) JSValue { log("getData()", .{}); return .js_undefined; } - pub fn setData(this: *This, globalObject: *JSC.JSGlobalObject, value: JSC.JSValue) void { + pub fn setData(this: *This, globalObject: *jsc.JSGlobalObject, value: jsc.JSValue) void { log("setData()", .{}); This.js.dataSetCached(this.this_value, globalObject, value); } - pub fn getListener(this: *This, _: *JSC.JSGlobalObject) JSValue { + pub fn getListener(this: *This, _: *jsc.JSGlobalObject) JSValue { if (!this.handlers.is_server or this.socket.isDetached()) { return .js_undefined; } @@ -688,7 +688,7 @@ pub fn NewSocket(comptime ssl: bool) type { return l.strong_self.get() orelse .js_undefined; } - pub fn getReadyState(this: *This, _: *JSC.JSGlobalObject) JSValue { + pub fn getReadyState(this: *This, _: *jsc.JSGlobalObject) JSValue { if (this.socket.isDetached()) { return JSValue.jsNumber(@as(i32, -1)); } else if (this.socket.isClosed()) { @@ -702,13 +702,13 @@ pub fn NewSocket(comptime ssl: bool) type { } } - pub fn getAuthorized(this: *This, _: *JSC.JSGlobalObject) JSValue { + pub fn getAuthorized(this: *This, _: *jsc.JSGlobalObject) JSValue { log("getAuthorized()", .{}); return JSValue.jsBoolean(this.flags.authorized); } - pub fn timeout(this: *This, globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { - JSC.markBinding(@src()); + pub fn timeout(this: *This, globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { + jsc.markBinding(@src()); const args = callframe.arguments_old(1); if (this.socket.isDetached()) return .js_undefined; if (args.len == 0) { @@ -725,8 +725,8 @@ pub fn NewSocket(comptime ssl: bool) type { return .js_undefined; } - pub fn getAuthorizationError(this: *This, globalObject: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!JSValue { - JSC.markBinding(@src()); + pub fn getAuthorizationError(this: *This, globalObject: *jsc.JSGlobalObject, _: *jsc.CallFrame) bun.JSError!JSValue { + jsc.markBinding(@src()); if (this.socket.isDetached()) { return JSValue.jsNull(); @@ -743,7 +743,7 @@ pub fn NewSocket(comptime ssl: bool) type { const reason = if (ssl_error.reason == null) "" else ssl_error.reason[0..bun.len(ssl_error.reason)]; - const fallback = JSC.SystemError{ + const fallback = jsc.SystemError{ .code = bun.String.cloneUTF8(code), .message = bun.String.cloneUTF8(reason), }; @@ -751,8 +751,8 @@ pub fn NewSocket(comptime ssl: bool) type { return fallback.toErrorInstance(globalObject); } - pub fn write(this: *This, globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { - JSC.markBinding(@src()); + pub fn write(this: *This, globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { + jsc.markBinding(@src()); if (this.socket.isDetached()) { return JSValue.jsNumber(@as(i32, -1)); @@ -766,7 +766,7 @@ pub fn NewSocket(comptime ssl: bool) type { }; } - pub fn getLocalFamily(this: *This, globalThis: *JSC.JSGlobalObject) JSValue { + pub fn getLocalFamily(this: *This, globalThis: *jsc.JSGlobalObject) JSValue { if (this.socket.isDetached()) { return .js_undefined; } @@ -780,7 +780,7 @@ pub fn NewSocket(comptime ssl: bool) type { }; } - pub fn getLocalAddress(this: *This, globalThis: *JSC.JSGlobalObject) JSValue { + pub fn getLocalAddress(this: *This, globalThis: *jsc.JSGlobalObject) JSValue { if (this.socket.isDetached()) { return .js_undefined; } @@ -799,7 +799,7 @@ pub fn NewSocket(comptime ssl: bool) type { return ZigString.init(text).toJS(globalThis); } - pub fn getLocalPort(this: *This, _: *JSC.JSGlobalObject) JSValue { + pub fn getLocalPort(this: *This, _: *jsc.JSGlobalObject) JSValue { if (this.socket.isDetached()) { return .js_undefined; } @@ -807,7 +807,7 @@ pub fn NewSocket(comptime ssl: bool) type { return JSValue.jsNumber(this.socket.localPort()); } - pub fn getRemoteFamily(this: *This, globalThis: *JSC.JSGlobalObject) JSValue { + pub fn getRemoteFamily(this: *This, globalThis: *jsc.JSGlobalObject) JSValue { if (this.socket.isDetached()) { return .js_undefined; } @@ -821,7 +821,7 @@ pub fn NewSocket(comptime ssl: bool) type { }; } - pub fn getRemoteAddress(this: *This, globalThis: *JSC.JSGlobalObject) JSValue { + pub fn getRemoteAddress(this: *This, globalThis: *jsc.JSGlobalObject) JSValue { if (this.socket.isDetached()) { return .js_undefined; } @@ -840,7 +840,7 @@ pub fn NewSocket(comptime ssl: bool) type { return ZigString.init(text).toJS(globalThis); } - pub fn getRemotePort(this: *This, _: *JSC.JSGlobalObject) JSValue { + pub fn getRemotePort(this: *This, _: *jsc.JSGlobalObject) JSValue { if (this.socket.isDetached()) { return .js_undefined; } @@ -872,11 +872,11 @@ pub fn NewSocket(comptime ssl: bool) type { return res; } - pub fn writeBuffered(this: *This, globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { + pub fn writeBuffered(this: *This, globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { if (this.socket.isDetached()) { this.buffered_data_for_node_net.deinitWithAllocator(bun.default_allocator); // TODO: should we separate unattached and detached? unattached shouldn't throw here - const err: JSC.SystemError = .{ + const err: jsc.SystemError = .{ .errno = @intFromEnum(bun.sys.SystemErrno.EBADF), .code = .static("EBADF"), .message = .static("write EBADF"), @@ -893,7 +893,7 @@ pub fn NewSocket(comptime ssl: bool) type { }; } - pub fn endBuffered(this: *This, globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { + pub fn endBuffered(this: *This, globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { if (this.socket.isDetached()) { this.buffered_data_for_node_net.deinitWithAllocator(bun.default_allocator); return JSValue.jsBoolean(false); @@ -914,18 +914,18 @@ pub fn NewSocket(comptime ssl: bool) type { }; } - fn writeOrEndBuffered(this: *This, globalObject: *JSC.JSGlobalObject, data_value: JSC.JSValue, encoding_value: JSC.JSValue, comptime is_end: bool) WriteResult { + fn writeOrEndBuffered(this: *This, globalObject: *jsc.JSGlobalObject, data_value: jsc.JSValue, encoding_value: jsc.JSValue, comptime is_end: bool) WriteResult { if (this.buffered_data_for_node_net.len == 0) { - var values = [4]JSC.JSValue{ data_value, .js_undefined, .js_undefined, encoding_value }; + var values = [4]jsc.JSValue{ data_value, .js_undefined, .js_undefined, encoding_value }; return this.writeOrEnd(globalObject, &values, true, is_end); } var stack_fallback = std.heap.stackFallback(16 * 1024, bun.default_allocator); const allow_string_object = true; - const buffer: JSC.Node.StringOrBuffer = if (data_value.isUndefined()) - JSC.Node.StringOrBuffer.empty + const buffer: jsc.Node.StringOrBuffer = if (data_value.isUndefined()) + jsc.Node.StringOrBuffer.empty else - JSC.Node.StringOrBuffer.fromJSWithEncodingValueMaybeAsync(globalObject, stack_fallback.get(), data_value, encoding_value, false, allow_string_object) catch { + jsc.Node.StringOrBuffer.fromJSWithEncodingValueMaybeAsync(globalObject, stack_fallback.get(), data_value, encoding_value, false, allow_string_object) catch { return .fail; } orelse { if (!globalObject.hasException()) { @@ -1033,7 +1033,7 @@ pub fn NewSocket(comptime ssl: bool) type { }; } - fn writeOrEnd(this: *This, globalObject: *JSC.JSGlobalObject, args: []JSC.JSValue, buffer_unwritten_data: bool, comptime is_end: bool) WriteResult { + fn writeOrEnd(this: *This, globalObject: *jsc.JSGlobalObject, args: []jsc.JSValue, buffer_unwritten_data: bool, comptime is_end: bool) WriteResult { if (args[0].isUndefined()) { if (!this.flags.end_after_flush and is_end) { this.flags.end_after_flush = true; @@ -1043,7 +1043,7 @@ pub fn NewSocket(comptime ssl: bool) type { } bun.debugAssert(this.buffered_data_for_node_net.len == 0); - var encoding_value: JSC.JSValue = args[3]; + var encoding_value: jsc.JSValue = args[3]; if (args[2].isString()) { encoding_value = args[2]; args[2] = .js_undefined; @@ -1060,10 +1060,10 @@ pub fn NewSocket(comptime ssl: bool) type { } var stack_fallback = std.heap.stackFallback(16 * 1024, bun.default_allocator); - const buffer: JSC.Node.BlobOrStringOrBuffer = if (args[0].isUndefined()) - JSC.Node.BlobOrStringOrBuffer{ .string_or_buffer = JSC.Node.StringOrBuffer.empty } + const buffer: jsc.Node.BlobOrStringOrBuffer = if (args[0].isUndefined()) + jsc.Node.BlobOrStringOrBuffer{ .string_or_buffer = jsc.Node.StringOrBuffer.empty } else - JSC.Node.BlobOrStringOrBuffer.fromJSWithEncodingValueMaybeAsyncAllowRequestResponse(globalObject, stack_fallback.get(), args[0], encoding_value, false, true) catch { + jsc.Node.BlobOrStringOrBuffer.fromJSWithEncodingValueMaybeAsyncAllowRequestResponse(globalObject, stack_fallback.get(), args[0], encoding_value, false, true) catch { return .fail; } orelse { if (!globalObject.hasException()) { @@ -1086,7 +1086,7 @@ pub fn NewSocket(comptime ssl: bool) type { } const i = offset_value.toInt64(); if (i < 0) { - return globalObject.throwRangeError(i, .{ .field_name = "byteOffset", .min = 0, .max = JSC.MAX_SAFE_INTEGER }) catch .fail; + return globalObject.throwRangeError(i, .{ .field_name = "byteOffset", .min = 0, .max = jsc.MAX_SAFE_INTEGER }) catch .fail; } break :brk @intCast(i); }; @@ -1100,7 +1100,7 @@ pub fn NewSocket(comptime ssl: bool) type { const l = length_value.toInt64(); if (l < 0) { - return globalObject.throwRangeError(l, .{ .field_name = "byteLength", .min = 0, .max = JSC.MAX_SAFE_INTEGER }) catch .fail; + return globalObject.throwRangeError(l, .{ .field_name = "byteLength", .min = 0, .max = jsc.MAX_SAFE_INTEGER }) catch .fail; } break :brk @intCast(l); }; @@ -1208,20 +1208,20 @@ pub fn NewSocket(comptime ssl: bool) type { } } - pub fn flush(this: *This, _: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!JSValue { - JSC.markBinding(@src()); + pub fn flush(this: *This, _: *jsc.JSGlobalObject, _: *jsc.CallFrame) bun.JSError!JSValue { + jsc.markBinding(@src()); this.internalFlush(); return .js_undefined; } - pub fn terminate(this: *This, _: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!JSValue { - JSC.markBinding(@src()); + pub fn terminate(this: *This, _: *jsc.JSGlobalObject, _: *jsc.CallFrame) bun.JSError!JSValue { + jsc.markBinding(@src()); this.closeAndDetach(.failure); return .js_undefined; } - pub fn shutdown(this: *This, _: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { - JSC.markBinding(@src()); + pub fn shutdown(this: *This, _: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { + jsc.markBinding(@src()); const args = callframe.arguments_old(1); if (args.len > 0 and args.ptr[0].toBoolean()) { this.socket.shutdownRead(); @@ -1232,8 +1232,8 @@ pub fn NewSocket(comptime ssl: bool) type { return .js_undefined; } - pub fn close(this: *This, globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { - JSC.markBinding(@src()); + pub fn close(this: *This, globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { + jsc.markBinding(@src()); _ = callframe; this.socket.close(.normal); this.socket.detach(); @@ -1241,8 +1241,8 @@ pub fn NewSocket(comptime ssl: bool) type { return .js_undefined; } - pub fn end(this: *This, globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { - JSC.markBinding(@src()); + pub fn end(this: *This, globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { + jsc.markBinding(@src()); var args = callframe.argumentsUndef(5); @@ -1265,16 +1265,16 @@ pub fn NewSocket(comptime ssl: bool) type { }; } - pub fn jsRef(this: *This, globalObject: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!JSValue { - JSC.markBinding(@src()); + pub fn jsRef(this: *This, globalObject: *jsc.JSGlobalObject, _: *jsc.CallFrame) bun.JSError!JSValue { + jsc.markBinding(@src()); if (this.socket.isDetached()) this.ref_pollref_on_connect = true; if (this.socket.isDetached()) return .js_undefined; this.poll_ref.ref(globalObject.bunVM()); return .js_undefined; } - pub fn jsUnref(this: *This, globalObject: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!JSValue { - JSC.markBinding(@src()); + pub fn jsUnref(this: *This, globalObject: *jsc.JSGlobalObject, _: *jsc.CallFrame) bun.JSError!JSValue { + jsc.markBinding(@src()); if (this.socket.isDetached()) this.ref_pollref_on_connect = false; this.poll_ref.unref(globalObject.bunVM()); return .js_undefined; @@ -1286,7 +1286,7 @@ pub fn NewSocket(comptime ssl: bool) type { this.buffered_data_for_node_net.deinitWithAllocator(bun.default_allocator); - this.poll_ref.unref(JSC.VirtualMachine.get()); + this.poll_ref.unref(jsc.VirtualMachine.get()); // need to deinit event without being attached if (this.flags.owned_protos) { if (this.protos) |protos| { @@ -1321,7 +1321,7 @@ pub fn NewSocket(comptime ssl: bool) type { this.deref(); } - pub fn reload(this: *This, globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { + pub fn reload(this: *This, globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { const args = callframe.arguments_old(1); if (args.len < 1) { @@ -1352,15 +1352,15 @@ pub fn NewSocket(comptime ssl: bool) type { return .js_undefined; } - pub fn getBytesWritten(this: *This, _: *JSC.JSGlobalObject) JSValue { - return JSC.JSValue.jsNumber(this.bytes_written + this.buffered_data_for_node_net.len); + pub fn getBytesWritten(this: *This, _: *jsc.JSGlobalObject) JSValue { + return jsc.JSValue.jsNumber(this.bytes_written + this.buffered_data_for_node_net.len); } // this invalidates the current socket returning 2 new sockets // one for non-TLS and another for TLS // handlers for non-TLS are preserved - pub fn upgradeTLS(this: *This, globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { - JSC.markBinding(@src()); + pub fn upgradeTLS(this: *This, globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { + jsc.markBinding(@src()); const this_js = callframe.this(); if (comptime ssl) { @@ -1395,7 +1395,7 @@ pub fn NewSocket(comptime ssl: bool) type { return .zero; } - var ssl_opts: ?JSC.API.ServerConfig.SSLConfig = null; + var ssl_opts: ?jsc.API.ServerConfig.SSLConfig = null; defer { if (!success) { if (ssl_opts) |*ssl_config| { @@ -1407,10 +1407,10 @@ pub fn NewSocket(comptime ssl: bool) type { if (try opts.getTruthy(globalObject, "tls")) |tls| { if (tls.isBoolean()) { if (tls.toBoolean()) { - ssl_opts = JSC.API.ServerConfig.SSLConfig.zero; + ssl_opts = jsc.API.ServerConfig.SSLConfig.zero; } } else { - if (try JSC.API.ServerConfig.SSLConfig.fromJS(JSC.VirtualMachine.get(), globalObject, tls)) |ssl_config| { + if (try jsc.API.ServerConfig.SSLConfig.fromJS(jsc.VirtualMachine.get(), globalObject, tls)) |ssl_config| { ssl_opts = ssl_config; } } @@ -1579,7 +1579,7 @@ pub fn NewSocket(comptime ssl: bool) type { this.has_pending_activity.store(false, .release); } - const array = try JSC.JSValue.createEmptyArray(globalObject, 2); + const array = try jsc.JSValue.createEmptyArray(globalObject, 2); try array.putIndex(globalObject, 0, raw_js_value); try array.putIndex(globalObject, 1, tls_js_value); @@ -1618,19 +1618,19 @@ pub fn NewSocket(comptime ssl: bool) type { pub const getServername = if (ssl) tls_socket_functions.getServername else tcp_socket_function_that_returns_undefined; pub const setServername = if (ssl) tls_socket_functions.setServername else tcp_socket_function_that_returns_undefined; - fn tcp_socket_function_that_returns_undefined(_: *This, _: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!JSValue { + fn tcp_socket_function_that_returns_undefined(_: *This, _: *jsc.JSGlobalObject, _: *jsc.CallFrame) bun.JSError!JSValue { return .js_undefined; } - fn tcp_socket_function_that_returns_false(_: *This, _: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!JSValue { + fn tcp_socket_function_that_returns_false(_: *This, _: *jsc.JSGlobalObject, _: *jsc.CallFrame) bun.JSError!JSValue { return .false; } - fn tcp_socket_getter_that_returns_false(_: *This, _: *JSC.JSGlobalObject) bun.JSError!JSValue { + fn tcp_socket_getter_that_returns_false(_: *This, _: *jsc.JSGlobalObject) bun.JSError!JSValue { return .false; } - fn tcp_socket_function_that_returns_null(_: *This, _: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!JSValue { + fn tcp_socket_function_that_returns_null(_: *This, _: *jsc.JSGlobalObject, _: *jsc.CallFrame) bun.JSError!JSValue { return .null; } }; @@ -1777,10 +1777,10 @@ pub const DuplexUpgradeContext = struct { // We only us a tls and not a raw socket when upgrading a Duplex, Duplex dont support socketpairs tls: ?*TLSSocket, // task used to deinit the context in the next tick, vm is used to enqueue the task - vm: *JSC.VirtualMachine, - task: JSC.AnyTask, + vm: *jsc.VirtualMachine, + task: jsc.AnyTask, task_event: EventState = .StartTLS, - ssl_config: ?JSC.API.ServerConfig.SSLConfig, + ssl_config: ?jsc.API.ServerConfig.SSLConfig, is_open: bool = false, pub const EventState = enum(u8) { @@ -1830,7 +1830,7 @@ pub const DuplexUpgradeContext = struct { } } - fn onError(this: *DuplexUpgradeContext, err_value: JSC.JSValue) void { + fn onError(this: *DuplexUpgradeContext, err_value: jsc.JSValue) void { if (this.is_open) { if (this.tls) |tls| { tls.handleError(err_value); @@ -1892,12 +1892,12 @@ pub const DuplexUpgradeContext = struct { fn deinitInNextTick(this: *DuplexUpgradeContext) void { this.task_event = .Close; - this.vm.enqueueTask(JSC.Task.init(&this.task)); + this.vm.enqueueTask(jsc.Task.init(&this.task)); } fn startTLS(this: *DuplexUpgradeContext) void { this.task_event = .StartTLS; - this.vm.enqueueTask(JSC.Task.init(&this.task)); + this.vm.enqueueTask(jsc.Task.init(&this.task)); } fn deinit(this: *DuplexUpgradeContext) void { @@ -1910,8 +1910,8 @@ pub const DuplexUpgradeContext = struct { } }; -pub fn jsUpgradeDuplexToTLS(globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { - JSC.markBinding(@src()); +pub fn jsUpgradeDuplexToTLS(globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { + jsc.markBinding(@src()); const args = callframe.arguments_old(2); if (args.len < 2) { @@ -1934,14 +1934,14 @@ pub fn jsUpgradeDuplexToTLS(globalObject: *JSC.JSGlobalObject, callframe: *JSC.C var handlers = try Handlers.fromJS(globalObject, socket_obj, false); - var ssl_opts: ?JSC.API.ServerConfig.SSLConfig = null; + var ssl_opts: ?jsc.API.ServerConfig.SSLConfig = null; if (try opts.getTruthy(globalObject, "tls")) |tls| { if (tls.isBoolean()) { if (tls.toBoolean()) { - ssl_opts = JSC.API.ServerConfig.SSLConfig.zero; + ssl_opts = jsc.API.ServerConfig.SSLConfig.zero; } } else { - if (try JSC.API.ServerConfig.SSLConfig.fromJS(JSC.VirtualMachine.get(), globalObject, tls)) |ssl_config| { + if (try jsc.API.ServerConfig.SSLConfig.fromJS(jsc.VirtualMachine.get(), globalObject, tls)) |ssl_config| { ssl_opts = ssl_config; } } @@ -1991,7 +1991,7 @@ pub fn jsUpgradeDuplexToTLS(globalObject: *JSC.JSGlobalObject, callframe: *JSC.C }); tls.ref(); - duplexContext.task = JSC.AnyTask.New(DuplexUpgradeContext, DuplexUpgradeContext.runEvent).init(duplexContext); + duplexContext.task = jsc.AnyTask.New(DuplexUpgradeContext, DuplexUpgradeContext.runEvent).init(duplexContext); duplexContext.upgrade = uws.UpgradedDuplex.from(globalObject, duplex, .{ .onOpen = @ptrCast(&DuplexUpgradeContext.onOpen), .onData = @ptrCast(&DuplexUpgradeContext.onData), @@ -2010,7 +2010,7 @@ pub fn jsUpgradeDuplexToTLS(globalObject: *JSC.JSGlobalObject, callframe: *JSC.C duplexContext.startTLS(); - const array = try JSC.JSValue.createEmptyArray(globalObject, 2); + const array = try jsc.JSValue.createEmptyArray(globalObject, 2); try array.putIndex(globalObject, 0, tls_js_value); // data, end, drain and close events must be reported try array.putIndex(globalObject, 1, try duplexContext.upgrade.getJSHandlers(globalObject)); @@ -2018,8 +2018,8 @@ pub fn jsUpgradeDuplexToTLS(globalObject: *JSC.JSGlobalObject, callframe: *JSC.C return array; } -pub fn jsIsNamedPipeSocket(global: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { - JSC.markBinding(@src()); +pub fn jsIsNamedPipeSocket(global: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { + jsc.markBinding(@src()); const arguments = callframe.arguments_old(3); if (arguments.len < 1) { @@ -2027,15 +2027,15 @@ pub fn jsIsNamedPipeSocket(global: *JSC.JSGlobalObject, callframe: *JSC.CallFram } const socket = arguments.ptr[0]; if (socket.as(TCPSocket)) |this| { - return JSC.JSValue.jsBoolean(this.socket.isNamedPipe()); + return jsc.JSValue.jsBoolean(this.socket.isNamedPipe()); } else if (socket.as(TLSSocket)) |this| { - return JSC.JSValue.jsBoolean(this.socket.isNamedPipe()); + return jsc.JSValue.jsBoolean(this.socket.isNamedPipe()); } - return JSC.JSValue.jsBoolean(false); + return jsc.JSValue.jsBoolean(false); } -pub fn jsGetBufferedAmount(global: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { - JSC.markBinding(@src()); +pub fn jsGetBufferedAmount(global: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { + jsc.markBinding(@src()); const arguments = callframe.arguments_old(3); if (arguments.len < 1) { @@ -2043,15 +2043,15 @@ pub fn jsGetBufferedAmount(global: *JSC.JSGlobalObject, callframe: *JSC.CallFram } const socket = arguments.ptr[0]; if (socket.as(TCPSocket)) |this| { - return JSC.JSValue.jsNumber(this.buffered_data_for_node_net.len); + return jsc.JSValue.jsNumber(this.buffered_data_for_node_net.len); } else if (socket.as(TLSSocket)) |this| { - return JSC.JSValue.jsNumber(this.buffered_data_for_node_net.len); + return jsc.JSValue.jsNumber(this.buffered_data_for_node_net.len); } - return JSC.JSValue.jsNumber(0); + return jsc.JSValue.jsNumber(0); } -pub fn jsCreateSocketPair(global: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!JSValue { - JSC.markBinding(@src()); +pub fn jsCreateSocketPair(global: *jsc.JSGlobalObject, _: *jsc.CallFrame) bun.JSError!JSValue { + jsc.markBinding(@src()); if (Environment.isWindows) { return global.throw("Not implemented on Windows", .{}); @@ -2067,13 +2067,13 @@ pub fn jsCreateSocketPair(global: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JS _ = bun.FD.fromNative(fds_[0]).updateNonblocking(true); _ = bun.FD.fromNative(fds_[1]).updateNonblocking(true); - const array = try JSC.JSValue.createEmptyArray(global, 2); - try array.putIndex(global, 0, JSC.jsNumber(fds_[0])); - try array.putIndex(global, 1, JSC.jsNumber(fds_[1])); + const array = try jsc.JSValue.createEmptyArray(global, 2); + try array.putIndex(global, 0, jsc.jsNumber(fds_[0])); + try array.putIndex(global, 1, jsc.jsNumber(fds_[1])); return array; } -pub fn jsSetSocketOptions(global: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { +pub fn jsSetSocketOptions(global: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const arguments = callframe.arguments(); if (arguments.len < 3) { @@ -2106,6 +2106,8 @@ pub fn jsSetSocketOptions(global: *JSC.JSGlobalObject, callframe: *JSC.CallFrame return .js_undefined; } +const string = []const u8; + const std = @import("std"); const tls_socket_functions = @import("./socket/tls_socket_functions.zig"); const H2FrameParser = @import("./h2_frame_parser.zig").H2FrameParser; @@ -2115,11 +2117,10 @@ const Async = bun.Async; const Environment = bun.Environment; const Output = bun.Output; const default_allocator = bun.default_allocator; -const string = bun.string; const uws = bun.uws; const BoringSSL = bun.BoringSSL.c; -const JSC = bun.JSC; -const JSGlobalObject = JSC.JSGlobalObject; -const JSValue = JSC.JSValue; -const ZigString = JSC.ZigString; +const jsc = bun.jsc; +const JSGlobalObject = jsc.JSGlobalObject; +const JSValue = jsc.JSValue; +const ZigString = jsc.ZigString; diff --git a/src/bun.js/api/bun/socket/Handlers.zig b/src/bun.js/api/bun/socket/Handlers.zig index c8385f8a75..b87975827e 100644 --- a/src/bun.js/api/bun/socket/Handlers.zig +++ b/src/bun.js/api/bun/socket/Handlers.zig @@ -1,22 +1,22 @@ const Handlers = @This(); -onOpen: JSC.JSValue = .zero, -onClose: JSC.JSValue = .zero, -onData: JSC.JSValue = .zero, -onWritable: JSC.JSValue = .zero, -onTimeout: JSC.JSValue = .zero, -onConnectError: JSC.JSValue = .zero, -onEnd: JSC.JSValue = .zero, -onError: JSC.JSValue = .zero, -onHandshake: JSC.JSValue = .zero, +onOpen: jsc.JSValue = .zero, +onClose: jsc.JSValue = .zero, +onData: jsc.JSValue = .zero, +onWritable: jsc.JSValue = .zero, +onTimeout: jsc.JSValue = .zero, +onConnectError: jsc.JSValue = .zero, +onEnd: jsc.JSValue = .zero, +onError: jsc.JSValue = .zero, +onHandshake: jsc.JSValue = .zero, binary_type: BinaryType = .Buffer, -vm: *JSC.VirtualMachine, -globalObject: *JSC.JSGlobalObject, +vm: *jsc.VirtualMachine, +globalObject: *jsc.JSGlobalObject, active_connections: u32 = 0, is_server: bool, -promise: JSC.Strong.Optional = .empty, +promise: jsc.Strong.Optional = .empty, protection_count: bun.DebugOnly(u32) = if (Environment.isDebug) 0, @@ -103,7 +103,7 @@ pub fn callErrorHandler(this: *Handlers, thisValue: JSValue, args: *const [2]JSV return true; } -pub fn fromJS(globalObject: *JSC.JSGlobalObject, opts: JSC.JSValue, is_server: bool) bun.JSError!Handlers { +pub fn fromJS(globalObject: *jsc.JSGlobalObject, opts: jsc.JSValue, is_server: bool) bun.JSError!Handlers { var handlers = Handlers{ .vm = globalObject.bunVM(), .globalObject = globalObject, @@ -172,7 +172,7 @@ pub fn unprotect(this: *Handlers) void { this.onHandshake.unprotect(); } -pub fn withAsyncContextIfNeeded(this: *Handlers, globalObject: *JSC.JSGlobalObject) void { +pub fn withAsyncContextIfNeeded(this: *Handlers, globalObject: *jsc.JSGlobalObject) void { inline for (.{ "onOpen", "onClose", @@ -207,12 +207,12 @@ pub fn protect(this: *Handlers) void { } pub const SocketConfig = struct { - hostname_or_unix: JSC.ZigString.Slice, + hostname_or_unix: jsc.ZigString.Slice, port: ?u16 = null, fd: ?bun.FileDescriptor = null, - ssl: ?JSC.API.ServerConfig.SSLConfig = null, + ssl: ?jsc.API.ServerConfig.SSLConfig = null, handlers: Handlers, - default_data: JSC.JSValue = .zero, + default_data: jsc.JSValue = .zero, exclusive: bool = false, allowHalfOpen: bool = false, reusePort: bool = false, @@ -236,8 +236,8 @@ pub const SocketConfig = struct { return flags; } - pub fn fromJS(vm: *JSC.VirtualMachine, opts: JSC.JSValue, globalObject: *JSC.JSGlobalObject, is_server: bool) bun.JSError!SocketConfig { - var hostname_or_unix: JSC.ZigString.Slice = JSC.ZigString.Slice.empty; + pub fn fromJS(vm: *jsc.VirtualMachine, opts: jsc.JSValue, globalObject: *jsc.JSGlobalObject, is_server: bool) bun.JSError!SocketConfig { + var hostname_or_unix: jsc.ZigString.Slice = jsc.ZigString.Slice.empty; errdefer hostname_or_unix.deinit(); var port: ?u16 = null; var fd: ?bun.FileDescriptor = null; @@ -246,16 +246,16 @@ pub const SocketConfig = struct { var reusePort = false; var ipv6Only = false; - var ssl: ?JSC.API.ServerConfig.SSLConfig = null; + var ssl: ?jsc.API.ServerConfig.SSLConfig = null; var default_data = JSValue.zero; if (try opts.getTruthy(globalObject, "tls")) |tls| { if (tls.isBoolean()) { if (tls.toBoolean()) { - ssl = JSC.API.ServerConfig.SSLConfig.zero; + ssl = jsc.API.ServerConfig.SSLConfig.zero; } } else { - if (try JSC.API.ServerConfig.SSLConfig.fromJS(vm, globalObject, tls)) |ssl_config| { + if (try jsc.API.ServerConfig.SSLConfig.fromJS(vm, globalObject, tls)) |ssl_config| { ssl = ssl_config; } } @@ -383,8 +383,8 @@ const Environment = bun.Environment; const strings = bun.strings; const uws = bun.uws; -const JSC = bun.JSC; -const JSValue = JSC.JSValue; -const ZigString = JSC.ZigString; -const BinaryType = JSC.ArrayBuffer.BinaryType; -const Listener = JSC.API.Listener; +const jsc = bun.jsc; +const JSValue = jsc.JSValue; +const ZigString = jsc.ZigString; +const BinaryType = jsc.ArrayBuffer.BinaryType; +const Listener = jsc.API.Listener; diff --git a/src/bun.js/api/bun/socket/Listener.zig b/src/bun.js/api/bun/socket/Listener.zig index 7d6012687b..d87cd2bf6d 100644 --- a/src/bun.js/api/bun/socket/Listener.zig +++ b/src/bun.js/api/bun/socket/Listener.zig @@ -11,10 +11,10 @@ socket_context: ?*uws.SocketContext = null, ssl: bool = false, protos: ?[]const u8 = null, -strong_data: JSC.Strong.Optional = .empty, -strong_self: JSC.Strong.Optional = .empty, +strong_data: jsc.Strong.Optional = .empty, +strong_self: jsc.Strong.Optional = .empty, -pub const js = JSC.Codegen.JSListener; +pub const js = jsc.Codegen.JSListener; pub const toJS = js.toJS; pub const fromJS = js.fromJS; pub const fromJSDirect = js.fromJSDirect; @@ -25,12 +25,12 @@ pub const ListenerType = union(enum) { none: void, }; -pub fn getData(this: *Listener, _: *JSC.JSGlobalObject) JSValue { +pub fn getData(this: *Listener, _: *jsc.JSGlobalObject) JSValue { log("getData()", .{}); return this.strong_data.get() orelse .js_undefined; } -pub fn setData(this: *Listener, globalObject: *JSC.JSGlobalObject, value: JSC.JSValue) void { +pub fn setData(this: *Listener, globalObject: *jsc.JSGlobalObject, value: jsc.JSValue) void { log("setData()", .{}); this.strong_data.set(globalObject, value); } @@ -75,7 +75,7 @@ pub const UnixOrHost = union(enum) { } }; -pub fn reload(this: *Listener, globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { +pub fn reload(this: *Listener, globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { const args = callframe.arguments_old(1); if (args.len < 1 or (this.listener == .none and this.handlers.active_connections == 0)) { @@ -102,13 +102,13 @@ pub fn reload(this: *Listener, globalObject: *JSC.JSGlobalObject, callframe: *JS return .js_undefined; } -pub fn listen(globalObject: *JSC.JSGlobalObject, opts: JSValue) bun.JSError!JSValue { +pub fn listen(globalObject: *jsc.JSGlobalObject, opts: JSValue) bun.JSError!JSValue { log("listen", .{}); if (opts.isEmptyOrUndefinedOrNull() or opts.isBoolean() or !opts.isObject()) { return globalObject.throwInvalidArguments("Expected object", .{}); } - const vm = JSC.VirtualMachine.get(); + const vm = jsc.VirtualMachine.get(); var socket_config = try SocketConfig.fromJS(vm, opts, globalObject, true); @@ -173,7 +173,7 @@ pub fn listen(globalObject: *JSC.JSGlobalObject, opts: JSValue) bun.JSError!JSVa } } const ctx_opts: uws.SocketContext.BunSocketContextOptions = if (ssl != null) - JSC.API.ServerConfig.SSLConfig.asUSockets(ssl.?) + jsc.API.ServerConfig.SSLConfig.asUSockets(ssl.?) else .{}; @@ -338,7 +338,7 @@ pub fn onCreateTCP(socket: uws.NewSocketHandler(false)) void { onCreate(false, socket); } -pub fn constructor(globalObject: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!*Listener { +pub fn constructor(globalObject: *jsc.JSGlobalObject, _: *jsc.CallFrame) bun.JSError!*Listener { return globalObject.throw("Cannot construct Listener", .{}); } @@ -365,7 +365,7 @@ pub fn onNamePipeCreated(comptime ssl: bool, listener: *Listener) *NewSocket(ssl } pub fn onCreate(comptime ssl: bool, socket: uws.NewSocketHandler(ssl)) void { - JSC.markBinding(@src()); + jsc.markBinding(@src()); log("onCreate", .{}); //PS: We dont reach this path when using named pipes on windows see onNamePipeCreated @@ -393,7 +393,7 @@ pub fn onCreate(comptime ssl: bool, socket: uws.NewSocketHandler(ssl)) void { socket.setTimeout(120); } -pub fn addServerName(this: *Listener, global: *JSC.JSGlobalObject, hostname: JSValue, tls: JSValue) bun.JSError!JSValue { +pub fn addServerName(this: *Listener, global: *jsc.JSGlobalObject, hostname: JSValue, tls: JSValue) bun.JSError!JSValue { if (!this.ssl) { return global.throwInvalidArguments("addServerName requires SSL support", .{}); } @@ -411,7 +411,7 @@ pub fn addServerName(this: *Listener, global: *JSC.JSGlobalObject, hostname: JSV return global.throwInvalidArguments("hostname pattern cannot be empty", .{}); } - if (try JSC.API.ServerConfig.SSLConfig.fromJS(JSC.VirtualMachine.get(), global, tls)) |ssl_config| { + if (try jsc.API.ServerConfig.SSLConfig.fromJS(jsc.VirtualMachine.get(), global, tls)) |ssl_config| { // to keep nodejs compatibility, we allow to replace the server name this.socket_context.?.removeServerName(true, server_name); this.socket_context.?.addServerName(true, server_name, ssl_config.asUSockets()); @@ -420,12 +420,12 @@ pub fn addServerName(this: *Listener, global: *JSC.JSGlobalObject, hostname: JSV return .js_undefined; } -pub fn dispose(this: *Listener, _: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!JSValue { +pub fn dispose(this: *Listener, _: *jsc.JSGlobalObject, _: *jsc.CallFrame) bun.JSError!JSValue { this.doStop(true); return .js_undefined; } -pub fn stop(this: *Listener, _: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { +pub fn stop(this: *Listener, _: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { const arguments = callframe.arguments_old(1); log("close", .{}); @@ -505,11 +505,11 @@ pub fn deinit(this: *Listener) void { bun.default_allocator.destroy(this); } -pub fn getConnectionsCount(this: *Listener, _: *JSC.JSGlobalObject) JSValue { +pub fn getConnectionsCount(this: *Listener, _: *jsc.JSGlobalObject) JSValue { return JSValue.jsNumber(this.handlers.active_connections); } -pub fn getUnix(this: *Listener, globalObject: *JSC.JSGlobalObject) JSValue { +pub fn getUnix(this: *Listener, globalObject: *jsc.JSGlobalObject) JSValue { if (this.connection != .unix) { return .js_undefined; } @@ -517,21 +517,21 @@ pub fn getUnix(this: *Listener, globalObject: *JSC.JSGlobalObject) JSValue { return ZigString.init(this.connection.unix).withEncoding().toJS(globalObject); } -pub fn getHostname(this: *Listener, globalObject: *JSC.JSGlobalObject) JSValue { +pub fn getHostname(this: *Listener, globalObject: *jsc.JSGlobalObject) JSValue { if (this.connection != .host) { return .js_undefined; } return ZigString.init(this.connection.host.host).withEncoding().toJS(globalObject); } -pub fn getPort(this: *Listener, _: *JSC.JSGlobalObject) JSValue { +pub fn getPort(this: *Listener, _: *jsc.JSGlobalObject) JSValue { if (this.connection != .host) { return .js_undefined; } return JSValue.jsNumber(this.connection.host.port); } -pub fn ref(this: *Listener, globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { +pub fn ref(this: *Listener, globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { const this_value = callframe.this(); if (this.listener == .none) return .js_undefined; this.poll_ref.ref(globalObject.bunVM()); @@ -539,7 +539,7 @@ pub fn ref(this: *Listener, globalObject: *JSC.JSGlobalObject, callframe: *JSC.C return .js_undefined; } -pub fn unref(this: *Listener, globalObject: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!JSValue { +pub fn unref(this: *Listener, globalObject: *jsc.JSGlobalObject, _: *jsc.CallFrame) bun.JSError!JSValue { this.poll_ref.unref(globalObject.bunVM()); if (this.handlers.active_connections == 0) { this.strong_self.clearWithoutDeallocation(); @@ -547,11 +547,11 @@ pub fn unref(this: *Listener, globalObject: *JSC.JSGlobalObject, _: *JSC.CallFra return .js_undefined; } -pub fn connect(globalObject: *JSC.JSGlobalObject, opts: JSValue) bun.JSError!JSValue { +pub fn connect(globalObject: *jsc.JSGlobalObject, opts: JSValue) bun.JSError!JSValue { return connectInner(globalObject, null, null, opts); } -pub fn connectInner(globalObject: *JSC.JSGlobalObject, prev_maybe_tcp: ?*TCPSocket, prev_maybe_tls: ?*TLSSocket, opts: JSValue) bun.JSError!JSValue { +pub fn connectInner(globalObject: *jsc.JSGlobalObject, prev_maybe_tcp: ?*TCPSocket, prev_maybe_tls: ?*TLSSocket, opts: JSValue) bun.JSError!JSValue { if (opts.isEmptyOrUndefinedOrNull() or opts.isBoolean() or !opts.isObject()) { return globalObject.throwInvalidArguments("Expected options object", .{}); } @@ -620,7 +620,7 @@ pub fn connectInner(globalObject: *JSC.JSGlobalObject, prev_maybe_tcp: ?*TCPSock var handlers_ptr = handlers.vm.allocator.create(Handlers) catch bun.outOfMemory(); handlers_ptr.* = handlers; - var promise = JSC.JSPromise.create(globalObject); + var promise = jsc.JSPromise.create(globalObject); const promise_value = promise.toJS(); handlers_ptr.promise.set(globalObject, promise_value); @@ -702,7 +702,7 @@ pub fn connectInner(globalObject: *JSC.JSGlobalObject, prev_maybe_tcp: ?*TCPSock } const ctx_opts: uws.SocketContext.BunSocketContextOptions = if (ssl != null) - JSC.API.ServerConfig.SSLConfig.asUSockets(ssl.?) + jsc.API.ServerConfig.SSLConfig.asUSockets(ssl.?) else .{}; @@ -711,7 +711,7 @@ pub fn connectInner(globalObject: *JSC.JSGlobalObject, prev_maybe_tcp: ?*TCPSock true => uws.SocketContext.createSSLContext(uws.Loop.get(), @sizeOf(usize), ctx_opts, &create_err), false => uws.SocketContext.createNoSSLContext(uws.Loop.get(), @sizeOf(usize)), } orelse { - const err = JSC.SystemError{ + const err = jsc.SystemError{ .message = bun.String.static("Failed to connect"), .syscall = bun.String.static("connect"), .code = if (port == null) bun.String.static("ENOENT") else bun.String.static("ECONNREFUSED"), @@ -739,7 +739,7 @@ pub fn connectInner(globalObject: *JSC.JSGlobalObject, prev_maybe_tcp: ?*TCPSock handlers_ptr.* = handlers; handlers_ptr.is_server = false; - var promise = JSC.JSPromise.create(globalObject); + var promise = jsc.JSPromise.create(globalObject); const promise_value = promise.toJS(); handlers_ptr.promise.set(globalObject, promise_value); @@ -784,7 +784,7 @@ pub fn connectInner(globalObject: *JSC.JSGlobalObject, prev_maybe_tcp: ?*TCPSock } } -pub fn getsockname(this: *Listener, globalThis: *JSC.JSGlobalObject, callFrame: *JSC.CallFrame) bun.JSError!JSValue { +pub fn getsockname(this: *Listener, globalThis: *jsc.JSGlobalObject, callFrame: *jsc.CallFrame) bun.JSError!JSValue { if (this.listener != .uws) { return .js_undefined; } @@ -814,8 +814,8 @@ pub fn getsockname(this: *Listener, globalThis: *JSC.JSGlobalObject, callFrame: return .js_undefined; } -pub fn jsAddServerName(global: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { - JSC.markBinding(@src()); +pub fn jsAddServerName(global: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { + jsc.markBinding(@src()); const arguments = callframe.arguments_old(3); if (arguments.len < 3) { @@ -865,8 +865,8 @@ fn normalizePipeName(pipe_name: []const u8, buffer: []u8) ?[]const u8 { pub const WindowsNamedPipeListeningContext = if (Environment.isWindows) struct { uvPipe: uv.Pipe = std.mem.zeroes(uv.Pipe), listener: ?*Listener, - globalThis: *JSC.JSGlobalObject, - vm: *JSC.VirtualMachine, + globalThis: *jsc.JSGlobalObject, + vm: *jsc.VirtualMachine, ctx: ?*BoringSSL.SSL_CTX = null, // server reuses the same ctx pub const new = bun.TrivialNew(WindowsNamedPipeListeningContext); @@ -904,7 +904,7 @@ pub const WindowsNamedPipeListeningContext = if (Environment.isWindows) struct { this.uvPipe.close(onPipeClosed); } - pub fn listen(globalThis: *JSC.JSGlobalObject, path: []const u8, backlog: i32, ssl_config: ?JSC.API.ServerConfig.SSLConfig, listener: *Listener) !*WindowsNamedPipeListeningContext { + pub fn listen(globalThis: *jsc.JSGlobalObject, path: []const u8, backlog: i32, ssl_config: ?jsc.API.ServerConfig.SSLConfig, listener: *Listener) !*WindowsNamedPipeListeningContext { const this = WindowsNamedPipeListeningContext.new(.{ .globalThis = globalThis, .vm = globalThis.bunVM(), @@ -914,7 +914,7 @@ pub const WindowsNamedPipeListeningContext = if (Environment.isWindows) struct { if (ssl_config) |ssl_options| { bun.BoringSSL.load(); - const ctx_opts: uws.SocketContext.BunSocketContextOptions = JSC.API.ServerConfig.SSLConfig.asUSockets(ssl_options); + const ctx_opts: uws.SocketContext.BunSocketContextOptions = jsc.API.ServerConfig.SSLConfig.asUSockets(ssl_options); var err: uws.create_bun_socket_error_t = .none; // Create SSL context using uSockets to match behavior of node.js const ctx = ctx_opts.createSSLContext(&err) orelse return error.InvalidOptions; // invalid options @@ -960,7 +960,7 @@ pub const WindowsNamedPipeListeningContext = if (Environment.isWindows) struct { fn deinitInNextTick(this: *WindowsNamedPipeListeningContext) void { bun.assert(this.task_event != .deinit); this.task_event = .deinit; - this.vm.enqueueTask(JSC.Task.init(&this.task)); + this.vm.enqueueTask(jsc.Task.init(&this.task)); } fn deinit(this: *WindowsNamedPipeListeningContext) void { @@ -973,30 +973,31 @@ pub const WindowsNamedPipeListeningContext = if (Environment.isWindows) struct { } } else void; -const std = @import("std"); +const string = []const u8; -const socket_ = @import("../socket.zig"); -const NewSocket = socket_.NewSocket; -const SocketConfig = socket_.SocketConfig; -const WindowsNamedPipeContext = socket_.WindowsNamedPipeContext; +const std = @import("std"); const bun = @import("bun"); const Async = bun.Async; const Environment = bun.Environment; const Output = bun.Output; +const api = bun.api; const default_allocator = bun.default_allocator; -const string = bun.string; const strings = bun.strings; const uws = bun.uws; const BoringSSL = bun.BoringSSL.c; const uv = bun.windows.libuv; -const JSC = bun.JSC; -const JSGlobalObject = JSC.JSGlobalObject; -const JSValue = JSC.JSValue; -const ZigString = JSC.ZigString; -const NodePath = JSC.Node.path; +const NewSocket = api.socket.NewSocket; +const SocketConfig = api.socket.SocketConfig; +const WindowsNamedPipeContext = api.socket.WindowsNamedPipeContext; -const Handlers = JSC.API.SocketHandlers; -const TCPSocket = JSC.API.TCPSocket; -const TLSSocket = JSC.API.TLSSocket; +const jsc = bun.jsc; +const JSGlobalObject = jsc.JSGlobalObject; +const JSValue = jsc.JSValue; +const ZigString = jsc.ZigString; +const NodePath = jsc.Node.path; + +const Handlers = jsc.API.SocketHandlers; +const TCPSocket = jsc.API.TCPSocket; +const TLSSocket = jsc.API.TLSSocket; diff --git a/src/bun.js/api/bun/socket/SocketAddress.zig b/src/bun.js/api/bun/socket/SocketAddress.zig index 3e10710b3a..25af0145db 100644 --- a/src/bun.js/api/bun/socket/SocketAddress.zig +++ b/src/bun.js/api/bun/socket/SocketAddress.zig @@ -7,7 +7,7 @@ const SocketAddress = @This(); -pub const js = JSC.Codegen.JSSocketAddress; +pub const js = jsc.Codegen.JSSocketAddress; pub const toJS = js.toJS; pub const fromJS = js.fromJS; pub const fromJSDirect = js.fromJSDirect; @@ -39,7 +39,7 @@ pub const Options = struct { flowlabel: ?u32 = null, /// NOTE: assumes options object has been normalized and validated by JS code. - pub fn fromJS(global: *JSC.JSGlobalObject, obj: JSValue) bun.JSError!Options { + pub fn fromJS(global: *jsc.JSGlobalObject, obj: JSValue) bun.JSError!Options { if (!obj.isObject()) return global.throwInvalidArgumentTypeValue("options", "object", obj); const address_str: ?bun.String = if (try obj.get(global, "address")) |a| addr: { @@ -80,7 +80,7 @@ pub const Options = struct { }; } - inline fn throwBadPort(global: *JSC.JSGlobalObject, port_: JSC.JSValue) bun.JSError { + inline fn throwBadPort(global: *jsc.JSGlobalObject, port_: jsc.JSValue) bun.JSError { const ty = global.determineSpecificType(port_) catch { return global.ERR(.SOCKET_BAD_PORT, "The \"options.port\" argument must be a valid IP port number.", .{}).throw(); }; @@ -95,7 +95,7 @@ pub const Options = struct { /// ### `SocketAddress.parse(input: string): SocketAddress | undefined` /// Parse an address string (with an optional `:port`) into a `SocketAddress`. /// Returns `undefined` if the input is invalid. -pub fn parse(global: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { +pub fn parse(global: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const input = blk: { const input_arg = callframe.argument(0); if (!input_arg.isString()) return global.throwInvalidArgumentTypeValue("input", "string", input_arg); @@ -116,7 +116,7 @@ pub fn parse(global: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError }; defer url_str.deref(); - const url = JSC.URL.fromString(url_str) orelse return .js_undefined; + const url = jsc.URL.fromString(url_str) orelse return .js_undefined; defer url.deinit(); const host = url.host(); const port_: u16 = blk: { @@ -144,7 +144,7 @@ pub fn parse(global: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError /// ### `SocketAddress.isSocketAddress(value: unknown): value is SocketAddress` /// Returns `true` if `value` is a `SocketAddress`. Subclasses and similarly-shaped /// objects are not considered `SocketAddress`s. -pub fn isSocketAddress(_: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { +pub fn isSocketAddress(_: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { const value = callframe.argument(0); return JSValue.jsBoolean(value.isCell() and SocketAddress.fromJSDirect(value) != null); } @@ -161,7 +161,7 @@ pub fn isSocketAddress(_: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JS /// /// ## References /// - [Node docs](https://nodejs.org/api/net.html#new-netsocketaddressoptions) -pub fn constructor(global: *JSC.JSGlobalObject, frame: *JSC.CallFrame) bun.JSError!*SocketAddress { +pub fn constructor(global: *jsc.JSGlobalObject, frame: *jsc.CallFrame) bun.JSError!*SocketAddress { const options_obj = frame.argument(0); if (options_obj.isUndefined()) return SocketAddress.new(.{ ._addr = sockaddr.@"127.0.0.1", @@ -185,7 +185,7 @@ pub fn constructor(global: *JSC.JSGlobalObject, frame: *JSC.CallFrame) bun.JSErr return SocketAddress.create(global, options); } -pub fn initFromAddrFamily(global: *JSC.JSGlobalObject, address_js: JSValue, family_js: JSValue) bun.JSError!SocketAddress { +pub fn initFromAddrFamily(global: *jsc.JSGlobalObject, address_js: JSValue, family_js: JSValue) bun.JSError!SocketAddress { if (!address_js.isString()) return global.throwInvalidArgumentTypeValue("options.address", "string", address_js); const address_: bun.String = try .fromJS(address_js, global); const family_: AF = try .fromJS(global, family_js); @@ -201,11 +201,11 @@ pub fn initFromAddrFamily(global: *JSC.JSGlobalObject, address_js: JSValue, fami /// ## Safety /// - `options.address` gets moved, much like `adoptRef`. Do not `deref` it /// after passing it in. -pub fn create(global: *JSC.JSGlobalObject, options: Options) bun.JSError!*SocketAddress { +pub fn create(global: *jsc.JSGlobalObject, options: Options) bun.JSError!*SocketAddress { return .new(try .initJS(global, options)); } -pub fn initJS(global: *JSC.JSGlobalObject, options: Options) bun.JSError!SocketAddress { +pub fn initJS(global: *jsc.JSGlobalObject, options: Options) bun.JSError!SocketAddress { var presentation: bun.String = .empty; // We need a zero-terminated cstring for `ares_inet_pton`, which forces us to @@ -308,7 +308,7 @@ fn deinit(this: *SocketAddress) void { } pub fn finalize(this: *SocketAddress) void { - JSC.markBinding(@src()); + jsc.markBinding(@src()); this.deinit(); } @@ -326,7 +326,7 @@ pub fn finalize(this: *SocketAddress) void { /// This method is slightly faster if you are creating a lot of socket addresses /// that will not be around for very long. `createDTO` is even faster, but /// requires callers to already have a presentation-formatted address. -pub fn intoDTO(this: *SocketAddress, global: *JSC.JSGlobalObject) JSC.JSValue { +pub fn intoDTO(this: *SocketAddress, global: *jsc.JSGlobalObject) jsc.JSValue { var addr_str = this.address(); defer this._presentation = .dead; return JSSocketAddressDTO__create(global, addr_str.transferToJS(global), this.port(), this.family() == AF.INET6); @@ -338,7 +338,7 @@ pub fn intoDTO(this: *SocketAddress, global: *JSC.JSGlobalObject) JSC.JSValue { /// /// - The address string is assumed to be ASCII and a valid IP address (either v4 or v6). /// - Port is a valid `in_port_t` (between 0 and 2^16) in host byte order. -pub fn createDTO(globalObject: *JSC.JSGlobalObject, addr_: []const u8, port_: u16, is_ipv6: bool) bun.JSError!JSC.JSValue { +pub fn createDTO(globalObject: *jsc.JSGlobalObject, addr_: []const u8, port_: u16, is_ipv6: bool) bun.JSError!jsc.JSValue { if (comptime bun.Environment.isDebug) { bun.assertWithLocation(addr_.len > 0, @src()); } @@ -346,11 +346,11 @@ pub fn createDTO(globalObject: *JSC.JSGlobalObject, addr_: []const u8, port_: u1 return JSSocketAddressDTO__create(globalObject, try bun.String.createUTF8ForJS(globalObject, addr_), port_, is_ipv6); } -extern "c" fn JSSocketAddressDTO__create(globalObject: *JSC.JSGlobalObject, address_: JSC.JSValue, port_: u16, is_ipv6: bool) JSC.JSValue; +extern "c" fn JSSocketAddressDTO__create(globalObject: *jsc.JSGlobalObject, address_: jsc.JSValue, port_: u16, is_ipv6: bool) jsc.JSValue; // ============================================================================= -pub fn getAddress(this: *SocketAddress, global: *JSC.JSGlobalObject) JSC.JSValue { +pub fn getAddress(this: *SocketAddress, global: *jsc.JSGlobalObject) jsc.JSValue { // toJS increments ref count const addr_ = this.address(); return switch (addr_.tag) { @@ -375,7 +375,7 @@ pub fn address(this: *SocketAddress) bun.String { if (this._presentation.tag != .Dead) return this._presentation; var buf: [inet.INET6_ADDRSTRLEN]u8 = undefined; const formatted = this._addr.fmt(&buf); - const presentation = JSC.WebCore.encoding.toBunStringComptime(formatted, .latin1); + const presentation = jsc.WebCore.encoding.toBunStringComptime(formatted, .latin1); bun.debugAssert(presentation.tag != .Dead); this._presentation = presentation; return presentation; @@ -388,7 +388,7 @@ pub fn address(this: *SocketAddress) bun.String { /// /// NOTE: node's `net.SocketAddress` wants `"ipv4"` and `"ipv6"` while Bun's APIs /// use `"IPv4"` and `"IPv6"`. This is annoying. -pub fn getFamily(this: *SocketAddress, global: *JSC.JSGlobalObject) JSValue { +pub fn getFamily(this: *SocketAddress, global: *jsc.JSGlobalObject) JSValue { // NOTE: cannot use global.commonStrings().IPv[4,6]() b/c this needs to be // lower case. return switch (this.family()) { @@ -398,7 +398,7 @@ pub fn getFamily(this: *SocketAddress, global: *JSC.JSGlobalObject) JSValue { } /// `sockaddr.addrfamily` -pub fn getAddrFamily(this: *SocketAddress, _: *JSC.JSGlobalObject) JSValue { +pub fn getAddrFamily(this: *SocketAddress, _: *jsc.JSGlobalObject) JSValue { return JSValue.jsNumber(this.family().int()); } @@ -409,7 +409,7 @@ pub fn family(this: *const SocketAddress) AF { return @enumFromInt(this._addr.sin.family); } -pub fn getPort(this: *SocketAddress, _: *JSC.JSGlobalObject) JSValue { +pub fn getPort(this: *SocketAddress, _: *jsc.JSGlobalObject) JSValue { return JSValue.jsNumber(this.port()); } @@ -421,7 +421,7 @@ pub fn port(this: *const SocketAddress) u16 { return std.mem.bigToNative(u16, this._addr.sin.port); } -pub fn getFlowLabel(this: *SocketAddress, _: *JSC.JSGlobalObject) JSValue { +pub fn getFlowLabel(this: *SocketAddress, _: *jsc.JSGlobalObject) JSValue { return JSValue.jsNumber(this.flowLabel() orelse 0); } @@ -449,8 +449,8 @@ pub fn estimatedSize(this: *SocketAddress) usize { return @sizeOf(SocketAddress) + this._presentation.estimatedSize(); } -pub fn toJSON(this: *SocketAddress, global: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!JSC.JSValue { - return (try JSC.JSObject.create(.{ +pub fn toJSON(this: *SocketAddress, global: *jsc.JSGlobalObject, _: *jsc.CallFrame) bun.JSError!jsc.JSValue { + return (try jsc.JSObject.create(.{ .address = this.getAddress(global), .family = this.getFamily(global), .port = this.port(), @@ -458,7 +458,7 @@ pub fn toJSON(this: *SocketAddress, global: *JSC.JSGlobalObject, _: *JSC.CallFra }, global)).toJS(); } -fn pton(global: *JSC.JSGlobalObject, comptime af: c_int, addr: [:0]const u8, dst: *anyopaque) bun.JSError!void { +fn pton(global: *jsc.JSGlobalObject, comptime af: c_int, addr: [:0]const u8, dst: *anyopaque) bun.JSError!void { return switch (ares.ares_inet_pton(af, addr.ptr, dst)) { 0 => global.throwSysError(.{ .code = .ERR_INVALID_IP_ADDRESS }, "Invalid socket address", .{}), @@ -502,7 +502,7 @@ pub const AF = enum(inet.sa_family_t) { return @intFromEnum(this); } - pub fn fromJS(global: *JSC.JSGlobalObject, value: JSValue) !AF { + pub fn fromJS(global: *jsc.JSGlobalObject, value: JSValue) !AF { if (value.isString()) { const fam_str = try bun.String.fromJS(value, global); defer fam_str.deref(); @@ -677,17 +677,18 @@ win: { }; }; +const string = []const u8; + const bun = @import("bun"); const ares = bun.c_ares; -const string = bun.string; const StaticStringImpl = bun.WTF.StringImpl; const Environment = bun.Environment; const isDebug = bun.Environment.isDebug; -const JSC = bun.JSC; -const CallFrame = JSC.CallFrame; -const JSValue = JSC.JSValue; +const jsc = bun.jsc; +const CallFrame = jsc.CallFrame; +const JSValue = jsc.JSValue; const std = @import("std"); const net = std.net; diff --git a/src/bun.js/api/bun/socket/WindowsNamedPipeContext.zig b/src/bun.js/api/bun/socket/WindowsNamedPipeContext.zig index 020abf7bed..d51ee8b0d7 100644 --- a/src/bun.js/api/bun/socket/WindowsNamedPipeContext.zig +++ b/src/bun.js/api/bun/socket/WindowsNamedPipeContext.zig @@ -4,9 +4,9 @@ named_pipe: uws.WindowsNamedPipe, socket: SocketType, // task used to deinit the context in the next tick, vm is used to enqueue the task -vm: *JSC.VirtualMachine, -globalThis: *JSC.JSGlobalObject, -task: JSC.AnyTask, +vm: *jsc.VirtualMachine, +globalThis: *jsc.JSGlobalObject, +task: jsc.AnyTask, task_event: EventState = .none, is_open: bool = false, @@ -163,10 +163,10 @@ fn runEvent(this: *WindowsNamedPipeContext) void { fn deinitInNextTick(this: *WindowsNamedPipeContext) void { bun.assert(this.task_event != .deinit); this.task_event = .deinit; - this.vm.enqueueTask(JSC.Task.init(&this.task)); + this.vm.enqueueTask(jsc.Task.init(&this.task)); } -pub fn create(globalThis: *JSC.JSGlobalObject, socket: SocketType) *WindowsNamedPipeContext { +pub fn create(globalThis: *jsc.JSGlobalObject, socket: SocketType) *WindowsNamedPipeContext { const vm = globalThis.bunVM(); const this = WindowsNamedPipeContext.new(.{ .vm = vm, @@ -188,7 +188,7 @@ pub fn create(globalThis: *JSC.JSGlobalObject, socket: SocketType) *WindowsNamed .onTimeout = @ptrCast(&WindowsNamedPipeContext.onTimeout), .onClose = @ptrCast(&WindowsNamedPipeContext.onClose), }, vm); - this.task = JSC.AnyTask.New(WindowsNamedPipeContext, WindowsNamedPipeContext.runEvent).init(this); + this.task = jsc.AnyTask.New(WindowsNamedPipeContext, WindowsNamedPipeContext.runEvent).init(this); switch (socket) { .tls => |tls| { @@ -203,7 +203,7 @@ pub fn create(globalThis: *JSC.JSGlobalObject, socket: SocketType) *WindowsNamed return this; } -pub fn open(globalThis: *JSC.JSGlobalObject, fd: bun.FileDescriptor, ssl_config: ?JSC.API.ServerConfig.SSLConfig, socket: SocketType) !*uws.WindowsNamedPipe { +pub fn open(globalThis: *jsc.JSGlobalObject, fd: bun.FileDescriptor, ssl_config: ?jsc.API.ServerConfig.SSLConfig, socket: SocketType) !*uws.WindowsNamedPipe { // TODO: reuse the same context for multiple connections when possibles const this = WindowsNamedPipeContext.create(globalThis, socket); @@ -224,7 +224,7 @@ pub fn open(globalThis: *JSC.JSGlobalObject, fd: bun.FileDescriptor, ssl_config: return &this.named_pipe; } -pub fn connect(globalThis: *JSC.JSGlobalObject, path: []const u8, ssl_config: ?JSC.API.ServerConfig.SSLConfig, socket: SocketType) !*uws.WindowsNamedPipe { +pub fn connect(globalThis: *jsc.JSGlobalObject, path: []const u8, ssl_config: ?jsc.API.ServerConfig.SSLConfig, socket: SocketType) !*uws.WindowsNamedPipe { // TODO: reuse the same context for multiple connections when possibles const this = WindowsNamedPipeContext.create(globalThis, socket); @@ -277,10 +277,10 @@ pub fn deinit(this: *WindowsNamedPipeContext) void { } const bun = @import("bun"); -const JSC = bun.JSC; const Output = bun.Output; +const jsc = bun.jsc; const uws = bun.uws; const uv = bun.windows.libuv; -const TCPSocket = JSC.API.TCPSocket; -const TLSSocket = JSC.API.TLSSocket; +const TCPSocket = jsc.API.TCPSocket; +const TLSSocket = jsc.API.TLSSocket; diff --git a/src/bun.js/api/bun/socket/tls_socket_functions.zig b/src/bun.js/api/bun/socket/tls_socket_functions.zig index c5dd48160f..37e6b84c42 100644 --- a/src/bun.js/api/bun/socket/tls_socket_functions.zig +++ b/src/bun.js/api/bun/socket/tls_socket_functions.zig @@ -1,4 +1,4 @@ -pub fn getServername(this: *This, globalObject: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!JSValue { +pub fn getServername(this: *This, globalObject: *jsc.JSGlobalObject, _: *jsc.CallFrame) bun.JSError!JSValue { const ssl_ptr = this.socket.ssl(); const servername = BoringSSL.SSL_get_servername(ssl_ptr, BoringSSL.TLSEXT_NAMETYPE_host_name); @@ -8,7 +8,7 @@ pub fn getServername(this: *This, globalObject: *JSC.JSGlobalObject, _: *JSC.Cal return ZigString.fromUTF8(servername[0..bun.len(servername)]).toJS(globalObject); } -pub fn setServername(this: *This, globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { +pub fn setServername(this: *This, globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { if (this.handlers.is_server) { return globalObject.throw("Cannot issue SNI from a TLS server-side socket", .{}); } @@ -47,7 +47,7 @@ pub fn setServername(this: *This, globalObject: *JSC.JSGlobalObject, callframe: return .js_undefined; } -pub fn getPeerX509Certificate(this: *This, globalObject: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!JSValue { +pub fn getPeerX509Certificate(this: *This, globalObject: *jsc.JSGlobalObject, _: *jsc.CallFrame) bun.JSError!JSValue { const ssl_ptr = this.socket.ssl() orelse return .js_undefined; const cert = BoringSSL.SSL_get_peer_certificate(ssl_ptr); if (cert) |x509| { @@ -56,7 +56,7 @@ pub fn getPeerX509Certificate(this: *This, globalObject: *JSC.JSGlobalObject, _: return .js_undefined; } -pub fn getX509Certificate(this: *This, globalObject: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!JSValue { +pub fn getX509Certificate(this: *This, globalObject: *jsc.JSGlobalObject, _: *jsc.CallFrame) bun.JSError!JSValue { const ssl_ptr = this.socket.ssl() orelse return .js_undefined; const cert = BoringSSL.SSL_get_certificate(ssl_ptr); if (cert) |x509| { @@ -65,8 +65,8 @@ pub fn getX509Certificate(this: *This, globalObject: *JSC.JSGlobalObject, _: *JS return .js_undefined; } -pub fn getTLSVersion(this: *This, globalObject: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!JSValue { - JSC.markBinding(@src()); +pub fn getTLSVersion(this: *This, globalObject: *jsc.JSGlobalObject, _: *jsc.CallFrame) bun.JSError!JSValue { + jsc.markBinding(@src()); const ssl_ptr = this.socket.ssl() orelse return JSValue.jsNull(); const version = BoringSSL.SSL_get_version(ssl_ptr); @@ -77,8 +77,8 @@ pub fn getTLSVersion(this: *This, globalObject: *JSC.JSGlobalObject, _: *JSC.Cal return ZigString.fromUTF8(slice).toJS(globalObject); } -pub fn setMaxSendFragment(this: *This, globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { - JSC.markBinding(@src()); +pub fn setMaxSendFragment(this: *This, globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { + jsc.markBinding(@src()); const args = callframe.arguments_old(1); @@ -102,8 +102,8 @@ pub fn setMaxSendFragment(this: *This, globalObject: *JSC.JSGlobalObject, callfr return JSValue.jsBoolean(BoringSSL.SSL_set_max_send_fragment(ssl_ptr, @as(usize, @intCast(size))) == 1); } -pub fn getPeerCertificate(this: *This, globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { - JSC.markBinding(@src()); +pub fn getPeerCertificate(this: *This, globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { + jsc.markBinding(@src()); const args = callframe.arguments_old(1); var abbreviated: bool = true; @@ -145,7 +145,7 @@ pub fn getPeerCertificate(this: *This, globalObject: *JSC.JSGlobalObject, callfr return .js_undefined; } -pub fn getCertificate(this: *This, globalObject: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!JSValue { +pub fn getCertificate(this: *This, globalObject: *jsc.JSGlobalObject, _: *jsc.CallFrame) bun.JSError!JSValue { const ssl_ptr = this.socket.ssl() orelse return .js_undefined; const cert = BoringSSL.SSL_get_certificate(ssl_ptr); @@ -155,7 +155,7 @@ pub fn getCertificate(this: *This, globalObject: *JSC.JSGlobalObject, _: *JSC.Ca return .js_undefined; } -pub fn getTLSFinishedMessage(this: *This, globalObject: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!JSValue { +pub fn getTLSFinishedMessage(this: *This, globalObject: *jsc.JSGlobalObject, _: *jsc.CallFrame) bun.JSError!JSValue { const ssl_ptr = this.socket.ssl() orelse return .js_undefined; // We cannot just pass nullptr to SSL_get_finished() // because it would further be propagated to memcpy(), @@ -175,14 +175,14 @@ pub fn getTLSFinishedMessage(this: *This, globalObject: *JSC.JSGlobalObject, _: return buffer; } -pub fn getSharedSigalgs(this: *This, globalObject: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!JSValue { - JSC.markBinding(@src()); +pub fn getSharedSigalgs(this: *This, globalObject: *jsc.JSGlobalObject, _: *jsc.CallFrame) bun.JSError!JSValue { + jsc.markBinding(@src()); const ssl_ptr = this.socket.ssl() orelse return JSValue.jsNull(); const nsig = BoringSSL.SSL_get_shared_sigalgs(ssl_ptr, 0, null, null, null, null, null); - const array = try JSC.JSValue.createEmptyArray(globalObject, @as(usize, @intCast(nsig))); + const array = try jsc.JSValue.createEmptyArray(globalObject, @as(usize, @intCast(nsig))); for (0..@as(usize, @intCast(nsig))) |i| { var hash_nid: c_int = 0; @@ -243,20 +243,20 @@ pub fn getSharedSigalgs(this: *This, globalObject: *JSC.JSGlobalObject, _: *JSC. bun.copy(u8, buffer, sig_with_md); buffer[sig_with_md.len] = '+'; bun.copy(u8, buffer[sig_with_md.len + 1 ..], hash_slice); - try array.putIndex(globalObject, @as(u32, @intCast(i)), JSC.ZigString.fromUTF8(buffer).toJS(globalObject)); + try array.putIndex(globalObject, @as(u32, @intCast(i)), jsc.ZigString.fromUTF8(buffer).toJS(globalObject)); } else { const buffer = bun.default_allocator.alloc(u8, sig_with_md.len + 6) catch bun.outOfMemory(); defer bun.default_allocator.free(buffer); bun.copy(u8, buffer, sig_with_md); bun.copy(u8, buffer[sig_with_md.len..], "+UNDEF"); - try array.putIndex(globalObject, @as(u32, @intCast(i)), JSC.ZigString.fromUTF8(buffer).toJS(globalObject)); + try array.putIndex(globalObject, @as(u32, @intCast(i)), jsc.ZigString.fromUTF8(buffer).toJS(globalObject)); } } return array; } -pub fn getCipher(this: *This, globalObject: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!JSValue { +pub fn getCipher(this: *This, globalObject: *jsc.JSGlobalObject, _: *jsc.CallFrame) bun.JSError!JSValue { const ssl_ptr = this.socket.ssl() orelse return .js_undefined; const cipher = BoringSSL.SSL_get_current_cipher(ssl_ptr); var result = JSValue.createEmptyObject(globalObject, 3); @@ -292,7 +292,7 @@ pub fn getCipher(this: *This, globalObject: *JSC.JSGlobalObject, _: *JSC.CallFra return result; } -pub fn getTLSPeerFinishedMessage(this: *This, globalObject: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!JSValue { +pub fn getTLSPeerFinishedMessage(this: *This, globalObject: *jsc.JSGlobalObject, _: *jsc.CallFrame) bun.JSError!JSValue { const ssl_ptr = this.socket.ssl() orelse return .js_undefined; // We cannot just pass nullptr to SSL_get_peer_finished() // because it would further be propagated to memcpy(), @@ -312,7 +312,7 @@ pub fn getTLSPeerFinishedMessage(this: *This, globalObject: *JSC.JSGlobalObject, return buffer; } -pub fn exportKeyingMaterial(this: *This, globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { +pub fn exportKeyingMaterial(this: *This, globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { if (this.socket.isDetached()) { return .js_undefined; } @@ -348,7 +348,7 @@ pub fn exportKeyingMaterial(this: *This, globalObject: *JSC.JSGlobalObject, call var arena: bun.ArenaAllocator = bun.ArenaAllocator.init(bun.default_allocator); defer arena.deinit(); - if (try JSC.Node.StringOrBuffer.fromJS(globalObject, arena.allocator(), context_arg)) |sb| { + if (try jsc.Node.StringOrBuffer.fromJS(globalObject, arena.allocator(), context_arg)) |sb| { defer sb.deinit(); const context_slice = sb.slice(); @@ -377,7 +377,7 @@ pub fn exportKeyingMaterial(this: *This, globalObject: *JSC.JSGlobalObject, call } } -pub fn getEphemeralKeyInfo(this: *This, globalObject: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!JSValue { +pub fn getEphemeralKeyInfo(this: *This, globalObject: *jsc.JSGlobalObject, _: *jsc.CallFrame) bun.JSError!JSValue { // only available for clients if (this.handlers.is_server) { @@ -436,7 +436,7 @@ pub fn getEphemeralKeyInfo(this: *This, globalObject: *JSC.JSGlobalObject, _: *J return result; } -pub fn getALPNProtocol(this: *This, globalObject: *JSC.JSGlobalObject) bun.JSError!JSValue { +pub fn getALPNProtocol(this: *This, globalObject: *jsc.JSGlobalObject) bun.JSError!JSValue { var alpn_proto: [*c]const u8 = null; var alpn_proto_len: u32 = 0; @@ -457,7 +457,7 @@ pub fn getALPNProtocol(this: *This, globalObject: *JSC.JSGlobalObject) bun.JSErr return ZigString.fromUTF8(slice).toJS(globalObject); } -pub fn getSession(this: *This, globalObject: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!JSValue { +pub fn getSession(this: *This, globalObject: *jsc.JSGlobalObject, _: *jsc.CallFrame) bun.JSError!JSValue { const ssl_ptr = this.socket.ssl() orelse return .js_undefined; const session = BoringSSL.SSL_get_session(ssl_ptr) orelse return .js_undefined; const size = BoringSSL.i2d_SSL_SESSION(session, null); @@ -474,7 +474,7 @@ pub fn getSession(this: *This, globalObject: *JSC.JSGlobalObject, _: *JSC.CallFr return buffer; } -pub fn setSession(this: *This, globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { +pub fn setSession(this: *This, globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { if (this.socket.isDetached()) { return .js_undefined; } @@ -489,7 +489,7 @@ pub fn setSession(this: *This, globalObject: *JSC.JSGlobalObject, callframe: *JS var arena: bun.ArenaAllocator = bun.ArenaAllocator.init(bun.default_allocator); defer arena.deinit(); - if (try JSC.Node.StringOrBuffer.fromJS(globalObject, arena.allocator(), session_arg)) |sb| { + if (try jsc.Node.StringOrBuffer.fromJS(globalObject, arena.allocator(), session_arg)) |sb| { defer sb.deinit(); const session_slice = sb.slice(); const ssl_ptr = this.socket.ssl(); @@ -504,7 +504,7 @@ pub fn setSession(this: *This, globalObject: *JSC.JSGlobalObject, callframe: *JS } } -pub fn getTLSTicket(this: *This, globalObject: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!JSValue { +pub fn getTLSTicket(this: *This, globalObject: *jsc.JSGlobalObject, _: *jsc.CallFrame) bun.JSError!JSValue { const ssl_ptr = this.socket.ssl() orelse return .js_undefined; const session = BoringSSL.SSL_get_session(ssl_ptr) orelse return .js_undefined; var ticket: [*c]const u8 = undefined; @@ -516,10 +516,10 @@ pub fn getTLSTicket(this: *This, globalObject: *JSC.JSGlobalObject, _: *JSC.Call return .js_undefined; } - return JSC.ArrayBuffer.createBuffer(globalObject, ticket[0..length]); + return jsc.ArrayBuffer.createBuffer(globalObject, ticket[0..length]); } -pub fn renegotiate(this: *This, globalObject: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!JSValue { +pub fn renegotiate(this: *This, globalObject: *jsc.JSGlobalObject, _: *jsc.CallFrame) bun.JSError!JSValue { const ssl_ptr = this.socket.ssl() orelse return .js_undefined; BoringSSL.ERR_clear_error(); if (BoringSSL.SSL_renegotiate(ssl_ptr) != 1) { @@ -528,13 +528,13 @@ pub fn renegotiate(this: *This, globalObject: *JSC.JSGlobalObject, _: *JSC.CallF return .js_undefined; } -pub fn disableRenegotiation(this: *This, _: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!JSValue { +pub fn disableRenegotiation(this: *This, _: *jsc.JSGlobalObject, _: *jsc.CallFrame) bun.JSError!JSValue { const ssl_ptr = this.socket.ssl() orelse return .js_undefined; BoringSSL.SSL_set_renegotiate_mode(ssl_ptr, BoringSSL.ssl_renegotiate_never); return .js_undefined; } -pub fn setVerifyMode(this: *This, globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { +pub fn setVerifyMode(this: *This, globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { if (this.socket.isDetached()) { return .js_undefined; } @@ -570,7 +570,7 @@ fn alwaysAllowSSLVerifyCallback(_: c_int, _: ?*BoringSSL.X509_STORE_CTX) callcon return 1; } -noinline fn getSSLException(globalThis: *JSC.JSGlobalObject, defaultMessage: []const u8) JSValue { +noinline fn getSSLException(globalThis: *jsc.JSGlobalObject, defaultMessage: []const u8) JSValue { var zig_str: ZigString = ZigString.init(""); var output_buf: [4096]u8 = undefined; @@ -643,17 +643,18 @@ noinline fn getSSLException(globalThis: *JSC.JSGlobalObject, defaultMessage: []c return exception; } +const string = []const u8; + const X509 = @import("../x509.zig"); const std = @import("std"); const bun = @import("bun"); const default_allocator = bun.default_allocator; -const string = bun.string; const strings = bun.strings; const BoringSSL = bun.BoringSSL.c; -const JSC = bun.JSC; -const JSGlobalObject = JSC.JSGlobalObject; -const JSValue = JSC.JSValue; -const ZigString = JSC.ZigString; -const This = JSC.API.TLSSocket; +const jsc = bun.jsc; +const JSGlobalObject = jsc.JSGlobalObject; +const JSValue = jsc.JSValue; +const ZigString = jsc.ZigString; +const This = jsc.API.TLSSocket; diff --git a/src/bun.js/api/bun/spawn.zig b/src/bun.js/api/bun/spawn.zig index 514dc87bc9..d85a7afe26 100644 --- a/src/bun.js/api/bun/spawn.zig +++ b/src/bun.js/api/bun/spawn.zig @@ -386,7 +386,7 @@ pub const PosixSpawn = struct { }, .INTR => continue, - else => return JSC.Maybe(WaitPidResult).errnoSys(rc, .waitpid).?, + else => return jsc.Maybe(WaitPidResult).errnoSys(rc, .waitpid).?, } } } @@ -406,7 +406,7 @@ pub const PosixSpawn = struct { }, .INTR => continue, - else => return JSC.Maybe(WaitPidResult).errnoSys(rc, .waitpid).?, + else => return jsc.Maybe(WaitPidResult).errnoSys(rc, .waitpid).?, } } } @@ -431,8 +431,8 @@ const std = @import("std"); const bun = @import("bun"); const Environment = bun.Environment; -const JSC = bun.JSC; -const Maybe = JSC.Maybe; +const jsc = bun.jsc; +const Maybe = jsc.Maybe; const errno = std.posix.errno; const fd_t = std.posix.fd_t; diff --git a/src/bun.js/api/bun/spawn/stdio.zig b/src/bun.js/api/bun/spawn/stdio.zig index 40d11161a2..291c800f44 100644 --- a/src/bun.js/api/bun/spawn/stdio.zig +++ b/src/bun.js/api/bun/spawn/stdio.zig @@ -4,16 +4,16 @@ pub const Stdio = union(enum) { ignore, fd: bun.FileDescriptor, dup2: struct { - out: bun.JSC.Subprocess.StdioKind, - to: bun.JSC.Subprocess.StdioKind, + out: bun.jsc.Subprocess.StdioKind, + to: bun.jsc.Subprocess.StdioKind, }, - path: JSC.Node.PathLike, - blob: JSC.WebCore.Blob.Any, - array_buffer: JSC.ArrayBuffer.Strong, + path: jsc.Node.PathLike, + blob: jsc.WebCore.Blob.Any, + array_buffer: jsc.ArrayBuffer.Strong, memfd: bun.FileDescriptor, pipe, ipc, - readable_stream: JSC.WebCore.ReadableStream, + readable_stream: jsc.WebCore.ReadableStream, const log = bun.sys.syslog; @@ -44,7 +44,7 @@ pub const Stdio = union(enum) { }; } - pub fn throwJS(this: *const @This(), globalThis: *JSC.JSGlobalObject) bun.JSError { + pub fn throwJS(this: *const @This(), globalThis: *jsc.JSGlobalObject) bun.JSError { return globalThis.throw("{s}", .{this.toStr()}); } }; @@ -277,7 +277,7 @@ pub const Stdio = union(enum) { }; } - fn extractBodyValue(out_stdio: *Stdio, globalThis: *JSC.JSGlobalObject, i: i32, body: *JSC.WebCore.Body.Value, is_sync: bool) bun.JSError!void { + fn extractBodyValue(out_stdio: *Stdio, globalThis: *jsc.JSGlobalObject, i: i32, body: *jsc.WebCore.Body.Value, is_sync: bool) bun.JSError!void { body.toBlobIfPossible(); if (body.tryUseAsAnyBlob()) |blob| { @@ -315,7 +315,7 @@ pub const Stdio = union(enum) { const stream_value = try body.toReadableStream(globalThis); - const stream = (try JSC.WebCore.ReadableStream.fromJS(stream_value, globalThis)) orelse return globalThis.throwInvalidArguments("Failed to create ReadableStream", .{}); + const stream = (try jsc.WebCore.ReadableStream.fromJS(stream_value, globalThis)) orelse return globalThis.throwInvalidArguments("Failed to create ReadableStream", .{}); if (stream.isDisturbed(globalThis)) { return globalThis.ERR(.BODY_ALREADY_USED, "ReadableStream has already been used", .{}).throw(); @@ -328,7 +328,7 @@ pub const Stdio = union(enum) { return; } - pub fn extract(out_stdio: *Stdio, globalThis: *JSC.JSGlobalObject, i: i32, value: JSValue, is_sync: bool) bun.JSError!void { + pub fn extract(out_stdio: *Stdio, globalThis: *jsc.JSGlobalObject, i: i32, value: JSValue, is_sync: bool) bun.JSError!void { if (value == .zero) return; if (value.isUndefined()) return; if (value.isNull()) { @@ -358,7 +358,7 @@ pub const Stdio = union(enum) { } if (file_fd >= std.math.maxInt(i32)) { - var formatter = JSC.ConsoleObject.Formatter{ .globalThis = globalThis }; + var formatter = jsc.ConsoleObject.Formatter{ .globalThis = globalThis }; defer formatter.deinit(); return globalThis.throwInvalidArguments("file descriptor must be a valid integer, received: {}", .{value.toFmt(&formatter)}); } @@ -388,15 +388,15 @@ pub const Stdio = union(enum) { out_stdio.* = Stdio{ .fd = fd }; return; - } else if (value.as(JSC.WebCore.Blob)) |blob| { + } else if (value.as(jsc.WebCore.Blob)) |blob| { return out_stdio.extractBlob(globalThis, .{ .Blob = blob.dupe() }, i); - } else if (value.as(JSC.WebCore.Request)) |req| { + } else if (value.as(jsc.WebCore.Request)) |req| { return extractBodyValue(out_stdio, globalThis, i, req.getBodyValue(), is_sync); - } else if (value.as(JSC.WebCore.Response)) |res| { + } else if (value.as(jsc.WebCore.Response)) |res| { return extractBodyValue(out_stdio, globalThis, i, res.getBodyValue(), is_sync); } - if (try JSC.WebCore.ReadableStream.fromJS(value, globalThis)) |stream_| { + if (try jsc.WebCore.ReadableStream.fromJS(value, globalThis)) |stream_| { var stream = stream_; if (stream.toAnyBlob(globalThis)) |blob| { return out_stdio.extractBlob(globalThis, blob, i); @@ -428,7 +428,7 @@ pub const Stdio = union(enum) { } out_stdio.* = .{ - .array_buffer = JSC.ArrayBuffer.Strong{ + .array_buffer = jsc.ArrayBuffer.Strong{ .array_buffer = array_buffer, .held = .create(array_buffer.value, globalThis), }, @@ -439,7 +439,7 @@ pub const Stdio = union(enum) { return globalThis.throwInvalidArguments("stdio must be an array of 'inherit', 'ignore', or null", .{}); } - pub fn extractBlob(stdio: *Stdio, globalThis: *JSC.JSGlobalObject, blob: JSC.WebCore.Blob.Any, i: i32) bun.JSError!void { + pub fn extractBlob(stdio: *Stdio, globalThis: *jsc.JSGlobalObject, blob: jsc.WebCore.Blob.Any, i: i32) bun.JSError!void { const fd = bun.FD.Stdio.fromInt(i).?.fd(); if (blob.needsToReadFile()) { @@ -495,6 +495,6 @@ const Output = bun.Output; const default_allocator = bun.default_allocator; const uv = bun.windows.libuv; -const JSC = bun.JSC; -const JSGlobalObject = JSC.JSGlobalObject; -const JSValue = JSC.JSValue; +const jsc = bun.jsc; +const JSGlobalObject = jsc.JSGlobalObject; +const JSValue = jsc.JSValue; diff --git a/src/bun.js/api/bun/ssl_wrapper.zig b/src/bun.js/api/bun/ssl_wrapper.zig index 5d55b53785..be4ed15d02 100644 --- a/src/bun.js/api/bun/ssl_wrapper.zig +++ b/src/bun.js/api/bun/ssl_wrapper.zig @@ -90,10 +90,10 @@ pub fn SSLWrapper(comptime T: type) type { }; } - pub fn init(ssl_options: JSC.API.ServerConfig.SSLConfig, is_client: bool, handlers: Handlers) !This { + pub fn init(ssl_options: jsc.API.ServerConfig.SSLConfig, is_client: bool, handlers: Handlers) !This { bun.BoringSSL.load(); - const ctx_opts: uws.SocketContext.BunSocketContextOptions = JSC.API.ServerConfig.SSLConfig.asUSockets(ssl_options); + const ctx_opts: uws.SocketContext.BunSocketContextOptions = jsc.API.ServerConfig.SSLConfig.asUSockets(ssl_options); var err: uws.create_bun_socket_error_t = .none; // Create SSL context using uSockets to match behavior of node.js const ctx = ctx_opts.createSSLContext(&err) orelse return error.InvalidOptions; // invalid options @@ -498,6 +498,6 @@ pub fn SSLWrapper(comptime T: type) type { } const bun = @import("bun"); -const JSC = bun.JSC; +const jsc = bun.jsc; const uws = bun.uws; const BoringSSL = bun.BoringSSL.c; diff --git a/src/bun.js/api/bun/subprocess.zig b/src/bun.js/api/bun/subprocess.zig index ffa45f0962..7c669ff0ba 100644 --- a/src/bun.js/api/bun/subprocess.zig +++ b/src/bun.js/api/bun/subprocess.zig @@ -3,7 +3,7 @@ const Subprocess = @This(); -pub const js = JSC.Codegen.JSSubprocess; +pub const js = jsc.Codegen.JSSubprocess; pub const toJS = js.toJS; pub const fromJS = js.fromJS; pub const fromJSDirect = js.fromJSDirect; @@ -20,7 +20,7 @@ stderr: Readable, stdio_pipes: if (Environment.isWindows) std.ArrayListUnmanaged(StdioResult) else std.ArrayListUnmanaged(bun.FileDescriptor) = .{}, pid_rusage: ?Rusage = null, -globalThis: *JSC.JSGlobalObject, +globalThis: *jsc.JSGlobalObject, observable_getters: std.enums.EnumSet(enum { stdin, stdout, @@ -29,13 +29,13 @@ observable_getters: std.enums.EnumSet(enum { }) = .{}, closed: std.enums.EnumSet(StdioKind) = .{}, has_pending_activity: std.atomic.Value(bool) = std.atomic.Value(bool).init(true), -this_jsvalue: JSC.JSValue = .zero, +this_jsvalue: jsc.JSValue = .zero, /// `null` indicates all of the IPC data is uninitialized. ipc_data: ?IPC.SendQueue, flags: Flags = .{}, -weak_file_sink_stdin_ptr: ?*JSC.WebCore.FileSink = null, +weak_file_sink_stdin_ptr: ?*jsc.WebCore.FileSink = null, abort_signal: ?*webcore.AbortSignal = null, event_loop_timer_refd: bool = false, @@ -85,7 +85,7 @@ pub inline fn assertStdioResult(result: StdioResult) void { } pub const ResourceUsage = struct { - pub const js = JSC.Codegen.JSResourceUsage; + pub const js = jsc.Codegen.JSResourceUsage; pub const toJS = ResourceUsage.js.toJS; pub const fromJS = ResourceUsage.js.fromJS; pub const fromJSDirect = ResourceUsage.js.fromJSDirect; @@ -93,53 +93,53 @@ pub const ResourceUsage = struct { rusage: Rusage, pub fn getCPUTime(this: *ResourceUsage, globalObject: *JSGlobalObject) bun.JSError!JSValue { - var cpu = JSC.JSValue.createEmptyObjectWithNullPrototype(globalObject); + var cpu = jsc.JSValue.createEmptyObjectWithNullPrototype(globalObject); const rusage = this.rusage; const usrTime = try JSValue.fromTimevalNoTruncate(globalObject, rusage.utime.usec, rusage.utime.sec); const sysTime = try JSValue.fromTimevalNoTruncate(globalObject, rusage.stime.usec, rusage.stime.sec); - cpu.put(globalObject, JSC.ZigString.static("user"), usrTime); - cpu.put(globalObject, JSC.ZigString.static("system"), sysTime); - cpu.put(globalObject, JSC.ZigString.static("total"), JSValue.bigIntSum(globalObject, usrTime, sysTime)); + cpu.put(globalObject, jsc.ZigString.static("user"), usrTime); + cpu.put(globalObject, jsc.ZigString.static("system"), sysTime); + cpu.put(globalObject, jsc.ZigString.static("total"), JSValue.bigIntSum(globalObject, usrTime, sysTime)); return cpu; } pub fn getMaxRSS(this: *ResourceUsage, _: *JSGlobalObject) JSValue { - return JSC.JSValue.jsNumber(this.rusage.maxrss); + return jsc.JSValue.jsNumber(this.rusage.maxrss); } pub fn getSharedMemorySize(this: *ResourceUsage, _: *JSGlobalObject) JSValue { - return JSC.JSValue.jsNumber(this.rusage.ixrss); + return jsc.JSValue.jsNumber(this.rusage.ixrss); } pub fn getSwapCount(this: *ResourceUsage, _: *JSGlobalObject) JSValue { - return JSC.JSValue.jsNumber(this.rusage.nswap); + return jsc.JSValue.jsNumber(this.rusage.nswap); } pub fn getOps(this: *ResourceUsage, globalObject: *JSGlobalObject) JSValue { - var ops = JSC.JSValue.createEmptyObjectWithNullPrototype(globalObject); - ops.put(globalObject, JSC.ZigString.static("in"), JSC.JSValue.jsNumber(this.rusage.inblock)); - ops.put(globalObject, JSC.ZigString.static("out"), JSC.JSValue.jsNumber(this.rusage.oublock)); + var ops = jsc.JSValue.createEmptyObjectWithNullPrototype(globalObject); + ops.put(globalObject, jsc.ZigString.static("in"), jsc.JSValue.jsNumber(this.rusage.inblock)); + ops.put(globalObject, jsc.ZigString.static("out"), jsc.JSValue.jsNumber(this.rusage.oublock)); return ops; } pub fn getMessages(this: *ResourceUsage, globalObject: *JSGlobalObject) JSValue { - var msgs = JSC.JSValue.createEmptyObjectWithNullPrototype(globalObject); - msgs.put(globalObject, JSC.ZigString.static("sent"), JSC.JSValue.jsNumber(this.rusage.msgsnd)); - msgs.put(globalObject, JSC.ZigString.static("received"), JSC.JSValue.jsNumber(this.rusage.msgrcv)); + var msgs = jsc.JSValue.createEmptyObjectWithNullPrototype(globalObject); + msgs.put(globalObject, jsc.ZigString.static("sent"), jsc.JSValue.jsNumber(this.rusage.msgsnd)); + msgs.put(globalObject, jsc.ZigString.static("received"), jsc.JSValue.jsNumber(this.rusage.msgrcv)); return msgs; } pub fn getSignalCount(this: *ResourceUsage, _: *JSGlobalObject) JSValue { - return JSC.JSValue.jsNumber(this.rusage.nsignals); + return jsc.JSValue.jsNumber(this.rusage.nsignals); } pub fn getContextSwitches(this: *ResourceUsage, globalObject: *JSGlobalObject) JSValue { - var ctx = JSC.JSValue.createEmptyObjectWithNullPrototype(globalObject); - ctx.put(globalObject, JSC.ZigString.static("voluntary"), JSC.JSValue.jsNumber(this.rusage.nvcsw)); - ctx.put(globalObject, JSC.ZigString.static("involuntary"), JSC.JSValue.jsNumber(this.rusage.nivcsw)); + var ctx = jsc.JSValue.createEmptyObjectWithNullPrototype(globalObject); + ctx.put(globalObject, jsc.ZigString.static("voluntary"), jsc.JSValue.jsNumber(this.rusage.nvcsw)); + ctx.put(globalObject, jsc.ZigString.static("involuntary"), jsc.JSValue.jsNumber(this.rusage.nivcsw)); return ctx; } @@ -148,8 +148,8 @@ pub const ResourceUsage = struct { } }; -pub fn appendEnvpFromJS(globalThis: *JSC.JSGlobalObject, object: *JSC.JSObject, envp: *std.ArrayList(?[*:0]const u8), PATH: *[]const u8) bun.JSError!void { - var object_iter = try JSC.JSPropertyIterator(.{ .skip_empty_name = false, .include_value = true }).init(globalThis, object); +pub fn appendEnvpFromJS(globalThis: *jsc.JSGlobalObject, object: *jsc.JSObject, envp: *std.ArrayList(?[*:0]const u8), PATH: *[]const u8) bun.JSError!void { + var object_iter = try jsc.JSPropertyIterator(.{ .skip_empty_name = false, .include_value = true }).init(globalThis, object); defer object_iter.deinit(); try envp.ensureTotalCapacityPrecise(object_iter.len + @@ -193,7 +193,7 @@ pub const StdioKind = enum { } }; -pub fn onAbortSignal(subprocess_ctx: ?*anyopaque, _: JSC.JSValue) callconv(.C) void { +pub fn onAbortSignal(subprocess_ctx: ?*anyopaque, _: jsc.JSValue) callconv(.C) void { var this: *Subprocess = @ptrCast(@alignCast(subprocess_ctx.?)); this.clearAbortSignal(); _ = this.tryKill(this.killSignal); @@ -202,7 +202,7 @@ pub fn onAbortSignal(subprocess_ctx: ?*anyopaque, _: JSC.JSValue) callconv(.C) v pub fn resourceUsage( this: *Subprocess, globalObject: *JSGlobalObject, - _: *JSC.CallFrame, + _: *jsc.CallFrame, ) bun.JSError!JSValue { return this.createResourceUsageObject(globalObject); } @@ -353,7 +353,7 @@ pub fn jsUnref(this: *Subprocess) void { this.updateHasPendingActivity(); } -pub fn constructor(globalObject: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!*Subprocess { +pub fn constructor(globalObject: *jsc.JSGlobalObject, _: *jsc.CallFrame) bun.JSError!*Subprocess { return globalObject.throw("Cannot construct Subprocess", .{}); } @@ -405,7 +405,7 @@ const Readable = union(enum) { } } - pub fn init(stdio: Stdio, event_loop: *JSC.EventLoop, process: *Subprocess, result: StdioResult, allocator: std.mem.Allocator, max_size: ?*MaxBuf, is_sync: bool) Readable { + pub fn init(stdio: Stdio, event_loop: *jsc.EventLoop, process: *Subprocess, result: StdioResult, allocator: std.mem.Allocator, max_size: ?*MaxBuf, is_sync: bool) Readable { _ = allocator; // autofix _ = is_sync; // autofix assertStdioResult(result); @@ -433,7 +433,7 @@ const Readable = union(enum) { this.* = .closed; } - pub fn onReady(_: *Readable, _: ?JSC.WebCore.Blob.SizeType, _: ?JSC.WebCore.Blob.SizeType) void {} + pub fn onReady(_: *Readable, _: ?jsc.WebCore.Blob.SizeType, _: ?jsc.WebCore.Blob.SizeType) void {} pub fn onStart(_: *Readable) void {} @@ -473,7 +473,7 @@ const Readable = union(enum) { } } - pub fn toJS(this: *Readable, globalThis: *JSC.JSGlobalObject, exited: bool) bun.JSError!JSValue { + pub fn toJS(this: *Readable, globalThis: *jsc.JSGlobalObject, exited: bool) bun.JSError!JSValue { _ = exited; // autofix switch (this.*) { // should only be reachable when the entire output is buffered. @@ -491,11 +491,11 @@ const Readable = union(enum) { defer this.* = .{ .closed = {} }; if (buffer.length() == 0) { - return JSC.WebCore.ReadableStream.empty(globalThis); + return jsc.WebCore.ReadableStream.empty(globalThis); } const own = try buffer.takeSlice(bun.default_allocator); - return JSC.WebCore.ReadableStream.fromOwnedSlice(globalThis, own, 0); + return jsc.WebCore.ReadableStream.fromOwnedSlice(globalThis, own, 0); }, else => { return .js_undefined; @@ -503,7 +503,7 @@ const Readable = union(enum) { } } - pub fn toBufferedValue(this: *Readable, globalThis: *JSC.JSGlobalObject) bun.JSError!JSValue { + pub fn toBufferedValue(this: *Readable, globalThis: *jsc.JSGlobalObject) bun.JSError!JSValue { switch (this.*) { .fd => |fd| { return fd.toJS(globalThis); @@ -513,7 +513,7 @@ const Readable = union(enum) { Output.panic("memfd is only supported on Linux", .{}); } this.* = .{ .closed = {} }; - return JSC.ArrayBuffer.toJSBufferFromMemfd(fd, globalThis); + return jsc.ArrayBuffer.toJSBufferFromMemfd(fd, globalThis); }, .pipe => |pipe| { defer pipe.detach(); @@ -526,7 +526,7 @@ const Readable = union(enum) { return globalThis.throwOutOfMemory(); }; - return JSC.MarkedArrayBuffer.fromBytes(own, bun.default_allocator, .Uint8Array).toNodeBuffer(globalThis); + return jsc.MarkedArrayBuffer.fromBytes(own, bun.default_allocator, .Uint8Array).toNodeBuffer(globalThis); }, else => { return .js_undefined; @@ -553,7 +553,7 @@ pub fn getStdout(this: *Subprocess, globalThis: *JSGlobalObject) bun.JSError!JSV return this.stdout.toJS(globalThis, this.hasExited()); } -pub fn asyncDispose(this: *Subprocess, global: *JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { +pub fn asyncDispose(this: *Subprocess, global: *JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { if (this.process.hasExited()) { // rely on GC to clean everything up in this case return .js_undefined; @@ -607,7 +607,7 @@ pub fn onMaxBuffer(this: *Subprocess, kind: MaxBuf.Kind) void { _ = this.tryKill(this.killSignal); } -fn parseSignal(arg: JSC.JSValue, globalThis: *JSC.JSGlobalObject) !SignalCode { +fn parseSignal(arg: jsc.JSValue, globalThis: *jsc.JSGlobalObject) !SignalCode { if (arg.getNumber()) |sig64| { // Node does this: if (std.math.isNan(sig64)) { @@ -645,7 +645,7 @@ fn parseSignal(arg: JSC.JSValue, globalThis: *JSC.JSGlobalObject) !SignalCode { pub fn kill( this: *Subprocess, globalThis: *JSGlobalObject, - callframe: *JSC.CallFrame, + callframe: *jsc.CallFrame, ) bun.JSError!JSValue { this.this_jsvalue = callframe.this(); @@ -671,7 +671,7 @@ pub fn hasKilled(this: *const Subprocess) bool { return this.process.hasKilled(); } -pub fn tryKill(this: *Subprocess, sig: SignalCode) JSC.Maybe(void) { +pub fn tryKill(this: *Subprocess, sig: SignalCode) jsc.Maybe(void) { if (this.hasExited()) { return .{ .result = {} }; } @@ -689,12 +689,12 @@ fn closeProcess(this: *Subprocess) void { this.process.close(); } -pub fn doRef(this: *Subprocess, _: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!JSValue { +pub fn doRef(this: *Subprocess, _: *jsc.JSGlobalObject, _: *jsc.CallFrame) bun.JSError!JSValue { this.jsRef(); return .js_undefined; } -pub fn doUnref(this: *Subprocess, _: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!JSValue { +pub fn doUnref(this: *Subprocess, _: *jsc.JSGlobalObject, _: *jsc.CallFrame) bun.JSError!JSValue { this.jsUnref(); return .js_undefined; } @@ -713,7 +713,7 @@ pub fn onStdinDestroyed(this: *Subprocess) void { } } -pub fn doSend(this: *Subprocess, global: *JSC.JSGlobalObject, callFrame: *JSC.CallFrame) bun.JSError!JSValue { +pub fn doSend(this: *Subprocess, global: *jsc.JSGlobalObject, callFrame: *jsc.CallFrame) bun.JSError!JSValue { IPClog("Subprocess#doSend", .{}); return IPC.doSend(if (this.ipc_data) |*data| data else null, global, callFrame, if (this.hasExited()) .subprocess_exited else .subprocess); @@ -722,7 +722,7 @@ pub fn disconnectIPC(this: *Subprocess, nextTick: bool) void { const ipc_data = this.ipc() orelse return; ipc_data.closeSocketNextTick(nextTick); } -pub fn disconnect(this: *Subprocess, globalThis: *JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { +pub fn disconnect(this: *Subprocess, globalThis: *JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { _ = globalThis; _ = callframe; this.disconnectIPC(true); @@ -774,8 +774,8 @@ pub fn getStdio(this: *Subprocess, global: *JSGlobalObject) bun.JSError!JSValue } pub const Source = union(enum) { - blob: JSC.WebCore.Blob.Any, - array_buffer: JSC.ArrayBuffer.Strong, + blob: jsc.WebCore.Blob.Any, + array_buffer: jsc.ArrayBuffer.Strong, detached: void, pub fn memoryCost(this: *const Source) usize { @@ -821,7 +821,7 @@ pub fn NewStaticPipeWriter(comptime ProcessType: type) type { stdio_result: StdioResult, source: Source = .{ .detached = {} }, process: *ProcessType = undefined, - event_loop: JSC.EventLoopHandle, + event_loop: jsc.EventLoopHandle, buffer: []const u8 = "", // It seems there is a bug in the Zig compiler. We'll get back to this one later @@ -861,7 +861,7 @@ pub fn NewStaticPipeWriter(comptime ProcessType: type) type { pub fn create(event_loop: anytype, subprocess: *ProcessType, result: StdioResult, source: Source) *This { const this = bun.new(This, .{ .ref_count = .init(), - .event_loop = JSC.EventLoopHandle.init(event_loop), + .event_loop = jsc.EventLoopHandle.init(event_loop), .process = subprocess, .stdio_result = result, .source = source, @@ -873,7 +873,7 @@ pub fn NewStaticPipeWriter(comptime ProcessType: type) type { return this; } - pub fn start(this: *This) JSC.Maybe(void) { + pub fn start(this: *This) jsc.Maybe(void) { log("StaticPipeWriter(0x{x}) start()", .{@intFromPtr(this)}); this.ref(); this.buffer = this.source.slice(); @@ -934,7 +934,7 @@ pub fn NewStaticPipeWriter(comptime ProcessType: type) type { } } - pub fn eventLoop(this: *This) JSC.EventLoopHandle { + pub fn eventLoop(this: *This) jsc.EventLoopHandle { return this.event_loop; } }; @@ -947,7 +947,7 @@ pub const PipeReader = struct { reader: IOReader = undefined, process: ?*Subprocess = null, - event_loop: *JSC.EventLoop = undefined, + event_loop: *jsc.EventLoop = undefined, ref_count: PipeReader.RefCount, state: union(enum) { pending: void, @@ -974,7 +974,7 @@ pub const PipeReader = struct { this.deref(); } - pub fn create(event_loop: *JSC.EventLoop, process: *Subprocess, result: StdioResult, limit: ?*MaxBuf) *PipeReader { + pub fn create(event_loop: *jsc.EventLoop, process: *Subprocess, result: StdioResult, limit: ?*MaxBuf) *PipeReader { var this = bun.new(PipeReader, .{ .ref_count = .init(), .process = process, @@ -996,7 +996,7 @@ pub const PipeReader = struct { this.reader.read(); } - pub fn start(this: *PipeReader, process: *Subprocess, event_loop: *JSC.EventLoop) JSC.Maybe(void) { + pub fn start(this: *PipeReader, process: *Subprocess, event_loop: *jsc.EventLoop) jsc.Maybe(void) { this.ref(); this.process = process; this.event_loop = event_loop; @@ -1073,33 +1073,33 @@ pub const PipeReader = struct { this.reader.watch(); } - pub fn toReadableStream(this: *PipeReader, globalObject: *JSC.JSGlobalObject) bun.JSError!JSC.JSValue { + pub fn toReadableStream(this: *PipeReader, globalObject: *jsc.JSGlobalObject) bun.JSError!jsc.JSValue { defer this.detach(); switch (this.state) { .pending => { - const stream = JSC.WebCore.ReadableStream.fromPipe(globalObject, this, &this.reader); + const stream = jsc.WebCore.ReadableStream.fromPipe(globalObject, this, &this.reader); this.state = .{ .done = &.{} }; return stream; }, .done => |bytes| { this.state = .{ .done = &.{} }; - return JSC.WebCore.ReadableStream.fromOwnedSlice(globalObject, bytes, 0); + return jsc.WebCore.ReadableStream.fromOwnedSlice(globalObject, bytes, 0); }, .err => |err| { _ = err; - const empty = try JSC.WebCore.ReadableStream.empty(globalObject); - JSC.WebCore.ReadableStream.cancel(&(try JSC.WebCore.ReadableStream.fromJS(empty, globalObject)).?, globalObject); + const empty = try jsc.WebCore.ReadableStream.empty(globalObject); + jsc.WebCore.ReadableStream.cancel(&(try jsc.WebCore.ReadableStream.fromJS(empty, globalObject)).?, globalObject); return empty; }, } } - pub fn toBuffer(this: *PipeReader, globalThis: *JSC.JSGlobalObject) JSC.JSValue { + pub fn toBuffer(this: *PipeReader, globalThis: *jsc.JSGlobalObject) jsc.JSValue { switch (this.state) { .done => |bytes| { defer this.state = .{ .done = &.{} }; - return JSC.MarkedArrayBuffer.fromBytes(bytes, bun.default_allocator, .Uint8Array).toNodeBuffer(globalThis); + return jsc.MarkedArrayBuffer.fromBytes(bytes, bun.default_allocator, .Uint8Array).toNodeBuffer(globalThis); }, else => { return .js_undefined; @@ -1126,7 +1126,7 @@ pub const PipeReader = struct { } } - pub fn eventLoop(this: *PipeReader) *JSC.EventLoop { + pub fn eventLoop(this: *PipeReader) *jsc.EventLoop { return this.event_loop; } @@ -1153,7 +1153,7 @@ pub const PipeReader = struct { }; const Writable = union(enum) { - pipe: *JSC.WebCore.FileSink, + pipe: *jsc.WebCore.FileSink, fd: bun.FileDescriptor, buffer: *StaticPipeWriter, memfd: bun.FileDescriptor, @@ -1210,7 +1210,7 @@ const Writable = union(enum) { if (process.this_jsvalue != .zero) { if (js.stdinGetCached(process.this_jsvalue)) |existing_value| { - JSC.WebCore.FileSink.JSSink.setDestroyCallback(existing_value, 0); + jsc.WebCore.FileSink.JSSink.setDestroyCallback(existing_value, 0); } } @@ -1230,15 +1230,15 @@ const Writable = union(enum) { .ignore = {}, }; } - pub fn onReady(_: *Writable, _: ?JSC.WebCore.Blob.SizeType, _: ?JSC.WebCore.Blob.SizeType) void {} + pub fn onReady(_: *Writable, _: ?jsc.WebCore.Blob.SizeType, _: ?jsc.WebCore.Blob.SizeType) void {} pub fn onStart(_: *Writable) void {} pub fn init( stdio: *Stdio, - event_loop: *JSC.EventLoop, + event_loop: *jsc.EventLoop, subprocess: *Subprocess, result: StdioResult, - promise_for_stream: *JSC.JSValue, + promise_for_stream: *jsc.JSValue, ) !Writable { assertStdioResult(result); @@ -1246,7 +1246,7 @@ const Writable = union(enum) { switch (stdio.*) { .pipe, .readable_stream => { if (result == .buffer) { - const pipe = JSC.WebCore.FileSink.createWithPipe(event_loop, result.buffer); + const pipe = jsc.WebCore.FileSink.createWithPipe(event_loop, result.buffer); switch (pipe.writer.startWithCurrentPipe()) { .result => {}, @@ -1319,7 +1319,7 @@ const Writable = union(enum) { switch (stdio.*) { .dup2 => @panic("TODO dup2 stdio"), .pipe, .readable_stream => { - const pipe = JSC.WebCore.FileSink.create(event_loop, result.?); + const pipe = jsc.WebCore.FileSink.create(event_loop, result.?); switch (pipe.writer.start(pipe.fd, true)) { .result => {}, @@ -1385,7 +1385,7 @@ const Writable = union(enum) { } } - pub fn toJS(this: *Writable, globalThis: *JSC.JSGlobalObject, subprocess: *Subprocess) JSValue { + pub fn toJS(this: *Writable, globalThis: *jsc.JSGlobalObject, subprocess: *Subprocess) JSValue { return switch (this.*) { .fd => |fd| fd.toJS(globalThis), .memfd, .ignore => .js_undefined, @@ -1415,7 +1415,7 @@ const Writable = union(enum) { } return pipe.toJSWithDestructor( globalThis, - JSC.WebCore.Sink.DestructorPtr.init(subprocess), + jsc.WebCore.Sink.DestructorPtr.init(subprocess), ); } }, @@ -1425,8 +1425,8 @@ const Writable = union(enum) { pub fn finalize(this: *Writable) void { const subprocess: *Subprocess = @fieldParentPtr("stdin", this); if (subprocess.this_jsvalue != .zero) { - if (JSC.Codegen.JSSubprocess.stdinGetCached(subprocess.this_jsvalue)) |existing_value| { - JSC.WebCore.FileSink.JSSink.setDestroyCallback(existing_value, 0); + if (jsc.Codegen.JSSubprocess.stdinGetCached(subprocess.this_jsvalue)) |existing_value| { + jsc.WebCore.FileSink.JSSink.setDestroyCallback(existing_value, 0); } } @@ -1482,25 +1482,25 @@ pub fn memoryCost(this: *const Subprocess) usize { this.stderr.memoryCost(); } -fn consumeExitedPromise(this_jsvalue: JSValue, globalThis: *JSC.JSGlobalObject) ?JSValue { - if (JSC.Codegen.JSSubprocess.exitedPromiseGetCached(this_jsvalue)) |promise| { - JSC.Codegen.JSSubprocess.exitedPromiseSetCached(this_jsvalue, globalThis, .zero); +fn consumeExitedPromise(this_jsvalue: JSValue, globalThis: *jsc.JSGlobalObject) ?JSValue { + if (jsc.Codegen.JSSubprocess.exitedPromiseGetCached(this_jsvalue)) |promise| { + jsc.Codegen.JSSubprocess.exitedPromiseSetCached(this_jsvalue, globalThis, .zero); return promise; } return null; } -fn consumeOnExitCallback(this_jsvalue: JSValue, globalThis: *JSC.JSGlobalObject) ?JSValue { - if (JSC.Codegen.JSSubprocess.onExitCallbackGetCached(this_jsvalue)) |callback| { - JSC.Codegen.JSSubprocess.onExitCallbackSetCached(this_jsvalue, globalThis, .zero); +fn consumeOnExitCallback(this_jsvalue: JSValue, globalThis: *jsc.JSGlobalObject) ?JSValue { + if (jsc.Codegen.JSSubprocess.onExitCallbackGetCached(this_jsvalue)) |callback| { + jsc.Codegen.JSSubprocess.onExitCallbackSetCached(this_jsvalue, globalThis, .zero); return callback; } return null; } -fn consumeOnDisconnectCallback(this_jsvalue: JSValue, globalThis: *JSC.JSGlobalObject) ?JSValue { - if (JSC.Codegen.JSSubprocess.onDisconnectCallbackGetCached(this_jsvalue)) |callback| { - JSC.Codegen.JSSubprocess.onDisconnectCallbackSetCached(this_jsvalue, globalThis, .zero); +fn consumeOnDisconnectCallback(this_jsvalue: JSValue, globalThis: *jsc.JSGlobalObject) ?JSValue { + if (jsc.Codegen.JSSubprocess.onDisconnectCallbackGetCached(this_jsvalue)) |callback| { + jsc.Codegen.JSSubprocess.onDisconnectCallbackSetCached(this_jsvalue, globalThis, .zero); return callback; } return null; @@ -1526,14 +1526,14 @@ pub fn onProcessExit(this: *Subprocess, process: *Process, status: bun.spawn.Sta jsc_vm.onSubprocessExit(process); - var stdin: ?*JSC.WebCore.FileSink = if (this.stdin == .pipe and this.flags.is_stdin_a_readable_stream) this.stdin.pipe else this.weak_file_sink_stdin_ptr; - var existing_stdin_value = JSC.JSValue.zero; + var stdin: ?*jsc.WebCore.FileSink = if (this.stdin == .pipe and this.flags.is_stdin_a_readable_stream) this.stdin.pipe else this.weak_file_sink_stdin_ptr; + var existing_stdin_value = jsc.JSValue.zero; if (this_jsvalue != .zero) { - if (JSC.Codegen.JSSubprocess.stdinGetCached(this_jsvalue)) |existing_value| { + if (jsc.Codegen.JSSubprocess.stdinGetCached(this_jsvalue)) |existing_value| { if (existing_stdin_value.isCell()) { if (stdin == null) { // TODO: review this cast - stdin = @alignCast(@ptrCast(JSC.WebCore.FileSink.JSSink.fromJS(existing_value))); + stdin = @alignCast(@ptrCast(jsc.WebCore.FileSink.JSSink.fromJS(existing_value))); } if (!this.flags.is_stdin_a_readable_stream) { @@ -1549,7 +1549,7 @@ pub fn onProcessExit(this: *Subprocess, process: *Process, status: bun.spawn.Sta } if (existing_stdin_value != .zero) { - JSC.WebCore.FileSink.JSSink.setDestroyCallback(existing_stdin_value, 0); + jsc.WebCore.FileSink.JSSink.setDestroyCallback(existing_stdin_value, 0); } if (this.flags.is_sync) { @@ -1715,7 +1715,7 @@ pub fn finalize(this: *Subprocess) callconv(.C) void { this.clearAbortSignal(); - bun.assert(!this.hasPendingActivity() or JSC.VirtualMachine.get().isShuttingDown()); + bun.assert(!this.hasPendingActivity() or jsc.VirtualMachine.get().isShuttingDown()); this.finalizeStreams(); this.process.detach(); @@ -1742,23 +1742,23 @@ pub fn getExited( this_value: JSValue, globalThis: *JSGlobalObject, ) JSValue { - if (JSC.Codegen.JSSubprocess.exitedPromiseGetCached(this_value)) |promise| { + if (jsc.Codegen.JSSubprocess.exitedPromiseGetCached(this_value)) |promise| { return promise; } switch (this.process.status) { .exited => |exit| { - return JSC.JSPromise.resolvedPromiseValue(globalThis, JSValue.jsNumber(exit.code)); + return jsc.JSPromise.resolvedPromiseValue(globalThis, JSValue.jsNumber(exit.code)); }, .signaled => |signal| { - return JSC.JSPromise.resolvedPromiseValue(globalThis, JSValue.jsNumber(signal.toExitCode() orelse 254)); + return jsc.JSPromise.resolvedPromiseValue(globalThis, JSValue.jsNumber(signal.toExitCode() orelse 254)); }, .err => |err| { - return JSC.JSPromise.dangerouslyCreateRejectedPromiseValueWithoutNotifyingVM(globalThis, err.toJS(globalThis)); + return jsc.JSPromise.dangerouslyCreateRejectedPromiseValueWithoutNotifyingVM(globalThis, err.toJS(globalThis)); }, else => { - const promise = JSC.JSPromise.create(globalThis).toJS(); - JSC.Codegen.JSSubprocess.exitedPromiseSetCached(this_value, globalThis, promise); + const promise = jsc.JSPromise.create(globalThis).toJS(); + jsc.Codegen.JSSubprocess.exitedPromiseSetCached(this_value, globalThis, promise); return promise; }, } @@ -1769,9 +1769,9 @@ pub fn getExitCode( _: *JSGlobalObject, ) JSValue { if (this.process.status == .exited) { - return JSC.JSValue.jsNumber(this.process.status.exited.code); + return jsc.JSValue.jsNumber(this.process.status.exited.code); } - return JSC.JSValue.jsNull(); + return jsc.JSValue.jsNull(); } pub fn getSignalCode( @@ -1780,19 +1780,19 @@ pub fn getSignalCode( ) JSValue { if (this.process.signalCode()) |signal| { if (signal.name()) |name| - return JSC.ZigString.init(name).toJS(global) + return jsc.ZigString.init(name).toJS(global) else - return JSC.JSValue.jsNumber(@intFromEnum(signal)); + return jsc.JSValue.jsNumber(@intFromEnum(signal)); } - return JSC.JSValue.jsNull(); + return jsc.JSValue.jsNull(); } -pub fn spawn(globalThis: *JSC.JSGlobalObject, args: JSValue, secondaryArgsValue: ?JSValue) bun.JSError!JSValue { +pub fn spawn(globalThis: *jsc.JSGlobalObject, args: JSValue, secondaryArgsValue: ?JSValue) bun.JSError!JSValue { return spawnMaybeSync(globalThis, args, secondaryArgsValue, false); } -pub fn spawnSync(globalThis: *JSC.JSGlobalObject, args: JSValue, secondaryArgsValue: ?JSValue) bun.JSError!JSValue { +pub fn spawnSync(globalThis: *jsc.JSGlobalObject, args: JSValue, secondaryArgsValue: ?JSValue) bun.JSError!JSValue { return spawnMaybeSync(globalThis, args, secondaryArgsValue, true); } @@ -1800,7 +1800,7 @@ extern "C" const BUN_DEFAULT_PATH_FOR_SPAWN: [*:0]const u8; // This is split into a separate function to conserve stack space. // On Windows, a single path buffer can take 64 KB. -fn getArgv0(globalThis: *JSC.JSGlobalObject, PATH: []const u8, cwd: []const u8, pretend_argv0: ?[*:0]const u8, first_cmd: JSValue, allocator: std.mem.Allocator) bun.JSError!struct { +fn getArgv0(globalThis: *jsc.JSGlobalObject, PATH: []const u8, cwd: []const u8, pretend_argv0: ?[*:0]const u8, first_cmd: JSValue, allocator: std.mem.Allocator) bun.JSError!struct { argv0: [:0]const u8, arg0: [:0]u8, } { @@ -1843,7 +1843,7 @@ fn getArgv0(globalThis: *JSC.JSGlobalObject, PATH: []const u8, cwd: []const u8, }; } -fn getArgv(globalThis: *JSC.JSGlobalObject, args: JSValue, PATH: []const u8, cwd: []const u8, argv0: *?[*:0]const u8, allocator: std.mem.Allocator, argv: *std.ArrayList(?[*:0]const u8)) bun.JSError!void { +fn getArgv(globalThis: *jsc.JSGlobalObject, args: JSValue, PATH: []const u8, cwd: []const u8, argv0: *?[*:0]const u8, allocator: std.mem.Allocator, argv: *std.ArrayList(?[*:0]const u8)) bun.JSError!void { var cmds_array = try args.arrayIterator(globalThis); // + 1 for argv0 // + 1 for null terminator @@ -1875,7 +1875,7 @@ fn getArgv(globalThis: *JSC.JSGlobalObject, args: JSValue, PATH: []const u8, cwd } pub fn spawnMaybeSync( - globalThis: *JSC.JSGlobalObject, + globalThis: *jsc.JSGlobalObject, args_: JSValue, secondaryArgsValue: ?JSValue, comptime is_sync: bool, @@ -1930,7 +1930,7 @@ pub fn spawnMaybeSync( var windows_hide: bool = false; var windows_verbatim_arguments: bool = false; - var abort_signal: ?*JSC.WebCore.AbortSignal = null; + var abort_signal: ?*jsc.WebCore.AbortSignal = null; defer { // Ensure we clean it up on error. if (abort_signal) |signal| { @@ -1999,7 +1999,7 @@ pub fn spawnMaybeSync( } if (try args.getTruthy(globalThis, "signal")) |signal_val| { - if (signal_val.as(JSC.WebCore.AbortSignal)) |signal| { + if (signal_val.as(jsc.WebCore.AbortSignal)) |signal| { abort_signal = signal.ref(); } else { return globalThis.throwInvalidArgumentTypeValue("signal", "AbortSignal", signal_val); @@ -2252,7 +2252,7 @@ pub fn spawnMaybeSync( !stdio[2].isPiped() and extra_fds.items.len == 0 and !jsc_vm.auto_killer.enabled and - !jsc_vm.jsc.hasExecutionTimeLimit() and + !jsc_vm.jsc_vm.hasExecutionTimeLimit() and !jsc_vm.isInspectorEnabled() and !bun.getRuntimeFeatureFlag(.BUN_FEATURE_FLAG_DISABLE_SPAWNSYNC_FAST_PATH); @@ -2278,7 +2278,7 @@ pub fn spawnMaybeSync( .windows = if (Environment.isWindows) .{ .hide_window = windows_hide, .verbatim_arguments = windows_verbatim_arguments, - .loop = JSC.EventLoopHandle.init(jsc_vm), + .loop = jsc.EventLoopHandle.init(jsc_vm), }, }; @@ -2352,7 +2352,7 @@ pub fn spawnMaybeSync( MaxBuf.createForSubprocess(subprocess, &subprocess.stderr_maxbuf, maxBuffer); MaxBuf.createForSubprocess(subprocess, &subprocess.stdout_maxbuf, maxBuffer); - var promise_for_stream: JSC.JSValue = .zero; + var promise_for_stream: jsc.JSValue = .zero; // When run synchronously, subprocess isn't garbage collected subprocess.* = Subprocess{ @@ -2463,7 +2463,7 @@ pub fn spawnMaybeSync( } if (subprocess.stdin == .pipe and promise_for_stream == .zero) { - subprocess.stdin.pipe.signal = JSC.WebCore.streams.Signal.init(&subprocess.stdin); + subprocess.stdin.pipe.signal = jsc.WebCore.streams.Signal.init(&subprocess.stdin); } const out = if (comptime !is_sync) @@ -2485,17 +2485,17 @@ pub fn spawnMaybeSync( bun.debugAssert(out != .zero); if (on_exit_callback.isCell()) { - JSC.Codegen.JSSubprocess.onExitCallbackSetCached(out, globalThis, on_exit_callback); + jsc.Codegen.JSSubprocess.onExitCallbackSetCached(out, globalThis, on_exit_callback); } if (on_disconnect_callback.isCell()) { - JSC.Codegen.JSSubprocess.onDisconnectCallbackSetCached(out, globalThis, on_disconnect_callback); + jsc.Codegen.JSSubprocess.onDisconnectCallbackSetCached(out, globalThis, on_disconnect_callback); } if (ipc_callback.isCell()) { - JSC.Codegen.JSSubprocess.ipcCallbackSetCached(out, globalThis, ipc_callback); + jsc.Codegen.JSSubprocess.ipcCallbackSetCached(out, globalThis, ipc_callback); } if (stdio[0] == .readable_stream) { - JSC.Codegen.JSSubprocess.stdinSetCached(out, globalThis, stdio[0].readable_stream.value); + jsc.Codegen.JSSubprocess.stdinSetCached(out, globalThis, stdio[0].readable_stream.value); } switch (subprocess.process.watch()) { @@ -2621,7 +2621,7 @@ pub fn spawnMaybeSync( const resource_usage: JSValue = if (!globalThis.hasException()) subprocess.createResourceUsageObject(globalThis) else .zero; const exitedDueToTimeout = subprocess.event_loop_timer.state == .FIRED; const exitedDueToMaxBuffer = subprocess.exited_due_to_maxbuf; - const resultPid = JSC.JSValue.jsNumberFromInt32(subprocess.pid()); + const resultPid = jsc.JSValue.jsNumberFromInt32(subprocess.pid()); subprocess.finalize(); if (globalThis.hasException()) { @@ -2629,24 +2629,24 @@ pub fn spawnMaybeSync( return .zero; } - const sync_value = JSC.JSValue.createEmptyObject(globalThis, 5 + @as(usize, @intFromBool(!signalCode.isEmptyOrUndefinedOrNull()))); - sync_value.put(globalThis, JSC.ZigString.static("exitCode"), exitCode); + const sync_value = jsc.JSValue.createEmptyObject(globalThis, 5 + @as(usize, @intFromBool(!signalCode.isEmptyOrUndefinedOrNull()))); + sync_value.put(globalThis, jsc.ZigString.static("exitCode"), exitCode); if (!signalCode.isEmptyOrUndefinedOrNull()) { - sync_value.put(globalThis, JSC.ZigString.static("signalCode"), signalCode); + sync_value.put(globalThis, jsc.ZigString.static("signalCode"), signalCode); } - sync_value.put(globalThis, JSC.ZigString.static("stdout"), stdout); - sync_value.put(globalThis, JSC.ZigString.static("stderr"), stderr); - sync_value.put(globalThis, JSC.ZigString.static("success"), JSValue.jsBoolean(exitCode.isInt32() and exitCode.asInt32() == 0)); - sync_value.put(globalThis, JSC.ZigString.static("resourceUsage"), resource_usage); - if (timeout != null) sync_value.put(globalThis, JSC.ZigString.static("exitedDueToTimeout"), if (exitedDueToTimeout) JSC.JSValue.true else JSC.JSValue.false); - if (maxBuffer != null) sync_value.put(globalThis, JSC.ZigString.static("exitedDueToMaxBuffer"), if (exitedDueToMaxBuffer != null) JSC.JSValue.true else JSC.JSValue.false); - sync_value.put(globalThis, JSC.ZigString.static("pid"), resultPid); + sync_value.put(globalThis, jsc.ZigString.static("stdout"), stdout); + sync_value.put(globalThis, jsc.ZigString.static("stderr"), stderr); + sync_value.put(globalThis, jsc.ZigString.static("success"), JSValue.jsBoolean(exitCode.isInt32() and exitCode.asInt32() == 0)); + sync_value.put(globalThis, jsc.ZigString.static("resourceUsage"), resource_usage); + if (timeout != null) sync_value.put(globalThis, jsc.ZigString.static("exitedDueToTimeout"), if (exitedDueToTimeout) jsc.JSValue.true else jsc.JSValue.false); + if (maxBuffer != null) sync_value.put(globalThis, jsc.ZigString.static("exitedDueToMaxBuffer"), if (exitedDueToMaxBuffer != null) jsc.JSValue.true else jsc.JSValue.false); + sync_value.put(globalThis, jsc.ZigString.static("pid"), resultPid); return sync_value; } -fn throwCommandNotFound(globalThis: *JSC.JSGlobalObject, command: []const u8) bun.JSError { - const err = JSC.SystemError{ +fn throwCommandNotFound(globalThis: *jsc.JSGlobalObject, command: []const u8) bun.JSError { + const err = jsc.SystemError{ .message = bun.String.createFormat("Executable not found in $PATH: \"{s}\"", .{command}) catch bun.outOfMemory(), .code = bun.String.static("ENOENT"), .errno = -bun.sys.UV_E.NOENT, @@ -2658,7 +2658,7 @@ fn throwCommandNotFound(globalThis: *JSC.JSGlobalObject, command: []const u8) bu pub fn handleIPCMessage( this: *Subprocess, message: IPC.DecodedIPCMessage, - handle: JSC.JSValue, + handle: jsc.JSValue, ) void { IPClog("Subprocess#handleIPCMessage", .{}); switch (message) { @@ -2672,7 +2672,7 @@ pub fn handleIPCMessage( const this_jsvalue = this.this_jsvalue; defer this_jsvalue.ensureStillAlive(); if (this_jsvalue != .zero) { - if (JSC.Codegen.JSSubprocess.ipcCallbackGetCached(this_jsvalue)) |cb| { + if (jsc.Codegen.JSSubprocess.ipcCallbackGetCached(this_jsvalue)) |cb| { const globalThis = this.globalThis; globalThis.bunVM().eventLoop().runCallback( cb, @@ -2699,7 +2699,7 @@ pub fn handleIPCClose(this: *Subprocess) void { if (this_jsvalue != .zero) { // Avoid keeping the callback alive longer than necessary - JSC.Codegen.JSSubprocess.ipcCallbackSetCached(this_jsvalue, globalThis, .zero); + jsc.Codegen.JSSubprocess.ipcCallbackSetCached(this_jsvalue, globalThis, .zero); // Call the onDisconnectCallback if it exists and prevent it from being kept alive longer than necessary if (consumeOnDisconnectCallback(this_jsvalue, globalThis)) |callback| { @@ -2711,7 +2711,7 @@ pub fn handleIPCClose(this: *Subprocess) void { pub fn ipc(this: *Subprocess) ?*IPC.SendQueue { return &(this.ipc_data orelse return null); } -pub fn getGlobalThis(this: *Subprocess) ?*JSC.JSGlobalObject { +pub fn getGlobalThis(this: *Subprocess) ?*jsc.JSGlobalObject { return this.globalThis; } @@ -2721,6 +2721,8 @@ const StdioResult = if (Environment.isWindows) bun.spawn.WindowsSpawnResult.Stdi pub const MaxBuf = bun.io.MaxBuf; +const string = []const u8; + const IPC = @import("../../ipc.zig"); const node_cluster_binding = @import("../../node/node_cluster_binding.zig"); const std = @import("std"); @@ -2731,16 +2733,15 @@ const Async = bun.Async; const Environment = bun.Environment; const Output = bun.Output; const default_allocator = bun.default_allocator; -const string = bun.string; const strings = bun.strings; const uws = bun.uws; const webcore = bun.webcore; const which = bun.which; const CowString = bun.ptr.CowString; -const JSC = bun.JSC; -const JSGlobalObject = JSC.JSGlobalObject; -const JSValue = JSC.JSValue; +const jsc = bun.jsc; +const JSGlobalObject = jsc.JSGlobalObject; +const JSValue = jsc.JSValue; const PosixSpawn = bun.spawn; const Process = bun.spawn.Process; diff --git a/src/bun.js/api/bun/udp_socket.zig b/src/bun.js/api/bun/udp_socket.zig index 52bed0bd03..09f2c6c097 100644 --- a/src/bun.js/api/bun/udp_socket.zig +++ b/src/bun.js/api/bun/udp_socket.zig @@ -9,7 +9,7 @@ extern fn inet_ntop(af: c_int, src: ?*const anyopaque, dst: [*c]u8, size: c_int) extern fn inet_pton(af: c_int, src: [*c]const u8, dst: ?*anyopaque) c_int; fn onClose(socket: *uws.udp.Socket) callconv(.C) void { - JSC.markBinding(@src()); + jsc.markBinding(@src()); const this: *UDPSocket = bun.cast(*UDPSocket, socket.user().?); this.closed = true; @@ -18,13 +18,13 @@ fn onClose(socket: *uws.udp.Socket) callconv(.C) void { } fn onDrain(socket: *uws.udp.Socket) callconv(.C) void { - JSC.markBinding(@src()); + jsc.markBinding(@src()); const this: *UDPSocket = bun.cast(*UDPSocket, socket.user().?); const callback = this.config.on_drain; if (callback == .zero) return; - const vm = JSC.VirtualMachine.get(); + const vm = jsc.VirtualMachine.get(); const event_loop = vm.eventLoop(); event_loop.enter(); defer event_loop.exit(); @@ -34,7 +34,7 @@ fn onDrain(socket: *uws.udp.Socket) callconv(.C) void { } fn onData(socket: *uws.udp.Socket, buf: *uws.udp.PacketBuffer, packets: c_int) callconv(.C) void { - JSC.markBinding(@src()); + jsc.markBinding(@src()); const udpSocket: *UDPSocket = bun.cast(*UDPSocket, socket.user().?); const callback = udpSocket.config.on_data; @@ -94,7 +94,7 @@ fn onData(socket: *uws.udp.Socket, buf: *uws.udp.PacketBuffer, packets: c_int) c _ = callback.call(globalThis, udpSocket.thisValue, &.{ udpSocket.thisValue, udpSocket.config.binary_type.toJS(slice, globalThis) catch return, // TODO: properly propagate exception upwards - JSC.jsNumber(port), + jsc.jsNumber(port), hostname_string.transferToJS(globalThis), }) catch |err| { udpSocket.callErrorHandler(.zero, udpSocket.globalThis.takeException(err)); @@ -119,7 +119,7 @@ pub const UDPSocketConfig = struct { connect: ?ConnectConfig = null, port: u16, flags: i32, - binary_type: JSC.ArrayBuffer.BinaryType = .Buffer, + binary_type: jsc.ArrayBuffer.BinaryType = .Buffer, on_data: JSValue = .zero, on_drain: JSValue = .zero, on_error: JSValue = .zero, @@ -176,7 +176,7 @@ pub const UDPSocketConfig = struct { return globalThis.throwInvalidArguments("Expected \"socket.binaryType\" to be a string", .{}); } - config.binary_type = try JSC.ArrayBuffer.BinaryType.fromJSValue(globalThis, value) orelse { + config.binary_type = try jsc.ArrayBuffer.BinaryType.fromJSValue(globalThis, value) orelse { return globalThis.throwInvalidArguments("Expected \"socket.binaryType\" to be 'arraybuffer', 'uint8array', or 'buffer'", .{}); }; } @@ -264,19 +264,19 @@ pub const UDPSocket = struct { globalThis: *JSGlobalObject, thisValue: JSValue = .zero, - jsc_ref: JSC.Ref = JSC.Ref.init(), + jsc_ref: jsc.Ref = jsc.Ref.init(), poll_ref: Async.KeepAlive = Async.KeepAlive.init(), // if marked as closed the socket pointer may be stale closed: bool = false, connect_info: ?ConnectInfo = null, - vm: *JSC.VirtualMachine, + vm: *jsc.VirtualMachine, js_refcount: std.atomic.Value(usize) = std.atomic.Value(usize).init(1), const ConnectInfo = struct { port: u16, }; - pub const js = JSC.Codegen.JSUDPSocket; + pub const js = jsc.Codegen.JSUDPSocket; pub const toJS = js.toJS; pub const fromJS = js.fromJS; pub const fromJSDirect = js.fromJSDirect; @@ -320,7 +320,7 @@ pub const UDPSocket = struct { defer this.deinit(); if (err != 0) { const code = @tagName(bun.sys.SystemErrno.init(@as(c_int, @intCast(err))).?); - const sys_err = JSC.SystemError{ + const sys_err = jsc.SystemError{ .errno = err, .code = bun.String.static(code), .message = bun.String.createFormat("bind {s} {s}", .{ code, config.hostname }) catch bun.outOfMemory(), @@ -340,7 +340,7 @@ pub const UDPSocket = struct { if (config.connect) |connect| { const ret = this.socket.connect(connect.address, connect.port); if (ret != 0) { - if (JSC.Maybe(void).errnoSys(ret, .connect)) |sys_err| { + if (jsc.Maybe(void).errnoSys(ret, .connect)) |sys_err| { return globalThis.throwValue(try sys_err.toJS(globalThis)); } @@ -355,7 +355,7 @@ pub const UDPSocket = struct { const thisValue = this.toJS(globalThis); thisValue.ensureStillAlive(); this.thisValue = thisValue; - return JSC.JSPromise.resolvedPromiseValue(globalThis, thisValue); + return jsc.JSPromise.resolvedPromiseValue(globalThis, thisValue); } pub fn callErrorHandler( @@ -380,7 +380,7 @@ pub const UDPSocket = struct { pub fn setBroadcast(this: *This, globalThis: *JSGlobalObject, callframe: *CallFrame) bun.JSError!JSValue { if (this.closed) { - return globalThis.throwValue(try bun.JSC.Maybe(void).errnoSys(@as(i32, @intCast(@intFromEnum(std.posix.E.BADF))), .setsockopt).?.toJS(globalThis)); + return globalThis.throwValue(try bun.jsc.Maybe(void).errnoSys(@as(i32, @intCast(@intFromEnum(std.posix.E.BADF))), .setsockopt).?.toJS(globalThis)); } const arguments = callframe.arguments(); @@ -400,7 +400,7 @@ pub const UDPSocket = struct { pub fn setMulticastLoopback(this: *This, globalThis: *JSGlobalObject, callframe: *CallFrame) bun.JSError!JSValue { if (this.closed) { - return globalThis.throwValue(try bun.JSC.Maybe(void).errnoSys(@as(i32, @intCast(@intFromEnum(std.posix.E.BADF))), .setsockopt).?.toJS(globalThis)); + return globalThis.throwValue(try bun.jsc.Maybe(void).errnoSys(@as(i32, @intCast(@intFromEnum(std.posix.E.BADF))), .setsockopt).?.toJS(globalThis)); } const arguments = callframe.arguments(); @@ -420,7 +420,7 @@ pub const UDPSocket = struct { fn setMembership(this: *This, globalThis: *JSGlobalObject, callframe: *CallFrame, drop: bool) bun.JSError!JSValue { if (this.closed) { - return globalThis.throwValue(try bun.JSC.Maybe(void).errnoSys(@as(i32, @intCast(@intFromEnum(std.posix.E.BADF))), .setsockopt).?.toJS(globalThis)); + return globalThis.throwValue(try bun.jsc.Maybe(void).errnoSys(@as(i32, @intCast(@intFromEnum(std.posix.E.BADF))), .setsockopt).?.toJS(globalThis)); } const arguments = callframe.arguments(); @@ -429,13 +429,13 @@ pub const UDPSocket = struct { } var addr = std.mem.zeroes(std.posix.sockaddr.storage); - if (!try parseAddr(this, globalThis, JSC.jsNumber(0), arguments[0], &addr)) { - return globalThis.throwValue(try bun.JSC.Maybe(void).errnoSys(@as(i32, @intCast(@intFromEnum(std.posix.E.INVAL))), .setsockopt).?.toJS(globalThis)); + if (!try parseAddr(this, globalThis, jsc.jsNumber(0), arguments[0], &addr)) { + return globalThis.throwValue(try bun.jsc.Maybe(void).errnoSys(@as(i32, @intCast(@intFromEnum(std.posix.E.INVAL))), .setsockopt).?.toJS(globalThis)); } var interface = std.mem.zeroes(std.posix.sockaddr.storage); - const res = if (arguments.len > 1 and try parseAddr(this, globalThis, JSC.jsNumber(0), arguments[1], &interface)) blk: { + const res = if (arguments.len > 1 and try parseAddr(this, globalThis, jsc.jsNumber(0), arguments[1], &interface)) blk: { if (addr.family != interface.family) { return globalThis.throwInvalidArguments("Family mismatch between address and interface", .{}); } @@ -459,7 +459,7 @@ pub const UDPSocket = struct { fn setSourceSpecificMembership(this: *This, globalThis: *JSGlobalObject, callframe: *CallFrame, drop: bool) bun.JSError!JSValue { if (this.closed) { - return globalThis.throwValue(try bun.JSC.Maybe(void).errnoSys(@as(i32, @intCast(@intFromEnum(std.posix.E.BADF))), .setsockopt).?.toJS(globalThis)); + return globalThis.throwValue(try bun.jsc.Maybe(void).errnoSys(@as(i32, @intCast(@intFromEnum(std.posix.E.BADF))), .setsockopt).?.toJS(globalThis)); } const arguments = callframe.arguments(); @@ -468,13 +468,13 @@ pub const UDPSocket = struct { } var source_addr: std.posix.sockaddr.storage = undefined; - if (!try parseAddr(this, globalThis, JSC.jsNumber(0), arguments[0], &source_addr)) { - return globalThis.throwValue(try bun.JSC.Maybe(void).errnoSys(@as(i32, @intCast(@intFromEnum(std.posix.E.INVAL))), .setsockopt).?.toJS(globalThis)); + if (!try parseAddr(this, globalThis, jsc.jsNumber(0), arguments[0], &source_addr)) { + return globalThis.throwValue(try bun.jsc.Maybe(void).errnoSys(@as(i32, @intCast(@intFromEnum(std.posix.E.INVAL))), .setsockopt).?.toJS(globalThis)); } var group_addr: std.posix.sockaddr.storage = undefined; - if (!try parseAddr(this, globalThis, JSC.jsNumber(0), arguments[1], &group_addr)) { - return globalThis.throwValue(try bun.JSC.Maybe(void).errnoSys(@as(i32, @intCast(@intFromEnum(std.posix.E.INVAL))), .setsockopt).?.toJS(globalThis)); + if (!try parseAddr(this, globalThis, jsc.jsNumber(0), arguments[1], &group_addr)) { + return globalThis.throwValue(try bun.jsc.Maybe(void).errnoSys(@as(i32, @intCast(@intFromEnum(std.posix.E.INVAL))), .setsockopt).?.toJS(globalThis)); } if (source_addr.family != group_addr.family) { @@ -483,7 +483,7 @@ pub const UDPSocket = struct { var interface: std.posix.sockaddr.storage = undefined; - const res = if (arguments.len > 2 and try parseAddr(this, globalThis, JSC.jsNumber(0), arguments[2], &interface)) blk: { + const res = if (arguments.len > 2 and try parseAddr(this, globalThis, jsc.jsNumber(0), arguments[2], &interface)) blk: { if (source_addr.family != interface.family) { return globalThis.throwInvalidArguments("Family mismatch among source, group and interface addresses", .{}); } @@ -507,7 +507,7 @@ pub const UDPSocket = struct { pub fn setMulticastInterface(this: *This, globalThis: *JSGlobalObject, callframe: *CallFrame) bun.JSError!JSValue { if (this.closed) { - return globalThis.throwValue(try bun.JSC.Maybe(void).errnoSys(@as(i32, @intCast(@intFromEnum(std.posix.E.BADF))), .setsockopt).?.toJS(globalThis)); + return globalThis.throwValue(try bun.jsc.Maybe(void).errnoSys(@as(i32, @intCast(@intFromEnum(std.posix.E.BADF))), .setsockopt).?.toJS(globalThis)); } const arguments = callframe.arguments(); @@ -517,7 +517,7 @@ pub const UDPSocket = struct { var addr: std.posix.sockaddr.storage = undefined; - if (!try parseAddr(this, globalThis, JSC.jsNumber(0), arguments[0], &addr)) { + if (!try parseAddr(this, globalThis, jsc.jsNumber(0), arguments[0], &addr)) { return .false; } @@ -538,7 +538,7 @@ pub const UDPSocket = struct { return setAnyTTL(this, globalThis, callframe, uws.udp.Socket.setMulticastTTL); } - fn getUSError(res: c_int, tag: bun.sys.Tag, comptime use_wsa: bool) ?bun.JSC.Maybe(void) { + fn getUSError(res: c_int, tag: bun.sys.Tag, comptime use_wsa: bool) ?bun.jsc.Maybe(void) { if (comptime bun.Environment.isWindows) { // setsockopt returns 0 on success, but errnoSys considers 0 to be failure on Windows. // This applies to some other usockets functions too. @@ -550,20 +550,20 @@ pub const UDPSocket = struct { if (bun.windows.WSAGetLastError()) |wsa| { if (wsa != .SUCCESS) { std.os.windows.ws2_32.WSASetLastError(0); - return bun.JSC.Maybe(void).errno(wsa.toE(), tag); + return bun.jsc.Maybe(void).errno(wsa.toE(), tag); } } } - return bun.JSC.Maybe(void).errno(@as(bun.sys.E, @enumFromInt(std.c._errno().*)), tag); + return bun.jsc.Maybe(void).errno(@as(bun.sys.E, @enumFromInt(std.c._errno().*)), tag); } else { - return bun.JSC.Maybe(void).errnoSys(res, tag); + return bun.jsc.Maybe(void).errnoSys(res, tag); } } fn setAnyTTL(this: *This, globalThis: *JSGlobalObject, callframe: *CallFrame, comptime function: fn (*uws.udp.Socket, i32) c_int) bun.JSError!JSValue { if (this.closed) { - return globalThis.throwValue(try bun.JSC.Maybe(void).errnoSys(@as(i32, @intCast(@intFromEnum(std.posix.E.BADF))), .setsockopt).?.toJS(globalThis)); + return globalThis.throwValue(try bun.jsc.Maybe(void).errnoSys(@as(i32, @intCast(@intFromEnum(std.posix.E.BADF))), .setsockopt).?.toJS(globalThis)); } const arguments = callframe.arguments(); @@ -684,7 +684,7 @@ pub const UDPSocket = struct { }; const payload_arg = arguments.ptr[0]; - var payload_str = JSC.ZigString.Slice.empty; + var payload_str = jsc.ZigString.Slice.empty; defer payload_str.deinit(); const payload = brk: { if (payload_arg.asArrayBuffer(globalThis)) |array_buffer| { @@ -777,7 +777,7 @@ pub const UDPSocket = struct { address: JSValue, }; - pub fn ref(this: *This, globalThis: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!JSValue { + pub fn ref(this: *This, globalThis: *jsc.JSGlobalObject, _: *jsc.CallFrame) bun.JSError!JSValue { if (!this.closed) { this.poll_ref.ref(globalThis.bunVM()); } @@ -785,7 +785,7 @@ pub const UDPSocket = struct { return .js_undefined; } - pub fn unref(this: *This, globalThis: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!JSValue { + pub fn unref(this: *This, globalThis: *jsc.JSGlobalObject, _: *jsc.CallFrame) bun.JSError!JSValue { this.poll_ref.unref(globalThis.bunVM()); return .js_undefined; @@ -824,7 +824,7 @@ pub const UDPSocket = struct { } pub fn getHostname(this: *This, _: *JSGlobalObject) JSValue { - const hostname = JSC.ZigString.init(this.config.hostname); + const hostname = jsc.ZigString.init(this.config.hostname); return hostname.toJS(this.globalThis); } @@ -849,7 +849,7 @@ pub const UDPSocket = struct { return createSockAddr(globalThis, address_bytes, @intCast(port)); } - pub fn getRemoteAddress(this: *This, globalThis: *JSC.JSGlobalObject) JSC.JSValue { + pub fn getRemoteAddress(this: *This, globalThis: *jsc.JSGlobalObject) jsc.JSValue { if (this.closed) return .js_undefined; const connect_info = this.connect_info orelse return .js_undefined; var buf: [64]u8 = [_]u8{0} ** 64; @@ -886,7 +886,7 @@ pub const UDPSocket = struct { bun.destroy(this); } - pub fn jsConnect(globalThis: *JSC.JSGlobalObject, callFrame: *JSC.CallFrame) bun.JSError!JSC.JSValue { + pub fn jsConnect(globalThis: *jsc.JSGlobalObject, callFrame: *jsc.CallFrame) bun.JSError!jsc.JSValue { const args = callFrame.arguments_old(2); const this = callFrame.this().as(UDPSocket) orelse { @@ -932,7 +932,7 @@ pub const UDPSocket = struct { return .js_undefined; } - pub fn jsDisconnect(globalObject: *JSC.JSGlobalObject, callFrame: *JSC.CallFrame) bun.JSError!JSC.JSValue { + pub fn jsDisconnect(globalObject: *jsc.JSGlobalObject, callFrame: *jsc.CallFrame) bun.JSError!jsc.JSValue { const this = callFrame.this().as(UDPSocket) orelse { return globalObject.throwInvalidArguments("Expected UDPSocket as 'this'", .{}); }; @@ -962,8 +962,8 @@ const Async = bun.Async; const Output = bun.Output; const default_allocator = bun.default_allocator; -const JSC = bun.JSC; -const CallFrame = JSC.CallFrame; -const JSGlobalObject = JSC.JSGlobalObject; -const JSValue = JSC.JSValue; -const SocketAddress = JSC.API.SocketAddress; +const jsc = bun.jsc; +const CallFrame = jsc.CallFrame; +const JSGlobalObject = jsc.JSGlobalObject; +const JSValue = jsc.JSValue; +const SocketAddress = jsc.API.SocketAddress; diff --git a/src/bun.js/api/bun/x509.zig b/src/bun.js/api/bun/x509.zig index c6339c80f1..acbe38eb7a 100644 --- a/src/bun.js/api/bun/x509.zig +++ b/src/bun.js/api/bun/x509.zig @@ -52,6 +52,6 @@ extern fn Bun__X509__toJS(cert: *BoringSSL.X509, globalObject: *JSGlobalObject) const bun = @import("bun"); const BoringSSL = bun.BoringSSL.c; -const JSC = bun.JSC; -const JSGlobalObject = JSC.JSGlobalObject; -const JSValue = JSC.JSValue; +const jsc = bun.jsc; +const JSGlobalObject = jsc.JSGlobalObject; +const JSValue = jsc.JSValue; diff --git a/src/bun.js/api/crypto.zig b/src/bun.js/api/crypto.zig index c091f8a6cc..2945528252 100644 --- a/src/bun.js/api/crypto.zig +++ b/src/bun.js/api/crypto.zig @@ -1,4 +1,4 @@ -pub fn createCryptoError(globalThis: *JSC.JSGlobalObject, err_code: u32) JSValue { +pub fn createCryptoError(globalThis: *jsc.JSGlobalObject, err_code: u32) JSValue { return bun.BoringSSL.ERR_toJS(globalThis, err_code); } @@ -23,6 +23,6 @@ comptime { const bun = @import("bun"); -const JSC = bun.JSC; -const JSGlobalObject = JSC.JSGlobalObject; -const JSValue = JSC.JSValue; +const jsc = bun.jsc; +const JSGlobalObject = jsc.JSGlobalObject; +const JSValue = jsc.JSValue; diff --git a/src/bun.js/api/crypto/CryptoHasher.zig b/src/bun.js/api/crypto/CryptoHasher.zig index c82c7f9354..f72080f38a 100644 --- a/src/bun.js/api/crypto/CryptoHasher.zig +++ b/src/bun.js/api/crypto/CryptoHasher.zig @@ -7,7 +7,7 @@ pub const CryptoHasher = union(enum) { const Digest = EVP.Digest; - pub const js = JSC.Codegen.JSCryptoHasher; + pub const js = jsc.Codegen.JSCryptoHasher; pub const toJS = js.toJS; pub const fromJS = js.fromJS; pub const fromJSDirect = js.fromJSDirect; @@ -128,15 +128,15 @@ pub const CryptoHasher = union(enum) { } }; - pub const digest = JSC.host_fn.wrapInstanceMethod(CryptoHasher, "digest_", false); - pub const hash = JSC.host_fn.wrapStaticMethod(CryptoHasher, "hash_", false); + pub const digest = jsc.host_fn.wrapInstanceMethod(CryptoHasher, "digest_", false); + pub const hash = jsc.host_fn.wrapStaticMethod(CryptoHasher, "hash_", false); - fn throwHmacConsumed(globalThis: *JSC.JSGlobalObject) bun.JSError { + fn throwHmacConsumed(globalThis: *jsc.JSGlobalObject) bun.JSError { return globalThis.throw("HMAC has been consumed and is no longer usable", .{}); } - pub fn getByteLength(this: *CryptoHasher, globalThis: *JSC.JSGlobalObject) bun.JSError!JSC.JSValue { - return JSC.JSValue.jsNumber(switch (this.*) { + pub fn getByteLength(this: *CryptoHasher, globalThis: *jsc.JSGlobalObject) bun.JSError!jsc.JSValue { + return jsc.JSValue.jsNumber(switch (this.*) { .evp => |*inner| inner.size(), .hmac => |inner| if (inner) |hmac| hmac.size() else { return throwHmacConsumed(globalThis); @@ -145,7 +145,7 @@ pub const CryptoHasher = union(enum) { }); } - pub fn getAlgorithm(this: *CryptoHasher, globalObject: *JSC.JSGlobalObject) bun.JSError!JSC.JSValue { + pub fn getAlgorithm(this: *CryptoHasher, globalObject: *jsc.JSGlobalObject) bun.JSError!jsc.JSValue { return switch (this.*) { inline .evp, .zig => |*inner| ZigString.fromUTF8(bun.asByteSlice(@tagName(inner.algorithm))).toJS(globalObject), .hmac => |inner| if (inner) |hmac| ZigString.fromUTF8(bun.asByteSlice(@tagName(hmac.algorithm))).toJS(globalObject) else { @@ -154,11 +154,11 @@ pub const CryptoHasher = union(enum) { }; } - pub fn getAlgorithms(globalThis_: *JSC.JSGlobalObject, _: JSValue, _: JSValue) bun.JSError!JSC.JSValue { + pub fn getAlgorithms(globalThis_: *jsc.JSGlobalObject, _: JSValue, _: JSValue) bun.JSError!jsc.JSValue { return bun.String.toJSArray(globalThis_, &EVP.Algorithm.names.values); } - fn hashToEncoding(globalThis: *JSGlobalObject, evp: *EVP, input: JSC.Node.BlobOrStringOrBuffer, encoding: JSC.Node.Encoding) bun.JSError!JSC.JSValue { + fn hashToEncoding(globalThis: *JSGlobalObject, evp: *EVP, input: jsc.Node.BlobOrStringOrBuffer, encoding: jsc.Node.Encoding) bun.JSError!jsc.JSValue { var output_digest_buf: Digest = undefined; defer input.deinit(); @@ -175,7 +175,7 @@ pub const CryptoHasher = union(enum) { return encoding.encodeWithMaxSize(globalThis, BoringSSL.EVP_MAX_MD_SIZE, output_digest_buf[0..len]); } - fn hashToBytes(globalThis: *JSGlobalObject, evp: *EVP, input: JSC.Node.BlobOrStringOrBuffer, output: ?JSC.ArrayBuffer) bun.JSError!JSC.JSValue { + fn hashToBytes(globalThis: *JSGlobalObject, evp: *EVP, input: jsc.Node.BlobOrStringOrBuffer, output: ?jsc.ArrayBuffer) bun.JSError!jsc.JSValue { var output_digest_buf: Digest = undefined; var output_digest_slice: []u8 = &output_digest_buf; defer input.deinit(); @@ -204,16 +204,16 @@ pub const CryptoHasher = union(enum) { return output_buf.value; } else { // Clone to GC-managed memory - return JSC.ArrayBuffer.createBuffer(globalThis, output_digest_slice[0..len]); + return jsc.ArrayBuffer.createBuffer(globalThis, output_digest_slice[0..len]); } } pub fn hash_( globalThis: *JSGlobalObject, algorithm: ZigString, - input: JSC.Node.BlobOrStringOrBuffer, - output: ?JSC.Node.StringOrBuffer, - ) bun.JSError!JSC.JSValue { + input: jsc.Node.BlobOrStringOrBuffer, + output: ?jsc.Node.StringOrBuffer, + ) bun.JSError!jsc.JSValue { var evp = EVP.byName(algorithm, globalThis) orelse return try CryptoHasherZig.hashByName(globalThis, algorithm, input, output) orelse { return globalThis.throwInvalidArguments("Unsupported algorithm \"{any}\"", .{algorithm}); }; @@ -223,7 +223,7 @@ pub const CryptoHasher = union(enum) { switch (string_or_buffer) { inline else => |*str| { defer str.deinit(); - const encoding = JSC.Node.Encoding.from(str.slice()) orelse { + const encoding = jsc.Node.Encoding.from(str.slice()) orelse { return globalThis.ERR(.INVALID_ARG_VALUE, "Unknown encoding: {s}", .{str.slice()}).throw(); }; @@ -239,7 +239,7 @@ pub const CryptoHasher = union(enum) { } // Bun.CryptoHasher(algorithm, hmacKey?: string | Buffer) - pub fn constructor(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!*CryptoHasher { + pub fn constructor(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!*CryptoHasher { const arguments = callframe.arguments_old(2); if (arguments.len == 0) { return globalThis.throwInvalidArguments("Expected an algorithm name as an argument", .{}); @@ -257,7 +257,7 @@ pub const CryptoHasher = union(enum) { } const hmac_value = arguments.ptr[1]; - var hmac_key: ?JSC.Node.StringOrBuffer = null; + var hmac_key: ?jsc.Node.StringOrBuffer = null; defer { if (hmac_key) |*key| { key.deinit(); @@ -265,7 +265,7 @@ pub const CryptoHasher = union(enum) { } if (!hmac_value.isEmptyOrUndefinedOrNull()) { - hmac_key = try JSC.Node.StringOrBuffer.fromJS(globalThis, bun.default_allocator, hmac_value) orelse { + hmac_key = try jsc.Node.StringOrBuffer.fromJS(globalThis, bun.default_allocator, hmac_value) orelse { return globalThis.throwInvalidArguments("key must be a string or buffer", .{}); }; } @@ -304,13 +304,13 @@ pub const CryptoHasher = union(enum) { } pub fn getter( - globalObject: *JSC.JSGlobalObject, - _: *JSC.JSObject, - ) JSC.JSValue { + globalObject: *jsc.JSGlobalObject, + _: *jsc.JSObject, + ) jsc.JSValue { return CryptoHasher.js.getConstructor(globalObject); } - pub fn update(this: *CryptoHasher, globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { + pub fn update(this: *CryptoHasher, globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const thisValue = callframe.this(); const arguments = callframe.arguments_old(2); const input = arguments.ptr[0]; @@ -318,7 +318,7 @@ pub const CryptoHasher = union(enum) { return globalThis.throwInvalidArguments("expected blob, string or buffer", .{}); } const encoding = arguments.ptr[1]; - const buffer = try JSC.Node.BlobOrStringOrBuffer.fromJSWithEncodingValue(globalThis, globalThis.bunVM().allocator, input, encoding) orelse { + const buffer = try jsc.Node.BlobOrStringOrBuffer.fromJSWithEncodingValue(globalThis, globalThis.bunVM().allocator, input, encoding) orelse { if (!globalThis.hasException()) return globalThis.throwInvalidArguments("expected blob, string or buffer", .{}); return error.JSError; }; @@ -361,9 +361,9 @@ pub const CryptoHasher = union(enum) { pub fn copy( this: *CryptoHasher, - globalObject: *JSC.JSGlobalObject, - _: *JSC.CallFrame, - ) bun.JSError!JSC.JSValue { + globalObject: *jsc.JSGlobalObject, + _: *jsc.CallFrame, + ) bun.JSError!jsc.JSValue { const copied: CryptoHasher = switch (this.*) { .evp => |*inner| .{ .evp = inner.copy(globalObject.bunVM().rareData().boringEngine()) catch bun.outOfMemory() }, .hmac => |inner| brk: { @@ -383,12 +383,12 @@ pub const CryptoHasher = union(enum) { return CryptoHasher.new(copied).toJS(globalObject); } - pub fn digest_(this: *CryptoHasher, globalThis: *JSGlobalObject, output: ?JSC.Node.StringOrBuffer) bun.JSError!JSC.JSValue { + pub fn digest_(this: *CryptoHasher, globalThis: *JSGlobalObject, output: ?jsc.Node.StringOrBuffer) bun.JSError!jsc.JSValue { if (output) |string_or_buffer| { switch (string_or_buffer) { inline else => |*str| { defer str.deinit(); - const encoding = JSC.Node.Encoding.from(str.slice()) orelse { + const encoding = jsc.Node.Encoding.from(str.slice()) orelse { return globalThis.ERR(.INVALID_ARG_VALUE, "Unknown encoding: {s}", .{str.slice()}).throw(); }; @@ -406,7 +406,7 @@ pub const CryptoHasher = union(enum) { } } - fn digestToBytes(this: *CryptoHasher, globalThis: *JSGlobalObject, output: ?JSC.ArrayBuffer) bun.JSError!JSC.JSValue { + fn digestToBytes(this: *CryptoHasher, globalThis: *JSGlobalObject, output: ?jsc.ArrayBuffer) bun.JSError!jsc.JSValue { var output_digest_buf: EVP.Digest = undefined; var output_digest_slice: []u8 = &output_digest_buf; if (output) |output_buf| { @@ -428,11 +428,11 @@ pub const CryptoHasher = union(enum) { return output_buf.value; } else { // Clone to GC-managed memory - return JSC.ArrayBuffer.createBuffer(globalThis, result); + return jsc.ArrayBuffer.createBuffer(globalThis, result); } } - fn digestToEncoding(this: *CryptoHasher, globalThis: *JSGlobalObject, encoding: JSC.Node.Encoding) bun.JSError!JSC.JSValue { + fn digestToEncoding(this: *CryptoHasher, globalThis: *JSGlobalObject, encoding: jsc.Node.Encoding) bun.JSError!jsc.JSValue { var output_digest_buf: EVP.Digest = std.mem.zeroes(EVP.Digest); const output_digest_slice: []u8 = &output_digest_buf; const out = this.final(globalThis, output_digest_slice) catch return .zero; @@ -498,7 +498,7 @@ const CryptoHasherZig = struct { }; } - pub fn hashByName(globalThis: *JSGlobalObject, algorithm: ZigString, input: JSC.Node.BlobOrStringOrBuffer, output: ?JSC.Node.StringOrBuffer) bun.JSError!?JSC.JSValue { + pub fn hashByName(globalThis: *JSGlobalObject, algorithm: ZigString, input: jsc.Node.BlobOrStringOrBuffer, output: ?jsc.Node.StringOrBuffer) bun.JSError!?jsc.JSValue { inline for (algo_map) |item| { if (bun.strings.eqlComptime(algorithm.slice(), item[0])) { return try hashByNameInner(globalThis, item[1], input, output); @@ -507,12 +507,12 @@ const CryptoHasherZig = struct { return null; } - fn hashByNameInner(globalThis: *JSGlobalObject, comptime Algorithm: type, input: JSC.Node.BlobOrStringOrBuffer, output: ?JSC.Node.StringOrBuffer) bun.JSError!JSC.JSValue { + fn hashByNameInner(globalThis: *JSGlobalObject, comptime Algorithm: type, input: jsc.Node.BlobOrStringOrBuffer, output: ?jsc.Node.StringOrBuffer) bun.JSError!jsc.JSValue { if (output) |string_or_buffer| { switch (string_or_buffer) { inline else => |*str| { defer str.deinit(); - const encoding = JSC.Node.Encoding.from(str.slice()) orelse { + const encoding = jsc.Node.Encoding.from(str.slice()) orelse { return globalThis.ERR(.INVALID_ARG_VALUE, "Unknown encoding: {s}", .{str.slice()}).throw(); }; @@ -530,7 +530,7 @@ const CryptoHasherZig = struct { return hashByNameInnerToBytes(globalThis, Algorithm, input, null); } - fn hashByNameInnerToString(globalThis: *JSGlobalObject, comptime Algorithm: type, input: JSC.Node.BlobOrStringOrBuffer, encoding: JSC.Node.Encoding) bun.JSError!JSC.JSValue { + fn hashByNameInnerToString(globalThis: *JSGlobalObject, comptime Algorithm: type, input: jsc.Node.BlobOrStringOrBuffer, encoding: jsc.Node.Encoding) bun.JSError!jsc.JSValue { defer input.deinit(); if (input == .blob and input.blob.isBunFile()) { @@ -546,7 +546,7 @@ const CryptoHasherZig = struct { return encoding.encodeWithSize(globalThis, digestLength(Algorithm), &out); } - fn hashByNameInnerToBytes(globalThis: *JSGlobalObject, comptime Algorithm: type, input: JSC.Node.BlobOrStringOrBuffer, output: ?JSC.ArrayBuffer) bun.JSError!JSC.JSValue { + fn hashByNameInnerToBytes(globalThis: *JSGlobalObject, comptime Algorithm: type, input: jsc.Node.BlobOrStringOrBuffer, output: ?jsc.ArrayBuffer) bun.JSError!jsc.JSValue { defer input.deinit(); if (input == .blob and input.blob.isBunFile()) { @@ -571,7 +571,7 @@ const CryptoHasherZig = struct { var out: [digestLength(Algorithm)]u8 = undefined; h.final(&out); // Clone to GC-managed memory - return JSC.ArrayBuffer.createBuffer(globalThis, &out); + return jsc.ArrayBuffer.createBuffer(globalThis, &out); } } @@ -660,7 +660,7 @@ fn StaticCryptoHasher(comptime Hasher: type, comptime name: [:0]const u8) type { const ThisHasher = @This(); - pub const js = @field(JSC.Codegen, "JS" ++ name); + pub const js = @field(jsc.Codegen, "JS" ++ name); pub const toJS = js.toJS; pub const fromJS = js.fromJS; pub const fromJSDirect = js.fromJSDirect; @@ -670,20 +670,20 @@ fn StaticCryptoHasher(comptime Hasher: type, comptime name: [:0]const u8) type { pub fn getByteLength( _: *@This(), - _: *JSC.JSGlobalObject, - ) JSC.JSValue { - return JSC.JSValue.jsNumber(@as(u16, Hasher.digest)); + _: *jsc.JSGlobalObject, + ) jsc.JSValue { + return jsc.JSValue.jsNumber(@as(u16, Hasher.digest)); } pub fn getByteLengthStatic( - _: *JSC.JSGlobalObject, + _: *jsc.JSGlobalObject, _: JSValue, _: JSValue, - ) JSC.JSValue { - return JSC.JSValue.jsNumber(@as(u16, Hasher.digest)); + ) jsc.JSValue { + return jsc.JSValue.jsNumber(@as(u16, Hasher.digest)); } - fn hashToEncoding(globalThis: *JSGlobalObject, input: JSC.Node.BlobOrStringOrBuffer, encoding: JSC.Node.Encoding) bun.JSError!JSC.JSValue { + fn hashToEncoding(globalThis: *JSGlobalObject, input: jsc.Node.BlobOrStringOrBuffer, encoding: jsc.Node.Encoding) bun.JSError!jsc.JSValue { var output_digest_buf: Hasher.Digest = undefined; if (input == .blob and input.blob.isBunFile()) { @@ -691,7 +691,7 @@ fn StaticCryptoHasher(comptime Hasher: type, comptime name: [:0]const u8) type { } if (comptime @typeInfo(@TypeOf(Hasher.hash)).@"fn".params.len == 3) { - Hasher.hash(input.slice(), &output_digest_buf, JSC.VirtualMachine.get().rareData().boringEngine()); + Hasher.hash(input.slice(), &output_digest_buf, jsc.VirtualMachine.get().rareData().boringEngine()); } else { Hasher.hash(input.slice(), &output_digest_buf); } @@ -699,7 +699,7 @@ fn StaticCryptoHasher(comptime Hasher: type, comptime name: [:0]const u8) type { return encoding.encodeWithSize(globalThis, Hasher.digest, &output_digest_buf); } - fn hashToBytes(globalThis: *JSGlobalObject, input: JSC.Node.BlobOrStringOrBuffer, output: ?JSC.ArrayBuffer) bun.JSError!JSC.JSValue { + fn hashToBytes(globalThis: *JSGlobalObject, input: jsc.Node.BlobOrStringOrBuffer, output: ?jsc.ArrayBuffer) bun.JSError!jsc.JSValue { var output_digest_buf: Hasher.Digest = undefined; var output_digest_slice: *Hasher.Digest = &output_digest_buf; if (output) |output_buf| { @@ -711,7 +711,7 @@ fn StaticCryptoHasher(comptime Hasher: type, comptime name: [:0]const u8) type { } if (comptime @typeInfo(@TypeOf(Hasher.hash)).@"fn".params.len == 3) { - Hasher.hash(input.slice(), output_digest_slice, JSC.VirtualMachine.get().rareData().boringEngine()); + Hasher.hash(input.slice(), output_digest_slice, jsc.VirtualMachine.get().rareData().boringEngine()); } else { Hasher.hash(input.slice(), output_digest_slice); } @@ -719,16 +719,16 @@ fn StaticCryptoHasher(comptime Hasher: type, comptime name: [:0]const u8) type { if (output) |output_buf| { return output_buf.value; } else { - var array_buffer_out = JSC.ArrayBuffer.fromBytes(bun.default_allocator.dupe(u8, output_digest_slice) catch unreachable, .Uint8Array); + var array_buffer_out = jsc.ArrayBuffer.fromBytes(bun.default_allocator.dupe(u8, output_digest_slice) catch unreachable, .Uint8Array); return array_buffer_out.toJSUnchecked(globalThis); } } pub fn hash_( globalThis: *JSGlobalObject, - input: JSC.Node.BlobOrStringOrBuffer, - output: ?JSC.Node.StringOrBuffer, - ) bun.JSError!JSC.JSValue { + input: jsc.Node.BlobOrStringOrBuffer, + output: ?jsc.Node.StringOrBuffer, + ) bun.JSError!jsc.JSValue { defer input.deinit(); if (input == .blob and input.blob.isBunFile()) { @@ -739,7 +739,7 @@ fn StaticCryptoHasher(comptime Hasher: type, comptime name: [:0]const u8) type { switch (string_or_buffer) { inline else => |*str| { defer str.deinit(); - const encoding = JSC.Node.Encoding.from(str.slice()) orelse { + const encoding = jsc.Node.Encoding.from(str.slice()) orelse { return globalThis.ERR(.INVALID_ARG_VALUE, "Unknown encoding: {s}", .{str.slice()}).throw(); }; @@ -754,26 +754,26 @@ fn StaticCryptoHasher(comptime Hasher: type, comptime name: [:0]const u8) type { } } - pub fn constructor(_: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!*@This() { + pub fn constructor(_: *jsc.JSGlobalObject, _: *jsc.CallFrame) bun.JSError!*@This() { const this = try bun.default_allocator.create(@This()); this.* = .{ .hashing = Hasher.init() }; return this; } pub fn getter( - globalObject: *JSC.JSGlobalObject, - _: *JSC.JSObject, - ) JSC.JSValue { + globalObject: *jsc.JSGlobalObject, + _: *jsc.JSObject, + ) jsc.JSValue { return ThisHasher.js.getConstructor(globalObject); } - pub fn update(this: *@This(), globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { + pub fn update(this: *@This(), globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { if (this.digested) { return globalThis.ERR(.INVALID_STATE, name ++ " hasher already digested, create a new instance to update", .{}).throw(); } const thisValue = callframe.this(); const input = callframe.argument(0); - const buffer = try JSC.Node.BlobOrStringOrBuffer.fromJS(globalThis, globalThis.bunVM().allocator, input) orelse { + const buffer = try jsc.Node.BlobOrStringOrBuffer.fromJS(globalThis, globalThis.bunVM().allocator, input) orelse { return globalThis.throwInvalidArguments("expected blob or string or buffer", .{}); }; defer buffer.deinit(); @@ -788,8 +788,8 @@ fn StaticCryptoHasher(comptime Hasher: type, comptime name: [:0]const u8) type { pub fn digest_( this: *@This(), globalThis: *JSGlobalObject, - output: ?JSC.Node.StringOrBuffer, - ) bun.JSError!JSC.JSValue { + output: ?jsc.Node.StringOrBuffer, + ) bun.JSError!jsc.JSValue { if (this.digested) { return globalThis.ERR(.INVALID_STATE, name ++ " hasher already digested, create a new instance to digest again", .{}).throw(); } @@ -797,7 +797,7 @@ fn StaticCryptoHasher(comptime Hasher: type, comptime name: [:0]const u8) type { switch (string_or_buffer.*) { inline else => |*str| { defer str.deinit(); - const encoding = JSC.Node.Encoding.from(str.slice()) orelse { + const encoding = jsc.Node.Encoding.from(str.slice()) orelse { return globalThis.ERR(.INVALID_ARG_VALUE, "Unknown encoding: {s}", .{str.slice()}).throw(); }; @@ -815,7 +815,7 @@ fn StaticCryptoHasher(comptime Hasher: type, comptime name: [:0]const u8) type { } } - fn digestToBytes(this: *@This(), globalThis: *JSGlobalObject, output: ?JSC.ArrayBuffer) bun.JSError!JSC.JSValue { + fn digestToBytes(this: *@This(), globalThis: *JSGlobalObject, output: ?jsc.ArrayBuffer) bun.JSError!jsc.JSValue { var output_digest_buf: Hasher.Digest = undefined; var output_digest_slice: *Hasher.Digest = &output_digest_buf; if (output) |output_buf| { @@ -834,12 +834,12 @@ fn StaticCryptoHasher(comptime Hasher: type, comptime name: [:0]const u8) type { if (output) |output_buf| { return output_buf.value; } else { - var array_buffer_out = JSC.ArrayBuffer.fromBytes(bun.default_allocator.dupe(u8, &output_digest_buf) catch unreachable, .Uint8Array); + var array_buffer_out = jsc.ArrayBuffer.fromBytes(bun.default_allocator.dupe(u8, &output_digest_buf) catch unreachable, .Uint8Array); return array_buffer_out.toJSUnchecked(globalThis); } } - fn digestToEncoding(this: *@This(), globalThis: *JSGlobalObject, encoding: JSC.Node.Encoding) bun.JSError!JSC.JSValue { + fn digestToEncoding(this: *@This(), globalThis: *JSGlobalObject, encoding: jsc.Node.Encoding) bun.JSError!jsc.JSValue { var output_digest_buf: Hasher.Digest = comptime brk: { var bytes: Hasher.Digest = undefined; var i: usize = 0; @@ -873,24 +873,25 @@ pub const SHA384 = StaticCryptoHasher(Hashers.SHA384, "SHA384"); pub const SHA512 = StaticCryptoHasher(Hashers.SHA512, "SHA512"); pub const SHA512_256 = StaticCryptoHasher(Hashers.SHA512_256, "SHA512_256"); +const string = []const u8; + const Hashers = @import("../../../sha.zig"); const std = @import("std"); const bun = @import("bun"); const default_allocator = bun.default_allocator; -const string = bun.string; const strings = bun.strings; const BoringSSL = bun.BoringSSL.c; + +const jsc = bun.jsc; +const CallFrame = jsc.CallFrame; +const JSGlobalObject = jsc.JSGlobalObject; +const JSValue = jsc.JSValue; +const VirtualMachine = jsc.VirtualMachine; +const ZigString = jsc.ZigString; const host_fn = bun.jsc.host_fn; -const JSC = bun.JSC; -const CallFrame = JSC.CallFrame; -const JSGlobalObject = JSC.JSGlobalObject; -const JSValue = JSC.JSValue; -const VirtualMachine = JSC.VirtualMachine; -const ZigString = JSC.ZigString; - -const Crypto = JSC.API.Bun.Crypto; +const Crypto = jsc.API.Bun.Crypto; const EVP = Crypto.EVP; const HMAC = Crypto.HMAC; const createCryptoError = Crypto.createCryptoError; diff --git a/src/bun.js/api/crypto/EVP.zig b/src/bun.js/api/crypto/EVP.zig index e67c699ef5..14a976997f 100644 --- a/src/bun.js/api/crypto/EVP.zig +++ b/src/bun.js/api/crypto/EVP.zig @@ -190,7 +190,7 @@ pub fn byNameAndEngine(engine: *BoringSSL.ENGINE, name: []const u8) ?EVP { return null; } -pub fn byName(name: ZigString, global: *JSC.JSGlobalObject) ?EVP { +pub fn byName(name: ZigString, global: *jsc.JSGlobalObject) ?EVP { var name_str = name.toSlice(global.allocator()); defer name_str.deinit(); return byNameAndEngine(global.bunVM().rareData().boringEngine(), name_str.slice()); @@ -211,6 +211,6 @@ const bun = @import("bun"); const strings = bun.strings; const BoringSSL = bun.BoringSSL.c; -const JSC = bun.JSC; -const JSGlobalObject = JSC.JSGlobalObject; -const ZigString = JSC.ZigString; +const jsc = bun.jsc; +const JSGlobalObject = jsc.JSGlobalObject; +const ZigString = jsc.ZigString; diff --git a/src/bun.js/api/crypto/HMAC.zig b/src/bun.js/api/crypto/HMAC.zig index 9d1ede3d5f..9ec2f159f0 100644 --- a/src/bun.js/api/crypto/HMAC.zig +++ b/src/bun.js/api/crypto/HMAC.zig @@ -52,6 +52,6 @@ pub fn deinit(this: *HMAC) void { } const bun = @import("bun"); -const JSC = bun.JSC; +const jsc = bun.jsc; const BoringSSL = bun.BoringSSL.c; -const EVP = JSC.API.Bun.Crypto.EVP; +const EVP = jsc.API.Bun.Crypto.EVP; diff --git a/src/bun.js/api/crypto/PBKDF2.zig b/src/bun.js/api/crypto/PBKDF2.zig index 619bd58965..8ef641bac1 100644 --- a/src/bun.js/api/crypto/PBKDF2.zig +++ b/src/bun.js/api/crypto/PBKDF2.zig @@ -1,7 +1,7 @@ const PBKDF2 = @This(); -password: JSC.Node.StringOrBuffer = JSC.Node.StringOrBuffer.empty, -salt: JSC.Node.StringOrBuffer = JSC.Node.StringOrBuffer.empty, +password: jsc.Node.StringOrBuffer = jsc.Node.StringOrBuffer.empty, +salt: jsc.Node.StringOrBuffer = jsc.Node.StringOrBuffer.empty, iteration_count: u32 = 1, length: i32 = 0, algorithm: EVP.Algorithm, @@ -37,18 +37,18 @@ pub fn run(this: *PBKDF2, output: []u8) bool { pub const Job = struct { pbkdf2: PBKDF2, output: []u8 = &[_]u8{}, - task: JSC.WorkPoolTask = .{ .callback = &runTask }, - promise: JSC.JSPromise.Strong = .{}, - vm: *JSC.VirtualMachine, + task: jsc.WorkPoolTask = .{ .callback = &runTask }, + promise: jsc.JSPromise.Strong = .{}, + vm: *jsc.VirtualMachine, err: ?u32 = null, - any_task: JSC.AnyTask = undefined, + any_task: jsc.AnyTask = undefined, poll: Async.KeepAlive = .{}, pub const new = bun.TrivialNew(@This()); - pub fn runTask(task: *JSC.WorkPoolTask) void { + pub fn runTask(task: *jsc.WorkPoolTask) void { const job: *PBKDF2.Job = @fieldParentPtr("task", task); - defer job.vm.enqueueTaskConcurrent(JSC.ConcurrentTask.create(job.any_task.task())); + defer job.vm.enqueueTaskConcurrent(jsc.ConcurrentTask.create(job.any_task.task())); job.output = bun.default_allocator.alloc(u8, @as(usize, @intCast(job.pbkdf2.length))) catch { job.err = BoringSSL.EVP_R_MEMORY_LIMIT_EXCEEDED; return; @@ -77,7 +77,7 @@ pub const Job = struct { const output_slice = this.output; assert(output_slice.len == @as(usize, @intCast(this.pbkdf2.length))); - const buffer_value = JSC.JSValue.createBuffer(globalThis, output_slice, bun.default_allocator); + const buffer_value = jsc.JSValue.createBuffer(globalThis, output_slice, bun.default_allocator); this.output = &[_]u8{}; promise.resolve(globalThis, buffer_value); } @@ -90,17 +90,17 @@ pub const Job = struct { bun.destroy(this); } - pub fn create(vm: *JSC.VirtualMachine, globalThis: *JSC.JSGlobalObject, data: *const PBKDF2) *Job { + pub fn create(vm: *jsc.VirtualMachine, globalThis: *jsc.JSGlobalObject, data: *const PBKDF2) *Job { var job = Job.new(.{ .pbkdf2 = data.*, .vm = vm, .any_task = undefined, }); - job.promise = JSC.JSPromise.Strong.init(globalThis); - job.any_task = JSC.AnyTask.New(@This(), &runFromJS).init(job); + job.promise = jsc.JSPromise.Strong.init(globalThis); + job.any_task = jsc.AnyTask.New(@This(), &runFromJS).init(job); job.poll.ref(vm); - JSC.WorkPool.schedule(&job.task); + jsc.WorkPool.schedule(&job.task); return job; } @@ -116,7 +116,7 @@ pub fn deinit(this: *PBKDF2) void { this.salt.deinit(); } -pub fn fromJS(globalThis: *JSC.JSGlobalObject, callFrame: *JSC.CallFrame, is_async: bool) bun.JSError!PBKDF2 { +pub fn fromJS(globalThis: *jsc.JSGlobalObject, callFrame: *jsc.CallFrame, is_async: bool) bun.JSError!PBKDF2 { const arg0, const arg1, const arg2, const arg3, const arg4, const arg5 = callFrame.argumentsAsArray(6); if (!arg3.isNumber()) { @@ -192,7 +192,7 @@ pub fn fromJS(globalThis: *JSC.JSGlobalObject, callFrame: *JSC.CallFrame, is_asy } const allow_string_object = true; - out.salt = try JSC.Node.StringOrBuffer.fromJSMaybeAsync(globalThis, bun.default_allocator, arg1, is_async, allow_string_object) orelse { + out.salt = try jsc.Node.StringOrBuffer.fromJSMaybeAsync(globalThis, bun.default_allocator, arg1, is_async, allow_string_object) orelse { return globalThis.throwInvalidArgumentTypeValue("salt", "string or buffer", arg1); }; @@ -200,7 +200,7 @@ pub fn fromJS(globalThis: *JSC.JSGlobalObject, callFrame: *JSC.CallFrame, is_asy return globalThis.throwInvalidArguments("salt is too long", .{}); } - out.password = try JSC.Node.StringOrBuffer.fromJSMaybeAsync(globalThis, bun.default_allocator, arg0, is_async, allow_string_object) orelse { + out.password = try jsc.Node.StringOrBuffer.fromJSMaybeAsync(globalThis, bun.default_allocator, arg0, is_async, allow_string_object) orelse { return globalThis.throwInvalidArgumentTypeValue("password", "string or buffer", arg0); }; @@ -227,8 +227,8 @@ pub fn pbkdf2( ) ?[]const u8 { var pbk = PBKDF2{ .algorithm = algorithm, - .password = JSC.Node.StringOrBuffer{ .encoded_slice = JSC.ZigString.Slice.fromUTF8NeverFree(password) }, - .salt = JSC.Node.StringOrBuffer{ .encoded_slice = JSC.ZigString.Slice.fromUTF8NeverFree(salt) }, + .password = jsc.Node.StringOrBuffer{ .encoded_slice = jsc.ZigString.Slice.fromUTF8NeverFree(password) }, + .salt = jsc.Node.StringOrBuffer{ .encoded_slice = jsc.ZigString.Slice.fromUTF8NeverFree(salt) }, .iteration_count = iteration_count, .length = @intCast(output.len), }; @@ -240,22 +240,23 @@ pub fn pbkdf2( return output; } +const string = []const u8; + const std = @import("std"); const bun = @import("bun"); const Async = bun.Async; const assert = bun.assert; const default_allocator = bun.default_allocator; -const string = bun.string; const BoringSSL = bun.BoringSSL.c; -const JSC = bun.JSC; -const CallFrame = JSC.CallFrame; -const JSGlobalObject = JSC.JSGlobalObject; -const JSValue = JSC.JSValue; -const VirtualMachine = JSC.VirtualMachine; -const ZigString = JSC.ZigString; -const createCryptoError = JSC.API.Bun.Crypto.createCryptoError; +const jsc = bun.jsc; +const CallFrame = jsc.CallFrame; +const JSGlobalObject = jsc.JSGlobalObject; +const JSValue = jsc.JSValue; +const VirtualMachine = jsc.VirtualMachine; +const ZigString = jsc.ZigString; +const createCryptoError = jsc.API.Bun.Crypto.createCryptoError; -const EVP = JSC.API.Bun.Crypto.EVP; +const EVP = jsc.API.Bun.Crypto.EVP; const Algorithm = EVP.Algorithm; diff --git a/src/bun.js/api/crypto/PasswordObject.zig b/src/bun.js/api/crypto/PasswordObject.zig index fa74c4c46c..8e1363eeaa 100644 --- a/src/bun.js/api/crypto/PasswordObject.zig +++ b/src/bun.js/api/crypto/PasswordObject.zig @@ -19,7 +19,7 @@ pub const PasswordObject = struct { .argon2id = .{}, }; - pub fn fromJS(globalObject: *JSC.JSGlobalObject, value: JSC.JSValue) bun.JSError!Value { + pub fn fromJS(globalObject: *jsc.JSGlobalObject, value: jsc.JSValue) bun.JSError!Value { if (value.isObject()) { if (try value.getTruthy(globalObject, "algorithm")) |algorithm_value| { if (!algorithm_value.isString()) { @@ -28,7 +28,7 @@ pub const PasswordObject = struct { const algorithm_string = try algorithm_value.getZigString(globalObject); - switch (PasswordObject.Algorithm.label.getWithEql(algorithm_string, JSC.ZigString.eqlComptime) orelse { + switch (PasswordObject.Algorithm.label.getWithEql(algorithm_string, jsc.ZigString.eqlComptime) orelse { return globalObject.throwInvalidArgumentType("hash", "algorithm", unknown_password_algorithm_message); }) { .bcrypt => { @@ -94,7 +94,7 @@ pub const PasswordObject = struct { } else if (value.isString()) { const algorithm_string = try value.getZigString(globalObject); - switch (PasswordObject.Algorithm.label.getWithEql(algorithm_string, JSC.ZigString.eqlComptime) orelse { + switch (PasswordObject.Algorithm.label.getWithEql(algorithm_string, jsc.ZigString.eqlComptime) orelse { return globalObject.throwInvalidArgumentType("hash", "algorithm", unknown_password_algorithm_message); }) { .bcrypt => { @@ -322,27 +322,27 @@ pub const JSPasswordObject = struct { } }; - pub export fn JSPasswordObject__create(globalObject: *JSC.JSGlobalObject) JSC.JSValue { + pub export fn JSPasswordObject__create(globalObject: *jsc.JSGlobalObject) jsc.JSValue { var object = JSValue.createEmptyObject(globalObject, 4); object.put( globalObject, ZigString.static("hash"), - JSC.createCallback(globalObject, ZigString.static("hash"), 2, JSPasswordObject__hash), + jsc.createCallback(globalObject, ZigString.static("hash"), 2, JSPasswordObject__hash), ); object.put( globalObject, ZigString.static("hashSync"), - JSC.createCallback(globalObject, ZigString.static("hashSync"), 2, JSPasswordObject__hashSync), + jsc.createCallback(globalObject, ZigString.static("hashSync"), 2, JSPasswordObject__hashSync), ); object.put( globalObject, ZigString.static("verify"), - JSC.createCallback(globalObject, ZigString.static("verify"), 2, JSPasswordObject__verify), + jsc.createCallback(globalObject, ZigString.static("verify"), 2, JSPasswordObject__verify), ); object.put( globalObject, ZigString.static("verifySync"), - JSC.createCallback(globalObject, ZigString.static("verifySync"), 2, JSPasswordObject__verifySync), + jsc.createCallback(globalObject, ZigString.static("verifySync"), 2, JSPasswordObject__verifySync), ); return object; } @@ -350,11 +350,11 @@ pub const JSPasswordObject = struct { const HashJob = struct { algorithm: PasswordObject.Algorithm.Value, password: []const u8, - promise: JSC.JSPromise.Strong, - event_loop: *JSC.EventLoop, - global: *JSC.JSGlobalObject, + promise: jsc.JSPromise.Strong, + event_loop: *jsc.EventLoop, + global: *jsc.JSGlobalObject, ref: Async.KeepAlive = .{}, - task: JSC.WorkPoolTask = .{ .callback = &run }, + task: jsc.WorkPoolTask = .{ .callback = &run }, pub const new = bun.TrivialNew(@This()); @@ -362,9 +362,9 @@ pub const JSPasswordObject = struct { value: Value, ref: Async.KeepAlive = .{}, - task: JSC.AnyTask = undefined, - promise: JSC.JSPromise.Strong, - global: *JSC.JSGlobalObject, + task: jsc.AnyTask = undefined, + promise: jsc.JSPromise.Strong, + global: *jsc.JSGlobalObject, pub const new = bun.TrivialNew(@This()); @@ -372,11 +372,11 @@ pub const JSPasswordObject = struct { err: PasswordObject.HashError, hash: []const u8, - pub fn toErrorInstance(this: Value, globalObject: *JSC.JSGlobalObject) JSC.JSValue { + pub fn toErrorInstance(this: Value, globalObject: *jsc.JSGlobalObject) jsc.JSValue { const error_code = std.fmt.allocPrint(bun.default_allocator, "PASSWORD{}", .{PascalToUpperUnderscoreCaseFormatter{ .input = @errorName(this.err) }}) catch bun.outOfMemory(); defer bun.default_allocator.free(error_code); const instance = globalObject.createErrorInstance("Password hashing failed with error \"{s}\"", .{@errorName(this.err)}); - instance.put(globalObject, ZigString.static("code"), JSC.ZigString.init(error_code).toJS(globalObject)); + instance.put(globalObject, ZigString.static("code"), jsc.ZigString.init(error_code).toJS(globalObject)); return instance; } }; @@ -394,7 +394,7 @@ pub const JSPasswordObject = struct { promise.reject(global, error_instance); }, .hash => |value| { - const js_string = JSC.ZigString.init(value).toJS(global); + const js_string = jsc.ZigString.init(value).toJS(global); bun.destroy(this); promise.resolve(global, js_string); }, @@ -427,14 +427,14 @@ pub const JSPasswordObject = struct { }); this.promise = .empty; - result.task = JSC.AnyTask.New(Result, Result.runFromJS).init(result); + result.task = jsc.AnyTask.New(Result, Result.runFromJS).init(result); this.ref = .{}; - this.event_loop.enqueueTaskConcurrent(JSC.ConcurrentTask.createFrom(&result.task)); + this.event_loop.enqueueTaskConcurrent(jsc.ConcurrentTask.createFrom(&result.task)); this.deinit(); } }; - pub fn hash(globalObject: *JSC.JSGlobalObject, password: []const u8, algorithm: PasswordObject.Algorithm.Value, comptime sync: bool) bun.JSError!JSC.JSValue { + pub fn hash(globalObject: *jsc.JSGlobalObject, password: []const u8, algorithm: PasswordObject.Algorithm.Value, comptime sync: bool) bun.JSError!jsc.JSValue { assert(password.len > 0); // caller must check if (comptime sync) { @@ -445,14 +445,14 @@ pub const JSPasswordObject = struct { return globalObject.throwValue(error_instance); }, .hash => |h| { - return JSC.ZigString.init(h).toJS(globalObject); + return jsc.ZigString.init(h).toJS(globalObject); }, } unreachable; } - const promise = JSC.JSPromise.Strong.init(globalObject); + const promise = jsc.JSPromise.Strong.init(globalObject); var job = HashJob.new(.{ .algorithm = algorithm, @@ -462,12 +462,12 @@ pub const JSPasswordObject = struct { .global = globalObject, }); job.ref.ref(globalObject.bunVM()); - JSC.WorkPool.schedule(&job.task); + jsc.WorkPool.schedule(&job.task); return promise.value(); } - pub fn verify(globalObject: *JSC.JSGlobalObject, password: []const u8, prev_hash: []const u8, algorithm: ?PasswordObject.Algorithm, comptime sync: bool) bun.JSError!JSC.JSValue { + pub fn verify(globalObject: *jsc.JSGlobalObject, password: []const u8, prev_hash: []const u8, algorithm: ?PasswordObject.Algorithm, comptime sync: bool) bun.JSError!jsc.JSValue { assert(password.len > 0); // caller must check if (comptime sync) { @@ -478,14 +478,14 @@ pub const JSPasswordObject = struct { return globalObject.throwValue(error_instance); }, .pass => |pass| { - return JSC.JSValue.jsBoolean(pass); + return jsc.JSValue.jsBoolean(pass); }, } unreachable; } - var promise = JSC.JSPromise.Strong.init(globalObject); + var promise = jsc.JSPromise.Strong.init(globalObject); const job = VerifyJob.new(.{ .algorithm = algorithm, @@ -496,13 +496,13 @@ pub const JSPasswordObject = struct { .global = globalObject, }); job.ref.ref(globalObject.bunVM()); - JSC.WorkPool.schedule(&job.task); + jsc.WorkPool.schedule(&job.task); return promise.value(); } // Once we have bindings generator, this should be replaced with a generated function - pub fn JSPasswordObject__hash(globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { + pub fn JSPasswordObject__hash(globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const arguments_ = callframe.arguments_old(2); const arguments = arguments_.ptr[0..arguments_.len]; @@ -521,7 +521,7 @@ pub const JSPasswordObject = struct { // fromJS(...) orelse { // return globalObject.throwInvalidArgumentType("hash", "password", "string or TypedArray"); // } - const password_to_hash = try JSC.Node.StringOrBuffer.fromJSToOwnedSlice(globalObject, arguments[0], bun.default_allocator); + const password_to_hash = try jsc.Node.StringOrBuffer.fromJSToOwnedSlice(globalObject, arguments[0], bun.default_allocator); errdefer bun.default_allocator.free(password_to_hash); if (password_to_hash.len == 0) { @@ -532,7 +532,7 @@ pub const JSPasswordObject = struct { } // Once we have bindings generator, this should be replaced with a generated function - pub fn JSPasswordObject__hashSync(globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { + pub fn JSPasswordObject__hashSync(globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const arguments_ = callframe.arguments_old(2); const arguments = arguments_.ptr[0..arguments_.len]; @@ -546,7 +546,7 @@ pub const JSPasswordObject = struct { algorithm = try PasswordObject.Algorithm.Value.fromJS(globalObject, arguments[1]); } - var string_or_buffer = try JSC.Node.StringOrBuffer.fromJS(globalObject, bun.default_allocator, arguments[0]) orelse { + var string_or_buffer = try jsc.Node.StringOrBuffer.fromJS(globalObject, bun.default_allocator, arguments[0]) orelse { return globalObject.throwInvalidArgumentType("hash", "password", "string or TypedArray"); }; defer string_or_buffer.deinit(); @@ -562,11 +562,11 @@ pub const JSPasswordObject = struct { algorithm: ?PasswordObject.Algorithm = null, password: []const u8, prev_hash: []const u8, - promise: JSC.JSPromise.Strong, - event_loop: *JSC.EventLoop, - global: *JSC.JSGlobalObject, + promise: jsc.JSPromise.Strong, + event_loop: *jsc.EventLoop, + global: *jsc.JSGlobalObject, ref: Async.KeepAlive = .{}, - task: JSC.WorkPoolTask = .{ .callback = &run }, + task: jsc.WorkPoolTask = .{ .callback = &run }, pub const new = bun.TrivialNew(@This()); @@ -574,9 +574,9 @@ pub const JSPasswordObject = struct { value: Value, ref: Async.KeepAlive = .{}, - task: JSC.AnyTask = undefined, - promise: JSC.JSPromise.Strong, - global: *JSC.JSGlobalObject, + task: jsc.AnyTask = undefined, + promise: jsc.JSPromise.Strong, + global: *jsc.JSGlobalObject, pub const new = bun.TrivialNew(@This()); @@ -584,11 +584,11 @@ pub const JSPasswordObject = struct { err: PasswordObject.HashError, pass: bool, - pub fn toErrorInstance(this: Value, globalObject: *JSC.JSGlobalObject) JSC.JSValue { + pub fn toErrorInstance(this: Value, globalObject: *jsc.JSGlobalObject) jsc.JSValue { const error_code = std.fmt.allocPrint(bun.default_allocator, "PASSWORD{}", .{PascalToUpperUnderscoreCaseFormatter{ .input = @errorName(this.err) }}) catch bun.outOfMemory(); defer bun.default_allocator.free(error_code); const instance = globalObject.createErrorInstance("Password verification failed with error \"{s}\"", .{@errorName(this.err)}); - instance.put(globalObject, ZigString.static("code"), JSC.ZigString.init(error_code).toJS(globalObject)); + instance.put(globalObject, ZigString.static("code"), jsc.ZigString.init(error_code).toJS(globalObject)); return instance; } }; @@ -607,7 +607,7 @@ pub const JSPasswordObject = struct { }, .pass => |pass| { bun.destroy(this); - promise.resolve(global, JSC.JSValue.jsBoolean(pass)); + promise.resolve(global, jsc.JSValue.jsBoolean(pass)); }, } } @@ -641,15 +641,15 @@ pub const JSPasswordObject = struct { }); this.promise = .empty; - result.task = JSC.AnyTask.New(Result, Result.runFromJS).init(result); + result.task = jsc.AnyTask.New(Result, Result.runFromJS).init(result); this.ref = .{}; - this.event_loop.enqueueTaskConcurrent(JSC.ConcurrentTask.createFrom(&result.task)); + this.event_loop.enqueueTaskConcurrent(jsc.ConcurrentTask.createFrom(&result.task)); this.deinit(); } }; // Once we have bindings generator, this should be replaced with a generated function - pub fn JSPasswordObject__verify(globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { + pub fn JSPasswordObject__verify(globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const arguments_ = callframe.arguments_old(3); const arguments = arguments_.ptr[0..arguments_.len]; @@ -666,7 +666,7 @@ pub const JSPasswordObject = struct { const algorithm_string = try arguments[2].getZigString(globalObject); - algorithm = PasswordObject.Algorithm.label.getWithEql(algorithm_string, JSC.ZigString.eqlComptime) orelse { + algorithm = PasswordObject.Algorithm.label.getWithEql(algorithm_string, jsc.ZigString.eqlComptime) orelse { if (!globalObject.hasException()) { return globalObject.throwInvalidArgumentType("verify", "algorithm", unknown_password_algorithm_message); } @@ -679,33 +679,33 @@ pub const JSPasswordObject = struct { // fromJS(...) orelse { // return globalObject.throwInvalidArgumentType("hash", "password", "string or TypedArray"); // } - const owned_password = try JSC.Node.StringOrBuffer.fromJSToOwnedSlice(globalObject, arguments[0], bun.default_allocator); + const owned_password = try jsc.Node.StringOrBuffer.fromJSToOwnedSlice(globalObject, arguments[0], bun.default_allocator); // TODO: this most likely should error like `verifySync` instead of stringifying. // // fromJS(...) orelse { // return globalObject.throwInvalidArgumentType("hash", "password", "string or TypedArray"); // } - const owned_hash = JSC.Node.StringOrBuffer.fromJSToOwnedSlice(globalObject, arguments[1], bun.default_allocator) catch |err| { + const owned_hash = jsc.Node.StringOrBuffer.fromJSToOwnedSlice(globalObject, arguments[1], bun.default_allocator) catch |err| { bun.default_allocator.free(owned_password); return err; }; if (owned_hash.len == 0) { bun.default_allocator.free(owned_password); - return JSC.JSPromise.resolvedPromiseValue(globalObject, JSC.JSValue.jsBoolean(false)); + return jsc.JSPromise.resolvedPromiseValue(globalObject, jsc.JSValue.jsBoolean(false)); } if (owned_password.len == 0) { bun.default_allocator.free(owned_hash); - return JSC.JSPromise.resolvedPromiseValue(globalObject, JSC.JSValue.jsBoolean(false)); + return jsc.JSPromise.resolvedPromiseValue(globalObject, jsc.JSValue.jsBoolean(false)); } return verify(globalObject, owned_password, owned_hash, algorithm, false); } // Once we have bindings generator, this should be replaced with a generated function - pub fn JSPasswordObject__verifySync(globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { + pub fn JSPasswordObject__verifySync(globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const arguments_ = callframe.arguments_old(3); const arguments = arguments_.ptr[0..arguments_.len]; @@ -722,7 +722,7 @@ pub const JSPasswordObject = struct { const algorithm_string = try arguments[2].getZigString(globalObject); - algorithm = PasswordObject.Algorithm.label.getWithEql(algorithm_string, JSC.ZigString.eqlComptime) orelse { + algorithm = PasswordObject.Algorithm.label.getWithEql(algorithm_string, jsc.ZigString.eqlComptime) orelse { if (!globalObject.hasException()) { return globalObject.throwInvalidArgumentType("verify", "algorithm", unknown_password_algorithm_message); } @@ -730,11 +730,11 @@ pub const JSPasswordObject = struct { }; } - var password = try JSC.Node.StringOrBuffer.fromJS(globalObject, bun.default_allocator, arguments[0]) orelse { + var password = try jsc.Node.StringOrBuffer.fromJS(globalObject, bun.default_allocator, arguments[0]) orelse { return globalObject.throwInvalidArgumentType("verify", "password", "string or TypedArray"); }; - var hash_ = try JSC.Node.StringOrBuffer.fromJS(globalObject, bun.default_allocator, arguments[1]) orelse { + var hash_ = try jsc.Node.StringOrBuffer.fromJS(globalObject, bun.default_allocator, arguments[1]) orelse { password.deinit(); return globalObject.throwInvalidArgumentType("verify", "hash", "string or TypedArray"); }; @@ -743,11 +743,11 @@ pub const JSPasswordObject = struct { defer hash_.deinit(); if (hash_.slice().len == 0) { - return JSC.JSValue.jsBoolean(false); + return jsc.JSValue.jsBoolean(false); } if (password.slice().len == 0) { - return JSC.JSValue.jsBoolean(false); + return jsc.JSValue.jsBoolean(false); } return verify(globalObject, password.slice(), hash_.slice(), algorithm, true); @@ -756,17 +756,18 @@ pub const JSPasswordObject = struct { const unknown_password_algorithm_message = "unknown algorithm, expected one of: \"bcrypt\", \"argon2id\", \"argon2d\", \"argon2i\" (default is \"argon2id\")"; +const string = []const u8; + const std = @import("std"); const bun = @import("bun"); const Async = bun.Async; const assert = bun.assert; const default_allocator = bun.default_allocator; -const string = bun.string; const strings = bun.strings; -const JSC = bun.JSC; -const CallFrame = JSC.CallFrame; -const JSGlobalObject = JSC.JSGlobalObject; -const JSValue = JSC.JSValue; -const ZigString = JSC.ZigString; +const jsc = bun.jsc; +const CallFrame = jsc.CallFrame; +const JSGlobalObject = jsc.JSGlobalObject; +const JSValue = jsc.JSValue; +const ZigString = jsc.ZigString; diff --git a/src/bun.js/api/ffi.zig b/src/bun.js/api/ffi.zig index 32dbf694c6..f69e17f160 100644 --- a/src/bun.js/api/ffi.zig +++ b/src/bun.js/api/ffi.zig @@ -32,7 +32,7 @@ const Offsets = extern struct { }; pub const FFI = struct { - pub const js = JSC.Codegen.JSFFI; + pub const js = jsc.Codegen.JSFFI; pub const toJS = js.toJS; pub const fromJS = js.fromJS; pub const fromJSDirect = js.fromJSDirect; @@ -515,7 +515,7 @@ pub const FFI = struct { bun.default_allocator.free(this.items); } - pub fn fromJSArray(globalThis: *JSC.JSGlobalObject, value: JSC.JSValue, comptime property: []const u8) bun.JSError!StringArray { + pub fn fromJSArray(globalThis: *jsc.JSGlobalObject, value: jsc.JSValue, comptime property: []const u8) bun.JSError!StringArray { var iter = try value.arrayIterator(globalThis); var items = std.ArrayList([:0]const u8).init(bun.default_allocator); @@ -535,7 +535,7 @@ pub const FFI = struct { return .{ .items = items.items }; } - pub fn fromJSString(globalThis: *JSC.JSGlobalObject, value: JSC.JSValue, comptime property: []const u8) bun.JSError!StringArray { + pub fn fromJSString(globalThis: *jsc.JSGlobalObject, value: jsc.JSValue, comptime property: []const u8) bun.JSError!StringArray { if (value.isUndefined()) return .{}; if (!value.isString()) { return globalThis.throwInvalidArgumentTypeValue(property, "array of strings", value); @@ -547,7 +547,7 @@ pub const FFI = struct { return .{ .items = items.items }; } - pub fn fromJS(globalThis: *JSC.JSGlobalObject, value: JSC.JSValue, comptime property: []const u8) bun.JSError!StringArray { + pub fn fromJS(globalThis: *jsc.JSGlobalObject, value: jsc.JSValue, comptime property: []const u8) bun.JSError!StringArray { if (value.isArray()) { return fromJSArray(globalThis, value, property); } @@ -555,7 +555,7 @@ pub const FFI = struct { } }; - pub fn Bun__FFI__cc(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { + pub fn Bun__FFI__cc(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const arguments = callframe.arguments_old(1).slice(); if (arguments.len == 0 or !arguments[0].isObject()) { return globalThis.throwInvalidArguments("Expected object", .{}); @@ -640,7 +640,7 @@ pub const FFI = struct { if (try object.getTruthy(globalThis, "define")) |define_value| { if (define_value.getObject()) |define_obj| { - const Iter = JSC.JSPropertyIterator(.{ .include_value = true, .skip_empty_name = true }); + const Iter = jsc.JSPropertyIterator(.{ .include_value = true, .skip_empty_name = true }); var iter = try Iter.init(globalThis, define_obj); defer iter.deinit(); while (try iter.next()) |entry| { @@ -726,7 +726,7 @@ pub const FFI = struct { const napi_env = makeNapiEnvIfNeeded(compile_c.symbols.map.values(), globalThis); - var obj = JSC.JSValue.createEmptyObject(globalThis, compile_c.symbols.map.count()); + var obj = jsc.JSValue.createEmptyObject(globalThis, compile_c.symbols.map.count()); for (compile_c.symbols.map.values()) |*function| { const function_name = function.base_name.?; @@ -750,11 +750,11 @@ pub const FFI = struct { }, .compiled => |*compiled| { const str = ZigString.init(bun.asByteSlice(function_name)); - const cb = JSC.host_fn.NewRuntimeFunction( + const cb = jsc.host_fn.NewRuntimeFunction( globalThis, &str, @as(u32, @intCast(function.arg_types.items.len)), - bun.cast(*const JSC.JSHostFn, compiled.ptr), + bun.cast(*const jsc.JSHostFn, compiled.ptr), false, true, function.symbol_from_dynamic_library, @@ -778,7 +778,7 @@ pub const FFI = struct { compile_c.symbols = .{}; const js_object = lib.toJS(globalThis); - JSC.Codegen.JSFFI.symbolsValueSetCached(js_object, globalThis, obj); + jsc.Codegen.JSFFI.symbolsValueSetCached(js_object, globalThis, obj); return js_object; } @@ -788,8 +788,8 @@ pub const FFI = struct { return .js_undefined; } - pub fn callback(globalThis: *JSGlobalObject, interface: JSC.JSValue, js_callback: JSC.JSValue) bun.JSError!JSValue { - JSC.markBinding(@src()); + pub fn callback(globalThis: *JSGlobalObject, interface: jsc.JSValue, js_callback: jsc.JSValue) bun.JSError!JSValue { + jsc.markBinding(@src()); if (!interface.isObject()) { return globalThis.toInvalidArguments("Expected object", .{}); } @@ -830,8 +830,8 @@ pub const FFI = struct { globalThis, ZigString.static("ptr"), ZigString.static("ctx"), - JSC.JSValue.fromPtrAddress(@intFromPtr(function_.step.compiled.ptr)), - JSC.JSValue.fromPtrAddress(@intFromPtr(function_)), + jsc.JSValue.fromPtrAddress(@intFromPtr(function_.step.compiled.ptr)), + jsc.JSValue.fromPtrAddress(@intFromPtr(function_)), ); }, } @@ -839,10 +839,10 @@ pub const FFI = struct { pub fn close( this: *FFI, - globalThis: *JSC.JSGlobalObject, - _: *JSC.CallFrame, + globalThis: *jsc.JSGlobalObject, + _: *jsc.CallFrame, ) bun.JSError!JSValue { - JSC.markBinding(@src()); + jsc.markBinding(@src()); if (this.closed) { return .js_undefined; } @@ -875,8 +875,8 @@ pub const FFI = struct { return .js_undefined; } - pub fn printCallback(global: *JSGlobalObject, object: JSC.JSValue) JSValue { - JSC.markBinding(@src()); + pub fn printCallback(global: *JSGlobalObject, object: jsc.JSValue) JSValue { + jsc.markBinding(@src()); const allocator = VirtualMachine.get().allocator; if (object.isEmptyOrUndefinedOrNull() or !object.isObject()) { @@ -900,7 +900,7 @@ pub const FFI = struct { return ZigString.init(arraylist.items).toJS(global); } - pub fn print(global: *JSGlobalObject, object: JSC.JSValue, is_callback_val: ?JSC.JSValue) bun.JSError!JSValue { + pub fn print(global: *JSGlobalObject, object: jsc.JSValue, is_callback_val: ?jsc.JSValue) bun.JSError!JSValue { const allocator = bun.default_allocator; if (is_callback_val) |is_callback| { if (is_callback.toBoolean()) { @@ -912,7 +912,7 @@ pub const FFI = struct { const obj = object.getObject() orelse return invalidOptionsArg(global); var symbols = bun.StringArrayHashMapUnmanaged(Function){}; - if (generateSymbols(global, bun.default_allocator, &symbols, obj) catch JSC.JSValue.zero) |val| { + if (generateSymbols(global, bun.default_allocator, &symbols, obj) catch jsc.JSValue.zero) |val| { // an error while validating symbols for (symbols.keys()) |key| { allocator.free(@constCast(key)); @@ -920,7 +920,7 @@ pub const FFI = struct { symbols.clearAndFree(allocator); return val; } - JSC.markBinding(@src()); + jsc.markBinding(@src()); var strs = std.ArrayList(bun.String).initCapacity(allocator, symbols.count()) catch bun.outOfMemory(); defer { for (strs.items) |str| { @@ -968,8 +968,8 @@ pub const FFI = struct { return global.toInvalidArguments("Expected an options object with symbol names", .{}); } - pub fn open(global: *JSGlobalObject, name_str: ZigString, object_value: JSC.JSValue) JSC.JSValue { - JSC.markBinding(@src()); + pub fn open(global: *JSGlobalObject, name_str: ZigString, object_value: jsc.JSValue) jsc.JSValue { + jsc.markBinding(@src()); const vm = VirtualMachine.get(); var name_slice = name_str.toSlice(bun.default_allocator); defer name_slice.deinit(); @@ -979,7 +979,7 @@ pub const FFI = struct { var filepath_buf: bun.PathBuffer = undefined; const name = brk: { - if (JSC.ModuleLoader.resolveEmbeddedFile( + if (jsc.ModuleLoader.resolveEmbeddedFile( vm, name_slice.slice(), switch (Environment.os) { @@ -1002,7 +1002,7 @@ pub const FFI = struct { } var symbols = bun.StringArrayHashMapUnmanaged(Function){}; - if (generateSymbols(global, bun.default_allocator, &symbols, object) catch JSC.JSValue.zero) |val| { + if (generateSymbols(global, bun.default_allocator, &symbols, object) catch jsc.JSValue.zero) |val| { // an error while validating symbols for (symbols.keys()) |key| { bun.default_allocator.free(@constCast(key)); @@ -1021,7 +1021,7 @@ pub const FFI = struct { // if that fails, try resolving the filepath relative to the current working directory break :brk std.DynLib.open(backup_name) catch { // Then, if that fails, report an error. - const system_error = JSC.SystemError{ + const system_error = jsc.SystemError{ .code = bun.String.cloneUTF8(@tagName(.ERR_DLOPEN_FAILED)), .message = bun.String.cloneUTF8("Failed to open library. This is usually caused by a missing library or an invalid library path."), .syscall = bun.String.cloneUTF8("dlopen"), @@ -1035,7 +1035,7 @@ pub const FFI = struct { if (size >= 63) { size = 0; } - var obj = JSC.JSValue.createEmptyObject(global, size); + var obj = jsc.JSValue.createEmptyObject(global, size); obj.protect(); defer obj.unprotect(); @@ -1094,11 +1094,11 @@ pub const FFI = struct { }, .compiled => |*compiled| { const str = ZigString.init(bun.asByteSlice(function_name)); - const cb = JSC.host_fn.NewRuntimeFunction( + const cb = jsc.host_fn.NewRuntimeFunction( global, &str, @as(u32, @intCast(function.arg_types.items.len)), - bun.cast(*const JSC.JSHostFn, compiled.ptr), + bun.cast(*const jsc.JSHostFn, compiled.ptr), false, true, function.symbol_from_dynamic_library, @@ -1115,24 +1115,24 @@ pub const FFI = struct { }); const js_object = lib.toJS(global); - JSC.Codegen.JSFFI.symbolsValueSetCached(js_object, global, obj); + jsc.Codegen.JSFFI.symbolsValueSetCached(js_object, global, obj); return js_object; } - pub fn getSymbols(_: *FFI, _: *JSC.JSGlobalObject) JSC.JSValue { + pub fn getSymbols(_: *FFI, _: *jsc.JSGlobalObject) jsc.JSValue { // This shouldn't be called. The cachedValue is what should be called. return .js_undefined; } - pub fn linkSymbols(global: *JSGlobalObject, object_value: JSC.JSValue) JSC.JSValue { - JSC.markBinding(@src()); + pub fn linkSymbols(global: *JSGlobalObject, object_value: jsc.JSValue) jsc.JSValue { + jsc.markBinding(@src()); const allocator = VirtualMachine.get().allocator; if (object_value.isEmptyOrUndefinedOrNull()) return invalidOptionsArg(global); const object = object_value.getObject() orelse return invalidOptionsArg(global); var symbols = bun.StringArrayHashMapUnmanaged(Function){}; - if (generateSymbols(global, allocator, &symbols, object) catch JSC.JSValue.zero) |val| { + if (generateSymbols(global, allocator, &symbols, object) catch jsc.JSValue.zero) |val| { // an error while validating symbols for (symbols.keys()) |key| { allocator.free(@constCast(key)); @@ -1197,11 +1197,11 @@ pub const FFI = struct { .compiled => |*compiled| { const name = &ZigString.init(bun.asByteSlice(function_name)); - const cb = JSC.host_fn.NewRuntimeFunction( + const cb = jsc.host_fn.NewRuntimeFunction( global, name, @as(u32, @intCast(function.arg_types.items.len)), - bun.cast(*JSC.JSHostFn, compiled.ptr), + bun.cast(*jsc.JSHostFn, compiled.ptr), false, true, function.symbol_from_dynamic_library, @@ -1219,11 +1219,11 @@ pub const FFI = struct { }); const js_object = lib.toJS(global); - JSC.Codegen.JSFFI.symbolsValueSetCached(js_object, global, obj); + jsc.Codegen.JSFFI.symbolsValueSetCached(js_object, global, obj); return js_object; } - pub fn generateSymbolForFunction(global: *JSGlobalObject, allocator: std.mem.Allocator, value: JSC.JSValue, function: *Function) bun.JSError!?JSValue { - JSC.markBinding(@src()); + pub fn generateSymbolForFunction(global: *JSGlobalObject, allocator: std.mem.Allocator, value: jsc.JSValue, function: *Function) bun.JSError!?JSValue { + jsc.markBinding(@src()); var abi_types = std.ArrayListUnmanaged(ABIType){}; @@ -1339,10 +1339,10 @@ pub const FFI = struct { return null; } - pub fn generateSymbols(global: *JSGlobalObject, allocator: Allocator, symbols: *bun.StringArrayHashMapUnmanaged(Function), object: *JSC.JSObject) bun.JSError!?JSValue { - JSC.markBinding(@src()); + pub fn generateSymbols(global: *JSGlobalObject, allocator: Allocator, symbols: *bun.StringArrayHashMapUnmanaged(Function), object: *jsc.JSObject) bun.JSError!?JSValue { + jsc.markBinding(@src()); - var symbols_iter = try JSC.JSPropertyIterator(.{ + var symbols_iter = try jsc.JSPropertyIterator(.{ .skip_empty_name = true, .include_value = true, @@ -1394,8 +1394,8 @@ pub const FFI = struct { extern "c" fn FFICallbackFunctionWrapper_destroy(*anyopaque) void; - pub fn deinit(val: *Function, globalThis: *JSC.JSGlobalObject) void { - JSC.markBinding(@src()); + pub fn deinit(val: *Function, globalThis: *jsc.JSGlobalObject) void { + jsc.markBinding(@src()); if (val.base_name) |base_name| { if (bun.asByteSlice(base_name).len > 0) { @@ -1414,7 +1414,7 @@ pub const FFI = struct { // val.allocator.free(val.step.compiled.buf); if (val.step.compiled.js_function != .zero) { _ = globalThis; - // _ = JSC.untrackFunction(globalThis, val.step.compiled.js_function); + // _ = jsc.untrackFunction(globalThis, val.step.compiled.js_function); val.step.compiled.js_function = .zero; } @@ -1547,11 +1547,11 @@ pub const FFI = struct { pub fn compileCallback( this: *Function, - js_context: *JSC.JSGlobalObject, + js_context: *jsc.JSGlobalObject, js_function: JSValue, is_threadsafe: bool, ) !void { - JSC.markBinding(@src()); + jsc.markBinding(@src()); var source_code = std.ArrayList(u8).init(this.allocator); var source_code_writer = source_code.writer(); const ffi_wrapper = Bun__createFFICallbackFunction(js_context, js_function); @@ -1845,11 +1845,11 @@ pub const FFI = struct { extern fn FFI_Callback_threadsafe_call(*anyopaque, usize, [*]JSValue) JSValue; extern fn FFI_Callback_call_6(*anyopaque, usize, [*]JSValue) JSValue; extern fn FFI_Callback_call_7(*anyopaque, usize, [*]JSValue) JSValue; - extern fn Bun__createFFICallbackFunction(*JSC.JSGlobalObject, JSValue) *anyopaque; + extern fn Bun__createFFICallbackFunction(*jsc.JSGlobalObject, JSValue) *anyopaque; pub fn printCallbackSourceCode( this: *Function, - globalObject: ?*JSC.JSGlobalObject, + globalObject: ?*jsc.JSGlobalObject, context_ptr: ?*anyopaque, writer: anytype, ) !void { @@ -2319,11 +2319,11 @@ const CompilerRT = struct { } const MyFunctionSStructWorkAround = struct { - JSVALUE_TO_INT64: *const fn (JSValue0: JSC.JSValue) callconv(.C) i64, - JSVALUE_TO_UINT64: *const fn (JSValue0: JSC.JSValue) callconv(.C) u64, - INT64_TO_JSVALUE: *const fn (arg0: *JSC.JSGlobalObject, arg1: i64) callconv(.C) JSC.JSValue, - UINT64_TO_JSVALUE: *const fn (arg0: *JSC.JSGlobalObject, arg1: u64) callconv(.C) JSC.JSValue, - bun_call: *const @TypeOf(JSC.C.JSObjectCallAsFunction), + JSVALUE_TO_INT64: *const fn (JSValue0: jsc.JSValue) callconv(.C) i64, + JSVALUE_TO_UINT64: *const fn (JSValue0: jsc.JSValue) callconv(.C) u64, + INT64_TO_JSVALUE: *const fn (arg0: *jsc.JSGlobalObject, arg1: i64) callconv(.C) jsc.JSValue, + UINT64_TO_JSVALUE: *const fn (arg0: *jsc.JSGlobalObject, arg1: u64) callconv(.C) jsc.JSValue, + bun_call: *const @TypeOf(jsc.C.JSObjectCallAsFunction), }; const headers = JSValue.exposed_to_ffi; var workaround: MyFunctionSStructWorkAround = .{ @@ -2331,7 +2331,7 @@ const CompilerRT = struct { .JSVALUE_TO_UINT64 = headers.JSVALUE_TO_UINT64, .INT64_TO_JSVALUE = headers.INT64_TO_JSVALUE, .UINT64_TO_JSVALUE = headers.UINT64_TO_JSVALUE, - .bun_call = &JSC.C.JSObjectCallAsFunction, + .bun_call = &jsc.C.JSObjectCallAsFunction, }; noinline fn memset( @@ -2367,8 +2367,8 @@ const CompilerRT = struct { .JSArrayBufferView__offsetOfLength = offsets.JSArrayBufferView__offsetOfLength, .JSArrayBufferView__offsetOfVector = offsets.JSArrayBufferView__offsetOfVector, .JSCell__offsetOfType = offsets.JSCell__offsetOfType, - .JSTypeArrayBufferViewMin = @intFromEnum(JSC.JSValue.JSType.min_typed_array), - .JSTypeArrayBufferViewMax = @intFromEnum(JSC.JSValue.JSType.max_typed_array), + .JSTypeArrayBufferViewMin = @intFromEnum(jsc.JSValue.JSType.min_typed_array), + .JSTypeArrayBufferViewMax = @intFromEnum(jsc.JSValue.JSType.max_typed_array), }); } @@ -2397,6 +2397,8 @@ fn makeNapiEnvIfNeeded(functions: []const FFI.Function, globalThis: *JSGlobalObj return null; } +const string = []const u8; + const Fs = @import("../../fs.zig"); const TCC = @import("../../deps/tcc.zig"); const napi = @import("../../napi/napi.zig"); @@ -2407,12 +2409,11 @@ const Allocator = std.mem.Allocator; const bun = @import("bun"); const Environment = bun.Environment; const Output = bun.Output; -const string = bun.string; const strings = bun.strings; -const JSC = bun.JSC; -const JSGlobalObject = bun.JSC.JSGlobalObject; -const JSValue = bun.JSC.JSValue; -const VM = bun.JSC.VM; -const VirtualMachine = JSC.VirtualMachine; -const ZigString = bun.JSC.ZigString; +const jsc = bun.jsc; +const JSGlobalObject = bun.jsc.JSGlobalObject; +const JSValue = bun.jsc.JSValue; +const VM = bun.jsc.VM; +const VirtualMachine = jsc.VirtualMachine; +const ZigString = bun.jsc.ZigString; diff --git a/src/bun.js/api/filesystem_router.zig b/src/bun.js/api/filesystem_router.zig index 0e5c098b4a..f3a0da0695 100644 --- a/src/bun.js/api/filesystem_router.zig +++ b/src/bun.js/api/filesystem_router.zig @@ -8,19 +8,19 @@ const default_extensions = &[_][]const u8{ }; pub const FileSystemRouter = struct { - origin: ?*JSC.RefString = null, - base_dir: ?*JSC.RefString = null, + origin: ?*jsc.RefString = null, + base_dir: ?*jsc.RefString = null, router: Router, arena: *bun.ArenaAllocator = undefined, allocator: std.mem.Allocator = undefined, - asset_prefix: ?*JSC.RefString = null, + asset_prefix: ?*jsc.RefString = null, - pub const js = JSC.Codegen.JSFileSystemRouter; + pub const js = jsc.Codegen.JSFileSystemRouter; pub const toJS = js.toJS; pub const fromJS = js.fromJS; pub const fromJSDirect = js.fromJSDirect; - pub fn constructor(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!*FileSystemRouter { + pub fn constructor(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!*FileSystemRouter { const argument_ = callframe.arguments_old(1); if (argument_.len == 0) { return globalThis.throwInvalidArguments("Expected object", .{}); @@ -58,7 +58,7 @@ pub const FileSystemRouter = struct { root_dir_path = root_dir_path_; } else { var parts = [_][]const u8{path}; - root_dir_path = JSC.ZigString.Slice.fromUTF8NeverFree(bun.path.joinAbsStringBuf(Fs.FileSystem.instance.top_level_dir, &out_buf, &parts, .auto)); + root_dir_path = jsc.ZigString.Slice.fromUTF8NeverFree(bun.path.joinAbsStringBuf(Fs.FileSystem.instance.top_level_dir, &out_buf, &parts, .auto)); } } } else { @@ -169,7 +169,7 @@ pub const FileSystemRouter = struct { } threadlocal var win32_normalized_dir_info_cache_buf: if (Environment.isWindows) [bun.MAX_PATH_BYTES * 2]u8 else void = undefined; - pub fn bustDirCacheRecursive(this: *FileSystemRouter, globalThis: *JSC.JSGlobalObject, inputPath: []const u8) void { + pub fn bustDirCacheRecursive(this: *FileSystemRouter, globalThis: *jsc.JSGlobalObject, inputPath: []const u8) void { var vm = globalThis.bunVM(); var path = inputPath; if (comptime Environment.isWindows) { @@ -208,11 +208,11 @@ pub const FileSystemRouter = struct { _ = vm.transpiler.resolver.bustDirCache(path); } - pub fn bustDirCache(this: *FileSystemRouter, globalThis: *JSC.JSGlobalObject) void { + pub fn bustDirCache(this: *FileSystemRouter, globalThis: *jsc.JSGlobalObject) void { bustDirCacheRecursive(this, globalThis, strings.withoutTrailingSlashWindowsPath(this.router.config.dir)); } - pub fn reload(this: *FileSystemRouter, globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { + pub fn reload(this: *FileSystemRouter, globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { const this_value = callframe.this(); var arena = globalThis.allocator().create(bun.ArenaAllocator) catch unreachable; @@ -252,13 +252,13 @@ pub const FileSystemRouter = struct { globalThis.allocator().destroy(this.arena); this.arena = arena; - js.routesSetCached(this_value, globalThis, JSC.JSValue.zero); + js.routesSetCached(this_value, globalThis, jsc.JSValue.zero); this.allocator = allocator; this.router = router; return this_value; } - pub fn match(this: *FileSystemRouter, globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { + pub fn match(this: *FileSystemRouter, globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { const argument_ = callframe.arguments_old(2); if (argument_.len == 0) { return globalThis.throwInvalidArguments("Expected string, Request or Response", .{}); @@ -275,12 +275,12 @@ pub const FileSystemRouter = struct { } if (argument.isCell()) { - if (argument.as(JSC.WebCore.Request)) |req| { + if (argument.as(jsc.WebCore.Request)) |req| { req.ensureURL() catch unreachable; break :brk req.url.toUTF8(globalThis.allocator()); } - if (argument.as(JSC.WebCore.Response)) |resp| { + if (argument.as(jsc.WebCore.Response)) |resp| { break :brk resp.url.toUTF8(globalThis.allocator()); } } @@ -322,15 +322,15 @@ pub const FileSystemRouter = struct { return result.toJS(globalThis); } - pub fn getOrigin(this: *FileSystemRouter, globalThis: *JSC.JSGlobalObject) JSValue { + pub fn getOrigin(this: *FileSystemRouter, globalThis: *jsc.JSGlobalObject) JSValue { if (this.origin) |origin| { - return JSC.ZigString.init(origin.slice()).withEncoding().toJS(globalThis); + return jsc.ZigString.init(origin.slice()).withEncoding().toJS(globalThis); } return JSValue.jsNull(); } - pub fn getRoutes(this: *FileSystemRouter, globalThis: *JSC.JSGlobalObject) bun.JSError!JSValue { + pub fn getRoutes(this: *FileSystemRouter, globalThis: *jsc.JSGlobalObject) bun.JSError!JSValue { const paths = this.router.getEntryPoints(); const names = this.router.getNames(); var name_strings = try bun.default_allocator.alloc(ZigString, names.len * 2); @@ -340,7 +340,7 @@ pub const FileSystemRouter = struct { name_strings[i] = ZigString.init(name).withEncoding(); paths_strings[i] = ZigString.init(paths[i]).withEncoding(); } - return JSC.JSValue.fromEntries( + return jsc.JSValue.fromEntries( globalThis, name_strings.ptr, paths_strings.ptr, @@ -349,13 +349,13 @@ pub const FileSystemRouter = struct { ); } - pub fn getStyle(_: *FileSystemRouter, globalThis: *JSC.JSGlobalObject) JSValue { + pub fn getStyle(_: *FileSystemRouter, globalThis: *jsc.JSGlobalObject) JSValue { return bun.String.static("nextjs").toJS(globalThis); } - pub fn getAssetPrefix(this: *FileSystemRouter, globalThis: *JSC.JSGlobalObject) JSValue { + pub fn getAssetPrefix(this: *FileSystemRouter, globalThis: *jsc.JSGlobalObject) JSValue { if (this.asset_prefix) |asset_prefix| { - return JSC.ZigString.init(asset_prefix.slice()).withEncoding().toJS(globalThis); + return jsc.ZigString.init(asset_prefix.slice()).withEncoding().toJS(globalThis); } return JSValue.jsNull(); @@ -387,26 +387,26 @@ pub const MatchedRoute = struct { query_string_map: ?QueryStringMap = null, param_map: ?QueryStringMap = null, params_list_holder: Router.Param.List = .{}, - origin: ?*JSC.RefString = null, - asset_prefix: ?*JSC.RefString = null, + origin: ?*jsc.RefString = null, + asset_prefix: ?*jsc.RefString = null, needs_deinit: bool = true, - base_dir: ?*JSC.RefString = null, + base_dir: ?*jsc.RefString = null, - pub const js = JSC.Codegen.JSMatchedRoute; + pub const js = jsc.Codegen.JSMatchedRoute; pub const toJS = js.toJS; pub const fromJS = js.fromJS; pub const fromJSDirect = js.fromJSDirect; - pub fn getName(this: *MatchedRoute, globalThis: *JSC.JSGlobalObject) JSValue { + pub fn getName(this: *MatchedRoute, globalThis: *jsc.JSGlobalObject) JSValue { return ZigString.init(this.route.name).withEncoding().toJS(globalThis); } pub fn init( allocator: std.mem.Allocator, match: Router.Match, - origin: ?*JSC.RefString, - asset_prefix: ?*JSC.RefString, - base_dir: *JSC.RefString, + origin: ?*jsc.RefString, + asset_prefix: ?*jsc.RefString, + base_dir: *jsc.RefString, ) !*MatchedRoute { const params_list = try match.params.clone(allocator); @@ -439,8 +439,8 @@ pub const MatchedRoute = struct { map.deinit(); } if (this.needs_deinit) { - if (this.route.pathname.len > 0 and bun.Mimalloc.mi_is_in_heap_region(this.route.pathname.ptr)) { - bun.Mimalloc.mi_free(@constCast(this.route.pathname.ptr)); + if (this.route.pathname.len > 0 and bun.mimalloc.mi_is_in_heap_region(this.route.pathname.ptr)) { + bun.mimalloc.mi_free(@constCast(this.route.pathname.ptr)); } this.params_list_holder.deinit(bun.default_allocator); @@ -463,7 +463,7 @@ pub const MatchedRoute = struct { pub fn getFilePath( this: *MatchedRoute, - globalThis: *JSC.JSGlobalObject, + globalThis: *jsc.JSGlobalObject, ) JSValue { return ZigString.init(this.route.file_path) .withEncoding() @@ -476,13 +476,13 @@ pub const MatchedRoute = struct { this.deinit(); } - pub fn getPathname(this: *MatchedRoute, globalThis: *JSC.JSGlobalObject) JSValue { + pub fn getPathname(this: *MatchedRoute, globalThis: *jsc.JSGlobalObject) JSValue { return ZigString.init(this.route.pathname) .withEncoding() .toJS(globalThis); } - pub fn getRoute(this: *MatchedRoute, globalThis: *JSC.JSGlobalObject) JSValue { + pub fn getRoute(this: *MatchedRoute, globalThis: *jsc.JSGlobalObject) JSValue { return ZigString.init(this.route.name) .withEncoding() .toJS(globalThis); @@ -508,13 +508,13 @@ pub const MatchedRoute = struct { } }; - pub fn getKind(this: *MatchedRoute, globalThis: *JSC.JSGlobalObject) JSValue { + pub fn getKind(this: *MatchedRoute, globalThis: *jsc.JSGlobalObject) JSValue { return KindEnum.init(this.route.name).toJS(globalThis); } threadlocal var query_string_values_buf: [256]string = undefined; threadlocal var query_string_value_refs_buf: [256]ZigString = undefined; - pub fn createQueryObject(ctx: *JSC.JSGlobalObject, map: *QueryStringMap) JSValue { + pub fn createQueryObject(ctx: *jsc.JSGlobalObject, map: *QueryStringMap) JSValue { const QueryObjectCreator = struct { query: *QueryStringMap, pub fn create(this: *@This(), obj: *JSObject, global: *JSGlobalObject) void { @@ -557,7 +557,7 @@ pub const MatchedRoute = struct { // instead, we just store a boolean saying whether we should generate this whenever the script is requested // this is kind of bad. we should consider instead a way to inline the contents of the script. if (client_framework_enabled) { - JSC.API.Bun.getPublicPath( + jsc.API.Bun.getPublicPath( Transpiler.ClientEntryPoint.generateEntryPointPath( &entry_point_tempbuf, Fs.PathName.init(file_path), @@ -567,20 +567,20 @@ pub const MatchedRoute = struct { writer, ); } else { - JSC.API.Bun.getPublicPath(file_path, origin, Writer, writer); + jsc.API.Bun.getPublicPath(file_path, origin, Writer, writer); } } pub fn getScriptSrc( this: *MatchedRoute, - globalThis: *JSC.JSGlobalObject, - ) JSC.JSValue { + globalThis: *jsc.JSGlobalObject, + ) jsc.JSValue { var buf: bun.PathBuffer = undefined; var stream = std.io.fixedBufferStream(&buf); var writer = stream.writer(); - JSC.API.Bun.getPublicPathWithAssetPrefix( + jsc.API.Bun.getPublicPathWithAssetPrefix( this.route.file_path, - if (this.base_dir) |base_dir| base_dir.slice() else JSC.VirtualMachine.get().transpiler.fs.top_level_dir, + if (this.base_dir) |base_dir| base_dir.slice() else jsc.VirtualMachine.get().transpiler.fs.top_level_dir, if (this.origin) |origin| URL.parse(origin.slice()) else URL{}, if (this.asset_prefix) |prefix| prefix.slice() else "", @TypeOf(&writer), @@ -594,8 +594,8 @@ pub const MatchedRoute = struct { pub fn getParams( this: *MatchedRoute, - globalThis: *JSC.JSGlobalObject, - ) bun.JSError!JSC.JSValue { + globalThis: *jsc.JSGlobalObject, + ) bun.JSError!jsc.JSValue { if (this.route.params.len == 0) return JSValue.createEmptyObject(globalThis, 0); @@ -616,8 +616,8 @@ pub const MatchedRoute = struct { pub fn getQuery( this: *MatchedRoute, - globalThis: *JSC.JSGlobalObject, - ) bun.JSError!JSC.JSValue { + globalThis: *jsc.JSGlobalObject, + ) bun.JSError!jsc.JSValue { if (this.route.query_string.len == 0 and this.route.params.len == 0) { return JSValue.createEmptyObject(globalThis, 0); } else if (this.route.query_string.len == 0) { @@ -647,6 +647,8 @@ pub const MatchedRoute = struct { } }; +const string = []const u8; + const Fs = @import("../../fs.zig"); const Router = @import("../../router.zig"); const URLPath = @import("../../http/URLPath.zig"); @@ -661,14 +663,13 @@ const bun = @import("bun"); const Environment = bun.Environment; const Log = bun.logger; const Transpiler = bun.transpiler; -const string = bun.string; const strings = bun.strings; -const JSC = bun.JSC; -const JSGlobalObject = JSC.JSGlobalObject; -const JSObject = JSC.JSObject; -const JSValue = JSC.JSValue; -const ZigString = JSC.ZigString; +const jsc = bun.jsc; +const JSGlobalObject = jsc.JSGlobalObject; +const JSObject = jsc.JSObject; +const JSValue = jsc.JSValue; +const ZigString = jsc.ZigString; -const WebCore = JSC.WebCore; +const WebCore = jsc.WebCore; const Request = WebCore.Request; diff --git a/src/bun.js/api/glob.zig b/src/bun.js/api/glob.zig index 4c7807f157..f01ca494fc 100644 --- a/src/bun.js/api/glob.zig +++ b/src/bun.js/api/glob.zig @@ -1,6 +1,6 @@ const Glob = @This(); -pub const js = JSC.Codegen.JSGlob; +pub const js = jsc.Codegen.JSGlob; pub const toJS = js.toJS; pub const fromJS = js.fromJS; pub const fromJSDirect = js.fromJSDirect; @@ -17,7 +17,7 @@ const ScanOpts = struct { follow_symlinks: bool, error_on_broken_symlinks: bool, - fn parseCWD(globalThis: *JSGlobalObject, allocator: std.mem.Allocator, cwdVal: JSC.JSValue, absolute: bool, comptime fnName: string) bun.JSError![]const u8 { + fn parseCWD(globalThis: *JSGlobalObject, allocator: std.mem.Allocator, cwdVal: jsc.JSValue, absolute: bool, comptime fnName: string) bun.JSError![]const u8 { const cwd_str_raw = try cwdVal.toSlice(globalThis, allocator); if (cwd_str_raw.len == 0) return ""; @@ -125,7 +125,7 @@ pub const WalkTask = struct { walker: *GlobWalker, alloc: Allocator, err: ?Err = null, - global: *JSC.JSGlobalObject, + global: *jsc.JSGlobalObject, has_pending_activity: *std.atomic.Value(usize), pub const Err = union(enum) { @@ -140,10 +140,10 @@ pub const WalkTask = struct { } }; - pub const AsyncGlobWalkTask = JSC.ConcurrentPromiseTask(WalkTask); + pub const AsyncGlobWalkTask = jsc.ConcurrentPromiseTask(WalkTask); pub fn create( - globalThis: *JSC.JSGlobalObject, + globalThis: *jsc.JSGlobalObject, alloc: Allocator, globWalker: *GlobWalker, has_pending_activity: *std.atomic.Value(usize), @@ -172,7 +172,7 @@ pub const WalkTask = struct { } } - pub fn then(this: *WalkTask, promise: *JSC.JSPromise) void { + pub fn then(this: *WalkTask, promise: *jsc.JSPromise) void { defer this.deinit(); if (this.err) |err| { @@ -193,7 +193,7 @@ pub const WalkTask = struct { fn globWalkResultToJS(globWalk: *GlobWalker, globalThis: *JSGlobalObject) bun.JSError!JSValue { if (globWalk.matchedPaths.keys().len == 0) { - return JSC.JSValue.createEmptyArray(globalThis, 0); + return jsc.JSValue.createEmptyArray(globalThis, 0); } return BunString.toJSArray(globalThis, globWalk.matchedPaths.keys()); @@ -258,11 +258,11 @@ fn makeGlobWalker( return globWalker; } -pub fn constructor(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!*Glob { +pub fn constructor(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!*Glob { const alloc = bun.default_allocator; const arguments_ = callframe.arguments_old(1); - var arguments = JSC.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), arguments_.slice()); + var arguments = jsc.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), arguments_.slice()); defer arguments.deinit(); const pat_arg: JSValue = arguments.nextEat() orelse { return globalThis.throw("Glob.constructor: expected 1 arguments, got 0", .{}); @@ -283,7 +283,7 @@ pub fn constructor(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) b pub fn finalize( this: *Glob, ) callconv(.C) void { - const alloc = JSC.VirtualMachine.get().allocator; + const alloc = jsc.VirtualMachine.get().allocator; alloc.free(this.pattern); if (this.pattern_codepoints) |*codepoints| { codepoints.deinit(); @@ -303,11 +303,11 @@ fn decrPendingActivityFlag(has_pending_activity: *std.atomic.Value(usize)) void _ = has_pending_activity.fetchSub(1, .seq_cst); } -pub fn __scan(this: *Glob, globalThis: *JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { +pub fn __scan(this: *Glob, globalThis: *JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const alloc = bun.default_allocator; const arguments_ = callframe.arguments_old(1); - var arguments = JSC.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), arguments_.slice()); + var arguments = jsc.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), arguments_.slice()); defer arguments.deinit(); var arena = std.heap.ArenaAllocator.init(alloc); @@ -326,11 +326,11 @@ pub fn __scan(this: *Glob, globalThis: *JSGlobalObject, callframe: *JSC.CallFram return task.promise.value(); } -pub fn __scanSync(this: *Glob, globalThis: *JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { +pub fn __scanSync(this: *Glob, globalThis: *JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const alloc = bun.default_allocator; const arguments_ = callframe.arguments_old(1); - var arguments = JSC.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), arguments_.slice()); + var arguments = jsc.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), arguments_.slice()); defer arguments.deinit(); var arena = std.heap.ArenaAllocator.init(alloc); @@ -352,13 +352,13 @@ pub fn __scanSync(this: *Glob, globalThis: *JSGlobalObject, callframe: *JSC.Call return matchedPaths; } -pub fn match(this: *Glob, globalThis: *JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { +pub fn match(this: *Glob, globalThis: *JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const alloc = bun.default_allocator; var arena = Arena.init(alloc); defer arena.deinit(); const arguments_ = callframe.arguments_old(1); - var arguments = JSC.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), arguments_.slice()); + var arguments = jsc.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), arguments_.slice()); defer arguments.deinit(); const str_arg = arguments.nextEat() orelse { return globalThis.throw("Glob.matchString: expected 1 arguments, got 0", .{}); @@ -371,7 +371,7 @@ pub fn match(this: *Glob, globalThis: *JSGlobalObject, callframe: *JSC.CallFrame var str = try str_arg.toSlice(globalThis, arena.allocator()); defer str.deinit(); - return JSC.JSValue.jsBoolean(globImpl.match(arena.allocator(), this.pattern, str.slice()).matches()); + return jsc.JSValue.jsBoolean(globImpl.match(arena.allocator(), this.pattern, str.slice()).matches()); } pub fn convertUtf8(codepoints: *std.ArrayList(u32), pattern: []const u8) !void { @@ -382,10 +382,11 @@ pub fn convertUtf8(codepoints: *std.ArrayList(u32), pattern: []const u8) !void { } } +const string = []const u8; + const ResolvePath = @import("../../resolver/resolve_path.zig"); const Syscall = @import("../../sys.zig"); const std = @import("std"); -const CodepointIterator = @import("../../string_immutable.zig").UnsignedCodepointIterator; const Allocator = std.mem.Allocator; const Arena = std.heap.ArenaAllocator; @@ -394,10 +395,10 @@ const GlobWalker = globImpl.BunGlobWalker; const bun = @import("bun"); const BunString = bun.String; -const string = bun.string; +const CodepointIterator = bun.strings.UnsignedCodepointIterator; -const JSC = bun.JSC; -const JSGlobalObject = JSC.JSGlobalObject; -const JSValue = JSC.JSValue; -const ZigString = JSC.ZigString; -const ArgumentsSlice = JSC.CallFrame.ArgumentsSlice; +const jsc = bun.jsc; +const JSGlobalObject = jsc.JSGlobalObject; +const JSValue = jsc.JSValue; +const ZigString = jsc.ZigString; +const ArgumentsSlice = jsc.CallFrame.ArgumentsSlice; diff --git a/src/bun.js/api/html_rewriter.zig b/src/bun.js/api/html_rewriter.zig index 2c9930552b..bc4069177a 100644 --- a/src/bun.js/api/html_rewriter.zig +++ b/src/bun.js/api/html_rewriter.zig @@ -35,12 +35,12 @@ pub const HTMLRewriter = struct { builder: *LOLHTML.HTMLRewriter.Builder, context: *LOLHTMLContext, - pub const js = JSC.Codegen.JSHTMLRewriter; + pub const js = jsc.Codegen.JSHTMLRewriter; pub const toJS = js.toJS; pub const fromJS = js.fromJS; pub const fromJSDirect = js.fromJSDirect; - pub fn constructor(_: *JSGlobalObject, _: *JSC.CallFrame) bun.JSError!*HTMLRewriter { + pub fn constructor(_: *JSGlobalObject, _: *jsc.CallFrame) bun.JSError!*HTMLRewriter { const rewriter = bun.default_allocator.create(HTMLRewriter) catch bun.outOfMemory(); rewriter.* = HTMLRewriter{ .builder = LOLHTML.HTMLRewriter.Builder.init(), @@ -48,7 +48,7 @@ pub const HTMLRewriter = struct { .ref_count = .init(), }), }; - bun.Analytics.Features.html_rewriter += 1; + bun.analytics.Features.html_rewriter += 1; return rewriter; } @@ -56,7 +56,7 @@ pub const HTMLRewriter = struct { this: *HTMLRewriter, global: *JSGlobalObject, selector_name: ZigString, - callFrame: *JSC.CallFrame, + callFrame: *jsc.CallFrame, listener: JSValue, ) bun.JSError!JSValue { const selector_slice = std.fmt.allocPrint(bun.default_allocator, "{}", .{selector_name}) catch bun.outOfMemory(); @@ -104,7 +104,7 @@ pub const HTMLRewriter = struct { this: *HTMLRewriter, global: *JSGlobalObject, listener: JSValue, - callFrame: *JSC.CallFrame, + callFrame: *jsc.CallFrame, ) bun.JSError!JSValue { const handler_ = try DocumentHandler.init(global, listener); @@ -162,7 +162,7 @@ pub const HTMLRewriter = struct { return BufferOutputSink.init(new_context, global, response, this.builder); } - pub fn transform_(this: *HTMLRewriter, global: *JSGlobalObject, response_value: JSC.JSValue) bun.JSError!JSValue { + pub fn transform_(this: *HTMLRewriter, global: *JSGlobalObject, response_value: jsc.JSValue) bun.JSError!JSValue { if (response_value.as(Response)) |response| { if (response.body.value == .Used) { return global.throwInvalidArguments("Response body already used", .{}); @@ -184,7 +184,7 @@ pub const HTMLRewriter = struct { if (kind != .other) { { - const body_value = try JSC.WebCore.Body.extract(global, response_value); + const body_value = try jsc.WebCore.Body.extract(global, response_value); const resp = bun.new(Response, Response{ .init = .{ .status_code = 200, @@ -228,8 +228,8 @@ pub const HTMLRewriter = struct { context: LOLHTMLContext, chunk_size: usize = 0, failed: bool = false, - output: JSC.WebCore.Sink, - signal: JSC.WebCore.Signal = .{}, + output: jsc.WebCore.Sink, + signal: jsc.WebCore.Signal = .{}, backpressure: std.fifo.LinearFifo(u8, .Dynamic) = std.fifo.LinearFifo(u8, .Dynamic).init(bun.default_allocator), pub fn finalize(this: *HTMLRewriterLoader) void { @@ -247,7 +247,7 @@ pub const HTMLRewriter = struct { this.finalize(); } - pub fn connect(this: *HTMLRewriterLoader, signal: JSC.WebCore.Signal) void { + pub fn connect(this: *HTMLRewriterLoader, signal: jsc.WebCore.Signal) void { this.signal = signal; } @@ -291,7 +291,7 @@ pub const HTMLRewriter = struct { builder: *LOLHTML.HTMLRewriter.Builder, context: *LOLHTMLContext, size_hint: ?usize, - output: JSC.WebCore.Sink, + output: jsc.WebCore.Sink, ) ?[]const u8 { const chunk_size = @max(size_hint orelse 16384, 1024); this.rewriter = builder.build( @@ -317,8 +317,8 @@ pub const HTMLRewriter = struct { return null; } - pub fn sink(this: *HTMLRewriterLoader) JSC.WebCore.Sink { - return JSC.WebCore.Sink.init(this); + pub fn sink(this: *HTMLRewriterLoader) jsc.WebCore.Sink { + return jsc.WebCore.Sink.init(this); } fn writeBytes(this: *HTMLRewriterLoader, bytes: bun.ByteList, comptime deinit_: bool) ?bun.sys.Error { @@ -333,7 +333,7 @@ pub const HTMLRewriter = struct { return null; } - pub fn write(this: *HTMLRewriterLoader, data: JSC.WebCore.StreamResult) JSC.WebCore.StreamResult.Writable { + pub fn write(this: *HTMLRewriterLoader, data: jsc.WebCore.StreamResult) jsc.WebCore.StreamResult.Writable { switch (data) { .owned => |bytes| { if (this.writeBytes(bytes, true)) |err| { @@ -363,12 +363,12 @@ pub const HTMLRewriter = struct { } } - pub fn writeUTF16(this: *HTMLRewriterLoader, data: JSC.WebCore.StreamResult) JSC.WebCore.StreamResult.Writable { - return JSC.WebCore.Sink.UTF8Fallback.writeUTF16(HTMLRewriterLoader, this, data, write); + pub fn writeUTF16(this: *HTMLRewriterLoader, data: jsc.WebCore.StreamResult) jsc.WebCore.StreamResult.Writable { + return jsc.WebCore.Sink.UTF8Fallback.writeUTF16(HTMLRewriterLoader, this, data, write); } - pub fn writeLatin1(this: *HTMLRewriterLoader, data: JSC.WebCore.StreamResult) JSC.WebCore.StreamResult.Writable { - return JSC.WebCore.Sink.UTF8Fallback.writeLatin1(HTMLRewriterLoader, this, data, write); + pub fn writeLatin1(this: *HTMLRewriterLoader, data: jsc.WebCore.StreamResult) jsc.WebCore.StreamResult.Writable { + return jsc.WebCore.Sink.UTF8Fallback.writeLatin1(HTMLRewriterLoader, this, data, write); } }; @@ -383,12 +383,12 @@ pub const HTMLRewriter = struct { rewriter: ?*LOLHTML.HTMLRewriter = null, context: *LOLHTMLContext, response: *Response, - response_value: JSC.Strong.Optional = .empty, - bodyValueBufferer: ?JSC.WebCore.Body.ValueBufferer = null, - tmp_sync_error: ?*JSC.JSValue = null, + response_value: jsc.Strong.Optional = .empty, + bodyValueBufferer: ?jsc.WebCore.Body.ValueBufferer = null, + tmp_sync_error: ?*jsc.JSValue = null, // const log = bun.Output.scoped(.BufferOutputSink, false); - pub fn init(context: *LOLHTMLContext, global: *JSGlobalObject, original: *Response, builder: *LOLHTML.HTMLRewriter.Builder) bun.JSError!JSC.JSValue { + pub fn init(context: *LOLHTMLContext, global: *JSGlobalObject, original: *Response, builder: *LOLHTML.HTMLRewriter.Builder) bun.JSError!jsc.JSValue { var sink = bun.new(BufferOutputSink, .{ .ref_count = .init(), .global = global, @@ -413,7 +413,7 @@ pub const HTMLRewriter = struct { }); sink.response = result; - var sink_error: JSC.JSValue = .zero; + var sink_error: jsc.JSValue = .zero; const input_size = original.body.len(); var vm = global.bunVM(); @@ -424,7 +424,7 @@ pub const HTMLRewriter = struct { const prev_unhandled_pending_rejection_to_capture = vm.unhandled_pending_rejection_to_capture; vm.unhandled_pending_rejection_to_capture = &sink_error; sink.tmp_sync_error = &sink_error; - vm.onUnhandledRejection = &JSC.VirtualMachine.onQuietUnhandledRejectionHandlerCaptureValue; + vm.onUnhandledRejection = &jsc.VirtualMachine.onQuietUnhandledRejectionHandlerCaptureValue; defer { sink_error.ensureStillAlive(); vm.unhandled_pending_rejection_to_capture = prev_unhandled_pending_rejection_to_capture; @@ -434,7 +434,7 @@ pub const HTMLRewriter = struct { sink.rewriter = builder.build( .UTF8, .{ - .preallocated_parsing_buffer_size = if (input_size == JSC.WebCore.Blob.max_size) + .preallocated_parsing_buffer_size = if (input_size == jsc.WebCore.Blob.max_size) 1024 else @max(input_size, 1024), @@ -467,21 +467,21 @@ pub const HTMLRewriter = struct { const value = original.getBodyValue(); sink.ref(); - sink.bodyValueBufferer = JSC.WebCore.Body.ValueBufferer.init(sink, @ptrCast(&onFinishedBuffering), sink.global, bun.default_allocator); + sink.bodyValueBufferer = jsc.WebCore.Body.ValueBufferer.init(sink, @ptrCast(&onFinishedBuffering), sink.global, bun.default_allocator); response_js_value.ensureStillAlive(); sink.bodyValueBufferer.?.run(value) catch |buffering_error| { defer sink.deref(); return switch (buffering_error) { error.StreamAlreadyUsed => { - var err = JSC.SystemError{ + var err = jsc.SystemError{ .code = bun.String.static("ERR_STREAM_ALREADY_FINISHED"), .message = bun.String.static("Stream already used, please create a new one"), }; return err.toErrorInstance(sink.global); }, else => { - var err = JSC.SystemError{ + var err = jsc.SystemError{ .code = bun.String.static("ERR_STREAM_CANNOT_PIPE"), .message = bun.String.static("Failed to pipe stream"), }; @@ -502,7 +502,7 @@ pub const HTMLRewriter = struct { return response_js_value; } - pub fn onFinishedBuffering(sink: *BufferOutputSink, bytes: []const u8, js_err: ?JSC.WebCore.Body.Value.ValueError, is_async: bool) void { + pub fn onFinishedBuffering(sink: *BufferOutputSink, bytes: []const u8, js_err: ?jsc.WebCore.Body.Value.ValueError, is_async: bool) void { defer sink.deref(); if (js_err) |err| { if (sink.response.body.value == .Locked and @intFromPtr(sink.response.body.value.Locked.task) == @intFromPtr(sink) and @@ -574,7 +574,7 @@ pub const HTMLRewriter = struct { pub fn done(this: *BufferOutputSink) void { var prev_value = this.response.body.value; - this.response.body.value = JSC.WebCore.Body.Value{ + this.response.body.value = jsc.WebCore.Body.Value{ .InternalBlob = .{ .bytes = this.bytes.list.toManaged(bun.default_allocator), }, @@ -620,7 +620,7 @@ pub const HTMLRewriter = struct { // rewriter: *LOLHTML.HTMLRewriter, // context: LOLHTMLContext, // response: *Response, - // input: JSC.WebCore.Blob = undefined, + // input: jsc.WebCore.Blob = undefined, // pub fn init(context: LOLHTMLContext, global: *JSGlobalObject, original: *Response, builder: *LOLHTML.HTMLRewriter.Builder) JSValue { // var result = bun.default_allocator.create(Response) catch unreachable; // var sink = bun.default_allocator.create(StreamOutputSink) catch unreachable; @@ -678,7 +678,7 @@ pub const HTMLRewriter = struct { // result.url = bun.default_allocator.dupe(u8, original.url) catch unreachable; // result.status_text = bun.default_allocator.dupe(u8, original.status_text) catch unreachable; - // var input: JSC.WebCore.Blob = original.body.value.use(); + // var input: jsc.WebCore.Blob = original.body.value.use(); // const is_pending = input.needsToReadFile(); // defer if (!is_pending) input.detach(); @@ -691,7 +691,7 @@ pub const HTMLRewriter = struct { // // Hold off on cloning until we're actually done. - // return JSC.JSValue.fromRef( + // return jsc.JSValue.fromRef( // Response.makeMaybePooled(sink.global, sink.response), // ); // } @@ -714,7 +714,7 @@ pub const HTMLRewriter = struct { // var prev_value = this.response.body.value; // var bytes = this.bytes.slice(); // this.response.body.value = .{ - // .Blob = JSC.WebCore.Blob.init(bytes, this.bytes.allocator, this.global), + // .Blob = jsc.WebCore.Blob.init(bytes, this.bytes.allocator, this.global), // }; // prev_value.resolve( // &this.response.body.value, @@ -869,7 +869,7 @@ fn HandlerCallback( ) (fn (*HandlerType, *LOLHTMLType) bool) { return struct { pub fn callback(this: *HandlerType, value: *LOLHTMLType) bool { - JSC.markBinding(@src()); + jsc.markBinding(@src()); var wrapper = ZigType.init(value); wrapper.ref(); @@ -1060,7 +1060,7 @@ pub const TextChunk = struct { ref_count: RefCount, text_chunk: ?*LOLHTML.TextChunk = null, - pub const js = JSC.Codegen.JSTextChunk; + pub const js = jsc.Codegen.JSTextChunk; pub const toJS = js.toJS; pub const fromJS = js.fromJS; pub const fromJSDirect = js.fromJSDirect; @@ -1089,7 +1089,7 @@ pub const TextChunk = struct { pub fn before_( this: *TextChunk, - callFrame: *JSC.CallFrame, + callFrame: *jsc.CallFrame, globalObject: *JSGlobalObject, content: ZigString, contentOptions: ?ContentOptions, @@ -1099,7 +1099,7 @@ pub const TextChunk = struct { pub fn after_( this: *TextChunk, - callFrame: *JSC.CallFrame, + callFrame: *jsc.CallFrame, globalObject: *JSGlobalObject, content: ZigString, contentOptions: ?ContentOptions, @@ -1109,7 +1109,7 @@ pub const TextChunk = struct { pub fn replace_( this: *TextChunk, - callFrame: *JSC.CallFrame, + callFrame: *jsc.CallFrame, globalObject: *JSGlobalObject, content: ZigString, contentOptions: ?ContentOptions, @@ -1124,7 +1124,7 @@ pub const TextChunk = struct { pub fn remove( this: *TextChunk, _: *JSGlobalObject, - callFrame: *JSC.CallFrame, + callFrame: *jsc.CallFrame, ) bun.JSError!JSValue { if (this.text_chunk == null) return .js_undefined; @@ -1183,7 +1183,7 @@ pub const DocType = struct { }); } - pub const js = JSC.Codegen.JSDocType; + pub const js = jsc.Codegen.JSDocType; pub const toJS = js.toJS; pub const fromJS = js.fromJS; pub const fromJSDirect = js.fromJSDirect; @@ -1230,7 +1230,7 @@ pub const DocType = struct { pub fn remove( this: *DocType, _: *JSGlobalObject, - callFrame: *JSC.CallFrame, + callFrame: *jsc.CallFrame, ) bun.JSError!JSValue { if (this.doctype == null) return .js_undefined; @@ -1256,7 +1256,7 @@ pub const DocEnd = struct { ref_count: RefCount, doc_end: ?*LOLHTML.DocEnd, - pub const js = JSC.Codegen.JSDocEnd; + pub const js = jsc.Codegen.JSDocEnd; pub const toJS = js.toJS; pub const fromJS = js.fromJS; pub const fromJSDirect = js.fromJSDirect; @@ -1286,7 +1286,7 @@ pub const DocEnd = struct { pub fn append_( this: *DocEnd, - callFrame: *JSC.CallFrame, + callFrame: *jsc.CallFrame, globalObject: *JSGlobalObject, content: ZigString, contentOptions: ?ContentOptions, @@ -1314,7 +1314,7 @@ pub const Comment = struct { ref_count: RefCount, comment: ?*LOLHTML.Comment = null, - pub const js = JSC.Codegen.JSComment; + pub const js = jsc.Codegen.JSComment; pub const toJS = js.toJS; pub const fromJS = js.fromJS; pub const fromJSDirect = js.fromJSDirect; @@ -1343,7 +1343,7 @@ pub const Comment = struct { pub fn before_( this: *Comment, - callFrame: *JSC.CallFrame, + callFrame: *jsc.CallFrame, globalObject: *JSGlobalObject, content: ZigString, contentOptions: ?ContentOptions, @@ -1353,7 +1353,7 @@ pub const Comment = struct { pub fn after_( this: *Comment, - callFrame: *JSC.CallFrame, + callFrame: *jsc.CallFrame, globalObject: *JSGlobalObject, content: ZigString, contentOptions: ?ContentOptions, @@ -1363,7 +1363,7 @@ pub const Comment = struct { pub fn replace_( this: *Comment, - callFrame: *JSC.CallFrame, + callFrame: *jsc.CallFrame, globalObject: *JSGlobalObject, content: ZigString, contentOptions: ?ContentOptions, @@ -1378,7 +1378,7 @@ pub const Comment = struct { pub fn remove( this: *Comment, _: *JSGlobalObject, - callFrame: *JSC.CallFrame, + callFrame: *jsc.CallFrame, ) bun.JSError!JSValue { if (this.comment == null) return JSValue.jsNull(); @@ -1467,7 +1467,7 @@ pub const EndTag = struct { pub const onEndTagHandler = LOLHTML.DirectiveHandler(LOLHTML.EndTag, Handler, onEndTag); }; - pub const js = JSC.Codegen.JSEndTag; + pub const js = jsc.Codegen.JSEndTag; pub const toJS = js.toJS; pub const fromJS = js.fromJS; pub const fromJSDirect = js.fromJSDirect; @@ -1490,7 +1490,7 @@ pub const EndTag = struct { pub fn before_( this: *EndTag, - callFrame: *JSC.CallFrame, + callFrame: *jsc.CallFrame, globalObject: *JSGlobalObject, content: ZigString, contentOptions: ?ContentOptions, @@ -1500,7 +1500,7 @@ pub const EndTag = struct { pub fn after_( this: *EndTag, - callFrame: *JSC.CallFrame, + callFrame: *jsc.CallFrame, globalObject: *JSGlobalObject, content: ZigString, contentOptions: ?ContentOptions, @@ -1510,7 +1510,7 @@ pub const EndTag = struct { pub fn replace_( this: *EndTag, - callFrame: *JSC.CallFrame, + callFrame: *jsc.CallFrame, globalObject: *JSGlobalObject, content: ZigString, contentOptions: ?ContentOptions, @@ -1525,7 +1525,7 @@ pub const EndTag = struct { pub fn remove( this: *EndTag, _: *JSGlobalObject, - callFrame: *JSC.CallFrame, + callFrame: *jsc.CallFrame, ) bun.JSError!JSValue { if (this.end_tag == null) return .js_undefined; @@ -1591,14 +1591,14 @@ pub const AttributeIterator = struct { bun.destroy(this); } - pub const js = JSC.Codegen.JSAttributeIterator; + pub const js = jsc.Codegen.JSAttributeIterator; pub const toJS = js.toJS; pub const fromJS = js.fromJS; pub const fromJSDirect = js.fromJSDirect; - pub fn next(this: *AttributeIterator, globalObject: *JSGlobalObject, _: *JSC.CallFrame) bun.JSError!JSValue { - const done_label = JSC.ZigString.static("done"); - const value_label = JSC.ZigString.static("value"); + pub fn next(this: *AttributeIterator, globalObject: *JSGlobalObject, _: *jsc.CallFrame) bun.JSError!JSValue { + const done_label = jsc.ZigString.static("done"); + const value_label = jsc.ZigString.static("value"); if (this.iterator == null) { return JSValue.createObject2(globalObject, done_label, value_label, JSValue.jsBoolean(true), .js_undefined); @@ -1622,7 +1622,7 @@ pub const AttributeIterator = struct { )); } - pub fn getThis(_: *AttributeIterator, _: *JSGlobalObject, callFrame: *JSC.CallFrame) bun.JSError!JSValue { + pub fn getThis(_: *AttributeIterator, _: *JSGlobalObject, callFrame: *jsc.CallFrame) bun.JSError!JSValue { return callFrame.this(); } }; @@ -1634,7 +1634,7 @@ pub const Element = struct { ref_count: RefCount, element: ?*LOLHTML.Element = null, - pub const js = JSC.Codegen.JSElement; + pub const js = jsc.Codegen.JSElement; pub const toJS = js.toJS; pub const fromJS = js.fromJS; pub const fromJSDirect = js.fromJSDirect; @@ -1659,7 +1659,7 @@ pub const Element = struct { this: *Element, globalObject: *JSGlobalObject, function: JSValue, - callFrame: *JSC.CallFrame, + callFrame: *jsc.CallFrame, ) bun.JSError!JSValue { if (this.element == null) return JSValue.jsNull(); @@ -1708,7 +1708,7 @@ pub const Element = struct { } /// Sets an attribute to a provided value, creating the attribute if it does not exist. - pub fn setAttribute_(this: *Element, callFrame: *JSC.CallFrame, globalObject: *JSGlobalObject, name_: ZigString, value_: ZigString) JSValue { + pub fn setAttribute_(this: *Element, callFrame: *jsc.CallFrame, globalObject: *JSGlobalObject, name_: ZigString, value_: ZigString) JSValue { if (this.element == null) return .js_undefined; @@ -1722,7 +1722,7 @@ pub const Element = struct { } /// Removes the attribute. - pub fn removeAttribute_(this: *Element, callFrame: *JSC.CallFrame, globalObject: *JSGlobalObject, name: ZigString) JSValue { + pub fn removeAttribute_(this: *Element, callFrame: *jsc.CallFrame, globalObject: *JSGlobalObject, name: ZigString) JSValue { if (this.element == null) return .js_undefined; @@ -1758,7 +1758,7 @@ pub const Element = struct { } /// Inserts content before the element. - pub fn before_(this: *Element, callFrame: *JSC.CallFrame, globalObject: *JSGlobalObject, content: ZigString, contentOptions: ?ContentOptions) JSValue { + pub fn before_(this: *Element, callFrame: *jsc.CallFrame, globalObject: *JSGlobalObject, content: ZigString, contentOptions: ?ContentOptions) JSValue { return contentHandler( this, LOLHTML.Element.before, @@ -1770,7 +1770,7 @@ pub const Element = struct { } /// Inserts content right after the element. - pub fn after_(this: *Element, callFrame: *JSC.CallFrame, globalObject: *JSGlobalObject, content: ZigString, contentOptions: ?ContentOptions) JSValue { + pub fn after_(this: *Element, callFrame: *jsc.CallFrame, globalObject: *JSGlobalObject, content: ZigString, contentOptions: ?ContentOptions) JSValue { return contentHandler( this, LOLHTML.Element.after, @@ -1782,7 +1782,7 @@ pub const Element = struct { } /// Inserts content right after the start tag of the element. - pub fn prepend_(this: *Element, callFrame: *JSC.CallFrame, globalObject: *JSGlobalObject, content: ZigString, contentOptions: ?ContentOptions) JSValue { + pub fn prepend_(this: *Element, callFrame: *jsc.CallFrame, globalObject: *JSGlobalObject, content: ZigString, contentOptions: ?ContentOptions) JSValue { return contentHandler( this, LOLHTML.Element.prepend, @@ -1794,7 +1794,7 @@ pub const Element = struct { } /// Inserts content right before the end tag of the element. - pub fn append_(this: *Element, callFrame: *JSC.CallFrame, globalObject: *JSGlobalObject, content: ZigString, contentOptions: ?ContentOptions) JSValue { + pub fn append_(this: *Element, callFrame: *jsc.CallFrame, globalObject: *JSGlobalObject, content: ZigString, contentOptions: ?ContentOptions) JSValue { return contentHandler( this, LOLHTML.Element.append, @@ -1806,7 +1806,7 @@ pub const Element = struct { } /// Removes the element and inserts content in place of it. - pub fn replace_(this: *Element, callFrame: *JSC.CallFrame, globalObject: *JSGlobalObject, content: ZigString, contentOptions: ?ContentOptions) JSValue { + pub fn replace_(this: *Element, callFrame: *jsc.CallFrame, globalObject: *JSGlobalObject, content: ZigString, contentOptions: ?ContentOptions) JSValue { return contentHandler( this, LOLHTML.Element.replace, @@ -1818,7 +1818,7 @@ pub const Element = struct { } /// Replaces content of the element. - pub fn setInnerContent_(this: *Element, callFrame: *JSC.CallFrame, globalObject: *JSGlobalObject, content: ZigString, contentOptions: ?ContentOptions) JSValue { + pub fn setInnerContent_(this: *Element, callFrame: *jsc.CallFrame, globalObject: *JSGlobalObject, content: ZigString, contentOptions: ?ContentOptions) JSValue { return contentHandler( this, LOLHTML.Element.setInnerContent, @@ -1837,7 +1837,7 @@ pub const Element = struct { pub const setInnerContent = host_fn.wrapInstanceMethod(Element, "setInnerContent_", false); /// Removes the element with all its content. - pub fn remove(this: *Element, _: *JSGlobalObject, callFrame: *JSC.CallFrame) bun.JSError!JSValue { + pub fn remove(this: *Element, _: *JSGlobalObject, callFrame: *jsc.CallFrame) bun.JSError!JSValue { if (this.element == null) return .js_undefined; @@ -1846,7 +1846,7 @@ pub const Element = struct { } /// Removes the start tag and end tag of the element but keeps its inner content intact. - pub fn removeAndKeepContent(this: *Element, _: *JSGlobalObject, callFrame: *JSC.CallFrame) bun.JSError!JSValue { + pub fn removeAndKeepContent(this: *Element, _: *JSGlobalObject, callFrame: *jsc.CallFrame) bun.JSError!JSValue { if (this.element == null) return .js_undefined; @@ -1909,16 +1909,17 @@ pub const Element = struct { } }; +const string = []const u8; + const std = @import("std"); const bun = @import("bun"); const JSError = bun.JSError; const LOLHTML = bun.LOLHTML; -const string = bun.string; const Response = bun.webcore.Response; -const JSC = bun.JSC; -const JSGlobalObject = JSC.JSGlobalObject; -const JSValue = JSC.JSValue; -const ZigString = JSC.ZigString; -const host_fn = JSC.host_fn; +const jsc = bun.jsc; +const JSGlobalObject = jsc.JSGlobalObject; +const JSValue = jsc.JSValue; +const ZigString = jsc.ZigString; +const host_fn = jsc.host_fn; diff --git a/src/bun.js/api/server.zig b/src/bun.js/api/server.zig index b15058fdab..2f8c2aff97 100644 --- a/src/bun.js/api/server.zig +++ b/src/bun.js/api/server.zig @@ -1,10 +1,9 @@ -const Bun = @This(); - const httplog = Output.scoped(.Server, false); const ctxLog = Output.scoped(.RequestContext, false); pub const WebSocketServerContext = @import("./server/WebSocketServerContext.zig"); pub const HTTPStatusText = @import("./server/HTTPStatusText.zig"); +pub const HTMLBundle = @import("./server/HTMLBundle.zig"); pub fn writeStatus(comptime ssl: bool, resp_ptr: ?*uws.NewApp(ssl).Response, status: u16) void { if (resp_ptr) |resp| { @@ -74,12 +73,12 @@ pub const AnyRoute = union(enum) { } } - fn bundledHTMLManifestItemFromJS(argument: JSC.JSValue, index_path: []const u8, init_ctx: *ServerInitContext) bun.JSError!?AnyRoute { + fn bundledHTMLManifestItemFromJS(argument: jsc.JSValue, index_path: []const u8, init_ctx: *ServerInitContext) bun.JSError!?AnyRoute { if (!argument.isObject()) return null; const path_string = try bun.String.fromJS(try argument.get(init_ctx.global, "path") orelse return null, init_ctx.global); defer path_string.deref(); - var path = JSC.Node.PathOrFileDescriptor{ .path = try JSC.Node.PathLike.fromBunString(init_ctx.global, path_string, false, bun.default_allocator) }; + var path = jsc.Node.PathOrFileDescriptor{ .path = try jsc.Node.PathLike.fromBunString(init_ctx.global, path_string, false, bun.default_allocator) }; defer path.deinit(); // Construct the route by stripping paths above the root. @@ -113,7 +112,7 @@ pub const AnyRoute = union(enum) { try builder.appendSlice(relative_path); - const fetch_headers = try JSC.WebCore.FetchHeaders.createFromJS(init_ctx.global, try argument.get(init_ctx.global, "headers") orelse return null); + const fetch_headers = try jsc.WebCore.FetchHeaders.createFromJS(init_ctx.global, try argument.get(init_ctx.global, "headers") orelse return null); defer if (fetch_headers) |headers| headers.deref(); if (init_ctx.global.hasException()) return error.JSError; @@ -138,7 +137,7 @@ pub const AnyRoute = union(enum) { /// This is the JS representation of an HTMLImportManifest /// /// See ./src/bundler/HTMLImportManifest.zig - fn bundledHTMLManifestFromJS(argument: JSC.JSValue, init_ctx: *ServerInitContext) bun.JSError!?AnyRoute { + fn bundledHTMLManifestFromJS(argument: jsc.JSValue, init_ctx: *ServerInitContext) bun.JSError!?AnyRoute { if (!argument.isObject()) return null; const index = try argument.getOptional(init_ctx.global, "index", ZigString.Slice) orelse return null; @@ -156,7 +155,7 @@ pub const AnyRoute = union(enum) { return html_route; } - pub fn fromOptions(global: *JSC.JSGlobalObject, headers: ?*JSC.WebCore.FetchHeaders, path: *JSC.Node.PathOrFileDescriptor) !AnyRoute { + pub fn fromOptions(global: *jsc.JSGlobalObject, headers: ?*jsc.WebCore.FetchHeaders, path: *jsc.Node.PathOrFileDescriptor) !AnyRoute { // The file/static route doesn't ref it. var blob = Blob.findOrCreateFileFromPath(path, global, false); @@ -188,7 +187,7 @@ pub const AnyRoute = union(enum) { return AnyRoute{ .static = StaticRoute.initFromAnyBlob(&.{ .Blob = blob }, .{ .server = null, .headers = headers }) }; } - pub fn htmlRouteFromJS(argument: JSC.JSValue, init_ctx: *ServerInitContext) bun.JSError!?AnyRoute { + pub fn htmlRouteFromJS(argument: jsc.JSValue, init_ctx: *ServerInitContext) bun.JSError!?AnyRoute { if (argument.as(HTMLBundle)) |html_bundle| { const entry = init_ctx.dedupe_html_bundle_map.getOrPut(html_bundle) catch bun.outOfMemory(); if (!entry.found_existing) { @@ -210,15 +209,15 @@ pub const AnyRoute = union(enum) { arena: std.heap.ArenaAllocator, dedupe_html_bundle_map: std.AutoHashMap(*HTMLBundle, bun.ptr.RefPtr(HTMLBundle.Route)), js_string_allocations: bun.bake.StringRefList, - global: *JSC.JSGlobalObject, + global: *jsc.JSGlobalObject, framework_router_list: std.ArrayList(bun.bake.Framework.FileSystemRouterType), user_routes: *std.ArrayList(ServerConfig.StaticRouteEntry), }; pub fn fromJS( - global: *JSC.JSGlobalObject, + global: *jsc.JSGlobalObject, path: []const u8, - argument: JSC.JSValue, + argument: jsc.JSValue, init_ctx: *ServerInitContext, ) bun.JSError!?AnyRoute { if (try AnyRoute.htmlRouteFromJS(argument, init_ctx)) |html_route| { @@ -290,19 +289,19 @@ const ServePlugins = struct { unqueued: []const []const u8, pending: struct { /// Promise may be empty if the plugin load finishes synchronously. - plugin: *bun.JSC.API.JSBundler.Plugin, - promise: JSC.JSPromise.Strong, + plugin: *bun.jsc.API.JSBundler.Plugin, + promise: jsc.JSPromise.Strong, html_bundle_routes: std.ArrayListUnmanaged(*HTMLBundle.Route), dev_server: ?*bun.bake.DevServer, }, - loaded: *bun.JSC.API.JSBundler.Plugin, + loaded: *bun.jsc.API.JSBundler.Plugin, /// Error information is not stored as it is already reported. err, }; pub const GetOrStartLoadResult = union(enum) { /// null = no plugins, used by server implementation - ready: ?*bun.JSC.API.JSBundler.Plugin, + ready: ?*bun.jsc.API.JSBundler.Plugin, pending, err, }; @@ -326,7 +325,7 @@ const ServePlugins = struct { bun.destroy(this); } - pub fn getOrStartLoad(this: *ServePlugins, global: *JSC.JSGlobalObject, cb: Callback) bun.JSError!GetOrStartLoadResult { + pub fn getOrStartLoad(this: *ServePlugins, global: *jsc.JSGlobalObject, cb: Callback) bun.JSError!GetOrStartLoadResult { sw: switch (this.state) { .unqueued => { try this.loadAndResolvePlugins(global); @@ -351,12 +350,12 @@ const ServePlugins = struct { } extern fn JSBundlerPlugin__loadAndResolvePluginsForServe( - plugin: *bun.JSC.API.JSBundler.Plugin, - plugins: JSC.JSValue, - bunfig_folder: JSC.JSValue, + plugin: *bun.jsc.API.JSBundler.Plugin, + plugins: jsc.JSValue, + bunfig_folder: jsc.JSValue, ) JSValue; - fn loadAndResolvePlugins(this: *ServePlugins, global: *JSC.JSGlobalObject) bun.JSError!void { + fn loadAndResolvePlugins(this: *ServePlugins, global: *jsc.JSGlobalObject) bun.JSError!void { bun.assert(this.state == .unqueued); const plugin_list = this.state.unqueued; const bunfig_folder = bun.path.dirname(global.bunVM().transpiler.options.bunfig_path, .auto); @@ -364,7 +363,7 @@ const ServePlugins = struct { this.ref(); defer this.deref(); - const plugin = bun.JSC.API.JSBundler.Plugin.create(global, .browser); + const plugin = bun.jsc.API.JSBundler.Plugin.create(global, .browser); var sfb = std.heap.stackFallback(@sizeOf(bun.String) * 4, bun.default_allocator); const alloc = sfb.get(); const bunstring_array = alloc.alloc(bun.String, plugin_list.len) catch bun.outOfMemory(); @@ -376,7 +375,7 @@ const ServePlugins = struct { const bunfig_folder_bunstr = try bun.String.createUTF8ForJS(global, bunfig_folder); this.state = .{ .pending = .{ - .promise = JSC.JSPromise.Strong.init(global), + .promise = jsc.JSPromise.Strong.init(global), .plugin = plugin, .html_bundle_routes = .empty, .dev_server = null, @@ -424,10 +423,10 @@ const ServePlugins = struct { } } - pub const onResolve = JSC.toJSHostFn(onResolveImpl); - pub const onReject = JSC.toJSHostFn(onRejectImpl); + pub const onResolve = jsc.toJSHostFn(onResolveImpl); + pub const onReject = jsc.toJSHostFn(onRejectImpl); - pub fn onResolveImpl(_: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { + pub fn onResolveImpl(_: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { ctxLog("onResolve", .{}); const plugins_result, const plugins_js = callframe.argumentsAsArray(2); @@ -461,7 +460,7 @@ const ServePlugins = struct { } } - pub fn onRejectImpl(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { + pub fn onRejectImpl(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { ctxLog("onReject", .{}); const error_js, const plugin_js = callframe.argumentsAsArray(2); @@ -471,7 +470,7 @@ const ServePlugins = struct { return .js_undefined; } - pub fn handleOnReject(this: *ServePlugins, global: *JSC.JSGlobalObject, err: JSValue) void { + pub fn handleOnReject(this: *ServePlugins, global: *jsc.JSGlobalObject, err: JSValue) void { bun.assert(this.state == .pending); const pending = &this.state.pending; var html_bundle_routes = pending.html_bundle_routes; @@ -502,7 +501,7 @@ const ServePlugins = struct { const PluginsResult = union(enum) { pending, - found: ?*bun.JSC.API.JSBundler.Plugin, + found: ?*bun.jsc.API.JSBundler.Plugin, err, }; @@ -510,12 +509,12 @@ pub fn NewServer(protocol_enum: enum { http, https }, development_kind: enum { d return struct { pub const js = switch (protocol_enum) { .http => switch (development_kind) { - .debug => bun.JSC.Codegen.JSDebugHTTPServer, - .production => bun.JSC.Codegen.JSHTTPServer, + .debug => bun.jsc.Codegen.JSDebugHTTPServer, + .production => bun.jsc.Codegen.JSHTTPServer, }, .https => switch (development_kind) { - .debug => bun.JSC.Codegen.JSDebugHTTPSServer, - .production => bun.JSC.Codegen.JSHTTPSServer, + .debug => bun.jsc.Codegen.JSDebugHTTPSServer, + .production => bun.jsc.Codegen.JSHTTPSServer, }, }; pub const fromJS = js.fromJS; @@ -533,17 +532,17 @@ pub fn NewServer(protocol_enum: enum { http, https }, development_kind: enum { d pub const App = uws.NewApp(ssl_enabled); app: ?*App = null, listener: ?*App.ListenSocket = null, - js_value: JSC.Strong.Optional = .empty, + js_value: jsc.Strong.Optional = .empty, /// Potentially null before listen() is called, and once .destroy() is called. - vm: *JSC.VirtualMachine, + vm: *jsc.VirtualMachine, globalThis: *JSGlobalObject, base_url_string_for_joining: string = "", config: ServerConfig = ServerConfig{}, pending_requests: usize = 0, request_pool_allocator: *RequestContext.RequestContextStackAllocator = undefined, - all_closed_promise: JSC.JSPromise.Strong = .{}, + all_closed_promise: jsc.JSPromise.Strong = .{}, - listen_callback: JSC.AnyTask = undefined, + listen_callback: jsc.AnyTask = undefined, allocator: std.mem.Allocator, poll_ref: Async.KeepAlive = .{}, @@ -565,9 +564,9 @@ pub fn NewServer(protocol_enum: enum { http, https }, development_kind: enum { d /// So we have to store it. user_routes: std.ArrayListUnmanaged(UserRoute) = .{}, - on_clienterror: JSC.Strong.Optional = .empty, + on_clienterror: jsc.Strong.Optional = .empty, - inspector_server_id: JSC.Debugger.DebuggerId = .init(0), + inspector_server_id: jsc.Debugger.DebuggerId = .init(0), pub const doStop = host_fn.wrapInstanceMethod(ThisServer, "stopFromJS", false); pub const dispose = host_fn.wrapInstanceMethod(ThisServer, "disposeFromJS", false); @@ -600,7 +599,7 @@ pub fn NewServer(protocol_enum: enum { http, https }, development_kind: enum { d return .{ .ready = null }; } - pub fn doSubscriberCount(this: *ThisServer, globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { + pub fn doSubscriberCount(this: *ThisServer, globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const arguments = callframe.arguments_old(1); if (arguments.len < 1) { return globalThis.throwNotEnoughArguments("subscriberCount", 1, 0); @@ -620,11 +619,11 @@ pub fn NewServer(protocol_enum: enum { http, https }, development_kind: enum { d return JSValue.jsNumber((this.app.?.numSubscribers(topic.slice()))); } - pub fn constructor(globalThis: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!*ThisServer { + pub fn constructor(globalThis: *jsc.JSGlobalObject, _: *jsc.CallFrame) bun.JSError!*ThisServer { return globalThis.throw2("Server() is not a constructor", .{}); } - pub fn jsValueAssertAlive(server: *ThisServer) JSC.JSValue { + pub fn jsValueAssertAlive(server: *ThisServer) jsc.JSValue { bun.debugAssert(server.listener != null); // this assertion is only valid while listening return server.js_value.get() orelse brk: { bun.debugAssert(false); @@ -632,7 +631,7 @@ pub fn NewServer(protocol_enum: enum { http, https }, development_kind: enum { d }; } - pub fn requestIP(this: *ThisServer, request: *JSC.WebCore.Request) bun.JSError!JSC.JSValue { + pub fn requestIP(this: *ThisServer, request: *jsc.WebCore.Request) bun.JSError!jsc.JSValue { if (this.config.address == .unix) return JSValue.jsNull(); const info = request.request_context.getRemoteSocketInfo() orelse return JSValue.jsNull(); return SocketAddress.createDTO(this.globalThis, info.ip, @intCast(info.port), info.is_ipv6); @@ -645,7 +644,7 @@ pub fn NewServer(protocol_enum: enum { http, https }, development_kind: enum { d (if (this.dev_server) |dev| dev.memoryCost() else 0); } - pub fn timeout(this: *ThisServer, globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { + pub fn timeout(this: *ThisServer, globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const arguments = callframe.arguments_old(2).slice(); if (arguments.len < 2 or arguments[0].isEmptyOrUndefinedOrNull()) { return globalObject.throwNotEnoughArguments("timeout", 2, arguments.len); @@ -693,7 +692,7 @@ pub fn NewServer(protocol_enum: enum { http, https }, development_kind: enum { d try this.config.appendStaticRoute(path, route, method); } - pub fn publish(this: *ThisServer, globalThis: *JSC.JSGlobalObject, topic: ZigString, message_value: JSValue, compress_value: ?JSValue) bun.JSError!JSValue { + pub fn publish(this: *ThisServer, globalThis: *jsc.JSGlobalObject, topic: ZigString, message_value: JSValue, compress_value: ?JSValue) bun.JSError!JSValue { if (this.config.websocket == null) return JSValue.jsNumber(0); @@ -742,8 +741,8 @@ pub fn NewServer(protocol_enum: enum { http, https }, development_kind: enum { d pub fn onUpgrade( this: *ThisServer, - globalThis: *JSC.JSGlobalObject, - object: JSC.JSValue, + globalThis: *jsc.JSGlobalObject, + object: jsc.JSValue, optional: ?JSValue, ) bun.JSError!JSValue { if (this.config.websocket == null) { @@ -756,10 +755,10 @@ pub fn NewServer(protocol_enum: enum { http, https }, development_kind: enum { d if (object.as(NodeHTTPResponse)) |nodeHttpResponse| { if (nodeHttpResponse.flags.ended or nodeHttpResponse.flags.socket_closed) { - return JSC.jsBoolean(false); + return jsc.jsBoolean(false); } - var data_value = JSC.JSValue.zero; + var data_value = jsc.JSValue.zero; // if we converted a HeadersInit to a Headers object, we need to free it var fetch_headers_to_deref: ?*WebCore.FetchHeaders = null; @@ -833,21 +832,21 @@ pub fn NewServer(protocol_enum: enum { http, https }, development_kind: enum { d } } } - return JSC.jsBoolean(nodeHttpResponse.upgrade(data_value, sec_websocket_protocol, sec_websocket_extensions)); + return jsc.jsBoolean(nodeHttpResponse.upgrade(data_value, sec_websocket_protocol, sec_websocket_extensions)); } var request = object.as(Request) orelse { return globalThis.throwInvalidArguments("upgrade requires a Request object", .{}); }; - var upgrader = request.request_context.get(RequestContext) orelse return JSC.jsBoolean(false); + var upgrader = request.request_context.get(RequestContext) orelse return jsc.jsBoolean(false); if (upgrader.isAbortedOrEnded()) { - return JSC.jsBoolean(false); + return jsc.jsBoolean(false); } if (upgrader.upgrade_context == null or @intFromPtr(upgrader.upgrade_context) == std.math.maxInt(usize)) { - return JSC.jsBoolean(false); + return jsc.jsBoolean(false); } const resp = upgrader.resp.?; @@ -879,7 +878,7 @@ pub fn NewServer(protocol_enum: enum { http, https }, development_kind: enum { d } if (sec_websocket_key_str.len == 0) { - return JSC.jsBoolean(false); + return jsc.jsBoolean(false); } if (sec_websocket_protocol.len > 0) { @@ -890,7 +889,7 @@ pub fn NewServer(protocol_enum: enum { http, https }, development_kind: enum { d sec_websocket_extensions.markUTF8(); } - var data_value = JSC.JSValue.zero; + var data_value = jsc.JSValue.zero; // if we converted a HeadersInit to a Headers object, we need to free it var fetch_headers_to_deref: ?*WebCore.FetchHeaders = null; @@ -1003,10 +1002,10 @@ pub fn NewServer(protocol_enum: enum { http, https }, development_kind: enum { d ctx, ); - return JSC.jsBoolean(true); + return jsc.jsBoolean(true); } - pub fn onReloadFromZig(this: *ThisServer, new_config: *ServerConfig, globalThis: *JSC.JSGlobalObject) void { + pub fn onReloadFromZig(this: *ThisServer, new_config: *ServerConfig, globalThis: *jsc.JSGlobalObject) void { httplog("onReload", .{}); this.app.?.clearRoutes(); @@ -1102,13 +1101,13 @@ pub fn NewServer(protocol_enum: enum { http, https }, development_kind: enum { d return true; } - pub fn onReload(this: *ThisServer, globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { + pub fn onReload(this: *ThisServer, globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const arguments = callframe.arguments(); if (arguments.len < 1) { return globalThis.throwNotEnoughArguments("reload", 1, 0); } - var args_slice = JSC.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), arguments); + var args_slice = jsc.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), arguments); defer args_slice.deinit(); var new_config: ServerConfig = .{}; @@ -1129,10 +1128,10 @@ pub fn NewServer(protocol_enum: enum { http, https }, development_kind: enum { d pub fn onFetch( this: *ThisServer, - ctx: *JSC.JSGlobalObject, - callframe: *JSC.CallFrame, - ) bun.JSError!JSC.JSValue { - JSC.markBinding(@src()); + ctx: *jsc.JSGlobalObject, + callframe: *jsc.CallFrame, + ) bun.JSError!jsc.JSValue { + jsc.markBinding(@src()); if (this.config.onRequest == .zero) { return JSPromise.dangerouslyCreateRejectedPromiseValueWithoutNotifyingVM(ctx, ZigString.init("fetch() requires the server to have a fetch handler").toErrorInstance(ctx)); @@ -1146,11 +1145,11 @@ pub fn NewServer(protocol_enum: enum { http, https }, development_kind: enum { d var headers: ?*WebCore.FetchHeaders = null; var method = HTTP.Method.GET; - var args = JSC.CallFrame.ArgumentsSlice.init(ctx.bunVM(), arguments); + var args = jsc.CallFrame.ArgumentsSlice.init(ctx.bunVM(), arguments); defer args.deinit(); var first_arg = args.nextEat().?; - var body: JSC.WebCore.Body.Value = .{ .Null = {} }; + var body: jsc.WebCore.Body.Value = .{ .Null = {} }; var existing_request: WebCore.Request = undefined; // TODO: set Host header // TODO: set User-Agent header @@ -1161,7 +1160,7 @@ pub fn NewServer(protocol_enum: enum { http, https }, development_kind: enum { d var temp_url_str = url_zig_str.slice(); if (temp_url_str.len == 0) { - const fetch_error = JSC.WebCore.Fetch.fetch_error_blank_url; + const fetch_error = jsc.WebCore.Fetch.fetch_error_blank_url; return JSPromise.dangerouslyCreateRejectedPromiseValueWithoutNotifyingVM(ctx, ZigString.init(fetch_error).toErrorInstance(ctx)); } @@ -1215,7 +1214,7 @@ pub fn NewServer(protocol_enum: enum { http, https }, development_kind: enum { d false, ); } else { - const fetch_error = JSC.WebCore.Fetch.fetch_type_error_strings.get(bun.JSC.C.JSValueGetType(ctx, first_arg.asRef())); + const fetch_error = jsc.WebCore.Fetch.fetch_type_error_strings.get(bun.jsc.C.JSValueGetType(ctx, first_arg.asRef())); const err = ctx.toTypeError(.INVALID_ARG_TYPE, "{s}", .{fetch_error}); return JSPromise.dangerouslyCreateRejectedPromiseValueWithoutNotifyingVM(ctx, err); @@ -1227,28 +1226,28 @@ pub fn NewServer(protocol_enum: enum { http, https }, development_kind: enum { d const response_value = this.config.onRequest.call( this.globalThis, this.jsValueAssertAlive(), - &[_]JSC.JSValue{request.toJS(this.globalThis)}, + &[_]jsc.JSValue{request.toJS(this.globalThis)}, ) catch |err| this.globalThis.takeException(err); if (response_value.isAnyError()) { - return JSC.JSPromise.dangerouslyCreateRejectedPromiseValueWithoutNotifyingVM(ctx, response_value); + return jsc.JSPromise.dangerouslyCreateRejectedPromiseValueWithoutNotifyingVM(ctx, response_value); } if (response_value.isEmptyOrUndefinedOrNull()) { - return JSC.JSPromise.dangerouslyCreateRejectedPromiseValueWithoutNotifyingVM(ctx, ZigString.init("fetch() returned an empty value").toErrorInstance(ctx)); + return jsc.JSPromise.dangerouslyCreateRejectedPromiseValueWithoutNotifyingVM(ctx, ZigString.init("fetch() returned an empty value").toErrorInstance(ctx)); } if (response_value.asAnyPromise() != null) { return response_value; } - if (response_value.as(JSC.WebCore.Response)) |resp| { + if (response_value.as(jsc.WebCore.Response)) |resp| { resp.url = existing_request.url.clone(); } - return JSC.JSPromise.resolvedPromiseValue(ctx, response_value); + return jsc.JSPromise.resolvedPromiseValue(ctx, response_value); } - pub fn stopFromJS(this: *ThisServer, abruptly: ?JSValue) JSC.JSValue { + pub fn stopFromJS(this: *ThisServer, abruptly: ?JSValue) jsc.JSValue { const rc = this.getAllClosedPromise(this.globalThis); if (this.listener != null) { @@ -1267,7 +1266,7 @@ pub fn NewServer(protocol_enum: enum { http, https }, development_kind: enum { d return rc; } - pub fn disposeFromJS(this: *ThisServer) JSC.JSValue { + pub fn disposeFromJS(this: *ThisServer) jsc.JSValue { if (this.listener != null) { this.stop(true); } @@ -1277,30 +1276,30 @@ pub fn NewServer(protocol_enum: enum { http, https }, development_kind: enum { d pub fn getPort( this: *ThisServer, - _: *JSC.JSGlobalObject, - ) JSC.JSValue { + _: *jsc.JSGlobalObject, + ) jsc.JSValue { switch (this.config.address) { .unix => return .js_undefined, else => {}, } - var listener = this.listener orelse return JSC.JSValue.jsNumber(this.config.address.tcp.port); - return JSC.JSValue.jsNumber(listener.getLocalPort()); + var listener = this.listener orelse return jsc.JSValue.jsNumber(this.config.address.tcp.port); + return jsc.JSValue.jsNumber(listener.getLocalPort()); } - pub fn getId(this: *ThisServer, globalThis: *JSC.JSGlobalObject) bun.JSError!JSC.JSValue { + pub fn getId(this: *ThisServer, globalThis: *jsc.JSGlobalObject) bun.JSError!jsc.JSValue { return bun.String.createUTF8ForJS(globalThis, this.config.id); } - pub fn getPendingRequests(this: *ThisServer, _: *JSC.JSGlobalObject) JSC.JSValue { - return JSC.JSValue.jsNumber(@as(i32, @intCast(@as(u31, @truncate(this.pending_requests))))); + pub fn getPendingRequests(this: *ThisServer, _: *jsc.JSGlobalObject) jsc.JSValue { + return jsc.JSValue.jsNumber(@as(i32, @intCast(@as(u31, @truncate(this.pending_requests))))); } - pub fn getPendingWebSockets(this: *ThisServer, _: *JSC.JSGlobalObject) JSC.JSValue { - return JSC.JSValue.jsNumber(@as(i32, @intCast(@as(u31, @truncate(this.activeSocketsCount()))))); + pub fn getPendingWebSockets(this: *ThisServer, _: *jsc.JSGlobalObject) jsc.JSValue { + return jsc.JSValue.jsNumber(@as(i32, @intCast(@as(u31, @truncate(this.activeSocketsCount()))))); } - pub fn getAddress(this: *ThisServer, globalThis: *JSGlobalObject) JSC.JSValue { + pub fn getAddress(this: *ThisServer, globalThis: *JSGlobalObject) jsc.JSValue { switch (this.config.address) { .unix => |unix| { var value = bun.String.cloneUTF8(unix); @@ -1361,14 +1360,14 @@ pub fn NewServer(protocol_enum: enum { http, https }, development_kind: enum { d return bun.String.cloneUTF8(buf); } - pub fn getURL(this: *ThisServer, globalThis: *JSGlobalObject) bun.OOM!JSC.JSValue { + pub fn getURL(this: *ThisServer, globalThis: *JSGlobalObject) bun.OOM!jsc.JSValue { var url = try this.getURLAsString(); defer url.deref(); return url.toJSDOMURL(globalThis); } - pub fn getHostname(this: *ThisServer, globalThis: *JSGlobalObject) JSC.JSValue { + pub fn getHostname(this: *ThisServer, globalThis: *JSGlobalObject) jsc.JSValue { switch (this.config.address) { .unix => return .js_undefined, else => {}, @@ -1402,16 +1401,16 @@ pub fn NewServer(protocol_enum: enum { http, https }, development_kind: enum { d return this.cached_hostname.toJS(globalThis); } - pub fn getProtocol(this: *ThisServer, globalThis: *JSGlobalObject) JSC.JSValue { + pub fn getProtocol(this: *ThisServer, globalThis: *JSGlobalObject) jsc.JSValue { _ = this; return bun.String.static(if (ssl_enabled) "https" else "http").toJS(globalThis); } pub fn getDevelopment( _: *ThisServer, - _: *JSC.JSGlobalObject, - ) JSC.JSValue { - return JSC.JSValue.jsBoolean(debug_mode); + _: *jsc.JSGlobalObject, + ) jsc.JSValue { + return jsc.JSValue.jsBoolean(debug_mode); } pub fn onStaticRequestComplete(this: *ThisServer) void { @@ -1441,15 +1440,15 @@ pub fn NewServer(protocol_enum: enum { http, https }, development_kind: enum { d return this.activeSocketsCount() > 0; } - pub fn getAllClosedPromise(this: *ThisServer, globalThis: *JSC.JSGlobalObject) JSC.JSValue { + pub fn getAllClosedPromise(this: *ThisServer, globalThis: *jsc.JSGlobalObject) jsc.JSValue { if (this.listener == null and this.pending_requests == 0) { - return JSC.JSPromise.resolvedPromise(globalThis, .js_undefined).toJS(); + return jsc.JSPromise.resolvedPromise(globalThis, .js_undefined).toJS(); } const prom = &this.all_closed_promise; if (prom.strong.has()) { return prom.value(); } - prom.* = JSC.JSPromise.Strong.init(globalThis); + prom.* = jsc.JSPromise.Strong.init(globalThis); return prom.value(); } @@ -1485,9 +1484,9 @@ pub fn NewServer(protocol_enum: enum { http, https }, development_kind: enum { d .promise = .{ .strong = .create(this.all_closed_promise.value(), this.globalThis), }, - .tracker = JSC.Debugger.AsyncTaskTracker.init(vm), + .tracker = jsc.Debugger.AsyncTaskTracker.init(vm), }); - event_loop.enqueueTask(JSC.Task.init(task)); + event_loop.enqueueTask(jsc.Task.init(task)); } if (this.pending_requests == 0 and this.listener == null and @@ -1565,14 +1564,14 @@ pub fn NewServer(protocol_enum: enum { http, https }, development_kind: enum { d // scheduleDeinit can be called inside a finalizer. // Therefore, we split it into two tasks. this.flags.terminated = true; - const task = bun.default_allocator.create(JSC.AnyTask) catch unreachable; - task.* = JSC.AnyTask.New(App, App.close).init(this.app.?); - this.vm.enqueueTask(JSC.Task.init(task)); + const task = bun.default_allocator.create(jsc.AnyTask) catch unreachable; + task.* = jsc.AnyTask.New(App, App.close).init(this.app.?); + this.vm.enqueueTask(jsc.Task.init(task)); } - const task = bun.default_allocator.create(JSC.AnyTask) catch unreachable; - task.* = JSC.AnyTask.New(ThisServer, deinit).init(this); - this.vm.enqueueTask(JSC.Task.init(task)); + const task = bun.default_allocator.create(jsc.AnyTask) catch unreachable; + task.* = jsc.AnyTask.New(ThisServer, deinit).init(this); + this.vm.enqueueTask(jsc.Task.init(task)); } fn notifyInspectorServerStopped(this: *ThisServer) void { @@ -1642,7 +1641,7 @@ pub fn NewServer(protocol_enum: enum { http, https }, development_kind: enum { d .globalThis = global, .config = config.*, .base_url_string_for_joining = base_url, - .vm = JSC.VirtualMachine.get(), + .vm = jsc.VirtualMachine.get(), .allocator = Arena.getThreadlocalDefault(), .dev_server = dev_server, }); @@ -1658,9 +1657,9 @@ pub fn NewServer(protocol_enum: enum { http, https }, development_kind: enum { d server.request_pool_allocator = RequestContext.pool.?; if (comptime ssl_enabled) { - Analytics.Features.https_server += 1; + analytics.Features.https_server += 1; } else { - Analytics.Features.http_server += 1; + analytics.Features.http_server += 1; } return server; @@ -1671,7 +1670,7 @@ pub fn NewServer(protocol_enum: enum { http, https }, development_kind: enum { d const globalThis = this.globalThis; - var error_instance = JSC.JSValue.zero; + var error_instance = jsc.JSValue.zero; var output_buf: [4096]u8 = undefined; if (comptime ssl_enabled) { @@ -1735,7 +1734,7 @@ pub fn NewServer(protocol_enum: enum { http, https }, development_kind: enum { d const rc: i32 = -1; const code = Sys.getErrno(rc); if (code == bun.sys.E.ACCES) { - error_instance = (JSC.SystemError{ + error_instance = (jsc.SystemError{ .message = bun.String.init(std.fmt.bufPrint(&output_buf, "permission denied {s}:{d}", .{ tcp.hostname orelse "0.0.0.0", tcp.port }) catch "Failed to start server"), .code = bun.String.static("EACCES"), .syscall = bun.String.static("listen"), @@ -1743,7 +1742,7 @@ pub fn NewServer(protocol_enum: enum { http, https }, development_kind: enum { d break :error_set; } } - error_instance = (JSC.SystemError{ + error_instance = (jsc.SystemError{ .message = bun.String.init(std.fmt.bufPrint(&output_buf, "Failed to start server. Is port {d} in use?", .{tcp.port}) catch "Failed to start server"), .code = bun.String.static("EADDRINUSE"), .syscall = bun.String.static("listen"), @@ -1753,7 +1752,7 @@ pub fn NewServer(protocol_enum: enum { http, https }, development_kind: enum { d .unix => |unix| { switch (bun.sys.getErrno(@as(i32, -1))) { .SUCCESS => { - error_instance = (JSC.SystemError{ + error_instance = (jsc.SystemError{ .message = bun.String.init(std.fmt.bufPrint(&output_buf, "Failed to listen on unix socket {}", .{bun.fmt.QuotedFormatter{ .text = unix }}) catch "Failed to start server"), .code = bun.String.static("EADDRINUSE"), .syscall = bun.String.static("listen"), @@ -1796,14 +1795,14 @@ pub fn NewServer(protocol_enum: enum { http, https }, development_kind: enum { d this.poll_ref.unref(this.vm); } - pub fn doRef(this: *ThisServer, _: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { + pub fn doRef(this: *ThisServer, _: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const this_value = callframe.this(); this.ref(); return this_value; } - pub fn doUnref(this: *ThisServer, _: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { + pub fn doUnref(this: *ThisServer, _: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const this_value = callframe.this(); this.unref(); @@ -1811,7 +1810,7 @@ pub fn NewServer(protocol_enum: enum { http, https }, development_kind: enum { d } pub fn onBunInfoRequest(this: *ThisServer, req: *uws.Request, resp: *App.Response) void { - JSC.markBinding(@src()); + jsc.markBinding(@src()); this.pending_requests += 1; defer this.pending_requests -= 1; req.setYield(false); @@ -1825,7 +1824,7 @@ pub fn NewServer(protocol_enum: enum { http, https }, development_kind: enum { d _ = js_printer.printJSON( *js_printer.BufferPrinter, &writer, - bun.Global.BunInfo.generate(*Transpiler, &JSC.VirtualMachine.get().transpiler, allocator) catch unreachable, + bun.Global.BunInfo.generate(*Transpiler, &jsc.VirtualMachine.get().transpiler, allocator) catch unreachable, source, .{ .mangled_props = null }, ) catch unreachable; @@ -1885,12 +1884,12 @@ pub fn NewServer(protocol_enum: enum { http, https }, development_kind: enum { d }) catch globalThis.takeException(error.JSError); const HTTPResult = union(enum) { - rejection: JSC.JSValue, - exception: JSC.JSValue, + rejection: jsc.JSValue, + exception: jsc.JSValue, success: void, - pending: JSC.JSValue, + pending: jsc.JSValue, }; - var strong_promise: JSC.Strong.Optional = .empty; + var strong_promise: jsc.Strong.Optional = .empty; var needs_to_drain = true; defer { @@ -1987,7 +1986,7 @@ pub fn NewServer(protocol_enum: enum { http, https }, development_kind: enum { d req: *uws.Request, resp: *App.Response, ) void { - JSC.markBinding(@src()); + jsc.markBinding(@src()); onNodeHTTPRequestWithUpgradeCtx(this, req, resp, null); } @@ -2003,7 +2002,7 @@ pub fn NewServer(protocol_enum: enum { http, https }, development_kind: enum { d var did_send_idletimeout_warning_once = false; fn onTimeoutForIdleWarn(_: *anyopaque, _: *App.Response) void { if (debug_mode and !did_send_idletimeout_warning_once) { - if (!bun.CLI.Command.get().debug.silent) { + if (!bun.cli.Command.get().debug.silent) { did_send_idletimeout_warning_once = true; Output.prettyErrorln("[Bun.serve]: request timed out after 10 seconds. Pass `idleTimeout` to configure.", .{}); Output.flush(); @@ -2013,7 +2012,7 @@ pub fn NewServer(protocol_enum: enum { http, https }, development_kind: enum { d fn shouldAddTimeoutHandlerForWarning(server: *ThisServer) bool { if (comptime debug_mode) { - if (!did_send_idletimeout_warning_once and !bun.CLI.Command.get().debug.silent) { + if (!did_send_idletimeout_warning_once and !bun.cli.Command.get().debug.silent) { return !server.config.has_idleTimeout; } } @@ -2037,7 +2036,7 @@ pub fn NewServer(protocol_enum: enum { http, https }, development_kind: enum { d server.handleRequest(&should_deinit_context, prepared, req, response_value); } - fn handleRequest(this: *ThisServer, should_deinit_context: *bool, prepared: PreparedRequest, req: *uws.Request, response_value: JSC.JSValue) void { + fn handleRequest(this: *ThisServer, should_deinit_context: *bool, prepared: PreparedRequest, req: *uws.Request, response_value: jsc.JSValue) void { const ctx = prepared.ctx; defer { @@ -2154,7 +2153,7 @@ pub fn NewServer(protocol_enum: enum { http, https }, development_kind: enum { d /// to until the bundle is actually ready. pub fn save( prepared: PreparedRequest, - global: *JSC.JSGlobalObject, + global: *jsc.JSGlobalObject, req: *uws.Request, resp: *App.Response, ) SavedRequest { @@ -2173,7 +2172,7 @@ pub fn NewServer(protocol_enum: enum { http, https }, development_kind: enum { d }; pub fn prepareJsRequestContext(this: *ThisServer, req: *uws.Request, resp: *App.Response, should_deinit_context: ?*bool, create_js_request: bool, method: ?bun.http.Method) ?PreparedRequest { - JSC.markBinding(@src()); + jsc.markBinding(@src()); this.onPendingRequest(); if (comptime Environment.isDebug) { this.vm.eventLoop().debug.enter(); @@ -2195,11 +2194,11 @@ pub fn NewServer(protocol_enum: enum { http, https }, development_kind: enum { d const ctx = this.request_pool_allocator.tryGet() catch bun.outOfMemory(); ctx.create(this, req, resp, should_deinit_context, method); - this.vm.jsc.reportExtraMemory(@sizeOf(RequestContext)); + this.vm.jsc_vm.reportExtraMemory(@sizeOf(RequestContext)); const body = this.vm.initRequestBodyValue(.{ .Null = {} }) catch unreachable; ctx.request_body = body; - var signal = JSC.WebCore.AbortSignal.new(this.globalThis); + var signal = jsc.WebCore.AbortSignal.new(this.globalThis); ctx.signal = signal; signal.pendingActivityRef(); @@ -2291,7 +2290,7 @@ pub fn NewServer(protocol_enum: enum { http, https }, development_kind: enum { d upgrade_ctx: *uws.SocketContext, id: usize, ) void { - JSC.markBinding(@src()); + jsc.markBinding(@src()); if (id == 1) { // This is actually a UserRoute if id is 1 so it's safe to cast upgradeWebSocketUserRoute(@ptrCast(this), resp, req, upgrade_ctx, null); @@ -2318,7 +2317,7 @@ pub fn NewServer(protocol_enum: enum { http, https }, development_kind: enum { d var body = this.vm.initRequestBodyValue(.{ .Null = {} }) catch unreachable; ctx.request_body = body; - var signal = JSC.WebCore.AbortSignal.new(this.globalThis); + var signal = jsc.WebCore.AbortSignal.new(this.globalThis); ctx.signal = signal; var request_object = Request.new(.{ @@ -2331,7 +2330,7 @@ pub fn NewServer(protocol_enum: enum { http, https }, development_kind: enum { d ctx.upgrade_context = upgrade_ctx; ctx.request_weakref = .initRef(request_object); // We keep the Request object alive for the duration of the request so that we can remove the pointer to the UWS request object. - var args = [_]JSC.JSValue{ + var args = [_]jsc.JSValue{ request_object.toJS(this.globalThis), this.jsValueAssertAlive(), }; @@ -2403,7 +2402,7 @@ pub fn NewServer(protocol_enum: enum { http, https }, development_kind: enum { d const first_hash_segment: [8]u8 = brk: { const buffer = bun.path_buffer_pool.get(); defer bun.path_buffer_pool.put(buffer); - const main = JSC.VirtualMachine.get().main; + const main = jsc.VirtualMachine.get().main; const len = @min(main.len, buffer.len); break :brk @bitCast(bun.hash(bun.strings.copyLowercase(main[0..len], buffer[0..len]))); }; @@ -2438,8 +2437,8 @@ pub fn NewServer(protocol_enum: enum { http, https }, development_kind: enum { d resp.end(json_string, resp.shouldCloseConnection()); } - fn setRoutes(this: *ThisServer) JSC.JSValue { - var route_list_value = JSC.JSValue.zero; + fn setRoutes(this: *ThisServer) jsc.JSValue { + var route_list_value = jsc.JSValue.zero; const app = this.app.?; const any_server = AnyServer.from(this); const dev_server = this.dev_server; @@ -2462,7 +2461,7 @@ pub fn NewServer(protocol_enum: enum { http, https }, development_kind: enum { d this.user_routes = std.ArrayListUnmanaged(UserRoute).initCapacity(bun.default_allocator, user_routes_to_build_list.items.len) catch @panic("OOM"); const paths_zig = bun.default_allocator.alloc(ZigString, user_routes_to_build_list.items.len) catch @panic("OOM"); defer bun.default_allocator.free(paths_zig); - const callbacks_js = bun.default_allocator.alloc(JSC.JSValue, user_routes_to_build_list.items.len) catch @panic("OOM"); + const callbacks_js = bun.default_allocator.alloc(jsc.JSValue, user_routes_to_build_list.items.len) catch @panic("OOM"); defer bun.default_allocator.free(callbacks_js); for (user_routes_to_build_list.items, paths_zig, callbacks_js, 0..) |*builder, *p_zig, *cb_js, i| { @@ -2608,7 +2607,7 @@ pub fn NewServer(protocol_enum: enum { http, https }, development_kind: enum { d if (debug_mode) { app.get("/bun:info", *ThisServer, this, onBunInfoRequest); if (this.config.inspector) { - JSC.markBinding(@src()); + jsc.markBinding(@src()); Bun__addInspector(ssl_enabled, app, this.globalThis); } } @@ -2689,11 +2688,11 @@ pub fn NewServer(protocol_enum: enum { http, https }, development_kind: enum { d } // TODO: make this return JSError!void, and do not deinitialize on synchronous failure, to allow errdefer in caller scope - pub fn listen(this: *ThisServer) JSC.JSValue { + pub fn listen(this: *ThisServer) jsc.JSValue { httplog("listen", .{}); var app: *App = undefined; const globalThis = this.globalThis; - var route_list_value = JSC.JSValue.zero; + var route_list_value = jsc.JSValue.zero; if (ssl_enabled) { bun.BoringSSL.load(); const ssl_config = this.config.ssl_config orelse @panic("Assertion failure: ssl_config"); @@ -2848,7 +2847,7 @@ pub fn NewServer(protocol_enum: enum { http, https }, development_kind: enum { d if (node_socket.isUndefinedOrNull()) return; const error_code_value = JSValue.jsNumber(error_code); - const raw_packet_value = JSC.ArrayBuffer.createBuffer(this.globalThis, raw_packet) catch return; // TODO: properly propagate exception upwards + const raw_packet_value = jsc.ArrayBuffer.createBuffer(this.globalThis, raw_packet) catch return; // TODO: properly propagate exception upwards const loop = this.globalThis.bunVM().eventLoop(); loop.enter(); defer loop.exit(); @@ -2864,7 +2863,7 @@ pub const AnyRequestContext = @import("./server/AnyRequestContext.zig"); pub const NewRequestContext = @import("./server/RequestContext.zig").NewRequestContext; pub const SavedRequest = struct { - js_request: JSC.Strong.Optional, + js_request: jsc.Strong.Optional, request: *Request, ctx: AnyRequestContext, response: uws.AnyResponse, @@ -2876,18 +2875,18 @@ pub const SavedRequest = struct { pub const Union = union(enum) { stack: *uws.Request, - saved: bun.JSC.API.SavedRequest, + saved: bun.jsc.API.SavedRequest, }; }; pub const ServerAllConnectionsClosedTask = struct { - globalObject: *JSC.JSGlobalObject, - promise: JSC.JSPromise.Strong, - tracker: JSC.Debugger.AsyncTaskTracker, + globalObject: *jsc.JSGlobalObject, + promise: jsc.JSPromise.Strong, + tracker: jsc.Debugger.AsyncTaskTracker, pub const new = bun.TrivialNew(@This()); - pub fn runFromJSThread(this: *ServerAllConnectionsClosedTask, vm: *JSC.VirtualMachine) void { + pub fn runFromJSThread(this: *ServerAllConnectionsClosedTask, vm: *jsc.VirtualMachine) void { httplog("ServerAllConnectionsClosedTask runFromJSThread", .{}); const globalObject = this.globalObject; @@ -2945,7 +2944,7 @@ pub const AnyServer = struct { else => bun.unreachablePanic("Invalid pointer tag", .{}), }; } - pub fn vm(this: AnyServer) *JSC.VirtualMachine { + pub fn vm(this: AnyServer) *jsc.VirtualMachine { return switch (this.ptr.tag()) { Ptr.case(HTTPServer) => this.ptr.as(HTTPServer).vm, Ptr.case(HTTPSServer) => this.ptr.as(HTTPSServer).vm, @@ -2954,7 +2953,7 @@ pub const AnyServer = struct { else => bun.unreachablePanic("Invalid pointer tag", .{}), }; } - pub fn setInspectorServerID(this: AnyServer, id: JSC.Debugger.DebuggerId) void { + pub fn setInspectorServerID(this: AnyServer, id: jsc.Debugger.DebuggerId) void { switch (this.ptr.tag()) { Ptr.case(HTTPServer) => { this.ptr.as(HTTPServer).inspector_server_id = id; @@ -2984,7 +2983,7 @@ pub const AnyServer = struct { } } - pub fn inspectorServerID(this: AnyServer) JSC.Debugger.DebuggerId { + pub fn inspectorServerID(this: AnyServer) jsc.Debugger.DebuggerId { return switch (this.ptr.tag()) { Ptr.case(HTTPServer) => this.ptr.as(HTTPServer).inspector_server_id, Ptr.case(HTTPSServer) => this.ptr.as(HTTPSServer).inspector_server_id, @@ -3058,7 +3057,7 @@ pub const AnyServer = struct { }; } - pub fn globalThis(this: AnyServer) *JSC.JSGlobalObject { + pub fn globalThis(this: AnyServer) *jsc.JSGlobalObject { return switch (this.ptr.tag()) { Ptr.case(HTTPServer) => this.ptr.as(HTTPServer).globalThis, Ptr.case(HTTPSServer) => this.ptr.as(HTTPSServer).globalThis, @@ -3152,7 +3151,7 @@ pub const AnyServer = struct { this: AnyServer, req: SavedRequest.Union, resp: uws.AnyResponse, - callback: JSC.JSValue, + callback: jsc.JSValue, comptime extra_arg_count: usize, extra_args: [extra_arg_count]JSValue, ) void { @@ -3169,7 +3168,7 @@ pub const AnyServer = struct { server: AnyServer, req: *uws.Request, resp: uws.AnyResponse, - global: *JSC.JSGlobalObject, + global: *jsc.JSGlobalObject, method: ?bun.http.Method, ) ?SavedRequest { return switch (server.ptr.tag()) { @@ -3201,9 +3200,9 @@ pub const AnyServer = struct { } }; -extern fn Bun__addInspector(bool, *anyopaque, *JSC.JSGlobalObject) void; +extern fn Bun__addInspector(bool, *anyopaque, *jsc.JSGlobalObject) void; -pub export fn Server__setIdleTimeout(server: JSC.JSValue, seconds: JSC.JSValue, globalThis: *JSC.JSGlobalObject) void { +pub export fn Server__setIdleTimeout(server: jsc.JSValue, seconds: jsc.JSValue, globalThis: *jsc.JSGlobalObject) void { Server__setIdleTimeout_(server, seconds, globalThis) catch |err| switch (err) { error.JSError => {}, error.OutOfMemory => { @@ -3212,7 +3211,7 @@ pub export fn Server__setIdleTimeout(server: JSC.JSValue, seconds: JSC.JSValue, }; } -pub fn Server__setIdleTimeout_(server: JSC.JSValue, seconds: JSC.JSValue, globalThis: *JSC.JSGlobalObject) bun.JSError!void { +pub fn Server__setIdleTimeout_(server: jsc.JSValue, seconds: jsc.JSValue, globalThis: *jsc.JSGlobalObject) bun.JSError!void { if (!server.isObject()) { return globalThis.throw("Failed to set timeout: The 'this' value is not a Server.", .{}); } @@ -3234,7 +3233,7 @@ pub fn Server__setIdleTimeout_(server: JSC.JSValue, seconds: JSC.JSValue, global } } -pub fn Server__setOnClientError_(globalThis: *JSC.JSGlobalObject, server: JSC.JSValue, callback: JSC.JSValue) bun.JSError!JSC.JSValue { +pub fn Server__setOnClientError_(globalThis: *jsc.JSGlobalObject, server: jsc.JSValue, callback: jsc.JSValue) bun.JSError!jsc.JSValue { if (!server.isObject()) { return globalThis.throw("Failed to set clientError: The 'this' value is not a Server.", .{}); } @@ -3246,25 +3245,25 @@ pub fn Server__setOnClientError_(globalThis: *JSC.JSGlobalObject, server: JSC.JS if (server.as(HTTPServer)) |this| { if (this.app) |app| { this.on_clienterror.deinit(); - this.on_clienterror = JSC.Strong.Optional.create(callback, globalThis); + this.on_clienterror = jsc.Strong.Optional.create(callback, globalThis); app.onClientError(*HTTPServer, this, HTTPServer.onClientErrorCallback); } } else if (server.as(HTTPSServer)) |this| { if (this.app) |app| { this.on_clienterror.deinit(); - this.on_clienterror = JSC.Strong.Optional.create(callback, globalThis); + this.on_clienterror = jsc.Strong.Optional.create(callback, globalThis); app.onClientError(*HTTPSServer, this, HTTPSServer.onClientErrorCallback); } } else if (server.as(DebugHTTPServer)) |this| { if (this.app) |app| { this.on_clienterror.deinit(); - this.on_clienterror = JSC.Strong.Optional.create(callback, globalThis); + this.on_clienterror = jsc.Strong.Optional.create(callback, globalThis); app.onClientError(*DebugHTTPServer, this, DebugHTTPServer.onClientErrorCallback); } } else if (server.as(DebugHTTPSServer)) |this| { if (this.app) |app| { this.on_clienterror.deinit(); - this.on_clienterror = JSC.Strong.Optional.create(callback, globalThis); + this.on_clienterror = jsc.Strong.Optional.create(callback, globalThis); app.onClientError(*DebugHTTPSServer, this, DebugHTTPSServer.onClientErrorCallback); } } else { @@ -3273,7 +3272,7 @@ pub fn Server__setOnClientError_(globalThis: *JSC.JSGlobalObject, server: JSC.JS return .js_undefined; } -pub fn Server__setAppFlags_(globalThis: *JSC.JSGlobalObject, server: JSC.JSValue, require_host_header: bool, use_strict_method_validation: bool) bun.JSError!JSC.JSValue { +pub fn Server__setAppFlags_(globalThis: *jsc.JSGlobalObject, server: jsc.JSValue, require_host_header: bool, use_strict_method_validation: bool) bun.JSError!jsc.JSValue { if (!server.isObject()) { return globalThis.throw("Failed to set requireHostHeader: The 'this' value is not a Server.", .{}); } @@ -3292,7 +3291,7 @@ pub fn Server__setAppFlags_(globalThis: *JSC.JSGlobalObject, server: JSC.JSValue return .js_undefined; } -pub fn Server__setMaxHTTPHeaderSize_(globalThis: *JSC.JSGlobalObject, server: JSC.JSValue, max_header_size: u64) bun.JSError!JSC.JSValue { +pub fn Server__setMaxHTTPHeaderSize_(globalThis: *jsc.JSGlobalObject, server: jsc.JSValue, max_header_size: u64) bun.JSError!jsc.JSValue { if (!server.isObject()) { return globalThis.throw("Failed to set maxHeaderSize: The 'this' value is not a Server.", .{}); } @@ -3313,72 +3312,71 @@ pub fn Server__setMaxHTTPHeaderSize_(globalThis: *JSC.JSGlobalObject, server: JS comptime { _ = Server__setIdleTimeout; _ = NodeHTTPResponse.create; - @export(&JSC.host_fn.wrap4(Server__setAppFlags_), .{ .name = "Server__setAppFlags" }); - @export(&JSC.host_fn.wrap3(Server__setOnClientError_), .{ .name = "Server__setOnClientError" }); - @export(&JSC.host_fn.wrap3(Server__setMaxHTTPHeaderSize_), .{ .name = "Server__setMaxHTTPHeaderSize" }); + @export(&jsc.host_fn.wrap4(Server__setAppFlags_), .{ .name = "Server__setAppFlags" }); + @export(&jsc.host_fn.wrap3(Server__setOnClientError_), .{ .name = "Server__setOnClientError" }); + @export(&jsc.host_fn.wrap3(Server__setMaxHTTPHeaderSize_), .{ .name = "Server__setMaxHTTPHeaderSize" }); } extern fn NodeHTTPServer__onRequest_http( any_server: usize, - globalThis: *JSC.JSGlobalObject, - this: JSC.JSValue, - callback: JSC.JSValue, - methodString: JSC.JSValue, + globalThis: *jsc.JSGlobalObject, + this: jsc.JSValue, + callback: jsc.JSValue, + methodString: jsc.JSValue, request: *uws.Request, response: *uws.NewApp(false).Response, upgrade_ctx: ?*uws.SocketContext, node_response_ptr: *?*NodeHTTPResponse, -) JSC.JSValue; +) jsc.JSValue; extern fn NodeHTTPServer__onRequest_https( any_server: usize, - globalThis: *JSC.JSGlobalObject, - this: JSC.JSValue, - callback: JSC.JSValue, - methodString: JSC.JSValue, + globalThis: *jsc.JSGlobalObject, + this: jsc.JSValue, + callback: jsc.JSValue, + methodString: jsc.JSValue, request: *uws.Request, response: *uws.NewApp(true).Response, upgrade_ctx: ?*uws.SocketContext, node_response_ptr: *?*NodeHTTPResponse, -) JSC.JSValue; +) jsc.JSValue; -extern fn Bun__createNodeHTTPServerSocket(bool, *anyopaque, *JSC.JSGlobalObject) JSC.JSValue; +extern fn Bun__createNodeHTTPServerSocket(bool, *anyopaque, *jsc.JSGlobalObject) jsc.JSValue; extern fn NodeHTTP_assignOnCloseFunction(bool, *anyopaque) void; extern fn NodeHTTP_setUsingCustomExpectHandler(bool, *anyopaque, bool) void; extern "c" fn Bun__ServerRouteList__callRoute( - globalObject: *JSC.JSGlobalObject, + globalObject: *jsc.JSGlobalObject, index: u32, requestPtr: *Request, - serverObject: JSC.JSValue, - routeListObject: JSC.JSValue, - requestObject: *JSC.JSValue, + serverObject: jsc.JSValue, + routeListObject: jsc.JSValue, + requestObject: *jsc.JSValue, req: *uws.Request, -) JSC.JSValue; +) jsc.JSValue; extern "c" fn Bun__ServerRouteList__create( - globalObject: *JSC.JSGlobalObject, - callbacks: [*]JSC.JSValue, + globalObject: *jsc.JSGlobalObject, + callbacks: [*]jsc.JSValue, paths: [*]ZigString, pathsLength: usize, -) JSC.JSValue; +) jsc.JSValue; -fn throwSSLErrorIfNecessary(globalThis: *JSC.JSGlobalObject) bool { +fn throwSSLErrorIfNecessary(globalThis: *jsc.JSGlobalObject) bool { const err_code = BoringSSL.ERR_get_error(); if (err_code != 0) { defer BoringSSL.ERR_clear_error(); - globalThis.throwValue(JSC.API.Bun.Crypto.createCryptoError(globalThis, err_code)) catch {}; + globalThis.throwValue(jsc.API.Bun.Crypto.createCryptoError(globalThis, err_code)) catch {}; return true; } return false; } -const Analytics = @import("../../analytics/analytics_thread.zig"); +const string = []const u8; + const Sys = @import("../../sys.zig"); const options = @import("../../options.zig"); const std = @import("std"); -const Arena = @import("../../allocators/mimalloc_arena.zig").Arena; -const SocketAddress = @import("./bun/socket.zig").SocketAddress; const URL = @import("../../url.zig").URL; const Allocator = std.mem.Allocator; @@ -3391,32 +3389,33 @@ const Environment = bun.Environment; const Global = bun.Global; const Output = bun.Output; const Transpiler = bun.Transpiler; +const analytics = bun.analytics; const assert = bun.assert; const default_allocator = bun.default_allocator; const js_printer = bun.js_printer; const logger = bun.logger; -const string = bun.string; const strings = bun.strings; const uws = bun.uws; +const Arena = bun.allocators.MimallocArena; const BoringSSL = bun.BoringSSL.c; +const SocketAddress = bun.api.socket.SocketAddress; -const JSC = bun.JSC; -const JSGlobalObject = bun.JSC.JSGlobalObject; -const JSPromise = bun.JSC.JSPromise; -const JSValue = bun.JSC.JSValue; -const Node = bun.JSC.Node; -const VM = bun.JSC.VM; -const VirtualMachine = JSC.VirtualMachine; -const ZigString = bun.JSC.ZigString; -const host_fn = JSC.host_fn; -const HTMLBundle = JSC.API.HTMLBundle; +const HTTP = bun.http; +const MimeType = HTTP.MimeType; -const WebCore = bun.JSC.WebCore; -const Blob = JSC.WebCore.Blob; +const jsc = bun.jsc; +const JSGlobalObject = bun.jsc.JSGlobalObject; +const JSPromise = bun.jsc.JSPromise; +const JSValue = bun.jsc.JSValue; +const Node = bun.jsc.Node; +const VM = bun.jsc.VM; +const VirtualMachine = jsc.VirtualMachine; +const ZigString = bun.jsc.ZigString; +const host_fn = jsc.host_fn; + +const WebCore = bun.jsc.WebCore; +const Blob = jsc.WebCore.Blob; const Fetch = WebCore.Fetch; const Headers = WebCore.Headers; const Request = WebCore.Request; const Response = WebCore.Response; - -const HTTP = bun.http; -const MimeType = HTTP.MimeType; diff --git a/src/bun.js/api/server/AnyRequestContext.zig b/src/bun.js/api/server/AnyRequestContext.zig index 121082e96f..f79ecca8b2 100644 --- a/src/bun.js/api/server/AnyRequestContext.zig +++ b/src/bun.js/api/server/AnyRequestContext.zig @@ -67,7 +67,7 @@ pub fn setTimeout(self: AnyRequestContext, seconds: c_uint) bool { return false; } -pub fn setCookies(self: AnyRequestContext, cookie_map: ?*JSC.WebCore.CookieMap) void { +pub fn setCookies(self: AnyRequestContext, cookie_map: ?*jsc.WebCore.CookieMap) void { if (self.tagged_pointer.isNull()) { return; } @@ -221,11 +221,11 @@ pub fn deref(self: AnyRequestContext) void { } } -const DebugHTTPSServer = @import("../server.zig").DebugHTTPSServer; -const DebugHTTPServer = @import("../server.zig").DebugHTTPServer; -const HTTPSServer = @import("../server.zig").HTTPSServer; -const HTTPServer = @import("../server.zig").HTTPServer; - const bun = @import("bun"); -const JSC = bun.JSC; +const jsc = bun.jsc; const uws = bun.uws; + +const DebugHTTPSServer = bun.api.DebugHTTPSServer; +const DebugHTTPServer = bun.api.DebugHTTPServer; +const HTTPSServer = bun.api.HTTPSServer; +const HTTPServer = bun.api.HTTPServer; diff --git a/src/bun.js/api/server/FileRoute.zig b/src/bun.js/api/server/FileRoute.zig index cebbe62ea2..efbcebdff8 100644 --- a/src/bun.js/api/server/FileRoute.zig +++ b/src/bun.js/api/server/FileRoute.zig @@ -12,7 +12,7 @@ has_content_length_header: bool, pub const InitOptions = struct { server: ?AnyServer, status_code: u16 = 200, - headers: ?*JSC.WebCore.FetchHeaders = null, + headers: ?*jsc.WebCore.FetchHeaders = null, }; pub fn lastModifiedDate(this: *const FileRoute) bun.JSError!?u64 { @@ -20,7 +20,7 @@ pub fn lastModifiedDate(this: *const FileRoute) bun.JSError!?u64 { if (this.headers.get("last-modified")) |last_modified| { var string = bun.String.init(last_modified); defer string.deref(); - const date_f64 = try bun.String.parseDate(&string, bun.JSC.VirtualMachine.get().global); + const date_f64 = try bun.String.parseDate(&string, bun.jsc.VirtualMachine.get().global); if (!std.math.isNan(date_f64) and std.math.isFinite(date_f64)) { return @intFromFloat(date_f64); } @@ -57,8 +57,8 @@ pub fn memoryCost(this: *const FileRoute) usize { return @sizeOf(FileRoute) + this.headers.memoryCost() + this.blob.reported_estimated_size; } -pub fn fromJS(globalThis: *JSC.JSGlobalObject, argument: JSC.JSValue) bun.JSError!?*FileRoute { - if (argument.as(JSC.WebCore.Response)) |response| { +pub fn fromJS(globalThis: *jsc.JSGlobalObject, argument: jsc.JSValue) bun.JSError!?*FileRoute { + if (argument.as(jsc.WebCore.Response)) |response| { response.body.value.toBlobIfPossible(); if (response.body.value == .Blob and response.body.value.Blob.needsToReadFile()) { if (response.body.value.Blob.store.?.data.file.pathlike == .fd) { @@ -297,7 +297,7 @@ const StreamTransfer = struct { max_size: ?u64 = null, - eof_task: ?JSC.AnyTask = null, + eof_task: ?jsc.AnyTask = null, state: packed struct(u8) { has_ended_response: bool = false, @@ -398,8 +398,8 @@ const StreamTransfer = struct { // dont need to ref because we are already holding a ref and will be derefed in onReaderDone this.reader.pause(); // we cannot free inside onReadChunk this would be UAF so we schedule it to be done in the next event loop tick - this.eof_task = JSC.AnyTask.New(StreamTransfer, StreamTransfer.onReaderDone).init(this); - server.vm().enqueueTask(JSC.Task.init(&this.eof_task.?)); + this.eof_task = jsc.AnyTask.New(StreamTransfer, StreamTransfer.onReaderDone).init(this); + server.vm().enqueueTask(jsc.Task.init(&this.eof_task.?)); } break :brk .{ chunk, .eof }; } @@ -462,8 +462,8 @@ const StreamTransfer = struct { this.finish(); } - pub fn eventLoop(this: *StreamTransfer) JSC.EventLoopHandle { - return JSC.EventLoopHandle.init(this.route.server.?.vm().eventLoop()); + pub fn eventLoop(this: *StreamTransfer) jsc.EventLoopHandle { + return jsc.EventLoopHandle.init(this.route.server.?.vm().eventLoop()); } pub fn loop(this: *StreamTransfer) *Async.Loop { @@ -532,16 +532,16 @@ pub const ref = RefCount.ref; pub const deref = RefCount.deref; const std = @import("std"); -const writeStatus = @import("../server.zig").writeStatus; const bun = @import("bun"); const Async = bun.Async; -const JSC = bun.JSC; const Output = bun.Output; +const jsc = bun.jsc; const FileType = bun.io.FileType; const Headers = bun.http.Headers; -const AnyServer = JSC.API.AnyServer; -const Blob = JSC.WebCore.Blob; +const AnyServer = jsc.API.AnyServer; +const Blob = jsc.WebCore.Blob; +const writeStatus = bun.api.server.writeStatus; const uws = bun.uws; const AnyResponse = uws.AnyResponse; diff --git a/src/bun.js/api/server/HTMLBundle.zig b/src/bun.js/api/server/HTMLBundle.zig index 4cbd4126bd..d5929b3372 100644 --- a/src/bun.js/api/server/HTMLBundle.zig +++ b/src/bun.js/api/server/HTMLBundle.zig @@ -2,7 +2,7 @@ //! HTML file, and can be passed to the `static` option in `Bun.serve`. The build //! is done lazily (state held in HTMLBundle.Route or DevServer.RouteBundle.HTML). pub const HTMLBundle = @This(); -pub const js = JSC.Codegen.JSHTMLBundle; +pub const js = jsc.Codegen.JSHTMLBundle; pub const toJS = js.toJS; pub const fromJS = js.fromJS; pub const fromJSDirect = js.fromJSDirect; @@ -216,7 +216,7 @@ pub const Route = struct { } } - pub fn onPluginsResolved(this: *Route, plugins: ?*JSC.API.JSBundler.Plugin) !void { + pub fn onPluginsResolved(this: *Route, plugins: ?*jsc.API.JSBundler.Plugin) !void { const global = this.bundle.data.global; const server = this.server.?; const development = server.config().development; @@ -250,25 +250,25 @@ pub const Route = struct { config.target = .browser; const is_development = development.isDevelopment(); - if (bun.CLI.Command.get().args.serve_minify_identifiers) |minify_identifiers| { + if (bun.cli.Command.get().args.serve_minify_identifiers) |minify_identifiers| { config.minify.identifiers = minify_identifiers; } else if (!is_development) { config.minify.identifiers = true; } - if (bun.CLI.Command.get().args.serve_minify_whitespace) |minify_whitespace| { + if (bun.cli.Command.get().args.serve_minify_whitespace) |minify_whitespace| { config.minify.whitespace = minify_whitespace; } else if (!is_development) { config.minify.whitespace = true; } - if (bun.CLI.Command.get().args.serve_minify_syntax) |minify_syntax| { + if (bun.cli.Command.get().args.serve_minify_syntax) |minify_syntax| { config.minify.syntax = minify_syntax; } else if (!is_development) { config.minify.syntax = true; } - if (bun.CLI.Command.get().args.serve_define) |define| { + if (bun.cli.Command.get().args.serve_define) |define| { bun.assert(define.keys.len == define.values.len); try config.define.map.ensureUnusedCapacity(define.keys.len); config.define.map.unmanaged.entries.len = define.keys.len; @@ -360,7 +360,7 @@ pub const Route = struct { // Create static routes for each output file for (output_files) |*output_file| { - const blob = JSC.WebCore.Blob.Any{ .Blob = output_file.toBlob(bun.default_allocator, globalThis) catch bun.outOfMemory() }; + const blob = jsc.WebCore.Blob.Any{ .Blob = output_file.toBlob(bun.default_allocator, globalThis) catch bun.outOfMemory() }; var headers = bun.http.Headers{ .allocator = bun.default_allocator }; const content_type = blob.Blob.contentTypeOrMimeType() orelse brk: { bun.debugAssert(false); // should be populated by `output_file.toBlob` @@ -513,12 +513,12 @@ const bun = @import("bun"); const strings = bun.strings; const RefPtr = bun.ptr.RefPtr; -const JSC = bun.JSC; -const JSGlobalObject = JSC.JSGlobalObject; -const JSValue = JSC.JSValue; +const jsc = bun.jsc; +const JSGlobalObject = jsc.JSGlobalObject; +const JSValue = jsc.JSValue; -const AnyServer = JSC.API.AnyServer; -const JSBundler = JSC.API.JSBundler; +const AnyServer = jsc.API.AnyServer; +const JSBundler = jsc.API.JSBundler; const uws = bun.uws; const HTTPResponse = bun.uws.AnyResponse; diff --git a/src/bun.js/api/server/InspectorBunFrontendDevServerAgent.zig b/src/bun.js/api/server/InspectorBunFrontendDevServerAgent.zig index 2d96530767..7410adc331 100644 --- a/src/bun.js/api/server/InspectorBunFrontendDevServerAgent.zig +++ b/src/bun.js/api/server/InspectorBunFrontendDevServerAgent.zig @@ -105,13 +105,13 @@ pub const BunFrontendDevServerAgent = struct { } export fn Bun__InspectorBunFrontendDevServerAgent__setEnabled(agent: ?*InspectorBunFrontendDevServerAgentHandle) void { - if (JSC.VirtualMachine.get().debugger) |*debugger| { + if (jsc.VirtualMachine.get().debugger) |*debugger| { debugger.frontend_dev_server_agent.handle = agent; } } }; const bun = @import("bun"); -const JSC = bun.JSC; +const jsc = bun.jsc; const DevServer = bun.bake.DevServer; -const DebuggerId = JSC.Debugger.DebuggerId; +const DebuggerId = jsc.Debugger.DebuggerId; diff --git a/src/bun.js/api/server/NodeHTTPResponse.zig b/src/bun.js/api/server/NodeHTTPResponse.zig index ee95808b94..6d288d7752 100644 --- a/src/bun.js/api/server/NodeHTTPResponse.zig +++ b/src/bun.js/api/server/NodeHTTPResponse.zig @@ -2,7 +2,7 @@ const NodeHTTPResponse = @This(); const log = bun.Output.scoped(.NodeHTTPResponse, false); -pub const js = JSC.Codegen.JSNodeHTTPResponse; +pub const js = jsc.Codegen.JSNodeHTTPResponse; pub const toJS = js.toJS; pub const fromJS = js.fromJS; pub const fromJSDirect = js.fromJSDirect; @@ -17,11 +17,11 @@ raw_response: uws.AnyResponse, flags: Flags = .{}, -js_ref: JSC.Ref = .{}, +js_ref: jsc.Ref = .{}, body_read_state: BodyReadState = .none, -body_read_ref: JSC.Ref = .{}, -promise: JSC.Strong.Optional = .empty, +body_read_ref: jsc.Ref = .{}, +promise: jsc.Strong.Optional = .empty, server: AnyServer, /// When you call pause() on the node:http IncomingMessage @@ -93,8 +93,8 @@ pub const BodyReadState = enum(u8) { done = 2, }; -extern "C" fn Bun__getNodeHTTPResponseThisValue(bool, *anyopaque) JSC.JSValue; -pub fn getThisValue(this: *NodeHTTPResponse) JSC.JSValue { +extern "C" fn Bun__getNodeHTTPResponseThisValue(bool, *anyopaque) jsc.JSValue; +pub fn getThisValue(this: *NodeHTTPResponse) jsc.JSValue { if (this.flags.socket_closed) { return .zero; } @@ -102,8 +102,8 @@ pub fn getThisValue(this: *NodeHTTPResponse) JSC.JSValue { return Bun__getNodeHTTPResponseThisValue(this.raw_response == .SSL, this.raw_response.socket()); } -extern "C" fn Bun__getNodeHTTPServerSocketThisValue(bool, *anyopaque) JSC.JSValue; -pub fn getServerSocketValue(this: *NodeHTTPResponse) JSC.JSValue { +extern "C" fn Bun__getNodeHTTPServerSocketThisValue(bool, *anyopaque) jsc.JSValue; +pub fn getServerSocketValue(this: *NodeHTTPResponse) jsc.JSValue { if (this.flags.socket_closed) { return .zero; } @@ -145,7 +145,7 @@ pub fn upgrade(this: *NodeHTTPResponse, data_value: JSValue, sec_websocket_proto this.flags.upgraded = true; Bun__setNodeHTTPServerSocketUsSocketValue(socketValue, socket); ServerWebSocket.js.socketSetCached(ws.getThisValue(), ws_handler.globalObject, socketValue); - defer this.js_ref.unref(JSC.VirtualMachine.get()); + defer this.js_ref.unref(jsc.VirtualMachine.get()); switch (this.raw_response) { .SSL => this.raw_response = uws.AnyResponse.init(uws.NewApp(true).Response.castRes(@alignCast(@ptrCast(socket)))), .TCP => this.raw_response = uws.AnyResponse.init(uws.NewApp(false).Response.castRes(@alignCast(@ptrCast(socket)))), @@ -222,7 +222,7 @@ pub fn upgrade(this: *NodeHTTPResponse, data_value: JSValue, sec_websocket_proto ); return true; } -pub fn maybeStopReadingBody(this: *NodeHTTPResponse, vm: *JSC.VirtualMachine, thisValue: JSC.JSValue) void { +pub fn maybeStopReadingBody(this: *NodeHTTPResponse, vm: *jsc.VirtualMachine, thisValue: jsc.JSValue) void { this.upgrade_context.deinit(); // we can discard the upgrade context now if ((this.flags.socket_closed or this.flags.ended) and @@ -252,7 +252,7 @@ pub fn shouldRequestBePending(this: *const NodeHTTPResponse) bool { return true; } -pub fn dumpRequestBody(this: *NodeHTTPResponse, globalObject: *JSC.JSGlobalObject, _: *JSC.CallFrame, thisValue: JSC.JSValue) bun.JSError!JSC.JSValue { +pub fn dumpRequestBody(this: *NodeHTTPResponse, globalObject: *jsc.JSGlobalObject, _: *jsc.CallFrame, thisValue: jsc.JSValue) bun.JSError!jsc.JSValue { if (this.buffered_request_body_data_during_pause.cap > 0) { this.buffered_request_body_data_during_pause.deinitWithAllocator(bun.default_allocator); } @@ -267,12 +267,12 @@ fn markRequestAsDone(this: *NodeHTTPResponse) void { log("markRequestAsDone()", .{}); this.flags.is_request_pending = false; - this.clearOnDataCallback(this.getThisValue(), JSC.VirtualMachine.get().global); + this.clearOnDataCallback(this.getThisValue(), jsc.VirtualMachine.get().global); this.upgrade_context.deinit(); this.buffered_request_body_data_during_pause.deinitWithAllocator(bun.default_allocator); const server = this.server; - this.js_ref.unref(JSC.VirtualMachine.get()); + this.js_ref.unref(jsc.VirtualMachine.get()); this.deref(); server.onRequestComplete(); } @@ -285,14 +285,14 @@ fn markRequestAsDoneIfNecessary(this: *NodeHTTPResponse) void { pub fn create( any_server_tag: u64, - globalObject: *JSC.JSGlobalObject, + globalObject: *jsc.JSGlobalObject, has_body: *bool, request: *uws.Request, is_ssl: i32, response_ptr: *anyopaque, upgrade_ctx: ?*anyopaque, node_response_ptr: *?*NodeHTTPResponse, -) callconv(.C) JSC.JSValue { +) callconv(.C) jsc.JSValue { const vm = globalObject.bunVM(); const method = HTTP.Method.which(request.method()) orelse HTTP.Method.OPTIONS; // GET in node.js can have a body @@ -350,23 +350,23 @@ fn isDone(this: *const NodeHTTPResponse) bool { return this.flags.request_has_completed or this.flags.ended or this.flags.socket_closed; } -pub fn getEnded(this: *const NodeHTTPResponse, _: *JSC.JSGlobalObject) JSC.JSValue { - return JSC.JSValue.jsBoolean(this.flags.ended); +pub fn getEnded(this: *const NodeHTTPResponse, _: *jsc.JSGlobalObject) jsc.JSValue { + return jsc.JSValue.jsBoolean(this.flags.ended); } -pub fn getFinished(this: *const NodeHTTPResponse, _: *JSC.JSGlobalObject) JSC.JSValue { - return JSC.JSValue.jsBoolean(this.flags.request_has_completed); +pub fn getFinished(this: *const NodeHTTPResponse, _: *jsc.JSGlobalObject) jsc.JSValue { + return jsc.JSValue.jsBoolean(this.flags.request_has_completed); } -pub fn getFlags(this: *const NodeHTTPResponse, _: *JSC.JSGlobalObject) JSC.JSValue { - return JSC.JSValue.jsNumber(@as(u8, @bitCast(this.flags))); +pub fn getFlags(this: *const NodeHTTPResponse, _: *jsc.JSGlobalObject) jsc.JSValue { + return jsc.JSValue.jsNumber(@as(u8, @bitCast(this.flags))); } -pub fn getAborted(this: *const NodeHTTPResponse, _: *JSC.JSGlobalObject) JSC.JSValue { - return JSC.JSValue.jsBoolean(this.flags.socket_closed); +pub fn getAborted(this: *const NodeHTTPResponse, _: *jsc.JSGlobalObject) jsc.JSValue { + return jsc.JSValue.jsBoolean(this.flags.socket_closed); } -pub fn getHasBody(this: *const NodeHTTPResponse, _: *JSC.JSGlobalObject) JSC.JSValue { +pub fn getHasBody(this: *const NodeHTTPResponse, _: *jsc.JSGlobalObject) jsc.JSValue { var result: i32 = 0; switch (this.body_read_state) { .none => {}, @@ -380,54 +380,54 @@ pub fn getHasBody(this: *const NodeHTTPResponse, _: *JSC.JSGlobalObject) JSC.JSV result |= 1 << 2; } - return JSC.JSValue.jsNumber(result); + return jsc.JSValue.jsNumber(result); } -pub fn getBufferedAmount(this: *const NodeHTTPResponse, _: *JSC.JSGlobalObject) JSC.JSValue { +pub fn getBufferedAmount(this: *const NodeHTTPResponse, _: *jsc.JSGlobalObject) jsc.JSValue { if (this.flags.request_has_completed or this.flags.socket_closed) { - return JSC.JSValue.jsNumber(0); + return jsc.JSValue.jsNumber(0); } - return JSC.JSValue.jsNumber(this.raw_response.getBufferedAmount()); + return jsc.JSValue.jsNumber(this.raw_response.getBufferedAmount()); } -pub fn jsRef(this: *NodeHTTPResponse, globalObject: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!JSC.JSValue { +pub fn jsRef(this: *NodeHTTPResponse, globalObject: *jsc.JSGlobalObject, _: *jsc.CallFrame) bun.JSError!jsc.JSValue { if (!this.isDone()) { this.js_ref.ref(globalObject.bunVM()); } return .js_undefined; } -pub fn jsUnref(this: *NodeHTTPResponse, globalObject: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!JSC.JSValue { +pub fn jsUnref(this: *NodeHTTPResponse, globalObject: *jsc.JSGlobalObject, _: *jsc.CallFrame) bun.JSError!jsc.JSValue { if (!this.isDone()) { this.js_ref.unref(globalObject.bunVM()); } return .js_undefined; } -fn handleEndedIfNecessary(state: uws.State, globalObject: *JSC.JSGlobalObject) bun.JSError!void { +fn handleEndedIfNecessary(state: uws.State, globalObject: *jsc.JSGlobalObject) bun.JSError!void { if (!state.isResponsePending()) { return globalObject.ERR(.HTTP_HEADERS_SENT, "Stream is already ended", .{}).throw(); } } extern "C" fn NodeHTTPServer__writeHead_http( - globalObject: *JSC.JSGlobalObject, + globalObject: *jsc.JSGlobalObject, statusMessage: [*]const u8, statusMessageLength: usize, - headersObjectValue: JSC.JSValue, + headersObjectValue: jsc.JSValue, response: *anyopaque, ) void; extern "C" fn NodeHTTPServer__writeHead_https( - globalObject: *JSC.JSGlobalObject, + globalObject: *jsc.JSGlobalObject, statusMessage: [*]const u8, statusMessageLength: usize, - headersObjectValue: JSC.JSValue, + headersObjectValue: jsc.JSValue, response: *anyopaque, ) void; -pub fn writeHead(this: *NodeHTTPResponse, globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { +pub fn writeHead(this: *NodeHTTPResponse, globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const arguments = callframe.argumentsUndef(3).slice(); if (this.isDone()) { @@ -487,7 +487,7 @@ pub fn writeHead(this: *NodeHTTPResponse, globalObject: *JSC.JSGlobalObject, cal return .js_undefined; } -fn writeHeadInternal(response: uws.AnyResponse, globalObject: *JSC.JSGlobalObject, status_message: []const u8, headers: JSC.JSValue) void { +fn writeHeadInternal(response: uws.AnyResponse, globalObject: *jsc.JSGlobalObject, status_message: []const u8, headers: jsc.JSValue) void { log("writeHeadInternal({s})", .{status_message}); switch (response) { .TCP => NodeHTTPServer__writeHead_http(globalObject, status_message.ptr, status_message.len, headers, @ptrCast(response.TCP)), @@ -495,7 +495,7 @@ fn writeHeadInternal(response: uws.AnyResponse, globalObject: *JSC.JSGlobalObjec } } -pub fn writeContinue(this: *NodeHTTPResponse, globalObject: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!JSC.JSValue { +pub fn writeContinue(this: *NodeHTTPResponse, globalObject: *jsc.JSGlobalObject, _: *jsc.CallFrame) bun.JSError!jsc.JSValue { if (this.isDone()) { return .js_undefined; } @@ -513,7 +513,7 @@ pub const AbortEvent = enum(u8) { timeout = 2, }; -fn handleAbortOrTimeout(this: *NodeHTTPResponse, comptime event: AbortEvent, js_value: JSC.JSValue) void { +fn handleAbortOrTimeout(this: *NodeHTTPResponse, comptime event: AbortEvent, js_value: jsc.JSValue) void { if (this.flags.request_has_completed) { return; } @@ -528,7 +528,7 @@ fn handleAbortOrTimeout(this: *NodeHTTPResponse, comptime event: AbortEvent, js_ const js_this: JSValue = if (js_value == .zero) this.getThisValue() else js_value; if (js.onAbortedGetCached(js_this)) |on_aborted| { - const globalThis = JSC.VirtualMachine.get().global; + const globalThis = jsc.VirtualMachine.get().global; defer { if (event == .abort) { js.onAbortedSetCached(js_this, globalThis, .zero); @@ -539,7 +539,7 @@ fn handleAbortOrTimeout(this: *NodeHTTPResponse, comptime event: AbortEvent, js_ const event_loop = vm.eventLoop(); event_loop.runCallback(on_aborted, globalThis, js_this, &.{ - JSC.JSValue.jsNumber(@intFromEnum(event)), + jsc.JSValue.jsNumber(@intFromEnum(event)), }); } @@ -548,7 +548,7 @@ fn handleAbortOrTimeout(this: *NodeHTTPResponse, comptime event: AbortEvent, js_ } } -pub fn onAbort(this: *NodeHTTPResponse, js_value: JSC.JSValue) void { +pub fn onAbort(this: *NodeHTTPResponse, js_value: jsc.JSValue) void { log("onAbort", .{}); this.handleAbortOrTimeout(.abort, js_value); } @@ -558,7 +558,7 @@ pub fn onTimeout(this: *NodeHTTPResponse, _: uws.AnyResponse) void { this.handleAbortOrTimeout(.timeout, .zero); } -pub fn doPause(this: *NodeHTTPResponse, _: *JSC.JSGlobalObject, _: *JSC.CallFrame, thisValue: JSC.JSValue) bun.JSError!JSC.JSValue { +pub fn doPause(this: *NodeHTTPResponse, _: *jsc.JSGlobalObject, _: *jsc.CallFrame, thisValue: jsc.JSValue) bun.JSError!jsc.JSValue { log("doPause", .{}); if (this.flags.request_has_completed or this.flags.socket_closed or this.flags.ended) { return .false; @@ -575,26 +575,26 @@ pub fn doPause(this: *NodeHTTPResponse, _: *JSC.JSGlobalObject, _: *JSC.CallFram return .true; } -pub fn drainRequestBody(this: *NodeHTTPResponse, globalObject: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!JSC.JSValue { +pub fn drainRequestBody(this: *NodeHTTPResponse, globalObject: *jsc.JSGlobalObject, _: *jsc.CallFrame) bun.JSError!jsc.JSValue { return this.drainBufferedRequestBodyFromPause(globalObject) orelse .js_undefined; } -fn drainBufferedRequestBodyFromPause(this: *NodeHTTPResponse, globalObject: *JSC.JSGlobalObject) ?JSC.JSValue { +fn drainBufferedRequestBodyFromPause(this: *NodeHTTPResponse, globalObject: *jsc.JSGlobalObject) ?jsc.JSValue { if (this.buffered_request_body_data_during_pause.len > 0) { - const result = JSC.JSValue.createBuffer(globalObject, this.buffered_request_body_data_during_pause.slice(), bun.default_allocator); + const result = jsc.JSValue.createBuffer(globalObject, this.buffered_request_body_data_during_pause.slice(), bun.default_allocator); this.buffered_request_body_data_during_pause = .{}; return result; } return null; } -pub fn doResume(this: *NodeHTTPResponse, globalObject: *JSC.JSGlobalObject, _: *JSC.CallFrame) JSC.JSValue { +pub fn doResume(this: *NodeHTTPResponse, globalObject: *jsc.JSGlobalObject, _: *jsc.CallFrame) jsc.JSValue { log("doResume", .{}); if (this.flags.request_has_completed or this.flags.socket_closed or this.flags.ended) { return .false; } - var result = JSC.JSValue.true; + var result = jsc.JSValue.true; if (this.flags.is_data_buffered_during_pause) { this.raw_response.clearOnData(); this.flags.is_data_buffered_during_pause = false; @@ -614,12 +614,12 @@ pub fn onRequestComplete(this: *NodeHTTPResponse) void { } log("onRequestComplete", .{}); this.flags.request_has_completed = true; - this.js_ref.unref(JSC.VirtualMachine.get()); + this.js_ref.unref(jsc.VirtualMachine.get()); this.markRequestAsDoneIfNecessary(); } -pub export fn Bun__NodeHTTPRequest__onResolve(globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) callconv(JSC.conv) JSC.JSValue { +pub export fn Bun__NodeHTTPRequest__onResolve(globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) callconv(jsc.conv) jsc.JSValue { log("onResolve", .{}); const arguments = callframe.arguments_old(2).slice(); const this: *NodeHTTPResponse = arguments[1].as(NodeHTTPResponse).?; @@ -644,7 +644,7 @@ pub export fn Bun__NodeHTTPRequest__onResolve(globalObject: *JSC.JSGlobalObject, return .js_undefined; } -pub export fn Bun__NodeHTTPRequest__onReject(globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) callconv(JSC.conv) JSC.JSValue { +pub export fn Bun__NodeHTTPRequest__onReject(globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) callconv(jsc.conv) jsc.JSValue { const arguments = callframe.arguments_old(2).slice(); const err = arguments[0]; const this: *NodeHTTPResponse = arguments[1].as(NodeHTTPResponse).?; @@ -672,7 +672,7 @@ pub export fn Bun__NodeHTTPRequest__onReject(globalObject: *JSC.JSGlobalObject, return .js_undefined; } -pub fn abort(this: *NodeHTTPResponse, _: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!JSC.JSValue { +pub fn abort(this: *NodeHTTPResponse, _: *jsc.JSGlobalObject, _: *jsc.CallFrame) bun.JSError!jsc.JSValue { if (this.isDone()) { return .js_undefined; } @@ -697,13 +697,13 @@ fn onBufferRequestBodyWhilePaused(this: *NodeHTTPResponse, chunk: []const u8, la if (last) { this.flags.is_data_buffered_during_pause_last = true; if (this.body_read_ref.has) { - this.body_read_ref.unref(JSC.VirtualMachine.get()); + this.body_read_ref.unref(jsc.VirtualMachine.get()); this.markRequestAsDoneIfNecessary(); } } } -fn onDataOrAborted(this: *NodeHTTPResponse, chunk: []const u8, last: bool, event: AbortEvent, thisValue: JSC.JSValue) void { +fn onDataOrAborted(this: *NodeHTTPResponse, chunk: []const u8, last: bool, event: AbortEvent, thisValue: jsc.JSValue) void { if (last) { this.ref(); this.body_read_state = .done; @@ -712,7 +712,7 @@ fn onDataOrAborted(this: *NodeHTTPResponse, chunk: []const u8, last: bool, event defer { if (last) { if (this.body_read_ref.has) { - this.body_read_ref.unref(JSC.VirtualMachine.get()); + this.body_read_ref.unref(jsc.VirtualMachine.get()); this.markRequestAsDoneIfNecessary(); } @@ -725,12 +725,12 @@ fn onDataOrAborted(this: *NodeHTTPResponse, chunk: []const u8, last: bool, event return; } - const globalThis = JSC.VirtualMachine.get().global; + const globalThis = jsc.VirtualMachine.get().global; const event_loop = globalThis.bunVM().eventLoop(); - const bytes: JSC.JSValue = brk: { + const bytes: jsc.JSValue = brk: { if (chunk.len > 0 and this.buffered_request_body_data_during_pause.len > 0) { - const buffer = JSC.JSValue.createBufferFromLength(globalThis, chunk.len + this.buffered_request_body_data_during_pause.len) catch return; // TODO: properly propagate exception upwards + const buffer = jsc.JSValue.createBufferFromLength(globalThis, chunk.len + this.buffered_request_body_data_during_pause.len) catch return; // TODO: properly propagate exception upwards this.buffered_request_body_data_during_pause.deinitWithAllocator(bun.default_allocator); if (buffer.asArrayBuffer(globalThis)) |array_buffer| { var input = array_buffer.slice(); @@ -745,15 +745,15 @@ fn onDataOrAborted(this: *NodeHTTPResponse, chunk: []const u8, last: bool, event } if (chunk.len > 0) { - break :brk JSC.ArrayBuffer.createBuffer(globalThis, chunk) catch return; // TODO: properly propagate exception upwards + break :brk jsc.ArrayBuffer.createBuffer(globalThis, chunk) catch return; // TODO: properly propagate exception upwards } break :brk .js_undefined; }; event_loop.runCallback(callback, globalThis, .js_undefined, &.{ bytes, - JSC.JSValue.jsBoolean(last), - JSC.JSValue.jsNumber(@intFromEnum(event)), + jsc.JSValue.jsBoolean(last), + jsc.JSValue.jsNumber(@intFromEnum(event)), }); } } @@ -775,22 +775,22 @@ fn onDrain(this: *NodeHTTPResponse, offset: u64, response: uws.AnyResponse) bool } const thisValue = this.getThisValue(); const on_writable = js.onWritableGetCached(thisValue) orelse return false; - const globalThis = JSC.VirtualMachine.get().global; + const globalThis = jsc.VirtualMachine.get().global; js.onWritableSetCached(thisValue, globalThis, .js_undefined); // TODO(@heimskr): is this necessary? const vm = globalThis.bunVM(); - response.corked(JSC.EventLoop.runCallback, .{ vm.eventLoop(), on_writable, globalThis, .js_undefined, &.{JSC.JSValue.jsNumberFromUint64(offset)} }); + response.corked(jsc.EventLoop.runCallback, .{ vm.eventLoop(), on_writable, globalThis, .js_undefined, &.{jsc.JSValue.jsNumberFromUint64(offset)} }); // return true means we may have something to drain return true; } fn writeOrEnd( this: *NodeHTTPResponse, - globalObject: *JSC.JSGlobalObject, - arguments: []const JSC.JSValue, - this_value: JSC.JSValue, + globalObject: *jsc.JSGlobalObject, + arguments: []const jsc.JSValue, + this_value: jsc.JSValue, comptime is_end: bool, -) bun.JSError!JSC.JSValue { +) bun.JSError!jsc.JSValue { if (this.isDone()) { return globalObject.ERR(.STREAM_WRITE_AFTER_END, "Stream already ended", .{}).throw(); } @@ -826,23 +826,23 @@ fn writeOrEnd( break :brk null; }; - const string_or_buffer: JSC.Node.StringOrBuffer = brk: { + const string_or_buffer: jsc.Node.StringOrBuffer = brk: { if (input_value.isUndefinedOrNull()) { - break :brk JSC.Node.StringOrBuffer.empty; + break :brk jsc.Node.StringOrBuffer.empty; } - var encoding: JSC.Node.Encoding = .utf8; + var encoding: jsc.Node.Encoding = .utf8; if (!encoding_value.isUndefinedOrNull()) { if (!encoding_value.isString()) { return globalObject.throwInvalidArgumentTypeValue("encoding", "string", encoding_value); } - encoding = try JSC.Node.Encoding.fromJS(encoding_value, globalObject) orelse { + encoding = try jsc.Node.Encoding.fromJS(encoding_value, globalObject) orelse { return globalObject.throwInvalidArguments("Invalid encoding", .{}); }; } - const result = try JSC.Node.StringOrBuffer.fromJSWithEncoding(globalObject, bun.default_allocator, input_value, encoding); + const result = try jsc.Node.StringOrBuffer.fromJSWithEncoding(globalObject, bun.default_allocator, input_value, encoding); break :brk result orelse { return globalObject.throwInvalidArgumentTypeValue("input", "string or buffer", input_value); }; @@ -879,7 +879,7 @@ fn writeOrEnd( // Discard the body read ref if it's pending and no onData callback is set at this point. // This is the equivalent of req._dump(). if (this.body_read_ref.has and this.body_read_state == .pending and (!this.flags.hasCustomOnData or js.onDataGetCached(this_value) == null)) { - this.body_read_ref.unref(JSC.VirtualMachine.get()); + this.body_read_ref.unref(jsc.VirtualMachine.get()); this.body_read_state = .none; } @@ -898,14 +898,14 @@ fn writeOrEnd( } this.onRequestComplete(); - return JSC.JSValue.jsNumberFromUint64(bytes.len); + return jsc.JSValue.jsNumberFromUint64(bytes.len); } else { const js_this = if (this_value != .zero) this_value else this.getThisValue(); switch (this.raw_response.write(bytes)) { .want_more => |written| { this.raw_response.clearOnWritable(); js.onWritableSetCached(js_this, globalObject, .js_undefined); - return JSC.JSValue.jsNumberFromUint64(written); + return jsc.JSValue.jsNumberFromUint64(written); }, .backpressure => |written| { if (!callback_value.isUndefined()) { @@ -913,13 +913,13 @@ fn writeOrEnd( this.raw_response.onWritable(*NodeHTTPResponse, onDrain, this); } - return JSC.JSValue.jsNumberFromInt64(-@as(i64, @intCast(@min(written, std.math.maxInt(i64))))); + return jsc.JSValue.jsNumberFromInt64(-@as(i64, @intCast(@min(written, std.math.maxInt(i64))))); }, } } } -pub fn setOnWritable(this: *NodeHTTPResponse, thisValue: JSC.JSValue, globalObject: *JSC.JSGlobalObject, value: JSValue) void { +pub fn setOnWritable(this: *NodeHTTPResponse, thisValue: jsc.JSValue, globalObject: *jsc.JSGlobalObject, value: JSValue) void { if (this.isDone() or value.isUndefined()) { js.onWritableSetCached(thisValue, globalObject, .js_undefined); } else { @@ -927,18 +927,18 @@ pub fn setOnWritable(this: *NodeHTTPResponse, thisValue: JSC.JSValue, globalObje } } -pub fn getOnWritable(_: *NodeHTTPResponse, thisValue: JSC.JSValue, _: *JSC.JSGlobalObject) JSC.JSValue { +pub fn getOnWritable(_: *NodeHTTPResponse, thisValue: jsc.JSValue, _: *jsc.JSGlobalObject) jsc.JSValue { return js.onWritableGetCached(thisValue) orelse .js_undefined; } -pub fn getOnAbort(this: *NodeHTTPResponse, thisValue: JSC.JSValue, _: *JSC.JSGlobalObject) JSC.JSValue { +pub fn getOnAbort(this: *NodeHTTPResponse, thisValue: jsc.JSValue, _: *jsc.JSGlobalObject) jsc.JSValue { if (this.flags.socket_closed) { return .js_undefined; } return js.onAbortedGetCached(thisValue) orelse .js_undefined; } -pub fn setOnAbort(this: *NodeHTTPResponse, thisValue: JSC.JSValue, globalObject: *JSC.JSGlobalObject, value: JSValue) void { +pub fn setOnAbort(this: *NodeHTTPResponse, thisValue: jsc.JSValue, globalObject: *jsc.JSGlobalObject, value: JSValue) void { if (this.flags.socket_closed) { return; } @@ -950,23 +950,23 @@ pub fn setOnAbort(this: *NodeHTTPResponse, thisValue: JSC.JSValue, globalObject: } } -pub fn getOnData(_: *NodeHTTPResponse, thisValue: JSC.JSValue, _: *JSC.JSGlobalObject) JSC.JSValue { +pub fn getOnData(_: *NodeHTTPResponse, thisValue: jsc.JSValue, _: *jsc.JSGlobalObject) jsc.JSValue { return js.onDataGetCached(thisValue) orelse .js_undefined; } -pub fn getHasCustomOnData(this: *NodeHTTPResponse, _: *JSC.JSGlobalObject) JSC.JSValue { - return JSC.jsBoolean(this.flags.hasCustomOnData); +pub fn getHasCustomOnData(this: *NodeHTTPResponse, _: *jsc.JSGlobalObject) jsc.JSValue { + return jsc.jsBoolean(this.flags.hasCustomOnData); } -pub fn getUpgraded(this: *NodeHTTPResponse, _: *JSC.JSGlobalObject) JSC.JSValue { - return JSC.jsBoolean(this.flags.upgraded); +pub fn getUpgraded(this: *NodeHTTPResponse, _: *jsc.JSGlobalObject) jsc.JSValue { + return jsc.jsBoolean(this.flags.upgraded); } -pub fn setHasCustomOnData(this: *NodeHTTPResponse, _: *JSC.JSGlobalObject, value: JSValue) void { +pub fn setHasCustomOnData(this: *NodeHTTPResponse, _: *jsc.JSGlobalObject, value: JSValue) void { this.flags.hasCustomOnData = value.toBoolean(); } -fn clearOnDataCallback(this: *NodeHTTPResponse, thisValue: JSC.JSValue, globalObject: *JSC.JSGlobalObject) void { +fn clearOnDataCallback(this: *NodeHTTPResponse, thisValue: jsc.JSValue, globalObject: *jsc.JSGlobalObject) void { if (this.body_read_state != .none) { if (thisValue != .zero) { js.onDataSetCached(thisValue, globalObject, .js_undefined); @@ -979,7 +979,7 @@ fn clearOnDataCallback(this: *NodeHTTPResponse, thisValue: JSC.JSValue, globalOb } } -pub fn setOnData(this: *NodeHTTPResponse, thisValue: JSC.JSValue, globalObject: *JSC.JSGlobalObject, value: JSValue) void { +pub fn setOnData(this: *NodeHTTPResponse, thisValue: jsc.JSValue, globalObject: *jsc.JSGlobalObject, value: JSValue) void { if (value.isUndefined() or this.flags.ended or this.flags.socket_closed or this.body_read_state == .none or this.flags.is_data_buffered_during_pause_last) { js.onDataSetCached(thisValue, globalObject, .js_undefined); defer { @@ -1010,29 +1010,29 @@ pub fn setOnData(this: *NodeHTTPResponse, thisValue: JSC.JSValue, globalObject: } } -pub fn write(this: *NodeHTTPResponse, globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { +pub fn write(this: *NodeHTTPResponse, globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const arguments = callframe.arguments(); return writeOrEnd(this, globalObject, arguments, .zero, false); } -pub fn flushHeaders(this: *NodeHTTPResponse, _: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!JSC.JSValue { +pub fn flushHeaders(this: *NodeHTTPResponse, _: *jsc.JSGlobalObject, _: *jsc.CallFrame) bun.JSError!jsc.JSValue { this.raw_response.flushHeaders(); return .js_undefined; } -pub fn end(this: *NodeHTTPResponse, globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { +pub fn end(this: *NodeHTTPResponse, globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const arguments = callframe.arguments(); //We dont wanna a paused socket when we call end, so is important to resume the socket resumeSocket(this); return writeOrEnd(this, globalObject, arguments, callframe.this(), true); } -pub fn getBytesWritten(this: *NodeHTTPResponse, _: *JSC.JSGlobalObject, _: *JSC.CallFrame) JSC.JSValue { - return JSC.JSValue.jsNumber(this.bytes_written); +pub fn getBytesWritten(this: *NodeHTTPResponse, _: *jsc.JSGlobalObject, _: *jsc.CallFrame) jsc.JSValue { + return jsc.JSValue.jsNumber(this.bytes_written); } -fn handleCorked(globalObject: *JSC.JSGlobalObject, function: JSC.JSValue, result: *JSValue, is_exception: *bool) void { +fn handleCorked(globalObject: *jsc.JSGlobalObject, function: jsc.JSValue, result: *JSValue, is_exception: *bool) void { result.* = function.call(globalObject, .js_undefined, &.{}) catch |err| { result.* = globalObject.takeException(err); is_exception.* = true; @@ -1048,7 +1048,7 @@ pub fn setTimeout(this: *NodeHTTPResponse, seconds: u8) void { this.raw_response.timeout(seconds); } -export fn NodeHTTPResponse__setTimeout(this: *NodeHTTPResponse, seconds: JSC.JSValue, globalThis: *JSC.JSGlobalObject) bool { +export fn NodeHTTPResponse__setTimeout(this: *NodeHTTPResponse, seconds: jsc.JSValue, globalThis: *jsc.JSGlobalObject) bool { if (!seconds.isNumber()) { globalThis.throwInvalidArgumentTypeValue("timeout", "number", seconds) catch {}; return false; @@ -1062,7 +1062,7 @@ export fn NodeHTTPResponse__setTimeout(this: *NodeHTTPResponse, seconds: JSC.JSV return true; } -pub fn cork(this: *NodeHTTPResponse, globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { +pub fn cork(this: *NodeHTTPResponse, globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const arguments = callframe.arguments_old(1).slice(); if (arguments.len == 0) { return globalObject.throwNotEnoughArguments("cork", 1, 0); @@ -1076,7 +1076,7 @@ pub fn cork(this: *NodeHTTPResponse, globalObject: *JSC.JSGlobalObject, callfram return globalObject.ERR(.STREAM_ALREADY_FINISHED, "Stream is already ended", .{}).throw(); } - var result: JSC.JSValue = .zero; + var result: jsc.JSValue = .zero; var is_exception: bool = false; this.ref(); defer this.deref(); @@ -1108,8 +1108,8 @@ fn deinit(this: *NodeHTTPResponse) void { bun.debugAssert(this.flags.socket_closed or this.flags.request_has_completed); this.buffered_request_body_data_during_pause.deinitWithAllocator(bun.default_allocator); - this.js_ref.unref(JSC.VirtualMachine.get()); - this.body_read_ref.unref(JSC.VirtualMachine.get()); + this.js_ref.unref(jsc.VirtualMachine.get()); + this.body_read_ref.unref(jsc.VirtualMachine.get()); this.promise.deinit(); bun.destroy(this); @@ -1118,9 +1118,9 @@ fn deinit(this: *NodeHTTPResponse) void { comptime { @export(&create, .{ .name = "NodeHTTPResponse__createForJS" }); } -extern "c" fn Bun__setNodeHTTPServerSocketUsSocketValue(JSC.JSValue, ?*anyopaque) void; +extern "c" fn Bun__setNodeHTTPServerSocketUsSocketValue(jsc.JSValue, ?*anyopaque) void; -pub export fn Bun__NodeHTTPResponse_onClose(response: *NodeHTTPResponse, js_value: JSC.JSValue) void { +pub export fn Bun__NodeHTTPResponse_onClose(response: *NodeHTTPResponse, js_value: jsc.JSValue) void { response.onAbort(js_value); } @@ -1131,18 +1131,18 @@ pub export fn Bun__NodeHTTPResponse_setClosed(response: *NodeHTTPResponse) void const string = []const u8; const std = @import("std"); -const HTTPStatusText = @import("../server.zig").HTTPStatusText; const bun = @import("bun"); const Environment = bun.Environment; const HTTP = bun.http; const Output = bun.Output; const uws = bun.uws; +const HTTPStatusText = bun.api.server.HTTPStatusText; -const JSC = bun.JSC; -const JSGlobalObject = JSC.JSGlobalObject; -const JSValue = JSC.JSValue; -const ZigString = JSC.ZigString; +const jsc = bun.jsc; +const JSGlobalObject = jsc.JSGlobalObject; +const JSValue = jsc.JSValue; +const ZigString = jsc.ZigString; -const AnyServer = JSC.API.AnyServer; -const ServerWebSocket = JSC.API.ServerWebSocket; +const AnyServer = jsc.API.AnyServer; +const ServerWebSocket = jsc.API.ServerWebSocket; diff --git a/src/bun.js/api/server/RequestContext.zig b/src/bun.js/api/server/RequestContext.zig index ada50f6c63..6bcab2874d 100644 --- a/src/bun.js/api/server/RequestContext.zig +++ b/src/bun.js/api/server/RequestContext.zig @@ -4,7 +4,7 @@ pub fn NewRequestContext(comptime ssl_enabled: bool, comptime debug_mode: bool, const App = uws.NewApp(ssl_enabled); pub threadlocal var pool: ?*RequestContext.RequestContextStackAllocator = null; - pub const ResponseStream = JSC.WebCore.HTTPServerWritable(ssl_enabled); + pub const ResponseStream = jsc.WebCore.HTTPServerWritable(ssl_enabled); // This pre-allocates up to 2,048 RequestContext structs. // It costs about 655,632 bytes. @@ -17,9 +17,9 @@ pub fn NewRequestContext(comptime ssl_enabled: bool, comptime debug_mode: bool, allocator: std.mem.Allocator, req: ?*uws.Request, request_weakref: Request.WeakRef = .empty, - signal: ?*JSC.WebCore.AbortSignal = null, + signal: ?*jsc.WebCore.AbortSignal = null, method: HTTP.Method, - cookies: ?*JSC.WebCore.CookieMap = null, + cookies: ?*jsc.WebCore.CookieMap = null, flags: NewFlags(debug_mode) = .{}, @@ -27,23 +27,23 @@ pub fn NewRequestContext(comptime ssl_enabled: bool, comptime debug_mode: bool, /// We can only safely free once the request body promise is finalized /// and the response is rejected - response_jsvalue: JSC.JSValue = JSC.JSValue.zero, + response_jsvalue: jsc.JSValue = jsc.JSValue.zero, ref_count: u8 = 1, - response_ptr: ?*JSC.WebCore.Response = null, - blob: JSC.WebCore.Blob.Any = JSC.WebCore.Blob.Any{ .Blob = .{} }, + response_ptr: ?*jsc.WebCore.Response = null, + blob: jsc.WebCore.Blob.Any = jsc.WebCore.Blob.Any{ .Blob = .{} }, sendfile: SendfileContext = undefined, - request_body_readable_stream_ref: JSC.WebCore.ReadableStream.Strong = .{}, + request_body_readable_stream_ref: jsc.WebCore.ReadableStream.Strong = .{}, request_body: ?*WebCore.Body.Value.HiveRef = null, request_body_buf: std.ArrayListUnmanaged(u8) = .{}, request_body_content_len: usize = 0, sink: ?*ResponseStream.JSSink = null, - byte_stream: ?*JSC.WebCore.ByteStream = null, + byte_stream: ?*jsc.WebCore.ByteStream = null, // reference to the readable stream / byte_stream alive - readable_stream_ref: JSC.WebCore.ReadableStream.Strong = .{}, + readable_stream_ref: jsc.WebCore.ReadableStream.Strong = .{}, /// Used in errors pathname: bun.String = bun.String.empty, @@ -80,7 +80,7 @@ pub fn NewRequestContext(comptime ssl_enabled: bool, comptime debug_mode: bool, } } - pub fn setCookies(this: *RequestContext, cookie_map: ?*JSC.WebCore.CookieMap) void { + pub fn setCookies(this: *RequestContext, cookie_map: ?*jsc.WebCore.CookieMap) void { if (this.cookies) |cookies| cookies.deref(); this.cookies = cookie_map; if (this.cookies) |cookies| cookies.ref(); @@ -94,7 +94,7 @@ pub fn NewRequestContext(comptime ssl_enabled: bool, comptime debug_mode: bool, } } - pub fn onResolve(_: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { + pub fn onResolve(_: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { ctxLog("onResolve", .{}); const arguments = callframe.arguments_old(2); @@ -108,11 +108,11 @@ pub fn NewRequestContext(comptime ssl_enabled: bool, comptime debug_mode: bool, return .js_undefined; } - fn renderMissingInvalidResponse(ctx: *RequestContext, value: JSC.JSValue) void { + fn renderMissingInvalidResponse(ctx: *RequestContext, value: jsc.JSValue) void { const class_name = value.getClassInfoName() orelse ""; if (ctx.server) |server| { - const globalThis: *JSC.JSGlobalObject = server.globalThis; + const globalThis: *jsc.JSGlobalObject = server.globalThis; Output.enableBuffering(); var writer = Output.errorWriter(); @@ -120,7 +120,7 @@ pub fn NewRequestContext(comptime ssl_enabled: bool, comptime debug_mode: bool, if (bun.strings.eqlComptime(class_name, "Response")) { Output.errGeneric("Expected a native Response object, but received a polyfilled Response object. Bun.serve() only supports native Response objects.", .{}); } else if (value != .zero and !globalThis.hasException()) { - var formatter = JSC.ConsoleObject.Formatter{ + var formatter = jsc.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true, }; @@ -132,14 +132,14 @@ pub fn NewRequestContext(comptime ssl_enabled: bool, comptime debug_mode: bool, Output.flush(); if (!globalThis.hasException()) { - JSC.ConsoleObject.writeTrace(@TypeOf(&writer), &writer, globalThis); + jsc.ConsoleObject.writeTrace(@TypeOf(&writer), &writer, globalThis); } Output.flush(); } ctx.renderMissing(); } - fn handleResolve(ctx: *RequestContext, value: JSC.JSValue) void { + fn handleResolve(ctx: *RequestContext, value: jsc.JSValue) void { if (ctx.isAbortedOrEnded() or ctx.didUpgradeWebSocket()) { return; } @@ -153,7 +153,7 @@ pub fn NewRequestContext(comptime ssl_enabled: bool, comptime debug_mode: bool, return; } - const response = value.as(JSC.WebCore.Response) orelse { + const response = value.as(jsc.WebCore.Response) orelse { ctx.renderMissingInvalidResponse(value); return; }; @@ -247,7 +247,7 @@ pub fn NewRequestContext(comptime ssl_enabled: bool, comptime debug_mode: bool, this.ref_count += 1; } - pub fn onReject(_: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { + pub fn onReject(_: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { ctxLog("onReject", .{}); const arguments = callframe.arguments_old(2); @@ -258,7 +258,7 @@ pub fn NewRequestContext(comptime ssl_enabled: bool, comptime debug_mode: bool, return .js_undefined; } - fn handleReject(ctx: *RequestContext, value: JSC.JSValue) void { + fn handleReject(ctx: *RequestContext, value: jsc.JSValue) void { if (ctx.isAbortedOrEnded()) { return; } @@ -644,7 +644,7 @@ pub fn NewRequestContext(comptime ssl_enabled: bool, comptime debug_mode: bool, this.response_jsvalue.unprotect(); this.flags.response_protected = false; } - this.response_jsvalue = JSC.JSValue.zero; + this.response_jsvalue = jsc.JSValue.zero; } this.request_body_readable_stream_ref.deinit(); @@ -843,7 +843,7 @@ pub fn NewRequestContext(comptime ssl_enabled: bool, comptime debug_mode: bool, // We tried open() in another thread for this // it was not faster due to the mountain of syscalls - pub fn renderSendFile(this: *RequestContext, blob: JSC.WebCore.Blob) void { + pub fn renderSendFile(this: *RequestContext, blob: jsc.WebCore.Blob) void { if (this.resp == null or this.server == null) return; const globalThis = this.server.?.globalThis; const resp = this.resp.?; @@ -1024,7 +1024,7 @@ pub fn NewRequestContext(comptime ssl_enabled: bool, comptime debug_mode: bool, } } - pub fn doRenderWithBodyLocked(this: *anyopaque, value: *JSC.WebCore.Body.Value) void { + pub fn doRenderWithBodyLocked(this: *anyopaque, value: *jsc.WebCore.Body.Value) void { doRenderWithBody(bun.cast(*RequestContext, this), value); } @@ -1042,7 +1042,7 @@ pub fn NewRequestContext(comptime ssl_enabled: bool, comptime debug_mode: bool, this.doRenderBlob(); } - const StreamPair = struct { this: *RequestContext, stream: JSC.WebCore.ReadableStream }; + const StreamPair = struct { this: *RequestContext, stream: jsc.WebCore.ReadableStream }; fn handleFirstStreamWrite(this: *@This()) void { if (!this.flags.has_written_status) { @@ -1151,7 +1151,7 @@ pub fn NewRequestContext(comptime ssl_enabled: bool, comptime debug_mode: bool, // TODO: should this timeout? this.response_ptr.?.body.value = .{ .Locked = .{ - .readable = JSC.WebCore.ReadableStream.Strong.init(stream, globalThis), + .readable = jsc.WebCore.ReadableStream.Strong.init(stream, globalThis), .global = globalThis, }, }; @@ -1217,7 +1217,7 @@ pub fn NewRequestContext(comptime ssl_enabled: bool, comptime debug_mode: bool, response_stream.sink.buffer.len == 0); if (!stream.isLocked(globalThis) and !is_in_progress) { - if (JSC.WebCore.ReadableStream.fromJS(stream.value, globalThis) catch null) |comparator| { // TODO: properly propagate exception upwards + if (jsc.WebCore.ReadableStream.fromJS(stream.value, globalThis) catch null) |comparator| { // TODO: properly propagate exception upwards if (std.meta.activeTag(comparator.ptr) == std.meta.activeTag(stream.ptr)) { streamLog("is not locked", .{}); this.renderMissing(); @@ -1344,7 +1344,7 @@ pub fn NewRequestContext(comptime ssl_enabled: bool, comptime debug_mode: bool, resp.runCorkedWithType(*HeaderResponseSizePair, doRenderHeadResponseAfterS3SizeResolved, &pair); } } - const HeaderResponsePair = struct { this: *RequestContext, response: *JSC.WebCore.Response }; + const HeaderResponsePair = struct { this: *RequestContext, response: *jsc.WebCore.Response }; fn doRenderHeadResponse(pair: *HeaderResponsePair) void { var this = pair.this; @@ -1483,7 +1483,7 @@ pub fn NewRequestContext(comptime ssl_enabled: bool, comptime debug_mode: bool, return; } - if (response_value.as(JSC.WebCore.Response)) |response| { + if (response_value.as(jsc.WebCore.Response)) |response| { ctx.response_jsvalue = response_value; ctx.response_jsvalue.ensureStillAlive(); ctx.flags.response_protected = false; @@ -1537,7 +1537,7 @@ pub fn NewRequestContext(comptime ssl_enabled: bool, comptime debug_mode: bool, ctx.renderMissingInvalidResponse(fulfilled_value); return; } - var response = fulfilled_value.as(JSC.WebCore.Response) orelse { + var response = fulfilled_value.as(jsc.WebCore.Response) orelse { ctx.renderMissingInvalidResponse(fulfilled_value); return; }; @@ -1616,7 +1616,7 @@ pub fn NewRequestContext(comptime ssl_enabled: bool, comptime debug_mode: bool, req.endStream(req.shouldCloseConnection()); } - pub fn onResolveStream(_: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { + pub fn onResolveStream(_: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { streamLog("onResolveStream", .{}); var args = callframe.arguments_old(2); var req: *@This() = args.ptr[args.len - 1].asPromisePtr(@This()); @@ -1624,7 +1624,7 @@ pub fn NewRequestContext(comptime ssl_enabled: bool, comptime debug_mode: bool, req.handleResolveStream(); return .js_undefined; } - pub fn onRejectStream(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { + pub fn onRejectStream(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { streamLog("onRejectStream", .{}); const args = callframe.arguments_old(2); var req = args.ptr[args.len - 1].asPromisePtr(@This()); @@ -1635,7 +1635,7 @@ pub fn NewRequestContext(comptime ssl_enabled: bool, comptime debug_mode: bool, return .js_undefined; } - pub fn handleRejectStream(req: *@This(), globalThis: *JSC.JSGlobalObject, err: JSValue) void { + pub fn handleRejectStream(req: *@This(), globalThis: *jsc.JSGlobalObject, err: JSValue) void { streamLog("handleRejectStream", .{}); if (req.sink) |wrapper| { @@ -1681,7 +1681,7 @@ pub fn NewRequestContext(comptime ssl_enabled: bool, comptime debug_mode: bool, req.endStream(req.shouldCloseConnection()); } - pub fn doRenderWithBody(this: *RequestContext, value: *JSC.WebCore.Body.Value) void { + pub fn doRenderWithBody(this: *RequestContext, value: *jsc.WebCore.Body.Value) void { this.drainMicrotasks(); // If a ReadableStream can trivially be converted to a Blob, do so. @@ -1713,15 +1713,15 @@ pub fn NewRequestContext(comptime ssl_enabled: bool, comptime debug_mode: bool, } if (lock.readable.get(globalThis)) |stream_| { - const stream: JSC.WebCore.ReadableStream = stream_; + const stream: jsc.WebCore.ReadableStream = stream_; // we hold the stream alive until we're done with it this.readable_stream_ref = lock.readable; value.* = .{ .Used = {} }; if (stream.isLocked(globalThis)) { streamLog("was locked but it shouldn't be", .{}); - var err = JSC.SystemError{ - .code = bun.String.static(@tagName(JSC.Node.ErrorCode.ERR_STREAM_CANNOT_PIPE)), + var err = jsc.SystemError{ + .code = bun.String.static(@tagName(jsc.Node.ErrorCode.ERR_STREAM_CANNOT_PIPE)), .message = bun.String.static("Stream already used, please create a new one"), }; stream.value.unprotect(); @@ -1766,8 +1766,8 @@ pub fn NewRequestContext(comptime ssl_enabled: bool, comptime debug_mode: bool, return; } this.ref(); - byte_stream.pipe = JSC.WebCore.Pipe.Wrap(@This(), onPipe).init(this); - this.readable_stream_ref = JSC.WebCore.ReadableStream.Strong.init(stream, globalThis); + byte_stream.pipe = jsc.WebCore.Pipe.Wrap(@This(), onPipe).init(this); + this.readable_stream_ref = jsc.WebCore.ReadableStream.Strong.init(stream, globalThis); this.byte_stream = byte_stream; this.response_buf_owned = byte_stream.drain().list(); @@ -1808,7 +1808,7 @@ pub fn NewRequestContext(comptime ssl_enabled: bool, comptime debug_mode: bool, this.doRenderBlob(); } - pub fn onPipe(this: *RequestContext, stream: JSC.WebCore.streams.Result, allocator: std.mem.Allocator) void { + pub fn onPipe(this: *RequestContext, stream: jsc.WebCore.streams.Result, allocator: std.mem.Allocator) void { const stream_needs_deinit = stream == .owned or stream == .owned_and_done; const is_done = stream.isDone(); defer { @@ -1900,7 +1900,7 @@ pub fn NewRequestContext(comptime ssl_enabled: bool, comptime debug_mode: bool, pub fn runErrorHandler( this: *RequestContext, - value: JSC.JSValue, + value: jsc.JSValue, ) void { runErrorHandlerWithStatusCode(this, value, 500); } @@ -1938,9 +1938,9 @@ pub fn NewRequestContext(comptime ssl_enabled: bool, comptime debug_mode: bool, return false; } - fn finishRunningErrorHandler(this: *RequestContext, value: JSC.JSValue, status: u16) void { + fn finishRunningErrorHandler(this: *RequestContext, value: jsc.JSValue, status: u16) void { if (this.server == null) return this.renderProductionError(status); - var vm: *JSC.VirtualMachine = this.server.?.vm; + var vm: *jsc.VirtualMachine = this.server.?.vm; const globalThis = this.server.?.globalThis; if (comptime debug_mode) { var exception_list: std.ArrayList(Api.JsException) = std.ArrayList(Api.JsException).init(this.allocator); @@ -1969,10 +1969,10 @@ pub fn NewRequestContext(comptime ssl_enabled: bool, comptime debug_mode: bool, pub fn runErrorHandlerWithStatusCodeDontCheckResponded( this: *RequestContext, - value: JSC.JSValue, + value: jsc.JSValue, status: u16, ) void { - JSC.markBinding(@src()); + jsc.markBinding(@src()); if (this.server) |server| { if (server.config.onError != .zero and !this.flags.has_called_error_handler) { this.flags.has_called_error_handler = true; @@ -2002,9 +2002,9 @@ pub fn NewRequestContext(comptime ssl_enabled: bool, comptime debug_mode: bool, fn processOnErrorPromise( ctx: *RequestContext, - promise_js: JSC.JSValue, - promise: JSC.AnyPromise, - value: JSC.JSValue, + promise_js: jsc.JSValue, + promise: jsc.AnyPromise, + value: jsc.JSValue, status: u16, ) void { assert(ctx.server != null); @@ -2030,7 +2030,7 @@ pub fn NewRequestContext(comptime ssl_enabled: bool, comptime debug_mode: bool, return; } - var response = fulfilled_value.as(JSC.WebCore.Response) orelse { + var response = fulfilled_value.as(jsc.WebCore.Response) orelse { ctx.finishRunningErrorHandler(value, status); return; }; @@ -2066,10 +2066,10 @@ pub fn NewRequestContext(comptime ssl_enabled: bool, comptime debug_mode: bool, pub fn runErrorHandlerWithStatusCode( this: *RequestContext, - value: JSC.JSValue, + value: jsc.JSValue, status: u16, ) void { - JSC.markBinding(@src()); + jsc.markBinding(@src()); if (this.resp == null or this.resp.?.hasResponded()) return; runErrorHandlerWithStatusCodeDontCheckResponded(this, value, status); @@ -2079,7 +2079,7 @@ pub fn NewRequestContext(comptime ssl_enabled: bool, comptime debug_mode: bool, if (this.resp == null) return; const resp = this.resp.?; - var response: *JSC.WebCore.Response = this.response_ptr.?; + var response: *jsc.WebCore.Response = this.response_ptr.?; var status = response.statusCode(); var needs_content_range = this.flags.needs_content_range and this.sendfile.remain < this.blob.size(); @@ -2205,7 +2205,7 @@ pub fn NewRequestContext(comptime ssl_enabled: bool, comptime debug_mode: bool, this.deref(); } - pub fn render(this: *RequestContext, response: *JSC.WebCore.Response) void { + pub fn render(this: *RequestContext, response: *jsc.WebCore.Response) void { ctxLog("render", .{}); this.response_ptr = response; @@ -2274,13 +2274,13 @@ pub fn NewRequestContext(comptime ssl_enabled: bool, comptime debug_mode: bool, const total = bytes.items.len + chunk.len; getter: { - // if (total <= JSC.WebCore.InlineBlob.available_bytes) { + // if (total <= jsc.WebCore.InlineBlob.available_bytes) { // if (total == 0) { // body.value = .{ .Empty = {} }; // break :getter; // } - // body.value = .{ .InlineBlob = JSC.WebCore.InlineBlob.concat(bytes.items, chunk) }; + // body.value = .{ .InlineBlob = jsc.WebCore.InlineBlob.concat(bytes.items, chunk) }; // this.request_body_buf.clearAndFree(this.allocator); // } else { bytes.ensureTotalCapacityPrecise(this.allocator, total) catch |err| { @@ -2319,10 +2319,10 @@ pub fn NewRequestContext(comptime ssl_enabled: bool, comptime debug_mode: bool, } } - pub fn onStartStreamingRequestBody(this: *RequestContext) JSC.WebCore.DrainResult { + pub fn onStartStreamingRequestBody(this: *RequestContext) jsc.WebCore.DrainResult { ctxLog("onStartStreamingRequestBody", .{}); if (this.isAbortedOrEnded()) { - return JSC.WebCore.DrainResult{ + return jsc.WebCore.DrainResult{ .aborted = {}, }; } @@ -2367,17 +2367,17 @@ pub fn NewRequestContext(comptime ssl_enabled: bool, comptime debug_mode: bool, } } - pub fn onRequestBodyReadableStreamAvailable(ptr: *anyopaque, globalThis: *JSC.JSGlobalObject, readable: JSC.WebCore.ReadableStream) void { + pub fn onRequestBodyReadableStreamAvailable(ptr: *anyopaque, globalThis: *jsc.JSGlobalObject, readable: jsc.WebCore.ReadableStream) void { var this = bun.cast(*RequestContext, ptr); bun.debugAssert(this.request_body_readable_stream_ref.held.impl == null); - this.request_body_readable_stream_ref = JSC.WebCore.ReadableStream.Strong.init(readable, globalThis); + this.request_body_readable_stream_ref = jsc.WebCore.ReadableStream.Strong.init(readable, globalThis); } pub fn onStartBufferingCallback(this: *anyopaque) void { onStartBuffering(bun.cast(*RequestContext, this)); } - pub fn onStartStreamingRequestBodyCallback(this: *anyopaque) JSC.WebCore.DrainResult { + pub fn onStartStreamingRequestBodyCallback(this: *anyopaque) jsc.WebCore.DrainResult { return onStartStreamingRequestBody(bun.cast(*RequestContext, this)); } @@ -2409,10 +2409,10 @@ pub fn NewRequestContext(comptime ssl_enabled: bool, comptime debug_mode: bool, comptime { const export_prefix = "Bun__HTTPRequestContext" ++ (if (debug_mode) "Debug" else "") ++ (if (ThisServer.ssl_enabled) "TLS" else ""); if (bun.Environment.export_cpp_apis) { - @export(&JSC.toJSHostFn(onResolve), .{ .name = export_prefix ++ "__onResolve" }); - @export(&JSC.toJSHostFn(onReject), .{ .name = export_prefix ++ "__onReject" }); - @export(&JSC.toJSHostFn(onResolveStream), .{ .name = export_prefix ++ "__onResolveStream" }); - @export(&JSC.toJSHostFn(onRejectStream), .{ .name = export_prefix ++ "__onRejectStream" }); + @export(&jsc.toJSHostFn(onResolve), .{ .name = export_prefix ++ "__onResolve" }); + @export(&jsc.toJSHostFn(onReject), .{ .name = export_prefix ++ "__onReject" }); + @export(&jsc.toJSHostFn(onResolveStream), .{ .name = export_prefix ++ "__onResolveStream" }); + @export(&jsc.toJSHostFn(onRejectStream), .{ .name = export_prefix ++ "__onRejectStream" }); } } }; @@ -2522,7 +2522,6 @@ const string = []const u8; const std = @import("std"); const Fallback = @import("../../../runtime.zig").Fallback; -const writeStatus = @import("../server.zig").writeStatus; const linux = std.os.linux; const bun = @import("bun"); @@ -2534,20 +2533,21 @@ const String = bun.String; const assert = bun.assert; const logger = bun.logger; const uws = bun.uws; -const Api = bun.Schema.Api; - -const JSC = bun.JSC; -const JSGlobalObject = JSC.JSGlobalObject; -const JSValue = JSC.JSValue; -const VirtualMachine = JSC.VirtualMachine; -const AnyRequestContext = JSC.API.AnyRequestContext; - -const WebCore = JSC.WebCore; -const Blob = JSC.WebCore.Blob; -const Body = JSC.WebCore.Body; -const FetchHeaders = JSC.WebCore.FetchHeaders; -const Request = JSC.WebCore.Request; -const Response = JSC.WebCore.Response; +const Api = bun.schema.api; +const writeStatus = bun.api.server.writeStatus; const HTTP = bun.http; const MimeType = bun.http.MimeType; + +const jsc = bun.jsc; +const JSGlobalObject = jsc.JSGlobalObject; +const JSValue = jsc.JSValue; +const VirtualMachine = jsc.VirtualMachine; +const AnyRequestContext = jsc.API.AnyRequestContext; + +const WebCore = jsc.WebCore; +const Blob = jsc.WebCore.Blob; +const Body = jsc.WebCore.Body; +const FetchHeaders = jsc.WebCore.FetchHeaders; +const Request = jsc.WebCore.Request; +const Response = jsc.WebCore.Response; diff --git a/src/bun.js/api/server/SSLConfig.zig b/src/bun.js/api/server/SSLConfig.zig index 96f5f4785a..707156b0cf 100644 --- a/src/bun.js/api/server/SSLConfig.zig +++ b/src/bun.js/api/server/SSLConfig.zig @@ -33,11 +33,11 @@ client_renegotiation_window: u32 = 0, const BlobFileContentResult = struct { data: [:0]const u8, - fn init(comptime fieldname: []const u8, js_obj: JSC.JSValue, global: *JSC.JSGlobalObject) bun.JSError!?BlobFileContentResult { + fn init(comptime fieldname: []const u8, js_obj: jsc.JSValue, global: *jsc.JSGlobalObject) bun.JSError!?BlobFileContentResult { { - const body = try JSC.WebCore.Body.Value.fromJS(global, js_obj); + const body = try jsc.WebCore.Body.Value.fromJS(global, js_obj); if (body == .Blob and body.Blob.store != null and body.Blob.store.?.data == .file) { - var fs: JSC.Node.fs.NodeFS = .{}; + var fs: jsc.Node.fs.NodeFS = .{}; const read = fs.readFileWithOptions(.{ .path = body.Blob.store.?.data.file.pathlike }, .sync, .null_terminated); switch (read) { .err => { @@ -221,7 +221,7 @@ pub fn deinit(this: *SSLConfig) void { pub const zero = SSLConfig{}; -pub fn fromJS(vm: *JSC.VirtualMachine, global: *JSC.JSGlobalObject, obj: JSC.JSValue) bun.JSError!?SSLConfig { +pub fn fromJS(vm: *jsc.VirtualMachine, global: *jsc.JSGlobalObject, obj: jsc.JSValue) bun.JSError!?SSLConfig { var result = zero; errdefer result.deinit(); @@ -259,7 +259,7 @@ pub fn fromJS(vm: *JSC.VirtualMachine, global: *JSC.JSGlobalObject, obj: JSC.JSV var valid_count: u32 = 0; for (0..count) |i| { const item = try js_obj.getIndex(global, @intCast(i)); - if (try JSC.Node.StringOrBuffer.fromJS(global, arena.allocator(), item)) |sb| { + if (try jsc.Node.StringOrBuffer.fromJS(global, arena.allocator(), item)) |sb| { defer sb.deinit(); const sliced = sb.slice(); if (sliced.len > 0) { @@ -309,7 +309,7 @@ pub fn fromJS(vm: *JSC.VirtualMachine, global: *JSC.JSGlobalObject, obj: JSC.JSV } } else { const native_array = try bun.default_allocator.alloc([*c]const u8, 1); - if (try JSC.Node.StringOrBuffer.fromJS(global, arena.allocator(), js_obj)) |sb| { + if (try jsc.Node.StringOrBuffer.fromJS(global, arena.allocator(), js_obj)) |sb| { defer sb.deinit(); const sliced = sb.slice(); if (sliced.len > 0) { @@ -343,7 +343,7 @@ pub fn fromJS(vm: *JSC.VirtualMachine, global: *JSC.JSGlobalObject, obj: JSC.JSV } if (try obj.getTruthy(global, "ALPNProtocols")) |protocols| { - if (try JSC.Node.StringOrBuffer.fromJS(global, arena.allocator(), protocols)) |sb| { + if (try jsc.Node.StringOrBuffer.fromJS(global, arena.allocator(), protocols)) |sb| { defer sb.deinit(); const sliced = sb.slice(); if (sliced.len > 0) { @@ -367,7 +367,7 @@ pub fn fromJS(vm: *JSC.VirtualMachine, global: *JSC.JSGlobalObject, obj: JSC.JSV var valid_count: u32 = 0; for (0..count) |i| { const item = try js_obj.getIndex(global, @intCast(i)); - if (try JSC.Node.StringOrBuffer.fromJS(global, arena.allocator(), item)) |sb| { + if (try jsc.Node.StringOrBuffer.fromJS(global, arena.allocator(), item)) |sb| { defer sb.deinit(); const sliced = sb.slice(); if (sliced.len > 0) { @@ -417,7 +417,7 @@ pub fn fromJS(vm: *JSC.VirtualMachine, global: *JSC.JSGlobalObject, obj: JSC.JSV } } else { const native_array = try bun.default_allocator.alloc([*c]const u8, 1); - if (try JSC.Node.StringOrBuffer.fromJS(global, arena.allocator(), js_obj)) |sb| { + if (try jsc.Node.StringOrBuffer.fromJS(global, arena.allocator(), js_obj)) |sb| { defer sb.deinit(); const sliced = sb.slice(); if (sliced.len > 0) { @@ -476,7 +476,7 @@ pub fn fromJS(vm: *JSC.VirtualMachine, global: *JSC.JSGlobalObject, obj: JSC.JSV var valid_count: u32 = 0; for (0..count) |i| { const item = try js_obj.getIndex(global, @intCast(i)); - if (try JSC.Node.StringOrBuffer.fromJS(global, arena.allocator(), item)) |sb| { + if (try jsc.Node.StringOrBuffer.fromJS(global, arena.allocator(), item)) |sb| { defer sb.deinit(); const sliced = sb.slice(); if (sliced.len > 0) { @@ -526,7 +526,7 @@ pub fn fromJS(vm: *JSC.VirtualMachine, global: *JSC.JSGlobalObject, obj: JSC.JSV } } else { const native_array = try bun.default_allocator.alloc([*c]const u8, 1); - if (try JSC.Node.StringOrBuffer.fromJS(global, arena.allocator(), js_obj)) |sb| { + if (try jsc.Node.StringOrBuffer.fromJS(global, arena.allocator(), js_obj)) |sb| { defer sb.deinit(); const sliced = sb.slice(); if (sliced.len > 0) { @@ -616,7 +616,7 @@ const bun = @import("bun"); const strings = bun.strings; const uws = bun.uws; -const JSC = bun.JSC; -const JSGlobalObject = JSC.JSGlobalObject; -const JSValue = JSC.JSValue; -const VirtualMachine = JSC.VirtualMachine; +const jsc = bun.jsc; +const JSGlobalObject = jsc.JSGlobalObject; +const JSValue = jsc.JSValue; +const VirtualMachine = jsc.VirtualMachine; diff --git a/src/bun.js/api/server/ServerConfig.zig b/src/bun.js/api/server/ServerConfig.zig index c9c837498c..b685c370ed 100644 --- a/src/bun.js/api/server/ServerConfig.zig +++ b/src/bun.js/api/server/ServerConfig.zig @@ -42,9 +42,9 @@ broadcast_console_log_from_browser_to_server_for_bake: bool = false, /// If HMR is not enabled, then this field is ignored. enable_chrome_devtools_automatic_workspace_folders: bool = true, -onError: JSC.JSValue = JSC.JSValue.zero, -onRequest: JSC.JSValue = JSC.JSValue.zero, -onNodeHTTPRequest: JSC.JSValue = JSC.JSValue.zero, +onError: jsc.JSValue = jsc.JSValue.zero, +onRequest: jsc.JSValue = jsc.JSValue.zero, +onNodeHTTPRequest: jsc.JSValue = jsc.JSValue.zero, websocket: ?WebSocketServerContext = null, @@ -325,7 +325,7 @@ pub fn getUsocketsOptions(this: *const ServerConfig) i32 { return out; } -fn validateRouteName(global: *JSC.JSGlobalObject, path: []const u8) !void { +fn validateRouteName(global: *jsc.JSGlobalObject, path: []const u8) !void { // Already validated by the caller bun.debugAssert(path.len > 0 and path[0] == '/'); @@ -361,7 +361,7 @@ fn validateRouteName(global: *JSC.JSGlobalObject, path: []const u8) !void { pub const SSLConfig = @import("./SSLConfig.zig"); -fn getRoutesObject(global: *JSC.JSGlobalObject, arg: JSC.JSValue) bun.JSError!?JSC.JSValue { +fn getRoutesObject(global: *jsc.JSGlobalObject, arg: jsc.JSValue) bun.JSError!?jsc.JSValue { inline for (.{ "routes", "static" }) |key| { if (try arg.get(global, key)) |routes| { // https://github.com/oven-sh/bun/issues/17568 @@ -381,9 +381,9 @@ pub const FromJSOptions = struct { }; pub fn fromJS( - global: *JSC.JSGlobalObject, + global: *jsc.JSGlobalObject, args: *ServerConfig, - arguments: *JSC.CallFrame.ArgumentsSlice, + arguments: *jsc.CallFrame.ArgumentsSlice, opts: FromJSOptions, ) bun.JSError!void { const vm = arguments.vm; @@ -500,7 +500,7 @@ pub fn fromJS( }; args.had_routes_object = true; - var iter = try JSC.JSPropertyIterator(.{ + var iter = try jsc.JSPropertyIterator(.{ .skip_empty_name = true, .include_value = true, }).init(global, static_obj); @@ -536,7 +536,7 @@ pub fn fromJS( const path, const is_ascii = key.toOwnedSliceReturningAllASCII(bun.default_allocator) catch bun.outOfMemory(); errdefer bun.default_allocator.free(path); - const value: JSC.JSValue = iter.value; + const value: jsc.JSValue = iter.value; if (value.isUndefined()) { continue; @@ -1072,7 +1072,7 @@ pub fn fromJS( const UserRouteBuilder = struct { route: ServerConfig.RouteDeclaration, - callback: JSC.Strong.Optional = .empty, + callback: jsc.Strong.Optional = .empty, pub fn deinit(this: *UserRouteBuilder) void { this.route.deinit(); @@ -1084,14 +1084,14 @@ const string = []const u8; const WebSocketServerContext = @import("./WebSocketServerContext.zig"); const std = @import("std"); -const AnyRoute = @import("../server.zig").AnyRoute; const bun = @import("bun"); const HTTP = bun.http; -const JSC = bun.JSC; const JSError = bun.JSError; const URL = bun.URL; const assert = bun.assert; +const jsc = bun.jsc; const strings = bun.strings; const uws = bun.uws; -const AnyServer = JSC.API.AnyServer; +const AnyRoute = bun.api.server.AnyRoute; +const AnyServer = jsc.API.AnyServer; diff --git a/src/bun.js/api/server/ServerWebSocket.zig b/src/bun.js/api/server/ServerWebSocket.zig index dabbf54516..9d0c1a3d57 100644 --- a/src/bun.js/api/server/ServerWebSocket.zig +++ b/src/bun.js/api/server/ServerWebSocket.zig @@ -10,7 +10,7 @@ const Flags = packed struct(u64) { ssl: bool = false, closed: bool = false, opened: bool = false, - binary_type: JSC.ArrayBuffer.BinaryType = .Buffer, + binary_type: jsc.ArrayBuffer.BinaryType = .Buffer, packed_websocket_ptr: u57 = 0, inline fn websocket(this: Flags) uws.AnyWebSocket { @@ -29,7 +29,7 @@ inline fn websocket(this: *const ServerWebSocket) uws.AnyWebSocket { return this.flags.websocket(); } -pub const js = JSC.Codegen.JSServerWebSocket; +pub const js = jsc.Codegen.JSServerWebSocket; pub const toJS = js.toJS; pub const fromJS = js.fromJS; pub const fromJSDirect = js.fromJSDirect; @@ -194,7 +194,7 @@ pub fn onDrain(this: *ServerWebSocket, _: uws.AnyWebSocket) void { const globalObject = handler.globalObject; var corker = Corker{ - .args = &[_]JSC.JSValue{this.getThisValue()}, + .args = &[_]jsc.JSValue{this.getThisValue()}, .globalObject = globalObject, .callback = handler.onDrain, }; @@ -210,18 +210,18 @@ pub fn onDrain(this: *ServerWebSocket, _: uws.AnyWebSocket) void { } } -fn binaryToJS(this: *const ServerWebSocket, globalThis: *JSC.JSGlobalObject, data: []const u8) bun.JSError!JSC.JSValue { +fn binaryToJS(this: *const ServerWebSocket, globalThis: *jsc.JSGlobalObject, data: []const u8) bun.JSError!jsc.JSValue { return switch (this.flags.binary_type) { - .Buffer => JSC.ArrayBuffer.createBuffer( + .Buffer => jsc.ArrayBuffer.createBuffer( globalThis, data, ), - .Uint8Array => JSC.ArrayBuffer.create( + .Uint8Array => jsc.ArrayBuffer.create( globalThis, data, .Uint8Array, ), - else => JSC.ArrayBuffer.create( + else => jsc.ArrayBuffer.create( globalThis, data, .ArrayBuffer, @@ -246,7 +246,7 @@ pub fn onPing(this: *ServerWebSocket, _: uws.AnyWebSocket, data: []const u8) voi _ = cb.call( globalThis, .js_undefined, - &[_]JSC.JSValue{ this.getThisValue(), this.binaryToJS(globalThis, data) catch .zero }, // TODO: properly propagate exception upwards + &[_]jsc.JSValue{ this.getThisValue(), this.binaryToJS(globalThis, data) catch .zero }, // TODO: properly propagate exception upwards ) catch |e| { const err = globalThis.takeException(e); log("onPing error", .{}); @@ -274,7 +274,7 @@ pub fn onPong(this: *ServerWebSocket, _: uws.AnyWebSocket, data: []const u8) voi _ = cb.call( globalThis, .js_undefined, - &[_]JSC.JSValue{ this.getThisValue(), this.binaryToJS(globalThis, data) catch .zero }, // TODO: properly propagate exception upwards + &[_]jsc.JSValue{ this.getThisValue(), this.binaryToJS(globalThis, data) catch .zero }, // TODO: properly propagate exception upwards ) catch |e| { const err = globalThis.takeException(e); log("onPong error", .{}); @@ -331,7 +331,7 @@ pub fn onClose(this: *ServerWebSocket, _: uws.AnyWebSocket, code: i32, message: return; }; - _ = handler.onClose.call(globalObject, .js_undefined, &[_]JSC.JSValue{ this.getThisValue(), JSValue.jsNumber(code), message_js }) catch |e| { + _ = handler.onClose.call(globalObject, .js_undefined, &[_]jsc.JSValue{ this.getThisValue(), JSValue.jsNumber(code), message_js }) catch |e| { const err = globalObject.takeException(e); log("onClose error", .{}); handler.runErrorCallback(vm, globalObject, err); @@ -355,7 +355,7 @@ pub fn behavior(comptime ServerType: type, comptime ssl: bool, opts: uws.WebSock return uws.WebSocketBehavior.Wrap(ServerType, @This(), ssl).apply(opts); } -pub fn constructor(globalObject: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!*ServerWebSocket { +pub fn constructor(globalObject: *jsc.JSGlobalObject, _: *jsc.CallFrame) bun.JSError!*ServerWebSocket { return globalObject.throw("Cannot construct ServerWebSocket", .{}); } @@ -366,8 +366,8 @@ pub fn finalize(this: *ServerWebSocket) void { pub fn publish( this: *ServerWebSocket, - globalThis: *JSC.JSGlobalObject, - callframe: *JSC.CallFrame, + globalThis: *jsc.JSGlobalObject, + callframe: *jsc.CallFrame, ) bun.JSError!JSValue { const args = callframe.arguments_old(4); if (args.len < 1) { @@ -453,8 +453,8 @@ pub fn publish( pub fn publishText( this: *ServerWebSocket, - globalThis: *JSC.JSGlobalObject, - callframe: *JSC.CallFrame, + globalThis: *jsc.JSGlobalObject, + callframe: *jsc.CallFrame, ) bun.JSError!JSValue { const args = callframe.arguments_old(4); @@ -519,8 +519,8 @@ pub fn publishText( pub fn publishBinary( this: *ServerWebSocket, - globalThis: *JSC.JSGlobalObject, - callframe: *JSC.CallFrame, + globalThis: *jsc.JSGlobalObject, + callframe: *jsc.CallFrame, ) bun.JSError!JSValue { const args = callframe.arguments_old(4); @@ -580,10 +580,10 @@ pub fn publishBinary( pub fn publishBinaryWithoutTypeChecks( this: *ServerWebSocket, - globalThis: *JSC.JSGlobalObject, - topic_str: *JSC.JSString, - array: *JSC.JSUint8Array, -) bun.JSError!JSC.JSValue { + globalThis: *jsc.JSGlobalObject, + topic_str: *jsc.JSString, + array: *jsc.JSUint8Array, +) bun.JSError!jsc.JSValue { const app = this.handler.app orelse { log("publish() closed", .{}); return JSValue.jsNumber(0); @@ -602,7 +602,7 @@ pub fn publishBinaryWithoutTypeChecks( const buffer = array.slice(); if (buffer.len == 0) { - return JSC.JSValue.jsNumber(0); + return jsc.JSValue.jsNumber(0); } const result = if (!publish_to_self and !this.isClosed()) @@ -619,10 +619,10 @@ pub fn publishBinaryWithoutTypeChecks( pub fn publishTextWithoutTypeChecks( this: *ServerWebSocket, - globalThis: *JSC.JSGlobalObject, - topic_str: *JSC.JSString, - str: *JSC.JSString, -) bun.JSError!JSC.JSValue { + globalThis: *jsc.JSGlobalObject, + topic_str: *jsc.JSString, + str: *jsc.JSString, +) bun.JSError!jsc.JSValue { const app = this.handler.app orelse { log("publish() closed", .{}); return JSValue.jsNumber(0); @@ -644,7 +644,7 @@ pub fn publishTextWithoutTypeChecks( const buffer = slice.slice(); if (buffer.len == 0) { - return JSC.JSValue.jsNumber(0); + return jsc.JSValue.jsNumber(0); } const result = if (!publish_to_self and !this.isClosed()) @@ -661,11 +661,11 @@ pub fn publishTextWithoutTypeChecks( pub fn cork( this: *ServerWebSocket, - globalThis: *JSC.JSGlobalObject, - callframe: *JSC.CallFrame, + globalThis: *jsc.JSGlobalObject, + callframe: *jsc.CallFrame, // Since we're passing the `this` value to the cork function, we need to // make sure the `this` value is up to date. - this_value: JSC.JSValue, + this_value: jsc.JSValue, ) bun.JSError!JSValue { const args = callframe.arguments_old(1); this.this_value = this_value; @@ -701,8 +701,8 @@ pub fn cork( pub fn send( this: *ServerWebSocket, - globalThis: *JSC.JSGlobalObject, - callframe: *JSC.CallFrame, + globalThis: *jsc.JSGlobalObject, + callframe: *jsc.CallFrame, ) bun.JSError!JSValue { const args = callframe.arguments_old(2); @@ -777,8 +777,8 @@ pub fn send( pub fn sendText( this: *ServerWebSocket, - globalThis: *JSC.JSGlobalObject, - callframe: *JSC.CallFrame, + globalThis: *jsc.JSGlobalObject, + callframe: *jsc.CallFrame, ) bun.JSError!JSValue { const args = callframe.arguments_old(2); @@ -834,8 +834,8 @@ pub fn sendText( pub fn sendTextWithoutTypeChecks( this: *ServerWebSocket, - globalThis: *JSC.JSGlobalObject, - message_str: *JSC.JSString, + globalThis: *jsc.JSGlobalObject, + message_str: *jsc.JSString, compress: bool, ) JSValue { if (this.isClosed()) { @@ -865,8 +865,8 @@ pub fn sendTextWithoutTypeChecks( pub fn sendBinary( this: *ServerWebSocket, - globalThis: *JSC.JSGlobalObject, - callframe: *JSC.CallFrame, + globalThis: *jsc.JSGlobalObject, + callframe: *jsc.CallFrame, ) bun.JSError!JSValue { const args = callframe.arguments_old(2); @@ -911,8 +911,8 @@ pub fn sendBinary( pub fn sendBinaryWithoutTypeChecks( this: *ServerWebSocket, - _: *JSC.JSGlobalObject, - array_buffer: *JSC.JSUint8Array, + _: *jsc.JSGlobalObject, + array_buffer: *jsc.JSUint8Array, compress: bool, ) JSValue { if (this.isClosed()) { @@ -940,24 +940,24 @@ pub fn sendBinaryWithoutTypeChecks( pub fn ping( this: *ServerWebSocket, - globalThis: *JSC.JSGlobalObject, - callframe: *JSC.CallFrame, + globalThis: *jsc.JSGlobalObject, + callframe: *jsc.CallFrame, ) bun.JSError!JSValue { return sendPing(this, globalThis, callframe, "ping", .ping); } pub fn pong( this: *ServerWebSocket, - globalThis: *JSC.JSGlobalObject, - callframe: *JSC.CallFrame, + globalThis: *jsc.JSGlobalObject, + callframe: *jsc.CallFrame, ) bun.JSError!JSValue { return sendPing(this, globalThis, callframe, "pong", .pong); } inline fn sendPing( this: *ServerWebSocket, - globalThis: *JSC.JSGlobalObject, - callframe: *JSC.CallFrame, + globalThis: *jsc.JSGlobalObject, + callframe: *jsc.CallFrame, comptime name: string, comptime opcode: uws.Opcode, ) bun.JSError!JSValue { @@ -1030,7 +1030,7 @@ inline fn sendPing( pub fn getData( _: *ServerWebSocket, - _: *JSC.JSGlobalObject, + _: *jsc.JSGlobalObject, ) JSValue { log("getData()", .{}); return .js_undefined; @@ -1038,8 +1038,8 @@ pub fn getData( pub fn setData( this: *ServerWebSocket, - globalObject: *JSC.JSGlobalObject, - value: JSC.JSValue, + globalObject: *jsc.JSGlobalObject, + value: jsc.JSValue, ) void { log("setData()", .{}); js.dataSetCached(this.this_value, globalObject, value); @@ -1047,7 +1047,7 @@ pub fn setData( pub fn getReadyState( this: *ServerWebSocket, - _: *JSC.JSGlobalObject, + _: *jsc.JSGlobalObject, ) JSValue { log("getReadyState()", .{}); @@ -1060,10 +1060,10 @@ pub fn getReadyState( pub fn close( this: *ServerWebSocket, - globalThis: *JSC.JSGlobalObject, - callframe: *JSC.CallFrame, + globalThis: *jsc.JSGlobalObject, + callframe: *jsc.CallFrame, // Since close() can lead to the close() callback being called, let's always ensure the `this` value is up to date. - this_value: JSC.JSValue, + this_value: jsc.JSValue, ) bun.JSError!JSValue { const args = callframe.arguments_old(2); log("close()", .{}); @@ -1100,10 +1100,10 @@ pub fn close( pub fn terminate( this: *ServerWebSocket, - globalThis: *JSC.JSGlobalObject, - callframe: *JSC.CallFrame, + globalThis: *jsc.JSGlobalObject, + callframe: *jsc.CallFrame, // Since terminate() can lead to close() being called, let's always ensure the `this` value is up to date. - this_value: JSC.JSValue, + this_value: jsc.JSValue, ) bun.JSError!JSValue { _ = globalThis; const args = callframe.arguments_old(2); @@ -1125,7 +1125,7 @@ pub fn terminate( pub fn getBinaryType( this: *ServerWebSocket, - globalThis: *JSC.JSGlobalObject, + globalThis: *jsc.JSGlobalObject, ) JSValue { log("getBinaryType()", .{}); @@ -1137,10 +1137,10 @@ pub fn getBinaryType( }; } -pub fn setBinaryType(this: *ServerWebSocket, globalThis: *JSC.JSGlobalObject, value: JSC.JSValue) bun.JSError!void { +pub fn setBinaryType(this: *ServerWebSocket, globalThis: *jsc.JSGlobalObject, value: jsc.JSValue) bun.JSError!void { log("setBinaryType()", .{}); - const btype = try JSC.ArrayBuffer.BinaryType.fromJSValue(globalThis, value); + const btype = try jsc.ArrayBuffer.BinaryType.fromJSValue(globalThis, value); switch (btype orelse // some other value which we don't support .Float64Array) { @@ -1156,8 +1156,8 @@ pub fn setBinaryType(this: *ServerWebSocket, globalThis: *JSC.JSGlobalObject, va pub fn getBufferedAmount( this: *ServerWebSocket, - _: *JSC.JSGlobalObject, - _: *JSC.CallFrame, + _: *jsc.JSGlobalObject, + _: *jsc.CallFrame, ) bun.JSError!JSValue { log("getBufferedAmount()", .{}); @@ -1169,8 +1169,8 @@ pub fn getBufferedAmount( } pub fn subscribe( this: *ServerWebSocket, - globalThis: *JSC.JSGlobalObject, - callframe: *JSC.CallFrame, + globalThis: *jsc.JSGlobalObject, + callframe: *jsc.CallFrame, ) bun.JSError!JSValue { const args = callframe.arguments_old(1); if (args.len < 1) { @@ -1194,7 +1194,7 @@ pub fn subscribe( return JSValue.jsBoolean(this.websocket().subscribe(topic.slice())); } -pub fn unsubscribe(this: *ServerWebSocket, globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { +pub fn unsubscribe(this: *ServerWebSocket, globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { const args = callframe.arguments_old(1); if (args.len < 1) { return globalThis.throw("unsubscribe requires at least 1 argument", .{}); @@ -1219,8 +1219,8 @@ pub fn unsubscribe(this: *ServerWebSocket, globalThis: *JSC.JSGlobalObject, call } pub fn isSubscribed( this: *ServerWebSocket, - globalThis: *JSC.JSGlobalObject, - callframe: *JSC.CallFrame, + globalThis: *jsc.JSGlobalObject, + callframe: *jsc.CallFrame, ) bun.JSError!JSValue { const args = callframe.arguments_old(1); if (args.len < 1) { @@ -1247,7 +1247,7 @@ pub fn isSubscribed( pub fn getRemoteAddress( this: *ServerWebSocket, - globalThis: *JSC.JSGlobalObject, + globalThis: *jsc.JSGlobalObject, ) bun.JSError!JSValue { if (this.isClosed()) { return .js_undefined; @@ -1269,9 +1269,9 @@ pub fn getRemoteAddress( const Corker = struct { args: []const JSValue = &.{}, - globalObject: *JSC.JSGlobalObject, - this_value: JSC.JSValue = .zero, - callback: JSC.JSValue, + globalObject: *jsc.JSGlobalObject, + this_value: jsc.JSValue = .zero, + callback: jsc.JSValue, result: JSValue = .zero, pub fn run(this: *Corker) void { @@ -1284,18 +1284,18 @@ const Corker = struct { } }; -extern "c" fn Bun__callNodeHTTPServerSocketOnClose(JSC.JSValue) void; +extern "c" fn Bun__callNodeHTTPServerSocketOnClose(jsc.JSValue) void; const string = []const u8; const std = @import("std"); -const WebSocketServer = @import("../server.zig").WebSocketServerContext; const bun = @import("bun"); const Output = bun.Output; const uws = bun.uws; +const WebSocketServer = bun.api.server.WebSocketServerContext; -const JSC = bun.JSC; -const JSGlobalObject = JSC.JSGlobalObject; -const JSValue = JSC.JSValue; -const ZigString = JSC.ZigString; +const jsc = bun.jsc; +const JSGlobalObject = jsc.JSGlobalObject; +const JSValue = jsc.JSValue; +const ZigString = jsc.ZigString; diff --git a/src/bun.js/api/server/StaticRoute.zig b/src/bun.js/api/server/StaticRoute.zig index 012a722fd9..5e79ef6af6 100644 --- a/src/bun.js/api/server/StaticRoute.zig +++ b/src/bun.js/api/server/StaticRoute.zig @@ -23,7 +23,7 @@ pub const InitFromBytesOptions = struct { server: ?AnyServer, mime_type: ?*const bun.http.MimeType = null, status_code: u16 = 200, - headers: ?*JSC.WebCore.FetchHeaders = null, + headers: ?*jsc.WebCore.FetchHeaders = null, }; /// Ownership of `blob` is transferred to this function. @@ -59,7 +59,7 @@ fn deinit(this: *StaticRoute) void { bun.destroy(this); } -pub fn clone(this: *StaticRoute, globalThis: *JSC.JSGlobalObject) !*StaticRoute { +pub fn clone(this: *StaticRoute, globalThis: *jsc.JSGlobalObject) !*StaticRoute { var blob = this.blob.toBlob(globalThis); this.blob = .{ .Blob = blob }; @@ -78,8 +78,8 @@ pub fn memoryCost(this: *const StaticRoute) usize { return @sizeOf(StaticRoute) + this.blob.memoryCost() + this.headers.memoryCost(); } -pub fn fromJS(globalThis: *JSC.JSGlobalObject, argument: JSC.JSValue) bun.JSError!?*StaticRoute { - if (argument.as(JSC.WebCore.Response)) |response| { +pub fn fromJS(globalThis: *jsc.JSGlobalObject, argument: jsc.JSValue) bun.JSError!?*StaticRoute { + if (argument.as(jsc.WebCore.Response)) |response| { // The user may want to pass in the same Response object multiple endpoints // Let's let them do that. @@ -267,8 +267,8 @@ fn doWriteHeaders(this: *StaticRoute, resp: AnyResponse) void { switch (resp) { inline .SSL, .TCP => |s| { const entries = this.headers.entries.slice(); - const names: []const Api.StringPointer = entries.items(.name); - const values: []const Api.StringPointer = entries.items(.value); + const names: []const api.StringPointer = entries.items(.name); + const values: []const api.StringPointer = entries.items(.value); const buf = this.headers.buf.items; for (names, values) |name, value| { @@ -307,14 +307,14 @@ pub fn onWithMethod(this: *StaticRoute, method: bun.http.Method, resp: AnyRespon } const std = @import("std"); -const Api = @import("../../../api/schema.zig").Api; -const writeStatus = @import("../server.zig").writeStatus; const bun = @import("bun"); -const JSC = bun.JSC; +const jsc = bun.jsc; const Headers = bun.http.Headers; -const AnyServer = JSC.API.AnyServer; -const AnyBlob = JSC.WebCore.Blob.Any; +const api = bun.schema.api; +const AnyServer = jsc.API.AnyServer; +const writeStatus = bun.api.server.writeStatus; +const AnyBlob = jsc.WebCore.Blob.Any; const uws = bun.uws; const AnyResponse = uws.AnyResponse; diff --git a/src/bun.js/api/server/WebSocketServerContext.zig b/src/bun.js/api/server/WebSocketServerContext.zig index f79fc2b717..8b92eddf68 100644 --- a/src/bun.js/api/server/WebSocketServerContext.zig +++ b/src/bun.js/api/server/WebSocketServerContext.zig @@ -1,6 +1,6 @@ const WebSocketServerContext = @This(); -globalObject: *JSC.JSGlobalObject = undefined, +globalObject: *jsc.JSGlobalObject = undefined, handler: Handler = .{}, maxPayloadLength: u32 = 1024 * 1024 * 16, // 16MB @@ -13,19 +13,19 @@ resetIdleTimeoutOnSend: bool = true, closeOnBackpressureLimit: bool = false, pub const Handler = struct { - onOpen: JSC.JSValue = .zero, - onMessage: JSC.JSValue = .zero, - onClose: JSC.JSValue = .zero, - onDrain: JSC.JSValue = .zero, - onError: JSC.JSValue = .zero, - onPing: JSC.JSValue = .zero, - onPong: JSC.JSValue = .zero, + onOpen: jsc.JSValue = .zero, + onMessage: jsc.JSValue = .zero, + onClose: jsc.JSValue = .zero, + onDrain: jsc.JSValue = .zero, + onError: jsc.JSValue = .zero, + onPing: jsc.JSValue = .zero, + onPong: jsc.JSValue = .zero, app: ?*anyopaque = null, // Always set manually. - vm: *JSC.VirtualMachine = undefined, - globalObject: *JSC.JSGlobalObject = undefined, + vm: *jsc.VirtualMachine = undefined, + globalObject: *jsc.JSGlobalObject = undefined, active_connections: usize = 0, /// used by publish() @@ -34,7 +34,7 @@ pub const Handler = struct { publish_to_self: bool = false, } = .{}, - pub fn runErrorCallback(this: *const Handler, vm: *JSC.VirtualMachine, globalObject: *JSC.JSGlobalObject, error_value: JSC.JSValue) void { + pub fn runErrorCallback(this: *const Handler, vm: *jsc.VirtualMachine, globalObject: *jsc.JSGlobalObject, error_value: jsc.JSValue) void { const onError = this.onError; if (!onError.isEmptyOrUndefinedOrNull()) { _ = onError.call(globalObject, .js_undefined, &.{error_value}) catch |err| @@ -45,7 +45,7 @@ pub const Handler = struct { _ = vm.uncaughtException(globalObject, error_value, false); } - pub fn fromJS(globalObject: *JSC.JSGlobalObject, object: JSC.JSValue) bun.JSError!Handler { + pub fn fromJS(globalObject: *jsc.JSGlobalObject, object: jsc.JSValue) bun.JSError!Handler { var handler = Handler{ .globalObject = globalObject, .vm = VirtualMachine.get() }; var valid = false; @@ -152,7 +152,7 @@ const DecompressTable = bun.ComptimeStringMap(i32, .{ .{ "256KB", uws.DEDICATED_COMPRESSOR_256KB }, }); -pub fn onCreate(globalObject: *JSC.JSGlobalObject, object: JSValue) bun.JSError!WebSocketServerContext { +pub fn onCreate(globalObject: *jsc.JSGlobalObject, object: JSValue) bun.JSError!WebSocketServerContext { var server = WebSocketServerContext{}; server.handler = try Handler.fromJS(globalObject, object); @@ -272,8 +272,8 @@ const bun = @import("bun"); const JSError = bun.JSError; const uws = bun.uws; -const JSC = bun.JSC; -const JSGlobalObject = JSC.JSGlobalObject; -const JSValue = JSC.JSValue; -const VirtualMachine = JSC.VirtualMachine; -const ZigString = JSC.ZigString; +const jsc = bun.jsc; +const JSGlobalObject = jsc.JSGlobalObject; +const JSValue = jsc.JSValue; +const VirtualMachine = jsc.VirtualMachine; +const ZigString = jsc.ZigString; diff --git a/src/bun.js/bindgen_test.zig b/src/bun.js/bindgen_test.zig index fe139ca16d..3dceffa1ac 100644 --- a/src/bun.js/bindgen_test.zig +++ b/src/bun.js/bindgen_test.zig @@ -1,14 +1,14 @@ //! This namespace is used to test binding generator -pub fn getBindgenTestFunctions(global: *JSC.JSGlobalObject) bun.JSError!JSC.JSValue { - return (try JSC.JSObject.create(.{ +pub fn getBindgenTestFunctions(global: *jsc.JSGlobalObject) bun.JSError!jsc.JSValue { + return (try jsc.JSObject.create(.{ .add = gen.createAddCallback(global), .requiredAndOptionalArg = gen.createRequiredAndOptionalArgCallback(global), }, global)).toJS(); } // This example should be kept in sync with bindgen's documentation -pub fn add(global: *JSC.JSGlobalObject, a: i32, b: i32) !i32 { +pub fn add(global: *jsc.JSGlobalObject, a: i32, b: i32) !i32 { return std.math.add(i32, a, b) catch { // Binding functions can return `error.OutOfMemory` and `error.JSError`. // Others like `error.Overflow` from `std.math.add` must be converted. @@ -33,5 +33,5 @@ pub fn requiredAndOptionalArg(a: bool, b: ?usize, c: i32, d: ?u8) i32 { const std = @import("std"); const bun = @import("bun"); -const JSC = bun.JSC; +const jsc = bun.jsc; const gen = bun.gen.bindgen_test; diff --git a/src/bun.js/bindings/AbortSignal.zig b/src/bun.js/bindings/AbortSignal.zig index 6fcf2e5769..36356ac693 100644 --- a/src/bun.js/bindings/AbortSignal.zig +++ b/src/bun.js/bindings/AbortSignal.zig @@ -41,14 +41,14 @@ pub const AbortSignal = opaque { return WebCore__AbortSignal__cleanNativeBindings(this, ctx); } - extern fn WebCore__AbortSignal__signal(*AbortSignal, *JSC.JSGlobalObject, CommonAbortReason) void; + extern fn WebCore__AbortSignal__signal(*AbortSignal, *jsc.JSGlobalObject, CommonAbortReason) void; pub fn signal( this: *AbortSignal, - globalObject: *JSC.JSGlobalObject, + globalObject: *jsc.JSGlobalObject, reason: CommonAbortReason, ) void { - bun.Analytics.Features.abort_signal += 1; + bun.analytics.Features.abort_signal += 1; return WebCore__AbortSignal__signal(this, globalObject, reason); } @@ -73,20 +73,20 @@ pub const AbortSignal = opaque { return WebCore__AbortSignal__abortReason(this); } - extern fn WebCore__AbortSignal__reasonIfAborted(*AbortSignal, *JSC.JSGlobalObject, *u8) JSValue; + extern fn WebCore__AbortSignal__reasonIfAborted(*AbortSignal, *jsc.JSGlobalObject, *u8) JSValue; pub const AbortReason = union(enum) { common: CommonAbortReason, js: JSValue, - pub fn toBodyValueError(this: AbortReason, globalObject: *JSC.JSGlobalObject) JSC.WebCore.Body.Value.ValueError { + pub fn toBodyValueError(this: AbortReason, globalObject: *jsc.JSGlobalObject) jsc.WebCore.Body.Value.ValueError { return switch (this) { .common => |reason| .{ .AbortReason = reason }, .js => |value| .{ .JSValue = .create(value, globalObject) }, }; } - pub fn toJS(this: AbortReason, global: *JSC.JSGlobalObject) JSValue { + pub fn toJS(this: AbortReason, global: *jsc.JSGlobalObject) JSValue { return switch (this) { .common => |reason| reason.toJS(global), .js => |value| value, @@ -94,7 +94,7 @@ pub const AbortSignal = opaque { } }; - pub fn reasonIfAborted(this: *AbortSignal, global: *JSC.JSGlobalObject) ?AbortReason { + pub fn reasonIfAborted(this: *AbortSignal, global: *jsc.JSGlobalObject) ?AbortReason { var reason: u8 = 0; const js_reason = WebCore__AbortSignal__reasonIfAborted(this, global, &reason); if (reason > 0) { @@ -134,7 +134,7 @@ pub const AbortSignal = opaque { extern fn WebCore__AbortSignal__new(*JSGlobalObject) *AbortSignal; pub fn new(global: *JSGlobalObject) *AbortSignal { - JSC.markBinding(@src()); + jsc.markBinding(@src()); return WebCore__AbortSignal__new(global); } }; @@ -142,6 +142,6 @@ pub const AbortSignal = opaque { const bun = @import("bun"); const CommonAbortReason = @import("./CommonAbortReason.zig").CommonAbortReason; -const JSC = bun.JSC; -const JSGlobalObject = JSC.JSGlobalObject; -const JSValue = JSC.JSValue; +const jsc = bun.jsc; +const JSGlobalObject = jsc.JSGlobalObject; +const JSValue = jsc.JSValue; diff --git a/src/bun.js/bindings/AnyPromise.zig b/src/bun.js/bindings/AnyPromise.zig index 6ee9499928..ef53b82bd6 100644 --- a/src/bun.js/bindings/AnyPromise.zig +++ b/src/bun.js/bindings/AnyPromise.zig @@ -53,7 +53,7 @@ pub const AnyPromise = union(enum) { }; } - extern fn JSC__AnyPromise__wrap(*JSC.JSGlobalObject, JSValue, *anyopaque, *const fn (*anyopaque, *JSC.JSGlobalObject) callconv(.C) JSC.JSValue) void; + extern fn JSC__AnyPromise__wrap(*jsc.JSGlobalObject, JSValue, *anyopaque, *const fn (*anyopaque, *jsc.JSGlobalObject) callconv(.C) jsc.JSValue) void; pub fn wrap( this: AnyPromise, @@ -66,12 +66,12 @@ pub const AnyPromise = union(enum) { const Wrapper = struct { args: Args, - pub fn call(wrap_: *@This(), global: *JSC.JSGlobalObject) callconv(.c) JSC.JSValue { - return JSC.toJSHostCall(global, @src(), Fn, wrap_.args); + pub fn call(wrap_: *@This(), global: *jsc.JSGlobalObject) callconv(.c) jsc.JSValue { + return jsc.toJSHostCall(global, @src(), Fn, wrap_.args); } }; - var scope: JSC.CatchScope = undefined; + var scope: jsc.CatchScope = undefined; scope.init(globalObject, @src()); defer scope.deinit(); var ctx = Wrapper{ .args = args }; @@ -85,7 +85,7 @@ const std = @import("std"); const JSInternalPromise = @import("./JSInternalPromise.zig").JSInternalPromise; const JSPromise = @import("./JSPromise.zig").JSPromise; -const JSC = bun.JSC; -const JSGlobalObject = JSC.JSGlobalObject; -const JSValue = JSC.JSValue; -const VM = JSC.VM; +const jsc = bun.jsc; +const JSGlobalObject = jsc.JSGlobalObject; +const JSValue = jsc.JSValue; +const VM = jsc.VM; diff --git a/src/bun.js/bindings/CallFrame.zig b/src/bun.js/bindings/CallFrame.zig index b7ebd3cb6f..0f833bd564 100644 --- a/src/bun.js/bindings/CallFrame.zig +++ b/src/bun.js/bindings/CallFrame.zig @@ -17,7 +17,7 @@ pub const CallFrame = opaque { } /// This function protects out-of-bounds access by returning undefined - pub fn argument(self: *const CallFrame, i: usize) JSC.JSValue { + pub fn argument(self: *const CallFrame, i: usize) jsc.JSValue { return if (self.argumentsCount() > i) self.arguments()[i] else .js_undefined; } @@ -27,12 +27,12 @@ pub const CallFrame = opaque { /// When this CallFrame belongs to a constructor, this value is not the `this` /// value, but instead the value of `new.target`. - pub fn this(self: *const CallFrame) JSC.JSValue { + pub fn this(self: *const CallFrame) jsc.JSValue { return self.asUnsafeJSValueArray()[offset_this_argument]; } /// `JSValue` for the current function being called. - pub fn callee(self: *const CallFrame) JSC.JSValue { + pub fn callee(self: *const CallFrame) jsc.JSValue { return self.asUnsafeJSValueArray()[offset_callee]; } @@ -72,7 +72,7 @@ pub const CallFrame = opaque { /// | ...... | /// /// The proper return type of this should be []Register, but - inline fn asUnsafeJSValueArray(self: *const CallFrame) [*]const JSC.JSValue { + inline fn asUnsafeJSValueArray(self: *const CallFrame) [*]const jsc.JSValue { return @ptrCast(@alignCast(self)); } @@ -113,11 +113,11 @@ pub const CallFrame = opaque { fn Arguments(comptime max: usize) type { return struct { - ptr: [max]JSC.JSValue, + ptr: [max]jsc.JSValue, len: usize, - pub inline fn init(comptime i: usize, ptr: [*]const JSC.JSValue) @This() { - var args: [max]JSC.JSValue = std.mem.zeroes([max]JSC.JSValue); + pub inline fn init(comptime i: usize, ptr: [*]const jsc.JSValue) @This() { + var args: [max]jsc.JSValue = std.mem.zeroes([max]jsc.JSValue); args[0..i].* = ptr[0..i].*; return @This(){ @@ -126,8 +126,8 @@ pub const CallFrame = opaque { }; } - pub inline fn initUndef(comptime i: usize, ptr: [*]const JSC.JSValue) @This() { - var args: [max]JSC.JSValue = @splat(.js_undefined); + pub inline fn initUndef(comptime i: usize, ptr: [*]const jsc.JSValue) @This() { + var args: [max]jsc.JSValue = @splat(.js_undefined); args[0..i].* = ptr[0..i].*; return @This(){ .ptr = args, .len = i }; } @@ -209,10 +209,10 @@ pub const CallFrame = opaque { /// /// Prefer `Iterator` for a simpler iterator. pub const ArgumentsSlice = struct { - remaining: []const JSC.JSValue, - vm: *JSC.VirtualMachine, + remaining: []const jsc.JSValue, + vm: *jsc.VirtualMachine, arena: bun.ArenaAllocator = bun.ArenaAllocator.init(bun.default_allocator), - all: []const JSC.JSValue, + all: []const jsc.JSValue, threw: bool = false, protected: bun.bit_set.IntegerBitSet(32) = bun.bit_set.IntegerBitSet(32).initEmpty(), will_be_async: bool = false, @@ -238,15 +238,15 @@ pub const CallFrame = opaque { slice.eat(); } - pub fn protectEatNext(slice: *ArgumentsSlice) ?JSC.JSValue { + pub fn protectEatNext(slice: *ArgumentsSlice) ?jsc.JSValue { if (slice.remaining.len == 0) return null; return slice.nextEat(); } - pub fn from(vm: *JSC.VirtualMachine, slice: []const JSC.JSValueRef) ArgumentsSlice { - return init(vm, @as([*]const JSC.JSValue, @ptrCast(slice.ptr))[0..slice.len]); + pub fn from(vm: *jsc.VirtualMachine, slice: []const jsc.JSValueRef) ArgumentsSlice { + return init(vm, @as([*]const jsc.JSValue, @ptrCast(slice.ptr))[0..slice.len]); } - pub fn init(vm: *JSC.VirtualMachine, slice: []const JSC.JSValue) ArgumentsSlice { + pub fn init(vm: *jsc.VirtualMachine, slice: []const jsc.JSValue) ArgumentsSlice { return ArgumentsSlice{ .remaining = slice, .vm = vm, @@ -255,9 +255,9 @@ pub const CallFrame = opaque { }; } - pub fn initAsync(vm: *JSC.VirtualMachine, slice: []const JSC.JSValue) ArgumentsSlice { + pub fn initAsync(vm: *jsc.VirtualMachine, slice: []const jsc.JSValue) ArgumentsSlice { return ArgumentsSlice{ - .remaining = bun.default_allocator.dupe(JSC.JSValue, slice), + .remaining = bun.default_allocator.dupe(jsc.JSValue, slice), .vm = vm, .all = slice, .arena = bun.ArenaAllocator.init(bun.default_allocator), @@ -277,7 +277,7 @@ pub const CallFrame = opaque { } /// Peek the next argument without eating it - pub fn next(slice: *ArgumentsSlice) ?JSC.JSValue { + pub fn next(slice: *ArgumentsSlice) ?jsc.JSValue { if (slice.remaining.len == 0) { return null; } @@ -285,7 +285,7 @@ pub const CallFrame = opaque { return slice.remaining[0]; } - pub fn nextEat(slice: *ArgumentsSlice) ?JSC.JSValue { + pub fn nextEat(slice: *ArgumentsSlice) ?jsc.JSValue { if (slice.remaining.len == 0) { return null; } @@ -299,6 +299,6 @@ const bun = @import("bun"); const std = @import("std"); const VM = @import("./VM.zig").VM; -const JSC = bun.JSC; -const JSGlobalObject = JSC.JSGlobalObject; -const JSValue = JSC.JSValue; +const jsc = bun.jsc; +const JSGlobalObject = jsc.JSGlobalObject; +const JSValue = jsc.JSValue; diff --git a/src/bun.js/bindings/CommonAbortReason.zig b/src/bun.js/bindings/CommonAbortReason.zig index fe4abd174c..cf9d628d11 100644 --- a/src/bun.js/bindings/CommonAbortReason.zig +++ b/src/bun.js/bindings/CommonAbortReason.zig @@ -12,6 +12,6 @@ pub const CommonAbortReason = enum(u8) { const bun = @import("bun"); -const JSC = bun.JSC; -const JSGlobalObject = JSC.JSGlobalObject; -const JSValue = JSC.JSValue; +const jsc = bun.jsc; +const JSGlobalObject = jsc.JSGlobalObject; +const JSValue = jsc.JSValue; diff --git a/src/bun.js/bindings/CommonStrings.zig b/src/bun.js/bindings/CommonStrings.zig index 6cdc4a681e..0966fbd8d1 100644 --- a/src/bun.js/bindings/CommonStrings.zig +++ b/src/bun.js/bindings/CommonStrings.zig @@ -2,7 +2,7 @@ /// /// All getters return a `JSC::JSString`; pub const CommonStrings = struct { - globalObject: *JSC.JSGlobalObject, + globalObject: *jsc.JSGlobalObject, const CommonStringsForZig = enum(u8) { IPv4 = 0, @@ -10,7 +10,7 @@ pub const CommonStrings = struct { IN4Loopback = 2, IN6Any = 3, - extern "c" fn Bun__CommonStringsForZig__toJS(commonString: CommonStringsForZig, globalObject: *JSC.JSGlobalObject) JSC.JSValue; + extern "c" fn Bun__CommonStringsForZig__toJS(commonString: CommonStringsForZig, globalObject: *jsc.JSGlobalObject) jsc.JSValue; pub const toJS = Bun__CommonStringsForZig__toJS; }; @@ -30,5 +30,5 @@ pub const CommonStrings = struct { const bun = @import("bun"); -const JSC = bun.JSC; -const JSValue = JSC.JSValue; +const jsc = bun.jsc; +const JSValue = jsc.JSValue; diff --git a/src/bun.js/bindings/DOMFormData.zig b/src/bun.js/bindings/DOMFormData.zig index 82f4c872e5..09d654d58e 100644 --- a/src/bun.js/bindings/DOMFormData.zig +++ b/src/bun.js/bindings/DOMFormData.zig @@ -57,7 +57,7 @@ pub const DOMFormData = opaque { pub fn appendBlob( this: *DOMFormData, - global: *JSC.JSGlobalObject, + global: *jsc.JSGlobalObject, name_: *ZigString, blob: *anyopaque, filename_: *ZigString, @@ -83,7 +83,7 @@ pub const DOMFormData = opaque { pub const FormDataEntry = union(enum) { string: ZigString, file: struct { - blob: *JSC.WebCore.Blob, + blob: *jsc.WebCore.Blob, filename: ZigString, }, }; @@ -108,7 +108,7 @@ pub const DOMFormData = opaque { else FormDataEntry{ .file = .{ - .blob = bun.cast(*JSC.WebCore.Blob, value_ptr), + .blob = bun.cast(*jsc.WebCore.Blob, value_ptr), .filename = (filename orelse &ZigString.Empty).*, }, }; @@ -116,15 +116,15 @@ pub const DOMFormData = opaque { wrapper(ctx_, name_.*, value); } }; - JSC.markBinding(@src()); + jsc.markBinding(@src()); DOMFormData__forEach(this, ctx, Wrap.forEachWrapper); } }; const bun = @import("bun"); -const JSC = bun.JSC; -const JSGlobalObject = JSC.JSGlobalObject; -const JSValue = JSC.JSValue; -const VM = JSC.VM; -const ZigString = JSC.ZigString; +const jsc = bun.jsc; +const JSGlobalObject = jsc.JSGlobalObject; +const JSValue = jsc.JSValue; +const VM = jsc.VM; +const ZigString = jsc.ZigString; diff --git a/src/bun.js/bindings/DOMURL.zig b/src/bun.js/bindings/DOMURL.zig index 1c8d9f80d8..75f98e8c1f 100644 --- a/src/bun.js/bindings/DOMURL.zig +++ b/src/bun.js/bindings/DOMURL.zig @@ -6,7 +6,7 @@ pub const DOMURL = opaque { } pub fn cast(value: JSValue) ?*DOMURL { - return cast_(value, JSC.VirtualMachine.get().global.vm()); + return cast_(value, jsc.VirtualMachine.get().global.vm()); } pub fn href_(this: *DOMURL, out: *ZigString) void { @@ -52,7 +52,7 @@ pub const DOMURL = opaque { const bun = @import("bun"); const String = bun.String; -const JSC = bun.JSC; -const JSValue = JSC.JSValue; -const VM = JSC.VM; -const ZigString = JSC.ZigString; +const jsc = bun.jsc; +const JSValue = jsc.JSValue; +const VM = jsc.VM; +const ZigString = jsc.ZigString; diff --git a/src/bun.js/bindings/DeferredError.zig b/src/bun.js/bindings/DeferredError.zig index d2ab21fb52..a1a4b6ff3d 100644 --- a/src/bun.js/bindings/DeferredError.zig +++ b/src/bun.js/bindings/DeferredError.zig @@ -2,12 +2,12 @@ // information until its ready to be materialized later. pub const DeferredError = struct { kind: Kind, - code: JSC.Node.ErrorCode, + code: jsc.Node.ErrorCode, msg: bun.String, pub const Kind = enum { plainerror, typeerror, rangeerror }; - pub fn from(kind: Kind, code: JSC.Node.ErrorCode, comptime fmt: [:0]const u8, args: anytype) DeferredError { + pub fn from(kind: Kind, code: jsc.Node.ErrorCode, comptime fmt: [:0]const u8, args: anytype) DeferredError { return .{ .kind = kind, .code = code, @@ -29,6 +29,6 @@ pub const DeferredError = struct { const bun = @import("bun"); const ZigString = @import("./ZigString.zig").ZigString; -const JSC = bun.JSC; -const JSGlobalObject = JSC.JSGlobalObject; -const JSValue = JSC.JSValue; +const jsc = bun.jsc; +const JSGlobalObject = jsc.JSGlobalObject; +const JSValue = jsc.JSValue; diff --git a/src/bun.js/bindings/EventType.zig b/src/bun.js/bindings/EventType.zig index 573b9da7f4..826fae8ed7 100644 --- a/src/bun.js/bindings/EventType.zig +++ b/src/bun.js/bindings/EventType.zig @@ -27,5 +27,6 @@ pub const EventType = enum(u8) { } }; +const string = []const u8; + const bun = @import("bun"); -const string = bun.string; diff --git a/src/bun.js/bindings/Exception.zig b/src/bun.js/bindings/Exception.zig index 7801d32fc7..7b45f2ff7c 100644 --- a/src/bun.js/bindings/Exception.zig +++ b/src/bun.js/bindings/Exception.zig @@ -15,6 +15,6 @@ pub const Exception = opaque { const bun = @import("bun"); const ZigStackTrace = @import("./ZigStackTrace.zig").ZigStackTrace; -const JSC = bun.JSC; -const JSGlobalObject = JSC.JSGlobalObject; -const JSValue = JSC.JSValue; +const jsc = bun.jsc; +const JSGlobalObject = jsc.JSGlobalObject; +const JSValue = jsc.JSValue; diff --git a/src/bun.js/bindings/FetchHeaders.zig b/src/bun.js/bindings/FetchHeaders.zig index ae09b41287..a9336077b3 100644 --- a/src/bun.js/bindings/FetchHeaders.zig +++ b/src/bun.js/bindings/FetchHeaders.zig @@ -23,8 +23,8 @@ pub const FetchHeaders = opaque { pub fn createValue( global: *JSGlobalObject, - names: [*c]Api.StringPointer, - values: [*c]Api.StringPointer, + names: [*c]api.StringPointer, + values: [*c]api.StringPointer, buf: *const ZigString, count_: u32, ) JSValue { @@ -37,7 +37,7 @@ pub const FetchHeaders = opaque { ); } - extern "c" fn WebCore__FetchHeaders__createFromJS(*JSC.JSGlobalObject, JSValue) ?*FetchHeaders; + extern "c" fn WebCore__FetchHeaders__createFromJS(*jsc.JSGlobalObject, JSValue) ?*FetchHeaders; /// Construct a `Headers` object from a JSValue. /// /// This can be: @@ -61,8 +61,8 @@ pub const FetchHeaders = opaque { pub fn from( global: *JSGlobalObject, - names: [*c]Api.StringPointer, - values: [*c]Api.StringPointer, + names: [*c]api.StringPointer, + values: [*c]api.StringPointer, buf: *const ZigString, count_: u32, ) JSValue { @@ -361,7 +361,7 @@ pub const FetchHeaders = opaque { } pub fn cast(value: JSValue) ?*FetchHeaders { - return cast_(value, JSC.VirtualMachine.get().global.vm()); + return cast_(value, jsc.VirtualMachine.get().global.vm()); } pub fn toJS(this: *FetchHeaders, globalThis: *JSGlobalObject) JSValue { @@ -405,8 +405,8 @@ pub const FetchHeaders = opaque { pub fn copyTo( this: *FetchHeaders, - names: [*]Api.StringPointer, - values: [*]Api.StringPointer, + names: [*]api.StringPointer, + values: [*]api.StringPointer, buf: [*]u8, ) void { return WebCore__FetchHeaders__copyTo( @@ -420,11 +420,11 @@ pub const FetchHeaders = opaque { const bun = @import("bun"); -const Api = @import("../../api/schema.zig").Api; -const StringPointer = Api.StringPointer; +const jsc = bun.jsc; +const JSGlobalObject = jsc.JSGlobalObject; +const JSValue = jsc.JSValue; +const VM = jsc.VM; +const ZigString = jsc.ZigString; -const JSC = bun.JSC; -const JSGlobalObject = JSC.JSGlobalObject; -const JSValue = JSC.JSValue; -const VM = JSC.VM; -const ZigString = JSC.ZigString; +const api = bun.schema.api; +const StringPointer = api.StringPointer; diff --git a/src/bun.js/bindings/HTTPServerAgent.zig b/src/bun.js/bindings/HTTPServerAgent.zig index 88352b4019..ac7356281c 100644 --- a/src/bun.js/bindings/HTTPServerAgent.zig +++ b/src/bun.js/bindings/HTTPServerAgent.zig @@ -11,7 +11,7 @@ pub fn isEnabled(this: *const HTTPServerAgent) bool { } //#region Events -pub fn notifyServerStarted(this: *HTTPServerAgent, instance: JSC.API.AnyServer) void { +pub fn notifyServerStarted(this: *HTTPServerAgent, instance: jsc.API.AnyServer) void { if (this.agent) |agent| { this.next_server_id = .init(this.next_server_id.get() + 1); instance.setInspectorServerID(this.next_server_id); @@ -28,13 +28,13 @@ pub fn notifyServerStarted(this: *HTTPServerAgent, instance: JSC.API.AnyServer) } } -pub fn notifyServerStopped(this: *const HTTPServerAgent, server: JSC.API.AnyServer) void { +pub fn notifyServerStopped(this: *const HTTPServerAgent, server: jsc.API.AnyServer) void { if (this.agent) |agent| { agent.notifyServerStopped(server.inspectorServerID(), @floatFromInt(std.time.milliTimestamp())); } } -pub fn notifyServerRoutesUpdated(this: *const HTTPServerAgent, server: JSC.API.AnyServer) !void { +pub fn notifyServerRoutesUpdated(this: *const HTTPServerAgent, server: jsc.API.AnyServer) !void { if (this.agent) |agent| { const config = server.config(); var routes = std.ArrayList(Route).init(bun.default_allocator); @@ -50,7 +50,7 @@ pub fn notifyServerRoutesUpdated(this: *const HTTPServerAgent, server: JSC.API.A switch (server.userRoutes()) { inline else => |user_routes| { for (user_routes) |*user_route| { - const decl: *const JSC.API.ServerConfig.RouteDeclaration = &user_route.route; + const decl: *const jsc.API.ServerConfig.RouteDeclaration = &user_route.route; max_id = @max(max_id, user_route.id); try routes.append(.{ .route_id = @intCast(user_route.id), @@ -87,7 +87,7 @@ pub fn notifyServerRoutesUpdated(this: *const HTTPServerAgent, server: JSC.API.A max_id += 1; } - agent.notifyServerRoutesUpdated(server.inspectorServerID(), @intCast(JSC.VirtualMachine.get().hot_reload_counter), routes.items); + agent.notifyServerRoutesUpdated(server.inspectorServerID(), @intCast(jsc.VirtualMachine.get().hot_reload_counter), routes.items); } } @@ -158,7 +158,7 @@ pub const InspectorHTTPServerAgent = opaque { //#region Zig -> C++ export fn Bun__HTTPServerAgent__setEnabled(agent: ?*InspectorHTTPServerAgent) void { - if (JSC.VirtualMachine.get().debugger) |*debugger| { + if (jsc.VirtualMachine.get().debugger) |*debugger| { debugger.http_server_agent.agent = agent; } } @@ -166,7 +166,7 @@ export fn Bun__HTTPServerAgent__setEnabled(agent: ?*InspectorHTTPServerAgent) vo //#endregion // Typedefs from HTTPServer.json -pub const ServerId = JSC.Debugger.DebuggerId; +pub const ServerId = jsc.Debugger.DebuggerId; pub const RequestId = i32; pub const RouteId = i32; pub const HotReloadId = i32; @@ -176,4 +176,4 @@ const std = @import("std"); const bun = @import("bun"); const BunString = bun.String; -const JSC = bun.JSC; +const jsc = bun.jsc; diff --git a/src/bun.js/bindings/JSArray.zig b/src/bun.js/bindings/JSArray.zig index e25ecec761..cda9286c81 100644 --- a/src/bun.js/bindings/JSArray.zig +++ b/src/bun.js/bindings/JSArray.zig @@ -20,6 +20,6 @@ pub const JSArray = opaque { const bun = @import("bun"); const JSArrayIterator = @import("./JSArrayIterator.zig").JSArrayIterator; -const JSC = bun.JSC; -const JSGlobalObject = JSC.JSGlobalObject; -const JSValue = JSC.JSValue; +const jsc = bun.jsc; +const JSGlobalObject = jsc.JSGlobalObject; +const JSValue = jsc.JSValue; diff --git a/src/bun.js/bindings/JSArrayIterator.zig b/src/bun.js/bindings/JSArrayIterator.zig index edf68cc90c..8368839d8e 100644 --- a/src/bun.js/bindings/JSArrayIterator.zig +++ b/src/bun.js/bindings/JSArrayIterator.zig @@ -25,6 +25,6 @@ pub const JSArrayIterator = struct { const bun = @import("bun"); const JSObject = @import("./JSObject.zig").JSObject; -const JSC = bun.JSC; -const JSGlobalObject = JSC.JSGlobalObject; -const JSValue = JSC.JSValue; +const jsc = bun.jsc; +const JSGlobalObject = jsc.JSGlobalObject; +const JSValue = jsc.JSValue; diff --git a/src/bun.js/bindings/JSCell.zig b/src/bun.js/bindings/JSCell.zig index 40e71606b4..42f5db7102 100644 --- a/src/bun.js/bindings/JSCell.zig +++ b/src/bun.js/bindings/JSCell.zig @@ -1,8 +1,8 @@ pub const JSCell = opaque { /// Statically cast a cell to a JSObject. Returns null for non-objects. /// Use `toObject` to mutate non-objects into objects. - pub fn getObject(this: *JSCell) ?*JSC.JSObject { - JSC.markMemberBinding(JSCell, @src()); + pub fn getObject(this: *JSCell) ?*jsc.JSObject { + jsc.markMemberBinding(JSCell, @src()); return JSC__JSCell__getObject(this); } @@ -13,18 +13,18 @@ pub const JSCell = opaque { /// /// ## References /// - [ECMA-262 §7.1.18 ToObject](https://tc39.es/ecma262/#sec-toobject) - pub fn toObject(this: *JSCell, global: *JSC.JSGlobalObject) *JSC.JSObject { - JSC.markMemberBinding(JSCell, @src()); + pub fn toObject(this: *JSCell, global: *jsc.JSGlobalObject) *jsc.JSObject { + jsc.markMemberBinding(JSCell, @src()); return JSC__JSCell__toObject(this, global); } pub fn getType(this: *const JSCell) u8 { - JSC.markMemberBinding(JSCell, @src()); + jsc.markMemberBinding(JSCell, @src()); return @enumFromInt(JSC__JSCell__getType(this)); } - pub fn toJS(this: *JSCell) JSC.JSValue { - return JSC.JSValue.fromCell(this); + pub fn toJS(this: *JSCell) jsc.JSValue { + return jsc.JSValue.fromCell(this); } pub fn getGetterSetter(this: *JSCell) *GetterSetter { @@ -45,8 +45,8 @@ pub const JSCell = opaque { std.mem.doNotOptimizeAway(this); } - extern fn JSC__JSCell__getObject(this: *JSCell) *JSC.JSObject; - extern fn JSC__JSCell__toObject(this: *JSCell, *JSGlobalObject) *JSC.JSObject; + extern fn JSC__JSCell__getObject(this: *JSCell) *jsc.JSObject; + extern fn JSC__JSCell__toObject(this: *JSCell, *JSGlobalObject) *jsc.JSObject; // NOTE: this function always returns a JSType, but by using `u8` then // casting it via `@enumFromInt` we can ensure our `JSType` enum matches // WebKit's. This protects us from possible future breaking changes made @@ -59,6 +59,6 @@ const std = @import("std"); const CustomGetterSetter = @import("./CustomGetterSetter.zig").CustomGetterSetter; const GetterSetter = @import("./GetterSetter.zig").GetterSetter; -const JSC = bun.JSC; -const JSGlobalObject = JSC.JSGlobalObject; -const JSValue = JSC.JSValue; +const jsc = bun.jsc; +const JSGlobalObject = jsc.JSGlobalObject; +const JSValue = jsc.JSValue; diff --git a/src/bun.js/bindings/JSFunction.zig b/src/bun.js/bindings/JSFunction.zig index 8646541826..9e4ede4e1a 100644 --- a/src/bun.js/bindings/JSFunction.zig +++ b/src/bun.js/bindings/JSFunction.zig @@ -30,7 +30,7 @@ pub const JSFunction = opaque { pub fn create( global: *JSGlobalObject, fn_name: anytype, - comptime implementation: JSC.JSHostFnZig, + comptime implementation: jsc.JSHostFnZig, function_length: u32, options: CreateJSFunctionOptions, ) JSValue { @@ -40,7 +40,7 @@ pub const JSFunction = opaque { bun.String => fn_name, else => bun.String.init(fn_name), }, - JSC.toJSHostFn(implementation), + jsc.toJSHostFn(implementation), function_length, options.implementation_visibility, options.intrinsic, @@ -64,8 +64,8 @@ pub const JSFunction = opaque { const bun = @import("bun"); const String = bun.String; -const JSC = bun.JSC; -const JSGlobalObject = JSC.JSGlobalObject; -const JSHostFn = JSC.JSHostFn; -const JSValue = JSC.JSValue; -const ZigString = JSC.ZigString; +const jsc = bun.jsc; +const JSGlobalObject = jsc.JSGlobalObject; +const JSHostFn = jsc.JSHostFn; +const JSValue = jsc.JSValue; +const ZigString = jsc.ZigString; diff --git a/src/bun.js/bindings/JSGlobalObject.zig b/src/bun.js/bindings/JSGlobalObject.zig index c045fa4e8c..dee6115d8f 100644 --- a/src/bun.js/bindings/JSGlobalObject.zig +++ b/src/bun.js/bindings/JSGlobalObject.zig @@ -60,11 +60,11 @@ pub const JSGlobalObject = opaque { comptime name_: []const u8, comptime field: []const u8, comptime typename: []const u8, - ) JSC.JSValue { + ) jsc.JSValue { return this.ERR(.INVALID_ARG_TYPE, comptime std.fmt.comptimePrint("Expected {s} to be a {s} for '{s}'.", .{ field, typename, name_ }), .{}).toJS(); } - pub fn toJS(this: *JSC.JSGlobalObject, value: anytype) bun.JSError!JSC.JSValue { + pub fn toJS(this: *jsc.JSGlobalObject, value: anytype) bun.JSError!jsc.JSValue { return .fromAny(this, @TypeOf(value), value); } @@ -211,7 +211,7 @@ pub const JSGlobalObject = opaque { comptime name_: []const u8, comptime expected: usize, got: usize, - ) JSC.JSValue { + ) jsc.JSValue { return this.toTypeError(.MISSING_ARGS, "Not enough arguments to '" ++ name_ ++ "'. Expected {d}, got {d}.", .{ expected, got }); } @@ -226,7 +226,7 @@ pub const JSGlobalObject = opaque { } extern fn JSC__JSGlobalObject__reload(JSC__JSGlobalObject__ptr: *JSGlobalObject) void; - pub fn reload(this: *JSC.JSGlobalObject) void { + pub fn reload(this: *jsc.JSGlobalObject) void { this.vm().drainMicrotasks(); this.vm().collectAsync(); @@ -238,18 +238,18 @@ pub const JSGlobalObject = opaque { node = 1, browser = 2, }; - extern fn Bun__runOnLoadPlugins(*JSC.JSGlobalObject, ?*const bun.String, *const bun.String, BunPluginTarget) JSValue; - extern fn Bun__runOnResolvePlugins(*JSC.JSGlobalObject, ?*const bun.String, *const bun.String, *const String, BunPluginTarget) JSValue; + extern fn Bun__runOnLoadPlugins(*jsc.JSGlobalObject, ?*const bun.String, *const bun.String, BunPluginTarget) JSValue; + extern fn Bun__runOnResolvePlugins(*jsc.JSGlobalObject, ?*const bun.String, *const bun.String, *const String, BunPluginTarget) JSValue; pub fn runOnLoadPlugins(this: *JSGlobalObject, namespace_: bun.String, path: bun.String, target: BunPluginTarget) bun.JSError!?JSValue { - JSC.markBinding(@src()); + jsc.markBinding(@src()); const result = try bun.jsc.fromJSHostCall(this, @src(), Bun__runOnLoadPlugins, .{ this, if (namespace_.length() > 0) &namespace_ else null, &path, target }); if (result.isUndefinedOrNull()) return null; return result; } pub fn runOnResolvePlugins(this: *JSGlobalObject, namespace_: bun.String, path: bun.String, source: bun.String, target: BunPluginTarget) bun.JSError!?JSValue { - JSC.markBinding(@src()); + jsc.markBinding(@src()); const result = try bun.jsc.fromJSHostCall(this, @src(), Bun__runOnResolvePlugins, .{ this, if (namespace_.length() > 0) &namespace_ else null, &path, &source, target }); if (result.isUndefinedOrNull()) return null; return result; @@ -292,7 +292,7 @@ pub const JSGlobalObject = opaque { } } - pub fn createDOMExceptionInstance(this: *JSGlobalObject, code: JSC.WebCore.DOMExceptionCode, comptime fmt: [:0]const u8, args: anytype) JSError!JSValue { + pub fn createDOMExceptionInstance(this: *JSGlobalObject, code: jsc.WebCore.DOMExceptionCode, comptime fmt: [:0]const u8, args: anytype) JSError!JSValue { if (comptime std.meta.fieldNames(@TypeOf(args)).len > 0) { var stack_fallback = std.heap.stackFallback(1024 * 4, this.allocator()); var buf = try bun.MutableString.init2048(stack_fallback.get()); @@ -336,29 +336,29 @@ pub const JSGlobalObject = opaque { pub fn createRangeError(this: *JSGlobalObject, comptime fmt: [:0]const u8, args: anytype) JSValue { const err = createErrorInstance(this, fmt, args); - err.put(this, ZigString.static("code"), ZigString.static(@tagName(JSC.Node.ErrorCode.ERR_OUT_OF_RANGE)).toJS(this)); + err.put(this, ZigString.static("code"), ZigString.static(@tagName(jsc.Node.ErrorCode.ERR_OUT_OF_RANGE)).toJS(this)); return err; } pub fn createInvalidArgs(this: *JSGlobalObject, comptime fmt: [:0]const u8, args: anytype) JSValue { - return JSC.Error.INVALID_ARG_TYPE.fmt(this, fmt, args); + return jsc.Error.INVALID_ARG_TYPE.fmt(this, fmt, args); } pub const SysErrOptions = struct { - code: JSC.Node.ErrorCode, + code: jsc.Node.ErrorCode, errno: ?i32 = null, name: ?string = null, }; pub fn throwSysError( this: *JSGlobalObject, opts: SysErrOptions, - comptime message: bun.stringZ, + comptime message: [:0]const u8, args: anytype, ) JSError { const err = createErrorInstance(this, message, args); err.put(this, ZigString.static("code"), ZigString.init(@tagName(opts.code)).toJS(this)); if (opts.name) |name| err.put(this, ZigString.static("name"), ZigString.init(name).toJS(this)); - if (opts.errno) |errno| err.put(this, ZigString.static("errno"), try JSC.toJS(this, i32, errno)); + if (opts.errno) |errno| err.put(this, ZigString.static("errno"), try jsc.toJS(this, i32, errno)); return this.throwValue(err); } @@ -382,7 +382,7 @@ pub const JSGlobalObject = opaque { ctx_val: anytype, comptime Function: fn (ctx: @TypeOf(ctx_val)) void, ) void { - JSC.markBinding(@src()); + jsc.markBinding(@src()); const Fn = Function; const ContextType = @TypeOf(ctx_val); const Wrapper = struct { @@ -394,7 +394,7 @@ pub const JSGlobalObject = opaque { JSC__JSGlobalObject__queueMicrotaskCallback(this, ctx_val, &Wrapper.call); } - pub fn queueMicrotask(this: *JSGlobalObject, function: JSValue, args: []const JSC.JSValue) void { + pub fn queueMicrotask(this: *JSGlobalObject, function: JSValue, args: []const jsc.JSValue) void { this.queueMicrotaskJob( function, if (args.len > 0) args[0] else .zero, @@ -412,7 +412,7 @@ pub const JSGlobalObject = opaque { JSC__JSGlobalObject__queueMicrotaskJob(this, function, first, second); } - pub fn throwValue(this: *JSGlobalObject, value: JSC.JSValue) JSError { + pub fn throwValue(this: *JSGlobalObject, value: jsc.JSValue) JSError { return this.vm().throwError(this, value); } @@ -421,7 +421,7 @@ pub const JSGlobalObject = opaque { return this.throwValue(instance); } - pub fn throwDOMException(this: *JSGlobalObject, code: JSC.WebCore.DOMExceptionCode, comptime fmt: [:0]const u8, args: anytype) bun.JSError { + pub fn throwDOMException(this: *JSGlobalObject, code: jsc.WebCore.DOMExceptionCode, comptime fmt: [:0]const u8, args: anytype) bun.JSError { const instance = try this.createDOMExceptionInstance(code, fmt, args); return this.throwValue(instance); } @@ -552,19 +552,19 @@ pub const JSGlobalObject = opaque { return JSC__JSGlobalObject__bunVM(this); } - pub fn bunVM(this: *JSGlobalObject) *JSC.VirtualMachine { + pub fn bunVM(this: *JSGlobalObject) *jsc.VirtualMachine { if (comptime bun.Environment.allow_assert) { // if this fails // you most likely need to run // make clean-jsc-bindings // make bindings -j10 - if (JSC.VirtualMachine.VMHolder.vm) |vm_| { + if (jsc.VirtualMachine.VMHolder.vm) |vm_| { bun.assert(this.bunVMUnsafe() == @as(*anyopaque, @ptrCast(vm_))); } else { @panic("This thread lacks a Bun VM"); } } - return @as(*JSC.VirtualMachine, @ptrCast(@alignCast(this.bunVMUnsafe()))); + return @as(*jsc.VirtualMachine, @ptrCast(@alignCast(this.bunVMUnsafe()))); } pub const ThreadKind = enum { @@ -572,10 +572,10 @@ pub const JSGlobalObject = opaque { other, }; - pub fn tryBunVM(this: *JSGlobalObject) struct { *JSC.VirtualMachine, ThreadKind } { - const vmPtr = @as(*JSC.VirtualMachine, @ptrCast(@alignCast(this.bunVMUnsafe()))); + pub fn tryBunVM(this: *JSGlobalObject) struct { *jsc.VirtualMachine, ThreadKind } { + const vmPtr = @as(*jsc.VirtualMachine, @ptrCast(@alignCast(this.bunVMUnsafe()))); - if (JSC.VirtualMachine.VMHolder.vm) |vm_| { + if (jsc.VirtualMachine.VMHolder.vm) |vm_| { if (comptime bun.Environment.allow_assert) { bun.assert(this.bunVMUnsafe() == @as(*anyopaque, @ptrCast(vm_))); } @@ -587,8 +587,8 @@ pub const JSGlobalObject = opaque { } /// We can't do the threadlocal check when queued from another thread - pub fn bunVMConcurrently(this: *JSGlobalObject) *JSC.VirtualMachine { - return @as(*JSC.VirtualMachine, @ptrCast(@alignCast(this.bunVMUnsafe()))); + pub fn bunVMConcurrently(this: *JSGlobalObject) *jsc.VirtualMachine { + return @as(*jsc.VirtualMachine, @ptrCast(@alignCast(this.bunVMUnsafe()))); } extern fn JSC__JSGlobalObject__handleRejectedPromises(*JSGlobalObject) void; @@ -661,8 +661,8 @@ pub const JSGlobalObject = opaque { } pub const IntegerRange = struct { - min: comptime_int = JSC.MIN_SAFE_INTEGER, - max: comptime_int = JSC.MAX_SAFE_INTEGER, + min: comptime_int = jsc.MIN_SAFE_INTEGER, + max: comptime_int = jsc.MAX_SAFE_INTEGER, field_name: []const u8 = "", always_allow_zero: bool = false, }; @@ -672,8 +672,8 @@ pub const JSGlobalObject = opaque { return default; } - const min_t = comptime @max(range.min, std.math.minInt(T), JSC.MIN_SAFE_INTEGER); - const max_t = comptime @min(range.max, std.math.maxInt(T), JSC.MAX_SAFE_INTEGER); + const min_t = comptime @max(range.min, std.math.minInt(T), jsc.MIN_SAFE_INTEGER); + const max_t = comptime @min(range.max, std.math.maxInt(T), jsc.MAX_SAFE_INTEGER); comptime { if (min_t > max_t) { @@ -741,16 +741,16 @@ pub const JSGlobalObject = opaque { // when querying from JavaScript, 'func.len' comptime argument_count: u32, ) JSValue { - return JSC.host_fn.NewRuntimeFunction(global, ZigString.static(display_name), argument_count, JSC.toJSHostFn(function), false, false, null); + return jsc.host_fn.NewRuntimeFunction(global, ZigString.static(display_name), argument_count, jsc.toJSHostFn(function), false, false, null); } /// Get a lazily-initialized `JSC::String` from `BunCommonStrings.h`. - pub inline fn commonStrings(this: *JSC.JSGlobalObject) CommonStrings { - JSC.markBinding(@src()); + pub inline fn commonStrings(this: *jsc.JSGlobalObject) CommonStrings { + jsc.markBinding(@src()); return .{ .globalObject = this }; } - pub fn ERR(global: *JSGlobalObject, comptime code: JSC.Error, comptime fmt: [:0]const u8, args: anytype) @import("ErrorCode").ErrorBuilder(code, fmt, @TypeOf(args)) { + pub fn ERR(global: *JSGlobalObject, comptime code: jsc.Error, comptime fmt: [:0]const u8, args: anytype) @import("ErrorCode").ErrorBuilder(code, fmt, @TypeOf(args)) { return .{ .global = global, .args = args }; } @@ -767,7 +767,7 @@ pub const JSGlobalObject = opaque { extern fn Zig__GlobalObject__create(*anyopaque, i32, bool, bool, ?*anyopaque) *JSGlobalObject; pub fn create( - v: *JSC.VirtualMachine, + v: *jsc.VirtualMachine, console: *anyopaque, context_id: i32, mini_mode: bool, @@ -797,35 +797,35 @@ pub const JSGlobalObject = opaque { } pub fn resolve(res: *ErrorableString, global: *JSGlobalObject, specifier: *bun.String, source: *bun.String, query: *ZigString) callconv(.C) void { - JSC.markBinding(@src()); - return JSC.VirtualMachine.resolve(res, global, specifier.*, source.*, query, true) catch { + jsc.markBinding(@src()); + return jsc.VirtualMachine.resolve(res, global, specifier.*, source.*, query, true) catch { bun.debugAssert(res.success == false); }; } - pub fn reportUncaughtException(global: *JSGlobalObject, exception: *JSC.Exception) callconv(.C) JSValue { - JSC.markBinding(@src()); - return JSC.VirtualMachine.reportUncaughtException(global, exception); + pub fn reportUncaughtException(global: *JSGlobalObject, exception: *jsc.Exception) callconv(.C) JSValue { + jsc.markBinding(@src()); + return jsc.VirtualMachine.reportUncaughtException(global, exception); } pub fn reportUncaughtExceptionFromError(global: *JSGlobalObject, proof: bun.JSError) void { - JSC.markBinding(@src()); + jsc.markBinding(@src()); _ = global.reportUncaughtException(global.takeException(proof).asException(global.vm()).?); } pub fn onCrash() callconv(.C) void { - JSC.markBinding(@src()); + jsc.markBinding(@src()); bun.Output.flush(); @panic("A C++ exception occurred"); } pub fn createError( - globalThis: *JSC.JSGlobalObject, + globalThis: *jsc.JSGlobalObject, comptime fmt: string, args: anytype, - ) JSC.JSValue { + ) jsc.JSValue { if (comptime std.meta.fields(@TypeOf(args)).len == 0) { - var zig_str = JSC.ZigString.init(fmt); + var zig_str = jsc.ZigString.init(fmt); if (comptime !strings.isAllASCII(fmt)) { zig_str.markUTF16(); } @@ -836,7 +836,7 @@ pub const JSGlobalObject = opaque { var alloc = fallback.get(); const buf = std.fmt.allocPrint(alloc, fmt, args) catch unreachable; - var zig_str = JSC.ZigString.init(buf); + var zig_str = jsc.ZigString.init(buf); zig_str.detectEncoding(); // it alwayas clones const res = zig_str.toErrorInstance(globalThis); @@ -846,26 +846,26 @@ pub const JSGlobalObject = opaque { } pub fn toTypeError( - global: *JSC.JSGlobalObject, - code: JSC.Error, + global: *jsc.JSGlobalObject, + code: jsc.Error, comptime fmt: [:0]const u8, args: anytype, - ) JSC.JSValue { + ) jsc.JSValue { return code.fmt(global, fmt, args); } pub fn toInvalidArguments( - global: *JSC.JSGlobalObject, + global: *jsc.JSGlobalObject, comptime fmt: [:0]const u8, args: anytype, - ) JSC.JSValue { + ) jsc.JSValue { @branchHint(.cold); - return JSC.Error.INVALID_ARG_TYPE.fmt(global, fmt, args); + return jsc.Error.INVALID_ARG_TYPE.fmt(global, fmt, args); } - extern fn ScriptExecutionContextIdentifier__forGlobalObject(global: *JSC.JSGlobalObject) u32; + extern fn ScriptExecutionContextIdentifier__forGlobalObject(global: *jsc.JSGlobalObject) u32; - pub fn scriptExecutionContextIdentifier(global: *JSC.JSGlobalObject) bun.webcore.ScriptExecutionContext.Identifier { + pub fn scriptExecutionContextIdentifier(global: *jsc.JSGlobalObject) bun.webcore.ScriptExecutionContext.Identifier { return @enumFromInt(ScriptExecutionContextIdentifier__forGlobalObject(global)); } @@ -878,6 +878,8 @@ pub const JSGlobalObject = opaque { } }; +const string = []const u8; + const napi = @import("../../napi/napi.zig"); const std = @import("std"); @@ -886,12 +888,11 @@ const JSError = bun.JSError; const MutableString = bun.MutableString; const Output = bun.Output; const String = bun.String; -const string = bun.string; const strings = bun.strings; -const JSC = bun.JSC; -const CommonStrings = JSC.CommonStrings; -const ErrorableString = JSC.ErrorableString; -const JSValue = JSC.JSValue; -const VM = JSC.VM; -const ZigString = JSC.ZigString; +const jsc = bun.jsc; +const CommonStrings = jsc.CommonStrings; +const ErrorableString = jsc.ErrorableString; +const JSValue = jsc.JSValue; +const VM = jsc.VM; +const ZigString = jsc.ZigString; diff --git a/src/bun.js/bindings/JSInternalPromise.zig b/src/bun.js/bindings/JSInternalPromise.zig index 3bae78113a..87742b5055 100644 --- a/src/bun.js/bindings/JSInternalPromise.zig +++ b/src/bun.js/bindings/JSInternalPromise.zig @@ -3,7 +3,7 @@ pub const JSInternalPromise = opaque { extern fn JSC__JSInternalPromise__isHandled(arg0: *const JSInternalPromise, arg1: *VM) bool; extern fn JSC__JSInternalPromise__reject(arg0: *JSInternalPromise, arg1: *JSGlobalObject, JSValue2: JSValue) void; extern fn JSC__JSInternalPromise__rejectAsHandled(arg0: *JSInternalPromise, arg1: *JSGlobalObject, JSValue2: JSValue) void; - extern fn JSC__JSInternalPromise__rejectAsHandledException(arg0: *JSInternalPromise, arg1: *JSGlobalObject, arg2: *JSC.Exception) void; + extern fn JSC__JSInternalPromise__rejectAsHandledException(arg0: *JSInternalPromise, arg1: *JSGlobalObject, arg2: *jsc.Exception) void; extern fn JSC__JSInternalPromise__rejectedPromise(arg0: *JSGlobalObject, JSValue1: JSValue) *JSInternalPromise; extern fn JSC__JSInternalPromise__resolve(arg0: *JSInternalPromise, arg1: *JSGlobalObject, JSValue2: JSValue) void; extern fn JSC__JSInternalPromise__resolvedPromise(arg0: *JSGlobalObject, JSValue1: JSValue) *JSInternalPromise; @@ -64,7 +64,7 @@ pub const JSInternalPromise = opaque { const bun = @import("bun"); const JSPromise = @import("./JSPromise.zig").JSPromise; -const JSC = bun.JSC; -const JSGlobalObject = JSC.JSGlobalObject; -const JSValue = JSC.JSValue; -const VM = JSC.VM; +const jsc = bun.jsc; +const JSGlobalObject = jsc.JSGlobalObject; +const JSValue = jsc.JSValue; +const VM = jsc.VM; diff --git a/src/bun.js/bindings/JSMap.zig b/src/bun.js/bindings/JSMap.zig index ea05be9815..5c4ce35be9 100644 --- a/src/bun.js/bindings/JSMap.zig +++ b/src/bun.js/bindings/JSMap.zig @@ -40,6 +40,6 @@ pub const JSMap = opaque { const bun = @import("bun"); -const JSC = bun.JSC; -const JSGlobalObject = JSC.JSGlobalObject; -const JSValue = JSC.JSValue; +const jsc = bun.jsc; +const JSGlobalObject = jsc.JSGlobalObject; +const JSValue = jsc.JSValue; diff --git a/src/bun.js/bindings/JSModuleLoader.zig b/src/bun.js/bindings/JSModuleLoader.zig index 44e2b4e991..e82b18eb60 100644 --- a/src/bun.js/bindings/JSModuleLoader.zig +++ b/src/bun.js/bindings/JSModuleLoader.zig @@ -50,6 +50,6 @@ const JSInternalPromise = @import("./JSInternalPromise.zig").JSInternalPromise; const bun = @import("bun"); const String = bun.String; -const JSC = bun.JSC; -const JSGlobalObject = JSC.JSGlobalObject; -const JSValue = JSC.JSValue; +const jsc = bun.jsc; +const JSGlobalObject = jsc.JSGlobalObject; +const JSValue = jsc.JSValue; diff --git a/src/bun.js/bindings/JSObject.zig b/src/bun.js/bindings/JSObject.zig index cfcade0012..17d46a704d 100644 --- a/src/bun.js/bindings/JSObject.zig +++ b/src/bun.js/bindings/JSObject.zig @@ -8,7 +8,7 @@ pub const JSObject = opaque { extern fn JSC__JSObject__getIndex(this: JSValue, globalThis: *JSGlobalObject, i: u32) JSValue; extern fn JSC__JSObject__putRecord(this: *JSObject, global: *JSGlobalObject, key: *ZigString, values: [*]ZigString, len: usize) void; extern fn Bun__JSObject__getCodePropertyVMInquiry(global: *JSGlobalObject, obj: *JSObject) JSValue; - extern fn JSC__createStructure(global: *JSC.JSGlobalObject, owner: *JSC.JSCell, length: u32, names: [*]ExternColumnIdentifier) JSC.JSValue; + extern fn JSC__createStructure(global: *jsc.JSGlobalObject, owner: *jsc.JSCell, length: u32, names: [*]ExternColumnIdentifier) jsc.JSValue; extern fn JSC__JSObject__create(global_object: *JSGlobalObject, length: usize, ctx: *anyopaque, initializer: InitializeCallback) JSValue; pub fn toJS(obj: *JSObject) JSValue { @@ -17,7 +17,7 @@ pub const JSObject = opaque { /// Marshall a struct instance into a JSObject, copying its properties. /// - /// Each field will be encoded with `JSC.toJS`. Fields whose types have a + /// Each field will be encoded with `jsc.toJS`. Fields whose types have a /// `toJS` method will have it called to encode. /// /// This method is equivalent to `Object.create(...)` + setting properties, @@ -28,7 +28,7 @@ pub const JSObject = opaque { /// Marshall a struct into a JSObject, copying its properties. It's /// `__proto__` will be `null`. /// - /// Each field will be encoded with `JSC.toJS`. Fields whose types have a + /// Each field will be encoded with `jsc.toJS`. Fields whose types have a /// `toJS` method will have it called to encode. /// /// This is roughly equivalent to creating an object with @@ -39,7 +39,7 @@ pub const JSObject = opaque { /// Marshall a struct instance into a JSObject. `pojo` is borrowed. /// - /// Each field will be encoded with `JSC.toJS`. Fields whose types have a + /// Each field will be encoded with `jsc.toJS`. Fields whose types have a /// `toJS` method will have it called to encode. /// /// This method is equivalent to `Object.create(...)` + setting properties, @@ -68,7 +68,7 @@ pub const JSObject = opaque { cell.put( global, field.name, - try JSC.toJS(global, @TypeOf(property), property), + try jsc.toJS(global, @TypeOf(property), property), ); } @@ -116,8 +116,8 @@ pub const JSObject = opaque { } }; - pub fn createStructure(global: *JSGlobalObject, owner: JSC.JSValue, length: u32, names: [*]ExternColumnIdentifier) JSValue { - JSC.markBinding(@src()); + pub fn createStructure(global: *JSGlobalObject, owner: jsc.JSValue, length: u32, names: [*]ExternColumnIdentifier) JSValue { + jsc.markBinding(@src()); return JSC__createStructure(global, owner.asCell(), length, names); } @@ -141,7 +141,7 @@ pub const JSObject = opaque { // then the JSValue is zero. the function this ends up calling can return undefined // with an exception: // https://github.com/oven-sh/WebKit/blob/397dafc9721b8f8046f9448abb6dbc14efe096d3/Source/JavaScriptCore/runtime/JSObjectInlines.h#L112 - var scope: JSC.CatchScope = undefined; + var scope: jsc.CatchScope = undefined; scope.init(globalThis, @src()); defer scope.deinit(); const value = JSC__JSObject__getIndex(this, globalThis, i); @@ -167,7 +167,7 @@ const std = @import("std"); const bun = @import("bun"); const JSError = bun.JSError; -const JSC = bun.JSC; -const JSGlobalObject = JSC.JSGlobalObject; -const JSValue = JSC.JSValue; -const ZigString = JSC.ZigString; +const jsc = bun.jsc; +const JSGlobalObject = jsc.JSGlobalObject; +const JSValue = jsc.JSValue; +const ZigString = jsc.ZigString; diff --git a/src/bun.js/bindings/JSPromise.zig b/src/bun.js/bindings/JSPromise.zig index fcf011dec8..35a581b106 100644 --- a/src/bun.js/bindings/JSPromise.zig +++ b/src/bun.js/bindings/JSPromise.zig @@ -12,46 +12,46 @@ pub const JSPromise = opaque { extern fn JSC__JSPromise__rejectedPromiseValue(arg0: *JSGlobalObject, JSValue1: JSValue) JSValue; extern fn JSC__JSPromise__resolvedPromise(arg0: *JSGlobalObject, JSValue1: JSValue) *JSPromise; extern fn JSC__JSPromise__resolvedPromiseValue(arg0: *JSGlobalObject, JSValue1: JSValue) JSValue; - extern fn JSC__JSPromise__wrap(*JSC.JSGlobalObject, *anyopaque, *const fn (*anyopaque, *JSC.JSGlobalObject) callconv(.C) JSC.JSValue) JSC.JSValue; + extern fn JSC__JSPromise__wrap(*jsc.JSGlobalObject, *anyopaque, *const fn (*anyopaque, *jsc.JSGlobalObject) callconv(.C) jsc.JSValue) jsc.JSValue; pub fn Weak(comptime T: type) type { return struct { - weak: JSC.Weak(T) = .{}, + weak: jsc.Weak(T) = .{}, const WeakType = @This(); - pub fn reject(this: *WeakType, globalThis: *JSC.JSGlobalObject, val: JSC.JSValue) void { + pub fn reject(this: *WeakType, globalThis: *jsc.JSGlobalObject, val: jsc.JSValue) void { this.swap().reject(globalThis, val); } /// Like `reject`, except it drains microtasks at the end of the current event loop iteration. - pub fn rejectTask(this: *WeakType, globalThis: *JSC.JSGlobalObject, val: JSC.JSValue) void { - const loop = JSC.VirtualMachine.get().eventLoop(); + pub fn rejectTask(this: *WeakType, globalThis: *jsc.JSGlobalObject, val: jsc.JSValue) void { + const loop = jsc.VirtualMachine.get().eventLoop(); loop.enter(); defer loop.exit(); this.reject(globalThis, val); } - pub fn resolve(this: *WeakType, globalThis: *JSC.JSGlobalObject, val: JSC.JSValue) void { + pub fn resolve(this: *WeakType, globalThis: *jsc.JSGlobalObject, val: jsc.JSValue) void { this.swap().resolve(globalThis, val); } /// Like `resolve`, except it drains microtasks at the end of the current event loop iteration. - pub fn resolveTask(this: *WeakType, globalThis: *JSC.JSGlobalObject, val: JSC.JSValue) void { - const loop = JSC.VirtualMachine.get().eventLoop(); + pub fn resolveTask(this: *WeakType, globalThis: *jsc.JSGlobalObject, val: jsc.JSValue) void { + const loop = jsc.VirtualMachine.get().eventLoop(); loop.enter(); defer loop.exit(); this.resolve(globalThis, val); } pub fn init( - globalThis: *JSC.JSGlobalObject, + globalThis: *jsc.JSGlobalObject, promise: JSValue, ctx: *T, - comptime finalizer: *const fn (*T, JSC.JSValue) void, + comptime finalizer: *const fn (*T, jsc.JSValue) void, ) WeakType { return WeakType{ - .weak = JSC.Weak(T).create( + .weak = jsc.Weak(T).create( promise, globalThis, ctx, @@ -60,11 +60,11 @@ pub const JSPromise = opaque { }; } - pub fn get(this: *const WeakType) *JSC.JSPromise { + pub fn get(this: *const WeakType) *jsc.JSPromise { return this.weak.get().?.asPromise().?; } - pub fn getOrNull(this: *const WeakType) ?*JSC.JSPromise { + pub fn getOrNull(this: *const WeakType) ?*jsc.JSPromise { const promise_value = this.weak.get() orelse return null; return promise_value.asPromise(); } @@ -77,7 +77,7 @@ pub const JSPromise = opaque { return this.weak.get() orelse .zero; } - pub fn swap(this: *WeakType) *JSC.JSPromise { + pub fn swap(this: *WeakType) *jsc.JSPromise { const prom = this.weak.swap().asPromise().?; this.weak.deinit(); return prom; @@ -91,17 +91,17 @@ pub const JSPromise = opaque { } pub const Strong = struct { - strong: JSC.Strong.Optional = .empty, + strong: jsc.Strong.Optional = .empty, pub const empty: Strong = .{ .strong = .empty }; - pub fn reject(this: *Strong, globalThis: *JSC.JSGlobalObject, val: JSError!JSC.JSValue) void { + pub fn reject(this: *Strong, globalThis: *jsc.JSGlobalObject, val: JSError!jsc.JSValue) void { this.swap().reject(globalThis, val catch globalThis.tryTakeException().?); } /// Like `reject`, except it drains microtasks at the end of the current event loop iteration. - pub fn rejectTask(this: *Strong, globalThis: *JSC.JSGlobalObject, val: JSC.JSValue) void { - const loop = JSC.VirtualMachine.get().eventLoop(); + pub fn rejectTask(this: *Strong, globalThis: *jsc.JSGlobalObject, val: jsc.JSValue) void { + const loop = jsc.VirtualMachine.get().eventLoop(); loop.enter(); defer loop.exit(); @@ -110,28 +110,28 @@ pub const JSPromise = opaque { pub const rejectOnNextTick = @compileError("Either use an event loop task, or you're draining microtasks when you shouldn't be."); - pub fn resolve(this: *Strong, globalThis: *JSC.JSGlobalObject, val: JSC.JSValue) void { + pub fn resolve(this: *Strong, globalThis: *jsc.JSGlobalObject, val: jsc.JSValue) void { this.swap().resolve(globalThis, val); } /// Like `resolve`, except it drains microtasks at the end of the current event loop iteration. - pub fn resolveTask(this: *Strong, globalThis: *JSC.JSGlobalObject, val: JSC.JSValue) void { - const loop = JSC.VirtualMachine.get().eventLoop(); + pub fn resolveTask(this: *Strong, globalThis: *jsc.JSGlobalObject, val: jsc.JSValue) void { + const loop = jsc.VirtualMachine.get().eventLoop(); loop.enter(); defer loop.exit(); this.resolve(globalThis, val); } - pub fn init(globalThis: *JSC.JSGlobalObject) Strong { + pub fn init(globalThis: *jsc.JSGlobalObject) Strong { return Strong{ .strong = .create( - JSC.JSPromise.create(globalThis).toJS(), + jsc.JSPromise.create(globalThis).toJS(), globalThis, ), }; } - pub fn get(this: *const Strong) *JSC.JSPromise { + pub fn get(this: *const Strong) *jsc.JSPromise { return this.strong.get().?.asPromise().?; } @@ -147,7 +147,7 @@ pub const JSPromise = opaque { return this.strong.has(); } - pub fn swap(this: *Strong) *JSC.JSPromise { + pub fn swap(this: *Strong) *jsc.JSPromise { const prom = this.strong.swap().asPromise().?; this.strong.deinit(); return prom; @@ -172,12 +172,12 @@ pub const JSPromise = opaque { const Wrapper = struct { args: Args, - pub fn call(this: *@This(), g: *JSC.JSGlobalObject) callconv(.c) JSC.JSValue { - return JSC.toJSHostCall(g, @src(), Fn, this.args); + pub fn call(this: *@This(), g: *jsc.JSGlobalObject) callconv(.c) jsc.JSValue { + return jsc.toJSHostCall(g, @src(), Fn, this.args); } }; - var scope: JSC.CatchScope = undefined; + var scope: jsc.CatchScope = undefined; scope.init(globalObject, @src()); defer scope.deinit(); var ctx = Wrapper{ .args = args }; @@ -247,7 +247,7 @@ pub const JSPromise = opaque { /// If you want to create a new Promise that is already resolved, see JSPromise.resolvedPromiseValue pub fn resolve(this: *JSPromise, globalThis: *JSGlobalObject, value: JSValue) void { if (comptime bun.Environment.isDebug) { - const loop = JSC.VirtualMachine.get().eventLoop(); + const loop = jsc.VirtualMachine.get().eventLoop(); loop.debug.js_call_count_outside_tick_queue += @as(usize, @intFromBool(!loop.debug.is_inside_tick_queue)); if (loop.debug.track_last_fn_name and !loop.debug.is_inside_tick_queue) { loop.debug.last_fn_name = String.static("resolve"); @@ -259,7 +259,7 @@ pub const JSPromise = opaque { pub fn reject(this: *JSPromise, globalThis: *JSGlobalObject, value: JSError!JSValue) void { if (comptime bun.Environment.isDebug) { - const loop = JSC.VirtualMachine.get().eventLoop(); + const loop = jsc.VirtualMachine.get().eventLoop(); loop.debug.js_call_count_outside_tick_queue += @as(usize, @intFromBool(!loop.debug.is_inside_tick_queue)); if (loop.debug.track_last_fn_name and !loop.debug.is_inside_tick_queue) { loop.debug.last_fn_name = String.static("reject"); @@ -311,7 +311,7 @@ const bun = @import("bun"); const JSError = bun.JSError; const String = bun.String; -const JSC = bun.JSC; -const JSGlobalObject = JSC.JSGlobalObject; -const JSValue = JSC.JSValue; -const VM = JSC.VM; +const jsc = bun.jsc; +const JSGlobalObject = jsc.JSGlobalObject; +const JSValue = jsc.JSValue; +const VM = jsc.VM; diff --git a/src/bun.js/bindings/JSPropertyIterator.zig b/src/bun.js/bindings/JSPropertyIterator.zig index 66f3f39fab..ab3cc81ca6 100644 --- a/src/bun.js/bindings/JSPropertyIterator.zig +++ b/src/bun.js/bindings/JSPropertyIterator.zig @@ -14,10 +14,10 @@ pub fn JSPropertyIterator(comptime options: JSPropertyIteratorOptions) type { /// null if and only if `object` has no properties (i.e. `len == 0`) impl: ?*JSPropertyIteratorImpl = null, - globalObject: *JSC.JSGlobalObject, - object: *JSC.JSObject, + globalObject: *jsc.JSGlobalObject, + object: *jsc.JSObject, // current property being yielded - value: JSC.JSValue = .zero, + value: jsc.JSValue = .zero, pub fn getLongestPropertyName(this: *@This()) usize { return if (this.impl) |iter| @@ -32,7 +32,7 @@ pub fn JSPropertyIterator(comptime options: JSPropertyIteratorOptions) type { } /// `object` should be a `JSC::JSObject`. Non-objects will be runtime converted. - pub fn init(globalObject: *JSC.JSGlobalObject, object: *JSC.JSObject) bun.JSError!@This() { + pub fn init(globalObject: *jsc.JSGlobalObject, object: *jsc.JSObject) bun.JSError!@This() { var len: usize = 0; object.ensureStillAlive(); const impl = try JSPropertyIteratorImpl.init( @@ -78,7 +78,7 @@ pub fn JSPropertyIterator(comptime options: JSPropertyIteratorOptions) type { var name = bun.String.dead; if (comptime options.include_value) { const FnToUse = if (options.observable) JSPropertyIteratorImpl.getNameAndValue else JSPropertyIteratorImpl.getNameAndValueNonObservable; - const current: JSC.JSValue = try FnToUse(this.impl.?, this.globalObject, this.object, &name, i); + const current: jsc.JSValue = try FnToUse(this.impl.?, this.globalObject, this.object, &name, i); if (current == .zero) continue; current.ensureStillAlive(); this.value = current; @@ -107,8 +107,8 @@ pub fn JSPropertyIterator(comptime options: JSPropertyIteratorOptions) type { const JSPropertyIteratorImpl = opaque { pub fn init( - globalObject: *JSC.JSGlobalObject, - object: *JSC.JSObject, + globalObject: *jsc.JSGlobalObject, + object: *jsc.JSObject, count: *usize, own_properties_only: bool, only_non_index_properties: bool, @@ -118,7 +118,7 @@ const JSPropertyIteratorImpl = opaque { pub const deinit = Bun__JSPropertyIterator__deinit; - pub fn getNameAndValue(iter: *JSPropertyIteratorImpl, globalObject: *JSC.JSGlobalObject, object: *JSC.JSObject, propertyName: *bun.String, i: usize) bun.JSError!JSC.JSValue { + pub fn getNameAndValue(iter: *JSPropertyIteratorImpl, globalObject: *jsc.JSGlobalObject, object: *jsc.JSObject, propertyName: *bun.String, i: usize) bun.JSError!jsc.JSValue { var scope: bun.jsc.CatchScope = undefined; scope.init(globalObject, @src()); defer scope.deinit(); @@ -127,7 +127,7 @@ const JSPropertyIteratorImpl = opaque { return value; } - pub fn getNameAndValueNonObservable(iter: *JSPropertyIteratorImpl, globalObject: *JSC.JSGlobalObject, object: *JSC.JSObject, propertyName: *bun.String, i: usize) bun.JSError!JSC.JSValue { + pub fn getNameAndValueNonObservable(iter: *JSPropertyIteratorImpl, globalObject: *jsc.JSGlobalObject, object: *jsc.JSObject, propertyName: *bun.String, i: usize) bun.JSError!jsc.JSValue { var scope: bun.jsc.CatchScope = undefined; scope.init(globalObject, @src()); defer scope.deinit(); @@ -141,13 +141,13 @@ const JSPropertyIteratorImpl = opaque { pub const getLongestPropertyName = Bun__JSPropertyIterator__getLongestPropertyName; /// may return null without an exception - extern "c" fn Bun__JSPropertyIterator__create(globalObject: *JSC.JSGlobalObject, encodedValue: JSC.JSValue, count: *usize, own_properties_only: bool, only_non_index_properties: bool) ?*JSPropertyIteratorImpl; - extern "c" fn Bun__JSPropertyIterator__getNameAndValue(iter: *JSPropertyIteratorImpl, globalObject: *JSC.JSGlobalObject, object: *JSC.JSObject, propertyName: *bun.String, i: usize) JSC.JSValue; - extern "c" fn Bun__JSPropertyIterator__getNameAndValueNonObservable(iter: *JSPropertyIteratorImpl, globalObject: *JSC.JSGlobalObject, object: *JSC.JSObject, propertyName: *bun.String, i: usize) JSC.JSValue; + extern "c" fn Bun__JSPropertyIterator__create(globalObject: *jsc.JSGlobalObject, encodedValue: jsc.JSValue, count: *usize, own_properties_only: bool, only_non_index_properties: bool) ?*JSPropertyIteratorImpl; + extern "c" fn Bun__JSPropertyIterator__getNameAndValue(iter: *JSPropertyIteratorImpl, globalObject: *jsc.JSGlobalObject, object: *jsc.JSObject, propertyName: *bun.String, i: usize) jsc.JSValue; + extern "c" fn Bun__JSPropertyIterator__getNameAndValueNonObservable(iter: *JSPropertyIteratorImpl, globalObject: *jsc.JSGlobalObject, object: *jsc.JSObject, propertyName: *bun.String, i: usize) jsc.JSValue; extern "c" fn Bun__JSPropertyIterator__getName(iter: *JSPropertyIteratorImpl, propertyName: *bun.String, i: usize) void; extern "c" fn Bun__JSPropertyIterator__deinit(iter: *JSPropertyIteratorImpl) void; - extern "c" fn Bun__JSPropertyIterator__getLongestPropertyName(iter: *JSPropertyIteratorImpl, globalObject: *JSC.JSGlobalObject, object: *JSC.JSObject) usize; + extern "c" fn Bun__JSPropertyIterator__getLongestPropertyName(iter: *JSPropertyIteratorImpl, globalObject: *jsc.JSGlobalObject, object: *jsc.JSObject) usize; }; const bun = @import("bun"); -const JSC = bun.JSC; +const jsc = bun.jsc; diff --git a/src/bun.js/bindings/JSRef.zig b/src/bun.js/bindings/JSRef.zig index 70fe4cb704..a4f079b98d 100644 --- a/src/bun.js/bindings/JSRef.zig +++ b/src/bun.js/bindings/JSRef.zig @@ -1,13 +1,13 @@ pub const JSRef = union(enum) { - weak: JSC.JSValue, - strong: JSC.Strong.Optional, + weak: jsc.JSValue, + strong: jsc.Strong.Optional, finalized: void, - pub fn initWeak(value: JSC.JSValue) @This() { + pub fn initWeak(value: jsc.JSValue) @This() { return .{ .weak = value }; } - pub fn initStrong(value: JSC.JSValue, globalThis: *JSC.JSGlobalObject) @This() { + pub fn initStrong(value: jsc.JSValue, globalThis: *jsc.JSGlobalObject) @This() { return .{ .strong = .create(value, globalThis) }; } @@ -15,7 +15,7 @@ pub const JSRef = union(enum) { return .{ .weak = .zero }; } - pub fn get(this: *@This()) JSC.JSValue { + pub fn get(this: *@This()) jsc.JSValue { return switch (this.*) { .weak => this.weak, .strong => this.strong.get() orelse .zero, @@ -23,14 +23,14 @@ pub const JSRef = union(enum) { }; } - pub fn tryGet(this: *@This()) ?JSC.JSValue { + pub fn tryGet(this: *@This()) ?jsc.JSValue { return switch (this.*) { .weak => if (this.weak != .zero) this.weak else null, .strong => this.strong.get(), .finalized => null, }; } - pub fn setWeak(this: *@This(), value: JSC.JSValue) void { + pub fn setWeak(this: *@This(), value: jsc.JSValue) void { switch (this.*) { .weak => {}, .strong => { @@ -43,7 +43,7 @@ pub const JSRef = union(enum) { this.* = .{ .weak = value }; } - pub fn setStrong(this: *@This(), value: JSC.JSValue, globalThis: *JSC.JSGlobalObject) void { + pub fn setStrong(this: *@This(), value: jsc.JSValue, globalThis: *jsc.JSGlobalObject) void { if (this.* == .strong) { this.strong.set(globalThis, value); return; @@ -51,7 +51,7 @@ pub const JSRef = union(enum) { this.* = .{ .strong = .create(value, globalThis) }; } - pub fn upgrade(this: *@This(), globalThis: *JSC.JSGlobalObject) void { + pub fn upgrade(this: *@This(), globalThis: *jsc.JSGlobalObject) void { switch (this.*) { .weak => { bun.assert(this.weak != .zero); @@ -79,5 +79,5 @@ pub const JSRef = union(enum) { const bun = @import("bun"); -const JSC = bun.JSC; -const JSValue = JSC.JSValue; +const jsc = bun.jsc; +const JSValue = jsc.JSValue; diff --git a/src/bun.js/bindings/JSString.zig b/src/bun.js/bindings/JSString.zig index 1c40888617..35af854c16 100644 --- a/src/bun.js/bindings/JSString.zig +++ b/src/bun.js/bindings/JSString.zig @@ -1,6 +1,6 @@ pub const JSString = opaque { extern fn JSC__JSString__toObject(this: *JSString, global: *JSGlobalObject) ?*JSObject; - extern fn JSC__JSString__toZigString(this: *JSString, global: *JSGlobalObject, zig_str: *JSC.ZigString) void; + extern fn JSC__JSString__toZigString(this: *JSString, global: *JSGlobalObject, zig_str: *jsc.ZigString) void; extern fn JSC__JSString__eql(this: *const JSString, global: *JSGlobalObject, other: *JSString) bool; extern fn JSC__JSString__iterator(this: *JSString, globalObject: *JSGlobalObject, iter: *anyopaque) void; extern fn JSC__JSString__length(this: *const JSString) usize; @@ -14,7 +14,7 @@ pub const JSString = opaque { return JSC__JSString__toObject(this, global); } - pub fn toZigString(this: *JSString, global: *JSGlobalObject, zig_str: *JSC.ZigString) void { + pub fn toZigString(this: *JSString, global: *JSGlobalObject, zig_str: *jsc.ZigString) void { return JSC__JSString__toZigString(this, global, zig_str); } @@ -22,8 +22,8 @@ pub const JSString = opaque { std.mem.doNotOptimizeAway(this); } - pub fn getZigString(this: *JSString, global: *JSGlobalObject) JSC.ZigString { - var out = JSC.ZigString.init(""); + pub fn getZigString(this: *JSString, global: *JSGlobalObject) jsc.ZigString { + var out = jsc.ZigString.init(""); this.toZigString(global, &out); return out; } @@ -98,6 +98,6 @@ const ZigString = @import("./ZigString.zig").ZigString; const bun = @import("bun"); const JSError = bun.JSError; -const JSC = bun.JSC; -const JSGlobalObject = JSC.JSGlobalObject; -const JSValue = JSC.JSValue; +const jsc = bun.jsc; +const JSGlobalObject = jsc.JSGlobalObject; +const JSValue = jsc.JSValue; diff --git a/src/bun.js/bindings/JSUint8Array.zig b/src/bun.js/bindings/JSUint8Array.zig index 84ca9be661..110be156c6 100644 --- a/src/bun.js/bindings/JSUint8Array.zig +++ b/src/bun.js/bindings/JSUint8Array.zig @@ -11,13 +11,13 @@ pub const JSUint8Array = opaque { return this.ptr()[0..this.len()]; } - extern fn JSUint8Array__fromDefaultAllocator(*JSC.JSGlobalObject, ptr: [*]u8, len: usize) JSC.JSValue; + extern fn JSUint8Array__fromDefaultAllocator(*jsc.JSGlobalObject, ptr: [*]u8, len: usize) jsc.JSValue; /// *bytes* must come from bun.default_allocator - pub fn fromBytes(globalThis: *JSGlobalObject, bytes: []u8) JSC.JSValue { + pub fn fromBytes(globalThis: *JSGlobalObject, bytes: []u8) jsc.JSValue { return JSUint8Array__fromDefaultAllocator(globalThis, bytes.ptr, bytes.len); } - extern fn Bun__createUint8ArrayForCopy(*JSC.JSGlobalObject, ptr: ?*const anyopaque, len: usize, buffer: bool) JSValue; + extern fn Bun__createUint8ArrayForCopy(*jsc.JSGlobalObject, ptr: ?*const anyopaque, len: usize, buffer: bool) JSValue; pub fn fromBytesCopy(globalThis: *JSGlobalObject, bytes: []const u8) JSValue { return Bun__createUint8ArrayForCopy(globalThis, bytes.ptr, bytes.len, false); } @@ -30,6 +30,6 @@ pub const JSUint8Array = opaque { const Sizes = @import("./sizes.zig"); const bun = @import("bun"); -const JSC = bun.JSC; -const JSGlobalObject = JSC.JSGlobalObject; -const JSValue = JSC.JSValue; +const jsc = bun.jsc; +const JSGlobalObject = jsc.JSGlobalObject; +const JSValue = jsc.JSValue; diff --git a/src/bun.js/bindings/JSValue.zig b/src/bun.js/bindings/JSValue.zig index c06cd3051c..c3d3ad518a 100644 --- a/src/bun.js/bindings/JSValue.zig +++ b/src/bun.js/bindings/JSValue.zig @@ -16,7 +16,7 @@ pub const JSValue = enum(i64) { /// this value except in the return value of `JSC__JSValue__getIfPropertyExistsImpl` /// and `JSC__JSValue__fastGet` /// - /// Deleted is a special encoding used in JSC hash map internals used for + /// Deleted is a special encoding used in jsc hash map internals used for /// the null state. It is re-used here for encoding the "not present" state /// in `JSC__JSValue__getIfPropertyExistsImpl` property_does_not_exist_on_object = 0x4, @@ -29,16 +29,16 @@ pub const JSValue = enum(i64) { return @as(JSValue, @enumFromInt(@as(i64, @bitCast(@intFromPtr(ptr))))); } - pub fn coerceToInt32(this: JSValue, globalThis: *JSC.JSGlobalObject) bun.JSError!i32 { + pub fn coerceToInt32(this: JSValue, globalThis: *jsc.JSGlobalObject) bun.JSError!i32 { return bun.cpp.JSC__JSValue__coerceToInt32(this, globalThis); } - pub fn coerceToInt64(this: JSValue, globalThis: *JSC.JSGlobalObject) bun.JSError!i64 { + pub fn coerceToInt64(this: JSValue, globalThis: *jsc.JSGlobalObject) bun.JSError!i64 { return bun.cpp.JSC__JSValue__coerceToInt64(this, globalThis); } pub fn getIndex(this: JSValue, globalThis: *JSGlobalObject, i: u32) JSError!JSValue { - return JSC.JSObject.getIndex(this, globalThis, i); + return jsc.JSObject.getIndex(this, globalThis, i); } extern fn JSC__JSValue__getDirectIndex(JSValue, *JSGlobalObject, u32) JSValue; @@ -67,7 +67,7 @@ pub const JSValue = enum(i64) { pub fn forEachPropertyNonIndexed( this: JSValue, - globalThis: *JSC.JSGlobalObject, + globalThis: *jsc.JSGlobalObject, ctx: ?*anyopaque, callback: PropertyIteratorFn, ) JSError!void { @@ -76,7 +76,7 @@ pub const JSValue = enum(i64) { pub fn forEachProperty( this: JSValue, - globalThis: *JSC.JSGlobalObject, + globalThis: *jsc.JSGlobalObject, ctx: ?*anyopaque, callback: PropertyIteratorFn, ) JSError!void { @@ -85,7 +85,7 @@ pub const JSValue = enum(i64) { pub fn forEachPropertyOrdered( this: JSValue, - globalThis: *JSC.JSGlobalObject, + globalThis: *jsc.JSGlobalObject, ctx: ?*anyopaque, callback: PropertyIteratorFn, ) JSError!void { @@ -126,10 +126,10 @@ pub const JSValue = enum(i64) { return false; } const d = this.asDouble(); - return @trunc(d) == d and @abs(d) <= JSC.MAX_SAFE_INTEGER; + return @trunc(d) == d and @abs(d) <= jsc.MAX_SAFE_INTEGER; } - pub fn coerce(this: JSValue, comptime T: type, globalThis: *JSC.JSGlobalObject) bun.JSError!T { + pub fn coerce(this: JSValue, comptime T: type, globalThis: *jsc.JSGlobalObject) bun.JSError!T { return switch (T) { f64 => { if (this.isDouble()) { @@ -193,18 +193,18 @@ pub const JSValue = enum(i64) { if (this.isNumber()) { const double = try this.toNumber(global); if (std.math.isNan(double)) { - return JSC.Error.SOCKET_BAD_PORT.throw(global, "Invalid port number", .{}); + return jsc.Error.SOCKET_BAD_PORT.throw(global, "Invalid port number", .{}); } const port = this.to(i64); if (0 <= port and port <= 65535) { return @as(u16, @truncate(@max(0, port))); } else { - return JSC.Error.SOCKET_BAD_PORT.throw(global, "Port number out of range: {d}", .{port}); + return jsc.Error.SOCKET_BAD_PORT.throw(global, "Port number out of range: {d}", .{port}); } } - return JSC.Error.SOCKET_BAD_PORT.throw(global, "Invalid port number", .{}); + return jsc.Error.SOCKET_BAD_PORT.throw(global, "Invalid port number", .{}); } extern fn JSC__JSValue__isInstanceOf(this: JSValue, global: *JSGlobalObject, constructor: JSValue) bool; @@ -215,7 +215,7 @@ pub const JSValue = enum(i64) { return JSC__JSValue__isInstanceOf(this, global, constructor); } - pub fn callWithGlobalThis(this: JSValue, globalThis: *JSGlobalObject, args: []const JSC.JSValue) !JSC.JSValue { + pub fn callWithGlobalThis(this: JSValue, globalThis: *JSGlobalObject, args: []const jsc.JSValue) !jsc.JSValue { return this.call(globalThis, globalThis.toJSValue(), args); } @@ -227,10 +227,10 @@ pub const JSValue = enum(i64) { arguments: [*]const JSValue, ) JSValue; - pub fn call(function: JSValue, global: *JSGlobalObject, thisValue: JSC.JSValue, args: []const JSC.JSValue) bun.JSError!JSC.JSValue { - JSC.markBinding(@src()); + pub fn call(function: JSValue, global: *JSGlobalObject, thisValue: jsc.JSValue, args: []const jsc.JSValue) bun.JSError!jsc.JSValue { + jsc.markBinding(@src()); if (comptime bun.Environment.isDebug) { - const loop = JSC.VirtualMachine.get().eventLoop(); + const loop = jsc.VirtualMachine.get().eventLoop(); loop.debug.js_call_count_outside_tick_queue += @as(usize, @intFromBool(!loop.debug.is_inside_tick_queue)); if (loop.debug.track_last_fn_name and !loop.debug.is_inside_tick_queue) { loop.debug.last_fn_name.deref(); @@ -279,9 +279,9 @@ pub const JSValue = enum(i64) { return this.jsType(); } - extern fn JSC__jsTypeStringForValue(globalObject: *JSGlobalObject, value: JSValue) *JSC.JSString; + extern fn JSC__jsTypeStringForValue(globalObject: *JSGlobalObject, value: JSValue) *jsc.JSString; - pub fn jsTypeString(this: JSValue, globalObject: *JSGlobalObject) *JSC.JSString { + pub fn jsTypeString(this: JSValue, globalObject: *JSGlobalObject) *jsc.JSString { return JSC__jsTypeStringForValue(globalObject, this); } @@ -305,19 +305,19 @@ pub const JSValue = enum(i64) { pub fn putRecord(value: JSValue, global: *JSGlobalObject, key: *ZigString, values_array: [*]ZigString, values_len: usize) void { return JSC__JSValue__putRecord(value, global, key, values_array, values_len); } - extern fn JSC__JSValue__put(value: JSValue, global: *JSGlobalObject, key: *const ZigString, result: JSC.JSValue) void; - pub fn putZigString(value: JSValue, global: *JSGlobalObject, key: *const ZigString, result: JSC.JSValue) void { + extern fn JSC__JSValue__put(value: JSValue, global: *JSGlobalObject, key: *const ZigString, result: jsc.JSValue) void; + pub fn putZigString(value: JSValue, global: *JSGlobalObject, key: *const ZigString, result: jsc.JSValue) void { JSC__JSValue__put(value, global, key, result); } - extern "c" fn JSC__JSValue__putBunString(value: JSValue, global: *JSGlobalObject, key: *const bun.String, result: JSC.JSValue) void; - fn putBunString(value: JSValue, global: *JSGlobalObject, key: *const bun.String, result: JSC.JSValue) void { + extern "c" fn JSC__JSValue__putBunString(value: JSValue, global: *JSGlobalObject, key: *const bun.String, result: jsc.JSValue) void; + fn putBunString(value: JSValue, global: *JSGlobalObject, key: *const bun.String, result: jsc.JSValue) void { if (comptime bun.Environment.isDebug) - JSC.markBinding(@src()); + jsc.markBinding(@src()); JSC__JSValue__putBunString(value, global, key, result); } - pub fn put(value: JSValue, global: *JSGlobalObject, key: anytype, result: JSC.JSValue) void { + pub fn put(value: JSValue, global: *JSGlobalObject, key: anytype, result: jsc.JSValue) void { const Key = @TypeOf(key); if (comptime @typeInfo(Key) == .pointer) { const Elem = @typeInfo(Key).pointer.child; @@ -338,7 +338,7 @@ pub const JSValue = enum(i64) { @compileError("Unsupported key type in put(). Expected ZigString or bun.String, got " ++ @typeName(Key)); } } - extern fn JSC__JSValue__putMayBeIndex(target: JSValue, globalObject: *JSGlobalObject, key: *const String, value: JSC.JSValue) void; + extern fn JSC__JSValue__putMayBeIndex(target: JSValue, globalObject: *JSGlobalObject, key: *const String, value: jsc.JSValue) void; /// Note: key can't be numeric (if so, use putMayBeIndex instead) /// Same as `.put` but accepts both non-numeric and numeric keys. /// Prefer to use `.put` if the key is guaranteed to be non-numeric (e.g. known at comptime) @@ -346,8 +346,8 @@ pub const JSValue = enum(i64) { JSC__JSValue__putMayBeIndex(this, globalObject, key, value); } - extern fn JSC__JSValue__putToPropertyKey(target: JSValue, globalObject: *JSGlobalObject, key: JSC.JSValue, value: JSC.JSValue) void; - pub fn putToPropertyKey(target: JSValue, globalObject: *JSGlobalObject, key: JSC.JSValue, value: JSC.JSValue) bun.JSError!void { + extern fn JSC__JSValue__putToPropertyKey(target: JSValue, globalObject: *JSGlobalObject, key: jsc.JSValue, value: jsc.JSValue) void; + pub fn putToPropertyKey(target: JSValue, globalObject: *JSGlobalObject, key: jsc.JSValue, value: jsc.JSValue) bun.JSError!void { return bun.jsc.host_fn.fromJSHostCallGeneric(globalObject, @src(), JSC__JSValue__putToPropertyKey, .{ target, globalObject, key, value }); } @@ -361,8 +361,8 @@ pub const JSValue = enum(i64) { return bun.jsc.fromJSHostCallGeneric(globalObject, @src(), JSC__JSValue__push, .{ value, globalObject, out }); } - extern fn JSC__JSValue__toISOString(*JSC.JSGlobalObject, JSC.JSValue, *[28]u8) c_int; - pub fn toISOString(this: JSValue, globalObject: *JSC.JSGlobalObject, buf: *[28]u8) []const u8 { + extern fn JSC__JSValue__toISOString(*jsc.JSGlobalObject, jsc.JSValue, *[28]u8) c_int; + pub fn toISOString(this: JSValue, globalObject: *jsc.JSGlobalObject, buf: *[28]u8) []const u8 { const count = JSC__JSValue__toISOString(globalObject, this, buf); if (count < 0) { return ""; @@ -371,7 +371,7 @@ pub const JSValue = enum(i64) { return buf[0..@as(usize, @intCast(count))]; } extern fn JSC__JSValue__DateNowISOString(*JSGlobalObject, f64) JSValue; - pub fn getDateNowISOString(globalObject: *JSC.JSGlobalObject, buf: *[28]u8) []const u8 { + pub fn getDateNowISOString(globalObject: *jsc.JSGlobalObject, buf: *[28]u8) []const u8 { const count = JSC__JSValue__DateNowISOString(globalObject, buf); if (count < 0) { return ""; @@ -402,25 +402,25 @@ pub const JSValue = enum(i64) { return FetchHeaders.cast(value); } - if (comptime ZigType == JSC.WebCore.Body.Value) { - if (value.as(JSC.WebCore.Request)) |req| { + if (comptime ZigType == jsc.WebCore.Body.Value) { + if (value.as(jsc.WebCore.Request)) |req| { return req.getBodyValue(); } - if (value.as(JSC.WebCore.Response)) |res| { + if (value.as(jsc.WebCore.Response)) |res| { return res.getBodyValue(); } return null; } - if (comptime @hasDecl(ZigType, "fromJS") and @TypeOf(ZigType.fromJS) == fn (JSC.JSValue) ?*ZigType) { - if (comptime ZigType == JSC.WebCore.Blob) { + if (comptime @hasDecl(ZigType, "fromJS") and @TypeOf(ZigType.fromJS) == fn (jsc.JSValue) ?*ZigType) { + if (comptime ZigType == jsc.WebCore.Blob) { if (ZigType.fromJS(value)) |blob| { return blob; } - if (JSC.API.BuildArtifact.fromJS(value)) |build| { + if (jsc.API.BuildArtifact.fromJS(value)) |build| { return &build.blob; } @@ -433,20 +433,20 @@ pub const JSValue = enum(i64) { extern fn JSC__JSValue__dateInstanceFromNullTerminatedString(*JSGlobalObject, [*:0]const u8) JSValue; pub fn fromDateString(globalObject: *JSGlobalObject, str: [*:0]const u8) JSValue { - JSC.markBinding(@src()); + jsc.markBinding(@src()); return JSC__JSValue__dateInstanceFromNullTerminatedString(globalObject, str); } extern fn JSC__JSValue__dateInstanceFromNumber(*JSGlobalObject, f64) JSValue; pub fn fromDateNumber(globalObject: *JSGlobalObject, value: f64) JSValue { - JSC.markBinding(@src()); + jsc.markBinding(@src()); return JSC__JSValue__dateInstanceFromNumber(globalObject, value); } extern fn JSBuffer__isBuffer(*JSGlobalObject, JSValue) bool; pub fn isBuffer(value: JSValue, global: *JSGlobalObject) bool { - JSC.markBinding(@src()); + jsc.markBinding(@src()); return JSBuffer__isBuffer(global, value); } @@ -500,8 +500,8 @@ pub const JSValue = enum(i64) { return @ptrFromInt(this.asPtrAddress()); } - extern fn JSC__JSValue__createRopeString(this: JSValue, rhs: JSValue, globalThis: *JSC.JSGlobalObject) JSValue; - pub fn createRopeString(this: JSValue, rhs: JSValue, globalThis: *JSC.JSGlobalObject) JSValue { + extern fn JSC__JSValue__createRopeString(this: JSValue, rhs: JSValue, globalThis: *jsc.JSGlobalObject) JSValue; + pub fn createRopeString(this: JSValue, rhs: JSValue, globalThis: *jsc.JSGlobalObject) JSValue { return JSC__JSValue__createRopeString(this, rhs, globalThis); } @@ -511,7 +511,7 @@ pub const JSValue = enum(i64) { } pub fn createBufferFromLength(globalObject: *JSGlobalObject, len: usize) bun.JSError!JSValue { - JSC.markBinding(@src()); + jsc.markBinding(@src()); return bun.jsc.fromJSHostCall(globalObject, @src(), JSBuffer__bufferFromLength, .{ globalObject, @intCast(len) }); } @@ -545,10 +545,10 @@ pub const JSValue = enum(i64) { /// Must come from globally-allocated memory if allocator is not null pub fn createBuffer(globalObject: *JSGlobalObject, slice: []u8, allocator: ?std.mem.Allocator) JSValue { - JSC.markBinding(@src()); + jsc.markBinding(@src()); @setRuntimeSafety(false); if (allocator) |alloc| { - return JSBuffer__bufferFromPointerAndLengthAndDeinit(globalObject, slice.ptr, slice.len, alloc.ptr, JSC.array_buffer.MarkedArrayBuffer_deallocator); + return JSBuffer__bufferFromPointerAndLengthAndDeinit(globalObject, slice.ptr, slice.len, alloc.ptr, jsc.array_buffer.MarkedArrayBuffer_deallocator); } else { return JSBuffer__bufferFromPointerAndLengthAndDeinit(globalObject, slice.ptr, slice.len, null, null); } @@ -556,17 +556,17 @@ pub const JSValue = enum(i64) { extern fn JSC__JSValue__createUninitializedUint8Array(globalObject: *JSGlobalObject, len: usize) JSValue; pub fn createUninitializedUint8Array(globalObject: *JSGlobalObject, len: usize) bun.JSError!JSValue { - JSC.markBinding(@src()); + jsc.markBinding(@src()); return bun.jsc.fromJSHostCall(globalObject, @src(), JSC__JSValue__createUninitializedUint8Array, .{ globalObject, len }); } - pub fn createBufferWithCtx(globalObject: *JSGlobalObject, slice: []u8, ptr: ?*anyopaque, func: JSC.C.JSTypedArrayBytesDeallocator) JSValue { - JSC.markBinding(@src()); + pub fn createBufferWithCtx(globalObject: *JSGlobalObject, slice: []u8, ptr: ?*anyopaque, func: jsc.C.JSTypedArrayBytesDeallocator) JSValue { + jsc.markBinding(@src()); @setRuntimeSafety(false); return JSBuffer__bufferFromPointerAndLengthAndDeinit(globalObject, slice.ptr, slice.len, ptr, func); } - extern fn JSBuffer__bufferFromPointerAndLengthAndDeinit(*JSGlobalObject, [*]u8, usize, ?*anyopaque, JSC.C.JSTypedArrayBytesDeallocator) JSValue; + extern fn JSBuffer__bufferFromPointerAndLengthAndDeinit(*JSGlobalObject, [*]u8, usize, ?*anyopaque, jsc.C.JSTypedArrayBytesDeallocator) JSValue; pub fn jsNumberWithType(comptime Number: type, number: Number) JSValue { if (@typeInfo(Number) == .@"enum") { @@ -657,15 +657,15 @@ pub const JSValue = enum(i64) { pub fn print( this: JSValue, globalObject: *JSGlobalObject, - message_type: JSC.ConsoleObject.MessageType, - message_level: JSC.ConsoleObject.MessageLevel, + message_type: jsc.ConsoleObject.MessageType, + message_level: jsc.ConsoleObject.MessageLevel, ) void { - JSC.ConsoleObject.messageWithTypeAndLevel( + jsc.ConsoleObject.messageWithTypeAndLevel( undefined, message_type, message_level, globalObject, - &[_]JSC.JSValue{this}, + &[_]jsc.JSValue{this}, 1, ); } @@ -1012,7 +1012,7 @@ pub const JSValue = enum(i64) { return bun.jsc.fromJSHostCallGeneric(global, @src(), JSC__JSValue__getNameProperty, .{ this, global, ret }); } - extern fn JSC__JSValue__getName(JSC.JSValue, *JSC.JSGlobalObject, *bun.String) void; + extern fn JSC__JSValue__getName(jsc.JSValue, *jsc.JSGlobalObject, *bun.String) void; pub fn getName(this: JSValue, global: *JSGlobalObject) bun.String { var ret = bun.String.empty; JSC__JSValue__getName(this, global, &ret); @@ -1056,9 +1056,9 @@ pub const JSValue = enum(i64) { } /// Cast to an Exception pointer, or null if not an Exception - pub fn asException(this: JSValue, vm: *VM) ?*JSC.Exception { + pub fn asException(this: JSValue, vm: *VM) ?*jsc.Exception { return if (this.isException(vm)) - this.uncheckedPtrCast(JSC.Exception) + this.uncheckedPtrCast(jsc.Exception) else null; } @@ -1078,7 +1078,7 @@ pub const JSValue = enum(i64) { } /// Increments the reference count, you must call `.deref()` or it will leak memory. - pub fn toBunString(this: JSValue, globalObject: *JSC.JSGlobalObject) JSError!bun.String { + pub fn toBunString(this: JSValue, globalObject: *jsc.JSGlobalObject) JSError!bun.String { return bun.String.fromJS(this, globalObject); } @@ -1297,7 +1297,7 @@ pub const JSValue = enum(i64) { } }; - pub fn fastGetOrElse(this: JSValue, global: *JSGlobalObject, builtin_name: BuiltinName, alternate: ?JSC.JSValue) ?JSValue { + pub fn fastGetOrElse(this: JSValue, global: *JSGlobalObject, builtin_name: BuiltinName, alternate: ?jsc.JSValue) ?JSValue { return (try this.fastGet(global, builtin_name)) orelse { if (alternate) |alt| return alt.fastGet(global, builtin_name); @@ -1375,12 +1375,12 @@ pub const JSValue = enum(i64) { return JSC__JSValue__symbolKeyFor(this, global, str); } - extern fn JSC__JSValue___then(this: JSValue, global: *JSGlobalObject, ctx: JSValue, resolve: *const JSC.JSHostFn, reject: *const JSC.JSHostFn) void; - fn _then(this: JSValue, global: *JSGlobalObject, ctx: JSValue, resolve: JSC.JSHostFnZig, reject: JSC.JSHostFnZig) void { + extern fn JSC__JSValue___then(this: JSValue, global: *JSGlobalObject, ctx: JSValue, resolve: *const jsc.JSHostFn, reject: *const jsc.JSHostFn) void; + fn _then(this: JSValue, global: *JSGlobalObject, ctx: JSValue, resolve: jsc.JSHostFnZig, reject: jsc.JSHostFnZig) void { return JSC__JSValue___then(this, global, ctx, toJSHostFunction(resolve), toJSHostFunction(reject)); } - pub fn _then2(this: JSValue, global: *JSGlobalObject, ctx: JSValue, resolve: *const JSC.JSHostFn, reject: *const JSC.JSHostFn) void { + pub fn _then2(this: JSValue, global: *JSGlobalObject, ctx: JSValue, resolve: *const jsc.JSHostFn, reject: *const jsc.JSHostFn) void { var scope: CatchScope = undefined; scope.init(global, @src()); defer scope.deinit(); @@ -1388,7 +1388,7 @@ pub const JSValue = enum(i64) { bun.debugAssert(!scope.hasException()); // TODO: properly propagate exception upwards } - pub fn then(this: JSValue, global: *JSGlobalObject, ctx: ?*anyopaque, resolve: JSC.JSHostFnZig, reject: JSC.JSHostFnZig) void { + pub fn then(this: JSValue, global: *JSGlobalObject, ctx: ?*anyopaque, resolve: jsc.JSHostFnZig, reject: jsc.JSHostFnZig) void { var scope: CatchScope = undefined; scope.init(global, @src()); defer scope.deinit(); @@ -1699,7 +1699,7 @@ pub const JSValue = enum(i64) { return null; } - pub fn getOwnObject(this: JSValue, globalThis: *JSGlobalObject, comptime property_name: []const u8) JSError!?*JSC.JSObject { + pub fn getOwnObject(this: JSValue, globalThis: *JSGlobalObject, comptime property_name: []const u8) JSError!?*jsc.JSObject { if (try getOwnTruthy(this, globalThis, property_name)) |prop| { const obj = prop.getObject() orelse { return globalThis.throwInvalidArguments(property_name ++ " must be an object", .{}); @@ -1743,7 +1743,7 @@ pub const JSValue = enum(i64) { if (prop.isString()) { return try prop.toSliceOrNull(global); } - return JSC.Node.validators.throwErrInvalidArgType(global, property_name, .{}, "string", prop); + return jsc.Node.validators.throwErrInvalidArgType(global, property_name, .{}, "string", prop); }, i32 => return prop.coerce(i32, global), i64 => return prop.coerce(i64, global), @@ -1767,7 +1767,7 @@ pub const JSValue = enum(i64) { .js_undefined => null, .false, .true => prop == .true, else => { - return JSC.Node.validators.throwErrInvalidArgType(global, property_name, .{}, "boolean", prop); + return jsc.Node.validators.throwErrInvalidArgType(global, property_name, .{}, "boolean", prop); }, }; } @@ -1790,8 +1790,8 @@ pub const JSValue = enum(i64) { @compileError("getOptionalInt only works with integer types"); } const is_unsigned = info.int.signedness == .unsigned; - const min: i64 = if (is_unsigned) 0 else @max(std.math.minInt(Type), -JSC.MAX_SAFE_INTEGER); - const max: i64 = @min(std.math.maxInt(Type), JSC.MAX_SAFE_INTEGER); + const min: i64 = if (is_unsigned) 0 else @max(std.math.minInt(Type), -jsc.MAX_SAFE_INTEGER); + const max: i64 = @min(std.math.maxInt(Type), jsc.MAX_SAFE_INTEGER); return try globalThis.validateIntegerRange(value, Type, 0, .{ .min = min, .max = max, .field_name = property_name }); } @@ -1895,15 +1895,15 @@ pub const JSValue = enum(i64) { return JSC__JSValue__getUnixTimestamp(this); } - extern fn JSC__JSValue__getUTCTimestamp(globalObject: *JSC.JSGlobalObject, this: JSValue) f64; + extern fn JSC__JSValue__getUTCTimestamp(globalObject: *jsc.JSGlobalObject, this: JSValue) f64; /// Calls getTime() - getUTCT - pub fn getUTCTimestamp(this: JSValue, globalObject: *JSC.JSGlobalObject) f64 { + pub fn getUTCTimestamp(this: JSValue, globalObject: *jsc.JSGlobalObject) f64 { return JSC__JSValue__getUTCTimestamp(globalObject, this); } pub const StringFormatter = struct { - value: JSC.JSValue, - globalObject: *JSC.JSGlobalObject, + value: jsc.JSValue, + globalObject: *jsc.JSGlobalObject, pub fn format(this: StringFormatter, comptime text: []const u8, opts: std.fmt.FormatOptions, writer: anytype) !void { const str = try this.value.toBunString(this.globalObject); @@ -1912,7 +1912,7 @@ pub const JSValue = enum(i64) { } }; - pub fn fmtString(this: JSValue, globalObject: *JSC.JSGlobalObject) StringFormatter { + pub fn fmtString(this: JSValue, globalObject: *jsc.JSGlobalObject) StringFormatter { return .{ .value = this, .globalObject = globalObject, @@ -1921,15 +1921,15 @@ pub const JSValue = enum(i64) { pub fn toFmt( this: JSValue, - formatter: *JSC.ConsoleObject.Formatter, - ) JSC.ConsoleObject.Formatter.ZigFormatter { + formatter: *jsc.ConsoleObject.Formatter, + ) jsc.ConsoleObject.Formatter.ZigFormatter { formatter.remaining_values = &[_]JSValue{}; if (formatter.map_node != null) { formatter.deinit(); } formatter.stack_check.update(); - return JSC.ConsoleObject.Formatter.ZigFormatter{ + return jsc.ConsoleObject.Formatter.ZigFormatter{ .formatter = formatter, .value = this, }; @@ -2151,7 +2151,7 @@ pub const JSValue = enum(i64) { /// - Do not pass the callback as-is to JS; The wrapped object is NOT a function. /// - If passed to C++, call it with AsyncContextFrame::call() instead of JSC::call() pub inline fn withAsyncContextIfNeeded(this: JSValue, global: *JSGlobalObject) JSValue { - JSC.markBinding(@src()); + jsc.markBinding(@src()); return AsyncContextFrame__withAsyncContextIfNeeded(global, this); } @@ -2166,7 +2166,7 @@ pub const JSValue = enum(i64) { return bun.jsc.fromJSHostCall(global, @src(), Bun__JSValue__deserialize, .{ global, bytes.ptr, bytes.len }); } - extern fn Bun__serializeJSValue(global: *JSC.JSGlobalObject, value: JSValue, forTransfer: bool) SerializedScriptValue.External; + extern fn Bun__serializeJSValue(global: *jsc.JSGlobalObject, value: JSValue, forTransfer: bool) SerializedScriptValue.External; extern fn Bun__SerializedScriptSlice__free(*anyopaque) void; pub const SerializedScriptValue = struct { @@ -2225,10 +2225,10 @@ pub const JSValue = enum(i64) { /// /// `lifetime` describes the lifetime of `value`. If it must be copied, specify `temporary`. pub fn fromAny( - globalObject: *JSC.JSGlobalObject, + globalObject: *jsc.JSGlobalObject, comptime T: type, value: T, - ) bun.JSError!JSC.JSValue { + ) bun.JSError!jsc.JSValue { const Type = comptime brk: { var CurrentType = T; if (@typeInfo(T) == .optional) { @@ -2241,13 +2241,13 @@ pub const JSValue = enum(i64) { }; if (comptime bun.trait.isNumber(Type)) { - return JSC.JSValue.jsNumberWithType(Type, if (comptime Type != T) value.* else value); + return jsc.JSValue.jsNumberWithType(Type, if (comptime Type != T) value.* else value); } switch (comptime Type) { void => return .js_undefined, - bool => return JSC.JSValue.jsBoolean(if (comptime Type != T) value.* else value), - *JSC.JSGlobalObject => return value.toJSValue(), + bool => return jsc.JSValue.jsBoolean(if (comptime Type != T) value.* else value), + *jsc.JSGlobalObject => return value.toJSValue(), []const u8, [:0]const u8, [*:0]const u8, []u8, [:0]u8, [*:0]u8 => { return bun.String.createUTF8ForJS(globalObject, value); }, @@ -2260,15 +2260,15 @@ pub const JSValue = enum(i64) { } return bun.String.toJSArray(globalObject, value); }, - JSC.JSValue => return if (Type != T) value.* else value, + jsc.JSValue => return if (Type != T) value.* else value, inline []const u16, []const u32, []const i16, []const i8, []const i32, []const f32 => { - var array = try JSC.JSValue.createEmptyArray(globalObject, value.len); + var array = try jsc.JSValue.createEmptyArray(globalObject, value.len); for (value, 0..) |item, i| { try array.putIndex( globalObject, @truncate(i), - JSC.jsNumber(item), + jsc.jsNumber(item), ); } return array; @@ -2280,7 +2280,7 @@ pub const JSValue = enum(i64) { if (bun.trait.isSlice(Type)) { const Child = comptime std.meta.Child(Type); - var array = try JSC.JSValue.createEmptyArray(globalObject, value.len); + var array = try jsc.JSValue.createEmptyArray(globalObject, value.len); for (value, 0..) |*item, i| { const res = try fromAny(globalObject, *Child, item); if (res == .zero) return .zero; @@ -2305,7 +2305,7 @@ pub const JSValue = enum(i64) { if (@typeInfo(Type) == .@"enum") { // FIXME: creates non-normalized integers (e.g. u2), which // aren't handled by `jsNumberWithType` rn - return JSC.JSValue.jsNumberWithType(u32, @as(u32, @intFromEnum(value))); + return jsc.JSValue.jsNumberWithType(u32, @as(u32, @intFromEnum(value))); } @compileError("dont know how to convert " ++ @typeName(T) ++ " to JS"); @@ -2314,24 +2314,24 @@ pub const JSValue = enum(i64) { } /// Print a JSValue to stdout; this is only meant for debugging purposes - pub fn dump(value: JSC.WebCore.JSValue, globalObject: *JSC.JSGlobalObject) !void { - var formatter = JSC.ConsoleObject.Formatter{ .globalThis = globalObject }; + pub fn dump(value: jsc.WebCore.JSValue, globalObject: *jsc.JSGlobalObject) !void { + var formatter = jsc.ConsoleObject.Formatter{ .globalThis = globalObject }; defer formatter.deinit(); try Output.errorWriter().print("{}\n", .{value.toFmt(globalObject, &formatter)}); Output.flush(); } pub const JSPropertyNameIterator = struct { - array: JSC.C.JSPropertyNameArrayRef, + array: jsc.C.JSPropertyNameArrayRef, count: u32, i: u32 = 0, - pub fn next(this: *JSPropertyNameIterator) ?JSC.C.JSStringRef { + pub fn next(this: *JSPropertyNameIterator) ?jsc.C.JSStringRef { if (this.i >= this.count) return null; const i = this.i; this.i += 1; - return JSC.C.JSPropertyNameArrayGetNameAtIndex(this.array, i); + return jsc.C.JSPropertyNameArrayGetNameAtIndex(this.array, i); } }; @@ -2348,6 +2348,8 @@ pub const JSValue = enum(i64) { extern "c" fn AsyncContextFrame__withAsyncContextIfNeeded(global: *JSGlobalObject, callback: JSValue) JSValue; extern "c" fn Bun__JSValue__isAsyncContextFrame(value: JSValue) bool; +const string = []const u8; + const FFI = @import("./FFI.zig"); const std = @import("std"); const JestPrettyFormat = @import("../test/pretty_format.zig").JestPrettyFormat; @@ -2358,25 +2360,24 @@ const JSError = bun.JSError; const MutableString = bun.MutableString; const Output = bun.Output; const String = bun.String; -const string = bun.string; const FetchHeaders = bun.webcore.FetchHeaders; -const JSC = bun.JSC; -const AnyPromise = JSC.AnyPromise; -const ArrayBuffer = JSC.ArrayBuffer; -const C_API = bun.JSC.C; -const CatchScope = JSC.CatchScope; -const DOMURL = JSC.DOMURL; -const ExceptionValidationScope = JSC.ExceptionValidationScope; -const JSArrayIterator = JSC.JSArrayIterator; -const JSCell = JSC.JSCell; -const JSGlobalObject = JSC.JSGlobalObject; -const JSInternalPromise = JSC.JSInternalPromise; -const JSObject = JSC.JSObject; -const JSPromise = JSC.JSPromise; -const JSString = JSC.JSString; -const VM = JSC.VM; -const ZigException = JSC.ZigException; -const ZigString = JSC.ZigString; -const fromJSHostCall = JSC.fromJSHostCall; -const toJSHostFunction = JSC.toJSHostFn; +const jsc = bun.jsc; +const AnyPromise = jsc.AnyPromise; +const ArrayBuffer = jsc.ArrayBuffer; +const C_API = bun.jsc.C; +const CatchScope = jsc.CatchScope; +const DOMURL = jsc.DOMURL; +const ExceptionValidationScope = jsc.ExceptionValidationScope; +const JSArrayIterator = jsc.JSArrayIterator; +const JSCell = jsc.JSCell; +const JSGlobalObject = jsc.JSGlobalObject; +const JSInternalPromise = jsc.JSInternalPromise; +const JSObject = jsc.JSObject; +const JSPromise = jsc.JSPromise; +const JSString = jsc.JSString; +const VM = jsc.VM; +const ZigException = jsc.ZigException; +const ZigString = jsc.ZigString; +const fromJSHostCall = jsc.fromJSHostCall; +const toJSHostFunction = jsc.toJSHostFn; diff --git a/src/bun.js/bindings/NodeModuleModule.zig b/src/bun.js/bindings/NodeModuleModule.zig index 7a6e12ac5d..22eef36724 100644 --- a/src/bun.js/bindings/NodeModuleModule.zig +++ b/src/bun.js/bindings/NodeModuleModule.zig @@ -1,10 +1,10 @@ -export const NodeModuleModule__findPath = JSC.host_fn.wrap3(findPath); +export const NodeModuleModule__findPath = jsc.host_fn.wrap3(findPath); // https://github.com/nodejs/node/blob/40ef9d541ed79470977f90eb445c291b95ab75a0/lib/internal/modules/cjs/loader.js#L666 fn findPath( global: *JSGlobalObject, request_bun_str: bun.String, - paths_maybe: ?*JSC.JSArray, + paths_maybe: ?*jsc.JSArray, ) bun.JSError!JSValue { var stack_buf = std.heap.stackFallback(8192, bun.default_allocator); const alloc = stack_buf.get(); @@ -46,7 +46,7 @@ fn findPathInner( global: *JSGlobalObject, ) ?bun.String { var errorable: ErrorableString = undefined; - JSC.VirtualMachine.resolveMaybeNeedsTrailingSlash( + jsc.VirtualMachine.resolveMaybeNeedsTrailingSlash( &errorable, global, request, @@ -76,17 +76,17 @@ pub fn _stat(path: []const u8) i32 { pub const CustomLoader = union(enum) { loader: bun.options.Loader, - custom: JSC.Strong, + custom: jsc.Strong, }; -extern fn JSCommonJSExtensions__appendFunction(global: *JSC.JSGlobalObject, value: JSC.JSValue) u32; -extern fn JSCommonJSExtensions__setFunction(global: *JSC.JSGlobalObject, index: u32, value: JSC.JSValue) void; +extern fn JSCommonJSExtensions__appendFunction(global: *jsc.JSGlobalObject, value: jsc.JSValue) u32; +extern fn JSCommonJSExtensions__setFunction(global: *jsc.JSGlobalObject, index: u32, value: jsc.JSValue) void; /// Returns the index of the last value, which must have it's references updated to `index` -extern fn JSCommonJSExtensions__swapRemove(global: *JSC.JSGlobalObject, index: u32) u32; +extern fn JSCommonJSExtensions__swapRemove(global: *jsc.JSGlobalObject, index: u32) u32; // Memory management is complicated because JSValues are stored in gc-visitable // WriteBarriers in C++ but the hash map for extensions is in Zig for flexibility. -fn onRequireExtensionModify(global: *JSC.JSGlobalObject, str: []const u8, kind: i32, value: JSC.JSValue) !void { +fn onRequireExtensionModify(global: *jsc.JSGlobalObject, str: []const u8, kind: i32, value: jsc.JSValue) !void { bun.assert(kind >= -1 and kind <= 4); const vm = global.bunVM(); const list = &vm.commonjs_custom_extensions; @@ -143,7 +143,7 @@ fn onRequireExtensionModify(global: *JSC.JSGlobalObject, str: []const u8, kind: } } -pub fn findLongestRegisteredExtension(vm: *JSC.VirtualMachine, filename: []const u8) ?CustomLoader { +pub fn findLongestRegisteredExtension(vm: *jsc.VirtualMachine, filename: []const u8) ?CustomLoader { const basename = std.fs.path.basename(filename); var next: usize = 0; while (bun.strings.indexOfCharPos(basename, '.', next)) |i| { @@ -158,10 +158,10 @@ pub fn findLongestRegisteredExtension(vm: *JSC.VirtualMachine, filename: []const } fn onRequireExtensionModifyBinding( - global: *JSC.JSGlobalObject, + global: *jsc.JSGlobalObject, str: *const bun.String, kind: i32, - value: JSC.JSValue, + value: jsc.JSValue, ) callconv(.c) void { var sfa_state = std.heap.stackFallback(8192, bun.default_allocator); const alloc = sfa_state.get(); @@ -179,7 +179,7 @@ comptime { const bun = @import("bun"); const std = @import("std"); -const JSC = bun.JSC; -const ErrorableString = JSC.ErrorableString; -const JSGlobalObject = JSC.JSGlobalObject; -const JSValue = JSC.JSValue; +const jsc = bun.jsc; +const ErrorableString = jsc.ErrorableString; +const JSGlobalObject = jsc.JSGlobalObject; +const JSValue = jsc.JSValue; diff --git a/src/bun.js/bindings/ResolvedSource.zig b/src/bun.js/bindings/ResolvedSource.zig index 2e247df0a4..a105592b36 100644 --- a/src/bun.js/bindings/ResolvedSource.zig +++ b/src/bun.js/bindings/ResolvedSource.zig @@ -32,5 +32,5 @@ pub const ResolvedSource = extern struct { const bun = @import("bun"); -const JSC = bun.JSC; -const JSValue = JSC.JSValue; +const jsc = bun.jsc; +const JSValue = jsc.JSValue; diff --git a/src/bun.js/bindings/SystemError.zig b/src/bun.js/bindings/SystemError.zig index 83659f111c..128b5d6c8f 100644 --- a/src/bun.js/bindings/SystemError.zig +++ b/src/bun.js/bindings/SystemError.zig @@ -18,7 +18,7 @@ pub const SystemError = extern struct { } extern fn SystemError__toErrorInstance(this: *const SystemError, global: *JSGlobalObject) JSValue; - extern fn SystemError__toErrorInstanceWithInfoObject(this: *const SystemError, global: *JSC.JSGlobalObject) JSValue; + extern fn SystemError__toErrorInstanceWithInfoObject(this: *const SystemError, global: *jsc.JSGlobalObject) JSValue; pub fn getErrno(this: *const SystemError) bun.sys.E { // The inverse in bun.sys.Error.toSystemError() @@ -112,6 +112,6 @@ const std = @import("std"); const bun = @import("bun"); const String = bun.String; -const JSC = bun.JSC; -const JSGlobalObject = JSC.JSGlobalObject; -const JSValue = JSC.JSValue; +const jsc = bun.jsc; +const JSGlobalObject = jsc.JSGlobalObject; +const JSValue = jsc.JSValue; diff --git a/src/bun.js/bindings/URL.zig b/src/bun.js/bindings/URL.zig index 4e9f1f123c..8bd1c7b96a 100644 --- a/src/bun.js/bindings/URL.zig +++ b/src/bun.js/bindings/URL.zig @@ -1,5 +1,5 @@ pub const URL = opaque { - extern fn URL__fromJS(JSValue, *JSC.JSGlobalObject) ?*URL; + extern fn URL__fromJS(JSValue, *jsc.JSGlobalObject) ?*URL; extern fn URL__fromString(*bun.String) ?*URL; extern fn URL__protocol(*URL) String; extern fn URL__href(*URL) String; @@ -11,48 +11,48 @@ pub const URL = opaque { extern fn URL__port(*URL) u32; extern fn URL__deinit(*URL) void; extern fn URL__pathname(*URL) String; - extern fn URL__getHrefFromJS(JSValue, *JSC.JSGlobalObject) String; + extern fn URL__getHrefFromJS(JSValue, *jsc.JSGlobalObject) String; extern fn URL__getHref(*String) String; extern fn URL__getFileURLString(*String) String; extern fn URL__getHrefJoin(*String, *String) String; extern fn URL__pathFromFileURL(*String) String; pub fn hrefFromString(str: bun.String) String { - JSC.markBinding(@src()); + jsc.markBinding(@src()); var input = str; return URL__getHref(&input); } pub fn join(base: bun.String, relative: bun.String) String { - JSC.markBinding(@src()); + jsc.markBinding(@src()); var base_str = base; var relative_str = relative; return URL__getHrefJoin(&base_str, &relative_str); } pub fn fileURLFromString(str: bun.String) String { - JSC.markBinding(@src()); + jsc.markBinding(@src()); var input = str; return URL__getFileURLString(&input); } pub fn pathFromFileURL(str: bun.String) String { - JSC.markBinding(@src()); + jsc.markBinding(@src()); var input = str; return URL__pathFromFileURL(&input); } /// This percent-encodes the URL, punycode-encodes the hostname, and returns the result /// If it fails, the tag is marked Dead - pub fn hrefFromJS(value: JSValue, globalObject: *JSC.JSGlobalObject) bun.JSError!String { - JSC.markBinding(@src()); + pub fn hrefFromJS(value: JSValue, globalObject: *jsc.JSGlobalObject) bun.JSError!String { + jsc.markBinding(@src()); const result = URL__getHrefFromJS(value, globalObject); if (globalObject.hasException()) return error.JSError; return result; } - pub fn fromJS(value: JSValue, globalObject: *JSC.JSGlobalObject) bun.JSError!?*URL { - JSC.markBinding(@src()); + pub fn fromJS(value: JSValue, globalObject: *jsc.JSGlobalObject) bun.JSError!?*URL { + jsc.markBinding(@src()); const result = URL__fromJS(value, globalObject); if (globalObject.hasException()) return error.JSError; return result; @@ -62,56 +62,56 @@ pub const URL = opaque { return fromString(String.borrowUTF8(input)); } pub fn fromString(str: bun.String) ?*URL { - JSC.markBinding(@src()); + jsc.markBinding(@src()); var input = str; return URL__fromString(&input); } pub fn protocol(url: *URL) String { - JSC.markBinding(@src()); + jsc.markBinding(@src()); return URL__protocol(url); } pub fn href(url: *URL) String { - JSC.markBinding(@src()); + jsc.markBinding(@src()); return URL__href(url); } pub fn username(url: *URL) String { - JSC.markBinding(@src()); + jsc.markBinding(@src()); return URL__username(url); } pub fn password(url: *URL) String { - JSC.markBinding(@src()); + jsc.markBinding(@src()); return URL__password(url); } pub fn search(url: *URL) String { - JSC.markBinding(@src()); + jsc.markBinding(@src()); return URL__search(url); } pub fn host(url: *URL) String { - JSC.markBinding(@src()); + jsc.markBinding(@src()); return URL__host(url); } pub fn hostname(url: *URL) String { - JSC.markBinding(@src()); + jsc.markBinding(@src()); return URL__hostname(url); } /// Returns `std.math.maxInt(u32)` if the port is not set. Otherwise, `port` /// is guaranteed to be within the `u16` range. pub fn port(url: *URL) u32 { - JSC.markBinding(@src()); + jsc.markBinding(@src()); return URL__port(url); } pub fn deinit(url: *URL) void { - JSC.markBinding(@src()); + jsc.markBinding(@src()); return URL__deinit(url); } pub fn pathname(url: *URL) String { - JSC.markBinding(@src()); + jsc.markBinding(@src()); return URL__pathname(url); } extern fn URL__originLength(latin1_slice: [*]const u8, len: usize) u32; pub fn originFromSlice(slice: []const u8) ?[]const u8 { - JSC.markBinding(@src()); + jsc.markBinding(@src()); // a valid URL will not have ascii in the origin. const first_non_ascii = bun.strings.firstNonASCII(slice) orelse slice.len; const len = URL__originLength( @@ -129,6 +129,6 @@ const bun = @import("bun"); const JSError = bun.JSError; const String = bun.String; -const JSC = bun.JSC; -const JSGlobalObject = JSC.JSGlobalObject; -const JSValue = JSC.JSValue; +const jsc = bun.jsc; +const JSGlobalObject = jsc.JSGlobalObject; +const JSValue = jsc.JSValue; diff --git a/src/bun.js/bindings/URLSearchParams.zig b/src/bun.js/bindings/URLSearchParams.zig index ed22518541..64f6be1efd 100644 --- a/src/bun.js/bindings/URLSearchParams.zig +++ b/src/bun.js/bindings/URLSearchParams.zig @@ -1,13 +1,13 @@ pub const URLSearchParams = opaque { extern fn URLSearchParams__create(globalObject: *JSGlobalObject, *const ZigString) JSValue; pub fn create(globalObject: *JSGlobalObject, init: ZigString) JSValue { - JSC.markBinding(@src()); + jsc.markBinding(@src()); return URLSearchParams__create(globalObject, &init); } extern fn URLSearchParams__fromJS(JSValue) ?*URLSearchParams; pub fn fromJS(value: JSValue) ?*URLSearchParams { - JSC.markBinding(@src()); + jsc.markBinding(@src()); return URLSearchParams__fromJS(value); } @@ -23,7 +23,7 @@ pub const URLSearchParams = opaque { ctx: *Ctx, comptime callback: *const fn (ctx: *Ctx, str: ZigString) void, ) void { - JSC.markBinding(@src()); + jsc.markBinding(@src()); const Wrap = struct { const cb_ = callback; pub fn cb(c: *anyopaque, str: *const ZigString) callconv(.C) void { @@ -41,6 +41,6 @@ pub const URLSearchParams = opaque { const bun = @import("bun"); const ZigString = @import("./ZigString.zig").ZigString; -const JSC = bun.JSC; -const JSGlobalObject = JSC.JSGlobalObject; -const JSValue = JSC.JSValue; +const jsc = bun.jsc; +const JSGlobalObject = jsc.JSGlobalObject; +const JSValue = jsc.JSValue; diff --git a/src/bun.js/bindings/VM.zig b/src/bun.js/bindings/VM.zig index 5858e7e26d..784a51e7fc 100644 --- a/src/bun.js/bindings/VM.zig +++ b/src/bun.js/bindings/VM.zig @@ -57,7 +57,7 @@ pub const VM = opaque { } extern fn JSC__VM__reportExtraMemory(*VM, usize) void; pub fn reportExtraMemory(this: *VM, size: usize) void { - JSC.markBinding(@src()); + jsc.markBinding(@src()); JSC__VM__reportExtraMemory(this, size); } @@ -116,28 +116,28 @@ pub const VM = opaque { extern fn JSC__VM__notifyNeedTermination(vm: *VM) void; - /// Fires NeedTermination Trap. Thread safe. See JSC's "VMTraps.h" for explaination on traps. + /// Fires NeedTermination Trap. Thread safe. See jsc's "VMTraps.h" for explaination on traps. pub fn notifyNeedTermination(vm: *VM) void { JSC__VM__notifyNeedTermination(vm); } extern fn JSC__VM__notifyNeedWatchdogCheck(vm: *VM) void; - /// Fires NeedWatchdogCheck Trap. Thread safe. See JSC's "VMTraps.h" for explaination on traps. + /// Fires NeedWatchdogCheck Trap. Thread safe. See jsc's "VMTraps.h" for explaination on traps. pub fn notifyNeedWatchdogCheck(vm: *VM) void { JSC__VM__notifyNeedWatchdogCheck(vm); } extern fn JSC__VM__notifyNeedDebuggerBreak(vm: *VM) void; - /// Fires NeedDebuggerBreak Trap. Thread safe. See JSC's "VMTraps.h" for explaination on traps. + /// Fires NeedDebuggerBreak Trap. Thread safe. See jsc's "VMTraps.h" for explaination on traps. pub fn notifyNeedDebuggerBreak(vm: *VM) void { JSC__VM__notifyNeedDebuggerBreak(vm); } extern fn JSC__VM__notifyNeedShellTimeoutCheck(vm: *VM) void; - /// Fires NeedShellTimeoutCheck Trap. Thread safe. See JSC's "VMTraps.h" for explaination on traps. + /// Fires NeedShellTimeoutCheck Trap. Thread safe. See jsc's "VMTraps.h" for explaination on traps. pub fn notifyNeedShellTimeoutCheck(vm: *VM) void { JSC__VM__notifyNeedShellTimeoutCheck(vm); } @@ -191,6 +191,6 @@ pub const VM = opaque { const bun = @import("bun"); -const JSC = bun.JSC; -const JSGlobalObject = JSC.JSGlobalObject; -const JSValue = JSC.JSValue; +const jsc = bun.jsc; +const JSGlobalObject = jsc.JSGlobalObject; +const JSValue = jsc.JSValue; diff --git a/src/bun.js/bindings/WTF.zig b/src/bun.js/bindings/WTF.zig index 2baea40aa3..17c5661b2a 100644 --- a/src/bun.js/bindings/WTF.zig +++ b/src/bun.js/bindings/WTF.zig @@ -2,7 +2,7 @@ pub const WTF = struct { extern fn WTF__parseDouble(bytes: [*]const u8, length: usize, counted: *usize) f64; pub fn parseDouble(buf: []const u8) !f64 { - JSC.markBinding(@src()); + jsc.markBinding(@src()); if (buf.len == 0) return error.InvalidCharacter; @@ -32,4 +32,4 @@ pub const WTF = struct { }; const bun = @import("bun"); -const JSC = bun.JSC; +const jsc = bun.jsc; diff --git a/src/bun.js/bindings/ZigException.zig b/src/bun.js/bindings/ZigException.zig index 5f08689695..75e3e167ab 100644 --- a/src/bun.js/bindings/ZigException.zig +++ b/src/bun.js/bindings/ZigException.zig @@ -86,7 +86,7 @@ pub const ZigException = extern struct { return Holder.Zero; } - pub fn deinit(this: *Holder, vm: *JSC.VirtualMachine) void { + pub fn deinit(this: *Holder, vm: *jsc.VirtualMachine) void { if (this.loaded) { this.zig_exception.deinit(); } @@ -124,7 +124,7 @@ pub const ZigException = extern struct { pub fn addToErrorList( this: *ZigException, - error_list: *std.ArrayList(Api.JsException), + error_list: *std.ArrayList(api.JsException), root_path: string, origin: ?*const ZigURL, ) !void { @@ -137,7 +137,7 @@ pub const ZigException = extern struct { defer message_slice.deinit(); var is_empty = true; - var api_exception = Api.JsException{ + var api_exception = api.JsException{ .runtime_type = @intFromEnum(this.runtime_type), .code = @intFromEnum(this.type), }; @@ -163,19 +163,20 @@ pub const ZigException = extern struct { } }; +const string = []const u8; + const std = @import("std"); -const Api = @import("../../api/schema.zig").Api; const ZigURL = @import("../../url.zig").URL; const bun = @import("bun"); const String = bun.String; -const string = bun.string; +const api = bun.schema.api; -const JSC = bun.JSC; -const Exception = JSC.Exception; -const JSErrorCode = JSC.JSErrorCode; -const JSGlobalObject = JSC.JSGlobalObject; -const JSRuntimeType = JSC.JSRuntimeType; -const JSValue = JSC.JSValue; -const ZigStackFrame = JSC.ZigStackFrame; -const ZigStackTrace = JSC.ZigStackTrace; +const jsc = bun.jsc; +const Exception = jsc.Exception; +const JSErrorCode = jsc.JSErrorCode; +const JSGlobalObject = jsc.JSGlobalObject; +const JSRuntimeType = jsc.JSRuntimeType; +const JSValue = jsc.JSValue; +const ZigStackFrame = jsc.ZigStackFrame; +const ZigStackTrace = jsc.ZigStackTrace; diff --git a/src/bun.js/bindings/ZigStackFrame.zig b/src/bun.js/bindings/ZigStackFrame.zig index 46a8104e68..fdf933d7a0 100644 --- a/src/bun.js/bindings/ZigStackFrame.zig +++ b/src/bun.js/bindings/ZigStackFrame.zig @@ -15,8 +15,8 @@ pub const ZigStackFrame = extern struct { this.source_url.deref(); } - pub fn toAPI(this: *const ZigStackFrame, root_path: string, origin: ?*const ZigURL, allocator: std.mem.Allocator) !Api.StackFrame { - var frame: Api.StackFrame = comptime std.mem.zeroes(Api.StackFrame); + pub fn toAPI(this: *const ZigStackFrame, root_path: string, origin: ?*const ZigURL, allocator: std.mem.Allocator) !api.StackFrame { + var frame: api.StackFrame = comptime std.mem.zeroes(api.StackFrame); if (!this.function_name.isEmpty()) { var slicer = this.function_name.toUTF8(allocator); defer slicer.deinit(); @@ -28,7 +28,7 @@ pub const ZigStackFrame = extern struct { } frame.position = this.position; - frame.scope = @as(Api.StackFrameScope, @enumFromInt(@intFromEnum(this.code_type))); + frame.scope = @as(api.StackFrameScope, @enumFromInt(@intFromEnum(this.code_type))); return frame; } @@ -199,14 +199,14 @@ pub const ZigStackFrame = extern struct { }; const std = @import("std"); -const Api = @import("../../api/schema.zig").Api; const ZigURL = @import("../../url.zig").URL; const bun = @import("bun"); const Output = bun.Output; const String = bun.String; const strings = bun.strings; +const api = bun.schema.api; -const JSC = bun.JSC; -const ZigStackFrameCode = JSC.ZigStackFrameCode; -const ZigStackFramePosition = JSC.ZigStackFramePosition; +const jsc = bun.jsc; +const ZigStackFrameCode = jsc.ZigStackFrameCode; +const ZigStackFramePosition = jsc.ZigStackFramePosition; diff --git a/src/bun.js/bindings/ZigStackTrace.zig b/src/bun.js/bindings/ZigStackTrace.zig index 1b09e6389e..0af2db4cff 100644 --- a/src/bun.js/bindings/ZigStackTrace.zig +++ b/src/bun.js/bindings/ZigStackTrace.zig @@ -33,15 +33,15 @@ pub const ZigStackTrace = extern struct { allocator: std.mem.Allocator, root_path: string, origin: ?*const ZigURL, - ) !Api.StackTrace { - var stack_trace: Api.StackTrace = comptime std.mem.zeroes(Api.StackTrace); + ) !api.StackTrace { + var stack_trace: api.StackTrace = comptime std.mem.zeroes(api.StackTrace); { var source_lines_iter = this.sourceLineIterator(); const source_line_len = source_lines_iter.getLength(); if (source_line_len > 0) { - var source_lines = try allocator.alloc(Api.SourceLine, @as(usize, @intCast(@max(source_lines_iter.i + 1, 0)))); + var source_lines = try allocator.alloc(api.SourceLine, @as(usize, @intCast(@max(source_lines_iter.i + 1, 0)))); var source_line_buf = try allocator.alloc(u8, source_line_len); source_lines_iter = this.sourceLineIterator(); var remain_buf = source_line_buf[0..]; @@ -65,7 +65,7 @@ pub const ZigStackTrace = extern struct { { const _frames = this.frames(); if (_frames.len > 0) { - var stack_frames = try allocator.alloc(Api.StackFrame, _frames.len); + var stack_frames = try allocator.alloc(api.StackFrame, _frames.len); stack_trace.frames = stack_frames; for (_frames, 0..) |frame, i| { @@ -136,12 +136,13 @@ pub const ZigStackTrace = extern struct { } }; -const bun = @import("bun"); const std = @import("std"); -const Api = @import("../../api/schema.zig").Api; const ZigURL = @import("../../url.zig").URL; -const JSC = bun.JSC; -const SourceProvider = JSC.SourceProvider; -const ZigStackFrame = JSC.ZigStackFrame; -const ZigString = JSC.ZigString; +const bun = @import("bun"); +const api = bun.schema.api; + +const jsc = bun.jsc; +const SourceProvider = jsc.SourceProvider; +const ZigStackFrame = jsc.ZigStackFrame; +const ZigString = jsc.ZigString; diff --git a/src/bun.js/bindings/ZigString.zig b/src/bun.js/bindings/ZigString.zig index 962ac4dc53..12a8a91bff 100644 --- a/src/bun.js/bindings/ZigString.zig +++ b/src/bun.js/bindings/ZigString.zig @@ -23,14 +23,14 @@ pub const ZigString = extern struct { return if (this.is16Bit()) .{ .utf16 = this.utf16SliceAligned() } else .{ .latin1 = this.slice() }; } - pub fn encode(this: ZigString, encoding: JSC.Node.Encoding) []u8 { + pub fn encode(this: ZigString, encoding: jsc.Node.Encoding) []u8 { return this.encodeWithAllocator(bun.default_allocator, encoding); } - pub fn encodeWithAllocator(this: ZigString, allocator: std.mem.Allocator, encoding: JSC.Node.Encoding) []u8 { + pub fn encodeWithAllocator(this: ZigString, allocator: std.mem.Allocator, encoding: jsc.Node.Encoding) []u8 { return switch (this.as()) { inline else => |repr| switch (encoding) { - inline else => |enc| JSC.WebCore.encoding.constructFrom(std.meta.Child(@TypeOf(repr)), repr, allocator, enc), + inline else => |enc| jsc.WebCore.encoding.constructFrom(std.meta.Child(@TypeOf(repr)), repr, allocator, enc), }, }; } @@ -48,8 +48,8 @@ pub const ZigString = extern struct { } } - extern fn ZigString__toValueGC(arg0: *const ZigString, arg1: *JSGlobalObject) JSC.JSValue; - pub fn toJS(this: *const ZigString, ctx: *JSC.JSGlobalObject) JSValue { + extern fn ZigString__toValueGC(arg0: *const ZigString, arg1: *JSGlobalObject) jsc.JSValue; + pub fn toJS(this: *const ZigString, ctx: *jsc.JSGlobalObject) JSValue { if (this.isGloballyAllocated()) { return this.toExternalValue(ctx); } @@ -150,17 +150,17 @@ pub const ZigString = extern struct { return this; } - extern fn ZigString__toJSONObject(this: *const ZigString, *JSC.JSGlobalObject) callconv(.C) JSC.JSValue; + extern fn ZigString__toJSONObject(this: *const ZigString, *jsc.JSGlobalObject) callconv(.C) jsc.JSValue; - pub fn toJSONObject(this: ZigString, globalThis: *JSC.JSGlobalObject) JSValue { - JSC.markBinding(@src()); + pub fn toJSONObject(this: ZigString, globalThis: *jsc.JSGlobalObject) JSValue { + jsc.markBinding(@src()); return ZigString__toJSONObject(&this, globalThis); } - extern fn BunString__toURL(this: *const ZigString, *JSC.JSGlobalObject) callconv(.C) JSC.JSValue; + extern fn BunString__toURL(this: *const ZigString, *jsc.JSGlobalObject) callconv(.C) jsc.JSValue; - pub fn toURL(this: ZigString, globalThis: *JSC.JSGlobalObject) JSValue { - JSC.markBinding(@src()); + pub fn toURL(this: ZigString, globalThis: *jsc.JSGlobalObject) JSValue { + jsc.markBinding(@src()); return BunString__toURL(&this, globalThis); } @@ -217,7 +217,7 @@ pub const ZigString = extern struct { return this.len * 2; } - return JSC.WebCore.encoding.byteLengthU8(this.slice().ptr, this.slice().len, .utf16le); + return jsc.WebCore.encoding.byteLengthU8(this.slice().ptr, this.slice().len, .utf16le); } pub fn latin1ByteLength(this: ZigString) usize { @@ -321,9 +321,9 @@ pub const ZigString = extern struct { ptr: [*]const u8 = undefined, len: u32 = 0, - pub fn reportExtraMemory(this: *const Slice, vm: *JSC.VM) void { + pub fn reportExtraMemory(this: *const Slice, vm: *jsc.VM) void { if (this.allocator.get()) |allocator| { - // Don't report it if the memory is actually owned by JSC. + // Don't report it if the memory is actually owned by jsc. if (!bun.String.isWTFAllocator(allocator)) { vm.reportExtraMemory(this.len); } @@ -538,8 +538,8 @@ pub const ZigString = extern struct { return GithubActionFormatter{ .text = this }; } - extern fn ZigString__toAtomicValue(this: *const ZigString, globalThis: *JSC.JSGlobalObject) JSValue; - pub fn toAtomicValue(this: *const ZigString, globalThis: *JSC.JSGlobalObject) JSValue { + extern fn ZigString__toAtomicValue(this: *const ZigString, globalThis: *jsc.JSGlobalObject) JSValue; + pub fn toAtomicValue(this: *const ZigString, globalThis: *jsc.JSGlobalObject) JSValue { return ZigString__toAtomicValue(this, globalThis); } @@ -767,8 +767,8 @@ pub const ZigString = extern struct { inline fn assertGlobal(this: *const ZigString) void { if (comptime bun.Environment.allow_assert) { bun.assert(this.len == 0 or - bun.Mimalloc.mi_is_in_heap_region(untagged(this._unsafe_ptr_do_not_use)) or - bun.Mimalloc.mi_check_owned(untagged(this._unsafe_ptr_do_not_use))); + bun.mimalloc.mi_is_in_heap_region(untagged(this._unsafe_ptr_do_not_use)) or + bun.mimalloc.mi_check_owned(untagged(this._unsafe_ptr_do_not_use))); } } @@ -851,7 +851,7 @@ pub const ZigString = extern struct { } extern fn ZigString__toDOMExceptionInstance(this: *const ZigString, global: *JSGlobalObject, code: u8) JSValue; - pub fn toDOMExceptionInstance(this: *const ZigString, global: *JSGlobalObject, code: JSC.WebCore.DOMExceptionCode) JSValue { + pub fn toDOMExceptionInstance(this: *const ZigString, global: *JSGlobalObject, code: jsc.WebCore.DOMExceptionCode) JSValue { return ZigString__toDOMExceptionInstance(this, global, @intFromEnum(code)); } @@ -891,18 +891,19 @@ export fn ZigString__freeGlobal(ptr: [*]const u8, len: usize) void { Mimalloc.mi_free(untagged); } +const string = []const u8; + const std = @import("std"); const bun = @import("bun"); const Environment = bun.Environment; -const Mimalloc = bun.Mimalloc; +const Mimalloc = bun.mimalloc; const NullableAllocator = bun.NullableAllocator; const OOM = bun.OOM; const String = bun.String; -const string = bun.string; const strings = bun.strings; -const JSC = bun.JSC; -const C_API = bun.JSC.C; -const JSGlobalObject = JSC.JSGlobalObject; -const JSValue = JSC.JSValue; +const jsc = bun.jsc; +const C_API = bun.jsc.C; +const JSGlobalObject = jsc.JSGlobalObject; +const JSValue = jsc.JSValue; diff --git a/src/bun.js/bindings/bun-simdutf.zig b/src/bun.js/bindings/bun-simdutf.zig index e71ab5d068..85d94104f3 100644 --- a/src/bun.js/bindings/bun-simdutf.zig +++ b/src/bun.js/bindings/bun-simdutf.zig @@ -114,7 +114,7 @@ pub const validate = struct { return simdutf__validate_utf8(input.ptr, input.len); } pub fn ascii(input: []const u8) bool { - JSC.markBinding(@src()); + jsc.markBinding(@src()); return simdutf__validate_ascii(input.ptr, input.len); } pub fn utf16le(input: []const u16) bool { @@ -260,11 +260,11 @@ pub const length = struct { pub const from = struct { pub const utf16 = struct { pub fn le(input: []const u16) usize { - JSC.markBinding(@src()); + jsc.markBinding(@src()); return simdutf__utf8_length_from_utf16le(input.ptr, input.len); } pub fn be(input: []const u16) usize { - JSC.markBinding(@src()); + jsc.markBinding(@src()); return simdutf__utf8_length_from_utf16be(input.ptr, input.len); } }; @@ -274,7 +274,7 @@ pub const length = struct { } pub fn utf32(input: []const u32) usize { - JSC.markBinding(@src()); + jsc.markBinding(@src()); return simdutf__utf8_length_from_utf32(input.ptr, input.len); } }; @@ -290,7 +290,7 @@ pub const length = struct { } pub fn utf32(input: []const u32) usize { - JSC.markBinding(@src()); + jsc.markBinding(@src()); return simdutf__utf16_length_from_utf32(input.ptr, input.len); } @@ -304,7 +304,7 @@ pub const length = struct { pub const from = struct { pub const utf8 = struct { pub fn le(input: []const u8) usize { - JSC.markBinding(@src()); + jsc.markBinding(@src()); return simdutf__utf32_length_from_utf8(input.ptr, input.len); } pub fn be(input: []const u8) usize { @@ -314,11 +314,11 @@ pub const length = struct { pub const utf16 = struct { pub fn le(input: []const u16) usize { - JSC.markBinding(@src()); + jsc.markBinding(@src()); return simdutf__utf32_length_from_utf16le(input.ptr, input.len); } pub fn be(input: []const u16) usize { - JSC.markBinding(@src()); + jsc.markBinding(@src()); return simdutf__utf32_length_from_utf16be(input.ptr, input.len); } }; @@ -409,4 +409,4 @@ pub const base64 = struct { }; const bun = @import("bun"); -const JSC = bun.JSC; +const jsc = bun.jsc; diff --git a/src/bun.js/bindings/codegen.zig b/src/bun.js/bindings/codegen.zig index 02f78f6831..5a2bbceb29 100644 --- a/src/bun.js/bindings/codegen.zig +++ b/src/bun.js/bindings/codegen.zig @@ -1,13 +1,13 @@ -pub const CallbackGetterFn = fn (JSC.JSValue) callconv(.C) JSC.JSValue; -pub const CallbackSetterFn = fn (JSC.JSValue, JSC.JSValue) callconv(.C) void; +pub const CallbackGetterFn = fn (jsc.JSValue) callconv(.C) jsc.JSValue; +pub const CallbackSetterFn = fn (jsc.JSValue, jsc.JSValue) callconv(.C) void; pub fn CallbackWrapper(comptime Getter: *const CallbackGetterFn, comptime Setter: *const CallbackSetterFn) type { return struct { const GetFn = Getter; const SetFn = Setter; - container: JSC.JSValue, + container: jsc.JSValue, - pub inline fn get(self: @This()) ?JSC.JSValue { + pub inline fn get(self: @This()) ?jsc.JSValue { const res = GetFn(self.container); if (res.isEmptyOrUndefinedOrNull()) return null; @@ -15,11 +15,11 @@ pub fn CallbackWrapper(comptime Getter: *const CallbackGetterFn, comptime Setter return res; } - pub inline fn set(self: @This(), value: JSC.JSValue) void { + pub inline fn set(self: @This(), value: jsc.JSValue) void { SetFn(self.container, value); } - pub inline fn call(self: @This(), globalObject: *JSC.JSGlobalObject, args: []const JSC.JSValue) ?JSC.JSValue { + pub inline fn call(self: @This(), globalObject: *jsc.JSGlobalObject, args: []const jsc.JSValue) ?jsc.JSValue { if (self.get()) |callback| { return callback.call(globalObject, args); } @@ -30,4 +30,4 @@ pub fn CallbackWrapper(comptime Getter: *const CallbackGetterFn, comptime Setter } const bun = @import("bun"); -const JSC = bun.JSC; +const jsc = bun.jsc; diff --git a/src/bun.js/bindings/generated_classes_list.zig b/src/bun.js/bindings/generated_classes_list.zig index d97ff23a11..2544e94951 100644 --- a/src/bun.js/bindings/generated_classes_list.zig +++ b/src/bun.js/bindings/generated_classes_list.zig @@ -74,7 +74,7 @@ pub const Classes = struct { pub const NativeBrotli = api.NativeBrotli; pub const NodeHTTPResponse = api.NodeHTTPResponse; pub const FrameworkFileSystemRouter = bun.bake.FrameworkRouter.JSFrameworkRouter; - pub const DNSResolver = api.DNS.DNSResolver; + pub const DNSResolver = api.dns.Resolver; pub const S3Client = webcore.S3Client; pub const S3Stat = webcore.S3Stat; pub const ResumableFetchSink = webcore.ResumableFetchSink; @@ -87,7 +87,7 @@ pub const Classes = struct { }; const bun = @import("bun"); -const jsc = bun.JSC; +const jsc = bun.jsc; const webcore = bun.webcore; const api = bun.api; diff --git a/src/bun.js/config.zig b/src/bun.js/config.zig index 6c8bd3fc51..a6d1a55728 100644 --- a/src/bun.js/config.zig +++ b/src/bun.js/config.zig @@ -7,20 +7,20 @@ pub const DefaultBunDefines = struct { }; }; -pub fn configureTransformOptionsForBunVM(allocator: std.mem.Allocator, _args: Api.TransformOptions) !Api.TransformOptions { +pub fn configureTransformOptionsForBunVM(allocator: std.mem.Allocator, _args: api.TransformOptions) !api.TransformOptions { var args = _args; args.write = false; - args.resolve = Api.ResolveMode.lazy; + args.resolve = api.ResolveMode.lazy; return try configureTransformOptionsForBun(allocator, args); } -pub fn configureTransformOptionsForBun(_: std.mem.Allocator, _args: Api.TransformOptions) !Api.TransformOptions { +pub fn configureTransformOptionsForBun(_: std.mem.Allocator, _args: api.TransformOptions) !api.TransformOptions { var args = _args; - args.target = Api.Target.bun; + args.target = api.Target.bun; return args; } const bun = @import("bun"); const std = @import("std"); -const Api = @import("../api/schema.zig").Api; +const api = bun.schema.api; diff --git a/src/bun.js/event_loop.zig b/src/bun.js/event_loop.zig index 641dae67d6..77670b86c8 100644 --- a/src/bun.js/event_loop.zig +++ b/src/bun.js/event_loop.zig @@ -15,7 +15,7 @@ immediate_tasks: std.ArrayListUnmanaged(*Timer.ImmediateObject) = .{}, next_immediate_tasks: std.ArrayListUnmanaged(*Timer.ImmediateObject) = .{}, concurrent_tasks: ConcurrentTask.Queue = ConcurrentTask.Queue{}, -global: *JSC.JSGlobalObject = undefined, +global: *jsc.JSGlobalObject = undefined, virtual_machine: *VirtualMachine = undefined, waker: ?Waker = null, forever_timer: ?*uws.Timer = null, @@ -70,7 +70,7 @@ pub fn exit(this: *EventLoop) void { defer this.debug.exit(); if (count == 1 and !this.virtual_machine.is_inside_deferred_task_queue) { - this.drainMicrotasksWithGlobal(this.global, this.virtual_machine.jsc) catch {}; + this.drainMicrotasksWithGlobal(this.global, this.virtual_machine.jsc_vm) catch {}; } this.entered_event_loop_count -= 1; @@ -83,7 +83,7 @@ pub fn exitMaybeDrainMicrotasks(this: *EventLoop, allow_drain_microtask: bool) b defer this.debug.exit(); if (allow_drain_microtask and count == 1 and !this.virtual_machine.is_inside_deferred_task_queue) { - try this.drainMicrotasksWithGlobal(this.global, this.virtual_machine.jsc); + try this.drainMicrotasksWithGlobal(this.global, this.virtual_machine.jsc_vm); } this.entered_event_loop_count -= 1; @@ -106,10 +106,10 @@ pub fn tickWhilePaused(this: *EventLoop, done: *bool) void { } } -extern fn JSC__JSGlobalObject__drainMicrotasks(*JSC.JSGlobalObject) void; -pub fn drainMicrotasksWithGlobal(this: *EventLoop, globalObject: *JSC.JSGlobalObject, jsc_vm: *JSC.VM) bun.JSExecutionTerminated!void { - JSC.markBinding(@src()); - var scope: JSC.CatchScope = undefined; +extern fn JSC__JSGlobalObject__drainMicrotasks(*jsc.JSGlobalObject) void; +pub fn drainMicrotasksWithGlobal(this: *EventLoop, globalObject: *jsc.JSGlobalObject, jsc_vm: *jsc.VM) bun.JSExecutionTerminated!void { + jsc.markBinding(@src()); + var scope: jsc.CatchScope = undefined; scope.init(globalObject, @src()); defer scope.deinit(); @@ -127,13 +127,13 @@ pub fn drainMicrotasksWithGlobal(this: *EventLoop, globalObject: *JSC.JSGlobalOb } pub fn drainMicrotasks(this: *EventLoop) bun.JSExecutionTerminated!void { - try this.drainMicrotasksWithGlobal(this.global, this.virtual_machine.jsc); + try this.drainMicrotasksWithGlobal(this.global, this.virtual_machine.jsc_vm); } // should be called after exit() pub fn maybeDrainMicrotasks(this: *EventLoop) void { if (this.entered_event_loop_count == 0 and !this.virtual_machine.is_inside_deferred_task_queue) { - this.drainMicrotasksWithGlobal(this.global, this.virtual_machine.jsc) catch {}; + this.drainMicrotasksWithGlobal(this.global, this.virtual_machine.jsc_vm) catch {}; } } @@ -146,26 +146,26 @@ pub fn maybeDrainMicrotasks(this: *EventLoop) void { /// Otherwise, you will risk a large number of microtasks being queued and /// not being drained, which can lead to catastrophic memory usage and /// application slowdown. -pub fn runCallback(this: *EventLoop, callback: JSC.JSValue, globalObject: *JSC.JSGlobalObject, thisValue: JSC.JSValue, arguments: []const JSC.JSValue) void { +pub fn runCallback(this: *EventLoop, callback: jsc.JSValue, globalObject: *jsc.JSGlobalObject, thisValue: jsc.JSValue, arguments: []const jsc.JSValue) void { this.enter(); defer this.exit(); _ = callback.call(globalObject, thisValue, arguments) catch |err| globalObject.reportActiveExceptionAsUnhandled(err); } -fn externRunCallback1(global: *JSC.JSGlobalObject, callback: JSC.JSValue, thisValue: JSC.JSValue, arg0: JSC.JSValue) callconv(.c) void { +fn externRunCallback1(global: *jsc.JSGlobalObject, callback: jsc.JSValue, thisValue: jsc.JSValue, arg0: jsc.JSValue) callconv(.c) void { const vm = global.bunVM(); var loop = vm.eventLoop(); loop.runCallback(callback, global, thisValue, &.{arg0}); } -fn externRunCallback2(global: *JSC.JSGlobalObject, callback: JSC.JSValue, thisValue: JSC.JSValue, arg0: JSC.JSValue, arg1: JSC.JSValue) callconv(.c) void { +fn externRunCallback2(global: *jsc.JSGlobalObject, callback: jsc.JSValue, thisValue: jsc.JSValue, arg0: jsc.JSValue, arg1: jsc.JSValue) callconv(.c) void { const vm = global.bunVM(); var loop = vm.eventLoop(); loop.runCallback(callback, global, thisValue, &.{ arg0, arg1 }); } -fn externRunCallback3(global: *JSC.JSGlobalObject, callback: JSC.JSValue, thisValue: JSC.JSValue, arg0: JSC.JSValue, arg1: JSC.JSValue, arg2: JSC.JSValue) callconv(.c) void { +fn externRunCallback3(global: *jsc.JSGlobalObject, callback: jsc.JSValue, thisValue: jsc.JSValue, arg0: jsc.JSValue, arg1: jsc.JSValue, arg2: jsc.JSValue) callconv(.c) void { const vm = global.bunVM(); var loop = vm.eventLoop(); loop.runCallback(callback, global, thisValue, &.{ arg0, arg1, arg2 }); @@ -177,7 +177,7 @@ comptime { @export(&externRunCallback3, .{ .name = "Bun__EventLoop__runCallback3" }); } -pub fn runCallbackWithResult(this: *EventLoop, callback: JSC.JSValue, globalObject: *JSC.JSGlobalObject, thisValue: JSC.JSValue, arguments: []const JSC.JSValue) JSC.JSValue { +pub fn runCallbackWithResult(this: *EventLoop, callback: jsc.JSValue, globalObject: *jsc.JSGlobalObject, thisValue: jsc.JSValue, arguments: []const jsc.JSValue) jsc.JSValue { this.enter(); defer this.exit(); @@ -445,8 +445,8 @@ pub fn processGCTimer(this: *EventLoop) void { } pub fn tick(this: *EventLoop) void { - JSC.markBinding(@src()); - var scope: JSC.CatchScope = undefined; + jsc.markBinding(@src()); + var scope: jsc.CatchScope = undefined; scope.init(this.global, @src()); defer scope.deinit(); this.entered_event_loop_count += 1; @@ -461,7 +461,7 @@ pub fn tick(this: *EventLoop) void { this.processGCTimer(); const global = ctx.global; - const global_vm = ctx.jsc; + const global_vm = ctx.jsc_vm; while (true) { while (this.tickWithCount(ctx) > 0) : (this.global.handleRejectedPromises()) { @@ -482,8 +482,8 @@ pub fn tick(this: *EventLoop) void { this.global.handleRejectedPromises(); } -pub fn waitForPromise(this: *EventLoop, promise: JSC.AnyPromise) void { - const jsc_vm = this.virtual_machine.jsc; +pub fn waitForPromise(this: *EventLoop, promise: jsc.AnyPromise) void { + const jsc_vm = this.virtual_machine.jsc_vm; switch (promise.status(jsc_vm)) { .pending => { while (promise.status(jsc_vm) == .pending) { @@ -498,9 +498,9 @@ pub fn waitForPromise(this: *EventLoop, promise: JSC.AnyPromise) void { } } -pub fn waitForPromiseWithTermination(this: *EventLoop, promise: JSC.AnyPromise) void { +pub fn waitForPromiseWithTermination(this: *EventLoop, promise: jsc.AnyPromise) void { const worker = this.virtual_machine.worker orelse @panic("EventLoop.waitForPromiseWithTermination: worker is not initialized"); - const jsc_vm = this.virtual_machine.jsc; + const jsc_vm = this.virtual_machine.jsc_vm; switch (promise.status(jsc_vm)) { .pending => { while (!worker.hasRequestedTerminate() and promise.status(jsc_vm) == .pending) { @@ -538,7 +538,7 @@ pub fn callTask(timer: *uws.Timer) callconv(.C) void { } pub fn ensureWaker(this: *EventLoop) void { - JSC.markBinding(@src()); + jsc.markBinding(@src()); if (this.virtual_machine.event_loop_handle == null) { if (comptime Environment.isWindows) { this.uws_loop = bun.uws.Loop.get(); @@ -548,15 +548,15 @@ pub fn ensureWaker(this: *EventLoop) void { } this.virtual_machine.gc_controller.init(this.virtual_machine); - // _ = actual.addPostHandler(*JSC.EventLoop, this, JSC.EventLoop.afterUSocketsTick); - // _ = actual.addPreHandler(*JSC.VM, this.virtual_machine.jsc, JSC.VM.drainMicrotasks); + // _ = actual.addPostHandler(*jsc.EventLoop, this, jsc.EventLoop.afterUSocketsTick); + // _ = actual.addPreHandler(*jsc.VM, this.virtual_machine.jsc_vm, jsc.VM.drainMicrotasks); } if (comptime Environment.isWindows) { if (this.uws_loop == null) { this.uws_loop = bun.uws.Loop.get(); } } - bun.uws.Loop.get().internal_loop_data.setParentEventLoop(bun.JSC.EventLoopHandle.init(this)); + bun.uws.Loop.get().internal_loop_data.setParentEventLoop(bun.jsc.EventLoopHandle.init(this)); } /// Asynchronously run the garbage collector and track how much memory is now allocated @@ -657,5 +657,5 @@ const Timer = bun.api.Timer; const Async = bun.Async; const Waker = bun.Async.Waker; -const JSC = bun.JSC; -const VirtualMachine = bun.JSC.VirtualMachine; +const jsc = bun.jsc; +const VirtualMachine = bun.jsc.VirtualMachine; diff --git a/src/bun.js/event_loop/AnyEventLoop.zig b/src/bun.js/event_loop/AnyEventLoop.zig index b956a0ca7f..3b75642a84 100644 --- a/src/bun.js/event_loop/AnyEventLoop.zig +++ b/src/bun.js/event_loop/AnyEventLoop.zig @@ -1,5 +1,5 @@ /// Useful for code that may need an event loop and could be used from either JavaScript or directly without JavaScript. -/// Unlike JSC.EventLoopHandle, this owns the event loop when it's not a JavaScript event loop. +/// Unlike jsc.EventLoopHandle, this owns the event loop when it's not a JavaScript event loop. pub const AnyEventLoop = union(EventLoopKind) { js: *EventLoop, mini: MiniEventLoop, @@ -98,7 +98,7 @@ pub const AnyEventLoop = union(EventLoopKind) { // const TaskType = AnyTask.New(Context, Callback); // @field(ctx, field) = TaskType.init(ctx); // var concurrent = bun.default_allocator.create(ConcurrentTask) catch unreachable; - // _ = concurrent.from(JSC.Task.init(&@field(ctx, field))); + // _ = concurrent.from(jsc.Task.init(&@field(ctx, field))); // concurrent.auto_delete = true; // this.virtual_machine.jsc.enqueueTaskConcurrent(concurrent); }, @@ -115,9 +115,9 @@ const bun = @import("bun"); const Async = bun.Async; const uws = bun.uws; -const JSC = bun.JSC; -const AnyTaskWithExtraContext = JSC.AnyTaskWithExtraContext; -const EventLoop = JSC.EventLoop; -const EventLoopKind = JSC.EventLoopKind; -const MiniEventLoop = JSC.MiniEventLoop; -const Task = JSC.Task; +const jsc = bun.jsc; +const AnyTaskWithExtraContext = jsc.AnyTaskWithExtraContext; +const EventLoop = jsc.EventLoop; +const EventLoopKind = jsc.EventLoopKind; +const MiniEventLoop = jsc.MiniEventLoop; +const Task = jsc.Task; diff --git a/src/bun.js/event_loop/AnyTask.zig b/src/bun.js/event_loop/AnyTask.zig index 3e64c79a16..2c72b6701d 100644 --- a/src/bun.js/event_loop/AnyTask.zig +++ b/src/bun.js/event_loop/AnyTask.zig @@ -34,5 +34,5 @@ pub fn New(comptime Type: type, comptime Callback: anytype) type { const bun = @import("bun"); -const JSC = bun.JSC; -const Task = JSC.Task; +const jsc = bun.jsc; +const Task = jsc.Task; diff --git a/src/bun.js/event_loop/AnyTaskWithExtraContext.zig b/src/bun.js/event_loop/AnyTaskWithExtraContext.zig index b327c843e3..4a5771bcbf 100644 --- a/src/bun.js/event_loop/AnyTaskWithExtraContext.zig +++ b/src/bun.js/event_loop/AnyTaskWithExtraContext.zig @@ -1,5 +1,5 @@ //! This is AnyTask except it gives you two pointers instead of one. -//! Generally, prefer JSC.Task instead of this. +//! Generally, prefer jsc.Task instead of this. const AnyTaskWithExtraContext = @This(); @@ -68,5 +68,5 @@ pub fn New(comptime Type: type, comptime ContextType: type, comptime Callback: a const bun = @import("bun"); const std = @import("std"); -const JSC = bun.JSC; -const Task = JSC.Task; +const jsc = bun.jsc; +const Task = jsc.Task; diff --git a/src/bun.js/event_loop/ConcurrentPromiseTask.zig b/src/bun.js/event_loop/ConcurrentPromiseTask.zig index ee6740eb1e..47b7e703c6 100644 --- a/src/bun.js/event_loop/ConcurrentPromiseTask.zig +++ b/src/bun.js/event_loop/ConcurrentPromiseTask.zig @@ -4,31 +4,31 @@ /// /// The Context type must implement: /// - `run(*Context)` - performs the work on the thread pool -/// - `then(*Context, JSC.JSPromise)` - resolves the promise with the result on the JS thread +/// - `then(*Context, jsc.JSPromise)` - resolves the promise with the result on the JS thread pub fn ConcurrentPromiseTask(comptime Context: type) type { return struct { const This = @This(); ctx: *Context, task: WorkPoolTask = .{ .callback = &runFromThreadPool }, - event_loop: *JSC.EventLoop, + event_loop: *jsc.EventLoop, allocator: std.mem.Allocator, - promise: JSC.JSPromise.Strong = .{}, - globalThis: *JSC.JSGlobalObject, - concurrent_task: JSC.ConcurrentTask = .{}, + promise: jsc.JSPromise.Strong = .{}, + globalThis: *jsc.JSGlobalObject, + concurrent_task: jsc.ConcurrentTask = .{}, // This is a poll because we want it to enter the uSockets loop ref: Async.KeepAlive = .{}, pub const new = bun.TrivialNew(@This()); - pub fn createOnJSThread(allocator: std.mem.Allocator, globalThis: *JSC.JSGlobalObject, value: *Context) !*This { + pub fn createOnJSThread(allocator: std.mem.Allocator, globalThis: *jsc.JSGlobalObject, value: *Context) !*This { var this = This.new(.{ .event_loop = VirtualMachine.get().event_loop, .ctx = value, .allocator = allocator, .globalThis = globalThis, }); - var promise = JSC.JSPromise.create(globalThis); + var promise = jsc.JSPromise.create(globalThis); this.promise.strong.set(globalThis, promise.toJS()); this.ref.ref(this.event_loop.virtual_machine); @@ -70,8 +70,8 @@ const std = @import("std"); const bun = @import("bun"); const Async = bun.Async; -const JSC = bun.JSC; -const JSPromise = JSC.JSPromise; -const VirtualMachine = JSC.VirtualMachine; -const WorkPool = JSC.WorkPool; -const WorkPoolTask = JSC.WorkPoolTask; +const jsc = bun.jsc; +const JSPromise = jsc.JSPromise; +const VirtualMachine = jsc.VirtualMachine; +const WorkPool = jsc.WorkPool; +const WorkPoolTask = jsc.WorkPoolTask; diff --git a/src/bun.js/event_loop/ConcurrentTask.zig b/src/bun.js/event_loop/ConcurrentTask.zig index 7333bd1cbb..5f8ca7c73e 100644 --- a/src/bun.js/event_loop/ConcurrentTask.zig +++ b/src/bun.js/event_loop/ConcurrentTask.zig @@ -31,18 +31,18 @@ pub fn create(task: Task) *ConcurrentTask { } pub fn createFrom(task: anytype) *ConcurrentTask { - JSC.markBinding(@src()); + jsc.markBinding(@src()); return create(Task.init(task)); } pub fn fromCallback(ptr: anytype, comptime callback: anytype) *ConcurrentTask { - JSC.markBinding(@src()); + jsc.markBinding(@src()); return create(ManagedTask.New(std.meta.Child(@TypeOf(ptr)), callback).init(ptr)); } pub fn from(this: *ConcurrentTask, of: anytype, auto_deinit: AutoDeinit) *ConcurrentTask { - JSC.markBinding(@src()); + jsc.markBinding(@src()); this.* = .{ .task = Task.init(of), @@ -52,10 +52,11 @@ pub fn from(this: *ConcurrentTask, of: anytype, auto_deinit: AutoDeinit) *Concur return this; } -const bun = @import("bun"); const std = @import("std"); + +const bun = @import("bun"); const UnboundedQueue = bun.threading.UnboundedQueue; -const JSC = bun.JSC; -const ManagedTask = JSC.ManagedTask; -const Task = JSC.Task; +const jsc = bun.jsc; +const ManagedTask = jsc.ManagedTask; +const Task = jsc.Task; diff --git a/src/bun.js/event_loop/CppTask.zig b/src/bun.js/event_loop/CppTask.zig index 73928cb274..f0c1433f1f 100644 --- a/src/bun.js/event_loop/CppTask.zig +++ b/src/bun.js/event_loop/CppTask.zig @@ -1,8 +1,8 @@ /// A task created from C++ code, usually via ScriptExecutionContext. pub const CppTask = opaque { - extern fn Bun__performTask(globalObject: *JSC.JSGlobalObject, task: *CppTask) void; - pub fn run(this: *CppTask, global: *JSC.JSGlobalObject) void { - JSC.markBinding(@src()); + extern fn Bun__performTask(globalObject: *jsc.JSGlobalObject, task: *CppTask) void; + pub fn run(this: *CppTask, global: *jsc.JSGlobalObject) void { + jsc.markBinding(@src()); // TODO: properly propagate exception upwards bun.jsc.fromJSHostCallGeneric(global, @src(), Bun__performTask, .{ global, this }) catch |err| { _ = global.reportUncaughtException(global.takeException(err).asException(global.vm()).?); @@ -15,7 +15,7 @@ pub const ConcurrentCppTask = struct { pub const new = bun.TrivialNew(@This()); cpp_task: *EventLoopTaskNoContext, - workpool_task: JSC.WorkPoolTask = .{ .callback = &runFromWorkpool }, + workpool_task: jsc.WorkPoolTask = .{ .callback = &runFromWorkpool }, const EventLoopTaskNoContext = opaque { extern fn Bun__EventLoopTaskNoContext__performTask(task: *EventLoopTaskNoContext) void; @@ -32,7 +32,7 @@ pub const ConcurrentCppTask = struct { } }; - pub fn runFromWorkpool(task: *JSC.WorkPoolTask) void { + pub fn runFromWorkpool(task: *jsc.WorkPoolTask) void { const this: *ConcurrentCppTask = @fieldParentPtr("workpool_task", task); // Extract all the info we need from `this` and `cpp_task` before we call functions that // free them @@ -46,12 +46,12 @@ pub const ConcurrentCppTask = struct { } pub export fn ConcurrentCppTask__createAndRun(cpp_task: *EventLoopTaskNoContext) void { - JSC.markBinding(@src()); + jsc.markBinding(@src()); if (cpp_task.getVM()) |vm| { vm.event_loop.refConcurrently(); } const cpp = ConcurrentCppTask.new(.{ .cpp_task = cpp_task }); - JSC.WorkPool.schedule(&cpp.workpool_task); + jsc.WorkPool.schedule(&cpp.workpool_task); } }; @@ -61,5 +61,5 @@ comptime { const bun = @import("bun"); -const JSC = bun.JSC; -const VirtualMachine = JSC.VirtualMachine; +const jsc = bun.jsc; +const VirtualMachine = jsc.VirtualMachine; diff --git a/src/bun.js/event_loop/EventLoopHandle.zig b/src/bun.js/event_loop/EventLoopHandle.zig index 8494984a22..17acc43145 100644 --- a/src/bun.js/event_loop/EventLoopHandle.zig +++ b/src/bun.js/event_loop/EventLoopHandle.zig @@ -1,16 +1,16 @@ /// A non-owning reference to either the JS event loop or the mini event loop. pub const EventLoopHandle = union(EventLoopKind) { - js: *JSC.EventLoop, + js: *jsc.EventLoop, mini: *MiniEventLoop, - pub fn globalObject(this: EventLoopHandle) ?*JSC.JSGlobalObject { + pub fn globalObject(this: EventLoopHandle) ?*jsc.JSGlobalObject { return switch (this) { .js => this.js.global, .mini => null, }; } - pub fn stdout(this: EventLoopHandle) *JSC.WebCore.Blob.Store { + pub fn stdout(this: EventLoopHandle) *jsc.WebCore.Blob.Store { return switch (this) { .js => this.js.virtual_machine.rareData().stdout(), .mini => this.mini.stdout(), @@ -25,7 +25,7 @@ pub const EventLoopHandle = union(EventLoopKind) { return null; } - pub fn stderr(this: EventLoopHandle) *JSC.WebCore.Blob.Store { + pub fn stderr(this: EventLoopHandle) *jsc.WebCore.Blob.Store { return switch (this) { .js => this.js.virtual_machine.rareData().stderr(), .mini => this.mini.stderr(), @@ -54,8 +54,8 @@ pub const EventLoopHandle = union(EventLoopKind) { const Context = @TypeOf(context); return switch (Context) { *VirtualMachine => .{ .js = context.eventLoop() }, - *JSC.EventLoop => .{ .js = context }, - *JSC.MiniEventLoop => .{ .mini = context }, + *jsc.EventLoop => .{ .js = context }, + *jsc.MiniEventLoop => .{ .mini = context }, *AnyEventLoop => switch (context.*) { .js => .{ .js = context.js }, .mini => .{ .mini = &context.mini }, @@ -144,8 +144,8 @@ pub const EventLoopHandle = union(EventLoopKind) { }; pub const EventLoopTask = union(EventLoopKind) { - js: JSC.ConcurrentTask, - mini: JSC.AnyTaskWithExtraContext, + js: jsc.ConcurrentTask, + mini: jsc.AnyTaskWithExtraContext, pub fn init(kind: EventLoopKind) EventLoopTask { switch (kind) { @@ -154,7 +154,7 @@ pub const EventLoopTask = union(EventLoopKind) { } } - pub fn fromEventLoop(loop: JSC.EventLoopHandle) EventLoopTask { + pub fn fromEventLoop(loop: jsc.EventLoopHandle) EventLoopTask { switch (loop) { .js => return .{ .js = .{} }, .mini => return .{ .mini = .{} }, @@ -163,8 +163,8 @@ pub const EventLoopTask = union(EventLoopKind) { }; pub const EventLoopTaskPtr = union { - js: *JSC.ConcurrentTask, - mini: *JSC.AnyTaskWithExtraContext, + js: *jsc.ConcurrentTask, + mini: *jsc.AnyTaskWithExtraContext, }; const std = @import("std"); @@ -173,8 +173,8 @@ const Allocator = std.mem.Allocator; const bun = @import("bun"); const Async = bun.Async; -const JSC = bun.JSC; -const AnyEventLoop = JSC.AnyEventLoop; -const EventLoopKind = JSC.EventLoopKind; -const MiniEventLoop = JSC.MiniEventLoop; -const VirtualMachine = JSC.VirtualMachine; +const jsc = bun.jsc; +const AnyEventLoop = jsc.AnyEventLoop; +const EventLoopKind = jsc.EventLoopKind; +const MiniEventLoop = jsc.MiniEventLoop; +const VirtualMachine = jsc.VirtualMachine; diff --git a/src/bun.js/event_loop/GarbageCollectionController.zig b/src/bun.js/event_loop/GarbageCollectionController.zig index 335455764a..fc18a7ac67 100644 --- a/src/bun.js/event_loop/GarbageCollectionController.zig +++ b/src/bun.js/event_loop/GarbageCollectionController.zig @@ -34,7 +34,7 @@ pub fn init(this: *GarbageCollectionController, vm: *VirtualMachine) void { const actual = uws.Loop.get(); this.gc_timer = uws.Timer.createFallthrough(actual, this); this.gc_repeating_timer = uws.Timer.createFallthrough(actual, this); - actual.internal_loop_data.jsc_vm = vm.jsc; + actual.internal_loop_data.jsc_vm = vm.jsc_vm; if (comptime Environment.isDebug) { if (bun.getenvZ("BUN_TRACK_LAST_FN_NAME") != null) { @@ -115,11 +115,11 @@ pub fn onGCRepeatingTimer(timer: *uws.Timer) callconv(.C) void { pub fn processGCTimer(this: *GarbageCollectionController) void { if (this.disabled) return; - var vm = this.bunVM().jsc; + var vm = this.bunVM().jsc_vm; this.processGCTimerWithHeapSize(vm, vm.blockBytesAllocated()); } -fn processGCTimerWithHeapSize(this: *GarbageCollectionController, vm: *JSC.VM, this_heap_size: usize) void { +fn processGCTimerWithHeapSize(this: *GarbageCollectionController, vm: *jsc.VM, this_heap_size: usize) void { const prev = this.gc_last_heap_size; switch (this.gc_timer_state) { @@ -156,7 +156,7 @@ fn processGCTimerWithHeapSize(this: *GarbageCollectionController, vm: *JSC.VM, t pub fn performGC(this: *GarbageCollectionController) void { if (this.disabled) return; - var vm = this.bunVM().jsc; + var vm = this.bunVM().jsc_vm; vm.collectAsync(); this.gc_last_heap_size = vm.blockBytesAllocated(); } @@ -173,5 +173,5 @@ const bun = @import("bun"); const Environment = bun.Environment; const uws = bun.uws; -const JSC = bun.JSC; -const VirtualMachine = JSC.VirtualMachine; +const jsc = bun.jsc; +const VirtualMachine = jsc.VirtualMachine; diff --git a/src/bun.js/event_loop/JSCScheduler.zig b/src/bun.js/event_loop/JSCScheduler.zig index 1f207cec63..c79258034f 100644 --- a/src/bun.js/event_loop/JSCScheduler.zig +++ b/src/bun.js/event_loop/JSCScheduler.zig @@ -13,7 +13,7 @@ pub const JSCDeferredWorkTask = opaque { }; export fn Bun__eventLoop__incrementRefConcurrently(jsc_vm: *VirtualMachine, delta: c_int) void { - JSC.markBinding(@src()); + jsc.markBinding(@src()); if (delta > 0) { jsc_vm.event_loop.refConcurrently(); @@ -23,7 +23,7 @@ export fn Bun__eventLoop__incrementRefConcurrently(jsc_vm: *VirtualMachine, delt } export fn Bun__queueJSCDeferredWorkTaskConcurrently(jsc_vm: *VirtualMachine, task: *JSCScheduler.JSCDeferredWorkTask) void { - JSC.markBinding(@src()); + jsc.markBinding(@src()); var loop = jsc_vm.eventLoop(); loop.enqueueTaskConcurrent(ConcurrentTask.new(.{ .task = Task.init(task), @@ -33,7 +33,7 @@ export fn Bun__queueJSCDeferredWorkTaskConcurrently(jsc_vm: *VirtualMachine, tas } export fn Bun__tickWhilePaused(paused: *bool) void { - JSC.markBinding(@src()); + jsc.markBinding(@src()); VirtualMachine.get().eventLoop().tickWhilePaused(paused); } @@ -45,7 +45,7 @@ comptime { const bun = @import("bun"); -const JSC = bun.JSC; -const ConcurrentTask = JSC.ConcurrentTask; -const Task = JSC.Task; -const VirtualMachine = JSC.VirtualMachine; +const jsc = bun.jsc; +const ConcurrentTask = jsc.ConcurrentTask; +const Task = jsc.Task; +const VirtualMachine = jsc.VirtualMachine; diff --git a/src/bun.js/event_loop/ManagedTask.zig b/src/bun.js/event_loop/ManagedTask.zig index a87a95ade5..453face69a 100644 --- a/src/bun.js/event_loop/ManagedTask.zig +++ b/src/bun.js/event_loop/ManagedTask.zig @@ -1,5 +1,5 @@ //! This is a slow, dynamically-allocated one-off task -//! Use it when you can't add to JSC.Task directly and managing the lifetime of the Task struct is overly complex +//! Use it when you can't add to jsc.Task directly and managing the lifetime of the Task struct is overly complex const ManagedTask = @This(); @@ -43,5 +43,5 @@ pub fn New(comptime Type: type, comptime Callback: anytype) type { const bun = @import("bun"); -const JSC = bun.JSC; -const Task = JSC.Task; +const jsc = bun.jsc; +const Task = jsc.Task; diff --git a/src/bun.js/event_loop/MiniEventLoop.zig b/src/bun.js/event_loop/MiniEventLoop.zig index 98e04c1dda..56b407a15e 100644 --- a/src/bun.js/event_loop/MiniEventLoop.zig +++ b/src/bun.js/event_loop/MiniEventLoop.zig @@ -1,12 +1,12 @@ //! MiniEventLoop: A lightweight event loop for non-JavaScript contexts //! -//! This is a simplified version of JSC.EventLoop that provides event loop functionality +//! This is a simplified version of jsc.EventLoop that provides event loop functionality //! without requiring a JavaScript runtime. It enables code reuse between JavaScript-enabled //! contexts (like `bun run`) and JavaScript-free contexts (like `bun build`, `bun install`, //! and the Bun Shell). //! //! Key characteristics: -//! - Wraps the uSockets event loop, same as JSC.EventLoop +//! - Wraps the uSockets event loop, same as jsc.EventLoop //! - Supports concurrent task execution via thread pools //! - Provides file polling capabilities for watching filesystem changes //! - Manages stdout/stderr streams without JavaScript bindings @@ -29,7 +29,7 @@ file_polls_: ?*Async.FilePoll.Store = null, env: ?*bun.DotEnv.Loader = null, top_level_dir: []const u8 = "", after_event_loop_callback_ctx: ?*anyopaque = null, -after_event_loop_callback: ?JSC.OpaqueCallback = null, +after_event_loop_callback: ?jsc.OpaqueCallback = null, pipe_read_buffer: ?*PipeReadBuffer = null, stdout_store: ?*bun.webcore.Blob.Store = null, stderr_store: ?*bun.webcore.Blob.Store = null, @@ -45,7 +45,7 @@ pub fn initGlobal(env: ?*bun.DotEnv.Loader) *MiniEventLoop { const loop = MiniEventLoop.init(bun.default_allocator); global = bun.default_allocator.create(MiniEventLoop) catch bun.outOfMemory(); global.* = loop; - global.loop.internal_loop_data.setParentEventLoop(bun.JSC.EventLoopHandle.init(global)); + global.loop.internal_loop_data.setParentEventLoop(bun.jsc.EventLoopHandle.init(global)); global.env = env orelse bun.DotEnv.instance orelse env_loader: { const map = bun.default_allocator.create(bun.DotEnv.Map) catch bun.outOfMemory(); map.* = bun.DotEnv.Map.init(bun.default_allocator); @@ -212,7 +212,7 @@ pub fn enqueueTaskConcurrentWithExtraCtx( comptime Callback: fn (*Context, *ParentContext) void, comptime field: std.meta.FieldEnum(Context), ) void { - JSC.markBinding(@src()); + jsc.markBinding(@src()); const TaskType = MiniEventLoop.Task.New(Context, ParentContext, Callback); @field(ctx, @tagName(field)) = TaskType.init(ctx); @@ -221,7 +221,7 @@ pub fn enqueueTaskConcurrentWithExtraCtx( this.loop.wakeup(); } -pub fn stderr(this: *MiniEventLoop) *JSC.WebCore.Blob.Store { +pub fn stderr(this: *MiniEventLoop) *jsc.WebCore.Blob.Store { return this.stderr_store orelse brk: { var mode: bun.Mode = 0; const fd = bun.FD.fromUV(2); @@ -233,7 +233,7 @@ pub fn stderr(this: *MiniEventLoop) *JSC.WebCore.Blob.Store { .err => {}, } - const store = JSC.WebCore.Blob.Store.new(.{ + const store = jsc.WebCore.Blob.Store.new(.{ .ref_count = std.atomic.Value(u32).init(2), .allocator = bun.default_allocator, .data = .{ @@ -252,7 +252,7 @@ pub fn stderr(this: *MiniEventLoop) *JSC.WebCore.Blob.Store { }; } -pub fn stdout(this: *MiniEventLoop) *JSC.WebCore.Blob.Store { +pub fn stdout(this: *MiniEventLoop) *jsc.WebCore.Blob.Store { return this.stdout_store orelse brk: { var mode: bun.Mode = 0; const fd = bun.FD.stdout(); @@ -264,7 +264,7 @@ pub fn stdout(this: *MiniEventLoop) *JSC.WebCore.Blob.Store { .err => {}, } - const store = JSC.WebCore.Blob.Store.new(.{ + const store = jsc.WebCore.Blob.Store.new(.{ .ref_count = std.atomic.Value(u32).init(2), .allocator = bun.default_allocator, .data = .{ @@ -292,7 +292,7 @@ pub const JsVM = struct { }; } - pub inline fn loop(this: @This()) *JSC.EventLoop { + pub inline fn loop(this: @This()) *jsc.EventLoop { return this.vm.event_loop; } @@ -300,7 +300,7 @@ pub const JsVM = struct { return this.vm.rareData().filePolls(this.vm).get(); } - pub inline fn platformEventLoop(this: @This()) *JSC.PlatformEventLoop { + pub inline fn platformEventLoop(this: @This()) *jsc.PlatformEventLoop { return this.vm.event_loop_handle.?; } @@ -314,15 +314,15 @@ pub const JsVM = struct { }; pub const MiniVM = struct { - mini: *JSC.MiniEventLoop, + mini: *jsc.MiniEventLoop, - pub fn init(inner: *JSC.MiniEventLoop) MiniVM { + pub fn init(inner: *jsc.MiniEventLoop) MiniVM { return .{ .mini = inner, }; } - pub inline fn loop(this: @This()) *JSC.MiniEventLoop { + pub inline fn loop(this: @This()) *jsc.MiniEventLoop { return this.mini; } @@ -330,7 +330,7 @@ pub const MiniVM = struct { return this.mini.filePolls().get(); } - pub inline fn platformEventLoop(this: @This()) *JSC.PlatformEventLoop { + pub inline fn platformEventLoop(this: @This()) *jsc.PlatformEventLoop { if (comptime Environment.isWindows) { return this.mini.loop.uv_loop; } @@ -361,25 +361,25 @@ pub const EventLoopKind = enum { pub fn refType(comptime this: EventLoopKind) type { return switch (this) { .js => *VirtualMachine, - .mini => *JSC.MiniEventLoop, + .mini => *jsc.MiniEventLoop, }; } pub fn getVm(comptime this: EventLoopKind) EventLoopKind.refType(this) { return switch (this) { .js => VirtualMachine.get(), - .mini => JSC.MiniEventLoop.global, + .mini => jsc.MiniEventLoop.global, }; } }; pub fn AbstractVM(inner: anytype) switch (@TypeOf(inner)) { *VirtualMachine => JsVM, - *JSC.MiniEventLoop => MiniVM, + *jsc.MiniEventLoop => MiniVM, else => @compileError("Invalid event loop ctx: " ++ @typeName(@TypeOf(inner))), } { if (comptime @TypeOf(inner) == *VirtualMachine) return JsVM.init(inner); - if (comptime @TypeOf(inner) == *JSC.MiniEventLoop) return MiniVM.init(inner); + if (comptime @TypeOf(inner) == *jsc.MiniEventLoop) return MiniVM.init(inner); @compileError("Invalid event loop ctx: " ++ @typeName(@TypeOf(inner))); } @@ -391,7 +391,7 @@ const Environment = bun.Environment; const uws = bun.uws; const UnboundedQueue = bun.threading.UnboundedQueue; -const JSC = bun.JSC; -const AnyTaskWithExtraContext = JSC.AnyTaskWithExtraContext; -const EventLoop = JSC.EventLoop; -const VirtualMachine = JSC.VirtualMachine; +const jsc = bun.jsc; +const AnyTaskWithExtraContext = jsc.AnyTaskWithExtraContext; +const EventLoop = jsc.EventLoop; +const VirtualMachine = jsc.VirtualMachine; diff --git a/src/bun.js/event_loop/PosixSignalHandle.zig b/src/bun.js/event_loop/PosixSignalHandle.zig index 6ba91e294a..1e793eacc0 100644 --- a/src/bun.js/event_loop/PosixSignalHandle.zig +++ b/src/bun.js/event_loop/PosixSignalHandle.zig @@ -76,11 +76,11 @@ pub fn dequeue(this: *PosixSignalHandle) ?u8 { /// Drain as many signals as possible and enqueue them as tasks in the event loop. /// Called by the main thread. -pub fn drain(this: *PosixSignalHandle, event_loop: *JSC.EventLoop) void { +pub fn drain(this: *PosixSignalHandle, event_loop: *jsc.EventLoop) void { while (this.dequeue()) |signal| { // Example: wrap the signal into a Task structure var posix_signal_task: PosixSignalTask = undefined; - var task = JSC.Task.init(&posix_signal_task); + var task = jsc.Task.init(&posix_signal_task); task.setUintptr(signal); event_loop.enqueueTask(task); } @@ -88,10 +88,10 @@ pub fn drain(this: *PosixSignalHandle, event_loop: *JSC.EventLoop) void { pub const PosixSignalTask = struct { number: u8, - extern "c" fn Bun__onSignalForJS(number: i32, globalObject: *JSC.JSGlobalObject) void; + extern "c" fn Bun__onSignalForJS(number: i32, globalObject: *jsc.JSGlobalObject) void; pub const new = bun.TrivialNew(@This()); - pub fn runFromJSThread(number: u8, globalObject: *JSC.JSGlobalObject) void { + pub fn runFromJSThread(number: u8, globalObject: *jsc.JSGlobalObject) void { Bun__onSignalForJS(number, globalObject); } }; @@ -120,5 +120,5 @@ const std = @import("std"); const bun = @import("bun"); const Environment = bun.Environment; -const JSC = bun.JSC; -const VirtualMachine = JSC.VirtualMachine; +const jsc = bun.jsc; +const VirtualMachine = jsc.VirtualMachine; diff --git a/src/bun.js/event_loop/Task.zig b/src/bun.js/event_loop/Task.zig index e33704231f..fbdf1db9d3 100644 --- a/src/bun.js/event_loop/Task.zig +++ b/src/bun.js/event_loop/Task.zig @@ -237,7 +237,7 @@ pub fn tickQueueWithCount(this: *EventLoop, virtual_machine: *VirtualMachine) u3 }, @field(Task.Tag, @typeName(JSCDeferredWorkTask)) => { var jsc_task: *JSCDeferredWorkTask = task.get(JSCDeferredWorkTask).?; - JSC.markBinding(@src()); + jsc.markBinding(@src()); jsc_task.run(); }, @field(Task.Tag, @typeName(WriteFileTask)) => { @@ -518,8 +518,6 @@ const ProcessWaiterThreadTask = if (Environment.isPosix) bun.spawn.process.Waite const log = bun.Output.scoped(.Task, true); -const ServerAllConnectionsClosedTask = @import("../api/server.zig").ServerAllConnectionsClosedTask; - const Fetch = @import("../webcore/fetch.zig"); const FetchTasklet = Fetch.FetchTasklet; @@ -532,36 +530,14 @@ const Environment = bun.Environment; const TaggedPointerUnion = bun.TaggedPointerUnion; const shell = bun.shell; const FlushPendingFileSinkTask = bun.webcore.FileSink.FlushPendingTask; +const ServerAllConnectionsClosedTask = bun.api.server.ServerAllConnectionsClosedTask; const CopyFilePromiseTask = bun.webcore.Blob.copy_file.CopyFilePromiseTask; -const GetAddrInfoRequestTask = bun.api.DNS.GetAddrInfoRequest.Task; +const GetAddrInfoRequestTask = bun.api.dns.GetAddrInfoRequest.Task; const ReadFileTask = bun.webcore.Blob.read_file.ReadFileTask; const WriteFileTask = bun.webcore.Blob.write_file.WriteFileTask; const FSWatchTask = bun.api.node.fs.Watcher.FSWatchTask; const ShellGlobTask = shell.interpret.Interpreter.Expansion.ShellGlobTask; -const JSC = bun.JSC; -const AnyTask = JSC.AnyTask; -const CppTask = JSC.CppTask; -const EventLoop = JSC.EventLoop; -const ManagedTask = JSC.ManagedTask; -const PosixSignalTask = JSC.PosixSignalTask; -const VirtualMachine = JSC.VirtualMachine; -const HotReloadTask = JSC.hot_reloader.HotReloader.Task; -const StreamPending = JSC.WebCore.streams.Result.Pending; - -const NativeBrotli = JSC.API.NativeBrotli; -const NativeZlib = JSC.API.NativeZlib; -const NativeZstd = JSC.API.NativeZstd; -const AsyncGlobWalkTask = JSC.API.Glob.WalkTask.AsyncGlobWalkTask; -const AsyncTransformTask = JSC.API.JSTranspiler.TransformTask.AsyncTransformTask; - -const Timer = JSC.API.Timer; -const ImmediateObject = Timer.ImmediateObject; -const TimeoutObject = Timer.TimeoutObject; - -const RuntimeTranspilerStore = JSC.ModuleLoader.RuntimeTranspilerStore; -const PollPendingModulesTask = JSC.ModuleLoader.AsyncModule.Queue; - const S3 = bun.S3; const S3HttpDownloadStreamingTask = S3.S3HttpDownloadStreamingTask; const S3HttpSimpleTask = S3.S3HttpSimpleTask; @@ -614,6 +590,29 @@ const Write = AsyncFS.write; const WriteFile = AsyncFS.writeFile; const Writev = AsyncFS.writev; +const jsc = bun.jsc; +const AnyTask = jsc.AnyTask; +const CppTask = jsc.CppTask; +const EventLoop = jsc.EventLoop; +const ManagedTask = jsc.ManagedTask; +const PosixSignalTask = jsc.PosixSignalTask; +const VirtualMachine = jsc.VirtualMachine; +const HotReloadTask = jsc.hot_reloader.HotReloader.Task; +const StreamPending = jsc.WebCore.streams.Result.Pending; + +const NativeBrotli = jsc.API.NativeBrotli; +const NativeZlib = jsc.API.NativeZlib; +const NativeZstd = jsc.API.NativeZstd; +const AsyncGlobWalkTask = jsc.API.Glob.WalkTask.AsyncGlobWalkTask; +const AsyncTransformTask = jsc.API.JSTranspiler.TransformTask.AsyncTransformTask; + +const Timer = jsc.API.Timer; +const ImmediateObject = Timer.ImmediateObject; +const TimeoutObject = Timer.TimeoutObject; + +const RuntimeTranspilerStore = jsc.ModuleLoader.RuntimeTranspilerStore; +const PollPendingModulesTask = jsc.ModuleLoader.AsyncModule.Queue; + const ShellAsync = shell.Interpreter.Async; const ShellIOReaderAsyncDeinit = shell.Interpreter.AsyncDeinitReader; const ShellIOWriter = shell.Interpreter.IOWriter; diff --git a/src/bun.js/event_loop/WorkTask.zig b/src/bun.js/event_loop/WorkTask.zig index 185366e7f9..bcdbbfc57b 100644 --- a/src/bun.js/event_loop/WorkTask.zig +++ b/src/bun.js/event_loop/WorkTask.zig @@ -4,7 +4,7 @@ /// /// The Context type must implement: /// - `run(*Context, *WorkTask)` - performs the work on the thread pool -/// - `then(*JSC.JSGlobalObject)` - handles the result on the JS thread (no automatic Promise resolution) +/// - `then(*jsc.JSGlobalObject)` - handles the result on the JS thread (no automatic Promise resolution) /// /// Key differences from ConcurrentPromiseTask: /// - No automatic Promise creation or resolution @@ -18,23 +18,23 @@ pub fn WorkTask(comptime Context: type) type { const This = @This(); ctx: *Context, task: TaskType = .{ .callback = &runFromThreadPool }, - event_loop: *JSC.EventLoop, + event_loop: *jsc.EventLoop, allocator: std.mem.Allocator, - globalThis: *JSC.JSGlobalObject, + globalThis: *jsc.JSGlobalObject, concurrent_task: ConcurrentTask = .{}, - async_task_tracker: JSC.Debugger.AsyncTaskTracker, + async_task_tracker: jsc.Debugger.AsyncTaskTracker, // This is a poll because we want it to enter the uSockets loop ref: Async.KeepAlive = .{}, - pub fn createOnJSThread(allocator: std.mem.Allocator, globalThis: *JSC.JSGlobalObject, value: *Context) !*This { + pub fn createOnJSThread(allocator: std.mem.Allocator, globalThis: *jsc.JSGlobalObject, value: *Context) !*This { var vm = globalThis.bunVM(); var this = bun.new(This, .{ .event_loop = vm.eventLoop(), .ctx = value, .allocator = allocator, .globalThis = globalThis, - .async_task_tracker = JSC.Debugger.AsyncTaskTracker.init(vm), + .async_task_tracker = jsc.Debugger.AsyncTaskTracker.init(vm), }); this.ref.ref(this.event_loop.virtual_machine); @@ -47,7 +47,7 @@ pub fn WorkTask(comptime Context: type) type { } pub fn runFromThreadPool(task: *TaskType) void { - JSC.markBinding(@src()); + jsc.markBinding(@src()); const this: *This = @fieldParentPtr("task", task); Context.run(this.ctx, this); } @@ -82,7 +82,7 @@ const std = @import("std"); const bun = @import("bun"); const Async = bun.Async; -const JSC = bun.JSC; -const ConcurrentTask = JSC.ConcurrentTask; -const WorkPool = JSC.WorkPool; -const WorkPoolTask = JSC.WorkPoolTask; +const jsc = bun.jsc; +const ConcurrentTask = jsc.ConcurrentTask; +const WorkPool = jsc.WorkPool; +const WorkPoolTask = jsc.WorkPoolTask; diff --git a/src/bun.js/hot_reloader.zig b/src/bun.js/hot_reloader.zig index d58cd9a7fc..74fe099250 100644 --- a/src/bun.js/hot_reloader.zig +++ b/src/bun.js/hot_reloader.zig @@ -34,7 +34,7 @@ pub const ImportWatcher = union(enum) { dir_fd: bun.FD, package_json: ?*bun.PackageJSON, comptime copy_file_path: bool, - ) bun.JSC.Maybe(void) { + ) bun.jsc.Maybe(void) { return switch (this) { inline .hot, .watch => |watcher| watcher.addFile( fd, @@ -50,8 +50,8 @@ pub const ImportWatcher = union(enum) { } }; -pub const HotReloader = NewHotReloader(VirtualMachine, JSC.EventLoop, false); -pub const WatchReloader = NewHotReloader(VirtualMachine, JSC.EventLoop, true); +pub const HotReloader = NewHotReloader(VirtualMachine, jsc.EventLoop, false); +pub const WatchReloader = NewHotReloader(VirtualMachine, jsc.EventLoop, true); extern fn BunDebugger__willHotReload() void; @@ -96,7 +96,7 @@ pub fn NewHotReloader(comptime Ctx: type, comptime EventLoopType: type, comptime return this.ctx.eventLoop(); } - pub fn enqueueTaskConcurrent(this: @This(), task: *JSC.ConcurrentTask) void { + pub fn enqueueTaskConcurrent(this: @This(), task: *jsc.ConcurrentTask) void { if (comptime reload_immediately) unreachable; @@ -110,7 +110,7 @@ pub fn NewHotReloader(comptime Ctx: type, comptime EventLoopType: type, comptime hashes: [8]u32, paths: if (Ctx == bun.bake.DevServer) [8][]const u8 else void, /// Left uninitialized until .enqueue - concurrent_task: JSC.ConcurrentTask, + concurrent_task: jsc.ConcurrentTask, reloader: *Reloader, pub fn initEmpty(reloader: *Reloader) Task { @@ -150,7 +150,7 @@ pub fn NewHotReloader(comptime Ctx: type, comptime EventLoopType: type, comptime } pub fn enqueue(this: *Task) void { - JSC.markBinding(@src()); + jsc.markBinding(@src()); if (this.count == 0) return; @@ -174,7 +174,7 @@ pub fn NewHotReloader(comptime Ctx: type, comptime EventLoopType: type, comptime .hashes = this.hashes, .concurrent_task = undefined, }); - that.concurrent_task = .{ .task = JSC.Task.init(that), .auto_delete = false }; + that.concurrent_task = .{ .task = jsc.Task.init(that), .auto_delete = false }; that.reloader.enqueueTaskConcurrent(&that.concurrent_task); this.count = 0; } @@ -473,7 +473,7 @@ const Output = bun.Output; const Watcher = bun.Watcher; const options = bun.options; const strings = bun.strings; -const MarkedArrayBuffer = bun.jsc.MarkedArrayBuffer; -const JSC = bun.JSC; -const VirtualMachine = JSC.VirtualMachine; +const jsc = bun.jsc; +const MarkedArrayBuffer = bun.jsc.MarkedArrayBuffer; +const VirtualMachine = jsc.VirtualMachine; diff --git a/src/bun.js/ipc.zig b/src/bun.js/ipc.zig index 0206ca2091..1b1893bd41 100644 --- a/src/bun.js/ipc.zig +++ b/src/bun.js/ipc.zig @@ -64,7 +64,7 @@ const advanced = struct { version: u32 align(1) = version, }; - pub fn decodeIPCMessage(data: []const u8, global: *JSC.JSGlobalObject) IPCDecodeError!DecodeIPCMessageResult { + pub fn decodeIPCMessage(data: []const u8, global: *jsc.JSGlobalObject) IPCDecodeError!DecodeIPCMessageResult { if (data.len < header_length) { log("Not enough bytes to decode IPC message header, have {d} bytes", .{data.len}); return IPCDecodeError.NotEnoughBytes; @@ -116,7 +116,7 @@ const advanced = struct { return "\x02\x25\x00\x00\x00\r\x00\x00\x00\x02\x03\x00\x00\x80cmd\x10\x10\x00\x00\x80NODE_HANDLE_NACK\xff\xff\xff\xff"; } - pub fn serialize(writer: *bun.io.StreamBuffer, global: *JSC.JSGlobalObject, value: JSValue, is_internal: IsInternal) !usize { + pub fn serialize(writer: *bun.io.StreamBuffer, global: *jsc.JSGlobalObject, value: JSValue, is_internal: IsInternal) !usize { const serialized = try value.serialize(global, true); defer serialized.deinit(); @@ -157,7 +157,7 @@ const json = struct { // 2 is internal // ["[{\d\.] is regular - pub fn decodeIPCMessage(data: []const u8, globalThis: *JSC.JSGlobalObject) IPCDecodeError!DecodeIPCMessageResult { + pub fn decodeIPCMessage(data: []const u8, globalThis: *jsc.JSGlobalObject) IPCDecodeError!DecodeIPCMessageResult { // { "foo": "bar"} // tag is 1 or 2 if (bun.strings.indexOfChar(data, '\n')) |idx| { var json_data = data[0..idx]; @@ -218,7 +218,7 @@ const json = struct { return IPCDecodeError.NotEnoughBytes; } - pub fn serialize(writer: *bun.io.StreamBuffer, global: *JSC.JSGlobalObject, value: JSValue, is_internal: IsInternal) !usize { + pub fn serialize(writer: *bun.io.StreamBuffer, global: *jsc.JSGlobalObject, value: JSValue, is_internal: IsInternal) !usize { var out: bun.String = undefined; try value.jsonStringify(global, 0, &out); defer out.deref(); @@ -247,7 +247,7 @@ const json = struct { }; /// Given potentially unfinished buffer `data`, attempt to decode and process a message from it. -pub fn decodeIPCMessage(mode: Mode, data: []const u8, global: *JSC.JSGlobalObject) IPCDecodeError!DecodeIPCMessageResult { +pub fn decodeIPCMessage(mode: Mode, data: []const u8, global: *jsc.JSGlobalObject) IPCDecodeError!DecodeIPCMessageResult { return switch (mode) { inline else => |t| @field(@This(), @tagName(t)).decodeIPCMessage(data, global), }; @@ -262,7 +262,7 @@ pub fn getVersionPacket(mode: Mode) []const u8 { /// Given a writer interface, serialize and write a value. /// Returns true if the value was written, false if it was not. -pub fn serialize(mode: Mode, writer: *bun.io.StreamBuffer, global: *JSC.JSGlobalObject, value: JSValue, is_internal: IsInternal) !usize { +pub fn serialize(mode: Mode, writer: *bun.io.StreamBuffer, global: *jsc.JSGlobalObject, value: JSValue, is_internal: IsInternal) !usize { return switch (mode) { .advanced => advanced.serialize(writer, global, value, is_internal), .json => json.serialize(writer, global, value, is_internal), @@ -287,8 +287,8 @@ pub const Socket = uws.NewSocketHandler(false); pub const Handle = struct { fd: bun.FileDescriptor, - js: JSC.JSValue, - pub fn init(fd: bun.FileDescriptor, js: JSC.JSValue) @This() { + js: jsc.JSValue, + pub fn init(fd: bun.FileDescriptor, js: jsc.JSValue) @This() { js.protect(); return .{ .fd = fd, .js = js }; } @@ -300,12 +300,12 @@ pub const CallbackList = union(enum) { ack_nack, none, /// js callable - callback: JSC.JSValue, + callback: jsc.JSValue, /// js array - callback_array: JSC.JSValue, + callback_array: jsc.JSValue, /// protects the callback - pub fn init(callback: JSC.JSValue) @This() { + pub fn init(callback: jsc.JSValue) @This() { if (callback.isCallable()) { callback.protect(); return .{ .callback = callback }; @@ -314,7 +314,7 @@ pub const CallbackList = union(enum) { } /// protects the callback - pub fn push(self: *@This(), callback: JSC.JSValue, global: *JSC.JSGlobalObject) bun.JSError!void { + pub fn push(self: *@This(), callback: jsc.JSValue, global: *jsc.JSGlobalObject) bun.JSError!void { switch (self.*) { .ack_nack => unreachable, .none => { @@ -323,7 +323,7 @@ pub const CallbackList = union(enum) { }, .callback => { const prev = self.callback; - const arr = try JSC.JSValue.createEmptyArray(global, 2); + const arr = try jsc.JSValue.createEmptyArray(global, 2); arr.protect(); try arr.putIndex(global, 0, prev); // add the old callback to the array try arr.putIndex(global, 1, callback); // add the new callback to the array @@ -335,7 +335,7 @@ pub const CallbackList = union(enum) { }, } } - fn callNextTick(self: *@This(), global: *JSC.JSGlobalObject) bun.JSError!void { + fn callNextTick(self: *@This(), global: *jsc.JSGlobalObject) bun.JSError!void { switch (self.*) { .ack_nack => {}, .none => {}, @@ -377,7 +377,7 @@ pub const SendHandle = struct { } /// Call the callback and deinit - pub fn complete(self: *SendHandle, global: *JSC.JSGlobalObject) void { + pub fn complete(self: *SendHandle, global: *jsc.JSGlobalObject) void { defer self.deinit(); self.callbacks.callNextTick(global) catch {}; // TODO: properly propagate exception upwards } @@ -415,7 +415,7 @@ pub const SendQueue = struct { socket: SocketUnion, owner: SendQueueOwner, - close_next_tick: ?JSC.Task = null, + close_next_tick: ?jsc.Task = null, write_in_progress: bool = false, close_event_sent: bool = false, @@ -430,7 +430,7 @@ pub const SendQueue = struct { pub const SendQueueOwner = union(enum) { subprocess: *bun.api.Subprocess, - virtual_machine: *bun.JSC.VirtualMachine.IPCInstance, + virtual_machine: *bun.jsc.VirtualMachine.IPCInstance, }; pub const SocketType = switch (Environment.isWindows) { true => *uv.Pipe, @@ -459,7 +459,7 @@ pub const SendQueue = struct { // if there is a close next tick task, cancel it so it doesn't get called and then UAF if (self.close_next_tick) |close_next_tick_task| { - const managed: *bun.JSC.ManagedTask = close_next_tick_task.as(bun.JSC.ManagedTask); + const managed: *bun.jsc.ManagedTask = close_next_tick_task.as(bun.jsc.ManagedTask); managed.cancel(); } } @@ -537,8 +537,8 @@ pub const SendQueue = struct { this.closeSocket(.normal, .user); return; } - this.close_next_tick = JSC.ManagedTask.New(SendQueue, _closeSocketTask).init(this); - JSC.VirtualMachine.get().enqueueTask(this.close_next_tick.?); + this.close_next_tick = jsc.ManagedTask.New(SendQueue, _closeSocketTask).init(this); + jsc.VirtualMachine.get().enqueueTask(this.close_next_tick.?); } fn _closeSocketTask(this: *SendQueue) void { @@ -560,7 +560,7 @@ pub const SendQueue = struct { } /// returned pointer is invalidated if the queue is modified - pub fn startMessage(self: *SendQueue, global: *JSC.JSGlobalObject, callback: JSC.JSValue, handle: ?Handle) bun.JSError!*SendHandle { + pub fn startMessage(self: *SendQueue, global: *jsc.JSGlobalObject, callback: jsc.JSValue, handle: ?Handle) bun.JSError!*SendHandle { log("SendQueue#startMessage", .{}); if (Environment.allow_assert) bun.debugAssert(self.has_written_version == 1); @@ -654,7 +654,7 @@ pub const SendQueue = struct { new_message_appended, on_writable, }; - fn continueSend(this: *SendQueue, global: *JSC.JSGlobalObject, reason: ContinueSendReason) void { + fn continueSend(this: *SendQueue, global: *jsc.JSGlobalObject, reason: ContinueSendReason) void { log("IPC continueSend: {s}", .{@tagName(reason)}); this.debugLogMessageQueue(); defer this.updateRef(global); @@ -747,7 +747,7 @@ pub const SendQueue = struct { } if (Environment.allow_assert) this.has_written_version = 1; } - pub fn serializeAndSend(self: *SendQueue, global: *JSGlobalObject, value: JSValue, is_internal: IsInternal, callback: JSC.JSValue, handle: ?Handle) SerializeAndSendResult { + pub fn serializeAndSend(self: *SendQueue, global: *JSGlobalObject, value: JSValue, is_internal: IsInternal, callback: jsc.JSValue, handle: ?Handle) SerializeAndSendResult { log("SendQueue#serializeAndSend", .{}); const indicate_backoff = self.waiting_for_ack != null and self.queue.items.len > 0; const msg = self.startMessage(global, callback, handle) catch return .failure; @@ -832,7 +832,7 @@ pub const SendQueue = struct { break :blk write_req.owner orelse return; // orelse case if disconnected before the write completes }; - const vm = JSC.VirtualMachine.get(); + const vm = jsc.VirtualMachine.get(); vm.eventLoop().enter(); defer vm.eventLoop().exit(); @@ -848,7 +848,7 @@ pub const SendQueue = struct { this.closeSocket(.normal, .user); } } - fn getGlobalThis(this: *SendQueue) *JSC.JSGlobalObject { + fn getGlobalThis(this: *SendQueue) *jsc.JSGlobalObject { return switch (this.owner) { inline else => |owner| owner.globalThis, }; @@ -859,7 +859,7 @@ pub const SendQueue = struct { bun.default_allocator.destroy(this); } - pub fn windowsConfigureServer(this: *SendQueue, ipc_pipe: *uv.Pipe) JSC.Maybe(void) { + pub fn windowsConfigureServer(this: *SendQueue, ipc_pipe: *uv.Pipe) jsc.Maybe(void) { log("configureServer", .{}); ipc_pipe.data = this; ipc_pipe.unref(); @@ -903,26 +903,26 @@ pub const SendQueue = struct { }; const MAX_HANDLE_RETRANSMISSIONS = 3; -fn emitProcessErrorEvent(globalThis: *JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { +fn emitProcessErrorEvent(globalThis: *JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { const ex = callframe.argumentsAsArray(1)[0]; - JSC.VirtualMachine.Process__emitErrorEvent(globalThis, ex); + jsc.VirtualMachine.Process__emitErrorEvent(globalThis, ex); return .js_undefined; } const FromEnum = enum { subprocess_exited, subprocess, process }; -fn doSendErr(globalObject: *JSC.JSGlobalObject, callback: JSC.JSValue, ex: JSC.JSValue, from: FromEnum) bun.JSError!JSC.JSValue { +fn doSendErr(globalObject: *jsc.JSGlobalObject, callback: jsc.JSValue, ex: jsc.JSValue, from: FromEnum) bun.JSError!jsc.JSValue { if (callback.isCallable()) { try callback.callNextTick(globalObject, .{ex}); return .false; } if (from == .process) { - const target = JSC.JSFunction.create(globalObject, bun.String.empty, emitProcessErrorEvent, 1, .{}); + const target = jsc.JSFunction.create(globalObject, bun.String.empty, emitProcessErrorEvent, 1, .{}); try target.callNextTick(globalObject, .{ex}); return .false; } // Bun.spawn().send() should throw an error (unless callback is passed) return globalObject.throwValue(ex); } -pub fn doSend(ipc: ?*SendQueue, globalObject: *JSC.JSGlobalObject, callFrame: *JSC.CallFrame, from: FromEnum) bun.JSError!JSValue { +pub fn doSend(ipc: ?*SendQueue, globalObject: *jsc.JSGlobalObject, callFrame: *jsc.CallFrame, from: FromEnum) bun.JSError!JSValue { var message, var handle, var options_, var callback = callFrame.argumentsAsArray(4); if (handle.isCallable()) { @@ -956,7 +956,7 @@ pub fn doSend(ipc: ?*SendQueue, globalObject: *JSC.JSGlobalObject, callFrame: *J } if (!handle.isUndefinedOrNull()) { - const serialized_array: JSC.JSValue = try ipcSerialize(globalObject, message, handle); + const serialized_array: jsc.JSValue = try ipcSerialize(globalObject, message, handle); if (serialized_array.isUndefinedOrNull()) { handle = .js_undefined; } else { @@ -969,7 +969,7 @@ pub fn doSend(ipc: ?*SendQueue, globalObject: *JSC.JSGlobalObject, callFrame: *J var zig_handle: ?Handle = null; if (!handle.isUndefinedOrNull()) { - if (bun.JSC.API.Listener.fromJS(handle)) |listener| { + if (bun.jsc.API.Listener.fromJS(handle)) |listener| { log("got listener", .{}); switch (listener.listener) { .uws => |socket_uws| { @@ -991,7 +991,7 @@ pub fn doSend(ipc: ?*SendQueue, globalObject: *JSC.JSGlobalObject, callFrame: *J if (status == .failure) { const ex = globalObject.createTypeErrorInstance("process.send() failed", .{}); - ex.put(globalObject, JSC.ZigString.static("syscall"), bun.String.static("write").toJS(globalObject)); + ex.put(globalObject, jsc.ZigString.static("syscall"), bun.String.static("write").toJS(globalObject)); return doSendErr(globalObject, callback, ex, from); } @@ -999,28 +999,28 @@ pub fn doSend(ipc: ?*SendQueue, globalObject: *JSC.JSGlobalObject, callFrame: *J return if (status == .success) .true else .false; } -pub fn emitHandleIPCMessage(globalThis: *JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { +pub fn emitHandleIPCMessage(globalThis: *JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { const target, const message, const handle = callframe.argumentsAsArray(3); if (target.isNull()) { const ipc = globalThis.bunVM().getIPCInstance() orelse return .js_undefined; ipc.handleIPCMessage(.{ .data = message }, handle); } else { if (!target.isCell()) return .js_undefined; - const subprocess = bun.JSC.Subprocess.fromJSDirect(target) orelse return .js_undefined; + const subprocess = bun.jsc.Subprocess.fromJSDirect(target) orelse return .js_undefined; subprocess.handleIPCMessage(.{ .data = message }, handle); } return .js_undefined; } const IPCCommand = union(enum) { - handle: JSC.JSValue, + handle: jsc.JSValue, ack, nack, }; -fn handleIPCMessage(send_queue: *SendQueue, message: DecodedIPCMessage, globalThis: *JSC.JSGlobalObject) void { +fn handleIPCMessage(send_queue: *SendQueue, message: DecodedIPCMessage, globalThis: *jsc.JSGlobalObject) void { if (Environment.isDebug) { - var formatter = JSC.ConsoleObject.Formatter{ .globalThis = globalThis }; + var formatter = jsc.ConsoleObject.Formatter{ .globalThis = globalThis }; defer formatter.deinit(); switch (message) { .version => |version| log("received ipc message: version: {}", .{version}), @@ -1078,9 +1078,9 @@ fn handleIPCMessage(send_queue: *SendQueue, message: DecodedIPCMessage, globalTh const fd = send_queue.incoming_fd.?; send_queue.incoming_fd = null; - const target: bun.JSC.JSValue = switch (send_queue.owner) { + const target: bun.jsc.JSValue = switch (send_queue.owner) { .subprocess => |subprocess| subprocess.this_jsvalue, - .virtual_machine => bun.JSC.JSValue.null, + .virtual_machine => bun.jsc.JSValue.null, }; const vm = globalThis.bunVM(); @@ -1358,25 +1358,26 @@ pub const IPCHandlers = struct { }; }; -pub fn ipcSerialize(globalObject: *JSC.JSGlobalObject, message: JSC.JSValue, handle: JSC.JSValue) bun.JSError!JSC.JSValue { +pub fn ipcSerialize(globalObject: *jsc.JSGlobalObject, message: jsc.JSValue, handle: jsc.JSValue) bun.JSError!jsc.JSValue { return bun.cpp.IPCSerialize(globalObject, message, handle); } -pub fn ipcParse(globalObject: *JSC.JSGlobalObject, target: JSC.JSValue, serialized: JSC.JSValue, fd: JSC.JSValue) bun.JSError!JSC.JSValue { +pub fn ipcParse(globalObject: *jsc.JSGlobalObject, target: jsc.JSValue, serialized: jsc.JSValue, fd: jsc.JSValue) bun.JSError!jsc.JSValue { return bun.cpp.IPCParse(globalObject, target, serialized, fd); } +const string = []const u8; + const node_cluster_binding = @import("./node/node_cluster_binding.zig"); const std = @import("std"); const bun = @import("bun"); const Environment = bun.Environment; const Output = bun.Output; -const string = bun.string; const strings = bun.strings; const uws = bun.uws; const uv = bun.windows.libuv; -const JSC = bun.JSC; -const JSGlobalObject = JSC.JSGlobalObject; -const JSValue = JSC.JSValue; +const jsc = bun.jsc; +const JSGlobalObject = jsc.JSGlobalObject; +const JSValue = jsc.JSValue; diff --git a/src/bun.js/javascript_core_c_api.zig b/src/bun.js/javascript_core_c_api.zig index 3510a2123e..c295df5ee1 100644 --- a/src/bun.js/javascript_core_c_api.zig +++ b/src/bun.js/javascript_core_c_api.zig @@ -2,20 +2,20 @@ /// **** DO NOT USE THIS ON NEW CODE **** /// ************************************* /// To generate a new class exposed to JavaScript, look at *.classes.ts -/// Otherwise, use `JSC.JSValue`. +/// Otherwise, use `jsc.JSValue`. /// ************************************ const bun = @import("bun"); -const JSC = bun.JSC; +const jsc = bun.jsc; const generic = opaque { - pub fn value(this: *const generic) JSC.JSValue { - return @enumFromInt(@as(JSC.JSValue.backing_int, @bitCast(@intFromPtr(this)))); + pub fn value(this: *const generic) jsc.JSValue { + return @enumFromInt(@as(jsc.JSValue.backing_int, @bitCast(@intFromPtr(this)))); } }; pub const Private = anyopaque; pub const struct_OpaqueJSContextGroup = generic; pub const JSContextGroupRef = ?*const struct_OpaqueJSContextGroup; pub const struct_OpaqueJSContext = generic; -pub const JSGlobalContextRef = ?*JSC.JSGlobalObject; +pub const JSGlobalContextRef = ?*jsc.JSGlobalObject; pub const struct_OpaqueJSPropertyNameAccumulator = generic; pub const JSPropertyNameAccumulatorRef = ?*struct_OpaqueJSPropertyNameAccumulator; @@ -23,7 +23,7 @@ pub const JSTypedArrayBytesDeallocator = ?*const fn (*anyopaque, *anyopaque) cal pub const OpaqueJSValue = generic; pub const JSValueRef = ?*OpaqueJSValue; pub const JSObjectRef = ?*OpaqueJSValue; -pub extern fn JSGarbageCollect(ctx: *JSC.JSGlobalObject) void; +pub extern fn JSGarbageCollect(ctx: *jsc.JSGlobalObject) void; pub const JSType = enum(c_uint) { kJSTypeUndefined, kJSTypeNull, @@ -68,10 +68,10 @@ pub const kJSTypedArrayTypeFloat32Array = @intFromEnum(JSTypedArrayType.kJSTyped pub const kJSTypedArrayTypeFloat64Array = @intFromEnum(JSTypedArrayType.kJSTypedArrayTypeFloat64Array); pub const kJSTypedArrayTypeArrayBuffer = @intFromEnum(JSTypedArrayType.kJSTypedArrayTypeArrayBuffer); pub const kJSTypedArrayTypeNone = @intFromEnum(JSTypedArrayType.kJSTypedArrayTypeNone); -pub extern fn JSValueGetType(ctx: *JSC.JSGlobalObject, value: JSValueRef) JSType; -pub extern fn JSValueMakeNull(ctx: *JSC.JSGlobalObject) JSValueRef; -pub extern fn JSValueToNumber(ctx: *JSC.JSGlobalObject, value: JSValueRef, exception: ExceptionRef) f64; -pub extern fn JSValueToObject(ctx: *JSC.JSGlobalObject, value: JSValueRef, exception: ExceptionRef) JSObjectRef; +pub extern fn JSValueGetType(ctx: *jsc.JSGlobalObject, value: JSValueRef) JSType; +pub extern fn JSValueMakeNull(ctx: *jsc.JSGlobalObject) JSValueRef; +pub extern fn JSValueToNumber(ctx: *jsc.JSGlobalObject, value: JSValueRef, exception: ExceptionRef) f64; +pub extern fn JSValueToObject(ctx: *jsc.JSGlobalObject, value: JSValueRef, exception: ExceptionRef) JSObjectRef; pub const JSPropertyAttributes = enum(c_uint) { kJSPropertyAttributeNone = 0, @@ -92,40 +92,40 @@ pub const JSClassAttributes = enum(c_uint) { pub const kJSClassAttributeNone = @intFromEnum(JSClassAttributes.kJSClassAttributeNone); pub const kJSClassAttributeNoAutomaticPrototype = @intFromEnum(JSClassAttributes.kJSClassAttributeNoAutomaticPrototype); -pub const JSObjectInitializeCallback = *const fn (*JSC.JSGlobalObject, JSObjectRef) callconv(.C) void; +pub const JSObjectInitializeCallback = *const fn (*jsc.JSGlobalObject, JSObjectRef) callconv(.C) void; pub const JSObjectFinalizeCallback = *const fn (JSObjectRef) callconv(.C) void; -pub const JSObjectGetPropertyNamesCallback = *const fn (*JSC.JSGlobalObject, JSObjectRef, JSPropertyNameAccumulatorRef) callconv(.C) void; +pub const JSObjectGetPropertyNamesCallback = *const fn (*jsc.JSGlobalObject, JSObjectRef, JSPropertyNameAccumulatorRef) callconv(.C) void; pub const ExceptionRef = [*c]JSValueRef; pub const JSObjectCallAsFunctionCallback = *const fn ( - ctx: *JSC.JSGlobalObject, + ctx: *jsc.JSGlobalObject, function: JSObjectRef, thisObject: JSObjectRef, argumentCount: usize, arguments: [*c]const JSValueRef, exception: ExceptionRef, ) callconv(.C) JSValueRef; -pub const JSObjectCallAsConstructorCallback = *const fn (*JSC.JSGlobalObject, JSObjectRef, usize, [*c]const JSValueRef, ExceptionRef) callconv(.C) JSObjectRef; -pub const JSObjectHasInstanceCallback = *const fn (*JSC.JSGlobalObject, JSObjectRef, JSValueRef, ExceptionRef) callconv(.C) bool; -pub const JSObjectConvertToTypeCallback = *const fn (*JSC.JSGlobalObject, JSObjectRef, JSType, ExceptionRef) callconv(.C) JSValueRef; +pub const JSObjectCallAsConstructorCallback = *const fn (*jsc.JSGlobalObject, JSObjectRef, usize, [*c]const JSValueRef, ExceptionRef) callconv(.C) JSObjectRef; +pub const JSObjectHasInstanceCallback = *const fn (*jsc.JSGlobalObject, JSObjectRef, JSValueRef, ExceptionRef) callconv(.C) bool; +pub const JSObjectConvertToTypeCallback = *const fn (*jsc.JSGlobalObject, JSObjectRef, JSType, ExceptionRef) callconv(.C) JSValueRef; -pub extern "c" fn JSObjectGetPrototype(ctx: *JSC.JSGlobalObject, object: JSObjectRef) JSValueRef; -pub extern "c" fn JSObjectGetPropertyAtIndex(ctx: *JSC.JSGlobalObject, object: JSObjectRef, propertyIndex: c_uint, exception: ExceptionRef) JSValueRef; -pub extern "c" fn JSObjectSetPropertyAtIndex(ctx: *JSC.JSGlobalObject, object: JSObjectRef, propertyIndex: c_uint, value: JSValueRef, exception: ExceptionRef) void; -pub extern "c" fn JSObjectCallAsFunction(ctx: *JSC.JSGlobalObject, object: JSObjectRef, thisObject: JSObjectRef, argumentCount: usize, arguments: [*c]const JSValueRef, exception: ExceptionRef) JSValueRef; -pub extern "c" fn JSObjectIsConstructor(ctx: *JSC.JSGlobalObject, object: JSObjectRef) bool; -pub extern "c" fn JSObjectCallAsConstructor(ctx: *JSC.JSGlobalObject, object: JSObjectRef, argumentCount: usize, arguments: [*c]const JSValueRef, exception: ExceptionRef) JSObjectRef; -pub extern "c" fn JSObjectMakeDate(ctx: *JSC.JSGlobalObject, argumentCount: usize, arguments: [*c]const JSValueRef, exception: ExceptionRef) JSObjectRef; +pub extern "c" fn JSObjectGetPrototype(ctx: *jsc.JSGlobalObject, object: JSObjectRef) JSValueRef; +pub extern "c" fn JSObjectGetPropertyAtIndex(ctx: *jsc.JSGlobalObject, object: JSObjectRef, propertyIndex: c_uint, exception: ExceptionRef) JSValueRef; +pub extern "c" fn JSObjectSetPropertyAtIndex(ctx: *jsc.JSGlobalObject, object: JSObjectRef, propertyIndex: c_uint, value: JSValueRef, exception: ExceptionRef) void; +pub extern "c" fn JSObjectCallAsFunction(ctx: *jsc.JSGlobalObject, object: JSObjectRef, thisObject: JSObjectRef, argumentCount: usize, arguments: [*c]const JSValueRef, exception: ExceptionRef) JSValueRef; +pub extern "c" fn JSObjectIsConstructor(ctx: *jsc.JSGlobalObject, object: JSObjectRef) bool; +pub extern "c" fn JSObjectCallAsConstructor(ctx: *jsc.JSGlobalObject, object: JSObjectRef, argumentCount: usize, arguments: [*c]const JSValueRef, exception: ExceptionRef) JSObjectRef; +pub extern "c" fn JSObjectMakeDate(ctx: *jsc.JSGlobalObject, argumentCount: usize, arguments: [*c]const JSValueRef, exception: ExceptionRef) JSObjectRef; pub const JSChar = u16; -pub extern fn JSObjectMakeTypedArray(ctx: *JSC.JSGlobalObject, arrayType: JSTypedArrayType, length: usize, exception: ExceptionRef) JSObjectRef; -pub extern fn JSObjectMakeTypedArrayWithArrayBuffer(ctx: *JSC.JSGlobalObject, arrayType: JSTypedArrayType, buffer: JSObjectRef, exception: ExceptionRef) JSObjectRef; -pub extern fn JSObjectMakeTypedArrayWithArrayBufferAndOffset(ctx: *JSC.JSGlobalObject, arrayType: JSTypedArrayType, buffer: JSObjectRef, byteOffset: usize, length: usize, exception: ExceptionRef) JSObjectRef; -pub extern fn JSObjectGetTypedArrayBytesPtr(ctx: *JSC.JSGlobalObject, object: JSObjectRef, exception: ExceptionRef) ?*anyopaque; -pub extern fn JSObjectGetTypedArrayLength(ctx: *JSC.JSGlobalObject, object: JSObjectRef, exception: ExceptionRef) usize; -pub extern fn JSObjectGetTypedArrayByteLength(ctx: *JSC.JSGlobalObject, object: JSObjectRef, exception: ExceptionRef) usize; -pub extern fn JSObjectGetTypedArrayByteOffset(ctx: *JSC.JSGlobalObject, object: JSObjectRef, exception: ExceptionRef) usize; -pub extern fn JSObjectGetTypedArrayBuffer(ctx: *JSC.JSGlobalObject, object: JSObjectRef, exception: ExceptionRef) JSObjectRef; -pub extern fn JSObjectGetArrayBufferBytesPtr(ctx: *JSC.JSGlobalObject, object: JSObjectRef, exception: ExceptionRef) ?*anyopaque; -pub extern fn JSObjectGetArrayBufferByteLength(ctx: *JSC.JSGlobalObject, object: JSObjectRef, exception: ExceptionRef) usize; +pub extern fn JSObjectMakeTypedArray(ctx: *jsc.JSGlobalObject, arrayType: JSTypedArrayType, length: usize, exception: ExceptionRef) JSObjectRef; +pub extern fn JSObjectMakeTypedArrayWithArrayBuffer(ctx: *jsc.JSGlobalObject, arrayType: JSTypedArrayType, buffer: JSObjectRef, exception: ExceptionRef) JSObjectRef; +pub extern fn JSObjectMakeTypedArrayWithArrayBufferAndOffset(ctx: *jsc.JSGlobalObject, arrayType: JSTypedArrayType, buffer: JSObjectRef, byteOffset: usize, length: usize, exception: ExceptionRef) JSObjectRef; +pub extern fn JSObjectGetTypedArrayBytesPtr(ctx: *jsc.JSGlobalObject, object: JSObjectRef, exception: ExceptionRef) ?*anyopaque; +pub extern fn JSObjectGetTypedArrayLength(ctx: *jsc.JSGlobalObject, object: JSObjectRef, exception: ExceptionRef) usize; +pub extern fn JSObjectGetTypedArrayByteLength(ctx: *jsc.JSGlobalObject, object: JSObjectRef, exception: ExceptionRef) usize; +pub extern fn JSObjectGetTypedArrayByteOffset(ctx: *jsc.JSGlobalObject, object: JSObjectRef, exception: ExceptionRef) usize; +pub extern fn JSObjectGetTypedArrayBuffer(ctx: *jsc.JSGlobalObject, object: JSObjectRef, exception: ExceptionRef) JSObjectRef; +pub extern fn JSObjectGetArrayBufferBytesPtr(ctx: *jsc.JSGlobalObject, object: JSObjectRef, exception: ExceptionRef) ?*anyopaque; +pub extern fn JSObjectGetArrayBufferByteLength(ctx: *jsc.JSGlobalObject, object: JSObjectRef, exception: ExceptionRef) usize; pub const OpaqueJSContextGroup = struct_OpaqueJSContextGroup; pub const OpaqueJSContext = struct_OpaqueJSContext; pub const OpaqueJSPropertyNameAccumulator = struct_OpaqueJSPropertyNameAccumulator; @@ -133,7 +133,7 @@ pub const OpaqueJSPropertyNameAccumulator = struct_OpaqueJSPropertyNameAccumulat // This is a workaround for not receiving a JSException* object // This function lets us use the C API but returns a plain old JSValue // allowing us to have exceptions that include stack traces -pub extern "c" fn JSObjectCallAsFunctionReturnValueHoldingAPILock(ctx: *JSC.JSGlobalObject, object: JSObjectRef, thisObject: JSObjectRef, argumentCount: usize, arguments: [*c]const JSValueRef) JSC.JSValue; +pub extern "c" fn JSObjectCallAsFunctionReturnValueHoldingAPILock(ctx: *jsc.JSGlobalObject, object: JSObjectRef, thisObject: JSObjectRef, argumentCount: usize, arguments: [*c]const JSValueRef) jsc.JSValue; pub extern fn JSRemoteInspectorDisableAutoStart() void; pub extern fn JSRemoteInspectorStart() void; diff --git a/src/bun.js/jsc/array_buffer.zig b/src/bun.js/jsc/array_buffer.zig index 92b90d23a2..0af270dbca 100644 --- a/src/bun.js/jsc/array_buffer.zig +++ b/src/bun.js/jsc/array_buffer.zig @@ -3,15 +3,15 @@ pub const ArrayBuffer = extern struct { offset: usize = 0, len: usize = 0, byte_len: usize = 0, - typed_array_type: JSC.JSValue.JSType = .Cell, - value: JSC.JSValue = JSC.JSValue.zero, + typed_array_type: jsc.JSValue.JSType = .Cell, + value: jsc.JSValue = jsc.JSValue.zero, shared: bool = false, // require('buffer').kMaxLength. // keep in sync with Bun::Buffer::kMaxLength pub const max_size = std.math.maxInt(c_uint); - extern fn JSBuffer__fromMmap(*JSC.JSGlobalObject, addr: *anyopaque, len: usize) JSC.JSValue; + extern fn JSBuffer__fromMmap(*jsc.JSGlobalObject, addr: *anyopaque, len: usize) jsc.JSValue; // 4 MB or so is pretty good for mmap() const mmap_threshold = 1024 * 1024 * 4; @@ -29,7 +29,7 @@ pub const ArrayBuffer = extern struct { /// Only use this when reading from the file descriptor is _very_ cheap. Like, for example, an in-memory file descriptor. /// Do not use this for pipes, however tempting it may seem. - pub fn toJSBufferFromFd(fd: bun.FileDescriptor, size: usize, globalObject: *JSC.JSGlobalObject) JSC.JSValue { + pub fn toJSBufferFromFd(fd: bun.FileDescriptor, size: usize, globalObject: *jsc.JSGlobalObject) jsc.JSValue { const buffer_value = Bun__createUint8ArrayForCopy(globalObject, null, size, true); if (buffer_value == .zero) { return .zero; @@ -65,10 +65,10 @@ pub const ArrayBuffer = extern struct { return buffer_value; } - extern fn ArrayBuffer__fromSharedMemfd(fd: i64, globalObject: *JSC.JSGlobalObject, byte_offset: usize, byte_length: usize, total_size: usize, JSC.JSValue.JSType) JSC.JSValue; + extern fn ArrayBuffer__fromSharedMemfd(fd: i64, globalObject: *jsc.JSGlobalObject, byte_offset: usize, byte_length: usize, total_size: usize, jsc.JSValue.JSType) jsc.JSValue; pub const toArrayBufferFromSharedMemfd = ArrayBuffer__fromSharedMemfd; - pub fn toJSBufferFromMemfd(fd: bun.FileDescriptor, globalObject: *JSC.JSGlobalObject) bun.JSError!JSC.JSValue { + pub fn toJSBufferFromMemfd(fd: bun.FileDescriptor, globalObject: *jsc.JSGlobalObject) bun.JSError!jsc.JSValue { const stat = switch (bun.sys.fstat(fd)) { .err => |err| { fd.close(); @@ -116,11 +116,11 @@ pub const ArrayBuffer = extern struct { pub const Strong = struct { array_buffer: ArrayBuffer, - held: JSC.Strong.Optional = .empty, + held: jsc.Strong.Optional = .empty, pub fn clear(this: *ArrayBuffer.Strong) void { var ref: *bun.api.napi.Ref = this.ref orelse return; - ref.set(JSC.JSValue.zero); + ref.set(jsc.JSValue.zero); } pub fn slice(this: *const ArrayBuffer.Strong) []u8 { @@ -141,8 +141,8 @@ pub const ArrayBuffer = extern struct { return Stream{ .pos = 0, .buf = this.slice() }; } - pub fn create(globalThis: *JSC.JSGlobalObject, bytes: []const u8, comptime kind: JSC.JSValue.JSType) bun.JSError!JSC.JSValue { - JSC.markBinding(@src()); + pub fn create(globalThis: *jsc.JSGlobalObject, bytes: []const u8, comptime kind: jsc.JSValue.JSType) bun.JSError!jsc.JSValue { + jsc.markBinding(@src()); return switch (comptime kind) { .Uint8Array => bun.jsc.fromJSHostCall(globalThis, @src(), Bun__createUint8ArrayForCopy, .{ globalThis, bytes.ptr, bytes.len, false }), .ArrayBuffer => bun.jsc.fromJSHostCall(globalThis, @src(), Bun__createArrayBufferForCopy, .{ globalThis, bytes.ptr, bytes.len }), @@ -150,8 +150,8 @@ pub const ArrayBuffer = extern struct { }; } - pub fn createEmpty(globalThis: *JSC.JSGlobalObject, comptime kind: JSC.JSValue.JSType) bun.JSError!JSC.JSValue { - JSC.markBinding(@src()); + pub fn createEmpty(globalThis: *jsc.JSGlobalObject, comptime kind: jsc.JSValue.JSType) bun.JSError!jsc.JSValue { + jsc.markBinding(@src()); return switch (comptime kind) { .Uint8Array => bun.jsc.fromJSHostCall(Bun__createUint8ArrayForCopy, .{ globalThis, null, 0, false }), .ArrayBuffer => bun.jsc.fromJSHostCall(Bun__createArrayBufferForCopy, .{ globalThis, null, 0 }), @@ -159,20 +159,20 @@ pub const ArrayBuffer = extern struct { }; } - pub fn createBuffer(globalThis: *JSC.JSGlobalObject, bytes: []const u8) bun.JSError!JSC.JSValue { - JSC.markBinding(@src()); + pub fn createBuffer(globalThis: *jsc.JSGlobalObject, bytes: []const u8) bun.JSError!jsc.JSValue { + jsc.markBinding(@src()); return bun.jsc.fromJSHostCall(globalThis, @src(), Bun__createUint8ArrayForCopy, .{ globalThis, bytes.ptr, bytes.len, true }); } - pub fn createUint8Array(globalThis: *JSC.JSGlobalObject, bytes: []const u8) bun.JSError!JSC.JSValue { - JSC.markBinding(@src()); + pub fn createUint8Array(globalThis: *jsc.JSGlobalObject, bytes: []const u8) bun.JSError!jsc.JSValue { + jsc.markBinding(@src()); return bun.jsc.fromJSHostCall(globalThis, @src(), Bun__createUint8ArrayForCopy, .{ globalThis, bytes.ptr, bytes.len, false }); } - extern "c" fn Bun__allocUint8ArrayForCopy(*JSC.JSGlobalObject, usize, **anyopaque) JSC.JSValue; - extern "c" fn Bun__allocArrayBufferForCopy(*JSC.JSGlobalObject, usize, **anyopaque) JSC.JSValue; + extern "c" fn Bun__allocUint8ArrayForCopy(*jsc.JSGlobalObject, usize, **anyopaque) jsc.JSValue; + extern "c" fn Bun__allocArrayBufferForCopy(*jsc.JSGlobalObject, usize, **anyopaque) jsc.JSValue; - pub fn alloc(global: *JSC.JSGlobalObject, comptime kind: JSC.JSValue.JSType, len: u32) JSError!struct { JSC.JSValue, []u8 } { + pub fn alloc(global: *jsc.JSGlobalObject, comptime kind: jsc.JSValue.JSType, len: u32) JSError!struct { jsc.JSValue, []u8 } { var ptr: [*]u8 = undefined; const buf = switch (comptime kind) { .Uint8Array => try bun.jsc.fromJSHostCall(global, @src(), Bun__allocUint8ArrayForCopy, .{ global, len, @ptrCast(&ptr) }), @@ -182,10 +182,10 @@ pub const ArrayBuffer = extern struct { return .{ buf, ptr[0..len] }; } - extern "c" fn Bun__createUint8ArrayForCopy(*JSC.JSGlobalObject, ptr: ?*const anyopaque, len: usize, buffer: bool) JSC.JSValue; - extern "c" fn Bun__createArrayBufferForCopy(*JSC.JSGlobalObject, ptr: ?*const anyopaque, len: usize) JSC.JSValue; + extern "c" fn Bun__createUint8ArrayForCopy(*jsc.JSGlobalObject, ptr: ?*const anyopaque, len: usize, buffer: bool) jsc.JSValue; + extern "c" fn Bun__createArrayBufferForCopy(*jsc.JSGlobalObject, ptr: ?*const anyopaque, len: usize) jsc.JSValue; - pub fn fromTypedArray(ctx: *JSC.JSGlobalObject, value: JSC.JSValue) ArrayBuffer { + pub fn fromTypedArray(ctx: *jsc.JSGlobalObject, value: jsc.JSValue) ArrayBuffer { var out: ArrayBuffer = .{}; const was = value.asArrayBuffer_(ctx, &out); bun.assert(was); @@ -193,24 +193,24 @@ pub const ArrayBuffer = extern struct { return out; } - extern "c" fn JSArrayBuffer__fromDefaultAllocator(*JSC.JSGlobalObject, ptr: [*]u8, len: usize) JSC.JSValue; - pub fn toJSFromDefaultAllocator(globalThis: *JSC.JSGlobalObject, bytes: []u8) JSC.JSValue { + extern "c" fn JSArrayBuffer__fromDefaultAllocator(*jsc.JSGlobalObject, ptr: [*]u8, len: usize) jsc.JSValue; + pub fn toJSFromDefaultAllocator(globalThis: *jsc.JSGlobalObject, bytes: []u8) jsc.JSValue { return JSArrayBuffer__fromDefaultAllocator(globalThis, bytes.ptr, bytes.len); } - pub fn fromDefaultAllocator(globalThis: *JSC.JSGlobalObject, bytes: []u8, comptime typed_array_type: JSC.JSValue.JSType) JSC.JSValue { + pub fn fromDefaultAllocator(globalThis: *jsc.JSGlobalObject, bytes: []u8, comptime typed_array_type: jsc.JSValue.JSType) jsc.JSValue { return switch (typed_array_type) { .ArrayBuffer => JSArrayBuffer__fromDefaultAllocator(globalThis, bytes.ptr, bytes.len), - .Uint8Array => JSC.JSUint8Array.fromBytes(globalThis, bytes), + .Uint8Array => jsc.JSUint8Array.fromBytes(globalThis, bytes), else => @compileError("Not implemented yet"), }; } - pub fn fromBytes(bytes: []u8, typed_array_type: JSC.JSValue.JSType) ArrayBuffer { + pub fn fromBytes(bytes: []u8, typed_array_type: jsc.JSValue.JSType) ArrayBuffer { return ArrayBuffer{ .offset = 0, .len = @as(u32, @intCast(bytes.len)), .byte_len = @as(u32, @intCast(bytes.len)), .typed_array_type = typed_array_type, .ptr = bytes.ptr }; } - pub fn toJSUnchecked(this: ArrayBuffer, ctx: *JSC.JSGlobalObject) bun.JSError!JSC.JSValue { + pub fn toJSUnchecked(this: ArrayBuffer, ctx: *jsc.JSGlobalObject) bun.JSError!jsc.JSValue { // The reason for this is // JSC C API returns a detached arraybuffer // if you pass it a zero-length TypedArray @@ -250,13 +250,13 @@ pub const ArrayBuffer = extern struct { const log = Output.scoped(.ArrayBuffer, false); - pub fn toJS(this: ArrayBuffer, ctx: *JSC.JSGlobalObject) bun.JSError!JSC.JSValue { + pub fn toJS(this: ArrayBuffer, ctx: *jsc.JSGlobalObject) bun.JSError!jsc.JSValue { if (this.value != .zero) { return this.value; } // If it's not a mimalloc heap buffer, we're not going to call a deallocator - if (this.len > 0 and !bun.Mimalloc.mi_is_in_heap_region(this.ptr)) { + if (this.len > 0 and !bun.mimalloc.mi_is_in_heap_region(this.ptr)) { log("toJS but will never free: {d} bytes", .{this.len}); if (this.typed_array_type == .ArrayBuffer) { @@ -284,10 +284,10 @@ pub const ArrayBuffer = extern struct { pub fn toJSWithContext( this: ArrayBuffer, - ctx: *JSC.JSGlobalObject, + ctx: *jsc.JSGlobalObject, deallocator: ?*anyopaque, - callback: JSC.C.JSTypedArrayBytesDeallocator, - ) bun.JSError!JSC.JSValue { + callback: jsc.C.JSTypedArrayBytesDeallocator, + ) bun.JSError!jsc.JSValue { if (this.value != .zero) { return this.value; } @@ -359,7 +359,7 @@ pub const ArrayBuffer = extern struct { BigUint64Array, // DataView, - pub fn toJSType(this: BinaryType) JSC.JSValue.JSType { + pub fn toJSType(this: BinaryType) jsc.JSValue.JSType { return switch (this) { .ArrayBuffer => .ArrayBuffer, .Buffer => .Uint8Array, @@ -433,7 +433,7 @@ pub const ArrayBuffer = extern struct { return Map.get(input); } - pub fn fromJSValue(globalThis: *JSC.JSGlobalObject, input: JSC.JSValue) bun.JSError!?BinaryType { + pub fn fromJSValue(globalThis: *jsc.JSGlobalObject, input: jsc.JSValue) bun.JSError!?BinaryType { if (input.isString()) { return Map.getWithEql(try input.toBunString(globalThis), bun.String.eqlComptime); } @@ -442,11 +442,11 @@ pub const ArrayBuffer = extern struct { } /// This clones bytes - pub fn toJS(this: BinaryType, bytes: []const u8, globalThis: *JSC.JSGlobalObject) bun.JSError!JSC.JSValue { + pub fn toJS(this: BinaryType, bytes: []const u8, globalThis: *jsc.JSGlobalObject) bun.JSError!jsc.JSValue { switch (this) { - .Buffer => return JSC.ArrayBuffer.createBuffer(globalThis, bytes), - .ArrayBuffer => return JSC.ArrayBuffer.create(globalThis, bytes, .ArrayBuffer), - .Uint8Array => return JSC.ArrayBuffer.create(globalThis, bytes, .Uint8Array), + .Buffer => return jsc.ArrayBuffer.createBuffer(globalThis, bytes), + .ArrayBuffer => return jsc.ArrayBuffer.create(globalThis, bytes, .ArrayBuffer), + .Uint8Array => return jsc.ArrayBuffer.create(globalThis, bytes, .Uint8Array), // These aren't documented, but they are supported .Uint8ClampedArray, @@ -461,8 +461,8 @@ pub const ArrayBuffer = extern struct { .BigInt64Array, .BigUint64Array, => { - const buffer = try JSC.ArrayBuffer.create(globalThis, bytes, .ArrayBuffer); - return JSC.JSValue.c(JSC.C.JSObjectMakeTypedArrayWithArrayBuffer(globalThis, this.toTypedArrayType().toC(), buffer.asObjectRef(), null)); + const buffer = try jsc.ArrayBuffer.create(globalThis, bytes, .ArrayBuffer); + return jsc.JSValue.c(jsc.C.JSObjectMakeTypedArrayWithArrayBuffer(globalThis, this.toTypedArrayType().toC(), buffer.asObjectRef(), null)); }, } } @@ -485,7 +485,7 @@ pub const ArrayBuffer = extern struct { TypeBigUint64, TypeDataView, - pub fn toC(this: TypedArrayType) JSC.C.JSTypedArrayType { + pub fn toC(this: TypedArrayType) jsc.C.JSTypedArrayType { return switch (this) { .TypeNone => .kJSTypedArrayTypeNone, .TypeInt8 => .kJSTypedArrayTypeInt8Array, @@ -533,14 +533,14 @@ pub const MarkedArrayBuffer = struct { return this.buffer.stream(); } - pub fn fromTypedArray(ctx: *JSC.JSGlobalObject, value: JSC.JSValue) MarkedArrayBuffer { + pub fn fromTypedArray(ctx: *jsc.JSGlobalObject, value: jsc.JSValue) MarkedArrayBuffer { return MarkedArrayBuffer{ .allocator = null, .buffer = ArrayBuffer.fromTypedArray(ctx, value), }; } - pub fn fromArrayBuffer(ctx: *JSC.JSGlobalObject, value: JSC.JSValue) MarkedArrayBuffer { + pub fn fromArrayBuffer(ctx: *jsc.JSGlobalObject, value: jsc.JSValue) MarkedArrayBuffer { return MarkedArrayBuffer{ .allocator = null, .buffer = ArrayBuffer.fromArrayBuffer(ctx, value), @@ -549,15 +549,15 @@ pub const MarkedArrayBuffer = struct { pub fn fromString(str: []const u8, allocator: std.mem.Allocator) !MarkedArrayBuffer { const buf = try allocator.dupe(u8, str); - return MarkedArrayBuffer.fromBytes(buf, allocator, JSC.JSValue.JSType.Uint8Array); + return MarkedArrayBuffer.fromBytes(buf, allocator, jsc.JSValue.JSType.Uint8Array); } - pub fn fromJS(global: *JSC.JSGlobalObject, value: JSC.JSValue) ?MarkedArrayBuffer { + pub fn fromJS(global: *jsc.JSGlobalObject, value: jsc.JSValue) ?MarkedArrayBuffer { const array_buffer = value.asArrayBuffer(global) orelse return null; return MarkedArrayBuffer{ .buffer = array_buffer, .allocator = null }; } - pub fn fromBytes(bytes: []u8, allocator: std.mem.Allocator, typed_array_type: JSC.JSValue.JSType) MarkedArrayBuffer { + pub fn fromBytes(bytes: []u8, allocator: std.mem.Allocator, typed_array_type: jsc.JSValue.JSType) MarkedArrayBuffer { return MarkedArrayBuffer{ .buffer = ArrayBuffer.fromBytes(bytes, typed_array_type), .allocator = allocator, @@ -582,18 +582,18 @@ pub const MarkedArrayBuffer = struct { } } - pub fn init(allocator: std.mem.Allocator, size: u32, typed_array_type: JSC.JSValue.JSType) !*MarkedArrayBuffer { + pub fn init(allocator: std.mem.Allocator, size: u32, typed_array_type: jsc.JSValue.JSType) !*MarkedArrayBuffer { const bytes = try allocator.alloc(u8, size); const container = try allocator.create(MarkedArrayBuffer); container.* = MarkedArrayBuffer.fromBytes(bytes, allocator, typed_array_type); return container; } - pub fn toNodeBuffer(this: *const MarkedArrayBuffer, ctx: *JSC.JSGlobalObject) JSC.JSValue { - return JSC.JSValue.createBufferWithCtx(ctx, this.buffer.byteSlice(), this.buffer.ptr, MarkedArrayBuffer_deallocator); + pub fn toNodeBuffer(this: *const MarkedArrayBuffer, ctx: *jsc.JSGlobalObject) jsc.JSValue { + return jsc.JSValue.createBufferWithCtx(ctx, this.buffer.byteSlice(), this.buffer.ptr, MarkedArrayBuffer_deallocator); } - pub fn toJS(this: *const MarkedArrayBuffer, globalObject: *JSC.JSGlobalObject) bun.JSError!JSC.JSValue { + pub fn toJS(this: *const MarkedArrayBuffer, globalObject: *jsc.JSGlobalObject) bun.JSError!jsc.JSValue { if (!this.buffer.value.isEmptyOrUndefinedOrNull()) { return this.buffer.value; } @@ -619,13 +619,13 @@ pub const MarkedArrayBuffer = struct { }; pub export fn MarkedArrayBuffer_deallocator(bytes_: *anyopaque, _: *anyopaque) void { - const mimalloc = bun.Mimalloc; + const mimalloc = bun.mimalloc; // zig's memory allocator interface won't work here // mimalloc knows the size of things // but we don't // if (comptime Environment.allow_assert) { // bun.assert(mimalloc.mi_check_owned(bytes_) or - // mimalloc.mi_heap_check_owned(JSC.VirtualMachine.get().arena.heap.?, bytes_)); + // mimalloc.mi_heap_check_owned(jsc.VirtualMachine.get().arena.heap.?, bytes_)); // } mimalloc.mi_free(bytes_); @@ -635,24 +635,24 @@ pub export fn BlobArrayBuffer_deallocator(_: *anyopaque, blob: *anyopaque) void // zig's memory allocator interface won't work here // mimalloc knows the size of things // but we don't - var store = bun.cast(*JSC.WebCore.Blob.Store, blob); + var store = bun.cast(*jsc.WebCore.Blob.Store, blob); store.deref(); } -extern fn Bun__makeArrayBufferWithBytesNoCopy(*JSC.JSGlobalObject, ?*anyopaque, usize, JSC.C.JSTypedArrayBytesDeallocator, ?*anyopaque) JSC.JSValue; -extern fn Bun__makeTypedArrayWithBytesNoCopy(*JSC.JSGlobalObject, ArrayBuffer.TypedArrayType, ?*anyopaque, usize, JSC.C.JSTypedArrayBytesDeallocator, ?*anyopaque) JSC.JSValue; +extern fn Bun__makeArrayBufferWithBytesNoCopy(*jsc.JSGlobalObject, ?*anyopaque, usize, jsc.C.JSTypedArrayBytesDeallocator, ?*anyopaque) jsc.JSValue; +extern fn Bun__makeTypedArrayWithBytesNoCopy(*jsc.JSGlobalObject, ArrayBuffer.TypedArrayType, ?*anyopaque, usize, jsc.C.JSTypedArrayBytesDeallocator, ?*anyopaque) jsc.JSValue; -pub fn makeArrayBufferWithBytesNoCopy(globalObject: *JSC.JSGlobalObject, ptr: ?*anyopaque, len: usize, deallocator: JSC.C.JSTypedArrayBytesDeallocator, deallocatorContext: ?*anyopaque) bun.JSError!JSC.JSValue { +pub fn makeArrayBufferWithBytesNoCopy(globalObject: *jsc.JSGlobalObject, ptr: ?*anyopaque, len: usize, deallocator: jsc.C.JSTypedArrayBytesDeallocator, deallocatorContext: ?*anyopaque) bun.JSError!jsc.JSValue { return bun.jsc.fromJSHostCall(globalObject, @src(), Bun__makeArrayBufferWithBytesNoCopy, .{ globalObject, ptr, len, deallocator, deallocatorContext }); } -pub fn makeTypedArrayWithBytesNoCopy(globalObject: *JSC.JSGlobalObject, arrayType: ArrayBuffer.TypedArrayType, ptr: ?*anyopaque, len: usize, deallocator: JSC.C.JSTypedArrayBytesDeallocator, deallocatorContext: ?*anyopaque) bun.JSError!JSC.JSValue { +pub fn makeTypedArrayWithBytesNoCopy(globalObject: *jsc.JSGlobalObject, arrayType: ArrayBuffer.TypedArrayType, ptr: ?*anyopaque, len: usize, deallocator: jsc.C.JSTypedArrayBytesDeallocator, deallocatorContext: ?*anyopaque) bun.JSError!jsc.JSValue { return bun.jsc.fromJSHostCall(globalObject, @src(), Bun__makeTypedArrayWithBytesNoCopy, .{ globalObject, arrayType, ptr, len, deallocator, deallocatorContext }); } const std = @import("std"); const bun = @import("bun"); -const JSC = bun.jsc; const JSError = bun.JSError; const Output = bun.Output; +const jsc = bun.jsc; diff --git a/src/bun.js/node.zig b/src/bun.js/node.zig index 98e1be6c59..176f09f7d7 100644 --- a/src/bun.js/node.zig +++ b/src/bun.js/node.zig @@ -18,7 +18,7 @@ pub const process = @import("./node/node_process.zig"); pub const validators = @import("./node/util/validators.zig"); pub const ErrorCode = @import("./node/nodejs_error_code.zig").Code; -pub const Buffer = JSC.MarkedArrayBuffer; +pub const Buffer = jsc.MarkedArrayBuffer; pub const PathOrBlob = types.PathOrBlob; pub const Dirent = types.Dirent; @@ -190,23 +190,23 @@ pub fn Maybe(comptime ReturnTypeT: type, comptime ErrorTypeT: type) type { }; } - pub fn toJS(this: @This(), globalObject: *JSC.JSGlobalObject) bun.JSError!JSC.JSValue { + pub fn toJS(this: @This(), globalObject: *jsc.JSGlobalObject) bun.JSError!jsc.JSValue { return switch (this) { .result => |r| switch (ReturnType) { - JSC.JSValue => r, + jsc.JSValue => r, void => .js_undefined, - bool => JSC.JSValue.jsBoolean(r), + bool => jsc.JSValue.jsBoolean(r), - JSC.ArrayBuffer => r.toJS(globalObject), - []u8 => JSC.ArrayBuffer.fromBytes(r, .ArrayBuffer).toJS(globalObject), + jsc.ArrayBuffer => r.toJS(globalObject), + []u8 => jsc.ArrayBuffer.fromBytes(r, .ArrayBuffer).toJS(globalObject), else => switch (@typeInfo(ReturnType)) { - .int, .float, .comptime_int, .comptime_float => JSC.JSValue.jsNumber(r), + .int, .float, .comptime_int, .comptime_float => jsc.JSValue.jsNumber(r), .@"struct", .@"enum", .@"opaque", .@"union" => r.toJS(globalObject), .pointer => { if (bun.trait.isZigString(ReturnType)) - JSC.ZigString.init(bun.asByteSlice(r)).withEncoding().toJS(globalObject); + jsc.ZigString.init(bun.asByteSlice(r)).withEncoding().toJS(globalObject); return r.toJS(globalObject); }, @@ -216,9 +216,9 @@ pub fn Maybe(comptime ReturnTypeT: type, comptime ErrorTypeT: type) type { }; } - pub fn toArrayBuffer(this: @This(), globalObject: *JSC.JSGlobalObject) JSC.JSValue { + pub fn toArrayBuffer(this: @This(), globalObject: *jsc.JSGlobalObject) jsc.JSValue { return switch (this) { - .result => |r| JSC.ArrayBuffer.fromBytes(r, .ArrayBuffer).toJS(globalObject, null), + .result => |r| jsc.ArrayBuffer.fromBytes(r, .ArrayBuffer).toJS(globalObject, null), .err => |e| e.toJS(globalObject), }; } @@ -357,7 +357,7 @@ const types = @import("./node/types.zig"); const bun = @import("bun"); const Environment = bun.Environment; -const JSC = bun.JSC; +const jsc = bun.jsc; const meta = bun.meta; const sys = bun.sys; const windows = bun.windows; diff --git a/src/bun.js/node/Stat.zig b/src/bun.js/node/Stat.zig index f13dc0a0c3..45e3492ec0 100644 --- a/src/bun.js/node/Stat.zig +++ b/src/bun.js/node/Stat.zig @@ -44,11 +44,11 @@ pub fn StatType(comptime big: bool) type { } } - pub fn toJS(this: *const @This(), globalObject: *JSC.JSGlobalObject) bun.JSError!JSC.JSValue { + pub fn toJS(this: *const @This(), globalObject: *jsc.JSGlobalObject) bun.JSError!jsc.JSValue { return statToJS(&this.value, globalObject); } - pub fn getConstructor(globalObject: *JSC.JSGlobalObject) JSC.JSValue { + pub fn getConstructor(globalObject: *jsc.JSGlobalObject) jsc.JSValue { return if (big) Bun__JSBigIntStatsObjectConstructor(globalObject) else Bun__JSStatsObjectConstructor(globalObject); } @@ -56,7 +56,7 @@ pub fn StatType(comptime big: bool) type { return @intCast(@min(@max(value, 0), std.math.maxInt(i64))); } - fn statToJS(stat_: *const bun.Stat, globalObject: *JSC.JSGlobalObject) bun.JSError!JSC.JSValue { + fn statToJS(stat_: *const bun.Stat, globalObject: *jsc.JSGlobalObject) bun.JSError!jsc.JSValue { const aTime = stat_.atime(); const mTime = stat_.mtime(); const cTime = stat_.ctime(); @@ -129,11 +129,11 @@ pub fn StatType(comptime big: bool) type { } }; } -extern fn Bun__JSBigIntStatsObjectConstructor(*JSC.JSGlobalObject) JSC.JSValue; -extern fn Bun__JSStatsObjectConstructor(*JSC.JSGlobalObject) JSC.JSValue; +extern fn Bun__JSBigIntStatsObjectConstructor(*jsc.JSGlobalObject) jsc.JSValue; +extern fn Bun__JSStatsObjectConstructor(*jsc.JSGlobalObject) jsc.JSValue; extern fn Bun__createJSStatsObject( - globalObject: *JSC.JSGlobalObject, + globalObject: *jsc.JSGlobalObject, dev: i64, ino: i64, mode: i64, @@ -148,10 +148,10 @@ extern fn Bun__createJSStatsObject( mtimeMs: f64, ctimeMs: f64, birthtimeMs: f64, -) JSC.JSValue; +) jsc.JSValue; extern fn Bun__createJSBigIntStatsObject( - globalObject: *JSC.JSGlobalObject, + globalObject: *jsc.JSGlobalObject, dev: i64, ino: i64, mode: i64, @@ -170,7 +170,7 @@ extern fn Bun__createJSBigIntStatsObject( mtimeNs: u64, ctimeNs: u64, birthtimeNs: u64, -) JSC.JSValue; +) jsc.JSValue; pub const StatsSmall = StatType(false); pub const StatsBig = StatType(true); @@ -188,14 +188,14 @@ pub const Stats = union(enum) { } } - pub fn toJSNewlyCreated(this: *const Stats, globalObject: *JSC.JSGlobalObject) bun.JSError!JSC.JSValue { + pub fn toJSNewlyCreated(this: *const Stats, globalObject: *jsc.JSGlobalObject) bun.JSError!jsc.JSValue { return switch (this.*) { .big => this.big.toJS(globalObject), .small => this.small.toJS(globalObject), }; } - pub inline fn toJS(this: *Stats, globalObject: *JSC.JSGlobalObject) JSC.JSValue { + pub inline fn toJS(this: *Stats, globalObject: *jsc.JSGlobalObject) jsc.JSValue { _ = this; _ = globalObject; @@ -207,4 +207,4 @@ const std = @import("std"); const bun = @import("bun"); const Environment = bun.Environment; -const JSC = bun.JSC; +const jsc = bun.jsc; diff --git a/src/bun.js/node/StatFS.zig b/src/bun.js/node/StatFS.zig index 03f267080b..d0f3577023 100644 --- a/src/bun.js/node/StatFS.zig +++ b/src/bun.js/node/StatFS.zig @@ -15,11 +15,11 @@ pub fn StatFSType(comptime big: bool) type { const This = @This(); - pub fn toJS(this: *const This, globalObject: *JSC.JSGlobalObject) bun.JSError!JSC.JSValue { + pub fn toJS(this: *const This, globalObject: *jsc.JSGlobalObject) bun.JSError!jsc.JSValue { return statfsToJS(this, globalObject); } - fn statfsToJS(this: *const This, globalObject: *JSC.JSGlobalObject) bun.JSError!JSC.JSValue { + fn statfsToJS(this: *const This, globalObject: *jsc.JSGlobalObject) bun.JSError!jsc.JSValue { if (big) { return bun.jsc.fromJSHostCall(globalObject, @src(), Bun__createJSBigIntStatFSObject, .{ globalObject, @@ -80,11 +80,11 @@ pub fn StatFSType(comptime big: bool) type { }; } -extern fn Bun__JSBigIntStatFSObjectConstructor(*JSC.JSGlobalObject) JSC.JSValue; -extern fn Bun__JSStatFSObjectConstructor(*JSC.JSGlobalObject) JSC.JSValue; +extern fn Bun__JSBigIntStatFSObjectConstructor(*jsc.JSGlobalObject) jsc.JSValue; +extern fn Bun__JSStatFSObjectConstructor(*jsc.JSGlobalObject) jsc.JSValue; extern fn Bun__createJSStatFSObject( - globalObject: *JSC.JSGlobalObject, + globalObject: *jsc.JSGlobalObject, fstype: i64, bsize: i64, blocks: i64, @@ -92,10 +92,10 @@ extern fn Bun__createJSStatFSObject( bavail: i64, files: i64, ffree: i64, -) JSC.JSValue; +) jsc.JSValue; extern fn Bun__createJSBigIntStatFSObject( - globalObject: *JSC.JSGlobalObject, + globalObject: *jsc.JSGlobalObject, fstype: i64, bsize: i64, blocks: i64, @@ -103,7 +103,7 @@ extern fn Bun__createJSBigIntStatFSObject( bavail: i64, files: i64, ffree: i64, -) JSC.JSValue; +) jsc.JSValue; pub const StatFSSmall = StatFSType(false); pub const StatFSBig = StatFSType(true); @@ -121,14 +121,14 @@ pub const StatFS = union(enum) { } } - pub fn toJSNewlyCreated(this: *const StatFS, globalObject: *JSC.JSGlobalObject) bun.JSError!JSC.JSValue { + pub fn toJSNewlyCreated(this: *const StatFS, globalObject: *jsc.JSGlobalObject) bun.JSError!jsc.JSValue { return switch (this.*) { .big => |*big| big.toJS(globalObject), .small => |*small| small.toJS(globalObject), }; } - pub inline fn toJS(this: *StatFS, globalObject: *JSC.JSGlobalObject) JSC.JSValue { + pub inline fn toJS(this: *StatFS, globalObject: *jsc.JSGlobalObject) jsc.JSValue { _ = this; _ = globalObject; @@ -138,4 +138,4 @@ pub const StatFS = union(enum) { const bun = @import("bun"); const Environment = bun.Environment; -const JSC = bun.JSC; +const jsc = bun.jsc; diff --git a/src/bun.js/node/buffer.zig b/src/bun.js/node/buffer.zig index ba2aeea3e4..f9be0f93d3 100644 --- a/src/bun.js/node/buffer.zig +++ b/src/bun.js/node/buffer.zig @@ -1,9 +1,9 @@ pub const BufferVectorized = struct { pub fn fill( - str: *JSC.ZigString, + str: *jsc.ZigString, buf_ptr: [*]u8, fill_length: usize, - encoding: JSC.Node.Encoding, + encoding: jsc.Node.Encoding, ) callconv(.C) bool { if (str.len == 0) return true; @@ -86,5 +86,5 @@ const std = @import("std"); const bun = @import("bun"); const Environment = bun.Environment; -const JSC = bun.JSC; -const Encoder = JSC.WebCore.encoding; +const jsc = bun.jsc; +const Encoder = jsc.WebCore.encoding; diff --git a/src/bun.js/node/dir_iterator.zig b/src/bun.js/node/dir_iterator.zig index 76e920c525..05ab1d3c73 100644 --- a/src/bun.js/node/dir_iterator.zig +++ b/src/bun.js/node/dir_iterator.zig @@ -471,9 +471,9 @@ const FD = bun.FD; const PathString = bun.PathString; const strings = bun.strings; -const JSC = bun.JSC; -const Maybe = JSC.Maybe; -const Entry = JSC.Node.Dirent; +const jsc = bun.jsc; +const Maybe = jsc.Maybe; +const Entry = jsc.Node.Dirent; const std = @import("std"); const mem = std.mem; diff --git a/src/bun.js/node/fs_events.zig b/src/bun.js/node/fs_events.zig index 172ddfe7e5..59df4243ff 100644 --- a/src/bun.js/node/fs_events.zig +++ b/src/bun.js/node/fs_events.zig @@ -619,6 +619,8 @@ pub fn closeAndWait() void { } } +const string = []const u8; + const std = @import("std"); const Semaphore = std.Thread.Semaphore; @@ -627,6 +629,5 @@ const EventType = PathWatcher.EventType; const bun = @import("bun"); const Mutex = bun.Mutex; -const string = bun.string; const UnboundedQueue = bun.threading.UnboundedQueue; -const Event = bun.JSC.Node.fs.Watcher.Event; +const Event = bun.jsc.Node.fs.Watcher.Event; diff --git a/src/bun.js/node/net/BlockList.zig b/src/bun.js/node/net/BlockList.zig index 4c56a25ab8..38ddfad2e5 100644 --- a/src/bun.js/node/net/BlockList.zig +++ b/src/bun.js/node/net/BlockList.zig @@ -7,11 +7,11 @@ pub const fromJS = js.fromJS; pub const toJS = js.toJS; ref_count: RefCount = .init(), -globalThis: *JSC.JSGlobalObject, +globalThis: *jsc.JSGlobalObject, da_rules: std.ArrayList(Rule), mutex: bun.Mutex = .{}, -pub fn constructor(globalThis: *JSC.JSGlobalObject, callFrame: *JSC.CallFrame) bun.JSError!*@This() { +pub fn constructor(globalThis: *jsc.JSGlobalObject, callFrame: *jsc.CallFrame) bun.JSError!*@This() { _ = callFrame; const ptr = @This().new(.{ .globalThis = globalThis, @@ -35,13 +35,13 @@ pub fn deinit(this: *@This()) void { bun.destroy(this); } -pub fn isBlockList(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { +pub fn isBlockList(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { _ = globalThis; const value = callframe.argumentsAsArray(1)[0]; return .jsBoolean(value.as(@This()) != null); } -pub fn addAddress(this: *@This(), globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { +pub fn addAddress(this: *@This(), globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { this.mutex.lock(); defer this.mutex.unlock(); const arguments = callframe.argumentsAsArray(2); @@ -56,7 +56,7 @@ pub fn addAddress(this: *@This(), globalThis: *JSC.JSGlobalObject, callframe: *J return .js_undefined; } -pub fn addRange(this: *@This(), globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { +pub fn addRange(this: *@This(), globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { this.mutex.lock(); defer this.mutex.unlock(); const arguments = callframe.argumentsAsArray(3); @@ -81,7 +81,7 @@ pub fn addRange(this: *@This(), globalThis: *JSC.JSGlobalObject, callframe: *JSC return .js_undefined; } -pub fn addSubnet(this: *@This(), globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { +pub fn addSubnet(this: *@This(), globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { this.mutex.lock(); defer this.mutex.unlock(); const arguments = callframe.argumentsAsArray(3); @@ -102,7 +102,7 @@ pub fn addSubnet(this: *@This(), globalThis: *JSC.JSGlobalObject, callframe: *JS return .js_undefined; } -pub fn check(this: *@This(), globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { +pub fn check(this: *@This(), globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { this.mutex.lock(); defer this.mutex.unlock(); const arguments = callframe.argumentsAsArray(2); @@ -153,10 +153,10 @@ pub fn check(this: *@This(), globalThis: *JSC.JSGlobalObject, callframe: *JSC.Ca return .jsBoolean(false); } -pub fn rules(this: *@This(), globalThis: *JSC.JSGlobalObject) bun.JSError!JSC.JSValue { +pub fn rules(this: *@This(), globalThis: *jsc.JSGlobalObject) bun.JSError!jsc.JSValue { this.mutex.lock(); defer this.mutex.unlock(); - var list = std.ArrayList(JSC.JSValue).initCapacity(bun.default_allocator, this.da_rules.items.len) catch bun.outOfMemory(); + var list = std.ArrayList(jsc.JSValue).initCapacity(bun.default_allocator, this.da_rules.items.len) catch bun.outOfMemory(); defer list.deinit(); for (this.da_rules.items) |rule| { switch (rule) { @@ -175,10 +175,10 @@ pub fn rules(this: *@This(), globalThis: *JSC.JSGlobalObject) bun.JSError!JSC.JS }, } } - return JSC.JSArray.create(globalThis, list.items); + return jsc.JSArray.create(globalThis, list.items); } -pub fn onStructuredCloneSerialize(this: *@This(), globalThis: *JSC.JSGlobalObject, ctx: *anyopaque, writeBytes: *const fn (*anyopaque, ptr: [*]const u8, len: u32) callconv(JSC.conv) void) void { +pub fn onStructuredCloneSerialize(this: *@This(), globalThis: *jsc.JSGlobalObject, ctx: *anyopaque, writeBytes: *const fn (*anyopaque, ptr: [*]const u8, len: u32) callconv(jsc.conv) void) void { _ = globalThis; this.mutex.lock(); defer this.mutex.unlock(); @@ -189,7 +189,7 @@ pub fn onStructuredCloneSerialize(this: *@This(), globalThis: *JSC.JSGlobalObjec const StructuredCloneWriter = struct { ctx: *anyopaque, - impl: *const fn (*anyopaque, ptr: [*]const u8, len: u32) callconv(JSC.conv) void, + impl: *const fn (*anyopaque, ptr: [*]const u8, len: u32) callconv(jsc.conv) void, pub const Writer = std.io.Writer(@This(), Error, write); pub const Error = error{}; @@ -200,7 +200,7 @@ const StructuredCloneWriter = struct { } }; -pub fn onStructuredCloneDeserialize(globalThis: *JSC.JSGlobalObject, ptr: [*]u8, end: [*]u8) bun.JSError!JSC.JSValue { +pub fn onStructuredCloneDeserialize(globalThis: *jsc.JSGlobalObject, ptr: [*]u8, end: [*]u8) bun.JSError!jsc.JSValue { const total_length: usize = @intFromPtr(end) - @intFromPtr(ptr); var buffer_stream = std.io.fixedBufferStream(ptr[0..total_length]); const reader = buffer_stream.reader(); @@ -230,8 +230,8 @@ const std = @import("std"); const validators = @import("../util/validators.zig"); const bun = @import("bun"); -const JSC = bun.JSC; -const js = JSC.Codegen.JSBlockList; +const jsc = bun.jsc; +const js = jsc.Codegen.JSBlockList; -const SocketAddress = bun.JSC.GeneratedClassesList.SocketAddress; +const SocketAddress = bun.jsc.GeneratedClassesList.SocketAddress; const sockaddr = SocketAddress.sockaddr; diff --git a/src/bun.js/node/node_assert.zig b/src/bun.js/node/node_assert.zig index fd9dea23d0..9c9deeb26b 100644 --- a/src/bun.js/node/node_assert.zig +++ b/src/bun.js/node/node_assert.zig @@ -12,7 +12,7 @@ /// - `actual` and `expected` are alive and have the same encoding. pub fn myersDiff( allocator: Allocator, - global: *JSC.JSGlobalObject, + global: *jsc.JSGlobalObject, actual: *const BunString, expected: *const BunString, // If true, strings that have a trailing comma but are otherwise equal are @@ -20,14 +20,14 @@ pub fn myersDiff( check_comma_disparity: bool, // split `actual` and `expected` into lines before diffing lines: bool, -) bun.JSError!JSC.JSValue { +) bun.JSError!jsc.JSValue { // Short circuit on empty strings. Note that, in release builds where // assertions are disabled, if `actual` and `expected` are both dead, this // branch will be hit since dead strings have a length of 0. This should be // moot since BunStrings with non-zero reference counds should never be // dead. if (actual.length() == 0 and expected.length() == 0) { - return try JSC.JSValue.createEmptyArray(global, 0); + return try jsc.JSValue.createEmptyArray(global, 0); } const actual_encoding = actual.encoding(); @@ -67,10 +67,10 @@ pub fn myersDiff( fn diffChars( comptime T: type, allocator: Allocator, - global: *JSC.JSGlobalObject, + global: *jsc.JSGlobalObject, actual: []const T, expected: []const T, -) bun.JSError!JSC.JSValue { +) bun.JSError!jsc.JSValue { const Differ = MyersDiff.Differ(T, .{ .check_comma_disparity = false }); const diff: MyersDiff.DiffList(T) = Differ.diff(allocator, actual, expected) catch |err| return mapDiffError(global, err); return diffListToJS(T, global, diff); @@ -79,11 +79,11 @@ fn diffChars( fn diffLines( comptime T: type, allocator: Allocator, - global: *JSC.JSGlobalObject, + global: *jsc.JSGlobalObject, actual: []const T, expected: []const T, check_comma_disparity: bool, -) bun.JSError!JSC.JSValue { +) bun.JSError!jsc.JSValue { var a = try MyersDiff.split(T, allocator, actual); defer a.deinit(allocator); var e = try MyersDiff.split(T, allocator, expected); @@ -101,15 +101,15 @@ fn diffLines( return diffListToJS([]const T, global, diff); } -fn diffListToJS(comptime T: type, global: *JSC.JSGlobalObject, diff_list: MyersDiff.DiffList(T)) bun.JSError!JSC.JSValue { - var array = try JSC.JSValue.createEmptyArray(global, diff_list.items.len); +fn diffListToJS(comptime T: type, global: *jsc.JSGlobalObject, diff_list: MyersDiff.DiffList(T)) bun.JSError!jsc.JSValue { + var array = try jsc.JSValue.createEmptyArray(global, diff_list.items.len); for (diff_list.items, 0..) |*line, i| { - try array.putIndex(global, @truncate(i), (try JSC.JSObject.createNullProto(line.*, global)).toJS()); + try array.putIndex(global, @truncate(i), (try jsc.JSObject.createNullProto(line.*, global)).toJS()); } return array; } -fn mapDiffError(global: *JSC.JSGlobalObject, err: MyersDiff.Error) bun.JSError { +fn mapDiffError(global: *jsc.JSGlobalObject, err: MyersDiff.Error) bun.JSError { return switch (err) { error.OutOfMemory => error.OutOfMemory, error.DiffTooLarge => global.throwInvalidArguments("Diffing these two values would create a string that is too large. If this was intentional, please open a bug report on GitHub.", .{}), @@ -124,5 +124,5 @@ const Allocator = std.mem.Allocator; const bun = @import("bun"); const BunString = bun.String; -const JSC = bun.JSC; -const JSValue = JSC.JSValue; +const jsc = bun.jsc; +const JSValue = jsc.JSValue; diff --git a/src/bun.js/node/node_assert_binding.zig b/src/bun.js/node/node_assert_binding.zig index 6e2c12f82c..7355decd01 100644 --- a/src/bun.js/node/node_assert_binding.zig +++ b/src/bun.js/node/node_assert_binding.zig @@ -7,7 +7,7 @@ /// type Diff = { operation: DiffType, text: string }; /// declare function myersDiff(actual: string, expected: string): Diff[]; /// ``` -pub fn myersDiff(global: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { +pub fn myersDiff(global: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { var stack_fallback = std.heap.stackFallback(1024 * 2, bun.default_allocator); var arena = std.heap.ArenaAllocator.init(stack_fallback.get()); defer arena.deinit(); @@ -49,14 +49,14 @@ pub fn myersDiff(global: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSE } const StrDiffList = DiffList([]const u8); -fn diffListToJS(global: *JSC.JSGlobalObject, diff_list: StrDiffList) bun.JSError!JSC.JSValue { +fn diffListToJS(global: *jsc.JSGlobalObject, diff_list: StrDiffList) bun.JSError!jsc.JSValue { // todo: replace with toJS - var array = try JSC.JSValue.createEmptyArray(global, diff_list.items.len); + var array = try jsc.JSValue.createEmptyArray(global, diff_list.items.len); for (diff_list.items, 0..) |*line, i| { - var obj = JSC.JSValue.createEmptyObjectWithNullPrototype(global); + var obj = jsc.JSValue.createEmptyObjectWithNullPrototype(global); if (obj == .zero) return global.throwOutOfMemory(); - obj.put(global, bun.String.static("kind"), JSC.JSValue.jsNumber(@as(u32, @intFromEnum(line.kind)))); - obj.put(global, bun.String.static("value"), JSC.toJS(global, []const u8, line.value)); + obj.put(global, bun.String.static("kind"), jsc.JSValue.jsNumber(@as(u32, @intFromEnum(line.kind)))); + obj.put(global, bun.String.static("value"), jsc.toJS(global, []const u8, line.value)); array.putIndex(global, @truncate(i), obj); } return array; @@ -64,13 +64,13 @@ fn diffListToJS(global: *JSC.JSGlobalObject, diff_list: StrDiffList) bun.JSError // ============================================================================= -pub fn generate(global: *JSC.JSGlobalObject) JSC.JSValue { - const exports = JSC.JSValue.createEmptyObject(global, 1); +pub fn generate(global: *jsc.JSGlobalObject) jsc.JSValue { + const exports = jsc.JSValue.createEmptyObject(global, 1); exports.put( global, bun.String.static("myersDiff"), - JSC.JSFunction.create(global, "myersDiff", myersDiff, 2, .{}), + jsc.JSFunction.create(global, "myersDiff", myersDiff, 2, .{}), ); return exports; @@ -81,5 +81,5 @@ const bun = @import("bun"); const std = @import("std"); const DiffList = @import("./assert/myers_diff.zig").DiffList; -const JSC = bun.JSC; -const JSValue = JSC.JSValue; +const jsc = bun.jsc; +const JSValue = jsc.JSValue; diff --git a/src/bun.js/node/node_cluster_binding.zig b/src/bun.js/node/node_cluster_binding.zig index e61134d002..176694b211 100644 --- a/src/bun.js/node/node_cluster_binding.zig +++ b/src/bun.js/node/node_cluster_binding.zig @@ -1,16 +1,16 @@ // Most of this code should be rewritten. -// - Usage of JSC.Strong.Optional here is likely to cause memory leaks. +// - Usage of jsc.Strong.Optional here is likely to cause memory leaks. // - These sequence numbers and ACKs shouldn't exist from JavaScript's perspective // at all. It should happen in the protocol before it reaches JS. // - We should not be creating JSFunction's in process.nextTick. const log = Output.scoped(.IPC, false); -extern fn Bun__Process__queueNextTick1(*JSC.JSGlobalObject, JSC.JSValue, JSC.JSValue) void; -extern fn Process__emitErrorEvent(global: *JSC.JSGlobalObject, value: JSC.JSValue) void; +extern fn Bun__Process__queueNextTick1(*jsc.JSGlobalObject, jsc.JSValue, jsc.JSValue) void; +extern fn Process__emitErrorEvent(global: *jsc.JSGlobalObject, value: jsc.JSValue) void; pub var child_singleton: InternalMsgHolder = .{}; -pub fn sendHelperChild(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { +pub fn sendHelperChild(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { log("sendHelperChild", .{}); const arguments = callframe.arguments_old(3).ptr; @@ -35,22 +35,22 @@ pub fn sendHelperChild(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFram if (callback.isFunction()) { // TODO: remove this strong. This is expensive and would be an easy way to create a memory leak. // These sequence numbers shouldn't exist from JavaScript's perspective at all. - child_singleton.callbacks.put(bun.default_allocator, child_singleton.seq, JSC.Strong.Optional.create(callback, globalThis)) catch bun.outOfMemory(); + child_singleton.callbacks.put(bun.default_allocator, child_singleton.seq, jsc.Strong.Optional.create(callback, globalThis)) catch bun.outOfMemory(); } // sequence number for InternalMsgHolder - message.put(globalThis, ZigString.static("seq"), JSC.JSValue.jsNumber(child_singleton.seq)); + message.put(globalThis, ZigString.static("seq"), jsc.JSValue.jsNumber(child_singleton.seq)); child_singleton.seq +%= 1; // similar code as Bun__Process__send - var formatter = JSC.ConsoleObject.Formatter{ .globalThis = globalThis }; + var formatter = jsc.ConsoleObject.Formatter{ .globalThis = globalThis }; defer formatter.deinit(); if (Environment.isDebug) log("child: {}", .{message.toFmt(&formatter)}); const ipc_instance = vm.getIPCInstance().?; const S = struct { - fn impl(globalThis_: *JSC.JSGlobalObject, callframe_: *JSC.CallFrame) bun.JSError!JSC.JSValue { + fn impl(globalThis_: *jsc.JSGlobalObject, callframe_: *jsc.CallFrame) bun.JSError!jsc.JSValue { const arguments_ = callframe_.arguments_old(1).slice(); const ex = arguments_[0]; Process__emitErrorEvent(globalThis_, ex.toError() orelse ex); @@ -63,7 +63,7 @@ pub fn sendHelperChild(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFram if (good == .failure) { const ex = globalThis.createTypeErrorInstance("sendInternal() failed", .{}); ex.put(globalThis, ZigString.static("syscall"), bun.String.static("write").toJS(globalThis)); - const fnvalue = JSC.JSFunction.create(globalThis, "", S.impl, 1, .{}); + const fnvalue = jsc.JSFunction.create(globalThis, "", S.impl, 1, .{}); try fnvalue.callNextTick(globalThis, .{ex}); return .false; } @@ -71,17 +71,17 @@ pub fn sendHelperChild(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFram return if (good == .success) .true else .false; } -pub fn onInternalMessageChild(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { +pub fn onInternalMessageChild(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { log("onInternalMessageChild", .{}); const arguments = callframe.arguments_old(2).ptr; - // TODO: we should not create two JSC.Strong.Optional here. If absolutely necessary, a single Array. should be all we use. + // TODO: we should not create two jsc.Strong.Optional here. If absolutely necessary, a single Array. should be all we use. child_singleton.worker = .create(arguments[0], globalThis); child_singleton.cb = .create(arguments[1], globalThis); try child_singleton.flush(globalThis); return .js_undefined; } -pub fn handleInternalMessageChild(globalThis: *JSC.JSGlobalObject, message: JSC.JSValue) bun.JSError!void { +pub fn handleInternalMessageChild(globalThis: *jsc.JSGlobalObject, message: jsc.JSValue) bun.JSError!void { log("handleInternalMessageChild", .{}); try child_singleton.dispatch(message, globalThis); @@ -96,22 +96,22 @@ pub const InternalMsgHolder = struct { // TODO: move this to an Array or a JS Object or something which doesn't // individually create a Strong for every single IPC message... - callbacks: std.AutoArrayHashMapUnmanaged(i32, JSC.Strong.Optional) = .{}, - worker: JSC.Strong.Optional = .empty, - cb: JSC.Strong.Optional = .empty, - messages: std.ArrayListUnmanaged(JSC.Strong.Optional) = .{}, + callbacks: std.AutoArrayHashMapUnmanaged(i32, jsc.Strong.Optional) = .{}, + worker: jsc.Strong.Optional = .empty, + cb: jsc.Strong.Optional = .empty, + messages: std.ArrayListUnmanaged(jsc.Strong.Optional) = .{}, pub fn isReady(this: *InternalMsgHolder) bool { return this.worker.has() and this.cb.has(); } - pub fn enqueue(this: *InternalMsgHolder, message: JSC.JSValue, globalThis: *JSC.JSGlobalObject) void { + pub fn enqueue(this: *InternalMsgHolder, message: jsc.JSValue, globalThis: *jsc.JSGlobalObject) void { //TODO: .addOne is workaround for .append causing crash/ dependency loop in zig compiler const new_item_ptr = this.messages.addOne(bun.default_allocator) catch bun.outOfMemory(); new_item_ptr.* = .create(message, globalThis); } - pub fn dispatch(this: *InternalMsgHolder, message: JSC.JSValue, globalThis: *JSC.JSGlobalObject) bun.JSError!void { + pub fn dispatch(this: *InternalMsgHolder, message: jsc.JSValue, globalThis: *jsc.JSGlobalObject) bun.JSError!void { if (!this.isReady()) { this.enqueue(message, globalThis); return; @@ -119,7 +119,7 @@ pub const InternalMsgHolder = struct { try this.dispatchUnsafe(message, globalThis); } - fn dispatchUnsafe(this: *InternalMsgHolder, message: JSC.JSValue, globalThis: *JSC.JSGlobalObject) bun.JSError!void { + fn dispatchUnsafe(this: *InternalMsgHolder, message: jsc.JSValue, globalThis: *jsc.JSGlobalObject) bun.JSError!void { const cb = this.cb.get().?; const worker = this.worker.get().?; @@ -149,7 +149,7 @@ pub const InternalMsgHolder = struct { }); } - pub fn flush(this: *InternalMsgHolder, globalThis: *JSC.JSGlobalObject) bun.JSError!void { + pub fn flush(this: *InternalMsgHolder, globalThis: *jsc.JSGlobalObject) bun.JSError!void { bun.assert(this.isReady()); var messages = this.messages; this.messages = .{}; @@ -172,11 +172,11 @@ pub const InternalMsgHolder = struct { } }; -pub fn sendHelperPrimary(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { +pub fn sendHelperPrimary(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { log("sendHelperPrimary", .{}); const arguments = callframe.arguments_old(4).ptr; - const subprocess = arguments[0].as(bun.JSC.Subprocess).?; + const subprocess = arguments[0].as(bun.jsc.Subprocess).?; const message = arguments[1]; const handle = arguments[2]; const callback = arguments[3]; @@ -190,15 +190,15 @@ pub fn sendHelperPrimary(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFr return globalThis.throwInvalidArgumentTypeValue("message", "object", message); } if (callback.isFunction()) { - ipc_data.internal_msg_queue.callbacks.put(bun.default_allocator, ipc_data.internal_msg_queue.seq, JSC.Strong.Optional.create(callback, globalThis)) catch bun.outOfMemory(); + ipc_data.internal_msg_queue.callbacks.put(bun.default_allocator, ipc_data.internal_msg_queue.seq, jsc.Strong.Optional.create(callback, globalThis)) catch bun.outOfMemory(); } // sequence number for InternalMsgHolder - message.put(globalThis, ZigString.static("seq"), JSC.JSValue.jsNumber(ipc_data.internal_msg_queue.seq)); + message.put(globalThis, ZigString.static("seq"), jsc.JSValue.jsNumber(ipc_data.internal_msg_queue.seq)); ipc_data.internal_msg_queue.seq +%= 1; - // similar code as bun.JSC.Subprocess.doSend - var formatter = JSC.ConsoleObject.Formatter{ .globalThis = globalThis }; + // similar code as bun.jsc.Subprocess.doSend + var formatter = jsc.ConsoleObject.Formatter{ .globalThis = globalThis }; defer formatter.deinit(); if (Environment.isDebug) log("primary: {}", .{message.toFmt(&formatter)}); @@ -207,9 +207,9 @@ pub fn sendHelperPrimary(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFr return if (success == .success) .true else .false; } -pub fn onInternalMessagePrimary(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { +pub fn onInternalMessagePrimary(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const arguments = callframe.arguments_old(3).ptr; - const subprocess = arguments[0].as(bun.JSC.Subprocess).?; + const subprocess = arguments[0].as(bun.jsc.Subprocess).?; const ipc_data = subprocess.ipc() orelse return .js_undefined; // TODO: remove these strongs. ipc_data.internal_msg_queue.worker = .create(arguments[1], globalThis); @@ -217,7 +217,7 @@ pub fn onInternalMessagePrimary(globalThis: *JSC.JSGlobalObject, callframe: *JSC return .js_undefined; } -pub fn handleInternalMessagePrimary(globalThis: *JSC.JSGlobalObject, subprocess: *JSC.Subprocess, message: JSC.JSValue) bun.JSError!void { +pub fn handleInternalMessagePrimary(globalThis: *jsc.JSGlobalObject, subprocess: *jsc.Subprocess, message: jsc.JSValue) bun.JSError!void { const ipc_data = subprocess.ipc() orelse return; const event_loop = globalThis.bunVM().eventLoop(); @@ -251,7 +251,7 @@ pub fn handleInternalMessagePrimary(globalThis: *JSC.JSGlobalObject, subprocess: // // -pub fn setRef(globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { +pub fn setRef(globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const arguments = callframe.arguments_old(1).ptr; if (arguments.len == 0) { @@ -272,24 +272,24 @@ pub fn setRef(globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun. return .js_undefined; } -export fn Bun__refChannelUnlessOverridden(globalObject: *JSC.JSGlobalObject) void { +export fn Bun__refChannelUnlessOverridden(globalObject: *jsc.JSGlobalObject) void { const vm = globalObject.bunVM(); if (!vm.channel_ref_overridden) { vm.channel_ref.ref(vm); } } -export fn Bun__unrefChannelUnlessOverridden(globalObject: *JSC.JSGlobalObject) void { +export fn Bun__unrefChannelUnlessOverridden(globalObject: *jsc.JSGlobalObject) void { const vm = globalObject.bunVM(); if (!vm.channel_ref_overridden) { vm.channel_ref.unref(vm); } } -pub fn channelIgnoreOneDisconnectEventListener(globalObject: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!JSC.JSValue { +pub fn channelIgnoreOneDisconnectEventListener(globalObject: *jsc.JSGlobalObject, _: *jsc.CallFrame) bun.JSError!jsc.JSValue { const vm = globalObject.bunVM(); vm.channel_ref_should_ignore_one_disconnect_event_listener = true; return .false; } -export fn Bun__shouldIgnoreOneDisconnectEventListener(globalObject: *JSC.JSGlobalObject) bool { +export fn Bun__shouldIgnoreOneDisconnectEventListener(globalObject: *jsc.JSGlobalObject) bool { const vm = globalObject.bunVM(); return vm.channel_ref_should_ignore_one_disconnect_event_listener; } @@ -300,5 +300,5 @@ const bun = @import("bun"); const Environment = bun.Environment; const Output = bun.Output; -const JSC = bun.JSC; -const ZigString = JSC.ZigString; +const jsc = bun.jsc; +const ZigString = jsc.ZigString; diff --git a/src/bun.js/node/node_crypto_binding.zig b/src/bun.js/node/node_crypto_binding.zig index 62f37586b4..94a249e077 100644 --- a/src/bun.js/node/node_crypto_binding.zig +++ b/src/bun.js/node/node_crypto_binding.zig @@ -1,10 +1,10 @@ fn ExternCryptoJob(comptime name: []const u8) type { return struct { - vm: *JSC.VirtualMachine, - task: JSC.WorkPoolTask, - any_task: JSC.AnyTask, + vm: *jsc.VirtualMachine, + task: jsc.WorkPoolTask, + any_task: jsc.AnyTask, poll: Async.KeepAlive = .{}, - callback: JSC.Strong.Optional, + callback: jsc.Strong.Optional, ctx: *Ctx, @@ -32,7 +32,7 @@ fn ExternCryptoJob(comptime name: []const u8) type { .ctx = ctx, .callback = .create(callback, global), }); - job.any_task = JSC.AnyTask.New(@This(), &runFromJS).init(job); + job.any_task = jsc.AnyTask.New(@This(), &runFromJS).init(job); return job; } @@ -41,10 +41,10 @@ fn ExternCryptoJob(comptime name: []const u8) type { job.schedule(); } - pub fn runTask(task: *JSC.WorkPoolTask) void { + pub fn runTask(task: *jsc.WorkPoolTask) void { const job: *@This() = @fieldParentPtr("task", task); var vm = job.vm; - defer vm.enqueueTaskConcurrent(JSC.ConcurrentTask.create(job.any_task.task())); + defer vm.enqueueTaskConcurrent(jsc.ConcurrentTask.create(job.any_task.task())); job.ctx.runTask(vm.global); } @@ -75,7 +75,7 @@ fn ExternCryptoJob(comptime name: []const u8) type { pub fn schedule(this: *@This()) callconv(.c) void { this.poll.ref(this.vm); - JSC.WorkPool.schedule(&this.task); + jsc.WorkPool.schedule(&this.task); } comptime { @@ -115,12 +115,12 @@ comptime { fn CryptoJob(comptime Ctx: type) type { return struct { - vm: *JSC.VirtualMachine, - task: JSC.WorkPoolTask, - any_task: JSC.AnyTask, + vm: *jsc.VirtualMachine, + task: jsc.WorkPoolTask, + any_task: jsc.AnyTask, poll: Async.KeepAlive = .{}, - callback: JSC.Strong.Optional, + callback: jsc.Strong.Optional, ctx: Ctx, @@ -137,7 +137,7 @@ fn CryptoJob(comptime Ctx: type) type { }); errdefer bun.destroy(job); try job.ctx.init(global); - job.any_task = JSC.AnyTask.New(@This(), &runFromJS).init(job); + job.any_task = jsc.AnyTask.New(@This(), &runFromJS).init(job); return job; } @@ -146,10 +146,10 @@ fn CryptoJob(comptime Ctx: type) type { job.schedule(); } - pub fn runTask(task: *JSC.WorkPoolTask) void { + pub fn runTask(task: *jsc.WorkPoolTask) void { const job: *@This() = @fieldParentPtr("task", task); var vm = job.vm; - defer vm.enqueueTaskConcurrent(JSC.ConcurrentTask.create(job.any_task.task())); + defer vm.enqueueTaskConcurrent(jsc.ConcurrentTask.create(job.any_task.task())); job.ctx.runTask(job.ctx.result); } @@ -178,7 +178,7 @@ fn CryptoJob(comptime Ctx: type) type { pub fn schedule(this: *@This()) callconv(.c) void { this.poll.ref(this.vm); - JSC.WorkPool.schedule(&this.task); + jsc.WorkPool.schedule(&this.task); } }; } @@ -212,10 +212,10 @@ const random = struct { const Job = CryptoJob(JobCtx); - const max_possible_length = @min(JSC.ArrayBuffer.max_size, std.math.maxInt(i32)); + const max_possible_length = @min(jsc.ArrayBuffer.max_size, std.math.maxInt(i32)); const max_range = 0xffff_ffff_ffff; - fn randomInt(global: *JSC.JSGlobalObject, callFrame: *JSC.CallFrame) bun.JSError!JSC.JSValue { + fn randomInt(global: *jsc.JSGlobalObject, callFrame: *jsc.CallFrame) bun.JSError!jsc.JSValue { var min_value, var max_value, var callback = callFrame.argumentsAsArray(3); var min_specified = true; @@ -266,7 +266,7 @@ const random = struct { return JSValue.jsNumber(res); } - fn randomUUID(global: *JSGlobalObject, callFrame: *JSC.CallFrame) JSError!JSValue { + fn randomUUID(global: *JSGlobalObject, callFrame: *jsc.CallFrame) JSError!JSValue { const args = callFrame.arguments(); var disable_entropy_cache = false; @@ -319,7 +319,7 @@ const random = struct { return @intFromFloat(size); } - fn randomBytes(global: *JSGlobalObject, callFrame: *JSC.CallFrame) JSError!JSValue { + fn randomBytes(global: *JSGlobalObject, callFrame: *jsc.CallFrame) JSError!JSValue { const size_value, const callback = callFrame.argumentsAsArray(2); const size = try assertSize(global, size_value, 1, 0, max_possible_length + 1); @@ -328,7 +328,7 @@ const random = struct { _ = try validators.validateFunction(global, "callback", callback); } - const result, const bytes = try JSC.ArrayBuffer.alloc(global, .ArrayBuffer, size); + const result, const bytes = try jsc.ArrayBuffer.alloc(global, .ArrayBuffer, size); if (callback.isUndefined()) { // sync @@ -347,7 +347,7 @@ const random = struct { return .js_undefined; } - fn randomFillSync(global: *JSGlobalObject, callFrame: *JSC.CallFrame) JSError!JSValue { + fn randomFillSync(global: *JSGlobalObject, callFrame: *jsc.CallFrame) JSError!JSValue { const buf_value, const offset_value, const size_value = callFrame.argumentsAsArray(3); const buf = buf_value.asArrayBuffer(global) orelse { @@ -358,7 +358,7 @@ const random = struct { const offset = try assertOffset( global, - if (offset_value.isUndefined()) JSC.jsNumber(0) else offset_value, + if (offset_value.isUndefined()) jsc.jsNumber(0) else offset_value, element_size, buf.byte_len, ); @@ -377,7 +377,7 @@ const random = struct { return buf_value; } - fn randomFill(global: *JSGlobalObject, callFrame: *JSC.CallFrame) JSError!JSValue { + fn randomFill(global: *JSGlobalObject, callFrame: *jsc.CallFrame) JSError!JSValue { const buf_value, var offset_value, var size_value, var callback = callFrame.argumentsAsArray(4); @@ -423,17 +423,17 @@ const random = struct { } }; -fn pbkdf2(globalThis: *JSC.JSGlobalObject, callFrame: *JSC.CallFrame) bun.JSError!JSC.JSValue { +fn pbkdf2(globalThis: *jsc.JSGlobalObject, callFrame: *jsc.CallFrame) bun.JSError!jsc.JSValue { const data = try PBKDF2.fromJS(globalThis, callFrame, true); - const job = PBKDF2.Job.create(JSC.VirtualMachine.get(), globalThis, &data); + const job = PBKDF2.Job.create(jsc.VirtualMachine.get(), globalThis, &data); return job.promise.value(); } -fn pbkdf2Sync(globalThis: *JSC.JSGlobalObject, callFrame: *JSC.CallFrame) bun.JSError!JSC.JSValue { +fn pbkdf2Sync(globalThis: *jsc.JSGlobalObject, callFrame: *jsc.CallFrame) bun.JSError!jsc.JSValue { var data = try PBKDF2.fromJS(globalThis, callFrame, false); defer data.deinit(); - const out_arraybuffer = try JSC.JSValue.createBufferFromLength(globalThis, @intCast(data.length)); + const out_arraybuffer = try jsc.JSValue.createBufferFromLength(globalThis, @intCast(data.length)); const output = out_arraybuffer.asArrayBuffer(globalThis) orelse { data.deinit(); @@ -449,7 +449,7 @@ fn pbkdf2Sync(globalThis: *JSC.JSGlobalObject, callFrame: *JSC.CallFrame) bun.JS return out_arraybuffer; } -pub fn timingSafeEqual(global: *JSGlobalObject, callFrame: *JSC.CallFrame) JSError!JSValue { +pub fn timingSafeEqual(global: *JSGlobalObject, callFrame: *jsc.CallFrame) JSError!JSValue { const l_value, const r_value = callFrame.argumentsAsArray(2); const l_buf = l_value.asArrayBuffer(global) orelse { @@ -466,22 +466,22 @@ pub fn timingSafeEqual(global: *JSGlobalObject, callFrame: *JSC.CallFrame) JSErr return global.ERR(.CRYPTO_TIMING_SAFE_EQUAL_LENGTH, "Input buffers must have the same byte length", .{}).throw(); } - return JSC.jsBoolean(BoringSSL.CRYPTO_memcmp(l.ptr, r.ptr, l.len) == 0); + return jsc.jsBoolean(BoringSSL.CRYPTO_memcmp(l.ptr, r.ptr, l.len) == 0); } -pub fn secureHeapUsed(_: *JSGlobalObject, _: *JSC.CallFrame) JSError!JSValue { +pub fn secureHeapUsed(_: *JSGlobalObject, _: *jsc.CallFrame) JSError!JSValue { return .js_undefined; } -pub fn getFips(_: *JSGlobalObject, _: *JSC.CallFrame) JSError!JSValue { +pub fn getFips(_: *JSGlobalObject, _: *jsc.CallFrame) JSError!JSValue { return JSValue.jsNumber(0); } -pub fn setFips(_: *JSGlobalObject, _: *JSC.CallFrame) JSError!JSValue { +pub fn setFips(_: *JSGlobalObject, _: *jsc.CallFrame) JSError!JSValue { return .js_undefined; } -pub fn setEngine(global: *JSGlobalObject, _: *JSC.CallFrame) JSError!JSValue { +pub fn setEngine(global: *JSGlobalObject, _: *jsc.CallFrame) JSError!JSValue { return global.ERR(.CRYPTO_CUSTOM_ENGINE_NOT_SUPPORTED, "Custom engines not supported by BoringSSL", .{}).throw(); } @@ -491,7 +491,7 @@ fn forEachHash(_: *const BoringSSL.EVP_MD, maybe_from: ?[*:0]const u8, _: ?[*:0] hashes.put(bun.span(from), {}) catch bun.outOfMemory(); } -fn getHashes(global: *JSGlobalObject, _: *JSC.CallFrame) JSError!JSValue { +fn getHashes(global: *JSGlobalObject, _: *jsc.CallFrame) JSError!JSValue { var hashes: bun.CaseInsensitiveASCIIStringArrayHashMap(void) = .init(bun.default_allocator); defer hashes.deinit(); @@ -518,13 +518,13 @@ const Scrypt = struct { keylen: u32, // used in async mode - buf: JSC.Strong.Optional = .empty, + buf: jsc.Strong.Optional = .empty, result: []u8 = &.{}, err: ?u32 = null, const Job = CryptoJob(Scrypt); - pub fn fromJS(global: *JSGlobalObject, callFrame: *JSC.CallFrame, comptime is_async: bool) JSError!if (is_async) struct { @This(), JSValue } else @This() { + pub fn fromJS(global: *JSGlobalObject, callFrame: *jsc.CallFrame, comptime is_async: bool) JSError!if (is_async) struct { @This(), JSValue } else @This() { const password_value, const salt_value, const keylen_value, var maybe_options_value: ?JSValue, var callback = callFrame.argumentsAsArray(5); @@ -659,7 +659,7 @@ const Scrypt = struct { } fn init(this: *Scrypt, global: *JSGlobalObject) JSError!void { - const buf, const bytes = try JSC.ArrayBuffer.alloc(global, .ArrayBuffer, this.keylen); + const buf, const bytes = try jsc.ArrayBuffer.alloc(global, .ArrayBuffer, this.keylen); // to be filled in later this.result = bytes; @@ -725,44 +725,46 @@ const Scrypt = struct { } }; -fn scrypt(global: *JSGlobalObject, callFrame: *JSC.CallFrame) JSError!JSValue { +fn scrypt(global: *JSGlobalObject, callFrame: *jsc.CallFrame) JSError!JSValue { const ctx, const callback = try Scrypt.fromJS(global, callFrame, true); try Scrypt.Job.initAndSchedule(global, callback, &ctx); return .js_undefined; } -fn scryptSync(global: *JSGlobalObject, callFrame: *JSC.CallFrame) JSError!JSValue { +fn scryptSync(global: *JSGlobalObject, callFrame: *jsc.CallFrame) JSError!JSValue { var ctx = try Scrypt.fromJS(global, callFrame, false); - const buf, const bytes = try JSC.ArrayBuffer.alloc(global, .ArrayBuffer, ctx.keylen); + const buf, const bytes = try jsc.ArrayBuffer.alloc(global, .ArrayBuffer, ctx.keylen); ctx.runTask(bytes); return buf; } -pub fn createNodeCryptoBindingZig(global: *JSC.JSGlobalObject) JSC.JSValue { - const crypto = JSC.JSValue.createEmptyObject(global, 15); +pub fn createNodeCryptoBindingZig(global: *jsc.JSGlobalObject) jsc.JSValue { + const crypto = jsc.JSValue.createEmptyObject(global, 15); - crypto.put(global, String.init("pbkdf2"), JSC.JSFunction.create(global, "pbkdf2", pbkdf2, 5, .{})); - crypto.put(global, String.init("pbkdf2Sync"), JSC.JSFunction.create(global, "pbkdf2Sync", pbkdf2Sync, 5, .{})); - crypto.put(global, String.init("randomInt"), JSC.JSFunction.create(global, "randomInt", random.randomInt, 2, .{})); - crypto.put(global, String.init("randomFill"), JSC.JSFunction.create(global, "randomFill", random.randomFill, 4, .{})); - crypto.put(global, String.init("randomFillSync"), JSC.JSFunction.create(global, "randomFillSync", random.randomFillSync, 3, .{})); - crypto.put(global, String.init("randomUUID"), JSC.JSFunction.create(global, "randomUUID", random.randomUUID, 1, .{})); - crypto.put(global, String.init("randomBytes"), JSC.JSFunction.create(global, "randomBytes", random.randomBytes, 2, .{})); - crypto.put(global, String.init("timingSafeEqual"), JSC.JSFunction.create(global, "timingSafeEqual", timingSafeEqual, 2, .{})); + crypto.put(global, String.init("pbkdf2"), jsc.JSFunction.create(global, "pbkdf2", pbkdf2, 5, .{})); + crypto.put(global, String.init("pbkdf2Sync"), jsc.JSFunction.create(global, "pbkdf2Sync", pbkdf2Sync, 5, .{})); + crypto.put(global, String.init("randomInt"), jsc.JSFunction.create(global, "randomInt", random.randomInt, 2, .{})); + crypto.put(global, String.init("randomFill"), jsc.JSFunction.create(global, "randomFill", random.randomFill, 4, .{})); + crypto.put(global, String.init("randomFillSync"), jsc.JSFunction.create(global, "randomFillSync", random.randomFillSync, 3, .{})); + crypto.put(global, String.init("randomUUID"), jsc.JSFunction.create(global, "randomUUID", random.randomUUID, 1, .{})); + crypto.put(global, String.init("randomBytes"), jsc.JSFunction.create(global, "randomBytes", random.randomBytes, 2, .{})); + crypto.put(global, String.init("timingSafeEqual"), jsc.JSFunction.create(global, "timingSafeEqual", timingSafeEqual, 2, .{})); - crypto.put(global, String.init("secureHeapUsed"), JSC.JSFunction.create(global, "secureHeapUsed", secureHeapUsed, 0, .{})); - crypto.put(global, String.init("getFips"), JSC.JSFunction.create(global, "getFips", getFips, 0, .{})); - crypto.put(global, String.init("setFips"), JSC.JSFunction.create(global, "setFips", setFips, 1, .{})); - crypto.put(global, String.init("setEngine"), JSC.JSFunction.create(global, "setEngine", setEngine, 2, .{})); + crypto.put(global, String.init("secureHeapUsed"), jsc.JSFunction.create(global, "secureHeapUsed", secureHeapUsed, 0, .{})); + crypto.put(global, String.init("getFips"), jsc.JSFunction.create(global, "getFips", getFips, 0, .{})); + crypto.put(global, String.init("setFips"), jsc.JSFunction.create(global, "setFips", setFips, 1, .{})); + crypto.put(global, String.init("setEngine"), jsc.JSFunction.create(global, "setEngine", setEngine, 2, .{})); - crypto.put(global, String.init("getHashes"), JSC.JSFunction.create(global, "getHashes", getHashes, 0, .{})); + crypto.put(global, String.init("getHashes"), jsc.JSFunction.create(global, "getHashes", getHashes, 0, .{})); - crypto.put(global, String.init("scrypt"), JSC.JSFunction.create(global, "scrypt", scrypt, 5, .{})); - crypto.put(global, String.init("scryptSync"), JSC.JSFunction.create(global, "scryptSync", scryptSync, 4, .{})); + crypto.put(global, String.init("scrypt"), jsc.JSFunction.create(global, "scrypt", scrypt, 5, .{})); + crypto.put(global, String.init("scryptSync"), jsc.JSFunction.create(global, "scryptSync", scryptSync, 4, .{})); return crypto; } +const string = []const u8; + const std = @import("std"); const validators = @import("./util/validators.zig"); @@ -771,14 +773,13 @@ const Async = bun.Async; const JSError = bun.JSError; const String = bun.String; const UUID = bun.UUID; -const string = bun.string; const BoringSSL = bun.BoringSSL.c; -const JSC = bun.JSC; -const JSGlobalObject = JSC.JSGlobalObject; -const JSValue = JSC.JSValue; -const Node = JSC.Node; -const Crypto = JSC.API.Bun.Crypto; +const jsc = bun.jsc; +const JSGlobalObject = jsc.JSGlobalObject; +const JSValue = jsc.JSValue; +const Node = jsc.Node; +const Crypto = jsc.API.Bun.Crypto; const EVP = Crypto.EVP; const PBKDF2 = EVP.PBKDF2; diff --git a/src/bun.js/node/node_error_binding.zig b/src/bun.js/node/node_error_binding.zig index e0e57b08d5..b4b59089ed 100644 --- a/src/bun.js/node/node_error_binding.zig +++ b/src/bun.js/node/node_error_binding.zig @@ -1,24 +1,25 @@ pub const ERR_INVALID_HANDLE_TYPE = createSimpleError(createTypeError, .ERR_INVALID_HANDLE_TYPE, "This handle type cannot be sent"); pub const ERR_CHILD_CLOSED_BEFORE_REPLY = createSimpleError(createError, .ERR_CHILD_CLOSED_BEFORE_REPLY, "Child closed before reply received"); -fn createSimpleError(comptime createFn: anytype, comptime code: JSC.Node.ErrorCode, comptime message: string) JSC.JS2NativeFunctionType { +fn createSimpleError(comptime createFn: anytype, comptime code: jsc.Node.ErrorCode, comptime message: string) jsc.JS2NativeFunctionType { const R = struct { - pub fn cbb(global: *JSC.JSGlobalObject) bun.JSError!JSC.JSValue { + pub fn cbb(global: *jsc.JSGlobalObject) bun.JSError!jsc.JSValue { const S = struct { - fn cb(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { + fn cb(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { _ = callframe; return createFn(globalThis, code, message, .{}); } }; - return JSC.JSFunction.create(global, @tagName(code), S.cb, 0, .{}); + return jsc.JSFunction.create(global, @tagName(code), S.cb, 0, .{}); } }; return R.cbb; } -const bun = @import("bun"); -const JSC = bun.JSC; -const string = bun.string; +const string = []const u8; -const createError = JSC.JSGlobalObject.createErrorInstanceWithCode; -const createTypeError = JSC.JSGlobalObject.createTypeErrorInstanceWithCode; +const bun = @import("bun"); +const jsc = bun.jsc; + +const createError = jsc.JSGlobalObject.createErrorInstanceWithCode; +const createTypeError = jsc.JSGlobalObject.createTypeErrorInstanceWithCode; diff --git a/src/bun.js/node/node_fs.zig b/src/bun.js/node/node_fs.zig index a03a8aabc8..3bdbf8ff6a 100644 --- a/src/bun.js/node/node_fs.zig +++ b/src/bun.js/node/node_fs.zig @@ -77,16 +77,16 @@ pub const Async = struct { /// Used internally. Not from JavaScript. pub const AsyncMkdirp = struct { completion_ctx: *anyopaque, - completion: *const fn (*anyopaque, JSC.Maybe(void)) void, + completion: *const fn (*anyopaque, jsc.Maybe(void)) void, /// Memory is not owned by this struct path: []const u8, - task: JSC.WorkPoolTask = .{ .callback = &workPoolCallback }, + task: jsc.WorkPoolTask = .{ .callback = &workPoolCallback }, pub const new = bun.TrivialNew(@This()); - pub fn workPoolCallback(task: *JSC.WorkPoolTask) void { + pub fn workPoolCallback(task: *jsc.WorkPoolTask) void { var this: *AsyncMkdirp = @fieldParentPtr("task", task); var node_fs = NodeFS{}; @@ -101,13 +101,13 @@ pub const Async = struct { this.completion(this.completion_ctx, .{ .err = err.withPath(bun.default_allocator.dupe(u8, err.path) catch bun.outOfMemory()) }); }, .result => { - this.completion(this.completion_ctx, JSC.Maybe(void).success); + this.completion(this.completion_ctx, jsc.Maybe(void).success); }, } } pub fn schedule(this: *AsyncMkdirp) void { - JSC.WorkPool.schedule(&this.task); + jsc.WorkPool.schedule(&this.task); } }; @@ -129,25 +129,25 @@ pub const Async = struct { } return struct { - promise: JSC.JSPromise.Strong, + promise: jsc.JSPromise.Strong, args: ArgumentType, - globalObject: *JSC.JSGlobalObject, + globalObject: *jsc.JSGlobalObject, req: uv.fs_t = std.mem.zeroes(uv.fs_t), - result: JSC.Maybe(ReturnType), + result: jsc.Maybe(ReturnType), ref: bun.Async.KeepAlive = .{}, - tracker: JSC.Debugger.AsyncTaskTracker, + tracker: jsc.Debugger.AsyncTaskTracker, pub const Task = @This(); pub const heap_label = "Async" ++ bun.meta.typeBaseName(@typeName(ArgumentType)) ++ "UvTask"; - pub fn create(globalObject: *JSC.JSGlobalObject, this: *JSC.Node.fs.Binding, task_args: ArgumentType, vm: *JSC.VirtualMachine) JSC.JSValue { + pub fn create(globalObject: *jsc.JSGlobalObject, this: *jsc.Node.fs.Binding, task_args: ArgumentType, vm: *jsc.VirtualMachine) jsc.JSValue { var task = bun.new(Task, .{ - .promise = JSC.JSPromise.Strong.init(globalObject), + .promise = jsc.JSPromise.Strong.init(globalObject), .args = task_args, .result = undefined, .globalObject = globalObject, - .tracker = JSC.Debugger.AsyncTaskTracker.init(vm), + .tracker = jsc.Debugger.AsyncTaskTracker.init(vm), }); task.ref.ref(vm); task.args.toThreadSafe(); @@ -179,7 +179,7 @@ pub const Async = struct { if (fd == 1 or fd == 2) { log("uv close({}) SKIPPED", .{fd}); task.result = Maybe(Return.Close).success; - task.globalObject.bunVM().eventLoop().enqueueTask(JSC.Task.init(task)); + task.globalObject.bunVM().eventLoop().enqueueTask(jsc.Task.init(task)); return task.promise.value(); } @@ -233,7 +233,7 @@ pub const Async = struct { if (bufs.len == 0) { task.result = Maybe(Return.Writev).success; - task.globalObject.bunVM().eventLoop().enqueueTask(JSC.Task.init(task)); + task.globalObject.bunVM().eventLoop().enqueueTask(jsc.Task.init(task)); return task.promise.value(); } @@ -270,7 +270,7 @@ pub const Async = struct { std.mem.doNotOptimizeAway(&node_fs); } - this.globalObject.bunVM().eventLoop().enqueueTask(JSC.Task.init(this)); + this.globalObject.bunVM().eventLoop().enqueueTask(jsc.Task.init(this)); } fn uv_callbackreq(req: *uv.fs_t) callconv(.C) void { @@ -284,12 +284,12 @@ pub const Async = struct { std.mem.doNotOptimizeAway(&node_fs); } - this.globalObject.bunVM().eventLoop().enqueueTask(JSC.Task.init(this)); + this.globalObject.bunVM().eventLoop().enqueueTask(jsc.Task.init(this)); } pub fn runFromJSThread(this: *Task) void { const globalObject = this.globalObject; - const success = @as(JSC.Maybe(ReturnType).Tag, this.result) == .result; + const success = @as(jsc.Maybe(ReturnType).Tag, this.result) == .result; var promise_value = this.promise.value(); var promise = this.promise.get(); const result = switch (this.result) { @@ -336,13 +336,13 @@ pub const Async = struct { return struct { pub const Task = @This(); - promise: JSC.JSPromise.Strong, + promise: jsc.JSPromise.Strong, args: ArgumentType, - globalObject: *JSC.JSGlobalObject, - task: JSC.WorkPoolTask = .{ .callback = &workPoolCallback }, - result: JSC.Maybe(ReturnType), + globalObject: *jsc.JSGlobalObject, + task: jsc.WorkPoolTask = .{ .callback = &workPoolCallback }, + result: jsc.Maybe(ReturnType), ref: bun.Async.KeepAlive = .{}, - tracker: JSC.Debugger.AsyncTaskTracker, + tracker: jsc.Debugger.AsyncTaskTracker, /// NewAsyncFSTask supports cancelable operations via AbortSignal, /// so long as a "signal" field exists. The task wrapper will ensure @@ -353,26 +353,26 @@ pub const Async = struct { pub const heap_label = "Async" ++ bun.meta.typeBaseName(@typeName(ArgumentType)) ++ "Task"; pub fn create( - globalObject: *JSC.JSGlobalObject, + globalObject: *jsc.JSGlobalObject, _: *bun.api.node.fs.Binding, args: ArgumentType, - vm: *JSC.VirtualMachine, - ) JSC.JSValue { + vm: *jsc.VirtualMachine, + ) jsc.JSValue { var task = bun.new(Task, .{ - .promise = JSC.JSPromise.Strong.init(globalObject), + .promise = jsc.JSPromise.Strong.init(globalObject), .args = args, .result = undefined, .globalObject = globalObject, - .tracker = JSC.Debugger.AsyncTaskTracker.init(vm), + .tracker = jsc.Debugger.AsyncTaskTracker.init(vm), }); task.ref.ref(vm); task.args.toThreadSafe(); task.tracker.didSchedule(globalObject); - JSC.WorkPool.schedule(&task.task); + jsc.WorkPool.schedule(&task.task); return task.promise.value(); } - fn workPoolCallback(task: *JSC.WorkPoolTask) void { + fn workPoolCallback(task: *jsc.WorkPoolTask) void { var this: *Task = @alignCast(@fieldParentPtr("task", task)); var node_fs = NodeFS{}; @@ -383,12 +383,12 @@ pub const Async = struct { std.mem.doNotOptimizeAway(&node_fs); } - this.globalObject.bunVMConcurrently().eventLoop().enqueueTaskConcurrent(JSC.ConcurrentTask.createFrom(this)); + this.globalObject.bunVMConcurrently().eventLoop().enqueueTaskConcurrent(jsc.ConcurrentTask.createFrom(this)); } pub fn runFromJSThread(this: *Task) void { const globalObject = this.globalObject; - const success = @as(JSC.Maybe(ReturnType).Tag, this.result) == .result; + const success = @as(jsc.Maybe(ReturnType).Tag, this.result) == .result; var promise_value = this.promise.value(); var promise = this.promise.get(); const result = switch (this.result) { @@ -448,17 +448,17 @@ pub fn NewAsyncCpTask(comptime is_shell: bool) type { const ShellTask = bun.shell.Interpreter.Builtin.Cp.ShellCpTask; const ShellTaskT = if (is_shell) *ShellTask else u0; return struct { - promise: JSC.JSPromise.Strong = .{}, + promise: jsc.JSPromise.Strong = .{}, args: Arguments.Cp, - evtloop: JSC.EventLoopHandle, - task: JSC.WorkPoolTask = .{ .callback = &workPoolCallback }, - result: JSC.Maybe(Return.Cp), + evtloop: jsc.EventLoopHandle, + task: jsc.WorkPoolTask = .{ .callback = &workPoolCallback }, + result: jsc.Maybe(Return.Cp), /// If this task is called by the shell then we shouldn't call this as /// it is not threadsafe and is unnecessary as the process will be kept /// alive by the shell instance ref: if (!is_shell) bun.Async.KeepAlive else struct {} = .{}, arena: bun.ArenaAllocator, - tracker: JSC.Debugger.AsyncTaskTracker, + tracker: jsc.Debugger.AsyncTaskTracker, has_result: std.atomic.Value(bool), /// On each creation of a `AsyncCpSingleFileTask`, this is incremented. /// When each task is finished, decrement. @@ -475,7 +475,7 @@ pub fn NewAsyncCpTask(comptime is_shell: bool) type { cp_task: *ThisAsyncCpTask, src: bun.OSPathSliceZ, dest: bun.OSPathSliceZ, - task: JSC.WorkPoolTask = .{ .callback = &SingleTask.workPoolCallback }, + task: jsc.WorkPoolTask = .{ .callback = &SingleTask.workPoolCallback }, const ThisSingleTask = @This(); @@ -490,10 +490,10 @@ pub fn NewAsyncCpTask(comptime is_shell: bool) type { .dest = dest, }); - JSC.WorkPool.schedule(&task.task); + jsc.WorkPool.schedule(&task.task); } - fn workPoolCallback(task: *JSC.WorkPoolTask) void { + fn workPoolCallback(task: *jsc.WorkPoolTask) void { var this: *ThisSingleTask = @fieldParentPtr("task", task); // TODO: error strings on node_fs will die @@ -553,20 +553,20 @@ pub fn NewAsyncCpTask(comptime is_shell: bool) type { } pub fn create( - globalObject: *JSC.JSGlobalObject, - _: *JSC.Node.fs.Binding, + globalObject: *jsc.JSGlobalObject, + _: *jsc.Node.fs.Binding, cp_args: Arguments.Cp, - vm: *JSC.VirtualMachine, + vm: *jsc.VirtualMachine, arena: bun.ArenaAllocator, - ) JSC.JSValue { + ) jsc.JSValue { const task = createWithShellTask(globalObject, cp_args, vm, arena, 0, true); return task.promise.value(); } pub fn createWithShellTask( - globalObject: *JSC.JSGlobalObject, + globalObject: *jsc.JSGlobalObject, cp_args: Arguments.Cp, - vm: *JSC.VirtualMachine, + vm: *jsc.VirtualMachine, arena: bun.ArenaAllocator, shelltask: ShellTaskT, comptime enable_promise: bool, @@ -574,12 +574,12 @@ pub fn NewAsyncCpTask(comptime is_shell: bool) type { var task = bun.new( ThisAsyncCpTask, ThisAsyncCpTask{ - .promise = if (comptime enable_promise) JSC.JSPromise.Strong.init(globalObject) else .{}, + .promise = if (comptime enable_promise) jsc.JSPromise.Strong.init(globalObject) else .{}, .args = cp_args, .has_result = .{ .raw = false }, .result = undefined, .evtloop = .{ .js = vm.event_loop }, - .tracker = JSC.Debugger.AsyncTaskTracker.init(vm), + .tracker = jsc.Debugger.AsyncTaskTracker.init(vm), .arena = arena, .subtask_count = .{ .raw = 1 }, .shelltask = shelltask, @@ -590,14 +590,14 @@ pub fn NewAsyncCpTask(comptime is_shell: bool) type { task.args.dest.toThreadSafe(); task.tracker.didSchedule(globalObject); - JSC.WorkPool.schedule(&task.task); + jsc.WorkPool.schedule(&task.task); return task; } pub fn createMini( cp_args: Arguments.Cp, - mini: *JSC.MiniEventLoop, + mini: *jsc.MiniEventLoop, arena: bun.ArenaAllocator, shelltask: *ShellTask, ) *ThisAsyncCpTask { @@ -608,7 +608,7 @@ pub fn NewAsyncCpTask(comptime is_shell: bool) type { .has_result = .{ .raw = false }, .result = undefined, .evtloop = .{ .mini = mini }, - .tracker = JSC.Debugger.AsyncTaskTracker{ .id = 0 }, + .tracker = jsc.Debugger.AsyncTaskTracker{ .id = 0 }, .arena = arena, .subtask_count = .{ .raw = 1 }, .shelltask = shelltask, @@ -618,12 +618,12 @@ pub fn NewAsyncCpTask(comptime is_shell: bool) type { task.args.src.toThreadSafe(); task.args.dest.toThreadSafe(); - JSC.WorkPool.schedule(&task.task); + jsc.WorkPool.schedule(&task.task); return task; } - fn workPoolCallback(task: *JSC.WorkPoolTask) void { + fn workPoolCallback(task: *jsc.WorkPoolTask) void { const this: *ThisAsyncCpTask = @alignCast(@fieldParentPtr("task", task)); var node_fs = NodeFS{}; @@ -643,9 +643,9 @@ pub fn NewAsyncCpTask(comptime is_shell: bool) type { } if (this.evtloop == .js) { - this.evtloop.enqueueTaskConcurrent(.{ .js = JSC.ConcurrentTask.fromCallback(this, runFromJSThread) }); + this.evtloop.enqueueTaskConcurrent(.{ .js = jsc.ConcurrentTask.fromCallback(this, runFromJSThread) }); } else { - this.evtloop.enqueueTaskConcurrent(.{ .mini = JSC.AnyTaskWithExtraContext.fromCallbackAutoDeinit(this, "runFromJSThreadMini") }); + this.evtloop.enqueueTaskConcurrent(.{ .mini = jsc.AnyTaskWithExtraContext.fromCallbackAutoDeinit(this, "runFromJSThreadMini") }); } } @@ -662,7 +662,7 @@ pub fn NewAsyncCpTask(comptime is_shell: bool) type { const globalObject = this.evtloop.globalObject() orelse { @panic("No global object, this indicates a bug in Bun. Please file a GitHub issue."); }; - const success = @as(JSC.Maybe(Return.Cp).Tag, this.result) == .result; + const success = @as(jsc.Maybe(Return.Cp).Tag, this.result) == .result; var promise_value = this.promise.value(); var promise = this.promise.get(); const result = switch (this.result) { @@ -924,12 +924,12 @@ pub fn NewAsyncCpTask(comptime is_shell: bool) type { } pub const AsyncReaddirRecursiveTask = struct { - promise: JSC.JSPromise.Strong, + promise: jsc.JSPromise.Strong, args: Arguments.Readdir, - globalObject: *JSC.JSGlobalObject, - task: JSC.WorkPoolTask = .{ .callback = &workPoolCallback }, + globalObject: *jsc.JSGlobalObject, + task: jsc.WorkPoolTask = .{ .callback = &workPoolCallback }, ref: bun.Async.KeepAlive = .{}, - tracker: JSC.Debugger.AsyncTaskTracker, + tracker: jsc.Debugger.AsyncTaskTracker, // It's not 100% clear this one is necessary has_result: std.atomic.Value(bool), @@ -960,7 +960,7 @@ pub const AsyncReaddirRecursiveTask = struct { pub const ResultListEntry = struct { pub const Value = union(Return.Readdir.Tag) { - with_file_types: std.ArrayList(bun.JSC.Node.Dirent), + with_file_types: std.ArrayList(bun.jsc.Node.Dirent), buffers: std.ArrayList(Buffer), files: std.ArrayList(bun.String), @@ -997,11 +997,11 @@ pub const AsyncReaddirRecursiveTask = struct { pub const Subtask = struct { readdir_task: *AsyncReaddirRecursiveTask, basename: bun.PathString = bun.PathString.empty, - task: JSC.WorkPoolTask = .{ .callback = call }, + task: jsc.WorkPoolTask = .{ .callback = call }, pub const new = bun.TrivialNew(@This()); - pub fn call(task: *JSC.WorkPoolTask) void { + pub fn call(task: *jsc.WorkPoolTask) void { var this: *Subtask = @alignCast(@fieldParentPtr("task", task)); defer { bun.default_allocator.free(this.basename.sliceAssumeZ()); @@ -1023,20 +1023,20 @@ pub const AsyncReaddirRecursiveTask = struct { }, ); bun.assert(readdir_task.subtask_count.fetchAdd(1, .monotonic) > 0); - JSC.WorkPool.schedule(&task.task); + jsc.WorkPool.schedule(&task.task); } pub fn create( - globalObject: *JSC.JSGlobalObject, + globalObject: *jsc.JSGlobalObject, args: Arguments.Readdir, - vm: *JSC.VirtualMachine, - ) JSC.JSValue { + vm: *jsc.VirtualMachine, + ) jsc.JSValue { var task = AsyncReaddirRecursiveTask.new(.{ - .promise = JSC.JSPromise.Strong.init(globalObject), + .promise = jsc.JSPromise.Strong.init(globalObject), .args = args, .has_result = .{ .raw = false }, .globalObject = globalObject, - .tracker = JSC.Debugger.AsyncTaskTracker.init(vm), + .tracker = jsc.Debugger.AsyncTaskTracker.init(vm), .subtask_count = .{ .raw = 1 }, .root_path = PathString.init(bun.default_allocator.dupeZ(u8, args.path.slice()) catch bun.outOfMemory()), .result_list = switch (args.tag()) { @@ -1049,7 +1049,7 @@ pub const AsyncReaddirRecursiveTask = struct { task.args.toThreadSafe(); task.tracker.didSchedule(globalObject); - JSC.WorkPool.schedule(&task.task); + jsc.WorkPool.schedule(&task.task); return task.promise.value(); } @@ -1059,7 +1059,7 @@ pub const AsyncReaddirRecursiveTask = struct { inline else => |tag| { const ResultType = comptime switch (tag) { .files => bun.String, - .with_file_types => bun.JSC.Node.Dirent, + .with_file_types => bun.jsc.Node.Dirent, .buffers => Buffer, }; var stack = std.heap.stackFallback(8192, bun.default_allocator); @@ -1082,7 +1082,7 @@ pub const AsyncReaddirRecursiveTask = struct { for (entries.items) |*item| { switch (ResultType) { bun.String => item.deref(), - bun.JSC.Node.Dirent => item.deref(), + bun.jsc.Node.Dirent => item.deref(), Buffer => bun.default_allocator.free(item.buffer.byteSlice()), else => @compileError("unreachable"), } @@ -1109,7 +1109,7 @@ pub const AsyncReaddirRecursiveTask = struct { } } - fn workPoolCallback(task: *JSC.WorkPoolTask) void { + fn workPoolCallback(task: *jsc.WorkPoolTask) void { var this: *AsyncReaddirRecursiveTask = @alignCast(@fieldParentPtr("task", task)); var buf: bun.PathBuffer = undefined; this.performWork(this.root_path.sliceAssumeZ(), &buf, true); @@ -1119,7 +1119,7 @@ pub const AsyncReaddirRecursiveTask = struct { if (result.items.len > 0) { const Field = switch (ResultType) { bun.String => .files, - bun.JSC.Node.Dirent => .with_file_types, + bun.jsc.Node.Dirent => .with_file_types, Buffer => .buffers, else => @compileError("unreachable"), }; @@ -1189,7 +1189,7 @@ pub const AsyncReaddirRecursiveTask = struct { } } - this.globalObject.bunVMConcurrently().enqueueTaskConcurrent(JSC.ConcurrentTask.create(JSC.Task.init(this))); + this.globalObject.bunVMConcurrently().enqueueTaskConcurrent(jsc.ConcurrentTask.create(jsc.Task.init(this))); } fn clearResultList(this: *AsyncReaddirRecursiveTask) void { @@ -1280,7 +1280,7 @@ pub const Arguments = struct { this.new_path.toThreadSafe(); } - pub fn fromJS(ctx: *JSC.JSGlobalObject, arguments: *ArgumentsSlice) bun.JSError!Rename { + pub fn fromJS(ctx: *jsc.JSGlobalObject, arguments: *ArgumentsSlice) bun.JSError!Rename { const old_path = try PathLike.fromJS(ctx, arguments) orelse { return ctx.throwInvalidArgumentTypeValue("oldPath", "string or an instance of Buffer or URL", arguments.next() orelse .js_undefined); }; @@ -1311,13 +1311,13 @@ pub const Arguments = struct { this.path.toThreadSafe(); } - pub fn fromJS(ctx: *JSC.JSGlobalObject, arguments: *ArgumentsSlice) bun.JSError!Truncate { + pub fn fromJS(ctx: *jsc.JSGlobalObject, arguments: *ArgumentsSlice) bun.JSError!Truncate { const path = try PathOrFileDescriptor.fromJS(ctx, arguments, bun.default_allocator) orelse { return ctx.throwInvalidArguments("path must be a string or TypedArray", .{}); }; const len: u63 = brk: { const len_value = arguments.next() orelse break :brk 0; - break :brk @max(0, try JSC.Node.validators.validateInteger(ctx, len_value, "len", null, null)); + break :brk @max(0, try jsc.Node.validators.validateInteger(ctx, len_value, "len", null, null)); }; return .{ .path = path, .len = len }; } @@ -1325,7 +1325,7 @@ pub const Arguments = struct { pub const Writev = struct { fd: FileDescriptor, - buffers: JSC.Node.VectorArrayBuffer, + buffers: jsc.Node.VectorArrayBuffer, position: ?u52 = 0, pub fn deinit(_: *const @This()) void {} @@ -1345,13 +1345,13 @@ pub const Arguments = struct { this.buffers.buffers.allocator = bun.default_allocator; } - pub fn fromJS(ctx: *JSC.JSGlobalObject, arguments: *ArgumentsSlice) bun.JSError!Writev { - const fd_value: JSC.JSValue = arguments.nextEat() orelse .js_undefined; + pub fn fromJS(ctx: *jsc.JSGlobalObject, arguments: *ArgumentsSlice) bun.JSError!Writev { + const fd_value: jsc.JSValue = arguments.nextEat() orelse .js_undefined; const fd = try bun.FD.fromJSValidated(fd_value, ctx) orelse { return throwInvalidFdError(ctx, fd_value); }; - const buffers = try JSC.Node.VectorArrayBuffer.fromJS( + const buffers = try jsc.Node.VectorArrayBuffer.fromJS( ctx, arguments.protectEatNext() orelse { return ctx.throwInvalidArguments("Expected an ArrayBufferView[]", .{}); @@ -1377,7 +1377,7 @@ pub const Arguments = struct { pub const Readv = struct { fd: FileDescriptor, - buffers: JSC.Node.VectorArrayBuffer, + buffers: jsc.Node.VectorArrayBuffer, position: ?u52 = 0, pub fn deinit(this: *const @This()) void { @@ -1399,13 +1399,13 @@ pub const Arguments = struct { this.buffers.buffers.allocator = bun.default_allocator; } - pub fn fromJS(ctx: *JSC.JSGlobalObject, arguments: *ArgumentsSlice) bun.JSError!Readv { - const fd_value: JSC.JSValue = arguments.nextEat() orelse .js_undefined; + pub fn fromJS(ctx: *jsc.JSGlobalObject, arguments: *ArgumentsSlice) bun.JSError!Readv { + const fd_value: jsc.JSValue = arguments.nextEat() orelse .js_undefined; const fd = try bun.FD.fromJSValidated(fd_value, ctx) orelse { return throwInvalidFdError(ctx, fd_value); }; - const buffers = try JSC.Node.VectorArrayBuffer.fromJS( + const buffers = try jsc.Node.VectorArrayBuffer.fromJS( ctx, arguments.protectEatNext() orelse { return ctx.throwInvalidArguments("Expected an ArrayBufferView[]", .{}); @@ -1431,7 +1431,7 @@ pub const Arguments = struct { pub const FTruncate = struct { fd: FileDescriptor, - len: ?JSC.WebCore.Blob.SizeType = null, + len: ?jsc.WebCore.Blob.SizeType = null, pub fn deinit(this: @This()) void { _ = this; @@ -1445,18 +1445,18 @@ pub const Arguments = struct { _ = this; } - pub fn fromJS(ctx: *JSC.JSGlobalObject, arguments: *ArgumentsSlice) bun.JSError!FTruncate { - const fd_value: JSC.JSValue = arguments.nextEat() orelse .js_undefined; + pub fn fromJS(ctx: *jsc.JSGlobalObject, arguments: *ArgumentsSlice) bun.JSError!FTruncate { + const fd_value: jsc.JSValue = arguments.nextEat() orelse .js_undefined; const fd = try bun.FD.fromJSValidated(fd_value, ctx) orelse { return throwInvalidFdError(ctx, fd_value); }; - const len: JSC.WebCore.Blob.SizeType = @intCast(@max(try JSC.Node.validators.validateInteger( + const len: jsc.WebCore.Blob.SizeType = @intCast(@max(try jsc.Node.validators.validateInteger( ctx, - arguments.next() orelse JSC.JSValue.jsNumber(0), + arguments.next() orelse jsc.JSValue.jsNumber(0), "len", std.math.minInt(i52), - std.math.maxInt(JSC.WebCore.Blob.SizeType), + std.math.maxInt(jsc.WebCore.Blob.SizeType), ), 0)); return FTruncate{ .fd = fd, .len = len }; @@ -1480,7 +1480,7 @@ pub const Arguments = struct { this.path.toThreadSafe(); } - pub fn fromJS(ctx: *JSC.JSGlobalObject, arguments: *ArgumentsSlice) bun.JSError!Chown { + pub fn fromJS(ctx: *jsc.JSGlobalObject, arguments: *ArgumentsSlice) bun.JSError!Chown { const path = try PathLike.fromJS(ctx, arguments) orelse { return ctx.throwInvalidArguments("path must be a string or TypedArray", .{}); }; @@ -1492,7 +1492,7 @@ pub const Arguments = struct { }; arguments.eat(); - break :brk wrapTo(uid_t, try JSC.Node.validators.validateInteger(ctx, uid_value, "uid", -1, std.math.maxInt(u32))); + break :brk wrapTo(uid_t, try jsc.Node.validators.validateInteger(ctx, uid_value, "uid", -1, std.math.maxInt(u32))); }; const gid: gid_t = brk: { @@ -1500,7 +1500,7 @@ pub const Arguments = struct { return ctx.throwInvalidArguments("gid is required", .{}); }; arguments.eat(); - break :brk wrapTo(gid_t, try JSC.Node.validators.validateInteger(ctx, gid_value, "gid", -1, std.math.maxInt(u32))); + break :brk wrapTo(gid_t, try jsc.Node.validators.validateInteger(ctx, gid_value, "gid", -1, std.math.maxInt(u32))); }; return Chown{ .path = path, .uid = uid, .gid = gid }; @@ -1516,8 +1516,8 @@ pub const Arguments = struct { pub fn toThreadSafe(_: *const @This()) void {} - pub fn fromJS(ctx: *JSC.JSGlobalObject, arguments: *ArgumentsSlice) bun.JSError!Fchown { - const fd_value: JSC.JSValue = arguments.nextEat() orelse .js_undefined; + pub fn fromJS(ctx: *jsc.JSGlobalObject, arguments: *ArgumentsSlice) bun.JSError!Fchown { + const fd_value: jsc.JSValue = arguments.nextEat() orelse .js_undefined; const fd = try bun.FD.fromJSValidated(fd_value, ctx) orelse { return throwInvalidFdError(ctx, fd_value); }; @@ -1528,7 +1528,7 @@ pub const Arguments = struct { }; arguments.eat(); - break :brk wrapTo(uid_t, try JSC.Node.validators.validateInteger(ctx, uid_value, "uid", -1, std.math.maxInt(u32))); + break :brk wrapTo(uid_t, try jsc.Node.validators.validateInteger(ctx, uid_value, "uid", -1, std.math.maxInt(u32))); }; const gid: gid_t = brk: { @@ -1536,7 +1536,7 @@ pub const Arguments = struct { return ctx.throwInvalidArguments("gid is required", .{}); }; arguments.eat(); - break :brk wrapTo(gid_t, try JSC.Node.validators.validateInteger(ctx, gid_value, "gid", -1, std.math.maxInt(u32))); + break :brk wrapTo(gid_t, try jsc.Node.validators.validateInteger(ctx, gid_value, "gid", -1, std.math.maxInt(u32))); }; return Fchown{ .fd = fd, .uid = uid, .gid = gid }; @@ -1567,13 +1567,13 @@ pub const Arguments = struct { this.path.toThreadSafe(); } - pub fn fromJS(ctx: *JSC.JSGlobalObject, arguments: *ArgumentsSlice) bun.JSError!Lutimes { + pub fn fromJS(ctx: *jsc.JSGlobalObject, arguments: *ArgumentsSlice) bun.JSError!Lutimes { const path = try PathLike.fromJS(ctx, arguments) orelse { return ctx.throwInvalidArguments("path must be a string or TypedArray", .{}); }; errdefer path.deinit(); - const atime = try JSC.Node.timeLikeFromJS(ctx, arguments.next() orelse { + const atime = try jsc.Node.timeLikeFromJS(ctx, arguments.next() orelse { return ctx.throwInvalidArguments("atime is required", .{}); }) orelse { return ctx.throwInvalidArguments("atime must be a number or a Date", .{}); @@ -1581,7 +1581,7 @@ pub const Arguments = struct { arguments.eat(); - const mtime = try JSC.Node.timeLikeFromJS(ctx, arguments.next() orelse { + const mtime = try jsc.Node.timeLikeFromJS(ctx, arguments.next() orelse { return ctx.throwInvalidArguments("mtime is required", .{}); }) orelse { return ctx.throwInvalidArguments("mtime must be a number or a Date", .{}); @@ -1609,15 +1609,15 @@ pub const Arguments = struct { this.path.deinitAndUnprotect(); } - pub fn fromJS(ctx: *JSC.JSGlobalObject, arguments: *ArgumentsSlice) bun.JSError!Chmod { + pub fn fromJS(ctx: *jsc.JSGlobalObject, arguments: *ArgumentsSlice) bun.JSError!Chmod { const path = try PathLike.fromJS(ctx, arguments) orelse { return ctx.throwInvalidArguments("path must be a string or TypedArray", .{}); }; errdefer path.deinit(); - const mode_arg: JSC.JSValue = arguments.next() orelse .js_undefined; - const mode: Mode = try JSC.Node.modeFromJS(ctx, mode_arg) orelse { - return JSC.Node.validators.throwErrInvalidArgType(ctx, "mode", .{}, "number", mode_arg); + const mode_arg: jsc.JSValue = arguments.next() orelse .js_undefined; + const mode: Mode = try jsc.Node.modeFromJS(ctx, mode_arg) orelse { + return jsc.Node.validators.throwErrInvalidArgType(ctx, "mode", .{}, "number", mode_arg); }; arguments.eat(); @@ -1634,15 +1634,15 @@ pub const Arguments = struct { pub fn toThreadSafe(_: *const @This()) void {} - pub fn fromJS(ctx: *JSC.JSGlobalObject, arguments: *ArgumentsSlice) bun.JSError!FChmod { - const fd_value: JSC.JSValue = arguments.nextEat() orelse .js_undefined; + pub fn fromJS(ctx: *jsc.JSGlobalObject, arguments: *ArgumentsSlice) bun.JSError!FChmod { + const fd_value: jsc.JSValue = arguments.nextEat() orelse .js_undefined; const fd = try bun.FD.fromJSValidated(fd_value, ctx) orelse { return throwInvalidFdError(ctx, fd_value); }; - const mode_arg: JSC.JSValue = arguments.next() orelse .js_undefined; - const mode: Mode = try JSC.Node.modeFromJS(ctx, mode_arg) orelse { - return JSC.Node.validators.throwErrInvalidArgType(ctx, "mode", .{}, "number", mode_arg); + const mode_arg: jsc.JSValue = arguments.next() orelse .js_undefined; + const mode: Mode = try jsc.Node.modeFromJS(ctx, mode_arg) orelse { + return jsc.Node.validators.throwErrInvalidArgType(ctx, "mode", .{}, "number", mode_arg); }; arguments.eat(); @@ -1669,7 +1669,7 @@ pub const Arguments = struct { this.path.toThreadSafe(); } - pub fn fromJS(ctx: *JSC.JSGlobalObject, arguments: *ArgumentsSlice) bun.JSError!Arguments.StatFS { + pub fn fromJS(ctx: *jsc.JSGlobalObject, arguments: *ArgumentsSlice) bun.JSError!Arguments.StatFS { const path = try PathLike.fromJS(ctx, arguments) orelse { return ctx.throwInvalidArguments("path must be a string or TypedArray", .{}); }; @@ -1710,7 +1710,7 @@ pub const Arguments = struct { this.path.toThreadSafe(); } - pub fn fromJS(ctx: *JSC.JSGlobalObject, arguments: *ArgumentsSlice) bun.JSError!Stat { + pub fn fromJS(ctx: *jsc.JSGlobalObject, arguments: *ArgumentsSlice) bun.JSError!Stat { const path = try PathLike.fromJS(ctx, arguments) orelse { return ctx.throwInvalidArguments("path must be a string or TypedArray", .{}); }; @@ -1748,8 +1748,8 @@ pub const Arguments = struct { pub fn toThreadSafe(_: *@This()) void {} - pub fn fromJS(ctx: *JSC.JSGlobalObject, arguments: *ArgumentsSlice) bun.JSError!Fstat { - const fd_value: JSC.JSValue = arguments.nextEat() orelse .js_undefined; + pub fn fromJS(ctx: *jsc.JSGlobalObject, arguments: *ArgumentsSlice) bun.JSError!Fstat { + const fd_value: jsc.JSValue = arguments.nextEat() orelse .js_undefined; const fd = try bun.FD.fromJSValidated(fd_value, ctx) orelse { return throwInvalidFdError(ctx, fd_value); }; @@ -1793,7 +1793,7 @@ pub const Arguments = struct { this.new_path.toThreadSafe(); } - pub fn fromJS(ctx: *JSC.JSGlobalObject, arguments: *ArgumentsSlice) bun.JSError!Link { + pub fn fromJS(ctx: *jsc.JSGlobalObject, arguments: *ArgumentsSlice) bun.JSError!Link { const old_path = try PathLike.fromJS(ctx, arguments) orelse { return ctx.throwInvalidArguments("oldPath must be a string or TypedArray", .{}); }; @@ -1836,7 +1836,7 @@ pub const Arguments = struct { this.new_path.toThreadSafe(); } - pub fn fromJS(ctx: *JSC.JSGlobalObject, arguments: *ArgumentsSlice) bun.JSError!Symlink { + pub fn fromJS(ctx: *jsc.JSGlobalObject, arguments: *ArgumentsSlice) bun.JSError!Symlink { const old_path = try PathLike.fromJS(ctx, arguments) orelse { return ctx.throwInvalidArguments("target must be a string or TypedArray", .{}); }; @@ -1897,7 +1897,7 @@ pub const Arguments = struct { this.path.toThreadSafe(); } - pub fn fromJS(ctx: *JSC.JSGlobalObject, arguments: *ArgumentsSlice) bun.JSError!Readlink { + pub fn fromJS(ctx: *jsc.JSGlobalObject, arguments: *ArgumentsSlice) bun.JSError!Readlink { const path = try PathLike.fromJS(ctx, arguments) orelse { return ctx.throwInvalidArguments("path must be a string or TypedArray", .{}); }; @@ -1908,7 +1908,7 @@ pub const Arguments = struct { arguments.eat(); switch (val.jsType()) { - JSC.JSValue.JSType.String, JSC.JSValue.JSType.StringObject, JSC.JSValue.JSType.DerivedStringObject => { + jsc.JSValue.JSType.String, jsc.JSValue.JSType.StringObject, jsc.JSValue.JSType.DerivedStringObject => { encoding = try Encoding.assert(val, ctx, encoding); }, else => { @@ -1939,7 +1939,7 @@ pub const Arguments = struct { this.path.toThreadSafe(); } - pub fn fromJS(ctx: *JSC.JSGlobalObject, arguments: *ArgumentsSlice) bun.JSError!Realpath { + pub fn fromJS(ctx: *jsc.JSGlobalObject, arguments: *ArgumentsSlice) bun.JSError!Realpath { const path = try PathLike.fromJS(ctx, arguments) orelse { return ctx.throwInvalidArguments("path must be a string or TypedArray", .{}); }; @@ -1950,9 +1950,9 @@ pub const Arguments = struct { arguments.eat(); switch (val.jsType()) { - JSC.JSValue.JSType.String, - JSC.JSValue.JSType.StringObject, - JSC.JSValue.JSType.DerivedStringObject, + jsc.JSValue.JSType.String, + jsc.JSValue.JSType.StringObject, + jsc.JSValue.JSType.DerivedStringObject, => { encoding = try Encoding.assert(val, ctx, encoding); }, @@ -1968,7 +1968,7 @@ pub const Arguments = struct { } }; - fn getEncoding(object: JSC.JSValue, globalObject: *JSC.JSGlobalObject, default: Encoding) bun.JSError!Encoding { + fn getEncoding(object: jsc.JSValue, globalObject: *jsc.JSGlobalObject, default: Encoding) bun.JSError!Encoding { if (try object.fastGet(globalObject, .encoding)) |value| { return Encoding.assert(value, globalObject, default); } @@ -1991,7 +1991,7 @@ pub const Arguments = struct { this.path.toThreadSafe(); } - pub fn fromJS(ctx: *JSC.JSGlobalObject, arguments: *ArgumentsSlice) bun.JSError!Unlink { + pub fn fromJS(ctx: *jsc.JSGlobalObject, arguments: *ArgumentsSlice) bun.JSError!Unlink { const path = try PathLike.fromJS(ctx, arguments) orelse { return ctx.throwInvalidArguments("path must be a string or TypedArray", .{}); }; @@ -2026,7 +2026,7 @@ pub const Arguments = struct { this.path.deinit(); } - pub fn fromJS(ctx: *JSC.JSGlobalObject, arguments: *ArgumentsSlice) bun.JSError!RmDir { + pub fn fromJS(ctx: *jsc.JSGlobalObject, arguments: *ArgumentsSlice) bun.JSError!RmDir { const path = try PathLike.fromJS(ctx, arguments) orelse { return ctx.throwInvalidArguments("path must be a string or TypedArray", .{}); }; @@ -2057,11 +2057,11 @@ pub const Arguments = struct { } if (try val.get(ctx, "retryDelay")) |delay| { - retry_delay = @intCast(try JSC.Node.validators.validateInteger(ctx, delay, "options.retryDelay", 0, std.math.maxInt(c_uint))); + retry_delay = @intCast(try jsc.Node.validators.validateInteger(ctx, delay, "options.retryDelay", 0, std.math.maxInt(c_uint))); } if (try val.get(ctx, "maxRetries")) |retries| { - max_retries = @intCast(try JSC.Node.validators.validateInteger(ctx, retries, "options.maxRetries", 0, std.math.maxInt(u32))); + max_retries = @intCast(try jsc.Node.validators.validateInteger(ctx, retries, "options.maxRetries", 0, std.math.maxInt(u32))); } } else if (!val.isUndefined()) { return ctx.throwInvalidArguments("The \"options\" argument must be of type object.", .{}); @@ -2104,7 +2104,7 @@ pub const Arguments = struct { this.path.toThreadSafe(); } - pub fn fromJS(ctx: *JSC.JSGlobalObject, arguments: *ArgumentsSlice) bun.JSError!Mkdir { + pub fn fromJS(ctx: *jsc.JSGlobalObject, arguments: *ArgumentsSlice) bun.JSError!Mkdir { const path = try PathLike.fromJS(ctx, arguments) orelse { return ctx.throwInvalidArguments("path must be a string or TypedArray", .{}); }; @@ -2122,11 +2122,11 @@ pub const Arguments = struct { } if (try val.get(ctx, "mode")) |mode_| { - mode = try JSC.Node.modeFromJS(ctx, mode_) orelse mode; + mode = try jsc.Node.modeFromJS(ctx, mode_) orelse mode; } } if (val.isNumber() or val.isString()) { - mode = try JSC.Node.modeFromJS(ctx, val) orelse mode; + mode = try jsc.Node.modeFromJS(ctx, val) orelse mode; } } @@ -2139,7 +2139,7 @@ pub const Arguments = struct { }; const MkdirTemp = struct { - prefix: PathLike = .{ .buffer = .{ .buffer = JSC.ArrayBuffer.empty } }, + prefix: PathLike = .{ .buffer = .{ .buffer = jsc.ArrayBuffer.empty } }, encoding: Encoding = .utf8, pub fn deinit(this: MkdirTemp) void { @@ -2154,7 +2154,7 @@ pub const Arguments = struct { this.prefix.toThreadSafe(); } - pub fn fromJS(ctx: *JSC.JSGlobalObject, arguments: *ArgumentsSlice) bun.JSError!MkdirTemp { + pub fn fromJS(ctx: *jsc.JSGlobalObject, arguments: *ArgumentsSlice) bun.JSError!MkdirTemp { const prefix = try PathLike.fromJS(ctx, arguments) orelse { return ctx.throwInvalidArgumentTypeValue("prefix", "string, Buffer, or URL", arguments.next() orelse .js_undefined); }; @@ -2166,7 +2166,7 @@ pub const Arguments = struct { arguments.eat(); switch (val.jsType()) { - JSC.JSValue.JSType.String, JSC.JSValue.JSType.StringObject, JSC.JSValue.JSType.DerivedStringObject => { + jsc.JSValue.JSType.String, jsc.JSValue.JSType.StringObject, jsc.JSValue.JSType.DerivedStringObject => { encoding = try Encoding.assert(val, ctx, encoding); }, else => { @@ -2212,7 +2212,7 @@ pub const Arguments = struct { }; } - pub fn fromJS(ctx: *JSC.JSGlobalObject, arguments: *ArgumentsSlice) bun.JSError!Readdir { + pub fn fromJS(ctx: *jsc.JSGlobalObject, arguments: *ArgumentsSlice) bun.JSError!Readdir { const path = try PathLike.fromJS(ctx, arguments) orelse { return ctx.throwInvalidArguments("path must be a string or TypedArray", .{}); }; @@ -2263,8 +2263,8 @@ pub const Arguments = struct { pub fn deinit(_: Close) void {} pub fn toThreadSafe(_: Close) void {} - pub fn fromJS(ctx: *JSC.JSGlobalObject, arguments: *ArgumentsSlice) bun.JSError!Close { - const fd_value: JSC.JSValue = arguments.nextEat() orelse .js_undefined; + pub fn fromJS(ctx: *jsc.JSGlobalObject, arguments: *ArgumentsSlice) bun.JSError!Close { + const fd_value: jsc.JSValue = arguments.nextEat() orelse .js_undefined; const fd = try bun.FD.fromJSValidated(fd_value, ctx) orelse { return throwInvalidFdError(ctx, fd_value); }; @@ -2290,7 +2290,7 @@ pub const Arguments = struct { this.path.toThreadSafe(); } - pub fn fromJS(ctx: *JSC.JSGlobalObject, arguments: *ArgumentsSlice) bun.JSError!Open { + pub fn fromJS(ctx: *jsc.JSGlobalObject, arguments: *ArgumentsSlice) bun.JSError!Open { const path = try PathLike.fromJS(ctx, arguments) orelse { return ctx.throwInvalidArguments("path must be a string or TypedArray", .{}); }; @@ -2308,7 +2308,7 @@ pub const Arguments = struct { } if (try val.getTruthy(ctx, "mode")) |mode_| { - mode = try JSC.Node.modeFromJS(ctx, mode_) orelse mode; + mode = try jsc.Node.modeFromJS(ctx, mode_) orelse mode; } } else if (val != .zero) { if (!val.isUndefinedOrNull()) { @@ -2317,7 +2317,7 @@ pub const Arguments = struct { } if (arguments.nextEat()) |next| { - mode = try JSC.Node.modeFromJS(ctx, next) orelse mode; + mode = try jsc.Node.modeFromJS(ctx, next) orelse mode; } } } @@ -2350,20 +2350,20 @@ pub const Arguments = struct { _ = self; } - pub fn fromJS(ctx: *JSC.JSGlobalObject, arguments: *ArgumentsSlice) bun.JSError!Futimes { - const fd_value: JSC.JSValue = arguments.nextEat() orelse .js_undefined; + pub fn fromJS(ctx: *jsc.JSGlobalObject, arguments: *ArgumentsSlice) bun.JSError!Futimes { + const fd_value: jsc.JSValue = arguments.nextEat() orelse .js_undefined; const fd = try bun.FD.fromJSValidated(fd_value, ctx) orelse { return throwInvalidFdError(ctx, fd_value); }; - const atime = try JSC.Node.timeLikeFromJS(ctx, arguments.next() orelse { + const atime = try jsc.Node.timeLikeFromJS(ctx, arguments.next() orelse { return ctx.throwInvalidArguments("atime is required", .{}); }) orelse { return ctx.throwInvalidArguments("atime must be a number or a Date", .{}); }; arguments.eat(); - const mtime = try JSC.Node.timeLikeFromJS(ctx, arguments.next() orelse { + const mtime = try jsc.Node.timeLikeFromJS(ctx, arguments.next() orelse { return ctx.throwInvalidArguments("mtime is required", .{}); }) orelse { return ctx.throwInvalidArguments("mtime must be a number or a Date", .{}); @@ -2404,7 +2404,7 @@ pub const Arguments = struct { pub const Write = struct { fd: FileDescriptor, buffer: StringOrBuffer, - // buffer_val: JSC.JSValue = JSC.JSValue.zero, + // buffer_val: jsc.JSValue = jsc.JSValue.zero, offset: u64 = 0, length: u64 = std.math.maxInt(u64), position: ?ReadPosition = null, @@ -2422,8 +2422,8 @@ pub const Arguments = struct { self.buffer.toThreadSafe(); } - pub fn fromJS(ctx: *JSC.JSGlobalObject, arguments: *ArgumentsSlice) bun.JSError!Write { - const fd_value: JSC.JSValue = arguments.nextEat() orelse .js_undefined; + pub fn fromJS(ctx: *jsc.JSGlobalObject, arguments: *ArgumentsSlice) bun.JSError!Write { + const fd_value: jsc.JSValue = arguments.nextEat() orelse .js_undefined; const fd = try bun.FD.fromJSValidated(fd_value, ctx) orelse { return throwInvalidFdError(ctx, fd_value); }; @@ -2468,7 +2468,7 @@ pub const Arguments = struct { // fs.write(fd, buffer[, offset[, length[, position]]], callback) .buffer => { if (current.isUndefinedOrNull() or current.isFunction()) break :parse; - args.offset = @intCast(try JSC.Node.validators.validateInteger(ctx, current, "offset", 0, 9007199254740991)); + args.offset = @intCast(try jsc.Node.validators.validateInteger(ctx, current, "offset", 0, 9007199254740991)); arguments.eat(); current = arguments.next() orelse break :parse; @@ -2523,12 +2523,12 @@ pub const Arguments = struct { this.buffer.buffer.value.unprotect(); } - pub fn fromJS(ctx: *JSC.JSGlobalObject, arguments: *ArgumentsSlice) bun.JSError!Read { + pub fn fromJS(ctx: *jsc.JSGlobalObject, arguments: *ArgumentsSlice) bun.JSError!Read { // About half of the normalization has already been done. The second half is done in the native code. // fs_binding.read(fd, buffer, offset, length, position) // fd = getValidatedFd(fd); - const fd_value: JSC.JSValue = arguments.nextEat() orelse .js_undefined; + const fd_value: jsc.JSValue = arguments.nextEat() orelse .js_undefined; const fd = try bun.FD.fromJSValidated(fd_value, ctx) orelse { return throwInvalidFdError(ctx, fd_value); }; @@ -2537,10 +2537,10 @@ pub const Arguments = struct { const buffer_value = arguments.nextEat() orelse // theoretically impossible, argument has been passed already return ctx.throwInvalidArguments("buffer is required", .{}); - const buffer: JSC.MarkedArrayBuffer = Buffer.fromJS(ctx, buffer_value) orelse + const buffer: jsc.MarkedArrayBuffer = Buffer.fromJS(ctx, buffer_value) orelse return ctx.throwInvalidArgumentTypeValue("buffer", "TypedArray", buffer_value); - const offset_value: JSC.JSValue = arguments.nextEat() orelse .null; + const offset_value: jsc.JSValue = arguments.nextEat() orelse .null; // if (offset == null) { // offset = 0; // } else { @@ -2549,7 +2549,7 @@ pub const Arguments = struct { const offset: u64 = if (offset_value.isUndefinedOrNull()) 0 else - @intCast(try JSC.Node.validators.validateInteger(ctx, offset_value, "offset", 0, JSC.MAX_SAFE_INTEGER)); + @intCast(try jsc.Node.validators.validateInteger(ctx, offset_value, "offset", 0, jsc.MAX_SAFE_INTEGER)); // length |= 0; const length_float: f64 = if (arguments.nextEat()) |arg| @@ -2597,12 +2597,12 @@ pub const Arguments = struct { // } else { // validatePosition(position, 'position', length); // } - const position_value: JSC.JSValue = arguments.nextEat() orelse .null; + const position_value: jsc.JSValue = arguments.nextEat() orelse .null; const position_int: i64 = if (position_value.isUndefinedOrNull()) -1 else if (position_value.isNumber()) - try JSC.Node.validators.validateInteger(ctx, position_value, "position", -1, JSC.MAX_SAFE_INTEGER) - else if (JSC.JSBigInt.fromJS(position_value)) |position| pos: { + try jsc.Node.validators.validateInteger(ctx, position_value, "position", -1, jsc.MAX_SAFE_INTEGER) + else if (jsc.JSBigInt.fromJS(position_value)) |position| pos: { // const maxPosition = 2n ** 63n - 1n - BigInt(length) const max_position = std.math.maxInt(i64) - length_int; if (position.order(i64, -1) == .lt or position.order(i64, max_position) == .gt) { @@ -2643,8 +2643,8 @@ pub const Arguments = struct { path: PathOrFileDescriptor, encoding: Encoding = Encoding.utf8, - offset: JSC.WebCore.Blob.SizeType = 0, - max_size: ?JSC.WebCore.Blob.SizeType = null, + offset: jsc.WebCore.Blob.SizeType = 0, + max_size: ?jsc.WebCore.Blob.SizeType = null, limit_size_for_javascript: bool = false, flag: FileSystemFlags = FileSystemFlags.r, @@ -2671,7 +2671,7 @@ pub const Arguments = struct { self.path.toThreadSafe(); } - pub fn fromJS(ctx: *JSC.JSGlobalObject, arguments: *ArgumentsSlice) bun.JSError!ReadFile { + pub fn fromJS(ctx: *jsc.JSGlobalObject, arguments: *ArgumentsSlice) bun.JSError!ReadFile { const path = try PathOrFileDescriptor.fromJS(ctx, arguments, bun.default_allocator) orelse { return ctx.throwInvalidArguments("path must be a string or a file descriptor", .{}); }; @@ -2764,7 +2764,7 @@ pub const Arguments = struct { signal.unref(); } } - pub fn fromJS(ctx: *JSC.JSGlobalObject, arguments: *ArgumentsSlice) bun.JSError!WriteFile { + pub fn fromJS(ctx: *jsc.JSGlobalObject, arguments: *ArgumentsSlice) bun.JSError!WriteFile { const path = try PathOrFileDescriptor.fromJS(ctx, arguments, bun.default_allocator) orelse { return ctx.throwInvalidArguments("path must be a string or a file descriptor", .{}); }; @@ -2803,7 +2803,7 @@ pub const Arguments = struct { } if (try arg.getTruthy(ctx, "mode")) |mode_| { - mode = try JSC.Node.modeFromJS(ctx, mode_) orelse mode; + mode = try jsc.Node.modeFromJS(ctx, mode_) orelse mode; } if (try arg.getTruthy(ctx, "signal")) |value| { @@ -2815,7 +2815,7 @@ pub const Arguments = struct { } } - if (try arg.getOptional(ctx, "flush", JSC.JSValue)) |flush_| { + if (try arg.getOptional(ctx, "flush", jsc.JSValue)) |flush_| { if (flush_.isBoolean() or flush_.isUndefinedOrNull()) { flush = flush_ == .true; } else { @@ -2865,7 +2865,7 @@ pub const Arguments = struct { self.path.deinit(); } - pub fn fromJS(ctx: *JSC.JSGlobalObject, arguments: *ArgumentsSlice) bun.JSError!OpenDir { + pub fn fromJS(ctx: *jsc.JSGlobalObject, arguments: *ArgumentsSlice) bun.JSError!OpenDir { const path = try PathLike.fromJS(ctx, arguments) orelse { return ctx.throwInvalidArguments("path must be a string or TypedArray", .{}); }; @@ -2921,7 +2921,7 @@ pub const Arguments = struct { } } - pub fn fromJS(ctx: *JSC.JSGlobalObject, arguments: *ArgumentsSlice) bun.JSError!Exists { + pub fn fromJS(ctx: *jsc.JSGlobalObject, arguments: *ArgumentsSlice) bun.JSError!Exists { return Exists{ .path = try PathLike.fromJS(ctx, arguments), }; @@ -2944,7 +2944,7 @@ pub const Arguments = struct { this.path.deinitAndUnprotect(); } - pub fn fromJS(ctx: *JSC.JSGlobalObject, arguments: *ArgumentsSlice) bun.JSError!Access { + pub fn fromJS(ctx: *jsc.JSGlobalObject, arguments: *ArgumentsSlice) bun.JSError!Access { const path = try PathLike.fromJS(ctx, arguments) orelse { return ctx.throwInvalidArguments("path must be a string or TypedArray", .{}); }; @@ -2972,8 +2972,8 @@ pub const Arguments = struct { _ = self; } - pub fn fromJS(ctx: *JSC.JSGlobalObject, arguments: *ArgumentsSlice) bun.JSError!FdataSync { - const fd_value: JSC.JSValue = arguments.nextEat() orelse .js_undefined; + pub fn fromJS(ctx: *jsc.JSGlobalObject, arguments: *ArgumentsSlice) bun.JSError!FdataSync { + const fd_value: jsc.JSValue = arguments.nextEat() orelse .js_undefined; const fd = try bun.FD.fromJSValidated(fd_value, ctx) orelse { return throwInvalidFdError(ctx, fd_value); }; @@ -3002,7 +3002,7 @@ pub const Arguments = struct { this.dest.deinitAndUnprotect(); } - pub fn fromJS(ctx: *JSC.JSGlobalObject, arguments: *ArgumentsSlice) bun.JSError!CopyFile { + pub fn fromJS(ctx: *jsc.JSGlobalObject, arguments: *ArgumentsSlice) bun.JSError!CopyFile { const src = try PathLike.fromJS(ctx, arguments) orelse { return ctx.throwInvalidArguments("src must be a string or TypedArray", .{}); }; @@ -3047,7 +3047,7 @@ pub const Arguments = struct { } } - pub fn fromJS(ctx: *JSC.JSGlobalObject, arguments: *ArgumentsSlice) bun.JSError!Cp { + pub fn fromJS(ctx: *jsc.JSGlobalObject, arguments: *ArgumentsSlice) bun.JSError!Cp { const src = try PathLike.fromJS(ctx, arguments) orelse { return ctx.throwInvalidArguments("src must be a string or TypedArray", .{}); }; @@ -3122,8 +3122,8 @@ pub const Arguments = struct { pub fn deinit(_: Fsync) void {} pub fn toThreadSafe(_: *const @This()) void {} - pub fn fromJS(ctx: *JSC.JSGlobalObject, arguments: *ArgumentsSlice) bun.JSError!Fsync { - const fd_value: JSC.JSValue = arguments.nextEat() orelse .js_undefined; + pub fn fromJS(ctx: *jsc.JSGlobalObject, arguments: *ArgumentsSlice) bun.JSError!Fsync { + const fd_value: jsc.JSValue = arguments.nextEat() orelse .js_undefined; const fd = try bun.FD.fromJSValidated(fd_value, ctx) orelse { return throwInvalidFdError(ctx, fd_value); }; @@ -3134,17 +3134,17 @@ pub const Arguments = struct { }; pub const StatOrNotFound = union(enum) { - stats: bun.JSC.Node.Stats, + stats: bun.jsc.Node.Stats, not_found: void, - pub fn toJS(this: *StatOrNotFound, globalObject: *JSC.JSGlobalObject) JSC.JSValue { + pub fn toJS(this: *StatOrNotFound, globalObject: *jsc.JSGlobalObject) jsc.JSValue { return switch (this.*) { .stats => this.stats.toJS(globalObject), .not_found => .js_undefined, }; } - pub fn toJSNewlyCreated(this: *const StatOrNotFound, globalObject: *JSC.JSGlobalObject) bun.JSError!JSC.JSValue { + pub fn toJSNewlyCreated(this: *const StatOrNotFound, globalObject: *jsc.JSGlobalObject) bun.JSError!jsc.JSValue { return switch (this.*) { .stats => this.stats.toJSNewlyCreated(globalObject), .not_found => .js_undefined, @@ -3156,7 +3156,7 @@ pub const StringOrUndefined = union(enum) { string: bun.String, none: void, - pub fn toJS(this: *const StringOrUndefined, globalObject: *JSC.JSGlobalObject) JSC.JSValue { + pub fn toJS(this: *const StringOrUndefined, globalObject: *jsc.JSGlobalObject) jsc.JSValue { return switch (this.*) { .string => this.string.toJS(globalObject), .none => .js_undefined, @@ -3166,7 +3166,7 @@ pub const StringOrUndefined = union(enum) { /// For use in `Return`'s definitions to act as `void` while returning `null` to JavaScript const Null = struct { - pub fn toJS(_: @This(), _: *JSC.JSGlobalObject) JSC.JSValue { + pub fn toJS(_: @This(), _: *jsc.JSGlobalObject) jsc.JSValue { return .null; } }; @@ -3182,7 +3182,7 @@ const Return = struct { pub const Chmod = void; pub const Fchown = void; pub const Fdatasync = void; - pub const Fstat = bun.JSC.Node.Stats; + pub const Fstat = bun.jsc.Node.Stats; pub const Rm = void; pub const Fsync = void; pub const Ftruncate = void; @@ -3192,34 +3192,34 @@ const Return = struct { pub const Link = void; pub const Lstat = StatOrNotFound; pub const Mkdir = StringOrUndefined; - pub const Mkdtemp = JSC.ZigString; + pub const Mkdtemp = jsc.ZigString; pub const Open = FD; pub const WriteFile = void; pub const Readv = Read; - pub const StatFS = bun.JSC.Node.StatFS; + pub const StatFS = bun.jsc.Node.StatFS; pub const Read = struct { bytes_read: u52, - pub fn toJS(this: Read, _: *JSC.JSGlobalObject) JSC.JSValue { - return JSC.JSValue.jsNumberFromUint64(this.bytes_read); + pub fn toJS(this: Read, _: *jsc.JSGlobalObject) jsc.JSValue { + return jsc.JSValue.jsNumberFromUint64(this.bytes_read); } }; pub const ReadPromise = struct { bytes_read: u52, - buffer_val: JSC.JSValue = JSC.JSValue.zero, + buffer_val: jsc.JSValue = jsc.JSValue.zero, const fields = .{ - .bytesRead = JSC.ZigString.init("bytesRead"), - .buffer = JSC.ZigString.init("buffer"), + .bytesRead = jsc.ZigString.init("bytesRead"), + .buffer = jsc.ZigString.init("buffer"), }; - pub fn toJS(this: *const ReadPromise, ctx: *JSC.JSGlobalObject) bun.JSError!JSC.JSValue { + pub fn toJS(this: *const ReadPromise, ctx: *jsc.JSGlobalObject) bun.JSError!jsc.JSValue { defer if (!this.buffer_val.isEmptyOrUndefinedOrNull()) this.buffer_val.unprotect(); - return JSC.JSValue.createObject2( + return jsc.JSValue.createObject2( ctx, &fields.bytesRead, &fields.buffer, - JSC.JSValue.jsNumberFromUint64(@as(u52, @intCast(@min(std.math.maxInt(u52), this.bytes_read)))), + jsc.JSValue.jsNumberFromUint64(@as(u52, @intCast(@min(std.math.maxInt(u52), this.bytes_read)))), this.buffer_val, ); } @@ -3227,22 +3227,22 @@ const Return = struct { pub const WritePromise = struct { bytes_written: u52, buffer: StringOrBuffer, - buffer_val: JSC.JSValue = JSC.JSValue.zero, + buffer_val: jsc.JSValue = jsc.JSValue.zero, const fields = .{ - .bytesWritten = JSC.ZigString.init("bytesWritten"), - .buffer = JSC.ZigString.init("buffer"), + .bytesWritten = jsc.ZigString.init("bytesWritten"), + .buffer = jsc.ZigString.init("buffer"), }; // Excited for the issue that's like "cannot read file bigger than 2 GB" - pub fn toJS(this: *const WritePromise, globalObject: *JSC.JSGlobalObject) bun.JSError!bun.jsc.JSValue { + pub fn toJS(this: *const WritePromise, globalObject: *jsc.JSGlobalObject) bun.JSError!bun.jsc.JSValue { defer if (!this.buffer_val.isEmptyOrUndefinedOrNull()) this.buffer_val.unprotect(); - return JSC.JSValue.createObject2( + return jsc.JSValue.createObject2( globalObject, &fields.bytesWritten, &fields.buffer, - JSC.JSValue.jsNumberFromUint64(@as(u52, @intCast(@min(std.math.maxInt(u52), this.bytes_written)))), + jsc.JSValue.jsNumberFromUint64(@as(u52, @intCast(@min(std.math.maxInt(u52), this.bytes_written)))), if (this.buffer == .buffer) this.buffer_val else @@ -3253,16 +3253,16 @@ const Return = struct { pub const Write = struct { bytes_written: u52, const fields = .{ - .bytesWritten = JSC.ZigString.init("bytesWritten"), + .bytesWritten = jsc.ZigString.init("bytesWritten"), }; // Excited for the issue that's like "cannot read file bigger than 2 GB" - pub fn toJS(this: *const Write, _: *JSC.JSGlobalObject) JSC.JSValue { - return JSC.JSValue.jsNumberFromUint64(this.bytes_written); + pub fn toJS(this: *const Write, _: *jsc.JSGlobalObject) jsc.JSValue { + return jsc.JSValue.jsNumberFromUint64(this.bytes_written); } }; pub const Readdir = union(Tag) { - with_file_types: []bun.JSC.Node.Dirent, + with_file_types: []bun.jsc.Node.Dirent, buffers: []Buffer, files: []const bun.String, @@ -3272,12 +3272,12 @@ const Return = struct { files, }; - pub fn toJS(this: Readdir, globalObject: *JSC.JSGlobalObject) bun.JSError!JSC.JSValue { + pub fn toJS(this: Readdir, globalObject: *jsc.JSGlobalObject) bun.JSError!jsc.JSValue { switch (this) { .with_file_types => { defer bun.default_allocator.free(this.with_file_types); - var array = try JSC.JSValue.createEmptyArray(globalObject, this.with_file_types.len); - var previous_jsstring: ?*JSC.JSString = null; + var array = try jsc.JSValue.createEmptyArray(globalObject, this.with_file_types.len); + var previous_jsstring: ?*jsc.JSString = null; for (this.with_file_types, 0..) |*item, i| { const res = try item.toJSNewlyCreated(globalObject, &previous_jsstring); try array.putIndex(globalObject, @truncate(i), res); @@ -3286,11 +3286,11 @@ const Return = struct { }, .buffers => { defer bun.default_allocator.free(this.buffers); - return JSC.toJS(globalObject, []Buffer, this.buffers); + return jsc.toJS(globalObject, []Buffer, this.buffers); }, .files => { // automatically freed - return JSC.toJS(globalObject, []const bun.String, this.files); + return jsc.toJS(globalObject, []const bun.String, this.files); }, } } @@ -3312,8 +3312,8 @@ const Return = struct { pub const Truncate = void; pub const Unlink = void; pub const UnwatchFile = void; - pub const Watch = JSC.JSValue; - pub const WatchFile = JSC.JSValue; + pub const Watch = jsc.JSValue; + pub const WatchFile = jsc.JSValue; pub const Utimes = void; pub const Chown = void; pub const Lutimes = void; @@ -3326,11 +3326,11 @@ const Return = struct { pub const NodeFS = struct { /// Buffer to store a temporary file path that might appear in a returned error message. /// - /// We want to avoid allocating a new path buffer for every error message so that JSC can clone + GC it. + /// We want to avoid allocating a new path buffer for every error message so that jsc can clone + GC it. /// That means a stack-allocated buffer won't suffice. Instead, we re-use /// the heap allocated buffer on the NodeFS struct sync_error_buf: bun.PathBuffer align(@alignOf(u16)) = undefined, - vm: ?*JSC.VirtualMachine = null, + vm: ?*jsc.VirtualMachine = null, pub const ReturnType = Return; @@ -3567,7 +3567,7 @@ pub const NodeFS = struct { flags |= bun.O.EXCL; } - const dest_fd = switch (Syscall.open(dest, flags, JSC.Node.fs.default_permission)) { + const dest_fd = switch (Syscall.open(dest, flags, jsc.Node.fs.default_permission)) { .result => |result| result, .err => |err| return Maybe(Return.CopyFile){ .err = err.withPath(args.dest.slice()) }, }; @@ -3621,7 +3621,7 @@ pub const NodeFS = struct { flags |= bun.O.EXCL; } - const dest_fd = switch (Syscall.open(dest, flags, JSC.Node.fs.default_permission)) { + const dest_fd = switch (Syscall.open(dest, flags, jsc.Node.fs.default_permission)) { .result => |result| result, .err => |err| return Maybe(Return.CopyFile){ .err = err }, }; @@ -4128,14 +4128,14 @@ pub const NodeFS = struct { } }; } return .{ - .result = JSC.ZigString.dupeForJS(bun.sliceTo(req.path, 0), bun.default_allocator) catch bun.outOfMemory(), + .result = jsc.ZigString.dupeForJS(bun.sliceTo(req.path, 0), bun.default_allocator) catch bun.outOfMemory(), }; } const rc = c.mkdtemp(prefix_buf); if (rc) |ptr| { return .{ - .result = JSC.ZigString.dupeForJS(bun.sliceTo(ptr, 0), bun.default_allocator) catch bun.outOfMemory(), + .result = jsc.ZigString.dupeForJS(bun.sliceTo(ptr, 0), bun.default_allocator) catch bun.outOfMemory(), }; } @@ -4400,7 +4400,7 @@ pub const NodeFS = struct { const maybe = switch (args.recursive) { inline else => |recursive| switch (args.tag()) { .buffers => readdirInner(&this.sync_error_buf, args, Buffer, recursive, flavor), - .with_file_types => readdirInner(&this.sync_error_buf, args, bun.JSC.Node.Dirent, recursive, flavor), + .with_file_types => readdirInner(&this.sync_error_buf, args, bun.jsc.Node.Dirent, recursive, flavor), .files => readdirInner(&this.sync_error_buf, args, bun.String, recursive, flavor), }, }; @@ -4421,7 +4421,7 @@ pub const NodeFS = struct { comptime ExpectedType: type, entries: *std.ArrayList(ExpectedType), ) Maybe(void) { - const is_u16 = comptime Environment.isWindows and (ExpectedType == bun.String or ExpectedType == bun.JSC.Node.Dirent); + const is_u16 = comptime Environment.isWindows and (ExpectedType == bun.String or ExpectedType == bun.jsc.Node.Dirent); var dirent_path: bun.String = bun.String.dead; defer { @@ -4442,7 +4442,7 @@ pub const NodeFS = struct { .err => |err| { for (entries.items) |*item| { switch (ExpectedType) { - bun.JSC.Node.Dirent => { + bun.jsc.Node.Dirent => { item.deref(); }, Buffer => { @@ -4463,18 +4463,18 @@ pub const NodeFS = struct { }, .result => |ent| ent, }) |current| : (entry = iterator.next()) { - if (ExpectedType == JSC.Node.Dirent) { + if (ExpectedType == jsc.Node.Dirent) { if (dirent_path.isEmpty()) { - dirent_path = JSC.WebCore.encoding.toBunString(strings.withoutNTPrefix(std.meta.Child(@TypeOf(basename)), basename), args.encoding); + dirent_path = jsc.WebCore.encoding.toBunString(strings.withoutNTPrefix(std.meta.Child(@TypeOf(basename)), basename), args.encoding); } } if (comptime !is_u16) { const utf8_name = current.name.slice(); switch (ExpectedType) { - JSC.Node.Dirent => { + jsc.Node.Dirent => { dirent_path.ref(); entries.append(.{ - .name = JSC.WebCore.encoding.toBunString(utf8_name, args.encoding), + .name = jsc.WebCore.encoding.toBunString(utf8_name, args.encoding), .path = dirent_path, .kind = current.kind, }) catch bun.outOfMemory(); @@ -4483,14 +4483,14 @@ pub const NodeFS = struct { entries.append(Buffer.fromString(utf8_name, bun.default_allocator) catch bun.outOfMemory()) catch bun.outOfMemory(); }, bun.String => { - entries.append(JSC.WebCore.encoding.toBunString(utf8_name, args.encoding)) catch bun.outOfMemory(); + entries.append(jsc.WebCore.encoding.toBunString(utf8_name, args.encoding)) catch bun.outOfMemory(); }, else => @compileError("unreachable"), } } else { const utf16_name = current.name.slice(); switch (ExpectedType) { - JSC.Node.Dirent => { + jsc.Node.Dirent => { dirent_path.ref(); entries.append(.{ .name = bun.String.cloneUTF16(utf16_name), @@ -4505,7 +4505,7 @@ pub const NodeFS = struct { .utf8 => entries.append(bun.String.cloneUTF16(utf16_name)) catch bun.outOfMemory(), else => |enc| { const utf8_path = bun.strings.fromWPath(re_encoding_buffer.?, utf16_name); - entries.append(JSC.WebCore.encoding.toBunString(utf8_path, enc)) catch bun.outOfMemory(); + entries.append(jsc.WebCore.encoding.toBunString(utf8_path, enc)) catch bun.outOfMemory(); }, }, else => @compileError("unreachable"), @@ -4625,7 +4625,7 @@ pub const NodeFS = struct { } switch (comptime ExpectedType) { - bun.JSC.Node.Dirent => { + bun.jsc.Node.Dirent => { const path_u8 = bun.path.dirname(bun.path.join(&[_]string{ root_basename, name_to_copy }, .auto), .auto); if (dirent_path_prev.isEmpty() or !bun.strings.eql(dirent_path_prev.byteSlice(), path_u8)) { dirent_path_prev.deref(); @@ -4765,15 +4765,15 @@ pub const NodeFS = struct { } switch (comptime ExpectedType) { - bun.JSC.Node.Dirent => { + bun.jsc.Node.Dirent => { const path_u8 = bun.path.dirname(bun.path.join(&[_]string{ root_basename, name_to_copy }, .auto), .auto); if (dirent_path_prev.isEmpty() or !bun.strings.eql(dirent_path_prev.byteSlice(), path_u8)) { dirent_path_prev.deref(); - dirent_path_prev = JSC.WebCore.encoding.toBunString(strings.withoutNTPrefix(std.meta.Child(@TypeOf(path_u8)), path_u8), args.encoding); + dirent_path_prev = jsc.WebCore.encoding.toBunString(strings.withoutNTPrefix(std.meta.Child(@TypeOf(path_u8)), path_u8), args.encoding); } dirent_path_prev.ref(); entries.append(.{ - .name = JSC.WebCore.encoding.toBunString(utf8_name, args.encoding), + .name = jsc.WebCore.encoding.toBunString(utf8_name, args.encoding), .path = dirent_path_prev, .kind = current.kind, }) catch bun.outOfMemory(); @@ -4782,7 +4782,7 @@ pub const NodeFS = struct { entries.append(Buffer.fromString(strings.withoutNTPrefix(std.meta.Child(@TypeOf(name_to_copy)), name_to_copy), bun.default_allocator) catch bun.outOfMemory()) catch bun.outOfMemory(); }, bun.String => { - entries.append(JSC.WebCore.encoding.toBunString(strings.withoutNTPrefix(std.meta.Child(@TypeOf(name_to_copy)), name_to_copy), args.encoding)) catch bun.outOfMemory(); + entries.append(jsc.WebCore.encoding.toBunString(strings.withoutNTPrefix(std.meta.Child(@TypeOf(name_to_copy)), name_to_copy), args.encoding)) catch bun.outOfMemory(); }, else => @compileError(unreachable), } @@ -4805,7 +4805,7 @@ pub const NodeFS = struct { if ( // Typed arrays in JavaScript are limited to 4.7 GB. - adjusted_size > JSC.VirtualMachine.synthetic_allocation_limit or + adjusted_size > jsc.VirtualMachine.synthetic_allocation_limit or // If they do not have enough memory to open the file and they're on Linux, let's throw an error instead of dealing with the OOM killer. (Environment.isLinux and size >= bun.getTotalMemorySize())) { @@ -4823,7 +4823,7 @@ pub const NodeFS = struct { comptime flavor: Flavor, ) Maybe(Return.Readdir) { const file_type = switch (ExpectedType) { - bun.JSC.Node.Dirent => "with_file_types", + bun.jsc.Node.Dirent => "with_file_types", bun.String => "files", Buffer => "buffers", else => @compileError("unreachable"), @@ -4839,7 +4839,7 @@ pub const NodeFS = struct { .err => |err| { for (entries.items) |*result| { switch (ExpectedType) { - bun.JSC.Node.Dirent => { + bun.jsc.Node.Dirent => { result.name.deref(); }, Buffer => { @@ -5032,13 +5032,13 @@ pub const NodeFS = struct { .buffer => { if (comptime flavor == .sync and string_type == .default) { if (this.vm) |vm| { - // Attempt to create the buffer in JSC's heap. + // Attempt to create the buffer in jsc's heap. // This avoids creating a WastefulTypedArray. - const array_buffer = JSC.ArrayBuffer.createBuffer(vm.global, temporary_read_buffer) catch .zero; // TODO: properly propagate exception upwards + const array_buffer = jsc.ArrayBuffer.createBuffer(vm.global, temporary_read_buffer) catch .zero; // TODO: properly propagate exception upwards array_buffer.ensureStillAlive(); return .{ .result = .{ - .buffer = JSC.MarkedArrayBuffer{ + .buffer = jsc.MarkedArrayBuffer{ .buffer = array_buffer.asArrayBuffer(vm.global) orelse { // This case shouldn't really happen. return .{ @@ -5067,7 +5067,7 @@ pub const NodeFS = struct { if (comptime string_type == .default) { return .{ .result = .{ - .transcoded_string = JSC.WebCore.encoding.toBunString(temporary_read_buffer, args.encoding), + .transcoded_string = jsc.WebCore.encoding.toBunString(temporary_read_buffer, args.encoding), }, }; } else { @@ -5098,7 +5098,7 @@ pub const NodeFS = struct { // For certain files, the size might be 0 but the file might still have contents. // https://github.com/oven-sh/bun/issues/1220 - const max_size = args.max_size orelse std.math.maxInt(JSC.WebCore.Blob.SizeType); + const max_size = args.max_size orelse std.math.maxInt(jsc.WebCore.Blob.SizeType); const has_max_size = args.max_size != null; const size = @as( @@ -5452,7 +5452,7 @@ pub const NodeFS = struct { }; }, else => |enc| .{ - .string = .{ .utf8 = .{}, .underlying = JSC.WebCore.encoding.toBunString(buf, enc) }, + .string = .{ .utf8 = .{}, .underlying = jsc.WebCore.encoding.toBunString(buf, enc) }, }, }, }; @@ -5504,7 +5504,7 @@ pub const NodeFS = struct { }; }, else => |enc| .{ - .string = .{ .utf8 = .{}, .underlying = JSC.WebCore.encoding.toBunString(buf, enc) }, + .string = .{ .utf8 = .{}, .underlying = jsc.WebCore.encoding.toBunString(buf, enc) }, }, }, }; @@ -5861,7 +5861,7 @@ pub const NodeFS = struct { const watcher = args.createStatWatcher() catch |err| { const buf = std.fmt.allocPrint(bun.default_allocator, "Failed to watch file {}", .{bun.fmt.QuotedFormatter{ .text = args.path.slice() }}) catch bun.outOfMemory(); defer bun.default_allocator.free(buf); - args.global_this.throwValue((JSC.SystemError{ + args.global_this.throwValue((jsc.SystemError{ .message = bun.String.init(buf), .code = bun.String.init(@errorName(err)), .path = bun.String.init(args.path.slice()), @@ -6246,7 +6246,7 @@ pub const NodeFS = struct { } const dest_fd = dest_fd: { - switch (Syscall.open(dest, flags, JSC.Node.fs.default_permission)) { + switch (Syscall.open(dest, flags, jsc.Node.fs.default_permission)) { .result => |result| break :dest_fd result, .err => |err| { if (err.getErrno() == .NOENT) { @@ -6263,7 +6263,7 @@ pub const NodeFS = struct { return Maybe(Return.CopyFile){ .err = mkdirResult.err }; } - switch (Syscall.open(dest, flags, JSC.Node.fs.default_permission)) { + switch (Syscall.open(dest, flags, jsc.Node.fs.default_permission)) { .result => |result| break :dest_fd result, .err => {}, } @@ -6341,7 +6341,7 @@ pub const NodeFS = struct { } const dest_fd = dest_fd: { - switch (Syscall.open(dest, flags, JSC.Node.fs.default_permission)) { + switch (Syscall.open(dest, flags, jsc.Node.fs.default_permission)) { .result => |result| break :dest_fd result, .err => |err| { if (err.getErrno() == .NOENT) { @@ -6358,7 +6358,7 @@ pub const NodeFS = struct { return Maybe(Return.CopyFile){ .err = mkdirResult.err }; } - switch (Syscall.open(dest, flags, JSC.Node.fs.default_permission)) { + switch (Syscall.open(dest, flags, jsc.Node.fs.default_permission)) { .result => |result| break :dest_fd result, .err => {}, } @@ -6515,14 +6515,14 @@ pub const NodeFS = struct { } }; -fn throwInvalidFdError(global: *JSC.JSGlobalObject, value: JSC.JSValue) bun.JSError { +fn throwInvalidFdError(global: *jsc.JSGlobalObject, value: jsc.JSValue) bun.JSError { if (value.isNumber()) { return global.ERR(.OUT_OF_RANGE, "The value of \"fd\" is out of range. It must be an integer. Received {d}", .{bun.fmt.double(value.asNumber())}).throw(); } return global.throwInvalidArgumentTypeValue("fd", "number", value); } -pub export fn Bun__mkdirp(globalThis: *JSC.JSGlobalObject, path: [*:0]const u8) bool { +pub export fn Bun__mkdirp(globalThis: *jsc.JSGlobalObject, path: [*:0]const u8) bool { return globalThis.bunVM().nodeFS().mkdirRecursive( Arguments.Mkdir{ .path = PathLike{ .string = PathString.init(bun.span(path)) }, @@ -6899,6 +6899,8 @@ const Syscall = if (Environment.isWindows) bun.sys.sys_uv else bun.sys; const ReadPosition = i64; const NodeFSFunctionEnum = std.meta.DeclEnum(NodeFS); +const string = []const u8; + const DirIterator = @import("./dir_iterator.zig"); const FileSystem = @import("../../fs.zig").FileSystem; @@ -6909,24 +6911,23 @@ const FileDescriptor = bun.FileDescriptor; const Mode = bun.Mode; const PathString = bun.PathString; const c = bun.c; -const string = bun.string; const strings = bun.strings; const AbortSignal = bun.webcore.AbortSignal; const Buffer = bun.api.node.Buffer; -const JSC = bun.JSC; -const ArrayBuffer = JSC.MarkedArrayBuffer; -const Maybe = JSC.Maybe; -const ArgumentsSlice = JSC.CallFrame.ArgumentsSlice; +const jsc = bun.jsc; +const ArrayBuffer = jsc.MarkedArrayBuffer; +const Maybe = jsc.Maybe; +const ArgumentsSlice = jsc.CallFrame.ArgumentsSlice; -const Encoding = JSC.Node.Encoding; -const FileSystemFlags = JSC.Node.FileSystemFlags; -const PathLike = JSC.Node.PathLike; -const PathOrFileDescriptor = JSC.Node.PathOrFileDescriptor; -const StringOrBuffer = JSC.Node.StringOrBuffer; -const TimeLike = JSC.Node.TimeLike; -const gid_t = JSC.Node.gid_t; -const uid_t = JSC.Node.uid_t; +const Encoding = jsc.Node.Encoding; +const FileSystemFlags = jsc.Node.FileSystemFlags; +const PathLike = jsc.Node.PathLike; +const PathOrFileDescriptor = jsc.Node.PathOrFileDescriptor; +const StringOrBuffer = jsc.Node.StringOrBuffer; +const TimeLike = jsc.Node.TimeLike; +const gid_t = jsc.Node.gid_t; +const uid_t = jsc.Node.uid_t; const E = bun.sys.E; const SystemErrno = bun.sys.SystemErrno; diff --git a/src/bun.js/node/node_fs_binding.zig b/src/bun.js/node/node_fs_binding.zig index e7dea70c40..57c85544a9 100644 --- a/src/bun.js/node/node_fs_binding.zig +++ b/src/bun.js/node/node_fs_binding.zig @@ -1,11 +1,11 @@ -const NodeFSFunction = fn (this: *JSC.Node.fs.Binding, globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue; +const NodeFSFunction = fn (this: *jsc.Node.fs.Binding, globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue; const NodeFSFunctionEnum = std.meta.DeclEnum(node.fs.NodeFS); -/// Returns bindings to call JSC.Node.fs.NodeFS.. +/// Returns bindings to call jsc.Node.fs.NodeFS.. /// Async calls use a thread pool. fn Bindings(comptime function_name: NodeFSFunctionEnum) type { - const function = @field(JSC.Node.fs.NodeFS, @tagName(function_name)); + const function = @field(jsc.Node.fs.NodeFS, @tagName(function_name)); const fn_info = @typeInfo(@TypeOf(function)).@"fn"; if (fn_info.params.len != 3) { @compileError("Expected fn(NodeFS, Arguments) Return for NodeFS." ++ @tagName(function_name)); @@ -13,7 +13,7 @@ fn Bindings(comptime function_name: NodeFSFunctionEnum) type { const Arguments = fn_info.params[1].type.?; return struct { - pub fn runSync(this: *Binding, globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { + pub fn runSync(this: *Binding, globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { var slice = ArgumentsSlice.init(globalObject.bunVM(), callframe.arguments()); defer slice.deinit(); @@ -34,7 +34,7 @@ fn Bindings(comptime function_name: NodeFSFunctionEnum) type { }; } - pub fn runAsync(this: *Binding, globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { + pub fn runAsync(this: *Binding, globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { var slice = ArgumentsSlice.init(globalObject.bunVM(), callframe.arguments()); slice.will_be_async = true; var deinit = false; @@ -59,7 +59,7 @@ fn Bindings(comptime function_name: NodeFSFunctionEnum) type { const signal = args.signal orelse break :check_early_abort; if (signal.reasonIfAborted(globalObject)) |reason| { deinit = true; - return JSC.JSPromise.dangerouslyCreateRejectedPromiseValueWithoutNotifyingVM(globalObject, reason.toJS(globalObject)); + return jsc.JSPromise.dangerouslyCreateRejectedPromiseValueWithoutNotifyingVM(globalObject, reason.toJS(globalObject)); } } @@ -84,7 +84,7 @@ fn callSync(comptime FunctionEnum: NodeFSFunctionEnum) NodeFSFunction { pub const Binding = struct { node_fs: node.fs.NodeFS = .{}, - pub const js = JSC.Codegen.JSNodeJSFS; + pub const js = jsc.Codegen.JSNodeJSFS; pub const toJS = js.toJS; pub const fromJS = js.fromJS; pub const fromJSDirect = js.fromJSDirect; @@ -101,12 +101,12 @@ pub const Binding = struct { bun.destroy(this); } - pub fn getDirent(_: *Binding, globalThis: *JSC.JSGlobalObject) JSC.JSValue { - return JSC.Node.Dirent.getConstructor(globalThis); + pub fn getDirent(_: *Binding, globalThis: *jsc.JSGlobalObject) jsc.JSValue { + return jsc.Node.Dirent.getConstructor(globalThis); } - pub fn getStats(_: *Binding, globalThis: *JSC.JSGlobalObject) JSC.JSValue { - return JSC.Node.StatsSmall.getConstructor(globalThis); + pub fn getStats(_: *Binding, globalThis: *jsc.JSGlobalObject) jsc.JSValue { + return jsc.Node.StatsSmall.getConstructor(globalThis); } pub const access = callAsync(.access); @@ -200,7 +200,7 @@ pub const Binding = struct { // pub const statfsSync = callSync(.statfs); }; -pub fn createBinding(globalObject: *JSC.JSGlobalObject) JSC.JSValue { +pub fn createBinding(globalObject: *jsc.JSGlobalObject) jsc.JSValue { const module = Binding.new(.{}); const vm = globalObject.bunVM(); @@ -209,7 +209,7 @@ pub fn createBinding(globalObject: *JSC.JSGlobalObject) JSC.JSValue { return module.toJS(globalObject); } -pub fn createMemfdForTesting(globalObject: *JSC.JSGlobalObject, callFrame: *JSC.CallFrame) bun.JSError!JSC.JSValue { +pub fn createMemfdForTesting(globalObject: *jsc.JSGlobalObject, callFrame: *jsc.CallFrame) bun.JSError!jsc.JSValue { const arguments = callFrame.arguments_old(1); if (arguments.len < 1) { @@ -224,7 +224,7 @@ pub fn createMemfdForTesting(globalObject: *JSC.JSGlobalObject, callFrame: *JSC. switch (bun.sys.memfd_create("my_memfd", std.os.linux.MFD.CLOEXEC)) { .result => |fd| { _ = bun.sys.ftruncate(fd, size); - return JSC.JSValue.jsNumber(fd.cast()); + return jsc.JSValue.jsNumber(fd.cast()); }, .err => |err| { return globalObject.throwValue(err.toJS(globalObject)); @@ -235,6 +235,6 @@ pub fn createMemfdForTesting(globalObject: *JSC.JSGlobalObject, callFrame: *JSC. const std = @import("std"); const bun = @import("bun"); -const JSC = bun.JSC; +const jsc = bun.jsc; const node = bun.api.node; -const ArgumentsSlice = JSC.CallFrame.ArgumentsSlice; +const ArgumentsSlice = jsc.CallFrame.ArgumentsSlice; diff --git a/src/bun.js/node/node_fs_stat_watcher.zig b/src/bun.js/node/node_fs_stat_watcher.zig index 740d6b6c0c..5bb0dec2c7 100644 --- a/src/bun.js/node/node_fs_stat_watcher.zig +++ b/src/bun.js/node/node_fs_stat_watcher.zig @@ -1,6 +1,6 @@ const log = bun.Output.scoped(.StatWatcher, false); -fn statToJSStats(globalThis: *JSC.JSGlobalObject, stats: *const bun.Stat, bigint: bool) bun.JSError!JSC.JSValue { +fn statToJSStats(globalThis: *jsc.JSGlobalObject, stats: *const bun.Stat, bigint: bool) bun.JSError!jsc.JSValue { if (bigint) { return StatsBig.init(stats).toJS(globalThis); } else { @@ -11,9 +11,9 @@ fn statToJSStats(globalThis: *JSC.JSGlobalObject, stats: *const bun.Stat, bigint /// This is a singleton struct that contains the timer used to schedule re-stat calls. pub const StatWatcherScheduler = struct { current_interval: std.atomic.Value(i32) = .{ .raw = 0 }, - task: JSC.WorkPoolTask = .{ .callback = &workPoolCallback }, + task: jsc.WorkPoolTask = .{ .callback = &workPoolCallback }, main_thread: std.Thread.Id, - vm: *bun.JSC.VirtualMachine, + vm: *bun.jsc.VirtualMachine, watchers: WatcherQueue = WatcherQueue{}, event_loop_timer: EventLoopTimer = .{ @@ -29,7 +29,7 @@ pub const StatWatcherScheduler = struct { const WatcherQueue = UnboundedQueue(StatWatcher, .next); - pub fn init(vm: *bun.JSC.VirtualMachine) bun.ptr.RefPtr(StatWatcherScheduler) { + pub fn init(vm: *bun.jsc.VirtualMachine) bun.ptr.RefPtr(StatWatcherScheduler) { return .new(.{ .ref_count = .init(), .main_thread = std.Thread.getCurrentId(), @@ -95,7 +95,7 @@ pub const StatWatcherScheduler = struct { fn scheduleTimerUpdate(this: *StatWatcherScheduler) void { const Holder = struct { scheduler: *StatWatcherScheduler, - task: JSC.AnyTask, + task: jsc.AnyTask, pub fn updateTimer(self: *@This()) void { defer bun.default_allocator.destroy(self); @@ -105,9 +105,9 @@ pub const StatWatcherScheduler = struct { const holder = bun.default_allocator.create(Holder) catch bun.outOfMemory(); holder.* = .{ .scheduler = this, - .task = JSC.AnyTask.New(Holder, Holder.updateTimer).init(holder), + .task = jsc.AnyTask.New(Holder, Holder.updateTimer).init(holder), }; - this.vm.enqueueTaskConcurrent(JSC.ConcurrentTask.create(JSC.Task.init(&holder.task))); + this.vm.enqueueTaskConcurrent(jsc.ConcurrentTask.create(jsc.Task.init(&holder.task))); } pub fn timerCallback(this: *StatWatcherScheduler) EventLoopTimer.Arm { @@ -120,12 +120,12 @@ pub const StatWatcherScheduler = struct { return .disarm; } - JSC.WorkPool.schedule(&this.task); + jsc.WorkPool.schedule(&this.task); return .disarm; } - pub fn workPoolCallback(task: *JSC.WorkPoolTask) void { + pub fn workPoolCallback(task: *jsc.WorkPoolTask) void { var this: *StatWatcherScheduler = @alignCast(@fieldParentPtr("task", task)); // ref'd when the timer was scheduled defer this.deref(); @@ -187,13 +187,13 @@ pub const StatWatcher = struct { interval: i32, last_check: std.time.Instant, - globalThis: *JSC.JSGlobalObject, - js_this: JSC.JSValue, + globalThis: *jsc.JSGlobalObject, + js_this: jsc.JSValue, poll_ref: bun.Async.KeepAlive = .{}, last_stat: bun.Stat, - last_jsvalue: JSC.Strong.Optional, + last_jsvalue: jsc.Strong.Optional, scheduler: bun.ptr.RefPtr(StatWatcherScheduler), @@ -201,7 +201,7 @@ pub const StatWatcher = struct { pub const ref = RefCount.ref; pub const deref = RefCount.deref; - pub const js = JSC.Codegen.JSStatWatcher; + pub const js = jsc.Codegen.JSStatWatcher; pub const toJS = js.toJS; pub const fromJS = js.fromJS; pub const fromJSDirect = js.fromJSDirect; @@ -210,7 +210,7 @@ pub const StatWatcher = struct { return this.ctx.eventLoop(); } - pub fn enqueueTaskConcurrent(this: StatWatcher, task: *JSC.ConcurrentTask) void { + pub fn enqueueTaskConcurrent(this: StatWatcher, task: *jsc.ConcurrentTask) void { this.eventLoop().enqueueTaskConcurrent(task); } @@ -230,20 +230,20 @@ pub const StatWatcher = struct { pub const Arguments = struct { path: PathLike, - listener: JSC.JSValue, + listener: jsc.JSValue, persistent: bool, bigint: bool, interval: i32, - global_this: *JSC.JSGlobalObject, + global_this: *jsc.JSGlobalObject, - pub fn fromJS(global: *JSC.JSGlobalObject, arguments: *ArgumentsSlice) bun.JSError!Arguments { + pub fn fromJS(global: *jsc.JSGlobalObject, arguments: *ArgumentsSlice) bun.JSError!Arguments { const path = try PathLike.fromJSWithAllocator(global, arguments, bun.default_allocator) orelse { return global.throwInvalidArguments("filename must be a string or TypedArray", .{}); }; - var listener: JSC.JSValue = .zero; + var listener: jsc.JSValue = .zero; var persistent: bool = true; var bigint: bool = false; var interval: i32 = 5007; @@ -286,7 +286,7 @@ pub const StatWatcher = struct { }; } - pub fn createStatWatcher(this: Arguments) !JSC.JSValue { + pub fn createStatWatcher(this: Arguments) !jsc.JSValue { const obj = try StatWatcher.init(this); if (obj.js_this != .zero) { return obj.js_this; @@ -295,7 +295,7 @@ pub const StatWatcher = struct { } }; - pub fn doRef(this: *StatWatcher, _: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!JSC.JSValue { + pub fn doRef(this: *StatWatcher, _: *jsc.JSGlobalObject, _: *jsc.CallFrame) bun.JSError!jsc.JSValue { if (!this.closed and !this.persistent) { this.persistent = true; this.poll_ref.ref(this.ctx); @@ -303,7 +303,7 @@ pub const StatWatcher = struct { return .js_undefined; } - pub fn doUnref(this: *StatWatcher, _: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!JSC.JSValue { + pub fn doUnref(this: *StatWatcher, _: *jsc.JSGlobalObject, _: *jsc.CallFrame) bun.JSError!jsc.JSValue { if (this.persistent) { this.persistent = false; this.poll_ref.unref(this.ctx); @@ -321,7 +321,7 @@ pub const StatWatcher = struct { this.last_jsvalue.clearWithoutDeallocation(); } - pub fn doClose(this: *StatWatcher, _: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!JSC.JSValue { + pub fn doClose(this: *StatWatcher, _: *jsc.JSGlobalObject, _: *jsc.CallFrame) bun.JSError!jsc.JSValue { this.close(); return .js_undefined; } @@ -336,14 +336,14 @@ pub const StatWatcher = struct { pub const InitialStatTask = struct { watcher: *StatWatcher, - task: JSC.WorkPoolTask = .{ .callback = &workPoolCallback }, + task: jsc.WorkPoolTask = .{ .callback = &workPoolCallback }, pub fn createAndSchedule(watcher: *StatWatcher) void { const task = bun.new(InitialStatTask, .{ .watcher = watcher }); - JSC.WorkPool.schedule(&task.task); + jsc.WorkPool.schedule(&task.task); } - fn workPoolCallback(task: *JSC.WorkPoolTask) void { + fn workPoolCallback(task: *jsc.WorkPoolTask) void { const initial_stat_task: *InitialStatTask = @fieldParentPtr("task", task); defer bun.destroy(initial_stat_task); const this = initial_stat_task.watcher; @@ -357,13 +357,13 @@ pub const StatWatcher = struct { .result => |res| { // we store the stat, but do not call the callback this.last_stat = res; - this.enqueueTaskConcurrent(JSC.ConcurrentTask.fromCallback(this, initialStatSuccessOnMainThread)); + this.enqueueTaskConcurrent(jsc.ConcurrentTask.fromCallback(this, initialStatSuccessOnMainThread)); }, .err => { // on enoent, eperm, we call cb with two zeroed stat objects // and store previous stat as a zeroed stat object, and then call the callback. this.last_stat = std.mem.zeroes(bun.Stat); - this.enqueueTaskConcurrent(JSC.ConcurrentTask.fromCallback(this, initialStatErrorOnMainThread)); + this.enqueueTaskConcurrent(jsc.ConcurrentTask.fromCallback(this, initialStatErrorOnMainThread)); }, } } @@ -391,7 +391,7 @@ pub const StatWatcher = struct { _ = js.listenerGetCached(this.js_this).?.call( this.globalThis, .js_undefined, - &[2]JSC.JSValue{ + &[2]jsc.JSValue{ jsvalue, jsvalue, }, @@ -425,7 +425,7 @@ pub const StatWatcher = struct { if (std.mem.eql(u8, std.mem.asBytes(&compare), std.mem.asBytes(&this.last_stat))) return; this.last_stat = res; - this.enqueueTaskConcurrent(JSC.ConcurrentTask.fromCallback(this, swapAndCallListenerOnMainThread)); + this.enqueueTaskConcurrent(jsc.ConcurrentTask.fromCallback(this, swapAndCallListenerOnMainThread)); } /// After a restat found the file changed, this calls the listener function. @@ -437,7 +437,7 @@ pub const StatWatcher = struct { _ = js.listenerGetCached(this.js_this).?.call( this.globalThis, .js_undefined, - &[2]JSC.JSValue{ + &[2]jsc.JSValue{ current_jsvalue, prev_jsvalue, }, @@ -456,7 +456,7 @@ pub const StatWatcher = struct { var parts = [_]string{slice}; const file_path = Path.joinAbsStringBuf( - Fs.FileSystem.instance.top_level_dir, + fs.FileSystem.instance.top_level_dir, buf, &parts, .auto, @@ -500,21 +500,22 @@ pub const StatWatcher = struct { } }; -const Fs = @import("../../fs.zig"); +const string = []const u8; + const Path = @import("../../resolver/resolve_path.zig"); +const fs = @import("../../fs.zig"); const std = @import("std"); -const EventLoopTimer = @import("../api/Timer.zig").EventLoopTimer; const bun = @import("bun"); const Output = bun.Output; -const string = bun.string; const UnboundedQueue = bun.threading.UnboundedQueue; +const EventLoopTimer = bun.api.Timer.EventLoopTimer; -const JSC = bun.JSC; -const EventLoop = JSC.EventLoop; -const VirtualMachine = JSC.VirtualMachine; -const ArgumentsSlice = JSC.CallFrame.ArgumentsSlice; +const jsc = bun.jsc; +const EventLoop = jsc.EventLoop; +const VirtualMachine = jsc.VirtualMachine; +const ArgumentsSlice = jsc.CallFrame.ArgumentsSlice; -const PathLike = JSC.Node.PathLike; -const StatsBig = bun.JSC.Node.StatsBig; -const StatsSmall = bun.JSC.Node.StatsSmall; +const PathLike = jsc.Node.PathLike; +const StatsBig = bun.jsc.Node.StatsBig; +const StatsSmall = bun.jsc.Node.StatsSmall; diff --git a/src/bun.js/node/node_fs_watcher.zig b/src/bun.js/node/node_fs_watcher.zig index 58c14aad60..1ce72f643c 100644 --- a/src/bun.js/node/node_fs_watcher.zig +++ b/src/bun.js/node/node_fs_watcher.zig @@ -3,7 +3,7 @@ const PathWatcher = if (Environment.isWindows) @import("./win_watcher.zig") else // TODO: make this a top-level struct pub const FSWatcher = struct { - pub const js = JSC.Codegen.JSFSWatcher; + pub const js = jsc.Codegen.JSFSWatcher; pub const toJS = js.toJS; pub const fromJS = js.fromJS; pub const fromJSDirect = js.fromJSDirect; @@ -16,9 +16,9 @@ pub const FSWatcher = struct { persistent: bool, path_watcher: ?*PathWatcher.PathWatcher, poll_ref: Async.KeepAlive = .{}, - globalThis: *JSC.JSGlobalObject, - js_this: JSC.JSValue, - encoding: JSC.Node.Encoding, + globalThis: *jsc.JSGlobalObject, + js_this: jsc.JSValue, + encoding: jsc.Node.Encoding, /// User can call close and pre-detach so we need to track this closed: bool, @@ -31,7 +31,7 @@ pub const FSWatcher = struct { return this.ctx.eventLoop(); } - pub fn enqueueTaskConcurrent(this: FSWatcher, task: *JSC.ConcurrentTask) void { + pub fn enqueueTaskConcurrent(this: FSWatcher, task: *jsc.ConcurrentTask) void { this.eventLoop().enqueueTaskConcurrent(task); } @@ -51,7 +51,7 @@ pub const FSWatcher = struct { count: u8 = 0, entries: [8]Entry = undefined, - concurrent_task: JSC.ConcurrentTask = undefined, + concurrent_task: jsc.ConcurrentTask = undefined, pub const Entry = struct { event: Event, @@ -119,7 +119,7 @@ pub const FSWatcher = struct { if (this.ctx.refTask()) { var that = FSWatchTask.new(this.*); this.count = 0; - that.concurrent_task.task = JSC.Task.init(that); + that.concurrent_task.task = jsc.Task.init(that); this.ctx.enqueueTaskConcurrent(&that.concurrent_task); return; } @@ -177,12 +177,12 @@ pub const FSWatcher = struct { pub fn toJS( this: EventType, - globalObject: *JSC.JSGlobalObject, - ) JSC.JSValue { + globalObject: *jsc.JSGlobalObject, + ) jsc.JSValue { return Bun__domEventNameToJS(globalObject, this); } - extern fn Bun__domEventNameToJS(*JSC.JSGlobalObject, EventType) JSC.JSValue; + extern fn Bun__domEventNameToJS(*jsc.JSGlobalObject, EventType) jsc.JSValue; }; pub const FSWatchTaskWindows = struct { @@ -221,7 +221,7 @@ pub const FSWatcher = struct { .event = .abort, }); - ctx.eventLoop().enqueueTask(JSC.Task.init(task)); + ctx.eventLoop().enqueueTask(jsc.Task.init(task)); } /// this runs on JS Context Thread @@ -303,7 +303,7 @@ pub const FSWatcher = struct { .ctx = this, .event = event, }); - this.eventLoop().enqueueTask(JSC.Task.init(task)); + this.eventLoop().enqueueTask(jsc.Task.init(task)); } pub const onPathUpdate = if (Environment.isWindows) onPathUpdateWindows else onPathUpdatePosix; @@ -321,26 +321,26 @@ pub const FSWatcher = struct { pub const Arguments = struct { path: PathLike, - listener: JSC.JSValue, - global_this: *JSC.JSGlobalObject, + listener: jsc.JSValue, + global_this: *jsc.JSGlobalObject, signal: ?*webcore.AbortSignal, persistent: bool, recursive: bool, - encoding: JSC.Node.Encoding, + encoding: jsc.Node.Encoding, verbose: bool, - pub fn fromJS(ctx: *JSC.JSGlobalObject, arguments: *ArgumentsSlice) bun.JSError!Arguments { + pub fn fromJS(ctx: *jsc.JSGlobalObject, arguments: *ArgumentsSlice) bun.JSError!Arguments { const path = try PathLike.fromJS(ctx, arguments) orelse { return ctx.throwInvalidArguments("filename must be a string or TypedArray", .{}); }; var should_deinit_path = true; defer if (should_deinit_path) path.deinit(); - var listener: JSC.JSValue = .zero; + var listener: jsc.JSValue = .zero; var signal: ?*webcore.AbortSignal = null; var persistent: bool = true; var recursive: bool = false; - var encoding: JSC.Node.Encoding = .utf8; + var encoding: jsc.Node.Encoding = .utf8; var verbose = false; if (arguments.nextEat()) |options_or_callable| { @@ -361,7 +361,7 @@ pub const FSWatcher = struct { } if (try options_or_callable.fastGet(ctx, .encoding)) |encoding_| { - encoding = try JSC.Node.Encoding.assert(encoding_, ctx, encoding); + encoding = try jsc.Node.Encoding.assert(encoding_, ctx, encoding); } if (try options_or_callable.getTruthy(ctx, "recursive")) |recursive_| { @@ -417,7 +417,7 @@ pub const FSWatcher = struct { pub const createFSWatcher = FSWatcher.init; }; - pub fn initJS(this: *FSWatcher, listener: JSC.JSValue) void { + pub fn initJS(this: *FSWatcher, listener: jsc.JSValue) void { if (this.persistent) { this.poll_ref.ref(this.ctx); _ = this.pending_activity_count.fetchAdd(1, .monotonic); @@ -452,7 +452,7 @@ pub const FSWatcher = struct { } } - pub fn emitAbort(this: *FSWatcher, err: JSC.JSValue) void { + pub fn emitAbort(this: *FSWatcher, err: jsc.JSValue) void { if (this.closed) return; _ = this.pending_activity_count.fetchAdd(1, .monotonic); defer this.close(); @@ -464,9 +464,9 @@ pub const FSWatcher = struct { js_this.ensureStillAlive(); if (js.listenerGetCached(js_this)) |listener| { listener.ensureStillAlive(); - var args = [_]JSC.JSValue{ + var args = [_]jsc.JSValue{ EventType.@"error".toJS(this.globalThis), - if (err.isEmptyOrUndefinedOrNull()) JSC.CommonAbortReason.UserAbort.toJS(this.globalThis) else err, + if (err.isEmptyOrUndefinedOrNull()) jsc.CommonAbortReason.UserAbort.toJS(this.globalThis) else err, }; _ = listener.callWithGlobalThis( this.globalThis, @@ -485,7 +485,7 @@ pub const FSWatcher = struct { if (js.listenerGetCached(js_this)) |listener| { listener.ensureStillAlive(); const globalObject = this.globalThis; - var args = [_]JSC.JSValue{ + var args = [_]jsc.JSValue{ EventType.@"error".toJS(globalObject), err.toJS(globalObject), }; @@ -497,7 +497,7 @@ pub const FSWatcher = struct { } } - pub fn emitWithFilename(this: *FSWatcher, file_name: JSC.JSValue, comptime eventType: EventType) void { + pub fn emitWithFilename(this: *FSWatcher, file_name: jsc.JSValue, comptime eventType: EventType) void { const js_this = this.js_this; if (js_this == .zero) return; const listener = js.listenerGetCached(js_this) orelse return; @@ -510,12 +510,12 @@ pub const FSWatcher = struct { if (js_this == .zero) return; const listener = js.listenerGetCached(js_this) orelse return; const globalObject = this.globalThis; - var filename: JSC.JSValue = .js_undefined; + var filename: jsc.JSValue = .js_undefined; if (file_name.len > 0) { if (this.encoding == .buffer) - filename = JSC.ArrayBuffer.createBuffer(globalObject, file_name) catch return // TODO: properly propagate exception upwards + filename = jsc.ArrayBuffer.createBuffer(globalObject, file_name) catch return // TODO: properly propagate exception upwards else if (this.encoding == .utf8) { - filename = JSC.ZigString.fromUTF8(file_name).toJS(globalObject); + filename = jsc.ZigString.fromUTF8(file_name).toJS(globalObject); } else { // convert to desired encoding filename = Encoder.toString(file_name, globalObject, this.encoding); @@ -525,8 +525,8 @@ pub const FSWatcher = struct { emitJS(listener, globalObject, filename, event_type); } - fn emitJS(listener: JSC.JSValue, globalObject: *JSC.JSGlobalObject, filename: JSC.JSValue, comptime event_type: EventType) void { - var args = [_]JSC.JSValue{ + fn emitJS(listener: jsc.JSValue, globalObject: *jsc.JSGlobalObject, filename: jsc.JSValue, comptime event_type: EventType) void { + var args = [_]jsc.JSValue{ event_type.toJS(globalObject), filename, }; @@ -537,7 +537,7 @@ pub const FSWatcher = struct { ) catch |err| globalObject.reportActiveExceptionAsUnhandled(err); } - pub fn doRef(this: *FSWatcher, _: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!JSC.JSValue { + pub fn doRef(this: *FSWatcher, _: *jsc.JSGlobalObject, _: *jsc.CallFrame) bun.JSError!jsc.JSValue { if (!this.closed and !this.persistent) { this.persistent = true; this.poll_ref.ref(this.ctx); @@ -545,7 +545,7 @@ pub const FSWatcher = struct { return .js_undefined; } - pub fn doUnref(this: *FSWatcher, _: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!JSC.JSValue { + pub fn doUnref(this: *FSWatcher, _: *jsc.JSGlobalObject, _: *jsc.CallFrame) bun.JSError!jsc.JSValue { if (this.persistent) { this.persistent = false; this.poll_ref.unref(this.ctx); @@ -553,8 +553,8 @@ pub const FSWatcher = struct { return .js_undefined; } - pub fn hasRef(this: *FSWatcher, _: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!JSC.JSValue { - return JSC.JSValue.jsBoolean(this.persistent); + pub fn hasRef(this: *FSWatcher, _: *jsc.JSGlobalObject, _: *jsc.CallFrame) bun.JSError!jsc.JSValue { + return jsc.JSValue.jsBoolean(this.persistent); } // this can be called from Watcher Thread or JS Context Thread @@ -621,12 +621,12 @@ pub const FSWatcher = struct { this.js_this = .zero; } - pub fn doClose(this: *FSWatcher, _: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!JSC.JSValue { + pub fn doClose(this: *FSWatcher, _: *jsc.JSGlobalObject, _: *jsc.CallFrame) bun.JSError!jsc.JSValue { this.close(); return .js_undefined; } - pub fn init(args: Arguments) bun.JSC.Maybe(*FSWatcher) { + pub fn init(args: Arguments) bun.jsc.Maybe(*FSWatcher) { const joined_buf = bun.path_buffer_pool.get(); defer bun.path_buffer_pool.put(joined_buf); const file_path: [:0]const u8 = brk: { @@ -695,6 +695,8 @@ pub const FSWatcher = struct { } }; +const string = []const u8; + const Path = @import("../../resolver/resolve_path.zig"); const std = @import("std"); @@ -703,12 +705,11 @@ const Async = bun.Async; const Environment = bun.Environment; const Mutex = bun.Mutex; const Output = bun.Output; -const string = bun.string; const webcore = bun.webcore; -const JSC = bun.JSC; -const EventLoop = JSC.EventLoop; -const VirtualMachine = JSC.VirtualMachine; -const ArgumentsSlice = JSC.CallFrame.ArgumentsSlice; -const Encoder = JSC.WebCore.encoding; -const PathLike = JSC.Node.PathLike; +const jsc = bun.jsc; +const EventLoop = jsc.EventLoop; +const VirtualMachine = jsc.VirtualMachine; +const ArgumentsSlice = jsc.CallFrame.ArgumentsSlice; +const Encoder = jsc.WebCore.encoding; +const PathLike = jsc.Node.PathLike; diff --git a/src/bun.js/node/node_http_binding.zig b/src/bun.js/node/node_http_binding.zig index 57f8fcbf91..8daa967a14 100644 --- a/src/bun.js/node/node_http_binding.zig +++ b/src/bun.js/node/node_http_binding.zig @@ -1,4 +1,4 @@ -pub fn getBunServerAllClosedPromise(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { +pub fn getBunServerAllClosedPromise(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const arguments = callframe.arguments_old(1).slice(); if (arguments.len < 1) { return globalThis.throwNotEnoughArguments("getBunServerAllClosePromise", 1, arguments.len); @@ -7,10 +7,10 @@ pub fn getBunServerAllClosedPromise(globalThis: *JSC.JSGlobalObject, callframe: const value = arguments[0]; inline for ([_]type{ - JSC.API.HTTPServer, - JSC.API.HTTPSServer, - JSC.API.DebugHTTPServer, - JSC.API.DebugHTTPSServer, + jsc.API.HTTPServer, + jsc.API.HTTPSServer, + jsc.API.DebugHTTPServer, + jsc.API.DebugHTTPSServer, }) |Server| { if (value.as(Server)) |server| { return server.getAllClosedPromise(globalThis); @@ -20,13 +20,13 @@ pub fn getBunServerAllClosedPromise(globalThis: *JSC.JSGlobalObject, callframe: return globalThis.throwInvalidArgumentTypeValue("server", "bun.Server", value); } -pub fn getMaxHTTPHeaderSize(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { +pub fn getMaxHTTPHeaderSize(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { _ = globalThis; // autofix _ = callframe; // autofix - return JSC.JSValue.jsNumber(bun.http.max_http_header_size); + return jsc.JSValue.jsNumber(bun.http.max_http_header_size); } -pub fn setMaxHTTPHeaderSize(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { +pub fn setMaxHTTPHeaderSize(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const arguments = callframe.arguments_old(1).slice(); if (arguments.len < 1) { return globalThis.throwNotEnoughArguments("setMaxHTTPHeaderSize", 1, arguments.len); @@ -37,8 +37,8 @@ pub fn setMaxHTTPHeaderSize(globalThis: *JSC.JSGlobalObject, callframe: *JSC.Cal return globalThis.throwInvalidArgumentTypeValue("maxHeaderSize", "non-negative integer", value); } bun.http.max_http_header_size = @intCast(num); - return JSC.JSValue.jsNumber(bun.http.max_http_header_size); + return jsc.JSValue.jsNumber(bun.http.max_http_header_size); } const bun = @import("bun"); -const JSC = bun.JSC; +const jsc = bun.jsc; diff --git a/src/bun.js/node/node_net_binding.zig b/src/bun.js/node/node_net_binding.zig index b91e8ca0fc..0e5ff8478b 100644 --- a/src/bun.js/node/node_net_binding.zig +++ b/src/bun.js/node/node_net_binding.zig @@ -3,19 +3,19 @@ pub var autoSelectFamilyDefault: bool = true; -pub fn getDefaultAutoSelectFamily(global: *JSC.JSGlobalObject) JSC.JSValue { - return JSC.JSFunction.create(global, "getDefaultAutoSelectFamily", (struct { - fn getter(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { +pub fn getDefaultAutoSelectFamily(global: *jsc.JSGlobalObject) jsc.JSValue { + return jsc.JSFunction.create(global, "getDefaultAutoSelectFamily", (struct { + fn getter(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { _ = globalThis; _ = callframe; - return JSC.jsBoolean(autoSelectFamilyDefault); + return jsc.jsBoolean(autoSelectFamilyDefault); } }).getter, 0, .{}); } -pub fn setDefaultAutoSelectFamily(global: *JSC.JSGlobalObject) JSC.JSValue { - return JSC.JSFunction.create(global, "setDefaultAutoSelectFamily", (struct { - fn setter(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { +pub fn setDefaultAutoSelectFamily(global: *jsc.JSGlobalObject) jsc.JSValue { + return jsc.JSFunction.create(global, "setDefaultAutoSelectFamily", (struct { + fn setter(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const arguments = callframe.arguments_old(1); if (arguments.len < 1) { return globalThis.throw("missing argument", .{}); @@ -26,7 +26,7 @@ pub fn setDefaultAutoSelectFamily(global: *JSC.JSGlobalObject) JSC.JSValue { } const value = arg.toBoolean(); autoSelectFamilyDefault = value; - return JSC.jsBoolean(value); + return jsc.jsBoolean(value); } }).setter, 1, .{}); } @@ -40,19 +40,19 @@ pub fn setDefaultAutoSelectFamily(global: *JSC.JSGlobalObject) JSC.JSValue { /// need to store it as a field in the VirtualMachine instead of in a `threadlocal`. pub threadlocal var autoSelectFamilyAttemptTimeoutDefault: u32 = 250; -pub fn getDefaultAutoSelectFamilyAttemptTimeout(global: *JSC.JSGlobalObject) JSC.JSValue { - return JSC.JSFunction.create(global, "getDefaultAutoSelectFamilyAttemptTimeout", (struct { - fn getter(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { +pub fn getDefaultAutoSelectFamilyAttemptTimeout(global: *jsc.JSGlobalObject) jsc.JSValue { + return jsc.JSFunction.create(global, "getDefaultAutoSelectFamilyAttemptTimeout", (struct { + fn getter(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { _ = globalThis; _ = callframe; - return JSC.jsNumber(autoSelectFamilyAttemptTimeoutDefault); + return jsc.jsNumber(autoSelectFamilyAttemptTimeoutDefault); } }).getter, 0, .{}); } -pub fn setDefaultAutoSelectFamilyAttemptTimeout(global: *JSC.JSGlobalObject) JSC.JSValue { - return JSC.JSFunction.create(global, "setDefaultAutoSelectFamilyAttemptTimeout", (struct { - fn setter(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { +pub fn setDefaultAutoSelectFamilyAttemptTimeout(global: *jsc.JSGlobalObject) jsc.JSValue { + return jsc.JSFunction.create(global, "setDefaultAutoSelectFamilyAttemptTimeout", (struct { + fn setter(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const arguments = callframe.arguments_old(1); if (arguments.len < 1) { return globalThis.throw("missing argument", .{}); @@ -61,16 +61,16 @@ pub fn setDefaultAutoSelectFamilyAttemptTimeout(global: *JSC.JSGlobalObject) JSC var value = try validators.validateInt32(globalThis, arg, "value", .{}, 1, null); if (value < 10) value = 10; autoSelectFamilyAttemptTimeoutDefault = @intCast(value); - return JSC.jsNumber(value); + return jsc.jsNumber(value); } }).setter, 1, .{}); } -pub const SocketAddress = bun.JSC.Codegen.JSSocketAddress.getConstructor; +pub const SocketAddress = bun.jsc.Codegen.JSSocketAddress.getConstructor; -pub const BlockList = JSC.Codegen.JSBlockList.getConstructor; +pub const BlockList = jsc.Codegen.JSBlockList.getConstructor; -pub fn newDetachedSocket(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { +pub fn newDetachedSocket(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const args = callframe.argumentsAsArray(1); const is_ssl = args[0].toBoolean(); @@ -95,7 +95,7 @@ pub fn newDetachedSocket(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFr } } -pub fn doConnect(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { +pub fn doConnect(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const prev, const opts = callframe.argumentsAsArray(2); const maybe_tcp = prev.as(bun.api.TCPSocket); const maybe_tls = prev.as(bun.api.TLSSocket); @@ -105,4 +105,4 @@ pub fn doConnect(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun const validators = @import("./util/validators.zig"); const bun = @import("bun"); -const JSC = bun.JSC; +const jsc = bun.jsc; diff --git a/src/bun.js/node/node_os.zig b/src/bun.js/node/node_os.zig index 0fb5f65ca5..4ba5acd9d4 100644 --- a/src/bun.js/node/node_os.zig +++ b/src/bun.js/node/node_os.zig @@ -1,5 +1,5 @@ -pub fn createNodeOsBinding(global: *JSC.JSGlobalObject) bun.JSError!JSC.JSValue { - return (try JSC.JSObject.create(.{ +pub fn createNodeOsBinding(global: *jsc.JSGlobalObject) bun.JSError!jsc.JSValue { + return (try jsc.JSObject.create(.{ .cpus = gen.createCpusCallback(global), .freemem = gen.createFreememCallback(global), .getPriority = gen.createGetPriorityCallback(global), @@ -23,17 +23,17 @@ const CPUTimes = struct { idle: u64 = 0, irq: u64 = 0, - pub fn toValue(self: CPUTimes, globalThis: *JSC.JSGlobalObject) JSC.JSValue { + pub fn toValue(self: CPUTimes, globalThis: *jsc.JSGlobalObject) jsc.JSValue { const fields = comptime std.meta.fieldNames(CPUTimes); - const ret = JSC.JSValue.createEmptyObject(globalThis, fields.len); + const ret = jsc.JSValue.createEmptyObject(globalThis, fields.len); inline for (fields) |fieldName| { - ret.put(globalThis, JSC.ZigString.static(fieldName), JSC.JSValue.jsNumberFromUint64(@field(self, fieldName))); + ret.put(globalThis, jsc.ZigString.static(fieldName), jsc.JSValue.jsNumberFromUint64(@field(self, fieldName))); } return ret; } }; -pub fn cpus(global: *JSC.JSGlobalObject) bun.JSError!JSC.JSValue { +pub fn cpus(global: *jsc.JSGlobalObject) bun.JSError!jsc.JSValue { const cpusImpl = switch (Environment.os) { .linux => cpusImplLinux, .mac => cpusImplDarwin, @@ -42,17 +42,17 @@ pub fn cpus(global: *JSC.JSGlobalObject) bun.JSError!JSC.JSValue { }; return cpusImpl(global) catch { - const err = JSC.SystemError{ + const err = jsc.SystemError{ .message = bun.String.static("Failed to get CPU information"), - .code = bun.String.static(@tagName(JSC.Node.ErrorCode.ERR_SYSTEM_ERROR)), + .code = bun.String.static(@tagName(jsc.Node.ErrorCode.ERR_SYSTEM_ERROR)), }; return global.throwValue(err.toErrorInstance(global)); }; } -fn cpusImplLinux(globalThis: *JSC.JSGlobalObject) !JSC.JSValue { +fn cpusImplLinux(globalThis: *jsc.JSGlobalObject) !jsc.JSValue { // Create the return array - const values = try JSC.JSValue.createEmptyArray(globalThis, 0); + const values = try jsc.JSValue.createEmptyArray(globalThis, 0); var num_cpus: u32 = 0; var stack_fallback = std.heap.stackFallback(1024 * 8, bun.default_allocator); @@ -92,8 +92,8 @@ fn cpusImplLinux(globalThis: *JSC.JSGlobalObject) !JSC.JSValue { times.irq = scale * try std.fmt.parseInt(u64, toks.next() orelse return error.eol, 10); // Actually create the JS object representing the CPU - const cpu = JSC.JSValue.createEmptyObject(globalThis, 3); - cpu.put(globalThis, JSC.ZigString.static("times"), times.toValue(globalThis)); + const cpu = jsc.JSValue.createEmptyObject(globalThis, 3); + cpu.put(globalThis, jsc.ZigString.static("times"), times.toValue(globalThis)); try values.putIndex(globalThis, num_cpus, cpu); num_cpus += 1; @@ -119,7 +119,7 @@ fn cpusImplLinux(globalThis: *JSC.JSGlobalObject) !JSC.JSValue { if (strings.hasPrefixComptime(line, key_processor)) { if (!has_model_name) { const cpu = try values.getIndex(globalThis, cpu_index); - cpu.put(globalThis, JSC.ZigString.static("model"), JSC.ZigString.static("unknown").withEncoding().toJS(globalThis)); + cpu.put(globalThis, jsc.ZigString.static("model"), jsc.ZigString.static("unknown").withEncoding().toJS(globalThis)); } // If this line starts a new processor, parse the index from the line const digits = std.mem.trim(u8, line[key_processor.len..], " \t\n"); @@ -130,19 +130,19 @@ fn cpusImplLinux(globalThis: *JSC.JSGlobalObject) !JSC.JSValue { // If this is the model name, extract it and store on the current cpu const model_name = line[key_model_name.len..]; const cpu = try values.getIndex(globalThis, cpu_index); - cpu.put(globalThis, JSC.ZigString.static("model"), JSC.ZigString.init(model_name).withEncoding().toJS(globalThis)); + cpu.put(globalThis, jsc.ZigString.static("model"), jsc.ZigString.init(model_name).withEncoding().toJS(globalThis)); has_model_name = true; } } if (!has_model_name) { const cpu = try values.getIndex(globalThis, cpu_index); - cpu.put(globalThis, JSC.ZigString.static("model"), JSC.ZigString.static("unknown").withEncoding().toJS(globalThis)); + cpu.put(globalThis, jsc.ZigString.static("model"), jsc.ZigString.static("unknown").withEncoding().toJS(globalThis)); } } else |_| { // Initialize model name to "unknown" var it = try values.arrayIterator(globalThis); while (try it.next()) |cpu| { - cpu.put(globalThis, JSC.ZigString.static("model"), JSC.ZigString.static("unknown").withEncoding().toJS(globalThis)); + cpu.put(globalThis, jsc.ZigString.static("model"), jsc.ZigString.static("unknown").withEncoding().toJS(globalThis)); } } @@ -162,10 +162,10 @@ fn cpusImplLinux(globalThis: *JSC.JSGlobalObject) !JSC.JSValue { const digits = std.mem.trim(u8, contents, " \n"); const speed = (std.fmt.parseInt(u64, digits, 10) catch 0) / 1000; - cpu.put(globalThis, JSC.ZigString.static("speed"), JSC.JSValue.jsNumber(speed)); + cpu.put(globalThis, jsc.ZigString.static("speed"), jsc.JSValue.jsNumber(speed)); } else |_| { // Initialize CPU speed to 0 - cpu.put(globalThis, JSC.ZigString.static("speed"), JSC.JSValue.jsNumber(0)); + cpu.put(globalThis, jsc.ZigString.static("speed"), jsc.JSValue.jsNumber(0)); } } @@ -173,7 +173,7 @@ fn cpusImplLinux(globalThis: *JSC.JSGlobalObject) !JSC.JSValue { } extern fn bun_sysconf__SC_CLK_TCK() isize; -fn cpusImplDarwin(globalThis: *JSC.JSGlobalObject) !JSC.JSValue { +fn cpusImplDarwin(globalThis: *jsc.JSGlobalObject) !jsc.JSValue { // Fetch the CPU info structure var num_cpus: c.natural_t = 0; var info: [*]bun.c.processor_cpu_load_info = undefined; @@ -206,7 +206,7 @@ fn cpusImplDarwin(globalThis: *JSC.JSGlobalObject) !JSC.JSValue { // NOTE: sysctlbyname doesn't update len if it was large enough, so we // still have to find the null terminator. All cpus can share the same // model name. - const model_name = JSC.ZigString.init(std.mem.sliceTo(&model_name_buf, 0)).withEncoding().toJS(globalThis); + const model_name = jsc.ZigString.init(std.mem.sliceTo(&model_name_buf, 0)).withEncoding().toJS(globalThis); // Get CPU speed var speed: u64 = 0; @@ -224,7 +224,7 @@ fn cpusImplDarwin(globalThis: *JSC.JSGlobalObject) !JSC.JSValue { const multiplier = 1000 / @as(u64, @intCast(ticks)); // Set up each CPU value in the return - const values = try JSC.JSValue.createEmptyArray(globalThis, @as(u32, @intCast(num_cpus))); + const values = try jsc.JSValue.createEmptyArray(globalThis, @as(u32, @intCast(num_cpus))); var cpu_index: u32 = 0; while (cpu_index < num_cpus) : (cpu_index += 1) { const times = CPUTimes{ @@ -235,17 +235,17 @@ fn cpusImplDarwin(globalThis: *JSC.JSGlobalObject) !JSC.JSValue { .irq = 0, // not available }; - const cpu = JSC.JSValue.createEmptyObject(globalThis, 3); - cpu.put(globalThis, JSC.ZigString.static("speed"), JSC.JSValue.jsNumber(speed / 1_000_000)); - cpu.put(globalThis, JSC.ZigString.static("model"), model_name); - cpu.put(globalThis, JSC.ZigString.static("times"), times.toValue(globalThis)); + const cpu = jsc.JSValue.createEmptyObject(globalThis, 3); + cpu.put(globalThis, jsc.ZigString.static("speed"), jsc.JSValue.jsNumber(speed / 1_000_000)); + cpu.put(globalThis, jsc.ZigString.static("model"), model_name); + cpu.put(globalThis, jsc.ZigString.static("times"), times.toValue(globalThis)); try values.putIndex(globalThis, cpu_index, cpu); } return values; } -pub fn cpusImplWindows(globalThis: *JSC.JSGlobalObject) !JSC.JSValue { +pub fn cpusImplWindows(globalThis: *jsc.JSGlobalObject) !jsc.JSValue { var cpu_infos: [*]libuv.uv_cpu_info_t = undefined; var count: c_int = undefined; const err = libuv.uv_cpu_info(&cpu_infos, &count); @@ -254,7 +254,7 @@ pub fn cpusImplWindows(globalThis: *JSC.JSGlobalObject) !JSC.JSValue { } defer libuv.uv_free_cpu_info(cpu_infos, count); - const values = try JSC.JSValue.createEmptyArray(globalThis, @intCast(count)); + const values = try jsc.JSValue.createEmptyArray(globalThis, @intCast(count)); for (cpu_infos[0..@intCast(count)], 0..@intCast(count)) |cpu_info, i| { const times = CPUTimes{ @@ -265,10 +265,10 @@ pub fn cpusImplWindows(globalThis: *JSC.JSGlobalObject) !JSC.JSValue { .irq = cpu_info.cpu_times.irq, }; - const cpu = JSC.JSValue.createEmptyObject(globalThis, 3); - cpu.put(globalThis, JSC.ZigString.static("model"), JSC.ZigString.init(bun.span(cpu_info.model)).withEncoding().toJS(globalThis)); - cpu.put(globalThis, JSC.ZigString.static("speed"), JSC.JSValue.jsNumber(cpu_info.speed)); - cpu.put(globalThis, JSC.ZigString.static("times"), times.toValue(globalThis)); + const cpu = jsc.JSValue.createEmptyObject(globalThis, 3); + cpu.put(globalThis, jsc.ZigString.static("model"), jsc.ZigString.init(bun.span(cpu_info.model)).withEncoding().toJS(globalThis)); + cpu.put(globalThis, jsc.ZigString.static("speed"), jsc.JSValue.jsNumber(cpu_info.speed)); + cpu.put(globalThis, jsc.ZigString.static("times"), times.toValue(globalThis)); try values.putIndex(globalThis, @intCast(i), cpu); } @@ -284,10 +284,10 @@ pub fn freemem() u64 { } extern fn get_process_priority(pid: i32) i32; -pub fn getPriority(global: *JSC.JSGlobalObject, pid: i32) bun.JSError!i32 { +pub fn getPriority(global: *jsc.JSGlobalObject, pid: i32) bun.JSError!i32 { const result = get_process_priority(pid); if (result == std.math.maxInt(i32)) { - const err = JSC.SystemError{ + const err = jsc.SystemError{ .message = bun.String.static("no such process"), .code = bun.String.static("ESRCH"), .errno = comptime switch (bun.Environment.os) { @@ -301,7 +301,7 @@ pub fn getPriority(global: *JSC.JSGlobalObject, pid: i32) bun.JSError!i32 { return result; } -pub fn homedir(global: *JSC.JSGlobalObject) !bun.String { +pub fn homedir(global: *jsc.JSGlobalObject) !bun.String { // In Node.js, this is a wrapper around uv_os_homedir. if (Environment.isWindows) { var out: bun.PathBuffer = undefined; @@ -379,7 +379,7 @@ pub fn homedir(global: *JSC.JSGlobalObject) !bun.String { } } -pub fn hostname(global: *JSC.JSGlobalObject) bun.JSError!JSC.JSValue { +pub fn hostname(global: *jsc.JSGlobalObject) bun.JSError!jsc.JSValue { if (Environment.isWindows) { var name_buffer: [129:0]u16 = undefined; if (bun.windows.GetHostNameW(&name_buffer, name_buffer.len) == 0) { @@ -397,14 +397,14 @@ pub fn hostname(global: *JSC.JSGlobalObject) bun.JSError!JSC.JSValue { } } - return JSC.ZigString.init("unknown").withEncoding().toJS(global); + return jsc.ZigString.init("unknown").withEncoding().toJS(global); } else { var name_buffer: [bun.HOST_NAME_MAX]u8 = undefined; - return JSC.ZigString.init(std.posix.gethostname(&name_buffer) catch "unknown").withEncoding().toJS(global); + return jsc.ZigString.init(std.posix.gethostname(&name_buffer) catch "unknown").withEncoding().toJS(global); } } -pub fn loadavg(global: *JSC.JSGlobalObject) bun.JSError!JSC.JSValue { +pub fn loadavg(global: *jsc.JSGlobalObject) bun.JSError!jsc.JSValue { const result = switch (bun.Environment.os) { .mac => loadavg: { var avg: c.struct_loadavg = undefined; @@ -442,10 +442,10 @@ pub fn loadavg(global: *JSC.JSGlobalObject) bun.JSError!JSC.JSValue { .wasm => @compileError("TODO"), }; - return JSC.JSArray.create(global, &.{ - JSC.JSValue.jsNumber(result[0]), - JSC.JSValue.jsNumber(result[1]), - JSC.JSValue.jsNumber(result[2]), + return jsc.JSArray.create(global, &.{ + jsc.JSValue.jsNumber(result[0]), + jsc.JSValue.jsNumber(result[1]), + jsc.JSValue.jsNumber(result[2]), }); } @@ -455,12 +455,12 @@ pub const networkInterfaces = switch (Environment.os) { else => @compileError("Unsupported OS"), }; -fn networkInterfacesPosix(globalThis: *JSC.JSGlobalObject) bun.JSError!JSC.JSValue { +fn networkInterfacesPosix(globalThis: *jsc.JSGlobalObject) bun.JSError!jsc.JSValue { // getifaddrs sets a pointer to a linked list var interface_start: ?*c.ifaddrs = null; const rc = c.getifaddrs(&interface_start); if (rc != 0) { - const err = JSC.SystemError{ + const err = jsc.SystemError{ .message = bun.String.static("A system error occurred: getifaddrs returned an error"), .code = bun.String.static("ERR_SYSTEM_ERROR"), .errno = @intFromEnum(std.posix.errno(rc)), @@ -511,7 +511,7 @@ fn networkInterfacesPosix(globalThis: *JSC.JSGlobalObject) bun.JSError!JSC.JSVal num_inet_interfaces += 1; } - var ret = JSC.JSValue.createEmptyObject(globalThis, 8); + var ret = jsc.JSValue.createEmptyObject(globalThis, 8); // Second pass through, populate each interface object it = interface_start; @@ -522,7 +522,7 @@ fn networkInterfacesPosix(globalThis: *JSC.JSGlobalObject) bun.JSError!JSC.JSVal const addr = std.net.Address.initPosix(@alignCast(@as(*std.posix.sockaddr, @ptrCast(iface.ifa_addr)))); const netmask = std.net.Address.initPosix(@alignCast(@as(*std.posix.sockaddr, @ptrCast(iface.ifa_netmask)))); - var interface = JSC.JSValue.createEmptyObject(globalThis, 7); + var interface = jsc.JSValue.createEmptyObject(globalThis, 7); // address The assigned IPv4 or IPv6 address // cidr The assigned IPv4 or IPv6 address with the routing prefix in CIDR notation. If the netmask is invalid, this property is set to null. @@ -540,7 +540,7 @@ fn networkInterfacesPosix(globalThis: *JSC.JSGlobalObject) bun.JSError!JSC.JSVal // e.g. addr_str = "192.168.88.254", cidr_str = "192.168.88.254/24" var buf: [64]u8 = undefined; const addr_str = bun.fmt.formatIp(addr, &buf) catch unreachable; - var cidr = JSC.JSValue.null; + var cidr = jsc.JSValue.null; if (maybe_suffix) |suffix| { //NOTE addr_str might not start at buf[0] due to slicing in formatIp const start = @intFromPtr(addr_str.ptr) - @intFromPtr(&buf[0]); @@ -548,25 +548,25 @@ fn networkInterfacesPosix(globalThis: *JSC.JSGlobalObject) bun.JSError!JSC.JSVal const suffix_str = std.fmt.bufPrint(buf[start + addr_str.len ..], "/{}", .{suffix}) catch unreachable; // The full cidr value is the address + the suffix const cidr_str = buf[start .. start + addr_str.len + suffix_str.len]; - cidr = JSC.ZigString.init(cidr_str).withEncoding().toJS(globalThis); + cidr = jsc.ZigString.init(cidr_str).withEncoding().toJS(globalThis); } - interface.put(globalThis, JSC.ZigString.static("address"), JSC.ZigString.init(addr_str).withEncoding().toJS(globalThis)); - interface.put(globalThis, JSC.ZigString.static("cidr"), cidr); + interface.put(globalThis, jsc.ZigString.static("address"), jsc.ZigString.init(addr_str).withEncoding().toJS(globalThis)); + interface.put(globalThis, jsc.ZigString.static("cidr"), cidr); } // netmask The IPv4 or IPv6 network mask { var buf: [64]u8 = undefined; const str = bun.fmt.formatIp(netmask, &buf) catch unreachable; - interface.put(globalThis, JSC.ZigString.static("netmask"), JSC.ZigString.init(str).withEncoding().toJS(globalThis)); + interface.put(globalThis, jsc.ZigString.static("netmask"), jsc.ZigString.init(str).withEncoding().toJS(globalThis)); } // family Either IPv4 or IPv6 - interface.put(globalThis, JSC.ZigString.static("family"), (switch (addr.any.family) { - std.posix.AF.INET => JSC.ZigString.static("IPv4"), - std.posix.AF.INET6 => JSC.ZigString.static("IPv6"), - else => JSC.ZigString.static("unknown"), + interface.put(globalThis, jsc.ZigString.static("family"), (switch (addr.any.family) { + std.posix.AF.INET => jsc.ZigString.static("IPv4"), + std.posix.AF.INET6 => jsc.ZigString.static("IPv6"), + else => jsc.ZigString.static("unknown"), }).toJS(globalThis)); // mac The MAC address of the network interface @@ -598,26 +598,26 @@ fn networkInterfacesPosix(globalThis: *JSC.JSGlobalObject) bun.JSError!JSC.JSVal const addr_data = if (comptime Environment.isLinux) ll_addr.addr else if (comptime Environment.isMac) ll_addr.sdl_data[ll_addr.sdl_nlen..] else @compileError("unreachable"); if (addr_data.len < 6) { const mac = "00:00:00:00:00:00"; - interface.put(globalThis, JSC.ZigString.static("mac"), JSC.ZigString.init(mac).withEncoding().toJS(globalThis)); + interface.put(globalThis, jsc.ZigString.static("mac"), jsc.ZigString.init(mac).withEncoding().toJS(globalThis)); } else { const mac = std.fmt.bufPrint(&mac_buf, "{x:0>2}:{x:0>2}:{x:0>2}:{x:0>2}:{x:0>2}:{x:0>2}", .{ addr_data[0], addr_data[1], addr_data[2], addr_data[3], addr_data[4], addr_data[5], }) catch unreachable; - interface.put(globalThis, JSC.ZigString.static("mac"), JSC.ZigString.init(mac).withEncoding().toJS(globalThis)); + interface.put(globalThis, jsc.ZigString.static("mac"), jsc.ZigString.init(mac).withEncoding().toJS(globalThis)); } } else { const mac = "00:00:00:00:00:00"; - interface.put(globalThis, JSC.ZigString.static("mac"), JSC.ZigString.init(mac).withEncoding().toJS(globalThis)); + interface.put(globalThis, jsc.ZigString.static("mac"), jsc.ZigString.init(mac).withEncoding().toJS(globalThis)); } } // internal true if the network interface is a loopback or similar interface that is not remotely accessible; otherwise false - interface.put(globalThis, JSC.ZigString.static("internal"), JSC.JSValue.jsBoolean(helpers.isLoopback(iface))); + interface.put(globalThis, jsc.ZigString.static("internal"), jsc.JSValue.jsBoolean(helpers.isLoopback(iface))); // scopeid The numeric IPv6 scope ID (only specified when family is IPv6) if (addr.any.family == std.posix.AF.INET6) { - interface.put(globalThis, JSC.ZigString.static("scopeid"), JSC.JSValue.jsNumber(addr.in6.sa.scope_id)); + interface.put(globalThis, jsc.ZigString.static("scopeid"), jsc.JSValue.jsNumber(addr.in6.sa.scope_id)); } // Does this entry already exist? @@ -627,8 +627,8 @@ fn networkInterfacesPosix(globalThis: *JSC.JSGlobalObject) bun.JSError!JSC.JSVal try array.putIndex(globalThis, next_index, interface); } else { // Add it as an array with this interface as an element - const member_name = JSC.ZigString.init(interface_name); - var array = try JSC.JSValue.createEmptyArray(globalThis, 1); + const member_name = jsc.ZigString.init(interface_name); + var array = try jsc.JSValue.createEmptyArray(globalThis, 1); try array.putIndex(globalThis, 0, interface); ret.put(globalThis, &member_name, array); } @@ -637,12 +637,12 @@ fn networkInterfacesPosix(globalThis: *JSC.JSGlobalObject) bun.JSError!JSC.JSVal return ret; } -fn networkInterfacesWindows(globalThis: *JSC.JSGlobalObject) bun.JSError!JSC.JSValue { +fn networkInterfacesWindows(globalThis: *jsc.JSGlobalObject) bun.JSError!jsc.JSValue { var ifaces: [*]libuv.uv_interface_address_t = undefined; var count: c_int = undefined; const err = libuv.uv_interface_addresses(&ifaces, &count); if (err != 0) { - const sys_err = JSC.SystemError{ + const sys_err = jsc.SystemError{ .message = bun.String.static("uv_interface_addresses failed"), .code = bun.String.static("ERR_SYSTEM_ERROR"), //.info = info, @@ -653,18 +653,18 @@ fn networkInterfacesWindows(globalThis: *JSC.JSGlobalObject) bun.JSError!JSC.JSV } defer libuv.uv_free_interface_addresses(ifaces, count); - var ret = JSC.JSValue.createEmptyObject(globalThis, 8); + var ret = jsc.JSValue.createEmptyObject(globalThis, 8); // 65 comes from: https://stackoverflow.com/questions/39443413/why-is-inet6-addrstrlen-defined-as-46-in-c var ip_buf: [65]u8 = undefined; var mac_buf: [17]u8 = undefined; for (ifaces[0..@intCast(count)]) |iface| { - var interface = JSC.JSValue.createEmptyObject(globalThis, 7); + var interface = jsc.JSValue.createEmptyObject(globalThis, 7); // address The assigned IPv4 or IPv6 address // cidr The assigned IPv4 or IPv6 address with the routing prefix in CIDR notation. If the netmask is invalid, this property is set to null. - var cidr = JSC.JSValue.null; + var cidr = jsc.JSValue.null; { // Compute the CIDR suffix; returns null if the netmask cannot // be converted to a CIDR suffix @@ -689,10 +689,10 @@ fn networkInterfacesWindows(globalThis: *JSC.JSGlobalObject) bun.JSError!JSC.JSV const suffix_str = std.fmt.bufPrint(ip_buf[start + addr_str.len ..], "/{}", .{suffix}) catch unreachable; // The full cidr value is the address + the suffix const cidr_str = ip_buf[start .. start + addr_str.len + suffix_str.len]; - cidr = JSC.ZigString.init(cidr_str).withEncoding().toJS(globalThis); + cidr = jsc.ZigString.init(cidr_str).withEncoding().toJS(globalThis); } - interface.put(globalThis, JSC.ZigString.static("address"), JSC.ZigString.init(addr_str).withEncoding().toJS(globalThis)); + interface.put(globalThis, jsc.ZigString.static("address"), jsc.ZigString.init(addr_str).withEncoding().toJS(globalThis)); } // netmask @@ -702,13 +702,13 @@ fn networkInterfacesWindows(globalThis: *JSC.JSGlobalObject) bun.JSError!JSC.JSV std.net.Address.initPosix(@ptrCast(&iface.netmask.netmask4)), &ip_buf, ) catch unreachable; - interface.put(globalThis, JSC.ZigString.static("netmask"), JSC.ZigString.init(str).withEncoding().toJS(globalThis)); + interface.put(globalThis, jsc.ZigString.static("netmask"), jsc.ZigString.init(str).withEncoding().toJS(globalThis)); } // family - interface.put(globalThis, JSC.ZigString.static("family"), (switch (iface.address.address4.family) { - std.posix.AF.INET => JSC.ZigString.static("IPv4"), - std.posix.AF.INET6 => JSC.ZigString.static("IPv6"), - else => JSC.ZigString.static("unknown"), + interface.put(globalThis, jsc.ZigString.static("family"), (switch (iface.address.address4.family) { + std.posix.AF.INET => jsc.ZigString.static("IPv4"), + std.posix.AF.INET6 => jsc.ZigString.static("IPv6"), + else => jsc.ZigString.static("unknown"), }).toJS(globalThis)); // mac @@ -717,20 +717,20 @@ fn networkInterfacesWindows(globalThis: *JSC.JSGlobalObject) bun.JSError!JSC.JSV const mac = std.fmt.bufPrint(&mac_buf, "{x:0>2}:{x:0>2}:{x:0>2}:{x:0>2}:{x:0>2}:{x:0>2}", .{ phys[0], phys[1], phys[2], phys[3], phys[4], phys[5], }) catch unreachable; - interface.put(globalThis, JSC.ZigString.static("mac"), JSC.ZigString.init(mac).withEncoding().toJS(globalThis)); + interface.put(globalThis, jsc.ZigString.static("mac"), jsc.ZigString.init(mac).withEncoding().toJS(globalThis)); } // internal { - interface.put(globalThis, JSC.ZigString.static("internal"), JSC.JSValue.jsBoolean(iface.is_internal != 0)); + interface.put(globalThis, jsc.ZigString.static("internal"), jsc.JSValue.jsBoolean(iface.is_internal != 0)); } // cidr. this is here to keep ordering consistent with the node implementation - interface.put(globalThis, JSC.ZigString.static("cidr"), cidr); + interface.put(globalThis, jsc.ZigString.static("cidr"), cidr); // scopeid if (iface.address.address4.family == std.posix.AF.INET6) { - interface.put(globalThis, JSC.ZigString.static("scopeid"), JSC.JSValue.jsNumber(iface.address.address6.scope_id)); + interface.put(globalThis, jsc.ZigString.static("scopeid"), jsc.JSValue.jsNumber(iface.address.address6.scope_id)); } // Does this entry already exist? @@ -741,8 +741,8 @@ fn networkInterfacesWindows(globalThis: *JSC.JSGlobalObject) bun.JSError!JSC.JSV try array.putIndex(globalThis, next_index, interface); } else { // Add it as an array with this interface as an element - const member_name = JSC.ZigString.init(interface_name); - var array = try JSC.JSValue.createEmptyArray(globalThis, 1); + const member_name = jsc.ZigString.init(interface_name); + var array = try jsc.JSValue.createEmptyArray(globalThis, 1); try array.putIndex(globalThis, 0, interface); ret.put(globalThis, &member_name, array); } @@ -806,11 +806,11 @@ pub fn setProcessPriorityImpl(pid: i32, priority: i32) std.c.E { return @enumFromInt(@intFromEnum(errcode)); } -pub fn setPriority1(global: *JSC.JSGlobalObject, pid: i32, priority: i32) !void { +pub fn setPriority1(global: *jsc.JSGlobalObject, pid: i32, priority: i32) !void { const errcode = setProcessPriorityImpl(pid, priority); switch (errcode) { .SRCH => { - const err = JSC.SystemError{ + const err = jsc.SystemError{ .message = bun.String.static("no such process"), .code = bun.String.static("ESRCH"), .errno = comptime switch (bun.Environment.os) { @@ -822,7 +822,7 @@ pub fn setPriority1(global: *JSC.JSGlobalObject, pid: i32, priority: i32) !void return global.throwValue(err.toErrorInstanceWithInfoObject(global)); }, .ACCES => { - const err = JSC.SystemError{ + const err = jsc.SystemError{ .message = bun.String.static("permission denied"), .code = bun.String.static("EACCES"), .errno = comptime switch (bun.Environment.os) { @@ -834,7 +834,7 @@ pub fn setPriority1(global: *JSC.JSGlobalObject, pid: i32, priority: i32) !void return global.throwValue(err.toErrorInstanceWithInfoObject(global)); }, .PERM => { - const err = JSC.SystemError{ + const err = jsc.SystemError{ .message = bun.String.static("operation not permitted"), .code = bun.String.static("EPERM"), .errno = comptime switch (bun.Environment.os) { @@ -851,7 +851,7 @@ pub fn setPriority1(global: *JSC.JSGlobalObject, pid: i32, priority: i32) !void } } -pub fn setPriority2(global: *JSC.JSGlobalObject, priority: i32) !void { +pub fn setPriority2(global: *jsc.JSGlobalObject, priority: i32) !void { return setPriority1(global, 0, priority); } @@ -885,13 +885,13 @@ pub fn totalmem() u64 { } } -pub fn uptime(global: *JSC.JSGlobalObject) bun.JSError!f64 { +pub fn uptime(global: *jsc.JSGlobalObject) bun.JSError!f64 { switch (Environment.os) { .windows => { var uptime_value: f64 = undefined; const err = libuv.uv_uptime(&uptime_value); if (err != 0) { - const sys_err = JSC.SystemError{ + const sys_err = jsc.SystemError{ .message = bun.String.static("failed to get system uptime"), .code = bun.String.static("ERR_SYSTEM_ERROR"), .errno = err, @@ -927,28 +927,28 @@ pub fn uptime(global: *JSC.JSGlobalObject) bun.JSError!f64 { } } -pub fn userInfo(globalThis: *JSC.JSGlobalObject, options: gen.UserInfoOptions) bun.JSError!JSC.JSValue { +pub fn userInfo(globalThis: *jsc.JSGlobalObject, options: gen.UserInfoOptions) bun.JSError!jsc.JSValue { _ = options; // TODO: - const result = JSC.JSValue.createEmptyObject(globalThis, 5); + const result = jsc.JSValue.createEmptyObject(globalThis, 5); const home = try homedir(globalThis); defer home.deref(); - result.put(globalThis, JSC.ZigString.static("homedir"), home.toJS(globalThis)); + result.put(globalThis, jsc.ZigString.static("homedir"), home.toJS(globalThis)); if (comptime Environment.isWindows) { - result.put(globalThis, JSC.ZigString.static("username"), JSC.ZigString.init(bun.getenvZ("USERNAME") orelse "unknown").withEncoding().toJS(globalThis)); - result.put(globalThis, JSC.ZigString.static("uid"), JSC.JSValue.jsNumber(-1)); - result.put(globalThis, JSC.ZigString.static("gid"), JSC.JSValue.jsNumber(-1)); - result.put(globalThis, JSC.ZigString.static("shell"), JSC.JSValue.jsNull()); + result.put(globalThis, jsc.ZigString.static("username"), jsc.ZigString.init(bun.getenvZ("USERNAME") orelse "unknown").withEncoding().toJS(globalThis)); + result.put(globalThis, jsc.ZigString.static("uid"), jsc.JSValue.jsNumber(-1)); + result.put(globalThis, jsc.ZigString.static("gid"), jsc.JSValue.jsNumber(-1)); + result.put(globalThis, jsc.ZigString.static("shell"), jsc.JSValue.jsNull()); } else { const username = bun.getenvZ("USER") orelse "unknown"; - result.put(globalThis, JSC.ZigString.static("username"), JSC.ZigString.init(username).withEncoding().toJS(globalThis)); - result.put(globalThis, JSC.ZigString.static("shell"), JSC.ZigString.init(bun.getenvZ("SHELL") orelse "unknown").withEncoding().toJS(globalThis)); - result.put(globalThis, JSC.ZigString.static("uid"), JSC.JSValue.jsNumber(c.getuid())); - result.put(globalThis, JSC.ZigString.static("gid"), JSC.JSValue.jsNumber(c.getgid())); + result.put(globalThis, jsc.ZigString.static("username"), jsc.ZigString.init(username).withEncoding().toJS(globalThis)); + result.put(globalThis, jsc.ZigString.static("shell"), jsc.ZigString.init(bun.getenvZ("SHELL") orelse "unknown").withEncoding().toJS(globalThis)); + result.put(globalThis, jsc.ZigString.static("uid"), jsc.JSValue.jsNumber(c.getuid())); + result.put(globalThis, jsc.ZigString.static("gid"), jsc.JSValue.jsNumber(c.getgid())); } return result; @@ -1011,13 +1011,14 @@ fn netmaskToCIDRSuffix(mask: anytype) ?u8 { return first_zero; } +const string = []const u8; + const std = @import("std"); const bun = @import("bun"); const Environment = bun.Environment; -const JSC = bun.JSC; const c = bun.c; -const string = bun.string; +const jsc = bun.jsc; const strings = bun.strings; const sys = bun.sys; const gen = bun.gen.node_os; diff --git a/src/bun.js/node/node_process.zig b/src/bun.js/node/node_process.zig index 1efa9f1948..3ff6c848a2 100644 --- a/src/bun.js/node/node_process.zig +++ b/src/bun.js/node/node_process.zig @@ -17,7 +17,7 @@ var title_mutex = bun.Mutex{}; pub fn getTitle(_: *JSGlobalObject, title: *ZigString) callconv(.C) void { title_mutex.lock(); defer title_mutex.unlock(); - const str = bun.CLI.Bun__Node__ProcessTitle; + const str = bun.cli.Bun__Node__ProcessTitle; title.* = ZigString.init(str orelse "bun"); } @@ -25,25 +25,25 @@ pub fn getTitle(_: *JSGlobalObject, title: *ZigString) callconv(.C) void { pub fn setTitle(globalObject: *JSGlobalObject, newvalue: *ZigString) callconv(.C) JSValue { title_mutex.lock(); defer title_mutex.unlock(); - if (bun.CLI.Bun__Node__ProcessTitle) |_| bun.default_allocator.free(bun.CLI.Bun__Node__ProcessTitle.?); - bun.CLI.Bun__Node__ProcessTitle = newvalue.dupe(bun.default_allocator) catch bun.outOfMemory(); + if (bun.cli.Bun__Node__ProcessTitle) |_| bun.default_allocator.free(bun.cli.Bun__Node__ProcessTitle.?); + bun.cli.Bun__Node__ProcessTitle = newvalue.dupe(bun.default_allocator) catch bun.outOfMemory(); return newvalue.toJS(globalObject); } -pub fn createArgv0(globalObject: *JSC.JSGlobalObject) callconv(.C) JSC.JSValue { - return JSC.ZigString.fromUTF8(bun.argv[0]).toJS(globalObject); +pub fn createArgv0(globalObject: *jsc.JSGlobalObject) callconv(.C) jsc.JSValue { + return jsc.ZigString.fromUTF8(bun.argv[0]).toJS(globalObject); } -pub fn getExecPath(globalObject: *JSC.JSGlobalObject) callconv(.C) JSC.JSValue { +pub fn getExecPath(globalObject: *jsc.JSGlobalObject) callconv(.C) jsc.JSValue { const out = bun.selfExePath() catch { // if for any reason we are unable to get the executable path, we just return argv[0] return createArgv0(globalObject); }; - return JSC.ZigString.fromUTF8(out).toJS(globalObject); + return jsc.ZigString.fromUTF8(out).toJS(globalObject); } -fn createExecArgv(globalObject: *JSC.JSGlobalObject) bun.JSError!JSC.JSValue { +fn createExecArgv(globalObject: *jsc.JSGlobalObject) bun.JSError!jsc.JSValue { var sfb = std.heap.stackFallback(4096, globalObject.allocator()); const temp_alloc = sfb.get(); const vm = globalObject.bunVM(); @@ -51,7 +51,7 @@ fn createExecArgv(globalObject: *JSC.JSGlobalObject) bun.JSError!JSC.JSValue { if (vm.worker) |worker| { // was explicitly overridden for the worker? if (worker.execArgv) |execArgv| { - const array = try JSC.JSValue.createEmptyArray(globalObject, execArgv.len); + const array = try jsc.JSValue.createEmptyArray(globalObject, execArgv.len); for (0..execArgv.len) |i| { try array.putIndex(globalObject, @intCast(i), bun.String.init(execArgv[i]).toJS(globalObject)); } @@ -84,7 +84,7 @@ fn createExecArgv(globalObject: *JSC.JSGlobalObject) bun.JSError!JSC.JSValue { // A set of execArgv args consume an extra argument, so we do not want to // confuse these with script names. const map = bun.ComptimeStringMap(void, comptime brk: { - const auto_params = bun.CLI.Arguments.auto_params; + const auto_params = bun.cli.Arguments.auto_params; const KV = struct { []const u8, void }; var entries: [auto_params.len]KV = undefined; var i = 0; @@ -118,12 +118,12 @@ fn createExecArgv(globalObject: *JSC.JSGlobalObject) bun.JSError!JSC.JSValue { return bun.String.toJSArray(globalObject, args.items); } -fn createArgv(globalObject: *JSC.JSGlobalObject) callconv(.C) JSC.JSValue { +fn createArgv(globalObject: *jsc.JSGlobalObject) callconv(.C) jsc.JSValue { const vm = globalObject.bunVM(); // Allocate up to 32 strings in stack var stack_fallback_allocator = std.heap.stackFallback( - 32 * @sizeOf(JSC.ZigString) + (bun.MAX_PATH_BYTES + 1) + 32, + 32 * @sizeOf(jsc.ZigString) + (bun.MAX_PATH_BYTES + 1) + 32, bun.default_allocator, ); const allocator = stack_fallback_allocator.get(); @@ -194,27 +194,27 @@ pub fn getExecArgv(global: *JSGlobalObject) callconv(.c) JSValue { return Bun__Process__getExecArgv(global); } -pub fn getEval(globalObject: *JSC.JSGlobalObject) callconv(.C) JSC.JSValue { +pub fn getEval(globalObject: *jsc.JSGlobalObject) callconv(.C) jsc.JSValue { const vm = globalObject.bunVM(); if (vm.module_loader.eval_source) |source| { - return JSC.ZigString.init(source.contents).toJS(globalObject); + return jsc.ZigString.init(source.contents).toJS(globalObject); } return .js_undefined; } -pub const getCwd = JSC.host_fn.wrap1(getCwd_); -fn getCwd_(globalObject: *JSC.JSGlobalObject) bun.JSError!JSC.JSValue { +pub const getCwd = jsc.host_fn.wrap1(getCwd_); +fn getCwd_(globalObject: *jsc.JSGlobalObject) bun.JSError!jsc.JSValue { var buf: bun.PathBuffer = undefined; switch (bun.api.node.path.getCwd(&buf)) { - .result => |r| return JSC.ZigString.init(r).withEncoding().toJS(globalObject), + .result => |r| return jsc.ZigString.init(r).withEncoding().toJS(globalObject), .err => |e| { return globalObject.throwValue(e.toJS(globalObject)); }, } } -pub const setCwd = JSC.host_fn.wrap2(setCwd_); -fn setCwd_(globalObject: *JSC.JSGlobalObject, to: *JSC.ZigString) bun.JSError!JSC.JSValue { +pub const setCwd = jsc.host_fn.wrap2(setCwd_); +fn setCwd_(globalObject: *jsc.JSGlobalObject, to: *jsc.ZigString) bun.JSError!jsc.JSValue { if (to.len == 0) { return globalObject.throwInvalidArguments("Expected path to be a non-empty string", .{}); } @@ -258,7 +258,7 @@ fn setCwd_(globalObject: *JSC.JSGlobalObject, to: *JSC.ZigString) bun.JSError!JS } // TODO(@190n) this may need to be noreturn -pub fn exit(globalObject: *JSC.JSGlobalObject, code: u8) callconv(.c) void { +pub fn exit(globalObject: *jsc.JSGlobalObject, code: u8) callconv(.c) void { var vm = globalObject.bunVM(); vm.exit_handler.exit_code = code; if (vm.worker) |worker| { @@ -342,7 +342,7 @@ const Environment = bun.Environment; const Syscall = bun.sys; const strings = bun.strings; -const JSC = bun.JSC; -const JSGlobalObject = JSC.JSGlobalObject; -const JSValue = JSC.JSValue; -const ZigString = JSC.ZigString; +const jsc = bun.jsc; +const JSGlobalObject = jsc.JSGlobalObject; +const JSValue = jsc.JSValue; +const ZigString = jsc.ZigString; diff --git a/src/bun.js/node/node_util_binding.zig b/src/bun.js/node/node_util_binding.zig index 324dbf0293..bbff581841 100644 --- a/src/bun.js/node/node_util_binding.zig +++ b/src/bun.js/node/node_util_binding.zig @@ -1,4 +1,4 @@ -pub fn internalErrorName(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { +pub fn internalErrorName(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const arguments = callframe.arguments_old(1).slice(); if (arguments.len < 1) { return globalThis.throwNotEnoughArguments("internalErrorName", 1, arguments.len); @@ -98,12 +98,12 @@ pub fn internalErrorName(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFr return fmtstring.transferToJS(globalThis); } -pub fn etimedoutErrorCode(_: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!JSC.JSValue { - return JSC.JSValue.jsNumberFromInt32(-bun.sys.UV_E.TIMEDOUT); +pub fn etimedoutErrorCode(_: *jsc.JSGlobalObject, _: *jsc.CallFrame) bun.JSError!jsc.JSValue { + return jsc.JSValue.jsNumberFromInt32(-bun.sys.UV_E.TIMEDOUT); } -pub fn enobufsErrorCode(_: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!JSC.JSValue { - return JSC.JSValue.jsNumberFromInt32(-bun.sys.UV_E.NOBUFS); +pub fn enobufsErrorCode(_: *jsc.JSGlobalObject, _: *jsc.CallFrame) bun.JSError!jsc.JSValue { + return jsc.JSValue.jsNumberFromInt32(-bun.sys.UV_E.NOBUFS); } /// `extractedSplitNewLines` for ASCII/Latin1 strings. Panics if passed a non-string. @@ -114,7 +114,7 @@ pub fn enobufsErrorCode(_: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!J /// const extractedNewLineRe = new RegExp("(?<=\\n)"); /// extractedSplitNewLines = value => RegExpPrototypeSymbolSplit(extractedNewLineRe, value); /// ``` -pub fn extractedSplitNewLinesFastPathStringsOnly(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { +pub fn extractedSplitNewLinesFastPathStringsOnly(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { bun.assert(callframe.argumentsCount() == 1); const value = callframe.argument(0); bun.assert(value.isString()); @@ -133,10 +133,10 @@ pub fn extractedSplitNewLinesFastPathStringsOnly(globalThis: *JSC.JSGlobalObject fn split( comptime encoding: bun.strings.EncodingNonAscii, - globalThis: *JSC.JSGlobalObject, + globalThis: *jsc.JSGlobalObject, allocator: Allocator, str: *const bun.String, -) bun.JSError!JSC.JSValue { +) bun.JSError!jsc.JSValue { var fallback = std.heap.stackFallback(1024, allocator); const alloc = fallback.get(); const Char = switch (encoding) { @@ -194,17 +194,17 @@ pub fn SplitNewlineIterator(comptime T: type) type { }; } -pub fn normalizeEncoding(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { +pub fn normalizeEncoding(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const input = callframe.argument(0); const str = try bun.String.fromJS(input, globalThis); bun.assert(str.tag != .Dead); defer str.deref(); - if (str.length() == 0) return JSC.Node.Encoding.utf8.toJS(globalThis); - if (str.inMapCaseInsensitive(JSC.Node.Encoding.map)) |enc| return enc.toJS(globalThis); + if (str.length() == 0) return jsc.Node.Encoding.utf8.toJS(globalThis); + if (str.inMapCaseInsensitive(jsc.Node.Encoding.map)) |enc| return enc.toJS(globalThis); return .js_undefined; } -pub fn parseEnv(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { +pub fn parseEnv(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const content = callframe.argument(0); try validators.validateString(globalThis, content, "content", .{}); @@ -218,20 +218,20 @@ pub fn parseEnv(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun. var p = envloader.Loader.init(&map, allocator); p.loadFromString(str.slice(), true, false); - var obj = JSC.JSValue.createEmptyObject(globalThis, map.map.count()); + var obj = jsc.JSValue.createEmptyObject(globalThis, map.map.count()); for (map.map.keys(), map.map.values()) |k, v| { - obj.put(globalThis, JSC.ZigString.initUTF8(k), try bun.String.createUTF8ForJS(globalThis, v.value)); + obj.put(globalThis, jsc.ZigString.initUTF8(k), try bun.String.createUTF8ForJS(globalThis, v.value)); } return obj; } +const string = []const u8; + +const bun = @import("bun"); const envloader = @import("../../env_loader.zig"); const std = @import("std"); const validators = @import("./util/validators.zig"); const Allocator = std.mem.Allocator; -const bun = @import("bun"); -const string = bun.string; - -const JSC = bun.JSC; -const ZigString = JSC.ZigString; +const jsc = bun.jsc; +const ZigString = jsc.ZigString; diff --git a/src/bun.js/node/node_zlib_binding.zig b/src/bun.js/node/node_zlib_binding.zig index 44b1501b57..2d5d671ed6 100644 --- a/src/bun.js/node/node_zlib_binding.zig +++ b/src/bun.js/node/node_zlib_binding.zig @@ -1,10 +1,10 @@ const debug = bun.Output.scoped(.zlib, true); -pub fn crc32(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { +pub fn crc32(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const arguments = callframe.arguments_old(2).ptr; const data: ZigString.Slice = blk: { - const data: JSC.JSValue = arguments[0]; + const data: jsc.JSValue = arguments[0]; if (data == .zero) { return globalThis.throwInvalidArgumentTypeValue("data", "string or an instance of Buffer, TypedArray, or DataView", .js_undefined); @@ -22,7 +22,7 @@ pub fn crc32(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSE defer data.deinit(); const value: u32 = blk: { - const value: JSC.JSValue = arguments[1]; + const value: jsc.JSValue = arguments[1]; if (value == .zero) { break :blk 0; } @@ -44,12 +44,12 @@ pub fn crc32(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSE // crc32 returns a u64 but the data will always be within a u32 range so the outer @intCast is always safe. const slice_u8 = data.slice(); - return JSC.JSValue.jsNumber(@as(u32, @intCast(bun.zlib.crc32(value, slice_u8.ptr, @intCast(slice_u8.len))))); + return jsc.JSValue.jsNumber(@as(u32, @intCast(bun.zlib.crc32(value, slice_u8.ptr, @intCast(slice_u8.len))))); } pub fn CompressionStream(comptime T: type) type { return struct { - pub fn write(this: *T, globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { + pub fn write(this: *T, globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const arguments = callframe.argumentsUndef(7).slice(); if (arguments.len != 7) { @@ -104,29 +104,29 @@ pub fn CompressionStream(comptime T: type) type { const vm = globalThis.bunVM(); this.task = .{ .callback = &AsyncJob.runTask }; this.poll_ref.ref(vm); - JSC.WorkPool.schedule(&this.task); + jsc.WorkPool.schedule(&this.task); return .js_undefined; } const AsyncJob = struct { - pub fn runTask(task: *JSC.WorkPoolTask) void { + pub fn runTask(task: *jsc.WorkPoolTask) void { const this: *T = @fieldParentPtr("task", task); AsyncJob.run(this); } pub fn run(this: *T) void { - const globalThis: *JSC.JSGlobalObject = this.globalThis; + const globalThis: *jsc.JSGlobalObject = this.globalThis; const vm = globalThis.bunVMConcurrently(); this.stream.doWork(); - vm.enqueueTaskConcurrent(JSC.ConcurrentTask.create(JSC.Task.init(this))); + vm.enqueueTaskConcurrent(jsc.ConcurrentTask.create(jsc.Task.init(this))); } }; pub fn runFromJSThread(this: *T) void { - const global: *JSC.JSGlobalObject = this.globalThis; + const global: *jsc.JSGlobalObject = this.globalThis; const vm = global.bunVM(); this.poll_ref.unref(vm); defer this.deref(); @@ -148,14 +148,14 @@ pub fn CompressionStream(comptime T: type) type { this.stream.updateWriteResult(&this.write_result.?[1], &this.write_result.?[0]); this_value.ensureStillAlive(); - const write_callback: JSC.JSValue = T.js.writeCallbackGetCached(this_value).?; + const write_callback: jsc.JSValue = T.js.writeCallbackGetCached(this_value).?; vm.eventLoop().runCallback(write_callback, global, this_value, &.{}); if (this.pending_close) _ = closeInternal(this); } - pub fn writeSync(this: *T, globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { + pub fn writeSync(this: *T, globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const arguments = callframe.argumentsUndef(7).slice(); if (arguments.len != 7) { @@ -212,7 +212,7 @@ pub fn CompressionStream(comptime T: type) type { return .js_undefined; } - pub fn reset(this: *T, globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { + pub fn reset(this: *T, globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const err = this.stream.reset(); if (err.isError()) { try emitError(this, globalThis, callframe.this(), err); @@ -220,7 +220,7 @@ pub fn CompressionStream(comptime T: type) type { return .js_undefined; } - pub fn close(this: *T, globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { + pub fn close(this: *T, globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { _ = globalThis; _ = callframe; closeInternal(this); @@ -238,32 +238,32 @@ pub fn CompressionStream(comptime T: type) type { this.stream.close(); } - pub fn setOnError(_: *T, this_value: JSC.JSValue, globalObject: *JSC.JSGlobalObject, value: JSC.JSValue) void { + pub fn setOnError(_: *T, this_value: jsc.JSValue, globalObject: *jsc.JSGlobalObject, value: jsc.JSValue) void { if (value.isFunction()) { T.js.errorCallbackSetCached(this_value, globalObject, value.withAsyncContextIfNeeded(globalObject)); } } - pub fn getOnError(_: *T, this_value: JSC.JSValue, _: *JSC.JSGlobalObject) JSC.JSValue { + pub fn getOnError(_: *T, this_value: jsc.JSValue, _: *jsc.JSGlobalObject) jsc.JSValue { return T.js.errorCallbackGetCached(this_value) orelse .js_undefined; } /// returns true if no error was detected/emitted - fn checkError(this: *T, globalThis: *JSC.JSGlobalObject, this_value: JSC.JSValue) !bool { + fn checkError(this: *T, globalThis: *jsc.JSGlobalObject, this_value: jsc.JSValue) !bool { const err = this.stream.getErrorInfo(); if (!err.isError()) return true; try emitError(this, globalThis, this_value, err); return false; } - pub fn emitError(this: *T, globalThis: *JSC.JSGlobalObject, this_value: JSC.JSValue, err_: Error) !void { + pub fn emitError(this: *T, globalThis: *jsc.JSGlobalObject, this_value: jsc.JSValue, err_: Error) !void { var msg_str = bun.String.createFormat("{s}", .{std.mem.sliceTo(err_.msg, 0) orelse ""}) catch bun.outOfMemory(); const msg_value = msg_str.transferToJS(globalThis); - const err_value = JSC.jsNumber(err_.err); + const err_value = jsc.jsNumber(err_.err); var code_str = bun.String.createFormat("{s}", .{std.mem.sliceTo(err_.code, 0) orelse ""}) catch bun.outOfMemory(); const code_value = code_str.transferToJS(globalThis); - const callback: JSC.JSValue = T.js.errorCallbackGetCached(this_value) orelse + const callback: jsc.JSValue = T.js.errorCallbackGetCached(this_value) orelse Output.panic("Assertion failure: cachedErrorCallback is null in node:zlib binding", .{}); _ = try callback.call(globalThis, this_value, &.{ msg_value, err_value, code_value }); @@ -277,24 +277,24 @@ pub fn CompressionStream(comptime T: type) type { }; } -pub const NativeZlib = JSC.Codegen.JSNativeZlib.getConstructor; +pub const NativeZlib = jsc.Codegen.JSNativeZlib.getConstructor; -pub const NativeBrotli = JSC.Codegen.JSNativeBrotli.getConstructor; +pub const NativeBrotli = jsc.Codegen.JSNativeBrotli.getConstructor; -pub const NativeZstd = JSC.Codegen.JSNativeZstd.getConstructor; +pub const NativeZstd = jsc.Codegen.JSNativeZstd.getConstructor; pub const CountedKeepAlive = struct { keep_alive: bun.Async.KeepAlive = .{}, ref_count: u32 = 0, - pub fn ref(this: *@This(), vm: *JSC.VirtualMachine) void { + pub fn ref(this: *@This(), vm: *jsc.VirtualMachine) void { if (this.ref_count == 0) { this.keep_alive.ref(vm); } this.ref_count += 1; } - pub fn unref(this: *@This(), vm: *JSC.VirtualMachine) void { + pub fn unref(this: *@This(), vm: *jsc.VirtualMachine) void { this.ref_count -= 1; if (this.ref_count == 0) { this.keep_alive.unref(vm); @@ -326,12 +326,13 @@ pub const Error = struct { } }; +const string = []const u8; + const std = @import("std"); const bun = @import("bun"); const Output = bun.Output; -const string = bun.string; const Buffer = bun.api.node.Buffer; -const JSC = bun.JSC; -const ZigString = JSC.ZigString; +const jsc = bun.jsc; +const ZigString = jsc.ZigString; diff --git a/src/bun.js/node/os/constants.zig b/src/bun.js/node/os/constants.zig index 03e44be301..d93c82af21 100644 --- a/src/bun.js/node/os/constants.zig +++ b/src/bun.js/node/os/constants.zig @@ -28,52 +28,52 @@ fn getDlopenConstant(comptime name: []const u8) ?comptime_int { return null; } -fn defineConstant(globalObject: *JSC.JSGlobalObject, object: JSC.JSValue, comptime ctype: ConstantType, comptime name: string) void { +fn defineConstant(globalObject: *jsc.JSGlobalObject, object: jsc.JSValue, comptime ctype: ConstantType, comptime name: string) void { return __defineConstant(globalObject, object, ctype, name, null); } -fn __defineConstant(globalObject: *JSC.JSGlobalObject, object: JSC.JSValue, comptime ctype: ConstantType, comptime name: string, comptime value: ?i32) void { +fn __defineConstant(globalObject: *jsc.JSGlobalObject, object: jsc.JSValue, comptime ctype: ConstantType, comptime name: string, comptime value: ?i32) void { switch (ctype) { .ERRNO => { if (comptime getErrnoConstant(name)) |constant| { - object.put(globalObject, JSC.ZigString.static("E" ++ name), JSC.JSValue.jsNumber(constant)); + object.put(globalObject, jsc.ZigString.static("E" ++ name), jsc.JSValue.jsNumber(constant)); } }, .ERRNO_WIN => { if (comptime getWindowsErrnoConstant(name)) |constant| { - object.put(globalObject, JSC.ZigString.static(name), JSC.JSValue.jsNumber(constant)); + object.put(globalObject, jsc.ZigString.static(name), jsc.JSValue.jsNumber(constant)); } }, .SIG => { if (comptime getSignalsConstant(name)) |constant| { - object.put(globalObject, JSC.ZigString.static("SIG" ++ name), JSC.JSValue.jsNumber(constant)); + object.put(globalObject, jsc.ZigString.static("SIG" ++ name), jsc.JSValue.jsNumber(constant)); } }, .DLOPEN => { if (comptime getDlopenConstant(name)) |constant| { - object.put(globalObject, JSC.ZigString.static("RTLD_" ++ name), JSC.JSValue.jsNumber(constant)); + object.put(globalObject, jsc.ZigString.static("RTLD_" ++ name), jsc.JSValue.jsNumber(constant)); } }, .OTHER => { - object.put(globalObject, JSC.ZigString.static(name), JSC.JSValue.jsNumberFromInt32(value.?)); + object.put(globalObject, jsc.ZigString.static(name), jsc.JSValue.jsNumberFromInt32(value.?)); }, } } -pub fn create(globalObject: *JSC.JSGlobalObject) JSC.JSValue { - const object = JSC.JSValue.createEmptyObject(globalObject, 0); +pub fn create(globalObject: *jsc.JSGlobalObject) jsc.JSValue { + const object = jsc.JSValue.createEmptyObject(globalObject, 0); - object.put(globalObject, JSC.ZigString.static("errno"), createErrno(globalObject)); - object.put(globalObject, JSC.ZigString.static("signals"), createSignals(globalObject)); - object.put(globalObject, JSC.ZigString.static("priority"), createPriority(globalObject)); - object.put(globalObject, JSC.ZigString.static("dlopen"), createDlopen(globalObject)); + object.put(globalObject, jsc.ZigString.static("errno"), createErrno(globalObject)); + object.put(globalObject, jsc.ZigString.static("signals"), createSignals(globalObject)); + object.put(globalObject, jsc.ZigString.static("priority"), createPriority(globalObject)); + object.put(globalObject, jsc.ZigString.static("dlopen"), createDlopen(globalObject)); __defineConstant(globalObject, object, .OTHER, "UV_UDP_REUSEADDR", 4); return object; } -fn createErrno(globalObject: *JSC.JSGlobalObject) JSC.JSValue { - const object = JSC.JSValue.createEmptyObject(globalObject, 0); +fn createErrno(globalObject: *jsc.JSGlobalObject) jsc.JSValue { + const object = jsc.JSValue.createEmptyObject(globalObject, 0); defineConstant(globalObject, object, .ERRNO, "2BIG"); defineConstant(globalObject, object, .ERRNO, "ACCES"); @@ -219,8 +219,8 @@ fn createErrno(globalObject: *JSC.JSGlobalObject) JSC.JSValue { return object; } -fn createSignals(globalObject: *JSC.JSGlobalObject) JSC.JSValue { - const object = JSC.JSValue.createEmptyObject(globalObject, 0); +fn createSignals(globalObject: *jsc.JSGlobalObject) jsc.JSValue { + const object = jsc.JSValue.createEmptyObject(globalObject, 0); defineConstant(globalObject, object, .SIG, "HUP"); defineConstant(globalObject, object, .SIG, "INT"); @@ -263,8 +263,8 @@ fn createSignals(globalObject: *JSC.JSGlobalObject) JSC.JSValue { return object; } -fn createPriority(globalObject: *JSC.JSGlobalObject) JSC.JSValue { - const object = JSC.JSValue.createEmptyObject(globalObject, 6); +fn createPriority(globalObject: *jsc.JSGlobalObject) jsc.JSValue { + const object = jsc.JSValue.createEmptyObject(globalObject, 6); __defineConstant(globalObject, object, .OTHER, "PRIORITY_LOW", 19); __defineConstant(globalObject, object, .OTHER, "PRIORITY_BELOW_NORMAL", 10); @@ -276,8 +276,8 @@ fn createPriority(globalObject: *JSC.JSGlobalObject) JSC.JSValue { return object; } -fn createDlopen(globalObject: *JSC.JSGlobalObject) JSC.JSValue { - const object = JSC.JSValue.createEmptyObject(globalObject, 5); +fn createDlopen(globalObject: *jsc.JSGlobalObject) jsc.JSValue { + const object = jsc.JSValue.createEmptyObject(globalObject, 5); defineConstant(globalObject, object, .DLOPEN, "LAZY"); defineConstant(globalObject, object, .DLOPEN, "NOW"); @@ -288,9 +288,10 @@ fn createDlopen(globalObject: *JSC.JSGlobalObject) JSC.JSValue { return object; } +const string = []const u8; + const std = @import("std"); const bun = @import("bun"); const Environment = bun.Environment; -const JSC = bun.JSC; -const string = bun.string; +const jsc = bun.jsc; diff --git a/src/bun.js/node/path.zig b/src/bun.js/node/path.zig index 3a433fa40b..372f48e2af 100644 --- a/src/bun.js/node/path.zig +++ b/src/bun.js/node/path.zig @@ -35,11 +35,11 @@ inline fn toLowerT(comptime T: type, a_c: T) T { } fn MaybeBuf(comptime T: type) type { - return JSC.Node.Maybe([]T, Syscall.Error); + return jsc.Node.Maybe([]T, Syscall.Error); } fn MaybeSlice(comptime T: type) type { - return JSC.Node.Maybe([:0]const T, Syscall.Error); + return jsc.Node.Maybe([:0]const T, Syscall.Error); } fn validatePathT(comptime T: type, comptime methodName: []const u8) void { @@ -70,13 +70,13 @@ fn PathParsed(comptime T: type) type { ext: []const T = "", name: []const T = "", - pub fn toJSObject(this: @This(), globalObject: *JSC.JSGlobalObject) bun.JSError!JSC.JSValue { - var jsObject = JSC.JSValue.createEmptyObject(globalObject, 5); - jsObject.put(globalObject, JSC.ZigString.static("root"), try bun.String.createUTF8ForJS(globalObject, this.root)); - jsObject.put(globalObject, JSC.ZigString.static("dir"), try bun.String.createUTF8ForJS(globalObject, this.dir)); - jsObject.put(globalObject, JSC.ZigString.static("base"), try bun.String.createUTF8ForJS(globalObject, this.base)); - jsObject.put(globalObject, JSC.ZigString.static("ext"), try bun.String.createUTF8ForJS(globalObject, this.ext)); - jsObject.put(globalObject, JSC.ZigString.static("name"), try bun.String.createUTF8ForJS(globalObject, this.name)); + pub fn toJSObject(this: @This(), globalObject: *jsc.JSGlobalObject) bun.JSError!jsc.JSValue { + var jsObject = jsc.JSValue.createEmptyObject(globalObject, 5); + jsObject.put(globalObject, jsc.ZigString.static("root"), try bun.String.createUTF8ForJS(globalObject, this.root)); + jsObject.put(globalObject, jsc.ZigString.static("dir"), try bun.String.createUTF8ForJS(globalObject, this.dir)); + jsObject.put(globalObject, jsc.ZigString.static("base"), try bun.String.createUTF8ForJS(globalObject, this.base)); + jsObject.put(globalObject, jsc.ZigString.static("ext"), try bun.String.createUTF8ForJS(globalObject, this.ext)); + jsObject.put(globalObject, jsc.ZigString.static("name"), try bun.String.createUTF8ForJS(globalObject, this.name)); return jsObject; } }; @@ -404,30 +404,30 @@ pub fn basenameWindowsT(comptime T: type, path: []const T, suffix: ?[]const T) [ &.{}; } -pub fn basenamePosixJS_T(comptime T: type, globalObject: *JSC.JSGlobalObject, path: []const T, suffix: ?[]const T) bun.JSError!JSC.JSValue { +pub fn basenamePosixJS_T(comptime T: type, globalObject: *jsc.JSGlobalObject, path: []const T, suffix: ?[]const T) bun.JSError!jsc.JSValue { return bun.String.createUTF8ForJS(globalObject, basenamePosixT(T, path, suffix)); } -pub fn basenameWindowsJS_T(comptime T: type, globalObject: *JSC.JSGlobalObject, path: []const T, suffix: ?[]const T) bun.JSError!JSC.JSValue { +pub fn basenameWindowsJS_T(comptime T: type, globalObject: *jsc.JSGlobalObject, path: []const T, suffix: ?[]const T) bun.JSError!jsc.JSValue { return bun.String.createUTF8ForJS(globalObject, basenameWindowsT(T, path, suffix)); } -pub fn basenameJS_T(comptime T: type, globalObject: *JSC.JSGlobalObject, isWindows: bool, path: []const T, suffix: ?[]const T) bun.JSError!JSC.JSValue { +pub fn basenameJS_T(comptime T: type, globalObject: *jsc.JSGlobalObject, isWindows: bool, path: []const T, suffix: ?[]const T) bun.JSError!jsc.JSValue { return if (isWindows) basenameWindowsJS_T(T, globalObject, path, suffix) else basenamePosixJS_T(T, globalObject, path, suffix); } -pub fn basename(globalObject: *JSC.JSGlobalObject, isWindows: bool, args_ptr: [*]JSC.JSValue, args_len: u16) bun.JSError!JSC.JSValue { - const suffix_ptr: ?JSC.JSValue = if (args_len > 1 and !args_ptr[1].isUndefined()) args_ptr[1] else null; +pub fn basename(globalObject: *jsc.JSGlobalObject, isWindows: bool, args_ptr: [*]jsc.JSValue, args_len: u16) bun.JSError!jsc.JSValue { + const suffix_ptr: ?jsc.JSValue = if (args_len > 1 and !args_ptr[1].isUndefined()) args_ptr[1] else null; if (suffix_ptr) |_suffix_ptr| { // Supress exeption in zig. It does globalThis.vm().throwError() in JS land. try validateString(globalObject, _suffix_ptr, "ext", .{}); } - const path_ptr: JSC.JSValue = if (args_len > 0) args_ptr[0] else .js_undefined; + const path_ptr: jsc.JSValue = if (args_len > 0) args_ptr[0] else .js_undefined; // Supress exeption in zig. It does globalThis.vm().throwError() in JS land. try validateString(globalObject, path_ptr, "path", .{}); @@ -440,7 +440,7 @@ pub fn basename(globalObject: *JSC.JSGlobalObject, isWindows: bool, args_ptr: [* const pathZSlice = pathZStr.toSlice(allocator); defer pathZSlice.deinit(); - var suffixZSlice: ?JSC.ZigString.Slice = null; + var suffixZSlice: ?jsc.ZigString.Slice = null; if (suffix_ptr) |_suffix_ptr| { const suffixZStr = try _suffix_ptr.getZigString(globalObject); if (suffixZStr.len > 0 and suffixZStr.len <= pathZStr.len) { @@ -600,23 +600,23 @@ pub fn dirnameWindowsT(comptime T: type, path: []const T) []const T { comptime L(T, CHAR_STR_DOT); } -pub fn dirnamePosixJS_T(comptime T: type, globalObject: *JSC.JSGlobalObject, path: []const T) bun.JSError!JSC.JSValue { +pub fn dirnamePosixJS_T(comptime T: type, globalObject: *jsc.JSGlobalObject, path: []const T) bun.JSError!jsc.JSValue { return bun.String.createUTF8ForJS(globalObject, dirnamePosixT(T, path)); } -pub fn dirnameWindowsJS_T(comptime T: type, globalObject: *JSC.JSGlobalObject, path: []const T) bun.JSError!JSC.JSValue { +pub fn dirnameWindowsJS_T(comptime T: type, globalObject: *jsc.JSGlobalObject, path: []const T) bun.JSError!jsc.JSValue { return bun.String.createUTF8ForJS(globalObject, dirnameWindowsT(T, path)); } -pub fn dirnameJS_T(comptime T: type, globalObject: *JSC.JSGlobalObject, isWindows: bool, path: []const T) bun.JSError!JSC.JSValue { +pub fn dirnameJS_T(comptime T: type, globalObject: *jsc.JSGlobalObject, isWindows: bool, path: []const T) bun.JSError!jsc.JSValue { return if (isWindows) dirnameWindowsJS_T(T, globalObject, path) else dirnamePosixJS_T(T, globalObject, path); } -pub fn dirname(globalObject: *JSC.JSGlobalObject, isWindows: bool, args_ptr: [*]JSC.JSValue, args_len: u16) bun.JSError!JSC.JSValue { - const path_ptr: JSC.JSValue = if (args_len > 0) args_ptr[0] else .js_undefined; +pub fn dirname(globalObject: *jsc.JSGlobalObject, isWindows: bool, args_ptr: [*]jsc.JSValue, args_len: u16) bun.JSError!jsc.JSValue { + const path_ptr: jsc.JSValue = if (args_len > 0) args_ptr[0] else .js_undefined; // Supress exeption in zig. It does globalThis.vm().throwError() in JS land. try validateString(globalObject, path_ptr, "path", .{}); @@ -796,23 +796,23 @@ pub fn extnameWindowsT(comptime T: type, path: []const T) []const T { return path[_startDot.._end]; } -pub fn extnamePosixJS_T(comptime T: type, globalObject: *JSC.JSGlobalObject, path: []const T) bun.JSError!JSC.JSValue { +pub fn extnamePosixJS_T(comptime T: type, globalObject: *jsc.JSGlobalObject, path: []const T) bun.JSError!jsc.JSValue { return bun.String.createUTF8ForJS(globalObject, extnamePosixT(T, path)); } -pub fn extnameWindowsJS_T(comptime T: type, globalObject: *JSC.JSGlobalObject, path: []const T) bun.JSError!JSC.JSValue { +pub fn extnameWindowsJS_T(comptime T: type, globalObject: *jsc.JSGlobalObject, path: []const T) bun.JSError!jsc.JSValue { return bun.String.createUTF8ForJS(globalObject, extnameWindowsT(T, path)); } -pub fn extnameJS_T(comptime T: type, globalObject: *JSC.JSGlobalObject, isWindows: bool, path: []const T) bun.JSError!JSC.JSValue { +pub fn extnameJS_T(comptime T: type, globalObject: *jsc.JSGlobalObject, isWindows: bool, path: []const T) bun.JSError!jsc.JSValue { return if (isWindows) extnameWindowsJS_T(T, globalObject, path) else extnamePosixJS_T(T, globalObject, path); } -pub fn extname(globalObject: *JSC.JSGlobalObject, isWindows: bool, args_ptr: [*]JSC.JSValue, args_len: u16) bun.JSError!JSC.JSValue { - const path_ptr: JSC.JSValue = if (args_len > 0) args_ptr[0] else .js_undefined; +pub fn extname(globalObject: *jsc.JSGlobalObject, isWindows: bool, args_ptr: [*]jsc.JSValue, args_len: u16) bun.JSError!jsc.JSValue { + const path_ptr: jsc.JSValue = if (args_len > 0) args_ptr[0] else .js_undefined; // Supress exeption in zig. It does globalThis.vm().throwError() in JS land. try validateString(globalObject, path_ptr, "path", .{}); @@ -902,15 +902,15 @@ fn _formatT(comptime T: type, pathObject: PathParsed(T), sep: T, buf: []T) []con return buf[0..bufSize]; } -pub fn formatPosixJS_T(comptime T: type, globalObject: *JSC.JSGlobalObject, pathObject: PathParsed(T), buf: []T) bun.JSError!JSC.JSValue { +pub fn formatPosixJS_T(comptime T: type, globalObject: *jsc.JSGlobalObject, pathObject: PathParsed(T), buf: []T) bun.JSError!jsc.JSValue { return bun.String.createUTF8ForJS(globalObject, _formatT(T, pathObject, CHAR_FORWARD_SLASH, buf)); } -pub fn formatWindowsJS_T(comptime T: type, globalObject: *JSC.JSGlobalObject, pathObject: PathParsed(T), buf: []T) bun.JSError!JSC.JSValue { +pub fn formatWindowsJS_T(comptime T: type, globalObject: *jsc.JSGlobalObject, pathObject: PathParsed(T), buf: []T) bun.JSError!jsc.JSValue { return bun.String.createUTF8ForJS(globalObject, _formatT(T, pathObject, CHAR_BACKWARD_SLASH, buf)); } -pub fn formatJS_T(comptime T: type, globalObject: *JSC.JSGlobalObject, allocator: std.mem.Allocator, isWindows: bool, pathObject: PathParsed(T)) bun.JSError!JSC.JSValue { +pub fn formatJS_T(comptime T: type, globalObject: *jsc.JSGlobalObject, allocator: std.mem.Allocator, isWindows: bool, pathObject: PathParsed(T)) bun.JSError!jsc.JSValue { const baseLen = pathObject.base.len; const dirLen = pathObject.dir.len; // Add one for the possible separator. @@ -922,8 +922,8 @@ pub fn formatJS_T(comptime T: type, globalObject: *JSC.JSGlobalObject, allocator return if (isWindows) formatWindowsJS_T(T, globalObject, pathObject, buf) else formatPosixJS_T(T, globalObject, pathObject, buf); } -pub fn format(globalObject: *JSC.JSGlobalObject, isWindows: bool, args_ptr: [*]JSC.JSValue, args_len: u16) bun.JSError!JSC.JSValue { - const pathObject_ptr: JSC.JSValue = if (args_len > 0) args_ptr[0] else .js_undefined; +pub fn format(globalObject: *jsc.JSGlobalObject, isWindows: bool, args_ptr: [*]jsc.JSValue, args_len: u16) bun.JSError!jsc.JSValue { + const pathObject_ptr: jsc.JSValue = if (args_len > 0) args_ptr[0] else .js_undefined; // Supress exeption in zig. It does globalThis.vm().throwError() in JS land. try validateObject(globalObject, pathObject_ptr, "pathObject", .{}, .{}); @@ -931,7 +931,7 @@ pub fn format(globalObject: *JSC.JSGlobalObject, isWindows: bool, args_ptr: [*]J const allocator = stack_fallback.get(); var root: []const u8 = ""; - var root_slice: ?JSC.ZigString.Slice = null; + var root_slice: ?jsc.ZigString.Slice = null; defer if (root_slice) |slice| slice.deinit(); if (try pathObject_ptr.getTruthy(globalObject, "root")) |jsValue| { @@ -939,7 +939,7 @@ pub fn format(globalObject: *JSC.JSGlobalObject, isWindows: bool, args_ptr: [*]J root = root_slice.?.slice(); } var dir: []const u8 = ""; - var dir_slice: ?JSC.ZigString.Slice = null; + var dir_slice: ?jsc.ZigString.Slice = null; defer if (dir_slice) |slice| slice.deinit(); if (try pathObject_ptr.getTruthy(globalObject, "dir")) |jsValue| { @@ -947,7 +947,7 @@ pub fn format(globalObject: *JSC.JSGlobalObject, isWindows: bool, args_ptr: [*]J dir = dir_slice.?.slice(); } var base: []const u8 = ""; - var base_slice: ?JSC.ZigString.Slice = null; + var base_slice: ?jsc.ZigString.Slice = null; defer if (base_slice) |slice| slice.deinit(); if (try pathObject_ptr.getTruthy(globalObject, "base")) |jsValue| { @@ -955,7 +955,7 @@ pub fn format(globalObject: *JSC.JSGlobalObject, isWindows: bool, args_ptr: [*]J base = base_slice.?.slice(); } var _name: []const u8 = ""; - var _name_slice: ?JSC.ZigString.Slice = null; + var _name_slice: ?jsc.ZigString.Slice = null; defer if (_name_slice) |slice| slice.deinit(); if (try pathObject_ptr.getTruthy(globalObject, "name")) |jsValue| { @@ -963,7 +963,7 @@ pub fn format(globalObject: *JSC.JSGlobalObject, isWindows: bool, args_ptr: [*]J _name = _name_slice.?.slice(); } var ext: []const u8 = ""; - var ext_slice: ?JSC.ZigString.Slice = null; + var ext_slice: ?jsc.ZigString.Slice = null; defer if (ext_slice) |slice| slice.deinit(); if (try pathObject_ptr.getTruthy(globalObject, "ext")) |jsValue| { @@ -997,7 +997,7 @@ pub fn isAbsoluteWindowsT(comptime T: type, path: []const T) bool { isSepWindowsT(T, path[2])); } -pub fn isAbsolutePosixZigString(pathZStr: JSC.ZigString) bool { +pub fn isAbsolutePosixZigString(pathZStr: jsc.ZigString) bool { const pathZStrTrunc = pathZStr.trunc(1); return if (pathZStrTrunc.len > 0 and pathZStrTrunc.is16Bit()) isAbsolutePosixT(u16, pathZStrTrunc.utf16SliceAligned()) @@ -1005,22 +1005,22 @@ pub fn isAbsolutePosixZigString(pathZStr: JSC.ZigString) bool { isAbsolutePosixT(u8, pathZStrTrunc.slice()); } -pub fn isAbsoluteWindowsZigString(pathZStr: JSC.ZigString) bool { +pub fn isAbsoluteWindowsZigString(pathZStr: jsc.ZigString) bool { return if (pathZStr.len > 0 and pathZStr.is16Bit()) isAbsoluteWindowsT(u16, @alignCast(pathZStr.utf16Slice())) else isAbsoluteWindowsT(u8, pathZStr.slice()); } -pub fn isAbsolute(globalObject: *JSC.JSGlobalObject, isWindows: bool, args_ptr: [*]JSC.JSValue, args_len: u16) bun.JSError!JSC.JSValue { - const path_ptr: JSC.JSValue = if (args_len > 0) args_ptr[0] else .js_undefined; +pub fn isAbsolute(globalObject: *jsc.JSGlobalObject, isWindows: bool, args_ptr: [*]jsc.JSValue, args_len: u16) bun.JSError!jsc.JSValue { + const path_ptr: jsc.JSValue = if (args_len > 0) args_ptr[0] else .js_undefined; // Supress exeption in zig. It does globalThis.vm().throwError() in JS land. try validateString(globalObject, path_ptr, "path", .{}); const pathZStr = try path_ptr.getZigString(globalObject); - if (pathZStr.len == 0) return JSC.JSValue.jsBoolean(false); - if (isWindows) return JSC.JSValue.jsBoolean(isAbsoluteWindowsZigString(pathZStr)); - return JSC.JSValue.jsBoolean(isAbsolutePosixZigString(pathZStr)); + if (pathZStr.len == 0) return jsc.JSValue.jsBoolean(false); + if (isWindows) return jsc.JSValue.jsBoolean(isAbsoluteWindowsZigString(pathZStr)); + return jsc.JSValue.jsBoolean(isAbsolutePosixZigString(pathZStr)); } pub fn isSepPosixT(comptime T: type, byte: T) bool { @@ -1203,15 +1203,15 @@ pub fn joinWindowsT(comptime T: type, paths: []const []const T, buf: []T, buf2: return normalizeWindowsT(T, joined, buf); } -pub fn joinPosixJS_T(comptime T: type, globalObject: *JSC.JSGlobalObject, paths: []const []const T, buf: []T, buf2: []T) bun.JSError!JSC.JSValue { +pub fn joinPosixJS_T(comptime T: type, globalObject: *jsc.JSGlobalObject, paths: []const []const T, buf: []T, buf2: []T) bun.JSError!jsc.JSValue { return bun.String.createUTF8ForJS(globalObject, joinPosixT(T, paths, buf, buf2)); } -pub fn joinWindowsJS_T(comptime T: type, globalObject: *JSC.JSGlobalObject, paths: []const []const T, buf: []T, buf2: []T) bun.JSError!JSC.JSValue { +pub fn joinWindowsJS_T(comptime T: type, globalObject: *jsc.JSGlobalObject, paths: []const []const T, buf: []T, buf2: []T) bun.JSError!jsc.JSValue { return bun.String.createUTF8ForJS(globalObject, joinWindowsT(T, paths, buf, buf2)); } -pub fn joinJS_T(comptime T: type, globalObject: *JSC.JSGlobalObject, allocator: std.mem.Allocator, isWindows: bool, paths: []const []const T) bun.JSError!JSC.JSValue { +pub fn joinJS_T(comptime T: type, globalObject: *jsc.JSGlobalObject, allocator: std.mem.Allocator, isWindows: bool, paths: []const []const T) bun.JSError!jsc.JSValue { // Adding 8 bytes when Windows for the possible UNC root. var bufLen: usize = if (isWindows) 8 else 0; for (paths) |path| bufLen += if (path.len > 0) path.len + 1 else path.len; @@ -1223,7 +1223,7 @@ pub fn joinJS_T(comptime T: type, globalObject: *JSC.JSGlobalObject, allocator: return if (isWindows) joinWindowsJS_T(T, globalObject, paths, buf, buf2) else joinPosixJS_T(T, globalObject, paths, buf, buf2); } -pub fn join(globalObject: *JSC.JSGlobalObject, isWindows: bool, args_ptr: [*]JSC.JSValue, args_len: u16) bun.JSError!JSC.JSValue { +pub fn join(globalObject: *jsc.JSGlobalObject, isWindows: bool, args_ptr: [*]jsc.JSValue, args_len: u16) bun.JSError!jsc.JSValue { if (args_len == 0) return bun.String.createUTF8ForJS(globalObject, CHAR_STR_DOT); var arena = bun.ArenaAllocator.init(bun.default_allocator); @@ -1615,23 +1615,23 @@ pub fn normalizeT(comptime T: type, path: []const T, buf: []T) []const T { }; } -pub fn normalizePosixJS_T(comptime T: type, globalObject: *JSC.JSGlobalObject, path: []const T, buf: []T) bun.JSError!JSC.JSValue { +pub fn normalizePosixJS_T(comptime T: type, globalObject: *jsc.JSGlobalObject, path: []const T, buf: []T) bun.JSError!jsc.JSValue { return bun.String.createUTF8ForJS(globalObject, normalizePosixT(T, path, buf)); } -pub fn normalizeWindowsJS_T(comptime T: type, globalObject: *JSC.JSGlobalObject, path: []const T, buf: []T) bun.JSError!JSC.JSValue { +pub fn normalizeWindowsJS_T(comptime T: type, globalObject: *jsc.JSGlobalObject, path: []const T, buf: []T) bun.JSError!jsc.JSValue { return bun.String.createUTF8ForJS(globalObject, normalizeWindowsT(T, path, buf)); } -pub fn normalizeJS_T(comptime T: type, globalObject: *JSC.JSGlobalObject, allocator: std.mem.Allocator, isWindows: bool, path: []const T) bun.JSError!JSC.JSValue { +pub fn normalizeJS_T(comptime T: type, globalObject: *jsc.JSGlobalObject, allocator: std.mem.Allocator, isWindows: bool, path: []const T) bun.JSError!jsc.JSValue { const bufLen = @max(path.len, PATH_SIZE(T)); const buf = allocator.alloc(T, bufLen) catch bun.outOfMemory(); defer allocator.free(buf); return if (isWindows) normalizeWindowsJS_T(T, globalObject, path, buf) else normalizePosixJS_T(T, globalObject, path, buf); } -pub fn normalize(globalObject: *JSC.JSGlobalObject, isWindows: bool, args_ptr: [*]JSC.JSValue, args_len: u16) bun.JSError!JSC.JSValue { - const path_ptr: JSC.JSValue = if (args_len > 0) args_ptr[0] else .js_undefined; +pub fn normalize(globalObject: *jsc.JSGlobalObject, isWindows: bool, args_ptr: [*]jsc.JSValue, args_len: u16) bun.JSError!jsc.JSValue { + const path_ptr: jsc.JSValue = if (args_len > 0) args_ptr[0] else .js_undefined; // Supress exeption in zig. It does globalThis.vm().throwError() in JS land. try validateString(globalObject, path_ptr, "path", .{}); const pathZStr = try path_ptr.getZigString(globalObject); @@ -1938,20 +1938,20 @@ pub fn parseWindowsT(comptime T: type, path: []const T) PathParsed(T) { return .{ .root = root, .dir = dir, .base = base, .ext = ext, .name = _name }; } -pub fn parsePosixJS_T(comptime T: type, globalObject: *JSC.JSGlobalObject, path: []const T) bun.JSError!JSC.JSValue { +pub fn parsePosixJS_T(comptime T: type, globalObject: *jsc.JSGlobalObject, path: []const T) bun.JSError!jsc.JSValue { return parsePosixT(T, path).toJSObject(globalObject); } -pub fn parseWindowsJS_T(comptime T: type, globalObject: *JSC.JSGlobalObject, path: []const T) bun.JSError!JSC.JSValue { +pub fn parseWindowsJS_T(comptime T: type, globalObject: *jsc.JSGlobalObject, path: []const T) bun.JSError!jsc.JSValue { return parseWindowsT(T, path).toJSObject(globalObject); } -pub fn parseJS_T(comptime T: type, globalObject: *JSC.JSGlobalObject, isWindows: bool, path: []const T) bun.JSError!JSC.JSValue { +pub fn parseJS_T(comptime T: type, globalObject: *jsc.JSGlobalObject, isWindows: bool, path: []const T) bun.JSError!jsc.JSValue { return if (isWindows) parseWindowsJS_T(T, globalObject, path) else parsePosixJS_T(T, globalObject, path); } -pub fn parse(globalObject: *JSC.JSGlobalObject, isWindows: bool, args_ptr: [*]JSC.JSValue, args_len: u16) bun.JSError!JSC.JSValue { - const path_ptr: JSC.JSValue = if (args_len > 0) args_ptr[0] else .js_undefined; +pub fn parse(globalObject: *jsc.JSGlobalObject, isWindows: bool, args_ptr: [*]jsc.JSValue, args_len: u16) bun.JSError!jsc.JSValue { + const path_ptr: jsc.JSValue = if (args_len > 0) args_ptr[0] else .js_undefined; // Supress exeption in zig. It does globalThis.vm().throwError() in JS land. try validateString(globalObject, path_ptr, "path", .{}); @@ -2283,21 +2283,21 @@ pub fn relativeWindowsT(comptime T: type, from: []const T, to: []const T, buf: [ return MaybeSlice(T){ .result = toOrig[toStart..toEnd :0] }; } -pub fn relativePosixJS_T(comptime T: type, globalObject: *JSC.JSGlobalObject, from: []const T, to: []const T, buf: []T, buf2: []T, buf3: []T) bun.JSError!JSC.JSValue { +pub fn relativePosixJS_T(comptime T: type, globalObject: *jsc.JSGlobalObject, from: []const T, to: []const T, buf: []T, buf2: []T, buf3: []T) bun.JSError!jsc.JSValue { return switch (relativePosixT(T, from, to, buf, buf2, buf3)) { .result => |r| bun.String.createUTF8ForJS(globalObject, r), .err => |e| e.toJS(globalObject), }; } -pub fn relativeWindowsJS_T(comptime T: type, globalObject: *JSC.JSGlobalObject, from: []const T, to: []const T, buf: []T, buf2: []T, buf3: []T) bun.JSError!JSC.JSValue { +pub fn relativeWindowsJS_T(comptime T: type, globalObject: *jsc.JSGlobalObject, from: []const T, to: []const T, buf: []T, buf2: []T, buf3: []T) bun.JSError!jsc.JSValue { return switch (relativeWindowsT(T, from, to, buf, buf2, buf3)) { .result => |r| bun.String.createUTF8ForJS(globalObject, r), .err => |e| e.toJS(globalObject), }; } -pub fn relativeJS_T(comptime T: type, globalObject: *JSC.JSGlobalObject, allocator: std.mem.Allocator, isWindows: bool, from: []const T, to: []const T) bun.JSError!JSC.JSValue { +pub fn relativeJS_T(comptime T: type, globalObject: *jsc.JSGlobalObject, allocator: std.mem.Allocator, isWindows: bool, from: []const T, to: []const T) bun.JSError!jsc.JSValue { const bufLen = @max(from.len + to.len, PATH_SIZE(T)); const buf = allocator.alloc(T, bufLen) catch bun.outOfMemory(); defer allocator.free(buf); @@ -2308,11 +2308,11 @@ pub fn relativeJS_T(comptime T: type, globalObject: *JSC.JSGlobalObject, allocat return if (isWindows) relativeWindowsJS_T(T, globalObject, from, to, buf, buf2, buf3) else relativePosixJS_T(T, globalObject, from, to, buf, buf2, buf3); } -pub fn relative(globalObject: *JSC.JSGlobalObject, isWindows: bool, args_ptr: [*]JSC.JSValue, args_len: u16) bun.JSError!JSC.JSValue { - const from_ptr: JSC.JSValue = if (args_len > 0) args_ptr[0] else .js_undefined; +pub fn relative(globalObject: *jsc.JSGlobalObject, isWindows: bool, args_ptr: [*]jsc.JSValue, args_len: u16) bun.JSError!jsc.JSValue { + const from_ptr: jsc.JSValue = if (args_len > 0) args_ptr[0] else .js_undefined; // Supress exeption in zig. It does globalThis.vm().throwError() in JS land. try validateString(globalObject, from_ptr, "from", .{}); - const to_ptr: JSC.JSValue = if (args_len > 1) args_ptr[1] else .js_undefined; + const to_ptr: jsc.JSValue = if (args_len > 1) args_ptr[1] else .js_undefined; // Supress exeption in zig. It does globalThis.vm().throwError() in JS land. try validateString(globalObject, to_ptr, "to", .{}); @@ -2732,21 +2732,21 @@ pub fn resolveWindowsT(comptime T: type, paths: []const []const T, buf: []T, buf return MaybeSlice(T){ .result = comptime L(T, CHAR_STR_DOT) }; } -pub fn resolvePosixJS_T(comptime T: type, globalObject: *JSC.JSGlobalObject, paths: []const []const T, buf: []T, buf2: []T) bun.JSError!JSC.JSValue { +pub fn resolvePosixJS_T(comptime T: type, globalObject: *jsc.JSGlobalObject, paths: []const []const T, buf: []T, buf2: []T) bun.JSError!jsc.JSValue { return switch (resolvePosixT(T, paths, buf, buf2)) { .result => |r| bun.String.createUTF8ForJS(globalObject, r), .err => |e| e.toJS(globalObject), }; } -pub fn resolveWindowsJS_T(comptime T: type, globalObject: *JSC.JSGlobalObject, paths: []const []const T, buf: []T, buf2: []T) bun.JSError!JSC.JSValue { +pub fn resolveWindowsJS_T(comptime T: type, globalObject: *jsc.JSGlobalObject, paths: []const []const T, buf: []T, buf2: []T) bun.JSError!jsc.JSValue { return switch (resolveWindowsT(T, paths, buf, buf2)) { .result => |r| bun.String.createUTF8ForJS(globalObject, r), .err => |e| e.toJS(globalObject), }; } -pub fn resolveJS_T(comptime T: type, globalObject: *JSC.JSGlobalObject, allocator: std.mem.Allocator, isWindows: bool, paths: []const []const T) bun.JSError!JSC.JSValue { +pub fn resolveJS_T(comptime T: type, globalObject: *jsc.JSGlobalObject, allocator: std.mem.Allocator, isWindows: bool, paths: []const []const T) bun.JSError!jsc.JSValue { // Adding 8 bytes when Windows for the possible UNC root. var bufLen: usize = if (isWindows) 8 else 0; for (paths) |path| bufLen += if (bufLen > 0 and path.len > 0) path.len + 1 else path.len; @@ -2758,9 +2758,9 @@ pub fn resolveJS_T(comptime T: type, globalObject: *JSC.JSGlobalObject, allocato return if (isWindows) resolveWindowsJS_T(T, globalObject, paths, buf, buf2) else resolvePosixJS_T(T, globalObject, paths, buf, buf2); } -extern "c" fn Process__getCachedCwd(*JSC.JSGlobalObject) JSC.JSValue; +extern "c" fn Process__getCachedCwd(*jsc.JSGlobalObject) jsc.JSValue; -pub fn resolve(globalObject: *JSC.JSGlobalObject, isWindows: bool, args_ptr: [*]JSC.JSValue, args_len: u16) bun.JSError!JSC.JSValue { +pub fn resolve(globalObject: *jsc.JSGlobalObject, isWindows: bool, args_ptr: [*]jsc.JSValue, args_len: u16) bun.JSError!jsc.JSValue { var arena = bun.ArenaAllocator.init(bun.default_allocator); defer arena.deinit(); @@ -2875,14 +2875,14 @@ pub fn toNamespacedPathWindowsT(comptime T: type, path: []const T, buf: []T, buf return MaybeSlice(T){ .result = resolvedPath }; } -pub fn toNamespacedPathWindowsJS_T(comptime T: type, globalObject: *JSC.JSGlobalObject, path: []const T, buf: []T, buf2: []T) bun.JSError!JSC.JSValue { +pub fn toNamespacedPathWindowsJS_T(comptime T: type, globalObject: *jsc.JSGlobalObject, path: []const T, buf: []T, buf2: []T) bun.JSError!jsc.JSValue { return switch (toNamespacedPathWindowsT(T, path, buf, buf2)) { .result => |r| bun.String.createUTF8ForJS(globalObject, r), .err => |e| e.toJS(globalObject), }; } -pub fn toNamespacedPathJS_T(comptime T: type, globalObject: *JSC.JSGlobalObject, allocator: std.mem.Allocator, isWindows: bool, path: []const T) bun.JSError!JSC.JSValue { +pub fn toNamespacedPathJS_T(comptime T: type, globalObject: *jsc.JSGlobalObject, allocator: std.mem.Allocator, isWindows: bool, path: []const T) bun.JSError!jsc.JSValue { if (!isWindows or path.len == 0) return bun.String.createUTF8ForJS(globalObject, path); const bufLen = @max(path.len, PATH_SIZE(T)); const buf = allocator.alloc(T, bufLen) catch bun.outOfMemory(); @@ -2892,7 +2892,7 @@ pub fn toNamespacedPathJS_T(comptime T: type, globalObject: *JSC.JSGlobalObject, return toNamespacedPathWindowsJS_T(T, globalObject, path, buf, buf2); } -pub fn toNamespacedPath(globalObject: *JSC.JSGlobalObject, isWindows: bool, args_ptr: [*]JSC.JSValue, args_len: u16) bun.JSError!JSC.JSValue { +pub fn toNamespacedPath(globalObject: *jsc.JSGlobalObject, isWindows: bool, args_ptr: [*]jsc.JSValue, args_len: u16) bun.JSError!jsc.JSValue { if (args_len == 0) return .js_undefined; var path_ptr = args_ptr[0]; @@ -2928,6 +2928,8 @@ comptime { @export(&bun.jsc.host_fn.wrap4v(Path.toNamespacedPath), .{ .name = "Bun__Path__toNamespacedPath" }); } +const string = []const u8; + const std = @import("std"); const validators = @import("./util/validators.zig"); @@ -2936,9 +2938,8 @@ const validateString = validators.validateString; const bun = @import("bun"); const Environment = bun.Environment; -const JSC = bun.JSC; const Syscall = bun.sys; -const string = bun.string; +const jsc = bun.jsc; const windows = bun.windows; const typeBaseNameT = bun.meta.typeBaseNameT; diff --git a/src/bun.js/node/path_watcher.zig b/src/bun.js/node/path_watcher.zig index 632c630010..3223d058d7 100644 --- a/src/bun.js/node/path_watcher.zig +++ b/src/bun.js/node/path_watcher.zig @@ -8,7 +8,7 @@ pub const PathWatcherManager = struct { watchers: bun.BabyList(?*PathWatcher) = .{}, watcher_count: u32 = 0, - vm: *JSC.VirtualMachine, + vm: *jsc.VirtualMachine, file_paths: bun.StringHashMap(PathInfo), current_fd_task: bun.FDHashMap(*DirectoryRegisterTask), deinit_on_last_watcher: bool = false, @@ -51,7 +51,7 @@ pub const PathWatcherManager = struct { fn _fdFromAbsolutePathZ( this: *PathWatcherManager, path: [:0]const u8, - ) bun.JSC.Maybe(PathInfo) { + ) bun.jsc.Maybe(PathInfo) { this.mutex.lock(); defer this.mutex.unlock(); @@ -109,7 +109,7 @@ pub const PathWatcherManager = struct { std.posix.INotifyInitError || std.Thread.SpawnError; - pub fn init(vm: *JSC.VirtualMachine) PathWatcherManagerError!*PathWatcherManager { + pub fn init(vm: *jsc.VirtualMachine) PathWatcherManagerError!*PathWatcherManager { const this = bun.default_allocator.create(PathWatcherManager) catch bun.outOfMemory(); errdefer bun.default_allocator.destroy(this); var watchers = bun.BabyList(?*PathWatcher).initCapacity(bun.default_allocator, 1) catch bun.outOfMemory(); @@ -325,10 +325,10 @@ pub const PathWatcherManager = struct { pub const DirectoryRegisterTask = struct { manager: *PathWatcherManager, path: PathInfo, - task: JSC.WorkPoolTask = .{ .callback = callback }, + task: jsc.WorkPoolTask = .{ .callback = callback }, watcher_list: bun.BabyList(*PathWatcher) = .{}, - pub fn callback(task: *JSC.WorkPoolTask) void { + pub fn callback(task: *jsc.WorkPoolTask) void { var routine: *@This() = @fieldParentPtr("task", task); defer routine.deinit(); routine.run(); @@ -382,7 +382,7 @@ pub const PathWatcherManager = struct { }; } if (manager.refPendingTask()) { - JSC.WorkPool.schedule(&routine.task); + jsc.WorkPool.schedule(&routine.task); return; } return error.UnexpectedFailure; @@ -406,7 +406,7 @@ pub const PathWatcherManager = struct { this: *DirectoryRegisterTask, watcher: *PathWatcher, buf: *bun.PathBuffer, - ) bun.JSC.Maybe(void) { + ) bun.jsc.Maybe(void) { if (Environment.isWindows) @compileError("use win_watcher.zig"); const manager = this.manager; @@ -514,7 +514,7 @@ pub const PathWatcherManager = struct { }; // this should only be called if thread pool is not null - fn _addDirectory(this: *PathWatcherManager, watcher: *PathWatcher, path: PathInfo) bun.JSC.Maybe(void) { + fn _addDirectory(this: *PathWatcherManager, watcher: *PathWatcher, path: PathInfo) bun.jsc.Maybe(void) { const fd = path.fd; switch (this.main_watcher.addDirectory(fd, path.path, path.hash, false)) { .err => |err| return .{ .err = err.withPath(path.path) }, @@ -914,7 +914,7 @@ pub fn watch( comptime callback: PathWatcher.Callback, comptime updateEnd: PathWatcher.UpdateEndCallback, ctx: ?*anyopaque, -) bun.JSC.Maybe(*PathWatcher) { +) bun.jsc.Maybe(*PathWatcher) { const manager = default_manager orelse brk: { default_manager_mutex.lock(); defer default_manager_mutex.unlock(); @@ -993,6 +993,8 @@ pub fn watch( return .{ .result = watcher }; } +const string = []const u8; + const FSEvents = @import("./fs_events.zig"); const Fs = @import("../../fs.zig"); const Path = @import("../../resolver/resolve_path.zig"); @@ -1004,10 +1006,9 @@ const FD = bun.FD; const Mutex = bun.Mutex; const Output = bun.Output; const Watcher = bun.Watcher; -const string = bun.string; - -const JSC = bun.JSC; -const VirtualMachine = JSC.VirtualMachine; const FSWatcher = bun.api.node.fs.Watcher; const Event = FSWatcher.Event; + +const jsc = bun.jsc; +const VirtualMachine = jsc.VirtualMachine; diff --git a/src/bun.js/node/types.zig b/src/bun.js/node/types.zig index 35544ecfcf..8fac8a92dc 100644 --- a/src/bun.js/node/types.zig +++ b/src/bun.js/node/types.zig @@ -1,5 +1,5 @@ pub const BlobOrStringOrBuffer = union(enum) { - blob: JSC.WebCore.Blob, + blob: jsc.WebCore.Blob, string_or_buffer: StringOrBuffer, pub fn deinit(this: *const BlobOrStringOrBuffer) void { @@ -46,10 +46,10 @@ pub const BlobOrStringOrBuffer = union(enum) { return this.slice().len; } - pub fn fromJSMaybeFile(global: *JSC.JSGlobalObject, allocator: std.mem.Allocator, value: JSC.JSValue, allow_file: bool) JSError!?BlobOrStringOrBuffer { + pub fn fromJSMaybeFile(global: *jsc.JSGlobalObject, allocator: std.mem.Allocator, value: jsc.JSValue, allow_file: bool) JSError!?BlobOrStringOrBuffer { // Check StringOrBuffer first because it's more common and cheaper. const str = try StringOrBuffer.fromJS(global, allocator, value) orelse { - const blob = value.as(JSC.WebCore.Blob) orelse return null; + const blob = value.as(jsc.WebCore.Blob) orelse return null; if (allow_file and blob.needsToReadFile()) { return global.throwInvalidArguments("File blob cannot be used here", .{}); } @@ -63,29 +63,29 @@ pub const BlobOrStringOrBuffer = union(enum) { return .{ .string_or_buffer = str }; } - pub fn fromJS(global: *JSC.JSGlobalObject, allocator: std.mem.Allocator, value: JSC.JSValue) JSError!?BlobOrStringOrBuffer { + pub fn fromJS(global: *jsc.JSGlobalObject, allocator: std.mem.Allocator, value: jsc.JSValue) JSError!?BlobOrStringOrBuffer { return fromJSMaybeFile(global, allocator, value, true); } - pub fn fromJSWithEncodingValue(global: *JSC.JSGlobalObject, allocator: std.mem.Allocator, value: JSC.JSValue, encoding_value: JSC.JSValue) bun.JSError!?BlobOrStringOrBuffer { + pub fn fromJSWithEncodingValue(global: *jsc.JSGlobalObject, allocator: std.mem.Allocator, value: jsc.JSValue, encoding_value: jsc.JSValue) bun.JSError!?BlobOrStringOrBuffer { return fromJSWithEncodingValueMaybeAsync(global, allocator, value, encoding_value, false); } - pub fn fromJSWithEncodingValueMaybeAsync(global: *JSC.JSGlobalObject, allocator: std.mem.Allocator, value: JSC.JSValue, encoding_value: JSC.JSValue, is_async: bool) bun.JSError!?BlobOrStringOrBuffer { + pub fn fromJSWithEncodingValueMaybeAsync(global: *jsc.JSGlobalObject, allocator: std.mem.Allocator, value: jsc.JSValue, encoding_value: jsc.JSValue, is_async: bool) bun.JSError!?BlobOrStringOrBuffer { return fromJSWithEncodingValueMaybeAsyncAllowRequestResponse(global, allocator, value, encoding_value, is_async, false); } - pub fn fromJSWithEncodingValueMaybeAsyncAllowRequestResponse(global: *JSC.JSGlobalObject, allocator: std.mem.Allocator, value: JSC.JSValue, encoding_value: JSC.JSValue, is_async: bool, allow_request_response: bool) bun.JSError!?BlobOrStringOrBuffer { + pub fn fromJSWithEncodingValueMaybeAsyncAllowRequestResponse(global: *jsc.JSGlobalObject, allocator: std.mem.Allocator, value: jsc.JSValue, encoding_value: jsc.JSValue, is_async: bool, allow_request_response: bool) bun.JSError!?BlobOrStringOrBuffer { switch (value.jsType()) { .DOMWrapper => { - if (value.as(JSC.WebCore.Blob)) |blob| { + if (value.as(jsc.WebCore.Blob)) |blob| { if (blob.store) |store| { store.ref(); } return .{ .blob = blob.* }; } if (allow_request_response) { - if (value.as(JSC.WebCore.Request)) |request| { + if (value.as(jsc.WebCore.Request)) |request| { request.body.value.toBlobIfPossible(); if (request.body.value.tryUseAsAnyBlob()) |any_blob_| { @@ -97,7 +97,7 @@ pub const BlobOrStringOrBuffer = union(enum) { return global.throwInvalidArguments("Only buffered Request/Response bodies are supported for now.", .{}); } - if (value.as(JSC.WebCore.Response)) |response| { + if (value.as(jsc.WebCore.Response)) |response| { response.body.value.toBlobIfPossible(); if (response.body.value.tryUseAsAnyBlob()) |any_blob_| { @@ -121,10 +121,10 @@ pub const BlobOrStringOrBuffer = union(enum) { pub const StringOrBuffer = union(enum) { string: bun.SliceWithUnderlyingString, threadsafe_string: bun.SliceWithUnderlyingString, - encoded_slice: JSC.ZigString.Slice, + encoded_slice: jsc.ZigString.Slice, buffer: Buffer, - pub const empty = StringOrBuffer{ .encoded_slice = JSC.ZigString.Slice.empty }; + pub const empty = StringOrBuffer{ .encoded_slice = jsc.ZigString.Slice.empty }; pub fn toThreadSafe(this: *@This()) void { switch (this.*) { @@ -142,7 +142,7 @@ pub const StringOrBuffer = union(enum) { } } - pub fn fromJSToOwnedSlice(globalObject: *JSC.JSGlobalObject, value: JSC.JSValue, allocator: std.mem.Allocator) bun.JSError![]u8 { + pub fn fromJSToOwnedSlice(globalObject: *jsc.JSGlobalObject, value: jsc.JSValue, allocator: std.mem.Allocator) bun.JSError![]u8 { if (value.asArrayBuffer(globalObject)) |array_buffer| { defer globalObject.vm().reportExtraMemory(array_buffer.len); @@ -157,7 +157,7 @@ pub const StringOrBuffer = union(enum) { return result; } - pub fn toJS(this: *StringOrBuffer, ctx: *JSC.JSGlobalObject) bun.JSError!JSC.JSValue { + pub fn toJS(this: *StringOrBuffer, ctx: *jsc.JSGlobalObject) bun.JSError!jsc.JSValue { return switch (this.*) { inline .threadsafe_string, .string => |*str| { return str.transferToJS(ctx); @@ -212,7 +212,7 @@ pub const StringOrBuffer = union(enum) { } } - pub fn fromJSMaybeAsync(global: *JSC.JSGlobalObject, allocator: std.mem.Allocator, value: JSC.JSValue, is_async: bool, allow_string_object: bool) JSError!?StringOrBuffer { + pub fn fromJSMaybeAsync(global: *jsc.JSGlobalObject, allocator: std.mem.Allocator, value: jsc.JSValue, is_async: bool, allow_string_object: bool) JSError!?StringOrBuffer { return switch (value.jsType()) { .String, .StringObject, @@ -258,15 +258,15 @@ pub const StringOrBuffer = union(enum) { }; } - pub fn fromJS(global: *JSC.JSGlobalObject, allocator: std.mem.Allocator, value: JSC.JSValue) JSError!?StringOrBuffer { + pub fn fromJS(global: *jsc.JSGlobalObject, allocator: std.mem.Allocator, value: jsc.JSValue) JSError!?StringOrBuffer { return fromJSMaybeAsync(global, allocator, value, false, true); } - pub fn fromJSWithEncoding(global: *JSC.JSGlobalObject, allocator: std.mem.Allocator, value: JSC.JSValue, encoding: Encoding) bun.JSError!?StringOrBuffer { + pub fn fromJSWithEncoding(global: *jsc.JSGlobalObject, allocator: std.mem.Allocator, value: jsc.JSValue, encoding: Encoding) bun.JSError!?StringOrBuffer { return fromJSWithEncodingMaybeAsync(global, allocator, value, encoding, false, true); } - pub fn fromJSWithEncodingMaybeAsync(global: *JSC.JSGlobalObject, allocator: std.mem.Allocator, value: JSC.JSValue, encoding: Encoding, is_async: bool, allow_string_object: bool) bun.JSError!?StringOrBuffer { + pub fn fromJSWithEncodingMaybeAsync(global: *jsc.JSGlobalObject, allocator: std.mem.Allocator, value: jsc.JSValue, encoding: Encoding, is_async: bool, allow_string_object: bool) bun.JSError!?StringOrBuffer { if (value.isCell() and value.jsType().isArrayBufferLike()) { return .{ .buffer = Buffer.fromTypedArray(global, value) }; } @@ -285,13 +285,13 @@ pub const StringOrBuffer = union(enum) { const out = str.encode(encoding); defer global.vm().reportExtraMemory(out.len); - return .{ .encoded_slice = JSC.ZigString.Slice.init(bun.default_allocator, out) }; + return .{ .encoded_slice = jsc.ZigString.Slice.init(bun.default_allocator, out) }; } return null; } - pub fn fromJSWithEncodingValue(global: *JSC.JSGlobalObject, allocator: std.mem.Allocator, value: JSC.JSValue, encoding_value: JSC.JSValue) bun.JSError!?StringOrBuffer { + pub fn fromJSWithEncodingValue(global: *jsc.JSGlobalObject, allocator: std.mem.Allocator, value: jsc.JSValue, encoding_value: jsc.JSValue) bun.JSError!?StringOrBuffer { const encoding: Encoding = brk: { if (!encoding_value.isCell()) break :brk .utf8; @@ -301,7 +301,7 @@ pub const StringOrBuffer = union(enum) { return fromJSWithEncoding(global, allocator, value, encoding); } - pub fn fromJSWithEncodingValueMaybeAsync(global: *JSC.JSGlobalObject, allocator: std.mem.Allocator, value: JSC.JSValue, encoding_value: JSC.JSValue, maybe_async: bool, allow_string_object: bool) bun.JSError!?StringOrBuffer { + pub fn fromJSWithEncodingValueMaybeAsync(global: *jsc.JSGlobalObject, allocator: std.mem.Allocator, value: jsc.JSValue, encoding_value: jsc.JSValue, maybe_async: bool, allow_string_object: bool) bun.JSError!?StringOrBuffer { const encoding: Encoding = brk: { if (!encoding_value.isCell()) break :brk .utf8; @@ -312,7 +312,7 @@ pub const StringOrBuffer = union(enum) { }; /// https://github.com/nodejs/node/blob/master/lib/buffer.js#L587 -/// See `JSC.WebCore.encoding` for encoding and decoding functions. +/// See `jsc.WebCore.encoding` for encoding and decoding functions. /// must match src/bun.js/bindings/BufferEncodingType.h pub const Encoding = enum(u8) { utf8, @@ -350,7 +350,7 @@ pub const Encoding = enum(u8) { }; } - pub fn fromJS(value: JSC.JSValue, global: *JSC.JSGlobalObject) JSError!?Encoding { + pub fn fromJS(value: jsc.JSValue, global: *jsc.JSGlobalObject) JSError!?Encoding { return map.fromJSCaseInsensitive(global, value); } @@ -359,7 +359,7 @@ pub const Encoding = enum(u8) { return strings.inMapCaseInsensitive(slice, map); } - pub fn assert(value: JSC.JSValue, globalObject: *JSC.JSGlobalObject, default: Encoding) bun.JSError!Encoding { + pub fn assert(value: jsc.JSValue, globalObject: *jsc.JSGlobalObject, default: Encoding) bun.JSError!Encoding { if (value.isFalsey()) { return default; } @@ -371,7 +371,7 @@ pub const Encoding = enum(u8) { return try fromJSWithDefaultOnEmpty(value, globalObject, default) orelse throwEncodingError(globalObject, value); } - pub fn fromJSWithDefaultOnEmpty(value: JSC.JSValue, globalObject: *JSC.JSGlobalObject, default: Encoding) bun.JSError!?Encoding { + pub fn fromJSWithDefaultOnEmpty(value: jsc.JSValue, globalObject: *jsc.JSGlobalObject, default: Encoding) bun.JSError!?Encoding { const str = try bun.String.fromJS(value, globalObject); defer str.deref(); if (str.isEmpty()) { @@ -380,34 +380,34 @@ pub const Encoding = enum(u8) { return str.inMapCaseInsensitive(Encoding.map); } - pub fn throwEncodingError(globalObject: *JSC.JSGlobalObject, value: JSC.JSValue) bun.JSError { + pub fn throwEncodingError(globalObject: *jsc.JSGlobalObject, value: jsc.JSValue) bun.JSError { return globalObject.ERR(.INVALID_ARG_VALUE, "encoding '{}' is an invalid encoding", .{value.fmtString(globalObject)}).throw(); } - pub fn encodeWithSize(encoding: Encoding, globalObject: *JSC.JSGlobalObject, comptime size: usize, input: *const [size]u8) bun.JSError!JSC.JSValue { + pub fn encodeWithSize(encoding: Encoding, globalObject: *jsc.JSGlobalObject, comptime size: usize, input: *const [size]u8) bun.JSError!jsc.JSValue { switch (encoding) { .base64 => { var buf: [std.base64.standard.Encoder.calcSize(size)]u8 = undefined; const len = bun.base64.encode(&buf, input); - return JSC.ZigString.init(buf[0..len]).toJS(globalObject); + return jsc.ZigString.init(buf[0..len]).toJS(globalObject); }, .base64url => { var buf: [std.base64.url_safe_no_pad.Encoder.calcSize(size)]u8 = undefined; const encoded = std.base64.url_safe_no_pad.Encoder.encode(&buf, input); - return JSC.ZigString.init(buf[0..encoded.len]).toJS(globalObject); + return jsc.ZigString.init(buf[0..encoded.len]).toJS(globalObject); }, .hex => { var buf: [size * 4]u8 = undefined; const out = std.fmt.bufPrint(&buf, "{}", .{std.fmt.fmtSliceHexLower(input)}) catch bun.outOfMemory(); - const result = JSC.ZigString.init(out).toJS(globalObject); + const result = jsc.ZigString.init(out).toJS(globalObject); return result; }, .buffer => { - return JSC.ArrayBuffer.createBuffer(globalObject, input); + return jsc.ArrayBuffer.createBuffer(globalObject, input); }, inline else => |enc| { - const res = JSC.WebCore.encoding.toStringComptime(input, globalObject, enc); + const res = jsc.WebCore.encoding.toStringComptime(input, globalObject, enc); if (res.isError()) { return globalObject.throwValue(res); } @@ -416,7 +416,7 @@ pub const Encoding = enum(u8) { } } - pub fn encodeWithMaxSize(encoding: Encoding, globalObject: *JSC.JSGlobalObject, comptime max_size: usize, input: []const u8) bun.JSError!JSC.JSValue { + pub fn encodeWithMaxSize(encoding: Encoding, globalObject: *jsc.JSGlobalObject, comptime max_size: usize, input: []const u8) bun.JSError!jsc.JSValue { switch (encoding) { .base64 => { var base64_buf: [std.base64.standard.Encoder.calcSize(max_size * 4)]u8 = undefined; @@ -429,19 +429,19 @@ pub const Encoding = enum(u8) { var buf: [std.base64.url_safe_no_pad.Encoder.calcSize(max_size * 4)]u8 = undefined; const encoded = std.base64.url_safe_no_pad.Encoder.encode(&buf, input); - return JSC.ZigString.init(buf[0..encoded.len]).toJS(globalObject); + return jsc.ZigString.init(buf[0..encoded.len]).toJS(globalObject); }, .hex => { var buf: [max_size * 4]u8 = undefined; const out = std.fmt.bufPrint(&buf, "{}", .{std.fmt.fmtSliceHexLower(input)}) catch bun.outOfMemory(); - const result = JSC.ZigString.init(out).toJS(globalObject); + const result = jsc.ZigString.init(out).toJS(globalObject); return result; }, .buffer => { - return JSC.ArrayBuffer.createBuffer(globalObject, input); + return jsc.ArrayBuffer.createBuffer(globalObject, input); }, inline else => |enc| { - const res = JSC.WebCore.encoding.toStringComptime(input, globalObject, enc); + const res = jsc.WebCore.encoding.toStringComptime(input, globalObject, enc); if (res.isError()) { return globalObject.throwValue(res); } @@ -451,14 +451,14 @@ pub const Encoding = enum(u8) { } } - extern fn WebCore_BufferEncodingType_toJS(globalObject: *JSC.JSGlobalObject, encoding: Encoding) JSC.JSValue; - pub fn toJS(encoding: Encoding, globalObject: *JSC.JSGlobalObject) JSC.JSValue { + extern fn WebCore_BufferEncodingType_toJS(globalObject: *jsc.JSGlobalObject, encoding: Encoding) jsc.JSValue; + pub fn toJS(encoding: Encoding, globalObject: *jsc.JSGlobalObject) jsc.JSValue { return WebCore_BufferEncodingType_toJS(globalObject, encoding); } }; /// This is used on the windows implementation of realpath, which is in javascript -pub fn jsAssertEncodingValid(global: *JSC.JSGlobalObject, call_frame: *JSC.CallFrame) bun.JSError!JSC.JSValue { +pub fn jsAssertEncodingValid(global: *jsc.JSGlobalObject, call_frame: *jsc.CallFrame) bun.JSError!jsc.JSValue { const value = call_frame.argument(0); _ = try Encoding.assert(value, global, .utf8); return .js_undefined; @@ -477,12 +477,12 @@ const PathOrBuffer = union(Tag) { pub fn CallbackTask(comptime Result: type) type { return struct { - callback: JSC.C.JSObjectRef, + callback: jsc.C.JSObjectRef, option: Option, success: bool = false, pub const Option = union { - err: JSC.SystemError, + err: jsc.SystemError, result: Result, }; }; @@ -493,7 +493,7 @@ pub const PathLike = union(enum) { buffer: Buffer, slice_with_underlying_string: bun.SliceWithUnderlyingString, threadsafe_string: bun.SliceWithUnderlyingString, - encoded_slice: JSC.ZigString.Slice, + encoded_slice: jsc.ZigString.Slice, pub fn estimatedSize(this: *const PathLike) usize { return switch (this.*) { @@ -617,11 +617,11 @@ pub const PathLike = union(enum) { return sliceZWithForceCopy(this, buf, false); } - pub fn fromJS(ctx: *JSC.JSGlobalObject, arguments: *ArgumentsSlice) bun.JSError!?PathLike { + pub fn fromJS(ctx: *jsc.JSGlobalObject, arguments: *ArgumentsSlice) bun.JSError!?PathLike { return fromJSWithAllocator(ctx, arguments, bun.default_allocator); } - pub fn fromJSWithAllocator(ctx: *JSC.JSGlobalObject, arguments: *ArgumentsSlice, allocator: std.mem.Allocator) bun.JSError!?PathLike { + pub fn fromJSWithAllocator(ctx: *jsc.JSGlobalObject, arguments: *ArgumentsSlice, allocator: std.mem.Allocator) bun.JSError!?PathLike { const arg = arguments.next() orelse return null; switch (arg.jsType()) { .Uint8Array, @@ -656,7 +656,7 @@ pub const PathLike = union(enum) { return try fromBunString(ctx, str, arguments.will_be_async, allocator); }, else => { - if (arg.as(JSC.DOMURL)) |domurl| { + if (arg.as(jsc.DOMURL)) |domurl| { var str: bun.String = domurl.fileSystemPath() catch |err| switch (err) { error.NotFileUrl => { return ctx.ERR(.INVALID_URL_SCHEME, "URL must be a non-empty \"file:\" path", .{}).throw(); @@ -682,7 +682,7 @@ pub const PathLike = union(enum) { } } - pub fn fromBunString(global: *JSC.JSGlobalObject, str: bun.String, will_be_async: bool, allocator: std.mem.Allocator) !PathLike { + pub fn fromBunString(global: *jsc.JSGlobalObject, str: bun.String, will_be_async: bool, allocator: std.mem.Allocator) !PathLike { try Valid.pathStringLength(str.length(), global); if (will_be_async) { @@ -718,7 +718,7 @@ pub const PathLike = union(enum) { }; pub const Valid = struct { - pub fn pathSlice(zig_str: JSC.ZigString.Slice, ctx: *JSC.JSGlobalObject) bun.JSError!void { + pub fn pathSlice(zig_str: jsc.ZigString.Slice, ctx: *jsc.JSGlobalObject) bun.JSError!void { switch (zig_str.len) { 0...bun.MAX_PATH_BYTES => return, else => { @@ -730,7 +730,7 @@ pub const Valid = struct { comptime unreachable; } - pub fn pathStringLength(len: usize, ctx: *JSC.JSGlobalObject) bun.JSError!void { + pub fn pathStringLength(len: usize, ctx: *jsc.JSGlobalObject) bun.JSError!void { switch (len) { 0...bun.MAX_PATH_BYTES => return, else => { @@ -742,11 +742,11 @@ pub const Valid = struct { comptime unreachable; } - pub fn pathString(zig_str: JSC.ZigString, ctx: *JSC.JSGlobalObject) bun.JSError!void { + pub fn pathString(zig_str: jsc.ZigString, ctx: *jsc.JSGlobalObject) bun.JSError!void { return pathStringLength(zig_str.len, ctx); } - pub fn pathBuffer(buffer: Buffer, ctx: *JSC.JSGlobalObject) bun.JSError!void { + pub fn pathBuffer(buffer: Buffer, ctx: *jsc.JSGlobalObject) bun.JSError!void { const slice = buffer.slice(); switch (slice.len) { 0 => { @@ -762,7 +762,7 @@ pub const Valid = struct { comptime unreachable; } - pub fn pathNullBytes(slice: []const u8, global: *JSC.JSGlobalObject) bun.JSError!void { + pub fn pathNullBytes(slice: []const u8, global: *jsc.JSGlobalObject) bun.JSError!void { if (bun.strings.indexOfChar(slice, 0) != null) { return global.ERR(.INVALID_ARG_VALUE, "The argument 'path' must be a string, Uint8Array, or URL without null bytes. Received {}", .{bun.fmt.quote(slice)}).throw(); } @@ -770,14 +770,14 @@ pub const Valid = struct { }; pub const VectorArrayBuffer = struct { - value: JSC.JSValue, + value: jsc.JSValue, buffers: std.ArrayList(bun.PlatformIOVec), - pub fn toJS(this: VectorArrayBuffer, _: *JSC.JSGlobalObject) JSC.JSValue { + pub fn toJS(this: VectorArrayBuffer, _: *jsc.JSGlobalObject) jsc.JSValue { return this.value; } - pub fn fromJS(globalObject: *JSC.JSGlobalObject, val: JSC.JSValue, allocator: std.mem.Allocator) bun.JSError!VectorArrayBuffer { + pub fn fromJS(globalObject: *jsc.JSGlobalObject, val: jsc.JSValue, allocator: std.mem.Allocator) bun.JSError!VectorArrayBuffer { if (!val.jsType().isArrayLike()) { return globalObject.throwInvalidArguments("Expected ArrayBufferView[]", .{}); } @@ -807,7 +807,7 @@ pub const VectorArrayBuffer = struct { } }; -pub fn modeFromJS(ctx: *JSC.JSGlobalObject, value: JSC.JSValue) bun.JSError!?Mode { +pub fn modeFromJS(ctx: *jsc.JSGlobalObject, value: jsc.JSValue) bun.JSError!?Mode { const mode_int = if (value.isNumber()) brk: { break :brk try node.validators.validateUint32(ctx, value, "mode", .{}, false); } else brk: { @@ -823,7 +823,7 @@ pub fn modeFromJS(ctx: *JSC.JSGlobalObject, value: JSC.JSValue) bun.JSError!?Mod // the example), specifies permissions for the group. The right-most // digit (5 in the example), specifies the permissions for others. - var zig_str = JSC.ZigString.Empty; + var zig_str = jsc.ZigString.Empty; try value.toZigString(&zig_str, ctx); var slice = zig_str.slice(); if (strings.hasPrefix(slice, "0o")) { @@ -831,7 +831,7 @@ pub fn modeFromJS(ctx: *JSC.JSGlobalObject, value: JSC.JSValue) bun.JSError!?Mod } break :brk std.fmt.parseInt(Mode, slice, 8) catch { - var formatter = bun.JSC.ConsoleObject.Formatter{ .globalThis = ctx }; + var formatter = bun.jsc.ConsoleObject.Formatter{ .globalThis = ctx }; defer formatter.deinit(); return ctx.throwValue(ctx.ERR(.INVALID_ARG_VALUE, "The argument 'mode' must be a 32-bit unsigned integer or an octal string. Received {}", .{value.toFmt(&formatter)}).toJS()); }; @@ -874,14 +874,14 @@ pub const PathOrFileDescriptor = union(Tag) { } } - pub fn hash(this: JSC.Node.PathOrFileDescriptor) u64 { + pub fn hash(this: jsc.Node.PathOrFileDescriptor) u64 { return switch (this) { .path => bun.hash(this.path.slice()), .fd => bun.hash(std.mem.asBytes(&this.fd)), }; } - pub fn format(this: JSC.Node.PathOrFileDescriptor, comptime fmt: []const u8, _: std.fmt.FormatOptions, writer: anytype) !void { + pub fn format(this: jsc.Node.PathOrFileDescriptor, comptime fmt: []const u8, _: std.fmt.FormatOptions, writer: anytype) !void { if (fmt.len != 0 and fmt[0] != 's') { @compileError("Unsupported format argument: '" ++ fmt ++ "'."); } @@ -891,7 +891,7 @@ pub const PathOrFileDescriptor = union(Tag) { } } - pub fn fromJS(ctx: *JSC.JSGlobalObject, arguments: *ArgumentsSlice, allocator: std.mem.Allocator) bun.JSError!?JSC.Node.PathOrFileDescriptor { + pub fn fromJS(ctx: *jsc.JSGlobalObject, arguments: *ArgumentsSlice, allocator: std.mem.Allocator) bun.JSError!?jsc.Node.PathOrFileDescriptor { const first = arguments.next() orelse return null; if (try bun.FD.fromJSValidated(first, ctx)) |fd| { @@ -899,7 +899,7 @@ pub const PathOrFileDescriptor = union(Tag) { return .{ .fd = fd }; } - return JSC.Node.PathOrFileDescriptor{ + return jsc.Node.PathOrFileDescriptor{ .path = try PathLike.fromJSWithAllocator(ctx, arguments, allocator) orelse return null, }; } @@ -996,7 +996,7 @@ pub const FileSystemFlags = enum(c_int) { .{ "SA+", O.APPEND | O.CREAT | O.RDWR | O.SYNC }, }); - pub fn fromJS(ctx: *JSC.JSGlobalObject, val: JSC.JSValue) bun.JSError!?FileSystemFlags { + pub fn fromJS(ctx: *jsc.JSGlobalObject, val: jsc.JSValue) bun.JSError!?FileSystemFlags { if (val.isNumber()) { if (!val.isInt32()) { return ctx.throwValue(ctx.ERR(.OUT_OF_RANGE, "The value of \"flags\" is out of range. It must be an integer. Received {d}", .{val.asNumber()}).toJS()); @@ -1035,7 +1035,7 @@ pub const FileSystemFlags = enum(c_int) { }, } - break :brk map.getWithEql(str, JSC.ZigString.eqlComptime) orelse break :brk null; + break :brk map.getWithEql(str, jsc.ZigString.eqlComptime) orelse break :brk null; } orelse { return ctx.throwInvalidArguments("Invalid flag '{any}'. Learn more at https://nodejs.org/api/fs.html#fs_file_system_flags", .{str}); }; @@ -1047,7 +1047,7 @@ pub const FileSystemFlags = enum(c_int) { } /// Equivalent of GetValidFileMode, which is used to implement fs.access and copyFile - pub fn fromJSNumberOnly(global: *JSC.JSGlobalObject, value: JSC.JSValue, comptime kind: enum { access, copy_file }) bun.JSError!FileSystemFlags { + pub fn fromJSNumberOnly(global: *jsc.JSGlobalObject, value: jsc.JSValue, comptime kind: enum { access, copy_file }) bun.JSError!FileSystemFlags { // Allow only int32 or null/undefined values. if (!value.isNumber()) { if (value.isUndefinedOrNull()) { @@ -1106,11 +1106,11 @@ pub const Dirent = struct { pub const Kind = std.fs.File.Kind; - extern fn Bun__JSDirentObjectConstructor(*JSC.JSGlobalObject) JSC.JSValue; + extern fn Bun__JSDirentObjectConstructor(*jsc.JSGlobalObject) jsc.JSValue; pub const getConstructor = Bun__JSDirentObjectConstructor; - extern fn Bun__Dirent__toJS(*JSC.JSGlobalObject, i32, *bun.String, *bun.String, cached_previous_path_jsvalue: ?*?*JSC.JSString) JSC.JSValue; - pub fn toJS(this: *Dirent, globalObject: *JSC.JSGlobalObject, cached_previous_path_jsvalue: ?*?*JSC.JSString) bun.JSError!JSC.JSValue { + extern fn Bun__Dirent__toJS(*jsc.JSGlobalObject, i32, *bun.String, *bun.String, cached_previous_path_jsvalue: ?*?*jsc.JSString) jsc.JSValue; + pub fn toJS(this: *Dirent, globalObject: *jsc.JSGlobalObject, cached_previous_path_jsvalue: ?*?*jsc.JSString) bun.JSError!jsc.JSValue { return bun.jsc.fromJSHostCall(globalObject, @src(), Bun__Dirent__toJS, .{ globalObject, switch (this.kind) { @@ -1130,7 +1130,7 @@ pub const Dirent = struct { }); } - pub fn toJSNewlyCreated(this: *Dirent, globalObject: *JSC.JSGlobalObject, previous_jsstring: ?*?*JSC.JSString) bun.JSError!JSC.JSValue { + pub fn toJSNewlyCreated(this: *Dirent, globalObject: *jsc.JSGlobalObject, previous_jsstring: ?*?*jsc.JSString) bun.JSError!jsc.JSValue { // Shouldn't techcnically be necessary. defer this.deref(); return this.toJS(globalObject, previous_jsstring); @@ -1143,13 +1143,13 @@ pub const Dirent = struct { }; pub const PathOrBlob = union(enum) { - path: JSC.Node.PathOrFileDescriptor, + path: jsc.Node.PathOrFileDescriptor, blob: Blob, - const Blob = JSC.WebCore.Blob; + const Blob = jsc.WebCore.Blob; - pub fn fromJSNoCopy(ctx: *JSC.JSGlobalObject, args: *JSC.CallFrame.ArgumentsSlice) bun.JSError!PathOrBlob { - if (try JSC.Node.PathOrFileDescriptor.fromJS(ctx, args, bun.default_allocator)) |path| { + pub fn fromJSNoCopy(ctx: *jsc.JSGlobalObject, args: *jsc.CallFrame.ArgumentsSlice) bun.JSError!PathOrBlob { + if (try jsc.Node.PathOrFileDescriptor.fromJS(ctx, args, bun.default_allocator)) |path| { return PathOrBlob{ .path = path, }; @@ -1167,19 +1167,20 @@ pub const PathOrBlob = union(enum) { } }; +const string = []const u8; + const std = @import("std"); const URL = @import("../../url.zig").URL; const bun = @import("bun"); const Environment = bun.Environment; -const JSC = bun.JSC; const JSError = bun.JSError; const Mode = bun.Mode; +const jsc = bun.jsc; const path_handler = bun.path; -const string = bun.string; const strings = bun.strings; const windows = bun.windows; -const ArgumentsSlice = JSC.CallFrame.ArgumentsSlice; +const ArgumentsSlice = jsc.CallFrame.ArgumentsSlice; const node = bun.api.node; const Buffer = node.Buffer; diff --git a/src/bun.js/node/util/parse_args.zig b/src/bun.js/node/util/parse_args.zig index e3870115e4..8dba5ac7e0 100644 --- a/src/bun.js/node/util/parse_args.zig +++ b/src/bun.js/node/util/parse_args.zig @@ -259,7 +259,7 @@ fn storeOption(globalThis: *JSGlobalObject, option_name: ValueRef, option_value: // We store based on the option value rather than option type, // preserving the users intent for author to deal with. - const new_value = if (value.isUndefined()) JSC.jsBoolean(!negative) else value; + const new_value = if (value.isUndefined()) jsc.jsBoolean(!negative) else value; const is_multiple = if (option_idx) |idx| options[idx].multiple else false; if (is_multiple) { @@ -282,7 +282,7 @@ fn storeOption(globalThis: *JSGlobalObject, option_name: ValueRef, option_value: fn parseOptionDefinitions(globalThis: *JSGlobalObject, options_obj: JSValue, option_definitions: *std.ArrayList(OptionDefinition)) bun.JSError!void { try validators.validateObject(globalThis, options_obj, "options", .{}, .{}); - var iter = try JSC.JSPropertyIterator(.{ .skip_empty_name = false, .include_value = true }).init( + var iter = try jsc.JSPropertyIterator(.{ .skip_empty_name = false, .include_value = true }).init( globalThis, // SAFETY: validateObject ensures it's an object options_obj.getObject().?, @@ -633,12 +633,12 @@ const ParseArgsState = struct { }; comptime { - const parseArgsFn = JSC.toJSHostFn(parseArgs); + const parseArgsFn = jsc.toJSHostFn(parseArgs); @export(&parseArgsFn, .{ .name = "Bun__NodeUtil__jsParseArgs" }); } -pub fn parseArgs(globalThis: *JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { - JSC.markBinding(@src()); +pub fn parseArgs(globalThis: *JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { + jsc.markBinding(@src()); const config_value = callframe.argumentsAsArray(1)[0]; // // Phase 0: parse the config object @@ -660,7 +660,7 @@ pub fn parseArgs(globalThis: *JSGlobalObject, callframe: *JSC.CallFrame) bun.JSE // Phase 0.B: Parse and validate config const config_strict: JSValue = (if (config) |c| try c.getOwn(globalThis, "strict") else null) orelse JSValue.jsBoolean(true); - var config_allow_positionals: JSValue = if (config) |c| try c.getOwn(globalThis, "allowPositionals") orelse JSC.jsBoolean(!config_strict.toBoolean()) else JSC.jsBoolean(!config_strict.toBoolean()); + var config_allow_positionals: JSValue = if (config) |c| try c.getOwn(globalThis, "allowPositionals") orelse jsc.jsBoolean(!config_strict.toBoolean()) else jsc.jsBoolean(!config_strict.toBoolean()); const config_return_tokens: JSValue = (if (config) |c| try c.getOwn(globalThis, "tokens") else null) orelse JSValue.jsBoolean(false); const config_allow_negative: JSValue = if (config) |c| try c.getOwn(globalThis, "allowNegative") orelse .false else .false; const config_options: JSValue = if (config) |c| try c.getOwn(globalThis, "options") orelse .js_undefined else .js_undefined; @@ -668,7 +668,7 @@ pub fn parseArgs(globalThis: *JSGlobalObject, callframe: *JSC.CallFrame) bun.JSE const strict = try validators.validateBoolean(globalThis, config_strict, "strict", .{}); if (config_allow_positionals.isUndefinedOrNull()) { - config_allow_positionals = JSC.jsBoolean(!strict); + config_allow_positionals = jsc.jsBoolean(!strict); } const allow_positionals = try validators.validateBoolean(globalThis, config_allow_positionals, "allowPositionals", .{}); @@ -695,8 +695,8 @@ pub fn parseArgs(globalThis: *JSGlobalObject, callframe: *JSC.CallFrame) bun.JSE // note that "values" needs to have a null prototype instead of Object, to avoid issues such as "values.toString"` being defined const values = JSValue.createEmptyObjectWithNullPrototype(globalThis); - const positionals = try JSC.JSValue.createEmptyArray(globalThis, 0); - const tokens: JSValue = if (return_tokens) try JSC.JSValue.createEmptyArray(globalThis, 0) else .js_undefined; + const positionals = try jsc.JSValue.createEmptyArray(globalThis, 0); + const tokens: JSValue = if (return_tokens) try jsc.JSValue.createEmptyArray(globalThis, 0) else .js_undefined; var state = ParseArgsState{ .globalThis = globalThis, @@ -743,6 +743,8 @@ pub fn parseArgs(globalThis: *JSGlobalObject, callframe: *JSC.CallFrame) bun.JSE return result; } +const string = []const u8; + const std = @import("std"); const validators = @import("./validators.zig"); @@ -755,9 +757,8 @@ const isOptionLikeValue = utils.isOptionLikeValue; const bun = @import("bun"); const String = bun.String; -const string = bun.string; -const JSC = bun.JSC; -const JSGlobalObject = JSC.JSGlobalObject; -const JSValue = JSC.JSValue; -const ZigString = JSC.ZigString; +const jsc = bun.jsc; +const JSGlobalObject = jsc.JSGlobalObject; +const JSValue = jsc.JSValue; +const ZigString = jsc.ZigString; diff --git a/src/bun.js/node/util/parse_args_utils.zig b/src/bun.js/node/util/parse_args_utils.zig index b535b66e46..96c7e17e4a 100644 --- a/src/bun.js/node/util/parse_args_utils.zig +++ b/src/bun.js/node/util/parse_args_utils.zig @@ -89,4 +89,4 @@ pub fn findOptionByShortName(short_name: String, options: []const OptionDefiniti const bun = @import("bun"); const String = bun.String; -const JSValue = bun.JSC.JSValue; +const JSValue = bun.jsc.JSValue; diff --git a/src/bun.js/node/util/validators.zig b/src/bun.js/node/util/validators.zig index 4e4ca69cf4..b47e98a92d 100644 --- a/src/bun.js/node/util/validators.zig +++ b/src/bun.js/node/util/validators.zig @@ -56,19 +56,19 @@ pub fn validateInteger(globalThis: *JSGlobalObject, value: JSValue, comptime nam comptime { if (min_value) |min| { - if (min < JSC.MIN_SAFE_INTEGER) { - @compileError("min_value must be greater than or equal to JSC.MIN_SAFE_INTEGER"); + if (min < jsc.MIN_SAFE_INTEGER) { + @compileError("min_value must be greater than or equal to jsc.MIN_SAFE_INTEGER"); } } if (max_value) |max| { - if (max > JSC.MAX_SAFE_INTEGER) { - @compileError("max_value must be less than or equal to JSC.MAX_SAFE_INTEGER"); + if (max > jsc.MAX_SAFE_INTEGER) { + @compileError("max_value must be less than or equal to jsc.MAX_SAFE_INTEGER"); } } } - const min: f64 = @floatFromInt(min_value orelse JSC.MIN_SAFE_INTEGER); - const max: f64 = @floatFromInt(max_value orelse JSC.MAX_SAFE_INTEGER); + const min: f64 = @floatFromInt(min_value orelse jsc.MIN_SAFE_INTEGER); + const max: f64 = @floatFromInt(max_value orelse jsc.MAX_SAFE_INTEGER); const num = value.asNumber(); @@ -80,8 +80,8 @@ pub fn validateInteger(globalThis: *JSGlobalObject, value: JSValue, comptime nam } pub fn validateIntegerOrBigInt(globalThis: *JSGlobalObject, value: JSValue, comptime name: string, min_value: ?i64, max_value: ?i64) bun.JSError!i64 { - const min = min_value orelse JSC.MIN_SAFE_INTEGER; - const max = max_value orelse JSC.MAX_SAFE_INTEGER; + const min = min_value orelse jsc.MIN_SAFE_INTEGER; + const max = max_value orelse jsc.MAX_SAFE_INTEGER; if (value.isBigInt()) { const num = value.to(i64); @@ -116,14 +116,14 @@ pub fn validateInt32(globalThis: *JSGlobalObject, value: JSValue, comptime name_ return throwErrInvalidArgType(globalThis, name_fmt, name_args, "number", value); } if (!value.isAnyInt()) { - var formatter = JSC.ConsoleObject.Formatter{ .globalThis = globalThis }; + var formatter = jsc.ConsoleObject.Formatter{ .globalThis = globalThis }; defer formatter.deinit(); return throwRangeError(globalThis, "The value of \"" ++ name_fmt ++ "\" is out of range. It must be an integer. Received {}", name_args ++ .{value.toFmt(&formatter)}); } const num = value.asNumber(); // Use floating point comparison here to ensure values out of i32 range get caught instead of clamp/truncated. if (num < @as(f64, @floatFromInt(min)) or num > @as(f64, @floatFromInt(max))) { - var formatter = JSC.ConsoleObject.Formatter{ .globalThis = globalThis }; + var formatter = jsc.ConsoleObject.Formatter{ .globalThis = globalThis }; defer formatter.deinit(); return throwRangeError(globalThis, "The value of \"" ++ name_fmt ++ "\" is out of range. It must be >= {d} and <= {d}. Received {}", name_args ++ .{ min, max, value.toFmt(&formatter) }); } @@ -135,7 +135,7 @@ pub fn validateUint32(globalThis: *JSGlobalObject, value: JSValue, comptime name return throwErrInvalidArgType(globalThis, name_fmt, name_args, "number", value); } if (!value.isAnyInt()) { - var formatter = JSC.ConsoleObject.Formatter{ .globalThis = globalThis }; + var formatter = jsc.ConsoleObject.Formatter{ .globalThis = globalThis }; defer formatter.deinit(); return throwRangeError(globalThis, "The value of \"" ++ name_fmt ++ "\" is out of range. It must be an integer. Received {}", name_args ++ .{value.toFmt(&formatter)}); } @@ -143,7 +143,7 @@ pub fn validateUint32(globalThis: *JSGlobalObject, value: JSValue, comptime name const min: i64 = if (greater_than_zero) 1 else 0; const max: i64 = @intCast(std.math.maxInt(u32)); if (num < min or num > max) { - var formatter = JSC.ConsoleObject.Formatter{ .globalThis = globalThis }; + var formatter = jsc.ConsoleObject.Formatter{ .globalThis = globalThis }; defer formatter.deinit(); return throwRangeError(globalThis, "The value of \"" ++ name_fmt ++ "\" is out of range. It must be >= {d} and <= {d}. Received {}", name_args ++ .{ min, max, value.toFmt(&formatter) }); } @@ -288,13 +288,14 @@ pub fn validateStringEnum(comptime T: type, globalThis: *JSGlobalObject, value: return throwErrInvalidArgTypeWithMessage(globalThis, name_fmt ++ " must be one of: {s}", name_args ++ .{values_info}); } +const string = []const u8; + const std = @import("std"); const bun = @import("bun"); const JSError = bun.JSError; -const string = bun.string; -const JSC = bun.JSC; -const JSGlobalObject = JSC.JSGlobalObject; -const JSValue = JSC.JSValue; -const ZigString = JSC.ZigString; +const jsc = bun.jsc; +const JSGlobalObject = jsc.JSGlobalObject; +const JSValue = jsc.JSValue; +const ZigString = jsc.ZigString; diff --git a/src/bun.js/node/win_watcher.zig b/src/bun.js/node/win_watcher.zig index c263ac02e8..8511d423a8 100644 --- a/src/bun.js/node/win_watcher.zig +++ b/src/bun.js/node/win_watcher.zig @@ -7,12 +7,12 @@ pub const PathWatcherManager = struct { const log = Output.scoped(.PathWatcherManager, false); watchers: bun.StringArrayHashMapUnmanaged(*PathWatcher) = .{}, - vm: *JSC.VirtualMachine, + vm: *jsc.VirtualMachine, deinit_on_last_watcher: bool = false, pub const new = bun.TrivialNew(PathWatcherManager); - pub fn init(vm: *JSC.VirtualMachine) *PathWatcherManager { + pub fn init(vm: *jsc.VirtualMachine) *PathWatcherManager { return PathWatcherManager.new(.{ .watchers = .{}, .vm = vm, @@ -160,7 +160,7 @@ pub const PathWatcher = struct { this.maybeDeinit(); } - pub fn init(manager: *PathWatcherManager, path: [:0]const u8, recursive: bool) bun.JSC.Maybe(*PathWatcher) { + pub fn init(manager: *PathWatcherManager, path: [:0]const u8, recursive: bool) bun.jsc.Maybe(*PathWatcher) { var outbuf: bun.PathBuffer = undefined; const event_path = switch (bun.sys.readlink(path, &outbuf)) { .err => |err| brk: { @@ -262,7 +262,7 @@ pub fn watch( comptime callback: PathWatcher.Callback, comptime updateEnd: PathWatcher.UpdateEndCallback, ctx: *anyopaque, -) bun.JSC.Maybe(*PathWatcher) { +) bun.jsc.Maybe(*PathWatcher) { comptime { if (callback != onPathUpdateFn) { @compileError("callback must be onPathUpdateFn"); @@ -289,21 +289,22 @@ pub fn watch( return .{ .result = watcher }; } +const string = []const u8; + const std = @import("std"); const EventType = @import("./path_watcher.zig").PathWatcher.EventType; const bun = @import("bun"); const Output = bun.Output; const Watcher = bun.Watcher; -const string = bun.string; -const JSC = bun.JSC; -const VirtualMachine = JSC.VirtualMachine; +const jsc = bun.jsc; +const VirtualMachine = jsc.VirtualMachine; -const FSWatcher = bun.JSC.Node.fs.Watcher; +const FSWatcher = bun.jsc.Node.fs.Watcher; const Event = FSWatcher.Event; -const onPathUpdateFn = JSC.Node.fs.Watcher.onPathUpdate; -const onUpdateEndFn = JSC.Node.fs.Watcher.onUpdateEnd; +const onPathUpdateFn = jsc.Node.fs.Watcher.onPathUpdate; +const onUpdateEndFn = jsc.Node.fs.Watcher.onUpdateEnd; const windows = bun.windows; const uv = windows.libuv; diff --git a/src/bun.js/node/zlib/NativeBrotli.zig b/src/bun.js/node/zlib/NativeBrotli.zig index 9469035023..60caa6906f 100644 --- a/src/bun.js/node/zlib/NativeBrotli.zig +++ b/src/bun.js/node/zlib/NativeBrotli.zig @@ -2,7 +2,7 @@ const RefCount = bun.ptr.RefCount(@This(), "ref_count", deinit, .{}); pub const ref = RefCount.ref; pub const deref = RefCount.deref; -pub const js = JSC.Codegen.JSNativeBrotli; +pub const js = jsc.Codegen.JSNativeBrotli; pub const toJS = js.toJS; pub const fromJS = js.fromJS; pub const fromJSDirect = js.fromJSDirect; @@ -18,17 +18,17 @@ pub const getOnError = impl.getOnError; pub const finalize = impl.finalize; ref_count: RefCount, -globalThis: *JSC.JSGlobalObject, +globalThis: *jsc.JSGlobalObject, stream: Context = .{}, write_result: ?[*]u32 = null, poll_ref: CountedKeepAlive = .{}, -this_value: JSC.Strong.Optional = .empty, +this_value: jsc.Strong.Optional = .empty, write_in_progress: bool = false, pending_close: bool = false, closed: bool = false, -task: JSC.WorkPoolTask = .{ .callback = undefined }, +task: jsc.WorkPoolTask = .{ .callback = undefined }, -pub fn constructor(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!*@This() { +pub fn constructor(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!*@This() { const arguments = callframe.argumentsUndef(1).ptr; var mode = arguments[0]; @@ -62,7 +62,7 @@ pub fn estimatedSize(this: *const @This()) usize { }; } -pub fn init(this: *@This(), globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { +pub fn init(this: *@This(), globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const arguments = callframe.argumentsUndef(3).slice(); const this_value = callframe.this(); if (arguments.len != 3) { @@ -80,7 +80,7 @@ pub fn init(this: *@This(), globalThis: *JSC.JSGlobalObject, callframe: *JSC.Cal var err = this.stream.init(); if (err.isError()) { try impl.emitError(this, globalThis, this_value, err); - return JSC.jsBoolean(false); + return jsc.jsBoolean(false); } const params_ = arguments[0].asArrayBuffer(globalThis).?.asU32(); @@ -93,13 +93,13 @@ pub fn init(this: *@This(), globalThis: *JSC.JSGlobalObject, callframe: *JSC.Cal err = this.stream.setParams(@intCast(i), d); if (err.isError()) { // try impl.emitError(this, globalThis, this_value, err); //XXX: onerror isn't set yet - return JSC.jsBoolean(false); + return jsc.jsBoolean(false); } } - return JSC.jsBoolean(true); + return jsc.jsBoolean(true); } -pub fn params(this: *@This(), globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { +pub fn params(this: *@This(), globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { _ = this; _ = globalThis; _ = callframe; @@ -267,4 +267,4 @@ const CountedKeepAlive = @import("../node_zlib_binding.zig").CountedKeepAlive; const Error = @import("../node_zlib_binding.zig").Error; const bun = @import("bun"); -const JSC = bun.JSC; +const jsc = bun.jsc; diff --git a/src/bun.js/node/zlib/NativeZlib.zig b/src/bun.js/node/zlib/NativeZlib.zig index da3c2ca4cc..98dea8ffda 100644 --- a/src/bun.js/node/zlib/NativeZlib.zig +++ b/src/bun.js/node/zlib/NativeZlib.zig @@ -2,7 +2,7 @@ const RefCount = bun.ptr.RefCount(@This(), "ref_count", deinit, .{}); pub const ref = RefCount.ref; pub const deref = RefCount.deref; -pub const js = JSC.Codegen.JSNativeZlib; +pub const js = jsc.Codegen.JSNativeZlib; pub const toJS = js.toJS; pub const fromJS = js.fromJS; pub const fromJSDirect = js.fromJSDirect; @@ -18,17 +18,17 @@ pub const getOnError = impl.getOnError; pub const finalize = impl.finalize; ref_count: RefCount, -globalThis: *JSC.JSGlobalObject, +globalThis: *jsc.JSGlobalObject, stream: Context = .{}, write_result: ?[*]u32 = null, poll_ref: CountedKeepAlive = .{}, -this_value: JSC.Strong.Optional = .empty, +this_value: jsc.Strong.Optional = .empty, write_in_progress: bool = false, pending_close: bool = false, closed: bool = false, -task: JSC.WorkPoolTask = .{ .callback = undefined }, +task: jsc.WorkPoolTask = .{ .callback = undefined }, -pub fn constructor(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!*@This() { +pub fn constructor(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!*@This() { const arguments = callframe.argumentsUndef(4).ptr; var mode = arguments[0]; @@ -58,7 +58,7 @@ pub fn estimatedSize(_: *const @This()) usize { return @sizeOf(@This()) + internal_state_size; } -pub fn init(this: *@This(), globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { +pub fn init(this: *@This(), globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const arguments = callframe.argumentsUndef(7).slice(); const this_value = callframe.this(); @@ -88,7 +88,7 @@ pub fn init(this: *@This(), globalThis: *JSC.JSGlobalObject, callframe: *JSC.Cal return .js_undefined; } -pub fn params(this: *@This(), globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { +pub fn params(this: *@This(), globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const arguments = callframe.argumentsUndef(2).slice(); if (arguments.len != 2) { @@ -365,4 +365,4 @@ const CountedKeepAlive = @import("../node_zlib_binding.zig").CountedKeepAlive; const Error = @import("../node_zlib_binding.zig").Error; const bun = @import("bun"); -const JSC = bun.JSC; +const jsc = bun.jsc; diff --git a/src/bun.js/node/zlib/NativeZstd.zig b/src/bun.js/node/zlib/NativeZstd.zig index 6b15369a34..140c41a96e 100644 --- a/src/bun.js/node/zlib/NativeZstd.zig +++ b/src/bun.js/node/zlib/NativeZstd.zig @@ -2,7 +2,7 @@ const RefCount = bun.ptr.RefCount(@This(), "ref_count", deinit, .{}); pub const ref = RefCount.ref; pub const deref = RefCount.deref; -pub const js = JSC.Codegen.JSNativeZstd; +pub const js = jsc.Codegen.JSNativeZstd; pub const toJS = js.toJS; pub const fromJS = js.fromJS; pub const fromJSDirect = js.fromJSDirect; @@ -18,17 +18,17 @@ pub const getOnError = impl.getOnError; pub const finalize = impl.finalize; ref_count: RefCount, -globalThis: *JSC.JSGlobalObject, +globalThis: *jsc.JSGlobalObject, stream: Context = .{}, write_result: ?[*]u32 = null, poll_ref: CountedKeepAlive = .{}, -this_value: JSC.Strong.Optional = .empty, +this_value: jsc.Strong.Optional = .empty, write_in_progress: bool = false, pending_close: bool = false, closed: bool = false, -task: JSC.WorkPoolTask = .{ .callback = undefined }, +task: jsc.WorkPoolTask = .{ .callback = undefined }, -pub fn constructor(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!*@This() { +pub fn constructor(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!*@This() { const arguments = callframe.argumentsAsArray(1); var mode = arguments[0]; @@ -60,7 +60,7 @@ pub fn estimatedSize(this: *const @This()) usize { }; } -pub fn init(this: *@This(), globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { +pub fn init(this: *@This(), globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const arguments = callframe.argumentsAsArray(4); const this_value = callframe.this(); if (callframe.argumentsCount() != 4) return globalThis.ERR(.MISSING_ARGS, "init(initParamsArray, pledgedSrcSize, writeState, processCallback)", .{}).throw(); @@ -99,7 +99,7 @@ pub fn init(this: *@This(), globalThis: *JSC.JSGlobalObject, callframe: *JSC.Cal return .jsBoolean(true); } -pub fn params(this: *@This(), globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { +pub fn params(this: *@This(), globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { _ = this; _ = globalThis; _ = callframe; @@ -261,4 +261,4 @@ const CountedKeepAlive = @import("../node_zlib_binding.zig").CountedKeepAlive; const Error = @import("../node_zlib_binding.zig").Error; const bun = @import("bun"); -const JSC = bun.JSC; +const jsc = bun.jsc; diff --git a/src/bun.js/rare_data.zig b/src/bun.js/rare_data.zig index de9a3eccb8..5bb371352e 100644 --- a/src/bun.js/rare_data.zig +++ b/src/bun.js/rare_data.zig @@ -19,7 +19,7 @@ cleanup_hooks: std.ArrayListUnmanaged(CleanupHook) = .{}, file_polls_: ?*Async.FilePoll.Store = null, -global_dns_data: ?*bun.api.DNS.GlobalData = null, +global_dns_data: ?*bun.api.dns.GlobalData = null, spawn_ipc_usockets_context: ?*uws.SocketContext = null, @@ -34,7 +34,7 @@ temp_pipe_read_buffer: ?*PipeReadBuffer = null, aws_signature_cache: AWSSignatureCache = .{}, -s3_default_client: JSC.Strong.Optional = .empty, +s3_default_client: jsc.Strong.Optional = .empty, default_csrf_secret: []const u8 = "", valkey_context: ValkeyContext = .{}, @@ -147,13 +147,13 @@ pub fn mimeTypeFromString(this: *RareData, allocator: std.mem.Allocator, str: [] pub const HotMap = struct { _map: bun.StringArrayHashMap(Entry), - const HTTPServer = JSC.API.HTTPServer; - const HTTPSServer = JSC.API.HTTPSServer; - const DebugHTTPServer = JSC.API.DebugHTTPServer; - const DebugHTTPSServer = JSC.API.DebugHTTPSServer; - const TCPSocket = JSC.API.TCPSocket; - const TLSSocket = JSC.API.TLSSocket; - const Listener = JSC.API.Listener; + const HTTPServer = jsc.API.HTTPServer; + const HTTPSServer = jsc.API.HTTPSServer; + const DebugHTTPServer = jsc.API.DebugHTTPServer; + const DebugHTTPSServer = jsc.API.DebugHTTPSServer; + const TCPSocket = jsc.API.TCPSocket; + const TLSSocket = jsc.API.TLSSocket; + const Listener = jsc.API.Listener; const Entry = bun.TaggedPointerUnion(.{ HTTPServer, HTTPSServer, @@ -199,7 +199,7 @@ pub const HotMap = struct { } }; -pub fn filePolls(this: *RareData, vm: *JSC.VirtualMachine) *Async.FilePoll.Store { +pub fn filePolls(this: *RareData, vm: *jsc.VirtualMachine) *Async.FilePoll.Store { return this.file_polls_ orelse { this.file_polls_ = vm.allocator.create(Async.FilePoll.Store) catch unreachable; this.file_polls_.?.* = Async.FilePoll.Store.init(); @@ -268,7 +268,7 @@ pub const EntropyCache = struct { pub const CleanupHook = struct { ctx: ?*anyopaque, func: Function, - globalThis: *JSC.JSGlobalObject, + globalThis: *jsc.JSGlobalObject, pub fn eql(self: CleanupHook, other: CleanupHook) bool { return self.ctx == other.ctx and self.func == other.func and self.globalThis == other.globalThis; @@ -279,7 +279,7 @@ pub const CleanupHook = struct { } pub fn init( - globalThis: *JSC.JSGlobalObject, + globalThis: *jsc.JSGlobalObject, ctx: ?*anyopaque, func: CleanupHook.Function, ) CleanupHook { @@ -295,7 +295,7 @@ pub const CleanupHook = struct { pub fn pushCleanupHook( this: *RareData, - globalThis: *JSC.JSGlobalObject, + globalThis: *jsc.JSGlobalObject, ctx: ?*anyopaque, func: CleanupHook.Function, ) void { @@ -310,7 +310,7 @@ pub fn boringEngine(rare: *RareData) *BoringSSL.ENGINE { } pub fn stderr(rare: *RareData) *Blob.Store { - bun.Analytics.Features.@"Bun.stderr" += 1; + bun.analytics.Features.@"Bun.stderr" += 1; return rare.stderr_store orelse brk: { var mode: bun.Mode = 0; const fd = bun.FD.fromUV(2); @@ -342,7 +342,7 @@ pub fn stderr(rare: *RareData) *Blob.Store { } pub fn stdout(rare: *RareData) *Blob.Store { - bun.Analytics.Features.@"Bun.stdout" += 1; + bun.analytics.Features.@"Bun.stdout" += 1; return rare.stdout_store orelse brk: { var mode: bun.Mode = 0; const fd = bun.FD.fromUV(1); @@ -372,7 +372,7 @@ pub fn stdout(rare: *RareData) *Blob.Store { } pub fn stdin(rare: *RareData) *Blob.Store { - bun.Analytics.Features.@"Bun.stdin" += 1; + bun.analytics.Features.@"Bun.stdin" += 1; return rare.stdin_store orelse brk: { var mode: bun.Mode = 0; const fd = bun.FD.fromUV(0); @@ -405,7 +405,7 @@ const StdinFdType = enum(i32) { socket = 2, }; -pub export fn Bun__Process__getStdinFdType(vm: *JSC.VirtualMachine, fd: i32) StdinFdType { +pub export fn Bun__Process__getStdinFdType(vm: *jsc.VirtualMachine, fd: i32) StdinFdType { const mode = switch (fd) { 0 => vm.rareData().stdin().data.file.mode, 1 => vm.rareData().stdout().data.file.mode, @@ -421,7 +421,7 @@ pub export fn Bun__Process__getStdinFdType(vm: *JSC.VirtualMachine, fd: i32) Std } } -pub fn spawnIPCContext(rare: *RareData, vm: *JSC.VirtualMachine) *uws.SocketContext { +pub fn spawnIPCContext(rare: *RareData, vm: *jsc.VirtualMachine) *uws.SocketContext { if (rare.spawn_ipc_usockets_context) |ctx| { return ctx; } @@ -432,28 +432,28 @@ pub fn spawnIPCContext(rare: *RareData, vm: *JSC.VirtualMachine) *uws.SocketCont return ctx; } -pub fn globalDNSResolver(rare: *RareData, vm: *JSC.VirtualMachine) *api.DNS.DNSResolver { +pub fn globalDNSResolver(rare: *RareData, vm: *jsc.VirtualMachine) *api.dns.Resolver { if (rare.global_dns_data == null) { - rare.global_dns_data = api.DNS.GlobalData.init(vm.allocator, vm); + rare.global_dns_data = api.dns.GlobalData.init(vm.allocator, vm); rare.global_dns_data.?.resolver.ref(); // live forever } return &rare.global_dns_data.?.resolver; } -pub fn nodeFSStatWatcherScheduler(rare: *RareData, vm: *JSC.VirtualMachine) bun.ptr.RefPtr(StatWatcherScheduler) { +pub fn nodeFSStatWatcherScheduler(rare: *RareData, vm: *jsc.VirtualMachine) bun.ptr.RefPtr(StatWatcherScheduler) { return (rare.node_fs_stat_watcher_scheduler orelse init: { rare.node_fs_stat_watcher_scheduler = StatWatcherScheduler.init(vm); break :init rare.node_fs_stat_watcher_scheduler.?; }).dupeRef(); } -pub fn s3DefaultClient(rare: *RareData, globalThis: *JSC.JSGlobalObject) JSC.JSValue { +pub fn s3DefaultClient(rare: *RareData, globalThis: *jsc.JSGlobalObject) jsc.JSValue { return rare.s3_default_client.get() orelse { const vm = globalThis.bunVM(); var aws_options = bun.S3.S3Credentials.getCredentialsWithOptions(vm.transpiler.env.getS3Credentials(), .{}, null, null, null, globalThis) catch bun.outOfMemory(); defer aws_options.deinit(); - const client = JSC.WebCore.S3Client.new(.{ + const client = jsc.WebCore.S3Client.new(.{ .credentials = aws_options.credentials.dupe(), .options = aws_options.options, .acl = aws_options.acl, @@ -518,11 +518,11 @@ const ValkeyContext = @import("../valkey/valkey.zig").ValkeyContext; const bun = @import("bun"); const Async = bun.Async; -const JSC = bun.JSC; const Output = bun.Output; const Syscall = bun.sys; const api = bun.api; const default_allocator = bun.default_allocator; +const jsc = bun.jsc; const uws = bun.uws; const BoringSSL = bun.BoringSSL.c; -const Blob = JSC.WebCore.Blob; +const Blob = jsc.WebCore.Blob; diff --git a/src/bun.js/test/diff_format.zig b/src/bun.js/test/diff_format.zig index aa1585b0af..b26d5f172b 100644 --- a/src/bun.js/test/diff_format.zig +++ b/src/bun.js/test/diff_format.zig @@ -282,6 +282,8 @@ pub const DiffFormatter = struct { } }; +const string = []const u8; + const DiffMatchPatch = @import("../../deps/diffz/DiffMatchPatch.zig"); const std = @import("std"); @@ -289,9 +291,8 @@ const bun = @import("bun"); const MutableString = bun.MutableString; const Output = bun.Output; const default_allocator = bun.default_allocator; -const string = bun.string; -const JSC = bun.JSC; -const ConsoleObject = JSC.ConsoleObject; -const JSGlobalObject = JSC.JSGlobalObject; -const JSValue = JSC.JSValue; +const jsc = bun.jsc; +const ConsoleObject = jsc.ConsoleObject; +const JSGlobalObject = jsc.JSGlobalObject; +const JSValue = jsc.JSValue; diff --git a/src/bun.js/test/expect.zig b/src/bun.js/test/expect.zig index 40c2de1c69..7fdbaa504e 100644 --- a/src/bun.js/test/expect.zig +++ b/src/bun.js/test/expect.zig @@ -31,7 +31,7 @@ pub fn getMatcherFlags(comptime T: type, value: JSValue) Expect.Flags { /// https://jestjs.io/docs/expect // To support async tests, we need to track the test ID pub const Expect = struct { - pub const js = JSC.Codegen.JSExpect; + pub const js = jsc.Codegen.JSExpect; pub const toJS = js.toJS; pub const fromJS = js.fromJS; pub const fromJSDirect = js.fromJSDirect; @@ -195,7 +195,7 @@ pub const Expect = struct { .resolves => {}, .rejects => { if (!silent) { - var formatter = JSC.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; + var formatter = jsc.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; defer formatter.deinit(); const message = "Expected promise that rejects\nReceived promise that resolved: {any}\n"; return throwPrettyMatcherError(globalThis, custom_label, matcher_name, matcher_params, flags, message, .{value.toFmt(&formatter)}); @@ -208,7 +208,7 @@ pub const Expect = struct { .rejects => {}, .resolves => { if (!silent) { - var formatter = JSC.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; + var formatter = jsc.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; defer formatter.deinit(); const message = "Expected promise that resolves\nReceived promise that rejected: {any}\n"; return throwPrettyMatcherError(globalThis, custom_label, matcher_name, matcher_params, flags, message, .{value.toFmt(&formatter)}); @@ -224,7 +224,7 @@ pub const Expect = struct { return newValue; } else { if (!silent) { - var formatter = JSC.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; + var formatter = jsc.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; defer formatter.deinit(); const message = "Expected promise\nReceived: {any}\n"; return throwPrettyMatcherError(globalThis, custom_label, matcher_name, matcher_params, flags, message, .{value.toFmt(&formatter)}); @@ -499,7 +499,7 @@ pub const Expect = struct { if (pass) return .js_undefined; // handle failure - var formatter = JSC.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; + var formatter = jsc.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; defer formatter.deinit(); switch (this.custom_label.isEmpty()) { @@ -556,18 +556,18 @@ pub const Expect = struct { const value: JSValue = try this.getValue(globalThis, thisValue, "toHaveLength", "expected"); if (!value.isObject() and !value.isString()) { - var fmt = JSC.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; + var fmt = jsc.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; return globalThis.throw("Received value does not have a length property: {any}", .{value.toFmt(&fmt)}); } if (!expected.isNumber()) { - var fmt = JSC.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; + var fmt = jsc.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; return globalThis.throw("Expected value must be a non-negative integer: {any}", .{expected.toFmt(&fmt)}); } const expected_length: f64 = expected.asNumber(); if (@round(expected_length) != expected_length or std.math.isInf(expected_length) or std.math.isNan(expected_length) or expected_length < 0) { - var fmt = JSC.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; + var fmt = jsc.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; return globalThis.throw("Expected value must be a non-negative integer: {any}", .{expected.toFmt(&fmt)}); } @@ -577,7 +577,7 @@ pub const Expect = struct { const actual_length = try value.getLengthIfPropertyExistsInternal(globalThis); if (actual_length == std.math.inf(f64)) { - var fmt = JSC.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; + var fmt = jsc.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; return globalThis.throw("Received value does not have a length property: {any}", .{value.toFmt(&fmt)}); } else if (std.math.isNan(actual_length)) { return globalThis.throw("Received value has non-number length property: {}", .{actual_length}); @@ -648,7 +648,7 @@ pub const Expect = struct { }; try list_value.forEach(globalThis, &expected_entry, struct { pub fn sameValueIterator( - _: *JSC.VM, + _: *jsc.VM, _: *JSGlobalObject, entry_: ?*anyopaque, item: JSValue, @@ -669,7 +669,7 @@ pub const Expect = struct { if (pass) return .js_undefined; // handle failure - var formatter = JSC.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; + var formatter = jsc.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; defer formatter.deinit(); const value_fmt = list_value.toFmt(&formatter); const expected_fmt = expected.toFmt(&formatter); @@ -744,7 +744,7 @@ pub const Expect = struct { }; try value.forEach(globalThis, &expected_entry, struct { pub fn sameValueIterator( - _: *JSC.VM, + _: *jsc.VM, _: *JSGlobalObject, entry_: ?*anyopaque, item: JSValue, @@ -764,7 +764,7 @@ pub const Expect = struct { if (pass) return .js_undefined; // handle failure - var formatter = JSC.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; + var formatter = jsc.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; defer formatter.deinit(); const value_fmt = value.toFmt(&formatter); const expected_fmt = expected.toFmt(&formatter); @@ -800,7 +800,7 @@ pub const Expect = struct { const expected = arguments[0]; expected.ensureStillAlive(); const value: JSValue = try this.getValue(globalThis, thisValue, "toContainKey", "expected"); - var formatter = JSC.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; + var formatter = jsc.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; defer formatter.deinit(); const not = this.flags.not; @@ -879,7 +879,7 @@ pub const Expect = struct { if (pass) return thisValue; // handle failure - var formatter = JSC.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; + var formatter = jsc.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; defer formatter.deinit(); const value_fmt = value.toFmt(&formatter); const expected_fmt = expected.toFmt(&formatter); @@ -944,7 +944,7 @@ pub const Expect = struct { if (pass) return thisValue; // handle failure - var formatter = JSC.ConsoleObject.Formatter{ .globalThis = globalObject, .quote_strings = true }; + var formatter = jsc.ConsoleObject.Formatter{ .globalThis = globalObject, .quote_strings = true }; defer formatter.deinit(); const value_fmt = keys.toFmt(&formatter); const expected_fmt = expected.toFmt(&formatter); @@ -1005,7 +1005,7 @@ pub const Expect = struct { if (pass) return thisValue; // handle failure - var formatter = JSC.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; + var formatter = jsc.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; defer formatter.deinit(); const value_fmt = value.toFmt(&formatter); const expected_fmt = expected.toFmt(&formatter); @@ -1060,7 +1060,7 @@ pub const Expect = struct { if (pass) return thisValue; // handle failure - var formatter = JSC.ConsoleObject.Formatter{ .globalThis = globalObject, .quote_strings = true }; + var formatter = jsc.ConsoleObject.Formatter{ .globalThis = globalObject, .quote_strings = true }; defer formatter.deinit(); const value_fmt = value.toFmt(&formatter); const expected_fmt = expected.toFmt(&formatter); @@ -1124,7 +1124,7 @@ pub const Expect = struct { if (pass) return thisValue; // handle failure - var formatter = JSC.ConsoleObject.Formatter{ .globalThis = globalObject, .quote_strings = true }; + var formatter = jsc.ConsoleObject.Formatter{ .globalThis = globalObject, .quote_strings = true }; defer formatter.deinit(); const value_fmt = value.toFmt(&formatter); const expected_fmt = expected.toFmt(&formatter); @@ -1194,7 +1194,7 @@ pub const Expect = struct { if (pass) return thisValue; // handle failure - var formatter = JSC.ConsoleObject.Formatter{ .globalThis = globalObject, .quote_strings = true }; + var formatter = jsc.ConsoleObject.Formatter{ .globalThis = globalObject, .quote_strings = true }; defer formatter.deinit(); const value_fmt = value.toFmt(&formatter); const expected_fmt = expected.toFmt(&formatter); @@ -1258,7 +1258,7 @@ pub const Expect = struct { if (pass) return thisValue; // handle failure - var formatter = JSC.ConsoleObject.Formatter{ .globalThis = globalObject, .quote_strings = true }; + var formatter = jsc.ConsoleObject.Formatter{ .globalThis = globalObject, .quote_strings = true }; defer formatter.deinit(); const value_fmt = value.toFmt(&formatter); const expected_fmt = expected.toFmt(&formatter); @@ -1342,7 +1342,7 @@ pub const Expect = struct { }; try value.forEach(globalThis, &expected_entry, struct { pub fn deepEqualsIterator( - _: *JSC.VM, + _: *jsc.VM, _: *JSGlobalObject, entry_: ?*anyopaque, item: JSValue, @@ -1362,7 +1362,7 @@ pub const Expect = struct { if (pass) return thisValue; // handle failure - var formatter = JSC.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; + var formatter = jsc.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; defer formatter.deinit(); const value_fmt = value.toFmt(&formatter); const expected_fmt = expected.toFmt(&formatter); @@ -1395,7 +1395,7 @@ pub const Expect = struct { if (pass) return .js_undefined; // handle failure - var formatter = JSC.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; + var formatter = jsc.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; defer formatter.deinit(); const value_fmt = value.toFmt(&formatter); if (not) { @@ -1424,7 +1424,7 @@ pub const Expect = struct { if (pass) return .js_undefined; // handle failure - var formatter = JSC.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; + var formatter = jsc.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; defer formatter.deinit(); const value_fmt = value.toFmt(&formatter); if (not) { @@ -1457,7 +1457,7 @@ pub const Expect = struct { if (pass) return .js_undefined; // handle failure - var formatter = JSC.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; + var formatter = jsc.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; defer formatter.deinit(); const value_fmt = value.toFmt(&formatter); if (not) { @@ -1485,7 +1485,7 @@ pub const Expect = struct { if (pass) return .js_undefined; // handle failure - var formatter = JSC.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; + var formatter = jsc.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; defer formatter.deinit(); const value_fmt = value.toFmt(&formatter); if (not) { @@ -1513,7 +1513,7 @@ pub const Expect = struct { if (pass) return .js_undefined; // handle failure - var formatter = JSC.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; + var formatter = jsc.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; defer formatter.deinit(); const value_fmt = value.toFmt(&formatter); if (not) { @@ -1546,7 +1546,7 @@ pub const Expect = struct { if (pass) return .js_undefined; // handle failure - var formatter = JSC.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; + var formatter = jsc.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; defer formatter.deinit(); const value_fmt = value.toFmt(&formatter); if (not) { @@ -1677,7 +1677,7 @@ pub const Expect = struct { if (pass) return .js_undefined; // handle failure - var formatter = JSC.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; + var formatter = jsc.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; defer formatter.deinit(); if (not) { if (expected_property != null) { @@ -1761,7 +1761,7 @@ pub const Expect = struct { if (pass) return .js_undefined; // handle failure - var formatter = JSC.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; + var formatter = jsc.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; defer formatter.deinit(); const value_fmt = value.toFmt(&formatter); if (not) { @@ -1818,7 +1818,7 @@ pub const Expect = struct { if (pass) return .js_undefined; // handle failure - var formatter = JSC.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; + var formatter = jsc.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; defer formatter.deinit(); const value_fmt = value.toFmt(&formatter); const expected_fmt = other_value.toFmt(&formatter); @@ -1878,7 +1878,7 @@ pub const Expect = struct { if (pass) return .js_undefined; // handle failure - var formatter = JSC.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; + var formatter = jsc.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; defer formatter.deinit(); const value_fmt = value.toFmt(&formatter); const expected_fmt = other_value.toFmt(&formatter); @@ -1938,7 +1938,7 @@ pub const Expect = struct { if (pass) return .js_undefined; // handle failure - var formatter = JSC.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; + var formatter = jsc.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; defer formatter.deinit(); const value_fmt = value.toFmt(&formatter); const expected_fmt = other_value.toFmt(&formatter); @@ -1998,7 +1998,7 @@ pub const Expect = struct { if (pass) return .js_undefined; // handle failure - var formatter = JSC.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; + var formatter = jsc.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; defer formatter.deinit(); const value_fmt = value.toFmt(&formatter); const expected_fmt = other_value.toFmt(&formatter); @@ -2070,7 +2070,7 @@ pub const Expect = struct { if (pass) return .js_undefined; - var formatter = JSC.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; + var formatter = jsc.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; defer formatter.deinit(); const expected_fmt = expected_.toFmt(&formatter); @@ -2130,7 +2130,7 @@ pub const Expect = struct { if (pass) return .js_undefined; // handle failure - var formatter = JSC.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; + var formatter = jsc.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; defer formatter.deinit(); const value_fmt = value.toFmt(&formatter); if (not) { @@ -2158,7 +2158,7 @@ pub const Expect = struct { } const value = arguments[0]; if (value.isUndefinedOrNull() or !value.isObject() and !value.isString()) { - var fmt = JSC.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; + var fmt = jsc.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; return globalThis.throw("Expected value must be string or Error: {any}", .{value.toFmt(&fmt)}); } if (value.isObject()) { @@ -2188,7 +2188,7 @@ pub const Expect = struct { if (!did_throw) return .js_undefined; const result: JSValue = result_.?; - var formatter = JSC.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; + var formatter = jsc.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; defer formatter.deinit(); if (expected_value == .zero or expected_value.isUndefined()) { @@ -2296,7 +2296,7 @@ pub const Expect = struct { } // error: message from received error does not match expected string - var formatter = JSC.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; + var formatter = jsc.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; defer formatter.deinit(); const signature = comptime getSignature("toThrow", "expected", false); @@ -2322,7 +2322,7 @@ pub const Expect = struct { } // error: message from received error does not match expected pattern - var formatter = JSC.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; + var formatter = jsc.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; defer formatter.deinit(); if (_received_message) |received_message| { @@ -2351,7 +2351,7 @@ pub const Expect = struct { return .js_undefined; } - var formatter = JSC.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; + var formatter = jsc.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; defer formatter.deinit(); const received_fmt = result.toFmt(&formatter); const expected_fmt = expected_value.toFmt(&formatter); @@ -2369,7 +2369,7 @@ pub const Expect = struct { } // error: message from received error does not match expected error message. - var formatter = JSC.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; + var formatter = jsc.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; defer formatter.deinit(); if (_received_message) |received_message| { @@ -2386,7 +2386,7 @@ pub const Expect = struct { if (result.isInstanceOf(globalThis, expected_value)) return .js_undefined; // error: received error not instance of received error constructor - var formatter = JSC.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; + var formatter = jsc.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; defer formatter.deinit(); var expected_class = ZigString.Empty; var received_class = ZigString.Empty; @@ -2418,7 +2418,7 @@ pub const Expect = struct { // did not throw const result = return_value_from_function; - var formatter = JSC.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; + var formatter = jsc.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; defer formatter.deinit(); const received_line = "Received function did not throw\nReceived value: {any}\n"; @@ -2890,14 +2890,14 @@ pub const Expect = struct { const fmt = signature ++ "\n\nExpected propertyMatchers to match properties from received object" ++ "\n\nReceived: {any}\n"; - var formatter = JSC.ConsoleObject.Formatter{ .globalThis = globalThis }; + var formatter = jsc.ConsoleObject.Formatter{ .globalThis = globalThis }; defer formatter.deinit(); return globalThis.throwPretty(fmt, .{value.toFmt(&formatter)}); } } value.jestSnapshotPrettyFormat(pretty_value, globalThis) catch { - var formatter = JSC.ConsoleObject.Formatter{ .globalThis = globalThis }; + var formatter = jsc.ConsoleObject.Formatter{ .globalThis = globalThis }; defer formatter.deinit(); return globalThis.throw("Failed to pretty format value: {s}", .{value.toFmt(&formatter)}); }; @@ -2908,7 +2908,7 @@ pub const Expect = struct { try this.matchAndFmtSnapshot(globalThis, value, property_matchers, &pretty_value, fn_name); const existing_value = Jest.runner.?.snapshots.getOrPut(this, pretty_value.slice(), hint) catch |err| { - var formatter = JSC.ConsoleObject.Formatter{ .globalThis = globalThis }; + var formatter = jsc.ConsoleObject.Formatter{ .globalThis = globalThis }; defer formatter.deinit(); const test_file_path = Jest.runner.?.files.get(this.testScope().?.describe.file_id).source.path.text; return switch (err) { @@ -2951,7 +2951,7 @@ pub const Expect = struct { const not = this.flags.not; var pass = false; - var formatter = JSC.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; + var formatter = jsc.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; defer formatter.deinit(); const actual_length = try value.getLengthIfPropertyExistsInternal(globalThis); @@ -2962,7 +2962,7 @@ pub const Expect = struct { var any_properties_in_iterator = false; try value.forEach(globalThis, &any_properties_in_iterator, struct { pub fn anythingInIterator( - _: *JSC.VM, + _: *jsc.VM, _: *JSGlobalObject, any_: ?*anyopaque, _: JSValue, @@ -2975,7 +2975,7 @@ pub const Expect = struct { const cell = value.toCell() orelse { return globalThis.throwTypeError("Expected value to be a string, object, or iterable", .{}); }; - var props_iter = try JSC.JSPropertyIterator(.{ + var props_iter = try jsc.JSPropertyIterator(.{ .skip_empty_name = false, .own_properties_only = false, .include_value = true, @@ -3033,7 +3033,7 @@ pub const Expect = struct { if (not) pass = !pass; if (pass) return thisValue; - var formatter = JSC.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; + var formatter = jsc.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; defer formatter.deinit(); const received = value.toFmt(&formatter); @@ -3059,7 +3059,7 @@ pub const Expect = struct { if (pass) return .js_undefined; - var formatter = JSC.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; + var formatter = jsc.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; defer formatter.deinit(); const received = value.toFmt(&formatter); @@ -3085,7 +3085,7 @@ pub const Expect = struct { if (pass) return .js_undefined; - var formatter = JSC.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; + var formatter = jsc.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; defer formatter.deinit(); const received = value.toFmt(&formatter); @@ -3126,7 +3126,7 @@ pub const Expect = struct { if (not) pass = !pass; if (pass) return .js_undefined; - var formatter = JSC.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; + var formatter = jsc.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; defer formatter.deinit(); const received = value.toFmt(&formatter); @@ -3152,7 +3152,7 @@ pub const Expect = struct { if (pass) return .js_undefined; - var formatter = JSC.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; + var formatter = jsc.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; defer formatter.deinit(); const received = value.toFmt(&formatter); @@ -3223,7 +3223,7 @@ pub const Expect = struct { if (not) pass = !pass; if (pass) return .js_undefined; - var formatter = JSC.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; + var formatter = jsc.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; defer formatter.deinit(); const received = value.toFmt(&formatter); const expected_str = expected.toFmt(&formatter); @@ -3250,7 +3250,7 @@ pub const Expect = struct { if (pass) return .js_undefined; - var formatter = JSC.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; + var formatter = jsc.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; defer formatter.deinit(); const received = value.toFmt(&formatter); @@ -3276,7 +3276,7 @@ pub const Expect = struct { if (pass) return .js_undefined; - var formatter = JSC.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; + var formatter = jsc.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; defer formatter.deinit(); const received = value.toFmt(&formatter); @@ -3302,7 +3302,7 @@ pub const Expect = struct { if (pass) return .js_undefined; - var formatter = JSC.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; + var formatter = jsc.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; defer formatter.deinit(); const received = value.toFmt(&formatter); @@ -3328,7 +3328,7 @@ pub const Expect = struct { if (pass) return .js_undefined; - var formatter = JSC.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; + var formatter = jsc.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; defer formatter.deinit(); const received = value.toFmt(&formatter); @@ -3354,7 +3354,7 @@ pub const Expect = struct { if (pass) return thisValue; - var formatter = JSC.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; + var formatter = jsc.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; defer formatter.deinit(); const received = value.toFmt(&formatter); @@ -3386,7 +3386,7 @@ pub const Expect = struct { if (pass) return .js_undefined; - var formatter = JSC.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; + var formatter = jsc.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; defer formatter.deinit(); const received = value.toFmt(&formatter); @@ -3418,7 +3418,7 @@ pub const Expect = struct { if (pass) return .js_undefined; - var formatter = JSC.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; + var formatter = jsc.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; defer formatter.deinit(); const received = value.toFmt(&formatter); @@ -3450,7 +3450,7 @@ pub const Expect = struct { if (pass) return .js_undefined; - var formatter = JSC.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; + var formatter = jsc.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; defer formatter.deinit(); const received = value.toFmt(&formatter); @@ -3503,7 +3503,7 @@ pub const Expect = struct { if (pass) return .js_undefined; - var formatter = JSC.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; + var formatter = jsc.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; defer formatter.deinit(); const start_fmt = startValue.toFmt(&formatter); const end_fmt = endValue.toFmt(&formatter); @@ -3587,7 +3587,7 @@ pub const Expect = struct { if (pass) return .js_undefined; // handle failure - var formatter = JSC.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; + var formatter = jsc.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; defer formatter.deinit(); const expected_fmt = expected.toFmt(&formatter); const value_fmt = value.toFmt(&formatter); @@ -3614,7 +3614,7 @@ pub const Expect = struct { if (pass) return .js_undefined; - var formatter = JSC.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; + var formatter = jsc.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; defer formatter.deinit(); const received = value.toFmt(&formatter); @@ -3640,7 +3640,7 @@ pub const Expect = struct { if (pass) return .js_undefined; - var formatter = JSC.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; + var formatter = jsc.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; defer formatter.deinit(); const received = value.toFmt(&formatter); @@ -3666,7 +3666,7 @@ pub const Expect = struct { if (pass) return .js_undefined; - var formatter = JSC.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; + var formatter = jsc.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; defer formatter.deinit(); const received = value.toFmt(&formatter); @@ -3693,7 +3693,7 @@ pub const Expect = struct { if (pass) return thisValue; - var formatter = JSC.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; + var formatter = jsc.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; defer formatter.deinit(); const received = value.toFmt(&formatter); @@ -3719,7 +3719,7 @@ pub const Expect = struct { if (pass) return .js_undefined; - var formatter = JSC.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; + var formatter = jsc.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; defer formatter.deinit(); const received = value.toFmt(&formatter); @@ -3768,7 +3768,7 @@ pub const Expect = struct { if (pass) return .js_undefined; - var formatter = JSC.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; + var formatter = jsc.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; defer formatter.deinit(); const value_fmt = value.toFmt(&formatter); const expected_fmt = expected.toFmt(&formatter); @@ -3849,7 +3849,7 @@ pub const Expect = struct { if (not) pass = !pass; if (pass) return .js_undefined; - var formatter = JSC.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; + var formatter = jsc.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; defer formatter.deinit(); const expect_string_fmt = expect_string.toFmt(&formatter); const substring_fmt = substring.toFmt(&formatter); @@ -3924,7 +3924,7 @@ pub const Expect = struct { if (pass) return .js_undefined; - var formatter = JSC.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; + var formatter = jsc.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; defer formatter.deinit(); if (not) { @@ -3976,7 +3976,7 @@ pub const Expect = struct { if (pass) return .js_undefined; - var formatter = JSC.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; + var formatter = jsc.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; defer formatter.deinit(); const value_fmt = value.toFmt(&formatter); const expected_fmt = expected.toFmt(&formatter); @@ -4030,7 +4030,7 @@ pub const Expect = struct { if (pass) return .js_undefined; - var formatter = JSC.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; + var formatter = jsc.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; defer formatter.deinit(); const value_fmt = value.toFmt(&formatter); const expected_fmt = expected.toFmt(&formatter); @@ -4060,7 +4060,7 @@ pub const Expect = struct { } incrementExpectCallCounter(); - var formatter = JSC.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; + var formatter = jsc.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; defer formatter.deinit(); const expected_value = arguments[0]; @@ -4093,7 +4093,7 @@ pub const Expect = struct { } pub fn toMatch(this: *Expect, globalThis: *JSGlobalObject, callFrame: *CallFrame) bun.JSError!JSValue { - JSC.markBinding(@src()); + jsc.markBinding(@src()); defer this.postMatch(globalThis); @@ -4107,7 +4107,7 @@ pub const Expect = struct { incrementExpectCallCounter(); - var formatter = JSC.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; + var formatter = jsc.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; defer formatter.deinit(); const expected_value = arguments[0]; @@ -4153,7 +4153,7 @@ pub const Expect = struct { } pub fn toHaveBeenCalled(this: *Expect, globalThis: *JSGlobalObject, callframe: *CallFrame) bun.JSError!JSValue { - JSC.markBinding(@src()); + jsc.markBinding(@src()); const thisValue = callframe.this(); defer this.postMatch(globalThis); @@ -4183,7 +4183,7 @@ pub const Expect = struct { } pub fn toHaveBeenCalledOnce(this: *Expect, globalThis: *JSGlobalObject, callframe: *CallFrame) bun.JSError!JSValue { - JSC.markBinding(@src()); + jsc.markBinding(@src()); const thisValue = callframe.this(); defer this.postMatch(globalThis); @@ -4214,7 +4214,7 @@ pub const Expect = struct { } pub fn toHaveBeenCalledTimes(this: *Expect, globalThis: *JSGlobalObject, callframe: *CallFrame) bun.JSError!JSValue { - JSC.markBinding(@src()); + jsc.markBinding(@src()); const thisValue = callframe.this(); const arguments_ = callframe.arguments_old(1); @@ -4252,7 +4252,7 @@ pub const Expect = struct { } pub fn toMatchObject(this: *Expect, globalThis: *JSGlobalObject, callFrame: *CallFrame) bun.JSError!JSValue { - JSC.markBinding(@src()); + jsc.markBinding(@src()); defer this.postMatch(globalThis); const thisValue = callFrame.this(); @@ -4310,7 +4310,7 @@ pub const Expect = struct { } pub fn toHaveBeenCalledWith(this: *Expect, globalThis: *JSGlobalObject, callframe: *CallFrame) bun.JSError!JSValue { - JSC.markBinding(@src()); + jsc.markBinding(@src()); const thisValue = callframe.this(); const arguments = callframe.arguments(); @@ -4368,7 +4368,7 @@ pub const Expect = struct { } pub fn toHaveBeenLastCalledWith(this: *Expect, globalThis: *JSGlobalObject, callframe: *CallFrame) bun.JSError!JSValue { - JSC.markBinding(@src()); + jsc.markBinding(@src()); const thisValue = callframe.this(); const arguments = callframe.arguments(); @@ -4412,7 +4412,7 @@ pub const Expect = struct { if (pass) return .js_undefined; // handle failure - var formatter = JSC.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; + var formatter = jsc.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; defer formatter.deinit(); const received_fmt = lastCallValue.toFmt(&formatter); @@ -4426,7 +4426,7 @@ pub const Expect = struct { } pub fn toHaveBeenNthCalledWith(this: *Expect, globalThis: *JSGlobalObject, callframe: *CallFrame) bun.JSError!JSValue { - JSC.markBinding(@src()); + jsc.markBinding(@src()); const thisValue = callframe.this(); const arguments = callframe.arguments(); @@ -4475,7 +4475,7 @@ pub const Expect = struct { if (pass) return .js_undefined; // handle failure - var formatter = JSC.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; + var formatter = jsc.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; defer formatter.deinit(); const received_fmt = nthCallValue.toFmt(&formatter); @@ -4497,7 +4497,7 @@ pub const Expect = struct { }; inline fn toHaveReturnedTimesFn(this: *Expect, globalThis: *JSGlobalObject, callframe: *CallFrame, comptime known_index: ?i32) bun.JSError!JSValue { - JSC.markBinding(@src()); + jsc.markBinding(@src()); const thisValue = callframe.this(); const arguments = callframe.arguments_old(1).slice(); @@ -4559,7 +4559,7 @@ pub const Expect = struct { if (!pass and return_status == ReturnStatus.throw) { const signature = comptime getSignature(name, "expected", false); const fmt = signature ++ "\n\n" ++ "Function threw an exception\n{any}\n"; - var formatter = JSC.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; + var formatter = jsc.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; defer formatter.deinit(); return globalThis.throwPretty(fmt, .{(try times_value.get(globalThis, "value")).?.toFmt(&formatter)}); } @@ -4639,7 +4639,7 @@ pub const Expect = struct { // SAFETY: already checked that args[0] is an object const matchers_to_register = args[0].getObject().?; { - var iter = try JSC.JSPropertyIterator(.{ + var iter = try jsc.JSPropertyIterator(.{ .skip_empty_name = false, .include_value = true, .own_properties_only = false, @@ -4658,7 +4658,7 @@ pub const Expect = struct { // Even though they point to the same native functions for all matchers, // multiple instances are created because each instance will hold the matcher_fn as a property - const wrapper_fn = Bun__JSWrappingFunction__create(globalThis, matcher_name, JSC.toJSHostFn(Expect.applyCustomMatcher), matcher_fn, true); + const wrapper_fn = Bun__JSWrappingFunction__create(globalThis, matcher_name, jsc.toJSHostFn(Expect.applyCustomMatcher), matcher_fn, true); expect_proto.put(globalThis, matcher_name, wrapper_fn); expect_constructor.put(globalThis, matcher_name, wrapper_fn); @@ -4678,7 +4678,7 @@ pub const Expect = struct { pub fn format(this: CustomMatcherParamsFormatter, comptime _: []const u8, _: std.fmt.FormatOptions, writer: anytype) !void { // try to detect param names from matcher_fn (user function) source code - if (JSC.JSFunction.getSourceCode(this.matcher_fn)) |source_str| { + if (jsc.JSFunction.getSourceCode(this.matcher_fn)) |source_str| { var source_slice = source_str.toSlice(this.globalThis.allocator()); defer source_slice.deinit(); @@ -4721,7 +4721,7 @@ pub const Expect = struct { fn throwInvalidMatcherError(globalThis: *JSGlobalObject, matcher_name: bun.String, result: JSValue) bun.JSError { @branchHint(.cold); - var formatter = JSC.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; + var formatter = jsc.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; defer formatter.deinit(); const fmt = @@ -4763,7 +4763,7 @@ pub const Expect = struct { .fulfilled => {}, .rejected => { // TODO: rewrite this code to use .then() instead of blocking the event loop - JSC.VirtualMachine.get().runErrorHandler(result, null); + jsc.VirtualMachine.get().runErrorHandler(result, null); return globalThis.throw("Matcher `{s}` returned a promise that rejected", .{matcher_name}); }, } @@ -4824,7 +4824,7 @@ pub const Expect = struct { /// Function that is run for either `expect.myMatcher()` call or `expect().myMatcher` call, /// and we can known which case it is based on if the `callFrame.this()` value is an instance of Expect - pub fn applyCustomMatcher(globalThis: *JSGlobalObject, callFrame: *CallFrame) bun.JSError!JSC.JSValue { + pub fn applyCustomMatcher(globalThis: *JSGlobalObject, callFrame: *CallFrame) bun.JSError!jsc.JSValue { defer globalThis.bunVM().autoGarbageCollect(); // retrieve the user-provided matcher function (matcher_fn) @@ -4899,13 +4899,13 @@ pub const Expect = struct { const expected: JSValue = arguments[0]; if (!expected.isNumber()) { - var fmt = JSC.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; + var fmt = jsc.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; return globalThis.throw("Expected value must be a non-negative integer: {any}", .{expected.toFmt(&fmt)}); } const expected_assertions: f64 = try expected.toNumber(globalThis); if (@round(expected_assertions) != expected_assertions or std.math.isInf(expected_assertions) or std.math.isNan(expected_assertions) or expected_assertions < 0 or expected_assertions > std.math.maxInt(u32)) { - var fmt = JSC.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; + var fmt = jsc.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; return globalThis.throw("Expected value must be a non-negative integer: {any}", .{expected.toFmt(&fmt)}); } @@ -4960,7 +4960,7 @@ pub const Expect = struct { /// Static instance of expect, holding a set of flags. /// Returned for example when executing `expect.not` pub const ExpectStatic = struct { - pub const js = JSC.Codegen.JSExpectStatic; + pub const js = jsc.Codegen.JSExpectStatic; pub const toJS = js.toJS; pub const fromJS = js.fromJS; pub const fromJSDirect = js.fromJSDirect; @@ -5054,7 +5054,7 @@ pub const ExpectStatic = struct { }; pub const ExpectAnything = struct { - pub const js = JSC.Codegen.JSExpectAnything; + pub const js = jsc.Codegen.JSExpectAnything; pub const toJS = js.toJS; pub const fromJS = js.fromJS; pub const fromJSDirect = js.fromJSDirect; @@ -5082,7 +5082,7 @@ pub const ExpectAnything = struct { }; pub const ExpectStringMatching = struct { - pub const js = JSC.Codegen.JSExpectStringMatching; + pub const js = jsc.Codegen.JSExpectStringMatching; pub const toJS = js.toJS; pub const fromJS = js.fromJS; pub const fromJSDirect = js.fromJSDirect; @@ -5118,7 +5118,7 @@ pub const ExpectStringMatching = struct { }; pub const ExpectCloseTo = struct { - pub const js = JSC.Codegen.JSExpectCloseTo; + pub const js = jsc.Codegen.JSExpectCloseTo; pub const toJS = js.toJS; pub const fromJS = js.fromJS; pub const fromJSDirect = js.fromJSDirect; @@ -5163,7 +5163,7 @@ pub const ExpectCloseTo = struct { }; pub const ExpectObjectContaining = struct { - pub const js = JSC.Codegen.JSExpectObjectContaining; + pub const js = jsc.Codegen.JSExpectObjectContaining; pub const toJS = js.toJS; pub const fromJS = js.fromJS; pub const fromJSDirect = js.fromJSDirect; @@ -5199,7 +5199,7 @@ pub const ExpectObjectContaining = struct { }; pub const ExpectStringContaining = struct { - pub const js = JSC.Codegen.JSExpectStringContaining; + pub const js = jsc.Codegen.JSExpectStringContaining; pub const toJS = js.toJS; pub const fromJS = js.fromJS; pub const fromJSDirect = js.fromJSDirect; @@ -5235,7 +5235,7 @@ pub const ExpectStringContaining = struct { }; pub const ExpectAny = struct { - pub const js = JSC.Codegen.JSExpectAny; + pub const js = jsc.Codegen.JSExpectAny; pub const toJS = js.toJS; pub const fromJS = js.fromJS; pub const fromJSDirect = js.fromJSDirect; @@ -5288,7 +5288,7 @@ pub const ExpectAny = struct { }; pub const ExpectArrayContaining = struct { - pub const js = JSC.Codegen.JSExpectArrayContaining; + pub const js = jsc.Codegen.JSExpectArrayContaining; pub const toJS = js.toJS; pub const fromJS = js.fromJS; pub const fromJSDirect = js.fromJSDirect; @@ -5328,7 +5328,7 @@ pub const ExpectArrayContaining = struct { /// Reference: `AsymmetricMatcher` in https://github.com/jestjs/jest/blob/main/packages/expect/src/types.ts /// (but only created for *custom* matchers, as built-ins have their own classes) pub const ExpectCustomAsymmetricMatcher = struct { - pub const js = JSC.Codegen.JSExpectCustomAsymmetricMatcher; + pub const js = jsc.Codegen.JSExpectCustomAsymmetricMatcher; pub const toJS = js.toJS; pub const fromJS = js.fromJS; pub const fromJSDirect = js.fromJSDirect; @@ -5471,7 +5471,7 @@ pub const ExpectCustomAsymmetricMatcher = struct { /// Reference: `MatcherContext` in https://github.com/jestjs/jest/blob/main/packages/expect/src/types.ts pub const ExpectMatcherContext = struct { - pub const js = JSC.Codegen.JSExpectMatcherContext; + pub const js = jsc.Codegen.JSExpectMatcherContext; pub const toJS = js.toJS; pub const fromJS = js.fromJS; pub const fromJSDirect = js.fromJSDirect; @@ -5518,7 +5518,7 @@ pub const ExpectMatcherContext = struct { /// Reference: `MatcherUtils` in https://github.com/jestjs/jest/blob/main/packages/expect/src/types.ts pub const ExpectMatcherUtils = struct { - pub const js = JSC.Codegen.JSExpectMatcherUtils; + pub const js = jsc.Codegen.JSExpectMatcherUtils; pub const toJS = js.toJS; pub const fromJS = js.fromJS; pub const fromJSDirect = js.fromJSDirect; @@ -5550,7 +5550,7 @@ pub const ExpectMatcherUtils = struct { } } - var formatter = JSC.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; + var formatter = jsc.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; defer formatter.deinit(); try writer.print("{}", .{value.toFmt(&formatter)}); @@ -5603,9 +5603,9 @@ pub const ExpectMatcherUtils = struct { const options = if (arguments.len > 3) arguments[3] else .js_undefined; var is_not = false; - var comment: ?*JSC.JSString = null; // TODO support - var promise: ?*JSC.JSString = null; // TODO support - var second_argument: ?*JSC.JSString = null; // TODO support + var comment: ?*jsc.JSString = null; // TODO support + var promise: ?*jsc.JSString = null; // TODO support + var second_argument: ?*jsc.JSString = null; // TODO support // TODO support "chalk" colors (they are actually functions like: (value: string) => string;) //var second_argument_color: ?string = null; //var expected_color: ?string = null; @@ -5662,7 +5662,7 @@ extern fn JSMockFunction__getCalls(JSValue) JSValue; /// If there were no calls, it returns an empty JSArray* extern fn JSMockFunction__getReturns(JSValue) JSValue; -extern fn Bun__JSWrappingFunction__create(globalThis: *JSGlobalObject, symbolName: *const bun.String, functionPointer: *const JSC.JSHostFn, wrappedFn: JSValue, strong: bool) JSValue; +extern fn Bun__JSWrappingFunction__create(globalThis: *JSGlobalObject, symbolName: *const bun.String, functionPointer: *const jsc.JSHostFn, wrappedFn: JSValue, strong: bool) JSValue; extern fn Bun__JSWrappingFunction__getWrappedFunction(this: JSValue, globalThis: *JSGlobalObject) JSValue; extern fn ExpectMatcherUtils__getSingleton(globalThis: *JSGlobalObject) JSValue; @@ -5790,6 +5790,8 @@ test "fuzz Expect.trimLeadingWhitespaceForInlineSnapshot" { try std.testing.fuzz(testOne, .{}); } +const string = []const u8; + const std = @import("std"); const DiffFormatter = @import("./diff_format.zig").DiffFormatter; @@ -5799,17 +5801,16 @@ const MutableString = bun.MutableString; const Output = bun.Output; const assert = bun.assert; const default_allocator = bun.default_allocator; -const string = bun.string; const strings = bun.strings; -const JSC = bun.JSC; -const CallFrame = JSC.CallFrame; -const JSGlobalObject = JSC.JSGlobalObject; -const JSValue = JSC.JSValue; -const VirtualMachine = JSC.VirtualMachine; -const ZigString = JSC.ZigString; +const jsc = bun.jsc; +const CallFrame = jsc.CallFrame; +const JSGlobalObject = jsc.JSGlobalObject; +const JSValue = jsc.JSValue; +const VirtualMachine = jsc.VirtualMachine; +const ZigString = jsc.ZigString; -const jest = bun.JSC.Jest; +const jest = bun.jsc.Jest; const DescribeScope = jest.DescribeScope; const Jest = jest.Jest; const TestRunner = jest.TestRunner; diff --git a/src/bun.js/test/jest.zig b/src/bun.js/test/jest.zig index c2d04f59e9..2cd6868f3f 100644 --- a/src/bun.js/test/jest.zig +++ b/src/bun.js/test/jest.zig @@ -74,7 +74,7 @@ pub const TestRunner = struct { allocator: std.mem.Allocator, callback: *Callback = undefined, - drainer: JSC.AnyTask = undefined, + drainer: jsc.AnyTask = undefined, queue: std.fifo.LinearFifo(*TestRunnerTask, .{ .Dynamic = {} }) = std.fifo.LinearFifo(*TestRunnerTask, .{ .Dynamic = {} }).init(default_allocator), has_pending_tests: bool = false, @@ -92,7 +92,7 @@ pub const TestRunner = struct { .tag = .TestRunner, }, active_test_for_timeout: ?TestRunner.Test.ID = null, - test_options: *const bun.CLI.Command.TestOptions = undefined, + test_options: *const bun.cli.Command.TestOptions = undefined, global_callbacks: struct { beforeAll: std.ArrayListUnmanaged(JSValue) = .{}, @@ -108,7 +108,7 @@ pub const TestRunner = struct { unhandled_errors_between_tests: u32 = 0, summary: Summary = Summary{}, - pub const Drainer = JSC.AnyTask.New(TestRunner, drain); + pub const Drainer = jsc.AnyTask.New(TestRunner, drain); pub const Summary = struct { pass: u32 = 0, @@ -149,7 +149,7 @@ pub const TestRunner = struct { pub fn scheduleTimeout(this: *TestRunner, milliseconds: u32) void { const then = bun.timespec.msFromNow(@intCast(milliseconds)); - const vm = JSC.VirtualMachine.get(); + const vm = jsc.VirtualMachine.get(); this.event_loop_timer.tag = .TestRunner; if (this.event_loop_timer.state == .ACTIVE) { @@ -168,7 +168,7 @@ pub const TestRunner = struct { this.has_pending_tests = false; this.pending_test = null; - const vm = JSC.VirtualMachine.get(); + const vm = jsc.VirtualMachine.get(); vm.auto_killer.clear(); vm.auto_killer.disable(); @@ -313,7 +313,7 @@ pub const TestRunner = struct { pub const Jest = struct { pub var runner: ?*TestRunner = null; - fn globalHook(comptime name: string) JSC.JSHostFnZig { + fn globalHook(comptime name: string) jsc.JSHostFnZig { return struct { pub fn appendGlobalFunctionCallback(globalThis: *JSGlobalObject, callframe: *CallFrame) bun.JSError!JSValue { const the_runner = runner orelse { @@ -357,7 +357,7 @@ pub const Jest = struct { const module = JSValue.createEmptyObject(globalObject, 14); - const test_fn = JSC.host_fn.NewFunction(globalObject, ZigString.static("test"), 2, ThisTestScope.call, false); + const test_fn = jsc.host_fn.NewFunction(globalObject, ZigString.static("test"), 2, ThisTestScope.call, false); module.put( globalObject, ZigString.static("test"), @@ -369,14 +369,14 @@ pub const Jest = struct { test_fn.put( globalObject, name, - JSC.host_fn.NewFunction(globalObject, name, 2, @field(ThisTestScope, method_name), false), + jsc.host_fn.NewFunction(globalObject, name, 2, @field(ThisTestScope, method_name), false), ); } test_fn.put( globalObject, ZigString.static("if"), - JSC.host_fn.NewFunction(globalObject, ZigString.static("if"), 2, ThisTestScope.callIf, false), + jsc.host_fn.NewFunction(globalObject, ZigString.static("if"), 2, ThisTestScope.callIf, false), ); module.put( @@ -384,7 +384,7 @@ pub const Jest = struct { ZigString.static("it"), test_fn, ); - const describe = JSC.host_fn.NewFunction(globalObject, ZigString.static("describe"), 2, ThisDescribeScope.call, false); + const describe = jsc.host_fn.NewFunction(globalObject, ZigString.static("describe"), 2, ThisDescribeScope.call, false); inline for (.{ "only", "skip", @@ -397,13 +397,13 @@ pub const Jest = struct { describe.put( globalObject, name, - JSC.host_fn.NewFunction(globalObject, name, 2, @field(ThisDescribeScope, method_name), false), + jsc.host_fn.NewFunction(globalObject, name, 2, @field(ThisDescribeScope, method_name), false), ); } describe.put( globalObject, ZigString.static("if"), - JSC.host_fn.NewFunction(globalObject, ZigString.static("if"), 2, ThisDescribeScope.callIf, false), + jsc.host_fn.NewFunction(globalObject, ZigString.static("if"), 2, ThisDescribeScope.callIf, false), ); module.put( @@ -414,9 +414,9 @@ pub const Jest = struct { inline for (.{ "beforeAll", "beforeEach", "afterAll", "afterEach" }) |name| { const function = if (outside_of_test) - JSC.host_fn.NewFunction(globalObject, null, 1, globalHook(name), false) + jsc.host_fn.NewFunction(globalObject, null, 1, globalHook(name), false) else - JSC.host_fn.NewFunction( + jsc.host_fn.NewFunction( globalObject, ZigString.static(name), 1, @@ -430,7 +430,7 @@ pub const Jest = struct { module.put( globalObject, ZigString.static("setDefaultTimeout"), - JSC.host_fn.NewFunction(globalObject, ZigString.static("setDefaultTimeout"), 1, jsSetDefaultTimeout, false), + jsc.host_fn.NewFunction(globalObject, ZigString.static("setDefaultTimeout"), 1, jsSetDefaultTimeout, false), ); module.put( @@ -445,20 +445,20 @@ pub const Jest = struct { } fn createMockObjects(globalObject: *JSGlobalObject, module: JSValue) void { - const setSystemTime = JSC.host_fn.NewFunction(globalObject, ZigString.static("setSystemTime"), 0, JSMock__jsSetSystemTime, false); + const setSystemTime = jsc.host_fn.NewFunction(globalObject, ZigString.static("setSystemTime"), 0, JSMock__jsSetSystemTime, false); module.put( globalObject, ZigString.static("setSystemTime"), setSystemTime, ); - const useFakeTimers = JSC.host_fn.NewFunction(globalObject, ZigString.static("useFakeTimers"), 0, JSMock__jsUseFakeTimers, false); - const useRealTimers = JSC.host_fn.NewFunction(globalObject, ZigString.static("useRealTimers"), 0, JSMock__jsUseRealTimers, false); + const useFakeTimers = jsc.host_fn.NewFunction(globalObject, ZigString.static("useFakeTimers"), 0, JSMock__jsUseFakeTimers, false); + const useRealTimers = jsc.host_fn.NewFunction(globalObject, ZigString.static("useRealTimers"), 0, JSMock__jsUseRealTimers, false); - const mockFn = JSC.host_fn.NewFunction(globalObject, ZigString.static("fn"), 1, JSMock__jsMockFn, false); - const spyOn = JSC.host_fn.NewFunction(globalObject, ZigString.static("spyOn"), 2, JSMock__jsSpyOn, false); - const restoreAllMocks = JSC.host_fn.NewFunction(globalObject, ZigString.static("restoreAllMocks"), 2, JSMock__jsRestoreAllMocks, false); - const clearAllMocks = JSC.host_fn.NewFunction(globalObject, ZigString.static("clearAllMocks"), 2, JSMock__jsClearAllMocks, false); - const mockModuleFn = JSC.host_fn.NewFunction(globalObject, ZigString.static("module"), 2, JSMock__jsModuleMock, false); + const mockFn = jsc.host_fn.NewFunction(globalObject, ZigString.static("fn"), 1, JSMock__jsMockFn, false); + const spyOn = jsc.host_fn.NewFunction(globalObject, ZigString.static("spyOn"), 2, JSMock__jsSpyOn, false); + const restoreAllMocks = jsc.host_fn.NewFunction(globalObject, ZigString.static("restoreAllMocks"), 2, JSMock__jsRestoreAllMocks, false); + const clearAllMocks = jsc.host_fn.NewFunction(globalObject, ZigString.static("clearAllMocks"), 2, JSMock__jsClearAllMocks, false); + const mockModuleFn = jsc.host_fn.NewFunction(globalObject, ZigString.static("module"), 2, JSMock__jsModuleMock, false); module.put(globalObject, ZigString.static("mock"), mockFn); mockFn.put(globalObject, ZigString.static("module"), mockModuleFn); mockFn.put(globalObject, ZigString.static("restore"), restoreAllMocks); @@ -483,8 +483,8 @@ pub const Jest = struct { ZigString.static("useRealTimers"), useRealTimers, ); - jest.put(globalObject, ZigString.static("now"), JSC.host_fn.NewFunction(globalObject, ZigString.static("now"), 0, JSMock__jsNow, false)); - jest.put(globalObject, ZigString.static("setTimeout"), JSC.host_fn.NewFunction(globalObject, ZigString.static("setTimeout"), 1, jsSetDefaultTimeout, false)); + jest.put(globalObject, ZigString.static("now"), jsc.host_fn.NewFunction(globalObject, ZigString.static("now"), 0, JSMock__jsNow, false)); + jest.put(globalObject, ZigString.static("setTimeout"), jsc.host_fn.NewFunction(globalObject, ZigString.static("setTimeout"), 1, jsSetDefaultTimeout, false)); module.put(globalObject, ZigString.static("jest"), jest); module.put(globalObject, ZigString.static("spyOn"), spyOn); @@ -505,15 +505,15 @@ pub const Jest = struct { extern fn Bun__Jest__testPreloadObject(*JSGlobalObject) JSValue; extern fn Bun__Jest__testModuleObject(*JSGlobalObject) JSValue; - extern fn JSMock__jsMockFn(*JSGlobalObject, *CallFrame) callconv(JSC.conv) JSValue; - extern fn JSMock__jsModuleMock(*JSGlobalObject, *CallFrame) callconv(JSC.conv) JSValue; - extern fn JSMock__jsNow(*JSGlobalObject, *CallFrame) callconv(JSC.conv) JSValue; - extern fn JSMock__jsSetSystemTime(*JSGlobalObject, *CallFrame) callconv(JSC.conv) JSValue; - extern fn JSMock__jsRestoreAllMocks(*JSGlobalObject, *CallFrame) callconv(JSC.conv) JSValue; - extern fn JSMock__jsClearAllMocks(*JSGlobalObject, *CallFrame) callconv(JSC.conv) JSValue; - extern fn JSMock__jsSpyOn(*JSGlobalObject, *CallFrame) callconv(JSC.conv) JSValue; - extern fn JSMock__jsUseFakeTimers(*JSGlobalObject, *CallFrame) callconv(JSC.conv) JSValue; - extern fn JSMock__jsUseRealTimers(*JSGlobalObject, *CallFrame) callconv(JSC.conv) JSValue; + extern fn JSMock__jsMockFn(*JSGlobalObject, *CallFrame) callconv(jsc.conv) JSValue; + extern fn JSMock__jsModuleMock(*JSGlobalObject, *CallFrame) callconv(jsc.conv) JSValue; + extern fn JSMock__jsNow(*JSGlobalObject, *CallFrame) callconv(jsc.conv) JSValue; + extern fn JSMock__jsSetSystemTime(*JSGlobalObject, *CallFrame) callconv(jsc.conv) JSValue; + extern fn JSMock__jsRestoreAllMocks(*JSGlobalObject, *CallFrame) callconv(jsc.conv) JSValue; + extern fn JSMock__jsClearAllMocks(*JSGlobalObject, *CallFrame) callconv(jsc.conv) JSValue; + extern fn JSMock__jsSpyOn(*JSGlobalObject, *CallFrame) callconv(jsc.conv) JSValue; + extern fn JSMock__jsUseFakeTimers(*JSGlobalObject, *CallFrame) callconv(jsc.conv) JSValue; + extern fn JSMock__jsUseRealTimers(*JSGlobalObject, *CallFrame) callconv(jsc.conv) JSValue; pub fn call( globalObject: *JSGlobalObject, @@ -646,7 +646,7 @@ pub const TestScope = struct { globalThis.bunVM().autoGarbageCollect(); return .js_undefined; } - const jsOnReject = JSC.toJSHostFn(onReject); + const jsOnReject = jsc.toJSHostFn(onReject); pub fn onResolve(globalThis: *JSGlobalObject, callframe: *CallFrame) bun.JSError!JSValue { debug("onResolve", .{}); @@ -656,7 +656,7 @@ pub const TestScope = struct { globalThis.bunVM().autoGarbageCollect(); return .js_undefined; } - const jsOnResolve = JSC.toJSHostFn(onResolve); + const jsOnResolve = jsc.toJSHostFn(onResolve); pub fn onDone( globalThis: *JSGlobalObject, @@ -666,7 +666,7 @@ pub const TestScope = struct { const args = callframe.arguments_old(1); defer globalThis.bunVM().autoGarbageCollect(); - if (JSC.host_fn.getFunctionData(function)) |data| { + if (jsc.host_fn.getFunctionData(function)) |data| { var task = bun.cast(*TestRunnerTask, data); const expect_count = expect.active_test_expectation_counter.actual; const current_test = task.testScope(); @@ -675,7 +675,7 @@ pub const TestScope = struct { else .{ .pass = expect_count }; - JSC.host_fn.setFunctionData(function, null); + jsc.host_fn.setFunctionData(function, null); if (args.len > 0) { const err = args.ptr[0]; if (err.isEmptyOrUndefinedOrNull()) { @@ -718,7 +718,7 @@ pub const TestScope = struct { this.func_has_callback = false; vm.autoGarbageCollect(); } - JSC.markBinding(@src()); + jsc.markBinding(@src()); debug("test({})", .{bun.fmt.QuotedFormatter{ .text = this.label }}); var initial_value = JSValue.zero; @@ -746,7 +746,7 @@ pub const TestScope = struct { } if (this.func_has_callback) { - const callback_func = JSC.host_fn.NewFunctionWithData( + const callback_func = jsc.host_fn.NewFunctionWithData( vm.global, ZigString.static("done"), 0, @@ -917,11 +917,11 @@ pub const DescribeScope = struct { pub threadlocal var active: ?*DescribeScope = null; - const CallbackFn = JSC.JSHostFnZig; + const CallbackFn = jsc.JSHostFnZig; fn createCallback(comptime hook: LifecycleHook) CallbackFn { return struct { - pub fn run(globalThis: *JSGlobalObject, callframe: *CallFrame) bun.JSError!JSC.JSValue { + pub fn run(globalThis: *JSGlobalObject, callframe: *CallFrame) bun.JSError!jsc.JSValue { const arguments = callframe.arguments_old(2); if (arguments.len < 1) { return globalThis.throwNotEnoughArguments("callback", 1, arguments.len); @@ -940,16 +940,16 @@ pub const DescribeScope = struct { } pub fn onDone( - ctx: *JSC.JSGlobalObject, + ctx: *jsc.JSGlobalObject, callframe: *CallFrame, ) bun.JSError!JSValue { const function = callframe.callee(); const args = callframe.arguments_old(1); defer ctx.bunVM().autoGarbageCollect(); - if (JSC.host_fn.getFunctionData(function)) |data| { + if (jsc.host_fn.getFunctionData(function)) |data| { var scope = bun.cast(*DescribeScope, data); - JSC.host_fn.setFunctionData(function, null); + jsc.host_fn.setFunctionData(function, null); if (args.len > 0) { const err = args.ptr[0]; if (!err.isEmptyOrUndefinedOrNull()) { @@ -992,7 +992,7 @@ pub const DescribeScope = struct { 0 => callJSFunctionForTestRunner(vm, globalObject, cb, &.{}), else => brk: { this.done = false; - const done_func = JSC.host_fn.NewFunctionWithData( + const done_func = jsc.host_fn.NewFunctionWithData( globalObject, ZigString.static("done"), 0, @@ -1142,7 +1142,7 @@ pub const DescribeScope = struct { } { - JSC.markBinding(@src()); + jsc.markBinding(@src()); var result = callJSFunctionForTestRunner(VirtualMachine.get(), globalObject, callback, args); if (result.asAnyPromise()) |prom| { @@ -1271,7 +1271,7 @@ pub const DescribeScope = struct { const ScopeStack = ObjectPool(std.ArrayListUnmanaged(*DescribeScope), null, true, 16); }; -pub fn wrapTestFunction(comptime name: []const u8, comptime func: JSC.JSHostFnZig) DescribeScope.CallbackFn { +pub fn wrapTestFunction(comptime name: []const u8, comptime func: jsc.JSHostFnZig) DescribeScope.CallbackFn { return struct { pub fn wrapped(globalThis: *JSGlobalObject, callframe: *CallFrame) bun.JSError!JSValue { if (Jest.runner == null) { @@ -1317,7 +1317,7 @@ pub const TestRunnerTask = struct { globalThis: *JSGlobalObject, source_file_path: string = "", needs_before_each: bool = true, - ref: JSC.Ref = JSC.Ref.init(), + ref: jsc.Ref = jsc.Ref.init(), done_callback_state: AsyncState = .none, promise_state: AsyncState = .none, @@ -1518,7 +1518,7 @@ pub const TestRunnerTask = struct { // Drain microtasks one more time. // But don't hang forever. // We report the test failure before that task is run. - this.globalThis.bunVM().enqueueTask(JSC.ManagedTask.New(@This(), deinit).init(this)); + this.globalThis.bunVM().enqueueTask(jsc.ManagedTask.New(@This(), deinit).init(this)); } pub fn handleResultPtr(this: *TestRunnerTask, result: *Result, from: ResultType) void { @@ -1734,7 +1734,7 @@ pub const TestRunnerTask = struct { } fn deinit(this: *TestRunnerTask) void { - const vm = JSC.VirtualMachine.get(); + const vm = jsc.VirtualMachine.get(); if (vm.onUnhandledRejectionCtx) |ctx| { if (ctx == @as(*anyopaque, @ptrCast(this))) { vm.onUnhandledRejectionCtx = null; @@ -2016,7 +2016,7 @@ inline fn createIfScope( }; switch (@intFromBool(value)) { - inline else => |index| return JSC.host_fn.NewFunction(globalThis, name, 2, truthy_falsey[index], false), + inline else => |index| return jsc.host_fn.NewFunction(globalThis, name, 2, truthy_falsey[index], false), } } @@ -2076,7 +2076,7 @@ fn formatLabel(globalThis: *JSGlobalObject, label: string, function_args: []JSVa const var_path = label[var_start..var_end]; const value = try function_args[0].getIfPropertyExistsFromPath(globalThis, bun.String.init(var_path).toJS(globalThis)); if (!value.isEmptyOrUndefinedOrNull()) { - var formatter = JSC.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; + var formatter = jsc.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; defer formatter.deinit(); const value_str = std.fmt.allocPrint(allocator, "{}", .{value.toFmt(&formatter)}) catch bun.outOfMemory(); defer allocator.free(value_str); @@ -2120,7 +2120,7 @@ fn formatLabel(globalThis: *JSGlobalObject, label: string, function_args: []JSVa args_idx += 1; }, 'p' => { - var formatter = JSC.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; + var formatter = jsc.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; defer formatter.deinit(); const value_fmt = current_arg.toFmt(&formatter); const test_index_str = std.fmt.allocPrint(allocator, "{}", .{value_fmt}) catch bun.outOfMemory(); @@ -2151,7 +2151,7 @@ fn formatLabel(globalThis: *JSGlobalObject, label: string, function_args: []JSVa } pub const EachData = struct { - strong: JSC.Strong.Optional, + strong: jsc.Strong.Optional, is_test: bool, line_number: u32 = 0, }; @@ -2202,10 +2202,10 @@ fn eachBind(globalThis: *JSGlobalObject, callframe: *CallFrame) bun.JSError!JSVa const parent = DescribeScope.active.?; - if (JSC.host_fn.getFunctionData(callee)) |data| { + if (jsc.host_fn.getFunctionData(callee)) |data| { const allocator = bun.default_allocator; const each_data = bun.cast(*EachData, data); - JSC.host_fn.setFunctionData(callee, null); + jsc.host_fn.setFunctionData(callee, null); const array = each_data.*.strong.get() orelse return .js_undefined; defer { each_data.*.strong.deinit(); @@ -2253,7 +2253,7 @@ fn eachBind(globalThis: *JSGlobalObject, callframe: *CallFrame) bun.JSError!JSVa item.protect(); function_args[0] = item; } - var _label: ?JSC.ZigString.Slice = null; + var _label: ?jsc.ZigString.Slice = null; defer if (_label) |slice| slice.deinit(); const label = brk: { if (description.isEmptyOrUndefinedOrNull()) { @@ -2390,7 +2390,7 @@ inline fn createEach( const allocator = bun.default_allocator; const name = ZigString.static(property); - const strong = JSC.Strong.Optional.create(array, globalThis); + const strong = jsc.Strong.Optional.create(array, globalThis); const each_data = allocator.create(EachData) catch unreachable; each_data.* = EachData{ .strong = strong, @@ -2398,10 +2398,10 @@ inline fn createEach( .line_number = captureTestLineNumber(callframe, globalThis), }; - return JSC.host_fn.NewFunctionWithData(globalThis, name, 3, eachBind, true, each_data); + return jsc.host_fn.NewFunctionWithData(globalThis, name, 3, eachBind, true, each_data); } -fn callJSFunctionForTestRunner(vm: *JSC.VirtualMachine, globalObject: *JSGlobalObject, function: JSValue, args: []const JSValue) JSValue { +fn callJSFunctionForTestRunner(vm: *jsc.VirtualMachine, globalObject: *JSGlobalObject, function: JSValue, args: []const JSValue) JSValue { vm.eventLoop().enter(); defer vm.eventLoop().exit(); @@ -2409,9 +2409,9 @@ fn callJSFunctionForTestRunner(vm: *JSC.VirtualMachine, globalObject: *JSGlobalO return function.call(globalObject, .js_undefined, args) catch |err| globalObject.takeException(err); } -extern fn Bun__CallFrame__getLineNumber(callframe: *JSC.CallFrame, globalObject: *JSC.JSGlobalObject) u32; +extern fn Bun__CallFrame__getLineNumber(callframe: *jsc.CallFrame, globalObject: *jsc.JSGlobalObject) u32; -fn captureTestLineNumber(callframe: *JSC.CallFrame, globalThis: *JSGlobalObject) u32 { +fn captureTestLineNumber(callframe: *jsc.CallFrame, globalThis: *JSGlobalObject) u32 { if (Jest.runner) |runner| { if (runner.test_options.file_reporter == .junit) { return Bun__CallFrame__getLineNumber(callframe, globalThis); @@ -2420,6 +2420,8 @@ fn captureTestLineNumber(callframe: *JSC.CallFrame, globalThis: *JSGlobalObject) return 0; } +const string = []const u8; + const std = @import("std"); const ObjectPool = @import("../../pool.zig").ObjectPool; const Snapshots = @import("./snapshot.zig").Snapshots; @@ -2438,12 +2440,11 @@ const RegularExpression = bun.RegularExpression; const assert = bun.assert; const default_allocator = bun.default_allocator; const logger = bun.logger; -const string = bun.string; -const JSC = bun.JSC; -const CallFrame = JSC.CallFrame; -const JSGlobalObject = JSC.JSGlobalObject; -const JSInternalPromise = JSC.JSInternalPromise; -const JSValue = JSC.JSValue; -const VirtualMachine = JSC.VirtualMachine; -const ZigString = JSC.ZigString; +const jsc = bun.jsc; +const CallFrame = jsc.CallFrame; +const JSGlobalObject = jsc.JSGlobalObject; +const JSInternalPromise = jsc.JSInternalPromise; +const JSValue = jsc.JSValue; +const VirtualMachine = jsc.VirtualMachine; +const ZigString = jsc.ZigString; diff --git a/src/bun.js/test/pretty_format.zig b/src/bun.js/test/pretty_format.zig index 581548d6d6..78ef12787a 100644 --- a/src/bun.js/test/pretty_format.zig +++ b/src/bun.js/test/pretty_format.zig @@ -417,7 +417,7 @@ pub const JestPrettyFormat = struct { if (js_type == .GlobalProxy) { return Tag.get( - JSC.JSValue.c(JSC.C.JSObjectGetProxyTarget(value.asObjectRef())), + jsc.JSValue.c(jsc.C.JSObjectGetProxyTarget(value.asObjectRef())), globalThis, ); } @@ -659,11 +659,11 @@ pub const JestPrettyFormat = struct { return struct { formatter: *JestPrettyFormat.Formatter, writer: Writer, - pub fn forEach(_: *JSC.VM, globalObject: *JSGlobalObject, ctx: ?*anyopaque, nextValue: JSValue) callconv(.C) void { + pub fn forEach(_: *jsc.VM, globalObject: *JSGlobalObject, ctx: ?*anyopaque, nextValue: JSValue) callconv(.C) void { var this: *@This() = bun.cast(*@This(), ctx orelse return); if (this.formatter.failed) return; - const key = JSC.JSObject.getIndex(nextValue, globalObject, 0) catch return; - const value = JSC.JSObject.getIndex(nextValue, globalObject, 1) catch return; + const key = jsc.JSObject.getIndex(nextValue, globalObject, 0) catch return; + const value = jsc.JSObject.getIndex(nextValue, globalObject, 1) catch return; this.formatter.writeIndent(Writer, this.writer) catch return; const key_tag = Tag.get(key, globalObject) catch return; @@ -695,7 +695,7 @@ pub const JestPrettyFormat = struct { return struct { formatter: *JestPrettyFormat.Formatter, writer: Writer, - pub fn forEach(_: *JSC.VM, globalObject: *JSGlobalObject, ctx: ?*anyopaque, nextValue: JSValue) callconv(.C) void { + pub fn forEach(_: *jsc.VM, globalObject: *JSGlobalObject, ctx: ?*anyopaque, nextValue: JSValue) callconv(.C) void { var this: *@This() = bun.cast(*@This(), ctx orelse return); if (this.formatter.failed) return; this.formatter.writeIndent(Writer, this.writer) catch return; @@ -722,7 +722,7 @@ pub const JestPrettyFormat = struct { always_newline: bool = false, parent: JSValue, const enable_ansi_colors = enable_ansi_colors_; - pub fn handleFirstProperty(this: *@This(), globalThis: *JSC.JSGlobalObject, value: JSValue) bun.JSError!void { + pub fn handleFirstProperty(this: *@This(), globalThis: *jsc.JSGlobalObject, value: JSValue) bun.JSError!void { if (!value.jsType().isFunction()) { var writer = WrappedWriter(Writer){ .ctx = this.writer, @@ -1206,7 +1206,7 @@ pub const JestPrettyFormat = struct { this.addForNewLine(1); }, .Private => { - if (value.as(JSC.WebCore.Response)) |response| { + if (value.as(jsc.WebCore.Response)) |response| { response.writeFormat(Formatter, this, writer_, enable_ansi_colors) catch |err| { this.failed = true; // TODO: make this better @@ -1215,7 +1215,7 @@ pub const JestPrettyFormat = struct { } return error.JSError; }; - } else if (value.as(JSC.WebCore.Request)) |request| { + } else if (value.as(jsc.WebCore.Request)) |request| { request.writeFormat(value, Formatter, this, writer_, enable_ansi_colors) catch |err| { this.failed = true; // TODO: make this better @@ -1225,7 +1225,7 @@ pub const JestPrettyFormat = struct { return error.JSError; }; return; - } else if (value.as(JSC.API.BuildArtifact)) |build| { + } else if (value.as(jsc.API.BuildArtifact)) |build| { build.writeFormat(Formatter, this, writer_, enable_ansi_colors) catch |err| { this.failed = true; // TODO: make this better @@ -1234,7 +1234,7 @@ pub const JestPrettyFormat = struct { } return error.JSError; }; - } else if (value.as(JSC.WebCore.Blob)) |blob| { + } else if (value.as(jsc.WebCore.Blob)) |blob| { blob.writeFormat(Formatter, this, writer_, enable_ansi_colors) catch |err| { this.failed = true; // TODO: make this better @@ -1244,7 +1244,7 @@ pub const JestPrettyFormat = struct { return error.JSError; }; return; - } else if (value.as(JSC.DOMFormData) != null) { + } else if (value.as(jsc.DOMFormData) != null) { const toJSONFunction = (try value.get(this.globalThis, "toJSON")).?; this.addForNewLine("FormData (entries) ".len); @@ -1326,7 +1326,7 @@ pub const JestPrettyFormat = struct { writer.writeAll(comptime Output.prettyFmt("" ++ fmt ++ "", enable_ansi_colors)); }, .Map => { - const length_value = try value.get(this.globalThis, "size") orelse JSC.JSValue.jsNumberFromInt32(0); + const length_value = try value.get(this.globalThis, "size") orelse jsc.JSValue.jsNumberFromInt32(0); const length = length_value.toInt32(); const prev_quote_strings = this.quote_strings; @@ -1354,7 +1354,7 @@ pub const JestPrettyFormat = struct { writer.writeAll("\n"); }, .Set => { - const length_value = try value.get(this.globalThis, "size") orelse JSC.JSValue.jsNumberFromInt32(0); + const length_value = try value.get(this.globalThis, "size") orelse jsc.JSValue.jsNumberFromInt32(0); const length = length_value.toInt32(); const prev_quote_strings = this.quote_strings; @@ -1560,7 +1560,7 @@ pub const JestPrettyFormat = struct { // SAFETY: JSX props are always an object. const props_obj = props.getObject().?; - var props_iter = try JSC.JSPropertyIterator(.{ + var props_iter = try jsc.JSPropertyIterator(.{ .skip_empty_name = true, .include_value = true, }).init(this.globalThis, props_obj); @@ -1681,7 +1681,7 @@ pub const JestPrettyFormat = struct { var j: usize = 0; while (j < length) : (j += 1) { - const child = try JSC.JSObject.getIndex(children, this.globalThis, @as(u32, @intCast(j))); + const child = try jsc.JSObject.getIndex(children, this.globalThis, @as(u32, @intCast(j))); try this.format(try Tag.get(child, this.globalThis), Writer, writer_, child, this.globalThis, enable_ansi_colors); if (j + 1 < length) { writer.writeAll("\n"); @@ -2144,6 +2144,8 @@ pub const JestPrettyFormat = struct { } }; +const string = []const u8; + const expect = @import("./expect.zig"); const std = @import("std"); @@ -2151,12 +2153,11 @@ const bun = @import("bun"); const JSLexer = bun.js_lexer; const Output = bun.Output; const default_allocator = bun.default_allocator; -const string = bun.string; const strings = bun.strings; -const JSC = bun.JSC; -const CAPI = JSC.C; -const JSGlobalObject = JSC.JSGlobalObject; -const JSPromise = JSC.JSPromise; -const JSValue = JSC.JSValue; -const ZigString = JSC.ZigString; +const jsc = bun.jsc; +const CAPI = jsc.C; +const JSGlobalObject = jsc.JSGlobalObject; +const JSPromise = jsc.JSPromise; +const JSValue = jsc.JSValue; +const ZigString = jsc.ZigString; diff --git a/src/bun.js/test/snapshot.zig b/src/bun.js/test/snapshot.zig index aabff37f4a..7231a26181 100644 --- a/src/bun.js/test/snapshot.zig +++ b/src/bun.js/test/snapshot.zig @@ -455,7 +455,7 @@ pub const Snapshots = struct { return success; } - fn getSnapshotFile(this: *Snapshots, file_id: TestRunner.File.ID) !JSC.Maybe(void) { + fn getSnapshotFile(this: *Snapshots, file_id: TestRunner.File.ID) !jsc.Maybe(void) { if (this._current_file == null or this._current_file.?.id != file_id) { try this.writeSnapshotFile(); @@ -478,7 +478,7 @@ pub const Snapshots = struct { .err => |err| { switch (err.getErrno()) { .EXIST => this.snapshot_dir_path = dir_path, - else => return JSC.Maybe(void){ + else => return jsc.Maybe(void){ .err = err, }, } @@ -497,7 +497,7 @@ pub const Snapshots = struct { if (this.update_snapshots) flags |= bun.O.TRUNC; const fd = switch (bun.sys.open(snapshot_file_path, flags, 0o644)) { .result => |_fd| _fd, - .err => |err| return JSC.Maybe(void){ + .err => |err| return jsc.Maybe(void){ .err = err, }, }; @@ -529,10 +529,12 @@ pub const Snapshots = struct { this._current_file = file; } - return JSC.Maybe(void).success; + return jsc.Maybe(void).success; } }; +const string = []const u8; + const std = @import("std"); const Expect = @import("./expect.zig").Expect; @@ -541,11 +543,10 @@ const Jest = jest.Jest; const TestRunner = jest.TestRunner; const bun = @import("bun"); -const js_ast = bun.JSAst; +const js_ast = bun.ast; const js_parser = bun.js_parser; const logger = bun.logger; -const string = bun.string; const strings = bun.strings; -const JSC = bun.JSC; -const VirtualMachine = JSC.VirtualMachine; +const jsc = bun.jsc; +const VirtualMachine = jsc.VirtualMachine; diff --git a/src/bun.js/virtual_machine_exports.zig b/src/bun.js/virtual_machine_exports.zig index efb35c7edb..41fa44cafc 100644 --- a/src/bun.js/virtual_machine_exports.zig +++ b/src/bun.js/virtual_machine_exports.zig @@ -8,22 +8,22 @@ pub export fn Bun__VirtualMachine__isShuttingDown(this: *const VirtualMachine) c return this.isShuttingDown(); } -pub export fn Bun__getVM() *JSC.VirtualMachine { - return JSC.VirtualMachine.get(); +pub export fn Bun__getVM() *jsc.VirtualMachine { + return jsc.VirtualMachine.get(); } /// Caller must check for termination exception pub export fn Bun__drainMicrotasks() void { - JSC.VirtualMachine.get().eventLoop().tick(); + jsc.VirtualMachine.get().eventLoop().tick(); } -export fn Bun__readOriginTimer(vm: *JSC.VirtualMachine) u64 { +export fn Bun__readOriginTimer(vm: *jsc.VirtualMachine) u64 { return vm.origin_timer.read(); } -export fn Bun__readOriginTimerStart(vm: *JSC.VirtualMachine) f64 { +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)); + return @as(f64, @floatCast((@as(f64, @floatFromInt(vm.origin_timestamp)) + jsc.VirtualMachine.origin_relative_epoch) / 1_000_000.0)); } pub export fn Bun__GlobalObject__connectedIPC(global: *JSGlobalObject) bool { @@ -42,16 +42,16 @@ pub export fn Bun__GlobalObject__hasIPC(global: *JSGlobalObject) bool { return false; } -export fn Bun__VirtualMachine__exitDuringUncaughtException(this: *JSC.VirtualMachine) void { +export fn Bun__VirtualMachine__exitDuringUncaughtException(this: *jsc.VirtualMachine) void { this.exit_on_uncaught_exception = true; } comptime { - const Bun__Process__send = JSC.toJSHostFn(Bun__Process__send_); + const Bun__Process__send = jsc.toJSHostFn(Bun__Process__send_); @export(&Bun__Process__send, .{ .name = "Bun__Process__send" }); } -pub fn Bun__Process__send_(globalObject: *JSGlobalObject, callFrame: *JSC.CallFrame) bun.JSError!JSValue { - JSC.markBinding(@src()); +pub fn Bun__Process__send_(globalObject: *JSGlobalObject, callFrame: *jsc.CallFrame) bun.JSError!JSValue { + jsc.markBinding(@src()); const vm = globalObject.bunVM(); return IPC.doSend(if (vm.getIPCInstance()) |i| &i.data else null, globalObject, callFrame, .process); @@ -72,20 +72,20 @@ pub export fn Bun__ensureProcessIPCInitialized(globalObject: *JSGlobalObject) vo /// 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 { - JSC.markBinding(@src()); +pub export fn Bun__queueTask(global: *JSGlobalObject, task: *jsc.CppTask) void { + jsc.markBinding(@src()); - global.bunVM().eventLoop().enqueueTask(JSC.Task.init(task)); + global.bunVM().eventLoop().enqueueTask(jsc.Task.init(task)); } -pub export fn Bun__queueTaskWithTimeout(global: *JSGlobalObject, task: *JSC.CppTask, milliseconds: i32) void { - JSC.markBinding(@src()); +pub export fn Bun__queueTaskWithTimeout(global: *JSGlobalObject, task: *jsc.CppTask, milliseconds: i32) void { + jsc.markBinding(@src()); - global.bunVM().eventLoop().enqueueTaskWithTimeout(JSC.Task.init(task), milliseconds); + global.bunVM().eventLoop().enqueueTaskWithTimeout(jsc.Task.init(task), milliseconds); } pub export fn Bun__reportUnhandledError(globalObject: *JSGlobalObject, value: JSValue) callconv(.C) JSValue { - JSC.markBinding(@src()); + jsc.markBinding(@src()); if (!value.isTerminationException()) { _ = globalObject.bunVM().uncaughtException(globalObject, value, false); @@ -96,16 +96,16 @@ pub export fn Bun__reportUnhandledError(globalObject: *JSGlobalObject, value: JS /// 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 { - JSC.markBinding(@src()); +pub export fn Bun__queueTaskConcurrently(global: *JSGlobalObject, task: *jsc.CppTask) void { + jsc.markBinding(@src()); global.bunVMConcurrently().eventLoop().enqueueTaskConcurrent( - JSC.ConcurrentTask.create(JSC.Task.init(task)), + jsc.ConcurrentTask.create(jsc.Task.init(task)), ); } -pub export fn Bun__handleRejectedPromise(global: *JSGlobalObject, promise: *JSC.JSPromise) void { - JSC.markBinding(@src()); +pub export fn Bun__handleRejectedPromise(global: *JSGlobalObject, promise: *jsc.JSPromise) void { + jsc.markBinding(@src()); const result = promise.result(global.vm()); var jsc_vm = global.bunVM(); @@ -118,22 +118,22 @@ pub export fn Bun__handleRejectedPromise(global: *JSGlobalObject, promise: *JSC. jsc_vm.autoGarbageCollect(); } -pub export fn Bun__handleHandledPromise(global: *JSGlobalObject, promise: *JSC.JSPromise) void { +pub export fn Bun__handleHandledPromise(global: *JSGlobalObject, promise: *jsc.JSPromise) void { const Context = struct { - globalThis: *JSC.JSGlobalObject, - promise: JSC.JSValue, + globalThis: *jsc.JSGlobalObject, + promise: jsc.JSValue, pub fn callback(context: *@This()) void { _ = context.globalThis.bunVM().handledPromise(context.globalThis, context.promise); context.promise.unprotect(); bun.default_allocator.destroy(context); } }; - JSC.markBinding(@src()); + jsc.markBinding(@src()); const promise_js = promise.toJS(); promise_js.protect(); const context = bun.default_allocator.create(Context) catch bun.outOfMemory(); context.* = .{ .globalThis = global, .promise = promise_js }; - global.bunVM().eventLoop().enqueueTask(JSC.ManagedTask.New(Context, Context.callback).init(context)); + global.bunVM().eventLoop().enqueueTask(jsc.ManagedTask.New(Context, Context.callback).init(context)); } pub export fn Bun__onDidAppendPlugin(jsc_vm: *VirtualMachine, globalObject: *JSGlobalObject) void { @@ -157,7 +157,7 @@ export fn Bun__setTLSRejectUnauthorizedValue(value: i32) void { } export fn Bun__getTLSRejectUnauthorizedValue() i32 { - return if (JSC.VirtualMachine.get().getTLSRejectUnauthorized()) 1 else 0; + return if (jsc.VirtualMachine.get().getTLSRejectUnauthorized()) 1 else 0; } export fn Bun__setVerboseFetchValue(value: i32) void { @@ -165,7 +165,7 @@ export fn Bun__setVerboseFetchValue(value: i32) void { } export fn Bun__getVerboseFetchValue() i32 { - return switch (JSC.VirtualMachine.get().getVerboseFetch()) { + return switch (jsc.VirtualMachine.get().getVerboseFetch()) { .none => 0, .headers => 1, .curl => 2, @@ -193,7 +193,7 @@ export fn Bun__removeSourceProviderSourceMap(vm: *VirtualMachine, opaque_source_ vm.source_mappings.removeZigSourceProvider(opaque_source_provider, slice.slice()); } -pub fn Bun__setSyntheticAllocationLimitForTesting(globalObject: *JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { +pub fn Bun__setSyntheticAllocationLimitForTesting(globalObject: *JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { const args = callframe.arguments_old(1).slice(); if (args.len < 1) { return globalObject.throwNotEnoughArguments("setSyntheticAllocationLimitForTesting", 1, args.len); @@ -217,7 +217,7 @@ const bun = @import("bun"); const BakeSourceProvider = bun.sourcemap.BakeSourceProvider; const PluginRunner = bun.transpiler.PluginRunner; -const JSC = bun.jsc; -const JSGlobalObject = JSC.JSGlobalObject; -const JSValue = JSC.JSValue; -const VirtualMachine = JSC.VirtualMachine; +const jsc = bun.jsc; +const JSGlobalObject = jsc.JSGlobalObject; +const JSValue = jsc.JSValue; +const VirtualMachine = jsc.VirtualMachine; diff --git a/src/bun.js/web_worker.zig b/src/bun.js/web_worker.zig index 45c7d4c0f3..093fa17664 100644 --- a/src/bun.js/web_worker.zig +++ b/src/bun.js/web_worker.zig @@ -250,7 +250,7 @@ pub fn create( pub fn startWithErrorHandling( this: *WebWorker, ) void { - bun.Analytics.Features.workers_spawned += 1; + bun.analytics.Features.workers_spawned += 1; start(this) catch |err| { Output.panic("An unhandled error occurred while starting a worker: {s}\n", .{@errorName(err)}); }; @@ -291,7 +291,7 @@ pub fn start( var diag: bun.clap.Diagnostic = .{}; var iter: bun.clap.args.SliceIterator = .init(new_args.items); - var args = bun.clap.parseEx(bun.clap.Help, bun.CLI.Command.Tag.RunCommand.params(), &iter, .{ + var args = bun.clap.parseEx(bun.clap.Help, bun.cli.Command.Tag.RunCommand.params(), &iter, .{ .diagnostic = &diag, .allocator = bun.default_allocator, @@ -568,7 +568,7 @@ pub fn notifyNeedTermination(this: *WebWorker) callconv(.c) void { pub fn exitAndDeinit(this: *WebWorker) noreturn { jsc.markBinding(@src()); this.setStatus(.terminated); - bun.Analytics.Features.workers_terminated += 1; + bun.analytics.Features.workers_terminated += 1; log("[{d}] exitAndDeinit", .{this.execution_context_id}); const cpp_worker = this.cpp_worker; diff --git a/src/bun.js/webcore.zig b/src/bun.js/webcore.zig index 029cbb8030..9fcfebfc29 100644 --- a/src/bun.js/webcore.zig +++ b/src/bun.js/webcore.zig @@ -55,7 +55,7 @@ comptime { } pub const PathOrFileDescriptor = union(enum) { - path: JSC.ZigString.Slice, + path: jsc.ZigString.Slice, fd: bun.FileDescriptor, pub fn deinit(this: *const PathOrFileDescriptor) void { @@ -123,4 +123,4 @@ const WebSocketHTTPClient = @import("../http/websocket_http_client.zig").WebSock const WebSocketHTTPSClient = @import("../http/websocket_http_client.zig").WebSocketHTTPSClient; const bun = @import("bun"); -const JSC = bun.JSC; +const jsc = bun.jsc; diff --git a/src/bun.js/webcore/ArrayBufferSink.zig b/src/bun.js/webcore/ArrayBufferSink.zig index 5dde265235..80e5b028cf 100644 --- a/src/bun.js/webcore/ArrayBufferSink.zig +++ b/src/bun.js/webcore/ArrayBufferSink.zig @@ -15,7 +15,7 @@ pub fn connect(this: *ArrayBufferSink, signal: Signal) void { this.signal = signal; } -pub fn start(this: *ArrayBufferSink, stream_start: streams.Start) JSC.Maybe(void) { +pub fn start(this: *ArrayBufferSink, stream_start: streams.Start) jsc.Maybe(void) { this.bytes.len = 0; var list = this.bytes.listManaged(this.allocator); list.clearRetainingCapacity(); @@ -39,15 +39,15 @@ pub fn start(this: *ArrayBufferSink, stream_start: streams.Start) JSC.Maybe(void return .{ .result = {} }; } -pub fn flush(_: *ArrayBufferSink) JSC.Maybe(void) { +pub fn flush(_: *ArrayBufferSink) jsc.Maybe(void) { return .{ .result = {} }; } -pub fn flushFromJS(this: *ArrayBufferSink, globalThis: *JSGlobalObject, wait: bool) JSC.Maybe(JSValue) { +pub fn flushFromJS(this: *ArrayBufferSink, globalThis: *JSGlobalObject, wait: bool) jsc.Maybe(JSValue) { if (this.streaming) { const value: JSValue = switch (this.as_uint8array) { - true => JSC.ArrayBuffer.create(globalThis, this.bytes.slice(), .Uint8Array) catch .zero, // TODO: properly propagate exception upwards - false => JSC.ArrayBuffer.create(globalThis, this.bytes.slice(), .ArrayBuffer) catch .zero, // TODO: properly propagate exception upwards + true => jsc.ArrayBuffer.create(globalThis, this.bytes.slice(), .Uint8Array) catch .zero, // TODO: properly propagate exception upwards + false => jsc.ArrayBuffer.create(globalThis, this.bytes.slice(), .ArrayBuffer) catch .zero, // TODO: properly propagate exception upwards }; this.bytes.len = 0; if (wait) {} @@ -113,7 +113,7 @@ pub fn writeUTF16(this: *@This(), data: streams.Result) streams.Result.Writable return .{ .owned = len }; } -pub fn end(this: *ArrayBufferSink, err: ?Syscall.Error) JSC.Maybe(void) { +pub fn end(this: *ArrayBufferSink, err: ?Syscall.Error) jsc.Maybe(void) { if (this.next) |*next| { return next.end(err); } @@ -127,8 +127,8 @@ pub fn destroy(this: *ArrayBufferSink) void { pub fn toJS(this: *ArrayBufferSink, globalThis: *JSGlobalObject, as_uint8array: bool) JSValue { if (this.streaming) { const value: JSValue = switch (as_uint8array) { - true => JSC.ArrayBuffer.create(globalThis, this.bytes.slice(), .Uint8Array), - false => JSC.ArrayBuffer.create(globalThis, this.bytes.slice(), .ArrayBuffer), + true => jsc.ArrayBuffer.create(globalThis, this.bytes.slice(), .Uint8Array), + false => jsc.ArrayBuffer.create(globalThis, this.bytes.slice(), .ArrayBuffer), }; this.bytes.len = 0; return value; @@ -145,7 +145,7 @@ pub fn toJS(this: *ArrayBufferSink, globalThis: *JSGlobalObject, as_uint8array: ).toJS(globalThis, null); } -pub fn endFromJS(this: *ArrayBufferSink, _: *JSGlobalObject) JSC.Maybe(ArrayBuffer) { +pub fn endFromJS(this: *ArrayBufferSink, _: *JSGlobalObject) jsc.Maybe(ArrayBuffer) { if (this.done) { return .{ .result = ArrayBuffer.fromBytes(&[_]u8{}, .ArrayBuffer) }; } @@ -178,10 +178,10 @@ const std = @import("std"); const bun = @import("bun"); const Syscall = bun.sys; -const JSC = bun.JSC; -const ArrayBuffer = JSC.ArrayBuffer; -const JSGlobalObject = JSC.JSGlobalObject; -const JSValue = JSC.JSValue; +const jsc = bun.jsc; +const ArrayBuffer = jsc.ArrayBuffer; +const JSGlobalObject = jsc.JSGlobalObject; +const JSValue = jsc.JSValue; const webcore = bun.webcore; const Sink = webcore.Sink; diff --git a/src/bun.js/webcore/AutoFlusher.zig b/src/bun.js/webcore/AutoFlusher.zig index 49ef6b1f9f..1a2a9d8f70 100644 --- a/src/bun.js/webcore/AutoFlusher.zig +++ b/src/bun.js/webcore/AutoFlusher.zig @@ -1,26 +1,26 @@ registered: bool = false, -pub fn registerDeferredMicrotaskWithType(comptime Type: type, this: *Type, vm: *JSC.VirtualMachine) void { +pub fn registerDeferredMicrotaskWithType(comptime Type: type, this: *Type, vm: *jsc.VirtualMachine) void { if (this.auto_flusher.registered) return; registerDeferredMicrotaskWithTypeUnchecked(Type, this, vm); } -pub fn unregisterDeferredMicrotaskWithType(comptime Type: type, this: *Type, vm: *JSC.VirtualMachine) void { +pub fn unregisterDeferredMicrotaskWithType(comptime Type: type, this: *Type, vm: *jsc.VirtualMachine) void { if (!this.auto_flusher.registered) return; unregisterDeferredMicrotaskWithTypeUnchecked(Type, this, vm); } -pub fn unregisterDeferredMicrotaskWithTypeUnchecked(comptime Type: type, this: *Type, vm: *JSC.VirtualMachine) void { +pub fn unregisterDeferredMicrotaskWithTypeUnchecked(comptime Type: type, this: *Type, vm: *jsc.VirtualMachine) void { bun.assert(this.auto_flusher.registered); bun.assert(vm.eventLoop().deferred_tasks.unregisterTask(this)); this.auto_flusher.registered = false; } -pub fn registerDeferredMicrotaskWithTypeUnchecked(comptime Type: type, this: *Type, vm: *JSC.VirtualMachine) void { +pub fn registerDeferredMicrotaskWithTypeUnchecked(comptime Type: type, this: *Type, vm: *jsc.VirtualMachine) void { bun.assert(!this.auto_flusher.registered); this.auto_flusher.registered = true; bun.assert(!vm.eventLoop().deferred_tasks.postTask(this, @ptrCast(&Type.onAutoFlush))); } const bun = @import("bun"); -const JSC = bun.JSC; +const jsc = bun.jsc; diff --git a/src/bun.js/webcore/Blob.zig b/src/bun.js/webcore/Blob.zig index d2eaebe8af..afc77c6366 100644 --- a/src/bun.js/webcore/Blob.zig +++ b/src/bun.js/webcore/Blob.zig @@ -14,7 +14,7 @@ pub const write_file = @import("./blob/write_file.zig"); pub const copy_file = @import("./blob/copy_file.zig"); pub const new = bun.TrivialNew(@This()); -pub const js = JSC.Codegen.JSBlob; +pub const js = jsc.Codegen.JSBlob; pub const fromJS = js.fromJS; pub const fromJSDirect = js.fromJSDirect; @@ -106,8 +106,8 @@ pub fn doReadFromS3(this: *Blob, comptime Function: anytype, global: *JSGlobalOb debug("doReadFromS3", .{}); const WrappedFn = struct { - pub fn wrapped(b: *Blob, g: *JSGlobalObject, by: []u8) JSC.JSValue { - return JSC.toJSHostCall(g, @src(), Function, .{ b, g, by, .clone }); + pub fn wrapped(b: *Blob, g: *JSGlobalObject, by: []u8) jsc.JSValue { + return jsc.toJSHostCall(g, @src(), Function, .{ b, g, by, .clone }); } }; return S3BlobDownloadTask.init(global, this, WrappedFn.wrapped); @@ -189,9 +189,9 @@ const FormDataContext = struct { joiner: StringJoiner, boundary: []const u8, failed: bool = false, - globalThis: *JSC.JSGlobalObject, + globalThis: *jsc.JSGlobalObject, - pub fn onEntry(this: *FormDataContext, name: ZigString, entry: JSC.DOMFormData.FormDataEntry) void { + pub fn onEntry(this: *FormDataContext, name: ZigString, entry: jsc.DOMFormData.FormDataEntry) void { if (this.failed) return; var globalThis = this.globalThis; @@ -237,7 +237,7 @@ const FormDataContext = struct { .file => |file| { // TODO: make this async + lazy - const res = JSC.Node.fs.NodeFS.readFile( + const res = jsc.Node.fs.NodeFS.readFile( globalThis.bunVM().nodeFS(), .{ .encoding = .buffer, @@ -281,7 +281,7 @@ pub fn getContentType( const StructuredCloneWriter = struct { ctx: *anyopaque, - impl: *const fn (*anyopaque, ptr: [*]const u8, len: u32) callconv(JSC.conv) void, + impl: *const fn (*anyopaque, ptr: [*]const u8, len: u32) callconv(jsc.conv) void, pub const WriteError = error{}; pub fn write(this: StructuredCloneWriter, bytes: []const u8) WriteError!usize { @@ -321,9 +321,9 @@ fn _onStructuredCloneSerialize( pub fn onStructuredCloneSerialize( this: *Blob, - globalThis: *JSC.JSGlobalObject, + globalThis: *jsc.JSGlobalObject, ctx: *anyopaque, - writeBytes: *const fn (*anyopaque, ptr: [*]const u8, len: u32) callconv(JSC.conv) void, + writeBytes: *const fn (*anyopaque, ptr: [*]const u8, len: u32) callconv(jsc.conv) void, ) void { _ = globalThis; @@ -340,7 +340,7 @@ pub fn onStructuredCloneSerialize( pub fn onStructuredCloneTransfer( this: *Blob, - globalThis: *JSC.JSGlobalObject, + globalThis: *jsc.JSGlobalObject, ctx: *anyopaque, write: *const fn (*anyopaque, ptr: [*]const u8, len: usize) callconv(.C) void, ) void { @@ -381,7 +381,7 @@ fn readSlice( } fn _onStructuredCloneDeserialize( - globalThis: *JSC.JSGlobalObject, + globalThis: *jsc.JSGlobalObject, comptime Reader: type, reader: Reader, ) !JSValue { @@ -423,13 +423,13 @@ fn _onStructuredCloneDeserialize( break :bytes Blob.new(blob); }, .file => file: { - const pathlike_tag = try reader.readEnum(JSC.Node.PathOrFileDescriptor.SerializeTag, .little); + const pathlike_tag = try reader.readEnum(jsc.Node.PathOrFileDescriptor.SerializeTag, .little); switch (pathlike_tag) { .fd => { const fd = try reader.readStruct(bun.FD); - var path_or_fd = JSC.Node.PathOrFileDescriptor{ + var path_or_fd = jsc.Node.PathOrFileDescriptor{ .fd = fd, }; const blob = Blob.new(Blob.findOrCreateFileFromPath( @@ -444,7 +444,7 @@ fn _onStructuredCloneDeserialize( const path_len = try reader.readInt(u32, .little); const path = try readSlice(reader, path_len, default_allocator); - var dest = JSC.Node.PathOrFileDescriptor{ + var dest = jsc.Node.PathOrFileDescriptor{ .path = .{ .string = bun.PathString.init(path), }, @@ -484,7 +484,7 @@ fn _onStructuredCloneDeserialize( return blob.toJS(globalThis); } -pub fn onStructuredCloneDeserialize(globalThis: *JSC.JSGlobalObject, ptr: [*]u8, end: [*]u8) bun.JSError!JSValue { +pub fn onStructuredCloneDeserialize(globalThis: *jsc.JSGlobalObject, ptr: [*]u8, end: [*]u8) bun.JSError!JSValue { const total_length: usize = @intFromPtr(end) - @intFromPtr(ptr); var buffer_stream = std.io.fixedBufferStream(ptr[0..total_length]); const reader = buffer_stream.reader(); @@ -502,7 +502,7 @@ pub fn onStructuredCloneDeserialize(globalThis: *JSC.JSGlobalObject, ptr: [*]u8, const URLSearchParamsConverter = struct { allocator: std.mem.Allocator, buf: []u8 = "", - globalThis: *JSC.JSGlobalObject, + globalThis: *jsc.JSGlobalObject, pub fn convert(this: *URLSearchParamsConverter, str: ZigString) void { var out = str.toSlice(this.allocator).cloneIfNeeded(this.allocator) catch bun.outOfMemory(); this.buf = @constCast(out.slice()); @@ -510,9 +510,9 @@ const URLSearchParamsConverter = struct { }; pub fn fromURLSearchParams( - globalThis: *JSC.JSGlobalObject, + globalThis: *jsc.JSGlobalObject, allocator: std.mem.Allocator, - search_params: *JSC.URLSearchParams, + search_params: *jsc.URLSearchParams, ) Blob { var converter = URLSearchParamsConverter{ .allocator = allocator, @@ -529,9 +529,9 @@ pub fn fromURLSearchParams( } pub fn fromDOMFormData( - globalThis: *JSC.JSGlobalObject, + globalThis: *jsc.JSGlobalObject, allocator: std.mem.Allocator, - form_data: *JSC.DOMFormData, + form_data: *jsc.DOMFormData, ) Blob { var arena = bun.ArenaAllocator.init(allocator); defer arena.deinit(); @@ -578,7 +578,7 @@ pub fn isDetached(this: *const Blob) bool { return this.store == null; } -export fn Blob__dupeFromJS(value: JSC.JSValue) ?*Blob { +export fn Blob__dupeFromJS(value: jsc.JSValue) ?*Blob { const this = Blob.fromJS(value) orelse return null; return Blob__dupe(this); } @@ -782,7 +782,7 @@ const Retry = enum { @"continue", fail, no }; pub noinline fn mkdirIfNotExists(this: anytype, err: bun.sys.Error, path_string: [:0]const u8, err_path: []const u8) Retry { if (err.getErrno() == .NOENT and this.mkdirp_if_not_exists) { if (std.fs.path.dirname(path_string)) |dirname| { - var node_fs: JSC.Node.fs.NodeFS = .{}; + var node_fs: jsc.Node.fs.NodeFS = .{}; switch (node_fs.mkdirRecursive(.{ .path = .{ .string = bun.PathString.init(dirname) }, .recursive = true, @@ -815,7 +815,7 @@ pub noinline fn mkdirIfNotExists(this: anytype, err: bun.sys.Error, path_string: /// Returns an encoded `*JSPromise` that resolves if the file /// - doesn't exist and is created /// - exists and is truncated -fn writeFileWithEmptySourceToDestination(ctx: *JSC.JSGlobalObject, destination_blob: *Blob, options: WriteFileOptions) bun.JSError!JSC.JSValue { +fn writeFileWithEmptySourceToDestination(ctx: *jsc.JSGlobalObject, destination_blob: *Blob, options: WriteFileOptions) bun.JSError!jsc.JSValue { // SAFETY: null-checked by caller const destination_store = destination_blob.store.?; defer destination_blob.detach(); @@ -871,7 +871,7 @@ fn writeFileWithEmptySourceToDestination(ctx: *JSC.JSGlobalObject, destination_b // not above, returning if it is. var buf: bun.PathBuffer = undefined; // TODO: respect `options.mode` - const mode: bun.Mode = JSC.Node.fs.default_permission; + const mode: bun.Mode = jsc.Node.fs.default_permission; while (true) { const open_res = bun.sys.open(file.pathlike.path.sliceZ(&buf), bun.O.CREAT | bun.O.TRUNC, mode); switch (open_res) { @@ -883,7 +883,7 @@ fn writeFileWithEmptySourceToDestination(ctx: *JSC.JSGlobalObject, destination_b }, .result => |fd| { fd.close(); - return JSC.JSPromise.resolvedPromiseValue(ctx, .jsNumber(0)); + return jsc.JSPromise.resolvedPromiseValue(ctx, .jsNumber(0)); }, } } @@ -892,28 +892,28 @@ fn writeFileWithEmptySourceToDestination(ctx: *JSC.JSGlobalObject, destination_b } result.err = result.err.withPathLike(file.pathlike); - return JSC.JSPromise.dangerouslyCreateRejectedPromiseValueWithoutNotifyingVM(ctx, try result.toJS(ctx)); + return jsc.JSPromise.dangerouslyCreateRejectedPromiseValueWithoutNotifyingVM(ctx, try result.toJS(ctx)); } }, .s3 => |*s3| { // create empty file var aws_options = s3.getCredentialsWithOptions(options.extra_options, ctx) catch |err| { - return JSC.JSPromise.dangerouslyCreateRejectedPromiseValueWithoutNotifyingVM(ctx, ctx.takeException(err)); + return jsc.JSPromise.dangerouslyCreateRejectedPromiseValueWithoutNotifyingVM(ctx, ctx.takeException(err)); }; defer aws_options.deinit(); const Wrapper = struct { - promise: JSC.JSPromise.Strong, + promise: jsc.JSPromise.Strong, store: *Store, - global: *JSC.JSGlobalObject, + global: *jsc.JSGlobalObject, pub const new = bun.TrivialNew(@This()); pub fn resolve(result: S3.S3UploadResult, opaque_this: *anyopaque) void { const this: *@This() = @ptrCast(@alignCast(opaque_this)); switch (result) { - .success => this.promise.resolve(this.global, JSC.jsNumber(0)), + .success => this.promise.resolve(this.global, jsc.jsNumber(0)), .failure => |err| this.promise.reject(this.global, err.toJS(this.global, this.store.getPath())), } this.deinit(); @@ -926,7 +926,7 @@ fn writeFileWithEmptySourceToDestination(ctx: *JSC.JSGlobalObject, destination_b } }; - const promise = JSC.JSPromise.Strong.init(ctx); + const promise = jsc.JSPromise.Strong.init(ctx); const promise_value = promise.value(); const proxy = ctx.bunVM().transpiler.env.getHttpProxy(true, null); const proxy_url = if (proxy) |p| p.href else null; @@ -953,10 +953,10 @@ fn writeFileWithEmptySourceToDestination(ctx: *JSC.JSGlobalObject, destination_b .bytes => {}, } - return JSC.JSPromise.resolvedPromiseValue(ctx, JSC.JSValue.jsNumber(0)); + return jsc.JSPromise.resolvedPromiseValue(ctx, jsc.JSValue.jsNumber(0)); } -pub fn writeFileWithSourceDestination(ctx: *JSC.JSGlobalObject, source_blob: *Blob, destination_blob: *Blob, options: WriteFileOptions) bun.JSError!JSC.JSValue { +pub fn writeFileWithSourceDestination(ctx: *jsc.JSGlobalObject, source_blob: *Blob, destination_blob: *Blob, options: WriteFileOptions) bun.JSError!jsc.JSValue { const destination_store = destination_blob.store orelse Output.panic("Destination blob is detached", .{}); const destination_type = std.meta.activeTag(destination_store.data); @@ -1002,7 +1002,7 @@ pub fn writeFileWithSourceDestination(ctx: *JSC.JSGlobalObject, source_blob: *Bl ) catch unreachable; var task = write_file.WriteFileTask.createOnJSThread(bun.default_allocator, ctx, file_copier) catch bun.outOfMemory(); // Defer promise creation until we're just about to schedule the task - var promise = JSC.JSPromise.create(ctx); + var promise = jsc.JSPromise.create(ctx); const promise_value = promise.asValue(ctx); write_file_promise.promise.strong.set(ctx, promise_value); promise_value.ensureStillAlive(); @@ -1033,14 +1033,14 @@ pub fn writeFileWithSourceDestination(ctx: *JSC.JSGlobalObject, source_blob: *Bl return file_copier.promise.value(); } else if (destination_type == .file and source_type == .s3) { const s3 = &source_store.data.s3; - if (try JSC.WebCore.ReadableStream.fromJS(try JSC.WebCore.ReadableStream.fromBlobCopyRef( + if (try jsc.WebCore.ReadableStream.fromJS(try jsc.WebCore.ReadableStream.fromBlobCopyRef( ctx, source_blob, @truncate(s3.options.partSize), ), ctx)) |stream| { return destination_blob.pipeReadableStreamToBlob(ctx, stream, options.extra_options); } else { - return JSC.JSPromise.dangerouslyCreateRejectedPromiseValueWithoutNotifyingVM(ctx, ctx.createErrorInstance("Failed to stream bytes from s3 bucket", .{})); + return jsc.JSPromise.dangerouslyCreateRejectedPromiseValueWithoutNotifyingVM(ctx, ctx.createErrorInstance("Failed to stream bytes from s3 bucket", .{})); } } else if (destination_type == .bytes and source_type == .bytes) { // If this is bytes <> bytes, we can just duplicate it @@ -1062,7 +1062,7 @@ pub fn writeFileWithSourceDestination(ctx: *JSC.JSGlobalObject, source_blob: *Bl } else if (destination_type == .s3) { const s3 = &destination_store.data.s3; var aws_options = s3.getCredentialsWithOptions(options.extra_options, ctx) catch |err| { - return JSC.JSPromise.dangerouslyCreateRejectedPromiseValueWithoutNotifyingVM(ctx, ctx.takeException(err)); + return jsc.JSPromise.dangerouslyCreateRejectedPromiseValueWithoutNotifyingVM(ctx, ctx.takeException(err)); }; defer aws_options.deinit(); const proxy = ctx.bunVM().transpiler.env.getHttpProxy(true, null); @@ -1070,7 +1070,7 @@ pub fn writeFileWithSourceDestination(ctx: *JSC.JSGlobalObject, source_blob: *Bl switch (source_store.data) { .bytes => |bytes| { if (bytes.len > S3.MultiPartUploadOptions.MAX_SINGLE_UPLOAD_SIZE) { - if (try JSC.WebCore.ReadableStream.fromJS(try JSC.WebCore.ReadableStream.fromBlobCopyRef( + if (try jsc.WebCore.ReadableStream.fromJS(try jsc.WebCore.ReadableStream.fromBlobCopyRef( ctx, source_blob, @truncate(s3.options.partSize), @@ -1089,20 +1089,20 @@ pub fn writeFileWithSourceDestination(ctx: *JSC.JSGlobalObject, source_blob: *Bl undefined, ); } else { - return JSC.JSPromise.dangerouslyCreateRejectedPromiseValueWithoutNotifyingVM(ctx, ctx.createErrorInstance("Failed to stream bytes to s3 bucket", .{})); + return jsc.JSPromise.dangerouslyCreateRejectedPromiseValueWithoutNotifyingVM(ctx, ctx.createErrorInstance("Failed to stream bytes to s3 bucket", .{})); } } else { const Wrapper = struct { store: *Store, - promise: JSC.JSPromise.Strong, - global: *JSC.JSGlobalObject, + promise: jsc.JSPromise.Strong, + global: *jsc.JSGlobalObject, pub const new = bun.TrivialNew(@This()); pub fn resolve(result: S3.S3UploadResult, opaque_self: *anyopaque) void { const this: *@This() = @ptrCast(@alignCast(opaque_self)); switch (result) { - .success => this.promise.resolve(this.global, JSC.jsNumber(this.store.data.bytes.len)), + .success => this.promise.resolve(this.global, jsc.jsNumber(this.store.data.bytes.len)), .failure => |err| this.promise.reject(this.global, err.toJS(this.global, this.store.getPath())), } this.deinit(); @@ -1114,7 +1114,7 @@ pub fn writeFileWithSourceDestination(ctx: *JSC.JSGlobalObject, source_blob: *Bl } }; source_store.ref(); - const promise = JSC.JSPromise.Strong.init(ctx); + const promise = jsc.JSPromise.Strong.init(ctx); const promise_value = promise.value(); S3.upload( @@ -1137,7 +1137,7 @@ pub fn writeFileWithSourceDestination(ctx: *JSC.JSGlobalObject, source_blob: *Bl }, .file, .s3 => { // stream - if (try JSC.WebCore.ReadableStream.fromJS(try JSC.WebCore.ReadableStream.fromBlobCopyRef( + if (try jsc.WebCore.ReadableStream.fromJS(try jsc.WebCore.ReadableStream.fromBlobCopyRef( ctx, source_blob, @truncate(s3.options.partSize), @@ -1156,7 +1156,7 @@ pub fn writeFileWithSourceDestination(ctx: *JSC.JSGlobalObject, source_blob: *Bl undefined, ); } else { - return JSC.JSPromise.dangerouslyCreateRejectedPromiseValueWithoutNotifyingVM(ctx, ctx.createErrorInstance("Failed to stream bytes to s3 bucket", .{})); + return jsc.JSPromise.dangerouslyCreateRejectedPromiseValueWithoutNotifyingVM(ctx, ctx.createErrorInstance("Failed to stream bytes to s3 bucket", .{})); } }, } @@ -1174,7 +1174,7 @@ const WriteFileOptions = struct { /// - If `path_or_blob` is a detached blob /// ## Panics /// - If `path_or_blob` is a `Blob` backed by a byte store -pub fn writeFileInternal(globalThis: *JSC.JSGlobalObject, path_or_blob_: *PathOrBlob, data: JSC.JSValue, options: WriteFileOptions) bun.JSError!JSC.JSValue { +pub fn writeFileInternal(globalThis: *jsc.JSGlobalObject, path_or_blob_: *PathOrBlob, data: jsc.JSValue, options: WriteFileOptions) bun.JSError!jsc.JSValue { if (data.isEmptyOrUndefinedOrNull()) { return globalThis.throwInvalidArguments("Bun.write(pathOrFdOrBlob, blob) expects a Blob-y thing to write", .{}); } @@ -1188,7 +1188,7 @@ pub fn writeFileInternal(globalThis: *JSC.JSGlobalObject, path_or_blob_: *PathOr // resetting last_modified at the beginning for better performance. if (blob_store.data == .file) { // reset last_modified to force getLastModified() to reload after writing. - blob_store.data.file.last_modified = JSC.init_timestamp; + blob_store.data.file.last_modified = jsc.init_timestamp; } } @@ -1230,7 +1230,7 @@ pub fn writeFileInternal(globalThis: *JSC.JSGlobalObject, path_or_blob_: *PathOr const str = try data.toBunString(globalThis); defer str.deref(); - const pathlike: JSC.Node.PathOrFileDescriptor = if (path_or_blob == .path) + const pathlike: jsc.Node.PathOrFileDescriptor = if (path_or_blob == .path) path_or_blob.path else path_or_blob.blob.store.?.data.file.pathlike; @@ -1261,7 +1261,7 @@ pub fn writeFileInternal(globalThis: *JSC.JSGlobalObject, path_or_blob_: *PathOr } } else if (data.asArrayBuffer(globalThis)) |buffer_view| { if (buffer_view.byte_len < 256 * 1024) { - const pathlike: JSC.Node.PathOrFileDescriptor = if (path_or_blob == .path) + const pathlike: jsc.Node.PathOrFileDescriptor = if (path_or_blob == .path) path_or_blob.path else path_or_blob.blob.store.?.data.file.pathlike; @@ -1328,7 +1328,7 @@ pub fn writeFileInternal(globalThis: *JSC.JSGlobalObject, path_or_blob_: *PathOr .Error => |*err_ref| { destination_blob.detach(); _ = response.body.value.use(); - return JSC.JSPromise.dangerouslyCreateRejectedPromiseValueWithoutNotifyingVM(globalThis, err_ref.toJS(globalThis)); + return jsc.JSPromise.dangerouslyCreateRejectedPromiseValueWithoutNotifyingVM(globalThis, err_ref.toJS(globalThis)); }, .Locked => |*locked| { if (destination_blob.isS3()) { @@ -1364,7 +1364,7 @@ pub fn writeFileInternal(globalThis: *JSC.JSGlobalObject, path_or_blob_: *PathOr var task = bun.new(WriteFileWaitFromLockedValueTask, .{ .globalThis = globalThis, .file_blob = destination_blob, - .promise = JSC.JSPromise.Strong.init(globalThis), + .promise = jsc.JSPromise.Strong.init(globalThis), .mkdirp_if_not_exists = options.mkdirp_if_not_exists orelse true, }); @@ -1389,7 +1389,7 @@ pub fn writeFileInternal(globalThis: *JSC.JSGlobalObject, path_or_blob_: *PathOr .Error => |*err_ref| { destination_blob.detach(); _ = request.body.value.use(); - return JSC.JSPromise.dangerouslyCreateRejectedPromiseValueWithoutNotifyingVM(globalThis, err_ref.toJS(globalThis)); + return jsc.JSPromise.dangerouslyCreateRejectedPromiseValueWithoutNotifyingVM(globalThis, err_ref.toJS(globalThis)); }, .Locked => |locked| { if (destination_blob.isS3()) { @@ -1424,7 +1424,7 @@ pub fn writeFileInternal(globalThis: *JSC.JSGlobalObject, path_or_blob_: *PathOr var task = bun.new(WriteFileWaitFromLockedValueTask, .{ .globalThis = globalThis, .file_blob = destination_blob, - .promise = JSC.JSPromise.Strong.init(globalThis), + .promise = jsc.JSPromise.Strong.init(globalThis), .mkdirp_if_not_exists = options.mkdirp_if_not_exists orelse true, }); @@ -1465,9 +1465,9 @@ pub fn writeFileInternal(globalThis: *JSC.JSGlobalObject, path_or_blob_: *PathOr } /// `Bun.write(destination, input, options?)` -pub fn writeFile(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { +pub fn writeFile(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const arguments = callframe.arguments(); - var args = JSC.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), arguments); + var args = jsc.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), arguments); defer args.deinit(); // accept a path or a blob @@ -1513,12 +1513,12 @@ pub fn writeFile(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun const write_permissions = 0o664; fn writeStringToFileFast( - globalThis: *JSC.JSGlobalObject, - pathlike: JSC.Node.PathOrFileDescriptor, + globalThis: *jsc.JSGlobalObject, + pathlike: jsc.Node.PathOrFileDescriptor, str: bun.String, needs_async: *bool, comptime needs_open: bool, -) JSC.JSValue { +) jsc.JSValue { const fd: bun.FileDescriptor = if (comptime !needs_open) pathlike.fd else brk: { var file_path: bun.PathBuffer = undefined; switch (bun.sys.open( @@ -1537,7 +1537,7 @@ fn writeStringToFileFast( return .zero; } - return JSC.JSPromise.dangerouslyCreateRejectedPromiseValueWithoutNotifyingVM( + return jsc.JSPromise.dangerouslyCreateRejectedPromiseValueWithoutNotifyingVM( globalThis, err.withPath(pathlike.path.slice()).toJS(globalThis), ); @@ -1580,9 +1580,9 @@ fn writeStringToFileFast( return .zero; } if (comptime !needs_open) { - return JSC.JSPromise.dangerouslyCreateRejectedPromiseValueWithoutNotifyingVM(globalThis, err.toJS(globalThis)); + return jsc.JSPromise.dangerouslyCreateRejectedPromiseValueWithoutNotifyingVM(globalThis, err.toJS(globalThis)); } - return JSC.JSPromise.dangerouslyCreateRejectedPromiseValueWithoutNotifyingVM( + return jsc.JSPromise.dangerouslyCreateRejectedPromiseValueWithoutNotifyingVM( globalThis, err.withPath(pathlike.path.slice()).toJS(globalThis), ); @@ -1591,16 +1591,16 @@ fn writeStringToFileFast( } } - return JSC.JSPromise.resolvedPromiseValue(globalThis, JSC.JSValue.jsNumber(written)); + return jsc.JSPromise.resolvedPromiseValue(globalThis, jsc.JSValue.jsNumber(written)); } fn writeBytesToFileFast( - globalThis: *JSC.JSGlobalObject, - pathlike: JSC.Node.PathOrFileDescriptor, + globalThis: *jsc.JSGlobalObject, + pathlike: jsc.Node.PathOrFileDescriptor, bytes: []const u8, needs_async: *bool, comptime needs_open: bool, -) JSC.JSValue { +) jsc.JSValue { const fd: bun.FileDescriptor = if (comptime !needs_open) pathlike.fd else brk: { var file_path: bun.PathBuffer = undefined; switch (bun.sys.open( @@ -1624,7 +1624,7 @@ fn writeBytesToFileFast( } } - return JSC.JSPromise.dangerouslyCreateRejectedPromiseValueWithoutNotifyingVM( + return jsc.JSPromise.dangerouslyCreateRejectedPromiseValueWithoutNotifyingVM( globalThis, err.withPath(pathlike.path.slice()).toJS(globalThis), ); @@ -1657,12 +1657,12 @@ fn writeBytesToFileFast( } } if (comptime !needs_open) { - return JSC.JSPromise.dangerouslyCreateRejectedPromiseValueWithoutNotifyingVM( + return jsc.JSPromise.dangerouslyCreateRejectedPromiseValueWithoutNotifyingVM( globalThis, err.toJS(globalThis), ); } - return JSC.JSPromise.dangerouslyCreateRejectedPromiseValueWithoutNotifyingVM( + return jsc.JSPromise.dangerouslyCreateRejectedPromiseValueWithoutNotifyingVM( globalThis, err.withPath(pathlike.path.slice()).toJS(globalThis), ); @@ -1678,9 +1678,9 @@ fn writeBytesToFileFast( } } - return JSC.JSPromise.resolvedPromiseValue(globalThis, JSC.JSValue.jsNumber(written)); + return jsc.JSPromise.resolvedPromiseValue(globalThis, jsc.JSValue.jsNumber(written)); } -export fn JSDOMFile__construct(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) callconv(JSC.conv) ?*Blob { +export fn JSDOMFile__construct(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) callconv(jsc.conv) ?*Blob { return JSDOMFile__construct_(globalThis, callframe) catch |err| switch (err) { error.JSError => null, error.OutOfMemory => { @@ -1689,8 +1689,8 @@ export fn JSDOMFile__construct(globalThis: *JSC.JSGlobalObject, callframe: *JSC. }, }; } -pub fn JSDOMFile__construct_(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!*Blob { - JSC.markBinding(@src()); +pub fn JSDOMFile__construct_(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!*Blob { + jsc.markBinding(@src()); const allocator = bun.default_allocator; var blob: Blob = undefined; var arguments = callframe.arguments_old(3); @@ -1823,15 +1823,15 @@ comptime { } pub fn constructBunFile( - globalObject: *JSC.JSGlobalObject, - callframe: *JSC.CallFrame, -) bun.JSError!JSC.JSValue { + globalObject: *jsc.JSGlobalObject, + callframe: *jsc.CallFrame, +) bun.JSError!jsc.JSValue { var vm = globalObject.bunVM(); const arguments = callframe.arguments_old(2).slice(); - var args = JSC.CallFrame.ArgumentsSlice.init(vm, arguments); + var args = jsc.CallFrame.ArgumentsSlice.init(vm, arguments); defer args.deinit(); - var path = (try JSC.Node.PathOrFileDescriptor.fromJS(globalObject, &args, bun.default_allocator)) orelse { + var path = (try jsc.Node.PathOrFileDescriptor.fromJS(globalObject, &args, bun.default_allocator)) orelse { return globalObject.throwInvalidArguments("Expected file path string or file descriptor", .{}); }; const options = if (arguments.len >= 2) arguments[1] else null; @@ -1879,7 +1879,7 @@ pub fn constructBunFile( return ptr.toJS(globalObject); } -pub fn findOrCreateFileFromPath(path_or_fd: *JSC.Node.PathOrFileDescriptor, globalThis: *JSGlobalObject, comptime check_s3: bool) Blob { +pub fn findOrCreateFileFromPath(path_or_fd: *jsc.Node.PathOrFileDescriptor, globalThis: *JSGlobalObject, comptime check_s3: bool) Blob { var vm = globalThis.bunVM(); const allocator = bun.default_allocator; if (check_s3) { @@ -1893,7 +1893,7 @@ pub fn findOrCreateFileFromPath(path_or_fd: *JSC.Node.PathOrFileDescriptor, glob } } - const path: JSC.Node.PathOrFileDescriptor = brk: { + const path: jsc.Node.PathOrFileDescriptor = brk: { switch (path_or_fd.*) { .path => { var slice = path_or_fd.path.slice(); @@ -1947,9 +1947,9 @@ pub fn findOrCreateFileFromPath(path_or_fd: *JSC.Node.PathOrFileDescriptor, glob pub fn getStream( this: *Blob, - globalThis: *JSC.JSGlobalObject, - callframe: *JSC.CallFrame, -) bun.JSError!JSC.JSValue { + globalThis: *jsc.JSGlobalObject, + callframe: *jsc.CallFrame, +) bun.JSError!jsc.JSValue { const thisValue = callframe.this(); if (js.streamGetCached(thisValue)) |cached| { return cached; @@ -1964,7 +1964,7 @@ pub fn getStream( recommended_chunk_size = @as(SizeType, @intCast(@max(0, @as(i52, @truncate(arguments[0].toInt64()))))); } - const stream = try JSC.WebCore.ReadableStream.fromBlobCopyRef( + const stream = try jsc.WebCore.ReadableStream.fromBlobCopyRef( globalThis, this, recommended_chunk_size, @@ -1989,13 +1989,13 @@ pub fn getStream( } pub fn toStreamWithOffset( - globalThis: *JSC.JSGlobalObject, - callframe: *JSC.CallFrame, -) bun.JSError!JSC.JSValue { + globalThis: *jsc.JSGlobalObject, + callframe: *jsc.CallFrame, +) bun.JSError!jsc.JSValue { const this = callframe.this().as(Blob) orelse @panic("this is not a Blob"); const args = callframe.arguments_old(1).slice(); - return JSC.WebCore.ReadableStream.fromFileBlobWithOffset( + return jsc.WebCore.ReadableStream.fromFileBlobWithOffset( globalThis, this, @intCast(args[0].toInt64()), @@ -2003,129 +2003,129 @@ pub fn toStreamWithOffset( } // Zig doesn't let you pass a function with a comptime argument to a runtime-knwon function. -fn lifetimeWrap(comptime Fn: anytype, comptime lifetime: JSC.WebCore.Lifetime) fn (*Blob, *JSC.JSGlobalObject) JSC.JSValue { +fn lifetimeWrap(comptime Fn: anytype, comptime lifetime: jsc.WebCore.Lifetime) fn (*Blob, *jsc.JSGlobalObject) jsc.JSValue { return struct { - fn wrap(this: *Blob, globalObject: *JSC.JSGlobalObject) JSC.JSValue { - return JSC.toJSHostCall(globalObject, @src(), Fn, .{ this, globalObject, lifetime }); + fn wrap(this: *Blob, globalObject: *jsc.JSGlobalObject) jsc.JSValue { + return jsc.toJSHostCall(globalObject, @src(), Fn, .{ this, globalObject, lifetime }); } }.wrap; } pub fn getText( this: *Blob, - globalThis: *JSC.JSGlobalObject, - _: *JSC.CallFrame, -) bun.JSError!JSC.JSValue { + globalThis: *jsc.JSGlobalObject, + _: *jsc.CallFrame, +) bun.JSError!jsc.JSValue { return this.getTextClone(globalThis); } pub fn getTextClone( this: *Blob, - globalObject: *JSC.JSGlobalObject, -) JSC.JSValue { + globalObject: *jsc.JSGlobalObject, +) jsc.JSValue { const store = this.store; if (store) |st| st.ref(); defer if (store) |st| st.deref(); - return JSC.JSPromise.wrap(globalObject, lifetimeWrap(toString, .clone), .{ this, globalObject }); + return jsc.JSPromise.wrap(globalObject, lifetimeWrap(toString, .clone), .{ this, globalObject }); } pub fn getTextTransfer( this: *Blob, - globalObject: *JSC.JSGlobalObject, -) JSC.JSValue { + globalObject: *jsc.JSGlobalObject, +) jsc.JSValue { const store = this.store; if (store) |st| st.ref(); defer if (store) |st| st.deref(); - return JSC.JSPromise.wrap(globalObject, lifetimeWrap(toString, .transfer), .{ this, globalObject }); + return jsc.JSPromise.wrap(globalObject, lifetimeWrap(toString, .transfer), .{ this, globalObject }); } pub fn getJSON( this: *Blob, - globalThis: *JSC.JSGlobalObject, - _: *JSC.CallFrame, -) bun.JSError!JSC.JSValue { + globalThis: *jsc.JSGlobalObject, + _: *jsc.CallFrame, +) bun.JSError!jsc.JSValue { return this.getJSONShare(globalThis); } pub fn getJSONShare( this: *Blob, - globalObject: *JSC.JSGlobalObject, -) JSC.JSValue { + globalObject: *jsc.JSGlobalObject, +) jsc.JSValue { const store = this.store; if (store) |st| st.ref(); defer if (store) |st| st.deref(); - return JSC.JSPromise.wrap(globalObject, lifetimeWrap(toJSON, .share), .{ this, globalObject }); + return jsc.JSPromise.wrap(globalObject, lifetimeWrap(toJSON, .share), .{ this, globalObject }); } pub fn getArrayBufferTransfer( this: *Blob, - globalThis: *JSC.JSGlobalObject, -) JSC.JSValue { + globalThis: *jsc.JSGlobalObject, +) jsc.JSValue { const store = this.store; if (store) |st| st.ref(); defer if (store) |st| st.deref(); - return JSC.JSPromise.wrap(globalThis, lifetimeWrap(toArrayBuffer, .transfer), .{ this, globalThis }); + return jsc.JSPromise.wrap(globalThis, lifetimeWrap(toArrayBuffer, .transfer), .{ this, globalThis }); } pub fn getArrayBufferClone( this: *Blob, - globalThis: *JSC.JSGlobalObject, -) JSC.JSValue { + globalThis: *jsc.JSGlobalObject, +) jsc.JSValue { const store = this.store; if (store) |st| st.ref(); defer if (store) |st| st.deref(); - return JSC.JSPromise.wrap(globalThis, lifetimeWrap(toArrayBuffer, .clone), .{ this, globalThis }); + return jsc.JSPromise.wrap(globalThis, lifetimeWrap(toArrayBuffer, .clone), .{ this, globalThis }); } pub fn getArrayBuffer( this: *Blob, - globalThis: *JSC.JSGlobalObject, - _: *JSC.CallFrame, + globalThis: *jsc.JSGlobalObject, + _: *jsc.CallFrame, ) bun.JSError!JSValue { return this.getArrayBufferClone(globalThis); } pub fn getBytesClone( this: *Blob, - globalThis: *JSC.JSGlobalObject, + globalThis: *jsc.JSGlobalObject, ) JSValue { const store = this.store; if (store) |st| st.ref(); defer if (store) |st| st.deref(); - return JSC.JSPromise.wrap(globalThis, lifetimeWrap(toUint8Array, .clone), .{ this, globalThis }); + return jsc.JSPromise.wrap(globalThis, lifetimeWrap(toUint8Array, .clone), .{ this, globalThis }); } pub fn getBytes( this: *Blob, - globalThis: *JSC.JSGlobalObject, - _: *JSC.CallFrame, + globalThis: *jsc.JSGlobalObject, + _: *jsc.CallFrame, ) bun.JSError!JSValue { return this.getBytesClone(globalThis); } pub fn getBytesTransfer( this: *Blob, - globalThis: *JSC.JSGlobalObject, + globalThis: *jsc.JSGlobalObject, ) JSValue { const store = this.store; if (store) |st| st.ref(); defer if (store) |st| st.deref(); - return JSC.JSPromise.wrap(globalThis, lifetimeWrap(toUint8Array, .transfer), .{ this, globalThis }); + return jsc.JSPromise.wrap(globalThis, lifetimeWrap(toUint8Array, .transfer), .{ this, globalThis }); } pub fn getFormData( this: *Blob, - globalThis: *JSC.JSGlobalObject, - _: *JSC.CallFrame, + globalThis: *jsc.JSGlobalObject, + _: *jsc.CallFrame, ) bun.JSError!JSValue { const store = this.store; if (store) |st| st.ref(); defer if (store) |st| st.deref(); - return JSC.JSPromise.wrap(globalThis, lifetimeWrap(toFormData, .temporary), .{ this, globalThis }); + return jsc.JSPromise.wrap(globalThis, lifetimeWrap(toFormData, .temporary), .{ this, globalThis }); } -fn getExistsSync(this: *Blob) JSC.JSValue { +fn getExistsSync(this: *Blob) jsc.JSValue { if (this.size == Blob.max_size) { this.resolveSize(); } @@ -2155,8 +2155,8 @@ pub fn isS3(this: *const Blob) bool { const S3BlobDownloadTask = struct { blob: Blob, - globalThis: *JSC.JSGlobalObject, - promise: JSC.JSPromise.Strong, + globalThis: *jsc.JSGlobalObject, + promise: jsc.JSPromise.Strong, poll_ref: bun.Async.KeepAlive = .{}, handler: S3ReadHandler, @@ -2174,7 +2174,7 @@ const S3BlobDownloadTask = struct { if (this.blob.size == Blob.max_size) { this.blob.size = @truncate(bytes.len); } - JSC.AnyPromise.wrap(.{ .normal = this.promise.get() }, this.globalThis, S3BlobDownloadTask.callHandler, .{ this, bytes }); + jsc.AnyPromise.wrap(.{ .normal = this.promise.get() }, this.globalThis, S3BlobDownloadTask.callHandler, .{ this, bytes }); }, inline .not_found, .failure => |err| { this.promise.reject(this.globalThis, err.toJS(this.globalThis, this.blob.store.?.getPath())); @@ -2182,13 +2182,13 @@ const S3BlobDownloadTask = struct { } } - pub fn init(globalThis: *JSC.JSGlobalObject, blob: *Blob, handler: S3BlobDownloadTask.S3ReadHandler) JSValue { + pub fn init(globalThis: *jsc.JSGlobalObject, blob: *Blob, handler: S3BlobDownloadTask.S3ReadHandler) JSValue { blob.store.?.ref(); const this = S3BlobDownloadTask.new(.{ .globalThis = globalThis, .blob = blob.*, - .promise = JSC.JSPromise.Strong.init(globalThis), + .promise = jsc.JSPromise.Strong.init(globalThis), .handler = handler, }); const promise = this.promise.value(); @@ -2219,9 +2219,9 @@ const S3BlobDownloadTask = struct { } }; -pub fn doWrite(this: *Blob, globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { +pub fn doWrite(this: *Blob, globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { const arguments = callframe.arguments_old(3).slice(); - var args = JSC.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), arguments); + var args = jsc.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), arguments); defer args.deinit(); const data = args.nextEat() orelse { @@ -2271,36 +2271,36 @@ pub fn doWrite(this: *Blob, globalThis: *JSC.JSGlobalObject, callframe: *JSC.Cal return writeFileInternal(globalThis, &blob_internal, data, .{ .mkdirp_if_not_exists = mkdirp_if_not_exists, .extra_options = options }); } -pub fn doUnlink(this: *Blob, globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { +pub fn doUnlink(this: *Blob, globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { const arguments = callframe.arguments_old(1).slice(); - var args = JSC.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), arguments); + var args = jsc.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), arguments); defer args.deinit(); const store = this.store orelse { - return JSC.JSPromise.resolvedPromiseValue(globalThis, globalThis.createInvalidArgs("Blob is detached", .{})); + return jsc.JSPromise.resolvedPromiseValue(globalThis, globalThis.createInvalidArgs("Blob is detached", .{})); }; return switch (store.data) { .s3 => |*s3| try s3.unlink(store, globalThis, args.nextEat()), .file => |file| file.unlink(globalThis), - else => JSC.JSPromise.resolvedPromiseValue(globalThis, globalThis.createInvalidArgs("Blob is read-only", .{})), + else => jsc.JSPromise.resolvedPromiseValue(globalThis, globalThis.createInvalidArgs("Blob is read-only", .{})), }; } // This mostly means 'can it be read?' pub fn getExists( this: *Blob, - globalThis: *JSC.JSGlobalObject, - _: *JSC.CallFrame, + globalThis: *jsc.JSGlobalObject, + _: *jsc.CallFrame, ) bun.JSError!JSValue { if (this.isS3()) { return S3File.S3BlobStatTask.exists(globalThis, this); } - return JSC.JSPromise.resolvedPromiseValue(globalThis, this.getExistsSync()); + return jsc.JSPromise.resolvedPromiseValue(globalThis, this.getExistsSync()); } pub const FileStreamWrapper = struct { - promise: JSC.JSPromise.Strong, - readable_stream_ref: JSC.WebCore.ReadableStream.Strong, - sink: *JSC.WebCore.FileSink, + promise: jsc.JSPromise.Strong, + readable_stream_ref: jsc.WebCore.ReadableStream.Strong, + sink: *jsc.WebCore.FileSink, pub const new = bun.TrivialNew(@This()); @@ -2312,7 +2312,7 @@ pub const FileStreamWrapper = struct { } }; -pub fn onFileStreamResolveRequestStream(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { +pub fn onFileStreamResolveRequestStream(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { var args = callframe.arguments_old(2); var this = args.ptr[args.len - 1].asPromisePtr(FileStreamWrapper); defer this.deinit(); @@ -2322,11 +2322,11 @@ pub fn onFileStreamResolveRequestStream(globalThis: *JSC.JSGlobalObject, callfra if (strong.get(globalThis)) |stream| { stream.done(globalThis); } - this.promise.resolve(globalThis, JSC.JSValue.jsNumber(0)); + this.promise.resolve(globalThis, jsc.JSValue.jsNumber(0)); return .js_undefined; } -pub fn onFileStreamRejectRequestStream(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { +pub fn onFileStreamRejectRequestStream(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const args = callframe.arguments_old(2); var this = args.ptr[args.len - 1].asPromisePtr(FileStreamWrapper); defer this.sink.deref(); @@ -2344,21 +2344,21 @@ pub fn onFileStreamRejectRequestStream(globalThis: *JSC.JSGlobalObject, callfram return .js_undefined; } comptime { - const jsonResolveRequestStream = JSC.toJSHostFn(onFileStreamResolveRequestStream); + const jsonResolveRequestStream = jsc.toJSHostFn(onFileStreamResolveRequestStream); @export(&jsonResolveRequestStream, .{ .name = "Bun__FileStreamWrapper__onResolveRequestStream" }); - const jsonRejectRequestStream = JSC.toJSHostFn(onFileStreamRejectRequestStream); + const jsonRejectRequestStream = jsc.toJSHostFn(onFileStreamRejectRequestStream); @export(&jsonRejectRequestStream, .{ .name = "Bun__FileStreamWrapper__onRejectRequestStream" }); } -pub fn pipeReadableStreamToBlob(this: *Blob, globalThis: *JSC.JSGlobalObject, readable_stream: JSC.WebCore.ReadableStream, extra_options: ?JSValue) JSC.JSValue { +pub fn pipeReadableStreamToBlob(this: *Blob, globalThis: *jsc.JSGlobalObject, readable_stream: jsc.WebCore.ReadableStream, extra_options: ?JSValue) jsc.JSValue { var store = this.store orelse { - return JSC.JSPromise.dangerouslyCreateRejectedPromiseValueWithoutNotifyingVM(globalThis, globalThis.createErrorInstance("Blob is detached", .{})); + return jsc.JSPromise.dangerouslyCreateRejectedPromiseValueWithoutNotifyingVM(globalThis, globalThis.createErrorInstance("Blob is detached", .{})); }; if (this.isS3()) { const s3 = &this.store.?.data.s3; var aws_options = s3.getCredentialsWithOptions(extra_options, globalThis) catch |err| { - return JSC.JSPromise.dangerouslyCreateRejectedPromiseValueWithoutNotifyingVM(globalThis, globalThis.takeException(err)); + return jsc.JSPromise.dangerouslyCreateRejectedPromiseValueWithoutNotifyingVM(globalThis, globalThis.takeException(err)); }; defer aws_options.deinit(); @@ -2382,7 +2382,7 @@ pub fn pipeReadableStreamToBlob(this: *Blob, globalThis: *JSC.JSGlobalObject, re } if (store.data != .file) { - return JSC.JSPromise.dangerouslyCreateRejectedPromiseValueWithoutNotifyingVM(globalThis, globalThis.createErrorInstance("Blob is read-only", .{})); + return jsc.JSPromise.dangerouslyCreateRejectedPromiseValueWithoutNotifyingVM(globalThis, globalThis.createErrorInstance("Blob is read-only", .{})); } const file_sink = brk_sink: { @@ -2400,7 +2400,7 @@ pub fn pipeReadableStreamToBlob(this: *Blob, globalThis: *JSC.JSGlobalObject, re break :brk result; }, .err => |err| { - return JSC.JSPromise.dangerouslyCreateRejectedPromiseValueWithoutNotifyingVM(globalThis, err.withPath(path).toJS(globalThis)); + return jsc.JSPromise.dangerouslyCreateRejectedPromiseValueWithoutNotifyingVM(globalThis, err.withPath(path).toJS(globalThis)); }, } unreachable; @@ -2426,14 +2426,14 @@ pub fn pipeReadableStreamToBlob(this: *Blob, globalThis: *JSC.JSGlobalObject, re else => false, } else false; }; - var sink = JSC.WebCore.FileSink.init(fd, this.globalThis.bunVM().eventLoop()); + var sink = jsc.WebCore.FileSink.init(fd, this.globalThis.bunVM().eventLoop()); sink.writer.owns_fd = pathlike != .fd; if (is_stdout_or_stderr) { switch (sink.writer.startSync(fd, false)) { .err => |err| { sink.deref(); - return JSC.JSPromise.dangerouslyCreateRejectedPromiseValueWithoutNotifyingVM(globalThis, err.toJS(globalThis)); + return jsc.JSPromise.dangerouslyCreateRejectedPromiseValueWithoutNotifyingVM(globalThis, err.toJS(globalThis)); }, else => {}, } @@ -2441,7 +2441,7 @@ pub fn pipeReadableStreamToBlob(this: *Blob, globalThis: *JSC.JSGlobalObject, re switch (sink.writer.start(fd, true)) { .err => |err| { sink.deref(); - return JSC.JSPromise.dangerouslyCreateRejectedPromiseValueWithoutNotifyingVM(globalThis, err.toJS(globalThis)); + return jsc.JSPromise.dangerouslyCreateRejectedPromiseValueWithoutNotifyingVM(globalThis, err.toJS(globalThis)); }, else => {}, } @@ -2450,9 +2450,9 @@ pub fn pipeReadableStreamToBlob(this: *Blob, globalThis: *JSC.JSGlobalObject, re break :brk_sink sink; } - var sink = JSC.WebCore.FileSink.init(bun.invalid_fd, this.globalThis.bunVM().eventLoop()); + var sink = jsc.WebCore.FileSink.init(bun.invalid_fd, this.globalThis.bunVM().eventLoop()); - const input_path: JSC.WebCore.PathOrFileDescriptor = brk: { + const input_path: jsc.WebCore.PathOrFileDescriptor = brk: { if (store.data.file.pathlike == .fd) { break :brk .{ .fd = store.data.file.pathlike.fd }; } else { @@ -2467,7 +2467,7 @@ pub fn pipeReadableStreamToBlob(this: *Blob, globalThis: *JSC.JSGlobalObject, re }; defer input_path.deinit(); - const stream_start: JSC.WebCore.streams.Start = .{ + const stream_start: jsc.WebCore.streams.Start = .{ .FileSink = .{ .input_path = input_path, }, @@ -2476,7 +2476,7 @@ pub fn pipeReadableStreamToBlob(this: *Blob, globalThis: *JSC.JSGlobalObject, re switch (sink.start(stream_start)) { .err => |err| { sink.deref(); - return JSC.JSPromise.dangerouslyCreateRejectedPromiseValueWithoutNotifyingVM(globalThis, err.toJS(globalThis)); + return jsc.JSPromise.dangerouslyCreateRejectedPromiseValueWithoutNotifyingVM(globalThis, err.toJS(globalThis)); }, else => {}, } @@ -2484,14 +2484,14 @@ pub fn pipeReadableStreamToBlob(this: *Blob, globalThis: *JSC.JSGlobalObject, re }; var signal = &file_sink.signal; - signal.* = JSC.WebCore.FileSink.JSSink.SinkSignal.init(.zero); + signal.* = jsc.WebCore.FileSink.JSSink.SinkSignal.init(.zero); // explicitly set it to a dead pointer // we use this memory address to disable signals being sent signal.clear(); bun.assert(signal.isDead()); - const assignment_result: JSC.JSValue = JSC.WebCore.FileSink.JSSink.assignToStream( + const assignment_result: jsc.JSValue = jsc.WebCore.FileSink.JSSink.assignToStream( globalThis, readable_stream.value, file_sink, @@ -2505,7 +2505,7 @@ pub fn pipeReadableStreamToBlob(this: *Blob, globalThis: *JSC.JSGlobalObject, re if (assignment_result.toError()) |err| { file_sink.deref(); - return JSC.JSPromise.dangerouslyCreateRejectedPromiseValueWithoutNotifyingVM(globalThis, err); + return jsc.JSPromise.dangerouslyCreateRejectedPromiseValueWithoutNotifyingVM(globalThis, err); } if (!assignment_result.isEmptyOrUndefinedOrNull()) { @@ -2517,8 +2517,8 @@ pub fn pipeReadableStreamToBlob(this: *Blob, globalThis: *JSC.JSGlobalObject, re switch (promise.status(globalThis.vm())) { .pending => { const wrapper = FileStreamWrapper.new(.{ - .promise = JSC.JSPromise.Strong.init(globalThis), - .readable_stream_ref = JSC.WebCore.ReadableStream.Strong.init(readable_stream, globalThis), + .promise = jsc.JSPromise.Strong.init(globalThis), + .readable_stream_ref = jsc.WebCore.ReadableStream.Strong.init(readable_stream, globalThis), .sink = file_sink, }); const promise_value = wrapper.promise.value(); @@ -2534,14 +2534,14 @@ pub fn pipeReadableStreamToBlob(this: *Blob, globalThis: *JSC.JSGlobalObject, re .fulfilled => { file_sink.deref(); readable_stream.done(globalThis); - return JSC.JSPromise.resolvedPromiseValue(globalThis, JSC.JSValue.jsNumber(0)); + return jsc.JSPromise.resolvedPromiseValue(globalThis, jsc.JSValue.jsNumber(0)); }, .rejected => { file_sink.deref(); readable_stream.cancel(globalThis); - return JSC.JSPromise.dangerouslyCreateRejectedPromiseValueWithoutNotifyingVM(globalThis, promise.result(globalThis.vm())); + return jsc.JSPromise.dangerouslyCreateRejectedPromiseValueWithoutNotifyingVM(globalThis, promise.result(globalThis.vm())); }, } } else { @@ -2549,19 +2549,19 @@ pub fn pipeReadableStreamToBlob(this: *Blob, globalThis: *JSC.JSGlobalObject, re readable_stream.cancel(globalThis); - return JSC.JSPromise.dangerouslyCreateRejectedPromiseValueWithoutNotifyingVM(globalThis, assignment_result); + return jsc.JSPromise.dangerouslyCreateRejectedPromiseValueWithoutNotifyingVM(globalThis, assignment_result); } } file_sink.deref(); - return JSC.JSPromise.resolvedPromiseValue(globalThis, JSC.JSValue.jsNumber(0)); + return jsc.JSPromise.resolvedPromiseValue(globalThis, jsc.JSValue.jsNumber(0)); } pub fn getWriter( this: *Blob, - globalThis: *JSC.JSGlobalObject, - callframe: *JSC.CallFrame, -) bun.JSError!JSC.JSValue { + globalThis: *jsc.JSGlobalObject, + callframe: *jsc.CallFrame, +) bun.JSError!jsc.JSValue { var arguments_ = callframe.arguments_old(1); var arguments = arguments_.ptr[0..arguments_.len]; @@ -2669,7 +2669,7 @@ pub fn getWriter( else => false, } else false; }; - var sink = JSC.WebCore.FileSink.init(fd, this.globalThis.bunVM().eventLoop()); + var sink = jsc.WebCore.FileSink.init(fd, this.globalThis.bunVM().eventLoop()); sink.writer.owns_fd = pathlike != .fd; if (is_stdout_or_stderr) { @@ -2693,9 +2693,9 @@ pub fn getWriter( return sink.toJS(globalThis); } - var sink = JSC.WebCore.FileSink.init(bun.invalid_fd, this.globalThis.bunVM().eventLoop()); + var sink = jsc.WebCore.FileSink.init(bun.invalid_fd, this.globalThis.bunVM().eventLoop()); - const input_path: JSC.WebCore.PathOrFileDescriptor = brk: { + const input_path: jsc.WebCore.PathOrFileDescriptor = brk: { if (store.data.file.pathlike == .fd) { break :brk .{ .fd = store.data.file.pathlike.fd }; } else { @@ -2717,7 +2717,7 @@ pub fn getWriter( }; if (arguments.len > 0 and arguments.ptr[0].isObject()) { - stream_start = try JSC.WebCore.streams.Start.fromJSWithTag(globalThis, arguments[0], .FileSink); + stream_start = try jsc.WebCore.streams.Start.fromJSWithTag(globalThis, arguments[0], .FileSink); stream_start.FileSink.input_path = input_path; } @@ -2732,7 +2732,7 @@ pub fn getWriter( return sink.toJS(globalThis); } -pub fn getSliceFrom(this: *Blob, globalThis: *JSC.JSGlobalObject, relativeStart: i64, relativeEnd: i64, content_type: []const u8, content_type_was_allocated: bool) JSValue { +pub fn getSliceFrom(this: *Blob, globalThis: *jsc.JSGlobalObject, relativeStart: i64, relativeEnd: i64, content_type: []const u8, content_type_was_allocated: bool) JSValue { const offset = this.offset +| @as(SizeType, @intCast(relativeStart)); const len = @as(SizeType, @intCast(@max(relativeEnd -| relativeStart, 0))); @@ -2763,9 +2763,9 @@ pub fn getSliceFrom(this: *Blob, globalThis: *JSC.JSGlobalObject, relativeStart: /// contentType parameter. It must act as follows: pub fn getSlice( this: *Blob, - globalThis: *JSC.JSGlobalObject, - callframe: *JSC.CallFrame, -) bun.JSError!JSC.JSValue { + globalThis: *jsc.JSGlobalObject, + callframe: *jsc.CallFrame, +) bun.JSError!jsc.JSValue { const allocator = bun.default_allocator; var arguments_ = callframe.arguments_old(3); var args = arguments_.ptr[0..arguments_.len]; @@ -2794,7 +2794,7 @@ pub fn getSlice( args.len = 3; } - var args_iter = JSC.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), args); + var args_iter = jsc.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), args); if (args_iter.nextEat()) |start_| { if (start_.isNumber()) { const start = start_.toInt64(); @@ -2872,7 +2872,7 @@ pub fn getMimeTypeOrContentType(this: *const Blob) ?bun.http.MimeType { pub fn getType( this: *Blob, - globalThis: *JSC.JSGlobalObject, + globalThis: *jsc.JSGlobalObject, ) JSValue { if (this.content_type.len > 0) { if (this.content_type_allocated) { @@ -2902,16 +2902,16 @@ pub fn getNameString(this: *Blob) ?bun.String { // TODO: Move this to a separate `File` object or BunFile pub fn getName( this: *Blob, - _: JSC.JSValue, - globalThis: *JSC.JSGlobalObject, + _: jsc.JSValue, + globalThis: *jsc.JSGlobalObject, ) JSValue { return if (this.getNameString()) |name| name.toJS(globalThis) else .js_undefined; } pub fn setName( this: *Blob, - jsThis: JSC.JSValue, - globalThis: *JSC.JSGlobalObject, + jsThis: jsc.JSValue, + globalThis: *jsc.JSGlobalObject, value: JSValue, ) JSError!void { // by default we don't have a name so lets allow it to be set undefined @@ -2968,12 +2968,12 @@ pub fn getLoader(blob: *const Blob, jsc_vm: *VirtualMachine) ?bun.options.Loader // TODO: Move this to a separate `File` object or BunFile pub fn getLastModified( this: *Blob, - _: *JSC.JSGlobalObject, + _: *jsc.JSGlobalObject, ) JSValue { if (this.store) |store| { if (store.data == .file) { // last_modified can be already set during read. - if (store.data.file.last_modified == JSC.init_timestamp and !this.isS3()) { + if (store.data.file.last_modified == jsc.init_timestamp and !this.isS3()) { resolveFileStat(store); } return JSValue.jsNumber(store.data.file.last_modified); @@ -2984,7 +2984,7 @@ pub fn getLastModified( return JSValue.jsNumber(this.last_modified); } - return JSValue.jsNumber(JSC.init_timestamp); + return JSValue.jsNumber(jsc.init_timestamp); } pub fn getSizeForBindings(this: *Blob) u64 { @@ -3010,7 +3010,7 @@ export fn Bun__Blob__getSizeForBindings(this: *Blob) callconv(.C) u64 { return this.getSizeForBindings(); } -pub fn getStat(this: *Blob, globalThis: *JSC.JSGlobalObject, callback: *JSC.CallFrame) bun.JSError!JSC.JSValue { +pub fn getStat(this: *Blob, globalThis: *jsc.JSGlobalObject, callback: *jsc.CallFrame) bun.JSError!jsc.JSValue { const store = this.store orelse return .js_undefined; // TODO: make this async for files return switch (store.data) { @@ -3034,20 +3034,20 @@ pub fn getStat(this: *Blob, globalThis: *JSC.JSGlobalObject, callback: *JSC.Call else => .js_undefined, }; } -pub fn getSize(this: *Blob, _: *JSC.JSGlobalObject) JSValue { +pub fn getSize(this: *Blob, _: *jsc.JSGlobalObject) JSValue { if (this.size == Blob.max_size) { if (this.isS3()) { - return JSC.JSValue.jsNumber(std.math.nan(f64)); + return jsc.JSValue.jsNumber(std.math.nan(f64)); } this.resolveSize(); if (this.size == Blob.max_size and this.store != null) { - return JSC.jsNumber(std.math.inf(f64)); + return jsc.jsNumber(std.math.inf(f64)); } else if (this.size == 0 and this.store != null) { if (this.store.?.data == .file and (this.store.?.data.file.seekable orelse true) == false and this.store.?.data.file.max_size == Blob.max_size) { - return JSC.jsNumber(std.math.inf(f64)); + return jsc.jsNumber(std.math.inf(f64)); } } } @@ -3099,7 +3099,7 @@ fn resolveFileStat(store: *Store) void { Blob.max_size; store.data.file.mode = @intCast(stat.mode); store.data.file.seekable = bun.isRegularFile(stat.mode); - store.data.file.last_modified = JSC.toJSTime(stat.mtime().sec, stat.mtime().nsec); + store.data.file.last_modified = jsc.toJSTime(stat.mtime().sec, stat.mtime().nsec); }, // the file may not exist yet. Thats's okay. else => {}, @@ -3113,7 +3113,7 @@ fn resolveFileStat(store: *Store) void { Blob.max_size; store.data.file.mode = @intCast(stat.mode); store.data.file.seekable = bun.isRegularFile(stat.mode); - store.data.file.last_modified = JSC.toJSTime(stat.mtime().sec, stat.mtime().nsec); + store.data.file.last_modified = jsc.toJSTime(stat.mtime().sec, stat.mtime().nsec); }, // the file may not exist yet. Thats's okay. else => {}, @@ -3121,7 +3121,7 @@ fn resolveFileStat(store: *Store) void { } } -pub fn constructor(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!*Blob { +pub fn constructor(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!*Blob { const allocator = bun.default_allocator; var blob: Blob = undefined; var arguments = callframe.arguments_old(2); @@ -3243,8 +3243,8 @@ pub fn tryCreate( was_string: bool, ) !Blob { if (comptime Environment.isLinux) { - if (bun.linux.memfd_allocator.shouldUse(bytes_)) { - switch (bun.linux.memfd_allocator.create(bytes_)) { + if (bun.linux.MemFdAllocator.shouldUse(bytes_)) { + switch (bun.linux.MemFdAllocator.create(bytes_)) { .err => {}, .result => |result| { const store = Store.new( @@ -3326,7 +3326,7 @@ pub fn dupeWithContentType(this: *const Blob, include_content_type: bool) Blob { if (duped.content_type_allocated and duped.allocator != null and !include_content_type) { // for now, we just want to avoid a use-after-free here - if (JSC.VirtualMachine.get().mimeType(duped.content_type)) |mime| { + if (jsc.VirtualMachine.get().mimeType(duped.content_type)) |mime| { duped.content_type = mime.value; } else { // TODO: fix this @@ -3349,7 +3349,7 @@ pub fn dupeWithContentType(this: *const Blob, include_content_type: bool) Blob { return duped; } -pub fn toJS(this: *Blob, globalObject: *JSC.JSGlobalObject) JSC.JSValue { +pub fn toJS(this: *Blob, globalObject: *jsc.JSGlobalObject) jsc.JSValue { // if (comptime Environment.allow_assert) { // assert(this.allocator != null); // } @@ -3384,7 +3384,7 @@ pub fn sharedView(this: *const Blob) []const u8 { return slice_[0..@min(slice_.len, @as(usize, this.size))]; } -pub const Lifetime = JSC.WebCore.Lifetime; +pub const Lifetime = jsc.WebCore.Lifetime; pub fn setIsASCIIFlag(this: *Blob, is_all_ascii: bool) void { this.is_all_ascii = is_all_ascii; // if this Blob represents the entire binary data @@ -3567,12 +3567,12 @@ pub fn toUint8ArrayWithBytes(this: *Blob, global: *JSGlobalObject, buf: []u8, co return toArrayBufferViewWithBytes(this, global, buf, lifetime, .Uint8Array); } -pub fn toArrayBufferViewWithBytes(this: *Blob, global: *JSGlobalObject, buf: []u8, comptime lifetime: Lifetime, comptime TypedArrayView: JSC.JSValue.JSType) bun.JSError!JSValue { +pub fn toArrayBufferViewWithBytes(this: *Blob, global: *JSGlobalObject, buf: []u8, comptime lifetime: Lifetime, comptime TypedArrayView: jsc.JSValue.JSType) bun.JSError!JSValue { switch (comptime lifetime) { .clone => { if (TypedArrayView != .ArrayBuffer) { // ArrayBuffer doesn't have this limit. - if (buf.len > JSC.VirtualMachine.synthetic_allocation_limit) { + if (buf.len > jsc.VirtualMachine.synthetic_allocation_limit) { this.detach(); return global.throwOutOfMemory(); } @@ -3584,14 +3584,14 @@ pub fn toArrayBufferViewWithBytes(this: *Blob, global: *JSGlobalObject, buf: []u if (store.data == .bytes) { const allocated_slice = store.data.bytes.allocatedSlice(); if (bun.isSliceInBuffer(buf, allocated_slice)) { - if (bun.linux.memfd_allocator.from(store.data.bytes.allocator)) |allocator| { + if (bun.linux.MemFdAllocator.from(store.data.bytes.allocator)) |allocator| { allocator.ref(); defer allocator.deref(); const byteOffset = @as(usize, @intFromPtr(buf.ptr)) -| @as(usize, @intFromPtr(allocated_slice.ptr)); const byteLength = buf.len; - const result = JSC.ArrayBuffer.toArrayBufferFromSharedMemfd( + const result = jsc.ArrayBuffer.toArrayBufferFromSharedMemfd( allocator.fd.cast(), global, byteOffset, @@ -3609,42 +3609,42 @@ pub fn toArrayBufferViewWithBytes(this: *Blob, global: *JSGlobalObject, buf: []u } } } - return JSC.ArrayBuffer.create(global, buf, TypedArrayView); + return jsc.ArrayBuffer.create(global, buf, TypedArrayView); }, .share => { - if (buf.len > JSC.synthetic_allocation_limit and TypedArrayView != .ArrayBuffer) { + if (buf.len > jsc.synthetic_allocation_limit and TypedArrayView != .ArrayBuffer) { return global.throwOutOfMemory(); } this.store.?.ref(); - return JSC.ArrayBuffer.fromBytes(buf, TypedArrayView).toJSWithContext( + return jsc.ArrayBuffer.fromBytes(buf, TypedArrayView).toJSWithContext( global, this.store.?, - JSC.BlobArrayBuffer_deallocator, + jsc.BlobArrayBuffer_deallocator, null, ); }, .transfer => { - if (buf.len > JSC.VirtualMachine.synthetic_allocation_limit and TypedArrayView != .ArrayBuffer) { + if (buf.len > jsc.VirtualMachine.synthetic_allocation_limit and TypedArrayView != .ArrayBuffer) { this.detach(); return global.throwOutOfMemory(); } const store = this.store.?; this.transfer(); - return JSC.ArrayBuffer.fromBytes(buf, TypedArrayView).toJSWithContext( + return jsc.ArrayBuffer.fromBytes(buf, TypedArrayView).toJSWithContext( global, store, - JSC.array_buffer.BlobArrayBuffer_deallocator, + jsc.array_buffer.BlobArrayBuffer_deallocator, ); }, .temporary => { - if (buf.len > JSC.VirtualMachine.synthetic_allocation_limit and TypedArrayView != .ArrayBuffer) { + if (buf.len > jsc.VirtualMachine.synthetic_allocation_limit and TypedArrayView != .ArrayBuffer) { bun.default_allocator.free(buf); return global.throwOutOfMemory(); } - return JSC.ArrayBuffer.fromBytes(buf, TypedArrayView).toJS(global); + return jsc.ArrayBuffer.fromBytes(buf, TypedArrayView).toJS(global); }, } } @@ -3659,7 +3659,7 @@ pub fn toUint8Array(this: *Blob, global: *JSGlobalObject, comptime lifetime: Lif return toArrayBufferView(this, global, lifetime, .Uint8Array); } -pub fn toArrayBufferView(this: *Blob, global: *JSGlobalObject, comptime lifetime: Lifetime, comptime TypedArrayView: JSC.JSValue.JSType) bun.JSError!JSValue { +pub fn toArrayBufferView(this: *Blob, global: *JSGlobalObject, comptime lifetime: Lifetime, comptime TypedArrayView: jsc.JSValue.JSType) bun.JSError!JSValue { const WithBytesFn = comptime if (TypedArrayView == .Uint8Array) toUint8ArrayWithBytes else @@ -3674,7 +3674,7 @@ pub fn toArrayBufferView(this: *Blob, global: *JSGlobalObject, comptime lifetime const view_ = this.sharedView(); if (view_.len == 0) - return JSC.ArrayBuffer.create(global, "", TypedArrayView); + return jsc.ArrayBuffer.create(global, "", TypedArrayView); return WithBytesFn(this, global, @constCast(view_), lifetime); } @@ -3690,7 +3690,7 @@ pub fn toFormData(this: *Blob, global: *JSGlobalObject, comptime lifetime: Lifet const view_ = this.sharedView(); if (view_.len == 0) - return JSC.DOMFormData.create(global); + return jsc.DOMFormData.create(global); return toFormDataWithBytes(this, global, @constCast(view_), lifetime); } @@ -3752,7 +3752,7 @@ fn fromJSWithoutDeferGC( var fail_if_top_value_is_not_typed_array_like = false; switch (current.jsTypeLoose()) { .Array, .DerivedArray => { - var top_iter = try JSC.JSArrayIterator.init(current, global); + var top_iter = try jsc.JSArrayIterator.init(current, global); might_only_be_one_thing = top_iter.len == 1; if (top_iter.len == 0) { return Blob{ .globalThis = global }; @@ -3775,9 +3775,9 @@ fn fromJSWithoutDeferGC( switch (top_value.jsTypeLoose()) { .Cell, .NumberObject, - JSC.JSValue.JSType.String, - JSC.JSValue.JSType.StringObject, - JSC.JSValue.JSType.DerivedStringObject, + jsc.JSValue.JSType.String, + jsc.JSValue.JSType.StringObject, + jsc.JSValue.JSType.DerivedStringObject, => { if (!fail_if_top_value_is_not_typed_array_like) { var str = try top_value.toBunString(global); @@ -3787,20 +3787,20 @@ fn fromJSWithoutDeferGC( } }, - JSC.JSValue.JSType.ArrayBuffer, - JSC.JSValue.JSType.Int8Array, - JSC.JSValue.JSType.Uint8Array, - JSC.JSValue.JSType.Uint8ClampedArray, - JSC.JSValue.JSType.Int16Array, - JSC.JSValue.JSType.Uint16Array, - JSC.JSValue.JSType.Int32Array, - JSC.JSValue.JSType.Uint32Array, - JSC.JSValue.JSType.Float16Array, - JSC.JSValue.JSType.Float32Array, - JSC.JSValue.JSType.Float64Array, - JSC.JSValue.JSType.BigInt64Array, - JSC.JSValue.JSType.BigUint64Array, - JSC.JSValue.JSType.DataView, + jsc.JSValue.JSType.ArrayBuffer, + jsc.JSValue.JSType.Int8Array, + jsc.JSValue.JSType.Uint8Array, + jsc.JSValue.JSType.Uint8ClampedArray, + jsc.JSValue.JSType.Int16Array, + jsc.JSValue.JSType.Uint16Array, + jsc.JSValue.JSType.Int32Array, + jsc.JSValue.JSType.Uint32Array, + jsc.JSValue.JSType.Float16Array, + jsc.JSValue.JSType.Float32Array, + jsc.JSValue.JSType.Float64Array, + jsc.JSValue.JSType.BigInt64Array, + jsc.JSValue.JSType.BigUint64Array, + jsc.JSValue.JSType.DataView, => { return try Blob.tryCreate(top_value.asArrayBuffer(global).?.byteSlice(), bun.default_allocator, global, false); }, @@ -3816,7 +3816,7 @@ fn fromJSWithoutDeferGC( } else { return blob.dupe(); } - } else if (top_value.as(JSC.API.BuildArtifact)) |build| { + } else if (top_value.as(jsc.API.BuildArtifact)) |build| { if (comptime move) { // I don't think this case should happen? var blob = build.blob; @@ -3854,9 +3854,9 @@ fn fromJSWithoutDeferGC( while (true) { switch (current.jsTypeLoose()) { .NumberObject, - JSC.JSValue.JSType.String, - JSC.JSValue.JSType.StringObject, - JSC.JSValue.JSType.DerivedStringObject, + jsc.JSValue.JSType.String, + jsc.JSValue.JSType.StringObject, + jsc.JSValue.JSType.DerivedStringObject, => { var sliced = try current.toSlice(global, bun.default_allocator); const allocator = sliced.allocator.get(); @@ -3865,7 +3865,7 @@ fn fromJSWithoutDeferGC( }, .Array, .DerivedArray => { - var iter = try JSC.JSArrayIterator.init(current, global); + var iter = try jsc.JSArrayIterator.init(current, global); try stack.ensureUnusedCapacity(iter.len); var any_arrays = false; while (try iter.next()) |item| { @@ -4062,7 +4062,7 @@ pub const Any = union(enum) { } } - pub fn toActionValue(this: *Any, globalThis: *JSGlobalObject, action: streams.BufferAction.Tag) bun.JSError!JSC.JSValue { + pub fn toActionValue(this: *Any, globalThis: *JSGlobalObject, action: streams.BufferAction.Tag) bun.JSError!jsc.JSValue { if (action != .blob) { this.toInternalBlobIfPossible(); } @@ -4101,15 +4101,15 @@ pub const Any = union(enum) { } } - pub fn toPromise(this: *Any, globalThis: *JSGlobalObject, action: streams.BufferAction.Tag) JSC.JSValue { - return JSC.JSPromise.wrap(globalThis, toActionValue, .{ this, globalThis, action }); + pub fn toPromise(this: *Any, globalThis: *JSGlobalObject, action: streams.BufferAction.Tag) jsc.JSValue { + return jsc.JSPromise.wrap(globalThis, toActionValue, .{ this, globalThis, action }); } - pub fn wrap(this: *Any, promise: JSC.AnyPromise, globalThis: *JSGlobalObject, action: streams.BufferAction.Tag) void { + pub fn wrap(this: *Any, promise: jsc.AnyPromise, globalThis: *JSGlobalObject, action: streams.BufferAction.Tag) void { promise.wrap(globalThis, toActionValue, .{ this, globalThis, action }); } - pub fn toJSON(this: *Any, global: *JSGlobalObject, comptime lifetime: JSC.WebCore.Lifetime) bun.JSError!JSValue { + pub fn toJSON(this: *Any, global: *JSGlobalObject, comptime lifetime: jsc.WebCore.Lifetime) bun.JSError!JSValue { switch (this.*) { .Blob => return this.Blob.toJSON(global, lifetime), // .InlineBlob => { @@ -4185,7 +4185,7 @@ pub const Any = union(enum) { return blob; } - pub fn toString(this: *Any, global: *JSGlobalObject, comptime lifetime: JSC.WebCore.Lifetime) bun.JSError!JSValue { + pub fn toString(this: *Any, global: *JSGlobalObject, comptime lifetime: jsc.WebCore.Lifetime) bun.JSError!JSValue { switch (this.*) { .Blob => return this.Blob.toString(global, lifetime), // .InlineBlob => { @@ -4215,24 +4215,24 @@ pub const Any = union(enum) { } } - pub fn toArrayBuffer(this: *Any, global: *JSGlobalObject, comptime lifetime: JSC.WebCore.Lifetime) bun.JSError!JSValue { + pub fn toArrayBuffer(this: *Any, global: *JSGlobalObject, comptime lifetime: jsc.WebCore.Lifetime) bun.JSError!JSValue { return this.toArrayBufferView(global, lifetime, .ArrayBuffer); } - pub fn toUint8Array(this: *Any, global: *JSGlobalObject, comptime lifetime: JSC.WebCore.Lifetime) bun.JSError!JSValue { + pub fn toUint8Array(this: *Any, global: *JSGlobalObject, comptime lifetime: jsc.WebCore.Lifetime) bun.JSError!JSValue { return this.toArrayBufferView(global, lifetime, .Uint8Array); } - pub fn toArrayBufferView(this: *Any, global: *JSGlobalObject, comptime lifetime: JSC.WebCore.Lifetime, comptime TypedArrayView: JSC.JSValue.JSType) bun.JSError!JSValue { + pub fn toArrayBufferView(this: *Any, global: *JSGlobalObject, comptime lifetime: jsc.WebCore.Lifetime, comptime TypedArrayView: jsc.JSValue.JSType) bun.JSError!JSValue { switch (this.*) { .Blob => return this.Blob.toArrayBufferView(global, lifetime, TypedArrayView), // .InlineBlob => { // if (this.InlineBlob.len == 0) { - // return JSC.ArrayBuffer.create(global, "", .ArrayBuffer); + // return jsc.ArrayBuffer.create(global, "", .ArrayBuffer); // } // var bytes = this.InlineBlob.sliceConst(); // this.InlineBlob.len = 0; - // const value = JSC.ArrayBuffer.create( + // const value = jsc.ArrayBuffer.create( // global, // bytes, // .ArrayBuffer, @@ -4243,7 +4243,7 @@ pub const Any = union(enum) { const bytes = this.InternalBlob.toOwnedSlice(); this.* = .{ .Blob = .{} }; - return JSC.ArrayBuffer.fromDefaultAllocator( + return jsc.ArrayBuffer.fromDefaultAllocator( global, bytes, TypedArrayView, @@ -4256,14 +4256,14 @@ pub const Any = union(enum) { const out_bytes = str.toUTF8WithoutRef(bun.default_allocator); if (out_bytes.isAllocated()) { - return JSC.ArrayBuffer.fromDefaultAllocator( + return jsc.ArrayBuffer.fromDefaultAllocator( global, @constCast(out_bytes.slice()), TypedArrayView, ); } - return JSC.ArrayBuffer.create(global, out_bytes.slice(), TypedArrayView); + return jsc.ArrayBuffer.create(global, out_bytes.slice(), TypedArrayView); }, } } @@ -4357,7 +4357,7 @@ pub const Internal = struct { return this.bytes.capacity; } - pub fn toStringOwned(this: *@This(), globalThis: *JSC.JSGlobalObject) JSValue { + pub fn toStringOwned(this: *@This(), globalThis: *jsc.JSGlobalObject) JSValue { const bytes_without_bom = strings.withoutUTF8BOM(this.bytes.items); if (strings.toUTF16Alloc(globalThis.allocator(), bytes_without_bom, false, false) catch &[_]u16{}) |out| { const return_value = ZigString.toExternalU16(out.ptr, out.len, globalThis); @@ -4378,7 +4378,7 @@ pub const Internal = struct { } } - pub fn toJSON(this: *@This(), globalThis: *JSC.JSGlobalObject) JSValue { + pub fn toJSON(this: *@This(), globalThis: *jsc.JSGlobalObject) JSValue { const str_bytes = ZigString.init(strings.withoutUTF8BOM(this.bytes.items)).withEncoding(); const json = str_bytes.toJSONObject(globalThis); this.deinit(); @@ -4439,7 +4439,7 @@ pub const Inline = extern struct { const total = first.len + second.len; assert(total <= available_bytes); - var inline_blob: JSC.WebCore.InlineBlob = .{}; + var inline_blob: jsc.WebCore.InlineBlob = .{}; var bytes_slice = inline_blob.bytes[0..total]; if (first.len > 0) @@ -4473,7 +4473,7 @@ pub const Inline = extern struct { return internalInit(data, true); } - pub fn toStringOwned(this: *@This(), globalThis: *JSC.JSGlobalObject) JSValue { + pub fn toStringOwned(this: *@This(), globalThis: *jsc.JSGlobalObject) JSValue { if (this.len == 0) return ZigString.Empty.toJS(globalThis); @@ -4514,8 +4514,8 @@ pub const Inline = extern struct { pub fn clearAndFree(_: *@This()) void {} }; -pub export fn JSDOMFile__hasInstance(_: JSC.JSValue, _: *JSC.JSGlobalObject, value: JSC.JSValue) callconv(JSC.conv) bool { - JSC.markBinding(@src()); +pub export fn JSDOMFile__hasInstance(_: jsc.JSValue, _: *jsc.JSGlobalObject, value: jsc.JSValue) callconv(jsc.conv) bool { + jsc.markBinding(@src()); const blob = value.as(Blob) orelse return false; return blob.is_jsdom_file; } @@ -4572,7 +4572,7 @@ pub fn FileOpener(comptime This: type) type { &this.req, path, open_flags_, - JSC.Node.fs.default_permission, + jsc.Node.fs.default_permission, &WrappedCallback.callback, ); if (rc.errEnum()) |errno| { @@ -4586,7 +4586,7 @@ pub fn FileOpener(comptime This: type) type { } while (true) { - this.opened_fd = switch (bun.sys.open(path, open_flags_, JSC.Node.fs.default_permission)) { + this.opened_fd = switch (bun.sys.open(path, open_flags_, jsc.Node.fs.default_permission)) { .result => |fd| fd, .err => |err| { if (comptime @hasField(This, "mkdirp_if_not_exists")) { @@ -4662,10 +4662,10 @@ pub fn FileCloser(comptime This: type) type { fn onIORequestClosed(this: *This) void { this.io_poll.flags.remove(.was_ever_registered); this.task = .{ .callback = &onCloseIORequest }; - bun.JSC.WorkPool.schedule(&this.task); + bun.jsc.WorkPool.schedule(&this.task); } - fn onCloseIORequest(task: *JSC.WorkPoolTask) void { + fn onCloseIORequest(task: *jsc.WorkPoolTask) void { debug("onCloseIORequest()", .{}); var this: *This = @alignCast(@fieldParentPtr("task", task)); this.close_after_io = false; @@ -4705,6 +4705,8 @@ const WriteFilePromise = write_file.WriteFilePromise; const WriteFileWaitFromLockedValueTask = write_file.WriteFileWaitFromLockedValueTask; const NewReadFileHandler = read_file.NewReadFileHandler; +const string = []const u8; + const Environment = @import("../../env.zig"); const S3File = @import("./S3File.zig"); const std = @import("std"); @@ -4718,21 +4720,20 @@ const assert = bun.assert; const default_allocator = bun.default_allocator; const invalid_fd = bun.invalid_fd; const io = bun.io; -const string = bun.string; const strings = bun.strings; const libuv = bun.windows.libuv; const streams = bun.webcore.streams; -const JSC = bun.JSC; -const JSGlobalObject = JSC.JSGlobalObject; -const JSPromise = JSC.JSPromise; -const JSValue = JSC.JSValue; -const VirtualMachine = JSC.VirtualMachine; -const ZigString = JSC.ZigString; -const PathOrBlob = JSC.Node.PathOrBlob; - -const Request = JSC.WebCore.Request; -const Response = JSC.WebCore.Response; - const http = bun.http; const MimeType = http.MimeType; + +const jsc = bun.jsc; +const JSGlobalObject = jsc.JSGlobalObject; +const JSPromise = jsc.JSPromise; +const JSValue = jsc.JSValue; +const VirtualMachine = jsc.VirtualMachine; +const ZigString = jsc.ZigString; +const PathOrBlob = jsc.Node.PathOrBlob; + +const Request = jsc.WebCore.Request; +const Response = jsc.WebCore.Response; diff --git a/src/bun.js/webcore/Body.zig b/src/bun.js/webcore/Body.zig index a3edeb01d6..72b1dd5faf 100644 --- a/src/bun.js/webcore/Body.zig +++ b/src/bun.js/webcore/Body.zig @@ -27,7 +27,7 @@ pub fn writeFormat(this: *Body, comptime Formatter: type, formatter: *Formatter, try formatter.writeIndent(Writer, writer); try writer.writeAll(comptime Output.prettyFmt("bodyUsed: ", enable_ansi_colors)); - try formatter.printAs(.Boolean, Writer, writer, JSC.JSValue.jsBoolean(this.value == .Used), .BooleanObject, enable_ansi_colors); + try formatter.printAs(.Boolean, Writer, writer, jsc.JSValue.jsBoolean(this.value == .Used), .BooleanObject, enable_ansi_colors); if (this.value == .Blob) { try formatter.printComma(Writer, writer, enable_ansi_colors); @@ -55,8 +55,8 @@ pub fn deinit(this: *Body, _: std.mem.Allocator) void { pub const PendingValue = struct { promise: ?JSValue = null, - readable: JSC.WebCore.ReadableStream.Strong = .{}, - // writable: JSC.WebCore.Sink + readable: jsc.WebCore.ReadableStream.Strong = .{}, + // writable: jsc.WebCore.Sink global: *JSGlobalObject, task: ?*anyopaque = null, @@ -67,8 +67,8 @@ pub const PendingValue = struct { /// conditionally runs when requesting data /// used in HTTP server to ignore request bodies unless asked for it onStartBuffering: ?*const fn (ctx: *anyopaque) void = null, - onStartStreaming: ?*const fn (ctx: *anyopaque) JSC.WebCore.DrainResult = null, - onReadableStreamAvailable: ?*const fn (ctx: *anyopaque, globalThis: *JSC.JSGlobalObject, readable: JSC.WebCore.ReadableStream) void = null, + onStartStreaming: ?*const fn (ctx: *anyopaque) jsc.WebCore.DrainResult = null, + onReadableStreamAvailable: ?*const fn (ctx: *anyopaque, globalThis: *jsc.JSGlobalObject, readable: jsc.WebCore.ReadableStream) void = null, size_hint: Blob.SizeType = 0, deinit: bool = false, @@ -94,13 +94,13 @@ pub const PendingValue = struct { return this.toAnyBlobAllowPromise(); } - pub fn isDisturbed(this: *const PendingValue, comptime T: type, globalObject: *JSC.JSGlobalObject, this_value: JSC.JSValue) bool { + pub fn isDisturbed(this: *const PendingValue, comptime T: type, globalObject: *jsc.JSGlobalObject, this_value: jsc.JSValue) bool { if (this.promise != null) { return true; } if (T.js.bodyGetCached(this_value)) |body_value| { - if (JSC.WebCore.ReadableStream.isDisturbedValue(body_value, globalObject)) { + if (jsc.WebCore.ReadableStream.isDisturbedValue(body_value, globalObject)) { return true; } @@ -114,7 +114,7 @@ pub const PendingValue = struct { return false; } - pub fn isDisturbed2(this: *const PendingValue, globalObject: *JSC.JSGlobalObject) bool { + pub fn isDisturbed2(this: *const PendingValue, globalObject: *jsc.JSGlobalObject) bool { if (this.promise != null) { return true; } @@ -157,7 +157,7 @@ pub const PendingValue = struct { return null; } - pub fn setPromise(value: *PendingValue, globalThis: *JSC.JSGlobalObject, action: Action) JSValue { + pub fn setPromise(value: *PendingValue, globalThis: *jsc.JSGlobalObject, action: Action) JSValue { value.action = action; if (value.readable.get(globalThis)) |readable| { switch (action) { @@ -193,7 +193,7 @@ pub const PendingValue = struct { } { - var promise = JSC.JSPromise.create(globalThis); + var promise = jsc.JSPromise.create(globalThis); const promise_value = promise.toJS(); value.promise = promise_value; promise_value.protect(); @@ -222,7 +222,7 @@ pub const Value = union(Tag) { const log = Output.scoped(.BodyValue, false); const pool_size = if (bun.heap_breakdown.enabled) 0 else 256; - pub const HiveRef = bun.HiveRef(JSC.WebCore.Body.Value, pool_size); + pub const HiveRef = bun.HiveRef(jsc.WebCore.Body.Value, pool_size); pub const HiveAllocator = bun.HiveArray(HiveRef, pool_size).Fallback; Blob: Blob, @@ -285,12 +285,12 @@ pub const Value = union(Tag) { pub const heap_breakdown_label = "BodyValue"; pub const ValueError = union(enum) { - AbortReason: JSC.CommonAbortReason, - SystemError: JSC.SystemError, + AbortReason: jsc.CommonAbortReason, + SystemError: jsc.SystemError, Message: bun.String, - JSValue: JSC.Strong.Optional, + JSValue: jsc.Strong.Optional, - pub fn toStreamError(this: *@This(), globalObject: *JSC.JSGlobalObject) streams.Result.StreamError { + pub fn toStreamError(this: *@This(), globalObject: *jsc.JSGlobalObject) streams.Result.StreamError { return switch (this.*) { .AbortReason => .{ .AbortReason = this.AbortReason, @@ -301,7 +301,7 @@ pub const Value = union(Tag) { }; } - pub fn toJS(this: *@This(), globalObject: *JSC.JSGlobalObject) JSC.JSValue { + pub fn toJS(this: *@This(), globalObject: *jsc.JSGlobalObject) jsc.JSValue { const js_value = switch (this.*) { .AbortReason => |reason| reason.toJS(globalObject), .SystemError => |system_error| system_error.toErrorInstance(globalObject), @@ -313,7 +313,7 @@ pub const Value = union(Tag) { return js_value; } - pub fn dupe(this: *const @This(), globalObject: *JSC.JSGlobalObject) @This() { + pub fn dupe(this: *const @This(), globalObject: *jsc.JSGlobalObject) @This() { var value = this.*; switch (this.*) { .SystemError => value.SystemError.ref(), @@ -445,14 +445,14 @@ pub const Value = union(Tag) { // pub const empty = Value{ .Empty = {} }; pub fn toReadableStream(this: *Value, globalThis: *JSGlobalObject) bun.JSError!JSValue { - JSC.markBinding(@src()); + jsc.markBinding(@src()); switch (this.*) { .Used => { - return JSC.WebCore.ReadableStream.used(globalThis); + return jsc.WebCore.ReadableStream.used(globalThis); }, .Empty => { - return JSC.WebCore.ReadableStream.empty(globalThis); + return jsc.WebCore.ReadableStream.empty(globalThis); }, .Null => { return JSValue.null; @@ -461,11 +461,11 @@ pub const Value = union(Tag) { var blob = this.use(); defer blob.detach(); blob.resolveSize(); - const value = try JSC.WebCore.ReadableStream.fromBlobCopyRef(globalThis, &blob, blob.size); + const value = try jsc.WebCore.ReadableStream.fromBlobCopyRef(globalThis, &blob, blob.size); this.* = .{ .Locked = .{ - .readable = JSC.WebCore.ReadableStream.Strong.init((try JSC.WebCore.ReadableStream.fromJS(value, globalThis)).?, globalThis), + .readable = jsc.WebCore.ReadableStream.Strong.init((try jsc.WebCore.ReadableStream.fromJS(value, globalThis)).?, globalThis), .global = globalThis, }, }; @@ -477,9 +477,9 @@ pub const Value = union(Tag) { return readable.value; } if (locked.promise != null or locked.action != .none) { - return JSC.WebCore.ReadableStream.used(globalThis); + return jsc.WebCore.ReadableStream.used(globalThis); } - var drain_result: JSC.WebCore.DrainResult = .{ + var drain_result: jsc.WebCore.DrainResult = .{ .estimated_size = 0, }; @@ -490,10 +490,10 @@ pub const Value = union(Tag) { if (drain_result == .empty or drain_result == .aborted) { this.* = .{ .Null = {} }; - return JSC.WebCore.ReadableStream.empty(globalThis); + return jsc.WebCore.ReadableStream.empty(globalThis); } - var reader = JSC.WebCore.ByteStream.Source.new(.{ + var reader = jsc.WebCore.ByteStream.Source.new(.{ .context = undefined, .globalThis = globalThis, }); @@ -508,7 +508,7 @@ pub const Value = union(Tag) { reader.context.size_hint = @as(Blob.SizeType, @truncate(drain_result.owned.size_hint)); } - locked.readable = JSC.WebCore.ReadableStream.Strong.init(.{ + locked.readable = jsc.WebCore.ReadableStream.Strong.init(.{ .ptr = .{ .Bytes = &reader.context }, .value = try reader.toReadableStream(globalThis), }, globalThis); @@ -521,7 +521,7 @@ pub const Value = union(Tag) { }, .Error => { // TODO: handle error properly - return JSC.WebCore.ReadableStream.empty(globalThis); + return jsc.WebCore.ReadableStream.empty(globalThis); }, } } @@ -577,13 +577,13 @@ pub const Value = union(Tag) { } } - if (value.as(JSC.DOMFormData)) |form_data| { + if (value.as(jsc.DOMFormData)) |form_data| { return Body.Value{ .Blob = Blob.fromDOMFormData(globalThis, bun.default_allocator, form_data), }; } - if (value.as(JSC.URLSearchParams)) |search_params| { + if (value.as(jsc.URLSearchParams)) |search_params| { return Body.Value{ .Blob = Blob.fromURLSearchParams(globalThis, bun.default_allocator, search_params), }; @@ -600,7 +600,7 @@ pub const Value = union(Tag) { value.ensureStillAlive(); - if (try JSC.WebCore.ReadableStream.fromJS(value, globalThis)) |readable| { + if (try jsc.WebCore.ReadableStream.fromJS(value, globalThis)) |readable| { if (readable.isDisturbed(globalThis)) { return globalThis.throw("ReadableStream has already been used", .{}); } @@ -639,10 +639,10 @@ pub const Value = union(Tag) { }; } - pub fn fromReadableStreamWithoutLockCheck(readable: JSC.WebCore.ReadableStream, globalThis: *JSGlobalObject) Value { + pub fn fromReadableStreamWithoutLockCheck(readable: jsc.WebCore.ReadableStream, globalThis: *JSGlobalObject) Value { return .{ .Locked = .{ - .readable = JSC.WebCore.ReadableStream.Strong.init(readable, globalThis), + .readable = jsc.WebCore.ReadableStream.Strong.init(readable, globalThis), .global = globalThis, }, }; @@ -772,7 +772,7 @@ pub const Value = union(Tag) { // we have to use the default allocator // even if it was actually allocated on a different thread bun.default_allocator, - JSC.VirtualMachine.get().global, + jsc.VirtualMachine.get().global, ); this.* = .{ .Used = {} }; @@ -786,13 +786,13 @@ pub const Value = union(Tag) { new_blob = Blob.init( @constCast(allocated_slice.slice()), bun.default_allocator, - JSC.VirtualMachine.get().global, + jsc.VirtualMachine.get().global, ); } else { new_blob = Blob.init( bun.default_allocator.dupe(u8, wtf.latin1Slice()) catch bun.outOfMemory(), bun.default_allocator, - JSC.VirtualMachine.get().global, + jsc.VirtualMachine.get().global, ); } @@ -805,7 +805,7 @@ pub const Value = union(Tag) { // const new_blob = Blob.create( // cloned[0..this.InlineBlob.len], // bun.default_allocator, - // JSC.VirtualMachine.get().global, + // jsc.VirtualMachine.get().global, // false, // ); @@ -965,7 +965,7 @@ pub const Value = union(Tag) { } } - pub fn tee(this: *Value, globalThis: *JSC.JSGlobalObject) bun.JSError!Value { + pub fn tee(this: *Value, globalThis: *jsc.JSGlobalObject) bun.JSError!Value { var locked = &this.Locked; if (locked.readable.isDisturbed(globalThis)) { @@ -975,7 +975,7 @@ pub const Value = union(Tag) { if (try locked.readable.tee(globalThis)) |readable| { return Value{ .Locked = .{ - .readable = JSC.WebCore.ReadableStream.Strong.init(readable, globalThis), + .readable = jsc.WebCore.ReadableStream.Strong.init(readable, globalThis), .global = globalThis, }, }; @@ -984,7 +984,7 @@ pub const Value = union(Tag) { return Value{ .Used = {} }; } - var drain_result: JSC.WebCore.DrainResult = .{ + var drain_result: jsc.WebCore.DrainResult = .{ .estimated_size = 0, }; @@ -998,7 +998,7 @@ pub const Value = union(Tag) { return Value{ .Null = {} }; } - var reader = JSC.WebCore.ByteStream.Source.new(.{ + var reader = jsc.WebCore.ByteStream.Source.new(.{ .context = undefined, .globalThis = globalThis, }); @@ -1013,7 +1013,7 @@ pub const Value = union(Tag) { reader.context.size_hint = @as(Blob.SizeType, @truncate(drain_result.owned.size_hint)); } - locked.readable = JSC.WebCore.ReadableStream.Strong.init(.{ + locked.readable = jsc.WebCore.ReadableStream.Strong.init(.{ .ptr = .{ .Bytes = &reader.context }, .value = try reader.toReadableStream(globalThis), }, globalThis); @@ -1026,13 +1026,13 @@ pub const Value = union(Tag) { return Value{ .Locked = .{ - .readable = JSC.WebCore.ReadableStream.Strong.init(teed, globalThis), + .readable = jsc.WebCore.ReadableStream.Strong.init(teed, globalThis), .global = globalThis, }, }; } - pub fn clone(this: *Value, globalThis: *JSC.JSGlobalObject) bun.JSError!Value { + pub fn clone(this: *Value, globalThis: *jsc.JSGlobalObject) bun.JSError!Value { this.toBlobIfPossible(); if (this.* == .Locked) { @@ -1087,7 +1087,7 @@ pub fn extract( pub fn Mixin(comptime Type: type) type { return struct { - pub fn getText(this: *Type, globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { + pub fn getText(this: *Type, globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { var value: *Body.Value = this.getBodyValue(); if (value.* == .Used) { return handleBodyAlreadyUsed(globalObject); @@ -1102,20 +1102,20 @@ pub fn Mixin(comptime Type: type) type { } var blob = value.useAsAnyBlobAllowNonUTF8String(); - return JSC.JSPromise.wrap(globalObject, lifetimeWrap(AnyBlob.toString, .transfer), .{ &blob, globalObject }); + return jsc.JSPromise.wrap(globalObject, lifetimeWrap(AnyBlob.toString, .transfer), .{ &blob, globalObject }); } - pub fn getBody(this: *Type, globalThis: *JSC.JSGlobalObject) bun.JSError!JSValue { + pub fn getBody(this: *Type, globalThis: *jsc.JSGlobalObject) bun.JSError!JSValue { var body: *Body.Value = this.getBodyValue(); if (body.* == .Used) { - return JSC.WebCore.ReadableStream.used(globalThis); + return jsc.WebCore.ReadableStream.used(globalThis); } return body.toReadableStream(globalThis); } - pub fn getBodyUsed(this: *Type, globalObject: *JSC.JSGlobalObject) JSValue { + pub fn getBodyUsed(this: *Type, globalObject: *jsc.JSGlobalObject) JSValue { return JSValue.jsBoolean( switch (this.getBodyValue().*) { .Used => true, @@ -1135,15 +1135,15 @@ pub fn Mixin(comptime Type: type) type { ); } - fn lifetimeWrap(comptime Fn: anytype, comptime lifetime: JSC.WebCore.Lifetime) fn (*AnyBlob, *JSC.JSGlobalObject) JSC.JSValue { + fn lifetimeWrap(comptime Fn: anytype, comptime lifetime: jsc.WebCore.Lifetime) fn (*AnyBlob, *jsc.JSGlobalObject) jsc.JSValue { return struct { - fn wrap(this: *AnyBlob, globalObject: *JSC.JSGlobalObject) JSC.JSValue { - return JSC.toJSHostCall(globalObject, @src(), Fn, .{ this, globalObject, lifetime }); + fn wrap(this: *AnyBlob, globalObject: *jsc.JSGlobalObject) jsc.JSValue { + return jsc.toJSHostCall(globalObject, @src(), Fn, .{ this, globalObject, lifetime }); } }.wrap; } - pub fn getJSON(this: *Type, globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { + pub fn getJSON(this: *Type, globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { var value: *Body.Value = this.getBodyValue(); if (value.* == .Used) { return handleBodyAlreadyUsed(globalObject); @@ -1162,14 +1162,14 @@ pub fn Mixin(comptime Type: type) type { var blob = value.useAsAnyBlobAllowNonUTF8String(); - return JSC.JSPromise.wrap(globalObject, lifetimeWrap(AnyBlob.toJSON, .share), .{ &blob, globalObject }); + return jsc.JSPromise.wrap(globalObject, lifetimeWrap(AnyBlob.toJSON, .share), .{ &blob, globalObject }); } - fn handleBodyAlreadyUsed(globalObject: *JSC.JSGlobalObject) JSValue { + fn handleBodyAlreadyUsed(globalObject: *jsc.JSGlobalObject) JSValue { return globalObject.ERR(.BODY_ALREADY_USED, "Body already used", .{}).reject(); } - pub fn getArrayBuffer(this: *Type, globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { + pub fn getArrayBuffer(this: *Type, globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { var value: *Body.Value = this.getBodyValue(); if (value.* == .Used) { @@ -1190,10 +1190,10 @@ pub fn Mixin(comptime Type: type) type { // toArrayBuffer in AnyBlob checks for non-UTF8 strings var blob: AnyBlob = value.useAsAnyBlobAllowNonUTF8String(); - return JSC.JSPromise.wrap(globalObject, lifetimeWrap(AnyBlob.toArrayBuffer, .transfer), .{ &blob, globalObject }); + return jsc.JSPromise.wrap(globalObject, lifetimeWrap(AnyBlob.toArrayBuffer, .transfer), .{ &blob, globalObject }); } - pub fn getBytes(this: *Type, globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { + pub fn getBytes(this: *Type, globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { var value: *Body.Value = this.getBodyValue(); if (value.* == .Used) { @@ -1212,10 +1212,10 @@ pub fn Mixin(comptime Type: type) type { // toArrayBuffer in AnyBlob checks for non-UTF8 strings var blob: AnyBlob = value.useAsAnyBlobAllowNonUTF8String(); - return JSC.JSPromise.wrap(globalObject, lifetimeWrap(AnyBlob.toUint8Array, .transfer), .{ &blob, globalObject }); + return jsc.JSPromise.wrap(globalObject, lifetimeWrap(AnyBlob.toUint8Array, .transfer), .{ &blob, globalObject }); } - pub fn getFormData(this: *Type, globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { + pub fn getFormData(this: *Type, globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { var value: *Body.Value = this.getBodyValue(); if (value.* == .Used) { @@ -1256,17 +1256,17 @@ pub fn Mixin(comptime Type: type) type { ).reject(); }; - return JSC.JSPromise.wrapValue( + return jsc.JSPromise.wrapValue( globalObject, js_value, ); } - pub fn getBlob(this: *Type, globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { + pub fn getBlob(this: *Type, globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { return getBlobWithThisValue(this, globalObject, callframe.this()); } - pub fn getBlobWithThisValue(this: *Type, globalObject: *JSC.JSGlobalObject, this_value: JSValue) bun.JSError!JSC.JSValue { + pub fn getBlobWithThisValue(this: *Type, globalObject: *jsc.JSGlobalObject, this_value: JSValue) bun.JSError!jsc.JSValue { var value: *Body.Value = this.getBodyValue(); if (value.* == .Used) { @@ -1312,10 +1312,10 @@ pub fn Mixin(comptime Type: type) type { blob.store.?.mime_type = MimeType.text; } } - return JSC.JSPromise.resolvedPromiseValue(globalObject, blob.toJS(globalObject)); + return jsc.JSPromise.resolvedPromiseValue(globalObject, blob.toJS(globalObject)); } - pub fn getBlobWithoutCallFrame(this: *Type, globalObject: *JSC.JSGlobalObject) bun.JSError!JSC.JSValue { + pub fn getBlobWithoutCallFrame(this: *Type, globalObject: *jsc.JSGlobalObject) bun.JSError!jsc.JSValue { return getBlobWithThisValue(this, globalObject, .zero); } }; @@ -1331,9 +1331,9 @@ pub const ValueBufferer = struct { onFinishedBuffering: Callback, js_sink: ?*ArrayBufferSink.JSSink = null, - byte_stream: ?*JSC.WebCore.ByteStream = null, + byte_stream: ?*jsc.WebCore.ByteStream = null, // readable stream strong ref to keep byte stream alive - readable_stream_ref: JSC.WebCore.ReadableStream.Strong = .{}, + readable_stream_ref: jsc.WebCore.ReadableStream.Strong = .{}, stream_buffer: bun.MutableString, allocator: std.mem.Allocator, global: *JSGlobalObject, @@ -1374,7 +1374,7 @@ pub const ValueBufferer = struct { return this; } - pub fn run(sink: *@This(), value: *JSC.WebCore.Body.Value) !void { + pub fn run(sink: *@This(), value: *jsc.WebCore.Body.Value) !void { value.toBlobIfPossible(); switch (value.*) { @@ -1433,7 +1433,7 @@ pub const ValueBufferer = struct { }, } } - fn onStreamPipe(sink: *@This(), stream: JSC.WebCore.streams.Result, allocator: std.mem.Allocator) void { + fn onStreamPipe(sink: *@This(), stream: jsc.WebCore.streams.Result, allocator: std.mem.Allocator) void { const stream_needs_deinit = stream == .owned or stream == .owned_and_done; defer { @@ -1457,14 +1457,14 @@ pub const ValueBufferer = struct { } } - pub fn onResolveStream(_: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { + pub fn onResolveStream(_: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { var args = callframe.arguments_old(2); var sink: *@This() = args.ptr[args.len - 1].asPromisePtr(@This()); sink.handleResolveStream(true); return .js_undefined; } - pub fn onRejectStream(_: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { + pub fn onRejectStream(_: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const args = callframe.arguments_old(2); var sink = args.ptr[args.len - 1].asPromisePtr(@This()); const err = args.ptr[0]; @@ -1478,7 +1478,7 @@ pub const ValueBufferer = struct { sink.js_sink = null; wrapper.sink.destroy(); } - var ref = JSC.Strong.Optional.create(err, sink.global); + var ref = jsc.Strong.Optional.create(err, sink.global); defer ref.deinit(); sink.onFinishedBuffering(sink.ctx, "", .{ .JSValue = ref }, is_async); } @@ -1494,7 +1494,7 @@ pub const ValueBufferer = struct { } } - fn createJSSink(sink: *@This(), stream: JSC.WebCore.ReadableStream) !void { + fn createJSSink(sink: *@This(), stream: jsc.WebCore.ReadableStream) !void { stream.value.ensureStillAlive(); var allocator = sink.allocator; var buffer_stream = try allocator.create(ArrayBufferSink.JSSink); @@ -1563,7 +1563,7 @@ pub const ValueBufferer = struct { return error.PipeFailed; } - fn bufferLockedBodyValue(sink: *@This(), value: *JSC.WebCore.Body.Value) !void { + fn bufferLockedBodyValue(sink: *@This(), value: *jsc.WebCore.Body.Value) !void { assert(value.* == .Locked); const locked = &value.Locked; if (locked.readable.get(sink.global)) |stream| { @@ -1601,7 +1601,7 @@ pub const ValueBufferer = struct { return; } - byte_stream.pipe = JSC.WebCore.Pipe.Wrap(@This(), onStreamPipe).init(sink); + byte_stream.pipe = jsc.WebCore.Pipe.Wrap(@This(), onStreamPipe).init(sink); sink.byte_stream = byte_stream; log("byte stream pre-buffered {}", .{bytes.len}); @@ -1623,7 +1623,7 @@ pub const ValueBufferer = struct { locked.onReceiveValue = @This().onReceiveValue; } - fn onReceiveValue(ctx: *anyopaque, value: *JSC.WebCore.Body.Value) void { + fn onReceiveValue(ctx: *anyopaque, value: *jsc.WebCore.Body.Value) void { const sink = bun.cast(*@This(), ctx); switch (value.*) { .Error => |err| { @@ -1642,13 +1642,15 @@ pub const ValueBufferer = struct { } comptime { - const jsonResolveStream = JSC.toJSHostFn(onResolveStream); + const jsonResolveStream = jsc.toJSHostFn(onResolveStream); @export(&jsonResolveStream, .{ .name = "Bun__BodyValueBufferer__onResolveStream" }); - const jsonRejectStream = JSC.toJSHostFn(onRejectStream); + const jsonRejectStream = jsc.toJSHostFn(onRejectStream); @export(&jsonRejectStream, .{ .name = "Bun__BodyValueBufferer__onRejectStream" }); } }; +const string = []const u8; + const std = @import("std"); const bun = @import("bun"); @@ -1656,23 +1658,22 @@ const MutableString = bun.MutableString; const Output = bun.Output; const assert = bun.assert; const default_allocator = bun.default_allocator; -const string = bun.string; const strings = bun.strings; const FetchHeaders = bun.webcore.FetchHeaders; const MimeType = bun.http.MimeType; -const JSC = bun.JSC; -const ArrayBuffer = JSC.ArrayBuffer; -const JSGlobalObject = JSC.JSGlobalObject; -const JSPromise = JSC.JSPromise; -const JSValue = JSC.JSValue; -const SystemError = JSC.SystemError; -const VirtualMachine = JSC.VirtualMachine; -const ZigString = JSC.ZigString; +const jsc = bun.jsc; +const ArrayBuffer = jsc.ArrayBuffer; +const JSGlobalObject = jsc.JSGlobalObject; +const JSPromise = jsc.JSPromise; +const JSValue = jsc.JSValue; +const SystemError = jsc.SystemError; +const VirtualMachine = jsc.VirtualMachine; +const ZigString = jsc.ZigString; -const Response = JSC.WebCore.Response; -const streams = JSC.WebCore.streams; +const Response = jsc.WebCore.Response; +const streams = jsc.WebCore.streams; -const Blob = JSC.WebCore.Blob; +const Blob = jsc.WebCore.Blob; const AnyBlob = Blob.Any; const InternalBlob = Blob.Internal; diff --git a/src/bun.js/webcore/CookieMap.zig b/src/bun.js/webcore/CookieMap.zig index a47f9f596b..0cc15b1f86 100644 --- a/src/bun.js/webcore/CookieMap.zig +++ b/src/bun.js/webcore/CookieMap.zig @@ -1,7 +1,7 @@ pub const CookieMap = opaque { - extern fn CookieMap__write(cookie_map: *CookieMap, global_this: *bun.JSC.JSGlobalObject, ssl_enabled: bool, uws_http_response: *anyopaque) void; + extern fn CookieMap__write(cookie_map: *CookieMap, global_this: *bun.jsc.JSGlobalObject, ssl_enabled: bool, uws_http_response: *anyopaque) void; - pub fn write(cookie_map: *CookieMap, globalThis: *bun.JSC.JSGlobalObject, ssl_enabled: bool, uws_http_response: *anyopaque) bun.JSError!void { + pub fn write(cookie_map: *CookieMap, globalThis: *bun.jsc.JSGlobalObject, ssl_enabled: bool, uws_http_response: *anyopaque) bun.JSError!void { return bun.jsc.fromJSHostCallGeneric(globalThis, @src(), CookieMap__write, .{ cookie_map, globalThis, ssl_enabled, uws_http_response }); } diff --git a/src/bun.js/webcore/Crypto.zig b/src/bun.js/webcore/Crypto.zig index b5a7719bb9..653b9a17be 100644 --- a/src/bun.js/webcore/Crypto.zig +++ b/src/bun.js/webcore/Crypto.zig @@ -1,6 +1,6 @@ const Crypto = @This(); -pub const js = JSC.Codegen.JSCrypto; +pub const js = jsc.Codegen.JSCrypto; pub const toJS = js.toJS; pub const fromJS = js.fromJS; pub const fromJSDirect = js.fromJSDirect; @@ -11,26 +11,26 @@ comptime { _ = CryptoObject__create; } -fn throwInvalidParameter(globalThis: *JSC.JSGlobalObject) bun.JSError { +fn throwInvalidParameter(globalThis: *jsc.JSGlobalObject) bun.JSError { return globalThis.ERR(.CRYPTO_SCRYPT_INVALID_PARAMETER, "Invalid scrypt parameters", .{}).throw(); } -fn throwInvalidParams(globalThis: *JSC.JSGlobalObject, comptime error_type: @Type(.enum_literal), comptime message: [:0]const u8, fmt: anytype) bun.JSError { +fn throwInvalidParams(globalThis: *jsc.JSGlobalObject, comptime error_type: @Type(.enum_literal), comptime message: [:0]const u8, fmt: anytype) bun.JSError { if (error_type != .RangeError) @compileError("Error type not added!"); BoringSSL.ERR_clear_error(); return globalThis.ERR(.CRYPTO_INVALID_SCRYPT_PARAMS, message, fmt).throw(); } -pub fn timingSafeEqual(_: *@This(), global: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { - return JSC.Node.crypto.timingSafeEqual(global, callframe); +pub fn timingSafeEqual(_: *@This(), global: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { + return jsc.Node.crypto.timingSafeEqual(global, callframe); } pub fn timingSafeEqualWithoutTypeChecks( _: *@This(), - globalThis: *JSC.JSGlobalObject, - array_a: *JSC.JSUint8Array, - array_b: *JSC.JSUint8Array, -) JSC.JSValue { + globalThis: *jsc.JSGlobalObject, + array_a: *jsc.JSUint8Array, + array_b: *jsc.JSUint8Array, +) jsc.JSValue { const a = array_a.slice(); const b = array_b.slice(); @@ -39,14 +39,14 @@ pub fn timingSafeEqualWithoutTypeChecks( return globalThis.ERR(.CRYPTO_TIMING_SAFE_EQUAL_LENGTH, "Input buffers must have the same byte length", .{}).throw(); } - return JSC.jsBoolean(bun.BoringSSL.c.CRYPTO_memcmp(a.ptr, b.ptr, len) == 0); + return jsc.jsBoolean(bun.BoringSSL.c.CRYPTO_memcmp(a.ptr, b.ptr, len) == 0); } pub fn getRandomValues( _: *@This(), - globalThis: *JSC.JSGlobalObject, - callframe: *JSC.CallFrame, -) bun.JSError!JSC.JSValue { + globalThis: *jsc.JSGlobalObject, + callframe: *jsc.CallFrame, +) bun.JSError!jsc.JSValue { const arguments = callframe.arguments(); if (arguments.len == 0) { return globalThis.throwDOMException(.TypeMismatchError, "The data argument must be an integer-type TypedArray", .{}); @@ -65,16 +65,16 @@ pub fn getRandomValues( pub fn getRandomValuesWithoutTypeChecks( _: *@This(), - globalThis: *JSC.JSGlobalObject, - array: *JSC.JSUint8Array, -) JSC.JSValue { + globalThis: *jsc.JSGlobalObject, + array: *jsc.JSUint8Array, +) jsc.JSValue { const slice = array.slice(); randomData(globalThis, slice.ptr, slice.len); - return @as(JSC.JSValue, @enumFromInt(@as(i64, @bitCast(@intFromPtr(array))))); + return @as(jsc.JSValue, @enumFromInt(@as(i64, @bitCast(@intFromPtr(array))))); } fn randomData( - globalThis: *JSC.JSGlobalObject, + globalThis: *jsc.JSGlobalObject, ptr: [*]u8, len: usize, ) void { @@ -83,7 +83,7 @@ fn randomData( switch (slice.len) { 0 => {}, // 512 bytes or less we reuse from the same cache as UUID generation. - 1...JSC.RareData.EntropyCache.size / 8 => { + 1...jsc.RareData.EntropyCache.size / 8 => { bun.copy(u8, slice, globalThis.bunVM().rareData().entropySlice(slice.len)); }, else => { @@ -94,9 +94,9 @@ fn randomData( pub fn randomUUID( _: *@This(), - globalThis: *JSC.JSGlobalObject, - _: *JSC.CallFrame, -) bun.JSError!JSC.JSValue { + globalThis: *jsc.JSGlobalObject, + _: *jsc.CallFrame, +) bun.JSError!jsc.JSValue { var str, var bytes = bun.String.createUninitialized(.latin1, 36); const uuid = globalThis.bunVM().rareData().nextUUID(); @@ -106,31 +106,31 @@ pub fn randomUUID( } comptime { - const Bun__randomUUIDv7 = JSC.toJSHostFn(Bun__randomUUIDv7_); + const Bun__randomUUIDv7 = jsc.toJSHostFn(Bun__randomUUIDv7_); @export(&Bun__randomUUIDv7, .{ .name = "Bun__randomUUIDv7" }); } -pub fn Bun__randomUUIDv7_(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { +pub fn Bun__randomUUIDv7_(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const arguments = callframe.argumentsUndef(2).slice(); - var encoding_value: JSC.JSValue = .js_undefined; + var encoding_value: jsc.JSValue = .js_undefined; - const encoding: JSC.Node.Encoding = brk: { + const encoding: jsc.Node.Encoding = brk: { if (arguments.len > 0) { if (!arguments[0].isUndefined()) { if (arguments[0].isString()) { encoding_value = arguments[0]; - break :brk try JSC.Node.Encoding.fromJS(encoding_value, globalThis) orelse { + break :brk try jsc.Node.Encoding.fromJS(encoding_value, globalThis) orelse { return globalThis.ERR(.UNKNOWN_ENCODING, "Encoding must be one of base64, base64url, hex, or buffer", .{}).throw(); }; } } } - break :brk JSC.Node.Encoding.hex; + break :brk jsc.Node.Encoding.hex; }; const timestamp: u64 = brk: { - const timestamp_value: JSC.JSValue = if (!encoding_value.isUndefined() and arguments.len > 1) + const timestamp_value: jsc.JSValue = if (!encoding_value.isUndefined() and arguments.len > 1) arguments[1] else if (arguments.len == 1 and encoding_value.isUndefined()) arguments[0] @@ -162,12 +162,12 @@ pub fn Bun__randomUUIDv7_(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallF } comptime { - const Bun__randomUUIDv5 = JSC.toJSHostFn(Bun__randomUUIDv5_); + const Bun__randomUUIDv5 = jsc.toJSHostFn(Bun__randomUUIDv5_); @export(&Bun__randomUUIDv5, .{ .name = "Bun__randomUUIDv5" }); } -pub fn Bun__randomUUIDv5_(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { - const arguments: []const JSC.JSValue = callframe.argumentsUndef(3).slice(); +pub fn Bun__randomUUIDv5_(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { + const arguments: []const jsc.JSValue = callframe.argumentsUndef(3).slice(); if (arguments.len == 0 or arguments[0].isUndefinedOrNull()) { return globalThis.ERR(.INVALID_ARG_TYPE, "The \"name\" argument must be specified", .{}).throw(); @@ -177,16 +177,16 @@ pub fn Bun__randomUUIDv5_(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallF return globalThis.ERR(.INVALID_ARG_TYPE, "The \"namespace\" argument must be specified", .{}).throw(); } - const encoding: JSC.Node.Encoding = brk: { + const encoding: jsc.Node.Encoding = brk: { if (arguments.len > 2 and !arguments[2].isUndefined()) { if (arguments[2].isString()) { - break :brk try JSC.Node.Encoding.fromJS(arguments[2], globalThis) orelse { + break :brk try jsc.Node.Encoding.fromJS(arguments[2], globalThis) orelse { return globalThis.ERR(.UNKNOWN_ENCODING, "Encoding must be one of base64, base64url, hex, or buffer", .{}).throw(); }; } } - break :brk JSC.Node.Encoding.hex; + break :brk jsc.Node.Encoding.hex; }; const name_value = arguments[0]; @@ -200,7 +200,7 @@ pub fn Bun__randomUUIDv5_(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallF break :brk result; } else if (name_value.asArrayBuffer(globalThis)) |array_buffer| { - break :brk JSC.ZigString.Slice.fromUTF8NeverFree(array_buffer.byteSlice()); + break :brk jsc.ZigString.Slice.fromUTF8NeverFree(array_buffer.byteSlice()); } else { return globalThis.ERR(.INVALID_ARG_TYPE, "The \"name\" argument must be of type string or BufferSource", .{}).throw(); } @@ -250,8 +250,8 @@ pub fn Bun__randomUUIDv5_(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallF pub fn randomUUIDWithoutTypeChecks( _: *Crypto, - globalThis: *JSC.JSGlobalObject, -) JSC.JSValue { + globalThis: *jsc.JSGlobalObject, +) jsc.JSValue { const str, var bytes = bun.String.createUninitialized(.latin1, 36); defer str.deref(); @@ -263,12 +263,12 @@ pub fn randomUUIDWithoutTypeChecks( return str.toJS(globalThis); } -pub fn constructor(globalThis: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!*Crypto { - return JSC.Error.ILLEGAL_CONSTRUCTOR.throw(globalThis, "Crypto is not constructable", .{}); +pub fn constructor(globalThis: *jsc.JSGlobalObject, _: *jsc.CallFrame) bun.JSError!*Crypto { + return jsc.Error.ILLEGAL_CONSTRUCTOR.throw(globalThis, "Crypto is not constructable", .{}); } -pub export fn CryptoObject__create(globalThis: *JSC.JSGlobalObject) JSC.JSValue { - JSC.markBinding(@src()); +pub export fn CryptoObject__create(globalThis: *jsc.JSGlobalObject) jsc.JSValue { + jsc.markBinding(@src()); var ptr = bun.default_allocator.create(Crypto) catch { return globalThis.throwOutOfMemoryValue(); @@ -284,5 +284,5 @@ const UUID5 = @import("../uuid.zig").UUID5; const UUID7 = @import("../uuid.zig").UUID7; const bun = @import("bun"); -const JSC = bun.jsc; +const jsc = bun.jsc; const BoringSSL = bun.BoringSSL.c; diff --git a/src/bun.js/webcore/FileReader.zig b/src/bun.js/webcore/FileReader.zig index f8c527c23a..d3ceae17d3 100644 --- a/src/bun.js/webcore/FileReader.zig +++ b/src/bun.js/webcore/FileReader.zig @@ -5,7 +5,7 @@ const log = Output.scoped(.FileReader, false); reader: IOReader = IOReader.init(FileReader), done: bool = false, pending: streams.Result.Pending = .{}, -pending_value: JSC.Strong.Optional = .empty, +pending_value: jsc.Strong.Optional = .empty, pending_view: []u8 = &.{}, fd: bun.FileDescriptor = bun.invalid_fd, start_offset: ?usize = null, @@ -13,7 +13,7 @@ max_size: ?usize = null, total_readed: usize = 0, started: bool = false, waiting_for_onReaderDone: bool = false, -event_loop: JSC.EventLoopHandle, +event_loop: jsc.EventLoopHandle, lazy: Lazy = .{ .none = {} }, buffered: std.ArrayListUnmanaged(u8) = .{}, read_inside_on_pull: ReadDuringJSOnPullResult = .{ .none = {} }, @@ -43,7 +43,7 @@ pub const Lazy = union(enum) { }; pub extern "c" fn open_as_nonblocking_tty(i32, i32) i32; - pub fn openFileBlob(file: *Blob.Store.File) JSC.Maybe(OpenedFileBlob) { + pub fn openFileBlob(file: *Blob.Store.File) jsc.Maybe(OpenedFileBlob) { var this = OpenedFileBlob{ .fd = bun.invalid_fd }; var file_buf: bun.PathBuffer = undefined; var is_nonblocking = false; @@ -153,7 +153,7 @@ pub const Lazy = union(enum) { } }; -pub fn eventLoop(this: *const FileReader) JSC.EventLoopHandle { +pub fn eventLoop(this: *const FileReader) jsc.EventLoopHandle { return this.event_loop; } @@ -212,7 +212,7 @@ pub fn onStart(this: *FileReader) streams.Start { } } - this.event_loop = JSC.EventLoopHandle.init(this.parent().globalThis.bunVM().eventLoop()); + this.event_loop = jsc.EventLoopHandle.init(this.parent().globalThis.bunVM().eventLoop()); if (was_lazy) { _ = this.parent().incrementCount(); @@ -466,7 +466,7 @@ fn isPulling(this: *const FileReader) bool { return this.read_inside_on_pull != .none; } -pub fn onPull(this: *FileReader, buffer: []u8, array: JSC.JSValue) streams.Result { +pub fn onPull(this: *FileReader, buffer: []u8, array: jsc.JSValue) streams.Result { array.ensureStillAlive(); defer array.ensureStillAlive(); const drained = this.drain(); @@ -614,7 +614,7 @@ pub fn onReaderDone(this: *FileReader) void { globalThis, .js_undefined, &.{ - JSC.ArrayBuffer.fromBytes(buffered.items, .Uint8Array).toJS(globalThis) catch |err| { + jsc.ArrayBuffer.fromBytes(buffered.items, .Uint8Array).toJS(globalThis) catch |err| { this.pending.result = .{ .err = .{ .WeakJSValue = globalThis.takeException(err) } }; return; }, @@ -672,8 +672,8 @@ const std = @import("std"); const bun = @import("bun"); const Environment = bun.Environment; -const JSC = bun.jsc; const Output = bun.Output; +const jsc = bun.jsc; const webcore = bun.webcore; const Blob = webcore.Blob; diff --git a/src/bun.js/webcore/FileSink.zig b/src/bun.js/webcore/FileSink.zig index cd1901aaa8..06480529d8 100644 --- a/src/bun.js/webcore/FileSink.zig +++ b/src/bun.js/webcore/FileSink.zig @@ -2,7 +2,7 @@ const FileSink = @This(); ref_count: RefCount, writer: IOWriter = .{}, -event_loop_handle: JSC.EventLoopHandle, +event_loop_handle: jsc.EventLoopHandle, written: usize = 0, pending: streams.Result.Writable.Pending = .{ .result = .{ .done = {} }, @@ -25,7 +25,7 @@ auto_flusher: webcore.AutoFlusher = .{}, run_pending_later: FlushPendingTask = .{}, /// Currently, only used when `stdin` in `Bun.spawn` is a ReadableStream. -readable_stream: JSC.WebCore.ReadableStream.Strong = .{}, +readable_stream: jsc.WebCore.ReadableStream.Strong = .{}, const log = Output.scoped(.FileSink, false); @@ -60,7 +60,7 @@ pub fn memoryCost(this: *const FileSink) usize { return this.writer.memoryCost(); } -fn Bun__ForceFileSinkToBeSynchronousForProcessObjectStdio(_: *JSC.JSGlobalObject, jsvalue: JSC.JSValue) callconv(.C) void { +fn Bun__ForceFileSinkToBeSynchronousForProcessObjectStdio(_: *jsc.JSGlobalObject, jsvalue: jsc.JSValue) callconv(.C) void { var this: *FileSink = @alignCast(@ptrCast(JSSink.fromJS(jsvalue) orelse return)); this.force_sync = true; if (comptime !Environment.isWindows) { @@ -222,13 +222,13 @@ pub fn createWithPipe( } const evtloop = switch (@TypeOf(event_loop_)) { - JSC.EventLoopHandle => event_loop_, - else => JSC.EventLoopHandle.init(event_loop_), + jsc.EventLoopHandle => event_loop_, + else => jsc.EventLoopHandle.init(event_loop_), }; var this = bun.new(FileSink, .{ .ref_count = .init(), - .event_loop_handle = JSC.EventLoopHandle.init(evtloop), + .event_loop_handle = jsc.EventLoopHandle.init(evtloop), .fd = pipe.fd(), }); this.writer.setPipe(pipe); @@ -241,19 +241,19 @@ pub fn create( fd: bun.FileDescriptor, ) *FileSink { const evtloop = switch (@TypeOf(event_loop_)) { - JSC.EventLoopHandle => event_loop_, - else => JSC.EventLoopHandle.init(event_loop_), + jsc.EventLoopHandle => event_loop_, + else => jsc.EventLoopHandle.init(event_loop_), }; var this = bun.new(FileSink, .{ .ref_count = .init(), - .event_loop_handle = JSC.EventLoopHandle.init(evtloop), + .event_loop_handle = jsc.EventLoopHandle.init(evtloop), .fd = fd, }); this.writer.setParent(this); return this; } -pub fn setup(this: *FileSink, options: *const FileSink.Options) JSC.Maybe(void) { +pub fn setup(this: *FileSink, options: *const FileSink.Options) jsc.Maybe(void) { if (this.readable_stream.has()) { // Already started. return .{ .result = {} }; @@ -339,7 +339,7 @@ pub fn loop(this: *FileSink) *bun.Async.Loop { return this.event_loop_handle.loop(); } -pub fn eventLoop(this: *FileSink) JSC.EventLoopHandle { +pub fn eventLoop(this: *FileSink) jsc.EventLoopHandle { return this.event_loop_handle; } @@ -347,7 +347,7 @@ pub fn connect(this: *FileSink, signal: streams.Signal) void { this.signal = signal; } -pub fn start(this: *FileSink, stream_start: streams.Start) JSC.Maybe(void) { +pub fn start(this: *FileSink, stream_start: streams.Start) jsc.Maybe(void) { switch (stream_start) { .FileSink => |*file| { switch (this.setup(file)) { @@ -374,7 +374,7 @@ pub fn runPendingLater(this: *FileSink) void { const event_loop = this.eventLoop(); if (event_loop == .js) { this.ref(); - event_loop.js.enqueueTask(JSC.Task.init(&this.run_pending_later)); + event_loop.js.enqueueTask(jsc.Task.init(&this.run_pending_later)); } } @@ -411,11 +411,11 @@ pub fn onAutoFlush(this: *FileSink) bool { return is_registered; } -pub fn flush(_: *FileSink) JSC.Maybe(void) { +pub fn flush(_: *FileSink) jsc.Maybe(void) { return .{ .result = {} }; } -pub fn flushFromJS(this: *FileSink, globalThis: *JSGlobalObject, wait: bool) JSC.Maybe(JSValue) { +pub fn flushFromJS(this: *FileSink, globalThis: *JSGlobalObject, wait: bool) jsc.Maybe(JSValue) { _ = wait; if (this.pending.state == .pending) { @@ -458,7 +458,7 @@ pub fn init(fd: bun.FileDescriptor, event_loop_handle: anytype) *FileSink { .ref_count = .init(), .writer = .{}, .fd = fd, - .event_loop_handle = JSC.EventLoopHandle.init(event_loop_handle), + .event_loop_handle = jsc.EventLoopHandle.init(event_loop_handle), }); this.writer.setParent(this); @@ -468,7 +468,7 @@ pub fn init(fd: bun.FileDescriptor, event_loop_handle: anytype) *FileSink { pub fn construct(this: *FileSink, _: std.mem.Allocator) void { this.* = FileSink{ .ref_count = .init(), - .event_loop_handle = JSC.EventLoopHandle.init(JSC.VirtualMachine.get().eventLoop()), + .event_loop_handle = jsc.EventLoopHandle.init(jsc.VirtualMachine.get().eventLoop()), }; } @@ -495,7 +495,7 @@ pub fn writeUTF16(this: *@This(), data: streams.Result) streams.Result.Writable return this.toResult(this.writer.writeUTF16(data.slice16())); } -pub fn end(this: *FileSink, _: ?bun.sys.Error) JSC.Maybe(void) { +pub fn end(this: *FileSink, _: ?bun.sys.Error) jsc.Maybe(void) { if (this.done) { return .{ .result = {} }; } @@ -545,7 +545,7 @@ pub fn toJSWithDestructor(this: *FileSink, globalThis: *JSGlobalObject, destruct return JSSink.createObject(globalThis, this, if (destructor) |dest| @intFromPtr(dest.ptr()) else 0); } -pub fn endFromJS(this: *FileSink, globalThis: *JSGlobalObject) JSC.Maybe(JSValue) { +pub fn endFromJS(this: *FileSink, globalThis: *JSGlobalObject) jsc.Maybe(JSValue) { if (this.done) { if (this.pending.state == .pending) { return .{ .result = this.pending.future.promise.strong.value() }; @@ -648,7 +648,7 @@ pub const FlushPendingTask = struct { }; /// Does not ref or unref. -fn handleResolveStream(this: *FileSink, globalThis: *JSC.JSGlobalObject) void { +fn handleResolveStream(this: *FileSink, globalThis: *jsc.JSGlobalObject) void { if (this.readable_stream.get(globalThis)) |*stream| { stream.done(globalThis); } @@ -659,7 +659,7 @@ fn handleResolveStream(this: *FileSink, globalThis: *JSC.JSGlobalObject) void { } /// Does not ref or unref. -fn handleRejectStream(this: *FileSink, globalThis: *JSC.JSGlobalObject, _: JSC.JSValue) void { +fn handleRejectStream(this: *FileSink, globalThis: *jsc.JSGlobalObject, _: jsc.JSValue) void { if (this.readable_stream.get(globalThis)) |*stream| { stream.abort(globalThis); this.readable_stream.deinit(); @@ -670,7 +670,7 @@ fn handleRejectStream(this: *FileSink, globalThis: *JSC.JSGlobalObject, _: JSC.J } } -fn onResolveStream(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { +fn onResolveStream(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { log("onResolveStream", .{}); var args = callframe.arguments(); var this: *@This() = args[args.len - 1].asPromisePtr(@This()); @@ -678,7 +678,7 @@ fn onResolveStream(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) b this.handleResolveStream(globalThis); return .js_undefined; } -fn onRejectStream(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { +fn onRejectStream(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { log("onRejectStream", .{}); const args = callframe.arguments(); var this = args[args.len - 1].asPromisePtr(@This()); @@ -689,9 +689,9 @@ fn onRejectStream(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bu return .js_undefined; } -pub fn assignToStream(this: *FileSink, stream: *JSC.WebCore.ReadableStream, globalThis: *JSGlobalObject) JSC.JSValue { +pub fn assignToStream(this: *FileSink, stream: *jsc.WebCore.ReadableStream, globalThis: *JSGlobalObject) jsc.JSValue { var signal = &this.signal; - signal.* = JSC.WebCore.FileSink.JSSink.SinkSignal.init(JSValue.zero); + signal.* = jsc.WebCore.FileSink.JSSink.SinkSignal.init(JSValue.zero); this.ref(); defer this.deref(); @@ -700,7 +700,7 @@ pub fn assignToStream(this: *FileSink, stream: *JSC.WebCore.ReadableStream, glob signal.clear(); this.readable_stream = .init(stream.*, globalThis); - const promise_result = JSC.WebCore.FileSink.JSSink.assignToStream(globalThis, stream.value, this, @as(**anyopaque, @ptrCast(&signal.ptr))); + const promise_result = jsc.WebCore.FileSink.JSSink.assignToStream(globalThis, stream.value, this, @as(**anyopaque, @ptrCast(&signal.ptr))); if (promise_result.toError()) |err| { this.readable_stream.deinit(); @@ -734,8 +734,8 @@ pub fn assignToStream(this: *FileSink, stream: *JSC.WebCore.ReadableStream, glob comptime { const export_prefix = "Bun__FileSink"; if (bun.Environment.export_cpp_apis) { - @export(&JSC.toJSHostFn(onResolveStream), .{ .name = export_prefix ++ "__onResolveStream" }); - @export(&JSC.toJSHostFn(onRejectStream), .{ .name = export_prefix ++ "__onRejectStream" }); + @export(&jsc.toJSHostFn(onResolveStream), .{ .name = export_prefix ++ "__onResolveStream" }); + @export(&jsc.toJSHostFn(onRejectStream), .{ .name = export_prefix ++ "__onRejectStream" }); } } @@ -746,9 +746,9 @@ const Environment = bun.Environment; const Output = bun.Output; const uv = bun.windows.libuv; -const JSC = bun.jsc; -const JSGlobalObject = JSC.JSGlobalObject; -const JSValue = JSC.JSValue; +const jsc = bun.jsc; +const JSGlobalObject = jsc.JSGlobalObject; +const JSValue = jsc.JSValue; const webcore = bun.webcore; const Blob = webcore.Blob; diff --git a/src/bun.js/webcore/ObjectURLRegistry.zig b/src/bun.js/webcore/ObjectURLRegistry.zig index 6432fb2a43..314ce7a5f3 100644 --- a/src/bun.js/webcore/ObjectURLRegistry.zig +++ b/src/bun.js/webcore/ObjectURLRegistry.zig @@ -4,10 +4,10 @@ lock: bun.Mutex = .{}, map: std.AutoHashMap(UUID, *Entry) = std.AutoHashMap(UUID, *Entry).init(bun.default_allocator), pub const Entry = struct { - blob: JSC.WebCore.Blob, + blob: jsc.WebCore.Blob, pub const new = bun.TrivialNew(@This()); - pub fn init(blob: *const JSC.WebCore.Blob) *Entry { + pub fn init(blob: *const jsc.WebCore.Blob) *Entry { return Entry.new(.{ .blob = blob.dupeWithContentType(true), }); @@ -19,7 +19,7 @@ pub const Entry = struct { } }; -pub fn register(this: *ObjectURLRegistry, vm: *JSC.VirtualMachine, blob: *const JSC.WebCore.Blob) UUID { +pub fn register(this: *ObjectURLRegistry, vm: *jsc.VirtualMachine, blob: *const jsc.WebCore.Blob) UUID { const uuid = vm.rareData().nextUUID(); const entry = Entry.init(blob); @@ -44,7 +44,7 @@ pub fn singleton() *ObjectURLRegistry { return &Singleton.registry; } -fn getDupedBlob(this: *ObjectURLRegistry, uuid: *const UUID) ?JSC.WebCore.Blob { +fn getDupedBlob(this: *ObjectURLRegistry, uuid: *const UUID) ?jsc.WebCore.Blob { this.lock.lock(); defer this.lock.unlock(); const entry = this.map.get(uuid.*) orelse return null; @@ -55,7 +55,7 @@ fn uuidFromPathname(pathname: []const u8) ?UUID { return UUID.parse(pathname) catch return null; } -pub fn resolveAndDupe(this: *ObjectURLRegistry, pathname: []const u8) ?JSC.WebCore.Blob { +pub fn resolveAndDupe(this: *ObjectURLRegistry, pathname: []const u8) ?jsc.WebCore.Blob { const uuid = uuidFromPathname(pathname) orelse return null; this.lock.lock(); defer this.lock.unlock(); @@ -63,8 +63,8 @@ pub fn resolveAndDupe(this: *ObjectURLRegistry, pathname: []const u8) ?JSC.WebCo return entry.blob.dupeWithContentType(true); } -pub fn resolveAndDupeToJS(this: *ObjectURLRegistry, pathname: []const u8, globalObject: *JSC.JSGlobalObject) ?JSC.JSValue { - var blob = JSC.WebCore.Blob.new(this.resolveAndDupe(pathname) orelse return null); +pub fn resolveAndDupeToJS(this: *ObjectURLRegistry, pathname: []const u8, globalObject: *jsc.JSGlobalObject) ?jsc.JSValue { + var blob = jsc.WebCore.Blob.new(this.resolveAndDupe(pathname) orelse return null); blob.allocator = bun.default_allocator; return blob.toJS(globalObject); } @@ -85,15 +85,15 @@ pub fn has(this: *ObjectURLRegistry, pathname: []const u8) bool { } comptime { - const Bun__createObjectURL = JSC.toJSHostFn(Bun__createObjectURL_); + const Bun__createObjectURL = jsc.toJSHostFn(Bun__createObjectURL_); @export(&Bun__createObjectURL, .{ .name = "Bun__createObjectURL" }); } -fn Bun__createObjectURL_(globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { +fn Bun__createObjectURL_(globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const arguments = callframe.arguments_old(1); if (arguments.len < 1) { return globalObject.throwNotEnoughArguments("createObjectURL", 1, arguments.len); } - const blob = arguments.ptr[0].as(JSC.WebCore.Blob) orelse { + const blob = arguments.ptr[0].as(jsc.WebCore.Blob) orelse { return globalObject.throwInvalidArguments("createObjectURL expects a Blob object", .{}); }; const registry = ObjectURLRegistry.singleton(); @@ -103,10 +103,10 @@ fn Bun__createObjectURL_(globalObject: *JSC.JSGlobalObject, callframe: *JSC.Call } comptime { - const Bun__revokeObjectURL = JSC.toJSHostFn(Bun__revokeObjectURL_); + const Bun__revokeObjectURL = jsc.toJSHostFn(Bun__revokeObjectURL_); @export(&Bun__revokeObjectURL, .{ .name = "Bun__revokeObjectURL" }); } -fn Bun__revokeObjectURL_(globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { +fn Bun__revokeObjectURL_(globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const arguments = callframe.arguments_old(1); if (arguments.len < 1) { return globalObject.throwNotEnoughArguments("revokeObjectURL", 1, arguments.len); @@ -132,10 +132,10 @@ fn Bun__revokeObjectURL_(globalObject: *JSC.JSGlobalObject, callframe: *JSC.Call } comptime { - const jsFunctionResolveObjectURL = JSC.toJSHostFn(jsFunctionResolveObjectURL_); + const jsFunctionResolveObjectURL = jsc.toJSHostFn(jsFunctionResolveObjectURL_); @export(&jsFunctionResolveObjectURL, .{ .name = "jsFunctionResolveObjectURL" }); } -fn jsFunctionResolveObjectURL_(globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { +fn jsFunctionResolveObjectURL_(globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const arguments = callframe.arguments_old(1); // Errors are ignored. @@ -173,5 +173,5 @@ pub fn isBlobURL(url: []const u8) bool { const std = @import("std"); const bun = @import("bun"); -const JSC = bun.JSC; const UUID = bun.UUID; +const jsc = bun.jsc; diff --git a/src/bun.js/webcore/ReadableStream.zig b/src/bun.js/webcore/ReadableStream.zig index b2de188181..4697c8e2c7 100644 --- a/src/bun.js/webcore/ReadableStream.zig +++ b/src/bun.js/webcore/ReadableStream.zig @@ -4,13 +4,13 @@ value: JSValue, ptr: Source, pub const Strong = struct { - held: JSC.Strong.Optional = .empty, + held: jsc.Strong.Optional = .empty, pub fn has(this: *Strong) bool { return this.held.has(); } - pub fn isDisturbed(this: *const Strong, global: *JSC.JSGlobalObject) bool { + pub fn isDisturbed(this: *const Strong, global: *jsc.JSGlobalObject) bool { if (this.get(global)) |stream| { return stream.isDisturbed(global); } @@ -24,7 +24,7 @@ pub const Strong = struct { }; } - pub fn get(this: *const Strong, global: *JSC.JSGlobalObject) ?ReadableStream { + pub fn get(this: *const Strong, global: *jsc.JSGlobalObject) ?ReadableStream { if (this.held.get()) |value| { return ReadableStream.fromJS(value, global) catch null; // TODO: properly propagate exception upwards } @@ -48,10 +48,10 @@ pub const Strong = struct { } }; -extern fn ReadableStream__tee(stream: JSValue, globalThis: *JSGlobalObject, out1: *JSC.JSValue, out2: *JSC.JSValue) bool; +extern fn ReadableStream__tee(stream: JSValue, globalThis: *JSGlobalObject, out1: *jsc.JSValue, out2: *jsc.JSValue) bool; pub fn tee(this: *const ReadableStream, globalThis: *JSGlobalObject) bun.JSError!?struct { ReadableStream, ReadableStream } { - var out1: JSC.JSValue = .zero; - var out2: JSC.JSValue = .zero; + var out1: jsc.JSValue = .zero; + var out2: jsc.JSValue = .zero; if (!try bun.jsc.fromJSHostCallGeneric(globalThis, @src(), ReadableStream__tee, .{ this.value, globalThis, &out1, &out2 })) { return null; } @@ -64,7 +64,7 @@ pub fn toJS(this: *const ReadableStream) JSValue { return this.value; } -pub fn reloadTag(this: *ReadableStream, globalThis: *JSC.JSGlobalObject) bun.JSError!void { +pub fn reloadTag(this: *ReadableStream, globalThis: *jsc.JSGlobalObject) bun.JSError!void { if (try ReadableStream.fromJS(this.value, globalThis)) |stream| { this.* = stream; } else { @@ -74,7 +74,7 @@ pub fn reloadTag(this: *ReadableStream, globalThis: *JSC.JSGlobalObject) bun.JSE pub fn toAnyBlob( stream: *ReadableStream, - globalThis: *JSC.JSGlobalObject, + globalThis: *jsc.JSGlobalObject, ) ?Blob.Any { if (stream.isDisturbed(globalThis)) { return null; @@ -116,7 +116,7 @@ pub fn toAnyBlob( } pub fn done(this: *const ReadableStream, globalThis: *JSGlobalObject) void { - JSC.markBinding(@src()); + jsc.markBinding(@src()); // done is called when we are done consuming the stream // cancel actually mark the stream source as done // this will resolve any pending promises to done: true @@ -136,7 +136,7 @@ pub fn done(this: *const ReadableStream, globalThis: *JSGlobalObject) void { } pub fn cancel(this: *const ReadableStream, globalThis: *JSGlobalObject) void { - JSC.markBinding(@src()); + jsc.markBinding(@src()); // cancel the stream ReadableStream__cancel(this.value, globalThis); // mark the stream source as done @@ -144,7 +144,7 @@ pub fn cancel(this: *const ReadableStream, globalThis: *JSGlobalObject) void { } pub fn abort(this: *const ReadableStream, globalThis: *JSGlobalObject) void { - JSC.markBinding(@src()); + jsc.markBinding(@src()); // for now we are just calling cancel should be fine this.cancel(globalThis); } @@ -157,7 +157,7 @@ pub fn forceDetach(this: *const ReadableStream, globalObject: *JSGlobalObject) v /// be careful, this can invalidate the stream do not call this multiple times /// this is meant to be called only once when we are done consuming the stream or from the ReadableStream.Strong.deinit pub fn detachIfPossible(_: *const ReadableStream, _: *JSGlobalObject) void { - JSC.markBinding(@src()); + jsc.markBinding(@src()); } pub const Tag = enum(i32) { @@ -207,8 +207,8 @@ pub const Source = union(Tag) { extern fn ReadableStreamTag__tagged(globalObject: *JSGlobalObject, possibleReadableStream: *JSValue, ptr: *?*anyopaque) Tag; extern fn ReadableStream__isDisturbed(possibleReadableStream: JSValue, globalObject: *JSGlobalObject) bool; extern fn ReadableStream__isLocked(possibleReadableStream: JSValue, globalObject: *JSGlobalObject) bool; -extern fn ReadableStream__empty(*JSGlobalObject) JSC.JSValue; -extern fn ReadableStream__used(*JSGlobalObject) JSC.JSValue; +extern fn ReadableStream__empty(*JSGlobalObject) jsc.JSValue; +extern fn ReadableStream__used(*JSGlobalObject) jsc.JSValue; extern fn ReadableStream__cancel(stream: JSValue, *JSGlobalObject) void; extern fn ReadableStream__abort(stream: JSValue, *JSGlobalObject) void; extern fn ReadableStream__detach(stream: JSValue, *JSGlobalObject) void; @@ -217,25 +217,25 @@ extern fn ReadableStream__fromBlob( store: *anyopaque, offset: usize, length: usize, -) JSC.JSValue; +) jsc.JSValue; pub fn isDisturbed(this: *const ReadableStream, globalObject: *JSGlobalObject) bool { - JSC.markBinding(@src()); + jsc.markBinding(@src()); return isDisturbedValue(this.value, globalObject); } -pub fn isDisturbedValue(value: JSC.JSValue, globalObject: *JSGlobalObject) bool { - JSC.markBinding(@src()); +pub fn isDisturbedValue(value: jsc.JSValue, globalObject: *JSGlobalObject) bool { + jsc.markBinding(@src()); return ReadableStream__isDisturbed(value, globalObject); } pub fn isLocked(this: *const ReadableStream, globalObject: *JSGlobalObject) bool { - JSC.markBinding(@src()); + jsc.markBinding(@src()); return ReadableStream__isLocked(this.value, globalObject); } pub fn fromJS(value: JSValue, globalThis: *JSGlobalObject) bun.JSError!?ReadableStream { - JSC.markBinding(@src()); + jsc.markBinding(@src()); value.ensureStillAlive(); var out = value; @@ -285,19 +285,19 @@ pub fn fromJS(value: JSValue, globalThis: *JSGlobalObject) bun.JSError!?Readable extern fn ZigGlobalObject__createNativeReadableStream(*JSGlobalObject, nativePtr: JSValue) JSValue; -pub fn fromNative(globalThis: *JSGlobalObject, native: JSC.JSValue) bun.JSError!JSC.JSValue { - JSC.markBinding(@src()); +pub fn fromNative(globalThis: *JSGlobalObject, native: jsc.JSValue) bun.JSError!jsc.JSValue { + jsc.markBinding(@src()); return bun.jsc.fromJSHostCall(globalThis, @src(), ZigGlobalObject__createNativeReadableStream, .{ globalThis, native }); } -pub fn fromOwnedSlice(globalThis: *JSGlobalObject, bytes: []u8, recommended_chunk_size: Blob.SizeType) bun.JSError!JSC.JSValue { +pub fn fromOwnedSlice(globalThis: *JSGlobalObject, bytes: []u8, recommended_chunk_size: Blob.SizeType) bun.JSError!jsc.JSValue { var blob = Blob.init(bytes, bun.default_allocator, globalThis); defer blob.deinit(); return fromBlobCopyRef(globalThis, &blob, recommended_chunk_size); } -pub fn fromBlobCopyRef(globalThis: *JSGlobalObject, blob: *const Blob, recommended_chunk_size: Blob.SizeType) bun.JSError!JSC.JSValue { - JSC.markBinding(@src()); +pub fn fromBlobCopyRef(globalThis: *JSGlobalObject, blob: *const Blob, recommended_chunk_size: Blob.SizeType) bun.JSError!jsc.JSValue { + jsc.markBinding(@src()); var store = blob.store orelse { return ReadableStream.empty(globalThis); }; @@ -316,7 +316,7 @@ pub fn fromBlobCopyRef(globalThis: *JSGlobalObject, blob: *const Blob, recommend var reader = webcore.FileReader.Source.new(.{ .globalThis = globalThis, .context = .{ - .event_loop = JSC.EventLoopHandle.init(globalThis.bunVM().eventLoop()), + .event_loop = jsc.EventLoopHandle.init(globalThis.bunVM().eventLoop()), .start_offset = blob.offset, .max_size = if (blob.size != Blob.max_size) blob.size else null, @@ -344,8 +344,8 @@ pub fn fromFileBlobWithOffset( globalThis: *JSGlobalObject, blob: *const Blob, offset: usize, -) bun.JSError!JSC.JSValue { - JSC.markBinding(@src()); +) bun.JSError!jsc.JSValue { + jsc.markBinding(@src()); var store = blob.store orelse { return ReadableStream.empty(globalThis); }; @@ -354,7 +354,7 @@ pub fn fromFileBlobWithOffset( var reader = webcore.FileReader.Source.new(.{ .globalThis = globalThis, .context = .{ - .event_loop = JSC.EventLoopHandle.init(globalThis.bunVM().eventLoop()), + .event_loop = jsc.EventLoopHandle.init(globalThis.bunVM().eventLoop()), .start_offset = offset, .lazy = .{ .blob = store, @@ -375,13 +375,13 @@ pub fn fromPipe( globalThis: *JSGlobalObject, parent: anytype, buffered_reader: anytype, -) bun.JSError!JSC.JSValue { +) bun.JSError!jsc.JSValue { _ = parent; // autofix - JSC.markBinding(@src()); + jsc.markBinding(@src()); var source = webcore.FileReader.Source.new(.{ .globalThis = globalThis, .context = .{ - .event_loop = JSC.EventLoopHandle.init(globalThis.bunVM().eventLoop()), + .event_loop = jsc.EventLoopHandle.init(globalThis.bunVM().eventLoop()), }, }); source.context.reader.from(buffered_reader, &source.context); @@ -389,13 +389,13 @@ pub fn fromPipe( return source.toReadableStream(globalThis); } -pub fn empty(globalThis: *JSGlobalObject) bun.JSError!JSC.JSValue { - JSC.markBinding(@src()); +pub fn empty(globalThis: *JSGlobalObject) bun.JSError!jsc.JSValue { + jsc.markBinding(@src()); return bun.jsc.fromJSHostCall(globalThis, @src(), ReadableStream__empty, .{globalThis}); } -pub fn used(globalThis: *JSGlobalObject) JSC.JSValue { - JSC.markBinding(@src()); +pub fn used(globalThis: *JSGlobalObject) jsc.JSValue { + jsc.markBinding(@src()); return ReadableStream__used(globalThis); } @@ -433,7 +433,7 @@ pub fn NewSource( comptime setRefUnrefFn: ?fn (this: *Context, enable: bool) void, comptime drainInternalBuffer: ?fn (this: *Context) bun.ByteList, comptime memoryCostFn: ?fn (this: *const Context) usize, - comptime toBufferedValue: ?fn (this: *Context, globalThis: *JSC.JSGlobalObject, action: streams.BufferAction.Tag) bun.JSError!JSC.JSValue, + comptime toBufferedValue: ?fn (this: *Context, globalThis: *jsc.JSGlobalObject, action: streams.BufferAction.Tag) bun.JSError!jsc.JSValue, ) type { return struct { context: Context, @@ -442,9 +442,9 @@ pub fn NewSource( pending_err: ?Syscall.Error = null, close_handler: ?*const fn (?*anyopaque) void = null, close_ctx: ?*anyopaque = null, - close_jsvalue: JSC.Strong.Optional = .empty, + close_jsvalue: jsc.Strong.Optional = .empty, globalThis: *JSGlobalObject = undefined, - this_jsvalue: JSC.JSValue = .zero, + this_jsvalue: jsc.JSValue = .zero, is_closed: bool = false, const This = @This(); @@ -549,7 +549,7 @@ pub fn NewSource( return .{}; } - pub fn toReadableStream(this: *ReadableStreamSourceType, globalThis: *JSGlobalObject) bun.JSError!JSC.JSValue { + pub fn toReadableStream(this: *ReadableStreamSourceType, globalThis: *JSGlobalObject) bun.JSError!jsc.JSValue { const out_value = brk: { if (this.this_jsvalue != .zero) { break :brk this.this_jsvalue; @@ -562,7 +562,7 @@ pub fn NewSource( return ReadableStream.fromNative(globalThis, out_value); } - pub fn setRawModeFromJS(this: *ReadableStreamSourceType, global: *JSC.JSGlobalObject, call_frame: *JSC.CallFrame) bun.JSError!JSValue { + pub fn setRawModeFromJS(this: *ReadableStreamSourceType, global: *jsc.JSGlobalObject, call_frame: *jsc.CallFrame) bun.JSError!JSValue { if (@hasDecl(Context, "setRawMode")) { const flag = call_frame.argument(0); if (Environment.allow_assert) { @@ -579,7 +579,7 @@ pub fn NewSource( const supports_ref = setRefUnrefFn != null; - pub const js = @field(JSC.Codegen, "JS" ++ name_ ++ "InternalReadableStreamSource"); + pub const js = @field(jsc.Codegen, "JS" ++ name_ ++ "InternalReadableStreamSource"); pub const toJS = js.toJS; pub const fromJS = js.fromJS; pub const fromJSDirect = js.fromJSDirect; @@ -610,8 +610,8 @@ pub fn NewSource( } pub const JSReadableStreamSource = struct { - pub fn pull(this: *ReadableStreamSourceType, globalThis: *JSGlobalObject, callFrame: *JSC.CallFrame) bun.JSError!JSC.JSValue { - JSC.markBinding(@src()); + pub fn pull(this: *ReadableStreamSourceType, globalThis: *JSGlobalObject, callFrame: *jsc.CallFrame) bun.JSError!jsc.JSValue { + jsc.markBinding(@src()); const this_jsvalue = callFrame.this(); const arguments = callFrame.arguments_old(2); const view = arguments.ptr[0]; @@ -626,8 +626,8 @@ pub fn NewSource( ); } - pub fn start(this: *ReadableStreamSourceType, globalThis: *JSGlobalObject, callFrame: *JSC.CallFrame) bun.JSError!JSC.JSValue { - JSC.markBinding(@src()); + pub fn start(this: *ReadableStreamSourceType, globalThis: *JSGlobalObject, callFrame: *jsc.CallFrame) bun.JSError!jsc.JSValue { + jsc.markBinding(@src()); this.globalThis = globalThis; this.this_jsvalue = callFrame.this(); switch (this.onStartFromJS()) { @@ -643,12 +643,12 @@ pub fn NewSource( } } - pub fn isClosed(this: *ReadableStreamSourceType, globalObject: *JSC.JSGlobalObject) JSC.JSValue { + pub fn isClosed(this: *ReadableStreamSourceType, globalObject: *jsc.JSGlobalObject) jsc.JSValue { _ = globalObject; // autofix - return JSC.JSValue.jsBoolean(this.is_closed); + return jsc.JSValue.jsBoolean(this.is_closed); } - fn processResult(this_jsvalue: JSC.JSValue, globalThis: *JSGlobalObject, flags: JSValue, result: streams.Result) bun.JSError!JSC.JSValue { + fn processResult(this_jsvalue: jsc.JSValue, globalThis: *JSGlobalObject, flags: JSValue, result: streams.Result) bun.JSError!jsc.JSValue { switch (result) { .err => |err| { if (err == .Error) { @@ -666,23 +666,23 @@ pub fn NewSource( return out; }, .temporary_and_done, .owned_and_done, .into_array_and_done => { - JSC.C.JSObjectSetPropertyAtIndex(globalThis, flags.asObjectRef(), 0, JSValue.jsBoolean(true).asObjectRef(), null); + jsc.C.JSObjectSetPropertyAtIndex(globalThis, flags.asObjectRef(), 0, JSValue.jsBoolean(true).asObjectRef(), null); return result.toJS(globalThis); }, else => return result.toJS(globalThis), } } - pub fn cancel(this: *ReadableStreamSourceType, globalObject: *JSC.JSGlobalObject, callFrame: *JSC.CallFrame) bun.JSError!JSC.JSValue { + pub fn cancel(this: *ReadableStreamSourceType, globalObject: *jsc.JSGlobalObject, callFrame: *jsc.CallFrame) bun.JSError!jsc.JSValue { _ = globalObject; // autofix - JSC.markBinding(@src()); + jsc.markBinding(@src()); this.this_jsvalue = callFrame.this(); this.cancel(); return .js_undefined; } - pub fn setOnCloseFromJS(this: *ReadableStreamSourceType, globalObject: *JSC.JSGlobalObject, value: JSC.JSValue) bun.JSError!void { - JSC.markBinding(@src()); + pub fn setOnCloseFromJS(this: *ReadableStreamSourceType, globalObject: *jsc.JSGlobalObject, value: jsc.JSValue) bun.JSError!void { + jsc.markBinding(@src()); this.close_handler = JSReadableStreamSource.onClose; this.globalThis = globalObject; @@ -698,8 +698,8 @@ pub fn NewSource( this.close_jsvalue.set(globalObject, cb); } - pub fn setOnDrainFromJS(this: *ReadableStreamSourceType, globalObject: *JSC.JSGlobalObject, value: JSC.JSValue) bun.JSError!void { - JSC.markBinding(@src()); + pub fn setOnDrainFromJS(this: *ReadableStreamSourceType, globalObject: *jsc.JSGlobalObject, value: jsc.JSValue) bun.JSError!void { + jsc.markBinding(@src()); this.globalThis = globalObject; if (value.isUndefined()) { @@ -714,18 +714,18 @@ pub fn NewSource( js.onDrainCallbackSetCached(this.this_jsvalue, globalObject, cb); } - pub fn getOnCloseFromJS(this: *ReadableStreamSourceType, globalObject: *JSC.JSGlobalObject) JSC.JSValue { + pub fn getOnCloseFromJS(this: *ReadableStreamSourceType, globalObject: *jsc.JSGlobalObject) jsc.JSValue { _ = globalObject; // autofix - JSC.markBinding(@src()); + jsc.markBinding(@src()); return this.close_jsvalue.get() orelse .js_undefined; } - pub fn getOnDrainFromJS(this: *ReadableStreamSourceType, globalObject: *JSC.JSGlobalObject) JSC.JSValue { + pub fn getOnDrainFromJS(this: *ReadableStreamSourceType, globalObject: *jsc.JSGlobalObject) jsc.JSValue { _ = globalObject; // autofix - JSC.markBinding(@src()); + jsc.markBinding(@src()); if (js.onDrainCallbackGetCached(this.this_jsvalue)) |val| { return val; @@ -734,9 +734,9 @@ pub fn NewSource( return .js_undefined; } - pub fn updateRef(this: *ReadableStreamSourceType, globalObject: *JSGlobalObject, callFrame: *JSC.CallFrame) bun.JSError!JSC.JSValue { + pub fn updateRef(this: *ReadableStreamSourceType, globalObject: *JSGlobalObject, callFrame: *jsc.CallFrame) bun.JSError!jsc.JSValue { _ = globalObject; // autofix - JSC.markBinding(@src()); + jsc.markBinding(@src()); this.this_jsvalue = callFrame.this(); const ref_or_unref = callFrame.argument(0).toBoolean(); this.setRef(ref_or_unref); @@ -745,7 +745,7 @@ pub fn NewSource( } fn onClose(ptr: ?*anyopaque) void { - JSC.markBinding(@src()); + jsc.markBinding(@src()); var this = bun.cast(*ReadableStreamSourceType, ptr.?); if (this.close_jsvalue.trySwap()) |cb| { this.globalThis.queueMicrotask(cb, &.{}); @@ -760,18 +760,18 @@ pub fn NewSource( _ = this.decrementCount(); } - pub fn drain(this: *ReadableStreamSourceType, globalThis: *JSGlobalObject, callFrame: *JSC.CallFrame) bun.JSError!JSC.JSValue { - JSC.markBinding(@src()); + pub fn drain(this: *ReadableStreamSourceType, globalThis: *JSGlobalObject, callFrame: *jsc.CallFrame) bun.JSError!jsc.JSValue { + jsc.markBinding(@src()); this.this_jsvalue = callFrame.this(); var list = this.drain(); if (list.len > 0) { - return JSC.ArrayBuffer.fromBytes(list.slice(), .Uint8Array).toJS(globalThis); + return jsc.ArrayBuffer.fromBytes(list.slice(), .Uint8Array).toJS(globalThis); } return .js_undefined; } - pub fn text(this: *ReadableStreamSourceType, globalThis: *JSGlobalObject, callFrame: *JSC.CallFrame) bun.JSError!JSC.JSValue { - JSC.markBinding(@src()); + pub fn text(this: *ReadableStreamSourceType, globalThis: *JSGlobalObject, callFrame: *jsc.CallFrame) bun.JSError!jsc.JSValue { + jsc.markBinding(@src()); this.this_jsvalue = callFrame.this(); if (toBufferedValue) |to_buffered_value| { @@ -782,8 +782,8 @@ pub fn NewSource( return .zero; } - pub fn arrayBuffer(this: *ReadableStreamSourceType, globalThis: *JSGlobalObject, callFrame: *JSC.CallFrame) bun.JSError!JSC.JSValue { - JSC.markBinding(@src()); + pub fn arrayBuffer(this: *ReadableStreamSourceType, globalThis: *JSGlobalObject, callFrame: *jsc.CallFrame) bun.JSError!jsc.JSValue { + jsc.markBinding(@src()); this.this_jsvalue = callFrame.this(); if (toBufferedValue) |to_buffered_value| { @@ -794,8 +794,8 @@ pub fn NewSource( return .zero; } - pub fn blob(this: *ReadableStreamSourceType, globalThis: *JSGlobalObject, callFrame: *JSC.CallFrame) bun.JSError!JSC.JSValue { - JSC.markBinding(@src()); + pub fn blob(this: *ReadableStreamSourceType, globalThis: *JSGlobalObject, callFrame: *jsc.CallFrame) bun.JSError!jsc.JSValue { + jsc.markBinding(@src()); this.this_jsvalue = callFrame.this(); if (toBufferedValue) |to_buffered_value| { @@ -806,8 +806,8 @@ pub fn NewSource( return .zero; } - pub fn bytes(this: *ReadableStreamSourceType, globalThis: *JSGlobalObject, callFrame: *JSC.CallFrame) bun.JSError!JSC.JSValue { - JSC.markBinding(@src()); + pub fn bytes(this: *ReadableStreamSourceType, globalThis: *JSGlobalObject, callFrame: *jsc.CallFrame) bun.JSError!jsc.JSValue { + jsc.markBinding(@src()); this.this_jsvalue = callFrame.this(); if (toBufferedValue) |to_buffered_value| { @@ -818,8 +818,8 @@ pub fn NewSource( return .zero; } - pub fn json(this: *ReadableStreamSourceType, globalThis: *JSGlobalObject, callFrame: *JSC.CallFrame) bun.JSError!JSC.JSValue { - JSC.markBinding(@src()); + pub fn json(this: *ReadableStreamSourceType, globalThis: *JSGlobalObject, callFrame: *jsc.CallFrame) bun.JSError!jsc.JSValue { + jsc.markBinding(@src()); this.this_jsvalue = callFrame.this(); if (toBufferedValue) |to_buffered_value| { @@ -837,9 +837,9 @@ const bun = @import("bun"); const Environment = bun.Environment; const Syscall = bun.sys; -const JSC = bun.jsc; -const JSGlobalObject = JSC.JSGlobalObject; -const JSValue = JSC.JSValue; +const jsc = bun.jsc; +const JSGlobalObject = jsc.JSGlobalObject; +const JSValue = jsc.JSValue; const webcore = bun.webcore; const Blob = webcore.Blob; diff --git a/src/bun.js/webcore/Request.zig b/src/bun.js/webcore/Request.zig index 8e13c751b1..205a2d90b9 100644 --- a/src/bun.js/webcore/Request.zig +++ b/src/bun.js/webcore/Request.zig @@ -9,14 +9,14 @@ signal: ?*AbortSignal = null, body: *Body.Value.HiveRef, method: Method = Method.GET, redirect: FetchRedirect = .follow, -request_context: JSC.API.AnyRequestContext = JSC.API.AnyRequestContext.Null, +request_context: jsc.API.AnyRequestContext = jsc.API.AnyRequestContext.Null, https: bool = false, weak_ptr_data: WeakRef.Data = .empty, // We must report a consistent value for this reported_estimated_size: usize = 0, internal_event_callback: InternalJSEventCallback = .{}, -pub const js = JSC.Codegen.JSRequest; +pub const js = jsc.Codegen.JSRequest; // NOTE: toJS is overridden pub const fromJS = js.fromJS; pub const fromJSDirect = js.fromJSDirect; @@ -39,7 +39,7 @@ pub fn memoryCost(this: *const Request) usize { return @sizeOf(Request) + this.request_context.memoryCost() + this.url.byteSlice().len + this.body.value.memoryCost(); } -pub export fn Request__setCookiesOnRequestContext(this: *Request, cookieMap: ?*JSC.WebCore.CookieMap) void { +pub export fn Request__setCookiesOnRequestContext(this: *Request, cookieMap: ?*jsc.WebCore.CookieMap) void { this.request_context.setCookies(cookieMap); } @@ -51,15 +51,15 @@ pub export fn Request__getUWSRequest( pub export fn Request__setInternalEventCallback( this: *Request, - callback: JSC.JSValue, - globalThis: *JSC.JSGlobalObject, + callback: jsc.JSValue, + globalThis: *jsc.JSGlobalObject, ) void { this.internal_event_callback = InternalJSEventCallback.init(callback, globalThis); // we always have the abort event but we need to enable the timeout event as well in case of `node:http`.Server.setTimeout is set this.request_context.enableTimeoutEvents(); } -pub export fn Request__setTimeout(this: *Request, seconds: JSC.JSValue, globalThis: *JSC.JSGlobalObject) void { +pub export fn Request__setTimeout(this: *Request, seconds: jsc.JSValue, globalThis: *jsc.JSGlobalObject) void { if (!seconds.isNumber()) { globalThis.throw("Failed to set timeout: The provided value is not of type 'number'.", .{}) catch {}; return; @@ -68,7 +68,7 @@ pub export fn Request__setTimeout(this: *Request, seconds: JSC.JSValue, globalTh this.setTimeout(seconds.to(c_uint)); } -pub export fn Request__clone(this: *Request, globalThis: *JSC.JSGlobalObject) ?*Request { +pub export fn Request__clone(this: *Request, globalThis: *jsc.JSGlobalObject) ?*Request { return this.clone(bun.default_allocator, globalThis) catch null; } @@ -80,11 +80,11 @@ comptime { } pub const InternalJSEventCallback = struct { - function: JSC.Strong.Optional = .empty, + function: jsc.Strong.Optional = .empty, - pub const EventType = JSC.API.NodeHTTPResponse.AbortEvent; + pub const EventType = jsc.API.NodeHTTPResponse.AbortEvent; - pub fn init(function: JSC.JSValue, globalThis: *JSC.JSGlobalObject) InternalJSEventCallback { + pub fn init(function: jsc.JSValue, globalThis: *jsc.JSGlobalObject) InternalJSEventCallback { return InternalJSEventCallback{ .function = .create(function, globalThis), }; @@ -94,9 +94,9 @@ pub const InternalJSEventCallback = struct { return this.function.has(); } - pub fn trigger(this: *InternalJSEventCallback, eventType: EventType, globalThis: *JSC.JSGlobalObject) bool { + pub fn trigger(this: *InternalJSEventCallback, eventType: EventType, globalThis: *jsc.JSGlobalObject) bool { if (this.function.get()) |callback| { - _ = callback.call(globalThis, .js_undefined, &.{JSC.JSValue.jsNumber( + _ = callback.call(globalThis, .js_undefined, &.{jsc.JSValue.jsNumber( @intFromEnum(eventType), )}) catch |err| globalThis.reportActiveExceptionAsUnhandled(err); return true; @@ -157,9 +157,9 @@ pub fn estimatedSize(this: *Request) callconv(.C) usize { return this.reported_estimated_size; } -pub fn getRemoteSocketInfo(this: *Request, globalObject: *JSC.JSGlobalObject) ?JSC.JSValue { +pub fn getRemoteSocketInfo(this: *Request, globalObject: *jsc.JSGlobalObject) ?jsc.JSValue { if (this.request_context.getRemoteSocketInfo()) |info| { - return JSC.JSSocketAddress.create(globalObject, info.ip, info.port, info.is_ipv6); + return jsc.JSSocketAddress.create(globalObject, info.ip, info.port, info.is_ipv6); } return null; @@ -272,31 +272,31 @@ pub fn mimeType(this: *const Request) string { pub fn getCache( _: *Request, - globalThis: *JSC.JSGlobalObject, -) JSC.JSValue { + globalThis: *jsc.JSGlobalObject, +) jsc.JSValue { return ZigString.init("default").toJS(globalThis); } pub fn getCredentials( _: *Request, - globalThis: *JSC.JSGlobalObject, -) JSC.JSValue { + globalThis: *jsc.JSGlobalObject, +) jsc.JSValue { return ZigString.init("include").toJS(globalThis); } pub fn getDestination( _: *Request, - globalThis: *JSC.JSGlobalObject, -) JSC.JSValue { + globalThis: *jsc.JSGlobalObject, +) jsc.JSValue { return ZigString.init("").toJS(globalThis); } pub fn getIntegrity( _: *Request, - globalThis: *JSC.JSGlobalObject, -) JSC.JSValue { + globalThis: *jsc.JSGlobalObject, +) jsc.JSValue { return ZigString.Empty.toJS(globalThis); } -pub fn getSignal(this: *Request, globalThis: *JSC.JSGlobalObject) JSC.JSValue { +pub fn getSignal(this: *Request, globalThis: *jsc.JSGlobalObject) jsc.JSValue { // Already have an C++ instance if (this.signal) |signal| { return signal.toJS(globalThis); @@ -313,15 +313,15 @@ pub fn getSignal(this: *Request, globalThis: *JSC.JSGlobalObject) JSC.JSValue { pub fn getMethod( this: *Request, - globalThis: *JSC.JSGlobalObject, -) JSC.JSValue { + globalThis: *jsc.JSGlobalObject, +) jsc.JSValue { return this.method.toJS(globalThis); } pub fn getMode( _: *Request, - globalThis: *JSC.JSGlobalObject, -) JSC.JSValue { + globalThis: *jsc.JSGlobalObject, +) jsc.JSValue { return ZigString.init("navigate").toJS(globalThis); } @@ -351,16 +351,16 @@ pub fn finalize(this: *Request) void { pub fn getRedirect( this: *Request, - globalThis: *JSC.JSGlobalObject, -) JSC.JSValue { + globalThis: *jsc.JSGlobalObject, +) jsc.JSValue { return switch (this.redirect) { inline else => |tag| ZigString.static(@tagName(tag)).toJS(globalThis), }; } pub fn getReferrer( this: *Request, - globalObject: *JSC.JSGlobalObject, -) JSC.JSValue { + globalObject: *jsc.JSGlobalObject, +) jsc.JSValue { if (this._headers) |headers_ref| { if (headers_ref.get("referrer", globalObject)) |referrer| { return ZigString.init(referrer).toJS(globalObject); @@ -371,11 +371,11 @@ pub fn getReferrer( } pub fn getReferrerPolicy( _: *Request, - globalThis: *JSC.JSGlobalObject, -) JSC.JSValue { + globalThis: *jsc.JSGlobalObject, +) jsc.JSValue { return ZigString.init("").toJS(globalThis); } -pub fn getUrl(this: *Request, globalObject: *JSC.JSGlobalObject) bun.JSError!JSC.JSValue { +pub fn getUrl(this: *Request, globalObject: *jsc.JSGlobalObject) bun.JSError!jsc.JSValue { try this.ensureURL(); return this.url.toJS(globalObject); } @@ -441,7 +441,7 @@ pub fn ensureURL(this: *Request) bun.OOM!void { bun.assert(this.sizeOfURL() == url.len); } - var href = bun.JSC.URL.hrefFromString(bun.String.fromBytes(url)); + var href = bun.jsc.URL.hrefFromString(bun.String.fromBytes(url)); if (!href.isEmpty()) { if (href.byteSlice().ptr == url.ptr) { this.url = bun.String.cloneLatin1(url[0..href.length()]); @@ -477,7 +477,7 @@ pub fn ensureURL(this: *Request) bun.OOM!void { this.url = bun.String.cloneUTF8(temp_url); } - const href = bun.JSC.URL.hrefFromString(this.url); + const href = bun.jsc.URL.hrefFromString(this.url); // TODO: what is the right thing to do for invalid URLS? if (!href.isEmpty()) { this.url.deref(); @@ -512,7 +512,7 @@ const Fields = enum { url, }; -pub fn constructInto(globalThis: *JSC.JSGlobalObject, arguments: []const JSC.JSValue) bun.JSError!Request { +pub fn constructInto(globalThis: *jsc.JSGlobalObject, arguments: []const jsc.JSValue) bun.JSError!Request { var success = false; const vm = globalThis.bunVM(); const body = try vm.initRequestBodyValue(.{ .Null = {} }); @@ -543,7 +543,7 @@ pub fn constructInto(globalThis: *JSC.JSGlobalObject, arguments: []const JSC.JSV // fastest path: url_or_object_type.isStringLike() or // slower path: - url_or_object.as(JSC.DOMURL) != null; + url_or_object.as(jsc.DOMURL) != null; if (is_first_argument_a_url) { const str = try bun.String.fromJS(arguments[0], globalThis); @@ -732,7 +732,7 @@ pub fn constructInto(globalThis: *JSC.JSGlobalObject, arguments: []const JSC.JSV return globalThis.throw("Failed to construct 'Request': url is required.", .{}); } - const href = JSC.URL.hrefFromString(req.url); + const href = jsc.URL.hrefFromString(req.url); if (href.isEmpty()) { if (!globalThis.hasException()) { // globalThis.throw can cause GC, which could cause the above string to be freed. @@ -765,7 +765,7 @@ pub fn constructInto(globalThis: *JSC.JSGlobalObject, arguments: []const JSC.JSV return req; } -pub fn constructor(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!*Request { +pub fn constructor(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!*Request { const arguments_ = callframe.arguments_old(2); const arguments = arguments_.ptr[0..arguments_.len]; @@ -781,9 +781,9 @@ pub fn getBodyValue( pub fn doClone( this: *Request, - globalThis: *JSC.JSGlobalObject, - callframe: *JSC.CallFrame, -) bun.JSError!JSC.JSValue { + globalThis: *jsc.JSGlobalObject, + callframe: *jsc.CallFrame, +) bun.JSError!jsc.JSValue { const this_value = callframe.this(); const cloned = try this.clone(bun.default_allocator, globalThis); @@ -829,7 +829,7 @@ pub fn setFetchHeaders( /// If the headers are empty and request_context is null, it will create an empty FetchHeaders object. pub fn ensureFetchHeaders( this: *Request, - globalThis: *JSC.JSGlobalObject, + globalThis: *jsc.JSGlobalObject, ) bun.JSError!*FetchHeaders { if (this._headers) |headers| { // headers is already set @@ -888,8 +888,8 @@ pub fn getFetchHeaders( /// This should only be called by the JS code. use getFetchHeaders to get the current headers or ensureFetchHeaders to get the headers and create them if they don't exist. pub fn getHeaders( this: *Request, - globalThis: *JSC.JSGlobalObject, -) bun.JSError!JSC.JSValue { + globalThis: *jsc.JSGlobalObject, +) bun.JSError!jsc.JSValue { return (try this.ensureFetchHeaders(globalThis)).toJS(globalThis); } @@ -956,6 +956,8 @@ pub fn setTimeout( _ = this.request_context.setTimeout(seconds); } +const string = []const u8; + const Environment = @import("../../env.zig"); const std = @import("std"); const FetchRedirect = @import("../../http/FetchRedirect.zig").FetchRedirect; @@ -964,23 +966,22 @@ const Method = @import("../../http/Method.zig").Method; const bun = @import("bun"); const Output = bun.Output; const default_allocator = bun.default_allocator; -const string = bun.string; const strings = bun.strings; const uws = bun.uws; const FetchHeaders = bun.webcore.FetchHeaders; const MimeType = bun.http.MimeType; -const JSC = bun.JSC; -const JSGlobalObject = JSC.JSGlobalObject; -const JSValue = JSC.JSValue; -const ZigString = JSC.ZigString; +const jsc = bun.jsc; +const JSGlobalObject = jsc.JSGlobalObject; +const JSValue = jsc.JSValue; +const ZigString = jsc.ZigString; -const AbortSignal = JSC.WebCore.AbortSignal; -const Response = JSC.WebCore.Response; +const AbortSignal = jsc.WebCore.AbortSignal; +const Response = jsc.WebCore.Response; -const Blob = JSC.WebCore.Blob; -const InlineBlob = JSC.WebCore.Blob.Inline; -const InternalBlob = JSC.WebCore.Blob.Internal; +const Blob = jsc.WebCore.Blob; +const InlineBlob = jsc.WebCore.Blob.Inline; +const InternalBlob = jsc.WebCore.Blob.Internal; -const Body = JSC.WebCore.Body; -const BodyMixin = JSC.WebCore.Body.Mixin; +const Body = jsc.WebCore.Body; +const BodyMixin = jsc.WebCore.Body.Mixin; diff --git a/src/bun.js/webcore/Response.zig b/src/bun.js/webcore/Response.zig index efb31584fb..83b9013e65 100644 --- a/src/bun.js/webcore/Response.zig +++ b/src/bun.js/webcore/Response.zig @@ -1,7 +1,7 @@ const Response = @This(); const ResponseMixin = BodyMixin(@This()); -pub const js = JSC.Codegen.JSResponse; +pub const js = jsc.Codegen.JSResponse; // NOTE: toJS is overridden pub const fromJS = js.fromJS; pub const fromJSDirect = js.fromJSDirect; @@ -56,7 +56,7 @@ pub fn getBodyValue( return &this.body.value; } -pub export fn jsFunctionRequestOrResponseHasBodyValue(globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) callconv(JSC.conv) JSC.JSValue { +pub export fn jsFunctionRequestOrResponseHasBodyValue(globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) callconv(jsc.conv) jsc.JSValue { _ = globalObject; // autofix const arguments = callframe.arguments_old(1); const this_value = arguments.ptr[0]; @@ -65,15 +65,15 @@ pub export fn jsFunctionRequestOrResponseHasBodyValue(globalObject: *JSC.JSGloba } if (this_value.as(Response)) |response| { - return JSC.JSValue.jsBoolean(!response.body.value.isDefinitelyEmpty()); + return jsc.JSValue.jsBoolean(!response.body.value.isDefinitelyEmpty()); } else if (this_value.as(Request)) |request| { - return JSC.JSValue.jsBoolean(!request.body.value.isDefinitelyEmpty()); + return jsc.JSValue.jsBoolean(!request.body.value.isDefinitelyEmpty()); } return .false; } -pub export fn jsFunctionGetCompleteRequestOrResponseBodyValueAsArrayBuffer(globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) callconv(JSC.conv) JSC.JSValue { +pub export fn jsFunctionGetCompleteRequestOrResponseBodyValueAsArrayBuffer(globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) callconv(jsc.conv) jsc.JSValue { const arguments = callframe.arguments_old(1); const this_value = arguments.ptr[0]; if (this_value.isEmptyOrUndefinedOrNull()) { @@ -141,7 +141,7 @@ pub fn writeFormat(this: *Response, comptime Formatter: type, formatter: *Format try formatter.writeIndent(Writer, writer); try writer.writeAll(comptime Output.prettyFmt("ok: ", enable_ansi_colors)); - try formatter.printAs(.Boolean, Writer, writer, JSC.JSValue.jsBoolean(this.isOK()), .BooleanObject, enable_ansi_colors); + try formatter.printAs(.Boolean, Writer, writer, jsc.JSValue.jsBoolean(this.isOK()), .BooleanObject, enable_ansi_colors); formatter.printComma(Writer, writer, enable_ansi_colors) catch bun.outOfMemory(); try writer.writeAll("\n"); @@ -154,7 +154,7 @@ pub fn writeFormat(this: *Response, comptime Formatter: type, formatter: *Format try formatter.writeIndent(Writer, writer); try writer.writeAll(comptime Output.prettyFmt("status: ", enable_ansi_colors)); - try formatter.printAs(.Double, Writer, writer, JSC.JSValue.jsNumber(this.init.status_code), .NumberObject, enable_ansi_colors); + try formatter.printAs(.Double, Writer, writer, jsc.JSValue.jsNumber(this.init.status_code), .NumberObject, enable_ansi_colors); formatter.printComma(Writer, writer, enable_ansi_colors) catch bun.outOfMemory(); try writer.writeAll("\n"); @@ -172,7 +172,7 @@ pub fn writeFormat(this: *Response, comptime Formatter: type, formatter: *Format try formatter.writeIndent(Writer, writer); try writer.writeAll(comptime Output.prettyFmt("redirected: ", enable_ansi_colors)); - try formatter.printAs(.Boolean, Writer, writer, JSC.JSValue.jsBoolean(this.redirected), .BooleanObject, enable_ansi_colors); + try formatter.printAs(.Boolean, Writer, writer, jsc.JSValue.jsBoolean(this.redirected), .BooleanObject, enable_ansi_colors); formatter.printComma(Writer, writer, enable_ansi_colors) catch bun.outOfMemory(); try writer.writeAll("\n"); @@ -191,16 +191,16 @@ pub fn isOK(this: *const Response) bool { pub fn getURL( this: *Response, - globalThis: *JSC.JSGlobalObject, -) JSC.JSValue { + globalThis: *jsc.JSGlobalObject, +) jsc.JSValue { // https://developer.mozilla.org/en-US/docs/Web/API/Response/url return this.url.toJS(globalThis); } pub fn getResponseType( this: *Response, - globalThis: *JSC.JSGlobalObject, -) JSC.JSValue { + globalThis: *jsc.JSGlobalObject, +) jsc.JSValue { if (this.init.status_code < 200) { return bun.String.static("error").toJS(globalThis); } @@ -210,29 +210,29 @@ pub fn getResponseType( pub fn getStatusText( this: *Response, - globalThis: *JSC.JSGlobalObject, -) JSC.JSValue { + globalThis: *jsc.JSGlobalObject, +) jsc.JSValue { // https://developer.mozilla.org/en-US/docs/Web/API/Response/statusText return this.init.status_text.toJS(globalThis); } pub fn getRedirected( this: *Response, - _: *JSC.JSGlobalObject, -) JSC.JSValue { + _: *jsc.JSGlobalObject, +) jsc.JSValue { // https://developer.mozilla.org/en-US/docs/Web/API/Response/redirected return JSValue.jsBoolean(this.redirected); } pub fn getOK( this: *Response, - _: *JSC.JSGlobalObject, -) JSC.JSValue { + _: *jsc.JSGlobalObject, +) jsc.JSValue { // https://developer.mozilla.org/en-US/docs/Web/API/Response/ok return JSValue.jsBoolean(this.isOK()); } -fn getOrCreateHeaders(this: *Response, globalThis: *JSC.JSGlobalObject) bun.JSError!*FetchHeaders { +fn getOrCreateHeaders(this: *Response, globalThis: *jsc.JSGlobalObject) bun.JSError!*FetchHeaders { if (this.init.headers == null) { this.init.headers = FetchHeaders.createEmpty(); @@ -249,15 +249,15 @@ fn getOrCreateHeaders(this: *Response, globalThis: *JSC.JSGlobalObject) bun.JSEr pub fn getHeaders( this: *Response, - globalThis: *JSC.JSGlobalObject, -) bun.JSError!JSC.JSValue { + globalThis: *jsc.JSGlobalObject, +) bun.JSError!jsc.JSValue { return (try this.getOrCreateHeaders(globalThis)).toJS(globalThis); } pub fn doClone( this: *Response, - globalThis: *JSC.JSGlobalObject, - callframe: *JSC.CallFrame, + globalThis: *jsc.JSGlobalObject, + callframe: *jsc.CallFrame, ) bun.JSError!JSValue { const this_value = callframe.this(); const cloned = try this.clone(globalThis); @@ -282,7 +282,7 @@ pub fn doClone( return js_wrapper; } -pub fn makeMaybePooled(globalObject: *JSC.JSGlobalObject, ptr: *Response) JSValue { +pub fn makeMaybePooled(globalObject: *jsc.JSGlobalObject, ptr: *Response) JSValue { return ptr.toJS(globalObject); } @@ -308,8 +308,8 @@ pub fn clone(this: *Response, globalThis: *JSGlobalObject) bun.JSError!*Response pub fn getStatus( this: *Response, - _: *JSC.JSGlobalObject, -) JSC.JSValue { + _: *jsc.JSGlobalObject, +) jsc.JSValue { // https://developer.mozilla.org/en-US/docs/Web/API/Response/status return JSValue.jsNumber(this.init.status_code); } @@ -359,12 +359,12 @@ pub fn getContentType( } pub fn constructJSON( - globalThis: *JSC.JSGlobalObject, - callframe: *JSC.CallFrame, + globalThis: *jsc.JSGlobalObject, + callframe: *jsc.CallFrame, ) bun.JSError!JSValue { const args_list = callframe.arguments_old(2); // https://github.com/remix-run/remix/blob/db2c31f64affb2095e4286b91306b96435967969/packages/remix-server-runtime/responses.ts#L4 - var args = JSC.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), args_list.ptr[0..args_list.len]); + var args = jsc.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), args_list.ptr[0..args_list.len]); var response = Response{ .body = Body{ @@ -382,7 +382,7 @@ pub fn constructJSON( response.init.deinit(bun.default_allocator); } } - const json_value = args.nextEat() orelse JSC.JSValue.zero; + const json_value = args.nextEat() orelse jsc.JSValue.zero; if (@intFromEnum(json_value) != 0) { var str = bun.String.empty; @@ -427,12 +427,12 @@ pub fn constructJSON( return bun.new(Response, response).toJS(globalThis); } pub fn constructRedirect( - globalThis: *JSC.JSGlobalObject, - callframe: *JSC.CallFrame, + globalThis: *jsc.JSGlobalObject, + callframe: *jsc.CallFrame, ) bun.JSError!JSValue { var args_list = callframe.arguments_old(4); // https://github.com/remix-run/remix/blob/db2c31f64affb2095e4286b91306b96435967969/packages/remix-server-runtime/responses.ts#L4 - var args = JSC.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), args_list.ptr[0..args_list.len]); + var args = jsc.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), args_list.ptr[0..args_list.len]); var url_string_slice = ZigString.Slice.empty; defer url_string_slice.deinit(); @@ -447,7 +447,7 @@ pub fn constructRedirect( .url = bun.String.empty, }; - const url_string_value = args.nextEat() orelse JSC.JSValue.zero; + const url_string_value = args.nextEat() orelse jsc.JSValue.zero; var url_string = ZigString.init(""); if (@intFromEnum(url_string_value) != 0) { @@ -489,8 +489,8 @@ pub fn constructRedirect( return ptr.toJS(globalThis); } pub fn constructError( - globalThis: *JSC.JSGlobalObject, - _: *JSC.CallFrame, + globalThis: *jsc.JSGlobalObject, + _: *jsc.CallFrame, ) bun.JSError!JSValue { const response = bun.new( Response, @@ -507,7 +507,7 @@ pub fn constructError( return response.toJS(globalThis); } -pub fn constructor(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!*Response { +pub fn constructor(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!*Response { const arguments = callframe.argumentsAsArray(2); if (!arguments[0].isUndefinedOrNull() and arguments[0].isObject()) { @@ -613,7 +613,7 @@ pub const Init = struct { return that; } - pub fn init(globalThis: *JSGlobalObject, response_init: JSC.JSValue) bun.JSError!?Init { + pub fn init(globalThis: *JSGlobalObject, response_init: jsc.JSValue) bun.JSError!?Init { var result = Init{ .status_code = 200 }; errdefer { result.deinit(bun.default_allocator); @@ -699,15 +699,15 @@ pub const Init = struct { } }; -pub fn @"404"(globalThis: *JSC.JSGlobalObject) Response { +pub fn @"404"(globalThis: *jsc.JSGlobalObject) Response { return emptyWithStatus(globalThis, 404); } -pub fn @"200"(globalThis: *JSC.JSGlobalObject) Response { +pub fn @"200"(globalThis: *jsc.JSGlobalObject) Response { return emptyWithStatus(globalThis, 200); } -inline fn emptyWithStatus(_: *JSC.JSGlobalObject, status: u16) Response { +inline fn emptyWithStatus(_: *jsc.JSGlobalObject, status: u16) Response { return bun.new(Response, .{ .body = Body{ .value = Body.Value{ .Null = {} }, @@ -719,7 +719,9 @@ inline fn emptyWithStatus(_: *JSC.JSGlobalObject, status: u16) Response { } /// https://developer.mozilla.org/en-US/docs/Web/API/Headers -// TODO: move to http.zig. this has nothing to do with JSC or WebCore +// TODO: move to http.zig. this has nothing to do with jsc or WebCore + +const string = []const u8; const std = @import("std"); const Method = @import("../../http/Method.zig").Method; @@ -728,20 +730,19 @@ const bun = @import("bun"); const Output = bun.Output; const default_allocator = bun.default_allocator; const s3 = bun.S3; -const string = bun.string; const FetchHeaders = bun.webcore.FetchHeaders; -const JSC = bun.JSC; -const JSGlobalObject = JSC.JSGlobalObject; -const JSValue = JSC.JSValue; -const ZigString = JSC.ZigString; -const Request = JSC.WebCore.Request; - -const Blob = JSC.WebCore.Blob; -const InternalBlob = JSC.WebCore.Blob.Internal; - -const Body = JSC.WebCore.Body; -const BodyMixin = JSC.WebCore.Body.Mixin; - const http = bun.http; const MimeType = bun.http.MimeType; + +const jsc = bun.jsc; +const JSGlobalObject = jsc.JSGlobalObject; +const JSValue = jsc.JSValue; +const ZigString = jsc.ZigString; +const Request = jsc.WebCore.Request; + +const Blob = jsc.WebCore.Blob; +const InternalBlob = jsc.WebCore.Blob.Internal; + +const Body = jsc.WebCore.Body; +const BodyMixin = jsc.WebCore.Body.Mixin; diff --git a/src/bun.js/webcore/ResumableSink.zig b/src/bun.js/webcore/ResumableSink.zig index 9d604333b1..a5fe0e3339 100644 --- a/src/bun.js/webcore/ResumableSink.zig +++ b/src/bun.js/webcore/ResumableSink.zig @@ -7,7 +7,7 @@ pub fn ResumableSink( comptime js: type, comptime Context: type, comptime onWrite: fn (context: *Context, chunk: []const u8) bool, - comptime onEnd: fn (context: *Context, err: ?JSC.JSValue) void, + comptime onEnd: fn (context: *Context, err: ?jsc.JSValue) void, ) type { return struct { const log = bun.Output.scoped(.ResumableSink, false); @@ -26,10 +26,10 @@ pub fn ResumableSink( const setStream = js.streamSetCached; const getStream = js.streamGetCached; ref_count: RefCount, - self: JSC.Strong.Optional = JSC.Strong.Optional.empty, + self: jsc.Strong.Optional = jsc.Strong.Optional.empty, // We can have a detached self, and still have a strong reference to the stream - stream: JSC.WebCore.ReadableStream.Strong = .{}, - globalThis: *JSC.JSGlobalObject, + stream: jsc.WebCore.ReadableStream.Strong = .{}, + globalThis: *jsc.JSGlobalObject, context: *Context, highWaterMark: i64 = 16384, status: Status = .started, @@ -41,23 +41,23 @@ pub fn ResumableSink( done, }; - pub fn constructor(globalThis: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!*@This() { + pub fn constructor(globalThis: *jsc.JSGlobalObject, _: *jsc.CallFrame) bun.JSError!*@This() { return globalThis.throwInvalidArguments("ResumableSink is not constructable", .{}); } - pub fn init(globalThis: *JSC.JSGlobalObject, stream: JSC.WebCore.ReadableStream, context: *Context) *@This() { + pub fn init(globalThis: *jsc.JSGlobalObject, stream: jsc.WebCore.ReadableStream, context: *Context) *@This() { return initExactRefs(globalThis, stream, context, 1); } - pub fn initExactRefs(globalThis: *JSC.JSGlobalObject, stream: JSC.WebCore.ReadableStream, context: *Context, ref_count: u32) *@This() { + pub fn initExactRefs(globalThis: *jsc.JSGlobalObject, stream: jsc.WebCore.ReadableStream, context: *Context, ref_count: u32) *@This() { const this = @This().new(.{ .globalThis = globalThis, .context = context, .ref_count = RefCount.initExactRefs(ref_count), }); if (stream.isLocked(globalThis) or stream.isDisturbed(globalThis)) { - var err = JSC.SystemError{ - .code = bun.String.static(@tagName(JSC.Node.ErrorCode.ERR_STREAM_CANNOT_PIPE)), + var err = jsc.SystemError{ + .code = bun.String.static(@tagName(jsc.Node.ErrorCode.ERR_STREAM_CANNOT_PIPE)), .message = bun.String.static("Stream already used, please create a new one"), }; const err_instance = err.toErrorInstance(globalThis); @@ -110,11 +110,11 @@ pub fn ResumableSink( _ = onWrite(this.context, bytes.items); } this.status = .piped; - byte_stream.pipe = JSC.WebCore.Pipe.Wrap(@This(), onStreamPipe).init(this); + byte_stream.pipe = jsc.WebCore.Pipe.Wrap(@This(), onStreamPipe).init(this); this.ref(); // one ref for the pipe // we only need the stream, we dont need to touch JS side yet - this.stream = JSC.WebCore.ReadableStream.Strong.init(stream, this.globalThis); + this.stream = jsc.WebCore.ReadableStream.Strong.init(stream, this.globalThis); return this; } } @@ -124,13 +124,13 @@ pub fn ResumableSink( const js_stream = stream.toJS(); js_stream.ensureStillAlive(); _ = Bun__assignStreamIntoResumableSink(globalThis, js_stream, self); - this.self = JSC.Strong.Optional.create(self, globalThis); + this.self = jsc.Strong.Optional.create(self, globalThis); setStream(self, globalThis, js_stream); return this; } - pub fn jsSetHandlers(_: *@This(), globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame, this_value: JSC.JSValue) bun.JSError!JSC.JSValue { - JSC.markBinding(@src()); + pub fn jsSetHandlers(_: *@This(), globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame, this_value: jsc.JSValue) bun.JSError!jsc.JSValue { + jsc.markBinding(@src()); const args = callframe.arguments(); if (args.len < 2) { @@ -149,8 +149,8 @@ pub fn ResumableSink( return .js_undefined; } - pub fn jsStart(this: *@This(), globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { - JSC.markBinding(@src()); + pub fn jsStart(this: *@This(), globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { + jsc.markBinding(@src()); const args = callframe.arguments(); if (args.len > 0 and args[0].isObject()) { if (try args[0].getOptionalInt(globalThis, "highWaterMark", i64)) |highWaterMark| { @@ -161,8 +161,8 @@ pub fn ResumableSink( return .js_undefined; } - pub fn jsWrite(this: *@This(), globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { - JSC.markBinding(@src()); + pub fn jsWrite(this: *@This(), globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { + jsc.markBinding(@src()); const args = callframe.arguments(); // ignore any call if detached if (!this.self.has() or this.status == .done) return .js_undefined; @@ -173,7 +173,7 @@ pub fn ResumableSink( const buffer = args[0]; buffer.ensureStillAlive(); - if (try JSC.Node.StringOrBuffer.fromJS(globalThis, bun.default_allocator, buffer)) |sb| { + if (try jsc.Node.StringOrBuffer.fromJS(globalThis, bun.default_allocator, buffer)) |sb| { defer sb.deinit(); const bytes = sb.slice(); log("jsWrite {}", .{bytes.len}); @@ -182,14 +182,14 @@ pub fn ResumableSink( log("paused", .{}); this.status = .paused; } - return JSC.jsBoolean(should_continue); + return jsc.jsBoolean(should_continue); } return globalThis.throwInvalidArguments("ResumableSink.write requires a string or buffer", .{}); } - pub fn jsEnd(this: *@This(), _: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { - JSC.markBinding(@src()); + pub fn jsEnd(this: *@This(), _: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { + jsc.markBinding(@src()); const args = callframe.arguments(); // ignore any call if detached if (!this.self.has() or this.status == .done) return .js_undefined; @@ -224,7 +224,7 @@ pub fn ResumableSink( } } - pub fn cancel(this: *@This(), reason: JSC.JSValue) void { + pub fn cancel(this: *@This(), reason: jsc.JSValue) void { if (this.status == .piped) { reason.ensureStillAlive(); this.endPipe(reason); @@ -266,7 +266,7 @@ pub fn ResumableSink( setCancel(js_this, this.globalThis, .zero); setStream(js_this, this.globalThis, .zero); this.self.deinit(); - this.self = JSC.Strong.Optional.empty; + this.self = jsc.Strong.Optional.empty; } } pub fn deinit(this: *@This()) void { @@ -301,7 +301,7 @@ pub fn ResumableSink( const is_done = stream.isDone(); if (is_done) { - const err: ?JSC.JSValue = brk_err: { + const err: ?jsc.JSValue = brk_err: { if (stream == .err) { const js_err, const was_strong = stream.err.toJSWeak(this.globalThis); js_err.ensureStillAlive(); @@ -318,7 +318,7 @@ pub fn ResumableSink( } } - fn endPipe(this: *@This(), err: ?JSC.JSValue) void { + fn endPipe(this: *@This(), err: ?jsc.JSValue) void { log("endPipe", .{}); if (this.status != .piped) return; this.status = .done; @@ -351,14 +351,14 @@ pub fn ResumableSink( }; } -pub const ResumableFetchSink = ResumableSink(JSC.Codegen.JSResumableFetchSink, FetchTasklet, FetchTasklet.writeRequestData, FetchTasklet.writeEndRequest); -pub const ResumableS3UploadSink = ResumableSink(JSC.Codegen.JSResumableS3UploadSink, S3UploadStreamWrapper, S3UploadStreamWrapper.writeRequestData, S3UploadStreamWrapper.writeEndRequest); +pub const ResumableFetchSink = ResumableSink(jsc.Codegen.JSResumableFetchSink, FetchTasklet, FetchTasklet.writeRequestData, FetchTasklet.writeEndRequest); +pub const ResumableS3UploadSink = ResumableSink(jsc.Codegen.JSResumableS3UploadSink, S3UploadStreamWrapper, S3UploadStreamWrapper.writeRequestData, S3UploadStreamWrapper.writeEndRequest); -extern fn Bun__assignStreamIntoResumableSink(globalThis: *JSC.JSGlobalObject, stream: JSC.JSValue, sink: JSC.JSValue) JSC.JSValue; +extern fn Bun__assignStreamIntoResumableSink(globalThis: *jsc.JSGlobalObject, stream: jsc.JSValue, sink: jsc.JSValue) jsc.JSValue; const std = @import("std"); const FetchTasklet = @import("./fetch.zig").FetchTasklet; const S3UploadStreamWrapper = @import("../../s3/client.zig").S3UploadStreamWrapper; const bun = @import("bun"); -const JSC = bun.JSC; +const jsc = bun.jsc; diff --git a/src/bun.js/webcore/S3Client.zig b/src/bun.js/webcore/S3Client.zig index fb7e1e1a22..5502ae7472 100644 --- a/src/bun.js/webcore/S3Client.zig +++ b/src/bun.js/webcore/S3Client.zig @@ -58,27 +58,27 @@ pub fn writeFormatCredentials(credentials: *S3Credentials, options: bun.S3.Multi try formatter.writeIndent(Writer, writer); try writer.writeAll(comptime bun.Output.prettyFmt("partSize: ", enable_ansi_colors)); - try formatter.printAs(.Double, Writer, writer, JSC.JSValue.jsNumber(options.partSize), .NumberObject, enable_ansi_colors); + try formatter.printAs(.Double, Writer, writer, jsc.JSValue.jsNumber(options.partSize), .NumberObject, enable_ansi_colors); formatter.printComma(Writer, writer, enable_ansi_colors) catch bun.outOfMemory(); try writer.writeAll("\n"); try formatter.writeIndent(Writer, writer); try writer.writeAll(comptime bun.Output.prettyFmt("queueSize: ", enable_ansi_colors)); - try formatter.printAs(.Double, Writer, writer, JSC.JSValue.jsNumber(options.queueSize), .NumberObject, enable_ansi_colors); + try formatter.printAs(.Double, Writer, writer, jsc.JSValue.jsNumber(options.queueSize), .NumberObject, enable_ansi_colors); formatter.printComma(Writer, writer, enable_ansi_colors) catch bun.outOfMemory(); try writer.writeAll("\n"); try formatter.writeIndent(Writer, writer); try writer.writeAll(comptime bun.Output.prettyFmt("retry: ", enable_ansi_colors)); - try formatter.printAs(.Double, Writer, writer, JSC.JSValue.jsNumber(options.retry), .NumberObject, enable_ansi_colors); + try formatter.printAs(.Double, Writer, writer, jsc.JSValue.jsNumber(options.retry), .NumberObject, enable_ansi_colors); try writer.writeAll("\n"); } } pub const S3Client = struct { const log = bun.Output.scoped(.S3Client, false); - pub const js = JSC.Codegen.JSS3Client; + pub const js = jsc.Codegen.JSS3Client; pub const toJS = js.toJS; pub const fromJS = js.fromJS; pub const fromJSDirect = js.fromJSDirect; @@ -89,9 +89,9 @@ pub const S3Client = struct { acl: ?bun.S3.ACL = null, storage_class: ?bun.S3.StorageClass = null, - pub fn constructor(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!*@This() { + pub fn constructor(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!*@This() { const arguments = callframe.arguments_old(1).slice(); - var args = JSC.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), arguments); + var args = jsc.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), arguments); defer args.deinit(); var aws_options = try S3Credentials.getCredentialsWithOptions(globalThis.bunVM().transpiler.env.getS3Credentials(), .{}, args.nextEat(), null, null, globalThis); defer aws_options.deinit(); @@ -123,11 +123,11 @@ pub const S3Client = struct { try writer.writeAll("}"); formatter.resetLine(); } - pub fn file(ptr: *@This(), globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { + pub fn file(ptr: *@This(), globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { const arguments = callframe.arguments_old(2).slice(); - var args = JSC.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), arguments); + var args = jsc.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), arguments); defer args.deinit(); - const path: JSC.Node.PathLike = try JSC.Node.PathLike.fromJS(globalThis, &args) orelse { + const path: jsc.Node.PathLike = try jsc.Node.PathLike.fromJS(globalThis, &args) orelse { if (args.len() == 0) { return globalThis.ERR(.MISSING_ARGS, "Expected a path ", .{}).throw(); } @@ -140,11 +140,11 @@ pub const S3Client = struct { return blob.toJS(globalThis); } - pub fn presign(ptr: *@This(), globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { + pub fn presign(ptr: *@This(), globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { const arguments = callframe.arguments_old(2).slice(); - var args = JSC.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), arguments); + var args = jsc.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), arguments); defer args.deinit(); - const path: JSC.Node.PathLike = try JSC.Node.PathLike.fromJS(globalThis, &args) orelse { + const path: jsc.Node.PathLike = try jsc.Node.PathLike.fromJS(globalThis, &args) orelse { if (args.len() == 0) { return globalThis.ERR(.MISSING_ARGS, "Expected a path to presign", .{}).throw(); } @@ -158,11 +158,11 @@ pub const S3Client = struct { return S3File.getPresignUrlFrom(&blob, globalThis, options); } - pub fn exists(ptr: *@This(), globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { + pub fn exists(ptr: *@This(), globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { const arguments = callframe.arguments_old(2).slice(); - var args = JSC.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), arguments); + var args = jsc.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), arguments); defer args.deinit(); - const path: JSC.Node.PathLike = try JSC.Node.PathLike.fromJS(globalThis, &args) orelse { + const path: jsc.Node.PathLike = try jsc.Node.PathLike.fromJS(globalThis, &args) orelse { if (args.len() == 0) { return globalThis.ERR(.MISSING_ARGS, "Expected a path to check if it exists", .{}).throw(); } @@ -175,11 +175,11 @@ pub const S3Client = struct { return S3File.S3BlobStatTask.exists(globalThis, &blob); } - pub fn size(ptr: *@This(), globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { + pub fn size(ptr: *@This(), globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { const arguments = callframe.arguments_old(2).slice(); - var args = JSC.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), arguments); + var args = jsc.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), arguments); defer args.deinit(); - const path: JSC.Node.PathLike = try JSC.Node.PathLike.fromJS(globalThis, &args) orelse { + const path: jsc.Node.PathLike = try jsc.Node.PathLike.fromJS(globalThis, &args) orelse { if (args.len() == 0) { return globalThis.ERR(.MISSING_ARGS, "Expected a path to check the size of", .{}).throw(); } @@ -192,11 +192,11 @@ pub const S3Client = struct { return S3File.S3BlobStatTask.size(globalThis, &blob); } - pub fn stat(ptr: *@This(), globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { + pub fn stat(ptr: *@This(), globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { const arguments = callframe.arguments_old(2).slice(); - var args = JSC.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), arguments); + var args = jsc.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), arguments); defer args.deinit(); - const path: JSC.Node.PathLike = try JSC.Node.PathLike.fromJS(globalThis, &args) orelse { + const path: jsc.Node.PathLike = try jsc.Node.PathLike.fromJS(globalThis, &args) orelse { if (args.len() == 0) { return globalThis.ERR(.MISSING_ARGS, "Expected a path to check the stat of", .{}).throw(); } @@ -209,11 +209,11 @@ pub const S3Client = struct { return S3File.S3BlobStatTask.stat(globalThis, &blob); } - pub fn write(ptr: *@This(), globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { + pub fn write(ptr: *@This(), globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { const arguments = callframe.arguments_old(3).slice(); - var args = JSC.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), arguments); + var args = jsc.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), arguments); defer args.deinit(); - const path: JSC.Node.PathLike = try JSC.Node.PathLike.fromJS(globalThis, &args) orelse { + const path: jsc.Node.PathLike = try jsc.Node.PathLike.fromJS(globalThis, &args) orelse { return globalThis.ERR(.MISSING_ARGS, "Expected a path to write to", .{}).throw(); }; errdefer path.deinit(); @@ -231,7 +231,7 @@ pub const S3Client = struct { }); } - pub fn listObjects(ptr: *@This(), globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { + pub fn listObjects(ptr: *@This(), globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { const args = callframe.argumentsAsArray(2); const object_keys = args[0]; @@ -243,11 +243,11 @@ pub const S3Client = struct { return blob.store.?.data.s3.listObjects(blob.store.?, globalThis, object_keys, options); } - pub fn unlink(ptr: *@This(), globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { + pub fn unlink(ptr: *@This(), globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { const arguments = callframe.arguments_old(2).slice(); - var args = JSC.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), arguments); + var args = jsc.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), arguments); defer args.deinit(); - const path: JSC.Node.PathLike = try JSC.Node.PathLike.fromJS(globalThis, &args) orelse { + const path: jsc.Node.PathLike = try jsc.Node.PathLike.fromJS(globalThis, &args) orelse { return globalThis.ERR(.MISSING_ARGS, "Expected a path to unlink", .{}).throw(); }; errdefer path.deinit(); @@ -270,42 +270,42 @@ pub const S3Client = struct { // Static methods - pub fn staticWrite(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { + pub fn staticWrite(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { return S3File.write(globalThis, callframe); } - pub fn staticPresign(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { + pub fn staticPresign(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { return S3File.presign(globalThis, callframe); } - pub fn staticExists(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { + pub fn staticExists(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { return S3File.exists(globalThis, callframe); } - pub fn staticSize(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { + pub fn staticSize(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { return S3File.size(globalThis, callframe); } - pub fn staticUnlink(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { + pub fn staticUnlink(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { return S3File.unlink(globalThis, callframe); } - pub fn staticFile(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { + pub fn staticFile(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { const arguments = callframe.arguments_old(2).slice(); - var args = JSC.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), arguments); + var args = jsc.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), arguments); defer args.deinit(); - const path = (try JSC.Node.PathLike.fromJS(globalThis, &args)) orelse { + const path = (try jsc.Node.PathLike.fromJS(globalThis, &args)) orelse { return globalThis.throwInvalidArguments("Expected file path string", .{}); }; return try S3File.constructInternalJS(globalThis, path, args.nextEat()); } - pub fn staticStat(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { + pub fn staticStat(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { return S3File.stat(globalThis, callframe); } - pub fn staticListObjects(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { + pub fn staticListObjects(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { const args = callframe.argumentsAsArray(2); const object_keys = args[0]; const options = args[1]; @@ -321,10 +321,11 @@ pub const S3Client = struct { }; const S3File = @import("./S3File.zig"); + const bun = @import("bun"); const S3Credentials = bun.S3.S3Credentials; -const JSC = bun.JSC; -const JSValue = JSC.JSValue; -const Blob = JSC.WebCore.Blob; -const PathOrBlob = JSC.Node.PathOrBlob; +const jsc = bun.jsc; +const JSValue = jsc.JSValue; +const Blob = jsc.WebCore.Blob; +const PathOrBlob = jsc.Node.PathOrBlob; diff --git a/src/bun.js/webcore/S3File.zig b/src/bun.js/webcore/S3File.zig index 13cbfeade4..f2bab413a1 100644 --- a/src/bun.js/webcore/S3File.zig +++ b/src/bun.js/webcore/S3File.zig @@ -60,9 +60,9 @@ pub fn writeFormat(s3: *Blob.Store.S3, comptime Formatter: type, formatter: *For try writer.writeAll("}"); formatter.resetLine(); } -pub fn presign(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { +pub fn presign(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { const arguments = callframe.arguments_old(3).slice(); - var args = JSC.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), arguments); + var args = jsc.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), arguments); defer args.deinit(); // accept a path or a blob @@ -91,9 +91,9 @@ pub fn presign(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.J } } -pub fn unlink(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { +pub fn unlink(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { const arguments = callframe.arguments_old(3).slice(); - var args = JSC.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), arguments); + var args = jsc.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), arguments); defer args.deinit(); // accept a path or a blob @@ -123,9 +123,9 @@ pub fn unlink(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JS } } -pub fn write(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { +pub fn write(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { const arguments = callframe.arguments_old(3).slice(); - var args = JSC.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), arguments); + var args = jsc.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), arguments); defer args.deinit(); // accept a path or a blob @@ -166,9 +166,9 @@ pub fn write(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSE } } -pub fn size(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { +pub fn size(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { const arguments = callframe.arguments_old(3).slice(); - var args = JSC.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), arguments); + var args = jsc.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), arguments); defer args.deinit(); // accept a path or a blob @@ -199,9 +199,9 @@ pub fn size(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSEr }, } } -pub fn exists(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { +pub fn exists(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { const arguments = callframe.arguments_old(3).slice(); - var args = JSC.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), arguments); + var args = jsc.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), arguments); defer args.deinit(); // accept a path or a blob @@ -234,9 +234,9 @@ pub fn exists(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JS } fn constructS3FileInternalStore( - globalObject: *JSC.JSGlobalObject, - path: JSC.Node.PathLike, - options: ?JSC.JSValue, + globalObject: *jsc.JSGlobalObject, + path: jsc.Node.PathLike, + options: ?jsc.JSValue, ) bun.JSError!Blob { // get credentials from env const existing_credentials = globalObject.bunVM().transpiler.env.getS3Credentials(); @@ -244,9 +244,9 @@ fn constructS3FileInternalStore( } /// if the credentials have changed, we need to clone it, if not we can just ref/deref it pub fn constructS3FileWithS3CredentialsAndOptions( - globalObject: *JSC.JSGlobalObject, - path: JSC.Node.PathLike, - options: ?JSC.JSValue, + globalObject: *jsc.JSGlobalObject, + path: jsc.Node.PathLike, + options: ?jsc.JSValue, default_credentials: *S3.S3Credentials, default_options: bun.S3.MultiPartUploadOptions, default_acl: ?bun.S3.ACL, @@ -297,9 +297,9 @@ pub fn constructS3FileWithS3CredentialsAndOptions( } pub fn constructS3FileWithS3Credentials( - globalObject: *JSC.JSGlobalObject, - path: JSC.Node.PathLike, - options: ?JSC.JSValue, + globalObject: *jsc.JSGlobalObject, + path: jsc.Node.PathLike, + options: ?jsc.JSValue, existing_credentials: S3.S3Credentials, ) bun.JSError!Blob { var aws_options = try S3.S3Credentials.getCredentialsWithOptions(existing_credentials, .{}, options, null, null, globalObject); @@ -339,9 +339,9 @@ pub fn constructS3FileWithS3Credentials( return blob; } fn constructS3FileInternal( - globalObject: *JSC.JSGlobalObject, - path: JSC.Node.PathLike, - options: ?JSC.JSValue, + globalObject: *jsc.JSGlobalObject, + path: jsc.Node.PathLike, + options: ?jsc.JSValue, ) bun.JSError!*Blob { var ptr = Blob.new(try constructS3FileInternalStore(globalObject, path, options)); ptr.allocator = bun.default_allocator; @@ -349,8 +349,8 @@ fn constructS3FileInternal( } pub const S3BlobStatTask = struct { - promise: JSC.JSPromise.Strong, - global: *JSC.JSGlobalObject, + promise: jsc.JSPromise.Strong, + global: *jsc.JSGlobalObject, store: *Blob.Store, pub const new = bun.TrivialNew(S3BlobStatTask); @@ -407,9 +407,9 @@ pub const S3BlobStatTask = struct { } } - pub fn exists(globalThis: *JSC.JSGlobalObject, blob: *Blob) JSValue { + pub fn exists(globalThis: *jsc.JSGlobalObject, blob: *Blob) JSValue { const this = S3BlobStatTask.new(.{ - .promise = JSC.JSPromise.Strong.init(globalThis), + .promise = jsc.JSPromise.Strong.init(globalThis), .store = blob.store.?, .global = globalThis, }); @@ -422,9 +422,9 @@ pub const S3BlobStatTask = struct { S3.stat(credentials, path, @ptrCast(&S3BlobStatTask.onS3ExistsResolved), this, if (env.getHttpProxy(true, null)) |proxy| proxy.href else null); return promise; } - pub fn stat(globalThis: *JSC.JSGlobalObject, blob: *Blob) JSValue { + pub fn stat(globalThis: *jsc.JSGlobalObject, blob: *Blob) JSValue { const this = S3BlobStatTask.new(.{ - .promise = JSC.JSPromise.Strong.init(globalThis), + .promise = jsc.JSPromise.Strong.init(globalThis), .store = blob.store.?, .global = globalThis, }); @@ -437,9 +437,9 @@ pub const S3BlobStatTask = struct { S3.stat(credentials, path, @ptrCast(&S3BlobStatTask.onS3StatResolved), this, if (env.getHttpProxy(true, null)) |proxy| proxy.href else null); return promise; } - pub fn size(globalThis: *JSC.JSGlobalObject, blob: *Blob) JSValue { + pub fn size(globalThis: *jsc.JSGlobalObject, blob: *Blob) JSValue { const this = S3BlobStatTask.new(.{ - .promise = JSC.JSPromise.Strong.init(globalThis), + .promise = jsc.JSPromise.Strong.init(globalThis), .store = blob.store.?, .global = globalThis, }); @@ -460,7 +460,7 @@ pub const S3BlobStatTask = struct { } }; -pub fn getPresignUrlFrom(this: *Blob, globalThis: *JSC.JSGlobalObject, extra_options: ?JSValue) bun.JSError!JSValue { +pub fn getPresignUrlFrom(this: *Blob, globalThis: *jsc.JSGlobalObject, extra_options: ?JSValue) bun.JSError!JSValue { if (!this.isS3()) { return globalThis.ERR(.INVALID_THIS, "presign is only possible for s3:// files", .{}).throw(); } @@ -527,24 +527,24 @@ pub fn getBucketName( return bucket; } -pub fn getBucket(this: *Blob, globalThis: *JSC.JSGlobalObject) callconv(JSC.conv) JSValue { +pub fn getBucket(this: *Blob, globalThis: *jsc.JSGlobalObject) callconv(jsc.conv) JSValue { if (getBucketName(this)) |name| { return bun.String.createUTF8ForJS(globalThis, name) catch .zero; } return .js_undefined; } -pub fn getPresignUrl(this: *Blob, globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { +pub fn getPresignUrl(this: *Blob, globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { const args = callframe.arguments_old(1); return getPresignUrlFrom(this, globalThis, if (args.len > 0) args.ptr[0] else null); } -pub fn getStat(this: *Blob, globalThis: *JSC.JSGlobalObject, _: *JSC.CallFrame) callconv(JSC.conv) JSValue { +pub fn getStat(this: *Blob, globalThis: *jsc.JSGlobalObject, _: *jsc.CallFrame) callconv(jsc.conv) JSValue { return S3BlobStatTask.stat(globalThis, this); } -pub fn stat(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { +pub fn stat(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { const arguments = callframe.arguments_old(3).slice(); - var args = JSC.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), arguments); + var args = jsc.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), arguments); defer args.deinit(); // accept a path or a blob @@ -577,40 +577,40 @@ pub fn stat(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSEr } pub fn constructInternalJS( - globalObject: *JSC.JSGlobalObject, - path: JSC.Node.PathLike, - options: ?JSC.JSValue, + globalObject: *jsc.JSGlobalObject, + path: jsc.Node.PathLike, + options: ?jsc.JSValue, ) bun.JSError!JSValue { const blob = try constructS3FileInternal(globalObject, path, options); return blob.toJS(globalObject); } pub fn toJSUnchecked( - globalObject: *JSC.JSGlobalObject, + globalObject: *jsc.JSGlobalObject, this: *Blob, ) JSValue { return BUN__createJSS3FileUnsafely(globalObject, this); } pub fn constructInternal( - globalObject: *JSC.JSGlobalObject, - callframe: *JSC.CallFrame, + globalObject: *jsc.JSGlobalObject, + callframe: *jsc.CallFrame, ) bun.JSError!*Blob { const vm = globalObject.bunVM(); const arguments = callframe.arguments_old(2).slice(); - var args = JSC.CallFrame.ArgumentsSlice.init(vm, arguments); + var args = jsc.CallFrame.ArgumentsSlice.init(vm, arguments); defer args.deinit(); - const path = (try JSC.Node.PathLike.fromJS(globalObject, &args)) orelse { + const path = (try jsc.Node.PathLike.fromJS(globalObject, &args)) orelse { return globalObject.throwInvalidArguments("Expected file path string", .{}); }; return constructS3FileInternal(globalObject, path, args.nextEat()); } pub fn construct( - globalObject: *JSC.JSGlobalObject, - callframe: *JSC.CallFrame, -) callconv(JSC.conv) ?*Blob { + globalObject: *jsc.JSGlobalObject, + callframe: *jsc.CallFrame, +) callconv(jsc.conv) ?*Blob { return constructInternal(globalObject, callframe) catch |err| switch (err) { error.JSError => null, error.OutOfMemory => { @@ -619,8 +619,8 @@ pub fn construct( }, }; } -pub fn hasInstance(_: JSC.JSValue, _: *JSC.JSGlobalObject, value: JSC.JSValue) callconv(JSC.conv) bool { - JSC.markBinding(@src()); +pub fn hasInstance(_: jsc.JSValue, _: *jsc.JSGlobalObject, value: jsc.JSValue) callconv(jsc.conv) bool { + jsc.markBinding(@src()); const blob = value.as(Blob) orelse return false; return blob.isS3(); } @@ -634,12 +634,12 @@ comptime { } pub const exports = struct { - pub const JSS3File__presign = JSC.toJSHostFnWithContext(Blob, getPresignUrl); - pub const JSS3File__stat = JSC.toJSHostFnWithContext(Blob, getStat); + pub const JSS3File__presign = jsc.toJSHostFnWithContext(Blob, getPresignUrl); + pub const JSS3File__stat = jsc.toJSHostFnWithContext(Blob, getStat); }; -extern fn BUN__createJSS3File(*JSC.JSGlobalObject, *JSC.CallFrame) callconv(JSC.conv) JSValue; -extern fn BUN__createJSS3FileUnsafely(*JSC.JSGlobalObject, *Blob) callconv(JSC.conv) JSValue; -pub fn createJSS3File(globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) callconv(JSC.conv) JSValue { +extern fn BUN__createJSS3File(*jsc.JSGlobalObject, *jsc.CallFrame) callconv(jsc.conv) JSValue; +extern fn BUN__createJSS3FileUnsafely(*jsc.JSGlobalObject, *Blob) callconv(jsc.conv) JSValue; +pub fn createJSS3File(globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) callconv(jsc.conv) JSValue { return BUN__createJSS3File(globalObject, callframe); } @@ -652,7 +652,7 @@ const S3 = bun.S3; const strings = bun.strings; const Method = bun.http.Method; -const JSC = bun.JSC; -const JSValue = JSC.JSValue; -const Blob = JSC.WebCore.Blob; -const PathOrBlob = JSC.Node.PathOrBlob; +const jsc = bun.jsc; +const JSValue = jsc.JSValue; +const Blob = jsc.WebCore.Blob; +const PathOrBlob = jsc.Node.PathOrBlob; diff --git a/src/bun.js/webcore/S3Stat.zig b/src/bun.js/webcore/S3Stat.zig index 196938ae27..6cbb0e1c3f 100644 --- a/src/bun.js/webcore/S3Stat.zig +++ b/src/bun.js/webcore/S3Stat.zig @@ -1,6 +1,6 @@ pub const S3Stat = struct { const log = bun.Output.scoped(.S3Stat, false); - pub const js = JSC.Codegen.JSS3Stat; + pub const js = jsc.Codegen.JSS3Stat; pub const toJS = js.toJS; pub const fromJS = js.fromJS; pub const fromJSDirect = js.fromJSDirect; @@ -12,7 +12,7 @@ pub const S3Stat = struct { contentType: bun.String, lastModified: f64, - pub fn constructor(globalThis: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!*@This() { + pub fn constructor(globalThis: *jsc.JSGlobalObject, _: *jsc.CallFrame) bun.JSError!*@This() { return globalThis.throwInvalidArguments("S3Stat is not constructable", .{}); } @@ -21,7 +21,7 @@ pub const S3Stat = struct { etag: []const u8, contentType: []const u8, lastModified: []const u8, - globalThis: *JSC.JSGlobalObject, + globalThis: *jsc.JSGlobalObject, ) bun.JSError!*@This() { var date_str = bun.String.init(lastModified); defer date_str.deref(); @@ -35,20 +35,20 @@ pub const S3Stat = struct { }); } - pub fn getSize(this: *@This(), _: *JSC.JSGlobalObject) JSC.JSValue { - return JSC.JSValue.jsNumber(this.size); + pub fn getSize(this: *@This(), _: *jsc.JSGlobalObject) jsc.JSValue { + return jsc.JSValue.jsNumber(this.size); } - pub fn getEtag(this: *@This(), globalObject: *JSC.JSGlobalObject) JSC.JSValue { + pub fn getEtag(this: *@This(), globalObject: *jsc.JSGlobalObject) jsc.JSValue { return this.etag.toJS(globalObject); } - pub fn getContentType(this: *@This(), globalObject: *JSC.JSGlobalObject) JSC.JSValue { + pub fn getContentType(this: *@This(), globalObject: *jsc.JSGlobalObject) jsc.JSValue { return this.contentType.toJS(globalObject); } - pub fn getLastModified(this: *@This(), globalObject: *JSC.JSGlobalObject) JSC.JSValue { - return JSC.JSValue.fromDateNumber(globalObject, this.lastModified); + pub fn getLastModified(this: *@This(), globalObject: *jsc.JSGlobalObject) jsc.JSValue { + return jsc.JSValue.fromDateNumber(globalObject, this.lastModified); } pub fn finalize(this: *@This()) void { @@ -59,4 +59,4 @@ pub const S3Stat = struct { }; const bun = @import("bun"); -const JSC = bun.JSC; +const jsc = bun.jsc; diff --git a/src/bun.js/webcore/Sink.zig b/src/bun.js/webcore/Sink.zig index d41f43e1c2..63a130aecc 100644 --- a/src/bun.js/webcore/Sink.zig +++ b/src/bun.js/webcore/Sink.zig @@ -106,8 +106,8 @@ pub const VTable = struct { pub const WriteUTF16Fn = *const (fn (this: *anyopaque, data: streams.Result) streams.Result.Writable); pub const WriteUTF8Fn = *const (fn (this: *anyopaque, data: streams.Result) streams.Result.Writable); pub const WriteLatin1Fn = *const (fn (this: *anyopaque, data: streams.Result) streams.Result.Writable); - pub const EndFn = *const (fn (this: *anyopaque, err: ?Syscall.Error) JSC.Maybe(void)); - pub const ConnectFn = *const (fn (this: *anyopaque, signal: streams.Signal) JSC.Maybe(void)); + pub const EndFn = *const (fn (this: *anyopaque, err: ?Syscall.Error) jsc.Maybe(void)); + pub const ConnectFn = *const (fn (this: *anyopaque, signal: streams.Signal) jsc.Maybe(void)); connect: ConnectFn, write: WriteUTF8Fn, @@ -122,7 +122,7 @@ pub const VTable = struct { pub fn onWrite(this: *anyopaque, data: streams.Result) streams.Result.Writable { return Wrapped.write(@as(*Wrapped, @ptrCast(@alignCast(this))), data); } - pub fn onConnect(this: *anyopaque, signal: streams.Signal) JSC.Maybe(void) { + pub fn onConnect(this: *anyopaque, signal: streams.Signal) jsc.Maybe(void) { return Wrapped.connect(@as(*Wrapped, @ptrCast(@alignCast(this))), signal); } pub fn onWriteLatin1(this: *anyopaque, data: streams.Result) streams.Result.Writable { @@ -131,7 +131,7 @@ pub const VTable = struct { pub fn onWriteUTF16(this: *anyopaque, data: streams.Result) streams.Result.Writable { return Wrapped.writeUTF16(@as(*Wrapped, @ptrCast(@alignCast(this))), data); } - pub fn onEnd(this: *anyopaque, err: ?Syscall.Error) JSC.Maybe(void) { + pub fn onEnd(this: *anyopaque, err: ?Syscall.Error) jsc.Maybe(void) { return Wrapped.end(@as(*Wrapped, @ptrCast(@alignCast(this))), err); } }; @@ -146,7 +146,7 @@ pub const VTable = struct { } }; -pub fn end(this: *Sink, err: ?Syscall.Error) JSC.Maybe(void) { +pub fn end(this: *Sink, err: ?Syscall.Error) jsc.Maybe(void) { if (this.status == .closed) { return .{ .result = {} }; } @@ -263,28 +263,28 @@ pub fn JSSink(comptime SinkType: type, comptime abi_name: []const u8) type { } pub fn onClose(ptr: JSValue, reason: JSValue) void { - JSC.markBinding(@src()); + jsc.markBinding(@src()); const globalThis = bun.jsc.VirtualMachine.get().global; // TODO: this should be got from a parameter return bun.jsc.fromJSHostCallGeneric(globalThis, @src(), onCloseExtern, .{ ptr, reason }) catch return; // TODO: properly propagate exception upwards } pub fn onReady(ptr: JSValue, amount: JSValue, offset: JSValue) void { - JSC.markBinding(@src()); + jsc.markBinding(@src()); return onReadyExtern(ptr, amount, offset); } pub fn onStart(ptr: JSValue, globalThis: *JSGlobalObject) void { - JSC.markBinding(@src()); + jsc.markBinding(@src()); return onStartExtern(ptr, globalThis); } pub fn createObject(globalThis: *JSGlobalObject, object: *anyopaque, destructor: usize) JSValue { - JSC.markBinding(@src()); + jsc.markBinding(@src()); return createObjectExtern(globalThis, object, destructor); } pub fn setDestroyCallback(value: JSValue, callback: usize) void { - JSC.markBinding(@src()); + jsc.markBinding(@src()); return setDestroyCallbackExtern(value, callback); } @@ -292,14 +292,14 @@ pub fn JSSink(comptime SinkType: type, comptime abi_name: []const u8) type { return bun.jsc.fromJSHostCallGeneric(globalThis, @src(), detachPtrExtern, .{ptr}); } - pub fn construct(globalThis: *JSGlobalObject, _: *JSC.CallFrame) bun.JSError!JSC.JSValue { - JSC.markBinding(@src()); + pub fn construct(globalThis: *JSGlobalObject, _: *jsc.CallFrame) bun.JSError!jsc.JSValue { + jsc.markBinding(@src()); if (comptime !@hasDecl(SinkType, "construct")) { const Static = struct { pub const message = std.fmt.comptimePrint("{s} is not constructable", .{SinkType.name}); }; - const err = JSC.SystemError{ + const err = jsc.SystemError{ .message = bun.String.static(Static.message), .code = bun.String.static(@tagName(.ERR_ILLEGAL_CONSTRUCTOR)), }; @@ -325,7 +325,7 @@ pub fn JSSink(comptime SinkType: type, comptime abi_name: []const u8) type { if (this.sink.signal.isDead()) return; this.sink.signal.clear(); - const value = @as(JSValue, @enumFromInt(@as(JSC.JSValue.backing_int, @bitCast(@intFromPtr(ptr))))); + const value = @as(JSValue, @enumFromInt(@as(jsc.JSValue.backing_int, @bitCast(@intFromPtr(ptr))))); value.unprotect(); detachPtr(globalThis, value) catch {}; // TODO: properly propagate exception upwards } @@ -351,7 +351,7 @@ pub fn JSSink(comptime SinkType: type, comptime abi_name: []const u8) type { } } - fn getThis(global: *JSGlobalObject, callframe: *const JSC.CallFrame) bun.JSError!*ThisSink { + fn getThis(global: *JSGlobalObject, callframe: *const jsc.CallFrame) bun.JSError!*ThisSink { return switch (fromJSExtern(callframe.this())) { .detached => global.throw("This " ++ abi_name ++ " has already been closed. A \"direct\" ReadableStream terminates its underlying socket once `async pull()` returns.", .{}), .cast_failed => global.ERR(.INVALID_THIS, "Expected " ++ abi_name, .{}).throw(), @@ -363,8 +363,8 @@ pub fn JSSink(comptime SinkType: type, comptime abi_name: []const u8) type { _ = this; } - pub fn write(globalThis: *JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { - JSC.markBinding(@src()); + pub fn write(globalThis: *JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { + jsc.markBinding(@src()); const this = try getThis(globalThis, callframe); if (comptime @hasDecl(SinkType, "getPendingError")) { @@ -391,7 +391,7 @@ pub fn JSSink(comptime SinkType: type, comptime abi_name: []const u8) type { if (arg.asArrayBuffer(globalThis)) |buffer| { const slice = buffer.slice(); if (slice.len == 0) { - return JSC.JSValue.jsNumber(0); + return jsc.JSValue.jsNumber(0); } return this.sink.writeBytes(.{ .temporary = bun.ByteList.init(slice) }).toJS(globalThis); @@ -409,7 +409,7 @@ pub fn JSSink(comptime SinkType: type, comptime abi_name: []const u8) type { const view = str.view(globalThis); if (view.isEmpty()) { - return JSC.JSValue.jsNumber(0); + return jsc.JSValue.jsNumber(0); } defer str.ensureStillAlive(); @@ -420,8 +420,8 @@ pub fn JSSink(comptime SinkType: type, comptime abi_name: []const u8) type { return this.sink.writeLatin1(.{ .temporary = bun.ByteList.initConst(view.slice()) }).toJS(globalThis); } - pub fn writeUTF8(globalThis: *JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { - JSC.markBinding(@src()); + pub fn writeUTF8(globalThis: *JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { + jsc.markBinding(@src()); const this = try getThis(globalThis, callframe); @@ -451,7 +451,7 @@ pub fn JSSink(comptime SinkType: type, comptime abi_name: []const u8) type { const view = str.view(globalThis); if (view.isEmpty()) { - return JSC.JSValue.jsNumber(0); + return jsc.JSValue.jsNumber(0); } defer str.ensureStillAlive(); @@ -463,7 +463,7 @@ pub fn JSSink(comptime SinkType: type, comptime abi_name: []const u8) type { } pub fn close(globalThis: *JSGlobalObject, sink_ptr: ?*anyopaque) callconv(.C) JSValue { - JSC.markBinding(@src()); + jsc.markBinding(@src()); const this: *ThisSink = @ptrCast(@alignCast(sink_ptr orelse return .js_undefined)); if (comptime @hasDecl(SinkType, "getPendingError")) { @@ -475,8 +475,8 @@ pub fn JSSink(comptime SinkType: type, comptime abi_name: []const u8) type { return this.sink.end(null).toJS(globalThis) catch .zero; // TODO: properly propagate exception upwards } - pub fn flush(globalThis: *JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { - JSC.markBinding(@src()); + pub fn flush(globalThis: *JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { + jsc.markBinding(@src()); const this = try getThis(globalThis, callframe); @@ -494,7 +494,7 @@ pub fn JSSink(comptime SinkType: type, comptime abi_name: []const u8) type { if (comptime @hasDecl(SinkType, "flushFromJS")) { const wait = callframe.argumentsCount() > 0 and callframe.argument(0).isBoolean() and callframe.argument(0).asBoolean(); - const maybe_value: JSC.Maybe(JSValue) = this.sink.flushFromJS(globalThis, wait); + const maybe_value: jsc.Maybe(JSValue) = this.sink.flushFromJS(globalThis, wait); return switch (maybe_value) { .result => |value| value, .err => |err| return globalThis.throwValue(err.toJS(globalThis)), @@ -504,8 +504,8 @@ pub fn JSSink(comptime SinkType: type, comptime abi_name: []const u8) type { return this.sink.flush().toJS(globalThis); } - pub fn start(globalThis: *JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { - JSC.markBinding(@src()); + pub fn start(globalThis: *JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { + jsc.markBinding(@src()); const this = try getThis(globalThis, callframe); @@ -536,8 +536,8 @@ pub fn JSSink(comptime SinkType: type, comptime abi_name: []const u8) type { ).toJS(globalThis); } - pub fn end(globalThis: *JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { - JSC.markBinding(@src()); + pub fn end(globalThis: *JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { + jsc.markBinding(@src()); const this = try getThis(globalThis, callframe); @@ -558,8 +558,8 @@ pub fn JSSink(comptime SinkType: type, comptime abi_name: []const u8) type { return this.sink.endFromJS(globalThis).toJS(globalThis); } - pub fn endWithSink(ptr: *anyopaque, globalThis: *JSGlobalObject) callconv(JSC.conv) JSValue { - JSC.markBinding(@src()); + pub fn endWithSink(ptr: *anyopaque, globalThis: *JSGlobalObject) callconv(jsc.conv) JSValue { + jsc.markBinding(@src()); var this = @as(*ThisSink, @ptrCast(@alignCast(ptr))); @@ -573,17 +573,17 @@ pub fn JSSink(comptime SinkType: type, comptime abi_name: []const u8) type { } pub fn updateRef(ptr: *anyopaque, value: bool) callconv(.C) void { - JSC.markBinding(@src()); + jsc.markBinding(@src()); var this = bun.cast(*ThisSink, ptr); if (comptime @hasDecl(SinkType, "updateRef")) this.sink.updateRef(value); } - const jsWrite = JSC.toJSHostFn(@This().write); - const jsFlush = JSC.toJSHostFn(flush); - const jsStart = JSC.toJSHostFn(start); - const jsEnd = JSC.toJSHostFn(@This().end); - const jsConstruct = JSC.toJSHostFn(construct); + const jsWrite = jsc.toJSHostFn(@This().write); + const jsFlush = jsc.toJSHostFn(flush); + const jsStart = jsc.toJSHostFn(start); + const jsEnd = jsc.toJSHostFn(@This().end); + const jsConstruct = jsc.toJSHostFn(construct); fn jsGetInternalFd(ptr: *anyopaque) callconv(.C) JSValue { var this = bun.cast(*ThisSink, ptr); @@ -649,9 +649,9 @@ const Output = bun.Output; const Syscall = bun.sys; const Subprocess = bun.api.Subprocess; -const JSC = bun.jsc; -const JSGlobalObject = JSC.JSGlobalObject; -const JSValue = JSC.JSValue; +const jsc = bun.jsc; +const JSGlobalObject = jsc.JSGlobalObject; +const JSValue = jsc.JSValue; const webcore = bun.webcore; const Blob = webcore.Blob; diff --git a/src/bun.js/webcore/TextDecoder.zig b/src/bun.js/webcore/TextDecoder.zig index 9a2b049387..402f5d793c 100644 --- a/src/bun.js/webcore/TextDecoder.zig +++ b/src/bun.js/webcore/TextDecoder.zig @@ -18,7 +18,7 @@ ignore_bom: bool = false, fatal: bool = false, encoding: EncodingLabel = EncodingLabel.@"UTF-8", -pub const js = JSC.Codegen.JSTextDecoder; +pub const js = jsc.Codegen.JSTextDecoder; pub const toJS = js.toJS; pub const fromJS = js.fromJS; pub const fromJSDirect = js.fromJSDirect; @@ -31,22 +31,22 @@ pub fn finalize(this: *TextDecoder) void { pub fn getIgnoreBOM( this: *TextDecoder, - _: *JSC.JSGlobalObject, -) JSC.JSValue { - return JSC.JSValue.jsBoolean(this.ignore_bom); + _: *jsc.JSGlobalObject, +) jsc.JSValue { + return jsc.JSValue.jsBoolean(this.ignore_bom); } pub fn getFatal( this: *TextDecoder, - _: *JSC.JSGlobalObject, -) JSC.JSValue { - return JSC.JSValue.jsBoolean(this.fatal); + _: *jsc.JSGlobalObject, +) jsc.JSValue { + return jsc.JSValue.jsBoolean(this.fatal); } pub fn getEncoding( this: *TextDecoder, - globalThis: *JSC.JSGlobalObject, -) JSC.JSValue { + globalThis: *jsc.JSGlobalObject, +) jsc.JSValue { return ZigString.init(EncodingLabel.getLabel(this.encoding)).toJS(globalThis); } const Vector16 = std.meta.Vector(16, u16); @@ -155,7 +155,7 @@ pub fn decodeUTF16( return .{ output, saw_error }; } -pub fn decode(this: *TextDecoder, globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { +pub fn decode(this: *TextDecoder, globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { const arguments = callframe.arguments_old(2).slice(); const input_slice = input_slice: { @@ -185,11 +185,11 @@ pub fn decode(this: *TextDecoder, globalThis: *JSC.JSGlobalObject, callframe: *J }; } -pub fn decodeWithoutTypeChecks(this: *TextDecoder, globalThis: *JSC.JSGlobalObject, uint8array: *JSC.JSUint8Array) bun.JSError!JSValue { +pub fn decodeWithoutTypeChecks(this: *TextDecoder, globalThis: *jsc.JSGlobalObject, uint8array: *jsc.JSUint8Array) bun.JSError!JSValue { return this.decodeSlice(globalThis, uint8array.slice(), false); } -fn decodeSlice(this: *TextDecoder, globalThis: *JSC.JSGlobalObject, buffer_slice: []const u8, comptime flush: bool) bun.JSError!JSValue { +fn decodeSlice(this: *TextDecoder, globalThis: *jsc.JSGlobalObject, buffer_slice: []const u8, comptime flush: bool) bun.JSError!JSValue { switch (this.encoding) { EncodingLabel.latin1 => { if (strings.isAllASCII(buffer_slice)) { @@ -277,7 +277,7 @@ fn decodeSlice(this: *TextDecoder, globalThis: *JSC.JSGlobalObject, buffer_slice } } -pub fn constructor(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!*TextDecoder { +pub fn constructor(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!*TextDecoder { const encoding_value, const options_value = callframe.argumentsAsArray(2); var decoder = TextDecoder{}; @@ -324,10 +324,10 @@ const std = @import("std"); const bun = @import("bun"); const strings = bun.strings; -const JSC = bun.JSC; -const ArrayBuffer = JSC.ArrayBuffer; -const JSGlobalObject = JSC.JSGlobalObject; -const JSUint8Array = JSC.JSUint8Array; -const JSValue = JSC.JSValue; -const ZigString = JSC.ZigString; -const EncodingLabel = JSC.WebCore.EncodingLabel; +const jsc = bun.jsc; +const ArrayBuffer = jsc.ArrayBuffer; +const JSGlobalObject = jsc.JSGlobalObject; +const JSUint8Array = jsc.JSUint8Array; +const JSValue = jsc.JSValue; +const ZigString = jsc.ZigString; +const EncodingLabel = jsc.WebCore.EncodingLabel; diff --git a/src/bun.js/webcore/TextEncoder.zig b/src/bun.js/webcore/TextEncoder.zig index bfcff2fae9..1cff9e5561 100644 --- a/src/bun.js/webcore/TextEncoder.zig +++ b/src/bun.js/webcore/TextEncoder.zig @@ -5,10 +5,10 @@ pub export fn TextEncoder__encode8( ptr: [*]const u8, len: usize, ) JSValue { - // as much as possible, rely on JSC to own the memory + // as much as possible, rely on jsc to own the memory // their code is more battle-tested than bun's code // so we do a stack allocation here - // and then copy into JSC memory + // and then copy into jsc memory // unless it's huge // JSC will GC Uint8Array that occupy less than 512 bytes // so it's extra good for that case @@ -18,7 +18,7 @@ pub export fn TextEncoder__encode8( if (slice.len <= buf.len / 2) { const result = strings.copyLatin1IntoUTF8(&buf, []const u8, slice); - const uint8array = JSC.JSValue.createUninitializedUint8Array(globalThis, result.written) catch return .zero; + const uint8array = jsc.JSValue.createUninitializedUint8Array(globalThis, result.written) catch return .zero; bun.assert(result.written <= buf.len); bun.assert(result.read == slice.len); const array_buffer = uint8array.asArrayBuffer(globalThis) orelse return .zero; @@ -39,10 +39,10 @@ pub export fn TextEncoder__encode16( ptr: [*]const u16, len: usize, ) JSValue { - // as much as possible, rely on JSC to own the memory + // as much as possible, rely on jsc to own the memory // their code is more battle-tested than bun's code // so we do a stack allocation here - // and then copy into JSC memory + // and then copy into jsc memory // unless it's huge // JSC will GC Uint8Array that occupy less than 512 bytes // so it's extra good for that case @@ -55,13 +55,13 @@ pub export fn TextEncoder__encode16( if (slice.len <= buf.len / 4) { const result = strings.copyUTF16IntoUTF8(&buf, @TypeOf(slice), slice); if (result.read == 0 or result.written == 0) { - const uint8array = JSC.JSValue.createUninitializedUint8Array(globalThis, 3) catch return .zero; + const uint8array = jsc.JSValue.createUninitializedUint8Array(globalThis, 3) catch return .zero; const array_buffer = uint8array.asArrayBuffer(globalThis).?; const replacement_char = [_]u8{ 239, 191, 189 }; @memcpy(array_buffer.slice()[0..replacement_char.len], &replacement_char); return uint8array; } - const uint8array = JSC.JSValue.createUninitializedUint8Array(globalThis, result.written) catch return .zero; + const uint8array = jsc.JSValue.createUninitializedUint8Array(globalThis, result.written) catch return .zero; bun.assert(result.written <= buf.len); bun.assert(result.read == slice.len); const array_buffer = uint8array.asArrayBuffer(globalThis).?; @@ -85,10 +85,10 @@ pub export fn c( ptr: [*]const u16, len: usize, ) JSValue { - // as much as possible, rely on JSC to own the memory + // as much as possible, rely on jsc to own the memory // their code is more battle-tested than bun's code // so we do a stack allocation here - // and then copy into JSC memory + // and then copy into jsc memory // unless it's huge // JSC will GC Uint8Array that occupy less than 512 bytes // so it's extra good for that case @@ -101,13 +101,13 @@ pub export fn c( if (slice.len <= buf.len / 4) { const result = strings.copyUTF16IntoUTF8(&buf, @TypeOf(slice), slice); if (result.read == 0 or result.written == 0) { - const uint8array = JSC.JSValue.createUninitializedUint8Array(globalThis, 3) catch return .zero; + const uint8array = jsc.JSValue.createUninitializedUint8Array(globalThis, 3) catch return .zero; const array_buffer = uint8array.asArrayBuffer(globalThis).?; const replacement_char = [_]u8{ 239, 191, 189 }; @memcpy(array_buffer.slice()[0..replacement_char.len], &replacement_char); return uint8array; } - const uint8array = JSC.JSValue.createUninitializedUint8Array(globalThis, result.written) catch return .zero; + const uint8array = jsc.JSValue.createUninitializedUint8Array(globalThis, result.written) catch return .zero; bun.assert(result.written <= buf.len); bun.assert(result.read == slice.len); const array_buffer = uint8array.asArrayBuffer(globalThis).?; @@ -134,7 +134,7 @@ const RopeStringEncoder = struct { tail: usize = 0, any_non_ascii: bool = false, - pub fn append8(it: *JSC.JSString.Iterator, ptr: [*]const u8, len: u32) callconv(.C) void { + pub fn append8(it: *jsc.JSString.Iterator, ptr: [*]const u8, len: u32) callconv(.C) void { var this = bun.cast(*RopeStringEncoder, it.data.?); const result = strings.copyLatin1IntoUTF8StopOnNonASCII(this.buf[this.tail..], []const u8, ptr[0..len], true); if (result.read == std.math.maxInt(u32) and result.written == std.math.maxInt(u32)) { @@ -144,12 +144,12 @@ const RopeStringEncoder = struct { this.tail += result.written; } } - pub fn append16(it: *JSC.JSString.Iterator, _: [*]const u16, _: u32) callconv(.C) void { + pub fn append16(it: *jsc.JSString.Iterator, _: [*]const u16, _: u32) callconv(.C) void { var this = bun.cast(*RopeStringEncoder, it.data.?); this.any_non_ascii = true; it.stop = 1; } - pub fn write8(it: *JSC.JSString.Iterator, ptr: [*]const u8, len: u32, offset: u32) callconv(.C) void { + pub fn write8(it: *jsc.JSString.Iterator, ptr: [*]const u8, len: u32, offset: u32) callconv(.C) void { var this = bun.cast(*RopeStringEncoder, it.data.?); const result = strings.copyLatin1IntoUTF8StopOnNonASCII(this.buf[offset..], []const u8, ptr[0..len], true); if (result.read == std.math.maxInt(u32) and result.written == std.math.maxInt(u32)) { @@ -157,13 +157,13 @@ const RopeStringEncoder = struct { this.any_non_ascii = true; } } - pub fn write16(it: *JSC.JSString.Iterator, _: [*]const u16, _: u32, _: u32) callconv(.C) void { + pub fn write16(it: *jsc.JSString.Iterator, _: [*]const u16, _: u32, _: u32) callconv(.C) void { var this = bun.cast(*RopeStringEncoder, it.data.?); this.any_non_ascii = true; it.stop = 1; } - pub fn iter(this: *RopeStringEncoder) JSC.JSString.Iterator { + pub fn iter(this: *RopeStringEncoder) jsc.JSString.Iterator { return .{ .data = this, .stop = 0, @@ -180,7 +180,7 @@ const RopeStringEncoder = struct { // It also isn't usable for latin1 strings which contain non-ascii characters pub export fn TextEncoder__encodeRopeString( globalThis: *JSGlobalObject, - rope_str: *JSC.JSString, + rope_str: *jsc.JSString, ) JSValue { if (comptime Environment.allow_assert) bun.assert(rope_str.is8Bit()); var stack_buf: [2048]u8 = undefined; @@ -188,7 +188,7 @@ pub export fn TextEncoder__encodeRopeString( const length = rope_str.length(); var array: JSValue = .zero; if (length > stack_buf.len / 2) { - array = JSC.JSValue.createUninitializedUint8Array(globalThis, length) catch return .zero; + array = jsc.JSValue.createUninitializedUint8Array(globalThis, length) catch return .zero; array.ensureStillAlive(); buf_to_use = array.asArrayBuffer(globalThis).?.slice(); } @@ -206,7 +206,7 @@ pub export fn TextEncoder__encodeRopeString( } if (array == .zero) { - array = JSC.JSValue.createUninitializedUint8Array(globalThis, length) catch return .zero; + array = jsc.JSValue.createUninitializedUint8Array(globalThis, length) catch return .zero; array.ensureStillAlive(); @memcpy(array.asArrayBuffer(globalThis).?.ptr[0..length], buf_to_use[0..length]); } @@ -261,7 +261,7 @@ const bun = @import("bun"); const Environment = bun.Environment; const strings = bun.strings; -const JSC = bun.JSC; -const ArrayBuffer = JSC.ArrayBuffer; -const JSGlobalObject = JSC.JSGlobalObject; -const JSValue = JSC.JSValue; +const jsc = bun.jsc; +const ArrayBuffer = jsc.ArrayBuffer; +const JSGlobalObject = jsc.JSGlobalObject; +const JSValue = jsc.JSValue; diff --git a/src/bun.js/webcore/TextEncoderStreamEncoder.zig b/src/bun.js/webcore/TextEncoderStreamEncoder.zig index 5a9a0bf752..d05e240934 100644 --- a/src/bun.js/webcore/TextEncoderStreamEncoder.zig +++ b/src/bun.js/webcore/TextEncoderStreamEncoder.zig @@ -4,7 +4,7 @@ pending_lead_surrogate: ?u16 = null, const log = Output.scoped(.TextEncoderStreamEncoder, false); -pub const js = JSC.Codegen.JSTextEncoderStreamEncoder; +pub const js = jsc.Codegen.JSTextEncoderStreamEncoder; pub const toJS = js.toJS; pub const fromJS = js.fromJS; pub const fromJSDirect = js.fromJSDirect; @@ -15,11 +15,11 @@ pub fn finalize(this: *TextEncoderStreamEncoder) void { bun.destroy(this); } -pub fn constructor(_: *JSGlobalObject, _: *JSC.CallFrame) bun.JSError!*TextEncoderStreamEncoder { +pub fn constructor(_: *JSGlobalObject, _: *jsc.CallFrame) bun.JSError!*TextEncoderStreamEncoder { return TextEncoderStreamEncoder.new(.{}); } -pub fn encode(this: *TextEncoderStreamEncoder, globalObject: *JSC.JSGlobalObject, callFrame: *JSC.CallFrame) bun.JSError!JSValue { +pub fn encode(this: *TextEncoderStreamEncoder, globalObject: *jsc.JSGlobalObject, callFrame: *jsc.CallFrame) bun.JSError!JSValue { const arguments = callFrame.arguments_old(1).slice(); if (arguments.len == 0) { return globalObject.throwNotEnoughArguments("TextEncoderStreamEncoder.encode", 1, arguments.len); @@ -34,7 +34,7 @@ pub fn encode(this: *TextEncoderStreamEncoder, globalObject: *JSC.JSGlobalObject return this.encodeLatin1(globalObject, str.slice()); } -pub fn encodeWithoutTypeChecks(this: *TextEncoderStreamEncoder, globalObject: *JSC.JSGlobalObject, input: *JSC.JSString) JSValue { +pub fn encodeWithoutTypeChecks(this: *TextEncoderStreamEncoder, globalObject: *jsc.JSGlobalObject, input: *jsc.JSString) JSValue { const str = input.getZigString(globalObject); if (str.is16Bit()) { @@ -97,7 +97,7 @@ fn encodeLatin1(this: *TextEncoderStreamEncoder, globalObject: *JSGlobalObject, bun.debugAssert(buffer.items.len == (bun.simdutf.length.utf8.from.latin1(input) + prepend_replacement_len)); } - return JSC.JSUint8Array.fromBytes(globalObject, buffer.items); + return jsc.JSUint8Array.fromBytes(globalObject, buffer.items); } fn encodeUTF16(this: *TextEncoderStreamEncoder, globalObject: *JSGlobalObject, input: []const u16) JSValue { @@ -174,16 +174,16 @@ fn encodeUTF16(this: *TextEncoderStreamEncoder, globalObject: *JSGlobalObject, i if (buf.items.len == 0) return JSUint8Array.createEmpty(globalObject); } - return JSC.JSUint8Array.fromBytes(globalObject, buf.items); + return jsc.JSUint8Array.fromBytes(globalObject, buf.items); }, .success => { buf.items.len += result.count; - return JSC.JSUint8Array.fromBytes(globalObject, buf.items); + return jsc.JSUint8Array.fromBytes(globalObject, buf.items); }, } } -pub fn flush(this: *TextEncoderStreamEncoder, globalObject: *JSGlobalObject, _: *JSC.CallFrame) bun.JSError!JSValue { +pub fn flush(this: *TextEncoderStreamEncoder, globalObject: *JSGlobalObject, _: *jsc.CallFrame) bun.JSError!JSValue { return flushBody(this, globalObject); } @@ -205,7 +205,7 @@ const Environment = bun.Environment; const Output = bun.Output; const strings = bun.strings; -const JSC = bun.JSC; -const JSGlobalObject = JSC.JSGlobalObject; -const JSUint8Array = JSC.JSUint8Array; -const JSValue = JSC.JSValue; +const jsc = bun.jsc; +const JSGlobalObject = jsc.JSGlobalObject; +const JSUint8Array = jsc.JSUint8Array; +const JSValue = jsc.JSValue; diff --git a/src/bun.js/webcore/blob/Store.zig b/src/bun.js/webcore/blob/Store.zig index 6afdbf2f5a..dc1e8f2712 100644 --- a/src/bun.js/webcore/blob/Store.zig +++ b/src/bun.js/webcore/blob/Store.zig @@ -32,7 +32,7 @@ pub fn size(this: *const Store) SizeType { }; } -pub const Map = std.HashMap(u64, *JSC.WebCore.Blob.Store, bun.IdentityContext(u64), 80); +pub const Map = std.HashMap(u64, *jsc.WebCore.Blob.Store, bun.IdentityContext(u64), 80); pub const Data = union(enum) { bytes: Bytes, @@ -122,7 +122,7 @@ pub fn initS3(pathlike: node.PathLike, mime_type: ?MimeType, credentials: bun.S3 }); return store; } -pub fn initFile(pathlike: JSC.Node.PathOrFileDescriptor, mime_type: ?MimeType, allocator: std.mem.Allocator) !*Store { +pub fn initFile(pathlike: jsc.Node.PathOrFileDescriptor, mime_type: ?MimeType, allocator: std.mem.Allocator) !*Store { const store = Blob.Store.new(.{ .data = .{ .file = File.init( @@ -209,7 +209,7 @@ pub const SerializeTag = enum(u8) { pub fn serialize(this: *Store, comptime Writer: type, writer: Writer) !void { switch (this.data) { .file => |file| { - const pathlike_tag: JSC.Node.PathOrFileDescriptor.SerializeTag = if (file.pathlike == .fd) .fd else .path; + const pathlike_tag: jsc.Node.PathOrFileDescriptor.SerializeTag = if (file.pathlike == .fd) .fd else .path; try writer.writeInt(u8, @intFromEnum(pathlike_tag), .little); switch (file.pathlike) { @@ -224,7 +224,7 @@ pub fn serialize(this: *Store, comptime Writer: type, writer: Writer) !void { } }, .s3 => |s3| { - const pathlike_tag: JSC.Node.PathOrFileDescriptor.SerializeTag = .path; + const pathlike_tag: jsc.Node.PathOrFileDescriptor.SerializeTag = .path; try writer.writeInt(u8, @intFromEnum(pathlike_tag), .little); const path_slice = s3.pathlike.slice(); @@ -248,26 +248,26 @@ pub fn fromArrayList(list: std.ArrayListUnmanaged(u8), allocator: std.mem.Alloca /// A blob store that references a file on disk. pub const File = struct { - pathlike: JSC.Node.PathOrFileDescriptor, + pathlike: jsc.Node.PathOrFileDescriptor, mime_type: MimeType = MimeType.other, is_atty: ?bool = null, mode: bun.Mode = 0, seekable: ?bool = null, max_size: SizeType = Blob.max_size, // milliseconds since ECMAScript epoch - last_modified: JSC.JSTimeType = JSC.init_timestamp, + last_modified: jsc.JSTimeType = jsc.init_timestamp, pub fn unlink(this: *const File, globalThis: *JSGlobalObject) bun.JSError!JSValue { return switch (this.pathlike) { - .path => |path_like| JSC.Node.fs.Async.unlink.create(globalThis, undefined, .{ + .path => |path_like| jsc.Node.fs.Async.unlink.create(globalThis, undefined, .{ .path = .{ .encoded_slice = switch (path_like) { .encoded_slice => |slice| try slice.toOwned(bun.default_allocator), - else => try JSC.ZigString.init(path_like.slice()).toSliceClone(bun.default_allocator), + else => try jsc.ZigString.init(path_like.slice()).toSliceClone(bun.default_allocator), }, }, }, globalThis.bunVM()), - .fd => JSC.JSPromise.resolvedPromiseValue(globalThis, globalThis.createInvalidArgs("Is not possible to unlink a file descriptor", .{})), + .fd => jsc.JSPromise.resolvedPromiseValue(globalThis, globalThis.createInvalidArgs("Is not possible to unlink a file descriptor", .{})), }; } pub fn isSeekable(this: *const File) ?bool { @@ -282,7 +282,7 @@ pub const File = struct { return null; } - pub fn init(pathlike: JSC.Node.PathOrFileDescriptor, mime_type: ?MimeType) File { + pub fn init(pathlike: jsc.Node.PathOrFileDescriptor, mime_type: ?MimeType) File { return .{ .pathlike = pathlike, .mime_type = mime_type orelse MimeType.other }; } }; @@ -327,7 +327,7 @@ pub const S3 = struct { pub fn unlink(this: *@This(), store: *Store, globalThis: *JSGlobalObject, extra_options: ?JSValue) bun.JSError!JSValue { const Wrapper = struct { - promise: JSC.JSPromise.Strong, + promise: jsc.JSPromise.Strong, store: *Store, global: *JSGlobalObject, @@ -353,7 +353,7 @@ pub const S3 = struct { bun.destroy(wrap); } }; - const promise = JSC.JSPromise.Strong.init(globalThis); + const promise = jsc.JSPromise.Strong.init(globalThis); const value = promise.value(); const proxy_url = globalThis.bunVM().transpiler.env.getHttpProxy(true, null); const proxy = if (proxy_url) |url| url.href else null; @@ -375,7 +375,7 @@ pub const S3 = struct { } const Wrapper = struct { - promise: JSC.JSPromise.Strong, + promise: jsc.JSPromise.Strong, store: *Store, resolvedlistOptions: bun.S3.S3ListObjectsOptions, global: *JSGlobalObject, @@ -410,7 +410,7 @@ pub const S3 = struct { } }; - const promise = JSC.JSPromise.Strong.init(globalThis); + const promise = jsc.JSPromise.Strong.init(globalThis); const value = promise.value(); const proxy_url = globalThis.bunVM().transpiler.env.getHttpProxy(true, null); const proxy = if (proxy_url) |url| url.href else null; @@ -567,9 +567,9 @@ const webcore = bun.webcore; const MimeType = bun.http.MimeType; const node = bun.api.node; -const JSC = bun.JSC; -const JSGlobalObject = JSC.JSGlobalObject; -const JSValue = JSC.JSValue; +const jsc = bun.jsc; +const JSGlobalObject = jsc.JSGlobalObject; +const JSValue = jsc.JSValue; const Blob = webcore.Blob; const SizeType = Blob.SizeType; diff --git a/src/bun.js/webcore/blob/copy_file.zig b/src/bun.js/webcore/blob/copy_file.zig index b1888397ba..10009a6299 100644 --- a/src/bun.js/webcore/blob/copy_file.zig +++ b/src/bun.js/webcore/blob/copy_file.zig @@ -61,7 +61,7 @@ pub const CopyFile = struct { bun.destroy(this); } - pub fn reject(this: *CopyFile, promise: *JSC.JSPromise) void { + pub fn reject(this: *CopyFile, promise: *jsc.JSPromise) void { const globalThis = this.globalThis; var system_error: SystemError = this.system_error orelse SystemError{ .message = .empty }; if (this.source_file_store.pathlike == .path and system_error.path.isEmpty()) { @@ -79,7 +79,7 @@ pub const CopyFile = struct { promise.reject(globalThis, instance); } - pub fn then(this: *CopyFile, promise: *JSC.JSPromise) void { + pub fn then(this: *CopyFile, promise: *jsc.JSPromise) void { this.source_store.?.deref(); if (this.system_error != null) { @@ -87,7 +87,7 @@ pub const CopyFile = struct { return; } - promise.resolve(this.globalThis, JSC.JSValue.jsNumberFromUint64(this.read_len)); + promise.resolve(this.globalThis, jsc.JSValue.jsNumberFromUint64(this.read_len)); } pub fn run(this: *CopyFile) void { @@ -158,7 +158,7 @@ pub const CopyFile = struct { this.destination_fd = switch (bun.sys.open( dest, open_destination_flags, - JSC.Node.fs.default_permission, + jsc.Node.fs.default_permission, )) { .result => |result| switch (result.makeLibUVOwnedForSyscall(.open, .close_on_fail)) { .result => |result_fd| result_fd, @@ -234,7 +234,7 @@ pub const CopyFile = struct { // If they can't use copy_file_range, they probably also can't // use sendfile() or splice() if (!bun.canUseCopyFileRangeSyscall()) { - switch (JSC.Node.fs.NodeFS.copyFileUsingReadWriteLoop("", "", src_fd, dest_fd, if (unknown_size) 0 else remain, &total_written)) { + switch (jsc.Node.fs.NodeFS.copyFileUsingReadWriteLoop("", "", src_fd, dest_fd, if (unknown_size) 0 else remain, &total_written)) { .err => |err| { this.system_error = err.toSystemError(); return bun.errnoToZigErr(err.errno); @@ -259,7 +259,7 @@ pub const CopyFile = struct { .NOSYS, .XDEV => { // TODO: this should use non-blocking I/O. - switch (JSC.Node.fs.NodeFS.copyFileUsingReadWriteLoop("", "", src_fd, dest_fd, if (unknown_size) 0 else remain, &total_written)) { + switch (jsc.Node.fs.NodeFS.copyFileUsingReadWriteLoop("", "", src_fd, dest_fd, if (unknown_size) 0 else remain, &total_written)) { .err => |err| { this.system_error = err.toSystemError(); return bun.errnoToZigErr(err.errno); @@ -292,7 +292,7 @@ pub const CopyFile = struct { // to a read/write loop if (total_written == 0) { // TODO: this should use non-blocking I/O. - switch (JSC.Node.fs.NodeFS.copyFileUsingReadWriteLoop("", "", src_fd, dest_fd, if (unknown_size) 0 else remain, &total_written)) { + switch (jsc.Node.fs.NodeFS.copyFileUsingReadWriteLoop("", "", src_fd, dest_fd, if (unknown_size) 0 else remain, &total_written)) { .err => |err| { this.system_error = err.toSystemError(); return bun.errnoToZigErr(err.errno); @@ -339,7 +339,7 @@ pub const CopyFile = struct { var total_written: u64 = 0; // TODO: this should use non-blocking I/O. - switch (JSC.Node.fs.NodeFS.copyFileUsingReadWriteLoop("", "", this.source_fd, this.destination_fd, 0, &total_written)) { + switch (jsc.Node.fs.NodeFS.copyFileUsingReadWriteLoop("", "", this.source_fd, this.destination_fd, 0, &total_written)) { .err => |err| { this.system_error = err.toSystemError(); return bun.errnoToZigErr(err.errno); @@ -571,9 +571,9 @@ pub const CopyFileWindows = struct { source_file_store: *Store, io_request: libuv.fs_t = std.mem.zeroes(libuv.fs_t), - promise: JSC.JSPromise.Strong = .{}, + promise: jsc.JSPromise.Strong = .{}, mkdirp_if_not_exists: bool = false, - event_loop: *JSC.EventLoop, + event_loop: *jsc.EventLoop, size: Blob.SizeType = Blob.max_size, @@ -592,13 +592,13 @@ pub const CopyFileWindows = struct { read_buf: std.ArrayList(u8) = std.ArrayList(u8).init(bun.default_allocator), uv_buf: libuv.uv_buf_t = .{ .base = undefined, .len = 0 }, - pub fn start(read_write_loop: *ReadWriteLoop, this: *CopyFileWindows) JSC.Maybe(void) { + pub fn start(read_write_loop: *ReadWriteLoop, this: *CopyFileWindows) jsc.Maybe(void) { read_write_loop.read_buf.ensureTotalCapacityPrecise(64 * 1024) catch bun.outOfMemory(); return read(read_write_loop, this); } - pub fn read(read_write_loop: *ReadWriteLoop, this: *CopyFileWindows) JSC.Maybe(void) { + pub fn read(read_write_loop: *ReadWriteLoop, this: *CopyFileWindows) jsc.Maybe(void) { read_write_loop.read_buf.items.len = 0; read_write_loop.uv_buf = libuv.uv_buf_t.init(read_write_loop.read_buf.allocatedSlice()); const loop = this.event_loop.virtual_machine.event_loop_handle.?; @@ -783,16 +783,16 @@ pub const CopyFileWindows = struct { pub fn init( destination_file_store: *Store, source_file_store: *Store, - event_loop: *JSC.EventLoop, + event_loop: *jsc.EventLoop, mkdirp_if_not_exists: bool, size_: Blob.SizeType, - ) JSC.JSValue { + ) jsc.JSValue { destination_file_store.ref(); source_file_store.ref(); const result = CopyFileWindows.new(.{ .destination_file_store = destination_file_store, .source_file_store = source_file_store, - .promise = JSC.JSPromise.Strong.init(event_loop.global), + .promise = jsc.JSPromise.Strong.init(event_loop.global), .io_request = std.mem.zeroes(libuv.fs_t), .event_loop = event_loop, .mkdirp_if_not_exists = mkdirp_if_not_exists, @@ -807,7 +807,7 @@ pub const CopyFileWindows = struct { return promise; } - fn preparePathlike(pathlike: *JSC.Node.PathOrFileDescriptor, must_close: *bool, is_reading: bool) JSC.Maybe(bun.FileDescriptor) { + fn preparePathlike(pathlike: *jsc.Node.PathOrFileDescriptor, must_close: *bool, is_reading: bool) jsc.Maybe(bun.FileDescriptor) { if (pathlike.* == .path) { const fd = switch (bun.sys.openatWindowsT( u8, @@ -1057,14 +1057,14 @@ pub const CopyFileWindows = struct { defer event_loop.exit(); this.deinit(); - promise.resolve(globalThis, JSC.JSValue.jsNumberFromUint64(written)); + promise.resolve(globalThis, jsc.JSValue.jsNumberFromUint64(written)); } fn truncate(this: *CopyFileWindows) void { // TODO: optimize this @branchHint(.cold); - var node_fs: JSC.Node.fs.NodeFS = .{}; + var node_fs: jsc.Node.fs.NodeFS = .{}; _ = node_fs.truncate( .{ .path = this.destination_file_store.data.file.pathlike, @@ -1098,7 +1098,7 @@ pub const CopyFileWindows = struct { } this.event_loop.refConcurrently(); - JSC.Node.fs.Async.AsyncMkdirp.new(.{ + jsc.Node.fs.Async.AsyncMkdirp.new(.{ .completion = @ptrCast(&onMkdirpCompleteConcurrent), .completion_ctx = this, .path = bun.Dirname.dirname(u8, destination.pathlike.path.slice()) @@ -1120,11 +1120,11 @@ pub const CopyFileWindows = struct { this.copyfile(); } - fn onMkdirpCompleteConcurrent(this: *CopyFileWindows, err_: JSC.Maybe(void)) void { + fn onMkdirpCompleteConcurrent(this: *CopyFileWindows, err_: jsc.Maybe(void)) void { bun.sys.syslog("mkdirp complete", .{}); assert(this.err == null); this.err = if (err_ == .err) err_.err else null; - this.event_loop.enqueueTaskConcurrent(JSC.ConcurrentTask.create(JSC.ManagedTask.New(CopyFileWindows, onMkdirpComplete).init(this))); + this.event_loop.enqueueTaskConcurrent(jsc.ConcurrentTask.create(jsc.ManagedTask.New(CopyFileWindows, onMkdirpComplete).init(this))); } }; @@ -1145,7 +1145,7 @@ const unsupported_non_regular_file_error = SystemError{ .syscall = bun.String.static("fstat"), }; -pub const CopyFilePromiseTask = JSC.ConcurrentPromiseTask(CopyFile); +pub const CopyFilePromiseTask = jsc.ConcurrentPromiseTask(CopyFile); pub const CopyFilePromiseTaskEventLoopTask = CopyFilePromiseTask.EventLoopTask; const std = @import("std"); @@ -1156,10 +1156,10 @@ const assert = bun.assert; const webcore = bun.webcore; const libuv = bun.windows.libuv; -const JSC = bun.jsc; -const JSGlobalObject = JSC.JSGlobalObject; -const JSValue = JSC.JSValue; -const SystemError = JSC.SystemError; +const jsc = bun.jsc; +const JSGlobalObject = jsc.JSGlobalObject; +const JSValue = jsc.JSValue; +const SystemError = jsc.SystemError; const Blob = webcore.Blob; const SizeType = Blob.SizeType; diff --git a/src/bun.js/webcore/blob/read_file.zig b/src/bun.js/webcore/blob/read_file.zig index b4282e1ef2..a3de215b72 100644 --- a/src/bun.js/webcore/blob/read_file.zig +++ b/src/bun.js/webcore/blob/read_file.zig @@ -20,12 +20,12 @@ pub fn NewReadFileHandler(comptime Function: anytype) type { if (blob.size > 0) blob.size = @min(@as(SizeType, @truncate(bytes.len)), blob.size); const WrappedFn = struct { - pub fn wrapped(b: *Blob, g: *JSGlobalObject, by: []u8) JSC.JSValue { - return JSC.toJSHostCall(g, @src(), Function, .{ b, g, by, .temporary }); + pub fn wrapped(b: *Blob, g: *JSGlobalObject, by: []u8) jsc.JSValue { + return jsc.toJSHostCall(g, @src(), Function, .{ b, g, by, .temporary }); } }; - JSC.AnyPromise.wrap(.{ .normal = promise }, globalThis, WrappedFn.wrapped, .{ &blob, globalThis, bytes }); + jsc.AnyPromise.wrap(.{ .normal = promise }, globalThis, WrappedFn.wrapped, .{ &blob, globalThis, bytes }); }, .err => |err| { promise.reject(globalThis, err.toErrorInstance(globalThis)); @@ -38,7 +38,7 @@ pub fn NewReadFileHandler(comptime Function: anytype) type { pub const ReadFileOnReadFileCallback = *const fn (ctx: *anyopaque, bytes: ReadFileResultType) void; pub const ReadFileRead = struct { buf: []u8, is_temporary: bool = false, total_size: SizeType = 0 }; pub const ReadFileResultType = SystemError.Maybe(ReadFileRead); -pub const ReadFileTask = JSC.WorkTask(ReadFile); +pub const ReadFileTask = jsc.WorkTask(ReadFile); pub const ReadFile = struct { file_store: FileStore, @@ -53,7 +53,7 @@ pub const ReadFile = struct { size: SizeType = 0, buffer: std.ArrayListUnmanaged(u8) = .{}, task: bun.ThreadPool.Task = undefined, - system_error: ?JSC.SystemError = null, + system_error: ?jsc.SystemError = null, errno: ?anyerror = null, onCompleteCtx: *anyopaque = undefined, onCompleteCallback: ReadFileOnReadFileCallback = undefined, @@ -139,7 +139,7 @@ pub const ReadFile = struct { this.close_after_io = this.io_request.scheduled; } - JSC.WorkPool.schedule(&this.task); + jsc.WorkPool.schedule(&this.task); } pub fn onIOError(this: *ReadFile, err: bun.sys.Error) void { @@ -154,7 +154,7 @@ pub const ReadFile = struct { // unless pending IO has been scheduled in-between. this.close_after_io = this.io_request.scheduled; } - JSC.WorkPool.schedule(&this.task); + jsc.WorkPool.schedule(&this.task); } pub fn onRequestReadable(request: *io.Request) io.Action { @@ -187,7 +187,7 @@ pub const ReadFile = struct { } pub fn doRead(this: *ReadFile, buffer: []u8, read_len: *usize, retry: *bool) bool { - const result: JSC.Maybe(usize) = brk: { + const result: jsc.Maybe(usize) = brk: { if (std.posix.S.ISSOCK(this.file_store.mode)) { break :brk bun.sys.recvNonBlock(this.opened_fd, buffer); } @@ -233,7 +233,7 @@ pub const ReadFile = struct { return true; } - pub fn then(this: *ReadFile, _: *JSC.JSGlobalObject) void { + pub fn then(this: *ReadFile, _: *jsc.JSGlobalObject) void { const cb = this.onCompleteCallback; const cb_ctx = this.onCompleteCtx; @@ -322,13 +322,13 @@ pub const ReadFile = struct { if (this.store) |store| { if (store.data == .file) { - store.data.file.last_modified = JSC.toJSTime(stat.mtime().sec, stat.mtime().nsec); + store.data.file.last_modified = jsc.toJSTime(stat.mtime().sec, stat.mtime().nsec); } } if (bun.S.ISDIR(@intCast(stat.mode))) { this.errno = error.EISDIR; - this.system_error = JSC.SystemError{ + this.system_error = jsc.SystemError{ .code = bun.String.static("EISDIR"), .path = if (this.file_store.pathlike == .path) bun.String.cloneUTF8(this.file_store.pathlike.path.slice()) @@ -413,7 +413,7 @@ pub const ReadFile = struct { this.doReadLoop(); } - fn doReadLoopTask(task: *JSC.WorkPoolTask) void { + fn doReadLoopTask(task: *jsc.WorkPoolTask) void { var this: *ReadFile = @alignCast(@fieldParentPtr("task", task)); this.update(); @@ -536,7 +536,7 @@ pub const ReadFileUV = struct { read_eof: bool = false, size: SizeType = 0, buffer: std.ArrayListUnmanaged(u8) = .{}, - system_error: ?JSC.SystemError = null, + system_error: ?jsc.SystemError = null, errno: ?anyerror = null, on_complete_data: *anyopaque = undefined, on_complete_fn: ReadFileOnReadFileCallback, @@ -637,12 +637,12 @@ pub const ReadFileUV = struct { // keep in sync with resolveSizeAndLastModified if (this.store.data == .file) { - this.store.data.file.last_modified = JSC.toJSTime(stat.mtime().sec, stat.mtime().nsec); + this.store.data.file.last_modified = jsc.toJSTime(stat.mtime().sec, stat.mtime().nsec); } if (bun.S.ISDIR(@intCast(stat.mode))) { this.errno = error.EISDIR; - this.system_error = JSC.SystemError{ + this.system_error = jsc.SystemError{ .code = bun.String.static("EISDIR"), .path = if (this.file_store.pathlike == .path) bun.String.cloneUTF8(this.file_store.pathlike.path.slice()) @@ -805,10 +805,10 @@ const invalid_fd = bun.invalid_fd; const io = bun.io; const libuv = bun.windows.libuv; -const JSC = bun.JSC; -const JSGlobalObject = JSC.JSGlobalObject; -const JSPromise = JSC.JSPromise; -const SystemError = JSC.SystemError; +const jsc = bun.jsc; +const JSGlobalObject = jsc.JSGlobalObject; +const JSPromise = jsc.JSPromise; +const SystemError = jsc.SystemError; const Blob = bun.webcore.Blob; const ClosingState = Blob.ClosingState; diff --git a/src/bun.js/webcore/blob/write_file.zig b/src/bun.js/webcore/blob/write_file.zig index 4849be2a2a..8bf21f1e7b 100644 --- a/src/bun.js/webcore/blob/write_file.zig +++ b/src/bun.js/webcore/blob/write_file.zig @@ -1,13 +1,13 @@ pub const WriteFileResultType = SystemError.Maybe(SizeType); pub const WriteFileOnWriteFileCallback = *const fn (ctx: *anyopaque, count: WriteFileResultType) void; -pub const WriteFileTask = JSC.WorkTask(WriteFile); +pub const WriteFileTask = jsc.WorkTask(WriteFile); pub const WriteFile = struct { file_blob: Blob, bytes_blob: Blob, opened_fd: bun.FileDescriptor = invalid_fd, - system_error: ?JSC.SystemError = null, + system_error: ?jsc.SystemError = null, errno: ?anyerror = null, task: bun.ThreadPool.Task = undefined, io_task: ?*WriteFileTask = null, @@ -38,7 +38,7 @@ pub const WriteFile = struct { pub fn onReady(this: *WriteFile) void { bloblog("WriteFile.onReady()", .{}); this.task = .{ .callback = &doWriteLoopTask }; - JSC.WorkPool.schedule(&this.task); + jsc.WorkPool.schedule(&this.task); } pub fn onIOError(this: *WriteFile, err: bun.sys.Error) void { @@ -46,7 +46,7 @@ pub const WriteFile = struct { this.errno = bun.errnoToZigErr(err.errno); this.system_error = err.toSystemError(); this.task = .{ .callback = &doWriteLoopTask }; - JSC.WorkPool.schedule(&this.task); + jsc.WorkPool.schedule(&this.task); } pub fn onRequestWritable(request: *io.Request) io.Action { @@ -122,7 +122,7 @@ pub const WriteFile = struct { const fd = this.opened_fd; bun.assert(fd != invalid_fd); - const result: JSC.Maybe(usize) = + const result: jsc.Maybe(usize) = // We do not use pwrite() because the file may not be // seekable (such as stdout) // @@ -161,7 +161,7 @@ pub const WriteFile = struct { return true; } - pub fn then(this: *WriteFile, _: *JSC.JSGlobalObject) void { + pub fn then(this: *WriteFile, _: *jsc.JSGlobalObject) void { const cb = this.onCompleteCallback; const cb_ctx = this.onCompleteCtx; @@ -280,7 +280,7 @@ pub const WriteFile = struct { this.doWriteLoop(); } - fn doWriteLoopTask(task: *JSC.WorkPoolTask) void { + fn doWriteLoopTask(task: *jsc.WorkPoolTask) void { var this: *WriteFile = @fieldParentPtr("task", task); // On macOS, we use one-shot mode, so we don't need to unregister. if (comptime Environment.isMac) { @@ -349,7 +349,7 @@ pub const WriteFileWindows = struct { fd: uv.uv_file = -1, err: ?bun.sys.Error = null, total_written: usize = 0, - event_loop: *JSC.EventLoop, + event_loop: *jsc.EventLoop, owned_fd: bool = false, @@ -358,7 +358,7 @@ pub const WriteFileWindows = struct { pub fn createWithCtx( file_blob: Blob, bytes_blob: Blob, - event_loop: *bun.JSC.EventLoop, + event_loop: *bun.jsc.EventLoop, onWriteFileContext: *anyopaque, onCompleteCallback: WriteFileOnWriteFileCallback, mkdirp_if_not_exists: bool, @@ -479,7 +479,7 @@ pub const WriteFileWindows = struct { this.event_loop.refConcurrently(); const path = this.file_blob.store.?.data.file.pathlike.path.slice(); - JSC.Node.fs.Async.AsyncMkdirp.new(.{ + jsc.Node.fs.Async.AsyncMkdirp.new(.{ .completion = @ptrCast(&onMkdirpCompleteConcurrent), .completion_ctx = this, .path = bun.Dirname.dirname(u8, path) @@ -502,11 +502,11 @@ pub const WriteFileWindows = struct { this.open(); } - fn onMkdirpCompleteConcurrent(this: *WriteFileWindows, err_: JSC.Maybe(void)) void { + fn onMkdirpCompleteConcurrent(this: *WriteFileWindows, err_: jsc.Maybe(void)) void { log("mkdirp complete", .{}); bun.assert(this.err == null); this.err = if (err_ == .err) err_.err else null; - this.event_loop.enqueueTaskConcurrent(JSC.ConcurrentTask.create(JSC.ManagedTask.New(WriteFileWindows, onMkdirpComplete).init(this))); + this.event_loop.enqueueTaskConcurrent(jsc.ConcurrentTask.create(jsc.ManagedTask.New(WriteFileWindows, onMkdirpComplete).init(this))); } fn onWriteComplete(req: *uv.fs_t) callconv(.C) void { @@ -557,7 +557,7 @@ pub const WriteFileWindows = struct { this.onFinish(); } - pub fn toSystemError(this: *WriteFileWindows) ?JSC.SystemError { + pub fn toSystemError(this: *WriteFileWindows) ?jsc.SystemError { if (this.err) |err| { var sys_err = err; if (this.owned_fd) { @@ -616,7 +616,7 @@ pub const WriteFileWindows = struct { } pub fn create( - event_loop: *JSC.EventLoop, + event_loop: *jsc.EventLoop, file_blob: Blob, bytes_blob: Blob, comptime Context: type, @@ -649,7 +649,7 @@ pub const WriteFilePromise = struct { promise.reject(globalThis, err.toErrorInstance(globalThis)); }, .result => |wrote| { - promise.resolve(globalThis, JSC.JSValue.jsNumberFromUint64(wrote)); + promise.resolve(globalThis, jsc.JSValue.jsNumberFromUint64(wrote)); }, } } @@ -658,7 +658,7 @@ pub const WriteFilePromise = struct { pub const WriteFileWaitFromLockedValueTask = struct { file_blob: Blob, globalThis: *JSGlobalObject, - promise: JSC.JSPromise.Strong, + promise: jsc.JSPromise.Strong, mkdirp_if_not_exists: bool = false, pub fn thenWrap(this: *anyopaque, value: *Body.Value) void { @@ -731,14 +731,14 @@ const invalid_fd = bun.invalid_fd; const io = bun.io; const uv = bun.windows.libuv; -const JSC = bun.JSC; -const JSGlobalObject = JSC.JSGlobalObject; -const JSPromise = JSC.JSPromise; -const SystemError = JSC.SystemError; -const ZigString = JSC.ZigString; -const Body = JSC.WebCore.Body; +const jsc = bun.jsc; +const JSGlobalObject = jsc.JSGlobalObject; +const JSPromise = jsc.JSPromise; +const SystemError = jsc.SystemError; +const ZigString = jsc.ZigString; +const Body = jsc.WebCore.Body; -const Blob = JSC.WebCore.Blob; +const Blob = jsc.WebCore.Blob; const ClosingState = Blob.ClosingState; const FileCloser = Blob.FileCloser; const FileOpener = Blob.FileOpener; diff --git a/src/bun.js/webcore/encoding.zig b/src/bun.js/webcore/encoding.zig index 203bf41758..374341ed39 100644 --- a/src/bun.js/webcore/encoding.zig +++ b/src/bun.js/webcore/encoding.zig @@ -50,7 +50,7 @@ export fn Bun__encoding__constructFromLatin1(globalObject: *JSGlobalObject, inpu .base64 => constructFromU8(input, len, bun.default_allocator, .base64), else => unreachable, }; - return JSC.JSValue.createBuffer(globalObject, slice, globalObject.bunVM().allocator); + return jsc.JSValue.createBuffer(globalObject, slice, globalObject.bunVM().allocator); } export fn Bun__encoding__constructFromUTF16(globalObject: *JSGlobalObject, input: [*]const u16, len: usize, encoding: u8) JSValue { @@ -65,15 +65,15 @@ export fn Bun__encoding__constructFromUTF16(globalObject: *JSGlobalObject, input .latin1 => constructFromU16(input, len, bun.default_allocator, .latin1), else => unreachable, }; - return JSC.JSValue.createBuffer(globalObject, slice, globalObject.bunVM().allocator); + return jsc.JSValue.createBuffer(globalObject, slice, globalObject.bunVM().allocator); } // for SQL statement -export fn Bun__encoding__toStringUTF8(input: [*]const u8, len: usize, globalObject: *JSC.JSGlobalObject) JSValue { +export fn Bun__encoding__toStringUTF8(input: [*]const u8, len: usize, globalObject: *jsc.JSGlobalObject) JSValue { return toStringComptime(input[0..len], globalObject, .utf8); } -export fn Bun__encoding__toString(input: [*]const u8, len: usize, globalObject: *JSC.JSGlobalObject, encoding: u8) JSValue { +export fn Bun__encoding__toString(input: [*]const u8, len: usize, globalObject: *jsc.JSGlobalObject, encoding: u8) JSValue { return toString(input[0..len], globalObject, @enumFromInt(encoding)); } @@ -508,13 +508,14 @@ comptime { _ = &Bun__encoding__constructFromUTF16; } +const string = []const u8; + const std = @import("std"); const bun = @import("bun"); -const string = bun.string; const strings = bun.strings; -const JSC = bun.JSC; -const JSGlobalObject = JSC.JSGlobalObject; -const JSValue = JSC.JSValue; -const Encoding = JSC.Node.Encoding; +const jsc = bun.jsc; +const JSGlobalObject = jsc.JSGlobalObject; +const JSValue = jsc.JSValue; +const Encoding = jsc.Node.Encoding; diff --git a/src/bun.js/webcore/fetch.zig b/src/bun.js/webcore/fetch.zig index dbf555bee1..dca2fb18ef 100644 --- a/src/bun.js/webcore/fetch.zig +++ b/src/bun.js/webcore/fetch.zig @@ -59,7 +59,7 @@ pub const fetch_type_error_strings: JSTypeErrorEnum = brk: { }; pub const FetchTasklet = struct { - pub const ResumableSink = JSC.WebCore.ResumableFetchSink; + pub const ResumableSink = jsc.WebCore.ResumableFetchSink; const log = Output.scoped(.FetchTasklet, false); sink: ?*ResumableSink = null, @@ -76,15 +76,15 @@ pub const FetchTasklet = struct { /// buffer used to stream response to JS scheduled_response_buffer: MutableString = undefined, /// response weak ref we need this to track the response JS lifetime - response: JSC.Weak(FetchTasklet) = .{}, + response: jsc.Weak(FetchTasklet) = .{}, /// native response ref if we still need it when JS is discarted native_response: ?*Response = null, ignore_data: bool = false, /// stream strong ref if any is available - readable_stream_ref: JSC.WebCore.ReadableStream.Strong = .{}, + readable_stream_ref: jsc.WebCore.ReadableStream.Strong = .{}, request_headers: Headers = Headers{ .allocator = undefined }, - promise: JSC.JSPromise.Strong, - concurrent_task: JSC.ConcurrentTask = .{}, + promise: jsc.JSPromise.Strong, + concurrent_task: jsc.ConcurrentTask = .{}, poll_ref: Async.KeepAlive = .{}, memory_reporter: *bun.MemoryReportingAllocator, /// For Http Client requests @@ -97,16 +97,16 @@ pub const FetchTasklet = struct { /// We always clone url and proxy (if informed) url_proxy_buffer: []const u8 = "", - signal: ?*JSC.WebCore.AbortSignal = null, + signal: ?*jsc.WebCore.AbortSignal = null, signals: http.Signals = .{}, signal_store: http.Signals.Store = .{}, has_schedule_callback: std.atomic.Value(bool) = std.atomic.Value(bool).init(false), // must be stored because AbortSignal stores reason weakly - abort_reason: JSC.Strong.Optional = .empty, + abort_reason: jsc.Strong.Optional = .empty, // custom checkServerIdentity - check_server_identity: JSC.Strong.Optional = .empty, + check_server_identity: jsc.Strong.Optional = .empty, reject_unauthorized: bool = true, // Custom Hostname hostname: ?[]u8 = null, @@ -115,7 +115,7 @@ pub const FetchTasklet = struct { is_waiting_request_stream_start: bool = false, mutex: Mutex, - tracker: JSC.Debugger.AsyncTaskTracker, + tracker: jsc.Debugger.AsyncTaskTracker, ref_count: std.atomic.Value(u32) = std.atomic.Value(u32).init(1), @@ -141,14 +141,14 @@ pub const FetchTasklet = struct { // this is really unlikely to happen, but can happen // lets make sure that we always call deinit from main thread - this.javascript_vm.eventLoop().enqueueTaskConcurrent(JSC.ConcurrentTask.fromCallback(this, FetchTasklet.deinit)); + this.javascript_vm.eventLoop().enqueueTaskConcurrent(jsc.ConcurrentTask.fromCallback(this, FetchTasklet.deinit)); } } pub const HTTPRequestBody = union(enum) { AnyBlob: AnyBlob, Sendfile: http.SendFile, - ReadableStream: JSC.WebCore.ReadableStream.Strong, + ReadableStream: jsc.WebCore.ReadableStream.Strong, pub const Empty: HTTPRequestBody = .{ .AnyBlob = .{ .Blob = .{} } }; @@ -510,7 +510,7 @@ pub const FetchTasklet = struct { } pub fn onProgressUpdate(this: *FetchTasklet) void { - JSC.markBinding(@src()); + jsc.markBinding(@src()); log("onProgressUpdate", .{}); this.mutex.lock(); this.has_schedule_callback.store(false, .monotonic); @@ -598,9 +598,9 @@ pub const FetchTasklet = struct { } const success = this.result.isSuccess(); const result = switch (success) { - true => JSC.Strong.Optional.create(this.onResolve(), globalThis), + true => jsc.Strong.Optional.create(this.onResolve(), globalThis), false => brk: { - // in this case we wanna a JSC.Strong.Optional so we just convert it + // in this case we wanna a jsc.Strong.Optional so we just convert it var value = this.onReject(); const err = value.toJS(globalThis); if (this.sink) |sink| { @@ -612,10 +612,10 @@ pub const FetchTasklet = struct { promise_value.ensureStillAlive(); const Holder = struct { - held: JSC.Strong.Optional, - promise: JSC.Strong.Optional, - globalObject: *JSC.JSGlobalObject, - task: JSC.AnyTask, + held: jsc.Strong.Optional, + promise: jsc.Strong.Optional, + globalObject: *jsc.JSGlobalObject, + task: jsc.AnyTask, pub fn resolve(self: *@This()) void { // cleanup @@ -652,11 +652,11 @@ pub const FetchTasklet = struct { }; this.promise.strong = .empty; holder.task = switch (success) { - true => JSC.AnyTask.New(Holder, Holder.resolve).init(holder), - false => JSC.AnyTask.New(Holder, Holder.reject).init(holder), + true => jsc.AnyTask.New(Holder, Holder.resolve).init(holder), + false => jsc.AnyTask.New(Holder, Holder.reject).init(holder), }; - vm.enqueueTask(JSC.Task.init(&holder.task)); + vm.enqueueTask(jsc.Task.init(&holder.task)); } pub fn checkServerIdentity(this: *FetchTasklet, certificate_info: http.CertificateInfo) bool { @@ -767,7 +767,7 @@ pub const FetchTasklet = struct { else bun.String.empty; - const fetch_error = JSC.SystemError{ + const fetch_error = jsc.SystemError{ .code = bun.String.static(switch (this.result.fail.?) { error.ConnectionClosed => "ECONNRESET", else => |e| @errorName(e), @@ -857,18 +857,18 @@ pub const FetchTasklet = struct { return .{ .SystemError = fetch_error }; } - pub fn onReadableStreamAvailable(ctx: *anyopaque, globalThis: *JSC.JSGlobalObject, readable: JSC.WebCore.ReadableStream) void { + pub fn onReadableStreamAvailable(ctx: *anyopaque, globalThis: *jsc.JSGlobalObject, readable: jsc.WebCore.ReadableStream) void { const this = bun.cast(*FetchTasklet, ctx); - this.readable_stream_ref = JSC.WebCore.ReadableStream.Strong.init(readable, globalThis); + this.readable_stream_ref = jsc.WebCore.ReadableStream.Strong.init(readable, globalThis); } - pub fn onStartStreamingRequestBodyCallback(ctx: *anyopaque) JSC.WebCore.DrainResult { + pub fn onStartStreamingRequestBodyCallback(ctx: *anyopaque) jsc.WebCore.DrainResult { const this = bun.cast(*FetchTasklet, ctx); if (this.http) |http_| { http_.enableBodyStreaming(); } if (this.signal_store.aborted.load(.monotonic)) { - return JSC.WebCore.DrainResult{ + return jsc.WebCore.DrainResult{ .aborted = {}, }; } @@ -1024,18 +1024,18 @@ pub const FetchTasklet = struct { pub fn onResolve(this: *FetchTasklet) JSValue { log("onResolve", .{}); const response = bun.new(Response, this.toResponse()); - const response_js = Response.makeMaybePooled(@as(*JSC.JSGlobalObject, this.global_this), response); + const response_js = Response.makeMaybePooled(@as(*jsc.JSGlobalObject, this.global_this), response); response_js.ensureStillAlive(); - this.response = JSC.Weak(FetchTasklet).create(response_js, this.global_this, .FetchResponse, this); + this.response = jsc.Weak(FetchTasklet).create(response_js, this.global_this, .FetchResponse, this); this.native_response = response.ref(); return response_js; } pub fn get( allocator: std.mem.Allocator, - globalThis: *JSC.JSGlobalObject, + globalThis: *jsc.JSGlobalObject, fetch_options: FetchOptions, - promise: JSC.JSPromise.Strong, + promise: jsc.JSPromise.Strong, ) !*FetchTasklet { var jsc_vm = globalThis.bunVM(); var fetch_tasklet = try allocator.create(FetchTasklet); @@ -1065,7 +1065,7 @@ pub const FetchTasklet = struct { .url_proxy_buffer = fetch_options.url_proxy_buffer, .signal = fetch_options.signal, .hostname = fetch_options.hostname, - .tracker = JSC.Debugger.AsyncTaskTracker.init(jsc_vm), + .tracker = jsc.Debugger.AsyncTaskTracker.init(jsc_vm), .memory_reporter = fetch_options.memory_reporter, .check_server_identity = fetch_options.check_server_identity, .reject_unauthorized = fetch_options.reject_unauthorized, @@ -1174,7 +1174,7 @@ pub const FetchTasklet = struct { pub fn onWriteRequestDataDrain(this: *FetchTasklet) void { // ref until the main thread callback is called this.ref(); - this.javascript_vm.eventLoop().enqueueTaskConcurrent(JSC.ConcurrentTask.fromCallback(this, FetchTasklet.resumeRequestDataStream)); + this.javascript_vm.eventLoop().enqueueTaskConcurrent(jsc.ConcurrentTask.fromCallback(this, FetchTasklet.resumeRequestDataStream)); } /// This is ALWAYS called from the main thread @@ -1215,7 +1215,7 @@ pub const FetchTasklet = struct { return false; } - pub fn writeEndRequest(this: *FetchTasklet, err: ?JSC.JSValue) void { + pub fn writeEndRequest(this: *FetchTasklet, err: ?jsc.JSValue) void { log("writeEndRequest hasError? {}", .{err != null}); this.clearSink(); defer this.deref(); @@ -1257,12 +1257,12 @@ pub const FetchTasklet = struct { redirect_type: FetchRedirect = FetchRedirect.follow, proxy: ?ZigURL = null, url_proxy_buffer: []const u8 = "", - signal: ?*JSC.WebCore.AbortSignal = null, + signal: ?*jsc.WebCore.AbortSignal = null, globalThis: ?*JSGlobalObject, // Custom Hostname hostname: ?[]u8 = null, memory_reporter: *bun.MemoryReportingAllocator, - check_server_identity: JSC.Strong.Optional = .empty, + check_server_identity: jsc.Strong.Optional = .empty, unix_socket_path: ZigString.Slice, ssl_config: ?*SSLConfig = null, }; @@ -1271,7 +1271,7 @@ pub const FetchTasklet = struct { allocator: std.mem.Allocator, global: *JSGlobalObject, fetch_options: FetchOptions, - promise: JSC.JSPromise.Strong, + promise: jsc.JSPromise.Strong, ) !*FetchTasklet { http.HTTPThread.init(&.{}); var node = try get( @@ -1409,20 +1409,20 @@ fn dataURLResponse( } comptime { - const Bun__fetchPreconnect = JSC.toJSHostFn(Bun__fetchPreconnect_); + const Bun__fetchPreconnect = jsc.toJSHostFn(Bun__fetchPreconnect_); @export(&Bun__fetchPreconnect, .{ .name = "Bun__fetchPreconnect" }); } pub fn Bun__fetchPreconnect_( - globalObject: *JSC.JSGlobalObject, - callframe: *JSC.CallFrame, -) bun.JSError!JSC.JSValue { + globalObject: *jsc.JSGlobalObject, + callframe: *jsc.CallFrame, +) bun.JSError!jsc.JSValue { const arguments = callframe.arguments_old(1).slice(); if (arguments.len < 1) { return globalObject.throwNotEnoughArguments("fetch.preconnect", 1, arguments.len); } - var url_str = try JSC.URL.hrefFromJS(arguments[0], globalObject); + var url_str = try jsc.URL.hrefFromJS(arguments[0], globalObject); defer url_str.deref(); if (globalObject.hasException()) { @@ -1458,32 +1458,32 @@ pub fn Bun__fetchPreconnect_( } const StringOrURL = struct { - pub fn fromJS(value: JSC.JSValue, globalThis: *JSC.JSGlobalObject) bun.JSError!?bun.String { + pub fn fromJS(value: jsc.JSValue, globalThis: *jsc.JSGlobalObject) bun.JSError!?bun.String { if (value.isString()) { return try bun.String.fromJS(value, globalThis); } - const out = try JSC.URL.hrefFromJS(value, globalThis); + const out = try jsc.URL.hrefFromJS(value, globalThis); if (out.tag == .Dead) return null; return out; } }; comptime { - const Bun__fetch = JSC.toJSHostFn(Bun__fetch_); + const Bun__fetch = jsc.toJSHostFn(Bun__fetch_); @export(&Bun__fetch, .{ .name = "Bun__fetch" }); } /// Implementation of `Bun.fetch` pub fn Bun__fetch_( - ctx: *JSC.JSGlobalObject, - callframe: *JSC.CallFrame, -) bun.JSError!JSC.JSValue { - JSC.markBinding(@src()); + ctx: *jsc.JSGlobalObject, + callframe: *jsc.CallFrame, +) bun.JSError!jsc.JSValue { + jsc.markBinding(@src()); const globalThis = ctx; const arguments = callframe.arguments_old(2); - bun.Analytics.Features.fetch += 1; - const vm = JSC.VirtualMachine.get(); + bun.analytics.Features.fetch += 1; + const vm = jsc.VirtualMachine.get(); var memory_reporter = bun.default_allocator.create(bun.MemoryReportingAllocator) catch bun.outOfMemory(); // used to clean up dynamically allocated memory on error (a poor man's errdefer) @@ -1504,7 +1504,7 @@ pub fn Bun__fetch_( var headers: ?Headers = null; var method = Method.GET; - var args = JSC.CallFrame.ArgumentsSlice.init(vm, arguments.slice()); + var args = jsc.CallFrame.ArgumentsSlice.init(vm, arguments.slice()); var url = ZigURL{}; var first_arg = args.nextEat().?; @@ -1528,7 +1528,7 @@ pub fn Bun__fetch_( var proxy: ?ZigURL = null; var redirect_type: FetchRedirect = FetchRedirect.follow; - var signal: ?*JSC.WebCore.AbortSignal = null; + var signal: ?*jsc.WebCore.AbortSignal = null; // Custom Hostname var hostname: ?[]u8 = null; var range: ?[]u8 = null; @@ -1955,7 +1955,7 @@ pub fn Bun__fetch_( // proxy: string | undefined; url_proxy_buffer = extract_proxy: { - const objects_to_try = [_]JSC.JSValue{ + const objects_to_try = [_]jsc.JSValue{ options_object orelse .zero, request_init_object orelse .zero, }; @@ -1963,7 +1963,7 @@ pub fn Bun__fetch_( if (objects_to_try[i] != .zero) { if (try objects_to_try[i].get(globalThis, "proxy")) |proxy_arg| { if (proxy_arg.isString() and try proxy_arg.getLength(ctx) > 0) { - var href = try JSC.URL.hrefFromJS(proxy_arg, globalThis); + var href = try jsc.URL.hrefFromJS(proxy_arg, globalThis); if (href.tag == .Dead) { const err = ctx.toTypeError(.INVALID_ARG_VALUE, "fetch() proxy URL is invalid", .{}); is_error = true; @@ -2004,7 +2004,7 @@ pub fn Bun__fetch_( if (options_object) |options| { if (try options.get(globalThis, "signal")) |signal_| { if (!signal_.isUndefined()) { - if (signal_.as(JSC.WebCore.AbortSignal)) |signal__| { + if (signal_.as(jsc.WebCore.AbortSignal)) |signal__| { break :extract_signal signal__.ref(); } } @@ -2029,7 +2029,7 @@ pub fn Bun__fetch_( break :extract_signal null; } - if (signal_.as(JSC.WebCore.AbortSignal)) |signal__| { + if (signal_.as(jsc.WebCore.AbortSignal)) |signal__| { break :extract_signal signal__.ref(); } } @@ -2069,11 +2069,11 @@ pub fn Bun__fetch_( if (req.body.value == .Locked) { if (req.body.value.Locked.readable.has()) { - break :extract_body FetchTasklet.HTTPRequestBody{ .ReadableStream = JSC.WebCore.ReadableStream.Strong.init(req.body.value.Locked.readable.get(globalThis).?, globalThis) }; + break :extract_body FetchTasklet.HTTPRequestBody{ .ReadableStream = jsc.WebCore.ReadableStream.Strong.init(req.body.value.Locked.readable.get(globalThis).?, globalThis) }; } const readable = try req.body.value.toReadableStream(globalThis); if (!readable.isEmptyOrUndefinedOrNull() and req.body.value == .Locked and req.body.value.Locked.readable.has()) { - break :extract_body FetchTasklet.HTTPRequestBody{ .ReadableStream = JSC.WebCore.ReadableStream.Strong.init(req.body.value.Locked.readable.get(globalThis).?, globalThis) }; + break :extract_body FetchTasklet.HTTPRequestBody{ .ReadableStream = jsc.WebCore.ReadableStream.Strong.init(req.body.value.Locked.readable.get(globalThis).?, globalThis) }; } } @@ -2241,7 +2241,7 @@ pub fn Bun__fetch_( // Support blob: urls if (url_type == URLType.blob) { - if (JSC.WebCore.ObjectURLRegistry.singleton().resolveAndDupe(url_path_decoded)) |blob| { + if (jsc.WebCore.ObjectURLRegistry.singleton().resolveAndDupe(url_path_decoded)) |blob| { url_string = bun.String.createFormat("blob:{s}", .{url_path_decoded}) catch bun.outOfMemory(); break :blob blob; } else { @@ -2291,9 +2291,9 @@ pub fn Bun__fetch_( break :brk fullpath; }; - url_string = JSC.URL.fileURLFromString(bun.String.borrowUTF8(temp_file_path)); + url_string = jsc.URL.fileURLFromString(bun.String.borrowUTF8(temp_file_path)); - var pathlike: JSC.Node.PathOrFileDescriptor = .{ + var pathlike: jsc.Node.PathOrFileDescriptor = .{ .path = .{ .encoded_slice = ZigString.Slice.init(bun.default_allocator, try bun.default_allocator.dupe(u8, temp_file_path)), }, @@ -2346,10 +2346,10 @@ pub fn Bun__fetch_( prepare_body: { // is a S3 file we can use chunked here - if (try JSC.WebCore.ReadableStream.fromJS(try JSC.WebCore.ReadableStream.fromBlobCopyRef(globalThis, &body.AnyBlob.Blob, s3.MultiPartUploadOptions.DefaultPartSize), globalThis)) |stream| { + if (try jsc.WebCore.ReadableStream.fromJS(try jsc.WebCore.ReadableStream.fromBlobCopyRef(globalThis, &body.AnyBlob.Blob, s3.MultiPartUploadOptions.DefaultPartSize), globalThis)) |stream| { var old = body; defer old.detach(); - body = .{ .ReadableStream = JSC.WebCore.ReadableStream.Strong.init(stream, globalThis) }; + body = .{ .ReadableStream = jsc.WebCore.ReadableStream.Strong.init(stream, globalThis) }; break :prepare_body; } const rejected_value = JSPromise.dangerouslyCreateRejectedPromiseValueWithoutNotifyingVM(globalThis, globalThis.createErrorInstance("Failed to start s3 stream", .{})); @@ -2360,7 +2360,7 @@ pub fn Bun__fetch_( } if (body.needsToReadFile()) { prepare_body: { - const opened_fd_res: JSC.Maybe(bun.FileDescriptor) = switch (body.store().?.data.file.pathlike) { + const opened_fd_res: jsc.Maybe(bun.FileDescriptor) = switch (body.store().?.data.file.pathlike) { .fd => |fd| bun.sys.dup(fd), .path => |path| bun.sys.open(path.sliceZ(&globalThis.bunVM().nodeFS().sync_error_buf), if (Environment.isWindows) bun.O.RDONLY else bun.O.RDONLY | bun.O.NOCTTY, 0), }; @@ -2421,7 +2421,7 @@ pub fn Bun__fetch_( } // TODO: make this async + lazy - const res = JSC.Node.fs.NodeFS.readFile( + const res = jsc.Node.fs.NodeFS.readFile( globalThis.bunVM().nodeFS(), .{ .encoding = .buffer, @@ -2478,10 +2478,10 @@ pub fn Bun__fetch_( // we cannot direct stream to s3 we need to use multi part upload defer body.ReadableStream.deinit(); const Wrapper = struct { - promise: JSC.JSPromise.Strong, + promise: jsc.JSPromise.Strong, url: ZigURL, url_proxy_buffer: []const u8, - global: *JSC.JSGlobalObject, + global: *jsc.JSGlobalObject, pub const new = bun.TrivialNew(@This()); @@ -2495,7 +2495,7 @@ pub fn Bun__fetch_( .init = .{ .method = .PUT, .status_code = 200 }, .url = bun.String.createAtomIfPossible(self.url.href), }); - const response_js = Response.makeMaybePooled(@as(*JSC.JSGlobalObject, global), response); + const response_js = Response.makeMaybePooled(@as(*jsc.JSGlobalObject, global), response); response_js.ensureStillAlive(); self.promise.resolve(global, response_js); }, @@ -2517,7 +2517,7 @@ pub fn Bun__fetch_( }, .url = bun.String.createAtomIfPossible(self.url.href), }); - const response_js = Response.makeMaybePooled(@as(*JSC.JSGlobalObject, global), response); + const response_js = Response.makeMaybePooled(@as(*jsc.JSGlobalObject, global), response); response_js.ensureStillAlive(); self.promise.resolve(global, response_js); }, @@ -2527,9 +2527,9 @@ pub fn Bun__fetch_( } }; if (method != .PUT and method != .POST) { - return JSC.JSPromise.dangerouslyCreateRejectedPromiseValueWithoutNotifyingVM(globalThis, globalThis.createErrorInstance("Only POST and PUT do support body when using S3", .{})); + return jsc.JSPromise.dangerouslyCreateRejectedPromiseValueWithoutNotifyingVM(globalThis, globalThis.createErrorInstance("Only POST and PUT do support body when using S3", .{})); } - const promise = JSC.JSPromise.Strong.init(globalThis); + const promise = jsc.JSPromise.Strong.init(globalThis); const s3_stream = Wrapper.new(.{ .url = url, @@ -2690,12 +2690,13 @@ fn setHeaders(headers: *?Headers, new_headers: []const picohttp.Header, allocato } } +const string = []const u8; + const X509 = @import("../api/bun/x509.zig"); const std = @import("std"); const DataURL = @import("../../resolver/data_url.zig").DataURL; const Method = @import("../../http/Method.zig").Method; const ZigURL = @import("../../url.zig").URL; -const SSLConfig = @import("../api/server.zig").ServerConfig.SSLConfig; const bun = @import("bun"); const Async = bun.Async; @@ -2705,26 +2706,26 @@ const Mutex = bun.Mutex; const Output = bun.Output; const picohttp = bun.picohttp; const s3 = bun.S3; -const string = bun.string; const BoringSSL = bun.BoringSSL.c; const FetchHeaders = bun.webcore.FetchHeaders; const PosixToWinNormalizer = bun.path.PosixToWinNormalizer; - -const JSC = bun.JSC; -const JSGlobalObject = JSC.JSGlobalObject; -const JSPromise = JSC.JSPromise; -const JSValue = JSC.JSValue; -const VirtualMachine = JSC.VirtualMachine; -const ZigString = JSC.ZigString; -const JSType = JSC.C.JSType; - -const Body = JSC.WebCore.Body; -const Request = JSC.WebCore.Request; -const Response = JSC.WebCore.Response; - -const Blob = JSC.WebCore.Blob; -const AnyBlob = JSC.WebCore.Blob.Any; +const SSLConfig = bun.api.server.ServerConfig.SSLConfig; const http = bun.http; const FetchRedirect = http.FetchRedirect; const Headers = bun.http.Headers; + +const jsc = bun.jsc; +const JSGlobalObject = jsc.JSGlobalObject; +const JSPromise = jsc.JSPromise; +const JSValue = jsc.JSValue; +const VirtualMachine = jsc.VirtualMachine; +const ZigString = jsc.ZigString; +const JSType = jsc.C.JSType; + +const Body = jsc.WebCore.Body; +const Request = jsc.WebCore.Request; +const Response = jsc.WebCore.Response; + +const Blob = jsc.WebCore.Blob; +const AnyBlob = jsc.WebCore.Blob.Any; diff --git a/src/bun.js/webcore/prompt.zig b/src/bun.js/webcore/prompt.zig index 202f036e45..fd951d2fc3 100644 --- a/src/bun.js/webcore/prompt.zig +++ b/src/bun.js/webcore/prompt.zig @@ -1,15 +1,15 @@ //! Implements prompt, alert, and confirm Web API comptime { - const js_alert = JSC.toJSHostFn(alert); + const js_alert = jsc.toJSHostFn(alert); @export(&js_alert, .{ .name = "WebCore__alert" }); - const js_prompt = JSC.toJSHostFn(prompt.call); + const js_prompt = jsc.toJSHostFn(prompt.call); @export(&js_prompt, .{ .name = "WebCore__prompt" }); - const js_confirm = JSC.toJSHostFn(confirm); + const js_confirm = jsc.toJSHostFn(confirm); @export(&js_confirm, .{ .name = "WebCore__confirm" }); } /// https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-alert -fn alert(globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { +fn alert(globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const arguments = callframe.arguments_old(1).slice(); var output = bun.Output.writer(); const has_message = arguments.len != 0; @@ -59,7 +59,7 @@ fn alert(globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSErr return .js_undefined; } -fn confirm(globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { +fn confirm(globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const arguments = callframe.arguments_old(1).slice(); var output = bun.Output.writer(); const has_message = arguments.len != 0; @@ -195,9 +195,9 @@ pub const prompt = struct { /// https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-prompt pub fn call( - globalObject: *JSC.JSGlobalObject, - callframe: *JSC.CallFrame, - ) bun.JSError!JSC.JSValue { + globalObject: *jsc.JSGlobalObject, + callframe: *jsc.CallFrame, + ) bun.JSError!jsc.JSValue { const arguments = callframe.arguments_old(3).slice(); var state = std.heap.stackFallback(2048, bun.default_allocator); const allocator = state.get(); @@ -331,7 +331,7 @@ pub const prompt = struct { // 8. Let result be null if the user aborts, or otherwise the string // that the user responded with. - var result = JSC.ZigString.init(input.items); + var result = jsc.ZigString.init(input.items); result.markUTF8(); // 9. Invoke WebDriver BiDi user prompt closed with this, false if @@ -347,5 +347,5 @@ const std = @import("std"); const bun = @import("bun"); const Environment = bun.Environment; -const JSC = bun.jsc; const c = bun.c; +const jsc = bun.jsc; diff --git a/src/bun.js/webcore/streams.zig b/src/bun.js/webcore/streams.zig index 6ce0f3db37..2e9dce08a0 100644 --- a/src/bun.js/webcore/streams.zig +++ b/src/bun.js/webcore/streams.zig @@ -29,22 +29,22 @@ pub const Start = union(Tag) { done, }; - pub fn toJS(this: Start, globalThis: *JSGlobalObject) bun.JSError!JSC.JSValue { + pub fn toJS(this: Start, globalThis: *JSGlobalObject) bun.JSError!jsc.JSValue { switch (this) { .empty, .ready => { return .js_undefined; }, .chunk_size => |chunk| { - return JSC.JSValue.jsNumber(@as(Blob.SizeType, @intCast(chunk))); + return jsc.JSValue.jsNumber(@as(Blob.SizeType, @intCast(chunk))); }, .err => |err| { return globalThis.throwValue(err.toJS(globalThis)); }, .owned_and_done => |list| { - return JSC.ArrayBuffer.fromBytes(list.slice(), .Uint8Array).toJS(globalThis); + return jsc.ArrayBuffer.fromBytes(list.slice(), .Uint8Array).toJS(globalThis); }, .done => |list| { - return JSC.ArrayBuffer.create(globalThis, list.slice(), .Uint8Array); + return jsc.ArrayBuffer.create(globalThis, list.slice(), .Uint8Array); }, else => { return .js_undefined; @@ -220,18 +220,18 @@ pub const Result = union(Tag) { pub const StreamError = union(enum) { Error: Syscall.Error, - AbortReason: JSC.CommonAbortReason, + AbortReason: jsc.CommonAbortReason, - // TODO: use an explicit JSC.Strong.Optional here. - JSValue: JSC.JSValue, - WeakJSValue: JSC.JSValue, + // TODO: use an explicit jsc.Strong.Optional here. + JSValue: jsc.JSValue, + WeakJSValue: jsc.JSValue, const WasStrong = enum { Strong, Weak, }; - pub fn toJSWeak(this: *const @This(), globalObject: *JSC.JSGlobalObject) struct { JSC.JSValue, WasStrong } { + pub fn toJSWeak(this: *const @This(), globalObject: *jsc.JSGlobalObject) struct { jsc.JSValue, WasStrong } { return switch (this.*) { .Error => |err| { return .{ err.toJS(globalObject), WasStrong.Weak }; @@ -299,8 +299,8 @@ pub const Result = union(Tag) { pub const Future = union(enum) { none: void, promise: struct { - strong: JSC.JSPromise.Strong, - global: *JSC.JSGlobalObject, + strong: jsc.JSPromise.Strong, + global: *jsc.JSGlobalObject, }, handler: Handler, @@ -312,7 +312,7 @@ pub const Result = union(Tag) { } }; - pub fn promise(this: *Writable.Pending, globalThis: *JSC.JSGlobalObject) *JSPromise { + pub fn promise(this: *Writable.Pending, globalThis: *jsc.JSGlobalObject) *JSPromise { this.state = .pending; switch (this.future) { @@ -322,7 +322,7 @@ pub const Result = union(Tag) { else => { this.future = .{ .promise = .{ - .strong = JSC.JSPromise.Strong.init(globalThis), + .strong = jsc.JSPromise.Strong.init(globalThis), .global = globalThis, }, }; @@ -394,18 +394,18 @@ pub const Result = union(Tag) { pub fn toJS(this: Writable, globalThis: *JSGlobalObject) JSValue { return switch (this) { - .err => |err| JSC.JSPromise.rejectedPromise(globalThis, err.toJS(globalThis)).toJS(), + .err => |err| jsc.JSPromise.rejectedPromise(globalThis, err.toJS(globalThis)).toJS(), - .owned => |len| JSC.JSValue.jsNumber(len), - .owned_and_done => |len| JSC.JSValue.jsNumber(len), - .temporary_and_done => |len| JSC.JSValue.jsNumber(len), - .temporary => |len| JSC.JSValue.jsNumber(len), - .into_array => |len| JSC.JSValue.jsNumber(len), - .into_array_and_done => |len| JSC.JSValue.jsNumber(len), + .owned => |len| jsc.JSValue.jsNumber(len), + .owned_and_done => |len| jsc.JSValue.jsNumber(len), + .temporary_and_done => |len| jsc.JSValue.jsNumber(len), + .temporary => |len| jsc.JSValue.jsNumber(len), + .into_array => |len| jsc.JSValue.jsNumber(len), + .into_array_and_done => |len| jsc.JSValue.jsNumber(len), // false == controller.close() // undefined == noop, but we probably won't send it - .done => JSC.JSValue.jsBoolean(true), + .done => jsc.JSValue.jsBoolean(true), .pending => |pending| pending.promise(globalThis).toJS(), }; @@ -427,8 +427,8 @@ pub const Result = union(Tag) { this.state = .pending; } - pub fn promise(this: *Pending, globalObject: *JSC.JSGlobalObject) *JSC.JSPromise { - const prom = JSC.JSPromise.create(globalObject); + pub fn promise(this: *Pending, globalObject: *jsc.JSGlobalObject) *jsc.JSPromise { + const prom = jsc.JSPromise.create(globalObject); this.future = .{ .promise = .{ .promise = prom, @@ -441,7 +441,7 @@ pub const Result = union(Tag) { pub fn runOnNextTick(this: *Pending) void { if (this.state != .pending) return; - const vm = JSC.VirtualMachine.get(); + const vm = jsc.VirtualMachine.get(); if (vm.isShuttingDown()) { return; } @@ -449,7 +449,7 @@ pub const Result = union(Tag) { const clone = bun.create(bun.default_allocator, Pending, this.*); this.state = .none; this.result = .{ .done = {} }; - vm.eventLoop().enqueueTask(JSC.Task.init(clone)); + vm.eventLoop().enqueueTask(jsc.Task.init(clone)); } pub fn runFromJSThread(this: *Pending) void { @@ -461,7 +461,7 @@ pub const Result = union(Tag) { pub const Future = union(enum) { promise: struct { promise: *JSPromise, - globalThis: *JSC.JSGlobalObject, + globalThis: *jsc.JSGlobalObject, }, handler: Handler, @@ -517,7 +517,7 @@ pub const Result = union(Tag) { }; } - pub fn fulfillPromise(result: *Result, promise: *JSC.JSPromise, globalThis: *JSC.JSGlobalObject) void { + pub fn fulfillPromise(result: *Result, promise: *jsc.JSPromise, globalThis: *jsc.JSGlobalObject) void { const vm = globalThis.bunVM(); const loop = vm.eventLoop(); const promise_value = promise.toJS(); @@ -557,7 +557,7 @@ pub const Result = union(Tag) { } pub fn toJS(this: *const Result, globalThis: *JSGlobalObject) bun.JSError!JSValue { - if (JSC.VirtualMachine.get().isShuttingDown()) { + if (jsc.VirtualMachine.get().isShuttingDown()) { var that = this.*; that.deinit(); return .zero; @@ -565,30 +565,30 @@ pub const Result = union(Tag) { switch (this.*) { .owned => |list| { - return JSC.ArrayBuffer.fromBytes(list.slice(), .Uint8Array).toJS(globalThis); + return jsc.ArrayBuffer.fromBytes(list.slice(), .Uint8Array).toJS(globalThis); }, .owned_and_done => |list| { - return JSC.ArrayBuffer.fromBytes(list.slice(), .Uint8Array).toJS(globalThis); + return jsc.ArrayBuffer.fromBytes(list.slice(), .Uint8Array).toJS(globalThis); }, .temporary => |temp| { - var array = try JSC.JSValue.createUninitializedUint8Array(globalThis, temp.len); + var array = try jsc.JSValue.createUninitializedUint8Array(globalThis, temp.len); var slice_ = array.asArrayBuffer(globalThis).?.slice(); const temp_slice = temp.slice(); @memcpy(slice_[0..temp_slice.len], temp_slice); return array; }, .temporary_and_done => |temp| { - var array = try JSC.JSValue.createUninitializedUint8Array(globalThis, temp.len); + var array = try jsc.JSValue.createUninitializedUint8Array(globalThis, temp.len); var slice_ = array.asArrayBuffer(globalThis).?.slice(); const temp_slice = temp.slice(); @memcpy(slice_[0..temp_slice.len], temp_slice); return array; }, .into_array => |array| { - return JSC.JSValue.jsNumberFromInt64(array.len); + return jsc.JSValue.jsNumberFromInt64(array.len); }, .into_array_and_done => |array| { - return JSC.JSValue.jsNumberFromInt64(array.len); + return jsc.JSValue.jsNumberFromInt64(array.len); }, .pending => |pending| { const promise = pending.promise(globalThis).toJS(); @@ -602,13 +602,13 @@ pub const Result = union(Tag) { js_err.unprotect(); } js_err.ensureStillAlive(); - return JSC.JSPromise.rejectedPromise(globalThis, js_err).toJS(); + return jsc.JSPromise.rejectedPromise(globalThis, js_err).toJS(); }, // false == controller.close() // undefined == noop, but we probably won't send it .done => { - return JSC.JSValue.jsBoolean(false); + return jsc.JSValue.jsBoolean(false); }, } } @@ -713,7 +713,7 @@ pub fn HTTPServerWritable(comptime ssl: bool) type { allocator: std.mem.Allocator, done: bool = false, signal: Signal = .{}, - pending_flush: ?*JSC.JSPromise = null, + pending_flush: ?*jsc.JSPromise = null, wrote_at_start_of_flush: Blob.SizeType = 0, globalThis: *JSGlobalObject = undefined, highWaterMark: Blob.SizeType = 2048, @@ -874,7 +874,7 @@ pub fn HTTPServerWritable(comptime ssl: bool) type { return true; } - pub fn start(this: *@This(), stream_start: Start) JSC.Maybe(void) { + pub fn start(this: *@This(), stream_start: Start) jsc.Maybe(void) { if (this.aborted or this.res.hasResponded()) { this.markDone(); this.signal.close(null); @@ -920,7 +920,7 @@ pub fn HTTPServerWritable(comptime ssl: bool) type { return .{ .result = {} }; } - fn flushFromJSNoWait(this: *@This()) JSC.Maybe(JSValue) { + fn flushFromJSNoWait(this: *@This()) jsc.Maybe(JSValue) { log("flushFromJSNoWait", .{}); return .{ .result = JSValue.jsNumber(this.flushNoWait()) }; @@ -944,7 +944,7 @@ pub fn HTTPServerWritable(comptime ssl: bool) type { return 0; } - pub fn flushFromJS(this: *@This(), globalThis: *JSGlobalObject, wait: bool) JSC.Maybe(JSValue) { + pub fn flushFromJS(this: *@This(), globalThis: *JSGlobalObject, wait: bool) jsc.Maybe(JSValue) { log("flushFromJS({any})", .{wait}); this.unregisterAutoFlusher(); @@ -957,7 +957,7 @@ pub fn HTTPServerWritable(comptime ssl: bool) type { } if (this.buffer.len == 0 or this.done) { - return .{ .result = JSC.JSPromise.resolvedPromiseValue(globalThis, JSValue.jsNumberFromInt32(0)) }; + return .{ .result = jsc.JSPromise.resolvedPromiseValue(globalThis, JSValue.jsNumberFromInt32(0)) }; } if (!this.hasBackpressureAndIsTryEnd()) { @@ -965,11 +965,11 @@ pub fn HTTPServerWritable(comptime ssl: bool) type { assert(slice.len > 0); const success = this.send(slice); if (success) { - return .{ .result = JSC.JSPromise.resolvedPromiseValue(globalThis, JSValue.jsNumber(slice.len)) }; + return .{ .result = jsc.JSPromise.resolvedPromiseValue(globalThis, JSValue.jsNumber(slice.len)) }; } } this.wrote_at_start_of_flush = this.wrote; - this.pending_flush = JSC.JSPromise.create(globalThis); + this.pending_flush = jsc.JSPromise.create(globalThis); this.globalThis = globalThis; var promise_value = this.pending_flush.?.toJS(); promise_value.protect(); @@ -977,7 +977,7 @@ pub fn HTTPServerWritable(comptime ssl: bool) type { return .{ .result = promise_value }; } - pub fn flush(this: *@This()) JSC.Maybe(void) { + pub fn flush(this: *@This()) jsc.Maybe(void) { log("flush()", .{}); this.unregisterAutoFlusher(); @@ -1131,7 +1131,7 @@ pub fn HTTPServerWritable(comptime ssl: bool) type { } // In this case, it's always an error - pub fn end(this: *@This(), err: ?Syscall.Error) JSC.Maybe(void) { + pub fn end(this: *@This(), err: ?Syscall.Error) jsc.Maybe(void) { log("end({any})", .{err}); if (this.requested_end) { @@ -1160,11 +1160,11 @@ pub fn HTTPServerWritable(comptime ssl: bool) type { return .{ .result = {} }; } - pub fn endFromJS(this: *@This(), globalThis: *JSGlobalObject) JSC.Maybe(JSValue) { + pub fn endFromJS(this: *@This(), globalThis: *JSGlobalObject) jsc.Maybe(JSValue) { log("endFromJS()", .{}); if (this.requested_end) { - return .{ .result = JSC.JSValue.jsNumber(0) }; + return .{ .result = jsc.JSValue.jsNumber(0) }; } if (this.done or this.res.hasResponded()) { @@ -1172,7 +1172,7 @@ pub fn HTTPServerWritable(comptime ssl: bool) type { this.signal.close(null); this.markDone(); this.finalize(); - return .{ .result = JSC.JSValue.jsNumber(0) }; + return .{ .result = jsc.JSValue.jsNumber(0) }; } this.requested_end = true; @@ -1181,7 +1181,7 @@ pub fn HTTPServerWritable(comptime ssl: bool) type { if (readable.len > 0) { if (!this.send(readable)) { - this.pending_flush = JSC.JSPromise.create(globalThis); + this.pending_flush = jsc.JSPromise.create(globalThis); this.globalThis = globalThis; const value = this.pending_flush.?.toJS(); value.protect(); @@ -1196,7 +1196,7 @@ pub fn HTTPServerWritable(comptime ssl: bool) type { this.signal.close(null); this.finalize(); - return .{ .result = JSC.JSValue.jsNumber(this.wrote) }; + return .{ .result = jsc.JSValue.jsNumber(this.wrote) }; } pub fn sink(this: *@This()) Sink { @@ -1312,7 +1312,7 @@ pub fn HTTPServerWritable(comptime ssl: bool) type { this.pending_flush = null; const globalThis = this.globalThis; prom.toJS().unprotect(); - prom.resolve(globalThis, JSC.JSValue.jsNumber(this.wrote -| this.wrote_at_start_of_flush)); + prom.resolve(globalThis, jsc.JSValue.jsNumber(this.wrote -| this.wrote_at_start_of_flush)); this.wrote_at_start_of_flush = this.wrote; } } @@ -1331,8 +1331,8 @@ pub const NetworkSink = struct { signal: Signal = .{}, globalThis: *JSGlobalObject = undefined, highWaterMark: Blob.SizeType = 2048, - flushPromise: JSC.JSPromise.Strong = .{}, - endPromise: JSC.JSPromise.Strong = .{}, + flushPromise: jsc.JSPromise.Strong = .{}, + endPromise: jsc.JSPromise.Strong = .{}, ended: bool = false, done: bool = false, cancel: bool = false, @@ -1353,7 +1353,7 @@ pub const NetworkSink = struct { return null; } - pub fn start(this: *@This(), stream_start: Start) JSC.Maybe(void) { + pub fn start(this: *@This(), stream_start: Start) jsc.Maybe(void) { if (this.ended) { return .{ .result = {} }; } @@ -1394,15 +1394,15 @@ pub const NetworkSink = struct { pub fn onWritable(task: *bun.S3.MultiPartUpload, this: *@This(), flushed: u64) void { log("onWritable flushed: {d} state: {s}", .{ flushed, @tagName(task.state) }); if (this.flushPromise.hasValue()) { - this.flushPromise.resolve(this.globalThis, JSC.JSValue.jsNumber(flushed)); + this.flushPromise.resolve(this.globalThis, jsc.JSValue.jsNumber(flushed)); } } - pub fn flush(_: *@This()) JSC.Maybe(void) { + pub fn flush(_: *@This()) jsc.Maybe(void) { return .{ .result = {} }; } - pub fn flushFromJS(this: *@This(), globalThis: *JSGlobalObject, _: bool) JSC.Maybe(JSValue) { + pub fn flushFromJS(this: *@This(), globalThis: *JSGlobalObject, _: bool) jsc.Maybe(JSValue) { // still waiting for more data tobe flushed if (this.flushPromise.hasValue()) { return .{ .result = this.flushPromise.value() }; @@ -1410,18 +1410,18 @@ pub const NetworkSink = struct { // nothing todo here if (this.done) { - return .{ .result = JSC.JSPromise.resolvedPromiseValue(globalThis, JSValue.jsNumber(0)) }; + return .{ .result = jsc.JSPromise.resolvedPromiseValue(globalThis, JSValue.jsNumber(0)) }; } // flush more if (this.task) |task| { if (!task.isQueueEmpty()) { // we have something queued, we need to wait for the next flush - this.flushPromise = JSC.JSPromise.Strong.init(globalThis); + this.flushPromise = jsc.JSPromise.Strong.init(globalThis); return .{ .result = this.flushPromise.value() }; } } // we are done flushing no backpressure - return .{ .result = JSC.JSPromise.resolvedPromiseValue(globalThis, JSValue.jsNumber(0)) }; + return .{ .result = jsc.JSPromise.resolvedPromiseValue(globalThis, JSValue.jsNumber(0)) }; } pub fn finalizeAndDestroy(this: *@This()) void { this.finalize(); @@ -1483,7 +1483,7 @@ pub const NetworkSink = struct { return .{ .owned = @as(Blob.SizeType, @intCast(bytes.len)) }; } - pub fn end(this: *@This(), err: ?Syscall.Error) JSC.Maybe(void) { + pub fn end(this: *@This(), err: ?Syscall.Error) jsc.Maybe(void) { if (this.ended) { return .{ .result = {} }; } @@ -1498,7 +1498,7 @@ pub const NetworkSink = struct { this.signal.close(err); return .{ .result = {} }; } - pub fn endFromJS(this: *@This(), _: *JSGlobalObject) JSC.Maybe(JSValue) { + pub fn endFromJS(this: *@This(), _: *JSGlobalObject) jsc.Maybe(JSValue) { _ = this.end(null); if (this.endPromise.hasValue()) { // we are already waiting for the end @@ -1506,7 +1506,7 @@ pub const NetworkSink = struct { } if (this.task) |task| { // we need to wait for the task to end - this.endPromise = JSC.JSPromise.Strong.init(this.globalThis); + this.endPromise = jsc.JSPromise.Strong.init(this.globalThis); const value = this.endPromise.value(); if (!this.ended) { this.ended = true; @@ -1517,7 +1517,7 @@ pub const NetworkSink = struct { return .{ .result = value }; } // task already detached - return .{ .result = JSC.JSValue.jsNumber(0) }; + return .{ .result = jsc.JSValue.jsNumber(0) }; } pub fn toJS(this: *@This(), globalThis: *JSGlobalObject) JSValue { return JSSink.createObject(globalThis, this, 0); @@ -1537,39 +1537,39 @@ pub const NetworkSink = struct { }; pub const BufferAction = union(enum) { - text: JSC.JSPromise.Strong, - arrayBuffer: JSC.JSPromise.Strong, - blob: JSC.JSPromise.Strong, - bytes: JSC.JSPromise.Strong, - json: JSC.JSPromise.Strong, + text: jsc.JSPromise.Strong, + arrayBuffer: jsc.JSPromise.Strong, + blob: jsc.JSPromise.Strong, + bytes: jsc.JSPromise.Strong, + json: jsc.JSPromise.Strong, pub const Tag = @typeInfo(BufferAction).@"union".tag_type.?; - pub fn fulfill(this: *BufferAction, global: *JSC.JSGlobalObject, blob: *AnyBlob) void { + pub fn fulfill(this: *BufferAction, global: *jsc.JSGlobalObject, blob: *AnyBlob) void { blob.wrap(.{ .normal = this.swap() }, global, this.*); } - pub fn reject(this: *BufferAction, global: *JSC.JSGlobalObject, err: Result.StreamError) void { + pub fn reject(this: *BufferAction, global: *jsc.JSGlobalObject, err: Result.StreamError) void { this.swap().reject(global, err.toJSWeak(global)[0]); } - pub fn resolve(this: *BufferAction, global: *JSC.JSGlobalObject, result: JSC.JSValue) void { + pub fn resolve(this: *BufferAction, global: *jsc.JSGlobalObject, result: jsc.JSValue) void { this.swap().resolve(global, result); } - pub fn value(this: *BufferAction) JSC.JSValue { + pub fn value(this: *BufferAction) jsc.JSValue { return switch (this.*) { inline else => |promise| promise.value(), }; } - pub fn get(this: *BufferAction) *JSC.JSPromise { + pub fn get(this: *BufferAction) *jsc.JSPromise { return switch (this.*) { inline else => |promise| promise.get(), }; } - pub fn swap(this: *BufferAction) *JSC.JSPromise { + pub fn swap(this: *BufferAction) *jsc.JSPromise { return switch (this.*) { inline else => |*promise| promise.swap(), }; @@ -1640,6 +1640,8 @@ pub const AutoSizer = struct { } }; +const string = []const u8; + const std = @import("std"); const bun = @import("bun"); @@ -1648,21 +1650,20 @@ const Output = bun.Output; const Syscall = bun.sys; const assert = bun.assert; const default_allocator = bun.default_allocator; -const string = bun.string; const strings = bun.strings; const uws = bun.uws; -const JSC = bun.JSC; -const ArrayBuffer = JSC.ArrayBuffer; -const JSGlobalObject = JSC.JSGlobalObject; -const JSPromise = JSC.JSPromise; -const JSValue = JSC.JSValue; -const VirtualMachine = JSC.VirtualMachine; +const jsc = bun.jsc; +const ArrayBuffer = jsc.ArrayBuffer; +const JSGlobalObject = jsc.JSGlobalObject; +const JSPromise = jsc.JSPromise; +const JSValue = jsc.JSValue; +const VirtualMachine = jsc.VirtualMachine; -const WebCore = JSC.WebCore; +const WebCore = jsc.WebCore; const AutoFlusher = WebCore.AutoFlusher; const FileSink = WebCore.FileSink; -const Response = JSC.WebCore.Response; +const Response = jsc.WebCore.Response; const Sink = WebCore.Sink; const Blob = bun.webcore.Blob; diff --git a/src/bun.zig b/src/bun.zig index cd080b870b..5d93c3cfce 100644 --- a/src/bun.zig +++ b/src/bun.zig @@ -10,16 +10,16 @@ pub const Environment = @import("./env.zig"); pub const use_mimalloc = true; -pub const default_allocator: std.mem.Allocator = if (!use_mimalloc) - std.heap.c_allocator +pub const default_allocator: std.mem.Allocator = if (use_mimalloc) + allocators.c_allocator else - @import("./allocators/memory_allocator.zig").c_allocator; + std.heap.c_allocator; /// Zeroing memory allocator -pub const z_allocator: std.mem.Allocator = if (!use_mimalloc) - std.heap.c_allocator +pub const z_allocator: std.mem.Allocator = if (use_mimalloc) + allocators.z_allocator else - @import("./allocators/memory_allocator.zig").z_allocator; + std.heap.c_allocator; pub const callmod_inline: std.builtin.CallModifier = if (builtin.mode == .Debug) .auto else .always_inline; pub const callconv_inline: std.builtin.CallingConvention = if (builtin.mode == .Debug) .Unspecified else .Inline; @@ -160,8 +160,6 @@ pub const resolver = @import("./resolver/resolver.zig"); pub const DirIterator = @import("./bun.js/node/dir_iterator.zig"); pub const PackageJSON = @import("./resolver/package_json.zig").PackageJSON; pub const fmt = @import("./fmt.zig"); -pub const allocators = @import("./allocators.zig"); -pub const bun_js = @import("./bun_js.zig"); // This file is gennerated, but cant be placed in the build/debug/codegen // folder because zig will complain about outside-of-module stuff @@ -248,11 +246,6 @@ pub fn platformIOVecToSlice(iovec: PlatformIOVec) []u8 { pub const libarchive = @import("./libarchive/libarchive.zig"); -pub const StringTypes = @import("./string_types.zig"); -pub const stringZ = StringTypes.stringZ; -pub const string = StringTypes.string; -pub const CodePoint = StringTypes.CodePoint; - pub const paths = @import("./paths.zig"); pub const MAX_PATH_BYTES = paths.MAX_PATH_BYTES; pub const PathBuffer = paths.PathBuffer; @@ -385,8 +378,14 @@ pub const StringHashMapUnowned = struct { } }; }; -pub const OffsetList = @import("./baby_list.zig").OffsetList; -pub const BabyList = @import("./baby_list.zig").BabyList; + +pub const collections = @import("./collections.zig"); +pub const MultiArrayList = bun.collections.MultiArrayList; +pub const BabyList = collections.BabyList; +pub const OffsetList = collections.OffsetList; +pub const bit_set = collections.bit_set; +pub const HiveArray = collections.HiveArray; + pub const ByteList = BabyList(u8); pub const OffsetByteList = OffsetList(u8); @@ -446,8 +445,6 @@ pub fn clone(item: anytype, allocator: std.mem.Allocator) !@TypeOf(item) { return try allocator.dupe(Child, item); } -pub const StringBuilder = @import("./string.zig").StringBuilder; - pub const LinearFifo = @import("./linear_fifo.zig").LinearFifo; /// hash a string @@ -503,8 +500,6 @@ pub fn hash32(content: []const u8) u32 { return @as(u32, @truncate(res)); } -pub const HiveArray = @import("./hive_array.zig").HiveArray; - pub fn csprng(bytes: []u8) void { _ = BoringSSL.c.RAND_bytes(bytes.ptr, bytes.len); } @@ -617,8 +612,6 @@ pub const Bunfig = @import("./bunfig.zig").Bunfig; pub const HTTPThread = @import("./http.zig").HTTPThread; pub const http = @import("./http.zig"); -pub const Analytics = @import("./analytics/analytics_thread.zig"); - pub const TaggedPointer = ptr.TaggedPointer; pub const TaggedPointerUnion = ptr.TaggedPointerUnion; @@ -642,20 +635,25 @@ pub fn isHeapMemory(memory: anytype) bool { if (comptime use_mimalloc) { const Memory = @TypeOf(memory); if (comptime std.meta.trait.isSingleItemPtr(Memory)) { - return Mimalloc.mi_is_in_heap_region(memory); + return mimalloc.mi_is_in_heap_region(memory); } - return Mimalloc.mi_is_in_heap_region(std.mem.sliceAsBytes(memory).ptr); + return mimalloc.mi_is_in_heap_region(std.mem.sliceAsBytes(memory).ptr); } return false; } -pub const Mimalloc = @import("./allocators/mimalloc.zig"); -pub const AllocationScope = @import("./allocators/AllocationScope.zig"); +pub const allocators = @import("./allocators.zig"); +pub const mimalloc = allocators.mimalloc; +pub const MimallocArena = allocators.MimallocArena; +pub const AllocationScope = allocators.AllocationScope; +pub const NullableAllocator = allocators.NullableAllocator; +pub const MaxHeapAllocator = allocators.MaxHeapAllocator; +pub const MemoryReportingAllocator = allocators.MemoryReportingAllocator; pub const isSliceInBuffer = allocators.isSliceInBuffer; pub const isSliceInBufferT = allocators.isSliceInBufferT; -pub inline fn sliceInBuffer(stable: string, value: string) string { +pub inline fn sliceInBuffer(stable: []const u8, value: []const u8) []const u8 { if (allocators.sliceRange(stable, value)) |_| { return value; } @@ -680,18 +678,14 @@ pub fn rangeOfSliceInBuffer(slice: []const u8, buffer: []const u8) ?[2]u32 { // Please prefer `bun.FD.Optional.none` over this pub const invalid_fd: FileDescriptor = .invalid; -pub const simdutf = @import("./bun.js/bindings/bun-simdutf.zig"); - -/// Deprecated: Prefer the lowercase `jsc` since it is a namespace and not a struct. -pub const JSC = jsc; - +pub const bun_js = @import("./bun.js.zig"); /// Bindings to JavaScriptCore and other JavaScript primatives. /// Web and runtime-specific APIs should go in `webcore` and `api`. -pub const jsc = @import("./bun.js/jsc.zig"); +pub const jsc = bun_js.jsc; /// JavaScript Web APIs -pub const webcore = @import("./bun.js/webcore.zig"); +pub const webcore = bun_js.webcore; /// "api" in this context means "the Bun APIs", as in "the exposed JS APIs" -pub const api = @import("./bun.js/api.zig"); +pub const api = bun_js.api; pub const logger = @import("./logger.zig"); pub const default_thread_stack_size = ThreadPool.default_thread_stack_size; @@ -700,8 +694,9 @@ pub const uws = @import("./deps/uws.zig"); pub const BoringSSL = @import("./boringssl.zig"); pub const LOLHTML = @import("./deps/lol-html.zig"); pub const clap = @import("./deps/zig-clap/clap.zig"); -pub const analytics = @import("./analytics/analytics_thread.zig"); +pub const analytics = @import("./analytics.zig"); pub const zlib = @import("./zlib.zig"); +pub const simdutf = @import("./bun.js/bindings/bun-simdutf.zig"); pub var start_time: i128 = 0; @@ -791,7 +786,6 @@ pub fn openDirAbsoluteNotForDeletingOrRenaming(path_: []const u8) !std.fs.Dir { return fd.stdDir(); } -pub const MimallocArena = @import("./allocators/mimalloc_arena.zig").Arena; pub fn getRuntimeFeatureFlag(comptime flag: FeatureFlags.RuntimeFeatureFlag) bool { return struct { const state = enum(u8) { idk, disabled, enabled }; @@ -1048,7 +1042,7 @@ pub fn parseDouble(input: []const u8) !f64 { if (comptime Environment.isWasm) { return try std.fmt.parseFloat(f64, input); } - return JSC.wtf.parseDouble(input); + return jsc.wtf.parseDouble(input); } pub const SignalCode = enum(u8) { @@ -1186,7 +1180,7 @@ pub fn isMissingIOUring() bool { }; return Missing.is_missing_io_uring orelse brk: { - const kernel = Analytics.GenerateHeader.GeneratePlatform.kernelVersion(); + const kernel = analytics.GenerateHeader.GeneratePlatform.kernelVersion(); // io_uring was introduced in earlier versions of Linux, but it was not // really usable for us until 5.3 const result = kernel.major < 5 or (kernel.major == 5 and kernel.minor < 3); @@ -1195,22 +1189,23 @@ pub fn isMissingIOUring() bool { }; } -pub const CLI = @import("./cli.zig"); +pub const cli = @import("./cli.zig"); pub const install = @import("./install/install.zig"); pub const PackageManager = install.PackageManager; pub const RunCommand = @import("./cli/run_command.zig").RunCommand; pub const fs = @import("./fs.zig"); -pub const Transpiler = transpiler.Transpiler; pub const transpiler = @import("./transpiler.zig"); +pub const Transpiler = transpiler.Transpiler; pub const which = @import("./which.zig").which; pub const js_parser = @import("./js_parser.zig"); pub const js_printer = @import("./js_printer.zig"); pub const js_lexer = @import("./js_lexer.zig"); -pub const JSON = @import("./json_parser.zig"); -pub const JSAst = @import("./js_ast.zig"); -pub const bit_set = @import("./bit_set.zig"); +pub const ast = @import("./ast.zig"); + +pub const interchange = @import("./interchange.zig"); +pub const json = interchange.json; pub fn enumMap(comptime T: type, comptime args: anytype) (fn (T) [:0]const u8) { const Map = struct { @@ -1471,9 +1466,6 @@ pub const fast_debug_build_cmd = .None; pub const fast_debug_build_mode = fast_debug_build_cmd != .None and Environment.isDebug; -pub const MultiArrayList = @import("./multi_array_list.zig").MultiArrayList; -pub const NullableAllocator = @import("./allocators/NullableAllocator.zig"); - pub const renamer = @import("./renamer.zig"); // TODO: Rename to SourceMap as this is a struct. pub const sourcemap = @import("./sourcemap/sourcemap.zig"); @@ -1707,6 +1699,7 @@ pub fn reloadProcess( @compileError("unsupported platform for reloadProcess"); } } + pub var auto_reload_on_crash = false; pub const options = @import("./options.zig"); @@ -1732,7 +1725,7 @@ pub const StringSet = struct { }; } - pub fn keys(self: StringSet) []const string { + pub fn keys(self: StringSet) []const []const u8 { return self.map.keys(); } @@ -1760,13 +1753,13 @@ pub const StringSet = struct { } }; -pub const Schema = @import("./api/schema.zig"); +pub const schema = @import("./api/schema.zig"); pub const StringMap = struct { map: Map, dupe_keys: bool = false, - pub const Map = StringArrayHashMap(string); + pub const Map = StringArrayHashMap([]const u8); pub fn clone(self: StringMap) !StringMap { return StringMap{ @@ -1782,11 +1775,11 @@ pub const StringMap = struct { }; } - pub fn keys(self: StringMap) []const string { + pub fn keys(self: StringMap) []const []const u8 { return self.map.keys(); } - pub fn values(self: StringMap) []const string { + pub fn values(self: StringMap) []const []const u8 { return self.map.values(); } @@ -1794,8 +1787,8 @@ pub const StringMap = struct { return self.map.count(); } - pub fn toAPI(self: StringMap) Schema.Api.StringMap { - return Schema.Api.StringMap{ + pub fn toAPI(self: StringMap) schema.api.StringMap { + return schema.api.StringMap{ .keys = self.keys(), .values = self.values(), }; @@ -1839,7 +1832,6 @@ pub const StringMap = struct { pub const DotEnv = @import("./env_loader.zig"); pub const bundle_v2 = @import("./bundler/bundle_v2.zig"); -pub const js_ast = bun.bundle_v2.js_ast; pub const Loader = bundle_v2.Loader; pub const BundleV2 = bundle_v2.BundleV2; pub const ParseTask = bundle_v2.ParseTask; @@ -1895,8 +1887,6 @@ pub fn HiveRef(comptime T: type, comptime capacity: u16) type { }; } -pub const MaxHeapAllocator = @import("./allocators/max_heap_allocator.zig").MaxHeapAllocator; - pub const tracy = @import("./tracy.zig"); pub const trace = tracy.trace; @@ -1929,22 +1919,27 @@ pub fn openDirForPath(file_path: [:0]const u8) !std.fs.Dir { pub const Generation = u16; pub const zstd = @import("./deps/zstd.zig"); -pub const StringPointer = Schema.Api.StringPointer; +pub const StringPointer = schema.api.StringPointer; pub const StandaloneModuleGraph = @import("./StandaloneModuleGraph.zig").StandaloneModuleGraph; -pub const strings = @import("./string_immutable.zig"); -pub const String = _string.String; -pub const ZigString = JSC.ZigString; -pub const StringJoiner = _string.StringJoiner; -pub const SliceWithUnderlyingString = _string.SliceWithUnderlyingString; -pub const PathString = _string.PathString; -pub const HashedString = _string.HashedString; -pub const MutableString = _string.MutableString; +pub const string = @import("./string.zig"); +pub const String = string.String; +pub const ZigString = jsc.ZigString; +pub const StringJoiner = string.StringJoiner; +pub const SliceWithUnderlyingString = string.SliceWithUnderlyingString; +pub const PathString = string.PathString; +pub const HashedString = string.HashedString; +pub const MutableString = string.MutableString; +pub const StringBuilder = string.StringBuilder; + +/// Utilities for immutable strings +pub const strings = string.immutable; +pub const CodePoint = strings.CodePoint; pub const WTF = struct { /// The String type from WebKit's WTF library. - pub const StringImpl = _string.WTFStringImpl; - pub const _StringImplStruct = _string.WTFStringImplStruct; + pub const StringImpl = string.WTFStringImpl; + pub const _StringImplStruct = string.WTFStringImplStruct; }; pub const Wyhash11 = @import("./wyhash.zig").Wyhash11; @@ -2202,7 +2197,11 @@ pub const LazyBoolValue = enum { /// Create a lazily computed boolean value. /// Getter must be a function that takes a pointer to the parent struct and returns a boolean. /// Parent must be a type which contains the field we are getting. -pub fn LazyBool(comptime Getter: anytype, comptime Parent: type, comptime field: string) type { +pub fn LazyBool( + comptime Getter: anytype, + comptime Parent: type, + comptime field: []const u8, +) type { return struct { value: LazyBoolValue = .unknown, @@ -2601,9 +2600,13 @@ pub noinline fn outOfMemory() noreturn { crash_handler.crashHandler(.out_of_memory, null, @returnAddress()); } -pub fn todoPanic(src: std.builtin.SourceLocation, comptime format: string, args: anytype) noreturn { +pub fn todoPanic( + src: std.builtin.SourceLocation, + comptime format: []const u8, + args: anytype, +) noreturn { @branchHint(.cold); - bun.Analytics.Features.todo_panic = 1; + analytics.Features.todo_panic = 1; Output.panic("TODO: " ++ format ++ " ({s}:{d})", args ++ .{ src.file, src.line }); } @@ -2724,10 +2727,10 @@ pub fn exitThread() noreturn { pub fn deleteAllPoolsForThreadExit() void { const pools_to_delete = .{ - JSC.WebCore.ByteListPool, + jsc.WebCore.ByteListPool, bun.w_path_buffer_pool, bun.path_buffer_pool, - bun.JSC.ConsoleObject.Formatter.Visited.Pool, + jsc.ConsoleObject.Formatter.Visited.Pool, bun.js_parser.StringVoidMap.Pool, }; inline for (pools_to_delete) |pool| { @@ -2815,8 +2818,8 @@ pub fn getUserName(output_buffer: []u8) ?[]const u8 { pub inline fn resolveSourcePath( comptime root: enum { codegen, src }, - comptime sub_path: string, -) string { + comptime sub_path: []const u8, +) []const u8 { return comptime path: { @setEvalBranchQuota(2000000); var buf: bun.PathBuffer = undefined; @@ -3403,7 +3406,7 @@ pub fn memmove(output: []u8, input: []const u8) void { pub const hmac = @import("./hmac.zig"); pub const libdeflate = @import("./deps/libdeflate.zig"); -pub const bake = @import("./bake/bake.zig"); +pub const bake = @import("./bake.zig"); /// like std.enums.tagName, except it doesn't lose the sentinel value. pub fn tagName(comptime Enum: type, value: Enum) ?[:0]const u8 { @@ -3692,7 +3695,7 @@ pub inline fn itemOrNull(comptime T: type, slice: []const T, index: usize) ?T { return if (index < slice.len) slice[index] else null; } -pub const Maybe = bun.JSC.Node.Maybe; +pub const Maybe = jsc.Node.Maybe; /// To handle stack overflows: /// 1. StackCheck.init() @@ -3743,14 +3746,11 @@ pub fn freeSensitive(allocator: std.mem.Allocator, slice: anytype) void { allocator.free(slice); } -pub const server = @import("./bun.js/api/server.zig"); pub const macho = @import("./macho.zig"); pub const pe = @import("./pe.zig"); pub const valkey = @import("./valkey/index.zig"); pub const highway = @import("./highway.zig"); -pub const MemoryReportingAllocator = @import("./allocators/MemoryReportingAllocator.zig"); - pub const mach_port = if (Environment.isMac) std.c.mach_port_t else u32; pub const cpp = @import("cpp").bindings; @@ -3764,7 +3764,6 @@ pub fn contains(item: anytype, list: *const std.ArrayListUnmanaged(@TypeOf(item) } const CopyFile = @import("./copy_file.zig"); -const _string = @import("./string.zig"); const builtin = @import("builtin"); const std = @import("std"); const Allocator = std.mem.Allocator; diff --git a/src/bundler/AstBuilder.zig b/src/bundler/AstBuilder.zig index 65a9646816..24e718a45b 100644 --- a/src/bundler/AstBuilder.zig +++ b/src/bundler/AstBuilder.zig @@ -339,27 +339,18 @@ pub const AstBuilder = struct { } }; -pub const Ref = @import("../ast/base.zig").Ref; +pub const Ref = bun.ast.Ref; -pub const Index = @import("../ast/base.zig").Index; +pub const Index = bun.ast.Index; pub const DeferredBatchTask = bun.bundle_v2.DeferredBatchTask; pub const ThreadPool = bun.bundle_v2.ThreadPool; pub const ParseTask = bun.bundle_v2.ParseTask; +const string = []const u8; + const options = @import("../options.zig"); const std = @import("std"); -const BabyList = @import("../baby_list.zig").BabyList; - -const js_ast = @import("../js_ast.zig"); -const Binding = js_ast.Binding; -const E = js_ast.E; -const Expr = js_ast.Expr; -const Part = js_ast.Part; -const S = js_ast.S; -const Scope = js_ast.Scope; -const Stmt = js_ast.Stmt; -const Symbol = js_ast.Symbol; const Logger = @import("../logger.zig"); const Loc = Logger.Loc; @@ -370,5 +361,15 @@ const ImportRecord = bun.ImportRecord; const Output = bun.Output; const js_parser = bun.js_parser; const renamer = bun.renamer; -const string = bun.string; const strings = bun.strings; +const BabyList = bun.collections.BabyList; + +const js_ast = bun.ast; +const Binding = js_ast.Binding; +const E = js_ast.E; +const Expr = js_ast.Expr; +const Part = js_ast.Part; +const S = js_ast.S; +const Scope = js_ast.Scope; +const Stmt = js_ast.Stmt; +const Symbol = js_ast.Symbol; diff --git a/src/bundler/BundleThread.zig b/src/bundler/BundleThread.zig index ffdb676079..798f604b1c 100644 --- a/src/bundler/BundleThread.zig +++ b/src/bundler/BundleThread.zig @@ -92,7 +92,7 @@ pub fn BundleThread(CompletionStruct: type) type { instance.generation +|= 1; if (has_bundled) { - bun.Mimalloc.mi_collect(false); + bun.mimalloc.mi_collect(false); has_bundled = false; } @@ -102,7 +102,7 @@ pub fn BundleThread(CompletionStruct: type) type { /// This is called from `Bun.build` in JavaScript. fn generateInNewThread(completion: *CompletionStruct, generation: bun.Generation) !void { - var heap = try ThreadlocalArena.init(); + var heap = try ThreadLocalArena.init(); defer heap.deinit(); const allocator = heap.allocator(); @@ -121,9 +121,9 @@ pub fn BundleThread(CompletionStruct: type) type { transpiler, null, // TODO: Kit allocator, - JSC.AnyEventLoop.init(allocator), + jsc.AnyEventLoop.init(allocator), false, - JSC.WorkPool.get(), + jsc.WorkPool.get(), heap, ); @@ -161,9 +161,9 @@ pub fn BundleThread(CompletionStruct: type) type { }; } -pub const Ref = @import("../ast/base.zig").Ref; +pub const Ref = bun.ast.Ref; -pub const Index = @import("../ast/base.zig").Index; +pub const Index = bun.ast.Index; pub const DeferredBatchTask = bun.bundle_v2.DeferredBatchTask; pub const ThreadPool = bun.bundle_v2.ThreadPool; @@ -171,21 +171,22 @@ pub const ParseTask = bun.bundle_v2.ParseTask; const Logger = @import("../logger.zig"); const Timer = @import("../system_timer.zig"); -const allocators = @import("../allocators.zig"); -const js_ast = @import("../js_ast.zig"); const linker = @import("../linker.zig"); const options = @import("../options.zig"); const std = @import("std"); -const ThreadlocalArena = @import("../allocators/mimalloc_arena.zig").Arena; const bun = @import("bun"); const Async = bun.Async; const Environment = bun.Environment; -const JSC = bun.JSC; const Output = bun.Output; const Transpiler = bun.Transpiler; const bake = bun.bake; const default_allocator = bun.default_allocator; +const js_ast = bun.ast; +const jsc = bun.jsc; + +const allocators = bun.allocators; +const ThreadLocalArena = bun.allocators.MimallocArena; const bundler = bun.bundle_v2; const BundleV2 = bundler.BundleV2; diff --git a/src/bundler/Chunk.zig b/src/bundler/Chunk.zig index 5c73133e98..ef1f17f924 100644 --- a/src/bundler/Chunk.zig +++ b/src/bundler/Chunk.zig @@ -620,20 +620,18 @@ pub const Chunk = struct { }; }; -pub const Ref = @import("../ast/base.zig").Ref; +pub const Ref = bun.ast.Ref; -pub const Index = @import("../ast/base.zig").Index; +pub const Index = bun.ast.Index; pub const DeferredBatchTask = bun.bundle_v2.DeferredBatchTask; pub const ThreadPool = bun.bundle_v2.ThreadPool; pub const ParseTask = bun.bundle_v2.ParseTask; +const string = []const u8; + const HTMLImportManifest = @import("./HTMLImportManifest.zig"); const std = @import("std"); -const BabyList = @import("../baby_list.zig").BabyList; - -const js_ast = @import("../js_ast.zig"); -const Stmt = js_ast.Stmt; const options = @import("../options.zig"); const Loader = options.Loader; @@ -647,9 +645,12 @@ const StringJoiner = bun.StringJoiner; const default_allocator = bun.default_allocator; const renamer = bun.renamer; const sourcemap = bun.sourcemap; -const string = bun.string; const strings = bun.strings; const AutoBitSet = bun.bit_set.AutoBitSet; +const BabyList = bun.collections.BabyList; + +const js_ast = bun.ast; +const Stmt = js_ast.Stmt; const bundler = bun.bundle_v2; const BundleV2 = bundler.BundleV2; diff --git a/src/bundler/DeferredBatchTask.zig b/src/bundler/DeferredBatchTask.zig index a7f79c6941..32ac3b01e6 100644 --- a/src/bundler/DeferredBatchTask.zig +++ b/src/bundler/DeferredBatchTask.zig @@ -23,7 +23,7 @@ pub fn schedule(this: *DeferredBatchTask) void { bun.assert(!this.running); this.running = false; } - this.getBundleV2().jsLoopForPlugins().enqueueTaskConcurrent(JSC.ConcurrentTask.create(JSC.Task.init(this))); + this.getBundleV2().jsLoopForPlugins().enqueueTaskConcurrent(jsc.ConcurrentTask.create(jsc.Task.init(this))); } pub fn deinit(this: *DeferredBatchTask) void { @@ -43,10 +43,10 @@ pub fn runOnJSThread(this: *DeferredBatchTask) void { ) catch return; } -pub const Ref = @import("../ast/base.zig").Ref; +pub const Ref = bun.ast.Ref; -pub const Index = @import("../ast/base.zig").Index; +pub const Index = bun.ast.Index; const bun = @import("bun"); const Environment = bun.Environment; -const JSC = bun.JSC; +const jsc = bun.jsc; diff --git a/src/bundler/Graph.zig b/src/bundler/Graph.zig index a1529b02af..868256c8c3 100644 --- a/src/bundler/Graph.zig +++ b/src/bundler/Graph.zig @@ -1,7 +1,7 @@ const Graph = @This(); pool: *ThreadPool, -heap: ThreadlocalArena = .{}, +heap: ThreadLocalArena = .{}, /// This allocator is thread-local to the Bundler thread /// .allocator == .heap.allocator() allocator: std.mem.Allocator = undefined, @@ -98,20 +98,15 @@ pub fn drainDeferredTasks(this: *Graph, transpiler: *BundleV2) bool { return false; } -pub const Ref = @import("../ast/base.zig").Ref; +pub const Ref = bun.ast.Ref; -pub const Index = @import("../ast/base.zig").Index; +pub const Index = bun.ast.Index; + +const string = []const u8; const Logger = @import("../logger.zig"); const _resolver = @import("../resolver/resolver.zig"); -const allocators = @import("../allocators.zig"); const std = @import("std"); -const BabyList = @import("../baby_list.zig").BabyList; -const ThreadlocalArena = @import("../allocators/mimalloc_arena.zig").Arena; - -const js_ast = @import("../js_ast.zig"); -const JSAst = js_ast.BundledAst; -const ServerComponentBoundary = js_ast.ServerComponentBoundary; const options = @import("../options.zig"); const Loader = options.Loader; @@ -119,7 +114,14 @@ const Loader = options.Loader; const bun = @import("bun"); const MultiArrayList = bun.MultiArrayList; const default_allocator = bun.default_allocator; -const string = bun.string; +const BabyList = bun.collections.BabyList; + +const allocators = bun.allocators; +const ThreadLocalArena = bun.allocators.MimallocArena; + +const js_ast = bun.ast; +const JSAst = js_ast.BundledAst; +const ServerComponentBoundary = js_ast.ServerComponentBoundary; const AdditionalFile = bun.bundle_v2.AdditionalFile; const BundleV2 = bun.bundle_v2.BundleV2; diff --git a/src/bundler/HTMLImportManifest.zig b/src/bundler/HTMLImportManifest.zig index 329da265ac..24e3387066 100644 --- a/src/bundler/HTMLImportManifest.zig +++ b/src/bundler/HTMLImportManifest.zig @@ -55,7 +55,7 @@ fn writeEntryItem( path: []const u8, hash: u64, loader: options.Loader, - kind: bun.JSC.API.BuildArtifact.OutputKind, + kind: bun.jsc.API.BuildArtifact.OutputKind, ) !void { try writer.writeAll("{"); diff --git a/src/bundler/LinkerContext.zig b/src/bundler/LinkerContext.zig index ecdb9b3e64..6a3ecc132e 100644 --- a/src/bundler/LinkerContext.zig +++ b/src/bundler/LinkerContext.zig @@ -1830,7 +1830,7 @@ pub const LinkerContext = struct { // "undefined" instead of emitting an error. symbol.import_item_status = .missing; - if (c.resolver.opts.target == .browser and JSC.ModuleLoader.HardcodedModule.Alias.has(next_source.path.pretty, .bun)) { + if (c.resolver.opts.target == .browser and jsc.ModuleLoader.HardcodedModule.Alias.has(next_source.path.pretty, .bun)) { c.log.addRangeWarningFmtWithNote( source, r, @@ -2463,37 +2463,25 @@ pub const LinkerContext = struct { } }; -pub const Ref = @import("../ast/base.zig").Ref; +pub const Ref = bun.ast.Ref; pub const ThreadPoolLib = bun.ThreadPool; pub const Fs = @import("../fs.zig"); -pub const Index = @import("../ast/base.zig").Index; +pub const Index = bun.ast.Index; const debugTreeShake = Output.scoped(.TreeShake, true); pub const DeferredBatchTask = bun.bundle_v2.DeferredBatchTask; pub const ThreadPool = bun.bundle_v2.ThreadPool; pub const ParseTask = bun.bundle_v2.ParseTask; +const string = []const u8; + const NodeFallbackModules = @import("../node_fallbacks.zig"); const js_printer = @import("../js_printer.zig"); const lex = @import("../js_lexer.zig"); const linker = @import("../linker.zig"); const runtime = @import("../runtime.zig"); const std = @import("std"); -const BabyList = @import("../baby_list.zig").BabyList; - -const js_ast = @import("../js_ast.zig"); -const B = js_ast.B; -const Binding = js_ast.Binding; -const Dependency = js_ast.Dependency; -const E = js_ast.E; -const Expr = js_ast.Expr; -const G = js_ast.G; -const JSAst = js_ast.BundledAst; -const Part = js_ast.Part; -const S = js_ast.S; -const Stmt = js_ast.Stmt; -const Symbol = js_ast.Symbol; const Logger = @import("../logger.zig"); const Loc = Logger.Loc; @@ -2516,13 +2504,23 @@ const bake = bun.bake; const base64 = bun.base64; const renamer = bun.renamer; const sourcemap = bun.sourcemap; -const string = bun.string; const strings = bun.strings; const sync = bun.threading; const AutoBitSet = bun.bit_set.AutoBitSet; +const BabyList = bun.collections.BabyList; -const JSC = bun.JSC; -const EventLoop = bun.JSC.AnyEventLoop; +const js_ast = bun.ast; +const B = js_ast.B; +const Binding = js_ast.Binding; +const Dependency = js_ast.Dependency; +const E = js_ast.E; +const Expr = js_ast.Expr; +const G = js_ast.G; +const JSAst = js_ast.BundledAst; +const Part = js_ast.Part; +const S = js_ast.S; +const Stmt = js_ast.Stmt; +const Symbol = js_ast.Symbol; const bundler = bun.bundle_v2; const AdditionalFile = bundler.AdditionalFile; @@ -2544,3 +2542,6 @@ const StableRef = bundler.StableRef; const WrapKind = bundler.WrapKind; const genericPathWithPrettyInitialized = bundler.genericPathWithPrettyInitialized; const logPartDependencyTree = bundler.logPartDependencyTree; + +const jsc = bun.jsc; +const EventLoop = bun.jsc.AnyEventLoop; diff --git a/src/bundler/LinkerGraph.zig b/src/bundler/LinkerGraph.zig index 03bace0138..45330f3d93 100644 --- a/src/bundler/LinkerGraph.zig +++ b/src/bundler/LinkerGraph.zig @@ -442,10 +442,9 @@ pub const File = struct { pub const List = MultiArrayList(File); }; -const std = @import("std"); +const string = []const u8; -const js_ast = @import("../js_ast.zig"); -const Symbol = @import("../js_ast.zig").Symbol; +const std = @import("std"); const bun = @import("bun"); const BabyList = bun.BabyList; @@ -453,7 +452,9 @@ const Environment = bun.Environment; const ImportRecord = bun.ImportRecord; const MultiArrayList = bun.MultiArrayList; const Output = bun.Output; -const string = bun.string; + +const js_ast = bun.ast; +const Symbol = js_ast.Symbol; const AutoBitSet = bun.bit_set.AutoBitSet; const BitSet = bun.bit_set.DynamicBitSetUnmanaged; diff --git a/src/bundler/ParseTask.zig b/src/bundler/ParseTask.zig index 63a4558e45..6f876152ba 100644 --- a/src/bundler/ParseTask.zig +++ b/src/bundler/ParseTask.zig @@ -948,7 +948,7 @@ const OnBeforeParsePlugin = struct { return 0; } - pub fn run(this: *OnBeforeParsePlugin, plugin: *JSC.API.JSBundler.Plugin, from_plugin: *bool) !CacheEntry { + pub fn run(this: *OnBeforeParsePlugin, plugin: *jsc.API.JSBundler.Plugin, from_plugin: *bool) !CacheEntry { var args = OnBeforeParseArguments{ .context = this, .path_ptr = this.file_path.text.ptr, @@ -1348,7 +1348,7 @@ pub fn runFromThreadPool(this: *ParseTask) void { switch (worker.ctx.loop().*) { .js => |jsc_event_loop| { - jsc_event_loop.enqueueTaskConcurrent(JSC.ConcurrentTask.fromCallback(result, onComplete)); + jsc_event_loop.enqueueTaskConcurrent(jsc.ConcurrentTask.fromCallback(result, onComplete)); }, .mini => |*mini| { mini.enqueueTaskConcurrentWithExtraCtx( @@ -1366,32 +1366,24 @@ pub fn onComplete(result: *Result) void { BundleV2.onParseTaskComplete(result, result.ctx); } -pub const Ref = @import("../ast/base.zig").Ref; +pub const Ref = bun.ast.Ref; -pub const Index = @import("../ast/base.zig").Index; +pub const Index = bun.ast.Index; pub const DeferredBatchTask = bun.bundle_v2.DeferredBatchTask; pub const ThreadPool = bun.bundle_v2.ThreadPool; +const string = []const u8; + const Fs = @import("../fs.zig"); const HTMLScanner = @import("../HTMLScanner.zig"); const NodeFallbackModules = @import("../node_fallbacks.zig"); const linker = @import("../linker.zig"); const runtime = @import("../runtime.zig"); const std = @import("std"); -const BabyList = @import("../baby_list.zig").BabyList; -const TOML = @import("../toml/toml_parser.zig").TOML; const URL = @import("../url.zig").URL; const CacheEntry = @import("../cache.zig").Fs.Entry; -const js_ast = @import("../js_ast.zig"); -const E = js_ast.E; -const Expr = js_ast.Expr; -const G = js_ast.G; -const JSAst = js_ast.BundledAst; -const Part = js_ast.Part; -const Symbol = js_ast.Symbol; - const Logger = @import("../logger.zig"); const Loc = Logger.Loc; @@ -1413,14 +1405,23 @@ const bake = bun.bake; const base64 = bun.base64; const default_allocator = bun.default_allocator; const js_parser = bun.js_parser; -const string = bun.string; const strings = bun.strings; +const BabyList = bun.collections.BabyList; +const TOML = bun.interchange.toml.TOML; -const JSC = bun.JSC; -const EventLoop = bun.JSC.AnyEventLoop; +const js_ast = bun.ast; +const E = js_ast.E; +const Expr = js_ast.Expr; +const G = js_ast.G; +const JSAst = js_ast.BundledAst; +const Part = js_ast.Part; +const Symbol = js_ast.Symbol; const bundler = bun.bundle_v2; const BundleV2 = bundler.BundleV2; const ContentHasher = bundler.ContentHasher; const UseDirective = bundler.UseDirective; const targetFromHashbang = bundler.targetFromHashbang; + +const jsc = bun.jsc; +const EventLoop = bun.jsc.AnyEventLoop; diff --git a/src/bundler/ServerComponentParseTask.zig b/src/bundler/ServerComponentParseTask.zig index 336fd506c1..6da3484259 100644 --- a/src/bundler/ServerComponentParseTask.zig +++ b/src/bundler/ServerComponentParseTask.zig @@ -51,7 +51,7 @@ fn taskCallbackWrap(thread_pool_task: *ThreadPoolLib.Task) void { switch (worker.ctx.loop().*) { .js => |jsc_event_loop| { - jsc_event_loop.enqueueTaskConcurrent(JSC.ConcurrentTask.fromCallback(result, ParseTask.onComplete)); + jsc_event_loop.enqueueTaskConcurrent(jsc.ConcurrentTask.fromCallback(result, ParseTask.onComplete)); }, .mini => |*mini| { mini.enqueueTaskConcurrentWithExtraCtx( @@ -203,9 +203,9 @@ fn generateClientReferenceProxy(task: *ServerComponentParseTask, data: Data.Refe } } -pub const Ref = @import("../ast/base.zig").Ref; +pub const Ref = bun.ast.Ref; -pub const Index = @import("../ast/base.zig").Index; +pub const Index = bun.ast.Index; pub const DeferredBatchTask = bun.bundle_v2.DeferredBatchTask; pub const ThreadPool = bun.bundle_v2.ThreadPool; @@ -213,9 +213,20 @@ pub const ParseTask = bun.bundle_v2.ParseTask; const options = @import("../options.zig"); const std = @import("std"); -const BabyList = @import("../baby_list.zig").BabyList; -const js_ast = @import("../js_ast.zig"); +const Logger = @import("../logger.zig"); +const Loc = Logger.Loc; + +const bun = @import("bun"); +const OOM = bun.OOM; +const ThreadPoolLib = bun.ThreadPool; +const default_allocator = bun.default_allocator; +const js_parser = bun.js_parser; +const jsc = bun.jsc; +const strings = bun.strings; +const BabyList = bun.collections.BabyList; + +const js_ast = bun.ast; const B = js_ast.B; const Binding = js_ast.Binding; const E = js_ast.E; @@ -225,17 +236,6 @@ const JSAst = js_ast.BundledAst; const S = js_ast.S; const Stmt = js_ast.Stmt; -const Logger = @import("../logger.zig"); -const Loc = Logger.Loc; - -const bun = @import("bun"); -const JSC = bun.JSC; -const OOM = bun.OOM; -const ThreadPoolLib = bun.ThreadPool; -const default_allocator = bun.default_allocator; -const js_parser = bun.js_parser; -const strings = bun.strings; - const bundler = bun.bundle_v2; const AstBuilder = bundler.AstBuilder; const BundleV2 = bundler.BundleV2; diff --git a/src/bundler/ThreadPool.zig b/src/bundler/ThreadPool.zig index f4425a4d87..26c8871992 100644 --- a/src/bundler/ThreadPool.zig +++ b/src/bundler/ThreadPool.zig @@ -202,7 +202,7 @@ pub const ThreadPool = struct { } pub const Worker = struct { - heap: ThreadlocalArena = ThreadlocalArena{}, + heap: ThreadLocalArena = ThreadLocalArena{}, /// Thread-local memory allocator /// All allocations are freed in `deinit` at the very end of bundling. @@ -284,7 +284,7 @@ pub const ThreadPool = struct { this.has_created = true; Output.Source.configureThread(); - this.heap = ThreadlocalArena.init() catch unreachable; + this.heap = ThreadLocalArena.init() catch unreachable; this.allocator = this.heap.allocator(); const allocator = this.allocator; @@ -339,16 +339,13 @@ pub const ThreadPool = struct { }; }; -pub const Ref = @import("../ast/base.zig").Ref; +pub const Ref = bun.ast.Ref; -pub const Index = @import("../ast/base.zig").Index; +pub const Index = bun.ast.Index; const Logger = @import("../logger.zig"); -const allocators = @import("../allocators.zig"); -const js_ast = @import("../js_ast.zig"); const linker = @import("../linker.zig"); const std = @import("std"); -const ThreadlocalArena = @import("../allocators/mimalloc_arena.zig").Arena; const bun = @import("bun"); const Environment = bun.Environment; @@ -357,6 +354,10 @@ const Output = bun.Output; const ThreadPoolLib = bun.ThreadPool; const Transpiler = bun.Transpiler; const default_allocator = bun.default_allocator; +const js_ast = bun.ast; + +const allocators = bun.allocators; +const ThreadLocalArena = bun.allocators.MimallocArena; const BundleV2 = bun.bundle_v2.BundleV2; const LinkerContext = bun.bundle_v2.LinkerContext; diff --git a/src/bundler/bundle_v2.zig b/src/bundler/bundle_v2.zig index e6d1b3e0b9..c2872cae9f 100644 --- a/src/bundler/bundle_v2.zig +++ b/src/bundler/bundle_v2.zig @@ -47,7 +47,7 @@ pub const logPartDependencyTree = Output.scoped(.part_dep_tree, false); pub const MangledProps = std.AutoArrayHashMapUnmanaged(Ref, []const u8); pub const PathToSourceIndexMap = std.HashMapUnmanaged(u64, Index.Int, IdentityContext(u64), 80); -pub const Watcher = bun.JSC.hot_reloader.NewHotReloader(BundleV2, EventLoop, true); +pub const Watcher = bun.jsc.hot_reloader.NewHotReloader(BundleV2, EventLoop, true); /// This assigns a concise, predictable, and unique `.pretty` attribute to a Path. /// DevServer relies on pretty paths for identifying modules, so they must be unique. @@ -114,7 +114,7 @@ pub const BundleV2 = struct { graph: Graph, linker: LinkerContext, bun_watcher: ?*bun.Watcher, - plugins: ?*JSC.API.JSBundler.Plugin, + plugins: ?*jsc.API.JSBundler.Plugin, completion: ?*JSBundleCompletionTask, source_code_length: usize, @@ -146,7 +146,7 @@ pub const BundleV2 = struct { framework: bake.Framework, client_transpiler: *Transpiler, ssr_transpiler: *Transpiler, - plugins: ?*JSC.API.JSBundler.Plugin, + plugins: ?*jsc.API.JSBundler.Plugin, }; const debug = Output.scoped(.Bundle, false); @@ -155,8 +155,8 @@ pub const BundleV2 = struct { return &this.linker.loop; } - /// Returns the JSC.EventLoop where plugin callbacks can be queued up on - pub fn jsLoopForPlugins(this: *BundleV2) *JSC.EventLoop { + /// Returns the jsc.EventLoop where plugin callbacks can be queued up on + pub fn jsLoopForPlugins(this: *BundleV2) *jsc.EventLoop { bun.assert(this.plugins != null); if (this.completion) |completion| // From Bun.build @@ -165,7 +165,7 @@ pub const BundleV2 = struct { // From bake where the loop running the bundle is also the loop // running the plugins. .js => |jsc_event_loop| return jsc_event_loop, - // The CLI currently has no JSC event loop; for now, no plugin support + // The CLI currently has no jsc event loop; for now, no plugin support .mini => @panic("No JavaScript event loop for transpiler plugins to run on"), } } @@ -467,7 +467,7 @@ pub const BundleV2 = struct { /// This runs on the Bundle Thread. pub fn runResolver( this: *BundleV2, - import_record: bun.JSC.API.JSBundler.Resolve.MiniImportRecord, + import_record: bun.jsc.API.JSBundler.Resolve.MiniImportRecord, target: options.Target, ) void { const transpiler = this.transpilerForTarget(target); @@ -782,7 +782,7 @@ pub const BundleV2 = struct { event_loop: EventLoop, cli_watch_flag: bool, thread_pool: ?*ThreadPoolLib, - heap: ThreadlocalArena, + heap: ThreadLocalArena, ) !*BundleV2 { transpiler.env.loadTracy(); @@ -1343,7 +1343,7 @@ pub const BundleV2 = struct { if (path.len > 0 and // Check for either node or bun builtins // We don't use the list from .bun because that includes third-party packages in some cases. - !JSC.ModuleLoader.HardcodedModule.Alias.has(path, .node) and + !jsc.ModuleLoader.HardcodedModule.Alias.has(path, .node) and !strings.hasPrefixComptime(path, "bun:") and !strings.eqlComptime(path, "bun")) { @@ -1379,7 +1379,7 @@ pub const BundleV2 = struct { event_loop, enable_reloading, null, - try ThreadlocalArena.init(), + try ThreadLocalArena.init(), ); this.unique_key = generateUniqueKey(); @@ -1395,7 +1395,7 @@ pub const BundleV2 = struct { this.waitForParse(); - minify_duration.* = @as(u64, @intCast(@divTrunc(@as(i64, @truncate(std.time.nanoTimestamp())) - @as(i64, @truncate(bun.CLI.start_time)), @as(i64, std.time.ns_per_ms)))); + minify_duration.* = @as(u64, @intCast(@divTrunc(@as(i64, @truncate(std.time.nanoTimestamp())) - @as(i64, @truncate(bun.cli.start_time)), @as(i64, std.time.ns_per_ms)))); source_code_size.* = this.source_code_length; if (this.transpiler.log.hasErrors()) { @@ -1443,7 +1443,7 @@ pub const BundleV2 = struct { event_loop, false, null, - try ThreadlocalArena.init(), + try ThreadLocalArena.init(), ); this.unique_key = generateUniqueKey(); @@ -1588,10 +1588,10 @@ pub const BundleV2 = struct { pub const JSBundleThread = BundleThread(JSBundleCompletionTask); pub fn createAndScheduleCompletionTask( - config: bun.JSC.API.JSBundler.Config, - plugins: ?*bun.JSC.API.JSBundler.Plugin, - globalThis: *JSC.JSGlobalObject, - event_loop: *bun.JSC.EventLoop, + config: bun.jsc.API.JSBundler.Config, + plugins: ?*bun.jsc.API.JSBundler.Plugin, + globalThis: *jsc.JSGlobalObject, + event_loop: *bun.jsc.EventLoop, _: std.mem.Allocator, ) OOM!*JSBundleCompletionTask { const completion = bun.new(JSBundleCompletionTask, .{ @@ -1613,7 +1613,7 @@ pub const BundleV2 = struct { // Ensure this exists before we spawn the thread to prevent any race // conditions from creating two - _ = JSC.WorkPool.get(); + _ = jsc.WorkPool.get(); JSBundleThread.singleton.enqueue(completion); @@ -1623,14 +1623,14 @@ pub const BundleV2 = struct { } pub fn generateFromJavaScript( - config: bun.JSC.API.JSBundler.Config, - plugins: ?*bun.JSC.API.JSBundler.Plugin, - globalThis: *JSC.JSGlobalObject, - event_loop: *bun.JSC.EventLoop, + config: bun.jsc.API.JSBundler.Config, + plugins: ?*bun.jsc.API.JSBundler.Plugin, + globalThis: *jsc.JSGlobalObject, + event_loop: *bun.jsc.EventLoop, allocator: std.mem.Allocator, - ) OOM!bun.JSC.JSValue { + ) OOM!bun.jsc.JSValue { const completion = try createAndScheduleCompletionTask(config, plugins, globalThis, event_loop, allocator); - completion.promise = JSC.JSPromise.Strong.init(globalThis); + completion.promise = jsc.JSPromise.Strong.init(globalThis); return completion.promise.value(); } @@ -1667,23 +1667,23 @@ pub const BundleV2 = struct { pub const deref = RefCount.deref; ref_count: RefCount, - config: bun.JSC.API.JSBundler.Config, - jsc_event_loop: *bun.JSC.EventLoop, - task: bun.JSC.AnyTask, - globalThis: *JSC.JSGlobalObject, - promise: JSC.JSPromise.Strong = .{}, + config: bun.jsc.API.JSBundler.Config, + jsc_event_loop: *bun.jsc.EventLoop, + task: bun.jsc.AnyTask, + globalThis: *jsc.JSGlobalObject, + promise: jsc.JSPromise.Strong = .{}, poll_ref: Async.KeepAlive = Async.KeepAlive.init(), env: *bun.DotEnv.Loader, log: Logger.Log, cancelled: bool = false, - html_build_task: ?*JSC.API.HTMLBundle.HTMLBundleRoute = null, + html_build_task: ?*jsc.API.HTMLBundle.HTMLBundleRoute = null, result: Result = .{ .pending = {} }, next: ?*JSBundleCompletionTask = null, transpiler: *BundleV2 = undefined, - plugins: ?*bun.JSC.API.JSBundler.Plugin = null, + plugins: ?*bun.jsc.API.JSBundler.Plugin = null, started_at_ns: u64 = 0, pub fn configureBundler( @@ -1696,7 +1696,7 @@ pub const BundleV2 = struct { transpiler.* = try bun.Transpiler.init( allocator, &completion.log, - Api.TransformOptions{ + api.TransformOptions{ .define = if (config.define.count() > 0) config.define.toAPI() else null, .entry_points = config.entry_points.keys(), .target = config.target.toAPI(), @@ -1760,10 +1760,10 @@ pub const BundleV2 = struct { } pub fn completeOnBundleThread(completion: *JSBundleCompletionTask) void { - completion.jsc_event_loop.enqueueTaskConcurrent(JSC.ConcurrentTask.create(completion.task.task())); + completion.jsc_event_loop.enqueueTaskConcurrent(jsc.ConcurrentTask.create(completion.task.task())); } - pub const TaskCompletion = bun.JSC.AnyTask.New(JSBundleCompletionTask, onComplete); + pub const TaskCompletion = bun.jsc.AnyTask.New(JSBundleCompletionTask, onComplete); fn deinit(this: *JSBundleCompletionTask) void { this.result.deinit(); @@ -1802,16 +1802,16 @@ pub const BundleV2 = struct { break :brk; } - const root_obj = JSC.JSValue.createEmptyObject(globalThis, 3); - root_obj.put(globalThis, JSC.ZigString.static("outputs"), JSC.JSValue.createEmptyArray(globalThis, 0) catch return promise.reject(globalThis, error.JSError)); + const root_obj = jsc.JSValue.createEmptyObject(globalThis, 3); + root_obj.put(globalThis, jsc.ZigString.static("outputs"), jsc.JSValue.createEmptyArray(globalThis, 0) catch return promise.reject(globalThis, error.JSError)); root_obj.put( globalThis, - JSC.ZigString.static("success"), - JSC.JSValue.jsBoolean(false), + jsc.ZigString.static("success"), + jsc.JSValue.jsBoolean(false), ); root_obj.put( globalThis, - JSC.ZigString.static("logs"), + jsc.ZigString.static("logs"), this.log.toJSArray(globalThis, bun.default_allocator) catch |err| { return promise.reject(globalThis, err); }, @@ -1819,14 +1819,14 @@ pub const BundleV2 = struct { promise.resolve(globalThis, root_obj); }, .value => |*build| { - const root_obj = JSC.JSValue.createEmptyObject(globalThis, 3); + const root_obj = jsc.JSValue.createEmptyObject(globalThis, 3); const output_files: []options.OutputFile = build.output_files.items; - const output_files_js = JSC.JSValue.createEmptyArray(globalThis, output_files.len) catch return promise.reject(globalThis, error.JSError); + const output_files_js = jsc.JSValue.createEmptyArray(globalThis, output_files.len) catch return promise.reject(globalThis, error.JSError); if (output_files_js == .zero) { @panic("Unexpected pending JavaScript exception in JSBundleCompletionTask.onComplete. This is a bug in Bun."); } - var to_assign_on_sourcemap: JSC.JSValue = .zero; + var to_assign_on_sourcemap: jsc.JSValue = .zero; for (output_files, 0..) |*output_file, i| { const result = output_file.toJS( if (!this.config.outdir.isEmpty()) @@ -1856,8 +1856,8 @@ pub const BundleV2 = struct { globalThis, ); if (to_assign_on_sourcemap != .zero) { - JSC.Codegen.JSBuildArtifact.sourcemapSetCached(to_assign_on_sourcemap, globalThis, result); - if (to_assign_on_sourcemap.as(JSC.API.BuildArtifact)) |to_assign_on_sourcemap_artifact| { + jsc.Codegen.JSBuildArtifact.sourcemapSetCached(to_assign_on_sourcemap, globalThis, result); + if (to_assign_on_sourcemap.as(jsc.API.BuildArtifact)) |to_assign_on_sourcemap_artifact| { to_assign_on_sourcemap_artifact.sourcemap.set(globalThis, result); } to_assign_on_sourcemap = .zero; @@ -1870,15 +1870,15 @@ pub const BundleV2 = struct { output_files_js.putIndex(globalThis, @as(u32, @intCast(i)), result) catch return; // TODO: properly propagate exception upwards } - root_obj.put(globalThis, JSC.ZigString.static("outputs"), output_files_js); + root_obj.put(globalThis, jsc.ZigString.static("outputs"), output_files_js); root_obj.put( globalThis, - JSC.ZigString.static("success"), - JSC.JSValue.jsBoolean(true), + jsc.ZigString.static("success"), + jsc.JSValue.jsBoolean(true), ); root_obj.put( globalThis, - JSC.ZigString.static("logs"), + jsc.ZigString.static("logs"), this.log.toJSArray(globalThis, bun.default_allocator) catch |err| { return promise.reject(globalThis, err); }, @@ -1893,14 +1893,14 @@ pub const BundleV2 = struct { } }; - pub fn onLoadAsync(this: *BundleV2, load: *bun.JSC.API.JSBundler.Load) void { + pub fn onLoadAsync(this: *BundleV2, load: *bun.jsc.API.JSBundler.Load) void { switch (this.loop().*) { .js => |jsc_event_loop| { - jsc_event_loop.enqueueTaskConcurrent(JSC.ConcurrentTask.fromCallback(load, onLoadFromJsLoop)); + jsc_event_loop.enqueueTaskConcurrent(jsc.ConcurrentTask.fromCallback(load, onLoadFromJsLoop)); }, .mini => |*mini| { mini.enqueueTaskConcurrentWithExtraCtx( - bun.JSC.API.JSBundler.Load, + bun.jsc.API.JSBundler.Load, BundleV2, load, BundleV2.onLoad, @@ -1910,14 +1910,14 @@ pub const BundleV2 = struct { } } - pub fn onResolveAsync(this: *BundleV2, resolve: *bun.JSC.API.JSBundler.Resolve) void { + pub fn onResolveAsync(this: *BundleV2, resolve: *bun.jsc.API.JSBundler.Resolve) void { switch (this.loop().*) { .js => |jsc_event_loop| { - jsc_event_loop.enqueueTaskConcurrent(JSC.ConcurrentTask.fromCallback(resolve, onResolveFromJsLoop)); + jsc_event_loop.enqueueTaskConcurrent(jsc.ConcurrentTask.fromCallback(resolve, onResolveFromJsLoop)); }, .mini => |*mini| { mini.enqueueTaskConcurrentWithExtraCtx( - bun.JSC.API.JSBundler.Resolve, + bun.jsc.API.JSBundler.Resolve, BundleV2, resolve, BundleV2.onResolve, @@ -1927,11 +1927,11 @@ pub const BundleV2 = struct { } } - pub fn onLoadFromJsLoop(load: *bun.JSC.API.JSBundler.Load) void { + pub fn onLoadFromJsLoop(load: *bun.jsc.API.JSBundler.Load) void { onLoad(load, load.bv2); } - pub fn onLoad(load: *bun.JSC.API.JSBundler.Load, this: *BundleV2) void { + pub fn onLoad(load: *bun.jsc.API.JSBundler.Load, this: *BundleV2) void { debug("onLoad: ({d}, {s})", .{ load.source_index.get(), @tagName(load.value) }); defer load.deinit(); defer { @@ -2044,11 +2044,11 @@ pub const BundleV2 = struct { } } - pub fn onResolveFromJsLoop(resolve: *bun.JSC.API.JSBundler.Resolve) void { + pub fn onResolveFromJsLoop(resolve: *bun.jsc.API.JSBundler.Resolve) void { onResolve(resolve, resolve.bv2); } - pub fn onResolve(resolve: *bun.JSC.API.JSBundler.Resolve, this: *BundleV2) void { + pub fn onResolve(resolve: *bun.jsc.API.JSBundler.Resolve, this: *BundleV2) void { defer resolve.deinit(); defer this.decrementScanCounter(); debug("onResolve: ({s}:{s}, {s})", .{ resolve.import_record.namespace, resolve.import_record.specifier, @tagName(resolve.value) }); @@ -2569,14 +2569,14 @@ pub const BundleV2 = struct { if (this.plugins) |plugins| { if (plugins.hasAnyMatches(&import_record.path, false)) { // This is where onResolve plugins are enqueued - var resolve: *JSC.API.JSBundler.Resolve = bun.default_allocator.create(JSC.API.JSBundler.Resolve) catch unreachable; + var resolve: *jsc.API.JSBundler.Resolve = bun.default_allocator.create(jsc.API.JSBundler.Resolve) catch unreachable; debug("enqueue onResolve: {s}:{s}", .{ import_record.path.namespace, import_record.path.text, }); this.incrementScanCounter(); - resolve.* = JSC.API.JSBundler.Resolve.init(this, .{ + resolve.* = jsc.API.JSBundler.Resolve.init(this, .{ .kind = import_record.kind, .source_file = source_file, .namespace = import_record.path.namespace, @@ -2626,8 +2626,8 @@ pub const BundleV2 = struct { parse.path.namespace, parse.path.text, }); - const load = bun.default_allocator.create(JSC.API.JSBundler.Load) catch bun.outOfMemory(); - load.* = JSC.API.JSBundler.Load.init(this, parse); + const load = bun.default_allocator.create(jsc.API.JSBundler.Load) catch bun.outOfMemory(); + load.* = jsc.API.JSBundler.Load.init(this, parse); load.dispatch(); return true; } @@ -2747,7 +2747,7 @@ pub const BundleV2 = struct { } if (ast.target.isBun()) { - if (JSC.ModuleLoader.HardcodedModule.Alias.get(import_record.path.text, .bun)) |replacement| { + if (jsc.ModuleLoader.HardcodedModule.Alias.get(import_record.path.text, .bun)) |replacement| { // When bundling node builtins, remove the "node:" prefix. // This supports special use cases where the bundle is put // into a non-node module resolver that doesn't support @@ -3191,7 +3191,7 @@ pub const BundleV2 = struct { this.decrementScanCounter(); } - pub fn onNotifyDeferMini(_: *bun.JSC.API.JSBundler.Load, this: *BundleV2) void { + pub fn onNotifyDeferMini(_: *bun.jsc.API.JSBundler.Load, this: *BundleV2) void { this.onNotifyDefer(); } @@ -3726,7 +3726,7 @@ pub const EntryPoint = struct { dynamic_import, html, - pub fn outputKind(this: Kind) JSC.API.BuildArtifact.OutputKind { + pub fn outputKind(this: Kind) jsc.API.BuildArtifact.OutputKind { return switch (this) { .user_specified => .@"entry-point", else => .chunk, @@ -4113,21 +4113,20 @@ pub const lex = @import("../js_lexer.zig"); pub const Logger = @import("../logger.zig"); pub const Part = js_ast.Part; pub const js_printer = @import("../js_printer.zig"); -pub const js_ast = @import("../js_ast.zig"); +pub const js_ast = bun.ast; pub const linker = @import("../linker.zig"); pub const sourcemap = bun.sourcemap; pub const StringJoiner = bun.StringJoiner; pub const base64 = bun.base64; -pub const Ref = @import("../ast/base.zig").Ref; -pub const ThreadlocalArena = @import("../allocators/mimalloc_arena.zig").Arena; -pub const BabyList = @import("../baby_list.zig").BabyList; +pub const Ref = bun.ast.Ref; +pub const ThreadLocalArena = bun.allocators.MimallocArena; +pub const BabyList = bun.collections.BabyList; pub const Fs = @import("../fs.zig"); -pub const schema = @import("../api/schema.zig"); -pub const Api = schema.Api; +pub const api = bun.schema.api; pub const _resolver = @import("../resolver/resolver.zig"); pub const ImportRecord = bun.ImportRecord; pub const ImportKind = bun.ImportKind; -pub const allocators = @import("../allocators.zig"); +pub const allocators = bun.allocators; pub const resolve_path = @import("../resolver/resolve_path.zig"); pub const runtime = @import("../runtime.zig"); pub const Timer = @import("../system_timer.zig"); @@ -4139,13 +4138,13 @@ pub const NodeFallbackModules = @import("../node_fallbacks.zig"); pub const CacheEntry = @import("../cache.zig").Fs.Entry; pub const URL = @import("../url.zig").URL; pub const Resolver = _resolver.Resolver; -pub const TOML = @import("../toml/toml_parser.zig").TOML; +pub const TOML = bun.interchange.toml.TOML; pub const Dependency = js_ast.Dependency; pub const JSAst = js_ast.BundledAst; pub const Loader = options.Loader; -pub const Index = @import("../ast/base.zig").Index; +pub const Index = bun.ast.Index; pub const Symbol = js_ast.Symbol; -pub const EventLoop = bun.JSC.AnyEventLoop; +pub const EventLoop = bun.jsc.AnyEventLoop; pub const MultiArrayList = bun.MultiArrayList; pub const Stmt = js_ast.Stmt; pub const Expr = js_ast.Expr; @@ -4159,7 +4158,7 @@ pub const renamer = bun.renamer; pub const StableSymbolCount = renamer.StableSymbolCount; pub const MinifyRenamer = renamer.MinifyRenamer; pub const Scope = js_ast.Scope; -pub const JSC = bun.JSC; +pub const jsc = bun.jsc; pub const debugTreeShake = Output.scoped(.TreeShake, true); pub const debugPartRanges = Output.scoped(.PartRanges, true); pub const BitSet = bun.bit_set.DynamicBitSetUnmanaged; @@ -4176,6 +4175,8 @@ pub const LinkerContext = @import("./LinkerContext.zig").LinkerContext; pub const LinkerGraph = @import("./LinkerGraph.zig").LinkerGraph; pub const Graph = @import("./Graph.zig"); +const string = []const u8; + const options = @import("../options.zig"); const IdentityContext = @import("../identity_context.zig").IdentityContext; @@ -4186,5 +4187,4 @@ const Output = bun.Output; const ThreadPoolLib = bun.ThreadPool; const Transpiler = bun.Transpiler; const default_allocator = bun.default_allocator; -const string = bun.string; const strings = bun.strings; diff --git a/src/bundler/entry_points.zig b/src/bundler/entry_points.zig index c387e64272..42eca7b748 100644 --- a/src/bundler/entry_points.zig +++ b/src/bundler/entry_points.zig @@ -337,12 +337,13 @@ pub const MacroEntryPoint = struct { } }; +const string = []const u8; + const Fs = @import("../fs.zig"); const std = @import("std"); const bun = @import("bun"); const Transpiler = bun.Transpiler; -const js_ast = bun.JSAst; +const js_ast = bun.ast; const logger = bun.logger; -const string = bun.string; const strings = bun.strings; diff --git a/src/bundler/linker_context/computeChunks.zig b/src/bundler/linker_context/computeChunks.zig index 15c6881837..30517ecb6c 100644 --- a/src/bundler/linker_context/computeChunks.zig +++ b/src/bundler/linker_context/computeChunks.zig @@ -413,13 +413,14 @@ pub const DeferredBatchTask = bun.bundle_v2.DeferredBatchTask; pub const ThreadPool = bun.bundle_v2.ThreadPool; pub const ParseTask = bun.bundle_v2.ParseTask; +const string = []const u8; + const std = @import("std"); const bun = @import("bun"); const BabyList = bun.BabyList; const options = bun.options; const sourcemap = bun.sourcemap; -const string = bun.string; const AutoBitSet = bun.bit_set.AutoBitSet; const bundler = bun.bundle_v2; diff --git a/src/bundler/linker_context/computeCrossChunkDependencies.zig b/src/bundler/linker_context/computeCrossChunkDependencies.zig index c603c2e094..2638bca36c 100644 --- a/src/bundler/linker_context/computeCrossChunkDependencies.zig +++ b/src/bundler/linker_context/computeCrossChunkDependencies.zig @@ -421,6 +421,8 @@ pub const DeferredBatchTask = bun.bundle_v2.DeferredBatchTask; pub const ThreadPool = bun.bundle_v2.ThreadPool; pub const ParseTask = bun.bundle_v2.ParseTask; +const string = []const u8; + const std = @import("std"); const bun = @import("bun"); @@ -429,7 +431,12 @@ const Environment = bun.Environment; const ImportRecord = bun.ImportRecord; const default_allocator = bun.default_allocator; const renamer = bun.renamer; -const string = bun.string; + +const js_ast = bun.ast; +const Part = js_ast.Part; +const S = js_ast.S; +const Stmt = js_ast.Stmt; +const Symbol = js_ast.Symbol; const bundler = bun.bundle_v2; const Chunk = bundler.Chunk; @@ -445,11 +452,5 @@ const LinkerContext = bun.bundle_v2.LinkerContext; const ChunkMeta = LinkerContext.ChunkMeta; const debug = LinkerContext.debug; -const js_ast = bun.js_ast; -const Part = js_ast.Part; -const S = js_ast.S; -const Stmt = js_ast.Stmt; -const Symbol = js_ast.Symbol; - const Logger = bun.logger; const Loc = Logger.Loc; diff --git a/src/bundler/linker_context/convertStmtsForChunk.zig b/src/bundler/linker_context/convertStmtsForChunk.zig index a5501ccfa1..d25ec13780 100644 --- a/src/bundler/linker_context/convertStmtsForChunk.zig +++ b/src/bundler/linker_context/convertStmtsForChunk.zig @@ -533,14 +533,7 @@ const bun = @import("bun"); const BabyList = bun.BabyList; const FeatureFlags = bun.FeatureFlags; -const bundler = bun.bundle_v2; -const Chunk = bundler.Chunk; -const WrapKind = bundler.WrapKind; - -const LinkerContext = bun.bundle_v2.LinkerContext; -const StmtList = LinkerContext.StmtList; - -const js_ast = bun.js_ast; +const js_ast = bun.ast; const B = js_ast.B; const Binding = js_ast.Binding; const E = js_ast.E; @@ -550,5 +543,12 @@ const JSAst = js_ast.BundledAst; const S = js_ast.S; const Stmt = js_ast.Stmt; +const bundler = bun.bundle_v2; +const Chunk = bundler.Chunk; +const WrapKind = bundler.WrapKind; + +const LinkerContext = bun.bundle_v2.LinkerContext; +const StmtList = LinkerContext.StmtList; + const Logger = bun.logger; const Loc = Logger.Loc; diff --git a/src/bundler/linker_context/convertStmtsForChunkForDevServer.zig b/src/bundler/linker_context/convertStmtsForChunkForDevServer.zig index b35733ed7e..ca36be7531 100644 --- a/src/bundler/linker_context/convertStmtsForChunkForDevServer.zig +++ b/src/bundler/linker_context/convertStmtsForChunkForDevServer.zig @@ -159,10 +159,7 @@ pub const ParseTask = bun.bundle_v2.ParseTask; const bun = @import("bun"); const std = @import("std"); -const LinkerContext = bun.bundle_v2.LinkerContext; -const StmtList = LinkerContext.StmtList; - -const js_ast = bun.js_ast; +const js_ast = bun.ast; const B = js_ast.B; const Binding = js_ast.Binding; const E = js_ast.E; @@ -172,5 +169,8 @@ const JSAst = js_ast.BundledAst; const S = js_ast.S; const Stmt = js_ast.Stmt; +const LinkerContext = bun.bundle_v2.LinkerContext; +const StmtList = LinkerContext.StmtList; + const Logger = bun.logger; const Loc = Logger.Loc; diff --git a/src/bundler/linker_context/doStep5.zig b/src/bundler/linker_context/doStep5.zig index 5e4bbe6fc9..744f23c6cb 100644 --- a/src/bundler/linker_context/doStep5.zig +++ b/src/bundler/linker_context/doStep5.zig @@ -470,12 +470,13 @@ pub fn createExportsForFile( pub const ThreadPool = bun.bundle_v2.ThreadPool; +const string = []const u8; + const std = @import("std"); const bun = @import("bun"); const Environment = bun.Environment; const options = bun.options; -const string = bun.string; const strings = bun.strings; const ImportData = bun.bundle_v2.ImportData; diff --git a/src/bundler/linker_context/findImportedFilesInCSSOrder.zig b/src/bundler/linker_context/findImportedFilesInCSSOrder.zig index 107c468e1e..92973533ca 100644 --- a/src/bundler/linker_context/findImportedFilesInCSSOrder.zig +++ b/src/bundler/linker_context/findImportedFilesInCSSOrder.zig @@ -666,6 +666,10 @@ const Environment = bun.Environment; const ImportRecord = bun.ImportRecord; const default_allocator = bun.default_allocator; +const js_ast = bun.ast; +const B = js_ast.B; +const Symbol = js_ast.Symbol; + const bundler = bun.bundle_v2; const Chunk = bundler.Chunk; const Graph = bundler.Graph; @@ -674,7 +678,3 @@ const LinkerGraph = bundler.LinkerGraph; const LinkerContext = bun.bundle_v2.LinkerContext; const debug = LinkerContext.debug; - -const js_ast = bun.js_ast; -const B = js_ast.B; -const Symbol = js_ast.Symbol; diff --git a/src/bundler/linker_context/generateChunksInParallel.zig b/src/bundler/linker_context/generateChunksInParallel.zig index 2ca0656627..e3d868f846 100644 --- a/src/bundler/linker_context/generateChunksInParallel.zig +++ b/src/bundler/linker_context/generateChunksInParallel.zig @@ -426,15 +426,15 @@ pub fn generateChunksInParallel( .js; if (loader.isJavaScriptLike()) { - JSC.VirtualMachine.is_bundler_thread_for_bytecode_cache = true; - JSC.initialize(false); + jsc.VirtualMachine.is_bundler_thread_for_bytecode_cache = true; + jsc.initialize(false); var fdpath: bun.PathBuffer = undefined; var source_provider_url = try bun.String.createFormat("{s}" ++ bun.bytecode_extension, .{chunk.final_rel_path}); source_provider_url.ref(); defer source_provider_url.deref(); - if (JSC.CachedBytecode.generate(c.options.output_format, code_result.buffer, &source_provider_url)) |result| { + if (jsc.CachedBytecode.generate(c.options.output_format, code_result.buffer, &source_provider_url)) |result| { const bytecode, const cached_bytecode = result; const source_provider_url_str = source_provider_url.toSlice(bun.default_allocator); defer source_provider_url_str.deinit(); @@ -553,11 +553,11 @@ const std = @import("std"); const bun = @import("bun"); const Environment = bun.Environment; -const JSC = bun.JSC; const Loader = bun.Loader; const Output = bun.Output; const ThreadPoolLib = bun.ThreadPool; const base64 = bun.base64; +const jsc = bun.jsc; const strings = bun.strings; const AutoBitSet = bun.bit_set.AutoBitSet; diff --git a/src/bundler/linker_context/generateCodeForLazyExport.zig b/src/bundler/linker_context/generateCodeForLazyExport.zig index 97aa93f3f5..8fde055441 100644 --- a/src/bundler/linker_context/generateCodeForLazyExport.zig +++ b/src/bundler/linker_context/generateCodeForLazyExport.zig @@ -393,19 +393,16 @@ pub const DeferredBatchTask = bun.bundle_v2.DeferredBatchTask; pub const ThreadPool = bun.bundle_v2.ThreadPool; pub const ParseTask = bun.bundle_v2.ParseTask; +const string = []const u8; + const std = @import("std"); const bun = @import("bun"); const BabyList = bun.BabyList; const ImportRecord = bun.ImportRecord; -const string = bun.string; const BitSet = bun.bit_set.DynamicBitSetUnmanaged; -const Index = bun.bundle_v2.Index; -const LinkerContext = bun.bundle_v2.LinkerContext; -const Ref = bun.bundle_v2.Ref; - -const js_ast = bun.js_ast; +const js_ast = bun.ast; const B = js_ast.B; const Binding = js_ast.Binding; const E = js_ast.E; @@ -416,5 +413,9 @@ const S = js_ast.S; const Stmt = js_ast.Stmt; const Symbol = js_ast.Symbol; +const Index = bun.bundle_v2.Index; +const LinkerContext = bun.bundle_v2.LinkerContext; +const Ref = bun.bundle_v2.Ref; + const Logger = bun.logger; const Loc = Logger.Loc; diff --git a/src/bundler/linker_context/generateCompileResultForCssChunk.zig b/src/bundler/linker_context/generateCompileResultForCssChunk.zig index 4bb78bdaa1..86546e0658 100644 --- a/src/bundler/linker_context/generateCompileResultForCssChunk.zig +++ b/src/bundler/linker_context/generateCompileResultForCssChunk.zig @@ -155,6 +155,9 @@ const ThreadPoolLib = bun.ThreadPool; const js_printer = bun.js_printer; const options = bun.options; +const js_ast = bun.ast; +const Symbol = js_ast.Symbol; + const bundler = bun.bundle_v2; const Chunk = bundler.Chunk; const CompileResult = bundler.CompileResult; @@ -162,6 +165,3 @@ const Index = bun.bundle_v2.Index; const LinkerContext = bun.bundle_v2.LinkerContext; const PendingPartRange = LinkerContext.PendingPartRange; - -const js_ast = bun.js_ast; -const Symbol = js_ast.Symbol; diff --git a/src/bundler/linker_context/generateCompileResultForJSChunk.zig b/src/bundler/linker_context/generateCompileResultForJSChunk.zig index a2375e8027..3996ab0ce8 100644 --- a/src/bundler/linker_context/generateCompileResultForJSChunk.zig +++ b/src/bundler/linker_context/generateCompileResultForJSChunk.zig @@ -16,7 +16,7 @@ pub fn generateCompileResultForJSChunk(task: *ThreadPoolLib.Task) void { if (Environment.show_crash_trace) { const path = ctx.c.parse_graph.input_files.items(.source)[part_range.part_range.source_index.get()].path; - if (bun.CLI.debug_flags.hasPrintBreakpoint(path)) { + if (bun.cli.debug_flags.hasPrintBreakpoint(path)) { @breakpoint(); } } @@ -80,6 +80,9 @@ const default_allocator = bun.default_allocator; const js_printer = bun.js_printer; const renamer = bun.renamer; +const js_ast = bun.ast; +const Scope = js_ast.Scope; + const bundler = bun.bundle_v2; const Chunk = bundler.Chunk; const CompileResult = bundler.CompileResult; @@ -89,6 +92,3 @@ const ThreadPool = bun.bundle_v2.ThreadPool; const LinkerContext = bun.bundle_v2.LinkerContext; const PendingPartRange = LinkerContext.PendingPartRange; - -const js_ast = bun.js_ast; -const Scope = js_ast.Scope; diff --git a/src/bundler/linker_context/renameSymbolsInChunk.zig b/src/bundler/linker_context/renameSymbolsInChunk.zig index db813fddca..c50b111348 100644 --- a/src/bundler/linker_context/renameSymbolsInChunk.zig +++ b/src/bundler/linker_context/renameSymbolsInChunk.zig @@ -261,6 +261,9 @@ const std = @import("std"); const bun = @import("bun"); const ImportRecord = bun.ImportRecord; +const js_ast = bun.ast; +const Part = js_ast.Part; + const bundler = bun.bundle_v2; const Chunk = bundler.Chunk; const JSMeta = bundler.JSMeta; @@ -268,9 +271,6 @@ const LinkerContext = bun.bundle_v2.LinkerContext; const Ref = bun.bundle_v2.Ref; const StableRef = bundler.StableRef; -const js_ast = bun.js_ast; -const Part = js_ast.Part; - const renamer = bun.renamer; const MinifyRenamer = renamer.MinifyRenamer; const StableSymbolCount = renamer.StableSymbolCount; diff --git a/src/bundler/linker_context/writeOutputFilesToDisk.zig b/src/bundler/linker_context/writeOutputFilesToDisk.zig index 42221a82ff..2592cb57af 100644 --- a/src/bundler/linker_context/writeOutputFilesToDisk.zig +++ b/src/bundler/linker_context/writeOutputFilesToDisk.zig @@ -111,10 +111,10 @@ pub fn writeOutputFilesToDisk( code_result.buffer = buf.items; } - switch (JSC.Node.fs.NodeFS.writeFileWithPathBuffer( + switch (jsc.Node.fs.NodeFS.writeFileWithPathBuffer( &pathbuf, .{ - .data = JSC.Node.StringOrBuffer{ + .data = jsc.Node.StringOrBuffer{ .buffer = bun.api.node.Buffer{ .buffer = .{ .ptr = @constCast(output_source_map.ptr), @@ -186,15 +186,15 @@ pub fn writeOutputFilesToDisk( .js; if (loader.isJavaScriptLike()) { - JSC.VirtualMachine.is_bundler_thread_for_bytecode_cache = true; - JSC.initialize(false); + jsc.VirtualMachine.is_bundler_thread_for_bytecode_cache = true; + jsc.initialize(false); var fdpath: bun.PathBuffer = undefined; var source_provider_url = try bun.String.createFormat("{s}" ++ bun.bytecode_extension, .{chunk.final_rel_path}); source_provider_url.ref(); defer source_provider_url.deref(); - if (JSC.CachedBytecode.generate(c.options.output_format, code_result.buffer, &source_provider_url)) |result| { + if (jsc.CachedBytecode.generate(c.options.output_format, code_result.buffer, &source_provider_url)) |result| { const source_provider_url_str = source_provider_url.toSlice(bun.default_allocator); defer source_provider_url_str.deinit(); const bytecode, const cached_bytecode = result; @@ -202,7 +202,7 @@ pub fn writeOutputFilesToDisk( @memcpy(fdpath[0..chunk.final_rel_path.len], chunk.final_rel_path); fdpath[chunk.final_rel_path.len..][0..bun.bytecode_extension.len].* = bun.bytecode_extension.*; defer cached_bytecode.deref(); - switch (JSC.Node.fs.NodeFS.writeFileWithPathBuffer( + switch (jsc.Node.fs.NodeFS.writeFileWithPathBuffer( &pathbuf, .{ .data = .{ @@ -258,7 +258,7 @@ pub fn writeOutputFilesToDisk( break :brk null; }; - switch (JSC.Node.fs.NodeFS.writeFileWithPathBuffer( + switch (jsc.Node.fs.NodeFS.writeFileWithPathBuffer( &pathbuf, .{ .data = .{ @@ -276,7 +276,7 @@ pub fn writeOutputFilesToDisk( .dirfd = .fromStdDir(root_dir), .file = .{ - .path = JSC.Node.PathLike{ + .path = jsc.Node.PathLike{ .string = bun.PathString.init(rel_path), }, }, @@ -371,7 +371,7 @@ pub fn writeOutputFilesToDisk( } } - switch (JSC.Node.fs.NodeFS.writeFileWithPathBuffer( + switch (jsc.Node.fs.NodeFS.writeFileWithPathBuffer( &pathbuf, .{ .data = .{ @@ -386,7 +386,7 @@ pub fn writeOutputFilesToDisk( .encoding = .buffer, .dirfd = .fromStdDir(root_dir), .file = .{ - .path = JSC.Node.PathLike{ + .path = jsc.Node.PathLike{ .string = bun.PathString.init(src.dest_path), }, }, @@ -414,17 +414,18 @@ pub const DeferredBatchTask = bun.bundle_v2.DeferredBatchTask; pub const ThreadPool = bun.bundle_v2.ThreadPool; pub const ParseTask = bun.bundle_v2.ParseTask; +const string = []const u8; + const std = @import("std"); const bun = @import("bun"); -const JSC = bun.JSC; const Loader = bun.Loader; const Output = bun.Output; const base64 = bun.base64; const default_allocator = bun.default_allocator; +const jsc = bun.jsc; const options = bun.options; const sourcemap = bun.sourcemap; -const string = bun.string; const strings = bun.strings; const bundler = bun.bundle_v2; diff --git a/src/bunfig.zig b/src/bunfig.zig index 7b36ce9fb4..fd5d2eae3f 100644 --- a/src/bunfig.zig +++ b/src/bunfig.zig @@ -3,7 +3,7 @@ pub const MacroMap = bun.StringArrayHashMapUnmanaged(MacroImportReplacementMap); pub const BundlePackageOverride = bun.StringArrayHashMapUnmanaged(options.BundleOverride); const LoaderMap = bun.StringArrayHashMapUnmanaged(options.Loader); -// TODO: replace Api.TransformOptions with Bunfig +// TODO: replace api.TransformOptions with Bunfig pub const Bunfig = struct { pub const OfflineMode = enum { online, @@ -21,7 +21,7 @@ pub const Bunfig = struct { source: *const logger.Source, log: *logger.Log, allocator: std.mem.Allocator, - bunfig: *Api.TransformOptions, + bunfig: *api.TransformOptions, ctx: Command.Context, fn addError(this: *Parser, loc: logger.Loc, comptime text: string) !void { @@ -42,9 +42,9 @@ pub const Bunfig = struct { return error.@"Invalid Bunfig"; } - fn parseRegistryURLString(this: *Parser, str: *js_ast.E.String) !Api.NpmRegistry { + fn parseRegistryURLString(this: *Parser, str: *js_ast.E.String) !api.NpmRegistry { const url = URL.parse(str.data); - var registry = std.mem.zeroes(Api.NpmRegistry); + var registry = std.mem.zeroes(api.NpmRegistry); // Token if (url.username.len == 0 and url.password.len > 0) { @@ -63,8 +63,8 @@ pub const Bunfig = struct { return registry; } - fn parseRegistryObject(this: *Parser, obj: *js_ast.E.Object) !Api.NpmRegistry { - var registry = std.mem.zeroes(Api.NpmRegistry); + fn parseRegistryObject(this: *Parser, obj: *js_ast.E.Object) !api.NpmRegistry { + var registry = std.mem.zeroes(api.NpmRegistry); if (obj.get("url")) |url| { try this.expectString(url); @@ -91,7 +91,7 @@ pub const Bunfig = struct { return registry; } - fn parseRegistry(this: *Parser, expr: js_ast.Expr) !Api.NpmRegistry { + fn parseRegistry(this: *Parser, expr: js_ast.Expr) !api.NpmRegistry { switch (expr.data) { .e_string => |str| { return this.parseRegistryURLString(str); @@ -101,7 +101,7 @@ pub const Bunfig = struct { }, else => { try this.addError(expr.loc, "Expected registry to be a URL string or an object"); - return std.mem.zeroes(Api.NpmRegistry); + return std.mem.zeroes(api.NpmRegistry); }, } } @@ -111,10 +111,10 @@ pub const Bunfig = struct { const Matcher = strings.ExactSizeMatcher(8); this.bunfig.log_level = switch (Matcher.match(expr.asString(this.allocator).?)) { - Matcher.case("debug") => Api.MessageLevel.debug, - Matcher.case("error") => Api.MessageLevel.err, - Matcher.case("warn") => Api.MessageLevel.warn, - Matcher.case("info") => Api.MessageLevel.info, + Matcher.case("debug") => api.MessageLevel.debug, + Matcher.case("error") => api.MessageLevel.err, + Matcher.case("warn") => api.MessageLevel.warn, + Matcher.case("info") => api.MessageLevel.info, else => { try this.addError(expr.loc, "Invalid log level, must be one of debug, error, or warn"); unreachable; @@ -180,7 +180,7 @@ pub const Bunfig = struct { values[i] = prop.value.?.data.e_string.string(allocator) catch unreachable; i += 1; } - this.bunfig.define = Api.StringMap{ + this.bunfig.define = api.StringMap{ .keys = keys, .values = values, }; @@ -357,9 +357,9 @@ pub const Bunfig = struct { if (comptime cmd.isNPMRelated() or cmd == .RunCommand or cmd == .AutoCommand or cmd == .TestCommand) { if (json.getObject("install")) |install_obj| { - var install: *Api.BunInstall = this.ctx.install orelse brk: { - const install = try this.allocator.create(Api.BunInstall); - install.* = std.mem.zeroes(Api.BunInstall); + var install: *api.BunInstall = this.ctx.install orelse brk: { + const install = try this.allocator.create(api.BunInstall); + install.* = std.mem.zeroes(api.BunInstall); this.ctx.install = install; break :brk install; }; @@ -435,7 +435,7 @@ pub const Bunfig = struct { } if (install_obj.get("scopes")) |scopes| { - var registry_map = install.scoped orelse Api.NpmRegistryMap{}; + var registry_map = install.scoped orelse api.NpmRegistryMap{}; try this.expect(scopes, .e_object); try registry_map.scopes.ensureUnusedCapacity(this.allocator, scopes.data.e_object.properties.len); @@ -735,7 +735,7 @@ pub const Bunfig = struct { values[i] = prop.value.?.data.e_string.string(allocator) catch unreachable; i += 1; } - this.bunfig.serve_define = Api.StringMap{ + this.bunfig.serve_define = api.StringMap{ .keys = keys, .values = values, }; @@ -841,20 +841,20 @@ pub const Bunfig = struct { var jsx_factory: string = ""; var jsx_fragment: string = ""; var jsx_import_source: string = ""; - var jsx_runtime = Api.JsxRuntime.automatic; + var jsx_runtime = api.JsxRuntime.automatic; var jsx_dev = true; if (json.get("jsx")) |expr| { if (expr.asString(allocator)) |value| { if (strings.eqlComptime(value, "react")) { - jsx_runtime = Api.JsxRuntime.classic; + jsx_runtime = api.JsxRuntime.classic; } else if (strings.eqlComptime(value, "solid")) { - jsx_runtime = Api.JsxRuntime.solid; + jsx_runtime = api.JsxRuntime.solid; } else if (strings.eqlComptime(value, "react-jsx")) { - jsx_runtime = Api.JsxRuntime.automatic; + jsx_runtime = api.JsxRuntime.automatic; jsx_dev = false; } else if (strings.eqlComptime(value, "react-jsxDEV")) { - jsx_runtime = Api.JsxRuntime.automatic; + jsx_runtime = api.JsxRuntime.automatic; jsx_dev = true; } else { try this.addError(expr.loc, "Invalid jsx runtime, only 'react', 'solid', 'react-jsx', and 'react-jsxDEV' are supported"); @@ -881,7 +881,7 @@ pub const Bunfig = struct { } if (this.bunfig.jsx == null) { - this.bunfig.jsx = Api.Jsx{ + this.bunfig.jsx = api.Jsx{ .factory = @constCast(jsx_factory), .fragment = @constCast(jsx_fragment), .import_source = @constCast(jsx_import_source), @@ -889,7 +889,7 @@ pub const Bunfig = struct { .development = jsx_dev, }; } else { - var jsx: *Api.Jsx = &this.bunfig.jsx.?; + var jsx: *api.Jsx = &this.bunfig.jsx.?; if (jsx_factory.len > 0) { jsx.factory = jsx_factory; } @@ -947,7 +947,7 @@ pub const Bunfig = struct { try this.expect(expr, .e_object); const properties = expr.data.e_object.properties.slice(); var loader_names = try this.allocator.alloc(string, properties.len); - var loader_values = try this.allocator.alloc(Api.Loader, properties.len); + var loader_values = try this.allocator.alloc(api.Loader, properties.len); for (properties, 0..) |item, i| { const key = item.key.?.asString(allocator).?; @@ -966,7 +966,7 @@ pub const Bunfig = struct { loader_names[i] = key; loader_values[i] = loader.toAPI(); } - this.bunfig.loaders = Api.LoaderMap{ + this.bunfig.loaders = api.LoaderMap{ .extensions = loader_names, .loaders = loader_values, }; @@ -1047,21 +1047,22 @@ pub const Bunfig = struct { } }; +const string = []const u8; + const options = @import("./options.zig"); const resolver = @import("./resolver/resolver.zig"); const std = @import("std"); -const Api = @import("./api/schema.zig").Api; const Command = @import("./cli.zig").Command; const PackageJSON = @import("./resolver/package_json.zig").PackageJSON; -const TOML = @import("./toml/toml_parser.zig").TOML; const TestCommand = @import("./cli/test_command.zig").TestCommand; const URL = @import("./url.zig").URL; const bun = @import("bun"); -const JSONParser = bun.JSON; +const JSONParser = bun.json; const default_allocator = bun.default_allocator; -const js_ast = bun.JSAst; +const js_ast = bun.ast; const logger = bun.logger; -const string = bun.string; const strings = bun.strings; const PackageManager = bun.install.PackageManager; +const api = bun.schema.api; +const TOML = bun.interchange.toml.TOML; diff --git a/src/cache.zig b/src/cache.zig index 4d37628517..89b75aea00 100644 --- a/src/cache.zig +++ b/src/cache.zig @@ -313,6 +313,8 @@ pub const Json = struct { } }; +const string = []const u8; + const fs = @import("./fs.zig"); const std = @import("std"); const Define = @import("./defines.zig").Define; @@ -325,9 +327,8 @@ const MutableString = bun.MutableString; const Output = bun.Output; const StoredFileDescriptorType = bun.StoredFileDescriptorType; const default_allocator = bun.default_allocator; -const js_ast = bun.JSAst; +const js_ast = bun.ast; const js_parser = bun.js_parser; -const json_parser = bun.JSON; +const json_parser = bun.json; const logger = bun.logger; -const string = bun.string; const strings = bun.strings; diff --git a/src/cli.zig b/src/cli.zig index 5b101df7dd..81d7793e2e 100644 --- a/src/cli.zig +++ b/src/cli.zig @@ -7,7 +7,7 @@ pub var Bun__Node__ProcessTitle: ?string = null; pub const Cli = struct { pub const CompileTarget = @import("./compile_target.zig"); pub var log_: logger.Log = undefined; - pub fn startTransform(_: std.mem.Allocator, _: Api.TransformOptions, _: *logger.Log) anyerror!void {} + pub fn startTransform(_: std.mem.Allocator, _: api.TransformOptions, _: *logger.Log) anyerror!void {} pub fn start(allocator: std.mem.Allocator) void { is_main_thread = true; start_time = std.time.nanoTimestamp(); @@ -54,7 +54,7 @@ pub const debug_flags = if (Environment.show_crash_trace) struct { } } else @compileError("Do not access this namespace in a release build"); -pub const LoaderColonList = ColonListType(Api.Loader, Arguments.loader_resolver); +pub const LoaderColonList = ColonListType(api.Loader, Arguments.loader_resolver); pub const DefineColonList = ColonListType(string, Arguments.noop_resolver); pub fn invalidTarget(diag: *clap.Diagnostic, _target: []const u8) noreturn { @branchHint(.cold); @@ -367,12 +367,12 @@ pub const Command = struct { pub const ContextData = struct { start_time: i128, - args: Api.TransformOptions, + args: api.TransformOptions, log: *logger.Log, allocator: std.mem.Allocator, positionals: []const string = &.{}, passthrough: []const string = &.{}, - install: ?*Api.BunInstall = null, + install: ?*api.BunInstall = null, debug: DebugOptions = .{}, test_options: TestOptions = .{}, @@ -414,7 +414,7 @@ pub const Command = struct { production: bool = false, - env_behavior: Api.DotEnvBehavior = .disable, + env_behavior: api.DotEnvBehavior = .disable, env_prefix: []const u8 = "", elide_lines: ?usize = null, // Compile options @@ -427,7 +427,7 @@ pub const Command = struct { pub fn create(allocator: std.mem.Allocator, log: *logger.Log, comptime command: Command.Tag) anyerror!Context { Cli.cmd = command; context_data = .{ - .args = std.mem.zeroes(Api.TransformOptions), + .args = std.mem.zeroes(api.TransformOptions), .log = log, .start_time = start_time, .allocator = allocator, @@ -628,7 +628,7 @@ pub const Command = struct { pub fn start(allocator: std.mem.Allocator, log: *logger.Log) !void { if (comptime Environment.allow_assert) { if (bun.getenvZ("MI_VERBOSE") == null) { - bun.Mimalloc.mi_option_set_enabled(.verbose, false); + bun.mimalloc.mi_option_set_enabled(.verbose, false); } } @@ -636,7 +636,7 @@ pub const Command = struct { if (!bun.getRuntimeFeatureFlag(.BUN_BE_BUN)) { if (try bun.StandaloneModuleGraph.fromExecutable(bun.default_allocator)) |graph| { context_data = .{ - .args = std.mem.zeroes(Api.TransformOptions), + .args = std.mem.zeroes(api.TransformOptions), .log = log, .start_time = start_time, .allocator = bun.default_allocator, @@ -644,14 +644,14 @@ pub const Command = struct { global_cli_ctx = &context_data; var ctx = global_cli_ctx; - ctx.args.target = Api.Target.bun; + ctx.args.target = api.Target.bun; if (bun.argv.len > 1) { ctx.passthrough = bun.argv[1..]; } else { ctx.passthrough = &[_]string{}; } - try @import("./bun_js.zig").Run.bootStandalone( + try bun_js.Run.bootStandalone( ctx, graph.entryPoint().name, graph, @@ -1389,7 +1389,7 @@ pub const Command = struct { const cwd = try std.posix.getcwd(&entry_point_buf); @memcpy(entry_point_buf[cwd.len..][0..trigger.len], trigger); ctx.passthrough = try std.mem.concat(ctx.allocator, []const u8, &.{ ctx.positionals, ctx.passthrough }); - try BunJS.Run.boot(ctx, entry_point_buf[0 .. cwd.len + trigger.len], null); + try bun_js.Run.boot(ctx, entry_point_buf[0 .. cwd.len + trigger.len], null); } fn @"bun ./bun.lockb"(ctx: Context) !void { @@ -1676,14 +1676,14 @@ pub fn printRevisionAndExit() noreturn { Global.exit(0); } +const string = []const u8; + const AddCompletions = @import("./cli/add_completions.zig"); -const BunJS = @import("./bun_js.zig"); const FilterRun = @import("./cli/filter_run.zig"); const PmViewCommand = @import("./cli/pm_view_command.zig"); const fs = @import("./fs.zig"); const options = @import("./options.zig"); const std = @import("std"); -const Api = @import("./api/schema.zig").Api; const Bunfig = @import("./bunfig.zig").Bunfig; const ColonListType = @import("./cli/colon_list_type.zig").ColonListType; const MacroMap = @import("./resolver/package_json.zig").MacroMap; @@ -1698,9 +1698,10 @@ const Environment = bun.Environment; const Global = bun.Global; const Output = bun.Output; const RegularExpression = bun.RegularExpression; +const bun_js = bun.bun_js; const clap = bun.clap; const default_allocator = bun.default_allocator; const logger = bun.logger; -const string = bun.string; const strings = bun.strings; const File = bun.sys.File; +const api = bun.schema.api; diff --git a/src/cli/Arguments.zig b/src/cli/Arguments.zig index bfb09a4e95..c7d41bfe0f 100644 --- a/src/cli/Arguments.zig +++ b/src/cli/Arguments.zig @@ -693,7 +693,7 @@ pub fn parse(allocator: std.mem.Allocator, ctx: Command.Context, comptime cmd: C .path_or_port = inspect_flag, } }; - bun.JSC.RuntimeTranspilerCache.is_disabled = true; + bun.jsc.RuntimeTranspilerCache.is_disabled = true; } else if (args.option("--inspect-wait")) |inspect_flag| { ctx.runtime_options.debugger = if (inspect_flag.len == 0) Command.Debugger{ .enable = .{ @@ -705,7 +705,7 @@ pub fn parse(allocator: std.mem.Allocator, ctx: Command.Context, comptime cmd: C .wait_for_connection = true, } }; - bun.JSC.RuntimeTranspilerCache.is_disabled = true; + bun.jsc.RuntimeTranspilerCache.is_disabled = true; } else if (args.option("--inspect-brk")) |inspect_flag| { ctx.runtime_options.debugger = if (inspect_flag.len == 0) Command.Debugger{ .enable = .{ @@ -719,7 +719,7 @@ pub fn parse(allocator: std.mem.Allocator, ctx: Command.Context, comptime cmd: C .set_breakpoint_on_first_line = true, } }; - bun.JSC.RuntimeTranspilerCache.is_disabled = true; + bun.jsc.RuntimeTranspilerCache.is_disabled = true; } if (args.flag("--no-deprecation")) { @@ -1064,7 +1064,7 @@ pub fn parse(allocator: std.mem.Allocator, ctx: Command.Context, comptime cmd: C if (opts.define) |define| { if (define.keys.len > 0) - bun.JSC.RuntimeTranspilerCache.is_disabled = true; + bun.jsc.RuntimeTranspilerCache.is_disabled = true; } } @@ -1172,6 +1172,8 @@ export var Bun__Node__ZeroFillBuffers = false; export var Bun__Node__ProcessNoDeprecation = false; export var Bun__Node__ProcessThrowDeprecation = false; +const string = []const u8; + const builtin = @import("builtin"); const std = @import("std"); @@ -1184,15 +1186,14 @@ const OOM = bun.OOM; const Output = bun.Output; const RegularExpression = bun.RegularExpression; const clap = bun.clap; -const js_ast = bun.js_ast; +const js_ast = bun.ast; const logger = bun.logger; const options = bun.options; const resolve_path = bun.path; -const string = bun.string; const strings = bun.strings; -const Api = bun.Schema.Api; +const Api = bun.schema.api; -const CLI = bun.CLI; +const CLI = bun.cli; const Command = CLI.Command; const DefineColonList = CLI.DefineColonList; const LoaderColonList = CLI.LoaderColonList; diff --git a/src/cli/add_command.zig b/src/cli/add_command.zig index 36c9c54249..a4ba3e0bc0 100644 --- a/src/cli/add_command.zig +++ b/src/cli/add_command.zig @@ -5,7 +5,7 @@ pub const AddCommand = struct { }; const bun = @import("bun"); -const Command = bun.CLI.Command; +const Command = bun.cli.Command; const PackageManager = bun.install.PackageManager; const updatePackageJSONAndInstallCatchError = PackageManager.updatePackageJSONAndInstallCatchError; diff --git a/src/cli/audit_command.zig b/src/cli/audit_command.zig index a780439aa0..911236495f 100644 --- a/src/cli/audit_command.zig +++ b/src/cli/audit_command.zig @@ -103,7 +103,7 @@ pub const AuditCommand = struct { var log = logger.Log.init(ctx.allocator); defer log.deinit(); - const expr = @import("../json_parser.zig").parse(source, &log, ctx.allocator, true) catch { + const expr = bun.json.parse(source, &log, ctx.allocator, true) catch { Output.prettyErrorln("error: audit request failed to parse json. Is the registry down?", .{}); return 1; // If we can't parse then safe to assume a similar failure }; @@ -348,7 +348,7 @@ fn sendAuditRequest(allocator: std.mem.Allocator, pm: *PackageManager, body: []c return try allocator.dupe(u8, response_buf.slice()); } -fn parseVulnerability(allocator: std.mem.Allocator, package_name: []const u8, vuln: bun.JSAst.Expr) bun.OOM!VulnerabilityInfo { +fn parseVulnerability(allocator: std.mem.Allocator, package_name: []const u8, vuln: bun.ast.Expr) bun.OOM!VulnerabilityInfo { var vulnerability = VulnerabilityInfo{ .severity = "moderate", .title = "Vulnerability found", @@ -535,7 +535,7 @@ fn printEnhancedAuditReport( var log = logger.Log.init(allocator); defer log.deinit(); - const expr = @import("../json_parser.zig").parse(source, &log, allocator, true) catch { + const expr = bun.json.parse(source, &log, allocator, true) catch { Output.writer().writeAll(response_text) catch {}; Output.writer().writeByte('\n') catch {}; return 1; diff --git a/src/cli/build_command.zig b/src/cli/build_command.zig index 7b4b69c75d..9ffcbf0378 100644 --- a/src/cli/build_command.zig +++ b/src/cli/build_command.zig @@ -307,7 +307,7 @@ pub const BuildCommand = struct { break :brk (BundleV2.generateFromCLI( &this_transpiler, allocator, - bun.JSC.AnyEventLoop.init(ctx.allocator), + bun.jsc.AnyEventLoop.init(ctx.allocator), ctx.debug.hot_reload == .watch, &reachable_file_count, &minify_duration, @@ -468,13 +468,13 @@ pub const BuildCommand = struct { if (log.errors == 0) { if (this_transpiler.options.transform_only) { Output.prettyln("Transpiled file in {d}ms", .{ - @divFloor(std.time.nanoTimestamp() - bun.CLI.start_time, std.time.ns_per_ms), + @divFloor(std.time.nanoTimestamp() - bun.cli.start_time, std.time.ns_per_ms), }); } else { Output.prettyln("Bundled {d} module{s} in {d}ms", .{ reachable_file_count, if (reachable_file_count == 1) "" else "s", - @divFloor(std.time.nanoTimestamp() - bun.CLI.start_time, std.time.ns_per_ms), + @divFloor(std.time.nanoTimestamp() - bun.cli.start_time, std.time.ns_per_ms), }); } Output.prettyln("\n", .{}); @@ -561,7 +561,7 @@ fn exitOrWatch(code: u8, watch: bool) noreturn { fn printSummary(bundled_end: i128, minify_duration: u64, minified: bool, input_code_length: usize, reachable_file_count: usize, output_files: []const options.OutputFile) void { const padding_buf = [_]u8{' '} ** 16; - const bundle_until_now = @divTrunc(@as(i64, @truncate(bundled_end - bun.CLI.start_time)), @as(i64, std.time.ns_per_ms)); + const bundle_until_now = @divTrunc(@as(i64, @truncate(bundled_end - bun.cli.start_time)), @as(i64, std.time.ns_per_ms)); const bundle_elapsed = if (minified) bundle_until_now - @as(i64, @intCast(@as(u63, @truncate(minify_duration)))) @@ -628,6 +628,8 @@ fn printSummary(bundled_end: i128, minify_duration: u64, minified: bool, input_c ); } +const string = []const u8; + const fs = @import("../fs.zig"); const options = @import("../options.zig"); const resolve_path = @import("../resolver/resolve_path.zig"); @@ -639,6 +641,5 @@ const bun = @import("bun"); const Global = bun.Global; const Output = bun.Output; const default_allocator = bun.default_allocator; -const string = bun.string; const strings = bun.strings; const transpiler = bun.transpiler; diff --git a/src/cli/bunx_command.zig b/src/cli/bunx_command.zig index f33c2d3e6c..bbdb893ddb 100644 --- a/src/cli/bunx_command.zig +++ b/src/cli/bunx_command.zig @@ -25,7 +25,7 @@ pub const BunxCommand = struct { /// - `--revision` or `--version` flags are passed without a target /// command also being provided. This is not a failure. /// - Incorrect arguments are passed. Prints usage and exits with a failure code. - fn parse(ctx: bun.CLI.Command.Context, argv: [][:0]const u8) Allocator.Error!Options { + fn parse(ctx: bun.cli.Command.Context, argv: [][:0]const u8) Allocator.Error!Options { var found_subcommand_name = false; var maybe_package_name: ?string = null; var has_version = false; // --version @@ -140,16 +140,16 @@ pub const BunxCommand = struct { // TODO: make this better if (package_json_read.err) |err| { - try (bun.JSC.Maybe(void){ .err = err }).unwrap(); + try (bun.jsc.Maybe(void){ .err = err }).unwrap(); } const package_json_contents = package_json_read.bytes.items; const source = &bun.logger.Source.initPathString(bun.span(subpath_z), package_json_contents); - bun.JSAst.Expr.Data.Store.create(); - bun.JSAst.Stmt.Data.Store.create(); + bun.ast.Expr.Data.Store.create(); + bun.ast.Stmt.Data.Store.create(); - const expr = try bun.JSON.parsePackageJSONUTF8(source, transpiler.log, transpiler.allocator); + const expr = try bun.json.parsePackageJSONUTF8(source, transpiler.log, transpiler.allocator); // choose the first package that fits if (expr.get("bin")) |bin_expr| { @@ -279,7 +279,7 @@ pub const BunxCommand = struct { Global.exit(1); } - pub fn exec(ctx: bun.CLI.Command.Context, argv: [][:0]const u8) !void { + pub fn exec(ctx: bun.cli.Command.Context, argv: [][:0]const u8) !void { // Don't log stuff ctx.debug.silent = true; @@ -695,7 +695,7 @@ pub const BunxCommand = struct { .stdin = .inherit, .windows = if (Environment.isWindows) .{ - .loop = bun.JSC.EventLoopHandle.init(bun.JSC.MiniEventLoop.initGlobal(this_transpiler.env)), + .loop = bun.jsc.EventLoopHandle.init(bun.jsc.MiniEventLoop.initGlobal(this_transpiler.env)), }, }) catch |err| { Output.prettyErrorln("error: bunx failed to install {s} due to error {s}", .{ install_param, @errorName(err) }); @@ -786,6 +786,8 @@ pub const BunxCommand = struct { } }; +const string = []const u8; + const std = @import("std"); const Run = @import("./run_command.zig").RunCommand; const Allocator = std.mem.Allocator; @@ -798,6 +800,5 @@ const Environment = bun.Environment; const Global = bun.Global; const Output = bun.Output; const default_allocator = bun.default_allocator; -const string = bun.string; const strings = bun.strings; const UpdateRequest = bun.PackageManager.UpdateRequest; diff --git a/src/cli/colon_list_type.zig b/src/cli/colon_list_type.zig index eec050c2f4..0699d94213 100644 --- a/src/cli/colon_list_type.zig +++ b/src/cli/colon_list_type.zig @@ -19,7 +19,7 @@ pub fn ColonListType(comptime t: type, comptime value_resolver: anytype) type { return error.InvalidSeparator; } - if (comptime t == bun.Schema.Api.Loader) { + if (comptime t == bun.schema.api.Loader) { if (str[0..midpoint].len > 0 and str[0] != '.') { Output.prettyErrorln("error: file extension must start with a '.' (while mapping loader {s})", .{bun.fmt.quote(str)}); Global.exit(1); @@ -52,10 +52,11 @@ pub fn ColonListType(comptime t: type, comptime value_resolver: anytype) type { }; } +const string = []const u8; + const std = @import("std"); const bun = @import("bun"); const Global = bun.Global; const Output = bun.Output; -const string = bun.string; const strings = bun.strings; diff --git a/src/cli/create_command.zig b/src/cli/create_command.zig index 864e9956ac..4f7ed16287 100644 --- a/src/cli/create_command.zig +++ b/src/cli/create_command.zig @@ -109,7 +109,7 @@ fn execTask(allocator: std.mem.Allocator, task_: string, cwd: string, _: string, .stdin = .inherit, .windows = if (Environment.isWindows) .{ - .loop = bun.JSC.EventLoopHandle.init(bun.JSC.MiniEventLoop.initGlobal(null)), + .loop = bun.jsc.EventLoopHandle.init(bun.jsc.MiniEventLoop.initGlobal(null)), }, }) catch return; } @@ -1483,7 +1483,7 @@ pub const CreateCommand = struct { .stdin = .inherit, .windows = if (Environment.isWindows) .{ - .loop = bun.JSC.EventLoopHandle.init(bun.JSC.MiniEventLoop.initGlobal(null)), + .loop = bun.jsc.EventLoopHandle.init(bun.jsc.MiniEventLoop.initGlobal(null)), }, }); _ = try process.unwrap(); @@ -1663,7 +1663,7 @@ pub const CreateCommand = struct { .entry_points = &[_]string{analyzer.entry_point}, .onFetch = @ptrCast(&Analyzer.onAnalyze), }; - try bun.CLI.BuildCommand.exec(bun.CLI.Command.get(), &fetcher); + try bun.cli.BuildCommand.exec(bun.cli.Command.get(), &fetcher); } pub fn extractInfo(ctx: Command.Context) !struct { example_tag: Example.Tag, template: []const u8 } { var example_tag = Example.Tag.unknown; @@ -1672,7 +1672,7 @@ pub const CreateCommand = struct { const create_options = try CreateOptions.parse(ctx); const positionals = create_options.positionals; if (positionals.len == 0) { - bun.CLI.Command.Tag.printHelp(.CreateCommand, false); + bun.cli.Command.Tag.printHelp(.CreateCommand, false); Global.crash(); } @@ -2422,6 +2422,8 @@ const GitHandler = struct { } }; +const string = []const u8; + const CopyFile = @import("../copy_file.zig"); const DotEnv = @import("../env_loader.zig"); const SourceFileProjectGenerator = @import("../create/SourceFileProjectGenerator.zig"); @@ -2438,16 +2440,15 @@ const bun = @import("bun"); const Environment = bun.Environment; const Futex = bun.Futex; const Global = bun.Global; -const JSON = bun.JSON; +const JSON = bun.json; const JSPrinter = bun.js_printer; const MutableString = bun.MutableString; const Output = bun.Output; const Progress = bun.Progress; const clap = bun.clap; const default_allocator = bun.default_allocator; -const js_ast = bun.JSAst; +const js_ast = bun.ast; const logger = bun.logger; -const string = bun.string; const strings = bun.strings; const Archiver = bun.libarchive.Archiver; diff --git a/src/cli/exec_command.zig b/src/cli/exec_command.zig index 1ed22f00c3..4d14fbe6dd 100644 --- a/src/cli/exec_command.zig +++ b/src/cli/exec_command.zig @@ -9,7 +9,7 @@ pub const ExecCommand = struct { null, ); try bundle.runEnvLoader(false); - const mini = bun.JSC.MiniEventLoop.initGlobal(bundle.env); + const mini = bun.jsc.MiniEventLoop.initGlobal(bundle.env); var buf: bun.PathBuffer = undefined; const cwd = switch (bun.sys.getcwd(&buf)) { @@ -44,4 +44,4 @@ pub const ExecCommand = struct { const bun = @import("bun"); const Global = bun.Global; const Output = bun.Output; -const Command = bun.CLI.Command; +const Command = bun.cli.Command; diff --git a/src/cli/filter_arg.zig b/src/cli/filter_arg.zig index f1dcc91464..0d072805d6 100644 --- a/src/cli/filter_arg.zig +++ b/src/cli/filter_arg.zig @@ -25,11 +25,11 @@ fn globIgnoreFn(val: []const u8) bool { const GlobWalker = Glob.GlobWalker(globIgnoreFn, Glob.walk.DirEntryAccessor, false); pub fn getCandidatePackagePatterns(allocator: std.mem.Allocator, log: *bun.logger.Log, out_patterns: *std.ArrayList([]u8), workdir_: []const u8, root_buf: *bun.PathBuffer) ![]const u8 { - bun.JSAst.Expr.Data.Store.create(); - bun.JSAst.Stmt.Data.Store.create(); + bun.ast.Expr.Data.Store.create(); + bun.ast.Stmt.Data.Store.create(); defer { - bun.JSAst.Expr.Data.Store.reset(); - bun.JSAst.Stmt.Data.Store.reset(); + bun.ast.Expr.Data.Store.reset(); + bun.ast.Stmt.Data.Store.reset(); } var workdir = workdir_; @@ -273,12 +273,13 @@ pub const PackageFilterIterator = struct { } }; +const string = []const u8; + const Glob = @import("../glob.zig"); const std = @import("std"); const bun = @import("bun"); const Global = bun.Global; -const JSON = bun.JSON; +const JSON = bun.json; const Output = bun.Output; -const string = bun.string; const strings = bun.strings; diff --git a/src/cli/filter_run.zig b/src/cli/filter_run.zig index 34868f2cd2..79e8d074c5 100644 --- a/src/cli/filter_run.zig +++ b/src/cli/filter_run.zig @@ -123,7 +123,7 @@ pub const ProcessHandle = struct { this.state.processExit(this) catch {}; } - pub fn eventLoop(this: *This) *bun.JSC.MiniEventLoop { + pub fn eventLoop(this: *This) *bun.jsc.MiniEventLoop { return this.state.event_loop; } @@ -140,7 +140,7 @@ const State = struct { const This = @This(); handles: []ProcessHandle, - event_loop: *bun.JSC.MiniEventLoop, + event_loop: *bun.jsc.MiniEventLoop, remaining_scripts: usize = 0, // buffer for batched output draw_buf: std.ArrayList(u8) = std.ArrayList(u8).init(bun.default_allocator), @@ -504,7 +504,7 @@ pub fn runScriptsWithFilter(ctx: Command.Context) !noreturn { Global.exit(1); } - const event_loop = bun.JSC.MiniEventLoop.initGlobal(this_transpiler.env); + const event_loop = bun.jsc.MiniEventLoop.initGlobal(this_transpiler.env); const shell_bin: [:0]const u8 = if (Environment.isPosix) RunCommand.findShell(this_transpiler.env.get("PATH") orelse "", fsinstance.top_level_dir) orelse return error.MissingShell else @@ -535,7 +535,7 @@ pub fn runScriptsWithFilter(ctx: Command.Context) !noreturn { .stdout = if (Environment.isPosix) .buffer else .{ .buffer = try bun.default_allocator.create(bun.windows.libuv.Pipe) }, .stderr = if (Environment.isPosix) .buffer else .{ .buffer = try bun.default_allocator.create(bun.windows.libuv.Pipe) }, .cwd = std.fs.path.dirname(script.package_json_path) orelse "", - .windows = if (Environment.isWindows) .{ .loop = bun.JSC.EventLoopHandle.init(event_loop) }, + .windows = if (Environment.isWindows) .{ .loop = bun.jsc.EventLoopHandle.init(event_loop) }, .stream = true, }, }; @@ -650,5 +650,5 @@ const Global = bun.Global; const Output = bun.Output; const transpiler = bun.transpiler; -const CLI = bun.CLI; +const CLI = bun.cli; const Command = CLI.Command; diff --git a/src/cli/init_command.zig b/src/cli/init_command.zig index 330b27b186..22ec411280 100644 --- a/src/cli/init_command.zig +++ b/src/cli/init_command.zig @@ -1239,6 +1239,9 @@ const Template = enum { } }; +const string = []const u8; +const stringZ = [:0]const u8; + const CLI = @import("../cli.zig"); const Fs = @import("../fs.zig"); const options = @import("../options.zig"); @@ -1248,15 +1251,13 @@ const initializeStore = @import("./create_command.zig").initializeStore; const bun = @import("bun"); const Environment = bun.Environment; const Global = bun.Global; -const JSON = bun.JSON; +const JSON = bun.json; const JSPrinter = bun.js_printer; const MutableString = bun.MutableString; const Output = bun.Output; const default_allocator = bun.default_allocator; -const js_ast = bun.JSAst; +const js_ast = bun.ast; const logger = bun.logger; -const string = bun.string; -const stringZ = bun.stringZ; const strings = bun.strings; const exists = bun.sys.exists; diff --git a/src/cli/install_command.zig b/src/cli/install_command.zig index 27e048d1d3..2dd5524580 100644 --- a/src/cli/install_command.zig +++ b/src/cli/install_command.zig @@ -4,7 +4,7 @@ pub const InstallCommand = struct { error.InstallFailed, error.InvalidPackageJSON, => { - const log = &bun.CLI.Cli.log_; + const log = &bun.cli.Cli.log_; log.print(bun.Output.errorWriter()) catch {}; bun.Global.exit(1); }, @@ -48,7 +48,7 @@ fn install(ctx: Command.Context) !void { .onFetch = @ptrCast(&Analyzer.onAnalyze), }; - try bun.CLI.BuildCommand.exec(bun.CLI.Command.get(), &fetcher); + try bun.cli.BuildCommand.exec(bun.cli.Command.get(), &fetcher); return; } @@ -92,14 +92,15 @@ fn installWithCLI(ctx: Command.Context, cli: CommandLineArguments) !void { } } +const string = []const u8; + const std = @import("std"); const bun = @import("bun"); const Global = bun.Global; const Output = bun.Output; const default_allocator = bun.default_allocator; -const string = bun.string; -const Command = bun.CLI.Command; +const Command = bun.cli.Command; const PackageManager = bun.install.PackageManager; const CommandLineArguments = PackageManager.CommandLineArguments; diff --git a/src/cli/install_completions_command.zig b/src/cli/install_completions_command.zig index c49c29eac7..a205cf6c95 100644 --- a/src/cli/install_completions_command.zig +++ b/src/cli/install_completions_command.zig @@ -529,6 +529,8 @@ pub const InstallCompletionsCommand = struct { } }; +const string = []const u8; + const DotEnv = @import("../env_loader.zig"); const ShellCompletions = @import("./shell_completions.zig"); const fs = @import("../fs.zig"); @@ -540,5 +542,4 @@ const bun = @import("bun"); const Environment = bun.Environment; const Global = bun.Global; const Output = bun.Output; -const string = bun.string; const strings = bun.strings; diff --git a/src/cli/link_command.zig b/src/cli/link_command.zig index e9bcf6ed74..8ac22d9d48 100644 --- a/src/cli/link_command.zig +++ b/src/cli/link_command.zig @@ -187,6 +187,8 @@ fn link(ctx: Command.Context) !void { } } +const string = []const u8; + const std = @import("std"); const bun = @import("bun"); @@ -194,9 +196,8 @@ const Environment = bun.Environment; const Global = bun.Global; const Output = bun.Output; const Path = bun.path; -const string = bun.string; const strings = bun.strings; -const Command = bun.CLI.Command; +const Command = bun.cli.Command; const File = bun.sys.File; const Fs = bun.fs; diff --git a/src/cli/outdated_command.zig b/src/cli/outdated_command.zig index 1b91f8f13e..c642b75069 100644 --- a/src/cli/outdated_command.zig +++ b/src/cli/outdated_command.zig @@ -630,6 +630,8 @@ pub const OutdatedCommand = struct { } }; +const string = []const u8; + const std = @import("std"); const bun = @import("bun"); @@ -639,9 +641,8 @@ const Output = bun.Output; const PathBuffer = bun.PathBuffer; const glob = bun.glob; const path = bun.path; -const string = bun.string; const strings = bun.strings; -const Command = bun.CLI.Command; +const Command = bun.cli.Command; const FileSystem = bun.fs.FileSystem; const Table = bun.fmt.Table; diff --git a/src/cli/pack_command.zig b/src/cli/pack_command.zig index 14588a6dc3..50aaef2987 100644 --- a/src/cli/pack_command.zig +++ b/src/cli/pack_command.zig @@ -2482,14 +2482,14 @@ pub const PackCommand = struct { }; pub const bindings = struct { - const JSC = bun.JSC; - const JSValue = JSC.JSValue; - const JSGlobalObject = JSC.JSGlobalObject; - const CallFrame = JSC.CallFrame; - const ZigString = JSC.ZigString; + const jsc = bun.jsc; + const JSValue = jsc.JSValue; + const JSGlobalObject = jsc.JSGlobalObject; + const CallFrame = jsc.CallFrame; + const ZigString = jsc.ZigString; const String = bun.String; - const JSArray = JSC.JSArray; - const JSObject = JSC.JSObject; + const JSArray = jsc.JSArray; + const JSObject = jsc.JSObject; pub fn jsReadTarball(global: *JSGlobalObject, callFrame: *CallFrame) bun.JSError!JSValue { const args = callFrame.arguments_old(1).slice(); @@ -2664,6 +2664,9 @@ pub const bindings = struct { } }; +const string = []const u8; +const stringZ = [:0]const u8; + const std = @import("std"); const libarchive = @import("../libarchive/libarchive.zig").lib; @@ -2675,7 +2678,7 @@ const Environment = bun.Environment; const FD = bun.FD; const FileDescriptor = bun.FileDescriptor; const Global = bun.Global; -const JSON = bun.JSON; +const JSON = bun.json; const OOM = bun.OOM; const Output = bun.Output; const PathBuffer = bun.PathBuffer; @@ -2685,14 +2688,12 @@ const Semver = bun.Semver; const glob = bun.glob; const js_printer = bun.js_printer; const sha = bun.sha; -const string = bun.string; -const stringZ = bun.stringZ; const strings = bun.strings; const CowString = bun.ptr.CowString; const File = bun.sys.File; -const Command = bun.CLI.Command; -const Publish = bun.CLI.PublishCommand; +const Command = bun.cli.Command; +const Publish = bun.cli.PublishCommand; const Install = bun.install; const Dependency = Install.Dependency; diff --git a/src/cli/package_manager_command.zig b/src/cli/package_manager_command.zig index 7906cd4c93..1a569636c7 100644 --- a/src/cli/package_manager_command.zig +++ b/src/cli/package_manager_command.zig @@ -561,6 +561,8 @@ fn printNodeModulesFolderStructure( } } +const string = []const u8; + const Dependency = @import("../install/dependency.zig"); const Fs = @import("../fs.zig"); const Lockfile = @import("../install/lockfile.zig"); @@ -587,6 +589,5 @@ const Environment = bun.Environment; const Global = bun.Global; const Output = bun.Output; const log = bun.log; -const string = bun.string; const strings = bun.strings; const File = bun.sys.File; diff --git a/src/cli/patch_command.zig b/src/cli/patch_command.zig index 47cc1d2a56..4181da37f4 100644 --- a/src/cli/patch_command.zig +++ b/src/cli/patch_command.zig @@ -8,9 +8,10 @@ pub const PatchCommand = struct { } }; +const string = []const u8; + const bun = @import("bun"); -const string = bun.string; -const Command = bun.CLI.Command; +const Command = bun.cli.Command; const PackageManager = bun.install.PackageManager; const updatePackageJSONAndInstallCatchError = PackageManager.updatePackageJSONAndInstallCatchError; diff --git a/src/cli/patch_commit_command.zig b/src/cli/patch_commit_command.zig index 24a8e965db..6f4bc323b1 100644 --- a/src/cli/patch_commit_command.zig +++ b/src/cli/patch_commit_command.zig @@ -5,7 +5,7 @@ pub const PatchCommitCommand = struct { }; const bun = @import("bun"); -const Command = bun.CLI.Command; +const Command = bun.cli.Command; const PackageManager = bun.install.PackageManager; const updatePackageJSONAndInstallCatchError = PackageManager.updatePackageJSONAndInstallCatchError; diff --git a/src/cli/pm_pkg_command.zig b/src/cli/pm_pkg_command.zig index a2de75a05a..a694398c0f 100644 --- a/src/cli/pm_pkg_command.zig +++ b/src/cli/pm_pkg_command.zig @@ -767,16 +767,17 @@ pub const PmPkgCommand = struct { } }; +const string = []const u8; + const std = @import("std"); const bun = @import("bun"); const Global = bun.Global; -const JSON = bun.JSON; +const JSON = bun.json; const JSPrinter = bun.js_printer; const Output = bun.Output; -const js_ast = bun.js_ast; +const js_ast = bun.ast; const logger = bun.logger; -const string = bun.string; const strings = bun.strings; -const Command = bun.CLI.Command; +const Command = bun.cli.Command; const PackageManager = bun.install.PackageManager; diff --git a/src/cli/pm_trusted_command.zig b/src/cli/pm_trusted_command.zig index 3d02a4603f..5ec1807119 100644 --- a/src/cli/pm_trusted_command.zig +++ b/src/cli/pm_trusted_command.zig @@ -345,7 +345,7 @@ pub const TrustCommand = struct { const package_json_source = logger.Source.initPathString(PackageManager.package_json_cwd, package_json_contents); - var package_json = bun.JSON.parseUTF8(&package_json_source, ctx.log, ctx.allocator) catch |err| { + var package_json = bun.json.parseUTF8(&package_json_source, ctx.log, ctx.allocator) catch |err| { ctx.log.print(Output.errorWriter()) catch {}; Output.errGeneric("failed to parse package.json: {s}", .{@errorName(err)}); @@ -433,6 +433,8 @@ pub const TrustCommand = struct { } }; +const string = []const u8; + const std = @import("std"); const Command = @import("../cli.zig").Command; const PackageManagerCommand = @import("./package_manager_command.zig").PackageManagerCommand; @@ -451,6 +453,5 @@ const Global = bun.Global; const Output = bun.Output; const Progress = bun.Progress; const logger = bun.logger; -const string = bun.string; const strings = bun.strings; const String = bun.Semver.String; diff --git a/src/cli/pm_version_command.zig b/src/cli/pm_version_command.zig index 330dd3903e..742fddb01f 100644 --- a/src/cli/pm_version_command.zig +++ b/src/cli/pm_version_command.zig @@ -461,7 +461,7 @@ pub const PmVersionCommand = struct { .cwd = cwd, .envp = null, .windows = if (Environment.isWindows) .{ - .loop = bun.JSC.EventLoopHandle.init(bun.JSC.MiniEventLoop.initGlobal(null)), + .loop = bun.jsc.EventLoopHandle.init(bun.jsc.MiniEventLoop.initGlobal(null)), }, }) catch |err| { Output.errGeneric("Failed to spawn git process: {s}", .{@errorName(err)}); @@ -494,7 +494,7 @@ pub const PmVersionCommand = struct { .cwd = cwd, .envp = null, .windows = if (Environment.isWindows) .{ - .loop = bun.JSC.EventLoopHandle.init(bun.JSC.MiniEventLoop.initGlobal(null)), + .loop = bun.jsc.EventLoopHandle.init(bun.jsc.MiniEventLoop.initGlobal(null)), }, }) catch |err| { Output.err(err, "Failed to spawn git process", .{}); @@ -541,7 +541,7 @@ pub const PmVersionCommand = struct { .stdin = .ignore, .envp = null, .windows = if (Environment.isWindows) .{ - .loop = bun.JSC.EventLoopHandle.init(bun.JSC.MiniEventLoop.initGlobal(null)), + .loop = bun.jsc.EventLoopHandle.init(bun.jsc.MiniEventLoop.initGlobal(null)), }, }) catch |err| { Output.errGeneric("Git add failed: {s}", .{@errorName(err)}); @@ -575,7 +575,7 @@ pub const PmVersionCommand = struct { .stdin = .ignore, .envp = null, .windows = if (Environment.isWindows) .{ - .loop = bun.JSC.EventLoopHandle.init(bun.JSC.MiniEventLoop.initGlobal(null)), + .loop = bun.jsc.EventLoopHandle.init(bun.jsc.MiniEventLoop.initGlobal(null)), }, }) catch |err| { Output.errGeneric("Git commit failed: {s}", .{@errorName(err)}); @@ -606,7 +606,7 @@ pub const PmVersionCommand = struct { .stdin = .ignore, .envp = null, .windows = if (Environment.isWindows) .{ - .loop = bun.JSC.EventLoopHandle.init(bun.JSC.MiniEventLoop.initGlobal(null)), + .loop = bun.jsc.EventLoopHandle.init(bun.jsc.MiniEventLoop.initGlobal(null)), }, }) catch |err| { Output.errGeneric("Git tag failed: {s}", .{@errorName(err)}); @@ -628,18 +628,19 @@ pub const PmVersionCommand = struct { } }; +const string = []const u8; + const std = @import("std"); const bun = @import("bun"); const Environment = bun.Environment; const Global = bun.Global; -const JSON = bun.JSON; +const JSON = bun.json; const JSPrinter = bun.js_printer; const Output = bun.Output; const RunCommand = bun.RunCommand; const Semver = bun.Semver; const logger = bun.logger; -const string = bun.string; const strings = bun.strings; -const Command = bun.CLI.Command; +const Command = bun.cli.Command; const PackageManager = bun.install.PackageManager; diff --git a/src/cli/pm_view_command.zig b/src/cli/pm_view_command.zig index 3c4ff1be5d..ec06f94be6 100644 --- a/src/cli/pm_view_command.zig +++ b/src/cli/pm_view_command.zig @@ -186,13 +186,13 @@ pub fn view(allocator: std.mem.Allocator, manager: *PackageManager, spec_: strin // Treat versions specially because npm does some normalization on there. if (json.getObject("versions")) |versions_object| { - const keys = try allocator.alloc(bun.JSAst.Expr, versions_object.data.e_object.properties.len); + const keys = try allocator.alloc(bun.ast.Expr, versions_object.data.e_object.properties.len); for (versions_object.data.e_object.properties.slice(), keys) |*prop, *key| { key.* = prop.key.?; } - const versions_array = bun.JSAst.Expr.init( - bun.JSAst.E.Array, - bun.JSAst.E.Array{ + const versions_array = bun.ast.Expr.init( + bun.ast.E.Array, + bun.ast.E.Array{ .items = .init(keys), }, .{ .start = -1 }, @@ -391,18 +391,19 @@ pub fn view(allocator: std.mem.Allocator, manager: *PackageManager, spec_: strin } } +const string = []const u8; + const std = @import("std"); -const strings = @import("../string_immutable.zig"); const PackageManager = @import("../install/install.zig").PackageManager; const PackageManifest = @import("../install/npm.zig").PackageManifest; const URL = @import("../url.zig").URL; -const string = @import("../string_types.zig").string; const bun = @import("bun"); const Global = bun.Global; -const JSON = bun.JSON; +const JSON = bun.json; const MutableString = bun.MutableString; const Output = bun.Output; const Semver = bun.Semver; const http = bun.http; const logger = bun.logger; +const strings = bun.strings; diff --git a/src/cli/pm_why_command.zig b/src/cli/pm_why_command.zig index 4cb7deffc3..0285bb61ed 100644 --- a/src/cli/pm_why_command.zig +++ b/src/cli/pm_why_command.zig @@ -4,9 +4,9 @@ pub const PmWhyCommand = struct { } }; -const WhyCommand = @import("./why_command.zig").WhyCommand; +const string = []const u8; const bun = @import("bun"); -const string = bun.string; -const Command = bun.CLI.Command; +const WhyCommand = @import("./why_command.zig").WhyCommand; +const Command = bun.cli.Command; const PackageManager = bun.install.PackageManager; diff --git a/src/cli/publish_command.zig b/src/cli/publish_command.zig index 7a218f9d09..015b66735a 100644 --- a/src/cli/publish_command.zig +++ b/src/cli/publish_command.zig @@ -1342,6 +1342,9 @@ pub const PublishCommand = struct { } }; +const string = []const u8; +const stringZ = [:0]const u8; + const Open = @import("../open.zig"); const std = @import("std"); @@ -1349,7 +1352,7 @@ const bun = @import("bun"); const DotEnv = bun.DotEnv; const Environment = bun.Environment; const Global = bun.Global; -const JSON = bun.JSON; +const JSON = bun.json; const MutableString = bun.MutableString; const OOM = bun.OOM; const Output = bun.Output; @@ -1357,21 +1360,19 @@ const URL = bun.URL; const logger = bun.logger; const path = bun.path; const sha = bun.sha; -const string = bun.string; -const stringZ = bun.stringZ; const strings = bun.strings; const Expr = bun.js_parser.Expr; const File = bun.sys.File; const FileSystem = bun.fs.FileSystem; const Archive = bun.libarchive.lib.Archive; -const Command = bun.CLI.Command; -const Pack = bun.CLI.PackCommand; -const Run = bun.CLI.RunCommand; -const prompt = bun.CLI.InitCommand.prompt; +const E = bun.ast.E; +const G = bun.ast.G; -const E = bun.JSAst.E; -const G = bun.JSAst.G; +const Command = bun.cli.Command; +const Pack = bun.cli.PackCommand; +const Run = bun.cli.RunCommand; +const prompt = bun.cli.InitCommand.prompt; const http = bun.http; const HeaderBuilder = http.HeaderBuilder; diff --git a/src/cli/remove_command.zig b/src/cli/remove_command.zig index 17394f65ce..f4a72f3f88 100644 --- a/src/cli/remove_command.zig +++ b/src/cli/remove_command.zig @@ -5,7 +5,7 @@ pub const RemoveCommand = struct { }; const bun = @import("bun"); -const Command = bun.CLI.Command; +const Command = bun.cli.Command; const PackageManager = bun.install.PackageManager; const updatePackageJSONAndInstallCatchError = PackageManager.updatePackageJSONAndInstallCatchError; diff --git a/src/cli/run_command.zig b/src/cli/run_command.zig index 476bbe1fac..681e8e286c 100644 --- a/src/cli/run_command.zig +++ b/src/cli/run_command.zig @@ -246,7 +246,7 @@ pub const RunCommand = struct { } if (!use_system_shell) { - const mini = bun.JSC.MiniEventLoop.initGlobal(env); + const mini = bun.jsc.MiniEventLoop.initGlobal(env); const code = bun.shell.Interpreter.initAndRunFromSource(ctx, mini, name, copy_script.items, cwd) catch |err| { if (!silent) { Output.prettyErrorln("error: Failed to run script {s} due to error {s}", .{ name, @errorName(err) }); @@ -294,7 +294,7 @@ pub const RunCommand = struct { .ipc = ipc_fd, .windows = if (Environment.isWindows) .{ - .loop = JSC.EventLoopHandle.init(JSC.MiniEventLoop.initGlobal(env)), + .loop = jsc.EventLoopHandle.init(jsc.MiniEventLoop.initGlobal(env)), }, }) catch |err| { if (!silent) { @@ -458,7 +458,7 @@ pub const RunCommand = struct { .use_execve_on_macos = silent, .windows = if (Environment.isWindows) .{ - .loop = JSC.EventLoopHandle.init(JSC.MiniEventLoop.initGlobal(env)), + .loop = jsc.EventLoopHandle.init(jsc.MiniEventLoop.initGlobal(env)), }, }) catch |err| { bun.handleErrorReturnTrace(err, @errorReturnTrace()); @@ -574,7 +574,7 @@ pub const RunCommand = struct { const args = ctx.args; var this_transpiler = try transpiler.Transpiler.init(ctx.allocator, ctx.log, args, null); - this_transpiler.options.env.behavior = Api.DotEnvBehavior.load_all; + this_transpiler.options.env.behavior = api.DotEnvBehavior.load_all; this_transpiler.options.env.prefix = ""; this_transpiler.resolver.care_about_bin_folder = true; @@ -757,7 +757,7 @@ pub const RunCommand = struct { ) !*DirInfo { const args = ctx.args; this_transpiler.* = try transpiler.Transpiler.init(ctx.allocator, ctx.log, args, env); - this_transpiler.options.env.behavior = Api.DotEnvBehavior.load_all; + this_transpiler.options.env.behavior = api.DotEnvBehavior.load_all; this_transpiler.env.quiet = true; this_transpiler.options.env.prefix = ""; @@ -957,7 +957,7 @@ pub const RunCommand = struct { const args = ctx.args; var this_transpiler = transpiler.Transpiler.init(ctx.allocator, ctx.log, args, null) catch return shell_out; - this_transpiler.options.env.behavior = Api.DotEnvBehavior.load_all; + this_transpiler.options.env.behavior = api.DotEnvBehavior.load_all; this_transpiler.options.env.prefix = ""; this_transpiler.env.quiet = true; @@ -1291,7 +1291,7 @@ pub const RunCommand = struct { } if (!ctx.debug.loaded_bunfig) { - bun.CLI.Arguments.loadConfigPath(ctx.allocator, true, "bunfig.toml", ctx, .RunCommand) catch {}; + bun.cli.Arguments.loadConfigPath(ctx.allocator, true, "bunfig.toml", ctx, .RunCommand) catch {}; } _ = _bootAndHandleError(ctx, absolute_script_path.?, null); @@ -1351,7 +1351,7 @@ pub const RunCommand = struct { this_transpiler.env.map.put("npm_command", "run-script") catch unreachable; if (!ctx.debug.loaded_bunfig) { - bun.CLI.Arguments.loadConfigPath(ctx.allocator, true, "bunfig.toml", ctx, .RunCommand) catch {}; + bun.cli.Arguments.loadConfigPath(ctx.allocator, true, "bunfig.toml", ctx, .RunCommand) catch {}; } // check for empty command @@ -1711,14 +1711,15 @@ pub const BunXFastPath = struct { } }; +const string = []const u8; +const stringZ = [:0]const u8; + const DotEnv = @import("../env_loader.zig"); const ShellCompletions = @import("./shell_completions.zig"); const options = @import("../options.zig"); const resolve_path = @import("../resolver/resolve_path.zig"); const std = @import("std"); -const Api = @import("../api/schema.zig").Api; const PackageJSON = @import("../resolver/package_json.zig").PackageJSON; -const Run = @import("../bun_js.zig").Run; const which = @import("../which.zig").which; const yarn_commands = @import("./list-of-yarn-commands.zig").all_yarn_commands; const windows = std.os.windows; @@ -1726,16 +1727,16 @@ const windows = std.os.windows; const bun = @import("bun"); const Environment = bun.Environment; const Global = bun.Global; -const JSC = bun.JSC; const OOM = bun.OOM; const Output = bun.Output; const clap = bun.clap; const default_allocator = bun.default_allocator; -const string = bun.string; -const stringZ = bun.stringZ; +const jsc = bun.jsc; const strings = bun.strings; const transpiler = bun.transpiler; +const Run = bun.bun_js.Run; +const api = bun.schema.api; -const CLI = bun.CLI; +const CLI = bun.cli; const Arguments = CLI.Arguments; const Command = CLI.Command; diff --git a/src/cli/test/Scanner.zig b/src/cli/test/Scanner.zig index 89385ec947..8f4369a919 100644 --- a/src/cli/test/Scanner.zig +++ b/src/cli/test/Scanner.zig @@ -218,8 +218,8 @@ const bun = @import("bun"); const Transpiler = bun.Transpiler; const FileSystem = bun.fs.FileSystem; -const JSC = bun.JSC; -const jest = JSC.Jest; +const jsc = bun.jsc; +const jest = jsc.Jest; const strings = bun.strings; const StringOrTinyString = strings.StringOrTinyString; diff --git a/src/cli/test_command.zig b/src/cli/test_command.zig index af539822b1..b5ad3df23a 100644 --- a/src/cli/test_command.zig +++ b/src/cli/test_command.zig @@ -934,7 +934,7 @@ pub const CommandLineReporter = struct { Output.printStartEnd(bun.start_time, std.time.nanoTimestamp()); } - pub fn generateCodeCoverage(this: *CommandLineReporter, vm: *JSC.VirtualMachine, opts: *TestCommand.CodeCoverageOptions, comptime reporters: TestCommand.Reporters, comptime enable_ansi_colors: bool) !void { + pub fn generateCodeCoverage(this: *CommandLineReporter, vm: *jsc.VirtualMachine, opts: *TestCommand.CodeCoverageOptions, comptime reporters: TestCommand.Reporters, comptime enable_ansi_colors: bool) !void { if (comptime !reporters.text and !reporters.lcov) { return; } @@ -963,7 +963,7 @@ pub const CommandLineReporter = struct { pub fn printCodeCoverage( _: *CommandLineReporter, - vm: *JSC.VirtualMachine, + vm: *jsc.VirtualMachine, opts: *TestCommand.CodeCoverageOptions, byte_ranges: []bun.sourcemap.coverage.ByteRangeMapping, comptime reporters: TestCommand.Reporters, @@ -1049,11 +1049,11 @@ pub const CommandLineReporter = struct { if (comptime !reporters.lcov) break :brk .{ {}, {}, {}, {} }; // Ensure the directory exists - var fs = bun.JSC.Node.fs.NodeFS{}; + var fs = bun.jsc.Node.fs.NodeFS{}; _ = fs.mkdirRecursive( .{ - .path = bun.JSC.Node.PathLike{ - .encoded_slice = JSC.ZigString.Slice.fromUTF8NeverFree(opts.reports_directory), + .path = bun.jsc.Node.PathLike{ + .encoded_slice = jsc.ZigString.Slice.fromUTF8NeverFree(opts.reports_directory), }, .always_return_none = true, }, @@ -1218,7 +1218,7 @@ pub const CommandLineReporter = struct { }; export fn BunTest__shouldGenerateCodeCoverage(test_name_str: bun.String) callconv(.C) bool { - var zig_slice: bun.JSC.ZigString.Slice = .{}; + var zig_slice: bun.jsc.ZigString.Slice = .{}; defer zig_slice.deinit(); // In this particular case, we don't actually care about non-ascii latin1 characters. @@ -1234,7 +1234,7 @@ export fn BunTest__shouldGenerateCodeCoverage(test_name_str: bun.String) callcon } const ext = std.fs.path.extension(slice); - const loader_by_ext = JSC.VirtualMachine.get().transpiler.options.loader(ext); + const loader_by_ext = jsc.VirtualMachine.get().transpiler.options.loader(ext); // allow file loader just incase they use a custom loader with a non-standard extension if (!(loader_by_ext.isJavaScriptLike() or loader_by_ext == .file)) { @@ -1295,14 +1295,14 @@ pub const TestCommand = struct { loader.* = DotEnv.Loader.init(map, ctx.allocator); break :brk loader; }; - bun.JSC.initialize(false); + bun.jsc.initialize(false); HTTPThread.init(&.{}); var snapshot_file_buf = std.ArrayList(u8).init(ctx.allocator); var snapshot_values = Snapshots.ValuesHashMap.init(ctx.allocator); var snapshot_counts = bun.StringHashMap(usize).init(ctx.allocator); var inline_snapshots_to_write = std.AutoArrayHashMap(TestRunner.File.ID, std.ArrayList(Snapshots.InlineSnapshotToWrite)).init(ctx.allocator); - JSC.VirtualMachine.isBunTest = true; + jsc.VirtualMachine.isBunTest = true; var reporter = try ctx.allocator.create(CommandLineReporter); defer { @@ -1358,7 +1358,7 @@ pub const TestCommand = struct { js_ast.Expr.Data.Store.create(); js_ast.Stmt.Data.Store.create(); - var vm = try JSC.VirtualMachine.init( + var vm = try jsc.VirtualMachine.init( .{ .allocator = ctx.allocator, .args = ctx.args, @@ -1394,7 +1394,7 @@ pub const TestCommand = struct { vm.loadExtraEnvAndSourceCodePrinter(); vm.is_main_thread = true; - JSC.VirtualMachine.is_main_thread_vm = true; + jsc.VirtualMachine.is_main_thread_vm = true; if (ctx.test_options.coverage.enabled) { vm.transpiler.options.code_coverage = true; @@ -1416,7 +1416,7 @@ pub const TestCommand = struct { } if (TZ_NAME.len > 0) { - _ = vm.global.setTimeZone(&JSC.ZigString.init(TZ_NAME)); + _ = vm.global.setTimeZone(&jsc.ZigString.init(TZ_NAME)); } // Start the debugger before we scan for files @@ -1495,8 +1495,8 @@ pub const TestCommand = struct { vm.hot_reload = ctx.debug.hot_reload; switch (vm.hot_reload) { - .hot => JSC.hot_reloader.HotReloader.enableHotModuleReloading(vm), - .watch => JSC.hot_reloader.WatchReloader.enableHotModuleReloading(vm), + .hot => jsc.hot_reloader.HotReloader.enableHotModuleReloading(vm), + .watch => jsc.hot_reloader.WatchReloader.enableHotModuleReloading(vm), else => {}, } @@ -1719,7 +1719,7 @@ pub const TestCommand = struct { } if (vm.hot_reload == .watch) { - vm.runWithAPILock(JSC.VirtualMachine, vm, runEventLoopForWatch); + vm.runWithAPILock(jsc.VirtualMachine, vm, runEventLoopForWatch); } const summary = reporter.summary(); @@ -1728,11 +1728,11 @@ pub const TestCommand = struct { } else if (reporter.jest.unhandled_errors_between_tests > 0) { Global.exit(reporter.jest.unhandled_errors_between_tests); } else { - vm.runWithAPILock(JSC.VirtualMachine, vm, JSC.VirtualMachine.globalExit); + vm.runWithAPILock(jsc.VirtualMachine, vm, jsc.VirtualMachine.globalExit); } } - fn runEventLoopForWatch(vm: *JSC.VirtualMachine) void { + fn runEventLoopForWatch(vm: *jsc.VirtualMachine) void { vm.eventLoop().tickPossiblyForever(); while (true) { @@ -1747,13 +1747,13 @@ pub const TestCommand = struct { pub fn runAllTests( reporter_: *CommandLineReporter, - vm_: *JSC.VirtualMachine, + vm_: *jsc.VirtualMachine, files_: []const PathString, allocator_: std.mem.Allocator, ) void { const Context = struct { reporter: *CommandLineReporter, - vm: *JSC.VirtualMachine, + vm: *jsc.VirtualMachine, files: []const PathString, allocator: std.mem.Allocator, pub fn begin(this: *@This()) void { @@ -1787,7 +1787,7 @@ pub const TestCommand = struct { pub fn run( reporter: *CommandLineReporter, - vm: *JSC.VirtualMachine, + vm: *jsc.VirtualMachine, file_name: string, _: std.mem.Allocator, is_last: bool, @@ -1907,7 +1907,7 @@ pub const TestCommand = struct { vm.global.handleRejectedPromises(); if (repeat_index > 0) { try vm.clearEntryPoint(); - var entry = JSC.ZigString.init(file_path); + var entry = jsc.ZigString.init(file_path); try vm.global.deleteModuleRegistryEntry(&entry); } @@ -1944,6 +1944,8 @@ pub fn @"export"() void { _ = &Scanner.BunTest__shouldGenerateCodeCoverage; } +const string = []const u8; + const DotEnv = @import("../env_loader.zig"); const Scanner = @import("./test/Scanner.zig"); const options = @import("../options.zig"); @@ -1960,17 +1962,16 @@ const MutableString = bun.MutableString; const Output = bun.Output; const PathString = bun.PathString; const default_allocator = bun.default_allocator; -const js_ast = bun.JSAst; -const string = bun.string; +const js_ast = bun.ast; const strings = bun.strings; const uws = bun.uws; const HTTPThread = bun.http.HTTPThread; -const JSC = bun.JSC; -const jest = JSC.Jest; -const Snapshots = JSC.Snapshot.Snapshots; +const jsc = bun.jsc; +const jest = jsc.Jest; +const Snapshots = jsc.Snapshot.Snapshots; -const TestRunner = JSC.Jest.TestRunner; +const TestRunner = jsc.Jest.TestRunner; const Test = TestRunner.Test; const coverage = bun.sourcemap.coverage; diff --git a/src/cli/unlink_command.zig b/src/cli/unlink_command.zig index e6b15aa93c..1cc48c2def 100644 --- a/src/cli/unlink_command.zig +++ b/src/cli/unlink_command.zig @@ -130,15 +130,16 @@ fn unlink(ctx: Command.Context) !void { } } +const string = []const u8; + const std = @import("std"); const bun = @import("bun"); const Global = bun.Global; const Output = bun.Output; const Path = bun.path; -const string = bun.string; const strings = bun.strings; -const Command = bun.CLI.Command; +const Command = bun.cli.Command; const Bin = bun.install.Bin; const Features = bun.install.Features; diff --git a/src/cli/update_command.zig b/src/cli/update_command.zig index b21a774dde..c280ba7f31 100644 --- a/src/cli/update_command.zig +++ b/src/cli/update_command.zig @@ -12,7 +12,7 @@ pub const UpdateCommand = struct { }; const bun = @import("bun"); -const Command = bun.CLI.Command; +const Command = bun.cli.Command; const PackageManager = bun.install.PackageManager; const updatePackageJSONAndInstallCatchError = PackageManager.updatePackageJSONAndInstallCatchError; diff --git a/src/cli/update_interactive_command.zig b/src/cli/update_interactive_command.zig index 1c88c23225..8105fa4526 100644 --- a/src/cli/update_interactive_command.zig +++ b/src/cli/update_interactive_command.zig @@ -1101,6 +1101,8 @@ pub const UpdateInteractiveCommand = struct { extern fn Bun__ttySetMode(fd: c_int, mode: c_int) c_int; +const string = []const u8; + const std = @import("std"); const bun = @import("bun"); @@ -1112,16 +1114,15 @@ const Output = bun.Output; const PathBuffer = bun.PathBuffer; const glob = bun.glob; const path = bun.path; -const string = bun.string; const strings = bun.strings; const FileSystem = bun.fs.FileSystem; -const Command = bun.CLI.Command; -const OutdatedCommand = bun.CLI.OutdatedCommand; - const Semver = bun.Semver; const SlicedString = Semver.SlicedString; +const Command = bun.cli.Command; +const OutdatedCommand = bun.cli.OutdatedCommand; + const Install = bun.install; const DependencyID = Install.DependencyID; const PackageID = Install.PackageID; diff --git a/src/cli/upgrade_command.zig b/src/cli/upgrade_command.zig index cca8743e25..cc83cbc352 100644 --- a/src/cli/upgrade_command.zig +++ b/src/cli/upgrade_command.zig @@ -601,7 +601,7 @@ pub const UpgradeCommand = struct { .stdin = .inherit, .windows = if (Environment.isWindows) .{ - .loop = bun.JSC.EventLoopHandle.init(bun.JSC.MiniEventLoop.initGlobal(null)), + .loop = bun.jsc.EventLoopHandle.init(bun.jsc.MiniEventLoop.initGlobal(null)), }, }) catch |err| { Output.prettyErrorln("error: Failed to spawn Expand-Archive on {s} due to error {s}", .{ tmpname, @errorName(err) }); @@ -893,24 +893,24 @@ pub const UpgradeCommand = struct { }; pub const upgrade_js_bindings = struct { - const JSC = bun.JSC; - const JSValue = JSC.JSValue; - const ZigString = JSC.ZigString; + const jsc = bun.jsc; + const JSValue = jsc.JSValue; + const ZigString = jsc.ZigString; var tempdir_fd: ?bun.FileDescriptor = null; - pub fn generate(global: *JSC.JSGlobalObject) JSC.JSValue { + pub fn generate(global: *jsc.JSGlobalObject) jsc.JSValue { const obj = JSValue.createEmptyObject(global, 3); const open = ZigString.static("openTempDirWithoutSharingDelete"); - obj.put(global, open, JSC.createCallback(global, open, 1, jsOpenTempDirWithoutSharingDelete)); + obj.put(global, open, jsc.createCallback(global, open, 1, jsOpenTempDirWithoutSharingDelete)); const close = ZigString.static("closeTempDirHandle"); - obj.put(global, close, JSC.createCallback(global, close, 1, jsCloseTempDirHandle)); + obj.put(global, close, jsc.createCallback(global, close, 1, jsCloseTempDirHandle)); return obj; } /// For testing upgrades when the temp directory has an open handle without FILE_SHARE_DELETE. /// Windows only - pub fn jsOpenTempDirWithoutSharingDelete(_: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!bun.JSC.JSValue { + pub fn jsOpenTempDirWithoutSharingDelete(_: *jsc.JSGlobalObject, _: *jsc.CallFrame) bun.JSError!bun.jsc.JSValue { if (comptime !Environment.isWindows) return .js_undefined; const w = std.os.windows; @@ -964,7 +964,7 @@ pub const upgrade_js_bindings = struct { return .js_undefined; } - pub fn jsCloseTempDirHandle(_: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!JSValue { + pub fn jsCloseTempDirHandle(_: *jsc.JSGlobalObject, _: *jsc.CallFrame) bun.JSError!JSValue { if (comptime !Environment.isWindows) return .js_undefined; if (tempdir_fd) |fd| { @@ -980,6 +980,9 @@ pub fn @"export"() void { Version.@"export"(); } +const string = []const u8; +const stringZ = [:0]const u8; + const DotEnv = @import("../env_loader.zig"); const fs = @import("../fs.zig"); const linker = @import("../linker.zig"); @@ -992,15 +995,13 @@ const which = @import("../which.zig").which; const bun = @import("bun"); const Environment = bun.Environment; const Global = bun.Global; -const JSON = bun.JSON; +const JSON = bun.json; const MutableString = bun.MutableString; const Output = bun.Output; const Progress = bun.Progress; const default_allocator = bun.default_allocator; -const js_ast = bun.JSAst; +const js_ast = bun.ast; const logger = bun.logger; -const string = bun.string; -const stringZ = bun.stringZ; const strings = bun.strings; const HTTP = bun.http; diff --git a/src/cli/why_command.zig b/src/cli/why_command.zig index 042bce6214..a88234b44a 100644 --- a/src/cli/why_command.zig +++ b/src/cli/why_command.zig @@ -477,6 +477,8 @@ pub const WhyCommand = struct { } }; +const string = []const u8; + const std = @import("std"); const PackageID = @import("../install/install.zig").PackageID; const PackageManagerCommand = @import("./package_manager_command.zig").PackageManagerCommand; @@ -485,7 +487,6 @@ const bun = @import("bun"); const Global = bun.Global; const Output = bun.Output; const Semver = bun.Semver; -const string = bun.string; const strings = bun.strings; -const Command = bun.CLI.Command; +const Command = bun.cli.Command; const PackageManager = bun.install.PackageManager; diff --git a/src/codegen/bindgen.ts b/src/codegen/bindgen.ts index a96dcd0ccd..a33ad4a470 100644 --- a/src/codegen/bindgen.ts +++ b/src/codegen/bindgen.ts @@ -804,7 +804,7 @@ function zigTypeNameInner(type: TypeImpl): string { return "usize"; case "globalObject": case "zigVirtualMachine": - return "*JSC.JSGlobalObject"; + return "*jsc.JSGlobalObject"; default: const cAbiType = type.canDirectlyMapToCAbi(); if (cAbiType) { @@ -837,7 +837,7 @@ function returnStrategyZigType(strategy: ReturnStrategy): string { case "void": return "bool"; // true=success, false=exception case "jsvalue": - return "JSC.JSValue"; + return "jsc.JSValue"; default: throw new Error( `TODO: returnStrategyZigType for ${Bun.inspect(strategy satisfies never, { colors: Bun.enableANSIColors })}`, @@ -1129,8 +1129,8 @@ const cppInternal = new CodeWriter(); const headers = new Set(); zig.line('const bun = @import("bun");'); -zig.line("const JSC = bun.JSC;"); -zig.line("const JSHostFunctionType = JSC.JSHostFn;\n"); +zig.line("const jsc = bun.jsc;"); +zig.line("const JSHostFunctionType = jsc.JSHostFn;\n"); zigInternal.line("const binding_internals = struct {"); zigInternal.indent(); @@ -1308,7 +1308,7 @@ for (const [filename, { functions, typedefs }] of files) { let globalObjectArg = ""; if (vari.globalObjectArg === "hidden") { - args.push(`global: *JSC.JSGlobalObject`); + args.push(`global: *jsc.JSGlobalObject`); globalObjectArg = "global"; } let argNum = 0; @@ -1366,7 +1366,7 @@ for (const [filename, { functions, typedefs }] of files) { switch (returnStrategy.type) { case "jsvalue": - zigInternal.add(`return JSC.toJSHostCall(${globalObjectArg}, @src(), `); + zigInternal.add(`return jsc.toJSHostCall(${globalObjectArg}, @src(), `); break; case "basic-out-param": zigInternal.add(`out.* = @as(bun.JSError!${returnStrategy.abiType}, `); @@ -1452,9 +1452,9 @@ for (const [filename, { functions, typedefs }] of files) { // Wrapper to init JSValue const wrapperName = zid("create" + cap(fn.name) + "Callback"); const minArgCount = fn.variants.reduce((acc, vari) => Math.min(acc, vari.args.length), Number.MAX_SAFE_INTEGER); - zig.line(`pub fn ${wrapperName}(global: *JSC.JSGlobalObject) callconv(JSC.conv) JSC.JSValue {`); + zig.line(`pub fn ${wrapperName}(global: *jsc.JSGlobalObject) callconv(jsc.conv) jsc.JSValue {`); zig.line( - ` return JSC.host_fn.NewRuntimeFunction(global, JSC.ZigString.static(${str(fn.name)}), ${minArgCount}, js${cap(fn.name)}, false, false, null);`, + ` return jsc.host_fn.NewRuntimeFunction(global, jsc.ZigString.static(${str(fn.name)}), ${minArgCount}, js${cap(fn.name)}, false, false, null);`, ); zig.line(`}`); } diff --git a/src/codegen/generate-js2native.ts b/src/codegen/generate-js2native.ts index 84c0aa7065..f8f8e82449 100644 --- a/src/codegen/generate-js2native.ts +++ b/src/codegen/generate-js2native.ts @@ -46,6 +46,7 @@ function resolveNativeFileId(call_type: NativeCallType, filename: string) { throw new Error(`Expected filename for $${call_type} to have ${ext} extension, got ${JSON.stringify(filename)}`); } + filename = filename.replaceAll("/", sep); const resolved = sourceFiles.find(file => file.endsWith(sep + filename)); if (!resolved) { const fnName = call_type === "bind" ? "bindgenFn" : call_type; @@ -210,12 +211,12 @@ export function getJS2NativeZig(gs2NativeZigPath: string) { return [ "//! This file is generated by src/codegen/generate-js2native.ts based on seen calls to the $zig() JS macro", `const bun = @import("bun");`, - `const JSC = bun.JSC;`, + `const jsc = bun.jsc;`, ...nativeCalls .filter(x => x.type === "zig") .flatMap(call => [ - `export fn ${symbol(call)}_workaround(global: *JSC.JSGlobalObject) callconv(JSC.conv) JSC.JSValue {`, - ` return JSC.toJSHostCall(global, @src(), @import(${JSON.stringify(path.relative(path.dirname(gs2NativeZigPath), call.filename))}).${call.symbol}, .{global});`, + `export fn ${symbol(call)}_workaround(global: *jsc.JSGlobalObject) callconv(jsc.conv) jsc.JSValue {`, + ` return jsc.toJSHostCall(global, @src(), @import(${JSON.stringify(path.relative(path.dirname(gs2NativeZigPath), call.filename))}).${call.symbol}, .{global});`, "}", ]), ...wrapperCalls @@ -225,9 +226,9 @@ export function getJS2NativeZig(gs2NativeZigPath: string) { type: "zig", symbol: x.symbol_target, filename: x.filename, - })}(global: *JSC.JSGlobalObject, call_frame: *JSC.CallFrame) callconv(JSC.conv) JSC.JSValue {`, + })}(global: *jsc.JSGlobalObject, call_frame: *jsc.CallFrame) callconv(jsc.conv) jsc.JSValue {`, ` const function = @import(${JSON.stringify(path.relative(path.dirname(gs2NativeZigPath), x.filename))});`, - ` return @call(.always_inline, JSC.toJSHostFn(function.${x.symbol_target}), .{global, call_frame});`, + ` return @call(.always_inline, jsc.toJSHostFn(function.${x.symbol_target}), .{global, call_frame});`, "}", ]), "comptime {", diff --git a/src/codegen/generate-node-errors.ts b/src/codegen/generate-node-errors.ts index bb41dc1389..c3f10c0bc0 100644 --- a/src/codegen/generate-node-errors.ts +++ b/src/codegen/generate-node-errors.ts @@ -53,11 +53,11 @@ zig = ` // Generated by: src/codegen/generate-node-errors.ts const std = @import("std"); const bun = @import("bun"); -const JSC = bun.JSC; +const jsc = bun.jsc; pub fn ErrorBuilder(comptime code: Error, comptime fmt: [:0]const u8, Args: type) type { return struct { - global: *JSC.JSGlobalObject, + global: *jsc.JSGlobalObject, args: Args, // Throw this error as a JS exception @@ -66,16 +66,16 @@ pub fn ErrorBuilder(comptime code: Error, comptime fmt: [:0]const u8, Args: type } /// Turn this into a JSValue - pub inline fn toJS(this: @This()) JSC.JSValue { + pub inline fn toJS(this: @This()) jsc.JSValue { return code.fmt(this.global, fmt, this.args); } /// Turn this into a JSPromise that is already rejected. - pub inline fn reject(this: @This()) JSC.JSValue { + pub inline fn reject(this: @This()) jsc.JSValue { if (comptime bun.FeatureFlags.breaking_changes_1_3) { - return JSC.JSPromise.rejectedPromise(this.globalThis, code.fmt(this.global, fmt, this.args)).toJS(); + return jsc.JSPromise.rejectedPromise(this.globalThis, code.fmt(this.global, fmt, this.args)).toJS(); } else { - return JSC.JSPromise.dangerouslyCreateRejectedPromiseValueWithoutNotifyingVM(this.global, code.fmt(this.global, fmt, this.args)); + return jsc.JSPromise.dangerouslyCreateRejectedPromiseValueWithoutNotifyingVM(this.global, code.fmt(this.global, fmt, this.args)); } } }; @@ -121,17 +121,17 @@ listHeader += ` zig += ` - extern fn Bun__createErrorWithCode(globalThis: *JSC.JSGlobalObject, code: Error, message: *bun.String) JSC.JSValue; + extern fn Bun__createErrorWithCode(globalThis: *jsc.JSGlobalObject, code: Error, message: *bun.String) jsc.JSValue; /// Creates an Error object with the given error code. /// If an error is thrown while creating the Error object, returns that error instead. /// Derefs the message string. - pub fn toJS(this: Error, globalThis: *JSC.JSGlobalObject, message: *bun.String) JSC.JSValue { + pub fn toJS(this: Error, globalThis: *jsc.JSGlobalObject, message: *bun.String) jsc.JSValue { defer message.deref(); return Bun__createErrorWithCode(globalThis, this, message); } - pub fn fmt(this: Error, globalThis: *JSC.JSGlobalObject, comptime fmt_str: [:0]const u8, args: anytype) JSC.JSValue { + pub fn fmt(this: Error, globalThis: *jsc.JSGlobalObject, comptime fmt_str: [:0]const u8, args: anytype) jsc.JSValue { if (comptime std.meta.fieldNames(@TypeOf(args)).len == 0) { var message = bun.String.static(fmt_str); return toJS(this, globalThis, &message); @@ -141,7 +141,7 @@ zig += ` return toJS(this, globalThis, &message); } - pub fn throw(this: Error, globalThis: *JSC.JSGlobalObject, comptime fmt_str: [:0]const u8, args: anytype) bun.JSError { + pub fn throw(this: Error, globalThis: *jsc.JSGlobalObject, comptime fmt_str: [:0]const u8, args: anytype) bun.JSError { return globalThis.throwValue(fmt(this, globalThis, fmt_str, args)); } diff --git a/src/codegen/shared-types.ts b/src/codegen/shared-types.ts index efdb213787..0307c9c322 100644 --- a/src/codegen/shared-types.ts +++ b/src/codegen/shared-types.ts @@ -48,11 +48,11 @@ export const sharedTypes: Record = { "JSC::VM": "jsc.VM", "WTF::StringImpl": "bun.WTF._StringImplStruct", "WebCore::DOMURL": "bun.DOMURL", - "ZigString": "bun.JSC.ZigString", - "JSC::JSPromise": "bun.JSC.JSPromise", - "JSC::JSMap": "bun.JSC.JSMap", - "JSC::CustomGetterSetter": "bun.JSC.CustomGetterSetter", - "JSC::SourceProvider": "bun.JSC.SourceProvider", + "ZigString": "bun.jsc.ZigString", + "JSC::JSPromise": "bun.jsc.JSPromise", + "JSC::JSMap": "bun.jsc.JSMap", + "JSC::CustomGetterSetter": "bun.jsc.CustomGetterSetter", + "JSC::SourceProvider": "bun.jsc.SourceProvider", }; export const bannedTypes: Record = { diff --git a/src/collections.zig b/src/collections.zig new file mode 100644 index 0000000000..cb158f068d --- /dev/null +++ b/src/collections.zig @@ -0,0 +1,5 @@ +pub const MultiArrayList = @import("./collections/multi_array_list.zig").MultiArrayList; +pub const BabyList = @import("./collections/baby_list.zig").BabyList; +pub const OffsetList = @import("./collections/baby_list.zig").OffsetList; +pub const bit_set = @import("./collections/bit_set.zig"); +pub const HiveArray = @import("./collections/hive_array.zig").HiveArray; diff --git a/src/baby_list.zig b/src/collections/baby_list.zig similarity index 98% rename from src/baby_list.zig rename to src/collections/baby_list.zig index 20ee1cab05..6166f52fa2 100644 --- a/src/baby_list.zig +++ b/src/collections/baby_list.zig @@ -108,7 +108,7 @@ pub fn BabyList(comptime Type: type) type { fn assertValidDeepClone(comptime T: type) void { if (@hasDecl(T, "deepClone")) return; return switch (T) { - bun.JSAst.Expr, bun.JSAst.G.Property, bun.css.ImportConditions, bun.css.LayerName => {}, + bun.ast.Expr, bun.ast.G.Property, bun.css.ImportConditions, bun.css.LayerName => {}, else => { @compileError("Unsupported type for BabyList.deepClone(): " ++ @typeName(Type)); }, @@ -470,7 +470,8 @@ pub fn OffsetList(comptime Type: type) type { }; } -const Environment = @import("./env.zig"); -const bun = @import("bun"); const std = @import("std"); -const strings = @import("./string_immutable.zig"); + +const bun = @import("bun"); +const Environment = bun.Environment; +const strings = bun.strings; diff --git a/src/bit_set.zig b/src/collections/bit_set.zig similarity index 99% rename from src/bit_set.zig rename to src/collections/bit_set.zig index 282179fca5..a235c868cb 100644 --- a/src/bit_set.zig +++ b/src/collections/bit_set.zig @@ -1,7 +1,7 @@ //! This is a fork of Zig standard library bit_set.zig //! - https://github.com/ziglang/zig/pull/14129 //! - AutoBitset which optimally chooses between a dynamic or static bitset. -//! Prefer our fork over std.bit_set.zig. +//! Prefer our fork over std.bit_set. //! //! This file defines several variants of bit sets. A bit set //! is a densely stored set of integers with a known maximum, diff --git a/src/hive_array.zig b/src/collections/hive_array.zig similarity index 100% rename from src/hive_array.zig rename to src/collections/hive_array.zig diff --git a/src/multi_array_list.zig b/src/collections/multi_array_list.zig similarity index 100% rename from src/multi_array_list.zig rename to src/collections/multi_array_list.zig diff --git a/src/comptime_string_map.zig b/src/comptime_string_map.zig index 3421962ad4..1c07b5bf59 100644 --- a/src/comptime_string_map.zig +++ b/src/comptime_string_map.zig @@ -191,7 +191,7 @@ pub fn ComptimeStringMapWithKeyType(comptime KeyType: type, comptime V: type, co } /// Caller must ensure that the input is a string. - pub fn fromJS(globalThis: *JSC.JSGlobalObject, input: JSC.JSValue) bun.JSError!?V { + pub fn fromJS(globalThis: *jsc.JSGlobalObject, input: jsc.JSValue) bun.JSError!?V { if (comptime bun.Environment.allow_assert) { if (!input.isString()) { @panic("ComptimeStringMap.fromJS: input is not a string"); @@ -205,7 +205,7 @@ pub fn ComptimeStringMapWithKeyType(comptime KeyType: type, comptime V: type, co } /// Caller must ensure that the input is a string. - pub fn fromJSCaseInsensitive(globalThis: *JSC.JSGlobalObject, input: JSC.JSValue) bun.JSError!?V { + pub fn fromJSCaseInsensitive(globalThis: *jsc.JSGlobalObject, input: jsc.JSValue) bun.JSError!?V { if (comptime bun.Environment.allow_assert) { if (!input.isString()) { @panic("ComptimeStringMap.fromJS: input is not a string"); @@ -552,10 +552,9 @@ const TestEnum2 = enum { }); }; -const strings = @import("./string_immutable.zig"); - const bun = @import("bun"); -const JSC = bun.JSC; +const jsc = bun.jsc; +const strings = bun.strings; const std = @import("std"); const mem = std.mem; diff --git a/src/crash_handler.zig b/src/crash_handler.zig index 09f0fbb1d4..45eda9a025 100644 --- a/src/crash_handler.zig +++ b/src/crash_handler.zig @@ -272,7 +272,7 @@ pub fn crashHandler( writer.writeAll(Output.prettyFmt("", true)) catch std.posix.abort(); } - if (bun.CLI.Cli.is_main_thread) { + if (bun.cli.Cli.is_main_thread) { writer.writeAll("(main thread)") catch std.posix.abort(); } else switch (bun.Environment.os) { .windows => { @@ -906,18 +906,18 @@ pub fn printMetadata(writer: anytype) !void { try writer.writeAll(metadata_version_line); { - const platform = bun.Analytics.GenerateHeader.GeneratePlatform.forOS(); + const platform = bun.analytics.GenerateHeader.GeneratePlatform.forOS(); const cpu_features = CPUFeatures.get(); if (bun.Environment.isLinux and !bun.Environment.isMusl) { const version = gnu_get_libc_version() orelse ""; - const kernel_version = bun.Analytics.GenerateHeader.GeneratePlatform.kernelVersion(); + const kernel_version = bun.analytics.GenerateHeader.GeneratePlatform.kernelVersion(); if (platform.os == .wsl) { try writer.print("WSL Kernel v{d}.{d}.{d} | glibc v{s}\n", .{ kernel_version.major, kernel_version.minor, kernel_version.patch, bun.sliceTo(version, 0) }); } else { try writer.print("Linux Kernel v{d}.{d}.{d} | glibc v{s}\n", .{ kernel_version.major, kernel_version.minor, kernel_version.patch, bun.sliceTo(version, 0) }); } } else if (bun.Environment.isLinux and bun.Environment.isMusl) { - const kernel_version = bun.Analytics.GenerateHeader.GeneratePlatform.kernelVersion(); + const kernel_version = bun.analytics.GenerateHeader.GeneratePlatform.kernelVersion(); try writer.print("Linux Kernel v{d}.{d}.{d} | musl\n", .{ kernel_version.major, kernel_version.minor, kernel_version.patch }); } else if (bun.Environment.isMac) { try writer.print("macOS v{s}\n", .{platform.version}); @@ -945,7 +945,7 @@ pub fn printMetadata(writer: anytype) !void { } } } - try writer.print("\n{}", .{bun.Analytics.Features.formatter()}); + try writer.print("\n{}", .{bun.analytics.Features.formatter()}); if (bun.use_mimalloc) { var elapsed_msecs: usize = 0; @@ -1261,7 +1261,7 @@ fn encodeTraceString(opts: TraceString, writer: anytype) !void { "/" ++ .{@intFromEnum(Platform.current)}, ); - try writer.writeByte(if (bun.CLI.Cli.cmd) |cmd| cmd.char() else '_'); + try writer.writeByte(if (bun.cli.Cli.cmd) |cmd| cmd.char() else '_'); try writer.writeAll(version_char ++ git_sha); @@ -1753,11 +1753,11 @@ pub const StoredTrace = struct { }; pub const js_bindings = struct { - const JSC = bun.JSC; - const JSValue = JSC.JSValue; + const jsc = bun.jsc; + const JSValue = jsc.JSValue; - pub fn generate(global: *JSC.JSGlobalObject) JSC.JSValue { - const obj = JSC.JSValue.createEmptyObject(global, 3); + pub fn generate(global: *jsc.JSGlobalObject) jsc.JSValue { + const obj = jsc.JSValue.createEmptyObject(global, 3); inline for (.{ .{ "getMachOImageZeroOffset", jsGetMachOImageZeroOffset }, .{ "getFeaturesAsVLQ", jsGetFeaturesAsVLQ }, @@ -1769,13 +1769,13 @@ pub const js_bindings = struct { .{ "outOfMemory", jsOutOfMemory }, .{ "raiseIgnoringPanicHandler", jsRaiseIgnoringPanicHandler }, }) |tuple| { - const name = JSC.ZigString.static(tuple[0]); - obj.put(global, name, JSC.createCallback(global, name, 1, tuple[1])); + const name = jsc.ZigString.static(tuple[0]); + obj.put(global, name, jsc.createCallback(global, name, 1, tuple[1])); } return obj; } - pub fn jsGetMachOImageZeroOffset(_: *bun.JSC.JSGlobalObject, _: *bun.JSC.CallFrame) bun.JSError!JSValue { + pub fn jsGetMachOImageZeroOffset(_: *bun.jsc.JSGlobalObject, _: *bun.jsc.CallFrame) bun.JSError!JSValue { if (!bun.Environment.isMac) return .js_undefined; const header = std.c._dyld_get_image_header(0) orelse return .js_undefined; @@ -1785,7 +1785,7 @@ pub const js_bindings = struct { return JSValue.jsNumber(base_address - vmaddr_slide); } - pub fn jsSegfault(_: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!JSC.JSValue { + pub fn jsSegfault(_: *jsc.JSGlobalObject, _: *jsc.CallFrame) bun.JSError!jsc.JSValue { @setRuntimeSafety(false); const ptr: [*]align(1) u64 = @ptrFromInt(0xDEADBEEF); ptr[0] = 0xDEADBEEF; @@ -1793,24 +1793,24 @@ pub const js_bindings = struct { return .js_undefined; } - pub fn jsPanic(_: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!JSC.JSValue { + pub fn jsPanic(_: *jsc.JSGlobalObject, _: *jsc.CallFrame) bun.JSError!jsc.JSValue { bun.crash_handler.panicImpl("invoked crashByPanic() handler", null, null); } - pub fn jsRootError(_: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!JSC.JSValue { + pub fn jsRootError(_: *jsc.JSGlobalObject, _: *jsc.CallFrame) bun.JSError!jsc.JSValue { bun.crash_handler.handleRootError(error.Test, null); } - pub fn jsOutOfMemory(_: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!JSC.JSValue { + pub fn jsOutOfMemory(_: *jsc.JSGlobalObject, _: *jsc.CallFrame) bun.JSError!jsc.JSValue { bun.outOfMemory(); } - pub fn jsRaiseIgnoringPanicHandler(_: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!JSC.JSValue { + pub fn jsRaiseIgnoringPanicHandler(_: *jsc.JSGlobalObject, _: *jsc.CallFrame) bun.JSError!jsc.JSValue { bun.Global.raiseIgnoringPanicHandler(.SIGSEGV); } - pub fn jsGetFeaturesAsVLQ(global: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!JSC.JSValue { - const bits = bun.Analytics.packedFeatures(); + pub fn jsGetFeaturesAsVLQ(global: *jsc.JSGlobalObject, _: *jsc.CallFrame) bun.JSError!jsc.JSValue { + const bits = bun.analytics.packedFeatures(); var buf = std.BoundedArray(u8, 16){}; writeU64AsTwoVLQs(buf.writer(), @bitCast(bits)) catch { // there is definitely enough space in the bounded array @@ -1820,22 +1820,22 @@ pub const js_bindings = struct { return str.transferToJS(global); } - pub fn jsGetFeatureData(global: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!JSC.JSValue { + pub fn jsGetFeatureData(global: *jsc.JSGlobalObject, _: *jsc.CallFrame) bun.JSError!jsc.JSValue { const obj = JSValue.createEmptyObject(global, 5); - const list = bun.Analytics.packed_features_list; + const list = bun.analytics.packed_features_list; const array = try JSValue.createEmptyArray(global, list.len); for (list, 0..) |feature, i| { try array.putIndex(global, @intCast(i), bun.String.static(feature).toJS(global)); } - obj.put(global, JSC.ZigString.static("features"), array); - obj.put(global, JSC.ZigString.static("version"), bun.String.init(Global.package_json_version).toJS(global)); - obj.put(global, JSC.ZigString.static("is_canary"), JSC.JSValue.jsBoolean(bun.Environment.is_canary)); + obj.put(global, jsc.ZigString.static("features"), array); + obj.put(global, jsc.ZigString.static("version"), bun.String.init(Global.package_json_version).toJS(global)); + obj.put(global, jsc.ZigString.static("is_canary"), jsc.JSValue.jsBoolean(bun.Environment.is_canary)); // This is the source of truth for the git sha. // Not the github ref or the git tag. - obj.put(global, JSC.ZigString.static("revision"), bun.String.init(bun.Environment.git_sha).toJS(global)); + obj.put(global, jsc.ZigString.static("revision"), bun.String.init(bun.Environment.git_sha).toJS(global)); - obj.put(global, JSC.ZigString.static("generated_at"), JSValue.jsNumberFromInt64(@max(std.time.milliTimestamp(), 0))); + obj.put(global, jsc.ZigString.static("generated_at"), JSValue.jsNumberFromInt64(@max(std.time.milliTimestamp(), 0))); return obj; } }; @@ -2195,7 +2195,6 @@ comptime { const CPUFeatures = @import("./bun.js/bindings/CPUFeatures.zig"); const builtin = @import("builtin"); -const mimalloc = @import("./allocators/mimalloc.zig"); const std = @import("std"); const windows = std.os.windows; @@ -2205,7 +2204,8 @@ const VLQ = SourceMap.VLQ; const bun = @import("bun"); const Global = bun.Global; const Output = bun.Output; -const Features = bun.Analytics.Features; +const mimalloc = bun.mimalloc; +const Features = bun.analytics.Features; const debug = std.debug; const SourceLocation = debug.SourceLocation; diff --git a/src/create/SourceFileProjectGenerator.zig b/src/create/SourceFileProjectGenerator.zig index 89418d8fe9..dfcca654b3 100644 --- a/src/create/SourceFileProjectGenerator.zig +++ b/src/create/SourceFileProjectGenerator.zig @@ -79,7 +79,7 @@ pub fn generate(_: Command.Context, _: Example.Tag, entry_point: string, result: } // Create a file with given contents, returns if file was newly created -fn createFile(filename: []const u8, contents: []const u8) bun.JSC.Maybe(bool) { +fn createFile(filename: []const u8, contents: []const u8) bun.jsc.Maybe(bool) { // Check if file exists and has same contents if (bun.sys.File.readFrom(bun.FD.cwd(), filename, default_allocator).asValue()) |source_contents| { defer default_allocator.free(source_contents); @@ -248,7 +248,7 @@ pub fn generateFiles(allocator: std.mem.Allocator, entry_point: string, dependen .stdin = .inherit, .windows = if (Environment.isWindows) .{ - .loop = bun.JSC.EventLoopHandle.init(bun.JSC.MiniEventLoop.initGlobal(null)), + .loop = bun.jsc.EventLoopHandle.init(bun.jsc.MiniEventLoop.initGlobal(null)), }, }) catch |err| { Output.err(err, "failed to install dependencies", .{}); @@ -361,7 +361,7 @@ pub fn generateFiles(allocator: std.mem.Allocator, entry_point: string, dependen .stdin = .inherit, .windows = if (Environment.isWindows) .{ - .loop = bun.JSC.EventLoopHandle.init(bun.JSC.MiniEventLoop.initGlobal(null)), + .loop = bun.jsc.EventLoopHandle.init(bun.jsc.MiniEventLoop.initGlobal(null)), }, }) catch |err| { Output.err(err, "failed to start app", .{}); @@ -849,6 +849,8 @@ pub const Template = union(Tag) { }; }; +const string = []const u8; + const linker = @import("../linker.zig"); const std = @import("std"); const Example = @import("../cli/create_command.zig").Example; @@ -859,9 +861,8 @@ const Global = bun.Global; const MutableString = bun.MutableString; const Output = bun.Output; const default_allocator = bun.default_allocator; -const js_ast = bun.JSAst; +const js_ast = bun.ast; const logger = bun.logger; -const string = bun.string; const strings = bun.strings; const BundleV2 = bun.bundle_v2.BundleV2; -const Command = bun.CLI.Command; +const Command = bun.cli.Command; diff --git a/src/csrf.zig b/src/csrf.zig index 58f8e11fb7..d78756a83f 100644 --- a/src/csrf.zig +++ b/src/csrf.zig @@ -7,7 +7,7 @@ pub const CSRF = @This(); pub const DEFAULT_EXPIRATION_MS: u64 = 24 * 60 * 60 * 1000; /// Default HMAC algorithm used for token signing -pub const DEFAULT_ALGORITHM: JSC.API.Bun.Crypto.EVP.Algorithm = .sha256; +pub const DEFAULT_ALGORITHM: jsc.API.Bun.Crypto.EVP.Algorithm = .sha256; /// Error types for CSRF operations pub const Error = error{ @@ -26,7 +26,7 @@ pub const GenerateOptions = struct { /// Format to encode the token in encoding: TokenFormat = .base64url, /// Algorithm to use for signing - algorithm: JSC.API.Bun.Crypto.EVP.Algorithm = DEFAULT_ALGORITHM, + algorithm: jsc.API.Bun.Crypto.EVP.Algorithm = DEFAULT_ALGORITHM, }; /// Options for validating CSRF tokens @@ -40,7 +40,7 @@ pub const VerifyOptions = struct { /// Encoding to use for the token encoding: TokenFormat = .base64url, /// Algorithm to use for signing - algorithm: JSC.API.Bun.Crypto.EVP.Algorithm = DEFAULT_ALGORITHM, + algorithm: jsc.API.Bun.Crypto.EVP.Algorithm = DEFAULT_ALGORITHM, }; /// Token encoding format @@ -49,7 +49,7 @@ pub const TokenFormat = enum { base64url, hex, - pub fn toNodeEncoding(self: TokenFormat) JSC.Node.Encoding { + pub fn toNodeEncoding(self: TokenFormat) jsc.Node.Encoding { return switch (self) { .base64 => .base64, .base64url => .base64url, @@ -62,7 +62,7 @@ pub const TokenFormat = enum { /// /// Parameters: /// - options: Configuration for token generation -/// - vm: The JSC virtual machine context +/// - vm: The jsc virtual machine context /// /// Returns: A string.Slice containing the encoded token pub fn generate( @@ -210,13 +210,13 @@ pub fn verify(options: VerifyOptions) bool { /// JS binding function for generating CSRF tokens /// First argument is secret (required), second is options (optional) -pub fn csrf__generate_impl(globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { - if (bun.Analytics.Features.csrf_generate < std.math.maxInt(usize)) - bun.Analytics.Features.csrf_generate += 1; +pub fn csrf__generate_impl(globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { + if (bun.analytics.Features.csrf_generate < std.math.maxInt(usize)) + bun.analytics.Features.csrf_generate += 1; // We should have at least one argument (secret) const args = callframe.arguments(); - var secret: ?JSC.ZigString.Slice = null; + var secret: ?jsc.ZigString.Slice = null; if (args.len >= 1) { const jsSecret = args[0]; // Extract the secret (required) @@ -233,7 +233,7 @@ pub fn csrf__generate_impl(globalObject: *JSC.JSGlobalObject, callframe: *JSC.Ca // Default values var expires_in: u64 = DEFAULT_EXPIRATION_MS; var encoding: TokenFormat = .base64url; - var algorithm: JSC.API.Bun.Crypto.EVP.Algorithm = DEFAULT_ALGORITHM; + var algorithm: jsc.API.Bun.Crypto.EVP.Algorithm = DEFAULT_ALGORITHM; // Check if we have options object if (args.len > 1 and args[1].isObject()) { @@ -246,7 +246,7 @@ pub fn csrf__generate_impl(globalObject: *JSC.JSGlobalObject, callframe: *JSC.Ca // Extract encoding (optional) if (try options_value.get(globalObject, "encoding")) |encoding_js| { - const encoding_enum = try JSC.Node.Encoding.fromJSWithDefaultOnEmpty(encoding_js, globalObject, .base64url) orelse { + const encoding_enum = try jsc.Node.Encoding.fromJSWithDefaultOnEmpty(encoding_js, globalObject, .base64url) orelse { return globalObject.throwInvalidArguments("Invalid format: must be 'base64', 'base64url', or 'hex'", .{}); }; encoding = switch (encoding_enum) { @@ -261,7 +261,7 @@ pub fn csrf__generate_impl(globalObject: *JSC.JSGlobalObject, callframe: *JSC.Ca if (!algorithm_js.isString()) { return globalObject.throwInvalidArgumentTypeValue("algorithm", "string", algorithm_js); } - algorithm = try JSC.API.Bun.Crypto.EVP.Algorithm.map.fromJSCaseInsensitive(globalObject, algorithm_js) orelse { + algorithm = try jsc.API.Bun.Crypto.EVP.Algorithm.map.fromJSCaseInsensitive(globalObject, algorithm_js) orelse { return globalObject.throwInvalidArguments("Algorithm not supported", .{}); }; switch (algorithm) { @@ -291,20 +291,20 @@ pub fn csrf__generate_impl(globalObject: *JSC.JSGlobalObject, callframe: *JSC.Ca return encoding.toNodeEncoding().encodeWithMaxSize(globalObject, boring.EVP_MAX_MD_SIZE + 32, token_bytes); } -pub const csrf__generate = JSC.toJSHostFn(csrf__generate_impl); +pub const csrf__generate = jsc.toJSHostFn(csrf__generate_impl); /// JS binding function for verifying CSRF tokens /// First argument is token (required), second is options (optional) -pub fn csrf__verify_impl(globalObject: *JSC.JSGlobalObject, call_frame: *JSC.CallFrame) bun.JSError!JSC.JSValue { - if (bun.Analytics.Features.csrf_verify < std.math.maxInt(usize)) { - bun.Analytics.Features.csrf_verify += 1; +pub fn csrf__verify_impl(globalObject: *jsc.JSGlobalObject, call_frame: *jsc.CallFrame) bun.JSError!jsc.JSValue { + if (bun.analytics.Features.csrf_verify < std.math.maxInt(usize)) { + bun.analytics.Features.csrf_verify += 1; } // We should have at least one argument (token) const args = call_frame.arguments(); if (args.len < 1) { return globalObject.throwInvalidArguments("Missing required token parameter", .{}); } - const jsToken: JSC.JSValue = args[0]; + const jsToken: jsc.JSValue = args[0]; // Extract the token (required) if (jsToken.isUndefinedOrNull()) { return globalObject.throwInvalidArguments("Token is required", .{}); @@ -316,19 +316,19 @@ pub fn csrf__verify_impl(globalObject: *JSC.JSGlobalObject, call_frame: *JSC.Cal defer token.deinit(); // Default values - var secret: ?JSC.ZigString.Slice = null; + var secret: ?jsc.ZigString.Slice = null; defer if (secret) |s| s.deinit(); var max_age: u64 = DEFAULT_EXPIRATION_MS; var encoding: TokenFormat = .base64url; - var algorithm: JSC.API.Bun.Crypto.EVP.Algorithm = DEFAULT_ALGORITHM; + var algorithm: jsc.API.Bun.Crypto.EVP.Algorithm = DEFAULT_ALGORITHM; // Check if we have options object if (args.len > 1 and args[1].isObject()) { const options_value = args[1]; // Extract the secret (required) - if (try options_value.getOptional(globalObject, "secret", JSC.ZigString.Slice)) |secretSlice| { + if (try options_value.getOptional(globalObject, "secret", jsc.ZigString.Slice)) |secretSlice| { if (secretSlice.len == 0) { return globalObject.throwInvalidArguments("Secret must be a non-empty string", .{}); } @@ -342,7 +342,7 @@ pub fn csrf__verify_impl(globalObject: *JSC.JSGlobalObject, call_frame: *JSC.Cal // Extract encoding (optional) if (try options_value.get(globalObject, "encoding")) |encoding_js| { - const encoding_enum = try JSC.Node.Encoding.fromJSWithDefaultOnEmpty(encoding_js, globalObject, .base64url) orelse { + const encoding_enum = try jsc.Node.Encoding.fromJSWithDefaultOnEmpty(encoding_js, globalObject, .base64url) orelse { return globalObject.throwInvalidArguments("Invalid format: must be 'base64', 'base64url', or 'hex'", .{}); }; encoding = switch (encoding_enum) { @@ -356,7 +356,7 @@ pub fn csrf__verify_impl(globalObject: *JSC.JSGlobalObject, call_frame: *JSC.Cal if (!algorithm_js.isString()) { return globalObject.throwInvalidArgumentTypeValue("algorithm", "string", algorithm_js); } - algorithm = try JSC.API.Bun.Crypto.EVP.Algorithm.map.fromJSCaseInsensitive(globalObject, algorithm_js) orelse { + algorithm = try jsc.API.Bun.Crypto.EVP.Algorithm.map.fromJSCaseInsensitive(globalObject, algorithm_js) orelse { return globalObject.throwInvalidArguments("Algorithm not supported", .{}); }; switch (algorithm) { @@ -374,15 +374,15 @@ pub fn csrf__verify_impl(globalObject: *JSC.JSGlobalObject, call_frame: *JSC.Cal .algorithm = algorithm, }); - return JSC.JSValue.jsBoolean(is_valid); + return jsc.JSValue.jsBoolean(is_valid); } -pub const csrf__verify = JSC.toJSHostFn(csrf__verify_impl); +pub const csrf__verify = jsc.toJSHostFn(csrf__verify_impl); const hmac = @import("./hmac.zig"); const std = @import("std"); const string = @import("./string.zig"); const bun = @import("bun"); -const JSC = bun.JSC; +const jsc = bun.jsc; const boring = bun.BoringSSL.c; diff --git a/src/css/css_internals.zig b/src/css/css_internals.zig index c2d663d3d8..169f86ff19 100644 --- a/src/css/css_internals.zig +++ b/src/css/css_internals.zig @@ -11,42 +11,42 @@ const TestCategory = enum { parser_options, }; -pub fn minifyErrorTestWithOptions(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { +pub fn minifyErrorTestWithOptions(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { return testingImpl(globalThis, callframe, .minify, .parser_options); } -pub fn minifyTestWithOptions(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { +pub fn minifyTestWithOptions(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { return testingImpl(globalThis, callframe, .minify, .parser_options); } -pub fn prefixTestWithOptions(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { +pub fn prefixTestWithOptions(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { return testingImpl(globalThis, callframe, .prefix, .parser_options); } -pub fn testWithOptions(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { +pub fn testWithOptions(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { return testingImpl(globalThis, callframe, .normal, .parser_options); } -pub fn minifyTest(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { +pub fn minifyTest(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { return testingImpl(globalThis, callframe, .minify, .normal); } -pub fn prefixTest(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { +pub fn prefixTest(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { return testingImpl(globalThis, callframe, .prefix, .normal); } -pub fn _test(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { +pub fn _test(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { return testingImpl(globalThis, callframe, .normal, .normal); } -pub fn testingImpl(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame, comptime test_kind: TestKind, comptime test_category: TestCategory) bun.JSError!JSC.JSValue { +pub fn testingImpl(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame, comptime test_kind: TestKind, comptime test_category: TestCategory) bun.JSError!jsc.JSValue { var arena = bun.ArenaAllocator.init(bun.default_allocator); defer arena.deinit(); const alloc = arena.allocator(); const arguments_ = callframe.arguments_old(3); - var arguments = JSC.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), arguments_.slice()); - const source_arg: JSC.JSValue = arguments.nextEat() orelse { + var arguments = jsc.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), arguments_.slice()); + const source_arg: jsc.JSValue = arguments.nextEat() orelse { return globalThis.throw("minifyTestWithOptions: expected 2 arguments, got 0", .{}); }; if (!source_arg.isString()) { @@ -112,7 +112,7 @@ pub fn testingImpl(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame, c minify_options.targets.browsers = browsers; _ = stylesheet.minify(alloc, minify_options, &extra).assert(); - const symbols = bun.JSAst.Symbol.Map{}; + const symbols = bun.ast.Symbol.Map{}; var local_names = bun.css.LocalsResultsMap{}; const result = switch (stylesheet.toCss( alloc, @@ -147,7 +147,7 @@ pub fn testingImpl(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame, c } } -fn parserOptionsFromJS(globalThis: *JSC.JSGlobalObject, allocator: Allocator, opts: *bun.css.ParserOptions, jsobj: JSValue) bun.JSError!void { +fn parserOptionsFromJS(globalThis: *jsc.JSGlobalObject, allocator: Allocator, opts: *bun.css.ParserOptions, jsobj: JSValue) bun.JSError!void { _ = allocator; // autofix if (try jsobj.getTruthy(globalThis, "flags")) |val| { if (val.isArray()) { @@ -180,7 +180,7 @@ fn parserOptionsFromJS(globalThis: *JSC.JSGlobalObject, allocator: Allocator, op // } } -fn targetsFromJS(globalThis: *JSC.JSGlobalObject, jsobj: JSValue) bun.JSError!bun.css.targets.Browsers { +fn targetsFromJS(globalThis: *jsc.JSGlobalObject, jsobj: JSValue) bun.JSError!bun.css.targets.Browsers { var targets = bun.css.targets.Browsers{}; if (try jsobj.getTruthy(globalThis, "android")) |val| { @@ -250,14 +250,14 @@ fn targetsFromJS(globalThis: *JSC.JSGlobalObject, jsobj: JSValue) bun.JSError!bu return targets; } -pub fn attrTest(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { +pub fn attrTest(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { var arena = bun.ArenaAllocator.init(bun.default_allocator); defer arena.deinit(); const alloc = arena.allocator(); const arguments_ = callframe.arguments_old(4); - var arguments = JSC.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), arguments_.slice()); - const source_arg: JSC.JSValue = arguments.nextEat() orelse { + var arguments = jsc.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), arguments_.slice()); + const source_arg: jsc.JSValue = arguments.nextEat() orelse { return globalThis.throw("attrTest: expected 3 arguments, got 0", .{}); }; if (!source_arg.isString()) { @@ -279,7 +279,7 @@ pub fn attrTest(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun. const expected = expected_bunstr.toUTF8(bun.default_allocator); defer expected.deinit(); - const minify_arg: JSC.JSValue = arguments.nextEat() orelse { + const minify_arg: jsc.JSValue = arguments.nextEat() orelse { return globalThis.throw("attrTest: expected 3 arguments, got 2", .{}); }; const minify = minify_arg.isBoolean() and minify_arg.toBoolean(); @@ -331,6 +331,6 @@ const bun = @import("bun"); const std = @import("std"); const Allocator = std.mem.Allocator; -const JSC = bun.JSC; -const JSGlobalObject = bun.JSC.JSGlobalObject; -const JSValue = bun.JSC.JSValue; +const jsc = bun.jsc; +const JSGlobalObject = bun.jsc.JSGlobalObject; +const JSValue = bun.jsc.JSValue; diff --git a/src/css/css_parser.zig b/src/css/css_parser.zig index 2e1c28ca65..f2f539b481 100644 --- a/src/css/css_parser.zig +++ b/src/css/css_parser.zig @@ -1,6 +1,6 @@ pub const SrcIndex = bun.bundle_v2.Index; -pub const SymbolList = bun.JSAst.Symbol.List; +pub const SymbolList = bun.ast.Symbol.List; pub const ImportRecord = bun.ImportRecord; pub const ImportKind = bun.ImportKind; @@ -89,7 +89,7 @@ pub const ImportInfo = css_printer.ImportInfo; pub const PropertyHandlerContext = context.PropertyHandlerContext; pub const DeclarationHandler = declaration.DeclarationHandler; -pub const Maybe = bun.JSC.Node.Maybe; +pub const Maybe = bun.jsc.Node.Maybe; // TODO: Remove existing Error defined here and replace it with these pub const Err = errors_.Err; pub const PrinterErrorKind = errors_.PrinterErrorKind; @@ -285,7 +285,7 @@ pub fn PrintResult(comptime T: type) type { } pub fn todo(comptime fmt: []const u8, args: anytype) noreturn { - bun.Analytics.Features.todo_panic = 1; + bun.analytics.Features.todo_panic = 1; std.debug.panic("TODO: " ++ fmt, args); } @@ -3134,7 +3134,7 @@ pub fn StyleSheet(comptime AtRule: type) type { options: css_printer.PrinterOptions, import_info: ?bun.css.ImportInfo, local_names: ?*const LocalsResultsMap, - symbols: *const bun.JSAst.Symbol.Map, + symbols: *const bun.ast.Symbol.Map, ) PrintResult(ToCssResultInternal) { const W = @TypeOf(writer); @@ -3204,7 +3204,7 @@ pub fn StyleSheet(comptime AtRule: type) type { options: css_printer.PrinterOptions, import_info: ?bun.css.ImportInfo, local_names: ?*const LocalsResultsMap, - symbols: *const bun.JSAst.Symbol.Map, + symbols: *const bun.ast.Symbol.Map, ) PrintResult(ToCssResult) { // TODO: this is not necessary // Make sure we always have capacity > 0: https://github.com/napi-rs/napi-rs/issues/1124. @@ -3489,7 +3489,7 @@ pub const StyleAttribute = struct { // "Source maps are not supported for style attributes" // ); - var symbols = bun.JSAst.Symbol.Map{}; + var symbols = bun.ast.Symbol.Map{}; var dest = ArrayList(u8){}; const writer = dest.writer(allocator); var printer = Printer(@TypeOf(writer)).new( @@ -3835,7 +3835,7 @@ pub const Parser = struct { }, .loc = loc, }; - extra.symbols.push(this.allocator(), bun.JSAst.Symbol{ + extra.symbols.push(this.allocator(), bun.ast.Symbol{ .kind = .local_css, .original_name = name, }) catch bun.outOfMemory(); @@ -7005,7 +7005,7 @@ pub const to_css = struct { options: PrinterOptions, import_info: ?ImportInfo, local_names: ?*const LocalsResultsMap, - symbols: *const bun.JSAst.Symbol.Map, + symbols: *const bun.ast.Symbol.Map, ) PrintErr![]const u8 { var s = ArrayList(u8){}; errdefer s.deinit(allocator); diff --git a/src/css/declaration.zig b/src/css/declaration.zig index 446a7d799c..27807fe6ed 100644 --- a/src/css/declaration.zig +++ b/src/css/declaration.zig @@ -48,7 +48,7 @@ pub const DeclarationBlock = struct { var arraylist = ArrayList(u8){}; const w = arraylist.writer(bun.default_allocator); defer arraylist.deinit(bun.default_allocator); - var symbols = bun.JSAst.Symbol.Map{}; + var symbols = bun.ast.Symbol.Map{}; var printer = css.Printer(@TypeOf(w)).new(bun.default_allocator, std.ArrayList(u8).init(bun.default_allocator), w, css.PrinterOptions.default(), null, null, &symbols); defer printer.deinit(); this.self.toCss(@TypeOf(w), &printer) catch |e| return try writer.print("\n", .{@errorName(e)}); diff --git a/src/css/dependencies.zig b/src/css/dependencies.zig index 648418d9fb..f0ea582111 100644 --- a/src/css/dependencies.zig +++ b/src/css/dependencies.zig @@ -54,7 +54,7 @@ pub const ImportDependency = struct { /// The location of the dependency in the source file. loc: SourceRange, - pub fn new(allocator: Allocator, rule: *const css.css_rules.import.ImportRule, filename: []const u8, local_names: ?*const css.LocalsResultsMap, symbols: *const bun.JSAst.Symbol.Map) ImportDependency { + pub fn new(allocator: Allocator, rule: *const css.css_rules.import.ImportRule, filename: []const u8, local_names: ?*const css.LocalsResultsMap, symbols: *const bun.ast.Symbol.Map) ImportDependency { const supports = if (rule.supports) |*supports| brk: { const s = css.to_css.string( allocator, diff --git a/src/css/error.zig b/src/css/error.zig index cc9fed55e6..1b7a806783 100644 --- a/src/css/error.zig +++ b/src/css/error.zig @@ -34,7 +34,7 @@ pub fn Err(comptime T: type) type { @compileError("fmt not implemented for " ++ @typeName(T)); } - pub fn toJSString(this: @This(), allocator: Allocator, globalThis: *bun.JSC.JSGlobalObject) bun.JSC.JSValue { + pub fn toJSString(this: @This(), allocator: Allocator, globalThis: *bun.jsc.JSGlobalObject) bun.jsc.JSValue { var error_string = ArrayList(u8){}; defer error_string.deinit(allocator); error_string.writer(allocator).print("{}", .{this.kind}) catch unreachable; diff --git a/src/css/printer.zig b/src/css/printer.zig index 60a1035438..88270143f3 100644 --- a/src/css/printer.zig +++ b/src/css/printer.zig @@ -123,7 +123,7 @@ pub fn Printer(comptime Writer: type) type { error_kind: ?css.PrinterError = null, import_info: ?ImportInfo = null, public_path: []const u8, - symbols: *const bun.JSAst.Symbol.Map, + symbols: *const bun.ast.Symbol.Map, local_names: ?*const css.LocalsResultsMap = null, /// NOTE This should be the same mimalloc heap arena allocator allocator: Allocator, @@ -241,7 +241,7 @@ pub fn Printer(comptime Writer: type) type { options: PrinterOptions, import_info: ?ImportInfo, local_names: ?*const css.LocalsResultsMap, - symbols: *const bun.JSAst.Symbol.Map, + symbols: *const bun.ast.Symbol.Map, ) This { return .{ .sources = null, diff --git a/src/css/selectors/parser.zig b/src/css/selectors/parser.zig index 602fb35970..f5b5527b41 100644 --- a/src/css/selectors/parser.zig +++ b/src/css/selectors/parser.zig @@ -1631,7 +1631,7 @@ pub fn GenericSelector(comptime Impl: type) type { var arraylist = ArrayList(u8){}; const w = arraylist.writer(bun.default_allocator); defer arraylist.deinit(bun.default_allocator); - const symbols = bun.JSAst.Symbol.Map{}; + const symbols = bun.ast.Symbol.Map{}; const P = css.Printer(@TypeOf(w)); var printer = P.new(bun.default_allocator, std.ArrayList(u8).init(bun.default_allocator), w, css.PrinterOptions.default(), null, null, &symbols); defer printer.deinit(); diff --git a/src/css/values/color_js.zig b/src/css/values/color_js.zig index 18cd1342cf..ff6b7ec16a 100644 --- a/src/css/values/color_js.zig +++ b/src/css/values/color_js.zig @@ -44,7 +44,7 @@ const OutputColorFormat = enum { }); }; -fn colorIntFromJS(globalThis: *JSC.JSGlobalObject, input: JSC.JSValue, comptime property: []const u8) bun.JSError!i32 { +fn colorIntFromJS(globalThis: *jsc.JSGlobalObject, input: jsc.JSValue, comptime property: []const u8) bun.JSError!i32 { if (input == .zero or input.isUndefined() or !input.isNumber()) { return globalThis.throwInvalidArgumentType("color", property, "integer"); } @@ -131,7 +131,7 @@ pub const Ansi256 = struct { } }; -pub fn jsFunctionColor(globalThis: *JSC.JSGlobalObject, callFrame: *JSC.CallFrame) bun.JSError!JSC.JSValue { +pub fn jsFunctionColor(globalThis: *jsc.JSGlobalObject, callFrame: *jsc.CallFrame) bun.JSError!jsc.JSValue { const args = callFrame.argumentsAsArray(2); if (args[0].isUndefined()) { return globalThis.throwInvalidArgumentType("color", "input", "string, number, or object"); @@ -156,7 +156,7 @@ pub fn jsFunctionColor(globalThis: *JSC.JSGlobalObject, callFrame: *JSC.CallFram break :brk OutputColorFormat.css; }; - var input = JSC.ZigString.Slice.empty; + var input = jsc.ZigString.Slice.empty; defer input.deinit(); var parsed_color: css.CssColor.ParseResult = brk: { @@ -236,7 +236,7 @@ pub fn jsFunctionColor(globalThis: *JSC.JSGlobalObject, callFrame: *JSC.CallFram .result => |*result| { const format: OutputColorFormat = if (unresolved_format == .ansi) switch (bun.Output.Source.colorDepth()) { // No color terminal, therefore return an empty string - .none => return JSC.JSValue.jsEmptyString(globalThis), + .none => return jsc.JSValue.jsEmptyString(globalThis), .@"16" => .ansi_16, .@"16m" => .ansi_16m, .@"256" => .ansi_256, @@ -278,33 +278,33 @@ pub fn jsFunctionColor(globalThis: *JSC.JSGlobalObject, callFrame: *JSC.CallFram const rgba = srgba.into(.RGBA); switch (tag) { .@"{rgba}" => { - const object = JSC.JSValue.createEmptyObject(globalThis, 4); - object.put(globalThis, "r", JSC.JSValue.jsNumber(rgba.red)); - object.put(globalThis, "g", JSC.JSValue.jsNumber(rgba.green)); - object.put(globalThis, "b", JSC.JSValue.jsNumber(rgba.blue)); - object.put(globalThis, "a", JSC.JSValue.jsNumber(rgba.alphaF32())); + const object = jsc.JSValue.createEmptyObject(globalThis, 4); + object.put(globalThis, "r", jsc.JSValue.jsNumber(rgba.red)); + object.put(globalThis, "g", jsc.JSValue.jsNumber(rgba.green)); + object.put(globalThis, "b", jsc.JSValue.jsNumber(rgba.blue)); + object.put(globalThis, "a", jsc.JSValue.jsNumber(rgba.alphaF32())); return object; }, .@"{rgb}" => { - const object = JSC.JSValue.createEmptyObject(globalThis, 4); - object.put(globalThis, "r", JSC.JSValue.jsNumber(rgba.red)); - object.put(globalThis, "g", JSC.JSValue.jsNumber(rgba.green)); - object.put(globalThis, "b", JSC.JSValue.jsNumber(rgba.blue)); + const object = jsc.JSValue.createEmptyObject(globalThis, 4); + object.put(globalThis, "r", jsc.JSValue.jsNumber(rgba.red)); + object.put(globalThis, "g", jsc.JSValue.jsNumber(rgba.green)); + object.put(globalThis, "b", jsc.JSValue.jsNumber(rgba.blue)); return object; }, .@"[rgb]" => { - const object = try JSC.JSValue.createEmptyArray(globalThis, 3); - try object.putIndex(globalThis, 0, JSC.JSValue.jsNumber(rgba.red)); - try object.putIndex(globalThis, 1, JSC.JSValue.jsNumber(rgba.green)); - try object.putIndex(globalThis, 2, JSC.JSValue.jsNumber(rgba.blue)); + const object = try jsc.JSValue.createEmptyArray(globalThis, 3); + try object.putIndex(globalThis, 0, jsc.JSValue.jsNumber(rgba.red)); + try object.putIndex(globalThis, 1, jsc.JSValue.jsNumber(rgba.green)); + try object.putIndex(globalThis, 2, jsc.JSValue.jsNumber(rgba.blue)); return object; }, .@"[rgba]" => { - const object = try JSC.JSValue.createEmptyArray(globalThis, 4); - try object.putIndex(globalThis, 0, JSC.JSValue.jsNumber(rgba.red)); - try object.putIndex(globalThis, 1, JSC.JSValue.jsNumber(rgba.green)); - try object.putIndex(globalThis, 2, JSC.JSValue.jsNumber(rgba.blue)); - try object.putIndex(globalThis, 3, JSC.JSValue.jsNumber(rgba.alpha)); + const object = try jsc.JSValue.createEmptyArray(globalThis, 4); + try object.putIndex(globalThis, 0, jsc.JSValue.jsNumber(rgba.red)); + try object.putIndex(globalThis, 1, jsc.JSValue.jsNumber(rgba.green)); + try object.putIndex(globalThis, 2, jsc.JSValue.jsNumber(rgba.blue)); + try object.putIndex(globalThis, 3, jsc.JSValue.jsNumber(rgba.alpha)); return object; }, .number => { @@ -312,7 +312,7 @@ pub fn jsFunctionColor(globalThis: *JSC.JSGlobalObject, callFrame: *JSC.CallFram int |= @as(u32, rgba.red) << 16; int |= @as(u32, rgba.green) << 8; int |= @as(u32, rgba.blue); - return JSC.JSValue.jsNumber(int); + return jsc.JSValue.jsNumber(int); }, .hex => { break :color bun.String.createFormat("#{}{}{}", .{ bun.fmt.hexIntLower(rgba.red), bun.fmt.hexIntLower(rgba.green), bun.fmt.hexIntLower(rgba.blue) }); @@ -409,7 +409,7 @@ pub fn jsFunctionColor(globalThis: *JSC.JSGlobalObject, callFrame: *JSC.CallFram defer dest.deinit(allocator); const writer = dest.writer(allocator); - const symbols = bun.JSAst.Symbol.Map{}; + const symbols = bun.ast.Symbol.Map{}; var printer = css.Printer(@TypeOf(writer)).new( allocator, std.ArrayList(u8).init(allocator), @@ -438,5 +438,5 @@ const RGBA = color.RGBA; const SRGB = color.SRGB; const bun = @import("bun"); -const JSC = bun.JSC; const css = bun.css; +const jsc = bun.jsc; diff --git a/src/css/values/ident.zig b/src/css/values/ident.zig index ff3c3362a2..b14ac562e0 100644 --- a/src/css/values/ident.zig +++ b/src/css/values/ident.zig @@ -225,7 +225,7 @@ pub const IdentOrRef = packed struct(u128) { return null; } - pub fn asStr(this: @This(), map: *const bun.JSAst.Symbol.Map, local_names: ?*const css.LocalsResultsMap) ?[]const u8 { + pub fn asStr(this: @This(), map: *const bun.ast.Symbol.Map, local_names: ?*const css.LocalsResultsMap) ?[]const u8 { if (this.isIdent()) return this.asIdent().?.v; const ref = this.asRef().?; const final_ref = map.follow(ref); @@ -322,4 +322,4 @@ pub const CustomIdentList = css.SmallList(CustomIdent, 1); const bun = @import("bun"); const std = @import("std"); const Allocator = std.mem.Allocator; -const Symbol = bun.JSAst.Symbol; +const Symbol = bun.ast.Symbol; diff --git a/src/css_scanner.zig b/src/css_scanner.zig index d9ee41c0bd..6968005a1c 100644 --- a/src/css_scanner.zig +++ b/src/css_scanner.zig @@ -1272,6 +1272,8 @@ pub fn NewBundler( }; } +const string = []const u8; + const Fs = @import("./fs.zig"); const Options = options; const import_record = @import("./import_record.zig"); @@ -1286,5 +1288,4 @@ const FeatureFlags = bun.FeatureFlags; const StoredFileDescriptorType = bun.StoredFileDescriptorType; const default_allocator = bun.default_allocator; const logger = bun.logger; -const string = bun.string; const strings = bun.strings; diff --git a/src/defines-table.zig b/src/defines-table.zig index 4e52daf2f0..d000012a43 100644 --- a/src/defines-table.zig +++ b/src/defines-table.zig @@ -918,9 +918,10 @@ pub const pure_global_identifier_map = bun.ComptimeStringMap(PureGlobalIdentifie .{ "crypto", PureGlobalIdentifierValue.other }, }); +const string = []const u8; + const defines = @import("./defines.zig"); const std = @import("std"); const bun = @import("bun"); -const js_ast = bun.JSAst; -const string = bun.string; +const js_ast = bun.ast; diff --git a/src/defines.zig b/src/defines.zig index d68c3aa813..d07c38177c 100644 --- a/src/defines.zig +++ b/src/defines.zig @@ -398,18 +398,20 @@ pub const Define = struct { } }; +const string = []const u8; + const fs = @import("./fs.zig"); const std = @import("std"); -const Ref = @import("./ast/base.zig").Ref; const table = @import("./defines-table.zig"); const global_no_side_effect_function_calls_safe_for_to_string = table.global_no_side_effect_function_calls_safe_for_to_string; const global_no_side_effect_property_accesses = table.global_no_side_effect_property_accesses; const bun = @import("bun"); -const js_ast = bun.JSAst; const js_lexer = bun.js_lexer; -const json_parser = bun.JSON; +const json_parser = bun.json; const logger = bun.logger; -const string = bun.string; const strings = bun.strings; + +const js_ast = bun.ast; +const Ref = bun.ast.Ref; diff --git a/src/deps/c_ares.zig b/src/deps/c_ares.zig index 55bb1cbe43..7375688ef2 100644 --- a/src/deps/c_ares.zig +++ b/src/deps/c_ares.zig @@ -192,17 +192,17 @@ pub const struct_hostent = extern struct { // hostent in glibc uses int for h_addrtype and h_length, whereas hostent in winsock2.h uses short. const hostent_int = if (bun.Environment.isWindows) c_short else c_int; - pub fn toJSResponse(this: *struct_hostent, _: std.mem.Allocator, globalThis: *JSC.JSGlobalObject, comptime lookup_name: []const u8) bun.JSError!JSC.JSValue { + pub fn toJSResponse(this: *struct_hostent, _: std.mem.Allocator, globalThis: *jsc.JSGlobalObject, comptime lookup_name: []const u8) bun.JSError!jsc.JSValue { if (comptime strings.eqlComptime(lookup_name, "cname")) { // A cname lookup always returns a single record but we follow the common API here. if (this.h_name == null) { - return try JSC.JSValue.createEmptyArray(globalThis, 0); + return try jsc.JSValue.createEmptyArray(globalThis, 0); } return bun.String.toJSArray(globalThis, &[_]bun.String{bun.String.borrowUTF8(this.h_name.?[0..bun.len(this.h_name.?)])}); } if (this.h_aliases == null) { - return try JSC.JSValue.createEmptyArray(globalThis, 0); + return try jsc.JSValue.createEmptyArray(globalThis, 0); } var count: u32 = 0; @@ -210,13 +210,13 @@ pub const struct_hostent = extern struct { count += 1; } - const array = try JSC.JSValue.createEmptyArray(globalThis, count); + const array = try jsc.JSValue.createEmptyArray(globalThis, count); count = 0; while (this.h_aliases.?[count]) |alias| { const alias_len = bun.len(alias); const alias_slice = alias[0..alias_len]; - try array.putIndex(globalThis, count, JSC.ZigString.fromUTF8(alias_slice).toJS(globalThis)); + try array.putIndex(globalThis, count, jsc.ZigString.fromUTF8(alias_slice).toJS(globalThis)); count += 1; } @@ -297,10 +297,10 @@ pub const hostent_with_ttls = struct { hostent: *struct_hostent, ttls: [256]c_int = [_]c_int{-1} ** 256, - pub fn toJSResponse(this: *hostent_with_ttls, _: std.mem.Allocator, globalThis: *JSC.JSGlobalObject, comptime lookup_name: []const u8) bun.JSError!JSC.JSValue { + pub fn toJSResponse(this: *hostent_with_ttls, _: std.mem.Allocator, globalThis: *jsc.JSGlobalObject, comptime lookup_name: []const u8) bun.JSError!jsc.JSValue { if (comptime strings.eqlComptime(lookup_name, "a") or strings.eqlComptime(lookup_name, "aaaa")) { if (this.hostent.h_addr_list == null) { - return try JSC.JSValue.createEmptyArray(globalThis, 0); + return try jsc.JSValue.createEmptyArray(globalThis, 0); } var count: u32 = 0; @@ -308,11 +308,11 @@ pub const hostent_with_ttls = struct { count += 1; } - const array = try JSC.JSValue.createEmptyArray(globalThis, count); + const array = try jsc.JSValue.createEmptyArray(globalThis, count); count = 0; - const addressKey = JSC.ZigString.static("address").withEncoding(); - const ttlKey = JSC.ZigString.static("ttl").withEncoding(); + const addressKey = jsc.ZigString.static("address").withEncoding(); + const ttlKey = jsc.ZigString.static("ttl").withEncoding(); while (this.hostent.h_addr_list.?[count]) |addr| : (count += 1) { const addrString = (if (this.hostent.h_addrtype == AF.INET6) @@ -321,7 +321,7 @@ pub const hostent_with_ttls = struct { bun.dns.addressToJS(&std.net.Address.initIp4(addr[0..4].*, 0), globalThis)) catch return globalThis.throwOutOfMemoryValue(); const ttl: ?c_int = if (count < this.ttls.len) this.ttls[count] else null; - const resultObject = try JSC.JSValue.createObject2(globalThis, &addressKey, &ttlKey, addrString, if (ttl) |val| JSC.jsNumber(val) else .js_undefined); + const resultObject = try jsc.JSValue.createObject2(globalThis, &addressKey, &ttlKey, addrString, if (ttl) |val| jsc.jsNumber(val) else .js_undefined); try array.putIndex(globalThis, count, resultObject); } @@ -372,7 +372,7 @@ pub const hostent_with_ttls = struct { }.handle; } - pub fn parse(comptime lookup_name: []const u8, buffer: [*c]u8, buffer_length: c_int) JSC.Node.Maybe(*hostent_with_ttls, Error) { + pub fn parse(comptime lookup_name: []const u8, buffer: [*c]u8, buffer_length: c_int) jsc.Node.Maybe(*hostent_with_ttls, Error) { var start: ?*struct_hostent = null; if (comptime strings.eqlComptime(lookup_name, "a")) { @@ -420,13 +420,13 @@ pub const struct_nameinfo = extern struct { node: [*c]u8, service: [*c]u8, - pub fn toJSResponse(this: *struct_nameinfo, _: std.mem.Allocator, globalThis: *JSC.JSGlobalObject) bun.JSError!JSC.JSValue { - const array = try JSC.JSValue.createEmptyArray(globalThis, 2); // [node, service] + pub fn toJSResponse(this: *struct_nameinfo, _: std.mem.Allocator, globalThis: *jsc.JSGlobalObject) bun.JSError!jsc.JSValue { + const array = try jsc.JSValue.createEmptyArray(globalThis, 2); // [node, service] if (this.node != null) { const node_len = bun.len(this.node); const node_slice = this.node[0..node_len]; - try array.putIndex(globalThis, 0, JSC.ZigString.fromUTF8(node_slice).toJS(globalThis)); + try array.putIndex(globalThis, 0, jsc.ZigString.fromUTF8(node_slice).toJS(globalThis)); } else { try array.putIndex(globalThis, 0, .js_undefined); } @@ -434,7 +434,7 @@ pub const struct_nameinfo = extern struct { if (this.service != null) { const service_len = bun.len(this.service); const service_slice = this.service[0..service_len]; - try array.putIndex(globalThis, 1, JSC.ZigString.fromUTF8(service_slice).toJS(globalThis)); + try array.putIndex(globalThis, 1, jsc.ZigString.fromUTF8(service_slice).toJS(globalThis)); } else { try array.putIndex(globalThis, 1, .js_undefined); } @@ -497,9 +497,9 @@ pub const AddrInfo = extern struct { node: ?*AddrInfo_node = null, name_: ?[*:0]u8 = null, - pub fn toJSArray(addr_info: *AddrInfo, globalThis: *JSC.JSGlobalObject) bun.JSError!JSC.JSValue { - var node = addr_info.node orelse return try JSC.JSValue.createEmptyArray(globalThis, 0); - const array = try JSC.JSValue.createEmptyArray(globalThis, node.count()); + pub fn toJSArray(addr_info: *AddrInfo, globalThis: *jsc.JSGlobalObject) bun.JSError!jsc.JSValue { + var node = addr_info.node orelse return try jsc.JSValue.createEmptyArray(globalThis, 0); + const array = try jsc.JSValue.createEmptyArray(globalThis, node.count()); { var j: u32 = 0; @@ -775,9 +775,9 @@ fn libraryInit() void { const rc = ares_library_init_mem( ARES_LIB_INIT_ALL, - bun.Mimalloc.mi_malloc, - bun.Mimalloc.mi_free, - bun.Mimalloc.mi_realloc, + bun.mimalloc.mi_malloc, + bun.mimalloc.mi_free, + bun.mimalloc.mi_realloc, ); if (rc != ARES_SUCCESS) { std.debug.panic("ares_library_init_mem failed: {any}", .{rc}); @@ -858,7 +858,7 @@ pub const struct_ares_caa_reply = extern struct { value: [*c]u8, length: usize, - pub fn toJSResponse(this: *struct_ares_caa_reply, parent_allocator: std.mem.Allocator, globalThis: *JSC.JSGlobalObject, comptime _: []const u8) bun.JSError!JSC.JSValue { + pub fn toJSResponse(this: *struct_ares_caa_reply, parent_allocator: std.mem.Allocator, globalThis: *jsc.JSGlobalObject, comptime _: []const u8) bun.JSError!jsc.JSValue { var stack = std.heap.stackFallback(2048, parent_allocator); var arena = bun.ArenaAllocator.init(stack.get()); defer arena.deinit(); @@ -870,7 +870,7 @@ pub const struct_ares_caa_reply = extern struct { count += 1; } - const array = try JSC.JSValue.createEmptyArray(globalThis, count); + const array = try jsc.JSValue.createEmptyArray(globalThis, count); caa = this; var i: u32 = 0; @@ -884,15 +884,15 @@ pub const struct_ares_caa_reply = extern struct { return array; } - pub fn toJS(this: *struct_ares_caa_reply, globalThis: *JSC.JSGlobalObject, _: std.mem.Allocator) JSC.JSValue { - var obj = JSC.JSValue.createEmptyObject(globalThis, 2); + pub fn toJS(this: *struct_ares_caa_reply, globalThis: *jsc.JSGlobalObject, _: std.mem.Allocator) jsc.JSValue { + var obj = jsc.JSValue.createEmptyObject(globalThis, 2); - obj.put(globalThis, JSC.ZigString.static("critical"), JSC.JSValue.jsNumber(this.critical)); + obj.put(globalThis, jsc.ZigString.static("critical"), jsc.JSValue.jsNumber(this.critical)); const property = this.property[0..this.plength]; const value = this.value[0..this.length]; - const property_str = JSC.ZigString.fromUTF8(property); - obj.put(globalThis, &property_str, JSC.ZigString.fromUTF8(value).toJS(globalThis)); + const property_str = jsc.ZigString.fromUTF8(property); + obj.put(globalThis, &property_str, jsc.ZigString.fromUTF8(value).toJS(globalThis)); return obj; } @@ -936,7 +936,7 @@ pub const struct_ares_srv_reply = extern struct { weight: c_ushort, port: c_ushort, - pub fn toJSResponse(this: *struct_ares_srv_reply, parent_allocator: std.mem.Allocator, globalThis: *JSC.JSGlobalObject, comptime _: []const u8) bun.JSError!JSC.JSValue { + pub fn toJSResponse(this: *struct_ares_srv_reply, parent_allocator: std.mem.Allocator, globalThis: *jsc.JSGlobalObject, comptime _: []const u8) bun.JSError!jsc.JSValue { var stack = std.heap.stackFallback(2048, parent_allocator); var arena = bun.ArenaAllocator.init(stack.get()); defer arena.deinit(); @@ -948,7 +948,7 @@ pub const struct_ares_srv_reply = extern struct { count += 1; } - const array = try JSC.JSValue.createEmptyArray(globalThis, count); + const array = try jsc.JSValue.createEmptyArray(globalThis, count); srv = this; var i: u32 = 0; @@ -962,8 +962,8 @@ pub const struct_ares_srv_reply = extern struct { return array; } - pub fn toJS(this: *struct_ares_srv_reply, globalThis: *JSC.JSGlobalObject, _: std.mem.Allocator) JSC.JSValue { - const obj = JSC.JSValue.createEmptyObject(globalThis, 4); + pub fn toJS(this: *struct_ares_srv_reply, globalThis: *jsc.JSGlobalObject, _: std.mem.Allocator) jsc.JSValue { + const obj = jsc.JSValue.createEmptyObject(globalThis, 4); // { // priority: 10, // weight: 5, @@ -971,13 +971,13 @@ pub const struct_ares_srv_reply = extern struct { // name: 'service.example.com' // } - obj.put(globalThis, JSC.ZigString.static("priority"), JSC.JSValue.jsNumber(this.priority)); - obj.put(globalThis, JSC.ZigString.static("weight"), JSC.JSValue.jsNumber(this.weight)); - obj.put(globalThis, JSC.ZigString.static("port"), JSC.JSValue.jsNumber(this.port)); + obj.put(globalThis, jsc.ZigString.static("priority"), jsc.JSValue.jsNumber(this.priority)); + obj.put(globalThis, jsc.ZigString.static("weight"), jsc.JSValue.jsNumber(this.weight)); + obj.put(globalThis, jsc.ZigString.static("port"), jsc.JSValue.jsNumber(this.port)); const len = bun.len(this.host); const host = this.host[0..len]; - obj.put(globalThis, JSC.ZigString.static("name"), JSC.ZigString.fromUTF8(host).toJS(globalThis)); + obj.put(globalThis, jsc.ZigString.static("name"), jsc.ZigString.fromUTF8(host).toJS(globalThis)); return obj; } @@ -1019,7 +1019,7 @@ pub const struct_ares_mx_reply = extern struct { host: [*c]u8, priority: c_ushort, - pub fn toJSResponse(this: *struct_ares_mx_reply, parent_allocator: std.mem.Allocator, globalThis: *JSC.JSGlobalObject, comptime _: []const u8) bun.JSError!JSC.JSValue { + pub fn toJSResponse(this: *struct_ares_mx_reply, parent_allocator: std.mem.Allocator, globalThis: *jsc.JSGlobalObject, comptime _: []const u8) bun.JSError!jsc.JSValue { var stack = std.heap.stackFallback(2048, parent_allocator); var arena = bun.ArenaAllocator.init(stack.get()); defer arena.deinit(); @@ -1031,7 +1031,7 @@ pub const struct_ares_mx_reply = extern struct { count += 1; } - const array = try JSC.JSValue.createEmptyArray(globalThis, count); + const array = try jsc.JSValue.createEmptyArray(globalThis, count); mx = this; var i: u32 = 0; @@ -1045,13 +1045,13 @@ pub const struct_ares_mx_reply = extern struct { return array; } - pub fn toJS(this: *struct_ares_mx_reply, globalThis: *JSC.JSGlobalObject, _: std.mem.Allocator) JSC.JSValue { - const obj = JSC.JSValue.createEmptyObject(globalThis, 2); - obj.put(globalThis, JSC.ZigString.static("priority"), JSC.JSValue.jsNumber(this.priority)); + pub fn toJS(this: *struct_ares_mx_reply, globalThis: *jsc.JSGlobalObject, _: std.mem.Allocator) jsc.JSValue { + const obj = jsc.JSValue.createEmptyObject(globalThis, 2); + obj.put(globalThis, jsc.ZigString.static("priority"), jsc.JSValue.jsNumber(this.priority)); const host_len = bun.len(this.host); const host = this.host[0..host_len]; - obj.put(globalThis, JSC.ZigString.static("exchange"), JSC.ZigString.fromUTF8(host).toJS(globalThis)); + obj.put(globalThis, jsc.ZigString.static("exchange"), jsc.ZigString.fromUTF8(host).toJS(globalThis)); return obj; } @@ -1093,7 +1093,7 @@ pub const struct_ares_txt_reply = extern struct { txt: [*c]u8, length: usize, - pub fn toJSResponse(this: *struct_ares_txt_reply, parent_allocator: std.mem.Allocator, globalThis: *JSC.JSGlobalObject, comptime _: []const u8) bun.JSError!JSC.JSValue { + pub fn toJSResponse(this: *struct_ares_txt_reply, parent_allocator: std.mem.Allocator, globalThis: *jsc.JSGlobalObject, comptime _: []const u8) bun.JSError!jsc.JSValue { var stack = std.heap.stackFallback(2048, parent_allocator); var arena = bun.ArenaAllocator.init(stack.get()); defer arena.deinit(); @@ -1105,7 +1105,7 @@ pub const struct_ares_txt_reply = extern struct { count += 1; } - const array = try JSC.JSValue.createEmptyArray(globalThis, count); + const array = try jsc.JSValue.createEmptyArray(globalThis, count); txt = this; var i: u32 = 0; @@ -1119,31 +1119,31 @@ pub const struct_ares_txt_reply = extern struct { return array; } - pub fn toJS(this: *struct_ares_txt_reply, globalThis: *JSC.JSGlobalObject, _: std.mem.Allocator) bun.JSError!JSC.JSValue { - const array = try JSC.JSValue.createEmptyArray(globalThis, 1); + pub fn toJS(this: *struct_ares_txt_reply, globalThis: *jsc.JSGlobalObject, _: std.mem.Allocator) bun.JSError!jsc.JSValue { + const array = try jsc.JSValue.createEmptyArray(globalThis, 1); const value = this.txt[0..this.length]; - try array.putIndex(globalThis, 0, JSC.ZigString.fromUTF8(value).toJS(globalThis)); + try array.putIndex(globalThis, 0, jsc.ZigString.fromUTF8(value).toJS(globalThis)); return array; } - pub fn toJSForAny(this: *struct_ares_txt_reply, _: std.mem.Allocator, globalThis: *JSC.JSGlobalObject, comptime _: []const u8) bun.JSError!JSC.JSValue { + pub fn toJSForAny(this: *struct_ares_txt_reply, _: std.mem.Allocator, globalThis: *jsc.JSGlobalObject, comptime _: []const u8) bun.JSError!jsc.JSValue { var count: usize = 0; var txt: ?*struct_ares_txt_reply = this; while (txt != null) : (txt = txt.?.next) { count += 1; } - const array = try JSC.JSValue.createEmptyArray(globalThis, count); + const array = try jsc.JSValue.createEmptyArray(globalThis, count); txt = this; var i: u32 = 0; while (txt != null) : (txt = txt.?.next) { var node = txt.?; - try array.putIndex(globalThis, i, JSC.ZigString.fromUTF8(node.txt[0..node.length]).toJS(globalThis)); + try array.putIndex(globalThis, i, jsc.ZigString.fromUTF8(node.txt[0..node.length]).toJS(globalThis)); i += 1; } - return (try JSC.JSObject.create(.{ + return (try jsc.JSObject.create(.{ .entries = array, }, globalThis)).toJS(); } @@ -1195,7 +1195,7 @@ pub const struct_ares_naptr_reply = extern struct { order: c_ushort, preference: c_ushort, - pub fn toJSResponse(this: *struct_ares_naptr_reply, parent_allocator: std.mem.Allocator, globalThis: *JSC.JSGlobalObject, comptime _: []const u8) bun.JSError!JSC.JSValue { + pub fn toJSResponse(this: *struct_ares_naptr_reply, parent_allocator: std.mem.Allocator, globalThis: *jsc.JSGlobalObject, comptime _: []const u8) bun.JSError!jsc.JSValue { var stack = std.heap.stackFallback(2048, parent_allocator); var arena = bun.ArenaAllocator.init(stack.get()); defer arena.deinit(); @@ -1207,7 +1207,7 @@ pub const struct_ares_naptr_reply = extern struct { count += 1; } - const array = try JSC.JSValue.createEmptyArray(globalThis, count); + const array = try jsc.JSValue.createEmptyArray(globalThis, count); naptr = this; var i: u32 = 0; @@ -1221,27 +1221,27 @@ pub const struct_ares_naptr_reply = extern struct { return array; } - pub fn toJS(this: *struct_ares_naptr_reply, globalThis: *JSC.JSGlobalObject, _: std.mem.Allocator) JSC.JSValue { - const obj = JSC.JSValue.createEmptyObject(globalThis, 6); + pub fn toJS(this: *struct_ares_naptr_reply, globalThis: *jsc.JSGlobalObject, _: std.mem.Allocator) jsc.JSValue { + const obj = jsc.JSValue.createEmptyObject(globalThis, 6); - obj.put(globalThis, JSC.ZigString.static("preference"), JSC.JSValue.jsNumber(this.preference)); - obj.put(globalThis, JSC.ZigString.static("order"), JSC.JSValue.jsNumber(this.order)); + obj.put(globalThis, jsc.ZigString.static("preference"), jsc.JSValue.jsNumber(this.preference)); + obj.put(globalThis, jsc.ZigString.static("order"), jsc.JSValue.jsNumber(this.order)); const flags_len = bun.len(this.flags); const flags = this.flags[0..flags_len]; - obj.put(globalThis, JSC.ZigString.static("flags"), JSC.ZigString.fromUTF8(flags).toJS(globalThis)); + obj.put(globalThis, jsc.ZigString.static("flags"), jsc.ZigString.fromUTF8(flags).toJS(globalThis)); const service_len = bun.len(this.service); const service = this.service[0..service_len]; - obj.put(globalThis, JSC.ZigString.static("service"), JSC.ZigString.fromUTF8(service).toJS(globalThis)); + obj.put(globalThis, jsc.ZigString.static("service"), jsc.ZigString.fromUTF8(service).toJS(globalThis)); const regexp_len = bun.len(this.regexp); const regexp = this.regexp[0..regexp_len]; - obj.put(globalThis, JSC.ZigString.static("regexp"), JSC.ZigString.fromUTF8(regexp).toJS(globalThis)); + obj.put(globalThis, jsc.ZigString.static("regexp"), jsc.ZigString.fromUTF8(regexp).toJS(globalThis)); const replacement_len = bun.len(this.replacement); const replacement = this.replacement[0..replacement_len]; - obj.put(globalThis, JSC.ZigString.static("replacement"), JSC.ZigString.fromUTF8(replacement).toJS(globalThis)); + obj.put(globalThis, jsc.ZigString.static("replacement"), jsc.ZigString.fromUTF8(replacement).toJS(globalThis)); return obj; } @@ -1287,7 +1287,7 @@ pub const struct_ares_soa_reply = extern struct { expire: c_uint, minttl: c_uint, - pub fn toJSResponse(this: *struct_ares_soa_reply, parent_allocator: std.mem.Allocator, globalThis: *JSC.JSGlobalObject, comptime _: []const u8) bun.JSError!JSC.JSValue { + pub fn toJSResponse(this: *struct_ares_soa_reply, parent_allocator: std.mem.Allocator, globalThis: *jsc.JSGlobalObject, comptime _: []const u8) bun.JSError!jsc.JSValue { var stack = std.heap.stackFallback(2048, parent_allocator); var arena = bun.ArenaAllocator.init(stack.get()); defer arena.deinit(); @@ -1297,22 +1297,22 @@ pub const struct_ares_soa_reply = extern struct { return this.toJS(globalThis, allocator); } - pub fn toJS(this: *struct_ares_soa_reply, globalThis: *JSC.JSGlobalObject, _: std.mem.Allocator) JSC.JSValue { - const obj = JSC.JSValue.createEmptyObject(globalThis, 7); + pub fn toJS(this: *struct_ares_soa_reply, globalThis: *jsc.JSGlobalObject, _: std.mem.Allocator) jsc.JSValue { + const obj = jsc.JSValue.createEmptyObject(globalThis, 7); - obj.put(globalThis, JSC.ZigString.static("serial"), JSC.JSValue.jsNumber(this.serial)); - obj.put(globalThis, JSC.ZigString.static("refresh"), JSC.JSValue.jsNumber(this.refresh)); - obj.put(globalThis, JSC.ZigString.static("retry"), JSC.JSValue.jsNumber(this.retry)); - obj.put(globalThis, JSC.ZigString.static("expire"), JSC.JSValue.jsNumber(this.expire)); - obj.put(globalThis, JSC.ZigString.static("minttl"), JSC.JSValue.jsNumber(this.minttl)); + obj.put(globalThis, jsc.ZigString.static("serial"), jsc.JSValue.jsNumber(this.serial)); + obj.put(globalThis, jsc.ZigString.static("refresh"), jsc.JSValue.jsNumber(this.refresh)); + obj.put(globalThis, jsc.ZigString.static("retry"), jsc.JSValue.jsNumber(this.retry)); + obj.put(globalThis, jsc.ZigString.static("expire"), jsc.JSValue.jsNumber(this.expire)); + obj.put(globalThis, jsc.ZigString.static("minttl"), jsc.JSValue.jsNumber(this.minttl)); const nsname_len = bun.len(this.nsname); const nsname = this.nsname[0..nsname_len]; - obj.put(globalThis, JSC.ZigString.static("nsname"), JSC.ZigString.fromUTF8(nsname).toJS(globalThis)); + obj.put(globalThis, jsc.ZigString.static("nsname"), jsc.ZigString.fromUTF8(nsname).toJS(globalThis)); const hostmaster_len = bun.len(this.hostmaster); const hostmaster = this.hostmaster[0..hostmaster_len]; - obj.put(globalThis, JSC.ZigString.static("hostmaster"), JSC.ZigString.fromUTF8(hostmaster).toJS(globalThis)); + obj.put(globalThis, jsc.ZigString.static("hostmaster"), jsc.ZigString.fromUTF8(hostmaster).toJS(globalThis)); return obj; } @@ -1370,7 +1370,7 @@ pub const struct_any_reply = struct { soa_reply: ?*struct_ares_soa_reply = null, caa_reply: ?*struct_ares_caa_reply = null, - pub fn toJSResponse(this: *struct_any_reply, parent_allocator: std.mem.Allocator, globalThis: *JSC.JSGlobalObject, comptime _: []const u8) bun.JSError!JSC.JSValue { + pub fn toJSResponse(this: *struct_any_reply, parent_allocator: std.mem.Allocator, globalThis: *jsc.JSGlobalObject, comptime _: []const u8) bun.JSError!jsc.JSValue { var stack = std.heap.stackFallback(2048, parent_allocator); var arena = bun.ArenaAllocator.init(stack.get()); defer arena.deinit(); @@ -1380,9 +1380,9 @@ pub const struct_any_reply = struct { return this.toJS(globalThis, allocator); } - fn append(globalThis: *JSC.JSGlobalObject, array: JSC.JSValue, i: *u32, response: JSC.JSValue, comptime lookup_name: []const u8) bun.JSError!void { + fn append(globalThis: *jsc.JSGlobalObject, array: jsc.JSValue, i: *u32, response: jsc.JSValue, comptime lookup_name: []const u8) bun.JSError!void { const transformed = if (response.isString()) - (try JSC.JSObject.create(.{ + (try jsc.JSObject.create(.{ .value = response, }, globalThis)).toJS() else blk: { @@ -1400,8 +1400,8 @@ pub const struct_any_reply = struct { i.* += 1; } - fn appendAll(globalThis: *JSC.JSGlobalObject, allocator: std.mem.Allocator, array: JSC.JSValue, i: *u32, reply: anytype, comptime lookup_name: []const u8) bun.JSError!void { - const response: JSC.JSValue = try if (comptime @hasDecl(@TypeOf(reply.*), "toJSForAny")) + fn appendAll(globalThis: *jsc.JSGlobalObject, allocator: std.mem.Allocator, array: jsc.JSValue, i: *u32, reply: anytype, comptime lookup_name: []const u8) bun.JSError!void { + const response: jsc.JSValue = try if (comptime @hasDecl(@TypeOf(reply.*), "toJSForAny")) reply.toJSForAny(allocator, globalThis, lookup_name) else reply.toJSResponse(allocator, globalThis, lookup_name); @@ -1416,8 +1416,8 @@ pub const struct_any_reply = struct { } } - pub fn toJS(this: *struct_any_reply, globalThis: *JSC.JSGlobalObject, allocator: std.mem.Allocator) bun.JSError!JSC.JSValue { - const array = try JSC.JSValue.createEmptyArray(globalThis, blk: { + pub fn toJS(this: *struct_any_reply, globalThis: *jsc.JSGlobalObject, allocator: std.mem.Allocator) bun.JSError!jsc.JSValue { + const array = try jsc.JSValue.createEmptyArray(globalThis, blk: { var len: usize = 0; inline for (comptime @typeInfo(struct_any_reply).@"struct".fields) |field| { if (comptime std.mem.endsWith(u8, field.name, "_reply")) { @@ -1669,11 +1669,11 @@ pub const Error = enum(i32) { errno: Error, syscall: []const u8, hostname: ?bun.String, - promise: JSC.JSPromise.Strong, + promise: jsc.JSPromise.Strong, pub const new = bun.TrivialNew(@This()); - pub fn init(errno: Error, syscall: []const u8, hostname: ?bun.String, promise: JSC.JSPromise.Strong) *Deferred { + pub fn init(errno: Error, syscall: []const u8, hostname: ?bun.String, promise: jsc.JSPromise.Strong) *Deferred { return Deferred.new(.{ .errno = errno, .syscall = syscall, @@ -1682,8 +1682,8 @@ pub const Error = enum(i32) { }); } - pub fn reject(this: *Deferred, globalThis: *JSC.JSGlobalObject) void { - const system_error = JSC.SystemError{ + pub fn reject(this: *Deferred, globalThis: *jsc.JSGlobalObject) void { + const system_error = jsc.SystemError{ .errno = @intFromEnum(this.errno), .code = bun.String.static(this.errno.code()), .message = if (this.hostname) |hostname| @@ -1702,10 +1702,10 @@ pub const Error = enum(i32) { this.deinit(); } - pub fn rejectLater(this: *Deferred, globalThis: *JSC.JSGlobalObject) void { + pub fn rejectLater(this: *Deferred, globalThis: *jsc.JSGlobalObject) void { const Context = struct { deferred: *Deferred, - globalThis: *JSC.JSGlobalObject, + globalThis: *jsc.JSGlobalObject, pub fn callback(context: *@This()) void { context.deferred.reject(context.globalThis); bun.default_allocator.destroy(context); @@ -1716,7 +1716,7 @@ pub const Error = enum(i32) { context.deferred = this; context.globalThis = globalThis; // TODO(@heimskr): new custom Task type - globalThis.bunVM().enqueueTask(JSC.ManagedTask.New(Context, Context.callback).init(context)); + globalThis.bunVM().enqueueTask(jsc.ManagedTask.New(Context, Context.callback).init(context)); } pub fn deinit(this: *@This()) void { @@ -1728,7 +1728,7 @@ pub const Error = enum(i32) { } }; - pub fn toDeferred(this: Error, syscall: []const u8, hostname: ?[]const u8, promise: *JSC.JSPromise.Strong) *Deferred { + pub fn toDeferred(this: Error, syscall: []const u8, hostname: ?[]const u8, promise: *jsc.JSPromise.Strong) *Deferred { const host_string: ?bun.String = if (hostname) |host| bun.String.cloneUTF8(host) else @@ -1737,8 +1737,8 @@ pub const Error = enum(i32) { return Deferred.init(this, syscall, host_string, promise.*); } - pub fn toJSWithSyscall(this: Error, globalThis: *JSC.JSGlobalObject, comptime syscall: [:0]const u8) JSC.JSValue { - const instance = (JSC.SystemError{ + pub fn toJSWithSyscall(this: Error, globalThis: *jsc.JSGlobalObject, comptime syscall: [:0]const u8) jsc.JSValue { + const instance = (jsc.SystemError{ .errno = @intFromEnum(this), .code = bun.String.static(this.code()[4..]), .syscall = bun.String.static(syscall), @@ -1748,8 +1748,8 @@ pub const Error = enum(i32) { return instance; } - pub fn toJSWithSyscallAndHostname(this: Error, globalThis: *JSC.JSGlobalObject, comptime syscall: [:0]const u8, hostname: []const u8) JSC.JSValue { - const instance = (JSC.SystemError{ + pub fn toJSWithSyscallAndHostname(this: Error, globalThis: *jsc.JSGlobalObject, comptime syscall: [:0]const u8, hostname: []const u8) jsc.JSValue { + const instance = (jsc.SystemError{ .errno = @intFromEnum(this), .code = bun.String.static(this.code()[4..]), .message = bun.String.createFormat("{s} {s} {s}", .{ syscall, this.code()[4..], hostname }) catch bun.outOfMemory(), @@ -1981,11 +1981,11 @@ pub const ares_addr_node = struct_ares_addr_node; pub const ares_addr_port_node = struct_ares_addr_port_node; comptime { - const Bun__canonicalizeIP = JSC.toJSHostFn(Bun__canonicalizeIP_); + const Bun__canonicalizeIP = jsc.toJSHostFn(Bun__canonicalizeIP_); @export(&Bun__canonicalizeIP, .{ .name = "Bun__canonicalizeIP" }); } -pub fn Bun__canonicalizeIP_(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { - JSC.markBinding(@src()); +pub fn Bun__canonicalizeIP_(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { + jsc.markBinding(@src()); const arguments = callframe.arguments_old(1); @@ -1996,7 +1996,7 @@ pub fn Bun__canonicalizeIP_(globalThis: *JSC.JSGlobalObject, callframe: *JSC.Cal const INET6_ADDRSTRLEN = if (comptime bun.Environment.isWindows) 65 else 46; const script_ctx = globalThis.bunVM(); - var args = JSC.CallFrame.ArgumentsSlice.init(script_ctx, arguments.slice()); + var args = jsc.CallFrame.ArgumentsSlice.init(script_ctx, arguments.slice()); const addr_arg = args.nextEat().?; const addr = try bun.String.fromJS(addr_arg, globalThis); @@ -2029,7 +2029,7 @@ pub fn Bun__canonicalizeIP_(globalThis: *JSC.JSGlobalObject, callframe: *JSC.Cal } // use the null-terminated size to return the string const size = bun.len(bun.cast([*:0]u8, &ip_addr)); - return JSC.ZigString.init(ip_addr[0..size]).toJS(globalThis); + return jsc.ZigString.init(ip_addr[0..size]).toJS(globalThis); } } @@ -2082,7 +2082,7 @@ const std = @import("std"); const iovec = @import("std").os.iovec; const bun = @import("bun"); -const JSC = bun.JSC; +const jsc = bun.jsc; const strings = bun.strings; const GetAddrInfo = bun.dns.GetAddrInfo; const libuv = bun.windows.libuv; diff --git a/src/deps/libdeflate.zig b/src/deps/libdeflate.zig index 31e501878d..ac0a8223f0 100644 --- a/src/deps/libdeflate.zig +++ b/src/deps/libdeflate.zig @@ -14,7 +14,7 @@ pub extern fn libdeflate_gzip_compress_bound(compressor: *Compressor, in_nbytes: pub extern fn libdeflate_free_compressor(compressor: *Compressor) void; fn load_once() void { - libdeflate_set_memory_allocator(bun.Mimalloc.mi_malloc, bun.Mimalloc.mi_free); + libdeflate_set_memory_allocator(bun.mimalloc.mi_malloc, bun.mimalloc.mi_free); } var loaded_once = std.once(load_once); diff --git a/src/deps/libuv.zig b/src/deps/libuv.zig index 561e2e1aef..7321ce6c2d 100644 --- a/src/deps/libuv.zig +++ b/src/deps/libuv.zig @@ -3089,7 +3089,7 @@ const sockaddr_storage = std.os.linux.sockaddr_storage; const bun = @import("bun"); const Env = bun.Environment; -const Maybe = bun.JSC.Maybe; +const Maybe = bun.jsc.Maybe; const windows = bun.windows; const BOOL = windows.BOOL; diff --git a/src/deps/lol-html.zig b/src/deps/lol-html.zig index 57e5b14d79..b823e7309b 100644 --- a/src/deps/lol-html.zig +++ b/src/deps/lol-html.zig @@ -609,7 +609,7 @@ pub const HTMLString = extern struct { return bun.String.cloneUTF8(bytes); } - pub fn toJS(this: HTMLString, globalThis: *bun.JSC.JSGlobalObject) bun.JSC.JSValue { + pub fn toJS(this: HTMLString, globalThis: *bun.jsc.JSGlobalObject) bun.jsc.JSValue { var str = this.toString(); defer str.deref(); return str.toJS(globalThis); diff --git a/src/deps/picohttp.zig b/src/deps/picohttp.zig index 62cfdf5e51..b674897fb9 100644 --- a/src/deps/picohttp.zig +++ b/src/deps/picohttp.zig @@ -365,6 +365,8 @@ pub const phr_parse_headers = c.phr_parse_headers; pub const phr_decode_chunked = c.phr_decode_chunked; pub const phr_decode_chunked_is_in_data = c.phr_decode_chunked_is_in_data; +const string = []const u8; + const c = @import("./picohttpparser.zig"); const bun = @import("bun"); @@ -372,7 +374,6 @@ const Environment = bun.Environment; const Output = bun.Output; const StringBuilder = bun.StringBuilder; const assert = bun.assert; -const string = bun.string; const strings = bun.strings; const std = @import("std"); diff --git a/src/deps/uws.zig b/src/deps/uws.zig index 489640cee9..8da33f6467 100644 --- a/src/deps/uws.zig +++ b/src/deps/uws.zig @@ -70,7 +70,7 @@ pub const create_bun_socket_error_t = enum(c_int) { invalid_ca_file, invalid_ca, - pub fn toJS(this: create_bun_socket_error_t, globalObject: *JSC.JSGlobalObject) JSC.JSValue { + pub fn toJS(this: create_bun_socket_error_t, globalObject: *jsc.JSGlobalObject) jsc.JSValue { return switch (this) { .none => brk: { bun.debugAssert(false); @@ -88,11 +88,11 @@ pub const us_bun_verify_error_t = extern struct { code: [*c]const u8 = null, reason: [*c]const u8 = null, - pub fn toJS(this: *const us_bun_verify_error_t, globalObject: *JSC.JSGlobalObject) JSC.JSValue { + pub fn toJS(this: *const us_bun_verify_error_t, globalObject: *jsc.JSGlobalObject) jsc.JSValue { const code = if (this.code == null) "" else this.code[0..bun.len(this.code)]; const reason = if (this.reason == null) "" else this.reason[0..bun.len(this.reason)]; - const fallback = JSC.SystemError{ + const fallback = jsc.SystemError{ .code = bun.String.cloneUTF8(code), .message = bun.String.cloneUTF8(reason), }; @@ -146,4 +146,4 @@ pub const LIBUS_SOCKET_DESCRIPTOR = switch (bun.Environment.isWindows) { const bun = @import("bun"); const Environment = bun.Environment; -const JSC = bun.JSC; +const jsc = bun.jsc; diff --git a/src/deps/uws/InternalLoopData.zig b/src/deps/uws/InternalLoopData.zig index 9260529e00..69918ec02a 100644 --- a/src/deps/uws/InternalLoopData.zig +++ b/src/deps/uws/InternalLoopData.zig @@ -22,13 +22,13 @@ pub const InternalLoopData = extern struct { parent_ptr: ?*anyopaque, parent_tag: c_char, iteration_nr: usize, - jsc_vm: ?*JSC.VM, + jsc_vm: ?*jsc.VM, pub fn recvSlice(this: *InternalLoopData) []u8 { return this.recv_buf[0..LIBUS_RECV_BUFFER_LENGTH]; } - pub fn setParentEventLoop(this: *InternalLoopData, parent: JSC.EventLoopHandle) void { + pub fn setParentEventLoop(this: *InternalLoopData, parent: jsc.EventLoopHandle) void { switch (parent) { .js => |ptr| { this.parent_tag = 1; @@ -41,12 +41,12 @@ pub const InternalLoopData = extern struct { } } - pub fn getParent(this: *InternalLoopData) JSC.EventLoopHandle { + pub fn getParent(this: *InternalLoopData) jsc.EventLoopHandle { const parent = this.parent_ptr orelse @panic("Parent loop not set - pointer is null"); return switch (this.parent_tag) { 0 => @panic("Parent loop not set - tag is zero"), - 1 => .{ .js = bun.cast(*JSC.EventLoop, parent) }, - 2 => .{ .mini = bun.cast(*JSC.MiniEventLoop, parent) }, + 1 => .{ .js = bun.cast(*jsc.EventLoop, parent) }, + 2 => .{ .mini = bun.cast(*jsc.MiniEventLoop, parent) }, else => @panic("Parent loop data corrupted - tag is invalid"), }; } @@ -55,7 +55,7 @@ pub const InternalLoopData = extern struct { }; const bun = @import("bun"); -const JSC = bun.JSC; +const jsc = bun.jsc; const uws = bun.uws; const ConnectingSocket = uws.ConnectingSocket; diff --git a/src/deps/uws/Request.zig b/src/deps/uws/Request.zig index fe43abd56a..7076bda139 100644 --- a/src/deps/uws/Request.zig +++ b/src/deps/uws/Request.zig @@ -30,7 +30,7 @@ pub const Request = opaque { if (value == null) return null; var string = bun.String.init(value.?); defer string.deref(); - const date_f64 = try bun.String.parseDate(&string, bun.JSC.VirtualMachine.get().global); + const date_f64 = try bun.String.parseDate(&string, bun.jsc.VirtualMachine.get().global); if (!std.math.isNan(date_f64) and std.math.isFinite(date_f64)) { return @intFromFloat(date_f64); } diff --git a/src/deps/uws/UpgradedDuplex.zig b/src/deps/uws/UpgradedDuplex.zig index b46736bc7e..497a0a4a9c 100644 --- a/src/deps/uws/UpgradedDuplex.zig +++ b/src/deps/uws/UpgradedDuplex.zig @@ -15,15 +15,15 @@ const UpgradedDuplex = @This(); wrapper: ?WrapperType, -origin: JSC.Strong.Optional = .empty, // any duplex -global: ?*JSC.JSGlobalObject = null, +origin: jsc.Strong.Optional = .empty, // any duplex +global: ?*jsc.JSGlobalObject = null, ssl_error: CertError = .{}, -vm: *JSC.VirtualMachine, +vm: *jsc.VirtualMachine, handlers: Handlers, -onDataCallback: JSC.Strong.Optional = .empty, -onEndCallback: JSC.Strong.Optional = .empty, -onWritableCallback: JSC.Strong.Optional = .empty, -onCloseCallback: JSC.Strong.Optional = .empty, +onDataCallback: jsc.Strong.Optional = .empty, +onEndCallback: jsc.Strong.Optional = .empty, +onWritableCallback: jsc.Strong.Optional = .empty, +onCloseCallback: jsc.Strong.Optional = .empty, event_loop_timer: EventLoopTimer = .{ .next = .epoch, .tag = .UpgradedDuplex, @@ -55,7 +55,7 @@ pub const Handlers = struct { onClose: *const fn (*anyopaque) void, onEnd: *const fn (*anyopaque) void, onWritable: *const fn (*anyopaque) void, - onError: *const fn (*anyopaque, JSC.JSValue) void, + onError: *const fn (*anyopaque, jsc.JSValue) void, onTimeout: *const fn (*anyopaque) void, }; @@ -97,7 +97,7 @@ fn callWriteOrEnd(this: *UpgradedDuplex, data: ?[]const u8, msg_more: bool) void const globalThis = this.global.?; const writeOrEnd = if (msg_more) duplex.getFunction(globalThis, "write") catch return orelse return else duplex.getFunction(globalThis, "end") catch return orelse return; if (data) |data_| { - const buffer = JSC.ArrayBuffer.BinaryType.toJS(.Buffer, data_, globalThis) catch |err| { + const buffer = jsc.ArrayBuffer.BinaryType.toJS(.Buffer, data_, globalThis) catch |err| { this.handlers.onError(this.handlers.ctx, globalThis.takeException(err)); return; }; @@ -139,15 +139,15 @@ fn onInternalReceiveData(this: *UpgradedDuplex, data: []const u8) void { } fn onReceivedData( - globalObject: *JSC.JSGlobalObject, - callframe: *JSC.CallFrame, -) bun.JSError!JSC.JSValue { + globalObject: *jsc.JSGlobalObject, + callframe: *jsc.CallFrame, +) bun.JSError!jsc.JSValue { log("onReceivedData", .{}); const function = callframe.callee(); const args = callframe.arguments_old(1); - if (JSC.host_fn.getFunctionData(function)) |self| { + if (jsc.host_fn.getFunctionData(function)) |self| { const this = @as(*UpgradedDuplex, @ptrCast(@alignCast(self))); if (args.len >= 1) { const data_arg = args.ptr[0]; @@ -172,14 +172,14 @@ fn onReceivedData( } fn onEnd( - globalObject: *JSC.JSGlobalObject, - callframe: *JSC.CallFrame, + globalObject: *jsc.JSGlobalObject, + callframe: *jsc.CallFrame, ) void { log("onEnd", .{}); _ = globalObject; const function = callframe.callee(); - if (JSC.host_fn.getFunctionData(function)) |self| { + if (jsc.host_fn.getFunctionData(function)) |self| { const this = @as(*UpgradedDuplex, @ptrCast(@alignCast(self))); if (this.wrapper != null) { @@ -189,15 +189,15 @@ fn onEnd( } fn onWritable( - globalObject: *JSC.JSGlobalObject, - callframe: *JSC.CallFrame, -) bun.JSError!JSC.JSValue { + globalObject: *jsc.JSGlobalObject, + callframe: *jsc.CallFrame, +) bun.JSError!jsc.JSValue { log("onWritable", .{}); _ = globalObject; const function = callframe.callee(); - if (JSC.host_fn.getFunctionData(function)) |self| { + if (jsc.host_fn.getFunctionData(function)) |self| { const this = @as(*UpgradedDuplex, @ptrCast(@alignCast(self))); // flush pending data if (this.wrapper) |*wrapper| { @@ -211,15 +211,15 @@ fn onWritable( } fn onCloseJS( - globalObject: *JSC.JSGlobalObject, - callframe: *JSC.CallFrame, -) bun.JSError!JSC.JSValue { + globalObject: *jsc.JSGlobalObject, + callframe: *jsc.CallFrame, +) bun.JSError!jsc.JSValue { log("onCloseJS", .{}); _ = globalObject; const function = callframe.callee(); - if (JSC.host_fn.getFunctionData(function)) |self| { + if (jsc.host_fn.getFunctionData(function)) |self| { const this = @as(*UpgradedDuplex, @ptrCast(@alignCast(self))); // flush pending data if (this.wrapper) |*wrapper| { @@ -248,8 +248,8 @@ pub fn onTimeout(this: *UpgradedDuplex) EventLoopTimer.Arm { } pub fn from( - globalThis: *JSC.JSGlobalObject, - origin: JSC.JSValue, + globalThis: *jsc.JSGlobalObject, + origin: jsc.JSValue, handlers: UpgradedDuplex.Handlers, ) UpgradedDuplex { return UpgradedDuplex{ @@ -261,13 +261,13 @@ pub fn from( }; } -pub fn getJSHandlers(this: *UpgradedDuplex, globalThis: *JSC.JSGlobalObject) bun.JSError!JSC.JSValue { - const array = try JSC.JSValue.createEmptyArray(globalThis, 4); +pub fn getJSHandlers(this: *UpgradedDuplex, globalThis: *jsc.JSGlobalObject) bun.JSError!jsc.JSValue { + const array = try jsc.JSValue.createEmptyArray(globalThis, 4); array.ensureStillAlive(); { const callback = this.onDataCallback.get() orelse brk: { - const dataCallback = JSC.host_fn.NewFunctionWithData( + const dataCallback = jsc.host_fn.NewFunctionWithData( globalThis, null, 0, @@ -277,7 +277,7 @@ pub fn getJSHandlers(this: *UpgradedDuplex, globalThis: *JSC.JSGlobalObject) bun ); dataCallback.ensureStillAlive(); - JSC.host_fn.setFunctionData(dataCallback, this); + jsc.host_fn.setFunctionData(dataCallback, this); this.onDataCallback = .create(dataCallback, globalThis); break :brk dataCallback; @@ -287,7 +287,7 @@ pub fn getJSHandlers(this: *UpgradedDuplex, globalThis: *JSC.JSGlobalObject) bun { const callback = this.onEndCallback.get() orelse brk: { - const endCallback = JSC.host_fn.NewFunctionWithData( + const endCallback = jsc.host_fn.NewFunctionWithData( globalThis, null, 0, @@ -297,7 +297,7 @@ pub fn getJSHandlers(this: *UpgradedDuplex, globalThis: *JSC.JSGlobalObject) bun ); endCallback.ensureStillAlive(); - JSC.host_fn.setFunctionData(endCallback, this); + jsc.host_fn.setFunctionData(endCallback, this); this.onEndCallback = .create(endCallback, globalThis); break :brk endCallback; @@ -307,7 +307,7 @@ pub fn getJSHandlers(this: *UpgradedDuplex, globalThis: *JSC.JSGlobalObject) bun { const callback = this.onWritableCallback.get() orelse brk: { - const writableCallback = JSC.host_fn.NewFunctionWithData( + const writableCallback = jsc.host_fn.NewFunctionWithData( globalThis, null, 0, @@ -317,7 +317,7 @@ pub fn getJSHandlers(this: *UpgradedDuplex, globalThis: *JSC.JSGlobalObject) bun ); writableCallback.ensureStillAlive(); - JSC.host_fn.setFunctionData(writableCallback, this); + jsc.host_fn.setFunctionData(writableCallback, this); this.onWritableCallback = .create(writableCallback, globalThis); break :brk writableCallback; }; @@ -326,7 +326,7 @@ pub fn getJSHandlers(this: *UpgradedDuplex, globalThis: *JSC.JSGlobalObject) bun { const callback = this.onCloseCallback.get() orelse brk: { - const closeCallback = JSC.host_fn.NewFunctionWithData( + const closeCallback = jsc.host_fn.NewFunctionWithData( globalThis, null, 0, @@ -336,7 +336,7 @@ pub fn getJSHandlers(this: *UpgradedDuplex, globalThis: *JSC.JSGlobalObject) bun ); closeCallback.ensureStillAlive(); - JSC.host_fn.setFunctionData(closeCallback, this); + jsc.host_fn.setFunctionData(closeCallback, this); this.onCloseCallback = .create(closeCallback, globalThis); break :brk closeCallback; }; @@ -346,7 +346,7 @@ pub fn getJSHandlers(this: *UpgradedDuplex, globalThis: *JSC.JSGlobalObject) bun return array; } -pub fn startTLS(this: *UpgradedDuplex, ssl_options: JSC.API.ServerConfig.SSLConfig, is_client: bool) !void { +pub fn startTLS(this: *UpgradedDuplex, ssl_options: jsc.API.ServerConfig.SSLConfig, is_client: bool) !void { this.wrapper = try WrapperType.init(ssl_options, is_client, .{ .ctx = this, .onOpen = UpgradedDuplex.onOpen, @@ -458,19 +458,19 @@ pub fn deinit(this: *UpgradedDuplex) void { this.origin.deinit(); if (this.onDataCallback.get()) |callback| { - JSC.host_fn.setFunctionData(callback, null); + jsc.host_fn.setFunctionData(callback, null); this.onDataCallback.deinit(); } if (this.onEndCallback.get()) |callback| { - JSC.host_fn.setFunctionData(callback, null); + jsc.host_fn.setFunctionData(callback, null); this.onEndCallback.deinit(); } if (this.onWritableCallback.get()) |callback| { - JSC.host_fn.setFunctionData(callback, null); + jsc.host_fn.setFunctionData(callback, null); this.onWritableCallback.deinit(); } if (this.onCloseCallback.get()) |callback| { - JSC.host_fn.setFunctionData(callback, null); + jsc.host_fn.setFunctionData(callback, null); this.onCloseCallback.deinit(); } var ssl_error = this.ssl_error; @@ -483,7 +483,7 @@ const log = bun.Output.scoped(.UpgradedDuplex, false); const SSLWrapper = @import("../../bun.js/api/bun/ssl_wrapper.zig").SSLWrapper; const bun = @import("bun"); -const JSC = bun.JSC; +const jsc = bun.jsc; const BoringSSL = bun.BoringSSL.c; const EventLoopTimer = bun.api.Timer.EventLoopTimer; diff --git a/src/deps/uws/WindowsNamedPipe.zig b/src/deps/uws/WindowsNamedPipe.zig index 39275418dc..e3267f8a03 100644 --- a/src/deps/uws/WindowsNamedPipe.zig +++ b/src/deps/uws/WindowsNamedPipe.zig @@ -21,7 +21,7 @@ const WindowsNamedPipe = @This(); wrapper: ?WrapperType, pipe: if (Environment.isWindows) ?*uv.Pipe else void, // any duplex -vm: *bun.JSC.VirtualMachine, //TODO: create a timeout version that dont need the JSC VM +vm: *bun.jsc.VirtualMachine, //TODO: create a timeout version that dont need the jsc VM writer: bun.io.StreamingWriter(WindowsNamedPipe, .{ .onClose = onClose, @@ -261,7 +261,7 @@ pub fn onTimeout(this: *WindowsNamedPipe) EventLoopTimer.Arm { pub fn from( pipe: *uv.Pipe, handlers: WindowsNamedPipe.Handlers, - vm: *JSC.VirtualMachine, + vm: *jsc.VirtualMachine, ) WindowsNamedPipe { if (Environment.isPosix) { @compileError("WindowsNamedPipe is not supported on POSIX systems"); @@ -298,7 +298,7 @@ fn onConnect(this: *WindowsNamedPipe, status: uv.ReturnCode) void { this.flush(); } -pub fn getAcceptedBy(this: *WindowsNamedPipe, server: *uv.Pipe, ssl_ctx: ?*BoringSSL.SSL_CTX) JSC.Maybe(void) { +pub fn getAcceptedBy(this: *WindowsNamedPipe, server: *uv.Pipe, ssl_ctx: ?*BoringSSL.SSL_CTX) jsc.Maybe(void) { bun.assert(this.pipe != null); this.flags.disconnected = true; @@ -346,7 +346,7 @@ pub fn getAcceptedBy(this: *WindowsNamedPipe, server: *uv.Pipe, ssl_ctx: ?*Borin } return .{ .result = {} }; } -pub fn open(this: *WindowsNamedPipe, fd: bun.FileDescriptor, ssl_options: ?JSC.API.ServerConfig.SSLConfig) JSC.Maybe(void) { +pub fn open(this: *WindowsNamedPipe, fd: bun.FileDescriptor, ssl_options: ?jsc.API.ServerConfig.SSLConfig) jsc.Maybe(void) { bun.assert(this.pipe != null); this.flags.disconnected = true; @@ -382,7 +382,7 @@ pub fn open(this: *WindowsNamedPipe, fd: bun.FileDescriptor, ssl_options: ?JSC.A return .{ .result = {} }; } -pub fn connect(this: *WindowsNamedPipe, path: []const u8, ssl_options: ?JSC.API.ServerConfig.SSLConfig) JSC.Maybe(void) { +pub fn connect(this: *WindowsNamedPipe, path: []const u8, ssl_options: ?jsc.API.ServerConfig.SSLConfig) jsc.Maybe(void) { bun.assert(this.pipe != null); this.flags.disconnected = true; // ref because we are connecting @@ -414,7 +414,7 @@ pub fn connect(this: *WindowsNamedPipe, path: []const u8, ssl_options: ?JSC.API. this.connect_req.data = this; return this.pipe.?.connect(&this.connect_req, path, this, onConnect); } -pub fn startTLS(this: *WindowsNamedPipe, ssl_options: JSC.API.ServerConfig.SSLConfig, is_client: bool) !void { +pub fn startTLS(this: *WindowsNamedPipe, ssl_options: jsc.API.ServerConfig.SSLConfig, is_client: bool) !void { this.flags.is_ssl = true; if (this.start(is_client)) { this.wrapper = try WrapperType.init(ssl_options, is_client, .{ @@ -580,7 +580,7 @@ const SSLWrapper = @import("../../bun.js/api/bun/ssl_wrapper.zig").SSLWrapper; const bun = @import("bun"); const Environment = bun.Environment; -const JSC = bun.JSC; +const jsc = bun.jsc; const BoringSSL = bun.BoringSSL.c; const uv = bun.windows.libuv; const EventLoopTimer = bun.api.Timer.EventLoopTimer; diff --git a/src/dns.zig b/src/dns.zig index 42f69f5c0e..e3bc939830 100644 --- a/src/dns.zig +++ b/src/dns.zig @@ -75,7 +75,7 @@ pub const GetAddrInfo = struct { InvalidOptions, }; - pub fn fromJS(value: JSC.JSValue, globalObject: *JSC.JSGlobalObject) FromJSError!Options { + pub fn fromJS(value: jsc.JSValue, globalObject: *jsc.JSGlobalObject) FromJSError!Options { if (value.isEmptyOrUndefinedOrNull()) return Options{}; @@ -135,7 +135,7 @@ pub const GetAddrInfo = struct { InvalidFamily, }; - pub fn fromJS(value: JSC.JSValue, globalObject: *JSC.JSGlobalObject) FromJSError!Family { + pub fn fromJS(value: jsc.JSValue, globalObject: *jsc.JSGlobalObject) FromJSError!Family { if (value.isEmptyOrUndefinedOrNull()) return .unspecified; @@ -195,7 +195,7 @@ pub const GetAddrInfo = struct { InvalidSocketType, }; - pub fn fromJS(value: JSC.JSValue, globalObject: *JSC.JSGlobalObject) FromJSError!SocketType { + pub fn fromJS(value: jsc.JSValue, globalObject: *jsc.JSGlobalObject) FromJSError!SocketType { if (value.isEmptyOrUndefinedOrNull()) // Default to .stream return .stream; @@ -236,7 +236,7 @@ pub const GetAddrInfo = struct { InvalidProtocol, }; - pub fn fromJS(value: JSC.JSValue, globalObject: *JSC.JSGlobalObject) FromJSError!Protocol { + pub fn fromJS(value: jsc.JSValue, globalObject: *jsc.JSGlobalObject) FromJSError!Protocol { if (value.isEmptyOrUndefinedOrNull()) return .unspecified; @@ -295,7 +295,7 @@ pub const GetAddrInfo = struct { InvalidBackend, }; - pub fn fromJS(value: JSC.JSValue, globalObject: *JSC.JSGlobalObject) FromJSError!Backend { + pub fn fromJS(value: jsc.JSValue, globalObject: *jsc.JSGlobalObject) FromJSError!Backend { if (value.isEmptyOrUndefinedOrNull()) return default; @@ -323,11 +323,11 @@ pub const GetAddrInfo = struct { addrinfo: ?*std.c.addrinfo, list: List, - pub fn toJS(this: *const Any, globalThis: *JSC.JSGlobalObject) bun.JSError!?JSC.JSValue { + pub fn toJS(this: *const Any, globalThis: *jsc.JSGlobalObject) bun.JSError!?jsc.JSValue { return switch (this.*) { .addrinfo => |addrinfo| try addrInfoToJSArray(addrinfo orelse return null, globalThis), .list => |list| brk: { - const array = try JSC.JSValue.createEmptyArray(globalThis, @as(u32, @truncate(list.items.len))); + const array = try jsc.JSValue.createEmptyArray(globalThis, @as(u32, @truncate(list.items.len))); var i: u32 = 0; const items: []const Result = list.items; for (items) |item| { @@ -373,18 +373,18 @@ pub const GetAddrInfo = struct { }; } - pub fn toJS(this: *const Result, globalThis: *JSC.JSGlobalObject) JSValue { - const obj = JSC.JSValue.createEmptyObject(globalThis, 3); - obj.put(globalThis, JSC.ZigString.static("address"), addressToJS(&this.address, globalThis) catch |err| return switch (err) { + pub fn toJS(this: *const Result, globalThis: *jsc.JSGlobalObject) JSValue { + const obj = jsc.JSValue.createEmptyObject(globalThis, 3); + obj.put(globalThis, jsc.ZigString.static("address"), addressToJS(&this.address, globalThis) catch |err| return switch (err) { error.JSError => .zero, error.OutOfMemory => globalThis.throwOutOfMemoryValue(), }); - obj.put(globalThis, JSC.ZigString.static("family"), switch (this.address.any.family) { + obj.put(globalThis, jsc.ZigString.static("family"), switch (this.address.any.family) { std.posix.AF.INET => JSValue.jsNumber(4), std.posix.AF.INET6 => JSValue.jsNumber(6), else => JSValue.jsNumber(0), }); - obj.put(globalThis, JSC.ZigString.static("ttl"), JSValue.jsNumber(this.ttl)); + obj.put(globalThis, jsc.ZigString.static("ttl"), JSValue.jsNumber(this.ttl)); return obj; } }; @@ -422,7 +422,7 @@ pub fn addressToString(address: *const std.net.Address) bun.OOM!bun.String { } } -pub fn addressToJS(address: *const std.net.Address, globalThis: *JSC.JSGlobalObject) bun.JSError!JSC.JSValue { +pub fn addressToJS(address: *const std.net.Address, globalThis: *jsc.JSGlobalObject) bun.JSError!jsc.JSValue { var str = addressToString(address) catch return globalThis.throwOutOfMemory(); return str.transferToJS(globalThis); } @@ -436,8 +436,8 @@ fn addrInfoCount(addrinfo: *std.c.addrinfo) u32 { return count; } -pub fn addrInfoToJSArray(addr_info: *std.c.addrinfo, globalThis: *JSC.JSGlobalObject) bun.JSError!JSC.JSValue { - const array = try JSC.JSValue.createEmptyArray( +pub fn addrInfoToJSArray(addr_info: *std.c.addrinfo, globalThis: *jsc.JSGlobalObject) bun.JSError!jsc.JSValue { + const array = try jsc.JSValue.createEmptyArray( globalThis, addrInfoCount(addr_info), ); @@ -461,7 +461,7 @@ pub fn addrInfoToJSArray(addr_info: *std.c.addrinfo, globalThis: *JSC.JSGlobalOb return array; } -pub const internal = bun.api.DNS.InternalDNS; +pub const internal = bun.api.dns.internal; const std = @import("std"); @@ -470,5 +470,5 @@ const JSError = bun.JSError; const String = bun.String; const default_allocator = bun.default_allocator; -const JSC = bun.JSC; -const JSValue = JSC.JSValue; +const jsc = bun.jsc; +const JSValue = jsc.JSValue; diff --git a/src/env_loader.zig b/src/env_loader.zig index d4c453abe3..d2399ff509 100644 --- a/src/env_loader.zig +++ b/src/env_loader.zig @@ -327,8 +327,8 @@ pub const Loader = struct { to_json: *JSONStore, comptime StringStore: type, to_string: *StringStore, - framework_defaults: Api.StringMap, - behavior: Api.DotEnvBehavior, + framework_defaults: api.StringMap, + behavior: api.DotEnvBehavior, prefix: string, allocator: std.mem.Allocator, ) !void { @@ -380,7 +380,7 @@ pub const Loader = struct { if (key_buf_len > 0) { iter.reset(); key_buf = try allocator.alloc(u8, key_buf_len + key_count * "process.env.".len); - const js_ast = bun.JSAst; + const js_ast = bun.ast; var e_strings = try allocator.alloc(js_ast.E.String, e_strings_to_allocate * 2); errdefer allocator.free(e_strings); @@ -551,7 +551,7 @@ pub const Loader = struct { while (iter.next()) |file_path| { if (file_path.len > 0) { try this.loadEnvFileDynamic(file_path, false); - Analytics.Features.dotenv += 1; + analytics.Features.dotenv += 1; } } } @@ -573,19 +573,19 @@ pub const Loader = struct { .development => { if (dir.hasComptimeQuery(".env.development.local")) { try this.loadEnvFile(dir_handle, ".env.development.local", false); - Analytics.Features.dotenv += 1; + analytics.Features.dotenv += 1; } }, .production => { if (dir.hasComptimeQuery(".env.production.local")) { try this.loadEnvFile(dir_handle, ".env.production.local", false); - Analytics.Features.dotenv += 1; + analytics.Features.dotenv += 1; } }, .@"test" => { if (dir.hasComptimeQuery(".env.test.local")) { try this.loadEnvFile(dir_handle, ".env.test.local", false); - Analytics.Features.dotenv += 1; + analytics.Features.dotenv += 1; } }, } @@ -593,7 +593,7 @@ pub const Loader = struct { if (comptime suffix != .@"test") { if (dir.hasComptimeQuery(".env.local")) { try this.loadEnvFile(dir_handle, ".env.local", false); - Analytics.Features.dotenv += 1; + analytics.Features.dotenv += 1; } } @@ -601,26 +601,26 @@ pub const Loader = struct { .development => { if (dir.hasComptimeQuery(".env.development")) { try this.loadEnvFile(dir_handle, ".env.development", false); - Analytics.Features.dotenv += 1; + analytics.Features.dotenv += 1; } }, .production => { if (dir.hasComptimeQuery(".env.production")) { try this.loadEnvFile(dir_handle, ".env.production", false); - Analytics.Features.dotenv += 1; + analytics.Features.dotenv += 1; } }, .@"test" => { if (dir.hasComptimeQuery(".env.test")) { try this.loadEnvFile(dir_handle, ".env.test", false); - Analytics.Features.dotenv += 1; + analytics.Features.dotenv += 1; } }, } if (dir.hasComptimeQuery(".env")) { try this.loadEnvFile(dir_handle, ".env", false); - Analytics.Features.dotenv += 1; + analytics.Features.dotenv += 1; } } @@ -1329,17 +1329,18 @@ pub var instance: ?*Loader = null; pub const home_env = if (Environment.isWindows) "USERPROFILE" else "HOME"; -const Analytics = @import("./analytics/analytics_thread.zig"); +const string = []const u8; + const Fs = @import("./fs.zig"); const std = @import("std"); -const Api = @import("./api/schema.zig").Api; const URL = @import("./url.zig").URL; const which = @import("./which.zig").which; const bun = @import("bun"); const Environment = bun.Environment; const Output = bun.Output; +const analytics = bun.analytics; const logger = bun.logger; const s3 = bun.S3; -const string = bun.string; const strings = bun.strings; +const api = bun.schema.api; diff --git a/src/fd.zig b/src/fd.zig index 9c77632765..f32750007a 100644 --- a/src/fd.zig +++ b/src/fd.zig @@ -323,7 +323,7 @@ pub const FD = packed struct(backing_int) { } // If a non-number is given, returns null. // If the given number is not an fd (negative), an error is thrown and error.JSException is returned. - pub fn fromJSValidated(value: JSValue, global: *JSC.JSGlobalObject) bun.JSError!?FD { + pub fn fromJSValidated(value: JSValue, global: *jsc.JSGlobalObject) bun.JSError!?FD { if (!value.isNumber()) return null; const float = value.asNumber(); @@ -344,10 +344,10 @@ pub const FD = packed struct(backing_int) { } /// After calling, the input file descriptor is no longer valid and must not be used. /// If an error is thrown, the file descriptor is cleaned up for you. - pub fn toJS(any_fd: FD, global: *JSC.JSGlobalObject) JSValue { + pub fn toJS(any_fd: FD, global: *jsc.JSGlobalObject) JSValue { const uv_owned_fd = any_fd.makeLibUVOwned() catch { any_fd.close(); - return global.throwValue((JSC.SystemError{ + return global.throwValue((jsc.SystemError{ .message = bun.String.static("EMFILE, too many open files"), .code = bun.String.static("EMFILE"), }).toErrorInstance(global)) catch .zero; @@ -689,8 +689,8 @@ const allow_assert = Environment.allow_assert; const is_posix = Environment.isPosix; const os = Environment.os; -const JSC = bun.JSC; -const JSValue = JSC.JSValue; +const jsc = bun.jsc; +const JSValue = jsc.JSValue; const libuv = bun.windows.libuv; const uv_file = bun.windows.libuv.uv_file; diff --git a/src/fmt.zig b/src/fmt.zig index ec84395921..a699bfb000 100644 --- a/src/fmt.zig +++ b/src/fmt.zig @@ -1742,7 +1742,7 @@ pub const js_bindings = struct { const gen = bun.gen.fmt; /// Internal function for testing in highlighter.test.ts - pub fn fmtString(global: *bun.JSC.JSGlobalObject, code: []const u8, formatter_id: gen.Formatter) bun.JSError!bun.String { + pub fn fmtString(global: *bun.jsc.JSGlobalObject, code: []const u8, formatter_id: gen.Formatter) bun.JSError!bun.String { var buffer = bun.MutableString.initEmpty(bun.default_allocator); defer buffer.deinit(); var writer = buffer.bufferedWriter(); @@ -1878,12 +1878,13 @@ fn truncatedHash32Impl(int: u64, comptime fmt_str: []const u8, _: std.fmt.Format }); } +const string = []const u8; + const bun = @import("bun"); const Environment = bun.Environment; const Output = bun.Output; const js_lexer = bun.js_lexer; const sha = bun.sha; -const string = bun.string; const strings = bun.strings; const std = @import("std"); diff --git a/src/fs.zig b/src/fs.zig index c1cc428b8e..7968cde64e 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -1950,10 +1950,13 @@ pub const Path = struct { // pub fn customRealpath(allocator: std.mem.Allocator, path: string) !string { // var opened = try std.posix.open(path, if (Environment.isLinux) bun.O.PATH else bun.O.RDONLY, 0); // defer std.posix.close(opened); - // } + pub const StatHash = @import("./fs/stat_hash.zig"); +const string = []const u8; +const stringZ = [:0]const u8; + const path_handler = @import("./resolver/resolve_path.zig"); const std = @import("std"); @@ -1973,6 +1976,4 @@ const StoredFileDescriptorType = bun.StoredFileDescriptorType; const WPathBuffer = bun.WPathBuffer; const allocators = bun.allocators; const default_allocator = bun.default_allocator; -const string = bun.string; -const stringZ = bun.stringZ; const strings = bun.strings; diff --git a/src/fs/stat_hash.zig b/src/fs/stat_hash.zig index 3670de2275..325a08ed8e 100644 --- a/src/fs/stat_hash.zig +++ b/src/fs/stat_hash.zig @@ -25,7 +25,7 @@ pub fn hash(this: *@This(), stat: bun.Stat, path: []const u8) void { .sec = @intCast(@max(mtime_timespec.sec, 0)), }; if (mtime.ms() > 0) { - this.last_modified_buffer_len = @intCast(bun.JSC.wtf.writeHTTPDate(&this.last_modified_buffer, mtime.msUnsigned()).len); + this.last_modified_buffer_len = @intCast(bun.jsc.wtf.writeHTTPDate(&this.last_modified_buffer, mtime.msUnsigned()).len); this.last_modified_u64 = mtime.msUnsigned(); } else { this.last_modified_buffer_len = 0; diff --git a/src/glob/GlobWalker.zig b/src/glob/GlobWalker.zig index 45cf3c5e6d..74482278fa 100644 --- a/src/glob/GlobWalker.zig +++ b/src/glob/GlobWalker.zig @@ -1669,20 +1669,20 @@ pub const matchImpl = match; const DirIterator = @import("../bun.js/node/dir_iterator.zig"); const ResolvePath = @import("../resolver/resolve_path.zig"); -const CodepointIterator = @import("../string_immutable.zig").UnsignedCodepointIterator; -const isAllAscii = @import("../string_immutable.zig").isAllASCII; const match = @import("./match.zig").match; -const Cursor = CodepointIterator.Cursor; -const Codepoint = CodepointIterator.Cursor.CodePointType; - const bun = @import("bun"); const BunString = bun.String; const Syscall = bun.sys; +const CodepointIterator = bun.strings.UnsignedCodepointIterator; +const isAllAscii = bun.strings.isAllASCII; -const JSC = bun.JSC; -const Maybe = JSC.Maybe; -const ZigString = bun.JSC.ZigString; +const jsc = bun.jsc; +const Maybe = jsc.Maybe; +const ZigString = bun.jsc.ZigString; + +const Cursor = CodepointIterator.Cursor; +const Codepoint = CodepointIterator.Cursor.CodePointType; const std = @import("std"); const ArrayList = std.ArrayListUnmanaged; diff --git a/src/highway.zig b/src/highway.zig index 293bc6b0bd..33b75554c9 100644 --- a/src/highway.zig +++ b/src/highway.zig @@ -298,9 +298,10 @@ pub fn indexOfSpaceOrNewlineOrNonASCII(haystack: string) ?usize { return result; } +const string = []const u8; + const std = @import("std"); const bun = @import("bun"); const Environment = bun.Environment; -const string = bun.string; const strings = bun.strings; diff --git a/src/hmac.zig b/src/hmac.zig index d664f32e39..72a7d36b8c 100644 --- a/src/hmac.zig +++ b/src/hmac.zig @@ -1,4 +1,4 @@ -pub fn generate(key: []const u8, data: []const u8, algorithm: bun.JSC.API.Bun.Crypto.EVP.Algorithm, out: *[boring.EVP_MAX_MD_SIZE]u8) ?[]const u8 { +pub fn generate(key: []const u8, data: []const u8, algorithm: bun.jsc.API.Bun.Crypto.EVP.Algorithm, out: *[boring.EVP_MAX_MD_SIZE]u8) ?[]const u8 { var outlen: c_uint = boring.EVP_MAX_MD_SIZE; if (boring.HMAC( algorithm.md() orelse bun.Output.panic("Expected BoringSSL algorithm for HMAC", .{}), diff --git a/src/http.zig b/src/http.zig index cdd4047952..15d0785a8e 100644 --- a/src/http.zig +++ b/src/http.zig @@ -438,7 +438,7 @@ proxy_tunnel: ?*ProxyTunnel = null, signals: Signals = .{}, async_http_id: u32 = 0, hostname: ?[]u8 = null, -unix_socket_path: JSC.ZigString.Slice = JSC.ZigString.Slice.empty, +unix_socket_path: jsc.ZigString.Slice = jsc.ZigString.Slice.empty, pub fn deinit(this: *HTTPClient) void { if (this.redirect.len > 0) { @@ -454,7 +454,7 @@ pub fn deinit(this: *HTTPClient) void { tunnel.detachAndDeref(); } this.unix_socket_path.deinit(); - this.unix_socket_path = JSC.ZigString.Slice.empty; + this.unix_socket_path = jsc.ZigString.Slice.empty; } pub fn isKeepAlivePossible(this: *HTTPClient) bool { @@ -527,7 +527,7 @@ else const user_agent_header = picohttp.Header{ .name = "User-Agent", .value = Global.user_agent }; -pub fn headerStr(this: *const HTTPClient, ptr: Api.StringPointer) string { +pub fn headerStr(this: *const HTTPClient, ptr: api.StringPointer) string { return this.header_buf[ptr.offset..][0..ptr.length]; } @@ -686,7 +686,7 @@ pub fn doRedirect( } this.unix_socket_path.deinit(); - this.unix_socket_path = JSC.ZigString.Slice.empty; + this.unix_socket_path = jsc.ZigString.Slice.empty; // TODO: what we do with stream body? const request_body = if (this.state.flags.resend_request_body_on_redirect and this.state.original_request_body == .bytes) this.state.original_request_body.bytes @@ -1285,7 +1285,7 @@ pub fn closeAndFail(this: *HTTPClient, err: anyerror, comptime is_ssl: bool, soc fn startProxyHandshake(this: *HTTPClient, comptime is_ssl: bool, socket: NewHTTPContext(is_ssl).HTTPSocket, start_payload: []const u8) void { log("startProxyHandshake", .{}); // if we have options we pass them (ca, reject_unauthorized, etc) otherwise use the default - const ssl_options = if (this.tls_props != null) this.tls_props.?.* else JSC.API.ServerConfig.SSLConfig.zero; + const ssl_options = if (this.tls_props != null) this.tls_props.?.* else jsc.API.ServerConfig.SSLConfig.zero; ProxyTunnel.start(this, is_ssl, socket, ssl_options, start_payload); } @@ -1683,7 +1683,7 @@ pub const HTTPClientResult = struct { body_size: BodySize = .unknown, certificate_info: ?CertificateInfo = null, - pub fn abortReason(this: *const HTTPClientResult) ?JSC.CommonAbortReason { + pub fn abortReason(this: *const HTTPClientResult) ?jsc.CommonAbortReason { if (this.isTimeout()) { return .Timeout; } @@ -2224,7 +2224,7 @@ pub fn handleResponseMetadata( if (comptime Environment.allow_assert) assert(string_builder.cap == string_builder.len); - const normalized_url = JSC.URL.hrefFromString(bun.String.fromBytes(string_builder.allocatedSlice())); + const normalized_url = jsc.URL.hrefFromString(bun.String.fromBytes(string_builder.allocatedSlice())); defer normalized_url.deref(); if (normalized_url.tag == .Dead) { // URL__getHref failed, dont pass dead tagged string to toOwnedSlice. @@ -2268,7 +2268,7 @@ pub fn handleResponseMetadata( if (comptime Environment.allow_assert) assert(string_builder.cap == string_builder.len); - const normalized_url = JSC.URL.hrefFromString(bun.String.fromBytes(string_builder.allocatedSlice())); + const normalized_url = jsc.URL.hrefFromString(bun.String.fromBytes(string_builder.allocatedSlice())); defer normalized_url.deref(); const normalized_url_str = try normalized_url.toOwnedSlice(bun.default_allocator); @@ -2279,7 +2279,7 @@ pub fn handleResponseMetadata( } else { const original_url = this.url; - const new_url_ = bun.JSC.URL.join( + const new_url_ = bun.jsc.URL.join( bun.String.fromBytes(original_url.href), bun.String.fromBytes(location), ); @@ -2442,29 +2442,30 @@ pub const InitError = @import("./http/InitError.zig").InitError; pub const HTTPRequestBody = @import("./http/HTTPRequestBody.zig").HTTPRequestBody; pub const SendFile = @import("./http/SendFile.zig"); +const string = []const u8; + const HTTPCertError = @import("./http/HTTPCertError.zig"); const ProxyTunnel = @import("./http/ProxyTunnel.zig"); const std = @import("std"); -const Api = @import("./api/schema.zig").Api; -const Arena = @import("./allocators/mimalloc_arena.zig").Arena; const URL = @import("./url.zig").URL; -const SSLConfig = @import("./bun.js/api/server.zig").ServerConfig.SSLConfig; const bun = @import("bun"); const Environment = bun.Environment; const FeatureFlags = bun.FeatureFlags; const Global = bun.Global; -const JSC = bun.JSC; const MutableString = bun.MutableString; const Output = bun.Output; const Progress = bun.Progress; const StringBuilder = bun.StringBuilder; const assert = bun.assert; +const jsc = bun.jsc; const picohttp = bun.picohttp; -const string = bun.string; const strings = bun.strings; const uws = bun.uws; +const Arena = bun.allocators.MimallocArena; const BoringSSL = bun.BoringSSL.c; +const api = bun.schema.api; +const SSLConfig = bun.api.server.ServerConfig.SSLConfig; const posix = std.posix; const SOCK = posix.SOCK; diff --git a/src/http/AsyncHTTP.zig b/src/http/AsyncHTTP.zig index dda2c01ace..defb87a76d 100644 --- a/src/http/AsyncHTTP.zig +++ b/src/http/AsyncHTTP.zig @@ -79,7 +79,7 @@ pub fn clearData(this: *AsyncHTTP) void { this.request = null; this.response = null; this.client.unix_socket_path.deinit(); - this.client.unix_socket_path = JSC.ZigString.Slice.empty; + this.client.unix_socket_path = jsc.ZigString.Slice.empty; } pub const State = enum(u32) { @@ -95,7 +95,7 @@ pub const Options = struct { http_proxy: ?URL = null, hostname: ?[]u8 = null, signals: ?Signals = null, - unix_socket_path: ?JSC.ZigString.Slice = null, + unix_socket_path: ?jsc.ZigString.Slice = null, disable_timeout: ?bool = null, verbose: ?HTTPVerboseLevel = null, disable_keepalive: ?bool = null, @@ -492,12 +492,13 @@ pub const HTTPChannelContext = struct { } }; +const string = []const u8; + const DotEnv = @import("../env_loader.zig"); const HTTPThread = @import("./HTTPThread.zig"); const Headers = @import("./Headers.zig"); const std = @import("std"); const Encoding = @import("./Encoding.zig").Encoding; -const SSLConfig = @import("../bun.js/api/server.zig").ServerConfig.SSLConfig; const PercentEncoding = @import("../url.zig").PercentEncoding; const URL = @import("../url.zig").URL; @@ -505,12 +506,12 @@ const URL = @import("../url.zig").URL; const bun = @import("bun"); const Environment = bun.Environment; const FeatureFlags = bun.FeatureFlags; -const JSC = bun.JSC; const MutableString = bun.MutableString; const assert = bun.assert; +const jsc = bun.jsc; const picohttp = bun.picohttp; -const string = bun.string; const Channel = bun.threading.Channel; +const SSLConfig = bun.api.server.ServerConfig.SSLConfig; const ThreadPool = bun.ThreadPool; const Batch = bun.ThreadPool.Batch; diff --git a/src/http/HTTPThread.zig b/src/http/HTTPThread.zig index 04650df55f..354cf93483 100644 --- a/src/http/HTTPThread.zig +++ b/src/http/HTTPThread.zig @@ -2,7 +2,7 @@ const HTTPThread = @This(); var custom_ssl_context_map = std.AutoArrayHashMap(*SSLConfig, *NewHTTPContext(true)).init(bun.default_allocator); -loop: *JSC.MiniEventLoop, +loop: *jsc.MiniEventLoop, http_context: NewHTTPContext(false), https_context: NewHTTPContext(true), @@ -198,7 +198,7 @@ pub fn onStart(opts: InitOpts) void { bun.http.default_arena = Arena.init() catch unreachable; bun.http.default_allocator = bun.http.default_arena.allocator(); - const loop = bun.JSC.MiniEventLoop.initGlobal(null); + const loop = bun.jsc.MiniEventLoop.initGlobal(null); if (Environment.isWindows) { _ = std.process.getenvW(comptime bun.strings.w("SystemRoot")) orelse { @@ -462,21 +462,22 @@ pub const Queue = UnboundedQueue(AsyncHTTP, .next); const log = Output.scoped(.HTTPThread, false); +const stringZ = [:0]const u8; + const ProxyTunnel = @import("./ProxyTunnel.zig"); const std = @import("std"); -const Arena = @import("../allocators/mimalloc_arena.zig").Arena; -const SSLConfig = @import("../bun.js/api/server.zig").ServerConfig.SSLConfig; const bun = @import("bun"); const Environment = bun.Environment; const Global = bun.Global; -const JSC = bun.JSC; const Output = bun.Output; -const stringZ = bun.stringZ; +const jsc = bun.jsc; const strings = bun.strings; const uws = bun.uws; +const Arena = bun.allocators.MimallocArena; const Batch = bun.ThreadPool.Batch; const UnboundedQueue = bun.threading.UnboundedQueue; +const SSLConfig = bun.api.server.ServerConfig.SSLConfig; const HTTPClient = bun.http; const AsyncHTTP = bun.http.AsyncHTTP; diff --git a/src/http/HeaderBuilder.zig b/src/http/HeaderBuilder.zig index 0c2906c4fb..2e11267196 100644 --- a/src/http/HeaderBuilder.zig +++ b/src/http/HeaderBuilder.zig @@ -15,14 +15,14 @@ pub fn allocate(this: *HeaderBuilder, allocator: std.mem.Allocator) !void { try this.entries.ensureTotalCapacity(allocator, this.header_count); } pub fn append(this: *HeaderBuilder, name: string, value: string) void { - const name_ptr = Api.StringPointer{ + const name_ptr = api.StringPointer{ .offset = @as(u32, @truncate(this.content.len)), .length = @as(u32, @truncate(name.len)), }; _ = this.content.append(name); - const value_ptr = Api.StringPointer{ + const value_ptr = api.StringPointer{ .offset = @as(u32, @truncate(this.content.len)), .length = @as(u32, @truncate(value.len)), }; @@ -31,7 +31,7 @@ pub fn append(this: *HeaderBuilder, name: string, value: string) void { } pub fn appendFmt(this: *HeaderBuilder, name: string, comptime fmt: string, args: anytype) void { - const name_ptr = Api.StringPointer{ + const name_ptr = api.StringPointer{ .offset = @as(u32, @truncate(this.content.len)), .length = @as(u32, @truncate(name.len)), }; @@ -40,7 +40,7 @@ pub fn appendFmt(this: *HeaderBuilder, name: string, comptime fmt: string, args: const value = this.content.fmt(fmt, args); - const value_ptr = Api.StringPointer{ + const value_ptr = api.StringPointer{ .offset = @as(u32, @truncate(this.content.len - value.len)), .length = @as(u32, @truncate(value.len)), }; @@ -53,11 +53,12 @@ pub fn apply(this: *HeaderBuilder, client: *HTTPClient) void { client.header_buf = this.content.ptr.?[0..this.content.len]; } +const string = []const u8; + const HTTPClient = @import("../http.zig"); const std = @import("std"); -const Api = @import("../api/schema.zig").Api; const bun = @import("bun"); const StringBuilder = bun.StringBuilder; -const string = bun.string; const Headers = bun.http.Headers; +const api = bun.schema.api; diff --git a/src/http/Headers.zig b/src/http/Headers.zig index ede9e3809f..587ec0b5eb 100644 --- a/src/http/Headers.zig +++ b/src/http/Headers.zig @@ -1,8 +1,8 @@ const Headers = @This(); pub const Entry = struct { - name: Api.StringPointer, - value: Api.StringPointer, + name: api.StringPointer, + value: api.StringPointer, pub const List = bun.MultiArrayList(Entry); }; @@ -39,7 +39,7 @@ pub fn get(this: *const Headers, name: []const u8) ?[]const u8 { pub fn append(this: *Headers, name: []const u8, value: []const u8) !void { var offset: u32 = @truncate(this.buf.items.len); try this.buf.ensureUnusedCapacity(this.allocator, name.len + value.len); - const name_ptr = Api.StringPointer{ + const name_ptr = api.StringPointer{ .offset = offset, .length = @truncate(name.len), }; @@ -47,7 +47,7 @@ pub fn append(this: *Headers, name: []const u8, value: []const u8) !void { offset = @truncate(this.buf.items.len); this.buf.appendSliceAssumeCapacity(value); - const value_ptr = Api.StringPointer{ + const value_ptr = api.StringPointer{ .offset = offset, .length = @truncate(value.len), }; @@ -76,7 +76,7 @@ pub fn getContentType(this: *const Headers) ?[]const u8 { } return null; } -pub fn asStr(this: *const Headers, ptr: Api.StringPointer) []const u8 { +pub fn asStr(this: *const Headers, ptr: api.StringPointer) []const u8 { return if (ptr.offset + ptr.length <= this.buf.items.len) this.buf.items[ptr.offset..][0..ptr.length] else @@ -176,10 +176,10 @@ pub fn from(fetch_headers_ref: ?*FetchHeaders, allocator: std.mem.Allocator, opt } const std = @import("std"); -const Api = @import("../api/schema.zig").Api; const bun = @import("bun"); const picohttp = bun.picohttp; +const api = bun.schema.api; const Blob = bun.webcore.Blob; const FetchHeaders = bun.webcore.FetchHeaders; diff --git a/src/http/Method.zig b/src/http/Method.zig index 54aca28045..f7435a9053 100644 --- a/src/http/Method.zig +++ b/src/http/Method.zig @@ -145,11 +145,11 @@ pub const Method = enum(u8) { return Map.get(str); } - extern "c" fn Bun__HTTPMethod__toJS(method: Method, globalObject: *JSC.JSGlobalObject) JSC.JSValue; + extern "c" fn Bun__HTTPMethod__toJS(method: Method, globalObject: *jsc.JSGlobalObject) jsc.JSValue; pub const toJS = Bun__HTTPMethod__toJS; - const JSC = bun.JSC; + const jsc = bun.jsc; pub const Optional = union(enum) { any: void, diff --git a/src/http/MimeType.zig b/src/http/MimeType.zig index c1090b7e7c..1b6a45cc91 100644 --- a/src/http/MimeType.zig +++ b/src/http/MimeType.zig @@ -1624,10 +1624,11 @@ pub fn sniff(bytes: []const u8) ?MimeType { return null; } +const string = []const u8; + const std = @import("std"); const Loader = @import("../options.zig").Loader; const bun = @import("bun"); const ComptimeStringMap = bun.ComptimeStringMap; -const string = bun.string; const strings = bun.strings; diff --git a/src/http/ProxyTunnel.zig b/src/http/ProxyTunnel.zig index a66b87c1b7..0f64ad5642 100644 --- a/src/http/ProxyTunnel.zig +++ b/src/http/ProxyTunnel.zig @@ -226,7 +226,7 @@ fn onClose(this: *HTTPClient) void { } } -pub fn start(this: *HTTPClient, comptime is_ssl: bool, socket: NewHTTPContext(is_ssl).HTTPSocket, ssl_options: JSC.API.ServerConfig.SSLConfig, start_payload: []const u8) void { +pub fn start(this: *HTTPClient, comptime is_ssl: bool, socket: NewHTTPContext(is_ssl).HTTPSocket, ssl_options: jsc.API.ServerConfig.SSLConfig, start_payload: []const u8) void { const proxy_tunnel = bun.new(ProxyTunnel, .{ .ref_count = .init(), }); @@ -340,7 +340,7 @@ const HTTPCertError = @import("./HTTPCertError.zig"); const SSLWrapper = @import("../bun.js/api/bun/ssl_wrapper.zig").SSLWrapper; const bun = @import("bun"); -const JSC = bun.JSC; +const jsc = bun.jsc; const strings = bun.strings; const uws = bun.uws; const BoringSSL = bun.BoringSSL.c; diff --git a/src/http/URLPath.zig b/src/http/URLPath.zig index 70d565f890..b259af1a03 100644 --- a/src/http/URLPath.zig +++ b/src/http/URLPath.zig @@ -141,9 +141,10 @@ pub fn parse(possibly_encoded_pathname_: string) !URLPath { }; } +const string = []const u8; + const std = @import("std"); const PercentEncoding = @import("../url.zig").PercentEncoding; const bun = @import("bun"); -const string = bun.string; const strings = bun.strings; diff --git a/src/http/websocket_client.zig b/src/http/websocket_client.zig index aa53a1d69e..4d681d9ee7 100644 --- a/src/http/websocket_client.zig +++ b/src/http/websocket_client.zig @@ -36,7 +36,7 @@ pub fn NewWebSocketClient(comptime ssl: bool) type { send_buffer: bun.LinearFifo(u8, .Dynamic), - globalThis: *JSC.JSGlobalObject, + globalThis: *jsc.JSGlobalObject, poll_ref: Async.KeepAlive = Async.KeepAlive.init(), header_fragment: ?u8 = null, @@ -45,7 +45,7 @@ pub fn NewWebSocketClient(comptime ssl: bool) type { payload_length_frame_len: u8 = 0, initial_data_handler: ?*InitialDataHandler = null, - event_loop: *JSC.EventLoop = undefined, + event_loop: *jsc.EventLoop = undefined, deflate: ?*WebSocketDeflate = null, // Track if current message is compressed @@ -74,7 +74,7 @@ pub fn NewWebSocketClient(comptime ssl: bool) type { return true; } - pub fn register(global: *JSC.JSGlobalObject, loop_: *anyopaque, ctx_: *anyopaque) callconv(.C) void { + pub fn register(global: *jsc.JSGlobalObject, loop_: *anyopaque, ctx_: *anyopaque) callconv(.C) void { const vm = global.bunVM(); const loop = @as(*uws.Loop, @ptrCast(@alignCast(loop_))); @@ -130,7 +130,7 @@ pub fn NewWebSocketClient(comptime ssl: bool) type { } pub fn fail(this: *WebSocket, code: ErrorCode) void { - JSC.markBinding(@src()); + jsc.markBinding(@src()); if (this.outgoing_websocket) |ws| { this.outgoing_websocket = null; log("fail ({s})", .{@tagName(code)}); @@ -142,7 +142,7 @@ pub fn NewWebSocketClient(comptime ssl: bool) type { } pub fn handleHandshake(this: *WebSocket, socket: Socket, success: i32, ssl_error: uws.us_bun_verify_error_t) void { - JSC.markBinding(@src()); + jsc.markBinding(@src()); const authorized = if (success == 1) true else false; @@ -182,7 +182,7 @@ pub fn NewWebSocketClient(comptime ssl: bool) type { } pub fn handleClose(this: *WebSocket, _: Socket, _: c_int, _: ?*anyopaque) void { log("onClose", .{}); - JSC.markBinding(@src()); + jsc.markBinding(@src()); this.clearData(); this.tcp.detach(); @@ -257,20 +257,20 @@ pub fn NewWebSocketClient(comptime ssl: bool) type { this.terminate(ErrorCode.invalid_utf8); return; }; - var outstring = JSC.ZigString.Empty; + var outstring = jsc.ZigString.Empty; if (utf16_bytes_) |utf16| { - outstring = JSC.ZigString.from16Slice(utf16); + outstring = jsc.ZigString.from16Slice(utf16); outstring.mark(); - JSC.markBinding(@src()); + jsc.markBinding(@src()); out.didReceiveText(false, &outstring); } else { - outstring = JSC.ZigString.init(data_); - JSC.markBinding(@src()); + outstring = jsc.ZigString.init(data_); + jsc.markBinding(@src()); out.didReceiveText(true, &outstring); } }, .Binary, .Ping, .Pong => { - JSC.markBinding(@src()); + jsc.markBinding(@src()); out.didReceiveBytes(data_.ptr, data_.len, @as(u8, @intFromEnum(kind))); }, else => { @@ -986,7 +986,7 @@ pub fn NewWebSocketClient(comptime ssl: bool) type { pub fn writeString( this: *WebSocket, - str_: *const JSC.ZigString, + str_: *const jsc.ZigString, op: u8, ) callconv(.C) void { const str = str_.*; @@ -1037,7 +1037,7 @@ pub fn NewWebSocketClient(comptime ssl: bool) type { fn dispatchAbruptClose(this: *WebSocket, code: ErrorCode) void { var out = this.outgoing_websocket orelse return; this.poll_ref.unref(this.globalThis.bunVM()); - JSC.markBinding(@src()); + jsc.markBinding(@src()); this.outgoing_websocket = null; out.didAbruptClose(code); this.deref(); @@ -1046,13 +1046,13 @@ pub fn NewWebSocketClient(comptime ssl: bool) type { fn dispatchClose(this: *WebSocket, code: u16, reason: *bun.String) void { var out = this.outgoing_websocket orelse return; this.poll_ref.unref(this.globalThis.bunVM()); - JSC.markBinding(@src()); + jsc.markBinding(@src()); this.outgoing_websocket = null; out.didClose(code, reason); this.deref(); } - pub fn close(this: *WebSocket, code: u16, reason: ?*const JSC.ZigString) callconv(.C) void { + pub fn close(this: *WebSocket, code: u16, reason: ?*const jsc.ZigString) callconv(.C) void { if (!this.hasTCP()) return; const tcp = this.tcp; @@ -1075,7 +1075,7 @@ pub fn NewWebSocketClient(comptime ssl: bool) type { ws: *CppWebSocket, slice: []u8, - pub const Handle = JSC.AnyTask.New(@This(), handle); + pub const Handle = jsc.AnyTask.New(@This(), handle); pub const new = bun.TrivialNew(@This()); @@ -1106,7 +1106,7 @@ pub fn NewWebSocketClient(comptime ssl: bool) type { outgoing: *CppWebSocket, input_socket: *anyopaque, socket_ctx: *anyopaque, - globalThis: *JSC.JSGlobalObject, + globalThis: *jsc.JSGlobalObject, buffered_data: [*]u8, buffered_data_len: usize, deflate_params: ?*const WebSocketDeflate.Params, @@ -1258,7 +1258,7 @@ pub const ErrorCode = enum(i32) { }; pub const Mask = struct { - pub fn fill(globalThis: *JSC.JSGlobalObject, mask_buf: *[4]u8, output_: []u8, input_: []const u8) void { + pub fn fill(globalThis: *jsc.JSGlobalObject, mask_buf: *[4]u8, output_: []u8, input_: []const u8) void { mask_buf.* = globalThis.bunVM().rareData().entropySlice(4)[0..4].*; const mask = mask_buf.*; @@ -1405,7 +1405,7 @@ const Copy = union(enum) { } } - pub fn copy(this: @This(), globalThis: *JSC.JSGlobalObject, buf: []u8, content_byte_len: usize, opcode: Opcode) void { + pub fn copy(this: @This(), globalThis: *jsc.JSGlobalObject, buf: []u8, content_byte_len: usize, opcode: Opcode) void { if (this == .raw) { bun.assert(buf.len >= this.raw.len); bun.assert(buf.ptr != this.raw.ptr); @@ -1474,7 +1474,7 @@ const Copy = union(enum) { } } - pub fn copyCompressed(globalThis: *JSC.JSGlobalObject, buf: []u8, compressed_data: []const u8, opcode: Opcode, is_first_fragment: bool) void { + pub fn copyCompressed(globalThis: *jsc.JSGlobalObject, buf: []u8, compressed_data: []const u8, opcode: Opcode, is_first_fragment: bool) void { const content_byte_len = compressed_data.len; const how_big_is_the_length_integer = WebsocketHeader.lengthByteCount(content_byte_len); const how_big_is_the_mask = 4; @@ -1513,6 +1513,8 @@ const Copy = union(enum) { const log = Output.scoped(.WebSocketClient, false); +const string = []const u8; + const WebSocketDeflate = @import("./websocket_client/WebSocketDeflate.zig"); const std = @import("std"); const CppWebSocket = @import("./websocket_client/CppWebSocket.zig").CppWebSocket; @@ -1524,9 +1526,8 @@ const bun = @import("bun"); const Async = bun.Async; const BoringSSL = bun.BoringSSL; const Environment = bun.Environment; -const JSC = bun.JSC; const Output = bun.Output; const default_allocator = bun.default_allocator; -const string = bun.string; +const jsc = bun.jsc; const strings = bun.strings; const uws = bun.uws; diff --git a/src/http/websocket_client/CppWebSocket.zig b/src/http/websocket_client/CppWebSocket.zig index 90beccdfa9..a76e0c23f4 100644 --- a/src/http/websocket_client/CppWebSocket.zig +++ b/src/http/websocket_client/CppWebSocket.zig @@ -17,41 +17,41 @@ pub const CppWebSocket = opaque { ) void; extern fn WebSocket__didAbruptClose(websocket_context: *CppWebSocket, reason: ErrorCode) void; extern fn WebSocket__didClose(websocket_context: *CppWebSocket, code: u16, reason: *const bun.String) void; - extern fn WebSocket__didReceiveText(websocket_context: *CppWebSocket, clone: bool, text: *const JSC.ZigString) void; + extern fn WebSocket__didReceiveText(websocket_context: *CppWebSocket, clone: bool, text: *const jsc.ZigString) void; extern fn WebSocket__didReceiveBytes(websocket_context: *CppWebSocket, bytes: [*]const u8, byte_len: usize, opcode: u8) void; extern fn WebSocket__rejectUnauthorized(websocket_context: *CppWebSocket) bool; pub fn didAbruptClose(this: *CppWebSocket, reason: ErrorCode) void { - const loop = JSC.VirtualMachine.get().eventLoop(); + const loop = jsc.VirtualMachine.get().eventLoop(); loop.enter(); defer loop.exit(); WebSocket__didAbruptClose(this, reason); } pub fn didClose(this: *CppWebSocket, code: u16, reason: *bun.String) void { - const loop = JSC.VirtualMachine.get().eventLoop(); + const loop = jsc.VirtualMachine.get().eventLoop(); loop.enter(); defer loop.exit(); WebSocket__didClose(this, code, reason); } - pub fn didReceiveText(this: *CppWebSocket, clone: bool, text: *const JSC.ZigString) void { - const loop = JSC.VirtualMachine.get().eventLoop(); + pub fn didReceiveText(this: *CppWebSocket, clone: bool, text: *const jsc.ZigString) void { + const loop = jsc.VirtualMachine.get().eventLoop(); loop.enter(); defer loop.exit(); WebSocket__didReceiveText(this, clone, text); } pub fn didReceiveBytes(this: *CppWebSocket, bytes: [*]const u8, byte_len: usize, opcode: u8) void { - const loop = JSC.VirtualMachine.get().eventLoop(); + const loop = jsc.VirtualMachine.get().eventLoop(); loop.enter(); defer loop.exit(); WebSocket__didReceiveBytes(this, bytes, byte_len, opcode); } pub fn rejectUnauthorized(this: *CppWebSocket) bool { - const loop = JSC.VirtualMachine.get().eventLoop(); + const loop = jsc.VirtualMachine.get().eventLoop(); loop.enter(); defer loop.exit(); return WebSocket__rejectUnauthorized(this); } pub fn didConnect(this: *CppWebSocket, socket: *uws.Socket, buffered_data: ?[*]u8, buffered_len: usize, deflate_params: ?*const WebSocketDeflate.Params) void { - const loop = JSC.VirtualMachine.get().eventLoop(); + const loop = jsc.VirtualMachine.get().eventLoop(); loop.enter(); defer loop.exit(); WebSocket__didConnect(this, socket, buffered_data, buffered_len, deflate_params); @@ -59,12 +59,12 @@ pub const CppWebSocket = opaque { extern fn WebSocket__incrementPendingActivity(websocket_context: *CppWebSocket) void; extern fn WebSocket__decrementPendingActivity(websocket_context: *CppWebSocket) void; pub fn ref(this: *CppWebSocket) void { - JSC.markBinding(@src()); + jsc.markBinding(@src()); WebSocket__incrementPendingActivity(this); } pub fn unref(this: *CppWebSocket) void { - JSC.markBinding(@src()); + jsc.markBinding(@src()); WebSocket__decrementPendingActivity(this); } }; @@ -73,5 +73,5 @@ const WebSocketDeflate = @import("./WebSocketDeflate.zig"); const ErrorCode = @import("../websocket_client.zig").ErrorCode; const bun = @import("bun"); -const JSC = bun.JSC; +const jsc = bun.jsc; const uws = bun.uws; diff --git a/src/http/websocket_client/WebSocketDeflate.zig b/src/http/websocket_client/WebSocketDeflate.zig index 1efd4aeae4..6521669279 100644 --- a/src/http/websocket_client/WebSocketDeflate.zig +++ b/src/http/websocket_client/WebSocketDeflate.zig @@ -79,7 +79,7 @@ const COMPRESSION_BUFFER_SIZE = 4096; // DEFLATE trailer bytes added by Z_SYNC_FLUSH const DEFLATE_TRAILER = [_]u8{ 0x00, 0x00, 0xff, 0xff }; -pub fn init(allocator: std.mem.Allocator, params: Params, rare_data: *JSC.RareData) !*PerMessageDeflate { +pub fn init(allocator: std.mem.Allocator, params: Params, rare_data: *jsc.RareData) !*PerMessageDeflate { const self = try allocator.create(PerMessageDeflate); self.* = .{ .allocator = allocator, @@ -219,6 +219,6 @@ pub fn compress(self: *PerMessageDeflate, in_buf: []const u8, out: *std.ArrayLis const std = @import("std"); const bun = @import("bun"); -const JSC = bun.JSC; +const jsc = bun.jsc; const libdeflate = bun.libdeflate; const zlib = bun.zlib; diff --git a/src/http/websocket_client/WebSocketUpgradeClient.zig b/src/http/websocket_client/WebSocketUpgradeClient.zig index 57bbd2a9f2..b02c51ecef 100644 --- a/src/http/websocket_client/WebSocketUpgradeClient.zig +++ b/src/http/websocket_client/WebSocketUpgradeClient.zig @@ -47,7 +47,7 @@ pub fn NewHTTPUpgradeClient(comptime ssl: bool) type { const State = enum { initializing, reading, failed }; const HTTPClient = @This(); - pub fn register(_: *JSC.JSGlobalObject, _: *anyopaque, ctx: *uws.SocketContext) callconv(.C) void { + pub fn register(_: *jsc.JSGlobalObject, _: *anyopaque, ctx: *uws.SocketContext) callconv(.C) void { Socket.configure( ctx, true, @@ -75,15 +75,15 @@ pub fn NewHTTPUpgradeClient(comptime ssl: bool) type { /// On error, this returns null. /// Returning null signals to the parent function that the connection failed. pub fn connect( - global: *JSC.JSGlobalObject, + global: *jsc.JSGlobalObject, socket_ctx: *anyopaque, websocket: *CppWebSocket, - host: *const JSC.ZigString, + host: *const jsc.ZigString, port: u16, - pathname: *const JSC.ZigString, - client_protocol: *const JSC.ZigString, - header_names: ?[*]const JSC.ZigString, - header_values: ?[*]const JSC.ZigString, + pathname: *const jsc.ZigString, + client_protocol: *const jsc.ZigString, + header_names: ?[*]const jsc.ZigString, + header_values: ?[*]const jsc.ZigString, header_count: usize, ) callconv(.C) ?*HTTPClient { const vm = global.bunVM(); @@ -135,7 +135,7 @@ pub fn NewHTTPUpgradeClient(comptime ssl: bool) type { client.deref(); return null; } - bun.Analytics.Features.WebSocket += 1; + bun.analytics.Features.WebSocket += 1; if (comptime ssl) { if (!strings.isIPAddress(host_.slice())) { @@ -160,7 +160,7 @@ pub fn NewHTTPUpgradeClient(comptime ssl: bool) type { this.input_body_buf.len = 0; } pub fn clearData(this: *HTTPClient) void { - this.poll_ref.unref(JSC.VirtualMachine.get()); + this.poll_ref.unref(jsc.VirtualMachine.get()); this.clearInput(); this.body.clearAndFree(bun.default_allocator); @@ -189,7 +189,7 @@ pub fn NewHTTPUpgradeClient(comptime ssl: bool) type { pub fn fail(this: *HTTPClient, code: ErrorCode) void { log("onFail: {s}", .{@tagName(code)}); - JSC.markBinding(@src()); + jsc.markBinding(@src()); this.ref(); defer this.deref(); @@ -213,7 +213,7 @@ pub fn NewHTTPUpgradeClient(comptime ssl: bool) type { pub fn handleClose(this: *HTTPClient, _: Socket, _: c_int, _: ?*anyopaque) void { log("onClose", .{}); - JSC.markBinding(@src()); + jsc.markBinding(@src()); this.clearData(); this.tcp.detach(); this.dispatchAbruptClose(ErrorCode.ended); @@ -497,7 +497,7 @@ pub fn NewHTTPUpgradeClient(comptime ssl: bool) type { } this.clearData(); - JSC.markBinding(@src()); + jsc.markBinding(@src()); if (!this.tcp.isClosed() and this.outgoing_websocket != null) { this.tcp.timeout(0); log("onDidConnect", .{}); @@ -589,8 +589,8 @@ pub fn NewHTTPUpgradeClient(comptime ssl: bool) type { } const NonUTF8Headers = struct { - names: []const JSC.ZigString, - values: []const JSC.ZigString, + names: []const jsc.ZigString, + values: []const jsc.ZigString, pub fn format(self: NonUTF8Headers, comptime _: []const u8, _: std.fmt.FormatOptions, writer: anytype) !void { const count = self.names.len; @@ -600,11 +600,11 @@ const NonUTF8Headers = struct { } } - pub fn init(names: ?[*]const JSC.ZigString, values: ?[*]const JSC.ZigString, len: usize) NonUTF8Headers { + pub fn init(names: ?[*]const jsc.ZigString, values: ?[*]const jsc.ZigString, len: usize) NonUTF8Headers { if (len == 0) { return .{ - .names = &[_]JSC.ZigString{}, - .values = &[_]JSC.ZigString{}, + .names = &[_]jsc.ZigString{}, + .values = &[_]jsc.ZigString{}, }; } @@ -616,12 +616,12 @@ const NonUTF8Headers = struct { }; fn buildRequestBody( - vm: *JSC.VirtualMachine, - pathname: *const JSC.ZigString, + vm: *jsc.VirtualMachine, + pathname: *const jsc.ZigString, is_https: bool, - host: *const JSC.ZigString, + host: *const jsc.ZigString, port: u16, - client_protocol: *const JSC.ZigString, + client_protocol: *const jsc.ZigString, client_protocol_hash: *u64, extra_headers: NonUTF8Headers, ) std.mem.Allocator.Error![]u8 { @@ -688,9 +688,9 @@ const bun = @import("bun"); const Async = bun.Async; const BoringSSL = bun.BoringSSL; const Environment = bun.Environment; -const JSC = bun.JSC; const Output = bun.Output; const PicoHTTP = bun.picohttp; const default_allocator = bun.default_allocator; +const jsc = bun.jsc; const strings = bun.strings; const uws = bun.uws; diff --git a/src/import_record.zig b/src/import_record.zig index 7d7465882c..122c709d41 100644 --- a/src/import_record.zig +++ b/src/import_record.zig @@ -83,16 +83,16 @@ pub const ImportKind = enum(u8) { return k == .at_conditional or k == .at or k == .url or k == .composes; } - pub fn toAPI(k: ImportKind) Api.ImportKind { + pub fn toAPI(k: ImportKind) api.ImportKind { return switch (k) { - ImportKind.entry_point => Api.ImportKind.entry_point, - ImportKind.stmt => Api.ImportKind.stmt, - ImportKind.require => Api.ImportKind.require, - ImportKind.dynamic => Api.ImportKind.dynamic, - ImportKind.require_resolve => Api.ImportKind.require_resolve, - ImportKind.at => Api.ImportKind.at, - ImportKind.url => Api.ImportKind.url, - else => Api.ImportKind.internal, + ImportKind.entry_point => api.ImportKind.entry_point, + ImportKind.stmt => api.ImportKind.stmt, + ImportKind.require => api.ImportKind.require, + ImportKind.dynamic => api.ImportKind.dynamic, + ImportKind.require_resolve => api.ImportKind.require_resolve, + ImportKind.at => api.ImportKind.at, + ImportKind.url => api.ImportKind.url, + else => api.ImportKind.internal, }; } }; @@ -106,7 +106,7 @@ pub const ImportRecord = struct { tag: Tag = .none, loader: ?bun.options.Loader = null, - source_index: bun.JSAst.Index = .invalid, + source_index: bun.ast.Index = .invalid, /// True for the following cases: /// @@ -206,9 +206,9 @@ pub const ImportRecord = struct { }; const std = @import("std"); -const Api = @import("./api/schema.zig").Api; -const Index = @import("./ast/base.zig").Index; const bun = @import("bun"); const fs = bun.fs; const logger = bun.logger; +const Index = bun.ast.Index; +const api = bun.schema.api; diff --git a/src/ini.zig b/src/ini.zig index d0d37bfc54..50082703d0 100644 --- a/src/ini.zig +++ b/src/ini.zig @@ -226,7 +226,7 @@ pub const Parser = struct { var log = bun.logger.Log.init(arena_allocator); defer log.deinit(); // Try to parse it and it if fails will just treat it as a string - const json_val: Expr = bun.JSON.parseUTF8Impl(&src, &log, arena_allocator, true) catch { + const json_val: Expr = bun.json.parseUTF8Impl(&src, &log, arena_allocator, true) catch { break :out; }; @@ -494,9 +494,9 @@ pub const Parser = struct { /// Used in JS tests, see `internal-for-testing.ts` and shell tests. pub const IniTestingAPIs = struct { - const JSC = bun.JSC; + const jsc = bun.jsc; - pub fn loadNpmrcFromJS(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { + pub fn loadNpmrcFromJS(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const arg = callframe.argument(0); const npmrc_contents = try arg.toBunString(globalThis); defer npmrc_contents.deref(); @@ -515,7 +515,7 @@ pub const IniTestingAPIs = struct { const env = if (envjs.isEmptyOrUndefinedOrNull()) globalThis.bunVM().transpiler.env else brk: { var envmap = bun.DotEnv.Map.HashTable.init(allocator); const envobj = envjs.getObject() orelse return globalThis.throwTypeError("env must be an object", .{}); - var object_iter = try JSC.JSPropertyIterator(.{ + var object_iter = try jsc.JSPropertyIterator(.{ .skip_empty_name = false, .include_value = true, }).init(globalThis, envobj); @@ -548,8 +548,8 @@ pub const IniTestingAPIs = struct { break :brk envstable; }; - const install = try allocator.create(bun.Schema.Api.BunInstall); - install.* = std.mem.zeroes(bun.Schema.Api.BunInstall); + const install = try allocator.create(bun.schema.api.BunInstall); + install.* = std.mem.zeroes(bun.schema.api.BunInstall); var configs = std.ArrayList(ConfigIterator.Item).init(allocator); defer configs.deinit(); loadNpmrc(allocator, install, env, ".npmrc", &log, source, &configs) catch { @@ -578,7 +578,7 @@ pub const IniTestingAPIs = struct { default_registry_password.deref(); } - return (try JSC.JSObject.create(.{ + return (try jsc.JSObject.create(.{ .default_registry_url = default_registry_url, .default_registry_token = default_registry_token, .default_registry_username = default_registry_username, @@ -586,7 +586,7 @@ pub const IniTestingAPIs = struct { }, globalThis)).toJS(); } - pub fn parse(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { + pub fn parse(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const arguments_ = callframe.arguments_old(1); const arguments = arguments_.slice(); @@ -811,7 +811,7 @@ pub const ScopeIterator = struct { no_value, }; - const Item = struct { scope: []const u8, registry: bun.Schema.Api.NpmRegistry }; + const Item = struct { scope: []const u8, registry: bun.schema.api.NpmRegistry }; pub fn next(this: *ScopeIterator) OOM!?Option(Item) { if (this.prop_idx >= this.config.properties.len) return null; @@ -829,7 +829,7 @@ pub const ScopeIterator = struct { .registry = brk: { if (prop.value) |value| { if (value.asUtf8StringLiteral()) |str| { - var parser = bun.Schema.Api.NpmRegistry.Parser{ + var parser = bun.schema.api.NpmRegistry.Parser{ .log = this.log, .source = this.source, .allocator = this.allocator, @@ -852,7 +852,7 @@ pub const ScopeIterator = struct { pub fn loadNpmrcConfig( allocator: std.mem.Allocator, - install: *bun.Schema.Api.BunInstall, + install: *bun.schema.api.BunInstall, env: *bun.DotEnv.Loader, auto_loaded: bool, npmrc_paths: []const [:0]const u8, @@ -897,7 +897,7 @@ pub fn loadNpmrcConfig( pub fn loadNpmrc( allocator: std.mem.Allocator, - install: *bun.Schema.Api.BunInstall, + install: *bun.schema.api.BunInstall, env: *bun.DotEnv.Loader, npmrc_path: [:0]const u8, log: *bun.logger.Log, @@ -915,7 +915,7 @@ pub fn loadNpmrc( if (out.asProperty("registry")) |query| { if (query.expr.asUtf8StringLiteral()) |str| { - var p = bun.Schema.Api.NpmRegistry.Parser{ + var p = bun.schema.api.NpmRegistry.Parser{ .allocator = allocator, .log = log, .source = source, @@ -1069,7 +1069,7 @@ pub fn loadNpmrc( } } - var registry_map = install.scoped orelse bun.Schema.Api.NpmRegistryMap{}; + var registry_map = install.scoped orelse bun.schema.api.NpmRegistryMap{}; // Process scopes { @@ -1205,9 +1205,9 @@ pub fn loadNpmrc( if (std.mem.eql(u8, bun.strings.withoutTrailingSlash(default_registry_url.host), bun.strings.withoutTrailingSlash(conf_item_url.host))) { // Apply config to default registry - const v: *bun.Schema.Api.NpmRegistry = brk: { + const v: *bun.schema.api.NpmRegistry = brk: { if (install.default_registry) |*r| break :brk r; - install.default_registry = bun.Schema.Api.NpmRegistry{ + install.default_registry = bun.schema.api.NpmRegistry{ .password = "", .token = "", .username = "", @@ -1268,7 +1268,7 @@ pub fn loadNpmrc( fn @"handle _auth"( allocator: Allocator, - v: *bun.Schema.Api.NpmRegistry, + v: *bun.schema.api.NpmRegistry, conf_item: *const ConfigIterator.Item, log: *bun.logger.Log, source: *const bun.logger.Source, @@ -1341,7 +1341,7 @@ const Output = bun.Output; const Loc = bun.logger.Loc; const Registry = bun.install.Npm.Registry; -const js_ast = bun.JSAst; -const E = bun.JSAst.E; -const Expr = bun.JSAst.Expr; +const js_ast = bun.ast; +const E = bun.ast.E; +const Expr = bun.ast.Expr; const Rope = js_ast.E.Object.Rope; diff --git a/src/install/NetworkTask.zig b/src/install/NetworkTask.zig index 7762f48e05..fc0f989fd6 100644 --- a/src/install/NetworkTask.zig +++ b/src/install/NetworkTask.zig @@ -92,7 +92,7 @@ pub fn forManifest( encoded_name = try std.mem.replaceOwned(u8, stack_fallback_allocator.get(), name, "/", "%2f"); } - const tmp = bun.JSC.URL.join( + const tmp = bun.jsc.URL.join( bun.String.borrowUTF8(scope.url.href), bun.String.borrowUTF8(encoded_name), ); @@ -301,6 +301,8 @@ pub fn forTarball( } } +const string = []const u8; + const std = @import("std"); const install = @import("./install.zig"); @@ -319,7 +321,6 @@ const OOM = bun.OOM; const ThreadPool = bun.ThreadPool; const URL = bun.URL; const logger = bun.logger; -const string = bun.string; const strings = bun.strings; const Fs = bun.fs; diff --git a/src/install/PackageInstall.zig b/src/install/PackageInstall.zig index 9f50841aa2..fe650508d6 100644 --- a/src/install/PackageInstall.zig +++ b/src/install/PackageInstall.zig @@ -496,7 +496,7 @@ pub const PackageInstall = struct { } }; - threadlocal var node_fs_for_package_installer: bun.JSC.Node.fs.NodeFS = .{}; + threadlocal var node_fs_for_package_installer: bun.jsc.Node.fs.NodeFS = .{}; fn initInstallDir(this: *@This(), state: *InstallDirState, destination_dir: std.fs.Dir, method: Method) Result { const destbase = destination_dir; @@ -740,7 +740,7 @@ pub const PackageInstall = struct { src: [:0]bun.OSPathChar, dest: [:0]bun.OSPathChar, basename: u16, - task: bun.JSC.WorkPoolTask = .{ .callback = &runFromThreadPool }, + task: bun.jsc.WorkPoolTask = .{ .callback = &runFromThreadPool }, err: ?anyerror = null, pub const Queue = NewTaskQueue(@This()); @@ -776,7 +776,7 @@ pub const PackageInstall = struct { }); } - pub fn runFromThreadPool(task: *bun.JSC.WorkPoolTask) void { + pub fn runFromThreadPool(task: *bun.jsc.WorkPoolTask) void { var iter: *@This() = @fieldParentPtr("task", task); defer queue.completeOne(); if (iter.run()) |err| { @@ -1137,9 +1137,9 @@ pub const PackageInstall = struct { pub const new = bun.TrivialNew(@This()); absolute_path: []const u8, - task: JSC.WorkPoolTask = .{ .callback = &run }, + task: jsc.WorkPoolTask = .{ .callback = &run }, - pub fn run(task: *JSC.WorkPoolTask) void { + pub fn run(task: *jsc.WorkPoolTask) void { var unintall_task: *@This() = @fieldParentPtr("task", task); var debug_timer = bun.Output.DebugTimer.start(); defer { @@ -1465,23 +1465,24 @@ pub const PackageInstall = struct { } }; +const string = []const u8; +const stringZ = [:0]const u8; + const Walker = @import("../walker_skippable.zig"); const std = @import("std"); const bun = @import("bun"); const Environment = bun.Environment; const Global = bun.Global; -const JSC = bun.JSC; -const JSON = bun.JSON; +const JSON = bun.json; const MutableString = bun.MutableString; const Output = bun.Output; const Path = bun.path; const Progress = bun.Progress; const Syscall = bun.sys; const ThreadPool = bun.ThreadPool; +const jsc = bun.jsc; const logger = bun.logger; -const string = bun.string; -const stringZ = bun.stringZ; const strings = bun.strings; const Bitset = bun.bit_set.DynamicBitSetUnmanaged; const FileSystem = bun.fs.FileSystem; diff --git a/src/install/PackageInstaller.zig b/src/install/PackageInstaller.zig index c7f78ff46d..d597881756 100644 --- a/src/install/PackageInstaller.zig +++ b/src/install/PackageInstaller.zig @@ -1395,6 +1395,8 @@ pub const PackageInstaller = struct { } }; +const string = []const u8; + const std = @import("std"); const bun = @import("bun"); @@ -1405,10 +1407,9 @@ const Output = bun.Output; const Path = bun.path; const Progress = bun.Progress; const Syscall = bun.sys; -const string = bun.string; const strings = bun.strings; const Bitset = bun.bit_set.DynamicBitSetUnmanaged; -const Command = bun.CLI.Command; +const Command = bun.cli.Command; const FileSystem = bun.fs.FileSystem; const String = bun.Semver.String; diff --git a/src/install/PackageManager.zig b/src/install/PackageManager.zig index 0972d32706..fb7b0941a7 100644 --- a/src/install/PackageManager.zig +++ b/src/install/PackageManager.zig @@ -104,7 +104,7 @@ peer_dependencies: std.fifo.LinearFifo(DependencyID, .Dynamic) = std.fifo.Linear // name hash from alias package name -> aliased package dependency version info known_npm_aliases: NpmAliasMap = .{}, -event_loop: JSC.AnyEventLoop, +event_loop: jsc.AnyEventLoop, // During `installPackages` we learn exactly what dependencies from --trust // actually have scripts to run, and we add them to this list @@ -862,7 +862,7 @@ pub fn init( .root_package_json_file = root_package_json_file, // .progress .event_loop = .{ - .mini = JSC.MiniEventLoop.init(bun.default_allocator), + .mini = jsc.MiniEventLoop.init(bun.default_allocator), }, .original_package_json_path = original_package_json_path, .workspace_package_json_cache = workspace_package_json_cache, @@ -870,9 +870,9 @@ pub fn init( .subcommand = subcommand, .root_package_json_name_at_time_of_init = root_package_json_name_at_time_of_init, }; - manager.event_loop.loop().internal_loop_data.setParentEventLoop(bun.JSC.EventLoopHandle.init(&manager.event_loop)); + manager.event_loop.loop().internal_loop_data.setParentEventLoop(bun.jsc.EventLoopHandle.init(&manager.event_loop)); manager.lockfile = try ctx.allocator.create(Lockfile); - JSC.MiniEventLoop.global = &manager.event_loop.mini; + jsc.MiniEventLoop.global = &manager.event_loop.mini; if (!manager.options.enable.cache) { manager.options.enable.manifest_cache = false; manager.options.enable.manifest_cache_control = false; @@ -1031,7 +1031,7 @@ pub fn initWithRuntimeOnce( .lockfile = undefined, .root_package_json_file = undefined, .event_loop = .{ - .js = JSC.VirtualMachine.get().eventLoop(), + .js = jsc.VirtualMachine.get().eventLoop(), }, .original_package_json_path = original_package_json_path[0..original_package_json_path.len :0], .subcommand = .install, @@ -1240,6 +1240,9 @@ pub const scheduleTasks = @import("./PackageManager/runTasks.zig").scheduleTasks pub const updatePackageJSONAndInstallCatchError = @import("./PackageManager/updatePackageJSONAndInstall.zig").updatePackageJSONAndInstallCatchError; pub const updatePackageJSONAndInstallWithManager = @import("./PackageManager/updatePackageJSONAndInstall.zig").updatePackageJSONAndInstallWithManager; +const string = []const u8; +const stringZ = [:0]const u8; + const DirInfo = @import("../resolver/dir_info.zig"); const resolution = @import("./PackageManager/PackageManagerResolution.zig"); const std = @import("std"); @@ -1252,8 +1255,7 @@ const bun = @import("bun"); const DotEnv = bun.DotEnv; const Environment = bun.Environment; const Global = bun.Global; -const JSC = bun.JSC; -const JSON = bun.JSON; +const JSON = bun.json; const OOM = bun.OOM; const Output = bun.Output; const Path = bun.path; @@ -1262,20 +1264,19 @@ const RunCommand = bun.RunCommand; const ThreadPool = bun.ThreadPool; const URL = bun.URL; const default_allocator = bun.default_allocator; +const jsc = bun.jsc; const logger = bun.logger; -const string = bun.string; -const stringZ = bun.stringZ; const strings = bun.strings; const transpiler = bun.transpiler; -const Api = bun.Schema.Api; +const Api = bun.schema.api; const File = bun.sys.File; -const BunArguments = bun.CLI.Arguments; -const Command = bun.CLI.Command; - const Semver = bun.Semver; const String = Semver.String; +const BunArguments = bun.cli.Arguments; +const Command = bun.cli.Command; + const Fs = bun.fs; const FileSystem = Fs.FileSystem; diff --git a/src/install/PackageManager/CommandLineArguments.zig b/src/install/PackageManager/CommandLineArguments.zig index 04aae8a703..84ed4f8d10 100644 --- a/src/install/PackageManager/CommandLineArguments.zig +++ b/src/install/PackageManager/CommandLineArguments.zig @@ -982,6 +982,8 @@ pub fn parse(allocator: std.mem.Allocator, comptime subcommand: Subcommand) !Com return cli; } +const string = []const u8; + const Options = @import("./PackageManagerOptions.zig"); const std = @import("std"); const PackageManagerCommand = @import("../../cli/package_manager_command.zig").PackageManagerCommand; @@ -989,12 +991,11 @@ const PackageManagerCommand = @import("../../cli/package_manager_command.zig").P const bun = @import("bun"); const Environment = bun.Environment; const Global = bun.Global; -const JSON = bun.JSON; +const JSON = bun.json; const Output = bun.Output; const Path = bun.path; const URL = bun.URL; const clap = bun.clap; -const string = bun.string; const strings = bun.strings; const PackageInstall = bun.install.PackageInstall; const Subcommand = bun.install.PackageManager.Subcommand; diff --git a/src/install/PackageManager/PackageJSONEditor.zig b/src/install/PackageManager/PackageJSONEditor.zig index 7526ed3a2f..67eae120ce 100644 --- a/src/install/PackageManager/PackageJSONEditor.zig +++ b/src/install/PackageManager/PackageJSONEditor.zig @@ -781,7 +781,7 @@ const Semver = bun.Semver; const logger = bun.logger; const strings = bun.strings; -const JSAst = bun.JSAst; +const JSAst = bun.ast; const E = JSAst.E; const Expr = JSAst.Expr; const G = JSAst.G; diff --git a/src/install/PackageManager/PackageManagerDirectories.zig b/src/install/PackageManager/PackageManagerDirectories.zig index e1a1219c63..dd4cc9b04a 100644 --- a/src/install/PackageManager/PackageManagerDirectories.zig +++ b/src/install/PackageManager/PackageManagerDirectories.zig @@ -739,6 +739,9 @@ const PatchHashFmt = struct { var using_fallback_temp_dir: bool = false; +const string = []const u8; +const stringZ = [:0]const u8; + const std = @import("std"); const bun = @import("bun"); @@ -751,9 +754,7 @@ const Output = bun.Output; const Path = bun.path; const Progress = bun.Progress; const default_allocator = bun.default_allocator; -const string = bun.string; -const stringZ = bun.stringZ; -const Command = bun.CLI.Command; +const Command = bun.cli.Command; const File = bun.sys.File; const Semver = bun.Semver; diff --git a/src/install/PackageManager/PackageManagerEnqueue.zig b/src/install/PackageManager/PackageManagerEnqueue.zig index 21e049a02e..b9434dd7fb 100644 --- a/src/install/PackageManager/PackageManagerEnqueue.zig +++ b/src/install/PackageManager/PackageManagerEnqueue.zig @@ -1763,6 +1763,8 @@ fn resolutionSatisfiesDependency(this: *PackageManager, resolution: Resolution, return false; } +const string = []const u8; + const std = @import("std"); const bun = @import("bun"); @@ -1771,7 +1773,6 @@ const Output = bun.Output; const Path = bun.path; const ThreadPool = bun.ThreadPool; const logger = bun.logger; -const string = bun.string; const strings = bun.strings; const Semver = bun.Semver; diff --git a/src/install/PackageManager/PackageManagerLifecycle.zig b/src/install/PackageManager/PackageManagerLifecycle.zig index 5d54a7f5a2..0d74f8514d 100644 --- a/src/install/PackageManager/PackageManagerLifecycle.zig +++ b/src/install/PackageManager/PackageManagerLifecycle.zig @@ -303,7 +303,7 @@ pub fn spawnPackageLifecycleScripts( } if (this.env.get("PATH")) |env_path| { - break :shell_bin bun.CLI.RunCommand.findShell(env_path, cwd); + break :shell_bin bun.cli.RunCommand.findShell(env_path, cwd); } break :shell_bin null; @@ -362,6 +362,8 @@ fn addDependenciesToSet( } } +const string = []const u8; + const std = @import("std"); const bun = @import("bun"); @@ -370,8 +372,7 @@ const Output = bun.Output; const Path = bun.path; const Syscall = bun.sys; const default_allocator = bun.default_allocator; -const string = bun.string; -const Command = bun.CLI.Command; +const Command = bun.cli.Command; const Semver = bun.Semver; const String = Semver.String; diff --git a/src/install/PackageManager/PackageManagerOptions.zig b/src/install/PackageManager/PackageManagerOptions.zig index 8e2dfbe606..26c023c1b2 100644 --- a/src/install/PackageManager/PackageManagerOptions.zig +++ b/src/install/PackageManager/PackageManagerOptions.zig @@ -687,6 +687,9 @@ pub const Enable = packed struct(u16) { _: u7 = 0, }; +const string = []const u8; +const stringZ = [:0]const u8; + const CommandLineArguments = @import("./CommandLineArguments.zig"); const std = @import("std"); @@ -699,10 +702,8 @@ const Output = bun.Output; const Path = bun.path; const URL = bun.URL; const logger = bun.logger; -const string = bun.string; -const stringZ = bun.stringZ; const strings = bun.strings; -const Api = bun.Schema.Api; +const Api = bun.schema.api; const HTTP = bun.http; const AsyncHTTP = HTTP.AsyncHTTP; diff --git a/src/install/PackageManager/PackageManagerResolution.zig b/src/install/PackageManager/PackageManagerResolution.zig index 4a27156fe6..7affcad333 100644 --- a/src/install/PackageManager/PackageManagerResolution.zig +++ b/src/install/PackageManager/PackageManagerResolution.zig @@ -216,13 +216,14 @@ pub fn verifyResolutions(this: *PackageManager, log_level: PackageManager.Option if (any_failed) this.crash(); } +const string = []const u8; + const std = @import("std"); const bun = @import("bun"); const Environment = bun.Environment; const OOM = bun.OOM; const Output = bun.Output; -const string = bun.string; const strings = bun.strings; const Semver = bun.Semver; diff --git a/src/install/PackageManager/ProgressStrings.zig b/src/install/PackageManager/ProgressStrings.zig index 6dbc03c4ea..308ae7f5bc 100644 --- a/src/install/PackageManager/ProgressStrings.zig +++ b/src/install/PackageManager/ProgressStrings.zig @@ -92,8 +92,9 @@ pub fn endProgressBar(manager: *PackageManager) void { manager.downloads_node = null; } +const string = []const u8; + const bun = @import("bun"); const Output = bun.Output; const Progress = bun.Progress; -const string = bun.string; const PackageManager = bun.install.PackageManager; diff --git a/src/install/PackageManager/UpdateRequest.zig b/src/install/PackageManager/UpdateRequest.zig index d80c4cf663..7273053dc5 100644 --- a/src/install/PackageManager/UpdateRequest.zig +++ b/src/install/PackageManager/UpdateRequest.zig @@ -46,7 +46,7 @@ pub fn getResolvedName(this: *const UpdateRequest, lockfile: *const Lockfile) st this.version.literal.slice(this.version_buf); } -pub fn fromJS(globalThis: *JSC.JSGlobalObject, input: JSC.JSValue) bun.JSError!JSC.JSValue { +pub fn fromJS(globalThis: *jsc.JSGlobalObject, input: jsc.JSValue) bun.JSError!jsc.JSValue { var arena = std.heap.ArenaAllocator.init(bun.default_allocator); defer arena.deinit(); var stack = std.heap.stackFallback(1024, arena.allocator()); @@ -94,7 +94,7 @@ pub fn fromJS(globalThis: *JSC.JSGlobalObject, input: JSC.JSValue) bun.JSError!J return globalThis.throw("Failed to parse dependencies", .{}); } - var object = JSC.JSValue.createEmptyObject(globalThis, 2); + var object = jsc.JSValue.createEmptyObject(globalThis, 2); var name_str = bun.String.init(update_requests[0].name); object.put(globalThis, "name", name_str.transferToJS(globalThis)); object.put(globalThis, "version", try update_requests[0].version.toJS(update_requests[0].version_buf, globalThis)); @@ -241,16 +241,17 @@ pub const PackageInstaller = PackageManager.PackageInstaller; pub const PackageJSONEditor = PackageManager.PackageJSONEditor; pub const Subcommand = PackageManager.Subcommand; +const string = []const u8; + const std = @import("std"); const bun = @import("bun"); const Global = bun.Global; -const JSAst = bun.JSAst; -const JSC = bun.JSC; +const JSAst = bun.ast; const Output = bun.Output; const default_allocator = bun.default_allocator; +const jsc = bun.jsc; const logger = bun.logger; -const string = bun.string; const strings = bun.strings; const Semver = bun.Semver; diff --git a/src/install/PackageManager/WorkspacePackageJSONCache.zig b/src/install/PackageManager/WorkspacePackageJSONCache.zig index c229c510dd..07ea1f2bb0 100644 --- a/src/install/PackageManager/WorkspacePackageJSONCache.zig +++ b/src/install/PackageManager/WorkspacePackageJSONCache.zig @@ -152,13 +152,12 @@ const std = @import("std"); const bun = @import("bun"); const Environment = bun.Environment; -const JSON = bun.JSON; +const JSON = bun.json; const JSPrinter = bun.js_printer; const default_allocator = bun.default_allocator; const logger = bun.logger; const File = bun.sys.File; const initializeStore = bun.install.initializeStore; -const JSAst = bun.JSAst; -const js_ast = bun.JSAst; +const js_ast = bun.ast; const Expr = js_ast.Expr; diff --git a/src/install/PackageManager/install_with_manager.zig b/src/install/PackageManager/install_with_manager.zig index 69e8914fe8..a2f485afc8 100644 --- a/src/install/PackageManager/install_with_manager.zig +++ b/src/install/PackageManager/install_with_manager.zig @@ -986,6 +986,8 @@ fn printBlockedPackagesInfo(summary: *const PackageInstall.Summary, global: bool } } +const string = []const u8; + const std = @import("std"); const installHoistedPackages = @import("../hoisted_install.zig").installHoistedPackages; const installIsolatedPackages = @import("../isolated_install.zig").installIsolatedPackages; @@ -998,9 +1000,8 @@ const Path = bun.path; const Progress = bun.Progress; const default_allocator = bun.default_allocator; const logger = bun.logger; -const string = bun.string; const strings = bun.strings; -const Command = bun.CLI.Command; +const Command = bun.cli.Command; const Semver = bun.Semver; const String = Semver.String; diff --git a/src/install/PackageManager/patchPackage.zig b/src/install/PackageManager/patchPackage.zig index 4a1820f169..924e5c0e07 100644 --- a/src/install/PackageManager/patchPackage.zig +++ b/src/install/PackageManager/patchPackage.zig @@ -433,8 +433,8 @@ pub fn doPatchCommit( .posix, ); - var nodefs = bun.JSC.Node.fs.NodeFS{}; - const args = bun.JSC.Node.fs.Arguments.Mkdir{ + var nodefs = bun.jsc.Node.fs.NodeFS{}; + const args = bun.jsc.Node.fs.Arguments.Mkdir{ .path = .{ .string = bun.PathString.init(manager.options.patch_features.commit.patches_dir) }, }; if (nodefs.mkdirRecursive(args).asErr()) |e| { @@ -1083,6 +1083,9 @@ const PatchArgKind = enum { } }; +const string = []const u8; +const stringZ = [:0]const u8; + const Walker = @import("../../walker_skippable.zig"); const std = @import("std"); @@ -1090,13 +1093,11 @@ const bun = @import("bun"); const Environment = bun.Environment; const FD = bun.FD; const Global = bun.Global; -const JSC = bun.JSC; -const JSON = bun.JSON; +const JSON = bun.json; const Output = bun.Output; const default_allocator = bun.default_allocator; +const jsc = bun.jsc; const logger = bun.logger; -const string = bun.string; -const stringZ = bun.stringZ; const strings = bun.strings; const File = bun.sys.File; diff --git a/src/install/PackageManager/processDependencyList.zig b/src/install/PackageManager/processDependencyList.zig index aa43a04b2c..805bda10ec 100644 --- a/src/install/PackageManager/processDependencyList.zig +++ b/src/install/PackageManager/processDependencyList.zig @@ -313,18 +313,19 @@ pub fn processDependencyList( } } +const string = []const u8; + const std = @import("std"); const bun = @import("bun"); const Environment = bun.Environment; const Global = bun.Global; -const JSAst = bun.JSAst; -const JSON = bun.JSON; +const JSAst = bun.ast; +const JSON = bun.json; const Output = bun.Output; const Path = bun.path; const Syscall = bun.sys; const logger = bun.logger; -const string = bun.string; const Semver = bun.Semver; const ExternalString = Semver.ExternalString; diff --git a/src/install/PackageManager/runTasks.zig b/src/install/PackageManager/runTasks.zig index ccb10753ee..0a7575a0c9 100644 --- a/src/install/PackageManager/runTasks.zig +++ b/src/install/PackageManager/runTasks.zig @@ -591,7 +591,7 @@ pub fn runTasks( } manager.extracted_count += 1; - bun.Analytics.Features.extracted_packages += 1; + bun.analytics.Features.extracted_packages += 1; if (comptime @TypeOf(callbacks.onExtract) != void) { switch (Ctx) { @@ -1054,6 +1054,8 @@ pub fn generateNetworkTaskForTarball( return network_task; } +const string = []const u8; + const std = @import("std"); const bun = @import("bun"); @@ -1062,7 +1064,6 @@ const Output = bun.Output; const ThreadPool = bun.ThreadPool; const default_allocator = bun.default_allocator; const logger = bun.logger; -const string = bun.string; const strings = bun.strings; const Fs = bun.fs; diff --git a/src/install/PackageManager/updatePackageJSONAndInstall.zig b/src/install/PackageManager/updatePackageJSONAndInstall.zig index 2052a04d26..c603555ec0 100644 --- a/src/install/PackageManager/updatePackageJSONAndInstall.zig +++ b/src/install/PackageManager/updatePackageJSONAndInstall.zig @@ -483,7 +483,7 @@ pub fn updatePackageJSONAndInstallCatchError( error.InstallFailed, error.InvalidPackageJSON, => { - const log = &bun.CLI.Cli.log_; + const log = &bun.cli.Cli.log_; log.print(bun.Output.errorWriter()) catch {}; bun.Global.exit(1); return; @@ -589,7 +589,7 @@ fn updatePackageJSONAndInstallAndCLI( if (needs_to_print) { const MoreInstructions = struct { - shell: bun.CLI.ShellCompletions.Shell = .unknown, + shell: bun.cli.ShellCompletions.Shell = .unknown, folder: []const u8, // Convert "/Users/Jarred Sumner" => "/Users/Jarred\ Sumner" @@ -654,7 +654,7 @@ fn updatePackageJSONAndInstallAndCLI( , .{ bun.fmt.quote(manager.track_installed_bin.basename), - MoreInstructions{ .shell = bun.CLI.ShellCompletions.Shell.fromEnv([]const u8, bun.getenvZ("SHELL") orelse ""), .folder = manager.options.bin_path }, + MoreInstructions{ .shell = bun.cli.ShellCompletions.Shell.fromEnv([]const u8, bun.getenvZ("SHELL") orelse ""), .folder = manager.options.bin_path }, }, ); Output.flush(); @@ -709,26 +709,27 @@ pub fn updatePackageJSONAndInstall( }; // This runs the bundler. - try bun.CLI.BuildCommand.exec(bun.CLI.Command.get(), &fetcher); + try bun.cli.BuildCommand.exec(bun.cli.Command.get(), &fetcher); return; } return updatePackageJSONAndInstallAndCLI(ctx, subcommand, cli); } +const string = []const u8; + const std = @import("std"); const bun = @import("bun"); const Environment = bun.Environment; const Global = bun.Global; -const JSON = bun.JSON; +const JSON = bun.json; const JSPrinter = bun.js_printer; const Output = bun.Output; const default_allocator = bun.default_allocator; const logger = bun.logger; -const string = bun.string; const strings = bun.strings; -const Command = bun.CLI.Command; +const Command = bun.cli.Command; const File = bun.sys.File; const PackageNameHash = bun.install.PackageNameHash; diff --git a/src/install/PackageManagerTask.zig b/src/install/PackageManagerTask.zig index 0ca1212867..5842b11c28 100644 --- a/src/install/PackageManagerTask.zig +++ b/src/install/PackageManagerTask.zig @@ -351,6 +351,8 @@ pub const Request = union { }, }; +const string = []const u8; + const std = @import("std"); const install = @import("./install.zig"); @@ -374,7 +376,6 @@ const Path = bun.path; const Semver = bun.Semver; const ThreadPool = bun.ThreadPool; const logger = bun.logger; -const string = bun.string; const strings = bun.strings; const File = bun.sys.File; diff --git a/src/install/PackageManifestMap.zig b/src/install/PackageManifestMap.zig index 1324e44d29..a758e8d55c 100644 --- a/src/install/PackageManifestMap.zig +++ b/src/install/PackageManifestMap.zig @@ -93,6 +93,8 @@ pub fn byNameHashAllowExpired( return null; } +const string = []const u8; + const std = @import("std"); const install = @import("./install.zig"); @@ -103,7 +105,6 @@ const PackageNameHash = install.PackageNameHash; const bun = @import("bun"); const IdentityContext = bun.IdentityContext; -const string = bun.string; const Semver = bun.Semver; const String = Semver.String; diff --git a/src/install/bin.zig b/src/install/bin.zig index 552499a30d..5646944bf1 100644 --- a/src/install/bin.zig +++ b/src/install/bin.zig @@ -611,7 +611,7 @@ pub const Bin = extern struct { return; } - bun.Analytics.Features.binlinks += 1; + bun.analytics.Features.binlinks += 1; if (comptime !Environment.isWindows) this.createSymlink(abs_target, abs_dest, global) @@ -1041,6 +1041,9 @@ pub const Bin = extern struct { }; }; +const string = []const u8; +const stringZ = [:0]const u8; + const Dependency = @import("./dependency.zig"); const Environment = @import("../env.zig"); const std = @import("std"); @@ -1050,11 +1053,9 @@ const ExternalStringList = @import("./install.zig").ExternalStringList; const Lockfile = Install.Lockfile; const bun = @import("bun"); -const JSON = bun.JSON; +const JSON = bun.json; const OOM = bun.OOM; const path = bun.path; -const string = bun.string; -const stringZ = bun.stringZ; const strings = bun.strings; const Semver = bun.Semver; diff --git a/src/install/dependency.zig b/src/install/dependency.zig index 6d0d507c62..2f5b559438 100644 --- a/src/install/dependency.zig +++ b/src/install/dependency.zig @@ -309,8 +309,8 @@ pub const Version = struct { literal: String = .{}, value: Value = .{ .uninitialized = {} }, - pub fn toJS(dep: *const Version, buf: []const u8, globalThis: *JSC.JSGlobalObject) bun.JSError!JSC.JSValue { - const object = JSC.JSValue.createEmptyObject(globalThis, 2); + pub fn toJS(dep: *const Version, buf: []const u8, globalThis: *jsc.JSGlobalObject) bun.JSError!jsc.JSValue { + const object = jsc.JSValue.createEmptyObject(globalThis, 2); object.put(globalThis, "type", bun.String.static(@tagName(dep.tag)).toJS(globalThis)); switch (dep.tag) { @@ -335,7 +335,7 @@ pub const Version = struct { object.put(globalThis, "name", try dep.value.npm.name.toJS(buf, globalThis)); var version_str = try bun.String.createFormat("{}", .{dep.value.npm.version.fmt(buf)}); object.put(globalThis, "version", version_str.transferToJS(globalThis)); - object.put(globalThis, "alias", JSC.JSValue.jsBoolean(dep.value.npm.is_alias)); + object.put(globalThis, "alias", jsc.JSValue.jsBoolean(dep.value.npm.is_alias)); }, .symlink => { object.put(globalThis, "path", try dep.value.symlink.toJS(buf, globalThis)); @@ -765,7 +765,7 @@ pub const Version = struct { return .npm; } - pub fn inferFromJS(globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { + pub fn inferFromJS(globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const arguments = callframe.arguments_old(1).slice(); if (arguments.len == 0 or !arguments[0].isString()) { return .js_undefined; @@ -1259,7 +1259,7 @@ pub fn parseWithTag( } } -pub fn fromJS(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { +pub fn fromJS(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const arguments = callframe.arguments_old(2).slice(); if (arguments.len == 1) { return try bun.install.PackageManager.UpdateRequest.fromJS(globalThis, arguments[0]); @@ -1269,7 +1269,7 @@ pub fn fromJS(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JS var stack = std.heap.stackFallback(1024, arena.allocator()); const allocator = stack.get(); - const alias_value: JSC.JSValue = if (arguments.len > 0) arguments[0] else .js_undefined; + const alias_value: jsc.JSValue = if (arguments.len > 0) arguments[0] else .js_undefined; if (!alias_value.isString()) { return .js_undefined; @@ -1281,7 +1281,7 @@ pub fn fromJS(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JS return .js_undefined; } - const name_value: JSC.JSValue = if (arguments.len > 1) arguments[1] else .js_undefined; + const name_value: jsc.JSValue = if (arguments.len > 1) arguments[1] else .js_undefined; const name_slice = try name_value.toSlice(globalThis, allocator); defer name_slice.deinit(); @@ -1440,11 +1440,11 @@ pub const Behavior = packed struct(u8) { } }; +const string = []const u8; + const Environment = @import("../env.zig"); const std = @import("std"); -const strings = @import("../string_immutable.zig"); const Repository = @import("./repository.zig").Repository; -const string = @import("../string_types.zig").string; const Install = @import("./install.zig"); const Features = Install.Features; @@ -1452,8 +1452,9 @@ const PackageManager = Install.PackageManager; const PackageNameHash = Install.PackageNameHash; const bun = @import("bun"); -const JSC = bun.JSC; +const jsc = bun.jsc; const logger = bun.logger; +const strings = bun.strings; const Semver = bun.Semver; const SlicedString = Semver.SlicedString; diff --git a/src/install/extract_tarball.zig b/src/install/extract_tarball.zig index 516074a9e1..d9d181cc6b 100644 --- a/src/install/extract_tarball.zig +++ b/src/install/extract_tarball.zig @@ -535,13 +535,13 @@ fn extract(this: *const ExtractTarball, log: *logger.Log, tgz_bytes: []const u8) }; } +const string = []const u8; + const Npm = @import("./npm.zig"); const std = @import("std"); -const strings = @import("../string_immutable.zig"); const FileSystem = @import("../fs.zig").FileSystem; const Integrity = @import("./integrity.zig").Integrity; const Resolution = @import("./resolution.zig").Resolution; -const string = @import("../string_types.zig").string; const Install = @import("./install.zig"); const DependencyID = Install.DependencyID; @@ -554,3 +554,4 @@ const Output = bun.Output; const Semver = bun.Semver; const default_allocator = bun.default_allocator; const logger = bun.logger; +const strings = bun.strings; diff --git a/src/install/hoisted_install.zig b/src/install/hoisted_install.zig index e919695d1c..e4ca16674d 100644 --- a/src/install/hoisted_install.zig +++ b/src/install/hoisted_install.zig @@ -5,7 +5,7 @@ pub fn installHoistedPackages( install_root_dependencies: bool, log_level: PackageManager.Options.LogLevel, ) !PackageInstall.Summary { - bun.Analytics.Features.hoisted_bun_install += 1; + bun.analytics.Features.hoisted_bun_install += 1; const original_trees = this.lockfile.buffers.trees; const original_tree_dep_ids = this.lockfile.buffers.hoisted_dependencies; @@ -365,7 +365,7 @@ const Output = bun.Output; const Progress = bun.Progress; const strings = bun.strings; const Bitset = bun.bit_set.DynamicBitSetUnmanaged; -const Command = bun.CLI.Command; +const Command = bun.cli.Command; const FileSystem = bun.fs.FileSystem; const install = bun.install; diff --git a/src/install/install.zig b/src/install/install.zig index a1506df252..35cc343bef 100644 --- a/src/install/install.zig +++ b/src/install/install.zig @@ -271,12 +271,13 @@ pub const PatchedDep = Lockfile.PatchedDep; pub const patch = @import("./patch_install.zig"); pub const PatchTask = patch.PatchTask; +const string = []const u8; + const std = @import("std"); const bun = @import("bun"); -const JSAst = bun.JSAst; +const JSAst = bun.ast; const default_allocator = bun.default_allocator; -const string = bun.string; const Semver = bun.Semver; const String = Semver.String; diff --git a/src/install/install_binding.zig b/src/install/install_binding.zig index f40207a4b2..128edb8b48 100644 --- a/src/install/install_binding.zig +++ b/src/install/install_binding.zig @@ -1,16 +1,16 @@ pub const bun_install_js_bindings = struct { - const JSValue = JSC.JSValue; - const ZigString = JSC.ZigString; - const JSGlobalObject = JSC.JSGlobalObject; + const JSValue = jsc.JSValue; + const ZigString = jsc.ZigString; + const JSGlobalObject = jsc.JSGlobalObject; pub fn generate(global: *JSGlobalObject) JSValue { const obj = JSValue.createEmptyObject(global, 2); const parseLockfile = ZigString.static("parseLockfile"); - obj.put(global, parseLockfile, JSC.createCallback(global, parseLockfile, 1, jsParseLockfile)); + obj.put(global, parseLockfile, jsc.createCallback(global, parseLockfile, 1, jsParseLockfile)); return obj; } - pub fn jsParseLockfile(globalObject: *JSGlobalObject, callFrame: *JSC.CallFrame) bun.JSError!JSValue { + pub fn jsParseLockfile(globalObject: *JSGlobalObject, callFrame: *jsc.CallFrame) bun.JSError!JSValue { const allocator = bun.default_allocator; var log = logger.Log.init(allocator); defer log.deinit(); @@ -75,11 +75,12 @@ pub const bun_install_js_bindings = struct { } }; +const string = []const u8; + const std = @import("std"); const bun = @import("bun"); -const JSC = bun.JSC; const Path = bun.path; +const jsc = bun.jsc; const logger = bun.logger; -const string = bun.string; const Lockfile = bun.install.Lockfile; diff --git a/src/install/integrity.zig b/src/install/integrity.zig index 0910aa33e1..50e51e0918 100644 --- a/src/install/integrity.zig +++ b/src/install/integrity.zig @@ -206,7 +206,8 @@ pub const Integrity = extern struct { } }; -const bun = @import("bun"); const std = @import("std"); -const strings = @import("../string_immutable.zig"); const Crypto = @import("../sha.zig").Hashers; + +const bun = @import("bun"); +const strings = bun.strings; diff --git a/src/install/isolated_install.zig b/src/install/isolated_install.zig index 5c0fb304a8..a8454cff19 100644 --- a/src/install/isolated_install.zig +++ b/src/install/isolated_install.zig @@ -6,7 +6,7 @@ pub fn installIsolatedPackages( install_root_dependencies: bool, workspace_filters: []const WorkspaceFilter, ) OOM!PackageInstall.Summary { - bun.Analytics.Features.isolated_bun_install += 1; + bun.analytics.Features.isolated_bun_install += 1; const lockfile = manager.lockfile; @@ -990,7 +990,7 @@ const OOM = bun.OOM; const Output = bun.Output; const Progress = bun.Progress; const sys = bun.sys; -const Command = bun.CLI.Command; +const Command = bun.cli.Command; const install = bun.install; const DependencyID = install.DependencyID; diff --git a/src/install/isolated_install/Installer.zig b/src/install/isolated_install/Installer.zig index ef2b3e69b0..fa4c942ac0 100644 --- a/src/install/isolated_install/Installer.zig +++ b/src/install/isolated_install/Installer.zig @@ -1271,6 +1271,8 @@ pub const Installer = struct { } }; +const string = []const u8; + const Hardlinker = @import("./Hardlinker.zig"); const std = @import("std"); const FileCopier = @import("./FileCopier.zig").FileCopier; @@ -1284,11 +1286,10 @@ const OOM = bun.OOM; const Output = bun.Output; const Progress = bun.Progress; const ThreadPool = bun.ThreadPool; -const string = bun.string; const strings = bun.strings; const sys = bun.sys; const Bitset = bun.bit_set.DynamicBitSetUnmanaged; -const Command = bun.CLI.Command; +const Command = bun.cli.Command; const Mutex = bun.threading.Mutex; const String = bun.Semver.String; diff --git a/src/install/isolated_install/Store.zig b/src/install/isolated_install/Store.zig index f75e12f80b..617b38a425 100644 --- a/src/install/isolated_install/Store.zig +++ b/src/install/isolated_install/Store.zig @@ -526,12 +526,13 @@ pub const Store = struct { }; }; +const string = []const u8; + const std = @import("std"); const bun = @import("bun"); const OOM = bun.OOM; const Output = bun.Output; -const string = bun.string; const Semver = bun.Semver; const String = Semver.String; diff --git a/src/install/lifecycle_script_runner.zig b/src/install/lifecycle_script_runner.zig index 7590dd907b..ef503d767a 100644 --- a/src/install/lifecycle_script_runner.zig +++ b/src/install/lifecycle_script_runner.zig @@ -51,7 +51,7 @@ pub const LifecycleScriptSubprocess = struct { return this.manager.event_loop.loop(); } - pub fn eventLoop(this: *const LifecycleScriptSubprocess) *JSC.AnyEventLoop { + pub fn eventLoop(this: *const LifecycleScriptSubprocess) *jsc.AnyEventLoop { return &this.manager.event_loop; } @@ -113,7 +113,7 @@ pub const LifecycleScriptSubprocess = struct { } pub fn spawnNextScript(this: *LifecycleScriptSubprocess, next_script_index: u8) !void { - bun.Analytics.Features.lifecycle_scripts += 1; + bun.analytics.Features.lifecycle_scripts += 1; if (!this.has_incremented_alive_count) { this.has_incremented_alive_count = true; @@ -142,7 +142,7 @@ pub const LifecycleScriptSubprocess = struct { var copy_script = try std.ArrayList(u8).initCapacity(manager.allocator, original_script.len + 1); defer copy_script.deinit(); - try bun.CLI.RunCommand.replacePackageManagerRun(©_script, original_script); + try bun.cli.RunCommand.replacePackageManagerRun(©_script, original_script); try copy_script.append(0); const combined_script: [:0]u8 = copy_script.items[0 .. copy_script.items.len - 1 :0]; @@ -208,7 +208,7 @@ pub const LifecycleScriptSubprocess = struct { .cwd = cwd, .windows = if (Environment.isWindows) .{ - .loop = JSC.EventLoopHandle.init(&manager.event_loop), + .loop = jsc.EventLoopHandle.init(&manager.event_loop), }, .stream = false, @@ -563,6 +563,8 @@ pub const LifecycleScriptSubprocess = struct { } }; +const string = []const u8; + const Lockfile = @import("./lockfile.zig"); const std = @import("std"); const PackageManager = @import("./install.zig").PackageManager; @@ -571,8 +573,7 @@ const Timer = std.time.Timer; const bun = @import("bun"); const Environment = bun.Environment; const Global = bun.Global; -const JSC = bun.JSC; const Output = bun.Output; -const string = bun.string; +const jsc = bun.jsc; const Process = bun.spawn.Process; const Store = bun.install.Store; diff --git a/src/install/lockfile.zig b/src/install/lockfile.zig index 669a508d3b..28510beeaa 100644 --- a/src/install/lockfile.zig +++ b/src/install/lockfile.zig @@ -290,7 +290,7 @@ pub fn loadFromDir( } }; - bun.Analytics.Features.text_lockfile += 1; + bun.analytics.Features.text_lockfile += 1; return .{ .ok = .{ @@ -333,7 +333,7 @@ pub fn loadFromDir( Output.panic("failed to parse text lockfile converted from binary lockfile: {s}", .{@errorName(err)}); }; - bun.Analytics.Features.text_lockfile += 1; + bun.analytics.Features.text_lockfile += 1; } }, else => {}, @@ -2008,6 +2008,9 @@ const MetaHash = [std.crypto.hash.sha2.Sha512T256.digest_length]u8; const zero_hash = std.mem.zeroes(MetaHash); pub const StringPool = String.Builder.StringPool; +const string = []const u8; +const stringZ = [:0]const u8; + const Dependency = @import("./dependency.zig"); const DotEnv = @import("../env_loader.zig"); const Path = @import("../resolver/resolve_path.zig"); @@ -2018,7 +2021,6 @@ const Crypto = @import("../sha.zig").Hashers; const Resolution = @import("./resolution.zig").Resolution; const StaticHashMap = @import("../StaticHashMap.zig").StaticHashMap; const which = @import("../which.zig").which; -const z_allocator = @import("../allocators/memory_allocator.zig").z_allocator; const Allocator = std.mem.Allocator; const Fs = @import("../fs.zig"); @@ -2031,16 +2033,15 @@ const bun = @import("bun"); const Environment = bun.Environment; const Global = bun.Global; const GlobalStringBuilder = bun.StringBuilder; -const JSON = bun.JSON; +const JSON = bun.json; const MutableString = bun.MutableString; const OOM = bun.OOM; const Output = bun.Output; const assert = bun.assert; const default_allocator = bun.default_allocator; const logger = bun.logger; -const string = bun.string; -const stringZ = bun.stringZ; const strings = bun.strings; +const z_allocator = bun.z_allocator; const Bitset = bun.bit_set.DynamicBitSetUnmanaged; const File = bun.sys.File; diff --git a/src/install/lockfile/CatalogMap.zig b/src/install/lockfile/CatalogMap.zig index 1d719a11e2..e42176b46f 100644 --- a/src/install/lockfile/CatalogMap.zig +++ b/src/install/lockfile/CatalogMap.zig @@ -380,7 +380,7 @@ const Allocator = std.mem.Allocator; const bun = @import("bun"); const OOM = bun.OOM; const logger = bun.logger; -const Expr = bun.JSAst.Expr; +const Expr = bun.ast.Expr; const String = bun.Semver.String; const Dependency = bun.install.Dependency; diff --git a/src/install/lockfile/OverrideMap.zig b/src/install/lockfile/OverrideMap.zig index 72db2f47fa..2643f58740 100644 --- a/src/install/lockfile/OverrideMap.zig +++ b/src/install/lockfile/OverrideMap.zig @@ -351,7 +351,7 @@ const Output = bun.Output; const assert = bun.assert; const logger = bun.logger; const strings = bun.strings; -const Expr = bun.JSAst.Expr; +const Expr = bun.ast.Expr; const String = bun.Semver.String; const Dependency = bun.install.Dependency; diff --git a/src/install/lockfile/Package.zig b/src/install/lockfile/Package.zig index 9002c4fa4f..a96b51c86f 100644 --- a/src/install/lockfile/Package.zig +++ b/src/install/lockfile/Package.zig @@ -2137,18 +2137,16 @@ const bun = @import("bun"); const ArrayIdentityContext = bun.ArrayIdentityContext; const Environment = bun.Environment; const Global = bun.Global; -const JSON = bun.JSON; +const JSON = bun.json; const Output = bun.Output; const PackageJSON = bun.PackageJSON; const Path = bun.path; const assert = bun.assert; const logger = bun.logger; const strings = bun.strings; +const Expr = bun.ast.Expr; const FileSystem = bun.fs.FileSystem; -const JSAst = bun.JSAst; -const Expr = bun.JSAst.Expr; - const Semver = bun.Semver; const ExternalString = Semver.ExternalString; const String = Semver.String; diff --git a/src/install/lockfile/Package/Scripts.zig b/src/install/lockfile/Package/Scripts.zig index 62a7c8f765..2dfe3bf5c4 100644 --- a/src/install/lockfile/Package/Scripts.zig +++ b/src/install/lockfile/Package/Scripts.zig @@ -375,14 +375,12 @@ const Allocator = std.mem.Allocator; const bun = @import("bun"); const Environment = bun.Environment; const FD = bun.FD; -const JSON = bun.JSON; +const JSON = bun.json; const Output = bun.Output; const assert = bun.assert; const logger = bun.logger; const strings = bun.strings; - -const JSAst = bun.JSAst; -const Expr = bun.JSAst.Expr; +const Expr = bun.ast.Expr; const Semver = bun.Semver; const String = Semver.String; diff --git a/src/install/lockfile/Package/WorkspaceMap.zig b/src/install/lockfile/Package/WorkspaceMap.zig index 8b270a80a5..d6406f4986 100644 --- a/src/install/lockfile/Package/WorkspaceMap.zig +++ b/src/install/lockfile/Package/WorkspaceMap.zig @@ -387,7 +387,7 @@ const Allocator = std.mem.Allocator; const bun = @import("bun"); const Environment = bun.Environment; const Glob = bun.glob; -const JSAst = bun.JSAst; +const JSAst = bun.ast; const Output = bun.Output; const Path = bun.path; const logger = bun.logger; diff --git a/src/install/lockfile/Tree.zig b/src/install/lockfile/Tree.zig index 5ae7907a1e..6949c3ec0a 100644 --- a/src/install/lockfile/Tree.zig +++ b/src/install/lockfile/Tree.zig @@ -643,6 +643,7 @@ pub const FillItem = struct { pub const TreeFiller = std.fifo.LinearFifo(FillItem, .Dynamic); const string = []const u8; +const stringZ = [:0]const u8; const std = @import("std"); const Allocator = std.mem.Allocator; @@ -654,7 +655,6 @@ const Output = bun.Output; const Path = bun.path; const assert = bun.assert; const logger = bun.logger; -const stringZ = bun.stringZ; const z_allocator = bun.z_allocator; const Bitset = bun.bit_set.DynamicBitSetUnmanaged; const String = bun.Semver.String; diff --git a/src/install/lockfile/bun.lock.zig b/src/install/lockfile/bun.lock.zig index 5c2b966482..8c393ea965 100644 --- a/src/install/lockfile/bun.lock.zig +++ b/src/install/lockfile/bun.lock.zig @@ -2193,16 +2193,17 @@ fn parseAppendDependencies( return .{ @intCast(off), @intCast(end - off) }; } +const string = []const u8; + const ExtractTarball = @import("../extract_tarball.zig"); const std = @import("std"); const Integrity = @import("../integrity.zig").Integrity; const bun = @import("bun"); const Environment = bun.Environment; -const JSON = bun.JSON; +const JSON = bun.json; const OOM = bun.OOM; const logger = bun.logger; -const string = bun.string; const strings = bun.strings; const Expr = bun.js_parser.Expr; diff --git a/src/install/migration.zig b/src/install/migration.zig index 411a04ffa0..31a813de1b 100644 --- a/src/install/migration.zig +++ b/src/install/migration.zig @@ -95,7 +95,7 @@ pub fn migrateNPMLockfile( Install.initializeStore(); const json_src = logger.Source.initPathString(abs_path, data); - const json = bun.JSON.parseUTF8(&json_src, log, allocator) catch return error.InvalidNPMLockfile; + const json = bun.json.parseUTF8(&json_src, log, allocator) catch return error.InvalidNPMLockfile; if (json.data != .e_object) { return error.InvalidNPMLockfile; @@ -111,7 +111,7 @@ pub fn migrateNPMLockfile( return error.InvalidNPMLockfile; } - bun.Analytics.Features.lockfile_migration_from_package_lock += 1; + bun.analytics.Features.lockfile_migration_from_package_lock += 1; // Count pass @@ -1019,6 +1019,8 @@ fn packageNameFromPath(pkg_path: []const u8) []const u8 { return pkg_path[pkg_name_start..]; } +const string = []const u8; + const Dependency = @import("./dependency.zig"); const Install = @import("./install.zig"); const Npm = @import("./npm.zig"); @@ -1036,13 +1038,12 @@ const Environment = bun.Environment; const Global = bun.Global; const Output = bun.Output; const logger = bun.logger; -const string = bun.string; const strings = bun.strings; const File = bun.sys.File; -const JSAst = bun.JSAst; -const E = JSAst.E; - const Semver = bun.Semver; const String = Semver.String; const stringHash = String.Builder.stringHash; + +const JSAst = bun.ast; +const E = JSAst.E; diff --git a/src/install/npm.zig b/src/install/npm.zig index d9fda04050..216820fe67 100644 --- a/src/install/npm.zig +++ b/src/install/npm.zig @@ -236,7 +236,7 @@ pub const Registry = struct { return name[1..]; } - pub fn fromAPI(name: string, registry_: Api.NpmRegistry, allocator: std.mem.Allocator, env: *DotEnv.Loader) OOM!Scope { + pub fn fromAPI(name: string, registry_: api.NpmRegistry, allocator: std.mem.Allocator, env: *DotEnv.Loader) OOM!Scope { var registry = registry_; // Support $ENV_VAR for registry URLs @@ -684,8 +684,8 @@ pub const OperatingSystem = enum(u16) { return .{ .added = this, .removed = .none }; } - const JSC = bun.JSC; - pub fn jsFunctionOperatingSystemIsMatch(globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { + const jsc = bun.jsc; + pub fn jsFunctionOperatingSystemIsMatch(globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const args = callframe.arguments_old(1); var operating_system = negatable(.none); var iter = try args.ptr[0].arrayIterator(globalObject); @@ -696,7 +696,7 @@ pub const OperatingSystem = enum(u16) { if (globalObject.hasException()) return .zero; } if (globalObject.hasException()) return .zero; - return JSC.JSValue.jsBoolean(operating_system.combine().isMatch()); + return jsc.JSValue.jsBoolean(operating_system.combine().isMatch()); } }; @@ -726,8 +726,8 @@ pub const Libc = enum(u8) { // TODO: pub const current: Libc = @intFromEnum(glibc); - const JSC = bun.JSC; - pub fn jsFunctionLibcIsMatch(globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { + const jsc = bun.jsc; + pub fn jsFunctionLibcIsMatch(globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const args = callframe.arguments_old(1); var libc = negatable(.none); var iter = args.ptr[0].arrayIterator(globalObject); @@ -738,7 +738,7 @@ pub const Libc = enum(u8) { if (globalObject.hasException()) return .zero; } if (globalObject.hasException()) return .zero; - return JSC.JSValue.jsBoolean(libc.combine().isMatch()); + return jsc.JSValue.jsBoolean(libc.combine().isMatch()); } }; @@ -801,8 +801,8 @@ pub const Architecture = enum(u16) { return .{ .added = this, .removed = .none }; } - const JSC = bun.JSC; - pub fn jsFunctionArchitectureIsMatch(globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { + const jsc = bun.jsc; + pub fn jsFunctionArchitectureIsMatch(globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const args = callframe.arguments_old(1); var architecture = negatable(.none); var iter = try args.ptr[0].arrayIterator(globalObject); @@ -813,7 +813,7 @@ pub const Architecture = enum(u16) { if (globalObject.hasException()) return .zero; } if (globalObject.hasException()) return .zero; - return JSC.JSValue.jsBoolean(architecture.combine().isMatch()); + return jsc.JSValue.jsBoolean(architecture.combine().isMatch()); } }; @@ -1318,16 +1318,16 @@ pub const PackageManifest = struct { }; pub const bindings = struct { - const JSC = bun.JSC; - const JSValue = JSC.JSValue; - const JSGlobalObject = JSC.JSGlobalObject; - const CallFrame = JSC.CallFrame; - const ZigString = JSC.ZigString; + const jsc = bun.jsc; + const JSValue = jsc.JSValue; + const JSGlobalObject = jsc.JSGlobalObject; + const CallFrame = jsc.CallFrame; + const ZigString = jsc.ZigString; pub fn generate(global: *JSGlobalObject) JSValue { const obj = JSValue.createEmptyObject(global, 1); const parseManifestString = ZigString.static("parseManifest"); - obj.put(global, parseManifestString, JSC.createCallback(global, parseManifestString, 2, jsParseManifest)); + obj.put(global, parseManifestString, jsc.createCallback(global, parseManifestString, 2, jsParseManifest)); return obj; } @@ -1529,7 +1529,7 @@ pub const PackageManifest = struct { ) !?PackageManifest { const source = &logger.Source.initPathString(expected_name, json_buffer); initializeStore(); - defer bun.JSAst.Stmt.Data.Store.memory_allocator.?.pop(); + defer bun.ast.Stmt.Data.Store.memory_allocator.?.pop(); var arena = bun.ArenaAllocator.init(allocator); defer arena.deinit(); const json = JSON.parseUTF8( @@ -2422,16 +2422,15 @@ pub const PackageManifest = struct { } }; +const string = []const u8; + const DotEnv = @import("../env_loader.zig"); const std = @import("std"); -const strings = @import("../string_immutable.zig"); -const Api = @import("../api/schema.zig").Api; const Bin = @import("./bin.zig").Bin; const IdentityContext = @import("../identity_context.zig").IdentityContext; const Integrity = @import("./integrity.zig").Integrity; const ObjectPool = @import("../pool.zig").ObjectPool; const URL = @import("../url.zig").URL; -const string = @import("../string_types.zig").string; const Aligner = @import("./install.zig").Aligner; const ExternalSlice = @import("./install.zig").ExternalSlice; @@ -2445,14 +2444,16 @@ const bun = @import("bun"); const Environment = bun.Environment; const Global = bun.Global; const HTTPClient = bun.http; -const JSON = bun.JSON; +const JSON = bun.json; const MutableString = bun.MutableString; const OOM = bun.OOM; const Output = bun.Output; const default_allocator = bun.default_allocator; const http = bun.http; const logger = bun.logger; +const strings = bun.strings; const File = bun.sys.File; +const api = bun.schema.api; const Semver = bun.Semver; const ExternalString = Semver.ExternalString; diff --git a/src/install/patch_install.zig b/src/install/patch_install.zig index 7d455035df..cbd11f56b8 100644 --- a/src/install/patch_install.zig +++ b/src/install/patch_install.zig @@ -579,6 +579,9 @@ pub const PatchTask = struct { } }; +const string = []const u8; +const stringZ = [:0]const u8; + const std = @import("std"); const Fs = @import("../fs.zig"); @@ -590,8 +593,6 @@ const Output = bun.Output; const PackageManager = bun.PackageManager; const Progress = bun.Progress; const ThreadPool = bun.ThreadPool; -const string = bun.string; -const stringZ = bun.stringZ; const String = bun.Semver.String; const Task = bun.install.Task; diff --git a/src/install/repository.zig b/src/install/repository.zig index 3184b76be5..8d374d0bfa 100644 --- a/src/install/repository.zig +++ b/src/install/repository.zig @@ -485,7 +485,7 @@ pub const Repository = extern struct { url: string, attempt: u8, ) !std.fs.Dir { - bun.Analytics.Features.git_dependencies += 1; + bun.analytics.Features.git_dependencies += 1; const folder_name = try std.fmt.bufPrintZ(&folder_name_buf, "{any}.git", .{ bun.fmt.hexIntLower(task_id.get()), }); @@ -582,7 +582,7 @@ pub const Repository = extern struct { url: string, resolved: string, ) !ExtractData { - bun.Analytics.Features.git_dependencies += 1; + bun.analytics.Features.git_dependencies += 1; const folder_name = PackageManager.cachedGitFolderNamePrint(&folder_name_buf, resolved, null); var package_dir = bun.openDir(cache_dir, folder_name) catch |not_found| brk: { @@ -681,13 +681,13 @@ pub const Repository = extern struct { } }; +const string = []const u8; + const Dependency = @import("./dependency.zig"); const DotEnv = @import("../env_loader.zig"); const Environment = @import("../env.zig"); const std = @import("std"); -const strings = @import("../string_immutable.zig"); const FileSystem = @import("../fs.zig").FileSystem; -const string = @import("../string_types.zig").string; const Install = @import("./install.zig"); const ExtractData = Install.ExtractData; @@ -697,6 +697,7 @@ const bun = @import("bun"); const OOM = bun.OOM; const Path = bun.path; const logger = bun.logger; +const strings = bun.strings; const File = bun.sys.File; const Semver = bun.Semver; diff --git a/src/install/resolution.zig b/src/install/resolution.zig index 4d6eab34b8..9ceec439a4 100644 --- a/src/install/resolution.zig +++ b/src/install/resolution.zig @@ -428,14 +428,15 @@ pub const Resolution = extern struct { }; }; +const string = []const u8; + const std = @import("std"); -const strings = @import("../string_immutable.zig"); const Repository = @import("./repository.zig").Repository; const VersionedURL = @import("./versioned_url.zig").VersionedURL; -const string = @import("../string_types.zig").string; const bun = @import("bun"); const OOM = bun.OOM; +const strings = bun.strings; const Dependency = bun.install.Dependency; const Semver = bun.Semver; diff --git a/src/install/resolvers/folder_resolver.zig b/src/install/resolvers/folder_resolver.zig index 723c7aafb4..7599e12e1e 100644 --- a/src/install/resolvers/folder_resolver.zig +++ b/src/install/resolvers/folder_resolver.zig @@ -328,6 +328,9 @@ pub const FolderResolution = union(Tag) { } }; +const string = []const u8; +const stringZ = [:0]const u8; + const Dependency = @import("../dependency.zig"); const Npm = @import("../npm.zig"); const std = @import("std"); @@ -341,10 +344,8 @@ const PackageID = @import("../install.zig").PackageID; const PackageManager = @import("../install.zig").PackageManager; const bun = @import("bun"); -const JSAst = bun.JSAst; +const JSAst = bun.ast; const logger = bun.logger; -const string = bun.string; -const stringZ = bun.stringZ; const strings = bun.strings; const Semver = bun.Semver; diff --git a/src/install/windows-shim/bun_shim_impl.zig b/src/install/windows-shim/bun_shim_impl.zig index 28756a1f2b..7cba0f8276 100644 --- a/src/install/windows-shim/bun_shim_impl.zig +++ b/src/install/windows-shim/bun_shim_impl.zig @@ -877,7 +877,7 @@ fn launcher(comptime mode: LauncherMode, bun_ctx: anytype) mode.RetType() { } pub const FromBunRunContext = struct { - const CommandContext = bun.CLI.Command.Context; + const CommandContext = bun.cli.Command.Context; /// Path like 'C:\Users\chloe\project\node_modules\.bin\foo.bunx' base_path: []u16, diff --git a/src/interchange.zig b/src/interchange.zig new file mode 100644 index 0000000000..a489e69e72 --- /dev/null +++ b/src/interchange.zig @@ -0,0 +1,2 @@ +pub const json = @import("./interchange/json.zig"); +pub const toml = @import("./interchange/toml.zig"); diff --git a/src/json_parser.zig b/src/interchange/json.zig similarity index 99% rename from src/json_parser.zig rename to src/interchange/json.zig index a0749804aa..ad5fb1bf39 100644 --- a/src/json_parser.zig +++ b/src/interchange/json.zig @@ -1004,8 +1004,9 @@ fn expectPrintedJSON(_contents: string, expected: string) !void { try std.testing.expectEqualStrings(expected, js); } +const string = []const u8; + const std = @import("std"); -const BabyList = @import("./baby_list.zig").BabyList; const expect = std.testing.expect; const bun = @import("bun"); @@ -1016,11 +1017,11 @@ const assert = bun.assert; const default_allocator = bun.default_allocator; const js_printer = bun.js_printer; const logger = bun.logger; -const string = bun.string; const strings = bun.strings; +const BabyList = bun.collections.BabyList; const Indentation = js_printer.Options.Indentation; -const js_ast = bun.JSAst; +const js_ast = bun.ast; const E = js_ast.E; const ExprNodeList = js_ast.ExprNodeList; const G = js_ast.G; diff --git a/src/toml/toml_parser.zig b/src/interchange/toml.zig similarity index 98% rename from src/toml/toml_parser.zig rename to src/interchange/toml.zig index f9ca213f74..ffec013f70 100644 --- a/src/toml/toml_parser.zig +++ b/src/interchange/toml.zig @@ -366,20 +366,21 @@ pub const TOML = struct { } }; +pub const lexer = @import("./toml/lexer.zig"); +pub const Lexer = lexer.Lexer; +const T = lexer.T; + +const string = []const u8; + const std = @import("std"); const IdentityContext = @import("../identity_context.zig").IdentityContext; const expect = std.testing.expect; -const toml_lexer = @import("./toml_lexer.zig"); -const Lexer = toml_lexer.Lexer; -const T = toml_lexer.T; - const bun = @import("bun"); const assert = bun.assert; const default_allocator = bun.default_allocator; const logger = bun.logger; -const string = bun.string; -const js_ast = bun.JSAst; +const js_ast = bun.ast; const E = js_ast.E; const Expr = js_ast.Expr; diff --git a/src/toml/toml_lexer.zig b/src/interchange/toml/lexer.zig similarity index 99% rename from src/toml/toml_lexer.zig rename to src/interchange/toml/lexer.zig index 6462a18192..d72b8ab7ab 100644 --- a/src/toml/toml_lexer.zig +++ b/src/interchange/toml/lexer.zig @@ -1237,11 +1237,12 @@ inline fn float64(num: anytype) f64 { return @as(f64, @floatFromInt(num)); } +const string = []const u8; + const std = @import("std"); const bun = @import("bun"); const CodePoint = bun.CodePoint; -const js_ast = bun.JSAst; +const js_ast = bun.ast; const logger = bun.logger; -const string = bun.string; const strings = bun.strings; diff --git a/src/io/MaxBuf.zig b/src/io/MaxBuf.zig index 34b2c34943..2ac0235a4e 100644 --- a/src/io/MaxBuf.zig +++ b/src/io/MaxBuf.zig @@ -83,4 +83,4 @@ pub const Kind = enum { const bun = @import("bun"); const std = @import("std"); -const Subprocess = bun.JSC.Subprocess; +const Subprocess = bun.jsc.Subprocess; diff --git a/src/io/PipeReader.zig b/src/io/PipeReader.zig index b06c41c30f..0a20313ff1 100644 --- a/src/io/PipeReader.zig +++ b/src/io/PipeReader.zig @@ -15,7 +15,7 @@ const BufferedReaderVTable = struct { onReaderDone: *const fn (*anyopaque) void, onReaderError: *const fn (*anyopaque, bun.sys.Error) void, loop: *const fn (*anyopaque) *Async.Loop, - eventLoop: *const fn (*anyopaque) JSC.EventLoopHandle, + eventLoop: *const fn (*anyopaque) jsc.EventLoopHandle, pub fn init(comptime Type: type) *const BufferedReaderVTable.Fn { const fns = struct { @@ -28,8 +28,8 @@ const BufferedReaderVTable = struct { fn onReaderError(this: *anyopaque, err: bun.sys.Error) void { return Type.onReaderError(@as(*Type, @alignCast(@ptrCast(this))), err); } - fn eventLoop(this: *anyopaque) JSC.EventLoopHandle { - return JSC.EventLoopHandle.init(Type.eventLoop(@as(*Type, @alignCast(@ptrCast(this))))); + fn eventLoop(this: *anyopaque) jsc.EventLoopHandle { + return jsc.EventLoopHandle.init(Type.eventLoop(@as(*Type, @alignCast(@ptrCast(this))))); } fn loop(this: *anyopaque) *Async.Loop { return Type.loop(@as(*Type, @alignCast(@ptrCast(this)))); @@ -45,7 +45,7 @@ const BufferedReaderVTable = struct { } }; - pub fn eventLoop(this: @This()) JSC.EventLoopHandle { + pub fn eventLoop(this: @This()) jsc.EventLoopHandle { return this.fns.eventLoop(this.parent); } @@ -281,7 +281,7 @@ const PosixBufferedReader = struct { } } - pub fn start(this: *PosixBufferedReader, fd: bun.FileDescriptor, is_pollable: bool) bun.JSC.Maybe(void) { + pub fn start(this: *PosixBufferedReader, fd: bun.FileDescriptor, is_pollable: bool) bun.jsc.Maybe(void) { if (!is_pollable) { this.buffer().clearRetainingCapacity(); this.flags.is_done = false; @@ -300,7 +300,7 @@ const PosixBufferedReader = struct { }; } - pub fn startFileOffset(this: *PosixBufferedReader, fd: bun.FileDescriptor, poll: bool, offset: usize) bun.JSC.Maybe(void) { + pub fn startFileOffset(this: *PosixBufferedReader, fd: bun.FileDescriptor, poll: bool, offset: usize) bun.jsc.Maybe(void) { this._offset = offset; this.flags.use_pread = true; return this.start(fd, poll); @@ -329,7 +329,7 @@ const PosixBufferedReader = struct { return this.vtable.loop(); } - pub fn eventLoop(this: *const PosixBufferedReader) JSC.EventLoopHandle { + pub fn eventLoop(this: *const PosixBufferedReader) jsc.EventLoopHandle { return this.vtable.eventLoop(); } @@ -397,9 +397,9 @@ const PosixBufferedReader = struct { return false; } - fn wrapReadFn(comptime func: *const fn (bun.FileDescriptor, []u8) JSC.Maybe(usize)) *const fn (bun.FileDescriptor, []u8, usize) JSC.Maybe(usize) { + fn wrapReadFn(comptime func: *const fn (bun.FileDescriptor, []u8) jsc.Maybe(usize)) *const fn (bun.FileDescriptor, []u8, usize) jsc.Maybe(usize) { return struct { - pub fn call(fd: bun.FileDescriptor, buf: []u8, offset: usize) JSC.Maybe(usize) { + pub fn call(fd: bun.FileDescriptor, buf: []u8, offset: usize) jsc.Maybe(usize) { _ = offset; return func(fd, buf); } @@ -408,7 +408,7 @@ const PosixBufferedReader = struct { fn readFile(parent: *PosixBufferedReader, resizable_buffer: *std.ArrayList(u8), fd: bun.FileDescriptor, size_hint: isize, received_hup: bool) void { const preadFn = struct { - pub fn call(fd1: bun.FileDescriptor, buf: []u8, offset: usize) JSC.Maybe(usize) { + pub fn call(fd1: bun.FileDescriptor, buf: []u8, offset: usize) jsc.Maybe(usize) { return bun.sys.pread(fd1, buf, @intCast(offset)); } }.call; @@ -505,7 +505,7 @@ const PosixBufferedReader = struct { } } - fn readWithFn(parent: *PosixBufferedReader, resizable_buffer: *std.ArrayList(u8), fd: bun.FileDescriptor, size_hint: isize, received_hup: bool, comptime file_type: FileType, comptime sys_fn: *const fn (bun.FileDescriptor, []u8, usize) JSC.Maybe(usize)) void { + fn readWithFn(parent: *PosixBufferedReader, resizable_buffer: *std.ArrayList(u8), fd: bun.FileDescriptor, size_hint: isize, received_hup: bool, comptime file_type: FileType, comptime sys_fn: *const fn (bun.FileDescriptor, []u8, usize) jsc.Maybe(usize)) void { _ = size_hint; // autofix const streaming = parent.vtable.isStreamingEnabled(); @@ -859,7 +859,7 @@ pub const WindowsBufferedReader = struct { return res; } - pub fn startWithCurrentPipe(this: *WindowsBufferedReader) bun.JSC.Maybe(void) { + pub fn startWithCurrentPipe(this: *WindowsBufferedReader) bun.jsc.Maybe(void) { bun.assert(!this.source.?.isClosed()); this.source.?.setData(this); this.buffer().clearRetainingCapacity(); @@ -867,12 +867,12 @@ pub const WindowsBufferedReader = struct { return this.startReading(); } - pub fn startWithPipe(this: *WindowsBufferedReader, pipe: *uv.Pipe) bun.JSC.Maybe(void) { + pub fn startWithPipe(this: *WindowsBufferedReader, pipe: *uv.Pipe) bun.jsc.Maybe(void) { this.source = .{ .pipe = pipe }; return this.startWithCurrentPipe(); } - pub fn start(this: *WindowsBufferedReader, fd: bun.FileDescriptor, _: bool) bun.JSC.Maybe(void) { + pub fn start(this: *WindowsBufferedReader, fd: bun.FileDescriptor, _: bool) bun.jsc.Maybe(void) { bun.assert(this.source == null); const source = switch (Source.open(uv.Loop.get(), fd)) { .err => |err| return .{ .err = err }, @@ -883,7 +883,7 @@ pub const WindowsBufferedReader = struct { return this.startWithCurrentPipe(); } - pub fn startFileOffset(this: *WindowsBufferedReader, fd: bun.FileDescriptor, poll: bool, offset: usize) bun.JSC.Maybe(void) { + pub fn startFileOffset(this: *WindowsBufferedReader, fd: bun.FileDescriptor, poll: bool, offset: usize) bun.jsc.Maybe(void) { this._offset = offset; this.flags.use_pread = true; return this.start(fd, poll); @@ -900,7 +900,7 @@ pub const WindowsBufferedReader = struct { } } - pub fn setRawMode(this: *WindowsBufferedReader, value: bool) bun.JSC.Maybe(void) { + pub fn setRawMode(this: *WindowsBufferedReader, value: bool) bun.jsc.Maybe(void) { const source = this.source orelse return .{ .err = .{ .errno = @intFromEnum(bun.sys.E.BADF), @@ -1011,7 +1011,7 @@ pub const WindowsBufferedReader = struct { } } - pub fn startReading(this: *WindowsBufferedReader) bun.JSC.Maybe(void) { + pub fn startReading(this: *WindowsBufferedReader) bun.jsc.Maybe(void) { if (this.flags.is_done or !this.flags.is_paused) return .{ .result = {} }; this.flags.is_paused = false; const source: Source = this.source orelse return .{ .err = bun.sys.Error.fromCode(bun.sys.E.BADF, .read) }; @@ -1038,7 +1038,7 @@ pub const WindowsBufferedReader = struct { return .{ .result = {} }; } - pub fn stopReading(this: *WindowsBufferedReader) bun.JSC.Maybe(void) { + pub fn stopReading(this: *WindowsBufferedReader) bun.jsc.Maybe(void) { if (this.flags.is_done or this.flags.is_paused) return .{ .result = {} }; this.flags.is_paused = true; const source = this.source orelse return .{ .result = {} }; @@ -1108,7 +1108,7 @@ pub const WindowsBufferedReader = struct { bun.default_allocator.destroy(this); } - pub fn onRead(this: *WindowsBufferedReader, amount: bun.JSC.Maybe(usize), slice: []u8, hasMore: ReadState) void { + pub fn onRead(this: *WindowsBufferedReader, amount: bun.jsc.Maybe(usize), slice: []u8, hasMore: ReadState) void { if (amount == .err) { this.onError(amount.err); return; @@ -1173,5 +1173,5 @@ const ReadState = @import("./pipes.zig").ReadState; const bun = @import("bun"); const Async = bun.Async; -const JSC = bun.JSC; +const jsc = bun.jsc; const uv = bun.windows.libuv; diff --git a/src/io/PipeWriter.zig b/src/io/PipeWriter.zig index 8d52d13f39..21f51dedb6 100644 --- a/src/io/PipeWriter.zig +++ b/src/io/PipeWriter.zig @@ -32,7 +32,7 @@ pub fn PosixPipeWriter( }; } - fn tryWriteWithWriteFn(this: *This, buf: []const u8, comptime write_fn: *const fn (bun.FileDescriptor, []const u8) JSC.Maybe(usize)) WriteResult { + fn tryWriteWithWriteFn(this: *This, buf: []const u8, comptime write_fn: *const fn (bun.FileDescriptor, []const u8) jsc.Maybe(usize)) WriteResult { const fd = getFd(this); var offset: usize = 0; @@ -63,7 +63,7 @@ pub fn PosixPipeWriter( return .{ .wrote = offset }; } - fn writeToFileType(comptime file_type: FileType) *const (fn (bun.FileDescriptor, []const u8) JSC.Maybe(usize)) { + fn writeToFileType(comptime file_type: FileType) *const (fn (bun.FileDescriptor, []const u8) jsc.Maybe(usize)) { comptime return switch (file_type) { .nonblocking_pipe, .file => &bun.sys.write, .pipe => &writeToBlockingPipe, @@ -71,7 +71,7 @@ pub fn PosixPipeWriter( }; } - fn writeToBlockingPipe(fd: bun.FileDescriptor, buf: []const u8) JSC.Maybe(usize) { + fn writeToBlockingPipe(fd: bun.FileDescriptor, buf: []const u8) jsc.Maybe(usize) { if (comptime bun.Environment.isLinux) { if (bun.linux.RWFFlagSupport.isMaybeSupported()) { return bun.sys.writeNonblocking(fd, buf); @@ -80,7 +80,7 @@ pub fn PosixPipeWriter( switch (bun.isWritable(fd)) { .ready, .hup => return bun.sys.write(fd, buf), - .not_ready => return JSC.Maybe(usize){ .err = bun.sys.Error.retry }, + .not_ready => return jsc.Maybe(usize){ .err = bun.sys.Error.retry }, } } @@ -339,12 +339,12 @@ pub fn PosixBufferedWriter(Parent: type, function_table: anytype) type { } } - pub fn start(this: *PosixWriter, fd: bun.FileDescriptor, pollable: bool) JSC.Maybe(void) { + pub fn start(this: *PosixWriter, fd: bun.FileDescriptor, pollable: bool) jsc.Maybe(void) { this.pollable = pollable; if (!pollable) { bun.assert(this.handle != .poll); this.handle = .{ .fd = fd }; - return JSC.Maybe(void){ .result = {} }; + return jsc.Maybe(void){ .result = {} }; } var poll = this.getPoll() orelse brk: { this.handle = .{ .poll = this.createPoll(fd) }; @@ -354,14 +354,14 @@ pub fn PosixBufferedWriter(Parent: type, function_table: anytype) type { switch (poll.registerWithFd(loop, .writable, .dispatch, fd)) { .err => |err| { - return JSC.Maybe(void){ .err = err }; + return jsc.Maybe(void){ .err = err }; }, .result => { this.enableKeepingProcessAlive(@as(*Parent, @ptrCast(this.parent)).eventLoop()); }, } - return JSC.Maybe(void){ .result = {} }; + return jsc.Maybe(void){ .result = {} }; } }; } @@ -695,19 +695,19 @@ pub fn PosixStreamingWriter(comptime Parent: type, comptime function_table: anyt return !this.is_done and poll.canEnableKeepingProcessAlive(); } - pub fn enableKeepingProcessAlive(this: *PosixWriter, event_loop: JSC.EventLoopHandle) void { + pub fn enableKeepingProcessAlive(this: *PosixWriter, event_loop: jsc.EventLoopHandle) void { if (this.is_done) return; const poll = this.getPoll() orelse return; poll.enableKeepingProcessAlive(event_loop); } - pub fn disableKeepingProcessAlive(this: *PosixWriter, event_loop: JSC.EventLoopHandle) void { + pub fn disableKeepingProcessAlive(this: *PosixWriter, event_loop: jsc.EventLoopHandle) void { const poll = this.getPoll() orelse return; poll.disableKeepingProcessAlive(event_loop); } - pub fn updateRef(this: *PosixWriter, event_loop: JSC.EventLoopHandle, value: bool) void { + pub fn updateRef(this: *PosixWriter, event_loop: jsc.EventLoopHandle, value: bool) void { if (value) { this.enableKeepingProcessAlive(event_loop); } else { @@ -735,11 +735,11 @@ pub fn PosixStreamingWriter(comptime Parent: type, comptime function_table: anyt this.handle.close(this.parent, onClose); } - pub fn start(this: *PosixWriter, fd: bun.FileDescriptor, is_pollable: bool) JSC.Maybe(void) { + pub fn start(this: *PosixWriter, fd: bun.FileDescriptor, is_pollable: bool) jsc.Maybe(void) { if (!is_pollable) { this.close(); this.handle = .{ .fd = fd }; - return JSC.Maybe(void){ .result = {} }; + return jsc.Maybe(void){ .result = {} }; } const loop = this.parent.eventLoop(); @@ -750,12 +750,12 @@ pub fn PosixStreamingWriter(comptime Parent: type, comptime function_table: anyt switch (poll.registerWithFd(loop.loop(), .writable, .dispatch, fd)) { .err => |err| { - return JSC.Maybe(void){ .err = err }; + return jsc.Maybe(void){ .err = err }; }, .result => {}, } - return JSC.Maybe(void){ .result = {} }; + return jsc.Maybe(void){ .result = {} }; } }; } @@ -766,7 +766,7 @@ pub fn PosixStreamingWriter(comptime Parent: type, comptime function_table: anyt /// source: ?Source = null, /// parent: *Parent = undefined, /// is_done: bool = false, -/// pub fn startWithCurrentPipe(this: *WindowsPipeWriter) bun.JSC.Maybe(void), +/// pub fn startWithCurrentPipe(this: *WindowsPipeWriter) bun.jsc.Maybe(void), /// fn onClosePipe(pipe: *uv.Pipe) callconv(.C) void, /// }; fn BaseWindowsPipeWriter( @@ -861,14 +861,14 @@ fn BaseWindowsPipeWriter( // no-op } - pub fn startWithPipe(this: *WindowsPipeWriter, pipe: *uv.Pipe) bun.JSC.Maybe(void) { + pub fn startWithPipe(this: *WindowsPipeWriter, pipe: *uv.Pipe) bun.jsc.Maybe(void) { bun.assert(this.source == null); this.source = .{ .pipe = pipe }; this.setParent(this.parent); return this.startWithCurrentPipe(); } - pub fn startSync(this: *WindowsPipeWriter, fd: bun.FileDescriptor, _: bool) bun.JSC.Maybe(void) { + pub fn startSync(this: *WindowsPipeWriter, fd: bun.FileDescriptor, _: bool) bun.jsc.Maybe(void) { bun.assert(this.source == null); const source = Source{ .sync_file = Source.openFile(fd), @@ -879,7 +879,7 @@ fn BaseWindowsPipeWriter( return this.startWithCurrentPipe(); } - pub fn startWithFile(this: *WindowsPipeWriter, fd: bun.FileDescriptor) bun.JSC.Maybe(void) { + pub fn startWithFile(this: *WindowsPipeWriter, fd: bun.FileDescriptor) bun.jsc.Maybe(void) { bun.assert(this.source == null); const source: bun.io.Source = .{ .file = Source.openFile(fd) }; source.setData(this); @@ -888,7 +888,7 @@ fn BaseWindowsPipeWriter( return this.startWithCurrentPipe(); } - pub fn start(this: *WindowsPipeWriter, fd: bun.FileDescriptor, _: bool) bun.JSC.Maybe(void) { + pub fn start(this: *WindowsPipeWriter, fd: bun.FileDescriptor, _: bool) bun.jsc.Maybe(void) { bun.assert(this.source == null); const source = switch (Source.open(uv.Loop.get(), fd)) { .result => |source| source, @@ -961,7 +961,7 @@ pub fn WindowsBufferedWriter(Parent: type, function_table: anytype) type { return @sizeOf(@This()) + this.write_buffer.len; } - pub fn startWithCurrentPipe(this: *WindowsWriter) bun.JSC.Maybe(void) { + pub fn startWithCurrentPipe(this: *WindowsWriter) bun.jsc.Maybe(void) { bun.assert(this.source != null); this.is_done = false; this.write(); @@ -1249,7 +1249,7 @@ pub fn WindowsStreamingWriter(comptime Parent: type, function_table: anytype) ty onClose(this.parent); } - pub fn startWithCurrentPipe(this: *WindowsWriter) bun.JSC.Maybe(void) { + pub fn startWithCurrentPipe(this: *WindowsWriter) bun.jsc.Maybe(void) { bun.assert(this.source != null); this.is_done = false; return .{ .result = {} }; @@ -1500,6 +1500,6 @@ const PollOrFd = @import("./pipes.zig").PollOrFd; const bun = @import("bun"); const Async = bun.Async; const Environment = bun.Environment; -const JSC = bun.JSC; const OOM = bun.OOM; +const jsc = bun.jsc; const uv = bun.windows.libuv; diff --git a/src/io/io.zig b/src/io/io.zig index 9782d257f8..ad9227f88e 100644 --- a/src/io/io.zig +++ b/src/io/io.zig @@ -621,7 +621,7 @@ pub const Poll = struct { } } - pub fn registerForEpoll(this: *Poll, tag: Pollable.Tag, loop: *Loop, comptime flag: Flags, one_shot: bool, fd: bun.FileDescriptor) JSC.Maybe(void) { + pub fn registerForEpoll(this: *Poll, tag: Pollable.Tag, loop: *Loop, comptime flag: Flags, one_shot: bool, fd: bun.FileDescriptor) jsc.Maybe(void) { const watcher_fd = loop.pollfd(); log("register: {s} ({})", .{ @tagName(flag), fd }); @@ -655,7 +655,7 @@ pub const Poll = struct { &event, ); - if (JSC.Maybe(void).errnoSys(ctl, .epoll_ctl)) |errno| { + if (jsc.Maybe(void).errnoSys(ctl, .epoll_ctl)) |errno| { return errno; } // Only mark if it successfully registered. @@ -675,7 +675,7 @@ pub const Poll = struct { }); this.flags.remove(.needs_rearm); - return JSC.Maybe(void).success; + return jsc.Maybe(void).success; } }; @@ -694,8 +694,8 @@ pub const MaxBuf = @import("./MaxBuf.zig"); const bun = @import("bun"); const Environment = bun.Environment; -const JSC = bun.JSC; const assert = bun.assert; +const jsc = bun.jsc; const sys = bun.sys; const ReadFile = bun.webcore.Blob.read_file.ReadFile; const WriteFile = bun.webcore.Blob.write_file.WriteFile; diff --git a/src/io/openForWriting.zig b/src/io/openForWriting.zig index 61028282e6..e577b00ec3 100644 --- a/src/io/openForWriting.zig +++ b/src/io/openForWriting.zig @@ -11,7 +11,7 @@ pub fn openForWriting( ctx: Ctx, comptime onForceSyncOrIsaTTY: *const fn (Ctx) void, comptime isPollable: *const fn (mode: bun.Mode) bool, -) JSC.Maybe(bun.FileDescriptor) { +) jsc.Maybe(bun.FileDescriptor) { return openForWritingImpl( dir, input_path, @@ -42,8 +42,8 @@ pub fn openForWritingImpl( ctx: Ctx, comptime onForceSyncOrIsaTTY: *const fn (Ctx) void, comptime isPollable: *const fn (mode: bun.Mode) bool, - comptime openat: *const fn (dir: bun.FileDescriptor, path: [:0]const u8, flags: i32, mode: bun.Mode) JSC.Maybe(bun.FileDescriptor), -) JSC.Maybe(bun.FileDescriptor) { + comptime openat: *const fn (dir: bun.FileDescriptor, path: [:0]const u8, flags: i32, mode: bun.Mode) jsc.Maybe(bun.FileDescriptor), +) jsc.Maybe(bun.FileDescriptor) { const PathT = @TypeOf(input_path); if (PathT != bun.webcore.PathOrFileDescriptor and PathT != [:0]const u8 and PathT != [:0]u8) { @compileError("Only string or PathOrFileDescriptor is supported but got: " ++ @typeName(PathT)); @@ -137,4 +137,4 @@ const std = @import("std"); const bun = @import("bun"); const Environment = bun.Environment; -const JSC = bun.JSC; +const jsc = bun.jsc; diff --git a/src/io/source.zig b/src/io/source.zig index 17e921d19d..1ebebd3d1f 100644 --- a/src/io/source.zig +++ b/src/io/source.zig @@ -98,7 +98,7 @@ pub const Source = union(enum) { }; } - pub fn openPipe(loop: *uv.Loop, fd: bun.FileDescriptor) bun.JSC.Maybe(*Source.Pipe) { + pub fn openPipe(loop: *uv.Loop, fd: bun.FileDescriptor) bun.jsc.Maybe(*Source.Pipe) { log("openPipe (fd = {})", .{fd}); const pipe = bun.default_allocator.create(Source.Pipe) catch bun.outOfMemory(); // we should never init using IPC here see ipc.zig @@ -122,7 +122,7 @@ pub const Source = union(enum) { pub var stdin_tty: uv.uv_tty_t = undefined; pub var stdin_tty_init = false; - pub fn openTty(loop: *uv.Loop, fd: bun.FileDescriptor) bun.JSC.Maybe(*Source.Tty) { + pub fn openTty(loop: *uv.Loop, fd: bun.FileDescriptor) bun.jsc.Maybe(*Source.Tty) { log("openTTY (fd = {})", .{fd}); const uv_fd = fd.uv(); @@ -156,7 +156,7 @@ pub const Source = union(enum) { return file; } - pub fn open(loop: *uv.Loop, fd: bun.FileDescriptor) bun.JSC.Maybe(Source) { + pub fn open(loop: *uv.Loop, fd: bun.FileDescriptor) bun.jsc.Maybe(Source) { const rc = bun.windows.libuv.uv_guess_handle(fd.uv()); log("open(fd: {}, type: {d})", .{ fd, @tagName(rc) }); @@ -220,7 +220,7 @@ pub const Source = union(enum) { }; export fn Source__setRawModeStdin(raw: bool) c_int { - const tty = switch (Source.openTty(bun.JSC.VirtualMachine.get().uvLoop(), .stdin())) { + const tty = switch (Source.openTty(bun.jsc.VirtualMachine.get().uvLoop(), .stdin())) { .result => |tty| tty, .err => |e| return e.errno, }; diff --git a/src/js/node/dns.ts b/src/js/node/dns.ts index 42b747c690..8bcb5d5f64 100644 --- a/src/js/node/dns.ts +++ b/src/js/node/dns.ts @@ -66,14 +66,14 @@ function setServers(servers) { } const getRuntimeDefaultResultOrderOption = $newZigFunction( - "dns_resolver.zig", - "DNSResolver.getRuntimeDefaultResultOrderOption", + "bun.js/api/bun/dns.zig", + "Resolver.getRuntimeDefaultResultOrderOption", 0, ); function newResolver(options) { if (!newResolver.zig) { - newResolver.zig = $newZigFunction("dns_resolver.zig", "DNSResolver.newResolver", 1); + newResolver.zig = $newZigFunction("bun.js/api/bun/dns.zig", "Resolver.newResolver", 1); } return newResolver.zig(options); } diff --git a/src/js/node/fs.ts b/src/js/node/fs.ts index 4ca4cbffbb..0bbc0d8849 100644 --- a/src/js/node/fs.ts +++ b/src/js/node/fs.ts @@ -731,7 +731,10 @@ const realpathSync: typeof import("node:fs").realpathSync = if (options) { if (typeof options === "string") encoding = options; else encoding = options?.encoding; - encoding && (assertEncodingForWindows ?? $newZigFunction("types.zig", "jsAssertEncodingValid", 1))(encoding); + encoding && + (assertEncodingForWindows ?? $newZigFunction("bun.js/node/types.zig", "jsAssertEncodingValid", 1))( + encoding, + ); } // This function is ported 1:1 from node.js, to emulate how it is unable to // resolve subst drives to their underlying location. The native call is @@ -849,7 +852,10 @@ const realpath: typeof import("node:fs").realpath = if (options) { if (typeof options === "string") encoding = options; else encoding = options?.encoding; - encoding && (assertEncodingForWindows ?? $newZigFunction("types.zig", "jsAssertEncodingValid", 1))(encoding); + encoding && + (assertEncodingForWindows ?? $newZigFunction("bun.js/node/types.zig", "jsAssertEncodingValid", 1))( + encoding, + ); } if (p instanceof URL) { if (p.pathname.indexOf("%00") != -1) { diff --git a/src/js_lexer.zig b/src/js_lexer.zig index 2b7b5b094a..2f3113c51b 100644 --- a/src/js_lexer.zig +++ b/src/js_lexer.zig @@ -3364,6 +3364,8 @@ fn indexOfInterestingCharacterInStringLiteral(text_: []const u8, quote: u8) ?usi return bun.highway.indexOfInterestingCharacterInStringLiteral(text_, quote); } +const string = []const u8; + const FeatureFlags = @import("./feature_flags.zig"); const JSIdentifier = @import("./js_lexer/identifier.zig"); const tables = @import("./js_lexer_tables.zig"); @@ -3373,8 +3375,7 @@ const CodePoint = bun.CodePoint; const Environment = bun.Environment; const MutableString = bun.MutableString; const Output = bun.Output; -const js_ast = bun.JSAst; -const string = bun.string; +const js_ast = bun.ast; const strings = bun.strings; const Indentation = bun.js_printer.Options.Indentation; diff --git a/src/js_lexer_tables.zig b/src/js_lexer_tables.zig index 0a11fd077f..e1d4cbc997 100644 --- a/src/js_lexer_tables.zig +++ b/src/js_lexer_tables.zig @@ -798,10 +798,10 @@ pub const jsxEntity = ComptimeStringMap(CodePoint, .{ .{ "zwnj", @as(CodePoint, 0x200C) }, }); -const std = @import("std"); +const string = []const u8; -const CodePoint = @import("./string_types.zig").CodePoint; -const string = @import("./string_types.zig").string; +const std = @import("std"); const bun = @import("bun"); const ComptimeStringMap = bun.ComptimeStringMap; +const CodePoint = bun.strings.CodePoint; diff --git a/src/js_parser.zig b/src/js_parser.zig index 6bc4f2d803..f99faf5c88 100644 --- a/src/js_parser.zig +++ b/src/js_parser.zig @@ -6,7 +6,7 @@ pub const std = @import("std"); pub const logger = bun.logger; pub const js_lexer = bun.js_lexer; pub const importRecord = @import("./import_record.zig"); -pub const js_ast = bun.JSAst; +pub const js_ast = bun.ast; pub const options = @import("./options.zig"); pub const js_printer = bun.js_printer; pub const renamer = @import("./renamer.zig"); @@ -3286,7 +3286,7 @@ pub const Parser = struct { // We must check the cache only after we've consumed the hashbang and leading // @bun pragma // We don't want to ever put files with `// @bun` into this cache, as that would be wasteful. if (comptime Environment.isNative and bun.FeatureFlags.runtime_transpiler_cache) { - const runtime_transpiler_cache: ?*bun.JSC.RuntimeTranspilerCache = p.options.features.runtime_transpiler_cache; + const runtime_transpiler_cache: ?*bun.jsc.RuntimeTranspilerCache = p.options.features.runtime_transpiler_cache; if (runtime_transpiler_cache) |cache| { if (cache.get(p.source, &p.options, p.options.jsx.parse and (!p.source.path.isNodeModule() or p.source.path.isJSXFile()))) { return js_ast.Result{ @@ -4276,7 +4276,7 @@ pub const Parser = struct { // p.popScope(); if (comptime Environment.isNative and bun.FeatureFlags.runtime_transpiler_cache) { - const runtime_transpiler_cache: ?*bun.JSC.RuntimeTranspilerCache = p.options.features.runtime_transpiler_cache; + const runtime_transpiler_cache: ?*bun.jsc.RuntimeTranspilerCache = p.options.features.runtime_transpiler_cache; if (runtime_transpiler_cache) |cache| { if (p.macro_call_count != 0) { // disable this for: @@ -7466,7 +7466,7 @@ fn NewParser_( .bin_pow => { if (p.should_fold_typescript_constant_expressions) { if (Expr.extractNumericValues(e_.left.data, e_.right.data)) |vals| { - return p.newExpr(E.Number{ .value = JSC.math.pow(vals[0], vals[1]) }, v.loc); + return p.newExpr(E.Number{ .value = jsc.math.pow(vals[0], vals[1]) }, v.loc); } } }, @@ -18823,7 +18823,7 @@ fn NewParser_( // Inline import.meta.url as file:// URL const bunstr = bun.String.fromBytes(p.source.path.text); defer bunstr.deref(); - const url = std.fmt.allocPrint(p.allocator, "{s}", .{JSC.URL.fileURLFromString(bunstr)}) catch unreachable; + const url = std.fmt.allocPrint(p.allocator, "{s}", .{jsc.URL.fileURLFromString(bunstr)}) catch unreachable; return p.newExpr(E.String.init(url), name_loc); } } @@ -24902,22 +24902,23 @@ fn floatToInt32(f: f64) i32 { return if (f < 0) @as(i32, 0) -% int else int; } +const string = []const u8; + const FeatureFlags = @import("./feature_flags.zig"); const _runtime = @import("./runtime.zig"); const ObjectPool = @import("./pool.zig").ObjectPool; -const Index = @import("./ast/base.zig").Index; -const Ref = @import("./ast/base.zig").Ref; -const RefCtx = @import("./ast/base.zig").RefCtx; - const Define = @import("./defines.zig").Define; const DefineData = @import("./defines.zig").DefineData; const bun = @import("bun"); const Environment = bun.Environment; -const JSC = bun.JSC; const Output = bun.Output; const StringHashMapUnmanaged = bun.StringHashMapUnmanaged; const default_allocator = bun.default_allocator; -const string = bun.string; +const jsc = bun.jsc; const strings = bun.strings; + +const Index = bun.ast.Index; +const Ref = bun.ast.Ref; +const RefCtx = bun.ast.RefCtx; diff --git a/src/js_printer.zig b/src/js_printer.zig index c16358f99d..5d304f8def 100644 --- a/src/js_printer.zig +++ b/src/js_printer.zig @@ -400,10 +400,10 @@ pub const Options = struct { source_map_allocator: ?std.mem.Allocator = null, source_map_handler: ?SourceMapHandler = null, source_map_builder: ?*bun.sourcemap.Chunk.Builder = null, - css_import_behavior: Api.CssInJsBehavior = Api.CssInJsBehavior.facade, + css_import_behavior: api.CssInJsBehavior = api.CssInJsBehavior.facade, target: options.Target = .browser, - runtime_transpiler_cache: ?*bun.JSC.RuntimeTranspilerCache = null, + runtime_transpiler_cache: ?*bun.jsc.RuntimeTranspilerCache = null, input_files_for_dev_server: ?[]logger.Source = null, commonjs_named_exports: js_ast.Ast.CommonJSNamedExports = .{}, @@ -6071,6 +6071,8 @@ pub fn printCommonJS( return @as(usize, @intCast(@max(printer.writer.written, 0))); } +const string = []const u8; + const SourceMap = @import("./sourcemap/sourcemap.zig"); const fs = @import("./fs.zig"); const importRecord = @import("./import_record.zig"); @@ -6078,9 +6080,6 @@ const options = @import("./options.zig"); const rename = @import("./renamer.zig"); const runtime = @import("./runtime.zig"); const std = @import("std"); -const Api = @import("./api/schema.zig").Api; -const CodepointIterator = @import("./string_immutable.zig").UnsignedCodepointIterator; -const Ref = @import("./ast/base.zig").Ref; const bun = @import("bun"); const Environment = bun.Environment; @@ -6094,19 +6093,22 @@ const assert = bun.assert; const default_allocator = bun.default_allocator; const js_lexer = bun.js_lexer; const logger = bun.logger; -const string = bun.string; -const strings = bun.strings; +const api = bun.schema.api; -const js_ast = bun.JSAst; +const js_ast = bun.ast; const Ast = js_ast.Ast; const B = js_ast.B; const Binding = js_ast.Binding; const E = js_ast.E; const Expr = js_ast.Expr; const G = js_ast.G; +const Ref = bun.ast.Ref; const S = js_ast.S; const Stmt = js_ast.Stmt; const Symbol = js_ast.Symbol; const Op = js_ast.Op; const Level = js_ast.Op.Level; + +const strings = bun.strings; +const CodepointIterator = bun.strings.UnsignedCodepointIterator; diff --git a/src/libarchive/libarchive.zig b/src/libarchive/libarchive.zig index 4fa56d474d..6d7d3ae172 100644 --- a/src/libarchive/libarchive.zig +++ b/src/libarchive/libarchive.zig @@ -612,6 +612,8 @@ pub const Archiver = struct { } }; +const string = []const u8; + const std = @import("std"); const bun = @import("bun"); @@ -621,5 +623,4 @@ const MutableString = bun.MutableString; const Output = bun.Output; const c = bun.c; const default_allocator = bun.default_allocator; -const string = bun.string; const strings = bun.strings; diff --git a/src/linker.zig b/src/linker.zig index 01d5d2e52e..13c1316405 100644 --- a/src/linker.zig +++ b/src/linker.zig @@ -146,7 +146,7 @@ pub const Linker = struct { } if (comptime is_bun) { - if (JSC.ModuleLoader.HardcodedModule.Alias.get(import_record.path.text, linker.options.target)) |replacement| { + if (jsc.ModuleLoader.HardcodedModule.Alias.get(import_record.path.text, linker.options.target)) |replacement| { if (replacement.tag == .builtin and import_record.kind.isCommonJS()) continue; import_record.path.text = replacement.path; @@ -205,11 +205,11 @@ pub const Linker = struct { linker.log, import_record.range.loc, if (is_bun) - JSC.JSGlobalObject.BunPluginTarget.bun + jsc.JSGlobalObject.BunPluginTarget.bun else if (linker.options.target == .browser) - JSC.JSGlobalObject.BunPluginTarget.browser + jsc.JSGlobalObject.BunPluginTarget.browser else - JSC.JSGlobalObject.BunPluginTarget.node, + jsc.JSGlobalObject.BunPluginTarget.node, )) |path| { import_record.path = try linker.generateImportPath( source_dir, @@ -420,9 +420,10 @@ pub const Linker = struct { } }; +const string = []const u8; + const Fs = @import("./fs.zig"); const Options = @import("./options.zig"); -const allocators = @import("./allocators.zig"); const std = @import("std"); const URL = @import("./url.zig").URL; @@ -435,9 +436,9 @@ const ResolverType = Resolver.Resolver; const bun = @import("bun"); const Environment = bun.Environment; const FileDescriptorType = bun.FileDescriptor; -const JSC = bun.JSC; +const allocators = bun.allocators; +const jsc = bun.jsc; const logger = bun.logger; -const string = bun.string; const strings = bun.strings; const _transpiler = bun.transpiler; diff --git a/src/linux.zig b/src/linux.zig index e29b8d257b..afe636afe4 100644 --- a/src/linux.zig +++ b/src/linux.zig @@ -3,7 +3,7 @@ //! If an API can be implemented on multiple platforms, //! it does not belong in this namespace. -pub const memfd_allocator = @import("./allocators/linux_memfd_allocator.zig").LinuxMemFdAllocator; +pub const MemFdAllocator = bun.allocators.LinuxMemFdAllocator; /// splice() moves data between two file descriptors without copying /// between kernel address space and user address space. It diff --git a/src/logger.zig b/src/logger.zig index ebc00e989d..70c665f5df 100644 --- a/src/logger.zig +++ b/src/logger.zig @@ -20,7 +20,7 @@ pub const Kind = enum(u8) { }; } - pub inline fn string(self: Kind) bun.string { + pub inline fn string(self: Kind) []const u8 { return switch (self) { .err => "error", .warn => "warn", @@ -30,7 +30,7 @@ pub const Kind = enum(u8) { }; } - pub inline fn toAPI(kind: Kind) Api.MessageLevel { + pub inline fn toAPI(kind: Kind) api.MessageLevel { return switch (kind) { .err => .err, .warn => .warn, @@ -133,8 +133,8 @@ pub const Location = struct { }; } - pub fn toAPI(this: *const Location) Api.Location { - return Api.Location{ + pub fn toAPI(this: *const Location) api.Location { + return api.Location{ .file = this.file, .namespace = this.namespace, .line = this.line, @@ -247,8 +247,8 @@ pub const Data = struct { if (this.location) |loc| loc.count(builder); } - pub fn toAPI(this: *const Data) Api.MessageData { - return Api.MessageData{ + pub fn toAPI(this: *const Data) api.MessageData { + return api.MessageData{ .text = this.text, .location = if (this.location != null) this.location.?.toAPI() else null, }; @@ -401,8 +401,8 @@ pub const Msg = struct { return cost; } - pub fn fromJS(allocator: std.mem.Allocator, globalObject: *bun.JSC.JSGlobalObject, file: string, err: bun.JSC.JSValue) bun.JSError!Msg { - var zig_exception_holder: bun.JSC.ZigException.Holder = bun.JSC.ZigException.Holder.init(); + pub fn fromJS(allocator: std.mem.Allocator, globalObject: *bun.jsc.JSGlobalObject, file: string, err: bun.jsc.JSValue) bun.JSError!Msg { + var zig_exception_holder: bun.jsc.ZigException.Holder = bun.jsc.ZigException.Holder.init(); if (err.toError()) |value| { value.toZigException(globalObject, zig_exception_holder.zigException()); } else { @@ -421,7 +421,7 @@ pub const Msg = struct { }; } - pub fn toJS(this: Msg, globalObject: *bun.JSC.JSGlobalObject, allocator: std.mem.Allocator) bun.OOM!JSC.JSValue { + pub fn toJS(this: Msg, globalObject: *bun.jsc.JSGlobalObject, allocator: std.mem.Allocator) bun.OOM!jsc.JSValue { return switch (this.metadata) { .build => bun.api.BuildMessage.create(globalObject, allocator, this), .resolve => bun.api.ResolveMessage.create(globalObject, allocator, this, ""), @@ -469,16 +469,16 @@ pub const Msg = struct { }; }; - pub fn toAPI(this: *const Msg, allocator: std.mem.Allocator) OOM!Api.Message { + pub fn toAPI(this: *const Msg, allocator: std.mem.Allocator) OOM!api.Message { var notes = try allocator.alloc( - Api.MessageData, + api.MessageData, this.notes.len, ); - const msg = Api.Message{ + const msg = api.Message{ .level = this.kind.toAPI(), .data = this.data.toAPI(), .notes = notes, - .on = Api.MessageMeta{ + .on = api.MessageMeta{ .resolve = if (this.metadata == .resolve) this.metadata.resolve.specifier.slice(this.data.text) else "", .build = this.metadata == .build, }, @@ -491,8 +491,8 @@ pub const Msg = struct { return msg; } - pub fn toAPIFromList(comptime ListType: type, list: ListType, allocator: std.mem.Allocator) OOM![]Api.Message { - var out_list = try allocator.alloc(Api.Message, list.items.len); + pub fn toAPIFromList(comptime ListType: type, list: ListType, allocator: std.mem.Allocator) OOM![]api.Message { + var out_list = try allocator.alloc(api.Message, list.items.len); for (list.items, 0..) |item, i| { out_list[i] = try item.toAPI(allocator); } @@ -634,7 +634,7 @@ pub const Log = struct { return (this.warnings + this.errors) > 0; } - pub fn toAPI(this: *const Log, allocator: std.mem.Allocator) !Api.Log { + pub fn toAPI(this: *const Log, allocator: std.mem.Allocator) !api.Log { var warnings: u32 = 0; var errors: u32 = 0; for (this.msgs.items) |msg| { @@ -642,7 +642,7 @@ pub const Log = struct { warnings += @as(u32, @intCast(@intFromBool(msg.kind == .warn))); } - return Api.Log{ + return api.Log{ .warnings = warnings, .errors = errors, .msgs = try Msg.toAPIFromList(@TypeOf(this.msgs), this.msgs, allocator), @@ -677,7 +677,7 @@ pub const Log = struct { .{ "error", Level.err }, }); - pub fn fromJS(globalThis: *JSC.JSGlobalObject, value: JSC.JSValue) JSError!?Level { + pub fn fromJS(globalThis: *jsc.JSGlobalObject, value: jsc.JSValue) JSError!?Level { if (value == .zero or value.isUndefined()) { return null; } @@ -723,9 +723,9 @@ pub const Log = struct { } } - pub fn toJS(this: Log, global: *JSC.JSGlobalObject, allocator: std.mem.Allocator, message: string) bun.JSError!JSC.JSValue { + pub fn toJS(this: Log, global: *jsc.JSGlobalObject, allocator: std.mem.Allocator, message: string) bun.JSError!jsc.JSValue { const msgs: []const Msg = this.msgs.items; - var errors_stack: [256]JSC.JSValue = undefined; + var errors_stack: [256]jsc.JSValue = undefined; const count = @as(u16, @intCast(@min(msgs.len, errors_stack.len))); switch (count) { @@ -744,7 +744,7 @@ pub const Log = struct { .resolve => try bun.api.ResolveMessage.create(global, allocator, msg, ""), }; } - const out = JSC.ZigString.init(message); + const out = jsc.ZigString.init(message); const agg = try global.createAggregateError(errors_stack[0..count], &out); return agg; }, @@ -752,14 +752,14 @@ pub const Log = struct { } /// unlike toJS, this always produces an AggregateError object - pub fn toJSAggregateError(this: Log, global: *JSC.JSGlobalObject, message: bun.String) bun.JSError!JSC.JSValue { + pub fn toJSAggregateError(this: Log, global: *jsc.JSGlobalObject, message: bun.String) bun.JSError!jsc.JSValue { return global.createAggregateErrorWithArray(message, try this.toJSArray(global, bun.default_allocator)); } - pub fn toJSArray(this: Log, global: *JSC.JSGlobalObject, allocator: std.mem.Allocator) bun.JSError!JSC.JSValue { + pub fn toJSArray(this: Log, global: *jsc.JSGlobalObject, allocator: std.mem.Allocator) bun.JSError!jsc.JSValue { const msgs: []const Msg = this.msgs.items; - const arr = try JSC.JSValue.createEmptyArray(global, msgs.len); + const arr = try jsc.JSValue.createEmptyArray(global, msgs.len); for (msgs, 0..) |msg, i| { try arr.putIndex(global, @as(u32, @intCast(i)), try msg.toJS(global, allocator)); } @@ -1603,21 +1603,22 @@ pub fn rangeData(source: ?*const Source, r: Range, text: string) Data { return Data{ .text = text, .location = Location.initOrNull(source, r) }; } +const string = []const u8; + const fs = @import("./fs.zig"); const std = @import("std"); -const Api = @import("./api/schema.zig").Api; const ImportKind = @import("./import_record.zig").ImportKind; -const Index = @import("./ast/base.zig").Index; const bun = @import("bun"); const Environment = bun.Environment; -const JSC = bun.JSC; const JSError = bun.JSError; const OOM = bun.OOM; const Output = bun.Output; const StringBuilder = bun.StringBuilder; const assert = bun.assert; const default_allocator = bun.default_allocator; -const js = bun.JSC; -const string = bun.string; +const js = bun.jsc; +const jsc = bun.jsc; const strings = bun.strings; +const Index = bun.ast.Index; +const api = bun.schema.api; diff --git a/src/main.zig b/src/main.zig index bfdcbd5745..1000c0134a 100644 --- a/src/main.zig +++ b/src/main.zig @@ -35,10 +35,10 @@ pub fn main() void { // So it's safest to put it very early in the main function. if (Environment.isWindows) { _ = bun.windows.libuv.uv_replace_allocator( - &bun.Mimalloc.mi_malloc, - &bun.Mimalloc.mi_realloc, - &bun.Mimalloc.mi_calloc, - &bun.Mimalloc.mi_free, + &bun.mimalloc.mi_malloc, + &bun.mimalloc.mi_realloc, + &bun.mimalloc.mi_calloc, + &bun.mimalloc.mi_free, ); environ = @ptrCast(std.os.environ.ptr); _environ = @ptrCast(std.os.environ.ptr); @@ -52,12 +52,12 @@ pub fn main() void { Output.Source.Stdio.init(); defer Output.flush(); if (Environment.isX64 and Environment.enableSIMD and Environment.isPosix) { - bun_warn_avx_missing(bun.CLI.UpgradeCommand.Bun__githubBaselineURL.ptr); + bun_warn_avx_missing(bun.cli.UpgradeCommand.Bun__githubBaselineURL.ptr); } bun.StackCheck.configureThread(); - bun.CLI.Cli.start(bun.default_allocator); + bun.cli.Cli.start(bun.default_allocator); bun.Global.exit(0); } diff --git a/src/main_test.zig b/src/main_test.zig index e27f7285c3..748d37af5b 100644 --- a/src/main_test.zig +++ b/src/main_test.zig @@ -23,10 +23,10 @@ pub fn main() void { // So it's safest to put it very early in the main function. if (Environment.isWindows) { _ = bun.windows.libuv.uv_replace_allocator( - @ptrCast(&bun.Mimalloc.mi_malloc), - @ptrCast(&bun.Mimalloc.mi_realloc), - @ptrCast(&bun.Mimalloc.mi_calloc), - @ptrCast(&bun.Mimalloc.mi_free), + @ptrCast(&bun.mimalloc.mi_malloc), + @ptrCast(&bun.mimalloc.mi_realloc), + @ptrCast(&bun.mimalloc.mi_calloc), + @ptrCast(&bun.mimalloc.mi_free), ); environ = @ptrCast(std.os.environ.ptr); _environ = @ptrCast(std.os.environ.ptr); diff --git a/src/main_wasm.zig b/src/main_wasm.zig index d802f0ad94..9e017bdb3e 100644 --- a/src/main_wasm.zig +++ b/src/main_wasm.zig @@ -146,8 +146,8 @@ pub const system = struct { export fn cycleStart() void {} export fn cycleEnd() void {} -var transform_response: Api.TransformResponse = std.mem.zeroes(Api.TransformResponse); -var output_files: [1]Api.OutputFile = undefined; +var transform_response: api.TransformResponse = std.mem.zeroes(api.TransformResponse); +var output_files: [1]api.OutputFile = undefined; var buffer_writer: JSPrinter.BufferWriter = undefined; var writer: JSPrinter.BufferPrinter = undefined; var define: *Define.Define = undefined; @@ -169,14 +169,13 @@ var error_stream = std.io.fixedBufferStream(&error_stream_buf); var output_source: global.Output.Source = undefined; var init_counter: usize = 0; export fn init(heapsize: u32) void { - const Mimalloc = @import("./allocators/mimalloc.zig"); defer init_counter +%= 1; if (init_counter == 0) { // reserve 256 MB upfront - Mimalloc.mi_option_set(.allow_decommit, 0); - Mimalloc.mi_option_set(.limit_os_alloc, 1); - _ = Mimalloc.mi_reserve_os_memory(heapsize, false, true); + mimalloc.mi_option_set(.allow_decommit, 0); + mimalloc.mi_option_set(.limit_os_alloc, 1); + _ = mimalloc.mi_reserve_os_memory(heapsize, false, true); JSAst.Stmt.Data.Store.create(default_allocator); JSAst.Expr.Data.Store.create(default_allocator); @@ -195,7 +194,7 @@ var log: Logger.Log = undefined; const TestAnalyzer = struct { string_buffer: std.ArrayList(u8), - items: std.ArrayList(Api.TestResponseItem), + items: std.ArrayList(api.TestResponseItem), pub fn visitExpr(this: *TestAnalyzer, parser: *bun.js_parser.TSXParser, expr: JSAst.Expr) !void { switch (expr.data) { @@ -206,14 +205,14 @@ const TestAnalyzer = struct { switch (label_expr.data) { .e_string => |str| { try str.toUTF8(this.string_buffer.allocator); - const ptr = Api.StringPointer{ + const ptr = api.StringPointer{ .offset = this.string_buffer.items.len, .length = str.data.len, }; try this.string_buffer.appendSlice(str.data); - try this.items.append(Api.TestResponseItem{ + try this.items.append(api.TestResponseItem{ .byte_offset = expr.loc.start, - .kind = if (call.target.isRef(parser.jest.describe)) Api.TestKind.describe_fn else .test_fn, + .kind = if (call.target.isRef(parser.jest.describe)) api.TestKind.describe_fn else .test_fn, .label = ptr, }); }, @@ -231,14 +230,14 @@ const TestAnalyzer = struct { switch (label_expr.data) { .e_string => |str| { try str.toUTF8(this.string_buffer.allocator); - const ptr = Api.StringPointer{ + const ptr = api.StringPointer{ .offset = this.string_buffer.items.len, .length = str.data.len, }; try this.string_buffer.appendSlice(str.data); - try this.items.append(Api.TestResponseItem{ + try this.items.append(api.TestResponseItem{ .byte_offset = expr.loc.start, - .kind = if (target.isRef(parser.jest.describe)) Api.TestKind.describe_fn else .test_fn, + .kind = if (target.isRef(parser.jest.describe)) api.TestKind.describe_fn else .test_fn, .label = ptr, }); }, @@ -393,7 +392,7 @@ const TestAnalyzer = struct { .s_import => |import| { if (bun.strings.eqlComptime(parser.import_records.items[import.import_record_index].path.text, "bun:test")) { for (import.items) |item| { - const clause: bun.JSAst.ClauseItem = item; + const clause: bun.ast.ClauseItem = item; if (bun.strings.eqlComptime(clause.alias, "test")) { parser.jest.@"test" = clause.name.ref.?; } else if (bun.strings.eqlComptime(clause.alias, "it")) { @@ -411,7 +410,7 @@ const TestAnalyzer = struct { pub fn visitParts( this: *TestAnalyzer, parser: *bun.js_parser.TSXParser, - parts: []bun.JSAst.Part, + parts: []bun.ast.Part, ) anyerror!void { var jest = &parser.jest; if (parser.symbols.items[jest.it.innerIndex()].use_count_estimate == 0) { @@ -437,7 +436,7 @@ export fn getTests(opts_array: u64) u64 { defer arena.deinit(); var log_ = Logger.Log.init(allocator); var reader = ApiReader.init(Uint8Array.fromJS(opts_array), allocator); - var opts = Api.GetTestsRequest.decode(&reader) catch bun.outOfMemory(); + var opts = api.GetTestsRequest.decode(&reader) catch bun.outOfMemory(); var code = Logger.Source.initPathString(if (opts.path.len > 0) opts.path else "my-test-file.test.tsx", opts.contents); code.contents_is_recycled = true; defer { @@ -452,7 +451,7 @@ export fn getTests(opts_array: u64) u64 { var anaylzer = TestAnalyzer{ .items = std.ArrayList( - Api.TestResponseItem, + api.TestResponseItem, ).init(allocator), .string_buffer = std.ArrayList( u8, @@ -475,7 +474,7 @@ export fn getTests(opts_array: u64) u64 { var output_writer = output.writer(); const Encoder = ApiWriter(@TypeOf(output_writer)); var encoder = Encoder.init(output_writer); - var response = Api.GetTestsResponse{ + var response = api.GetTestsResponse{ .tests = anaylzer.items.items, .contents = anaylzer.string_buffer.items, }; @@ -492,8 +491,8 @@ export fn transform(opts_array: u64) u64 { log = Logger.Log.init(allocator); var reader = ApiReader.init(Uint8Array.fromJS(opts_array), allocator); - var opts = Api.Transform.decode(&reader) catch unreachable; - const loader_ = opts.loader orelse Api.Loader.tsx; + var opts = api.Transform.decode(&reader) catch unreachable; + const loader_ = opts.loader orelse api.Loader.tsx; defer { JSAst.Stmt.Data.Store.reset(); @@ -540,8 +539,8 @@ export fn transform(opts_array: u64) u64 { output_files[0] = .{ .data = "", .path = path }; } - transform_response = Api.TransformResponse{ - .status = if (result == .ast and log.errors == 0) Api.TransformResponseStatus.success else Api.TransformResponseStatus.fail, + transform_response = api.TransformResponse{ + .status = if (result == .ast and log.errors == 0) api.TransformResponseStatus.success else api.TransformResponseStatus.fail, .files = &output_files, .errors = (log.toAPI(allocator) catch unreachable).msgs, }; @@ -562,8 +561,8 @@ export fn scan(opts_array: u64) u64 { log = Logger.Log.init(allocator); var reader = ApiReader.init(Uint8Array.fromJS(opts_array), allocator); - var opts = Api.Scan.decode(&reader) catch unreachable; - const loader_ = opts.loader orelse Api.Loader.tsx; + var opts = api.Scan.decode(&reader) catch unreachable; + const loader_ = opts.loader orelse api.Loader.tsx; defer { JSAst.Stmt.Data.Store.reset(); @@ -588,21 +587,21 @@ export fn scan(opts_array: u64) u64 { parser.options.features.top_level_await = true; const result = parser.parse() catch unreachable; if (log.errors == 0) { - var scan_result = std.mem.zeroes(Api.ScanResult); + var scan_result = std.mem.zeroes(api.ScanResult); var output = std.ArrayList(u8).init(default_allocator); var output_writer = output.writer(); const Encoder = ApiWriter(@TypeOf(output_writer)); if (result == .ast) { - var scanned_imports = allocator.alloc(Api.ScannedImport, result.ast.import_records.len) catch unreachable; + var scanned_imports = allocator.alloc(api.ScannedImport, result.ast.import_records.len) catch unreachable; var scanned_i: usize = 0; for (result.ast.import_records.slice()) |import_record| { if (import_record.kind == .internal) continue; - scanned_imports[scanned_i] = Api.ScannedImport{ .path = import_record.path.text, .kind = import_record.kind.toAPI() }; + scanned_imports[scanned_i] = api.ScannedImport{ .path = import_record.path.text, .kind = import_record.kind.toAPI() }; scanned_i += 1; } - scan_result = Api.ScanResult{ + scan_result = api.ScanResult{ .exports = result.ast.named_exports.keys(), .imports = scanned_imports[0..scanned_i], .errors = (log.toAPI(allocator) catch unreachable).msgs, @@ -616,7 +615,7 @@ export fn scan(opts_array: u64) u64 { var output = std.ArrayList(u8).init(default_allocator); var output_writer = output.writer(); const Encoder = ApiWriter(@TypeOf(output_writer)); - var scan_result = Api.ScanResult{ + var scan_result = api.ScanResult{ .exports = &.{}, .imports = &.{}, .errors = (log.toAPI(allocator) catch unreachable).msgs, @@ -653,17 +652,18 @@ comptime { const Define = @import("./defines.zig"); const Options = @import("./options.zig"); const std = @import("std"); -const Arena = @import("./allocators/mimalloc_arena.zig").Arena; - -const Api = @import("./api/schema.zig").Api; -const ApiReader = @import("./api/schema.zig").Reader; -const ApiWriter = @import("./api/schema.zig").Writer; const bun = @import("bun"); const global = @import("bun"); -const JSAst = bun.JSAst; +const JSAst = bun.ast; const JSParser = bun.js_parser; const JSPrinter = bun.js_printer; const Logger = bun.logger; const Output = global.Output; const default_allocator = global.default_allocator; +const mimalloc = bun.mimalloc; +const Arena = bun.allocators.MimallocArena; + +const ApiReader = bun.schema.Reader; +const ApiWriter = bun.schema.Writer; +const api = bun.schema.api; diff --git a/src/napi/napi.zig b/src/napi/napi.zig index 7e85a53cec..d7cca564a7 100644 --- a/src/napi/napi.zig +++ b/src/napi/napi.zig @@ -1,10 +1,10 @@ -const TODO_EXCEPTION: JSC.C.ExceptionRef = null; +const TODO_EXCEPTION: jsc.C.ExceptionRef = null; const log = bun.Output.scoped(.napi, false); /// This is `struct napi_env__` from napi.h pub const NapiEnv = opaque { - pub fn toJS(self: *NapiEnv) *JSC.JSGlobalObject { + pub fn toJS(self: *NapiEnv) *jsc.JSGlobalObject { return NapiEnv__globalObject(self); } @@ -46,7 +46,7 @@ pub const NapiEnv = opaque { return napi_internal_get_version(self); } - extern fn NapiEnv__globalObject(*NapiEnv) *JSC.JSGlobalObject; + extern fn NapiEnv__globalObject(*NapiEnv) *jsc.JSGlobalObject; extern fn napi_internal_get_version(*NapiEnv) u32; }; @@ -70,8 +70,8 @@ pub const napi_ref = *Ref; pub const NapiHandleScope = opaque { pub extern fn NapiHandleScope__open(env: *NapiEnv, escapable: bool) ?*NapiHandleScope; pub extern fn NapiHandleScope__close(env: *NapiEnv, current: ?*NapiHandleScope) void; - extern fn NapiHandleScope__append(env: *NapiEnv, value: JSC.JSValue.backing_int) void; - extern fn NapiHandleScope__escape(handleScope: *NapiHandleScope, value: JSC.JSValue.backing_int) bool; + extern fn NapiHandleScope__append(env: *NapiEnv, value: jsc.JSValue.backing_int) void; + extern fn NapiHandleScope__escape(handleScope: *NapiHandleScope, value: jsc.JSValue.backing_int) bool; /// Create a new handle scope in the given environment, or return null if creating one now is /// unsafe (i.e. inside a finalizer) @@ -88,14 +88,14 @@ pub const NapiHandleScope = opaque { /// Place a value in the handle scope. Must be done while returning any JS value into NAPI /// callbacks, as the value must remain alive as long as the handle scope is active, even if the /// native module doesn't keep it visible on the stack. - pub fn append(env: *NapiEnv, value: JSC.JSValue) void { + pub fn append(env: *NapiEnv, value: jsc.JSValue) void { NapiHandleScope__append(env, @intFromEnum(value)); } /// Move a value from the current handle scope (which must be escapable) to the reserved escape /// slot in the parent handle scope, allowing that value to outlive the current handle scope. /// Returns an error if escape() has already been called on this handle scope. - pub fn escape(self: *NapiHandleScope, value: JSC.JSValue) error{EscapeCalledTwice}!void { + pub fn escape(self: *NapiHandleScope, value: jsc.JSValue) error{EscapeCalledTwice}!void { if (!NapiHandleScope__escape(self, @intFromEnum(value))) { return error.EscapeCalledTwice; } @@ -104,28 +104,28 @@ pub const NapiHandleScope = opaque { pub const napi_handle_scope = ?*NapiHandleScope; pub const napi_escapable_handle_scope = ?*NapiHandleScope; -pub const napi_callback_info = *JSC.CallFrame; -pub const napi_deferred = *JSC.JSPromise.Strong; +pub const napi_callback_info = *jsc.CallFrame; +pub const napi_deferred = *jsc.JSPromise.Strong; /// To ensure napi_values are not collected prematurely after being returned into a native module, -/// you must use these functions rather than convert between napi_value and JSC.JSValue directly +/// you must use these functions rather than convert between napi_value and jsc.JSValue directly pub const napi_value = enum(i64) { _, pub fn set( self: *napi_value, env: *NapiEnv, - val: JSC.JSValue, + val: jsc.JSValue, ) void { NapiHandleScope.append(env, val); self.* = @enumFromInt(@intFromEnum(val)); } - pub fn get(self: *const napi_value) JSC.JSValue { + pub fn get(self: *const napi_value) jsc.JSValue { return @enumFromInt(@intFromEnum(self.*)); } - pub fn create(env: *NapiEnv, val: JSC.JSValue) napi_value { + pub fn create(env: *NapiEnv, val: jsc.JSValue) napi_value { NapiHandleScope.append(env, val); return @enumFromInt(@intFromEnum(val)); } @@ -158,7 +158,7 @@ pub const napi_typedarray_type = enum(c_uint) { bigint64_array = 9, biguint64_array = 10, - pub fn fromJSType(this: JSC.JSValue.JSType) ?napi_typedarray_type { + pub fn fromJSType(this: jsc.JSValue.JSType) ?napi_typedarray_type { return switch (this) { .Int8Array => napi_typedarray_type.int8_array, .Uint8Array => napi_typedarray_type.uint8_array, @@ -175,7 +175,7 @@ pub const napi_typedarray_type = enum(c_uint) { }; } - pub fn toJSType(this: napi_typedarray_type) JSC.JSValue.JSType { + pub fn toJSType(this: napi_typedarray_type) jsc.JSValue.JSType { return switch (this) { .int8_array => .Int8Array, .uint8_array => .Uint8Array, @@ -191,7 +191,7 @@ pub const napi_typedarray_type = enum(c_uint) { }; } - pub fn toC(this: napi_typedarray_type) JSC.C.JSTypedArrayType { + pub fn toC(this: napi_typedarray_type) jsc.C.JSTypedArrayType { return this.toJSType().toC(); } }; @@ -318,7 +318,7 @@ pub export fn napi_create_array_with_length(env_: napi_env, length: usize, resul // Node and V8 convert out-of-bounds array sizes to 0 const len = std.math.cast(u32, length) orelse 0; - const array = JSC.JSValue.createEmptyArray(env.toJS(), len) catch return env.setLastError(.pending_exception); + const array = jsc.JSValue.createEmptyArray(env.toJS(), len) catch return env.setLastError(.pending_exception); array.ensureStillAlive(); result.set(env, array); return env.ok(); @@ -517,7 +517,7 @@ pub export fn napi_get_prototype(env_: napi_env, object_: napi_value, result_: ? return env.setLastError(.object_expected); } - result.set(env, JSValue.c(JSC.C.JSObjectGetPrototype(env.toJS().ref(), object.asObjectRef()))); + result.set(env, JSValue.c(jsc.C.JSObjectGetPrototype(env.toJS().ref(), object.asObjectRef()))); return env.ok(); } // TODO: bind JSC::ownKeys @@ -667,7 +667,7 @@ pub export fn napi_make_callback(env_: napi_env, _: *anyopaque, recv_: napi_valu else .js_undefined, if (arg_count > 0 and args != null) - @as([*]const JSC.JSValue, @ptrCast(args.?))[0..arg_count] + @as([*]const jsc.JSValue, @ptrCast(args.?))[0..arg_count] else &.{}, ) catch |err| // TODO: handle errors correctly @@ -692,7 +692,7 @@ fn notImplementedYet(comptime name: []const u8) void { bun.onceUnsafe( struct { pub fn warn() void { - if (JSC.VirtualMachine.get().log.level.atLeast(.warn)) { + if (jsc.VirtualMachine.get().log.level.atLeast(.warn)) { bun.Output.prettyErrorln("warning: Node-API function \"{s}\" is not implemented yet.\n Track the status of Node-API in Bun: https://github.com/oven-sh/bun/issues/158", .{name}); bun.Output.flush(); } @@ -845,7 +845,7 @@ pub export fn napi_get_typedarray_info( length.* = array_buffer.len; if (maybe_arraybuffer) |arraybuffer| - arraybuffer.set(env, JSValue.c(JSC.C.JSObjectGetTypedArrayBuffer(env.toJS().ref(), typedarray.asObjectRef(), null))); + arraybuffer.set(env, JSValue.c(jsc.C.JSObjectGetTypedArrayBuffer(env.toJS().ref(), typedarray.asObjectRef(), null))); if (maybe_byte_offset) |byte_offset| byte_offset.* = array_buffer.offset; @@ -886,7 +886,7 @@ pub export fn napi_get_dataview_info( data.* = array_buffer.ptr; if (maybe_arraybuffer) |arraybuffer| - arraybuffer.set(env, JSValue.c(JSC.C.JSObjectGetTypedArrayBuffer(env.toJS().ref(), dataview.asObjectRef(), null))); + arraybuffer.set(env, JSValue.c(jsc.C.JSObjectGetTypedArrayBuffer(env.toJS().ref(), dataview.asObjectRef(), null))); if (maybe_byte_offset) |byte_offset| byte_offset.* = array_buffer.offset; @@ -916,8 +916,8 @@ pub export fn napi_create_promise(env_: napi_env, deferred_: ?*napi_deferred, pr const promise = promise_ orelse { return env.invalidArg(); }; - deferred.* = bun.default_allocator.create(JSC.JSPromise.Strong) catch @panic("failed to allocate napi_deferred"); - deferred.*.* = JSC.JSPromise.Strong.init(env.toJS()); + deferred.* = bun.default_allocator.create(jsc.JSPromise.Strong) catch @panic("failed to allocate napi_deferred"); + deferred.*.* = jsc.JSPromise.Strong.init(env.toJS()); promise.set(env, deferred.*.get().asValue(env.toJS())); return env.ok(); } @@ -973,8 +973,8 @@ pub export fn napi_create_date(env_: napi_env, time: f64, result_: ?*napi_value) const result = result_ orelse { return env.invalidArg(); }; - var args = [_]JSC.C.JSValueRef{JSC.JSValue.jsNumber(time).asObjectRef()}; - result.set(env, JSValue.c(JSC.C.JSObjectMakeDate(env.toJS().ref(), 1, &args, TODO_EXCEPTION))); + var args = [_]jsc.C.JSValueRef{jsc.JSValue.jsNumber(time).asObjectRef()}; + result.set(env, JSValue.c(jsc.C.JSObjectMakeDate(env.toJS().ref(), 1, &args, TODO_EXCEPTION))); return env.ok(); } pub export fn napi_is_date(env_: napi_env, value_: napi_value, is_date_: ?*bool) napi_status { @@ -1008,9 +1008,9 @@ pub extern fn napi_is_detached_arraybuffer(env: napi_env, value: napi_value, res /// must be globally allocated pub const napi_async_work = struct { task: WorkPoolTask = .{ .callback = &runFromThreadPool }, - concurrent_task: JSC.ConcurrentTask = .{}, - event_loop: *JSC.EventLoop, - global: *JSC.JSGlobalObject, + concurrent_task: jsc.ConcurrentTask = .{}, + event_loop: *jsc.EventLoop, + global: *jsc.JSGlobalObject, env: *NapiEnv, execute: napi_async_execute_callback, complete: ?napi_async_complete_callback, @@ -1072,7 +1072,7 @@ pub const napi_async_work = struct { return this.status.cmpxchgStrong(.pending, .cancelled, .seq_cst, .seq_cst) == null; } - pub fn runFromJS(this: *napi_async_work, vm: *JSC.VirtualMachine, global: *JSC.JSGlobalObject) void { + pub fn runFromJS(this: *napi_async_work, vm: *jsc.VirtualMachine, global: *jsc.JSGlobalObject) void { // Note: the "this" value here may already be freed by the user in `complete` var poll_ref = this.poll_ref; defer poll_ref.unref(vm); @@ -1177,7 +1177,7 @@ pub export fn napi_create_buffer_copy(env_: napi_env, length: usize, data: [*]u8 const result = result_ orelse { return env.invalidArg(); }; - var buffer = JSC.JSValue.createBufferFromLength(env.toJS(), length) catch return env.setLastError(.pending_exception); + var buffer = jsc.JSValue.createBufferFromLength(env.toJS(), length) catch return env.setLastError(.pending_exception); if (buffer.asArrayBuffer(env.toJS())) |array_buf| { if (length > 0) { @memcpy(array_buf.slice()[0..length], data[0..length]); @@ -1290,7 +1290,7 @@ pub export fn napi_get_node_version(env_: napi_env, version_: ?**const napi_node version.* = &napi_node_version.global; return env.ok(); } -const napi_event_loop = if (bun.Environment.isWindows) *bun.windows.libuv.Loop else *JSC.EventLoop; +const napi_event_loop = if (bun.Environment.isWindows) *bun.windows.libuv.Loop else *jsc.EventLoop; pub export fn napi_get_uv_event_loop(env_: napi_env, loop_: ?*napi_event_loop) napi_status { log("napi_get_uv_event_loop", .{}); const env = env_ orelse { @@ -1303,7 +1303,7 @@ pub export fn napi_get_uv_event_loop(env_: napi_env, loop_: ?*napi_event_loop) n // alignment error is incorrect. // TODO(@190n) investigate @setRuntimeSafety(false); - loop.* = JSC.VirtualMachine.get().uvLoop(); + loop.* = jsc.VirtualMachine.get().uvLoop(); } else { // there is no uv event loop on posix, we use our event loop handle. loop.* = env.toJS().bunVM().eventLoop(); @@ -1362,9 +1362,9 @@ pub const Finalizer = struct { // TODO: generate comptime version of this instead of runtime checking pub const ThreadSafeFunction = struct { pub const Callback = union(enum) { - js: JSC.Strong.Optional, + js: jsc.Strong.Optional, c: struct { - js: JSC.Strong.Optional, + js: jsc.Strong.Optional, napi_threadsafe_function_call_js: napi_threadsafe_function_call_js, }, @@ -1393,8 +1393,8 @@ pub const ThreadSafeFunction = struct { // for std.condvar lock: std.Thread.Mutex = .{}, - event_loop: *JSC.EventLoop, - tracker: JSC.Debugger.AsyncTaskTracker, + event_loop: *jsc.EventLoop, + tracker: jsc.Debugger.AsyncTaskTracker, env: *NapiEnv, @@ -1493,7 +1493,7 @@ pub const ThreadSafeFunction = struct { this.has_queued_finalizer = true; this.callback.deinit(); this.poll_ref.disable(); - this.event_loop.enqueueTask(JSC.Task.init(this)); + this.event_loop.enqueueTask(jsc.Task.init(this)); } }, .closed => { @@ -1607,7 +1607,7 @@ pub const ThreadSafeFunction = struct { fn scheduleDispatch(this: *ThreadSafeFunction) void { switch (this.dispatch_state.swap(.pending, .seq_cst)) { .idle => { - this.event_loop.enqueueTaskConcurrent(JSC.ConcurrentTask.createFrom(this)); + this.event_loop.enqueueTaskConcurrent(jsc.ConcurrentTask.createFrom(this)); }, .running => { // it will check if it has more work to do @@ -1708,16 +1708,16 @@ pub export fn napi_create_threadsafe_function( .callback = if (call_js_cb) |c| .{ .c = .{ .napi_threadsafe_function_call_js = c, - .js = if (func == .zero) .empty else JSC.Strong.Optional.create(func.withAsyncContextIfNeeded(env.toJS()), vm.global), + .js = if (func == .zero) .empty else jsc.Strong.Optional.create(func.withAsyncContextIfNeeded(env.toJS()), vm.global), }, } else .{ - .js = if (func == .zero) .empty else JSC.Strong.Optional.create(func.withAsyncContextIfNeeded(env.toJS()), vm.global), + .js = if (func == .zero) .empty else jsc.Strong.Optional.create(func.withAsyncContextIfNeeded(env.toJS()), vm.global), }, .ctx = context, .queue = ThreadSafeFunction.Queue.init(max_queue_size, bun.default_allocator), .thread_count = .{ .raw = @intCast(initial_thread_count) }, .poll_ref = Async.KeepAlive.init(), - .tracker = JSC.Debugger.AsyncTaskTracker.init(vm), + .tracker = jsc.Debugger.AsyncTaskTracker.init(vm), }); function.finalizer = .{ .env = env, .data = thread_finalize_data, .fun = thread_finalize_cb }; @@ -2406,7 +2406,7 @@ const uv_functions_to_export = if (bun.Environment.isPosix) struct { } else struct {}; pub fn fixDeadCodeElimination() void { - JSC.markBinding(@src()); + jsc.markBinding(@src()); inline for (napi_functions_to_export) |fn_name| { std.mem.doNotOptimizeAway(&fn_name); @@ -2430,7 +2430,7 @@ pub fn fixDeadCodeElimination() void { pub const NapiFinalizerTask = struct { finalizer: Finalizer, - const AnyTask = JSC.AnyTask.New(@This(), runOnJSThread); + const AnyTask = jsc.AnyTask.New(@This(), runOnJSThread); pub fn init(finalizer: Finalizer) *NapiFinalizerTask { const finalizer_task = bun.default_allocator.create(NapiFinalizerTask) catch bun.outOfMemory(); @@ -2447,7 +2447,7 @@ pub const NapiFinalizerTask = struct { if (thread_kind != .main) { // TODO(@heimskr): do we need to handle the case where the vm is shutting down? - vm.eventLoop().enqueueTaskConcurrent(JSC.ConcurrentTask.create(JSC.Task.init(this))); + vm.eventLoop().enqueueTaskConcurrent(jsc.ConcurrentTask.create(jsc.Task.init(this))); return; } @@ -2455,7 +2455,7 @@ pub const NapiFinalizerTask = struct { // Immediate tasks won't run, so we run this as a cleanup hook instead vm.rareData().pushCleanupHook(vm.global, this, runAsCleanupHook); } else { - globalThis.bunVM().event_loop.enqueueTask(JSC.Task.init(this)); + globalThis.bunVM().event_loop.enqueueTask(jsc.Task.init(this)); } } @@ -2482,5 +2482,5 @@ const WorkPoolTask = @import("../work_pool.zig").Task; const bun = @import("bun"); const Async = bun.Async; -const JSC = bun.JSC; -const JSValue = JSC.JSValue; +const jsc = bun.jsc; +const JSValue = jsc.JSValue; diff --git a/src/node_fallbacks.zig b/src/node_fallbacks.zig index b43aacf57e..4eed3bad67 100644 --- a/src/node_fallbacks.zig +++ b/src/node_fallbacks.zig @@ -88,10 +88,11 @@ pub fn contentsFromPath(path: string) ?string { return null; } +const string = []const u8; + const Fs = @import("./fs.zig"); const std = @import("std"); const PackageJSON = @import("./resolver/package_json.zig").PackageJSON; -const string = @import("./string_types.zig").string; const bun = @import("bun"); const Environment = bun.Environment; diff --git a/src/open.zig b/src/open.zig index 416e33ac22..a4249d6138 100644 --- a/src/open.zig +++ b/src/open.zig @@ -25,7 +25,7 @@ pub fn openURL(url: stringZ) void { .stdin = .inherit, .windows = if (Environment.isWindows) .{ - .loop = bun.JSC.EventLoopHandle.init(bun.JSC.MiniEventLoop.initGlobal(null)), + .loop = bun.jsc.EventLoopHandle.init(bun.jsc.MiniEventLoop.initGlobal(null)), }, }) catch break :maybe_fallback) { // don't fallback: @@ -434,6 +434,9 @@ pub const EditorContext = struct { } }; +const string = []const u8; +const stringZ = [:0]const u8; + const DotEnv = @import("./env_loader.zig"); const std = @import("std"); @@ -442,6 +445,4 @@ const Environment = bun.Environment; const Global = bun.Global; const Output = bun.Output; const default_allocator = bun.default_allocator; -const string = bun.string; -const stringZ = bun.stringZ; const strings = bun.strings; diff --git a/src/options.zig b/src/options.zig index 1635287c89..eb354bd52d 100644 --- a/src/options.zig +++ b/src/options.zig @@ -61,7 +61,7 @@ pub const ExternalModules = struct { }; pub fn isNodeBuiltin(str: string) bool { - return bun.JSC.ModuleLoader.HardcodedModule.Alias.has(str, .node); + return bun.jsc.ModuleLoader.HardcodedModule.Alias.has(str, .node); } const default_wildcard_patterns = &[_]WildcardPattern{ @@ -368,14 +368,14 @@ pub const Target = enum { .{ "node", .node }, }); - pub fn fromJS(global: *JSC.JSGlobalObject, value: JSC.JSValue) bun.JSError!?Target { + pub fn fromJS(global: *jsc.JSGlobalObject, value: jsc.JSValue) bun.JSError!?Target { if (!value.isString()) { return global.throwInvalidArguments("target must be a string", .{}); } return Map.fromJS(global, value); } - pub fn toAPI(this: Target) Api.Target { + pub fn toAPI(this: Target) api.Target { return switch (this) { .node => .node, .browser => .browser, @@ -442,8 +442,8 @@ pub const Target = enum { return exts; } - pub fn from(plat: ?api.Api.Target) Target { - return switch (plat orelse api.Api.Target._none) { + pub fn from(plat: ?api.Target) Target { + return switch (plat orelse api.Target._none) { .node => .node, .browser => .browser, .bun => .bun, @@ -583,7 +583,7 @@ pub const Format = enum { .{ "internal_bake_dev", .internal_bake_dev }, }); - pub fn fromJS(global: *JSC.JSGlobalObject, format: JSC.JSValue) bun.JSError!?Format { + pub fn fromJS(global: *jsc.JSGlobalObject, format: jsc.JSValue) bun.JSError!?Format { if (format.isUndefinedOrNull()) return null; if (!format.isString()) { @@ -739,14 +739,14 @@ pub const Loader = enum(u8) { return stdin_name.get(this); } - pub fn fromJS(global: *JSC.JSGlobalObject, loader: JSC.JSValue) bun.JSError!?Loader { + pub fn fromJS(global: *jsc.JSGlobalObject, loader: jsc.JSValue) bun.JSError!?Loader { if (loader.isUndefinedOrNull()) return null; if (!loader.isString()) { return global.throwInvalidArguments("loader must be a string", .{}); } - var zig_str = JSC.ZigString.init(""); + var zig_str = jsc.ZigString.init(""); try loader.toZigString(&zig_str, global); if (zig_str.len == 0) return null; @@ -782,7 +782,7 @@ pub const Loader = enum(u8) { .{ "html", .html }, }); - pub const api_names = bun.ComptimeStringMap(Api.Loader, .{ + pub const api_names = bun.ComptimeStringMap(api.Loader, .{ .{ "js", .js }, .{ "mjs", .js }, .{ "cjs", .js }, @@ -823,7 +823,7 @@ pub const Loader = enum(u8) { }; } - pub fn toAPI(loader: Loader) Api.Loader { + pub fn toAPI(loader: Loader) api.Loader { return switch (loader) { .jsx => .jsx, .js => .js, @@ -844,7 +844,7 @@ pub const Loader = enum(u8) { }; } - pub fn fromAPI(loader: Api.Loader) Loader { + pub fn fromAPI(loader: api.Loader) Loader { return switch (loader) { ._none => .file, .jsx => .jsx, @@ -931,7 +931,7 @@ pub const Loader = enum(u8) { }; pub fn normalizeSpecifier( - jsc_vm: *bun.JSC.VirtualMachine, + jsc_vm: *bun.jsc.VirtualMachine, slice_: string, ) struct { string, string, string } { var slice = slice_; @@ -972,9 +972,9 @@ const LoaderResult = struct { pub fn getLoaderAndVirtualSource( specifier_str: string, - jsc_vm: *JSC.VirtualMachine, + jsc_vm: *jsc.VirtualMachine, virtual_source_to_use: *?logger.Source, - blob_to_deinit: *?JSC.WebCore.Blob, + blob_to_deinit: *?jsc.WebCore.Blob, type_attribute_str: ?string, ) GetLoaderAndVirtualSourceErr!LoaderResult { const normalized_file_path_from_specifier, const specifier, const query = normalizeSpecifier( @@ -997,8 +997,8 @@ pub fn getLoaderAndVirtualSource( } } - if (JSC.WebCore.ObjectURLRegistry.isBlobURL(specifier)) { - if (JSC.WebCore.ObjectURLRegistry.singleton().resolveAndDupe(specifier["blob:".len..])) |blob| { + if (jsc.WebCore.ObjectURLRegistry.isBlobURL(specifier)) { + if (jsc.WebCore.ObjectURLRegistry.singleton().resolveAndDupe(specifier["blob:".len..])) |blob| { blob_to_deinit.* = blob; loader = blob.getLoader(jsc_vm); @@ -1329,7 +1329,7 @@ pub const JSX = struct { return out[0..i]; } - pub fn fromApi(jsx: api.Api.Jsx, allocator: std.mem.Allocator) !Pragma { + pub fn fromApi(jsx: api.Jsx, allocator: std.mem.Allocator) !Pragma { var pragma = JSX.Pragma{}; if (jsx.fragment.len > 0) { @@ -1354,7 +1354,7 @@ pub const JSX = struct { } }; - pub const Runtime = api.Api.JsxRuntime; + pub const Runtime = api.JsxRuntime; }; pub const DefaultUserDefines = struct { @@ -1372,7 +1372,7 @@ pub const DefaultUserDefines = struct { pub fn definesFromTransformOptions( allocator: std.mem.Allocator, log: *logger.Log, - maybe_input_define: ?Api.StringMap, + maybe_input_define: ?api.StringMap, target: Target, env_loader: ?*DotEnv.Loader, framework_env: ?*const Env, @@ -1380,7 +1380,7 @@ pub fn definesFromTransformOptions( drop: []const []const u8, omit_unused_global_calls: bool, ) !*defines.Define { - const input_user_define = maybe_input_define orelse std.mem.zeroes(Api.StringMap); + const input_user_define = maybe_input_define orelse std.mem.zeroes(api.StringMap); var user_defines = try stringHashMapFromArrays( defines.RawDefines, @@ -1392,7 +1392,7 @@ pub fn definesFromTransformOptions( var environment_defines = defines.UserDefinesArray.init(allocator); defer environment_defines.deinit(); - var behavior: Api.DotEnvBehavior = .disable; + var behavior: api.DotEnvBehavior = .disable; load_env: { const env = env_loader orelse break :load_env; @@ -1551,8 +1551,8 @@ pub const ResolveFileExtensions = struct { }; }; -pub fn loadersFromTransformOptions(allocator: std.mem.Allocator, _loaders: ?Api.LoaderMap, target: Target) std.mem.Allocator.Error!bun.StringArrayHashMap(Loader) { - const input_loaders = _loaders orelse std.mem.zeroes(Api.LoaderMap); +pub fn loadersFromTransformOptions(allocator: std.mem.Allocator, _loaders: ?api.LoaderMap, target: Target) std.mem.Allocator.Error!bun.StringArrayHashMap(Loader) { + const input_loaders = _loaders orelse std.mem.zeroes(api.LoaderMap); const loader_values = try allocator.alloc(Loader, input_loaders.loaders.len); for (loader_values, input_loaders.loaders) |*loader, input| { @@ -1593,7 +1593,7 @@ pub const SourceMapOption = enum { external, linked, - pub fn fromApi(source_map: ?Api.SourceMapMode) SourceMapOption { + pub fn fromApi(source_map: ?api.SourceMapMode) SourceMapOption { return switch (source_map orelse .none) { .external => .external, .@"inline" => .@"inline", @@ -1602,7 +1602,7 @@ pub const SourceMapOption = enum { }; } - pub fn toAPI(source_map: ?SourceMapOption) Api.SourceMapMode { + pub fn toAPI(source_map: ?SourceMapOption) api.SourceMapMode { return switch (source_map orelse .none) { .external => .external, .@"inline" => .@"inline", @@ -1630,7 +1630,7 @@ pub const PackagesOption = enum { bundle, external, - pub fn fromApi(packages: ?Api.PackagesMode) PackagesOption { + pub fn fromApi(packages: ?api.PackagesMode) PackagesOption { return switch (packages orelse .bundle) { .external => .external, .bundle => .bundle, @@ -1638,7 +1638,7 @@ pub const PackagesOption = enum { }; } - pub fn toAPI(packages: ?PackagesOption) Api.PackagesMode { + pub fn toAPI(packages: ?PackagesOption) api.PackagesMode { return switch (packages orelse .bundle) { .external => .external, .bundle => .bundle, @@ -1709,7 +1709,7 @@ pub const BundleOptions = struct { import_path_format: ImportPathFormat = ImportPathFormat.relative, defines_loaded: bool = false, env: Env = Env{}, - transform_options: Api.TransformOptions, + transform_options: api.TransformOptions, polyfill_node_globals: bool = false, transform_only: bool = false, load_tsconfig_json: bool = true, @@ -1730,7 +1730,7 @@ pub const BundleOptions = struct { global_cache: GlobalCache = .disable, prefer_offline_install: bool = false, prefer_latest_install: bool = false, - install: ?*Api.BunInstall = null, + install: ?*api.BunInstall = null, inlining: bool = false, inline_entrypoint_import_meta_main: bool = false, @@ -1802,7 +1802,7 @@ pub const BundleOptions = struct { "react-refresh", }; - pub inline fn cssImportBehavior(this: *const BundleOptions) Api.CssInJsBehavior { + pub inline fn cssImportBehavior(this: *const BundleOptions) api.CssInJsBehavior { switch (this.target) { .browser => { return .auto_onimportcss; @@ -1928,7 +1928,7 @@ pub const BundleOptions = struct { allocator: std.mem.Allocator, fs: *Fs.FileSystem, log: *logger.Log, - transform: Api.TransformOptions, + transform: api.TransformOptions, ) !BundleOptions { var opts: BundleOptions = BundleOptions{ .log = log, @@ -1946,8 +1946,8 @@ pub const BundleOptions = struct { .drop = transform.drop, }; - Analytics.Features.define += @as(usize, @intFromBool(transform.define != null)); - Analytics.Features.loaders += @as(usize, @intFromBool(transform.loaders != null)); + analytics.Features.define += @as(usize, @intFromBool(transform.define != null)); + analytics.Features.loaders += @as(usize, @intFromBool(transform.loaders != null)); opts.serve_plugins = transform.serve_plugins; opts.bunfig_path = transform.bunfig_path; @@ -2044,8 +2044,8 @@ pub const BundleOptions = struct { opts.tsconfig_override = tsconfig; } - Analytics.Features.macros += @as(usize, @intFromBool(opts.target == .bun_macro)); - Analytics.Features.external += @as(usize, @intFromBool(transform.external.len > 0)); + analytics.Features.macros += @as(usize, @intFromBool(opts.target == .bun_macro)); + analytics.Features.external += @as(usize, @intFromBool(transform.external.len > 0)); return opts; } }; @@ -2162,7 +2162,7 @@ pub const Env = struct { }; const List = std.MultiArrayList(Entry); - behavior: Api.DotEnvBehavior = Api.DotEnvBehavior.disable, + behavior: api.DotEnvBehavior = api.DotEnvBehavior.disable, prefix: string = "", defaults: List = List{}, allocator: std.mem.Allocator = undefined, @@ -2177,7 +2177,7 @@ pub const Env = struct { .allocator = allocator, .defaults = List{}, .prefix = "", - .behavior = Api.DotEnvBehavior.disable, + .behavior = api.DotEnvBehavior.disable, }; } @@ -2185,7 +2185,7 @@ pub const Env = struct { try this.defaults.ensureTotalCapacity(this.allocator, capacity); } - pub fn setDefaultsMap(this: *Env, defaults: Api.StringMap) !void { + pub fn setDefaultsMap(this: *Env, defaults: api.StringMap) !void { this.defaults.shrinkRetainingCapacity(0); if (defaults.keys.len == 0) { @@ -2200,7 +2200,7 @@ pub const Env = struct { } // For reading from API - pub fn setFromAPI(this: *Env, config: Api.EnvConfig) !void { + pub fn setFromAPI(this: *Env, config: api.EnvConfig) !void { this.setBehaviorFromPrefix(config.prefix orelse ""); if (config.defaults) |defaults| { @@ -2209,23 +2209,23 @@ pub const Env = struct { } pub fn setBehaviorFromPrefix(this: *Env, prefix: string) void { - this.behavior = Api.DotEnvBehavior.disable; + this.behavior = api.DotEnvBehavior.disable; this.prefix = ""; if (strings.eqlComptime(prefix, "*")) { - this.behavior = Api.DotEnvBehavior.load_all; + this.behavior = api.DotEnvBehavior.load_all; } else if (prefix.len > 0) { - this.behavior = Api.DotEnvBehavior.prefix; + this.behavior = api.DotEnvBehavior.prefix; this.prefix = prefix; } } - pub fn setFromLoaded(this: *Env, config: Api.LoadedEnvConfig, allocator: std.mem.Allocator) !void { + pub fn setFromLoaded(this: *Env, config: api.LoadedEnvConfig, allocator: std.mem.Allocator) !void { this.allocator = allocator; this.behavior = switch (config.dotenv) { - Api.DotEnvBehavior.prefix => Api.DotEnvBehavior.prefix, - Api.DotEnvBehavior.load_all => Api.DotEnvBehavior.load_all, - else => Api.DotEnvBehavior.disable, + api.DotEnvBehavior.prefix => api.DotEnvBehavior.prefix, + api.DotEnvBehavior.load_all => api.DotEnvBehavior.load_all, + else => api.DotEnvBehavior.disable, }; this.prefix = config.prefix; @@ -2233,10 +2233,10 @@ pub const Env = struct { try this.setDefaultsMap(config.defaults); } - pub fn toAPI(this: *const Env) Api.LoadedEnvConfig { + pub fn toAPI(this: *const Env) api.LoadedEnvConfig { var slice = this.defaults.slice(); - return Api.LoadedEnvConfig{ + return api.LoadedEnvConfig{ .dotenv = this.behavior, .prefix = this.prefix, .defaults = .{ .keys = slice.items(.key), .values = slice.items(.value) }, @@ -2272,7 +2272,7 @@ pub const EntryPoint = struct { fallback, disabled, - pub fn toAPI(this: Kind) Api.FrameworkEntryPointType { + pub fn toAPI(this: Kind) api.FrameworkEntryPointType { return switch (this) { .client => .client, .server => .server, @@ -2282,11 +2282,11 @@ pub const EntryPoint = struct { } }; - pub fn toAPI(this: *const EntryPoint, allocator: std.mem.Allocator, toplevel_path: string, kind: Kind) !?Api.FrameworkEntryPoint { + pub fn toAPI(this: *const EntryPoint, allocator: std.mem.Allocator, toplevel_path: string, kind: Kind) !?api.FrameworkEntryPoint { if (this.kind == .disabled) return null; - return Api.FrameworkEntryPoint{ .kind = kind.toAPI(), .env = this.env.toAPI(), .path = try this.normalizedPath(allocator, toplevel_path) }; + return api.FrameworkEntryPoint{ .kind = kind.toAPI(), .env = this.env.toAPI(), .path = try this.normalizedPath(allocator, toplevel_path) }; } fn normalizedPath(this: *const EntryPoint, allocator: std.mem.Allocator, toplevel_path: string) !string { @@ -2312,7 +2312,7 @@ pub const EntryPoint = struct { pub fn fromLoaded( this: *EntryPoint, - framework_entry_point: Api.FrameworkEntryPoint, + framework_entry_point: api.FrameworkEntryPoint, allocator: std.mem.Allocator, kind: Kind, ) !void { @@ -2323,7 +2323,7 @@ pub const EntryPoint = struct { pub fn fromAPI( this: *EntryPoint, - framework_entry_point: Api.FrameworkEntryPointMessage, + framework_entry_point: api.FrameworkEntryPointMessage, allocator: std.mem.Allocator, kind: Kind, ) !void { @@ -2358,7 +2358,7 @@ pub const RouteConfig = struct { extensions: []const string = &[_]string{}, routes_enabled: bool = false, - pub fn toAPI(this: *const RouteConfig) Api.LoadedRouteConfig { + pub fn toAPI(this: *const RouteConfig) api.LoadedRouteConfig { return .{ .asset_prefix = this.asset_prefix_path, .dir = if (this.routes_enabled) this.dir else "", @@ -2379,7 +2379,7 @@ pub const RouteConfig = struct { }; } - pub fn fromLoadedRoutes(loaded: Api.LoadedRouteConfig) RouteConfig { + pub fn fromLoadedRoutes(loaded: api.LoadedRouteConfig) RouteConfig { return RouteConfig{ .extensions = loaded.extensions, .dir = loaded.dir, @@ -2390,7 +2390,7 @@ pub const RouteConfig = struct { }; } - pub fn fromApi(router_: Api.RouteConfig, allocator: std.mem.Allocator) !RouteConfig { + pub fn fromApi(router_: api.RouteConfig, allocator: std.mem.Allocator) !RouteConfig { var router = zero(); const static_dir: string = std.mem.trimRight(u8, router_.static_dir orelse "", "/\\"); @@ -2587,16 +2587,14 @@ pub const PathTemplate = struct { }; }; -const Analytics = @import("./analytics/analytics_thread.zig"); +const string = []const u8; + const DotEnv = @import("./env_loader.zig"); const Fs = @import("./fs.zig"); const resolver = @import("./resolver/resolver.zig"); const Runtime = @import("./runtime.zig").Runtime; const URL = @import("./url.zig").URL; -const api = @import("./api/schema.zig"); -const Api = api.Api; - const MacroRemap = @import("./resolver/package_json.zig").MacroMap; const PackageJSON = @import("./resolver/package_json.zig").PackageJSON; const ConditionsMap = @import("./resolver/package_json.zig").ESModule.ConditionsMap; @@ -2604,9 +2602,10 @@ const ConditionsMap = @import("./resolver/package_json.zig").ESModule.Conditions const bun = @import("bun"); const Environment = bun.Environment; const Global = bun.Global; -const JSC = bun.JSC; const Output = bun.Output; +const analytics = bun.analytics; const assert = bun.assert; +const jsc = bun.jsc; const logger = bun.logger; -const string = bun.string; const strings = bun.strings; +const api = bun.schema.api; diff --git a/src/output.zig b/src/output.zig index d414aaf28e..dfd156af38 100644 --- a/src/output.zig +++ b/src/output.zig @@ -44,13 +44,8 @@ pub const Source = struct { stream: StreamType, err_stream: StreamType, ) Source { - if (comptime Environment.isDebug) { - if (comptime use_mimalloc) { - if (!source_set) { - const Mimalloc = @import("./allocators/mimalloc.zig"); - Mimalloc.mi_option_set(.show_errors, 1); - } - } + if ((comptime Environment.isDebug and use_mimalloc) and !source_set) { + bun.mimalloc.mi_option_set(.show_errors, 1); } source_set = true; @@ -75,7 +70,7 @@ pub const Source = struct { bun.StackCheck.configureThread(); } - pub fn configureNamedThread(name: StringTypes.stringZ) void { + pub fn configureNamedThread(name: [:0]const u8) void { Global.setThreadName(name); configureThread(); } @@ -1284,6 +1279,8 @@ pub var buffered_stdin = std.io.BufferedReader(4096, File.Reader){ .unbuffered_reader = .{ .context = .{ .handle = if (Environment.isWindows) undefined else .stdin() } }, }; +const string = []const u8; + const Environment = @import("./env.zig"); const root = @import("root"); const std = @import("std"); @@ -1292,9 +1289,7 @@ const SystemTimer = @import("./system_timer.zig").Timer; const bun = @import("bun"); const ComptimeStringMap = bun.ComptimeStringMap; const Global = bun.Global; -const StringTypes = bun.StringTypes; const c = bun.c; -const string = bun.string; const strings = bun.strings; const use_mimalloc = bun.use_mimalloc; const File = bun.sys.File; diff --git a/src/patch.zig b/src/patch.zig index 84ab983b9b..6dd2ff3874 100644 --- a/src/patch.zig +++ b/src/patch.zig @@ -36,7 +36,7 @@ pub const PatchFile = struct { pathbuf: bun.PathBuffer = undefined, patch_dir_abs_path: ?[:0]const u8 = null, - fn patchDirAbsPath(state: *@This(), fd: bun.FileDescriptor) JSC.Maybe([:0]const u8) { + fn patchDirAbsPath(state: *@This(), fd: bun.FileDescriptor) jsc.Maybe([:0]const u8) { if (state.patch_dir_abs_path) |p| return .{ .result = p }; return switch (bun.sys.getFdPath(fd, &state.pathbuf)) { .result => |p| { @@ -209,7 +209,7 @@ pub const PatchFile = struct { arena: *bun.ArenaAllocator, patch_dir: bun.FileDescriptor, state: *ApplyState, - ) JSC.Maybe(void) { + ) jsc.Maybe(void) { const file_path: [:0]const u8 = arena.allocator().dupeZ(u8, patch.path) catch bun.outOfMemory(); // Need to get the mode of the original file @@ -328,7 +328,7 @@ pub const PatchFile = struct { }; } - return JSC.Maybe(void).success; + return jsc.Maybe(void).success; } }; @@ -1068,9 +1068,9 @@ const PatchLinesParser = struct { }; pub const TestingAPIs = struct { - pub fn makeDiff(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { + pub fn makeDiff(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const arguments_ = callframe.arguments_old(2); - var arguments = JSC.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), arguments_.slice()); + var arguments = jsc.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), arguments_.slice()); const old_folder_jsval = arguments.nextEat() orelse { return globalThis.throw("expected 2 strings", .{}); @@ -1104,7 +1104,7 @@ pub const TestingAPIs = struct { }; } const ApplyArgs = struct { - patchfile_txt: JSC.ZigString.Slice, + patchfile_txt: jsc.ZigString.Slice, patchfile: PatchFile, dirfd: bun.FileDescriptor, @@ -1117,7 +1117,7 @@ pub const TestingAPIs = struct { } } }; - pub fn apply(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { + pub fn apply(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { var args = switch (parseApplyArgs(globalThis, callframe)) { .err => |e| return e, .result => |a| a, @@ -1131,9 +1131,9 @@ pub const TestingAPIs = struct { return .true; } /// Used in JS tests, see `internal-for-testing.ts` and patch tests. - pub fn parse(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { + pub fn parse(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const arguments_ = callframe.arguments_old(2); - var arguments = JSC.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), arguments_.slice()); + var arguments = jsc.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), arguments_.slice()); const patchfile_src_js = arguments.nextEat() orelse { return globalThis.throw("TestingAPIs.parse: expected at least 1 argument, got 0", .{}); @@ -1155,9 +1155,9 @@ pub const TestingAPIs = struct { return outstr.toJS(globalThis); } - pub fn parseApplyArgs(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSC.Node.Maybe(ApplyArgs, JSC.JSValue) { + pub fn parseApplyArgs(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.jsc.Node.Maybe(ApplyArgs, jsc.JSValue) { const arguments_ = callframe.arguments_old(2); - var arguments = JSC.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), arguments_.slice()); + var arguments = jsc.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), arguments_.slice()); const patchfile_js = arguments.nextEat() orelse { globalThis.throw("apply: expected at least 1 argument, got 0", .{}) catch {}; @@ -1209,7 +1209,7 @@ pub fn spawnOpts( new_folder: []const u8, cwd: [:0]const u8, git: [:0]const u8, - loop: *JSC.AnyEventLoop, + loop: *jsc.AnyEventLoop, ) bun.spawn.sync.Options { const argv: []const []const u8 = brk: { const ARGV = &[_][:0]const u8{ @@ -1265,7 +1265,7 @@ pub fn spawnOpts( }; } -pub fn diffPostProcess(result: *bun.spawn.sync.Result, old_folder: []const u8, new_folder: []const u8) !bun.JSC.Node.Maybe(std.ArrayList(u8), std.ArrayList(u8)) { +pub fn diffPostProcess(result: *bun.spawn.sync.Result, old_folder: []const u8, new_folder: []const u8) !bun.jsc.Node.Maybe(std.ArrayList(u8), std.ArrayList(u8)) { var stdout = std.ArrayList(u8).init(bun.default_allocator); var stderr = std.ArrayList(u8).init(bun.default_allocator); @@ -1333,7 +1333,7 @@ pub fn gitDiffInternal( allocator: std.mem.Allocator, old_folder_: []const u8, new_folder_: []const u8, -) !bun.JSC.Node.Maybe(std.ArrayList(u8), std.ArrayList(u8)) { +) !bun.jsc.Node.Maybe(std.ArrayList(u8), std.ArrayList(u8)) { const paths = gitDiffPreprocessPaths(allocator, old_folder_, new_folder_, false); const old_folder = paths[0]; const new_folder = paths[1]; @@ -1536,8 +1536,8 @@ fn shouldSkipLine(line: []const u8) bool { } const bun = @import("bun"); -const JSC = bun.JSC; const Output = bun.Output; +const jsc = bun.jsc; const std = @import("std"); const List = std.ArrayListUnmanaged; diff --git a/src/paths/EnvPath.zig b/src/paths/EnvPath.zig index d3a5152cf4..f320cefd25 100644 --- a/src/paths/EnvPath.zig +++ b/src/paths/EnvPath.zig @@ -82,10 +82,11 @@ pub fn EnvPath(comptime opts: EnvPathOptions) type { }; } +const string = []const u8; + const std = @import("std"); const bun = @import("bun"); const AbsPath = bun.AbsPath; const OOM = bun.OOM; -const string = bun.string; const strings = bun.strings; diff --git a/src/renamer.zig b/src/renamer.zig index af24df3712..1eec203d7e 100644 --- a/src/renamer.zig +++ b/src/renamer.zig @@ -949,17 +949,18 @@ pub fn computeReservedNamesForScope( } } +const string = []const u8; + const JSLexer = @import("./js_lexer.zig"); const std = @import("std"); -const Ref = @import("./ast/base.zig").Ref; -const RefCtx = @import("./ast/base.zig").RefCtx; - const bun = @import("bun"); const Environment = bun.Environment; const MutableString = bun.MutableString; const Output = bun.Output; -const js_ast = bun.JSAst; const logger = bun.logger; -const string = bun.string; const strings = bun.strings; + +const js_ast = bun.ast; +const Ref = bun.ast.Ref; +const RefCtx = bun.ast.RefCtx; diff --git a/src/resolver/data_url.zig b/src/resolver/data_url.zig index a81373ca57..279a5a3d9a 100644 --- a/src/resolver/data_url.zig +++ b/src/resolver/data_url.zig @@ -222,10 +222,11 @@ pub const DataURL = struct { } }; +const string = []const u8; + const std = @import("std"); const Allocator = std.mem.Allocator; const bun = @import("bun"); const Environment = bun.Environment; -const string = bun.string; const strings = bun.strings; diff --git a/src/resolver/dir_info.zig b/src/resolver/dir_info.zig index 390fc52ca9..d59b2251bd 100644 --- a/src/resolver/dir_info.zig +++ b/src/resolver/dir_info.zig @@ -103,8 +103,9 @@ pub fn getEnclosingBrowserScope(i: *const DirInfo) ?*DirInfo { // 4. Allocate onto the https://en.wikipedia.org/wiki/.bss#BSS_in_C instead of the heap, so we can avoid memory leaks pub const HashMap = allocators.BSSMap(DirInfo, Fs.Preallocate.Counts.dir_entry, false, 128, true); +const string = []const u8; + const Fs = @import("../fs.zig"); -const allocators = @import("../allocators.zig"); const std = @import("std"); const PackageJSON = @import("./package_json.zig").PackageJSON; const TSConfigJSON = @import("./tsconfig_json.zig").TSConfigJSON; @@ -112,4 +113,4 @@ const TSConfigJSON = @import("./tsconfig_json.zig").TSConfigJSON; const bun = @import("bun"); const FeatureFlags = bun.FeatureFlags; const StoredFileDescriptorType = bun.StoredFileDescriptorType; -const string = bun.string; +const allocators = bun.allocators; diff --git a/src/resolver/package_json.zig b/src/resolver/package_json.zig index 9a50d31eec..f0ad1c0a57 100644 --- a/src/resolver/package_json.zig +++ b/src/resolver/package_json.zig @@ -170,7 +170,7 @@ pub const PackageJSON = struct { values[i] = prop.value.?.data.e_string.string(allocator) catch unreachable; i += 1; } - framework.override_modules = Api.StringMap{ .keys = keys, .values = values }; + framework.override_modules = api.StringMap{ .keys = keys, .values = values }; } fn loadDefineExpression( @@ -2024,6 +2024,8 @@ fn findInvalidSegment(path_: string) ?string { return null; } +const string = []const u8; + const Dependency = @import("../install/dependency.zig"); const Install = @import("../install/install.zig"); const cache = @import("../cache.zig"); @@ -2032,7 +2034,6 @@ const options = @import("../options.zig"); const resolve_path = @import("./resolve_path.zig"); const resolver = @import("./resolver.zig"); const std = @import("std"); -const Api = @import("../api/schema.zig").Api; const Architecture = @import("../install/npm.zig").Architecture; const OperatingSystem = @import("../install/npm.zig").OperatingSystem; @@ -2043,11 +2044,11 @@ const MainFieldMap = bun.StringMap; const Output = bun.Output; const StoredFileDescriptorType = bun.StoredFileDescriptorType; const default_allocator = bun.default_allocator; -const js_ast = bun.JSAst; +const js_ast = bun.ast; const js_lexer = bun.js_lexer; const logger = bun.logger; -const string = bun.string; const strings = bun.strings; +const api = bun.schema.api; const Semver = bun.Semver; const String = Semver.String; diff --git a/src/resolver/resolve_path.zig b/src/resolver/resolve_path.zig index 7827ace98a..a884316479 100644 --- a/src/resolver/resolve_path.zig +++ b/src/resolver/resolve_path.zig @@ -1978,7 +1978,7 @@ pub const PosixToWinNormalizer = struct { /// Used in PathInlines.h /// gets cwd off of the global object export fn ResolvePath__joinAbsStringBufCurrentPlatformBunString( - globalObject: *bun.JSC.JSGlobalObject, + globalObject: *bun.jsc.JSGlobalObject, in: bun.String, ) bun.String { const str = in.toUTF8WithoutRef(bun.default_allocator); @@ -2058,7 +2058,7 @@ pub fn posixToPlatformInPlace(comptime T: type, path_buffer: []T) void { const Fs = @import("../fs.zig"); const std = @import("std"); -const strings = @import("../string_immutable.zig"); const bun = @import("bun"); const assert = bun.assert; +const strings = bun.strings; diff --git a/src/resolver/resolver.zig b/src/resolver/resolver.zig index 23817fa54a..f3237e40ec 100644 --- a/src/resolver/resolver.zig +++ b/src/resolver/resolver.zig @@ -637,7 +637,7 @@ pub const Resolver = struct { bun.crash_handler.current_action = prev_action; }; - if (Environment.show_crash_trace and bun.CLI.debug_flags.hasResolveBreakpoint(import_path)) { + if (Environment.show_crash_trace and bun.cli.debug_flags.hasResolveBreakpoint(import_path)) { bun.Output.debug("Resolving {s} from {s}", .{ import_path, source_dir, @@ -1203,7 +1203,7 @@ pub const Resolver = struct { if (had_node_prefix) { // Module resolution fails automatically for unknown node builtins - if (!bun.JSC.ModuleLoader.HardcodedModule.Alias.has(import_path_without_node_prefix, .node)) { + if (!bun.jsc.ModuleLoader.HardcodedModule.Alias.has(import_path_without_node_prefix, .node)) { return .{ .not_found = {} }; } @@ -3122,7 +3122,7 @@ pub const Resolver = struct { // } // if (r.opts.mark_builtins_as_external or r.opts.target.isBun()) { - if (JSC.ModuleLoader.HardcodedModule.Alias.get(esm_resolution.path, r.opts.target)) |alias| { + if (jsc.ModuleLoader.HardcodedModule.Alias.get(esm_resolution.path, r.opts.target)) |alias| { return .{ .success = .{ .path_pair = .{ .primary = bun.fs.Path.init(alias.path) }, @@ -3383,9 +3383,9 @@ pub const Resolver = struct { }; } - pub fn nodeModulePathsForJS(globalThis: *bun.JSC.JSGlobalObject, callframe: *bun.JSC.CallFrame) bun.JSError!JSC.JSValue { - bun.JSC.markBinding(@src()); - const argument: bun.JSC.JSValue = callframe.argument(0); + pub fn nodeModulePathsForJS(globalThis: *bun.jsc.JSGlobalObject, callframe: *bun.jsc.CallFrame) bun.JSError!jsc.JSValue { + bun.jsc.markBinding(@src()); + const argument: bun.jsc.JSValue = callframe.argument(0); if (argument == .zero or !argument.isString()) { return globalThis.throwInvalidArgumentType("nodeModulePaths", "path", "string"); @@ -3396,14 +3396,14 @@ pub const Resolver = struct { return nodeModulePathsJSValue(in_str, globalThis, false); } - pub export fn Resolver__propForRequireMainPaths(globalThis: *bun.JSC.JSGlobalObject) callconv(.C) JSC.JSValue { - bun.JSC.markBinding(@src()); + pub export fn Resolver__propForRequireMainPaths(globalThis: *bun.jsc.JSGlobalObject) callconv(.C) jsc.JSValue { + bun.jsc.markBinding(@src()); const in_str = bun.String.init("."); return nodeModulePathsJSValue(in_str, globalThis, false); } - pub fn nodeModulePathsJSValue(in_str: bun.String, globalObject: *bun.JSC.JSGlobalObject, use_dirname: bool) callconv(.C) bun.JSC.JSValue { + pub fn nodeModulePathsJSValue(in_str: bun.String, globalObject: *bun.jsc.JSGlobalObject, use_dirname: bool) callconv(.C) bun.jsc.JSValue { var arena = std.heap.ArenaAllocator.init(bun.default_allocator); defer arena.deinit(); var stack_fallback_allocator = std.heap.stackFallback(1024, arena.allocator()); @@ -4312,15 +4312,16 @@ pub const GlobalCache = enum { comptime { _ = Resolver.Resolver__propForRequireMainPaths; - @export(&JSC.toJSHostFn(Resolver.nodeModulePathsForJS), .{ .name = "Resolver__nodeModulePathsForJS" }); + @export(&jsc.toJSHostFn(Resolver.nodeModulePathsForJS), .{ .name = "Resolver__nodeModulePathsForJS" }); @export(&Resolver.nodeModulePathsJSValue, .{ .name = "Resolver__nodeModulePathsJSValue" }); } +const string = []const u8; + const Dependency = @import("../install/dependency.zig"); const DotEnv = @import("../env_loader.zig"); const NodeFallbackModules = @import("../node_fallbacks.zig"); const ResolvePath = @import("./resolve_path.zig"); -const allocators = @import("../allocators.zig"); const ast = @import("../import_record.zig"); const options = @import("../options.zig"); const std = @import("std"); @@ -4347,15 +4348,15 @@ const Environment = bun.Environment; const FD = bun.FD; const FeatureFlags = bun.FeatureFlags; const FileDescriptorType = bun.FileDescriptor; -const JSC = bun.JSC; const MutableString = bun.MutableString; const Mutex = bun.Mutex; const Output = bun.Output; const PathString = bun.PathString; const Semver = bun.Semver; +const allocators = bun.allocators; const assert = bun.assert; const default_allocator = bun.default_allocator; -const string = bun.string; +const jsc = bun.jsc; const strings = bun.strings; const logger = bun.logger; diff --git a/src/resolver/tsconfig_json.zig b/src/resolver/tsconfig_json.zig index 9edcdf3807..89b8c1608f 100644 --- a/src/resolver/tsconfig_json.zig +++ b/src/resolver/tsconfig_json.zig @@ -147,7 +147,7 @@ pub const TSConfigJSON = struct { // behavior may also be different). const json: js_ast.Expr = (json_cache.parseTSConfig(log, source, allocator) catch null) orelse return null; - bun.Analytics.Features.tsconfig += 1; + bun.analytics.Features.tsconfig += 1; var result: TSConfigJSON = TSConfigJSON{ .abs_path = source.path.text, .paths = PathsMap.init(allocator) }; errdefer allocator.free(result.paths); @@ -271,7 +271,7 @@ pub const TSConfigJSON = struct { switch (paths_prop.expr.data) { .e_object => { defer { - bun.Analytics.Features.tsconfig_paths += 1; + bun.analytics.Features.tsconfig_paths += 1; } var paths = paths_prop.expr.data.e_object; result.base_url_for_paths = if (result.base_url.len > 0) result.base_url else "."; @@ -483,6 +483,8 @@ pub const TSConfigJSON = struct { } }; +const string = []const u8; + const cache = @import("../cache.zig"); const options = @import("../options.zig"); const std = @import("std"); @@ -490,8 +492,7 @@ const std = @import("std"); const bun = @import("bun"); const Environment = bun.Environment; const assert = bun.assert; -const js_ast = bun.JSAst; +const js_ast = bun.ast; const js_lexer = bun.js_lexer; const logger = bun.logger; -const string = bun.string; const strings = bun.strings; diff --git a/src/router.zig b/src/router.zig index b1047528a7..872d053687 100644 --- a/src/router.zig +++ b/src/router.zig @@ -492,8 +492,8 @@ pub const TinyPtr = packed struct(u32) { pub inline fn str(this: TinyPtr, slice: string) string { return if (this.len > 0) slice[this.offset .. this.offset + this.len] else ""; } - pub inline fn toStringPointer(this: TinyPtr) Api.StringPointer { - return Api.StringPointer{ .offset = this.offset, .length = this.len }; + pub inline fn toStringPointer(this: TinyPtr) api.StringPointer { + return api.StringPointer{ .offset = this.offset, .length = this.len }; } pub inline fn eql(a: TinyPtr, b: TinyPtr) bool { @@ -942,7 +942,7 @@ pub const Test = struct { pub fn makeRoutes(comptime testName: string, data: anytype) !Routes { Output.initTest(); try makeTest(testName, data); - const JSAst = bun.JSAst; + const JSAst = bun.ast; JSAst.Expr.Data.Store.create(default_allocator); JSAst.Stmt.Data.Store.create(default_allocator); const fs = try FileSystem.init(null); @@ -973,7 +973,7 @@ pub const Test = struct { .routes = router.config, .entry_points = &.{}, .out_extensions = bun.StringHashMap(string).init(default_allocator), - .transform_options = std.mem.zeroes(Api.TransformOptions), + .transform_options = std.mem.zeroes(api.TransformOptions), .external = Options.ExternalModules.init( default_allocator, &FileSystem.instance.fs, @@ -997,7 +997,7 @@ pub const Test = struct { pub fn make(comptime testName: string, data: anytype) !Router { try makeTest(testName, data); - const JSAst = bun.JSAst; + const JSAst = bun.ast; JSAst.Expr.Data.Store.create(default_allocator); JSAst.Stmt.Data.Store.create(default_allocator); const fs = try FileSystem.initWithForce(null, true); @@ -1028,7 +1028,7 @@ pub const Test = struct { .routes = router.config, .entry_points = &.{}, .out_extensions = bun.StringHashMap(string).init(default_allocator), - .transform_options = std.mem.zeroes(Api.TransformOptions), + .transform_options = std.mem.zeroes(api.TransformOptions), .external = Options.ExternalModules.init( default_allocator, &FileSystem.instance.fs, @@ -1887,12 +1887,12 @@ test "Pattern" { try expectStr(catch_all.value.catch_all.str(pattern), "catch_all"); } +const string = []const u8; + const DirInfo = @import("./resolver/dir_info.zig"); const Options = @import("./options.zig"); const URLPath = @import("./http/URLPath.zig"); const std = @import("std"); -const Api = @import("./api/schema.zig").Api; -const CodepointIterator = @import("./string_immutable.zig").CodepointIterator; const PathnameScanner = @import("./url.zig").PathnameScanner; const Fs = @import("./fs.zig"); @@ -1906,8 +1906,10 @@ const Output = bun.Output; const PathString = bun.PathString; const StoredFileDescriptorType = bun.StoredFileDescriptorType; const default_allocator = bun.default_allocator; -const string = bun.string; +const api = bun.schema.api; + const strings = bun.strings; +const CodepointIterator = bun.strings.CodepointIterator; const expect = std.testing.expect; const expectEqual = std.testing.expectEqual; diff --git a/src/runtime.zig b/src/runtime.zig index aa4ead4bdf..2d8ab1e1c0 100644 --- a/src/runtime.zig +++ b/src/runtime.zig @@ -15,13 +15,13 @@ pub const Fallback = struct { pub const HTMLBackendTemplate = @embedFile("./fallback-backend.html"); const Base64FallbackMessage = struct { - msg: *const Api.FallbackMessageContainer, + msg: *const api.FallbackMessageContainer, allocator: std.mem.Allocator, pub fn format(this: Base64FallbackMessage, comptime _: []const u8, _: std.fmt.FormatOptions, writer: anytype) !void { var bb = std.ArrayList(u8).init(this.allocator); defer bb.deinit(); const bb_writer = bb.writer(); - const Encoder = Schema.Writer(@TypeOf(bb_writer)); + const Encoder = schema.Writer(@TypeOf(bb_writer)); var encoder = Encoder.init(bb_writer); this.msg.encode(&encoder) catch {}; @@ -85,7 +85,7 @@ pub const Fallback = struct { pub fn render( allocator: std.mem.Allocator, - msg: *const Api.FallbackMessageContainer, + msg: *const api.FallbackMessageContainer, preload: string, entry_point: string, comptime WriterType: type, @@ -107,7 +107,7 @@ pub const Fallback = struct { pub fn renderBackend( allocator: std.mem.Allocator, - msg: *const Api.FallbackMessageContainer, + msg: *const api.FallbackMessageContainer, comptime WriterType: type, writer: WriterType, ) !void { @@ -203,7 +203,7 @@ pub const Runtime = struct { /// This is used for `--print` entry points so we can get the result. remove_cjs_module_wrapper: bool = false, - runtime_transpiler_cache: ?*bun.JSC.RuntimeTranspilerCache = null, + runtime_transpiler_cache: ?*bun.jsc.RuntimeTranspilerCache = null, // TODO: make this a bitset of all unsupported features lower_using: bool = true, @@ -444,15 +444,17 @@ pub const Runtime = struct { }; }; -const std = @import("std"); -const Ref = @import("./ast/base.zig").Ref; +const string = []const u8; -const Schema = @import("./api/schema.zig"); -const Api = Schema.Api; +const std = @import("std"); const bun = @import("bun"); const Environment = bun.Environment; -const JSAst = bun.JSAst; const Output = bun.Output; -const string = bun.string; const strings = bun.strings; + +const JSAst = bun.ast; +const Ref = bun.ast.Ref; + +const schema = bun.schema; +const api = schema.api; diff --git a/src/s3/client.zig b/src/s3/client.zig index c555596044..086f658d1a 100644 --- a/src/s3/client.zig +++ b/src/s3/client.zig @@ -185,7 +185,7 @@ pub fn listObjects( .callback_context = callback_context, .callback = .{ .listObjects = callback }, .headers = headers, - .vm = JSC.VirtualMachine.get(), + .vm = jsc.VirtualMachine.get(), }); task.poll_ref.ref(task.vm); @@ -245,14 +245,14 @@ pub fn upload( pub fn writableStream( this: *S3Credentials, path: []const u8, - globalThis: *JSC.JSGlobalObject, + globalThis: *jsc.JSGlobalObject, options: MultiPartUploadOptions, content_type: ?[]const u8, proxy: ?[]const u8, storage_class: ?StorageClass, -) bun.JSError!JSC.JSValue { +) bun.JSError!jsc.JSValue { const Wrapper = struct { - pub fn callback(result: S3UploadResult, sink: *JSC.WebCore.NetworkSink) void { + pub fn callback(result: S3UploadResult, sink: *jsc.WebCore.NetworkSink) void { if (sink.endPromise.hasValue() or sink.flushPromise.hasValue()) { const event_loop = sink.globalThis.bunVM().eventLoop(); event_loop.enter(); @@ -260,10 +260,10 @@ pub fn writableStream( switch (result) { .success => { if (sink.flushPromise.hasValue()) { - sink.flushPromise.resolve(sink.globalThis, JSC.jsNumber(0)); + sink.flushPromise.resolve(sink.globalThis, jsc.jsNumber(0)); } if (sink.endPromise.hasValue()) { - sink.endPromise.resolve(sink.globalThis, JSC.jsNumber(0)); + sink.endPromise.resolve(sink.globalThis, jsc.jsNumber(0)); } }, .failure => |err| { @@ -297,22 +297,22 @@ pub fn writableStream( .callback_context = undefined, .globalThis = globalThis, .options = options, - .vm = JSC.VirtualMachine.get(), + .vm = jsc.VirtualMachine.get(), }); task.poll_ref.ref(task.vm); - var response_stream = JSC.WebCore.NetworkSink.new(.{ + var response_stream = jsc.WebCore.NetworkSink.new(.{ .task = task, .globalThis = globalThis, .highWaterMark = @truncate(options.partSize), }).toSink(); task.callback_context = @ptrCast(response_stream); - task.onWritable = @ptrCast(&JSC.WebCore.NetworkSink.onWritable); + task.onWritable = @ptrCast(&jsc.WebCore.NetworkSink.onWritable); var signal = &response_stream.sink.signal; - signal.* = JSC.WebCore.NetworkSink.JSSink.SinkSignal.init(.zero); + signal.* = jsc.WebCore.NetworkSink.JSSink.SinkSignal.init(.zero); // explicitly set it to a dead pointer // we use this memory address to disable signals being sent @@ -332,11 +332,11 @@ pub const S3UploadStreamWrapper = struct { sink: ?*ResumableSink, task: *MultiPartUpload, - endPromise: JSC.JSPromise.Strong, + endPromise: jsc.JSPromise.Strong, callback: ?*const fn (S3UploadResult, *anyopaque) void, callback_context: *anyopaque, path: []const u8, // this is owned by the task not by the wrapper - global: *JSC.JSGlobalObject, + global: *jsc.JSGlobalObject, fn detachSink(self: *@This()) void { log("detachSink {}", .{self.sink != null}); @@ -360,7 +360,7 @@ pub const S3UploadStreamWrapper = struct { return this.task.writeBytes(data, false) catch bun.outOfMemory(); } - pub fn writeEndRequest(this: *@This(), err: ?JSC.JSValue) void { + pub fn writeEndRequest(this: *@This(), err: ?jsc.JSValue) void { log("writeEndRequest {}", .{err != null}); this.detachSink(); defer this.deref(); @@ -389,7 +389,7 @@ pub const S3UploadStreamWrapper = struct { switch (result) { .success => { if (self.endPromise.hasValue()) { - self.endPromise.resolve(self.global, JSC.jsNumber(0)); + self.endPromise.resolve(self.global, jsc.jsNumber(0)); self.endPromise = .empty; } }, @@ -424,8 +424,8 @@ pub const S3UploadStreamWrapper = struct { pub fn uploadStream( this: *S3Credentials, path: []const u8, - readable_stream: JSC.WebCore.ReadableStream, - globalThis: *JSC.JSGlobalObject, + readable_stream: jsc.WebCore.ReadableStream, + globalThis: *jsc.JSGlobalObject, options: MultiPartUploadOptions, acl: ?ACL, storage_class: ?StorageClass, @@ -433,16 +433,16 @@ pub fn uploadStream( proxy: ?[]const u8, callback: ?*const fn (S3UploadResult, *anyopaque) void, callback_context: *anyopaque, -) JSC.JSValue { +) jsc.JSValue { this.ref(); // ref the credentials const proxy_url = (proxy orelse ""); if (readable_stream.isDisturbed(globalThis)) { - return JSC.JSPromise.rejectedPromise(globalThis, bun.String.static("ReadableStream is already disturbed").toErrorInstance(globalThis)).toJS(); + return jsc.JSPromise.rejectedPromise(globalThis, bun.String.static("ReadableStream is already disturbed").toErrorInstance(globalThis)).toJS(); } switch (readable_stream.ptr) { .Invalid => { - return JSC.JSPromise.rejectedPromise(globalThis, bun.String.static("ReadableStream is invalid").toErrorInstance(globalThis)).toJS(); + return jsc.JSPromise.rejectedPromise(globalThis, bun.String.static("ReadableStream is invalid").toErrorInstance(globalThis)).toJS(); }, inline .File, .Bytes => |stream| { if (stream.pending.result == .err) { @@ -454,7 +454,7 @@ pub fn uploadStream( js_err.unprotect(); } js_err.ensureStillAlive(); - return JSC.JSPromise.rejectedPromise(globalThis, js_err).toJS(); + return jsc.JSPromise.rejectedPromise(globalThis, js_err).toJS(); } }, else => {}, @@ -473,7 +473,7 @@ pub fn uploadStream( .options = options, .acl = acl, .storage_class = storage_class, - .vm = JSC.VirtualMachine.get(), + .vm = jsc.VirtualMachine.get(), }); task.poll_ref.ref(task.vm); @@ -485,7 +485,7 @@ pub fn uploadStream( .callback_context = callback_context, .path = task.path, .task = task, - .endPromise = JSC.JSPromise.Strong.init(globalThis), + .endPromise = jsc.JSPromise.Strong.init(globalThis), .global = globalThis, }); // +1 because the ctx refs the sink @@ -552,7 +552,7 @@ pub fn downloadStream( .callback = callback, .range = range, .headers = headers, - .vm = JSC.VirtualMachine.get(), + .vm = jsc.VirtualMachine.get(), }); task.poll_ref.ref(task.vm); @@ -596,9 +596,9 @@ pub fn readableStream( offset: usize, size: ?usize, proxy_url: ?[]const u8, - globalThis: *JSC.JSGlobalObject, -) bun.JSError!JSC.JSValue { - var reader = JSC.WebCore.ByteStream.Source.new(.{ + globalThis: *jsc.JSGlobalObject, +) bun.JSError!jsc.JSValue { + var reader = jsc.WebCore.ByteStream.Source.new(.{ .context = undefined, .globalThis = globalThis, }); @@ -609,9 +609,9 @@ pub fn readableStream( const S3DownloadStreamWrapper = struct { pub const new = bun.TrivialNew(@This()); - readable_stream_ref: JSC.WebCore.ReadableStream.Strong, + readable_stream_ref: jsc.WebCore.ReadableStream.Strong, path: []const u8, - global: *JSC.JSGlobalObject, + global: *jsc.JSGlobalObject, pub fn callback(chunk: bun.MutableString, has_more: bool, request_err: ?Error.S3Error, self: *@This()) void { defer if (!has_more) self.deinit(); @@ -662,7 +662,7 @@ pub fn readableStream( proxy_url, S3DownloadStreamWrapper.opaqueCallback, S3DownloadStreamWrapper.new(.{ - .readable_stream_ref = JSC.WebCore.ReadableStream.Strong.init(.{ + .readable_stream_ref = jsc.WebCore.ReadableStream.Strong.init(.{ .ptr = .{ .Bytes = &reader.context }, .value = readable_value, }, globalThis), @@ -679,5 +679,5 @@ const S3SimpleRequest = @import("./simple_request.zig"); const std = @import("std"); const bun = @import("bun"); -const JSC = bun.JSC; +const jsc = bun.jsc; const picohttp = bun.picohttp; diff --git a/src/s3/credentials.zig b/src/s3/credentials.zig index fd2a97445b..b0e0053c0e 100644 --- a/src/s3/credentials.zig +++ b/src/s3/credentials.zig @@ -35,7 +35,7 @@ pub const S3Credentials = struct { return hasher.final(); } - pub fn getCredentialsWithOptions(this: S3Credentials, default_options: MultiPartUploadOptions, options: ?JSC.JSValue, default_acl: ?ACL, default_storage_class: ?StorageClass, globalObject: *JSC.JSGlobalObject) bun.JSError!S3CredentialsWithOptions { + pub fn getCredentialsWithOptions(this: S3Credentials, default_options: MultiPartUploadOptions, options: ?jsc.JSValue, default_acl: ?ACL, default_storage_class: ?StorageClass, globalObject: *jsc.JSGlobalObject) bun.JSError!S3CredentialsWithOptions { bun.analytics.Features.s3 += 1; // get ENV config var new_credentials = S3CredentialsWithOptions{ @@ -284,10 +284,10 @@ pub const S3Credentials = struct { }; fn getAMZDate(allocator: std.mem.Allocator) DateResult { - // We can also use Date.now() but would be slower and would add JSC dependency + // We can also use Date.now() but would be slower and would add jsc dependency // var buffer: [28]u8 = undefined; // the code bellow is the same as new Date(Date.now()).toISOString() - // JSC.JSValue.getDateNowISOString(globalObject, &buffer); + // jsc.JSValue.getDateNowISOString(globalObject, &buffer); // Create UTC timestamp const secs: u64 = @intCast(@divFloor(std.time.milliTimestamp(), 1000)); @@ -754,7 +754,7 @@ pub const S3Credentials = struct { const sigDateRegionServiceReq = brk_sign: { const key = try std.fmt.bufPrint(&tmp_buffer, "{s}{s}{s}", .{ region, service_name, this.secretAccessKey }); - var cache = (JSC.VirtualMachine.getMainThreadVM() orelse JSC.VirtualMachine.get()).rareData().awsCache(); + var cache = (jsc.VirtualMachine.getMainThreadVM() orelse jsc.VirtualMachine.get()).rareData().awsCache(); if (cache.get(date_result.numeric_day, key)) |cached| { break :brk_sign cached; } @@ -827,7 +827,7 @@ pub const S3Credentials = struct { break :brk_canonical try std.fmt.bufPrint(&tmp_buffer, "{s}\n{s}\n{s}\nhost:{s}\n\nhost\n{s}", .{ method_name, normalizedPath, query_string.items, host, aws_content_hash }); }; var sha_digest = std.mem.zeroes(bun.sha.SHA256.Digest); - bun.sha.SHA256.hash(canonical, &sha_digest, JSC.VirtualMachine.get().rareData().boringEngine()); + bun.sha.SHA256.hash(canonical, &sha_digest, jsc.VirtualMachine.get().rareData().boringEngine()); const signValue = try std.fmt.bufPrint(&tmp_buffer, "AWS4-HMAC-SHA256\n{s}\n{s}/{s}/{s}/aws4_request\n{s}", .{ amz_date, amz_day, region, service_name, std.fmt.bytesToHex(sha_digest[0..bun.sha.SHA256.digest], .lower) }); @@ -1019,7 +1019,7 @@ pub const S3Credentials = struct { } }; var sha_digest = std.mem.zeroes(bun.sha.SHA256.Digest); - bun.sha.SHA256.hash(canonical, &sha_digest, JSC.VirtualMachine.get().rareData().boringEngine()); + bun.sha.SHA256.hash(canonical, &sha_digest, jsc.VirtualMachine.get().rareData().boringEngine()); const signValue = try std.fmt.bufPrint(&tmp_buffer, "AWS4-HMAC-SHA256\n{s}\n{s}/{s}/{s}/aws4_request\n{s}", .{ amz_date, amz_day, region, service_name, std.fmt.bytesToHex(sha_digest[0..bun.sha.SHA256.digest], .lower) }); @@ -1112,12 +1112,12 @@ pub const S3CredentialsWithOptions = struct { changed_credentials: bool = false, /// indicates if the virtual hosted style is used virtual_hosted_style: bool = false, - _accessKeyIdSlice: ?JSC.ZigString.Slice = null, - _secretAccessKeySlice: ?JSC.ZigString.Slice = null, - _regionSlice: ?JSC.ZigString.Slice = null, - _endpointSlice: ?JSC.ZigString.Slice = null, - _bucketSlice: ?JSC.ZigString.Slice = null, - _sessionTokenSlice: ?JSC.ZigString.Slice = null, + _accessKeyIdSlice: ?jsc.ZigString.Slice = null, + _secretAccessKeySlice: ?jsc.ZigString.Slice = null, + _regionSlice: ?jsc.ZigString.Slice = null, + _endpointSlice: ?jsc.ZigString.Slice = null, + _bucketSlice: ?jsc.ZigString.Slice = null, + _sessionTokenSlice: ?jsc.ZigString.Slice = null, pub fn deinit(this: *@This()) void { if (this._accessKeyIdSlice) |slice| slice.deinit(); @@ -1135,6 +1135,6 @@ const MultiPartUploadOptions = @import("./multipart_options.zig").MultiPartUploa const StorageClass = @import("./storage_class.zig").StorageClass; const bun = @import("bun"); -const JSC = bun.JSC; +const jsc = bun.jsc; const picohttp = bun.picohttp; const strings = bun.strings; diff --git a/src/s3/download_stream.zig b/src/s3/download_stream.zig index 8971ce6d5b..d743eee668 100644 --- a/src/s3/download_stream.zig +++ b/src/s3/download_stream.zig @@ -3,7 +3,7 @@ pub const S3HttpDownloadStreamingTask = struct { pub const new = bun.TrivialNew(@This()); http: bun.http.AsyncHTTP, - vm: *JSC.VirtualMachine, + vm: *jsc.VirtualMachine, sign_result: SignResult, headers: bun.http.Headers, callback_context: *anyopaque, @@ -31,7 +31,7 @@ pub const S3HttpDownloadStreamingTask = struct { }, state: State.AtomicType = State.AtomicType.init(@bitCast(State{})), - concurrent_task: JSC.ConcurrentTask = .{}, + concurrent_task: jsc.ConcurrentTask = .{}, range: ?[]const u8, proxy_url: []const u8, @@ -240,5 +240,5 @@ const S3Credentials = @import("./credentials.zig").S3Credentials; const SignResult = S3Credentials.SignResult; const bun = @import("bun"); -const JSC = bun.JSC; +const jsc = bun.jsc; const strings = bun.strings; diff --git a/src/s3/error.zig b/src/s3/error.zig index ebcd46e009..adc481c91d 100644 --- a/src/s3/error.zig +++ b/src/s3/error.zig @@ -12,7 +12,7 @@ pub fn getSignErrorMessage(comptime err: anyerror) [:0]const u8 { else => return "Failed to retrieve S3 content. Are the credentials correct?", }; } -pub fn getJSSignError(err: anyerror, globalThis: *JSC.JSGlobalObject) JSC.JSValue { +pub fn getJSSignError(err: anyerror, globalThis: *jsc.JSGlobalObject) jsc.JSValue { return switch (err) { error.MissingCredentials => return globalThis.ERR(.S3_MISSING_CREDENTIALS, getSignErrorMessage(error.MissingCredentials), .{}).toJS(), error.InvalidMethod => return globalThis.ERR(.S3_INVALID_METHOD, getSignErrorMessage(error.InvalidMethod), .{}).toJS(), @@ -22,7 +22,7 @@ pub fn getJSSignError(err: anyerror, globalThis: *JSC.JSGlobalObject) JSC.JSValu else => return globalThis.ERR(.S3_INVALID_SIGNATURE, getSignErrorMessage(error.SignError), .{}).toJS(), }; } -pub fn throwSignError(err: anyerror, globalThis: *JSC.JSGlobalObject) bun.JSError { +pub fn throwSignError(err: anyerror, globalThis: *jsc.JSGlobalObject) bun.JSError { return switch (err) { error.MissingCredentials => globalThis.ERR(.S3_MISSING_CREDENTIALS, getSignErrorMessage(error.MissingCredentials), .{}).throw(), error.InvalidMethod => globalThis.ERR(.S3_INVALID_METHOD, getSignErrorMessage(error.InvalidMethod), .{}).throw(), @@ -64,19 +64,19 @@ const JSS3Error = extern struct { this.message.deref(); } - pub fn toErrorInstance(this: *const @This(), global: *JSC.JSGlobalObject) JSC.JSValue { + pub fn toErrorInstance(this: *const @This(), global: *jsc.JSGlobalObject) jsc.JSValue { defer this.deinit(); return S3Error__toErrorInstance(this, global); } - extern fn S3Error__toErrorInstance(this: *const @This(), global: *JSC.JSGlobalObject) callconv(JSC.conv) JSC.JSValue; + extern fn S3Error__toErrorInstance(this: *const @This(), global: *jsc.JSGlobalObject) callconv(jsc.conv) jsc.JSValue; }; pub const S3Error = struct { code: []const u8, message: []const u8, - pub fn toJS(err: *const @This(), globalObject: *JSC.JSGlobalObject, path: ?[]const u8) JSC.JSValue { + pub fn toJS(err: *const @This(), globalObject: *jsc.JSGlobalObject, path: ?[]const u8) jsc.JSValue { const value = JSS3Error.init(err.code, err.message, path).toErrorInstance(globalObject); bun.assert(!globalObject.hasException()); return value; @@ -84,4 +84,4 @@ pub const S3Error = struct { }; const bun = @import("bun"); -const JSC = bun.JSC; +const jsc = bun.jsc; diff --git a/src/s3/list_objects.zig b/src/s3/list_objects.zig index 3b9aca8f66..4a962e724e 100644 --- a/src/s3/list_objects.zig +++ b/src/s3/list_objects.zig @@ -7,11 +7,11 @@ pub const S3ListObjectsOptions = struct { prefix: ?[]const u8, start_after: ?[]const u8, - _continuation_token: ?JSC.ZigString.Slice, - _delimiter: ?JSC.ZigString.Slice, - _encoding_type: ?JSC.ZigString.Slice, - _prefix: ?JSC.ZigString.Slice, - _start_after: ?JSC.ZigString.Slice, + _continuation_token: ?jsc.ZigString.Slice, + _delimiter: ?jsc.ZigString.Slice, + _encoding_type: ?jsc.ZigString.Slice, + _prefix: ?jsc.ZigString.Slice, + _start_after: ?jsc.ZigString.Slice, pub fn deinit(this: *@This()) void { if (this._continuation_token) |slice| slice.deinit(); @@ -71,42 +71,42 @@ pub const S3ListObjectsV2Result = struct { const jsResult = JSValue.createEmptyObject(globalObject, 12); if (this.name) |name| { - jsResult.put(globalObject, JSC.ZigString.static("name"), try bun.String.createUTF8ForJS(globalObject, name)); + jsResult.put(globalObject, jsc.ZigString.static("name"), try bun.String.createUTF8ForJS(globalObject, name)); } if (this.prefix) |prefix| { - jsResult.put(globalObject, JSC.ZigString.static("prefix"), try bun.String.createUTF8ForJS(globalObject, prefix)); + jsResult.put(globalObject, jsc.ZigString.static("prefix"), try bun.String.createUTF8ForJS(globalObject, prefix)); } if (this.delimiter) |delimiter| { - jsResult.put(globalObject, JSC.ZigString.static("delimiter"), try bun.String.createUTF8ForJS(globalObject, delimiter)); + jsResult.put(globalObject, jsc.ZigString.static("delimiter"), try bun.String.createUTF8ForJS(globalObject, delimiter)); } if (this.start_after) |start_after| { - jsResult.put(globalObject, JSC.ZigString.static("startAfter"), try bun.String.createUTF8ForJS(globalObject, start_after)); + jsResult.put(globalObject, jsc.ZigString.static("startAfter"), try bun.String.createUTF8ForJS(globalObject, start_after)); } if (this.encoding_type) |encoding_type| { - jsResult.put(globalObject, JSC.ZigString.static("encodingType"), try bun.String.createUTF8ForJS(globalObject, encoding_type)); + jsResult.put(globalObject, jsc.ZigString.static("encodingType"), try bun.String.createUTF8ForJS(globalObject, encoding_type)); } if (this.continuation_token) |continuation_token| { - jsResult.put(globalObject, JSC.ZigString.static("continuationToken"), try bun.String.createUTF8ForJS(globalObject, continuation_token)); + jsResult.put(globalObject, jsc.ZigString.static("continuationToken"), try bun.String.createUTF8ForJS(globalObject, continuation_token)); } if (this.next_continuation_token) |next_continuation_token| { - jsResult.put(globalObject, JSC.ZigString.static("nextContinuationToken"), try bun.String.createUTF8ForJS(globalObject, next_continuation_token)); + jsResult.put(globalObject, jsc.ZigString.static("nextContinuationToken"), try bun.String.createUTF8ForJS(globalObject, next_continuation_token)); } if (this.is_truncated) |is_truncated| { - jsResult.put(globalObject, JSC.ZigString.static("isTruncated"), JSValue.jsBoolean(is_truncated)); + jsResult.put(globalObject, jsc.ZigString.static("isTruncated"), JSValue.jsBoolean(is_truncated)); } if (this.key_count) |key_count| { - jsResult.put(globalObject, JSC.ZigString.static("keyCount"), JSValue.jsNumber(key_count)); + jsResult.put(globalObject, jsc.ZigString.static("keyCount"), JSValue.jsNumber(key_count)); } if (this.max_keys) |max_keys| { - jsResult.put(globalObject, JSC.ZigString.static("maxKeys"), JSValue.jsNumber(max_keys)); + jsResult.put(globalObject, jsc.ZigString.static("maxKeys"), JSValue.jsNumber(max_keys)); } if (this.contents) |contents| { @@ -114,49 +114,49 @@ pub const S3ListObjectsV2Result = struct { for (contents.items, 0..) |item, i| { const objectInfo = JSValue.createEmptyObject(globalObject, 1); - objectInfo.put(globalObject, JSC.ZigString.static("key"), try bun.String.createUTF8ForJS(globalObject, item.key)); + objectInfo.put(globalObject, jsc.ZigString.static("key"), try bun.String.createUTF8ForJS(globalObject, item.key)); if (item.etag) |etag| { - objectInfo.put(globalObject, JSC.ZigString.static("eTag"), try bun.String.createUTF8ForJS(globalObject, etag)); + objectInfo.put(globalObject, jsc.ZigString.static("eTag"), try bun.String.createUTF8ForJS(globalObject, etag)); } if (item.checksum_algorithme) |checksum_algorithme| { - objectInfo.put(globalObject, JSC.ZigString.static("checksumAlgorithme"), try bun.String.createUTF8ForJS(globalObject, checksum_algorithme)); + objectInfo.put(globalObject, jsc.ZigString.static("checksumAlgorithme"), try bun.String.createUTF8ForJS(globalObject, checksum_algorithme)); } if (item.checksum_type) |checksum_type| { - objectInfo.put(globalObject, JSC.ZigString.static("checksumType"), try bun.String.createUTF8ForJS(globalObject, checksum_type)); + objectInfo.put(globalObject, jsc.ZigString.static("checksumType"), try bun.String.createUTF8ForJS(globalObject, checksum_type)); } if (item.last_modified) |last_modified| { - objectInfo.put(globalObject, JSC.ZigString.static("lastModified"), try bun.String.createUTF8ForJS(globalObject, last_modified)); + objectInfo.put(globalObject, jsc.ZigString.static("lastModified"), try bun.String.createUTF8ForJS(globalObject, last_modified)); } if (item.object_size) |object_size| { - objectInfo.put(globalObject, JSC.ZigString.static("size"), JSValue.jsNumber(object_size)); + objectInfo.put(globalObject, jsc.ZigString.static("size"), JSValue.jsNumber(object_size)); } if (item.storage_class) |storage_class| { - objectInfo.put(globalObject, JSC.ZigString.static("storageClass"), try bun.String.createUTF8ForJS(globalObject, storage_class)); + objectInfo.put(globalObject, jsc.ZigString.static("storageClass"), try bun.String.createUTF8ForJS(globalObject, storage_class)); } if (item.owner) |owner| { const jsOwner = JSValue.createEmptyObject(globalObject, 2); if (owner.id) |id| { - jsOwner.put(globalObject, JSC.ZigString.static("id"), try bun.String.createUTF8ForJS(globalObject, id)); + jsOwner.put(globalObject, jsc.ZigString.static("id"), try bun.String.createUTF8ForJS(globalObject, id)); } if (owner.display_name) |display_name| { - jsOwner.put(globalObject, JSC.ZigString.static("displayName"), try bun.String.createUTF8ForJS(globalObject, display_name)); + jsOwner.put(globalObject, jsc.ZigString.static("displayName"), try bun.String.createUTF8ForJS(globalObject, display_name)); } - objectInfo.put(globalObject, JSC.ZigString.static("owner"), jsOwner); + objectInfo.put(globalObject, jsc.ZigString.static("owner"), jsOwner); } try jsContents.putIndex(globalObject, @intCast(i), objectInfo); } - jsResult.put(globalObject, JSC.ZigString.static("contents"), jsContents); + jsResult.put(globalObject, jsc.ZigString.static("contents"), jsContents); } if (this.common_prefixes) |common_prefixes| { @@ -164,11 +164,11 @@ pub const S3ListObjectsV2Result = struct { for (common_prefixes.items, 0..) |prefix, i| { const jsPrefix = JSValue.createEmptyObject(globalObject, 1); - jsPrefix.put(globalObject, JSC.ZigString.static("prefix"), try bun.String.createUTF8ForJS(globalObject, prefix)); + jsPrefix.put(globalObject, jsc.ZigString.static("prefix"), try bun.String.createUTF8ForJS(globalObject, prefix)); try jsCommonPrefixes.putIndex(globalObject, @intCast(i), jsPrefix); } - jsResult.put(globalObject, JSC.ZigString.static("commonPrefixes"), jsCommonPrefixes); + jsResult.put(globalObject, jsc.ZigString.static("commonPrefixes"), jsCommonPrefixes); } return jsResult; @@ -490,7 +490,7 @@ pub fn parseS3ListObjectsResult(xml: []const u8) !S3ListObjectsV2Result { return result; } -pub fn getListObjectsOptionsFromJS(globalThis: *JSC.JSGlobalObject, listOptions: JSValue) !S3ListObjectsOptions { +pub fn getListObjectsOptionsFromJS(globalThis: *jsc.JSGlobalObject, listOptions: JSValue) !S3ListObjectsOptions { var listObjectsOptions: S3ListObjectsOptions = .{ .continuation_token = null, .delimiter = null, @@ -584,6 +584,6 @@ const std = @import("std"); const bun = @import("bun"); const strings = bun.strings; -const JSC = bun.JSC; -const JSGlobalObject = JSC.JSGlobalObject; -const JSValue = JSC.JSValue; +const jsc = bun.jsc; +const JSGlobalObject = jsc.JSGlobalObject; +const JSValue = jsc.JSValue; diff --git a/src/s3/multipart.zig b/src/s3/multipart.zig index 99a521277d..a16daa2a7f 100644 --- a/src/s3/multipart.zig +++ b/src/s3/multipart.zig @@ -107,8 +107,8 @@ pub const MultiPartUpload = struct { storage_class: ?Storageclass = null, credentials: *S3Credentials, poll_ref: bun.Async.KeepAlive = bun.Async.KeepAlive.init(), - vm: *JSC.VirtualMachine, - globalThis: *JSC.JSGlobalObject, + vm: *jsc.VirtualMachine, + globalThis: *jsc.JSGlobalObject, buffered: bun.io.StreamBuffer = .{}, @@ -764,5 +764,5 @@ const S3SimpleRequest = @import("./simple_request.zig"); const executeSimpleS3Request = S3SimpleRequest.executeSimpleS3Request; const bun = @import("bun"); -const JSC = bun.JSC; +const jsc = bun.jsc; const strings = bun.strings; diff --git a/src/s3/simple_request.zig b/src/s3/simple_request.zig index 2ad22bb146..bbff79df19 100644 --- a/src/s3/simple_request.zig +++ b/src/s3/simple_request.zig @@ -59,7 +59,7 @@ pub const S3PartResult = union(enum) { pub const S3HttpSimpleTask = struct { http: bun.http.AsyncHTTP, - vm: *JSC.VirtualMachine, + vm: *jsc.VirtualMachine, sign_result: SignResult, headers: bun.http.Headers, callback_context: *anyopaque, @@ -72,7 +72,7 @@ pub const S3HttpSimpleTask = struct { }, }, result: bun.http.HTTPClientResult = .{}, - concurrent_task: JSC.ConcurrentTask = .{}, + concurrent_task: jsc.ConcurrentTask = .{}, range: ?[]const u8, poll_ref: bun.Async.KeepAlive = bun.Async.KeepAlive.init(), @@ -403,7 +403,7 @@ pub fn executeSimpleS3Request( .callback = callback, .range = options.range, .headers = headers, - .vm = JSC.VirtualMachine.get(), + .vm = jsc.VirtualMachine.get(), }); task.poll_ref.ref(task.vm); @@ -447,6 +447,6 @@ const S3Error = @import("./error.zig").S3Error; const getSignErrorCodeAndMessage = @import("./error.zig").getSignErrorCodeAndMessage; const bun = @import("bun"); -const JSC = bun.JSC; +const jsc = bun.jsc; const picohttp = bun.picohttp; const strings = bun.strings; diff --git a/src/semver/ExternalString.zig b/src/semver/ExternalString.zig index a2124c9e10..a2425b03c3 100644 --- a/src/semver/ExternalString.zig +++ b/src/semver/ExternalString.zig @@ -44,8 +44,8 @@ pub const ExternalString = extern struct { } }; -const std = @import("std"); +const string = []const u8; const bun = @import("bun"); -const string = bun.string; +const std = @import("std"); const String = bun.Semver.String; diff --git a/src/semver/SemverObject.zig b/src/semver/SemverObject.zig index 670ef98145..e5ba25d32c 100644 --- a/src/semver/SemverObject.zig +++ b/src/semver/SemverObject.zig @@ -1,14 +1,14 @@ const SemverObject = @This(); -pub fn create(globalThis: *JSC.JSGlobalObject) JSC.JSValue { - const object = JSC.JSValue.createEmptyObject(globalThis, 2); +pub fn create(globalThis: *jsc.JSGlobalObject) jsc.JSValue { + const object = jsc.JSValue.createEmptyObject(globalThis, 2); object.put( globalThis, - JSC.ZigString.static("satisfies"), - JSC.host_fn.NewFunction( + jsc.ZigString.static("satisfies"), + jsc.host_fn.NewFunction( globalThis, - JSC.ZigString.static("satisfies"), + jsc.ZigString.static("satisfies"), 2, SemverObject.satisfies, false, @@ -17,10 +17,10 @@ pub fn create(globalThis: *JSC.JSGlobalObject) JSC.JSValue { object.put( globalThis, - JSC.ZigString.static("order"), - JSC.host_fn.NewFunction( + jsc.ZigString.static("order"), + jsc.host_fn.NewFunction( globalThis, - JSC.ZigString.static("order"), + jsc.ZigString.static("order"), 2, SemverObject.order, false, @@ -31,9 +31,9 @@ pub fn create(globalThis: *JSC.JSGlobalObject) JSC.JSValue { } pub fn order( - globalThis: *JSC.JSGlobalObject, - callFrame: *JSC.CallFrame, -) bun.JSError!JSC.JSValue { + globalThis: *jsc.JSGlobalObject, + callFrame: *jsc.CallFrame, +) bun.JSError!jsc.JSValue { var arena = std.heap.ArenaAllocator.init(bun.default_allocator); defer arena.deinit(); var stack_fallback = std.heap.stackFallback(512, arena.allocator()); @@ -55,8 +55,8 @@ pub fn order( const right = right_string.toSlice(globalThis, allocator); defer right.deinit(); - if (!strings.isAllASCII(left.slice())) return JSC.jsNumber(0); - if (!strings.isAllASCII(right.slice())) return JSC.jsNumber(0); + if (!strings.isAllASCII(left.slice())) return jsc.jsNumber(0); + if (!strings.isAllASCII(right.slice())) return jsc.jsNumber(0); const left_result = Version.parse(SlicedString.init(left.slice(), left.slice())); const right_result = Version.parse(SlicedString.init(right.slice(), right.slice())); @@ -73,13 +73,13 @@ pub fn order( const right_version = right_result.version.max(); return switch (left_version.orderWithoutBuild(right_version, left.slice(), right.slice())) { - .eq => JSC.jsNumber(0), - .gt => JSC.jsNumber(1), - .lt => JSC.jsNumber(-1), + .eq => jsc.jsNumber(0), + .gt => jsc.jsNumber(1), + .lt => jsc.jsNumber(-1), }; } -pub fn satisfies(globalThis: *JSC.JSGlobalObject, callFrame: *JSC.CallFrame) bun.JSError!JSC.JSValue { +pub fn satisfies(globalThis: *jsc.JSGlobalObject, callFrame: *jsc.CallFrame) bun.JSError!jsc.JSValue { var arena = std.heap.ArenaAllocator.init(bun.default_allocator); defer arena.deinit(); var stack_fallback = std.heap.stackFallback(512, arena.allocator()); @@ -121,17 +121,17 @@ pub fn satisfies(globalThis: *JSC.JSGlobalObject, callFrame: *JSC.CallFrame) bun const right_version = right_group.getExactVersion(); if (right_version != null) { - return JSC.jsBoolean(left_version.eql(right_version.?)); + return jsc.jsBoolean(left_version.eql(right_version.?)); } - return JSC.jsBoolean(right_group.satisfies(left_version, right.slice(), left.slice())); + return jsc.jsBoolean(right_group.satisfies(left_version, right.slice(), left.slice())); } const std = @import("std"); const bun = @import("bun"); -const JSC = bun.JSC; const default_allocator = bun.default_allocator; +const jsc = bun.jsc; const strings = bun.strings; const Query = bun.Semver.Query; diff --git a/src/semver/SemverQuery.zig b/src/semver/SemverQuery.zig index 0fa6e996b4..fe98e42c6a 100644 --- a/src/semver/SemverQuery.zig +++ b/src/semver/SemverQuery.zig @@ -776,6 +776,8 @@ pub fn parse( return list; } +const string = []const u8; + const std = @import("std"); const Allocator = std.mem.Allocator; @@ -784,7 +786,6 @@ const Environment = bun.Environment; const OOM = bun.OOM; const assert = bun.assert; const default_allocator = bun.default_allocator; -const string = bun.string; const strings = bun.strings; const Range = bun.Semver.Range; diff --git a/src/semver/SemverRange.zig b/src/semver/SemverRange.zig index e087587cc6..c239c82bce 100644 --- a/src/semver/SemverRange.zig +++ b/src/semver/SemverRange.zig @@ -248,12 +248,13 @@ pub fn satisfiesPre(range: Range, version: Version, range_buf: string, version_b return true; } +const string = []const u8; + const std = @import("std"); const bun = @import("bun"); const Environment = bun.Environment; const assert = bun.assert; -const string = bun.string; const Query = bun.Semver.Query; const Version = bun.Semver.Version; diff --git a/src/semver/SemverString.zig b/src/semver/SemverString.zig index 9370abe276..649737a868 100644 --- a/src/semver/SemverString.zig +++ b/src/semver/SemverString.zig @@ -451,7 +451,7 @@ pub const String = extern struct { return @as(Pointer, @bitCast(@as(u64, @as(u63, @truncate(@as(u64, @bitCast(this))))))); } - pub fn toJS(this: *const String, buffer: []const u8, globalThis: *JSC.JSGlobalObject) bun.JSError!JSC.JSValue { + pub fn toJS(this: *const String, buffer: []const u8, globalThis: *jsc.JSGlobalObject) bun.JSError!jsc.JSValue { return bun.String.createUTF8ForJS(globalThis, this.slice(buffer)); } @@ -644,16 +644,17 @@ pub const String = extern struct { } }; +const string = []const u8; + const std = @import("std"); const Allocator = std.mem.Allocator; const bun = @import("bun"); const Environment = bun.Environment; const IdentityContext = bun.IdentityContext; -const JSC = bun.JSC; const OOM = bun.OOM; const assert = bun.assert; -const string = bun.string; +const jsc = bun.jsc; const strings = bun.strings; const Lockfile = bun.install.Lockfile; diff --git a/src/semver/SlicedString.zig b/src/semver/SlicedString.zig index f7f58ddebc..0f7ef55909 100644 --- a/src/semver/SlicedString.zig +++ b/src/semver/SlicedString.zig @@ -37,10 +37,11 @@ pub inline fn sub(this: SlicedString, input: string) SlicedString { return SlicedString{ .buf = this.buf, .slice = input }; } +const string = []const u8; + const bun = @import("bun"); const Environment = bun.Environment; const assert = bun.assert; -const string = bun.string; const ExternalString = bun.Semver.ExternalString; const String = bun.Semver.String; diff --git a/src/semver/Version.zig b/src/semver/Version.zig index d52612a36e..25489d33e5 100644 --- a/src/semver/Version.zig +++ b/src/semver/Version.zig @@ -985,13 +985,14 @@ pub const Version = extern struct { } }; +const string = []const u8; + const std = @import("std"); const bun = @import("bun"); const Environment = bun.Environment; const Output = bun.Output; const assert = bun.assert; -const string = bun.string; const strings = bun.strings; const ExternalString = bun.Semver.ExternalString; diff --git a/src/shell/Builtin.zig b/src/shell/Builtin.zig index ea0137213a..4957aca821 100644 --- a/src/shell/Builtin.zig +++ b/src/shell/Builtin.zig @@ -252,7 +252,7 @@ pub const BuiltinIO = struct { }; const ArrayBuf = struct { - buf: JSC.ArrayBuffer.Strong, + buf: jsc.ArrayBuffer.Strong, i: u32 = 0, }; @@ -493,7 +493,7 @@ fn initRedirections( .jsbuf => |val| { const globalObject = interpreter.event_loop.js.global; if (interpreter.jsobjs[file.jsbuf.idx].asArrayBuffer(globalObject)) |buf| { - const arraybuf: BuiltinIO.ArrayBuf = .{ .buf = JSC.ArrayBuffer.Strong{ + const arraybuf: BuiltinIO.ArrayBuf = .{ .buf = jsc.ArrayBuffer.Strong{ .array_buffer = buf, .held = .create(buf.value, globalObject), }, .i = 0 }; @@ -512,7 +512,7 @@ fn initRedirections( cmd.exec.bltn.stderr.deref(); cmd.exec.bltn.stderr = .{ .arraybuf = arraybuf }; } - } else if (interpreter.jsobjs[file.jsbuf.idx].as(JSC.WebCore.Body.Value)) |body| { + } else if (interpreter.jsobjs[file.jsbuf.idx].as(jsc.WebCore.Body.Value)) |body| { if ((node.redirect.stdout or node.redirect.stderr) and !(body.* == .Blob and !body.Blob.needsToReadFile())) { // TODO: Locked->stream -> file -> blob conversion via .toBlobIfPossible() except we want to avoid modifying the Response/Request if unnecessary. cmd.base.interpreter.event_loop.js.global.throw("Cannot redirect stdout/stderr to an immutable blob. Expected a file", .{}) catch {}; @@ -541,7 +541,7 @@ fn initRedirections( cmd.exec.bltn.stderr.deref(); cmd.exec.bltn.stderr = .{ .blob = blob }; } - } else if (interpreter.jsobjs[file.jsbuf.idx].as(JSC.WebCore.Blob)) |blob| { + } else if (interpreter.jsobjs[file.jsbuf.idx].as(jsc.WebCore.Blob)) |blob| { if ((node.redirect.stdout or node.redirect.stderr) and !blob.needsToReadFile()) { // TODO: Locked->stream -> file -> blob conversion via .toBlobIfPossible() except we want to avoid modifying the Response/Request if unnecessary. cmd.base.interpreter.event_loop.js.global.throw("Cannot redirect stdout/stderr to an immutable blob. Expected a file", .{}) catch {}; @@ -585,7 +585,7 @@ fn initRedirections( return null; } -pub inline fn eventLoop(this: *const Builtin) JSC.EventLoopHandle { +pub inline fn eventLoop(this: *const Builtin) jsc.EventLoopHandle { return this.parentCmd().base.eventLoop(); } @@ -725,7 +725,7 @@ pub fn taskErrorToString(this: *Builtin, comptime kind: Kind, err: anytype) []co } return this.fmtErrorArena(kind, "unknown error {d}\n", .{err.errno}); }, - JSC.SystemError => { + jsc.SystemError => { if (err.path.length() == 0) return this.fmtErrorArena(kind, "{s}\n", .{err.message.byteSlice()}); return this.fmtErrorArena(kind, "{s}: {s}\n", .{ err.message.byteSlice(), err.path }); }, @@ -771,7 +771,7 @@ const std = @import("std"); const Allocator = std.mem.Allocator; const bun = @import("bun"); -const JSC = bun.JSC; +const jsc = bun.jsc; const shell = bun.shell; const Yield = bun.shell.Yield; diff --git a/src/shell/IOReader.zig b/src/shell/IOReader.zig index c87444aee0..95050534d3 100644 --- a/src/shell/IOReader.zig +++ b/src/shell/IOReader.zig @@ -14,9 +14,9 @@ buf: std.ArrayListUnmanaged(u8) = .{}, readers: Readers = .{ .inlined = .{} }, read: usize = 0, ref_count: RefCount, -err: ?JSC.SystemError = null, -evtloop: JSC.EventLoopHandle, -concurrent_task: JSC.EventLoopTask, +err: ?jsc.SystemError = null, +evtloop: jsc.EventLoopHandle, +concurrent_task: jsc.EventLoopTask, async_deinit: AsyncDeinitReader, is_reading: if (bun.Environment.isWindows) bool else u0 = if (bun.Environment.isWindows) false else 0, @@ -35,7 +35,7 @@ pub fn refSelf(this: *IOReader) *IOReader { return this; } -pub fn eventLoop(this: *IOReader) JSC.EventLoopHandle { +pub fn eventLoop(this: *IOReader) jsc.EventLoopHandle { return this.evtloop; } @@ -43,13 +43,13 @@ pub fn loop(this: *IOReader) *bun.uws.Loop { return this.evtloop.loop(); } -pub fn init(fd: bun.FileDescriptor, evtloop: JSC.EventLoopHandle) *IOReader { +pub fn init(fd: bun.FileDescriptor, evtloop: jsc.EventLoopHandle) *IOReader { const this = bun.new(IOReader, .{ .ref_count = .init(), .fd = fd, .reader = ReaderImpl.init(@This()), .evtloop = evtloop, - .concurrent_task = JSC.EventLoopTask.fromEventLoop(evtloop), + .concurrent_task = jsc.EventLoopTask.fromEventLoop(evtloop), .async_deinit = .{}, }); log("IOReader(0x{x}, fd={}) create", .{ @intFromPtr(this), fd }); @@ -228,7 +228,7 @@ pub const IOReaderChildPtr = struct { return this.ptr.call("onIOReaderChunk", .{ chunk, remove }, Yield); } - pub fn onReaderDone(this: IOReaderChildPtr, err: ?JSC.SystemError) Yield { + pub fn onReaderDone(this: IOReaderChildPtr, err: ?jsc.SystemError) Yield { return this.ptr.call("onIOReaderDone", .{err}, Yield); } }; @@ -265,7 +265,7 @@ pub const AsyncDeinitReader = struct { const std = @import("std"); const bun = @import("bun"); -const JSC = bun.JSC; +const jsc = bun.jsc; const shell = bun.shell; const Interpreter = bun.shell.Interpreter; diff --git a/src/shell/IOWriter.zig b/src/shell/IOWriter.zig index c98b8f45d9..80c8524432 100644 --- a/src/shell/IOWriter.zig +++ b/src/shell/IOWriter.zig @@ -28,10 +28,10 @@ buf: std.ArrayListUnmanaged(u8) = .{}, winbuf: if (bun.Environment.isWindows) std.ArrayListUnmanaged(u8) else u0 = if (bun.Environment.isWindows) .empty else 0, writer_idx: usize = 0, total_bytes_written: usize = 0, -err: ?JSC.SystemError = null, -evtloop: JSC.EventLoopHandle, -concurrent_task: JSC.EventLoopTask, -concurrent_task2: JSC.EventLoopTask, +err: ?jsc.SystemError = null, +evtloop: jsc.EventLoopHandle, +concurrent_task: jsc.EventLoopTask, +concurrent_task2: jsc.EventLoopTask, is_writing: bool = false, async_deinit: AsyncDeinitWriter = .{}, started: bool = false, @@ -78,13 +78,13 @@ pub const Flags = packed struct(u8) { __unused: u4 = 0, }; -pub fn init(fd: bun.FileDescriptor, flags: Flags, evtloop: JSC.EventLoopHandle) *IOWriter { +pub fn init(fd: bun.FileDescriptor, flags: Flags, evtloop: jsc.EventLoopHandle) *IOWriter { const this = bun.new(IOWriter, .{ .ref_count = .init(), .fd = fd, .evtloop = evtloop, - .concurrent_task = JSC.EventLoopTask.fromEventLoop(evtloop), - .concurrent_task2 = JSC.EventLoopTask.fromEventLoop(evtloop), + .concurrent_task = jsc.EventLoopTask.fromEventLoop(evtloop), + .concurrent_task2 = jsc.EventLoopTask.fromEventLoop(evtloop), }); this.writer.parent = this; @@ -160,7 +160,7 @@ pub fn __start(this: *IOWriter) Maybe(void) { return Maybe(void).success; } -pub fn eventLoop(this: *IOWriter) JSC.EventLoopHandle { +pub fn eventLoop(this: *IOWriter) jsc.EventLoopHandle { return this.evtloop; } @@ -400,7 +400,7 @@ pub fn brokenPipeForWriters(this: *IOWriter) void { continue; } log("IOWriter(0x{x}, fd={}) brokenPipeForWriters Writer(0x{x}) {s}(0x{x})", .{ @intFromPtr(this), this.fd, @intFromPtr(w), @tagName(w.ptr.ptr.tag()), w.ptr.ptr.repr._ptr }); - const err: JSC.SystemError = bun.sys.Error.fromCode(.PIPE, .write).toSystemError(); + const err: jsc.SystemError = bun.sys.Error.fromCode(.PIPE, .write).toSystemError(); w.ptr.onIOWriterChunk(0, err).run(); offset += w.len; this.cancelChunks(w.ptr); @@ -571,7 +571,7 @@ pub fn enqueueInternal(this: *IOWriter) Yield { pub fn handleBrokenPipe(this: *IOWriter, ptr: ChildPtr) ?Yield { if (this.flags.broken_pipe) { - const err: JSC.SystemError = bun.sys.Error.fromCode(.PIPE, .write).toSystemError(); + const err: jsc.SystemError = bun.sys.Error.fromCode(.PIPE, .write).toSystemError(); log("IOWriter(0x{x}, fd={}) broken pipe {s}(0x{x})", .{ @intFromPtr(this), this.fd, @tagName(ptr.ptr.tag()), @intFromPtr(ptr.ptr.ptr()) }); return .{ .on_io_writer_chunk = .{ .child = ptr.asAnyOpaque(), .written = 0, .err = err } }; } @@ -692,7 +692,7 @@ pub const IOWriterChildPtr = struct { } /// Called when the IOWriter writes a complete chunk of data the child enqueued - pub fn onIOWriterChunk(this: IOWriterChildPtr, amount: usize, err: ?JSC.SystemError) Yield { + pub fn onIOWriterChunk(this: IOWriterChildPtr, amount: usize, err: ?jsc.SystemError) Yield { return this.ptr.call("onIOWriterChunk", .{ amount, err }, Yield); } }; @@ -730,7 +730,7 @@ pub const ChildPtrRaw = bun.TaggedPointerUnion(.{ /// TODO: This function and `drainBufferedData` are copy pastes from /// `PipeWriter.zig`, it would be nice to not have to do that -fn tryWriteWithWriteFn(fd: bun.FileDescriptor, buf: []const u8, comptime write_fn: *const fn (bun.FileDescriptor, []const u8) JSC.Maybe(usize)) bun.io.WriteResult { +fn tryWriteWithWriteFn(fd: bun.FileDescriptor, buf: []const u8, comptime write_fn: *const fn (bun.FileDescriptor, []const u8) jsc.Maybe(usize)) bun.io.WriteResult { var offset: usize = 0; while (offset < buf.len) { @@ -842,8 +842,8 @@ const std = @import("std"); const bun = @import("bun"); const assert = bun.assert; -const JSC = bun.JSC; -const Maybe = JSC.Maybe; +const jsc = bun.jsc; +const Maybe = jsc.Maybe; const shell = bun.shell; const Interpreter = shell.Interpreter; diff --git a/src/shell/ParsedShellScript.zig b/src/shell/ParsedShellScript.zig index c432e005ec..783406ba01 100644 --- a/src/shell/ParsedShellScript.zig +++ b/src/shell/ParsedShellScript.zig @@ -1,6 +1,6 @@ const ParsedShellScript = @This(); -pub const js = JSC.Codegen.JSParsedShellScript; +pub const js = jsc.Codegen.JSParsedShellScript; pub const toJS = js.toJS; pub const fromJS = js.fromJS; pub const fromJSDirect = js.fromJSDirect; @@ -15,7 +15,7 @@ this_jsvalue: JSValue = .zero, pub fn take( this: *ParsedShellScript, - _: *JSC.JSGlobalObject, + _: *jsc.JSGlobalObject, out_args: **ShellArgs, out_jsobjs: *std.ArrayList(JSValue), out_quiet: *bool, @@ -48,9 +48,9 @@ pub fn finalize( bun.destroy(this); } -pub fn setCwd(this: *ParsedShellScript, globalThis: *JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { +pub fn setCwd(this: *ParsedShellScript, globalThis: *JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const arguments_ = callframe.arguments_old(2); - var arguments = JSC.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), arguments_.slice()); + var arguments = jsc.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), arguments_.slice()); const str_js = arguments.nextEat() orelse { return globalThis.throw("$`...`.cwd(): expected a string argument", .{}); }; @@ -59,17 +59,17 @@ pub fn setCwd(this: *ParsedShellScript, globalThis: *JSGlobalObject, callframe: return .js_undefined; } -pub fn setQuiet(this: *ParsedShellScript, _: *JSGlobalObject, _: *JSC.CallFrame) bun.JSError!JSC.JSValue { +pub fn setQuiet(this: *ParsedShellScript, _: *JSGlobalObject, _: *jsc.CallFrame) bun.JSError!jsc.JSValue { this.quiet = true; return .js_undefined; } -pub fn setEnv(this: *ParsedShellScript, globalThis: *JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { +pub fn setEnv(this: *ParsedShellScript, globalThis: *JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const value1 = callframe.argument(0).getObject() orelse { return globalThis.throwInvalidArguments("env must be an object", .{}); }; - var object_iter = try JSC.JSPropertyIterator(.{ + var object_iter = try jsc.JSPropertyIterator(.{ .skip_empty_name = false, .include_value = true, }).init(globalThis, value1); @@ -102,7 +102,7 @@ pub fn setEnv(this: *ParsedShellScript, globalThis: *JSGlobalObject, callframe: return .js_undefined; } -pub fn createParsedShellScript(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { +pub fn createParsedShellScript(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { var shargs = ShellArgs.init(); const arguments_ = callframe.arguments_old(2); @@ -159,9 +159,9 @@ pub fn createParsedShellScript(globalThis: *JSC.JSGlobalObject, callframe: *JSC. .args = shargs, .jsobjs = jsobjs, }); - parsed_shell_script.this_jsvalue = JSC.Codegen.JSParsedShellScript.toJS(parsed_shell_script, globalThis); + parsed_shell_script.this_jsvalue = jsc.Codegen.JSParsedShellScript.toJS(parsed_shell_script, globalThis); - bun.Analytics.Features.shell += 1; + bun.analytics.Features.shell += 1; return parsed_shell_script.this_jsvalue; } @@ -173,12 +173,12 @@ const ShellArgs = interpreter.ShellArgs; const bun = @import("bun"); const assert = bun.assert; -const JSC = bun.JSC; -const JSGlobalObject = JSC.JSGlobalObject; -const JSValue = JSC.JSValue; +const jsc = bun.jsc; +const JSGlobalObject = jsc.JSGlobalObject; +const JSValue = jsc.JSValue; -const CallFrame = JSC.CallFrame; -const ArgumentsSlice = JSC.CallFrame.ArgumentsSlice; +const CallFrame = jsc.CallFrame; +const ArgumentsSlice = jsc.CallFrame.ArgumentsSlice; const shell = bun.shell; const EnvMap = shell.EnvMap; diff --git a/src/shell/Yield.zig b/src/shell/Yield.zig index 6a76145010..fd8570604c 100644 --- a/src/shell/Yield.zig +++ b/src/shell/Yield.zig @@ -46,7 +46,7 @@ pub const Yield = union(enum) { /// it is only used in 2 places. we might need to implement signals /// first tho. on_io_writer_chunk: struct { - err: ?JSC.SystemError, + err: ?jsc.SystemError, written: usize, /// This type is actually `IOWriterChildPtr`, but because /// of an annoying cyclic Zig compile error we're doing this @@ -144,7 +144,7 @@ const std = @import("std"); const bun = @import("bun"); const Environment = bun.Environment; -const JSC = bun.JSC; +const jsc = bun.jsc; const shell = bun.shell; const log = bun.shell.interpret.log; diff --git a/src/shell/builtin/basename.zig b/src/shell/builtin/basename.zig index a20c126841..c3b36c1c7e 100644 --- a/src/shell/builtin/basename.zig +++ b/src/shell/builtin/basename.zig @@ -42,7 +42,7 @@ fn print(this: *@This(), msg: []const u8) void { _ = this.bltn().writeNoIO(.stdout, msg); } -pub fn onIOWriterChunk(this: *@This(), _: usize, maybe_e: ?JSC.SystemError) Yield { +pub fn onIOWriterChunk(this: *@This(), _: usize, maybe_e: ?jsc.SystemError) Yield { if (maybe_e) |e| { defer e.deref(); this.state = .err; @@ -67,5 +67,5 @@ const Interpreter = interpreter.Interpreter; const Builtin = Interpreter.Builtin; const bun = @import("bun"); -const JSC = bun.JSC; +const jsc = bun.jsc; const Yield = bun.shell.Yield; diff --git a/src/shell/builtin/cat.zig b/src/shell/builtin/cat.zig index 177cb605ce..39c2d80223 100644 --- a/src/shell/builtin/cat.zig +++ b/src/shell/builtin/cat.zig @@ -117,7 +117,7 @@ pub fn next(this: *Cat) Yield { } } -pub fn onIOWriterChunk(this: *Cat, _: usize, err: ?JSC.SystemError) Yield { +pub fn onIOWriterChunk(this: *Cat, _: usize, err: ?jsc.SystemError) Yield { debug("onIOWriterChunk(0x{x}, {s}, had_err={any})", .{ @intFromPtr(this), @tagName(this.state), err != null }); const errno: ExitCode = if (err) |e| brk: { defer e.deref(); @@ -201,7 +201,7 @@ pub fn onIOReaderChunk(this: *Cat, chunk: []const u8, remove: *bool) Yield { return .done; } -pub fn onIOReaderDone(this: *Cat, err: ?JSC.SystemError) Yield { +pub fn onIOReaderDone(this: *Cat, err: ?jsc.SystemError) Yield { const errno: ExitCode = if (err) |e| brk: { defer e.deref(); break :brk @as(ExitCode, @intCast(@intFromEnum(e.getErrno()))); @@ -347,7 +347,7 @@ const Builtin = Interpreter.Builtin; const Result = Interpreter.Builtin.Result; const bun = @import("bun"); -const JSC = bun.JSC; +const jsc = bun.jsc; const shell = bun.shell; const ExitCode = shell.ExitCode; diff --git a/src/shell/builtin/cd.zig b/src/shell/builtin/cd.zig index 980ef19983..c4cbe1a31b 100644 --- a/src/shell/builtin/cd.zig +++ b/src/shell/builtin/cd.zig @@ -91,7 +91,7 @@ fn handleChangeCwdErr(this: *Cd, err: Syscall.Error, new_cwd_: []const u8) Yield } } -pub fn onIOWriterChunk(this: *Cd, _: usize, e: ?JSC.SystemError) Yield { +pub fn onIOWriterChunk(this: *Cd, _: usize, e: ?jsc.SystemError) Yield { if (comptime bun.Environment.allow_assert) { assert(this.state == .waiting_write_stderr); } @@ -125,9 +125,9 @@ const Interpreter = interpreter.Interpreter; const Builtin = Interpreter.Builtin; const bun = @import("bun"); -const JSC = bun.JSC; const Syscall = bun.sys; const assert = bun.assert; +const jsc = bun.jsc; const shell = bun.shell; const Yield = bun.shell.Yield; diff --git a/src/shell/builtin/cp.zig b/src/shell/builtin/cp.zig index 7da591875c..8e3e78a9c6 100644 --- a/src/shell/builtin/cp.zig +++ b/src/shell/builtin/cp.zig @@ -190,7 +190,7 @@ pub fn writeFailingError(this: *Cp, buf: []const u8, exit_code: ExitCode) Yield return this.bltn().done(exit_code); } -pub fn onIOWriterChunk(this: *Cp, _: usize, e: ?JSC.SystemError) Yield { +pub fn onIOWriterChunk(this: *Cp, _: usize, e: ?jsc.SystemError) Yield { if (e) |err| err.deref(); if (this.state == .waiting_write_err) { return this.bltn().done(1); @@ -308,9 +308,9 @@ pub const ShellCpTask = struct { verbose_output_lock: bun.Mutex = .{}, verbose_output: ArrayList(u8) = ArrayList(u8).init(bun.default_allocator), - task: JSC.WorkPoolTask = .{ .callback = &runFromThreadPool }, - event_loop: JSC.EventLoopHandle, - concurrent_task: JSC.EventLoopTask, + task: jsc.WorkPoolTask = .{ .callback = &runFromThreadPool }, + event_loop: jsc.EventLoopHandle, + concurrent_task: jsc.EventLoopTask, err: ?bun.shell.ShellErr = null, const debug = bun.Output.scoped(.ShellCpTask, false); @@ -337,7 +337,7 @@ pub const ShellCpTask = struct { pub fn create( cp: *Cp, - evtloop: JSC.EventLoopHandle, + evtloop: jsc.EventLoopHandle, opts: Opts, operands: usize, src: [:0]const u8, @@ -352,7 +352,7 @@ pub const ShellCpTask = struct { .tgt = tgt, .cwd_path = cwd_path, .event_loop = evtloop, - .concurrent_task = JSC.EventLoopTask.fromEventLoop(evtloop), + .concurrent_task = jsc.EventLoopTask.fromEventLoop(evtloop), }); } @@ -362,8 +362,8 @@ pub const ShellCpTask = struct { return out; } - pub fn ensureDest(nodefs: *JSC.Node.fs.NodeFS, dest: bun.OSPathSliceZ) Maybe(void) { - return switch (nodefs.mkdirRecursiveOSPath(dest, JSC.Node.Arguments.Mkdir.DefaultMode, false)) { + pub fn ensureDest(nodefs: *jsc.Node.fs.NodeFS, dest: bun.OSPathSliceZ) Maybe(void) { + return switch (nodefs.mkdirRecursiveOSPath(dest, jsc.Node.Arguments.Mkdir.DefaultMode, false)) { .err => |err| Maybe(void){ .err = err }, .result => Maybe(void).success, }; @@ -530,9 +530,9 @@ pub const ShellCpTask = struct { this.src_absolute = bun.default_allocator.dupeZ(u8, src[0..src.len]) catch bun.outOfMemory(); this.tgt_absolute = bun.default_allocator.dupeZ(u8, tgt[0..tgt.len]) catch bun.outOfMemory(); - const args = JSC.Node.fs.Arguments.Cp{ - .src = JSC.Node.PathLike{ .string = bun.PathString.init(this.src_absolute.?) }, - .dest = JSC.Node.PathLike{ .string = bun.PathString.init(this.tgt_absolute.?) }, + const args = jsc.Node.fs.Arguments.Cp{ + .src = jsc.Node.PathLike{ .string = bun.PathString.init(this.src_absolute.?) }, + .dest = jsc.Node.PathLike{ .string = bun.PathString.init(this.tgt_absolute.?) }, .flags = .{ .mode = @enumFromInt(0), .recursive = this.opts.recursive, @@ -544,7 +544,7 @@ pub const ShellCpTask = struct { debug("Scheduling {s} -> {s}", .{ this.src_absolute.?, this.tgt_absolute.? }); if (this.event_loop == .js) { - const vm: *JSC.VirtualMachine = this.event_loop.js.getVmImpl(); + const vm: *jsc.VirtualMachine = this.event_loop.js.getVmImpl(); debug("Yoops", .{}); _ = bun.api.node.fs.ShellAsyncCpTask.createWithShellTask( vm.global, @@ -747,9 +747,9 @@ const bun = @import("bun"); const ResolvePath = bun.path; const assert = bun.assert; -const JSC = bun.JSC; -const WorkPool = JSC.WorkPool; -const WorkPoolTask = JSC.WorkPoolTask; +const jsc = bun.jsc; +const WorkPool = jsc.WorkPool; +const WorkPoolTask = jsc.WorkPoolTask; const shell = bun.shell; const ExitCode = shell.ExitCode; diff --git a/src/shell/builtin/dirname.zig b/src/shell/builtin/dirname.zig index d86305fa01..647c315fbc 100644 --- a/src/shell/builtin/dirname.zig +++ b/src/shell/builtin/dirname.zig @@ -44,7 +44,7 @@ fn print(this: *@This(), msg: []const u8) Maybe(void) { return Maybe(void).success; } -pub fn onIOWriterChunk(this: *@This(), _: usize, maybe_e: ?JSC.SystemError) Yield { +pub fn onIOWriterChunk(this: *@This(), _: usize, maybe_e: ?jsc.SystemError) Yield { if (maybe_e) |e| { defer e.deref(); this.state = .err; @@ -71,6 +71,6 @@ const Interpreter = interpreter.Interpreter; const Builtin = Interpreter.Builtin; const bun = @import("bun"); -const JSC = bun.JSC; +const jsc = bun.jsc; const Maybe = bun.sys.Maybe; const Yield = bun.shell.Yield; diff --git a/src/shell/builtin/echo.zig b/src/shell/builtin/echo.zig index e406713acb..e2d7ac6af3 100644 --- a/src/shell/builtin/echo.zig +++ b/src/shell/builtin/echo.zig @@ -43,7 +43,7 @@ pub fn start(this: *Echo) Yield { return this.bltn().done(0); } -pub fn onIOWriterChunk(this: *Echo, _: usize, e: ?JSC.SystemError) Yield { +pub fn onIOWriterChunk(this: *Echo, _: usize, e: ?jsc.SystemError) Yield { if (comptime bun.Environment.allow_assert) { assert(this.state == .waiting or this.state == .waiting_write_err); } @@ -77,8 +77,8 @@ const Interpreter = interpreter.Interpreter; const Builtin = Interpreter.Builtin; const bun = @import("bun"); -const JSC = bun.JSC; const assert = bun.assert; +const jsc = bun.jsc; const ExitCode = bun.shell.ExitCode; const Yield = bun.shell.Yield; diff --git a/src/shell/builtin/exit.zig b/src/shell/builtin/exit.zig index 903cfca3d2..0f2aefcd68 100644 --- a/src/shell/builtin/exit.zig +++ b/src/shell/builtin/exit.zig @@ -51,7 +51,7 @@ pub fn next(this: *Exit) Yield { } } -pub fn onIOWriterChunk(this: *Exit, _: usize, maybe_e: ?JSC.SystemError) Yield { +pub fn onIOWriterChunk(this: *Exit, _: usize, maybe_e: ?jsc.SystemError) Yield { if (comptime bun.Environment.allow_assert) { assert(this.state == .waiting_io); } @@ -82,8 +82,8 @@ const Interpreter = interpreter.Interpreter; const Builtin = Interpreter.Builtin; const bun = @import("bun"); -const JSC = bun.JSC; const assert = bun.assert; +const jsc = bun.jsc; const shell = bun.shell; const ExitCode = shell.ExitCode; diff --git a/src/shell/builtin/export.zig b/src/shell/builtin/export.zig index 859c5d5fc5..30f64728ca 100644 --- a/src/shell/builtin/export.zig +++ b/src/shell/builtin/export.zig @@ -23,7 +23,7 @@ pub fn writeOutput(this: *Export, comptime io_kind: @Type(.enum_literal), compti return this.bltn().done(0); } -pub fn onIOWriterChunk(this: *Export, _: usize, e: ?JSC.SystemError) Yield { +pub fn onIOWriterChunk(this: *Export, _: usize, e: ?jsc.SystemError) Yield { if (comptime bun.Environment.allow_assert) { assert(this.printing); } @@ -136,8 +136,8 @@ const Builtin = Interpreter.Builtin; const BuiltinIO = Interpreter.Builtin.BuiltinIO; const bun = @import("bun"); -const JSC = bun.JSC; const assert = bun.assert; +const jsc = bun.jsc; const shell = bun.shell; const ExitCode = shell.ExitCode; diff --git a/src/shell/builtin/false.zig b/src/shell/builtin/false.zig index 74671e6384..2c9cfc2a67 100644 --- a/src/shell/builtin/false.zig +++ b/src/shell/builtin/false.zig @@ -6,7 +6,7 @@ pub fn deinit(this: *@This()) void { _ = this; } -pub fn onIOWriterChunk(_: *@This(), _: usize, _: ?JSC.SystemError) Yield { +pub fn onIOWriterChunk(_: *@This(), _: usize, _: ?jsc.SystemError) Yield { return .done; } @@ -23,5 +23,5 @@ const Interpreter = interpreter.Interpreter; const Builtin = Interpreter.Builtin; const bun = @import("bun"); -const JSC = bun.JSC; +const jsc = bun.jsc; const Yield = bun.shell.Yield; diff --git a/src/shell/builtin/ls.zig b/src/shell/builtin/ls.zig index eaabda6c09..db29e13941 100644 --- a/src/shell/builtin/ls.zig +++ b/src/shell/builtin/ls.zig @@ -118,7 +118,7 @@ pub fn deinit(this: *Ls) void { this.alloc_scope.endScope(); } -pub fn onIOWriterChunk(this: *Ls, _: usize, e: ?JSC.SystemError) Yield { +pub fn onIOWriterChunk(this: *Ls, _: usize, e: ?jsc.SystemError) Yield { if (e) |err| err.deref(); if (this.state == .waiting_write_err) { return this.bltn().done(1); @@ -226,14 +226,14 @@ pub const ShellLsTask = struct { err: ?Syscall.Error = null, result_kind: enum { file, dir, idk } = .idk, - event_loop: JSC.EventLoopHandle, - concurrent_task: JSC.EventLoopTask, - task: JSC.WorkPoolTask = .{ + event_loop: jsc.EventLoopHandle, + concurrent_task: jsc.EventLoopTask, + task: jsc.WorkPoolTask = .{ .callback = workPoolCallback, }, pub fn schedule(this: *@This()) void { - JSC.WorkPool.schedule(&this.task); + jsc.WorkPool.schedule(&this.task); } pub fn create( @@ -243,7 +243,7 @@ pub const ShellLsTask = struct { cwd: bun.FileDescriptor, path: [:0]const u8, owned_string: bool, - event_loop: JSC.EventLoopHandle, + event_loop: jsc.EventLoopHandle, ) *@This() { // We're going to free `task.path` so ensure it is allocated in this // scope and NOT a string literal or other string we don't own. @@ -254,7 +254,7 @@ pub const ShellLsTask = struct { .ls = ls, .opts = opts, .cwd = cwd, - .concurrent_task = JSC.EventLoopTask.fromEventLoop(event_loop), + .concurrent_task = jsc.EventLoopTask.fromEventLoop(event_loop), .event_loop = event_loop, .task_count = task_count, .path = path, @@ -390,7 +390,7 @@ pub const ShellLsTask = struct { return err.withPath(this.ls.alloc_scope.allocator().dupeZ(u8, path[0..path.len]) catch bun.outOfMemory()); } - pub fn workPoolCallback(task: *JSC.WorkPoolTask) void { + pub fn workPoolCallback(task: *jsc.WorkPoolTask) void { var this: *@This() = @fieldParentPtr("task", task); this.run(); this.doneLogic(); @@ -865,8 +865,8 @@ const Result = Interpreter.Builtin.Result; const bun = @import("bun"); const DirIterator = bun.DirIterator; -const JSC = bun.JSC; const Syscall = bun.sys; +const jsc = bun.jsc; const shell = bun.shell; const ExitCode = shell.ExitCode; diff --git a/src/shell/builtin/mkdir.zig b/src/shell/builtin/mkdir.zig index 163b91a597..91f8ae1f10 100644 --- a/src/shell/builtin/mkdir.zig +++ b/src/shell/builtin/mkdir.zig @@ -10,13 +10,13 @@ state: union(enum) { output_waiting: u16 = 0, output_done: u16 = 0, args: []const [*:0]const u8, - err: ?JSC.SystemError = null, + err: ?jsc.SystemError = null, }, waiting_write_err, done, } = .idle, -pub fn onIOWriterChunk(this: *Mkdir, _: usize, e: ?JSC.SystemError) Yield { +pub fn onIOWriterChunk(this: *Mkdir, _: usize, e: ?jsc.SystemError) Yield { if (e) |err| err.deref(); switch (this.state) { @@ -173,10 +173,10 @@ pub const ShellMkdirTask = struct { cwd_path: [:0]const u8, created_directories: ArrayList(u8), - err: ?JSC.SystemError = null, - task: JSC.WorkPoolTask = .{ .callback = &runFromThreadPool }, - event_loop: JSC.EventLoopHandle, - concurrent_task: JSC.EventLoopTask, + err: ?jsc.SystemError = null, + task: jsc.WorkPoolTask = .{ .callback = &runFromThreadPool }, + event_loop: jsc.EventLoopHandle, + concurrent_task: jsc.EventLoopTask, pub fn deinit(this: *ShellMkdirTask) void { this.created_directories.deinit(); @@ -210,7 +210,7 @@ pub const ShellMkdirTask = struct { .filepath = filepath, .created_directories = ArrayList(u8).init(bun.default_allocator), .event_loop = evtloop, - .concurrent_task = JSC.EventLoopTask.fromEventLoop(evtloop), + .concurrent_task = jsc.EventLoopTask.fromEventLoop(evtloop), }; return task; } @@ -229,7 +229,7 @@ pub const ShellMkdirTask = struct { this.runFromMainThread(); } - fn runFromThreadPool(task: *JSC.WorkPoolTask) void { + fn runFromThreadPool(task: *jsc.WorkPoolTask) void { var this: *ShellMkdirTask = @fieldParentPtr("task", task); debug("{} runFromThreadPool", .{this}); @@ -244,11 +244,11 @@ pub const ShellMkdirTask = struct { break :brk ResolvePath.joinZ(parts, .auto); }; - var node_fs = JSC.Node.fs.NodeFS{}; + var node_fs = jsc.Node.fs.NodeFS{}; // Recursive if (this.opts.parents) { - const args = JSC.Node.fs.Arguments.Mkdir{ - .path = JSC.Node.PathLike{ .string = bun.PathString.init(filepath) }, + const args = jsc.Node.fs.Arguments.Mkdir{ + .path = jsc.Node.PathLike{ .string = bun.PathString.init(filepath) }, .recursive = true, .always_return_none = true, }; @@ -263,8 +263,8 @@ pub const ShellMkdirTask = struct { }, } } else { - const args = JSC.Node.fs.Arguments.Mkdir{ - .path = JSC.Node.PathLike{ .string = bun.PathString.init(filepath) }, + const args = jsc.Node.fs.Arguments.Mkdir{ + .path = jsc.Node.PathLike{ .string = bun.PathString.init(filepath) }, .recursive = false, .always_return_none = true, }; @@ -390,8 +390,8 @@ const Result = Interpreter.Builtin.Result; const bun = @import("bun"); const ResolvePath = bun.path; -const JSC = bun.JSC; -const WorkPool = bun.JSC.WorkPool; +const jsc = bun.jsc; +const WorkPool = bun.jsc.WorkPool; const shell = bun.shell; const ExitCode = shell.ExitCode; diff --git a/src/shell/builtin/mv.zig b/src/shell/builtin/mv.zig index b4cff3bc06..b25ed04971 100644 --- a/src/shell/builtin/mv.zig +++ b/src/shell/builtin/mv.zig @@ -78,7 +78,7 @@ pub const ShellMvBatchedTask = struct { err: ?Syscall.Error = null, task: ShellTask(@This(), runFromThreadPool, runFromMainThread, debug), - event_loop: JSC.EventLoopHandle, + event_loop: jsc.EventLoopHandle, pub fn runFromThreadPool(this: *@This()) void { // Moving multiple entries into a directory @@ -203,7 +203,7 @@ pub fn next(this: *Mv) Yield { .target = this.args.target, .task = .{ .event_loop = this.bltn().parentCmd().base.eventLoop(), - .concurrent_task = JSC.EventLoopTask.fromEventLoop(this.bltn().parentCmd().base.eventLoop()), + .concurrent_task = jsc.EventLoopTask.fromEventLoop(this.bltn().parentCmd().base.eventLoop()), }, }, .state = .running, @@ -276,7 +276,7 @@ pub fn next(this: *Mv) Yield { .error_signal = undefined, .task = .{ .event_loop = this.bltn().parentCmd().base.eventLoop(), - .concurrent_task = JSC.EventLoopTask.fromEventLoop(this.bltn().parentCmd().base.eventLoop()), + .concurrent_task = jsc.EventLoopTask.fromEventLoop(this.bltn().parentCmd().base.eventLoop()), }, .event_loop = this.bltn().parentCmd().base.eventLoop(), }; @@ -313,7 +313,7 @@ pub fn next(this: *Mv) Yield { } } -pub fn onIOWriterChunk(this: *Mv, _: usize, e: ?JSC.SystemError) Yield { +pub fn onIOWriterChunk(this: *Mv, _: usize, e: ?jsc.SystemError) Yield { defer if (e) |err| err.deref(); switch (this.state) { .waiting_write_err => { @@ -499,9 +499,9 @@ const Builtin = Interpreter.Builtin; const Result = Interpreter.Builtin.Result; const bun = @import("bun"); -const JSC = bun.JSC; const ResolvePath = bun.path; const assert = bun.assert; +const jsc = bun.jsc; const shell = bun.shell; const ExitCode = shell.ExitCode; diff --git a/src/shell/builtin/pwd.zig b/src/shell/builtin/pwd.zig index e264da30c2..d4319a0a85 100644 --- a/src/shell/builtin/pwd.zig +++ b/src/shell/builtin/pwd.zig @@ -51,7 +51,7 @@ pub fn next(this: *Pwd) Yield { } } -pub fn onIOWriterChunk(this: *Pwd, _: usize, e: ?JSC.SystemError) Yield { +pub fn onIOWriterChunk(this: *Pwd, _: usize, e: ?jsc.SystemError) Yield { if (comptime bun.Environment.allow_assert) { assert(this.state == .waiting_io); } @@ -87,8 +87,8 @@ const Interpreter = interpreter.Interpreter; const Builtin = Interpreter.Builtin; const bun = @import("bun"); -const JSC = bun.JSC; const assert = bun.assert; +const jsc = bun.jsc; const shell = bun.shell; const Yield = shell.Yield; diff --git a/src/shell/builtin/rm.zig b/src/shell/builtin/rm.zig index 7a5938f6fb..d1d9358d5e 100644 --- a/src/shell/builtin/rm.zig +++ b/src/shell/builtin/rm.zig @@ -295,7 +295,7 @@ pub noinline fn next(this: *Rm) Yield { } } -pub fn onIOWriterChunk(this: *Rm, _: usize, e: ?JSC.SystemError) Yield { +pub fn onIOWriterChunk(this: *Rm, _: usize, e: ?jsc.SystemError) Yield { log("Rm(0x{x}).onIOWriterChunk()", .{@intFromPtr(this)}); if (comptime bun.Environment.allow_assert) { assert((this.state == .parse_opts and this.state.parse_opts.state == .wait_write_err) or @@ -466,9 +466,9 @@ pub const ShellRmTask = struct { err_mutex: bun.Mutex = .{}, err: ?Syscall.Error = null, - event_loop: JSC.EventLoopHandle, - concurrent_task: JSC.EventLoopTask, - task: JSC.WorkPoolTask = .{ + event_loop: jsc.EventLoopHandle, + concurrent_task: jsc.EventLoopTask, + task: jsc.WorkPoolTask = .{ .callback = workPoolCallback, }, join_style: JoinStyle, @@ -506,9 +506,9 @@ pub const ShellRmTask = struct { need_to_wait: std.atomic.Value(bool) = std.atomic.Value(bool).init(false), deleting_after_waiting_for_children: std.atomic.Value(bool) = std.atomic.Value(bool).init(false), kind_hint: EntryKindHint, - task: JSC.WorkPoolTask = .{ .callback = runFromThreadPool }, + task: jsc.WorkPoolTask = .{ .callback = runFromThreadPool }, deleted_entries: std.ArrayList(u8), - concurrent_task: JSC.EventLoopTask, + concurrent_task: jsc.EventLoopTask, const EntryKindHint = enum { idk, dir, file }; @@ -528,7 +528,7 @@ pub const ShellRmTask = struct { this.runFromMainThread(); } - pub fn runFromThreadPool(task: *JSC.WorkPoolTask) void { + pub fn runFromThreadPool(task: *jsc.WorkPoolTask) void { var this: *DirTask = @fieldParentPtr("task", task); this.runFromThreadPoolImpl(); } @@ -693,10 +693,10 @@ pub const ShellRmTask = struct { .subtask_count = std.atomic.Value(usize).init(1), .kind_hint = .idk, .deleted_entries = std.ArrayList(u8).init(bun.default_allocator), - .concurrent_task = JSC.EventLoopTask.fromEventLoop(rm.bltn().eventLoop()), + .concurrent_task = jsc.EventLoopTask.fromEventLoop(rm.bltn().eventLoop()), }, .event_loop = rm.bltn().parentCmd().base.eventLoop(), - .concurrent_task = JSC.EventLoopTask.fromEventLoop(rm.bltn().eventLoop()), + .concurrent_task = jsc.EventLoopTask.fromEventLoop(rm.bltn().eventLoop()), .error_signal = error_signal, .root_is_absolute = is_absolute, .join_style = JoinStyle.fromPath(root_path), @@ -705,7 +705,7 @@ pub const ShellRmTask = struct { } pub fn schedule(this: *@This()) void { - JSC.WorkPool.schedule(&this.task); + jsc.WorkPool.schedule(&this.task); } pub fn enqueue(this: *ShellRmTask, parent_dir: *DirTask, path: [:0]const u8, is_absolute: bool, kind_hint: DirTask.EntryKindHint) void { @@ -738,7 +738,7 @@ pub const ShellRmTask = struct { .subtask_count = std.atomic.Value(usize).init(1), .kind_hint = kind_hint, .deleted_entries = std.ArrayList(u8).init(bun.default_allocator), - .concurrent_task = JSC.EventLoopTask.fromEventLoop(this.event_loop), + .concurrent_task = jsc.EventLoopTask.fromEventLoop(this.event_loop), }; const count = parent_task.subtask_count.fetchAdd(1, .monotonic); @@ -746,7 +746,7 @@ pub const ShellRmTask = struct { assert(count > 0); } - JSC.WorkPool.schedule(&subtask.task); + jsc.WorkPool.schedule(&subtask.task); } pub fn getcwd(this: *ShellRmTask) bun.FileDescriptor { @@ -1158,7 +1158,7 @@ pub const ShellRmTask = struct { return out; } - pub fn workPoolCallback(task: *JSC.WorkPoolTask) void { + pub fn workPoolCallback(task: *jsc.WorkPoolTask) void { var this: *ShellRmTask = @alignCast(@fieldParentPtr("task", task)); this.root_task.runFromThreadPoolImpl(); } @@ -1210,9 +1210,9 @@ const Builtin = Interpreter.Builtin; const bun = @import("bun"); const DirIterator = bun.DirIterator; -const JSC = bun.JSC; const ResolvePath = bun.path; const assert = bun.assert; +const jsc = bun.jsc; const shell = bun.shell; const ExitCode = shell.ExitCode; diff --git a/src/shell/builtin/seq.zig b/src/shell/builtin/seq.zig index 3ec201065c..a41a17b675 100644 --- a/src/shell/builtin/seq.zig +++ b/src/shell/builtin/seq.zig @@ -109,7 +109,7 @@ fn print(this: *@This(), msg: []const u8) void { return; } -pub fn onIOWriterChunk(this: *@This(), _: usize, maybe_e: ?JSC.SystemError) Yield { +pub fn onIOWriterChunk(this: *@This(), _: usize, maybe_e: ?jsc.SystemError) Yield { if (maybe_e) |e| { defer e.deref(); this.state = .err; @@ -141,5 +141,5 @@ const Interpreter = interpreter.Interpreter; const Builtin = Interpreter.Builtin; const bun = @import("bun"); -const JSC = bun.JSC; +const jsc = bun.jsc; const Yield = bun.shell.Yield; diff --git a/src/shell/builtin/touch.zig b/src/shell/builtin/touch.zig index b0ecb6bda2..50ac67a410 100644 --- a/src/shell/builtin/touch.zig +++ b/src/shell/builtin/touch.zig @@ -11,7 +11,7 @@ state: union(enum) { output_waiting: usize = 0, started_output_queue: bool = false, args: []const [*:0]const u8, - err: ?JSC.SystemError = null, + err: ?jsc.SystemError = null, }, waiting_write_err, done, @@ -81,7 +81,7 @@ pub fn next(this: *Touch) Yield { } } -pub fn onIOWriterChunk(this: *Touch, _: usize, e: ?JSC.SystemError) Yield { +pub fn onIOWriterChunk(this: *Touch, _: usize, e: ?jsc.SystemError) Yield { if (this.state == .waiting_write_err) { return this.bltn().done(1); } @@ -173,10 +173,10 @@ pub const ShellTouchTask = struct { filepath: [:0]const u8, cwd_path: [:0]const u8, - err: ?JSC.SystemError = null, - task: JSC.WorkPoolTask = .{ .callback = &runFromThreadPool }, - event_loop: JSC.EventLoopHandle, - concurrent_task: JSC.EventLoopTask, + err: ?jsc.SystemError = null, + task: jsc.WorkPoolTask = .{ .callback = &runFromThreadPool }, + event_loop: jsc.EventLoopHandle, + concurrent_task: jsc.EventLoopTask, pub fn format(this: *const ShellTouchTask, comptime fmt: []const u8, opts: std.fmt.FormatOptions, writer: anytype) !void { _ = fmt; // autofix @@ -199,7 +199,7 @@ pub const ShellTouchTask = struct { .cwd_path = cwd_path, .filepath = filepath, .event_loop = touch.bltn().eventLoop(), - .concurrent_task = JSC.EventLoopTask.fromEventLoop(touch.bltn().eventLoop()), + .concurrent_task = jsc.EventLoopTask.fromEventLoop(touch.bltn().eventLoop()), }; return task; } @@ -218,7 +218,7 @@ pub const ShellTouchTask = struct { this.runFromMainThread(); } - fn runFromThreadPool(task: *JSC.WorkPoolTask) void { + fn runFromThreadPool(task: *jsc.WorkPoolTask) void { var this: *ShellTouchTask = @fieldParentPtr("task", task); debug("{} runFromThreadPool", .{this}); @@ -232,14 +232,14 @@ pub const ShellTouchTask = struct { break :brk ResolvePath.joinZ(parts, .auto); }; - var node_fs = JSC.Node.fs.NodeFS{}; + var node_fs = jsc.Node.fs.NodeFS{}; const milliseconds: f64 = @floatFromInt(std.time.milliTimestamp()); - const atime: JSC.Node.TimeLike = if (bun.Environment.isWindows) milliseconds / 1000.0 else JSC.Node.TimeLike{ + const atime: jsc.Node.TimeLike = if (bun.Environment.isWindows) milliseconds / 1000.0 else jsc.Node.TimeLike{ .sec = @intFromFloat(@divFloor(milliseconds, std.time.ms_per_s)), .nsec = @intFromFloat(@mod(milliseconds, std.time.ms_per_s) * std.time.ns_per_ms), }; const mtime = atime; - const args = JSC.Node.fs.Arguments.Utimes{ + const args = jsc.Node.fs.Arguments.Utimes{ .atime = atime, .mtime = mtime, .path = .{ .string = bun.PathString.init(filepath) }, @@ -408,8 +408,8 @@ const bun = @import("bun"); const ResolvePath = bun.path; const Syscall = bun.sys; -const JSC = bun.JSC; -const WorkPool = bun.JSC.WorkPool; +const jsc = bun.jsc; +const WorkPool = bun.jsc.WorkPool; const shell = bun.shell; const ExitCode = shell.ExitCode; diff --git a/src/shell/builtin/true.zig b/src/shell/builtin/true.zig index 704a1375e1..702bc25b07 100644 --- a/src/shell/builtin/true.zig +++ b/src/shell/builtin/true.zig @@ -6,7 +6,7 @@ pub fn deinit(this: *@This()) void { _ = this; } -pub fn onIOWriterChunk(_: *@This(), _: usize, _: ?JSC.SystemError) Yield { +pub fn onIOWriterChunk(_: *@This(), _: usize, _: ?jsc.SystemError) Yield { return .done; } @@ -23,5 +23,5 @@ const Interpreter = interpreter.Interpreter; const Builtin = Interpreter.Builtin; const bun = @import("bun"); -const JSC = bun.JSC; +const jsc = bun.jsc; const Yield = bun.shell.Yield; diff --git a/src/shell/builtin/which.zig b/src/shell/builtin/which.zig index 05e46e7ea0..9e812e8aeb 100644 --- a/src/shell/builtin/which.zig +++ b/src/shell/builtin/which.zig @@ -17,7 +17,7 @@ state: union(enum) { }, }, done, - err: JSC.SystemError, + err: jsc.SystemError, } = .idle, pub fn start(this: *Which) Yield { @@ -106,7 +106,7 @@ fn argComplete(this: *Which) Yield { return this.next(); } -pub fn onIOWriterChunk(this: *Which, _: usize, e: ?JSC.SystemError) Yield { +pub fn onIOWriterChunk(this: *Which, _: usize, e: ?jsc.SystemError) Yield { if (comptime bun.Environment.allow_assert) { assert(this.state == .one_arg or (this.state == .multi_args and this.state.multi_args.state == .waiting_write)); @@ -147,8 +147,8 @@ const Interpreter = interpreter.Interpreter; const Builtin = Interpreter.Builtin; const bun = @import("bun"); -const JSC = bun.JSC; const assert = bun.assert; +const jsc = bun.jsc; const which = bun.which; const shell = bun.shell; diff --git a/src/shell/builtin/yes.zig b/src/shell/builtin/yes.zig index 4361ce1827..badd090102 100644 --- a/src/shell/builtin/yes.zig +++ b/src/shell/builtin/yes.zig @@ -68,7 +68,7 @@ pub fn start(this: *@This()) Yield { const evtloop = this.bltn().eventLoop(); this.task = .{ .evtloop = evtloop, - .concurrent_task = JSC.EventLoopTask.fromEventLoop(evtloop), + .concurrent_task = jsc.EventLoopTask.fromEventLoop(evtloop), }; this.state = .waiting_io; return this.bltn().stdout.enqueue(this, this.buffer[0..this.buffer_used], safeguard); @@ -76,7 +76,7 @@ pub fn start(this: *@This()) Yield { this.task = .{ .evtloop = this.bltn().eventLoop(), - .concurrent_task = JSC.EventLoopTask.fromEventLoop(this.task.evtloop), + .concurrent_task = jsc.EventLoopTask.fromEventLoop(this.task.evtloop), }; return this.writeNoIO(); } @@ -114,7 +114,7 @@ pub fn writeFailingError(this: *Yes, buf: []const u8, exit_code: shell.ExitCode) return this.bltn().done(exit_code); } -pub fn onIOWriterChunk(this: *@This(), _: usize, maybe_e: ?JSC.SystemError) Yield { +pub fn onIOWriterChunk(this: *@This(), _: usize, maybe_e: ?jsc.SystemError) Yield { if (maybe_e) |e| { defer e.deref(); this.state = .err; @@ -141,8 +141,8 @@ pub fn deinit(this: *@This()) void { /// require IO. After writing a bit, we suspend execution to this task so we /// don't just block the main thread forever. pub const YesTask = struct { - evtloop: JSC.EventLoopHandle, - concurrent_task: JSC.EventLoopTask, + evtloop: jsc.EventLoopHandle, + concurrent_task: jsc.EventLoopTask, pub fn enqueue(this: *@This()) void { if (this.evtloop == .js) { @@ -173,7 +173,7 @@ const Interpreter = interpreter.Interpreter; const Builtin = Interpreter.Builtin; const bun = @import("bun"); -const JSC = bun.JSC; +const jsc = bun.jsc; const shell = bun.shell; const IO = shell.IO; diff --git a/src/shell/interpreter.zig b/src/shell/interpreter.zig index f8883ca07a..77396cdba6 100644 --- a/src/shell/interpreter.zig +++ b/src/shell/interpreter.zig @@ -61,8 +61,8 @@ const string = []const u8; pub const Arena = std.heap.ArenaAllocator; pub const Braces = @import("./braces.zig"); pub const Syscall = bun.sys; -pub const WorkPoolTask = JSC.WorkPoolTask; -pub const WorkPool = JSC.WorkPool; +pub const WorkPoolTask = jsc.WorkPoolTask; +pub const WorkPool = jsc.WorkPool; pub const Pipe = [2]bun.FileDescriptor; pub const SmolList = shell.SmolList; @@ -239,13 +239,13 @@ pub const AssignCtx = Interpreter.Assigns.AssignCtx; /// This interpreter works by basically turning the AST into a state machine so /// that execution can be suspended and resumed to support async. pub const Interpreter = struct { - pub const js = JSC.Codegen.JSShellInterpreter; + pub const js = jsc.Codegen.JSShellInterpreter; pub const toJS = js.toJS; pub const fromJS = js.fromJS; pub const fromJSDirect = js.fromJSDirect; - command_ctx: bun.CLI.Command.Context, - event_loop: JSC.EventLoopHandle, + command_ctx: bun.cli.Command.Context, + event_loop: jsc.EventLoopHandle, /// This is the allocator used to allocate interpreter state allocator: Allocator, @@ -263,10 +263,10 @@ pub const Interpreter = struct { // Necessary for builtin commands. keep_alive: bun.Async.KeepAlive = .{}, - vm_args_utf8: std.ArrayList(JSC.ZigString.Slice), + vm_args_utf8: std.ArrayList(jsc.ZigString.Slice), async_commands_executing: u32 = 0, - globalThis: *JSC.JSGlobalObject, + globalThis: *jsc.JSGlobalObject, flags: packed struct(u8) { done: bool = false, @@ -637,15 +637,15 @@ pub const Interpreter = struct { fn toJS(this: ShellErrorCtx, globalThis: *JSGlobalObject) JSValue { return switch (this) { .syscall => |err| err.toJS(globalThis), - .other => |err| bun.JSC.ZigString.fromBytes(@errorName(err)).toJS(globalThis), + .other => |err| bun.jsc.ZigString.fromBytes(@errorName(err)).toJS(globalThis), }; } }; - pub fn createShellInterpreter(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { + pub fn createShellInterpreter(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { const allocator = bun.default_allocator; const arguments_ = callframe.arguments_old(3); - var arguments = JSC.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), arguments_.slice()); + var arguments = jsc.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), arguments_.slice()); const resolve = arguments.nextEat() orelse return globalThis.throw("shell: expected 3 arguments, got 0", .{}); @@ -672,7 +672,7 @@ pub const Interpreter = struct { &export_env, ); - const cwd_string: ?bun.JSC.ZigString.Slice = if (cwd) |c| brk: { + const cwd_string: ?bun.jsc.ZigString.Slice = if (cwd) |c| brk: { break :brk c.toUTF8(bun.default_allocator); } else null; defer if (cwd_string) |c| c.deinit(); @@ -707,13 +707,13 @@ pub const Interpreter = struct { interpreter.flags.quiet = quiet; interpreter.globalThis = globalThis; - const js_value = JSC.Codegen.JSShellInterpreter.toJS(interpreter, globalThis); + const js_value = jsc.Codegen.JSShellInterpreter.toJS(interpreter, globalThis); interpreter.this_jsvalue = js_value; - JSC.Codegen.JSShellInterpreter.resolveSetCached(js_value, globalThis, resolve); - JSC.Codegen.JSShellInterpreter.rejectSetCached(js_value, globalThis, reject); + jsc.Codegen.JSShellInterpreter.resolveSetCached(js_value, globalThis, resolve); + jsc.Codegen.JSShellInterpreter.rejectSetCached(js_value, globalThis, reject); interpreter.keep_alive.ref(globalThis.bunVM()); - bun.Analytics.Features.shell += 1; + bun.analytics.Features.shell += 1; return js_value; } @@ -764,8 +764,8 @@ pub const Interpreter = struct { /// If all initialization allocations succeed, the arena will be copied /// into the interpreter struct, so it is not a stale reference and safe to call `arena.deinit()` on error. pub fn init( - ctx: bun.CLI.Command.Context, - event_loop: JSC.EventLoopHandle, + ctx: bun.cli.Command.Context, + event_loop: jsc.EventLoopHandle, allocator: Allocator, shargs: *ShellArgs, jsobjs: []JSValue, @@ -862,7 +862,7 @@ pub const Interpreter = struct { .stderr = .pipe, }, - .vm_args_utf8 = std.ArrayList(JSC.ZigString.Slice).init(bun.default_allocator), + .vm_args_utf8 = std.ArrayList(jsc.ZigString.Slice).init(bun.default_allocator), .__alloc_scope = if (bun.Environment.enableAllocScopes) bun.AllocationScope.init(allocator) else {}, .globalThis = undefined, }; @@ -876,7 +876,7 @@ pub const Interpreter = struct { return .{ .result = interpreter }; } - pub fn initAndRunFromFile(ctx: bun.CLI.Command.Context, mini: *JSC.MiniEventLoop, path: []const u8) !bun.shell.ExitCode { + pub fn initAndRunFromFile(ctx: bun.cli.Command.Context, mini: *jsc.MiniEventLoop, path: []const u8) !bun.shell.ExitCode { var shargs = ShellArgs.init(); const src = src: { var file = try std.fs.cwd().openFile(path, .{}); @@ -956,8 +956,8 @@ pub const Interpreter = struct { return code; } - pub fn initAndRunFromSource(ctx: bun.CLI.Command.Context, mini: *JSC.MiniEventLoop, path_for_errors: []const u8, src: []const u8, cwd: ?[]const u8) !ExitCode { - bun.Analytics.Features.standalone_shell += 1; + pub fn initAndRunFromSource(ctx: bun.cli.Command.Context, mini: *jsc.MiniEventLoop, path_for_errors: []const u8, src: []const u8, cwd: ?[]const u8) !ExitCode { + bun.analytics.Features.standalone_shell += 1; var shargs = ShellArgs.init(); defer shargs.deinit(); @@ -1086,7 +1086,7 @@ pub const Interpreter = struct { return Maybe(void).success; } - pub fn runFromJS(this: *ThisInterpreter, globalThis: *JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { + pub fn runFromJS(this: *ThisInterpreter, globalThis: *JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { log("Interpreter(0x{x}) runFromJS", .{@intFromPtr(this)}); _ = callframe; // autofix @@ -1108,9 +1108,9 @@ pub const Interpreter = struct { fn ioToJSValue(globalThis: *JSGlobalObject, buf: *bun.ByteList) JSValue { const bytelist = buf.*; buf.* = .{}; - const buffer: JSC.Node.Buffer = .{ + const buffer: jsc.Node.Buffer = .{ .allocator = bun.default_allocator, - .buffer = JSC.ArrayBuffer.fromBytes(@constCast(bytelist.slice()), .Uint8Array), + .buffer = jsc.ArrayBuffer.fromBytes(@constCast(bytelist.slice()), .Uint8Array), }; return buffer.toNodeBuffer(globalThis); } @@ -1144,7 +1144,7 @@ pub const Interpreter = struct { this.exit_code = exit_code; const this_jsvalue = this.this_jsvalue; if (this_jsvalue != .zero) { - if (JSC.Codegen.JSShellInterpreter.resolveGetCached(this_jsvalue)) |resolve| { + if (jsc.Codegen.JSShellInterpreter.resolveGetCached(this_jsvalue)) |resolve| { const loop = this.event_loop.js; const globalThis = this.globalThis; this.this_jsvalue = .zero; @@ -1155,8 +1155,8 @@ pub const Interpreter = struct { this.getBufferedStdout(globalThis), this.getBufferedStderr(globalThis), }) catch |err| globalThis.reportActiveExceptionAsUnhandled(err); - JSC.Codegen.JSShellInterpreter.resolveSetCached(this_jsvalue, globalThis, .js_undefined); - JSC.Codegen.JSShellInterpreter.rejectSetCached(this_jsvalue, globalThis, .js_undefined); + jsc.Codegen.JSShellInterpreter.resolveSetCached(this_jsvalue, globalThis, .js_undefined); + jsc.Codegen.JSShellInterpreter.rejectSetCached(this_jsvalue, globalThis, .js_undefined); loop.exit(); } } @@ -1205,13 +1205,13 @@ pub const Interpreter = struct { this.allocator.destroy(this); } - pub fn setQuiet(this: *ThisInterpreter, _: *JSGlobalObject, _: *JSC.CallFrame) bun.JSError!JSC.JSValue { + pub fn setQuiet(this: *ThisInterpreter, _: *JSGlobalObject, _: *jsc.CallFrame) bun.JSError!jsc.JSValue { log("Interpreter(0x{x}) setQuiet()", .{@intFromPtr(this)}); this.flags.quiet = true; return .js_undefined; } - pub fn setCwd(this: *ThisInterpreter, globalThis: *JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { + pub fn setCwd(this: *ThisInterpreter, globalThis: *JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const value = callframe.argument(0); const str = try bun.String.fromJS(value, globalThis); @@ -1226,13 +1226,13 @@ pub const Interpreter = struct { return .js_undefined; } - pub fn setEnv(this: *ThisInterpreter, globalThis: *JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { + pub fn setEnv(this: *ThisInterpreter, globalThis: *JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const value1 = callframe.argument(0); if (!value1.isObject()) { return globalThis.throwInvalidArguments("env must be an object", .{}); } - var object_iter = JSC.JSPropertyIterator(.{ + var object_iter = jsc.JSPropertyIterator(.{ .skip_empty_name = false, .include_value = true, }).init(globalThis, value1); @@ -1262,22 +1262,22 @@ pub const Interpreter = struct { return .js_undefined; } - pub fn isRunning(this: *ThisInterpreter, _: *JSGlobalObject, _: *JSC.CallFrame) bun.JSError!JSC.JSValue { - return JSC.JSValue.jsBoolean(this.hasPendingActivity()); + pub fn isRunning(this: *ThisInterpreter, _: *JSGlobalObject, _: *jsc.CallFrame) bun.JSError!jsc.JSValue { + return jsc.JSValue.jsBoolean(this.hasPendingActivity()); } - pub fn getStarted(this: *ThisInterpreter, globalThis: *JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { + pub fn getStarted(this: *ThisInterpreter, globalThis: *JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { _ = globalThis; // autofix _ = callframe; // autofix - return JSC.JSValue.jsBoolean(this.started.load(.seq_cst)); + return jsc.JSValue.jsBoolean(this.started.load(.seq_cst)); } - pub fn getBufferedStdout(this: *ThisInterpreter, globalThis: *JSGlobalObject) JSC.JSValue { + pub fn getBufferedStdout(this: *ThisInterpreter, globalThis: *JSGlobalObject) jsc.JSValue { return ioToJSValue(globalThis, this.root_shell.buffered_stdout()); } - pub fn getBufferedStderr(this: *ThisInterpreter, globalThis: *JSGlobalObject) JSC.JSValue { + pub fn getBufferedStderr(this: *ThisInterpreter, globalThis: *JSGlobalObject) jsc.JSValue { return ioToJSValue(globalThis, this.root_shell.buffered_stderr()); } @@ -1566,10 +1566,10 @@ pub fn ShellTask( ) type { return struct { task: WorkPoolTask = .{ .callback = &runFromThreadPool }, - event_loop: JSC.EventLoopHandle, + event_loop: jsc.EventLoopHandle, // This is a poll because we want it to enter the uSockets loop ref: bun.Async.KeepAlive = .{}, - concurrent_task: JSC.EventLoopTask, + concurrent_task: jsc.EventLoopTask, pub const InnerShellTask = @This(); @@ -1618,7 +1618,7 @@ inline fn errnocast(errno: anytype) u16 { /// 'js' event loop will always return JSError /// 'mini' event loop will always return noreturn and exit 1 -pub fn throwShellErr(e: *const bun.shell.ShellErr, event_loop: JSC.EventLoopHandle) bun.JSError!noreturn { +pub fn throwShellErr(e: *const bun.shell.ShellErr, event_loop: jsc.EventLoopHandle) bun.JSError!noreturn { return switch (event_loop) { .mini => e.throwMini(), .js => e.throwJS(event_loop.js.global), @@ -1820,7 +1820,7 @@ pub fn OutputTask( } } - pub fn onIOWriterChunk(this: *@This(), _: usize, err: ?JSC.SystemError) Yield { + pub fn onIOWriterChunk(this: *@This(), _: usize, err: ?jsc.SystemError) Yield { log("OutputTask({s}, 0x{x}) onIOWriterChunk", .{ @typeName(Parent), @intFromPtr(this) }); if (err) |e| { e.deref(); @@ -1967,10 +1967,10 @@ const TaggedPointerUnion = bun.TaggedPointerUnion; const assert = bun.assert; const which = bun.which; -const JSC = bun.JSC; -const JSGlobalObject = bun.JSC.JSGlobalObject; -const JSValue = bun.JSC.JSValue; -const Maybe = JSC.Maybe; +const jsc = bun.jsc; +const JSGlobalObject = bun.jsc.JSGlobalObject; +const JSValue = bun.jsc.JSValue; +const Maybe = jsc.Maybe; const shell = bun.shell; const Yield = shell.Yield; diff --git a/src/shell/shell.zig b/src/shell/shell.zig index ce2ee4d9ad..53fdf698d7 100644 --- a/src/shell/shell.zig +++ b/src/shell/shell.zig @@ -32,7 +32,7 @@ pub const WINDOWS_DEV_NULL: [:0]const u8 = "NUL"; /// The strings in this type are allocated with event loop ctx allocator pub const ShellErr = union(enum) { - sys: JSC.SystemError, + sys: jsc.SystemError, custom: []const u8, invalid_arguments: struct { val: []const u8 = "" }, todo: []const u8, @@ -41,7 +41,7 @@ pub const ShellErr = union(enum) { return .{ .sys = switch (@TypeOf(e)) { Syscall.Error => e.toShellSystemError(), - JSC.SystemError => e, + jsc.SystemError => e, else => @compileError("Invalid `e`: " ++ @typeName(e)), }, }; @@ -56,7 +56,7 @@ pub const ShellErr = union(enum) { }; } - pub fn throwJS(this: *const @This(), globalThis: *JSC.JSGlobalObject) bun.JSError { + pub fn throwJS(this: *const @This(), globalThis: *jsc.JSGlobalObject) bun.JSError { defer { // basically `transferToJS`. don't want to double deref the sys error switch (this.*) { @@ -76,7 +76,7 @@ pub const ShellErr = union(enum) { .custom => { const err_value = bun.String.cloneUTF8(this.custom).toErrorInstance(globalThis); return globalThis.throwValue(err_value); - // this.bunVM().allocator.free(JSC.ZigString.untagged(str._unsafe_ptr_do_not_use)[0..str.len]); + // this.bunVM().allocator.free(jsc.ZigString.untagged(str._unsafe_ptr_do_not_use)[0..str.len]); }, .invalid_arguments => { return globalThis.throwInvalidArguments("{s}", .{this.invalid_arguments.val}); @@ -157,9 +157,9 @@ pub const Pipe = [2]bun.FileDescriptor; const log = bun.Output.scoped(.SHELL, true); pub const GlobalJS = struct { - globalThis: *JSC.JSGlobalObject, + globalThis: *jsc.JSGlobalObject, - pub inline fn init(g: *JSC.JSGlobalObject) GlobalJS { + pub inline fn init(g: *jsc.JSGlobalObject) GlobalJS { return .{ .globalThis = g, }; @@ -169,7 +169,7 @@ pub const GlobalJS = struct { return this.globalThis.bunVM().allocator; } - pub inline fn eventLoopCtx(this: @This()) *JSC.VirtualMachine { + pub inline fn eventLoopCtx(this: @This()) *jsc.VirtualMachine { return this.globalThis.bunVM(); } @@ -212,7 +212,7 @@ pub const GlobalJS = struct { } pub inline fn enqueueTaskConcurrentWaitPid(this: @This(), task: anytype) void { - this.globalThis.bunVMConcurrently().enqueueTaskConcurrent(JSC.ConcurrentTask.create(JSC.Task.init(task))); + this.globalThis.bunVMConcurrently().enqueueTaskConcurrent(jsc.ConcurrentTask.create(jsc.Task.init(task))); } pub inline fn topLevelDir(this: @This()) []const u8 { @@ -223,8 +223,8 @@ pub const GlobalJS = struct { return this.globalThis.bunVM().transpiler.env; } - pub inline fn platformEventLoop(this: @This()) *JSC.PlatformEventLoop { - const loop = JSC.AbstractVM(this.eventLoopCtx()); + pub inline fn platformEventLoop(this: @This()) *jsc.PlatformEventLoop { + const loop = jsc.AbstractVM(this.eventLoopCtx()); return loop.platformEventLoop(); } @@ -234,9 +234,9 @@ pub const GlobalJS = struct { }; pub const GlobalMini = struct { - mini: *JSC.MiniEventLoop, + mini: *jsc.MiniEventLoop, - pub inline fn init(g: *JSC.MiniEventLoop) @This() { + pub inline fn init(g: *jsc.MiniEventLoop) @This() { return .{ .mini = g, }; @@ -250,7 +250,7 @@ pub const GlobalMini = struct { return this.mini.allocator; } - pub inline fn eventLoopCtx(this: @This()) *JSC.MiniEventLoop { + pub inline fn eventLoopCtx(this: @This()) *jsc.MiniEventLoop { return this.mini; } @@ -284,7 +284,7 @@ pub const GlobalMini = struct { } pub inline fn enqueueTaskConcurrentWaitPid(this: @This(), task: anytype) void { - var anytask = bun.default_allocator.create(JSC.AnyTaskWithExtraContext) catch bun.outOfMemory(); + var anytask = bun.default_allocator.create(jsc.AnyTaskWithExtraContext) catch bun.outOfMemory(); _ = anytask.from(task, "runFromMainThreadMini"); this.mini.enqueueTaskConcurrent(anytask); } @@ -304,13 +304,13 @@ pub const GlobalMini = struct { shellerr.throwMini(); } - pub inline fn platformEventLoop(this: @This()) *JSC.PlatformEventLoop { - const loop = JSC.AbstractVM(this.eventLoopCtx()); + pub inline fn platformEventLoop(this: @This()) *jsc.PlatformEventLoop { + const loop = jsc.AbstractVM(this.eventLoopCtx()); return loop.platformEventLoop(); } }; -// const GlobalHandle = if (JSC.EventLoopKind == .js) GlobalJS else GlobalMini; +// const GlobalHandle = if (jsc.EventLoopKind == .js) GlobalJS else GlobalMini; pub const AST = struct { pub const Script = struct { @@ -3695,9 +3695,9 @@ pub const Test = struct { }; pub fn shellCmdFromJS( - globalThis: *JSC.JSGlobalObject, + globalThis: *jsc.JSGlobalObject, string_args: JSValue, - template_args: *JSC.JSArrayIterator, + template_args: *jsc.JSArrayIterator, out_jsobjs: *std.ArrayList(JSValue), jsstrings: *std.ArrayList(bun.String), out_script: *std.ArrayList(u8), @@ -3726,7 +3726,7 @@ pub fn shellCmdFromJS( } pub fn handleTemplateValue( - globalThis: *JSC.JSGlobalObject, + globalThis: *jsc.JSGlobalObject, template_value: JSValue, out_jsobjs: *std.ArrayList(JSValue), out_script: *std.ArrayList(u8), @@ -3745,7 +3745,7 @@ pub fn handleTemplateValue( return; } - if (template_value.as(JSC.WebCore.Blob)) |blob| { + if (template_value.as(jsc.WebCore.Blob)) |blob| { if (blob.store) |store| { if (store.data == .file) { if (store.data.file.pathlike == .path) { @@ -3766,7 +3766,7 @@ pub fn handleTemplateValue( return; } - if (try JSC.WebCore.ReadableStream.fromJS(template_value, globalThis)) |rstream| { + if (try jsc.WebCore.ReadableStream.fromJS(template_value, globalThis)) |rstream| { _ = rstream; const idx = out_jsobjs.items.len; @@ -3777,7 +3777,7 @@ pub fn handleTemplateValue( return; } - if (template_value.as(JSC.WebCore.Response)) |req| { + if (template_value.as(jsc.WebCore.Response)) |req| { _ = req; const idx = out_jsobjs.items.len; @@ -3843,13 +3843,13 @@ pub fn handleTemplateValue( } pub const ShellSrcBuilder = struct { - globalThis: *JSC.JSGlobalObject, + globalThis: *jsc.JSGlobalObject, outbuf: *std.ArrayList(u8), jsstrs_to_escape: *std.ArrayList(bun.String), jsstr_ref_buf: [128]u8 = [_]u8{0} ** 128, pub fn init( - globalThis: *JSC.JSGlobalObject, + globalThis: *jsc.JSGlobalObject, outbuf: *std.ArrayList(u8), jsstrs_to_escape: *std.ArrayList(bun.String), ) ShellSrcBuilder { @@ -4273,11 +4273,11 @@ pub fn SmolList(comptime T: type, comptime INLINED_MAX: comptime_int) type { /// Used in JS tests, see `internal-for-testing.ts` and shell tests. pub const TestingAPIs = struct { - pub fn disabledOnThisPlatform(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { + pub fn disabledOnThisPlatform(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { if (comptime bun.Environment.isWindows) return JSValue.false; const arguments_ = callframe.arguments_old(1); - var arguments = JSC.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), arguments_.slice()); + var arguments = jsc.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), arguments_.slice()); const string = arguments.nextEat() orelse { return globalThis.throw("shellInternals.disabledOnPosix: expected 1 arguments, got 0", .{}); }; @@ -4296,11 +4296,11 @@ pub const TestingAPIs = struct { } pub fn shellLex( - globalThis: *JSC.JSGlobalObject, - callframe: *JSC.CallFrame, - ) bun.JSError!JSC.JSValue { + globalThis: *jsc.JSGlobalObject, + callframe: *jsc.CallFrame, + ) bun.JSError!jsc.JSValue { const arguments_ = callframe.arguments_old(2); - var arguments = JSC.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), arguments_.slice()); + var arguments = jsc.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), arguments_.slice()); const string_args = arguments.nextEat() orelse { return globalThis.throw("shell_parse: expected 2 arguments, got 0", .{}); }; @@ -4364,11 +4364,11 @@ pub const TestingAPIs = struct { } pub fn shellParse( - globalThis: *JSC.JSGlobalObject, - callframe: *JSC.CallFrame, - ) bun.JSError!JSC.JSValue { + globalThis: *jsc.JSGlobalObject, + callframe: *jsc.CallFrame, + ) bun.JSError!jsc.JSValue { const arguments_ = callframe.arguments_old(2); - var arguments = JSC.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), arguments_.slice()); + var arguments = jsc.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), arguments_.slice()); const string_args = arguments.nextEat() orelse { return globalThis.throw("shell_parse: expected 2 arguments, got 0", .{}); }; @@ -4429,15 +4429,15 @@ const Glob = @import("../glob.zig"); const Syscall = @import("../sys.zig"); const builtin = @import("builtin"); -const CodepointIterator = @import("../string_immutable.zig").UnsignedCodepointIterator; -const isAllAscii = @import("../string_immutable.zig").isAllASCII; - const bun = @import("bun"); const assert = bun.assert; -const JSC = bun.JSC; -const JSGlobalObject = bun.JSC.JSGlobalObject; -const JSValue = bun.JSC.JSValue; +const jsc = bun.jsc; +const JSGlobalObject = bun.jsc.JSGlobalObject; +const JSValue = bun.jsc.JSValue; + +const CodepointIterator = bun.strings.UnsignedCodepointIterator; +const isAllAscii = bun.strings.isAllASCII; const std = @import("std"); const ArrayList = std.ArrayList; diff --git a/src/shell/states/Async.zig b/src/shell/states/Async.zig index 8bb00c4f7f..a0344a3ec3 100644 --- a/src/shell/states/Async.zig +++ b/src/shell/states/Async.zig @@ -11,8 +11,8 @@ state: union(enum) { }, done: ExitCode, } = .idle, -event_loop: JSC.EventLoopHandle, -concurrent_task: JSC.EventLoopTask, +event_loop: jsc.EventLoopHandle, +concurrent_task: jsc.EventLoopTask, pub const ParentPtr = StatePtrUnion(.{ Binary, @@ -45,7 +45,7 @@ pub fn init( .parent = parent, .io = io, .event_loop = interpreter.event_loop, - .concurrent_task = JSC.EventLoopTask.fromEventLoop(interpreter.event_loop), + .concurrent_task = jsc.EventLoopTask.fromEventLoop(interpreter.event_loop), }; return async_cmd; } @@ -158,7 +158,7 @@ pub fn runFromMainThreadMini(this: *Async, _: *void) void { const std = @import("std"); const bun = @import("bun"); -const JSC = bun.JSC; +const jsc = bun.jsc; const shell = bun.shell; const ExitCode = bun.shell.ExitCode; diff --git a/src/shell/states/Base.zig b/src/shell/states/Base.zig index 94eef827bc..3add0ec5fc 100644 --- a/src/shell/states/Base.zig +++ b/src/shell/states/Base.zig @@ -89,7 +89,7 @@ pub fn endScope(this: *Base) void { } } -pub inline fn eventLoop(this: *const Base) JSC.EventLoopHandle { +pub inline fn eventLoop(this: *const Base) jsc.EventLoopHandle { return this.interpreter.event_loop; } @@ -129,7 +129,7 @@ pub fn leakSlice(this: *Base, memory: anytype) void { const std = @import("std"); const bun = @import("bun"); -const JSC = bun.JSC; +const jsc = bun.jsc; const Interpreter = bun.shell.Interpreter; const IO = bun.shell.Interpreter.IO; diff --git a/src/shell/states/Cmd.zig b/src/shell/states/Cmd.zig index d7425651ab..05de8d46ee 100644 --- a/src/shell/states/Cmd.zig +++ b/src/shell/states/Cmd.zig @@ -59,7 +59,7 @@ state: union(enum) { /// undefined memory. pub const ShellAsyncSubprocessDone = struct { cmd: *Cmd, - concurrent_task: JSC.EventLoopTask, + concurrent_task: jsc.EventLoopTask, pub fn format(this: *const ShellAsyncSubprocessDone, comptime fmt: []const u8, opts: std.fmt.FormatOptions, writer: anytype) !void { _ = fmt; // autofix @@ -352,7 +352,7 @@ pub fn start(this: *Cmd) Yield { return .{ .cmd = this }; } -pub fn onIOWriterChunk(this: *Cmd, _: usize, e: ?JSC.SystemError) Yield { +pub fn onIOWriterChunk(this: *Cmd, _: usize, e: ?jsc.SystemError) Yield { if (e) |err| { this.base.throw(&bun.shell.ShellErr.newSys(err)); return .failed; @@ -558,13 +558,13 @@ fn initRedirections(this: *Cmd, spawn_args: *Subprocess.SpawnArgs) bun.JSError!? const global = this.base.eventLoop().js.global; if (this.base.interpreter.jsobjs[val.idx].asArrayBuffer(global)) |buf| { - const stdio: bun.shell.subproc.Stdio = .{ .array_buffer = JSC.ArrayBuffer.Strong{ + const stdio: bun.shell.subproc.Stdio = .{ .array_buffer = jsc.ArrayBuffer.Strong{ .array_buffer = buf, .held = .create(buf.value, global), } }; setStdioFromRedirect(&spawn_args.stdio, this.node.redirect, stdio); - } else if (this.base.interpreter.jsobjs[val.idx].as(JSC.WebCore.Blob)) |blob__| { + } else if (this.base.interpreter.jsobjs[val.idx].as(jsc.WebCore.Blob)) |blob__| { const blob = blob__.dupe(); if (this.node.redirect.stdin) { try spawn_args.stdio[stdin_no].extractBlob(global, .{ .Blob = blob }, stdin_no); @@ -573,10 +573,10 @@ fn initRedirections(this: *Cmd, spawn_args: *Subprocess.SpawnArgs) bun.JSError!? } else if (this.node.redirect.stderr) { try spawn_args.stdio[stdin_no].extractBlob(global, .{ .Blob = blob }, stderr_no); } - } else if (try JSC.WebCore.ReadableStream.fromJS(this.base.interpreter.jsobjs[val.idx], global)) |rstream| { + } else if (try jsc.WebCore.ReadableStream.fromJS(this.base.interpreter.jsobjs[val.idx], global)) |rstream| { _ = rstream; @panic("TODO SHELL READABLE STREAM"); - } else if (this.base.interpreter.jsobjs[val.idx].as(JSC.WebCore.Response)) |req| { + } else if (this.base.interpreter.jsobjs[val.idx].as(jsc.WebCore.Response)) |req| { req.getBodyValue().toBlobIfPossible(); if (this.node.redirect.stdin) { try spawn_args.stdio[stdin_no].extractBlob(global, req.getBodyValue().useAsAnyBlob(), stdin_no); @@ -736,7 +736,7 @@ pub fn bufferedInputClose(this: *Cmd) void { this.exec.subproc.buffered_closed.close(this, .stdin); } -pub fn bufferedOutputClose(this: *Cmd, kind: Subprocess.OutKind, err: ?JSC.SystemError) Yield { +pub fn bufferedOutputClose(this: *Cmd, kind: Subprocess.OutKind, err: ?jsc.SystemError) Yield { switch (kind) { .stdout => this.bufferedOutputCloseStdout(err), .stderr => this.bufferedOutputCloseStderr(err), @@ -745,7 +745,7 @@ pub fn bufferedOutputClose(this: *Cmd, kind: Subprocess.OutKind, err: ?JSC.Syste if (!this.spawn_arena_freed) { var async_subprocess_done = bun.new(ShellAsyncSubprocessDone, .{ .cmd = this, - .concurrent_task = JSC.EventLoopTask.fromEventLoop(this.base.eventLoop()), + .concurrent_task = jsc.EventLoopTask.fromEventLoop(this.base.eventLoop()), }); async_subprocess_done.enqueue(); return .suspended; @@ -756,7 +756,7 @@ pub fn bufferedOutputClose(this: *Cmd, kind: Subprocess.OutKind, err: ?JSC.Syste return .suspended; } -pub fn bufferedOutputCloseStdout(this: *Cmd, err: ?JSC.SystemError) void { +pub fn bufferedOutputCloseStdout(this: *Cmd, err: ?jsc.SystemError) void { if (comptime bun.Environment.allow_assert) { assert(this.exec == .subproc); } @@ -773,7 +773,7 @@ pub fn bufferedOutputCloseStdout(this: *Cmd, err: ?JSC.SystemError) void { this.exec.subproc.child.closeIO(.stdout); } -pub fn bufferedOutputCloseStderr(this: *Cmd, err: ?JSC.SystemError) void { +pub fn bufferedOutputCloseStderr(this: *Cmd, err: ?jsc.SystemError) void { if (comptime bun.Environment.allow_assert) { assert(this.exec == .subproc); } @@ -793,8 +793,8 @@ const std = @import("std"); const Allocator = std.mem.Allocator; const bun = @import("bun"); -const JSC = bun.JSC; const assert = bun.assert; +const jsc = bun.jsc; const which = bun.which; const shell = bun.shell; diff --git a/src/shell/states/CondExpr.zig b/src/shell/states/CondExpr.zig index 2269023d21..d44bb52fbb 100644 --- a/src/shell/states/CondExpr.zig +++ b/src/shell/states/CondExpr.zig @@ -200,7 +200,7 @@ fn doStat(this: *CondExpr) Yield { const stat_task = bun.new(ShellCondExprStatTask, .{ .task = .{ .event_loop = this.base.eventLoop(), - .concurrent_task = JSC.EventLoopTask.fromEventLoop(this.base.eventLoop()), + .concurrent_task = jsc.EventLoopTask.fromEventLoop(this.base.eventLoop()), }, .condexpr = this, .path = this.args.items[0], @@ -253,7 +253,7 @@ pub fn writeFailingError(this: *CondExpr, comptime fmt: []const u8, args: anytyp return this.base.shell.writeFailingErrorFmt(this, handler.enqueueCb, fmt, args); } -pub fn onIOWriterChunk(this: *CondExpr, _: usize, err: ?JSC.SystemError) Yield { +pub fn onIOWriterChunk(this: *CondExpr, _: usize, err: ?jsc.SystemError) Yield { if (err != null) { defer err.?.deref(); const exit_code: ExitCode = @intFromEnum(err.?.getErrno()); @@ -272,8 +272,8 @@ const std = @import("std"); const bun = @import("bun"); const assert = bun.assert; -const JSC = bun.JSC; -const Maybe = JSC.Maybe; +const jsc = bun.jsc; +const Maybe = jsc.Maybe; const shell = bun.shell; const ExitCode = bun.shell.ExitCode; diff --git a/src/shell/states/Expansion.zig b/src/shell/states/Expansion.zig index 1365e5dab5..17c656a062 100644 --- a/src/shell/states/Expansion.zig +++ b/src/shell/states/Expansion.zig @@ -743,8 +743,8 @@ pub const ShellGlobTask = struct { walker: *GlobWalker, result: std.ArrayList([:0]const u8), - event_loop: JSC.EventLoopHandle, - concurrent_task: JSC.EventLoopTask, + event_loop: jsc.EventLoopHandle, + concurrent_task: jsc.EventLoopTask, // This is a poll because we want it to enter the uSockets loop ref: bun.Async.KeepAlive = .{}, err: ?Err = null, @@ -759,7 +759,7 @@ pub const ShellGlobTask = struct { pub fn toJS(this: Err, globalThis: *JSGlobalObject) JSValue { return switch (this) { .syscall => |err| err.toJS(globalThis), - .unknown => |err| JSC.ZigString.fromBytes(@errorName(err)).toJS(globalThis), + .unknown => |err| jsc.ZigString.fromBytes(@errorName(err)).toJS(globalThis), }; } }; @@ -771,7 +771,7 @@ pub const ShellGlobTask = struct { this.* = .{ .alloc_scope = alloc_scope, .event_loop = expansion.base.eventLoop(), - .concurrent_task = JSC.EventLoopTask.fromEventLoop(expansion.base.eventLoop()), + .concurrent_task = jsc.EventLoopTask.fromEventLoop(expansion.base.eventLoop()), .walker = walker, .expansion = expansion, .result = std.ArrayList([:0]const u8).init(this.alloc_scope.allocator()), @@ -853,10 +853,10 @@ const Allocator = std.mem.Allocator; const bun = @import("bun"); const assert = bun.assert; -const JSC = bun.JSC; -const JSGlobalObject = JSC.JSGlobalObject; -const JSValue = JSC.JSValue; -const Maybe = JSC.Maybe; +const jsc = bun.jsc; +const JSGlobalObject = jsc.JSGlobalObject; +const JSValue = jsc.JSValue; +const Maybe = jsc.Maybe; const ExitCode = bun.shell.ExitCode; const Yield = bun.shell.Yield; diff --git a/src/shell/states/Pipeline.zig b/src/shell/states/Pipeline.zig index ff936e4fd1..dd95b64152 100644 --- a/src/shell/states/Pipeline.zig +++ b/src/shell/states/Pipeline.zig @@ -191,7 +191,7 @@ pub fn next(this: *Pipeline) Yield { } } -pub fn onIOWriterChunk(this: *Pipeline, _: usize, err: ?JSC.SystemError) Yield { +pub fn onIOWriterChunk(this: *Pipeline, _: usize, err: ?jsc.SystemError) Yield { if (comptime bun.Environment.allow_assert) { assert(this.state == .waiting_write_err); } @@ -305,7 +305,7 @@ fn initializePipes(pipes: []Pipe, set_count: *u32) Maybe(void) { return Maybe(void).success; } -fn writePipe(pipes: []Pipe, proc_idx: usize, cmd_count: usize, io: *IO, evtloop: JSC.EventLoopHandle) IO.OutKind { +fn writePipe(pipes: []Pipe, proc_idx: usize, cmd_count: usize, io: *IO, evtloop: jsc.EventLoopHandle) IO.OutKind { // Last command in the pipeline should write to stdout if (proc_idx == cmd_count - 1) return io.stdout.ref(); return .{ @@ -318,7 +318,7 @@ fn writePipe(pipes: []Pipe, proc_idx: usize, cmd_count: usize, io: *IO, evtloop: }; } -fn readPipe(pipes: []Pipe, proc_idx: usize, io: *IO, evtloop: JSC.EventLoopHandle) IO.InKind { +fn readPipe(pipes: []Pipe, proc_idx: usize, io: *IO, evtloop: jsc.EventLoopHandle) IO.InKind { // First command in the pipeline should read from stdin if (proc_idx == 0) return io.stdin.ref(); return .{ .fd = IOReader.init(pipes[proc_idx - 1][0], evtloop) }; @@ -329,8 +329,8 @@ const std = @import("std"); const bun = @import("bun"); const assert = bun.assert; -const JSC = bun.JSC; -const Maybe = JSC.Maybe; +const jsc = bun.jsc; +const Maybe = jsc.Maybe; const shell = bun.shell; const ExitCode = bun.shell.ExitCode; diff --git a/src/shell/states/Subshell.zig b/src/shell/states/Subshell.zig index ee704dcf8e..0c8718e73d 100644 --- a/src/shell/states/Subshell.zig +++ b/src/shell/states/Subshell.zig @@ -57,7 +57,7 @@ pub fn initDupeShellState( node: *const ast.Subshell, parent: ParentPtr, io: IO, -) bun.JSC.Maybe(*Subshell) { +) bun.jsc.Maybe(*Subshell) { const subshell = parent.create(Subshell); subshell.* = .{ .base = State.initWithNewAllocScope(.subshell, interpreter, shell_state), @@ -157,7 +157,7 @@ pub fn childDone(this: *Subshell, child_ptr: ChildPtr, exit_code: ExitCode) Yiel bun.shell.unreachableState("Subshell.childDone", "expected Script or Expansion"); } -pub fn onIOWriterChunk(this: *Subshell, _: usize, err: ?JSC.SystemError) Yield { +pub fn onIOWriterChunk(this: *Subshell, _: usize, err: ?jsc.SystemError) Yield { if (comptime bun.Environment.allow_assert) { assert(this.state == .wait_write_err); } @@ -190,8 +190,8 @@ pub fn writeFailingError(this: *Subshell, comptime fmt: []const u8, args: anytyp const std = @import("std"); const bun = @import("bun"); -const JSC = bun.JSC; const assert = bun.assert; +const jsc = bun.jsc; const shell = bun.shell; const ExitCode = bun.shell.ExitCode; diff --git a/src/shell/subproc.zig b/src/shell/subproc.zig index 3fac5019d0..de7983aa8f 100644 --- a/src/shell/subproc.zig +++ b/src/shell/subproc.zig @@ -41,14 +41,14 @@ pub const ShellSubprocess = struct { stdout: Readable = undefined, stderr: Readable = undefined, - event_loop: JSC.EventLoopHandle, + event_loop: jsc.EventLoopHandle, closed: std.enums.EnumSet(enum { stdin, stdout, stderr, }) = .{}, - this_jsvalue: JSC.JSValue = .zero, + this_jsvalue: jsc.JSValue = .zero, flags: Flags = .{}, @@ -60,7 +60,7 @@ pub const ShellSubprocess = struct { } const Writable = union(enum) { - pipe: *JSC.WebCore.FileSink, + pipe: *jsc.WebCore.FileSink, fd: bun.FileDescriptor, buffer: *StaticPipeWriter, memfd: bun.FileDescriptor, @@ -116,12 +116,12 @@ pub const ShellSubprocess = struct { .ignore = {}, }; } - pub fn onReady(_: *Writable, _: ?JSC.WebCore.Blob.SizeType, _: ?JSC.WebCore.Blob.SizeType) void {} + pub fn onReady(_: *Writable, _: ?jsc.WebCore.Blob.SizeType, _: ?jsc.WebCore.Blob.SizeType) void {} pub fn onStart(_: *Writable) void {} pub fn init( stdio: Stdio, - event_loop: JSC.EventLoopHandle, + event_loop: jsc.EventLoopHandle, subprocess: *Subprocess, result: StdioResult, ) !Writable { @@ -131,7 +131,7 @@ pub const ShellSubprocess = struct { switch (stdio) { .pipe, .readable_stream => { if (result == .buffer) { - const pipe = JSC.WebCore.FileSink.createWithPipe(event_loop, result.buffer); + const pipe = jsc.WebCore.FileSink.createWithPipe(event_loop, result.buffer); switch (pipe.writer.startWithCurrentPipe()) { .result => {}, @@ -223,7 +223,7 @@ pub const ShellSubprocess = struct { } } - pub fn toJS(this: *Writable, globalThis: *JSC.JSGlobalObject, subprocess: *Subprocess) JSValue { + pub fn toJS(this: *Writable, globalThis: *jsc.JSGlobalObject, subprocess: *Subprocess) JSValue { return switch (this.*) { .fd => |fd| JSValue.jsNumber(fd), .memfd, .ignore => .js_undefined, @@ -238,7 +238,7 @@ pub const ShellSubprocess = struct { subprocess.weak_file_sink_stdin_ptr = pipe; return pipe.toJSWithDestructor( globalThis, - JSC.WebCore.sink_destructor.Ptr.init(subprocess), + jsc.WebCore.sink_destructor.Ptr.init(subprocess), ); } }, @@ -248,8 +248,8 @@ pub const ShellSubprocess = struct { pub fn finalize(this: *Writable) void { const subprocess: *Subprocess = @fieldParentPtr("stdin", this); if (subprocess.this_jsvalue != .zero) { - if (JSC.Codegen.JSSubprocess.stdinGetCached(subprocess.this_jsvalue)) |existing_value| { - JSC.WebCore.FileSink.JSSink.setDestroyCallback(existing_value, 0); + if (jsc.Codegen.JSSubprocess.stdinGetCached(subprocess.this_jsvalue)) |existing_value| { + jsc.WebCore.FileSink.JSSink.setDestroyCallback(existing_value, 0); } } @@ -342,7 +342,7 @@ pub const ShellSubprocess = struct { } } - pub fn init(out_type: bun.shell.Subprocess.OutKind, stdio: Stdio, shellio: ?*sh.IOWriter, event_loop: JSC.EventLoopHandle, process: *ShellSubprocess, result: StdioResult, allocator: std.mem.Allocator, max_size: u32, is_sync: bool) Readable { + pub fn init(out_type: bun.shell.Subprocess.OutKind, stdio: Stdio, shellio: ?*sh.IOWriter, event_loop: jsc.EventLoopHandle, process: *ShellSubprocess, result: StdioResult, allocator: std.mem.Allocator, max_size: u32, is_sync: bool) Readable { _ = allocator; // autofix _ = max_size; // autofix _ = is_sync; // autofix @@ -442,7 +442,7 @@ pub const ShellSubprocess = struct { // }, // }; - pub const StaticPipeWriter = JSC.Subprocess.NewStaticPipeWriter(ShellSubprocess); + pub const StaticPipeWriter = jsc.Subprocess.NewStaticPipeWriter(ShellSubprocess); pub fn getIO(this: *Subprocess, comptime out_kind: OutKind) *Readable { switch (out_kind) { @@ -483,7 +483,7 @@ pub const ShellSubprocess = struct { return this.process.hasKilled(); } - pub fn tryKill(this: *@This(), sig: i32) JSC.Maybe(void) { + pub fn tryKill(this: *@This(), sig: i32) jsc.Maybe(void) { if (this.hasExited()) { return .{ .result = {} }; } @@ -652,7 +652,7 @@ pub const ShellSubprocess = struct { } }; - pub fn default(arena: *bun.ArenaAllocator, cmd_parent: *ShellCmd, event_loop: JSC.EventLoopHandle, comptime is_sync: bool) SpawnArgs { + pub fn default(arena: *bun.ArenaAllocator, cmd_parent: *ShellCmd, event_loop: jsc.EventLoopHandle, comptime is_sync: bool) SpawnArgs { var out: SpawnArgs = .{ .arena = arena, @@ -721,7 +721,7 @@ pub const ShellSubprocess = struct { pub const WatchFd = bun.FileDescriptor; pub fn spawnAsync( - event_loop: JSC.EventLoopHandle, + event_loop: jsc.EventLoopHandle, shellio: *ShellIO, spawn_args_: SpawnArgs, out: **@This(), @@ -754,7 +754,7 @@ pub const ShellSubprocess = struct { comptime config: struct { is_sync: bool, }, - event_loop: JSC.EventLoopHandle, + event_loop: jsc.EventLoopHandle, allocator: Allocator, spawn_args: *SpawnArgs, shellio: *ShellIO, @@ -939,11 +939,11 @@ pub const PipeReader = struct { reader: IOReader = undefined, process: ?*ShellSubprocess = null, - event_loop: JSC.EventLoopHandle = undefined, + event_loop: jsc.EventLoopHandle = undefined, state: union(enum) { pending: void, done: []u8, - err: ?JSC.SystemError, + err: ?jsc.SystemError, } = .{ .pending = {} }, stdio_result: StdioResult, out_type: bun.shell.subproc.ShellSubprocess.OutKind, @@ -954,7 +954,7 @@ pub const PipeReader = struct { const BufferedOutput = union(enum) { bytelist: bun.ByteList, array_buffer: struct { - buf: JSC.ArrayBuffer.Strong, + buf: jsc.ArrayBuffer.Strong, i: u32 = 0, }, @@ -1005,7 +1005,7 @@ pub const PipeReader = struct { dead: bool = true, writer: *sh.IOWriter = undefined, written: usize = 0, - err: ?JSC.SystemError = null, + err: ?jsc.SystemError = null, pub fn doWrite(this: *CapturedWriter, chunk: []const u8) void { if (this.dead or this.err != null) return; @@ -1028,7 +1028,7 @@ pub const PipeReader = struct { return @fieldParentPtr("captured_writer", this); } - pub fn eventLoop(this: *CapturedWriter) JSC.EventLoopHandle { + pub fn eventLoop(this: *CapturedWriter) jsc.EventLoopHandle { return this.parent().eventLoop(); } @@ -1040,7 +1040,7 @@ pub const PipeReader = struct { return this.written + just_written >= this.parent().buffered_output.len(); } - pub fn onIOWriterChunk(this: *CapturedWriter, amount: usize, err: ?JSC.SystemError) Yield { + pub fn onIOWriterChunk(this: *CapturedWriter, amount: usize, err: ?jsc.SystemError) Yield { log("CapturedWriter({x}, {s}) onWrite({d}, has_err={any}) total_written={d} total_to_write={d}", .{ @intFromPtr(this), @tagName(this.parent().out_type), amount, err != null, this.written + amount, this.parent().buffered_output.len() }); this.written += amount; if (err) |e| { @@ -1090,7 +1090,7 @@ pub const PipeReader = struct { this.trySignalDoneToCmd().run(); } - pub fn create(event_loop: JSC.EventLoopHandle, process: *ShellSubprocess, result: StdioResult, capture: ?*sh.IOWriter, out_type: bun.shell.Subprocess.OutKind) *PipeReader { + pub fn create(event_loop: jsc.EventLoopHandle, process: *ShellSubprocess, result: StdioResult, capture: ?*sh.IOWriter, out_type: bun.shell.Subprocess.OutKind) *PipeReader { var this: *PipeReader = bun.new(PipeReader, .{ .ref_count = .init(), .process = process, @@ -1124,7 +1124,7 @@ pub const PipeReader = struct { this.reader.read(); } - pub fn start(this: *PipeReader, process: *ShellSubprocess, event_loop: JSC.EventLoopHandle) JSC.Maybe(void) { + pub fn start(this: *PipeReader, process: *ShellSubprocess, event_loop: jsc.EventLoopHandle) jsc.Maybe(void) { // this.ref(); this.process = process; this.event_loop = event_loop; @@ -1202,7 +1202,7 @@ pub const PipeReader = struct { this.state = .{ .err = e }; } } - const e: ?JSC.SystemError = brk: { + const e: ?jsc.SystemError = brk: { if (this.state != .err) break :brk null; if (this.state.err) |*e| { e.ref(); @@ -1260,33 +1260,33 @@ pub const PipeReader = struct { this.reader.watch(); } - pub fn toReadableStream(this: *PipeReader, globalObject: *JSC.JSGlobalObject) JSC.JSValue { + pub fn toReadableStream(this: *PipeReader, globalObject: *jsc.JSGlobalObject) jsc.JSValue { defer this.deinit(); switch (this.state) { .pending => { - const stream = JSC.WebCore.ReadableStream.fromPipe(globalObject, this, &this.reader); + const stream = jsc.WebCore.ReadableStream.fromPipe(globalObject, this, &this.reader); this.state = .{ .done = &.{} }; return stream; }, .done => |bytes| { this.state = .{ .done = &.{} }; - return JSC.WebCore.ReadableStream.fromOwnedSlice(globalObject, bytes, 0); + return jsc.WebCore.ReadableStream.fromOwnedSlice(globalObject, bytes, 0); }, .err => |err| { _ = err; // autofix - const empty = try JSC.WebCore.ReadableStream.empty(globalObject); - JSC.WebCore.ReadableStream.cancel(&JSC.WebCore.ReadableStream.fromJS(empty, globalObject).?, globalObject); + const empty = try jsc.WebCore.ReadableStream.empty(globalObject); + jsc.WebCore.ReadableStream.cancel(&jsc.WebCore.ReadableStream.fromJS(empty, globalObject).?, globalObject); return empty; }, } } - pub fn toBuffer(this: *PipeReader, globalThis: *JSC.JSGlobalObject) JSC.JSValue { + pub fn toBuffer(this: *PipeReader, globalThis: *jsc.JSGlobalObject) jsc.JSValue { switch (this.state) { .done => |bytes| { defer this.state = .{ .done = &.{} }; - return JSC.MarkedArrayBuffer.fromBytes(bytes, bun.default_allocator, .Uint8Array).toNodeBuffer(globalThis); + return jsc.MarkedArrayBuffer.fromBytes(bytes, bun.default_allocator, .Uint8Array).toNodeBuffer(globalThis); }, else => { return .js_undefined; @@ -1321,7 +1321,7 @@ pub const PipeReader = struct { } } - pub fn eventLoop(this: *PipeReader) JSC.EventLoopHandle { + pub fn eventLoop(this: *PipeReader) jsc.EventLoopHandle { return this.event_loop; } @@ -1389,10 +1389,10 @@ const default_allocator = bun.default_allocator; const strings = bun.strings; const uws = bun.uws; -const JSC = bun.JSC; -const JSGlobalObject = JSC.JSGlobalObject; -const JSValue = JSC.JSValue; -const FileSink = JSC.WebCore.FileSink; +const jsc = bun.jsc; +const JSGlobalObject = jsc.JSGlobalObject; +const JSValue = jsc.JSValue; +const FileSink = jsc.WebCore.FileSink; const sh = bun.shell; const Yield = bun.shell.Yield; diff --git a/src/sourcemap/CodeCoverage.zig b/src/sourcemap/CodeCoverage.zig index 7e0af482ef..f0bd230df0 100644 --- a/src/sourcemap/CodeCoverage.zig +++ b/src/sourcemap/CodeCoverage.zig @@ -1,4 +1,4 @@ -const LinesHits = @import("../baby_list.zig").BabyList(u32); +const LinesHits = bun.collections.BabyList(u32); /// Our code coverage currently only deals with lines of code, not statements or branches. /// JSC doesn't expose function names in their coverage data, so we don't include that either :(. @@ -15,7 +15,7 @@ const LinesHits = @import("../baby_list.zig").BabyList(u32); /// bitsets are simple and bitsets are relatively fast to construct and query /// pub const Report = struct { - source_url: bun.JSC.ZigString.Slice, + source_url: bun.jsc.ZigString.Slice, executable_lines: Bitset, lines_which_have_executed: Bitset, line_hits: LinesHits = .{}, @@ -272,7 +272,7 @@ pub const Report = struct { } extern fn CodeCoverage__withBlocksAndFunctions( - *bun.JSC.VM, + *bun.jsc.VM, i32, *anyopaque, bool, @@ -318,12 +318,12 @@ pub const Report = struct { }; pub fn generate( - globalThis: *bun.JSC.JSGlobalObject, + globalThis: *bun.jsc.JSGlobalObject, allocator: std.mem.Allocator, byte_range_mapping: *ByteRangeMapping, ignore_sourcemap_: bool, ) ?Report { - bun.JSC.markBinding(@src()); + bun.jsc.markBinding(@src()); const vm = globalThis.vm(); var result: ?Report = null; @@ -358,7 +358,7 @@ const BasicBlockRange = extern struct { pub const ByteRangeMapping = struct { line_offset_table: LineOffsetTable.List = .{}, source_id: i32, - source_url: bun.JSC.ZigString.Slice, + source_url: bun.jsc.ZigString.Slice, pub fn isLessThan(_: void, a: ByteRangeMapping, b: ByteRangeMapping) bool { return bun.strings.order(a.source_url.slice(), b.source_url.slice()) == .lt; @@ -373,8 +373,8 @@ pub const ByteRangeMapping = struct { pub threadlocal var map: ?*HashMap = null; pub fn generate(str: bun.String, source_contents_str: bun.String, source_id: i32) callconv(.C) void { var _map = map orelse brk: { - map = bun.JSC.VirtualMachine.get().allocator.create(HashMap) catch bun.outOfMemory(); - map.?.* = HashMap.init(bun.JSC.VirtualMachine.get().allocator); + map = bun.jsc.VirtualMachine.get().allocator.create(HashMap) catch bun.outOfMemory(); + map.?.* = HashMap.init(bun.jsc.VirtualMachine.get().allocator); break :brk map.?; }; var slice = str.toUTF8(bun.default_allocator); @@ -407,7 +407,7 @@ pub const ByteRangeMapping = struct { pub fn generateReportFromBlocks( this: *ByteRangeMapping, allocator: std.mem.Allocator, - source_url: bun.JSC.ZigString.Slice, + source_url: bun.jsc.ZigString.Slice, blocks: []const BasicBlockRange, function_blocks: []const BasicBlockRange, ignore_sourcemap: bool, @@ -416,7 +416,7 @@ pub const ByteRangeMapping = struct { var executable_lines: Bitset = Bitset{}; var lines_which_have_executed: Bitset = Bitset{}; - const parsed_mappings_ = bun.JSC.VirtualMachine.get().source_mappings.get(source_url.slice()); + const parsed_mappings_ = bun.jsc.VirtualMachine.get().source_mappings.get(source_url.slice()); defer if (parsed_mappings_) |parsed_mapping| parsed_mapping.deref(); var line_hits = LinesHits{}; @@ -650,14 +650,14 @@ pub const ByteRangeMapping = struct { } pub fn findExecutedLines( - globalThis: *bun.JSC.JSGlobalObject, + globalThis: *bun.jsc.JSGlobalObject, source_url: bun.String, blocks_ptr: [*]const BasicBlockRange, blocks_len: usize, function_start_offset: usize, ignore_sourcemap: bool, - ) callconv(.C) bun.JSC.JSValue { - var this = ByteRangeMapping.find(source_url) orelse return bun.JSC.JSValue.null; + ) callconv(.C) bun.jsc.JSValue { + var this = ByteRangeMapping.find(source_url) orelse return bun.jsc.JSValue.null; const blocks: []const BasicBlockRange = blocks_ptr[0..function_start_offset]; var function_blocks: []const BasicBlockRange = blocks_ptr[function_start_offset..blocks_len]; @@ -689,9 +689,9 @@ pub const ByteRangeMapping = struct { return bun.String.createUTF8ForJS(globalThis, mutable_str.slice()) catch return .zero; } - pub fn compute(source_contents: []const u8, source_id: i32, source_url: bun.JSC.ZigString.Slice) ByteRangeMapping { + pub fn compute(source_contents: []const u8, source_id: i32, source_url: bun.jsc.ZigString.Slice) ByteRangeMapping { return ByteRangeMapping{ - .line_offset_table = LineOffsetTable.generate(bun.JSC.VirtualMachine.get().allocator, source_contents, 0), + .line_offset_table = LineOffsetTable.generate(bun.jsc.VirtualMachine.get().allocator, source_contents, 0), .source_id = source_id, .source_url = source_url, }; diff --git a/src/sourcemap/JSSourceMap.zig b/src/sourcemap/JSSourceMap.zig index 266b8d6e54..21c5c10b90 100644 --- a/src/sourcemap/JSSourceMap.zig +++ b/src/sourcemap/JSSourceMap.zig @@ -28,7 +28,7 @@ fn findSourceMap( if (bun.strings.indexOf(source_url, "://")) |source_url_index| { if (bun.strings.eqlComptime(source_url[0..source_url_index], "file")) { - const path = bun.JSC.URL.pathFromFileURL(source_url_string); + const path = bun.jsc.URL.pathFromFileURL(source_url_string); if (path.tag == .Dead) { return globalObject.ERR(.INVALID_URL, "Invalid URL: {s}", .{source_url}).throw(); @@ -233,14 +233,14 @@ extern fn Bun__createNodeModuleSourceMapEntryObject( pub fn findOrigin(this: *JSSourceMap, globalObject: *JSGlobalObject, callFrame: *CallFrame) bun.JSError!JSValue { const line_number, const column_number = try getLineColumn(globalObject, callFrame); - const mapping = this.sourcemap.mappings.find(line_number, column_number) orelse return JSC.JSValue.createEmptyObject(globalObject, 0); + const mapping = this.sourcemap.mappings.find(line_number, column_number) orelse return jsc.JSValue.createEmptyObject(globalObject, 0); const name = try mappingNameToJS(this, globalObject, &mapping); const source = try sourceNameToJS(this, globalObject, &mapping); return Bun__createNodeModuleSourceMapOriginObject( globalObject, name, - JSC.JSValue.jsNumber(mapping.originalLine()), - JSC.JSValue.jsNumber(mapping.originalColumn()), + jsc.JSValue.jsNumber(mapping.originalLine()), + jsc.JSValue.jsNumber(mapping.originalColumn()), source, ); } @@ -248,16 +248,16 @@ pub fn findOrigin(this: *JSSourceMap, globalObject: *JSGlobalObject, callFrame: pub fn findEntry(this: *JSSourceMap, globalObject: *JSGlobalObject, callFrame: *CallFrame) bun.JSError!JSValue { const line_number, const column_number = try getLineColumn(globalObject, callFrame); - const mapping = this.sourcemap.mappings.find(line_number, column_number) orelse return JSC.JSValue.createEmptyObject(globalObject, 0); + const mapping = this.sourcemap.mappings.find(line_number, column_number) orelse return jsc.JSValue.createEmptyObject(globalObject, 0); const name = try mappingNameToJS(this, globalObject, &mapping); const source = try sourceNameToJS(this, globalObject, &mapping); return Bun__createNodeModuleSourceMapEntryObject( globalObject, - JSC.JSValue.jsNumber(mapping.generatedLine()), - JSC.JSValue.jsNumber(mapping.generatedColumn()), - JSC.JSValue.jsNumber(mapping.originalLine()), - JSC.JSValue.jsNumber(mapping.originalColumn()), + jsc.JSValue.jsNumber(mapping.generatedLine()), + jsc.JSValue.jsNumber(mapping.generatedColumn()), + jsc.JSValue.jsNumber(mapping.originalLine()), + jsc.JSValue.jsNumber(mapping.originalColumn()), source, name, ); @@ -284,21 +284,21 @@ pub fn finalize(this: *JSSourceMap) void { } comptime { - const jsFunctionFindSourceMap = JSC.toJSHostFn(findSourceMap); + const jsFunctionFindSourceMap = jsc.toJSHostFn(findSourceMap); @export(&jsFunctionFindSourceMap, .{ .name = "Bun__JSSourceMap__find" }); } -pub const js = JSC.Codegen.JSSourceMap; +pub const js = jsc.Codegen.JSSourceMap; pub const fromJS = js.fromJS; pub const fromJSDirect = js.fromJSDirect; pub const toJS = js.toJS; -const std = @import("std"); +const string = []const u8; const bun = @import("bun"); -const string = bun.string; +const std = @import("std"); -const JSC = bun.JSC; -const CallFrame = JSC.CallFrame; -const JSGlobalObject = JSC.JSGlobalObject; -const JSValue = JSC.JSValue; +const jsc = bun.jsc; +const CallFrame = jsc.CallFrame; +const JSGlobalObject = jsc.JSGlobalObject; +const JSValue = jsc.JSValue; diff --git a/src/sourcemap/sourcemap.zig b/src/sourcemap/sourcemap.zig index 8d2cabd1d6..20e3096910 100644 --- a/src/sourcemap/sourcemap.zig +++ b/src/sourcemap/sourcemap.zig @@ -109,16 +109,16 @@ pub fn parseJSON( // the allocator given to the JS parser is not respected for all parts // of the parse, so we need to remember to reset the ast store - bun.JSAst.Expr.Data.Store.reset(); - bun.JSAst.Stmt.Data.Store.reset(); + bun.ast.Expr.Data.Store.reset(); + bun.ast.Stmt.Data.Store.reset(); defer { // the allocator given to the JS parser is not respected for all parts // of the parse, so we need to remember to reset the ast store - bun.JSAst.Expr.Data.Store.reset(); - bun.JSAst.Stmt.Data.Store.reset(); + bun.ast.Expr.Data.Store.reset(); + bun.ast.Stmt.Data.Store.reset(); } debug("parse (JSON, {d} bytes)", .{source.len}); - var json = bun.JSON.parse(&json_src, &log, arena, false) catch { + var json = bun.json.parse(&json_src, &log, arena, false) catch { return error.InvalidJSON; }; @@ -495,7 +495,7 @@ pub const Mapping = struct { /// /// This data is freed after printed on the assumption that printing /// errors to the console are rare (this isnt used for error.stack) - pub fn getSourceCode(lookup: Lookup, base_filename: []const u8) ?bun.JSC.ZigString.Slice { + pub fn getSourceCode(lookup: Lookup, base_filename: []const u8) ?bun.jsc.ZigString.Slice { const bytes = bytes: { if (lookup.prefetched_source_code) |code| { break :bytes code; @@ -518,7 +518,7 @@ pub const Mapping = struct { const code = serialized.sourceFileContents(@intCast(index)); - return bun.JSC.ZigString.Slice.fromUTF8NeverFree(code orelse return null); + return bun.jsc.ZigString.Slice.fromUTF8NeverFree(code orelse return null); } if (provider.getSourceMap( @@ -551,7 +551,7 @@ pub const Mapping = struct { } }; - return bun.JSC.ZigString.Slice.init(bun.default_allocator, bytes); + return bun.jsc.ZigString.Slice.init(bun.default_allocator, bytes); } }; @@ -1020,14 +1020,14 @@ pub const SourceMapLoadHint = enum(u2) { is_external_map, }; -fn findSourceMappingURL(comptime T: type, source: []const T, alloc: std.mem.Allocator) ?bun.JSC.ZigString.Slice { +fn findSourceMappingURL(comptime T: type, source: []const T, alloc: std.mem.Allocator) ?bun.jsc.ZigString.Slice { const needle = comptime bun.strings.literal(T, "\n//# sourceMappingURL="); const found = bun.strings.indexOfT(T, source, needle) orelse return null; const end = std.mem.indexOfScalarPos(T, source, found + needle.len, '\n') orelse source.len; const url = std.mem.trimRight(T, source[found + needle.len .. end], &.{ ' ', '\r' }); return switch (T) { - u8 => bun.JSC.ZigString.Slice.fromUTF8NeverFree(url), - u16 => bun.JSC.ZigString.Slice.init( + u8 => bun.jsc.ZigString.Slice.fromUTF8NeverFree(url), + u16 => bun.jsc.ZigString.Slice.init( alloc, bun.strings.toUTF8Alloc(alloc, url) catch bun.outOfMemory(), ), @@ -1089,7 +1089,7 @@ pub fn getSourceMapImpl( // try to load a .map file if (load_hint != .is_inline_map) try_external: { if (comptime SourceProviderKind == BakeSourceProvider) fallback_to_normal: { - const global = bun.JSC.VirtualMachine.get().global; + const global = bun.jsc.VirtualMachine.get().global; // If we're using bake's production build the global object will // be Bake::GlobalObject and we can fetch the sourcemap from it, // if not fallback to the normal way @@ -1117,7 +1117,7 @@ pub fn getSourceMapImpl( source_filename, @errorName(err), }); // Disable the "try using --sourcemap=external" hint - bun.JSC.SavedSourceMap.MissingSourceMapNoteInfo.seen_invalid = true; + bun.jsc.SavedSourceMap.MissingSourceMapNoteInfo.seen_invalid = true; return null; }, }; @@ -1151,7 +1151,7 @@ pub fn getSourceMapImpl( source_filename, @errorName(err), }); // Disable the "try using --sourcemap=external" hint - bun.JSC.SavedSourceMap.MissingSourceMapNoteInfo.seen_invalid = true; + bun.jsc.SavedSourceMap.MissingSourceMapNoteInfo.seen_invalid = true; return null; }, }; @@ -1163,7 +1163,7 @@ pub fn getSourceMapImpl( @errorName(err), }); // Disable the "try using --sourcemap=external" hint - bun.JSC.SavedSourceMap.MissingSourceMapNoteInfo.seen_invalid = true; + bun.jsc.SavedSourceMap.MissingSourceMapNoteInfo.seen_invalid = true; return null; } @@ -1204,9 +1204,9 @@ pub const SourceProviderMap = opaque { } }; -extern "c" fn BakeGlobalObject__isBakeGlobalObject(global: *bun.JSC.JSGlobalObject) bool; +extern "c" fn BakeGlobalObject__isBakeGlobalObject(global: *bun.jsc.JSGlobalObject) bool; -extern "c" fn BakeGlobalObject__getPerThreadData(global: *bun.JSC.JSGlobalObject) *bun.bake.production.PerThread; +extern "c" fn BakeGlobalObject__getPerThreadData(global: *bun.jsc.JSGlobalObject) *bun.bake.production.PerThread; pub const BakeSourceProvider = opaque { extern fn BakeSourceProvider__getSourceSlice(*BakeSourceProvider) bun.String; @@ -1215,7 +1215,7 @@ pub const BakeSourceProvider = opaque { return ParsedSourceMap.SourceContentPtr.fromBakeProvider(this); } - pub fn getExternal(_: *BakeSourceProvider, global: *bun.JSC.JSGlobalObject, source_filename: []const u8) []const u8 { + pub fn getExternal(_: *BakeSourceProvider, global: *bun.jsc.JSGlobalObject, source_filename: []const u8) []const u8 { bun.assert(BakeGlobalObject__isBakeGlobalObject(global)); const pt = BakeGlobalObject__getPerThreadData(global); if (pt.source_maps.get(source_filename)) |value| { @@ -1473,7 +1473,13 @@ pub const SourceMapPieces = struct { // After all chunks are computed, they are joined together in a second pass. // This rewrites the first mapping in each chunk to be relative to the end // state of the previous chunk. -pub fn appendSourceMapChunk(j: *StringJoiner, allocator: std.mem.Allocator, prev_end_state_: SourceMapState, start_state_: SourceMapState, source_map_: bun.string) !void { +pub fn appendSourceMapChunk( + j: *StringJoiner, + allocator: std.mem.Allocator, + prev_end_state_: SourceMapState, + start_state_: SourceMapState, + source_map_: []const u8, +) !void { var prev_end_state = prev_end_state_; var start_state = start_state_; // Handle line breaks in between this mapping and the previous one @@ -1973,16 +1979,16 @@ pub const JSSourceMap = @import("./JSSourceMap.zig"); const decodeVLQAssumeValid = VLQ.decodeAssumeValid; const decodeVLQ = VLQ.decode; +const string = []const u8; + const std = @import("std"); const bun = @import("bun"); -const JSAst = bun.JSAst; const JSPrinter = bun.js_printer; const Logger = bun.logger; const MutableString = bun.MutableString; const StringJoiner = bun.StringJoiner; const URL = bun.URL; const assert = bun.assert; -const string = bun.string; const strings = bun.strings; const FileSystem = bun.fs.FileSystem; diff --git a/src/sql/postgres.zig b/src/sql/postgres.zig index e7977c761d..6deeeb8da0 100644 --- a/src/sql/postgres.zig +++ b/src/sql/postgres.zig @@ -1,17 +1,17 @@ -pub fn createBinding(globalObject: *JSC.JSGlobalObject) JSValue { +pub fn createBinding(globalObject: *jsc.JSGlobalObject) JSValue { const binding = JSValue.createEmptyObjectWithNullPrototype(globalObject); binding.put(globalObject, ZigString.static("PostgresSQLConnection"), PostgresSQLConnection.js.getConstructor(globalObject)); - binding.put(globalObject, ZigString.static("init"), JSC.JSFunction.create(globalObject, "init", PostgresSQLContext.init, 0, .{})); + binding.put(globalObject, ZigString.static("init"), jsc.JSFunction.create(globalObject, "init", PostgresSQLContext.init, 0, .{})); binding.put( globalObject, ZigString.static("createQuery"), - JSC.JSFunction.create(globalObject, "createQuery", PostgresSQLQuery.call, 6, .{}), + jsc.JSFunction.create(globalObject, "createQuery", PostgresSQLQuery.call, 6, .{}), ); binding.put( globalObject, ZigString.static("createConnection"), - JSC.JSFunction.create(globalObject, "createQuery", PostgresSQLConnection.call, 2, .{}), + jsc.JSFunction.create(globalObject, "createQuery", PostgresSQLConnection.call, 2, .{}), ); return binding; @@ -25,6 +25,6 @@ pub const types = @import("./postgres/PostgresTypes.zig"); const bun = @import("bun"); -const JSC = bun.JSC; -const JSValue = JSC.JSValue; -const ZigString = JSC.ZigString; +const jsc = bun.jsc; +const JSValue = jsc.JSValue; +const ZigString = jsc.ZigString; diff --git a/src/sql/postgres/AnyPostgresError.zig b/src/sql/postgres/AnyPostgresError.zig index 40ff3ddd92..58582814ad 100644 --- a/src/sql/postgres/AnyPostgresError.zig +++ b/src/sql/postgres/AnyPostgresError.zig @@ -33,8 +33,8 @@ pub const AnyPostgresError = error{ UnknownFormatCode, }; -pub fn postgresErrorToJS(globalObject: *JSC.JSGlobalObject, message: ?[]const u8, err: AnyPostgresError) JSValue { - const error_code: JSC.Error = switch (err) { +pub fn postgresErrorToJS(globalObject: *jsc.JSGlobalObject, message: ?[]const u8, err: AnyPostgresError) JSValue { + const error_code: jsc.Error = switch (err) { error.ConnectionClosed => .POSTGRES_CONNECTION_CLOSED, error.ExpectedRequest => .POSTGRES_EXPECTED_REQUEST, error.ExpectedStatement => .POSTGRES_EXPECTED_STATEMENT, @@ -83,5 +83,5 @@ pub fn postgresErrorToJS(globalObject: *JSC.JSGlobalObject, message: ?[]const u8 const bun = @import("bun"); -const JSC = bun.JSC; -const JSValue = JSC.JSValue; +const jsc = bun.jsc; +const JSValue = jsc.JSValue; diff --git a/src/sql/postgres/CommandTag.zig b/src/sql/postgres/CommandTag.zig index a19196030f..579cab853b 100644 --- a/src/sql/postgres/CommandTag.zig +++ b/src/sql/postgres/CommandTag.zig @@ -29,7 +29,7 @@ pub const CommandTag = union(enum) { other: []const u8, - pub fn toJSTag(this: CommandTag, globalObject: *JSC.JSGlobalObject) JSValue { + pub fn toJSTag(this: CommandTag, globalObject: *jsc.JSGlobalObject) JSValue { return switch (this) { .INSERT => JSValue.jsNumber(1), .DELETE => JSValue.jsNumber(2), @@ -39,7 +39,7 @@ pub const CommandTag = union(enum) { .MOVE => JSValue.jsNumber(6), .FETCH => JSValue.jsNumber(7), .COPY => JSValue.jsNumber(8), - .other => |tag| JSC.ZigString.init(tag).toJS(globalObject), + .other => |tag| jsc.ZigString.init(tag).toJS(globalObject), }; } @@ -101,5 +101,5 @@ const debug = bun.Output.scoped(.Postgres, false); const bun = @import("bun"); const std = @import("std"); -const JSC = bun.JSC; -const JSValue = JSC.JSValue; +const jsc = bun.jsc; +const JSValue = jsc.JSValue; diff --git a/src/sql/postgres/DataCell.zig b/src/sql/postgres/DataCell.zig index 6ba3dc832c..70e4a1361f 100644 --- a/src/sql/postgres/DataCell.zig +++ b/src/sql/postgres/DataCell.zig @@ -193,7 +193,7 @@ pub const DataCell = extern struct { if (slice.len <= count) return ""; return slice[count..]; } - fn parseArray(bytes: []const u8, bigint: bool, comptime arrayType: types.Tag, globalObject: *JSC.JSGlobalObject, offset: ?*usize, comptime is_json_sub_array: bool) !DataCell { + fn parseArray(bytes: []const u8, bigint: bool, comptime arrayType: types.Tag, globalObject: *jsc.JSGlobalObject, offset: ?*usize, comptime is_json_sub_array: bool) !DataCell { const closing_brace = if (is_json_sub_array) ']' else '}'; const opening_brace = if (is_json_sub_array) '[' else '{'; if (bytes.len < 2 or bytes[0] != opening_brace) { @@ -587,7 +587,7 @@ pub const DataCell = extern struct { return DataCell{ .tag = .array, .value = .{ .array = .{ .ptr = array.items.ptr, .len = @truncate(array.items.len), .cap = @truncate(array.capacity) } } }; } - pub fn fromBytes(binary: bool, bigint: bool, oid: types.Tag, bytes: []const u8, globalObject: *JSC.JSGlobalObject) !DataCell { + pub fn fromBytes(binary: bool, bigint: bool, oid: types.Tag, bytes: []const u8, globalObject: *jsc.JSGlobalObject) !DataCell { switch (oid) { // TODO: .int2_array, .float8_array inline .int4_array, .float4_array => |tag| { @@ -1001,22 +1001,22 @@ pub const DataCell = extern struct { binary: bool = false, bigint: bool = false, count: usize = 0, - globalObject: *JSC.JSGlobalObject, + globalObject: *jsc.JSGlobalObject, extern fn JSC__constructObjectFromDataCell( - *JSC.JSGlobalObject, + *jsc.JSGlobalObject, JSValue, JSValue, [*]DataCell, u32, Flags, u8, // result_mode - ?[*]JSC.JSObject.ExternColumnIdentifier, // names + ?[*]jsc.JSObject.ExternColumnIdentifier, // names u32, // names count ) JSValue; - pub fn toJS(this: *Putter, globalObject: *JSC.JSGlobalObject, array: JSValue, structure: JSValue, flags: Flags, result_mode: PostgresSQLQueryResultMode, cached_structure: ?PostgresCachedStructure) JSValue { - var names: ?[*]JSC.JSObject.ExternColumnIdentifier = null; + pub fn toJS(this: *Putter, globalObject: *jsc.JSGlobalObject, array: JSValue, structure: JSValue, flags: Flags, result_mode: PostgresSQLQueryResultMode, cached_structure: ?PostgresCachedStructure) JSValue { + var names: ?[*]jsc.JSObject.ExternColumnIdentifier = null; var names_count: u32 = 0; if (cached_structure) |c| { if (c.fields) |f| { @@ -1101,5 +1101,5 @@ const short = types.short; const bun = @import("bun"); const String = bun.String; -const JSC = bun.JSC; -const JSValue = JSC.JSValue; +const jsc = bun.jsc; +const JSValue = jsc.JSValue; diff --git a/src/sql/postgres/ObjectIterator.zig b/src/sql/postgres/ObjectIterator.zig index 904fc8163b..1e3fbb6de5 100644 --- a/src/sql/postgres/ObjectIterator.zig +++ b/src/sql/postgres/ObjectIterator.zig @@ -2,15 +2,15 @@ const ObjectIterator = @This(); array: JSValue, columns: JSValue = .zero, -globalObject: *JSC.JSGlobalObject, +globalObject: *jsc.JSGlobalObject, cell_i: usize = 0, row_i: usize = 0, -current_row: JSC.JSValue = .zero, +current_row: jsc.JSValue = .zero, columns_count: usize = 0, array_length: usize = 0, any_failed: bool = false, -pub fn next(this: *ObjectIterator) ?JSC.JSValue { +pub fn next(this: *ObjectIterator) ?jsc.JSValue { if (this.row_i >= this.array_length) { return null; } @@ -22,7 +22,7 @@ pub fn next(this: *ObjectIterator) ?JSC.JSValue { const globalObject = this.globalObject; if (this.current_row == .zero) { - this.current_row = JSC.JSObject.getIndex(this.array, globalObject, @intCast(row_i)) catch { + this.current_row = jsc.JSObject.getIndex(this.array, globalObject, @intCast(row_i)) catch { this.any_failed = true; return null; }; @@ -39,7 +39,7 @@ pub fn next(this: *ObjectIterator) ?JSC.JSValue { } } - const property = JSC.JSObject.getIndex(this.columns, globalObject, @intCast(cell_i)) catch { + const property = jsc.JSObject.getIndex(this.columns, globalObject, @intCast(cell_i)) catch { this.any_failed = true; return null; }; @@ -59,5 +59,5 @@ pub fn next(this: *ObjectIterator) ?JSC.JSValue { const bun = @import("bun"); -const JSC = bun.JSC; -const JSValue = JSC.JSValue; +const jsc = bun.jsc; +const JSValue = jsc.JSValue; diff --git a/src/sql/postgres/PostgresCachedStructure.zig b/src/sql/postgres/PostgresCachedStructure.zig index af60d46aa0..82838b94b7 100644 --- a/src/sql/postgres/PostgresCachedStructure.zig +++ b/src/sql/postgres/PostgresCachedStructure.zig @@ -1,16 +1,16 @@ -structure: JSC.Strong.Optional = .empty, -// only populated if more than JSC.JSC__JSObject__maxInlineCapacity fields otherwise the structure will contain all fields inlined -fields: ?[]JSC.JSObject.ExternColumnIdentifier = null, +structure: jsc.Strong.Optional = .empty, +// only populated if more than jsc.JSC__JSObject__maxInlineCapacity fields otherwise the structure will contain all fields inlined +fields: ?[]jsc.JSObject.ExternColumnIdentifier = null, pub fn has(this: *@This()) bool { return this.structure.has() or this.fields != null; } -pub fn jsValue(this: *const @This()) ?JSC.JSValue { +pub fn jsValue(this: *const @This()) ?jsc.JSValue { return this.structure.get(); } -pub fn set(this: *@This(), globalObject: *JSC.JSGlobalObject, value: ?JSC.JSValue, fields: ?[]JSC.JSObject.ExternColumnIdentifier) void { +pub fn set(this: *@This(), globalObject: *jsc.JSGlobalObject, value: ?jsc.JSValue, fields: ?[]jsc.JSObject.ExternColumnIdentifier) void { if (value) |v| { this.structure.set(globalObject, v); } @@ -29,4 +29,4 @@ pub fn deinit(this: *@This()) void { } const bun = @import("bun"); -const JSC = bun.JSC; +const jsc = bun.jsc; diff --git a/src/sql/postgres/PostgresRequest.zig b/src/sql/postgres/PostgresRequest.zig index ad473ddea6..d12cc60b91 100644 --- a/src/sql/postgres/PostgresRequest.zig +++ b/src/sql/postgres/PostgresRequest.zig @@ -1,7 +1,7 @@ pub fn writeBind( name: []const u8, cursor_name: bun.String, - globalObject: *JSC.JSGlobalObject, + globalObject: *jsc.JSGlobalObject, values_array: JSValue, columns_value: JSValue, parameter_fields: []const int4, @@ -209,7 +209,7 @@ pub fn writeQuery( } pub fn prepareAndQueryWithSignature( - globalObject: *JSC.JSGlobalObject, + globalObject: *jsc.JSGlobalObject, query: []const u8, array_value: JSValue, comptime Context: type, @@ -230,7 +230,7 @@ pub fn prepareAndQueryWithSignature( } pub fn bindAndExecute( - globalObject: *JSC.JSGlobalObject, + globalObject: *jsc.JSGlobalObject, statement: *PostgresSQLStatement, array_value: JSValue, columns_value: JSValue, @@ -342,5 +342,5 @@ const short = types.short; const bun = @import("bun"); const String = bun.String; -const JSC = bun.JSC; -const JSValue = JSC.JSValue; +const jsc = bun.jsc; +const JSValue = jsc.JSValue; diff --git a/src/sql/postgres/PostgresSQLConnection.zig b/src/sql/postgres/PostgresSQLConnection.zig index 2f76de2566..351fbebb51 100644 --- a/src/sql/postgres/PostgresSQLConnection.zig +++ b/src/sql/postgres/PostgresSQLConnection.zig @@ -14,7 +14,7 @@ pipelined_requests: u32 = 0, nonpipelinable_requests: u32 = 0, poll_ref: bun.Async.KeepAlive = .{}, -globalObject: *JSC.JSGlobalObject, +globalObject: *jsc.JSGlobalObject, statements: PreparedStatementsMap, prepared_statement_id: u64 = 0, @@ -34,7 +34,7 @@ options_buf: []const u8 = "", authentication_state: AuthenticationState = .{ .pending = {} }, tls_ctx: ?*uws.SocketContext = null, -tls_config: JSC.API.ServerConfig.SSLConfig = .{}, +tls_config: jsc.API.ServerConfig.SSLConfig = .{}, tls_status: TLSStatus = .none, ssl_mode: SSLMode = .disable, @@ -136,18 +136,18 @@ pub fn resetConnectionTimeout(this: *PostgresSQLConnection) void { this.globalObject.bunVM().timer.insert(&this.timer); } -pub fn getQueries(_: *PostgresSQLConnection, thisValue: JSC.JSValue, globalObject: *JSC.JSGlobalObject) bun.JSError!JSC.JSValue { +pub fn getQueries(_: *PostgresSQLConnection, thisValue: jsc.JSValue, globalObject: *jsc.JSGlobalObject) bun.JSError!jsc.JSValue { if (js.queriesGetCached(thisValue)) |value| { return value; } - const array = try JSC.JSValue.createEmptyArray(globalObject, 0); + const array = try jsc.JSValue.createEmptyArray(globalObject, 0); js.queriesSetCached(thisValue, globalObject, array); return array; } -pub fn getOnConnect(_: *PostgresSQLConnection, thisValue: JSC.JSValue, _: *JSC.JSGlobalObject) JSC.JSValue { +pub fn getOnConnect(_: *PostgresSQLConnection, thisValue: jsc.JSValue, _: *jsc.JSGlobalObject) jsc.JSValue { if (js.onconnectGetCached(thisValue)) |value| { return value; } @@ -155,11 +155,11 @@ pub fn getOnConnect(_: *PostgresSQLConnection, thisValue: JSC.JSValue, _: *JSC.J return .js_undefined; } -pub fn setOnConnect(_: *PostgresSQLConnection, thisValue: JSC.JSValue, globalObject: *JSC.JSGlobalObject, value: JSC.JSValue) void { +pub fn setOnConnect(_: *PostgresSQLConnection, thisValue: jsc.JSValue, globalObject: *jsc.JSGlobalObject, value: jsc.JSValue) void { js.onconnectSetCached(thisValue, globalObject, value); } -pub fn getOnClose(_: *PostgresSQLConnection, thisValue: JSC.JSValue, _: *JSC.JSGlobalObject) JSC.JSValue { +pub fn getOnClose(_: *PostgresSQLConnection, thisValue: jsc.JSValue, _: *jsc.JSGlobalObject) jsc.JSValue { if (js.oncloseGetCached(thisValue)) |value| { return value; } @@ -167,7 +167,7 @@ pub fn getOnClose(_: *PostgresSQLConnection, thisValue: JSC.JSValue, _: *JSC.JSG return .js_undefined; } -pub fn setOnClose(_: *PostgresSQLConnection, thisValue: JSC.JSValue, globalObject: *JSC.JSGlobalObject, value: JSC.JSValue) void { +pub fn setOnClose(_: *PostgresSQLConnection, thisValue: jsc.JSValue, globalObject: *jsc.JSGlobalObject, value: jsc.JSValue) void { js.oncloseSetCached(thisValue, globalObject, value); } @@ -328,7 +328,7 @@ pub fn failWithJSValue(this: *PostgresSQLConnection, value: JSValue) void { ) catch |e| this.globalObject.reportActiveExceptionAsUnhandled(e); } -pub fn failFmt(this: *PostgresSQLConnection, comptime error_code: JSC.Error, comptime fmt: [:0]const u8, args: anytype) void { +pub fn failFmt(this: *PostgresSQLConnection, comptime error_code: jsc.Error, comptime fmt: [:0]const u8, args: anytype) void { this.failWithJSValue(error_code.fmt(this.globalObject, fmt, args)); } @@ -553,17 +553,17 @@ pub fn onData(this: *PostgresSQLConnection, data: []const u8) void { this.read_buffer.head = 0; } -pub fn constructor(globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!*PostgresSQLConnection { +pub fn constructor(globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!*PostgresSQLConnection { _ = callframe; return globalObject.throw("PostgresSQLConnection cannot be constructed directly", .{}); } comptime { - const jscall = JSC.toJSHostFn(call); + const jscall = jsc.toJSHostFn(call); @export(&jscall, .{ .name = "PostgresSQLConnection__createInstance" }); } -pub fn call(globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { +pub fn call(globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { var vm = globalObject.bunVM(); const arguments = callframe.arguments_old(15).slice(); const hostname_str = try arguments[0].toBunString(globalObject); @@ -587,13 +587,13 @@ pub fn call(globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JS const tls_object = arguments[6]; - var tls_config: JSC.API.ServerConfig.SSLConfig = .{}; + var tls_config: jsc.API.ServerConfig.SSLConfig = .{}; var tls_ctx: ?*uws.SocketContext = null; if (ssl_mode != .disable) { tls_config = if (tls_object.isBoolean() and tls_object.toBoolean()) .{} else if (tls_object.isObject()) - (JSC.API.ServerConfig.SSLConfig.fromJS(vm, globalObject, tls_object) catch return .zero) orelse .{} + (jsc.API.ServerConfig.SSLConfig.fromJS(vm, globalObject, tls_object) catch return .zero) orelse .{} else { return globalObject.throwInvalidArguments("tls must be a boolean or an object", .{}); }; @@ -810,18 +810,18 @@ pub fn ref(this: *@This()) void { this.ref_count += 1; } -pub fn doRef(this: *@This(), _: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!JSValue { +pub fn doRef(this: *@This(), _: *jsc.JSGlobalObject, _: *jsc.CallFrame) bun.JSError!JSValue { this.poll_ref.ref(this.globalObject.bunVM()); this.updateHasPendingActivity(); return .js_undefined; } -pub fn doUnref(this: *@This(), _: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!JSValue { +pub fn doUnref(this: *@This(), _: *jsc.JSGlobalObject, _: *jsc.CallFrame) bun.JSError!JSValue { this.poll_ref.unref(this.globalObject.bunVM()); this.updateHasPendingActivity(); return .js_undefined; } -pub fn doFlush(this: *PostgresSQLConnection, _: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!JSC.JSValue { +pub fn doFlush(this: *PostgresSQLConnection, _: *jsc.JSGlobalObject, _: *jsc.CallFrame) bun.JSError!jsc.JSValue { this.registerAutoFlusher(); return .js_undefined; } @@ -836,7 +836,7 @@ pub fn deref(this: *@This()) void { } } -pub fn doClose(this: *@This(), globalObject: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!JSValue { +pub fn doClose(this: *@This(), globalObject: *jsc.JSGlobalObject, _: *jsc.CallFrame) bun.JSError!JSValue { _ = globalObject; this.disconnect(); this.unregisterAutoFlusher(); @@ -872,7 +872,7 @@ pub fn deinit(this: *@This()) void { bun.default_allocator.destroy(this); } -fn refAndClose(this: *@This(), js_reason: ?JSC.JSValue) void { +fn refAndClose(this: *@This(), js_reason: ?jsc.JSValue) void { // refAndClose is always called when we wanna to disconnect or when we are closed if (!this.socket.isClosed()) { @@ -1265,7 +1265,7 @@ pub fn on(this: *PostgresSQLConnection, comptime MessageType: @Type(.enum_litera }; var stack_buf: [70]DataCell = undefined; - var cells: []DataCell = stack_buf[0..@min(statement.fields.len, JSC.JSObject.maxInlineCapacity())]; + var cells: []DataCell = stack_buf[0..@min(statement.fields.len, jsc.JSObject.maxInlineCapacity())]; var free_cells = false; defer { for (cells[0..putter.count]) |*cell| { @@ -1274,7 +1274,7 @@ pub fn on(this: *PostgresSQLConnection, comptime MessageType: @Type(.enum_litera if (free_cells) bun.default_allocator.free(cells); } - if (statement.fields.len >= JSC.JSObject.maxInlineCapacity()) { + if (statement.fields.len >= jsc.JSObject.maxInlineCapacity()) { cells = try bun.default_allocator.alloc(DataCell, statement.fields.len); free_cells = true; } @@ -1688,11 +1688,11 @@ pub fn updateRef(this: *PostgresSQLConnection) void { } } -pub fn getConnected(this: *PostgresSQLConnection, _: *JSC.JSGlobalObject) JSValue { +pub fn getConnected(this: *PostgresSQLConnection, _: *jsc.JSGlobalObject) JSValue { return JSValue.jsBoolean(this.status == Status.connected); } -pub fn consumeOnConnectCallback(this: *const PostgresSQLConnection, globalObject: *JSC.JSGlobalObject) ?JSC.JSValue { +pub fn consumeOnConnectCallback(this: *const PostgresSQLConnection, globalObject: *jsc.JSGlobalObject) ?jsc.JSValue { debug("consumeOnConnectCallback", .{}); const on_connect = js.onconnectGetCached(this.js_value) orelse return null; debug("consumeOnConnectCallback exists", .{}); @@ -1701,7 +1701,7 @@ pub fn consumeOnConnectCallback(this: *const PostgresSQLConnection, globalObject return on_connect; } -pub fn consumeOnCloseCallback(this: *const PostgresSQLConnection, globalObject: *JSC.JSGlobalObject) ?JSC.JSValue { +pub fn consumeOnCloseCallback(this: *const PostgresSQLConnection, globalObject: *jsc.JSGlobalObject) ?jsc.JSValue { debug("consumeOnCloseCallback", .{}); const on_close = js.oncloseGetCached(this.js_value) orelse return null; debug("consumeOnCloseCallback exists", .{}); @@ -1715,7 +1715,7 @@ const debug = bun.Output.scoped(.Postgres, false); const MAX_PIPELINE_SIZE = std.math.maxInt(u16); // about 64KB per connection -pub const js = JSC.Codegen.JSPostgresSQLConnection; +pub const js = jsc.Codegen.JSPostgresSQLConnection; pub const fromJS = js.fromJS; pub const fromJSDirect = js.fromJSDirect; pub const toJS = js.toJS; @@ -1742,9 +1742,9 @@ const bun = @import("bun"); const BoringSSL = bun.BoringSSL; const assert = bun.assert; -const JSC = bun.JSC; -const JSValue = JSC.JSValue; -const AutoFlusher = JSC.WebCore.AutoFlusher; +const jsc = bun.jsc; +const JSValue = jsc.JSValue; +const AutoFlusher = jsc.WebCore.AutoFlusher; const uws = bun.uws; const Socket = uws.AnySocket; diff --git a/src/sql/postgres/PostgresSQLContext.zig b/src/sql/postgres/PostgresSQLContext.zig index dfac396218..8982f17d6e 100644 --- a/src/sql/postgres/PostgresSQLContext.zig +++ b/src/sql/postgres/PostgresSQLContext.zig @@ -1,9 +1,9 @@ tcp: ?*uws.SocketContext = null, -onQueryResolveFn: JSC.Strong.Optional = .empty, -onQueryRejectFn: JSC.Strong.Optional = .empty, +onQueryResolveFn: jsc.Strong.Optional = .empty, +onQueryRejectFn: jsc.Strong.Optional = .empty, -pub fn init(globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { +pub fn init(globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { var ctx = &globalObject.bunVM().rareData().postgresql_context; ctx.onQueryResolveFn.set(globalObject, callframe.argument(0)); ctx.onQueryRejectFn.set(globalObject, callframe.argument(1)); @@ -12,10 +12,10 @@ pub fn init(globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JS } comptime { - const js_init = JSC.toJSHostFn(init); + const js_init = jsc.toJSHostFn(init); @export(&js_init, .{ .name = "PostgresSQLContext__init" }); } const bun = @import("bun"); -const JSC = bun.JSC; +const jsc = bun.jsc; const uws = bun.uws; diff --git a/src/sql/postgres/PostgresSQLQuery.zig b/src/sql/postgres/PostgresSQLQuery.zig index b8dc15b46b..79b3f67311 100644 --- a/src/sql/postgres/PostgresSQLQuery.zig +++ b/src/sql/postgres/PostgresSQLQuery.zig @@ -20,7 +20,7 @@ flags: packed struct(u8) { _padding: u1 = 0, } = .{}, -pub fn getTarget(this: *PostgresSQLQuery, globalObject: *JSC.JSGlobalObject, clean_target: bool) JSC.JSValue { +pub fn getTarget(this: *PostgresSQLQuery, globalObject: *jsc.JSGlobalObject, clean_target: bool) jsc.JSValue { const thisValue = this.thisValue.get(); if (thisValue == .zero) { return .zero; @@ -90,7 +90,7 @@ pub fn ref(this: *@This()) void { pub fn onWriteFail( this: *@This(), err: AnyPostgresError, - globalObject: *JSC.JSGlobalObject, + globalObject: *jsc.JSGlobalObject, queries_array: JSValue, ) void { this.status = .fail; @@ -101,7 +101,7 @@ pub fn onWriteFail( return; } - const vm = JSC.VirtualMachine.get(); + const vm = jsc.VirtualMachine.get(); const function = vm.rareData().postgresql_context.onQueryRejectFn.get().?; const event_loop = vm.eventLoop(); event_loop.runCallback(function, globalObject, thisValue, &.{ @@ -110,7 +110,7 @@ pub fn onWriteFail( queries_array, }); } -pub fn onJSError(this: *@This(), err: JSC.JSValue, globalObject: *JSC.JSGlobalObject) void { +pub fn onJSError(this: *@This(), err: jsc.JSValue, globalObject: *jsc.JSGlobalObject) void { this.status = .fail; this.ref(); defer this.deref(); @@ -122,7 +122,7 @@ pub fn onJSError(this: *@This(), err: JSC.JSValue, globalObject: *JSC.JSGlobalOb return; } - var vm = JSC.VirtualMachine.get(); + var vm = jsc.VirtualMachine.get(); const function = vm.rareData().postgresql_context.onQueryRejectFn.get().?; const event_loop = vm.eventLoop(); event_loop.runCallback(function, globalObject, thisValue, &.{ @@ -130,11 +130,11 @@ pub fn onJSError(this: *@This(), err: JSC.JSValue, globalObject: *JSC.JSGlobalOb err, }); } -pub fn onError(this: *@This(), err: PostgresSQLStatement.Error, globalObject: *JSC.JSGlobalObject) void { +pub fn onError(this: *@This(), err: PostgresSQLStatement.Error, globalObject: *jsc.JSGlobalObject) void { this.onJSError(err.toJS(globalObject), globalObject); } -pub fn allowGC(thisValue: JSC.JSValue, globalObject: *JSC.JSGlobalObject) void { +pub fn allowGC(thisValue: jsc.JSValue, globalObject: *jsc.JSGlobalObject) void { if (thisValue == .zero) { return; } @@ -145,13 +145,13 @@ pub fn allowGC(thisValue: JSC.JSValue, globalObject: *JSC.JSGlobalObject) void { js.targetSetCached(thisValue, globalObject, .zero); } -fn consumePendingValue(thisValue: JSC.JSValue, globalObject: *JSC.JSGlobalObject) ?JSValue { +fn consumePendingValue(thisValue: jsc.JSValue, globalObject: *jsc.JSGlobalObject) ?JSValue { const pending_value = js.pendingValueGetCached(thisValue) orelse return null; js.pendingValueSetCached(thisValue, globalObject, .zero); return pending_value; } -pub fn onResult(this: *@This(), command_tag_str: []const u8, globalObject: *JSC.JSGlobalObject, connection: JSC.JSValue, is_last: bool) void { +pub fn onResult(this: *@This(), command_tag_str: []const u8, globalObject: *jsc.JSGlobalObject, connection: jsc.JSValue, is_last: bool) void { this.ref(); defer this.deref(); @@ -170,7 +170,7 @@ pub fn onResult(this: *@This(), command_tag_str: []const u8, globalObject: *JSC. return; } - const vm = JSC.VirtualMachine.get(); + const vm = jsc.VirtualMachine.get(); const function = vm.rareData().postgresql_context.onQueryResolveFn.get().?; const event_loop = vm.eventLoop(); const tag = CommandTag.init(command_tag_str); @@ -185,7 +185,7 @@ pub fn onResult(this: *@This(), command_tag_str: []const u8, globalObject: *JSC. }); } -pub fn constructor(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!*PostgresSQLQuery { +pub fn constructor(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!*PostgresSQLQuery { _ = callframe; return globalThis.throw("PostgresSQLQuery cannot be constructed directly", .{}); } @@ -195,9 +195,9 @@ pub fn estimatedSize(this: *PostgresSQLQuery) usize { return @sizeOf(PostgresSQLQuery); } -pub fn call(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { +pub fn call(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const arguments = callframe.arguments_old(6).slice(); - var args = JSC.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), arguments); + var args = jsc.CallFrame.ArgumentsSlice.init(globalThis.bunVM(), arguments); defer args.deinit(); const query = args.nextEat() orelse { return globalThis.throw("query must be a string", .{}); @@ -256,22 +256,22 @@ pub fn call(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSEr return this_value; } -pub fn push(this: *PostgresSQLQuery, globalThis: *JSC.JSGlobalObject, value: JSValue) void { +pub fn push(this: *PostgresSQLQuery, globalThis: *jsc.JSGlobalObject, value: JSValue) void { var pending_value = this.pending_value.get() orelse return; pending_value.push(globalThis, value); } -pub fn doDone(this: *@This(), globalObject: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!JSValue { +pub fn doDone(this: *@This(), globalObject: *jsc.JSGlobalObject, _: *jsc.CallFrame) bun.JSError!JSValue { _ = globalObject; this.flags.is_done = true; return .js_undefined; } -pub fn setPendingValue(this: *PostgresSQLQuery, globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { +pub fn setPendingValue(this: *PostgresSQLQuery, globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { const result = callframe.argument(0); js.pendingValueSetCached(this.thisValue.get(), globalObject, result); return .js_undefined; } -pub fn setMode(this: *PostgresSQLQuery, globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { +pub fn setMode(this: *PostgresSQLQuery, globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { const js_mode = callframe.argument(0); if (js_mode.isEmptyOrUndefinedOrNull() or !js_mode.isNumber()) { return globalObject.throwInvalidArgumentType("setMode", "mode", "Number"); @@ -284,7 +284,7 @@ pub fn setMode(this: *PostgresSQLQuery, globalObject: *JSC.JSGlobalObject, callf return .js_undefined; } -pub fn doRun(this: *PostgresSQLQuery, globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { +pub fn doRun(this: *PostgresSQLQuery, globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { var arguments_ = callframe.arguments_old(2); const arguments = arguments_.slice(); const connection: *PostgresSQLConnection = arguments[0].as(PostgresSQLConnection) orelse { @@ -465,7 +465,7 @@ pub fn doRun(this: *PostgresSQLQuery, globalObject: *JSC.JSGlobalObject, callfra return .js_undefined; } -pub fn doCancel(this: *PostgresSQLQuery, globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { +pub fn doCancel(this: *PostgresSQLQuery, globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { _ = callframe; _ = globalObject; _ = this; @@ -474,13 +474,13 @@ pub fn doCancel(this: *PostgresSQLQuery, globalObject: *JSC.JSGlobalObject, call } comptime { - const jscall = JSC.toJSHostFn(call); + const jscall = jsc.toJSHostFn(call); @export(&jscall, .{ .name = "PostgresSQLQuery__createInstance" }); } const debug = bun.Output.scoped(.Postgres, false); -pub const js = JSC.Codegen.JSPostgresSQLQuery; +pub const js = jsc.Codegen.JSPostgresSQLQuery; pub const fromJS = js.fromJS; pub const fromJSDirect = js.fromJSDirect; pub const toJS = js.toJS; @@ -498,7 +498,7 @@ const PostgresSQLQueryResultMode = @import("./PostgresSQLQueryResultMode.zig").P const AnyPostgresError = @import("./AnyPostgresError.zig").AnyPostgresError; const postgresErrorToJS = @import("./AnyPostgresError.zig").postgresErrorToJS; -const JSC = bun.JSC; -const JSGlobalObject = JSC.JSGlobalObject; -const JSRef = JSC.JSRef; -const JSValue = JSC.JSValue; +const jsc = bun.jsc; +const JSGlobalObject = jsc.JSGlobalObject; +const JSRef = jsc.JSRef; +const JSValue = jsc.JSValue; diff --git a/src/sql/postgres/PostgresSQLStatement.zig b/src/sql/postgres/PostgresSQLStatement.zig index e8387032b0..c238a19676 100644 --- a/src/sql/postgres/PostgresSQLStatement.zig +++ b/src/sql/postgres/PostgresSQLStatement.zig @@ -21,7 +21,7 @@ pub const Error = union(enum) { } } - pub fn toJS(this: *const @This(), globalObject: *JSC.JSGlobalObject) JSValue { + pub fn toJS(this: *const @This(), globalObject: *jsc.JSGlobalObject) JSValue { return switch (this.*) { .protocol => |err| err.toJS(globalObject), .postgres_error => |err| postgresErrorToJS(globalObject, null, err), @@ -117,14 +117,14 @@ pub fn deinit(this: *PostgresSQLStatement) void { bun.default_allocator.destroy(this); } -pub fn structure(this: *PostgresSQLStatement, owner: JSValue, globalObject: *JSC.JSGlobalObject) PostgresCachedStructure { +pub fn structure(this: *PostgresSQLStatement, owner: JSValue, globalObject: *jsc.JSGlobalObject) PostgresCachedStructure { if (this.cached_structure.has()) { return this.cached_structure; } this.checkForDuplicateFields(); // lets avoid most allocations - var stack_ids: [70]JSC.JSObject.ExternColumnIdentifier = undefined; + var stack_ids: [70]jsc.JSObject.ExternColumnIdentifier = undefined; // lets de duplicate the fields early var nonDuplicatedCount = this.fields.len; for (this.fields) |*field| { @@ -132,13 +132,13 @@ pub fn structure(this: *PostgresSQLStatement, owner: JSValue, globalObject: *JSC nonDuplicatedCount -= 1; } } - const ids = if (nonDuplicatedCount <= JSC.JSObject.maxInlineCapacity()) stack_ids[0..nonDuplicatedCount] else bun.default_allocator.alloc(JSC.JSObject.ExternColumnIdentifier, nonDuplicatedCount) catch bun.outOfMemory(); + const ids = if (nonDuplicatedCount <= jsc.JSObject.maxInlineCapacity()) stack_ids[0..nonDuplicatedCount] else bun.default_allocator.alloc(jsc.JSObject.ExternColumnIdentifier, nonDuplicatedCount) catch bun.outOfMemory(); var i: usize = 0; for (this.fields) |*field| { if (field.name_or_index == .duplicate) continue; - var id: *JSC.JSObject.ExternColumnIdentifier = &ids[i]; + var id: *jsc.JSObject.ExternColumnIdentifier = &ids[i]; switch (field.name_or_index) { .name => |name| { id.value.name = String.createAtomIfPossible(name.slice()); @@ -156,10 +156,10 @@ pub fn structure(this: *PostgresSQLStatement, owner: JSValue, globalObject: *JSC i += 1; } - if (nonDuplicatedCount > JSC.JSObject.maxInlineCapacity()) { + if (nonDuplicatedCount > jsc.JSObject.maxInlineCapacity()) { this.cached_structure.set(globalObject, null, ids); } else { - this.cached_structure.set(globalObject, JSC.JSObject.createStructure( + this.cached_structure.set(globalObject, jsc.JSObject.createStructure( globalObject, owner, @truncate(ids.len), @@ -187,5 +187,5 @@ const int4 = types.int4; const bun = @import("bun"); const String = bun.String; -const JSC = bun.JSC; -const JSValue = JSC.JSValue; +const jsc = bun.jsc; +const JSValue = jsc.JSValue; diff --git a/src/sql/postgres/QueryBindingIterator.zig b/src/sql/postgres/QueryBindingIterator.zig index ec7777cc66..24b6ccc36c 100644 --- a/src/sql/postgres/QueryBindingIterator.zig +++ b/src/sql/postgres/QueryBindingIterator.zig @@ -1,10 +1,10 @@ pub const QueryBindingIterator = union(enum) { - array: JSC.JSArrayIterator, + array: jsc.JSArrayIterator, objects: ObjectIterator, - pub fn init(array: JSValue, columns: JSValue, globalObject: *JSC.JSGlobalObject) bun.JSError!QueryBindingIterator { + pub fn init(array: JSValue, columns: JSValue, globalObject: *jsc.JSGlobalObject) bun.JSError!QueryBindingIterator { if (columns.isEmptyOrUndefinedOrNull()) { - return .{ .array = try JSC.JSArrayIterator.init(array, globalObject) }; + return .{ .array = try jsc.JSArrayIterator.init(array, globalObject) }; } return .{ @@ -18,7 +18,7 @@ pub const QueryBindingIterator = union(enum) { }; } - pub fn next(this: *QueryBindingIterator) bun.JSError!?JSC.JSValue { + pub fn next(this: *QueryBindingIterator) bun.JSError!?jsc.JSValue { return switch (this.*) { .array => |*iter| iter.next(), .objects => |*iter| iter.next(), @@ -60,5 +60,5 @@ pub const QueryBindingIterator = union(enum) { const ObjectIterator = @import("./ObjectIterator.zig"); const bun = @import("bun"); -const JSC = bun.JSC; -const JSValue = JSC.JSValue; +const jsc = bun.jsc; +const JSValue = jsc.JSValue; diff --git a/src/sql/postgres/SASL.zig b/src/sql/postgres/SASL.zig index e6d24c2f28..7ae2bbd0f1 100644 --- a/src/sql/postgres/SASL.zig +++ b/src/sql/postgres/SASL.zig @@ -65,7 +65,7 @@ pub fn clientKey(this: *const SASL) [32]u8 { pub fn clientKeySignature(_: *const SASL, client_key: []const u8, auth_string: []const u8) [32]u8 { var sha_digest = std.mem.zeroes(bun.sha.SHA256.Digest); - bun.sha.SHA256.hash(client_key, &sha_digest, JSC.VirtualMachine.get().rareData().boringEngine()); + bun.sha.SHA256.hash(client_key, &sha_digest, jsc.VirtualMachine.get().rareData().boringEngine()); return hmac(&sha_digest, auth_string).?; } @@ -89,6 +89,6 @@ const PostgresSQLConnection = @import("./PostgresSQLConnection.zig"); const std = @import("std"); const bun = @import("bun"); -const JSC = bun.JSC; const assert = bun.assert; -const Crypto = JSC.API.Bun.Crypto; +const jsc = bun.jsc; +const Crypto = jsc.API.Bun.Crypto; diff --git a/src/sql/postgres/Signature.zig b/src/sql/postgres/Signature.zig index b931bf9b42..53e74a3677 100644 --- a/src/sql/postgres/Signature.zig +++ b/src/sql/postgres/Signature.zig @@ -36,7 +36,7 @@ pub fn hash(this: *const Signature) u64 { return hasher.final(); } -pub fn generate(globalObject: *JSC.JSGlobalObject, query: []const u8, array_value: JSValue, columns: JSValue, prepared_statement_id: u64, unnamed: bool) !Signature { +pub fn generate(globalObject: *jsc.JSGlobalObject, query: []const u8, array_value: JSValue, columns: JSValue, prepared_statement_id: u64, unnamed: bool) !Signature { var fields = std.ArrayList(int4).init(bun.default_allocator); var name = try std.ArrayList(u8).initCapacity(bun.default_allocator, query.len); @@ -108,5 +108,5 @@ const QueryBindingIterator = @import("./QueryBindingIterator.zig").QueryBindingI const types = @import("./PostgresTypes.zig"); const int4 = types.int4; -const JSC = bun.JSC; -const JSValue = JSC.JSValue; +const jsc = bun.jsc; +const JSValue = jsc.JSValue; diff --git a/src/sql/postgres/protocol/ErrorResponse.zig b/src/sql/postgres/protocol/ErrorResponse.zig index c3c207b6e9..bc2bde4e47 100644 --- a/src/sql/postgres/protocol/ErrorResponse.zig +++ b/src/sql/postgres/protocol/ErrorResponse.zig @@ -29,7 +29,7 @@ pub fn decodeInternal(this: *@This(), comptime Container: type, reader: NewReade pub const decode = DecoderWrap(ErrorResponse, decodeInternal).decode; -pub fn toJS(this: ErrorResponse, globalObject: *JSC.JSGlobalObject) JSValue { +pub fn toJS(this: ErrorResponse, globalObject: *jsc.JSGlobalObject) JSValue { var b = bun.StringBuilder{}; defer b.deinit(bun.default_allocator); @@ -119,7 +119,7 @@ pub fn toJS(this: ErrorResponse, globalObject: *JSC.JSGlobalObject) JSValue { .{ "table", table, void }, .{ "where", where, void }, }; - const error_code: JSC.Error = + const error_code: jsc.Error = // https://www.postgresql.org/docs/8.1/errcodes-appendix.html if (code.eqlComptime("42601")) .POSTGRES_SYNTAX_ERROR @@ -132,14 +132,14 @@ pub fn toJS(this: ErrorResponse, globalObject: *JSC.JSGlobalObject) JSValue { const value = brk: { if (field.@"2" == i32) { if (field.@"1".toInt32()) |val| { - break :brk JSC.JSValue.jsNumberFromInt32(val); + break :brk jsc.JSValue.jsNumberFromInt32(val); } } break :brk field.@"1".toJS(globalObject); }; - err.put(globalObject, JSC.ZigString.static(field.@"0"), value); + err.put(globalObject, jsc.ZigString.static(field.@"0"), value); } } @@ -154,5 +154,5 @@ const NewReader = @import("./NewReader.zig").NewReader; const bun = @import("bun"); const String = bun.String; -const JSC = bun.JSC; -const JSValue = JSC.JSValue; +const jsc = bun.jsc; +const JSValue = jsc.JSValue; diff --git a/src/sql/postgres/protocol/NoticeResponse.zig b/src/sql/postgres/protocol/NoticeResponse.zig index d8ee47db08..315e09854a 100644 --- a/src/sql/postgres/protocol/NoticeResponse.zig +++ b/src/sql/postgres/protocol/NoticeResponse.zig @@ -19,7 +19,7 @@ pub fn decodeInternal(this: *@This(), comptime Container: type, reader: NewReade } pub const decode = DecoderWrap(NoticeResponse, decodeInternal).decode; -pub fn toJS(this: NoticeResponse, globalObject: *JSC.JSGlobalObject) JSValue { +pub fn toJS(this: NoticeResponse, globalObject: *jsc.JSGlobalObject) JSValue { var b = bun.StringBuilder{}; defer b.deinit(bun.default_allocator); @@ -39,7 +39,7 @@ pub fn toJS(this: NoticeResponse, globalObject: *JSC.JSGlobalObject) JSValue { _ = b.append("\n"); } - return JSC.ZigString.init(b.allocatedSlice()[0..b.len]).toJS(globalObject); + return jsc.ZigString.init(b.allocatedSlice()[0..b.len]).toJS(globalObject); } const bun = @import("bun"); @@ -48,5 +48,5 @@ const DecoderWrap = @import("./DecoderWrap.zig").DecoderWrap; const FieldMessage = @import("./FieldMessage.zig").FieldMessage; const NewReader = @import("./NewReader.zig").NewReader; -const JSC = bun.JSC; -const JSValue = JSC.JSValue; +const jsc = bun.jsc; +const JSValue = jsc.JSValue; diff --git a/src/sql/postgres/types/PostgresString.zig b/src/sql/postgres/types/PostgresString.zig index 9ca4ce5ae7..4ca1c822ec 100644 --- a/src/sql/postgres/types/PostgresString.zig +++ b/src/sql/postgres/types/PostgresString.zig @@ -2,7 +2,7 @@ pub const to = 25; pub const from = [_]short{1002}; pub fn toJSWithType( - globalThis: *JSC.JSGlobalObject, + globalThis: *jsc.JSGlobalObject, comptime Type: type, value: Type, ) AnyPostgresError!JSValue { @@ -31,7 +31,7 @@ pub fn toJSWithType( } pub fn toJS( - globalThis: *JSC.JSGlobalObject, + globalThis: *jsc.JSGlobalObject, value: anytype, ) !JSValue { var str = try toJSWithType(globalThis, @TypeOf(value), value); @@ -46,5 +46,5 @@ const Data = @import("../Data.zig").Data; const int_types = @import("./int_types.zig"); const short = int_types.short; -const JSC = bun.JSC; -const JSValue = JSC.JSValue; +const jsc = bun.jsc; +const JSValue = jsc.JSValue; diff --git a/src/sql/postgres/types/Tag.zig b/src/sql/postgres/types/Tag.zig index b61e91053b..086a1c168d 100644 --- a/src/sql/postgres/types/Tag.zig +++ b/src/sql/postgres/types/Tag.zig @@ -265,7 +265,7 @@ pub const Tag = enum(short) { fn toJSWithType( tag: Tag, - globalObject: *JSC.JSGlobalObject, + globalObject: *jsc.JSGlobalObject, comptime Type: type, value: Type, ) AnyPostgresError!JSValue { @@ -310,13 +310,13 @@ pub const Tag = enum(short) { pub fn toJS( tag: Tag, - globalObject: *JSC.JSGlobalObject, + globalObject: *jsc.JSGlobalObject, value: anytype, ) AnyPostgresError!JSValue { return toJSWithType(tag, globalObject, @TypeOf(value), value); } - pub fn fromJS(globalObject: *JSC.JSGlobalObject, value: JSValue) bun.JSError!Tag { + pub fn fromJS(globalObject: *jsc.JSGlobalObject, value: JSValue) bun.JSError!Tag { if (value.isEmptyOrUndefinedOrNull()) { return Tag.numeric; } @@ -405,5 +405,5 @@ const AnyPostgresError = @import("../AnyPostgresError.zig").AnyPostgresError; const int_types = @import("./int_types.zig"); const short = int_types.short; -const JSC = bun.JSC; -const JSValue = JSC.JSValue; +const jsc = bun.jsc; +const JSValue = jsc.JSValue; diff --git a/src/sql/postgres/types/bool.zig b/src/sql/postgres/types/bool.zig index 028b8427d5..682f53ada3 100644 --- a/src/sql/postgres/types/bool.zig +++ b/src/sql/postgres/types/bool.zig @@ -2,7 +2,7 @@ pub const to = 16; pub const from = [_]short{16}; pub fn toJS( - _: *JSC.JSGlobalObject, + _: *jsc.JSGlobalObject, value: bool, ) AnyPostgresError!JSValue { return JSValue.jsBoolean(value); @@ -14,5 +14,5 @@ const AnyPostgresError = @import("../AnyPostgresError.zig").AnyPostgresError; const int_types = @import("./int_types.zig"); const short = int_types.short; -const JSC = bun.JSC; -const JSValue = JSC.JSValue; +const jsc = bun.jsc; +const JSValue = jsc.JSValue; diff --git a/src/sql/postgres/types/bytea.zig b/src/sql/postgres/types/bytea.zig index 96ae72fd4c..42e453a2b2 100644 --- a/src/sql/postgres/types/bytea.zig +++ b/src/sql/postgres/types/bytea.zig @@ -2,7 +2,7 @@ pub const to = 17; pub const from = [_]short{17}; pub fn toJS( - globalObject: *JSC.JSGlobalObject, + globalObject: *jsc.JSGlobalObject, value: *Data, ) AnyPostgresError!JSValue { defer value.deinit(); @@ -19,5 +19,5 @@ const Data = @import("../Data.zig").Data; const int_types = @import("./int_types.zig"); const short = int_types.short; -const JSC = bun.JSC; -const JSValue = JSC.JSValue; +const jsc = bun.jsc; +const JSValue = jsc.JSValue; diff --git a/src/sql/postgres/types/date.zig b/src/sql/postgres/types/date.zig index ba8b8d37c7..95be95e48d 100644 --- a/src/sql/postgres/types/date.zig +++ b/src/sql/postgres/types/date.zig @@ -11,7 +11,7 @@ pub fn fromBinary(bytes: []const u8) f64 { return (double_microseconds / std.time.us_per_ms) + POSTGRES_EPOCH_DATE; } -pub fn fromJS(globalObject: *JSC.JSGlobalObject, value: JSValue) bun.JSError!i64 { +pub fn fromJS(globalObject: *jsc.JSGlobalObject, value: JSValue) bun.JSError!i64 { const double_value = if (value.isDate()) value.getUnixTimestamp() else if (value.isNumber()) @@ -27,7 +27,7 @@ pub fn fromJS(globalObject: *JSC.JSGlobalObject, value: JSValue) bun.JSError!i64 } pub fn toJS( - globalObject: *JSC.JSGlobalObject, + globalObject: *jsc.JSGlobalObject, value: anytype, ) JSValue { switch (@TypeOf(value)) { @@ -51,5 +51,5 @@ const Data = @import("../Data.zig").Data; const int_types = @import("./int_types.zig"); const short = int_types.short; -const JSC = bun.JSC; -const JSValue = JSC.JSValue; +const jsc = bun.jsc; +const JSValue = jsc.JSValue; diff --git a/src/sql/postgres/types/json.zig b/src/sql/postgres/types/json.zig index 2c663f67ee..14aad5fbe5 100644 --- a/src/sql/postgres/types/json.zig +++ b/src/sql/postgres/types/json.zig @@ -2,7 +2,7 @@ pub const to = 114; pub const from = [_]short{ 114, 3802 }; pub fn toJS( - globalObject: *JSC.JSGlobalObject, + globalObject: *jsc.JSGlobalObject, value: *Data, ) AnyPostgresError!JSValue { defer value.deinit(); @@ -23,5 +23,5 @@ const Data = @import("../Data.zig").Data; const int_types = @import("./int_types.zig"); const short = int_types.short; -const JSC = bun.JSC; -const JSValue = JSC.JSValue; +const jsc = bun.jsc; +const JSValue = jsc.JSValue; diff --git a/src/sql/postgres/types/numeric.zig b/src/sql/postgres/types/numeric.zig index a773f43eab..b9717df4e3 100644 --- a/src/sql/postgres/types/numeric.zig +++ b/src/sql/postgres/types/numeric.zig @@ -2,7 +2,7 @@ pub const to = 0; pub const from = [_]short{ 21, 23, 26, 700, 701 }; pub fn toJS( - _: *JSC.JSGlobalObject, + _: *jsc.JSGlobalObject, value: anytype, ) AnyPostgresError!JSValue { return JSValue.jsNumber(value); @@ -14,5 +14,5 @@ const AnyPostgresError = @import("../AnyPostgresError.zig").AnyPostgresError; const int_types = @import("./int_types.zig"); const short = int_types.short; -const JSC = bun.JSC; -const JSValue = JSC.JSValue; +const jsc = bun.jsc; +const JSValue = jsc.JSValue; diff --git a/src/string.zig b/src/string.zig index 16fab4c729..ac7d0b0eb3 100644 --- a/src/string.zig +++ b/src/string.zig @@ -1,3 +1,5 @@ +pub const immutable = @import("./string/immutable.zig"); + pub const HashedString = @import("./string/HashedString.zig"); pub const MutableString = @import("./string/MutableString.zig"); pub const PathString = @import("./string/PathString.zig").PathString; @@ -65,9 +67,9 @@ pub const String = extern struct { if (this.tag == .WTFStringImpl) this.value.WTFStringImpl.ensureHash(); } - extern fn BunString__transferToJS(this: *String, globalThis: *JSC.JSGlobalObject) JSC.JSValue; - pub fn transferToJS(this: *String, globalThis: *JSC.JSGlobalObject) JSC.JSValue { - JSC.markBinding(@src()); + extern fn BunString__transferToJS(this: *String, globalThis: *jsc.JSGlobalObject) jsc.JSValue; + pub fn transferToJS(this: *String, globalThis: *jsc.JSGlobalObject) jsc.JSValue { + jsc.markBinding(@src()); return BunString__transferToJS(this, globalThis); } @@ -157,7 +159,7 @@ pub const String = extern struct { } pub fn cloneLatin1(bytes: []const u8) String { - JSC.markBinding(@src()); + jsc.markBinding(@src()); if (bytes.len == 0) return String.empty; return validateRefCount(bun.cpp.BunString__fromLatin1(bytes.ptr, bytes.len)); } @@ -175,7 +177,7 @@ pub const String = extern struct { } pub fn cloneUTF8(bytes: []const u8) String { - return JSC.WebCore.encoding.toBunStringComptime(bytes, .utf8); + return jsc.WebCore.encoding.toBunStringComptime(bytes, .utf8); } pub fn cloneUTF16(bytes: []const u16) String { @@ -336,17 +338,17 @@ pub const String = extern struct { }; } - pub fn toErrorInstance(this: *const String, globalObject: *JSC.JSGlobalObject) JSC.JSValue { + pub fn toErrorInstance(this: *const String, globalObject: *jsc.JSGlobalObject) jsc.JSValue { defer this.deref(); return JSC__createError(globalObject, this); } - pub fn toTypeErrorInstance(this: *const String, globalObject: *JSC.JSGlobalObject) JSC.JSValue { + pub fn toTypeErrorInstance(this: *const String, globalObject: *jsc.JSGlobalObject) jsc.JSValue { defer this.deref(); return JSC__createTypeError(globalObject, this); } - pub fn toRangeErrorInstance(this: *const String, globalObject: *JSC.JSGlobalObject) JSC.JSValue { + pub fn toRangeErrorInstance(this: *const String, globalObject: *jsc.JSGlobalObject) jsc.JSValue { defer this.deref(); return JSC__createRangeError(globalObject, this); } @@ -395,7 +397,7 @@ pub const String = extern struct { ) String { comptime if (@typeInfo(Ctx) != .pointer) @compileError("context must be a pointer"); bun.assert(bytes.len > 0); - JSC.markBinding(@src()); + jsc.markBinding(@src()); if (bytes.len > max_length()) { if (callback) |cb| { cb(ctx, @ptrCast(@constCast(bytes.ptr)), @truncate(bytes.len)); @@ -410,7 +412,7 @@ pub const String = extern struct { /// So this really only makes sense when you need to dynamically allocate a /// string that will never be freed. pub fn createStaticExternal(bytes: []const u8, isLatin1: bool) String { - JSC.markBinding(@src()); + jsc.markBinding(@src()); bun.assert(bytes.len > 0); return BunString__createStaticExternal(bytes.ptr, bytes.len, isLatin1); } @@ -428,12 +430,12 @@ pub const String = extern struct { /// Max WTFStringImpl length. /// **Not** in bytes. In characters. pub inline fn max_length() usize { - return JSC.VirtualMachine.string_allocation_limit; + return jsc.VirtualMachine.string_allocation_limit; } /// If the allocation fails, this will free the bytes and return a dead string. pub fn createExternalGloballyAllocated(comptime kind: WTFEncoding, bytes: []kind.Byte()) String { - JSC.markBinding(@src()); + jsc.markBinding(@src()); bun.assert(bytes.len > 0); if (bytes.len > max_length()) { @@ -494,8 +496,8 @@ pub const String = extern struct { try self.toZigString().format(fmt, opts, writer); } - pub fn fromJS(value: bun.JSC.JSValue, globalObject: *JSC.JSGlobalObject) bun.JSError!String { - var scope: JSC.ExceptionValidationScope = undefined; + pub fn fromJS(value: bun.jsc.JSValue, globalObject: *jsc.JSGlobalObject) bun.JSError!String { + var scope: jsc.ExceptionValidationScope = undefined; scope.init(globalObject, @src()); defer scope.deinit(); var out: String = String.dead; @@ -513,27 +515,27 @@ pub const String = extern struct { return if (ok) out else error.JSError; } - pub fn toJS(this: *const String, globalObject: *bun.JSC.JSGlobalObject) JSC.JSValue { - JSC.markBinding(@src()); + pub fn toJS(this: *const String, globalObject: *bun.jsc.JSGlobalObject) jsc.JSValue { + jsc.markBinding(@src()); return BunString__toJS(globalObject, this); } - pub fn toJSDOMURL(this: *String, globalObject: *bun.JSC.JSGlobalObject) JSC.JSValue { - JSC.markBinding(@src()); + pub fn toJSDOMURL(this: *String, globalObject: *bun.jsc.JSGlobalObject) jsc.JSValue { + jsc.markBinding(@src()); return BunString__toJSDOMURL(globalObject, this); } extern fn BunString__createArray( - globalObject: *bun.JSC.JSGlobalObject, + globalObject: *bun.jsc.JSGlobalObject, ptr: [*]const String, len: usize, - ) JSC.JSValue; + ) jsc.JSValue; /// calls toJS on all elements of `array`. - pub fn toJSArray(globalObject: *bun.JSC.JSGlobalObject, array: []const bun.String) bun.JSError!JSC.JSValue { - JSC.markBinding(@src()); + pub fn toJSArray(globalObject: *bun.jsc.JSGlobalObject, array: []const bun.String) bun.JSError!jsc.JSValue { + jsc.markBinding(@src()); return bun.jsc.fromJSHostCall(globalObject, @src(), BunString__createArray, .{ globalObject, array.ptr, array.len }); } @@ -549,7 +551,7 @@ pub const String = extern struct { } pub fn toWTF(this: *String) void { - JSC.markBinding(@src()); + jsc.markBinding(@src()); bun.cpp.BunString__toWTFString(this); } @@ -647,23 +649,23 @@ pub const String = extern struct { return false; } - pub fn toJSByParseJSON(self: *String, globalObject: *JSC.JSGlobalObject) bun.JSError!JSC.JSValue { + pub fn toJSByParseJSON(self: *String, globalObject: *jsc.JSGlobalObject) bun.JSError!jsc.JSValue { return bun.cpp.BunString__toJSON(globalObject, self); } - pub fn encodeInto(self: String, out: []u8, comptime enc: JSC.Node.Encoding) !usize { + pub fn encodeInto(self: String, out: []u8, comptime enc: jsc.Node.Encoding) !usize { if (self.isUTF16()) { - return JSC.WebCore.encoding.encodeIntoFrom16(self.utf16(), out, enc, true); + return jsc.WebCore.encoding.encodeIntoFrom16(self.utf16(), out, enc, true); } if (self.isUTF8()) { @panic("TODO"); } - return JSC.WebCore.encoding.encodeIntoFrom8(self.latin1(), out, enc); + return jsc.WebCore.encoding.encodeIntoFrom8(self.latin1(), out, enc); } - pub fn encode(self: String, enc: JSC.Node.Encoding) []u8 { + pub fn encode(self: String, enc: jsc.Node.Encoding) []u8 { return self.toZigString().encodeWithAllocator(bun.default_allocator, enc); } @@ -812,25 +814,25 @@ pub const String = extern struct { return this.toSlice(allocator); } - extern fn BunString__toJS(globalObject: *JSC.JSGlobalObject, in: *const String) JSC.JSValue; - extern fn BunString__toJSWithLength(globalObject: *JSC.JSGlobalObject, in: *const String, usize) JSC.JSValue; - extern fn BunString__toJSDOMURL(globalObject: *JSC.JSGlobalObject, in: *String) JSC.JSValue; + extern fn BunString__toJS(globalObject: *jsc.JSGlobalObject, in: *const String) jsc.JSValue; + extern fn BunString__toJSWithLength(globalObject: *jsc.JSGlobalObject, in: *const String, usize) jsc.JSValue; + extern fn BunString__toJSDOMURL(globalObject: *jsc.JSGlobalObject, in: *String) jsc.JSValue; - pub fn createUTF8ForJS(globalObject: *JSC.JSGlobalObject, utf8_slice: []const u8) bun.JSError!JSC.JSValue { - JSC.markBinding(@src()); + pub fn createUTF8ForJS(globalObject: *jsc.JSGlobalObject, utf8_slice: []const u8) bun.JSError!jsc.JSValue { + jsc.markBinding(@src()); return bun.cpp.BunString__createUTF8ForJS(globalObject, utf8_slice.ptr, utf8_slice.len); } - pub fn createFormatForJS(globalObject: *JSC.JSGlobalObject, comptime fmt: [:0]const u8, args: anytype) bun.JSError!JSC.JSValue { - JSC.markBinding(@src()); + pub fn createFormatForJS(globalObject: *jsc.JSGlobalObject, comptime fmt: [:0]const u8, args: anytype) bun.JSError!jsc.JSValue { + jsc.markBinding(@src()); var builder = std.ArrayList(u8).init(bun.default_allocator); defer builder.deinit(); builder.writer().print(fmt, args) catch bun.outOfMemory(); return bun.cpp.BunString__createUTF8ForJS(globalObject, builder.items.ptr, builder.items.len); } - pub fn parseDate(this: *String, globalObject: *JSC.JSGlobalObject) bun.JSError!f64 { - JSC.markBinding(@src()); + pub fn parseDate(this: *String, globalObject: *jsc.JSGlobalObject) bun.JSError!f64 { + jsc.markBinding(@src()); return bun.cpp.Bun__parseDate(globalObject, this); } @@ -1029,7 +1031,7 @@ pub const String = extern struct { /// Does not increment the reference count unless the StringImpl is cloned. pub fn toThreadSafe(this: *String) void { - JSC.markBinding(@src()); + jsc.markBinding(@src()); if (this.tag == .WTFStringImpl) { bun.cpp.BunString__toThreadSafe(this); @@ -1040,7 +1042,7 @@ pub const String = extern struct { /// /// This will ref even if it doesn't change. pub fn toThreadSafeEnsureRef(this: *String) void { - JSC.markBinding(@src()); + jsc.markBinding(@src()); if (this.tag == .WTFStringImpl) { const orig = this.value.WTFStringImpl; @@ -1059,26 +1061,26 @@ pub const String = extern struct { return this.toZigString().eql(other.toZigString()); } - extern fn JSC__createError(*JSC.JSGlobalObject, str: *const String) JSC.JSValue; - extern fn JSC__createTypeError(*JSC.JSGlobalObject, str: *const String) JSC.JSValue; - extern fn JSC__createRangeError(*JSC.JSGlobalObject, str: *const String) JSC.JSValue; + extern fn JSC__createError(*jsc.JSGlobalObject, str: *const String) jsc.JSValue; + extern fn JSC__createTypeError(*jsc.JSGlobalObject, str: *const String) jsc.JSValue; + extern fn JSC__createRangeError(*jsc.JSGlobalObject, str: *const String) jsc.JSValue; - pub fn jsGetStringWidth(globalObject: *JSC.JSGlobalObject, callFrame: *JSC.CallFrame) bun.JSError!JSC.JSValue { + pub fn jsGetStringWidth(globalObject: *jsc.JSGlobalObject, callFrame: *jsc.CallFrame) bun.JSError!jsc.JSValue { const args = callFrame.arguments_old(1).slice(); if (args.len == 0 or !args.ptr[0].isString()) { - return JSC.jsNumber(@as(i32, 0)); + return jsc.jsNumber(@as(i32, 0)); } const str = try args[0].toBunString(globalObject); defer str.deref(); if (str.isEmpty()) { - return JSC.jsNumber(@as(i32, 0)); + return jsc.jsNumber(@as(i32, 0)); } const width = str.visibleWidth(false); - return JSC.jsNumber(width); + return jsc.jsNumber(width); } /// Reports owned allocation size, not the actual size of the string. @@ -1102,7 +1104,7 @@ pub const SliceWithUnderlyingString = struct { did_report_extra_memory_debug: bun.DebugOnly(bool) = if (bun.Environment.isDebug) false, - pub inline fn reportExtraMemory(this: *SliceWithUnderlyingString, vm: *JSC.VM) void { + pub inline fn reportExtraMemory(this: *SliceWithUnderlyingString, vm: *jsc.VM) void { if (comptime bun.Environment.isDebug) { bun.assert(!this.did_report_extra_memory_debug); this.did_report_extra_memory_debug = true; @@ -1130,7 +1132,7 @@ pub const SliceWithUnderlyingString = struct { /// Transcode a byte array to an encoded String, avoiding unnecessary copies. /// /// owned_input_bytes ownership is transferred to this function - pub fn transcodeFromOwnedSlice(owned_input_bytes: []u8, encoding: JSC.Node.Encoding) SliceWithUnderlyingString { + pub fn transcodeFromOwnedSlice(owned_input_bytes: []u8, encoding: jsc.Node.Encoding) SliceWithUnderlyingString { if (owned_input_bytes.len == 0) { return .{ .utf8 = ZigString.Slice.empty, @@ -1139,7 +1141,7 @@ pub const SliceWithUnderlyingString = struct { } return .{ - .underlying = JSC.WebCore.encoding.toBunStringFromOwnedSlice(owned_input_bytes, encoding), + .underlying = jsc.WebCore.encoding.toBunStringFromOwnedSlice(owned_input_bytes, encoding), }; } @@ -1190,15 +1192,15 @@ pub const SliceWithUnderlyingString = struct { try writer.writeAll(self.utf8.slice()); } - pub fn toJS(this: *SliceWithUnderlyingString, globalObject: *JSC.JSGlobalObject) bun.JSError!JSC.JSValue { + pub fn toJS(this: *SliceWithUnderlyingString, globalObject: *jsc.JSGlobalObject) bun.JSError!jsc.JSValue { return this.toJSWithOptions(globalObject, false); } - pub fn transferToJS(this: *SliceWithUnderlyingString, globalObject: *JSC.JSGlobalObject) bun.JSError!JSC.JSValue { + pub fn transferToJS(this: *SliceWithUnderlyingString, globalObject: *jsc.JSGlobalObject) bun.JSError!jsc.JSValue { return this.toJSWithOptions(globalObject, true); } - fn toJSWithOptions(this: *SliceWithUnderlyingString, globalObject: *JSC.JSGlobalObject, transfer: bool) bun.JSError!JSC.JSValue { + fn toJSWithOptions(this: *SliceWithUnderlyingString, globalObject: *jsc.JSGlobalObject, transfer: bool) bun.JSError!jsc.JSValue { if ((this.underlying.tag == .Dead or this.underlying.tag == .Empty) and this.utf8.length() > 0) { if (comptime bun.Environment.allow_assert) { if (this.utf8.allocator.get()) |allocator| { @@ -1210,7 +1212,7 @@ pub const SliceWithUnderlyingString = struct { if (bun.strings.toUTF16Alloc(bun.default_allocator, this.utf8.slice(), false, false) catch null) |utf16| { this.utf8.deinit(); this.utf8 = .{}; - return JSC.ZigString.toExternalU16(utf16.ptr, utf16.len, globalObject); + return jsc.ZigString.toExternalU16(utf16.ptr, utf16.len, globalObject); } else { const js_value = ZigString.init(this.utf8.slice()).toExternalValue( globalObject, @@ -1251,6 +1253,6 @@ const bun = @import("bun"); const JSError = bun.JSError; const OOM = bun.OOM; -const JSC = bun.JSC; -const JSValue = bun.JSC.JSValue; -const ZigString = bun.JSC.ZigString; +const jsc = bun.jsc; +const JSValue = bun.jsc.JSValue; +const ZigString = bun.jsc.ZigString; diff --git a/src/string/MutableString.zig b/src/string/MutableString.zig index fd0a7e3006..643e51ca39 100644 --- a/src/string/MutableString.zig +++ b/src/string/MutableString.zig @@ -345,7 +345,7 @@ pub const BufferedWriter = struct { return pending.len; } - const E = bun.JSAst.E; + const E = bun.ast.E; /// Write a E.String to the buffer. /// This automatically encodes UTF-16 into UTF-8 using @@ -455,10 +455,11 @@ pub fn writeAll(self: *MutableString, bytes: string) Allocator.Error!usize { return bytes.len; } +const string = []const u8; + const std = @import("std"); const Allocator = std.mem.Allocator; const bun = @import("bun"); const js_lexer = bun.js_lexer; -const string = bun.string; const strings = bun.strings; diff --git a/src/string/PathString.zig b/src/string/PathString.zig index cba4f76f25..7873b9fca1 100644 --- a/src/string/PathString.zig +++ b/src/string/PathString.zig @@ -14,7 +14,7 @@ pub const PathString = packed struct(PathStringBackingIntType) { ptr: PointerIntType = 0, len: PathInt = 0, - const JSC = bun.JSC; + const jsc = bun.jsc; pub fn estimatedSize(this: *const PathString) usize { return @as(usize, this.len); diff --git a/src/string/SmolStr.zig b/src/string/SmolStr.zig index 447925b24a..55560abd54 100644 --- a/src/string/SmolStr.zig +++ b/src/string/SmolStr.zig @@ -266,7 +266,8 @@ test "Creating an inlined SmolStr does not allocate" { try t.expect(hello.isInlined()); } -const BabyList = @import("../baby_list.zig").BabyList; +const bun = @import("bun"); +const BabyList = bun.collections.BabyList; const std = @import("std"); const t = std.testing; diff --git a/src/string/WTFStringImpl.zig b/src/string/WTFStringImpl.zig index 90595a6ac6..43fa4cd260 100644 --- a/src/string/WTFStringImpl.zig +++ b/src/string/WTFStringImpl.zig @@ -87,7 +87,7 @@ pub const WTFStringImplStruct = extern struct { } pub inline fn deref(self: WTFStringImpl) void { - JSC.markBinding(@src()); + jsc.markBinding(@src()); const current_count = self.refCount(); bun.assert(self.hasAtLeastOneRef()); // do not use current_count, it breaks for static strings bun.cpp.Bun__WTFStringImpl__deref(self); @@ -99,7 +99,7 @@ pub const WTFStringImplStruct = extern struct { } pub inline fn ref(self: WTFStringImpl) void { - JSC.markBinding(@src()); + jsc.markBinding(@src()); const current_count = self.refCount(); bun.assert(self.hasAtLeastOneRef()); // do not use current_count, it breaks for static strings bun.cpp.Bun__WTFStringImpl__ref(self); @@ -118,7 +118,7 @@ pub const WTFStringImplStruct = extern struct { /// Compute the hash() if necessary pub fn ensureHash(this: WTFStringImpl) void { - JSC.markBinding(@src()); + jsc.markBinding(@src()); bun.cpp.Bun__WTFStringImpl__ensureHash(this); } @@ -197,7 +197,7 @@ pub const WTFStringImplStruct = extern struct { pub fn utf8ByteLength(this: WTFStringImpl) usize { if (this.is8Bit()) { const input = this.latin1Slice(); - return if (input.len > 0) JSC.WebCore.encoding.byteLengthU8(input.ptr, input.len, .utf8) else 0; + return if (input.len > 0) jsc.WebCore.encoding.byteLengthU8(input.ptr, input.len, .utf8) else 0; } else { const input = this.utf16Slice(); return if (input.len > 0) bun.strings.elementLengthUTF16IntoUTF8([]const u16, input) else 0; @@ -260,5 +260,5 @@ pub const StringImplAllocator = struct { const bun = @import("bun"); const std = @import("std"); -const JSC = bun.JSC; -const ZigString = bun.JSC.ZigString; +const jsc = bun.jsc; +const ZigString = bun.jsc.ZigString; diff --git a/src/string_immutable.zig b/src/string/immutable.zig similarity index 96% rename from src/string_immutable.zig rename to src/string/immutable.zig index 9f6feff8f4..2a5804955f 100644 --- a/src/string_immutable.zig +++ b/src/string/immutable.zig @@ -1928,7 +1928,7 @@ pub fn moveSlice(slice: string, from: string, to: string) string { return result; } -pub const ExactSizeMatcher = @import("./exact_size_matcher.zig").ExactSizeMatcher; +pub const ExactSizeMatcher = @import("./immutable/exact_size_matcher.zig").ExactSizeMatcher; pub const unicode_replacement = 0xFFFD; pub const unicode_replacement_str = brk: { @@ -2297,65 +2297,67 @@ pub const wtf8ByteSequenceLength = unicode.wtf8ByteSequenceLength; pub const wtf8ByteSequenceLengthWithInvalid = unicode.wtf8ByteSequenceLengthWithInvalid; pub const wtf8Sequence = unicode.wtf8Sequence; -pub const isAmgiguousCodepointType = _visible.isAmgiguousCodepointType; -pub const isFullWidthCodepointType = _visible.isFullWidthCodepointType; -pub const isZeroWidthCodepointType = _visible.isZeroWidthCodepointType; -pub const visible = _visible.visible; -pub const visibleCodepointWidth = _visible.visibleCodepointWidth; -pub const visibleCodepointWidthMaybeEmoji = _visible.visibleCodepointWidthMaybeEmoji; -pub const visibleCodepointWidthType = _visible.visibleCodepointWidthType; +pub const isAmgiguousCodepointType = visible_.isAmgiguousCodepointType; +pub const isFullWidthCodepointType = visible_.isFullWidthCodepointType; +pub const isZeroWidthCodepointType = visible_.isZeroWidthCodepointType; +pub const visible = visible_.visible; +pub const visibleCodepointWidth = visible_.visibleCodepointWidth; +pub const visibleCodepointWidthMaybeEmoji = visible_.visibleCodepointWidthMaybeEmoji; +pub const visibleCodepointWidthType = visible_.visibleCodepointWidthType; -pub const escapeHTMLForLatin1Input = _escapeHTML.escapeHTMLForLatin1Input; -pub const escapeHTMLForUTF16Input = _escapeHTML.escapeHTMLForUTF16Input; +pub const escapeHTMLForLatin1Input = escapeHTML_.escapeHTMLForLatin1Input; +pub const escapeHTMLForUTF16Input = escapeHTML_.escapeHTMLForUTF16Input; -pub const addNTPathPrefix = _paths.addNTPathPrefix; -pub const addNTPathPrefixIfNeeded = _paths.addNTPathPrefixIfNeeded; -pub const addLongPathPrefix = _paths.addLongPathPrefix; -pub const addLongPathPrefixIfNeeded = _paths.addLongPathPrefixIfNeeded; -pub const assertIsValidWindowsPath = _paths.assertIsValidWindowsPath; -pub const charIsAnySlash = _paths.charIsAnySlash; -pub const cloneNormalizingSeparators = _paths.cloneNormalizingSeparators; -pub const fromWPath = _paths.fromWPath; -pub const isWindowsAbsolutePathMissingDriveLetter = _paths.isWindowsAbsolutePathMissingDriveLetter; -pub const normalizeSlashesOnly = _paths.normalizeSlashesOnly; -pub const normalizeSlashesOnlyT = _paths.normalizeSlashesOnlyT; -pub const pathContainsNodeModulesFolder = _paths.pathContainsNodeModulesFolder; -pub const removeLeadingDotSlash = _paths.removeLeadingDotSlash; -pub const startsWithWindowsDriveLetter = _paths.startsWithWindowsDriveLetter; -pub const startsWithWindowsDriveLetterT = _paths.startsWithWindowsDriveLetterT; -pub const toExtendedPathNormalized = _paths.toExtendedPathNormalized; -pub const toKernel32Path = _paths.toKernel32Path; -pub const toNTPath = _paths.toNTPath; -pub const toNTPath16 = _paths.toNTPath16; -pub const toPath = _paths.toPath; -pub const toPathMaybeDir = _paths.toPathMaybeDir; -pub const toPathNormalized = _paths.toPathNormalized; -pub const toWDirNormalized = _paths.toWDirNormalized; -pub const toWDirPath = _paths.toWDirPath; -pub const toWPath = _paths.toWPath; -pub const toWPathMaybeDir = _paths.toWPathMaybeDir; -pub const toWPathNormalizeAutoExtend = _paths.toWPathNormalizeAutoExtend; -pub const toWPathNormalized = _paths.toWPathNormalized; -pub const toWPathNormalized16 = _paths.toWPathNormalized16; -pub const withoutLeadingPathSeparator = _paths.withoutLeadingPathSeparator; -pub const withoutLeadingSlash = _paths.withoutLeadingSlash; -pub const withoutNTPrefix = _paths.withoutNTPrefix; -pub const withoutTrailingSlash = _paths.withoutTrailingSlash; -pub const withoutTrailingSlashWindowsPath = _paths.withoutTrailingSlashWindowsPath; -pub const basename = _paths.basename; +pub const addNTPathPrefix = paths_.addNTPathPrefix; +pub const addNTPathPrefixIfNeeded = paths_.addNTPathPrefixIfNeeded; +pub const addLongPathPrefix = paths_.addLongPathPrefix; +pub const addLongPathPrefixIfNeeded = paths_.addLongPathPrefixIfNeeded; +pub const assertIsValidWindowsPath = paths_.assertIsValidWindowsPath; +pub const charIsAnySlash = paths_.charIsAnySlash; +pub const cloneNormalizingSeparators = paths_.cloneNormalizingSeparators; +pub const fromWPath = paths_.fromWPath; +pub const isWindowsAbsolutePathMissingDriveLetter = paths_.isWindowsAbsolutePathMissingDriveLetter; +pub const normalizeSlashesOnly = paths_.normalizeSlashesOnly; +pub const normalizeSlashesOnlyT = paths_.normalizeSlashesOnlyT; +pub const pathContainsNodeModulesFolder = paths_.pathContainsNodeModulesFolder; +pub const removeLeadingDotSlash = paths_.removeLeadingDotSlash; +pub const startsWithWindowsDriveLetter = paths_.startsWithWindowsDriveLetter; +pub const startsWithWindowsDriveLetterT = paths_.startsWithWindowsDriveLetterT; +pub const toExtendedPathNormalized = paths_.toExtendedPathNormalized; +pub const toKernel32Path = paths_.toKernel32Path; +pub const toNTPath = paths_.toNTPath; +pub const toNTPath16 = paths_.toNTPath16; +pub const toPath = paths_.toPath; +pub const toPathMaybeDir = paths_.toPathMaybeDir; +pub const toPathNormalized = paths_.toPathNormalized; +pub const toWDirNormalized = paths_.toWDirNormalized; +pub const toWDirPath = paths_.toWDirPath; +pub const toWPath = paths_.toWPath; +pub const toWPathMaybeDir = paths_.toWPathMaybeDir; +pub const toWPathNormalizeAutoExtend = paths_.toWPathNormalizeAutoExtend; +pub const toWPathNormalized = paths_.toWPathNormalized; +pub const toWPathNormalized16 = paths_.toWPathNormalized16; +pub const withoutLeadingPathSeparator = paths_.withoutLeadingPathSeparator; +pub const withoutLeadingSlash = paths_.withoutLeadingSlash; +pub const withoutNTPrefix = paths_.withoutNTPrefix; +pub const withoutTrailingSlash = paths_.withoutTrailingSlash; +pub const withoutTrailingSlashWindowsPath = paths_.withoutTrailingSlashWindowsPath; +pub const basename = paths_.basename; pub const log = bun.Output.scoped(.STR, true); -pub const grapheme = @import("./grapheme.zig"); +pub const grapheme = @import("./immutable/grapheme.zig"); +pub const CodePoint = i32; -const Environment = @import("./env.zig"); -const _escapeHTML = @import("./string/escapeHTML.zig"); -const _paths = @import("./string/paths.zig"); -const _visible = @import("./string/visible.zig"); -const js_lexer = @import("./js_lexer.zig"); +const string = []const u8; + +const escapeHTML_ = @import("./immutable/escapeHTML.zig"); +const paths_ = @import("./immutable/paths.zig"); const std = @import("std"); -const unicode = @import("./string/unicode.zig"); +const unicode = @import("./immutable/unicode.zig"); +const visible_ = @import("./immutable/visible.zig"); const bun = @import("bun"); +const Environment = bun.Environment; const OOM = bun.OOM; const assert = bun.assert; -const string = bun.string; +const js_lexer = bun.js_lexer; diff --git a/src/string/escapeHTML.zig b/src/string/immutable/escapeHTML.zig similarity index 100% rename from src/string/escapeHTML.zig rename to src/string/immutable/escapeHTML.zig diff --git a/src/exact_size_matcher.zig b/src/string/immutable/exact_size_matcher.zig similarity index 100% rename from src/exact_size_matcher.zig rename to src/string/immutable/exact_size_matcher.zig diff --git a/src/grapheme.zig b/src/string/immutable/grapheme.zig similarity index 100% rename from src/grapheme.zig rename to src/string/immutable/grapheme.zig diff --git a/src/string/paths.zig b/src/string/immutable/paths.zig similarity index 100% rename from src/string/paths.zig rename to src/string/immutable/paths.zig diff --git a/src/string/unicode.zig b/src/string/immutable/unicode.zig similarity index 100% rename from src/string/unicode.zig rename to src/string/immutable/unicode.zig diff --git a/src/string/visible.zig b/src/string/immutable/visible.zig similarity index 100% rename from src/string/visible.zig rename to src/string/immutable/visible.zig diff --git a/src/string_types.zig b/src/string_types.zig deleted file mode 100644 index c3f615d3c2..0000000000 --- a/src/string_types.zig +++ /dev/null @@ -1,4 +0,0 @@ -pub const string = []const u8; -pub const stringZ = [:0]const u8; -pub const stringMutable = []u8; -pub const CodePoint = i32; diff --git a/src/sys.zig b/src/sys.zig index 49e93848a3..2f33a4d275 100644 --- a/src/sys.zig +++ b/src/sys.zig @@ -296,7 +296,7 @@ pub const Tag = enum(u8) { return @intFromEnum(this) > @intFromEnum(Tag.WriteFile); } - pub var strings = std.EnumMap(Tag, JSC.C.JSStringRef).initFull(null); + pub var strings = std.EnumMap(Tag, jsc.C.JSStringRef).initFull(null); }; pub const Error = struct { @@ -621,7 +621,7 @@ pub const Error = struct { return Error{ .errno = todo_errno, .syscall = .TODO }; } - pub fn toJS(this: Error, ptr: *JSC.JSGlobalObject) JSC.JSValue { + pub fn toJS(this: Error, ptr: *jsc.JSGlobalObject) jsc.JSValue { return this.toSystemError().toErrorInstance(ptr); } }; @@ -659,7 +659,7 @@ pub fn getcwdZ(buf: *bun.PathBuffer) Maybe([:0]const u8) { const syscall_or_c = if (Environment.isLinux) syscall else bun.c; -pub fn fchown(fd: bun.FileDescriptor, uid: JSC.Node.uid_t, gid: JSC.Node.gid_t) Maybe(void) { +pub fn fchown(fd: bun.FileDescriptor, uid: jsc.Node.uid_t, gid: jsc.Node.gid_t) Maybe(void) { if (comptime Environment.isWindows) { return sys_uv.fchown(fd, uid, gid); } @@ -729,7 +729,10 @@ pub fn chmod(path: [:0]const u8, mode: bun.Mode) Maybe(void) { unreachable; } -pub fn chdirOSPath(path: bun.stringZ, destination: if (Environment.isPosix) bun.stringZ else bun.string) Maybe(void) { +pub fn chdirOSPath( + path: [:0]const u8, + destination: if (Environment.isPosix) [:0]const u8 else []const u8, +) Maybe(void) { if (comptime Environment.isPosix) { const rc = syscall.chdir(destination); return Maybe(void).errnoSysPD(rc, .chdir, path, destination) orelse Maybe(void).success; @@ -875,7 +878,7 @@ pub fn fstat(fd: bun.FileDescriptor) Maybe(bun.Stat) { if (Maybe(bun.Stat).errnoSysFd(rc, .fstat, fd)) |err| return err; return Maybe(bun.Stat){ .result = stat_ }; } -pub fn lutimes(path: [:0]const u8, atime: JSC.Node.TimeLike, mtime: JSC.Node.TimeLike) Maybe(void) { +pub fn lutimes(path: [:0]const u8, atime: jsc.Node.TimeLike, mtime: jsc.Node.TimeLike) Maybe(void) { if (comptime Environment.isWindows) { return sys_uv.lutimes(path, atime, mtime); } @@ -1774,7 +1777,7 @@ pub fn openat(dirfd: bun.FileDescriptor, file_path: [:0]const u8, flags: i32, pe } } -pub fn openatFileWithLibuvFlags(dirfd: bun.FileDescriptor, file_path: [:0]const u8, flags: bun.JSC.Node.FileSystemFlags, perm: bun.Mode) Maybe(bun.FileDescriptor) { +pub fn openatFileWithLibuvFlags(dirfd: bun.FileDescriptor, file_path: [:0]const u8, flags: bun.jsc.Node.FileSystemFlags, perm: bun.Mode) Maybe(bun.FileDescriptor) { if (comptime Environment.isWindows) { const f = flags.toWindows() catch return .{ .err = .{ .errno = @intFromEnum(E.INVAL), @@ -3350,11 +3353,11 @@ pub fn existsZ(path: [:0]const u8) bool { } } -pub fn faccessat(dir_fd: bun.FileDescriptor, subpath: anytype) JSC.Maybe(bool) { +pub fn faccessat(dir_fd: bun.FileDescriptor, subpath: anytype) jsc.Maybe(bool) { const has_sentinel = std.meta.sentinel(@TypeOf(subpath)) != null; if (comptime !has_sentinel) { - const path = std.os.toPosixPath(subpath) catch return JSC.Maybe(bool){ .err = Error.fromCode(.NAMETOOLONG, .access) }; + const path = std.os.toPosixPath(subpath) catch return jsc.Maybe(bool){ .err = Error.fromCode(.NAMETOOLONG, .access) }; return faccessat(dir_fd, path); } @@ -3363,23 +3366,23 @@ pub fn faccessat(dir_fd: bun.FileDescriptor, subpath: anytype) JSC.Maybe(bool) { const rc = linux.faccessat(dir_fd.cast(), subpath, linux.F_OK, 0); syslog("faccessat({}, {}, O_RDONLY, 0) = {d}", .{ dir_fd, bun.fmt.fmtOSPath(subpath, .{}), if (rc == 0) 0 else @intFromEnum(getErrno(rc)) }); if (rc == 0) { - return JSC.Maybe(bool){ .result = true }; + return jsc.Maybe(bool){ .result = true }; } - return JSC.Maybe(bool){ .result = false }; + return jsc.Maybe(bool){ .result = false }; } // on other platforms use faccessat from libc const rc = std.c.faccessat(dir_fd.cast(), subpath, std.posix.F_OK, 0); syslog("faccessat({}, {}, O_RDONLY, 0) = {d}", .{ dir_fd, bun.fmt.fmtOSPath(subpath, .{}), if (rc == 0) 0 else @intFromEnum(getErrno(rc)) }); if (rc == 0) { - return JSC.Maybe(bool){ .result = true }; + return jsc.Maybe(bool){ .result = true }; } - return JSC.Maybe(bool){ .result = false }; + return jsc.Maybe(bool){ .result = false }; } -pub fn directoryExistsAt(dir: bun.FileDescriptor, subpath: anytype) JSC.Maybe(bool) { +pub fn directoryExistsAt(dir: bun.FileDescriptor, subpath: anytype) jsc.Maybe(bool) { return switch (existsAtType(dir, subpath)) { // .err => |err| if (err.getErrno() == .NOENT) @@ -3390,7 +3393,7 @@ pub fn directoryExistsAt(dir: bun.FileDescriptor, subpath: anytype) JSC.Maybe(bo }; } -pub fn futimens(fd: bun.FileDescriptor, atime: JSC.Node.TimeLike, mtime: JSC.Node.TimeLike) Maybe(void) { +pub fn futimens(fd: bun.FileDescriptor, atime: jsc.Node.TimeLike, mtime: jsc.Node.TimeLike) Maybe(void) { if (comptime Environment.isWindows) @compileError("TODO: futimes"); while (true) { @@ -3414,7 +3417,7 @@ pub fn futimens(fd: bun.FileDescriptor, atime: JSC.Node.TimeLike, mtime: JSC.Nod unreachable; } -fn utimensWithFlags(path: bun.OSPathSliceZ, atime: JSC.Node.TimeLike, mtime: JSC.Node.TimeLike, flags: u32) Maybe(void) { +fn utimensWithFlags(path: bun.OSPathSliceZ, atime: jsc.Node.TimeLike, mtime: jsc.Node.TimeLike, flags: u32) Maybe(void) { if (comptime Environment.isWindows) @compileError("TODO: utimens"); while (true) { @@ -3456,7 +3459,7 @@ pub fn getFcntlFlags(fd: bun.FileDescriptor) Maybe(fnctl_int) { }; } -pub fn utimens(path: bun.OSPathSliceZ, atime: JSC.Node.TimeLike, mtime: JSC.Node.TimeLike) Maybe(void) { +pub fn utimens(path: bun.OSPathSliceZ, atime: jsc.Node.TimeLike, mtime: jsc.Node.TimeLike) Maybe(void) { return utimensWithFlags(path, atime, mtime, 0); } @@ -3522,7 +3525,7 @@ pub fn existsAtType(fd: bun.FileDescriptor, subpath: anytype) Maybe(ExistsAtType }; var basic_info: w.FILE_BASIC_INFORMATION = undefined; const rc = ntdll.NtQueryAttributesFile(&attr, &basic_info); - if (JSC.Maybe(bool).errnoSys(rc, .access)) |err| { + if (jsc.Maybe(bool).errnoSys(rc, .access)) |err| { syslog("NtQueryAttributesFile({}, O_RDONLY, 0) = {}", .{ bun.fmt.fmtOSPath(path, .{}), err }); return .{ .err = err.err }; } @@ -4248,7 +4251,7 @@ pub const File = struct { pub fn unwrap(self: *const ReadToEndResult) ![]u8 { if (self.err) |err| { - try (JSC.Maybe(void){ .err = err }).unwrap(); + try (jsc.Maybe(void){ .err = err }).unwrap(); } return self.bytes.items; } @@ -5243,8 +5246,8 @@ const libc_stat = bun.Stat; const assertIsValidWindowsPath = bun.strings.assertIsValidWindowsPath; const darwin_nocancel = bun.darwin.nocancel; -const JSC = bun.JSC; -const SystemError = JSC.SystemError; +const jsc = bun.jsc; +const SystemError = jsc.SystemError; const windows = bun.windows; const kernel32 = bun.windows.kernel32; diff --git a/src/sys_uv.zig b/src/sys_uv.zig index 96011d121d..86db15b588 100644 --- a/src/sys_uv.zig +++ b/src/sys_uv.zig @@ -404,5 +404,5 @@ const FileDescriptor = bun.FileDescriptor; const assertIsValidWindowsPath = bun.strings.assertIsValidWindowsPath; const uv = bun.windows.libuv; -const JSC = bun.JSC; -const Maybe = JSC.Maybe; +const jsc = bun.jsc; +const Maybe = jsc.Maybe; diff --git a/src/tmp.zig b/src/tmp.zig index 1195175858..114aa63934 100644 --- a/src/tmp.zig +++ b/src/tmp.zig @@ -12,7 +12,7 @@ pub const Tmpfile = struct { pub fn create( destination_dir: bun.FileDescriptor, tmpfilename: [:0]const u8, - ) bun.JSC.Maybe(Tmpfile) { + ) bun.jsc.Maybe(Tmpfile) { const perm = 0o644; var tmpfile = Tmpfile{ .destination_dir = destination_dir, diff --git a/src/transpiler.zig b/src/transpiler.zig index f429bac211..3ec22ee790 100644 --- a/src/transpiler.zig +++ b/src/transpiler.zig @@ -1,6 +1,6 @@ pub const options = @import("./options.zig"); -pub const MacroJSValueType = JSC.JSValue; +pub const MacroJSValueType = jsc.JSValue; pub const EntryPoints = @import("./bundler/entry_points.zig"); @@ -13,7 +13,7 @@ pub const ParseResult = struct { empty: bool = false, pending_imports: _resolver.PendingResolution.List = .{}, - runtime_transpiler_cache: ?*bun.JSC.RuntimeTranspilerCache = null, + runtime_transpiler_cache: ?*bun.jsc.RuntimeTranspilerCache = null, pub const AlreadyBundled = union(enum) { none: void, @@ -56,7 +56,7 @@ pub const ParseResult = struct { }; pub const PluginRunner = struct { - global_object: *JSC.JSGlobalObject, + global_object: *jsc.JSGlobalObject, allocator: std.mem.Allocator, pub fn extractNamespace(specifier: string) string { @@ -88,7 +88,7 @@ pub const PluginRunner = struct { importer: []const u8, log: *logger.Log, loc: logger.Loc, - target: JSC.JSGlobalObject.BunPluginTarget, + target: jsc.JSGlobalObject.BunPluginTarget, ) bun.JSError!?Fs.Path { var global = this.global_object; const namespace_slice = extractNamespace(specifier); @@ -184,7 +184,7 @@ pub const PluginRunner = struct { } } - pub fn onResolveJSC(this: *const PluginRunner, namespace: bun.String, specifier: bun.String, importer: bun.String, target: JSC.JSGlobalObject.BunPluginTarget) bun.JSError!?JSC.ErrorableString { + pub fn onResolveJSC(this: *const PluginRunner, namespace: bun.String, specifier: bun.String, importer: bun.String, target: jsc.JSGlobalObject.BunPluginTarget) bun.JSError!?jsc.ErrorableString { var global = this.global_object; const on_resolve_plugin = try global.runOnResolvePlugins( if (namespace.length() > 0 and !namespace.eqlComptime("file")) @@ -199,7 +199,7 @@ pub const PluginRunner = struct { const path_value = try on_resolve_plugin.get(global, "path") orelse return null; if (path_value.isEmptyOrUndefinedOrNull()) return null; if (!path_value.isString()) { - return JSC.ErrorableString.err( + return jsc.ErrorableString.err( error.JSErrorObject, bun.String.static("Expected \"path\" to be a string in onResolve plugin").toErrorInstance(this.global_object), ); @@ -208,7 +208,7 @@ pub const PluginRunner = struct { const file_path = try path_value.toBunString(global); if (file_path.length() == 0) { - return JSC.ErrorableString.err( + return jsc.ErrorableString.err( error.JSErrorObject, bun.String.static("Expected \"path\" to be a non-empty string in onResolve plugin").toErrorInstance(this.global_object), ); @@ -219,7 +219,7 @@ pub const PluginRunner = struct { file_path.eqlComptime("...") or file_path.eqlComptime(" ")) { - return JSC.ErrorableString.err( + return jsc.ErrorableString.err( error.JSErrorObject, bun.String.static("\"path\" is invalid in onResolve plugin").toErrorInstance(this.global_object), ); @@ -228,7 +228,7 @@ pub const PluginRunner = struct { const user_namespace: bun.String = brk: { if (try on_resolve_plugin.get(global, "namespace")) |namespace_value| { if (!namespace_value.isString()) { - return JSC.ErrorableString.err( + return jsc.ErrorableString.err( error.JSErrorObject, bun.String.static("Expected \"namespace\" to be a string").toErrorInstance(this.global_object), ); @@ -263,13 +263,13 @@ pub const PluginRunner = struct { }; defer user_namespace.deref(); - // Our super slow way of cloning the string into memory owned by JSC + // Our super slow way of cloning the string into memory owned by jsc const combined_string = std.fmt.allocPrint(this.allocator, "{any}:{any}", .{ user_namespace, file_path }) catch unreachable; var out_ = bun.String.init(combined_string); const jsval = out_.toJS(this.global_object); const out = jsval.toBunString(this.global_object) catch @panic("unreachable"); this.allocator.free(combined_string); - return JSC.ErrorableString.ok(out); + return jsc.ErrorableString.ok(out); } }; @@ -384,7 +384,7 @@ pub const Transpiler = struct { pub fn init( allocator: std.mem.Allocator, log: *logger.Log, - opts: Api.TransformOptions, + opts: api.TransformOptions, env_loader_: ?*DotEnv.Loader, ) !Transpiler { js_ast.Expr.Data.Store.create(); @@ -716,7 +716,7 @@ pub const Transpiler = struct { transpiler.log.addErrorFmt(null, logger.Loc.Empty, transpiler.allocator, "{} while minifying", .{e.kind}) catch bun.outOfMemory(); return null; } - const symbols = bun.JSAst.Symbol.Map{}; + const symbols = bun.ast.Symbol.Map{}; const result = switch (sheet.toCss( alloc, bun.css.PrinterOptions{ @@ -767,7 +767,7 @@ pub const Transpiler = struct { comptime format: js_printer.Format, comptime enable_source_map: bool, source_map_context: ?js_printer.SourceMapHandler, - runtime_transpiler_cache: ?*bun.JSC.RuntimeTranspilerCache, + runtime_transpiler_cache: ?*bun.jsc.RuntimeTranspilerCache, ) !usize { const tracer = if (enable_source_map) bun.perf.trace("JSPrinter.printWithSourceMap") @@ -949,7 +949,7 @@ pub const Transpiler = struct { /// See: https://nodejs.org/api/packages.html#type module_type: options.ModuleType = .unknown, - runtime_transpiler_cache: ?*bun.JSC.RuntimeTranspilerCache = null, + runtime_transpiler_cache: ?*bun.jsc.RuntimeTranspilerCache = null, keep_json_and_toml_as_one_statement: bool = false, allow_bytecode_cache: bool = false, @@ -1424,7 +1424,7 @@ pub const Transpiler = struct { transpiler: *Transpiler, allocator: std.mem.Allocator, log: *logger.Log, - opts: Api.TransformOptions, + opts: api.TransformOptions, ) !options.TransformResult { _ = opts; var entry_points = try allocator.alloc(_resolver.Result, transpiler.options.entry_points.len); @@ -1552,6 +1552,8 @@ pub const ResolveQueue = std.fifo.LinearFifo( std.fifo.LinearFifoBufferType.Dynamic, ); +const string = []const u8; + const DotEnv = @import("./env_loader.zig"); const Fs = @import("./fs.zig"); const MimeType = @import("./http/MimeType.zig"); @@ -1562,14 +1564,9 @@ const std = @import("std"); const DataURL = @import("./resolver/data_url.zig").DataURL; const MacroRemap = @import("./resolver/package_json.zig").MacroMap; const PackageManager = @import("./install/install.zig").PackageManager; -const Ref = @import("./ast/base.zig").Ref; const SystemTimer = @import("./system_timer.zig").Timer; -const TOML = @import("./toml/toml_parser.zig").TOML; const URL = @import("./url.zig").URL; -const schema = @import("./api/schema.zig"); -const Api = schema.Api; - const linker = @import("./linker.zig"); const Linker = linker.Linker; @@ -1581,16 +1578,19 @@ const bun = @import("bun"); const Environment = bun.Environment; const FeatureFlags = bun.FeatureFlags; const Global = bun.Global; -const JSC = bun.JSC; -const JSON = bun.JSON; +const JSON = bun.json; const MutableString = bun.MutableString; const Output = bun.Output; const StoredFileDescriptorType = bun.StoredFileDescriptorType; const default_allocator = bun.default_allocator; -const js_ast = bun.JSAst; const js_parser = bun.js_parser; const js_printer = bun.js_printer; +const jsc = bun.jsc; const logger = bun.logger; -const string = bun.string; const strings = bun.strings; -const default_macro_js_value = JSC.JSValue.zero; +const api = bun.schema.api; +const TOML = bun.interchange.toml.TOML; +const default_macro_js_value = jsc.JSValue.zero; + +const js_ast = bun.ast; +const Ref = bun.ast.Ref; diff --git a/src/url.zig b/src/url.zig index 437d0c43f7..9013b0864c 100644 --- a/src/url.zig +++ b/src/url.zig @@ -40,11 +40,11 @@ pub const URL = struct { } pub fn isBlob(this: *const URL) bool { - return this.href.len == JSC.WebCore.ObjectURLRegistry.specifier_len and strings.hasPrefixComptime(this.href, "blob:"); + return this.href.len == jsc.WebCore.ObjectURLRegistry.specifier_len and strings.hasPrefixComptime(this.href, "blob:"); } - pub fn fromJS(js_value: JSC.JSValue, globalObject: *JSC.JSGlobalObject, allocator: std.mem.Allocator) !URL { - var href = JSC.URL.hrefFromJS(globalObject, js_value); + pub fn fromJS(js_value: jsc.JSValue, globalObject: *jsc.JSGlobalObject, allocator: std.mem.Allocator) !URL { + var href = jsc.URL.hrefFromJS(globalObject, js_value); if (href.tag == .Dead) { return error.InvalidURL; } @@ -53,7 +53,7 @@ pub const URL = struct { } pub fn fromString(allocator: std.mem.Allocator, input: bun.String) !URL { - var href = JSC.URL.hrefFromString(input); + var href = jsc.URL.hrefFromString(input); if (href.tag == .Dead) { return error.InvalidURL; } @@ -556,7 +556,7 @@ pub const QueryStringMap = struct { } }; - pub fn str(this: *const QueryStringMap, ptr: Api.StringPointer) string { + pub fn str(this: *const QueryStringMap, ptr: api.StringPointer) string { return this.slice[ptr.offset .. ptr.offset + ptr.length]; } @@ -597,9 +597,9 @@ pub const QueryStringMap = struct { } pub const Param = struct { - name: Api.StringPointer, + name: api.StringPointer, name_hash: u64, - value: Api.StringPointer, + value: api.StringPointer, pub const List = std.MultiArrayList(Param); }; @@ -925,10 +925,10 @@ pub const FormData = struct { this.allocator.destroy(this); } - pub fn toJS(this: *AsyncFormData, global: *JSC.JSGlobalObject, data: []const u8, promise: JSC.AnyPromise) void { + pub fn toJS(this: *AsyncFormData, global: *jsc.JSGlobalObject, data: []const u8, promise: jsc.AnyPromise) void { if (this.encoding == .Multipart and this.encoding.Multipart.len == 0) { log("AsnycFormData.toJS -> promise.reject missing boundary", .{}); - promise.reject(global, JSC.ZigString.init("FormData missing boundary").toErrorInstance(global)); + promise.reject(global, jsc.ZigString.init("FormData missing boundary").toErrorInstance(global)); return; } @@ -974,27 +974,27 @@ pub const FormData = struct { }; pub const External = extern struct { - name: JSC.ZigString, - value: JSC.ZigString, - blob: ?*JSC.WebCore.Blob = null, + name: jsc.ZigString, + value: jsc.ZigString, + blob: ?*jsc.WebCore.Blob = null, }; }; - pub fn toJS(globalThis: *JSC.JSGlobalObject, input: []const u8, encoding: Encoding) !JSC.JSValue { + pub fn toJS(globalThis: *jsc.JSGlobalObject, input: []const u8, encoding: Encoding) !jsc.JSValue { switch (encoding) { .URLEncoded => { - var str = JSC.ZigString.fromUTF8(strings.withoutUTF8BOM(input)); - return JSC.DOMFormData.createFromURLQuery(globalThis, &str); + var str = jsc.ZigString.fromUTF8(strings.withoutUTF8BOM(input)); + return jsc.DOMFormData.createFromURLQuery(globalThis, &str); }, .Multipart => |boundary| return toJSFromMultipartData(globalThis, input, boundary), } } pub fn fromMultipartData( - globalThis: *JSC.JSGlobalObject, - callframe: *JSC.CallFrame, - ) bun.JSError!JSC.JSValue { - JSC.markBinding(@src()); + globalThis: *jsc.JSGlobalObject, + callframe: *jsc.CallFrame, + ) bun.JSError!jsc.JSValue { + jsc.markBinding(@src()); const args_ = callframe.arguments_old(2); @@ -1002,7 +1002,7 @@ pub const FormData = struct { const input_value = args[0]; const boundary_value = args[1]; - var boundary_slice = JSC.ZigString.Slice.empty; + var boundary_slice = jsc.ZigString.Slice.empty; defer boundary_slice.deinit(); var encoding = Encoding{ @@ -1026,7 +1026,7 @@ pub const FormData = struct { return globalThis.throwInvalidArguments("boundary must be a string or ArrayBufferView", .{}); } } - var input_slice = JSC.ZigString.Slice{}; + var input_slice = jsc.ZigString.Slice{}; defer input_slice.deinit(); var input: []const u8 = ""; @@ -1035,7 +1035,7 @@ pub const FormData = struct { } else if (input_value.isString()) { input_slice = try input_value.toSliceOrNull(globalThis); input = input_slice.slice(); - } else if (input_value.as(JSC.WebCore.Blob)) |blob| { + } else if (input_value.as(jsc.WebCore.Blob)) |blob| { input = blob.sharedView(); } else { return globalThis.throwInvalidArguments("input must be a string or ArrayBufferView", .{}); @@ -1045,35 +1045,35 @@ pub const FormData = struct { } comptime { - const jsFunctionFromMultipartData = JSC.toJSHostFn(fromMultipartData); + const jsFunctionFromMultipartData = jsc.toJSHostFn(fromMultipartData); @export(&jsFunctionFromMultipartData, .{ .name = "FormData__jsFunctionFromMultipartData" }); } pub fn toJSFromMultipartData( - globalThis: *JSC.JSGlobalObject, + globalThis: *jsc.JSGlobalObject, input: []const u8, boundary: []const u8, - ) !JSC.JSValue { - const form_data_value = JSC.DOMFormData.create(globalThis); + ) !jsc.JSValue { + const form_data_value = jsc.DOMFormData.create(globalThis); form_data_value.ensureStillAlive(); - const form = JSC.DOMFormData.fromJS(form_data_value) orelse { + const form = jsc.DOMFormData.fromJS(form_data_value) orelse { log("failed to create DOMFormData.fromJS", .{}); return error.@"failed to parse multipart data"; }; const Wrapper = struct { - globalThis: *JSC.JSGlobalObject, - form: *JSC.DOMFormData, + globalThis: *jsc.JSGlobalObject, + form: *jsc.DOMFormData, pub fn onEntry(wrap: *@This(), name: bun.Semver.String, field: Field, buf: []const u8) void { const value_str = field.value.slice(buf); - var key = JSC.ZigString.initUTF8(name.slice(buf)); + var key = jsc.ZigString.initUTF8(name.slice(buf)); if (field.is_file) { const filename_str = field.filename.slice(buf); - var blob = JSC.WebCore.Blob.create(value_str, bun.default_allocator, wrap.globalThis, false); + var blob = jsc.WebCore.Blob.create(value_str, bun.default_allocator, wrap.globalThis, false); defer blob.detach(); - var filename = JSC.ZigString.initUTF8(filename_str); + var filename = jsc.ZigString.initUTF8(filename_str); const content_type: []const u8 = brk: { if (!field.content_type.isEmpty()) { break :brk field.content_type.slice(buf); @@ -1108,7 +1108,7 @@ pub const FormData = struct { wrap.form.appendBlob(wrap.globalThis, &key, &blob, &filename); } else { - var value = JSC.ZigString.initUTF8( + var value = jsc.ZigString.initUTF8( // > Each part whose `Content-Disposition` header does not // > contain a `filename` parameter must be parsed into an // > entry whose value is the UTF-8 decoded without BOM @@ -1284,25 +1284,25 @@ pub const CombinedScanner = struct { } }; -fn stringPointerFromStrings(parent: string, in: string) Api.StringPointer { - if (in.len == 0 or parent.len == 0) return Api.StringPointer{}; +fn stringPointerFromStrings(parent: string, in: string) api.StringPointer { + if (in.len == 0 or parent.len == 0) return api.StringPointer{}; if (bun.rangeOfSliceInBuffer(in, parent)) |range| { - return Api.StringPointer{ .offset = range[0], .length = range[1] }; + return api.StringPointer{ .offset = range[0], .length = range[1] }; } else { if (strings.indexOf(parent, in)) |i| { if (comptime Environment.allow_assert) { bun.assert(strings.eqlLong(parent[i..][0..in.len], in, false)); } - return Api.StringPointer{ + return api.StringPointer{ .offset = @as(u32, @truncate(i)), .length = @as(u32, @truncate(in.len)), }; } } - return Api.StringPointer{}; + return api.StringPointer{}; } pub const PathnameScanner = struct { @@ -1366,8 +1366,8 @@ pub const Scanner = struct { pub const Result = struct { name_needs_decoding: bool = false, value_needs_decoding: bool = false, - name: Api.StringPointer, - value: Api.StringPointer, + name: api.StringPointer, + value: api.StringPointer, pub inline fn rawName(this: *const Result, query_string: string) string { return if (this.name.length > 0) query_string[this.name.offset..][0..this.name.length] else ""; @@ -1390,8 +1390,8 @@ pub const Scanner = struct { const slice = this.query_string[this.i..]; relative_i = 0; - var name = Api.StringPointer{ .offset = @as(u32, @truncate(this.i)), .length = 0 }; - var value = Api.StringPointer{ .offset = 0, .length = 0 }; + var name = api.StringPointer{ .offset = @as(u32, @truncate(this.i)), .length = 0 }; + var value = api.StringPointer{ .offset = 0, .length = 0 }; var name_needs_decoding = false; while (relative_i < slice.len) { @@ -1450,16 +1450,17 @@ pub const Scanner = struct { } }; +const string = []const u8; + const resolve_path = @import("./resolver/resolve_path.zig"); const std = @import("std"); -const Api = @import("./api/schema.zig").Api; const ParamsList = @import("./router.zig").Param.List; const expect = std.testing.expect; const bun = @import("bun"); const Environment = bun.Environment; -const JSC = bun.JSC; const Output = bun.Output; const default_allocator = bun.default_allocator; -const string = bun.string; +const jsc = bun.jsc; const strings = bun.strings; +const api = bun.schema.api; diff --git a/src/valkey/ValkeyCommand.zig b/src/valkey/ValkeyCommand.zig index 07c6bbb83f..dfc9c448e6 100644 --- a/src/valkey/ValkeyCommand.zig +++ b/src/valkey/ValkeyCommand.zig @@ -115,17 +115,17 @@ pub const Meta = packed struct(u8) { /// Promise for a Valkey command pub const Promise = struct { meta: Meta, - promise: JSC.JSPromise.Strong, + promise: jsc.JSPromise.Strong, - pub fn create(globalObject: *JSC.JSGlobalObject, meta: Meta) Promise { - const promise = JSC.JSPromise.Strong.init(globalObject); + pub fn create(globalObject: *jsc.JSGlobalObject, meta: Meta) Promise { + const promise = jsc.JSPromise.Strong.init(globalObject); return Promise{ .meta = meta, .promise = promise, }; } - pub fn resolve(self: *Promise, globalObject: *JSC.JSGlobalObject, value: *protocol.RESPValue) void { + pub fn resolve(self: *Promise, globalObject: *jsc.JSGlobalObject, value: *protocol.RESPValue) void { const options = protocol.RESPValue.ToJSOptions{ .return_as_buffer = self.meta.return_as_buffer, }; @@ -137,7 +137,7 @@ pub const Promise = struct { self.promise.resolve(globalObject, js_value); } - pub fn reject(self: *Promise, globalObject: *JSC.JSGlobalObject, jsvalue: JSC.JSValue) void { + pub fn reject(self: *Promise, globalObject: *jsc.JSGlobalObject, jsvalue: jsc.JSValue) void { self.promise.reject(globalObject, jsvalue); } @@ -153,7 +153,7 @@ pub const PromisePair = struct { pub const Queue = std.fifo.LinearFifo(PromisePair, .Dynamic); - pub fn rejectCommand(self: *PromisePair, globalObject: *JSC.JSGlobalObject, jsvalue: JSC.JSValue) void { + pub fn rejectCommand(self: *PromisePair, globalObject: *jsc.JSGlobalObject, jsvalue: jsc.JSValue) void { self.promise.reject(globalObject, jsvalue); } }; @@ -162,6 +162,6 @@ const protocol = @import("./valkey_protocol.zig"); const std = @import("std"); const bun = @import("bun"); -const JSC = bun.JSC; +const jsc = bun.jsc; const node = bun.api.node; -const Slice = JSC.ZigString.Slice; +const Slice = jsc.ZigString.Slice; diff --git a/src/valkey/js_valkey.zig b/src/valkey/js_valkey.zig index c2d68cf95f..19fbb1b38a 100644 --- a/src/valkey/js_valkey.zig +++ b/src/valkey/js_valkey.zig @@ -1,8 +1,8 @@ /// Valkey client wrapper for JavaScript pub const JSValkeyClient = struct { client: valkey.ValkeyClient, - globalObject: *JSC.JSGlobalObject, - this_value: JSC.JSRef = JSC.JSRef.empty(), + globalObject: *jsc.JSGlobalObject, + this_value: jsc.JSRef = jsc.JSRef.empty(), poll_ref: bun.Async.KeepAlive = .{}, timer: Timer.EventLoopTimer = .{ .tag = .ValkeyConnectionTimeout, @@ -20,7 +20,7 @@ pub const JSValkeyClient = struct { }, ref_count: RefCount, - pub const js = JSC.Codegen.JSRedisClient; + pub const js = jsc.Codegen.JSRedisClient; pub const toJS = js.toJS; pub const fromJS = js.fromJS; pub const fromJSDirect = js.fromJSDirect; @@ -31,11 +31,11 @@ pub const JSValkeyClient = struct { pub const new = bun.TrivialNew(@This()); // Factory function to create a new Valkey client from JS - pub fn constructor(globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!*JSValkeyClient { + pub fn constructor(globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!*JSValkeyClient { return try create(globalObject, callframe.arguments()); } - pub fn create(globalObject: *JSC.JSGlobalObject, arguments: []const JSValue) bun.JSError!*JSValkeyClient { + pub fn create(globalObject: *jsc.JSGlobalObject, arguments: []const JSValue) bun.JSError!*JSValkeyClient { const vm = globalObject.bunVM(); const url_str = if (arguments.len < 1 or arguments[0].isUndefined()) if (vm.transpiler.env.get("REDIS_URL") orelse vm.transpiler.env.get("VALKEY_URL")) |url| @@ -148,31 +148,31 @@ pub const JSValkeyClient = struct { }); } - pub fn getConnected(this: *JSValkeyClient, _: *JSC.JSGlobalObject) JSValue { + pub fn getConnected(this: *JSValkeyClient, _: *jsc.JSGlobalObject) JSValue { return JSValue.jsBoolean(this.client.status == .connected); } - pub fn getBufferedAmount(this: *JSValkeyClient, _: *JSC.JSGlobalObject) JSValue { + pub fn getBufferedAmount(this: *JSValkeyClient, _: *jsc.JSGlobalObject) JSValue { const len = this.client.write_buffer.len() + this.client.read_buffer.len(); return JSValue.jsNumber(len); } - pub fn doConnect(this: *JSValkeyClient, globalObject: *JSC.JSGlobalObject, this_value: JSValue) bun.JSError!JSValue { + pub fn doConnect(this: *JSValkeyClient, globalObject: *jsc.JSGlobalObject, this_value: JSValue) bun.JSError!JSValue { this.ref(); defer this.deref(); // If already connected, resolve immediately if (this.client.status == .connected) { - return JSC.JSPromise.resolvedPromiseValue(globalObject, js.helloGetCached(this_value) orelse .js_undefined); + return jsc.JSPromise.resolvedPromiseValue(globalObject, js.helloGetCached(this_value) orelse .js_undefined); } if (js.connectionPromiseGetCached(this_value)) |promise| { return promise; } - const promise_ptr = JSC.JSPromise.create(globalObject); + const promise_ptr = jsc.JSPromise.create(globalObject); const promise = promise_ptr.toJS(); js.connectionPromiseSetCached(this_value, globalObject, promise); @@ -213,11 +213,11 @@ pub const JSValkeyClient = struct { return promise; } - pub fn jsConnect(this: *JSValkeyClient, globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { + pub fn jsConnect(this: *JSValkeyClient, globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { return try this.doConnect(globalObject, callframe.this()); } - pub fn jsDisconnect(this: *JSValkeyClient, _: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!JSValue { + pub fn jsDisconnect(this: *JSValkeyClient, _: *jsc.JSGlobalObject, _: *jsc.CallFrame) bun.JSError!JSValue { if (this.client.status == .disconnected) { return .js_undefined; } @@ -225,25 +225,25 @@ pub const JSValkeyClient = struct { return .js_undefined; } - pub fn getOnConnect(_: *JSValkeyClient, thisValue: JSValue, _: *JSC.JSGlobalObject) JSValue { + pub fn getOnConnect(_: *JSValkeyClient, thisValue: JSValue, _: *jsc.JSGlobalObject) JSValue { if (js.onconnectGetCached(thisValue)) |value| { return value; } return .js_undefined; } - pub fn setOnConnect(_: *JSValkeyClient, thisValue: JSValue, globalObject: *JSC.JSGlobalObject, value: JSValue) void { + pub fn setOnConnect(_: *JSValkeyClient, thisValue: JSValue, globalObject: *jsc.JSGlobalObject, value: JSValue) void { js.onconnectSetCached(thisValue, globalObject, value); } - pub fn getOnClose(_: *JSValkeyClient, thisValue: JSValue, _: *JSC.JSGlobalObject) JSValue { + pub fn getOnClose(_: *JSValkeyClient, thisValue: JSValue, _: *jsc.JSGlobalObject) JSValue { if (js.oncloseGetCached(thisValue)) |value| { return value; } return .js_undefined; } - pub fn setOnClose(_: *JSValkeyClient, thisValue: JSValue, globalObject: *JSC.JSGlobalObject, value: JSValue) void { + pub fn setOnClose(_: *JSValkeyClient, thisValue: JSValue, globalObject: *jsc.JSGlobalObject, value: JSValue) void { js.oncloseSetCached(thisValue, globalObject, value); } @@ -570,7 +570,7 @@ pub const JSValkeyClient = struct { this.client.socket = try this.client.address.connect(&this.client, ctx, this.client.tls != .none); } - pub fn send(this: *JSValkeyClient, globalThis: *JSC.JSGlobalObject, this_jsvalue: JSValue, command: *const Command) !*JSC.JSPromise { + pub fn send(this: *JSValkeyClient, globalThis: *jsc.JSGlobalObject, this_jsvalue: JSValue, command: *const Command) !*jsc.JSPromise { if (this.client.flags.needs_to_open_socket) { @branchHint(.unlikely); @@ -580,7 +580,7 @@ pub const JSValkeyClient = struct { this.connect() catch |err| { this.client.flags.needs_to_open_socket = true; const err_value = globalThis.ERR(.SOCKET_CLOSED_BEFORE_CONNECTION, " {s} connecting to Valkey", .{@errorName(err)}).toJS(); - const promise = JSC.JSPromise.create(globalThis); + const promise = jsc.JSPromise.create(globalThis); promise.reject(globalThis, err_value); return promise; }; @@ -806,7 +806,7 @@ fn SocketHandler(comptime ssl: bool) type { // Parse JavaScript options into Valkey client options const Options = struct { - pub fn fromJS(globalObject: *JSC.JSGlobalObject, options_obj: JSC.JSValue) !valkey.Options { + pub fn fromJS(globalObject: *jsc.JSGlobalObject, options_obj: jsc.JSValue) !valkey.Options { var this = valkey.Options{ .enable_auto_pipelining = !bun.getRuntimeFeatureFlag(.BUN_FEATURE_FLAG_DISABLE_REDIS_AUTO_PIPELINING), }; @@ -839,7 +839,7 @@ const Options = struct { if (tls.isBoolean() or tls.isUndefinedOrNull()) { this.tls = if (tls.toBoolean()) .enabled else .none; } else if (tls.isObject()) { - if (try JSC.API.ServerConfig.SSLConfig.fromJS(globalObject.bunVM(), globalObject, tls)) |ssl_config| { + if (try jsc.API.ServerConfig.SSLConfig.fromJS(globalObject.bunVM(), globalObject, tls)) |ssl_config| { this.tls = .{ .custom = ssl_config }; } else { return globalObject.throwInvalidArgumentType("tls", "tls", "object"); @@ -867,8 +867,8 @@ const BoringSSL = bun.BoringSSL; const String = bun.String; const Timer = bun.api.Timer; -const JSC = bun.JSC; -const JSValue = JSC.JSValue; +const jsc = bun.jsc; +const JSValue = jsc.JSValue; const uws = bun.uws; const Socket = uws.AnySocket; diff --git a/src/valkey/js_valkey_functions.zig b/src/valkey/js_valkey_functions.zig index 4ab881ba70..30ff2e0975 100644 --- a/src/valkey/js_valkey_functions.zig +++ b/src/valkey/js_valkey_functions.zig @@ -1,4 +1,4 @@ -pub fn jsSend(this: *JSValkeyClient, globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { +pub fn jsSend(this: *JSValkeyClient, globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { const command = try callframe.argument(0).toBunString(globalObject); defer command.deref(); @@ -40,7 +40,7 @@ pub fn jsSend(this: *JSValkeyClient, globalObject: *JSC.JSGlobalObject, callfram return promise.toJS(); } -pub fn get(this: *JSValkeyClient, globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { +pub fn get(this: *JSValkeyClient, globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { const key = (try fromJS(globalObject, callframe.argument(0))) orelse { return globalObject.throwInvalidArgumentType("get", "key", "string or buffer"); }; @@ -60,7 +60,7 @@ pub fn get(this: *JSValkeyClient, globalObject: *JSC.JSGlobalObject, callframe: return promise.toJS(); } -pub fn getBuffer(this: *JSValkeyClient, globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { +pub fn getBuffer(this: *JSValkeyClient, globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { const key = (try fromJS(globalObject, callframe.argument(0))) orelse { return globalObject.throwInvalidArgumentType("getBuffer", "key", "string or buffer"); }; @@ -80,7 +80,7 @@ pub fn getBuffer(this: *JSValkeyClient, globalObject: *JSC.JSGlobalObject, callf return promise.toJS(); } -pub fn set(this: *JSValkeyClient, globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { +pub fn set(this: *JSValkeyClient, globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { const args_view = callframe.arguments(); var stack_fallback = std.heap.stackFallback(512, bun.default_allocator); var args = try std.ArrayList(JSArgument).initCapacity(stack_fallback.get(), args_view.len); @@ -126,7 +126,7 @@ pub fn set(this: *JSValkeyClient, globalObject: *JSC.JSGlobalObject, callframe: return promise.toJS(); } -pub fn incr(this: *JSValkeyClient, globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { +pub fn incr(this: *JSValkeyClient, globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { const key = (try fromJS(globalObject, callframe.argument(0))) orelse { return globalObject.throwInvalidArgumentType("incr", "key", "string or buffer"); }; @@ -146,7 +146,7 @@ pub fn incr(this: *JSValkeyClient, globalObject: *JSC.JSGlobalObject, callframe: return promise.toJS(); } -pub fn decr(this: *JSValkeyClient, globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { +pub fn decr(this: *JSValkeyClient, globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { const key = (try fromJS(globalObject, callframe.argument(0))) orelse { return globalObject.throwInvalidArgumentType("decr", "key", "string or buffer"); }; @@ -166,7 +166,7 @@ pub fn decr(this: *JSValkeyClient, globalObject: *JSC.JSGlobalObject, callframe: return promise.toJS(); } -pub fn exists(this: *JSValkeyClient, globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { +pub fn exists(this: *JSValkeyClient, globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { const key = (try fromJS(globalObject, callframe.argument(0))) orelse { return globalObject.throwInvalidArgumentType("exists", "key", "string or buffer"); }; @@ -187,7 +187,7 @@ pub fn exists(this: *JSValkeyClient, globalObject: *JSC.JSGlobalObject, callfram return promise.toJS(); } -pub fn expire(this: *JSValkeyClient, globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { +pub fn expire(this: *JSValkeyClient, globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { const key = (try fromJS(globalObject, callframe.argument(0))) orelse { return globalObject.throwInvalidArgumentType("expire", "key", "string or buffer"); }; @@ -218,7 +218,7 @@ pub fn expire(this: *JSValkeyClient, globalObject: *JSC.JSGlobalObject, callfram return promise.toJS(); } -pub fn ttl(this: *JSValkeyClient, globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { +pub fn ttl(this: *JSValkeyClient, globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { const key = (try fromJS(globalObject, callframe.argument(0))) orelse { return globalObject.throwInvalidArgumentType("ttl", "key", "string or buffer"); }; @@ -239,7 +239,7 @@ pub fn ttl(this: *JSValkeyClient, globalObject: *JSC.JSGlobalObject, callframe: } // Implement srem (remove value from a set) -pub fn srem(this: *JSValkeyClient, globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { +pub fn srem(this: *JSValkeyClient, globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { const key = (try fromJS(globalObject, callframe.argument(0))) orelse { return globalObject.throwInvalidArgumentType("srem", "key", "string or buffer"); }; @@ -264,7 +264,7 @@ pub fn srem(this: *JSValkeyClient, globalObject: *JSC.JSGlobalObject, callframe: } // Implement srandmember (get random member from set) -pub fn srandmember(this: *JSValkeyClient, globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { +pub fn srandmember(this: *JSValkeyClient, globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { const key = (try fromJS(globalObject, callframe.argument(0))) orelse { return globalObject.throwInvalidArgumentType("srandmember", "key", "string or buffer"); }; @@ -285,7 +285,7 @@ pub fn srandmember(this: *JSValkeyClient, globalObject: *JSC.JSGlobalObject, cal } // Implement smembers (get all members of a set) -pub fn smembers(this: *JSValkeyClient, globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { +pub fn smembers(this: *JSValkeyClient, globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { const key = (try fromJS(globalObject, callframe.argument(0))) orelse { return globalObject.throwInvalidArgumentType("smembers", "key", "string or buffer"); }; @@ -306,7 +306,7 @@ pub fn smembers(this: *JSValkeyClient, globalObject: *JSC.JSGlobalObject, callfr } // Implement spop (pop a random member from a set) -pub fn spop(this: *JSValkeyClient, globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { +pub fn spop(this: *JSValkeyClient, globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { const key = (try fromJS(globalObject, callframe.argument(0))) orelse { return globalObject.throwInvalidArgumentType("spop", "key", "string or buffer"); }; @@ -327,7 +327,7 @@ pub fn spop(this: *JSValkeyClient, globalObject: *JSC.JSGlobalObject, callframe: } // Implement sadd (add member to a set) -pub fn sadd(this: *JSValkeyClient, globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { +pub fn sadd(this: *JSValkeyClient, globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { const key = (try fromJS(globalObject, callframe.argument(0))) orelse { return globalObject.throwInvalidArgumentType("sadd", "key", "string or buffer"); }; @@ -352,7 +352,7 @@ pub fn sadd(this: *JSValkeyClient, globalObject: *JSC.JSGlobalObject, callframe: } // Implement sismember (check if value is member of a set) -pub fn sismember(this: *JSValkeyClient, globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { +pub fn sismember(this: *JSValkeyClient, globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { const key = (try fromJS(globalObject, callframe.argument(0))) orelse { return globalObject.throwInvalidArgumentType("sismember", "key", "string or buffer"); }; @@ -378,7 +378,7 @@ pub fn sismember(this: *JSValkeyClient, globalObject: *JSC.JSGlobalObject, callf } // Implement hmget (get multiple values from hash) -pub fn hmget(this: *JSValkeyClient, globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { +pub fn hmget(this: *JSValkeyClient, globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { const key = (try fromJS(globalObject, callframe.argument(0))) orelse { return globalObject.throwInvalidArgumentType("hmget", "key", "string or buffer"); }; @@ -391,7 +391,7 @@ pub fn hmget(this: *JSValkeyClient, globalObject: *JSC.JSGlobalObject, callframe } var iter = try fields_array.arrayIterator(globalObject); - var args = try std.ArrayList(JSC.ZigString.Slice).initCapacity(bun.default_allocator, iter.len + 1); + var args = try std.ArrayList(jsc.ZigString.Slice).initCapacity(bun.default_allocator, iter.len + 1); defer { for (args.items) |item| { item.deinit(); @@ -399,7 +399,7 @@ pub fn hmget(this: *JSValkeyClient, globalObject: *JSC.JSGlobalObject, callframe args.deinit(); } - args.appendAssumeCapacity(JSC.ZigString.Slice.fromUTF8NeverFree(key.slice())); + args.appendAssumeCapacity(jsc.ZigString.Slice.fromUTF8NeverFree(key.slice())); // Add field names as arguments while (try iter.next()) |field_js| { @@ -425,7 +425,7 @@ pub fn hmget(this: *JSValkeyClient, globalObject: *JSC.JSGlobalObject, callframe } // Implement hincrby (increment hash field by integer value) -pub fn hincrby(this: *JSValkeyClient, globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { +pub fn hincrby(this: *JSValkeyClient, globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { const key = try callframe.argument(0).toBunString(globalObject); defer key.deref(); const field = try callframe.argument(1).toBunString(globalObject); @@ -455,7 +455,7 @@ pub fn hincrby(this: *JSValkeyClient, globalObject: *JSC.JSGlobalObject, callfra } // Implement hincrbyfloat (increment hash field by float value) -pub fn hincrbyfloat(this: *JSValkeyClient, globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { +pub fn hincrbyfloat(this: *JSValkeyClient, globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { const key = try callframe.argument(0).toBunString(globalObject); defer key.deref(); const field = try callframe.argument(1).toBunString(globalObject); @@ -485,7 +485,7 @@ pub fn hincrbyfloat(this: *JSValkeyClient, globalObject: *JSC.JSGlobalObject, ca } // Implement hmset (set multiple values in hash) -pub fn hmset(this: *JSValkeyClient, globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { +pub fn hmset(this: *JSValkeyClient, globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { const key = try callframe.argument(0).toBunString(globalObject); defer key.deref(); @@ -500,7 +500,7 @@ pub fn hmset(this: *JSValkeyClient, globalObject: *JSC.JSGlobalObject, callframe return globalObject.throw("Arguments must be an array of alternating field names and values", .{}); } - var args = try std.ArrayList(JSC.ZigString.Slice).initCapacity(bun.default_allocator, iter.len + 1); + var args = try std.ArrayList(jsc.ZigString.Slice).initCapacity(bun.default_allocator, iter.len + 1); defer { for (args.items) |item| { item.deinit(); @@ -547,7 +547,7 @@ pub fn hmset(this: *JSValkeyClient, globalObject: *JSC.JSGlobalObject, callframe } // Implement ping (send a PING command with an optional message) -pub fn ping(this: *JSValkeyClient, globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { +pub fn ping(this: *JSValkeyClient, globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { var message_buf: [1]JSArgument = undefined; var args_slice: []JSArgument = &.{}; @@ -650,7 +650,7 @@ const compile = struct { comptime arg0_name: []const u8, ) type { return struct { - pub fn call(this: *JSValkeyClient, globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { + pub fn call(this: *JSValkeyClient, globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { const key = (try fromJS(globalObject, callframe.argument(0))) orelse { return globalObject.throwInvalidArgumentType(name, arg0_name, "string or buffer"); }; @@ -677,7 +677,7 @@ const compile = struct { comptime arg0_name: []const u8, ) type { return struct { - pub fn call(this: *JSValkeyClient, globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { + pub fn call(this: *JSValkeyClient, globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { if (callframe.argument(0).isUndefinedOrNull()) { return globalObject.throwMissingArgumentsValue(&.{arg0_name}); } @@ -723,7 +723,7 @@ const compile = struct { comptime arg1_name: []const u8, ) type { return struct { - pub fn call(this: *JSValkeyClient, globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { + pub fn call(this: *JSValkeyClient, globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { const key = (try fromJS(globalObject, callframe.argument(0))) orelse { return globalObject.throwInvalidArgumentType(name, arg0_name, "string or buffer"); }; @@ -753,7 +753,7 @@ const compile = struct { comptime command: []const u8, ) type { return struct { - pub fn call(this: *JSValkeyClient, globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { + pub fn call(this: *JSValkeyClient, globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { var args = try std.ArrayList(JSArgument).initCapacity(bun.default_allocator, callframe.arguments().len); defer { for (args.items) |*item| { @@ -789,7 +789,7 @@ const compile = struct { comptime command: []const u8, ) type { return struct { - pub fn call(this: *JSValkeyClient, globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { + pub fn call(this: *JSValkeyClient, globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { var args = try std.ArrayList(JSArgument).initCapacity(bun.default_allocator, callframe.arguments().len); defer { for (args.items) |*item| { @@ -825,7 +825,7 @@ const compile = struct { } }; -fn fromJS(globalObject: *JSC.JSGlobalObject, value: JSValue) !?JSArgument { +fn fromJS(globalObject: *jsc.JSGlobalObject, value: JSValue) !?JSArgument { if (value.isUndefinedOrNull()) { return null; } @@ -848,10 +848,10 @@ const bun = @import("bun"); const std = @import("std"); const JSValkeyClient = @import("./js_valkey.zig").JSValkeyClient; -const JSC = bun.JSC; -const JSValue = JSC.JSValue; -const JSArgument = JSC.Node.BlobOrStringOrBuffer; -const Slice = JSC.ZigString.Slice; +const jsc = bun.jsc; +const JSValue = jsc.JSValue; +const JSArgument = jsc.Node.BlobOrStringOrBuffer; +const Slice = jsc.ZigString.Slice; const valkey = bun.valkey; const Command = valkey.Command; diff --git a/src/valkey/valkey.zig b/src/valkey/valkey.zig index 3be8fa1e47..840fad0d66 100644 --- a/src/valkey/valkey.zig +++ b/src/valkey/valkey.zig @@ -64,7 +64,7 @@ pub const Protocol = enum { pub const TLS = union(enum) { none, enabled, - custom: JSC.API.ServerConfig.SSLConfig, + custom: jsc.API.ServerConfig.SSLConfig, pub fn deinit(this: *TLS) void { switch (this.*) { @@ -73,7 +73,7 @@ pub const TLS = union(enum) { } } - pub fn rejectUnauthorized(this: *const TLS, vm: *JSC.VirtualMachine) bool { + pub fn rejectUnauthorized(this: *const TLS, vm: *jsc.VirtualMachine) bool { return switch (this.*) { .custom => |*ssl_config| ssl_config.reject_unauthorized != 0, .enabled => vm.getTLSRejectUnauthorized(), @@ -169,10 +169,10 @@ pub const ValkeyClient = struct { // Auto-pipelining auto_flusher: AutoFlusher = .{}, - vm: *JSC.VirtualMachine, + vm: *jsc.VirtualMachine, /// Clean up resources used by the Valkey client - pub fn deinit(this: *@This(), globalObjectOrFinalizing: ?*JSC.JSGlobalObject) void { + pub fn deinit(this: *@This(), globalObjectOrFinalizing: ?*jsc.JSGlobalObject) void { var pending = this.in_flight; this.in_flight = .init(this.allocator); defer pending.deinit(); @@ -214,7 +214,7 @@ pub const ValkeyClient = struct { } // ** Auto-pipelining ** - fn registerAutoFlusher(this: *ValkeyClient, vm: *JSC.VirtualMachine) void { + fn registerAutoFlusher(this: *ValkeyClient, vm: *jsc.VirtualMachine) void { if (!this.auto_flusher.registered) { AutoFlusher.registerDeferredMicrotaskWithTypeUnchecked(@This(), this, vm); this.auto_flusher.registered = true; @@ -320,7 +320,7 @@ pub const ValkeyClient = struct { } /// Reject all pending commands with an error - fn rejectAllPendingCommands(pending_ptr: *Command.PromisePair.Queue, entries_ptr: *Command.Entry.Queue, globalThis: *JSC.JSGlobalObject, allocator: std.mem.Allocator, jsvalue: JSC.JSValue) void { + fn rejectAllPendingCommands(pending_ptr: *Command.PromisePair.Queue, entries_ptr: *Command.Entry.Queue, globalThis: *jsc.JSGlobalObject, allocator: std.mem.Allocator, jsvalue: jsc.JSValue) void { var pending = pending_ptr.*; var entries = entries_ptr.*; defer pending.deinit(); @@ -356,7 +356,7 @@ pub const ValkeyClient = struct { const DeferredFailure = struct { message: []const u8, err: protocol.RedisError, - globalThis: *JSC.JSGlobalObject, + globalThis: *jsc.JSGlobalObject, in_flight: Command.PromisePair.Queue, queue: Command.Entry.Queue, @@ -372,8 +372,8 @@ pub const ValkeyClient = struct { pub fn enqueue(this: *DeferredFailure) void { debug("enqueueing deferred failure", .{}); - const managed_task = JSC.ManagedTask.New(DeferredFailure, run).init(this); - JSC.VirtualMachine.get().eventLoop().enqueueTask(managed_task); + const managed_task = jsc.ManagedTask.New(DeferredFailure, run).init(this); + jsc.VirtualMachine.get().eventLoop().enqueueTask(managed_task); } }; @@ -408,7 +408,7 @@ pub const ValkeyClient = struct { this.failWithJSValue(globalThis, protocol.valkeyErrorToJS(globalThis, message, err)); } - pub fn failWithJSValue(this: *ValkeyClient, globalThis: *JSC.JSGlobalObject, jsvalue: JSC.JSValue) void { + pub fn failWithJSValue(this: *ValkeyClient, globalThis: *jsc.JSGlobalObject, jsvalue: jsc.JSValue) void { this.status = .failed; rejectAllPendingCommands(&this.in_flight, &this.queue, globalThis, this.allocator, jsvalue); @@ -869,7 +869,7 @@ pub const ValkeyClient = struct { _ = this.flushData(); } - pub fn send(this: *ValkeyClient, globalThis: *JSC.JSGlobalObject, command: *const Command) !*JSC.JSPromise { + pub fn send(this: *ValkeyClient, globalThis: *jsc.JSGlobalObject, command: *const Command) !*jsc.JSPromise { var promise = Command.Promise.create(globalThis, command.meta); const js_promise = promise.promise.get(); @@ -937,7 +937,7 @@ pub const ValkeyClient = struct { return @fieldParentPtr("client", this); } - inline fn globalObject(this: *ValkeyClient) *JSC.JSGlobalObject { + inline fn globalObject(this: *ValkeyClient) *jsc.JSGlobalObject { return this.parent().globalObject; } @@ -966,7 +966,7 @@ const protocol = @import("./valkey_protocol.zig"); const std = @import("std"); const bun = @import("bun"); -const JSC = bun.JSC; +const jsc = bun.jsc; const uws = bun.uws; -const AutoFlusher = JSC.WebCore.AutoFlusher; -const JSValkeyClient = JSC.API.Valkey; +const AutoFlusher = jsc.WebCore.AutoFlusher; +const JSValkeyClient = jsc.API.Valkey; diff --git a/src/valkey/valkey_protocol.zig b/src/valkey/valkey_protocol.zig index 929aca7cd6..ac59719889 100644 --- a/src/valkey/valkey_protocol.zig +++ b/src/valkey/valkey_protocol.zig @@ -27,8 +27,8 @@ pub const RedisError = error{ IdleTimeout, }; -pub fn valkeyErrorToJS(globalObject: *JSC.JSGlobalObject, message: ?[]const u8, err: RedisError) JSC.JSValue { - const error_code: JSC.Error = switch (err) { +pub fn valkeyErrorToJS(globalObject: *jsc.JSGlobalObject, message: ?[]const u8, err: RedisError) jsc.JSValue { + const error_code: jsc.Error = switch (err) { error.ConnectionClosed => .REDIS_CONNECTION_CLOSED, error.InvalidResponse => .REDIS_INVALID_RESPONSE, error.InvalidBulkString => .REDIS_INVALID_BULK_STRING, @@ -238,7 +238,7 @@ pub const RESPValue = union(RESPType) { } } - pub fn toJS(self: *RESPValue, globalObject: *JSC.JSGlobalObject) bun.JSError!JSC.JSValue { + pub fn toJS(self: *RESPValue, globalObject: *jsc.JSGlobalObject) bun.JSError!jsc.JSValue { return self.toJSWithOptions(globalObject, .{}); } @@ -246,43 +246,43 @@ pub const RESPValue = union(RESPType) { return_as_buffer: bool = false, }; - fn valkeyStrToJSValue(globalObject: *JSC.JSGlobalObject, str: []const u8, options: *const ToJSOptions) bun.JSError!JSC.JSValue { + fn valkeyStrToJSValue(globalObject: *jsc.JSGlobalObject, str: []const u8, options: *const ToJSOptions) bun.JSError!jsc.JSValue { if (options.return_as_buffer) { // TODO: handle values > 4.7 GB - const buf = try JSC.ArrayBuffer.createBuffer(globalObject, str); + const buf = try jsc.ArrayBuffer.createBuffer(globalObject, str); return buf.toJS(globalObject); } else { return bun.String.createUTF8ForJS(globalObject, str); } } - pub fn toJSWithOptions(self: *RESPValue, globalObject: *JSC.JSGlobalObject, options: ToJSOptions) bun.JSError!JSC.JSValue { + pub fn toJSWithOptions(self: *RESPValue, globalObject: *jsc.JSGlobalObject, options: ToJSOptions) bun.JSError!jsc.JSValue { switch (self.*) { .SimpleString => |str| return valkeyStrToJSValue(globalObject, str, &options), .Error => |str| return valkeyErrorToJS(globalObject, str, RedisError.InvalidResponse), - .Integer => |int| return JSC.JSValue.jsNumber(int), + .Integer => |int| return jsc.JSValue.jsNumber(int), .BulkString => |maybe_str| { if (maybe_str) |str| { return valkeyStrToJSValue(globalObject, str, &options); } else { - return JSC.JSValue.jsNull(); + return jsc.JSValue.jsNull(); } }, .Array => |array| { - var js_array = try JSC.JSValue.createEmptyArray(globalObject, array.len); + var js_array = try jsc.JSValue.createEmptyArray(globalObject, array.len); for (array, 0..) |*item, i| { const js_item = try item.toJSWithOptions(globalObject, options); try js_array.putIndex(globalObject, @intCast(i), js_item); } return js_array; }, - .Null => return JSC.JSValue.jsNull(), - .Double => |d| return JSC.JSValue.jsNumber(d), - .Boolean => |b| return JSC.JSValue.jsBoolean(b), + .Null => return jsc.JSValue.jsNull(), + .Double => |d| return jsc.JSValue.jsNumber(d), + .Boolean => |b| return jsc.JSValue.jsBoolean(b), .BlobError => |str| return valkeyErrorToJS(globalObject, str, RedisError.InvalidBlobError), .VerbatimString => |verbatim| return valkeyStrToJSValue(globalObject, verbatim.content, &options), .Map => |entries| { - var js_obj = JSC.JSValue.createEmptyObjectWithNullPrototype(globalObject); + var js_obj = jsc.JSValue.createEmptyObjectWithNullPrototype(globalObject); for (entries) |*entry| { const js_key = try entry.key.toJSWithOptions(globalObject, .{}); var key_str = try js_key.toBunString(globalObject); @@ -294,7 +294,7 @@ pub const RESPValue = union(RESPType) { return js_obj; }, .Set => |set| { - var js_array = try JSC.JSValue.createEmptyArray(globalObject, set.len); + var js_array = try jsc.JSValue.createEmptyArray(globalObject, set.len); for (set, 0..) |*item, i| { const js_item = try item.toJSWithOptions(globalObject, options); try js_array.putIndex(globalObject, @intCast(i), js_item); @@ -307,14 +307,14 @@ pub const RESPValue = union(RESPType) { return try attribute.value.toJSWithOptions(globalObject, options); }, .Push => |push| { - var js_obj = JSC.JSValue.createEmptyObjectWithNullPrototype(globalObject); + var js_obj = jsc.JSValue.createEmptyObjectWithNullPrototype(globalObject); // Add the push type const kind_str = try bun.String.createUTF8ForJS(globalObject, push.kind); js_obj.put(globalObject, "type", kind_str); // Add the data as an array - var data_array = try JSC.JSValue.createEmptyArray(globalObject, push.data.len); + var data_array = try jsc.JSValue.createEmptyArray(globalObject, push.data.len); for (push.data, 0..) |*item, i| { const js_item = try item.toJSWithOptions(globalObject, options); try data_array.putIndex(globalObject, @intCast(i), js_item); @@ -326,7 +326,7 @@ pub const RESPValue = union(RESPType) { .BigNumber => |str| { // Try to parse as number if possible if (std.fmt.parseInt(i64, str, 10)) |int| { - return JSC.JSValue.jsNumber(int); + return jsc.JSValue.jsNumber(int); } else |_| { // If it doesn't fit in an i64, return as string return bun.String.createUTF8ForJS(globalObject, str); @@ -660,5 +660,5 @@ pub const Attribute = struct { const std = @import("std"); const bun = @import("bun"); -const JSC = bun.JSC; const String = bun.String; +const jsc = bun.jsc; diff --git a/src/watcher/INotifyWatcher.zig b/src/watcher/INotifyWatcher.zig index 372472fcaf..7840275c24 100644 --- a/src/watcher/INotifyWatcher.zig +++ b/src/watcher/INotifyWatcher.zig @@ -62,25 +62,25 @@ pub const Event = extern struct { } }; -pub fn watchPath(this: *INotifyWatcher, pathname: [:0]const u8) bun.JSC.Maybe(EventListIndex) { +pub fn watchPath(this: *INotifyWatcher, pathname: [:0]const u8) bun.jsc.Maybe(EventListIndex) { bun.assert(this.loaded); const old_count = this.watch_count.fetchAdd(1, .release); defer if (old_count == 0) Futex.wake(&this.watch_count, 10); const watch_file_mask = IN.EXCL_UNLINK | IN.MOVE_SELF | IN.DELETE_SELF | IN.MOVED_TO | IN.MODIFY; const rc = system.inotify_add_watch(this.fd.cast(), pathname, watch_file_mask); log("inotify_add_watch({}) = {}", .{ this.fd, rc }); - return bun.JSC.Maybe(EventListIndex).errnoSysP(rc, .watch, pathname) orelse + return bun.jsc.Maybe(EventListIndex).errnoSysP(rc, .watch, pathname) orelse .{ .result = rc }; } -pub fn watchDir(this: *INotifyWatcher, pathname: [:0]const u8) bun.JSC.Maybe(EventListIndex) { +pub fn watchDir(this: *INotifyWatcher, pathname: [:0]const u8) bun.jsc.Maybe(EventListIndex) { bun.assert(this.loaded); const old_count = this.watch_count.fetchAdd(1, .release); defer if (old_count == 0) Futex.wake(&this.watch_count, 10); const watch_dir_mask = IN.EXCL_UNLINK | IN.DELETE | IN.DELETE_SELF | IN.CREATE | IN.MOVE_SELF | IN.ONLYDIR | IN.MOVED_TO; const rc = system.inotify_add_watch(this.fd.cast(), pathname, watch_dir_mask); log("inotify_add_watch({}) = {}", .{ this.fd, rc }); - return bun.JSC.Maybe(EventListIndex).errnoSysP(rc, .watch, pathname) orelse + return bun.jsc.Maybe(EventListIndex).errnoSysP(rc, .watch, pathname) orelse .{ .result = rc }; } @@ -104,7 +104,7 @@ pub fn init(this: *INotifyWatcher, _: []const u8) !void { log("{} init", .{this.fd}); } -pub fn read(this: *INotifyWatcher) bun.JSC.Maybe([]const *align(1) Event) { +pub fn read(this: *INotifyWatcher) bun.jsc.Maybe([]const *align(1) Event) { bun.assert(this.loaded); // This is what replit does as of Jaunary 2023. // 1) CREATE .http.ts.3491171321~ @@ -226,7 +226,7 @@ pub fn stop(this: *INotifyWatcher) void { } /// Repeatedly called by the main watcher until the watcher is terminated. -pub fn watchLoopCycle(this: *bun.Watcher) bun.JSC.Maybe(void) { +pub fn watchLoopCycle(this: *bun.Watcher) bun.jsc.Maybe(void) { defer Output.flush(); var events = switch (this.platform.read()) { diff --git a/src/watcher/KEventWatcher.zig b/src/watcher/KEventWatcher.zig index 7ca9e2037e..4686bd2efa 100644 --- a/src/watcher/KEventWatcher.zig +++ b/src/watcher/KEventWatcher.zig @@ -33,7 +33,7 @@ pub fn watchEventFromKEvent(kevent: KEvent) Watcher.Event { }; } -pub fn watchLoopCycle(this: *Watcher) bun.JSC.Maybe(void) { +pub fn watchLoopCycle(this: *Watcher) bun.jsc.Maybe(void) { const fd: bun.FD = this.platform.fd.unwrap() orelse @panic("KEventWatcher has an invalid file descriptor"); diff --git a/src/watcher/WindowsWatcher.zig b/src/watcher/WindowsWatcher.zig index 5b117a92bc..6523997d7b 100644 --- a/src/watcher/WindowsWatcher.zig +++ b/src/watcher/WindowsWatcher.zig @@ -38,7 +38,7 @@ const DirWatcher = struct { dirHandle: w.HANDLE, // invalidates any EventIterators - fn prepare(this: *DirWatcher) bun.JSC.Maybe(void) { + fn prepare(this: *DirWatcher) bun.jsc.Maybe(void) { const filter: w.FileNotifyChangeFilter = .{ .file_name = true, .dir_name = true, .last_write = true, .creation = true }; if (w.kernel32.ReadDirectoryChangesW(this.dirHandle, &this.buf, this.buf.len, 1, filter, null, &this.overlapped, null) == 0) { const err = w.kernel32.GetLastError(); @@ -140,7 +140,7 @@ const Timeout = enum(w.DWORD) { }; // wait until new events are available -pub fn next(this: *WindowsWatcher, timeout: Timeout) bun.JSC.Maybe(?EventIterator) { +pub fn next(this: *WindowsWatcher, timeout: Timeout) bun.jsc.Maybe(?EventIterator) { switch (this.watcher.prepare()) { .err => |err| { log("prepare() returned error", .{}); @@ -197,7 +197,7 @@ pub fn stop(this: *WindowsWatcher) void { w.CloseHandle(this.iocp); } -pub fn watchLoopCycle(this: *bun.Watcher) bun.JSC.Maybe(void) { +pub fn watchLoopCycle(this: *bun.Watcher) bun.jsc.Maybe(void) { const buf = &this.platform.buf; const base_idx = this.platform.base_idx; diff --git a/src/which_npm_client.zig b/src/which_npm_client.zig index 2c188a1822..c7350fb4ed 100644 --- a/src/which_npm_client.zig +++ b/src/which_npm_client.zig @@ -7,5 +7,6 @@ pub const NPMClient = struct { }; }; +const string = []const u8; + const bun = @import("bun"); -const string = bun.string; diff --git a/src/windows.zig b/src/windows.zig index c5ca2b1fa5..0406d6edba 100644 --- a/src/windows.zig +++ b/src/windows.zig @@ -3218,7 +3218,7 @@ pub const INPUT_RECORD = extern struct { }; fn Bun__UVSignalHandle__init( - global: *bun.JSC.JSGlobalObject, + global: *bun.jsc.JSGlobalObject, signal_num: i32, callback: *const fn (sig: *libuv.uv_signal_t, num: c_int) callconv(.C) void, ) callconv(.C) ?*libuv.uv_signal_t { @@ -3492,7 +3492,7 @@ const FILE_DISPOSITION_ON_CLOSE: ULONG = 0x00000008; const FILE_DISPOSITION_IGNORE_READONLY_ATTRIBUTE: ULONG = 0x00000010; // Copy-paste of the standard library function except without unreachable. -pub fn DeleteFileBun(sub_path_w: []const u16, options: DeleteFileOptions) bun.JSC.Maybe(void) { +pub fn DeleteFileBun(sub_path_w: []const u16, options: DeleteFileOptions) bun.jsc.Maybe(void) { const create_options_flags: ULONG = if (options.remove_dir) FILE_DIRECTORY_FILE | FILE_OPEN_REPARSE_POINT else @@ -3535,7 +3535,7 @@ pub fn DeleteFileBun(sub_path_w: []const u16, options: DeleteFileOptions) bun.JS 0, ); bun.sys.syslog("NtCreateFile({}, DELETE) = {}", .{ bun.fmt.fmtPath(u16, sub_path_w, .{}), rc }); - if (bun.JSC.Maybe(void).errnoSys(rc, .open)) |err| { + if (bun.jsc.Maybe(void).errnoSys(rc, .open)) |err| { return err; } defer _ = bun.windows.CloseHandle(tmp_handle); @@ -3584,7 +3584,7 @@ pub fn DeleteFileBun(sub_path_w: []const u16, options: DeleteFileOptions) bun.JS ); bun.sys.syslog("NtSetInformationFile({}, DELETE) = {}", .{ bun.fmt.fmtPath(u16, sub_path_w, .{}), rc }); } - if (bun.JSC.Maybe(void).errnoSys(rc, .NtSetInformationFile)) |err| { + if (bun.jsc.Maybe(void).errnoSys(rc, .NtSetInformationFile)) |err| { return err; } diff --git a/src/workaround_missing_symbols.zig b/src/workaround_missing_symbols.zig index 62dcfd8fcb..8cb7201e9f 100644 --- a/src/workaround_missing_symbols.zig +++ b/src/workaround_missing_symbols.zig @@ -79,7 +79,7 @@ pub const darwin = struct { }; pub const windows = struct { /// Windows doesn't have memmem, so we need to implement it - /// This is used in src/string_immutable.zig + /// This is used in src/string/immutable.zig pub export fn memmem(haystack: ?[*]const u8, haystacklen: usize, needle: ?[*]const u8, needlelen: usize) ?[*]const u8 { // Handle null pointers if (haystack == null or needle == null) return null; diff --git a/src/zlib.zig b/src/zlib.zig index 33604ad76a..b869a5ebdf 100644 --- a/src/zlib.zig +++ b/src/zlib.zig @@ -929,10 +929,11 @@ pub const ZlibCompressorArrayList = struct { } }; -const bun = @import("bun"); -const mimalloc = @import("./allocators/mimalloc.zig"); const std = @import("std"); +const bun = @import("bun"); +const mimalloc = bun.mimalloc; + const internal = @import("zlib-internal"); const DataType = @import("zlib-internal").DataType; const zStream_struct = @import("zlib-internal").zStream_struct;