From e2f1832e9b472a3493bf53ff0141824e056c19cb Mon Sep 17 00:00:00 2001 From: Florian Rappl Date: Thu, 19 Nov 2026 12:28:21 +0100 Subject: [PATCH] Fixes for improving Acid3 --- CHANGELOG.md | 9 ++ src/AngleSharp.Js.Docs/package.json | 2 +- src/AngleSharp.Js.Tests/Acid3Tests.cs | 62 ++++++++++++ src/AngleSharp.Js/Cache/ConstantCache.cs | 98 +++++++++++++++++++ src/AngleSharp.Js/Cache/DomShapeCache.cs | 9 ++ src/AngleSharp.Js/EngineInstance.cs | 4 +- .../Extensions/JsValueExtensions.cs | 7 +- src/AngleSharp.Js/JsScriptingService.cs | 8 ++ .../Proxies/DomConstructorInstance.cs | 13 +++ src/AngleSharp.Js/Proxies/DomNodeInstance.cs | 13 ++- src/Directory.Build.props | 2 +- 11 files changed, 219 insertions(+), 8 deletions(-) create mode 100644 src/AngleSharp.Js.Tests/Acid3Tests.cs create mode 100644 src/AngleSharp.Js/Cache/ConstantCache.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index af0f8de..ca1ebf9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,12 @@ +# 1.2.3 + +Released on tbd. + +- Fixed `undefined` for an argument of an enumeration (e.g. the `how` of `compareBoundaryPoints`) throwing an error scripts could not catch +- Fixed event handler attributes of forms and selects (e.g. `form.onsubmit`) not being set +- Fixed a frame not finding the functions and variables of a script of another window, e.g. `parent.notify()` +- Added the constants of the interfaces, e.g. `Node.ELEMENT_NODE`, `Range.START_TO_END` or `NodeFilter.SHOW_ELEMENT` + # 1.2.2 Released on Sunday, November 15 2026. diff --git a/src/AngleSharp.Js.Docs/package.json b/src/AngleSharp.Js.Docs/package.json index 5d49256..23c6a67 100644 --- a/src/AngleSharp.Js.Docs/package.json +++ b/src/AngleSharp.Js.Docs/package.json @@ -1,6 +1,6 @@ { "name": "@anglesharp/js", - "version": "1.2.2", + "version": "1.2.3", "preview": true, "description": "The doclet for the AngleSharp.Js documentation.", "keywords": [ diff --git a/src/AngleSharp.Js.Tests/Acid3Tests.cs b/src/AngleSharp.Js.Tests/Acid3Tests.cs new file mode 100644 index 0000000..70919cd --- /dev/null +++ b/src/AngleSharp.Js.Tests/Acid3Tests.cs @@ -0,0 +1,62 @@ +namespace AngleSharp.Js.Tests +{ + using AngleSharp.Dom; + using AngleSharp.Html.Dom; + using NUnit.Framework; + using System.Threading.Tasks; + + /// + /// Behavior the Acid3 test (acid3.acidtests.org) relies on. + /// + [TestFixture] + public class Acid3Tests + { + [Test] + public async Task ConstantsAreOnTheInterfacesAndTheirInstances() + { + var result = await "[Node.ELEMENT_NODE, document.DOCUMENT_FRAGMENT_NODE, document.documentElement.TEXT_NODE, Range.START_TO_END, document.createRange().END_TO_START, Event.CAPTURING_PHASE, NodeFilter.SHOW_ELEMENT].join()".EvalScriptAsync(); + Assert.AreEqual("1,11,3,1,3,1,1", result); + } + + [Test] + public async Task ConstantsCannotBeChanged() + { + var result = await "(function () { Node.ELEMENT_NODE = 5; document.ELEMENT_NODE = 6; return [Node.ELEMENT_NODE, document.ELEMENT_NODE].join(); })()".EvalScriptAsync(); + Assert.AreEqual("1,1", result); + } + + [Test] + public async Task UndefinedForAnEnumerationArgumentIsZero() + { + var result = await "(function () { var r = document.createRange(); return r.compareBoundaryPoints(r.NO_SUCH_CONSTANT, r.cloneRange()); })()".EvalScriptAsync(); + Assert.AreEqual("0", result); + } + + [Test] + public async Task EventHandlerOfAFormIsNotANamedProperty() + { + var result = await "(function () { var f = document.createElement('form'); var n = 0; f.onsubmit = function () { n++; }; f.appendChild(document.createElement('input')); document.documentElement.appendChild(f); f.dispatchEvent(new Event('submit')); return [n, typeof f.onsubmit, f.length, f[0].tagName].join(); })()".EvalScriptAsync(); + Assert.AreEqual("1,function,1,INPUT", result); + } + + [Test] + public async Task FrameCallsAFunctionOfItsParent() + { + var config = Configuration.Default.WithJs().WithEventLoop(); + var document = await BrowsingContext.New(config).OpenAsync(m => m.Content(@"")); + await document.WhenStable(); + var frame = (IHtmlInlineFrameElement)document.QuerySelector("iframe"); + await frame.ContentDocument.WhenStable(); + + Assert.AreEqual("function from frame", document.Title); + } + } +} diff --git a/src/AngleSharp.Js/Cache/ConstantCache.cs b/src/AngleSharp.Js/Cache/ConstantCache.cs new file mode 100644 index 0000000..1532e45 --- /dev/null +++ b/src/AngleSharp.Js/Cache/ConstantCache.cs @@ -0,0 +1,98 @@ +namespace AngleSharp.Js.Cache +{ + using AngleSharp.Attributes; + using System; + using System.Collections.Concurrent; + using System.Collections.Generic; + using System.Linq; + using System.Reflection; + + /// + /// The WebIDL constants of the interfaces (e.g. Node.ELEMENT_NODE), which the libraries + /// declare as the fields of an enum named like the interface owning them. + /// + static class ConstantCache + { + private static readonly ConcurrentDictionary[]>> _constants = new(); + + // Enums whose name doesn't say the interface owning their constants (AngleSharp 1.10 names + // the document for those of a node, which all nodes have). + private static readonly Dictionary _owners = new(StringComparer.Ordinal) + { + { "AngleSharp.Dom.NodeType", "Node" }, + { "AngleSharp.Dom.DocumentPositions", "Node" }, + { "AngleSharp.Dom.DomError", "DOMException" }, + }; + + public static IEnumerable> GetConstants(this IEnumerable libs, String name) + { + if (name is null) + { + return []; + } + + return libs + .Select(m => _constants.GetOrAdd(m, Collect)) + .SelectMany(m => m.TryGetValue(name, out var constants) ? constants : []); + } + + private static IReadOnlyDictionary[]> Collect(Assembly assembly) + { + var result = new Dictionary>>(StringComparer.Ordinal); + + foreach (var type in GetTypes(assembly)) + { + var info = type.GetTypeInfo(); + + if (!info.IsEnum || info.GetCustomAttribute() != null) + { + continue; + } + + var owner = _owners.TryGetValue(type.FullName ?? String.Empty, out var known) ? known : + info.GetCustomAttributes().FirstOrDefault()?.OfficialName; + + if (owner is null) + { + continue; + } + + foreach (var field in info.DeclaredFields.Where(m => m.IsLiteral)) + { + var constant = field.GetCustomAttributes().FirstOrDefault()?.OfficialName; + + if (constant is not null && IsConstantName(constant)) + { + if (!result.TryGetValue(owner, out var list)) + { + result[owner] = list = []; + } + + if (!list.Any(m => m.Key == constant)) + { + list.Add(new KeyValuePair(constant, Convert.ToDouble(field.GetRawConstantValue()))); + } + } + } + } + + return result.ToDictionary(m => m.Key, m => m.Value.ToArray(), StringComparer.Ordinal); + } + + // constants are all upper case (the members of a string enumeration are not) + private static Boolean IsConstantName(String name) => + name.Length > 0 && Char.IsUpper(name[0]) && name.All(c => Char.IsUpper(c) || Char.IsDigit(c) || c == '_'); + + private static IEnumerable GetTypes(Assembly assembly) + { + try + { + return assembly.ExportedTypes; + } + catch (Exception) + { + return []; + } + } + } +} diff --git a/src/AngleSharp.Js/Cache/DomShapeCache.cs b/src/AngleSharp.Js/Cache/DomShapeCache.cs index 27d9604..9371e99 100644 --- a/src/AngleSharp.Js/Cache/DomShapeCache.cs +++ b/src/AngleSharp.Js/Cache/DomShapeCache.cs @@ -182,6 +182,15 @@ public DomShape Build(Engine engine) } } + // The constants are on the prototype as well, so that a node knows them (node.ELEMENT_NODE). + foreach (var constant in _libs.Assemblies.GetConstants(_name)) + { + if (!_members.ContainsKey(constant.Key) && !String.Equals(constant.Key, ConstructorName, StringComparison.Ordinal)) + { + builder.Constant(constant.Key, JsNumber.Create(constant.Value), true); + } + } + if (constructor != null) { // The attributes an eagerly written constructor had, and still resolved on first diff --git a/src/AngleSharp.Js/EngineInstance.cs b/src/AngleSharp.Js/EngineInstance.cs index fd42850..ed86734 100644 --- a/src/AngleSharp.Js/EngineInstance.cs +++ b/src/AngleSharp.Js/EngineInstance.cs @@ -859,7 +859,9 @@ private ObjectInstance CreateInstance(Object obj) private ObjectInstance CreateInstance(Object obj, Type type) { - var collection = type.GetIndexedCollection(); + // A node indexed like a collection (a form, a select) is a node still: only the node's + // proxy holds its event handler attributes (form.onsubmit), and it asks the indexers too. + var collection = obj is INode ? null : type.GetIndexedCollection(); if (collection != null) { diff --git a/src/AngleSharp.Js/Extensions/JsValueExtensions.cs b/src/AngleSharp.Js/Extensions/JsValueExtensions.cs index 870d029..34054cf 100644 --- a/src/AngleSharp.Js/Extensions/JsValueExtensions.cs +++ b/src/AngleSharp.Js/Extensions/JsValueExtensions.cs @@ -373,8 +373,13 @@ public static Object As(this JsValue value, Type targetType, EngineInstance engi } } + // a WebIDL integer (e.g. the "how" of compareBoundaryPoints): undefined or NaN is 0 var underlyingType = Enum.GetUnderlyingType(targetType); - var raw = Convert.ChangeType(TypeConverter.ToNumber(value), underlyingType); + var integer = TypeConverter.ToNumber(value); + var raw = underlyingType == typeof(Int32) ? TypeConverter.ToInt32(value) : + underlyingType == typeof(UInt32) ? TypeConverter.ToUint32(value) : + underlyingType == typeof(UInt16) ? TypeConverter.ToUint16(value) : + Convert.ChangeType(ToNumeric(integer, Type.GetTypeCode(underlyingType)), underlyingType); return Enum.ToObject(targetType, raw); } else if (Nullable.GetUnderlyingType(targetType) is Type nullableType) diff --git a/src/AngleSharp.Js/JsScriptingService.cs b/src/AngleSharp.Js/JsScriptingService.cs index aa486f0..90dac27 100644 --- a/src/AngleSharp.Js/JsScriptingService.cs +++ b/src/AngleSharp.Js/JsScriptingService.cs @@ -213,6 +213,14 @@ public Object EvaluateScript(IDocument document, String source, String type, Str #region Helpers + /// + /// Gets the engine of the given window, if its document ran scripts already. + /// + internal static EngineInstance TryGetInstance(IWindow window) => + window?.Document?.Context?.GetService() is { } service && service._contexts.TryGetValue(window, out var instance) + ? instance + : null; + internal EngineInstance GetOrCreateInstance(IDocument document) { var objectContext = document.DefaultView; diff --git a/src/AngleSharp.Js/Proxies/DomConstructorInstance.cs b/src/AngleSharp.Js/Proxies/DomConstructorInstance.cs index 84152aa..3b5201b 100644 --- a/src/AngleSharp.Js/Proxies/DomConstructorInstance.cs +++ b/src/AngleSharp.Js/Proxies/DomConstructorInstance.cs @@ -10,6 +10,7 @@ namespace AngleSharp.Js using Jint.Runtime.Descriptors; using Jint.Runtime.Interop; using System; + using System.Collections.Generic; using System.Reflection; sealed class DomConstructorInstance : Constructor @@ -40,6 +41,18 @@ public DomConstructorInstance(EngineInstance engine, ConstructorDefinition defin SetOwnProperty("prototype", new PropertyDescriptor(_objectPrototype, false, false, false)); AddStaticMembers(definition.Type.GetStaticMembers()); + AddConstants(engine.Libs.GetConstants(definition.Name)); + } + + private void AddConstants(IEnumerable> constants) + { + foreach (var constant in constants) + { + if (GetOwnProperty(constant.Key) == PropertyDescriptor.Undefined) + { + SetOwnProperty(constant.Key, new PropertyDescriptor(JsNumber.Create(constant.Value), false, true, false)); + } + } } private void AddStaticMembers(StaticMember[] members) diff --git a/src/AngleSharp.Js/Proxies/DomNodeInstance.cs b/src/AngleSharp.Js/Proxies/DomNodeInstance.cs index f5da692..54ccad9 100644 --- a/src/AngleSharp.Js/Proxies/DomNodeInstance.cs +++ b/src/AngleSharp.Js/Proxies/DomNodeInstance.cs @@ -246,11 +246,16 @@ protected override OwnPropertyProbe ProbeOwnProperty(JsValue property) /// private PropertyDescriptor GetGlobalProperty(JsValue property) { - if (_value is IWindow) + if (_value is IWindow window) { - var global = _instance.Jint.Global; - - if (!ReferenceEquals(global, this)) + // Another window (of the same origin, the others are wrapped) has its globals in the + // engine of its own document: a frame calling parent.notify() finds the function + // the parent declared. + var global = ReferenceEquals(_instance.Window?.Value, window) + ? _instance.Jint.Global + : AngleSharp.Scripting.JsScriptingService.TryGetInstance(window)?.Jint.Global; + + if (global != null && !ReferenceEquals(global, this)) { return global.GetOwnProperty(property); } diff --git a/src/Directory.Build.props b/src/Directory.Build.props index fd6785a..09b349d 100644 --- a/src/Directory.Build.props +++ b/src/Directory.Build.props @@ -10,7 +10,7 @@ entry of CHANGELOG.md, which build/Build.cs passes in as -p:Version, so this value only affects a plain `dotnet build` and no longer needs bumping for a release. --> - 1.2.2 + 1.2.3