Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust
Rust ai-agentsai-toolsbrowserbrowser-automationcloud-browserheadlessheadless-browserkitesurfplaywrightpuppeteerrustservoweb-crawlerweb-crawlingweb-scraperweb-scraping
feat(webidl): derive dictionary arguments and nested members
ldm0d13197459616
diff --git a/moli-webidl-derive/src/attrs.rs b/moli-webidl-derive/src/attrs.rsindex 80ffc1e47..dd094ffd2 100644--- a/moli-webidl-derive/src/attrs.rs+++ b/moli-webidl-derive/src/attrs.rs@@ -56,6 +56,7 @@ pub(crate) struct FieldAttrs {pub(crate) name: Option<LitStr>,pub(crate) default: Option<Expr>,pub(crate) converter: Option<crate::converter::ConverterKind>,+ pub(crate) dictionary: bool,pub(crate) interface: Option<Path>,pub(crate) brand_check: Option<Path>,pub(crate) missing_message: Option<LitStr>,@@ -128,6 +129,13 @@ pub(crate) fn parse_field_attrs(field: &Field) -> Result<FieldAttrs, Error> {parsed.interface = Some(meta.value()?.parse()?);return Ok(());}+ if meta.path.is_ident("dictionary") {+ if parsed.dictionary {+ return Err(meta.error("duplicate dictionary attribute"));+ }+ parsed.dictionary = true;+ return Ok(());+ }if meta.path.is_ident("brand_check") {if parsed.brand_check.is_some() {return Err(meta.error("duplicate brand_check attribute"));@@ -160,6 +168,26 @@ pub(crate) fn parse_field_attrs(field: &Field) -> Result<FieldAttrs, Error> {));}}+ if parsed.dictionary {+ if parsed.interface.is_some() || parsed.converter.is_some() || parsed.with.is_some() {+ return Err(Error::new(+ field.span(),+ "dictionary cannot be combined with interface, converter or with",+ ));+ }+ if parsed.variadic {+ return Err(Error::new(+ field.span(),+ "dictionary cannot be combined with variadic",+ ));+ }+ if parsed.treat_null_as_empty_string {+ return Err(Error::new(+ field.span(),+ "treat_null_as_empty_string only applies to string converters",+ ));+ }+ }Ok(parsed)}diff --git a/moli-webidl-derive/src/converter.rs b/moli-webidl-derive/src/converter.rsindex 2081422dd..69d16068a 100644--- a/moli-webidl-derive/src/converter.rs+++ b/moli-webidl-derive/src/converter.rs@@ -28,6 +28,7 @@ pub(crate) enum ConverterKind {Boolean,Enum,Interface,+ Dictionary,Raw,}@@ -94,6 +95,7 @@ impl ConverterKind {Self::Boolean => quote!(::moli_webidl::Boolean),Self::Enum => quote!(::moli_webidl::EnumValue<#ty>),Self::Interface => quote!(::moli_webidl::InterfaceObject<'_>),+ Self::Dictionary => quote!(::moli_webidl::Dictionary<#ty>),Self::Raw => quote!(#ty),}}@@ -134,6 +136,7 @@ impl ConverterKind {Self::Boolean => quote!(::moli_webidl::Boolean(#expr)),Self::Enum => quote!(::moli_webidl::EnumValue(#expr)),Self::Interface => quote!(::moli_webidl::InterfaceObject(#expr)),+ Self::Dictionary => quote!(::moli_webidl::Dictionary(#expr)),Self::Raw => quote!(#expr),}}@@ -160,7 +163,8 @@ impl ConverterKind {| Self::UnrestrictedDouble| Self::Boolean| Self::Enum- | Self::Interface => quote!(#value.0),+ | Self::Interface+ | Self::Dictionary => quote!(#value.0),Self::Raw => value,}}@@ -214,6 +218,9 @@ pub(crate) fn converter_kind_for_field_type(attrs: &FieldAttrs,ty: &Type,) -> Result<ConverterKind, Error> {+ if attrs.dictionary {+ return Ok(ConverterKind::Dictionary);+ }if attrs.interface.is_some() {if !is_v8_object_type(ty) {return Err(Error::new(diff --git a/moli-webidl-derive/src/expand.rs b/moli-webidl-derive/src/expand.rsindex 68da3450b..0d03f5c90 100644--- a/moli-webidl-derive/src/expand.rs+++ b/moli-webidl-derive/src/expand.rs@@ -399,7 +399,9 @@ fn expand_args_field(::std::option::Option::Some(#unwrap_value)};}- } else if attrs.required {+ } else if attrs.required+ || ((attrs.interface.is_some() || attrs.dictionary) && attrs.default.is_none())+ {quote! {let #ident = {let value = ::moli_webidl::argument_with_options::<#converter_ty>(@@ -580,6 +582,19 @@ fn expand_dictionary_field(});}+ if attrs.dictionary && attrs.default.is_none() {+ return Ok(quote! {+ let #ident = {+ let raw = ::moli_webidl::property_result(scope, object, #name, #context)?+ .unwrap_or_else(|| v8::undefined(scope).into());+ let value = ::moli_webidl::convert_with_options::<#converter_ty>(+ scope, raw, #context, &#options,+ )?;+ #unwrap_value+ };+ });+ }+let default = attrs.default.ok_or_else(|| {Error::new(field.span(),@@ -589,12 +604,13 @@ fn expand_dictionary_field(let wrapped_default = converter.wrap_default(default);Ok(quote! {let #ident = {+ let default_value = #wrapped_default;let value = #optional_member_or_fn::<#converter_ty>(scope,object,#name,#context,- #wrapped_default,+ default_value,&#options,)?;#unwrap_value@@ -607,6 +623,49 @@ mod tests {use super::{expand_webidl_args, expand_webidl_dictionary, impl_parts_for_scope};use syn::parse_quote;+ #[test]+ fn dictionary_attributes_reject_conflicting_conversion_paths() {+ for (attrs, message) in [+ (+ quote::quote!(dictionary, converter = "raw"),+ "dictionary cannot be combined",+ ),+ (+ quote::quote!(dictionary, with = parse),+ "dictionary cannot be combined",+ ),+ (+ quote::quote!(dictionary, interface = Base),+ "dictionary cannot be combined",+ ),+ (+ quote::quote!(dictionary, variadic),+ "dictionary cannot be combined with variadic",+ ),+ (+ quote::quote!(dictionary, dictionary),+ "duplicate dictionary attribute",+ ),+ (+ quote::quote!(dictionary, treat_null_as_empty_string),+ "treat_null_as_empty_string only applies",+ ),+ ] {+ let input: syn::DeriveInput = parse_quote! {+ struct Fields {+ #[webidl(#attrs)]+ value: Option<Options>,+ }+ };+ for error in [+ expand_webidl_args(input.clone()).unwrap_err(),+ expand_webidl_dictionary(input).unwrap_err(),+ ] {+ assert!(error.to_string().starts_with(message), "{error}");+ }+ }+ }+#[test]fn interface_attributes_reject_conflicting_or_incomplete_metadata() {let cases = [diff --git a/moli-webidl-derive/src/lib.rs b/moli-webidl-derive/src/lib.rsindex fae309520..15ac96af3 100644--- a/moli-webidl-derive/src/lib.rs+++ b/moli-webidl-derive/src/lib.rs@@ -14,6 +14,10 @@ use syn::{DeriveInput, parse_macro_input};/// `#[webidl(interface = Type)]` validates a V8 object using `Type::NAME` and/// `Type::is_instance`, with an optional `brand_check = path` override. It/// composes with optional/nullable fields and variadic object arguments.+/// Non-optional interface fields without a default convert at their field+/// position; `required` additionally enables the initial arity check.+/// `#[webidl(dictionary)]` delegates to a dictionary derive. Missing/nullish+/// values parse an empty dictionary; optional fields skip missing/undefined.#[proc_macro_derive(WebIdlArgs, attributes(webidl))]pub fn derive_webidl_args(input: TokenStream) -> TokenStream {match expand::expand_webidl_args(parse_macro_input!(input as DeriveInput)) {@@ -32,6 +36,8 @@ pub fn derive_webidl_args(input: TokenStream) -> TokenStream {/// matching common WebIDL dictionary spelling./// Object members support `interface = Type` and an optional `brand_check = path`/// using the same native identity conversion as positional arguments.+/// Nested members support `dictionary`: null parses an empty dictionary while+/// `Option<T>` skips missing/undefined and `nullable` also skips null.#[proc_macro_derive(WebIdlDictionary, attributes(webidl))]pub fn derive_webidl_dictionary(input: TokenStream) -> TokenStream {match expand::expand_webidl_dictionary(parse_macro_input!(input as DeriveInput)) {diff --git a/moli-webidl/src/convert.rs b/moli-webidl/src/convert.rsindex fd3c0c249..a34f9edff 100644--- a/moli-webidl/src/convert.rs+++ b/moli-webidl/src/convert.rs@@ -1,9 +1,9 @@use crate::{- Boolean, BufferSource, ByteString, ClampedUnsignedShort, Context, DomString, DomString16,- Double, EnforceRangeLong, EnforceRangeUnsignedLong, EnforceRangeUnsignedLongLong, EnumValue,- Long, Record, Sequence, StringOptions, UnrestrictedDouble, UnsignedLong, UnsignedLongLong,- UnsignedShort, UsvString, WebIdlArguments, WebIdlConverter, WebIdlDictionary, WebIdlEnum,- WebIdlError, WebIdlErrorKind, dictionary_value, is_nullish, property_result,+ Boolean, BufferSource, ByteString, ClampedUnsignedShort, Context, Dictionary, DomString,+ DomString16, Double, EnforceRangeLong, EnforceRangeUnsignedLong, EnforceRangeUnsignedLongLong,+ EnumValue, Long, Record, Sequence, StringOptions, UnrestrictedDouble, UnsignedLong,+ UnsignedLongLong, UnsignedShort, UsvString, WebIdlArguments, WebIdlConverter, WebIdlDictionary,+ WebIdlEnum, WebIdlError, WebIdlErrorKind, dictionary_value, is_nullish, property_result,symbol_property_result, throw_error, throw_type_error,};@@ -368,6 +368,24 @@ where}}+impl<'s, T> WebIdlConverter<'s> for Dictionary<T>+where+ T: WebIdlDictionary<'s>,+{+ type Options = ();++ fn convert(+ scope: &mut v8::PinScope<'s, '_>,+ value: v8::Local<'s, v8::Value>,+ context: Context,+ _options: &Self::Options,+ ) -> Result<Self, WebIdlError> {+ let object = dictionary_value(value, context)?+ .unwrap_or_else(|| moli_v8_util::new_null_prototype_object(scope));+ T::parse_dictionary(scope, object).map(Self)+ }+}+/// Converts an iterable to a WebIDL sequence, or returns `None` when the value/// has no `@@iterator` method.///diff --git a/moli-webidl/src/lib.rs b/moli-webidl/src/lib.rsindex 1c6b88bdf..e4888ee18 100644--- a/moli-webidl/src/lib.rs+++ b/moli-webidl/src/lib.rs@@ -38,6 +38,15 @@//! null. Identity is checked at the field's position in conversion order, and//! the original object is retained. Interface conversion cannot be combined//! with `converter`, `with`, or string conversion options.+//!+//! Dictionary fields use `#[webidl(dictionary)]` with a type implementing+//! `WebIdlDictionary`. Non-optional fields without an explicit default parse+//! missing/undefined/null as an empty dictionary, executing member defaults and+//! required-member checks. `Option<T>` skips missing/undefined but parses null+//! as `Some(empty_dictionary)`; `nullable` instead maps null to `None`.+//! Explicit `default = expr` replaces missing/undefined values only, following+//! the same evaluation order as other field defaults. Null still parses an+//! empty dictionary. Empty dictionaries have no inherited JavaScript properties.extern crate self as moli_webidl;@@ -71,8 +80,8 @@ pub use moli_webidl_callback::{pub use moli_webidl_derive::{WebIdlArgs, WebIdlDictionary, WebIdlEnum};pub use traits::{ParseOutcome, WebIdlArguments, WebIdlConverter, WebIdlDictionary, WebIdlEnum};pub use types::{- Boolean, BufferSource, ByteString, ClampedUnsignedShort, DomString, DomString16, Double,- EnforceRangeLong, EnforceRangeUnsignedLong, EnforceRangeUnsignedLongLong, EnumValue,+ Boolean, BufferSource, ByteString, ClampedUnsignedShort, Dictionary, DomString, DomString16,+ Double, EnforceRangeLong, EnforceRangeUnsignedLong, EnforceRangeUnsignedLongLong, EnumValue,EventListenerOptions, InterfaceObject, InterfaceOptions, Long, Record, Sequence, Short,StringOptions, UnrestrictedDouble, UnsignedLong, UnsignedLongLong, UnsignedShort, UsvString,};diff --git a/moli-webidl/src/types.rs b/moli-webidl/src/types.rsindex e5b2a0a29..60c32c6b5 100644--- a/moli-webidl/src/types.rs+++ b/moli-webidl/src/types.rs@@ -3,6 +3,12 @@ use crate::WebIdlDictionary;#[derive(Debug, Clone, Copy, Eq, PartialEq)]pub struct EnumValue<T>(pub T);+/// A dictionary value converted using its `WebIdlDictionary` implementation.+///+/// Null and undefined are parsed as an empty dictionary, including member+/// defaults and required-member validation. No Rust `Default` is required.+pub struct Dictionary<T>(pub T);+/// A platform object validated against native WebIDL interface identity.////// Argument and dictionary derives unwrap this to `v8::Local<v8::Object>`.diff --git a/moli-webidl/tests/dictionaries.rs b/moli-webidl/tests/dictionaries.rsnew file mode 100644index 000000000..b18db4017--- /dev/null+++ b/moli-webidl/tests/dictionaries.rs@@ -0,0 +1,429 @@+use moli_webidl::{Context, WebIdlArgs, WebIdlDictionary};++#[derive(WebIdlDictionary)]+#[webidl(prefix = "ChildOptions")]+struct ChildOptions<'scope> {+ #[webidl(default = 7)]+ limit: u32,+ #[webidl(default = "")]+ label: String,+ #[webidl(converter = "raw", default = v8::String::new(scope, "scoped").unwrap().into())]+ marker: v8::Local<'scope, v8::Value>,+}++#[derive(WebIdlArgs)]+#[webidl(prefix = "Test.defaults")]+struct DefaultArgs<'scope> {+ #[webidl(default = "")]+ before: String,+ #[webidl(dictionary)]+ options: ChildOptions<'scope>,+ #[webidl(default = "")]+ after: String,+}++#[derive(WebIdlArgs, WebIdlDictionary)]+#[webidl(prefix = "Test.nested")]+struct Nested<'scope> {+ #[webidl(dictionary)]+ child: Option<ChildOptions<'scope>>,+ #[webidl(dictionary, nullable)]+ nullable: Option<ChildOptions<'scope>>,+ #[webidl(default = "")]+ after: String,+}++#[derive(WebIdlDictionary)]+#[webidl(prefix = "Test.implicit")]+struct ImplicitNested<'scope> {+ #[webidl(dictionary)]+ child: ChildOptions<'scope>,+}++#[derive(WebIdlDictionary)]+#[webidl(prefix = "RequiredOptions")]+struct RequiredOptions {+ #[webidl(required)]+ name: String,+}++#[derive(WebIdlArgs)]+#[webidl(prefix = "Test.required")]+struct RequiredArgs {+ #[webidl(default = "")]+ before: String,+ #[webidl(required, dictionary)]+ options: RequiredOptions,+}++#[derive(WebIdlDictionary)]+#[webidl(prefix = "Test.requiredNested")]+struct RequiredNested {+ #[webidl(dictionary)]+ child: Option<RequiredOptions>,+ #[webidl(default = "")]+ after: String,+}++#[derive(WebIdlArgs, WebIdlDictionary)]+#[webidl(prefix = "Test.explicit")]+struct ExplicitDefault<'scope> {+ #[webidl(dictionary, default = explicit_default(scope))]+ options: ChildOptions<'scope>,+}++fn explicit_default<'s>(scope: &mut v8::PinScope<'s, '_>) -> ChildOptions<'s> {+ ChildOptions {+ limit: 9,+ label: "explicit".into(),+ marker: v8::String::new(scope, "explicit scoped").unwrap().into(),+ }+}++fn child_array<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ child: ChildOptions<'s>,+) -> v8::Local<'s, v8::Array> {+ let values = [+ v8::Integer::new_from_unsigned(scope, child.limit).into(),+ v8::String::new(scope, &child.label).unwrap().into(),+ child.marker,+ ];+ v8::Array::new_with_elements(scope, &values)+}++fn nested_array<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ parsed: Nested<'s>,+) -> v8::Local<'s, v8::Array> {+ let child = parsed+ .child+ .map(|child| child_array(scope, child).into())+ .unwrap_or_else(|| v8::null(scope).into());+ let nullable = parsed+ .nullable+ .map(|child| child_array(scope, child).into())+ .unwrap_or_else(|| v8::null(scope).into());+ let after = v8::String::new(scope, &parsed.after).unwrap();+ v8::Array::new_with_elements(scope, &[child, nullable, after.into()])+}++fn defaults<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ args: v8::FunctionCallbackArguments<'s>,+ mut rv: v8::ReturnValue<'s>,+) {+ if let Some(parsed) = moli_webidl::parse_args::<DefaultArgs>(scope, &args) {+ let before = v8::String::new(scope, &parsed.before).unwrap();+ let options = child_array(scope, parsed.options);+ let after = v8::String::new(scope, &parsed.after).unwrap();+ rv.set(+ v8::Array::new_with_elements(scope, &[before.into(), options.into(), after.into()])+ .into(),+ );+ }+}++fn nested_args<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ args: v8::FunctionCallbackArguments<'s>,+ mut rv: v8::ReturnValue<'s>,+) {+ if let Some(parsed) = moli_webidl::parse_args::<Nested>(scope, &args) {+ rv.set(nested_array(scope, parsed).into());+ }+}++fn nested_dictionary<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ args: v8::FunctionCallbackArguments<'s>,+ mut rv: v8::ReturnValue<'s>,+) {+ match moli_webidl::parse_dictionary_object::<Nested>(scope, args.get(0).try_into().unwrap()) {+ Ok(parsed) => rv.set(nested_array(scope, parsed).into()),+ Err(error) => moli_webidl::throw_error(scope, &error),+ }+}++fn implicit_dictionary<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ args: v8::FunctionCallbackArguments<'s>,+ mut rv: v8::ReturnValue<'s>,+) {+ match moli_webidl::parse_dictionary_object::<ImplicitNested>(+ scope,+ args.get(0).try_into().unwrap(),+ ) {+ Ok(parsed) => rv.set(child_array(scope, parsed.child).into()),+ Err(error) => moli_webidl::throw_error(scope, &error),+ }+}++fn required_args<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ args: v8::FunctionCallbackArguments<'s>,+ mut rv: v8::ReturnValue<'s>,+) {+ if let Some(parsed) = moli_webidl::parse_args::<RequiredArgs>(scope, &args) {+ rv.set(+ v8::String::new(scope, &format!("{}|{}", parsed.before, parsed.options.name))+ .unwrap()+ .into(),+ );+ }+}++fn required_nested<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ args: v8::FunctionCallbackArguments<'s>,+ mut rv: v8::ReturnValue<'s>,+) {+ match moli_webidl::parse_dictionary_object::<RequiredNested>(+ scope,+ args.get(0).try_into().unwrap(),+ ) {+ Ok(parsed) => rv.set(+ v8::String::new(+ scope,+ &format!(+ "{:?}|{}",+ parsed.child.map(|child| child.name),+ parsed.after+ ),+ )+ .unwrap()+ .into(),+ ),+ Err(error) => moli_webidl::throw_error(scope, &error),+ }+}++fn explicit_args<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ args: v8::FunctionCallbackArguments<'s>,+ mut rv: v8::ReturnValue<'s>,+) {+ if let Some(parsed) = moli_webidl::parse_args::<ExplicitDefault>(scope, &args) {+ rv.set(child_array(scope, parsed.options).into());+ }+}++fn explicit_dictionary<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ args: v8::FunctionCallbackArguments<'s>,+ mut rv: v8::ReturnValue<'s>,+) {+ match moli_webidl::parse_dictionary_object::<ExplicitDefault>(+ scope,+ args.get(0).try_into().unwrap(),+ ) {+ Ok(parsed) => rv.set(child_array(scope, parsed.options).into()),+ Err(error) => moli_webidl::throw_error(scope, &error),+ }+}++fn runtime_dictionary<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ args: v8::FunctionCallbackArguments<'s>,+ mut rv: v8::ReturnValue<'s>,+) {+ match moli_webidl::convert::<moli_webidl::Dictionary<RequiredOptions>>(+ scope,+ args.get(0),+ Context::argument("Test.runtime", 1),+ ) {+ Ok(parsed) => rv.set(v8::String::new(scope, &parsed.0.name).unwrap().into()),+ Err(error) => moli_webidl::throw_error(scope, &error),+ }+}++fn run_checks(source: &str) {+ moli_v8_test_util::ensure_v8();+ let mut isolate = v8::Isolate::new(Default::default());+ let scope = std::pin::pin!(v8::HandleScope::new(&mut isolate));+ let scope = &mut scope.init();+ let callee = v8::Context::new(scope, Default::default());+ let exports = {+ let scope = &mut v8::ContextScope::new(scope, callee);+ let key = v8::String::new(scope, "TypeError").unwrap();+ let type_error = callee.global(scope).get(scope, key.into()).unwrap();+ [+ (+ "defaults",+ v8::Function::new(scope, defaults).unwrap().into(),+ ),+ (+ "nestedArgs",+ v8::Function::new(scope, nested_args).unwrap().into(),+ ),+ (+ "nested",+ v8::Function::new(scope, nested_dictionary).unwrap().into(),+ ),+ (+ "implicit",+ v8::Function::new(scope, implicit_dictionary)+ .unwrap()+ .into(),+ ),+ (+ "requiredArgs",+ v8::Function::new(scope, required_args).unwrap().into(),+ ),+ (+ "requiredNested",+ v8::Function::new(scope, required_nested).unwrap().into(),+ ),+ (+ "explicitArgs",+ v8::Function::new(scope, explicit_args).unwrap().into(),+ ),+ (+ "explicit",+ v8::Function::new(scope, explicit_dictionary)+ .unwrap()+ .into(),+ ),+ (+ "runtime",+ v8::Function::new(scope, runtime_dictionary).unwrap().into(),+ ),+ ("CalleeTypeError", type_error),+ (+ "calleePrototype",+ v8::Object::new(scope).get_prototype(scope).unwrap(),+ ),+ ]+ };+ let caller = v8::Context::new(scope, Default::default());+ let scope = &mut v8::ContextScope::new(scope, caller);+ for (name, value) in exports {+ let key = v8::String::new(scope, name).unwrap();+ assert_eq!(+ caller.global(scope).set(scope, key.into(), value),+ Some(true)+ );+ }+ let scope = std::pin::pin!(v8::TryCatch::new(scope));+ let scope = &mut scope.init();+ let source = v8::String::new(scope, source).unwrap();+ let result = v8::Script::compile(scope, source, None).unwrap().run(scope);+ if result.is_none() {+ panic!(+ "dictionary assertions failed: {}",+ scope.exception().unwrap().to_rust_string_lossy(scope)+ );+ }+ assert!(result.unwrap().is_true());+}++#[test]+fn empty_optional_nullable_and_scope_dependent_dictionary_defaults() {+ run_checks(+ r#"+ const assert = (ok, message) => { if (!ok) throw new Error(message); };+ const empty = value => JSON.stringify(value) === '[7,"","scoped"]';+ for (const args of [[], ['before'], ['before', undefined], ['before', null], ['before', {}]]) {+ assert(empty(defaults(...args)[1]), 'empty/default dictionary: ' + args);+ }+ for (const value of [{}, {child: undefined}, {child: null}, {child: {}}]) {+ assert(empty(implicit(value)), 'implicit nested dictionary');+ }+ assert(nested({})[0] === null && nested({child: undefined})[0] === null, 'optional absence');+ assert(empty(nested({child: null})[0]), 'optional null is a present empty dictionary');+ assert(nested({nullable: null})[1] === null, 'nullable null is absent');+ assert(empty(nested({nullable: {}})[1]), 'nullable object parses');+ assert(nestedArgs()[0] === null && empty(nestedArgs(null)[0]), 'positional optional');+ assert(nestedArgs(undefined, null)[1] === null, 'positional nullable');+ assert(explicitArgs()[0] === 9 && explicitArgs(undefined)[0] === 9, 'explicit argument default');+ assert(explicit({})[0] === 9 && explicit({options: undefined})[0] === 9, 'explicit member default');+ assert(empty(explicitArgs(null)) && empty(explicit({options: null})), 'null still parses member defaults');+ for (const prototype of [Object.prototype, calleePrototype]) {+ Object.defineProperty(prototype, 'limit', {configurable: true, get() { throw 'prototype getter'; }});+ }+ try {+ assert(empty(defaults('before', null)[1]) && empty(implicit({child: null})), 'null has no inherited properties');+ } finally {+ delete Object.prototype.limit;+ delete calleePrototype.limit;+ }+ true;+ "#,+ );+}++#[test]+fn required_dictionary_members_and_argument_arity_are_not_bypassed_by_nullish_values() {+ run_checks(+ r#"+ const assert = (ok, message) => { if (!ok) throw new Error(message); };+ const fails = (call, message) => {+ let error;+ try { call(); } catch (caught) { error = caught; }+ assert(error instanceof CalleeTypeError && !(error instanceof TypeError), 'callee TypeError');+ assert(error.message.includes(message), 'error context: ' + error.message);+ };+ let reads = 0;+ const poison = {toString() { reads++; throw 'poison'; }};+ fails(() => requiredArgs(poison), 'required');+ assert(reads === 0, 'arity before coercion');+ for (const value of [undefined, null, {}]) {+ fails(() => requiredArgs('before', value), 'RequiredOptions: name is required');+ fails(() => runtime(value), 'RequiredOptions: name is required');+ }+ assert(requiredNested({}) === 'None|', 'missing optional required dictionary');+ fails(() => requiredNested({child: null}), 'RequiredOptions: name is required');+ assert(requiredArgs('before', {name: 'name'}) === 'before|name', 'required success');+ assert(runtime({name: 'name'}) === 'name', 'runtime conversion');+ for (const value of [false, 3, 'text', Symbol('symbol')]) {+ fails(() => defaults('before', value), 'Test.defaults: Argument 2');+ fails(() => nested({child: value}), 'Test.nested: child');+ }+ true;+ "#,+ );+}++#[test]+fn dictionary_getters_coercions_and_exceptions_preserve_field_order() {+ run_checks(+ r#"+ const assert = (ok, message) => { if (!ok) throw new Error(message); };+ const order = [];+ const text = name => ({toString() { order.push(name); return name; }});+ const child = Object.create({+ get limit() { order.push('limit'); return {valueOf() {order.push('number'); return 4;}}; },+ get label() { order.push('label'); return text('string'); },+ get marker() { order.push('marker'); return 'identity'; }+ });+ const parsed = nested({+ get child() { order.push('child'); return child; },+ get nullable() { order.push('nullable'); return undefined; },+ get after() { order.push('after'); return text('last'); }+ });+ assert(order.join() === 'child,limit,number,label,string,marker,nullable,after,last', 'dictionary order: ' + order);+ assert(parsed[0][0] === 4 && parsed[0][2] === 'identity', 'inherited members');+ order.length = 0;+ defaults(text('before'), child, text('after'));+ assert(order.join() === 'before,limit,number,label,string,marker,after', 'argument order: ' + order);+ const sentinel = {};+ let after = 0;+ for (const child of [+ {get limit() { throw sentinel; }},+ {limit: {valueOf() { throw sentinel; }}},+ {get label() { throw sentinel; }},+ {label: {toString() { throw sentinel; }}},+ ]) {+ let error;+ try { nested({child, get after() {after++; return '';}}); } catch (caught) {error = caught;}+ assert(error === sentinel, 'preserve child exception');+ }+ let error;+ try { requiredNested({child: null, get after() {after++; return '';}}); } catch (caught) {error = caught;}+ assert(error instanceof CalleeTypeError && after === 0, 'failed child prevents later getters');+ const marker = {};+ assert(nested({child: {marker}})[0][2] === marker, 'retain raw member identity');+ true;+ "#,+ );+}diff --git a/moli-webidl/tests/interfaces.rs b/moli-webidl/tests/interfaces.rsindex bc1ae13d3..ca1c1ad8e 100644--- a/moli-webidl/tests/interfaces.rs+++ b/moli-webidl/tests/interfaces.rs@@ -32,6 +32,15 @@ struct RequiredArgs<'scope> {object: v8::Local<'scope, v8::Object>,}+#[derive(WebIdlArgs)]+#[webidl(prefix = "Test.ordered")]+struct OrderedArgs<'scope> {+ #[webidl(required)]+ before: String,+ #[webidl(interface = interfaces::Base)]+ object: v8::Local<'scope, v8::Object>,+}+#[derive(WebIdlArgs, WebIdlDictionary)]#[webidl(prefix = "Test.requiredNullable")]struct RequiredNullable<'scope> {@@ -113,6 +122,17 @@ fn required_args<'s>(}}+fn ordered_args<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ args: v8::FunctionCallbackArguments<'s>,+ mut rv: v8::ReturnValue<'s>,+) {+ if let Some(parsed) = moli_webidl::parse_args::<OrderedArgs>(scope, &args) {+ let before = v8::String::new(scope, &parsed.before).unwrap();+ rv.set(v8::Array::new_with_elements(scope, &[before.into(), parsed.object.into()]).into());+ }+}+fn required_nullable_args<'s>(scope: &mut v8::PinScope<'s, '_>,args: v8::FunctionCallbackArguments<'s>,@@ -180,6 +200,10 @@ fn run_checks(source: &str) {"requiredArgs",v8::Function::new(scope, required_args).unwrap().into(),),+ (+ "orderedArgs",+ v8::Function::new(scope, ordered_args).unwrap().into(),+ ),("requiredNullableArgs",v8::Function::new(scope, required_nullable_args)@@ -237,6 +261,33 @@ fn run_checks(source: &str) {assert!(result.unwrap().is_true());}+#[test]+fn interface_conversion_without_arity_requirement_stays_in_field_order() {+ run_checks(+ r#"+ const assert = (ok, message) => { if (!ok) throw new Error(message); };+ const sentinel = {};+ let calls = 0;+ const before = { toString() { calls++; throw sentinel; } };+ for (const tail of [[], [undefined], [null], [{}]]) {+ let error;+ try { orderedArgs(before, ...tail); } catch (caught) { error = caught; }+ assert(error === sentinel, 'before conversion must run before interface failure');+ }+ assert(calls === 4, 'one conversion per call');+ for (const tail of [[], [undefined], [null], [{}]]) {+ let error;+ try { orderedArgs('before', ...tail); } catch (caught) { error = caught; }+ assert(error instanceof CalleeTypeError, 'missing/invalid interface must fail');+ assert(error.message.includes('Argument 2') && error.message.includes('RenamedBase'),+ 'interface conversion context');+ }+ assert(orderedArgs('before', native)[1] === native, 'retain original native proxy');+ true;+ "#,+ );+}+#[test]fn interface_arguments_preserve_native_identity_conversion_order_and_callee_errors() {run_checks(