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