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(css): share FontFace descriptor conversion and parsing
ldm0c822f282d24c
diff --git a/moli-renderer-v8/src/context_bootstrap/css_fontface_runtime.rs b/moli-renderer-v8/src/context_bootstrap/css_fontface_runtime.rsindex cc1358b82..1e9f95a55 100644--- a/moli-renderer-v8/src/context_bootstrap/css_fontface_runtime.rs+++ b/moli-renderer-v8/src/context_bootstrap/css_fontface_runtime.rs@@ -18,6 +18,11 @@ pub(super) const FONT_FACE_VARIANT_SLOT: &str = "__moliFontFaceVariant";pub(super) const FONT_FACE_FEATURE_SETTINGS_SLOT: &str = "__moliFontFaceFeatureSettings";pub(super) const FONT_FACE_VARIATION_SETTINGS_SLOT: &str = "__moliFontFaceVariationSettings";pub(super) const FONT_FACE_DISPLAY_SLOT: &str = "__moliFontFaceDisplay";+pub(super) const FONT_FACE_UNICODE_RANGE_SLOT: &str = "__moliFontFaceUnicodeRange";+pub(super) const FONT_FACE_ASCENT_OVERRIDE_SLOT: &str = "__moliFontFaceAscentOverride";+pub(super) const FONT_FACE_DESCENT_OVERRIDE_SLOT: &str = "__moliFontFaceDescentOverride";+pub(super) const FONT_FACE_LINE_GAP_OVERRIDE_SLOT: &str = "__moliFontFaceLineGapOverride";+pub(super) const FONT_FACE_SIZE_ADJUST_SLOT: &str = "__moliFontFaceSizeAdjust";pub(super) const FONT_FACE_STATUS_SLOT: &str = "__moliFontFaceStatus";pub(super) const FONT_FACE_LOADED_SLOT: &str = "__moliFontFaceLoaded";pub(super) const FONT_FACE_SET_OWNERS_SLOT: &str = "__moliFontFaceSetOwners";diff --git a/moli-renderer-v8/src/context_bootstrap/css_fontface_runtime/font_face.rs b/moli-renderer-v8/src/context_bootstrap/css_fontface_runtime/font_face.rsindex e713601de..943a964f7 100644--- a/moli-renderer-v8/src/context_bootstrap/css_fontface_runtime/font_face.rs+++ b/moli-renderer-v8/src/context_bootstrap/css_fontface_runtime/font_face.rs@@ -6,6 +6,9 @@ use crate::{};use moli_webapi_declare::{WebApiFunctionTemplate, WebApiObject};+mod descriptors;+use descriptors::{FONT_FACE_WRITABLE_ATTRIBUTES, parse_font_face_descriptors};+#[derive(WebApiObject)]#[webapi(interface = web_api_interfaces::FontFace)]struct FontFaceObjectDeclaration<'s> {@@ -27,6 +30,16 @@ struct FontFaceObjectDeclaration<'s> {variation_settings: String,#[webapi(slot = FONT_FACE_DISPLAY_SLOT)]display: String,+ #[webapi(slot = FONT_FACE_UNICODE_RANGE_SLOT)]+ unicode_range: String,+ #[webapi(slot = FONT_FACE_ASCENT_OVERRIDE_SLOT)]+ ascent_override: String,+ #[webapi(slot = FONT_FACE_DESCENT_OVERRIDE_SLOT)]+ descent_override: String,+ #[webapi(slot = FONT_FACE_LINE_GAP_OVERRIDE_SLOT)]+ line_gap_override: String,+ #[webapi(slot = FONT_FACE_SIZE_ADJUST_SLOT)]+ size_adjust: String,#[webapi(slot = FONT_FACE_STATUS_SLOT)]status: &'static str,#[webapi(slot = FONT_FACE_LOADED_SLOT)]@@ -104,6 +117,46 @@ struct FontFacePrototypeAccessorsDeclaration {enumerable)]display: (),+ #[webapi(+ accessor_property,+ getter = font_face_writable_attribute_getter_callback,+ setter = font_face_attribute_setter_callback,+ data = callback_data_index_value(scope, 8),+ enumerable+ )]+ unicode_range: (),+ #[webapi(+ accessor_property,+ getter = font_face_writable_attribute_getter_callback,+ setter = font_face_attribute_setter_callback,+ data = callback_data_index_value(scope, 9),+ enumerable+ )]+ ascent_override: (),+ #[webapi(+ accessor_property,+ getter = font_face_writable_attribute_getter_callback,+ setter = font_face_attribute_setter_callback,+ data = callback_data_index_value(scope, 10),+ enumerable+ )]+ descent_override: (),+ #[webapi(+ accessor_property,+ getter = font_face_writable_attribute_getter_callback,+ setter = font_face_attribute_setter_callback,+ data = callback_data_index_value(scope, 11),+ enumerable+ )]+ line_gap_override: (),+ #[webapi(+ accessor_property,+ getter = font_face_writable_attribute_getter_callback,+ setter = font_face_attribute_setter_callback,+ data = callback_data_index_value(scope, 12),+ enumerable+ )]+ size_adjust: (),#[webapi(accessor_property,getter = font_face_readonly_attribute_getter_callback,@@ -155,16 +208,16 @@ fn font_face_writable_attribute_getter_callback<'s>(args: v8::FunctionCallbackArguments<'s>,mut rv: v8::ReturnValue<'s, v8::Value>,) {- let Some(slot) = callback_data_item(+ let Some(descriptor) = callback_data_item(scope,&args,- FONT_FACE_WRITABLE_ATTRIBUTE_SLOTS,+ FONT_FACE_WRITABLE_ATTRIBUTES,"FontFace writable attribute slots",) else {rv.set_undefined();return;};- let value = font_face_slot_value(scope, args.this(), slot)+ let value = font_face_slot_value(scope, args.this(), descriptor.slot).unwrap_or_else(|| v8::undefined(scope).into());rv.set(value);}@@ -193,37 +246,31 @@ fn font_face_attribute_setter_callback<'s>(args: v8::FunctionCallbackArguments<'s>,mut rv: v8::ReturnValue<'s, v8::Value>,) {- let Some(slot) = callback_data_item(+ let Some(descriptor) = callback_data_item(scope,&args,- FONT_FACE_WRITABLE_ATTRIBUTE_SLOTS,+ FONT_FACE_WRITABLE_ATTRIBUTES,"FontFace writable attribute slots",) else {rv.set_undefined();return;};- let value = args- .get(0)- .to_string(scope)- .unwrap_or_else(|| v8::String::empty(scope));- let value = if slot == FONT_FACE_VARIATION_SETTINGS_SLOT {- let raw = value.to_rust_string_lossy(scope);- let Some(value) = canonical_font_face_descriptor_value("font-variation-settings", &raw)- else {- webidl::throw_dom_exception(- scope,- "SyntaxError",- "Invalid FontFace variationSettings descriptor.",- );+ let Some(value) = args.get(0).to_string(scope) else {+ return;+ };+ let value = if descriptor.slot == FONT_FACE_FAMILY_SLOT {+ value+ } else {+ let Some(parsed) = descriptor.parse(&value.to_rust_string_lossy(scope)) else {+ webidl::throw_dom_exception(scope, "SyntaxError", "Invalid FontFace descriptor.");return;};- v8_string(scope, &value)- .unwrap_or_else(|| v8::String::empty(scope))- .into()- } else {- value.into()+ let Some(value) = v8_string(scope, &parsed) else {+ return;+ };+ value};- set_font_face_slot_value(scope, args.this(), slot, value);+ set_font_face_slot_value(scope, args.this(), descriptor.slot, value.into());rv.set_undefined();}@@ -239,37 +286,56 @@ pub(in crate::context_bootstrap) fn font_face_constructor_callback<'s>(let Some(parsed) = webidl::parse_args::<FontFaceConstructorArgs>(scope, &args) else {return;};- let descriptors = v8::Local::<v8::Object>::try_from(args.get(2)).ok();- let this = args.this();- let style = descriptor_string_property(scope, descriptors, "style", "normal");- let weight = descriptor_string_property(scope, descriptors, "weight", "normal");- let stretch = descriptor_string_property(scope, descriptors, "stretch", "normal");- let variant = descriptor_string_property(scope, descriptors, "variant", "normal");- let feature_settings =- descriptor_string_property(scope, descriptors, "featureSettings", "normal");- let Some(variation_settings) = descriptor_variation_settings_property(scope, descriptors)+ let Some((descriptors, invalid_descriptors)) = parse_font_face_descriptors(scope, args.get(2))else {return;};- let display = descriptor_string_property(scope, descriptors, "display", "auto");- let (source, status, loaded) = match parsed.source {- FontFaceConstructorSource::Css(source) => {- let loaded = resolved_promise(scope, this.into());- (source, "loaded", loaded)- }- FontFaceConstructorSource::Binary(bytes)- if moli_web_mime::sniff_font_mime_type(&bytes).is_some() =>- {- let loaded = resolved_promise(scope, this.into());- (String::new(), "loaded", loaded)- }- FontFaceConstructorSource::Binary(_) => {- let loaded = super::query::make_rejected_dom_exception_promise(- scope,- "SyntaxError",- "Invalid font data in ArrayBuffer.",- );- (String::new(), "error", Some(loaded))+ let [+ style,+ weight,+ stretch,+ variant,+ feature_settings,+ variation_settings,+ display,+ unicode_range,+ ascent_override,+ descent_override,+ line_gap_override,+ size_adjust,+ ] = descriptors;+ let this = args.this();+ let (source, status, loaded) = if invalid_descriptors {+ let source = match parsed.source {+ FontFaceConstructorSource::Css(source) => source,+ FontFaceConstructorSource::Binary(_) => String::new(),+ };+ let loaded = super::query::make_rejected_dom_exception_promise(+ scope,+ "SyntaxError",+ "Invalid FontFace descriptor.",+ );+ (source, "error", Some(loaded))+ } else {+ match parsed.source {+ FontFaceConstructorSource::Css(source) => {+ let loaded = resolved_promise(scope, this.into());+ (source, "loaded", loaded)+ }+ FontFaceConstructorSource::Binary(bytes)+ if moli_web_mime::sniff_font_mime_type(&bytes).is_some() =>+ {+ let loaded = resolved_promise(scope, this.into());+ (String::new(), "loaded", loaded)+ }+ FontFaceConstructorSource::Binary(_) => {+ let loaded = super::query::make_rejected_dom_exception_promise(+ scope,+ "SyntaxError",+ "Invalid font data in ArrayBuffer.",+ );+ (String::new(), "error", Some(loaded))+ }}};FontFaceObjectDeclaration::new(@@ -282,6 +348,11 @@ pub(in crate::context_bootstrap) fn font_face_constructor_callback<'s>(feature_settings,variation_settings,display,+ unicode_range,+ ascent_override,+ descent_override,+ line_gap_override,+ size_adjust,status,loaded,)@@ -312,17 +383,6 @@ fn font_face_constructor_source_arg<'s>(.map(|source| FontFaceConstructorSource::Css(source.into()))}-const FONT_FACE_WRITABLE_ATTRIBUTE_SLOTS: &[&str] = &[- FONT_FACE_FAMILY_SLOT,- FONT_FACE_STYLE_SLOT,- FONT_FACE_WEIGHT_SLOT,- FONT_FACE_STRETCH_SLOT,- FONT_FACE_VARIANT_SLOT,- FONT_FACE_FEATURE_SETTINGS_SLOT,- FONT_FACE_VARIATION_SETTINGS_SLOT,- FONT_FACE_DISPLAY_SLOT,-];-const FONT_FACE_READONLY_ATTRIBUTE_SLOTS: &[&str] = &[FONT_FACE_SOURCE_SLOT,FONT_FACE_STATUS_SLOT,@@ -346,51 +406,6 @@ pub(in crate::context_bootstrap) fn font_face_load_callback<'s>(}}-fn descriptor_string_property(- scope: &mut v8::PinScope<'_, '_>,- object: Option<v8::Local<'_, v8::Object>>,- key: &str,- default: &str,-) -> String {- object- .and_then(|object| v8_string(scope, key).and_then(|key| object.get(scope, key.into())))- .and_then(|value| value.to_string(scope))- .map(|value| value.to_rust_string_lossy(scope))- .unwrap_or_else(|| default.to_owned())-}--fn descriptor_variation_settings_property(- scope: &mut v8::PinScope<'_, '_>,- object: Option<v8::Local<'_, v8::Object>>,-) -> Option<String> {- let Some(value) = object- .and_then(|object| {- v8_string(scope, "variationSettings").and_then(|key| object.get(scope, key.into()))- })- .filter(|value| !value.is_undefined())- else {- return Some("normal".to_owned());- };- let value = value- .to_string(scope)- .map(|value| value.to_rust_string_lossy(scope))?;- let Some(value) = canonical_font_face_descriptor_value("font-variation-settings", &value)- else {- webidl::throw_dom_exception(- scope,- "SyntaxError",- "Invalid FontFace variationSettings descriptor.",- );- return None;- };- Some(value)-}--fn canonical_font_face_descriptor_value(name: &str, value: &str) -> Option<String> {- moli_css_parse::parse_font_face_descriptor_entry_with_stylo(name, value)- .map(|entry| entry.value)-}-fn font_face_slot_value<'s>(scope: &mut v8::PinScope<'s, '_>,object: v8::Local<'s, v8::Object>,diff --git a/moli-renderer-v8/src/context_bootstrap/css_fontface_runtime/font_face/descriptors.rs b/moli-renderer-v8/src/context_bootstrap/css_fontface_runtime/font_face/descriptors.rsnew file mode 100644index 000000000..f8c41fb13--- /dev/null+++ b/moli-renderer-v8/src/context_bootstrap/css_fontface_runtime/font_face/descriptors.rs@@ -0,0 +1,130 @@+use super::*;++#[derive(Clone, Copy)]+pub(super) struct FontFaceDescriptor {+ pub(super) slot: &'static str,+ css_name: &'static str,+ initial: &'static str,+}++impl FontFaceDescriptor {+ const fn new(slot: &'static str, css_name: &'static str, initial: &'static str) -> Self {+ Self {+ slot,+ css_name,+ initial,+ }+ }++ pub(super) fn parse(self, value: &str) -> Option<String> {+ if self.slot == FONT_FACE_FAMILY_SLOT {+ return Some(value.to_owned());+ }+ if self.slot == FONT_FACE_VARIANT_SLOT {+ // The legacy FontFace variant attribute uses the CSS 2.1 values;+ // Stylo no longer exposes font-variant as an @font-face descriptor.+ let mut input = cssparser::ParserInput::new(value);+ let mut parser = cssparser::Parser::new(&mut input);+ let ident = parser.expect_ident().ok()?.to_ascii_lowercase();+ parser.expect_exhausted().ok()?;+ return matches!(ident.as_str(), "normal" | "small-caps").then_some(ident);+ }+ moli_css_parse::parse_font_face_descriptor_entry_with_stylo(self.css_name, value)+ .map(|entry| entry.value)+ }+}++// Keep the order aligned with the accessor callback-data indexes.+pub(super) const FONT_FACE_WRITABLE_ATTRIBUTES: &[FontFaceDescriptor] = &[+ FontFaceDescriptor::new(FONT_FACE_FAMILY_SLOT, "font-family", ""),+ FontFaceDescriptor::new(FONT_FACE_STYLE_SLOT, "font-style", "normal"),+ FontFaceDescriptor::new(FONT_FACE_WEIGHT_SLOT, "font-weight", "normal"),+ FontFaceDescriptor::new(FONT_FACE_STRETCH_SLOT, "font-stretch", "normal"),+ FontFaceDescriptor::new(FONT_FACE_VARIANT_SLOT, "font-variant", "normal"),+ FontFaceDescriptor::new(+ FONT_FACE_FEATURE_SETTINGS_SLOT,+ "font-feature-settings",+ "normal",+ ),+ FontFaceDescriptor::new(+ FONT_FACE_VARIATION_SETTINGS_SLOT,+ "font-variation-settings",+ "normal",+ ),+ FontFaceDescriptor::new(FONT_FACE_DISPLAY_SLOT, "font-display", "auto"),+ FontFaceDescriptor::new(FONT_FACE_UNICODE_RANGE_SLOT, "unicode-range", "U+0-10FFFF"),+ FontFaceDescriptor::new(FONT_FACE_ASCENT_OVERRIDE_SLOT, "ascent-override", "normal"),+ FontFaceDescriptor::new(+ FONT_FACE_DESCENT_OVERRIDE_SLOT,+ "descent-override",+ "normal",+ ),+ FontFaceDescriptor::new(+ FONT_FACE_LINE_GAP_OVERRIDE_SLOT,+ "line-gap-override",+ "normal",+ ),+ FontFaceDescriptor::new(FONT_FACE_SIZE_ADJUST_SLOT, "size-adjust", "100%"),+];++// WebIDL reads dictionary members in lexicographic order, and must finish+// their conversion before the constructor starts parsing CSS.+#[derive(Default, webidl::WebIdlDictionary)]+#[webidl(prefix = "FontFaceDescriptors")]+struct FontFaceDescriptors {+ ascent_override: Option<String>,+ descent_override: Option<String>,+ display: Option<String>,+ feature_settings: Option<String>,+ line_gap_override: Option<String>,+ size_adjust: Option<String>,+ stretch: Option<String>,+ style: Option<String>,+ unicode_range: Option<String>,+ variant: Option<String>,+ variation_settings: Option<String>,+ weight: Option<String>,+}++pub(super) fn parse_font_face_descriptors<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ value: v8::Local<'s, v8::Value>,+) -> Option<([String; 12], bool)> {+ let parsed = match webidl::parse_dictionary::<FontFaceDescriptors>(+ scope,+ value,+ webidl::Context::argument("FontFace", 3),+ ) {+ Ok(parsed) => parsed.unwrap_or_default(),+ Err(error) => {+ webidl::throw_error(scope, &error);+ return None;+ }+ };+ let raw = [+ parsed.style,+ parsed.weight,+ parsed.stretch,+ parsed.variant,+ parsed.feature_settings,+ parsed.variation_settings,+ parsed.display,+ parsed.unicode_range,+ parsed.ascent_override,+ parsed.descent_override,+ parsed.line_gap_override,+ parsed.size_adjust,+ ];+ let mut invalid = false;+ let values = std::array::from_fn(|index| {+ let descriptor = FONT_FACE_WRITABLE_ATTRIBUTES[index + 1];+ let Some(raw) = raw[index].as_deref() else {+ return descriptor.initial.to_owned();+ };+ descriptor.parse(raw).unwrap_or_else(|| {+ invalid = true;+ String::new()+ })+ });+ Some((values, invalid))+}diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/fontface_descriptors.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/fontface_descriptors.rsnew file mode 100644index 000000000..a41069632--- /dev/null+++ b/moli-renderer-v8/src/script_vm/tests/browser_api/fontface_descriptors.rs@@ -0,0 +1,43 @@+use super::*;++#[test]+fn font_face_descriptors_parse_css_and_convert_dictionaries_in_main_and_child_realms() {+ let mut vm = new_storage_test_vm("https://font-face-descriptors.test/");+ vm.eval(+ &format!(+ r#"(async () => {{+ {}+ const frame = (document.body || document.documentElement || document)+ .appendChild(document.createElement('iframe'));+ const child = frame.contentWindow;+ const mainFace = new FontFace('Main', 'url(unused.ttf)');+ const childFace = new child.FontFace('Child', 'url(unused.ttf)');+ const mainSetter = Object.getOwnPropertyDescriptor(FontFace.prototype, 'ascentOverride').set;+ const childSetter = Object.getOwnPropertyDescriptor(child.FontFace.prototype, 'ascentOverride').set;+ childSetter.call(mainFace, '20%');+ mainSetter.call(childFace, '30%');+ let borrowedError = false;+ try {{ childSetter.call(mainFace, 'invalid'); }}+ catch (error) {{+ borrowedError = error instanceof child.DOMException &&+ !(error instanceof DOMException) && error.name === 'SyntaxError';+ }}+ return JSON.stringify({{+ main: await fontFaceDescriptorsProbe(window),+ child: await fontFaceDescriptorsProbe(child),+ borrowedValues: [mainFace.ascentOverride, childFace.ascentOverride],+ borrowedError,+ }});+ }})().then(result => {{ globalThis.descriptorResult = result; }})"#,+ include_str!("../../../../tests/fixtures/fontface-descriptors.js"),+ ),+ ).expect("descriptor probe should evaluate");+ let result = vm.eval("descriptorResult").unwrap();+ let result: serde_json::Value = serde_json::from_str(&result).unwrap();+ for realm in ["main", "child"] {+ assert_eq!(result[realm]["failures"], serde_json::json!([]), "{result}");+ assert_eq!(result[realm]["checks"], 420, "{result}");+ }+ assert_eq!(result["borrowedValues"], serde_json::json!(["20%", "30%"]));+ assert_eq!(result["borrowedError"], true, "{result}");+}diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/misc.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/misc.rsindex ae3efe3b1..050c51af1 100644--- a/moli-renderer-v8/src/script_vm/tests/browser_api/misc.rs+++ b/moli-renderer-v8/src/script_vm/tests/browser_api/misc.rs@@ -1733,21 +1733,18 @@ fn font_face_variation_settings_use_stylo_descriptor_serialization() {} catch (error) {setterError = error.name;}- let constructorError = '';- try {- new FontFace('Invalid', 'url(invalid.woff2)', {- variationSettings: 'not-a-valid-setting'- });- } catch (error) {- constructorError = error.name;- }+ const invalid = new FontFace('Invalid', 'url(invalid.woff2)', {+ variationSettings: 'not-a-valid-setting'+ });+ invalid.loaded.catch(() => {});const descriptor = Object.getOwnPropertyDescriptor(FontFace.prototype,'variationSettings');return JSON.stringify({values: [initial, updated, face.variationSettings],- errors: [setterError, constructorError],+ setterError,+ constructorStatus: invalid.status,descriptor: [typeof descriptor.get,descriptor.get.length,@@ -1765,7 +1762,7 @@ fn font_face_variation_settings_use_stylo_descriptor_serialization() {assert_eq!(result,- r#"{"values":["\"wght\" 850","\"wdth\" 120.5","\"wdth\" 120.5"],"errors":["SyntaxError","SyntaxError"],"descriptor":["function",0,"function",1,true,true,false]}"#+ r#"{"values":["\"wght\" 850","\"wdth\" 120.5","\"wdth\" 120.5"],"setterError":"SyntaxError","constructorStatus":"error","descriptor":["function",0,"function",1,true,true,false]}"#);}diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/mod.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/mod.rsindex 4f5bb534d..6fc4fcbf6 100644--- a/moli-renderer-v8/src/script_vm/tests/browser_api/mod.rs+++ b/moli-renderer-v8/src/script_vm/tests/browser_api/mod.rs@@ -19,6 +19,7 @@ mod details;mod event_handlers;mod event_listener_options;mod events_selection_storage;+mod fontface_descriptors;mod gamepad;mod ice_candidate;mod idle_callbacks;diff --git a/moli-renderer-v8/tests/fixtures/fontface-descriptors.js b/moli-renderer-v8/tests/fixtures/fontface-descriptors.jsnew file mode 100644index 000000000..55b913d23--- /dev/null+++ b/moli-renderer-v8/tests/fixtures/fontface-descriptors.js@@ -0,0 +1,115 @@+async function fontFaceDescriptorsProbe(realm = globalThis) {+ const failures = [];+ let checks = 0;+ const check = (value, label) => { ++checks; if (!value) failures.push(label); };+ const throws = (callback, expected, label, name) => {+ try { callback(); check(false, label + ': accepted'); }+ catch (error) {+ check((error === expected || (typeof expected === 'function' && error instanceof expected)) &&+ (name === undefined || error.name === name), label + ': error');+ }+ };+ const defaults = {+ ascentOverride: 'normal', descentOverride: 'normal', display: 'auto',+ featureSettings: 'normal', lineGapOverride: 'normal', sizeAdjust: '100%',+ stretch: 'normal', style: 'normal', unicodeRange: 'U+0-10FFFF',+ variant: 'normal', variationSettings: 'normal', weight: 'normal',+ };+ const names = Object.keys(defaults);+ const make = options => new realm.FontFace('Descriptors', 'url(unused.ttf)', options);+ const initialStatus = make().status;+ for (const options of [undefined, null, {}, Object.fromEntries(names.map(n => [n, undefined]))]) {+ const face = make(options);+ for (const name of names) check(face[name] === defaults[name], 'default ' + name);+ check(face.status === initialStatus, 'default status');+ }+ const marker = new realm.Error('conversion marker');+ for (const name of names) {+ const descriptor = Object.getOwnPropertyDescriptor(realm.FontFace.prototype, name);+ check(descriptor && descriptor.enumerable && descriptor.configurable &&+ descriptor.get.length === 0 && descriptor.set.length === 1, 'descriptor ' + name);+ if (!descriptor) continue;+ const face = make();+ const revoked = Proxy.revocable(face, {}); revoked.revoke();+ let conversions = 0, traps = 0;+ const value = {toString() { ++conversions; return defaults[name]; }};+ for (const receiver of [{}, Object.create(face), new Proxy(face, {get() { ++traps; }}), revoked.proxy]) {+ throws(() => descriptor.get.call(receiver), realm.TypeError, name + ' get receiver');+ throws(() => descriptor.set.call(receiver, value), realm.TypeError, name + ' set receiver');+ }+ check(conversions === 0 && traps === 0, name + ' receiver before conversion');+ throws(() => { face[name] = Symbol(); }, realm.TypeError, name + ' Symbol');+ check(face[name] === defaults[name], name + ' Symbol retains value');+ throws(() => { face[name] = {toString() { throw marker; }}; }, marker, name + ' conversion');+ check(face[name] === defaults[name], name + ' conversion retains value');+ throws(() => { face[name] = 'invalid'; }, realm.DOMException, name + ' invalid CSS', 'SyntaxError');+ check(face[name] === defaults[name] && face.status === initialStatus, name + ' invalid CSS retains state');+ let bad;+ try { bad = make({[name]: 'invalid'}); }+ catch (_) { check(false, name + ' constructor threw for CSS syntax'); continue; }+ check(bad.status === 'error', name + ' constructor error status');+ const loaded = bad.loaded;+ check(loaded === bad.loaded && bad.load() === loaded, name + ' stable rejection');+ const error = await loaded.catch(error => error);+ check(error instanceof realm.DOMException && error.name === 'SyntaxError', name + ' constructor rejection');+ // CSS Font Loading clears the descriptor that failed to parse.+ check(bad[name] === '', name + ' invalid constructor descriptor');+ }+ const valid = [+ ['style', 'ITALIC', 'italic'], ['style', 'oblique 20deg 30deg', 'oblique 20deg 30deg'],+ ['weight', '0700', '700'], ['weight', '100 900', '100 900'], ['weight', 'calc(500 + 200)', 'calc(700)'],+ ['stretch', 'condensed', 'condensed'], ['stretch', '75% 125%', '75% 125%'],+ ['variant', 'SMALL-CAPS', 'small-caps'],+ ['featureSettings', "'liga' off", '"liga" 0'], ['featureSettings', "'kern' on", '"kern"'],+ ['variationSettings', "'wght' 850", '"wght" 850'], ['display', 'SWAP', 'swap'],+ ['unicodeRange', 'u+0020-007f', 'U+20-7F'], ['unicodeRange', 'U+??', 'U+0-FF'],+ ['unicodeRange', 'U+10FFFF', 'U+10FFFF'], ['unicodeRange', 'U+41, U+42', 'U+41, U+42'],+ ['ascentOverride', '50.000%', '50%'], ['ascentOverride', 'calc(20% + 5%)', 'calc(25%)'],+ ['descentOverride', '200%', '200%'], ['lineGapOverride', '0%', '0%'],+ ['sizeAdjust', '100%', '100%'], ['sizeAdjust', 'calc(100% + 20%)', 'calc(120%)'],+ ];+ for (const [name, input, expected] of valid) {+ const face = make({[name]: input});+ check(face.status === initialStatus && face[name] === expected, name + ' constructor serialization: ' + input);+ face[name] = input;+ check(face[name] === expected, name + ' setter serialization: ' + input);+ }+ for (const [name, values] of Object.entries({+ unicodeRange: ['U+110000', 'U+41-40', 'U+1-FFFFFF', 'U+41 trailing'],+ weight: ['0', '1001', 'bolder', '400 !important'],+ ascentOverride: ['-1%', '0', '10px'], descentOverride: ['-5%'],+ lineGapOverride: ['1em'], sizeAdjust: ['-1%', 'normal'],+ style: ['italic; font-weight: 700', 'var(--style)', 'inherit'],+ variant: ['all-small-caps', 'common-ligatures small-caps'],+ })) for (const input of values) {+ const face = make();+ throws(() => { face[name] = input; }, realm.DOMException, name + ' grammar: ' + input, 'SyntaxError');+ check(face[name] === defaults[name], name + ' failed write: ' + input);+ }+ const order = [];+ const dictionary = new Proxy({}, {get(_, key) { order.push(key); return undefined; }});+ new realm.FontFace({toString() {order.push('family'); return 'A';}},+ {toString() {order.push('source'); return 'url(unused.ttf)';}}, dictionary);+ check(order.join() === ['family', 'source', ...names].join(), 'dictionary member order: ' + order);+ for (const [index, name] of names.entries()) {+ const reads = [];+ const dictionary = new Proxy({}, {get(_, key) {+ reads.push(key);+ if (key === name) throw marker;+ return undefined;+ }});+ throws(() => make(dictionary), marker, name + ' dictionary exception');+ check(reads.join() === names.slice(0, index + 1).join(), name + ' stops dictionary reads');+ throws(() => make({[name]: Symbol()}), realm.TypeError, name + ' dictionary Symbol');+ }+ for (const dictionary of [true, 42, '', 'text', Symbol()]) {+ throws(() => make(dictionary), realm.TypeError, 'dictionary type');+ }+ throws(() => make({ascentOverride: 'invalid', get weight() {throw marker;}}), marker,+ 'convert entire dictionary before parsing CSS');+ class Derived extends realm.FontFace {}+ const derived = new Derived('Derived', 'url(unused.ttf)', {ascentOverride: '25%'});+ derived.unicodeRange = 'U+41';+ check(derived.ascentOverride === '25%' && derived.unicodeRange === 'U+41', 'subclass slots');+ return {checks, failures};+}diff --git a/moli-wpt-compat/fixtures/wpt/ported/css-font-loading/fontface-basic.html b/moli-wpt-compat/fixtures/wpt/ported/css-font-loading/fontface-basic.htmlindex 03f0fa39f..9f9b73211 100644--- a/moli-wpt-compat/fixtures/wpt/ported/css-font-loading/fontface-basic.html+++ b/moli-wpt-compat/fixtures/wpt/ported/css-font-loading/fontface-basic.html@@ -32,7 +32,7 @@ test(function () {assert_equals(face.weight, "700");assert_equals(face.stretch, "condensed");assert_equals(face.variant, "small-caps");- assert_equals(face.featureSettings, '"liga" off');+ assert_equals(face.featureSettings, '"liga" 0');assert_equals(face.display, "swap");assert_equals(face.status, "loaded");assert_true(face.loaded instanceof Promise);