@isoloop/dom 0.0.0-next.4da23df

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,272 @@
1
+ import { i as DomRecord, n as DomEvent, o as Namespace, s as NodeId, t as DomBatch, u as SyncedProp } from "./records-OXGckMg9.js";
2
+ type ListenerFn = (event: Event) => void;
3
+ type Listener = {
4
+ fn: ListenerFn | {
5
+ handleEvent: ListenerFn;
6
+ };
7
+ capture: boolean;
8
+ once: boolean;
9
+ };
10
+ /** Shared state of one document: ids, the recorder, known nodes. */
11
+ type Core = {
12
+ /** The render root, set by `createDom()`. */
13
+ root: WElement | null;
14
+ nextId: number;
15
+ known: Map<NodeId, WNode>;
16
+ record(r: DomRecord): void;
17
+ /** An element was inserted into `document.head`, which the bridge doesn't render. */
18
+ onHead(tag: string): void;
19
+ };
20
+ /** Listener storage and capture/bubble dispatch through `isoParentTarget()`. */
21
+ declare class WEventTarget {
22
+ /** @internal */ isoListeners: Map<string, Listener[]>;
23
+ /** @internal */ isoParentTarget(): WEventTarget | null;
24
+ /** @internal Called when the first listener of `type` is added, or the last removed. */
25
+ isoListenChanged(_type: string, _on: boolean): void;
26
+ addEventListener(type: string, fn: ListenerFn | {
27
+ handleEvent: ListenerFn;
28
+ } | null, options?: boolean | AddEventListenerOptions): void;
29
+ removeEventListener(type: string, fn: ListenerFn | {
30
+ handleEvent: ListenerFn;
31
+ } | null, options?: boolean | EventListenerOptions): void;
32
+ /** Capture from the top, then the target, then bubble (if `bubbles`). */
33
+ dispatchEvent(event: Event): boolean;
34
+ }
35
+ declare abstract class WNode extends WEventTarget {
36
+ static readonly ELEMENT_NODE = 1;
37
+ static readonly TEXT_NODE = 3;
38
+ static readonly COMMENT_NODE = 8;
39
+ static readonly DOCUMENT_NODE = 9;
40
+ static readonly DOCUMENT_FRAGMENT_NODE = 11;
41
+ readonly ELEMENT_NODE = 1;
42
+ readonly TEXT_NODE = 3;
43
+ readonly COMMENT_NODE = 8;
44
+ readonly DOCUMENT_FRAGMENT_NODE = 11;
45
+ abstract readonly nodeType: number;
46
+ abstract readonly nodeName: string;
47
+ readonly ownerDocument: WDocument;
48
+ /** @internal */ readonly isoId: NodeId;
49
+ /** @internal */ isoParent: WParentNode | null;
50
+ /** @internal */ isoPrev: WNode | null;
51
+ /** @internal */ isoNext: WNode | null;
52
+ /** @internal Whether the host knows this node (it's in the tree under the root). */
53
+ isoKnown: boolean;
54
+ constructor(doc: WDocument, id: NodeId);
55
+ /** @internal */ override isoParentTarget(): WEventTarget | null;
56
+ /** @internal */ override isoListenChanged(type: string, on: boolean): void;
57
+ get parentNode(): WParentNode | null;
58
+ get parentElement(): WElement | null;
59
+ get nextSibling(): WNode | null;
60
+ get previousSibling(): WNode | null;
61
+ get firstChild(): WNode | null;
62
+ get lastChild(): WNode | null;
63
+ get childNodes(): readonly WNode[];
64
+ get isConnected(): boolean;
65
+ abstract get textContent(): string;
66
+ abstract set textContent(v: string | null);
67
+ abstract get nodeValue(): string | null;
68
+ abstract set nodeValue(v: string | null);
69
+ hasChildNodes(): boolean;
70
+ contains(other: WNode | null): boolean;
71
+ remove(): void;
72
+ }
73
+ /** What text and comment nodes share: `data`, changed with a `text` record. */
74
+ declare abstract class WCharacterData extends WNode {
75
+ /** @internal */ isoData: string;
76
+ constructor(doc: WDocument, id: NodeId, data: string);
77
+ get data(): string;
78
+ set data(v: unknown);
79
+ get length(): number;
80
+ get textContent(): string;
81
+ set textContent(v: string | null);
82
+ get nodeValue(): string | null;
83
+ set nodeValue(v: string | null);
84
+ }
85
+ declare class WText extends WCharacterData {
86
+ readonly nodeType = 3;
87
+ readonly nodeName = "#text";
88
+ }
89
+ /** A comment node (DOM group 1, ADR 0010): rendered on the host, inert there. */
90
+ declare class WComment extends WCharacterData {
91
+ readonly nodeType = 8;
92
+ readonly nodeName = "#comment";
93
+ }
94
+ /** What `element.style` offers: declarations by property name, plus the methods frameworks call. */
95
+ type WStyle = {
96
+ setProperty(name: string, value: string | null): void;
97
+ removeProperty(name: string): string;
98
+ getPropertyValue(name: string): string;
99
+ cssText: string;
100
+ [property: string]: unknown;
101
+ };
102
+ /**
103
+ * `element.classList` (DOM group 1, ADR 0010): a view of the `class`
104
+ * attribute, so every write travels as an `attr` record.
105
+ */
106
+ declare class WDOMTokenList {
107
+ /** @internal */ readonly isoEl: WElement;
108
+ constructor(el: WElement);
109
+ /** @internal */ isoTokens(): string[];
110
+ /** @internal */ isoWrite(tokens: string[]): void;
111
+ get length(): number;
112
+ get value(): string;
113
+ set value(v: string);
114
+ item(i: number): string | null;
115
+ contains(token: string): boolean;
116
+ add(...tokens: string[]): void;
117
+ remove(...tokens: string[]): void;
118
+ toggle(token: string, force?: boolean): boolean;
119
+ replace(token: string, next: string): boolean;
120
+ toString(): string;
121
+ [Symbol.iterator](): IterableIterator<string>;
122
+ }
123
+ /**
124
+ * What elements and fragments share: an ordered child list. Changes under a
125
+ * known parent become records; a fragment is never known.
126
+ */
127
+ declare abstract class WParentNode extends WNode {
128
+ /** @internal */ isoFirst: WNode | null;
129
+ /** @internal */ isoLast: WNode | null;
130
+ /** @internal */ isoChildCache: WNode[] | null;
131
+ override get firstChild(): WNode | null;
132
+ override get lastChild(): WNode | null;
133
+ override get childNodes(): readonly WNode[];
134
+ get children(): readonly WElement[];
135
+ get firstElementChild(): WElement | null;
136
+ /** Text of the subtree; comments don't count, as in the DOM. */
137
+ get textContent(): string;
138
+ set textContent(v: string | null);
139
+ appendChild<T extends WNode>(child: T): T;
140
+ insertBefore<T extends WNode>(child: T, ref: WNode | null): T;
141
+ removeChild<T extends WNode>(child: T): T;
142
+ replaceChildren(...nodes: (WNode | string)[]): void;
143
+ append(...nodes: (WNode | string)[]): void;
144
+ /** @internal */ isoUnlink(child: WNode): void;
145
+ /** @internal */ isoLink(child: WNode, ref: WNode | null): void;
146
+ }
147
+ /**
148
+ * `DocumentFragment` (DOM group 1, ADR 0010): a detached holder. Inserting
149
+ * it inserts its children, in order, and empties it; it never reaches the
150
+ * host itself.
151
+ */
152
+ declare class WDocumentFragment extends WParentNode {
153
+ readonly nodeType = 11;
154
+ readonly nodeName = "#document-fragment";
155
+ get nodeValue(): string | null;
156
+ set nodeValue(_v: string | null);
157
+ }
158
+ declare class WElement extends WParentNode {
159
+ readonly nodeType = 1;
160
+ readonly localName: string;
161
+ readonly namespaceURI: string;
162
+ /** @internal */ readonly isoNs: Namespace;
163
+ /** @internal */ isoAttrs: Map<string, string>;
164
+ /** @internal */ isoProps: Map<SyncedProp, string | boolean>;
165
+ /** @internal */ isoStyle: WStyle | null;
166
+ /** @internal */ isoClassList: WDOMTokenList | null;
167
+ /** @internal */ isoDataset: Record<string, string | undefined> | null;
168
+ /** @internal The offsets the last `scroll` event brought (design §4.6). */
169
+ isoScroll: {
170
+ top: number;
171
+ left: number;
172
+ };
173
+ constructor(doc: WDocument, id: NodeId, localName: string, ns: Namespace);
174
+ get tagName(): string;
175
+ get nodeName(): string;
176
+ get nodeValue(): string | null;
177
+ set nodeValue(_v: string | null);
178
+ get attributes(): readonly {
179
+ name: string;
180
+ value: string;
181
+ }[];
182
+ getAttribute(name: string): string | null;
183
+ hasAttribute(name: string): boolean;
184
+ setAttribute(name: string, value: unknown): void;
185
+ removeAttribute(name: string): void;
186
+ /** @internal HTML attribute names are case-insensitive; SVG ones aren't. */
187
+ isoAttrName(name: string): string;
188
+ get style(): WStyle;
189
+ get classList(): WDOMTokenList;
190
+ get dataset(): Record<string, string | undefined>;
191
+ /**
192
+ * Read only, and as of the last `scroll` event the element got: the host
193
+ * owns scrolling. 0 until the element is scrolled and listens for `scroll`.
194
+ */
195
+ get scrollTop(): number;
196
+ get scrollLeft(): number;
197
+ get id(): string;
198
+ set id(v: string);
199
+ /** @internal */ isoSetProp(name: SyncedProp, value: string | boolean, record: boolean): void;
200
+ }
201
+ declare class WHTMLElement extends WElement {}
202
+ declare class WDocument extends WEventTarget {
203
+ readonly nodeType = 9;
204
+ readonly nodeName = "#document";
205
+ /** @internal */ readonly isoCore: Core;
206
+ /** Set by `install()`: the worker global. */
207
+ defaultView: unknown;
208
+ readonly activeElement: null;
209
+ /** `null`, as for every document. */
210
+ readonly ownerDocument: null;
211
+ /** A detached body, for code that falls back to `document.body`. */
212
+ readonly body: WHTMLElement;
213
+ /**
214
+ * A detached head: React 19 hoists `<title>`, `<meta>` and `<link>` into
215
+ * it. The bridge doesn't render it (M3a task 3).
216
+ */
217
+ readonly head: WHTMLElement;
218
+ constructor(core: Core);
219
+ createElement(tag: string): WElement;
220
+ createElementNS(ns: string | null, tag: string): WElement;
221
+ /** `data` is converted with `String()`, as in the DOM: Preact passes numbers. */
222
+ createTextNode(data: unknown): WText;
223
+ createComment(data: unknown): WComment;
224
+ /** Fragments never reach the host, so they take no id from the shared counter. */
225
+ createDocumentFragment(): WDocumentFragment;
226
+ /**
227
+ * The first element in tree order with this `id` (DOM group 1, ADR 0010):
228
+ * under the render root, then the detached head. Nodes not yet inserted
229
+ * aren't in the document, so they aren't found.
230
+ */
231
+ getElementById(id: string): WElement | null;
232
+ /**
233
+ * Type selectors only, alone or as a `head > title` child chain: what React
234
+ * 19 asks when it hoists a `<title>`. Queries in general are DOM group 2
235
+ * (ADR 0010), built when a library needs them; anything else throws.
236
+ */
237
+ querySelector(selector: string): WElement | null;
238
+ }
239
+ type WorkerDomOptions = {
240
+ /** Receives each batch, in order. */
241
+ onBatch(batch: DomBatch): void;
242
+ /** Called once per batch with the flush to run; default `queueMicrotask`. */
243
+ schedule?: (flush: () => void) => void;
244
+ /**
245
+ * An element was inserted into `document.head` (React 19 hoists `<title>`,
246
+ * `<meta>` and `<link>` there). The bridge doesn't render the head; the
247
+ * runtime tells the host, which warns in `dev` (M3a task 3).
248
+ */
249
+ onHead?: (tag: string) => void;
250
+ };
251
+ interface WorkerDom {
252
+ readonly document: WDocument;
253
+ /** The isolate's render root; the host maps it to the surface. */
254
+ readonly root: WElement;
255
+ /** Sends pending records now, if any. */
256
+ flush(): void;
257
+ /** Dispatches an event from the host to the node it names (capture and bubble in the worker). */
258
+ deliver(event: DomEvent): void;
259
+ /** The id of a node, for tests and host calls. */
260
+ idOf(node: WNode): NodeId;
261
+ /**
262
+ * Sets an input's, textarea's or select's `value`. With `force`, the host
263
+ * applies it even while the user is focused on a host-owned input, and
264
+ * keeps the caret at its end; it's recorded even if the worker already
265
+ * holds that value, since what the user typed may differ (M3a task 6).
266
+ */
267
+ setValue(node: WNode, value: string, opts?: {
268
+ force?: boolean;
269
+ }): void;
270
+ }
271
+ declare function createDom(opts: WorkerDomOptions): WorkerDom;
272
+ export { WNode as a, WorkerDomOptions as c, WElement as i, createDom as l, WDocument as n, WText as o, WDocumentFragment as r, WorkerDom as s, WComment as t };
package/dist/host.d.ts ADDED
@@ -0,0 +1,28 @@
1
+ import { a as ISOLOOP_DOM_FMT, c as ROOT_ID, d as isDomBatch, i as DomRecord, l as SerializedNode, n as DomEvent, o as Namespace, r as DomMods, s as NodeId, t as DomBatch, u as SyncedProp } from "./records-OXGckMg9.js";
2
+ /** Decides what the applier may create and write. Supplied by the host; required. */
3
+ interface SanitisePolicy {
4
+ /** The host element to create for an isolate's tag. */
5
+ element(tag: string, ns: Namespace): {
6
+ tag: string;
7
+ ns: Namespace;
8
+ };
9
+ /** The attribute value to write on a host element, or `null` to drop it. */
10
+ attribute(hostTag: string, ns: Namespace, name: string, value: string): string | null;
11
+ /**
12
+ * Whether to set a synced property on this element now (allow-list and
13
+ * host-owned input rules). `force` asks to override a focused input.
14
+ */
15
+ property(el: Element, name: SyncedProp, value: string | boolean, force: boolean): boolean;
16
+ }
17
+ interface Applier {
18
+ /** Applies one batch. Returns false, changing nothing, if its shape is wrong. */
19
+ apply(batch: unknown): boolean;
20
+ idFor(node: Node): NodeId | undefined;
21
+ nodeFor(id: NodeId): Node | undefined;
22
+ /** The event record for a DOM event, or `null` if no node on its path listens for it. */
23
+ eventFor(e: Event): DomEvent | null;
24
+ /** Removes everything the isolate rendered and forgets every id. */
25
+ clear(): void;
26
+ }
27
+ export declare function createApplier(container: Element, policy: SanitisePolicy): Applier;
28
+ export { type Applier, type DomBatch, type DomEvent, type DomMods, type DomRecord, ISOLOOP_DOM_FMT, type Namespace, type NodeId, ROOT_ID, type SanitisePolicy, type SerializedNode, type SyncedProp, isDomBatch };
package/dist/host.js ADDED
@@ -0,0 +1,3 @@
1
+ import { n as ROOT_ID, r as isDomBatch, t as ISOLOOP_DOM_FMT } from "./records-wVZrPpqr.js";
2
+ import { t as createApplier } from "./applier-D5wb4gz9.js";
3
+ export { ISOLOOP_DOM_FMT, ROOT_ID, createApplier, isDomBatch };
@@ -0,0 +1,37 @@
1
+ import { _ as WText, a as WDocumentFragment, c as WHTMLElement, d as WHTMLOptionElement, f as WHTMLSelectElement, g as WSVGElement, l as WHTMLIFrameElement, m as WNode, n as WComment, o as WElement, p as WHTMLTextAreaElement, r as WDOMTokenList, u as WHTMLInputElement } from "./dom-7EzPoV0N.js";
2
+ // src/worker/install.ts
3
+ /** The DOM globals the subset provides (ADR 0010 point 2), by their DOM names. */
4
+ const DOM_GLOBALS = {
5
+ Node: WNode,
6
+ Element: WElement,
7
+ HTMLElement: WHTMLElement,
8
+ SVGElement: WSVGElement,
9
+ Text: WText,
10
+ Comment: WComment,
11
+ DocumentFragment: WDocumentFragment,
12
+ HTMLInputElement: WHTMLInputElement,
13
+ HTMLTextAreaElement: WHTMLTextAreaElement,
14
+ HTMLSelectElement: WHTMLSelectElement,
15
+ HTMLOptionElement: WHTMLOptionElement,
16
+ HTMLIFrameElement: WHTMLIFrameElement,
17
+ DOMTokenList: WDOMTokenList
18
+ };
19
+ /**
20
+ * Exposes `dom` as the worker's `document`, `window` and DOM classes, so
21
+ * frameworks find them where they look. Only for isolates with a surface; a
22
+ * headless isolate never calls this.
23
+ */
24
+ function install(dom, scope) {
25
+ const define = (name, value) => {
26
+ Object.defineProperty(scope, name, {
27
+ value,
28
+ configurable: true,
29
+ writable: true
30
+ });
31
+ };
32
+ define("document", dom.document);
33
+ if (!("window" in scope)) define("window", scope);
34
+ for (const [name, value] of Object.entries(DOM_GLOBALS)) define(name, value);
35
+ dom.document.defaultView = scope;
36
+ }
37
+ export { install as n, DOM_GLOBALS as t };
@@ -0,0 +1,61 @@
1
+ declare const ISOLOOP_DOM_FMT = "isoloop-dom@1";
2
+ /** A node id. The worker assigns them at creation; the root is always 0. */
3
+ type NodeId = number;
4
+ declare const ROOT_ID: NodeId;
5
+ type Namespace = "html" | "svg";
6
+ /** Element properties that are synced as properties, not attributes. */
7
+ type SyncedProp = "value" | "checked" | "selected";
8
+ /** A new subtree, as `insert` carries it. */
9
+ type SerializedNode = {
10
+ k: "el";
11
+ id: NodeId;
12
+ tag: string;
13
+ ns: Namespace;
14
+ attrs: [name: string, value: string][];
15
+ props: [name: SyncedProp, value: string | boolean][];
16
+ /** Event types with at least one listener on this node. */
17
+ listen: string[];
18
+ children: SerializedNode[];
19
+ } | {
20
+ k: "text";
21
+ id: NodeId;
22
+ data: string;
23
+ } | {
24
+ k: "comment";
25
+ id: NodeId;
26
+ data: string;
27
+ };
28
+ type DomRecord = ["insert", parent: NodeId, node: SerializedNode, before: NodeId | null] | ["move", parent: NodeId, node: NodeId, before: NodeId | null] | ["remove", node: NodeId] | ["text", node: NodeId, data: string] | ["attr", node: NodeId, name: string, value: string | null] | ["prop", node: NodeId, name: SyncedProp, value: string | boolean, force?: true] | ["listen", node: NodeId, type: string, on: boolean];
29
+ /** One atomic UI change: every record since the last flush, in order. */
30
+ type DomBatch = DomRecord[];
31
+ /** Modifier keys, as an event record carries them. */
32
+ type DomMods = {
33
+ alt: boolean;
34
+ ctrl: boolean;
35
+ meta: boolean;
36
+ shift: boolean;
37
+ };
38
+ /** A DOM event as the host sends it to the worker half (design §4.6). */
39
+ type DomEvent = {
40
+ type: string;
41
+ target: NodeId;
42
+ /** The target and its ancestors that listen for `type`, innermost first. */
43
+ currentTargets: NodeId[];
44
+ value?: string;
45
+ checked?: boolean;
46
+ key?: string;
47
+ code?: string;
48
+ mods: DomMods;
49
+ x?: number;
50
+ y?: number;
51
+ button?: number;
52
+ /** For `resize` on a transferred canvas: its new CSS size (design §4.7). */
53
+ width?: number;
54
+ height?: number;
55
+ /** For `scroll`: the scrolled element's offsets, mirrored on the worker node. */
56
+ scrollTop?: number;
57
+ scrollLeft?: number;
58
+ };
59
+ /** The batch comes from an isolate, so its shape is checked before anything touches the DOM. */
60
+ declare function isDomBatch(x: unknown): x is DomBatch;
61
+ export { ISOLOOP_DOM_FMT as a, ROOT_ID as c, isDomBatch as d, DomRecord as i, SerializedNode as l, DomEvent as n, Namespace as o, DomMods as r, NodeId as s, DomBatch as t, SyncedProp as u };
@@ -0,0 +1,44 @@
1
+ // src/shared/records.ts
2
+ const ISOLOOP_DOM_FMT = "isoloop-dom@1";
3
+ const ROOT_ID = 0;
4
+ const isSyncedProp = (x) => x === "value" || x === "checked" || x === "selected";
5
+ const field = (x, k) => Reflect.get(x, k);
6
+ const isId = (x) => typeof x === "number" && Number.isInteger(x) && x >= 0;
7
+ const isStr = (x) => typeof x === "string";
8
+ const isIdOrNull = (x) => x === null || isId(x);
9
+ const isPair = (x, value) => Array.isArray(x) && x.length === 2 && isStr(x[0]) && value(x[1]);
10
+ function isSerializedNode(x, depth) {
11
+ if (depth > 512 || typeof x !== "object" || x === null) return false;
12
+ const k = field(x, "k");
13
+ if (k === "text" || k === "comment") return isId(field(x, "id")) && isStr(field(x, "data"));
14
+ if (k !== "el") return false;
15
+ const [id, tag, ns, attrs, props, listen, children] = [
16
+ "id",
17
+ "tag",
18
+ "ns",
19
+ "attrs",
20
+ "props",
21
+ "listen",
22
+ "children"
23
+ ].map((f) => field(x, f));
24
+ return isId(id) && isStr(tag) && (ns === "html" || ns === "svg") && Array.isArray(attrs) && attrs.every((a) => isPair(a, isStr)) && Array.isArray(props) && props.every((p) => isPair(p, (v) => isStr(v) || typeof v === "boolean") && Array.isArray(p) && isSyncedProp(p[0])) && Array.isArray(listen) && listen.every(isStr) && Array.isArray(children) && children.every((c) => isSerializedNode(c, depth + 1));
25
+ }
26
+ function isRecord(x) {
27
+ if (!Array.isArray(x)) return false;
28
+ const [k, a, b, c] = x;
29
+ switch (k) {
30
+ case "insert": return x.length === 4 && isId(a) && isSerializedNode(b, 0) && isIdOrNull(c);
31
+ case "move": return x.length === 4 && isId(a) && isId(b) && isIdOrNull(c);
32
+ case "remove": return x.length === 2 && isId(a);
33
+ case "text": return x.length === 3 && isId(a) && isStr(b);
34
+ case "attr": return x.length === 4 && isId(a) && isStr(b) && (c === null || isStr(c));
35
+ case "prop": return (x.length === 4 || x.length === 5 && x[4] === true) && isId(a) && isSyncedProp(b) && (isStr(c) || typeof c === "boolean");
36
+ case "listen": return x.length === 4 && isId(a) && isStr(b) && typeof c === "boolean";
37
+ default: return false;
38
+ }
39
+ }
40
+ /** The batch comes from an isolate, so its shape is checked before anything touches the DOM. */
41
+ function isDomBatch(x) {
42
+ return Array.isArray(x) && x.every(isRecord);
43
+ }
44
+ export { ROOT_ID as n, isDomBatch as r, ISOLOOP_DOM_FMT as t };
@@ -0,0 +1,49 @@
1
+ import { t as DomBatch } from "./records-OXGckMg9.js";
2
+ import { s as WorkerDom } from "./dom-ANUAQHqi.js";
3
+ /** One framework major's log, as `packages/dom/usage/<project>.json` stores it. */
4
+ export type UsageLog = {
5
+ /** E.g. `preact@10.29.8`. */
6
+ framework: string;
7
+ /** `Class.member` for every member of the subset that was read, written or called. */
8
+ used: string[];
9
+ /** Members looked up that nothing in the subset defines (reads that came back `undefined`). */
10
+ missing: string[];
11
+ /** Names checked with `in` that the subset doesn't define: feature probes, not uses. */
12
+ probed: string[];
13
+ };
14
+ export type UsageTracker = {
15
+ /** The log so far, sorted. */
16
+ report(framework: string): UsageLog;
17
+ };
18
+ /** What a fixture worker posts to the page. */
19
+ export type FixtureMessage = {
20
+ t: "batch";
21
+ batch: DomBatch;
22
+ } | {
23
+ t: "usage";
24
+ log: UsageLog;
25
+ } | {
26
+ t: "error";
27
+ error: string;
28
+ };
29
+ /**
30
+ * Installs the subset as this worker's `document`, posts every batch, and
31
+ * delivers the page's events. Import it before the framework: React decides
32
+ * at load time whether it has a DOM. Uncaught errors are posted with their
33
+ * stack, which a worker `error` event doesn't carry.
34
+ */
35
+ export declare function serveFixture(): {
36
+ dom: WorkerDom;
37
+ container: Element;
38
+ };
39
+ /** Starts logging. Call before the framework renders; it can't be undone. */
40
+ export declare function trackUsage(): UsageTracker;
41
+ /**
42
+ * Drives the usage fixture the way a user would, through host events: the
43
+ * fixture renders `<button name="toggle">` (hides and shows a conditional
44
+ * child), `<button name="reorder">` (reverses a keyed list), a controlled
45
+ * `<input>` and a `<select>`. `settle` waits for the framework to commit.
46
+ */
47
+ export declare function driveUsageFixture(dom: WorkerDom, settle: () => Promise<void>): Promise<void>;
48
+ /** Runs the fixture, lets the framework settle, and posts the log (or the error). */
49
+ export declare function reportUsage(tracker: UsageTracker, framework: string, run: () => Promise<void>): Promise<void>;
@@ -0,0 +1,183 @@
1
+ import { n as install, t as DOM_GLOBALS } from "./install-DE1VIvyG.js";
2
+ import { h as WParentNode, i as WDocument, o as WElement, s as WEventTarget, t as WCharacterData, v as createDom } from "./dom-7EzPoV0N.js";
3
+ // src/testing/worker.ts
4
+ /** Everything a framework sees: the classes `install()` exposes, and `document`. */
5
+ const CLASSES = [
6
+ ["EventTarget", WEventTarget],
7
+ ["ParentNode", WParentNode],
8
+ ["CharacterData", WCharacterData],
9
+ ...Object.entries(DOM_GLOBALS).flatMap(([name, C]) => typeof C === "function" ? [[name, C]] : []),
10
+ ["Document", WDocument]
11
+ ];
12
+ /** React's own markers (`_reactRootContainer`, `__reactFiber$…`), read before they're written, or never. */
13
+ const ownedByFramework = (key) => /^_+react/.test(key);
14
+ const sorted = (xs) => {
15
+ const out = [...xs];
16
+ out.sort();
17
+ return out;
18
+ };
19
+ const post = (msg) => {
20
+ postMessage(msg);
21
+ };
22
+ const fail = (err) => {
23
+ post({
24
+ t: "error",
25
+ error: err instanceof Error ? err.stack ?? err.message : String(err)
26
+ });
27
+ };
28
+ const isEventMessage = (x) => typeof x === "object" && x !== null && Reflect.get(x, "t") === "event";
29
+ /**
30
+ * Installs the subset as this worker's `document`, posts every batch, and
31
+ * delivers the page's events. Import it before the framework: React decides
32
+ * at load time whether it has a DOM. Uncaught errors are posted with their
33
+ * stack, which a worker `error` event doesn't carry.
34
+ */
35
+ function serveFixture() {
36
+ const dom = createDom({ onBatch: (batch) => post({
37
+ t: "batch",
38
+ batch
39
+ }) });
40
+ install(dom, self);
41
+ addEventListener("message", (e) => {
42
+ if (isEventMessage(e.data)) dom.deliver(e.data.event);
43
+ });
44
+ addEventListener("error", (e) => {
45
+ e.preventDefault();
46
+ fail(e.error);
47
+ });
48
+ addEventListener("unhandledrejection", (e) => {
49
+ e.preventDefault();
50
+ fail(e.reason);
51
+ });
52
+ const container = dom.root;
53
+ if (!(container instanceof Element)) throw new Error("the subset is not installed");
54
+ return {
55
+ dom,
56
+ container
57
+ };
58
+ }
59
+ /** Starts logging. Call before the framework renders; it can't be undone. */
60
+ function trackUsage() {
61
+ const used = /* @__PURE__ */ new Set();
62
+ const missing = /* @__PURE__ */ new Set();
63
+ const probed = /* @__PURE__ */ new Set();
64
+ const expandos = /* @__PURE__ */ new Set();
65
+ const seen = /* @__PURE__ */ new Set();
66
+ for (const [name, C] of CLASSES) {
67
+ const proto = C.prototype;
68
+ if (seen.has(proto)) continue;
69
+ seen.add(proto);
70
+ for (const key of Reflect.ownKeys(proto)) {
71
+ if (typeof key !== "string" || key === "constructor" || key.startsWith("iso")) continue;
72
+ const d = Object.getOwnPropertyDescriptor(proto, key);
73
+ if (!d) continue;
74
+ const tag = `${name}.${key}`;
75
+ const wrap = (fn) => function(...args) {
76
+ used.add(tag);
77
+ return Reflect.apply(fn, this, args);
78
+ };
79
+ for (const part of [
80
+ "value",
81
+ "get",
82
+ "set"
83
+ ]) {
84
+ const fn = Reflect.get(d, part);
85
+ if (typeof fn === "function") Reflect.set(d, part, wrap(fn));
86
+ }
87
+ Object.defineProperty(proto, key, d);
88
+ }
89
+ }
90
+ const base = Object.prototype;
91
+ const trap = new Proxy(base, {
92
+ get(target, key, receiver) {
93
+ if (typeof key === "string" && !(key in target) && !expandos.has(key) && !ownedByFramework(key)) missing.add(key);
94
+ return Reflect.get(target, key, receiver);
95
+ },
96
+ has(target, key) {
97
+ if (typeof key === "string" && !(key in target) && !expandos.has(key) && !ownedByFramework(key)) probed.add(key);
98
+ return Reflect.has(target, key);
99
+ },
100
+ set(target, key, value, receiver) {
101
+ if (typeof key === "string" && !(key in target)) {
102
+ expandos.add(key);
103
+ missing.delete(key);
104
+ probed.delete(key);
105
+ if (typeof receiver !== "object" || receiver === null) return false;
106
+ return Reflect.defineProperty(receiver, key, {
107
+ value,
108
+ writable: true,
109
+ enumerable: true,
110
+ configurable: true
111
+ });
112
+ }
113
+ return Reflect.set(target, key, value, receiver);
114
+ }
115
+ });
116
+ Object.setPrototypeOf(WEventTarget.prototype, trap);
117
+ return { report: (framework) => ({
118
+ framework,
119
+ used: sorted(used),
120
+ missing: sorted([...missing].filter((k) => !expandos.has(k))),
121
+ probed: sorted([...probed].filter((k) => !expandos.has(k)))
122
+ }) };
123
+ }
124
+ const mods = {
125
+ alt: false,
126
+ ctrl: false,
127
+ meta: false,
128
+ shift: false
129
+ };
130
+ /** The first element under `from` with this tag (and `name` attribute, if given). */
131
+ function find(from, tag, name) {
132
+ for (let n = from.firstChild; n; n = n.nextSibling) {
133
+ if (!(n instanceof WElement)) continue;
134
+ if (n.localName === tag && (name === void 0 || n.getAttribute("name") === name)) return n;
135
+ const deeper = find(n, tag, name);
136
+ if (deeper) return deeper;
137
+ }
138
+ return null;
139
+ }
140
+ /**
141
+ * Drives the usage fixture the way a user would, through host events: the
142
+ * fixture renders `<button name="toggle">` (hides and shows a conditional
143
+ * child), `<button name="reorder">` (reverses a keyed list), a controlled
144
+ * `<input>` and a `<select>`. `settle` waits for the framework to commit.
145
+ */
146
+ async function driveUsageFixture(dom, settle) {
147
+ const send = (tag, name, type, value) => {
148
+ const el = find(dom.root, tag, name);
149
+ if (!el) throw new Error(`usage fixture: no <${tag}${name ? ` name=${name}` : ""}> rendered`);
150
+ dom.deliver({
151
+ type,
152
+ target: dom.idOf(el),
153
+ currentTargets: [],
154
+ mods,
155
+ ...value === void 0 ? {} : { value }
156
+ });
157
+ };
158
+ await settle();
159
+ for (const step of [
160
+ () => send("button", "toggle", "click"),
161
+ () => send("button", "reorder", "click"),
162
+ () => send("input", void 0, "input", "typed"),
163
+ () => send("select", void 0, "change", "b"),
164
+ () => send("button", "toggle", "click")
165
+ ]) {
166
+ step();
167
+ await settle();
168
+ }
169
+ }
170
+ /** Runs the fixture, lets the framework settle, and posts the log (or the error). */
171
+ async function reportUsage(tracker, framework, run) {
172
+ try {
173
+ await run();
174
+ await new Promise((r) => setTimeout(r, 10));
175
+ post({
176
+ t: "usage",
177
+ log: tracker.report(framework)
178
+ });
179
+ } catch (err) {
180
+ fail(err);
181
+ }
182
+ }
183
+ export { driveUsageFixture, reportUsage, serveFixture, trackUsage };