@opentf/afw 0.0.0-stage → 0.32.0

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.
Files changed (72) hide show
  1. package/README.md +66 -2
  2. package/components/Link.d.ts +12 -0
  3. package/components/Link.jsx +54 -0
  4. package/core/context.d.ts +7 -0
  5. package/core/context.js +60 -0
  6. package/core/dev.js +27 -0
  7. package/core/errors.d.ts +14 -0
  8. package/core/errors.js +48 -0
  9. package/core/html.js +10 -0
  10. package/core/metadata.js +184 -0
  11. package/core/reactive.d.ts +5 -0
  12. package/core/reactive.js +190 -0
  13. package/core/render-context.js +11 -0
  14. package/core/signals.d.ts +8 -0
  15. package/core/signals.js +264 -0
  16. package/index.d.ts +5 -0
  17. package/index.js +13 -0
  18. package/jsx-runtime.d.ts +37 -0
  19. package/package.json +60 -4
  20. package/runtime/clipboard.d.ts +7 -0
  21. package/runtime/clipboard.js +47 -0
  22. package/runtime/code-block.d.ts +14 -0
  23. package/runtime/code-block.js +76 -0
  24. package/runtime/context.browser.js +163 -0
  25. package/runtime/context.d.ts +13 -0
  26. package/runtime/context.js +44 -0
  27. package/runtime/dom.browser.js +423 -0
  28. package/runtime/dom.d.ts +142 -0
  29. package/runtime/dom.js +670 -0
  30. package/runtime/error-boundary.browser.js +140 -0
  31. package/runtime/error-boundary.d.ts +19 -0
  32. package/runtime/error-boundary.js +123 -0
  33. package/runtime/events.browser.js +29 -0
  34. package/runtime/events.d.ts +1 -0
  35. package/runtime/events.js +17 -0
  36. package/runtime/head.js +29 -0
  37. package/runtime/hmr.js +170 -0
  38. package/runtime/hydrate.browser.js +144 -0
  39. package/runtime/hydrate.d.ts +173 -0
  40. package/runtime/hydrate.js +536 -0
  41. package/runtime/index.d.ts +14 -0
  42. package/runtime/index.js +24 -0
  43. package/runtime/lifecycle.d.ts +6 -0
  44. package/runtime/lifecycle.js +14 -0
  45. package/runtime/mount.d.ts +20 -0
  46. package/runtime/mount.js +85 -0
  47. package/runtime/portal.browser.js +85 -0
  48. package/runtime/portal.d.ts +12 -0
  49. package/runtime/portal.js +74 -0
  50. package/runtime/raw-html.d.ts +11 -0
  51. package/runtime/raw-html.js +55 -0
  52. package/runtime/resource.d.ts +9 -0
  53. package/runtime/resource.js +139 -0
  54. package/runtime/route-data.d.ts +15 -0
  55. package/runtime/route-data.js +64 -0
  56. package/runtime/router.d.ts +146 -0
  57. package/runtime/router.js +765 -0
  58. package/server/adapters/node.d.ts +28 -0
  59. package/server/adapters/node.js +74 -0
  60. package/server/api.d.ts +175 -0
  61. package/server/api.js +233 -0
  62. package/server/builtins.js +42 -0
  63. package/server/cookies.d.ts +44 -0
  64. package/server/cookies.js +122 -0
  65. package/server/head.js +9 -0
  66. package/server/index.d.ts +151 -0
  67. package/server/index.js +31 -0
  68. package/server/loader.js +201 -0
  69. package/server/middleware.js +119 -0
  70. package/server/render-context.js +30 -0
  71. package/server/render.js +172 -0
  72. package/server/ssg-runtime.js +239 -0
@@ -0,0 +1,140 @@
1
+ import { describe, expect, test } from "../../afw-test/browser-runner.js";
2
+
3
+ import { ErrorBoundary, handleError } from "./error-boundary.js";
4
+ import { hydrationProps } from "./hydrate.js";
5
+
6
+ const tick = () => new Promise((r) => queueMicrotask(r));
7
+
8
+ // A component that throws on connect until a module flag is cleared — mirrors how
9
+ // a compiled component funnels its connectedCallback error through handleError,
10
+ // including the deferred disconnect teardown that resets `_mounted` so a
11
+ // re-inserted element renders again.
12
+ let armed = true;
13
+ customElements.define(
14
+ "afw-bomb",
15
+ class extends HTMLElement {
16
+ connectedCallback() {
17
+ this._pendingTeardown = false;
18
+ if (this._mounted) return;
19
+ this._mounted = true;
20
+ try {
21
+ if (armed) throw new Error("boom");
22
+ this.appendChild(document.createTextNode("ok"));
23
+ } catch (e) {
24
+ handleError(this, e, { phase: "render", component: "Bomb" });
25
+ }
26
+ }
27
+ disconnectedCallback() {
28
+ this._pendingTeardown = true;
29
+ queueMicrotask(() => {
30
+ if (!this._pendingTeardown) return;
31
+ this._pendingTeardown = false;
32
+ this._mounted = false;
33
+ this.replaceChildren();
34
+ });
35
+ }
36
+ },
37
+ );
38
+
39
+ // A component whose throw condition comes from a *prop*, initialized the way the
40
+ // compiler emits it on an SSR/SSG page: read the server-recorded props out of the
41
+ // hydration record at construct time, then let the parent push updates in through
42
+ // the property setter. This is the shape that made Retry unrecoverable — see the
43
+ // "props updated after the failure" test.
44
+ customElements.define(
45
+ "afw-prop-bomb",
46
+ class extends HTMLElement {
47
+ constructor() {
48
+ super();
49
+ const props = hydrationProps(this);
50
+ this._armed = props && "armed" in props ? props.armed : this.hasAttribute("armed");
51
+ }
52
+ get armed() {
53
+ return this._armed;
54
+ }
55
+ set armed(v) {
56
+ this._armed = v;
57
+ }
58
+ connectedCallback() {
59
+ this._pendingTeardown = false;
60
+ if (this._mounted) return;
61
+ this._mounted = true;
62
+ try {
63
+ if (this._armed) throw new Error("prop boom");
64
+ this.appendChild(document.createTextNode("ok"));
65
+ } catch (e) {
66
+ handleError(this, e, { phase: "render", component: "PropBomb" });
67
+ }
68
+ }
69
+ disconnectedCallback() {
70
+ this._pendingTeardown = true;
71
+ queueMicrotask(() => {
72
+ if (!this._pendingTeardown) return;
73
+ this._pendingTeardown = false;
74
+ this._mounted = false;
75
+ this.replaceChildren();
76
+ });
77
+ }
78
+ },
79
+ );
80
+
81
+ describe("ErrorBoundary", () => {
82
+ test("catches a descendant render error and shows the fallback", async () => {
83
+ armed = true;
84
+ const boundary = document.createElement("afw-internal-error-boundary");
85
+ boundary.fallback = (error) => `caught: ${error.message}`;
86
+ boundary.appendChild(document.createElement("afw-bomb"));
87
+ document.body.appendChild(boundary); // connect: boundary, then bomb throws
88
+
89
+ await tick(); // catch defers the swap to a microtask
90
+ expect(boundary.querySelector("afw-bomb")).toBe(null); // broken subtree torn down
91
+ expect(boundary.textContent).toContain("caught: boom");
92
+ boundary.remove();
93
+ });
94
+
95
+ test("reset() rebuilds the subtree and recovers once the cause is gone", async () => {
96
+ armed = true;
97
+ const boundary = document.createElement("afw-internal-error-boundary");
98
+ boundary.appendChild(document.createElement("afw-bomb"));
99
+ document.body.appendChild(boundary);
100
+ await tick();
101
+ expect(boundary.querySelector("[data-afw-fallback]")).not.toBe(null);
102
+
103
+ armed = false; // defuse, then retry
104
+ boundary.reset();
105
+ await tick();
106
+ expect(boundary.querySelector("[data-afw-fallback]")).toBe(null);
107
+ expect(boundary.textContent).toContain("ok");
108
+ boundary.remove();
109
+ });
110
+
111
+ // Regression: reset() used to replay `cloneNode(true)` snapshots. A clone is a
112
+ // different element from the one the parent's reactive prop bindings target, so
113
+ // the fix the user just made never reached the rebuilt subtree and Retry threw
114
+ // forever. On an SSR page the clone also carried `data-h`, which made the rebuilt
115
+ // component re-read its *frozen server-time* props out of the hydration payload.
116
+ test("reset() delivers props updated after the failure", async () => {
117
+ const boundary = document.createElement("afw-internal-error-boundary");
118
+ // `data-hp` is how a pre-route-render island carries its server props; it goes
119
+ // through the same reader as the `data-h` payload the SSG writes.
120
+ boundary.innerHTML = `<afw-prop-bomb data-hp='{"armed":true}'></afw-prop-bomb>`;
121
+ const bomb = boundary.firstElementChild;
122
+ document.body.appendChild(boundary);
123
+ await tick();
124
+ expect(boundary.querySelector("[data-afw-fallback]")).not.toBe(null);
125
+
126
+ // The parent pushes the fix in through the same element it has always held —
127
+ // exactly what a compiled `armed={value}` binding does.
128
+ bomb.armed = false;
129
+ boundary.reset();
130
+ await tick();
131
+ await tick();
132
+ expect(boundary.querySelector("[data-afw-fallback]")).toBe(null);
133
+ expect(boundary.textContent).toContain("ok");
134
+ boundary.remove();
135
+ });
136
+
137
+ test("ErrorBoundary export is the element class", () => {
138
+ expect(ErrorBoundary).toBe(customElements.get("afw-internal-error-boundary"));
139
+ });
140
+ });
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Report a caught render/mount error and route it to the nearest enclosing
3
+ * `<ErrorBoundary>`. Called from a throwing component's connectedCallback catch.
4
+ */
5
+ export function handleError(el: any, error: any, context?: {}): void;
6
+ export class ErrorBoundaryElement extends HTMLElement {
7
+ set fallback(fn: any);
8
+ get fallback(): any;
9
+ _fallback: any;
10
+ connectedCallback(): void;
11
+ _mounted: boolean | undefined;
12
+ _blueprint: ChildNode[] | undefined;
13
+ catch(error: any): void;
14
+ _failed: boolean | undefined;
15
+ reset(): void;
16
+ #private;
17
+ }
18
+ /** JSX props consumed by the compiler-generated custom-element host. */
19
+ export const ErrorBoundary: { new(props: { fallback: (error: unknown, reset: () => void) => unknown; children?: unknown }): ErrorBoundaryElement; prototype: ErrorBoundaryElement };
@@ -0,0 +1,123 @@
1
+ //! ErrorBoundary — catch render/mount errors from descendant components and show
2
+ //! a fallback instead of letting the broken subtree (or its siblings) take the
3
+ //! page down.
4
+ //
5
+ // <ErrorBoundary fallback={(error, reset) => `Oops: ${error.message}`}>
6
+ // <Risky/>
7
+ // </ErrorBoundary>
8
+ //
9
+ // A descendant component's connectedCallback funnels a thrown error through
10
+ // `handleError(this, …)` (emitted by the compiler): it reports the error (dev
11
+ // overlay / logging) and walks up the DOM — hopping across portals, like
12
+ // `readContext` — to the nearest `afw-internal-error-boundary`, which swaps its children
13
+ // for the fallback. `reset()` rebuilds the original subtree (snapshotted before it
14
+ // ran) to retry. Only synchronous render/mount errors are caught; later
15
+ // effect/event errors still go to global reporting (as with React boundaries).
16
+
17
+ import { reportError } from "../core/errors.js";
18
+
19
+ /**
20
+ * Report a caught render/mount error and route it to the nearest enclosing
21
+ * `<ErrorBoundary>`. Called from a throwing component's connectedCallback catch.
22
+ */
23
+ export function handleError(el, error, context = {}) {
24
+ reportError(error, context); // always log / surface in the dev overlay
25
+ let node = el;
26
+ while (node) {
27
+ const boundary = node.closest ? node.closest("afw-internal-error-boundary") : null;
28
+ if (boundary) {
29
+ boundary.catch(error, context);
30
+ return;
31
+ }
32
+ const portal = node.closest ? node.closest("[data-afw-portal]") : null;
33
+ node = portal ? portal.__portalHost : null;
34
+ }
35
+ }
36
+
37
+ // A self-contained fallback (inline-styled so it reads fine without any app CSS).
38
+ function defaultFallback(message, reset) {
39
+ const box = document.createElement("div");
40
+ box.setAttribute("role", "alert");
41
+ box.setAttribute("data-afw-fallback", "");
42
+ box.style.cssText =
43
+ "display:flex;align-items:center;gap:.75rem;padding:.75rem 1rem;border:1px solid #ef4444;" +
44
+ "border-radius:.5rem;background:rgba(239,68,68,.1);color:#fca5a5;font:14px system-ui,sans-serif";
45
+ const text = document.createElement("span");
46
+ text.textContent = message;
47
+ box.appendChild(text);
48
+ const retry = document.createElement("button");
49
+ retry.textContent = "Retry";
50
+ retry.style.cssText =
51
+ "margin-left:auto;padding:.25rem .75rem;border-radius:.375rem;border:none;cursor:pointer;" +
52
+ "background:#ef4444;color:#fff;font:inherit";
53
+ retry.addEventListener("click", reset);
54
+ box.appendChild(retry);
55
+ return box;
56
+ }
57
+
58
+ export class ErrorBoundaryElement extends HTMLElement {
59
+ set fallback(fn) {
60
+ this._fallback = fn;
61
+ }
62
+ get fallback() {
63
+ return this._fallback;
64
+ }
65
+
66
+ connectedCallback() {
67
+ if (this._mounted) return;
68
+ this._mounted = true;
69
+ // Hold the *live* child nodes — not clones. reset() re-inserts these same
70
+ // nodes, which is what lets a rebuilt subtree see the fix: the parent's
71
+ // reactive prop bindings target these exact elements, so any prop written
72
+ // after the failure is already on them. A clone is a different element, cut
73
+ // off from those bindings — and on an SSR page it still carries `data-h`, so
74
+ // it would re-read its *server-time* props from the hydration payload and
75
+ // throw on the same stale value forever.
76
+ this._blueprint = Array.from(this.childNodes);
77
+ }
78
+
79
+ // Invoked by handleError when a descendant throws during render/mount. Deferred
80
+ // to a microtask so we never mutate the tree mid-connectedCallback (re-entrancy).
81
+ catch(error) {
82
+ if (this._failed) return; // first error wins; ignore the cascade
83
+ this._failed = true;
84
+ queueMicrotask(() => this.#renderFallback(error));
85
+ }
86
+
87
+ #renderFallback(error) {
88
+ this.replaceChildren(); // tear the broken subtree down (runs disconnect cleanups)
89
+ const reset = () => this.reset();
90
+ let view = null;
91
+ try {
92
+ view = this._fallback ? this._fallback(error, reset) : null;
93
+ } catch (e) {
94
+ reportError(e, { phase: "fallback" });
95
+ }
96
+ const message = typeof view === "string" ? view : (error && error.message) || "Something went wrong";
97
+ this.appendChild(view instanceof Node ? view : defaultFallback(message, reset));
98
+ }
99
+
100
+ reset() {
101
+ if (!this._failed) return;
102
+ this._failed = false;
103
+ // Deferred for the same reason the fallback swap is: tearing the broken
104
+ // subtree down queued each child's disconnect teardown on the microtask
105
+ // queue, and those must run (clearing `_mounted`) before the nodes go back
106
+ // in — otherwise a re-inserted child is treated as a move and never renders.
107
+ // Microtask order guarantees it: the teardowns were queued first.
108
+ queueMicrotask(() => {
109
+ if (this._failed) return; // failed again before the retry landed
110
+ // Re-insert the original nodes: each child reconnects and renders afresh,
111
+ // now reading whatever props it currently holds — it may throw again
112
+ // (→ catch) or render cleanly if the cause is gone.
113
+ this.replaceChildren(...this._blueprint);
114
+ });
115
+ }
116
+ }
117
+
118
+ // Exported so `import { ErrorBoundary } from "@opentf/afw"` resolves; the import
119
+ // side effect registers the element (JSX uses the `afw-internal-error-boundary` tag).
120
+ export const ErrorBoundary = ErrorBoundaryElement;
121
+ if (typeof customElements !== "undefined" && !customElements.get("afw-internal-error-boundary")) {
122
+ customElements.define("afw-internal-error-boundary", ErrorBoundaryElement);
123
+ }
@@ -0,0 +1,29 @@
1
+ import { describe, expect, test } from "../../afw-test/browser-runner.js";
2
+
3
+ import { emit } from "./events.js";
4
+
5
+ describe("emit", () => {
6
+ test("dispatches a bubbling, composed CustomEvent carrying detail", () => {
7
+ const parent = document.createElement("div");
8
+ const child = document.createElement("button");
9
+ parent.appendChild(child);
10
+ document.body.appendChild(parent);
11
+
12
+ let seen;
13
+ parent.addEventListener("select", (e) => (seen = e));
14
+ emit(child, "select", { id: 7 });
15
+
16
+ expect(seen).toBeDefined(); // bubbled to the parent
17
+ expect(seen.detail).toEqual({ id: 7 });
18
+ expect(seen.bubbles).toBe(true);
19
+ expect(seen.composed).toBe(true);
20
+ parent.remove();
21
+ });
22
+
23
+ test("returns false when a listener preventDefaults a cancelable event", () => {
24
+ const el = document.createElement("div");
25
+ el.addEventListener("act", (e) => e.preventDefault());
26
+ expect(emit(el, "act", null, { cancelable: true })).toBe(false);
27
+ expect(emit(el, "noop", null)).toBe(true);
28
+ });
29
+ });
@@ -0,0 +1 @@
1
+ export function emit(el: any, name: any, detail: any, options?: {}): any;
@@ -0,0 +1,17 @@
1
+ //! Events — the dispatch half of the hybrid event model.
2
+ //
3
+ // Two channels (SPEC §5.4):
4
+ // • callback props — `<Picker onSelect={fn}>` sets a property; the component
5
+ // calls `this.onSelect?.(detail)`. Direct parent→child, no bubbling.
6
+ // • event listeners — `<Picker onSelect:listen={fn}>` compiles to
7
+ // `addEventListener("select", fn, opts)` (with `:capture`/`:passive`/`:once`),
8
+ // for bubbling/interop/multiple subscribers. `emit` is the matching dispatch.
9
+ //
10
+ // `emit(el, "select", detail)` fires a CustomEvent that bubbles and crosses shadow
11
+ // boundaries by default, so a `web-*` element is a first-class event source for any
12
+ // framework consuming it. Returns false if a listener called preventDefault().
13
+
14
+ export function emit(el, name, detail, options = {}) {
15
+ const { bubbles = true, composed = true, cancelable = false } = options;
16
+ return el.dispatchEvent(new CustomEvent(name, { detail, bubbles, composed, cancelable }));
17
+ }
@@ -0,0 +1,29 @@
1
+ import { renderHead } from "../core/metadata.js";
2
+
3
+ let fallbackTitle = "";
4
+ let baseUrl = "";
5
+
6
+ export function prepareRouteHead(hydrate) {
7
+ baseUrl = window.location.origin;
8
+ const canonical = document.head.querySelector('link[rel="canonical"]')?.href;
9
+ if (canonical) {
10
+ try { baseUrl = new URL(canonical, window.location.href).origin; } catch {}
11
+ }
12
+ fallbackTitle = hydrate ? "" : document.title;
13
+ }
14
+
15
+ /** Replace route SEO while preserving styles, executable scripts and viewport. */
16
+ export function updateRouteHead(metadata, path) {
17
+ const template = document.createElement("template");
18
+ template.innerHTML = renderHead(metadata, { path, baseUrl, managed: true });
19
+ for (const node of [...document.head.children]) {
20
+ const name = node.getAttribute("name") || "";
21
+ const property = node.getAttribute("property") || "";
22
+ if (node.hasAttribute("data-afw-head") || node.localName === "title" ||
23
+ (node.localName === "meta" && (["description", "robots"].includes(name) || name.startsWith("twitter:") || property.startsWith("og:") || property.startsWith("article:"))) ||
24
+ (node.localName === "link" && node.getAttribute("rel") === "canonical") ||
25
+ (node.localName === "script" && node.getAttribute("type") === "application/ld+json")) node.remove();
26
+ }
27
+ document.head.append(...template.content.childNodes);
28
+ if (!document.head.querySelector("title") && fallbackTitle) document.title = fallbackTitle;
29
+ }
package/runtime/hmr.js ADDED
@@ -0,0 +1,170 @@
1
+ // Imported only by development compiler output. The Custom Elements registry
2
+ // caches lifecycle callbacks at define time, so stable callbacks dispatch to the
3
+ // current implementation rather than redefining an existing tag.
4
+ import { scope } from "../core/signals.js";
5
+ import { refreshHotRoute } from "./router.js";
6
+
7
+ const components = new Map();
8
+
9
+ // The `$state` slots of the page/layout view currently being built.
10
+ let routeSlots = null;
11
+
12
+ /**
13
+ * A page/layout `$state` signal kept in the view's refresh slots: a refresh of the
14
+ * same view reuses the signal (and its value) when the state shape is unchanged.
15
+ */
16
+ export function hotRouteState(key, create) {
17
+ if (!routeSlots) return create();
18
+ if (!routeSlots.has(key)) routeSlots.set(key, create());
19
+ return routeSlots.get(key);
20
+ }
21
+
22
+ export function registerHotRoute(hot, factory, safe, shape = "") {
23
+ if (!hot) return factory;
24
+ if (!safe) {
25
+ if (hot.data.afwRouteBoundary) hot.invalidate();
26
+ return factory;
27
+ }
28
+ hot.data.afwRouteBoundary = true;
29
+ const record = hot.keep("afw-route", () => {
30
+ const entry = { factory, shape };
31
+ // `previous` is the view node this build replaces during a refresh. Its state
32
+ // slots carry over when the declarations still match; otherwise state is fresh.
33
+ entry.view = (props, previous) => {
34
+ const kept = previous?.__afwHotSlots;
35
+ const slots = kept && kept.shape === entry.shape ? kept.slots : new Map();
36
+ let failed = false, failure;
37
+ const outer = routeSlots;
38
+ routeSlots = slots;
39
+ let built;
40
+ try {
41
+ built = scope(() => {
42
+ try { return entry.factory(props); }
43
+ catch (error) { failed = true; failure = error; }
44
+ });
45
+ } finally {
46
+ routeSlots = outer;
47
+ }
48
+ if (failed) {
49
+ try { built.dispose(); } catch (error) { console.error(error); }
50
+ throw failure;
51
+ }
52
+ const node = built.result;
53
+ const lifecycle = node.__lifecycle ??= { mounts: [], cleanups: [] };
54
+ lifecycle.cleanups.push(built.dispose);
55
+ node.__afwHotFactory = entry.view;
56
+ node.__afwHotSlots = { shape: entry.shape, slots };
57
+ return node;
58
+ };
59
+ return entry;
60
+ });
61
+ const updated = record.factory !== factory || record.shape !== shape;
62
+ record.factory = factory;
63
+ record.shape = shape;
64
+ hot.accept();
65
+ if (updated) queueMicrotask(() => {
66
+ if (!hot.data.afwInvalidated) void refreshHotRoute(record.view);
67
+ });
68
+ return record.view;
69
+ }
70
+
71
+ export function hotState(host, key, create) {
72
+ const slots = host._hotState ??= new Map();
73
+ if (!slots.has(key)) slots.set(key, create());
74
+ return slots.get(key);
75
+ }
76
+
77
+ function cleanup(host) {
78
+ const disposers = host._cleanups || [];
79
+ host._cleanups = [];
80
+ for (const dispose of disposers) {
81
+ try { dispose(); } catch (error) { console.error(error); }
82
+ }
83
+ }
84
+
85
+ function refresh(record, hosts) {
86
+ for (const host of hosts) {
87
+ if (!host.isConnected) continue;
88
+ const scroll = [window.scrollX, window.scrollY];
89
+ const focused = document.activeElement;
90
+ const focusId = host.contains(focused) ? focused.id : null;
91
+ const selection = focusId && typeof focused.selectionStart === "number"
92
+ ? [focused.selectionStart, focused.selectionEnd] : null;
93
+ cleanup(host);
94
+ host._mounted = false;
95
+ host._hotRefreshing = true;
96
+ // Slotted children belong to the parent. Keep the original capture and move
97
+ // those nodes into the new view in the same task (no genuine disconnect).
98
+ host.replaceChildren(...(host._hotChildren || []));
99
+ try { record.connected?.call(host); }
100
+ finally { host._hotRefreshing = false; }
101
+ if (focusId) {
102
+ const target = document.getElementById(focusId);
103
+ if (target && host.contains(target)) {
104
+ target.focus({ preventScroll: true });
105
+ if (selection && typeof target.setSelectionRange === "function") {
106
+ try { target.setSelectionRange(...selection); } catch {}
107
+ }
108
+ }
109
+ }
110
+ window.scrollTo(...scroll);
111
+ }
112
+ }
113
+
114
+ export function registerHotModule(hot, entries, safe, accept = true) {
115
+ const signature = entries.map(([component, shape]) => [component.tag, shape]);
116
+ const previous = hot?.data.afwSignature;
117
+ if (previous && (!safe || JSON.stringify(previous) !== JSON.stringify(signature))) {
118
+ hot.data.afwInvalidated = true;
119
+ hot.invalidate();
120
+ return;
121
+ }
122
+ if (hot) {
123
+ hot.data.afwSignature = signature;
124
+ hot.data.afwInvalidated = false;
125
+ }
126
+ const changed = [];
127
+ for (const [component] of entries) {
128
+ const tag = component.tag;
129
+ let record = components.get(tag);
130
+ const prototype = component.prototype;
131
+ const connected = prototype.connectedCallback;
132
+ const disconnected = prototype.disconnectedCallback;
133
+ const attributeChanged = prototype.attributeChangedCallback;
134
+ if (record) {
135
+ Object.assign(record, { connected, disconnected, attributeChanged });
136
+ changed.push(record);
137
+ continue;
138
+ }
139
+ // A tag registered outside this refresh runtime cannot safely be replaced.
140
+ if (customElements.get(tag)) {
141
+ if (hot) hot.data.afwInvalidated = true;
142
+ hot?.invalidate();
143
+ continue;
144
+ }
145
+ record = { connected, disconnected, attributeChanged, instances: new Set() };
146
+ components.set(tag, record);
147
+ prototype.connectedCallback = function () {
148
+ record.instances.add(this);
149
+ return record.connected?.call(this);
150
+ };
151
+ prototype.disconnectedCallback = function () {
152
+ record.instances.delete(this);
153
+ return record.disconnected?.call(this);
154
+ };
155
+ if (attributeChanged) prototype.attributeChangedCallback = function (...args) {
156
+ return record.attributeChanged.call(this, ...args);
157
+ };
158
+ customElements.define(tag, component);
159
+ }
160
+ // Install all implementations first. Refresh existing ancestors before their
161
+ // descendants, so children recreated by a parent don't mount twice per update.
162
+ const jobs = changed.flatMap(record => [...record.instances].map(host => {
163
+ let depth = 0;
164
+ for (let parent = host.parentElement; parent; parent = parent.parentElement) depth++;
165
+ return { record, host, depth };
166
+ }));
167
+ jobs.sort((a, b) => a.depth - b.depth);
168
+ for (const { record, host } of jobs) refresh(record, [host]);
169
+ if (safe && accept) hot?.accept();
170
+ }
@@ -0,0 +1,144 @@
1
+ import { describe, expect, test } from "../../afw-test/browser-runner.js";
2
+
3
+ import { signal } from "../core/signals.js";
4
+ import { bindText } from "./dom.js";
5
+ import {
6
+ HydrationMismatch,
7
+ claimElement,
8
+ claimText,
9
+ cursor,
10
+ isHydrating,
11
+ runHydration,
12
+ skipNode,
13
+ } from "./hydrate.js";
14
+
15
+ // Build a real DOM subtree from a server HTML string (as the browser would on load).
16
+ function serverDom(html) {
17
+ const host = document.createElement("div");
18
+ host.innerHTML = html;
19
+ return host;
20
+ }
21
+
22
+ describe("the hydration flag", () => {
23
+ test("isHydrating is false outside a pass and true inside runHydration", () => {
24
+ expect(isHydrating()).toBe(false);
25
+ let inside = null;
26
+ runHydration(() => (inside = isHydrating()));
27
+ expect(inside).toBe(true);
28
+ expect(isHydrating()).toBe(false);
29
+ });
30
+
31
+ test("runHydration restores the prior value (nesting-safe) and returns fn's result", () => {
32
+ const seen = [];
33
+ const out = runHydration(() => {
34
+ seen.push(isHydrating()); // true
35
+ runHydration(() => seen.push(isHydrating())); // true
36
+ seen.push(isHydrating()); // still true after the inner pass
37
+ return 42;
38
+ });
39
+ expect(seen).toEqual([true, true, true]);
40
+ expect(out).toBe(42);
41
+ expect(isHydrating()).toBe(false);
42
+ });
43
+ });
44
+
45
+ describe("claimElement", () => {
46
+ test("claims the next element, asserts its tag, and advances the cursor", () => {
47
+ const host = serverDom("<section></section><span></span>");
48
+ const cur = cursor(host);
49
+ const section = claimElement(cur, "section");
50
+ expect(section).toBe(host.firstChild);
51
+ const span = claimElement(cur, "span");
52
+ expect(span.tagName.toLowerCase()).toBe("span");
53
+ expect(cur.node).toBe(null); // walked off the end
54
+ });
55
+
56
+ test("throws HydrationMismatch on a wrong tag or a missing node", () => {
57
+ const host = serverDom("<p></p>");
58
+ const cur = cursor(host);
59
+ expect(() => claimElement(cur, "div")).toThrow(HydrationMismatch);
60
+ const empty = cursor(serverDom(""));
61
+ expect(() => claimElement(empty, "div")).toThrow(HydrationMismatch);
62
+ });
63
+ });
64
+
65
+ describe("claimText", () => {
66
+ test("adopts the server text node inside <!--$-->…<!--/--> markers", () => {
67
+ const host = serverDom("Count <!--$-->5<!--/-->");
68
+ const cur = cursor(host);
69
+ skipNode(cur); // the static "Count " text
70
+ const textNode = claimText(cur);
71
+ expect(textNode.nodeType).toBe(3);
72
+ expect(textNode.data).toBe("5");
73
+ expect(cur.node).toBe(null); // advanced past the closing marker
74
+ });
75
+
76
+ test("synthesizes an empty anchor when the server rendered no value", () => {
77
+ const host = serverDom("<!--$--><!--/-->");
78
+ const cur = cursor(host);
79
+ const textNode = claimText(cur);
80
+ expect(textNode.nodeType).toBe(3);
81
+ expect(textNode.data).toBe("");
82
+ // The synthesized node lives between the markers, in the real tree.
83
+ expect(textNode.parentNode).toBe(host);
84
+ });
85
+
86
+ test("throws when the start marker is absent", () => {
87
+ const cur = cursor(serverDom("<span></span>"));
88
+ expect(() => claimText(cur)).toThrow(HydrationMismatch);
89
+ });
90
+ });
91
+
92
+ describe("skipNode", () => {
93
+ test("advances past a static text node and returns it", () => {
94
+ const cur = cursor(serverDom("hi<span></span>"));
95
+ const skipped = skipNode(cur);
96
+ expect(skipped.nodeType).toBe(3);
97
+ expect(cur.node.tagName.toLowerCase()).toBe("span"); // advanced to the next node
98
+ });
99
+
100
+ test("throws when the aligned node is not static text (cursor misalignment)", () => {
101
+ // A step meant for a static `ViewNode::Text` must land on a real text node; an
102
+ // element/comment/absent node there means the walk desynced — surface it here.
103
+ expect(() => skipNode(cursor(serverDom("<span></span>")))).toThrow(HydrationMismatch);
104
+ expect(() => skipNode(cursor(serverDom("")))).toThrow(HydrationMismatch);
105
+ });
106
+ });
107
+
108
+ describe("integrated walk — adopt, don't rebuild", () => {
109
+ test("hydrating <div><h1>Count {n}</h1></div> adopts nodes and wires reactivity", () => {
110
+ // What the SSG/SSR backend emits for `<div class="box"><h1>Count {n}</h1></div>`
111
+ // with n initially 3.
112
+ const host = serverDom('<div class="box"><h1>Count <!--$-->3<!--/--></h1></div>');
113
+ const div = host.firstChild;
114
+ const h1 = div.firstChild;
115
+ const serverText = h1.childNodes[2]; // "Count ", <!--$-->, "3", <!--/-->
116
+
117
+ const n = signal(3); // client signal initializes to the same value the server used
118
+ let boundNode = null;
119
+
120
+ runHydration(() => {
121
+ const root = cursor(host);
122
+ const claimedDiv = claimElement(root, "div");
123
+ const inner = cursor(claimedDiv);
124
+ const claimedH1 = claimElement(inner, "h1");
125
+ const h1cur = cursor(claimedH1);
126
+ skipNode(h1cur); // "Count "
127
+ boundNode = claimText(h1cur);
128
+ bindText(boundNode, () => n.value);
129
+ });
130
+
131
+ // Adoption: the very same server nodes were claimed — nothing was re-created.
132
+ expect(boundNode).toBe(serverText);
133
+ expect(host.firstChild).toBe(div);
134
+ expect(div.firstChild).toBe(h1);
135
+ expect(host.querySelectorAll("div").length).toBe(1);
136
+ expect(host.querySelectorAll("h1").length).toBe(1);
137
+
138
+ // Reactivity is now live on the adopted text node.
139
+ n.value = 7;
140
+ expect(serverText.data).toBe("7");
141
+ // Still the same node identity after the update (no replacement).
142
+ expect(h1.childNodes[2]).toBe(serverText);
143
+ });
144
+ });