Lightpanda: the headless browser designed for AI and automation
bidi: basic script support
Karl Seguina97e8ec43c3d
diff --git a/src/browser/js/Inspector.zig b/src/browser/js/Inspector.zigindex 7190260fd..bfedebbb5 100644--- a/src/browser/js/Inspector.zig+++ b/src/browser/js/Inspector.zig@@ -367,13 +367,7 @@ pub fn getTaggedOpaque(value: *const v8.Value) ?*TaggedOpaque {if (!v8.v8__Value__IsObject(value)) {return null;}- const internal_field_count = v8.v8__Object__InternalFieldCount(value);- if (internal_field_count == 0) {- return null;- }-- const tao_ptr = v8.v8__Object__GetAlignedPointerFromInternalField(value, 0).?;- return @ptrCast(@alignCast(tao_ptr));+ return TaggedOpaque.fromObject(@ptrCast(value));}fn cZigStringToString(s: v8.CZigString) ?[]const u8 {diff --git a/src/browser/js/Local.zig b/src/browser/js/Local.zigindex 528e50bbb..39ee9f44a 100644--- a/src/browser/js/Local.zig+++ b/src/browser/js/Local.zig@@ -88,6 +88,14 @@ pub fn newDate(self: *const Local, time_ms: f64) !js.Value {return .{ .local = self, .handle = handle };}+// StringToBigInt semantics: arbitrary precision, sign-aware, and it never+// consults the page's globals. Fails on non-numeric digits.+pub fn newBigInt(self: *const Local, digits: []const u8) !js.Value {+ const str: *const v8.Value = @ptrCast(self.isolate.initStringHandle(digits));+ const handle = v8.v8__Value__ToBigInt(str, self.handle) orelse return error.JsException;+ return .{ .local = self, .handle = @ptrCast(handle) };+}+pub fn newNumber(self: *const Local, f: f64) !js.Value {return .{.local = self,diff --git a/src/browser/js/TaggedOpaque.zig b/src/browser/js/TaggedOpaque.zigindex 092a08542..3d32b1da1 100644--- a/src/browser/js/TaggedOpaque.zig+++ b/src/browser/js/TaggedOpaque.zig@@ -96,41 +96,41 @@ pub fn fromJS(comptime R: type, js_obj_handle: *const v8.Object) !R {return @constCast(@as(*const T, &.{}));}- const internal_field_count = v8.v8__Object__InternalFieldCount(js_obj_handle);- // if it isn't an empty struct, then the v8.Object should have an- // InternalFieldCount > 0, since our toa pointer should be embedded- // at index 0 of the internal field count.- if (internal_field_count == 0) {- return error.InvalidArgument;- }+ const tao = fromObject(js_obj_handle) orelse return error.InvalidArgument;+ return tao.as(T) orelse error.InvalidArgument;+}- if (!bridge.JsApiLookup.has(JsApi)) {- @compileError("unknown Zig type: " ++ @typeName(R));+pub fn fromObject(js_obj_handle: *const v8.Object) ?*TaggedOpaque {+ if (v8.v8__Object__InternalFieldCount(js_obj_handle) == 0) {+ return null;}-- const tao_ptr = v8.v8__Object__GetAlignedPointerFromInternalField(js_obj_handle, 0) orelse return error.InvalidArgument;- // A wrapped object always embeds an aligned TaggedOpaque pointer. An- // unaligned value is a leftover v8 tagged value: the object was created- // from our template but never mapped to a Zig instance (e.g. a custom- // element whose constructor threw).+ const tao_ptr = v8.v8__Object__GetAlignedPointerFromInternalField(js_obj_handle, 0) orelse return null;if (@intFromPtr(tao_ptr) % @alignOf(TaggedOpaque) != 0) {- return error.InvalidArgument;+ return null;+ }+ return @ptrCast(@alignCast(tao_ptr));+}++// The instance as a T: its own type, or one it inherits from. Null otherwise.+pub fn as(self: *const TaggedOpaque, comptime T: type) ?*T {+ const JsApi = bridge.Struct(T).JsApi;+ if (!bridge.JsApiLookup.has(JsApi)) {+ @compileError("unknown Zig type: " ++ @typeName(T));}- const tao: *TaggedOpaque = @ptrCast(@alignCast(tao_ptr));const expected_type_index = bridge.JsApiLookup.getId(JsApi);- const prototype_chain = tao.prototype_chain[0..tao.prototype_len];+ const prototype_chain = self.prototype_chain[0..self.prototype_len];if (prototype_chain[0].index == expected_type_index) {- return @ptrCast(@alignCast(tao.value));+ return @ptrCast(@alignCast(self.value));}// Ok, let's walk up the chain- var ptr = @intFromPtr(tao.value);+ var ptr = @intFromPtr(self.value);for (prototype_chain[1..]) |proto| {ptr -= proto.offset;if (proto.index == expected_type_index) {return @ptrFromInt(ptr);}}- return error.InvalidArgument;+ return null;}diff --git a/src/browser/js/Value.zig b/src/browser/js/Value.zigindex 1d17cebd5..3e2f23676 100644--- a/src/browser/js/Value.zig+++ b/src/browser/js/Value.zig@@ -124,10 +124,55 @@ pub fn isArrayBuffer(self: Value) bool {return v8.v8__Value__IsArrayBuffer(self.handle);}+pub fn taggedOpaque(self: Value) ?*const TaggedOpaque {+ // caller must ensure self.isObject()+ return TaggedOpaque.fromObject(@ptrCast(self.handle));+}++// === for JS values: identity for objects, value equality for primitives.+pub fn strictEquals(self: Value, other: Value) bool {+ return v8.v8__Value__StrictEquals(self.handle, other.handle);+}+pub fn isDate(self: Value) bool {return v8.v8__Value__IsDate(self.handle);}+pub fn dateValue(self: Value) f64 {+ if (comptime lp.IS_DEBUG) {+ std.debug.assert(self.isDate());+ }+ return v8.v8__Date__ValueOf(@ptrCast(self.handle));+}++pub fn isMap(self: Value) bool {+ return v8.v8__Value__IsMap(self.handle);+}++pub fn isSet(self: Value) bool {+ return v8.v8__Value__IsSet(self.handle);+}++pub fn isWeakMap(self: Value) bool {+ return v8.v8__Value__IsWeakMap(self.handle);+}++pub fn isWeakSet(self: Value) bool {+ return v8.v8__Value__IsWeakSet(self.handle);+}++pub fn isRegExp(self: Value) bool {+ return v8.v8__Value__IsRegExp(self.handle);+}++pub fn isProxy(self: Value) bool {+ return v8.v8__Value__IsProxy(self.handle);+}++pub fn isGeneratorObject(self: Value) bool {+ return v8.v8__Value__IsGeneratorObject(self.handle);+}+pub fn isUint8Array(self: Value) bool {return v8.v8__Value__IsUint8Array(self.handle);}@@ -514,11 +559,7 @@ const CloneDelegate = struct {blk: {const obj = object orelse break :blk;- if (v8.v8__Object__InternalFieldCount(obj) == 0) {- break :blk;- }- const tao_ptr = v8.v8__Object__GetAlignedPointerFromInternalField(obj, 0) orelse break :blk;- const tao: *TaggedOpaque = @ptrCast(@alignCast(tao_ptr));+ const tao = TaggedOpaque.fromObject(obj) orelse break :blk;const prototype_chain = tao.prototype_chain[0..tao.prototype_len];if (writeCloneable(ctx, prototype_chain[0].index, tao.value)) |result| {diff --git a/src/browser/js/js.zig b/src/browser/js/js.zigindex c366ce849..b6d5c2983 100644--- a/src/browser/js/js.zig+++ b/src/browser/js/js.zig@@ -36,6 +36,7 @@ pub const Identity = @import("Identity.zig");pub const Context = @import("Context.zig");pub const Execution = @import("Execution.zig");pub const Local = @import("Local.zig");+pub const TaggedOpaque = @import("TaggedOpaque.zig");pub const Inspector = @import("Inspector.zig");pub const Snapshot = @import("Snapshot.zig");pub const Platform = @import("Platform.zig");@@ -477,7 +478,7 @@ pub export fn v8_inspector__Client__IMPL__descriptionForValueSubtype(test "TaggedAnyOpaque" {// If we grow this, fine, but it should be a conscious decision- try std.testing.expectEqual(24, @sizeOf(@import("TaggedOpaque.zig")));+ try std.testing.expectEqual(24, @sizeOf(TaggedOpaque));}// Every finalizable instance of Zig gets 1 FinalizerCallback registered in thediff --git a/src/browser/tests/bidi/values.html b/src/browser/tests/bidi/values.htmlnew file mode 100644index 000000000..f7ba5bc34--- /dev/null+++ b/src/browser/tests/bidi/values.html@@ -0,0 +1,3 @@+<!DOCTYPE html>+<title>bidi values</title>+<div id=main class="a b" data-x="1"><p>hello</p></div>diff --git a/src/datetime.zig b/src/datetime.zigindex 678eff453..1dccb8095 100644--- a/src/datetime.zig+++ b/src/datetime.zig@@ -506,13 +506,25 @@ pub const DateTime = struct {}}+ // Date.prototype.toISOString's form: always exactly three fractional+ // digits, where format elides them when zero and widens to micros.+ pub fn formatMillis(self: DateTime, writer: *std.Io.Writer) !void {+ var buf: [28]u8 = undefined;+ const n = self.bufWriteWith(&buf, .millis);+ try writer.writeAll(buf[0..n]);+ }+fn bufWrite(self: DateTime, buf: []u8) usize {+ return self.bufWriteWith(buf, .auto);+ }++ fn bufWriteWith(self: DateTime, buf: []u8, precision: FractionPrecision) usize {const date_n = writeDate(buf, self.date());buf[date_n] = 'T';const time_start = date_n + 1;- const time_n = writeTime(buf[time_start..], self.time());+ const time_n = writeTimeWith(buf[time_start..], self.time(), precision);const time_stop = time_start + time_n;buf[time_stop] = 'Z';@@ -558,7 +570,18 @@ fn writeDate(into: []u8, date: Date) u8 {return if (year < 0) 11 else 10;}+const FractionPrecision = enum {+ // none when zero, else millis if exact, else micros+ auto,+ // always three digits, truncating micros+ millis,+};+fn writeTime(into: []u8, time: Time) u8 {+ return writeTimeWith(into, time, .auto);+}++fn writeTimeWith(into: []u8, time: Time, precision: FractionPrecision) u8 {into[0..2].* = paddingTwoDigits(time.hour);into[2] = ':';into[3..5].* = paddingTwoDigits(time.min);@@ -566,11 +589,11 @@ fn writeTime(into: []u8, time: Time) u8 {into[6..8].* = paddingTwoDigits(time.sec);const micros = time.micros;- if (micros == 0) {+ if (micros == 0 and precision == .auto) {return 8;}- if (@rem(micros, 1000) == 0) {+ if (precision == .millis or @rem(micros, 1000) == 0) {into[8] = '.';_ = std.fmt.printInt(into[9..12], micros / 1000, 10, .lower, .{ .width = 3, .fill = '0' });return 12;@@ -1749,6 +1772,22 @@ test "DateTime: format" {}}+test "DateTime: formatMillis" {+ const cases = [_]struct { micros: u32, expected: []const u8 }{+ .{ .micros = 0, .expected = "2023-05-22T08:09:10.000Z" },+ .{ .micros = 12, .expected = "2023-05-22T08:09:10.000Z" },+ .{ .micros = 1000, .expected = "2023-05-22T08:09:10.001Z" },+ .{ .micros = 123456, .expected = "2023-05-22T08:09:10.123Z" },+ .{ .micros = 999999, .expected = "2023-05-22T08:09:10.999Z" },+ };+ for (cases) |case| {+ var buf: [30]u8 = undefined;+ var w: std.Io.Writer = .fixed(&buf);+ try (try DateTime.initUTC(2023, 5, 22, 8, 9, 10, case.micros)).formatMillis(&w);+ try testing.expectString(case.expected, w.buffered());+ }+}+test "DateTime: order" {{const a = try DateTime.initUTC(2023, 11, 23, 19, 17, 22, 101002);diff --git a/src/server/bidi/BiDi.zig b/src/server/bidi/BiDi.zigindex 69af4a11a..917b27626 100644--- a/src/server/bidi/BiDi.zig+++ b/src/server/bidi/BiDi.zig@@ -19,17 +19,22 @@const std = @import("std");const App = @import("../../App.zig");+const uuidv4 = @import("../../id.zig").uuidv4;const Server = @import("../Server.zig");const Browser = @import("../../browser/Browser.zig");const Session = @import("../../browser/Session.zig");const Notification = @import("../../Notification.zig");+const NodeRegistry = @import("../../NodeRegistry.zig");+const Driver = @import("../Driver.zig");const Connection = @import("../Connection.zig");+const remote_value = @import("remote_value.zig");const browsing_context = @import("browsing_context.zig");const posix = std.posix;+const Allocator = std.mem.Allocator;const BiDi = @This();@@ -55,6 +60,12 @@ session: *Session,notification: *Notification,context: ?browsing_context.Context = null,+// Issues the script module's sharedIds+node_registry: NodeRegistry,++// Values the client owns via `resultOwnership: "root"`+handles: remote_value.Handles,+subscriptions: std.ArrayList(Subscription) = .empty,const Subscription = struct {@@ -76,6 +87,8 @@ pub fn init(self: *BiDi, app: *App, socket: posix.socket_t) !void {.browser = undefined,.session = undefined,.notification = undefined,+ .node_registry = .init(allocator),+ .handles = .{ .allocator = allocator },.message_arena = std.heap.ArenaAllocator.init(allocator),.session_arena = std.heap.ArenaAllocator.init(allocator),};@@ -104,7 +117,11 @@ pub fn init(self: *BiDi, app: *App, socket: posix.socket_t) !void {pub fn deinit(self: *BiDi) void {self.notification.unregisterAll(self);++ self.handles.deinit();self.browser.closeSession();++ self.node_registry.deinit();self.notification.deinit();self.browser.deinit();self.conn.deinit();@@ -112,6 +129,14 @@ pub fn deinit(self: *BiDi) void {self.session_arena.deinit();}+pub fn resetRealm(self: *BiDi) void {+ self.handles.releaseAll();+ self.node_registry.reset();+ if (self.context) |*ctx| {+ uuidv4(&ctx.realm_id);+ }+}+// Dispatch a single BiDi frame from the inbox. Unlike CDP, frames aren't// parsed on the Network thread, so `data` is the raw JSON.pub fn onMessage(self: *BiDi, data: []const u8) anyerror!void {@@ -135,7 +160,7 @@ pub fn onMessage(self: *BiDi, data: []const u8) anyerror!void {return self.sendError(id, "invalid argument", "missing command method");};- self.dispatch(id, method, data) catch |err| switch (err) {+ self.dispatch(arena, id, method, data) catch |err| switch (err) {error.UnknownCommand => try self.sendError(id, "unknown command", method),// Command.params already answered the client.error.InvalidParams => {},@@ -144,12 +169,13 @@ pub fn onMessage(self: *BiDi, data: []const u8) anyerror!void {}// A BiDi method is always "<module>.<command>".-fn dispatch(self: *BiDi, id: u64, method: []const u8, data: []const u8) !void {+fn dispatch(self: *BiDi, arena: Allocator, id: u64, method: []const u8, data: []const u8) !void {const i = std.mem.indexOfScalar(u8, method, '.') orelse {return error.UnknownCommand;};const module = std.meta.stringToEnum(enum {session,+ script,browser,browsingContext,}, method[0..i]) orelse return error.UnknownCommand;@@ -164,11 +190,13 @@ fn dispatch(self: *BiDi, id: u64, method: []const u8, data: []const u8) !void {.id = id,.bidi = self,.json = data,+ .arena = arena,.action = method[i + 1 ..],};switch (module) {.session => return @import("session.zig").processMessage(&cmd),+ .script => return @import("script.zig").processMessage(&cmd),.browser => return @import("browser.zig").processMessage(&cmd),.browsingContext => return browsing_context.processMessage(&cmd),}@@ -179,6 +207,9 @@ fn dispatch(self: *BiDi, id: u64, method: []const u8, data: []const u8) !void {pub const Command = struct {bidi: *BiDi,+ // The message_arena; valid for the lifetime of the command.+ arena: Allocator,+// Echoed back in the response.id: u64,@@ -192,8 +223,7 @@ pub const Command = struct {// error.InvalidParams when the message has no params or they don't// match T, so callers can just `try`. onMessage swallows that error.pub fn params(self: *const Command, comptime T: type) !T {- const arena = self.bidi.message_arena.allocator();- const wrapper = std.json.parseFromSliceLeaky(struct { params: T }, arena, self.json, .{+ const wrapper = std.json.parseFromSliceLeaky(struct { params: T }, self.arena, self.json, .{.ignore_unknown_fields = true,}) catch {try self.sendError("invalid argument", "invalid params");diff --git a/src/server/bidi/browser.zig b/src/server/bidi/browser.zigindex b60078593..6e5053790 100644--- a/src/server/bidi/browser.zig+++ b/src/server/bidi/browser.zig@@ -22,14 +22,24 @@ const BiDi = @import("BiDi.zig");pub fn processMessage(cmd: *const BiDi.Command) !void {const command = std.meta.stringToEnum(enum {+ close,getUserContexts,}, cmd.action) orelse return error.UnknownCommand;switch (command) {+ .close => return close(cmd),.getUserContexts => return getUserContexts(cmd),}}+fn close(cmd: *const BiDi.Command) !void {+ try cmd.sendResult(struct {}{});++ const browser = &cmd.bidi.browser;+ const arena = try browser.arena_pool.acquire(.tiny, "bidi browser close");+ browser.http_client.inbox.push(arena, .close);+}+fn getUserContexts(cmd: *const BiDi.Command) !void {return cmd.sendResult(.{.userContexts = &[_]struct { userContext: []const u8 }{diff --git a/src/server/bidi/browsing_context.zig b/src/server/bidi/browsing_context.zigindex 1be63fe05..c21807559 100644--- a/src/server/bidi/browsing_context.zig+++ b/src/server/bidi/browsing_context.zig@@ -38,6 +38,10 @@ pub const Context = struct {// ones the page itself initiates.navigation_id: [36]u8,+ // The window realm's id, reported by the script module. A navigation+ // means a new document and so a new realm.+ realm_id: [36]u8,+// A navigate command whose `wait` hasn't been satisfied yet.pending_navigate: ?PendingNavigate = null,};@@ -89,10 +93,12 @@ fn create(cmd: *const BiDi.Command) !void {var ctx = Context{.id = undefined,+ .realm_id = undefined,.frame_id = page.frame_id,.navigation_id = undefined,};uuidv4(&ctx.id);+ uuidv4(&ctx.realm_id);uuidv4(&ctx.navigation_id);bidi.context = ctx;@@ -178,9 +184,8 @@ fn close(cmd: *const BiDi.Command) !void {const ctx_id = ctx.id;// the frame's url doesn't survive closePage- const arena = bidi.message_arena.allocator();const url: []const u8 = if (bidi.session.currentFrame()) |frame|- try arena.dupe(u8, frame.url)+ try cmd.arena.dupe(u8, frame.url)else"about:blank";@@ -198,7 +203,7 @@ fn close(cmd: *const BiDi.Command) !void {return cmd.sendResult(struct {}{});}-fn requireContext(cmd: *const BiDi.Command, context: []const u8) !?*Context {+pub fn requireContext(cmd: *const BiDi.Command, context: []const u8) !?*Context {if (cmd.bidi.context) |*ctx| {if (std.mem.eql(u8, &ctx.id, context)) {return ctx;@@ -230,15 +235,29 @@ fn rejectPending(bidi: *BiDi, ctx: *Context, message: []const u8) !void {pub fn registerNotifications(bidi: *BiDi) !void {const notification = bidi.notification;try notification.register(.frame_loaded, bidi, onFrameLoaded);+ try notification.register(.frame_remove, bidi, onFrameRemove);try notification.register(.frame_navigate, bidi, onFrameNavigate);try notification.register(.frame_navigate_failed, bidi, onFrameNavigateFailed);try notification.register(.frame_dom_content_loaded, bidi, onFrameDOMContentLoaded);}+// The page whose nodes and persisted values these belong to is going away.+fn onFrameRemove(ptr: *anyopaque, _: Notification.FrameRemove) !void {+ const bidi: *BiDi = @ptrCast(@alignCast(ptr));+ bidi.resetRealm();+}+fn onFrameNavigate(ptr: *anyopaque, msg: *const Notification.FrameNavigate) !void {const bidi: *BiDi = @ptrCast(@alignCast(ptr));const ctx = rootContext(bidi, msg.frame_id) orelse return;+ if (msg.is_pending_root == false) {+ bidi.resetRealm();+ } else {+ // pending root keeps its old page and thus its sharedIds and handles+ // reachable until frameRemove commits the replacement.+ }+uuidv4(&ctx.navigation_id);try bidi.sendEvent("browsingContext.navigationStarted", .{.context = &ctx.id,diff --git a/src/server/bidi/remote_value.zig b/src/server/bidi/remote_value.zignew file mode 100644index 000000000..405a98c09--- /dev/null+++ b/src/server/bidi/remote_value.zig@@ -0,0 +1,721 @@+// Copyright (C) 2023-2026 Lightpanda (Selecy SAS)+//+// Francis Bouvier <[email protected]>+// Pierre Tachoire <[email protected]>+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as+// published by the Free Software Foundation, either version 3 of the+// License, or (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.+// https://w3c.github.io/webdriver-bidi/#type-script-RemoteValue++const std = @import("std");+const lp = @import("lightpanda");++const js = @import("../../browser/js/js.zig");+const Frame = @import("../../browser/Frame.zig");+const Node = @import("../../browser/webapi/Node.zig");+const Window = @import("../../browser/webapi/Window.zig");+const NodeList = @import("../../browser/webapi/collections/NodeList.zig");+const HTMLCollection = @import("../../browser/webapi/collections/HTMLCollection.zig");+const NodeRegistry = @import("../../NodeRegistry.zig");++const BiDi = @import("BiDi.zig");++const log = lp.log;+const Allocator = std.mem.Allocator;++pub const Remote = struct {+ body: Body,++ // Only set when the command asked for resultOwnership: "root".+ handle: ?[]const u8 = null,++ pub fn jsonStringify(self: *const Remote, w: anytype) error{WriteFailed}!void {+ try w.beginObject();++ try w.objectField("type");+ try w.write(self.body.typeName());++ switch (self.body) {+ .undefined, .null, .other => {},+ .boolean => |v| {+ try w.objectField("value");+ try w.write(v);+ },+ .string, .bigint, .date => |v| {+ try w.objectField("value");+ try w.write(v);+ },+ .regexp => |v| {+ try w.objectField("value");+ try w.write(v);+ },+ .number => |v| {+ try w.objectField("value");+ switch (v) {+ .special => |s| try w.write(s),+ .integer => |i| try w.write(i),+ .float => |f| try w.write(f),+ }+ },+ .array, .nodelist, .htmlcollection => |items| {+ try w.objectField("value");+ try w.beginArray();+ for (items) |*item| {+ try item.jsonStringify(w);+ }+ try w.endArray();+ },+ .object => |properties| {+ // An object's value is a list of [key, value] pairs, not a+ // JSON object: BiDi keys aren't necessarily strings.+ try w.objectField("value");+ try w.beginArray();+ for (properties) |*property| {+ try w.beginArray();+ try w.write(property.name);+ try property.value.jsonStringify(w);+ try w.endArray();+ }+ try w.endArray();+ },+ .node => |*v| try v.writeNode(w),+ }++ if (self.handle) |handle| {+ try w.objectField("handle");+ try w.write(handle);+ }++ try w.endObject();+ }++ const Body = union(enum) {+ undefined,+ null,+ boolean: bool,+ number: Number,+ string: []const u8,+ bigint: []const u8,+ date: []const u8,+ regexp: RegExp,+ array: []const Remote,+ nodelist: []const Remote,+ htmlcollection: []const Remote,+ object: []const Property,+ node: NodeValue,+ other: []const u8,++ fn typeName(self: *const Body) []const u8 {+ return switch (self.*) {+ .other => |name| name,+ else => @tagName(self.*),+ };+ }+ };+};++const Number = union(enum) {+ float: f64,+ integer: i64,+ special: enum { NaN, Infinity, @"-Infinity", @"-0" },++ fn from(value: f64) Number {+ if (std.math.isNan(value)) {+ return .{ .special = .NaN };+ }+ if (std.math.isPositiveInf(value)) {+ return .{ .special = .Infinity };+ }+ if (std.math.isNegativeInf(value)) {+ return .{ .special = .@"-Infinity" };+ }+ if (value == 0 and std.math.signbit(value)) {+ return .{ .special = .@"-0" };+ }++ const max_safe_integer = 9007199254740991;+ if (@trunc(value) == value and @abs(value) <= max_safe_integer) {+ // Whole numbers go out as JSON integers, avoids 5e0 for 5.0+ return .{ .integer = @intFromFloat(value) };+ }+ return .{ .float = value };+ }+};++pub const Property = struct {+ name: []const u8,+ value: Remote,+};++pub const RegExp = struct {+ flags: []const u8,+ pattern: []const u8,+};++pub const Attribute = struct {+ name: []const u8,+ value: []const u8,+};++pub const NodeValue = struct {+ node_type: u8,+ shared_id: []const u8,+ child_node_count: usize,+ local_name: ?[]const u8 = null,+ namespace_uri: ?[]const u8 = null,+ node_value: ?[]const u8 = null,+ attributes: ?[]const Attribute = null,+ children: ?[]const Remote = null,++ fn writeNode(node: *const NodeValue, w: anytype) error{WriteFailed}!void {+ try w.objectField("sharedId");+ try w.write(node.shared_id);++ try w.objectField("value");+ try w.beginObject();++ try w.objectField("nodeType");+ try w.write(node.node_type);++ try w.objectField("childNodeCount");+ try w.write(node.child_node_count);++ if (node.local_name) |v| {+ try w.objectField("localName");+ try w.write(v);+ }+ if (node.namespace_uri) |v| {+ try w.objectField("namespaceURI");+ try w.write(v);+ }+ if (node.node_value) |v| {+ try w.objectField("nodeValue");+ try w.write(v);+ }+ if (node.attributes) |attributes| {+ try w.objectField("attributes");+ try w.beginObject();+ for (attributes) |attribute| {+ try w.objectField(attribute.name);+ try w.write(attribute.value);+ }+ try w.endObject();+ }+ if (node.children) |children| {+ try w.objectField("children");+ try w.beginArray();+ for (children) |*child| {+ try child.jsonStringify(w);+ }+ try w.endArray();+ }++ try w.endObject();+ }+};++pub const Handles = struct {+ next_id: u32 = 1,+ allocator: Allocator,+ // id => global,the id is the handleId that client can send back+ map: std.AutoHashMapUnmanaged(u32, js.Value.Global) = .empty,++ pub fn deinit(self: *Handles) void {+ self.releaseAll();+ self.map.deinit(self.allocator);+ }++ pub fn releaseAll(self: *Handles) void {+ var it = self.map.valueIterator();+ while (it.next()) |global| {+ global.deinit();+ }+ self.map.clearRetainingCapacity();+ }++ pub fn add(self: *Handles, value: js.Value) !u32 {+ const global = try value.persist();+ errdefer global.deinit();++ const id = self.next_id;+ try self.map.putNoClobber(self.allocator, id, global);+ self.next_id = id + 1;+ return id;+ }++ pub fn get(self: *const Handles, id: u32) ?js.Value.Global {+ return self.map.get(id);+ }++ pub fn release(self: *Handles, id: u32) void {+ const entry = self.map.fetchRemove(id) orelse return;+ entry.value.deinit();+ }+};++pub const Options = struct {+ // by default, a node serializs without its children+ max_dom_depth: ?u32 = 0,++ // but an object serializes without limit (all the way down)+ max_object_depth: ?u32 = null,++ // when resultOwnership == "root", we'll persist the value in our handles+ // lookup+ own_root: bool = false,+};++pub const Serializer = struct {+ arena: Allocator,+ frame: *Frame,+ local: *const js.Local,+ registry: *NodeRegistry,+ handles: *Handles,+ opts: Options,++ // The containers we're currently inside, so a cycle collapses to the bare+ // type instead of recursing forever (maxObjectDepth defaults to unlimited).+ // Locals, not globals: everything happens inside the caller's scope.+ seen: std.ArrayList(js.Object) = .empty,++ pub fn init(cmd: *const BiDi.Command, frame: *Frame, local: *const js.Local, opts: Options) Serializer {+ return .{+ .frame = frame,+ .local = local,+ .arena = cmd.arena,+ .handles = &cmd.bidi.handles,+ .registry = &cmd.bidi.node_registry,+ .opts = opts,+ };+ }++ pub fn run(self: *Serializer, value: js.Value) !Remote {+ return self.remote(value, 0, self.opts.own_root);+ }++ const Error = error{+ OutOfMemory,+ InvalidArgument,+ TypeError,+ JsException,+ ExecutionTerminated,+ MethodNotFound,+ };++ fn remote(self: *Serializer, value: js.Value, depth: u32, own: bool) Error!Remote {+ const handle: ?[]const u8 = if (own and value.isObject()) blk: {+ const id = try self.handles.add(value);+ break :blk try std.fmt.allocPrint(self.arena, "{d}", .{id});+ } else null;++ return .{ .handle = handle, .body = try self.body(value, depth) };+ }++ // Ordered by how often each comes back from a driver: primitives, then+ // nodes and arrays, with the exotics probed last so a plain object doesn't+ // pay for them.+ fn body(self: *Serializer, value: js.Value, depth: u32) !Remote.Body {+ if (value.isUndefined()) {+ return .undefined;+ }+ if (value.isString() != null) {+ return .{ .string = try value.toStringSliceWithAlloc(self.arena) };+ }+ if (value.isNumber()) {+ return .{ .number = .from(try value.toF64()) };+ }+ if (value.isBoolean()) {+ return .{ .boolean = value.toBool() };+ }+ if (value.isNull()) {+ return .null;+ }+ if (value.isBigInt()) {+ return .{ .bigint = try value.toStringSliceWithAlloc(self.arena) };+ }+ if (value.isObject() == false) {+ // A symbol. BiDi has no type for one.+ return .{ .other = "object" };+ }++ if (value.taggedOpaque()) |tao| {+ return self.platform(tao, depth);+ }++ const object = value.toObject();+ if (value.isArray()) {+ if (self.isTooDeep(depth) or self.isSeen(object)) {+ return .{ .other = "array" };+ }+ return .{ .array = try self.items(value.toArray(), object, depth) };+ }++ if (value.isFunction()) {+ return .{ .other = "function" };+ }+ if (value.isPromise()) {+ return .{ .other = "promise" };+ }+ if (value.isNativeError()) {+ return .{ .other = "error" };+ }+ if (value.isDate()) {+ return .{ .date = try self.date(value) };+ }+ if (value.isRegExp()) {+ return .{ .regexp = .{+ .pattern = try (try object.get("source")).toStringSliceWithAlloc(self.arena),+ .flags = try (try object.get("flags")).toStringSliceWithAlloc(self.arena),+ } };+ }+ if (value.isTypedArray()) {+ return .{ .other = "typedarray" };+ }+ if (value.isArrayBuffer()) {+ return .{ .other = "arraybuffer" };+ }+ if (bareType(value)) |name| {+ return .{ .other = name };+ }++ if (self.isTooDeep(depth) or self.isSeen(object)) {+ return .{ .other = "object" };+ }+ return .{ .object = try self.properties(object, depth) };+ }++ // One of our objects. The spec only cares about four, the rest are opaque.+ fn platform(self: *Serializer, tao: *const js.TaggedOpaque, depth: u32) !Remote.Body {+ if (tao.as(Node)) |dom_node| {+ return .{ .node = try self.node(dom_node, 0) };+ }++ if (tao.as(Window)) |_| {+ return .{ .other = "window" };+ }++ if (tao.as(NodeList)) |list| {+ if (self.isTooDeep(depth)) {+ return .{ .other = "nodelist" };+ }+ const frame = self.frame;+ const nodes = try self.arena.alloc(Remote, try list.length(frame));+ for (nodes, 0..) |*item, i| {+ const dom_node = (try list.getAtIndex(i, frame)) orelse unreachable;+ item.* = .{ .body = .{ .node = try self.node(dom_node, 0) } };+ }+ return .{ .nodelist = nodes };+ }++ if (tao.as(HTMLCollection)) |collection| {+ if (self.isTooDeep(depth)) {+ return .{ .other = "htmlcollection" };+ }+ const frame = self.frame;+ const nodes = try self.arena.alloc(Remote, collection.length(frame));+ for (nodes, 0..) |*item, i| {+ const element = collection.getAtIndex(i, frame) orelse unreachable;+ item.* = .{ .body = .{ .node = try self.node(element.asNode(), 0) } };+ }+ return .{ .htmlcollection = nodes };+ }++ return .{ .other = "object" };+ }++ fn items(self: *Serializer, array: js.Array, object: js.Object, depth: u32) ![]const Remote {+ try self.see(object);+ defer self.unsee();++ const next_depth = depth + 1;+ const values = try self.arena.alloc(Remote, array.len());+ for (values, 0..) |*value, i| {+ value.* = try self.remote(try array.get(@intCast(i)), next_depth, false);+ }+ return values;+ }++ fn properties(self: *Serializer, object: js.Object, depth: u32) ![]const Property {+ try self.see(object);+ defer self.unsee();++ const next_depth = depth + 1;+ var names = try object.nameIterator();+ var list: std.ArrayList(Property) = try .initCapacity(self.arena, names.count);+ while (try names.next()) |name| {+ const owned = try self.arena.dupe(u8, name);+ const value = try object.get(owned);+ list.appendAssumeCapacity(.{ .name = owned, .value = try self.remote(value, next_depth, false) });+ }+ return list.items;+ }++ fn node(self: *Serializer, dom_node: *Node, dom_depth: u32) !NodeValue {+ const arena = self.arena;+ const registered = try self.registry.register(dom_node);++ var value: NodeValue = .{+ .shared_id = try std.fmt.allocPrint(arena, "{d}", .{registered.id}),+ .node_type = dom_node.getNodeType(),+ .child_node_count = dom_node.getChildrenCount(),+ };++ if (dom_node.is(Node.Element)) |element| {+ value.local_name = element.getLocalName();+ value.namespace_uri = element.getNamespaceURI();++ const entries = element.attributeEntries();+ const attributes = try arena.alloc(Attribute, entries.len);+ for (entries, attributes) |*entry, *attribute| {+ attribute.* = .{ .name = entry.name(), .value = entry.value() };+ }+ value.attributes = attributes;+ } else if (dom_node.getNodeValue()) |node_value| {+ value.node_value = try arena.dupe(u8, node_value.str());+ }++ // Unlike maxObjectDepth, maxDomDepth counts down from the node being+ // serialized, so the default of 0 still yields the node's own+ // properties — just no children.+ const include_children = if (self.opts.max_dom_depth) |max| dom_depth < max else true;+ if (include_children) {+ var children: std.ArrayList(Remote) = .empty;+ var it = dom_node.childrenIterator();+ while (it.next()) |child| {+ try children.append(arena, .{ .body = .{ .node = try self.node(child, dom_depth + 1) } });+ }+ value.children = children.items;+ }++ return value;+ }++ fn date(self: *Serializer, value: js.Value) ![]const u8 {+ const ms = value.dateValue();+ if (std.math.isNan(ms)) {+ return "Invalid Date";+ }++ if (lp.datetime.DateTime.fromUnix(@intFromFloat(ms), .milliseconds)) |dt| {+ var buf: [28]u8 = undefined;+ var w: std.Io.Writer = .fixed(&buf);+ dt.formatMillis(&w) catch unreachable;+ return self.arena.dupe(u8, w.buffered());+ } else |_| {}++ const iso = try value.toObject().callMethod(js.Value, "toISOString", .{});+ return iso.toStringSliceWithAlloc(self.arena);+ }++ fn isSeen(self: *const Serializer, object: js.Object) bool {+ const candidate = object.toValue();+ for (self.seen.items) |ancestor| {+ if (ancestor.toValue().strictEquals(candidate)) {+ return true;+ }+ }+ return false;+ }++ fn see(self: *Serializer, object: js.Object) !void {+ try self.seen.append(self.arena, object);+ }++ fn unsee(self: *Serializer) void {+ _ = self.seen.pop();+ }++ fn isTooDeep(self: *const Serializer, depth: u32) bool {+ return depth >= (self.opts.max_object_depth orelse return false);+ }+};++// Some of these we should serialize fully, but we don't have anything that+// needs them right now.+fn bareType(value: js.Value) ?[]const u8 {+ if (value.isMap()) {+ return "map";+ }++ if (value.isSet()) {+ return "set";+ }++ if (value.isWeakMap()) {+ return "weakmap";+ }++ if (value.isWeakSet()) {+ return "weakset";+ }++ if (value.isProxy()) {+ return "proxy";+ }++ if (value.isGeneratorObject()) {+ return "generator";+ }++ return null;+}++pub const LocalError = error{+ UnsupportedLocalValue,+ NoSuchHandle,+ NoSuchNode,+};++// script.LocalValue -> JS, for callFunction's `arguments` and `this`.+pub fn toJs(+ local: *const js.Local,+ handles: *const Handles,+ registry: *const NodeRegistry,+ value: std.json.Value,+) !js.Value {+ const fields = switch (value) {+ .object => |o| o,+ else => return error.UnsupportedLocalValue,+ };++ // A remote reference carries no `type`, which is how it's told apart from+ // a value.+ if (fields.get("handle")) |handle| {+ const id = parseId(u32, handle) orelse return error.NoSuchHandle;+ const global = handles.get(id) orelse return error.NoSuchHandle;+ return global.local(local);+ }+ if (fields.get("sharedId")) |shared_id| {+ const id = parseId(NodeRegistry.Id, shared_id) orelse return error.NoSuchNode;+ const node = registry.lookup_by_id.get(id) orelse return error.NoSuchNode;+ return local.zigValueToJs(node.dom, .{});+ }++ const name = switch (fields.get("type") orelse return error.UnsupportedLocalValue) {+ .string => |s| s,+ else => return error.UnsupportedLocalValue,+ };+ const tag = std.meta.stringToEnum(enum {+ undefined,+ null,+ string,+ number,+ boolean,+ bigint,+ array,+ object,+ }, name) orelse return error.UnsupportedLocalValue;++ const payload = fields.get("value") orelse .null;+ switch (tag) {+ .undefined => return local.zigValueToJs({}, .{}),+ .null => return local.zigValueToJs(null, .{}),+ .string => return local.zigValueToJs(switch (payload) {+ .string => |s| s,+ else => return error.UnsupportedLocalValue,+ }, .{}),+ .boolean => return local.zigValueToJs(switch (payload) {+ .bool => |b| b,+ else => return error.UnsupportedLocalValue,+ }, .{}),+ .number => return local.newNumber(switch (payload) {+ .integer => |i| @floatFromInt(i),+ .float => |f| f,+ // NaN / Infinity / -0 arrive as strings.+ .string => |s| specialNumber(s) orelse return error.UnsupportedLocalValue,+ else => return error.UnsupportedLocalValue,+ }),+ // A bigint's value is its decimal digits as a string.+ .bigint => {+ const digits = switch (payload) {+ .string => |s| s,+ else => return error.UnsupportedLocalValue,+ };+ return local.newBigInt(digits) catch return error.UnsupportedLocalValue;+ },+ .array => {+ const entries = switch (payload) {+ .array => |a| a.items,+ else => return error.UnsupportedLocalValue,+ };+ var array = local.newArray(@intCast(entries.len));+ for (entries, 0..) |entry, i| {+ const item = try toJs(local, handles, registry, entry);+ if (try array.set(@intCast(i), item, .{}) == false) {+ return error.UnsupportedLocalValue;+ }+ }+ return array.toValue();+ },+ // An object's value is a list of [key, value] pairs.+ .object => {+ const entries = switch (payload) {+ .array => |a| a.items,+ else => return error.UnsupportedLocalValue,+ };+ const object = local.newObject();+ for (entries) |entry| {+ const pair = switch (entry) {+ .array => |p| p.items,+ else => return error.UnsupportedLocalValue,+ };+ if (pair.len != 2) {+ return error.UnsupportedLocalValue;+ }+ const key = objectKey(pair[0]) orelse return error.UnsupportedLocalValue;+ const item = try toJs(local, handles, registry, pair[1]);+ if (try object.set(key, item, .{}) == false) {+ return error.UnsupportedLocalValue;+ }+ }+ return object.toValue();+ },+ }+}++fn objectKey(value: std.json.Value) ?[]const u8 {+ switch (value) {+ .string => |s| return s,+ .object => |fields| {+ // {"type": "string", "value": "over 9000"} is supported+ const name = switch (fields.get("type") orelse return null) {+ .string => |s| s,+ else => return null,+ };+ if (std.mem.eql(u8, name, "string") == false) {+ return null;+ }+ return switch (fields.get("value") orelse return null) {+ .string => |s| s,+ else => null,+ };+ },+ else => return null,+ }+}++fn parseId(comptime T: type, value: std.json.Value) ?T {+ const str = switch (value) {+ .string => |s| s,+ else => return null,+ };+ return std.fmt.parseInt(T, str, 10) catch null;+}++fn specialNumber(name: []const u8) ?f64 {+ if (std.mem.eql(u8, name, "NaN")) return std.math.nan(f64);+ if (std.mem.eql(u8, name, "Infinity")) return std.math.inf(f64);+ if (std.mem.eql(u8, name, "-Infinity")) return -std.math.inf(f64);+ if (std.mem.eql(u8, name, "-0")) return -0.0;+ return null;+}diff --git a/src/server/bidi/script.zig b/src/server/bidi/script.zignew file mode 100644index 000000000..1e625dd71--- /dev/null+++ b/src/server/bidi/script.zig@@ -0,0 +1,1101 @@+// Copyright (C) 2023-2026 Lightpanda (Selecy SAS)+//+// Francis Bouvier <[email protected]>+// Pierre Tachoire <[email protected]>+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as+// published by the Free Software Foundation, either version 3 of the+// License, or (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++const std = @import("std");+const lp = @import("lightpanda");++const js = @import("../../browser/js/js.zig");+const Frame = @import("../../browser/Frame.zig");++const BiDi = @import("BiDi.zig");+const remote_value = @import("remote_value.zig");+const browsing_context = @import("browsing_context.zig");++const log = lp.log;++pub fn processMessage(cmd: *const BiDi.Command) !void {+ const command = std.meta.stringToEnum(enum {+ evaluate,+ callFunction,+ disown,+ }, cmd.action) orelse return error.UnknownCommand;++ switch (command) {+ .evaluate => return evaluate(cmd),+ .callFunction => return callFunction(cmd),+ .disown => return disown(cmd),+ }+}++// Addresses the realm to run in. We only have the one, so a `realm` is+// accepted but a `sandbox` isn't.+const Target = struct {+ context: ?[]const u8 = null,+ realm: ?[]const u8 = null,+ sandbox: ?[]const u8 = null,+};++const SerializationOptions = struct {+ maxDomDepth: ?u32 = 0,+ maxObjectDepth: ?u32 = null,+ includeShadowTree: enum { none, open, all } = .none,+};++const ResultOwnership = enum { root, none };++fn evaluate(cmd: *const BiDi.Command) !void {+ const p = try cmd.params(struct {+ expression: []const u8,+ target: Target,+ awaitPromise: bool = false,+ resultOwnership: ResultOwnership = .none,+ serializationOptions: SerializationOptions = .{},+ userActivation: bool = false,+ });++ const ctx = (try resolveTarget(cmd, p.target)) orelse return;+ const frame = cmd.bidi.session.currentFrame() orelse {+ return cmd.sendError("no such frame", "no frame");+ };++ var ls: js.Local.Scope = undefined;+ frame.js.localScope(&ls);+ defer ls.deinit();++ var try_catch: js.TryCatch = undefined;+ try_catch.init(&ls.local);+ defer try_catch.deinit();++ const value = ls.local.exec(p.expression, "bidi.evaluate") catch |err| {+ return sendException(cmd, ctx, frame, &ls.local, &try_catch, err);+ };++ return settle(cmd, ctx, frame, &ls.local, value, p.awaitPromise, .{+ .own_root = p.resultOwnership == .root,+ .max_dom_depth = p.serializationOptions.maxDomDepth,+ .max_object_depth = p.serializationOptions.maxObjectDepth,+ });+}++fn callFunction(cmd: *const BiDi.Command) !void {+ const p = try cmd.params(struct {+ functionDeclaration: []const u8,+ target: Target,+ awaitPromise: bool = false,+ arguments: []const std.json.Value = &.{},+ this: ?std.json.Value = null,+ resultOwnership: ResultOwnership = .none,+ serializationOptions: SerializationOptions = .{},+ userActivation: bool = false,+ });++ const bidi = cmd.bidi;+ const ctx = (try resolveTarget(cmd, p.target)) orelse return;+ const frame = bidi.session.currentFrame() orelse {+ return cmd.sendError("no such frame", "no frame");+ };++ var ls: js.Local.Scope = undefined;+ frame.js.localScope(&ls);+ defer ls.deinit();++ var try_catch: js.TryCatch = undefined;+ try_catch.init(&ls.local);+ defer try_catch.deinit();++ // functionDeclaration is a function *expression*. Evaluating it+ // parenthesized is what turns it into something callable. \n added incase+ // the functionDeclaration has a trailing comment.+ const arena = cmd.arena;+ const source = try std.fmt.allocPrint(arena, "({s}\n)", .{p.functionDeclaration});+ const declaration = ls.local.exec(source, "bidi.callFunction") catch |err| {+ return sendException(cmd, ctx, frame, &ls.local, &try_catch, err);+ };+ if (declaration.isFunction() == false) {+ return cmd.sendError("invalid argument", "functionDeclaration is not a function");+ }+ const function = js.Function{ .local = &ls.local, .handle = @ptrCast(declaration.handle) };++ const arguments = try arena.alloc(js.Value, p.arguments.len);+ for (p.arguments, arguments) |argument, *js_argument| {+ js_argument.* = (try toJs(cmd, &ls.local, argument)) orelse return;+ }++ // `this` should be undefined when not given+ const this = if (p.this) |t| ((try toJs(cmd, &ls.local, t)) orelse return) else try ls.local.zigValueToJs({}, .{});++ const value = function.callWithThisRethrow(js.Value, this, arguments) catch |err| {+ return sendException(cmd, ctx, frame, &ls.local, &try_catch, err);+ };++ return settle(cmd, ctx, frame, &ls.local, value, p.awaitPromise, .{+ .own_root = p.resultOwnership == .root,+ .max_dom_depth = p.serializationOptions.maxDomDepth,+ .max_object_depth = p.serializationOptions.maxObjectDepth,+ });+}++fn disown(cmd: *const BiDi.Command) !void {+ const p = try cmd.params(struct {+ handles: []const []const u8,+ target: Target,+ });++ if ((try resolveTarget(cmd, p.target)) == null) {+ return;+ }++ // Unknown handles are not an error, just ignore them.+ for (p.handles) |handle| {+ const id = std.fmt.parseInt(u32, handle, 10) catch continue;+ cmd.bidi.handles.release(id);+ }++ return cmd.sendResult(struct {}{});+}++// Answers `cmd` with an EvaluateResultSuccess, resolving the promise first if+// the client asked for it.+fn settle(+ cmd: *const BiDi.Command,+ ctx: *const browsing_context.Context,+ frame: *Frame,+ local: *const js.Local,+ value: js.Value,+ await_promise: bool,+ opts: remote_value.Options,+) !void {+ var result = value;++ if (await_promise and value.isPromise()) {+ const promise = value.toPromise();+ promise.markAsHandled();++ // A promise that only needs the microtask queue — an async function+ // with no real await — settles right here. One waiting on I/O won't:+ // answering that means holding the command open across event-loop+ // ticks, which is machinery we don't have yet.+ local.runMicrotasks();++ switch (promise.state()) {+ .pending => return cmd.sendError("unsupported operation", "awaitPromise on a pending promise"),+ .fulfilled => result = promise.result(),+ .rejected => return sendRejection(cmd, ctx, frame, local, promise.result()),+ }+ }++ const remote = (try serialize(cmd, frame, local, result, opts)) orelse return;+ return cmd.sendResult(.{+ .type = "success",+ .result = remote,+ .realm = &ctx.realm_id,+ });+}++// A JS throw isn't a command failure: the command succeeds and reports the+// exception in its result. The thrown value is always serialized with the+// default options rather than the command's+fn sendException(+ cmd: *const BiDi.Command,+ ctx: *const browsing_context.Context,+ frame: *Frame,+ local: *const js.Local,+ try_catch: *js.TryCatch,+ err: anyerror,+) !void {+ if (err == error.ExecutionTerminated or err == error.OutOfMemory) {+ return err;+ }++ const arena = cmd.arena;+ const caught = try_catch.caughtOrError(arena, err);++ const thrown = try_catch.exceptionValue();+ const exception: remote_value.Remote = blk: {+ const value = thrown orelse break :blk .{ .body = .undefined };+ break :blk (try serialize(cmd, frame, local, value, .{})) orelse return;+ };++ // `text` is the exception stringified ("Error: nope"), not just its message+ const fallback = caught.exception orelse @errorName(err);+ const text = blk: {+ const value = thrown orelse break :blk fallback;+ break :blk value.toStringSliceWithAlloc(arena) catch fallback;+ };++ return sendExceptionDetails(cmd, ctx, exception, text, caught.line);+}++fn sendRejection(+ cmd: *const BiDi.Command,+ ctx: *const browsing_context.Context,+ frame: *Frame,+ local: *const js.Local,+ reason: js.Value,+) !void {+ const arena = cmd.arena;+ const text = reason.toStringSliceWithAlloc(arena) catch "promise rejected";+ const exception = (try serialize(cmd, frame, local, reason, .{})) orelse return;+ return sendExceptionDetails(cmd, ctx, exception, text, null);+}++fn sendExceptionDetails(+ cmd: *const BiDi.Command,+ ctx: *const browsing_context.Context,+ exception: remote_value.Remote,+ text: []const u8,+ line: ?u32,+) !void {+ return cmd.sendResult(.{+ .type = "exception",+ .exceptionDetails = .{+ .text = text,+ .exception = exception,+ .lineNumber = line orelse 0, // required by the spec, even if we don't know it+ .columnNumber = 0, // required by the spec, even if we don't know it+ .stackTrace = .{ .callFrames = &[_]struct {}{} },+ },+ .realm = &ctx.realm_id,+ });+}++fn serialize(+ cmd: *const BiDi.Command,+ frame: *Frame,+ local: *const js.Local,+ value: js.Value,+ opts: remote_value.Options,+) !?remote_value.Remote {+ var serializer = remote_value.Serializer.init(cmd, frame, local, opts);++ return serializer.run(value) catch |err| {+ if (err == error.OutOfMemory) {+ return err;+ }+ log.warn(.bidi, "serialize", .{ .err = err });+ try cmd.sendError("unknown error", "cannot serialize result");+ return null;+ };+}++// returns null when an error response was already sent.+fn toJs(cmd: *const BiDi.Command, local: *const js.Local, value: std.json.Value) !?js.Value {+ const bidi = cmd.bidi;+ return remote_value.toJs(local, &bidi.handles, &bidi.node_registry, value) catch |err| switch (err) {+ error.NoSuchHandle => {+ try cmd.sendError("no such handle", "unknown handle");+ return null;+ },+ error.NoSuchNode => {+ try cmd.sendError("no such node", "unknown sharedId");+ return null;+ },+ error.UnsupportedLocalValue => {+ try cmd.sendError("unsupported operation", "unsupported argument");+ return null;+ },+ else => return err,+ };+}++// Answers the client and returns null when the target doesn't name our one+// context, so callers can `orelse return`.+fn resolveTarget(cmd: *const BiDi.Command, target: Target) !?*browsing_context.Context {+ if (target.sandbox != null) {+ try cmd.sendError("unsupported operation", "sandboxes are not supported");+ return null;+ }++ const bidi = cmd.bidi;+ if (target.context) |context| {+ return browsing_context.requireContext(cmd, context);+ }++ if (target.realm) |realm| {+ if (bidi.context) |*ctx| {+ if (std.mem.eql(u8, &ctx.realm_id, realm)) {+ return ctx;+ }+ }+ try cmd.sendError("no such frame", "unknown realm");+ return null;+ }++ try cmd.sendError("invalid argument", "target requires a context or a realm");+ return null;+}++const testing = @import("testing.zig");++test "bidi.script: evaluate primitives" {+ var ctx = try testing.context();+ defer ctx.deinit();++ const context_id = try ctx.createContext(.{ .url = "bidi/values.html" });++ const cases = [_]struct { expression: []const u8, expected: []const u8 }{+ .{ .expression = "'hi'", .expected =+ \\{"type": "string", "value": "hi"}+ },+ .{ .expression = "1 + 2", .expected =+ \\{"type": "number", "value": 3}+ },+ // A whole number must not go out as 3e0 -- clients that reject+ // non-conforming JSON are within their rights.+ .{ .expression = "1.5", .expected =+ \\{"type": "number", "value": 1.5}+ },+ .{ .expression = "0/0", .expected =+ \\{"type": "number", "value": "NaN"}+ },+ .{ .expression = "-1/0", .expected =+ \\{"type": "number", "value": "-Infinity"}+ },+ .{ .expression = "-0", .expected =+ \\{"type": "number", "value": "-0"}+ },+ .{ .expression = "true", .expected =+ \\{"type": "boolean", "value": true}+ },+ .{ .expression = "null", .expected =+ \\{"type": "null"}+ },+ .{ .expression = "undefined", .expected =+ \\{"type": "undefined"}+ },+ .{ .expression = "12345678901234567890n", .expected =+ \\{"type": "bigint", "value": "12345678901234567890"}+ },+ .{ .expression = "() => {}", .expected =+ \\{"type": "function"}+ },+ .{ .expression = "new Map()", .expected =+ \\{"type": "map"}+ },+ .{ .expression = "new Set()", .expected =+ \\{"type": "set"}+ },+ .{ .expression = "new WeakMap()", .expected =+ \\{"type": "weakmap"}+ },+ .{ .expression = "new WeakSet()", .expected =+ \\{"type": "weakset"}+ },+ // A proxy is reported as a proxy, not as its target.+ .{ .expression = "new Proxy(new Map(), {})", .expected =+ \\{"type": "proxy"}+ },+ .{ .expression = "(function*(){})()", .expected =+ \\{"type": "generator"}+ },+ .{ .expression = "/ab+c/gi", .expected =+ \\{"type": "regexp", "value": {"pattern": "ab+c", "flags": "gi"}}+ },+ .{ .expression = "new Date(0)", .expected =+ \\{"type": "date", "value": "1970-01-01T00:00:00.000Z"}+ },+ .{ .expression = "new Date(1755264000123)", .expected =+ \\{"type": "date", "value": "2025-08-15T13:20:00.123Z"}+ },+ // Past year 9999 JS switches to a six-digit year.+ .{ .expression = "new Date(8.64e15)", .expected =+ \\{"type": "date", "value": "+275760-09-13T00:00:00.000Z"}+ },+ // toISOString would throw; String() round-trips on the client.+ .{ .expression = "new Date(NaN)", .expected =+ \\{"type": "date", "value": "Invalid Date"}+ },+ .{ .expression = "window", .expected =+ \\{"type": "window"}+ },+ };++ for (cases, 0..) |case, i| {+ const id = i + 1;+ try ctx.processMessage(.{+ .id = id,+ .method = "script.evaluate",+ .params = .{+ .expression = case.expression,+ .target = .{ .context = context_id },+ .awaitPromise = false,+ },+ });+ try ctx.expectSentResult(.{+ .type = "success",+ .result = try std.json.parseFromSliceLeaky(std.json.Value, testing.arena, case.expected, .{}),+ }, .{ .id = id });+ }+}++test "bidi.script: evaluate arrays and objects" {+ var ctx = try testing.context();+ defer ctx.deinit();++ const context_id = try ctx.createContext(.{ .url = "bidi/values.html" });++ try ctx.processMessage(.{+ .id = 1,+ .method = "script.evaluate",+ .params = .{+ .expression = "[1, 'two', {a: [true]}]",+ .target = .{ .context = context_id },+ },+ });+ try ctx.expectSentResult(.{+ .type = "success",+ .result = .{+ .type = "array",+ .value = .{+ .{ .type = "number", .value = 1 },+ .{ .type = "string", .value = "two" },+ .{+ .type = "object",+ .value = .{+ .{ "a", .{ .type = "array", .value = .{.{ .type = "boolean", .value = true }} } },+ },+ },+ },+ },+ }, .{ .id = 1 });++ // maxObjectDepth 0 is how a driver asks for a reference without paying+ // for the contents; the value is omitted entirely.+ try ctx.processMessage(.{+ .id = 2,+ .method = "script.evaluate",+ .params = .{+ .expression = "({a: 1})",+ .target = .{ .context = context_id },+ .serializationOptions = .{ .maxObjectDepth = 0 },+ },+ });+ try ctx.expectSentResult(.{ .type = "success", .result = .{ .type = "object" } }, .{ .id = 2 });++ // A self-reference collapses to the bare type rather than recursing:+ // maxObjectDepth defaults to unlimited.+ try ctx.processMessage(.{+ .id = 3,+ .method = "script.evaluate",+ .params = .{+ .expression = "(() => { const a = {}; a.self = a; return a; })()",+ .target = .{ .context = context_id },+ },+ });+ try ctx.expectSentResult(.{+ .type = "success",+ .result = .{ .type = "object", .value = .{.{ "self", .{ .type = "object" } }} },+ }, .{ .id = 3 });+}++test "bidi.script: serialization survives a page tampering with its globals" {+ var ctx = try testing.context();+ defer ctx.deinit();++ const context_id = try ctx.createContext(.{ .url = "bidi/values.html" });++ try ctx.processMessage(.{+ .id = 1,+ .method = "script.evaluate",+ .params = .{+ .expression = "delete Object.prototype.toString; delete window.Set; Date.prototype.toISOString = () => 'nope'; 1",+ .target = .{ .context = context_id },+ },+ });+ try ctx.expectSentResult(.{ .type = "success" }, .{ .id = 1 });++ // Nothing in serialization goes through the page's globals, cycle guard+ // included.+ try ctx.processMessage(.{+ .id = 2,+ .method = "script.evaluate",+ .params = .{+ .expression = "(() => { const a = {n: 1}; a.self = a; return [a, a]; })()",+ .target = .{ .context = context_id },+ },+ });+ try ctx.expectSentResult(.{+ .type = "success",+ .result = .{+ .type = "array",+ .value = .{+ // The repeat inside `a` is the cycle; the second element is+ // only a shared reference, so it serializes in full.+ .{ .type = "object", .value = .{+ .{ "n", .{ .type = "number", .value = 1 } },+ .{ "self", .{ .type = "object" } },+ } },+ .{ .type = "object", .value = .{+ .{ "n", .{ .type = "number", .value = 1 } },+ .{ "self", .{ .type = "object" } },+ } },+ },+ },+ }, .{ .id = 2 });++ // The native predicates still recognize a Map, deleted Set (and deleted+ // Object.prototype.toString) notwithstanding.+ try ctx.processMessage(.{+ .id = 3,+ .method = "script.evaluate",+ .params = .{+ .expression = "new Map()",+ .target = .{ .context = context_id },+ },+ });+ try ctx.expectSentResult(.{ .type = "success", .result = .{ .type = "map" } }, .{ .id = 3 });++ // A date is formatted natively, not through Date.prototype.+ try ctx.processMessage(.{+ .id = 5,+ .method = "script.evaluate",+ .params = .{+ .expression = "new Date(0)",+ .target = .{ .context = context_id },+ },+ });+ try ctx.expectSentResult(.{+ .type = "success",+ .result = .{ .type = "date", .value = "1970-01-01T00:00:00.000Z" },+ }, .{ .id = 5 });++ // A custom class has no bare-type name; it serializes as a plain object.+ try ctx.processMessage(.{+ .id = 4,+ .method = "script.evaluate",+ .params = .{+ .expression = "new (function Fake(){})()",+ .target = .{ .context = context_id },+ },+ });+ try ctx.expectSentResult(.{ .type = "success", .result = .{ .type = "object" } }, .{ .id = 4 });+}++test "bidi.script: evaluate nodes" {+ var ctx = try testing.context();+ defer ctx.deinit();++ const context_id = try ctx.createContext(.{ .url = "bidi/values.html" });++ // maxDomDepth defaults to 0: the node's own properties, no children.+ try ctx.processMessage(.{+ .id = 1,+ .method = "script.evaluate",+ .params = .{+ .expression = "document.getElementById('main')",+ .target = .{ .context = context_id },+ },+ });+ try ctx.expectSentResult(.{+ .type = "success",+ .result = .{+ .type = "node",+ .sharedId = "1",+ .value = .{+ .nodeType = 1,+ .childNodeCount = 1,+ .localName = "div",+ .attributes = .{ .id = "main", .class = "a b", .@"data-x" = "1" },+ },+ },+ }, .{ .id = 1 });++ // The same node keeps its sharedId.+ try ctx.processMessage(.{+ .id = 2,+ .method = "script.evaluate",+ .params = .{+ .expression = "document.querySelector('#main')",+ .target = .{ .context = context_id },+ },+ });+ try ctx.expectSentResult(.{+ .type = "success",+ .result = .{ .type = "node", .sharedId = "1" },+ }, .{ .id = 2 });++ try ctx.processMessage(.{+ .id = 3,+ .method = "script.evaluate",+ .params = .{+ .expression = "document.getElementById('main')",+ .target = .{ .context = context_id },+ .serializationOptions = .{ .maxDomDepth = 1 },+ },+ });+ try ctx.expectSentResult(.{+ .type = "success",+ .result = .{+ .type = "node",+ .value = .{+ .children = .{.{+ .type = "node",+ .value = .{ .nodeType = 1, .localName = "p", .childNodeCount = 1 },+ }},+ },+ },+ }, .{ .id = 3 });+}++test "bidi.script: evaluate platform objects" {+ var ctx = try testing.context();+ defer ctx.deinit();++ const context_id = try ctx.createContext(.{ .url = "bidi/values.html" });++ // NodeList and HTMLCollection are array-likes of nodes.+ try ctx.processMessage(.{+ .id = 1,+ .method = "script.evaluate",+ .params = .{+ .expression = "document.querySelectorAll('#main, p')",+ .target = .{ .context = context_id },+ },+ });+ try ctx.expectSentResult(.{+ .type = "success",+ .result = .{+ .type = "nodelist",+ .value = .{+ .{ .type = "node", .value = .{ .localName = "div" } },+ .{ .type = "node", .value = .{ .localName = "p" } },+ },+ },+ }, .{ .id = 1 });++ try ctx.processMessage(.{+ .id = 2,+ .method = "script.evaluate",+ .params = .{+ .expression = "document.getElementsByTagName('p')",+ .target = .{ .context = context_id },+ },+ });+ try ctx.expectSentResult(.{+ .type = "success",+ .result = .{+ .type = "htmlcollection",+ .value = .{.{ .type = "node", .value = .{ .localName = "p" } }},+ },+ }, .{ .id = 2 });++ // maxObjectDepth applies to them like any other container.+ try ctx.processMessage(.{+ .id = 3,+ .method = "script.evaluate",+ .params = .{+ .expression = "document.getElementsByTagName('p')",+ .target = .{ .context = context_id },+ .serializationOptions = .{ .maxObjectDepth = 0 },+ },+ });+ try ctx.expectSentResult(.{ .type = "success", .result = .{ .type = "htmlcollection" } }, .{ .id = 3 });+ const bare = try ctx.sentMessage(2);+ try testing.expect(bare.object.get("result").?.object.get("value") == null);++ // Any other platform object is opaque: its type, but not its properties.+ try ctx.processMessage(.{+ .id = 4,+ .method = "script.evaluate",+ .params = .{+ .expression = "navigator",+ .target = .{ .context = context_id },+ },+ });+ try ctx.expectSentResult(.{ .type = "success", .result = .{ .type = "object" } }, .{ .id = 4 });+ const opaque_object = try ctx.sentMessage(3);+ try testing.expect(opaque_object.object.get("result").?.object.get("value") == null);+}++test "bidi.script: sharedIds don't survive a navigation" {+ var ctx = try testing.context();+ defer ctx.deinit();++ const context_id = try ctx.createContext(.{ .url = "bidi/values.html" });++ try ctx.processMessage(.{+ .id = 1,+ .method = "script.evaluate",+ .params = .{ .expression = "document.body", .target = .{ .context = context_id } },+ });+ try ctx.expectSentResult(.{ .type = "success", .result = .{ .type = "node", .sharedId = "1" } }, .{ .id = 1 });++ try ctx.processMessage(.{+ .id = 2,+ .method = "browsingContext.navigate",+ .params = .{+ .context = context_id,+ .url = testing.test_server ++ "bidi/values.html",+ .wait = "complete",+ },+ });+ try ctx.wait();++ // The registry was cleared, so the id is gone rather than pointing at a+ // node from the previous document.+ try ctx.processMessage(.{+ .id = 3,+ .method = "script.callFunction",+ .params = .{+ .functionDeclaration = "(node) => node.tagName",+ .target = .{ .context = context_id },+ .arguments = .{.{ .sharedId = "1" }},+ },+ });+ try ctx.expectSentError("no such node", null, .{ .id = 3 });+}++test "bidi.script: evaluate reports a throw as an exception result" {+ var ctx = try testing.context();+ defer ctx.deinit();++ const context_id = try ctx.createContext(.{ .url = "bidi/values.html" });++ // A JS throw isn't a command failure: the reply is a success carrying an+ // exception result.+ try ctx.processMessage(.{+ .id = 1,+ .method = "script.evaluate",+ .params = .{+ .expression = "throw new Error('nope')",+ .target = .{ .context = context_id },+ },+ });+ // The text carries the error's name too — drivers split it back off.+ try ctx.expectSentResult(.{+ .type = "exception",+ .exceptionDetails = .{+ .text = "Error: nope",+ .exception = .{ .type = "error" },+ },+ }, .{ .id = 1 });++ try ctx.processMessage(.{+ .id = 2,+ .method = "script.evaluate",+ .params = .{+ .expression = "this is not javascript",+ .target = .{ .context = context_id },+ },+ });+ try ctx.expectSentResult(.{ .type = "exception" }, .{ .id = 2 });+}++test "bidi.script: evaluate awaitPromise" {+ var ctx = try testing.context();+ defer ctx.deinit();++ const context_id = try ctx.createContext(.{ .url = "bidi/values.html" });++ // Settling only needs the microtask queue, which we can drain inline.+ try ctx.processMessage(.{+ .id = 1,+ .method = "script.evaluate",+ .params = .{+ .expression = "Promise.resolve(42)",+ .target = .{ .context = context_id },+ .awaitPromise = true,+ },+ });+ try ctx.expectSentResult(.{+ .type = "success",+ .result = .{ .type = "number", .value = 42 },+ }, .{ .id = 1 });++ try ctx.processMessage(.{+ .id = 2,+ .method = "script.evaluate",+ .params = .{+ .expression = "Promise.reject(new Error('boom'))",+ .target = .{ .context = context_id },+ .awaitPromise = true,+ },+ });+ try ctx.expectSentResult(.{+ .type = "exception",+ .exceptionDetails = .{ .text = "Error: boom", .exception = .{ .type = "error" } },+ }, .{ .id = 2 });++ // Without awaitPromise the promise itself is the result, settled or not.+ try ctx.processMessage(.{+ .id = 3,+ .method = "script.evaluate",+ .params = .{+ .expression = "Promise.resolve(42)",+ .target = .{ .context = context_id },+ .awaitPromise = false,+ },+ });+ try ctx.expectSentResult(.{+ .type = "success",+ .result = .{ .type = "promise" },+ }, .{ .id = 3 });++ // A promise waiting on a timer can't settle without running the event+ // loop, which means holding the command open across ticks.+ try ctx.processMessage(.{+ .id = 4,+ .method = "script.evaluate",+ .params = .{+ .expression = "new Promise(r => setTimeout(r, 0))",+ .target = .{ .context = context_id },+ .awaitPromise = true,+ },+ });+ try ctx.expectSentError("unsupported operation", "awaitPromise on a pending promise", .{ .id = 4 });+}++test "bidi.script: callFunction arguments" {+ var ctx = try testing.context();+ defer ctx.deinit();++ const context_id = try ctx.createContext(.{ .url = "bidi/values.html" });++ try ctx.processMessage(.{+ .id = 1,+ .method = "script.callFunction",+ .params = .{+ .functionDeclaration = "(a, b, c) => a + b.n + c.length",+ .target = .{ .context = context_id },+ .arguments = .{+ .{ .type = "number", .value = 1 },+ // An object key is a LocalValue of its own, which is the form+ // drivers send even for a plain object.+ .{ .type = "object", .value = .{.{ .{ .type = "string", .value = "n" }, .{ .type = "number", .value = 2 } }} },+ .{ .type = "array", .value = .{ .{ .type = "boolean", .value = true }, .{ .type = "null" } } },+ },+ },+ });+ try ctx.expectSentResult(.{+ .type = "success",+ .result = .{ .type = "number", .value = 5 },+ }, .{ .id = 1 });++ // A bigint argument round-trips beyond 64 bits.+ try ctx.processMessage(.{+ .id = 6,+ .method = "script.callFunction",+ .params = .{+ .functionDeclaration = "(b) => b + 1n",+ .target = .{ .context = context_id },+ .arguments = .{.{ .type = "bigint", .value = "340282366920938463463374607431768211456" }},+ },+ });+ try ctx.expectSentResult(.{+ .type = "success",+ .result = .{ .type = "bigint", .value = "340282366920938463463374607431768211457" },+ }, .{ .id = 6 });++ // Plain text is also allowed for a key.+ try ctx.processMessage(.{+ .id = 5,+ .method = "script.callFunction",+ .params = .{+ .functionDeclaration = "(o) => o.n",+ .target = .{ .context = context_id },+ .arguments = .{.{ .type = "object", .value = .{.{ "n", .{ .type = "number", .value = 9 } }} }},+ },+ });+ try ctx.expectSentResult(.{+ .type = "success",+ .result = .{ .type = "number", .value = 9 },+ }, .{ .id = 5 });++ // The trailing sourceURL comment drivers append has to survive the wrap+ // that turns the declaration into a callable.+ try ctx.processMessage(.{+ .id = 2,+ .method = "script.callFunction",+ .params = .{+ .functionDeclaration = "() => 'ok'\n//# sourceURL=pptr://__puppeteer_evaluation_script__\n",+ .target = .{ .context = context_id },+ },+ });+ try ctx.expectSentResult(.{+ .type = "success",+ .result = .{ .type = "string", .value = "ok" },+ }, .{ .id = 2 });++ try ctx.processMessage(.{+ .id = 3,+ .method = "script.callFunction",+ .params = .{+ .functionDeclaration = "function() { return this.n; }",+ .target = .{ .context = context_id },+ .this = .{ .type = "object", .value = .{.{ "n", .{ .type = "string", .value = "this" } }} },+ },+ });+ try ctx.expectSentResult(.{+ .type = "success",+ .result = .{ .type = "string", .value = "this" },+ }, .{ .id = 3 });++ // Parses, but isn't callable. A declaration that doesn't parse at all+ // comes back as an exception result instead.+ try ctx.processMessage(.{+ .id = 4,+ .method = "script.callFunction",+ .params = .{+ .functionDeclaration = "42",+ .target = .{ .context = context_id },+ },+ });+ try ctx.expectSentError("invalid argument", null, .{ .id = 4 });+}++test "bidi.script: handles" {+ var ctx = try testing.context();+ defer ctx.deinit();++ const context_id = try ctx.createContext(.{ .url = "bidi/values.html" });++ // resultOwnership "root" keeps the value alive so a later command can+ // refer back to it.+ try ctx.processMessage(.{+ .id = 1,+ .method = "script.evaluate",+ .params = .{+ .expression = "({n: 7})",+ .target = .{ .context = context_id },+ .resultOwnership = "root",+ },+ });+ try ctx.expectSentResult(.{+ .type = "success",+ .result = .{ .type = "object", .handle = "1" },+ }, .{ .id = 1 });++ try ctx.processMessage(.{+ .id = 2,+ .method = "script.callFunction",+ .params = .{+ .functionDeclaration = "(o) => o.n",+ .target = .{ .context = context_id },+ .arguments = .{.{ .handle = "1" }},+ },+ });+ try ctx.expectSentResult(.{+ .type = "success",+ .result = .{ .type = "number", .value = 7 },+ }, .{ .id = 2 });++ // A primitive has nothing to hold on to, so it gets no handle.+ try ctx.processMessage(.{+ .id = 3,+ .method = "script.evaluate",+ .params = .{+ .expression = "'plain'",+ .target = .{ .context = context_id },+ .resultOwnership = "root",+ },+ });+ try ctx.expectSentResult(.{ .type = "success", .result = .{ .type = "string" } }, .{ .id = 3 });++ try ctx.processMessage(.{+ .id = 4,+ .method = "script.disown",+ .params = .{ .handles = .{"1"}, .target = .{ .context = context_id } },+ });+ try ctx.expectSentResult(null, .{ .id = 4 });++ try ctx.processMessage(.{+ .id = 5,+ .method = "script.callFunction",+ .params = .{+ .functionDeclaration = "(o) => o.n",+ .target = .{ .context = context_id },+ .arguments = .{.{ .handle = "1" }},+ },+ });+ try ctx.expectSentError("no such handle", null, .{ .id = 5 });++ // Disowning an unknown handle is a no-op, not an error: a client that+ // disowns twice is behaving normally.+ try ctx.processMessage(.{+ .id = 6,+ .method = "script.disown",+ .params = .{ .handles = .{"1"}, .target = .{ .context = context_id } },+ });+ try ctx.expectSentResult(null, .{ .id = 6 });+}++test "bidi.script: target validation" {+ var ctx = try testing.context();+ defer ctx.deinit();++ const context_id = try ctx.createContext(.{ .url = "bidi/values.html" });++ try ctx.processMessage(.{+ .id = 1,+ .method = "script.evaluate",+ .params = .{+ .expression = "1",+ .target = .{ .context = "00000000-0000-0000-0000-000000000000" },+ },+ });+ try ctx.expectSentError("no such frame", "unknown context", .{ .id = 1 });++ try ctx.processMessage(.{+ .id = 2,+ .method = "script.evaluate",+ .params = .{ .expression = "1", .target = .{} },+ });+ try ctx.expectSentError("invalid argument", null, .{ .id = 2 });++ // An isolated world would silently run against the wrong globals, so it's+ // refused rather than ignored.+ try ctx.processMessage(.{+ .id = 3,+ .method = "script.evaluate",+ .params = .{+ .expression = "1",+ .target = .{ .context = context_id, .sandbox = "mine" },+ },+ });+ try ctx.expectSentError("unsupported operation", "sandboxes are not supported", .{ .id = 3 });++ // The realm reported alongside a result is also accepted as a target.+ const realm = try testing.arena.dupe(u8, &ctx.bidi().context.?.realm_id);+ try ctx.processMessage(.{+ .id = 4,+ .method = "script.evaluate",+ .params = .{ .expression = "1", .target = .{ .realm = realm } },+ });+ try ctx.expectSentResult(.{ .type = "success", .realm = realm }, .{ .id = 4 });+}++test "bidi.script: commands need a session" {+ var ctx = try testing.context();+ defer ctx.deinit();++ try ctx.processMessage(.{+ .id = 1,+ .method = "script.evaluate",+ .params = .{ .expression = "1", .target = .{ .context = "x" } },+ });+ try ctx.expectSentError("invalid session id", "no active session", .{ .id = 1 });++ // The session gate runs before the module resolves its action, so an+ // unknown script command is only reported as such once there's a session.+ try ctx.processMessage(.{ .id = 2, .method = "script.nope" });+ try ctx.expectSentError("invalid session id", "no active session", .{ .id = 2 });++ try ctx.startSession();+ try ctx.processMessage(.{ .id = 3, .method = "script.nope" });+ try ctx.expectSentError("unknown command", "script.nope", .{ .id = 3 });+}diff --git a/src/server/bidi/testing.zig b/src/server/bidi/testing.zignew file mode 100644index 000000000..1d70a205a--- /dev/null+++ b/src/server/bidi/testing.zig@@ -0,0 +1,288 @@+// Copyright (C) 2023-2026 Lightpanda (Selecy SAS)+//+// Francis Bouvier <[email protected]>+// Pierre Tachoire <[email protected]>+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as+// published by the Free Software Foundation, either version 3 of the+// License, or (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++const std = @import("std");++const base = @import("../../testing.zig");+const Frame = @import("../../browser/Frame.zig");++const BiDi = @import("BiDi.zig");++const json = std.json;+const posix = std.posix;++pub const io = base.io;+pub const allocator = base.allocator;+pub const arena = base.arena_allocator;+pub const expect = std.testing.expect;+pub const expectEqual = base.expectEqual;+pub const expectError = base.expectError;+pub const expectString = base.expectString;+pub const expectLog = base.expectLog;+pub const silenceLog = base.silenceLog;++// Where the test http server serves src/browser/tests from.+pub const test_server = "http://127.0.0.1:9582/src/browser/tests/";++const TestContext = struct {+ read_at: usize = 0,+ read_buf: [1024 * 32]u8 = undefined,+ bidi_: BiDi = undefined,+ bidi_initialized: bool = false,+ bidi_socket: posix.socket_t,+ socket: posix.socket_t,+ received: std.ArrayList(json.Value) = .empty,+ received_raw: std.ArrayList([]const u8) = .empty,++ pub fn deinit(self: *TestContext) void {+ if (self.bidi_initialized) {+ self.bidi_.deinit();+ }+ _ = std.c.close(self.socket);+ _ = std.c.close(self.bidi_socket);+ base.reset();+ }++ pub fn bidi(self: *TestContext) *BiDi {+ if (!self.bidi_initialized) {+ self.bidi_.init(base.test_app, self.bidi_socket) catch |err| @panic(@errorName(err));+ self.bidi_initialized = true;+ }+ return &self.bidi_;+ }++ pub fn processMessage(self: *TestContext, msg: anytype) !void {+ const payload: []const u8 = blk: {+ if (@typeInfo(@TypeOf(msg)) != .pointer) {+ break :blk try json.Stringify.valueAlloc(base.arena_allocator, msg, .{});+ }+ // assume this is a string we want to send as-is; if it isn't we'll+ // get a compile error, so no big deal.+ break :blk msg;+ };+ return self.bidi().onMessage(payload);+ }++ // Starts the session every command outside the session module needs.+ pub fn startSession(self: *TestContext) !void {+ try self.processMessage(.{ .id = command_id_session, .method = "session.new" });+ }++ pub const ContextOpts = struct {+ // Relative to `test_server`. Left null, the context stays on+ // about:blank.+ url: ?[]const u8 = null,+ };++ // session.new + browsingContext.create (+ navigate), answering with the+ // generated context id so tests don't have to dig it out of the replies.+ pub fn createContext(self: *TestContext, opts: ContextOpts) ![]const u8 {+ try self.startSession();+ try self.processMessage(.{ .id = command_id_create, .method = "browsingContext.create", .params = .{ .type = "tab" } });++ const ctx = &(self.bidi().context orelse return error.NoBrowsingContext);+ const context_id = try base.arena_allocator.dupe(u8, &ctx.id);++ if (opts.url) |url| {+ try self.processMessage(.{+ .id = command_id_navigate,+ .method = "browsingContext.navigate",+ .params = .{+ .context = context_id,+ .url = try std.fmt.allocPrint(base.arena_allocator, test_server ++ "{s}", .{url}),+ .wait = "none",+ },+ });+ try self.wait();+ }+ return context_id;+ }++ // Runs the page until it's done loading. Navigation is asynchronous even+ // when the command already answered.+ pub fn wait(self: *TestContext) !void {+ const b = self.bidi();+ const ctx = b.context orelse return error.NoBrowsingContext;+ var runner = b.session.runner(.{});+ try runner.waitForFrame(ctx.frame_id, 2000, .{ .until = .done });+ }++ pub fn frame(self: *TestContext) !*Frame {+ return self.bidi().session.currentFrame() orelse error.NoFrame;+ }++ const SentOpts = struct {+ id: ?usize = null,+ };++ // The result half of a `{"type": "success", "id": N, "result": ...}`+ // reply.+ pub fn expectSentResult(self: *TestContext, expected: anytype, opts: SentOpts) !void {+ return self.expectSent(.{+ .type = "success",+ .id = opts.id,+ .result = if (comptime @typeInfo(@TypeOf(expected)) == .null) struct {}{} else expected,+ });+ }++ pub fn expectSentError(self: *TestContext, code: []const u8, message: ?[]const u8, opts: SentOpts) !void {+ return self.expectSent(.{+ .type = "error",+ .id = opts.id,+ .@"error" = code,+ .message = message,+ });+ }++ pub fn expectSentEvent(self: *TestContext, method: []const u8, params: anytype) !void {+ return self.expectSent(.{+ .type = "event",+ .method = method,+ .params = if (comptime @typeInfo(@TypeOf(params)) == .null) struct {}{} else params,+ });+ }++ // Matches on the fields `expected` actually sets, so a test can assert on+ // one field of a large result. Null optionals are skipped entirely, which+ // is what makes `.id = null` mean "any id".+ pub fn expectSent(self: *TestContext, expected: anytype) !void {+ const serialized = try json.Stringify.valueAlloc(base.arena_allocator, expected, .{+ .whitespace = .indent_2,+ .emit_null_optional_fields = false,+ });+ const expected_json = try json.parseFromSliceLeaky(json.Value, base.arena_allocator, serialized, .{});++ try self.read();+ for (self.received.items) |received| {+ if (try base.isEqualJson(expected_json, received)) {+ return;+ }+ }++ std.debug.print("Expected:\n{s}\n\n", .{serialized});+ self.dumpReceived();+ return error.MessageNotFound;+ }++ // The raw json of the nth message sent, for assertions that don't fit the+ // subset match (a generated id, a substring of a long result).+ pub fn sentMessage(self: *TestContext, index: usize) !json.Value {+ try self.read();+ if (index >= self.received.items.len) {+ self.dumpReceived();+ return error.MessageNotFound;+ }+ return self.received.items[index];+ }++ pub fn expectSentCount(self: *TestContext, expected: usize) !void {+ try self.read();+ try expectEqual(expected, self.received.items.len);+ }++ fn dumpReceived(self: *const TestContext) void {+ std.debug.print("BiDi messages received ({d})\n", .{self.received_raw.items.len});+ for (self.received_raw.items, 0..) |received, i| {+ std.debug.print("=== Message: {d} ===\n{s}\n\n", .{ i, received });+ }+ }++ fn read(self: *TestContext) !void {+ while (true) {+ const n = posix.read(self.socket, self.read_buf[self.read_at..]) catch |err| switch (err) {+ error.WouldBlock => return,+ else => return err,+ };+ if (n == 0) {+ return;+ }+ self.read_at += n;++ var pos: usize = 0;+ while (pos < self.read_at) {+ // 2-byte header minimum+ if (self.read_at - pos < 2) break;++ const opcode = self.read_buf[pos] & 0x0F;+ const payload_len_byte = self.read_buf[pos + 1] & 0x7F;++ var header_size: usize = 2;+ var payload_len: usize = payload_len_byte;+ if (payload_len_byte == 126) {+ if (self.read_at - pos < 4) break;+ payload_len = std.mem.readInt(u16, self.read_buf[pos + 2 ..][0..2], .big);+ header_size = 4;+ } else if (payload_len_byte == 127) {+ if (self.read_at - pos < 10) break;+ payload_len = @intCast(std.mem.readInt(u64, self.read_buf[pos + 2 ..][0..8], .big));+ header_size = 10;+ }++ const frame_size = header_size + payload_len;+ if (self.read_at - pos < frame_size) break;++ // text (1) or binary (2); control frames aren't interesting here+ if (opcode == 1 or opcode == 2) {+ const payload = self.read_buf[pos + header_size ..][0..payload_len];+ try self.received.append(base.arena_allocator, try json.parseFromSliceLeaky(json.Value, base.arena_allocator, payload, .{}));+ try self.received_raw.append(base.arena_allocator, try base.arena_allocator.dupe(u8, payload));+ }+ pos += frame_size;+ }++ if (pos > 0 and pos < self.read_at) {+ std.mem.copyForwards(u8, &self.read_buf, self.read_buf[pos..self.read_at]);+ self.read_at -= pos;+ } else if (pos == self.read_at) {+ self.read_at = 0;+ }+ }+ }+};++// Ids for the setup commands, well clear of what a test uses so a stray+// match can't come from the harness.+const command_id_session = 9001;+const command_id_create = 9002;+const command_id_navigate = 9003;++pub fn context() !TestContext {+ var pair: [2]posix.socket_t = undefined;+ if (std.c.socketpair(posix.AF.LOCAL, posix.SOCK.STREAM, 0, &pair) != 0) {+ return error.SocketPairFailed;+ }++ errdefer {+ _ = std.c.close(pair[0]);+ _ = std.c.close(pair[1]);+ }++ const timeout = std.mem.toBytes(posix.timeval{ .sec = 0, .usec = 5_000 });+ const buffer_size = std.mem.toBytes(@as(c_int, 32_768));+ for (pair) |socket| {+ try posix.setsockopt(socket, posix.SOL.SOCKET, posix.SO.RCVTIMEO, &timeout);+ try posix.setsockopt(socket, posix.SOL.SOCKET, posix.SO.SNDTIMEO, &timeout);+ try posix.setsockopt(socket, posix.SOL.SOCKET, posix.SO.RCVBUF, &buffer_size);+ try posix.setsockopt(socket, posix.SOL.SOCKET, posix.SO.SNDBUF, &buffer_size);+ }++ return .{+ .bidi_socket = pair[1],+ .socket = pair[0],+ };+}