Skip to content

Lightpanda: the headless browser designed for AI and automation

dev: groundwork for cross validating our unit tests in chrome

Karl Seguin7dcf8ef38ed3
diff --git a/build.zig b/build.zig
index 33d540928..c5a908d1e 100644
--- a/build.zig
+++ b/build.zig
@@ -189,6 +189,16 @@ pub fn build(b: *Build) !void {
run_step.dependOn(&run_cmd.step);
}
+ {
+ // fixture server, for opening src/browser/tests in another browser
+ const exe = addExe(b, exe_config, "lightpanda-test-server", "test_server_check", "src/main_test_server.zig");
+ const run_cmd = b.addRunArtifact(exe);
+ // fixtures are served relative to the cwd
+ run_cmd.setCwd(b.path("."));
+ const run_step = b.step("test-server", "Serve the test fixtures on 127.0.0.1:9582 (WebSocket 9584)");
+ run_step.dependOn(&run_cmd.step);
+ }
+
addGenerator(b, exe_config, "skills", "Generate LLM skill docs (zig-out/skills/<name>/SKILL.md)");
addGenerator(b, exe_config, "docs", "Generate reference partials for the docs site (zig-out/docs/*.mdx)");
diff --git a/src/TestHTTPServer.zig b/src/TestHTTPServer.zig
index 1633cc382..644d99c84 100644
--- a/src/TestHTTPServer.zig
+++ b/src/TestHTTPServer.zig
@@ -25,14 +25,16 @@ const URL = @import("browser/URL.zig");
const TestHTTPServer = @This();
+port: u16,
shutdown: std.atomic.Value(bool),
listener: ?std.Io.net.Server,
handler: Handler,
const Handler = *const fn (req: *std.http.Server.Request) anyerror!void;
-pub fn init(handler: Handler) TestHTTPServer {
+pub fn init(handler: Handler, port: u16) TestHTTPServer {
return .{
+ .port = port,
.shutdown = .init(true),
.listener = null,
.handler = handler,
@@ -54,7 +56,7 @@ pub fn stop(self: *TestHTTPServer) void {
}
pub fn run(self: *TestHTTPServer, wg: *lp.WaitGroup) !void {
- const address = try std.Io.net.IpAddress.parse("127.0.0.1", 0);
+ const address = try std.Io.net.IpAddress.parse("127.0.0.1", self.port);
self.listener = try address.listen(lp.io, .{ .reuse_address = true });
var listener = &self.listener.?;
@@ -143,7 +145,7 @@ pub fn sendFile(req: *std.http.Server.Request, file_path: []const u8) !void {
fn getContentType(file_path: []const u8) []const u8 {
if (std.mem.endsWith(u8, file_path, ".js")) {
- return "application/json";
+ return "text/javascript";
}
if (std.mem.endsWith(u8, file_path, ".GB2312.html")) {
@@ -181,7 +183,7 @@ fn getContentType(file_path: []const u8) []const u8 {
if (std.mem.endsWith(u8, file_path, ".mjs")) {
// mjs are ECMAScript modules
- return "application/json";
+ return "text/javascript";
}
std.debug.print("TestHTTPServer asked to serve an unknown file type: {s}\n", .{file_path});
diff --git a/src/TestWSServer.zig b/src/TestWSServer.zig
index 488c06332..0f3a2bba6 100644
--- a/src/TestWSServer.zig
+++ b/src/TestWSServer.zig
@@ -24,16 +24,15 @@ const posix = std.posix;
const TestWSServer = @This();
+port: u16,
shutdown: std.atomic.Value(bool),
listener: ?posix.socket_t,
-// ephemeral, known once run() has signaled the wait group
-port: u16,
-pub fn init() TestWSServer {
+pub fn init(port: u16) TestWSServer {
return .{
+ .port = port,
.shutdown = .init(true),
.listener = null,
- .port = 0,
};
}
@@ -57,7 +56,7 @@ fn runImpl(self: *TestWSServer, wg: *lp.WaitGroup) !void {
const socket = try sys_net.socket(posix.AF.INET, posix.SOCK.STREAM, 0);
errdefer _ = std.c.close(socket);
- const addr: sys_net.IpAddress = .{ .ip4 = .loopback(0) };
+ const addr: sys_net.IpAddress = .{ .ip4 = .loopback(self.port) };
try posix.setsockopt(socket, posix.SOL.SOCKET, posix.SO.REUSEADDR, &std.mem.toBytes(@as(c_int, 1)));
const sa = sys_net.sockaddrFromAddress(&addr);
diff --git a/src/browser/tests/animation/animation.html b/src/browser/tests/animation/animation.html
index bbbb7965d..2ab506993 100644
--- a/src/browser/tests/animation/animation.html
+++ b/src/browser/tests/animation/animation.html
@@ -1,4 +1,5 @@
<!DOCTYPE html>
+<meta name=lp-mode content=test>
<script src="../testing.js"></script>
<!--
diff --git a/src/browser/tests/blob.html b/src/browser/tests/blob.html
index fbfb3d901..7657d04dc 100644
--- a/src/browser/tests/blob.html
+++ b/src/browser/tests/blob.html
@@ -1,5 +1,6 @@
<!DOCTYPE html>
<meta charset="UTF-8">
+<meta name=lp-mode content=test>
<script src="./testing.js"></script>
<script id=basic type=module>
diff --git a/src/browser/tests/broadcast_channel.html b/src/browser/tests/broadcast_channel.html
index 50aa40103..a9a7c7876 100644
--- a/src/browser/tests/broadcast_channel.html
+++ b/src/browser/tests/broadcast_channel.html
@@ -1,4 +1,5 @@
<!DOCTYPE html>
+<meta name=lp-mode content=test>
<body>
<script src="testing.js"></script>
@@ -276,8 +277,12 @@
const blob = new Blob([
'const c = new BroadcastChannel("x-p2w");' +
- 'c.onmessage = (e) => postMessage({ got: e.data });' +
- 'postMessage({ ready: true });'
+ 'let timer = null;' +
+ 'c.onmessage = (e) => {' +
+ ' clearInterval(timer);' +
+ ' postMessage({ got: e.data });' +
+ '};' +
+ 'timer = setInterval(() => { postMessage({ ready: true }) }, 5);'
], { type: "text/javascript" });
const worker = new Worker(URL.createObjectURL(blob));
diff --git a/src/browser/tests/cache/teardown.html b/src/browser/tests/cache/teardown.html
index 5a9e7a6d1..ae5b4edd5 100644
--- a/src/browser/tests/cache/teardown.html
+++ b/src/browser/tests/cache/teardown.html
@@ -1,10 +1,15 @@
<!DOCTYPE html>
+<meta name=lp-mode content=test>
<script src="../testing.js"></script>
<script id=add_all_in_flight_at_teardown type=module>
+ const state = await testing.async();
+
// Never awaited: the page goes away with one fetch done and one still in
// flight. The runner's leak check is the assertion.
const cache = await caches.open('teardown');
cache.addAll(['/xhr', '/xhr/slow']);
- testing.expectTrue(true);
+
+ state.resolve();
+ await state.done(() => testing.expectTrue(true));
</script>
diff --git a/src/browser/tests/cdata/cdata_section.html b/src/browser/tests/cdata/cdata_section.html
index 6fc24a97c..7fbf1ca3c 100644
--- a/src/browser/tests/cdata/cdata_section.html
+++ b/src/browser/tests/cdata/cdata_section.html
@@ -1,4 +1,5 @@
-cdataClassName<!DOCTYPE html>
+<!DOCTYPE html>
+<meta name=lp-mode content=test>
<script src="../testing.js"></script>
<div id="container"></div>
diff --git a/src/browser/tests/cdata/character_data.html b/src/browser/tests/cdata/character_data.html
index d42b0d905..0ee43865f 100644
--- a/src/browser/tests/cdata/character_data.html
+++ b/src/browser/tests/cdata/character_data.html
@@ -1,4 +1,5 @@
<!DOCTYPE html>
+<meta name=lp-mode content=test>
<script src="../testing.js"></script>
<div id="container"></div>
diff --git a/src/browser/tests/cdata/comment.html b/src/browser/tests/cdata/comment.html
index e1e0e0a4a..0c928092c 100644
--- a/src/browser/tests/cdata/comment.html
+++ b/src/browser/tests/cdata/comment.html
@@ -1,4 +1,5 @@
<!DOCTYPE html>
+<meta name=lp-mode content=test>
<script src="../testing.js"></script>
<script id=comment>
diff --git a/src/browser/tests/cdata/data.html b/src/browser/tests/cdata/data.html
index b04a6d5c0..cb9c84405 100644
--- a/src/browser/tests/cdata/data.html
+++ b/src/browser/tests/cdata/data.html
@@ -1,4 +1,5 @@
<!DOCTYPE html>
+<meta name=lp-mode content=test>
<script src="../testing.js"></script>
<div id=a><!-- spice --></div>
diff --git a/src/browser/tests/cdata/raw_text_chunked.html b/src/browser/tests/cdata/raw_text_chunked.html
index 8a5503a4f..fce95e2b8 100644
--- a/src/browser/tests/cdata/raw_text_chunked.html
+++ b/src/browser/tests/cdata/raw_text_chunked.html
@@ -1,4 +1,5 @@
<!DOCTYPE html>
+<meta name=lp-mode content=test>
<script src="../testing.js"></script>
<!--
diff --git a/src/browser/tests/cdata/text.html b/src/browser/tests/cdata/text.html
index 1278deb04..33abb3ac0 100644
--- a/src/browser/tests/cdata/text.html
+++ b/src/browser/tests/cdata/text.html
@@ -1,4 +1,5 @@
<!DOCTYPE html>
+<meta name=lp-mode content=test>
<a id="link" href="foo" class="ok">OK</a>
<script src="../testing.js"></script>
diff --git a/src/browser/tests/collections/html_all_collection.html b/src/browser/tests/collections/html_all_collection.html
index 87993069f..b25b32b2d 100644
--- a/src/browser/tests/collections/html_all_collection.html
+++ b/src/browser/tests/collections/html_all_collection.html
@@ -1,4 +1,5 @@
<!DOCTYPE html>
+<meta name=lp-mode content=test>
<script src="../testing.js"></script>
<div id=a name=alpha></div>
<div id=b></div>
diff --git a/src/browser/tests/collections/live_collections.html b/src/browser/tests/collections/live_collections.html
index caf34173e..bdaf4f314 100644
--- a/src/browser/tests/collections/live_collections.html
+++ b/src/browser/tests/collections/live_collections.html
@@ -1,4 +1,5 @@
<!DOCTYPE html>
+<meta name=lp-mode content=test>
<script src="../testing.js"></script>
<div id=box>
diff --git a/src/browser/tests/collections/radio_node_list.html b/src/browser/tests/collections/radio_node_list.html
index b90b6494a..76affd2f3 100644
--- a/src/browser/tests/collections/radio_node_list.html
+++ b/src/browser/tests/collections/radio_node_list.html
@@ -1,4 +1,5 @@
<!DOCTYPE html>
+<meta name=lp-mode content=test>
<script src="../testing.js"></script>
<!-- Test fixtures for RadioNodeList -->
diff --git a/src/browser/tests/console/console.html b/src/browser/tests/console/console.html
index e1aefc286..fdb89618d 100644
--- a/src/browser/tests/console/console.html
+++ b/src/browser/tests/console/console.html
@@ -1,4 +1,5 @@
<!DOCTYPE html>
+<meta name=lp-mode content=test>
<script src="../testing.js"></script>
<script id=replaceable>
diff --git a/src/browser/tests/custom_elements/adopted.html b/src/browser/tests/custom_elements/adopted.html
index 80dbc72dc..a6ed51e04 100644
--- a/src/browser/tests/custom_elements/adopted.html
+++ b/src/browser/tests/custom_elements/adopted.html
@@ -1,4 +1,5 @@
<!DOCTYPE html>
+<meta name=lp-mode content=test>
<body>
<script src="../testing.js"></script>
<script id="adopted">
diff --git a/src/browser/tests/custom_elements/attribute_changed.html b/src/browser/tests/custom_elements/attribute_changed.html
index 660fc3824..2840e9157 100644
--- a/src/browser/tests/custom_elements/attribute_changed.html
+++ b/src/browser/tests/custom_elements/attribute_changed.html
@@ -1,4 +1,5 @@
<!DOCTYPE html>
+<meta name=lp-mode content=test>
<body>
<script src="../testing.js"></script>
<script id="attribute_changed">
diff --git a/src/browser/tests/custom_elements/clone_upgrade.html b/src/browser/tests/custom_elements/clone_upgrade.html
index 09418daa1..406f482c1 100644
--- a/src/browser/tests/custom_elements/clone_upgrade.html
+++ b/src/browser/tests/custom_elements/clone_upgrade.html
@@ -1,4 +1,5 @@
<!DOCTYPE html>
+<meta name=lp-mode content=test>
<script src="../testing.js"></script>
<body>
diff --git a/src/browser/tests/custom_elements/connected_from_parser.html b/src/browser/tests/custom_elements/connected_from_parser.html
index f2c575cfe..0c7aac258 100644
--- a/src/browser/tests/custom_elements/connected_from_parser.html
+++ b/src/browser/tests/custom_elements/connected_from_parser.html
@@ -1,5 +1,6 @@
<!DOCTYPE html>
<head>
+<meta name=lp-mode content=test>
<script src="../testing.js"></script>
<script>
{
diff --git a/src/browser/tests/custom_elements/constructor.html b/src/browser/tests/custom_elements/constructor.html
index 22d8f7bfb..55648e856 100644
--- a/src/browser/tests/custom_elements/constructor.html
+++ b/src/browser/tests/custom_elements/constructor.html
@@ -1,4 +1,5 @@
<!DOCTYPE html>
+<meta name=lp-mode content=test>
<script src="../testing.js"></script>
<script id="constructor">
{
diff --git a/src/browser/tests/custom_elements/context_element_not_reconstructed.html b/src/browser/tests/custom_elements/context_element_not_reconstructed.html
index cc355c3f6..a0a666614 100644
--- a/src/browser/tests/custom_elements/context_element_not_reconstructed.html
+++ b/src/browser/tests/custom_elements/context_element_not_reconstructed.html
@@ -1,4 +1,5 @@
<!DOCTYPE html>
+<meta name=lp-mode content=test>
<script src="../testing.js"></script>
<script id="constructor_sets_innerhtml">
diff --git a/src/browser/tests/custom_elements/create_element_post_conditions.html b/src/browser/tests/custom_elements/create_element_post_conditions.html
index 412995098..c3822fad0 100644
--- a/src/browser/tests/custom_elements/create_element_post_conditions.html
+++ b/src/browser/tests/custom_elements/create_element_post_conditions.html
@@ -1,4 +1,5 @@
<!DOCTYPE html>
+<meta name=lp-mode content=test>
<script src="../testing.js"></script>
<script id="uses_constructor_return_value">
diff --git a/src/browser/tests/custom_elements/error_reporting.html b/src/browser/tests/custom_elements/error_reporting.html
index 8598988c2..9861f40ab 100644
--- a/src/browser/tests/custom_elements/error_reporting.html
+++ b/src/browser/tests/custom_elements/error_reporting.html
@@ -1,4 +1,5 @@
<!DOCTYPE html>
+<meta name=lp-mode content=test>
<script src="../testing.js"></script>
<script id="create_element_reports_thrown_exception">
diff --git a/src/browser/tests/custom_elements/mutation_during_callback.html b/src/browser/tests/custom_elements/mutation_during_callback.html
index bacad4ba3..05cf74a58 100644
--- a/src/browser/tests/custom_elements/mutation_during_callback.html
+++ b/src/browser/tests/custom_elements/mutation_during_callback.html
@@ -1,4 +1,5 @@
<!DOCTYPE html>
+<meta name=lp-mode content=test>
<body>
<script src="../testing.js"></script>
diff --git a/src/browser/tests/custom_elements/parser_wrapper_removed.html b/src/browser/tests/custom_elements/parser_wrapper_removed.html
index c2ca9f62b..05b3901d2 100644
--- a/src/browser/tests/custom_elements/parser_wrapper_removed.html
+++ b/src/browser/tests/custom_elements/parser_wrapper_removed.html
@@ -1,4 +1,5 @@
<!DOCTYPE html>
+<meta name=lp-mode content=test>
<body>
<script src="../testing.js"></script>
diff --git a/src/browser/tests/custom_elements/reentrant_document_close.html b/src/browser/tests/custom_elements/reentrant_document_close.html
index 02fc54911..a08008bee 100644
--- a/src/browser/tests/custom_elements/reentrant_document_close.html
+++ b/src/browser/tests/custom_elements/reentrant_document_close.html
@@ -1,5 +1,6 @@
<!DOCTYPE html>
<head>
+<meta name=lp-mode content=test>
<script src="../testing.js"></script>
</head>
<body>
diff --git a/src/browser/tests/custom_elements/reentrant_document_write.html b/src/browser/tests/custom_elements/reentrant_document_write.html
index b6836d523..84368866d 100644
--- a/src/browser/tests/custom_elements/reentrant_document_write.html
+++ b/src/browser/tests/custom_elements/reentrant_document_write.html
@@ -1,5 +1,6 @@
<!DOCTYPE html>
<head>
+<meta name=lp-mode content=test>
<script src="../testing.js"></script>
</head>
<body>
diff --git a/src/browser/tests/custom_elements/registry.html b/src/browser/tests/custom_elements/registry.html
index 173606235..3b0023c70 100644
--- a/src/browser/tests/custom_elements/registry.html
+++ b/src/browser/tests/custom_elements/registry.html
@@ -1,4 +1,5 @@
<!DOCTYPE html>
+<meta name=lp-mode content=test>
<script src="../testing.js"></script>
<script id="registry">
{
diff --git a/src/browser/tests/custom_elements/shadow_tree_callbacks.html b/src/browser/tests/custom_elements/shadow_tree_callbacks.html
index a00b5ea6c..eecb580b5 100644
--- a/src/browser/tests/custom_elements/shadow_tree_callbacks.html
+++ b/src/browser/tests/custom_elements/shadow_tree_callbacks.html
@@ -1,4 +1,5 @@
<!DOCTYPE html>
+<meta name=lp-mode content=test>
<body>
<script src="../testing.js"></script>
<script id="shadow_tree_callbacks">
diff --git a/src/browser/tests/custom_elements/template_content.html b/src/browser/tests/custom_elements/template_content.html
index 253a9baa6..342c017e7 100644
--- a/src/browser/tests/custom_elements/template_content.html
+++ b/src/browser/tests/custom_elements/template_content.html
@@ -1,4 +1,5 @@
<!DOCTYPE html>
+<meta name=lp-mode content=test>
<body>
<script src="../testing.js"></script>
<script>
diff --git a/src/browser/tests/custom_elements/throw_on_dynamic_markup_insertion.html b/src/browser/tests/custom_elements/throw_on_dynamic_markup_insertion.html
index 067392973..ea2bd7d9d 100644
--- a/src/browser/tests/custom_elements/throw_on_dynamic_markup_insertion.html
+++ b/src/browser/tests/custom_elements/throw_on_dynamic_markup_insertion.html
@@ -1,5 +1,6 @@
<!DOCTYPE html>
<head>
+<meta name=lp-mode content=test>
<script src="../testing.js"></script>
<script>
// Test that document.open/write/close throw InvalidStateError during custom element
diff --git a/src/browser/tests/custom_elements/upgrade.html b/src/browser/tests/custom_elements/upgrade.html
index 00b04b082..3da6ab0f6 100644
--- a/src/browser/tests/custom_elements/upgrade.html
+++ b/src/browser/tests/custom_elements/upgrade.html
@@ -1,4 +1,5 @@
<!DOCTYPE html>
+<meta name=lp-mode content=test>
<body>
<my-early id="early"></my-early>
<script src="../testing.js"></script>
diff --git a/src/browser/tests/custom_elements/windowless_document.html b/src/browser/tests/custom_elements/windowless_document.html
index 3a05ba140..5ec05d123 100644
--- a/src/browser/tests/custom_elements/windowless_document.html
+++ b/src/browser/tests/custom_elements/windowless_document.html
@@ -1,4 +1,5 @@
<!DOCTYPE html>
+<meta name=lp-mode content=test>
<body>
<script src="../testing.js"></script>
diff --git a/src/browser/tests/document_head_body.html b/src/browser/tests/document_head_body.html
index b0419b62d..638f41ac2 100644
--- a/src/browser/tests/document_head_body.html
+++ b/src/browser/tests/document_head_body.html
@@ -1,4 +1,5 @@
<head id="the_head">
+ <meta name=lp-mode content=test>
<script src="testing.js"></script>
</head>
<body id="the_body">
@@ -6,4 +7,4 @@
testing.expectEqual(document.getElementById('the_head'), document.head);
testing.expectEqual(document.getElementById('the_body'), document.body);
</script>
-</body>
\ No newline at end of file
+</body>
diff --git a/src/browser/tests/domexception.html b/src/browser/tests/domexception.html
index 9f71fffe6..2f11552f8 100644
--- a/src/browser/tests/domexception.html
+++ b/src/browser/tests/domexception.html
@@ -1,5 +1,6 @@
<!DOCTYPE html>
<head>
+ <meta name=lp-mode content=test>
<title>DOMException Test</title>
<script src="testing.js"></script>
</head>
diff --git a/src/browser/tests/domimplementation.html b/src/browser/tests/domimplementation.html
index 295ea8a61..d7dd0a446 100644
--- a/src/browser/tests/domimplementation.html
+++ b/src/browser/tests/domimplementation.html
@@ -1,6 +1,7 @@
<!DOCTYPE html>
<head>
<title>DOMImplementation Test</title>
+ <meta name=lp-mode content=test>
<script src="testing.js"></script>
</head>
diff --git a/src/browser/tests/dommatrix.html b/src/browser/tests/dommatrix.html
index 9726316e1..b54eef04b 100644
--- a/src/browser/tests/dommatrix.html
+++ b/src/browser/tests/dommatrix.html
@@ -2,6 +2,7 @@
<head>
<title>DOMMatrix Test</title>
<script src="testing.js"></script>
+ <meta name=lp-mode content=test>
</head>
<body>
diff --git a/src/browser/tests/dompoint.html b/src/browser/tests/dompoint.html
index e485cfa17..5111787ba 100644
--- a/src/browser/tests/dompoint.html
+++ b/src/browser/tests/dompoint.html
@@ -2,6 +2,7 @@
<head>
<title>DOMPoint Test</title>
<script src="testing.js"></script>
+ <meta name=lp-mode content=test>
</head>
<body>
diff --git a/src/browser/tests/domrect.html b/src/browser/tests/domrect.html
index e7af22990..02bc66d49 100644
--- a/src/browser/tests/domrect.html
+++ b/src/browser/tests/domrect.html
@@ -2,6 +2,7 @@
<head>
<title>DOMRect Test</title>
<script src="testing.js"></script>
+ <meta name=lp-mode content=test>
</head>
<body>
diff --git a/src/browser/tests/events.html b/src/browser/tests/events.html
index 7bc12a679..71ec0a61f 100644
--- a/src/browser/tests/events.html
+++ b/src/browser/tests/events.html
@@ -1,4 +1,5 @@
<!DOCTYPE html>
+<meta name=lp-mode content=test>
<script src="testing.js"></script>
<div id=parent><p id=child></p></div>
diff --git a/src/browser/tests/file.html b/src/browser/tests/file.html
index 0b301b79e..edce56f86 100644
--- a/src/browser/tests/file.html
+++ b/src/browser/tests/file.html
@@ -2,6 +2,7 @@
<head id="the_head">
<title>Test File Web API</title>
<script src="./testing.js"></script>
+ <meta name=lp-mode content=test>
</head>
<script id=file_basic>
diff --git a/src/browser/tests/file_reader.html b/src/browser/tests/file_reader.html
index 234f91e16..f545fc030 100644
--- a/src/browser/tests/file_reader.html
+++ b/src/browser/tests/file_reader.html
@@ -1,5 +1,6 @@
<!DOCTYPE html>
<meta charset="UTF-8">
+<meta name=lp-mode content=test>
<script src="./testing.js"></script>
<script id=basic>
diff --git a/src/browser/tests/geolocation.html b/src/browser/tests/geolocation.html
index da86ff517..f82bb430e 100644
--- a/src/browser/tests/geolocation.html
+++ b/src/browser/tests/geolocation.html
@@ -1,4 +1,5 @@
<!DOCTYPE html>
+<meta name=lp-mode content=test>
<script src="./testing.js"></script>
<script id=geo_shape>
diff --git a/src/browser/tests/history.html b/src/browser/tests/history.html
index 6380a6d20..935465da2 100644
--- a/src/browser/tests/history.html
+++ b/src/browser/tests/history.html
@@ -1,4 +1,5 @@
<!DOCTYPE html>
+<meta name=lp-mode content=test>
<script src="testing.js"></script>
<script id=history>
diff --git a/src/browser/tests/history_url_update.html b/src/browser/tests/history_url_update.html
index 8aa6d8ca1..8a82c4b08 100644
--- a/src/browser/tests/history_url_update.html
+++ b/src/browser/tests/history_url_update.html
@@ -1,4 +1,5 @@
<!DOCTYPE html>
+<meta name=lp-mode content=test>
<script src="testing.js"></script>
<script id=url_updates>
diff --git a/src/browser/tests/testing.js b/src/browser/tests/testing.js
index 986cc4009..5b787af73 100644
--- a/src/browser/tests/testing.js
+++ b/src/browser/tests/testing.js
@@ -1,6 +1,9 @@
(() => {
let failed = false;
let observed_ids = {};
+ // includes observations no script could be attributed to (e.g. a module
+ // after an await, where currentScript is null)
+ let observation_count = 0;
let eventuallies = [];
let async_capture = null;
let current_script_id = null;
@@ -11,6 +14,15 @@
// runner will wait until this is empty (or timeout)
let async_pending = new Set();
+
+ let module_asyncs_done = 0;
+ let module_asyncs_started = 0;
+ let parsed_module_asyncs = 0;
+
+ document.addEventListener('DOMContentLoaded', () => {
+ parsed_module_asyncs = _moduleAsyncCount();
+ });
+
// A script that throws after an expect* passed would otherwise count as ok.
// Checked in assertOk, once dispatch is over: a test that expects the error
// cancels it (window.onerror returning true, or preventDefault()).
@@ -107,9 +119,14 @@
}
async function async() {
- // currentScript is null while a module runs in FF/Chrome (the test runner
- // does set it), which leaves us with no way to attribute the observations.
- const script_id = document.currentScript ? document.currentScript.id : 'cannot track module id in FF/Chrome';
+ // currentScript is null while a module runs (Lightpanda sets it, against
+ // the spec).
+ const script = document.currentScript;
+ const is_module = script === null || script.type === 'module';
+ if (is_module) {
+ module_asyncs_started += 1;
+ }
+ const script_id = script ? script.id : _moduleAsyncName(module_asyncs_started);
if (async_seen.has(script_id) && IS_TEST_RUNNER) {
throw new Error(`testing.async() called more than once for script '${script_id}'. A script may only register one async block (the runner can declare success in the gap between two of them); split the test into separate <script> tags.`);
@@ -127,6 +144,9 @@
done: async function(cb) {
const res = await this.promise;
async_pending.delete(script_id);
+ if (is_module) {
+ module_asyncs_done += 1;
+ }
async_capture = this.capture;
try {
cb(res);
@@ -160,21 +180,36 @@
return false;
}
+ const module_asyncs = _moduleAsyncCount();
+ if (module_asyncs_done < module_asyncs) {
+ // a module hasn't reached its testing.async() (yet)
+ return false;
+ }
+ if (module_asyncs_done > module_asyncs) {
+ throw new Error(`${module_asyncs_done} testing.async() blocks completed outside of a classic script, but only ${module_asyncs} inline module scripts call testing.async()`);
+ }
+
+ if (observation_count === 0 && eventuallies.length === 0) {
+ // A script may still be waiting on something (a module's await) without
+ // having registered a testing.async() block.
+ return false;
+ }
+
for (let e of eventuallies) {
current_script_id = e.script_id;
e.callback();
current_script_id = null;
}
- const script_ids = Object.keys(observed_ids);
- if (script_ids.length === 0) {
+ if (observation_count === 0) {
throw new Error('no test observations were recorded');
}
const scripts = document.getElementsByTagName('script');
for (let script of scripts) {
const script_id = script.id;
- if (!script_id) {
+ if (!script_id || script.type === 'module') {
+ // modules are counted instead, above
continue;
}
@@ -203,7 +238,16 @@
}
function printTimeoutState() {
- console.warn('Pending count:', Array.from(async_pending.keys()));
+ if (observation_count === 0) {
+ console.warn('no test observations were recorded');
+ }
+ if (async_pending.size > 0) {
+ console.warn(`Pending async scripts: ${Array.from(async_pending.keys()).join(', ')}`);
+ }
+ const module_asyncs = _moduleAsyncCount();
+ if (module_asyncs_done < module_asyncs) {
+ console.warn(`${module_asyncs_done} of ${module_asyncs} module testing.async() blocks completed, ${module_asyncs_started} started`);
+ }
}
const IS_TEST_RUNNER = window.navigator.userAgent.startsWith("Lightpanda/");
@@ -232,13 +276,15 @@
// The page is running in a different browser. Probably a developer making sure
// a test is correct. There are a few tweaks we need to do to make this a
// seamless, namely around adapting paths/urls.
- console.warn(`The page is not being executed in the test runner, certain behavior has been adjusted`);
window.testing.HOST = location.hostname;
window.testing.ORIGIN = location.origin;
- // Relative to this script, so a page served as //src/... (or from another
- // root) still resolves relative URLs the way the test expects.
- window.testing.BASE_URL = new URL('./', document.currentScript.src).href;
- window.addEventListener('load', testing.assertOk);
+
+ window.testing.BASE_URL = location.origin + '/src/browser/tests/';
+ // An external runner (../demo/browser-tests) polls assertOk itself.
+ if (window.__lp_external_runner !== true) {
+ console.warn(`The page is not being executed in the test runner, certain behavior has been adjusted`);
+ window.addEventListener('load', testing.assertOk);
+ }
}
@@ -284,8 +330,26 @@
return true;
}
+ function _moduleAsyncScripts() {
+ return Array.from(document.querySelectorAll('script[type=module]:not([src])'))
+ .filter((script) => script.text.includes('testing.async('));
+ }
+
+ function _moduleAsyncCount() {
+ return Math.max(_moduleAsyncScripts().length, parsed_module_asyncs);
+ }
+
+ // Inline modules start in document order, so the nth testing.async() from a
+ // module is the nth such script, as long as each one calls it before its
+ // first other await.
+ function _moduleAsyncName(n) {
+ const script = _moduleAsyncScripts()[n - 1];
+ return script?.id ? `module #${n} (${script.id})` : `module #${n}`;
+ }
+
function _registerObservation(status, opts) {
- script_id = opts?.script_id || _currentScriptId();
+ observation_count += 1;
+ const script_id = opts?.script_id || _currentScriptId();
if (!script_id) {
return;
}
diff --git a/src/lightpanda.zig b/src/lightpanda.zig
index aa2ab78dc..a44afe0ae 100644
--- a/src/lightpanda.zig
+++ b/src/lightpanda.zig
@@ -45,6 +45,11 @@ pub const SemanticTree = @import("SemanticTree.zig");
pub const NodeRegistry = @import("NodeRegistry.zig");
pub const crash_handler = @import("crash_handler.zig");
+// for `zig build test-server`
+pub const test_routes = @import("test_routes.zig");
+pub const TestWSServer = @import("TestWSServer.zig");
+pub const TestHTTPServer = @import("TestHTTPServer.zig");
+
pub const Network = @import("network/Network.zig");
pub const HttpClient = @import("network/HttpClient.zig");
diff --git a/src/main_test_server.zig b/src/main_test_server.zig
new file mode 100644
index 000000000..6d5b07a11
--- /dev/null
+++ b/src/main_test_server.zig
@@ -0,0 +1,39 @@
+// Copyright (C) 2023-2026 Lightpanda (Selecy SAS)
+//
+// Francis Bouvier <[email protected]>
+// Pierre Tachoire <[email protected]>
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as
+// published by the Free Software Foundation, either version 3 of the
+// License, or (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+const std = @import("std");
+const lp = @import("lightpanda");
+
+const HTTP_PORT = 9582;
+const WS_PORT = 9584;
+
+pub fn main() !void {
+ var http_server: lp.TestHTTPServer = .init(lp.test_routes.handle, HTTP_PORT);
+ var ws_server: lp.TestWSServer = .init(WS_PORT);
+
+ var wg: lp.WaitGroup = .{};
+ wg.startMany(2);
+ const http_thread = try std.Thread.spawn(.{}, lp.TestHTTPServer.run, .{ &http_server, &wg });
+ const ws_thread = try std.Thread.spawn(.{}, lp.TestWSServer.run, .{ &ws_server, &wg });
+ wg.wait();
+
+ std.debug.print("serving http://127.0.0.1:{d}/src/browser/tests/ (WebSocket on {d})\n", .{ HTTP_PORT, WS_PORT });
+
+ http_thread.join();
+ ws_thread.join();
+}
diff --git a/src/test_routes.zig b/src/test_routes.zig
new file mode 100644
index 000000000..2c73df4f7
--- /dev/null
+++ b/src/test_routes.zig
@@ -0,0 +1,920 @@
+// Copyright (C) 2023-2026 Lightpanda (Selecy SAS)
+//
+// Francis Bouvier <[email protected]>
+// Pierre Tachoire <[email protected]>
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as
+// published by the Free Software Foundation, either version 3 of the
+// License, or (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+// The routes the src/browser/tests fixtures load from: their files under
+// /src/browser/tests/ plus the endpoints below. Served by the test suite and
+// by `zig build test-server`.
+
+const std = @import("std");
+const lp = @import("lightpanda");
+
+const repeat = @import("string.zig").repeat;
+const Frame = @import("browser/Frame.zig");
+const TestHTTPServer = @import("TestHTTPServer.zig");
+
+// Server-side state for the /sse/* endpoints. sse_flag proves progressive
+// delivery (see /sse/streaming); sse_reconnect_hits makes /sse/reconnect
+// serve a different stream on the second connection.
+var sse_flag = std.atomic.Value(bool).init(false);
+var sse_reconnect_hits = std.atomic.Value(usize).init(0);
+
+// /serve-count/ counters; only ever touched from the test HTTP server thread.
+var serve_counts = [_]struct { name: []const u8, count: u32 = 0 }{
+ .{ .name = "defer" },
+ .{ .name = "async" },
+ .{ .name = "dynamic" },
+ .{ .name = "prescan_blocking" },
+ .{ .name = "prescan_defer" },
+ .{ .name = "prescan_module" },
+};
+
+fn origin(req: *std.http.Server.Request) ?[]const u8 {
+ var it = req.iterateHeaders();
+ while (it.next()) |h| {
+ if (std.mem.eql(u8, "origin", h.name)) {
+ return h.value;
+ }
+ }
+
+ return null;
+}
+
+pub fn handle(req: *std.http.Server.Request) !void {
+ var arena: std.heap.ArenaAllocator = .init(std.heap.c_allocator);
+ defer arena.deinit();
+ const req_allocator = arena.allocator();
+
+ const path = req.head.target;
+
+ if (std.mem.eql(u8, path, "/reset")) {
+ // A test process gets its own server, so this state starts fresh for
+ // it. A long-lived `zig build test-server` is reset per fixture instead.
+ for (&serve_counts) |*sc| sc.count = 0;
+ sse_flag.store(false, .release);
+ sse_reconnect_hits.store(0, .release);
+ return req.respond("", .{});
+ }
+
+ if (std.mem.eql(u8, path, "/")) {
+ return req.respond("<html><head></head><body></body></html>", .{
+ .extra_headers = &.{
+ .{ .name = "Content-Type", .value = "text/html; charset=utf-8" },
+ },
+ });
+ }
+
+ if (std.mem.eql(u8, path, "/xhr")) {
+ return req.respond(repeat("1234567890", 10), .{
+ .extra_headers = &.{
+ .{ .name = "Content-Type", .value = "text/html; charset=utf-8" },
+ },
+ });
+ }
+
+ if (std.mem.eql(u8, path, "/xhr/slow")) {
+ // Long enough for a timer scheduled by the requester to fire first.
+ lp.io.sleep(.fromMilliseconds(100), .awake) catch {};
+ return req.respond("slow", .{
+ .extra_headers = &.{
+ .{ .name = "Content-Type", .value = "text/plain" },
+ },
+ });
+ }
+
+ if (std.mem.eql(u8, path, "/xhr/hang")) {
+ // For asserting a request didn't wait for its response
+ lp.io.sleep(.fromMilliseconds(2000), .awake) catch {};
+ return req.respond("hang", .{
+ .extra_headers = &.{
+ .{ .name = "Content-Type", .value = "text/plain" },
+ },
+ });
+ }
+
+ if (std.mem.eql(u8, path, "/xhr_empty")) {
+ return req.respond("", .{
+ .extra_headers = &.{
+ .{ .name = "Content-Type", .value = "text/html; charset=utf-8" },
+ },
+ });
+ }
+
+ const xhr_xml_body = "<?xml version=\"1.0\"?><catalog><item id=\"a\"/><item id=\"b\"/><pubDate>2026</pubDate></catalog>";
+
+ if (std.mem.eql(u8, path, "/xhr/xml")) {
+ return req.respond(xhr_xml_body, .{
+ .extra_headers = &.{
+ .{ .name = "Content-Type", .value = "application/xml" },
+ },
+ });
+ }
+
+ if (std.mem.eql(u8, path, "/xhr/xml_as_text")) {
+ return req.respond(xhr_xml_body, .{
+ .extra_headers = &.{
+ .{ .name = "Content-Type", .value = "text/plain" },
+ },
+ });
+ }
+
+ if (std.mem.eql(u8, path, "/xhr/json")) {
+ return req.respond("{\"over\":\"9000!!!\",\"updated_at\":1765867200000}", .{
+ .extra_headers = &.{
+ .{ .name = "Content-Type", .value = "application/json" },
+ },
+ });
+ }
+
+ if (std.mem.eql(u8, path, "/xhr/redirect")) {
+ return req.respond("", .{
+ .status = .found,
+ .extra_headers = &.{
+ .{ .name = "Location", .value = "http://127.0.0.1:9582/xhr" },
+ },
+ });
+ }
+
+ // Scripts, so a cross-origin (localhost) load doesn't depend on CORS.
+ if (std.mem.eql(u8, path, "/resource-timing/tao")) {
+ return req.respond("window.__rt_tao = true;", .{
+ .extra_headers = &.{
+ .{ .name = "Content-Type", .value = "text/javascript" },
+ .{ .name = "Timing-Allow-Origin", .value = "https://example.com, *" },
+ },
+ });
+ }
+
+ if (std.mem.eql(u8, path, "/resource-timing/plain")) {
+ return req.respond("window.__rt_plain = true;", .{
+ .extra_headers = &.{
+ .{ .name = "Content-Type", .value = "text/javascript" },
+ },
+ });
+ }
+
+ if (std.mem.eql(u8, path, "/resource-timing/redirect")) {
+ return req.respond("", .{
+ .status = .found,
+ .extra_headers = &.{
+ .{ .name = "Location", .value = "/resource-timing/plain" },
+ },
+ });
+ }
+
+ if (std.mem.eql(u8, path, "/redirect-no-fragment")) {
+ return req.respond("", .{
+ .status = .found,
+ .extra_headers = &.{
+ .{ .name = "Location", .value = "/redirect-target" },
+ },
+ });
+ }
+
+ if (std.mem.eql(u8, path, "/redirect-cross-origin-x-hop")) {
+ return req.respond("", .{
+ .status = .found,
+ .extra_headers = &.{
+ .{ .name = "Location", .value = "http://localhost:9582/echo-x-hop" },
+ },
+ });
+ }
+
+ // Bounces to the same path on the other loopback host, e.g. for an iframe
+ // whose origin must change between its request and its response.
+ if (std.mem.startsWith(u8, path, "/redirect-cross-origin/")) {
+ var location_buf: [1024]u8 = undefined;
+ const location = try std.mem.print(&location_buf, "http://localhost:9582/{s}", .{path["/redirect-cross-origin/".len..]});
+ return req.respond("", .{
+ .status = .found,
+ .extra_headers = &.{
+ .{ .name = "Location", .value = location },
+ },
+ });
+ }
+
+ if (std.mem.eql(u8, path, "/echo-x-hop")) {
+ var it = req.iterateHeaders();
+ var value: []const u8 = "NONE";
+ while (it.next()) |header| {
+ if (std.ascii.eqlIgnoreCase(header.name, "x-hop")) {
+ value = header.value;
+ break;
+ }
+ }
+ return req.respond(value, .{
+ .extra_headers = &.{
+ .{ .name = "Content-Type", .value = "text/plain; charset=utf-8" },
+ },
+ });
+ }
+
+ if (std.mem.eql(u8, path, "/redirect-target")) {
+ return req.respond("<!DOCTYPE html><title>landed</title>", .{
+ .extra_headers = &.{
+ .{ .name = "Content-Type", .value = "text/html; charset=utf-8" },
+ },
+ });
+ }
+
+ if (std.mem.eql(u8, path, "/303-no-location")) {
+ // 3xx WITHOUT a Location header: not a redirect, a final response
+ // whose body must be delivered (RFC 9110 §15.4).
+ return req.respond("<!DOCTYPE html><title>landed</title><p>see other body</p>", .{
+ .status = .see_other,
+ .extra_headers = &.{
+ .{ .name = "Content-Type", .value = "text/html; charset=utf-8" },
+ },
+ });
+ }
+
+ if (std.mem.eql(u8, path, "/300-with-location")) {
+ // A non-redirect 3xx (fetch's redirect statuses are only 301, 302,
+ // 303, 307 and 308) carrying a Location header: the header is a
+ // preference hint, not a redirect — the body must be delivered.
+ return req.respond("<!DOCTYPE html><title>choices</title><p>multiple choices body</p>", .{
+ .status = .multiple_choice,
+ .extra_headers = &.{
+ .{ .name = "Content-Type", .value = "text/html; charset=utf-8" },
+ .{ .name = "Location", .value = "http://127.0.0.1:9582/hi.html" },
+ },
+ });
+ }
+
+ if (std.mem.eql(u8, path, "/redirect-with-fragment")) {
+ return req.respond("", .{
+ .status = .found,
+ .extra_headers = &.{
+ .{ .name = "Location", .value = "/redirect-target#target_fragment" },
+ },
+ });
+ }
+
+ if (std.mem.eql(u8, path, "/xhr/404")) {
+ return req.respond("Not Found", .{
+ .status = .not_found,
+ .extra_headers = &.{
+ .{ .name = "Content-Type", .value = "text/plain" },
+ },
+ });
+ }
+
+ if (std.mem.eql(u8, path, "/src/browser/tests/401")) {
+ return req.respond("No", .{
+ .status = .unauthorized,
+ .extra_headers = &.{
+ .{ .name = "Content-Type", .value = "text/plain" },
+ },
+ });
+ }
+
+ if (std.mem.eql(u8, path, "/404.js")) {
+ // Valid JS body served with a 404 status. Used to assert that
+ // ScriptManager does NOT execute the body of a failed script
+ // fetch — if it did, window.__404_body_executed would be set.
+ return req.respond("window.__404_body_executed = true;", .{
+ .status = .not_found,
+ .extra_headers = &.{
+ .{ .name = "Content-Type", .value = "application/javascript" },
+ },
+ });
+ }
+
+ if (std.mem.eql(u8, path, "/defer-marker.js")) {
+ // A deferred script body. Used by the regression test for a
+ // <script defer> whose completion is deferred by a later
+ // <link rel=stylesheet>'s synchronous fetch — it must still execute.
+ return req.respond("window.__deferRan = true;", .{
+ .extra_headers = &.{
+ .{ .name = "Content-Type", .value = "application/javascript" },
+ },
+ });
+ }
+
+ if (std.mem.startsWith(u8, path, "/serve-count/") and std.mem.endsWith(u8, path, ".js")) {
+ // Serves `window.__serve_count_<name> = N;` where N counts how many
+ // times this URL has been served. Lets a fixture assert a preloaded
+ // script was fetched exactly once: the body the consumer executes
+ // carries N == 1, while a duplicate fetch would execute N == 2.
+ // no-store so the second fetch can't be satisfied by the HTTP cache.
+ const name = path["/serve-count/".len .. path.len - ".js".len];
+ const slot: *u32 = blk: {
+ for (&serve_counts) |*sc| {
+ if (std.mem.eql(u8, sc.name, name)) break :blk &sc.count;
+ }
+ return req.respond("unknown counter", .{ .status = .not_found });
+ };
+ slot.* += 1;
+ var buf: [64]u8 = undefined;
+ const body = try std.mem.print(&buf, "window.__serve_count_{s} = {d};", .{ name, slot.* });
+ return req.respond(body, .{
+ .extra_headers = &.{
+ .{ .name = "Content-Type", .value = "application/javascript" },
+ .{ .name = "Cache-Control", .value = "no-store" },
+ },
+ });
+ }
+
+ if (std.mem.eql(u8, path, "/challenge/vercel")) {
+ return req.respond("<title>Vercel Security Checkpoint</title>", .{
+ .status = .too_many_requests,
+ .extra_headers = &.{
+ .{ .name = "Content-Type", .value = "text/html; charset=utf-8" },
+ .{ .name = "x-vercel-mitigated", .value = "challenge" },
+ },
+ });
+ }
+
+ if (std.mem.startsWith(u8, path, "/status/")) {
+ const code = try std.fmt.parseInt(u16, path["/status/".len..], 10);
+ return req.respond("", .{ .status = @fromBackingInt(@intCast(code)) });
+ }
+
+ if (std.mem.eql(u8, path, "/xhr/reason")) {
+ return req.respond("", .{
+ .status = .service_unavailable,
+ .reason = "HOUSTON WE HAVE A",
+ });
+ }
+
+ if (std.mem.eql(u8, path, "/xhr/duplicate_headers")) {
+ return req.respond("", .{
+ .extra_headers = &.{
+ .{ .name = "X-B", .value = "1" },
+ .{ .name = "X-A", .value = "a" },
+ .{ .name = "X-B", .value = "2, 3" },
+ .{ .name = "X_C", .value = "c" },
+ },
+ });
+ }
+
+ if (std.mem.eql(u8, path, "/xhr/401")) {
+ return req.respond("No", .{
+ .status = .unauthorized,
+ .extra_headers = &.{
+ .{ .name = "WWW-Authenticate", .value = "Basic realm=\"test\"" },
+ },
+ });
+ }
+
+ if (std.mem.eql(u8, path, "/xhr/500")) {
+ return req.respond("Internal Server Error", .{
+ .status = .internal_server_error,
+ .extra_headers = &.{
+ .{ .name = "Content-Type", .value = "text/plain" },
+ },
+ });
+ }
+
+ if (std.mem.eql(u8, path, "/xhr/bad_gzip")) {
+ return req.respond("not actually gzip", .{
+ .extra_headers = &.{
+ .{ .name = "Content-Encoding", .value = "gzip" },
+ },
+ });
+ }
+
+ if (std.mem.eql(u8, path, "/xhr/no_content_type")) {
+ return req.respond("untyped", .{});
+ }
+
+ if (std.mem.eql(u8, path, "/xhr/binary")) {
+ return req.respond(&.{ 0, 0, 1, 2, 0, 0, 9 }, .{
+ .extra_headers = &.{
+ .{ .name = "Content-Type", .value = "application/octet-stream" },
+ },
+ });
+ }
+
+ if (std.mem.eql(u8, path, "/sse/simple")) {
+ // A complete stream: default + custom event types, multi-line data,
+ // an id, and a comment. The connection closes right after; the test
+ // close()s before the (1s) reconnect fires.
+ return req.respond("retry: 1000\ndata: first\n\n: comment\nid: 42\nevent: custom\ndata: a\ndata: b\n\n", .{
+ .extra_headers = &.{
+ .{ .name = "Content-Type", .value = "text/event-stream" },
+ },
+ });
+ }
+
+ if (std.mem.eql(u8, path, "/stop_loading/streaming.html")) {
+ var send_buffer: [1024]u8 = undefined;
+ var res = try req.respondStreaming(&send_buffer, .{
+ .respond_options = .{
+ .extra_headers = &.{
+ .{ .name = "Content-Type", .value = "text/html; charset=utf-8" },
+ },
+ },
+ });
+ try res.writer.writeAll("<html><body><p id=first>first</p>");
+ try res.writer.flush();
+ try res.flush();
+ lp.io.sleep(.fromMilliseconds(1500), .awake) catch {};
+ try res.writer.writeAll("<p id=second>second</p></body></html>");
+ try res.writer.flush();
+ return res.end();
+ }
+
+ if (std.mem.eql(u8, path, "/sse/streaming")) {
+ sse_flag.store(false, .release);
+ var send_buffer: [1024]u8 = undefined;
+ var res = try req.respondStreaming(&send_buffer, .{
+ .respond_options = .{
+ .extra_headers = &.{
+ .{ .name = "Content-Type", .value = "text/event-stream" },
+ },
+ },
+ });
+ try res.writer.writeAll("data: first\n\n");
+ try res.writer.flush();
+ try res.flush();
+
+ // Proof of progressive delivery: "second" is only sent once the
+ // client has reacted to "first" (by fetching /sse/flag), which it
+ // can only do if "first" was delivered while this response was
+ // still streaming.
+ var waited: usize = 0;
+ while (!sse_flag.load(.acquire) and waited < 5000) : (waited += 10) {
+ lp.io.sleep(.fromMilliseconds(10), .awake) catch {};
+ }
+ if (sse_flag.load(.acquire)) {
+ // split mid-line to exercise buffering across chunks
+ try res.writer.writeAll("data: sec");
+ try res.writer.flush();
+ try res.flush();
+ lp.io.sleep(.fromMilliseconds(20), .awake) catch {};
+ try res.writer.writeAll("ond\n\n");
+ try res.writer.flush();
+ try res.flush();
+ }
+ return res.end();
+ }
+
+ if (std.mem.eql(u8, path, "/sse/flag")) {
+ sse_flag.store(true, .release);
+ return req.respond("", .{});
+ }
+
+ if (std.mem.eql(u8, path, "/sse/reconnect")) {
+ if (sse_reconnect_hits.fetchAdd(1, .monotonic) == 0) {
+ return req.respond("retry: 10\ndata: one\n\n", .{
+ .extra_headers = &.{
+ .{ .name = "Content-Type", .value = "text/event-stream" },
+ },
+ });
+ }
+ return req.respond("data: two\n\n", .{
+ .extra_headers = &.{
+ .{ .name = "Content-Type", .value = "text/event-stream" },
+ },
+ });
+ }
+
+ if (std.mem.eql(u8, path, "/sse/long_retry")) {
+ return req.respond("retry: 60000\ndata: x\n\n", .{
+ .extra_headers = &.{
+ .{ .name = "Content-Type", .value = "text/event-stream" },
+ },
+ });
+ }
+
+ if (std.mem.eql(u8, path, "/sse/404")) {
+ return req.respond("data: x\n\n", .{
+ .status = .not_found,
+ .extra_headers = &.{
+ .{ .name = "Content-Type", .value = "text/event-stream" },
+ },
+ });
+ }
+
+ if (std.mem.eql(u8, path, "/sse/badmime")) {
+ return req.respond("data: x\n\n", .{
+ .extra_headers = &.{
+ .{ .name = "Content-Type", .value = "text/plain" },
+ },
+ });
+ }
+
+ if (std.mem.eql(u8, path, "/styles/important-cascade.css")) {
+ return req.respond(".no-js-flex { display: none !important; }", .{
+ .extra_headers = &.{
+ .{ .name = "Content-Type", .value = "text/css" },
+ },
+ });
+ }
+
+ if (std.mem.eql(u8, path, "/styles/visibility.css")) {
+ // Used by css/external_stylesheet.html — drives the visibility
+ // cascade through StyleManager via Frame.loadExternalStylesheet
+ // so a `.ext-hide` element is observable to checkVisibility().
+ return req.respond(".ext-hide { display: none; }", .{
+ .extra_headers = &.{
+ .{ .name = "Content-Type", .value = "text/css" },
+ },
+ });
+ }
+
+ if (std.mem.eql(u8, path, "/styles/visibility2.css")) {
+ // Second visibility sheet used by the href-change regression test:
+ // mutating link.href must replace the cached sheet's rules in place,
+ // not append a new entry to document.styleSheets.
+ return req.respond(".ext-hide-2 { display: none; }", .{
+ .extra_headers = &.{
+ .{ .name = "Content-Type", .value = "text/css" },
+ },
+ });
+ }
+
+ // Latin-1 bytes in the reason phrase, a header name and a header value.
+ if (std.mem.eql(u8, path, "/latin1_response")) {
+ return req.respond("latin1", .{
+ .reason = "Caf\xE9",
+ .extra_headers = &.{
+ .{ .name = "Content-Type", .value = "text/plain" },
+ .{ .name = "X-Latin1", .value = "La\xA0Paz" },
+ .{ .name = "X-Caf\xE9", .value = "1" },
+ },
+ });
+ }
+
+ // Latin-1 sheets for css/stylesheet_charset.html: undecoded, the 0xE9
+ // swallows the bytes after it and the rule that follows is lost.
+ if (std.mem.eql(u8, path, "/styles/latin1-header.css")) {
+ return req.respond("/* caf\xE9 */ .by-header { display: none; --name: \"caf\xE9\"; }", .{
+ .extra_headers = &.{
+ .{ .name = "Content-Type", .value = "text/css; charset=iso-8859-1" },
+ },
+ });
+ }
+
+ if (std.mem.eql(u8, path, "/styles/latin1-at-charset.css")) {
+ return req.respond("@charset \"windows-1252\"; /* caf\xE9 */ .by-at-charset { display: none; }", .{
+ .extra_headers = &.{
+ .{ .name = "Content-Type", .value = "text/css" },
+ },
+ });
+ }
+
+ if (std.mem.eql(u8, path, "/styles/truncated-utf8.css")) {
+ return req.respond(".before-truncated { display: none; } \xE2", .{
+ .extra_headers = &.{
+ .{ .name = "Content-Type", .value = "text/css" },
+ },
+ });
+ }
+
+ // Latin-1 scripts for page/script_charset.html. /scripts/latin1/<name>.js
+ // and /scripts/latin1-header/<name>.js set window[<name>], the latter
+ // declaring its charset.
+ if (std.mem.eql(u8, path, "/scripts/bom-over-header.js")) {
+ return req.respond("\xEF\xBB\xBFwindow.byBom = 'caf\xC3\xA9';", .{
+ .extra_headers = &.{
+ .{ .name = "Content-Type", .value = "text/javascript; charset=iso-8859-1" },
+ },
+ });
+ }
+
+ const declares_charset = std.mem.startsWith(u8, path, "/scripts/latin1-header/");
+ if (declares_charset or std.mem.startsWith(u8, path, "/scripts/latin1/")) {
+ const body = try std.fmt.allocPrint(req_allocator, "window['{s}'] = 'caf\xE9';", .{std.fs.path.stem(path)});
+ const content_type = if (declares_charset) "text/javascript; charset=iso-8859-1" else "text/javascript";
+ return req.respond(body, .{
+ .extra_headers = &.{
+ .{ .name = "Content-Type", .value = content_type },
+ },
+ });
+ }
+
+ if (std.mem.eql(u8, path, "/styles/404.css")) {
+ return req.respond("/* unused */", .{
+ .status = .not_found,
+ .extra_headers = &.{
+ .{ .name = "Content-Type", .value = "text/css" },
+ },
+ });
+ }
+
+ if (std.mem.eql(u8, path, "/styles/large.css")) {
+ // Over 2 MiB, with the rule under test last.
+ const chunk = ".pad { color: #abcdef; } "; // 25 bytes
+ const tail = ".large-hide { display: none; }";
+ const repeats = 5 * 1024 * 1024 / 2 / chunk.len;
+ var body = try std.ArrayList(u8).initCapacity(req_allocator, chunk.len * repeats + tail.len);
+ for (0..repeats) |_| body.appendSliceAssumeCapacity(chunk);
+ body.appendSliceAssumeCapacity(tail);
+ return req.respond(body.items, .{
+ .extra_headers = &.{
+ .{ .name = "Content-Type", .value = "text/css" },
+ },
+ });
+ }
+
+ if (std.mem.eql(u8, path, "/styles/oversize.css")) {
+ // Body that exceeds Frame.MAX_STYLESHEET_BYTES — written as a
+ // long sequence of valid declarations so the response itself parses
+ // fine and the error path is exercised by the size cap, not by a
+ // CSS parse failure.
+ const chunk = ".pad { color: #abcdef; } "; // 25 bytes
+ const repeats = (Frame.MAX_STYLESHEET_BYTES / chunk.len) + 1024;
+ var body = try std.ArrayList(u8).initCapacity(req_allocator, chunk.len * repeats);
+ for (0..repeats) |_| body.appendSliceAssumeCapacity(chunk);
+ return req.respond(body.items, .{
+ .extra_headers = &.{
+ .{ .name = "Content-Type", .value = "text/css" },
+ },
+ });
+ }
+
+ // Bodies are non-empty so that libcurl always reaches the write callback,
+ // which is where a partial request decides whether to drain or abort.
+ // ok.png takes the abort branch, small.png the drain branch; both must
+ // behave identically as far as the DOM is concerned.
+ if (std.mem.eql(u8, path, "/images/ok.png")) {
+ // > HttpClient.Request.PARTIAL_DRAIN_MAX. The synthetic PNG
+ // header advertises 1000 x 750 pixels; no bitmap is decoded.
+ const body = try req_allocator.alloc(u8, 16 * 1024 + 1);
+ @memset(body, 'x');
+ @memcpy(body[0..24], "\x89PNG\r\n\x1a\n\x00\x00\x00\x0dIHDR\x00\x00\x03\xe8\x00\x00\x02\xee");
+ return req.respond(body, .{
+ .extra_headers = &.{
+ .{ .name = "Content-Type", .value = "image/png" },
+ },
+ });
+ }
+
+ // startsWith, not eql: a caller can append a query string to get distinct
+ // URLs (and so distinct transfers) off this one route.
+ if (std.mem.startsWith(u8, path, "/images/small.png")) {
+ const body = try req_allocator.alloc(u8, 1024);
+ @memset(body, 'x');
+ @memcpy(body[0..24], "\x89PNG\r\n\x1a\n\x00\x00\x00\x0dIHDR\x00\x00\x01\x40\x00\x00\x00\xf0");
+ return req.respond(body, .{
+ .extra_headers = &.{
+ .{ .name = "Content-Type", .value = "image/png" },
+ },
+ });
+ }
+
+ if (std.mem.eql(u8, path, "/images/photo.jpg")) {
+ const body = "\xff\xd8\xff\xe1\x00\x04\x00\x00\xff\xc0\x00\x0b\x08\x02\xee\x03\xe8\x01\x01\x11\x00";
+ return req.respond(body, .{
+ .extra_headers = &.{
+ .{ .name = "Content-Type", .value = "image/jpeg" },
+ },
+ });
+ }
+
+ // No Content-Length: whether the body is small enough to drain can only
+ // be decided as it arrives.
+ if (std.mem.eql(u8, path, "/images/chunked.png")) {
+ var send_buffer: [1024]u8 = undefined;
+ var res = try req.respondStreaming(&send_buffer, .{
+ .respond_options = .{
+ .extra_headers = &.{
+ .{ .name = "Content-Type", .value = "image/svg+xml" },
+ },
+ },
+ });
+ try res.writer.writeAll("<svg xmlns=\"http://www.w3.org/2000/svg\"/>");
+ try res.writer.flush();
+ return res.end();
+ }
+
+ if (std.mem.eql(u8, path, "/images/404.png")) {
+ return req.respond("not here", .{
+ .status = .not_found,
+ .extra_headers = &.{
+ .{ .name = "Content-Type", .value = "text/plain" },
+ },
+ });
+ }
+
+ if (std.mem.eql(u8, path, "/images/500.png")) {
+ return req.respond("boom", .{
+ .status = .internal_server_error,
+ .extra_headers = &.{
+ .{ .name = "Content-Type", .value = "text/plain" },
+ },
+ });
+ }
+
+ if (std.mem.eql(u8, path, "/images/redirect.png")) {
+ return req.respond("", .{
+ .status = .found,
+ .extra_headers = &.{
+ .{ .name = "Location", .value = "/images/ok.png" },
+ },
+ });
+ }
+
+ if (std.mem.eql(u8, path, "/echo_referer")) {
+ // Echo the request's Referer header back as HTML so tests can assert
+ // what Referer the navigation sent. Used by the cross-page Referer test.
+ var it = req.iterateHeaders();
+ var referer: []const u8 = "NONE";
+ while (it.next()) |h| {
+ if (std.ascii.eqlIgnoreCase(h.name, "Referer")) {
+ referer = h.value;
+ break;
+ }
+ }
+ var html_buf: [512]u8 = undefined;
+ const html = try std.mem.print(&html_buf, "<html><body>referer={s}</body></html>", .{referer});
+ return req.respond(html, .{
+ .extra_headers = &.{
+ .{ .name = "Content-Type", .value = "text/html; charset=utf-8" },
+ .{ .name = "Access-Control-Allow-Origin", .value = origin(req) orelse "*" },
+ },
+ });
+ }
+
+ if (std.mem.eql(u8, path, "/referer_link.html")) {
+ // Page with an anchor link to /echo_referer. The test clicks the link
+ // via JS and asserts the resulting page reports Referer = this page.
+ return req.respond(
+ "<html><body><a id=\"link\" href=\"/echo_referer\">go</a></body></html>",
+ .{
+ .extra_headers = &.{
+ .{ .name = "Content-Type", .value = "text/html; charset=utf-8" },
+ },
+ },
+ );
+ }
+
+ if (std.mem.eql(u8, path, "/echo_method")) {
+ // Echo the request method back as HTML so tests can assert on what
+ // method the navigation used. Used by the Page.reload-replays-POST test.
+ const method_name = @tagName(req.head.method);
+ var html_buf: [128]u8 = undefined;
+ const html = try std.mem.print(&html_buf, "<html><body>method={s}</body></html>", .{method_name});
+ return req.respond(html, .{
+ .extra_headers = &.{
+ .{ .name = "Content-Type", .value = "text/html; charset=utf-8" },
+ },
+ });
+ }
+
+ if (std.mem.eql(u8, path, "/echo_body")) {
+ // Echo the request body back verbatim, so tests can assert on the bytes
+ // a request actually sent rather than just on its status.
+ var body_buf: [4096]u8 = undefined;
+ const body = if (req.head.method.requestHasBody())
+ try req.readerExpectNone(&body_buf).allocRemaining(req_allocator, .limited(body_buf.len))
+ else
+ "";
+ return req.respond(body, .{
+ .extra_headers = &.{
+ .{ .name = "Content-Type", .value = "text/plain; charset=utf-8" },
+ },
+ });
+ }
+
+ if (std.mem.eql(u8, path, "/echo_brotli")) {
+ // Echo the request body back as `Content-Encoding: br`, so the HTTP
+ // client decodes it; checks CompressionStream('brotli') output with a
+ // decoder that isn't ours.
+ var body_buf: [4096]u8 = undefined;
+ const body = try req.readerExpectNone(&body_buf).allocRemaining(req_allocator, .limited(4 * 1024 * 1024));
+ return req.respond(body, .{
+ .extra_headers = &.{
+ .{ .name = "Content-Type", .value = "application/octet-stream" },
+ .{ .name = "Content-Encoding", .value = "br" },
+ },
+ });
+ }
+
+ if (std.mem.eql(u8, path, "/echo_headers")) {
+ if (req.head.method == .OPTIONS) {
+ return req.respond("", .{
+ .extra_headers = &.{
+ .{ .name = "Access-Control-Allow-Origin", .value = origin(req) orelse "*" },
+ .{ .name = "Access-Control-Allow-Methods", .value = "GET" },
+ .{ .name = "Access-Control-Allow-Headers", .value = "x-hop" },
+ },
+ });
+ }
+
+ // Echo every request header back as "name: value" lines, so tests
+ // can assert on the headers a request actually sent.
+ var buf: [8192]u8 = undefined;
+ var pos: usize = 0;
+ var it = req.iterateHeaders();
+ while (it.next()) |header| {
+ const line = try std.mem.print(buf[pos..], "{s}: {s}\n", .{ header.name, header.value });
+ pos += line.len;
+ }
+ return req.respond(buf[0..pos], .{
+ .extra_headers = &.{
+ .{ .name = "Content-Type", .value = "text/plain; charset=utf-8" },
+ .{ .name = "Access-Control-Allow-Origin", .value = origin(req) orelse "*" },
+ },
+ });
+ }
+
+ if (std.mem.eql(u8, path, "/set_cookie")) {
+ return req.respond("", .{
+ .extra_headers = &.{
+ .{ .name = "Set-Cookie", .value = "lp_hidden=1; Path=/set_cookie_scope" },
+ .{ .name = "X-Visible", .value = "yes" },
+ },
+ });
+ }
+
+ if (std.mem.eql(u8, path, "/redirect_same_echo_headers")) {
+ // Same-origin 302 to /echo_headers: Authorization must survive the hop.
+ return req.respond("", .{
+ .status = .found,
+ .extra_headers = &.{
+ .{ .name = "Location", .value = "/echo_headers" },
+ },
+ });
+ }
+
+ if (std.mem.eql(u8, path, "/redirect_cross_echo_headers")) {
+ // 302 to /echo_headers on the localhost alias — a cross-origin hop, so
+ // Authorization must be stripped before the request is re-sent.
+ return req.respond("", .{
+ .status = .found,
+ .extra_headers = &.{
+ .{ .name = "Location", .value = "http://localhost:9582/echo_headers" },
+ },
+ });
+ }
+
+ if (std.mem.eql(u8, path, "/redirect_same_echo_referer")) {
+ // Same-origin 302 to /echo_referer: the full Referer must survive the hop.
+ return req.respond("", .{
+ .status = .found,
+ .extra_headers = &.{
+ .{ .name = "Location", .value = "/echo_referer" },
+ },
+ });
+ }
+
+ if (std.mem.eql(u8, path, "/redirect_cross_echo_referer")) {
+ // 302 to /echo_referer on the localhost alias — a cross-origin hop, so
+ // the Referer must be recomputed at the redirect (stripped to origin
+ // under the default policy) rather than re-sent in full.
+ return req.respond("", .{
+ .status = .found,
+ .extra_headers = &.{
+ .{ .name = "Location", .value = "http://localhost:9582/echo_referer" },
+ },
+ });
+ }
+
+ if (std.mem.eql(u8, path, "/redirect_to_echo")) {
+ // 302 to /echo_method. Used by the Page.reload-after-redirect test to
+ // confirm a POST→302→GET chain doesn't replay POST on reload.
+ return req.respond("", .{
+ .status = .found,
+ .extra_headers = &.{
+ .{ .name = "Location", .value = "/echo_method" },
+ },
+ });
+ }
+
+ if (std.mem.eql(u8, path, "/download/report.csv")) {
+ // A file download: Content-Disposition: attachment drives the
+ // Browser.setDownloadBehavior path (issue #2701).
+ return req.respond("col1,col2\nhello,world\n42,1337\n", .{
+ .extra_headers = &.{
+ .{ .name = "Content-Type", .value = "text/csv" },
+ .{ .name = "Content-Disposition", .value = "attachment; filename=\"report.csv\"" },
+ },
+ });
+ }
+
+ if (std.mem.startsWith(u8, path, "/src/browser/tests/")) {
+ if (std.mem.find(u8, path, "delay_ms=")) |pos| {
+ const digits_start = pos + "delay_ms=".len;
+ var end = digits_start;
+ while (end < path.len and std.ascii.isDigit(path[end])) : (end += 1) {}
+ const delay_ms = std.fmt.parseInt(u64, path[digits_start..end], 10) catch 0;
+ lp.io.sleep(.fromMilliseconds(@intCast(delay_ms)), .awake) catch {};
+ }
+ // strip off leading / so that it's relative to CWD
+ return TestHTTPServer.sendFile(req, path[1..]);
+ }
+
+ if (std.mem.eql(u8, path, "/favicon.ico")) {
+ return req.respond("", .{ .status = .not_found });
+ }
+
+ std.debug.print("TestHTTPServer was asked to serve an unknown file: {s}\n", .{path});
+ return req.respond("not found", .{ .status = .not_found });
+}
diff --git a/src/testing.zig b/src/testing.zig
index 6631cb3f4..5c5dc7ecd 100644
--- a/src/testing.zig
+++ b/src/testing.zig
@@ -18,7 +18,6 @@
const std = @import("std");
const lp = @import("lightpanda");
-const repeat = @import("string.zig").repeat;
const http = @import("network/http.zig");
const sys_net = @import("sys/net.zig");
const libcurl = @import("sys/libcurl.zig");
@@ -522,6 +521,7 @@ pub fn pageTest(comptime test_file: []const u8, opts: PageTestOpts) !Session.Pag
const Server = @import("server/Server.zig");
const TestWSServer = @import("TestWSServer.zig");
const TestHTTPServer = @import("TestHTTPServer.zig");
+const test_routes = @import("test_routes.zig");
pub var test_cdp_server: ?*Server = null;
pub var test_cdp_port: u16 = 0;
@@ -531,12 +531,6 @@ var test_http_server_thread: ?std.Thread = null;
var test_ws_server: ?TestWSServer = null;
var test_ws_server_thread: ?std.Thread = null;
-// Server-side state for the /sse/* endpoints. sse_flag proves progressive
-// delivery (see /sse/streaming); sse_reconnect_hits makes /sse/reconnect
-// serve a different stream on the second connection.
-var sse_flag = std.atomic.Value(bool).init(false);
-var sse_reconnect_hits = std.atomic.Value(usize).init(0);
-
pub var test_config: Config = undefined;
test "tests:beforeAll" {
@@ -550,10 +544,10 @@ test "tests:beforeAll" {
var wg: lp.WaitGroup = .{};
wg.startMany(2);
- test_http_server = TestHTTPServer.init(testHTTPHandler);
+ test_http_server = TestHTTPServer.init(test_routes.handle, 0);
test_http_server_thread = try std.Thread.spawn(.{}, TestHTTPServer.run, .{ &test_http_server.?, &wg });
- test_ws_server = TestWSServer.init();
+ test_ws_server = TestWSServer.init(0);
test_ws_server_thread = try std.Thread.spawn(.{}, TestWSServer.run, .{ &test_ws_server.?, &wg });
wg.wait();
@@ -666,880 +660,6 @@ fn serveCDP(wg: *lp.WaitGroup) !void {
test_cdp_server.?.run();
}
-// /serve-count/ counters; only ever touched from the test HTTP server thread.
-var serve_counts = [_]struct { name: []const u8, count: u32 = 0 }{
- .{ .name = "defer" },
- .{ .name = "async" },
- .{ .name = "dynamic" },
- .{ .name = "prescan_blocking" },
- .{ .name = "prescan_defer" },
- .{ .name = "prescan_module" },
-};
-
-fn origin(req: *std.http.Server.Request) ?[]const u8 {
- var it = req.iterateHeaders();
- while (it.next()) |h| {
- if (std.mem.eql(u8, "origin", h.name)) {
- return h.value;
- }
- }
-
- return null;
-}
-
-fn testHTTPHandler(req: *std.http.Server.Request) !void {
- var arena: std.heap.ArenaAllocator = .init(std.heap.c_allocator);
- defer arena.deinit();
- const req_allocator = arena.allocator();
-
- const path = req.head.target;
-
- if (std.mem.eql(u8, path, "/")) {
- return req.respond("<html><head></head><body></body></html>", .{
- .extra_headers = &.{
- .{ .name = "Content-Type", .value = "text/html; charset=utf-8" },
- },
- });
- }
-
- if (std.mem.eql(u8, path, "/xhr")) {
- return req.respond(repeat("1234567890", 10), .{
- .extra_headers = &.{
- .{ .name = "Content-Type", .value = "text/html; charset=utf-8" },
- },
- });
- }
-
- if (std.mem.eql(u8, path, "/xhr/slow")) {
- // Long enough for a timer scheduled by the requester to fire first.
- lp.io.sleep(.fromMilliseconds(100), .awake) catch {};
- return req.respond("slow", .{
- .extra_headers = &.{
- .{ .name = "Content-Type", .value = "text/plain" },
- },
- });
- }
-
- if (std.mem.eql(u8, path, "/xhr/hang")) {
- // For asserting a request didn't wait for its response
- lp.io.sleep(.fromMilliseconds(2000), .awake) catch {};
- return req.respond("hang", .{
- .extra_headers = &.{
- .{ .name = "Content-Type", .value = "text/plain" },
- },
- });
- }
-
- if (std.mem.eql(u8, path, "/xhr_empty")) {
- return req.respond("", .{
- .extra_headers = &.{
- .{ .name = "Content-Type", .value = "text/html; charset=utf-8" },
- },
- });
- }
-
- const xhr_xml_body = "<?xml version=\"1.0\"?><catalog><item id=\"a\"/><item id=\"b\"/><pubDate>2026</pubDate></catalog>";
-
- if (std.mem.eql(u8, path, "/xhr/xml")) {
- return req.respond(xhr_xml_body, .{
- .extra_headers = &.{
- .{ .name = "Content-Type", .value = "application/xml" },
- },
- });
- }
-
- if (std.mem.eql(u8, path, "/xhr/xml_as_text")) {
- return req.respond(xhr_xml_body, .{
- .extra_headers = &.{
- .{ .name = "Content-Type", .value = "text/plain" },
- },
- });
- }
-
- if (std.mem.eql(u8, path, "/xhr/json")) {
- return req.respond("{\"over\":\"9000!!!\",\"updated_at\":1765867200000}", .{
- .extra_headers = &.{
- .{ .name = "Content-Type", .value = "application/json" },
- },
- });
- }
-
- if (std.mem.eql(u8, path, "/xhr/redirect")) {
- return req.respond("", .{
- .status = .found,
- .extra_headers = &.{
- .{ .name = "Location", .value = "http://127.0.0.1:9582/xhr" },
- },
- });
- }
-
- // Scripts, so a cross-origin (localhost) load doesn't depend on CORS.
- if (std.mem.eql(u8, path, "/resource-timing/tao")) {
- return req.respond("window.__rt_tao = true;", .{
- .extra_headers = &.{
- .{ .name = "Content-Type", .value = "text/javascript" },
- .{ .name = "Timing-Allow-Origin", .value = "https://example.com, *" },
- },
- });
- }
-
- if (std.mem.eql(u8, path, "/resource-timing/plain")) {
- return req.respond("window.__rt_plain = true;", .{
- .extra_headers = &.{
- .{ .name = "Content-Type", .value = "text/javascript" },
- },
- });
- }
-
- if (std.mem.eql(u8, path, "/resource-timing/redirect")) {
- return req.respond("", .{
- .status = .found,
- .extra_headers = &.{
- .{ .name = "Location", .value = "/resource-timing/plain" },
- },
- });
- }
-
- if (std.mem.eql(u8, path, "/redirect-no-fragment")) {
- return req.respond("", .{
- .status = .found,
- .extra_headers = &.{
- .{ .name = "Location", .value = "/redirect-target" },
- },
- });
- }
-
- if (std.mem.eql(u8, path, "/redirect-cross-origin-x-hop")) {
- return req.respond("", .{
- .status = .found,
- .extra_headers = &.{
- .{ .name = "Location", .value = "http://localhost:9582/echo-x-hop" },
- },
- });
- }
-
- // Bounces to the same path on the other loopback host, e.g. for an iframe
- // whose origin must change between its request and its response.
- if (std.mem.startsWith(u8, path, "/redirect-cross-origin/")) {
- var location_buf: [1024]u8 = undefined;
- const location = try std.mem.print(&location_buf, "http://localhost:9582/{s}", .{path["/redirect-cross-origin/".len..]});
- return req.respond("", .{
- .status = .found,
- .extra_headers = &.{
- .{ .name = "Location", .value = location },
- },
- });
- }
-
- if (std.mem.eql(u8, path, "/echo-x-hop")) {
- var it = req.iterateHeaders();
- var value: []const u8 = "NONE";
- while (it.next()) |header| {
- if (std.ascii.eqlIgnoreCase(header.name, "x-hop")) {
- value = header.value;
- break;
- }
- }
- return req.respond(value, .{
- .extra_headers = &.{
- .{ .name = "Content-Type", .value = "text/plain; charset=utf-8" },
- },
- });
- }
-
- if (std.mem.eql(u8, path, "/redirect-target")) {
- return req.respond("<!DOCTYPE html><title>landed</title>", .{
- .extra_headers = &.{
- .{ .name = "Content-Type", .value = "text/html; charset=utf-8" },
- },
- });
- }
-
- if (std.mem.eql(u8, path, "/303-no-location")) {
- // 3xx WITHOUT a Location header: not a redirect, a final response
- // whose body must be delivered (RFC 9110 §15.4).
- return req.respond("<!DOCTYPE html><title>landed</title><p>see other body</p>", .{
- .status = .see_other,
- .extra_headers = &.{
- .{ .name = "Content-Type", .value = "text/html; charset=utf-8" },
- },
- });
- }
-
- if (std.mem.eql(u8, path, "/300-with-location")) {
- // A non-redirect 3xx (fetch's redirect statuses are only 301, 302,
- // 303, 307 and 308) carrying a Location header: the header is a
- // preference hint, not a redirect — the body must be delivered.
- return req.respond("<!DOCTYPE html><title>choices</title><p>multiple choices body</p>", .{
- .status = .multiple_choice,
- .extra_headers = &.{
- .{ .name = "Content-Type", .value = "text/html; charset=utf-8" },
- .{ .name = "Location", .value = "http://127.0.0.1:9582/hi.html" },
- },
- });
- }
-
- if (std.mem.eql(u8, path, "/redirect-with-fragment")) {
- return req.respond("", .{
- .status = .found,
- .extra_headers = &.{
- .{ .name = "Location", .value = "/redirect-target#target_fragment" },
- },
- });
- }
-
- if (std.mem.eql(u8, path, "/xhr/404")) {
- return req.respond("Not Found", .{
- .status = .not_found,
- .extra_headers = &.{
- .{ .name = "Content-Type", .value = "text/plain" },
- },
- });
- }
-
- if (std.mem.eql(u8, path, "/src/browser/tests/401")) {
- return req.respond("No", .{
- .status = .unauthorized,
- .extra_headers = &.{
- .{ .name = "Content-Type", .value = "text/plain" },
- },
- });
- }
-
- if (std.mem.eql(u8, path, "/404.js")) {
- // Valid JS body served with a 404 status. Used to assert that
- // ScriptManager does NOT execute the body of a failed script
- // fetch — if it did, window.__404_body_executed would be set.
- return req.respond("window.__404_body_executed = true;", .{
- .status = .not_found,
- .extra_headers = &.{
- .{ .name = "Content-Type", .value = "application/javascript" },
- },
- });
- }
-
- if (std.mem.eql(u8, path, "/defer-marker.js")) {
- // A deferred script body. Used by the regression test for a
- // <script defer> whose completion is deferred by a later
- // <link rel=stylesheet>'s synchronous fetch — it must still execute.
- return req.respond("window.__deferRan = true;", .{
- .extra_headers = &.{
- .{ .name = "Content-Type", .value = "application/javascript" },
- },
- });
- }
-
- if (std.mem.startsWith(u8, path, "/serve-count/") and std.mem.endsWith(u8, path, ".js")) {
- // Serves `window.__serve_count_<name> = N;` where N counts how many
- // times this URL has been served. Lets a fixture assert a preloaded
- // script was fetched exactly once: the body the consumer executes
- // carries N == 1, while a duplicate fetch would execute N == 2.
- // no-store so the second fetch can't be satisfied by the HTTP cache.
- const name = path["/serve-count/".len .. path.len - ".js".len];
- const slot: *u32 = blk: {
- for (&serve_counts) |*sc| {
- if (std.mem.eql(u8, sc.name, name)) break :blk &sc.count;
- }
- return req.respond("unknown counter", .{ .status = .not_found });
- };
- slot.* += 1;
- var buf: [64]u8 = undefined;
- const body = try std.mem.print(&buf, "window.__serve_count_{s} = {d};", .{ name, slot.* });
- return req.respond(body, .{
- .extra_headers = &.{
- .{ .name = "Content-Type", .value = "application/javascript" },
- .{ .name = "Cache-Control", .value = "no-store" },
- },
- });
- }
-
- if (std.mem.eql(u8, path, "/challenge/vercel")) {
- return req.respond("<title>Vercel Security Checkpoint</title>", .{
- .status = .too_many_requests,
- .extra_headers = &.{
- .{ .name = "Content-Type", .value = "text/html; charset=utf-8" },
- .{ .name = "x-vercel-mitigated", .value = "challenge" },
- },
- });
- }
-
- if (std.mem.startsWith(u8, path, "/status/")) {
- const code = try std.fmt.parseInt(u16, path["/status/".len..], 10);
- return req.respond("", .{ .status = @fromBackingInt(@intCast(code)) });
- }
-
- if (std.mem.eql(u8, path, "/xhr/reason")) {
- return req.respond("", .{
- .status = .service_unavailable,
- .reason = "HOUSTON WE HAVE A",
- });
- }
-
- if (std.mem.eql(u8, path, "/xhr/duplicate_headers")) {
- return req.respond("", .{
- .extra_headers = &.{
- .{ .name = "X-B", .value = "1" },
- .{ .name = "X-A", .value = "a" },
- .{ .name = "X-B", .value = "2, 3" },
- .{ .name = "X_C", .value = "c" },
- },
- });
- }
-
- if (std.mem.eql(u8, path, "/xhr/401")) {
- return req.respond("No", .{
- .status = .unauthorized,
- .extra_headers = &.{
- .{ .name = "WWW-Authenticate", .value = "Basic realm=\"test\"" },
- },
- });
- }
-
- if (std.mem.eql(u8, path, "/xhr/500")) {
- return req.respond("Internal Server Error", .{
- .status = .internal_server_error,
- .extra_headers = &.{
- .{ .name = "Content-Type", .value = "text/plain" },
- },
- });
- }
-
- if (std.mem.eql(u8, path, "/xhr/bad_gzip")) {
- return req.respond("not actually gzip", .{
- .extra_headers = &.{
- .{ .name = "Content-Encoding", .value = "gzip" },
- },
- });
- }
-
- if (std.mem.eql(u8, path, "/xhr/no_content_type")) {
- return req.respond("untyped", .{});
- }
-
- if (std.mem.eql(u8, path, "/xhr/binary")) {
- return req.respond(&.{ 0, 0, 1, 2, 0, 0, 9 }, .{
- .extra_headers = &.{
- .{ .name = "Content-Type", .value = "application/octet-stream" },
- },
- });
- }
-
- if (std.mem.eql(u8, path, "/sse/simple")) {
- // A complete stream: default + custom event types, multi-line data,
- // an id, and a comment. The connection closes right after; the test
- // close()s before the (1s) reconnect fires.
- return req.respond("retry: 1000\ndata: first\n\n: comment\nid: 42\nevent: custom\ndata: a\ndata: b\n\n", .{
- .extra_headers = &.{
- .{ .name = "Content-Type", .value = "text/event-stream" },
- },
- });
- }
-
- if (std.mem.eql(u8, path, "/stop_loading/streaming.html")) {
- var send_buffer: [1024]u8 = undefined;
- var res = try req.respondStreaming(&send_buffer, .{
- .respond_options = .{
- .extra_headers = &.{
- .{ .name = "Content-Type", .value = "text/html; charset=utf-8" },
- },
- },
- });
- try res.writer.writeAll("<html><body><p id=first>first</p>");
- try res.writer.flush();
- try res.flush();
- lp.io.sleep(.fromMilliseconds(1500), .awake) catch {};
- try res.writer.writeAll("<p id=second>second</p></body></html>");
- try res.writer.flush();
- return res.end();
- }
-
- if (std.mem.eql(u8, path, "/sse/streaming")) {
- sse_flag.store(false, .release);
- var send_buffer: [1024]u8 = undefined;
- var res = try req.respondStreaming(&send_buffer, .{
- .respond_options = .{
- .extra_headers = &.{
- .{ .name = "Content-Type", .value = "text/event-stream" },
- },
- },
- });
- try res.writer.writeAll("data: first\n\n");
- try res.writer.flush();
- try res.flush();
-
- // Proof of progressive delivery: "second" is only sent once the
- // client has reacted to "first" (by fetching /sse/flag), which it
- // can only do if "first" was delivered while this response was
- // still streaming.
- var waited: usize = 0;
- while (!sse_flag.load(.acquire) and waited < 5000) : (waited += 10) {
- lp.io.sleep(.fromMilliseconds(10), .awake) catch {};
- }
- if (sse_flag.load(.acquire)) {
- // split mid-line to exercise buffering across chunks
- try res.writer.writeAll("data: sec");
- try res.writer.flush();
- try res.flush();
- lp.io.sleep(.fromMilliseconds(20), .awake) catch {};
- try res.writer.writeAll("ond\n\n");
- try res.writer.flush();
- try res.flush();
- }
- return res.end();
- }
-
- if (std.mem.eql(u8, path, "/sse/flag")) {
- sse_flag.store(true, .release);
- return req.respond("", .{});
- }
-
- if (std.mem.eql(u8, path, "/sse/reconnect")) {
- if (sse_reconnect_hits.fetchAdd(1, .monotonic) == 0) {
- return req.respond("retry: 10\ndata: one\n\n", .{
- .extra_headers = &.{
- .{ .name = "Content-Type", .value = "text/event-stream" },
- },
- });
- }
- return req.respond("data: two\n\n", .{
- .extra_headers = &.{
- .{ .name = "Content-Type", .value = "text/event-stream" },
- },
- });
- }
-
- if (std.mem.eql(u8, path, "/sse/long_retry")) {
- return req.respond("retry: 60000\ndata: x\n\n", .{
- .extra_headers = &.{
- .{ .name = "Content-Type", .value = "text/event-stream" },
- },
- });
- }
-
- if (std.mem.eql(u8, path, "/sse/404")) {
- return req.respond("data: x\n\n", .{
- .status = .not_found,
- .extra_headers = &.{
- .{ .name = "Content-Type", .value = "text/event-stream" },
- },
- });
- }
-
- if (std.mem.eql(u8, path, "/sse/badmime")) {
- return req.respond("data: x\n\n", .{
- .extra_headers = &.{
- .{ .name = "Content-Type", .value = "text/plain" },
- },
- });
- }
-
- if (std.mem.eql(u8, path, "/styles/important-cascade.css")) {
- return req.respond(".no-js-flex { display: none !important; }", .{
- .extra_headers = &.{
- .{ .name = "Content-Type", .value = "text/css" },
- },
- });
- }
-
- if (std.mem.eql(u8, path, "/styles/visibility.css")) {
- // Used by css/external_stylesheet.html — drives the visibility
- // cascade through StyleManager via Frame.loadExternalStylesheet
- // so a `.ext-hide` element is observable to checkVisibility().
- return req.respond(".ext-hide { display: none; }", .{
- .extra_headers = &.{
- .{ .name = "Content-Type", .value = "text/css" },
- },
- });
- }
-
- if (std.mem.eql(u8, path, "/styles/visibility2.css")) {
- // Second visibility sheet used by the href-change regression test:
- // mutating link.href must replace the cached sheet's rules in place,
- // not append a new entry to document.styleSheets.
- return req.respond(".ext-hide-2 { display: none; }", .{
- .extra_headers = &.{
- .{ .name = "Content-Type", .value = "text/css" },
- },
- });
- }
-
- // Latin-1 bytes in the reason phrase, a header name and a header value.
- if (std.mem.eql(u8, path, "/latin1_response")) {
- return req.respond("latin1", .{
- .reason = "Caf\xE9",
- .extra_headers = &.{
- .{ .name = "Content-Type", .value = "text/plain" },
- .{ .name = "X-Latin1", .value = "La\xA0Paz" },
- .{ .name = "X-Caf\xE9", .value = "1" },
- },
- });
- }
-
- // Latin-1 sheets for css/stylesheet_charset.html: undecoded, the 0xE9
- // swallows the bytes after it and the rule that follows is lost.
- if (std.mem.eql(u8, path, "/styles/latin1-header.css")) {
- return req.respond("/* caf\xE9 */ .by-header { display: none; --name: \"caf\xE9\"; }", .{
- .extra_headers = &.{
- .{ .name = "Content-Type", .value = "text/css; charset=iso-8859-1" },
- },
- });
- }
-
- if (std.mem.eql(u8, path, "/styles/latin1-at-charset.css")) {
- return req.respond("@charset \"windows-1252\"; /* caf\xE9 */ .by-at-charset { display: none; }", .{
- .extra_headers = &.{
- .{ .name = "Content-Type", .value = "text/css" },
- },
- });
- }
-
- if (std.mem.eql(u8, path, "/styles/truncated-utf8.css")) {
- return req.respond(".before-truncated { display: none; } \xE2", .{
- .extra_headers = &.{
- .{ .name = "Content-Type", .value = "text/css" },
- },
- });
- }
-
- // Latin-1 scripts for page/script_charset.html. /scripts/latin1/<name>.js
- // and /scripts/latin1-header/<name>.js set window[<name>], the latter
- // declaring its charset.
- if (std.mem.eql(u8, path, "/scripts/bom-over-header.js")) {
- return req.respond("\xEF\xBB\xBFwindow.byBom = 'caf\xC3\xA9';", .{
- .extra_headers = &.{
- .{ .name = "Content-Type", .value = "text/javascript; charset=iso-8859-1" },
- },
- });
- }
-
- const declares_charset = std.mem.startsWith(u8, path, "/scripts/latin1-header/");
- if (declares_charset or std.mem.startsWith(u8, path, "/scripts/latin1/")) {
- const body = try std.fmt.allocPrint(req_allocator, "window['{s}'] = 'caf\xE9';", .{std.fs.path.stem(path)});
- const content_type = if (declares_charset) "text/javascript; charset=iso-8859-1" else "text/javascript";
- return req.respond(body, .{
- .extra_headers = &.{
- .{ .name = "Content-Type", .value = content_type },
- },
- });
- }
-
- if (std.mem.eql(u8, path, "/styles/404.css")) {
- return req.respond("/* unused */", .{
- .status = .not_found,
- .extra_headers = &.{
- .{ .name = "Content-Type", .value = "text/css" },
- },
- });
- }
-
- if (std.mem.eql(u8, path, "/styles/large.css")) {
- // Over 2 MiB, with the rule under test last.
- const chunk = ".pad { color: #abcdef; } "; // 25 bytes
- const tail = ".large-hide { display: none; }";
- const repeats = 5 * 1024 * 1024 / 2 / chunk.len;
- var body = try std.ArrayList(u8).initCapacity(req_allocator, chunk.len * repeats + tail.len);
- for (0..repeats) |_| body.appendSliceAssumeCapacity(chunk);
- body.appendSliceAssumeCapacity(tail);
- return req.respond(body.items, .{
- .extra_headers = &.{
- .{ .name = "Content-Type", .value = "text/css" },
- },
- });
- }
-
- if (std.mem.eql(u8, path, "/styles/oversize.css")) {
- // Body that exceeds Frame.MAX_STYLESHEET_BYTES — written as a
- // long sequence of valid declarations so the response itself parses
- // fine and the error path is exercised by the size cap, not by a
- // CSS parse failure.
- const chunk = ".pad { color: #abcdef; } "; // 25 bytes
- const repeats = (Frame.MAX_STYLESHEET_BYTES / chunk.len) + 1024;
- var body = try std.ArrayList(u8).initCapacity(req_allocator, chunk.len * repeats);
- for (0..repeats) |_| body.appendSliceAssumeCapacity(chunk);
- return req.respond(body.items, .{
- .extra_headers = &.{
- .{ .name = "Content-Type", .value = "text/css" },
- },
- });
- }
-
- // Bodies are non-empty so that libcurl always reaches the write callback,
- // which is where a partial request decides whether to drain or abort.
- // ok.png takes the abort branch, small.png the drain branch; both must
- // behave identically as far as the DOM is concerned.
- if (std.mem.eql(u8, path, "/images/ok.png")) {
- // > HttpClient.Request.PARTIAL_DRAIN_MAX. The synthetic PNG
- // header advertises 1000 x 750 pixels; no bitmap is decoded.
- const body = try req_allocator.alloc(u8, 16 * 1024 + 1);
- @memset(body, 'x');
- @memcpy(body[0..24], "\x89PNG\r\n\x1a\n\x00\x00\x00\x0dIHDR\x00\x00\x03\xe8\x00\x00\x02\xee");
- return req.respond(body, .{
- .extra_headers = &.{
- .{ .name = "Content-Type", .value = "image/png" },
- },
- });
- }
-
- // startsWith, not eql: a caller can append a query string to get distinct
- // URLs (and so distinct transfers) off this one route.
- if (std.mem.startsWith(u8, path, "/images/small.png")) {
- const body = try req_allocator.alloc(u8, 1024);
- @memset(body, 'x');
- @memcpy(body[0..24], "\x89PNG\r\n\x1a\n\x00\x00\x00\x0dIHDR\x00\x00\x01\x40\x00\x00\x00\xf0");
- return req.respond(body, .{
- .extra_headers = &.{
- .{ .name = "Content-Type", .value = "image/png" },
- },
- });
- }
-
- if (std.mem.eql(u8, path, "/images/photo.jpg")) {
- const body = "\xff\xd8\xff\xe1\x00\x04\x00\x00\xff\xc0\x00\x0b\x08\x02\xee\x03\xe8\x01\x01\x11\x00";
- return req.respond(body, .{
- .extra_headers = &.{
- .{ .name = "Content-Type", .value = "image/jpeg" },
- },
- });
- }
-
- // No Content-Length: whether the body is small enough to drain can only
- // be decided as it arrives.
- if (std.mem.eql(u8, path, "/images/chunked.png")) {
- var send_buffer: [1024]u8 = undefined;
- var res = try req.respondStreaming(&send_buffer, .{
- .respond_options = .{
- .extra_headers = &.{
- .{ .name = "Content-Type", .value = "image/svg+xml" },
- },
- },
- });
- try res.writer.writeAll("<svg xmlns=\"http://www.w3.org/2000/svg\"/>");
- try res.writer.flush();
- return res.end();
- }
-
- if (std.mem.eql(u8, path, "/images/404.png")) {
- return req.respond("not here", .{
- .status = .not_found,
- .extra_headers = &.{
- .{ .name = "Content-Type", .value = "text/plain" },
- },
- });
- }
-
- if (std.mem.eql(u8, path, "/images/500.png")) {
- return req.respond("boom", .{
- .status = .internal_server_error,
- .extra_headers = &.{
- .{ .name = "Content-Type", .value = "text/plain" },
- },
- });
- }
-
- if (std.mem.eql(u8, path, "/images/redirect.png")) {
- return req.respond("", .{
- .status = .found,
- .extra_headers = &.{
- .{ .name = "Location", .value = "/images/ok.png" },
- },
- });
- }
-
- if (std.mem.eql(u8, path, "/echo_referer")) {
- // Echo the request's Referer header back as HTML so tests can assert
- // what Referer the navigation sent. Used by the cross-page Referer test.
- var it = req.iterateHeaders();
- var referer: []const u8 = "NONE";
- while (it.next()) |h| {
- if (std.ascii.eqlIgnoreCase(h.name, "Referer")) {
- referer = h.value;
- break;
- }
- }
- var html_buf: [512]u8 = undefined;
- const html = try std.mem.print(&html_buf, "<html><body>referer={s}</body></html>", .{referer});
- return req.respond(html, .{
- .extra_headers = &.{
- .{ .name = "Content-Type", .value = "text/html; charset=utf-8" },
- .{ .name = "Access-Control-Allow-Origin", .value = origin(req) orelse "*" },
- },
- });
- }
-
- if (std.mem.eql(u8, path, "/referer_link.html")) {
- // Page with an anchor link to /echo_referer. The test clicks the link
- // via JS and asserts the resulting page reports Referer = this page.
- return req.respond(
- "<html><body><a id=\"link\" href=\"/echo_referer\">go</a></body></html>",
- .{
- .extra_headers = &.{
- .{ .name = "Content-Type", .value = "text/html; charset=utf-8" },
- },
- },
- );
- }
-
- if (std.mem.eql(u8, path, "/echo_method")) {
- // Echo the request method back as HTML so tests can assert on what
- // method the navigation used. Used by the Page.reload-replays-POST test.
- const method_name = @tagName(req.head.method);
- var html_buf: [128]u8 = undefined;
- const html = try std.mem.print(&html_buf, "<html><body>method={s}</body></html>", .{method_name});
- return req.respond(html, .{
- .extra_headers = &.{
- .{ .name = "Content-Type", .value = "text/html; charset=utf-8" },
- },
- });
- }
-
- if (std.mem.eql(u8, path, "/echo_body")) {
- // Echo the request body back verbatim, so tests can assert on the bytes
- // a request actually sent rather than just on its status.
- var body_buf: [4096]u8 = undefined;
- const body = if (req.head.method.requestHasBody())
- try req.readerExpectNone(&body_buf).allocRemaining(req_allocator, .limited(body_buf.len))
- else
- "";
- return req.respond(body, .{
- .extra_headers = &.{
- .{ .name = "Content-Type", .value = "text/plain; charset=utf-8" },
- },
- });
- }
-
- if (std.mem.eql(u8, path, "/echo_brotli")) {
- // Echo the request body back as `Content-Encoding: br`, so the HTTP
- // client decodes it; checks CompressionStream('brotli') output with a
- // decoder that isn't ours.
- var body_buf: [4096]u8 = undefined;
- const body = try req.readerExpectNone(&body_buf).allocRemaining(req_allocator, .limited(4 * 1024 * 1024));
- return req.respond(body, .{
- .extra_headers = &.{
- .{ .name = "Content-Type", .value = "application/octet-stream" },
- .{ .name = "Content-Encoding", .value = "br" },
- },
- });
- }
-
- if (std.mem.eql(u8, path, "/echo_headers")) {
- if (req.head.method == .OPTIONS) {
- return req.respond("", .{
- .extra_headers = &.{
- .{ .name = "Access-Control-Allow-Origin", .value = origin(req) orelse "*" },
- .{ .name = "Access-Control-Allow-Methods", .value = "GET" },
- .{ .name = "Access-Control-Allow-Headers", .value = "x-hop" },
- },
- });
- }
-
- // Echo every request header back as "name: value" lines, so tests
- // can assert on the headers a request actually sent.
- var buf: [8192]u8 = undefined;
- var pos: usize = 0;
- var it = req.iterateHeaders();
- while (it.next()) |header| {
- const line = try std.mem.print(buf[pos..], "{s}: {s}\n", .{ header.name, header.value });
- pos += line.len;
- }
- return req.respond(buf[0..pos], .{
- .extra_headers = &.{
- .{ .name = "Content-Type", .value = "text/plain; charset=utf-8" },
- .{ .name = "Access-Control-Allow-Origin", .value = origin(req) orelse "*" },
- },
- });
- }
-
- if (std.mem.eql(u8, path, "/set_cookie")) {
- return req.respond("", .{
- .extra_headers = &.{
- .{ .name = "Set-Cookie", .value = "lp_hidden=1; Path=/set_cookie_scope" },
- .{ .name = "X-Visible", .value = "yes" },
- },
- });
- }
-
- if (std.mem.eql(u8, path, "/redirect_same_echo_headers")) {
- // Same-origin 302 to /echo_headers: Authorization must survive the hop.
- return req.respond("", .{
- .status = .found,
- .extra_headers = &.{
- .{ .name = "Location", .value = "/echo_headers" },
- },
- });
- }
-
- if (std.mem.eql(u8, path, "/redirect_cross_echo_headers")) {
- // 302 to /echo_headers on the localhost alias — a cross-origin hop, so
- // Authorization must be stripped before the request is re-sent.
- return req.respond("", .{
- .status = .found,
- .extra_headers = &.{
- .{ .name = "Location", .value = "http://localhost:9582/echo_headers" },
- },
- });
- }
-
- if (std.mem.eql(u8, path, "/redirect_same_echo_referer")) {
- // Same-origin 302 to /echo_referer: the full Referer must survive the hop.
- return req.respond("", .{
- .status = .found,
- .extra_headers = &.{
- .{ .name = "Location", .value = "/echo_referer" },
- },
- });
- }
-
- if (std.mem.eql(u8, path, "/redirect_cross_echo_referer")) {
- // 302 to /echo_referer on the localhost alias — a cross-origin hop, so
- // the Referer must be recomputed at the redirect (stripped to origin
- // under the default policy) rather than re-sent in full.
- return req.respond("", .{
- .status = .found,
- .extra_headers = &.{
- .{ .name = "Location", .value = "http://localhost:9582/echo_referer" },
- },
- });
- }
-
- if (std.mem.eql(u8, path, "/redirect_to_echo")) {
- // 302 to /echo_method. Used by the Page.reload-after-redirect test to
- // confirm a POST→302→GET chain doesn't replay POST on reload.
- return req.respond("", .{
- .status = .found,
- .extra_headers = &.{
- .{ .name = "Location", .value = "/echo_method" },
- },
- });
- }
-
- if (std.mem.eql(u8, path, "/download/report.csv")) {
- // A file download: Content-Disposition: attachment drives the
- // Browser.setDownloadBehavior path (issue #2701).
- return req.respond("col1,col2\nhello,world\n42,1337\n", .{
- .extra_headers = &.{
- .{ .name = "Content-Type", .value = "text/csv" },
- .{ .name = "Content-Disposition", .value = "attachment; filename=\"report.csv\"" },
- },
- });
- }
-
- if (std.mem.startsWith(u8, path, "/src/browser/tests/")) {
- if (std.mem.find(u8, path, "delay_ms=")) |pos| {
- const digits_start = pos + "delay_ms=".len;
- var end = digits_start;
- while (end < path.len and std.ascii.isDigit(path[end])) : (end += 1) {}
- const delay_ms = std.fmt.parseInt(u64, path[digits_start..end], 10) catch 0;
- lp.io.sleep(.fromMilliseconds(@intCast(delay_ms)), .awake) catch {};
- }
- // strip off leading / so that it's relative to CWD
- return TestHTTPServer.sendFile(req, path[1..]);
- }
-
- std.debug.print("TestHTTPServer was asked to serve an unknown file: {s}\n", .{path});
-
- unreachable;
-}
-
/// Declares the log lines a test expects to emit: one entry per line, so
/// `&.{ .js, .js, .http }` covers two `js` lines and one `http` line.
pub const expectLog = log.expectLog;