@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.
Files changed (73) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +123 -2
  3. package/components/Link.d.ts +12 -0
  4. package/components/Link.jsx +54 -0
  5. package/core/context.d.ts +7 -0
  6. package/core/context.js +60 -0
  7. package/core/dev.js +27 -0
  8. package/core/errors.d.ts +14 -0
  9. package/core/errors.js +48 -0
  10. package/core/html.js +10 -0
  11. package/core/metadata.js +186 -0
  12. package/core/reactive.d.ts +5 -0
  13. package/core/reactive.js +190 -0
  14. package/core/render-context.js +11 -0
  15. package/core/signals.d.ts +8 -0
  16. package/core/signals.js +264 -0
  17. package/index.d.ts +5 -0
  18. package/index.js +13 -0
  19. package/jsx-runtime.d.ts +37 -0
  20. package/package.json +66 -4
  21. package/runtime/clipboard.d.ts +7 -0
  22. package/runtime/clipboard.js +47 -0
  23. package/runtime/code-block.d.ts +14 -0
  24. package/runtime/code-block.js +76 -0
  25. package/runtime/context.browser.js +163 -0
  26. package/runtime/context.d.ts +13 -0
  27. package/runtime/context.js +44 -0
  28. package/runtime/dom.browser.js +423 -0
  29. package/runtime/dom.d.ts +142 -0
  30. package/runtime/dom.js +670 -0
  31. package/runtime/error-boundary.browser.js +140 -0
  32. package/runtime/error-boundary.d.ts +19 -0
  33. package/runtime/error-boundary.js +123 -0
  34. package/runtime/events.browser.js +29 -0
  35. package/runtime/events.d.ts +1 -0
  36. package/runtime/events.js +17 -0
  37. package/runtime/head.js +29 -0
  38. package/runtime/hmr.js +199 -0
  39. package/runtime/hydrate.browser.js +144 -0
  40. package/runtime/hydrate.d.ts +179 -0
  41. package/runtime/hydrate.js +584 -0
  42. package/runtime/index.d.ts +14 -0
  43. package/runtime/index.js +24 -0
  44. package/runtime/lifecycle.d.ts +6 -0
  45. package/runtime/lifecycle.js +14 -0
  46. package/runtime/mount.d.ts +20 -0
  47. package/runtime/mount.js +88 -0
  48. package/runtime/portal.browser.js +85 -0
  49. package/runtime/portal.d.ts +12 -0
  50. package/runtime/portal.js +74 -0
  51. package/runtime/raw-html.d.ts +11 -0
  52. package/runtime/raw-html.js +55 -0
  53. package/runtime/resource.d.ts +9 -0
  54. package/runtime/resource.js +139 -0
  55. package/runtime/route-data.d.ts +15 -0
  56. package/runtime/route-data.js +64 -0
  57. package/runtime/router.d.ts +149 -0
  58. package/runtime/router.js +807 -0
  59. package/server/adapters/node.d.ts +28 -0
  60. package/server/adapters/node.js +74 -0
  61. package/server/api.d.ts +175 -0
  62. package/server/api.js +233 -0
  63. package/server/builtins.js +42 -0
  64. package/server/cookies.d.ts +44 -0
  65. package/server/cookies.js +122 -0
  66. package/server/head.js +9 -0
  67. package/server/index.d.ts +155 -0
  68. package/server/index.js +31 -0
  69. package/server/loader.js +201 -0
  70. package/server/middleware.js +119 -0
  71. package/server/render-context.js +30 -0
  72. package/server/render.js +175 -0
  73. package/server/ssg-runtime.js +297 -0
@@ -0,0 +1,807 @@
1
+ // File-based client router for the AFW runtime.
2
+ //
3
+ // Pages/layouts compile to factory functions (default export) that return a DOM
4
+ // node; `mountApp` registers a route table discovered from the filesystem (by the
5
+ // dev server / build) and renders the matching page into the app root, swapping
6
+ // it on navigation. Route state (pathname/params/query) is exposed reactively via
7
+ // the `router` facade so views can read `router.pathname` etc. inside bindings.
8
+ //
9
+ // Dynamic segments use the `[param]` / `[...rest]` folder convention (SPEC §6).
10
+ //
11
+ // NOTE: passing route params to a page via its `props` argument
12
+ // (`function Page(props) { props.params.id }`) and layout `props.children`
13
+ // composition both require signal-free page props, which the compiler does not
14
+ // emit yet — for now pages read params via the reactive `router.params`, and a
15
+ // route loader's data via the reactive `router.data` (docs/DATA.md).
16
+
17
+ import { clearError, reportError } from "../core/errors.js";
18
+ import { signal } from "../core/signals.js";
19
+ import { getRenderContext } from "../core/render-context.js";
20
+ import { resolveMetadataModules } from "../core/metadata.js";
21
+ import { prepareRouteHead, updateRouteHead } from "./head.js";
22
+ import { beginHydration, cursor, endHydration, renderedForPath } from "./hydrate.js";
23
+ import { buildScopedView, runCleanup, runMount } from "./mount.js";
24
+ import { fetchRouteData, readInlineRouteData } from "./route-data.js";
25
+
26
+ const isBrowser = typeof window !== "undefined";
27
+
28
+ /**
29
+ * Drop a trailing slash (except for the root "/") so `router.pathname` matches the
30
+ * no-trailing-slash route table and nav paths regardless of how the URL was entered —
31
+ * a static host serves `/docs/x/`, a AFW Search result links to `/docs/x/`, etc. Without
32
+ * this, `/docs/x/` wouldn't match the `/docs/x` nav entry and the breadcrumb / active
33
+ * sidebar link / TOC would silently blank out.
34
+ */
35
+ const normalizePath = (p) => (p || "/").replace(/(.)\/+$/, "$1");
36
+
37
+ const state = {
38
+ pathname: signal(isBrowser ? normalizePath(window.location.pathname) : "/"),
39
+ searchParams: signal(new URLSearchParams(isBrowser ? window.location.search : "")),
40
+ params: signal({}),
41
+ locale: signal(null),
42
+ data: signal(undefined),
43
+ toc: signal([]),
44
+ };
45
+
46
+ export const routes = { pages: {}, layouts: {}, notFound: null, loaderRoutes: new Set() };
47
+ let guard = null;
48
+ let rootEl = null;
49
+
50
+ // Navigation mode (docs/HYDRATION.md §7): "spa" (default) lets the client router
51
+ // intercept same-origin `<Link>` clicks for reload-free nav; "mpa" leaves every
52
+ // navigation to the browser (full page load), with each page hydrating its own first
53
+ // paint. MPA is always the substrate — this only toggles the SPA enhancement on top.
54
+ let navMode = "spa";
55
+
56
+ /** Whether the client router should intercept link clicks (SPA) vs. let the browser
57
+ * do a full navigation (MPA). Read by `<Link>`. */
58
+ export function shouldInterceptNav() {
59
+ return navMode === "spa";
60
+ }
61
+
62
+ // i18n: path-prefix locale routing (docs/I18N.md). The route table stays
63
+ // locale-agnostic; a leading non-default locale segment is stripped before
64
+ // matching and recorded as `router.locale`. `prefix_except_default`: the default
65
+ // locale is served at the bare path, others are prefixed (`/fr/about`).
66
+ let i18nConfig = null;
67
+
68
+ /** Register the app's locales (called by `mountApp({ i18n })`). */
69
+ export function configureI18n(cfg) {
70
+ if (!cfg || !Array.isArray(cfg.locales) || cfg.locales.length === 0) {
71
+ i18nConfig = null;
72
+ return;
73
+ }
74
+ const defaultLocale = cfg.defaultLocale ?? cfg.locales[0];
75
+ i18nConfig = {
76
+ locales: cfg.locales,
77
+ defaultLocale,
78
+ nonDefault: new Set(cfg.locales.filter((l) => l !== defaultLocale)),
79
+ };
80
+ state.locale.value = defaultLocale;
81
+ }
82
+
83
+ /** The configured locales + default, or null when i18n isn't enabled. */
84
+ export function i18nLocales() {
85
+ return i18nConfig && { locales: i18nConfig.locales, defaultLocale: i18nConfig.defaultLocale };
86
+ }
87
+
88
+ /**
89
+ * Split a leading non-default locale segment off `pathname`, returning the active
90
+ * `locale` and the locale-agnostic `path` to match against the route table. When
91
+ * i18n is off, or the first segment isn't a configured non-default locale, the
92
+ * path passes through unchanged with the default (or null) locale.
93
+ */
94
+ export function resolveLocale(pathname) {
95
+ const def = i18nConfig ? i18nConfig.defaultLocale : null;
96
+ if (!i18nConfig) return { locale: def, path: pathname };
97
+ const m = (pathname || "/").match(/^\/([^/]+)(\/.*|)$/);
98
+ if (m && i18nConfig.nonDefault.has(m[1])) return { locale: m[1], path: m[2] || "/" };
99
+ return { locale: def, path: pathname };
100
+ }
101
+
102
+ /**
103
+ * Prefix `path` with `locale` (bare for the default locale). Any locale already on
104
+ * `path` is replaced. Used by `<Link>` and programmatic navigation to keep links
105
+ * in the active locale. Pass-through when i18n is off.
106
+ */
107
+ export function localizePath(path, locale = router.locale) {
108
+ if (!i18nConfig) return path;
109
+ // Strip ANY existing locale prefix (default included, unlike `resolveLocale`
110
+ // which keeps the canonical default bare) so a link can be re-pointed cleanly.
111
+ const m = (path || "/").match(/^\/([^/]+)(\/.*|)$/);
112
+ const bare = m && i18nConfig.locales.includes(m[1]) ? m[2] || "/" : path;
113
+ if (!locale || locale === i18nConfig.defaultLocale) return bare;
114
+ return bare === "/" ? `/${locale}` : `/${locale}${bare}`;
115
+ }
116
+
117
+ /**
118
+ * Set the active locale directly, without navigating. The reactive `router.locale`
119
+ * updates and any `t()`/formatter bindings re-render fine-grained. Intended for
120
+ * previews, tests, and programmatic control — in a routed app the locale is derived
121
+ * from the URL prefix (docs/I18N.md §2), so navigation is the normal path.
122
+ */
123
+ export function setLocale(locale) {
124
+ const route = getRenderContext()?.route;
125
+ if (route) {
126
+ route.locale = locale;
127
+ return;
128
+ }
129
+ state.locale.value = locale;
130
+ }
131
+ let currentNodes = [];
132
+
133
+ function routeValue(key) {
134
+ const route = getRenderContext()?.route;
135
+ return route ? route[key] : state[key].value;
136
+ }
137
+
138
+ /** Reactive router facade — getters read signal values (tracked in effects). */
139
+ export const router = {
140
+ get pathname() {
141
+ return routeValue("pathname");
142
+ },
143
+ get searchParams() {
144
+ return routeValue("searchParams");
145
+ },
146
+ get query() {
147
+ return Object.fromEntries(routeValue("searchParams"));
148
+ },
149
+ get params() {
150
+ return routeValue("params");
151
+ },
152
+ get locale() {
153
+ return routeValue("locale");
154
+ },
155
+ get data() {
156
+ return routeValue("data");
157
+ },
158
+ /** The current page's headings (`export const toc`, emitted for MDX), or `[]`. */
159
+ get toc() {
160
+ return routeValue("toc");
161
+ },
162
+ push: (path) => navigate(path),
163
+ replace: (path) => navigate(path, true),
164
+ };
165
+
166
+ /** Derive the route ("/counter", "/") from a `.../app/<route>/page.jsx` path. The
167
+ * lookahead pins `/app` to a complete path segment, so a route folder that merely
168
+ * starts with "app" (`/appointments`) isn't clipped. */
169
+ function routeFromPath(filePath) {
170
+ const r = filePath
171
+ .replace(/^.*\/app(?=\/)/, "")
172
+ .replace(/\/(page|layout|404)\.(jsx|tsx|mdx|md)$/, "");
173
+ return r === "" ? "/" : r;
174
+ }
175
+
176
+ /**
177
+ * Register routes from a `{ path: entry }` map. Each `entry` is either a module
178
+ * namespace (eager) or a `() => import(...)` loader (lazy, code-split) — both
179
+ * resolve to a default-export factory at navigation time. `layout.jsx` files
180
+ * register as layouts (wrapping nested pages), `404.jsx` as the fallback.
181
+ */
182
+ export function registerRoutes(modules) {
183
+ // Validate before changing the table: an unsupported fallback otherwise
184
+ // falls through as a page and resolves to "/", overwriting the homepage.
185
+ for (const file in modules) {
186
+ if (/\/404\.(mdx|md)$/.test(file)) {
187
+ throw new Error(`Unsupported Markdown 404 route: ${file}. Use 404.jsx or 404.tsx instead.`);
188
+ }
189
+ }
190
+ for (const file in modules) {
191
+ const entry = modules[file];
192
+ if (/\/404\.(jsx|tsx)$/.test(file)) routes.notFound = entry;
193
+ else if (/\/layout\.(jsx|tsx)$/.test(file)) routes.layouts[routeFromPath(file)] = entry;
194
+ else routes.pages[routeFromPath(file)] = entry;
195
+ }
196
+ }
197
+
198
+ /**
199
+ * Register which route *patterns* (`"/todos"`, `"/items/[id]"`) have a server
200
+ * loader (docs/DATA.md) — the toolchain discovers `loader.{js,ts}` files and
201
+ * passes the list via `mountApp({ loaders })`. `navigate` only fetches
202
+ * `<path>/__data.json` for routes in this set; `matchRoute` returns the same
203
+ * pattern string, so membership is a plain Set lookup.
204
+ */
205
+ export function registerLoaderRoutes(paths) {
206
+ routes.loaderRoutes = new Set(paths || []);
207
+ }
208
+
209
+ /** Set the reactive `router.data` directly (server render and tests). */
210
+ export function setRouteData(data) {
211
+ state.data.value = data;
212
+ }
213
+
214
+ /** Layout entries that wrap `route`, outermost (root) first. */
215
+ export function layoutChain(route) {
216
+ const chain = [];
217
+ // The 404 fallback has no route pattern of its own, but it still belongs to the
218
+ // app shell. Apply the root layout when one is registered so 404 pages inherit
219
+ // the same navigation, footer, and other site-wide UI as regular pages.
220
+ if (!route) return routes.layouts["/"] ? [routes.layouts["/"]] : chain;
221
+ let p = route;
222
+ while (true) {
223
+ if (routes.layouts[p]) chain.unshift(routes.layouts[p]);
224
+ if (p === "/") break;
225
+ p = p.slice(0, p.lastIndexOf("/")) || "/";
226
+ }
227
+ return chain;
228
+ }
229
+
230
+ /** Resolve a route entry (module namespace or lazy loader) to its factory. */
231
+ export async function resolveFactory(entry) {
232
+ const mod = await resolveModule(entry);
233
+ return mod && mod.default ? mod.default : mod;
234
+ }
235
+
236
+ /**
237
+ * Resolve every route entry *in parallel* and return them in order.
238
+ *
239
+ * A route's page and its whole layout chain are separate code-split chunks, and all
240
+ * of them are known before the first `import()` starts — so resolving them one after
241
+ * another would stack their network latencies (a page under two layouts pays 3× the
242
+ * round trip instead of 1×). Starting every `import()` in the same tick lets the
243
+ * browser fetch them concurrently.
244
+ *
245
+ * `Promise.allSettled` rather than `Promise.all`: `all` rejects on the first failure
246
+ * while the other imports are still in flight, so a second failure (a redeploy 404s
247
+ * *every* stale chunk, not just one) would surface as an unhandled rejection. Settle
248
+ * first, then rethrow the earliest failure — `navigate` still sees the same chunk-load
249
+ * error it needs for stale-chunk recovery.
250
+ */
251
+ async function resolveAll(entries, resolve) {
252
+ const settled = await Promise.allSettled(entries.map((e) => resolve(e)));
253
+ const failed = settled.find((r) => r.status === "rejected");
254
+ if (failed) throw failed.reason;
255
+ return settled.map((r) => r.value);
256
+ }
257
+
258
+ /**
259
+ * Build the DOM node for a matched route: the page factory wrapped by its layout
260
+ * chain (most-specific inward, root outermost). Returns the outermost `node` plus
261
+ * the ordered `nodes` list (page → … → root) so callers can run lifecycle on each.
262
+ * Each factory owns a reactive scope, disposed with its node on navigation.
263
+ */
264
+ export async function buildRouteNode(match, query = {}) {
265
+ const props = { params: match.params, query };
266
+ const chain = layoutChain(match.route);
267
+ const [pageModule, ...layoutModules] = await resolveAll(
268
+ [match.entry, ...chain],
269
+ resolveModule,
270
+ );
271
+ const namespace = module => typeof module === "function" ? { default: module } : module;
272
+ const modules = [...layoutModules, pageModule].map(namespace);
273
+ const pageFactory = pageModule?.default ?? pageModule;
274
+ const layoutFactories = layoutModules.map(module => module?.default ?? module);
275
+ setRouteToc(pageModule);
276
+ let node = buildScopedView(() => pageFactory(props));
277
+ const nodes = [node];
278
+ try {
279
+ for (let i = chain.length - 1; i >= 0; i--) {
280
+ node = buildScopedView(() => layoutFactories[i]({ ...props, children: node }));
281
+ nodes.push(node);
282
+ }
283
+ } catch (error) {
284
+ for (const n of nodes) runCleanup(n);
285
+ throw error;
286
+ }
287
+ return { node, nodes, modules };
288
+ }
289
+
290
+ /**
291
+ * Adopt a matched route's server-rendered DOM (docs/HYDRATION.md §3.4, 2.1c) — the hydrate
292
+ * analogue of {@link buildRouteNode}. One cursor threads the whole layout chain: the
293
+ * outermost layout adopts at the container, and each layout hands that cursor to the next at
294
+ * its `{children}` slot (`props.children` is a thunk that claims the nested route's subtree
295
+ * and advances the cursor), down to the page. Returns `{ nodes }` (page → … → root) for
296
+ * lifecycle, or `null` if the page or any layout isn't adoptable (no `hydrateAt` export) — the
297
+ * caller then falls back to a clean CSR build. A thrown `HydrationMismatch` propagates up,
298
+ * disposing each layer's partial wiring on the way (each `hydrateAt` has its own guard).
299
+ */
300
+ export async function hydrateRouteNode(match, query, rootEl) {
301
+ const props = { params: match.params, query };
302
+ const chain = layoutChain(match.route);
303
+ // Page + layout chunks download concurrently (see `resolveAll`). Adoptability is
304
+ // checked after they all land rather than short-circuiting on the page: bailing
305
+ // early would only skip imports the CSR fallback below is about to need anyway.
306
+ const [pageMod, ...layoutMods] = await resolveAll([match.entry, ...chain], resolveModule);
307
+ setRouteToc(pageMod);
308
+ if (!pageMod || typeof pageMod.hydrateAt !== "function") return null;
309
+ // The whole chain must be adoptable — one non-adoptable layout means a clean CSR build.
310
+ if (layoutMods.some((m) => !m || typeof m.hydrateAt !== "function")) return null;
311
+
312
+ // Compose the adopt thunks innermost-first: the page, then each layout wrapping it. Each
313
+ // thunk pushes its claimed root node, so `nodes` ends up page → … → outermost (the inner
314
+ // thunk runs — and pushes — during the outer layout's walk, before the outer pushes).
315
+ const nodes = [];
316
+ let thunk = (c) => {
317
+ const n = buildScopedView(() => pageMod.hydrateAt(c, props));
318
+ nodes.push(n);
319
+ return n;
320
+ };
321
+ for (let i = chain.length - 1; i >= 0; i--) {
322
+ const layout = layoutMods[i];
323
+ const inner = thunk;
324
+ thunk = (c) => {
325
+ const n = buildScopedView(() => layout.hydrateAt(c, { ...props, children: inner }));
326
+ nodes.push(n);
327
+ return n;
328
+ };
329
+ }
330
+ try {
331
+ thunk(cursor(rootEl)); // outermost adopts at the container; the chain threads inward
332
+ } catch (error) {
333
+ for (const node of nodes) runCleanup(node);
334
+ throw error;
335
+ }
336
+ return { nodes };
337
+ }
338
+
339
+ /** Resolve a route entry (lazy loader or module namespace) to its module. */
340
+ export async function resolveModule(entry) {
341
+ return typeof entry === "function" ? await entry() : entry;
342
+ }
343
+
344
+ /**
345
+ * Set the reactive route state directly (no history/render). Used by server render
346
+ * so a page reading `router.pathname`/`params`/`query` resolves to the route being
347
+ * pre-rendered. The client uses `navigate` instead.
348
+ */
349
+ /**
350
+ * Publish the page module's `toc` export as `router.toc`. Called once the page module is
351
+ * resolved and before any factory runs, so a layout's `<Toc>` renders the same outline on
352
+ * the server, at hydration and after a client navigation.
353
+ */
354
+ export function setRouteToc(pageModule) {
355
+ const toc = Array.isArray(pageModule?.toc) ? pageModule.toc : [];
356
+ const route = getRenderContext()?.route;
357
+ if (route) route.toc = toc;
358
+ else state.toc.value = toc;
359
+ }
360
+
361
+ export function setRouteState({ pathname = "/", search = "", params = {}, locale, data } = {}) {
362
+ const route = getRenderContext()?.route;
363
+ if (route) {
364
+ Object.assign(route, {
365
+ pathname: normalizePath(pathname),
366
+ searchParams: new URLSearchParams(search),
367
+ params,
368
+ locale: locale !== undefined ? locale : resolveLocale(pathname).locale,
369
+ data,
370
+ });
371
+ return;
372
+ }
373
+ state.pathname.value = normalizePath(pathname);
374
+ state.searchParams.value = new URLSearchParams(search);
375
+ state.params.value = params;
376
+ state.locale.value = locale !== undefined ? locale : resolveLocale(pathname).locale;
377
+ // Always assigned (even when the caller passed none) so a loader-less render
378
+ // never shows a previous route's stale data.
379
+ state.data.value = data;
380
+ }
381
+
382
+ /**
383
+ * Match `pathname` against the registered routes, resolving `[param]` segments. A
384
+ * leading non-default locale segment is stripped first (the route table is
385
+ * locale-agnostic; see `resolveLocale`).
386
+ */
387
+ export function matchRoute(pathname) {
388
+ pathname = resolveLocale(pathname).path;
389
+ for (const route in routes.pages) {
390
+ // `[param]` / `[...rest]` become named groups; literal parts are regex-escaped
391
+ // (a `v1.0` folder must not match `v1X0`).
392
+ const pattern = route
393
+ .split(/(\[\.\.\.[^\]]+\]|\[[^\]]+\])/)
394
+ .map((part) => {
395
+ if (part.startsWith("[...")) return `(?<${part.slice(4, -1)}>.+)`;
396
+ if (part.startsWith("[")) return `(?<${part.slice(1, -1)}>[^/]+)`;
397
+ return part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
398
+ })
399
+ .join("");
400
+ const m = pathname.match(new RegExp(`^${pattern}/?$`));
401
+ if (m) {
402
+ const params = { ...(m.groups || {}) };
403
+ for (const k in params) {
404
+ try {
405
+ params[k] = route.includes(`[...${k}]`)
406
+ ? params[k].split("/").map(decodeURIComponent) : decodeURIComponent(params[k]);
407
+ } catch { return null; }
408
+ }
409
+ return { entry: routes.pages[route], params, route };
410
+ }
411
+ }
412
+ return null;
413
+ }
414
+
415
+ // Monotonic navigation sequence: a navigation that awaited its loader-data fetch
416
+ // commits only if no newer navigation started meanwhile (stale data must never
417
+ // win over a later click).
418
+ let navSeq = 0;
419
+
420
+ // --- Stale-chunk recovery ---------------------------------------------------
421
+ // Pages/layouts are code-split, so a route is loaded by a lazy `() => import(...)`
422
+ // at navigation time. Asset filenames are content-hashed (`layout-DmM9YRKj.js`),
423
+ // so a new deploy replaces them: a tab that loaded the OLD `index.html` still holds
424
+ // the old chunk names, and the moment the user navigates to a not-yet-loaded route
425
+ // its `import()` 404s — "Failed to fetch dynamically imported module".
426
+ //
427
+ // Recovery is a single full page load, which fetches the fresh `index.html` (new
428
+ // hashes) and completes the navigation for real. We don't try to distinguish a
429
+ // redeploy from a transient network error first — a HEAD probe of the chunk isn't
430
+ // reliable across hosts (405 / no-HEAD, S3 returning 403 for missing keys, CORS
431
+ // preflight, CDN quirks). The reload is guarded by a one-time, tab-scoped
432
+ // sessionStorage flag that survives the reload, so a genuinely broken deploy (fresh
433
+ // HTML still 404s) reloads once and then surfaces the error instead of looping.
434
+
435
+ /**
436
+ * Whether `e` is a failed dynamic `import()` of a code-split route chunk — the
437
+ * signature of the stale-chunk-after-redeploy problem. The message differs per
438
+ * engine, so match all three:
439
+ * Chrome/Edge: "Failed to fetch dynamically imported module: <url>"
440
+ * Firefox: "error loading dynamically imported module: <url>"
441
+ * Safari: "Importing a module script failed."
442
+ */
443
+ function isChunkLoadError(e) {
444
+ const msg = (e && (e.message || String(e))) || "";
445
+ return /dynamically imported module|Importing a module script failed/i.test(msg);
446
+ }
447
+
448
+ // One-time reload guard. sessionStorage survives `location.reload()` and is scoped to
449
+ // this tab (auto-cleared when it closes), so it's the right place to remember "I've
450
+ // already tried reloading for this." A genuinely broken deploy — fresh HTML that still
451
+ // references a 404ing chunk — therefore reloads exactly once, then surfaces the error
452
+ // instead of looping. `clearChunkReloadFlag` drops it on the next successful render, so
453
+ // a *later* redeploy can recover in turn.
454
+ const CHUNK_RELOAD_FLAG = "afw:chunk-reloaded";
455
+
456
+ /**
457
+ * Hard-reload once to pick up fresh HTML + asset hashes, guarded so it can't loop.
458
+ * Returns `false` when a reload was already attempted (the caller should surface the
459
+ * error instead of reloading again).
460
+ */
461
+ function reloadForFreshAssets() {
462
+ if (!isBrowser) return false;
463
+ try {
464
+ if (window.sessionStorage.getItem(CHUNK_RELOAD_FLAG)) return false; // already tried once
465
+ window.sessionStorage.setItem(CHUNK_RELOAD_FLAG, "1");
466
+ } catch {
467
+ // sessionStorage unavailable — reload unguarded; a normal redeploy still recovers,
468
+ // and the rare broken-deploy loop is the only thing we can't defend against here.
469
+ }
470
+ window.location.reload();
471
+ return true;
472
+ }
473
+
474
+ /** Drop the one-time reload guard once a navigation renders successfully. */
475
+ function clearChunkReloadFlag() {
476
+ if (!isBrowser) return;
477
+ try {
478
+ window.sessionStorage.removeItem(CHUNK_RELOAD_FLAG);
479
+ } catch {
480
+ // ignore
481
+ }
482
+ }
483
+
484
+ /**
485
+ * Navigate to `path`. Runs an optional route guard, fetches the route's loader
486
+ * data when it has any (docs/DATA.md — fetch *then* commit, like the guard),
487
+ * swaps the rendered page (tearing down the previous one's lifecycle), and
488
+ * updates window.history.
489
+ */
490
+ export async function navigate(path, replace = false, isPop = false, hydrate = false) {
491
+ if (!path || !rootEl) return;
492
+ const seq = ++navSeq;
493
+ const url = new URL(path, window.location.origin);
494
+
495
+ if (guard) {
496
+ let redirected = false;
497
+ const to = {
498
+ // `pathname` is the documented, platform-standard field (matches the URL API
499
+ // and `router.pathname`); `path` is kept as a back-compat alias. `fullPath`
500
+ // is the whole relative URL (pathname + query + hash), for guards that need to
501
+ // preserve or inspect the query/hash (e.g. redirect back after login).
502
+ pathname: url.pathname,
503
+ path: url.pathname,
504
+ fullPath: url.pathname + url.search + url.hash,
505
+ params: matchRoute(url.pathname)?.params || {},
506
+ query: Object.fromEntries(url.searchParams),
507
+ };
508
+ await new Promise((resolve) => {
509
+ // A guard redirect on **first paint** leaves hydration: the server DOM in `#app`
510
+ // belongs to the route we're leaving, so the target route has to build fresh. The
511
+ // hydration flag is seeded `true` from the server sentinel at module load, and this
512
+ // path returns before the `hydrate && match` block that clears it in its `finally` —
513
+ // so without this the flag stayed true for the rest of the session. Every island the
514
+ // redirected build creates would then see `isHydrating() && this.firstChild` and take
515
+ // the *adopt* arm against DOM its own parent had just `createElement`'d, mismatching
516
+ // (`expected a region start marker, found <div>`) and rebuilding — and so would every
517
+ // later SPA navigation. Clear it before the target navigation builds anything.
518
+ const leaveHydration = () => {
519
+ if (hydrate) endHydration();
520
+ };
521
+ const tools = {
522
+ next: () => resolve(),
523
+ redirect: (p) => {
524
+ redirected = true;
525
+ leaveHydration();
526
+ navigate(p, true);
527
+ resolve();
528
+ },
529
+ replace: (p) => {
530
+ redirected = true;
531
+ leaveHydration();
532
+ navigate(p, true);
533
+ resolve();
534
+ },
535
+ };
536
+ Promise.resolve(guard(to, tools)).catch(() => resolve());
537
+ });
538
+ if (redirected) return;
539
+ }
540
+
541
+ const match =
542
+ matchRoute(url.pathname) ||
543
+ (routes.notFound ? { entry: routes.notFound, params: {}, route: null } : null);
544
+
545
+ // Loader data (docs/DATA.md): resolved before any state write / history push /
546
+ // DOM swap, mirroring the guard's "settle before commit" flow. First paint over
547
+ // server HTML reads the inlined payload; every other navigation (SPA nav, dev/CSR
548
+ // first load, popstate) fetches the `<path>/__data.json` endpoint. A failed fetch
549
+ // is reported and the navigation commits with `data === undefined`.
550
+ let data;
551
+ if (match && match.route && routes.loaderRoutes.has(match.route)) {
552
+ if (hydrate) {
553
+ data = readInlineRouteData();
554
+ } else {
555
+ try {
556
+ data = await fetchRouteData(url.pathname, url.search);
557
+ } catch (e) {
558
+ reportError(e, { phase: "data", path: url.pathname });
559
+ }
560
+ if (seq !== navSeq) return; // a newer navigation superseded this one
561
+ }
562
+ }
563
+
564
+ state.pathname.value = normalizePath(url.pathname);
565
+ state.searchParams.value = url.searchParams;
566
+ state.params.value = match ? match.params : {};
567
+ state.locale.value = resolveLocale(url.pathname).locale;
568
+ state.data.value = data;
569
+
570
+ if (!isPop) {
571
+ if (replace) window.history.replaceState({}, "", path);
572
+ else window.history.pushState({}, "", path);
573
+ }
574
+
575
+ // First paint over server-rendered DOM: *adopt* it (hydrate) instead of rebuilding,
576
+ // when the route module exposes a `hydrateAt` adopt factory (compiled with the hydrate
577
+ // target). `hydrateRouteNode` threads one cursor through the whole layout chain (2.1c);
578
+ // a route whose page or any layout isn't adoptable returns null → clean CSR build. A
579
+ // hydration mismatch is reported (never silent) and also falls through to a rebuild.
580
+ //
581
+ // The hydration flag must be live *before* the route modules are imported: route chunks
582
+ // are code-split, so `customElements.define` — and the synchronous upgrade of every
583
+ // server-rendered `<web-*>` host — happens during those imports, before the factories
584
+ // run. Those upgrading components read `isHydrating()` to adopt their server DOM rather
585
+ // than build (docs/HYDRATION.md §3.4). `endHydration()` in `finally` makes every
586
+ // subsequent client navigation build fresh; the CSR fallback below then runs with the
587
+ // flag cleared, so a rebuilt host builds instead of trying to re-adopt.
588
+ if (hydrate && match) {
589
+ beginHydration();
590
+ try {
591
+ const query = Object.fromEntries(url.searchParams);
592
+ const adopted = await hydrateRouteNode(match, query, rootEl);
593
+ if (adopted) {
594
+ currentNodes = adopted.nodes;
595
+ for (const n of adopted.nodes) runMount(n); // onMount for page + every layout
596
+ clearError({ phase: "route" });
597
+ clearChunkReloadFlag();
598
+ return;
599
+ }
600
+ } catch (e) {
601
+ reportError(e, { phase: "hydrate", path: url.pathname });
602
+ // fall through to a clean CSR build below
603
+ } finally {
604
+ endHydration();
605
+ }
606
+ }
607
+
608
+ // Resolve (and lazily load) the page + its layout chain before tearing down the
609
+ // current view, so a slow/failed import doesn't leave a blank page.
610
+ let nodes = null;
611
+ let metadata = {};
612
+ if (match) {
613
+ let built;
614
+ try {
615
+ built = await buildRouteNode(match, Object.fromEntries(url.searchParams));
616
+ metadata = await resolveMetadataModules(built.modules, { params: match.params, query: Object.fromEntries(url.searchParams) });
617
+ if (seq !== navSeq) {
618
+ for (const node of built.nodes) runCleanup(node);
619
+ return;
620
+ }
621
+ nodes = built.nodes;
622
+ } catch (e) {
623
+ if (built) for (const node of built.nodes) runCleanup(node);
624
+ if (seq !== navSeq) return;
625
+ // A failed route-chunk import (stale after a redeploy, or the network dropped):
626
+ // try one guarded full reload for fresh HTML + hashes. If we already reloaded once
627
+ // and it still fails, fall through to the error overlay instead of looping.
628
+ if (isChunkLoadError(e) && reloadForFreshAssets()) return;
629
+ reportError(e, { phase: "route", path: url.pathname });
630
+ for (const node of currentNodes) runCleanup(node);
631
+ rootEl.replaceChildren();
632
+ rootEl.innerHTML = `<pre style="color:#f87171;padding:1rem">Failed to load ${url.pathname}\n${e?.message ?? e}</pre>`;
633
+ currentNodes = [];
634
+ return;
635
+ }
636
+ }
637
+
638
+ for (const n of currentNodes) runCleanup(n);
639
+ rootEl.replaceChildren();
640
+ updateRouteHead(metadata, url.pathname);
641
+
642
+ if (nodes) {
643
+ rootEl.appendChild(nodes[nodes.length - 1]); // outermost node
644
+ for (const n of nodes) runMount(n); // run onMount for page + every layout
645
+ currentNodes = nodes;
646
+ clearError({ phase: "route" }); // a good render dismisses a prior error overlay
647
+ clearChunkReloadFlag(); // a successful render means the reload (if any) recovered
648
+ // A forward navigation lands at the top of the new page (or at the targeted
649
+ // anchor); back/forward (`isPop`) keeps the browser's restored scroll position.
650
+ if (!isPop && isBrowser) {
651
+ const anchor = url.hash ? document.getElementById(decodeURIComponent(url.hash.slice(1))) : null;
652
+ if (anchor) anchor.scrollIntoView();
653
+ else window.scrollTo(0, 0);
654
+ }
655
+ if (isBrowser) focusRouteContent(rootEl);
656
+ } else {
657
+ rootEl.innerHTML = "<h1>404 — Not Found</h1>";
658
+ currentNodes = [];
659
+ }
660
+ }
661
+
662
+ // Development factory refresh deliberately bypasses navigation: no guard,
663
+ // loader request, history mutation, route-state change or heading focus jump.
664
+ // Only the edited page or layout is rebuilt. Its `$state` slots carry over when
665
+ // the declarations still match (see `registerHotRoute`), outer layouts keep their
666
+ // nodes and state, and an edited layout receives the existing inner route view as
667
+ // `children`, so the page and its components move into it without remounting.
668
+ // The nodes a route view occupies in the document: the element itself, or the nodes a
669
+ // fragment root held (see `buildScopedView`).
670
+ const viewNodes = (node) => (node?.nodeType === 11 ? node.__afwNodes ?? [] : node ? [node] : []);
671
+
672
+ // A route view to pass on as a layout's `children`: a fragment root is empty once
673
+ // inserted, so it is refilled with the nodes it held.
674
+ function asChildren(node) {
675
+ if (node?.nodeType !== 11) return node;
676
+ const frag = document.createDocumentFragment();
677
+ frag.append(...viewNodes(node));
678
+ return frag;
679
+ }
680
+
681
+ export async function refreshHotRoute(factory, data = null) {
682
+ const index = currentNodes.findIndex(node => node.__afwHotFactory === factory);
683
+ if (!rootEl || index < 0) return;
684
+ const seq = navSeq;
685
+ const previous = currentNodes[index];
686
+ const match = matchRoute(state.pathname.value) ||
687
+ (routes.notFound ? { entry: routes.notFound, route: state.pathname.value, params: {} } : null);
688
+ if (!match) return;
689
+ const query = Object.fromEntries(state.searchParams.value);
690
+ const inner = index > 0 ? currentNodes[index - 1] : null;
691
+ const innerFirst = viewNodes(inner)[0];
692
+ const innerParent = innerFirst?.parentNode;
693
+ const innerNext = viewNodes(inner).at(-1)?.nextSibling;
694
+ let node;
695
+ try {
696
+ const [pageModule, ...layoutModules] = await resolveAll(
697
+ [match.entry, ...layoutChain(match.route)],
698
+ resolveModule,
699
+ );
700
+ if (seq !== navSeq || currentNodes[index] !== previous) return;
701
+ const focusedId = rootEl.contains(document.activeElement) ? document.activeElement.id : null;
702
+ const scroll = [window.scrollX, window.scrollY];
703
+ const props = { params: match.params, query };
704
+ if (inner) props.children = asChildren(inner);
705
+ // `data` is the edited module's route data; the modules imported above are the
706
+ // originals. currentNodes runs page → innermost layout → root, the chain root first.
707
+ const namespace = module => typeof module === "function" ? { default: module } : module;
708
+ const fresh = module => (data ? { ...namespace(module), ...data } : namespace(module));
709
+ const page = index === 0 ? fresh(pageModule) : namespace(pageModule);
710
+ const layouts = layoutModules.map((module, i) => (index === layoutModules.length - i ? fresh(module) : namespace(module)));
711
+ // An edited page may have new headings: publish them before the view rebuilds.
712
+ setRouteToc(page);
713
+ node = buildScopedView(() => factory(props, previous));
714
+ const old = viewNodes(previous);
715
+ if (old.length === 0) throw new Error("the refreshed view has no nodes in the document to replace");
716
+ old[0].parentNode.insertBefore(node, old[0]);
717
+ for (const n of old) n.remove();
718
+ runCleanup(previous);
719
+ currentNodes = currentNodes.map((current, i) => (i === index ? node : current));
720
+ runMount(node);
721
+ const metadata = await resolveMetadataModules([...layouts, page], { params: match.params, query });
722
+ if (seq === navSeq) updateRouteHead(metadata, state.pathname.value);
723
+ if (focusedId) document.getElementById(focusedId)?.focus({ preventScroll: true });
724
+ window.scrollTo(...scroll);
725
+ clearError({ phase: "route" });
726
+ } catch (error) {
727
+ // A failed layout build may already hold the inner view; put it back.
728
+ if (innerParent && innerFirst.parentNode !== innerParent) {
729
+ for (const n of viewNodes(inner)) innerParent.insertBefore(n, innerNext ?? null);
730
+ }
731
+ if (node && !node.isConnected) runCleanup(node);
732
+ reportError(error, { phase: "route", path: state.pathname.value });
733
+ }
734
+ }
735
+
736
+ /** Move keyboard/screen-reader focus into the newly rendered route after SPA nav. */
737
+ function focusRouteContent(container) {
738
+ const target = container.querySelector("h1") || container.querySelector("main");
739
+ if (!target) return;
740
+ // Headings and main landmarks are not normally in the tab order. A programmatic
741
+ // tabindex lets focus land there without adding another Tab stop.
742
+ if (!target.hasAttribute("tabindex")) target.setAttribute("tabindex", "-1");
743
+ try {
744
+ target.focus({ preventScroll: true });
745
+ } catch {
746
+ target.focus();
747
+ }
748
+ }
749
+
750
+ /**
751
+ * Bootstrap the application: register routes, wire history, and render the page
752
+ * for the current URL.
753
+ *
754
+ * @param {Object} opts
755
+ * @param {Object} opts.pages `{ path: module }` route map (from the dev server).
756
+ * @param {Element} [opts.target] the app root (defaults to `#app`).
757
+ * @param {Function} [opts.guard] optional `(to, tools) => …` route guard.
758
+ * @param {"spa"|"mpa"} [opts.nav] navigation mode (default "spa"); "mpa" disables
759
+ * client-side link interception so every navigation is a full page load.
760
+ * @param {string[]} [opts.loaders] route patterns that have a server loader
761
+ * (docs/DATA.md) — navigation fetches `<path>/__data.json` for these.
762
+ */
763
+ export function mountApp({ pages, target, guard: g, i18n, nav, loaders } = {}) {
764
+ rootEl = target || (isBrowser ? document.getElementById("app") : null);
765
+ navMode = nav === "mpa" ? "mpa" : "spa";
766
+ if (i18n) configureI18n(i18n);
767
+ if (pages) registerRoutes(pages);
768
+ if (loaders) registerLoaderRoutes(loaders);
769
+ guard = g || null;
770
+ // In MPA mode the browser owns navigation (full loads push real history entries),
771
+ // so there is no client-side history to react to — only wire popstate for SPA.
772
+ if (isBrowser && navMode === "spa") {
773
+ window.addEventListener("popstate", () =>
774
+ navigate(
775
+ window.location.pathname + window.location.search + window.location.hash,
776
+ false,
777
+ true,
778
+ ),
779
+ );
780
+ }
781
+ // Hydrate the first paint when the server stamped `data-afw-hydrate` on the root,
782
+ // left rendered markup in it, and rendered it for this URL; otherwise this is a
783
+ // plain CSR mount (build into #app), replacing any markup rendered for another path.
784
+ const hydrate = !!(
785
+ isBrowser &&
786
+ rootEl &&
787
+ rootEl.firstChild &&
788
+ renderedForPath(rootEl, window.location.pathname)
789
+ );
790
+ if (isBrowser) prepareRouteHead(hydrate);
791
+ // The flag is seeded `true` from the sentinel at module load (so eagerly-defined
792
+ // framework components adopt on upgrade — see hydrate.js). If this mount is NOT
793
+ // hydrating after all (no sentinel, or an empty root), clear it now so the CSR build
794
+ // below — and every later navigation — builds fresh. The hydrate path clears it itself
795
+ // (via `endHydration` in `navigate`'s `finally`) once first paint is adopted.
796
+ if (!hydrate) endHydration();
797
+ return navigate(
798
+ window.location.pathname + window.location.search + window.location.hash,
799
+ true,
800
+ true,
801
+ hydrate,
802
+ );
803
+ }
804
+
805
+ // `<Link>` is a pure JSX component (packages/afw/components/Link.jsx), compiled by
806
+ // the app's pipeline like any UI component — it lives there, not as a hand-written
807
+ // Custom Element here. It imports `navigate` from this module.