Skip to content

Lightpanda: the headless browser designed for AI and automation

chore: refactor Execution and GlobalScope

Karl Seguin30619301530a
diff --git a/src/browser/ScriptManagerBase.zig b/src/browser/ScriptManagerBase.zig
index 943775269..b9bded983 100644
--- a/src/browser/ScriptManagerBase.zig
+++ b/src/browser/ScriptManagerBase.zig
@@ -22,58 +22,20 @@ const lp = @import("lightpanda");
const HttpClient = @import("../network/HttpClient.zig");
const js = @import("js/js.zig");
-const Session = @import("Session.zig");
const Frame = @import("Frame.zig");
const ImportMap = @import("ImportMap.zig");
-const WorkerGlobalScope = @import("webapi/WorkerGlobalScope.zig");
const Element = @import("webapi/Element.zig");
+const WorkerGlobalScope = @import("webapi/WorkerGlobalScope.zig");
const log = lp.log;
const String = lp.String;
+const GlobalScope = lp.GlobalScope;
const Allocator = std.mem.Allocator;
const ScriptManagerBase = @This();
-// Either a *Frame (for page ScriptManagers) or *WorkerGlobalScope (for workers).
-// Used from HTTP callbacks that only have a *Script in hand; the Script reaches
-// the owner through its manager pointer.
-pub const Owner = union(enum) {
- frame: *Frame,
- worker: *WorkerGlobalScope,
-
- pub fn url(self: Owner) [:0]const u8 {
- return switch (self) {
- inline else => |g| g.url,
- };
- }
-
- pub fn session(self: Owner) *Session {
- return switch (self) {
- inline else => |g| g._session,
- };
- }
-
- pub fn origin(self: Owner) ?[]const u8 {
- return switch (self) {
- inline else => |g| g.origin,
- };
- }
-
- pub fn jsContext(self: Owner) *js.Context {
- return switch (self) {
- inline else => |g| g.js,
- };
- }
-
- pub fn makeRequest(self: Owner, req: HttpClient.Request) !void {
- return switch (self) {
- inline else => |g| g.makeRequest(req),
- };
- }
-};
-
-owner: Owner,
+owner: GlobalScope,
// used to prevent recursive evaluation
is_evaluating: bool,
@@ -113,7 +75,7 @@ importmap: ImportMap,
// scriptsCompletedLoading. Null for workers.
tail_hook: ?*const fn (*ScriptManagerBase) void,
-pub fn init(allocator: Allocator, http_client: *HttpClient, owner: Owner) ScriptManagerBase {
+pub fn init(allocator: Allocator, http_client: *HttpClient, owner: GlobalScope) ScriptManagerBase {
return .{
.owner = owner,
.async_scripts = .{},
@@ -232,7 +194,7 @@ pub fn preloadImport(self: *ScriptManagerBase, url: [:0]const u8, referrer: []co
if (comptime lp.IS_DEBUG) {
var ls: js.Local.Scope = undefined;
- self.owner.jsContext().localScope(&ls);
+ self.owner.getJs().localScope(&ls);
defer ls.deinit();
log.debug(.http, "script queue", .{
@@ -420,7 +382,7 @@ pub fn getAsyncImport(self: *ScriptManagerBase, url: [:0]const u8, cb: ImportAsy
if (comptime lp.IS_DEBUG) {
var ls: js.Local.Scope = undefined;
- self.owner.jsContext().localScope(&ls);
+ self.owner.getJs().localScope(&ls);
defer ls.deinit();
log.debug(.http, "script queue", .{
diff --git a/src/browser/global_scope.zig b/src/browser/global_scope.zig
new file mode 100644
index 000000000..e9b7e0e2c
--- /dev/null
+++ b/src/browser/global_scope.zig
@@ -0,0 +1,193 @@
+// 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 HttpClient = @import("../network/HttpClient.zig");
+
+const Event = @import("webapi/Event.zig");
+const Console = @import("webapi/Console.zig");
+const Cookie = @import("webapi/storage/Cookie.zig");
+const EventTarget = @import("webapi/EventTarget.zig");
+const Performance = @import("webapi/Performance.zig");
+const WorkerGlobalScope = @import("webapi/WorkerGlobalScope.zig");
+
+const Frame = @import("Frame.zig");
+const Session = @import("Session.zig");
+const EventManagerBase = @import("EventManagerBase.zig");
+
+pub const GlobalScope = union(enum) {
+ frame: *Frame,
+ worker: *WorkerGlobalScope,
+
+ // Returns the current base URL of the global scope.
+ pub fn base(self: GlobalScope) [:0]const u8 {
+ return switch (self) {
+ inline else => |g| g.base(),
+ };
+ }
+
+ // The context currently entered for this global. Caller swaps it for the
+ // duration of a call, so this is the running realm, not the main world.
+ pub fn getJs(self: GlobalScope) *lp.js.Context {
+ return switch (self) {
+ inline else => |g| g.js,
+ };
+ }
+
+ pub fn setJs(self: GlobalScope, ctx: *lp.js.Context) void {
+ switch (self) {
+ inline else => |g| g.js = ctx,
+ }
+ }
+
+ pub fn session(self: GlobalScope) *Session {
+ return switch (self) {
+ inline else => |g| g._session,
+ };
+ }
+
+ pub fn url(self: GlobalScope) [:0]const u8 {
+ return switch (self) {
+ inline else => |g| g.url,
+ };
+ }
+
+ // The global's serialized origin (e.g. "https://example.com"), or null for
+ // an opaque origin.
+ pub fn origin(self: GlobalScope) ?[]const u8 {
+ return switch (self) {
+ inline else => |g| g.origin,
+ };
+ }
+
+ pub fn frameId(self: GlobalScope) u32 {
+ return switch (self) {
+ inline else => |g| g._frame_id,
+ };
+ }
+
+ pub fn headersForRequest(self: GlobalScope, transfer: *HttpClient.Transfer) !void {
+ return switch (self) {
+ inline else => |g| g.headersForRequest(transfer),
+ };
+ }
+
+ pub fn isSameOrigin(self: GlobalScope, target: [:0]const u8) bool {
+ return switch (self) {
+ inline else => |g| g.isSameOrigin(target),
+ };
+ }
+
+ pub fn makeRequest(self: GlobalScope, req: HttpClient.Request) !void {
+ return switch (self) {
+ inline else => |g| g.makeRequest(req),
+ };
+ }
+
+ // Two-phase variant; see HttpClient.newRequest for the ownership contract.
+ pub fn newRequest(self: GlobalScope, req: HttpClient.Request) !*HttpClient.Transfer {
+ return switch (self) {
+ inline else => |g| g.newRequest(req),
+ };
+ }
+
+ pub fn getBroadcastChannels(self: GlobalScope) *std.DoublyLinkedList {
+ return switch (self) {
+ inline else => |g| &g._broadcast_channels,
+ };
+ }
+
+ // The owning global's (Frame or WGS) list of live MessagePorts, walked at
+ // that global's teardown to sever cross-context entanglement.
+ pub fn messagePorts(self: GlobalScope) *std.DoublyLinkedList {
+ return switch (self) {
+ inline else => |g| &g._message_ports,
+ };
+ }
+
+ pub fn siteForCookies(self: GlobalScope) Cookie.SiteForCookies {
+ return self.httpOwner().siteForCookies();
+ }
+
+ // HttpClient.Owner of the current global (Frame or WGS). Used by code
+ // that needs to register an in-flight network operation against the
+ // owning scope without caring whether it's a Frame or a Worker — e.g.
+ // WebSocket.init appending to `.websockets`.
+ pub fn httpOwner(self: GlobalScope) *HttpClient.Owner {
+ return switch (self) {
+ inline else => |g| &g._http_owner,
+ };
+ }
+
+ pub fn registerListener(
+ self: GlobalScope,
+ target: *EventTarget,
+ typ: []const u8,
+ callback: EventManagerBase.Callback,
+ opts: EventManagerBase.RegisterOptions,
+ ) !void {
+ switch (self) {
+ inline else => |g| _ = try g._event_manager.register(target, typ, callback, opts),
+ }
+ }
+
+ pub fn removeListener(
+ self: GlobalScope,
+ target: *EventTarget,
+ typ: []const u8,
+ callback: EventManagerBase.Callback,
+ use_capture: bool,
+ ) void {
+ switch (self) {
+ inline else => |g| g._event_manager.remove(target, typ, callback, use_capture),
+ }
+ }
+
+ pub fn dispatch(
+ self: GlobalScope,
+ target: *EventTarget,
+ event: *Event,
+ handler: anytype,
+ comptime opts: EventManagerBase.DispatchDirectOptions,
+ ) !void {
+ return switch (self) {
+ inline else => |g| g.dispatch(target, event, handler, opts),
+ };
+ }
+
+ pub fn hasDirectListeners(self: GlobalScope, target: *EventTarget, typ: []const u8, handler: anytype) bool {
+ return switch (self) {
+ inline else => |g| g.hasDirectListeners(target, typ, handler),
+ };
+ }
+
+ pub fn performance(self: GlobalScope) *Performance {
+ return switch (self) {
+ inline else => |g| g.performance(),
+ };
+ }
+
+ pub fn console(self: GlobalScope) *Console {
+ return switch (self) {
+ .frame => |frame| frame.window.getConsole(),
+ .worker => |worker| worker.getConsole(),
+ };
+ }
+};
diff --git a/src/browser/js/Context.zig b/src/browser/js/Context.zig
index 340537b54..3ed5e820b 100644
--- a/src/browser/js/Context.zig
+++ b/src/browser/js/Context.zig
@@ -38,35 +38,9 @@ const Allocator = std.mem.Allocator;
// Loosely maps to a Browser Page or Worker.
const Context = @This();
-pub const GlobalScope = union(enum) {
- frame: *Frame,
- worker: *WorkerGlobalScope,
-
- pub fn base(self: GlobalScope) [:0]const u8 {
- return switch (self) {
- .frame => |frame| frame.base(),
- .worker => |worker| worker.base(),
- };
- }
-
- pub fn getJs(self: GlobalScope) *Context {
- return switch (self) {
- .frame => |frame| frame.js,
- .worker => |worker| worker.js,
- };
- }
-
- pub fn setJs(self: GlobalScope, ctx: *Context) void {
- switch (self) {
- .frame => |frame| frame.js = ctx,
- .worker => |worker| worker.js = ctx,
- }
- }
-};
-
id: usize,
env: *Env,
-global: GlobalScope,
+global: lp.GlobalScope,
// The Page this Context belongs to. For main-world frame contexts, this is
// the Page of the frame. For worker contexts, this is the Page of the
@@ -1109,7 +1083,7 @@ const Entered = struct {
handle_scope: *js.HandleScope,
- global: GlobalScope,
+ global: lp.GlobalScope,
pub fn exit(self: Entered) void {
self.global.setJs(self.original);
diff --git a/src/browser/js/Execution.zig b/src/browser/js/Execution.zig
index 8862f8c5f..3313555f8 100644
--- a/src/browser/js/Execution.zig
+++ b/src/browser/js/Execution.zig
@@ -66,11 +66,6 @@ url: *[:0]const u8,
// Pointer to the charset field of the global (Page or WorkerGlobalScope).
charset: *[]const u8,
-// Returns the current base URL of the global scope.
-pub fn base(self: *const Execution) [:0]const u8 {
- return self.js.global.base();
-}
-
pub fn dupeString(self: *const Execution, value: []const u8) ![]const u8 {
if (String.intern(value)) |v| {
return v;
@@ -86,65 +81,71 @@ pub fn getPinnedArena(self: *const Execution, size_or_bucket: anytype, debug: []
return self.page.getPinnedArena(size_or_bucket, debug);
}
+// Everything below forwards to the GlobalScope (Frame or WorkerGlobalScope);
+// see global_scope.zig for what these actually do. They live on Execution too
+// because the bridge hands callers an Execution, not a scope.
+pub fn base(self: *const Execution) [:0]const u8 {
+ return self.js.global.base();
+}
+
pub fn headersForRequest(self: *const Execution, transfer: *HttpClient.Transfer) !void {
- return switch (self.js.global) {
- inline else => |g| g.headersForRequest(transfer),
- };
+ return self.js.global.headersForRequest(transfer);
}
pub fn isSameOrigin(self: *const Execution, url: [:0]const u8) bool {
- return switch (self.js.global) {
- inline else => |g| g.isSameOrigin(url),
- };
+ return self.js.global.isSameOrigin(url);
}
pub fn makeRequest(self: *const Execution, req: HttpClient.Request) !void {
- return switch (self.js.global) {
- inline else => |g| g.makeRequest(req),
- };
+ return self.js.global.makeRequest(req);
}
-// Two-phase variant; see HttpClient.newRequest for the ownership contract.
pub fn newRequest(self: *const Execution, req: HttpClient.Request) !*HttpClient.Transfer {
- return switch (self.js.global) {
- inline else => |g| g.newRequest(req),
- };
+ return self.js.global.newRequest(req);
}
pub fn getBroadcastChannels(self: *const Execution) *std.DoublyLinkedList {
- return switch (self.js.global) {
- inline else => |g| &g._broadcast_channels,
- };
+ return self.js.global.getBroadcastChannels();
}
-// The owning global's (Frame or WGS) list of live MessagePorts, walked at
-// that global's teardown to sever cross-context entanglement.
pub fn messagePorts(self: *const Execution) *std.DoublyLinkedList {
- return switch (self.js.global) {
- inline else => |g| &g._message_ports,
- };
+ return self.js.global.messagePorts();
}
-// The global's serialized origin (e.g. "https://example.com"), or null for an
-// opaque origin.
pub fn origin(self: *const Execution) ?[]const u8 {
- return switch (self.js.global) {
- inline else => |g| g.origin,
- };
+ return self.js.global.origin();
+}
+
+pub fn frameId(self: *const Execution) u32 {
+ return self.js.global.frameId();
}
pub fn siteForCookies(self: *const Execution) Cookie.SiteForCookies {
- return self.httpOwner().siteForCookies();
+ return self.js.global.siteForCookies();
}
-// HttpClient.Owner of the current global (Frame or WGS). Used by code
-// that needs to register an in-flight network operation against the
-// owning scope without caring whether it's a Frame or a Worker — e.g.
-// WebSocket.init appending to `.websockets`.
pub fn httpOwner(self: *const Execution) *HttpClient.Owner {
- return switch (self.js.global) {
- inline else => |g| &g._http_owner,
- };
+ return self.js.global.httpOwner();
+}
+
+pub fn registerListener(
+ self: *const Execution,
+ target: *EventTarget,
+ typ: []const u8,
+ callback: EventManagerBase.Callback,
+ opts: EventManagerBase.RegisterOptions,
+) !void {
+ return self.js.global.registerListener(target, typ, callback, opts);
+}
+
+pub fn removeListener(
+ self: *const Execution,
+ target: *EventTarget,
+ typ: []const u8,
+ callback: EventManagerBase.Callback,
+ use_capture: bool,
+) void {
+ self.js.global.removeListener(target, typ, callback, use_capture);
}
pub fn dispatch(
@@ -154,26 +155,17 @@ pub fn dispatch(
handler: anytype,
comptime opts: EventManagerBase.DispatchDirectOptions,
) !void {
- return switch (self.js.global) {
- inline else => |g| g.dispatch(target, event, handler, opts),
- };
+ return self.js.global.dispatch(target, event, handler, opts);
}
pub fn hasDirectListeners(self: *const Execution, target: *EventTarget, typ: []const u8, handler: anytype) bool {
- return switch (self.js.global) {
- inline else => |g| g.hasDirectListeners(target, typ, handler),
- };
+ return self.js.global.hasDirectListeners(target, typ, handler);
}
pub fn performance(self: *const Execution) *Performance {
- return switch (self.js.global) {
- inline else => |g| g.performance(),
- };
+ return self.js.global.performance();
}
pub fn console(self: *const Execution) *Console {
- return switch (self.js.global) {
- .frame => |frame| frame.window.getConsole(),
- .worker => |worker| worker.getConsole(),
- };
+ return self.js.global.console();
}
diff --git a/src/browser/webapi/EventTarget.zig b/src/browser/webapi/EventTarget.zig
index 5f0d83e93..056114ac9 100644
--- a/src/browser/webapi/EventTarget.zig
+++ b/src/browser/webapi/EventTarget.zig
@@ -262,9 +262,7 @@ pub fn addEventListener(self: *EventTarget, typ: []const u8, callback_: js.Nulla
.function => |func| .{ .function = func },
};
- switch (exec.js.global) {
- inline else => |g| _ = try g._event_manager.register(self, typ, em_callback, options),
- }
+ return exec.registerListener(self, typ, em_callback, options);
}
const RemoveEventListenerOptions = union(enum) {
@@ -298,9 +296,7 @@ pub fn removeEventListener(self: *EventTarget, typ: []const u8, callback_: js.Nu
};
};
- switch (exec.js.global) {
- inline else => |g| g._event_manager.remove(self, typ, em_callback, use_capture),
- }
+ exec.removeListener(self, typ, em_callback, use_capture);
}
pub fn format(self: *EventTarget, writer: *std.Io.Writer) !void {
diff --git a/src/browser/webapi/ModelContext.zig b/src/browser/webapi/ModelContext.zig
index 47a6d7e53..8bb96890c 100644
--- a/src/browser/webapi/ModelContext.zig
+++ b/src/browser/webapi/ModelContext.zig
@@ -121,11 +121,7 @@ pub fn registerTool(
// native MCP forwarder) can surface the new tool.
const event: Notification.ModelContextToolEvent = .{ .exec = exec, .tool = entry };
- const session = switch (exec.js.global) {
- inline else => |g| g._session,
- };
-
- session.notification.dispatch(.model_context_tool_added, &event);
+ exec.session.notification.dispatch(.model_context_tool_added, &event);
}
/// Snapshot of currently-registered tools.
@@ -147,9 +143,7 @@ pub fn findTool(self: *ModelContext, name: []const u8) ?*Tool {
/// dispatching `model_context_tool_removed` for each. Cheap when no
/// signals fired (which is the common case).
fn markAborted(self: *ModelContext, tool: *Tool, exec: *const Execution) !void {
- const session = switch (exec.js.global) {
- inline else => |g| g._session,
- };
+ const session = exec.session;
var i: usize = 0;
while (i < self._tools.items.len) {
diff --git a/src/browser/webapi/URL.zig b/src/browser/webapi/URL.zig
index 37e10204f..3a60e7a3d 100644
--- a/src/browser/webapi/URL.zig
+++ b/src/browser/webapi/URL.zig
@@ -307,22 +307,16 @@ pub fn toString(self: *const URL, _: *const Execution) ![]const u8 {
pub const canParse = @import("../URL.zig").canParse;
pub fn createObjectURL(blob: *Blob, exec: *const Execution) ![]const u8 {
- switch (exec.js.global) {
- inline else => |g| return g._page.createBlobUrl(blob, g.origin, g._frame_id),
- }
+ return exec.page.createBlobUrl(blob, exec.origin(), exec.frameId());
}
pub fn revokeObjectURL(url: []const u8, exec: *const Execution) void {
- switch (exec.js.global) {
- inline else => |g| {
- if (!Blob.urlBelongsToOrigin(url, g.origin)) {
- // different origin cannot revoke an object URL. Failure should
- // be silent
- return;
- }
- g._page.revokeBlobUrl(url);
- },
+ if (Blob.urlBelongsToOrigin(url, exec.origin()) == false) {
+ // different origin cannot revoke an object URL. Failure should
+ // be silent
+ return;
}
+ exec.page.revokeBlobUrl(url);
}
pub const JsApi = struct {
diff --git a/src/lightpanda.zig b/src/lightpanda.zig
index 63702fb41..216558887 100644
--- a/src/lightpanda.zig
+++ b/src/lightpanda.zig
@@ -27,6 +27,7 @@ pub const Network = @import("network/Network.zig");
pub const Config = @import("Config.zig");
pub const String = @import("string.zig").String;
pub const Notification = @import("Notification.zig");
+pub const ToolSession = @import("ToolSession.zig");
pub const Server = @import("server/Server.zig");
pub const URL = @import("browser/URL.zig");
@@ -34,7 +35,7 @@ pub const Page = @import("browser/Page.zig");
pub const Frame = @import("browser/Frame.zig");
pub const Browser = @import("browser/Browser.zig");
pub const Session = @import("browser/Session.zig");
-pub const ToolSession = @import("ToolSession.zig");
+pub const GlobalScope = @import("browser/global_scope.zig").GlobalScope;
pub const js = @import("browser/js/js.zig");
pub const dump = @import("browser/dump.zig");
diff --git a/src/server/cdp/domains/webmcp.zig b/src/server/cdp/domains/webmcp.zig
index 6a233ec1c..09ff2efe9 100644
--- a/src/server/cdp/domains/webmcp.zig
+++ b/src/server/cdp/domains/webmcp.zig
@@ -260,9 +260,7 @@ pub fn onToolAdded(
global.getJs().localScope(&ls);
defer ls.deinit();
- const frame_id = switch (global) {
- inline else => |g| g._frame_id,
- };
+ const frame_id = global.frameId();
const writer = ToolWriter{
.frame_id = id.toFrameId(frame_id),
@@ -278,9 +276,7 @@ pub fn onToolRemoved(
bc: *CDP.BrowserContext,
event: *const Notification.ModelContextToolEvent,
) !void {
- const frame_id = switch (event.exec.js.global) {
- inline else => |g| g._frame_id,
- };
+ const frame_id = event.exec.frameId();
try bc.cdp.sendEvent("WebMCP.toolsRemoved", .{
.tools = &.{
.{ .name = event.tool.name, .frameId = id.toFrameId(frame_id) },