Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust
Rust ai-agentsai-toolsbrowserbrowser-automationcloud-browserheadlessheadless-browserkitesurfplaywrightpuppeteerrustservoweb-crawlerweb-crawlingweb-scraperweb-scraping
fix(style): resolve imported web fonts from owning sheet
ldm099537792b6a7
diff --git a/moli-renderer-v8/src/css_resource_urls.rs b/moli-renderer-v8/src/css_resource_urls.rsindex 28e46c282..553401929 100644--- a/moli-renderer-v8/src/css_resource_urls.rs+++ b/moli-renderer-v8/src/css_resource_urls.rs@@ -164,23 +164,57 @@ pub(crate) fn stylesheet_web_font_resource() -> Option<StylesheetLoadBlockingResource> {let descriptor = parsed_web_font_face(css_text)?;let request_url = preferred_font_source_url(descriptor.source(), base_url)?;+ Some(stylesheet_web_font_resource_with_descriptor(+ css_text,+ request_url,+ descriptor,+ ))+}++/// Projects a native Stylo `@font-face` rule using the URL already resolved+/// in that rule's own parser context.+///+/// Imported rules retain their imported stylesheet's URL context inside+/// `SpecifiedUrl`. Callers must use this entry point instead of resolving the+/// serialized, relative `src` value against the root stylesheet again.+pub(crate) fn stylesheet_web_font_resource_with_resolved_url(+ css_text: &str,+ request_url: Url,+) -> Option<StylesheetLoadBlockingResource> {+ if !matches!(request_url.scheme(), "http" | "https" | "data" | "blob") {+ return None;+ }+ let descriptor = parsed_web_font_face(css_text)?;+ Some(stylesheet_web_font_resource_with_descriptor(+ css_text,+ request_url,+ descriptor,+ ))+}++fn stylesheet_web_font_resource_with_descriptor(+ css_text: &str,+ request_url: Url,+ descriptor: ParsedWebFontFace,+) -> StylesheetLoadBlockingResource {// The slot describes a declaration, not a layout generation. Two- // identical declarations may safely share decoded font data, while a- // CSSOM replacement gets a different slot even when it occupies the same- // rule index.- let mut slot_material = Vec::with_capacity(base_url.as_str().len() + css_text.len() + 1);- slot_material.extend_from_slice(base_url.as_str().as_bytes());+ // projections of the same parsed rule (the import response and the later+ // retained style world) must converge on one slot. Conversely, identical+ // relative declarations parsed under different stylesheet bases must not+ // alias, so identity includes the resolved request URL.+ let mut slot_material = Vec::with_capacity(request_url.as_str().len() + css_text.len() + 1);+ slot_material.extend_from_slice(request_url.as_str().as_bytes());slot_material.push(0);slot_material.extend_from_slice(css_text.as_bytes());let slot = format!("stylesheet-font:{}", sha256_hex(&slot_material));- Some(StylesheetLoadBlockingResource::font(+ StylesheetLoadBlockingResource::font(request_url,StylesheetWebFont {slot,face: descriptor.into_face(),request_id: None,},- ))+ )}fn collect_font_face_rule_css(rules: &[moli_css_parse::CssRuleSnapshot], output: &mut Vec<String>) {@@ -517,6 +551,65 @@ mod tests {);}+ #[test]+ fn native_resolved_font_projection_converges_with_import_response_slot() {+ let css_text = r#"+ @font-face {+ font-family: Imported;+ src: local("Imported"),+ url("./fonts/imported.svg") format("svg"),+ url("./fonts/imported.woff2") format("woff2");+ font-weight: 625 800;+ unicode-range: U+20-7E;+ }+ "#;+ let imported_base =+ Url::parse("https://example.test/theme/imported.css").expect("imported base URL");+ let resolved = Url::parse("https://example.test/theme/fonts/imported.woff2")+ .expect("resolved native font URL");++ let response_projection = stylesheet_web_font_resource(css_text, &imported_base)+ .expect("the import response should project its font");+ let native_projection =+ stylesheet_web_font_resource_with_resolved_url(css_text, resolved.clone())+ .expect("the retained native rule should project its resolved font");++ assert_eq!(response_projection.request_url(), &resolved);+ assert_eq!(native_projection.request_url(), &resolved);+ assert_eq!(+ response_projection+ .web_font()+ .expect("response font")+ .slot(),+ native_projection.web_font().expect("native font").slot(),+ "the early import-response registration and retained manifest must keep one slot",+ );+ assert_eq!(+ response_projection+ .web_font()+ .expect("response font")+ .face(),+ native_projection.web_font().expect("native font").face(),+ );+ }++ #[test]+ fn resolved_request_url_keeps_identical_relative_rules_in_distinct_slots() {+ let css_text = "@font-face { font-family: Shared; src: url(./fonts/shared.woff2); }";+ let first_url = Url::parse("https://example.test/first/fonts/shared.woff2").unwrap();+ let second_url = Url::parse("https://example.test/second/fonts/shared.woff2").unwrap();+ let first = stylesheet_web_font_resource_with_resolved_url(css_text, first_url)+ .expect("first native resource");+ let second = stylesheet_web_font_resource_with_resolved_url(css_text, second_url)+ .expect("second native resource");++ assert_ne!(+ first.web_font().expect("first font").slot(),+ second.web_font().expect("second font").slot(),+ "equal relative text parsed in different stylesheet directories must not alias",+ );+ }+#[test]fn load_blocking_font_selection_ignores_image_and_unrelated_bits() {let css = r#"diff --git a/moli-renderer-v8/src/script_vm/tests/mod.rs b/moli-renderer-v8/src/script_vm/tests/mod.rsindex ae960584a..e3ba66fd4 100644--- a/moli-renderer-v8/src/script_vm/tests/mod.rs+++ b/moli-renderer-v8/src/script_vm/tests/mod.rs@@ -9481,6 +9481,121 @@ async fn spawn_gated_font_resource_server() -> ()}+async fn spawn_imported_font_graph_server() -> (+ Url,+ tokio::sync::mpsc::UnboundedReceiver<String>,+ tokio::sync::watch::Sender<bool>,+ tokio::sync::oneshot::Sender<()>,+ tokio::task::JoinHandle<()>,+) {+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0")+ .await+ .expect("bind imported-font graph server");+ let address = listener.local_addr().expect("imported-font server address");+ let base_url = Url::parse(&format!("http://{address}/")).expect("imported-font base URL");+ let (request_tx, request_rx) = tokio::sync::mpsc::unbounded_channel();+ let (font_release_tx, font_release_rx) = tokio::sync::watch::channel(false);+ let (shutdown_tx, mut shutdown_rx) = tokio::sync::oneshot::channel();+ let server = tokio::spawn(async move {+ use tokio::io::{AsyncReadExt, AsyncWriteExt};++ let mut connections = tokio::task::JoinSet::new();+ loop {+ tokio::select! {+ accepted = listener.accept() => {+ let (mut stream, _) = accepted.expect("accept imported-font request");+ let request_tx = request_tx.clone();+ let mut font_release_rx = font_release_rx.clone();+ connections.spawn(async move {+ let mut request = Vec::new();+ let mut buffer = [0_u8; 2048];+ loop {+ let read = stream+ .read(&mut buffer)+ .await+ .expect("read imported-font request");+ assert_ne!(read, 0, "imported-font request ended before headers");+ request.extend_from_slice(&buffer[..read]);+ if request.windows(4).any(|window| window == b"\r\n\r\n") {+ break;+ }+ }+ let request_head = String::from_utf8_lossy(&request);+ let target = request_head+ .lines()+ .next()+ .and_then(|line| line.split_ascii_whitespace().nth(1))+ .expect("imported-font request target")+ .to_owned();+ let _ = request_tx.send(target.clone());++ const ROOT_CSS: &[u8] = b"@import '../theme/imported.css';";+ const IMPORTED_CSS: &[u8] = br#"+ @font-face {+ font-family: ImportedAhem;+ src: url('./fonts/imported.woff2') format('woff2');+ }+ #font-probe {+ display: inline-block;+ font-family: ImportedAhem;+ font-size: 20px;+ line-height: 20px;+ white-space: pre;+ }+ "#;+ const TEST_FONT: &[u8] = include_bytes!(+ "../../../../moli-layout/tests/fixtures/moli-ahem.woff2"+ );+ let (status, content_type, body, gate_font): (+ &str,+ &str,+ &[u8],+ bool,+ ) = match target.as_str() {+ "/css/root.css" => ("200 OK", "text/css", ROOT_CSS, false),+ "/theme/imported.css" => {+ ("200 OK", "text/css", IMPORTED_CSS, false)+ }+ "/theme/fonts/imported.woff2" => {+ ("200 OK", "font/woff2", TEST_FONT, true)+ }+ "/css/fonts/imported.woff2" => {+ ("404 Not Found", "text/plain", b"wrong font base", false)+ }+ _ => ("404 Not Found", "text/plain", b"not found", false),+ };+ if gate_font {+ while !*font_release_rx.borrow() {+ if font_release_rx.changed().await.is_err() {+ return;+ }+ }+ }+ let response_head = format!(+ "HTTP/1.1 {status}\r\nContent-Type: {content_type}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",+ body.len(),+ );+ stream+ .write_all(response_head.as_bytes())+ .await+ .expect("write imported-font response head");+ stream+ .write_all(body)+ .await+ .expect("write imported-font response body");+ });+ }+ _ = &mut shutdown_rx => break,+ }+ }+ drop(request_tx);+ while let Some(result) = connections.join_next().await {+ result.expect("imported-font connection task");+ }+ });+ (base_url, request_rx, font_release_tx, shutdown_tx, server)+}+async fn spawn_gated_text_track_resource_server(status: u16,) -> (@@ -11838,6 +11953,135 @@ async fn web_font_requests_and_registration_follow_effective_stylesheet_media());}+#[tokio::test(flavor = "current_thread")]+async fn imported_web_font_keeps_its_response_base_slot_through_layout_reconciliation() {+ let (base_url, mut requests, font_release, shutdown, server) =+ spawn_imported_font_graph_server().await;+ let document_url = base_url.join("page.html").expect("document URL");+ let root_stylesheet_url = base_url.join("css/root.css").expect("root stylesheet URL");+ let html = format!(+ concat!(+ "<!doctype html><html><head>",+ "<link rel='stylesheet' href='{}'>",+ "</head><body><span id='font-probe'>MMMM</span></body></html>",+ ),+ root_stylesheet_url,+ );+ let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).expect("loader");+ loader.set_optional_resource_fetch_mask(crate::protocol_types::OptionalResourceFetchMask::FONT);+ let (mut vm, mut resource_completions) =+ new_parsed_test_vm_with_loader_and_resource_completion_queue(+ document_url.as_str(),+ &html,+ &loader,+ );++ vm.queue_initial_connected_style_loads_for_current_owner();+ vm.prime_document_lifecycle_processing_and_record_stylesheet_network_results();+ for phase in ["root stylesheet", "import graph"] {+ assert!(+ tokio::time::timeout(+ std::time::Duration::from_secs(2),+ vm.wait_for_and_apply_stylesheet_networking_body_for_test(),+ )+ .await+ .unwrap_or_else(|_| panic!("{phase} completion timed out")),+ "{phase} completion should reach the stylesheet task source",+ );+ }++ let mut observed_paths = Vec::new();+ while !observed_paths+ .iter()+ .any(|path| path == "/theme/fonts/imported.woff2")+ {+ let path = tokio::time::timeout(std::time::Duration::from_secs(2), requests.recv())+ .await+ .expect("expected imported stylesheet/font request")+ .expect("imported-font server request stream");+ observed_paths.push(path);+ }+ assert!(observed_paths.iter().any(|path| path == "/css/root.css"));+ assert!(+ observed_paths+ .iter()+ .any(|path| path == "/theme/imported.css")+ );++ assert!(+ vm.refresh_layout_snapshot_for_test(moli_layout::LayoutViewport::new(800, 600, 1.0,))+ .expect("layout reconciliation should succeed")+ );+ assert_eq!(+ vm.document_web_font_counts_for_test(),+ (1, 0, 0),+ "retained reconciliation must preserve the one pending response-base slot",+ );+ let fallback_probe_width = vm+ .eval("String(document.getElementById('font-probe').getBoundingClientRect().width)")+ .expect("fallback probe width")+ .parse::<f64>()+ .expect("numeric fallback probe width");+ if let Ok(Some(path)) =+ tokio::time::timeout(std::time::Duration::from_millis(150), requests.recv()).await+ {+ observed_paths.push(path);+ }+ while let Ok(path) = requests.try_recv() {+ observed_paths.push(path);+ }+ assert!(+ !observed_paths+ .iter()+ .any(|path| path == "/css/fonts/imported.woff2"),+ "layout reconciliation must not request the imported rule against the root CSS base: {observed_paths:?}",+ );++ font_release+ .send(true)+ .expect("release imported Ahem response");+ assert!(+ tokio::time::timeout(+ std::time::Duration::from_secs(2),+ resource_completions.wait_for_arrival_without_timeout(),+ )+ .await+ .expect("imported font completion should reach the resource source")+ );+ let completion = resource_completions+ .pop_next_async_subresource_event()+ .expect("imported font completion body");+ let _ = vm+ .complete_async_subresource_fetch_event_body(completion)+ .expect("the response-base slot should accept its font completion");+ assert_eq!(+ vm.document_web_font_counts_for_test(),+ (1, 1, 1),+ "the correct slot and registered layout font must survive reconciliation",+ );++ assert!(+ vm.refresh_layout_snapshot_for_test(moli_layout::LayoutViewport::new(800, 600, 1.0,))+ .expect("web-font layout refresh should succeed")+ );+ let probe_width = vm+ .eval("String(document.getElementById('font-probe').getBoundingClientRect().width)")+ .expect("Ahem probe width")+ .parse::<f64>()+ .expect("numeric Ahem probe width");+ assert!(+ (probe_width - 48.0).abs() <= 0.05,+ "the four-glyph probe should use the deterministic Ahem fixture metrics after registration; got {probe_width}",+ );+ assert!(+ (probe_width - fallback_probe_width).abs() > 0.5,+ "registered Ahem metrics must replace the pending fallback metrics; before={fallback_probe_width}, after={probe_width}",+ );++ let _ = shutdown.send(());+ server.await.expect("imported-font server should finish");+}+#[tokio::test]async fn pending_web_font_response_is_stale_after_stylesheet_media_stops_matching() {let (font_url, request_rx, release_tx, server) = spawn_gated_font_resource_server().await;diff --git a/moli-renderer-v8/src/style_engine/stylesheet.rs b/moli-renderer-v8/src/style_engine/stylesheet.rsindex ba4bda8cb..e379588fb 100644--- a/moli-renderer-v8/src/style_engine/stylesheet.rs+++ b/moli-renderer-v8/src/style_engine/stylesheet.rs@@ -9,7 +9,9 @@ use moli_selector::StyloSourceDependencySummary;use style::{context::QuirksMode,device::{Device, servo::FontMetricsProvider},- font_face::FontFaceRule,+ font_face::{+ FontFaceRule, FontFaceSourceFormat, FontFaceSourceFormatKeyword, Source, SourceList,+ },font_metrics::FontMetrics,properties::{ComputedValues, style_structs::Font},servo::media_features::PointerCapabilities,@@ -104,10 +106,11 @@ pub(super) fn install_active_stylesheet(let web_font_resources = native_font_face_rules_for_stylesheet(&stylesheet).into_iter().filter_map(|rule| {- let resource = crate::css_resource_urls::stylesheet_web_font_resource(- &rule.rule_fingerprint,- source.base_url(),- )?;+ let resource =+ crate::css_resource_urls::stylesheet_web_font_resource_with_resolved_url(+ &rule.rule_fingerprint,+ rule.request_url?,+ )?;Some(ActiveWebFontResource::new(rule.rule, resource))}).collect::<Vec<_>>();@@ -174,6 +177,10 @@ pub(crate) struct NativeStylesheetFontFaceRuleProjection {pub(crate) rule: ServoArc<Locked<FontFaceRule>>,pub(crate) rule_fingerprint: String,pub(crate) descriptor: moli_css_parse::CssFontFace,+ /// First supported network source, resolved by Stylo in the exact parser+ /// context that owns this rule. Imported rules therefore retain the base+ /// URL of their imported stylesheet rather than inheriting the root base.+ pub(crate) request_url: Option<url::Url>,}#[derive(Clone, Debug, Default)]@@ -283,6 +290,7 @@ fn collect_font_face_rule_projections(family: family.name.to_string(),source: serialized_source,},+ request_url: preferred_native_font_source_url(source),});}continue;@@ -291,6 +299,37 @@ fn collect_font_face_rule_projections(}}+fn preferred_native_font_source_url(source_list: &SourceList) -> Option<url::Url> {+ source_list.0.iter().find_map(|source| {+ let Source::Url(source) = source else {+ return None;+ };+ if !native_font_source_format_is_supported(source.format_hint.as_ref()) {+ return None;+ }+ let url = source.url.url()?;+ matches!(url.scheme(), "http" | "https" | "data" | "blob").then(|| (**url).clone())+ })+}++fn native_font_source_format_is_supported(format: Option<&FontFaceSourceFormat>) -> bool {+ match format {+ None => true,+ Some(FontFaceSourceFormat::Keyword(format)) => matches!(+ format,+ FontFaceSourceFormatKeyword::Collection+ | FontFaceSourceFormatKeyword::Opentype+ | FontFaceSourceFormatKeyword::Truetype+ | FontFaceSourceFormatKeyword::Woff+ | FontFaceSourceFormatKeyword::Woff2+ ),+ Some(FontFaceSourceFormat::String(format)) => matches!(+ format.to_ascii_lowercase().as_str(),+ "collection" | "opentype" | "otf" | "truetype" | "ttf" | "woff" | "woff2"+ ),+ }+}+pub(super) fn moli_user_agent_source_dependency_summary() -> StdArc<StyloSourceDependencySummary> {StdArc::clone(&MOLI_UA_SOURCE_DEPENDENCY_SUMMARY)}diff --git a/moli-renderer-v8/src/style_engine/tests/subtree_cache.rs b/moli-renderer-v8/src/style_engine/tests/subtree_cache.rsindex 25d791736..7de97e19c 100644--- a/moli-renderer-v8/src/style_engine/tests/subtree_cache.rs+++ b/moli-renderer-v8/src/style_engine/tests/subtree_cache.rs@@ -5428,6 +5428,141 @@ fn retained_stylesheet_resource_manifest_advances_only_when_resources_change() {assert_eq!(stylesheet_resource_manifest_build_count_for_test(), 4);}+#[test]+fn retained_imported_font_resources_keep_each_import_parser_base_and_response_slot() {+ use style::{context::QuirksMode, stylesheets::AllowImportRules};++ let host = test_host();+ let document = host.document_handle();+ let mut engine = MoliStyleEngine::new();+ let registry = crate::live_stylesheet::LiveStylesheetRegistry::default();+ let root = registry.create(+ concat!(+ "@import '../theme/first/imported.css';",+ "@import '../theme/second/imported.css';",+ "@import '../redirect/entry.css';",+ ),+ url::Url::parse("https://example.test/css/root.css").unwrap(),+ QuirksMode::NoQuirks,+ AllowImportRules::Yes,+ engine.author_shared_lock(),+ );+ let responses = vec![+ crate::live_stylesheet::LiveStylesheetImportResponse {+ request_url: url::Url::parse("https://example.test/theme/first/imported.css").unwrap(),+ response_url: url::Url::parse("https://example.test/theme/first/imported.css").unwrap(),+ css_text: concat!(+ "@font-face { font-family: FirstImported; ",+ "src: url('./fonts/shared.woff2') format('woff2'); }",+ )+ .to_owned(),+ successful: true,+ origin_clean: true,+ },+ crate::live_stylesheet::LiveStylesheetImportResponse {+ request_url: url::Url::parse("https://example.test/theme/second/imported.css").unwrap(),+ response_url: url::Url::parse("https://example.test/theme/second/imported.css")+ .unwrap(),+ css_text: concat!(+ "@font-face { font-family: SecondImported; ",+ "src: url('./fonts/shared.woff2') format('woff2'); }",+ )+ .to_owned(),+ successful: true,+ origin_clean: true,+ },+ crate::live_stylesheet::LiveStylesheetImportResponse {+ request_url: url::Url::parse("https://example.test/redirect/entry.css").unwrap(),+ response_url: url::Url::parse("https://cdn.example.test/final/entry.css").unwrap(),+ css_text: "@import './nested.css';".to_owned(),+ successful: true,+ origin_clean: true,+ },+ crate::live_stylesheet::LiveStylesheetImportResponse {+ request_url: url::Url::parse("https://cdn.example.test/final/nested.css").unwrap(),+ response_url: url::Url::parse("https://assets.example.test/styles/nested.css").unwrap(),+ css_text: concat!(+ "@font-face { font-family: RedirectedNested; ",+ "src: local('RedirectedNested'), ",+ "url('../fonts/nested.svg') format('svg'), ",+ "url('../fonts/nested.woff2') format('woff2'); }",+ )+ .to_owned(),+ successful: true,+ origin_clean: true,+ },+ ];+ assert_eq!(+ registry.install_import_graph(+ root.id(),+ root.contents_revision(),+ root.import_generation(),+ &responses,+ Some(root.base_url()),+ ),+ Some(true),+ "the nested redirected import graph should install completely",+ );++ let source = StyloStylesheetSource::from_live_stylesheet(&root).with_source_id(Some(+ StyleSourceId::document_adopted_style_sheet(document, 73),+ ));+ engine.set_document_adopted_style_sheet_sources(document, vec![source.clone()]);+ let inputs = FullStyleWorldSnapshot {+ document_stylesheet_sources: vec![source],+ ..Default::default()+ };+ let key = StyleWorldKey::new(&inputs, None);+ engine.ensure_retained_style_system_for_document(&host, document, key, &inputs);++ let snapshot = engine+ .stylesheet_resource_snapshot_for_document(document)+ .expect("the imported font graph should publish a resource manifest");+ let retained_by_url = snapshot+ .web_fonts()+ .iter()+ .map(|resource| {+ (+ resource.request_url().as_str().to_owned(),+ resource+ .web_font()+ .expect("font manifest entry")+ .slot()+ .to_owned(),+ )+ })+ .collect::<std::collections::BTreeMap<_, _>>();+ assert_eq!(+ retained_by_url.keys().cloned().collect::<Vec<_>>(),+ [+ "https://assets.example.test/fonts/nested.woff2".to_owned(),+ "https://example.test/theme/first/fonts/shared.woff2".to_owned(),+ "https://example.test/theme/second/fonts/shared.woff2".to_owned(),+ ],+ "every imported rule must retain its own response/parser base, including redirects",+ );+ assert_ne!(+ retained_by_url["https://example.test/theme/first/fonts/shared.woff2"],+ retained_by_url["https://example.test/theme/second/fonts/shared.woff2"],+ "the same relative src in different imported directories needs distinct slots",+ );++ for response in responses {+ for early in crate::css_resource_urls::stylesheet_load_blocking_font_resources(+ &response.css_text,+ &response.response_url,+ crate::protocol_types::OptionalResourceFetchMask::FONT,+ ) {+ let retained_slot = &retained_by_url[early.request_url().as_str()];+ assert_eq!(+ retained_slot,+ early.web_font().expect("early response font").slot(),+ "response-time registration and retained reconciliation must share a slot",+ );+ }+ }+}+#[test]fn retained_stylesheet_resource_manifest_tracks_effective_font_faces_across_media_changes() {reset_author_source_text_parse_count_for_test();