Runtime.consoleAPICalled and Runtime.exceptionThrown wrapped their values
in the main frame's context and reported its executionContextId, even for
an iframe's message or exception.
Console messages now carry the frame they were logged in, read from the
calling context's global (a worker's is its owner's). The Runtime handlers
use the event's frame, or the main frame when it is gone.
page_id held the page's root frame id, a concept nothing else uses.
Name it frame_id like the other notifications and fill it with the frame
the event happened in; CDP maps it to its target like the frame events.
Console messages keep the page's root frame: Execution knows its page,
not its frame.
A CDP connection could open a single page: Target.createTarget failed
once a target existed, so Puppeteer's browser.newPage() or Playwright's
context.newPage() worked only once.
Per-page CDP state moves from BrowserContext to a new Target: target
and session ids, node registry, isolated worlds, preload scripts,
network capture, Fetch interception, extra headers, dialogs, WebMCP
invocations. A command reaches the target of the session it was sent
through, or the first target without a session. The context routes
frame lifecycle events to the page's target by frame id; a target
registers itself for the events it enables (Network, Fetch, Runtime,
Console, lifecycle, WebMCP) and keeps those of its page.
Each target is its own V8 inspector context group, so a session sees
only its page's execution contexts. Console messages, exceptions and
dialogs now carry their page's root frame id.
The Target domain handles any number of targets, up to 16 per
connection. Closing a target frees it and leaves the others running.
Popups stay frames of their opener's page, and viewport, user agent
and download events stay context-wide.
Add a new LP.waitUntil that mimics the fetch `--wait-until` flag. Clients that
provide a `waitUntil` behavior, e.g. page.goto('...', {waitUntil: 'done'),
implement that logic in the client. So we can't extend it.
Also emits a `settled` `Page.lifecycleEvent` (when lifecycle events are enabled)
Both puppeteer and playwright ignore unknown events.
There's no such CDP API, hence I've rolled `lp-stream-over-cdp` download behavior to add support for it. Sad part is we have to encode bytes we're sending since JSON cannot represent raw binary.
encodedDataLength was the Content-Length header: 0 for a chunked or
streamed response, the compressed length without any header byte for a
gzipped one. Chrome reports the bytes the response put on the wire, its
headers and its body as received (still compressed).
A response fetched over the network now reports libcurl's header size
(CURLINFO_HEADER_SIZE) plus its body bytes as received
(CURLINFO_SIZE_DOWNLOAD_T, after chunk framing is removed, before
decompression). A redirect counts its final hop, a revalidated 304 its
own bytes rather than the cached body it unlocks, and a partial fetch
that stops early what arrived before it stopped. A cache hit, a
fulfilled or a synthetic response keeps reporting its body length.
Network.responseReceived's encodedDataLength is unchanged.
The bridge would detect a trailing slice and map 0 or more parameters to it,
allow JS variadic functions to map simply to Zig. This introduces an
js.Variadic(T) type and makes the process explicit.
Why? because the current approach is ambiguous and sometimes wrong. You see
this in Slot.assign which has to take a `js.Value` so that it can reject an
array.
Consider DOMTokenList.add with the ambiguous `[]const []const u8`. Given the
JS argument ["a", "b"]...should it map to a Zig slice with 2 values or a single
"a,b" value. On `main` it incorrectly maps it to a slice with 2 values. Now,
it correctly gets mapped to "a,b".
This is inspired by https://github.com/lightpanda-io/browser/pull/4088 which
added better iterable support.
Rather than erroring, return an optional and let the caller decide how to handle
it. This is more explicit and avoids the temptation to swallow an unrelated
error.
Since #3905 an uncaught exception emits Runtime.exceptionThrown, but an
unhandled promise rejection doesn't, so Puppeteer's and Playwright's
page.on('pageerror') never hear of it. Chrome sends it with text
"Uncaught (in promise)" and the reason as the exception.
It can't be reported from V8's reject callback: that fires for every
promise rejected with no handler yet, including Promise.reject(x).catch(f)
and an async function that throws before its caller attaches .catch().
"unhandledrejection" was dispatched there, followed by "rejectionhandled",
for promises that were never unhandled.
A promise rejected with no handler is now kept on its context; a handler
attached before the end of the microtask checkpoint withdraws it silently.
What is left at the end of the checkpoint gets "unhandledrejection" (now
cancelable), as HTML's "notify about rejected promises" does, and unless
the page cancels it, it is logged as a page_error and reported through
the exception_thrown notification, which CDP sends with "Uncaught (in
promise)". Listeners can queue microtasks, so the checkpoint runs again,
a bounded number of times.
A module script that throws while it evaluates rejects its evaluation
promise instead of throwing. That rejection is ours: the exception is
reported like a classic script's, with an "error" event and "Uncaught".
Fetch.enable dropped every pattern with requestStage: "Response", so a
client asking to see responses before the page does got no pauses and no
error. A crawler that needs to decide from the real status and headers
whether to render a document, keep its raw bytes (a PDF, an XML sitemap,
an image) or refuse it had no way to do so: by the time Network events
report the response, the browser has already parsed it as a page.
A completed transfer is now parked before delivery, the way an auth
challenge already is: the conn is released and the response is
materialized, so nothing holds network resources while CDP decides.
Final responses, redirect responses and network failures are paused, as
the protocol describes; a failure the consumer caused (abort, cancel) is
not offered. Releasing a pause unchanged delivers the response, follows
the redirect, or reports the failure exactly as it would have been
without interception.
handleRedirect now reads the materialized response instead of the conn,
so a redirect can wait at the response stage after its conn is gone.
Fetch.continueResponse and Fetch.getResponseBody are added, and allowed
during a blocking-script wait like the other interception commands;
without that, pausing a parser-blocking script's response deadlocks the
page. continueResponse with response overrides, and continueRequest's
interceptResponse, still return NotImplemented.
Fixes https://github.com/lightpanda-io/browser/issues/3912
Moves the window.close() come to Frame so that IFrame can use the code on
disconnect. The teardown is only partial, the window/iframe can still be
referenced. But we stop it from running, e.g. stop its schedule tasks.
An exception the page doesn't catch reaches Window.reportError (from
timers, rAF, inline handlers and listeners since #3755, microtasks and
observers since #3849), but no CDP event reported it, so clients had no
equivalent of Chrome's Runtime.exceptionThrown (Puppeteer and Playwright
build page.on('pageerror') on it).
reportError now dispatches an exception_thrown notification when the
error event isn't cancelled, which is when HTML leaves the exception
"not handled" and Chrome reports it. With Runtime enabled, the CDP layer
answers it the way it answers console messages: the value is wrapped by
the primary session's inspector as exceptionDetails.exception, with
text "Uncaught", and line, column and script come from
v8::Exception::CreateMessage.
Closes#3904
Dependencies:
- v8: zig-v8-fork 0.17 branch (lightpanda-io/zig-v8-fork#218).
- sqlite3: build the amalgamation directly; the allyourcodebase wrapper
has no 0.17 support yet.
- pcre2: master commit with 0.17 support (no release yet).
- translate_c package (2.0.0) replaces the deprecated addTranslateC.
default_init is set to keep 0.16's zero-initialized struct fields.
Build:
- b.pathFromRoot/build_root/args/sysroot are gone: resolve paths from
b.root, use addPassthruArgs, declare configure-time file and directory
dependencies, and poison the configure cache for the git version.
- Drop curl config values the template never used (now an error).
- Drop the 0.16 zip-fetch workaround from the Makefile and CI.
- -Doptimize=ReleaseFast -> -Doptimize=fast.
Language and std:
- @intFromEnum/@enumFromInt -> @backingInt/@fromBackingInt.
- Struct-of-arrays @typeInfo (field_names, field_types, decl_names,
param_types, error_names).
- `a ** n` removed: @splat for arrays, string.repeat for strings.
- errdefer captures removed: split WebDriver.run and fulfillRedirect.
- @hasDecl only sees pub decls: make StyleManager's Spec.finish pub,
otherwise it silently stops running.
- SafeAllocator replaces DebugAllocator; the test runner now has to
initialize std.testing.allocator_instance itself.
- std.fmt.allocPrint/bufPrint -> Allocator.print/std.mem.print,
dupeZ -> dupeSentinel, std.builtin -> std.lang, builtin.os ->
builtin.target.os, zon.parse arena API, BufferFirstAllocator, and the
remaining renames (getLastOrNull, bit_set, ascii.find*, meta.Int).
If you look at https://github.com/lightpanda-io/browser/pull/3293, you'll see
a relatively contained change that has to touch over 20 files. The issue is that
every HttpClient.newRequest needs to provide a lot of data. But `newRequest`
takes a 2nd parameter: the HttpClient.Owner. If we make that Owner a little
smarter, we can start to remove some of the individual fields needed in
newRequest. For example, we can still allow a callsite to pass frame_id but,
by default, we can use the owner's frame_id (which is what we want in most
cases).
Saw a non-fatal error on cnn.com related to console. All members are supposed
to be static. Ran it through WPT /console/ and improved a few different thigns:
- added dir and dirxml
- assert condition is optional
CDP driver can send multiple Network.enable which would register the same
listener multiple times. This commit makes it so that only one (the first)
callback registered for a listener+eventtype is used. Subsequent registration
for the same listener+eventtype are ignored. This is safe because all callbacks
are currently static. It's a mistake (enforced by a debug-only assertion) for
code to try to register a different callback for an already registered listener+
eventtype.
This generalizes https://github.com/lightpanda-io/browser/pull/3038
Built against https://github.com/lightpanda-io/zig-v8-fork/tree/zig-0.16 but
it doesn't require a new v8 build.
Built against https://github.com/lightpanda-io/boringssl-zig/tree/zig-0.16
since the current fork we point to isn't updated.
A global std.Io instance, lp.io. Way easier this way and requires 0 changes to
our libcurl integration / event loop.
Network code uses a new layer that does what Zig 0.15's posix package used to
do. Again, quicker migration that way. But, as long as we have the global IO,
and given the half-baked nature of networking in std.Io 0.16, this just makes
sense. Things can be migrated as needed.
The std.time.* -> std.Io.Timestamp/Clock/Duration resulted in _a lot_ of
changes. ArrayList = .{} -> ArrayList -> .empty also resulted in a lot of
changes, but that's obviously superficial. As is the trimLeft/trimRight ->
trimStart/trimEnd rename.
Locking adopt the `Uncancelable` variants, e.g. mutex.lockUncancelable() to
preserve the error-free signature (and, because cancellation would be something
we'd have to put more thought into).
std.json.ObjectMap is now unmanaged, so the allocator had to be passed along.
However, there's still a deprecated managed variant of MemoryPool, so I switched
to it (we can do a small follow up PR to move to the unmanaged after).
I tried use_llvm = false, but it locks my computer, consuming RAM until MacOS
gives me a popup I've never seen before, begging me to start killing processes.
Agent and the networking stuff saw the most significant changes.
CDP clients (Playwright/Puppeteer) never saw same-document navigations —
history.pushState / replaceState changed frame.url but fired no CDP event,
so frame.url() went stale and waitForNavigation missed SPA route changes.
Add a frame_navigated_within_document notification, dispatched from
History.pushState/replaceState, and emit Page.navigatedWithinDocument from
the Page domain with frameId, url, and navigationType. Unlike frameNavigated,
this deliberately does NOT send Runtime.executionContextsCleared or
DOM.documentUpdated — the document and its execution context are unchanged,
and clearing them would invalidate the client's live context ids and break
frame.evaluate(). Adds a cdp.frame test.
Scoped to the History-API path; fragment and Navigation-API paths are left
for follow-ups.
Replaces layering with an inline request pipeline, and transfer queue. This is
meant to simplify the code, reduce footguns, and make future enhancements easier
to implement (e.g. speculative parsing (which requires streaming to fully
leverage)).
Previously, HttpClient implemented deferring as a layer which required special
pumping at various callsites (https://github.com/lightpanda-io/browser/pull/2855,
https://github.com/lightpanda-io/browser/pull/2843, ...). In this new approach,
deferring is built-into the HttpClient/Transfer's flow. Specifically, Transfers
now maintain a queue of events (start, header, data, end, err) which are
dispatched in HttpClient.tick. The result is that JS callbacks are never
executed in the same stack that initiated the I/O, without needing guards or any
external intervention.
tTwo other benefits come from this. The first is that reentrant libcurl is
eliminated. Instead of "libcurl -> callback", it's now "libcurl -> transfer
event queue THEN tick -> callback" (we don't have to wait until the NEXT tick, we
can just do it later in the tick). HttpClient still has to guard against libcurl
reentrancy, but only because of how WebSocket is implemented, and we should be
able to unify WebSockets to use an event queue too in a follow up PR (which will
eliminate a bunch of guard code).
The transfer queue should also be useful to re-implement streaming, since a
data chunk is just an event in the transfer's event queue. For now, I kept it
as a single buffered event to minimize the change. But since speculative parsing
depends on this, and speculative parsing seems to be the next major performance
tweak we can make, we need to re-introduce streaming.
The other change is the removal of all other layers in favor of a pipeline. This
works well with the existing Transfer.park mechanism, where a parked Transfer
can restart the pipeline for a transfer in an arbitrary point (not as fancy as
it sounds given how simple the flow is). The fallout from this is that we're no
longer creating/wrapping contexts and callbacks: whatever the request was
configured with is all we need.
Because of this, HttpClient.Response is removed. There are no intermediary
responses and no changing context, everything is just the Transfer.
A smaller change is the addition of newRequest + transfer.submit(). The one-shot
HttpClient.request and HttpClient.requestT still exist, but this explicit create
+ submit has some advantage. First, callers can use the transfer.arena (e.g.
Frame using the transfer's arena to set the Referrer header). Second, callers
can holds Transfer immediately, rather than waiting for their startCallback to
be fired. An abort on an XMLHttpRequest called before the start of the transfer
no longer silently fails.
Browser.setDownloadBehavior was a noop, so Lightpanda had no file-download
path. A response with Content-Disposition: attachment is now streamed to disk
under downloadPath, and Page.downloadWillBegin / Browser.downloadProgress are
emitted when eventsEnabled.
Fixes#2701
console.log and console.warn were both dispatched as .info, so
Runtime.consoleAPICalled (and Console.messageAdded) reported type
"info" for all three of log/info/warn — clients filtering console
output by severity saw them collapsed into one bucket.
Add log/warning members to ConsoleMessageType (the protocol's wire
values — "warning", not "warn") and map console.log -> log,
console.warn -> warning. info/error/debug/trace already matched.
Closes#2730
A root navigation that fails before any response headers arrive
(connection refused, DNS failure, TLS error) never answered the
Page.navigate command: the success reply is only sent from the
response-header path (frame_navigated), and frameErrorCallback dropped
the stored cdp_id along with the pending Page. The CDP client awaiting
the response was left hanging forever.
Dispatch a frame_navigate_failed notification from frameErrorCallback
when no response headers were processed (_http_status == null guards
against double-answering mid-body failures), and answer the pending
command with {frameId, loaderId, errorText} — matching Chrome, where
errorText is "present if and only if navigation has failed".
Closes#2728
1 - Track owner of a request (for simpler / more accurate abort (TBD))
2 - Create Transfer upfront, make everything work on Transfer (not Request)
This helps remove ambiguity about cleanup and simplifies layers. For example
Robots request is just another normal request, not a special case. This gives
everything a stable address (the *Transfer which can be looked up by id)
During a root navigation, we keep the existing page active until we get
the headers callback from the pending page. Then
Session.commitPendingPage makes the switch.
It delays the deinit of CPD execution context to handle JS execution in
the meantime.
Now session has an array of two pages, _active_idx points to the main
page.
Both active and pending pages share the same frame_id, it must remains
stable. So this PR adds a Request.protect_from_abort to avoid removing
the request form the pending page when deinit the previous active page.