diff options
Diffstat (limited to 'src/javascript')
36 files changed, 13853 insertions, 687 deletions
diff --git a/src/javascript/jsc/api/router.zig b/src/javascript/jsc/api/router.zig index 2e2588e5a..e8ef4dc09 100644 --- a/src/javascript/jsc/api/router.zig +++ b/src/javascript/jsc/api/router.zig @@ -39,17 +39,17 @@ script_src_buf_writer: ScriptSrcStream = undefined, pub fn importRoute( this: *Router, - _: js.JSContextRef, + ctx: js.JSContextRef, _: js.JSObjectRef, _: js.JSObjectRef, _: []const js.JSValueRef, _: js.ExceptionRef, ) js.JSObjectRef { - const prom = JSC.JSModuleLoader.loadAndEvaluateModule(VirtualMachine.vm.global, &ZigString.init(this.route.file_path)); + const prom = JSC.JSModuleLoader.loadAndEvaluateModule(ctx.ptr(), &ZigString.init(this.route.file_path)); VirtualMachine.vm.tick(); - return prom.result(VirtualMachine.vm.global.vm()).asRef(); + return prom.result(ctx.ptr().vm()).asRef(); } pub fn match( @@ -69,9 +69,9 @@ pub fn match( return matchFetchEvent(ctx, To.Zig.ptr(FetchEvent, arguments[0]), exception); } - if (js.JSValueIsString(ctx, arguments[0])) { - return matchPathName(ctx, arguments[0], exception); - } + // if (js.JSValueIsString(ctx, arguments[0])) { + // return matchPathName(ctx, arguments[0], exception); + // } if (js.JSValueIsObjectOfClass(ctx, arguments[0], Request.Class.get().*)) { return matchRequest(ctx, To.Zig.ptr(Request, arguments[0]), exception); @@ -88,20 +88,6 @@ fn matchRequest( return createRouteObject(ctx, request.request_context, exception); } -fn matchPathNameString( - _: js.JSContextRef, - _: string, - _: js.ExceptionRef, -) js.JSObjectRef {} - -fn matchPathName( - _: js.JSContextRef, - _: js.JSStringRef, - _: js.ExceptionRef, -) js.JSObjectRef { - return null; -} - fn matchFetchEvent( ctx: js.JSContextRef, fetch_event: *const FetchEvent, @@ -274,12 +260,12 @@ pub const Instance = NewClass( pub fn getFilePath( this: *Router, - _: js.JSContextRef, + ctx: js.JSContextRef, _: js.JSObjectRef, _: js.JSStringRef, _: js.ExceptionRef, ) js.JSValueRef { - return ZigString.init(this.route.file_path).toValue(VirtualMachine.vm.global).asRef(); + return ZigString.init(this.route.file_path).toValue(ctx.ptr()).asRef(); } pub fn finalize( @@ -292,22 +278,22 @@ pub fn finalize( pub fn getPathname( this: *Router, - _: js.JSContextRef, + ctx: js.JSContextRef, _: js.JSObjectRef, _: js.JSStringRef, _: js.ExceptionRef, ) js.JSValueRef { - return ZigString.init(this.route.pathname).toValue(VirtualMachine.vm.global).asRef(); + return ZigString.init(this.route.pathname).toValue(ctx.ptr()).asRef(); } pub fn getRoute( this: *Router, - _: js.JSContextRef, + ctx: js.JSContextRef, _: js.JSObjectRef, _: js.JSStringRef, _: js.ExceptionRef, ) js.JSValueRef { - return ZigString.init(this.route.name).toValue(VirtualMachine.vm.global).asRef(); + return ZigString.init(this.route.name).toValue(ctx.ptr()).asRef(); } const KindEnum = struct { @@ -332,17 +318,17 @@ const KindEnum = struct { pub fn getKind( this: *Router, - _: js.JSContextRef, + ctx: js.JSContextRef, _: js.JSObjectRef, _: js.JSStringRef, _: js.ExceptionRef, ) js.JSValueRef { - return KindEnum.init(this.route.name).toValue(VirtualMachine.vm.global).asRef(); + return KindEnum.init(this.route.name).toValue(ctx.ptr()).asRef(); } threadlocal var query_string_values_buf: [256]string = undefined; threadlocal var query_string_value_refs_buf: [256]ZigString = undefined; -pub fn createQueryObject(_: js.JSContextRef, map: *QueryStringMap, _: js.ExceptionRef) callconv(.C) js.JSValueRef { +pub fn createQueryObject(ctx: js.JSContextRef, map: *QueryStringMap, _: js.ExceptionRef) callconv(.C) js.JSValueRef { const QueryObjectCreator = struct { query: *QueryStringMap, pub fn create(this: *@This(), obj: *JSObject, global: *JSGlobalObject) void { @@ -369,7 +355,7 @@ pub fn createQueryObject(_: js.JSContextRef, map: *QueryStringMap, _: js.Excepti var creator = QueryObjectCreator{ .query = map }; - var value = JSObject.createWithInitializer(QueryObjectCreator, &creator, VirtualMachine.vm.global, map.getNameCount()); + var value = JSObject.createWithInitializer(QueryObjectCreator, &creator, ctx.ptr(), map.getNameCount()); return value.asRef(); } @@ -440,7 +426,7 @@ pub fn getParams( if (this.param_map) |*map| { return createQueryObject(ctx, map, exception); } else { - return JSValue.createEmptyObject(VirtualMachine.vm.global, 0).asRef(); + return JSValue.createEmptyObject(ctx.ptr(), 0).asRef(); } } @@ -473,6 +459,6 @@ pub fn getQuery( if (this.query_string_map) |*map| { return createQueryObject(ctx, map, exception); } else { - return JSValue.createEmptyObject(VirtualMachine.vm.global, 0).asRef(); + return JSValue.createEmptyObject(ctx.ptr(), 0).asRef(); } } diff --git a/src/javascript/jsc/base.zig b/src/javascript/jsc/base.zig index f51eb86d9..cf2ed1bad 100644 --- a/src/javascript/jsc/base.zig +++ b/src/javascript/jsc/base.zig @@ -13,7 +13,9 @@ const C = _global.C; const JavaScript = @import("./javascript.zig"); const ResolveError = JavaScript.ResolveError; const BuildError = JavaScript.BuildError; +const JSC = @import("../../jsc.zig"); const WebCore = @import("./webcore/response.zig"); +const Test = @import("./test/jest.zig"); const Fetch = WebCore.Fetch; const Response = WebCore.Response; const Request = WebCore.Request; @@ -128,6 +130,190 @@ pub const To = struct { }; } + pub fn withType(comptime Type: type, value: Type, context: JSC.C.JSContextRef, exception: JSC.C.ExceptionRef) JSC.C.JSValueRef { + return withTypeClone(Type, value, context, exception, false); + } + + pub fn withTypeClone(comptime Type: type, value: Type, context: JSC.C.JSContextRef, exception: JSC.C.ExceptionRef, clone: bool) JSC.C.JSValueRef { + if (comptime std.meta.trait.isNumber(Type)) { + return JSC.JSValue.jsNumberWithType(Type, value).asRef(); + } + + var zig_str: JSC.ZigString = undefined; + + return switch (comptime Type) { + void => JSC.C.JSValueMakeUndefined(context), + bool => JSC.C.JSValueMakeBoolean(context, value), + []const u8, [:0]const u8, [*:0]const u8, []u8, [:0]u8, [*:0]u8 => brk: { + zig_str = ZigString.init(value); + const val = zig_str.toValueAuto(context.ptr()); + + break :brk val.asObjectRef(); + }, + []const PathString, []const []const u8, []const []u8, [][]const u8, [][:0]const u8, [][:0]u8 => { + var zig_strings_buf: [32]ZigString = undefined; + var zig_strings: []ZigString = if (value.len < 32) + &zig_strings_buf + else + (_global.default_allocator.alloc(ZigString, value.len) catch unreachable); + defer if (zig_strings.ptr != &zig_strings_buf) + _global.default_allocator.free(zig_strings); + + for (value) |path_string, i| { + if (comptime Type == []const PathString) { + zig_strings[i] = ZigString.init(path_string.slice()); + } else { + zig_strings[i] = ZigString.init(path_string); + } + } + + var array = JSC.JSValue.createStringArray(context.ptr(), zig_strings.ptr, zig_strings.len, clone).asObjectRef(); + + if (clone) { + for (value) |path_string| { + if (comptime Type == []const PathString) { + _global.default_allocator.free(path_string.slice()); + } else { + _global.default_allocator.free(path_string); + } + } + _global.default_allocator.free(value); + } + + return array; + }, + + JSC.C.JSValueRef => value, + + else => { + const Info: std.builtin.TypeInfo = comptime @typeInfo(Type); + if (comptime Info == .Enum) { + const Enum: std.builtin.TypeInfo.Enum = Info.Enum; + if (comptime !std.meta.trait.isNumber(Enum.tag_type)) { + zig_str = JSC.ZigString.init(@tagName(value)); + return zig_str.toValue(context.ptr()).asObjectRef(); + } + } + + // Recursion can stack overflow here + if (comptime std.meta.trait.isSlice(Type)) { + const Child = std.meta.Child(Type); + + const prefill = 32; + if (value.len <= prefill) { + var array: [prefill]JSC.C.JSValueRef = undefined; + var i: u8 = 0; + const len = @minimum(@intCast(u8, value.len), prefill); + while (i < len and exception.* == null) : (i += 1) { + array[i] = if (comptime Child == JSC.C.JSValueRef) + value[i] + else + To.JS.withType(Child, value[i], context, exception); + } + + if (exception.* != null) { + return null; + } + + // TODO: this function copies to a MarkedArgumentsBuffer + // That copy is unnecessary. + const obj = JSC.C.JSObjectMakeArray(context, len, &array, exception); + + if (exception.* != null) { + return null; + } + return obj; + } + + { + var array = _global.default_allocator.alloc(JSC.C.JSValueRef, value.len) catch unreachable; + defer _global.default_allocator.free(array); + var i: usize = 0; + while (i < value.len and exception.* == null) : (i += 1) { + array[i] = if (comptime Child == JSC.C.JSValueRef) + value[i] + else + To.JS.withType(Child, value[i], context, exception); + } + + if (exception.* != null) { + return null; + } + + // TODO: this function copies to a MarkedArgumentsBuffer + // That copy is unnecessary. + const obj = JSC.C.JSObjectMakeArray(context, value.len, array.ptr, exception); + if (exception.* != null) { + return null; + } + + return obj; + } + } + + if (comptime std.meta.trait.isZigString(Type)) { + zig_str = JSC.ZigString.init(value); + return zig_str.toValue(context.ptr()).asObjectRef(); + } + + if (comptime Info == .Pointer) { + const Child = comptime std.meta.Child(Type); + if (comptime std.meta.trait.isContainer(Child) and @hasDecl(Child, "Class") and @hasDecl(Child.Class, "isJavaScriptCoreClass")) { + return Child.Class.make(context, value); + } + } + + if (comptime Info == .Struct) { + if (comptime @hasDecl(Type, "Class") and @hasDecl(Type.Class, "isJavaScriptCoreClass")) { + if (comptime !@hasDecl(Type, "finalize")) { + @compileError(comptime std.fmt.comptimePrint("JSC class {s} must implement finalize to prevent memory leaks", .{Type.Class.name})); + } + + if (comptime !@hasDecl(Type, "toJS")) { + var val = _global.default_allocator.create(Type) catch unreachable; + val.* = value; + return Type.Class.make(context, val); + } + } + } + + const res = value.toJS(context, exception); + + if (@TypeOf(res) == JSC.C.JSValueRef) { + return res; + } else if (@TypeOf(res) == JSC.JSValue) { + return res.asObjectRef(); + } + }, + }; + } + + pub fn PropertyGetter( + comptime Type: type, + ) type { + return comptime fn ( + this: ObjectPtrType(Type), + ctx: js.JSContextRef, + _: js.JSValueRef, + _: js.JSStringRef, + exception: js.ExceptionRef, + ) js.JSValueRef; + } + + pub fn Getter(comptime Type: type, comptime field: std.meta.FieldEnum(Type)) PropertyGetter(Type) { + return struct { + pub fn rfn( + this: ObjectPtrType(Type), + ctx: js.JSContextRef, + _: js.JSValueRef, + _: js.JSStringRef, + exception: js.ExceptionRef, + ) js.JSValueRef { + return withType(std.meta.fieldInfo(Type, field).field_type, @field(this, @tagName(field)), ctx, exception); + } + }.rfn; + } + pub fn Callback( comptime ZigContextType: type, comptime ctxfn: fn ( @@ -150,7 +336,7 @@ pub const To = struct { ) callconv(.C) js.JSValueRef { if (comptime ZigContextType == anyopaque) { return ctxfn( - js.JSObjectGetPrivate(function) or js.jsObjectGetPrivate(thisObject), + js.JSObjectGetPrivate(function) orelse js.JSObjectGetPrivate(thisObject) orelse undefined, ctx, function, thisObject, @@ -232,86 +418,12 @@ pub const Properties = struct { pub const follow = "follow"; }; - pub const UTF16 = struct { - pub const module: []c_ushort = std.unicode.utf8ToUtf16LeStringLiteral(UTF8.module); - pub const globalThis: []c_ushort = std.unicode.utf8ToUtf16LeStringLiteral(UTF8.globalThis); - pub const exports: []c_ushort = std.unicode.utf8ToUtf16LeStringLiteral(UTF8.exports); - pub const log: []c_ushort = std.unicode.utf8ToUtf16LeStringLiteral(UTF8.log); - pub const debug: []c_ushort = std.unicode.utf8ToUtf16LeStringLiteral(UTF8.debug); - pub const info: []c_ushort = std.unicode.utf8ToUtf16LeStringLiteral(UTF8.info); - pub const error_: []c_ushort = std.unicode.utf8ToUtf16LeStringLiteral(UTF8.error_); - pub const warn: []c_ushort = std.unicode.utf8ToUtf16LeStringLiteral(UTF8.warn); - pub const console: []c_ushort = std.unicode.utf8ToUtf16LeStringLiteral(UTF8.console); - pub const require: []c_ushort = std.unicode.utf8ToUtf16LeStringLiteral(UTF8.require); - pub const description: []c_ushort = std.unicode.utf8ToUtf16LeStringLiteral(UTF8.description); - pub const name: []c_ushort = std.unicode.utf8ToUtf16LeStringLiteral(UTF8.name); - pub const initialize_bundled_module = std.unicode.utf8ToUtf16LeStringLiteral(UTF8.initialize_bundled_module); - pub const load_module_function: []c_ushort = std.unicode.utf8ToUtf16LeStringLiteral(UTF8.load_module_function); - pub const window: []c_ushort = std.unicode.utf8ToUtf16LeStringLiteral(UTF8.window); - pub const default: []c_ushort = std.unicode.utf8ToUtf16LeStringLiteral(UTF8.default); - pub const include: []c_ushort = std.unicode.utf8ToUtf16LeStringLiteral(UTF8.include); - - pub const GET: []c_ushort = std.unicode.utf8ToUtf16LeStringLiteral(UTF8.GET); - pub const PUT: []c_ushort = std.unicode.utf8ToUtf16LeStringLiteral(UTF8.PUT); - pub const POST: []c_ushort = std.unicode.utf8ToUtf16LeStringLiteral(UTF8.POST); - pub const PATCH: []c_ushort = std.unicode.utf8ToUtf16LeStringLiteral(UTF8.PATCH); - pub const HEAD: []c_ushort = std.unicode.utf8ToUtf16LeStringLiteral(UTF8.HEAD); - pub const OPTIONS: []c_ushort = std.unicode.utf8ToUtf16LeStringLiteral(UTF8.OPTIONS); - - pub const navigate: []c_ushort = std.unicode.utf8ToUtf16LeStringLiteral(UTF8.navigate); - pub const follow: []c_ushort = std.unicode.utf8ToUtf16LeStringLiteral(UTF8.follow); - }; - pub const Refs = struct { - pub var filepath: js.JSStringRef = undefined; - - pub var module: js.JSStringRef = undefined; - pub var globalThis: js.JSStringRef = undefined; - pub var exports: js.JSStringRef = undefined; - pub var log: js.JSStringRef = undefined; - pub var debug: js.JSStringRef = undefined; - pub var info: js.JSStringRef = undefined; - pub var error_: js.JSStringRef = undefined; - pub var warn: js.JSStringRef = undefined; - pub var console: js.JSStringRef = undefined; - pub var require: js.JSStringRef = undefined; - pub var description: js.JSStringRef = undefined; - pub var name: js.JSStringRef = undefined; - pub var initialize_bundled_module: js.JSStringRef = undefined; - pub var load_module_function: js.JSStringRef = undefined; - pub var window: js.JSStringRef = undefined; - pub var default: js.JSStringRef = undefined; - pub var include: js.JSStringRef = undefined; - pub var GET: js.JSStringRef = undefined; - pub var PUT: js.JSStringRef = undefined; - pub var POST: js.JSStringRef = undefined; - pub var PATCH: js.JSStringRef = undefined; - pub var HEAD: js.JSStringRef = undefined; - pub var OPTIONS: js.JSStringRef = undefined; - pub var empty_string_ptr = [_]u8{0}; pub var empty_string: js.JSStringRef = undefined; - - pub var navigate: js.JSStringRef = undefined; - pub var follow: js.JSStringRef = undefined; - - pub const env: js.JSStringRef = undefined; }; pub fn init() void { - inline for (std.meta.fieldNames(UTF8)) |name| { - @field(Refs, name) = js.JSStringCreateStatic( - @field(UTF8, name).ptr, - @field(UTF8, name).len, - ); - - if (comptime Environment.isDebug) { - std.debug.assert( - js.JSStringIsEqualToString(@field(Refs, name), @field(UTF8, name).ptr, @field(UTF8, name).len), - ); - } - } - Refs.empty_string = js.JSStringCreateWithUTF8CString(&Refs.empty_string_ptr); } }; @@ -720,6 +832,8 @@ pub const ClassOptions = struct { ts: d.ts.decl = d.ts.decl{ .empty = 0 }, }; +// work around a comptime bug + pub fn NewClass( comptime ZigType: type, comptime options: ClassOptions, @@ -728,13 +842,16 @@ pub fn NewClass( ) type { const read_only = options.read_only; const singleton = options.singleton; + _ = read_only; return struct { const name = options.name; + pub const isJavaScriptCoreClass = true; const ClassDefinitionCreator = @This(); const function_names = std.meta.fieldNames(@TypeOf(staticFunctions)); const function_name_literals = function_names; var function_name_refs: [function_names.len]js.JSStringRef = undefined; + var function_name_refs_set = false; var class_name_str = name[0.. :0].ptr; var static_functions = brk: { @@ -750,24 +867,10 @@ pub fn NewClass( ); break :brk funcs; }; - var instance_functions = std.mem.zeroes([function_names.len]js.JSObjectRef); const property_names = std.meta.fieldNames(@TypeOf(properties)); - var property_name_refs = std.mem.zeroes([property_names.len]js.JSStringRef); + var property_name_refs: [property_names.len]js.JSStringRef = undefined; + var property_name_refs_set: bool = false; const property_name_literals = property_names; - var static_properties = brk: { - var props: [property_names.len + 1]js.JSStaticValue = undefined; - std.mem.set( - js.JSStaticValue, - &props, - js.JSStaticValue{ - .name = @intToPtr([*c]const u8, 0), - .getProperty = null, - .setProperty = null, - .attributes = js.JSPropertyAttributes.kJSPropertyAttributeNone, - }, - ); - break :brk props; - }; pub var ref: js.JSClassRef = null; pub var loaded = false; @@ -822,8 +925,6 @@ pub fn NewClass( pub const Constructor = ConstructorWrapper.rfn; - pub const static_value_count = static_properties.len; - pub fn get() callconv(.C) [*c]js.JSClassRef { if (!loaded) { loaded = true; @@ -883,39 +984,6 @@ pub fn NewClass( return ClassGetter; } - pub fn getPropertyCallback( - ctx: js.JSContextRef, - obj: js.JSObjectRef, - prop: js.JSStringRef, - exception: js.ExceptionRef, - ) callconv(.C) js.JSValueRef { - var pointer = GetJSPrivateData(ZigType, obj) orelse return js.JSValueMakeUndefined(ctx); - - if (singleton) { - inline for (function_names) |_, i| { - if (js.JSStringIsEqual(prop, function_name_refs[i])) { - return instance_functions[i]; - } - } - unreachable; - } else { - inline for (property_names) |propname, i| { - if (js.JSStringIsEqual(prop, property_name_refs[i])) { - return @field( - properties, - propname, - )(pointer, ctx, obj, exception); - } - } - - if (comptime std.meta.trait.hasFn("onMissingProperty")(ZigType)) { - return pointer.onMissingProperty(ctx, obj, prop, exception); - } - } - - return js.JSValueMakeUndefined(ctx); - } - fn StaticProperty(comptime id: usize) type { return struct { pub fn getter( @@ -943,6 +1011,13 @@ pub fn NewClass( ); }, .Struct => { + comptime { + if (!@hasField(@TypeOf(@field(properties, property_names[id])), "get")) { + @compileError( + "Cannot get static property " ++ property_names[id] ++ " of " ++ name ++ " because it is a struct without a getter", + ); + } + } const func = @field( @field( properties, @@ -988,7 +1063,7 @@ pub fn NewClass( value: js.JSValueRef, exception: js.ExceptionRef, ) callconv(.C) bool { - var this = GetJSPrivateData(ZigType, obj) orelse return js.JSValueMakeUndefined(ctx); + var this = GetJSPrivateData(ZigType, obj) orelse return false; switch (comptime @typeInfo(@TypeOf(@field( properties, @@ -1180,6 +1255,41 @@ pub fn NewClass( return decl; } + pub fn getPropertyNames( + _: js.JSContextRef, + _: js.JSObjectRef, + props: js.JSPropertyNameAccumulatorRef, + ) callconv(.C) void { + if (comptime property_name_refs.len > 0) { + comptime var i: usize = 0; + if (!property_name_refs_set) { + property_name_refs_set =true; + inline while (i < property_name_refs.len) : (i += 1) { + property_name_refs[i] = js.JSStringCreateStatic(property_names[i].ptr, property_names[i].len); + } + comptime i = 0; + } + inline while (i < property_name_refs.len) : (i += 1) { + js.JSPropertyNameAccumulatorAddName(props, property_name_refs[i]); + } + } + + if (comptime function_name_refs.len > 0) { + comptime var j: usize = 0; + if (!function_name_refs_set) { + function_name_refs_set = true; + inline while (j < function_name_refs.len) : (j += 1) { + function_name_refs[j] = js.JSStringCreateStatic(function_names[j].ptr, function_names[j].len); + } + comptime j = 0; + } + + inline while (j < function_name_refs.len) : (j += 1) { + js.JSPropertyNameAccumulatorAddName(props, function_name_refs[j]); + } + } + } + // This should only be run at comptime pub fn typescriptClassDeclaration() d.ts.class { comptime var class = options.ts.class; @@ -1301,11 +1411,26 @@ pub fn NewClass( return comptime class; } + var static_properties = brk: { + var props: [property_names.len + 1]js.JSStaticValue = undefined; + std.mem.set( + js.JSStaticValue, + &props, + js.JSStaticValue{ + .name = @intToPtr([*c]const u8, 0), + .getProperty = null, + .setProperty = null, + .attributes = js.JSPropertyAttributes.kJSPropertyAttributeNone, + }, + ); + break :brk props; + }; + pub fn define() js.JSClassDefinition { var def = js.JSClassDefinition{ .version = 0, .attributes = js.JSClassAttributes.kJSClassAttributeNone, - .className = class_name_str, + .className = name.ptr[0..name.len :0], .parentClass = null, .staticValues = null, .staticFunctions = null, @@ -1322,58 +1447,59 @@ pub fn NewClass( .convertToType = null, }; - if (static_functions.len > 0) { - std.mem.set(js.JSStaticFunction, &static_functions, std.mem.zeroes(js.JSStaticFunction)); - var count: usize = 0; - inline for (function_name_literals) |_, i| { - switch (comptime @typeInfo(@TypeOf(@field(staticFunctions, function_names[i])))) { + // These workaround stage1 compiler bugs + var JSStaticValue_empty = std.mem.zeroes(js.JSStaticValue); + var count: usize = 0; + + if (comptime static_functions.len > 0) { + inline for (function_name_literals) |function_name_literal, i| { + _ = i; + switch (comptime @typeInfo(@TypeOf(@field(staticFunctions, function_name_literal)))) { .Struct => { - if (comptime strings.eqlComptime(function_names[i], "constructor")) { + if (comptime strings.eqlComptime(function_name_literal, "constructor")) { def.callAsConstructor = To.JS.Constructor(staticFunctions.constructor.rfn).rfn; - } else if (comptime strings.eqlComptime(function_names[i], "finalize")) { + } else if (comptime strings.eqlComptime(function_name_literal, "finalize")) { def.finalize = To.JS.Finalize(ZigType, staticFunctions.finalize.rfn).rfn; - } else if (comptime strings.eqlComptime(function_names[i], "call")) { + } else if (comptime strings.eqlComptime(function_name_literal, "call")) { def.callAsFunction = To.JS.Callback(ZigType, staticFunctions.call.rfn).rfn; - } else if (comptime strings.eqlComptime(function_names[i], "callAsFunction")) { - const ctxfn = @field(staticFunctions, function_names[i]).rfn; + } else if (comptime strings.eqlComptime(function_name_literal, "callAsFunction")) { + const ctxfn = @field(staticFunctions, function_name_literal).rfn; const Func: std.builtin.TypeInfo.Fn = @typeInfo(@TypeOf(ctxfn)).Fn; const PointerType = std.meta.Child(Func.args[0].arg_type.?); - var callback = if (Func.calling_convention == .C) ctxfn else To.JS.Callback( + def.callAsFunction = if (Func.calling_convention == .C) ctxfn else To.JS.Callback( PointerType, ctxfn, ).rfn; - - def.callAsFunction = callback; - } else if (comptime strings.eqlComptime(function_names[i], "hasProperty")) { + } else if (comptime strings.eqlComptime(function_name_literal, "hasProperty")) { def.hasProperty = @field(staticFunctions, "hasProperty").rfn; - } else if (comptime strings.eqlComptime(function_names[i], "getProperty")) { + } else if (comptime strings.eqlComptime(function_name_literal, "getProperty")) { def.getProperty = @field(staticFunctions, "getProperty").rfn; - } else if (comptime strings.eqlComptime(function_names[i], "setProperty")) { + } else if (comptime strings.eqlComptime(function_name_literal, "setProperty")) { def.setProperty = @field(staticFunctions, "setProperty").rfn; - } else if (comptime strings.eqlComptime(function_names[i], "deleteProperty")) { + } else if (comptime strings.eqlComptime(function_name_literal, "deleteProperty")) { def.deleteProperty = @field(staticFunctions, "deleteProperty").rfn; - } else if (comptime strings.eqlComptime(function_names[i], "getPropertyNames")) { + } else if (comptime strings.eqlComptime(function_name_literal, "getPropertyNames")) { def.getPropertyNames = @field(staticFunctions, "getPropertyNames").rfn; + } else if (comptime strings.eqlComptime(function_name_literal, "convertToType")) { + def.convertToType = @field(staticFunctions, "convertToType").rfn; } else { - const CtxField = @field(staticFunctions, function_names[i]); + const CtxField = comptime @field(staticFunctions, function_name_literal); if (comptime !@hasField(@TypeOf(CtxField), "rfn")) { - @compileError("Expected " ++ options.name ++ "." ++ function_names[i] ++ " to have .rfn"); + @compileError("Expected " ++ options.name ++ "." ++ function_name_literal ++ " to have .rfn"); } const ctxfn = CtxField.rfn; const Func: std.builtin.TypeInfo.Fn = @typeInfo(@TypeOf(ctxfn)).Fn; const PointerType = if (Func.args[0].arg_type.? == void) void else std.meta.Child(Func.args[0].arg_type.?); - var callback = if (Func.calling_convention == .C) ctxfn else To.JS.Callback( - PointerType, - ctxfn, - ).rfn; - static_functions[count] = js.JSStaticFunction{ .name = (function_names[i][0.. :0]).ptr, - .callAsFunction = callback, + .callAsFunction = if (Func.calling_convention == .C) ctxfn else To.JS.Callback( + PointerType, + ctxfn, + ).rfn, .attributes = comptime if (read_only) js.JSPropertyAttributes.kJSPropertyAttributeReadOnly else js.JSPropertyAttributes.kJSPropertyAttributeNone, }; @@ -1381,27 +1507,30 @@ pub fn NewClass( } }, .Fn => { - if (comptime strings.eqlComptime(function_names[i], "constructor")) { + if (comptime strings.eqlComptime(function_name_literal, "constructor")) { def.callAsConstructor = To.JS.Constructor(staticFunctions.constructor).rfn; - } else if (comptime strings.eqlComptime(function_names[i], "finalize")) { + } else if (comptime strings.eqlComptime(function_name_literal, "finalize")) { def.finalize = To.JS.Finalize(ZigType, staticFunctions.finalize).rfn; - } else if (comptime strings.eqlComptime(function_names[i], "call")) { + } else if (comptime strings.eqlComptime(function_name_literal, "call")) { def.callAsFunction = To.JS.Callback(ZigType, staticFunctions.call).rfn; + } else if (comptime strings.eqlComptime(function_name_literal, "getPropertyNames")) { + def.getPropertyNames = To.JS.Callback(ZigType, staticFunctions.getPropertyNames).rfn; + } else if (comptime strings.eqlComptime(function_name_literal, "hasInstance")) { + def.hasInstance = staticFunctions.hasInstance; } else { - var callback = To.JS.Callback( - ZigType, - @field(staticFunctions, function_names[i]), - ).rfn; static_functions[count] = js.JSStaticFunction{ .name = (function_names[i][0.. :0]).ptr, - .callAsFunction = callback, + .callAsFunction = To.JS.Callback( + ZigType, + @field(staticFunctions, function_name_literal), + ).rfn, .attributes = comptime if (read_only) js.JSPropertyAttributes.kJSPropertyAttributeReadOnly else js.JSPropertyAttributes.kJSPropertyAttributeNone, }; count += 1; } }, - else => unreachable, + else => {}, } // if (singleton) { @@ -1413,13 +1542,9 @@ pub fn NewClass( def.staticFunctions = static_functions[0..count].ptr; } - if (property_names.len > 0) { - inline for (comptime property_name_literals) |prop_name, i| { - property_name_refs[i] = js.JSStringCreateStatic( - prop_name.ptr, - prop_name.len, - ); - static_properties[i] = std.mem.zeroes(js.JSStaticValue); + if (comptime property_names.len > 0) { + inline for (property_name_literals) |_, i| { + static_properties[i] = JSStaticValue_empty; static_properties[i].getProperty = StaticProperty(i).getter; const field = comptime @field(properties, property_names[i]); @@ -1429,7 +1554,7 @@ pub fn NewClass( } static_properties[i].name = property_names[i][0.. :0].ptr; } - def.staticValues = (&static_properties); + def.staticValues = &static_properties; } def.className = class_name_str; @@ -1443,38 +1568,97 @@ pub fn NewClass( def.callAsFunction = throwInvalidFunctionError; } - if (!singleton) + if (def.getPropertyNames == null) { + def.getPropertyNames = getPropertyNames; + } + + if (!singleton and def.hasInstance == null) def.hasInstance = customHasInstance; return def; } }; } +const JSValue = JSC.JSValue; +const ZigString = JSC.ZigString; + +pub const PathString = _global.PathString; + threadlocal var error_args: [1]js.JSValueRef = undefined; pub fn JSError( - allocator: std.mem.Allocator, + _: std.mem.Allocator, comptime fmt: string, args: anytype, ctx: js.JSContextRef, exception: ExceptionValueRef, ) void { + @setCold(true); + if (comptime std.meta.fields(@TypeOf(args)).len == 0) { - var message = js.JSStringCreateWithUTF8CString(fmt[0.. :0]); - defer js.JSStringRelease(message); - error_args[0] = js.JSValueMakeString(ctx, message); + var zig_str = JSC.ZigString.init(fmt); + zig_str.detectEncoding(); + error_args[0] = zig_str.toValueAuto(ctx.ptr()).asObjectRef(); exception.* = js.JSObjectMakeError(ctx, 1, &error_args, null); } else { - var buf = std.fmt.allocPrintZ(allocator, fmt, args) catch unreachable; - defer allocator.free(buf); + var buf = std.fmt.allocPrint(default_allocator, fmt, args) catch unreachable; + var zig_str = JSC.ZigString.init(buf); + zig_str.detectEncoding(); - var message = js.JSStringCreateWithUTF8CString(buf); - defer js.JSStringRelease(message); - - error_args[0] = js.JSValueMakeString(ctx, message); + error_args[0] = zig_str.toValueGC(ctx.ptr()).asObjectRef(); exception.* = js.JSObjectMakeError(ctx, 1, &error_args, null); } } +pub fn throwTypeError( + code: JSC.Node.ErrorCode, + comptime fmt: string, + args: anytype, + ctx: js.JSContextRef, + exception: ExceptionValueRef, +) void { + exception.* = toTypeError(code, fmt, args, ctx).asObjectRef(); +} + +pub fn toTypeError( + code: JSC.Node.ErrorCode, + comptime fmt: string, + args: anytype, + ctx: js.JSContextRef, +) JSC.JSValue { + @setCold(true); + var zig_str: JSC.ZigString = undefined; + if (comptime std.meta.fields(@TypeOf(args)).len == 0) { + zig_str = JSC.ZigString.init(fmt); + zig_str.detectEncoding(); + } else { + var buf = std.fmt.allocPrint(default_allocator, fmt, args) catch unreachable; + zig_str = JSC.ZigString.init(buf); + zig_str.detectEncoding(); + zig_str.mark(); + } + const code_str = ZigString.init(@tagName(code)); + return JSC.JSValue.createTypeError(&zig_str, &code_str, ctx.ptr()); +} + +pub fn throwInvalidArguments( + comptime fmt: string, + args: anytype, + ctx: js.JSContextRef, + exception: ExceptionValueRef, +) void { + @setCold(true); + return throwTypeError(JSC.Node.ErrorCode.ERR_INVALID_ARG_TYPE, fmt, args, ctx, exception); +} + +pub fn toInvalidArguments( + comptime fmt: string, + args: anytype, + ctx: js.JSContextRef, +) JSC.JSValue { + @setCold(true); + return toTypeError(JSC.Node.ErrorCode.ERR_INVALID_ARG_TYPE, fmt, args, ctx); +} + pub fn getAllocator(_: js.JSContextRef) std.mem.Allocator { return default_allocator; } @@ -1491,14 +1675,78 @@ pub const ArrayBuffer = struct { typed_array_type: js.JSTypedArrayType, - pub inline fn slice(this: *const ArrayBuffer) []u8 { + encoding: JSC.Node.Encoding = JSC.Node.Encoding.utf8, + + pub const Stream = std.io.FixedBufferStream([]u8); + + pub inline fn stream(this: ArrayBuffer) Stream { + return Stream{ .pos = 0, .buf = this.slice() }; + } + + pub fn fromTypedArray(ctx: JSC.C.JSContextRef, value: JSC.JSValue, exception: JSC.C.ExceptionRef) ArrayBuffer { + return ArrayBuffer{ + .byte_len = @truncate(u32, JSC.C.JSObjectGetTypedArrayByteLength(ctx, value.asObjectRef(), exception)), + .offset = @truncate(u32, JSC.C.JSObjectGetTypedArrayByteOffset(ctx, value.asObjectRef(), exception)), + .ptr = @ptrCast([*]u8, JSC.C.JSObjectGetTypedArrayBytesPtr(ctx, value.asObjectRef(), exception).?), + // TODO + .typed_array_type = js.JSTypedArrayType.kJSTypedArrayTypeUint8Array, + .len = @truncate(u32, JSC.C.JSObjectGetTypedArrayLength(ctx, value.asObjectRef(), exception)), + }; + } + + pub fn fromArrayBuffer(ctx: JSC.C.JSContextRef, value: JSC.JSValue, exception: JSC.C.ExceptionRef) ArrayBuffer { + var buffer = ArrayBuffer{ + .byte_len = @truncate(u32, JSC.C.JSObjectGetArrayBufferByteLength(ctx, value.asObjectRef(), exception)), + .ptr = @ptrCast([*]u8, JSC.C.JSObjectGetArrayBufferBytesPtr(ctx, value.asObjectRef(), exception).?), + // TODO + .typed_array_type = js.JSTypedArrayType.kJSTypedArrayTypeUint8Array, + .len = 0, + .offset = 0, + }; + buffer.len = buffer.byte_len; + return buffer; + } + + pub inline fn slice(this: *const @This()) []u8 { return this.ptr[this.offset .. this.offset + this.byte_len]; } }; pub const MarkedArrayBuffer = struct { buffer: ArrayBuffer, - allocator: std.mem.Allocator, + allocator: ?std.mem.Allocator = null, + + pub const Stream = ArrayBuffer.Stream; + + pub inline fn stream(this: *MarkedArrayBuffer) Stream { + return this.buffer.stream(); + } + + pub fn fromTypedArray(ctx: JSC.C.JSContextRef, value: JSC.JSValue, exception: JSC.C.ExceptionRef) MarkedArrayBuffer { + return MarkedArrayBuffer{ + .allocator = null, + .buffer = ArrayBuffer.fromTypedArray(ctx, value, exception), + }; + } + pub fn fromArrayBuffer(ctx: JSC.C.JSContextRef, value: JSC.JSValue, exception: JSC.C.ExceptionRef) MarkedArrayBuffer { + return MarkedArrayBuffer{ + .allocator = null, + .buffer = ArrayBuffer.fromArrayBuffer(ctx, value, exception), + }; + } + + pub fn fromString(str: []const u8, allocator: std.mem.Allocator) !MarkedArrayBuffer { + var buf = try allocator.dupe(u8, str); + return MarkedArrayBuffer.fromBytes(buf, allocator, js.JSTypedArrayType.kJSTypedArrayTypeUint8Array); + } + + pub fn fromJS(global: *JSC.JSGlobalObject, value: JSC.JSValue, exception: JSC.C.ExceptionRef) ?MarkedArrayBuffer { + return switch (value.jsType()) { + JSC.JSValue.JSType.Uint16Array, JSC.JSValue.JSType.Uint32Array, JSC.JSValue.JSType.Uint8Array, JSC.JSValue.JSType.DataView => fromTypedArray(global.ref(), value, exception), + JSC.JSValue.JSType.ArrayBuffer => fromArrayBuffer(global.ref(), value, exception), + else => null, + }; + } pub fn fromBytes(bytes: []u8, allocator: std.mem.Allocator, typed_array_type: js.JSTypedArrayType) MarkedArrayBuffer { return MarkedArrayBuffer{ @@ -1507,10 +1755,16 @@ pub const MarkedArrayBuffer = struct { }; } + pub inline fn slice(this: *const @This()) []u8 { + return this.buffer.slice(); + } + pub fn destroy(this: *MarkedArrayBuffer) void { const content = this.*; - content.allocator.free(content.buffer.slice()); - content.allocator.destroy(this); + if (this.allocator) |allocator| { + allocator.free(content.buffer.slice()); + allocator.destroy(this); + } } pub fn init(allocator: std.mem.Allocator, size: u32, typed_array_type: js.JSTypedArrayType) !*MarkedArrayBuffer { @@ -1520,9 +1774,11 @@ pub const MarkedArrayBuffer = struct { return container; } - pub fn toJSObjectRef(this: *MarkedArrayBuffer, ctx: js.JSContextRef, exception: js.ExceptionRef) js.JSObjectRef { - return js.JSObjectMakeTypedArrayWithBytesNoCopy(ctx, this.buffer.typed_array_type, this.buffer.ptr, this.buffer.byte_len, MarkedArrayBuffer_deallocator, this, exception); + pub fn toJSObjectRef(this: *const MarkedArrayBuffer, ctx: js.JSContextRef, exception: js.ExceptionRef) js.JSObjectRef { + return js.JSObjectMakeTypedArrayWithBytesNoCopy(ctx, this.buffer.typed_array_type, this.buffer.ptr, this.buffer.byte_len, MarkedArrayBuffer_deallocator, @intToPtr([*]u8, @ptrToInt(this)), exception); } + + pub const toJS = toJSObjectRef; }; export fn MarkedArrayBuffer_deallocator(bytes_: *anyopaque, ctx_: *anyopaque) void { @@ -1535,10 +1791,19 @@ export fn MarkedArrayBuffer_deallocator(bytes_: *anyopaque, ctx_: *anyopaque) vo pub fn castObj(obj: js.JSObjectRef, comptime Type: type) *Type { return JSPrivateDataPtr.from(js.JSObjectGetPrivate(obj)).as(Type); } + const JSNode = @import("../../js_ast.zig").Macro.JSNode; const LazyPropertiesObject = @import("../../js_ast.zig").Macro.LazyPropertiesObject; const ModuleNamespace = @import("../../js_ast.zig").Macro.ModuleNamespace; const FetchTaskletContext = Fetch.FetchTasklet.FetchTaskletContext; +const Expect = Test.Expect; +const DescribeScope = Test.DescribeScope; +const TestScope = Test.TestScope; +const ExpectPrototype = Test.ExpectPrototype; +const NodeFS = JSC.Node.NodeFS; +const DirEnt = JSC.Node.DirEnt; +const Stats = JSC.Node.Stats; +const BigIntStats = JSC.Node.BigIntStats; pub const JSPrivateDataPtr = TaggedPointerUnion(.{ ResolveError, BuildError, @@ -1552,6 +1817,13 @@ pub const JSPrivateDataPtr = TaggedPointerUnion(.{ LazyPropertiesObject, ModuleNamespace, FetchTaskletContext, + DescribeScope, + Expect, + ExpectPrototype, + NodeFS, + Stats, + BigIntStats, + DirEnt, }); pub inline fn GetJSPrivateData(comptime Type: type, ref: js.JSObjectRef) ?*Type { @@ -1567,6 +1839,7 @@ pub const JSPropertyNameIterator = struct { if (this.i >= this.count) return null; const i = this.i; this.i += 1; + return js.JSPropertyNameArrayGetNameAtIndex(this.array, i); } }; diff --git a/src/javascript/jsc/bindings/BunBuiltinNames.h b/src/javascript/jsc/bindings/BunBuiltinNames.h new file mode 100644 index 000000000..7a666df61 --- /dev/null +++ b/src/javascript/jsc/bindings/BunBuiltinNames.h @@ -0,0 +1,85 @@ +// clang-format off + +#pragma once + +#include "helpers.h" +#include "root.h" +#include <JavaScriptCore/BuiltinUtils.h> + + +namespace Bun { + +using namespace JSC; + + +#if !defined(BUN_ADDITIONAL_PRIVATE_IDENTIFIERS) +#define BUN_ADDITIONAL_PRIVATE_IDENTIFIERS(macro) +#endif + + + + +#define BUN_COMMON_PRIVATE_IDENTIFIERS_EACH_PROPERTY_NAME(macro) \ + macro(filePath) \ + macro(syscall) \ + macro(errno) \ + macro(code) \ + macro(path) \ + macro(dir) \ + macro(versions) \ + macro(argv) \ + macro(execArgv) \ + macro(nextTick) \ + macro(version) \ + macro(title) \ + macro(pid) \ + macro(ppid) \ + macro(chdir) \ + macro(cwd) \ + macro(process) \ + macro(map) \ + macro(addEventListener) \ + macro(removeEventListener) \ + macro(prependEventListener) \ + macro(write) \ + macro(end) \ + macro(close) \ + macro(destroy) \ + macro(cork) \ + macro(uncork) \ + macro(isPaused) \ + macro(read) \ + macro(pipe) \ + macro(unpipe) \ + macro(once) \ + macro(on) \ + macro(unshift) \ + macro(resume) \ + macro(pause) \ + BUN_ADDITIONAL_PRIVATE_IDENTIFIERS(macro) \ + +class BunBuiltinNames { +public: + // FIXME: Remove the __attribute__((nodebug)) when <rdar://68246686> is fixed. +#if COMPILER(CLANG) + __attribute__((nodebug)) +#endif + explicit BunBuiltinNames(JSC::VM& vm) + : m_vm(vm) + BUN_COMMON_PRIVATE_IDENTIFIERS_EACH_PROPERTY_NAME(INITIALIZE_BUILTIN_NAMES) + { +#define EXPORT_NAME(name) m_vm.propertyNames->appendExternalName(name##PublicName(), name##PrivateName()); + BUN_COMMON_PRIVATE_IDENTIFIERS_EACH_PROPERTY_NAME(EXPORT_NAME) +#undef EXPORT_NAME + } + + + BUN_COMMON_PRIVATE_IDENTIFIERS_EACH_PROPERTY_NAME(DECLARE_BUILTIN_IDENTIFIER_ACCESSOR) + +private: + JSC::VM& m_vm; + BUN_COMMON_PRIVATE_IDENTIFIERS_EACH_PROPERTY_NAME(DECLARE_BUILTIN_NAMES) +}; + +} // namespace Bun + diff --git a/src/javascript/jsc/bindings/BunClientData.cpp b/src/javascript/jsc/bindings/BunClientData.cpp new file mode 100644 index 000000000..a86720a85 --- /dev/null +++ b/src/javascript/jsc/bindings/BunClientData.cpp @@ -0,0 +1,33 @@ + +#include "BunClientData.h" +#include "root.h" + +#include <JavaScriptCore/FastMallocAlignedMemoryAllocator.h> +#include <JavaScriptCore/HeapInlines.h> +#include <JavaScriptCore/IsoHeapCellType.h> +#include <JavaScriptCore/JSDestructibleObjectHeapCellType.h> +#include <JavaScriptCore/MarkingConstraint.h> +#include <JavaScriptCore/SubspaceInlines.h> +#include <JavaScriptCore/VM.h> +#include <wtf/MainThread.h> + +// #include "BunGCOutputConstraint.h" + +namespace Bun { +using namespace JSC; + +JSVMClientData::JSVMClientData(VM &vm) : m_builtinNames(vm) {} + +JSVMClientData::~JSVMClientData() {} + +void JSVMClientData::create(VM *vm) { + JSVMClientData *clientData = new JSVMClientData(*vm); + vm->clientData = clientData; // ~VM deletes this pointer. + + // vm->heap.addMarkingConstraint(makeUnique<BunGCOutputConstraint>(*vm, *clientData)); + + // vm->m_typedArrayController = adoptRef(new WebCoreTypedArrayController( + // type == WorkerThreadType::DedicatedWorker || type == WorkerThreadType::Worklet)); +} + +} // namespace Bun
\ No newline at end of file diff --git a/src/javascript/jsc/bindings/BunClientData.h b/src/javascript/jsc/bindings/BunClientData.h new file mode 100644 index 000000000..cd506365f --- /dev/null +++ b/src/javascript/jsc/bindings/BunClientData.h @@ -0,0 +1,41 @@ +#pragma once + +#include "BunBuiltinNames.h" +#include "root.h" +#include <JavaScriptCore/BuiltinUtils.h> +#include <wtf/HashSet.h> +#include <wtf/RefPtr.h> + +namespace Bun { +using namespace JSC; + +class JSVMClientData : public JSC::VM::ClientData { + WTF_MAKE_NONCOPYABLE(JSVMClientData); + WTF_MAKE_FAST_ALLOCATED; + + public: + explicit JSVMClientData(JSC::VM &); + + virtual ~JSVMClientData(); + + static void create(JSC::VM *); + + BunBuiltinNames &builtinNames() { return m_builtinNames; } + + // Vector<JSC::IsoSubspace *> &outputConstraintSpaces() { return m_outputConstraintSpaces; } + + // template <typename Func> void forEachOutputConstraintSpace(const Func &func) { + // for (auto *space : m_outputConstraintSpaces) func(*space); + // } + + private: + BunBuiltinNames m_builtinNames; + + // Vector<JSC::IsoSubspace *> m_outputConstraintSpaces; +}; + +static JSVMClientData *clientData(JSC::VM &vm) { + return static_cast<Bun::JSVMClientData *>(vm.clientData); +} + +} // namespace Bun diff --git a/src/javascript/jsc/bindings/BunGCOutputConstraint.cpp b/src/javascript/jsc/bindings/BunGCOutputConstraint.cpp new file mode 100644 index 000000000..bc99ef2e2 --- /dev/null +++ b/src/javascript/jsc/bindings/BunGCOutputConstraint.cpp @@ -0,0 +1,47 @@ + + +// #include "BunGCOutputConstraint.h" + +// #include "BunClientData.h" +// #include <JavaScriptCore/BlockDirectoryInlines.h> +// #include <JavaScriptCore/HeapInlines.h> +// #include <JavaScriptCore/MarkedBlockInlines.h> +// #include <JavaScriptCore/MarkingConstraint.h> +// #include <JavaScriptCore/SubspaceInlines.h> +// #include <JavaScriptCore/VM.h> + +// namespace Bun { + +// using namespace JSC; + +// BunGCOutputConstraint::BunGCOutputConstraint(VM &vm, Bun::JSVMClientData &clientData) +// : MarkingConstraint("Domo", "DOM Output", ConstraintVolatility::SeldomGreyed, +// ConstraintConcurrency::Concurrent, ConstraintParallelism::Parallel), +// m_vm(vm), +// m_clientData(clientData), +// m_lastExecutionVersion(vm.heap.mutatorExecutionVersion()) {} + +// template <typename Visitor> void BunGCOutputConstraint::executeImplImpl(Visitor &visitor) { +// Heap &heap = m_vm.heap; + +// if (heap.mutatorExecutionVersion() == m_lastExecutionVersion) return; + +// m_lastExecutionVersion = heap.mutatorExecutionVersion(); + +// m_clientData.forEachOutputConstraintSpace([&](Subspace &subspace) { +// auto func = [](Visitor &visitor, HeapCell *heapCell, HeapCell::Kind) { +// SetRootMarkReasonScope rootScope(visitor, RootMarkReason::DOMGCOutput); +// JSCell *cell = static_cast<JSCell *>(heapCell); +// cell->methodTable(visitor.vm())->visitOutputConstraints(cell, visitor); +// }; + +// RefPtr<SharedTask<void(Visitor &)>> task = +// subspace.template forEachMarkedCellInParallel<Visitor>(func); +// visitor.addParallelConstraintTask(task); +// }); +// } + +// void BunGCOutputConstraint::executeImpl(AbstractSlotVisitor &visitor) { executeImplImpl(visitor); +// } void BunGCOutputConstraint::executeImpl(SlotVisitor &visitor) { executeImplImpl(visitor); } + +// } // namespace Bun diff --git a/src/javascript/jsc/bindings/BunGCOutputConstraint.h b/src/javascript/jsc/bindings/BunGCOutputConstraint.h new file mode 100644 index 000000000..521b0da8c --- /dev/null +++ b/src/javascript/jsc/bindings/BunGCOutputConstraint.h @@ -0,0 +1,34 @@ + +// #pragma once + +// #include "root.h" +// #include <JavaScriptCore/MarkingConstraint.h> + +// namespace JSC { +// class VM; +// } + +// namespace Bun { + +// class JSVMClientData; + +// class BunGCOutputConstraint : public JSC::MarkingConstraint { +// WTF_MAKE_FAST_ALLOCATED; + +// public: +// BunGCOutputConstraint(JSC::VM &, Bun::JSVMClientData &); +// ~BunGCOutputConstraint(){}; + +// protected: +// void executeImpl(JSC::AbstractSlotVisitor &) override; +// void executeImpl(JSC::SlotVisitor &) override; + +// private: +// template <typename Visitor> void executeImplImpl(Visitor &); + +// JSC::VM &m_vm; +// JSVMClientData &m_clientData; +// uint64_t m_lastExecutionVersion; +// }; + +// } // namespace Bun diff --git a/src/javascript/jsc/bindings/BunStream.cpp b/src/javascript/jsc/bindings/BunStream.cpp new file mode 100644 index 000000000..8c45feb40 --- /dev/null +++ b/src/javascript/jsc/bindings/BunStream.cpp @@ -0,0 +1,485 @@ +#include "BunStream.h" +#include <JavaScriptCore/JSMicrotask.h> +#include <JavaScriptCore/ObjectConstructor.h> + +namespace Bun { +using JSGlobalObject = JSC::JSGlobalObject; +using Exception = JSC::Exception; +using JSValue = JSC::JSValue; +using JSString = JSC::JSString; +using JSModuleLoader = JSC::JSModuleLoader; +using JSModuleRecord = JSC::JSModuleRecord; +using Identifier = JSC::Identifier; +using SourceOrigin = JSC::SourceOrigin; +using JSObject = JSC::JSObject; +using JSNonFinalObject = JSC::JSNonFinalObject; +namespace JSCastingHelpers = JSC::JSCastingHelpers; + +static ReadableEvent getReadableEvent(const WTF::String &eventName); +static ReadableEvent getReadableEvent(const WTF::String &eventName) { + if (eventName == "close") + return ReadableEvent__Close; + else if (eventName == "data") + return ReadableEvent__Data; + else if (eventName == "end") + return ReadableEvent__End; + else if (eventName == "error") + return ReadableEvent__Error; + else if (eventName == "pause") + return ReadableEvent__Pause; + else if (eventName == "readable") + return ReadableEvent__Readable; + else if (eventName == "resume") + return ReadableEvent__Resume; + else if (eventName == "open") + return ReadableEvent__Open; + else + return ReadableEventUser; +} + +static WritableEvent getWritableEvent(const WTF::String &eventName); +static WritableEvent getWritableEvent(const WTF::String &eventName) { + if (eventName == "close") + return WritableEvent__Close; + else if (eventName == "drain") + return WritableEvent__Drain; + else if (eventName == "error") + return WritableEvent__Error; + else if (eventName == "finish") + return WritableEvent__Finish; + else if (eventName == "pipe") + return WritableEvent__Pipe; + else if (eventName == "unpipe") + return WritableEvent__Unpipe; + else if (eventName == "open") + return WritableEvent__Open; + else + return WritableEventUser; +} + +// clang-format off +#define DEFINE_CALLBACK_FUNCTION_BODY(TypeName, ZigFunction) JSC::VM& vm = globalObject->vm(); \ + auto* thisObject = JSC::jsDynamicCast<TypeName*>(vm, callFrame->thisValue()); \ + auto scope = DECLARE_THROW_SCOPE(vm); \ + if (!thisObject) \ + return throwVMTypeError(globalObject, scope); \ + auto argCount = static_cast<uint16_t>(callFrame->argumentCount()); \ + WTF::Vector<JSC::EncodedJSValue, 16> arguments; \ + arguments.reserveInitialCapacity(argCount); \ + if (argCount) { \ + for (uint16_t i = 0; i < argCount; ++i) { \ + arguments.uncheckedAppend(JSC::JSValue::encode(callFrame->uncheckedArgument(i))); \ + } \ + } \ + JSC::JSValue result = JSC::JSValue::decode( \ + ZigFunction(thisObject->state, globalObject, arguments.data(), argCount) \ + ); \ + JSC::JSObject *obj = result.getObject(); \ + if (UNLIKELY(obj != nullptr && obj->isErrorInstance())) { \ + scope.throwException(globalObject, obj); \ + return JSC::JSValue::encode(JSC::jsUndefined()); \ + } \ + if (UNLIKELY(scope.exception())) \ + return JSC::JSValue::encode(JSC::jsUndefined()); \ + return JSC::JSValue::encode(result); + +// clang-format on +// static JSC_DECLARE_HOST_FUNCTION(Writable__addEventListener); +// static JSC_DECLARE_HOST_FUNCTION(Readable__addEventListener); +// static JSC_DECLARE_HOST_FUNCTION(Writable__prependListener); +// static JSC_DECLARE_HOST_FUNCTION(Readable__prependListener); +// static JSC_DECLARE_HOST_FUNCTION(Writable__prependOnceListener); +// static JSC_DECLARE_HOST_FUNCTION(Readable__prependOnceListener); +// static JSC_DECLARE_HOST_FUNCTION(Writable__setMaxListeners); +// static JSC_DECLARE_HOST_FUNCTION(Readable__setMaxListeners); +// static JSC_DECLARE_HOST_FUNCTION(Writable__getMaxListeners); +// static JSC_DECLARE_HOST_FUNCTION(Readable__getMaxListeners); +// static JSC_DECLARE_HOST_FUNCTION(Readable__setDefaultEncoding); +static JSC_DECLARE_HOST_FUNCTION(Readable__on); +// static JSC_DECLARE_HOST_FUNCTION(Readable__off); +static JSC_DECLARE_HOST_FUNCTION(Readable__once); +static JSC_DECLARE_HOST_FUNCTION(Readable__pause); +static JSC_DECLARE_HOST_FUNCTION(Readable__pipe); +static JSC_DECLARE_HOST_FUNCTION(Readable__read); +static JSC_DECLARE_HOST_FUNCTION(Readable__resume); +static JSC_DECLARE_HOST_FUNCTION(Readable__unpipe); +static JSC_DECLARE_HOST_FUNCTION(Readable__unshift); + +static JSC_DECLARE_HOST_FUNCTION(Writable__close); +// static JSC_DECLARE_HOST_FUNCTION(Writable__off); +static JSC_DECLARE_HOST_FUNCTION(Writable__cork); +static JSC_DECLARE_HOST_FUNCTION(Writable__destroy); +static JSC_DECLARE_HOST_FUNCTION(Writable__end); +static JSC_DECLARE_HOST_FUNCTION(Writable__on); +static JSC_DECLARE_HOST_FUNCTION(Writable__once); +static JSC_DECLARE_HOST_FUNCTION(Writable__uncork); +static JSC_DECLARE_HOST_FUNCTION(Writable__write); + +static JSC_DEFINE_HOST_FUNCTION(Readable__on, + (JSC::JSGlobalObject * globalObject, JSC::CallFrame *callFrame)) { + + if (callFrame->argumentCount() < 2) { return JSC::JSValue::encode(JSC::jsUndefined()); } + JSC::VM &vm = globalObject->vm(); + auto scope = DECLARE_THROW_SCOPE(vm); + + auto thisObject = JSC::jsDynamicCast<Bun::Readable *>(vm, callFrame->thisValue()); + if (UNLIKELY(!thisObject)) { + scope.release(); + JSC::throwVMTypeError(globalObject, scope); + return JSC::JSValue::encode(JSC::jsUndefined()); + } + + auto eventName = callFrame->argument(0).toStringOrNull(globalObject); + if (UNLIKELY(!eventName)) { + scope.release(); + return JSC::JSValue::encode(JSC::jsUndefined()); + } + + ReadableEvent event = getReadableEvent(eventName->value(globalObject)); + if (event == ReadableEventUser) { + // TODO: + scope.release(); + return JSC::JSValue::encode(JSC::jsUndefined()); + } + + auto listener = callFrame->argument(1); + JSC::JSObject *object = listener.getObject(); + if (UNLIKELY(!object) || !listener.isCallable(vm)) { + scope.release(); + return JSC::JSValue::encode(JSC::jsUndefined()); + } + + Bun__Readable__addEventListener(thisObject->state, globalObject, event, + JSC::JSValue::encode(listener), true); + + scope.release(); + return JSC::JSValue::encode(JSC::jsUndefined()); +} + +extern "C" Bun__Readable *JSC__JSValue__getReadableStreamState(JSC__JSValue value, JSC__VM *vm) { + auto *thisObject = JSC::jsDynamicCast<Bun::Readable *>(*vm, JSC::JSValue::decode(value)); + if (UNLIKELY(!thisObject)) { return nullptr; } + return thisObject->state; +} +extern "C" Bun__Writable *JSC__JSValue__getWritableStreamState(JSC__JSValue value, JSC__VM *vm) { + auto *thisObject = JSC::jsDynamicCast<Bun::Writable *>(*vm, JSC::JSValue::decode(value)); + if (UNLIKELY(!thisObject)) { return nullptr; } + return thisObject->state; +} + +const JSC::ClassInfo Readable::s_info = {"Readable", &Base::s_info, nullptr, nullptr, + CREATE_METHOD_TABLE(Readable)}; + +const JSC::ClassInfo Writable::s_info = {"Writable", &Base::s_info, nullptr, nullptr, + CREATE_METHOD_TABLE(Writable)}; + +static JSC_DEFINE_HOST_FUNCTION(Readable__once, + (JSC::JSGlobalObject * globalObject, JSC::CallFrame *callFrame)) { + + if (callFrame->argumentCount() < 2) { return JSC::JSValue::encode(JSC::jsUndefined()); } + JSC::VM &vm = globalObject->vm(); + auto scope = DECLARE_THROW_SCOPE(vm); + + auto thisObject = JSC::jsDynamicCast<Bun::Readable *>(vm, callFrame->thisValue()); + if (UNLIKELY(!thisObject)) { + scope.release(); + JSC::throwVMTypeError(globalObject, scope); + return JSC::JSValue::encode(JSC::jsUndefined()); + } + + auto eventName = callFrame->argument(0).toStringOrNull(globalObject); + if (UNLIKELY(!eventName)) { + scope.release(); + return JSC::JSValue::encode(JSC::jsUndefined()); + } + + ReadableEvent event = getReadableEvent(eventName->value(globalObject)); + if (event == ReadableEventUser) { + // TODO: + scope.release(); + return JSC::JSValue::encode(JSC::jsUndefined()); + } + + auto listener = callFrame->argument(1); + JSC::JSObject *object = listener.getObject(); + if (UNLIKELY(!object) || !listener.isCallable(vm)) { + scope.release(); + return JSC::JSValue::encode(JSC::jsUndefined()); + } + + Bun__Readable__addEventListener(thisObject->state, globalObject, event, + JSC::JSValue::encode(listener), true); + + scope.release(); + return JSC::JSValue::encode(JSC::jsUndefined()); +} + +static JSC_DEFINE_HOST_FUNCTION(Writable__on, + (JSC::JSGlobalObject * globalObject, JSC::CallFrame *callFrame)) { + + if (callFrame->argumentCount() < 2) { return JSC::JSValue::encode(JSC::jsUndefined()); } + JSC::VM &vm = globalObject->vm(); + auto scope = DECLARE_THROW_SCOPE(vm); + + auto thisObject = JSC::jsDynamicCast<Bun::Writable *>(vm, callFrame->thisValue()); + if (UNLIKELY(!thisObject)) { + scope.release(); + JSC::throwVMTypeError(globalObject, scope); + return JSC::JSValue::encode(JSC::jsUndefined()); + } + + auto eventName = callFrame->argument(0).toStringOrNull(globalObject); + if (UNLIKELY(!eventName)) { + scope.release(); + return JSC::JSValue::encode(JSC::jsUndefined()); + } + + WritableEvent event = getWritableEvent(eventName->value(globalObject)); + if (event == WritableEventUser) { + // TODO: + scope.release(); + return JSC::JSValue::encode(JSC::jsUndefined()); + } + + auto listener = callFrame->argument(1); + JSC::JSObject *object = listener.getObject(); + if (UNLIKELY(!object) || !listener.isCallable(vm)) { + scope.release(); + return JSC::JSValue::encode(JSC::jsUndefined()); + } + + Bun__Writable__addEventListener(thisObject->state, globalObject, event, + JSC::JSValue::encode(listener), false); + + scope.release(); + return JSC::JSValue::encode(JSC::jsUndefined()); +} + +static JSC_DEFINE_HOST_FUNCTION(Writable__once, + (JSC::JSGlobalObject * globalObject, JSC::CallFrame *callFrame)) { + + if (callFrame->argumentCount() < 2) { return JSC::JSValue::encode(JSC::jsUndefined()); } + JSC::VM &vm = globalObject->vm(); + auto scope = DECLARE_THROW_SCOPE(vm); + + auto thisObject = JSC::jsDynamicCast<Bun::Writable *>(vm, callFrame->thisValue()); + if (UNLIKELY(!thisObject)) { + scope.release(); + JSC::throwVMTypeError(globalObject, scope); + return JSC::JSValue::encode(JSC::jsUndefined()); + } + + auto eventName = callFrame->argument(0).toStringOrNull(globalObject); + if (UNLIKELY(!eventName)) { + scope.release(); + return JSC::JSValue::encode(JSC::jsUndefined()); + } + + WritableEvent event = getWritableEvent(eventName->value(globalObject)); + if (event == WritableEventUser) { + // TODO: + scope.release(); + return JSC::JSValue::encode(JSC::jsUndefined()); + } + + auto listener = callFrame->argument(1); + JSC::JSObject *object = listener.getObject(); + if (UNLIKELY(!object) || !listener.isCallable(vm)) { + scope.release(); + return JSC::JSValue::encode(JSC::jsUndefined()); + } + + Bun__Writable__addEventListener(thisObject->state, globalObject, event, + JSC::JSValue::encode(listener), true); + + scope.release(); + return JSC::JSValue::encode(JSC::jsUndefined()); +} + +static JSC_DEFINE_HOST_FUNCTION(Readable__read, + (JSC::JSGlobalObject * globalObject, JSC::CallFrame *callFrame)) { + DEFINE_CALLBACK_FUNCTION_BODY(Bun::Readable, Bun__Readable__read); +} + +static JSC_DEFINE_HOST_FUNCTION(Readable__pipe, + (JSC::JSGlobalObject * globalObject, JSC::CallFrame *callFrame)) { + DEFINE_CALLBACK_FUNCTION_BODY(Bun::Readable, Bun__Readable__pipe); +} + +static JSC_DEFINE_HOST_FUNCTION(Readable__resume, + (JSC::JSGlobalObject * globalObject, JSC::CallFrame *callFrame)) { + DEFINE_CALLBACK_FUNCTION_BODY(Bun::Readable, Bun__Readable__resume); +} +static JSC_DEFINE_HOST_FUNCTION(Readable__unpipe, + (JSC::JSGlobalObject * globalObject, JSC::CallFrame *callFrame)) { + DEFINE_CALLBACK_FUNCTION_BODY(Bun::Readable, Bun__Readable__unpipe); +} +static JSC_DEFINE_HOST_FUNCTION(Readable__pause, + (JSC::JSGlobalObject * globalObject, JSC::CallFrame *callFrame)) { + DEFINE_CALLBACK_FUNCTION_BODY(Bun::Readable, Bun__Readable__pause); +} +static JSC_DEFINE_HOST_FUNCTION(Readable__unshift, + (JSC::JSGlobalObject * globalObject, JSC::CallFrame *callFrame)) { + DEFINE_CALLBACK_FUNCTION_BODY(Bun::Readable, Bun__Readable__unshift); +} + +// static JSC_DECLARE_HOST_FUNCTION(Readable__isPaused); +// static JSC_DECLARE_HOST_FUNCTION(Writable__setDefaultEncoding); + +// static DEFINE_CALLBACK_FUNCTION(Writable__setDefaultEncoding, Bun::Writable, +// Bun__Writable__setDefaultEncoding); + +static JSC_DEFINE_HOST_FUNCTION(Writable__write, + (JSC::JSGlobalObject * globalObject, JSC::CallFrame *callFrame)) { + DEFINE_CALLBACK_FUNCTION_BODY(Bun::Writable, Bun__Writable__write); +} +static JSC_DEFINE_HOST_FUNCTION(Writable__end, + (JSC::JSGlobalObject * globalObject, JSC::CallFrame *callFrame)) { + DEFINE_CALLBACK_FUNCTION_BODY(Bun::Writable, Bun__Writable__end); +} +static JSC_DEFINE_HOST_FUNCTION(Writable__close, + (JSC::JSGlobalObject * globalObject, JSC::CallFrame *callFrame)) { + DEFINE_CALLBACK_FUNCTION_BODY(Bun::Writable, Bun__Writable__close); +} +static JSC_DEFINE_HOST_FUNCTION(Writable__destroy, + (JSC::JSGlobalObject * globalObject, JSC::CallFrame *callFrame)) { + DEFINE_CALLBACK_FUNCTION_BODY(Bun::Writable, Bun__Writable__destroy); +} +static JSC_DEFINE_HOST_FUNCTION(Writable__cork, + (JSC::JSGlobalObject * globalObject, JSC::CallFrame *callFrame)) { + DEFINE_CALLBACK_FUNCTION_BODY(Bun::Writable, Bun__Writable__cork); +} +static JSC_DEFINE_HOST_FUNCTION(Writable__uncork, + (JSC::JSGlobalObject * globalObject, JSC::CallFrame *callFrame)) { + DEFINE_CALLBACK_FUNCTION_BODY(Bun::Writable, Bun__Writable__uncork); +} + +extern "C" JSC__JSValue Bun__Readable__create(Bun__Readable *state, + JSC__JSGlobalObject *globalObject) { + JSC::JSValue result = JSC::JSValue(Readable::create( + globalObject->vm(), state, + Readable::createStructure(globalObject->vm(), globalObject, globalObject->objectPrototype()))); + + return JSC::JSValue::encode(result); +} +extern "C" JSC__JSValue Bun__Writable__create(Bun__Writable *state, + JSC__JSGlobalObject *globalObject) { + JSC::JSValue result = JSC::JSValue(Writable::create( + globalObject->vm(), state, + Writable::createStructure(globalObject->vm(), globalObject, globalObject->objectPrototype()))); + + return JSC::JSValue::encode(result); +} + +Readable::~Readable() { + if (this->state) { Bun__Readable__deinit(this->state); } +} + +Writable::~Writable() { + if (this->state) { Bun__Writable__deinit(this->state); } +} + +void Readable::finishCreation(JSC::VM &vm) { + Base::finishCreation(vm); + auto clientData = Bun::clientData(vm); + auto *globalObject = this->globalObject(); + + putDirect(vm, clientData->builtinNames().onPublicName(), + JSFunction::create(vm, globalObject, 2, + clientData->builtinNames().onPublicName().string(), Readable__on), + 0); + putDirect(vm, clientData->builtinNames().oncePublicName(), + JSFunction::create(vm, globalObject, 2, + clientData->builtinNames().oncePublicName().string(), + Readable__once), + 0); + putDirect(vm, clientData->builtinNames().pausePublicName(), + JSFunction::create(vm, globalObject, 2, + clientData->builtinNames().pausePublicName().string(), + Readable__pause), + 0); + putDirect(vm, clientData->builtinNames().pipePublicName(), + JSFunction::create(vm, globalObject, 2, + clientData->builtinNames().pipePublicName().string(), + Readable__pipe), + 0); + putDirect(vm, clientData->builtinNames().readPublicName(), + JSFunction::create(vm, globalObject, 2, + clientData->builtinNames().readPublicName().string(), + Readable__read), + 0); + putDirect(vm, clientData->builtinNames().resumePublicName(), + JSFunction::create(vm, globalObject, 2, + clientData->builtinNames().resumePublicName().string(), + Readable__resume), + 0); + putDirect(vm, clientData->builtinNames().unpipePublicName(), + JSFunction::create(vm, globalObject, 2, + clientData->builtinNames().unpipePublicName().string(), + Readable__unpipe), + 0); + putDirect(vm, clientData->builtinNames().unshiftPublicName(), + JSFunction::create(vm, globalObject, 2, + clientData->builtinNames().unshiftPublicName().string(), + Readable__unshift), + 0); +} + +void Writable::finishCreation(JSC::VM &vm) { + Base::finishCreation(vm); + auto clientData = Bun::clientData(vm); + + auto *globalObject = this->globalObject(); + + putDirect(vm, clientData->builtinNames().onPublicName(), + JSFunction::create(vm, globalObject, 2, + clientData->builtinNames().onPublicName().string(), Writable__on), + 0); + + putDirect(vm, clientData->builtinNames().oncePublicName(), + JSFunction::create(vm, globalObject, 2, + clientData->builtinNames().oncePublicName().string(), + Writable__once), + 0); + + putDirect(vm, clientData->builtinNames().closePublicName(), + JSFunction::create(vm, globalObject, 2, + clientData->builtinNames().closePublicName().string(), + Writable__close), + 0); + putDirect(vm, clientData->builtinNames().corkPublicName(), + JSFunction::create(vm, globalObject, 2, + clientData->builtinNames().corkPublicName().string(), + Writable__cork), + 0); + putDirect(vm, clientData->builtinNames().destroyPublicName(), + JSFunction::create(vm, globalObject, 2, + clientData->builtinNames().destroyPublicName().string(), + Writable__destroy), + 0); + putDirect(vm, clientData->builtinNames().endPublicName(), + JSFunction::create(vm, globalObject, 2, + clientData->builtinNames().endPublicName().string(), Writable__end), + 0); + putDirect(vm, clientData->builtinNames().onPublicName(), + JSFunction::create(vm, globalObject, 2, + clientData->builtinNames().onPublicName().string(), Writable__on), + 0); + putDirect(vm, clientData->builtinNames().oncePublicName(), + JSFunction::create(vm, globalObject, 2, + clientData->builtinNames().oncePublicName().string(), + Writable__once), + 0); + putDirect(vm, clientData->builtinNames().uncorkPublicName(), + JSFunction::create(vm, globalObject, 2, + clientData->builtinNames().uncorkPublicName().string(), + Writable__uncork), + 0); + putDirect(vm, clientData->builtinNames().writePublicName(), + JSFunction::create(vm, globalObject, 2, + clientData->builtinNames().writePublicName().string(), + Writable__write), + 0); +} + +} // namespace Bun
\ No newline at end of file diff --git a/src/javascript/jsc/bindings/BunStream.h b/src/javascript/jsc/bindings/BunStream.h new file mode 100644 index 000000000..37762d689 --- /dev/null +++ b/src/javascript/jsc/bindings/BunStream.h @@ -0,0 +1,82 @@ +#pragma once + +#include "BunBuiltinNames.h" +#include "BunClientData.h" +#include "root.h" + +namespace Bun { + +using namespace JSC; + +class Readable : public JSC::JSNonFinalObject { + using Base = JSC::JSNonFinalObject; + + public: + Bun__Readable *state; + Readable(JSC::VM &vm, Bun__Readable *readable, JSC::Structure *structure) : Base(vm, structure) { + state = readable; + } + + ~Readable(); + + DECLARE_INFO; + + static constexpr unsigned StructureFlags = Base::StructureFlags; + + template <typename CellType, JSC::SubspaceAccess> + static JSC::CompleteSubspace *subspaceFor(JSC::VM &vm) { + return &vm.cellSpace; + } + + static JSC::Structure *createStructure(JSC::VM &vm, JSC::JSGlobalObject *globalObject, + JSC::JSValue prototype) { + return JSC::Structure::create(vm, globalObject, prototype, + JSC::TypeInfo(JSC::ObjectType, StructureFlags), info()); + } + + static Readable *create(JSC::VM &vm, Bun__Readable *state, JSC::Structure *structure) { + Readable *accessor = + new (NotNull, JSC::allocateCell<Bun::Readable>(vm.heap)) Readable(vm, state, structure); + accessor->finishCreation(vm); + return accessor; + } + + void finishCreation(JSC::VM &vm); +}; + +class Writable : public JSC::JSNonFinalObject { + using Base = JSC::JSNonFinalObject; + + public: + Bun__Writable *state; + Writable(JSC::VM &vm, Bun__Writable *writable, JSC::Structure *structure) : Base(vm, structure) { + state = writable; + } + + DECLARE_INFO; + + static constexpr unsigned StructureFlags = Base::StructureFlags; + + template <typename CellType, JSC::SubspaceAccess> + static JSC::CompleteSubspace *subspaceFor(JSC::VM &vm) { + return &vm.cellSpace; + } + + static JSC::Structure *createStructure(JSC::VM &vm, JSC::JSGlobalObject *globalObject, + JSC::JSValue prototype) { + return JSC::Structure::create(vm, globalObject, prototype, + JSC::TypeInfo(JSC::ObjectType, StructureFlags), info()); + } + + static Writable *create(JSC::VM &vm, Bun__Writable *state, JSC::Structure *structure) { + Writable *accessor = + new (NotNull, JSC::allocateCell<Writable>(vm.heap)) Writable(vm, state, structure); + accessor->finishCreation(vm); + return accessor; + } + ~Writable(); + + void finishCreation(JSC::VM &vm); +}; + +} // namespace Bun
\ No newline at end of file diff --git a/src/javascript/jsc/bindings/Process.cpp b/src/javascript/jsc/bindings/Process.cpp new file mode 100644 index 000000000..754c1d96b --- /dev/null +++ b/src/javascript/jsc/bindings/Process.cpp @@ -0,0 +1,340 @@ +#include "Process.h" +#include <JavaScriptCore/JSMicrotask.h> +#include <JavaScriptCore/ObjectConstructor.h> + +#pragma mark - Node.js Process + +namespace Zig { + +using JSGlobalObject = JSC::JSGlobalObject; +using Exception = JSC::Exception; +using JSValue = JSC::JSValue; +using JSString = JSC::JSString; +using JSModuleLoader = JSC::JSModuleLoader; +using JSModuleRecord = JSC::JSModuleRecord; +using Identifier = JSC::Identifier; +using SourceOrigin = JSC::SourceOrigin; +using JSObject = JSC::JSObject; +using JSNonFinalObject = JSC::JSNonFinalObject; +namespace JSCastingHelpers = JSC::JSCastingHelpers; + +static JSC_DECLARE_CUSTOM_SETTER(Process_setTitle); +static JSC_DECLARE_CUSTOM_GETTER(Process_getArgv); +static JSC_DECLARE_CUSTOM_SETTER(Process_setArgv); +static JSC_DECLARE_CUSTOM_GETTER(Process_getTitle); +static JSC_DECLARE_CUSTOM_GETTER(Process_getVersionsLazy); +static JSC_DECLARE_CUSTOM_SETTER(Process_setVersionsLazy); + +static JSC_DECLARE_CUSTOM_GETTER(Process_getPID); +static JSC_DECLARE_CUSTOM_GETTER(Process_getPPID); + +static JSC_DECLARE_HOST_FUNCTION(Process_functionCwd); + +static JSC_DECLARE_HOST_FUNCTION(Process_functionNextTick); +static JSC_DEFINE_HOST_FUNCTION(Process_functionNextTick, + (JSC::JSGlobalObject * globalObject, JSC::CallFrame *callFrame)) { + JSC::VM &vm = globalObject->vm(); + auto argCount = callFrame->argumentCount(); + if (argCount == 0) { + auto scope = DECLARE_THROW_SCOPE(globalObject->vm()); + JSC::throwTypeError(globalObject, scope, "nextTick requires 1 argument (a function)"_s); + return JSC::JSValue::encode(JSC::JSValue{}); + } + + JSC::JSValue job = callFrame->uncheckedArgument(0); + + if (!job.isObject() || !job.getObject()->isCallable(vm)) { + auto scope = DECLARE_THROW_SCOPE(globalObject->vm()); + JSC::throwTypeError(globalObject, scope, "nextTick expects a function"_s); + return JSC::JSValue::encode(JSC::JSValue{}); + } + + switch (argCount) { + + case 1: { + // This is a JSC builtin function + globalObject->queueMicrotask(JSC::createJSMicrotask(vm, job)); + break; + } + + case 2: + case 3: + case 4: + case 5: { + JSC::JSValue argument0 = callFrame->uncheckedArgument(1); + JSC::JSValue argument1 = argCount > 2 ? callFrame->uncheckedArgument(2) : JSC::JSValue{}; + JSC::JSValue argument2 = argCount > 3 ? callFrame->uncheckedArgument(3) : JSC::JSValue{}; + JSC::JSValue argument3 = argCount > 4 ? callFrame->uncheckedArgument(4) : JSC::JSValue{}; + globalObject->queueMicrotask( + JSC::createJSMicrotask(vm, job, argument0, argument1, argument2, argument3)); + break; + } + + default: { + auto scope = DECLARE_THROW_SCOPE(globalObject->vm()); + JSC::throwTypeError(globalObject, scope, + "nextTick doesn't support more than 4 arguments currently"_s); + return JSC::JSValue::encode(JSC::JSValue{}); + + break; + } + + // JSC::MarkedArgumentBuffer args; + // for (unsigned i = 1; i < callFrame->argumentCount(); i++) { + // args.append(callFrame->uncheckedArgument(i)); + // } + + // JSC::ArgList argsList(args); + // JSC::gcProtect(job); + // JSC::JSFunction *callback = JSC::JSNativeStdFunction::create( + // vm, globalObject, 0, String(), + // [job, &argsList](JSC::JSGlobalObject *globalObject, JSC::CallFrame *callFrame) { + // JSC::VM &vm = globalObject->vm(); + // auto callData = getCallData(vm, job); + + // return JSC::JSValue::encode(JSC::call(globalObject, job, callData, job, argsList)); + // }); + + // globalObject->queueMicrotask(JSC::createJSMicrotask(vm, JSC::JSValue(callback))); + } + + return JSC::JSValue::encode(JSC::jsUndefined()); +} + +static JSC_DECLARE_HOST_FUNCTION(Process_functionChdir); + +static JSC_DEFINE_HOST_FUNCTION(Process_functionChdir, + (JSC::JSGlobalObject * globalObject, JSC::CallFrame *callFrame)) { + + auto scope = DECLARE_THROW_SCOPE(globalObject->vm()); + + ZigString str = ZigString{nullptr, 0}; + if (callFrame->argumentCount() > 0) { + str = Zig::toZigString(callFrame->uncheckedArgument(0).toWTFString(globalObject)); + } + + JSC::JSValue result = JSC::JSValue::decode(Bun__Process__setCwd(globalObject, &str)); + JSC::JSObject *obj = result.getObject(); + if (UNLIKELY(obj != nullptr && obj->isErrorInstance())) { + scope.throwException(globalObject, obj); + return JSValue::encode(JSC::jsUndefined()); + } + + return JSC::JSValue::encode(result); +} + +void Process::finishCreation(JSC::VM &vm) { + Base::finishCreation(vm); + auto clientData = Bun::clientData(vm); + + putDirectCustomAccessor(vm, clientData->builtinNames().pidPublicName(), + JSC::CustomGetterSetter::create(vm, Process_getPID, nullptr), + static_cast<unsigned>(JSC::PropertyAttribute::CustomValue)); + + putDirectCustomAccessor(vm, clientData->builtinNames().ppidPublicName(), + JSC::CustomGetterSetter::create(vm, Process_getPPID, nullptr), + static_cast<unsigned>(JSC::PropertyAttribute::CustomValue)); + + putDirectCustomAccessor(vm, clientData->builtinNames().titlePublicName(), + JSC::CustomGetterSetter::create(vm, Process_getTitle, Process_setTitle), + static_cast<unsigned>(JSC::PropertyAttribute::CustomValue)); + + putDirectCustomAccessor(vm, clientData->builtinNames().argvPublicName(), + JSC::CustomGetterSetter::create(vm, Process_getArgv, Process_setArgv), + static_cast<unsigned>(JSC::PropertyAttribute::CustomValue)); + + this->putDirect(vm, clientData->builtinNames().nextTickPublicName(), + JSC::JSFunction::create(vm, JSC::jsCast<JSC::JSGlobalObject *>(globalObject()), 0, + WTF::String("nextTick"), Process_functionNextTick), + 0); + + this->putDirect(vm, clientData->builtinNames().cwdPublicName(), + JSC::JSFunction::create(vm, JSC::jsCast<JSC::JSGlobalObject *>(globalObject()), 0, + WTF::String("cwd"), Process_functionCwd), + 0); + + this->putDirect(vm, clientData->builtinNames().chdirPublicName(), + JSC::JSFunction::create(vm, JSC::jsCast<JSC::JSGlobalObject *>(globalObject()), 0, + WTF::String("chdir"), Process_functionChdir), + 0); + + putDirectCustomAccessor( + vm, clientData->builtinNames().versionsPublicName(), + JSC::CustomGetterSetter::create(vm, Process_getVersionsLazy, Process_setVersionsLazy), 0); + // this should be transpiled out, but just incase + this->putDirect(this->vm(), JSC::Identifier::fromString(this->vm(), "browser"), + JSC::JSValue(false)); + + this->putDirect(this->vm(), clientData->builtinNames().versionPublicName(), + JSC::jsString(this->vm(), WTF::String(Bun__version))); + + // this gives some way of identifying at runtime whether the SSR is happening in node or not. + // this should probably be renamed to what the name of the bundler is, instead of "notNodeJS" + // but it must be something that won't evaluate to truthy in Node.js + this->putDirect(this->vm(), JSC::Identifier::fromString(this->vm(), "isBun"), JSC::JSValue(true)); +#if defined(__APPLE__) + this->putDirect(this->vm(), JSC::Identifier::fromString(this->vm(), "platform"), + JSC::jsString(this->vm(), WTF::String("darwin"))); +#else + this->putDirect(this->vm(), JSC::Identifier::fromString(this->vm(), "platform"), + JSC::jsString(this->vm(), WTF::String("linux"))); +#endif + +#if defined(__x86_64__) + this->putDirect(this->vm(), JSC::Identifier::fromString(this->vm(), "arch"), + JSC::jsString(this->vm(), WTF::String("x64"))); +#elif defined(__i386__) + this->putDirect(this->vm(), JSC::Identifier::fromString(this->vm(), "arch"), + JSC::jsString(this->vm(), WTF::String("x86"))); +#elif defined(__arm__) + this->putDirect(this->vm(), JSC::Identifier::fromString(this->vm(), "arch"), + JSC::jsString(this->vm(), WTF::String("arm"))); +#elif defined(__aarch64__) + this->putDirect(this->vm(), JSC::Identifier::fromString(this->vm(), "arch"), + JSC::jsString(this->vm(), WTF::String("arm64"))); +#endif +} + +const JSC::ClassInfo Process::s_info = {"Process", &Base::s_info, nullptr, nullptr, + CREATE_METHOD_TABLE(Process)}; + +JSC_DEFINE_CUSTOM_GETTER(Process_getTitle, (JSC::JSGlobalObject * globalObject, + JSC::EncodedJSValue thisValue, JSC::PropertyName)) { + ZigString str; + Bun__Process__getTitle(globalObject, &str); + return JSValue::encode(Zig::toJSStringValue(str, globalObject)); +} + +JSC_DEFINE_CUSTOM_SETTER(Process_setTitle, + (JSC::JSGlobalObject * globalObject, JSC::EncodedJSValue thisValue, + JSC::EncodedJSValue value, JSC::PropertyName)) { + JSC::VM &vm = globalObject->vm(); + + JSC::JSObject *thisObject = JSC::jsDynamicCast<JSC::JSObject *>(vm, JSValue::decode(thisValue)); + JSC::JSString *jsString = JSC::jsDynamicCast<JSC::JSString *>(vm, JSValue::decode(value)); + if (!thisObject || !jsString) { return false; } + + ZigString str = Zig::toZigString(jsString, globalObject); + Bun__Process__setTitle(globalObject, &str); + + return true; +} + +JSC_DEFINE_CUSTOM_GETTER(Process_getArgv, (JSC::JSGlobalObject * globalObject, + JSC::EncodedJSValue thisValue, JSC::PropertyName)) { + JSC::VM &vm = globalObject->vm(); + + Zig::Process *thisObject = JSC::jsDynamicCast<Zig::Process *>(vm, JSValue::decode(thisValue)); + if (!thisObject) { return JSValue::encode(JSC::jsUndefined()); } + auto clientData = Bun::clientData(vm); + + if (JSC::JSValue argv = thisObject->getIfPropertyExists( + globalObject, clientData->builtinNames().argvPrivateName())) { + return JSValue::encode(argv); + } + + JSC::EncodedJSValue argv_ = Bun__Process__getArgv(globalObject); + thisObject->putDirect(vm, clientData->builtinNames().argvPrivateName(), + JSC::JSValue::decode(argv_)); + + return argv_; +} + +JSC_DEFINE_CUSTOM_SETTER(Process_setArgv, + (JSC::JSGlobalObject * globalObject, JSC::EncodedJSValue thisValue, + JSC::EncodedJSValue value, JSC::PropertyName)) { + JSC::VM &vm = globalObject->vm(); + + JSC::JSObject *thisObject = JSC::jsDynamicCast<JSC::JSObject *>(vm, JSValue::decode(thisValue)); + if (!thisObject) { return false; } + + auto clientData = Bun::clientData(vm); + + return thisObject->putDirect(vm, clientData->builtinNames().argvPrivateName(), + JSC::JSValue::decode(value)); +} + +JSC_DEFINE_CUSTOM_GETTER(Process_getPID, (JSC::JSGlobalObject * globalObject, + JSC::EncodedJSValue thisValue, JSC::PropertyName)) { + return JSC::JSValue::encode(JSC::JSValue(getpid())); +} + +JSC_DEFINE_CUSTOM_GETTER(Process_getPPID, (JSC::JSGlobalObject * globalObject, + JSC::EncodedJSValue thisValue, JSC::PropertyName)) { + return JSC::JSValue::encode(JSC::JSValue(getppid())); +} + +JSC_DEFINE_CUSTOM_GETTER(Process_getVersionsLazy, + (JSC::JSGlobalObject * globalObject, JSC::EncodedJSValue thisValue, + JSC::PropertyName)) { + JSC::VM &vm = globalObject->vm(); + auto clientData = Bun::clientData(vm); + + Zig::Process *thisObject = JSC::jsDynamicCast<Zig::Process *>(vm, JSValue::decode(thisValue)); + if (!thisObject) { return JSValue::encode(JSC::jsUndefined()); } + + if (JSC::JSValue argv = thisObject->getIfPropertyExists( + globalObject, clientData->builtinNames().versionsPrivateName())) { + return JSValue::encode(argv); + } + + JSC::JSObject *object = + JSC::constructEmptyObject(globalObject, globalObject->objectPrototype(), 9); + + object->putDirect(vm, JSC::Identifier::fromString(vm, "node"), + JSC::JSValue(JSC::jsString(vm, WTF::String("17.0.0")))); + object->putDirect( + vm, JSC::Identifier::fromString(vm, "bun"), + JSC::JSValue(JSC::jsString(vm, WTF::String(Bun__version + 1 /* prefix with v */)))); + object->putDirect(vm, JSC::Identifier::fromString(vm, "webkit"), + JSC::JSValue(JSC::jsString(vm, WTF::String(Bun__versions_webkit)))); + object->putDirect(vm, JSC::Identifier::fromString(vm, "mimalloc"), + JSC::JSValue(JSC::jsString(vm, WTF::String(Bun__versions_mimalloc)))); + object->putDirect(vm, JSC::Identifier::fromString(vm, "libarchive"), + JSC::JSValue(JSC::jsString(vm, WTF::String(Bun__versions_libarchive)))); + object->putDirect(vm, JSC::Identifier::fromString(vm, "picohttpparser"), + JSC::JSValue(JSC::jsString(vm, WTF::String(Bun__versions_picohttpparser)))); + object->putDirect(vm, JSC::Identifier::fromString(vm, "boringssl"), + JSC::JSValue(JSC::jsString(vm, WTF::String(Bun__versions_boringssl)))); + object->putDirect(vm, JSC::Identifier::fromString(vm, "zlib"), + JSC::JSValue(JSC::jsString(vm, WTF::String(Bun__versions_zlib)))); + object->putDirect(vm, JSC::Identifier::fromString(vm, "zig"), + JSC::JSValue(JSC::jsString(vm, WTF::String(Bun__versions_zig)))); + + object->putDirect(vm, JSC::Identifier::fromString(vm, "modules"), + JSC::JSValue(JSC::jsString(vm, WTF::String("67")))); + + thisObject->putDirect(vm, clientData->builtinNames().versionsPrivateName(), object); + return JSC::JSValue::encode(object); +} +JSC_DEFINE_CUSTOM_SETTER(Process_setVersionsLazy, + (JSC::JSGlobalObject * globalObject, JSC::EncodedJSValue thisValue, + JSC::EncodedJSValue value, JSC::PropertyName)) { + + JSC::VM &vm = globalObject->vm(); + auto clientData = Bun::clientData(vm); + + Zig::Process *thisObject = JSC::jsDynamicCast<Zig::Process *>(vm, JSValue::decode(thisValue)); + if (!thisObject) { return JSValue::encode(JSC::jsUndefined()); } + + thisObject->putDirect(vm, clientData->builtinNames().versionsPrivateName(), + JSC::JSValue::decode(value)); + + return true; +} + +static JSC_DEFINE_HOST_FUNCTION(Process_functionCwd, + (JSC::JSGlobalObject * globalObject, JSC::CallFrame *callFrame)) { + + auto scope = DECLARE_THROW_SCOPE(globalObject->vm()); + JSC::JSValue result = JSC::JSValue::decode(Bun__Process__getCwd(globalObject)); + JSC::JSObject *obj = result.getObject(); + if (UNLIKELY(obj != nullptr && obj->isErrorInstance())) { + scope.throwException(globalObject, obj); + return JSValue::encode(JSC::jsUndefined()); + } + + return JSC::JSValue::encode(result); +} + +} // namespace Zig
\ No newline at end of file diff --git a/src/javascript/jsc/bindings/Process.h b/src/javascript/jsc/bindings/Process.h new file mode 100644 index 000000000..7e025bc3a --- /dev/null +++ b/src/javascript/jsc/bindings/Process.h @@ -0,0 +1,39 @@ +#pragma once + +#include "BunBuiltinNames.h" +#include "BunClientData.h" +#include "root.h" + +namespace Zig { + +class Process : public JSC::JSNonFinalObject { + using Base = JSC::JSNonFinalObject; + + public: + Process(JSC::VM &vm, JSC::Structure *structure) : Base(vm, structure) {} + + DECLARE_INFO; + + static constexpr unsigned StructureFlags = Base::StructureFlags; + + template <typename CellType, JSC::SubspaceAccess> + static JSC::CompleteSubspace *subspaceFor(JSC::VM &vm) { + return &vm.cellSpace; + } + + static JSC::Structure *createStructure(JSC::VM &vm, JSC::JSGlobalObject *globalObject, + JSC::JSValue prototype) { + return JSC::Structure::create(vm, globalObject, prototype, + JSC::TypeInfo(JSC::ObjectType, StructureFlags), info()); + } + + static Process *create(JSC::VM &vm, JSC::Structure *structure) { + Process *accessor = new (NotNull, JSC::allocateCell<Process>(vm.heap)) Process(vm, structure); + accessor->finishCreation(vm); + return accessor; + } + + void finishCreation(JSC::VM &vm); +}; + +} // namespace Zig
\ No newline at end of file diff --git a/src/javascript/jsc/bindings/ZigGlobalObject.cpp b/src/javascript/jsc/bindings/ZigGlobalObject.cpp index e113e4df2..0329024a4 100644 --- a/src/javascript/jsc/bindings/ZigGlobalObject.cpp +++ b/src/javascript/jsc/bindings/ZigGlobalObject.cpp @@ -26,6 +26,7 @@ #include <JavaScriptCore/JSCallbackObject.h> #include <JavaScriptCore/JSCast.h> #include <JavaScriptCore/JSClassRef.h> +#include <JavaScriptCore/JSMicrotask.h> // #include <JavaScriptCore/JSContextInternal.h> #include <JavaScriptCore/CatchScope.h> #include <JavaScriptCore/JSInternalPromise.h> @@ -51,6 +52,7 @@ #include <JavaScriptCore/VM.h> #include <JavaScriptCore/VMEntryScope.h> #include <JavaScriptCore/WasmFaultSignalHandler.h> +#include <unistd.h> #include <wtf/Gigacage.h> #include <wtf/StdLibExtras.h> #include <wtf/URL.h> @@ -68,6 +70,8 @@ #include <JavaScriptCore/JSCallbackObject.h> #include <JavaScriptCore/JSClassRef.h> +#include "BunClientData.h" + #include "ZigSourceProvider.h" using JSGlobalObject = JSC::JSGlobalObject; @@ -82,21 +86,20 @@ using JSObject = JSC::JSObject; using JSNonFinalObject = JSC::JSNonFinalObject; namespace JSCastingHelpers = JSC::JSCastingHelpers; -bool has_loaded_jsc = false; +static bool has_loaded_jsc = false; extern "C" void JSCInitialize() { if (has_loaded_jsc) return; + has_loaded_jsc = true; + JSC::Options::useSourceProviderCache() = true; JSC::Options::useUnlinkedCodeBlockJettisoning() = false; JSC::Options::exposeInternalModuleLoader() = true; JSC::Options::useSharedArrayBuffer() = true; // JSC::Options::useAtMethod() = true; - // std::set_terminate([]() { Zig__GlobalObject__onCrash(); }); WTF::initializeMainThread(); JSC::initialize(); - // Gigacage::disablePrimitiveGigacage(); - has_loaded_jsc = true; } extern "C" JSC__JSGlobalObject *Zig__GlobalObject__create(JSClassRef *globalObjectClass, int count, @@ -104,6 +107,8 @@ extern "C" JSC__JSGlobalObject *Zig__GlobalObject__create(JSClassRef *globalObje auto heapSize = JSC::LargeHeap; JSC::VM &vm = JSC::VM::create(heapSize).leakRef(); + Bun::JSVMClientData::create(&vm); + vm.heap.acquireAccess(); #if ENABLE(WEBASSEMBLY) JSC::Wasm::enableFastMemory(); @@ -257,33 +262,80 @@ void GlobalObject::setConsole(void *console) { this->setConsoleClient(makeWeakPtr(m_console)); } +#pragma mark - Globals + +static JSC_DECLARE_CUSTOM_SETTER(property_lazyProcessSetter); +static JSC_DECLARE_CUSTOM_GETTER(property_lazyProcessGetter); + +JSC_DEFINE_CUSTOM_SETTER(property_lazyProcessSetter, + (JSC::JSGlobalObject * globalObject, JSC::EncodedJSValue thisValue, + JSC::EncodedJSValue value, JSC::PropertyName)) { + return false; +} + +static JSClassRef dot_env_class_ref; +JSC_DEFINE_CUSTOM_GETTER(property_lazyProcessGetter, + (JSC::JSGlobalObject * _globalObject, JSC::EncodedJSValue thisValue, + JSC::PropertyName)) { + Zig::GlobalObject *globalObject = reinterpret_cast<Zig::GlobalObject *>(_globalObject); + if (LIKELY(globalObject->m_process)) + return JSValue::encode(JSC::JSValue(globalObject->m_process)); + + JSC::VM &vm = globalObject->vm(); + + globalObject->m_process = Zig::Process::create( + vm, Zig::Process::createStructure(vm, globalObject, globalObject->objectPrototype())); + + { + auto jsClass = dot_env_class_ref; + + JSC::JSCallbackObject<JSNonFinalObject> *object = + JSC::JSCallbackObject<JSNonFinalObject>::create( + globalObject, globalObject->callbackObjectStructure(), jsClass, nullptr); + if (JSObject *prototype = jsClass->prototype(globalObject)) + object->setPrototypeDirect(vm, prototype); + + globalObject->m_process->putDirect(vm, JSC::Identifier::fromString(vm, "env"), + JSC::JSValue(object), + JSC::PropertyAttribute::DontDelete | 0); + } + + return JSC::JSValue::encode(JSC::JSValue(globalObject->m_process)); +} + +static JSC_DECLARE_HOST_FUNCTION(functionQueueMicrotask); + +static JSC_DEFINE_HOST_FUNCTION(functionQueueMicrotask, + (JSC::JSGlobalObject * globalObject, JSC::CallFrame *callFrame)) { + JSC::VM &vm = globalObject->vm(); + + if (callFrame->argumentCount() == 0) { + auto scope = DECLARE_THROW_SCOPE(globalObject->vm()); + JSC::throwTypeError(globalObject, scope, "queueMicrotask requires 1 argument (a function)"_s); + return JSC::JSValue::encode(JSC::JSValue{}); + } + + JSC::JSValue job = callFrame->argument(0); + + if (!job.isObject() || !job.getObject()->isCallable(vm)) { + auto scope = DECLARE_THROW_SCOPE(globalObject->vm()); + JSC::throwTypeError(globalObject, scope, "queueMicrotask expects a function"_s); + return JSC::JSValue::encode(JSC::JSValue{}); + } + + // This is a JSC builtin function + globalObject->queueMicrotask(JSC::createJSMicrotask(vm, job)); + + return JSC::JSValue::encode(JSC::jsUndefined()); +} + // This is not a publicly exposed API currently. // This is used by the bundler to make Response, Request, FetchEvent, // and any other objects available globally. void GlobalObject::installAPIGlobals(JSClassRef *globals, int count) { WTF::Vector<GlobalPropertyInfo> extraStaticGlobals; - extraStaticGlobals.reserveCapacity((size_t)count + 2); - - // This is not nearly a complete implementation. It's just enough to make some npm packages that - // were compiled with Webpack to run without crashing in this environment. - JSC::JSObject *process = JSC::constructEmptyObject(this, this->objectPrototype(), 4); - - // this should be transpiled out, but just incase - process->putDirect(this->vm(), JSC::Identifier::fromString(this->vm(), "browser"), - JSC::JSValue(false)); - - // this gives some way of identifying at runtime whether the SSR is happening in node or not. - // this should probably be renamed to what the name of the bundler is, instead of "notNodeJS" - // but it must be something that won't evaluate to truthy in Node.js - process->putDirect(this->vm(), JSC::Identifier::fromString(this->vm(), "isBun"), - JSC::JSValue(true)); -#if defined(__APPLE__) - process->putDirect(this->vm(), JSC::Identifier::fromString(this->vm(), "platform"), - JSC::jsString(this->vm(), WTF::String("darwin"))); -#else - process->putDirect(this->vm(), JSC::Identifier::fromString(this->vm(), "platform"), - JSC::jsString(this->vm(), WTF::String("linux"))); -#endif + extraStaticGlobals.reserveCapacity((size_t)count + 3); + int i = 0; for (; i < count - 1; i++) { auto jsClass = globals[i]; @@ -300,23 +352,38 @@ void GlobalObject::installAPIGlobals(JSClassRef *globals, int count) { // The last one must be "process.env" // Runtime-support is for if they change - { - auto jsClass = globals[i]; + dot_env_class_ref = globals[i]; - JSC::JSCallbackObject<JSNonFinalObject> *object = - JSC::JSCallbackObject<JSNonFinalObject>::create(this, this->callbackObjectStructure(), - jsClass, nullptr); - if (JSObject *prototype = jsClass->prototype(this)) object->setPrototypeDirect(vm(), prototype); + // // The last one must be "process.env" + // // Runtime-support is for if they change + // { + // auto jsClass = globals[i]; - process->putDirect(this->vm(), JSC::Identifier::fromString(this->vm(), "env"), - JSC::JSValue(object), JSC::PropertyAttribute::DontDelete | 0); - } + // JSC::JSCallbackObject<JSNonFinalObject> *object = + // JSC::JSCallbackObject<JSNonFinalObject>::create(this, this->callbackObjectStructure(), + // jsClass, nullptr); + // if (JSObject *prototype = jsClass->prototype(this)) object->setPrototypeDirect(vm(), + // prototype); + + // process->putDirect(this->vm(), JSC::Identifier::fromString(this->vm(), "env"), + // JSC::JSValue(object), JSC::PropertyAttribute::DontDelete | 0); + // } + JSC::Identifier queueMicrotaskIdentifier = JSC::Identifier::fromString(vm(), "queueMicrotask"_s); extraStaticGlobals.uncheckedAppend( - GlobalPropertyInfo{JSC::Identifier::fromString(vm(), "process"), JSC::JSValue(process), + GlobalPropertyInfo{queueMicrotaskIdentifier, + JSC::JSFunction::create(vm(), JSC::jsCast<JSC::JSGlobalObject *>(this), 0, + "queueMicrotask", functionQueueMicrotask), JSC::PropertyAttribute::DontDelete | 0}); + auto clientData = Bun::clientData(vm()); + this->addStaticGlobals(extraStaticGlobals.data(), extraStaticGlobals.size()); + putDirectCustomAccessor( + vm(), clientData->builtinNames().processPublicName(), + JSC::CustomGetterSetter::create(vm(), property_lazyProcessGetter, property_lazyProcessSetter), + JSC::PropertyAttribute::CustomValue | 0); + extraStaticGlobals.releaseBuffer(); } @@ -418,7 +485,6 @@ JSC::JSObject *GlobalObject::moduleLoaderCreateImportMetaProperties(JSGlobalObje JSModuleRecord *record, JSValue val) { - ZigString specifier = Zig::toZigString(key, globalObject); JSC::VM &vm = globalObject->vm(); auto scope = DECLARE_THROW_SCOPE(vm); @@ -426,7 +492,16 @@ JSC::JSObject *GlobalObject::moduleLoaderCreateImportMetaProperties(JSGlobalObje JSC::constructEmptyObject(vm, globalObject->nullPrototypeObjectStructure()); RETURN_IF_EXCEPTION(scope, nullptr); - metaProperties->putDirect(vm, Identifier::fromString(vm, "filePath"), key); + auto clientData = Bun::clientData(vm); + JSString *keyString = key.toStringOrNull(globalObject); + if (UNLIKELY(!keyString)) { return metaProperties; } + auto view = keyString->value(globalObject); + auto index = view.reverseFind('/', view.length()); + if (index != WTF::notFound) { + metaProperties->putDirect(vm, clientData->builtinNames().dirPublicName(), + JSC::jsSubstring(globalObject, keyString, 0, index)); + } + metaProperties->putDirect(vm, clientData->builtinNames().pathPublicName(), key); RETURN_IF_EXCEPTION(scope, nullptr); // metaProperties->putDirect(vm, Identifier::fromString(vm, "resolve"), diff --git a/src/javascript/jsc/bindings/ZigGlobalObject.h b/src/javascript/jsc/bindings/ZigGlobalObject.h index 64ece0c64..3d5d389e0 100644 --- a/src/javascript/jsc/bindings/ZigGlobalObject.h +++ b/src/javascript/jsc/bindings/ZigGlobalObject.h @@ -9,11 +9,13 @@ class Identifier; } // namespace JSC +#include "Process.h" #include "ZigConsoleClient.h" #include <JavaScriptCore/CatchScope.h> #include <JavaScriptCore/JSGlobalObject.h> #include <JavaScriptCore/JSTypeInfo.h> #include <JavaScriptCore/Structure.h> + namespace Zig { class GlobalObject : public JSC::JSGlobalObject { @@ -22,7 +24,7 @@ class GlobalObject : public JSC::JSGlobalObject { public: DECLARE_EXPORT_INFO; static const JSC::GlobalObjectMethodTable s_globalObjectMethodTable; - + Zig::Process *m_process; static constexpr bool needsDestruction = true; template <typename CellType, JSC::SubspaceAccess mode> static JSC::IsoSubspace *subspaceFor(JSC::VM &vm) { @@ -74,17 +76,14 @@ class JSMicrotaskCallback : public RefCounted<JSMicrotaskCallback> { public: static Ref<JSMicrotaskCallback> create(JSC::JSGlobalObject &globalObject, Ref<JSC::Microtask> &&task) { - return adoptRef(*new JSMicrotaskCallback(globalObject, WTFMove(task))); + return adoptRef(*new JSMicrotaskCallback(globalObject, WTFMove(task).leakRef())); } void call() { auto protectedThis{makeRef(*this)}; JSC::VM &vm = m_globalObject->vm(); - JSC::JSLockHolder lock(vm); - auto scope = DECLARE_CATCH_SCOPE(vm); auto task = &m_task.get(); task->run(m_globalObject.get()); - scope.assertNoExceptionExceptTermination(); } private: diff --git a/src/javascript/jsc/bindings/bindings.cpp b/src/javascript/jsc/bindings/bindings.cpp index 60b6a442e..7af7d3a25 100644 --- a/src/javascript/jsc/bindings/bindings.cpp +++ b/src/javascript/jsc/bindings/bindings.cpp @@ -1,3 +1,4 @@ +#include "BunClientData.h" #include "ZigGlobalObject.h" #include "helpers.h" #include "root.h" @@ -6,8 +7,10 @@ #include <JavaScriptCore/CodeBlock.h> #include <JavaScriptCore/Completion.h> #include <JavaScriptCore/ErrorInstance.h> +#include <JavaScriptCore/ExceptionHelpers.h> #include <JavaScriptCore/ExceptionScope.h> #include <JavaScriptCore/FunctionConstructor.h> +#include <JavaScriptCore/HeapSnapshotBuilder.h> #include <JavaScriptCore/Identifier.h> #include <JavaScriptCore/IteratorOperations.h> #include <JavaScriptCore/JSArray.h> @@ -20,6 +23,7 @@ #include <JavaScriptCore/JSModuleLoader.h> #include <JavaScriptCore/JSModuleRecord.h> #include <JavaScriptCore/JSNativeStdFunction.h> +#include <JavaScriptCore/JSONObject.h> #include <JavaScriptCore/JSObject.h> #include <JavaScriptCore/JSSet.h> #include <JavaScriptCore/JSString.h> @@ -31,6 +35,7 @@ #include <JavaScriptCore/StackVisitor.h> #include <JavaScriptCore/VM.h> #include <JavaScriptCore/WasmFaultSignalHandler.h> +#include <JavaScriptCore/Watchdog.h> #include <wtf/text/ExternalStringImpl.h> #include <wtf/text/StringCommon.h> #include <wtf/text/StringImpl.h> @@ -39,6 +44,62 @@ extern "C" { +JSC__JSValue SystemError__toErrorInstance(const SystemError *arg0, + JSC__JSGlobalObject *globalObject) { + + static const char *system_error_name = "SystemError"; + SystemError err = *arg0; + + JSC::VM &vm = globalObject->vm(); + + auto scope = DECLARE_THROW_SCOPE(vm); + JSC::JSValue message = JSC::jsUndefined(); + if (err.message.len > 0) { message = Zig::toJSString(err.message, globalObject); } + + JSC::JSValue options = JSC::jsUndefined(); + + JSC::Structure *errorStructure = globalObject->errorStructure(); + JSC::JSObject *result = + JSC::ErrorInstance::create(globalObject, errorStructure, message, options); + + auto clientData = Bun::clientData(vm); + + if (err.code.len > 0) { + JSC::JSValue code = Zig::toJSString(err.code, globalObject); + result->putDirect(vm, clientData->builtinNames().codePublicName(), code, + JSC::PropertyAttribute::DontDelete | 0); + + result->putDirect(vm, vm.propertyNames->name, code, JSC::PropertyAttribute::DontEnum | 0); + } else { + + result->putDirect( + vm, vm.propertyNames->name, + JSC::JSValue(JSC::jsOwnedString( + vm, WTF::String(WTF::StringImpl::createWithoutCopying(system_error_name, 11)))), + JSC::PropertyAttribute::DontEnum | 0); + } + + if (err.path.len > 0) { + JSC::JSValue path = JSC::JSValue(Zig::toJSStringGC(err.path, globalObject)); + result->putDirect(vm, clientData->builtinNames().pathPublicName(), path, + JSC::PropertyAttribute::DontDelete | 0); + } + + if (err.syscall.len > 0) { + JSC::JSValue syscall = JSC::JSValue(Zig::toJSString(err.syscall, globalObject)); + result->putDirect(vm, clientData->builtinNames().syscallPublicName(), syscall, + JSC::PropertyAttribute::DontDelete | 0); + } + + result->putDirect(vm, clientData->builtinNames().errnoPublicName(), JSC::JSValue(err.errno_), + JSC::PropertyAttribute::DontDelete | 0); + + RETURN_IF_EXCEPTION(scope, JSC::JSValue::encode(JSC::JSValue())); + scope.release(); + + return JSC::JSValue::encode(JSC::JSValue(result)); +} + JSC__JSValue JSC__JSObject__create(JSC__JSGlobalObject *globalObject, size_t initialCapacity, void *arg2, void (*ArgFn3)(void *arg0, JSC__JSObject *arg1, JSC__JSGlobalObject *arg2)) { @@ -147,6 +208,19 @@ void JSC__JSValue__putRecord(JSC__JSValue objectValue, JSC__JSGlobalObject *glob scope.release(); } +void JSC__JSValue__jsonStringify(JSC__JSValue JSValue0, JSC__JSGlobalObject *arg1, uint32_t arg2, + ZigString *arg3) { + JSC::JSValue value = JSC::JSValue::decode(JSValue0); + WTF::String str = JSC::JSONStringify(arg1, value, (unsigned)arg2); + *arg3 = Zig::toZigString(str); +} +unsigned char JSC__JSValue__jsType(JSC__JSValue JSValue0) { + JSC::JSValue jsValue = JSC::JSValue::decode(JSValue0); + if (!jsValue.isCell()) return 0; + + return jsValue.asCell()->type(); +} + // This is very naive! JSC__JSInternalPromise *JSC__VM__reloadModule(JSC__VM *vm, JSC__JSGlobalObject *arg1, ZigString arg2) { @@ -175,6 +249,12 @@ JSC__JSInternalPromise *JSC__VM__reloadModule(JSC__VM *vm, JSC__JSGlobalObject * // return nullptr; } +bool JSC__JSValue__isSameValue(JSC__JSValue JSValue0, JSC__JSValue JSValue1, + JSC__JSGlobalObject *globalObject) { + return JSC::sameValue(globalObject, JSC::JSValue::decode(JSValue0), + JSC::JSValue::decode(JSValue1)); +} + // This is the same as the C API version, except it returns a JSValue which may be a *Exception // We want that so we can return stack traces. JSC__JSValue JSObjectCallAsFunctionReturnValue(JSContextRef ctx, JSObjectRef object, @@ -211,6 +291,44 @@ JSC__JSValue JSObjectCallAsFunctionReturnValue(JSContextRef ctx, JSObjectRef obj return JSC::JSValue::encode(result); } +JSC__JSValue JSObjectCallAsFunctionReturnValueHoldingAPILock(JSContextRef ctx, JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef *arguments); + +JSC__JSValue JSObjectCallAsFunctionReturnValueHoldingAPILock(JSContextRef ctx, JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef *arguments) { + JSC::JSGlobalObject *globalObject = toJS(ctx); + JSC::VM &vm = globalObject->vm(); + + JSC::JSLockHolder lock(vm); + + if (!object) return JSC::JSValue::encode(JSC::JSValue()); + + JSC::JSObject *jsObject = toJS(object); + JSC::JSObject *jsThisObject = toJS(thisObject); + + if (!jsThisObject) jsThisObject = globalObject->globalThis(); + + JSC::MarkedArgumentBuffer argList; + for (size_t i = 0; i < argumentCount; i++) argList.append(toJS(globalObject, arguments[i])); + + auto callData = getCallData(vm, jsObject); + if (callData.type == JSC::CallData::Type::None) return JSC::JSValue::encode(JSC::JSValue()); + + NakedPtr<JSC::Exception> returnedException = nullptr; + auto result = + JSC::call(globalObject, jsObject, callData, jsThisObject, argList, returnedException); + + if (returnedException.get()) { + return JSC::JSValue::encode(JSC::JSValue(returnedException.get())); + } + + return JSC::JSValue::encode(result); +} + #pragma mark - JSC::Exception JSC__Exception *JSC__Exception__create(JSC__JSGlobalObject *arg0, JSC__JSObject *arg1, @@ -236,10 +354,10 @@ JSC__JSValue JSC__JSObject__getIndex(JSC__JSValue jsValue, JSC__JSGlobalObject * return JSC::JSValue::encode(JSC::JSValue::decode(jsValue).toObject(arg1)->getIndex(arg1, arg3)); } JSC__JSValue JSC__JSObject__getDirect(JSC__JSObject *arg0, JSC__JSGlobalObject *arg1, - const ZigString * arg2) { + const ZigString *arg2) { return JSC::JSValue::encode(arg0->getDirect(arg1->vm(), Zig::toIdentifier(*arg2, arg1))); } -void JSC__JSObject__putDirect(JSC__JSObject *arg0, JSC__JSGlobalObject *arg1, const ZigString * key, +void JSC__JSObject__putDirect(JSC__JSObject *arg0, JSC__JSGlobalObject *arg1, const ZigString *key, JSC__JSValue value) { auto prop = Zig::toIdentifier(*key, arg1); @@ -348,10 +466,85 @@ static JSC::JSValue doLink(JSC__JSGlobalObject *globalObject, JSC::JSValue modul return JSC::linkAndEvaluateModule(globalObject, moduleKey, JSC::JSValue()); } +JSC__JSValue JSC__JSValue__createRangeError(const ZigString *message, const ZigString *arg1, + JSC__JSGlobalObject *globalObject) { + JSC::VM &vm = globalObject->vm(); + ZigString code = *arg1; + JSC::JSObject *rangeError = Zig::getErrorInstance(message, globalObject).asCell()->getObject(); + static const char *range_error_name = "RangeError"; + + rangeError->putDirect( + vm, vm.propertyNames->name, + JSC::JSValue(JSC::jsOwnedString( + vm, WTF::String(WTF::StringImpl::createWithoutCopying(range_error_name, 10)))), + 0); + + if (code.len > 0) { + auto clientData = Bun::clientData(vm); + JSC::JSValue codeValue = Zig::toJSStringValue(code, globalObject); + rangeError->putDirect(vm, clientData->builtinNames().codePublicName(), codeValue, + JSC::PropertyAttribute::ReadOnly | 0); + } + + return JSC::JSValue::encode(rangeError); +} +JSC__JSValue JSC__JSValue__createTypeError(const ZigString *message, const ZigString *arg1, + JSC__JSGlobalObject *globalObject) { + JSC::VM &vm = globalObject->vm(); + ZigString code = *arg1; + JSC::JSObject *typeError = Zig::getErrorInstance(message, globalObject).asCell()->getObject(); + static const char *range_error_name = "TypeError"; + + typeError->putDirect( + vm, vm.propertyNames->name, + JSC::JSValue(JSC::jsOwnedString( + vm, WTF::String(WTF::StringImpl::createWithoutCopying(range_error_name, 10)))), + 0); + + if (code.len > 0) { + auto clientData = Bun::clientData(vm); + JSC::JSValue codeValue = Zig::toJSStringValue(code, globalObject); + typeError->putDirect(vm, clientData->builtinNames().codePublicName(), codeValue, 0); + } + + return JSC::JSValue::encode(typeError); +} + +JSC__JSValue JSC__JSValue__fromEntries(JSC__JSGlobalObject *globalObject, ZigString *keys, + ZigString *values, size_t initialCapacity, bool clone) { + JSC::VM &vm = globalObject->vm(); + auto scope = DECLARE_THROW_SCOPE(vm); + if (initialCapacity == 0) { + return JSC::JSValue::encode(JSC::constructEmptyObject(globalObject)); + } + + JSC::JSObject *object = nullptr; + { + JSC::ObjectInitializationScope initializationScope(vm); + object = + JSC::constructEmptyObject(globalObject, globalObject->objectPrototype(), initialCapacity); + + if (!clone) { + for (size_t i = 0; i < initialCapacity; ++i) { + object->putDirect( + vm, JSC::PropertyName(JSC::Identifier::fromString(vm, Zig::toString(keys[i]))), + Zig::toJSStringValueGC(values[i], globalObject), 0); + } + } else { + for (size_t i = 0; i < initialCapacity; ++i) { + object->putDirect(vm, JSC::PropertyName(Zig::toIdentifier(keys[i], globalObject)), + Zig::toJSStringValueGC(values[i], globalObject), 0); + } + } + } + + return JSC::JSValue::encode(object); +} JSC__JSValue JSC__JSValue__createStringArray(JSC__JSGlobalObject *globalObject, ZigString *arg1, - size_t arg2) { + size_t arg2, bool clone) { JSC::VM &vm = globalObject->vm(); auto scope = DECLARE_THROW_SCOPE(vm); + if (arg2 == 0) { return JSC::JSValue::encode(JSC::JSArray::create(vm, 0)); } JSC::JSArray *array = nullptr; { @@ -361,8 +554,14 @@ JSC__JSValue JSC__JSValue__createStringArray(JSC__JSGlobalObject *globalObject, globalObject->arrayStructureForIndexingTypeDuringAllocation(JSC::ArrayWithContiguous), arg2))) { - for (size_t i = 0; i < arg2; ++i) { - array->putDirectIndex(globalObject, i, JSC::jsString(vm, Zig::toStringCopy(arg1[i]))); + if (!clone) { + for (size_t i = 0; i < arg2; ++i) { + array->putDirectIndex(globalObject, i, JSC::jsString(vm, Zig::toString(arg1[i]))); + } + } else { + for (size_t i = 0; i < arg2; ++i) { + array->putDirectIndex(globalObject, i, JSC::jsString(vm, Zig::toStringCopy(arg1[i]))); + } } } } @@ -376,7 +575,7 @@ JSC__JSValue JSC__JSValue__createStringArray(JSC__JSGlobalObject *globalObject, JSC__JSValue JSC__JSGlobalObject__createAggregateError(JSC__JSGlobalObject *globalObject, void **errors, uint16_t errors_count, - const ZigString * arg3) { + const ZigString *arg3) { JSC::VM &vm = globalObject->vm(); auto scope = DECLARE_THROW_SCOPE(vm); @@ -411,34 +610,34 @@ JSC__JSValue JSC__JSGlobalObject__createAggregateError(JSC__JSGlobalObject *glob // static JSC::JSNativeStdFunction* rejecterFunction; // static bool resolverFunctionInitialized = false; -JSC__JSValue ZigString__toValue(const ZigString * arg0, JSC__JSGlobalObject *arg1) { +JSC__JSValue ZigString__toValue(const ZigString *arg0, JSC__JSGlobalObject *arg1) { return JSC::JSValue::encode(JSC::JSValue(JSC::jsOwnedString(arg1->vm(), Zig::toString(*arg0)))); } -JSC__JSValue ZigString__toValueGC(const ZigString * arg0, JSC__JSGlobalObject *arg1) { +JSC__JSValue ZigString__to16BitValue(const ZigString *arg0, JSC__JSGlobalObject *arg1) { + auto str = WTF::String::fromUTF8(arg0->ptr, arg0->len); + return JSC::JSValue::encode(JSC::JSValue(JSC::jsString(arg1->vm(), str))); +} + +JSC__JSValue ZigString__toValueGC(const ZigString *arg0, JSC__JSGlobalObject *arg1) { return JSC::JSValue::encode( - JSC::JSValue(JSC::jsMakeNontrivialString(arg1->vm(), Zig::toString(*arg0)))); + JSC::JSValue(JSC::jsMakeNontrivialString(arg1->vm(), Zig::toStringCopy(*arg0)))); } void JSC__JSValue__toZigString(JSC__JSValue JSValue0, ZigString *arg1, JSC__JSGlobalObject *arg2) { JSC::JSValue value = JSC::JSValue::decode(JSValue0); auto str = value.toWTFString(arg2); - arg1->ptr = str.characters8(); + if (str.is8Bit()) { + arg1->ptr = str.characters8(); + } else { + arg1->ptr = Zig::taggedUTF16Ptr(str.characters16()); + } + arg1->len = str.length(); } -JSC__JSValue ZigString__toErrorInstance(const ZigString *str, JSC__JSGlobalObject *globalObject) { - JSC::VM &vm = globalObject->vm(); - auto scope = DECLARE_THROW_SCOPE(vm); - JSC::JSValue message = Zig::toJSString(*str, globalObject); - JSC::JSValue options = JSC::jsUndefined(); - JSC::Structure *errorStructure = globalObject->errorStructure(); - JSC::JSObject *result = - JSC::ErrorInstance::create(globalObject, errorStructure, message, options); - RETURN_IF_EXCEPTION(scope, JSC::JSValue::encode(JSC::JSValue())); - scope.release(); - - return JSC::JSValue::encode(JSC::JSValue(result)); +JSC__JSValue ZigString__toErrorInstance(const ZigString *str, JSC__JSGlobalObject *globalObject) { + return JSC::JSValue::encode(Zig::getErrorInstance(str, globalObject)); } static JSC::EncodedJSValue resolverFunctionCallback(JSC::JSGlobalObject *globalObject, @@ -447,7 +646,8 @@ static JSC::EncodedJSValue resolverFunctionCallback(JSC::JSGlobalObject *globalO } JSC__JSInternalPromise * -JSC__JSModuleLoader__loadAndEvaluateModule(JSC__JSGlobalObject *globalObject, const ZigString * arg1) { +JSC__JSModuleLoader__loadAndEvaluateModule(JSC__JSGlobalObject *globalObject, + const ZigString *arg1) { globalObject->vm().drainMicrotasks(); auto name = Zig::toString(*arg1); name.impl()->ref(); @@ -768,6 +968,22 @@ bWTF__String JSC__JSFunction__calculatedDisplayName(JSC__JSFunction *arg0, JSC__ }; #pragma mark - JSC::JSGlobalObject +JSC__JSValue JSC__JSGlobalObject__generateHeapSnapshot(JSC__JSGlobalObject *globalObject) { + JSC::VM &vm = globalObject->vm(); + + JSC::JSLockHolder lock(vm); + // JSC::DeferTermination deferScope(vm); + auto scope = DECLARE_THROW_SCOPE(vm); + + JSC::HeapSnapshotBuilder snapshotBuilder(vm.ensureHeapProfiler()); + snapshotBuilder.buildSnapshot(); + + WTF::String jsonString = snapshotBuilder.json(); + JSC::EncodedJSValue result = JSC::JSValue::encode(JSONParse(globalObject, jsonString)); + scope.releaseAssertNoException(); + return result; +} + JSC__ArrayIteratorPrototype * JSC__JSGlobalObject__arrayIteratorPrototype(JSC__JSGlobalObject *arg0) { return arg0->arrayIteratorPrototype(); @@ -1006,6 +1222,45 @@ JSC__JSValue JSC__JSValue__jsNumberFromUint64(uint64_t arg0) { return JSC::JSValue::encode(JSC::jsNumber(arg0)); }; +JSC__JSValue JSC__JSValue__createObject2(JSC__JSGlobalObject *globalObject, const ZigString *arg1, + const ZigString *arg2, JSC__JSValue JSValue3, + JSC__JSValue JSValue4) { + JSC::JSObject *object = JSC::constructEmptyObject(globalObject); + auto key1 = Zig::toIdentifier(*arg1, globalObject); + JSC::PropertyDescriptor descriptor1; + JSC::PropertyDescriptor descriptor2; + + descriptor1.setEnumerable(1); + descriptor1.setConfigurable(1); + descriptor1.setWritable(1); + descriptor1.setValue(JSC::JSValue::decode(JSValue3)); + + auto key2 = Zig::toIdentifier(*arg2, globalObject); + + descriptor2.setEnumerable(1); + descriptor2.setConfigurable(1); + descriptor2.setWritable(1); + descriptor2.setValue(JSC::JSValue::decode(JSValue4)); + + object->methodTable(globalObject->vm()) + ->defineOwnProperty(object, globalObject, key2, descriptor2, true); + object->methodTable(globalObject->vm()) + ->defineOwnProperty(object, globalObject, key1, descriptor1, true); + + return JSC::JSValue::encode(object); +} + +JSC__JSValue JSC__JSValue__getIfPropertyExistsImpl(JSC__JSValue JSValue0, + JSC__JSGlobalObject *globalObject, + const unsigned char *arg1, uint32_t arg2) { + + JSC::VM &vm = globalObject->vm(); + JSC::JSObject *object = JSC::JSValue::decode(JSValue0).asCell()->getObject(); + auto propertyName = JSC::PropertyName( + JSC::Identifier::fromString(vm, reinterpret_cast<const LChar *>(arg1), (int)arg2)); + return JSC::JSValue::encode(object->getIfPropertyExists(globalObject, propertyName)); +} + bool JSC__JSValue__toBoolean(JSC__JSValue JSValue0) { return JSC::JSValue::decode(JSValue0).asBoolean(); } @@ -1274,9 +1529,10 @@ static void fromErrorInstance(ZigException *except, JSC::JSGlobalObject *global, if (err->isStackOverflowError()) { except->code = 253; } if (err->isOutOfMemoryError()) { except->code = 8; } - if (obj->hasProperty(global, global->vm().propertyNames->message)) { - except->message = Zig::toZigString( - obj->getDirect(global->vm(), global->vm().propertyNames->message).toWTFString(global)); + if (JSC::JSValue message = + obj->getIfPropertyExists(global, global->vm().propertyNames->message)) { + + except->message = Zig::toZigString(message, global); } else { except->message = Zig::toZigString(err->sanitizedMessageString(global)); @@ -1284,19 +1540,40 @@ static void fromErrorInstance(ZigException *except, JSC::JSGlobalObject *global, except->name = Zig::toZigString(err->sanitizedNameString(global)); except->runtime_type = err->runtimeTypeForCause(); + auto clientData = Bun::clientData(global->vm()); + + if (JSC::JSValue syscall = + obj->getIfPropertyExists(global, clientData->builtinNames().syscallPublicName())) { + except->syscall = Zig::toZigString(syscall, global); + } + + if (JSC::JSValue code = + obj->getIfPropertyExists(global, clientData->builtinNames().codePublicName())) { + except->code_ = Zig::toZigString(code, global); + } + + if (JSC::JSValue path = + obj->getIfPropertyExists(global, clientData->builtinNames().pathPublicName())) { + except->path = Zig::toZigString(path, global); + } + + if (JSC::JSValue errno_ = + obj->getIfPropertyExists(global, clientData->builtinNames().errnoPublicName())) { + except->errno_ = errno_.toInt32(global); + } + if (getFromSourceURL) { - if (obj->hasProperty(global, global->vm().propertyNames->sourceURL)) { - except->stack.frames_ptr[0].source_url = Zig::toZigString( - obj->getDirect(global->vm(), global->vm().propertyNames->sourceURL).toWTFString(global)); + if (JSC::JSValue sourceURL = + obj->getIfPropertyExists(global, global->vm().propertyNames->sourceURL)) { + except->stack.frames_ptr[0].source_url = Zig::toZigString(sourceURL, global); - if (obj->hasProperty(global, global->vm().propertyNames->line)) { - except->stack.frames_ptr[0].position.line = - obj->getDirect(global->vm(), global->vm().propertyNames->line).toInt32(global); + if (JSC::JSValue line = obj->getIfPropertyExists(global, global->vm().propertyNames->line)) { + except->stack.frames_ptr[0].position.line = line.toInt32(global); } - if (obj->hasProperty(global, global->vm().propertyNames->column)) { - except->stack.frames_ptr[0].position.column_start = - obj->getDirect(global->vm(), global->vm().propertyNames->column).toInt32(global); + if (JSC::JSValue column = + obj->getIfPropertyExists(global, global->vm().propertyNames->column)) { + except->stack.frames_ptr[0].position.column_start = column.toInt32(global); } except->stack.frames_len = 1; } @@ -1469,8 +1746,36 @@ const WTF__StringImpl *JSC__PropertyName__uid(JSC__PropertyName *arg0) { return #pragma mark - JSC::VM +JSC__JSValue JSC__VM__runGC(JSC__VM *vm, bool sync) { + JSC::JSLockHolder lock(vm); + + if (sync) { + vm->heap.collectNow(JSC::Sync, JSC::CollectionScope::Full); + } else { + vm->heap.collectSync(JSC::CollectionScope::Full); + } + + return JSC::JSValue::encode(JSC::jsNumber(vm->heap.sizeAfterLastFullCollection())); +} + bool JSC__VM__isJITEnabled() { return JSC::Options::useJIT(); } +void JSC__VM__clearExecutionTimeLimit(JSC__VM *vm) { + JSC::JSLockHolder locker(vm); + if (vm->watchdog()) vm->watchdog()->setTimeLimit(JSC::Watchdog::noTimeLimit); +} +void JSC__VM__setExecutionTimeLimit(JSC__VM *vm, double limit) { + JSC::JSLockHolder locker(vm); + JSC::Watchdog &watchdog = vm->ensureWatchdog(); + watchdog.setTimeLimit(WTF::Seconds{limit}); +} + +bool JSC__JSValue__isTerminationException(JSC__JSValue JSValue0, JSC__VM *arg1) { + JSC::Exception *exception = + JSC::jsDynamicCast<JSC::Exception *>(*arg1, JSC::JSValue::decode(JSValue0)); + return exception != NULL && arg1->isTerminationException(exception); +} + void JSC__VM__shrinkFootprint(JSC__VM *arg0) { arg0->shrinkFootprintWhenIdle(); }; void JSC__VM__whenIdle(JSC__VM *arg0, void (*ArgFn1)()) { arg0->whenIdle(ArgFn1); }; @@ -1485,6 +1790,11 @@ JSC__VM *JSC__VM__create(unsigned char HeapType0) { return vm; } +void JSC__VM__holdAPILock(JSC__VM *arg0, void *ctx, void (*callback)(void *arg0)) { + JSC::JSLockHolder locker(arg0); + callback(ctx); +} + void JSC__VM__deleteAllCode(JSC__VM *arg1, JSC__JSGlobalObject *globalObject) { JSC::JSLockHolder locker(globalObject->vm()); diff --git a/src/javascript/jsc/bindings/bindings.zig b/src/javascript/jsc/bindings/bindings.zig index 971782e0b..a28717400 100644 --- a/src/javascript/jsc/bindings/bindings.zig +++ b/src/javascript/jsc/bindings/bindings.zig @@ -7,7 +7,7 @@ const hasRef = std.meta.trait.hasField("ref"); const C_API = @import("../../../jsc.zig").C; const StringPointer = @import("../../../api/schema.zig").Api.StringPointer; const Exports = @import("./exports.zig"); - +const strings = _global.strings; const ErrorableZigString = Exports.ErrorableZigString; const ErrorableResolvedSource = Exports.ErrorableResolvedSource; const ZigException = Exports.ZigException; @@ -71,15 +71,6 @@ pub const JSObject = extern struct { }); } - pub fn putDirect(this: *JSObject, globalThis: *JSGlobalObject, prop: *const ZigString, value: JSValue) void { - return cppFn("putDirect", .{ - this, - globalThis, - prop, - value, - }); - } - pub const Extern = [_][]const u8{ "putRecord", "create", @@ -87,18 +78,28 @@ pub const JSObject = extern struct { "getIndex", "putAtIndex", "getDirect", - "putDirect", }; }; pub const ZigString = extern struct { + // TODO: align this to align(2) + // That would improve perf a bit ptr: [*]const u8, len: usize, + pub const shim = Shimmer("", "ZigString", @This()); pub const name = "ZigString"; pub const namespace = ""; + pub inline fn is16Bit(this: *const ZigString) bool { + return (@ptrToInt(this.ptr) & (1 << 63)) != 0; + } + + pub inline fn utf16Slice(this: *const ZigString) []align(1) const u16 { + return @ptrCast([*]align(1) const u16, this.ptr)[0..this.len]; + } + pub fn fromStringPointer(ptr: StringPointer, buf: string, to: *ZigString) void { to.* = ZigString{ .len = ptr.length, @@ -110,6 +111,32 @@ pub const ZigString = extern struct { return ZigString{ .ptr = slice_.ptr, .len = slice_.len }; } + pub fn detectEncoding(this: *ZigString) void { + for (this.slice()) |char| { + if (char > 127) { + this.ptr = @intToPtr([*]const u8, @ptrToInt(this.ptr) | (1 << 63)); + return; + } + } + } + + pub inline fn isGloballyAllocated(this: *ZigString) bool { + return (@ptrToInt(this.ptr) & (1 << 62)) != 0; + } + + pub inline fn mark(this: *ZigString) void { + this.ptr = @intToPtr([*]const u8, @ptrToInt(this.ptr) | (1 << 62)); + } + + pub fn format(self: ZigString, comptime _: []const u8, _: std.fmt.FormatOptions, writer: anytype) !void { + if (self.is16Bit()) { + try strings.formatUTF16(self.utf16Slice(), writer); + return; + } + + try writer.writeAll(self.slice()); + } + pub inline fn toRef(slice_: []const u8, global: *JSGlobalObject) C_API.JSValueRef { return init(slice_).toValue(global).asRef(); } @@ -117,7 +144,11 @@ pub const ZigString = extern struct { pub const Empty = ZigString{ .ptr = "", .len = 0 }; pub fn slice(this: *const ZigString) []const u8 { - return this.ptr[0..std.math.min(this.len, 4096)]; + return this.ptr[0..@minimum(this.len, std.math.maxInt(u32))]; + } + + pub fn sliceZBuf(this: ZigString, buf: *[std.fs.MAX_PATH_BYTES]u8) ![:0]const u8 { + return try std.fmt.bufPrintZ(buf, "{}", .{this}); } pub inline fn full(this: *const ZigString) []const u8 { @@ -125,13 +156,25 @@ pub const ZigString = extern struct { } pub fn trimmedSlice(this: *const ZigString) []const u8 { - return std.mem.trim(u8, this.ptr[0..std.math.min(this.len, 4096)], " \r\n"); + return std.mem.trim(u8, this.ptr[0..@minimum(this.len, std.math.maxInt(u32))], " \r\n"); + } + + pub fn toValueAuto(this: *const ZigString, global: *JSGlobalObject) JSValue { + if (!this.is16Bit()) { + return this.toValue(global); + } else { + return this.to16BitValue(global); + } } pub fn toValue(this: *const ZigString, global: *JSGlobalObject) JSValue { return shim.cppFn("toValue", .{ this, global }); } + pub fn to16BitValue(this: *const ZigString, global: *JSGlobalObject) JSValue { + return shim.cppFn("to16BitValue", .{ this, global }); + } + pub fn toValueGC(this: *const ZigString, global: *JSGlobalObject) JSValue { return shim.cppFn("toValueGC", .{ this, global }); } @@ -141,7 +184,10 @@ pub const ZigString = extern struct { return undefined; } - return C_API.JSStringCreateStatic(this.ptr, this.len); + return if (this.is16Bit()) + C_API.JSStringCreateWithCharactersNoCopy(@ptrCast([*]const u16, @alignCast(@alignOf([*]const u16), this.ptr)), this.len) + else + C_API.JSStringCreateStatic(this.ptr, this.len); } pub fn toErrorInstance(this: *const ZigString, global: *JSGlobalObject) JSValue { @@ -150,11 +196,34 @@ pub const ZigString = extern struct { pub const Extern = [_][]const u8{ "toValue", + "to16BitValue", "toValueGC", "toErrorInstance", }; }; +pub const SystemError = extern struct { + errno: c_int = 0, + /// label for errno + code: ZigString = ZigString.init(""), + message: ZigString = ZigString.init(""), + path: ZigString = ZigString.init(""), + syscall: ZigString = ZigString.init(""), + + pub const shim = Shimmer("", "SystemError", @This()); + + pub const name = "SystemError"; + pub const namespace = ""; + + pub fn toErrorInstance(this: *const SystemError, global: *JSGlobalObject) JSValue { + return shim.cppFn("toErrorInstance", .{ this, global }); + } + + pub const Extern = [_][]const u8{ + "toErrorInstance", + }; +}; + pub const ReturnableException = *?*Exception; pub const JSCell = extern struct { @@ -935,6 +1004,10 @@ pub const JSGlobalObject = extern struct { return cppFn("createAggregateError", .{ globalObject, errors, errors_len, message }); } + pub fn generateHeapSnapshot(this: *JSGlobalObject) JSValue { + return cppFn("generateHeapSnapshot", .{this}); + } + pub fn vm(this: *JSGlobalObject) *VM { return cppFn("vm", .{this}); } @@ -966,6 +1039,7 @@ pub const JSGlobalObject = extern struct { "asyncGeneratorPrototype", "asyncGeneratorFunctionPrototype", "vm", + "generateHeapSnapshot", // "createError", // "throwError", }; @@ -1230,11 +1304,181 @@ pub const JSValue = enum(i64) { pub const include = "<JavaScriptCore/JSValue.h>"; pub const name = "JSC::JSValue"; pub const namespace = "JSC"; + pub const JSType = enum(u8) { + // The Cell value must come before any JS that is a JSCell. + Cell, + String, + HeapBigInt, + Symbol, + + GetterSetter, + CustomGetterSetter, + APIValueWrapper, + + NativeExecutable, + + ProgramExecutable, + ModuleProgramExecutable, + EvalExecutable, + FunctionExecutable, + + UnlinkedFunctionExecutable, + + UnlinkedProgramCodeBlock, + UnlinkedModuleProgramCodeBlock, + UnlinkedEvalCodeBlock, + UnlinkedFunctionCodeBlock, + + CodeBlock, + + JSImmutableButterfly, + JSSourceCode, + JSScriptFetcher, + JSScriptFetchParameters, + + // The Object value must come before any JS that is a subclass of JSObject. + Object, + FinalObject, + JSCallee, + JSFunction, + InternalFunction, + NullSetterFunction, + BooleanObject, + NumberObject, + ErrorInstance, + PureForwardingProxy, + DirectArguments, + ScopedArguments, + ClonedArguments, + + // Start JSArray types. + Array, + DerivedArray, + // End JSArray types. + + ArrayBuffer, + + // Start JSArrayBufferView types. Keep in sync with the order of FOR_EACH_TYPED_ARRAY_TYPE_EXCLUDING_DATA_VIEW. + Int8Array, + Uint8Array, + Uint8ClampedArray, + Int16Array, + Uint16Array, + Int32Array, + Uint32Array, + Float32Array, + Float64Array, + BigInt64Array, + BigUint64Array, + DataView, + // End JSArrayBufferView types. + + // JSScope <- JSWithScope + // <- StrictEvalActivation + // <- JSSymbolTableObject <- JSLexicalEnvironment <- JSModuleEnvironment + // <- JSSegmentedVariableObject <- JSGlobalLexicalEnvironment + // <- JSGlobalObject + // Start JSScope types. + // Start environment record types. + GlobalObject, + GlobalLexicalEnvironment, + LexicalEnvironment, + ModuleEnvironment, + StrictEvalActivation, + // End environment record types. + WithScope, + // End JSScope types. + + ModuleNamespaceObject, + RegExpObject, + JSDate, + ProxyObject, + JSGenerator, + JSAsyncGenerator, + JSArrayIterator, + JSMapIterator, + JSSetIterator, + JSStringIterator, + JSPromise, + JSMap, + JSSet, + JSWeakMap, + JSWeakSet, + WebAssemblyModule, + // Start StringObject types. + StringObject, + DerivedStringObject, + // End StringObject types. + + MaxJS = 0b11111111, + _, + + pub fn isHidden(this: JSType) bool { + return switch (this) { + .APIValueWrapper, + .NativeExecutable, + .ProgramExecutable, + .ModuleProgramExecutable, + .EvalExecutable, + .FunctionExecutable, + .UnlinkedFunctionExecutable, + .UnlinkedProgramCodeBlock, + .UnlinkedModuleProgramCodeBlock, + .UnlinkedEvalCodeBlock, + .UnlinkedFunctionCodeBlock, + .CodeBlock, + .JSImmutableButterfly, + .JSSourceCode, + .JSScriptFetcher, + .InternalFunction, + .JSScriptFetchParameters, + => true, + else => false, + }; + } + + pub const LastMaybeFalsyCellPrimitive = JSType.HeapBigInt; + pub const LastJSCObject = JSType.DerivedStringObject; // This is the last "JSC" Object type. After this, we have embedder's (e.g., WebCore) extended object types. + + pub inline fn isStringLike(this: JSType) bool { + return switch (this) { + .String, .StringObject, .DerivedStringObject => true, + else => false, + }; + } + }; pub inline fn cast(ptr: anytype) JSValue { return @intToEnum(JSValue, @intCast(i64, @ptrToInt(ptr))); } + pub fn to(this: JSValue, comptime T: type) T { + return switch (comptime T) { + u32 => toU32(this), + u16 => toU16(this), + c_uint => @intCast(c_uint, toU32(this)), + c_int => @intCast(c_int, toInt32(this)), + + // TODO: BigUint64? + u64 => @as(u64, toU32(this)), + + u8 => @truncate(u8, toU32(this)), + i16 => @truncate(i16, toInt32(this)), + i8 => @truncate(i8, toInt32(this)), + i32 => @truncate(i32, toInt32(this)), + + // TODO: BigInt64 + i64 => @as(i64, toInt32(this)), + else => @compileError("Not implemented yet"), + }; + } + + pub fn jsType( + this: JSValue, + ) JSType { + return cppFn("jsType", .{this}); + } + pub fn createEmptyObject(global: *JSGlobalObject, len: usize) JSValue { return cppFn("createEmptyObject", .{ global, len }); } @@ -1243,21 +1487,47 @@ pub const JSValue = enum(i64) { return cppFn("putRecord", .{ value, global, key, values, values_len }); } + /// Create an object with exactly two properties + pub fn createObject2(global: *JSGlobalObject, key1: *const ZigString, key2: *const ZigString, value1: JSValue, value2: JSValue) JSValue { + return cppFn("createObject2", .{ global, key1, key2, value1, value2 }); + } + pub fn getErrorsProperty(this: JSValue, globalObject: *JSGlobalObject) JSValue { return cppFn("getErrorsProperty", .{ this, globalObject }); } - pub fn jsNumber(number: anytype) JSValue { - return switch (@TypeOf(number)) { + + pub fn jsNumberWithType(comptime Number: type, number: Type) JSValue { + return switch (Number) { f64 => @call(.{ .modifier = .always_inline }, jsNumberFromDouble, .{number}), u8 => @call(.{ .modifier = .always_inline }, jsNumberFromChar, .{number}), u16 => @call(.{ .modifier = .always_inline }, jsNumberFromU16, .{number}), - i32 => @call(.{ .modifier = .always_inline }, jsNumberFromInt32, .{number}), - i64 => @call(.{ .modifier = .always_inline }, jsNumberFromInt64, .{number}), - u64 => @call(.{ .modifier = .always_inline }, jsNumberFromUint64, .{number}), - else => @compileError("Type transformation missing for number of type: " ++ @typeName(@TypeOf(number))), + i32 => @call(.{ .modifier = .always_inline }, jsNumberFromInt32, .{@truncate(i32, number)}), + c_int, i64 => if (number > std.math.maxInt(i32)) + jsNumberFromInt64(@truncate(i64, number)) + else + jsNumberFromInt32(@intCast(i32, number)), + + c_uint, u32 => if (number < std.math.maxInt(i32)) + jsNumberFromInt32(@intCast(i32, number)) + else + jsNumberFromUint64(@as(u64, number)), + + else => @compileError("Type transformation missing for number of type: " ++ @typeName(Number)), }; } + pub fn jsNumber(number: anytype) JSValue { + return jsNumberWithType(@TypeOf(number), number); + } + + pub fn getReadableStreamState(value: JSValue, vm: *VM) ?*Exports.NodeReadableStream { + return cppFn("getReadableStreamState", .{ value, vm }); + } + + pub fn getWritableStreamState(value: JSValue, vm: *VM) ?*Exports.NodeWritableStream { + return cppFn("getWritableStreamState", .{ value, vm }); + } + pub fn jsNull() JSValue { return cppFn("jsNull", .{}); } @@ -1274,11 +1544,22 @@ pub const JSValue = enum(i64) { return cppFn("jsDoubleNumber", .{i}); } - pub fn createStringArray(globalThis: *JSGlobalObject, str: [*c]ZigString, strings_count: usize) JSValue { + pub fn createStringArray(globalThis: *JSGlobalObject, str: [*c]ZigString, strings_count: usize, clone: bool) JSValue { return cppFn("createStringArray", .{ globalThis, str, strings_count, + clone, + }); + } + + pub fn fromEntries(globalThis: *JSGlobalObject, keys: [*c]ZigString, values: [*c]ZigString, strings_count: usize, clone: bool) JSValue { + return cppFn("fromEntries", .{ + globalThis, + keys, + values, + strings_count, + clone, }); } @@ -1392,6 +1673,10 @@ pub const JSValue = enum(i64) { return cppFn("isException", .{ this, vm }); } + pub fn isTerminationException(this: JSValue, vm: *VM) bool { + return cppFn("isTerminationException", .{ this, vm }); + } + pub fn toZigException(this: JSValue, global: *JSGlobalObject, exception: *ZigException) void { return cppFn("toZigException", .{ this, global, exception }); } @@ -1415,6 +1700,10 @@ pub const JSValue = enum(i64) { return cppFn("toWTFString", .{ this, globalThis }); } + pub fn jsonStringify(this: JSValue, globalThis: *JSGlobalObject, indent: u32, out: *ZigString) void { + return cppFn("jsonStringify", .{ this, globalThis, indent, out }); + } + // On exception, this returns null, to make exception checks faster. pub fn toStringOrNull(this: JSValue, globalThis: *JSGlobalObject) *JSString { return cppFn("toStringOrNull", .{ this, globalThis }); @@ -1441,6 +1730,31 @@ pub const JSValue = enum(i64) { return cppFn("eqlCell", .{ this, other }); } + // intended to be more lightweight than ZigString + pub fn getIfPropertyExistsImpl(this: JSValue, global: *JSGlobalObject, ptr: [*]const u8, len: u32) JSValue { + return cppFn("getIfPropertyExistsImpl", .{ this, global, ptr, len }); + } + + pub fn getIfPropertyExists(this: JSValue, global: *JSGlobalObject, property: []const u8) ?JSValue { + const value = getIfPropertyExistsImpl(this, global, property.ptr, @intCast(u32, property.len)); + return if (@enumToInt(value) != 0) value else return null; + } + + pub fn createTypeError(message: *const ZigString, code: *const ZigString, global: *JSGlobalObject) JSValue { + return cppFn("createTypeError", .{ message, code, global }); + } + + pub fn createRangeError(message: *const ZigString, code: *const ZigString, global: *JSGlobalObject) JSValue { + return cppFn("createRangeError", .{ message, code, global }); + } + + /// Object.is() + /// This algorithm differs from the IsStrictlyEqual Algorithm by treating all NaN values as equivalent and by differentiating +0𝔽 from -0𝔽. + /// https://tc39.es/ecma262/#sec-samevalue + pub fn isSameValue(this: JSValue, other: JSValue, global: *JSGlobalObject) bool { + return cppFn("isSameValue", .{ this, other, global }); + } + pub fn asString(this: JSValue) *JSString { return cppFn("asString", .{ this, @@ -1476,7 +1790,7 @@ pub const JSValue = enum(i64) { } pub inline fn toU32(this: JSValue) u32 { - return @intCast(u32, this.toInt32()); + return @intCast(u32, @maximum(this.toInt32(), 0)); } pub fn getLengthOfArray(this: JSValue, globalThis: *JSGlobalObject) u32 { @@ -1514,10 +1828,10 @@ pub const JSValue = enum(i64) { } pub inline fn asVoid(this: JSValue) *anyopaque { - return @intToPtr(*anyopaque, @intCast(usize, @enumToInt(this))); + return @intToPtr(*anyopaque, @bitCast(u64, @enumToInt(this))); } - pub const Extern = [_][]const u8{ "getLengthOfArray", "toZigString", "createStringArray", "createEmptyObject", "putRecord", "asPromise", "isClass", "getNameProperty", "getClassName", "getErrorsProperty", "toInt32", "toBoolean", "isInt32", "isIterable", "forEach", "isAggregateError", "toZigException", "isException", "toWTFString", "hasProperty", "getPropertyNames", "getDirect", "putDirect", "get", "getIfExists", "asString", "asObject", "asNumber", "isError", "jsNull", "jsUndefined", "jsTDZValue", "jsBoolean", "jsDoubleNumber", "jsNumberFromDouble", "jsNumberFromChar", "jsNumberFromU16", "jsNumberFromInt32", "jsNumberFromInt64", "jsNumberFromUint64", "isUndefined", "isNull", "isUndefinedOrNull", "isBoolean", "isAnyInt", "isUInt32AsAnyInt", "isInt32AsAnyInt", "isNumber", "isString", "isBigInt", "isHeapBigInt", "isBigInt32", "isSymbol", "isPrimitive", "isGetterSetter", "isCustomGetterSetter", "isObject", "isCell", "asCell", "toString", "toStringOrNull", "toPropertyKey", "toPropertyKeyValue", "toObject", "toString", "getPrototype", "getPropertyByPropertyName", "eqlValue", "eqlCell", "isCallable" }; + pub const Extern = [_][]const u8{ "getReadableStreamState", "getWritableStreamState", "fromEntries", "createTypeError", "createRangeError", "createObject2", "getIfPropertyExistsImpl", "jsType", "jsonStringify", "kind_", "isTerminationException", "isSameValue", "getLengthOfArray", "toZigString", "createStringArray", "createEmptyObject", "putRecord", "asPromise", "isClass", "getNameProperty", "getClassName", "getErrorsProperty", "toInt32", "toBoolean", "isInt32", "isIterable", "forEach", "isAggregateError", "toZigException", "isException", "toWTFString", "hasProperty", "getPropertyNames", "getDirect", "putDirect", "get", "getIfExists", "asString", "asObject", "asNumber", "isError", "jsNull", "jsUndefined", "jsTDZValue", "jsBoolean", "jsDoubleNumber", "jsNumberFromDouble", "jsNumberFromChar", "jsNumberFromU16", "jsNumberFromInt32", "jsNumberFromInt64", "jsNumberFromUint64", "isUndefined", "isNull", "isUndefinedOrNull", "isBoolean", "isAnyInt", "isUInt32AsAnyInt", "isInt32AsAnyInt", "isNumber", "isString", "isBigInt", "isHeapBigInt", "isBigInt32", "isSymbol", "isPrimitive", "isGetterSetter", "isCustomGetterSetter", "isObject", "isCell", "asCell", "toString", "toStringOrNull", "toPropertyKey", "toPropertyKeyValue", "toObject", "toString", "getPrototype", "getPropertyByPropertyName", "eqlValue", "eqlCell", "isCallable" }; }; extern "c" fn Microtask__run(*Microtask, *JSGlobalObject) void; @@ -1653,6 +1967,10 @@ pub const VM = extern struct { return cppFn("isJITEnabled", .{}); } + pub fn holdAPILock(this: *VM, ctx: ?*anyopaque, callback: fn (ctx: ?*anyopaque) callconv(.C) void) void { + cppFn("holdAPILock", .{ this, ctx, callback }); + } + pub fn deleteAllCode( vm: *VM, global_object: *JSGlobalObject, @@ -1675,10 +1993,25 @@ pub const VM = extern struct { }); } + pub fn runGC(vm: *VM, sync: bool) JSValue { + return cppFn("runGC", .{ + vm, + sync, + }); + } + pub fn setExecutionForbidden(vm: *VM, forbidden: bool) void { cppFn("setExecutionForbidden", .{ vm, forbidden }); } + pub fn setExecutionTimeLimit(vm: *VM, timeout: f64) void { + return cppFn("setExecutionTimeLimit", .{ vm, timeout }); + } + + pub fn clearExecutionTimeLimit(vm: *VM) void { + return cppFn("clearExecutionTimeLimit", .{vm}); + } + pub fn executionForbidden(vm: *VM) bool { return cppFn("executionForbidden", .{ vm, @@ -1717,7 +2050,7 @@ pub const VM = extern struct { }); } - pub const Extern = [_][]const u8{ "isJITEnabled", "deleteAllCode", "apiLock", "create", "deinit", "setExecutionForbidden", "executionForbidden", "isEntered", "throwError", "drainMicrotasks", "whenIdle", "shrinkFootprint" }; + pub const Extern = [_][]const u8{ "holdAPILock", "runGC", "generateHeapSnapshot", "isJITEnabled", "deleteAllCode", "apiLock", "create", "deinit", "setExecutionForbidden", "executionForbidden", "isEntered", "throwError", "drainMicrotasks", "whenIdle", "shrinkFootprint", "setExecutionTimeLimit", "clearExecutionTimeLimit" }; }; pub const ThrowScope = extern struct { diff --git a/src/javascript/jsc/bindings/exports.zig b/src/javascript/jsc/bindings/exports.zig index ee5878319..190b505b6 100644 --- a/src/javascript/jsc/bindings/exports.zig +++ b/src/javascript/jsc/bindings/exports.zig @@ -1,4 +1,4 @@ -const JSC = @import("./bindings.zig"); +const JSC = @import("../../../jsc.zig"); const Fs = @import("../../../fs.zig"); const CAPI = @import("../../../jsc.zig").C; const JS = @import("../javascript.zig"); @@ -26,6 +26,7 @@ const JSModuleLoader = JSC.JSModuleLoader; const JSModuleRecord = JSC.JSModuleRecord; const Microtask = JSC.Microtask; const JSPrivateDataPtr = @import("../base.zig").JSPrivateDataPtr; +const Backtrace = @import("../../../deps/backtrace.zig"); pub const ZigGlobalObject = extern struct { pub const shim = Shimmer("Zig", "GlobalObject", @This()); @@ -37,7 +38,9 @@ pub const ZigGlobalObject = extern struct { pub const Interface: type = NewGlobalObject(JS.VirtualMachine); pub fn create(class_ref: [*]CAPI.JSClassRef, count: i32, console: *anyopaque) *JSGlobalObject { - return shim.cppFn("create", .{ class_ref, count, console }); + var global = shim.cppFn("create", .{ class_ref, count, console }); + Backtrace.reloadHandlers(); + return global; } pub fn getModuleRegistryMap(global: *JSGlobalObject) *anyopaque { @@ -169,6 +172,11 @@ pub const ZigErrorType = extern struct { } }; +/// do not use this reference directly, use JSC.Node.Readable +pub const NodeReadableStream = JSC.Node.Readable.State; +/// do not use this reference directly, use JSC.Node.Writable +pub const NodeWritableStream = JSC.Node.Writable.State; + pub fn Errorable(comptime Type: type) type { return extern struct { result: Result, @@ -301,6 +309,54 @@ pub const ZigStackFrameCode = enum(u8) { } }; +pub const Process = extern struct { + pub const shim = Shimmer("Bun", "Process", @This()); + pub const name = "Process"; + pub const namespace = shim.namespace; + const _bun: string = "bun"; + + pub fn getTitle(_: *JSGlobalObject, title: *ZigString) callconv(.C) void { + title.* = ZigString.init(_bun); + } + + // TODO: https://github.com/nodejs/node/blob/master/deps/uv/src/unix/darwin-proctitle.c + pub fn setTitle(globalObject: *JSGlobalObject, _: *ZigString) callconv(.C) JSValue { + return ZigString.init(_bun).toValue(globalObject); + } + + pub const getArgv = JSC.Node.Process.getArgv; + pub const getCwd = JSC.Node.Process.getCwd; + pub const setCwd = JSC.Node.Process.setCwd; + + pub const Export = shim.exportFunctions(.{ + .@"getTitle" = getTitle, + .@"setTitle" = setTitle, + .@"getArgv" = getArgv, + .@"getCwd" = getCwd, + .@"setCwd" = setCwd, + }); + + comptime { + if (!is_bindgen) { + @export(getTitle, .{ + .name = Export[0].symbol_name, + }); + @export(setTitle, .{ + .name = Export[1].symbol_name, + }); + @export(getArgv, .{ + .name = Export[2].symbol_name, + }); + @export(getCwd, .{ + .name = Export[3].symbol_name, + }); + @export(setCwd, .{ + .name = Export[4].symbol_name, + }); + } + } +}; + pub const ZigStackTrace = extern struct { source_lines_ptr: [*c]ZigString, source_lines_numbers: [*c]i32, @@ -428,15 +484,18 @@ pub const ZigStackFrame = extern struct { source_url: ZigString, position: ZigStackFramePosition, enable_color: bool, - origin: *const ZigURL, + origin: ?*const ZigURL, + root_path: string = "", pub fn format(this: SourceURLFormatter, comptime _: []const u8, _: std.fmt.FormatOptions, writer: anytype) !void { - try writer.writeAll(this.origin.displayProtocol()); - try writer.writeAll("://"); - try writer.writeAll(this.origin.displayHostname()); - try writer.writeAll(":"); - try writer.writeAll(this.origin.port); - try writer.writeAll("/blob:"); + if (this.origin) |origin| { + try writer.writeAll(origin.displayProtocol()); + try writer.writeAll("://"); + try writer.writeAll(origin.displayHostname()); + try writer.writeAll(":"); + try writer.writeAll(origin.port); + try writer.writeAll("/blob:"); + } var source_slice = this.source_url.slice(); if (strings.startsWith(source_slice, this.root_path)) { @@ -505,7 +564,7 @@ pub const ZigStackFrame = extern struct { return NameFormatter{ .function_name = this.function_name, .code_type = this.code_type, .enable_color = enable_color }; } - pub fn sourceURLFormatter(this: *const ZigStackFrame, root_path: string, origin: *const ZigURL, comptime enable_color: bool) SourceURLFormatter { + pub fn sourceURLFormatter(this: *const ZigStackFrame, root_path: string, origin: ?*const ZigURL, comptime enable_color: bool) SourceURLFormatter { return SourceURLFormatter{ .source_url = this.source_url, .origin = origin, .root_path = root_path, .position = this.position, .enable_color = enable_color }; } }; @@ -538,6 +597,16 @@ pub const ZigStackFramePosition = extern struct { pub const ZigException = extern struct { code: JSErrorCode, runtime_type: JSRuntimeType, + + /// SystemError only + errno: c_int = 0, + /// SystemError only + syscall: ZigString = ZigString.Empty, + /// SystemError only + system_code: ZigString = ZigString.Empty, + /// SystemError only + path: ZigString = ZigString.Empty, + name: ZigString, message: ZigString, stack: ZigStackTrace, @@ -675,15 +744,40 @@ pub const ZigConsoleClient = struct { }; } - /// TODO: support %s %d %f %o %O + pub const MessageLevel = enum(u32) { + Log = 0, + Warning = 1, + Error = 2, + Debug = 3, + Info = 4, + _, + }; + + pub const MessageType = enum(u32) { + Log = 0, + Dir = 1, + DirXML = 2, + Table = 3, + Trace = 4, + StartGroup = 5, + StartGroupCollapsed = 6, + EndGroup = 7, + Clear = 8, + Assert = 9, + Timing = 10, + Profile = 11, + ProfileEnd = 12, + Image = 13, + _, + }; + /// https://console.spec.whatwg.org/#formatter pub fn messageWithTypeAndLevel( //console_: ZigConsoleClient.Type, _: ZigConsoleClient.Type, - //message_type: u32, - _: u32, + message_type: MessageType, //message_level: u32, - _: u32, + level: MessageLevel, global: *JSGlobalObject, vals: [*]JSValue, len: usize, @@ -693,130 +787,728 @@ pub const ZigConsoleClient = struct { } var console = JS.VirtualMachine.vm.console; - var i: usize = 0; - var buffered_writer = console.writer; + + if (message_type == .Clear) { + Output.resetTerminal(); + return; + } + + if (message_type == .Assert and len == 0) { + const text = if (Output.enable_ansi_colors_stderr) + Output.prettyFmt("<r><red>Assertion failed<r>\n", true) + else + "Assertion failed\n"; + console.error_writer.unbuffered_writer.writeAll(text) catch unreachable; + return; + } + + const enable_colors = if (level == .Warning or level == .Error) + Output.enable_ansi_colors_stderr + else + Output.enable_ansi_colors_stdout; + var buffered_writer = if (level == .Warning or level == .Error) + console.error_writer + else + console.writer; var writer = buffered_writer.writer(); + const BufferedWriterType = @TypeOf(writer); + + var fmt: Formatter = undefined; + defer { + if (fmt.map_node) |node| { + node.data = fmt.map; + node.data.clearRetainingCapacity(); + node.release(); + } + } + if (len == 1) { - if (Output.enable_ansi_colors) { - FormattableType.format( - @TypeOf(buffered_writer.unbuffered_writer), - buffered_writer.unbuffered_writer, - vals[0], - global, - true, - ) catch {}; + fmt = Formatter{ .remaining_values = &[_]JSValue{} }; + const tag = Formatter.Tag.get(vals[0], global); + + var unbuffered_writer = buffered_writer.unbuffered_writer.context.writer(); + const UnbufferedWriterType = @TypeOf(unbuffered_writer); + + if (tag.tag == .String) { + if (enable_colors) { + if (level == .Error) { + unbuffered_writer.writeAll(comptime Output.prettyFmt("<r><red>", true)) catch unreachable; + } + fmt.format( + tag, + UnbufferedWriterType, + unbuffered_writer, + vals[0], + global, + true, + ); + if (level == .Error) { + unbuffered_writer.writeAll(comptime Output.prettyFmt("<r>", true)) catch unreachable; + } + } else { + fmt.format( + tag, + UnbufferedWriterType, + unbuffered_writer, + vals[0], + global, + false, + ); + } + _ = unbuffered_writer.write("\n") catch 0; } else { - FormattableType.format( - @TypeOf(buffered_writer.unbuffered_writer), - buffered_writer.unbuffered_writer, - vals[0], - global, - false, - ) catch {}; + defer buffered_writer.flush() catch {}; + if (enable_colors) { + fmt.format( + tag, + BufferedWriterType, + writer, + vals[0], + global, + true, + ); + } else { + fmt.format( + tag, + BufferedWriterType, + writer, + vals[0], + global, + false, + ); + } + _ = writer.write("\n") catch 0; } - _ = buffered_writer.unbuffered_writer.write("\n") catch 0; - return; } - var values = vals[0..len]; defer buffered_writer.flush() catch {}; - if (Output.enable_ansi_colors) { - while (i < len) : (i += 1) { - _ = if (i > 0) (writer.write(" ") catch 0); + var this_value: JSValue = vals[0]; + fmt = Formatter{ .remaining_values = vals[0..len][1..] }; + var tag: Formatter.Tag.Result = undefined; + + var any = false; + if (enable_colors) { + if (level == .Error) { + writer.writeAll(comptime Output.prettyFmt("<r><red>", true)) catch unreachable; + } + while (true) { + if (any) { + _ = writer.write(" ") catch 0; + } + any = true; + + tag = Formatter.Tag.get(this_value, global); + if (tag.tag == .String and fmt.remaining_values.len > 0) { + tag.tag = .StringPossiblyFormatted; + } + + fmt.format(tag, BufferedWriterType, writer, this_value, global, true); + if (fmt.remaining_values.len == 0) { + break; + } - FormattableType.format(@TypeOf(writer), writer, values[i], global, true) catch {}; + this_value = fmt.remaining_values[0]; + fmt.remaining_values = fmt.remaining_values[1..]; + } + if (level == .Error) { + writer.writeAll(comptime Output.prettyFmt("<r>", true)) catch unreachable; } } else { - while (i < len) : (i += 1) { - _ = if (i > 0) (writer.write(" ") catch 0); + while (true) { + if (any) { + _ = writer.write(" ") catch 0; + } + any = true; + tag = Formatter.Tag.get(this_value, global); + if (tag.tag == .String and fmt.remaining_values.len > 0) { + tag.tag = .StringPossiblyFormatted; + } + + fmt.format(tag, BufferedWriterType, writer, this_value, global, false); + if (fmt.remaining_values.len == 0) + break; - FormattableType.format(@TypeOf(writer), writer, values[i], global, false) catch {}; + this_value = fmt.remaining_values[0]; + fmt.remaining_values = fmt.remaining_values[1..]; } } _ = writer.write("\n") catch 0; } - const FormattableType = enum { - Error, - String, - Undefined, - Double, - Integer, - Null, - Boolean, - const CellType = CAPI.CellType; - threadlocal var name_buf: [512]u8 = undefined; - pub fn format(comptime Writer: type, writer: Writer, value: JSValue, globalThis: *JSGlobalObject, comptime enable_ansi_colors: bool) anyerror!void { - if (comptime @hasDecl(@import("root"), "bindgen")) { - return; + pub const Formatter = struct { + remaining_values: []JSValue, + map: Visited.Map = undefined, + map_node: ?*Visited.Pool.Node = null, + hide_native: bool = false, + + // For detecting circular references + pub const Visited = struct { + const ObjectPool = @import("../../../pool.zig").ObjectPool; + pub const Map = std.AutoHashMap(i64, void); + pub const Pool = ObjectPool( + Map, + struct { + pub fn init(allocator: std.mem.Allocator) anyerror!Map { + return Map.init(allocator); + } + }.init, + true, + ); + }; + + pub const Tag = enum { + StringPossiblyFormatted, + String, + Undefined, + Double, + Integer, + Null, + Boolean, + Array, + Object, + Function, + Class, + Error, + TypedArray, + Map, + Set, + Symbol, + BigInt, + + GlobalObject, + Private, + Promise, + + JSON, + NativeCode, + ArrayBuffer, + + pub inline fn canHaveCircularReferences(tag: Tag) bool { + return tag == .Array or tag == .Object or tag == .Map or tag == .Set; } - if (value.isCell()) { - if (CAPI.JSObjectGetPrivate(value.asRef())) |private_data_ptr| { - const priv_data = JSPrivateDataPtr.from(private_data_ptr); - switch (priv_data.tag()) { - .BuildError => { - const build_error = priv_data.as(JS.BuildError); - try build_error.msg.formatWriter(Writer, writer, enable_ansi_colors); - return; - }, - .ResolveError => { - const resolve_error = priv_data.as(JS.ResolveError); - try resolve_error.msg.formatWriter(Writer, writer, enable_ansi_colors); - return; - }, - else => {}, + const Result = struct { + tag: Tag, + cell: JSValue.JSType = JSValue.JSType.Cell, + }; + + pub fn get(value: JSValue, globalThis: *JSGlobalObject) Result { + if (value.isInt32()) { + return .{ + .tag = .Integer, + }; + } else if (value.isNumber()) { + return .{ + .tag = .Double, + }; + } else if (value.isUndefined()) { + return .{ + .tag = .Undefined, + }; + } else if (value.isNull()) { + return .{ + .tag = .Null, + }; + } else if (value.isBoolean()) { + return .{ + .tag = .Boolean, + }; + } + + const js_type = value.jsType(); + + if (js_type.isHidden()) return .{ .tag = .NativeCode }; + + if (CAPI.JSObjectGetPrivate(value.asObjectRef()) != null) + return .{ + .tag = .Private, + }; + + // If we check an Object has a method table and it does not + // it will crash + const callable = js_type != .Object and value.isCallable(globalThis.vm()); + + if (value.isClass(globalThis) and !callable) { + // Temporary workaround + // console.log(process.env) shows up as [class JSCallbackObject] + // We want to print it like an object + if (CAPI.JSValueIsObjectOfClass(globalThis.ref(), value.asObjectRef(), JSC.Bun.EnvironmentVariables.Class.get().?[0])) { + return .{ + .tag = .Object, + }; } + return .{ + .tag = .Class, + }; } - switch (@intToEnum(CellType, value.asCell().getType())) { - CellType.ErrorInstanceType => { - JS.VirtualMachine.printErrorlikeObject(JS.VirtualMachine.vm, value, null, null, enable_ansi_colors); - return; + if (callable) { + return .{ + .tag = .Function, + }; + } + + return .{ + .tag = switch (js_type) { + JSValue.JSType.ErrorInstance => .Error, + JSValue.JSType.NumberObject => .Double, + JSValue.JSType.DerivedArray, JSValue.JSType.Array => .Array, + JSValue.JSType.DerivedStringObject, JSValue.JSType.String, JSValue.JSType.StringObject => .String, + JSValue.JSType.RegExpObject, + JSValue.JSType.Symbol, + => .String, + JSValue.JSType.BooleanObject => .Boolean, + JSValue.JSType.JSFunction => .Function, + JSValue.JSType.JSWeakMap, JSValue.JSType.JSMap => .Map, + JSValue.JSType.JSWeakSet, JSValue.JSType.JSSet => .Set, + JSValue.JSType.JSDate => .JSON, + JSValue.JSType.JSPromise => .Promise, + JSValue.JSType.Object, JSValue.JSType.FinalObject => .Object, + + JSValue.JSType.Int8Array, + JSValue.JSType.Uint8Array, + JSValue.JSType.Uint8ClampedArray, + JSValue.JSType.Int16Array, + JSValue.JSType.Uint16Array, + JSValue.JSType.Int32Array, + JSValue.JSType.Uint32Array, + JSValue.JSType.Float32Array, + JSValue.JSType.Float64Array, + JSValue.JSType.BigInt64Array, + JSValue.JSType.BigUint64Array, + => .TypedArray, + + // None of these should ever exist here + // But we're going to check anyway + .GetterSetter, + .CustomGetterSetter, + .APIValueWrapper, + .NativeExecutable, + .ProgramExecutable, + .ModuleProgramExecutable, + .EvalExecutable, + .FunctionExecutable, + .UnlinkedFunctionExecutable, + .UnlinkedProgramCodeBlock, + .UnlinkedModuleProgramCodeBlock, + .UnlinkedEvalCodeBlock, + .UnlinkedFunctionCodeBlock, + .CodeBlock, + .JSImmutableButterfly, + .JSSourceCode, + .JSScriptFetcher, + .JSScriptFetchParameters, + .JSCallee, + .GlobalLexicalEnvironment, + .LexicalEnvironment, + .ModuleEnvironment, + .StrictEvalActivation, + .WithScope, + => .NativeCode, + else => .JSON, }, + .cell = js_type, + }; + } + }; - CellType.GlobalObjectType => { - _ = try writer.write("[globalThis]"); - return; + const CellType = CAPI.CellType; + threadlocal var name_buf: [512]u8 = undefined; + + fn writeWithFormatting( + this: *Formatter, + comptime Writer: type, + writer_: Writer, + comptime Slice: type, + slice_: Slice, + globalThis: *JSGlobalObject, + comptime enable_ansi_colors: bool, + ) void { + var writer = WrappedWriter(Writer){ .ctx = writer_ }; + var slice = slice_; + var i: u32 = 0; + var len: u32 = @truncate(u32, slice.len); + while (i < len) : (i += 1) { + switch (slice[i]) { + '%' => { + i += 1; + if (i >= len) + break; + + const token = switch (slice[i]) { + 's' => Tag.String, + 'f' => Tag.Double, + 'o' => Tag.Undefined, + 'O' => Tag.Object, + 'd', 'i' => Tag.Integer, + else => continue, + }; + + // Flush everything up to the % + const end = slice[0 .. i - 1]; + writer.writeAll(end); + slice = slice[@minimum(slice.len, i + 1)..]; + i = 0; + len = @truncate(u32, slice.len); + const next_value = this.remaining_values[0]; + this.remaining_values = this.remaining_values[1..]; + switch (token) { + Tag.String => this.printAs(Tag.String, Writer, writer_, next_value, globalThis, next_value.jsType(), enable_ansi_colors), + Tag.Double => this.printAs(Tag.Double, Writer, writer_, next_value, globalThis, next_value.jsType(), enable_ansi_colors), + Tag.Object => this.printAs(Tag.Object, Writer, writer_, next_value, globalThis, next_value.jsType(), enable_ansi_colors), + Tag.Integer => this.printAs(Tag.Integer, Writer, writer_, next_value, globalThis, next_value.jsType(), enable_ansi_colors), + + // undefined is overloaded to mean the '%o" field + Tag.Undefined => this.format(Tag.get(next_value, globalThis), Writer, writer_, next_value, globalThis, enable_ansi_colors), + + else => unreachable, + } + if (this.remaining_values.len == 0) break; + }, + '\\' => { + i += 1; + if (i >= len) + break; + if (slice[i] == '%') i += 2; }, else => {}, } } - if (value.isInt32()) { - try writer.print(comptime Output.prettyFmt("<r><yellow>{d}<r>", enable_ansi_colors), .{value.toInt32()}); - } else if (value.isNumber()) { - try writer.print(comptime Output.prettyFmt("<r><yellow>{d}<r>", enable_ansi_colors), .{value.asNumber()}); - } else if (value.isUndefined()) { - try writer.print(comptime Output.prettyFmt("<r><d>undefined<r>", enable_ansi_colors), .{}); - } else if (value.isNull()) { - try writer.print(comptime Output.prettyFmt("<r><yellow>null<r>", enable_ansi_colors), .{}); - } else if (value.isBoolean()) { - if (value.toBoolean()) { - try writer.print(comptime Output.prettyFmt("<r><yellow>true<r>", enable_ansi_colors), .{}); - } else { - try writer.print(comptime Output.prettyFmt("<r><yellow>false<r>", enable_ansi_colors), .{}); + if (slice.len > 0) writer.writeAll(slice); + } + + pub fn WrappedWriter(comptime Writer: type) type { + return struct { + ctx: Writer, + + pub fn print(self: *@This(), comptime fmt: string, args: anytype) void { + self.ctx.print(fmt, args) catch unreachable; } - // } else if (value.isSymbol()) { - // try writer.print(comptime Output.prettyFmt("<r><yellow>Symbol(\"{s}\")<r>", enable_ansi_colors), .{ value.getDescriptionProperty() }); - } else if (value.isClass(globalThis)) { - var printable = ZigString.init(&name_buf); - value.getClassName(globalThis, &printable); - try writer.print("[class {s}]", .{printable.slice()}); - } else if (value.isCallable(globalThis.vm())) { - var printable = ZigString.init(&name_buf); - value.getNameProperty(globalThis, &printable); - try writer.print("[Function {s}]", .{printable.slice()}); - } else { - var str = value.toWTFString(JS.VirtualMachine.vm.global); - _ = try writer.write(str.slice()); + + pub inline fn writeAll(self: *@This(), buf: []const u8) void { + self.ctx.writeAll(buf) catch unreachable; + } + }; + } + + pub fn printAs( + this: *Formatter, + comptime Format: Formatter.Tag, + comptime Writer: type, + writer_: Writer, + value: JSValue, + globalThis: *JSGlobalObject, + jsType: JSValue.JSType, + comptime enable_ansi_colors: bool, + ) void { + var writer = WrappedWriter(Writer){ .ctx = writer_ }; + + if (comptime Format.canHaveCircularReferences()) { + if (this.map_node == null) { + this.map_node = Visited.Pool.get(default_allocator); + this.map_node.?.data.clearRetainingCapacity(); + this.map = this.map_node.?.data; + } + + var entry = this.map.getOrPut(@enumToInt(value)) catch unreachable; + if (entry.found_existing) { + writer.writeAll(comptime Output.prettyFmt("<r><cyan>[Circular]<r>", enable_ansi_colors)); + return; + } + } + + switch (comptime Format) { + .StringPossiblyFormatted => { + var str = ZigString.init(""); + value.toZigString(&str, globalThis); + + if (!str.is16Bit()) { + const slice = str.slice(); + this.writeWithFormatting(Writer, writer_, @TypeOf(slice), slice, globalThis, enable_ansi_colors); + } else { + // TODO: UTF16 + writer.print("{}", .{str}); + } + }, + .String => { + var str = ZigString.init(""); + value.toZigString(&str, globalThis); + if (jsType == .RegExpObject) { + writer.print(comptime Output.prettyFmt("<r><red>", enable_ansi_colors), .{}); + } + + writer.print("{}", .{str}); + + if (jsType == .RegExpObject) { + writer.print(comptime Output.prettyFmt("<r>", enable_ansi_colors), .{}); + } + }, + .Integer => { + writer.print(comptime Output.prettyFmt("<r><yellow>{d}<r>", enable_ansi_colors), .{value.toInt32()}); + }, + .Double => { + writer.print(comptime Output.prettyFmt("<r><yellow>{d}<r>", enable_ansi_colors), .{value.asNumber()}); + }, + .Undefined => { + writer.print(comptime Output.prettyFmt("<r><d>undefined<r>", enable_ansi_colors), .{}); + }, + .Null => { + writer.print(comptime Output.prettyFmt("<r><yellow>null<r>", enable_ansi_colors), .{}); + }, + .Error => { + JS.VirtualMachine.printErrorlikeObject(JS.VirtualMachine.vm, value, null, null, enable_ansi_colors); + }, + .Class => { + var printable = ZigString.init(&name_buf); + value.getClassName(globalThis, &printable); + if (printable.len == 0) { + writer.print(comptime Output.prettyFmt("[class]", enable_ansi_colors), .{}); + } else { + writer.print(comptime Output.prettyFmt("[class <cyan>{}<r>]", enable_ansi_colors), .{printable}); + } + }, + .Function => { + var printable = ZigString.init(&name_buf); + value.getNameProperty(globalThis, &printable); + + if (printable.len == 0) { + writer.print(comptime Output.prettyFmt("<cyan>[Function]<r>", enable_ansi_colors), .{}); + } else { + writer.print(comptime Output.prettyFmt("<cyan>[Function<d>:<r> <cyan>{}]<r>", enable_ansi_colors), .{printable}); + } + }, + .Array => { + const len = value.getLengthOfArray(globalThis); + if (len == 0) { + writer.writeAll("[]"); + return; + } + + writer.writeAll("[ "); + var i: u32 = 0; + var ref = value.asObjectRef(); + while (i < len) : (i += 1) { + if (i > 0) { + writer.writeAll(", "); + } + + const element = JSValue.fromRef(CAPI.JSObjectGetPropertyAtIndex(globalThis.ref(), ref, i, null)); + const tag = Tag.get(element, globalThis); + + if (tag.cell.isStringLike()) { + if (comptime enable_ansi_colors) { + writer.writeAll(comptime Output.prettyFmt("<r><green>", true)); + } + writer.writeAll("\""); + } + + this.format(tag, Writer, writer_, element, globalThis, enable_ansi_colors); + + if (tag.cell.isStringLike()) { + writer.writeAll("\""); + if (comptime enable_ansi_colors) { + writer.writeAll(comptime Output.prettyFmt("<r>", true)); + } + } + } + + writer.writeAll(" ]"); + }, + .Private => { + if (CAPI.JSObjectGetPrivate(value.asRef())) |private_data_ptr| { + const priv_data = JSPrivateDataPtr.from(private_data_ptr); + switch (priv_data.tag()) { + .BuildError => { + const build_error = priv_data.as(JS.BuildError); + build_error.msg.formatWriter(Writer, writer_, enable_ansi_colors) catch {}; + return; + }, + .ResolveError => { + const resolve_error = priv_data.as(JS.ResolveError); + resolve_error.msg.formatWriter(Writer, writer_, enable_ansi_colors) catch {}; + return; + }, + else => {}, + } + } + + writer.writeAll("[native code]"); + }, + .NativeCode => { + writer.writeAll("[native code]"); + }, + .Promise => { + writer.writeAll("Promise { " ++ comptime Output.prettyFmt("<r><cyan>", enable_ansi_colors)); + + switch (JSPromise.status(@ptrCast(*JSPromise, value.asObjectRef().?), globalThis.vm())) { + JSPromise.Status.Pending => { + writer.writeAll("<pending>"); + }, + JSPromise.Status.Fulfilled => { + writer.writeAll("<resolved>"); + }, + JSPromise.Status.Rejected => { + writer.writeAll("<rejected>"); + }, + } + + writer.writeAll(comptime Output.prettyFmt("<r>", enable_ansi_colors) ++ " }"); + }, + .Boolean => { + if (value.toBoolean()) { + writer.writeAll(comptime Output.prettyFmt("<r><yellow>true<r>", enable_ansi_colors)); + } else { + writer.writeAll(comptime Output.prettyFmt("<r><yellow>false<r>", enable_ansi_colors)); + } + }, + .GlobalObject => { + writer.writeAll(comptime Output.prettyFmt("<cyan>[globalThis]<r>", enable_ansi_colors)); + }, + .Map => {}, + .Set => {}, + .JSON => { + var str = ZigString.init(""); + value.jsonStringify(globalThis, 0, &str); + if (jsType == JSValue.JSType.JSDate) { + // in the code for printing dates, it never exceeds this amount + var iso_string_buf: [36]u8 = undefined; + var out_buf: []const u8 = std.fmt.bufPrint(&iso_string_buf, "{}", .{str}) catch ""; + if (out_buf.len > 2) { + // trim the quotes + out_buf = out_buf[1 .. out_buf.len - 1]; + } + + writer.print(comptime Output.prettyFmt("<r><magenta>{s}<r>", enable_ansi_colors), .{out_buf}); + return; + } + + writer.print("{}", .{str}); + }, + .Object => { + var object = value.asObjectRef(); + var array = CAPI.JSObjectCopyPropertyNames(globalThis.ref(), object); + defer CAPI.JSPropertyNameArrayRelease(array); + const count_ = CAPI.JSPropertyNameArrayGetCount(array); + var i: usize = 0; + + var name_str = ZigString.init(""); + value.getPrototype(globalThis).getNameProperty(globalThis, &name_str); + + if (name_str.len > 0 and !strings.eqlComptime(name_str.slice(), "Object")) { + writer.print("{} ", .{name_str}); + } + + if (count_ == 0) { + writer.writeAll("{ }"); + return; + } + + writer.writeAll("{ "); + + while (i < count_) : (i += 1) { + var property_name_ref = CAPI.JSPropertyNameArrayGetNameAtIndex(array, i); + defer CAPI.JSStringRelease(property_name_ref); + var prop = CAPI.JSStringGetCharacters8Ptr(property_name_ref)[0..CAPI.JSStringGetLength(property_name_ref)]; + + var property_value = CAPI.JSObjectGetProperty(globalThis.ref(), object, property_name_ref, null); + const tag = Tag.get(JSValue.fromRef(property_value), globalThis); + + if (tag.cell.isHidden()) continue; + + writer.print( + comptime Output.prettyFmt("{s}<d>:<r> ", enable_ansi_colors), + .{prop[0..@minimum(prop.len, 128)]}, + ); + + if (tag.cell.isStringLike()) { + if (comptime enable_ansi_colors) { + writer.writeAll(comptime Output.prettyFmt("<r><green>", true)); + } + writer.writeAll("\""); + } + + this.format(tag, Writer, writer_, JSValue.fromRef(property_value), globalThis, enable_ansi_colors); + + if (tag.cell.isStringLike()) { + writer.writeAll("\""); + if (comptime enable_ansi_colors) { + writer.writeAll(comptime Output.prettyFmt("<r>", true)); + } + } + + if (i + 1 < count_) { + writer.writeAll(", "); + } + } + + writer.writeAll(" }"); + }, + .TypedArray => { + const len = value.getLengthOfArray(globalThis); + if (len == 0) { + writer.writeAll("[]"); + return; + } + + writer.writeAll("[ "); + var i: u32 = 0; + var buffer = JSC.Buffer.fromJS(globalThis, value, null).?; + const slice = buffer.slice(); + while (i < len) : (i += 1) { + if (i > 0) { + writer.writeAll(", "); + } + + writer.print(comptime Output.prettyFmt("<r><yellow>{d}<r>", enable_ansi_colors), .{slice[i]}); + } + + writer.writeAll(" ]"); + }, + else => {}, } } + + pub fn format(this: *Formatter, result: Tag.Result, comptime Writer: type, writer: Writer, value: JSValue, globalThis: *JSGlobalObject, comptime enable_ansi_colors: bool) void { + if (comptime @hasDecl(@import("root"), "bindgen")) { + return; + } + + // This looks incredibly redudant. We make the Formatter.Tag a + // comptime var so we have to repeat it here. The rationale there is + // it _should_ limit the stack usage because each version of the + // function will be relatively small + return switch (result.tag) { + .StringPossiblyFormatted => this.printAs(.StringPossiblyFormatted, Writer, writer, value, globalThis, result.cell, enable_ansi_colors), + .String => this.printAs(.String, Writer, writer, value, globalThis, result.cell, enable_ansi_colors), + .Undefined => this.printAs(.Undefined, Writer, writer, value, globalThis, result.cell, enable_ansi_colors), + .Double => this.printAs(.Double, Writer, writer, value, globalThis, result.cell, enable_ansi_colors), + .Integer => this.printAs(.Integer, Writer, writer, value, globalThis, result.cell, enable_ansi_colors), + .Null => this.printAs(.Null, Writer, writer, value, globalThis, result.cell, enable_ansi_colors), + .Boolean => this.printAs(.Boolean, Writer, writer, value, globalThis, result.cell, enable_ansi_colors), + .Array => this.printAs(.Array, Writer, writer, value, globalThis, result.cell, enable_ansi_colors), + .Object => this.printAs(.Object, Writer, writer, value, globalThis, result.cell, enable_ansi_colors), + .Function => this.printAs(.Function, Writer, writer, value, globalThis, result.cell, enable_ansi_colors), + .Class => this.printAs(.Class, Writer, writer, value, globalThis, result.cell, enable_ansi_colors), + .Error => this.printAs(.Error, Writer, writer, value, globalThis, result.cell, enable_ansi_colors), + .TypedArray => this.printAs(.TypedArray, Writer, writer, value, globalThis, result.cell, enable_ansi_colors), + .Map => this.printAs(.Map, Writer, writer, value, globalThis, result.cell, enable_ansi_colors), + .Set => this.printAs(.Set, Writer, writer, value, globalThis, result.cell, enable_ansi_colors), + .Symbol => this.printAs(.Symbol, Writer, writer, value, globalThis, result.cell, enable_ansi_colors), + .BigInt => this.printAs(.BigInt, Writer, writer, value, globalThis, result.cell, enable_ansi_colors), + .GlobalObject => this.printAs(.GlobalObject, Writer, writer, value, globalThis, result.cell, enable_ansi_colors), + .Private => this.printAs(.Private, Writer, writer, value, globalThis, result.cell, enable_ansi_colors), + .Promise => this.printAs(.Promise, Writer, writer, value, globalThis, result.cell, enable_ansi_colors), + .JSON => this.printAs(.JSON, Writer, writer, value, globalThis, result.cell, enable_ansi_colors), + .NativeCode => this.printAs(.NativeCode, Writer, writer, value, globalThis, result.cell, enable_ansi_colors), + .ArrayBuffer => this.printAs(.ArrayBuffer, Writer, writer, value, globalThis, result.cell, enable_ansi_colors), + }; + } }; pub fn count( @@ -926,12 +1618,16 @@ pub const ZigConsoleClient = struct { // console _: ZigConsoleClient.Type, // global - _: *JSGlobalObject, + globalThis: *JSGlobalObject, // chars _: [*]const u8, // len _: usize, - ) callconv(.C) void {} + ) callconv(.C) void { + // TODO: this does an extra JSONStringify and we don't need it to! + var snapshot: [1]JSValue = .{globalThis.generateHeapSnapshot()}; + ZigConsoleClient.messageWithTypeAndLevel(undefined, MessageType.Log, MessageLevel.Debug, globalThis, &snapshot, 1); + } pub fn timeStamp( // console _: ZigConsoleClient.Type, @@ -1120,3 +1816,12 @@ comptime { @export(ErrorCode.ParserError, .{ .name = "Zig_ErrorCodeParserError" }); @export(ErrorCode.JSErrorObject, .{ .name = "Zig_ErrorCodeJSErrorObject" }); } + +comptime { + if (!is_bindgen) { + _ = Process.getTitle; + _ = Process.setTitle; + std.testing.refAllDecls(NodeReadableStream); + std.testing.refAllDecls(NodeWritableStream); + } +} diff --git a/src/javascript/jsc/bindings/header-gen.zig b/src/javascript/jsc/bindings/header-gen.zig index bdf1778ad..9a9b9314f 100644 --- a/src/javascript/jsc/bindings/header-gen.zig +++ b/src/javascript/jsc/bindings/header-gen.zig @@ -103,7 +103,7 @@ pub const C_Generator = struct { pub fn gen_func( self: *Self, comptime name: []const u8, - comptime func: FnDecl, + comptime func: anytype, comptime meta: FnMeta, comptime _: []const []const u8, comptime rewrite_return: bool, @@ -121,16 +121,21 @@ pub const C_Generator = struct { .export_zig => self.write("ZIG_DECL "), } + const return_type: type = comptime if (@TypeOf(func.return_type) == ?type) + (func.return_type orelse void) + else + func.return_type; + if (comptime rewrite_return) { self.writeType(void); } else { - self.writeType(comptime func.return_type); + self.writeType(comptime return_type); } self.write(" " ++ name ++ "("); if (comptime rewrite_return) { - self.writeType(comptime func.return_type); + self.writeType(comptime return_type); self.write("_buf ret_value"); if (comptime meta.args.len > 0) { @@ -515,9 +520,15 @@ pub fn HeaderGen(comptime first_import: type, comptime second_import: type, comp pub fn processStaticExport(comptime _: Self, _: anytype, gen: *C_Generator, comptime static_export: StaticExport) void { const fn_meta = comptime @typeInfo(static_export.Type).Fn; + const DeclData = static_export.Decl().data; + gen.gen_func( comptime static_export.symbol_name, - comptime static_export.Decl().data.Fn, + comptime switch (DeclData) { + .Fn => |Fn| Fn, + .Var => |Var| @typeInfo(Var).Fn, + else => unreachable, + }, comptime fn_meta, comptime std.mem.zeroes([]const []const u8), false, diff --git a/src/javascript/jsc/bindings/headers-cpp.h b/src/javascript/jsc/bindings/headers-cpp.h index 4ea0be1a6..470feff87 100644 --- a/src/javascript/jsc/bindings/headers-cpp.h +++ b/src/javascript/jsc/bindings/headers-cpp.h @@ -1,4 +1,4 @@ -//-- AUTOGENERATED FILE -- 1640933554 +//-- AUTOGENERATED FILE -- 1642473926 // clang-format off #pragma once @@ -216,6 +216,22 @@ extern "C" const size_t WTF__StringView_object_align_ = alignof(WTF::StringView) extern "C" const size_t Zig__GlobalObject_object_size_ = sizeof(Zig::GlobalObject); extern "C" const size_t Zig__GlobalObject_object_align_ = alignof(Zig::GlobalObject); +#ifndef INCLUDED_BunStream_h +#define INCLUDED_BunStream_h +#include BunStream.h +#endif + +extern "C" const size_t Bun__Readable_object_size_ = sizeof(Bun__Readable); +extern "C" const size_t Bun__Readable_object_align_ = alignof(Bun__Readable); + +#ifndef INCLUDED_BunStream_h +#define INCLUDED_BunStream_h +#include BunStream.h +#endif + +extern "C" const size_t Bun__Writable_object_size_ = sizeof(Bun__Writable); +extern "C" const size_t Bun__Writable_object_align_ = alignof(Bun__Writable); + #ifndef INCLUDED__ZigConsoleClient_h_ #define INCLUDED__ZigConsoleClient_h_ #include "ZigConsoleClient.h" @@ -224,8 +240,8 @@ extern "C" const size_t Zig__GlobalObject_object_align_ = alignof(Zig::GlobalObj extern "C" const size_t Zig__ConsoleClient_object_size_ = sizeof(Zig::ConsoleClient); extern "C" const size_t Zig__ConsoleClient_object_align_ = alignof(Zig::ConsoleClient); -const size_t sizes[26] = {sizeof(JSC::JSObject), sizeof(JSC::JSCell), sizeof(JSC::JSString), sizeof(Inspector::ScriptArguments), sizeof(JSC::JSModuleLoader), sizeof(JSC::JSModuleRecord), sizeof(JSC::JSPromise), sizeof(JSC::JSInternalPromise), sizeof(JSC::SourceOrigin), sizeof(JSC::SourceCode), sizeof(JSC::JSFunction), sizeof(JSC::JSGlobalObject), sizeof(WTF::URL), sizeof(WTF::String), sizeof(JSC::JSValue), sizeof(JSC::PropertyName), sizeof(JSC::Exception), sizeof(JSC::VM), sizeof(JSC::ThrowScope), sizeof(JSC::CatchScope), sizeof(JSC::CallFrame), sizeof(JSC::Identifier), sizeof(WTF::StringImpl), sizeof(WTF::ExternalStringImpl), sizeof(WTF::StringView), sizeof(Zig::GlobalObject)}; +const size_t sizes[29] = {sizeof(JSC::JSObject), sizeof(SystemError), sizeof(JSC::JSCell), sizeof(JSC::JSString), sizeof(Inspector::ScriptArguments), sizeof(JSC::JSModuleLoader), sizeof(JSC::JSModuleRecord), sizeof(JSC::JSPromise), sizeof(JSC::JSInternalPromise), sizeof(JSC::SourceOrigin), sizeof(JSC::SourceCode), sizeof(JSC::JSFunction), sizeof(JSC::JSGlobalObject), sizeof(WTF::URL), sizeof(WTF::String), sizeof(JSC::JSValue), sizeof(JSC::PropertyName), sizeof(JSC::Exception), sizeof(JSC::VM), sizeof(JSC::ThrowScope), sizeof(JSC::CatchScope), sizeof(JSC::CallFrame), sizeof(JSC::Identifier), sizeof(WTF::StringImpl), sizeof(WTF::ExternalStringImpl), sizeof(WTF::StringView), sizeof(Zig::GlobalObject), sizeof(Bun__Readable), sizeof(Bun__Writable)}; -const char* names[26] = {"JSC__JSObject", "JSC__JSCell", "JSC__JSString", "Inspector__ScriptArguments", "JSC__JSModuleLoader", "JSC__JSModuleRecord", "JSC__JSPromise", "JSC__JSInternalPromise", "JSC__SourceOrigin", "JSC__SourceCode", "JSC__JSFunction", "JSC__JSGlobalObject", "WTF__URL", "WTF__String", "JSC__JSValue", "JSC__PropertyName", "JSC__Exception", "JSC__VM", "JSC__ThrowScope", "JSC__CatchScope", "JSC__CallFrame", "JSC__Identifier", "WTF__StringImpl", "WTF__ExternalStringImpl", "WTF__StringView", "Zig__GlobalObject"}; +const char* names[29] = {"JSC__JSObject", "SystemError", "JSC__JSCell", "JSC__JSString", "Inspector__ScriptArguments", "JSC__JSModuleLoader", "JSC__JSModuleRecord", "JSC__JSPromise", "JSC__JSInternalPromise", "JSC__SourceOrigin", "JSC__SourceCode", "JSC__JSFunction", "JSC__JSGlobalObject", "WTF__URL", "WTF__String", "JSC__JSValue", "JSC__PropertyName", "JSC__Exception", "JSC__VM", "JSC__ThrowScope", "JSC__CatchScope", "JSC__CallFrame", "JSC__Identifier", "WTF__StringImpl", "WTF__ExternalStringImpl", "WTF__StringView", "Zig__GlobalObject", "Bun__Readable", "Bun__Writable"}; -const size_t aligns[26] = {alignof(JSC::JSObject), alignof(JSC::JSCell), alignof(JSC::JSString), alignof(Inspector::ScriptArguments), alignof(JSC::JSModuleLoader), alignof(JSC::JSModuleRecord), alignof(JSC::JSPromise), alignof(JSC::JSInternalPromise), alignof(JSC::SourceOrigin), alignof(JSC::SourceCode), alignof(JSC::JSFunction), alignof(JSC::JSGlobalObject), alignof(WTF::URL), alignof(WTF::String), alignof(JSC::JSValue), alignof(JSC::PropertyName), alignof(JSC::Exception), alignof(JSC::VM), alignof(JSC::ThrowScope), alignof(JSC::CatchScope), alignof(JSC::CallFrame), alignof(JSC::Identifier), alignof(WTF::StringImpl), alignof(WTF::ExternalStringImpl), alignof(WTF::StringView), alignof(Zig::GlobalObject)}; +const size_t aligns[29] = {alignof(JSC::JSObject), alignof(SystemError), alignof(JSC::JSCell), alignof(JSC::JSString), alignof(Inspector::ScriptArguments), alignof(JSC::JSModuleLoader), alignof(JSC::JSModuleRecord), alignof(JSC::JSPromise), alignof(JSC::JSInternalPromise), alignof(JSC::SourceOrigin), alignof(JSC::SourceCode), alignof(JSC::JSFunction), alignof(JSC::JSGlobalObject), alignof(WTF::URL), alignof(WTF::String), alignof(JSC::JSValue), alignof(JSC::PropertyName), alignof(JSC::Exception), alignof(JSC::VM), alignof(JSC::ThrowScope), alignof(JSC::CatchScope), alignof(JSC::CallFrame), alignof(JSC::Identifier), alignof(WTF::StringImpl), alignof(WTF::ExternalStringImpl), alignof(WTF::StringView), alignof(Zig::GlobalObject), alignof(Bun__Readable), alignof(Bun__Writable)}; diff --git a/src/javascript/jsc/bindings/headers-handwritten.h b/src/javascript/jsc/bindings/headers-handwritten.h index e07eca6b6..cf7c87e4f 100644 --- a/src/javascript/jsc/bindings/headers-handwritten.h +++ b/src/javascript/jsc/bindings/headers-handwritten.h @@ -35,6 +35,14 @@ typedef struct ErrorableResolvedSource { bool success; } ErrorableResolvedSource; +typedef struct SystemError { + int errno_; + ZigString code; + ZigString message; + ZigString path; + ZigString syscall; +} SystemError; + typedef uint8_t ZigStackFrameCode; const ZigStackFrameCode ZigStackFrameCodeNone = 0; const ZigStackFrameCode ZigStackFrameCodeEval = 1; @@ -74,6 +82,10 @@ typedef struct ZigStackTrace { typedef struct ZigException { unsigned char code; uint16_t runtime_type; + int errno_; + ZigString syscall; + ZigString code_; + ZigString path; ZigString name; ZigString message; ZigStackTrace stack; @@ -93,9 +105,83 @@ const JSErrorCode JSErrorCodeOutOfMemoryError = 8; const JSErrorCode JSErrorCodeStackOverflow = 253; const JSErrorCode JSErrorCodeUserErrorCode = 254; +#pragma mark - Stream + +typedef uint8_t Encoding; +const Encoding Encoding__utf8 = 0; +const Encoding Encoding__ucs2 = 1; +const Encoding Encoding__utf16le = 2; +const Encoding Encoding__latin1 = 3; +const Encoding Encoding__ascii = 4; +const Encoding Encoding__base64 = 5; +const Encoding Encoding__base64url = 6; +const Encoding Encoding__hex = 7; +const Encoding Encoding__buffer = 8; + +typedef uint8_t WritableEvent; +const WritableEvent WritableEvent__Close = 0; +const WritableEvent WritableEvent__Drain = 1; +const WritableEvent WritableEvent__Error = 2; +const WritableEvent WritableEvent__Finish = 3; +const WritableEvent WritableEvent__Pipe = 4; +const WritableEvent WritableEvent__Unpipe = 5; +const WritableEvent WritableEvent__Open = 6; +const WritableEvent WritableEventUser = 254; + +typedef uint8_t ReadableEvent; + +const ReadableEvent ReadableEvent__Close = 0; +const ReadableEvent ReadableEvent__Data = 1; +const ReadableEvent ReadableEvent__End = 2; +const ReadableEvent ReadableEvent__Error = 3; +const ReadableEvent ReadableEvent__Pause = 4; +const ReadableEvent ReadableEvent__Readable = 5; +const ReadableEvent ReadableEvent__Resume = 6; +const ReadableEvent ReadableEvent__Open = 7; +const ReadableEvent ReadableEventUser = 254; + +typedef struct { + uint32_t highwater_mark; + Encoding encoding; + int32_t start; + int32_t end; + bool readable; + bool aborted; + bool did_read; + bool ended; + uint8_t flowing; + bool emit_close; + bool emit_end; +} Bun__Readable; + +typedef struct { + uint32_t highwater_mark; + Encoding encoding; + uint32_t start; + bool destroyed; + bool ended; + bool corked; + bool finished; + bool emit_close; +} Bun__Writable; + #ifdef __cplusplus + extern "C" ZigErrorCode Zig_ErrorCodeParserError; extern "C" void ZigString__free(const unsigned char *ptr, size_t len, void *allocator); extern "C" void Microtask__run(void *ptr, void *global); + +// Used in process.version +extern "C" const char *Bun__version; + +// Used in process.versions +extern "C" const char *Bun__versions_webkit; +extern "C" const char *Bun__versions_mimalloc; +extern "C" const char *Bun__versions_libarchive; +extern "C" const char *Bun__versions_picohttpparser; +extern "C" const char *Bun__versions_boringssl; +extern "C" const char *Bun__versions_zlib; +extern "C" const char *Bun__versions_zig; + #endif diff --git a/src/javascript/jsc/bindings/headers-replacements.zig b/src/javascript/jsc/bindings/headers-replacements.zig index e45f0348d..96c058d56 100644 --- a/src/javascript/jsc/bindings/headers-replacements.zig +++ b/src/javascript/jsc/bindings/headers-replacements.zig @@ -53,4 +53,8 @@ pub const ZigStackTrace = bindings.ZigStackTrace; pub const ReturnableException = bindings.ReturnableException; pub const struct_Zig__JSMicrotaskCallback = bindings.Microtask; pub const bZig__JSMicrotaskCallback = struct_Zig__JSMicrotaskCallback; +pub const SystemError = bindings.SystemError; const JSClassRef = bindings.C.JSClassRef; +pub const JSC__CatchScope = bindings.CatchScope; +pub const Bun__Readable = bindings.NodeReadableStream; +pub const Bun__Writable = bindings.NodeWritableStream; diff --git a/src/javascript/jsc/bindings/headers.h b/src/javascript/jsc/bindings/headers.h index 6ae0dae83..9db733c02 100644 --- a/src/javascript/jsc/bindings/headers.h +++ b/src/javascript/jsc/bindings/headers.h @@ -1,5 +1,5 @@ // clang-format: off -//-- AUTOGENERATED FILE -- 1640933554 +//-- AUTOGENERATED FILE -- 1642473926 #pragma once #include <stddef.h> @@ -78,55 +78,58 @@ typedef void* JSClassRef; typedef char* bJSC__Identifier_buf; #ifndef __cplusplus - typedef struct JSC__RegExpPrototype JSC__RegExpPrototype; // JSC::RegExpPrototype + typedef bJSC__CatchScope JSC__CatchScope; // JSC::CatchScope typedef struct JSC__GeneratorPrototype JSC__GeneratorPrototype; // JSC::GeneratorPrototype typedef struct JSC__ArrayIteratorPrototype JSC__ArrayIteratorPrototype; // JSC::ArrayIteratorPrototype - typedef struct JSC__StringPrototype JSC__StringPrototype; // JSC::StringPrototype - typedef bWTF__StringView WTF__StringView; // WTF::StringView + typedef ErrorableResolvedSource ErrorableResolvedSource; typedef struct JSC__JSPromisePrototype JSC__JSPromisePrototype; // JSC::JSPromisePrototype - typedef bJSC__CatchScope JSC__CatchScope; // JSC::CatchScope - typedef bJSC__ThrowScope JSC__ThrowScope; // JSC::ThrowScope + typedef ErrorableZigString ErrorableZigString; typedef bJSC__PropertyName JSC__PropertyName; // JSC::PropertyName typedef bJSC__JSObject JSC__JSObject; // JSC::JSObject - typedef ErrorableResolvedSource ErrorableResolvedSource; - typedef ErrorableZigString ErrorableZigString; typedef bWTF__ExternalStringImpl WTF__ExternalStringImpl; // WTF::ExternalStringImpl typedef struct JSC__AsyncIteratorPrototype JSC__AsyncIteratorPrototype; // JSC::AsyncIteratorPrototype - typedef bWTF__StringImpl WTF__StringImpl; // WTF::StringImpl typedef bJSC__JSLock JSC__JSLock; // JSC::JSLock typedef bJSC__JSModuleLoader JSC__JSModuleLoader; // JSC::JSModuleLoader - typedef bJSC__VM JSC__VM; // JSC::VM - typedef JSClassRef JSClassRef; typedef struct JSC__AsyncGeneratorPrototype JSC__AsyncGeneratorPrototype; // JSC::AsyncGeneratorPrototype typedef struct JSC__AsyncGeneratorFunctionPrototype JSC__AsyncGeneratorFunctionPrototype; // JSC::AsyncGeneratorFunctionPrototype - typedef bJSC__JSGlobalObject JSC__JSGlobalObject; // JSC::JSGlobalObject - typedef bJSC__JSFunction JSC__JSFunction; // JSC::JSFunction - typedef struct JSC__ArrayPrototype JSC__ArrayPrototype; // JSC::ArrayPrototype - typedef struct JSC__AsyncFunctionPrototype JSC__AsyncFunctionPrototype; // JSC::AsyncFunctionPrototype typedef bJSC__Identifier JSC__Identifier; // JSC::Identifier + typedef struct JSC__ArrayPrototype JSC__ArrayPrototype; // JSC::ArrayPrototype + typedef struct Zig__JSMicrotaskCallback Zig__JSMicrotaskCallback; // Zig::JSMicrotaskCallback typedef bJSC__JSPromise JSC__JSPromise; // JSC::JSPromise - typedef ZigException ZigException; typedef struct JSC__SetIteratorPrototype JSC__SetIteratorPrototype; // JSC::SetIteratorPrototype - typedef bJSC__SourceCode JSC__SourceCode; // JSC::SourceCode - typedef struct Zig__JSMicrotaskCallback Zig__JSMicrotaskCallback; // Zig::JSMicrotaskCallback + typedef SystemError SystemError; typedef bJSC__JSCell JSC__JSCell; // JSC::JSCell - typedef struct JSC__BigIntPrototype JSC__BigIntPrototype; // JSC::BigIntPrototype - typedef struct JSC__GeneratorFunctionPrototype JSC__GeneratorFunctionPrototype; // JSC::GeneratorFunctionPrototype typedef bJSC__SourceOrigin JSC__SourceOrigin; // JSC::SourceOrigin - typedef ZigString ZigString; typedef bJSC__JSModuleRecord JSC__JSModuleRecord; // JSC::JSModuleRecord typedef bWTF__String WTF__String; // WTF::String typedef bWTF__URL WTF__URL; // WTF::URL - typedef int64_t JSC__JSValue; typedef struct JSC__IteratorPrototype JSC__IteratorPrototype; // JSC::IteratorPrototype + typedef Bun__Readable Bun__Readable; typedef bJSC__JSInternalPromise JSC__JSInternalPromise; // JSC::JSInternalPromise + typedef Bun__Writable Bun__Writable; + typedef struct JSC__RegExpPrototype JSC__RegExpPrototype; // JSC::RegExpPrototype + typedef bJSC__CallFrame JSC__CallFrame; // JSC::CallFrame + typedef struct JSC__MapIteratorPrototype JSC__MapIteratorPrototype; // JSC::MapIteratorPrototype + typedef bWTF__StringView WTF__StringView; // WTF::StringView + typedef bJSC__ThrowScope JSC__ThrowScope; // JSC::ThrowScope + typedef bWTF__StringImpl WTF__StringImpl; // WTF::StringImpl + typedef bJSC__VM JSC__VM; // JSC::VM + typedef JSClassRef JSClassRef; + typedef bJSC__JSGlobalObject JSC__JSGlobalObject; // JSC::JSGlobalObject + typedef bJSC__JSFunction JSC__JSFunction; // JSC::JSFunction + typedef struct JSC__AsyncFunctionPrototype JSC__AsyncFunctionPrototype; // JSC::AsyncFunctionPrototype + typedef ZigException ZigException; + typedef bJSC__SourceCode JSC__SourceCode; // JSC::SourceCode + typedef struct JSC__BigIntPrototype JSC__BigIntPrototype; // JSC::BigIntPrototype + typedef struct JSC__GeneratorFunctionPrototype JSC__GeneratorFunctionPrototype; // JSC::GeneratorFunctionPrototype + typedef ZigString ZigString; + typedef int64_t JSC__JSValue; typedef struct JSC__FunctionPrototype JSC__FunctionPrototype; // JSC::FunctionPrototype typedef bInspector__ScriptArguments Inspector__ScriptArguments; // Inspector::ScriptArguments typedef bJSC__Exception JSC__Exception; // JSC::Exception typedef bJSC__JSString JSC__JSString; // JSC::JSString typedef struct JSC__ObjectPrototype JSC__ObjectPrototype; // JSC::ObjectPrototype - typedef bJSC__CallFrame JSC__CallFrame; // JSC::CallFrame - typedef struct JSC__MapIteratorPrototype JSC__MapIteratorPrototype; // JSC::MapIteratorPrototype + typedef struct JSC__StringPrototype JSC__StringPrototype; // JSC::StringPrototype #endif @@ -134,8 +137,8 @@ typedef void* JSClassRef; namespace JSC { class JSCell; class Exception; - class StringPrototype; class JSPromisePrototype; + class StringPrototype; class GeneratorFunctionPrototype; class ArrayPrototype; class JSString; @@ -149,9 +152,9 @@ typedef void* JSClassRef; class CatchScope; class VM; class BigIntPrototype; - class SetIteratorPrototype; - class ThrowScope; class SourceOrigin; + class ThrowScope; + class SetIteratorPrototype; class AsyncGeneratorPrototype; class PropertyName; class MapIteratorPrototype; @@ -185,14 +188,17 @@ typedef void* JSClassRef; typedef ErrorableResolvedSource ErrorableResolvedSource; typedef ErrorableZigString ErrorableZigString; + typedef SystemError SystemError; + typedef Bun__Readable Bun__Readable; + typedef Bun__Writable Bun__Writable; typedef JSClassRef JSClassRef; typedef ZigException ZigException; typedef ZigString ZigString; typedef int64_t JSC__JSValue; using JSC__JSCell = JSC::JSCell; using JSC__Exception = JSC::Exception; - using JSC__StringPrototype = JSC::StringPrototype; using JSC__JSPromisePrototype = JSC::JSPromisePrototype; + using JSC__StringPrototype = JSC::StringPrototype; using JSC__GeneratorFunctionPrototype = JSC::GeneratorFunctionPrototype; using JSC__ArrayPrototype = JSC::ArrayPrototype; using JSC__JSString = JSC::JSString; @@ -206,9 +212,9 @@ typedef void* JSClassRef; using JSC__CatchScope = JSC::CatchScope; using JSC__VM = JSC::VM; using JSC__BigIntPrototype = JSC::BigIntPrototype; - using JSC__SetIteratorPrototype = JSC::SetIteratorPrototype; - using JSC__ThrowScope = JSC::ThrowScope; using JSC__SourceOrigin = JSC::SourceOrigin; + using JSC__ThrowScope = JSC::ThrowScope; + using JSC__SetIteratorPrototype = JSC::SetIteratorPrototype; using JSC__AsyncGeneratorPrototype = JSC::AsyncGeneratorPrototype; using JSC__PropertyName = JSC::PropertyName; using JSC__MapIteratorPrototype = JSC::MapIteratorPrototype; @@ -242,11 +248,12 @@ CPP_DECL JSC__JSValue JSC__JSObject__create(JSC__JSGlobalObject* arg0, size_t ar CPP_DECL size_t JSC__JSObject__getArrayLength(JSC__JSObject* arg0); CPP_DECL JSC__JSValue JSC__JSObject__getDirect(JSC__JSObject* arg0, JSC__JSGlobalObject* arg1, const ZigString* arg2); CPP_DECL JSC__JSValue JSC__JSObject__getIndex(JSC__JSValue JSValue0, JSC__JSGlobalObject* arg1, uint32_t arg2); -CPP_DECL void JSC__JSObject__putDirect(JSC__JSObject* arg0, JSC__JSGlobalObject* arg1, const ZigString* arg2, JSC__JSValue JSValue3); CPP_DECL void JSC__JSObject__putRecord(JSC__JSObject* arg0, JSC__JSGlobalObject* arg1, ZigString* arg2, ZigString* arg3, size_t arg4); +CPP_DECL JSC__JSValue ZigString__to16BitValue(const ZigString* arg0, JSC__JSGlobalObject* arg1); CPP_DECL JSC__JSValue ZigString__toErrorInstance(const ZigString* arg0, JSC__JSGlobalObject* arg1); CPP_DECL JSC__JSValue ZigString__toValue(const ZigString* arg0, JSC__JSGlobalObject* arg1); CPP_DECL JSC__JSValue ZigString__toValueGC(const ZigString* arg0, JSC__JSGlobalObject* arg1); +CPP_DECL JSC__JSValue SystemError__toErrorInstance(const SystemError* arg0, JSC__JSGlobalObject* arg1); #pragma mark - JSC::JSCell @@ -352,6 +359,7 @@ CPP_DECL JSC__JSValue JSC__JSGlobalObject__createAggregateError(JSC__JSGlobalObj CPP_DECL JSC__JSObject* JSC__JSGlobalObject__datePrototype(JSC__JSGlobalObject* arg0); CPP_DECL JSC__JSObject* JSC__JSGlobalObject__errorPrototype(JSC__JSGlobalObject* arg0); CPP_DECL JSC__FunctionPrototype* JSC__JSGlobalObject__functionPrototype(JSC__JSGlobalObject* arg0); +CPP_DECL JSC__JSValue JSC__JSGlobalObject__generateHeapSnapshot(JSC__JSGlobalObject* arg0); CPP_DECL JSC__GeneratorFunctionPrototype* JSC__JSGlobalObject__generatorFunctionPrototype(JSC__JSGlobalObject* arg0); CPP_DECL JSC__GeneratorPrototype* JSC__JSGlobalObject__generatorPrototype(JSC__JSGlobalObject* arg0); CPP_DECL JSC__IteratorPrototype* JSC__JSGlobalObject__iteratorPrototype(JSC__JSGlobalObject* arg0); @@ -422,15 +430,22 @@ CPP_DECL double JSC__JSValue__asNumber(JSC__JSValue JSValue0); CPP_DECL bJSC__JSObject JSC__JSValue__asObject(JSC__JSValue JSValue0); CPP_DECL JSC__JSString* JSC__JSValue__asString(JSC__JSValue JSValue0); CPP_DECL JSC__JSValue JSC__JSValue__createEmptyObject(JSC__JSGlobalObject* arg0, size_t arg1); -CPP_DECL JSC__JSValue JSC__JSValue__createStringArray(JSC__JSGlobalObject* arg0, ZigString* arg1, size_t arg2); +CPP_DECL JSC__JSValue JSC__JSValue__createObject2(JSC__JSGlobalObject* arg0, const ZigString* arg1, const ZigString* arg2, JSC__JSValue JSValue3, JSC__JSValue JSValue4); +CPP_DECL JSC__JSValue JSC__JSValue__createRangeError(const ZigString* arg0, const ZigString* arg1, JSC__JSGlobalObject* arg2); +CPP_DECL JSC__JSValue JSC__JSValue__createStringArray(JSC__JSGlobalObject* arg0, ZigString* arg1, size_t arg2, bool arg3); +CPP_DECL JSC__JSValue JSC__JSValue__createTypeError(const ZigString* arg0, const ZigString* arg1, JSC__JSGlobalObject* arg2); CPP_DECL bool JSC__JSValue__eqlCell(JSC__JSValue JSValue0, JSC__JSCell* arg1); CPP_DECL bool JSC__JSValue__eqlValue(JSC__JSValue JSValue0, JSC__JSValue JSValue1); CPP_DECL void JSC__JSValue__forEach(JSC__JSValue JSValue0, JSC__JSGlobalObject* arg1, void (* ArgFn2)(JSC__VM* arg0, JSC__JSGlobalObject* arg1, JSC__JSValue JSValue2)); +CPP_DECL JSC__JSValue JSC__JSValue__fromEntries(JSC__JSGlobalObject* arg0, ZigString* arg1, ZigString* arg2, size_t arg3, bool arg4); CPP_DECL void JSC__JSValue__getClassName(JSC__JSValue JSValue0, JSC__JSGlobalObject* arg1, ZigString* arg2); CPP_DECL JSC__JSValue JSC__JSValue__getErrorsProperty(JSC__JSValue JSValue0, JSC__JSGlobalObject* arg1); +CPP_DECL JSC__JSValue JSC__JSValue__getIfPropertyExistsImpl(JSC__JSValue JSValue0, JSC__JSGlobalObject* arg1, const unsigned char* arg2, uint32_t arg3); CPP_DECL uint32_t JSC__JSValue__getLengthOfArray(JSC__JSValue JSValue0, JSC__JSGlobalObject* arg1); CPP_DECL void JSC__JSValue__getNameProperty(JSC__JSValue JSValue0, JSC__JSGlobalObject* arg1, ZigString* arg2); CPP_DECL JSC__JSValue JSC__JSValue__getPrototype(JSC__JSValue JSValue0, JSC__JSGlobalObject* arg1); +CPP_DECL Bun__Readable* JSC__JSValue__getReadableStreamState(JSC__JSValue JSValue0, JSC__VM* arg1); +CPP_DECL Bun__Writable* JSC__JSValue__getWritableStreamState(JSC__JSValue JSValue0, JSC__VM* arg1); CPP_DECL bool JSC__JSValue__isAggregateError(JSC__JSValue JSValue0, JSC__JSGlobalObject* arg1); CPP_DECL bool JSC__JSValue__isAnyInt(JSC__JSValue JSValue0); CPP_DECL bool JSC__JSValue__isBigInt(JSC__JSValue JSValue0); @@ -451,8 +466,10 @@ CPP_DECL bool JSC__JSValue__isNull(JSC__JSValue JSValue0); CPP_DECL bool JSC__JSValue__isNumber(JSC__JSValue JSValue0); CPP_DECL bool JSC__JSValue__isObject(JSC__JSValue JSValue0); CPP_DECL bool JSC__JSValue__isPrimitive(JSC__JSValue JSValue0); +CPP_DECL bool JSC__JSValue__isSameValue(JSC__JSValue JSValue0, JSC__JSValue JSValue1, JSC__JSGlobalObject* arg2); CPP_DECL bool JSC__JSValue__isString(JSC__JSValue JSValue0); CPP_DECL bool JSC__JSValue__isSymbol(JSC__JSValue JSValue0); +CPP_DECL bool JSC__JSValue__isTerminationException(JSC__JSValue JSValue0, JSC__VM* arg1); CPP_DECL bool JSC__JSValue__isUInt32AsAnyInt(JSC__JSValue JSValue0); CPP_DECL bool JSC__JSValue__isUndefined(JSC__JSValue JSValue0); CPP_DECL bool JSC__JSValue__isUndefinedOrNull(JSC__JSValue JSValue0); @@ -465,7 +482,9 @@ CPP_DECL JSC__JSValue JSC__JSValue__jsNumberFromInt32(int32_t arg0); CPP_DECL JSC__JSValue JSC__JSValue__jsNumberFromInt64(int64_t arg0); CPP_DECL JSC__JSValue JSC__JSValue__jsNumberFromU16(uint16_t arg0); CPP_DECL JSC__JSValue JSC__JSValue__jsNumberFromUint64(uint64_t arg0); +CPP_DECL void JSC__JSValue__jsonStringify(JSC__JSValue JSValue0, JSC__JSGlobalObject* arg1, uint32_t arg2, ZigString* arg3); CPP_DECL JSC__JSValue JSC__JSValue__jsTDZValue(); +CPP_DECL unsigned char JSC__JSValue__jsType(JSC__JSValue JSValue0); CPP_DECL JSC__JSValue JSC__JSValue__jsUndefined(); CPP_DECL void JSC__JSValue__putRecord(JSC__JSValue JSValue0, JSC__JSGlobalObject* arg1, ZigString* arg2, ZigString* arg3, size_t arg4); CPP_DECL bool JSC__JSValue__toBoolean(JSC__JSValue JSValue0); @@ -496,14 +515,18 @@ CPP_DECL JSC__JSValue JSC__Exception__value(JSC__Exception* arg0); #pragma mark - JSC::VM CPP_DECL JSC__JSLock* JSC__VM__apiLock(JSC__VM* arg0); +CPP_DECL void JSC__VM__clearExecutionTimeLimit(JSC__VM* arg0); CPP_DECL JSC__VM* JSC__VM__create(unsigned char HeapType0); CPP_DECL void JSC__VM__deinit(JSC__VM* arg0, JSC__JSGlobalObject* arg1); CPP_DECL void JSC__VM__deleteAllCode(JSC__VM* arg0, JSC__JSGlobalObject* arg1); CPP_DECL void JSC__VM__drainMicrotasks(JSC__VM* arg0); CPP_DECL bool JSC__VM__executionForbidden(JSC__VM* arg0); +CPP_DECL void JSC__VM__holdAPILock(JSC__VM* arg0, void* arg1, void (* ArgFn2)(void* arg0)); CPP_DECL bool JSC__VM__isEntered(JSC__VM* arg0); CPP_DECL bool JSC__VM__isJITEnabled(); +CPP_DECL JSC__JSValue JSC__VM__runGC(JSC__VM* arg0, bool arg1); CPP_DECL void JSC__VM__setExecutionForbidden(JSC__VM* arg0, bool arg1); +CPP_DECL void JSC__VM__setExecutionTimeLimit(JSC__VM* arg0, double arg1); CPP_DECL void JSC__VM__shrinkFootprint(JSC__VM* arg0); CPP_DECL bool JSC__VM__throwError(JSC__VM* arg0, JSC__JSGlobalObject* arg1, JSC__ThrowScope* arg2, const unsigned char* arg3, size_t arg4); CPP_DECL void JSC__VM__whenIdle(JSC__VM* arg0, void (* ArgFn1)()); @@ -604,6 +627,54 @@ ZIG_DECL void Zig__GlobalObject__resolve(ErrorableZigString* arg0, JSC__JSGlobal ZIG_DECL bool Zig__ErrorType__isPrivateData(void* arg0); #endif + +#pragma mark - Bun__Readable + +CPP_DECL JSC__JSValue Bun__Readable__create(Bun__Readable* arg0, JSC__JSGlobalObject* arg1); + +#ifdef __cplusplus + +ZIG_DECL void Bun__Readable__addEventListener(Bun__Readable* arg0, JSC__JSGlobalObject* arg1, unsigned char Events2, JSC__JSValue JSValue3, bool arg4); +ZIG_DECL void Bun__Readable__deinit(Bun__Readable* arg0); +ZIG_DECL JSC__JSValue Bun__Readable__pause(Bun__Readable* arg0, JSC__JSGlobalObject* arg1, JSC__JSValue* arg2, uint16_t arg3); +ZIG_DECL JSC__JSValue Bun__Readable__pipe(Bun__Readable* arg0, JSC__JSGlobalObject* arg1, JSC__JSValue* arg2, uint16_t arg3); +ZIG_DECL void Bun__Readable__prependEventListener(Bun__Readable* arg0, JSC__JSGlobalObject* arg1, unsigned char Events2, JSC__JSValue JSValue3, bool arg4); +ZIG_DECL JSC__JSValue Bun__Readable__read(Bun__Readable* arg0, JSC__JSGlobalObject* arg1, JSC__JSValue* arg2, uint16_t arg3); +ZIG_DECL bool Bun__Readable__removeEventListener(Bun__Readable* arg0, JSC__JSGlobalObject* arg1, unsigned char Events2, JSC__JSValue JSValue3); +ZIG_DECL JSC__JSValue Bun__Readable__resume(Bun__Readable* arg0, JSC__JSGlobalObject* arg1, JSC__JSValue* arg2, uint16_t arg3); +ZIG_DECL JSC__JSValue Bun__Readable__unpipe(Bun__Readable* arg0, JSC__JSGlobalObject* arg1, JSC__JSValue* arg2, uint16_t arg3); +ZIG_DECL JSC__JSValue Bun__Readable__unshift(Bun__Readable* arg0, JSC__JSGlobalObject* arg1, JSC__JSValue* arg2, uint16_t arg3); + +#endif + +#pragma mark - Bun__Writable + +CPP_DECL JSC__JSValue Bun__Writable__create(Bun__Writable* arg0, JSC__JSGlobalObject* arg1); + +#ifdef __cplusplus + +ZIG_DECL void Bun__Writable__addEventListener(Bun__Writable* arg0, JSC__JSGlobalObject* arg1, unsigned char Events2, JSC__JSValue JSValue3, bool arg4); +ZIG_DECL JSC__JSValue Bun__Writable__close(Bun__Writable* arg0, JSC__JSGlobalObject* arg1, JSC__JSValue* arg2, uint16_t arg3); +ZIG_DECL JSC__JSValue Bun__Writable__cork(Bun__Writable* arg0, JSC__JSGlobalObject* arg1, JSC__JSValue* arg2, uint16_t arg3); +ZIG_DECL void Bun__Writable__deinit(Bun__Writable* arg0); +ZIG_DECL JSC__JSValue Bun__Writable__destroy(Bun__Writable* arg0, JSC__JSGlobalObject* arg1, JSC__JSValue* arg2, uint16_t arg3); +ZIG_DECL JSC__JSValue Bun__Writable__end(Bun__Writable* arg0, JSC__JSGlobalObject* arg1, JSC__JSValue* arg2, uint16_t arg3); +ZIG_DECL void Bun__Writable__prependEventListener(Bun__Writable* arg0, JSC__JSGlobalObject* arg1, unsigned char Events2, JSC__JSValue JSValue3, bool arg4); +ZIG_DECL bool Bun__Writable__removeEventListener(Bun__Writable* arg0, JSC__JSGlobalObject* arg1, unsigned char Events2, JSC__JSValue JSValue3); +ZIG_DECL JSC__JSValue Bun__Writable__uncork(Bun__Writable* arg0, JSC__JSGlobalObject* arg1, JSC__JSValue* arg2, uint16_t arg3); +ZIG_DECL JSC__JSValue Bun__Writable__write(Bun__Writable* arg0, JSC__JSGlobalObject* arg1, JSC__JSValue* arg2, uint16_t arg3); + +#endif + +#ifdef __cplusplus + +ZIG_DECL JSC__JSValue Bun__Process__getArgv(JSC__JSGlobalObject* arg0); +ZIG_DECL JSC__JSValue Bun__Process__getCwd(JSC__JSGlobalObject* arg0); +ZIG_DECL void Bun__Process__getTitle(JSC__JSGlobalObject* arg0, ZigString* arg1); +ZIG_DECL JSC__JSValue Bun__Process__setCwd(JSC__JSGlobalObject* arg0, ZigString* arg1); +ZIG_DECL JSC__JSValue Bun__Process__setTitle(JSC__JSGlobalObject* arg0, ZigString* arg1); + +#endif CPP_DECL ZigException ZigException__fromException(JSC__Exception* arg0); #pragma mark - Zig::ConsoleClient @@ -613,7 +684,7 @@ CPP_DECL ZigException ZigException__fromException(JSC__Exception* arg0); ZIG_DECL void Zig__ConsoleClient__count(void* arg0, JSC__JSGlobalObject* arg1, const unsigned char* arg2, size_t arg3); ZIG_DECL void Zig__ConsoleClient__countReset(void* arg0, JSC__JSGlobalObject* arg1, const unsigned char* arg2, size_t arg3); -ZIG_DECL void Zig__ConsoleClient__messageWithTypeAndLevel(void* arg0, uint32_t arg1, uint32_t arg2, JSC__JSGlobalObject* arg3, JSC__JSValue* arg4, size_t arg5); +ZIG_DECL void Zig__ConsoleClient__messageWithTypeAndLevel(void* arg0, uint32_t MessageType1, uint32_t MessageLevel2, JSC__JSGlobalObject* arg3, JSC__JSValue* arg4, size_t arg5); ZIG_DECL void Zig__ConsoleClient__profile(void* arg0, JSC__JSGlobalObject* arg1, const unsigned char* arg2, size_t arg3); ZIG_DECL void Zig__ConsoleClient__profileEnd(void* arg0, JSC__JSGlobalObject* arg1, const unsigned char* arg2, size_t arg3); ZIG_DECL void Zig__ConsoleClient__record(void* arg0, JSC__JSGlobalObject* arg1, Inspector__ScriptArguments* arg2); diff --git a/src/javascript/jsc/bindings/headers.zig b/src/javascript/jsc/bindings/headers.zig index f5ab2f69a..061fe3d17 100644 --- a/src/javascript/jsc/bindings/headers.zig +++ b/src/javascript/jsc/bindings/headers.zig @@ -53,7 +53,11 @@ pub const ZigStackTrace = bindings.ZigStackTrace; pub const ReturnableException = bindings.ReturnableException; pub const struct_Zig__JSMicrotaskCallback = bindings.Microtask; pub const bZig__JSMicrotaskCallback = struct_Zig__JSMicrotaskCallback; +pub const SystemError = bindings.SystemError; const JSClassRef = bindings.C.JSClassRef; +pub const JSC__CatchScope = bindings.CatchScope; +pub const Bun__Readable = bindings.NodeReadableStream; +pub const Bun__Writable = bindings.NodeWritableStream; // GENERATED CODE - DO NOT MODIFY BY HAND pub const ptrdiff_t = c_long; @@ -68,49 +72,31 @@ pub const __mbstate_t = extern union { _mbstateL: c_longlong, }; -pub const JSC__RegExpPrototype = struct_JSC__RegExpPrototype; - pub const JSC__GeneratorPrototype = struct_JSC__GeneratorPrototype; pub const JSC__ArrayIteratorPrototype = struct_JSC__ArrayIteratorPrototype; -pub const JSC__StringPrototype = struct_JSC__StringPrototype; -pub const WTF__StringView = bWTF__StringView; - pub const JSC__JSPromisePrototype = struct_JSC__JSPromisePrototype; -pub const JSC__CatchScope = bJSC__CatchScope; -pub const JSC__ThrowScope = bJSC__ThrowScope; pub const JSC__PropertyName = bJSC__PropertyName; pub const JSC__JSObject = bJSC__JSObject; pub const WTF__ExternalStringImpl = bWTF__ExternalStringImpl; pub const JSC__AsyncIteratorPrototype = struct_JSC__AsyncIteratorPrototype; -pub const WTF__StringImpl = bWTF__StringImpl; pub const JSC__JSLock = bJSC__JSLock; pub const JSC__JSModuleLoader = bJSC__JSModuleLoader; -pub const JSC__VM = bJSC__VM; pub const JSC__AsyncGeneratorPrototype = struct_JSC__AsyncGeneratorPrototype; pub const JSC__AsyncGeneratorFunctionPrototype = struct_JSC__AsyncGeneratorFunctionPrototype; -pub const JSC__JSGlobalObject = bJSC__JSGlobalObject; -pub const JSC__JSFunction = bJSC__JSFunction; +pub const JSC__Identifier = bJSC__Identifier; pub const JSC__ArrayPrototype = struct_JSC__ArrayPrototype; -pub const JSC__AsyncFunctionPrototype = struct_JSC__AsyncFunctionPrototype; -pub const JSC__Identifier = bJSC__Identifier; +pub const Zig__JSMicrotaskCallback = struct_Zig__JSMicrotaskCallback; pub const JSC__JSPromise = bJSC__JSPromise; pub const JSC__SetIteratorPrototype = struct_JSC__SetIteratorPrototype; -pub const JSC__SourceCode = bJSC__SourceCode; - -pub const Zig__JSMicrotaskCallback = struct_Zig__JSMicrotaskCallback; pub const JSC__JSCell = bJSC__JSCell; - -pub const JSC__BigIntPrototype = struct_JSC__BigIntPrototype; - -pub const JSC__GeneratorFunctionPrototype = struct_JSC__GeneratorFunctionPrototype; pub const JSC__SourceOrigin = bJSC__SourceOrigin; pub const JSC__JSModuleRecord = bJSC__JSModuleRecord; pub const WTF__String = bWTF__String; @@ -119,24 +105,42 @@ pub const WTF__URL = bWTF__URL; pub const JSC__IteratorPrototype = struct_JSC__IteratorPrototype; pub const JSC__JSInternalPromise = bJSC__JSInternalPromise; +pub const JSC__RegExpPrototype = struct_JSC__RegExpPrototype; +pub const JSC__CallFrame = bJSC__CallFrame; + +pub const JSC__MapIteratorPrototype = struct_JSC__MapIteratorPrototype; +pub const WTF__StringView = bWTF__StringView; +pub const JSC__ThrowScope = bJSC__ThrowScope; +pub const WTF__StringImpl = bWTF__StringImpl; +pub const JSC__VM = bJSC__VM; +pub const JSC__JSGlobalObject = bJSC__JSGlobalObject; +pub const JSC__JSFunction = bJSC__JSFunction; + +pub const JSC__AsyncFunctionPrototype = struct_JSC__AsyncFunctionPrototype; +pub const JSC__SourceCode = bJSC__SourceCode; + +pub const JSC__BigIntPrototype = struct_JSC__BigIntPrototype; + +pub const JSC__GeneratorFunctionPrototype = struct_JSC__GeneratorFunctionPrototype; + pub const JSC__FunctionPrototype = struct_JSC__FunctionPrototype; pub const Inspector__ScriptArguments = bInspector__ScriptArguments; pub const JSC__Exception = bJSC__Exception; pub const JSC__JSString = bJSC__JSString; pub const JSC__ObjectPrototype = struct_JSC__ObjectPrototype; -pub const JSC__CallFrame = bJSC__CallFrame; -pub const JSC__MapIteratorPrototype = struct_JSC__MapIteratorPrototype; +pub const JSC__StringPrototype = struct_JSC__StringPrototype; pub extern fn JSC__JSObject__create(arg0: [*c]JSC__JSGlobalObject, arg1: usize, arg2: ?*anyopaque, ArgFn3: ?fn (?*anyopaque, [*c]JSC__JSObject, [*c]JSC__JSGlobalObject) callconv(.C) void) JSC__JSValue; pub extern fn JSC__JSObject__getArrayLength(arg0: [*c]JSC__JSObject) usize; pub extern fn JSC__JSObject__getDirect(arg0: [*c]JSC__JSObject, arg1: [*c]JSC__JSGlobalObject, arg2: [*c]const ZigString) JSC__JSValue; pub extern fn JSC__JSObject__getIndex(JSValue0: JSC__JSValue, arg1: [*c]JSC__JSGlobalObject, arg2: u32) JSC__JSValue; -pub extern fn JSC__JSObject__putDirect(arg0: [*c]JSC__JSObject, arg1: [*c]JSC__JSGlobalObject, arg2: [*c]const ZigString, JSValue3: JSC__JSValue) void; pub extern fn JSC__JSObject__putRecord(arg0: [*c]JSC__JSObject, arg1: [*c]JSC__JSGlobalObject, arg2: [*c]ZigString, arg3: [*c]ZigString, arg4: usize) void; +pub extern fn ZigString__to16BitValue(arg0: [*c]const ZigString, arg1: [*c]JSC__JSGlobalObject) JSC__JSValue; pub extern fn ZigString__toErrorInstance(arg0: [*c]const ZigString, arg1: [*c]JSC__JSGlobalObject) JSC__JSValue; pub extern fn ZigString__toValue(arg0: [*c]const ZigString, arg1: [*c]JSC__JSGlobalObject) JSC__JSValue; pub extern fn ZigString__toValueGC(arg0: [*c]const ZigString, arg1: [*c]JSC__JSGlobalObject) JSC__JSValue; +pub extern fn SystemError__toErrorInstance(arg0: [*c]const SystemError, arg1: [*c]JSC__JSGlobalObject) JSC__JSValue; pub extern fn JSC__JSCell__getObject(arg0: [*c]JSC__JSCell) [*c]JSC__JSObject; pub extern fn JSC__JSCell__getString(arg0: [*c]JSC__JSCell, arg1: [*c]JSC__JSGlobalObject) bWTF__String; pub extern fn JSC__JSCell__getType(arg0: [*c]JSC__JSCell) u8; @@ -209,6 +213,7 @@ pub extern fn JSC__JSGlobalObject__createAggregateError(arg0: [*c]JSC__JSGlobalO pub extern fn JSC__JSGlobalObject__datePrototype(arg0: [*c]JSC__JSGlobalObject) [*c]JSC__JSObject; pub extern fn JSC__JSGlobalObject__errorPrototype(arg0: [*c]JSC__JSGlobalObject) [*c]JSC__JSObject; pub extern fn JSC__JSGlobalObject__functionPrototype(arg0: [*c]JSC__JSGlobalObject) ?*JSC__FunctionPrototype; +pub extern fn JSC__JSGlobalObject__generateHeapSnapshot(arg0: [*c]JSC__JSGlobalObject) JSC__JSValue; pub extern fn JSC__JSGlobalObject__generatorFunctionPrototype(arg0: [*c]JSC__JSGlobalObject) ?*JSC__GeneratorFunctionPrototype; pub extern fn JSC__JSGlobalObject__generatorPrototype(arg0: [*c]JSC__JSGlobalObject) ?*JSC__GeneratorPrototype; pub extern fn JSC__JSGlobalObject__iteratorPrototype(arg0: [*c]JSC__JSGlobalObject) ?*JSC__IteratorPrototype; @@ -270,15 +275,22 @@ pub extern fn JSC__JSValue__asNumber(JSValue0: JSC__JSValue) f64; pub extern fn JSC__JSValue__asObject(JSValue0: JSC__JSValue) bJSC__JSObject; pub extern fn JSC__JSValue__asString(JSValue0: JSC__JSValue) [*c]JSC__JSString; pub extern fn JSC__JSValue__createEmptyObject(arg0: [*c]JSC__JSGlobalObject, arg1: usize) JSC__JSValue; -pub extern fn JSC__JSValue__createStringArray(arg0: [*c]JSC__JSGlobalObject, arg1: [*c]ZigString, arg2: usize) JSC__JSValue; +pub extern fn JSC__JSValue__createObject2(arg0: [*c]JSC__JSGlobalObject, arg1: [*c]const ZigString, arg2: [*c]const ZigString, JSValue3: JSC__JSValue, JSValue4: JSC__JSValue) JSC__JSValue; +pub extern fn JSC__JSValue__createRangeError(arg0: [*c]const ZigString, arg1: [*c]const ZigString, arg2: [*c]JSC__JSGlobalObject) JSC__JSValue; +pub extern fn JSC__JSValue__createStringArray(arg0: [*c]JSC__JSGlobalObject, arg1: [*c]ZigString, arg2: usize, arg3: bool) JSC__JSValue; +pub extern fn JSC__JSValue__createTypeError(arg0: [*c]const ZigString, arg1: [*c]const ZigString, arg2: [*c]JSC__JSGlobalObject) JSC__JSValue; pub extern fn JSC__JSValue__eqlCell(JSValue0: JSC__JSValue, arg1: [*c]JSC__JSCell) bool; pub extern fn JSC__JSValue__eqlValue(JSValue0: JSC__JSValue, JSValue1: JSC__JSValue) bool; pub extern fn JSC__JSValue__forEach(JSValue0: JSC__JSValue, arg1: [*c]JSC__JSGlobalObject, ArgFn2: ?fn ([*c]JSC__VM, [*c]JSC__JSGlobalObject, JSC__JSValue) callconv(.C) void) void; +pub extern fn JSC__JSValue__fromEntries(arg0: [*c]JSC__JSGlobalObject, arg1: [*c]ZigString, arg2: [*c]ZigString, arg3: usize, arg4: bool) JSC__JSValue; pub extern fn JSC__JSValue__getClassName(JSValue0: JSC__JSValue, arg1: [*c]JSC__JSGlobalObject, arg2: [*c]ZigString) void; pub extern fn JSC__JSValue__getErrorsProperty(JSValue0: JSC__JSValue, arg1: [*c]JSC__JSGlobalObject) JSC__JSValue; +pub extern fn JSC__JSValue__getIfPropertyExistsImpl(JSValue0: JSC__JSValue, arg1: [*c]JSC__JSGlobalObject, arg2: [*c]const u8, arg3: u32) JSC__JSValue; pub extern fn JSC__JSValue__getLengthOfArray(JSValue0: JSC__JSValue, arg1: [*c]JSC__JSGlobalObject) u32; pub extern fn JSC__JSValue__getNameProperty(JSValue0: JSC__JSValue, arg1: [*c]JSC__JSGlobalObject, arg2: [*c]ZigString) void; pub extern fn JSC__JSValue__getPrototype(JSValue0: JSC__JSValue, arg1: [*c]JSC__JSGlobalObject) JSC__JSValue; +pub extern fn JSC__JSValue__getReadableStreamState(JSValue0: JSC__JSValue, arg1: [*c]JSC__VM) [*c]Bun__Readable; +pub extern fn JSC__JSValue__getWritableStreamState(JSValue0: JSC__JSValue, arg1: [*c]JSC__VM) [*c]Bun__Writable; pub extern fn JSC__JSValue__isAggregateError(JSValue0: JSC__JSValue, arg1: [*c]JSC__JSGlobalObject) bool; pub extern fn JSC__JSValue__isAnyInt(JSValue0: JSC__JSValue) bool; pub extern fn JSC__JSValue__isBigInt(JSValue0: JSC__JSValue) bool; @@ -299,8 +311,10 @@ pub extern fn JSC__JSValue__isNull(JSValue0: JSC__JSValue) bool; pub extern fn JSC__JSValue__isNumber(JSValue0: JSC__JSValue) bool; pub extern fn JSC__JSValue__isObject(JSValue0: JSC__JSValue) bool; pub extern fn JSC__JSValue__isPrimitive(JSValue0: JSC__JSValue) bool; +pub extern fn JSC__JSValue__isSameValue(JSValue0: JSC__JSValue, JSValue1: JSC__JSValue, arg2: [*c]JSC__JSGlobalObject) bool; pub extern fn JSC__JSValue__isString(JSValue0: JSC__JSValue) bool; pub extern fn JSC__JSValue__isSymbol(JSValue0: JSC__JSValue) bool; +pub extern fn JSC__JSValue__isTerminationException(JSValue0: JSC__JSValue, arg1: [*c]JSC__VM) bool; pub extern fn JSC__JSValue__isUInt32AsAnyInt(JSValue0: JSC__JSValue) bool; pub extern fn JSC__JSValue__isUndefined(JSValue0: JSC__JSValue) bool; pub extern fn JSC__JSValue__isUndefinedOrNull(JSValue0: JSC__JSValue) bool; @@ -313,7 +327,9 @@ pub extern fn JSC__JSValue__jsNumberFromInt32(arg0: i32) JSC__JSValue; pub extern fn JSC__JSValue__jsNumberFromInt64(arg0: i64) JSC__JSValue; pub extern fn JSC__JSValue__jsNumberFromU16(arg0: u16) JSC__JSValue; pub extern fn JSC__JSValue__jsNumberFromUint64(arg0: u64) JSC__JSValue; +pub extern fn JSC__JSValue__jsonStringify(JSValue0: JSC__JSValue, arg1: [*c]JSC__JSGlobalObject, arg2: u32, arg3: [*c]ZigString) void; pub extern fn JSC__JSValue__jsTDZValue(...) JSC__JSValue; +pub extern fn JSC__JSValue__jsType(JSValue0: JSC__JSValue) u8; pub extern fn JSC__JSValue__jsUndefined(...) JSC__JSValue; pub extern fn JSC__JSValue__putRecord(JSValue0: JSC__JSValue, arg1: [*c]JSC__JSGlobalObject, arg2: [*c]ZigString, arg3: [*c]ZigString, arg4: usize) void; pub extern fn JSC__JSValue__toBoolean(JSValue0: JSC__JSValue) bool; @@ -334,14 +350,18 @@ pub extern fn JSC__Exception__create(arg0: [*c]JSC__JSGlobalObject, arg1: [*c]JS pub extern fn JSC__Exception__getStackTrace(arg0: [*c]JSC__Exception, arg1: [*c]ZigStackTrace) void; pub extern fn JSC__Exception__value(arg0: [*c]JSC__Exception) JSC__JSValue; pub extern fn JSC__VM__apiLock(arg0: [*c]JSC__VM) [*c]JSC__JSLock; +pub extern fn JSC__VM__clearExecutionTimeLimit(arg0: [*c]JSC__VM) void; pub extern fn JSC__VM__create(HeapType0: u8) [*c]JSC__VM; pub extern fn JSC__VM__deinit(arg0: [*c]JSC__VM, arg1: [*c]JSC__JSGlobalObject) void; pub extern fn JSC__VM__deleteAllCode(arg0: [*c]JSC__VM, arg1: [*c]JSC__JSGlobalObject) void; pub extern fn JSC__VM__drainMicrotasks(arg0: [*c]JSC__VM) void; pub extern fn JSC__VM__executionForbidden(arg0: [*c]JSC__VM) bool; +pub extern fn JSC__VM__holdAPILock(arg0: [*c]JSC__VM, arg1: ?*anyopaque, ArgFn2: ?fn (?*anyopaque) callconv(.C) void) void; pub extern fn JSC__VM__isEntered(arg0: [*c]JSC__VM) bool; pub extern fn JSC__VM__isJITEnabled(...) bool; +pub extern fn JSC__VM__runGC(arg0: [*c]JSC__VM, arg1: bool) JSC__JSValue; pub extern fn JSC__VM__setExecutionForbidden(arg0: [*c]JSC__VM, arg1: bool) void; +pub extern fn JSC__VM__setExecutionTimeLimit(arg0: [*c]JSC__VM, arg1: f64) void; pub extern fn JSC__VM__shrinkFootprint(arg0: [*c]JSC__VM) void; pub extern fn JSC__VM__throwError(arg0: [*c]JSC__VM, arg1: [*c]JSC__JSGlobalObject, arg2: [*c]JSC__ThrowScope, arg3: [*c]const u8, arg4: usize) bool; pub extern fn JSC__VM__whenIdle(arg0: [*c]JSC__VM, ArgFn1: ?fn (...) callconv(.C) void) void; @@ -399,4 +419,6 @@ pub extern fn WTF__StringView__length(arg0: [*c]const WTF__StringView) usize; pub extern fn Zig__GlobalObject__create(arg0: [*c]JSClassRef, arg1: i32, arg2: ?*anyopaque) [*c]JSC__JSGlobalObject; pub extern fn Zig__GlobalObject__getModuleRegistryMap(arg0: [*c]JSC__JSGlobalObject) ?*anyopaque; pub extern fn Zig__GlobalObject__resetModuleRegistryMap(arg0: [*c]JSC__JSGlobalObject, arg1: ?*anyopaque) bool; +pub extern fn Bun__Readable__create(arg0: [*c]Bun__Readable, arg1: [*c]JSC__JSGlobalObject) JSC__JSValue; +pub extern fn Bun__Writable__create(arg0: [*c]Bun__Writable, arg1: [*c]JSC__JSGlobalObject) JSC__JSValue; pub extern fn ZigException__fromException(arg0: [*c]JSC__Exception) ZigException; diff --git a/src/javascript/jsc/bindings/helpers.h b/src/javascript/jsc/bindings/helpers.h index 73582d1dc..1c1237969 100644 --- a/src/javascript/jsc/bindings/helpers.h +++ b/src/javascript/jsc/bindings/helpers.h @@ -1,3 +1,5 @@ +#pragma once + #include "headers.h" #include "root.h" @@ -10,8 +12,6 @@ #include <JavaScriptCore/ThrowScope.h> #include <JavaScriptCore/VM.h> -#pragma once - template <class CppType, typename ZigType> class Wrap { public: Wrap(){}; @@ -72,46 +72,90 @@ static const JSC::Identifier toIdentifier(ZigString str, JSC::JSGlobalObject *gl return JSC::Identifier::fromString(global->vm(), str.ptr, str.len); } +static bool isTaggedUTF16Ptr(const unsigned char *ptr) { + return (reinterpret_cast<uintptr_t>(ptr) & (static_cast<uint64_t>(1) << 63)) != 0; +} + +static bool isTaggedExternalPtr(const unsigned char *ptr) { + return (reinterpret_cast<uintptr_t>(ptr) & (static_cast<uint64_t>(1) << 62)) != 0; +} + static const WTF::String toString(ZigString str) { if (str.len == 0 || str.ptr == nullptr) { return WTF::String(); } - return WTF::String(WTF::StringImpl::createWithoutCopying(str.ptr, str.len)); + return !isTaggedUTF16Ptr(str.ptr) + ? WTF::String(WTF::StringImpl::createWithoutCopying(str.ptr, str.len)) + : WTF::String(WTF::StringImpl::createWithoutCopying( + reinterpret_cast<const UChar *>(str.ptr), str.len)); } static const WTF::String toStringCopy(ZigString str) { if (str.len == 0 || str.ptr == nullptr) { return WTF::String(); } - return WTF::String(WTF::StringImpl::create(str.ptr, str.len)); + return !isTaggedUTF16Ptr(str.ptr) ? WTF::String(WTF::StringImpl::create(str.ptr, str.len)) + : WTF::String(WTF::StringImpl::create( + reinterpret_cast<const UChar *>(str.ptr), str.len)); } static WTF::String toStringNotConst(ZigString str) { if (str.len == 0 || str.ptr == nullptr) { return WTF::String(); } - return WTF::String(WTF::StringImpl::createWithoutCopying(str.ptr, str.len)); + return !isTaggedUTF16Ptr(str.ptr) ? WTF::String(WTF::StringImpl::create(str.ptr, str.len)) + : WTF::String(WTF::StringImpl::create( + reinterpret_cast<const UChar *>(str.ptr), str.len)); } static const JSC::JSString *toJSString(ZigString str, JSC::JSGlobalObject *global) { return JSC::jsOwnedString(global->vm(), toString(str)); } +static const JSC::JSValue toJSStringValue(ZigString str, JSC::JSGlobalObject *global) { + return JSC::JSValue(toJSString(str, global)); +} + +static const JSC::JSString *toJSStringGC(ZigString str, JSC::JSGlobalObject *global) { + return JSC::jsString(global->vm(), toStringCopy(str)); +} + +static const JSC::JSValue toJSStringValueGC(ZigString str, JSC::JSGlobalObject *global) { + return JSC::JSValue(toJSString(str, global)); +} + static const ZigString ZigStringEmpty = ZigString{nullptr, 0}; static const unsigned char __dot_char = '.'; static const ZigString ZigStringCwd = ZigString{&__dot_char, 1}; +static const unsigned char *taggedUTF16Ptr(const UChar *ptr) { + return reinterpret_cast<const unsigned char *>(reinterpret_cast<uintptr_t>(ptr) | + (static_cast<uint64_t>(1) << 63)); +} + static ZigString toZigString(WTF::String str) { - return str.isEmpty() ? ZigStringEmpty : ZigString{str.characters8(), str.length()}; + return str.isEmpty() + ? ZigStringEmpty + : ZigString{str.is8Bit() ? str.characters8() : taggedUTF16Ptr(str.characters16()), + str.length()}; } static ZigString toZigString(WTF::String *str) { - return str->isEmpty() ? ZigStringEmpty : ZigString{str->characters8(), str->length()}; + return str->isEmpty() + ? ZigStringEmpty + : ZigString{str->is8Bit() ? str->characters8() : taggedUTF16Ptr(str->characters16()), + str->length()}; } static ZigString toZigString(WTF::StringImpl &str) { - return str.isEmpty() ? ZigStringEmpty : ZigString{str.characters8(), str.length()}; + return str.isEmpty() + ? ZigStringEmpty + : ZigString{str.is8Bit() ? str.characters8() : taggedUTF16Ptr(str.characters16()), + str.length()}; } static ZigString toZigString(WTF::StringView &str) { - return str.isEmpty() ? ZigStringEmpty : ZigString{str.characters8(), str.length()}; + return str.isEmpty() + ? ZigStringEmpty + : ZigString{str.is8Bit() ? str.characters8() : taggedUTF16Ptr(str.characters16()), + str.length()}; } static ZigString toZigString(JSC::JSString &str, JSC::JSGlobalObject *global) { @@ -152,4 +196,19 @@ static ZigString toZigString(JSC::JSValue val, JSC::JSGlobalObject *global) { return toZigString(str); } +static JSC::JSValue getErrorInstance(const ZigString *str, JSC__JSGlobalObject *globalObject) { + JSC::VM &vm = globalObject->vm(); + + auto scope = DECLARE_THROW_SCOPE(vm); + JSC::JSValue message = Zig::toJSString(*str, globalObject); + JSC::JSValue options = JSC::jsUndefined(); + JSC::Structure *errorStructure = globalObject->errorStructure(); + JSC::JSObject *result = + JSC::ErrorInstance::create(globalObject, errorStructure, message, options); + RETURN_IF_EXCEPTION(scope, JSC::JSValue()); + scope.release(); + + return JSC::JSValue(result); +} + }; // namespace Zig diff --git a/src/javascript/jsc/fs.exports.js b/src/javascript/jsc/fs.exports.js new file mode 100644 index 000000000..923ef9801 --- /dev/null +++ b/src/javascript/jsc/fs.exports.js @@ -0,0 +1,77 @@ +var fs = Bun.fs(); +export default fs; +export var access = fs.access.bind(fs); +export var appendFile = fs.appendFile.bind(fs); +export var close = fs.close.bind(fs); +export var copyFile = fs.copyFile.bind(fs); +export var exists = fs.exists.bind(fs); +export var chown = fs.chown.bind(fs); +export var chmod = fs.chmod.bind(fs); +export var fchmod = fs.fchmod.bind(fs); +export var fchown = fs.fchown.bind(fs); +export var fstat = fs.fstat.bind(fs); +export var fsync = fs.fsync.bind(fs); +export var ftruncate = fs.ftruncate.bind(fs); +export var futimes = fs.futimes.bind(fs); +export var lchmod = fs.lchmod.bind(fs); +export var lchown = fs.lchown.bind(fs); +export var link = fs.link.bind(fs); +export var lstat = fs.lstat.bind(fs); +export var mkdir = fs.mkdir.bind(fs); +export var mkdtemp = fs.mkdtemp.bind(fs); +export var open = fs.open.bind(fs); +export var read = fs.read.bind(fs); +export var write = fs.write.bind(fs); +export var readdir = fs.readdir.bind(fs); +export var readFile = fs.readFile.bind(fs); +export var writeFile = fs.writeFile.bind(fs); +export var readlink = fs.readlink.bind(fs); +export var realpath = fs.realpath.bind(fs); +export var rename = fs.rename.bind(fs); +export var stat = fs.stat.bind(fs); +export var symlink = fs.symlink.bind(fs); +export var truncate = fs.truncate.bind(fs); +export var unlink = fs.unlink.bind(fs); +export var utimes = fs.utimes.bind(fs); +export var lutimes = fs.lutimes.bind(fs); +export var accessSync = fs.accessSync.bind(fs); +export var appendFileSync = fs.appendFileSync.bind(fs); +export var closeSync = fs.closeSync.bind(fs); +export var copyFileSync = fs.copyFileSync.bind(fs); +export var existsSync = fs.existsSync.bind(fs); +export var chownSync = fs.chownSync.bind(fs); +export var chmodSync = fs.chmodSync.bind(fs); +export var fchmodSync = fs.fchmodSync.bind(fs); +export var fchownSync = fs.fchownSync.bind(fs); +export var fstatSync = fs.fstatSync.bind(fs); +export var fsyncSync = fs.fsyncSync.bind(fs); +export var ftruncateSync = fs.ftruncateSync.bind(fs); +export var futimesSync = fs.futimesSync.bind(fs); +export var lchmodSync = fs.lchmodSync.bind(fs); +export var lchownSync = fs.lchownSync.bind(fs); +export var linkSync = fs.linkSync.bind(fs); +export var lstatSync = fs.lstatSync.bind(fs); +export var mkdirSync = fs.mkdirSync.bind(fs); +export var mkdtempSync = fs.mkdtempSync.bind(fs); +export var openSync = fs.openSync.bind(fs); +export var readSync = fs.readSync.bind(fs); +export var writeSync = fs.writeSync.bind(fs); +export var readdirSync = fs.readdirSync.bind(fs); +export var readFileSync = fs.readFileSync.bind(fs); +export var writeFileSync = fs.writeFileSync.bind(fs); +export var readlinkSync = fs.readlinkSync.bind(fs); +export var realpathSync = fs.realpathSync.bind(fs); +export var renameSync = fs.renameSync.bind(fs); +export var statSync = fs.statSync.bind(fs); +export var symlinkSync = fs.symlinkSync.bind(fs); +export var truncateSync = fs.truncateSync.bind(fs); +export var unlinkSync = fs.unlinkSync.bind(fs); +export var utimesSync = fs.utimesSync.bind(fs); +export var lutimesSync = fs.lutimesSync.bind(fs); + +export var createReadStream = fs.createReadStream.bind(fs); +export var createWriteStream = fs.createWriteStream.bind(fs); + +// lol +realpath.native = realpath; +realpathSync.native = realpathSync; diff --git a/src/javascript/jsc/javascript.zig b/src/javascript/jsc/javascript.zig index d571def15..64147bc5c 100644 --- a/src/javascript/jsc/javascript.zig +++ b/src/javascript/jsc/javascript.zig @@ -36,7 +36,7 @@ const http = @import("../../http.zig"); const NodeFallbackModules = @import("../../node_fallbacks.zig"); const ImportKind = ast.ImportKind; const Analytics = @import("../../analytics/analytics_thread.zig"); -const ZigString = @import("javascript_core").ZigString; +const ZigString = @import("../../jsc.zig").ZigString; const Runtime = @import("../../runtime.zig"); const Router = @import("./api/router.zig"); const ImportRecord = ast.ImportRecord; @@ -44,36 +44,37 @@ const DotEnv = @import("../../env_loader.zig"); const ParseResult = @import("../../bundler.zig").ParseResult; const PackageJSON = @import("../../resolver/package_json.zig").PackageJSON; const MacroRemap = @import("../../resolver/package_json.zig").MacroMap; -const WebCore = @import("javascript_core").WebCore; +const WebCore = @import("../../jsc.zig").WebCore; const Request = WebCore.Request; const Response = WebCore.Response; const Headers = WebCore.Headers; const Fetch = WebCore.Fetch; const FetchEvent = WebCore.FetchEvent; -const js = @import("javascript_core").C; +const js = @import("../../jsc.zig").C; const JSError = @import("./base.zig").JSError; const d = @import("./base.zig").d; const MarkedArrayBuffer = @import("./base.zig").MarkedArrayBuffer; const getAllocator = @import("./base.zig").getAllocator; -const JSValue = @import("javascript_core").JSValue; +const JSValue = @import("../../jsc.zig").JSValue; const NewClass = @import("./base.zig").NewClass; -const Microtask = @import("javascript_core").Microtask; -const JSGlobalObject = @import("javascript_core").JSGlobalObject; -const ExceptionValueRef = @import("javascript_core").ExceptionValueRef; -const JSPrivateDataPtr = @import("javascript_core").JSPrivateDataPtr; -const ZigConsoleClient = @import("javascript_core").ZigConsoleClient; -const ZigException = @import("javascript_core").ZigException; -const ZigStackTrace = @import("javascript_core").ZigStackTrace; -const ErrorableResolvedSource = @import("javascript_core").ErrorableResolvedSource; -const ResolvedSource = @import("javascript_core").ResolvedSource; -const JSPromise = @import("javascript_core").JSPromise; -const JSInternalPromise = @import("javascript_core").JSInternalPromise; -const JSModuleLoader = @import("javascript_core").JSModuleLoader; -const JSPromiseRejectionOperation = @import("javascript_core").JSPromiseRejectionOperation; -const Exception = @import("javascript_core").Exception; -const ErrorableZigString = @import("javascript_core").ErrorableZigString; -const ZigGlobalObject = @import("javascript_core").ZigGlobalObject; -const VM = @import("javascript_core").VM; +const Microtask = @import("../../jsc.zig").Microtask; +const JSGlobalObject = @import("../../jsc.zig").JSGlobalObject; +const ExceptionValueRef = @import("../../jsc.zig").ExceptionValueRef; +const JSPrivateDataPtr = @import("../../jsc.zig").JSPrivateDataPtr; +const ZigConsoleClient = @import("../../jsc.zig").ZigConsoleClient; +const Node = @import("../../jsc.zig").Node; +const ZigException = @import("../../jsc.zig").ZigException; +const ZigStackTrace = @import("../../jsc.zig").ZigStackTrace; +const ErrorableResolvedSource = @import("../../jsc.zig").ErrorableResolvedSource; +const ResolvedSource = @import("../../jsc.zig").ResolvedSource; +const JSPromise = @import("../../jsc.zig").JSPromise; +const JSInternalPromise = @import("../../jsc.zig").JSInternalPromise; +const JSModuleLoader = @import("../../jsc.zig").JSModuleLoader; +const JSPromiseRejectionOperation = @import("../../jsc.zig").JSPromiseRejectionOperation; +const Exception = @import("../../jsc.zig").Exception; +const ErrorableZigString = @import("../../jsc.zig").ErrorableZigString; +const ZigGlobalObject = @import("../../jsc.zig").ZigGlobalObject; +const VM = @import("../../jsc.zig").VM; const Config = @import("./config.zig"); const URL = @import("../../query_string_map.zig").URL; pub const GlobalClasses = [_]type{ @@ -92,6 +93,8 @@ pub const GlobalClasses = [_]type{ Bun.EnvironmentVariables.Class, }; const Blob = @import("../../blob.zig"); +pub const Buffer = MarkedArrayBuffer; +const Lock = @import("../../lock.zig").Lock; pub const Bun = struct { threadlocal var css_imports_list_strings: [512]ZigString = undefined; @@ -183,22 +186,22 @@ pub const Bun = struct { pub fn getCWD( _: void, - _: js.JSContextRef, + ctx: js.JSContextRef, _: js.JSValueRef, _: js.JSStringRef, _: js.ExceptionRef, ) js.JSValueRef { - return ZigString.init(VirtualMachine.vm.bundler.fs.top_level_dir).toValue(VirtualMachine.vm.global).asRef(); + return ZigString.init(VirtualMachine.vm.bundler.fs.top_level_dir).toValue(ctx.ptr()).asRef(); } pub fn getOrigin( _: void, - _: js.JSContextRef, + ctx: js.JSContextRef, _: js.JSValueRef, _: js.JSStringRef, _: js.ExceptionRef, ) js.JSValueRef { - return ZigString.init(VirtualMachine.vm.origin.origin).toValue(VirtualMachine.vm.global).asRef(); + return ZigString.init(VirtualMachine.vm.origin.origin).toValue(ctx.ptr()).asRef(); } pub fn enableANSIColors( @@ -212,22 +215,22 @@ pub const Bun = struct { } pub fn getMain( _: void, - _: js.JSContextRef, + ctx: js.JSContextRef, _: js.JSValueRef, _: js.JSStringRef, _: js.ExceptionRef, ) js.JSValueRef { - return ZigString.init(VirtualMachine.vm.main).toValue(VirtualMachine.vm.global).asRef(); + return ZigString.init(VirtualMachine.vm.main).toValue(ctx.ptr()).asRef(); } pub fn getAssetPrefix( _: void, - _: js.JSContextRef, + ctx: js.JSContextRef, _: js.JSValueRef, _: js.JSStringRef, _: js.ExceptionRef, ) js.JSValueRef { - return ZigString.init(VirtualMachine.vm.bundler.options.routes.asset_prefix_path).toValue(VirtualMachine.vm.global).asRef(); + return ZigString.init(VirtualMachine.vm.bundler.options.routes.asset_prefix_path).toValue(ctx.ptr()).asRef(); } pub fn getArgv( @@ -249,7 +252,7 @@ pub const Bun = struct { argv[i] = ZigString.init(std.mem.span(arg)); } - return JSValue.createStringArray(VirtualMachine.vm.global, argv.ptr, argv.len).asObjectRef(); + return JSValue.createStringArray(ctx.ptr(), argv.ptr, argv.len, true).asObjectRef(); } pub fn getRoutesDir( @@ -263,7 +266,7 @@ pub const Bun = struct { return js.JSValueMakeUndefined(ctx); } - return ZigString.init(VirtualMachine.vm.bundler.options.routes.dir).toValue(VirtualMachine.vm.global).asRef(); + return ZigString.init(VirtualMachine.vm.bundler.options.routes.dir).toValue(ctx.ptr()).asRef(); } pub fn getFilePath(ctx: js.JSContextRef, arguments: []const js.JSValueRef, buf: []u8, exception: js.ExceptionRef) ?string { @@ -275,7 +278,7 @@ pub const Bun = struct { const value = arguments[0]; if (js.JSValueIsString(ctx, value)) { var out = ZigString.Empty; - JSValue.toZigString(JSValue.fromRef(value), &out, VirtualMachine.vm.global); + JSValue.toZigString(JSValue.fromRef(value), &out, ctx.ptr()); var out_slice = out.slice(); // The dots are kind of unnecessary. They'll be normalized. @@ -298,7 +301,7 @@ pub const Bun = struct { } } - var iter = JSValue.fromRef(value).arrayIterator(VirtualMachine.vm.global); + var iter = JSValue.fromRef(value).arrayIterator(ctx.ptr()); while (iter.next()) |item| { if (temp_strings_list_len >= temp_strings_list.len) { break; @@ -310,7 +313,7 @@ pub const Bun = struct { } var out = ZigString.Empty; - JSValue.toZigString(item, &out, VirtualMachine.vm.global); + JSValue.toZigString(item, &out, ctx.ptr()); const out_slice = out.slice(); temp_strings_list[temp_strings_list_len] = out_slice; @@ -348,7 +351,7 @@ pub const Bun = struct { return js.JSObjectMakeArray(ctx, 0, null, null); } - return JSValue.createStringArray(VirtualMachine.vm.global, styles.ptr, styles.len).asRef(); + return JSValue.createStringArray(ctx.ptr(), styles.ptr, styles.len, true).asRef(); } pub fn readFileAsStringCallback( @@ -450,7 +453,7 @@ pub const Bun = struct { routes_list_strings[i] = ZigString.init(list[i]); } - const ref = JSValue.createStringArray(VirtualMachine.vm.global, &routes_list_strings, list.len).asRef(); + const ref = JSValue.createStringArray(ctx.ptr(), &routes_list_strings, list.len, true).asRef(); return ref; } @@ -471,7 +474,7 @@ pub const Bun = struct { routes_list_strings[i] = ZigString.init(list[i]); } - const ref = JSValue.createStringArray(VirtualMachine.vm.global, &routes_list_strings, list.len).asRef(); + const ref = JSValue.createStringArray(ctx.ptr(), &routes_list_strings, list.len, true).asRef(); return ref; } @@ -534,32 +537,85 @@ pub const Bun = struct { _: js.ExceptionRef, ) js.JSValueRef { if (js.JSValueIsNumber(ctx, arguments[0])) { - const ms = JSValue.fromRef(arguments[0]).asNumber(); - if (ms > 0 and std.math.isFinite(ms)) std.time.sleep(@floatToInt(u64, @floor(@floatCast(f128, ms) * std.time.ns_per_ms))); + const seconds = JSValue.fromRef(arguments[0]).asNumber(); + if (seconds > 0 and std.math.isFinite(seconds)) std.time.sleep(@floatToInt(u64, seconds * 1000) * std.time.ns_per_ms); } return js.JSValueMakeUndefined(ctx); } + pub fn createNodeFS( + _: void, + ctx: js.JSContextRef, + _: js.JSObjectRef, + _: js.JSObjectRef, + _: []const js.JSValueRef, + _: js.ExceptionRef, + ) js.JSValueRef { + return Node.NodeFSBindings.make( + ctx, + VirtualMachine.vm.node_fs orelse brk: { + VirtualMachine.vm.node_fs = _global.default_allocator.create(Node.NodeFS) catch unreachable; + VirtualMachine.vm.node_fs.?.* = Node.NodeFS{ .async_io = undefined }; + break :brk VirtualMachine.vm.node_fs.?; + }, + ); + } + + pub fn generateHeapSnapshot( + _: void, + ctx: js.JSContextRef, + _: js.JSObjectRef, + _: js.JSObjectRef, + _: []const js.JSValueRef, + _: js.ExceptionRef, + ) js.JSValueRef { + return ctx.ptr().generateHeapSnapshot().asObjectRef(); + } + + pub fn runGC( + _: void, + ctx: js.JSContextRef, + _: js.JSObjectRef, + _: js.JSObjectRef, + arguments: []const js.JSValueRef, + _: js.ExceptionRef, + ) js.JSValueRef { + Global.mimalloc_cleanup(true); + return ctx.ptr().vm().runGC(arguments.len > 0 and JSValue.fromRef(arguments[0]).toBoolean()).asRef(); + } + + pub fn shrink( + _: void, + ctx: js.JSContextRef, + _: js.JSObjectRef, + _: js.JSObjectRef, + _: []const js.JSValueRef, + _: js.ExceptionRef, + ) js.JSValueRef { + ctx.ptr().vm().shrinkFootprint(); + return JSValue.jsUndefined().asRef(); + } + var public_path_temp_str: [std.fs.MAX_PATH_BYTES]u8 = undefined; pub fn getPublicPathJS( _: void, - _: js.JSContextRef, + ctx: js.JSContextRef, _: js.JSObjectRef, _: js.JSObjectRef, arguments: []const js.JSValueRef, _: js.ExceptionRef, ) js.JSValueRef { var zig_str: ZigString = ZigString.Empty; - JSValue.toZigString(JSValue.fromRef(arguments[0]), &zig_str, VirtualMachine.vm.global); + JSValue.toZigString(JSValue.fromRef(arguments[0]), &zig_str, ctx.ptr()); const to = zig_str.slice(); var stream = std.io.fixedBufferStream(&public_path_temp_str); var writer = stream.writer(); getPublicPath(to, VirtualMachine.vm.origin, @TypeOf(&writer), &writer); - return ZigString.init(stream.buffer[0..stream.pos]).toValueGC(VirtualMachine.vm.global).asRef(); + return ZigString.init(stream.buffer[0..stream.pos]).toValueGC(ctx.ptr()).asRef(); } pub const Class = NewClass( @@ -579,6 +635,9 @@ pub const Bun = struct { .rfn = Router.match, .ts = Router.match_type_definition, }, + .__debug__doSegfault = .{ + .rfn = Bun.__debug__doSegfault, + }, .sleepSync = .{ .rfn = sleepSync, }, @@ -635,6 +694,26 @@ pub const Bun = struct { .@"return" = "undefined", }, }, + .fs = .{ + .rfn = Bun.createNodeFS, + .ts = d.ts{}, + }, + .jest = .{ + .rfn = @import("./test/jest.zig").Jest.call, + .ts = d.ts{}, + }, + .gc = .{ + .rfn = Bun.runGC, + .ts = d.ts{}, + }, + .generateHeapSnapshot = .{ + .rfn = Bun.generateHeapSnapshot, + .ts = d.ts{}, + }, + .shrink = .{ + .rfn = Bun.shrink, + .ts = d.ts{}, + }, }, .{ .main = .{ @@ -670,6 +749,21 @@ pub const Bun = struct { }, ); + // For testing the segfault handler + pub fn __debug__doSegfault( + _: void, + ctx: js.JSContextRef, + _: js.JSObjectRef, + _: js.JSObjectRef, + _: []const js.JSValueRef, + _: js.ExceptionRef, + ) js.JSValueRef { + _ = ctx; + var seggy: *VirtualMachine = undefined; + seggy.printErrorInstance(undefined, undefined, false) catch unreachable; + return JSValue.jsUndefined().asRef(); + } + /// EnvironmentVariables is runtime defined. /// Also, you can't iterate over process.env normally since it only exists at build-time otherwise // This is aliased to Bun.env @@ -684,12 +778,23 @@ pub const Bun = struct { .getProperty = .{ .rfn = getProperty, }, - // .hasProperty = .{ - // .rfn = hasProperty, - // }, + .setProperty = .{ + .rfn = setProperty, + }, + .deleteProperty = .{ + .rfn = deleteProperty, + }, + .convertToType = .{ .rfn = convertToType }, + .hasProperty = .{ + .rfn = hasProperty, + }, .getPropertyNames = .{ .rfn = getPropertyNames, }, + .toJSON = .{ + .rfn = toJSON, + .name = "toJSON", + }, }, .{}, ); @@ -719,19 +824,87 @@ pub const Bun = struct { var ptr = js.JSStringGetCharacters8Ptr(propertyName); var name = ptr[0..len]; if (VirtualMachine.vm.bundler.env.map.get(name)) |value| { - return ZigString.toRef(value, VirtualMachine.vm.global); + return ZigString.toRef(value, ctx.ptr()); } if (Output.enable_ansi_colors) { // https://github.com/chalk/supports-color/blob/main/index.js if (strings.eqlComptime(name, "FORCE_COLOR")) { - return ZigString.toRef(BooleanString.@"true", VirtualMachine.vm.global); + return ZigString.toRef(BooleanString.@"true", ctx.ptr()); } } return js.JSValueMakeUndefined(ctx); } + pub fn toJSON( + _: void, + ctx: js.JSContextRef, + _: js.JSObjectRef, + _: js.JSObjectRef, + _: []const js.JSValueRef, + _: js.ExceptionRef, + ) js.JSValueRef { + var map = VirtualMachine.vm.bundler.env.map.map; + var keys = map.keys(); + var values = map.values(); + const StackFallback = std.heap.StackFallbackAllocator(32 * 2 * @sizeOf(ZigString)); + var stack = StackFallback{ + .buffer = undefined, + .fallback_allocator = _global.default_allocator, + .fixed_buffer_allocator = undefined, + }; + var allocator = stack.get(); + var key_strings_ = allocator.alloc(ZigString, keys.len * 2) catch unreachable; + var key_strings = key_strings_[0..keys.len]; + var value_strings = key_strings_[keys.len..]; + + for (keys) |key, i| { + key_strings[i] = ZigString.init(key); + key_strings[i].detectEncoding(); + value_strings[i] = ZigString.init(values[i]); + value_strings[i].detectEncoding(); + } + + var result = JSValue.fromEntries(ctx.ptr(), key_strings.ptr, value_strings.ptr, keys.len, false).asObjectRef(); + allocator.free(key_strings_); + return result; + // } + // ZigConsoleClient.Formatter.format(this: *Formatter, result: Tag.Result, comptime Writer: type, writer: Writer, value: JSValue, globalThis: *JSGlobalObject, comptime enable_ansi_colors: bool) + } + + pub fn deleteProperty( + _: js.JSContextRef, + _: js.JSObjectRef, + propertyName: js.JSStringRef, + _: js.ExceptionRef, + ) callconv(.C) bool { + const len = js.JSStringGetLength(propertyName); + var ptr = js.JSStringGetCharacters8Ptr(propertyName); + var name = ptr[0..len]; + _ = VirtualMachine.vm.bundler.env.map.map.swapRemove(name); + return true; + } + + pub fn setProperty( + ctx: js.JSContextRef, + _: js.JSObjectRef, + propertyName: js.JSStringRef, + value: js.JSValueRef, + exception: js.ExceptionRef, + ) callconv(.C) bool { + const len = js.JSStringGetLength(propertyName); + var ptr = js.JSStringGetCharacters8Ptr(propertyName); + var name = ptr[0..len]; + var val = ZigString.init(""); + JSValue.fromRef(value).toZigString(&val, ctx.ptr()); + if (exception.* != null) return false; + var result = std.fmt.allocPrint(VirtualMachine.vm.allocator, "{}", .{val}) catch unreachable; + VirtualMachine.vm.bundler.env.map.put(name, result) catch unreachable; + + return true; + } + pub fn hasProperty( _: js.JSContextRef, _: js.JSObjectRef, @@ -743,6 +916,14 @@ pub const Bun = struct { return VirtualMachine.vm.bundler.env.map.get(name) != null or (Output.enable_ansi_colors and strings.eqlComptime(name, "FORCE_COLOR")); } + pub fn convertToType(ctx: js.JSContextRef, obj: js.JSObjectRef, kind: js.JSType, exception: js.ExceptionRef) callconv(.C) js.JSValueRef { + _ = ctx; + _ = obj; + _ = kind; + _ = exception; + return obj; + } + pub fn getPropertyNames( _: js.JSContextRef, _: js.JSObjectRef, @@ -758,6 +939,16 @@ pub const Bun = struct { }; }; +pub const OpaqueCallback = fn (current: ?*anyopaque) callconv(.C) void; +pub fn OpaqueWrap(comptime Context: type, comptime Function: fn (this: *Context) void) OpaqueCallback { + return struct { + pub fn callback(ctx: ?*anyopaque) callconv(.C) void { + var context: *Context = @ptrCast(*Context, @alignCast(@alignOf(Context), ctx.?)); + @call(.{}, Function, .{context}); + } + }.callback; +} + pub const Performance = struct { pub const Class = NewClass( void, @@ -801,6 +992,7 @@ const TaggedPointerUnion = @import("../../tagged_pointer.zig").TaggedPointerUnio pub const Task = TaggedPointerUnion(.{ FetchTasklet, Microtask, + // TimeoutTasklet, }); // If you read JavascriptCore/API/JSVirtualMachine.mm - https://github.com/WebKit/WebKit/blob/acff93fb303baa670c055cb24c2bad08691a01a0/Source/JavaScriptCore/API/JSVirtualMachine.mm#L101 @@ -817,10 +1009,11 @@ pub const VirtualMachine = struct { event_listeners: EventListenerMixin.Map, main: string = "", process: js.JSObjectRef = null, - blobs: *Blob.Group = undefined, + blobs: ?*Blob.Group = null, flush_list: std.ArrayList(string), entry_point: ServerEntryPoint = undefined, origin: URL = URL{}, + node_fs: ?*Node.NodeFS = null, arena: *std.heap.ArenaAllocator = undefined, has_loaded: bool = false, @@ -834,79 +1027,108 @@ pub const VirtualMachine = struct { macro_mode: bool = false, has_any_macro_remappings: bool = false, + is_from_devserver: bool = false, + has_enabled_macro_mode: bool = false, + argv: []const []const u8 = &[_][]const u8{"bun"}, origin_timer: std.time.Timer = undefined, macro_event_loop: EventLoop = EventLoop{}, regular_event_loop: EventLoop = EventLoop{}, + event_loop: *EventLoop = undefined, pub inline fn eventLoop(this: *VirtualMachine) *EventLoop { - return if (this.macro_mode) - return &this.macro_event_loop - else - return &this.regular_event_loop; + return this.event_loop; } const EventLoop = struct { ready_tasks_count: std.atomic.Atomic(u32) = std.atomic.Atomic(u32).init(0), pending_tasks_count: std.atomic.Atomic(u32) = std.atomic.Atomic(u32).init(0), - tasks: std.ArrayList(Task) = std.ArrayList(Task).init(default_allocator), + io_tasks_count: std.atomic.Atomic(u32) = std.atomic.Atomic(u32).init(0), + tasks: Queue = undefined, + concurrent_tasks: Queue = undefined, + concurrent_lock: Lock = Lock.init(), + pub const Queue = std.fifo.LinearFifo(Task, .Dynamic); pub fn tickWithCount(this: *EventLoop) u32 { var finished: u32 = 0; - var i: usize = 0; var global = VirtualMachine.vm.global; - while (i < this.tasks.items.len) { - var task: Task = this.tasks.items[i]; + while (this.tasks.readItem()) |task| { switch (task.tag()) { .Microtask => { - var micro: *Microtask = task.get(Microtask).?; - _ = this.tasks.swapRemove(i); - _ = this.pending_tasks_count.fetchSub(1, .Monotonic); + var micro: *Microtask = task.as(Microtask); micro.run(global); - finished += 1; - continue; }, .FetchTasklet => { var fetch_task: *Fetch.FetchTasklet = task.get(Fetch.FetchTasklet).?; - if (fetch_task.status == .done) { - _ = this.ready_tasks_count.fetchSub(1, .Monotonic); - _ = this.pending_tasks_count.fetchSub(1, .Monotonic); - _ = this.tasks.swapRemove(i); - fetch_task.onDone(); - finished += 1; - continue; - } + fetch_task.onDone(); + finished += 1; }, else => unreachable, } - i += 1; } + + if (finished > 0) { + _ = this.pending_tasks_count.fetchSub(finished, .Monotonic); + } + return finished; } + pub fn tickConcurrent(this: *EventLoop) void { + if (this.ready_tasks_count.load(.Monotonic) > 0) { + this.concurrent_lock.lock(); + defer this.concurrent_lock.unlock(); + var add: u32 = 0; + + // TODO: optimzie + this.tasks.ensureUnusedCapacity(this.concurrent_tasks.readableLength()) catch unreachable; + while (this.concurrent_tasks.readItem()) |task| { + this.tasks.writeItemAssumeCapacity(task); + } + _ = this.pending_tasks_count.fetchAdd(add, .Monotonic); + _ = this.ready_tasks_count.fetchSub(add, .Monotonic); + } + } pub fn tick(this: *EventLoop) void { + this.tickConcurrent(); + while (this.tickWithCount() > 0) {} } pub fn waitForTasks(this: *EventLoop) void { - while (this.pending_tasks_count.load(.Monotonic) > 0 or this.ready_tasks_count.load(.Monotonic) > 0) { + this.tickConcurrent(); + + while (this.pending_tasks_count.load(.Monotonic) > 0) { while (this.tickWithCount() > 0) {} } } - pub fn enqueueTask(this: *EventLoop, task: Task) !void { + pub fn enqueueTask(this: *EventLoop, task: Task) void { _ = this.pending_tasks_count.fetchAdd(1, .Monotonic); - try this.tasks.append(task); + this.tasks.writeItem(task) catch unreachable; + } + + pub fn enqueueTaskConcurrent(this: *EventLoop, task: Task) void { + this.concurrent_lock.lock(); + defer this.concurrent_lock.unlock(); + this.concurrent_tasks.writeItem(task) catch unreachable; + _ = this.ready_tasks_count.fetchAdd(1, .Monotonic); } }; - pub inline fn enqueueTask(this: *VirtualMachine, task: Task) !void { - try this.eventLoop().enqueueTask(task); + pub inline fn enqueueTask(this: *VirtualMachine, task: Task) void { + this.eventLoop().enqueueTask(task); + } + + pub inline fn enqueueTaskConcurrent(this: *VirtualMachine, task: Task) void { + this.eventLoop().enqueueTaskConcurrent(task); } pub fn tick(this: *VirtualMachine) void { + this.eventLoop().tickConcurrent(); + while (this.eventLoop().tickWithCount() > 0) {} } @@ -920,9 +1142,16 @@ pub const VirtualMachine = struct { pub threadlocal var vm: *VirtualMachine = undefined; pub fn enableMacroMode(this: *VirtualMachine) void { + if (!this.has_enabled_macro_mode) { + this.has_enabled_macro_mode = true; + this.macro_event_loop.tasks = EventLoop.Queue.init(default_allocator); + this.macro_event_loop.concurrent_tasks = EventLoop.Queue.init(default_allocator); + } + this.bundler.options.platform = .bun_macro; this.bundler.resolver.caches.fs.is_macro_mode = true; this.macro_mode = true; + this.event_loop = &this.macro_event_loop; Analytics.Features.macros = true; } @@ -930,6 +1159,7 @@ pub const VirtualMachine = struct { this.bundler.options.platform = .bun; this.bundler.resolver.caches.fs.is_macro_mode = false; this.macro_mode = false; + this.event_loop = &this.regular_event_loop; } pub fn init( @@ -967,13 +1197,18 @@ pub const VirtualMachine = struct { .node_modules = bundler.options.node_modules_bundle, .log = log, .flush_list = std.ArrayList(string).init(allocator), - .blobs = try Blob.Group.init(allocator), + .blobs = if (_args.serve orelse false) try Blob.Group.init(allocator) else null, .origin = bundler.options.origin, .macros = MacroMap.init(allocator), .macro_entry_points = @TypeOf(VirtualMachine.vm.macro_entry_points).init(allocator), .origin_timer = std.time.Timer.start() catch @panic("Please don't mess with timers."), }; + + VirtualMachine.vm.regular_event_loop.tasks = EventLoop.Queue.init(default_allocator); + VirtualMachine.vm.regular_event_loop.concurrent_tasks = EventLoop.Queue.init(default_allocator); + VirtualMachine.vm.event_loop = &VirtualMachine.vm.regular_event_loop; + vm.bundler.macro_context = null; VirtualMachine.vm.bundler.configureLinker(); @@ -1017,7 +1252,7 @@ pub const VirtualMachine = struct { pub fn preflush(this: *VirtualMachine) void { // We flush on the next tick so that if there were any errors you can still see them - this.blobs.temporary.reset() catch {}; + this.blobs.?.temporary.reset() catch {}; } pub fn flush(this: *VirtualMachine) void { @@ -1031,13 +1266,12 @@ pub const VirtualMachine = struct { } inline fn _fetch( - global: *JSGlobalObject, + _: *JSGlobalObject, _specifier: string, _: string, log: *logger.Log, ) !ResolvedSource { std.debug.assert(VirtualMachine.vm_loaded); - std.debug.assert(VirtualMachine.vm.global == global); if (vm.node_modules != null and strings.eqlComptime(_specifier, bun_file_import_path)) { // We kind of need an abstraction around this. @@ -1145,6 +1379,15 @@ pub const VirtualMachine = struct { .bytecodecache_fd = 0, }; } + } else if (strings.eqlComptime(_specifier, "node:fs")) { + return ResolvedSource{ + .allocator = null, + .source_code = ZigString.init(@embedFile("fs.exports.js")), + .specifier = ZigString.init("node:fs"), + .source_url = ZigString.init("node:fs"), + .hash = 0, + .bytecodecache_fd = 0, + }; } const specifier = normalizeSpecifier(_specifier); @@ -1282,14 +1525,13 @@ pub const VirtualMachine = struct { path: string, }; - fn _resolve(ret: *ResolveFunctionResult, global: *JSGlobalObject, specifier: string, source: string) !void { + fn _resolve(ret: *ResolveFunctionResult, _: *JSGlobalObject, specifier: string, source: string) !void { std.debug.assert(VirtualMachine.vm_loaded); - std.debug.assert(VirtualMachine.vm.global == global); if (vm.node_modules == null and strings.eqlComptime(std.fs.path.basename(specifier), Runtime.Runtime.Imports.alt_name)) { ret.path = Runtime.Runtime.Imports.Name; return; - } else if (vm.node_modules != null and strings.eql(specifier, bun_file_import_path)) { + } else if (vm.node_modules != null and strings.eqlComptime(specifier, bun_file_import_path)) { ret.path = bun_file_import_path; return; } else if (strings.eqlComptime(specifier, main_file_name)) { @@ -1304,6 +1546,10 @@ pub const VirtualMachine = struct { ret.result = null; ret.path = specifier; return; + } else if (strings.eqlComptime(specifier, "fs") or strings.eqlComptime(specifier, "node:fs")) { + ret.result = null; + ret.path = "node:fs"; + return; } const is_special_source = strings.eqlComptime(source, main_file_name) or js_ast.Macro.isMacroPath(source); @@ -1370,13 +1616,12 @@ pub const VirtualMachine = struct { ret.path = result_path.text; } pub fn queueMicrotaskToEventLoop( - global: *JSGlobalObject, + _: *JSGlobalObject, microtask: *Microtask, ) void { std.debug.assert(VirtualMachine.vm_loaded); - std.debug.assert(VirtualMachine.vm.global == global); - vm.enqueueTask(Task.init(microtask)) catch unreachable; + vm.enqueueTask(Task.init(microtask)); } pub fn resolve(res: *ErrorableZigString, global: *JSGlobalObject, specifier: ZigString, source: ZigString) void { var result = ResolveFunctionResult{ .path = "", .result = null }; @@ -1403,7 +1648,7 @@ pub const VirtualMachine = struct { }; { - res.* = ErrorableZigString.err(err, @ptrCast(*anyopaque, ResolveError.create(vm.allocator, msg, source.slice()))); + res.* = ErrorableZigString.err(err, @ptrCast(*anyopaque, ResolveError.create(global, vm.allocator, msg, source.slice()))); } return; @@ -1412,6 +1657,8 @@ pub const VirtualMachine = struct { res.* = ErrorableZigString.ok(ZigString.init(result.path)); } pub fn normalizeSpecifier(slice_: string) string { + var vm_ = VirtualMachine.vm; + var slice = slice_; if (slice.len == 0) return slice; var was_http = false; @@ -1425,23 +1672,23 @@ pub const VirtualMachine = struct { was_http = true; } - if (strings.hasPrefix(slice, VirtualMachine.vm.origin.host)) { - slice = slice[VirtualMachine.vm.origin.host.len..]; + if (strings.hasPrefix(slice, vm_.origin.host)) { + slice = slice[vm_.origin.host.len..]; } else if (was_http) { if (strings.indexOfChar(slice, '/')) |i| { slice = slice[i..]; } } - if (VirtualMachine.vm.origin.path.len > 1) { - if (strings.hasPrefix(slice, VirtualMachine.vm.origin.path)) { - slice = slice[VirtualMachine.vm.origin.path.len..]; + if (vm_.origin.path.len > 1) { + if (strings.hasPrefix(slice, vm_.origin.path)) { + slice = slice[vm_.origin.path.len..]; } } - if (VirtualMachine.vm.bundler.options.routes.asset_prefix_path.len > 0) { - if (strings.hasPrefix(slice, VirtualMachine.vm.bundler.options.routes.asset_prefix_path)) { - slice = slice[VirtualMachine.vm.bundler.options.routes.asset_prefix_path.len..]; + if (vm_.bundler.options.routes.asset_prefix_path.len > 0) { + if (strings.hasPrefix(slice, vm_.bundler.options.routes.asset_prefix_path)) { + slice = slice[vm_.bundler.options.routes.asset_prefix_path.len..]; } } @@ -1460,12 +1707,12 @@ pub const VirtualMachine = struct { var log = logger.Log.init(vm.bundler.allocator); const spec = specifier.slice(); const result = _fetch(global, spec, source.slice(), &log) catch |err| { - processFetchLog(specifier, source, &log, ret, err); + processFetchLog(global, specifier, source, &log, ret, err); return; }; if (log.errors > 0) { - processFetchLog(specifier, source, &log, ret, error.LinkError); + processFetchLog(global, specifier, source, &log, ret, error.LinkError); return; } @@ -1488,30 +1735,32 @@ pub const VirtualMachine = struct { ret.result.value = result; - const specifier_blob = brk: { - if (strings.startsWith(spec, VirtualMachine.vm.bundler.fs.top_level_dir)) { - break :brk spec[VirtualMachine.vm.bundler.fs.top_level_dir.len..]; - } - break :brk spec; - }; + if (vm.blobs) |blobs| { + const specifier_blob = brk: { + if (strings.hasPrefix(spec, VirtualMachine.vm.bundler.fs.top_level_dir)) { + break :brk spec[VirtualMachine.vm.bundler.fs.top_level_dir.len..]; + } + break :brk spec; + }; - if (vm.has_loaded) { - vm.blobs.temporary.put(specifier_blob, .{ .ptr = result.source_code.ptr, .len = result.source_code.len }) catch {}; - } else { - vm.blobs.persistent.put(specifier_blob, .{ .ptr = result.source_code.ptr, .len = result.source_code.len }) catch {}; + if (vm.has_loaded) { + blobs.temporary.put(specifier_blob, .{ .ptr = result.source_code.ptr, .len = result.source_code.len }) catch {}; + } else { + blobs.persistent.put(specifier_blob, .{ .ptr = result.source_code.ptr, .len = result.source_code.len }) catch {}; + } } ret.success = true; } - fn processFetchLog(specifier: ZigString, referrer: ZigString, log: *logger.Log, ret: *ErrorableResolvedSource, err: anyerror) void { + fn processFetchLog(globalThis: *JSGlobalObject, specifier: ZigString, referrer: ZigString, log: *logger.Log, ret: *ErrorableResolvedSource, err: anyerror) void { switch (log.msgs.items.len) { 0 => { const msg = logger.Msg{ .data = logger.rangeData(null, logger.Range.None, std.fmt.allocPrint(vm.allocator, "{s} while building {s}", .{ @errorName(err), specifier.slice() }) catch unreachable), }; { - ret.* = ErrorableResolvedSource.err(err, @ptrCast(*anyopaque, BuildError.create(vm.bundler.allocator, msg))); + ret.* = ErrorableResolvedSource.err(err, @ptrCast(*anyopaque, BuildError.create(globalThis, vm.bundler.allocator, msg))); } return; }, @@ -1519,8 +1768,9 @@ pub const VirtualMachine = struct { 1 => { const msg = log.msgs.items[0]; ret.* = ErrorableResolvedSource.err(err, switch (msg.metadata) { - .build => BuildError.create(vm.bundler.allocator, msg).?, + .build => BuildError.create(globalThis, vm.bundler.allocator, msg).?, .resolve => ResolveError.create( + globalThis, vm.bundler.allocator, msg, referrer.slice(), @@ -1529,12 +1779,13 @@ pub const VirtualMachine = struct { return; }, else => { - var errors = errors_stack[0..std.math.min(log.msgs.items.len, errors_stack.len)]; + var errors = errors_stack[0..@minimum(log.msgs.items.len, errors_stack.len)]; for (log.msgs.items) |msg, i| { errors[i] = switch (msg.metadata) { - .build => BuildError.create(vm.bundler.allocator, msg).?, + .build => BuildError.create(globalThis, vm.bundler.allocator, msg).?, .resolve => ResolveError.create( + globalThis, vm.bundler.allocator, msg, referrer.slice(), @@ -1544,13 +1795,17 @@ pub const VirtualMachine = struct { ret.* = ErrorableResolvedSource.err( err, - vm.global.createAggregateError( + globalThis.createAggregateError( errors.ptr, @intCast(u16, errors.len), - &ZigString.init(std.fmt.allocPrint(vm.bundler.allocator, "{d} errors building \"{s}\"", .{ errors.len, specifier.slice() }) catch unreachable), + &ZigString.init( + std.fmt.allocPrint(vm.bundler.allocator, "{d} errors building \"{s}\"", .{ + errors.len, + specifier.slice(), + }) catch unreachable, + ), ).asVoid(), ); - return; }, } } @@ -1624,9 +1879,35 @@ pub const VirtualMachine = struct { } var entry_point = entry_point_entry.value_ptr.*; + var loader = MacroEntryPointLoader{ + .path = entry_point.source.path.text, + }; + + this.runWithAPILock(MacroEntryPointLoader, &loader, MacroEntryPointLoader.load); + return loader.promise; + } + + /// A subtlelty of JavaScriptCore: + /// JavaScriptCore has many release asserts that check an API lock is currently held + /// We cannot hold it from Zig code because it relies on C++ ARIA to automatically release the lock + /// 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, OpaqueWrap(Context, function)); + } + + const MacroEntryPointLoader = struct { + path: string, + promise: *JSInternalPromise = undefined, + pub fn load(this: *MacroEntryPointLoader) void { + this.promise = vm._loadMacroEntryPoint(this.path); + } + }; + + pub inline fn _loadMacroEntryPoint(this: *VirtualMachine, entry_path: string) *JSInternalPromise { var promise: *JSInternalPromise = undefined; - promise = JSModuleLoader.loadAndEvaluateModule(this.global, &ZigString.init(entry_point.source.path.text)); + promise = JSModuleLoader.loadAndEvaluateModule(this.global, &ZigString.init(entry_path)); this.tick(); @@ -1721,6 +2002,7 @@ pub const VirtualMachine = struct { if (!build_error.logged) { var writer = Output.errorWriter(); build_error.msg.formatWriter(@TypeOf(writer), writer, allow_ansi_color) catch {}; + writer.writeAll("\n") catch {}; build_error.logged = true; } this.had_errors = this.had_errors or build_error.msg.kind == .err; @@ -1768,6 +2050,8 @@ pub const VirtualMachine = struct { const stack = trace.frames(); if (stack.len > 0) { var i: i16 = 0; + const origin: ?*const URL = if (vm.is_from_devserver) &vm.origin else null; + const dir = vm.bundler.fs.top_level_dir; while (i < stack.len) : (i += 1) { const frame = stack[@intCast(usize, i)]; @@ -1785,8 +2069,8 @@ pub const VirtualMachine = struct { allow_ansi_colors, ), frame.sourceURLFormatter( - vm.bundler.fs.top_level_dir, - &vm.origin, + dir, + origin, allow_ansi_colors, ), }, @@ -1879,8 +2163,8 @@ pub const VirtualMachine = struct { ) catch unreachable; } - const name = exception.name.slice(); - const message = exception.message.slice(); + const name = exception.name; + const message = exception.message; var did_print_name = false; if (source_lines.next()) |source| { if (source.text.len > 0 and exception.stack.frames()[0].position.isInvalid()) { @@ -1898,14 +2182,14 @@ pub const VirtualMachine = struct { ) catch unreachable; if (name.len > 0 and message.len > 0) { - writer.print(comptime Output.prettyFmt(" <r><red><b>{s}<r><d>:<r> <b>{s}<r>\n", allow_ansi_color), .{ + writer.print(comptime Output.prettyFmt(" <r><red><b>{}<r><d>:<r> <b>{}<r>\n", allow_ansi_color), .{ name, message, }) catch unreachable; } else if (name.len > 0) { - writer.print(comptime Output.prettyFmt(" <r><b>{s}<r>\n", allow_ansi_color), .{name}) catch unreachable; + writer.print(comptime Output.prettyFmt(" <r><b>{}<r>\n", allow_ansi_color), .{name}) catch unreachable; } else if (message.len > 0) { - writer.print(comptime Output.prettyFmt(" <r><b>{s}<r>\n", allow_ansi_color), .{message}) catch unreachable; + writer.print(comptime Output.prettyFmt(" <r><b>{}<r>\n", allow_ansi_color), .{message}) catch unreachable; } } else if (source.text.len > 0) { defer did_print_name = true; @@ -1978,6 +2262,56 @@ pub const VirtualMachine = struct { } } + var add_extra_line = false; + + const Show = struct { + system_code: bool = false, + syscall: bool = false, + errno: bool = false, + path: bool = false, + }; + + var show = Show{ + .system_code = exception.system_code.len > 0 and !strings.eql(exception.system_code.slice(), name.slice()), + .syscall = exception.syscall.len > 0, + .errno = exception.errno < 0, + .path = exception.path.len > 0, + }; + + if (show.path) { + if (show.syscall) { + writer.writeAll(" ") catch unreachable; + } else if (show.errno) { + writer.writeAll(" ") catch unreachable; + } + writer.print(comptime Output.prettyFmt(" path<d>: <r><cyan>\"{s}\"<r>\n", allow_ansi_color), .{exception.path}) catch unreachable; + } + + if (show.system_code) { + if (show.syscall) { + writer.writeAll(" ") catch unreachable; + } else if (show.errno) { + writer.writeAll(" ") catch unreachable; + } + writer.print(comptime Output.prettyFmt(" code<d>: <r><cyan>\"{s}\"<r>\n", allow_ansi_color), .{exception.system_code}) catch unreachable; + add_extra_line = true; + } + + if (show.syscall) { + writer.print(comptime Output.prettyFmt("syscall<d>: <r><cyan>\"{s}\"<r>\n", allow_ansi_color), .{exception.syscall}) catch unreachable; + add_extra_line = true; + } + + if (show.errno) { + if (show.syscall) { + writer.writeAll(" ") catch unreachable; + } + writer.print(comptime Output.prettyFmt("errno<d>: <r><yellow>{d}<r>\n", allow_ansi_color), .{exception.errno}) catch unreachable; + add_extra_line = true; + } + + if (add_extra_line) writer.writeAll("\n") catch unreachable; + try printStackTrace(@TypeOf(writer), writer, exception.stack, allow_ansi_color); } }; @@ -2210,6 +2544,7 @@ pub const ResolveError = struct { ); pub fn create( + globalThis: *JSGlobalObject, allocator: std.mem.Allocator, msg: logger.Msg, referrer: string, @@ -2220,8 +2555,8 @@ pub const ResolveError = struct { .allocator = allocator, .referrer = Fs.Path.init(referrer), }; - var ref = Class.make(VirtualMachine.vm.global.ctx(), resolve_error); - js.JSValueProtect(VirtualMachine.vm.global.ref(), ref); + var ref = Class.make(globalThis.ref(), resolve_error); + js.JSValueProtect(globalThis.ref(), ref); return ref; } @@ -2237,32 +2572,32 @@ pub const ResolveError = struct { pub fn getMessage( this: *ResolveError, - _: js.JSContextRef, + ctx: js.JSContextRef, _: js.JSObjectRef, _: js.JSStringRef, _: js.ExceptionRef, ) js.JSValueRef { - return ZigString.init(this.msg.data.text).toValue(VirtualMachine.vm.global).asRef(); + return ZigString.init(this.msg.data.text).toValue(ctx.ptr()).asRef(); } pub fn getSpecifier( this: *ResolveError, - _: js.JSContextRef, + ctx: js.JSContextRef, _: js.JSObjectRef, _: js.JSStringRef, _: js.ExceptionRef, ) js.JSValueRef { - return ZigString.init(this.msg.metadata.resolve.specifier.slice(this.msg.data.text)).toValue(VirtualMachine.vm.global).asRef(); + return ZigString.init(this.msg.metadata.resolve.specifier.slice(this.msg.data.text)).toValue(ctx.ptr()).asRef(); } pub fn getImportKind( this: *ResolveError, - _: js.JSContextRef, + ctx: js.JSContextRef, _: js.JSObjectRef, _: js.JSStringRef, _: js.ExceptionRef, ) js.JSValueRef { - return ZigString.init(@tagName(this.msg.metadata.resolve.import_kind)).toValue(VirtualMachine.vm.global).asRef(); + return ZigString.init(@tagName(this.msg.metadata.resolve.import_kind)).toValue(ctx.ptr()).asRef(); } pub fn getReferrer( @@ -2273,7 +2608,7 @@ pub const ResolveError = struct { _: js.ExceptionRef, ) js.JSValueRef { if (this.referrer) |referrer| { - return ZigString.init(referrer.text).toValue(VirtualMachine.vm.global).asRef(); + return ZigString.init(referrer.text).toValue(ctx.ptr()).asRef(); } else { return js.JSValueMakeNull(ctx); } @@ -2282,12 +2617,12 @@ pub const ResolveError = struct { const BuildErrorName = "ResolveError"; pub fn getName( _: *ResolveError, - _: js.JSContextRef, + ctx: js.JSContextRef, _: js.JSObjectRef, _: js.JSStringRef, _: js.ExceptionRef, ) js.JSValueRef { - return ZigString.init(BuildErrorName).toValue(VirtualMachine.vm.global).asRef(); + return ZigString.init(BuildErrorName).toValue(ctx.ptr()).asRef(); } }; @@ -2322,6 +2657,7 @@ pub const BuildError = struct { ); pub fn create( + globalThis: *JSGlobalObject, allocator: std.mem.Allocator, msg: logger.Msg, // resolve_result: *const Resolver.Result, @@ -2333,8 +2669,8 @@ pub const BuildError = struct { .allocator = allocator, }; - var ref = Class.make(VirtualMachine.vm.global.ref(), build_error); - js.JSValueProtect(VirtualMachine.vm.global.ref(), ref); + var ref = Class.make(globalThis.ref(), build_error); + js.JSValueProtect(globalThis.ref(), ref); return ref; } @@ -2474,23 +2810,23 @@ pub const BuildError = struct { pub fn getMessage( this: *BuildError, - _: js.JSContextRef, + ctx: js.JSContextRef, _: js.JSObjectRef, _: js.JSStringRef, _: js.ExceptionRef, ) js.JSValueRef { - return ZigString.init(this.msg.data.text).toValue(VirtualMachine.vm.global).asRef(); + return ZigString.init(this.msg.data.text).toValue(ctx.ptr()).asRef(); } const BuildErrorName = "BuildError"; pub fn getName( _: *BuildError, - _: js.JSContextRef, + ctx: js.JSContextRef, _: js.JSObjectRef, _: js.JSStringRef, _: js.ExceptionRef, ) js.JSValueRef { - return ZigString.init(BuildErrorName).toValue(VirtualMachine.vm.global).asRef(); + return ZigString.init(BuildErrorName).toValue(ctx.ptr()).asRef(); } }; diff --git a/src/javascript/jsc/javascript_core_c_api.zig b/src/javascript/jsc/javascript_core_c_api.zig index ecd37c44a..0ae0a10e9 100644 --- a/src/javascript/jsc/javascript_core_c_api.zig +++ b/src/javascript/jsc/javascript_core_c_api.zig @@ -1,10 +1,14 @@ const cpp = @import("./bindings/bindings.zig"); -const generic = opaque {}; +const generic = opaque { + pub inline fn ptr(this: *@This()) *cpp.JSGlobalObject { + return @ptrCast(*cpp.JSGlobalObject, @alignCast(@alignOf(*cpp.JSGlobalObject), this)); + } +}; pub const Private = anyopaque; pub const struct_OpaqueJSContextGroup = generic; pub const JSContextGroupRef = ?*const struct_OpaqueJSContextGroup; pub const struct_OpaqueJSContext = generic; -pub const JSContextRef = ?*const struct_OpaqueJSContext; +pub const JSContextRef = *struct_OpaqueJSContext; pub const JSGlobalContextRef = ?*struct_OpaqueJSContext; pub const struct_OpaqueJSString = generic; pub const JSStringRef = ?*struct_OpaqueJSString; @@ -246,6 +250,7 @@ pub const OpaqueJSPropertyNameAccumulator = struct_OpaqueJSPropertyNameAccumulat // 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 JSObjectCallAsFunctionReturnValue(ctx: JSContextRef, object: JSObjectRef, thisObject: JSObjectRef, argumentCount: usize, arguments: [*c]const JSValueRef) cpp.JSValue; +pub extern "c" fn JSObjectCallAsFunctionReturnValueHoldingAPILock(ctx: JSContextRef, object: JSObjectRef, thisObject: JSObjectRef, argumentCount: usize, arguments: [*c]const JSValueRef) cpp.JSValue; pub extern fn JSRemoteInspectorDisableAutoStart() void; pub extern fn JSRemoteInspectorStart() void; diff --git a/src/javascript/jsc/node/buffer.js b/src/javascript/jsc/node/buffer.js new file mode 100644 index 000000000..faee19655 --- /dev/null +++ b/src/javascript/jsc/node/buffer.js @@ -0,0 +1,97 @@ +"use strict"; + +function createBuffer(BufferPrototype, BufferStatic, Realm) { + "use strict"; + + var Uint8ArraySubarray = Realm.Uint8Array.prototype.subarray; + var isUint8Array = (value) => value instanceof Realm.Uint8Array; + var SymbolToPrimitive = Realm.Symbol.toPrimitive; + var isArray = Realm.Array.isArray; + var isArrayBufferLike = + "SharedArrayBuffer" in Realm + ? () => + value instanceof Realm.ArrayBuffer || + value instanceof Realm.SharedArrayBuffer + : () => value instanceof Realm.ArrayBuffer; + + var BufferInstance = class BufferInstance extends Realm.Uint8Array { + constructor(bufferOrLength, byteOffset, length) { + super(bufferOrLength, byteOffset, length); + } + + static isBuffer(obj) { + return obj instanceof BufferInstance; + } + + static from(value, encodingOrOffset, length) { + switch (typeof value) { + case "string": { + return BufferStatic.fromString(value, encodingOrOffset, length); + } + case "object": { + if (isUint8Array(value)) { + return BufferStatic.fromUint8Array(value, encodingOrOffset, length); + } + + if (isArrayBufferLike(value)) { + return new BufferInstance(value, 0, length); + } + + const valueOf = value.valueOf && value.valueOf(); + if ( + valueOf != null && + valueOf !== value && + (typeof valueOf === "string" || typeof valueOf === "object") + ) { + return BufferInstance.from(valueOf, encodingOrOffset, length); + } + + if (typeof value[SymbolToPrimitive] === "function") { + const primitive = value[SymbolToPrimitive]("string"); + if (typeof primitive === "string") { + return BufferStatic.fromString(primitive, encodingOrOffset); + } + } + + if (isArray(value)) { + return BufferStatic.fromArray(value, encodingOrOffset, length); + } + } + } + + throw new TypeError( + "First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object." + ); + } + + slice(start, end) { + return Uint8ArraySubarray.call(this, start, end); + } + + static get poolSize() { + return BufferStatic._poolSize; + } + + static set poolSize(value) { + BufferStatic._poolSize = value; + } + + get parent() { + return this.buffer; + } + + get offset() { + return this.byteOffset; + } + }; + + Object.assign(BufferInstance, BufferStatic); + Object.assign(BufferInstance.prototype, BufferPrototype); + Object.defineProperty(BufferInstance, "name", { + value: "Buffer", + configurable: false, + enumerable: false, + }); + + return BufferInstance; +} diff --git a/src/javascript/jsc/node/buffer.zig b/src/javascript/jsc/node/buffer.zig new file mode 100644 index 000000000..efe9ace13 --- /dev/null +++ b/src/javascript/jsc/node/buffer.zig @@ -0,0 +1,553 @@ +const std = @import("std"); +const _global = @import("../../../global.zig"); +const strings = _global.strings; +const string = _global.string; +const AsyncIO = @import("io"); +const JSC = @import("../../../jsc.zig"); +const PathString = JSC.PathString; +const Environment = _global.Environment; +const C = _global.C; +const Syscall = @import("./syscall.zig"); +const os = std.os; +const Buffer = JSC.ArrayBuffer; + +const JSGlobalObject = JSC.JSGlobalObject; +const ArgumentsSlice = JSC.Node.ArgumentsSlice; + +const BufferStaticFunctionEnum = JSC.Node.DeclEnum(BufferStatic); + +fn BufferStatic_wrap(comptime FunctionEnum: BufferStaticFunctionEnum) NodeFSFunction { + const Function = @field(BufferStatic, @tagName(BufferStaticFunctionEnum)); + const FunctionType = @TypeOf(Function); + + const function: std.builtin.TypeInfo.Fn = comptime @typeInfo(FunctionType).Fn; + comptime if (function.args.len != 3) @compileError("Expected 3 arguments"); + const Arguments = comptime function.args[1].arg_type.?; + const FormattedName = comptime [1]u8{std.ascii.toUpper(@tagName(BufferStaticFunctionEnum)[0])} ++ @tagName(BufferStaticFunctionEnum)[1..]; + const Result = JSC.JSValue; + + const NodeBindingClosure = struct { + pub fn bind( + _: void, + ctx: JSC.C.JSContextRef, + _: JSC.C.JSObjectRef, + _: JSC.C.JSObjectRef, + arguments: []const JSC.C.JSValueRef, + exception: JSC.C.ExceptionRef, + ) JSC.C.JSValueRef { + var slice = ArgumentsSlice.init(@ptrCast([*]const JSC.JSValue, arguments.ptr)[0..arguments.len]); + + defer { + // TODO: fix this + for (arguments) |arg| { + JSC.C.JSValueUnprotect(ctx, arg); + } + slice.arena.deinit(); + } + + const args = if (comptime Arguments != void) + (Arguments.fromJS(ctx, &slice, exception) orelse return null) + else + Arguments{}; + if (exception.* != null) return null; + + const result: Result = Function( + ctx.ptr(), + args, + exception, + ); + if (exception.* != null) { + return null; + } + + return result.asObjectRef(); + } + }; + + return NodeBindingClosure.bind; +} + +pub const BufferStatic = struct { + pub const Arguments = struct { + pub const Alloc = struct { + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?Alloc {} + }; + pub const AllocUnsafe = struct { + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?AllocUnsafe {} + }; + pub const AllocUnsafeSlow = struct { + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?AllocUnsafeSlow {} + }; + pub const Compare = struct { + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?Compare {} + }; + pub const Concat = struct { + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?Concat {} + }; + pub const IsEncoding = struct { + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?IsEncoding {} + }; + }; + pub fn alloc(globalThis: *JSGlobalObject, args: Arguments.Alloc, exception: JSC.C.ExceptionRef) JSC.JSValue {} + pub fn allocUnsafe(globalThis: *JSGlobalObject, args: Arguments.AllocUnsafe, exception: JSC.C.ExceptionRef) JSC.JSValue {} + pub fn allocUnsafeSlow(globalThis: *JSGlobalObject, args: Arguments.AllocUnsafeSlow, exception: JSC.C.ExceptionRef) JSC.JSValue {} + pub fn compare(globalThis: *JSGlobalObject, args: Arguments.Compare, exception: JSC.C.ExceptionRef) JSC.JSValue {} + pub fn concat(globalThis: *JSGlobalObject, args: Arguments.Concat, exception: JSC.C.ExceptionRef) JSC.JSValue {} + pub fn isEncoding(globalThis: *JSGlobalObject, args: Arguments.IsEncoding, exception: JSC.C.ExceptionRef) JSC.JSValue {} + + pub const Class = JSC.NewClass( + void, + .{ .name = "Buffer" }, + .{ + .alloc = .{ .name = "alloc", .rfn = BufferStatic_wrap(.alloc) }, + .allocUnsafe = .{ .name = "allocUnsafe", .rfn = BufferStatic_wrap(.allocUnsafe) }, + .allocUnsafeSlow = .{ .name = "allocUnsafeSlow", .rfn = BufferStatic_wrap(.allocUnsafeSlow) }, + .compare = .{ .name = "compare", .rfn = BufferStatic_wrap(.compare) }, + .concat = .{ .name = "concat", .rfn = BufferStatic_wrap(.concat) }, + .isEncoding = .{ .name = "isEncoding", .rfn = BufferStatic_wrap(.isEncoding) }, + }, + .{ ._poolSize = .{ .name = "_poolSize", .get = .{ .name = "get", .rfn = BufferStatic.getPoolSize }, .set = .{ .name = "set", .rfn = BufferStatic.setPoolSize } } }, + ); +}; + +pub const BufferPrototype = struct { + const Arguments = struct { + pub const Compare = struct { + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?Compare { + return null; + } + }; + pub const Copy = struct { + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?Copy { + return null; + } + }; + pub const Equals = struct { + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?Equals { + return null; + } + }; + pub const Fill = struct { + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?Fill { + return null; + } + }; + pub const Includes = struct { + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?Includes { + return null; + } + }; + pub const IndexOf = struct { + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?IndexOf { + return null; + } + }; + pub const LastIndexOf = struct { + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?LastIndexOf { + return null; + } + }; + pub const Swap16 = struct { + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?Swap16 { + return null; + } + }; + pub const Swap32 = struct { + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?Swap32 { + return null; + } + }; + pub const Swap64 = struct { + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?Swap64 { + return null; + } + }; + pub const Write = struct { + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?Write { + return null; + } + }; + pub const Read = struct { + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?Read { + return null; + } + }; + + pub fn WriteInt(comptime kind: Int) type { + return struct { + const This = @This(); + const Value = Int.native.get(kind); + }; + } + pub fn ReadInt(comptime kind: Int) type { + return struct { + const This = @This(); + const Value = Int.native.get(kind); + }; + } + }; + pub fn compare(this: *Buffer, globalThis: *JSC.JSGlobalObject, args: Arguments.Compare) JSC.JSValue { + _ = this; + _ = globalThis; + _ = args; + return JSC.JSValue.jsUndefined(); + } + pub fn copy(this: *Buffer, globalThis: *JSC.JSGlobalObject, args: Arguments.Copy) JSC.JSValue { + _ = this; + _ = globalThis; + _ = args; + return JSC.JSValue.jsUndefined(); + } + pub fn equals(this: *Buffer, globalThis: *JSC.JSGlobalObject, args: Arguments.Equals) JSC.JSValue { + _ = this; + _ = globalThis; + _ = args; + return JSC.JSValue.jsUndefined(); + } + pub fn fill(this: *Buffer, globalThis: *JSC.JSGlobalObject, args: Arguments.Fill) JSC.JSValue { + _ = this; + _ = globalThis; + _ = args; + return JSC.JSValue.jsUndefined(); + } + pub fn includes(this: *Buffer, globalThis: *JSC.JSGlobalObject, args: Arguments.Includes) JSC.JSValue { + _ = this; + _ = globalThis; + _ = args; + return JSC.JSValue.jsUndefined(); + } + pub fn indexOf(this: *Buffer, globalThis: *JSC.JSGlobalObject, args: Arguments.IndexOf) JSC.JSValue { + _ = this; + _ = globalThis; + _ = args; + return JSC.JSValue.jsUndefined(); + } + pub fn lastIndexOf(this: *Buffer, globalThis: *JSC.JSGlobalObject, args: Arguments.LastIndexOf) JSC.JSValue { + _ = this; + _ = globalThis; + _ = args; + return JSC.JSValue.jsUndefined(); + } + pub fn swap16(this: *Buffer, globalThis: *JSC.JSGlobalObject, args: Arguments.Swap16) JSC.JSValue { + _ = this; + _ = globalThis; + _ = args; + return JSC.JSValue.jsUndefined(); + } + pub fn swap32(this: *Buffer, globalThis: *JSC.JSGlobalObject, args: Arguments.Swap32) JSC.JSValue { + _ = this; + _ = globalThis; + _ = args; + return JSC.JSValue.jsUndefined(); + } + pub fn swap64(this: *Buffer, globalThis: *JSC.JSGlobalObject, args: Arguments.Swap64) JSC.JSValue { + _ = this; + _ = globalThis; + _ = args; + return JSC.JSValue.jsUndefined(); + } + pub fn write(this: *Buffer, globalThis: *JSC.JSGlobalObject, args: Arguments.Write) JSC.JSValue { + _ = this; + _ = globalThis; + _ = args; + return JSC.JSValue.jsUndefined(); + } + pub fn read(this: *Buffer, globalThis: *JSC.JSGlobalObject, args: Arguments.Read) JSC.JSValue { + _ = this; + _ = globalThis; + _ = args; + return JSC.JSValue.jsUndefined(); + } + + fn writeIntAny(this: *Buffer, comptime kind: Int, args: Arguments.WriteInt(kind)) JSC.JSValue {} + fn readIntAny(this: *Buffer, comptime kind: Int, args: Arguments.ReadInt(kind)) JSC.JSValue {} + + pub const Class = JSC.NewClass( + void, + .{ .name = "Buffer" }, + .{ + .compare = .{ + .name = "compare", + .rfn = wrap(BufferPrototype.compare), + }, + .copy = .{ + .name = "copy", + .rfn = wrap(BufferPrototype.copy), + }, + .equals = .{ + .name = "equals", + .rfn = wrap(BufferPrototype.equals), + }, + .fill = .{ + .name = "fill", + .rfn = wrap(BufferPrototype.fill), + }, + .includes = .{ + .name = "includes", + .rfn = wrap(BufferPrototype.includes), + }, + .indexOf = .{ + .name = "indexOf", + .rfn = wrap(BufferPrototype.indexOf), + }, + .lastIndexOf = .{ + .name = "lastIndexOf", + .rfn = wrap(BufferPrototype.lastIndexOf), + }, + .swap16 = .{ + .name = "swap16", + .rfn = wrap(BufferPrototype.swap16), + }, + .swap32 = .{ + .name = "swap32", + .rfn = wrap(BufferPrototype.swap32), + }, + .swap64 = .{ + .name = "swap64", + .rfn = wrap(BufferPrototype.swap64), + }, + .write = .{ + .name = "write", + .rfn = wrap(BufferPrototype.write), + }, + .read = .{ + .name = "read", + .rfn = wrap(BufferPrototype.read), + }, + + // -- Write -- + .writeBigInt64BE = .{ + .name = "writeBigInt64BE", + .rfn = writeWrap(Int.BigInt64BE), + }, + .writeBigInt64LE = .{ + .name = "writeBigInt64LE", + .rfn = writeWrap(Int.BigInt64LE), + }, + .writeBigUInt64BE = .{ + .name = "writeBigUInt64BE", + .rfn = writeWrap(Int.BigUInt64BE), + }, + .writeBigUInt64LE = .{ + .name = "writeBigUInt64LE", + .rfn = writeWrap(Int.BigUInt64LE), + }, + .writeDoubleBE = .{ + .name = "writeDoubleBE", + .rfn = writeWrap(Int.DoubleBE), + }, + .writeDoubleLE = .{ + .name = "writeDoubleLE", + .rfn = writeWrap(Int.DoubleLE), + }, + .writeFloatBE = .{ + .name = "writeFloatBE", + .rfn = writeWrap(Int.FloatBE), + }, + .writeFloatLE = .{ + .name = "writeFloatLE", + .rfn = writeWrap(Int.FloatLE), + }, + .writeInt8 = .{ + .name = "writeInt8", + .rfn = writeWrap(Int.Int8), + }, + .writeInt16BE = .{ + .name = "writeInt16BE", + .rfn = writeWrap(Int.Int16BE), + }, + .writeInt16LE = .{ + .name = "writeInt16LE", + .rfn = writeWrap(Int.Int16LE), + }, + .writeInt32BE = .{ + .name = "writeInt32BE", + .rfn = writeWrap(Int.Int32BE), + }, + .writeInt32LE = .{ + .name = "writeInt32LE", + .rfn = writeWrap(Int.Int32LE), + }, + .writeIntBE = .{ + .name = "writeIntBE", + .rfn = writeWrap(Int.IntBE), + }, + .writeIntLE = .{ + .name = "writeIntLE", + .rfn = writeWrap(Int.IntLE), + }, + .writeUInt8 = .{ + .name = "writeUInt8", + .rfn = writeWrap(Int.UInt8), + }, + .writeUInt16BE = .{ + .name = "writeUInt16BE", + .rfn = writeWrap(Int.UInt16BE), + }, + .writeUInt16LE = .{ + .name = "writeUInt16LE", + .rfn = writeWrap(Int.UInt16LE), + }, + .writeUInt32BE = .{ + .name = "writeUInt32BE", + .rfn = writeWrap(Int.UInt32BE), + }, + .writeUInt32LE = .{ + .name = "writeUInt32LE", + .rfn = writeWrap(Int.UInt32LE), + }, + .writeUIntBE = .{ + .name = "writeUIntBE", + .rfn = writeWrap(Int.UIntBE), + }, + .writeUIntLE = .{ + .name = "writeUIntLE", + .rfn = writeWrap(Int.UIntLE), + }, + + // -- Read -- + .readBigInt64BE = .{ + .name = "readBigInt64BE", + .rfn = readWrap(Int.BigInt64BE), + }, + .readBigInt64LE = .{ + .name = "readBigInt64LE", + .rfn = readWrap(Int.BigInt64LE), + }, + .readBigUInt64BE = .{ + .name = "readBigUInt64BE", + .rfn = readWrap(Int.BigUInt64BE), + }, + .readBigUInt64LE = .{ + .name = "readBigUInt64LE", + .rfn = readWrap(Int.BigUInt64LE), + }, + .readDoubleBE = .{ + .name = "readDoubleBE", + .rfn = readWrap(Int.DoubleBE), + }, + .readDoubleLE = .{ + .name = "readDoubleLE", + .rfn = readWrap(Int.DoubleLE), + }, + .readFloatBE = .{ + .name = "readFloatBE", + .rfn = readWrap(Int.FloatBE), + }, + .readFloatLE = .{ + .name = "readFloatLE", + .rfn = readWrap(Int.FloatLE), + }, + .readInt8 = .{ + .name = "readInt8", + .rfn = readWrap(Int.Int8), + }, + .readInt16BE = .{ + .name = "readInt16BE", + .rfn = readWrap(Int.Int16BE), + }, + .readInt16LE = .{ + .name = "readInt16LE", + .rfn = readWrap(Int.Int16LE), + }, + .readInt32BE = .{ + .name = "readInt32BE", + .rfn = readWrap(Int.Int32BE), + }, + .readInt32LE = .{ + .name = "readInt32LE", + .rfn = readWrap(Int.Int32LE), + }, + .readIntBE = .{ + .name = "readIntBE", + .rfn = readWrap(Int.IntBE), + }, + .readIntLE = .{ + .name = "readIntLE", + .rfn = readWrap(Int.IntLE), + }, + .readUInt8 = .{ + .name = "readUInt8", + .rfn = readWrap(Int.UInt8), + }, + .readUInt16BE = .{ + .name = "readUInt16BE", + .rfn = readWrap(Int.UInt16BE), + }, + .readUInt16LE = .{ + .name = "readUInt16LE", + .rfn = readWrap(Int.UInt16LE), + }, + .readUInt32BE = .{ + .name = "readUInt32BE", + .rfn = readWrap(Int.UInt32BE), + }, + .readUInt32LE = .{ + .name = "readUInt32LE", + .rfn = readWrap(Int.UInt32LE), + }, + .readUIntBE = .{ + .name = "readUIntBE", + .rfn = readWrap(Int.UIntBE), + }, + .readUIntLE = .{ + .name = "readUIntLE", + .rfn = readWrap(Int.UIntLE), + }, + }, + .{}, + ); +}; + +const Int = enum { + BigInt64BE, + BigInt64LE, + BigUInt64BE, + BigUInt64LE, + DoubleBE, + DoubleLE, + FloatBE, + FloatLE, + Int8, + Int16BE, + Int16LE, + Int32BE, + Int32LE, + IntBE, + IntLE, + UInt8, + UInt16BE, + UInt16LE, + UInt32BE, + UInt32LE, + UIntBE, + UIntLE, + + const NativeMap = std.EnumArray(Int, type); + pub const native: NativeMap = brk: { + var map = NativeMap.initUndefined(); + map.set(.BigInt64BE, i64); + map.set(.BigInt64LE, i64); + map.set(.BigUInt64BE, u64); + map.set(.BigUInt64LE, u64); + map.set(.DoubleBE, f64); + map.set(.DoubleLE, f64); + map.set(.FloatBE, f32); + map.set(.FloatLE, f32); + map.set(.Int8, i8); + map.set(.Int16BE, i16); + map.set(.Int16LE, i16); + map.set(.Int32BE, u32); + map.set(.Int32LE, u32); + map.set(.IntBE, i32); + map.set(.IntLE, i32); + map.set(.UInt8, u8); + map.set(.UInt16BE, u16); + map.set(.UInt16LE, u16); + map.set(.UInt32BE, u32); + map.set(.UInt32LE, u32); + map.set(.UIntBE, u32); + map.set(.UIntLE, u32); + break :brk map; + }; +}; diff --git a/src/javascript/jsc/node/dir_iterator.zig b/src/javascript/jsc/node/dir_iterator.zig new file mode 100644 index 000000000..f4c8b6d4a --- /dev/null +++ b/src/javascript/jsc/node/dir_iterator.zig @@ -0,0 +1,347 @@ +// This is copied from std.fs.Dir.Iterator +// The differences are: +// - it returns errors in the expected format +// - doesn't mark BADF as unreachable +// - It uses PathString instead of []const u8 + +const builtin = @import("builtin"); +const std = @import("std"); +const os = std.os; + +const Dir = std.fs.Dir; +const JSC = @import("../../../jsc.zig"); +const PathString = JSC.PathString; + +const IteratorError = error{ AccessDenied, SystemResources } || os.UnexpectedError; +const mem = std.mem; +const strings = @import("../../../global.zig").strings; +const Maybe = JSC.Node.Maybe; +const File = std.fs.File; +const Result = Maybe(?Entry); + +const Entry = JSC.Node.DirEnt; + +pub const Iterator = switch (builtin.os.tag) { + .macos, .ios, .freebsd, .netbsd, .dragonfly, .openbsd, .solaris => struct { + dir: Dir, + seek: i64, + buf: [8192]u8, // TODO align(@alignOf(os.system.dirent)), + index: usize, + end_index: usize, + + const Self = @This(); + + pub const Error = IteratorError; + + /// Memory such as file names referenced in this returned entry becomes invalid + /// with subsequent calls to `next`, as well as when this `Dir` is deinitialized. + const next = switch (builtin.os.tag) { + .macos, .ios => nextDarwin, + // .freebsd, .netbsd, .dragonfly, .openbsd => nextBsd, + // .solaris => nextSolaris, + else => @compileError("unimplemented"), + }; + + fn nextDarwin(self: *Self) Result { + start_over: while (true) { + if (self.index >= self.end_index) { + const rc = os.system.__getdirentries64( + self.dir.fd, + &self.buf, + self.buf.len, + &self.seek, + ); + + if (rc < 1) { + if (rc == 0) return Result{ .result = null }; + if (Result.errnoSys(rc, .getdirentries64)) |err| { + return err; + } + } + + self.index = 0; + self.end_index = @intCast(usize, rc); + } + const darwin_entry = @ptrCast(*align(1) os.system.dirent, &self.buf[self.index]); + const next_index = self.index + darwin_entry.reclen(); + self.index = next_index; + + const name = @ptrCast([*]u8, &darwin_entry.d_name)[0..darwin_entry.d_namlen]; + + if (strings.eqlComptime(name, ".") or strings.eqlComptime(name, "..") or (darwin_entry.d_ino == 0)) { + continue :start_over; + } + + const entry_kind = switch (darwin_entry.d_type) { + os.DT.BLK => Entry.Kind.BlockDevice, + os.DT.CHR => Entry.Kind.CharacterDevice, + os.DT.DIR => Entry.Kind.Directory, + os.DT.FIFO => Entry.Kind.NamedPipe, + os.DT.LNK => Entry.Kind.SymLink, + os.DT.REG => Entry.Kind.File, + os.DT.SOCK => Entry.Kind.UnixDomainSocket, + os.DT.WHT => Entry.Kind.Whiteout, + else => Entry.Kind.Unknown, + }; + return .{ + .result = Entry{ + .name = PathString.init(name), + .kind = entry_kind, + }, + }; + } + } + }, + + .linux => struct { + dir: Dir, + // The if guard is solely there to prevent compile errors from missing `linux.dirent64` + // definition when compiling for other OSes. It doesn't do anything when compiling for Linux. + buf: [8192]u8 align(if (builtin.os.tag != .linux) 1 else @alignOf(linux.dirent64)), + index: usize, + end_index: usize, + + const Self = @This(); + const linux = os.linux; + + pub const Error = IteratorError; + + /// Memory such as file names referenced in this returned entry becomes invalid + /// with subsequent calls to `next`, as well as when this `Dir` is deinitialized. + pub fn next(self: *Self) Result { + start_over: while (true) { + if (self.index >= self.end_index) { + const rc = linux.getdents64(self.dir.fd, &self.buf, self.buf.len); + if (Result.errnoSys(rc, .getdents64)) |err| return err; + if (rc == 0) return .{ .result = null }; + self.index = 0; + self.end_index = rc; + } + const linux_entry = @ptrCast(*align(1) linux.dirent64, &self.buf[self.index]); + const next_index = self.index + linux_entry.reclen(); + self.index = next_index; + + const name = mem.sliceTo(@ptrCast([*:0]u8, &linux_entry.d_name), 0); + + // skip . and .. entries + if (strings.eqlComptime(name, ".") or strings.eqlComptime(name, "..")) { + continue :start_over; + } + + const entry_kind = switch (linux_entry.d_type) { + linux.DT.BLK => Entry.Kind.BlockDevice, + linux.DT.CHR => Entry.Kind.CharacterDevice, + linux.DT.DIR => Entry.Kind.Directory, + linux.DT.FIFO => Entry.Kind.NamedPipe, + linux.DT.LNK => Entry.Kind.SymLink, + linux.DT.REG => Entry.Kind.File, + linux.DT.SOCK => Entry.Kind.UnixDomainSocket, + else => Entry.Kind.Unknown, + }; + return .{ + .result = Entry{ + .name = PathString.init(name), + .kind = entry_kind, + }, + }; + } + } + }, + .windows => struct { + dir: Dir, + buf: [8192]u8 align(@alignOf(os.windows.FILE_BOTH_DIR_INFORMATION)), + index: usize, + end_index: usize, + first: bool, + name_data: [256]u8, + + const Self = @This(); + + pub const Error = IteratorError; + + /// Memory such as file names referenced in this returned entry becomes invalid + /// with subsequent calls to `next`, as well as when this `Dir` is deinitialized. + pub fn next(self: *Self) Result { + while (true) { + const w = os.windows; + if (self.index >= self.end_index) { + var io: w.IO_STATUS_BLOCK = undefined; + const rc = w.ntdll.NtQueryDirectoryFile( + self.dir.fd, + null, + null, + null, + &io, + &self.buf, + self.buf.len, + .FileBothDirectoryInformation, + w.FALSE, + null, + if (self.first) @as(w.BOOLEAN, w.TRUE) else @as(w.BOOLEAN, w.FALSE), + ); + self.first = false; + if (io.Information == 0) return .{ .result = null }; + self.index = 0; + self.end_index = io.Information; + switch (rc) { + .SUCCESS => {}, + .ACCESS_DENIED => return error.AccessDenied, // Double-check that the Dir was opened with iteration ability + + else => return w.unexpectedStatus(rc), + } + } + + const aligned_ptr = @alignCast(@alignOf(w.FILE_BOTH_DIR_INFORMATION), &self.buf[self.index]); + const dir_info = @ptrCast(*w.FILE_BOTH_DIR_INFORMATION, aligned_ptr); + if (dir_info.NextEntryOffset != 0) { + self.index += dir_info.NextEntryOffset; + } else { + self.index = self.buf.len; + } + + const name_utf16le = @ptrCast([*]u16, &dir_info.FileName)[0 .. dir_info.FileNameLength / 2]; + + if (mem.eql(u16, name_utf16le, &[_]u16{'.'}) or mem.eql(u16, name_utf16le, &[_]u16{ '.', '.' })) + continue; + // Trust that Windows gives us valid UTF-16LE + const name_utf8_len = std.unicode.utf16leToUtf8(self.name_data[0..], name_utf16le) catch unreachable; + const name_utf8 = self.name_data[0..name_utf8_len]; + const kind = blk: { + const attrs = dir_info.FileAttributes; + if (attrs & w.FILE_ATTRIBUTE_DIRECTORY != 0) break :blk Entry.Kind.Directory; + if (attrs & w.FILE_ATTRIBUTE_REPARSE_POINT != 0) break :blk Entry.Kind.SymLink; + break :blk Entry.Kind.File; + }; + return .{ + .result = Entry{ + .name = PathString.init(name_utf8), + .kind = kind, + }, + }; + } + } + }, + .wasi => struct { + dir: Dir, + buf: [8192]u8, // TODO align(@alignOf(os.wasi.dirent_t)), + cookie: u64, + index: usize, + end_index: usize, + + const Self = @This(); + + pub const Error = IteratorError; + + /// Memory such as file names referenced in this returned entry becomes invalid + /// with subsequent calls to `next`, as well as when this `Dir` is deinitialized. + pub fn next(self: *Self) Result { + // We intentinally use fd_readdir even when linked with libc, + // since its implementation is exactly the same as below, + // and we avoid the code complexity here. + const w = os.wasi; + start_over: while (true) { + if (self.index >= self.end_index) { + var bufused: usize = undefined; + switch (w.fd_readdir(self.dir.fd, &self.buf, self.buf.len, self.cookie, &bufused)) { + .SUCCESS => {}, + .BADF => unreachable, // Dir is invalid or was opened without iteration ability + .FAULT => unreachable, + .NOTDIR => unreachable, + .INVAL => unreachable, + .NOTCAPABLE => return error.AccessDenied, + else => |err| return os.unexpectedErrno(err), + } + if (bufused == 0) return null; + self.index = 0; + self.end_index = bufused; + } + const entry = @ptrCast(*align(1) w.dirent_t, &self.buf[self.index]); + const entry_size = @sizeOf(w.dirent_t); + const name_index = self.index + entry_size; + const name = mem.span(self.buf[name_index .. name_index + entry.d_namlen]); + + const next_index = name_index + entry.d_namlen; + self.index = next_index; + self.cookie = entry.d_next; + + // skip . and .. entries + if (strings.eqlComptime(name, ".") or strings.eqlComptime(name, "..")) { + continue :start_over; + } + + const entry_kind = switch (entry.d_type) { + .BLOCK_DEVICE => Entry.Kind.BlockDevice, + .CHARACTER_DEVICE => Entry.Kind.CharacterDevice, + .DIRECTORY => Entry.Kind.Directory, + .SYMBOLIC_LINK => Entry.Kind.SymLink, + .REGULAR_FILE => Entry.Kind.File, + .SOCKET_STREAM, .SOCKET_DGRAM => Entry.Kind.UnixDomainSocket, + else => Entry.Kind.Unknown, + }; + return Entry{ + .name = name, + .kind = entry_kind, + }; + } + } + }, + else => @compileError("unimplemented"), +}; + +const WrappedIterator = struct { + iter: Iterator, + const Self = @This(); + + pub const Error = IteratorError; + + pub inline fn next(self: *Self) Result { + return self.iter.next(); + } +}; + +pub fn iterate(self: Dir) WrappedIterator { + return WrappedIterator{ + .iter = _iterate(self), + }; +} + +fn _iterate(self: Dir) Iterator { + switch (builtin.os.tag) { + .macos, + .ios, + .freebsd, + .netbsd, + .dragonfly, + .openbsd, + .solaris, + => return Iterator{ + .dir = self, + .seek = 0, + .index = 0, + .end_index = 0, + .buf = undefined, + }, + .linux, .haiku => return Iterator{ + .dir = self, + .index = 0, + .end_index = 0, + .buf = undefined, + }, + .windows => return Iterator{ + .dir = self, + .index = 0, + .end_index = 0, + .first = true, + .buf = undefined, + .name_data = undefined, + }, + .wasi => return Iterator{ + .dir = self, + .cookie = os.wasi.DIRCOOKIE_START, + .index = 0, + .end_index = 0, + .buf = undefined, + }, + else => @compileError("unimplemented"), + } +} diff --git a/src/javascript/jsc/node/node_fs.zig b/src/javascript/jsc/node/node_fs.zig new file mode 100644 index 000000000..a89eb190f --- /dev/null +++ b/src/javascript/jsc/node/node_fs.zig @@ -0,0 +1,3726 @@ +// This file contains the underlying implementation for sync & async functions +// for interacting with the filesystem from JavaScript. +// The top-level functions assume the arguments are already validated +const std = @import("std"); +const _global = @import("../../../global.zig"); +const strings = _global.strings; +const string = _global.string; +const AsyncIO = @import("io"); +const JSC = @import("../../../jsc.zig"); +const PathString = JSC.PathString; +const Environment = _global.Environment; +const C = _global.C; +const Flavor = JSC.Node.Flavor; +const system = std.os.system; +const Maybe = JSC.Node.Maybe; +const Encoding = JSC.Node.Encoding; +const Syscall = @import("./syscall.zig"); +const builtin = @import("builtin"); +const os = @import("std").os; +const darwin = os.darwin; +const linux = os.linux; +const PathOrBuffer = JSC.Node.PathOrBuffer; +const PathLike = JSC.Node.PathLike; +const PathOrFileDescriptor = JSC.Node.PathOrFileDescriptor; +const FileDescriptor = JSC.Node.FileDescriptor; +const DirIterator = @import("./dir_iterator.zig"); +const Path = @import("../../../resolver/resolve_path.zig"); +const FileSystem = @import("../../../fs.zig").FileSystem; +const StringOrBuffer = JSC.Node.StringOrBuffer; +const ArgumentsSlice = JSC.Node.ArgumentsSlice; +const TimeLike = JSC.Node.TimeLike; +const Mode = JSC.Node.Mode; + +const uid_t = std.os.uid_t; +const gid_t = std.os.gid_t; + +/// u63 to allow one null bit +const ReadPosition = u63; + +const Stats = JSC.Node.Stats; +const BigIntStats = JSC.Node.BigIntStats; +const DirEnt = JSC.Node.DirEnt; + +pub const FlavoredIO = struct { + io: *AsyncIO, +}; + +const ArrayBuffer = JSC.MarkedArrayBuffer; +const Buffer = JSC.Buffer; +const FileSystemFlags = JSC.Node.FileSystemFlags; + +// TODO: to improve performance for all of these +// The tagged unions for each type should become regular unions +// and the tags should be passed in as comptime arguments to the functions performing the syscalls +// This would reduce stack size, at the cost of instruction cache misses +const Arguments = struct { + pub const Rename = struct { + old_path: PathLike, + new_path: PathLike, + + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?Rename { + const old_path = PathLike.fromJS(ctx, arguments, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "oldPath must be a string or Buffer", + .{}, + ctx, + exception, + ); + } + return null; + }; + + const new_path = PathLike.fromJS(ctx, arguments, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "newPath must be a string or Buffer", + .{}, + ctx, + exception, + ); + } + return null; + }; + + return Rename{ .old_path = old_path, .new_path = new_path }; + } + }; + + pub const Truncate = struct { + /// Passing a file descriptor is deprecated and may result in an error being thrown in the future. + path: PathOrFileDescriptor, + len: u32 = 0, + + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?Truncate { + const path = PathOrFileDescriptor.fromJS(ctx, arguments, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "path must be a string or Buffer", + .{}, + ctx, + exception, + ); + } + return null; + }; + + const len: u32 = brk: { + const len_value = arguments.next() orelse break :brk 0; + + if (len_value.isNumber()) { + arguments.eat(); + break :brk len_value.toU32(); + } + + break :brk 0; + }; + + return Truncate{ .path = path, .len = len }; + } + }; + + pub const FTruncate = struct { + fd: FileDescriptor, + len: ?u32 = null, + + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?FTruncate { + const fd = JSC.Node.fileDescriptorFromJS(ctx, arguments.next() orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "file descriptor is required", + .{}, + ctx, + exception, + ); + } + return null; + }, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "file descriptor must be a number", + .{}, + ctx, + exception, + ); + } + return null; + }; + + arguments.eat(); + + if (exception.* != null) return null; + + const len: u32 = brk: { + const len_value = arguments.next() orelse break :brk 0; + if (len_value.isNumber()) { + arguments.eat(); + break :brk len_value.toU32(); + } + + break :brk 0; + }; + + return FTruncate{ .fd = fd, .len = len }; + } + }; + + pub const Chown = struct { + path: PathLike, + uid: uid_t = 0, + gid: gid_t = 0, + + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?Chown { + const path = PathLike.fromJS(ctx, arguments, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "path must be a string or Buffer", + .{}, + ctx, + exception, + ); + } + return null; + }; + + const uid: uid_t = brk: { + const uid_value = arguments.next() orelse break :brk { + if (exception.* == null) { + JSC.throwInvalidArguments( + "uid is required", + .{}, + ctx, + exception, + ); + } + return null; + }; + + arguments.eat(); + break :brk @intCast(uid_t, uid_value.toInt32()); + }; + + const gid: gid_t = brk: { + const gid_value = arguments.next() orelse break :brk { + if (exception.* == null) { + JSC.throwInvalidArguments( + "gid is required", + .{}, + ctx, + exception, + ); + } + return null; + }; + + arguments.eat(); + break :brk @intCast(gid_t, gid_value.toInt32()); + }; + + return Chown{ .path = path, .uid = uid, .gid = gid }; + } + }; + + pub const Fchown = struct { + fd: FileDescriptor, + uid: uid_t, + gid: gid_t, + + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?Fchown { + const fd = JSC.Node.fileDescriptorFromJS(ctx, arguments.next() orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "file descriptor is required", + .{}, + ctx, + exception, + ); + } + return null; + }, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "file descriptor must be a number", + .{}, + ctx, + exception, + ); + } + return null; + }; + + if (exception.* != null) return null; + + const uid: uid_t = brk: { + const uid_value = arguments.next() orelse break :brk { + if (exception.* == null) { + JSC.throwInvalidArguments( + "uid is required", + .{}, + ctx, + exception, + ); + } + return null; + }; + + arguments.eat(); + break :brk @intCast(uid_t, uid_value.toInt32()); + }; + + const gid: gid_t = brk: { + const gid_value = arguments.next() orelse break :brk { + if (exception.* == null) { + JSC.throwInvalidArguments( + "gid is required", + .{}, + ctx, + exception, + ); + } + return null; + }; + + arguments.eat(); + break :brk @intCast(gid_t, gid_value.toInt32()); + }; + + return Fchown{ .fd = fd, .uid = uid, .gid = gid }; + } + }; + + pub const LChown = Chown; + + pub const Lutimes = struct { + path: PathLike, + atime: TimeLike, + mtime: TimeLike, + + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?Lutimes { + const path = PathLike.fromJS(ctx, arguments, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "path must be a string or Buffer", + .{}, + ctx, + exception, + ); + } + return null; + }; + + const atime = JSC.Node.timeLikeFromJS(ctx, arguments.next() orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "atime is required", + .{}, + ctx, + exception, + ); + } + + return null; + }, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "atime must be a number or a Date", + .{}, + ctx, + exception, + ); + } + return null; + }; + + arguments.eat(); + + const mtime = JSC.Node.timeLikeFromJS(ctx, arguments.next() orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "mtime is required", + .{}, + ctx, + exception, + ); + } + + return null; + }, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "mtime must be a number or a Date", + .{}, + ctx, + exception, + ); + } + return null; + }; + + arguments.eat(); + + return Lutimes{ .path = path, .atime = atime, .mtime = mtime }; + } + }; + + pub const Chmod = struct { + path: PathLike, + mode: Mode = 0x777, + + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?Chmod { + const path = PathLike.fromJS(ctx, arguments, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "path must be a string or Buffer", + .{}, + ctx, + exception, + ); + } + return null; + }; + + const mode: Mode = JSC.Node.modeFromJS(ctx, arguments.next() orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "mode is required", + .{}, + ctx, + exception, + ); + } + return null; + }, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "mode must be a string or integer", + .{}, + ctx, + exception, + ); + } + return null; + }; + + arguments.eat(); + + return Chmod{ .path = path, .mode = mode }; + } + }; + + pub const FChmod = struct { + fd: FileDescriptor, + mode: Mode = 0x777, + + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?FChmod { + const fd = JSC.Node.fileDescriptorFromJS(ctx, arguments.next() orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "file descriptor is required", + .{}, + ctx, + exception, + ); + } + return null; + }, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "file descriptor must be a number", + .{}, + ctx, + exception, + ); + } + return null; + }; + + if (exception.* != null) return null; + arguments.eat(); + + const mode: Mode = JSC.Node.modeFromJS(ctx, arguments.next() orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "mode is required", + .{}, + ctx, + exception, + ); + } + return null; + }, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "mode must be a string or integer", + .{}, + ctx, + exception, + ); + } + return null; + }; + + arguments.eat(); + + return FChmod{ .fd = fd, .mode = mode }; + } + }; + + pub const LCHmod = Chmod; + + pub const Stat = struct { + path: PathLike, + big_int: bool = false, + + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?Stat { + const path = PathLike.fromJS(ctx, arguments, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "path must be a string or Buffer", + .{}, + ctx, + exception, + ); + } + return null; + }; + + if (exception.* != null) return null; + + const big_int = brk: { + if (arguments.next()) |next_val| { + if (next_val.isObject()) { + if (next_val.isCallable(ctx.ptr().vm())) break :brk false; + arguments.eat(); + + if (next_val.getIfPropertyExists(ctx.ptr(), "bigint")) |big_int| { + break :brk big_int.toBoolean(); + } + } + } + break :brk false; + }; + + if (exception.* != null) return null; + + return Stat{ .path = path, .big_int = big_int }; + } + }; + + pub const Fstat = struct { + fd: FileDescriptor, + big_int: bool = false, + + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?Fstat { + const fd = JSC.Node.fileDescriptorFromJS(ctx, arguments.next() orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "file descriptor is required", + .{}, + ctx, + exception, + ); + } + return null; + }, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "file descriptor must be a number", + .{}, + ctx, + exception, + ); + } + return null; + }; + + if (exception.* != null) return null; + + const big_int = brk: { + if (arguments.next()) |next_val| { + if (next_val.isObject()) { + if (next_val.isCallable(ctx.ptr().vm())) break :brk false; + arguments.eat(); + + if (next_val.getIfPropertyExists(ctx.ptr(), "bigint")) |big_int| { + break :brk big_int.toBoolean(); + } + } + } + break :brk false; + }; + + if (exception.* != null) return null; + + return Fstat{ .fd = fd, .big_int = big_int }; + } + }; + + pub const Lstat = Stat; + + pub const Link = struct { + old_path: PathLike, + new_path: PathLike, + + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?Link { + const old_path = PathLike.fromJS(ctx, arguments, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "oldPath must be a string or Buffer", + .{}, + ctx, + exception, + ); + } + return null; + }; + + if (exception.* != null) return null; + + const new_path = PathLike.fromJS(ctx, arguments, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "newPath must be a string or Buffer", + .{}, + ctx, + exception, + ); + } + return null; + }; + + if (exception.* != null) return null; + + return Link{ .old_path = old_path, .new_path = new_path }; + } + }; + + pub const Symlink = struct { + old_path: PathLike, + new_path: PathLike, + + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?Symlink { + const old_path = PathLike.fromJS(ctx, arguments, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "target must be a string or Buffer", + .{}, + ctx, + exception, + ); + } + return null; + }; + + if (exception.* != null) return null; + + const new_path = PathLike.fromJS(ctx, arguments, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "path must be a string or Buffer", + .{}, + ctx, + exception, + ); + } + return null; + }; + + if (exception.* != null) return null; + + if (arguments.next()) |next_val| { + // The type argument is only available on Windows and + // ignored on other platforms. It can be set to 'dir', + // 'file', or 'junction'. If the type argument is not set, + // Node.js will autodetect target type and use 'file' or + // 'dir'. If the target does not exist, 'file' will be used. + // Windows junction points require the destination path to + // be absolute. When using 'junction', the target argument + // will automatically be normalized to absolute path. + if (next_val.isString()) { + comptime if (Environment.isWindows) @compileError("Add support for type argument on Windows"); + arguments.eat(); + } + } + + return Symlink{ .old_path = old_path, .new_path = new_path }; + } + }; + + pub const Readlink = struct { + path: PathLike, + encoding: Encoding = Encoding.utf8, + + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?Readlink { + const path = PathLike.fromJS(ctx, arguments, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "path must be a string or Buffer", + .{}, + ctx, + exception, + ); + } + return null; + }; + + if (exception.* != null) return null; + var encoding = Encoding.utf8; + if (arguments.next()) |val| { + arguments.eat(); + + switch (val.jsType()) { + JSC.JSValue.JSType.String, JSC.JSValue.JSType.StringObject, JSC.JSValue.JSType.DerivedStringObject => { + encoding = Encoding.fromStringValue(val, ctx.ptr()) orelse Encoding.utf8; + }, + else => { + if (val.isObject()) { + if (val.getIfPropertyExists(ctx.ptr(), "encoding")) |encoding_| { + encoding = Encoding.fromStringValue(encoding_, ctx.ptr()) orelse Encoding.utf8; + } + } + }, + } + } + + return Readlink{ .path = path, .encoding = encoding }; + } + }; + + pub const Realpath = struct { + path: PathLike, + encoding: Encoding = Encoding.utf8, + + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?Realpath { + const path = PathLike.fromJS(ctx, arguments, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "path must be a string or Buffer", + .{}, + ctx, + exception, + ); + } + return null; + }; + + if (exception.* != null) return null; + var encoding = Encoding.utf8; + if (arguments.next()) |val| { + arguments.eat(); + + switch (val.jsType()) { + JSC.JSValue.JSType.String, JSC.JSValue.JSType.StringObject, JSC.JSValue.JSType.DerivedStringObject => { + encoding = Encoding.fromStringValue(val, ctx.ptr()) orelse Encoding.utf8; + }, + else => { + if (val.isObject()) { + if (val.getIfPropertyExists(ctx.ptr(), "encoding")) |encoding_| { + encoding = Encoding.fromStringValue(encoding_, ctx.ptr()) orelse Encoding.utf8; + } + } + }, + } + } + + return Realpath{ .path = path, .encoding = encoding }; + } + }; + + pub const Unlink = struct { + path: PathLike, + + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?Unlink { + const path = PathLike.fromJS(ctx, arguments, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "path must be a string or Buffer", + .{}, + ctx, + exception, + ); + } + return null; + }; + + if (exception.* != null) return null; + + return Unlink{ + .path = path, + }; + } + }; + + pub const Rm = struct { + path: PathLike, + force: bool = false, + max_retries: u32 = 0, + recursive: bool = false, + retry_delay: c_uint = 100, + }; + + pub const RmDir = struct { + path: PathLike, + + max_retries: u32 = 0, + recursive: bool = false, + retry_delay: c_uint = 100, + }; + + /// https://github.com/nodejs/node/blob/master/lib/fs.js#L1285 + pub const Mkdir = struct { + path: PathLike, + /// Indicates whether parent folders should be created. + /// If a folder was created, the path to the first created folder will be returned. + /// @default false + recursive: bool = false, + /// A file mode. If a string is passed, it is parsed as an octal integer. If not specified + /// @default + mode: Mode = 0o777, + + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?Mkdir { + const path = PathLike.fromJS(ctx, arguments, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "path must be a string or Buffer", + .{}, + ctx, + exception, + ); + } + return null; + }; + + if (exception.* != null) return null; + + var recursive = false; + var mode: Mode = 0o777; + + if (arguments.next()) |val| { + arguments.eat(); + + if (val.isObject()) { + if (val.getIfPropertyExists(ctx.ptr(), "recursive")) |recursive_| { + recursive = recursive_.toBoolean(); + } + + if (val.getIfPropertyExists(ctx.ptr(), "mode")) |mode_| { + mode = JSC.Node.modeFromJS(ctx, mode_, exception) orelse mode; + } + } + } + + return Mkdir{ + .path = path, + .recursive = recursive, + .mode = mode, + }; + } + }; + + const MkdirTemp = struct { + prefix: string = "", + encoding: Encoding = Encoding.utf8, + + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?MkdirTemp { + const prefix_value = arguments.next() orelse return MkdirTemp{}; + + var prefix = JSC.ZigString.Empty; + prefix_value.toZigString(&prefix, ctx.ptr()); + + if (exception.* != null) return null; + + arguments.eat(); + + var encoding = Encoding.utf8; + + if (arguments.next()) |val| { + arguments.eat(); + + switch (val.jsType()) { + JSC.JSValue.JSType.String, JSC.JSValue.JSType.StringObject, JSC.JSValue.JSType.DerivedStringObject => { + encoding = Encoding.fromStringValue(val, ctx.ptr()) orelse Encoding.utf8; + }, + else => { + if (val.isObject()) { + if (val.getIfPropertyExists(ctx.ptr(), "encoding")) |encoding_| { + encoding = Encoding.fromStringValue(encoding_, ctx.ptr()) orelse Encoding.utf8; + } + } + }, + } + } + + return MkdirTemp{ + .prefix = prefix.slice(), + .encoding = encoding, + }; + } + }; + + pub const Readdir = struct { + path: PathLike, + encoding: Encoding = Encoding.utf8, + with_file_types: bool = false, + + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?Readdir { + const path = PathLike.fromJS(ctx, arguments, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "path must be a string or Buffer", + .{}, + ctx, + exception, + ); + } + return null; + }; + + if (exception.* != null) return null; + + var encoding = Encoding.utf8; + var with_file_types = false; + + if (arguments.next()) |val| { + arguments.eat(); + + switch (val.jsType()) { + JSC.JSValue.JSType.String, JSC.JSValue.JSType.StringObject, JSC.JSValue.JSType.DerivedStringObject => { + encoding = Encoding.fromStringValue(val, ctx.ptr()) orelse Encoding.utf8; + }, + else => { + if (val.isObject()) { + if (val.getIfPropertyExists(ctx.ptr(), "encoding")) |encoding_| { + encoding = Encoding.fromStringValue(encoding_, ctx.ptr()) orelse Encoding.utf8; + } + + if (val.getIfPropertyExists(ctx.ptr(), "withFileTypes")) |with_file_types_| { + with_file_types = with_file_types_.toBoolean(); + } + } + }, + } + } + + return Readdir{ + .path = path, + .encoding = encoding, + .with_file_types = with_file_types, + }; + } + }; + + pub const Close = struct { + fd: FileDescriptor, + + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?Close { + const fd = JSC.Node.fileDescriptorFromJS(ctx, arguments.next() orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "File descriptor is required", + .{}, + ctx, + exception, + ); + } + return null; + }, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "fd must be a number", + .{}, + ctx, + exception, + ); + } + return null; + }; + + if (exception.* != null) return null; + + return Close{ + .fd = fd, + }; + } + }; + + pub const Open = struct { + path: PathLike, + flags: FileSystemFlags = FileSystemFlags.@"r", + mode: Mode = 0o666, + + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?Open { + const path = PathLike.fromJS(ctx, arguments, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "path must be a string or Buffer", + .{}, + ctx, + exception, + ); + } + return null; + }; + + if (exception.* != null) return null; + + var flags = FileSystemFlags.@"r"; + var mode: Mode = 0o666; + + if (arguments.next()) |val| { + arguments.eat(); + + if (val.isObject()) { + if (val.getIfPropertyExists(ctx.ptr(), "flags")) |flags_| { + flags = FileSystemFlags.fromJS(ctx, flags_, exception) orelse flags; + } + + if (val.getIfPropertyExists(ctx.ptr(), "mode")) |mode_| { + mode = JSC.Node.modeFromJS(ctx, mode_, exception) orelse mode; + } + } + } + + if (exception.* != null) return null; + + return Open{ + .path = path, + .flags = flags, + .mode = mode, + }; + } + }; + + /// Change the file system timestamps of the object referenced by `path`. + /// + /// The `atime` and `mtime` arguments follow these rules: + /// + /// * Values can be either numbers representing Unix epoch time in seconds,`Date`s, or a numeric string like `'123456789.0'`. + /// * If the value can not be converted to a number, or is `NaN`, `Infinity` or`-Infinity`, an `Error` will be thrown. + /// @since v0.4.2 + pub const Utimes = Lutimes; + + pub const Futimes = struct { + fd: FileDescriptor, + atime: TimeLike, + mtime: TimeLike, + + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?Futimes { + const fd = JSC.Node.fileDescriptorFromJS(ctx, arguments.next() orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "File descriptor is required", + .{}, + ctx, + exception, + ); + } + return null; + }, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "fd must be a number", + .{}, + ctx, + exception, + ); + } + return null; + }; + arguments.eat(); + if (exception.* != null) return null; + + const atime = JSC.Node.timeLikeFromJS(ctx, arguments.next() orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "atime is required", + .{}, + ctx, + exception, + ); + } + return null; + }, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "atime must be a number, Date or string", + .{}, + ctx, + exception, + ); + } + return null; + }; + + if (exception.* != null) return null; + + const mtime = JSC.Node.timeLikeFromJS(ctx, arguments.next() orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "mtime is required", + .{}, + ctx, + exception, + ); + } + return null; + }, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "mtime must be a number, Date or string", + .{}, + ctx, + exception, + ); + } + return null; + }; + + if (exception.* != null) return null; + + return Futimes{ + .fd = fd, + .atime = atime, + .mtime = mtime, + }; + } + }; + + pub const FSync = struct { + fd: FileDescriptor, + + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?FSync { + const fd = JSC.Node.fileDescriptorFromJS(ctx, arguments.next() orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "File descriptor is required", + .{}, + ctx, + exception, + ); + } + return null; + }, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "fd must be a number", + .{}, + ctx, + exception, + ); + } + return null; + }; + + if (exception.* != null) return null; + + return FSync{ + .fd = fd, + }; + } + }; + + /// Write `buffer` to the file specified by `fd`. If `buffer` is a normal object, it + /// must have an own `toString` function property. + /// + /// `offset` determines the part of the buffer to be written, and `length` is + /// an integer specifying the number of bytes to write. + /// + /// `position` refers to the offset from the beginning of the file where this data + /// should be written. If `typeof position !== 'number'`, the data will be written + /// at the current position. See [`pwrite(2)`](http://man7.org/linux/man-pages/man2/pwrite.2.html). + /// + /// The callback will be given three arguments `(err, bytesWritten, buffer)` where`bytesWritten` specifies how many _bytes_ were written from `buffer`. + /// + /// If this method is invoked as its `util.promisify()` ed version, it returns + /// a promise for an `Object` with `bytesWritten` and `buffer` properties. + /// + /// It is unsafe to use `fs.write()` multiple times on the same file without waiting + /// for the callback. For this scenario, {@link createWriteStream} is + /// recommended. + /// + /// On Linux, positional writes don't work when the file is opened in append mode. + /// The kernel ignores the position argument and always appends the data to + /// the end of the file. + /// @since v0.0.2 + /// + pub const Write = struct { + fd: FileDescriptor, + buffer: StringOrBuffer, + offset: u64 = 0, + length: u64 = std.math.maxInt(u64), + position: ?ReadPosition = null, + encoding: Encoding = Encoding.buffer, + + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?Write { + const fd = JSC.Node.fileDescriptorFromJS(ctx, arguments.next() orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "File descriptor is required", + .{}, + ctx, + exception, + ); + } + return null; + }, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "fd must be a number", + .{}, + ctx, + exception, + ); + } + return null; + }; + + arguments.eat(); + + if (exception.* != null) return null; + + const buffer = StringOrBuffer.fromJS(ctx.ptr(), arguments.next() orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "data is required", + .{}, + ctx, + exception, + ); + } + return null; + }, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "data must be a string or Buffer", + .{}, + ctx, + exception, + ); + } + return null; + }; + if (exception.* != null) return null; + + arguments.eat(); + + var args = Write{ + .fd = fd, + .buffer = buffer, + .encoding = switch (buffer) { + .string => Encoding.utf8, + .buffer => Encoding.buffer, + }, + }; + + // TODO: make this faster by passing argument count at comptime + if (arguments.next()) |current_| { + parse: { + var current = current_; + switch (buffer) { + // fs.write(fd, string[, position[, encoding]], callback) + .string => { + if (current.isNumber()) { + args.position = current.toU32(); + arguments.eat(); + current = arguments.next() orelse break :parse; + } + + if (current.isString()) { + args.encoding = Encoding.fromStringValue(current, ctx.ptr()) orelse Encoding.utf8; + arguments.eat(); + } + }, + // fs.write(fd, buffer[, offset[, length[, position]]], callback) + .buffer => { + if (!current.isNumber()) { + break :parse; + } + + if (!current.isNumber()) break :parse; + args.offset = current.toU32(); + arguments.eat(); + current = arguments.next() orelse break :parse; + + if (!current.isNumber()) break :parse; + args.length = current.toU32(); + arguments.eat(); + current = arguments.next() orelse break :parse; + + if (!current.isNumber()) break :parse; + args.position = current.toU32(); + arguments.eat(); + }, + } + } + } + + return args; + } + }; + + pub const Read = struct { + fd: FileDescriptor, + buffer: Buffer, + offset: u64 = 0, + length: u64 = std.math.maxInt(u64), + position: ?ReadPosition = null, + + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?Read { + const fd = JSC.Node.fileDescriptorFromJS(ctx, arguments.next() orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "File descriptor is required", + .{}, + ctx, + exception, + ); + } + return null; + }, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "fd must be a number", + .{}, + ctx, + exception, + ); + } + return null; + }; + + arguments.eat(); + + if (exception.* != null) return null; + + const buffer = Buffer.fromJS(ctx.ptr(), arguments.next() orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "buffer is required", + .{}, + ctx, + exception, + ); + } + return null; + }, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "buffer must be a Buffer", + .{}, + ctx, + exception, + ); + } + return null; + }; + + if (exception.* != null) return null; + + arguments.eat(); + + var args = Read{ + .fd = fd, + .buffer = buffer, + }; + + if (arguments.next()) |current| { + arguments.eat(); + if (current.isNumber()) { + args.offset = current.toU32(); + arguments.eat(); + + if (arguments.remaining.len < 2) { + JSC.throwInvalidArguments( + "length and position are required", + .{}, + ctx, + exception, + ); + + return null; + } + + args.length = arguments.remaining[0].toU32(); + + if (args.length == 0) { + JSC.throwInvalidArguments( + "length must be greater than 0", + .{}, + ctx, + exception, + ); + + return null; + } + + const position: i32 = if (arguments.remaining[1].isNumber()) + arguments.remaining[1].toInt32() + else + -1; + + args.position = if (position > -1) @intCast(ReadPosition, position) else null; + arguments.remaining = arguments.remaining[2..]; + } else if (current.isObject()) { + if (current.getIfPropertyExists(ctx.ptr(), "offset")) |num| { + args.offset = num.toU32(); + } + + if (current.getIfPropertyExists(ctx.ptr(), "length")) |num| { + args.length = num.toU32(); + } + + if (current.getIfPropertyExists(ctx.ptr(), "position")) |num| { + const position: i32 = if (num.isUndefinedOrNull()) -1 else num.toInt32(); + if (position > -1) { + args.position = @intCast(ReadPosition, position); + } + } + } + } + + return args; + } + }; + + /// Asynchronously reads the entire contents of a file. + /// @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + /// If a file descriptor is provided, the underlying file will _not_ be closed automatically. + /// @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + /// If a flag is not provided, it defaults to `'r'`. + pub const ReadFile = struct { + path: PathOrFileDescriptor, + encoding: Encoding = Encoding.utf8, + + flag: FileSystemFlags = FileSystemFlags.@"r", + + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?ReadFile { + const path = PathOrFileDescriptor.fromJS(ctx, arguments, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "path must be a string or a file descriptor", + .{}, + ctx, + exception, + ); + } + return null; + }; + + if (exception.* != null) return null; + + var encoding = Encoding.buffer; + var flag = FileSystemFlags.@"r"; + + if (arguments.next()) |arg| { + arguments.eat(); + if (arg.isString()) { + encoding = Encoding.fromStringValue(arg, ctx.ptr()) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "Invalid encoding", + .{}, + ctx, + exception, + ); + } + return null; + }; + } else if (arg.isObject()) { + if (arg.getIfPropertyExists(ctx.ptr(), "encoding")) |encoding_| { + if (!encoding_.isUndefinedOrNull()) { + encoding = Encoding.fromStringValue(encoding_, ctx.ptr()) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "Invalid encoding", + .{}, + ctx, + exception, + ); + } + return null; + }; + } + } + + if (arg.getIfPropertyExists(ctx.ptr(), "flag")) |flag_| { + flag = FileSystemFlags.fromJS(ctx, flag_, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "Invalid flag", + .{}, + ctx, + exception, + ); + } + return null; + }; + } + } + } + + // Note: Signal is not implemented + return ReadFile{ + .path = path, + .encoding = encoding, + .flag = flag, + }; + } + }; + + pub const WriteFile = struct { + encoding: Encoding = Encoding.utf8, + flag: FileSystemFlags = FileSystemFlags.@"w", + mode: Mode = 0o666, + file: PathOrFileDescriptor, + data: StringOrBuffer, + + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?WriteFile { + const file = PathOrFileDescriptor.fromJS(ctx, arguments, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "path must be a string or a file descriptor", + .{}, + ctx, + exception, + ); + } + return null; + }; + + if (exception.* != null) return null; + + const data = StringOrBuffer.fromJS(ctx.ptr(), arguments.next() orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "data is required", + .{}, + ctx, + exception, + ); + } + return null; + }, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "data must be a string or Buffer", + .{}, + ctx, + exception, + ); + } + return null; + }; + + if (exception.* != null) return null; + arguments.eat(); + + var encoding = Encoding.buffer; + var flag = FileSystemFlags.@"w"; + var mode: Mode = 0o666; + + if (arguments.next()) |arg| { + arguments.eat(); + if (arg.isString()) { + encoding = Encoding.fromStringValue(arg, ctx.ptr()) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "Invalid encoding", + .{}, + ctx, + exception, + ); + } + return null; + }; + } else if (arg.isObject()) { + if (arg.getIfPropertyExists(ctx.ptr(), "encoding")) |encoding_| { + if (!encoding_.isUndefinedOrNull()) { + encoding = Encoding.fromStringValue(encoding_, ctx.ptr()) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "Invalid encoding", + .{}, + ctx, + exception, + ); + } + return null; + }; + } + } + + if (arg.getIfPropertyExists(ctx.ptr(), "flag")) |flag_| { + flag = FileSystemFlags.fromJS(ctx, flag_, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "Invalid flag", + .{}, + ctx, + exception, + ); + } + return null; + }; + } + + if (arg.getIfPropertyExists(ctx.ptr(), "mode")) |mode_| { + mode = JSC.Node.modeFromJS(ctx, mode_, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "Invalid flag", + .{}, + ctx, + exception, + ); + } + return null; + }; + } + } + } + + // Note: Signal is not implemented + return WriteFile{ + .file = file, + .encoding = encoding, + .flag = flag, + .mode = mode, + .data = data, + }; + } + }; + + pub const AppendFile = WriteFile; + + pub const OpenDir = struct { + path: PathLike, + encoding: Encoding = Encoding.utf8, + + /// Number of directory entries that are buffered internally when reading from the directory. Higher values lead to better performance but higher memory usage. Default: 32 + buffer_size: c_int = 32, + + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?OpenDir { + const path = PathLike.fromJS(ctx, arguments, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "path must be a string or a file descriptor", + .{}, + ctx, + exception, + ); + } + return null; + }; + + if (exception.* != null) return null; + + var encoding = Encoding.buffer; + var buffer_size: c_int = 32; + + if (arguments.next()) |arg| { + arguments.eat(); + if (arg.isString()) { + encoding = Encoding.fromStringValue(arg, ctx.ptr()) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "Invalid encoding", + .{}, + ctx, + exception, + ); + } + return null; + }; + } else if (arg.isObject()) { + if (arg.getIfPropertyExists(ctx.ptr(), "encoding")) |encoding_| { + if (!encoding_.isUndefinedOrNull()) { + encoding = Encoding.fromStringValue(encoding_, ctx.ptr()) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "Invalid encoding", + .{}, + ctx, + exception, + ); + } + return null; + }; + } + } + + if (arg.getIfPropertyExists(ctx.ptr(), "bufferSize")) |buffer_size_| { + buffer_size = buffer_size_.toInt32(); + if (buffer_size < 0) { + if (exception.* == null) { + JSC.throwInvalidArguments( + "bufferSize must be > 0", + .{}, + ctx, + exception, + ); + } + return null; + } + } + } + } + + return OpenDir{ + .path = path, + .encoding = encoding, + .buffer_size = buffer_size, + }; + } + }; + pub const Exists = struct { + path: PathLike, + + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?Exists { + const path = PathLike.fromJS(ctx, arguments, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "path must be a string or buffer", + .{}, + ctx, + exception, + ); + } + return null; + }; + + if (exception.* != null) return null; + + return Exists{ + .path = path, + }; + } + }; + + pub const Access = struct { + path: PathLike, + mode: FileSystemFlags = FileSystemFlags.@"r", + + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?Access { + const path = PathLike.fromJS(ctx, arguments, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "path must be a string or buffer", + .{}, + ctx, + exception, + ); + } + return null; + }; + + if (exception.* != null) return null; + + var mode = FileSystemFlags.@"r"; + + if (arguments.next()) |arg| { + arguments.eat(); + if (arg.isString()) { + mode = FileSystemFlags.fromJS(ctx, arg, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "Invalid mode", + .{}, + ctx, + exception, + ); + } + return null; + }; + } + } + + return Access{ + .path = path, + .mode = mode, + }; + } + }; + + pub const CreateReadStream = struct { + file: PathOrFileDescriptor, + flags: FileSystemFlags = FileSystemFlags.@"r", + encoding: Encoding = Encoding.utf8, + mode: Mode = 0o666, + autoClose: bool = true, + emitClose: bool = true, + start: i32 = 0, + end: i32 = std.math.maxInt(i32), + highwater_mark: u32 = 64 * 1024, + global_object: *JSC.JSGlobalObject, + + pub fn copyToState(this: CreateReadStream, state: *JSC.Node.Readable.State) void { + state.encoding = this.encoding; + state.highwater_mark = this.highwater_mark; + state.start = this.start; + state.end = this.end; + } + + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?CreateReadStream { + var path = PathLike.fromJS(ctx, arguments, exception); + if (exception.* != null) return null; + if (path == null) arguments.eat(); + + var stream = CreateReadStream{ + .file = undefined, + .global_object = ctx.ptr(), + }; + var fd: FileDescriptor = std.math.maxInt(FileDescriptor); + + if (arguments.next()) |arg| { + arguments.eat(); + if (arg.isString()) { + stream.encoding = Encoding.fromStringValue(arg, ctx.ptr()) orelse { + if (exception.* != null) { + JSC.throwInvalidArguments( + "Invalid encoding", + .{}, + ctx, + exception, + ); + } + return null; + }; + } else if (arg.isObject()) { + if (arg.getIfPropertyExists(ctx.ptr(), "mode")) |mode_| { + stream.mode = JSC.Node.modeFromJS(ctx, mode_, exception) orelse { + if (exception.* != null) { + JSC.throwInvalidArguments( + "Invalid mode", + .{}, + ctx, + exception, + ); + } + return null; + }; + } + + if (arg.getIfPropertyExists(ctx.ptr(), "encoding")) |encoding| { + stream.encoding = Encoding.fromStringValue(encoding, ctx.ptr()) orelse { + if (exception.* != null) { + JSC.throwInvalidArguments( + "Invalid encoding", + .{}, + ctx, + exception, + ); + } + return null; + }; + } + + if (arg.getIfPropertyExists(ctx.ptr(), "flags")) |flags| { + stream.flags = FileSystemFlags.fromJS(ctx, flags, exception) orelse { + if (exception.* != null) { + JSC.throwInvalidArguments( + "Invalid flags", + .{}, + ctx, + exception, + ); + } + return null; + }; + } + + if (arg.getIfPropertyExists(ctx.ptr(), "fd")) |flags| { + fd = JSC.Node.fileDescriptorFromJS(ctx, flags, exception) orelse { + if (exception.* != null) { + JSC.throwInvalidArguments( + "Invalid file descriptor", + .{}, + ctx, + exception, + ); + } + return null; + }; + } + + if (arg.getIfPropertyExists(ctx.ptr(), "autoClose")) |autoClose| { + stream.autoClose = autoClose.toBoolean(); + } + + if (arg.getIfPropertyExists(ctx.ptr(), "emitClose")) |emitClose| { + stream.emitClose = emitClose.toBoolean(); + } + + if (arg.getIfPropertyExists(ctx.ptr(), "start")) |start| { + stream.start = start.toInt32(); + } + + if (arg.getIfPropertyExists(ctx.ptr(), "end")) |end| { + stream.end = end.toInt32(); + } + + if (arg.getIfPropertyExists(ctx.ptr(), "highwaterMark")) |highwaterMark| { + stream.highwater_mark = highwaterMark.toU32(); + } + } + } + + if (fd != std.math.maxInt(FileDescriptor)) { + stream.file = .{ .fd = fd }; + } else if (path) |path_| { + stream.file = .{ .path = path_ }; + } else { + JSC.throwInvalidArguments("Missing path or file descriptor", .{}, ctx, exception); + return null; + } + return stream; + } + }; + + pub const CreateWriteStream = struct { + file: PathOrFileDescriptor, + flags: FileSystemFlags = FileSystemFlags.@"w", + encoding: Encoding = Encoding.utf8, + mode: Mode = 0o666, + autoClose: bool = true, + emitClose: bool = true, + start: i32 = 0, + highwater_mark: u32 = 256 * 1024, + global_object: *JSC.JSGlobalObject, + + pub fn copyToState(this: CreateWriteStream, state: *JSC.Node.Writable.State) void { + state.encoding = this.encoding; + state.highwater_mark = this.highwater_mark; + state.start = this.start; + state.emit_close = this.emitClose; + } + + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?CreateWriteStream { + var path = PathLike.fromJS(ctx, arguments, exception); + if (exception.* != null) return null; + if (path == null) arguments.eat(); + + var stream = CreateWriteStream{ + .file = undefined, + .global_object = ctx.ptr(), + }; + var fd: FileDescriptor = std.math.maxInt(FileDescriptor); + + if (arguments.next()) |arg| { + arguments.eat(); + if (arg.isString()) { + stream.encoding = Encoding.fromStringValue(arg, ctx.ptr()) orelse { + if (exception.* != null) { + JSC.throwInvalidArguments( + "Invalid encoding", + .{}, + ctx, + exception, + ); + } + return null; + }; + } else if (arg.isObject()) { + if (arg.getIfPropertyExists(ctx.ptr(), "mode")) |mode_| { + stream.mode = JSC.Node.modeFromJS(ctx, mode_, exception) orelse { + if (exception.* != null) { + JSC.throwInvalidArguments( + "Invalid mode", + .{}, + ctx, + exception, + ); + } + return null; + }; + } + + if (arg.getIfPropertyExists(ctx.ptr(), "encoding")) |encoding| { + stream.encoding = Encoding.fromStringValue(encoding, ctx.ptr()) orelse { + if (exception.* != null) { + JSC.throwInvalidArguments( + "Invalid encoding", + .{}, + ctx, + exception, + ); + } + return null; + }; + } + + if (arg.getIfPropertyExists(ctx.ptr(), "flags")) |flags| { + stream.flags = FileSystemFlags.fromJS(ctx, flags, exception) orelse { + if (exception.* != null) { + JSC.throwInvalidArguments( + "Invalid flags", + .{}, + ctx, + exception, + ); + } + return null; + }; + } + + if (arg.getIfPropertyExists(ctx.ptr(), "fd")) |flags| { + fd = JSC.Node.fileDescriptorFromJS(ctx, flags, exception) orelse { + if (exception.* != null) { + JSC.throwInvalidArguments( + "Invalid file descriptor", + .{}, + ctx, + exception, + ); + } + return null; + }; + } + + if (arg.getIfPropertyExists(ctx.ptr(), "autoClose")) |autoClose| { + stream.autoClose = autoClose.toBoolean(); + } + + if (arg.getIfPropertyExists(ctx.ptr(), "emitClose")) |emitClose| { + stream.emitClose = emitClose.toBoolean(); + } + + if (arg.getIfPropertyExists(ctx.ptr(), "start")) |start| { + stream.start = start.toInt32(); + } + } + } + + if (fd != std.math.maxInt(FileDescriptor)) { + stream.file = .{ .fd = fd }; + } else if (path) |path_| { + stream.file = .{ .path = path_ }; + } else { + JSC.throwInvalidArguments("Missing path or file descriptor", .{}, ctx, exception); + return null; + } + return stream; + } + }; + + pub const FdataSync = struct { + fd: FileDescriptor, + + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?FdataSync { + const fd = JSC.Node.fileDescriptorFromJS(ctx, arguments.next() orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "File descriptor is required", + .{}, + ctx, + exception, + ); + } + return null; + }, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "fd must be a number", + .{}, + ctx, + exception, + ); + } + return null; + }; + + if (exception.* != null) return null; + + return FdataSync{ + .fd = fd, + }; + } + }; + + pub const CopyFile = struct { + src: PathLike, + dest: PathLike, + mode: Constants.Copyfile, + + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?CopyFile { + const src = PathLike.fromJS(ctx, arguments, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "src must be a string or buffer", + .{}, + ctx, + exception, + ); + } + return null; + }; + + if (exception.* != null) return null; + + const dest = PathLike.fromJS(ctx, arguments, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "dest must be a string or buffer", + .{}, + ctx, + exception, + ); + } + return null; + }; + + if (exception.* != null) return null; + + var mode: i32 = 0; + if (arguments.next()) |arg| { + arguments.eat(); + if (arg.isNumber()) { + mode = arg.toInt32(); + } + } + + return CopyFile{ + .src = src, + .dest = dest, + .mode = @intToEnum(Constants.Copyfile, mode), + }; + } + }; + + pub const WriteEv = struct { + fd: FileDescriptor, + buffers: []const ArrayBuffer, + position: ReadPosition, + }; + + pub const ReadEv = struct { + fd: FileDescriptor, + buffers: []ArrayBuffer, + position: ReadPosition, + }; + + pub const Copy = struct { + pub const FilterCallback = fn (source: string, destination: string) bool; + /// Dereference symlinks + /// @default false + dereference: bool = false, + + /// When `force` is `false`, and the destination + /// exists, throw an error. + /// @default false + errorOnExist: bool = false, + + /// Function to filter copied files/directories. Return + /// `true` to copy the item, `false` to ignore it. + filter: ?FilterCallback = null, + + /// Overwrite existing file or directory. _The copy + /// operation will ignore errors if you set this to false and the destination + /// exists. Use the `errorOnExist` option to change this behavior. + /// @default true + force: bool = true, + + /// When `true` timestamps from `src` will + /// be preserved. + /// @default false + preserve_timestamps: bool = false, + + /// Copy directories recursively. + /// @default false + recursive: bool = false, + }; + + pub const UnwatchFile = void; + pub const Watch = void; + pub const WatchFile = void; + pub const Fsync = struct { + fd: FileDescriptor, + + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?Fsync { + const fd = JSC.Node.fileDescriptorFromJS(ctx, arguments.next() orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "File descriptor is required", + .{}, + ctx, + exception, + ); + } + return null; + }, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "fd must be a number", + .{}, + ctx, + exception, + ); + } + return null; + }; + + if (exception.* != null) return null; + + return Fsync{ + .fd = fd, + }; + } + }; +}; + +const Constants = struct { + // File Access Constants + /// Constant for fs.access(). File is visible to the calling process. + pub const F_OK = std.os.F_OK; + /// Constant for fs.access(). File can be read by the calling process. + pub const R_OK = std.os.R_OK; + /// Constant for fs.access(). File can be written by the calling process. + pub const W_OK = std.os.W_OK; + /// Constant for fs.access(). File can be executed by the calling process. + pub const X_OK = std.os.X_OK; + // File Copy Constants + + pub const Copyfile = enum(i32) { + _, + pub const exclusive = 1; + pub const clone = 2; + pub const force = 4; + + pub inline fn isForceClone(this: Copyfile) bool { + return (@enumToInt(this) & COPYFILE_FICLONE_FORCE) != 0; + } + + pub inline fn shouldntOverwrite(this: Copyfile) bool { + return (@enumToInt(this) & COPYFILE_EXCL) != 0; + } + + pub inline fn canUseClone(this: Copyfile) bool { + _ = this; + return Environment.isMac; + // return (@enumToInt(this) | COPYFILE_FICLONE) != 0; + } + }; + + /// Constant for fs.copyFile. Flag indicating the destination file should not be overwritten if it already exists. + pub const COPYFILE_EXCL: i32 = 1 << Copyfile.exclusive; + + /// + /// Constant for fs.copyFile. copy operation will attempt to create a copy-on-write reflink. + /// If the underlying platform does not support copy-on-write, then a fallback copy mechanism is used. + pub const COPYFILE_FICLONE: i32 = 1 << Copyfile.clone; + /// + /// Constant for fs.copyFile. Copy operation will attempt to create a copy-on-write reflink. + /// If the underlying platform does not support copy-on-write, then the operation will fail with an error. + pub const COPYFILE_FICLONE_FORCE: i32 = 1 << Copyfile.force; + // File Open Constants + /// Constant for fs.open(). Flag indicating to open a file for read-only access. + pub const O_RDONLY = std.os.O.RDONLY; + /// Constant for fs.open(). Flag indicating to open a file for write-only access. + pub const O_WRONLY = std.os.O.WRONLY; + /// Constant for fs.open(). Flag indicating to open a file for read-write access. + pub const O_RDWR = std.os.O.RDWR; + /// Constant for fs.open(). Flag indicating to create the file if it does not already exist. + pub const O_CREAT = std.os.O.CREAT; + /// Constant for fs.open(). Flag indicating that opening a file should fail if the O_CREAT flag is set and the file already exists. + pub const O_EXCL = std.os.O.EXCL; + + /// + /// Constant for fs.open(). Flag indicating that if path identifies a terminal device, + /// opening the path shall not cause that terminal to become the controlling terminal for the process + /// (if the process does not already have one). + pub const O_NOCTTY = std.os.O.NOCTTY; + /// Constant for fs.open(). Flag indicating that if the file exists and is a regular file, and the file is opened successfully for write access, its length shall be truncated to zero. + pub const O_TRUNC = std.os.O.TRUNC; + /// Constant for fs.open(). Flag indicating that data will be appended to the end of the file. + pub const O_APPEND = std.os.O.APPEND; + /// Constant for fs.open(). Flag indicating that the open should fail if the path is not a directory. + pub const O_DIRECTORY = std.os.O.DIRECTORY; + + /// + /// constant for fs.open(). + /// Flag indicating reading accesses to the file system will no longer result in + /// an update to the atime information associated with the file. + /// This flag is available on Linux operating systems only. + pub const O_NOATIME = std.os.O.NOATIME; + /// Constant for fs.open(). Flag indicating that the open should fail if the path is a symbolic link. + pub const O_NOFOLLOW = std.os.O.NOFOLLOW; + /// Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O. + pub const O_SYNC = std.os.O.SYNC; + /// Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O with write operations waiting for data integrity. + pub const O_DSYNC = std.os.O.DSYNC; + /// Constant for fs.open(). Flag indicating to open the symbolic link itself rather than the resource it is pointing to. + pub const O_SYMLINK = std.os.O.SYMLINK; + /// Constant for fs.open(). When set, an attempt will be made to minimize caching effects of file I/O. + pub const O_DIRECT = std.os.O.DIRECT; + /// Constant for fs.open(). Flag indicating to open the file in nonblocking mode when possible. + pub const O_NONBLOCK = std.os.O.NONBLOCK; + // File Type Constants + /// Constant for fs.Stats mode property for determining a file's type. Bit mask used to extract the file type code. + pub const S_IFMT = std.os.S.IFMT; + /// Constant for fs.Stats mode property for determining a file's type. File type constant for a regular file. + pub const S_IFREG = std.os.S.IFREG; + /// Constant for fs.Stats mode property for determining a file's type. File type constant for a directory. + pub const S_IFDIR = std.os.S.IFDIR; + /// Constant for fs.Stats mode property for determining a file's type. File type constant for a character-oriented device file. + pub const S_IFCHR = std.os.S.IFCHR; + /// Constant for fs.Stats mode property for determining a file's type. File type constant for a block-oriented device file. + pub const S_IFBLK = std.os.S.IFBLK; + /// Constant for fs.Stats mode property for determining a file's type. File type constant for a FIFO/pipe. + pub const S_IFIFO = std.os.S.IFIFO; + /// Constant for fs.Stats mode property for determining a file's type. File type constant for a symbolic link. + pub const S_IFLNK = std.os.S.IFLNK; + /// Constant for fs.Stats mode property for determining a file's type. File type constant for a socket. + pub const S_IFSOCK = std.os.S.IFSOCK; + // File Mode Constants + /// Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by owner. + pub const S_IRWXU = std.os.S.IRWXU; + /// Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by owner. + pub const S_IRUSR = std.os.S.IRUSR; + /// Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by owner. + pub const S_IWUSR = std.os.S.IWUSR; + /// Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by owner. + pub const S_IXUSR = std.os.S.IXUSR; + /// Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by group. + pub const S_IRWXG = std.os.S.IRWXG; + /// Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by group. + pub const S_IRGRP = std.os.S.IRGRP; + /// Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by group. + pub const S_IWGRP = std.os.S.IWGRP; + /// Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by group. + pub const S_IXGRP = std.os.S.IXGRP; + /// Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by others. + pub const S_IRWXO = std.os.S.IRWXO; + /// Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by others. + pub const S_IROTH = std.os.S.IROTH; + /// Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by others. + pub const S_IWOTH = std.os.S.IWOTH; + /// Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by others. + pub const S_IXOTH = std.os.S.IXOTH; + + /// + /// When set, a memory file mapping is used to access the file. This flag + /// is available on Windows operating systems only. On other operating systems, + /// this flag is ignored. + pub const UV_FS_O_FILEMAP = 49152; +}; + +const Return = struct { + pub const Access = void; + pub const AppendFile = void; + pub const Close = void; + pub const CopyFile = void; + pub const Exists = bool; + pub const Fchmod = void; + pub const Chmod = void; + pub const Fchown = void; + pub const Fdatasync = void; + pub const Fstat = Stats; + pub const Rm = void; + pub const Fsync = void; + pub const Ftruncate = void; + pub const Futimes = void; + pub const Lchmod = void; + pub const Lchown = void; + pub const Link = void; + pub const Lstat = Stats; + pub const Mkdir = string; + pub const Mkdtemp = PathString; + pub const Open = FileDescriptor; + pub const WriteFile = void; + pub const Read = struct { + bytes_read: u32, + buffer: Buffer, + const fields = .{ + .@"bytesRead" = JSC.ZigString.init("bytesRead"), + .@"buffer" = JSC.ZigString.init("buffer"), + }; + // Excited for the issue that's like "cannot read file bigger than 2 GB" + pub fn toJS(this: Read, ctx: JSC.C.JSContextRef, exception: JSC.C.ExceptionRef) JSC.C.JSValueRef { + return JSC.JSValue.createObject2( + ctx.ptr(), + &fields.bytesRead, + &fields.buffer, + JSC.JSValue.jsNumberFromInt32(@intCast(i32, @minimum(std.math.maxInt(i32), this.bytes_read))), + JSC.JSValue.fromRef(this.buffer.toJS(ctx, exception)), + ).asObjectRef(); + } + }; + pub const Write = struct { + bytes_written: u32, + buffer: StringOrBuffer, + const fields = .{ + .@"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: Write, ctx: JSC.C.JSContextRef, exception: JSC.C.ExceptionRef) JSC.C.JSValueRef { + return JSC.JSValue.createObject2( + ctx.ptr(), + &fields.bytesWritten, + &fields.buffer, + JSC.JSValue.jsNumberFromInt32(@intCast(i32, @minimum(std.math.maxInt(i32), this.bytes_written))), + JSC.JSValue.fromRef(this.buffer.toJS(ctx, exception)), + ).asObjectRef(); + } + }; + + pub const Readdir = union(Tag) { + with_file_types: []const DirEnt, + buffers: []const Buffer, + files: []const PathString, + + pub const Tag = enum { + with_file_types, + buffers, + files, + }; + + pub fn toJS(this: Readdir, ctx: JSC.C.JSContextRef, exception: JSC.C.ExceptionRef) JSC.C.JSValueRef { + return switch (this) { + .with_file_types => JSC.To.JS.withType([]const DirEnt, this.with_file_types, ctx, exception), + .buffers => JSC.To.JS.withType([]const Buffer, this.buffers, ctx, exception), + .files => JSC.To.JS.withTypeClone([]const PathString, this.files, ctx, exception, true), + }; + } + }; + pub const ReadFile = StringOrBuffer; + pub const Readlink = StringOrBuffer; + pub const Realpath = StringOrBuffer; + pub const RealpathNative = Realpath; + pub const Rename = void; + pub const Rmdir = void; + pub const Stat = Stats; + + pub const Symlink = void; + pub const Truncate = void; + pub const Unlink = void; + pub const UnwatchFile = void; + pub const Watch = void; + pub const WatchFile = void; + pub const Utimes = void; + + pub const CreateReadStream = *JSC.Node.Stream; + pub const CreateWriteStream = *JSC.Node.Stream; + pub const Chown = void; + pub const Lutimes = void; +}; + +/// Bun's implementation of the Node.js "fs" module +/// https://nodejs.org/api/fs.html +/// https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/node/fs.d.ts +pub const NodeFS = struct { + async_io: *AsyncIO, + + /// 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. + /// That means a stack-allocated buffer won't suffice. Instead, we re-use + /// the heap allocated buffer on the NodefS struct + sync_error_buf: [std.fs.MAX_PATH_BYTES]u8 = undefined, + + pub const ReturnType = Return; + + pub fn access(this: *NodeFS, args: Arguments.Access, comptime _: Flavor) Maybe(Return.Access) { + var path = args.path.sliceZ(&this.sync_error_buf); + const rc = Syscall.system.access(path, @enumToInt(args.mode)); + return Maybe(Return.Access).errnoSysP(rc, .access, path) orelse Maybe(Return.Access).success; + } + + pub fn appendFile(this: *NodeFS, args: Arguments.AppendFile, comptime flavor: Flavor) Maybe(Return.AppendFile) { + var data = args.data.slice(); + + switch (args.file) { + .fd => |fd| { + switch (comptime flavor) { + .sync => { + while (data.len > 0) { + const written = switch (Syscall.write(fd, data)) { + .result => |result| result, + .err => |err| return .{ .err = err }, + }; + data = data[written..]; + } + + return Maybe(Return.AppendFile).success; + }, + else => { + _ = this; + @compileError("Not implemented yet"); + }, + } + }, + .path => |path_| { + const path = path_.sliceZ(&this.sync_error_buf); + switch (comptime flavor) { + .sync => { + const fd = switch (Syscall.open(path, @enumToInt(FileSystemFlags.@"a"), 000666)) { + .result => |result| result, + .err => |err| return .{ .err = err }, + }; + + defer { + _ = Syscall.close(fd); + } + + while (data.len > 0) { + const written = switch (Syscall.write(fd, data)) { + .result => |result| result, + .err => |err| return .{ .err = err }, + }; + data = data[written..]; + } + + return Maybe(Return.AppendFile).success; + }, + else => { + _ = this; + @compileError("Not implemented yet"); + }, + } + }, + } + + return Maybe(Return.AppendFile).todo; + } + + pub fn close(this: *NodeFS, args: Arguments.Close, comptime flavor: Flavor) Maybe(Return.Close) { + switch (comptime flavor) { + .sync => { + return if (Syscall.close(args.fd)) |err| .{ .err = err } else Maybe(Return.Close).success; + }, + else => { + _ = this; + }, + } + + return .{ .err = Syscall.Error.todo }; + } + + /// https://github.com/libuv/libuv/pull/2233 + /// https://github.com/pnpm/pnpm/issues/2761 + /// https://github.com/libuv/libuv/pull/2578 + /// https://github.com/nodejs/node/issues/34624 + pub fn copyFile(this: *NodeFS, args: Arguments.CopyFile, comptime flavor: Flavor) Maybe(Return.CopyFile) { + const ret = Maybe(Return.CopyFile); + + switch (comptime flavor) { + .sync => { + var src_buf: [std.fs.MAX_PATH_BYTES]u8 = undefined; + var dest_buf: [std.fs.MAX_PATH_BYTES]u8 = undefined; + var src = args.src.sliceZ(&src_buf); + var dest = args.dest.sliceZ(&dest_buf); + + if (comptime Environment.isMac) { + if (args.mode.isForceClone()) { + // https://www.manpagez.com/man/2/clonefile/ + return ret.errnoSysP(C.clonefile(src, dest, 0), .clonefile, src) orelse ret.success; + } + + var mode: Mode = C.darwin.COPYFILE_ACL | C.darwin.COPYFILE_DATA; + if (args.mode.shouldntOverwrite()) { + mode |= C.darwin.COPYFILE_EXCL; + } + + return ret.errnoSysP(C.copyfile(src, dest, null, mode), .copyfile, src) orelse ret.success; + } + + if (comptime Environment.isLinux) { + const src_fd = switch (Syscall.open(src, std.os.O.RDONLY, 0644)) { + .result => |result| result, + .err => |err| return .{ .err = err }, + }; + defer { + _ = Syscall.close(src_fd); + } + + const stat_: linux.Stat = switch (Syscall.fstat(src_fd)) { + .result => |result| result, + .err => |err| return Maybe(Return.CopyFile){ .err = err }, + }; + + if (!os.S.ISREG(stat_.mode)) { + return Maybe(Return.CopyFile){ .err = .{ .errno = @enumToInt(C.SystemErrno.ENOTSUP) } }; + } + + var flags: Mode = std.os.O.CREAT | std.os.O.WRONLY | std.os.O.TRUNC; + if (args.mode.shouldntOverwrite()) { + flags |= std.os.O.EXCL; + } + + const dest_fd = switch (Syscall.open(dest, flags, flags)) { + .result => |result| result, + .err => |err| return Maybe(Return.CopyFile){ .err = err }, + }; + defer { + _ = Syscall.close(dest_fd); + } + + var off_in_copy = @bitCast(i64, @as(u64, 0)); + var off_out_copy = @bitCast(i64, @as(u64, 0)); + + // https://manpages.debian.org/testing/manpages-dev/ioctl_ficlone.2.en.html + if (args.mode.isForceClone()) { + return Maybe(Return.CopyFile).todo; + } + + var size = @intCast(usize, @maximum(stat_.size, 0)); + while (size > 0) { + // Linux Kernel 5.3 or later + const written = linux.copy_file_range(src_fd, &off_in_copy, dest_fd, &off_out_copy, size, 0); + if (ret.errnoSysP(written, .copy_file_range, dest)) |err| return err; + // wrote zero bytes means EOF + if (written == 0) break; + size -|= written; + } + + return ret.success; + } + }, + else => { + _ = args; + _ = this; + _ = flavor; + }, + } + + return Maybe(Return.CopyFile).todo; + } + pub fn exists(this: *NodeFS, args: Arguments.Exists, comptime flavor: Flavor) Maybe(Return.Exists) { + const Ret = Maybe(Return.Exists); + const path = args.path.sliceZ(&this.sync_error_buf); + switch (comptime flavor) { + .sync => { + // access() may not work correctly on NFS file systems with UID + // mapping enabled, because UID mapping is done on the server and + // hidden from the client, which checks permissions. Similar + // problems can occur to FUSE mounts. + const rc = (system.access(path, std.os.F_OK)); + return Ret{ .result = rc == 0 }; + }, + else => {}, + } + _ = args; + _ = this; + _ = flavor; + return Ret.todo; + } + + pub fn chown(this: *NodeFS, args: Arguments.Chown, comptime flavor: Flavor) Maybe(Return.Chown) { + const path = args.path.sliceZ(&this.sync_error_buf); + + switch (comptime flavor) { + .sync => return Syscall.chown(path, args.uid, args.gid), + else => {}, + } + _ = args; + _ = this; + _ = flavor; + return Maybe(Return.Chown).todo; + } + + /// This should almost never be async + pub fn chmod(this: *NodeFS, args: Arguments.Chmod, comptime flavor: Flavor) Maybe(Return.Chmod) { + const path = args.path.sliceZ(&this.sync_error_buf); + + switch (comptime flavor) { + .sync => { + return Maybe(Return.Chmod).errnoSysP(C.chmod(path, args.mode), .chmod, path) orelse + Maybe(Return.Chmod).success; + }, + else => {}, + } + _ = args; + _ = this; + _ = flavor; + return Maybe(Return.Chmod).todo; + } + + /// This should almost never be async + pub fn fchmod(this: *NodeFS, args: Arguments.FChmod, comptime flavor: Flavor) Maybe(Return.Fchmod) { + switch (comptime flavor) { + .sync => { + return Syscall.fchmod(args.fd, args.mode); + }, + else => {}, + } + _ = args; + _ = this; + _ = flavor; + return Maybe(Return.Fchmod).todo; + } + pub fn fchown(this: *NodeFS, args: Arguments.Fchown, comptime flavor: Flavor) Maybe(Return.Fchown) { + switch (comptime flavor) { + .sync => { + return Maybe(Return.Fchown).errnoSys(C.fchown(args.fd, args.uid, args.gid), .fchown) orelse + Maybe(Return.Fchown).success; + }, + else => {}, + } + _ = args; + _ = this; + _ = flavor; + return Maybe(Return.Fchown).todo; + } + pub fn fdatasync(this: *NodeFS, args: Arguments.FdataSync, comptime flavor: Flavor) Maybe(Return.Fdatasync) { + switch (comptime flavor) { + .sync => return Maybe(Return.Fdatasync).errnoSys(system.fdatasync(args.fd), .fdatasync) orelse + Maybe(Return.Fdatasync).success, + else => {}, + } + + _ = args; + _ = this; + _ = flavor; + return Maybe(Return.Fdatasync).todo; + } + pub fn fstat(this: *NodeFS, args: Arguments.Fstat, comptime flavor: Flavor) Maybe(Return.Fstat) { + if (args.big_int) return Maybe(Return.Fstat).todo; + + switch (comptime flavor) { + .sync => { + return switch (Syscall.fstat(args.fd)) { + .result => |result| Maybe(Return.Fstat){ .result = Stats.init(result) }, + .err => |err| Maybe(Return.Fstat){ .err = err }, + }; + }, + else => {}, + } + + _ = args; + _ = this; + _ = flavor; + return Maybe(Return.Fstat).todo; + } + + pub fn fsync(this: *NodeFS, args: Arguments.Fsync, comptime flavor: Flavor) Maybe(Return.Fsync) { + switch (comptime flavor) { + .sync => return Maybe(Return.Fsync).errnoSys(system.fsync(args.fd), .fsync) orelse + Maybe(Return.Fsync).success, + else => {}, + } + + _ = args; + _ = this; + _ = flavor; + return Maybe(Return.Fsync).todo; + } + + pub fn ftruncate(this: *NodeFS, args: Arguments.FTruncate, comptime flavor: Flavor) Maybe(Return.Ftruncate) { + switch (comptime flavor) { + .sync => return Maybe(Return.Ftruncate).errnoSys(system.ftruncate(args.fd, args.len orelse 0), .ftruncate) orelse + Maybe(Return.Ftruncate).success, + else => {}, + } + + _ = args; + _ = this; + _ = flavor; + return Maybe(Return.Ftruncate).todo; + } + pub fn futimes(this: *NodeFS, args: Arguments.Futimes, comptime flavor: Flavor) Maybe(Return.Futimes) { + var times = [2]std.os.timespec{ + .{ + .tv_sec = args.mtime, + .tv_nsec = 0, + }, + .{ + .tv_sec = args.atime, + .tv_nsec = 0, + }, + }; + + switch (comptime flavor) { + .sync => return if (Maybe(Return.Futimes).errnoSys(system.futimens(args.fd, ×), .futimens)) |err| + err + else + Maybe(Return.Futimes).success, + else => {}, + } + + _ = args; + _ = this; + _ = flavor; + return Maybe(Return.Futimes).todo; + } + + pub fn lchmod(this: *NodeFS, args: Arguments.LCHmod, comptime flavor: Flavor) Maybe(Return.Lchmod) { + const path = args.path.sliceZ(&this.sync_error_buf); + + switch (comptime flavor) { + .sync => { + return Maybe(Return.Lchmod).errnoSysP(C.lchmod(path, args.mode), .lchmod, path) orelse + Maybe(Return.Lchmod).success; + }, + else => {}, + } + _ = args; + _ = this; + _ = flavor; + return Maybe(Return.Lchmod).todo; + } + + pub fn lchown(this: *NodeFS, args: Arguments.LChown, comptime flavor: Flavor) Maybe(Return.Lchown) { + const path = args.path.sliceZ(&this.sync_error_buf); + + switch (comptime flavor) { + .sync => { + return Maybe(Return.Lchown).errnoSysP(C.lchown(path, args.uid, args.gid), .lchown, path) orelse + Maybe(Return.Lchown).success; + }, + else => {}, + } + _ = args; + _ = this; + _ = flavor; + return Maybe(Return.Lchown).todo; + } + pub fn link(this: *NodeFS, args: Arguments.Link, comptime flavor: Flavor) Maybe(Return.Link) { + var new_path_buf: [std.fs.MAX_PATH_BYTES]u8 = undefined; + const from = args.old_path.sliceZ(&this.sync_error_buf); + const to = args.new_path.sliceZ(&new_path_buf); + + switch (comptime flavor) { + .sync => { + return Maybe(Return.Link).errnoSysP(system.link(from, to, 0), .link, from) orelse + Maybe(Return.Link).success; + }, + else => {}, + } + + _ = args; + _ = this; + _ = flavor; + return Maybe(Return.Link).todo; + } + pub fn lstat(this: *NodeFS, args: Arguments.Lstat, comptime flavor: Flavor) Maybe(Return.Lstat) { + if (args.big_int) return Maybe(Return.Lstat).todo; + + switch (comptime flavor) { + .sync => { + return switch (Syscall.lstat( + args.path.sliceZ( + &this.sync_error_buf, + ), + )) { + .result => |result| Maybe(Return.Lstat){ .result = Return.Lstat.init(result) }, + .err => |err| Maybe(Return.Lstat){ .err = err }, + }; + }, + else => {}, + } + + _ = args; + _ = this; + _ = flavor; + return Maybe(Return.Lstat).todo; + } + + pub fn mkdir(this: *NodeFS, args: Arguments.Mkdir, comptime flavor: Flavor) Maybe(Return.Mkdir) { + return if (args.recursive) mkdirRecursive(this, args, flavor) else mkdirNonRecursive(this, args, flavor); + } + // Node doesn't absolute the path so we don't have to either + fn mkdirNonRecursive(this: *NodeFS, args: Arguments.Mkdir, comptime flavor: Flavor) Maybe(Return.Mkdir) { + switch (comptime flavor) { + .sync => { + const path = args.path.sliceZ(&this.sync_error_buf); + return switch (Syscall.mkdir(path, args.mode)) { + .result => Maybe(Return.Mkdir){ .result = "" }, + .err => |err| Maybe(Return.Mkdir){ .err = err }, + }; + }, + else => {}, + } + _ = args; + _ = this; + _ = flavor; + return Maybe(Return.Mkdir).todo; + } + + // TODO: windows + // TODO: verify this works correctly with unicode codepoints + fn mkdirRecursive(this: *NodeFS, args: Arguments.Mkdir, comptime flavor: Flavor) Maybe(Return.Mkdir) { + const Option = Maybe(Return.Mkdir); + if (comptime Environment.isWindows) @compileError("This needs to be implemented on Windows."); + + switch (comptime flavor) { + // The sync version does no allocation except when returning the path + .sync => { + var buf: [std.fs.MAX_PATH_BYTES]u8 = undefined; + const path = args.path.sliceZWithForceCopy(&buf, true); + const len = @truncate(u16, path.len); + + // First, attempt to create the desired directory + // If that fails, then walk back up the path until we have a match + switch (Syscall.mkdir(path, args.mode)) { + .err => |err| { + switch (err.getErrno()) { + else => { + @memcpy(&this.sync_error_buf, path.ptr, len); + return .{ .err = err.withPath(this.sync_error_buf[0..len]) }; + }, + + .EXIST => { + return Option{ .result = "" }; + }, + // continue + .NOENT => {}, + } + }, + .result => { + return Option{ .result = args.path.slice() }; + }, + } + + var working_mem = &this.sync_error_buf; + @memcpy(working_mem, path.ptr, len); + + var i: u16 = len - 1; + + // iterate backwards until creating the directory works successfully + while (i > 0) : (i -= 1) { + if (path[i] == std.fs.path.sep) { + working_mem[i] = 0; + var parent: [:0]u8 = working_mem[0..i :0]; + + switch (Syscall.mkdir(parent, args.mode)) { + .err => |err| { + working_mem[i] = std.fs.path.sep; + switch (err.getErrno()) { + .EXIST => { + // Handle race condition + break; + }, + .NOENT => { + continue; + }, + else => return .{ .err = err.withPath(parent) }, + } + }, + .result => { + // We found a parent that worked + working_mem[i] = std.fs.path.sep; + break; + }, + } + } + } + var first_match: u16 = i; + i += 1; + // after we find one that works, we go forward _after_ the first working directory + while (i < len) : (i += 1) { + if (path[i] == std.fs.path.sep) { + working_mem[i] = 0; + var parent: [:0]u8 = working_mem[0..i :0]; + + switch (Syscall.mkdir(parent, args.mode)) { + .err => |err| { + working_mem[i] = std.fs.path.sep; + switch (err.getErrno()) { + .EXIST => { + std.debug.assert(false); + continue; + }, + else => return .{ .err = err }, + } + }, + + .result => { + working_mem[i] = std.fs.path.sep; + }, + } + } + } + + // Our final directory will not have a trailing separator + // so we have to create it once again + switch (Syscall.mkdir(working_mem[0..len :0], args.mode)) { + .err => |err| { + switch (err.getErrno()) { + // handle the race condition + .EXIST => { + var display_path: []const u8 = ""; + if (first_match != std.math.maxInt(u16)) { + // TODO: this leaks memory + display_path = _global.default_allocator.dupe(u8, display_path[0..first_match]) catch unreachable; + } + return Option{ .result = display_path }; + }, + + // NOENT shouldn't happen here + else => return .{ + .err = err.withPath(path), + }, + } + }, + .result => { + var display_path = args.path.slice(); + if (first_match != std.math.maxInt(u16)) { + // TODO: this leaks memory + display_path = _global.default_allocator.dupe(u8, display_path[0..first_match]) catch unreachable; + } + return Option{ .result = display_path }; + }, + } + }, + else => {}, + } + + _ = args; + _ = this; + _ = flavor; + return Maybe(Return.Mkdir).todo; + } + + pub fn mkdtemp(this: *NodeFS, args: Arguments.MkdirTemp, comptime flavor: Flavor) Maybe(Return.Mkdtemp) { + var prefix_buf = &this.sync_error_buf; + prefix_buf[0] = 0; + const len = args.prefix.len; + if (len > 0) { + @memcpy(prefix_buf, args.prefix.ptr, len); + prefix_buf[len] = 0; + } + + const rc = C.mkdtemp(prefix_buf); + switch (std.c.getErrno(@ptrToInt(rc))) { + .SUCCESS => {}, + else => |errno| return .{ .err = Syscall.Error{ .errno = @truncate(Syscall.Error.Int, @enumToInt(errno)), .syscall = .mkdtemp } }, + } + + _ = this; + _ = flavor; + return .{ + .result = PathString.init(_global.default_allocator.dupe(u8, std.mem.span(rc.?)) catch unreachable), + }; + } + pub fn open(this: *NodeFS, args: Arguments.Open, comptime flavor: Flavor) Maybe(Return.Open) { + switch (comptime flavor) { + // The sync version does no allocation except when returning the path + .sync => { + const path = args.path.sliceZ(&this.sync_error_buf); + return switch (Syscall.open(path, @enumToInt(args.flags), args.mode)) { + .err => |err| .{ + .err = err.withPath(args.path.slice()), + }, + .result => |fd| .{ .result = fd }, + }; + }, + else => {}, + } + + _ = args; + _ = this; + _ = flavor; + return Maybe(Return.Open).todo; + } + pub fn openDir(this: *NodeFS, args: Arguments.OpenDir, comptime flavor: Flavor) Maybe(Return.OpenDir) { + _ = args; + _ = this; + _ = flavor; + return Maybe(Return.OpenDir).todo; + } + + fn _read(this: *NodeFS, args: Arguments.Read, comptime flavor: Flavor) Maybe(Return.Read) { + _ = args; + _ = this; + _ = flavor; + std.debug.assert(args.position == null); + + switch (comptime flavor) { + // The sync version does no allocation except when returning the path + .sync => { + var buf = args.buffer.slice(); + buf = buf[@minimum(args.offset, buf.len)..]; + buf = buf[0..@minimum(buf.len, args.length)]; + + return switch (Syscall.read(args.fd, buf)) { + .err => |err| .{ + .err = err, + }, + .result => |amt| .{ + .result = .{ .bytes_read = @truncate(u32, amt), .buffer = args.buffer }, + }, + }; + }, + else => {}, + } + + return Maybe(Return.Read).todo; + } + + fn _pread(this: *NodeFS, args: Arguments.Read, comptime flavor: Flavor) Maybe(Return.Read) { + _ = args; + _ = this; + _ = flavor; + + switch (comptime flavor) { + // The sync version does no allocation except when returning the path + .sync => { + var buf = args.buffer.slice(); + buf = buf[@minimum(args.offset, buf.len)..]; + buf = buf[0..@minimum(buf.len, args.length)]; + + return switch (Syscall.pread(args.fd, buf, args.position.?)) { + .err => |err| .{ + .err = err, + }, + .result => |amt| .{ + .result = .{ .bytes_read = @truncate(u32, amt), .buffer = args.buffer }, + }, + }; + }, + else => {}, + } + + return Maybe(Return.Read).todo; + } + + pub fn read(this: *NodeFS, args: Arguments.Read, comptime flavor: Flavor) Maybe(Return.Read) { + return if (args.position != null) + this._pread( + args, + comptime flavor, + ) + else + this._read( + args, + comptime flavor, + ); + } + + pub fn write(this: *NodeFS, args: Arguments.Write, comptime flavor: Flavor) Maybe(Return.Write) { + return if (args.position != null) _pwrite(this, args, flavor) else _write(this, args, flavor); + } + fn _write(this: *NodeFS, args: Arguments.Write, comptime flavor: Flavor) Maybe(Return.Write) { + _ = args; + _ = this; + _ = flavor; + + switch (comptime flavor) { + .sync => { + var buf = args.buffer.slice(); + buf = buf[@minimum(args.offset, buf.len)..]; + buf = buf[0..@minimum(buf.len, args.length)]; + + return switch (Syscall.write(args.fd, buf)) { + .err => |err| .{ + .err = err, + }, + .result => |amt| .{ + .result = .{ .bytes_written = @truncate(u32, amt), .buffer = args.buffer }, + }, + }; + }, + else => {}, + } + + return Maybe(Return.Write).todo; + } + + fn _pwrite(this: *NodeFS, args: Arguments.Write, comptime flavor: Flavor) Maybe(Return.Write) { + _ = args; + _ = this; + _ = flavor; + + const position = args.position.?; + + switch (comptime flavor) { + .sync => { + var buf = args.buffer.slice(); + buf = buf[@minimum(args.offset, buf.len)..]; + buf = buf[0..@minimum(args.length, buf.len)]; + + return switch (Syscall.pwrite(args.fd, buf, position)) { + .err => |err| .{ + .err = err, + }, + .result => |amt| .{ .result = .{ .bytes_written = @truncate(u32, amt), .buffer = args.buffer } }, + }; + }, + else => {}, + } + + return Maybe(Return.Write).todo; + } + + pub fn readdir(this: *NodeFS, args: Arguments.Readdir, comptime flavor: Flavor) Maybe(Return.Readdir) { + return switch (args.encoding) { + .buffer => _readdir( + this, + args, + Buffer, + flavor, + ), + else => { + if (!args.with_file_types) { + return _readdir( + this, + args, + PathString, + flavor, + ); + } + + return _readdir( + this, + args, + DirEnt, + flavor, + ); + }, + }; + } + + pub fn _readdir( + this: *NodeFS, + args: Arguments.Readdir, + comptime ExpectedType: type, + comptime flavor: Flavor, + ) Maybe(Return.Readdir) { + const file_type = comptime switch (ExpectedType) { + DirEnt => "with_file_types", + PathString => "files", + Buffer => "buffers", + else => unreachable, + }; + + switch (comptime flavor) { + .sync => { + var path = args.path.sliceZ(&this.sync_error_buf); + const flags = os.O.DIRECTORY | os.O.RDONLY; + const fd = switch (Syscall.open(path, flags, 0)) { + .err => |err| return .{ + .err = err.withPath(args.path.slice()), + }, + .result => |fd_| fd_, + }; + defer { + _ = Syscall.close(fd); + } + + var entries = std.ArrayList(ExpectedType).init(_global.default_allocator); + var dir = std.fs.Dir{ .fd = fd }; + var iterator = DirIterator.iterate(dir); + var entry = iterator.next(); + while (switch (entry) { + .err => |err| { + for (entries.items) |*item| { + switch (comptime ExpectedType) { + DirEnt => { + _global.default_allocator.free(item.name.slice()); + }, + Buffer => { + item.destroy(); + }, + PathString => { + _global.default_allocator.free(item.slice()); + }, + else => unreachable, + } + } + + entries.deinit(); + + return .{ + .err = err.withPath(args.path.slice()), + }; + }, + .result => |ent| ent, + }) |current| : (entry = iterator.next()) { + switch (comptime ExpectedType) { + DirEnt => { + entries.append(.{ + .name = PathString.init(_global.default_allocator.dupe(u8, current.name.slice()) catch unreachable), + .kind = current.kind, + }) catch unreachable; + }, + Buffer => { + const slice = current.name.slice(); + entries.append(Buffer.fromString(slice, _global.default_allocator) catch unreachable) catch unreachable; + }, + PathString => { + entries.append( + PathString.init(_global.default_allocator.dupe(u8, current.name.slice()) catch unreachable), + ) catch unreachable; + }, + else => unreachable, + } + } + + return .{ .result = @unionInit(Return.Readdir, file_type, entries.items) }; + }, + else => {}, + } + + _ = args; + _ = this; + _ = flavor; + return Maybe(Return.Readdir).todo; + } + pub fn readFile(this: *NodeFS, args: Arguments.ReadFile, comptime flavor: Flavor) Maybe(Return.ReadFile) { + var path: [:0]const u8 = undefined; + switch (comptime flavor) { + .sync => { + const fd = switch (args.path) { + .path => brk: { + path = args.path.path.sliceZ(&this.sync_error_buf); + break :brk switch (Syscall.open( + path, + os.O.RDONLY | os.O.NOCTTY, + 0, + )) { + .err => |err| return .{ + .err = err.withPath(if (args.path == .path) args.path.path.slice() else ""), + }, + .result => |fd_| fd_, + }; + }, + .fd => |_fd| _fd, + }; + + defer { + if (args.path == .path) + _ = Syscall.close(fd); + } + + const stat_ = switch (Syscall.fstat(fd)) { + .err => |err| return .{ + .err = err, + }, + .result => |stat_| stat_, + }; + + const size = @intCast(u64, @maximum(stat_.size, 0)); + var buf = std.ArrayList(u8).init(_global.default_allocator); + buf.ensureTotalCapacity(size + 16) catch unreachable; + buf.expandToCapacity(); + var total: usize = 0; + + while (total < size) { + switch (Syscall.read(fd, buf.items[total..])) { + .err => |err| return .{ + .err = err, + }, + .result => |amt| { + total += amt; + // There are cases where stat()'s size is wrong or out of date + if (total > size and amt != 0) { + buf.ensureUnusedCapacity(512384) catch unreachable; + buf.expandToCapacity(); + continue; + } + + if (amt == 0) { + break; + } + }, + } + } + buf.items.len = total; + return switch (args.encoding) { + .buffer => .{ + .result = .{ + .buffer = Buffer.fromBytes(buf.items, _global.default_allocator, JSC.C.JSTypedArrayType.kJSTypedArrayTypeUint8Array), + }, + }, + else => .{ + .result = .{ + .string = buf.items, + }, + }, + }; + }, + else => {}, + } + + _ = args; + _ = this; + _ = flavor; + return Maybe(Return.ReadFile).todo; + } + + pub fn writeFile(this: *NodeFS, args: Arguments.WriteFile, comptime flavor: Flavor) Maybe(Return.WriteFile) { + var path: [:0]const u8 = undefined; + + switch (comptime flavor) { + .sync => { + const fd = switch (args.file) { + .path => brk: { + path = args.file.path.sliceZ(&this.sync_error_buf); + break :brk switch (Syscall.open( + path, + @enumToInt(args.flag) | os.O.NOCTTY, + args.mode, + )) { + .err => |err| return .{ + .err = err.withPath(path), + }, + .result => |fd_| fd_, + }; + }, + .fd => |_fd| _fd, + }; + + defer { + if (args.file == .path) + _ = Syscall.close(fd); + } + + var buf = args.data.slice(); + + while (buf.len > 0) { + switch (Syscall.write(fd, buf)) { + .err => |err| return .{ + .err = err, + }, + .result => |amt| { + buf = buf[amt..]; + if (amt == 0) { + break; + } + }, + } + } + return Maybe(Return.WriteFile).success; + }, + else => {}, + } + + _ = args; + _ = this; + _ = flavor; + return Maybe(Return.WriteFile).todo; + } + + pub fn readlink(this: *NodeFS, args: Arguments.Readlink, comptime flavor: Flavor) Maybe(Return.Readlink) { + var outbuf: [std.fs.MAX_PATH_BYTES]u8 = undefined; + var inbuf = &this.sync_error_buf; + switch (comptime flavor) { + .sync => { + const path = args.path.sliceZ(inbuf); + + const len = switch (Syscall.readlink(path, &outbuf)) { + .err => |err| return .{ + .err = err.withPath(args.path.slice()), + }, + .result => |buf_| buf_, + }; + + return .{ + .result = switch (args.encoding) { + .buffer => .{ + .buffer = Buffer.fromString(outbuf[0..len], _global.default_allocator) catch unreachable, + }, + else => .{ + .string = _global.default_allocator.dupe(u8, outbuf[0..len]) catch unreachable, + }, + }, + }; + }, + else => {}, + } + + _ = args; + _ = this; + _ = flavor; + return Maybe(Return.Readlink).todo; + } + pub fn realpath(this: *NodeFS, args: Arguments.Realpath, comptime flavor: Flavor) Maybe(Return.Realpath) { + var outbuf: [std.fs.MAX_PATH_BYTES]u8 = undefined; + var inbuf = &this.sync_error_buf; + if (comptime Environment.allow_assert) std.debug.assert(FileSystem.instance_loaded); + + switch (comptime flavor) { + .sync => { + var path_slice = args.path.slice(); + + var parts = [_]string{ FileSystem.instance.top_level_dir, path_slice }; + var path_ = FileSystem.instance.absBuf(&parts, inbuf); + inbuf[path_.len] = 0; + var path: [:0]u8 = inbuf[0..path_.len :0]; + + const flags = if (comptime Environment.isLinux) + // O_PATH is faster + std.os.O.PATH + else + std.os.O.RDONLY; + + const fd = switch (Syscall.open(path, flags, 0)) { + .err => |err| return .{ + .err = err.withPath(path), + }, + .result => |fd_| fd_, + }; + + defer { + _ = Syscall.close(fd); + } + + const buf = switch (Syscall.getFdPath(fd, &outbuf)) { + .err => |err| return .{ + .err = err.withPath(path), + }, + .result => |buf_| buf_, + }; + + return .{ + .result = switch (args.encoding) { + .buffer => .{ + .buffer = Buffer.fromString(buf, _global.default_allocator) catch unreachable, + }, + else => .{ + .string = _global.default_allocator.dupe(u8, buf) catch unreachable, + }, + }, + }; + }, + else => {}, + } + + _ = args; + _ = this; + _ = flavor; + return Maybe(Return.Realpath).todo; + } + pub const realpathNative = realpath; + // pub fn realpathNative(this: *NodeFS, args: Arguments.Realpath, comptime flavor: Flavor) Maybe(Return.Realpath) { + // _ = args; + // _ = this; + // _ = flavor; + // return error.NotImplementedYet; + // } + pub fn rename(this: *NodeFS, args: Arguments.Rename, comptime flavor: Flavor) Maybe(Return.Rename) { + var from_buf = &this.sync_error_buf; + var to_buf: [std.fs.MAX_PATH_BYTES]u8 = undefined; + + switch (comptime flavor) { + .sync => { + var from = args.old_path.sliceZ(from_buf); + var to = args.new_path.sliceZ(&to_buf); + return Syscall.rename(from, to); + }, + else => {}, + } + + _ = args; + _ = this; + _ = flavor; + return Maybe(Return.Rename).todo; + } + pub fn rmdir(this: *NodeFS, args: Arguments.RmDir, comptime flavor: Flavor) Maybe(Return.Rmdir) { + switch (comptime flavor) { + .sync => { + var dir = args.old_path.sliceZ(&this.sync_error_buf); + _ = dir; + }, + else => {}, + } + _ = args; + _ = this; + _ = flavor; + return Maybe(Return.Rmdir).todo; + } + pub fn rm(this: *NodeFS, args: Arguments.RmDir, comptime flavor: Flavor) Maybe(Return.Rm) { + _ = args; + _ = this; + _ = flavor; + return Maybe(Return.Rm).todo; + } + pub fn stat(this: *NodeFS, args: Arguments.Stat, comptime flavor: Flavor) Maybe(Return.Stat) { + if (args.big_int) return Maybe(Return.Stat).todo; + + switch (comptime flavor) { + .sync => { + return @as(Maybe(Return.Stat), switch (Syscall.stat( + args.path.sliceZ( + &this.sync_error_buf, + ), + )) { + .result => |result| Maybe(Return.Stat){ .result = Return.Stat.init(result) }, + .err => |err| Maybe(Return.Stat){ .err = err }, + }); + }, + else => {}, + } + + _ = args; + _ = this; + _ = flavor; + return Maybe(Return.Stat).todo; + } + + pub fn symlink(this: *NodeFS, args: Arguments.Symlink, comptime flavor: Flavor) Maybe(Return.Symlink) { + var to_buf: [std.fs.MAX_PATH_BYTES]u8 = undefined; + + switch (comptime flavor) { + .sync => { + return Syscall.symlink( + args.old_path.sliceZ(&this.sync_error_buf), + args.new_path.sliceZ(&to_buf), + ); + }, + else => {}, + } + + _ = args; + _ = this; + _ = flavor; + return Maybe(Return.Symlink).todo; + } + fn _truncate(this: *NodeFS, path: PathLike, len: u32, comptime flavor: Flavor) Maybe(Return.Truncate) { + switch (comptime flavor) { + .sync => { + return Maybe(Return.Truncate).errno(C.truncate(path.sliceZ(&this.sync_error_buf), len)) orelse + Maybe(Return.Truncate).success; + }, + else => {}, + } + + _ = this; + _ = flavor; + return Maybe(Return.Truncate).todo; + } + pub fn truncate(this: *NodeFS, args: Arguments.Truncate, comptime flavor: Flavor) Maybe(Return.Truncate) { + return switch (args.path) { + .fd => |fd| this.ftruncate( + Arguments.FTruncate{ .fd = fd, .len = args.len }, + flavor, + ), + .path => this._truncate( + args.path.path, + args.len, + flavor, + ), + }; + } + pub fn unlink(this: *NodeFS, args: Arguments.Unlink, comptime flavor: Flavor) Maybe(Return.Unlink) { + switch (comptime flavor) { + .sync => { + return Maybe(Return.Unlink).errnoSysP(system.unlink(args.path.sliceZ(&this.sync_error_buf)), .unlink, args.path.slice()) orelse + Maybe(Return.Unlink).success; + }, + else => {}, + } + + _ = args; + _ = this; + _ = flavor; + return Maybe(Return.Unlink).todo; + } + pub fn unwatchFile(this: *NodeFS, args: Arguments.UnwatchFile, comptime flavor: Flavor) Maybe(Return.UnwatchFile) { + _ = args; + _ = this; + _ = flavor; + return Maybe(Return.UnwatchFile).todo; + } + pub fn utimes(this: *NodeFS, args: Arguments.Utimes, comptime flavor: Flavor) Maybe(Return.Utimes) { + var times = [2]std.c.timeval{ + .{ + .tv_sec = args.mtime, + // TODO: is this correct? + .tv_usec = 0, + }, + .{ + .tv_sec = args.atime, + // TODO: is this correct? + .tv_usec = 0, + }, + }; + + switch (comptime flavor) { + // futimes uses the syscall version + // we use libc because here, not for a good reason + // just missing from the linux syscall interface in zig and I don't want to modify that right now + .sync => return if (Maybe(Return.Utimes).errnoSysP(std.c.utimes(args.path.sliceZ(&this.sync_error_buf), ×), .utimes, args.path.slice())) |err| + err + else + Maybe(Return.Utimes).success, + else => {}, + } + + _ = args; + _ = this; + _ = flavor; + return Maybe(Return.Utimes).todo; + } + + pub fn lutimes(this: *NodeFS, args: Arguments.Lutimes, comptime flavor: Flavor) Maybe(Return.Lutimes) { + var times = [2]std.c.timeval{ + .{ + .tv_sec = args.mtime, + // TODO: is this correct? + .tv_usec = 0, + }, + .{ + .tv_sec = args.atime, + // TODO: is this correct? + .tv_usec = 0, + }, + }; + + switch (comptime flavor) { + // futimes uses the syscall version + // we use libc because here, not for a good reason + // just missing from the linux syscall interface in zig and I don't want to modify that right now + .sync => return if (Maybe(Return.Lutimes).errnoSysP(C.lutimes(args.path.sliceZ(&this.sync_error_buf), ×), .lutimes, args.path.slice())) |err| + err + else + Maybe(Return.Lutimes).success, + else => {}, + } + + _ = args; + _ = this; + _ = flavor; + return Maybe(Return.Lutimes).todo; + } + pub fn watch(this: *NodeFS, args: Arguments.Watch, comptime flavor: Flavor) Maybe(Return.Watch) { + _ = args; + _ = this; + _ = flavor; + return Maybe(Return.Watch).todo; + } + pub fn createReadStream(this: *NodeFS, args: Arguments.CreateReadStream, comptime flavor: Flavor) Maybe(Return.CreateReadStream) { + _ = args; + _ = this; + _ = flavor; + var stream = _global.default_allocator.create(JSC.Node.Stream) catch unreachable; + stream.* = JSC.Node.Stream{ + .sink = .{ + .readable = JSC.Node.Readable{ + .stream = stream, + .globalObject = args.global_object, + }, + }, + .sink_type = .readable, + .content = undefined, + .content_type = undefined, + .allocator = _global.default_allocator, + }; + + args.file.copyToStream(args.flags, args.autoClose, args.mode, _global.default_allocator, stream) catch unreachable; + args.copyToState(&stream.sink.readable.state); + return Maybe(Return.CreateReadStream){ .result = stream }; + } + pub fn createWriteStream(this: *NodeFS, args: Arguments.CreateWriteStream, comptime flavor: Flavor) Maybe(Return.CreateWriteStream) { + _ = args; + _ = this; + _ = flavor; + var stream = _global.default_allocator.create(JSC.Node.Stream) catch unreachable; + stream.* = JSC.Node.Stream{ + .sink = .{ + .writable = JSC.Node.Writable{ + .stream = stream, + .globalObject = args.global_object, + }, + }, + .sink_type = .writable, + .content = undefined, + .content_type = undefined, + .allocator = _global.default_allocator, + }; + args.file.copyToStream(args.flags, args.autoClose, args.mode, _global.default_allocator, stream) catch unreachable; + args.copyToState(&stream.sink.writable.state); + return Maybe(Return.CreateWriteStream){ .result = stream }; + } +}; diff --git a/src/javascript/jsc/node/node_fs_binding.zig b/src/javascript/jsc/node/node_fs_binding.zig new file mode 100644 index 000000000..ae29f202a --- /dev/null +++ b/src/javascript/jsc/node/node_fs_binding.zig @@ -0,0 +1,429 @@ +const JSC = @import("../../../jsc.zig"); +const std = @import("std"); +const Flavor = JSC.Node.Flavor; +const ArgumentsSlice = JSC.Node.ArgumentsSlice; +const system = std.os.system; +const Maybe = JSC.Node.Maybe; +const Encoding = JSC.Node.Encoding; +const FeatureFlags = @import("../../../global.zig").FeatureFlags; +const Args = JSC.Node.NodeFS.Arguments; + +const NodeFSFunction = fn ( + *JSC.Node.NodeFS, + JSC.C.JSContextRef, + JSC.C.JSObjectRef, + JSC.C.JSObjectRef, + []const JSC.C.JSValueRef, + JSC.C.ExceptionRef, +) JSC.C.JSValueRef; + +pub const toJSTrait = std.meta.trait.hasFn("toJS"); +pub const fromJSTrait = std.meta.trait.hasFn("fromJS"); +const NodeFSFunctionEnum = JSC.Node.DeclEnum(JSC.Node.NodeFS); + +fn callSync(comptime FunctionEnum: NodeFSFunctionEnum) NodeFSFunction { + const Function = @field(JSC.Node.NodeFS, @tagName(FunctionEnum)); + const FunctionType = @TypeOf(Function); + + const function: std.builtin.TypeInfo.Fn = comptime @typeInfo(FunctionType).Fn; + comptime if (function.args.len != 3) @compileError("Expected 3 arguments"); + const Arguments = comptime function.args[1].arg_type.?; + const FormattedName = comptime [1]u8{std.ascii.toUpper(@tagName(FunctionEnum)[0])} ++ @tagName(FunctionEnum)[1..]; + const Result = comptime JSC.Node.Maybe(@field(JSC.Node.NodeFS.ReturnType, FormattedName)); + + const NodeBindingClosure = struct { + pub fn bind( + this: *JSC.Node.NodeFS, + ctx: JSC.C.JSContextRef, + _: JSC.C.JSObjectRef, + _: JSC.C.JSObjectRef, + arguments: []const JSC.C.JSValueRef, + exception: JSC.C.ExceptionRef, + ) JSC.C.JSValueRef { + var slice = ArgumentsSlice.init(@ptrCast([*]const JSC.JSValue, arguments.ptr)[0..arguments.len]); + + defer { + // TODO: fix this + for (arguments) |arg| { + JSC.C.JSValueUnprotect(ctx, arg); + } + slice.arena.deinit(); + } + + const args = if (comptime Arguments != void) + (Arguments.fromJS(ctx, &slice, exception) orelse return null) + else + Arguments{}; + if (exception.* != null) return null; + + const result: Result = Function( + this, + args, + comptime Flavor.sync, + ); + return switch (result) { + .err => |err| brk: { + exception.* = err.toJS(ctx); + break :brk null; + }, + .result => |res| if (comptime Result.ReturnType != void) + JSC.To.JS.withType(Result.ReturnType, res, ctx, exception) + else + JSC.C.JSValueMakeUndefined(ctx), + }; + } + }; + + return NodeBindingClosure.bind; +} + +fn call(comptime Function: NodeFSFunctionEnum) NodeFSFunction { + // const FunctionType = @TypeOf(Function); + _ = Function; + + // const function: std.builtin.TypeInfo.Fn = comptime @typeInfo(FunctionType).Fn; + // comptime if (function.args.len != 3) @compileError("Expected 3 arguments"); + // const Arguments = comptime function.args[2].arg_type orelse @compileError(std.fmt.comptimePrint("Function {s} expected to have an arg type at [2]", .{@typeName(FunctionType)})); + // const Result = comptime function.return_type.?; + // comptime if (Arguments != void and !fromJSTrait(Arguments)) @compileError(std.fmt.comptimePrint("{s} is missing fromJS()", .{@typeName(Arguments)})); + // comptime if (Result != void and !toJSTrait(Result)) @compileError(std.fmt.comptimePrint("{s} is missing toJS()", .{@typeName(Result)})); + const NodeBindingClosure = struct { + pub fn bind( + this: *JSC.Node.NodeFS, + ctx: JSC.C.JSContextRef, + _: JSC.C.JSObjectRef, + _: JSC.C.JSObjectRef, + arguments: []const JSC.C.JSValueRef, + exception: JSC.C.ExceptionRef, + ) JSC.C.JSValueRef { + _ = this; + _ = ctx; + _ = arguments; + var err = JSC.SystemError{}; + exception.* = err.toErrorInstance(ctx.ptr()).asObjectRef(); + return null; + // var slice = ArgumentsSlice.init(arguments); + + // defer { + // for (arguments.len) |arg| { + // JSC.C.JSValueUnprotect(ctx, arg); + // } + // slice.arena.deinit(); + // } + + // const args = if (comptime Arguments != void) + // Arguments.fromJS(ctx, &slice, exception) + // else + // Arguments{}; + // if (exception.* != null) return null; + + // const result: Maybe(Result) = Function(this, comptime Flavor.sync, args); + // switch (result) { + // .err => |err| { + // exception.* = err.toJS(ctx); + // return null; + // }, + // .result => |res| { + // return switch (comptime Result) { + // void => JSC.JSValue.jsUndefined().asRef(), + // else => res.toJS(ctx), + // }; + // }, + // } + // unreachable; + } + }; + return NodeBindingClosure.bind; +} + +pub const NodeFSBindings = JSC.NewClass( + JSC.Node.NodeFS, + .{ .name = "fs" }, + + .{ + .access = .{ + .name = "access", + .rfn = call(.access), + }, + .appendFile = .{ + .name = "appendFile", + .rfn = call(.appendFile), + }, + .close = .{ + .name = "close", + .rfn = call(.close), + }, + .copyFile = .{ + .name = "copyFile", + .rfn = call(.copyFile), + }, + .exists = .{ + .name = "exists", + .rfn = call(.exists), + }, + .chown = .{ + .name = "chown", + .rfn = call(.chown), + }, + .chmod = .{ + .name = "chmod", + .rfn = call(.chmod), + }, + .fchmod = .{ + .name = "fchmod", + .rfn = call(.fchmod), + }, + .fchown = .{ + .name = "fchown", + .rfn = call(.fchown), + }, + .fstat = .{ + .name = "fstat", + .rfn = call(.fstat), + }, + .fsync = .{ + .name = "fsync", + .rfn = call(.fsync), + }, + .ftruncate = .{ + .name = "ftruncate", + .rfn = call(.ftruncate), + }, + .futimes = .{ + .name = "futimes", + .rfn = call(.futimes), + }, + .lchmod = .{ + .name = "lchmod", + .rfn = call(.lchmod), + }, + .lchown = .{ + .name = "lchown", + .rfn = call(.lchown), + }, + .link = .{ + .name = "link", + .rfn = call(.link), + }, + .lstat = .{ + .name = "lstat", + .rfn = call(.lstat), + }, + .mkdir = .{ + .name = "mkdir", + .rfn = call(.mkdir), + }, + .mkdtemp = .{ + .name = "mkdtemp", + .rfn = call(.mkdtemp), + }, + .open = .{ + .name = "open", + .rfn = call(.open), + }, + .read = .{ + .name = "read", + .rfn = call(.read), + }, + .write = .{ + .name = "write", + .rfn = call(.write), + }, + .readdir = .{ + .name = "readdir", + .rfn = call(.readdir), + }, + .readFile = .{ + .name = "readFile", + .rfn = call(.readFile), + }, + .writeFile = .{ + .name = "writeFile", + .rfn = call(.writeFile), + }, + .readlink = .{ + .name = "readlink", + .rfn = call(.readlink), + }, + .realpath = .{ + .name = "realpath", + .rfn = call(.realpath), + }, + .rename = .{ + .name = "rename", + .rfn = call(.rename), + }, + .stat = .{ + .name = "stat", + .rfn = call(.stat), + }, + .symlink = .{ + .name = "symlink", + .rfn = call(.symlink), + }, + .truncate = .{ + .name = "truncate", + .rfn = call(.truncate), + }, + .unlink = .{ + .name = "unlink", + .rfn = call(.unlink), + }, + .utimes = .{ + .name = "utimes", + .rfn = call(.utimes), + }, + .lutimes = .{ + .name = "lutimes", + .rfn = call(.lutimes), + }, + + .createReadStream = .{ + .name = "createReadStream", + .rfn = if (FeatureFlags.node_streams) callSync(.createReadStream) else call(.createReadStream), + }, + + .createWriteStream = .{ + .name = "createWriteStream", + .rfn = if (FeatureFlags.node_streams) callSync(.createWriteStream) else call(.createWriteStream), + }, + + .accessSync = .{ + .name = "accessSync", + .rfn = callSync(.access), + }, + .appendFileSync = .{ + .name = "appendFileSync", + .rfn = callSync(.appendFile), + }, + .closeSync = .{ + .name = "closeSync", + .rfn = callSync(.close), + }, + .copyFileSync = .{ + .name = "copyFileSync", + .rfn = callSync(.copyFile), + }, + .existsSync = .{ + .name = "existsSync", + .rfn = callSync(.exists), + }, + .chownSync = .{ + .name = "chownSync", + .rfn = callSync(.chown), + }, + .chmodSync = .{ + .name = "chmodSync", + .rfn = callSync(.chmod), + }, + .fchmodSync = .{ + .name = "fchmodSync", + .rfn = callSync(.fchmod), + }, + .fchownSync = .{ + .name = "fchownSync", + .rfn = callSync(.fchown), + }, + .fstatSync = .{ + .name = "fstatSync", + .rfn = callSync(.fstat), + }, + .fsyncSync = .{ + .name = "fsyncSync", + .rfn = callSync(.fsync), + }, + .ftruncateSync = .{ + .name = "ftruncateSync", + .rfn = callSync(.ftruncate), + }, + .futimesSync = .{ + .name = "futimesSync", + .rfn = callSync(.futimes), + }, + .lchmodSync = .{ + .name = "lchmodSync", + .rfn = callSync(.lchmod), + }, + .lchownSync = .{ + .name = "lchownSync", + .rfn = callSync(.lchown), + }, + .linkSync = .{ + .name = "linkSync", + .rfn = callSync(.link), + }, + .lstatSync = .{ + .name = "lstatSync", + .rfn = callSync(.lstat), + }, + .mkdirSync = .{ + .name = "mkdirSync", + .rfn = callSync(.mkdir), + }, + .mkdtempSync = .{ + .name = "mkdtempSync", + .rfn = callSync(.mkdtemp), + }, + .openSync = .{ + .name = "openSync", + .rfn = callSync(.open), + }, + .readSync = .{ + .name = "readSync", + .rfn = callSync(.read), + }, + .writeSync = .{ + .name = "writeSync", + .rfn = callSync(.write), + }, + .readdirSync = .{ + .name = "readdirSync", + .rfn = callSync(.readdir), + }, + .readFileSync = .{ + .name = "readFileSync", + .rfn = callSync(.readFile), + }, + .writeFileSync = .{ + .name = "writeFileSync", + .rfn = callSync(.writeFile), + }, + .readlinkSync = .{ + .name = "readlinkSync", + .rfn = callSync(.readlink), + }, + .realpathSync = .{ + .name = "realpathSync", + .rfn = callSync(.realpath), + }, + .renameSync = .{ + .name = "renameSync", + .rfn = callSync(.rename), + }, + .statSync = .{ + .name = "statSync", + .rfn = callSync(.stat), + }, + .symlinkSync = .{ + .name = "symlinkSync", + .rfn = callSync(.symlink), + }, + .truncateSync = .{ + .name = "truncateSync", + .rfn = callSync(.truncate), + }, + .unlinkSync = .{ + .name = "unlinkSync", + .rfn = callSync(.unlink), + }, + .utimesSync = .{ + .name = "utimesSync", + .rfn = callSync(.utimes), + }, + .lutimesSync = .{ + .name = "lutimesSync", + .rfn = callSync(.lutimes), + }, + }, + .{}, +); diff --git a/src/javascript/jsc/node/nodejs_error_code.zig b/src/javascript/jsc/node/nodejs_error_code.zig new file mode 100644 index 000000000..5c54791ee --- /dev/null +++ b/src/javascript/jsc/node/nodejs_error_code.zig @@ -0,0 +1,1097 @@ +/// https://nodejs.org/api/errors.html#nodejs-error-codes +pub const Code = enum { + /// Used when an operation has been aborted (typically using an AbortController). + /// APIs not using AbortSignals typically do not raise an error with this code. + /// This code does not use the regular ERR_* convention Node.js errors use in order to be compatible with the web platform's AbortError. + /// Added in: v15.0.0 + ABORT_ERR, + + /// A function argument is being used in a way that suggests that the function signature may be misunderstood. This is thrown by the assert module when the message parameter in assert.throws(block, message) matches the error message thrown by block because that usage suggests that the user believes message is the expected message rather than the message the AssertionError will display if block does not throw. + ERR_AMBIGUOUS_ARGUMENT, + + /// An iterable argument (i.e. a value that works with for...of loops) was required, but not provided to a Node.js API. + ERR_ARG_NOT_ITERABLE, + + /// A special type of error that can be triggered whenever Node.js detects an exceptional logic violation that should never occur. These are raised typically by the assert module. + ERR_ASSERTION, + + /// An attempt was made to register something that is not a function as an AsyncHooks callback. + ERR_ASYNC_CALLBACK, + + /// The type of an asynchronous resource was invalid. Users are also able to define their own types if using the public embedder API. + ERR_ASYNC_TYPE, + + /// Data passed to a Brotli stream was not successfully compressed. + ERR_BROTLI_COMPRESSION_FAILED, + + /// An invalid parameter key was passed during construction of a Brotli stream. + ERR_BROTLI_INVALID_PARAM, + + /// When encountering this error, a possible alternative to creating a Buffer instance is to create a normal Uint8Array, which only differs in the prototype of the resulting object. Uint8Arrays are generally accepted in all Node.js core APIs where Buffers are; they are available in all Contexts. + /// An attempt was made to create a Node.js Buffer instance from addon or embedder code, while in a JS engine Context that is not associated with a Node.js instance. The data passed to the Buffer method will have been released by the time the method returns. + ERR_BUFFER_CONTEXT_NOT_AVAILABLE, + + /// An operation outside the bounds of a Buffer was attempted. + ERR_BUFFER_OUT_OF_BOUNDS, + + /// An attempt has been made to create a Buffer larger than the maximum allowed size. + ERR_BUFFER_TOO_LARGE, + + /// Node.js was unable to watch for the SIGINT signal. + ERR_CANNOT_WATCH_SIGINT, + + /// A child process was closed before the parent received a reply. + ERR_CHILD_CLOSED_BEFORE_REPLY, + + /// Used when a child process is being forked without specifying an IPC channel. + ERR_CHILD_PROCESS_IPC_REQUIRED, + + /// Used when the main process is trying to read data from the child process's STDERR/STDOUT, and the data's length is longer than the maxBuffer option. + ERR_CHILD_PROCESS_STDIO_MAXBUFFER, + + /// There was an attempt to use a MessagePort instance in a closed state, usually after .close() has been called. + ERR_CLOSED_MESSAGE_PORT, + + /// Console was instantiated without stdout stream, or Console has a non-writable stdout or stderr stream. + ERR_CONSOLE_WRITABLE_STREAM, + + /// A class constructor was called that is not callable. + ERR_CONSTRUCT_CALL_INVALID, + + /// A constructor for a class was called without new. + ERR_CONSTRUCT_CALL_REQUIRED, + + /// The vm context passed into the API is not yet initialized. This could happen when an error occurs (and is caught) during the creation of the context, for example, when the allocation fails or the maximum call stack size is reached when the context is created. + ERR_CONTEXT_NOT_INITIALIZED, + + /// A client certificate engine was requested that is not supported by the version of OpenSSL being used. + ERR_CRYPTO_CUSTOM_ENGINE_NOT_SUPPORTED, + + /// An invalid value for the format argument was passed to the crypto.ECDH() class getPublicKey() method. + ERR_CRYPTO_ECDH_INVALID_FORMAT, + + /// An invalid value for the key argument has been passed to the crypto.ECDH() class computeSecret() method. It means that the public key lies outside of the elliptic curve. + ERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY, + + /// An invalid crypto engine identifier was passed to require('crypto').setEngine(). + ERR_CRYPTO_ENGINE_UNKNOWN, + + /// The --force-fips command-line argument was used but there was an attempt to enable or disable FIPS mode in the crypto module. + ERR_CRYPTO_FIPS_FORCED, + + /// An attempt was made to enable or disable FIPS mode, but FIPS mode was not available. + ERR_CRYPTO_FIPS_UNAVAILABLE, + + /// hash.digest() was called multiple times. The hash.digest() method must be called no more than one time per instance of a Hash object. + ERR_CRYPTO_HASH_FINALIZED, + + /// hash.update() failed for any reason. This should rarely, if ever, happen. + ERR_CRYPTO_HASH_UPDATE_FAILED, + + /// The given crypto keys are incompatible with the attempted operation. + ERR_CRYPTO_INCOMPATIBLE_KEY, + + /// The selected public or private key encoding is incompatible with other options. + ERR_CRYPTO_INCOMPATIBLE_KEY_OPTIONS, + + /// Added in: v15.0.0 + /// Initialization of the crypto subsystem failed. + ERR_CRYPTO_INITIALIZATION_FAILED, + + /// Added in: v15.0.0 + /// An invalid authentication tag was provided. + ERR_CRYPTO_INVALID_AUTH_TAG, + + /// Added in: v15.0.0 + /// An invalid counter was provided for a counter-mode cipher. + ERR_CRYPTO_INVALID_COUNTER, + + /// An invalid elliptic-curve was provided. + /// Added in: v15.0.0 + ERR_CRYPTO_INVALID_CURVE, + + /// An invalid crypto digest algorithm was specified. + ERR_CRYPTO_INVALID_DIGEST, + + /// Added in: v15.0.0 + /// An invalid initialization vector was provided. + ERR_CRYPTO_INVALID_IV, + + /// Added in: v15.0.0 + /// An invalid JSON Web Key was provided. + ERR_CRYPTO_INVALID_JWK, + + /// The given crypto key object's type is invalid for the attempted operation. + ERR_CRYPTO_INVALID_KEY_OBJECT_TYPE, + + /// Added in: v15.0.0 + /// An invalid key length was provided. + ERR_CRYPTO_INVALID_KEYLEN, + + /// An invalid key pair was provided. + /// Added in: v15.0.0 + ERR_CRYPTO_INVALID_KEYPAIR, + + /// An invalid key type was provided. + /// Added in: v15.0.0 + ERR_CRYPTO_INVALID_KEYTYPE, + + /// Added in: v15.0.0 + /// An invalid message length was provided. + ERR_CRYPTO_INVALID_MESSAGELEN, + + /// Invalid scrypt algorithm parameters were provided. + /// Added in: v15.0.0 + ERR_CRYPTO_INVALID_SCRYPT_PARAMS, + + /// A crypto method was used on an object that was in an invalid state. For instance, calling cipher.getAuthTag() before calling cipher.final(). + ERR_CRYPTO_INVALID_STATE, + + /// Added in: v15.0.0 + /// An invalid authentication tag length was provided. + ERR_CRYPTO_INVALID_TAG_LENGTH, + + /// Added in: v15.0.0 + //// Initialization of an asynchronous crypto operation failed. + ERR_CRYPTO_JOB_INIT_FAILED, + + /// Key's Elliptic Curve is not registered for use in the JSON Web Key Elliptic Curve Registry. + ERR_CRYPTO_JWK_UNSUPPORTED_CURVE, + + /// Key's Asymmetric Key Type is not registered for use in the JSON Web Key Types Registry. + ERR_CRYPTO_JWK_UNSUPPORTED_KEY_TYPE, + + /// A crypto operation failed for an otherwise unspecified reason. + /// Added in: v15.0.0 + ERR_CRYPTO_OPERATION_FAILED, + + /// The PBKDF2 algorithm failed for unspecified reasons. OpenSSL does not provide more details and therefore neither does Node.js. + ERR_CRYPTO_PBKDF2_ERROR, + + /// One or more crypto.scrypt() or crypto.scryptSync() parameters are outside their legal range. + ERR_CRYPTO_SCRYPT_INVALID_PARAMETER, + + /// Node.js was compiled without scrypt support. Not possible with the official release binaries but can happen with custom builds, including distro builds. + ERR_CRYPTO_SCRYPT_NOT_SUPPORTED, + + /// A signing key was not provided to the sign.sign() method. + ERR_CRYPTO_SIGN_KEY_REQUIRED, + + /// crypto.timingSafeEqual() was called with Buffer, TypedArray, or DataView arguments of different lengths. + ERR_CRYPTO_TIMING_SAFE_EQUAL_LENGTH, + + /// An unknown cipher was specified. + ERR_CRYPTO_UNKNOWN_CIPHER, + + /// An unknown Diffie-Hellman group name was given. See crypto.getDiffieHellman() for a list of valid group names. + ERR_CRYPTO_UNKNOWN_DH_GROUP, + + /// Added in: v15.0.0, v14.18.0 + /// An attempt to invoke an unsupported crypto operation was made. + ERR_CRYPTO_UNSUPPORTED_OPERATION, + + /// An error occurred with the debugger. + /// Added in: v16.4.0, v14.17.4 + ERR_DEBUGGER_ERROR, + + /// Added in: v16.4.0, v14.17.4 + /// The debugger timed out waiting for the required host/port to be free. + ERR_DEBUGGER_STARTUP_ERROR, + + /// Added in: v16.10.0 + /// Loading native addons has been disabled using --no-addons. + ERR_DLOPEN_DISABLED, + + /// Added in: v15.0.0 + /// A call to process.dlopen() failed. + ERR_DLOPEN_FAILED, + + /// The fs.Dir was previously closed. + ERR_DIR_CLOSED, + + /// A synchronous read or close call was attempted on an fs.Dir which has ongoing asynchronous operations. + /// Added in: v14.3.0 + ERR_DIR_CONCURRENT_OPERATION, + + /// c-ares failed to set the DNS server. + ERR_DNS_SET_SERVERS_FAILED, + + /// The domain module was not usable since it could not establish the required error handling hooks, because process.setUncaughtExceptionCaptureCallback() had been called at an earlier point in time. + ERR_DOMAIN_CALLBACK_NOT_AVAILABLE, + + /// process.setUncaughtExceptionCaptureCallback() could not be called because the domain module has been loaded at an earlier point in time. + /// The stack trace is extended to include the point in time at which the domain module had been loaded. + ERR_DOMAIN_CANNOT_SET_UNCAUGHT_EXCEPTION_CAPTURE, + + /// Data provided to TextDecoder() API was invalid according to the encoding provided. + ERR_ENCODING_INVALID_ENCODED_DATA, + + /// Encoding provided to TextDecoder() API was not one of the WHATWG Supported Encodings. + ERR_ENCODING_NOT_SUPPORTED, + + /// --print cannot be used with ESM input. + ERR_EVAL_ESM_CANNOT_PRINT, + + /// Thrown when an attempt is made to recursively dispatch an event on EventTarget. + ERR_EVENT_RECURSION, + + /// The JS execution context is not associated with a Node.js environment. This may occur when Node.js is used as an embedded library and some hooks for the JS engine are not set up properly. + ERR_EXECUTION_ENVIRONMENT_NOT_AVAILABLE, + + /// A Promise that was callbackified via util.callbackify() was rejected with a falsy value. + ERR_FALSY_VALUE_REJECTION, + + /// Added in: v14.0.0 + /// Used when a feature that is not available to the current platform which is running Node.js is used. + ERR_FEATURE_UNAVAILABLE_ON_PLATFORM, + + /// An attempt was made to copy a directory to a non-directory (file, symlink, etc.) using fs.cp(). + ERR_FS_CP_DIR_TO_NON_DIR, + + /// An attempt was made to copy over a file that already existed with fs.cp(), with the force and errorOnExist set to true. + ERR_FS_CP_EEXIST, + + /// When using fs.cp(), src or dest pointed to an invalid path. + ERR_FS_CP_EINVAL, + + /// An attempt was made to copy a named pipe with fs.cp(). + ERR_FS_CP_FIFO_PIPE, + + /// An attempt was made to copy a non-directory (file, symlink, etc.) to a directory using fs.cp(). + ERR_FS_CP_NON_DIR_TO_DIR, + + /// An attempt was made to copy to a socket with fs.cp(). + ERR_FS_CP_SOCKET, + + /// When using fs.cp(), a symlink in dest pointed to a subdirectory of src. + ERR_FS_CP_SYMLINK_TO_SUBDIRECTORY, + + /// An attempt was made to copy to an unknown file type with fs.cp(). + ERR_FS_CP_UNKNOWN, + + /// Path is a directory. + ERR_FS_EISDIR, + + /// An attempt has been made to read a file whose size is larger than the maximum allowed size for a Buffer. + ERR_FS_FILE_TOO_LARGE, + + /// An invalid symlink type was passed to the fs.symlink() or fs.symlinkSync() methods. + ERR_FS_INVALID_SYMLINK_TYPE, + + /// An attempt was made to add more headers after the headers had already been sent. + ERR_HTTP_HEADERS_SENT, + + /// An invalid HTTP header value was specified. + ERR_HTTP_INVALID_HEADER_VALUE, + + /// Status code was outside the regular status code range (100-999). + ERR_HTTP_INVALID_STATUS_CODE, + + /// The client has not sent the entire request within the allowed time. + ERR_HTTP_REQUEST_TIMEOUT, + + /// Changing the socket encoding is not allowed per RFC 7230 Section 3. + ERR_HTTP_SOCKET_ENCODING, + + /// The Trailer header was set even though the transfer encoding does not support that. + ERR_HTTP_TRAILER_INVALID, + + /// HTTP/2 ALTSVC frames require a valid origin. + ERR_HTTP2_ALTSVC_INVALID_ORIGIN, + + /// HTTP/2 ALTSVC frames are limited to a maximum of 16,382 payload bytes. + ERR_HTTP2_ALTSVC_LENGTH, + + /// For HTTP/2 requests using the CONNECT method, the :authority pseudo-header is required. + ERR_HTTP2_CONNECT_AUTHORITY, + + /// For HTTP/2 requests using the CONNECT method, the :path pseudo-header is forbidden. + ERR_HTTP2_CONNECT_PATH, + + /// For HTTP/2 requests using the CONNECT method, the :scheme pseudo-header is forbidden. + ERR_HTTP2_CONNECT_SCHEME, + + /// A non-specific HTTP/2 error has occurred. + ERR_HTTP2_ERROR, + + /// New HTTP/2 Streams may not be opened after the Http2Session has received a GOAWAY frame from the connected peer. + ERR_HTTP2_GOAWAY_SESSION, + + /// Multiple values were provided for an HTTP/2 header field that was required to have only a single value. + ERR_HTTP2_HEADER_SINGLE_VALUE, + + /// An additional headers was specified after an HTTP/2 response was initiated. + ERR_HTTP2_HEADERS_AFTER_RESPOND, + + /// An attempt was made to send multiple response headers. + ERR_HTTP2_HEADERS_SENT, + + /// Informational HTTP status codes (1xx) may not be set as the response status code on HTTP/2 responses. + ERR_HTTP2_INFO_STATUS_NOT_ALLOWED, + + /// HTTP/1 connection specific headers are forbidden to be used in HTTP/2 requests and responses. + ERR_HTTP2_INVALID_CONNECTION_HEADERS, + + /// An invalid HTTP/2 header value was specified. + ERR_HTTP2_INVALID_HEADER_VALUE, + + /// An invalid HTTP informational status code has been specified. Informational status codes must be an integer between 100 and 199 (inclusive). + ERR_HTTP2_INVALID_INFO_STATUS, + + /// HTTP/2 ORIGIN frames require a valid origin. + ERR_HTTP2_INVALID_ORIGIN, + + /// Input Buffer and Uint8Array instances passed to the http2.getUnpackedSettings() API must have a length that is a multiple of six. + ERR_HTTP2_INVALID_PACKED_SETTINGS_LENGTH, + + /// Only valid HTTP/2 pseudoheaders (:status, :path, :authority, :scheme, and :method) may be used. + ERR_HTTP2_INVALID_PSEUDOHEADER, + + /// An action was performed on an Http2Session object that had already been destroyed. + ERR_HTTP2_INVALID_SESSION, + + /// An invalid value has been specified for an HTTP/2 setting. + ERR_HTTP2_INVALID_SETTING_VALUE, + + /// An operation was performed on a stream that had already been destroyed. + ERR_HTTP2_INVALID_STREAM, + + /// Whenever an HTTP/2 SETTINGS frame is sent to a connected peer, the peer is required to send an acknowledgment that it has received and applied the new SETTINGS. By default, a maximum number of unacknowledged SETTINGS frames may be sent at any given time. This error code is used when that limit has been reached. + ERR_HTTP2_MAX_PENDING_SETTINGS_ACK, + + /// An attempt was made to initiate a new push stream from within a push stream. Nested push streams are not permitted. + ERR_HTTP2_NESTED_PUSH, + + /// Out of memory when using the http2session.setLocalWindowSize(windowSize) API. + ERR_HTTP2_NO_MEM, + + /// An attempt was made to directly manipulate (read, write, pause, resume, etc.) a socket attached to an Http2Session. + ERR_HTTP2_NO_SOCKET_MANIPULATION, + + /// HTTP/2 ORIGIN frames are limited to a length of 16382 bytes. + ERR_HTTP2_ORIGIN_LENGTH, + + /// The number of streams created on a single HTTP/2 session reached the maximum limit. + ERR_HTTP2_OUT_OF_STREAMS, + + /// A message payload was specified for an HTTP response code for which a payload is forbidden. + ERR_HTTP2_PAYLOAD_FORBIDDEN, + + /// An HTTP/2 ping was canceled. + ERR_HTTP2_PING_CANCEL, + + /// HTTP/2 ping payloads must be exactly 8 bytes in length. + ERR_HTTP2_PING_LENGTH, + + /// An HTTP/2 pseudo-header has been used inappropriately. Pseudo-headers are header key names that begin with the : prefix. + ERR_HTTP2_PSEUDOHEADER_NOT_ALLOWED, + + /// An attempt was made to create a push stream, which had been disabled by the client. + ERR_HTTP2_PUSH_DISABLED, + + /// An attempt was made to use the Http2Stream.prototype.responseWithFile() API to send a directory. + ERR_HTTP2_SEND_FILE, + + /// An attempt was made to use the Http2Stream.prototype.responseWithFile() API to send something other than a regular file, but offset or length options were provided. + ERR_HTTP2_SEND_FILE_NOSEEK, + + /// The Http2Session closed with a non-zero error code. + ERR_HTTP2_SESSION_ERROR, + + /// The Http2Session settings canceled. + ERR_HTTP2_SETTINGS_CANCEL, + + /// An attempt was made to connect a Http2Session object to a net.Socket or tls.TLSSocket that had already been bound to another Http2Session object. + ERR_HTTP2_SOCKET_BOUND, + + /// An attempt was made to use the socket property of an Http2Session that has already been closed. + ERR_HTTP2_SOCKET_UNBOUND, + + /// Use of the 101 Informational status code is forbidden in HTTP/2. + ERR_HTTP2_STATUS_101, + + /// An invalid HTTP status code has been specified. Status codes must be an integer between 100 and 599 (inclusive). + ERR_HTTP2_STATUS_INVALID, + + /// An Http2Stream was destroyed before any data was transmitted to the connected peer. + ERR_HTTP2_STREAM_CANCEL, + + /// A non-zero error code was been specified in an RST_STREAM frame. + ERR_HTTP2_STREAM_ERROR, + + /// When setting the priority for an HTTP/2 stream, the stream may be marked as a dependency for a parent stream. This error code is used when an attempt is made to mark a stream and dependent of itself. + ERR_HTTP2_STREAM_SELF_DEPENDENCY, + + /// The limit of acceptable invalid HTTP/2 protocol frames sent by the peer, as specified through the maxSessionInvalidFrames option, has been exceeded. + ERR_HTTP2_TOO_MANY_INVALID_FRAMES, + + /// Trailing headers have already been sent on the Http2Stream. + ERR_HTTP2_TRAILERS_ALREADY_SENT, + + /// The http2stream.sendTrailers() method cannot be called until after the 'wantTrailers' event is emitted on an Http2Stream object. The 'wantTrailers' event will only be emitted if the waitForTrailers option is set for the Http2Stream. + ERR_HTTP2_TRAILERS_NOT_READY, + + /// http2.connect() was passed a URL that uses any protocol other than http: or https:. + ERR_HTTP2_UNSUPPORTED_PROTOCOL, + + /// An attempt was made to construct an object using a non-public constructor. + ERR_ILLEGAL_CONSTRUCTOR, + + /// An import assertion has failed, preventing the specified module to be imported. + /// Added in: v17.1.0 + ERR_IMPORT_ASSERTION_TYPE_FAILED, + + /// An import assertion is missing, preventing the specified module to be imported. + /// Added in: v17.1.0 + ERR_IMPORT_ASSERTION_TYPE_MISSING, + + /// An import assertion is not supported by this version of Node.js. + /// Added in: v17.1.0 + ERR_IMPORT_ASSERTION_TYPE_UNSUPPORTED, + + /// An option pair is incompatible with each other and cannot be used at the same time. + ERR_INCOMPATIBLE_OPTION_PAIR, + + /// Stability: 1 - Experimental + ERR_INPUT_TYPE_NOT_ALLOWED, + + /// The --input-type flag was used to attempt to execute a file. This flag can only be used with input via --eval, --print or STDIN. + /// While using the inspector module, an attempt was made to activate the inspector when it already started to listen on a port. Use inspector.close() before activating it on a different address. + ERR_INSPECTOR_ALREADY_ACTIVATED, + + /// While using the inspector module, an attempt was made to connect when the inspector was already connected. + ERR_INSPECTOR_ALREADY_CONNECTED, + + /// While using the inspector module, an attempt was made to use the inspector after the session had already closed. + ERR_INSPECTOR_CLOSED, + + /// An error occurred while issuing a command via the inspector module. + ERR_INSPECTOR_COMMAND, + + /// The inspector is not active when inspector.waitForDebugger() is called. + ERR_INSPECTOR_NOT_ACTIVE, + + /// The inspector module is not available for use. + ERR_INSPECTOR_NOT_AVAILABLE, + + /// While using the inspector module, an attempt was made to use the inspector before it was connected. + ERR_INSPECTOR_NOT_CONNECTED, + + /// An API was called on the main thread that can only be used from the worker thread. + ERR_INSPECTOR_NOT_WORKER, + + /// There was a bug in Node.js or incorrect usage of Node.js internals. To fix the error, open an issue at https://github.com/nodejs/node/issues. + ERR_INTERNAL_ASSERTION, + + /// The provided address family is not understood by the Node.js API. + ERR_INVALID_ADDRESS_FAMILY, + + /// An argument of the wrong type was passed to a Node.js API. + ERR_INVALID_ARG_TYPE, + + /// An invalid or unsupported value was passed for a given argument. + ERR_INVALID_ARG_VALUE, + + /// An invalid asyncId or triggerAsyncId was passed using AsyncHooks. An id less than -1 should never happen. + ERR_INVALID_ASYNC_ID, + + /// A swap was performed on a Buffer but its size was not compatible with the operation. + ERR_INVALID_BUFFER_SIZE, + + /// A callback function was required but was not been provided to a Node.js API. + ERR_INVALID_CALLBACK, + + /// Invalid characters were detected in headers. + ERR_INVALID_CHAR, + + /// A cursor on a given stream cannot be moved to a specified row without a specified column. + ERR_INVALID_CURSOR_POS, + + /// A file descriptor ('fd') was not valid (e.g. it was a negative value). + ERR_INVALID_FD, + + /// A file descriptor ('fd') type was not valid. + ERR_INVALID_FD_TYPE, + + /// A Node.js API that consumes file: URLs (such as certain functions in the fs module) encountered a file URL with an incompatible host. This situation can only occur on Unix-like systems where only localhost or an empty host is supported. + ERR_INVALID_FILE_URL_HOST, + + /// A Node.js API that consumes file: URLs (such as certain functions in the fs module) encountered a file URL with an incompatible path. The exact semantics for determining whether a path can be used is platform-dependent. + ERR_INVALID_FILE_URL_PATH, + + /// An attempt was made to send an unsupported "handle" over an IPC communication channel to a child process. See subprocess.send() and process.send() for more information. + ERR_INVALID_HANDLE_TYPE, + + /// An invalid HTTP token was supplied. + ERR_INVALID_HTTP_TOKEN, + + /// An IP address is not valid. + ERR_INVALID_IP_ADDRESS, + + /// Added in: v15.0.0, v14.18.0 + /// An attempt was made to load a module that does not exist or was otherwise not valid. + ERR_INVALID_MODULE, + + /// The imported module string is an invalid URL, package name, or package subpath specifier. + ERR_INVALID_MODULE_SPECIFIER, + + /// An invalid package.json file failed parsing. + ERR_INVALID_PACKAGE_CONFIG, + + /// The package.json "exports" field contains an invalid target mapping value for the attempted module resolution. + ERR_INVALID_PACKAGE_TARGET, + + /// While using the Performance Timing API (perf_hooks), a performance mark is invalid. + ERR_INVALID_PERFORMANCE_MARK, + + /// An invalid options.protocol was passed to http.request(). + ERR_INVALID_PROTOCOL, + + /// Both breakEvalOnSigint and eval options were set in the REPL config, which is not supported. + ERR_INVALID_REPL_EVAL_CONFIG, + + /// The input may not be used in the REPL. The conditions under which this error is used are described in the REPL documentation. + ERR_INVALID_REPL_INPUT, + + /// Thrown in case a function option does not provide a valid value for one of its returned object properties on execution. + ERR_INVALID_RETURN_PROPERTY, + + /// Thrown in case a function option does not provide an expected value type for one of its returned object properties on execution. + ERR_INVALID_RETURN_PROPERTY_VALUE, + + /// Thrown in case a function option does not return an expected value type on execution, such as when a function is expected to return a promise. + ERR_INVALID_RETURN_VALUE, + + /// Indicates that an operation cannot be completed due to an invalid state. For instance, an object may have already been destroyed, or may be performing another operation. + /// Added in: v15.0.0 + ERR_INVALID_STATE, + + /// A Buffer, TypedArray, DataView or string was provided as stdio input to an asynchronous fork. See the documentation for the child_process module for more information. + ERR_INVALID_SYNC_FORK_INPUT, + + /// A Node.js API function was called with an incompatible this value. + /// ```js + /// const urlSearchParams = new URLSearchParams('foo=bar&baz=new'); + /// const buf = Buffer.alloc(1); + /// urlSearchParams.has.call(buf, 'foo'); + /// ``` + /// Throws a TypeError with code 'ERR_INVALID_THIS' + ERR_INVALID_THIS, + + /// An invalid transfer object was passed to postMessage(). + ERR_INVALID_TRANSFER_OBJECT, + + /// An element in the iterable provided to the WHATWG URLSearchParams constructor did not represent a [name, value] tuple – that is, if an element is not iterable, or does not consist of exactly two elements. + ERR_INVALID_TUPLE, + + /// An invalid URI was passed. + ERR_INVALID_URI, + + /// An invalid URL was passed to the WHATWG URL constructor or the legacy url.parse() to be parsed. The thrown error object typically has an additional property 'input' that contains the URL that failed to parse. + ERR_INVALID_URL, + + /// An attempt was made to use a URL of an incompatible scheme (protocol) for a specific purpose. It is only used in the WHATWG URL API support in the fs module (which only accepts URLs with 'file' scheme), but may be used in other Node.js APIs as well in the future. + ERR_INVALID_URL_SCHEME, + + /// An attempt was made to use an IPC communication channel that was already closed. + ERR_IPC_CHANNEL_CLOSED, + + /// An attempt was made to disconnect an IPC communication channel that was already disconnected. See the documentation for the child_process module for more information. + ERR_IPC_DISCONNECTED, + + /// An attempt was made to create a child Node.js process using more than one IPC communication channel. See the documentation for the child_process module for more information. + ERR_IPC_ONE_PIPE, + + /// An attempt was made to open an IPC communication channel with a synchronously forked Node.js process. See the documentation for the child_process module for more information. + ERR_IPC_SYNC_FORK, + + /// An attempt was made to load a resource, but the resource did not match the integrity defined by the policy manifest. See the documentation for policy manifests for more information. + ERR_MANIFEST_ASSERT_INTEGRITY, + + /// An attempt was made to load a resource, but the resource was not listed as a dependency from the location that attempted to load it. See the documentation for policy manifests for more information. + ERR_MANIFEST_DEPENDENCY_MISSING, + + /// An attempt was made to load a policy manifest, but the manifest had multiple entries for a resource which did not match each other. Update the manifest entries to match in order to resolve this error. See the documentation for policy manifests for more information. + ERR_MANIFEST_INTEGRITY_MISMATCH, + + /// A policy manifest resource had an invalid value for one of its fields. Update the manifest entry to match in order to resolve this error. See the documentation for policy manifests for more information. + ERR_MANIFEST_INVALID_RESOURCE_FIELD, + + /// A policy manifest resource had an invalid value for one of its dependency mappings. Update the manifest entry to match to resolve this error. See the documentation for policy manifests for more information. + ERR_MANIFEST_INVALID_SPECIFIER, + + /// An attempt was made to load a policy manifest, but the manifest was unable to be parsed. See the documentation for policy manifests for more information. + ERR_MANIFEST_PARSE_POLICY, + + /// An attempt was made to read from a policy manifest, but the manifest initialization has not yet taken place. This is likely a bug in Node.js. + ERR_MANIFEST_TDZ, + + /// A policy manifest was loaded, but had an unknown value for its "onerror" behavior. See the documentation for policy manifests for more information. + ERR_MANIFEST_UNKNOWN_ONERROR, + + /// An attempt was made to allocate memory (usually in the C++ layer) but it failed. + ERR_MEMORY_ALLOCATION_FAILED, + + /// Added in: v14.5.0, v12.19.0 + /// A message posted to a MessagePort could not be deserialized in the target vm Context. Not all Node.js objects can be successfully instantiated in any context at this time, and attempting to transfer them using postMessage() can fail on the receiving side in that case. + ERR_MESSAGE_TARGET_CONTEXT_UNAVAILABLE, + + /// A method is required but not implemented. + ERR_METHOD_NOT_IMPLEMENTED, + + /// A required argument of a Node.js API was not passed. This is only used for strict compliance with the API specification (which in some cases may accept func(undefined) but not func()). In most native Node.js APIs, func(undefined) and func() are treated identically, and the ERR_INVALID_ARG_TYPE error code may be used instead. + ERR_MISSING_ARGS, + + /// For APIs that accept options objects, some options might be mandatory. This code is thrown if a required option is missing. + ERR_MISSING_OPTION, + + /// An attempt was made to read an encrypted key without specifying a passphrase. + ERR_MISSING_PASSPHRASE, + + /// The V8 platform used by this instance of Node.js does not support creating Workers. This is caused by lack of embedder support for Workers. In particular, this error will not occur with standard builds of Node.js. + ERR_MISSING_PLATFORM_FOR_WORKER, + + /// Added in: v15.0.0 + /// An object that needs to be explicitly listed in the transferList argument is in the object passed to a postMessage() call, but is not provided in the transferList for that call. Usually, this is a MessagePort. + /// In Node.js versions prior to v15.0.0, the error code being used here was ERR_MISSING_MESSAGE_PORT_IN_TRANSFER_LIST. However, the set of transferable object types has been expanded to cover more types than MessagePort. + ERR_MISSING_TRANSFERABLE_IN_TRANSFER_LIST, + + /// Stability: 1 - Experimental + /// An ES Module could not be resolved. + ERR_MODULE_NOT_FOUND, + + /// A callback was called more than once. + /// A callback is almost always meant to only be called once as the query can either be fulfilled or rejected but not both at the same time. The latter would be possible by calling a callback more than once. + ERR_MULTIPLE_CALLBACK, + + /// While using Node-API, a constructor passed was not a function. + ERR_NAPI_CONS_FUNCTION, + + /// While calling napi_create_dataview(), a given offset was outside the bounds of the dataview or offset + length was larger than a length of given buffer. + ERR_NAPI_INVALID_DATAVIEW_ARGS, + + /// While calling napi_create_typedarray(), the provided offset was not a multiple of the element size. + ERR_NAPI_INVALID_TYPEDARRAY_ALIGNMENT, + + /// While calling napi_create_typedarray(), (length * size_of_element) + byte_offset was larger than the length of given buffer. + ERR_NAPI_INVALID_TYPEDARRAY_LENGTH, + + /// An error occurred while invoking the JavaScript portion of the thread-safe function. + ERR_NAPI_TSFN_CALL_JS, + + /// An error occurred while attempting to retrieve the JavaScript undefined value. + ERR_NAPI_TSFN_GET_UNDEFINED, + + /// On the main thread, values are removed from the queue associated with the thread-safe function in an idle loop. This error indicates that an error has occurred when attempting to start the loop. + ERR_NAPI_TSFN_START_IDLE_LOOP, + + /// Once no more items are left in the queue, the idle loop must be suspended. This error indicates that the idle loop has failed to stop. + ERR_NAPI_TSFN_STOP_IDLE_LOOP, + + /// An attempt was made to use crypto features while Node.js was not compiled with OpenSSL crypto support. + ERR_NO_CRYPTO, + + /// An attempt was made to use features that require ICU, but Node.js was not compiled with ICU support. + ERR_NO_ICU, + + /// A non-context-aware native addon was loaded in a process that disallows them. + ERR_NON_CONTEXT_AWARE_DISABLED, + + /// A given value is out of the accepted range. + ERR_OUT_OF_RANGE, + + /// The package.json "imports" field does not define the given internal package specifier mapping. + ERR_PACKAGE_IMPORT_NOT_DEFINED, + + /// The package.json "exports" field does not export the requested subpath. Because exports are encapsulated, private internal modules that are not exported cannot be imported through the package resolution, unless using an absolute URL. + ERR_PACKAGE_PATH_NOT_EXPORTED, + + /// An invalid timestamp value was provided for a performance mark or measure. + ERR_PERFORMANCE_INVALID_TIMESTAMP, + + /// Invalid options were provided for a performance measure. + ERR_PERFORMANCE_MEASURE_INVALID_OPTIONS, + + /// Accessing Object.prototype.__proto__ has been forbidden using --disable-proto=throw. Object.getPrototypeOf and Object.setPrototypeOf should be used to get and set the prototype of an object. + ERR_PROTO_ACCESS, + + /// Stability: 1 - Experimental + /// An attempt was made to require() an ES Module. + ERR_REQUIRE_ESM, + + /// Script execution was interrupted by SIGINT (For example, Ctrl+C was pressed.) + ERR_SCRIPT_EXECUTION_INTERRUPTED, + + /// Script execution timed out, possibly due to bugs in the script being executed. + ERR_SCRIPT_EXECUTION_TIMEOUT, + + /// The server.listen() method was called while a net.Server was already listening. This applies to all instances of net.Server, including HTTP, HTTPS, and HTTP/2 Server instances. + ERR_SERVER_ALREADY_LISTEN, + + /// The server.close() method was called when a net.Server was not running. This applies to all instances of net.Server, including HTTP, HTTPS, and HTTP/2 Server instances. + ERR_SERVER_NOT_RUNNING, + + /// An attempt was made to bind a socket that has already been bound. + ERR_SOCKET_ALREADY_BOUND, + + /// An invalid (negative) size was passed for either the recvBufferSize or sendBufferSize options in dgram.createSocket(). + ERR_SOCKET_BAD_BUFFER_SIZE, + + /// An API function expecting a port >= 0 and < 65536 received an invalid value. + ERR_SOCKET_BAD_PORT, + + /// An API function expecting a socket type (udp4 or udp6) received an invalid value. + ERR_SOCKET_BAD_TYPE, + + /// While using dgram.createSocket(), the size of the receive or send Buffer could not be determined. + ERR_SOCKET_BUFFER_SIZE, + + /// An attempt was made to operate on an already closed socket. + ERR_SOCKET_CLOSED, + + /// A dgram.connect() call was made on an already connected socket. + ERR_SOCKET_DGRAM_IS_CONNECTED, + + /// A dgram.disconnect() or dgram.remoteAddress() call was made on a disconnected socket. + ERR_SOCKET_DGRAM_NOT_CONNECTED, + + /// A call was made and the UDP subsystem was not running. + ERR_SOCKET_DGRAM_NOT_RUNNING, + + /// A string was provided for a Subresource Integrity check, but was unable to be parsed. Check the format of integrity attributes by looking at the Subresource Integrity specification. + ERR_SRI_PARSE, + + /// A stream method was called that cannot complete because the stream was finished. + ERR_STREAM_ALREADY_FINISHED, + + /// An attempt was made to call stream.pipe() on a Writable stream. + ERR_STREAM_CANNOT_PIPE, + + /// A stream method was called that cannot complete because the stream was destroyed using stream.destroy(). + ERR_STREAM_DESTROYED, + + /// An attempt was made to call stream.write() with a null chunk. + ERR_STREAM_NULL_VALUES, + + /// An error returned by stream.finished() and stream.pipeline(), when a stream or a pipeline ends non gracefully with no explicit error. + ERR_STREAM_PREMATURE_CLOSE, + + /// An attempt was made to call stream.push() after a null(EOF) had been pushed to the stream. + ERR_STREAM_PUSH_AFTER_EOF, + + /// An attempt was made to call stream.unshift() after the 'end' event was emitted. + ERR_STREAM_UNSHIFT_AFTER_END_EVENT, + + /// Prevents an abort if a string decoder was set on the Socket or if the decoder is in objectMode. + /// const Socket = require('net').Socket; + /// const instance = new Socket(); + /// instance.setEncoding('utf8'); + ERR_STREAM_WRAP, + + /// An attempt was made to call stream.write() after stream.end() has been called. + ERR_STREAM_WRITE_AFTER_END, + + /// An attempt has been made to create a string longer than the maximum allowed length. + ERR_STRING_TOO_LONG, + + /// An artificial error object used to capture the call stack for diagnostic reports. + ERR_SYNTHETIC, + + /// An unspecified or non-specific system error has occurred within the Node.js process. The error object will have an err.info object property with additional details. + ERR_SYSTEM_ERROR, + + /// This error is thrown by checkServerIdentity if a user-supplied subjectaltname property violates encoding rules. Certificate objects produced by Node.js itself always comply with encoding rules and will never cause this error. + ERR_TLS_CERT_ALTNAME_FORMAT, + + /// While using TLS, the host name/IP of the peer did not match any of the subjectAltNames in its certificate. + ERR_TLS_CERT_ALTNAME_INVALID, + + /// While using TLS, the parameter offered for the Diffie-Hellman (DH) key-agreement protocol is too small. By default, the key length must be greater than or equal to 1024 bits to avoid vulnerabilities, even though it is strongly recommended to use 2048 bits or larger for stronger security. + ERR_TLS_DH_PARAM_SIZE, + + /// A TLS/SSL handshake timed out. In this case, the server must also abort the connection. + ERR_TLS_HANDSHAKE_TIMEOUT, + + /// The context must be a SecureContext. + /// Added in: v13.3.0 + ERR_TLS_INVALID_CONTEXT, + + /// The specified secureProtocol method is invalid. It is either unknown, or disabled because it is insecure. + ERR_TLS_INVALID_PROTOCOL_METHOD, + + /// Valid TLS protocol versions are 'TLSv1', 'TLSv1.1', or 'TLSv1.2'. + ERR_TLS_INVALID_PROTOCOL_VERSION, + + /// The TLS socket must be connected and securily established. Ensure the 'secure' event is emitted before continuing. + /// Added in: v13.10.0, v12.17.0 + ERR_TLS_INVALID_STATE, + + /// Attempting to set a TLS protocol minVersion or maxVersion conflicts with an attempt to set the secureProtocol explicitly. Use one mechanism or the other. + ERR_TLS_PROTOCOL_VERSION_CONFLICT, + + /// Failed to set PSK identity hint. Hint may be too long. + ERR_TLS_PSK_SET_IDENTIY_HINT_FAILED, + + /// An attempt was made to renegotiate TLS on a socket instance with TLS disabled. + ERR_TLS_RENEGOTIATION_DISABLED, + + /// While using TLS, the server.addContext() method was called without providing a host name in the first parameter. + ERR_TLS_REQUIRED_SERVER_NAME, + + /// An excessive amount of TLS renegotiations is detected, which is a potential vector for denial-of-service attacks. + ERR_TLS_SESSION_ATTACK, + + /// An attempt was made to issue Server Name Indication from a TLS server-side socket, which is only valid from a client. + ERR_TLS_SNI_FROM_SERVER, + + /// The trace_events.createTracing() method requires at least one trace event category. + ERR_TRACE_EVENTS_CATEGORY_REQUIRED, + + /// The trace_events module could not be loaded because Node.js was compiled with the --without-v8-platform flag. + ERR_TRACE_EVENTS_UNAVAILABLE, + + /// A Transform stream finished while it was still transforming. + ERR_TRANSFORM_ALREADY_TRANSFORMING, + + /// A Transform stream finished with data still in the write buffer. + ERR_TRANSFORM_WITH_LENGTH_0, + + /// The initialization of a TTY failed due to a system error. + ERR_TTY_INIT_FAILED, + + /// Function was called within a process.on('exit') handler that shouldn't be called within process.on('exit') handler. + ERR_UNAVAILABLE_DURING_EXIT, + + /// process.setUncaughtExceptionCaptureCallback() was called twice, without first resetting the callback to null. + /// This error is designed to prevent accidentally overwriting a callback registered from another module. + ERR_UNCAUGHT_EXCEPTION_CAPTURE_ALREADY_SET, + + /// A string that contained unescaped characters was received. + ERR_UNESCAPED_CHARACTERS, + + /// An unhandled error occurred (for instance, when an 'error' event is emitted by an EventEmitter but an 'error' handler is not registered). + ERR_UNHANDLED_ERROR, + + /// Used to identify a specific kind of internal Node.js error that should not typically be triggered by user code. Instances of this error point to an internal bug within the Node.js binary itself. + ERR_UNKNOWN_BUILTIN_MODULE, + + /// A Unix group or user identifier that does not exist was passed. + ERR_UNKNOWN_CREDENTIAL, + + /// An invalid or unknown encoding option was passed to an API. + ERR_UNKNOWN_ENCODING, + + /// Stability: 1 - Experimental + /// An attempt was made to load a module with an unknown or unsupported file extension. + ERR_UNKNOWN_FILE_EXTENSION, + + /// An attempt was made to load a module with an unknown or unsupported format. + ERR_UNKNOWN_MODULE_FORMAT, + + /// An invalid or unknown process signal was passed to an API expecting a valid signal (such as subprocess.kill()). + ERR_UNKNOWN_SIGNAL, + + /// import a directory URL is unsupported. Instead, self-reference a package using its name and define a custom subpath in the "exports" field of the package.json file. + /// ```js + /// import './'; // unsupported + /// import './index.js'; // supported + /// import 'package-name'; // supported + /// ``` + ERR_UNSUPPORTED_DIR_IMPORT, + + /// import with URL schemes other than file and data is unsupported. + ERR_UNSUPPORTED_ESM_URL_SCHEME, + + /// While using the Performance Timing API (perf_hooks), no valid performance entry types are found. + ERR_VALID_PERFORMANCE_ENTRY_TYPE, + + /// A dynamic import callback was not specified. + ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING, + + /// The module attempted to be linked is not eligible for linking, because of one of the following reasons: + /// - It has already been linked (linkingStatus is 'linked') + /// - It is being linked (linkingStatus is 'linking') + /// - Linking has failed for this module (linkingStatus is 'errored') + ERR_VM_MODULE_ALREADY_LINKED, + + /// The cachedData option passed to a module constructor is invalid. + ERR_VM_MODULE_CACHED_DATA_REJECTED, + + /// Cached data cannot be created for modules which have already been evaluated. + ERR_VM_MODULE_CANNOT_CREATE_CACHED_DATA, + + /// The module being returned from the linker function is from a different context than the parent module. Linked modules must share the same context. + ERR_VM_MODULE_DIFFERENT_CONTEXT, + + /// The linker function returned a module for which linking has failed. + ERR_VM_MODULE_LINKING_ERRORED, + + /// The module was unable to be linked due to a failure. + ERR_VM_MODULE_LINK_FAILURE, + + /// The fulfilled value of a linking promise is not a vm.Module object. + ERR_VM_MODULE_NOT_MODULE, + + /// The current module's status does not allow for this operation. The specific meaning of the error depends on the specific function. + ERR_VM_MODULE_STATUS, + + /// The WASI instance has already started. + ERR_WASI_ALREADY_STARTED, + + /// The WASI instance has not been started. + ERR_WASI_NOT_STARTED, + + /// The Worker initialization failed. + ERR_WORKER_INIT_FAILED, + + /// The execArgv option passed to the Worker constructor contains invalid flags. + ERR_WORKER_INVALID_EXEC_ARGV, + + /// An operation failed because the Worker instance is not currently running. + ERR_WORKER_NOT_RUNNING, + + /// The Worker instance terminated because it reached its memory limit. + ERR_WORKER_OUT_OF_MEMORY, + + /// The path for the main script of a worker is neither an absolute path nor a relative path starting with ./ or ../. + ERR_WORKER_PATH, + + /// All attempts at serializing an uncaught exception from a worker thread failed. + ERR_WORKER_UNSERIALIZABLE_ERROR, + + /// The requested functionality is not supported in worker threads. + ERR_WORKER_UNSUPPORTED_OPERATION, + + /// Creation of a zlib object failed due to incorrect configuration. + ERR_ZLIB_INITIALIZATION_FAILED, + + /// Too much HTTP header data was received. In order to protect against malicious or malconfigured clients, if more than 8 KB of HTTP header data is received then HTTP parsing will abort without a request or response object being created, and an Error with this code will be emitted. + HPE_HEADER_OVERFLOW, + + /// Server is sending both a Content-Length header and Transfer-Encoding: chunked. + /// Transfer-Encoding: chunked allows the server to maintain an HTTP persistent connection for dynamically generated content. In this case, the Content-Length HTTP header cannot be used. + /// Use Content-Length or Transfer-Encoding: chunked. + HPE_UNEXPECTED_CONTENT_LENGTH, + + /// History + /// A module file could not be resolved while attempting a require() or import operation. + MODULE_NOT_FOUND, + + // -- Deprecated --- + + /// The value passed to postMessage() contained an object that is not supported for transferring. + ERR_CANNOT_TRANSFER_OBJECT, + + /// The UTF-16 encoding was used with hash.digest(). While the hash.digest() method does allow an encoding argument to be passed in, causing the method to return a string rather than a Buffer, the UTF-16 encoding (e.g. ucs or utf16le) is not supported. + /// Added in: v9.0.0Removed in: v12.12.0 + ERR_CRYPTO_HASH_DIGEST_NO_UTF16, + + /// Added in: v9.0.0Removed in: v10.0.0 + ERR_HTTP2_FRAME_ERROR, + + /// Used when a failure occurs sending an individual frame on the HTTP/2 session. + /// Added in: v9.0.0Removed in: v10.0.0 + ERR_HTTP2_HEADERS_OBJECT, + + /// Used when an HTTP/2 Headers Object is expected. + /// Added in: v9.0.0Removed in: v10.0.0 + /// Used when a required header is missing in an HTTP/2 message. + ERR_HTTP2_HEADER_REQUIRED, + + /// HTTP/2 informational headers must only be sent prior to calling the Http2Stream.prototype.respond() method. + /// Added in: v9.0.0Removed in: v10.0.0 + ERR_HTTP2_INFO_HEADERS_AFTER_RESPOND, + + /// Used when an action has been performed on an HTTP/2 Stream that has already been closed. + /// Added in: v9.0.0Removed in: v10.0.0 + ERR_HTTP2_STREAM_CLOSED, + + /// Used when an invalid character is found in an HTTP response status message (reason phrase). + /// Added in: v10.0.0Removed in: v11.0.0 + ERR_HTTP_INVALID_CHAR, + + /// A given index was out of the accepted range (e.g. negative offsets). + /// Added in: v8.0.0Removed in: v15.0.0 + ERR_INDEX_OUT_OF_RANGE, + + /// An invalid or unexpected value was passed in an options object. + ERR_INVALID_OPT_VALUE, + + /// Added in: v9.0.0Removed in: v15.0.0 + /// An invalid or unknown file encoding was passed. + ERR_INVALID_OPT_VALUE_ENCODING, + + /// Removed in: v15.0.0 + /// This error code was replaced by ERR_MISSING_TRANSFERABLE_IN_TRANSFER_LIST in Node.js v15.0.0, because it is no longer accurate as other types of transferable objects also exist now. + ERR_MISSING_MESSAGE_PORT_IN_TRANSFER_LIST, + + /// Added in: v9.0.0Removed in: v10.0.0 + /// Used by the Node-API when Constructor.prototype is not an object. + ERR_NAPI_CONS_PROTOTYPE_OBJECT, + + /// A Node.js API was called in an unsupported manner, such as Buffer.write(string, encoding, offset[, length]). + ERR_NO_LONGER_SUPPORTED, + + /// An operation failed. This is typically used to signal the general failure of an asynchronous operation. + /// Added in: v15.0.0 + ERR_OPERATION_FAILED, + + /// Added in: v9.0.0Removed in: v10.0.0 + /// Used generically to identify that an operation caused an out of memory condition. + ERR_OUTOFMEMORY, + + /// Added in: v9.0.0Removed in: v10.0.0 + /// The repl module was unable to parse data from the REPL history file. + ERR_PARSE_HISTORY_DATA, + + /// Data could not be sent on a socket. + ERR_SOCKET_CANNOT_SEND, + + /// An attempt was made to close the process.stderr stream. By design, Node.js does not allow stdout or stderr streams to be closed by user code. + ERR_STDERR_CLOSE, + + /// An attempt was made to close the process.stdout stream. By design, Node.js does not allow stdout or stderr streams to be closed by user code. + ERR_STDOUT_CLOSE, + + /// Added in: v9.0.0Removed in: v10.0.0 + /// Used when an attempt is made to use a readable stream that has not implemented readable._read(). + ERR_STREAM_READ_NOT_IMPLEMENTED, + + /// Added in: v9.0.0Removed in: v10.0.0 + /// Used when a TLS renegotiation request has failed in a non-specific way. + /// Added in: v10.5.0Removed in: v14.0.0 + ERR_TLS_RENEGOTIATION_FAILED, + + /// A SharedArrayBuffer whose memory is not managed by the JavaScript engine or by Node.js was encountered during serialization. Such a SharedArrayBuffer cannot be serialized. + /// This can only happen when native addons create SharedArrayBuffers in "externalized" mode, or put existing SharedArrayBuffer into externalized mode. + ERR_TRANSFERRING_EXTERNALIZED_SHAREDARRAYBUFFER, + + /// Added in: v8.0.0Removed in: v11.7.0 + /// An attempt was made to launch a Node.js process with an unknown stdin file type. This error is usually an indication of a bug within Node.js itself, although it is possible for user code to trigger it. + ERR_UNKNOWN_STDIN_TYPE, + + /// Added in: v8.0.0Removed in: v11.7.0 + /// An attempt was made to launch a Node.js process with an unknown stdout or stderr file type. This error is usually an indication of a bug within Node.js itself, although it is possible for user code to trigger it. + ERR_UNKNOWN_STREAM_TYPE, + + /// The V8 BreakIterator API was used but the full ICU data set is not installed. + ERR_V8BREAKITERATOR, + + /// Added in: v9.0.0Removed in: v10.0.0 + /// Used when a given value is out of the accepted range. + ERR_VALUE_OUT_OF_RANGE, + + /// The module must be successfully linked before instantiation. + ERR_VM_MODULE_NOT_LINKED, + + /// Added in: v11.0.0Removed in: v16.9.0 + /// The pathname used for the main script of a worker has an unknown file extension. + ERR_WORKER_UNSUPPORTED_EXTENSION, + + /// Added in: v9.0.0Removed in: v10.0.0 + ERR_ZLIB_BINDING_CLOSED, + + /// Used when an attempt is made to use a zlib object after it has already been closed. + /// CPU USAGE + ERR_CPU_USAGE, +}; diff --git a/src/javascript/jsc/node/syscall.zig b/src/javascript/jsc/node/syscall.zig new file mode 100644 index 000000000..7dee85736 --- /dev/null +++ b/src/javascript/jsc/node/syscall.zig @@ -0,0 +1,465 @@ +// This file is entirely based on Zig's std.os +// The differences are in error handling +const std = @import("std"); +const os = std.os; +const builtin = @import("builtin"); + +const Syscall = @This(); +const Environment = @import("../../../global.zig").Environment; +const default_allocator = @import("../../../global.zig").default_allocator; +const JSC = @import("../../../jsc.zig"); +const SystemError = JSC.SystemError; +const darwin = os.darwin; +const MAX_PATH_BYTES = std.fs.MAX_PATH_BYTES; +const fd_t = std.os.fd_t; +const C = @import("../../../global.zig").C; +const linux = os.linux; +const Maybe = JSC.Node.Maybe; + +pub const system = if (Environment.isLinux) linux else darwin; +const libc = std.os.system; + +pub const Tag = enum(u8) { + TODO, + + access, + chmod, + chown, + clonefile, + close, + copy_file_range, + copyfile, + fchmod, + fchown, + fcntl, + fdatasync, + fstat, + fsync, + ftruncate, + futimens, + getdents64, + getdirentries64, + lchmod, + lchown, + link, + lseek, + lstat, + lutimes, + mkdir, + mkdtemp, + open, + pread, + pwrite, + read, + readlink, + rename, + stat, + symlink, + unlink, + utimes, + write, + getcwd, + chdir, + fcopyfile, + + pub var strings = std.EnumMap(Tag, JSC.C.JSStringRef).initFull(null); +}; +const PathString = @import("../../../global.zig").PathString; + +const mode_t = os.mode_t; + +const open_sym = system.open; + +const fstat_sym = if (builtin.os.tag == .linux and builtin.link_libc) + libc.fstat64 +else + libc.fstat; + +const mem = std.mem; + +pub fn getcwd(buf: *[std.fs.MAX_PATH_BYTES]u8) Maybe([]const u8) { + const Result = Maybe([]const u8); + buf[0] = 0; + const rc = std.c.getcwd(buf, std.fs.MAX_PATH_BYTES); + return if (rc != null) + Result{ .result = std.mem.sliceTo(rc.?[0..std.fs.MAX_PATH_BYTES], 0) } + else + Result.errnoSys(0, .getcwd).?; +} + +pub fn fchmod(fd: JSC.Node.FileDescriptor, mode: JSC.Node.Mode) Maybe(void) { + return Maybe(void).errnoSys(C.fchmod(fd, mode), .fchmod) orelse + Maybe(void).success; +} + +pub fn chdir(destination: [:0]const u8) Maybe(void) { + const rc = libc.chdir(destination); + return Maybe(void).errnoSys(rc, .chdir) orelse Maybe(void).success; +} + +pub fn stat(path: [:0]const u8) Maybe(os.Stat) { + var stat_ = mem.zeroes(os.Stat); + if (Maybe(os.Stat).errnoSys(libc.stat(path, &stat_), .stat)) |err| return err; + return Maybe(os.Stat){ .result = stat_ }; +} + +pub fn lstat(path: [:0]const u8) Maybe(os.Stat) { + var stat_ = mem.zeroes(os.Stat); + if (Maybe(os.Stat).errnoSys(C.lstat(path, &stat_), .lstat)) |err| return err; + return Maybe(os.Stat){ .result = stat_ }; +} + +pub fn fstat(fd: JSC.Node.FileDescriptor) Maybe(os.Stat) { + var stat_ = mem.zeroes(os.Stat); + if (Maybe(os.Stat).errnoSys(fstat_sym(fd, &stat_), .fstat)) |err| return err; + return Maybe(os.Stat){ .result = stat_ }; +} + +pub fn mkdir(file_path: [:0]const u8, flags: JSC.Node.Mode) Maybe(void) { + if (comptime Environment.isMac) { + return Maybe(void).errnoSysP(darwin.mkdir(file_path, flags), .mkdir, file_path) orelse Maybe(void).success; + } + + if (comptime Environment.isLinux) { + return Maybe(void).errnoSysP(linux.mkdir(file_path, flags), .mkdir, file_path) orelse Maybe(void).success; + } +} + +pub fn getErrno(rc: anytype) std.os.E { + if (comptime Environment.isMac) return std.os.errno(rc); + const Type = @TypeOf(rc); + + return switch (Type) { + comptime_int, usize => std.os.linux.getErrno(@as(usize, rc)), + i32, c_int, isize => std.os.linux.getErrno(@bitCast(usize, @as(isize, rc))), + else => @compileError("Not implemented yet for type " ++ @typeName(Type)), + }; +} + +pub fn open(file_path: [:0]const u8, flags: JSC.Node.Mode, perm: JSC.Node.Mode) Maybe(JSC.Node.FileDescriptor) { + while (true) { + const rc = Syscall.system.open(file_path, flags, perm); + return switch (Syscall.getErrno(rc)) { + .SUCCESS => .{ .result = @intCast(JSC.Node.FileDescriptor, rc) }, + .INTR => continue, + else => |err| { + return Maybe(std.os.fd_t){ + .err = .{ + .errno = @truncate(Syscall.Error.Int, @enumToInt(err)), + .syscall = .open, + }, + }; + }, + }; + } + + unreachable; +} + +// The zig standard library marks BADF as unreachable +// That error is not unreachable for us +pub fn close(fd: std.os.fd_t) ?Syscall.Error { + if (comptime Environment.isMac) { + // This avoids the EINTR problem. + return switch (darwin.getErrno(darwin.@"close$NOCANCEL"(fd))) { + .BADF => Syscall.Error{ .errno = @enumToInt(os.E.BADF), .syscall = .close }, + else => null, + }; + } + + if (comptime Environment.isLinux) { + return switch (linux.getErrno(linux.close(fd))) { + .BADF => Syscall.Error{ .errno = @enumToInt(os.E.BADF), .syscall = .close }, + else => null, + }; + } + + @compileError("Not implemented yet"); +} + +const max_count = switch (builtin.os.tag) { + .linux => 0x7ffff000, + .macos, .ios, .watchos, .tvos => std.math.maxInt(i32), + else => std.math.maxInt(isize), +}; + +pub fn write(fd: os.fd_t, bytes: []const u8) Maybe(usize) { + const adjusted_len = @minimum(max_count, bytes.len); + + while (true) { + const rc = libc.write(fd, bytes.ptr, adjusted_len); + if (Maybe(usize).errnoSys(rc, .write)) |err| { + if (err.getErrno() == .INTR) continue; + return err; + } + return Maybe(usize){ .result = @intCast(usize, rc) }; + } + unreachable; +} + +const pread_sym = if (builtin.os.tag == .linux and builtin.link_libc) + libc.pread64 +else + libc.pread; + +pub fn pread(fd: os.fd_t, buf: []u8, offset: i64) Maybe(usize) { + const adjusted_len = @minimum(buf.len, max_count); + + const ioffset = @bitCast(i64, offset); // the OS treats this as unsigned + while (true) { + const rc = pread_sym(fd, buf.ptr, adjusted_len, ioffset); + if (Maybe(usize).errnoSys(rc, .pread)) |err| { + if (err.getErrno() == .INTR) continue; + return err; + } + return Maybe(usize){ .result = @intCast(usize, rc) }; + } + unreachable; +} + +const pwrite_sym = if (builtin.os.tag == .linux and builtin.link_libc) + libc.pwrite64 +else + libc.pwrite; + +pub fn pwrite(fd: os.fd_t, bytes: []const u8, offset: i64) Maybe(usize) { + const adjusted_len = @minimum(bytes.len, max_count); + + const ioffset = @bitCast(i64, offset); // the OS treats this as unsigned + while (true) { + const rc = pwrite_sym(fd, bytes.ptr, adjusted_len, ioffset); + return if (Maybe(usize).errnoSys(rc, .pwrite)) |err| { + switch (err.getErrno()) { + .INTR => continue, + else => return err, + } + } else Maybe(usize){ .result = @intCast(usize, rc) }; + } + + unreachable; +} + +pub fn read(fd: os.fd_t, buf: []u8) Maybe(usize) { + const adjusted_len = @minimum(buf.len, max_count); + while (true) { + const rc = libc.read(fd, buf.ptr, adjusted_len); + if (Maybe(usize).errnoSys(rc, .read)) |err| { + if (err.getErrno() == .INTR) continue; + return err; + } + return Maybe(usize){ .result = @intCast(usize, rc) }; + } + unreachable; +} + +pub fn readlink(in: [:0]const u8, buf: []u8) Maybe(usize) { + while (true) { + const rc = libc.readlink(in, buf.ptr, buf.len); + + if (Maybe(usize).errnoSys(rc, .readlink)) |err| { + if (err.getErrno() == .INTR) continue; + return err; + } + return Maybe(usize){ .result = @intCast(usize, rc) }; + } + unreachable; +} + +pub fn rename(from: [:0]const u8, to: [:0]const u8) Maybe(void) { + while (true) { + if (Maybe(void).errnoSys(libc.rename(from, to), .rename)) |err| { + if (err.getErrno() == .INTR) continue; + return err; + } + return Maybe(void).success; + } + unreachable; +} + +pub fn chown(path: [:0]const u8, uid: os.uid_t, gid: os.gid_t) Maybe(void) { + while (true) { + if (Maybe(void).errnoSys(C.chown(path, uid, gid), .chown)) |err| { + if (err.getErrno() == .INTR) continue; + return err; + } + return Maybe(void).success; + } + unreachable; +} + +pub fn symlink(from: [:0]const u8, to: [:0]const u8) Maybe(void) { + while (true) { + if (Maybe(void).errnoSys(libc.symlink(from, to), .symlink)) |err| { + if (err.getErrno() == .INTR) continue; + return err; + } + return Maybe(void).success; + } + unreachable; +} + +pub fn clonefile(from: [:0]const u8, to: [:0]const u8) Maybe(void) { + if (comptime !Environment.isMac) @compileError("macOS only"); + + while (true) { + if (Maybe(void).errnoSys(C.darwin.clonefile(from, to, 0), .clonefile)) |err| { + if (err.getErrno() == .INTR) continue; + return err; + } + return Maybe(void).success; + } + unreachable; +} + +pub fn copyfile(from: [:0]const u8, to: [:0]const u8, flags: c_int) Maybe(void) { + if (comptime !Environment.isMac) @compileError("macOS only"); + + while (true) { + if (Maybe(void).errnoSys(C.darwin.copyfile(from, to, null, flags), .copyfile)) |err| { + if (err.getErrno() == .INTR) continue; + return err; + } + return Maybe(void).success; + } + unreachable; +} + +pub fn fcopyfile(fd_in: std.os.fd_t, fd_out: std.os.fd_t, flags: c_int) Maybe(void) { + if (comptime !Environment.isMac) @compileError("macOS only"); + + while (true) { + if (Maybe(void).errnoSys(darwin.fcopyfile(fd_in, fd_out, null, flags), .fcopyfile)) |err| { + if (err.getErrno() == .INTR) continue; + return err; + } + return Maybe(void).success; + } + unreachable; +} + +pub fn unlink(from: [:0]const u8) Maybe(void) { + while (true) { + if (Maybe(void).errno(libc.unlink(from), .unlink)) |err| { + if (err.getErrno() == .INTR) continue; + return err; + } + return Maybe(void).success; + } + unreachable; +} + +pub fn getFdPath(fd: fd_t, out_buffer: *[MAX_PATH_BYTES]u8) Maybe([]u8) { + switch (comptime builtin.os.tag) { + .windows => { + const windows = std.os.windows; + var wide_buf: [windows.PATH_MAX_WIDE]u16 = undefined; + const wide_slice = windows.GetFinalPathNameByHandle(fd, .{}, wide_buf[0..]) catch { + return Maybe([]u8){ .err = .{ .errno = .EBADF } }; + }; + + // Trust that Windows gives us valid UTF-16LE. + const end_index = std.unicode.utf16leToUtf8(out_buffer, wide_slice) catch unreachable; + return .{ .result = out_buffer[0..end_index] }; + }, + .macos, .ios, .watchos, .tvos => { + // On macOS, we can use F.GETPATH fcntl command to query the OS for + // the path to the file descriptor. + @memset(out_buffer, 0, MAX_PATH_BYTES); + if (Maybe([]u8).errnoSys(darwin.fcntl(fd, os.F.GETPATH, out_buffer), .fcntl)) |err| { + return err; + } + const len = mem.indexOfScalar(u8, out_buffer[0..], @as(u8, 0)) orelse MAX_PATH_BYTES; + return .{ .result = out_buffer[0..len] }; + }, + .linux => { + var procfs_buf: ["/proc/self/fd/-2147483648".len:0]u8 = undefined; + const proc_path = std.fmt.bufPrintZ(procfs_buf[0..], "/proc/self/fd/{d}\x00", .{fd}) catch unreachable; + + return switch (readlink(proc_path, out_buffer)) { + .err => |err| return .{ .err = err }, + .result => |len| return .{ .result = out_buffer[0..len] }, + }; + }, + // .solaris => { + // var procfs_buf: ["/proc/self/path/-2147483648".len:0]u8 = undefined; + // const proc_path = std.fmt.bufPrintZ(procfs_buf[0..], "/proc/self/path/{d}", .{fd}) catch unreachable; + + // const target = readlinkZ(proc_path, out_buffer) catch |err| switch (err) { + // error.UnsupportedReparsePointType => unreachable, + // error.NotLink => unreachable, + // else => |e| return e, + // }; + // return target; + // }, + else => @compileError("querying for canonical path of a handle is unsupported on this host"), + } +} + +pub const Error = struct { + const max_errno_value = brk: { + const errno_values = std.enums.values(os.E); + var err = @enumToInt(os.E.SUCCESS); + for (errno_values) |errn| { + err = @maximum(err, @enumToInt(errn)); + } + break :brk err; + }; + pub const Int: type = std.math.IntFittingRange(0, max_errno_value + 5); + + errno: Int, + syscall: Syscall.Tag = @intToEnum(Syscall.Tag, 0), + path: []const u8 = "", + + pub inline fn getErrno(this: Error) os.E { + return @intToEnum(os.E, this.errno); + } + + pub inline fn withPath(this: Error, path: anytype) Error { + return Error{ + .errno = this.errno, + .syscall = this.syscall, + .path = std.mem.span(path), + }; + } + + pub inline fn withSyscall(this: Error, syscall: Syscall) Error { + return Error{ + .errno = this.errno, + .syscall = syscall, + .path = this.path, + }; + } + + pub const todo_errno = std.math.maxInt(Int) - 1; + pub const todo = Error{ .errno = todo_errno }; + + pub fn toSystemError(this: Error) SystemError { + var sys = SystemError{ + .errno = @as(c_int, this.errno) * -1, + .syscall = JSC.ZigString.init(@tagName(this.syscall)), + }; + + // errno label + if (this.errno > 0 and this.errno < C.SystemErrno.max) { + const system_errno = @intToEnum(C.SystemErrno, this.errno); + sys.code = JSC.ZigString.init(@tagName(system_errno)); + if (C.SystemErrno.labels.get(system_errno)) |label| { + sys.message = JSC.ZigString.init(label); + } + } + + if (this.path.len > 0) { + sys.path = JSC.ZigString.init(this.path); + } + + return sys; + } + + pub fn toJS(this: Error, ctx: JSC.C.JSContextRef) JSC.C.JSObjectRef { + return this.toSystemError().toErrorInstance(ctx.ptr()).asObjectRef(); + } + + pub fn toJSC(this: Error, ptr: *JSC.JSGlobalObject) JSC.JSValue { + return this.toSystemError().toErrorInstance(ptr); + } +}; diff --git a/src/javascript/jsc/node/types.zig b/src/javascript/jsc/node/types.zig new file mode 100644 index 000000000..664df0d04 --- /dev/null +++ b/src/javascript/jsc/node/types.zig @@ -0,0 +1,2065 @@ +const std = @import("std"); +const builtin = @import("builtin"); +const _global = @import("../../../global.zig"); +const strings = _global.strings; +const string = _global.string; +const AsyncIO = @import("io"); +const JSC = @import("../../../jsc.zig"); +const PathString = JSC.PathString; +const Environment = _global.Environment; +const C = _global.C; +const Syscall = @import("./syscall.zig"); +const os = std.os; +const Buffer = JSC.MarkedArrayBuffer; +const IdentityContext = @import("../../../identity_context.zig").IdentityContext; +const logger = @import("../../../logger.zig"); +const Shimmer = @import("../bindings/shimmer.zig").Shimmer; +const is_bindgen: bool = std.meta.globalOption("bindgen", bool) orelse false; +const meta = _global.meta; + +/// Time in seconds. Not nanos! +pub const TimeLike = c_int; +pub const Mode = if (Environment.isLinux) u32 else std.os.mode_t; +const heap_allocator = _global.default_allocator; +pub fn DeclEnum(comptime T: type) type { + const fieldInfos = std.meta.declarations(T); + var enumFields: [fieldInfos.len]std.builtin.TypeInfo.EnumField = undefined; + var decls = [_]std.builtin.TypeInfo.Declaration{}; + inline for (fieldInfos) |field, i| { + enumFields[i] = .{ + .name = field.name, + .value = i, + }; + } + return @Type(.{ + .Enum = .{ + .layout = .Auto, + .tag_type = std.math.IntFittingRange(0, fieldInfos.len - 1), + .fields = &enumFields, + .decls = &decls, + .is_exhaustive = true, + }, + }); +} + +pub const FileDescriptor = os.fd_t; +pub const Flavor = enum { + sync, + promise, + callback, + + pub fn Wrap(comptime this: Flavor, comptime Type: type) type { + return comptime brk: { + switch (this) { + .sync => break :brk Type, + // .callback => { + // const Callback = CallbackTask(Type); + // }, + else => @compileError("Not implemented yet"), + } + }; + } +}; + +/// Node.js expects the error to include contextual information +/// - "syscall" +/// - "path" +/// - "errno" +pub fn Maybe(comptime ResultType: type) type { + return union(Tag) { + pub const ReturnType = ResultType; + + err: Syscall.Error, + result: ReturnType, + + pub const Tag = enum { err, result }; + + pub const success: @This() = @This(){ + .result = std.mem.zeroes(ReturnType), + }; + + pub const todo: @This() = @This(){ .err = Syscall.Error.todo }; + + pub inline fn getErrno(this: @This()) os.E { + return switch (this) { + .result => os.E.SUCCESS, + .err => |err| @intToEnum(os.E, err.errno), + }; + } + + pub inline fn errno(rc: anytype) ?@This() { + return switch (Syscall.getErrno(rc)) { + .SUCCESS => null, + else => |err| @This(){ + // always truncate + .err = .{ .errno = @truncate(Syscall.Error.Int, @enumToInt(err)) }, + }, + }; + } + + pub inline fn errnoSys(rc: anytype, syscall: Syscall.Tag) ?@This() { + return switch (Syscall.getErrno(rc)) { + .SUCCESS => null, + else => |err| @This(){ + // always truncate + .err = .{ .errno = @truncate(Syscall.Error.Int, @enumToInt(err)), .syscall = syscall }, + }, + }; + } + + pub inline fn errnoSysP(rc: anytype, syscall: Syscall.Tag, path: anytype) ?@This() { + return switch (Syscall.getErrno(rc)) { + .SUCCESS => null, + else => |err| @This(){ + // always truncate + .err = .{ .errno = @truncate(Syscall.Error.Int, @enumToInt(err)), .syscall = syscall, .path = std.mem.span(path) }, + }, + }; + } + }; +} + +pub const StringOrBuffer = union(Tag) { + string: string, + buffer: Buffer, + + pub const Tag = enum { string, buffer }; + + pub fn slice(this: StringOrBuffer) []const u8 { + return switch (this) { + .string => this.string, + .buffer => this.buffer.slice(), + }; + } + + pub export fn external_string_finalizer(_: ?*anyopaque, _: JSC.C.JSStringRef, buffer: *anyopaque, byteLength: usize) void { + _global.default_allocator.free(@ptrCast([*]const u8, buffer)[0..byteLength]); + } + + pub fn toJS(this: StringOrBuffer, ctx: JSC.C.JSContextRef, exception: JSC.C.ExceptionRef) JSC.C.JSValueRef { + return switch (this) { + .string => { + var external = JSC.C.JSStringCreateExternal(this.string.ptr, this.string.len, null, external_string_finalizer); + return JSC.C.JSValueMakeString(ctx, external); + }, + .buffer => this.buffer.toJSObjectRef(ctx, exception), + }; + } + + pub fn fromJS(global: *JSC.JSGlobalObject, value: JSC.JSValue, exception: JSC.C.ExceptionRef) ?StringOrBuffer { + return switch (value.jsType()) { + JSC.JSValue.JSType.String, JSC.JSValue.JSType.StringObject, JSC.JSValue.JSType.DerivedStringObject, JSC.JSValue.JSType.Object => { + var zig_str = JSC.ZigString.init(""); + value.toZigString(&zig_str, global); + if (zig_str.len == 0) { + JSC.throwInvalidArguments("Expected string to have length > 0", .{}, global.ref(), exception); + return null; + } + + return StringOrBuffer{ + .string = zig_str.slice(), + }; + }, + JSC.JSValue.JSType.ArrayBuffer => StringOrBuffer{ + .buffer = Buffer.fromArrayBuffer(global.ref(), value, exception), + }, + JSC.JSValue.JSType.Uint8Array, JSC.JSValue.JSType.DataView => StringOrBuffer{ + .buffer = Buffer.fromArrayBuffer(global.ref(), value, exception), + }, + else => null, + }; + } +}; +pub const ErrorCode = @import("./nodejs_error_code.zig").Code; + +// We can't really use Zig's error handling for syscalls because Node.js expects the "real" errno to be returned +// and various issues with std.os that make it too unstable for arbitrary user input (e.g. how .BADF is marked as unreachable) + +/// https://github.com/nodejs/node/blob/master/lib/buffer.js#L587 +pub const Encoding = enum(u8) { + utf8, + ucs2, + utf16le, + latin1, + ascii, + base64, + base64url, + hex, + + /// Refer to the buffer's encoding + buffer, + + const Eight = strings.ExactSizeMatcher(8); + /// Caller must verify the value is a string + pub fn fromStringValue(value: JSC.JSValue, global: *JSC.JSGlobalObject) ?Encoding { + var str = JSC.ZigString.Empty; + value.toZigString(&str, global); + const slice = str.slice(); + return switch (slice.len) { + 0...2 => null, + else => switch (Eight.matchLower(slice)) { + Eight.case("utf-8"), Eight.case("utf8") => Encoding.utf8, + Eight.case("ucs-2"), Eight.case("ucs2") => Encoding.ucs2, + Eight.case("utf16-le"), Eight.case("utf16le") => Encoding.utf16le, + Eight.case("latin1") => Encoding.latin1, + Eight.case("ascii") => Encoding.ascii, + Eight.case("base64") => Encoding.base64, + Eight.case("hex") => Encoding.hex, + Eight.case("buffer") => Encoding.buffer, + else => null, + }, + "base64url".len => brk: { + if (strings.eqlCaseInsensitiveASCII(slice, "base64url", false)) { + break :brk Encoding.base64url; + } + break :brk null; + }, + }; + } +}; + +const PathOrBuffer = union(Tag) { + path: PathString, + buffer: Buffer, + + pub const Tag = enum { path, buffer }; + + pub inline fn slice(this: PathOrBuffer) []const u8 { + return this.path.slice(); + } +}; + +pub fn CallbackTask(comptime Result: type) type { + return struct { + callback: JSC.C.JSObjectRef, + option: Option, + success: bool = false, + completion: AsyncIO.Completion, + + pub const Option = union { + err: JSC.SystemError, + result: Result, + }; + }; +} + +pub const PathLike = union(Tag) { + string: PathString, + buffer: Buffer, + url: void, + + pub const Tag = enum { string, buffer, url }; + + pub inline fn slice(this: PathLike) string { + return switch (this) { + .string => this.string.slice(), + .buffer => this.buffer.slice(), + else => unreachable, // TODO: + }; + } + + pub fn sliceZWithForceCopy(this: PathLike, buf: *[std.fs.MAX_PATH_BYTES]u8, comptime force: bool) [:0]const u8 { + var sliced = this.slice(); + + if (sliced.len == 0) return ""; + + if (comptime !force) { + if (sliced[sliced.len - 1] == 0) { + var sliced_ptr = sliced.ptr; + return sliced_ptr[0 .. sliced.len - 1 :0]; + } + } + + @memcpy(buf, sliced.ptr, sliced.len); + buf[sliced.len] = 0; + return buf[0..sliced.len :0]; + } + + pub inline fn sliceZ(this: PathLike, buf: *[std.fs.MAX_PATH_BYTES]u8) [:0]const u8 { + return sliceZWithForceCopy(this, buf, false); + } + + pub fn toJS(this: PathLike, ctx: JSC.C.JSContextRef, exception: JSC.C.ExceptionRef) JSC.C.JSValueRef { + return switch (this) { + .string => this.string.toJS(ctx, exception), + .buffer => this.buffer.toJSObjectRef(ctx, exception), + else => unreachable, + }; + } + + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?PathLike { + const arg = arguments.next() orelse return null; + switch (arg.jsType()) { + JSC.JSValue.JSType.Uint8Array, + JSC.JSValue.JSType.DataView, + => { + const buffer = Buffer.fromTypedArray(ctx, arg, exception); + if (exception.* != null) return null; + if (!Valid.pathBuffer(buffer, ctx, exception)) return null; + + JSC.C.JSValueProtect(ctx, arg.asObjectRef()); + arguments.eat(); + return PathLike{ .buffer = buffer }; + }, + + JSC.JSValue.JSType.ArrayBuffer => { + const buffer = Buffer.fromArrayBuffer(ctx, arg, exception); + if (exception.* != null) return null; + if (!Valid.pathBuffer(buffer, ctx, exception)) return null; + + JSC.C.JSValueProtect(ctx, arg.asObjectRef()); + arguments.eat(); + + return PathLike{ .buffer = buffer }; + }, + + JSC.JSValue.JSType.String, + JSC.JSValue.JSType.StringObject, + JSC.JSValue.JSType.DerivedStringObject, + => { + var zig_str = JSC.ZigString.init(""); + arg.toZigString(&zig_str, ctx.ptr()); + + if (!Valid.pathString(zig_str, ctx, exception)) return null; + + JSC.C.JSValueProtect(ctx, arg.asObjectRef()); + arguments.eat(); + + if (zig_str.is16Bit()) { + var printed = std.mem.span(std.fmt.allocPrintZ(arguments.arena.allocator(), "{}", .{zig_str}) catch unreachable); + return PathLike{ .string = PathString.init(printed.ptr[0 .. printed.len + 1]) }; + } + + return PathLike{ .string = PathString.init(zig_str.slice()) }; + }, + else => return null, + } + } +}; + +pub const Valid = struct { + pub fn fileDescriptor(fd: FileDescriptor, ctx: JSC.C.JSContextRef, exception: JSC.C.ExceptionRef) bool { + if (fd < 0) { + JSC.throwInvalidArguments("Invalid file descriptor, must not be negative number", .{}, ctx, exception); + return false; + } + + return true; + } + + pub fn pathString(zig_str: JSC.ZigString, ctx: JSC.C.JSContextRef, exception: JSC.C.ExceptionRef) bool { + switch (zig_str.len) { + 0 => { + JSC.throwInvalidArguments("Invalid path string: can't be empty", .{}, ctx, exception); + return false; + }, + 1...std.fs.MAX_PATH_BYTES => return true, + else => { + // TODO: should this be an EINVAL? + JSC.throwInvalidArguments( + comptime std.fmt.comptimePrint("Invalid path string: path is too long (max: {d})", .{std.fs.MAX_PATH_BYTES}), + .{}, + ctx, + exception, + ); + return false; + }, + } + + unreachable; + } + + pub fn pathBuffer(buffer: Buffer, ctx: JSC.C.JSContextRef, exception: JSC.C.ExceptionRef) bool { + const slice = buffer.slice(); + switch (slice.len) { + 0 => { + JSC.throwInvalidArguments("Invalid path buffer: can't be empty", .{}, ctx, exception); + return false; + }, + + else => { + + // TODO: should this be an EINVAL? + JSC.throwInvalidArguments( + comptime std.fmt.comptimePrint("Invalid path buffer: path is too long (max: {d})", .{std.fs.MAX_PATH_BYTES}), + .{}, + ctx, + exception, + ); + return false; + }, + 1...std.fs.MAX_PATH_BYTES => return true, + } + + unreachable; + } +}; + +pub const ArgumentsSlice = struct { + remaining: []const JSC.JSValue, + arena: std.heap.ArenaAllocator = std.heap.ArenaAllocator.init(_global.default_allocator), + all: []const JSC.JSValue, + + pub fn init(arguments: []const JSC.JSValue) ArgumentsSlice { + return ArgumentsSlice{ + .remaining = arguments, + .all = arguments, + }; + } + + pub inline fn len(this: *const ArgumentsSlice) u16 { + return @truncate(u16, this.remaining.len); + } + pub fn eat(this: *ArgumentsSlice) void { + if (this.remaining.len == 0) { + return; + } + + this.remaining = this.remaining[1..]; + } + + pub fn next(this: *ArgumentsSlice) ?JSC.JSValue { + if (this.remaining.len == 0) { + return null; + } + + return this.remaining[0]; + } +}; + +pub fn fileDescriptorFromJS(ctx: JSC.C.JSContextRef, value: JSC.JSValue, exception: JSC.C.ExceptionRef) ?FileDescriptor { + if (!value.isNumber() or value.isBigInt()) return null; + const fd = value.toInt32(); + if (!Valid.fileDescriptor(fd, ctx, exception)) { + return null; + } + + return @truncate(FileDescriptor, fd); +} + +var _get_time_prop_string: ?JSC.C.JSStringRef = null; +pub fn timeLikeFromJS(ctx: JSC.C.JSContextRef, value_: JSC.JSValue, exception: JSC.C.ExceptionRef) ?TimeLike { + var value = value_; + if (JSC.C.JSValueIsDate(ctx, value.asObjectRef())) { + // TODO: make this faster + var get_time_prop = _get_time_prop_string orelse brk: { + var str = JSC.C.JSStringCreateStatic("getTime", "getTime".len); + _get_time_prop_string = str; + break :brk str; + }; + + var getTimeFunction = JSC.C.JSObjectGetProperty(ctx, value.asObjectRef(), get_time_prop, exception); + if (exception.* != null) return null; + value = JSC.JSValue.fromRef(JSC.C.JSObjectCallAsFunction(ctx, getTimeFunction, value.asObjectRef(), 0, null, exception) orelse return null); + if (exception.* != null) return null; + } + + const seconds = value.asNumber(); + if (!std.math.isFinite(seconds)) { + return null; + } + + return @floatToInt(TimeLike, @maximum(@floor(seconds), std.math.minInt(TimeLike))); +} + +pub fn modeFromJS(ctx: JSC.C.JSContextRef, value: JSC.JSValue, exception: JSC.C.ExceptionRef) ?Mode { + const mode_int = if (value.isNumber()) + @truncate(Mode, value.to(Mode)) + else brk: { + if (value.isUndefinedOrNull()) return null; + + // An easier method of constructing the mode is to use a sequence of + // three octal digits (e.g. 765). The left-most digit (7 in the example), + // specifies the permissions for the file owner. The middle digit (6 in + // 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.init(""); + value.toZigString(&zig_str, ctx.ptr()); + var slice = zig_str.slice(); + if (strings.hasPrefix(slice, "0o")) { + slice = slice[2..]; + } + + break :brk std.fmt.parseInt(Mode, slice, 8) catch { + JSC.throwInvalidArguments("Invalid mode string: must be an octal number", .{}, ctx, exception); + return null; + }; + }; + + if (mode_int < 0 or mode_int > 0o777) { + JSC.throwInvalidArguments("Invalid mode: must be an octal number", .{}, ctx, exception); + return null; + } + + return mode_int; +} + +pub const PathOrFileDescriptor = union(Tag) { + path: PathLike, + fd: FileDescriptor, + + pub const Tag = enum { fd, path }; + + pub fn copyToStream(this: PathOrFileDescriptor, flags: FileSystemFlags, auto_close: bool, mode: Mode, allocator: std.mem.Allocator, stream: *Stream) !void { + switch (this) { + .fd => |fd| { + stream.content = Stream.Content{ + .file = .{ + .fd = fd, + .flags = flags, + .mode = mode, + }, + }; + stream.content_type = .file; + }, + .path => |path| { + stream.content = Stream.Content{ + .file_path = .{ + .path = PathString.init(std.mem.span(try allocator.dupeZ(u8, path.slice()))), + .auto_close = auto_close, + .file = .{ + .fd = std.math.maxInt(FileDescriptor), + .flags = flags, + .mode = mode, + }, + .opened = false, + }, + }; + stream.content_type = .file_path; + }, + } + } + + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?PathOrFileDescriptor { + const first = arguments.next() orelse return null; + + if (fileDescriptorFromJS(ctx, first, exception)) |fd| { + arguments.eat(); + return PathOrFileDescriptor{ .fd = fd }; + } + + if (exception.* != null) return null; + + return PathOrFileDescriptor{ .path = PathLike.fromJS(ctx, arguments, exception) orelse return null }; + } + + pub fn toJS(this: PathOrFileDescriptor, ctx: JSC.C.JSContextRef, exception: JSC.C.ExceptionRef) JSC.C.JSValueRef { + return switch (this) { + .path => this.path.toJS(ctx, exception), + .fd => JSC.JSValue.jsNumberFromInt32(@intCast(i32, this.fd)).asRef(), + }; + } +}; + +pub const FileSystemFlags = enum(Mode) { + /// Open file for appending. The file is created if it does not exist. + @"a" = std.os.O.APPEND, + /// Like 'a' but fails if the path exists. + // @"ax" = std.os.O.APPEND | std.os.O.EXCL, + /// Open file for reading and appending. The file is created if it does not exist. + // @"a+" = std.os.O.APPEND | std.os.O.RDWR, + /// Like 'a+' but fails if the path exists. + // @"ax+" = std.os.O.APPEND | std.os.O.RDWR | std.os.O.EXCL, + /// Open file for appending in synchronous mode. The file is created if it does not exist. + // @"as" = std.os.O.APPEND, + /// Open file for reading and appending in synchronous mode. The file is created if it does not exist. + // @"as+" = std.os.O.APPEND | std.os.O.RDWR, + /// Open file for reading. An exception occurs if the file does not exist. + @"r" = std.os.O.RDONLY, + /// Open file for reading and writing. An exception occurs if the file does not exist. + // @"r+" = std.os.O.RDWR, + /// Open file for reading and writing in synchronous mode. Instructs the operating system to bypass the local file system cache. + /// This is primarily useful for opening files on NFS mounts as it allows skipping the potentially stale local cache. It has a very real impact on I/O performance so using this flag is not recommended unless it is needed. + /// This doesn't turn fs.open() or fsPromises.open() into a synchronous blocking call. If synchronous operation is desired, something like fs.openSync() should be used. + // @"rs+" = std.os.O.RDWR, + /// Open file for writing. The file is created (if it does not exist) or truncated (if it exists). + @"w" = std.os.O.WRONLY | std.os.O.CREAT, + /// Like 'w' but fails if the path exists. + // @"wx" = std.os.O.WRONLY | std.os.O.TRUNC, + // /// Open file for reading and writing. The file is created (if it does not exist) or truncated (if it exists). + // @"w+" = std.os.O.RDWR | std.os.O.CREAT, + // /// Like 'w+' but fails if the path exists. + // @"wx+" = std.os.O.RDWR | std.os.O.EXCL, + + _, + + const O_RDONLY: Mode = std.os.O.RDONLY; + const O_RDWR: Mode = std.os.O.RDWR; + const O_APPEND: Mode = std.os.O.APPEND; + const O_CREAT: Mode = std.os.O.CREAT; + const O_WRONLY: Mode = std.os.O.WRONLY; + const O_EXCL: Mode = std.os.O.EXCL; + const O_SYNC: Mode = 0; + const O_TRUNC: Mode = std.os.O.TRUNC; + + pub fn fromJS(ctx: JSC.C.JSContextRef, val: JSC.JSValue, exception: JSC.C.ExceptionRef) ?FileSystemFlags { + if (val.isUndefinedOrNull()) { + return @intToEnum(FileSystemFlags, O_RDONLY); + } + + if (val.isNumber()) { + const number = val.toInt32(); + if (!(number > 0o000 and number < 0o777)) { + JSC.throwInvalidArguments( + "Invalid integer mode: must be a number between 0o000 and 0o777", + .{}, + ctx, + exception, + ); + return null; + } + return @intToEnum(FileSystemFlags, number); + } + + const jsType = val.jsType(); + if (jsType.isStringLike()) { + var zig_str = JSC.ZigString.init(""); + val.toZigString(&zig_str, ctx.ptr()); + + var buf: [4]u8 = .{ 0, 0, 0, 0 }; + @memcpy(&buf, zig_str.ptr, @minimum(buf.len, zig_str.len)); + const Matcher = strings.ExactSizeMatcher(4); + + // https://github.com/nodejs/node/blob/8c3637cd35cca352794e2c128f3bc5e6b6c41380/lib/internal/fs/utils.js#L565 + const flags = switch (Matcher.match(buf[0..4])) { + Matcher.case("r") => O_RDONLY, + Matcher.case("rs"), Matcher.case("sr") => O_RDONLY | O_SYNC, + Matcher.case("r+") => O_RDWR, + Matcher.case("rs+"), Matcher.case("sr+") => O_RDWR | O_SYNC, + + Matcher.case("w") => O_TRUNC | O_CREAT | O_WRONLY, + Matcher.case("wx"), Matcher.case("xw") => O_TRUNC | O_CREAT | O_WRONLY | O_EXCL, + + Matcher.case("w+") => O_TRUNC | O_CREAT | O_RDWR, + Matcher.case("wx+"), Matcher.case("xw+") => O_TRUNC | O_CREAT | O_RDWR | O_EXCL, + + Matcher.case("a") => O_APPEND | O_CREAT | O_WRONLY, + Matcher.case("ax"), Matcher.case("xa") => O_APPEND | O_CREAT | O_WRONLY | O_EXCL, + Matcher.case("as"), Matcher.case("sa") => O_APPEND | O_CREAT | O_WRONLY | O_SYNC, + + Matcher.case("a+") => O_APPEND | O_CREAT | O_RDWR, + Matcher.case("ax+"), Matcher.case("xa+") => O_APPEND | O_CREAT | O_RDWR | O_EXCL, + Matcher.case("as+"), Matcher.case("sa+") => O_APPEND | O_CREAT | O_RDWR | O_SYNC, + + Matcher.case("") => { + JSC.throwInvalidArguments( + "Invalid flag: string can't be empty", + .{}, + ctx, + exception, + ); + return null; + }, + else => { + JSC.throwInvalidArguments( + "Invalid flag. Learn more at https://nodejs.org/api/fs.html#fs_file_system_flags", + .{}, + ctx, + exception, + ); + return null; + }, + }; + + return @intToEnum(FileSystemFlags, flags); + } + + return null; + } +}; + +/// Milliseconds precision +pub const Date = enum(u64) { + _, + + pub fn toJS(this: Date, ctx: JSC.C.JSContextRef, exception: JSC.C.ExceptionRef) JSC.C.JSValueRef { + const seconds = @floatCast(f64, @intToFloat(f128, @enumToInt(this)) * 1000.0); + const unix_timestamp = JSC.C.JSValueMakeNumber(ctx, seconds); + const array: [1]JSC.C.JSValueRef = .{unix_timestamp}; + const obj = JSC.C.JSObjectMakeDate(ctx, 1, &array, exception); + return obj; + } +}; + +fn StatsLike(comptime name: string, comptime T: type) type { + return struct { + const This = @This(); + + pub const Class = JSC.NewClass( + This, + .{ .name = name }, + .{}, + .{ + .dev = .{ + .get = JSC.To.JS.Getter(This, .dev), + .name = "dev", + }, + .ino = .{ + .get = JSC.To.JS.Getter(This, .ino), + .name = "ino", + }, + .mode = .{ + .get = JSC.To.JS.Getter(This, .mode), + .name = "mode", + }, + .nlink = .{ + .get = JSC.To.JS.Getter(This, .nlink), + .name = "nlink", + }, + .uid = .{ + .get = JSC.To.JS.Getter(This, .uid), + .name = "uid", + }, + .gid = .{ + .get = JSC.To.JS.Getter(This, .gid), + .name = "gid", + }, + .rdev = .{ + .get = JSC.To.JS.Getter(This, .rdev), + .name = "rdev", + }, + .size = .{ + .get = JSC.To.JS.Getter(This, .size), + .name = "size", + }, + .blksize = .{ + .get = JSC.To.JS.Getter(This, .blksize), + .name = "blksize", + }, + .blocks = .{ + .get = JSC.To.JS.Getter(This, .blocks), + .name = "blocks", + }, + .atime = .{ + .get = JSC.To.JS.Getter(This, .atime), + .name = "atime", + }, + .mtime = .{ + .get = JSC.To.JS.Getter(This, .mtime), + .name = "mtime", + }, + .ctime = .{ + .get = JSC.To.JS.Getter(This, .ctime), + .name = "ctime", + }, + .birthtime = .{ + .get = JSC.To.JS.Getter(This, .birthtime), + .name = "birthtime", + }, + .atime_ms = .{ + .get = JSC.To.JS.Getter(This, .atime_ms), + .name = "atimeMs", + }, + .mtime_ms = .{ + .get = JSC.To.JS.Getter(This, .mtime_ms), + .name = "mtimeMs", + }, + .ctime_ms = .{ + .get = JSC.To.JS.Getter(This, .ctime_ms), + .name = "ctimeMs", + }, + .birthtime_ms = .{ + .get = JSC.To.JS.Getter(This, .birthtime_ms), + .name = "birthtimeMs", + }, + }, + ); + + dev: T, + ino: T, + mode: T, + nlink: T, + uid: T, + gid: T, + rdev: T, + size: T, + blksize: T, + blocks: T, + atime_ms: T, + mtime_ms: T, + ctime_ms: T, + birthtime_ms: T, + atime: Date, + mtime: Date, + ctime: Date, + birthtime: Date, + + pub fn init(stat_: os.Stat) @This() { + const atime = stat_.atime(); + const mtime = stat_.mtime(); + const ctime = stat_.ctime(); + return @This(){ + .dev = @truncate(T, @intCast(i64, stat_.dev)), + .ino = @truncate(T, @intCast(i64, stat_.ino)), + .mode = @truncate(T, @intCast(i64, stat_.mode)), + .nlink = @truncate(T, @intCast(i64, stat_.nlink)), + .uid = @truncate(T, @intCast(i64, stat_.uid)), + .gid = @truncate(T, @intCast(i64, stat_.gid)), + .rdev = @truncate(T, @intCast(i64, stat_.rdev)), + .size = @truncate(T, @intCast(i64, stat_.size)), + .blksize = @truncate(T, @intCast(i64, stat_.blksize)), + .blocks = @truncate(T, @intCast(i64, stat_.blocks)), + .atime_ms = @truncate(T, @intCast(i64, if (atime.tv_nsec > 0) (@intCast(usize, atime.tv_nsec) / std.time.ns_per_ms) else 0)), + .mtime_ms = @truncate(T, @intCast(i64, if (mtime.tv_nsec > 0) (@intCast(usize, mtime.tv_nsec) / std.time.ns_per_ms) else 0)), + .ctime_ms = @truncate(T, @intCast(i64, if (ctime.tv_nsec > 0) (@intCast(usize, ctime.tv_nsec) / std.time.ns_per_ms) else 0)), + .atime = @intToEnum(Date, @intCast(u64, @maximum(atime.tv_sec, 0))), + .mtime = @intToEnum(Date, @intCast(u64, @maximum(mtime.tv_sec, 0))), + .ctime = @intToEnum(Date, @intCast(u64, @maximum(ctime.tv_sec, 0))), + + // Linux doesn't include this info in stat + // maybe it does in statx, but do you really need birthtime? If you do please file an issue. + .birthtime_ms = if (Environment.isLinux) + 0 + else + @truncate(T, @intCast(i64, if (stat_.birthtimensec > 0) (@intCast(usize, stat_.birthtimensec) / std.time.ns_per_ms) else 0)), + + .birthtime = if (Environment.isLinux) + @intToEnum(Date, 0) + else + @intToEnum(Date, @intCast(u64, @maximum(stat_.birthtimesec, 0))), + }; + } + + pub fn toJS(this: Stats, ctx: JSC.C.JSContextRef, _: JSC.C.ExceptionRef) JSC.C.JSValueRef { + var _this = _global.default_allocator.create(Stats) catch unreachable; + _this.* = this; + return Class.make(ctx, _this); + } + + pub fn finalize(this: *Stats) void { + _global.default_allocator.destroy(this); + } + }; +} + +pub const Stats = StatsLike("Stats", i32); +pub const BigIntStats = StatsLike("BigIntStats", i64); + +/// A class representing a directory stream. +/// +/// Created by {@link opendir}, {@link opendirSync}, or `fsPromises.opendir()`. +/// +/// ```js +/// import { opendir } from 'fs/promises'; +/// +/// try { +/// const dir = await opendir('./'); +/// for await (const dirent of dir) +/// console.log(dirent.name); +/// } catch (err) { +/// console.error(err); +/// } +/// ``` +/// +/// When using the async iterator, the `fs.Dir` object will be automatically +/// closed after the iterator exits. +/// @since v12.12.0 +pub const DirEnt = struct { + name: PathString, + // not publicly exposed + kind: Kind, + + pub const Kind = std.fs.File.Kind; + + pub fn isBlockDevice( + this: *DirEnt, + ctx: JSC.C.JSContextRef, + _: JSC.C.JSObjectRef, + _: JSC.C.JSObjectRef, + _: []const JSC.C.JSValueRef, + _: JSC.C.ExceptionRef, + ) JSC.C.JSValueRef { + return JSC.C.JSValueMakeBoolean(ctx, this.kind == std.fs.File.Kind.BlockDevice); + } + pub fn isCharacterDevice( + this: *DirEnt, + ctx: JSC.C.JSContextRef, + _: JSC.C.JSObjectRef, + _: JSC.C.JSObjectRef, + _: []const JSC.C.JSValueRef, + _: JSC.C.ExceptionRef, + ) JSC.C.JSValueRef { + return JSC.C.JSValueMakeBoolean(ctx, this.kind == std.fs.File.Kind.CharacterDevice); + } + pub fn isDirectory( + this: *DirEnt, + ctx: JSC.C.JSContextRef, + _: JSC.C.JSObjectRef, + _: JSC.C.JSObjectRef, + _: []const JSC.C.JSValueRef, + _: JSC.C.ExceptionRef, + ) JSC.C.JSValueRef { + return JSC.C.JSValueMakeBoolean(ctx, this.kind == std.fs.File.Kind.Directory); + } + pub fn isFIFO( + this: *DirEnt, + ctx: JSC.C.JSContextRef, + _: JSC.C.JSObjectRef, + _: JSC.C.JSObjectRef, + _: []const JSC.C.JSValueRef, + _: JSC.C.ExceptionRef, + ) JSC.C.JSValueRef { + return JSC.C.JSValueMakeBoolean(ctx, this.kind == std.fs.File.Kind.NamedPipe or this.kind == std.fs.File.Kind.EventPort); + } + pub fn isFile( + this: *DirEnt, + ctx: JSC.C.JSContextRef, + _: JSC.C.JSObjectRef, + _: JSC.C.JSObjectRef, + _: []const JSC.C.JSValueRef, + _: JSC.C.ExceptionRef, + ) JSC.C.JSValueRef { + return JSC.C.JSValueMakeBoolean(ctx, this.kind == std.fs.File.Kind.File); + } + pub fn isSocket( + this: *DirEnt, + ctx: JSC.C.JSContextRef, + _: JSC.C.JSObjectRef, + _: JSC.C.JSObjectRef, + _: []const JSC.C.JSValueRef, + _: JSC.C.ExceptionRef, + ) JSC.C.JSValueRef { + return JSC.C.JSValueMakeBoolean(ctx, this.kind == std.fs.File.Kind.UnixDomainSocket); + } + pub fn isSymbolicLink( + this: *DirEnt, + ctx: JSC.C.JSContextRef, + _: JSC.C.JSObjectRef, + _: JSC.C.JSObjectRef, + _: []const JSC.C.JSValueRef, + _: JSC.C.ExceptionRef, + ) JSC.C.JSValueRef { + return JSC.C.JSValueMakeBoolean(ctx, this.kind == std.fs.File.Kind.SymLink); + } + + pub const Class = JSC.NewClass(DirEnt, .{ .name = "DirEnt" }, .{ + .isBlockDevice = .{ + .name = "isBlockDevice", + .rfn = isBlockDevice, + }, + .isCharacterDevice = .{ + .name = "isCharacterDevice", + .rfn = isCharacterDevice, + }, + .isDirectory = .{ + .name = "isDirectory", + .rfn = isDirectory, + }, + .isFIFO = .{ + .name = "isFIFO", + .rfn = isFIFO, + }, + .isFile = .{ + .name = "isFile", + .rfn = isFile, + }, + .isSocket = .{ + .name = "isSocket", + .rfn = isSocket, + }, + .isSymbolicLink = .{ + .name = "isSymbolicLink", + .rfn = isSymbolicLink, + }, + }, .{ + .name = .{ + .get = JSC.To.JS.Getter(DirEnt, .name), + .name = "name", + }, + }); + + pub fn finalize(this: *DirEnt) void { + _global.default_allocator.free(this.name.slice()); + _global.default_allocator.destroy(this); + } +}; + +pub const Emitter = struct { + pub const Listener = struct { + once: bool = false, + callback: JSC.JSValue, + + pub const List = struct { + pub const ArrayList = std.MultiArrayList(Listener); + list: ArrayList = ArrayList{}, + once_count: u32 = 0, + + pub fn append(this: *List, allocator: std.mem.Allocator, ctx: JSC.C.JSContextRef, listener: Listener) !void { + JSC.C.JSValueProtect(ctx, listener.callback.asObjectRef()); + try this.list.append(allocator, listener); + this.once_count +|= @as(u32, @boolToInt(listener.once)); + } + + pub fn prepend(this: *List, allocator: std.mem.Allocator, ctx: JSC.C.JSContextRef, listener: Listener) !void { + JSC.C.JSValueProtect(ctx, listener.callback.asObjectRef()); + try this.list.ensureUnusedCapacity(allocator, 1); + this.list.insertAssumeCapacity(0, listener); + this.once_count +|= @as(u32, @boolToInt(listener.once)); + } + + // removeListener() will remove, at most, one instance of a listener from the + // listener array. If any single listener has been added multiple times to the + // listener array for the specified eventName, then removeListener() must be + // called multiple times to remove each instance. + pub fn remove(this: *List, ctx: JSC.C.JSContextRef, callback: JSC.JSValue) bool { + const callbacks = this.list.items(.callback); + + for (callbacks) |item, i| { + if (callback.eqlValue(item)) { + JSC.C.JSValueUnprotect(ctx, callback.asObjectRef()); + this.once_count -|= @as(u32, @boolToInt(this.list.items(.once)[i])); + this.list.orderedRemove(i); + return true; + } + } + + return false; + } + + pub fn emit(this: *List, globalThis: *JSC.JSGlobalObject, value: JSC.JSValue) void { + var i: usize = 0; + outer: while (true) { + var slice = this.list.slice(); + var callbacks = slice.items(.callback); + var once = slice.items(.once); + while (i < callbacks.len) : (i += 1) { + const callback = callbacks[i]; + + globalThis.enqueueMicrotask1( + callback, + value, + ); + + if (once[i]) { + this.once_count -= 1; + JSC.C.JSValueUnprotect(globalThis.ref(), callback.asObjectRef()); + this.list.orderedRemove(i); + slice = this.list.slice(); + callbacks = slice.items(.callback); + once = slice.items(.once); + continue :outer; + } + } + + return; + } + } + }; + }; + + pub fn New(comptime EventType: type) type { + return struct { + const EventEmitter = @This(); + pub const Map = std.enums.EnumArray(EventType, Listener.List); + listeners: Map = Map.initFill(Listener.List{}), + + pub fn addListener(this: *EventEmitter, ctx: JSC.C.JSContextRef, event: EventType, listener: Emitter.Listener) !void { + try this.listeners.getPtr(event).append(_global.default_allocator, ctx, listener); + } + + pub fn prependListener(this: *EventEmitter, ctx: JSC.C.JSContextRef, event: EventType, listener: Emitter.Listener) !void { + try this.listeners.getPtr(event).prepend(_global.default_allocator, ctx, listener); + } + + pub fn emit(this: *EventEmitter, event: EventType, globalThis: *JSC.JSGlobalObject, value: JSC.JSValue) void { + this.listeners.getPtr(event).emit(globalThis, value); + } + + pub fn removeListener(this: *EventEmitter, ctx: JSC.C.JSContextRef, event: EventType, callback: JSC.JSValue) bool { + return this.listeners.getPtr(event).remove(ctx, callback); + } + }; + } +}; + +// pub fn Untag(comptime Union: type) type { +// const info: std.builtin.TypeInfo.Union = @typeInfo(Union); +// const tag = info.tag_type orelse @compileError("Must be tagged"); +// return struct { +// pub const Tag = tag; +// pub const Union = +// }; +// } + +pub const Stream = struct { + sink_type: Sink.Type, + sink: Sink, + content: Content, + content_type: Content.Type, + allocator: std.mem.Allocator, + + pub fn open(this: *Stream) ?JSC.Node.Syscall.Error { + switch (Syscall.open(this.content.file_path.path.sliceAssumeZ(), @enumToInt(this.content.file_path.file.flags))) { + .err => |err| { + return err.withPath(this.content.file_path.path.slice()); + }, + .result => |fd| { + this.content.file_path.file.fd = fd; + this.content.file_path.opened = true; + this.emit(.open); + return null; + }, + } + } + + pub fn getFd(this: *Stream) FileDescriptor { + return switch (this.content_type) { + .file => this.content.file.fd, + .file_path => if (comptime Environment.allow_assert) brk: { + std.debug.assert(this.content.file_path.opened); + break :brk this.content.file_path.file.fd; + } else this.content.file_path.file.fd, + else => unreachable, + }; + } + + pub fn close(this: *Stream) ?JSC.Node.Syscall.Error { + const fd = this.getFd(); + + // Don't ever close stdin, stdout, or stderr + // we are assuming that these are always 0 1 2, which is not strictly true in some cases + if (fd <= 2) { + return null; + } + + if (Syscall.close(fd)) |err| { + return err; + } + + switch (this.content_type) { + .file_path => { + this.content.file_path.opened = false; + this.content.file_path.file.fd = std.math.maxInt(FileDescriptor); + }, + .file => { + this.content.file.fd = std.math.maxInt(FileDescriptor); + }, + else => {}, + } + + this.emit(.Close); + } + + const CommonEvent = enum { Error, Open, Close }; + pub fn emit(this: *Stream, comptime event: CommonEvent) void { + switch (this.sink_type) { + .readable => { + switch (comptime event) { + .Open => this.sink.readable.emit(.Open), + .Close => this.sink.readable.emit(.Close), + else => unreachable, + } + }, + .writable => { + switch (comptime event) { + .Open => this.sink.writable.emit(.Open), + .Close => this.sink.writable.emit(.Close), + else => unreachable, + } + }, + } + } + + // This allocates a new stream object + pub fn toJS(this: *Stream, ctx: JSC.C.JSContextRef, _: JSC.C.ExceptionRef) JSC.C.JSValueRef { + switch (this.sink_type) { + .readable => { + var readable = &this.sink.readable.state; + return readable.create( + ctx.ptr(), + ).asObjectRef(); + }, + .writable => { + var writable = &this.sink.writable.state; + return writable.create( + ctx.ptr(), + ).asObjectRef(); + }, + } + } + + pub fn deinit(this: *Stream) void { + this.allocator.destroy(this); + } + + pub const Sink = union { + readable: Readable, + writable: Writable, + + pub const Type = enum(u8) { + readable, + writable, + }; + }; + + pub const Consumed = u52; + + const Response = struct { + bytes: [8]u8 = std.mem.zeroes([8]u8), + }; + + const Error = union(Type) { + Syscall: Syscall.Error, + JavaScript: JSC.JSValue, + Internal: anyerror, + + pub const Type = enum { + Syscall, + JavaScript, + Internal, + }; + }; + + pub const Content = union { + file: File, + file_path: FilePath, + socket: Socket, + buffer: *Buffer, + stream: *Stream, + javascript: JSC.JSValue, + + pub fn getFile(this: *Content, content_type: Content.Type) *File { + return switch (content_type) { + .file => &this.file, + .file_path => &this.file_path.file, + else => unreachable, + }; + } + + pub const File = struct { + fd: FileDescriptor, + flags: FileSystemFlags, + mode: Mode, + size: Consumed = std.math.maxInt(Consumed), + + // pub fn read(this: *File, comptime chunk_type: Content.Type, chunk: Source.Type.of(chunk_type)) Response {} + + pub inline fn setPermissions(this: File) meta.ReturnOf(Syscall.fchmod) { + return Syscall.fchmod(this.fd, this.mode); + } + }; + + pub const FilePath = struct { + path: PathString, + auto_close: bool = false, + file: File = File{ .fd = std.math.maxInt(FileDescriptor), .mode = 0o666, .flags = FileSystemFlags.@"r" }, + opened: bool = false, + + // pub fn read(this: *File, comptime chunk_type: Content.Type, chunk: Source.Type.of(chunk_type)) Response {} + }; + + pub const Socket = struct { + fd: FileDescriptor, + flags: FileSystemFlags, + + // pub fn write(this: *File, comptime chunk_type: Source.Type, chunk: Source.Type.of(chunk_type)) Response {} + // pub fn read(this: *File, comptime chunk_type: Source.Type, chunk: Source.Type.of(chunk_type)) Response {} + }; + + pub const Type = enum(u8) { + file, + file_path, + socket, + buffer, + stream, + javascript, + }; + }; +}; + +pub const Writable = struct { + state: State = State{}, + emitter: EventEmitter = EventEmitter{}, + + connection: ?*Stream = null, + globalObject: ?*JSC.JSGlobalObject = null, + + // workaround https://github.com/ziglang/zig/issues/6611 + stream: *Stream = undefined, + pipeline: Pipeline = Pipeline{}, + started: bool = false, + + pub const Chunk = struct { + data: StringOrBuffer, + encoding: Encoding = Encoding.utf8, + }; + + pub const Pipe = struct { + source: *Stream, + destination: *Stream, + chunk: ?*Chunk = null, + // Might be the end of the stream + // or it might just be another stream + next: ?*Pipe = null, + + pub fn start(this: *Pipe, pipeline: *Pipeline, chunk: ?*Chunk) void { + this.run(pipeline, chunk, null); + } + + var disable_clonefile = false; + + fn runCloneFileWithFallback(pipeline: *Pipeline, source: *Stream.Content, destination: *Stream.Content) void { + switch (Syscall.clonefile(source.path.sliceAssumeZ(), destination.path.sliceAssumeZ())) { + .result => return, + .err => |err| { + switch (err.getErrno()) { + // these are retryable + .ENOTSUP, .EXDEV, .EXIST, .EIO, .ENOTDIR => |call| { + if (call == .ENOTSUP) { + disable_clonefile = true; + } + + return runCopyfile( + false, + pipeline, + source, + .file_path, + destination, + .file_path, + ); + }, + else => { + pipeline.err = err; + return; + }, + } + }, + } + } + + fn runCopyfile( + must_open_files: bool, + pipeline: *Pipeline, + source: *Stream.Content, + source_type: Stream.Content.Type, + destination: *Stream.Content, + destination_type: Stream.Content.Type, + is_end: bool, + ) void { + do_the_work: { + // fallback-only + if (destination_type == .file_path and source_type == .file_path and !destination.file_path.opened and !must_open_files) { + switch (Syscall.copyfile(source.path.sliceAssumeZ(), destination.path.sliceAssumeZ(), 0)) { + .err => |err| { + pipeline.err = err; + + return; + }, + .result => break :do_the_work, + } + } + + defer { + if (source_type == .file_path and source.file_path.auto_close and source.file_path.opened) { + if (source.stream.close()) |err| { + if (pipeline.err == null) { + pipeline.err = err; + } + } + } + + if (is_end and destination_type == .file_path and destination.file_path.auto_close and destination.file_path.opened) { + if (destination.stream.close()) |err| { + if (pipeline.err == null) { + pipeline.err = err; + } + } + } + } + + if (source_type == .file_path and !source.file_path.opened) { + if (source.stream.open()) |err| { + pipeline.err = err; + return; + } + } + + const source_fd = if (source_type == .file_path) + source.file_path.file.fd + else + source.file.fd; + + if (destination == .file_path and !destination.file_path.opened) { + if (destination.stream.open()) |err| { + pipeline.err = err; + return; + } + } + + const dest_fd = if (destination_type == .file_path) + destination.file_path.file.fd + else + destination.file.fd; + + switch (Syscall.fcopyfile(source_fd, dest_fd, 0)) { + .err => |err| { + pipeline.err = err; + return; + }, + .result => break :do_the_work, + } + } + + switch (destination.getFile(destination_type).setPermissions()) { + .err => |err| { + destination.stream.emitError(err); + pipeline.err = err; + return; + }, + .result => return, + } + } + + pub fn run(this: *Pipe, pipeline: *Pipeline) void { + var source = this.source; + var destination = this.destination; + const source_content_type = source.content_type; + const destination_content_type = destination.content_type; + + if (pipeline.err != null) return; + + switch (FastPath.get( + source_content_type, + destination_content_type, + pipeline.head == this, + pipeline.tail == this, + )) { + .clonefile => { + if (comptime !Environment.isMac) unreachable; + if (destination.content.file_path.opened) { + runCopyfile( + // Can we skip sending a .open event? + (!source.content.file_path.auto_close and !source.content.file_path.opened) or (!destination.content.file_path.auto_close and !destination.content.file_path.opened), + pipeline, + &source.content, + .file_path, + &destination.content, + .file_path, + this.next == null, + ); + } else { + runCloneFileWithFallback(pipeline, source.content.file_path, destination.content.file_path); + } + }, + .copyfile => { + if (comptime !Environment.isMac) unreachable; + runCopyfile( + // Can we skip sending a .open event? + (!source.content.file_path.auto_close and !source.content.file_path.opened) or (!destination.content.file_path.auto_close and !destination.content.file_path.opened), + pipeline, + &source.content, + source_content_type, + &destination.content, + destination_content_type, + this.next == null, + ); + }, + else => {}, + } + } + + pub const FastPath = enum { + none, + clonefile, + sendfile, + copyfile, + copy_file_range, + + pub fn get(source: Stream.Content.Type, destination: Stream.Content.Type, is_head: bool, is_tail: bool) FastPath { + _ = is_tail; + if (comptime Environment.isMac) { + if (is_head) { + if (source == .file_path and destination == .file_path and !disable_clonefile) + return .clonefile; + + if ((source == .file or source == .file_path) and (destination == .file or destination == .file_path)) { + return .copyfile; + } + } + } + + return FastPath.none; + } + }; + }; + + pub const Pipeline = struct { + head: ?*Pipe = null, + tail: ?*Pipe = null, + + // Preallocate a single pipe so that + preallocated_tail_pipe: Pipe = undefined, + + /// Does the data exit at any point to JavaScript? + closed_loop: bool = true, + + // If there is a pending error, this is the error + err: ?Syscall.Error = null, + + pub const StartTask = struct { + writable: *Writable, + pub fn run(this: *StartTask) void { + var writable = this.writable; + var head = writable.pipeline.head orelse return; + if (writable.started) { + return; + } + writable.started = true; + + head.start(&writable.pipeline, null); + } + }; + }; + + pub fn appendReadable(this: *Writable, readable: *Stream) void { + if (comptime Environment.allow_assert) { + std.debug.assert(readable.sink_type == .readable); + } + + if (this.pipeline.tail == null) { + this.pipeline.head = &this.pipeline.preallocated_tail_pipe; + this.pipeline.head.?.* = Pipe{ + .destination = this.stream, + .source = readable, + }; + this.pipeline.tail = this.pipeline.head; + return; + } + + var pipe = readable.allocator.create(Pipe) catch unreachable; + pipe.* = Pipe{ + .source = readable, + .destination = this.stream, + }; + this.pipeline.tail.?.next = pipe; + this.pipeline.tail = pipe; + } + + pub const EventEmitter = Emitter.New(Events); + + pub fn emit(this: *Writable, event: Events, value: JSC.JSValue) void { + if (this.shouldSkipEvent(event)) return; + + this.emitter.emit(event, this.globalObject.?, value); + } + + pub inline fn shouldEmitEvent(this: *const Writable, event: Events) bool { + return switch (event) { + .Close => this.state.emit_close and this.emitter.listeners.get(.Close).list.len > 0, + .Drain => this.emitter.listeners.get(.Drain).list.len > 0, + .Error => this.emitter.listeners.get(.Error).list.len > 0, + .Finish => this.emitter.listeners.get(.Finish).list.len > 0, + .Pipe => this.emitter.listeners.get(.Pipe).list.len > 0, + .Unpipe => this.emitter.listeners.get(.Unpipe).list.len > 0, + .Open => this.emitter.listeners.get(.Open).list.len > 0, + }; + } + + pub const State = extern struct { + highwater_mark: u32 = 256_000, + encoding: Encoding = Encoding.utf8, + start: i32 = 0, + destroyed: bool = false, + ended: bool = false, + corked: bool = false, + finished: bool = false, + emit_close: bool = true, + + pub fn deinit(state: *State) callconv(.C) void { + if (comptime is_bindgen) return; + + var stream = state.getStream(); + stream.deinit(); + } + + pub fn create(state: *State, globalObject: *JSC.JSGlobalObject) callconv(.C) JSC.JSValue { + return shim.cppFn("create", .{ state, globalObject }); + } + + // i know. + pub inline fn getStream(state: *State) *Stream { + return getWritable(state).stream; + } + + pub inline fn getWritable(state: *State) *Writable { + return @fieldParentPtr(Writable, "state", state); + } + + pub fn addEventListener(state: *State, global: *JSC.JSGlobalObject, event: Events, callback: JSC.JSValue, is_once: bool) callconv(.C) void { + if (comptime is_bindgen) return; + var writable = state.getWritable(); + writable.emitter.addListener(global.ref(), event, .{ + .once = is_once, + .callback = callback, + }) catch unreachable; + } + + pub fn removeEventListener(state: *State, global: *JSC.JSGlobalObject, event: Events, callback: JSC.JSValue) callconv(.C) bool { + if (comptime is_bindgen) return true; + var writable = state.getWritable(); + return writable.emitter.removeListener(global.ref(), event, callback); + } + + pub fn prependEventListener(state: *State, global: *JSC.JSGlobalObject, event: Events, callback: JSC.JSValue, is_once: bool) callconv(.C) void { + if (comptime is_bindgen) return; + var writable = state.getWritable(); + writable.emitter.prependListener(global.ref(), event, .{ + .once = is_once, + .callback = callback, + }) catch unreachable; + } + + pub fn write(state: *State, global: *JSC.JSGlobalObject, args_ptr: [*]const JSC.JSValue, len: u16) callconv(.C) JSC.JSValue { + if (comptime is_bindgen) return JSC.JSValue.jsUndefined(); + _ = state; + _ = global; + _ = args_ptr; + _ = len; + + return JSC.JSValue.jsUndefined(); + } + pub fn end(state: *State, global: *JSC.JSGlobalObject, args_ptr: [*]const JSC.JSValue, len: u16) callconv(.C) JSC.JSValue { + if (comptime is_bindgen) return JSC.JSValue.jsUndefined(); + _ = state; + _ = global; + _ = args_ptr; + _ = len; + + return JSC.JSValue.jsUndefined(); + } + pub fn close(state: *State, global: *JSC.JSGlobalObject, args_ptr: [*]const JSC.JSValue, len: u16) callconv(.C) JSC.JSValue { + if (comptime is_bindgen) return JSC.JSValue.jsUndefined(); + _ = state; + _ = global; + _ = args_ptr; + _ = len; + + return JSC.JSValue.jsUndefined(); + } + pub fn destroy(state: *State, global: *JSC.JSGlobalObject, args_ptr: [*]const JSC.JSValue, len: u16) callconv(.C) JSC.JSValue { + if (comptime is_bindgen) return JSC.JSValue.jsUndefined(); + _ = state; + _ = global; + _ = args_ptr; + _ = len; + + return JSC.JSValue.jsUndefined(); + } + pub fn cork(state: *State, global: *JSC.JSGlobalObject, args_ptr: [*]const JSC.JSValue, len: u16) callconv(.C) JSC.JSValue { + if (comptime is_bindgen) return JSC.JSValue.jsUndefined(); + _ = state; + _ = global; + _ = args_ptr; + _ = len; + + return JSC.JSValue.jsUndefined(); + } + pub fn uncork(state: *State, global: *JSC.JSGlobalObject, args_ptr: [*]const JSC.JSValue, len: u16) callconv(.C) JSC.JSValue { + if (comptime is_bindgen) return JSC.JSValue.jsUndefined(); + _ = state; + _ = global; + _ = args_ptr; + _ = len; + + return JSC.JSValue.jsUndefined(); + } + + pub const Flowing = enum(u8) { + pending, + yes, + paused, + }; + + pub const shim = Shimmer("Bun", "Writable", @This()); + pub const name = "Bun__Writable"; + pub const include = "BunStream.h"; + pub const namespace = shim.namespace; + + pub const Export = shim.exportFunctions(.{ + .@"deinit" = deinit, + .@"addEventListener" = addEventListener, + .@"removeEventListener" = removeEventListener, + .@"prependEventListener" = prependEventListener, + .@"write" = write, + .@"end" = end, + .@"close" = close, + .@"destroy" = destroy, + .@"cork" = cork, + .@"uncork" = uncork, + }); + + pub const Extern = [_][]const u8{"create"}; + + comptime { + if (!is_bindgen) { + @export(deinit, .{ .name = Export[0].symbol_name }); + @export(addEventListener, .{ .name = Export[1].symbol_name }); + @export(removeEventListener, .{ .name = Export[2].symbol_name }); + @export(prependEventListener, .{ .name = Export[3].symbol_name }); + @export(write, .{ .name = Export[4].symbol_name }); + @export(end, .{ .name = Export[5].symbol_name }); + @export(close, .{ .name = Export[6].symbol_name }); + @export(destroy, .{ .name = Export[7].symbol_name }); + @export(cork, .{ .name = Export[8].symbol_name }); + @export(uncork, .{ .name = Export[9].symbol_name }); + } + } + }; + + pub const Events = enum(u8) { + Close, + Drain, + Error, + Finish, + Pipe, + Unpipe, + Open, + + pub const name = "WritableEvent"; + }; +}; + +pub const Readable = struct { + state: State = State{}, + emitter: EventEmitter = EventEmitter{}, + stream: *Stream = undefined, + destination: ?*Writable = null, + globalObject: ?*JSC.JSGlobalObject = null, + + pub const EventEmitter = Emitter.New(Events); + + pub fn emit(this: *Readable, event: Events, comptime ValueType: type, value: JSC.JSValue) void { + _ = ValueType; + if (this.shouldEmitEvent(event)) return; + + this.emitter.emit(event, this.globalObject.?, value); + } + + pub fn shouldEmitEvent(this: *Readable, event: Events) bool { + return switch (event) { + .Close => this.state.emit_close and this.emitter.listeners.get(.Close).list.len > 0, + .Data => this.emitter.listeners.get(.Data).list.len > 0, + .End => this.state.emit_end and this.emitter.listeners.get(.End).list.len > 0, + .Error => this.emitter.listeners.get(.Error).list.len > 0, + .Pause => this.emitter.listeners.get(.Pause).list.len > 0, + .Readable => this.emitter.listeners.get(.Readable).list.len > 0, + .Resume => this.emitter.listeners.get(.Resume).list.len > 0, + .Open => this.emitter.listeners.get(.Open).list.len > 0, + }; + } + + pub const Events = enum(u8) { + Close, + Data, + End, + Error, + Pause, + Readable, + Resume, + Open, + + pub const name = "ReadableEvent"; + }; + + // This struct is exposed to JavaScript + pub const State = extern struct { + highwater_mark: u32 = 256_000, + encoding: Encoding = Encoding.utf8, + + start: i32 = 0, + end: i32 = std.math.maxInt(i32), + + readable: bool = false, + aborted: bool = false, + did_read: bool = false, + ended: bool = false, + flowing: Flowing = Flowing.pending, + + emit_close: bool = true, + emit_end: bool = true, + + // i know. + pub inline fn getStream(state: *State) *Stream { + return getReadable(state).stream; + } + + pub inline fn getReadable(state: *State) *Readable { + return @fieldParentPtr(Readable, "state", state); + } + + pub const Flowing = enum(u8) { + pending, + yes, + paused, + }; + + pub const shim = Shimmer("Bun", "Readable", @This()); + pub const name = "Bun__Readable"; + pub const include = "BunStream.h"; + pub const namespace = shim.namespace; + + pub fn create( + state: *State, + globalObject: *JSC.JSGlobalObject, + ) callconv(.C) JSC.JSValue { + return shim.cppFn("create", .{ state, globalObject }); + } + + pub fn deinit(state: *State) callconv(.C) void { + if (comptime is_bindgen) return; + var stream = state.getStream(); + stream.deinit(); + } + + pub fn addEventListener(state: *State, global: *JSC.JSGlobalObject, event: Events, callback: JSC.JSValue, is_once: bool) callconv(.C) void { + if (comptime is_bindgen) return; + var readable = state.getReadable(); + + readable.emitter.addListener(global.ref(), event, .{ + .once = is_once, + .callback = callback, + }) catch unreachable; + } + + pub fn removeEventListener(state: *State, global: *JSC.JSGlobalObject, event: Events, callback: JSC.JSValue) callconv(.C) bool { + if (comptime is_bindgen) return true; + var readable = state.getReadable(); + return readable.emitter.removeListener(global.ref(), event, callback); + } + + pub fn prependEventListener(state: *State, global: *JSC.JSGlobalObject, event: Events, callback: JSC.JSValue, is_once: bool) callconv(.C) void { + if (comptime is_bindgen) return; + var readable = state.getReadable(); + readable.emitter.prependListener(global.ref(), event, .{ + .once = is_once, + .callback = callback, + }) catch unreachable; + } + + pub fn pipe(state: *State, global: *JSC.JSGlobalObject, args_ptr: [*]const JSC.JSValue, len: u16) callconv(.C) JSC.JSValue { + if (comptime is_bindgen) return JSC.JSValue.jsUndefined(); + _ = state; + _ = global; + _ = args_ptr; + _ = len; + + if (len < 1) { + return JSC.toInvalidArguments("Writable is required", .{}, global.ref()); + } + const args: []const JSC.JSValue = args_ptr[0..len]; + var writable_state: *Writable.State = args[0].getWritableStreamState(global.vm()) orelse { + return JSC.toInvalidArguments("Expected Writable but didn't receive it", .{}, global.ref()); + }; + writable_state.getWritable().appendReadable(state.getStream()); + return JSC.JSValue.jsUndefined(); + } + + pub fn unpipe(state: *State, global: *JSC.JSGlobalObject, args_ptr: [*]const JSC.JSValue, len: u16) callconv(.C) JSC.JSValue { + if (comptime is_bindgen) return JSC.JSValue.jsUndefined(); + _ = state; + _ = global; + _ = args_ptr; + _ = len; + + return JSC.JSValue.jsUndefined(); + } + + pub fn unshift(state: *State, global: *JSC.JSGlobalObject, args_ptr: [*]const JSC.JSValue, len: u16) callconv(.C) JSC.JSValue { + if (comptime is_bindgen) return JSC.JSValue.jsUndefined(); + _ = state; + _ = global; + _ = args_ptr; + _ = len; + + return JSC.JSValue.jsUndefined(); + } + + pub fn read(state: *State, global: *JSC.JSGlobalObject, args_ptr: [*]const JSC.JSValue, len: u16) callconv(.C) JSC.JSValue { + if (comptime is_bindgen) return JSC.JSValue.jsUndefined(); + _ = state; + _ = global; + _ = args_ptr; + _ = len; + + return JSC.JSValue.jsUndefined(); + } + + pub fn pause(state: *State, global: *JSC.JSGlobalObject, args_ptr: [*]const JSC.JSValue, len: u16) callconv(.C) JSC.JSValue { + if (comptime is_bindgen) return JSC.JSValue.jsUndefined(); + _ = state; + _ = global; + _ = args_ptr; + _ = len; + + return JSC.JSValue.jsUndefined(); + } + + pub fn @"resume"(state: *State, global: *JSC.JSGlobalObject, args_ptr: [*]const JSC.JSValue, len: u16) callconv(.C) JSC.JSValue { + if (comptime is_bindgen) return JSC.JSValue.jsUndefined(); + _ = state; + _ = global; + _ = args_ptr; + _ = len; + + return JSC.JSValue.jsUndefined(); + } + + pub const Export = shim.exportFunctions(.{ + .@"deinit" = deinit, + .@"addEventListener" = addEventListener, + .@"removeEventListener" = removeEventListener, + .@"prependEventListener" = prependEventListener, + .@"pipe" = pipe, + .@"unpipe" = unpipe, + .@"unshift" = unshift, + .@"read" = read, + .@"pause" = pause, + .@"resume" = State.@"resume", + }); + + pub const Extern = [_][]const u8{"create"}; + + comptime { + if (!is_bindgen) { + @export(deinit, .{ + .name = Export[0].symbol_name, + }); + @export(addEventListener, .{ + .name = Export[1].symbol_name, + }); + @export(removeEventListener, .{ + .name = Export[2].symbol_name, + }); + @export(prependEventListener, .{ + .name = Export[3].symbol_name, + }); + @export( + pipe, + .{ .name = Export[4].symbol_name }, + ); + @export( + unpipe, + .{ .name = Export[5].symbol_name }, + ); + @export( + unshift, + .{ .name = Export[6].symbol_name }, + ); + @export( + read, + .{ .name = Export[7].symbol_name }, + ); + @export( + pause, + .{ .name = Export[8].symbol_name }, + ); + @export( + State.@"resume", + .{ .name = Export[9].symbol_name }, + ); + } + } + }; +}; + +pub const Process = struct { + pub fn getArgv(globalObject: *JSC.JSGlobalObject) callconv(.C) JSC.JSValue { + if (JSC.VirtualMachine.vm.argv.len == 0) + return JSC.JSValue.createStringArray(globalObject, null, 0, false); + + // Allocate up to 32 strings in stack + var stack_fallback_allocator = std.heap.stackFallback( + 32 * @sizeOf(JSC.ZigString), + heap_allocator, + ); + var allocator = stack_fallback_allocator.get(); + + // If it was launched with bun run or bun test, skip it + var skip: usize = 0; + if (JSC.VirtualMachine.vm.argv.len > 1 and (strings.eqlComptime(JSC.VirtualMachine.vm.argv[0], "run") or strings.eqlComptime(JSC.VirtualMachine.vm.argv[0], "test"))) { + skip += 1; + } + const count = JSC.VirtualMachine.vm.argv.len + 1; + var args = allocator.alloc( + JSC.ZigString, + count - skip, + ) catch unreachable; + defer allocator.free(args); + + // https://github.com/yargs/yargs/blob/adb0d11e02c613af3d9427b3028cc192703a3869/lib/utils/process-argv.ts#L1 + args[0] = JSC.ZigString.init(std.mem.span(std.os.argv[0])); + + if (JSC.VirtualMachine.vm.argv.len > skip) { + for (JSC.VirtualMachine.vm.argv[skip..]) |arg, i| { + args[i + 1] = JSC.ZigString.init(arg); + args[i + 1].detectEncoding(); + } + } + + return JSC.JSValue.createStringArray(globalObject, args.ptr, args.len, true); + } + + pub fn getCwd(globalObject: *JSC.JSGlobalObject) callconv(.C) JSC.JSValue { + var buffer: [std.fs.MAX_PATH_BYTES]u8 = undefined; + switch (Syscall.getcwd(&buffer)) { + .err => |err| { + return err.toJSC(globalObject); + }, + .result => |result| { + var zig_str = JSC.ZigString.init(result); + zig_str.detectEncoding(); + + const value = zig_str.toValueGC(globalObject); + + return value; + }, + } + } + pub fn setCwd(globalObject: *JSC.JSGlobalObject, to: *JSC.ZigString) callconv(.C) JSC.JSValue { + if (to.len == 0) { + return JSC.toInvalidArguments("path is required", .{}, globalObject.ref()); + } + + var buf: [std.fs.MAX_PATH_BYTES]u8 = undefined; + const slice = to.sliceZBuf(&buf) catch { + return JSC.toInvalidArguments("Invalid path", .{}, globalObject.ref()); + }; + const result = Syscall.chdir(slice); + + switch (result) { + .err => |err| { + return err.toJSC(globalObject); + }, + .result => { + // When we update the cwd from JS, we have to update the bundler's version as well + // However, this might be called many times in a row, so we use a pre-allocated buffer + // that way we don't have to worry about garbage collector + var trimmed = std.mem.trimRight(u8, buf[0..slice.len], std.fs.path.sep_str); + buf[trimmed.len] = std.fs.path.sep; + const with_trailing_slash = buf[0 .. trimmed.len + 1]; + std.mem.copy(u8, &JSC.VirtualMachine.vm.bundler.fs.top_level_dir_buf, with_trailing_slash); + JSC.VirtualMachine.vm.bundler.fs.top_level_dir = JSC.VirtualMachine.vm.bundler.fs.top_level_dir_buf[0..with_trailing_slash.len]; + return JSC.JSValue.jsUndefined(); + }, + } + } + + pub export const Bun__version: [:0]const u8 = "v" ++ _global.Global.package_json_version; + pub export const Bun__versions_mimalloc: [:0]const u8 = _global.Global.versions.mimalloc; + pub export const Bun__versions_webkit: [:0]const u8 = _global.Global.versions.webkit; + pub export const Bun__versions_libarchive: [:0]const u8 = _global.Global.versions.libarchive; + pub export const Bun__versions_picohttpparser: [:0]const u8 = _global.Global.versions.picohttpparser; + pub export const Bun__versions_boringssl: [:0]const u8 = _global.Global.versions.boringssl; + pub export const Bun__versions_zlib: [:0]const u8 = _global.Global.versions.zlib; + pub export const Bun__versions_zig: [:0]const u8 = _global.Global.versions.zig; +}; + +comptime { + std.testing.refAllDecls(Process); + std.testing.refAllDecls(Stream); + std.testing.refAllDecls(Readable); + std.testing.refAllDecls(Writable); + std.testing.refAllDecls(Writable.State); + std.testing.refAllDecls(Readable.State); +} diff --git a/src/javascript/jsc/test/jest.zig b/src/javascript/jsc/test/jest.zig new file mode 100644 index 000000000..1398e9058 --- /dev/null +++ b/src/javascript/jsc/test/jest.zig @@ -0,0 +1,814 @@ +const std = @import("std"); +const Api = @import("../../../api/schema.zig").Api; +const RequestContext = @import("../../../http.zig").RequestContext; +const MimeType = @import("../../../http.zig").MimeType; +const ZigURL = @import("../../../query_string_map.zig").URL; +const HTTPClient = @import("http"); +const NetworkThread = HTTPClient.NetworkThread; + +const JSC = @import("../../../jsc.zig"); +const js = JSC.C; + +const logger = @import("../../../logger.zig"); +const Method = @import("../../../http/method.zig").Method; + +const ObjectPool = @import("../../../pool.zig").ObjectPool; + +const Output = @import("../../../global.zig").Output; +const MutableString = @import("../../../global.zig").MutableString; +const strings = @import("../../../global.zig").strings; +const string = @import("../../../global.zig").string; +const default_allocator = @import("../../../global.zig").default_allocator; +const FeatureFlags = @import("../../../global.zig").FeatureFlags; +const ArrayBuffer = @import("../base.zig").ArrayBuffer; +const Properties = @import("../base.zig").Properties; +const NewClass = @import("../base.zig").NewClass; +const d = @import("../base.zig").d; +const castObj = @import("../base.zig").castObj; +const getAllocator = @import("../base.zig").getAllocator; +const JSPrivateDataPtr = @import("../base.zig").JSPrivateDataPtr; +const GetJSPrivateData = @import("../base.zig").GetJSPrivateData; + +const ZigString = JSC.ZigString; +const JSInternalPromise = JSC.JSInternalPromise; +const JSPromise = JSC.JSPromise; +const JSValue = JSC.JSValue; +const JSError = JSC.JSError; +const JSGlobalObject = JSC.JSGlobalObject; + +const VirtualMachine = @import("../javascript.zig").VirtualMachine; +const Task = @import("../javascript.zig").Task; + +const Fs = @import("../../../fs.zig"); + +fn notImplementedFn(_: *anyopaque, ctx: js.JSContextRef, _: js.JSObjectRef, _: js.JSObjectRef, _: []const js.JSValueRef, exception: js.ExceptionRef) js.JSValueRef { + JSError(getAllocator(ctx), "Not implemented yet!", .{}, ctx, exception); + return null; +} + +fn notImplementedProp( + _: anytype, + ctx: js.JSContextRef, + _: js.JSObjectRef, + _: js.JSStringRef, + exception: js.ExceptionRef, +) js.JSValueRef { + JSError(getAllocator(ctx), "Property not implemented yet!", .{}, ctx, exception); + return null; +} + +const ArrayIdentityContext = @import("../../../identity_context.zig").ArrayIdentityContext; +pub const TestRunner = struct { + tests: TestRunner.Test.List = .{}, + log: *logger.Log, + files: File.List = .{}, + index: File.Map = File.Map{}, + + timeout_seconds: f64 = 5.0, + + allocator: std.mem.Allocator, + callback: *Callback = undefined, + + pub const Callback = struct { + pub const OnUpdateCount = fn (this: *Callback, delta: u32, total: u32) void; + pub const OnTestStart = fn (this: *Callback, test_id: Test.ID) void; + pub const OnTestPass = fn (this: *Callback, test_id: Test.ID, expectations: u32) void; + pub const OnTestFail = fn (this: *Callback, test_id: Test.ID, file: string, label: string, expectations: u32) void; + onUpdateCount: OnUpdateCount, + onTestStart: OnTestStart, + onTestPass: OnTestPass, + onTestFail: OnTestFail, + }; + + pub fn reportPass(this: *TestRunner, test_id: Test.ID, expectations: u32) void { + this.tests.items(.status)[test_id] = .pass; + this.callback.onTestPass(this.callback, test_id, expectations); + } + pub fn reportFailure(this: *TestRunner, test_id: Test.ID, file: string, label: string, expectations: u32) void { + this.tests.items(.status)[test_id] = .fail; + this.callback.onTestFail(this.callback, test_id, file, label, expectations); + } + + pub fn addTestCount(this: *TestRunner, count: u32) u32 { + this.tests.ensureUnusedCapacity(this.allocator, count) catch unreachable; + const start = @truncate(Test.ID, this.tests.len); + this.tests.len += count; + var statuses = this.tests.items(.status)[start..][0..count]; + std.mem.set(Test.Status, statuses, Test.Status.pending); + this.callback.onUpdateCount(this.callback, count, count + start); + return start; + } + + pub fn getOrPutFile(this: *TestRunner, file_path: string) *DescribeScope { + var entry = this.index.getOrPut(this.allocator, @truncate(u32, std.hash.Wyhash.hash(0, file_path))) catch unreachable; + if (entry.found_existing) { + return this.files.items(.module_scope)[entry.value_ptr.*]; + } + var scope = this.allocator.create(DescribeScope) catch unreachable; + const file_id = @truncate(File.ID, this.files.len); + scope.* = DescribeScope{ + .file_id = file_id, + .test_id_start = @truncate(Test.ID, this.tests.len), + }; + this.files.append(this.allocator, .{ .module_scope = scope, .source = logger.Source.initEmptyFile(file_path) }) catch unreachable; + entry.value_ptr.* = file_id; + return scope; + } + + pub const File = struct { + source: logger.Source = logger.Source.initEmptyFile(""), + log: logger.Log = logger.Log.init(default_allocator), + module_scope: *DescribeScope = undefined, + + pub const List = std.MultiArrayList(File); + pub const ID = u32; + pub const Map = std.ArrayHashMapUnmanaged(u32, u32, ArrayIdentityContext, false); + }; + + pub const Test = struct { + status: Status = Status.pending, + + pub const ID = u32; + pub const List = std.MultiArrayList(Test); + + pub const Status = enum(u3) { + pending, + pass, + fail, + }; + }; +}; + +pub const Jest = struct { + pub var runner: ?*TestRunner = null; + + pub fn call( + _: void, + ctx: js.JSContextRef, + _: js.JSObjectRef, + _: js.JSObjectRef, + arguments: []const js.JSValueRef, + exception: js.ExceptionRef, + ) js.JSValueRef { + var runner_ = runner orelse { + JSError(getAllocator(ctx), "Run bun test to run a test", .{}, ctx, exception); + return js.JSValueMakeUndefined(ctx); + }; + + if (arguments.len < 1 or !js.JSValueIsString(ctx, arguments[0])) { + JSError(getAllocator(ctx), "Bun.jest() expects a string filename", .{}, ctx, exception); + return js.JSValueMakeUndefined(ctx); + } + var str = js.JSValueToStringCopy(ctx, arguments[0], exception); + defer js.JSStringRelease(str); + var ptr = js.JSStringGetCharacters8Ptr(str); + const len = js.JSStringGetLength(str); + if (len == 0 or ptr[0] != '/') { + JSError(getAllocator(ctx), "Bun.jest() expects an absolute file path", .{}, ctx, exception); + return js.JSValueMakeUndefined(ctx); + } + var str_value = ptr[0..len]; + var filepath = Fs.FileSystem.instance.filename_store.append([]const u8, str_value) catch unreachable; + + var scope = runner_.getOrPutFile(filepath); + DescribeScope.active = scope; + + return DescribeScope.Class.make(ctx, scope); + } +}; + +/// https://jestjs.io/docs/expect +// To support async tests, we need to track the test ID +pub const Expect = struct { + test_id: TestRunner.Test.ID, + scope: *DescribeScope, + value: js.JSValueRef, + op: Op.Set = Op.Set.init(.{}), + + pub const Op = enum(u3) { + resolves, + rejects, + not, + pub const Set = std.EnumSet(Op); + }; + + pub fn finalize( + this: *Expect, + ) void { + js.JSValueUnprotect(VirtualMachine.vm.global.ref(), this.value); + VirtualMachine.vm.allocator.destroy(this); + } + + pub const Class = NewClass( + Expect, + .{ .name = "Expect" }, + .{ + .toBe = .{ + .rfn = Expect.toBe, + .name = "toBe", + }, + .toHaveBeenCalledTimes = .{ + .rfn = Expect.toHaveBeenCalledTimes, + .name = "toHaveBeenCalledTimes", + }, + .finalize = .{ .rfn = Expect.finalize, .name = "finalize" }, + .toHaveBeenCalledWith = .{ + .rfn = Expect.toHaveBeenCalledWith, + .name = "toHaveBeenCalledWith", + }, + .toHaveBeenLastCalledWith = .{ + .rfn = Expect.toHaveBeenLastCalledWith, + .name = "toHaveBeenLastCalledWith", + }, + .toHaveBeenNthCalledWith = .{ + .rfn = Expect.toHaveBeenNthCalledWith, + .name = "toHaveBeenNthCalledWith", + }, + .toHaveReturnedTimes = .{ + .rfn = Expect.toHaveReturnedTimes, + .name = "toHaveReturnedTimes", + }, + .toHaveReturnedWith = .{ + .rfn = Expect.toHaveReturnedWith, + .name = "toHaveReturnedWith", + }, + .toHaveLastReturnedWith = .{ + .rfn = Expect.toHaveLastReturnedWith, + .name = "toHaveLastReturnedWith", + }, + .toHaveNthReturnedWith = .{ + .rfn = Expect.toHaveNthReturnedWith, + .name = "toHaveNthReturnedWith", + }, + .toHaveLength = .{ + .rfn = Expect.toHaveLength, + .name = "toHaveLength", + }, + .toHaveProperty = .{ + .rfn = Expect.toHaveProperty, + .name = "toHaveProperty", + }, + .toBeCloseTo = .{ + .rfn = Expect.toBeCloseTo, + .name = "toBeCloseTo", + }, + .toBeGreaterThan = .{ + .rfn = Expect.toBeGreaterThan, + .name = "toBeGreaterThan", + }, + .toBeGreaterThanOrEqual = .{ + .rfn = Expect.toBeGreaterThanOrEqual, + .name = "toBeGreaterThanOrEqual", + }, + .toBeLessThan = .{ + .rfn = Expect.toBeLessThan, + .name = "toBeLessThan", + }, + .toBeLessThanOrEqual = .{ + .rfn = Expect.toBeLessThanOrEqual, + .name = "toBeLessThanOrEqual", + }, + .toBeInstanceOf = .{ + .rfn = Expect.toBeInstanceOf, + .name = "toBeInstanceOf", + }, + .toContain = .{ + .rfn = Expect.toContain, + .name = "toContain", + }, + .toContainEqual = .{ + .rfn = Expect.toContainEqual, + .name = "toContainEqual", + }, + .toEqual = .{ + .rfn = Expect.toEqual, + .name = "toEqual", + }, + .toMatch = .{ + .rfn = Expect.toMatch, + .name = "toMatch", + }, + .toMatchObject = .{ + .rfn = Expect.toMatchObject, + .name = "toMatchObject", + }, + .toMatchSnapshot = .{ + .rfn = Expect.toMatchSnapshot, + .name = "toMatchSnapshot", + }, + .toMatchInlineSnapshot = .{ + .rfn = Expect.toMatchInlineSnapshot, + .name = "toMatchInlineSnapshot", + }, + .toStrictEqual = .{ + .rfn = Expect.toStrictEqual, + .name = "toStrictEqual", + }, + .toThrow = .{ + .rfn = Expect.toThrow, + .name = "toThrow", + }, + .toThrowErrorMatchingSnapshot = .{ + .rfn = Expect.toThrowErrorMatchingSnapshot, + .name = "toThrowErrorMatchingSnapshot", + }, + .toThrowErrorMatchingInlineSnapshot = .{ + .rfn = Expect.toThrowErrorMatchingInlineSnapshot, + .name = "toThrowErrorMatchingInlineSnapshot", + }, + }, + .{ + .not = .{ + .get = Expect.not, + .name = "not", + }, + .resolves = .{ + .get = Expect.resolves, + .name = "resolves", + }, + .rejects = .{ + .get = Expect.rejects, + .name = "rejects", + }, + }, + ); + + /// Object.is() + pub fn toBe( + this: *Expect, + ctx: js.JSContextRef, + _: js.JSObjectRef, + thisObject: js.JSObjectRef, + arguments: []const js.JSValueRef, + exception: js.ExceptionRef, + ) js.JSValueRef { + if (arguments.len != 1) { + JSC.JSError( + getAllocator(ctx), + ".toBe() takes 1 argument", + .{}, + ctx, + exception, + ); + return js.JSValueMakeUndefined(ctx); + } + this.scope.tests.items[this.test_id].counter.actual += 1; + if (!JSValue.fromRef(arguments[0]).isSameValue(JSValue.fromRef(this.value), ctx.ptr())) { + JSC.JSError( + getAllocator(ctx), + "fail", + .{}, + ctx, + exception, + ); + return null; + } + return thisObject; + } + pub const toHaveBeenCalledTimes = notImplementedFn; + pub const toHaveBeenCalledWith = notImplementedFn; + pub const toHaveBeenLastCalledWith = notImplementedFn; + pub const toHaveBeenNthCalledWith = notImplementedFn; + pub const toHaveReturnedTimes = notImplementedFn; + pub const toHaveReturnedWith = notImplementedFn; + pub const toHaveLastReturnedWith = notImplementedFn; + pub const toHaveNthReturnedWith = notImplementedFn; + pub const toHaveLength = notImplementedFn; + pub const toHaveProperty = notImplementedFn; + pub const toBeCloseTo = notImplementedFn; + pub const toBeGreaterThan = notImplementedFn; + pub const toBeGreaterThanOrEqual = notImplementedFn; + pub const toBeLessThan = notImplementedFn; + pub const toBeLessThanOrEqual = notImplementedFn; + pub const toBeInstanceOf = notImplementedFn; + pub const toContain = notImplementedFn; + pub const toContainEqual = notImplementedFn; + pub const toEqual = notImplementedFn; + pub const toMatch = notImplementedFn; + pub const toMatchObject = notImplementedFn; + pub const toMatchSnapshot = notImplementedFn; + pub const toMatchInlineSnapshot = notImplementedFn; + pub const toStrictEqual = notImplementedFn; + pub const toThrow = notImplementedFn; + pub const toThrowErrorMatchingSnapshot = notImplementedFn; + pub const toThrowErrorMatchingInlineSnapshot = notImplementedFn; + + pub const not = notImplementedProp; + pub const resolves = notImplementedProp; + pub const rejects = notImplementedProp; +}; + +pub const ExpectPrototype = struct { + scope: *DescribeScope, + test_id: TestRunner.Test.ID, + op: Expect.Op.Set = Expect.Op.Set.init(.{}), + + pub const Class = NewClass( + ExpectPrototype, + .{ + .name = "ExpectPrototype", + .read_only = true, + }, + .{ + .call = .{ + .rfn = ExpectPrototype.call, + }, + .extend = .{ + .name = "extend", + .rfn = ExpectPrototype.extend, + }, + .anything = .{ + .name = "anything", + .rfn = ExpectPrototype.anything, + }, + .any = .{ + .name = "any", + .rfn = ExpectPrototype.any, + }, + .arrayContaining = .{ + .name = "arrayContaining", + .rfn = ExpectPrototype.arrayContaining, + }, + .assertions = .{ + .name = "assertions", + .rfn = ExpectPrototype.assertions, + }, + .hasAssertions = .{ + .name = "hasAssertions", + .rfn = ExpectPrototype.hasAssertions, + }, + .objectContaining = .{ + .name = "objectContaining", + .rfn = ExpectPrototype.objectContaining, + }, + .stringContaining = .{ + .name = "stringContaining", + .rfn = ExpectPrototype.stringContaining, + }, + .stringMatching = .{ + .name = "stringMatching", + .rfn = ExpectPrototype.stringMatching, + }, + .addSnapshotSerializer = .{ + .name = "addSnapshotSerializer", + .rfn = ExpectPrototype.addSnapshotSerializer, + }, + }, + .{ + .not = .{ + .name = "not", + .get = ExpectPrototype.not, + }, + .resolves = .{ + .name = "resolves", + .get = ExpectPrototype.resolves, + }, + .rejects = .{ + .name = "rejects", + .get = ExpectPrototype.rejects, + }, + }, + ); + pub const extend = notImplementedFn; + pub const anything = notImplementedFn; + pub const any = notImplementedFn; + pub const arrayContaining = notImplementedFn; + pub const assertions = notImplementedFn; + pub const hasAssertions = notImplementedFn; + pub const objectContaining = notImplementedFn; + pub const stringContaining = notImplementedFn; + pub const stringMatching = notImplementedFn; + pub const addSnapshotSerializer = notImplementedFn; + pub const not = notImplementedProp; + pub const resolves = notImplementedProp; + pub const rejects = notImplementedProp; + + pub fn call( + _: *ExpectPrototype, + ctx: js.JSContextRef, + _: js.JSObjectRef, + _: js.JSObjectRef, + arguments: []const js.JSValueRef, + exception: js.ExceptionRef, + ) js.JSObjectRef { + if (arguments.len != 1) { + JSError(getAllocator(ctx), "expect() requires one argument", .{}, ctx, exception); + return js.JSValueMakeUndefined(ctx); + } + var expect_ = getAllocator(ctx).create(Expect) catch unreachable; + js.JSValueProtect(ctx, arguments[0]); + expect_.* = .{ + .value = arguments[0], + .scope = DescribeScope.active, + .test_id = DescribeScope.active.current_test_id, + }; + return Expect.Class.make(ctx, expect_); + } +}; + +pub const TestScope = struct { + counter: Counter = Counter{}, + label: string = "", + parent: *DescribeScope, + callback: js.JSValueRef, + id: TestRunner.Test.ID = 0, + + pub const Class = NewClass(void, .{ .name = "test" }, .{ .call = call }, .{}); + + pub const Counter = struct { + expected: u32 = 0, + actual: u32 = 0, + }; + + pub fn call( + // the DescribeScope here is the top of the file, not the real one + _: void, + ctx: js.JSContextRef, + _: js.JSObjectRef, + _: js.JSObjectRef, + arguments: []const js.JSValueRef, + exception: js.ExceptionRef, + ) js.JSObjectRef { + var args = arguments[0..@minimum(arguments.len, 2)]; + var label: string = ""; + if (args.len == 0) { + return js.JSValueMakeUndefined(ctx); + } + + if (js.JSValueIsString(ctx, args[0])) { + var label_ = ZigString.init(""); + JSC.JSValue.fromRef(arguments[0]).toZigString(&label_, ctx.ptr()); + label = if (label_.is16Bit()) + (strings.toUTF8AllocWithType(getAllocator(ctx), @TypeOf(label_.utf16Slice()), label_.utf16Slice()) catch unreachable) + else + label_.full(); + args = args[1..]; + } + + var function = args[0]; + if (!js.JSValueIsObject(ctx, function) or !js.JSObjectIsFunction(ctx, function)) { + JSError(getAllocator(ctx), "test() expects a function", .{}, ctx, exception); + return js.JSValueMakeUndefined(ctx); + } + + js.JSValueProtect(ctx, function); + + DescribeScope.active.tests.append(getAllocator(ctx), TestScope{ + .label = label, + .callback = function, + .parent = DescribeScope.active, + }) catch unreachable; + + return js.JSValueMakeUndefined(ctx); + } + + pub const Result = union(TestRunner.Test.Status) { + fail: u32, + pass: u32, // assertion count + pending: void, + }; + + pub fn run( + this: *TestScope, + ) Result { + var vm = VirtualMachine.vm; + + var promise = JSC.JSPromise.resolvedPromise( + vm.global, + js.JSObjectCallAsFunctionReturnValue(vm.global.ref(), this.callback, null, 0, null), + ); + js.JSValueUnprotect(vm.global.ref(), this.callback); + this.callback = null; + + while (promise.status(vm.global.vm()) == JSC.JSPromise.Status.Pending) { + vm.tick(); + } + var result = promise.result(vm.global.vm()); + + if (result.isException(vm.global.vm()) or result.isError() or result.isAggregateError(vm.global)) { + vm.defaultErrorHandler(result, null); + return .{ .fail = this.counter.actual }; + } + + if (this.counter.expected > 0 and this.counter.expected < this.counter.actual) { + Output.prettyErrorln("Test fail: {d} / {d} expectations\n (make this better!)", .{ + this.counter.actual, + this.counter.expected, + }); + return .{ .fail = this.counter.actual }; + } + + return .{ .pass = this.counter.actual }; + } +}; + +pub const DescribeScope = struct { + label: string = "", + parent: ?*DescribeScope = null, + beforeAll: std.ArrayListUnmanaged(js.JSValueRef) = .{}, + beforeEach: std.ArrayListUnmanaged(js.JSValueRef) = .{}, + afterEach: std.ArrayListUnmanaged(js.JSValueRef) = .{}, + afterAll: std.ArrayListUnmanaged(js.JSValueRef) = .{}, + test_id_start: TestRunner.Test.ID = 0, + test_id_len: TestRunner.Test.ID = 0, + tests: std.ArrayListUnmanaged(TestScope) = .{}, + file_id: TestRunner.File.ID, + current_test_id: TestRunner.Test.ID = 0, + + pub const TestEntry = struct { + label: string, + callback: js.JSValueRef, + + pub const List = std.MultiArrayList(TestEntry); + }; + + pub threadlocal var active: *DescribeScope = undefined; + + pub const Class = NewClass( + DescribeScope, + .{ + .name = "describe", + .read_only = true, + }, + .{ + .call = describe, + .afterAll = .{ .rfn = callAfterAll, .name = "afterAll" }, + .beforeAll = .{ .rfn = callAfterAll, .name = "beforeAll" }, + .beforeEach = .{ .rfn = callAfterAll, .name = "beforeEach" }, + }, + .{ + .expect = .{ .get = createExpect, .name = "expect" }, + // kind of a mindfuck but + // describe("foo", () => {}).describe("bar") will wrok + .describe = .{ .get = createDescribe, .name = "describe" }, + .it = .{ .get = createTest, .name = "it" }, + .@"test" = .{ .get = createTest, .name = "test" }, + }, + ); + + pub fn describe( + this: *DescribeScope, + ctx: js.JSContextRef, + _: js.JSObjectRef, + _: js.JSObjectRef, + arguments: []const js.JSValueRef, + exception: js.ExceptionRef, + ) js.JSObjectRef { + if (arguments.len == 0 or arguments.len > 2) { + JSError(getAllocator(ctx), "describe() requires 1-2 arguments", .{}, ctx, exception); + return js.JSValueMakeUndefined(ctx); + } + + var label = ZigString.init(""); + var args = arguments; + + if (js.JSValueIsString(ctx, arguments[0])) { + JSC.JSValue.fromRef(arguments[0]).toZigString(&label, ctx.ptr()); + args = args[1..]; + } + + if (args.len == 0 or !js.JSObjectIsFunction(ctx, args[0])) { + JSError(getAllocator(ctx), "describe() requires a callback function", .{}, ctx, exception); + return js.JSValueMakeUndefined(ctx); + } + + var callback = args[0]; + + var scope = getAllocator(ctx).create(DescribeScope) catch unreachable; + scope.* = .{ + .label = if (label.is16Bit()) + (strings.toUTF8AllocWithType(getAllocator(ctx), @TypeOf(label.utf16Slice()), label.utf16Slice()) catch unreachable) + else + label.full(), + .parent = this, + .file_id = this.file_id, + }; + var new_this = DescribeScope.Class.make(ctx, scope); + + return scope.run(new_this, ctx, callback, exception); + } + + pub fn run(this: *DescribeScope, thisObject: js.JSObjectRef, ctx: js.JSContextRef, callback: js.JSObjectRef, exception: js.ExceptionRef) js.JSObjectRef { + js.JSValueProtect(ctx, callback); + defer js.JSValueUnprotect(ctx, callback); + var original_active = active; + defer active = original_active; + active = this; + + { + var result = js.JSObjectCallAsFunctionReturnValue(ctx, callback, thisObject, 0, null); + if (result.isException(ctx.ptr().vm())) { + exception.* = result.asObjectRef(); + return null; + } + } + this.runTests(ctx); + return js.JSValueMakeUndefined(ctx); + } + + pub fn runTests(this: *DescribeScope, ctx: js.JSContextRef) void { + // Step 1. Initialize the test block + + const file = this.file_id; + + var tests: []TestScope = this.tests.items; + const end = @truncate(TestRunner.Test.ID, tests.len); + + if (end == 0) return; + + // Step 2. Update the runner with the count of how many tests we have for this block + this.test_id_start = Jest.runner.?.addTestCount(end); + + // Step 3. Run the beforeAll callbacks, in reverse order + // TODO: + + const source: logger.Source = Jest.runner.?.files.items(.source)[file]; + + var i: TestRunner.Test.ID = 0; + + while (i < end) { + this.current_test_id = i; + const result = TestScope.run(&tests[i]); + // invalidate it + this.current_test_id = std.math.maxInt(TestRunner.Test.ID); + + const test_id = i + this.test_id_start; + switch (result) { + .pass => |count| Jest.runner.?.reportPass(test_id, count), + .fail => |count| Jest.runner.?.reportFailure(test_id, source.path.text, tests[i].label, count), + .pending => unreachable, + } + + i += 1; + } + this.tests.deinit(getAllocator(ctx)); + } + + const ScopeStack = ObjectPool(std.ArrayListUnmanaged(*DescribeScope), null, true); + + // pub fn runBeforeAll(this: *DescribeScope, ctx: js.JSContextRef, exception: js.ExceptionRef) bool { + // var scopes = ScopeStack.get(default_allocator); + // defer scopes.release(); + // scopes.data.clearRetainingCapacity(); + // var cur: ?*DescribeScope = this; + // while (cur) |scope| { + // scopes.data.append(default_allocator, this) catch unreachable; + // cur = scope.parent; + // } + + // // while (scopes.data.popOrNull()) |scope| { + // // scope. + // // } + // } + + pub fn runCallbacks(this: *DescribeScope, ctx: js.JSContextRef, callbacks: std.ArrayListUnmanaged(js.JSObjectRef), exception: js.ExceptionRef) bool { + var i: usize = 0; + while (i < callbacks.items.len) : (i += 1) { + var callback = callbacks.items[i]; + var result = js.JSObjectCallAsFunctionReturnValue(ctx, callback, this, 0); + if (result.isException(ctx.ptr().vm())) { + exception.* = result.asObjectRef(); + return false; + } + } + } + + pub const callAfterAll = notImplementedFn; + pub const callAfterEach = notImplementedFn; + pub const callBeforeAll = notImplementedFn; + + pub fn createExpect( + _: *DescribeScope, + ctx: js.JSContextRef, + _: js.JSValueRef, + _: js.JSStringRef, + _: js.ExceptionRef, + ) js.JSObjectRef { + var expect_ = getAllocator(ctx).create(ExpectPrototype) catch unreachable; + expect_.* = .{ + .scope = DescribeScope.active, + .test_id = DescribeScope.active.current_test_id, + }; + return ExpectPrototype.Class.make(ctx, expect_); + } + + pub fn createTest( + _: *DescribeScope, + ctx: js.JSContextRef, + _: js.JSValueRef, + _: js.JSStringRef, + _: js.ExceptionRef, + ) js.JSObjectRef { + return js.JSObjectMake(ctx, TestScope.Class.get().*, null); + } + + pub fn createDescribe( + this: *DescribeScope, + ctx: js.JSContextRef, + _: js.JSValueRef, + _: js.JSStringRef, + _: js.ExceptionRef, + ) js.JSObjectRef { + return DescribeScope.Class.make(ctx, this); + } +}; diff --git a/src/javascript/jsc/webcore/response.zig b/src/javascript/jsc/webcore/response.zig index dfb17f630..1ff43bc98 100644 --- a/src/javascript/jsc/webcore/response.zig +++ b/src/javascript/jsc/webcore/response.zig @@ -95,7 +95,7 @@ pub const Response = struct { pub fn getText( this: *Response, - _: js.JSContextRef, + ctx: js.JSContextRef, _: js.JSObjectRef, _: js.JSObjectRef, _: []const js.JSValueRef, @@ -104,30 +104,45 @@ pub const Response = struct { // https://developer.mozilla.org/en-US/docs/Web/API/Response/text defer this.body.value = .Empty; return JSPromise.resolvedPromiseValue( - VirtualMachine.vm.global, + ctx.ptr(), (brk: { switch (this.body.value) { .Unconsumed => { if (this.body.len > 0) { if (this.body.ptr) |_ptr| { - var offset: usize = 0; - while (offset < this.body.len and (_ptr[offset] > 127 or strings.utf8ByteSequenceLength(_ptr[offset]) == 0)) : (offset += 1) {} - if (offset < this.body.len) { - break :brk ZigString.init(_ptr[offset..this.body.len]).toValue(VirtualMachine.vm.global); + var zig_string = ZigString.init(_ptr[0..this.body.len]); + zig_string.detectEncoding(); + if (zig_string.is16Bit()) { + var value = zig_string.to16BitValue(ctx.ptr()); + this.body.ptr_allocator.?.free(_ptr[0..this.body.len]); + this.body.ptr_allocator = null; + this.body.ptr = null; + break :brk value; } + + break :brk zig_string.toValue(ctx.ptr()); } } - break :brk ZigString.init("").toValue(VirtualMachine.vm.global); + break :brk ZigString.init("").toValue(ctx.ptr()); }, .Empty => { - break :brk ZigString.init("").toValue(VirtualMachine.vm.global); + break :brk ZigString.init("").toValue(ctx.ptr()); }, .String => |str| { - break :brk ZigString.init(str).toValue(VirtualMachine.vm.global); + var zig_string = ZigString.init(str); + + zig_string.detectEncoding(); + if (zig_string.is16Bit()) { + var value = zig_string.to16BitValue(ctx.ptr()); + if (this.body.ptr_allocator) |allocator| this.body.deinit(allocator); + break :brk value; + } + + break :brk zig_string.toValue(ctx.ptr()); }, .ArrayBuffer => |buffer| { - break :brk ZigString.init(buffer.ptr[buffer.offset..buffer.byte_len]).toValue(VirtualMachine.vm.global); + break :brk ZigString.init(buffer.ptr[buffer.offset..buffer.byte_len]).toValue(ctx.ptr()); }, } }), @@ -188,9 +203,9 @@ pub const Response = struct { }, ) orelse { var out = std.fmt.bufPrint(&temp_error_buffer, "Invalid JSON\n\n \"{s}\"", .{zig_string.slice()[0..std.math.min(zig_string.len, 4000)]}) catch unreachable; - error_arg_list[0] = ZigString.init(out).toValueGC(VirtualMachine.vm.global).asRef(); + error_arg_list[0] = ZigString.init(out).toValueGC(ctx.ptr()).asRef(); return JSPromise.rejectedPromiseValue( - VirtualMachine.vm.global, + ctx.ptr(), JSValue.fromRef( js.JSObjectMakeError( ctx, @@ -203,7 +218,7 @@ pub const Response = struct { }); return JSPromise.resolvedPromiseValue( - VirtualMachine.vm.global, + ctx.ptr(), JSValue.fromRef(json_value), ).asRef(); } @@ -217,7 +232,7 @@ pub const Response = struct { ) js.JSValueRef { defer this.body.value = .Empty; return JSPromise.resolvedPromiseValue( - VirtualMachine.vm.global, + ctx.ptr(), JSValue.fromRef( (brk: { switch (this.body.value) { @@ -630,14 +645,13 @@ pub const Fetch = struct { node.data.http.schedule(allocator, &batch); NetworkThread.global.pool.schedule(batch); - try VirtualMachine.vm.enqueueTask(Task.init(&node.data)); return node; } pub fn callback(http_: *HTTPClient.AsyncHTTP, sender: *HTTPClient.AsyncHTTP.HTTPSender) void { var task: *FetchTasklet = @fieldParentPtr(FetchTasklet, "http", http_); @atomicStore(Status, &task.status, Status.done, .Monotonic); - _ = task.javascript_vm.eventLoop().ready_tasks_count.fetchAdd(1, .Monotonic); + task.javascript_vm.eventLoop().enqueueTaskConcurrent(Task.init(task)); sender.release(); } }; @@ -650,23 +664,25 @@ pub const Fetch = struct { arguments: []const js.JSValueRef, exception: js.ExceptionRef, ) js.JSObjectRef { + var globalThis = ctx.ptr(); + if (arguments.len == 0) { const fetch_error = fetch_error_no_args; - return JSPromise.rejectedPromiseValue(VirtualMachine.vm.global, ZigString.init(fetch_error).toErrorInstance(VirtualMachine.vm.global)).asRef(); + return JSPromise.rejectedPromiseValue(globalThis, ZigString.init(fetch_error).toErrorInstance(globalThis)).asRef(); } if (!js.JSValueIsString(ctx, arguments[0])) { const fetch_error = fetch_type_error_strings.get(js.JSValueGetType(ctx, arguments[0])); - return JSPromise.rejectedPromiseValue(VirtualMachine.vm.global, ZigString.init(fetch_error).toErrorInstance(VirtualMachine.vm.global)).asRef(); + return JSPromise.rejectedPromiseValue(globalThis, ZigString.init(fetch_error).toErrorInstance(globalThis)).asRef(); } var url_zig_str = ZigString.init(""); - JSValue.fromRef(arguments[0]).toZigString(&url_zig_str, VirtualMachine.vm.global); + JSValue.fromRef(arguments[0]).toZigString(&url_zig_str, globalThis); var url_str = url_zig_str.slice(); if (url_str.len == 0) { const fetch_error = fetch_error_blank_url; - return JSPromise.rejectedPromiseValue(VirtualMachine.vm.global, ZigString.init(fetch_error).toErrorInstance(VirtualMachine.vm.global)).asRef(); + return JSPromise.rejectedPromiseValue(globalThis, ZigString.init(fetch_error).toErrorInstance(globalThis)).asRef(); } if (url_str[0] == '/') { @@ -680,7 +696,7 @@ pub const Fetch = struct { if (url.origin.len > 0 and strings.eql(url.origin, VirtualMachine.vm.bundler.options.origin.origin)) { const fetch_error = fetch_error_cant_fetch_same_origin; - return JSPromise.rejectedPromiseValue(VirtualMachine.vm.global, ZigString.init(fetch_error).toErrorInstance(VirtualMachine.vm.global)).asRef(); + return JSPromise.rejectedPromiseValue(globalThis, ZigString.init(fetch_error).toErrorInstance(globalThis)).asRef(); } var headers: ?Headers = null; @@ -757,7 +773,7 @@ pub const Fetch = struct { // var resolve = FetchTasklet.FetchResolver.Class.make(ctx: js.JSContextRef, ptr: *ZigType) var queued = FetchTasklet.queue( default_allocator, - VirtualMachine.vm.global, + globalThis, method, url, header_entries, @@ -1302,7 +1318,8 @@ pub const Body = struct { ptr_allocator: ?std.mem.Allocator = null, pub fn deinit(this: *Body, allocator: std.mem.Allocator) void { - if (this.init.headers) |headers| { + this.ptr_allocator = null; + if (this.init.headers) |*headers| { headers.deinit(); } @@ -1312,6 +1329,7 @@ pub const Body = struct { allocator.free(str); }, .Empty => {}, + else => {}, } } @@ -1434,7 +1452,7 @@ pub const Body = struct { } else |_| {} } - var wtf_string = JSValue.fromRef(body_ref).toWTFString(VirtualMachine.vm.global); + var wtf_string = JSValue.fromRef(body_ref).toWTFString(ctx.ptr()); if (wtf_string.isEmpty()) { body.value = .{ .String = "" }; @@ -1575,7 +1593,7 @@ pub const Request = struct { _: js.JSStringRef, _: js.ExceptionRef, ) js.JSValueRef { - return js.JSValueMakeString(ctx, ZigString.init(Properties.UTF8.default).toValueGC(VirtualMachine.vm.global).asRef()); + return js.JSValueMakeString(ctx, ZigString.init(Properties.UTF8.default).toValueGC(ctx.ptr()).asRef()); } pub fn getCredentials( _: *Request, @@ -1584,7 +1602,7 @@ pub const Request = struct { _: js.JSStringRef, _: js.ExceptionRef, ) js.JSValueRef { - return js.JSValueMakeString(ctx, ZigString.init(Properties.UTF8.include).toValueGC(VirtualMachine.vm.global).asRef()); + return js.JSValueMakeString(ctx, ZigString.init(Properties.UTF8.include).toValueGC(ctx.ptr()).asRef()); } pub fn getDestination( _: *Request, @@ -1593,7 +1611,7 @@ pub const Request = struct { _: js.JSStringRef, _: js.ExceptionRef, ) js.JSValueRef { - return js.JSValueMakeString(ctx, ZigString.init("").toValueGC(VirtualMachine.vm.global).asRef()); + return js.JSValueMakeString(ctx, ZigString.init("").toValueGC(ctx.ptr()).asRef()); } pub fn getHeaders( this: *Request, @@ -1610,16 +1628,16 @@ pub const Request = struct { } pub fn getIntegrity( _: *Request, - _: js.JSContextRef, + ctx: js.JSContextRef, _: js.JSObjectRef, _: js.JSStringRef, _: js.ExceptionRef, ) js.JSValueRef { - return ZigString.Empty.toValueGC(VirtualMachine.vm.global).asRef(); + return ZigString.Empty.toValueGC(ctx.ptr()).asRef(); } pub fn getMethod( this: *Request, - _: js.JSContextRef, + ctx: js.JSContextRef, _: js.JSObjectRef, _: js.JSStringRef, _: js.ExceptionRef, @@ -1634,48 +1652,48 @@ pub const Request = struct { else => "", }; - return ZigString.init(string_contents).toValueGC(VirtualMachine.vm.global).asRef(); + return ZigString.init(string_contents).toValueGC(ctx.ptr()).asRef(); } pub fn getMode( _: *Request, - _: js.JSContextRef, + ctx: js.JSContextRef, _: js.JSObjectRef, _: js.JSStringRef, _: js.ExceptionRef, ) js.JSValueRef { - return ZigString.init(Properties.UTF8.navigate).toValueGC(VirtualMachine.vm.global).asRef(); + return ZigString.init(Properties.UTF8.navigate).toValueGC(ctx.ptr()).asRef(); } pub fn getRedirect( _: *Request, - _: js.JSContextRef, + ctx: js.JSContextRef, _: js.JSObjectRef, _: js.JSStringRef, _: js.ExceptionRef, ) js.JSValueRef { - return ZigString.init(Properties.UTF8.follow).toValueGC(VirtualMachine.vm.global).asRef(); + return ZigString.init(Properties.UTF8.follow).toValueGC(ctx.ptr()).asRef(); } pub fn getReferrer( this: *Request, - _: js.JSContextRef, + ctx: js.JSContextRef, _: js.JSObjectRef, _: js.JSStringRef, _: js.ExceptionRef, ) js.JSValueRef { if (this.request_context.header("Referrer")) |referrer| { - return ZigString.init(referrer).toValueGC(VirtualMachine.vm.global).asRef(); + return ZigString.init(referrer).toValueGC(ctx.ptr()).asRef(); } else { - return ZigString.init("").toValueGC(VirtualMachine.vm.global).asRef(); + return ZigString.init("").toValueGC(ctx.ptr()).asRef(); } } pub fn getReferrerPolicy( _: *Request, - _: js.JSContextRef, + ctx: js.JSContextRef, _: js.JSObjectRef, _: js.JSStringRef, _: js.ExceptionRef, ) js.JSValueRef { - return ZigString.init("").toValueGC(VirtualMachine.vm.global).asRef(); + return ZigString.init("").toValueGC(ctx.ptr()).asRef(); } pub fn getUrl( this: *Request, @@ -1775,6 +1793,7 @@ pub const FetchEvent = struct { exception: js.ExceptionRef, ) js.JSValueRef { if (this.request_context.has_called_done) return js.JSValueMakeUndefined(ctx); + var globalThis = ctx.ptr(); // A Response or a Promise that resolves to a Response. Otherwise, a network error is returned to Fetch. if (arguments.len == 0 or !Response.Class.loaded or !js.JSValueIsObject(ctx, arguments[0])) { @@ -1786,15 +1805,15 @@ pub const FetchEvent = struct { var arg = arguments[0]; if (!js.JSValueIsObjectOfClass(ctx, arg, Response.Class.ref)) { - this.pending_promise = this.pending_promise orelse JSInternalPromise.resolvedPromise(VirtualMachine.vm.global, JSValue.fromRef(arguments[0])); + this.pending_promise = this.pending_promise orelse JSInternalPromise.resolvedPromise(globalThis, JSValue.fromRef(arguments[0])); } if (this.pending_promise) |promise| { - var status = promise.status(VirtualMachine.vm.global.vm()); + var status = promise.status(globalThis.vm()); if (status == .Pending) { VirtualMachine.vm.tick(); - status = promise.status(VirtualMachine.vm.global.vm()); + status = promise.status(globalThis.vm()); } switch (status) { @@ -1806,13 +1825,13 @@ pub const FetchEvent = struct { this.onPromiseRejectionCtx, error.PromiseRejection, this, - promise.result(VirtualMachine.vm.global.vm()), + promise.result(globalThis.vm()), ); return js.JSValueMakeUndefined(ctx); }, } - arg = promise.result(VirtualMachine.vm.global.vm()).asRef(); + arg = promise.result(ctx.ptr().vm()).asRef(); } if (!js.JSValueIsObjectOfClass(ctx, arg, Response.Class.ref)) { |