Lightpanda: the headless browser designed for AI and automation
chore: add lp.IS_DEBUG and lp.IS_TEST
Karl Seguin6a83881634e7
diff --git a/src/App.zig b/src/App.zigindex 5eff1f64e..4f6e8dad8 100644--- a/src/App.zig+++ b/src/App.zig@@ -111,7 +111,7 @@ pub fn deinit(self: *App) void {}fn getAndMakeAppDir(allocator: Allocator) ?[]const u8 {- if (@import("builtin").is_test) {+ if (lp.IS_TEST) {return allocator.dupe(u8, "/tmp") catch unreachable;}const app_dir_path = getAppDataDir(allocator, "lightpanda") catch |err| {diff --git a/src/Arena.zig b/src/Arena.zigindex c40637eaf..91041bf56 100644--- a/src/Arena.zig+++ b/src/Arena.zig@@ -24,7 +24,6 @@const std = @import("std");const lp = @import("lightpanda");-const builtin = @import("builtin");const ArenaPool = @import("ArenaPool.zig");@@ -33,10 +32,8 @@ const ArenaAllocator = std.heap.ArenaAllocator;const Arena = @This();-const IS_DEBUG = builtin.mode == .Debug;-// In Debug, don't pool and don't retain capacity. Both can mask UAF.-pub const SAFETY = IS_DEBUG == true and builtin.is_test == false;+pub const SAFETY = lp.IS_DEBUG == true and lp.IS_TEST == false;// Amount of memory the arena hasn't reported to v8 yet. This is only tracked// when account != null.@@ -62,7 +59,7 @@ account: ?*Account,// `bytes` as of the last report() — what the account has already been told.reported: usize,-debug: if (IS_DEBUG) []const u8 else void = if (IS_DEBUG) "" else {},+debug: if (lp.IS_DEBUG) []const u8 else void = if (lp.IS_DEBUG) "" else {},pub fn allocator(self: *Arena) Allocator {return self._arena.allocator();diff --git a/src/ArenaPool.zig b/src/ArenaPool.zigindex 053d55bbe..784b7e8a9 100644--- a/src/ArenaPool.zig+++ b/src/ArenaPool.zig@@ -18,7 +18,6 @@const std = @import("std");const lp = @import("lightpanda");-const builtin = @import("builtin");const Arena = @import("Arena.zig");@@ -28,7 +27,6 @@ const ArenaAllocator = std.heap.ArenaAllocator;const ArenaPool = @This();-const IS_DEBUG = builtin.mode == .Debug;const SAFETY = Arena.SAFETY;pub const BucketSize = enum { tiny, small, medium, large };@@ -61,7 +59,7 @@ allocator: Allocator,mutex: std.Io.Mutex = .init,entry_pool: std.heap.MemoryPool(Arena),-_leak_track: if (IS_DEBUG) std.StringHashMapUnmanaged(isize) else void = if (IS_DEBUG) .empty else {},+_leak_track: if (lp.IS_DEBUG) std.StringHashMapUnmanaged(isize) else void = if (lp.IS_DEBUG) .empty else {},pub fn init(allocator: Allocator, config: Config) ArenaPool {return .{@@ -75,7 +73,7 @@ pub fn init(allocator: Allocator, config: Config) ArenaPool {}pub fn deinit(self: *ArenaPool) void {- if (IS_DEBUG) {+ if (lp.IS_DEBUG) {var has_leaks = false;var it = self._leak_track.iterator();while (it.next()) |kv| {@@ -148,7 +146,7 @@ fn _acquire(self: *ArenaPool, account: ?*Arena.Account, size_or_bucket: anytype,if (bucket.free_list) |entry| {bucket.free_list = entry.next;bucket.free_list_len -= 1;- if (IS_DEBUG) {+ if (lp.IS_DEBUG) {entry.debug = debug;const gop = try self._leak_track.getOrPut(self.allocator, debug);if (!gop.found_existing) {@@ -171,14 +169,14 @@ fn _acquire(self: *ArenaPool, account: ?*Arena.Account, size_or_bucket: anytype,.bytes = 0,.account = account,.reported = 0,- .debug = if (IS_DEBUG) debug else {},+ .debug = if (lp.IS_DEBUG) debug else {},._arena = undefined,};// Routed through the entry so it sees every node the arena takes and gives// back. entry is pool-allocated, so this pointer is stable.entry._arena = ArenaAllocator.init(entry.backing());- if (IS_DEBUG) {+ if (lp.IS_DEBUG) {const gop = try self._leak_track.getOrPut(self.allocator, debug);if (!gop.found_existing) {gop.value_ptr.* = 0;@@ -195,7 +193,7 @@ pub fn release(self: *ArenaPool, entry: *Arena) void {lp.metrics.arena_inflight.decr(bucket.size);- if (IS_DEBUG) {+ if (lp.IS_DEBUG) {self.mutex.lockUncancelable(lp.io);defer self.mutex.unlock(lp.io);if (self._leak_track.getPtr(entry.debug)) |count| {diff --git a/src/Config.zig b/src/Config.zigindex 7129f0082..ce173a4b5 100644--- a/src/Config.zig+++ b/src/Config.zig@@ -19,7 +19,6 @@const std = @import("std");const zenai = @import("zenai");const lp = @import("lightpanda");-const builtin = @import("builtin");const cli = @import("cli.zig");const dump = @import("browser/dump.zig");@@ -865,9 +864,8 @@ pub const HttpHeaders = struct {pub fn printUsageAndExit(self: *const Config, allocator: Allocator, help_for: RunMode, success: bool) !void {const exec_name = self.exec_name;const Help = @import("help.zon");- const is_debug = builtin.mode == .Debug;- const info_or_warn = if (comptime is_debug) "info" else "warn";- const pretty_or_logfmt = if (comptime is_debug) "pretty" else "logfmt";+ const info_or_warn = if (comptime lp.IS_DEBUG) "info" else "warn";+ const pretty_or_logfmt = if (comptime lp.IS_DEBUG) "pretty" else "logfmt";const comptimePrint = std.fmt.comptimePrint;const text = switch (help_for) {diff --git a/src/browser/CustomElementReactions.zig b/src/browser/CustomElementReactions.zigindex 79ef08090..b1a7b4b91 100644--- a/src/browser/CustomElementReactions.zig+++ b/src/browser/CustomElementReactions.zig@@ -44,7 +44,6 @@ const Custom = @import("webapi/element/html/Custom.zig");const String = lp.String;const Allocator = std.mem.Allocator;-const IS_DEBUG = @import("builtin").mode == .Debug;const Self = @This();@@ -96,7 +95,7 @@ fn route(self: *Self, frame: *Frame, reaction: Reaction) !void {try self.queue.append(self.allocator, reaction);return;}- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {lp.log.err(.bug, "custom element scope", .{ .note = "Missing explicit reaction scope, using fallback. This log is only generated in debug builds." });}try self.backup_queue.append(self.allocator, reaction);diff --git a/src/browser/EventManager.zig b/src/browser/EventManager.zigindex 093058175..c95810301 100644--- a/src/browser/EventManager.zig+++ b/src/browser/EventManager.zig@@ -18,7 +18,6 @@const std = @import("std");const lp = @import("lightpanda");-const builtin = @import("builtin");const js = @import("js/js.zig");const Frame = @import("Frame.zig");@@ -38,8 +37,6 @@ pub const RegisterOptions = EventManagerBase.RegisterOptions;pub const Callback = EventManagerBase.Callback;pub const Listener = EventManagerBase.Listener;-const IS_DEBUG = builtin.mode == .Debug;-pub const EventManager = @This();frame: *Frame,@@ -81,7 +78,7 @@ pub fn dispatch(self: *EventManager, target: *EventTarget, event: *Event) Dispat// Increment event count for Event Timing APIself.frame.window._performance._event_counts.increment(event._type_string.str());- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {log.debug(.event, "eventManager.dispatch", .{ .type = event._type_string.str(), .bubbles = event._bubbles });}diff --git a/src/browser/EventManagerBase.zig b/src/browser/EventManagerBase.zigindex 9b5c13464..e0aafe724 100644--- a/src/browser/EventManagerBase.zig+++ b/src/browser/EventManagerBase.zig@@ -18,7 +18,6 @@const std = @import("std");const lp = @import("lightpanda");-const builtin = @import("builtin");const js = @import("js/js.zig");const Page = @import("Page.zig");@@ -29,7 +28,6 @@ const EventTarget = @import("webapi/EventTarget.zig");const log = lp.log;const String = lp.String;const Allocator = std.mem.Allocator;-const IS_DEBUG = builtin.mode == .Debug;const EventKey = struct {event_target: usize,@@ -96,7 +94,7 @@ pub const Callback = union(enum) {// unless they need the resulting *Listener (e.g. Frame's load-listener// tracking).pub fn register(self: *EventManagerBase, target: *EventTarget, typ: []const u8, callback: Callback, opts: RegisterOptions) !?*Listener {- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {log.debug(.event, "EventManager.register", .{.type = typ,.capture = opts.capture,@@ -236,7 +234,7 @@ pub fn dispatchDirect(page: *Page,comptime opts: DispatchDirectOptions,) DispatchError!void {- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {log.debug(.event, "dispatchDirect", .{ .type = event._type_string, .context = opts.context });}diff --git a/src/browser/Factory.zig b/src/browser/Factory.zigindex 1c976427e..b400aff4d 100644--- a/src/browser/Factory.zig+++ b/src/browser/Factory.zig@@ -18,7 +18,6 @@const std = @import("std");const lp = @import("lightpanda");-const builtin = @import("builtin");const reflect = @import("reflect.zig");@@ -43,7 +42,6 @@ const log = lp.log;const String = lp.String;const assert = std.debug.assert;const Allocator = std.mem.Allocator;-const IS_DEBUG = builtin.mode == .Debug;// Shared across all frames of a Page.const Factory = @This();@@ -382,7 +380,7 @@ pub fn protoOffset(comptime T: type) usize {pub fn protoOf(value: anytype) *reflect.Proto(reflect.Struct(@TypeOf(value))).? {const T = reflect.Struct(@TypeOf(value));const proto: *reflect.Proto(T).? = @ptrFromInt(@intFromPtr(value) - comptime protoOffset(T));- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {// In debug, we'll assert that our offset and the _proto field agree.std.debug.assert(proto == if (comptime hasStoredProto(T)) value._proto else value._proto_canary);}@@ -394,7 +392,7 @@ fn setProto(ptr: anytype, proto: anytype) void {const T = reflect.Struct(@TypeOf(ptr));if (comptime hasStoredProto(T)) {ptr._proto = proto;- } else if (comptime IS_DEBUG and @hasField(T, "_proto_canary")) {+ } else if (comptime lp.IS_DEBUG and @hasField(T, "_proto_canary")) {ptr._proto_canary = proto;}}@@ -532,7 +530,7 @@ pub fn textTrackCue(self: *Factory, child: anytype) !*@TypeOf(child) {pub fn destroy(self: *Factory, value: anytype) void {const S = reflect.Struct(@TypeOf(value));- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {// We should always destroy from the leaf down.if (comptime @hasDecl(S, "_prototype_root")) {const is_leaf = if (comptime @hasField(S, "_type")) value._type == .generic else false;diff --git a/src/browser/Frame.zig b/src/browser/Frame.zigindex 77dad6cd0..542f9a4cf 100644--- a/src/browser/Frame.zig+++ b/src/browser/Frame.zig@@ -18,7 +18,6 @@const std = @import("std");const lp = @import("lightpanda");-const builtin = @import("builtin");const JS = @import("js/js.zig");const Mime = @import("Mime.zig");@@ -86,7 +85,6 @@ const log = lp.log;const String = lp.String;const IFrame = Element.Html.IFrame;const Allocator = std.mem.Allocator;-const IS_DEBUG = builtin.mode == .Debug;pub const BUF_SIZE = 1024;@@ -352,7 +350,7 @@ pub const InitOpts = struct {};pub fn init(self: *Frame, frame_id: u32, page: *Page, opts: InitOpts) !void {- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {log.debug(.frame, "frame.init", .{});}@@ -456,7 +454,7 @@ pub fn init(self: *Frame, frame_id: u32, page: *Page, opts: InitOpts) !void {document._frame = self;- if (comptime builtin.is_test == false) {+ if (comptime lp.IS_TEST == false) {if (parent == null) {// HTML test runner manually calls these as necessarytry self.js.scheduler.add(session.browser, struct {@@ -475,7 +473,7 @@ pub fn deinit(self: *Frame) void {frame.deinit();}- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {log.debug(.frame, "frame.deinit", .{ .url = self.url, .type = self._type });// Uncomment if you want slab statistics to print.@@ -1210,7 +1208,7 @@ fn _documentIsComplete(self: *Frame) !void {try self._event_manager.dispatchDirect(window_target, pageshow_event, self.window._on_pageshow, .{ .context = "page show" });}- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {log.debug(.frame, "load", .{ .url = self.url, .type = self._type });}@@ -1221,7 +1219,7 @@ fn notifyParentLoadComplete(self: *Frame) void {const parent = self.parent orelse return;if (self._parent_notified == true) {- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {std.debug.assert(false);}// shouldn't happen, don't want to crash a release build over it@@ -1271,7 +1269,7 @@ fn frameHeaderDoneCallback(transfer: *HttpClient.Transfer) !HttpClient.Transfer.self.window._location.releaseRef(self._page);self.window._location = location;- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {log.debug(.frame, "navigate header", .{.url = self.url,.status = transfer.responseStatus(),@@ -1487,7 +1485,7 @@ fn frameDataCallback(transfer: *HttpClient.Transfer, data: []const u8) !void {}}- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {log.debug(.frame, "navigate first chunk", .{.content_type = mime.content_type,.len = data.len,@@ -1579,7 +1577,7 @@ fn frameDataCallback(transfer: *HttpClient.Transfer, data: []const u8) !void {fn frameDoneCallback(ctx: *anyopaque) !void {var self: *Frame = @ptrCast(@alignCast(ctx));- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {log.debug(.frame, "navigate done", .{ .type = self._type, .url = self.url });}@@ -1591,7 +1589,7 @@ fn frameDoneCallback(ctx: *anyopaque) !void {self._pending_content_type = null;}- defer if (comptime IS_DEBUG) {+ defer if (comptime lp.IS_DEBUG) {log.debug(.frame, "frame load complete", .{.url = self.url,.type = self._type,@@ -2009,7 +2007,7 @@ fn getElementIdMap(frame: *Frame, node: *Node) ElementIdMaps {};}// Detached nodes should not have IDs registered- if (IS_DEBUG) {+ if (lp.IS_DEBUG) {std.debug.assert(false);}return .{diff --git a/src/browser/Page.zig b/src/browser/Page.zigindex 597c0ba47..f55e68d4f 100644--- a/src/browser/Page.zig+++ b/src/browser/Page.zig@@ -18,7 +18,6 @@const std = @import("std");const lp = @import("lightpanda");-const builtin = @import("builtin");const js = @import("js/js.zig");@@ -31,7 +30,6 @@ const Blob = @import("webapi/Blob.zig");const SharedWorkerGlobalScope = @import("webapi/SharedWorkerGlobalScope.zig");const Allocator = std.mem.Allocator;-const IS_DEBUG = builtin.mode == .Debug;// A Page is the container for a root Frame and all of its descendants// (nested iframes). It owns the resources that share the lifetime of the root@@ -187,7 +185,7 @@ pub fn deinit(self: *Page) void {self.shared_workers = .empty;{- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {std.debug.assert(self.blob_urls.count() == 0);}@@ -217,7 +215,7 @@ pub fn deinit(self: *Page) void {self.globals.deinit();- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {std.debug.assert(self.origins.count() == 0);}// Defensive cleanup in case origins leaked.diff --git a/src/browser/ScriptManager.zig b/src/browser/ScriptManager.zigindex a0b4ae485..b0a91ba16 100644--- a/src/browser/ScriptManager.zig+++ b/src/browser/ScriptManager.zig@@ -18,7 +18,6 @@const std = @import("std");const lp = @import("lightpanda");-const builtin = @import("builtin");const HttpClient = @import("../network/HttpClient.zig");@@ -31,7 +30,6 @@ const Element = @import("webapi/Element.zig");const log = lp.log;const Allocator = std.mem.Allocator;-const IS_DEBUG = builtin.mode == .Debug;const ScriptManager = @This();@@ -132,7 +130,7 @@ pub fn preloadScript(self: *ScriptManager, element: ?*Element.Html, url: []consttry self.preloaded_scripts.putNoClobber(self.base.allocator, owned_url, .{ .state = .{ .loading = script } });errdefer _ = self.preloaded_scripts.remove(owned_url);- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {log.debug(.http, "script queue", .{ .url = owned_url, .ctx = "preload" });}@@ -270,7 +268,7 @@ pub fn addFromElement(self: *ScriptManager, comptime from_parser: bool, script_ebreak :blk .normal;};- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {var ls: js.Local.Scope = undefined;frame.js.localScope(&ls);defer ls.deinit();@@ -296,7 +294,7 @@ pub fn addFromElement(self: *ScriptManager, comptime from_parser: bool, script_epreloaded = self.base.takeModuleHint(remote_url);}if (preloaded) |pre| {- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {log.debug(.http, "script adopt", .{ .url = remote_url, .ctx = ctx, .state = if (pre.complete) "done" else "loading" });}pre.extra = frame_extra;@@ -520,7 +518,7 @@ const PreloadedScript = struct {return Script.doneCallback(ctx);}script.complete = true;- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {log.debug(.http, "script fetch complete", .{ .req = script.url });}diff --git a/src/browser/ScriptManagerBase.zig b/src/browser/ScriptManagerBase.zigindex be2e9a7a5..e3edb7d1b 100644--- a/src/browser/ScriptManagerBase.zig+++ b/src/browser/ScriptManagerBase.zig@@ -18,7 +18,6 @@const std = @import("std");const lp = @import("lightpanda");-const builtin = @import("builtin");const http = @import("../network/http.zig");const HttpClient = @import("../network/HttpClient.zig");@@ -34,7 +33,6 @@ const Element = @import("webapi/Element.zig");const log = lp.log;const String = lp.String;const Allocator = std.mem.Allocator;-const IS_DEBUG = builtin.mode == .Debug;const ScriptManagerBase = @This();@@ -251,7 +249,7 @@ pub fn preloadImport(self: *ScriptManagerBase, url: [:0]const u8, referrer: []cogop.value_ptr.* = .{ .state = .{ .loading = script }, .hint = opts.hint };- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {var ls: js.Local.Scope = undefined;self.owner.jsContext().localScope(&ls);defer ls.deinit();@@ -399,7 +397,7 @@ pub fn getAsyncImport(self: *ScriptManagerBase, url: [:0]const u8, cb: ImportAsy// fetch is in flight, take the script and turn it into// our normal getAsyncImport flow (e.g. what we do at the// end of this file as-if imported_modules didn't have this script)- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {log.debug(.http, "script adopt", .{ .url = url, .ctx = "dynamic module", .state = "loading" });}script.extra = .{ .import_async = .{ .callback = cb, .data = cb_data } };@@ -411,7 +409,7 @@ pub fn getAsyncImport(self: *ScriptManagerBase, url: [:0]const u8, cb: ImportAsy// ready_scripts flow. evaluate() runs it now, or — if an// evaluation window is open — evaluate_pending runs it// when that window closes.- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {log.debug(.http, "script adopt", .{ .url = url, .ctx = "dynamic module", .state = "done" });}script.extra = .{ .import_async = .{ .callback = cb, .data = cb_data } };@@ -443,7 +441,7 @@ pub fn getAsyncImport(self: *ScriptManagerBase, url: [:0]const u8, cb: ImportAsy} },};- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {var ls: js.Local.Scope = undefined;self.owner.jsContext().localScope(&ls);defer ls.deinit();@@ -724,7 +722,7 @@ pub const Script = struct {return .abort;}- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {log.debug(.http, "script header", .{.req = transfer,.status = transfer.responseStatus(),@@ -797,7 +795,7 @@ pub const Script = struct {pub fn doneCallback(ctx: *anyopaque) !void {const self: *Script = @ptrCast(@alignCast(ctx));self.complete = true;- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {log.debug(.http, "script fetch complete", .{ .req = self.url });}@@ -976,7 +974,7 @@ pub const Script = struct {break :blk true;};- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {log.debug(.browser, "executed script", .{ .src = url, .success = success });}diff --git a/src/browser/Session.zig b/src/browser/Session.zigindex 9b318e217..f1948c5cf 100644--- a/src/browser/Session.zig+++ b/src/browser/Session.zig@@ -18,7 +18,6 @@const std = @import("std");const lp = @import("lightpanda");-const builtin = @import("builtin");const App = @import("../App.zig");@@ -39,7 +38,6 @@ const SharedWorkerGlobalScope = @import("webapi/SharedWorkerGlobalScope.zig");const log = lp.log;const ArenaPool = App.ArenaPool;-const IS_DEBUG = builtin.mode == .Debug;// A Session represents a browsing context group (cookie jar, session storage,// navigation history) within a Browser. It owns a set of live Pages — each a@@ -361,7 +359,7 @@ pub fn createPage(self: *Session) !PageHandle {// Drain any pending Page deinits now, while we're at a known-safe pointself.processDestroyQueues();- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {log.debug(.browser, "create page", .{});}@@ -433,7 +431,7 @@ pub fn pendingOrLivePage(self: *Session, frame_id: u32) ?*Page {pub fn replacementOf(self: *Session, page: *Page) ?*Page {const replacement = page.replacement;- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {// quick check to make sure our replacement <=> replaces link is in syncvar found: ?*Page = null;for (self.pages.items) |p| {@@ -457,7 +455,7 @@ pub fn primaryPage(self: *Session) ?PageHandle {return null;}const page = self.pages.items[0];- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {std.debug.assert(page.replaces == null);}return .{ .session = self, .frame_id = page.frame._frame_id };@@ -473,7 +471,7 @@ pub fn currentFrame(self: *Session) ?*Frame {return null;}const page = self.pages.items[0];- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {std.debug.assert(page.replaces == null);}return &page.frame;@@ -799,7 +797,7 @@ fn processRootQueuedNavigation(self: *Session, page: *Page) !void {fn replaceRootImmediate(self: *Session, frame_id: u32, url: [:0]const u8, opts: Frame.NavigateOpts) !void {if (self.livePage(frame_id)) |page| {self.tearDownPage(page);- } else if (comptime IS_DEBUG) {+ } else if (comptime lp.IS_DEBUG) {lp.assert(false, "Session.replaceRootImmediate - no live page", .{});}const new_frame = try self.installNewActivePage(frame_id);@@ -847,7 +845,7 @@ pub fn initiateRootNavigation(self: *Session, frame_id: u32, url: [:0]const u8,try self.pages.append(self.arena.allocator(), page);errdefer _ = self.pages.pop();- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {log.debug(.browser, "initiate root navigation", .{ .url = url });}@@ -888,7 +886,7 @@ pub fn commitPendingPage(self: *Session, replacement: *Page) !void {lp.assert(false, "Session.commitPendingPage - page has no replaces", .{});};- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {log.debug(.browser, "commit pending page", .{});}@@ -926,7 +924,7 @@ pub fn commitPendingPage(self: *Session, replacement: *Page) !void {// (HTTP error before commit, session deinit during pending, etc.). The// active page is untouched.pub fn discardPendingPage(self: *Session, replacement: *Page) void {- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {log.debug(.browser, "discard pending page", .{});}diff --git a/src/browser/StyleManager.zig b/src/browser/StyleManager.zigindex b45ea556a..b054de4f3 100644--- a/src/browser/StyleManager.zig+++ b/src/browser/StyleManager.zig@@ -17,7 +17,6 @@// along with this program. If not, see <https://www.gnu.org/licenses/>.const std = @import("std");-const builtin = @import("builtin");const lp = @import("lightpanda");const Frame = @import("Frame.zig");@@ -92,8 +91,6 @@ pub fn deinit(self: *StyleManager) void {self.arena.release();}-const IS_DEBUG = builtin.mode == .Debug;-/// Hard cap on `@media` / `@layer` nesting depth. CSS allows arbitrarily-deep/// at-rule nesting; without a cap a hostile inline stylesheet could blow the/// Zig stack via the mutually-recursive `applyMediaAtRule` / `applyLayerAtRule`@@ -285,7 +282,7 @@ fn registerLayerPath(self: *StyleManager, build_arena: Allocator, parent: u16, dvar it = std.mem.splitScalar(u8, dotted, '.');while (it.next()) |component| {// should have been verified by the caller, via isValidLayerName- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {std.debug.assert(isValidLayerComponent(component));}diff --git a/src/browser/css/Tokenizer.zig b/src/browser/css/Tokenizer.zigindex 4348745ba..d87eb38c1 100644--- a/src/browser/css/Tokenizer.zig+++ b/src/browser/css/Tokenizer.zig@@ -27,7 +27,7 @@//! See spec for more info: https://drafts.csswg.org/css-syntax/#tokenizationconst std = @import("std");-const builtin = @import("builtin");+const lp = @import("lightpanda");const assert = std.debug.assert;const Tokenizer = @This();@@ -228,7 +228,7 @@ fn sliceFrom(self: *const Tokenizer, start_pos: usize) []const u8 {// over ASCII bytes (excluding newlines), or UTF-8 sequence// leaders (excluding leaders for 4-byte sequences).fn advance(self: *Tokenizer, n: usize) void {- if (builtin.mode == .Debug) {+ if (lp.IS_DEBUG) {// Each byte must either be an ASCII byte or a sequence leader,// but not a 4-byte leader; also newlines are rejected.for (0..n) |i| {diff --git a/src/browser/dump.zig b/src/browser/dump.zigindex fc197bea0..9d5247745 100644--- a/src/browser/dump.zig+++ b/src/browser/dump.zig@@ -17,13 +17,12 @@// along with this program. If not, see <https://www.gnu.org/licenses/>.const std = @import("std");+const lp = @import("lightpanda");const Frame = @import("Frame.zig");const Node = @import("webapi/Node.zig");const Slot = @import("webapi/element/html/Slot.zig");const IFrame = @import("webapi/element/html/IFrame.zig");-const IS_DEBUG = @import("builtin").mode == .Debug;-pub const Opts = struct {with_base: bool = false,with_frames: bool = false,@@ -145,7 +144,7 @@ fn _deep(node: *Node, opts: Opts, comptime force_slot: bool, writer: *std.Io.Wriif (iframe.getContentDocument()) |doc| {// A frame's document should always ahave a frame, but// I'm not willing to crash a release build on that assertion.- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {std.debug.assert(doc._frame != null);}if (doc._frame) |f| {diff --git a/src/browser/frame/user_input.zig b/src/browser/frame/user_input.zigindex 534b6ae95..385919b5b 100644--- a/src/browser/frame/user_input.zig+++ b/src/browser/frame/user_input.zig@@ -24,7 +24,6 @@const std = @import("std");const lp = @import("lightpanda");-const builtin = @import("builtin");const Frame = @import("../Frame.zig");const js = @import("../js/js.zig");@@ -38,7 +37,6 @@ const WheelEvent = @import("../webapi/event/WheelEvent.zig");const KeyboardEvent = @import("../webapi/event/KeyboardEvent.zig");const log = lp.log;-const IS_DEBUG = builtin.mode == .Debug;// DOM MouseEvent.button values.// https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button@@ -68,7 +66,7 @@ fn dispatchMouseEventOn(frame: *Frame, target: *Element, comptime typ: []const upub fn triggerMousePress(frame: *Frame, x: f64, y: f64, button: i32) !void {const target = (try frame.window._document.elementFromPoint(x, y, frame)) orelse return;- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {log.debug(.frame, "frame mouse press", .{.url = frame.url,.node = target,@@ -84,7 +82,7 @@ pub fn triggerMousePress(frame: *Frame, x: f64, y: f64, button: i32) !void {pub fn triggerMouseMove(frame: *Frame, x: f64, y: f64) !void {const target = (try frame.window._document.elementFromPoint(x, y, frame)) orelse return;- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {log.debug(.frame, "frame mouse move", .{.url = frame.url,.node = target,@@ -122,7 +120,7 @@ pub fn triggerMouseMove(frame: *Frame, x: f64, y: f64) !void {pub fn triggerMouseRelease(frame: *Frame, x: f64, y: f64, button: i32, click_count: i32) !void {const target = (try frame.window._document.elementFromPoint(x, y, frame)) orelse return;- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {log.debug(.frame, "frame mouse release", .{.url = frame.url,.node = target,@@ -154,7 +152,7 @@ pub fn triggerMouseRelease(frame: *Frame, x: f64, y: f64, button: i32, click_coupub fn triggerMouseWheel(frame: *Frame, x: f64, y: f64, delta_x: f64, delta_y: f64) !void {const target = (try frame.window._document.elementFromPoint(x, y, frame)) orelse return;- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {log.debug(.frame, "frame mouse wheel", .{.url = frame.url,.node = target,@@ -423,7 +421,7 @@ pub fn triggerKeyboard(frame: *Frame, keyboard_event: *KeyboardEvent) !void {return;};- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {log.debug(.frame, "frame keydown", .{.url = frame.url,.node = element,diff --git a/src/browser/js/Caller.zig b/src/browser/js/Caller.zigindex 4e9deed75..9a993051a 100644--- a/src/browser/js/Caller.zig+++ b/src/browser/js/Caller.zig@@ -35,7 +35,6 @@ const log = lp.log;const ArenaAllocator = std.heap.ArenaAllocator;const CALL_ARENA_RETAIN = 1024 * 16;const LOCAL_ARENA_RETAIN = 1024 * 16;-const IS_DEBUG = @import("builtin").mode == .Debug;const Caller = @This();@@ -110,7 +109,7 @@ pub fn deinit(self: *Caller) void {// to avoid realloc churn.{const local_arena: *ArenaAllocator = @ptrCast(@alignCast(ctx.local_arena.ptr));- _ = local_arena.reset(if (comptime IS_DEBUG) .free_all else .{ .retain_with_limit = LOCAL_ARENA_RETAIN });+ _ = local_arena.reset(if (comptime lp.IS_DEBUG) .free_all else .{ .retain_with_limit = LOCAL_ARENA_RETAIN });}ctx.call_depth = call_depth;@@ -176,7 +175,7 @@ fn _constructor(self: *Caller, func: anytype, info: FunctionCallbackInfo, compticonst prototype_handle = v8.v8__Object__GetPrototype(new_this_handle).?;var out: v8.MaybeBool = undefined;v8.v8__Object__SetPrototype(this.handle, self.local.handle, prototype_handle, &out);- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {std.debug.assert(out.has_value and out.value);}}@@ -562,7 +561,7 @@ fn protoNode(comptime T: type, instance: *T) *@import("../webapi/Node.zig") {fn handleError(comptime T: type, comptime F: type, local: *const Local, err: anyerror, info: anytype) void {const isolate = local.isolate;- if (comptime IS_DEBUG and @TypeOf(info) == FunctionCallbackInfo) {+ if (comptime lp.IS_DEBUG and @TypeOf(info) == FunctionCallbackInfo) {if (log.enabled(.js, .debug)) {const DOMException = @import("../webapi/DOMException.zig");if (DOMException.fromError(err) == null) {@@ -930,7 +929,7 @@ pub const Function = struct {// the receiver doesn't have expected internal fields (e.g., global// proxy vs global object, cross-context scenarios).if (v8.v8__Object__InternalFieldCount(js_this) <= idx) {- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {std.debug.assert(false);}return false;diff --git a/src/browser/js/Context.zig b/src/browser/js/Context.zigindex f5f90499f..0b31c8b6c 100644--- a/src/browser/js/Context.zig+++ b/src/browser/js/Context.zig@@ -34,7 +34,6 @@ const v8 = js.v8;const log = lp.log;const Caller = js.Caller;const Allocator = std.mem.Allocator;-const IS_DEBUG = @import("builtin").mode == .Debug;// Loosely maps to a Browser Page or Worker.const Context = @This();@@ -152,7 +151,7 @@ scheduler: Scheduler,// interface that works in both Page and Worker contexts.execution: Execution,-unknown_properties: (if (IS_DEBUG) std.StringHashMapUnmanaged(UnknownPropertyStat) else void) = if (IS_DEBUG) .{} else {},+unknown_properties: (if (lp.IS_DEBUG) std.StringHashMapUnmanaged(UnknownPropertyStat) else void) = if (lp.IS_DEBUG) .{} else {},const ModuleEntry = struct {// Can be null if we're asynchronously loading the module, in@@ -193,7 +192,7 @@ pub fn fromIsolate(isolate: js.Isolate) ?struct { *Context, *const v8.Context }}pub fn deinit(self: *Context) void {- if (comptime IS_DEBUG and @import("builtin").is_test == false) {+ if (comptime lp.IS_DEBUG and lp.IS_TEST == false) {var it = self.unknown_properties.iterator();while (it.next()) |kv| {log.debug(.unknown_prop, "unknown property", .{@@ -408,7 +407,7 @@ pub fn module(self: *Context, comptime want_result: bool, local: *const js.Localfn evaluateModule(self: *Context, comptime want_result: bool, mod: js.Module, url: []const u8, cacheable: bool) !(if (want_result) ModuleEntry else void) {const evaluated = mod.evaluate() catch {- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {std.debug.assert(mod.getStatus() == .kErrored);}@@ -420,7 +419,7 @@ fn evaluateModule(self: *Context, comptime want_result: bool, mod: js.Module, urbreak :blk e.toSlice() catch "???";};const stack = blk: {- if (comptime IS_DEBUG == false) {+ if (comptime lp.IS_DEBUG == false) {// SetCaptureStackTraceForUncaughtExceptions is only set in Debugbreak :blk "";}@@ -885,7 +884,7 @@ fn _dynamicModuleCallback(self: *Context, specifier: [:0]const u8, referrer: []c}const evaluated = mod.evaluate() catch {- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {std.debug.assert(mod.getStatus() == .kErrored);}_ = resolver.reject("module evaluation", local.newString("Module evaluation failed"));@@ -956,7 +955,7 @@ fn resolveDynamicModule(self: *Context, state: *DynamicModuleResolveState, modul// we have a resolve loading this asynchronously.lp.assert(module_entry.module_promise != null, "Context.resolveDynamicModule has module_promise", .{});lp.assert(module_entry.resolver_promise != null, "Context.resolveDynamicModule has resolver_promise", .{});- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {std.debug.assert(self.module_cache.contains(state.specifier));}state.module = module_entry.module.?;@@ -1157,7 +1156,7 @@ pub fn queueMicrotaskFunc(self: *Context, cb: js.Function) void {// == Profiler ==pub fn startCpuProfiler(self: *Context) void {- if (comptime !IS_DEBUG) {+ if (comptime !lp.IS_DEBUG) {// Still testing this out, don't have it properly exposed, so add this// guard for the time being to prevent any accidental/weird prod issues.@compileError("CPU Profiling is only available in debug builds");@@ -1188,7 +1187,7 @@ pub fn stopCpuProfiler(self: *Context) ![]const u8 {}pub fn startHeapProfiler(self: *Context) void {- if (comptime !IS_DEBUG) {+ if (comptime !lp.IS_DEBUG) {@compileError("Heap Profiling is only available in debug builds");}diff --git a/src/browser/js/Env.zig b/src/browser/js/Env.zigindex 0407af56f..77dc8780b 100644--- a/src/browser/js/Env.zig+++ b/src/browser/js/Env.zig@@ -18,7 +18,6 @@const std = @import("std");const lp = @import("lightpanda");-const builtin = @import("builtin");const js = @import("js.zig");const bridge = @import("bridge.zig");@@ -39,7 +38,6 @@ const log = lp.log;const JsApis = bridge.JsApis;const Allocator = std.mem.Allocator;-const IS_DEBUG = builtin.mode == .Debug;const MAX_CONTEXTS = if (lp.build_config.wpt_extensions) 8192 else 128;@@ -109,7 +107,7 @@ pub const InitOpts = struct {};pub fn init(app: *App, opts: InitOpts) !Env {- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {comptime {// V8 requirement for any data using SetAlignedPointerInInternalFieldconst a = @alignOf(@import("TaggedOpaque.zig"));@@ -151,7 +149,7 @@ pub fn init(app: *App, opts: InitOpts) !Env {v8.v8__Isolate__SetFatalErrorHandler(isolate_handle, fatalCallback);v8.v8__Isolate__SetOOMErrorHandler(isolate_handle, oomCallback);- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {v8.v8__Isolate__SetCaptureStackTraceForUncaughtExceptions(isolate_handle, true, 64);}@@ -209,7 +207,7 @@ pub fn init(app: *App, opts: InitOpts) !Env {}pub fn deinit(self: *Env) void {- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {std.debug.assert(self.contexts.items.len == 0);}for (self.contexts.items) |ctx| {@@ -391,7 +389,7 @@ pub fn destroyContext(self: *Env, context: *Context) void {break;}} else {- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {@panic("Tried to remove unknown context");}}@@ -444,7 +442,7 @@ pub fn runMacrotasks(self: *Env) !void {var i: usize = 0;while (i < self.contexts.items.len) : (i += 1) {const ctx = self.contexts.items[i];- if (comptime builtin.is_test == false) {+ if (comptime lp.IS_TEST == false) {// I hate this comptime check as much as you do. But we have tests// which rely on short execution before shutdown. In real world, it's// underterministic whether a timer will or won't run before thediff --git a/src/browser/js/Function.zig b/src/browser/js/Function.zigindex 83fb86c57..c0d8c7b1d 100644--- a/src/browser/js/Function.zig+++ b/src/browser/js/Function.zig@@ -22,7 +22,6 @@ const js = @import("js.zig");const v8 = js.v8;const log = lp.log;-const IS_DEBUG = @import("builtin").mode == .Debug;const Function = @This();@@ -52,7 +51,7 @@ pub fn withThis(self: *const Function, value: anytype) !Function {pub fn newInstance(self: *const Function, caught: *js.TryCatch.Caught) !js.Object {const local = self.local;- if (comptime IS_DEBUG == false) {+ if (comptime lp.IS_DEBUG == false) {// This should not be possible, yet it happens. In Release, we'll log an// error and hope for the best. In Debug, we'll let the code execute// and v8 will crash on the null reference. This null value almost@@ -142,7 +141,7 @@ fn _tryCallWithThis(self: *const Function, comptime T: type, this: anytype, argscaught.* = .{};const local = self.local;- if (comptime IS_DEBUG == false) {+ if (comptime lp.IS_DEBUG == false) {// This should not be possible, yet it happens. In Release, we'll log an// error and hope for the best. In Debug, we'll let the code execute// and v8 will crash on the null reference. This null value almostdiff --git a/src/browser/js/Inspector.zig b/src/browser/js/Inspector.zigindex 0bc818728..7190260fd 100644--- a/src/browser/js/Inspector.zig+++ b/src/browser/js/Inspector.zig@@ -17,6 +17,7 @@// along with this program. If not, see <https://www.gnu.org/licenses/>.const std = @import("std");+const lp = @import("lightpanda");const js = @import("js.zig");const v8 = js.v8;@@ -26,7 +27,6 @@ const Allocator = std.mem.Allocator;const CONTEXT_GROUP_ID = 1;const CLIENT_TRUST_LEVEL = 1;-const IS_DEBUG = @import("builtin").mode == .Debug;// Inspector exists for the lifetime of the Isolate/Env. 1 Isolate = 1 Inspector.// It combines the v8.Inspector and the v8.InspectorClientImpl. The v8.InspectorClientImpl@@ -81,7 +81,7 @@ pub fn deinit(self: *const Inspector, allocator: Allocator) void {}pub fn startSession(self: *Inspector, ctx: anytype) *Session {- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {std.debug.assert(self.session == null);}diff --git a/src/browser/js/Local.zig b/src/browser/js/Local.zigindex e8d7bcab7..e84766246 100644--- a/src/browser/js/Local.zig+++ b/src/browser/js/Local.zig@@ -36,7 +36,6 @@ const v8 = js.v8;const log = lp.log;const CallOpts = Caller.CallOpts;const FinalizerCallback = js.FinalizerCallback;-const IS_DEBUG = @import("builtin").mode == .Debug;// Where js.Context has a lifetime tied to the frame, and holds the// v8::Global<v8::Context>, this has a much shorter lifetime and holds a@@ -1296,7 +1295,7 @@ pub fn resolveValue(value: anytype) Resolved {}fn resolveT(comptime T: type, value: *T) Resolved {- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {assertChainContiguity(T, value);}const Meta = T.JsApi.Meta;@@ -1362,7 +1361,7 @@ fn resolveT(comptime T: type, value: *T) Resolved {prev = n;node = n.next;} else {- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {std.debug.assert(false);}}diff --git a/src/browser/js/Object.zig b/src/browser/js/Object.zigindex 8869a9060..f0102fc3c 100644--- a/src/browser/js/Object.zig+++ b/src/browser/js/Object.zig@@ -17,11 +17,10 @@// along with this program. If not, see <https://www.gnu.org/licenses/>.const std = @import("std");+const lp = @import("lightpanda");const js = @import("js.zig");const v8 = js.v8;-const IS_DEBUG = @import("builtin").mode == .Debug;-const Object = @This();local: *const js.Local,@@ -84,7 +83,7 @@ pub fn toValue(self: Object) js.Value {}pub fn format(self: Object, writer: *std.Io.Writer) !void {- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {return self.local.ctx.debugValue(self.toValue(), writer);}const str = self.toString() catch return error.WriteFailed;diff --git a/src/browser/js/Scheduler.zig b/src/browser/js/Scheduler.zigindex b564991f3..9638ff29d 100644--- a/src/browser/js/Scheduler.zig+++ b/src/browser/js/Scheduler.zig@@ -18,10 +18,8 @@const std = @import("std");const lp = @import("lightpanda");-const builtin = @import("builtin");const log = lp.log;-const IS_DEBUG = builtin.mode == .Debug;const Queue = std.PriorityQueue(Task, void, struct {fn compare(_: void, a: Task, b: Task) std.math.Order {@@ -73,7 +71,7 @@ const AddOpts = struct {finalizer: ?Finalizer = null,};pub fn add(self: *Scheduler, ctx: *anyopaque, cb: Callback, run_in_ms: u32, opts: AddOpts) !void {- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {log.debug(.scheduler, "scheduler.add", .{ .name = opts.name, .run_in_ms = run_in_ms, .low_priority = opts.low_priority });}var queue = if (opts.low_priority) &self.low_priority else &self.high_priority;@@ -124,7 +122,7 @@ fn runQueue(self: *Scheduler, queue: *Queue) !void {return;}var task = queue.pop().?;- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {log.debug(.scheduler, "scheduler.runTask", .{ .name = task.name });}@@ -137,7 +135,7 @@ fn runQueue(self: *Scheduler, queue: *Queue) !void {if (repeat_in_ms) |ms| {// Task cannot be repeated immediately, and they should know that- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {std.debug.assert(ms != 0);}task.run_at = now + ms;diff --git a/src/browser/js/Snapshot.zig b/src/browser/js/Snapshot.zigindex 06b7d52de..14edf454c 100644--- a/src/browser/js/Snapshot.zig+++ b/src/browser/js/Snapshot.zig@@ -35,8 +35,6 @@ const PageJsApis = bridge.PageJsApis;const SharedWorkerJsApis = bridge.SharedWorkerJsApis;const DedicatedWorkerJsApis = bridge.DedicatedWorkerJsApis;-const IS_DEBUG = @import("builtin").mode == .Debug;-const Snapshot = @This();const Caller = @import("Caller.zig");@@ -476,7 +474,7 @@ fn countExternalReferences() comptime_int {}}- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {inline for (JsApis) |JsApi| {if (!hasNamedIndexedGetter(JsApi)) {count += 1;@@ -594,7 +592,7 @@ fn collectExternalReferences() [countExternalReferences()]isize {}}- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {inline for (JsApis) |JsApi| {if (!hasNamedIndexedGetter(JsApi)) {references[idx] = @bitCast(@intFromPtr(bridge.unknownObjectPropertyCallback(JsApi)));@@ -905,7 +903,7 @@ fn attachClass(comptime JsApi: type, comptime flatten: bool, isolate: *v8.Isolatv8.v8__Template__Set(@ptrCast(instance), js_name, js_value, v8.ReadOnly + v8.DontDelete);}- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {if (!has_named_index_getter) {var configuration: v8.NamedPropertyHandlerConfiguration = .{.getter = bridge.unknownObjectPropertyCallback(JsApi),diff --git a/src/browser/js/String.zig b/src/browser/js/String.zigindex 0ff474438..1778b85e4 100644--- a/src/browser/js/String.zig+++ b/src/browser/js/String.zig@@ -22,7 +22,6 @@ const lp = @import("lightpanda");const js = @import("js.zig");const Allocator = std.mem.Allocator;-const IS_DEBUG = @import("builtin").mode == .Debug;const v8 = js.v8;@@ -73,7 +72,7 @@ fn _toSlice(self: String, comptime null_terminate: bool, allocator: Allocator) !const l = v8.v8__String__Utf8Length(handle, isolate);const buf = try (if (comptime null_terminate) allocator.allocSentinel(u8, @intCast(l), 0) else allocator.alloc(u8, @intCast(l)));const n = v8.v8__String__WriteUtf8(handle, isolate, buf.ptr, buf.len, v8.NO_NULL_TERMINATION | v8.REPLACE_INVALID_UTF8);- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {std.debug.assert(n == l);}@@ -95,7 +94,7 @@ pub fn toSSOWithAlloc(self: String, allocator: Allocator) !lp.String {if (l <= 12) {var content: [12]u8 = undefined;const n = v8.v8__String__WriteUtf8(handle, isolate, &content[0], content.len, v8.NO_NULL_TERMINATION | v8.REPLACE_INVALID_UTF8);- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {std.debug.assert(n == l);}// Weird that we do this _after_, but we have to..I've seen weird issues@@ -107,7 +106,7 @@ pub fn toSSOWithAlloc(self: String, allocator: Allocator) !lp.String {const buf = try allocator.alloc(u8, l);const n = v8.v8__String__WriteUtf8(handle, isolate, buf.ptr, buf.len, v8.NO_NULL_TERMINATION | v8.REPLACE_INVALID_UTF8);- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {std.debug.assert(n == l);}diff --git a/src/browser/js/TryCatch.zig b/src/browser/js/TryCatch.zigindex 73681ed41..6a2e23b38 100644--- a/src/browser/js/TryCatch.zig+++ b/src/browser/js/TryCatch.zig@@ -23,7 +23,6 @@ const js = @import("js.zig");const v8 = js.v8;const Allocator = std.mem.Allocator;-const IS_DEBUG = @import("builtin").mode == .Debug;const TryCatch = @This();@@ -40,7 +39,7 @@ pub fn hasCaught(self: TryCatch) bool {}pub fn rethrow(self: *TryCatch) void {- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {std.debug.assert(self.hasCaught());}_ = v8.v8__TryCatch__ReThrow(&self.handle);diff --git a/src/browser/js/Value.zig b/src/browser/js/Value.zigindex e77eb3d58..5dcac824d 100644--- a/src/browser/js/Value.zig+++ b/src/browser/js/Value.zig@@ -25,8 +25,6 @@ const TaggedOpaque = @import("TaggedOpaque.zig");const v8 = js.v8;const bridge = js.bridge;-const IS_DEBUG = @import("builtin").mode == .Debug;-const Allocator = std.mem.Allocator;const Value = @This();@@ -274,7 +272,7 @@ pub fn toU32(self: Value) !u32 {}pub fn toPromise(self: Value) js.Promise {- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {std.debug.assert(self.isPromise());}return .{@@ -648,7 +646,7 @@ pub fn toZig(self: Value, comptime T: type) !T {}pub fn toObject(self: Value) js.Object {- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {std.debug.assert(self.isObject());}@@ -659,7 +657,7 @@ pub fn toObject(self: Value) js.Object {}pub fn toArray(self: Value) js.Array {- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {std.debug.assert(self.isArray());}@@ -670,7 +668,7 @@ pub fn toArray(self: Value) js.Array {}pub fn toBigInt(self: Value) js.BigInt {- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {std.debug.assert(self.isBigInt());}@@ -680,7 +678,7 @@ pub fn toBigInt(self: Value) js.BigInt {}pub fn format(self: Value, writer: *std.Io.Writer) !void {- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {return self.local.debugValue(self, writer);}const js_str = self.toString() catch return error.WriteFailed;diff --git a/src/browser/js/bridge.zig b/src/browser/js/bridge.zigindex 10909f24e..a7b0a13e6 100644--- a/src/browser/js/bridge.zig+++ b/src/browser/js/bridge.zig@@ -28,7 +28,6 @@ const Caller = @import("Caller.zig");const Context = @import("Context.zig");const v8 = js.v8;-const IS_DEBUG = @import("builtin").mode == .Debug;pub fn Builder(comptime T: type) type {return struct {@@ -671,7 +670,7 @@ pub fn unknownWindowPropertyCallback(c_name: ?*const v8.Name, handle: ?*const v8.worker => {}, // no global lookup in a worker}- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {if (std.mem.startsWith(u8, property, "__")) {// some frameworks will extend built-in types using a __ prefix// these should always be safe to ignore.@@ -717,7 +716,7 @@ pub fn unknownWindowPropertyCallback(c_name: ?*const v8.Name, handle: ?*const v8// Only used for debuggingpub fn unknownObjectPropertyCallback(comptime JsApi: type) *const fn (?*const v8.Name, ?*const v8.PropertyCallbackInfo) callconv(.c) u32 {- if (comptime !IS_DEBUG) {+ if (comptime !lp.IS_DEBUG) {@compileError("unknownObjectPropertyCallback should only be used in debug builds");}diff --git a/src/browser/parser/Parser.zig b/src/browser/parser/Parser.zigindex b95e4715b..1de032884 100644--- a/src/browser/parser/Parser.zig+++ b/src/browser/parser/Parser.zig@@ -29,7 +29,6 @@ pub const AttributeIterator = h5e.AttributeIterator;const Allocator = std.mem.Allocator;const TERMINATE_CHECK_INTERVAL = 1024;-const IS_DEBUG = @import("builtin").mode == .Debug;pub const ParsedNode = struct {node: *Node,@@ -682,7 +681,7 @@ fn _appendCallback(self: *Parser, parent: *Node, node_or_text: h5e.NodeOrText) !// in the wild, and I'm not sure why. In debug, let's crash so// we can try to figure it out. In release, let's disconnect// the child first.- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {unreachable;}self.frame.removeNode(previous_parent, child, .{ .will_be_reconnected = parent.isConnected() });diff --git a/src/browser/webapi/CData.zig b/src/browser/webapi/CData.zigindex 7a8f3bc20..ea160045c 100644--- a/src/browser/webapi/CData.zig+++ b/src/browser/webapi/CData.zig@@ -30,7 +30,6 @@ pub const CDATASection = @import("cdata/CDATASection.zig");pub const ProcessingInstruction = @import("cdata/ProcessingInstruction.zig");const String = lp.String;-const IS_DEBUG = @import("builtin").mode == .Debug;const CData = @This();@@ -41,7 +40,7 @@ _data: String = .empty,// In debug, set so that we can check that we have a proper contiguous block// of memory for the entire chain (and thus, simple pointer arithmetics will// work to resolve the proto).-_proto_canary: if (IS_DEBUG) *Node else void = undefined,+_proto_canary: if (lp.IS_DEBUG) *Node else void = undefined,// The subtype's struct is not a payload here: it's the member laid out after// the CData in the factory chain (see Factory.cdataNode), reachable via@@ -73,7 +72,7 @@ fn tagOf(comptime T: type) Type {pub fn subtype(self: *CData, comptime T: type) *T {const offset = comptime Factory.chainOffsetOf(T, T) - Factory.chainOffsetOf(T, CData);const sub: *T = @ptrFromInt(@intFromPtr(self) + offset);- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {// the arithmetic rides on factory-chain contiguity; the stored// back-pointer doubles as its canaryif (comptime T == CDATASection) {diff --git a/src/browser/webapi/Document.zig b/src/browser/webapi/Document.zigindex b97dd4d8e..b3084f635 100644--- a/src/browser/webapi/Document.zig+++ b/src/browser/webapi/Document.zig@@ -46,7 +46,6 @@ pub const HTMLDocument = @import("HTMLDocument.zig");const log = lp.log;const String = lp.String;-const IS_DEBUG = @import("builtin").mode == .Debug;const Document = @This();@@ -1469,7 +1468,7 @@ pub fn injectBlank(self: *Document, frame: *Frame) error{InjectBlankError}!void}fn _injectBlank(self: *Document, frame: *Frame) !void {- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {// should only be called on an empty documentstd.debug.assert(self.asNode()._first_child == null);}diff --git a/src/browser/webapi/Element.zig b/src/browser/webapi/Element.zigindex 8c81c4b7b..5fa85dd97 100644--- a/src/browser/webapi/Element.zig+++ b/src/browser/webapi/Element.zig@@ -43,7 +43,6 @@ pub const Attribute = @import("element/Attribute.zig");const DOMStringMap = @import("element/DOMStringMap.zig");const log = lp.log;-const IS_DEBUG = @import("builtin").mode == .Debug;const String = lp.String;const Element = @This();@@ -114,7 +113,7 @@ _attributes: Attribute.List = .{},// In debug, set so that we can check that we have a proper contiguous block// of memory for the entire chain (and thus, simple pointer arithmetics will// work to resolve the proto).-_proto_canary: if (IS_DEBUG) *Node else void = undefined,+_proto_canary: if (lp.IS_DEBUG) *Node else void = undefined,pub const Type = union(enum) {html: *Html,diff --git a/src/browser/webapi/Node.zig b/src/browser/webapi/Node.zigindex 471f45a62..4d41b2550 100644--- a/src/browser/webapi/Node.zig+++ b/src/browser/webapi/Node.zig@@ -38,7 +38,6 @@ pub const ShadowRoot = @import("ShadowRoot.zig");const String = lp.String;const Allocator = std.mem.Allocator;-const IS_DEBUG = @import("builtin").mode == .Debug;pub const AssignedSlotLookup = std.AutoHashMapUnmanaged(*Node, *Element.Html.Slot);@@ -56,7 +55,7 @@ _prev: ?*Node = null,// In debug, set so that we can check that we have a proper contiguous block// of memory for the entire chain (and thus, simple pointer arithmetics will// work to resolve the proto).-_proto_canary: if (IS_DEBUG) *EventTarget else void = undefined,+_proto_canary: if (lp.IS_DEBUG) *EventTarget else void = undefined,// Lookup for nodes that have a different owner document than frame.documentpub const OwnerDocumentLookup = std.AutoHashMapUnmanaged(*Node, *Document);diff --git a/src/browser/webapi/SharedWorkerGlobalScope.zig b/src/browser/webapi/SharedWorkerGlobalScope.zigindex b1013d6c2..c4ac47c95 100644--- a/src/browser/webapi/SharedWorkerGlobalScope.zig+++ b/src/browser/webapi/SharedWorkerGlobalScope.zig@@ -30,7 +30,6 @@ const WorkerGlobalScope = @import("WorkerGlobalScope.zig");const MessageEvent = @import("event/MessageEvent.zig");const log = lp.log;-const IS_DEBUG = @import("builtin").mode == .Debug;const SharedWorkerGlobalScope = @This();@@ -232,7 +231,7 @@ fn httpDoneCallback(ctx: *anyopaque) !void {const url = self._url;const script = self._script_buffer.items;- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {log.info(.browser, "shared worker fetch done", .{.url = url,.len = script.len,diff --git a/src/browser/webapi/Window.zig b/src/browser/webapi/Window.zigindex 4c56bc239..507009dd8 100644--- a/src/browser/webapi/Window.zig+++ b/src/browser/webapi/Window.zig@@ -18,7 +18,6 @@const std = @import("std");const lp = @import("lightpanda");-const builtin = @import("builtin");const js = @import("../js/js.zig");const URL = @import("../URL.zig");@@ -54,7 +53,6 @@ const Scheduler = @import("Scheduler.zig");const Notification = @import("../../Notification.zig");const log = lp.log;-const IS_DEBUG = builtin.mode == .Debug;const Execution = js.Execution;@@ -590,7 +588,7 @@ pub fn reportError(self: *Window, err: js.Value, frame: *Frame) !void {const target = self.asEventTarget();if (!frame._event_manager.hasDirectListeners(target, "error", self._on_error)) {- if (comptime builtin.is_test == false) {+ if (comptime lp.IS_TEST == false) {log.warn(.js, "window.reportError", .{.message = err.toStringSlice() catch "Unknown error",});@@ -643,7 +641,7 @@ pub fn reportError(self: *Window, err: js.Value, frame: *Frame) !void {.context = "window.reportError",});- if (comptime builtin.is_test == false) {+ if (comptime lp.IS_TEST == false) {if (!event._prevent_default) {log.warn(.js, "window.reportError", .{.message = error_event._message,@@ -1025,7 +1023,7 @@ pub fn getWebDriver(_: *const Window) @import("WebDriver.zig") {}pub fn unhandledPromiseRejection(self: *Window, no_handler: bool, rejection: js.PromiseRejection, frame: *Frame) !void {- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {log.debug(.js, "unhandled rejection", .{.target = "window",.value = rejection.reason(),diff --git a/src/browser/webapi/Worker.zig b/src/browser/webapi/Worker.zigindex abcf64f2c..c775d8626 100644--- a/src/browser/webapi/Worker.zig+++ b/src/browser/webapi/Worker.zig@@ -31,7 +31,6 @@ const ErrorEvent = @import("event/ErrorEvent.zig");const DedicatedWorkerGlobalScope = @import("DedicatedWorkerGlobalScope.zig");const log = lp.log;-const IS_DEBUG = @import("builtin").mode == .Debug;const Worker = @This();@@ -190,7 +189,7 @@ fn httpDoneCallback(ctx: *anyopaque) !void {const url = self._url;const script = self._script_buffer.items;- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {log.info(.browser, "worker fetch done", .{.url = url,.len = script.len,diff --git a/src/browser/webapi/WorkerGlobalScope.zig b/src/browser/webapi/WorkerGlobalScope.zigindex e8fd20d38..a845fa0fe 100644--- a/src/browser/webapi/WorkerGlobalScope.zig+++ b/src/browser/webapi/WorkerGlobalScope.zig@@ -50,9 +50,6 @@ const MessagePort = @import("MessagePort.zig");const SharedWorkerGlobalScope = @import("SharedWorkerGlobalScope.zig");const DedicatedWorkerGlobalScope = @import("DedicatedWorkerGlobalScope.zig");-const builtin = @import("builtin");-const IS_DEBUG = builtin.mode == .Debug;-const log = lp.log;const Allocator = std.mem.Allocator;@@ -365,7 +362,7 @@ pub fn structuredClone(_: *const WorkerGlobalScope, value: JS.Value) !JS.Value {}pub fn unhandledPromiseRejection(self: *WorkerGlobalScope, no_handler: bool, rejection: JS.PromiseRejection) !void {- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {log.debug(.js, "unhandled rejection", .{.target = "worker",.value = rejection.reason(),@@ -503,7 +500,7 @@ pub fn reportError(self: *WorkerGlobalScope, err: JS.Value) !void {// We still dispatch so that addEventListener('error', ...) listeners fire.try self.dispatch(self.asEventTarget(), event, null, .{});- if (comptime builtin.is_test == false) {+ if (comptime lp.IS_TEST == false) {if (!event._prevent_default) {log.warn(.js, "worker.reportError", .{.message = error_event._message,diff --git a/src/browser/webapi/collections/HTMLFormControlsCollection.zig b/src/browser/webapi/collections/HTMLFormControlsCollection.zigindex c842bdcc7..bf0c60677 100644--- a/src/browser/webapi/collections/HTMLFormControlsCollection.zig+++ b/src/browser/webapi/collections/HTMLFormControlsCollection.zig@@ -17,6 +17,7 @@// along with this program. If not, see <https://www.gnu.org/licenses/>.const std = @import("std");+const lp = @import("lightpanda");const js = @import("../../js/js.zig");const Page = @import("../../Page.zig");const Frame = @import("../../Frame.zig");@@ -26,8 +27,6 @@ const NodeList = @import("NodeList.zig");const RadioNodeList = @import("RadioNodeList.zig");const HTMLCollection = @import("HTMLCollection.zig");-const IS_DEBUG = @import("builtin").mode == .Debug;-const HTMLFormControlsCollection = @This();pub const Proto = HTMLCollection;@@ -120,7 +119,7 @@ pub fn namedItem(self: *HTMLFormControlsCollection, name: []const u8, frame: *Fr}// case == 2 was handled inside the loop- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {std.debug.assert(count == 1);}diff --git a/src/browser/webapi/element/Attribute.zig b/src/browser/webapi/element/Attribute.zigindex b3d4904ae..12b30ce75 100644--- a/src/browser/webapi/element/Attribute.zig+++ b/src/browser/webapi/element/Attribute.zig@@ -30,8 +30,6 @@ const GenericIterator = @import("../collections/iterator.zig").Entry;const String = lp.String;const Allocator = std.mem.Allocator;-const IS_DEBUG = @import("builtin").mode == .Debug;-pub fn registerTypes() []const type {return &.{Attribute,@@ -47,7 +45,7 @@ pub const Proto = Node;_name: String,_value: String,_element: ?*Element,-_proto_canary: if (IS_DEBUG) *Node else void = undefined,+_proto_canary: if (lp.IS_DEBUG) *Node else void = undefined,pub fn asNode(self: *Attribute) *Node {return Factory.protoOf(self);@@ -280,7 +278,7 @@ pub const List = struct {// not efficient, won't be called often (if ever!)pub fn putAttribute(self: *List, attribute: *Attribute, element: *Element, frame: *Frame) !?*Attribute {// we expect our caller to make sure this is true- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {std.debug.assert(attribute._element == null);}diff --git a/src/browser/webapi/element/Html.zig b/src/browser/webapi/element/Html.zigindex 1ccfa9d39..060c88acf 100644--- a/src/browser/webapi/element/Html.zig+++ b/src/browser/webapi/element/Html.zig@@ -99,7 +99,6 @@ pub const UL = @import("html/UL.zig");pub const Unknown = @import("html/Unknown.zig");const log = lp.log;-const IS_DEBUG = @import("builtin").mode == .Debug;const GlobalEventHandler = global_event_handlers.Handler;const HtmlElement = @This();@@ -107,7 +106,7 @@ const HtmlElement = @This();pub const Proto = Element;_type: Type,-_proto_canary: if (IS_DEBUG) *Element else void = undefined,+_proto_canary: if (lp.IS_DEBUG) *Element else void = undefined,// Special constructor for custom elements (autonomous, `extends HTMLElement`).// Two paths:@@ -542,7 +541,7 @@ fn setAttributeListener(listener_callback: ?js.Function.Global,frame: *Frame,) !void {- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {log.debug(.event, "Html.setAttributeListener", .{.type = std.meta.activeTag(self._type),.listener_type = listener_type,diff --git a/src/browser/webapi/element/Svg.zig b/src/browser/webapi/element/Svg.zigindex 76003bf32..a7a39cfe3 100644--- a/src/browser/webapi/element/Svg.zig+++ b/src/browser/webapi/element/Svg.zig@@ -40,14 +40,12 @@ pub const Stop = @import("svg/Stop.zig");const String = lp.String;-const IS_DEBUG = @import("builtin").mode == .Debug;-const Svg = @This();pub const Proto = Element;_type: Type,_tag_name: String, // Svg elements are case-preserving-_proto_canary: if (IS_DEBUG) *Element else void = undefined,+_proto_canary: if (lp.IS_DEBUG) *Element else void = undefined,pub const Type = union(enum) {graphics: *Graphics,diff --git a/src/browser/webapi/element/html/Media.zig b/src/browser/webapi/element/html/Media.zigindex 93c0c14be..8e3af790c 100644--- a/src/browser/webapi/element/html/Media.zig+++ b/src/browser/webapi/element/html/Media.zig@@ -17,6 +17,7 @@// along with this program. If not, see <https://www.gnu.org/licenses/>.const std = @import("std");+const lp = @import("lightpanda");const js = @import("../../../js/js.zig");const Frame = @import("../../../Frame.zig");@@ -29,8 +30,6 @@ pub const Audio = @import("Audio.zig");pub const Video = @import("Video.zig");const MediaError = @import("../../media/MediaError.zig");-const IS_DEBUG = @import("builtin").mode == .Debug;-const Media = @This();pub const Proto = HtmlElement;@@ -57,7 +56,7 @@ pub const Type = union(enum) {};_type: Type,-_proto_canary: if (IS_DEBUG) *HtmlElement else void = undefined,+_proto_canary: if (lp.IS_DEBUG) *HtmlElement else void = undefined,_paused: bool = true,_current_time: f64 = 0,_volume: f64 = 1.0,diff --git a/src/browser/webapi/element/svg/Geometry.zig b/src/browser/webapi/element/svg/Geometry.zigindex 74d28d4c6..7df09b2ce 100644--- a/src/browser/webapi/element/svg/Geometry.zig+++ b/src/browser/webapi/element/svg/Geometry.zig@@ -17,6 +17,7 @@// along with this program. If not, see <https://www.gnu.org/licenses/>.const std = @import("std");+const lp = @import("lightpanda");const js = @import("../../../js/js.zig");const Frame = @import("../../../Frame.zig");@@ -38,13 +39,11 @@ pub const Path = @import("Path.zig");pub const Polygon = @import("Polygon.zig");pub const Polyline = @import("Polyline.zig");-const IS_DEBUG = @import("builtin").mode == .Debug;-const Geometry = @This();pub const Proto = Graphics;_type: Type,-_proto_canary: if (IS_DEBUG) *Graphics else void = undefined,+_proto_canary: if (lp.IS_DEBUG) *Graphics else void = undefined,pub const Type = union(enum) {rect: *Rect,diff --git a/src/browser/webapi/element/svg/GradientElement.zig b/src/browser/webapi/element/svg/GradientElement.zigindex e7ba02b2d..c63d460df 100644--- a/src/browser/webapi/element/svg/GradientElement.zig+++ b/src/browser/webapi/element/svg/GradientElement.zig@@ -16,6 +16,7 @@// 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 lp = @import("lightpanda");const js = @import("../../../js/js.zig");const Frame = @import("../../../Frame.zig");@@ -32,13 +33,11 @@ const Svg = @import("../Svg.zig");pub const LinearGradient = @import("LinearGradient.zig");pub const RadialGradient = @import("RadialGradient.zig");-const IS_DEBUG = @import("builtin").mode == .Debug;-const GradientElement = @This();pub const Proto = Svg;_type: Type,-_proto_canary: if (IS_DEBUG) *Svg else void = undefined,+_proto_canary: if (lp.IS_DEBUG) *Svg else void = undefined,pub const Type = union(enum) {linear: *LinearGradient,diff --git a/src/browser/webapi/element/svg/Graphics.zig b/src/browser/webapi/element/svg/Graphics.zigindex 8c80d6db5..8668ba3b1 100644--- a/src/browser/webapi/element/svg/Graphics.zig+++ b/src/browser/webapi/element/svg/Graphics.zig@@ -17,6 +17,7 @@// along with this program. If not, see <https://www.gnu.org/licenses/>.const std = @import("std");+const lp = @import("lightpanda");const js = @import("../../../js/js.zig");const Frame = @import("../../../Frame.zig");@@ -42,13 +43,11 @@ pub const ForeignObject = @import("ForeignObject.zig");pub const TextContent = @import("TextContent.zig");pub const Geometry = @import("Geometry.zig");-const IS_DEBUG = @import("builtin").mode == .Debug;-const Graphics = @This();pub const Proto = SvgElement;_type: Type,-_proto_canary: if (IS_DEBUG) *SvgElement else void = undefined,+_proto_canary: if (lp.IS_DEBUG) *SvgElement else void = undefined,pub const Type = union(enum) {svg: *Svg,diff --git a/src/browser/webapi/element/svg/TextContent.zig b/src/browser/webapi/element/svg/TextContent.zigindex 15e2ec285..665453aca 100644--- a/src/browser/webapi/element/svg/TextContent.zig+++ b/src/browser/webapi/element/svg/TextContent.zig@@ -16,6 +16,7 @@// 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 lp = @import("lightpanda");const js = @import("../../../js/js.zig");const Frame = @import("../../../Frame.zig");const text_measure = @import("../../../text_measure.zig");@@ -32,13 +33,11 @@ const Graphics = @import("Graphics.zig");pub const TextPositioning = @import("TextPositioning.zig");pub const TextPath = @import("TextPath.zig");-const IS_DEBUG = @import("builtin").mode == .Debug;-const TextContent = @This();pub const Proto = Graphics;_type: Type,-_proto_canary: if (IS_DEBUG) *Graphics else void = undefined,+_proto_canary: if (lp.IS_DEBUG) *Graphics else void = undefined,pub const Type = union(enum) {positioning: *TextPositioning,diff --git a/src/browser/webapi/element/svg/TextPositioning.zig b/src/browser/webapi/element/svg/TextPositioning.zigindex 649127fe3..91052aed8 100644--- a/src/browser/webapi/element/svg/TextPositioning.zig+++ b/src/browser/webapi/element/svg/TextPositioning.zig@@ -16,6 +16,7 @@// 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 lp = @import("lightpanda");const js = @import("../../../js/js.zig");const Node = @import("../../Node.zig");@@ -27,13 +28,11 @@ const TextContent = @import("TextContent.zig");pub const Text = @import("Text.zig");pub const TSpan = @import("TSpan.zig");-const IS_DEBUG = @import("builtin").mode == .Debug;-const TextPositioning = @This();pub const Proto = TextContent;_type: Type,-_proto_canary: if (IS_DEBUG) *TextContent else void = undefined,+_proto_canary: if (lp.IS_DEBUG) *TextContent else void = undefined,pub const Type = union(enum) {text: *Text,diff --git a/src/browser/webapi/event/MessageEvent.zig b/src/browser/webapi/event/MessageEvent.zigindex 9b987906e..fdfbdb6c0 100644--- a/src/browser/webapi/event/MessageEvent.zig+++ b/src/browser/webapi/event/MessageEvent.zig@@ -27,7 +27,6 @@ const MessagePort = @import("../MessagePort.zig");const Window = @import("../Window.zig");const String = lp.String;-const IS_DEBUG = @import("builtin").mode == .Debug;const MessageEvent = @This();@@ -143,7 +142,7 @@ pub fn getSource(self: *const MessageEvent, exec: *js.Execution) ?SourceAccess {.frame => |frame| return .{ .window = Window.Access.init(frame.window, window) },.worker => {// a window source should never reach a worker context- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {std.debug.assert(false);}return null;diff --git a/src/browser/webapi/global_event_handlers.zig b/src/browser/webapi/global_event_handlers.zigindex cd6555583..519cf70c5 100644--- a/src/browser/webapi/global_event_handlers.zig+++ b/src/browser/webapi/global_event_handlers.zig@@ -23,8 +23,6 @@ const js = @import("../js/js.zig");const EventTarget = @import("EventTarget.zig");-const IS_DEBUG = @import("builtin").mode == .Debug;-const Key = struct {target: *EventTarget,handler: Handler,@@ -34,14 +32,14 @@ const Key = struct {/// See `Context.hash`.fn fuse(self: *const Key) u64 {// Check if we have 3 bits available from alignment of 8.- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {lp.assert(@alignOf(EventTarget) == 8, "Key.fuse: incorrect alignment", .{.event_target_alignment = @alignOf(EventTarget),});}const ptr = @intFromPtr(self.target) >> 3;- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {lp.assert(ptr < (1 << 57), "Key.fuse: pointer overflow", .{ .ptr = ptr });}return ptr | (@as(u64, @intFromEnum(self.handler)) << 57);diff --git a/src/browser/webapi/net/EventSource.zig b/src/browser/webapi/net/EventSource.zigindex 020be0863..2c1615d32 100644--- a/src/browser/webapi/net/EventSource.zig+++ b/src/browser/webapi/net/EventSource.zig@@ -33,7 +33,6 @@ const MessageEvent = @import("../event/MessageEvent.zig");const log = lp.log;const String = lp.String;const Execution = js.Execution;-const IS_DEBUG = @import("builtin").mode == .Debug;// https://html.spec.whatwg.org/multipage/server-sent-events.htmlconst EventSource = @This();@@ -113,7 +112,7 @@ pub fn init(url: []const u8, opts_: ?Opts, exec: *const Execution) !*EventSource// deactivate() releases it.self.acquireRef();- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {log.debug(.http, "EventSource connecting", .{ .url = resolved });}@@ -319,7 +318,7 @@ fn httpHeaderDoneCallback(transfer: *Transfer) !Transfer.HeaderResult {break :blk mime.content_type == .text_event_stream;};- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {log.debug(.http, "request header", .{.source = "eventsource",.url = self._url,diff --git a/src/browser/webapi/net/Fetch.zig b/src/browser/webapi/net/Fetch.zigindex a0cd111f8..6980ca3a6 100644--- a/src/browser/webapi/net/Fetch.zig+++ b/src/browser/webapi/net/Fetch.zig@@ -32,7 +32,6 @@ const Response = @import("Response.zig");const log = lp.log;const Execution = js.Execution;const Transfer = HttpClient.Transfer;-const IS_DEBUG = @import("builtin").mode == .Debug;const Fetch = @This();@@ -92,7 +91,7 @@ pub fn init(input: Input, options: ?InitOpts, exec: *const Execution) !js.Promis}try exec.headersForRequest(&headers);- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {log.debug(.http, "fetch", .{ .url = request._url });}@@ -157,7 +156,7 @@ fn httpHeaderDoneCallback(transfer: *Transfer) !Transfer.HeaderResult {const res = self._response;- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {log.debug(.http, "request header", .{.source = "fetch",.url = self._url,diff --git a/src/browser/webapi/net/WebSocket.zig b/src/browser/webapi/net/WebSocket.zigindex b9c13e62a..ad1ee7bd8 100644--- a/src/browser/webapi/net/WebSocket.zig+++ b/src/browser/webapi/net/WebSocket.zig@@ -35,7 +35,6 @@ const MessageEvent = @import("../event/MessageEvent.zig");const log = lp.log;const Execution = js.Execution;-const IS_DEBUG = @import("builtin").mode == .Debug;const WebSocket = @This();@@ -201,7 +200,7 @@ pub fn init(url: []const u8, protocols: [][]const u8, exec: *const Execution) !*// the moment it's created. deactivate() releases this reference.self.acquireRef();- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {log.info(.websocket, "connecting", .{ .url = url });}@@ -797,7 +796,7 @@ fn dispatchCloseEvent(self: *WebSocket, code: u16, reason: []const u8, was_clean}fn sendDataCallback(buffer: [*]u8, buf_count: usize, buf_len: usize, data: *anyopaque) callconv(.c) usize {- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {std.debug.assert(buf_count == 1);}const conn: *http.Connection = @ptrCast(@alignCast(data));@@ -851,7 +850,7 @@ fn _sendDataCallback(conn: *http.Connection, buf: []u8) !usize {fn writeContent(self: *WebSocket, conn: *http.Connection, buf: []u8, byte_msg: Message.Content, frame_type: http.WsFrameType) !usize {if (self._send_offset == 0) {// start of the message- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {log.debug(.websocket, "send start", .{ .url = self._url, .len = byte_msg.data.len });}try conn.wsStartFrame(frame_type, byte_msg.data.len);@@ -866,7 +865,7 @@ fn writeContent(self: *WebSocket, conn: *http.Connection, buf: []u8, byte_msg: Mif (self._send_offset >= byte_msg.data.len) {const removed = self._send_queue.orderedRemove(0);removed.deinit(self._exec.page);- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {log.debug(.websocket, "send complete", .{ .url = self._url, .len = byte_msg.data.len, .queue = self._send_queue.items.len });}self._send_offset = 0;@@ -876,7 +875,7 @@ fn writeContent(self: *WebSocket, conn: *http.Connection, buf: []u8, byte_msg: M}fn receivedDataCallback(buffer: [*]const u8, buf_count: usize, buf_len: usize, data: *anyopaque) callconv(.c) usize {- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {std.debug.assert(buf_count == 1);}const conn: *http.Connection = @ptrCast(@alignCast(data));@@ -898,7 +897,7 @@ fn _receivedDataCallback(conn: *http.Connection, data: []const u8) !void {};if (meta.offset == 0) {- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {log.debug(.websocket, "incoming message", .{ .url = self._url, .len = meta.len, .bytes_left = meta.bytes_left, .type = meta.frame_type });}// Start of new frame. Pre-allocate buffer@@ -944,7 +943,7 @@ fn _receivedDataCallback(conn: *http.Connection, data: []const u8) !void {// libcurl has no mechanism to signal that the connection is established. The// best option I could come up with was looking for an upgrade header response.fn receivedHeaderCallback(buffer: [*]const u8, header_count: usize, buf_len: usize, data: *anyopaque) callconv(.c) usize {- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {std.debug.assert(header_count == 1);}const conn: *http.Connection = @ptrCast(@alignCast(data));diff --git a/src/browser/webapi/net/XMLHttpRequest.zig b/src/browser/webapi/net/XMLHttpRequest.zigindex d3b2555e9..66998c250 100644--- a/src/browser/webapi/net/XMLHttpRequest.zig+++ b/src/browser/webapi/net/XMLHttpRequest.zig@@ -39,7 +39,6 @@ const XMLHttpRequestUpload = @import("XMLHttpRequestUpload.zig");const log = lp.log;const Execution = js.Execution;-const IS_DEBUG = @import("builtin").mode == .Debug;const XMLHttpRequest = @This();@@ -235,7 +234,7 @@ pub fn overrideMimeType(self: *XMLHttpRequest, mime: []const u8) !void {}pub fn send(self: *XMLHttpRequest, body_: ?BodyInit, exec_: *const Execution) !void {- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {log.debug(.http, "XMLHttpRequest.send", .{ .url = self._url });}if (self._ready_state != .opened or self._send_flag) {@@ -304,7 +303,7 @@ pub fn send(self: *XMLHttpRequest, body_: ?BodyInit, exec_: *const Execution) !v// callbacks clear it.self._http_transfer = transfer;- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {log.debug(.http, "request start", .{ .method = self._method, .url = self._url, .source = "xhr" });}@@ -510,7 +509,7 @@ fn httpHeaderCallback(transfer: *Transfer, header: http.Header) !void {fn httpHeaderDoneCallback(transfer: *Transfer) !Transfer.HeaderResult {const self: *XMLHttpRequest = @ptrCast(@alignCast(transfer.req.ctx));- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {log.debug(.http, "request header", .{.source = "xhr",.url = self._url,diff --git a/src/browser/webapi/selector/Parser.zig b/src/browser/webapi/selector/Parser.zigindex eb0be2d86..df497936a 100644--- a/src/browser/webapi/selector/Parser.zig+++ b/src/browser/webapi/selector/Parser.zig@@ -28,7 +28,6 @@ const Part = Selector.Part;const Segment = Selector.Segment;const Combinator = Selector.Combinator;const Allocator = std.mem.Allocator;-const IS_DEBUG = @import("builtin").mode == .Debug;const Parser = @This();@@ -398,7 +397,7 @@ fn consumeUntilCommaOrParen(self: *Parser) []const u8 {}fn pseudoClass(self: *Parser, arena: Allocator) !Selector.PseudoClass {- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {// Should have been verified by callerstd.debug.assert(self.peek() == ':');}@@ -767,7 +766,7 @@ fn parseNthPattern(self: *Parser) !Selector.NthPattern {}pub fn id(self: *Parser, arena: Allocator) ![]const u8 {- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {// should have been verified by callerstd.debug.assert(self.peek() == '#');}@@ -777,7 +776,7 @@ pub fn id(self: *Parser, arena: Allocator) ![]const u8 {}fn class(self: *Parser, arena: Allocator) ![]const u8 {- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {// should have been verified by callerstd.debug.assert(self.peek() == '.');}@@ -945,7 +944,7 @@ fn tag(self: *Parser) ![]const u8 {}fn attribute(self: *Parser, arena: Allocator) !Selector.Attribute {- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {// should have been verified by callerstd.debug.assert(self.peek() == '[');}diff --git a/src/browser/webapi/storage/idb/IDBTransaction.zig b/src/browser/webapi/storage/idb/IDBTransaction.zigindex 726cae77f..f488a9a35 100644--- a/src/browser/webapi/storage/idb/IDBTransaction.zig+++ b/src/browser/webapi/storage/idb/IDBTransaction.zig@@ -36,7 +36,6 @@ const DOMStringList = @import("../../collections.zig").DOMStringList;const log = lp.log;const Execution = js.Execution;const FunctionSetter = idb.FunctionSetter;-const IS_DEBUG = @import("builtin").mode == .Debug;const IDBTransaction = @This();@@ -175,7 +174,7 @@ pub fn initVersionChange(db: *IDBDatabase, exec: *Execution) !*IDBTransaction {}pub fn deinit(self: *IDBTransaction, _: *Page) void {- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {// Pins hold refs, so the last release can't happen while parked (nor// while a drain task is scheduled).std.debug.assert(self._parked == false);@@ -295,7 +294,7 @@ pub fn settle(self: *IDBTransaction, exec: *Execution) void {// enqueue more) and, once the queue stays empty, commit and fire `complete`.// Returns true while more batches remain.pub fn settleStep(self: *IDBTransaction, exec: *Execution) bool {- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {// non versionchange mode goes through the scheduler + drainstd.debug.assert(self._mode == .versionchange);}@@ -554,7 +553,7 @@ fn drainInner(self: *IDBTransaction) ?u32 {}fn unpark(self: *IDBTransaction) void {- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {std.debug.assert(self._parked);}self._parked = false;@@ -564,7 +563,7 @@ fn unpark(self: *IDBTransaction) void {// Scheduler wake-up: the gate was handed to us, so run the drain again.fn resumeDrain(waiter: *Engine.GateWaiter) void {const self: *IDBTransaction = @fieldParentPtr("_gate_waiter", waiter);- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {std.debug.assert(self._mode != .versionchange);}diff --git a/src/browser/webapi/streams/ReadableStream.zig b/src/browser/webapi/streams/ReadableStream.zigindex b1d63a2d0..11276d79a 100644--- a/src/browser/webapi/streams/ReadableStream.zig+++ b/src/browser/webapi/streams/ReadableStream.zig@@ -27,7 +27,6 @@ const WritableStream = @import("WritableStream.zig");const log = lp.log;const Execution = js.Execution;-const IS_DEBUG = @import("builtin").mode == .Debug;pub fn registerTypes() []const type {return &.{@@ -187,7 +186,7 @@ pub fn callPullIfNeeded(self: *ReadableStream) !void {self._pulling = true;const exec = self._execution;- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {if (exec.js.local == null) {log.fatal(.bug, "null context scope", .{ .src = "ReadableStream.callPullIfNeeded", .url = exec.url.* });std.debug.assert(exec.js.local != null);diff --git a/src/browser/webapi/streams/ReadableStreamDefaultController.zig b/src/browser/webapi/streams/ReadableStreamDefaultController.zigindex feda07051..c7c597801 100644--- a/src/browser/webapi/streams/ReadableStreamDefaultController.zig+++ b/src/browser/webapi/streams/ReadableStreamDefaultController.zig@@ -26,7 +26,6 @@ const ReadableStreamDefaultReader = @import("ReadableStreamDefaultReader.zig");const log = lp.log;const Execution = js.Execution;-const IS_DEBUG = @import("builtin").mode == .Debug;const ReadableStreamDefaultController = @This();@@ -88,7 +87,7 @@ pub fn enqueue(self: *ReadableStreamDefaultController, chunk: Chunk) !void {.value = .fromChunk(chunk),};- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {if (exec.js.local == null) {log.fatal(.bug, "null context scope", .{ .src = "ReadableStreamDefaultController.enqueue", .url = exec.url.* });std.debug.assert(exec.js.local != null);@@ -123,7 +122,7 @@ pub fn enqueueValue(self: *ReadableStreamDefaultController, value: js.Value) !vo.value = .{ .js_value = persisted },};- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {if (exec.js.local == null) {log.fatal(.bug, "null context scope", .{ .src = "ReadableStreamDefaultController.enqueueValue", .url = exec.url.* });std.debug.assert(exec.js.local != null);@@ -151,7 +150,7 @@ pub fn close(self: *ReadableStreamDefaultController) !void {};const exec = self._execution;- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {if (exec.js.local == null) {log.fatal(.bug, "null context scope", .{ .src = "ReadableStreamDefaultController.close", .url = exec.url.* });std.debug.assert(exec.js.local != null);diff --git a/src/cdp/CDP.zig b/src/cdp/CDP.zigindex 981aa5c63..76264330f 100644--- a/src/cdp/CDP.zig+++ b/src/cdp/CDP.zig@@ -47,8 +47,6 @@ const Allocator = std.mem.Allocator;pub const URL_BASE = "chrome://newtab/";-const IS_DEBUG = @import("builtin").mode == .Debug;-const SessionIdGen = Incrementing(u32, "SID");const BrowserSessionIdGen = Incrementing(u32, "BSID");const BrowserContextIdGen = Incrementing(u32, "BID");@@ -1124,7 +1122,7 @@ pub const BrowserContext = struct {buf.appendSliceAssumeCapacity(field);buf.appendSliceAssumeCapacity(session_id);buf.appendSliceAssumeCapacity("\"}");- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {std.debug.assert(buf.items.len == message_len);}diff --git a/src/cdp/Connection.zig b/src/cdp/Connection.zigindex aa5424337..696e4ed94 100644--- a/src/cdp/Connection.zig+++ b/src/cdp/Connection.zig@@ -18,7 +18,6 @@const std = @import("std");const lp = @import("lightpanda");-const builtin = @import("builtin");const CDP = @import("CDP.zig");@@ -58,7 +57,7 @@ pub fn init() !void {const socket_flags = try sys_net.fcntl(socket, posix.F.GETFL, 0);const nonblocking = @as(u32, @bitCast(posix.O{ .NONBLOCK = true }));- if (builtin.is_test == false) {+ if (lp.IS_TEST == false) {lp.assert(socket_flags & nonblocking == nonblocking, "Connection.init blocking", .{});}diff --git a/src/cdp/domains/runtime.zig b/src/cdp/domains/runtime.zigindex bcd1dd268..5912d5371 100644--- a/src/cdp/domains/runtime.zig+++ b/src/cdp/domains/runtime.zig@@ -18,7 +18,6 @@const std = @import("std");const lp = @import("lightpanda");-const builtin = @import("builtin");const js = @import("../../browser/js/js.zig");const CDP = @import("../CDP.zig");@@ -60,7 +59,7 @@ fn disable(cmd: *CDP.Command) !void {fn sendInspector(cmd: *CDP.Command, action: anytype) !void {// save script in file at debug mode- if (builtin.mode == .Debug) {+ if (lp.IS_DEBUG) {try logInspector(cmd, action);}diff --git a/src/crash_handler.zig b/src/crash_handler.zigindex 82830df73..41200409b 100644--- a/src/crash_handler.zig+++ b/src/crash_handler.zig@@ -2,8 +2,6 @@ const std = @import("std");const lp = @import("lightpanda");const builtin = @import("builtin");-const IS_DEBUG = builtin.mode == .Debug;-const abort = std.process.abort;// tracks how deep within a panic we're panicling@@ -72,7 +70,7 @@ pub noinline fn crash(}fn report(reason: []const u8, begin_addr: usize, args: anytype) !void {- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {return;}diff --git a/src/data/public_suffix_list.zig b/src/data/public_suffix_list.zigindex 530fc74d5..cd4499805 100644--- a/src/data/public_suffix_list.zig+++ b/src/data/public_suffix_list.zig@@ -1,5 +1,5 @@const std = @import("std");-const builtin = @import("builtin");+const lp = @import("lightpanda");pub fn lookup(value: []const u8) bool {return public_suffix_list.has(value);@@ -8,7 +8,7 @@ pub fn lookup(value: []const u8) bool {const public_suffix_list = std.StaticStringMap(void).initComptime(entries);const entries: []const struct { []const u8, void } =- if (builtin.is_test) &.{+ if (lp.IS_TEST) &.{.{ "api.gov.uk", {} },.{ "gov.uk", {} },} else &.{diff --git a/src/lightpanda.zig b/src/lightpanda.zigindex 4d747acf3..67f6ed37e 100644--- a/src/lightpanda.zig+++ b/src/lightpanda.zig@@ -64,6 +64,9 @@ pub const Updater = @import("Updater.zig");pub var metrics = @import("Metrics.zig"){};+pub const IS_TEST = @import("builtin").is_test;+pub const IS_DEBUG = @import("builtin").mode == .Debug;+/// Process-wide Io instance for blocking syscalls (fs, net, time, futex)./// Single-threaded-init only disables Io.async/Io.concurrent task spawning;/// blocking operations work from any thread.diff --git a/src/log.zig b/src/log.zigindex 43852e02b..706340bd1 100644--- a/src/log.zig+++ b/src/log.zig@@ -17,11 +17,7 @@// along with this program. If not, see <https://www.gnu.org/licenses/>.const std = @import("std");-const builtin = @import("builtin");--const IS_TEST = builtin.is_test;--const is_debug = builtin.mode == .Debug;+const lp = @import("lightpanda");pub const Scope = enum {app,@@ -71,8 +67,8 @@ pub fn resolveFilterScopes(rules: []const FilterRule) [num_scopes]bool {}const Opts = struct {- format: Format = if (is_debug) .pretty else .logfmt,- level: Level = if (is_debug) .info else .warn,+ format: Format = if (lp.IS_DEBUG) .pretty else .logfmt,+ level: Level = if (lp.IS_DEBUG) .info else .warn,// Per-scope enabled flags; a `false` entry suppresses that scope's logs.// Only consulted in Debug builds. Default: everything enabled.scope_enabled: [num_scopes]bool = [_]bool{true} ** num_scopes,@@ -90,7 +86,7 @@ pub fn enabled(scope: Scope, level: Level) bool {return false;}- if (comptime builtin.mode == .Debug) {+ if (comptime lp.IS_DEBUG) {if (opts.scope_enabled[@intFromEnum(scope)] == false) {return false;}@@ -106,7 +102,7 @@ var expected_logs: [num_scopes]u16 = @splat(0);// Registers one expected log line per entry in `scopes`.pub fn expectLog(comptime scopes: []const Scope) void {- comptime std.debug.assert(IS_TEST);+ comptime std.debug.assert(lp.IS_TEST);inline for (scopes) |scope| {expected_logs[@intFromEnum(scope)] += 1;}@@ -114,7 +110,7 @@ pub fn expectLog(comptime scopes: []const Scope) void {// Called after each test. Returns the expectations that were never met.pub fn resetTestState() [num_scopes]u16 {- std.debug.assert(IS_TEST);+ std.debug.assert(lp.IS_TEST);const unmet = expected_logs;expected_logs = @splat(0);opts.scope_enabled = @splat(true);@@ -163,7 +159,7 @@ pub fn fatal(scope: Scope, msg: []const u8, data: anytype) void {}pub fn note(scope: Scope, msg: []const u8, data: anytype) void {- if (comptime IS_TEST == false) {+ if (comptime lp.IS_TEST == false) {log(scope, .note, msg, data);}}@@ -173,7 +169,7 @@ pub fn log(scope: Scope, level: Level, msg: []const u8, data: anytype) void {return;}- if (comptime IS_TEST) {+ if (comptime lp.IS_TEST) {const expected = &expected_logs[@intFromEnum(scope)];if (expected.* > 0) {expected.* -= 1;@@ -214,7 +210,7 @@ fn logTo(scope: Scope, level: Level, msg: []const u8, data: anytype, out: *std.I}fn logToErased(scope: Scope, level: Level, msg: []const u8, kvs: []const KV, out: *std.Io.Writer) !void {- if (builtin.mode == .Debug) {+ if (lp.IS_DEBUG) {if (msg.len > 30) {std.debug.print("debug-only-panic: log msg cannot be more than 30 characters: {s}", .{msg});@panic("invalid log msg");@@ -540,7 +536,7 @@ fn elapsed() struct { time: f64, unit: []const u8 } {const datetime = @import("datetime.zig");fn timestamp(comptime clock: std.Io.Clock) u64 {- if (IS_TEST) {+ if (lp.IS_TEST) {return 1739795092929;}return datetime.milliTimestamp(clock);diff --git a/src/main.zig b/src/main.zigindex f8abbfc75..26ae7f24d 100644--- a/src/main.zig+++ b/src/main.zig@@ -18,7 +18,6 @@const std = @import("std");const lp = @import("lightpanda");-const builtin = @import("builtin");const Allocator = std.mem.Allocator;const log = lp.log;@@ -36,9 +35,9 @@ pub fn main(init: std.process.Init) !void {// - in Debug mode we use the General Purpose Allocator to detect memory leaks// - in Release mode we use the c allocatorvar gpa_instance: std.heap.DebugAllocator(.{ .stack_trace_frames = 10 }) = .init;- const gpa = if (builtin.mode == .Debug) gpa_instance.allocator() else std.heap.c_allocator;+ const gpa = if (lp.IS_DEBUG) gpa_instance.allocator() else std.heap.c_allocator;- defer if (builtin.mode == .Debug) {+ defer if (lp.IS_DEBUG) {if (gpa_instance.detectLeaks() != 0) std.process.exit(1);};diff --git a/src/network/HttpClient.zig b/src/network/HttpClient.zigindex e08315bf5..546ddbdb8 100644--- a/src/network/HttpClient.zig+++ b/src/network/HttpClient.zig@@ -18,7 +18,6 @@const std = @import("std");const lp = @import("lightpanda");-const builtin = @import("builtin");const Inbox = @import("../Inbox.zig");const ArenaPool = @import("../ArenaPool.zig");@@ -39,7 +38,6 @@ pub const BlockPattern = UrlBlocklist.Pattern;const log = lp.log;const Allocator = std.mem.Allocator;-const IS_DEBUG = builtin.mode == .Debug;pub const Method = http.Method;pub const Header = http.Header;@@ -235,7 +233,7 @@ pub fn deinit(self: *Client) void {self.abort();self.processGraveyard();- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {lp.assert(self.dispatch_count == 0,"dispatch_count must be 0",@@ -421,7 +419,7 @@ pub fn abort(self: *Client) void {// catch the regression rather than silently leaking on next use.// ws_dispatch_queue drains through owner teardown (abortOwner -> kill),// which precedes Client.deinit.- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {std.debug.assert(self.transfers.size == 0);std.debug.assert(self.pending_queue.first == null);std.debug.assert(self.dispatch_queue.first == null);@@ -458,7 +456,7 @@ pub fn abortOwner(self: *Client, owner: *Owner) void {const ws: *WebSocket = @fieldParentPtr("_owner_node", node);ws.kill();}- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {std.debug.assert(owner.websockets.first == null);}}@@ -682,7 +680,7 @@ pub fn _tick(self: *Client, timeout_ms: u32, mode: DrainMode) !bool {// dispatch CDP commandstry self.drainInbox(mode);- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {if (waited == false) {// we're about to tell our caller not to call us again without it// doing some work (e.g. running tasks). Let's assert that we were@@ -708,7 +706,7 @@ pub fn _tick(self: *Client, timeout_ms: u32, mode: DrainMode) !bool {// over.fn dispatchCompleted(self: *Client, mode: DrainMode) bool {if (mode == .all) {- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {// .all never inside a syncRequest, so nothing can be gating requests.std.debug.assert(self.blocking_requests.count() == 0);}@@ -854,7 +852,7 @@ fn pipeline(self: *Client, transfer: *Transfer, from: SubmitFrom) !void {// / abortParked.self.intercepted += 1;transfer.park(.intercept_request);- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {log.debug(.http, "wait for interception", .{ .intercepted = self.intercepted });}return;@@ -1060,7 +1058,7 @@ fn cacheStore(self: *Client, transfer: *Transfer) void {metadata.headers = headers;metadata.vary_headers = vary_headers.items;- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {log.debug(.browser, "http cache", .{ .key = transfer._cache_key, .metadata = metadata });}cache.put(metadata, transfer.res.buffer.items) catch |err| {@@ -1447,7 +1445,7 @@ fn processOneMessage(self: *Client, msg: http.Handles.MultiMessage, transfer: *T);if (wait_for_interception) {self.intercepted += 1;- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {log.debug(.http, "wait for auth interception", .{ .intercepted = self.intercepted });}@@ -1738,7 +1736,7 @@ pub const SyncResponse = struct {// challenge. The auth retry goes straight back to the network — it already// passed the request-side pipeline on its first attempt.pub fn continueTransfer(self: *Client, transfer: *Transfer) !void {- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {log.debug(.http, "continue transfer", .{ .intercepted = self.intercepted });}@@ -1753,7 +1751,7 @@ pub fn continueTransfer(self: *Client, transfer: *Transfer) !void {// gate, re-entering the pipeline at the step after interception. The CDP// command may have mutated req (url / method / headers / body) first.pub fn continueIntercepted(self: *Client, transfer: *Transfer) !void {- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {lp.assert(self.intercepted > 0, "Client.continueIntercepted", .{ .value = self.intercepted });}@@ -1775,7 +1773,7 @@ pub fn fulfillIntercepted(headers: []const http.Header,body: ?[]const u8,) !void {- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {lp.assert(self.intercepted > 0, "Client.fulfillIntercepted", .{ .value = self.intercepted });}@@ -2100,7 +2098,7 @@ pub const Transfer = struct {if (self._retired) {// transfer.deinit should be called once. But _retired and the graveyard// are a safety net born out of UAFs.- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {lp.assert(false, "Transfer.deinit on retired transfer", .{ .id = self.id });}return;@@ -2152,7 +2150,7 @@ pub const Transfer = struct {o.removeTransfer(self);}- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {// Any callback on a corpse is a bug — fail loudly instead of// silently running user code from a retired transfer.self.req.start_callback = null;@@ -2322,7 +2320,7 @@ pub const Transfer = struct {if (self.state == .delivering) {return;}- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {lp.assert(self.state == .created or self.state == .inflight,"Transfer.scheduleDispatch",@@ -2541,7 +2539,7 @@ pub const Transfer = struct {}fn buildResponseHeader(self: *Transfer, conn: *const http.Connection) !void {- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {std.debug.assert(self.res.header == null);}@@ -2688,7 +2686,7 @@ pub const Transfer = struct {// abort. We don't call self.releaseConn here b/c it has been done// before interception process.pub fn abortAuthChallenge(self: *Transfer) void {- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {log.debug(.http, "abort auth transfer", .{ .intercepted = self.client.intercepted });}@@ -2698,7 +2696,7 @@ pub const Transfer = struct {fn dataCallback(buffer: [*]const u8, chunk_count: usize, chunk_len: usize, data: *anyopaque) callconv(.c) usize {// libcurl should only ever emit 1 chunk at a time- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {std.debug.assert(chunk_count == 1);}@@ -2797,7 +2795,7 @@ pub const Transfer = struct {// deliver() is mid-batch on this transfer; its loop consumes// events appended behind its cursor..delivering => {},- else => if (comptime IS_DEBUG) {+ else => if (comptime lp.IS_DEBUG) {lp.assert(false, "Transfer.scheduleStreamDispatch", .{ .state = self.state });},}diff --git a/src/network/Network.zig b/src/network/Network.zigindex 6f50b5ef9..153011b9c 100644--- a/src/network/Network.zig+++ b/src/network/Network.zig@@ -41,7 +41,6 @@ const log = lp.log;const posix = std.posix;const Allocator = std.mem.Allocator;const DoublyLinkedList = std.DoublyLinkedList;-const IS_DEBUG = builtin.mode == .Debug;const Network = @This();@@ -144,8 +143,8 @@ pub fn globalInit(allocator: Allocator) void {// Only route curl's own allocations through our allocator in Debug, so the// leak detector sees them. In Release it'd just wrap c_allocator (curl's// default malloc anyway) at the cost of a per-allocation header.- const curl_allocator = comptime if (IS_DEBUG) CurlDebugAllocator.interface() else null;- if (comptime IS_DEBUG) {+ const curl_allocator = comptime if (lp.IS_DEBUG) CurlDebugAllocator.interface() else null;+ if (comptime lp.IS_DEBUG) {CurlDebugAllocator.init(allocator);}diff --git a/src/network/Robots.zig b/src/network/Robots.zigindex 02ce88a93..cc3cf949e 100644--- a/src/network/Robots.zig+++ b/src/network/Robots.zig@@ -18,7 +18,6 @@const std = @import("std");const lp = @import("lightpanda");-const builtin = @import("builtin");const log = lp.log;@@ -1251,7 +1250,7 @@ test "Robots: RobotStore.getContentSignals round-trips" {}fn testMatch(pattern: []const u8, path: []const u8) bool {- comptime if (!builtin.is_test) unreachable;+ comptime if (!lp.IS_TEST) unreachable;return matchPattern(CompiledPattern.compile(pattern), path);}diff --git a/src/string.zig b/src/string.zigindex 437133ebf..01123a575 100644--- a/src/string.zig+++ b/src/string.zig@@ -17,9 +17,9 @@// along with this program. If not, see <https://www.gnu.org/licenses/>.const std = @import("std");+const lp = @import("lightpanda");const Allocator = std.mem.Allocator;-const IS_DEBUG = @import("builtin").mode == .Debug;const M = @This();@@ -188,7 +188,7 @@ pub const String = packed struct {// Dangerous. Use this only when you have to (and, obviously, when you know// a.len == b.len)pub fn eqlWithSameLen(a: String, b: String) bool {- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {std.debug.assert(a.len == b.len);}@@ -432,7 +432,7 @@ pub fn latin1ToUtf8(allocator: Allocator, bytes: []const u8) ![]u8 {extra += 1;}}- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {// The way this is currently used:// 1 - the caller always wants the value duped,// 2 - the caller only got here because utf8ValidateSlice failed.diff --git a/src/sys/libcurl.zig b/src/sys/libcurl.zigindex 2027174a1..1ecb83283 100644--- a/src/sys/libcurl.zig+++ b/src/sys/libcurl.zig@@ -17,14 +17,12 @@// along with this program. If not, see <https://www.gnu.org/licenses/>.const std = @import("std");-const builtin = @import("builtin");+const lp = @import("lightpanda");const crypto = @import("libcrypto.zig");const c = @import("curl");-const IS_DEBUG = builtin.mode == .Debug;-pub const Curl = c.CURL;pub const CurlM = c.CURLM;pub const CurlCode = c.CURLcode;@@ -338,7 +336,7 @@ pub const Error = error{};pub fn errorFromCode(code: c.CURLcode) Error {- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {std.debug.assert(code != c.CURLE_OK);}@@ -456,7 +454,7 @@ pub const ErrorHeader = error{};pub fn errorMFromCode(code: c.CURLMcode) ErrorMulti {- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {std.debug.assert(code != c.CURLM_OK);}@@ -478,7 +476,7 @@ pub fn errorMFromCode(code: c.CURLMcode) ErrorMulti {}pub fn errorHFromCode(code: c.CURLHcode) ErrorHeader {- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {std.debug.assert(code != c.CURLHE_OK);}diff --git a/src/telemetry/lightpanda.zig b/src/telemetry/lightpanda.zigindex 15e1e29cd..4201ae22e 100644--- a/src/telemetry/lightpanda.zig+++ b/src/telemetry/lightpanda.zig@@ -13,7 +13,6 @@ const telemetry = @import("telemetry.zig");const log = lp.log;const Allocator = std.mem.Allocator;-const IS_DEBUG = builtin.mode == .Debug;const MAX_PENDING = 4096; // hard cap: drop + count beyond this (reported via buffer_overflow)const RECLAIM_CAPACITY = 64; // reclaim the drain buffer once a burst grows it past this@@ -223,7 +222,7 @@ fn postEvents(self: *LightPanda, conn: *http.Connection, events: []const telemet// now re-write the message that didn't fitconst fit = try self.writeEvent(event);- if (comptime IS_DEBUG) {+ if (comptime lp.IS_DEBUG) {std.debug.assert(fit);}if (fit == false) {diff --git a/src/telemetry/telemetry.zig b/src/telemetry/telemetry.zigindex 3c3dd3006..9a1c54c4b 100644--- a/src/telemetry/telemetry.zig+++ b/src/telemetry/telemetry.zig@@ -1,6 +1,5 @@const std = @import("std");const lp = @import("lightpanda");-const builtin = @import("builtin");const App = @import("../App.zig");const Config = @import("../Config.zig");@@ -11,7 +10,7 @@ const IID_FILE = "iid";const Allocator = std.mem.Allocator;pub fn isDisabled() bool {- if (builtin.mode == .Debug or builtin.is_test) {+ if (lp.IS_DEBUG or lp.IS_TEST) {return true;}@@ -30,7 +29,7 @@ fn TelemetryT(comptime P: type) type {pub fn init(app: *App, run_mode: Config.RunMode, interactive: bool) !Self {const disabled = isDisabled();- if (builtin.mode != .Debug and builtin.is_test == false) {+ if (lp.IS_DEBUG == false and lp.IS_TEST == false) {log.info(.telemetry, "telemetry status", .{ .disabled = disabled });}