Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 7 additions & 11 deletions packages/ui/src/dom.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
/* oxlint-disable bombshell-dev/no-generic-error -- Web IDL requires TypeError for missing arguments. */
/* oxlint-disable bombshell-dev/exported-function-async -- DOM apis are synchronous. */

import { findElement, findElements, querySelector } from './css-select.ts';
import { asciiUppercase, asciiLowercase } from './ascii.ts';
import { exposeAttributes, NamedNodeMap } from './named-node-map.ts';
import { HTMLCollection } from './html-collection.ts';
import { StyleDeclaration } from './style.ts';
import type { Window } from './window.ts';
import {
addEventListener,
removeEventListener,
Expand Down Expand Up @@ -101,11 +103,7 @@ export abstract class Node implements EventTarget {
}

dispatchEvent(this: EventTarget, event: Event): boolean {
return dispatch(this, {
event,
isTrusted: false,
path: this instanceof Node ? lineage(this) : [this],
});
return dispatch(this, { event, isTrusted: false });
}

hasChildNodes(): boolean {
Expand Down Expand Up @@ -295,6 +293,10 @@ export class Document extends Node {

readonly implementation: DOMImplementation;

get defaultView(): Window | null {
return null;
}

readonly #notify: () => void;
#factory: (...params: ConstructorParameters<typeof Element>) => Element;

Expand Down Expand Up @@ -878,12 +880,6 @@ export class HTMLUnknownElement extends HTMLElement {}

export class XMLDocument extends Document {}

function* lineage(node: Node): Iterable<Node> {
for (let current: Node | null = node; current; current = current.parentNode) {
yield current;
}
}

/** internal helpers **/

function getTextContent(node: Element | DocumentFragment): string {
Expand Down
33 changes: 17 additions & 16 deletions packages/ui/src/events.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
/* oxlint-disable bombshell-dev/no-generic-error -- Web IDL requires TypeError for missing arguments. */

import { asciiLowercase } from './ascii.ts';
import { Document, Node } from './dom.ts';

const NONE = 0;
const CAPTURING_PHASE = 1;
Expand All @@ -19,7 +20,6 @@ export function addEventListener(
options?: ListenerOptions | boolean;
},
): void {
assertEventTarget(target);
type = `${type}`;
if (listener != null && typeof listener !== 'function' && typeof listener !== 'object') {
throw new TypeError('Event listener must be a function or an object');
Expand Down Expand Up @@ -85,7 +85,6 @@ export function removeEventListener(
options?: EventListenerOptions | boolean;
},
): void {
assertEventTarget(target);
type = `${type}`;
if (listener != null && typeof listener !== 'function' && typeof listener !== 'object') {
throw new TypeError('Event listener must be a function or an object');
Expand Down Expand Up @@ -117,13 +116,8 @@ export function createEvent(eventInterface: string): Event {

export function dispatch(
node: EventTarget,
{
event,
isTrusted,
path = [node],
}: { event: Event; isTrusted: boolean; path?: Iterable<EventTarget> },
{ event, isTrusted, target = node }: { event: Event; isTrusted: boolean; target?: EventTarget },
): boolean {
assertEventTarget(node);
if (!(event instanceof Event)) {
throw new TypeError('dispatchEvent requires an Event');
}
Expand All @@ -134,10 +128,23 @@ export function dispatch(
if (!state.initialized) {
throw new DOMException('Event is not initialized', 'InvalidStateError');
}
const path: EventTarget[] = [node];
if (node instanceof Node) {
let root = node;
while (root.parentNode) {
root = root.parentNode;
path.push(root);
}
// A document's event parent is null for "load", so its path stops at the document.
// https://dom.spec.whatwg.org/#interface-document
if (root instanceof Document && root.defaultView && event.type !== 'load') {
path.push(root.defaultView);
}
}
state.dispatching = true;
state.target = node;
state.target = target;
state.isTrusted = isTrusted;
state.path = [...path];
state.path = path;

const invoke = (currentTarget: EventTarget, capture: boolean): void => {
if (state.stopped) {
Expand Down Expand Up @@ -206,12 +213,6 @@ export function dispatch(
}
}

function assertEventTarget(target: EventTarget): void {
if (!(target instanceof EventTarget)) {
throw new TypeError('Event listener methods require an EventTarget');
}
}

function stateFor(event: Event): DispatchState {
const existing = eventStates.get(event);
if (existing) {
Expand Down
26 changes: 26 additions & 0 deletions packages/ui/src/window.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/* oxlint-disable bombshell-dev/exported-function-async -- DOM apis are synchronous. */

import { Node, type Document } from './dom.ts';

export function createWindow(document: Document): Window {
const window = new Window();
return Window.init(window, document);
}

export class Window extends EventTarget {
declare readonly document: Document;

static init(window: Window, document: Document): Window {
Comment thread
cowboyd marked this conversation as resolved.
Resolved
Object.defineProperty(window, 'document', { get: () => document });
Object.defineProperty(document, 'defaultView', { get: () => window });
return window;
}
}

for (const name of ['addEventListener', 'removeEventListener', 'dispatchEvent'] as const) {
Object.defineProperty(
Window.prototype,
name,
Object.getOwnPropertyDescriptor(Node.prototype, name)!,
);
}
24 changes: 22 additions & 2 deletions packages/ui/wpt.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,18 @@ import {
import { NamedNodeMap } from './src/named-node-map.ts';
import { HTMLCollection } from './src/html-collection.ts';
import { StyleDeclaration } from './src/style.ts';
import { dispatch } from './src/events.ts';
import { Window } from './src/window.ts';

const config: WPTConfig = {
createDocument: () => createHTMLDocument(() => {}),
const config: WPTConfig<Document> = {
createWindow(scope) {
const window = Object.setPrototypeOf(scope, Window.prototype) as Window;
return Window.init(
window,
createHTMLDocument(() => {}),
);
},
dispatchEvent: dispatch,
globals: {
AbortController: globalThis.AbortController,
Attr,
Expand All @@ -52,9 +61,18 @@ const config: WPTConfig = {
NamedNodeMap,
Node,
Text,
Window,
XMLDocument,
},
include: {
'html/syntax/parsing/the-end.html': ['DOMContentLoaded', 'load'],
'html/browsers/the-window-object/Document-defaultView.html': [
'Document in a browsing context',
'Document created with the Document constructor',
'Document created with createDocument',
'Document created with createHTMLDocument',
// DOMParser remains unsupported.
],
'html/dom/elements/global-attributes/id-name.html': true,
'html/dom/elements/global-attributes/id-attribute.html': [
'After setting id via id attribute, getElementById find the element by the new id.',
Expand Down Expand Up @@ -400,6 +418,8 @@ const config: WPTConfig = {
exclude: { '**': true },
// excluded cases that run for their shared state, but we don't wait for
forceTimeout: {
// PageTransitionEvent and pageshow remain unsupported.
'html/syntax/parsing/the-end.html': ['pageshow', 'order'],
// Waits on an iframe load the fixture cannot deliver.
'dom/nodes/Node-parentNode.html': ['Removed iframe'],
},
Expand Down
47 changes: 34 additions & 13 deletions packages/web-platform-tests/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,16 +45,20 @@ implementation tests, and run the configured WPT cases.

## Configuration

A consumer needs only a `wpt.config.ts`. It supplies a document factory and the
A consumer needs only a `wpt.config.ts`. It supplies a window factory and the
implementation's global bindings, then selects upstream source paths and original
case names. See the [UI configuration](../ui/wpt.config.ts).

```ts
import type { WPTConfig } from "@bomb.sh/web-platform-tests/config";
import { createHTMLDocument, Node, Document, Element } from "./dom.ts";
import { Window } from "./window.ts";

export default {
createDocument: () => createHTMLDocument(),
createWindow(scope) {
Object.setPrototypeOf(scope, Window.prototype);
return Window.init(scope as Window, createHTMLDocument());
},
globals: { Node, Document, Element },
include: {
"dom/nodes/Node-parentNode.html": ["Document", "Root element"],
Expand All @@ -68,10 +72,22 @@ export default {
} satisfies WPTConfig;
```

`createDocument()` returns a fresh document for each upstream file. The harness
populates it with that file's HTML and installs `document.defaultView`.
`createWindow(scope)` initializes the supplied worker global as the implementation's
window and returns that same object, with a fresh `document` for each upstream file
and URL variant. The factory establishes `window.document` and
`document.defaultView`; the harness preserves those associations. This keeps
`globalThis === window` and `window === document.defaultView` in upstream scripts.
The harness binds the window's event methods to support bare `addEventListener`,
`removeEventListener`, and `dispatchEvent` calls.
It populates the document with that file's HTML and installs `document.location`,
`document.URL`, and `document.documentURI`. Window and document
share the fixture's location. URL reads are supported; navigation fails explicitly.
Optional `dispatchEvent(target, options)`
dispatches trusted host events; options contain `event`, `isTrusted`, and an optional
legacy `target` override used for window load. The UI configuration supplies this
hook using its shared event dispatcher.
`globals` supplies the constructors and other bindings the tests use. `timeout`
sets the maximum execution time per file in milliseconds; the default is 15,000.
sets the maximum execution time per variant in milliseconds; the default is 15,000.

Source keys support `*` within a path segment and `**` across directories. Values
are `true` for every subtest in a source or arrays of exact names and regular
Expand All @@ -88,14 +104,14 @@ whose unfinished work isn't needed by the selected tests.

`framework()` returns selectors for the DOM features used by React, Preact, Vue,
Solid, or Svelte. Pass them to `include` with `exclude: { '**': true }` to run
that profile against the consumer's document factory and globals:
that profile against the consumer's window factory and globals:

```ts
import { framework, type WPTConfig } from "@bomb.sh/web-platform-tests";
import { createDocument, globals } from "./dom.ts";
import { createWindow, globals } from "./fixture.ts";

export default {
createDocument,
createWindow,
globals,
include: framework("preact"),
exclude: { "**": true },
Expand Down Expand Up @@ -127,17 +143,23 @@ fail the checks. These tests run with `pnpm test` and in CI.

The harness parses HTML with parse5, populates the implementation's document,
and executes the original inline scripts and static local helpers in source
order within one fresh Node worker per file. It loads upstream `testharness.js` in
its shell environment and delivers window `load` after the scripts finish.
order within one fresh Node worker per URL variant. HTML `meta name="variant"`
and JavaScript `META: variant` declarations select query/fragment variants; each
gets a separate result group while selectors continue to match original case names.
It loads upstream `testharness.js` in its Window environment with rendering and
cross-window reporting disabled. After the scripts
finish, document readiness changes from `loading` to `interactive`, the harness
dispatches bubbling `DOMContentLoaded` at the document, readiness becomes
`complete`, and window `load` follows with the legacy document target.
Script elements are fixture nodes; parsing them does not execute their contents.

The worker loads the consumer configuration before installing its fixture globals,
then executes the harness and test scripts in that same JavaScript realm. Consumer
methods, native Node APIs, and fixture scripts therefore share the built-in error
constructors and prototypes; no error-prototype patches or error-constructor
bindings in `globals` are needed. Each worker is terminated after its file, so
bindings in `globals` are needed. Each worker is terminated after its variant, so
script globals, top-level lexical declarations, and module state cannot leak into
the next file. The file's `timeout` includes worker startup and configuration
the next variant. The variant's `timeout` includes worker startup and configuration
loading. The harness reports ordinary timeouts at that shared deadline; a parent
watchdog allows 250 ms for those results to arrive before terminating an
unresponsive worker, including one blocked in an asynchronous callback.
Expand All @@ -155,7 +177,6 @@ the runner waits for it normally. The UI lists `Removed iframe` in
The runner supports HTML sources and window `.any.js`/`.window.js` sources with
static helpers. It does not implement iframe navigation, parser-driven script
timing, module/async/defer scripts, server substitutions, or remote helpers.
Window event delegation currently requires extensible event objects.
Unsupported source features fail explicitly. Selecting part of a file does not
claim coverage of its remaining subtests or complete standards conformance.

Expand Down
13 changes: 9 additions & 4 deletions packages/web-platform-tests/src/config.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
/** Source globs select files; arrays select original WPT names within each file. */
export type WPTSelectors = Readonly<Record<string, true | readonly (string | RegExp)[]>>;

export interface WPTConfig {
/** Create a fresh implementation document for each upstream source file. */
createDocument(): unknown;
export interface WPTConfig<TDocument = unknown> {
/** Initialize and return the supplied worker global with a fresh associated document. */
createWindow(scope: object): EventTarget & { readonly document: TDocument };
/** Dispatch host events, including trusted lifecycle events and load's document target. */
dispatchEvent?(
target: EventTarget,
options: { event: Event; isTrusted: boolean; target?: EventTarget },
): boolean;
/** DOM constructors and other implementation bindings exposed to upstream scripts. */
globals?: Record<string, unknown>;
include?: WPTSelectors;
Expand All @@ -13,7 +18,7 @@ export interface WPTConfig {
* Maps exact source paths to arrays of original case names.
*/
forceTimeout?: Readonly<Record<string, readonly string[]>>;
/** Maximum execution time per source file, in milliseconds. Defaults to 15 seconds. */
/** Maximum execution time per source variant, in milliseconds. Defaults to 15 seconds. */
timeout?: number;
}

Expand Down
11 changes: 8 additions & 3 deletions packages/web-platform-tests/src/node/isolated.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,32 @@
import { clearTimeout, setTimeout } from 'node:timers';
import { Worker } from 'node:worker_threads';
import type { WPTFileResult } from './run.ts';
import type { SourceFile } from './source.ts';

interface WPTFileRequest {
file: string;
sourceRoot: string;
configFile: string;
source: SourceFile;
variant: string;
}

export interface WPTWorkerData extends WPTFileRequest {
deadline: number;
}

/** Give each source file a fresh realm for both its implementation and scripts. */
/** Give each source variant a fresh realm for both its implementation and scripts. */
export async function runWPTFile({
file,
sourceRoot,
configFile,
source,
variant,
timeout = 15_000,
}: WPTFileRequest & { timeout?: number }): Promise<WPTFileResult> {
const deadline = Date.now() + timeout;
const worker = new Worker(new URL('./worker.mjs', import.meta.url), {
workerData: { file, sourceRoot, configFile, deadline } satisfies WPTWorkerData,
workerData: { file, sourceRoot, configFile, source, variant, deadline } satisfies WPTWorkerData,
});
const completion = Promise.withResolvers<WPTFileResult>();
// Let an ordinary upstream timeout report its subtests before terminating a blocked worker.
Expand All @@ -31,7 +36,7 @@ export async function runWPTFile({
tests: [],
status: {
status: 2,
message: `WPT worker did not complete within ${timeout}ms: ${file}`,
message: `WPT worker did not complete within ${timeout}ms: ${file}${variant}`,
},
});
},
Expand Down
Loading
Loading