@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,172 @@
1
+ //! Server render for SSG (ARCHITECTURE.md §6) — composes a route's HTML by
2
+ //! calling the SSG render functions the compiler emits (page/layout factories
3
+ //! that return strings, components registered in the SSG registry). No DOM: this
4
+ //! runs in plain Bun/Node at build time.
5
+ //
6
+ // The route table (registerRoutes/matchRoute/layoutChain) is shared with the
7
+ // client router; here we resolve a route's page + layout chain to string
8
+ // renderers and concatenate them, passing `children` as an HTML string.
9
+
10
+ import {
11
+ layoutChain,
12
+ matchRoute,
13
+ resolveModule,
14
+ routes,
15
+ setRouteState,
16
+ } from "../runtime/router.js";
17
+ import { resolveMetadata } from "./head.js";
18
+ import { beginHydrationCollect, endHydrationCollect } from "./ssg-runtime.js";
19
+ import { withRenderContext } from "./render-context.js";
20
+
21
+ /**
22
+ * Render `pathname` to `{ html, metadata, status, hydration }`: the markup for inside
23
+ * `#app`, the resolved SEO metadata (for the `<head>`), an HTTP `status` (200 when the
24
+ * path matched a real route, 404 when it fell back to the registered 404 page — the SSR
25
+ * server uses it; SSG ignores it), and `hydration` — the JSON island-props payload the
26
+ * toolchain embeds so the client resumes from rich data (`""` when nothing needs it).
27
+ * `params` (from `getStaticPaths`) override the matched route's params for dynamic
28
+ * routes. `options.data` is the route's loader result (run by the caller — serve /
29
+ * prerender own the loader bundle) and is exposed to the page as `router.data`.
30
+ * Returns `null` if there's no match and no 404 page.
31
+ */
32
+ export async function renderRoute(pathname, params = null, search = "", { data } = {}) {
33
+ return withRenderContext({ route: {}, hydration: null }, () =>
34
+ renderInContext(pathname, params, search, data));
35
+ }
36
+
37
+ async function renderInContext(pathname, params, search, data) {
38
+ const real = matchRoute(pathname);
39
+ const match =
40
+ real || (routes.notFound ? { entry: routes.notFound, params: {}, route: null } : null);
41
+ if (!match) return null;
42
+ if (params) match.params = params;
43
+
44
+ // Let a page reading `router.params`/`pathname`/`query`/`data` resolve to this route.
45
+ setRouteState({ pathname, search, params: match.params, data });
46
+
47
+ const query = Object.fromEntries(new URLSearchParams(search));
48
+ const props = { params: match.params, query };
49
+
50
+ // Import modules before collecting: module-level JSX must keep its inline
51
+ // props rather than capture hydration ids belonging to just the first request.
52
+ const chain = layoutChain(match.route);
53
+ const [pageModule, ...layoutModules] = await Promise.all(
54
+ [match.entry, ...chain].map(async entry => {
55
+ const module = await resolveModule(entry);
56
+ // A loader can return a bare factory. Keep it distinguishable from a
57
+ // loader when these resolved entries are passed to metadata resolution.
58
+ return typeof module === "function" ? { default: module } : module;
59
+ }),
60
+ );
61
+ const page = pageModule?.default ?? pageModule;
62
+ const layouts = layoutModules.map(module => module?.default ?? module);
63
+
64
+ // Each context owns its hydration ids, including when another render is nested.
65
+ let html, hydration;
66
+ beginHydrationCollect();
67
+ try {
68
+ html = page(props);
69
+ // Wrap with layouts, most-specific inward to root outermost.
70
+ for (let i = layouts.length - 1; i >= 0; i--) {
71
+ html = layouts[i]({ ...props, children: html });
72
+ }
73
+ } finally {
74
+ hydration = endHydrationCollect();
75
+ }
76
+
77
+ const metadata = await resolveMetadata({
78
+ route: match.route,
79
+ entry: pageModule,
80
+ layouts: layoutModules,
81
+ params: match.params,
82
+ query,
83
+ });
84
+ // `route` is the matched *pattern* ("/docs/[slug]", null for the 404 fallback) — the
85
+ // toolchain keys its per-route chunk manifest by it to emit `<link rel="modulepreload">`.
86
+ return { html, metadata, status: real ? 200 : 404, hydration, route: match.route };
87
+ }
88
+
89
+ /** Back-compat / convenience: render just the `#app` markup for `pathname`. */
90
+ export async function renderToString(pathname, search = "") {
91
+ const result = await renderRoute(pathname, null, search);
92
+ return result ? result.html : null;
93
+ }
94
+
95
+ /** Validate a generated URL segment before encoding it for the route. */
96
+ function encodedSegment(value, route, key) {
97
+ if ((typeof value !== "string" && typeof value !== "number") ||
98
+ (typeof value === "number" && !Number.isFinite(value))) {
99
+ throw new Error(`getStaticPaths for ${route}: parameter "${key}" must be a string or finite number.`);
100
+ }
101
+ const text = String(value);
102
+ if (!text || text === "." || text === ".." || /[\\/\x00-\x1f\x7f]/.test(text)) {
103
+ throw new Error(`getStaticPaths for ${route}: invalid segment for "${key}". Use an array for catch-all segments.`);
104
+ }
105
+ try { return encodeURIComponent(text); }
106
+ catch { throw new Error(`getStaticPaths for ${route}: invalid Unicode in "${key}".`); }
107
+ }
108
+
109
+ function fillRoute(route, params) {
110
+ if (!params || typeof params !== "object" || Array.isArray(params)) {
111
+ throw new Error(`getStaticPaths for ${route}: params must be an object.`);
112
+ }
113
+ return route.replace(/\[(\.\.\.)?([^\]]+)\]/g, (_, rest, key) => {
114
+ if (!Object.prototype.hasOwnProperty.call(params, key)) {
115
+ throw new Error(`getStaticPaths for ${route}: missing parameter "${key}".`);
116
+ }
117
+ const value = params[key];
118
+ if (rest) {
119
+ const segments = Array.isArray(value) ? value : [value];
120
+ if (!segments.length) throw new Error(`getStaticPaths for ${route}: catch-all "${key}" must not be empty.`);
121
+ return segments.map(segment => encodedSegment(segment, route, key)).join("/");
122
+ }
123
+ return encodedSegment(value, route, key);
124
+ });
125
+ }
126
+
127
+ /**
128
+ * Enumerate the concrete paths to pre-render as `{ path, params, route }`. Static routes
129
+ * are taken as-is (`params: {}`); dynamic routes (`[param]`) are expanded via the
130
+ * page module's optional `getStaticPaths()` (returning `[{ params }]`), carrying the
131
+ * params forward so the renderer/`generateMetadata` see them. `route` is the pattern the
132
+ * concrete path came from, so the caller can look the path up in pattern-keyed build data
133
+ * (the chunk manifest behind `<link rel="modulepreload">`). Dynamic routes without
134
+ * `getStaticPaths` are collected as `skipped`.
135
+ */
136
+ export async function collectRoutePaths() {
137
+ const paths = [];
138
+ const skipped = [];
139
+ const seen = new Map();
140
+ function add(path, params, route) {
141
+ const key = new URL(path, "https://afw.invalid").pathname.replace(/\/+$/, "") || "/";
142
+ if (seen.has(key)) throw new Error(`Duplicate static path "${path}" from ${route}; already generated by ${seen.get(key)}.`);
143
+ seen.set(key, route);
144
+ paths.push({ path, params, route });
145
+ }
146
+ for (const route in routes.pages) {
147
+ if (!route.includes("[")) {
148
+ add(route, {}, route);
149
+ continue;
150
+ }
151
+ const ns = await resolveModule(routes.pages[route]);
152
+ const getStaticPaths =
153
+ ns && (ns.getStaticPaths || (ns.default && ns.default.getStaticPaths));
154
+ if (typeof getStaticPaths === "function") {
155
+ const entries = await getStaticPaths();
156
+ if (!Array.isArray(entries)) throw new Error(`getStaticPaths for ${route} must return an array.`);
157
+ for (const entry of entries) {
158
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
159
+ throw new Error(`getStaticPaths for ${route}: each entry must be a params object or { params }.`);
160
+ }
161
+ if (Object.prototype.hasOwnProperty.call(entry, "props")) {
162
+ throw new Error(`getStaticPaths for ${route}: props are unsupported. Use a route loader and router.data for page data.`);
163
+ }
164
+ const params = Object.prototype.hasOwnProperty.call(entry, "params") ? entry.params : entry;
165
+ add(fillRoute(route, params), params, route);
166
+ }
167
+ } else {
168
+ skipped.push(route);
169
+ }
170
+ }
171
+ return { paths, skipped };
172
+ }
@@ -0,0 +1,239 @@
1
+ //! SSG runtime helpers — the string-building primitives the SSG codegen emits
2
+ //! (ARCHITECTURE.md §6). No DOM: these run in plain Bun/Node at build time and
3
+ //! return HTML strings. Component output is composed via a tag→renderer registry,
4
+ //! mirroring how CSR composes by Custom Element tag.
5
+
6
+ import { escapeAttr, escapeHtml } from "../core/html.js";
7
+ export { escapeAttr, escapeHtml } from "../core/html.js";
8
+
9
+ import { getRenderContext } from "../core/render-context.js";
10
+
11
+ const VOID = new Set([
12
+ "area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta",
13
+ "param", "source", "track", "wbr",
14
+ ]);
15
+
16
+ const UNITLESS = new Set([
17
+ "opacity", "zIndex", "fontWeight", "lineHeight", "flex", "flexGrow", "flexShrink",
18
+ "order", "zoom", "tabSize", "columnCount", "fillOpacity", "strokeOpacity",
19
+ ]);
20
+
21
+ const registry = {};
22
+
23
+ /**
24
+ * Register a component's SSG renderer under its Custom Element tag. Returns the
25
+ * renderer so a caller can attach the optional `hostClass` / `hostAttrs` hooks.
26
+ */
27
+ export function defineSSG(tag, render) {
28
+ registry[tag] = render;
29
+ return render;
30
+ }
31
+
32
+ // ── hydration props collector (compiler-driven data hydration) ────────────────
33
+ // The lossy path is passing rich props through string attributes. Instead, each
34
+ // server-rendered island gets a `data-h` id and its JSON-safe props are recorded into a
35
+ // single payload the shell embeds as `<script type="application/json">`. At upgrade the
36
+ // client component initializes its prop *signals* from those real JS values (objects,
37
+ // arrays, numbers) — not from `getAttribute` — so islands resume with correct data, with
38
+ // no flash and no dependence on a parent walk re-applying props. `renderRoute` brackets a
39
+ // render with `beginHydrationCollect()` / `endHydrationCollect()`.
40
+ let _collect = null;
41
+
42
+ function hydrationCollector() {
43
+ const context = getRenderContext();
44
+ return context ? context.hydration : _collect;
45
+ }
46
+
47
+ function setHydrationCollector(value) {
48
+ const context = getRenderContext();
49
+ if (context) context.hydration = value;
50
+ else _collect = value;
51
+ }
52
+
53
+ /** Start collecting per-island hydration props for one render. */
54
+ export function beginHydrationCollect() {
55
+ setHydrationCollector([]);
56
+ }
57
+
58
+ /**
59
+ * Finish collecting and return the payload as a JSON string ("" when nothing needs
60
+ * hydration). `<` is escaped so a prop value can never break out of the surrounding
61
+ * `<script>` (a `</script>` / `<!--` injection).
62
+ */
63
+ export function endHydrationCollect() {
64
+ const data = hydrationCollector();
65
+ setHydrationCollector(null);
66
+ if (!data || data.length === 0) return "";
67
+ return JSON.stringify(data).replace(/</g, "\\u003c");
68
+ }
69
+
70
+ /**
71
+ * Record an island's JSON-safe props, returning its hydration id — or `null` when not
72
+ * collecting, or when nothing serializes. A JSON round-trip drops functions (event
73
+ * callbacks are client-only — applied by the parent walk, invisible so no flash),
74
+ * `undefined`, and anything cyclic/DOM/signal-shaped, so only plain data crosses.
75
+ */
76
+ function collectHydrationProps(props) {
77
+ const collector = hydrationCollector();
78
+ if (!collector) return null;
79
+ const safe = jsonSafeProps(props);
80
+ if (!safe) return null;
81
+ const id = collector.length;
82
+ collector.push(safe);
83
+ return id;
84
+ }
85
+
86
+ /** A component's props with everything the payload can't carry dropped, or `null` when
87
+ * nothing is left to send. A JSON round-trip drops functions, `undefined`, and anything
88
+ * cyclic/DOM/signal-shaped. */
89
+ function jsonSafeProps(props) {
90
+ if (props == null || typeof props !== "object") return null;
91
+ let safe;
92
+ try {
93
+ safe = JSON.parse(JSON.stringify(props));
94
+ } catch {
95
+ return null; // cyclic / non-serializable → client falls back to attributes/defaults
96
+ }
97
+ if (!safe || typeof safe !== "object" || Object.keys(safe).length === 0) return null;
98
+ return safe;
99
+ }
100
+
101
+ /**
102
+ * An island's props as an inline `data-hp` attribute — the fallback for one rendered
103
+ * *outside* a route render.
104
+ *
105
+ * A JSX value held in module-level data (`export const tabs = [{ content: <CodeBlock/> }]`,
106
+ * the MDX idiom) is rendered when the module is imported, before any `beginHydrationCollect`
107
+ * bracket, so there is no payload to record its props in and no `data-h` id to key them by.
108
+ * The markup is then spliced into whatever page reads it (see `ssgText`) and re-parsed on
109
+ * the client, where the island would upgrade with no props at all and blank its own
110
+ * content. Carrying the props on the host keeps that markup self-contained: it hydrates
111
+ * correctly wherever it ends up, at the cost of a few bytes on those hosts only.
112
+ */
113
+ function inlineHydrationProps(props) {
114
+ const safe = jsonSafeProps(props);
115
+ if (!safe) return "";
116
+ return JSON.stringify(safe).replace(/[&"<]/g, (c) => (c === "&" ? "&amp;" : c === '"' ? "&quot;" : "&lt;"));
117
+ }
118
+
119
+ /** clsx-style class normalization (mirrors runtime/dom.js). */
120
+ export function clsx(value) {
121
+ if (!value) return "";
122
+ if (typeof value === "string") return value;
123
+ if (typeof value === "number") return String(value);
124
+ if (Array.isArray(value)) {
125
+ const parts = [];
126
+ for (const v of value) {
127
+ const s = clsx(v);
128
+ if (s) parts.push(s);
129
+ }
130
+ return parts.join(" ");
131
+ }
132
+ if (typeof value === "object") {
133
+ const parts = [];
134
+ for (const k in value) if (value[k]) parts.push(k);
135
+ return parts.join(" ");
136
+ }
137
+ return "";
138
+ }
139
+
140
+ /** Serialize a style value (string passthrough, or object → `prop:val;`). */
141
+ export function styleString(value) {
142
+ if (!value) return "";
143
+ if (typeof value === "string") return value;
144
+ let s = "";
145
+ for (const k in value) {
146
+ const v = value[k];
147
+ if (v == null) continue;
148
+ const prop = k.startsWith("--") ? k : k.replace(/[A-Z]/g, (m) => "-" + m.toLowerCase());
149
+ const val = typeof v === "number" && !UNITLESS.has(k) ? `${v}px` : v;
150
+ s += `${prop}:${val};`;
151
+ }
152
+ return s;
153
+ }
154
+
155
+ /** Render one attribute: ` name="value"`, ` name` (true), or "" (null/false). */
156
+ export function attr(name, value) {
157
+ if (name === "class") value = clsx(value);
158
+ else if (name === "style") value = styleString(value);
159
+ if (value == null || value === false) return "";
160
+ if (value === true) return ` ${name}`;
161
+ return ` ${name}="${escapeAttr(String(value))}"`;
162
+ }
163
+
164
+ /**
165
+ * A dynamic hole's value → HTML: trusted `{__html}` raw, else escaped text. An
166
+ * array (`{[<a/>, <b/>]}` or `{[1, 2, 3]}`) renders each item concatenated with no
167
+ * separator — mirroring CSR's `toNodes`/`bindText`, where an array value inserts one
168
+ * node per item. Without this an array would stringify to `[object Object]` (JSX) or
169
+ * a comma-joined string, diverging from the hydrated client render.
170
+ */
171
+ export function ssgText(v) {
172
+ if (v == null || v === false || v === true) return "";
173
+ if (Array.isArray(v)) return v.map(ssgText).join("");
174
+ if (typeof v === "object" && v.__html != null) return v.__html;
175
+ return escapeHtml(String(v));
176
+ }
177
+
178
+ /**
179
+ * A dynamic hole inside a **raw text** element (`<script>`, `<style>`): written verbatim.
180
+ *
181
+ * The tokenizer does not parse markup — or character references — in there, so escaping
182
+ * would be served literally (`a &gt; b` in a stylesheet is the entity, not `>`), and the
183
+ * CSR path, which puts the value in the element's text node, doesn't escape either. The
184
+ * one sequence that must not survive is the element's own closing tag: `</script` inside
185
+ * the value would end the element early and spill the rest into the document. It is
186
+ * written as `<\/script`, which the tokenizer no longer recognizes as an end tag and
187
+ * which JavaScript reads back identically inside the string literal such a sequence
188
+ * almost always sits in. `<textarea>`/`<title>` are *escapable* raw text — they resolve
189
+ * character references — so their holes go through `ssgText` instead.
190
+ */
191
+ export function ssgRawText(v) {
192
+ if (v == null || v === false || v === true) return "";
193
+ if (Array.isArray(v)) return v.map(ssgRawText).join("");
194
+ return String(v).replace(/<\/(script|style|textarea|title|xmp|iframe|noembed|noframes)/gi, "<\\/$1");
195
+ }
196
+
197
+ /** Render an array.map list to concatenated HTML. */
198
+ export function ssgList(arr, fn) {
199
+ return (Array.isArray(arr) ? arr : []).map(fn).join("");
200
+ }
201
+
202
+ /**
203
+ * Render a child component `<tag>inner</tag>` via the registry. Props are passed to
204
+ * the renderer (which decides where they land — declared props become properties /
205
+ * forward into the view), so the host tag carries no reflected attributes — exactly
206
+ * as CSR composes a component (props go through `setProp`, declared ones as
207
+ * properties, not host attributes). Avoids duplicating e.g. `class` on both the
208
+ * host and the element the component renders.
209
+ */
210
+ export function ssgComponent(tag, props, children) {
211
+ const render = registry[tag];
212
+ let inner;
213
+ try {
214
+ inner = render ? render(props || {}, children ?? "") : (children ?? "");
215
+ } catch {
216
+ inner = ""; // fail soft (client renders/handles it)
217
+ }
218
+ // Stamp the stable styling hook on the host (mirrors CSR's `classList.add`) so
219
+ // tag-hashed components are still styleable by a readable class name, plus the
220
+ // hydration id (`data-h`) keying this island's rich props in the payload (if any).
221
+ const cls = render && render.hostClass;
222
+ const id = collectHydrationProps(props);
223
+ let attrs = cls ? ` class="${cls}"` : "";
224
+ // A renderer may need an attribute on the *host* to be present in the served HTML,
225
+ // before any script runs — see `afw-internal-context-provider`, whose subtree is
226
+ // resolved by `closest()` at custom-element upgrade time.
227
+ if (render && render.hostAttrs) attrs += render.hostAttrs(props || {}) || "";
228
+ if (id != null) {
229
+ attrs += ` data-h="${id}"`;
230
+ } else {
231
+ // Rendered outside a route render (module-level JSX-as-value): carry the props on
232
+ // the host itself so the markup hydrates wherever it is spliced in.
233
+ const inline = inlineHydrationProps(props);
234
+ if (inline) attrs += ` data-hp="${inline}"`;
235
+ }
236
+ return `<${tag}${attrs}>${inner}</${tag}>`;
237
+ }
238
+
239
+ export { VOID };