@opentf/afw 0.0.0-stage → 0.33.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.
- package/LICENSE +21 -0
- package/README.md +123 -2
- package/components/Link.d.ts +12 -0
- package/components/Link.jsx +54 -0
- package/core/context.d.ts +7 -0
- package/core/context.js +60 -0
- package/core/dev.js +27 -0
- package/core/errors.d.ts +14 -0
- package/core/errors.js +48 -0
- package/core/html.js +10 -0
- package/core/metadata.js +186 -0
- package/core/reactive.d.ts +5 -0
- package/core/reactive.js +190 -0
- package/core/render-context.js +11 -0
- package/core/signals.d.ts +8 -0
- package/core/signals.js +264 -0
- package/index.d.ts +5 -0
- package/index.js +13 -0
- package/jsx-runtime.d.ts +37 -0
- package/package.json +66 -4
- package/runtime/clipboard.d.ts +7 -0
- package/runtime/clipboard.js +47 -0
- package/runtime/code-block.d.ts +14 -0
- package/runtime/code-block.js +76 -0
- package/runtime/context.browser.js +163 -0
- package/runtime/context.d.ts +13 -0
- package/runtime/context.js +44 -0
- package/runtime/dom.browser.js +423 -0
- package/runtime/dom.d.ts +142 -0
- package/runtime/dom.js +670 -0
- package/runtime/error-boundary.browser.js +140 -0
- package/runtime/error-boundary.d.ts +19 -0
- package/runtime/error-boundary.js +123 -0
- package/runtime/events.browser.js +29 -0
- package/runtime/events.d.ts +1 -0
- package/runtime/events.js +17 -0
- package/runtime/head.js +29 -0
- package/runtime/hmr.js +199 -0
- package/runtime/hydrate.browser.js +144 -0
- package/runtime/hydrate.d.ts +179 -0
- package/runtime/hydrate.js +584 -0
- package/runtime/index.d.ts +14 -0
- package/runtime/index.js +24 -0
- package/runtime/lifecycle.d.ts +6 -0
- package/runtime/lifecycle.js +14 -0
- package/runtime/mount.d.ts +20 -0
- package/runtime/mount.js +88 -0
- package/runtime/portal.browser.js +85 -0
- package/runtime/portal.d.ts +12 -0
- package/runtime/portal.js +74 -0
- package/runtime/raw-html.d.ts +11 -0
- package/runtime/raw-html.js +55 -0
- package/runtime/resource.d.ts +9 -0
- package/runtime/resource.js +139 -0
- package/runtime/route-data.d.ts +15 -0
- package/runtime/route-data.js +64 -0
- package/runtime/router.d.ts +149 -0
- package/runtime/router.js +807 -0
- package/server/adapters/node.d.ts +28 -0
- package/server/adapters/node.js +74 -0
- package/server/api.d.ts +175 -0
- package/server/api.js +233 -0
- package/server/builtins.js +42 -0
- package/server/cookies.d.ts +44 -0
- package/server/cookies.js +122 -0
- package/server/head.js +9 -0
- package/server/index.d.ts +155 -0
- package/server/index.js +31 -0
- package/server/loader.js +201 -0
- package/server/middleware.js +119 -0
- package/server/render-context.js +30 -0
- package/server/render.js +175 -0
- package/server/ssg-runtime.js +297 -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
|
+
}
|
package/runtime/head.js
ADDED
|
@@ -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,199 @@
|
|
|
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
|
+
/**
|
|
23
|
+
* `exports` is the source of the page's exports other than its view and the route data the
|
|
24
|
+
* router re-reads (see the compiler's `hot_exports_shape`). Importers hold the old values,
|
|
25
|
+
* so a change there reloads; an edit to the view, its metadata or its headings refreshes.
|
|
26
|
+
*/
|
|
27
|
+
export function registerHotRoute(hot, factory, shape = "", exports = "", data = {}) {
|
|
28
|
+
if (!hot) return factory;
|
|
29
|
+
if (hot.data.afwRouteBoundary && hot.data.afwExports !== exports) {
|
|
30
|
+
hot.data.afwExports = exports;
|
|
31
|
+
hot.invalidate();
|
|
32
|
+
return factory;
|
|
33
|
+
}
|
|
34
|
+
hot.data.afwExports = exports;
|
|
35
|
+
hot.data.afwRouteBoundary = true;
|
|
36
|
+
const record = hot.keep("afw-route", () => {
|
|
37
|
+
const entry = { factory, shape };
|
|
38
|
+
// `previous` is the view node this build replaces during a refresh. Its state
|
|
39
|
+
// slots carry over when the declarations still match; otherwise state is fresh.
|
|
40
|
+
entry.view = (props, previous) => {
|
|
41
|
+
const kept = previous?.__afwHotSlots;
|
|
42
|
+
const slots = kept && kept.shape === entry.shape ? kept.slots : new Map();
|
|
43
|
+
let failed = false, failure;
|
|
44
|
+
const outer = routeSlots;
|
|
45
|
+
routeSlots = slots;
|
|
46
|
+
let built;
|
|
47
|
+
try {
|
|
48
|
+
built = scope(() => {
|
|
49
|
+
try { return entry.factory(props); }
|
|
50
|
+
catch (error) { failed = true; failure = error; }
|
|
51
|
+
});
|
|
52
|
+
} finally {
|
|
53
|
+
routeSlots = outer;
|
|
54
|
+
}
|
|
55
|
+
if (failed) {
|
|
56
|
+
try { built.dispose(); } catch (error) { console.error(error); }
|
|
57
|
+
throw failure;
|
|
58
|
+
}
|
|
59
|
+
const node = built.result;
|
|
60
|
+
const lifecycle = node.__lifecycle ??= { mounts: [], cleanups: [] };
|
|
61
|
+
lifecycle.cleanups.push(built.dispose);
|
|
62
|
+
node.__afwHotFactory = entry.view;
|
|
63
|
+
node.__afwHotSlots = { shape: entry.shape, slots };
|
|
64
|
+
return node;
|
|
65
|
+
};
|
|
66
|
+
return entry;
|
|
67
|
+
});
|
|
68
|
+
const updated = record.factory !== factory || record.shape !== shape;
|
|
69
|
+
record.factory = factory;
|
|
70
|
+
record.shape = shape;
|
|
71
|
+
// `data`: this update's `metadata`/`generateMetadata`/`toc`, which the router's import of
|
|
72
|
+
// the route (the original module) would not see.
|
|
73
|
+
record.data = data;
|
|
74
|
+
hot.accept();
|
|
75
|
+
if (updated) queueMicrotask(() => {
|
|
76
|
+
if (!hot.data.afwInvalidated) void refreshHotRoute(record.view, record.data);
|
|
77
|
+
});
|
|
78
|
+
return record.view;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export function hotState(host, key, create) {
|
|
82
|
+
const slots = host._hotState ??= new Map();
|
|
83
|
+
if (!slots.has(key)) slots.set(key, create());
|
|
84
|
+
return slots.get(key);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function cleanup(host) {
|
|
88
|
+
const disposers = host._cleanups || [];
|
|
89
|
+
host._cleanups = [];
|
|
90
|
+
for (const dispose of disposers) {
|
|
91
|
+
try { dispose(); } catch (error) { console.error(error); }
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function refresh(record, hosts) {
|
|
96
|
+
for (const host of hosts) {
|
|
97
|
+
if (!host.isConnected) continue;
|
|
98
|
+
const scroll = [window.scrollX, window.scrollY];
|
|
99
|
+
const focused = document.activeElement;
|
|
100
|
+
const focusId = host.contains(focused) ? focused.id : null;
|
|
101
|
+
const selection = focusId && typeof focused.selectionStart === "number"
|
|
102
|
+
? [focused.selectionStart, focused.selectionEnd] : null;
|
|
103
|
+
cleanup(host);
|
|
104
|
+
host._mounted = false;
|
|
105
|
+
host._hotRefreshing = true;
|
|
106
|
+
// Slotted children belong to the parent. Keep the original capture and move
|
|
107
|
+
// those nodes into the new view in the same task (no genuine disconnect).
|
|
108
|
+
host.replaceChildren(...(host._hotChildren || []));
|
|
109
|
+
try { record.connected?.call(host); }
|
|
110
|
+
finally { host._hotRefreshing = false; }
|
|
111
|
+
if (focusId) {
|
|
112
|
+
const target = document.getElementById(focusId);
|
|
113
|
+
if (target && host.contains(target)) {
|
|
114
|
+
target.focus({ preventScroll: true });
|
|
115
|
+
if (selection && typeof target.setSelectionRange === "function") {
|
|
116
|
+
try { target.setSelectionRange(...selection); } catch {}
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
window.scrollTo(...scroll);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* `exports` is the source of the module's exports other than its components: importers
|
|
126
|
+
* hold the old values, so a change there reloads, while an edit to the components alone
|
|
127
|
+
* refreshes them in place. Each entry's shape covers what a refresh can't carry over
|
|
128
|
+
* (props, state declarations, the exposed method names).
|
|
129
|
+
*/
|
|
130
|
+
/**
|
|
131
|
+
* `$expose` in a development build: publish `api` on the host like `Object.assign`, after
|
|
132
|
+
* removing whatever the previous version of the component exposed there. A refresh
|
|
133
|
+
* re-runs the component on the same host, so a renamed or removed method would otherwise
|
|
134
|
+
* linger beside its replacement.
|
|
135
|
+
*/
|
|
136
|
+
export function hotExpose(host, api) {
|
|
137
|
+
for (const key of host.__afwExposed ?? []) if (!(key in api)) delete host[key];
|
|
138
|
+
Object.assign(host, api);
|
|
139
|
+
host.__afwExposed = Object.keys(api);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
export function registerHotModule(hot, entries, accept = true, exports = "") {
|
|
143
|
+
const signature = entries.map(([component, shape]) => [component.tag, shape]);
|
|
144
|
+
const previous = hot?.data.afwSignature;
|
|
145
|
+
if (previous && (JSON.stringify(previous) !== JSON.stringify(signature) || hot.data.afwExports !== exports)) {
|
|
146
|
+
hot.data.afwInvalidated = true;
|
|
147
|
+
hot.invalidate();
|
|
148
|
+
return;
|
|
149
|
+
}
|
|
150
|
+
if (hot) {
|
|
151
|
+
hot.data.afwSignature = signature;
|
|
152
|
+
hot.data.afwExports = exports;
|
|
153
|
+
hot.data.afwInvalidated = false;
|
|
154
|
+
}
|
|
155
|
+
const changed = [];
|
|
156
|
+
for (const [component] of entries) {
|
|
157
|
+
const tag = component.tag;
|
|
158
|
+
let record = components.get(tag);
|
|
159
|
+
const prototype = component.prototype;
|
|
160
|
+
const connected = prototype.connectedCallback;
|
|
161
|
+
const disconnected = prototype.disconnectedCallback;
|
|
162
|
+
const attributeChanged = prototype.attributeChangedCallback;
|
|
163
|
+
if (record) {
|
|
164
|
+
Object.assign(record, { connected, disconnected, attributeChanged });
|
|
165
|
+
changed.push(record);
|
|
166
|
+
continue;
|
|
167
|
+
}
|
|
168
|
+
// A tag registered outside this refresh runtime cannot safely be replaced.
|
|
169
|
+
if (customElements.get(tag)) {
|
|
170
|
+
if (hot) hot.data.afwInvalidated = true;
|
|
171
|
+
hot?.invalidate();
|
|
172
|
+
continue;
|
|
173
|
+
}
|
|
174
|
+
record = { connected, disconnected, attributeChanged, instances: new Set() };
|
|
175
|
+
components.set(tag, record);
|
|
176
|
+
prototype.connectedCallback = function () {
|
|
177
|
+
record.instances.add(this);
|
|
178
|
+
return record.connected?.call(this);
|
|
179
|
+
};
|
|
180
|
+
prototype.disconnectedCallback = function () {
|
|
181
|
+
record.instances.delete(this);
|
|
182
|
+
return record.disconnected?.call(this);
|
|
183
|
+
};
|
|
184
|
+
if (attributeChanged) prototype.attributeChangedCallback = function (...args) {
|
|
185
|
+
return record.attributeChanged.call(this, ...args);
|
|
186
|
+
};
|
|
187
|
+
customElements.define(tag, component);
|
|
188
|
+
}
|
|
189
|
+
// Install all implementations first. Refresh existing ancestors before their
|
|
190
|
+
// descendants, so children recreated by a parent don't mount twice per update.
|
|
191
|
+
const jobs = changed.flatMap(record => [...record.instances].map(host => {
|
|
192
|
+
let depth = 0;
|
|
193
|
+
for (let parent = host.parentElement; parent; parent = parent.parentElement) depth++;
|
|
194
|
+
return { record, host, depth };
|
|
195
|
+
}));
|
|
196
|
+
jobs.sort((a, b) => a.depth - b.depth);
|
|
197
|
+
for (const { record, host } of jobs) refresh(record, [host]);
|
|
198
|
+
if (accept) hot?.accept();
|
|
199
|
+
}
|