@krate/runtime 0.5.0-alpha.3 → 0.5.0-beta.1

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 (76) hide show
  1. package/dist/action-context.d.ts +14 -3
  2. package/dist/action-context.js +70 -4
  3. package/dist/action-context.test.js +26 -1
  4. package/dist/actions.d.ts +12 -1
  5. package/dist/actions.js +101 -5
  6. package/dist/actions.test.js +87 -1
  7. package/dist/cache-scope.d.ts +118 -0
  8. package/dist/cache-scope.js +314 -0
  9. package/dist/cache.d.ts +55 -0
  10. package/dist/cache.js +155 -0
  11. package/dist/cache.test.d.ts +1 -0
  12. package/dist/cache.test.js +233 -0
  13. package/dist/class-helpers.d.ts +4 -4
  14. package/dist/class-helpers.js +357 -32
  15. package/dist/class-helpers.test.d.ts +1 -0
  16. package/dist/class-helpers.test.js +169 -0
  17. package/dist/context.d.ts +16 -2
  18. package/dist/context.js +44 -3
  19. package/dist/dev-overlay.js +75 -2
  20. package/dist/dev-overlay.test.js +22 -0
  21. package/dist/dom.d.ts +7 -0
  22. package/dist/dom.js +69 -3
  23. package/dist/effects.js +74 -3
  24. package/dist/error-overlay.js +4 -4
  25. package/dist/hook-args.d.ts +7 -0
  26. package/dist/hook-args.js +10 -0
  27. package/dist/htmlspec-attributes.d.ts +1 -0
  28. package/dist/htmlspec-attributes.js +159 -0
  29. package/dist/index.d.ts +3 -2
  30. package/dist/index.js +2 -1
  31. package/dist/krate-core.js +2 -0
  32. package/dist/krate-dev.js +65 -2
  33. package/dist/krate-f-actions.js +2 -0
  34. package/dist/krate-f-classes.js +8 -0
  35. package/dist/krate-f-helpers.js +2 -0
  36. package/dist/krate-f-list.js +2 -0
  37. package/dist/krate-f-router-lite.js +2 -0
  38. package/dist/krate-f-router.js +2 -0
  39. package/dist/krate-features.json +239 -0
  40. package/dist/krate-hydrate-lite.js +5 -5
  41. package/dist/krate-hydrate.js +5 -5
  42. package/dist/krate-runtime.js +5 -5
  43. package/dist/patterns.test.d.ts +1 -0
  44. package/dist/patterns.test.js +98 -0
  45. package/dist/portal.d.ts +5 -1
  46. package/dist/portal.js +15 -4
  47. package/dist/reactivity-core.test.d.ts +1 -0
  48. package/dist/reactivity-core.test.js +152 -0
  49. package/dist/reconcile.js +4 -2
  50. package/dist/request-context.d.ts +62 -0
  51. package/dist/request-context.js +107 -0
  52. package/dist/router-layout.test.d.ts +1 -0
  53. package/dist/router-layout.test.js +179 -0
  54. package/dist/router-lite.d.ts +25 -0
  55. package/dist/router-lite.js +73 -0
  56. package/dist/router-nav.test.d.ts +1 -0
  57. package/dist/router-nav.test.js +437 -0
  58. package/dist/router-slots.test.d.ts +1 -0
  59. package/dist/router-slots.test.js +144 -0
  60. package/dist/router-speculation.test.d.ts +1 -0
  61. package/dist/router-speculation.test.js +25 -0
  62. package/dist/router-styles.test.d.ts +1 -0
  63. package/dist/router-styles.test.js +98 -0
  64. package/dist/router.d.ts +66 -2
  65. package/dist/router.js +1617 -648
  66. package/dist/server-async.test.d.ts +1 -0
  67. package/dist/server-async.test.js +194 -0
  68. package/dist/server-renderer.js +556 -132
  69. package/dist/server.d.ts +24 -0
  70. package/dist/server.js +247 -11
  71. package/dist/server.test.js +20 -0
  72. package/dist/signal.d.ts +41 -4
  73. package/dist/signal.js +254 -24
  74. package/dist/slots.d.ts +5 -1
  75. package/dist/slots.js +40 -3
  76. package/package.json +6 -2
package/dist/router.js CHANGED
@@ -1,19 +1,14 @@
1
- let initialized = false;
2
- let pendingAbort;
3
- let routerCleanup = null;
4
- // Monotonic navigation sequence: a slower, superseded fetch must never apply
5
- // its HTML over a newer navigation.
6
- let navSeq = 0;
7
- /** Cache for prefetched page HTML keyed by URL (bounded LRU). */
8
- const prefetchCache = new Map();
9
- const PREFETCH_CACHE_MAX = 30;
10
- /** Saved scroll positions for back/forward navigation restoration (bounded). */
11
- const scrollPositions = new Map();
12
- const SCROLL_HISTORY_MAX = 50;
1
+ // Krate SPA router.
2
+ //
3
+ // Intercepts clicks on compiled <Link> anchors (a[data-krate-link]) and GET
4
+ // form submissions, fetches the target document, and swaps the app shell in
5
+ // place. All router state lives at module scope so `reinitRouter()` (called
6
+ // by every page's hydration script) only refreshes per-page bindings and never
7
+ // loses the prefetch cache, saved scroll positions or the in-flight navigation.
13
8
  /**
14
9
  * The shared runtime chunk is loaded once and must persist across SPA
15
10
  * navigations. Page-specific hydration scripts, in contrast, must be
16
- * re-executed on every visit (against the freshly reconciled DOM), so they are
11
+ * re-executed on every visit (against the freshly swapped DOM), so they are
17
12
  * removed before loading a new page and re-appended.
18
13
  */
19
14
  const RUNTIME_CHUNK_RE = /\/chunks\/runtime\.[^/]+\.js$/;
@@ -36,8 +31,20 @@ function stripBase(pathname) {
36
31
  }
37
32
  return pathname;
38
33
  }
39
- // Set during initRouter so the exported `navigate()` can drive the SPA router.
40
- let navigateImpl = null;
34
+ /** Compares two pathnames ignoring a trailing slash ("/a/" equals "/a"). */
35
+ function normPath(p) {
36
+ return p.length > 1 && p.endsWith('/') ? p.slice(0, -1) : p;
37
+ }
38
+ function devWarn(msg) {
39
+ if (!runtimeConfig().dev)
40
+ return;
41
+ try {
42
+ console.warn('[krate router] ' + msg);
43
+ }
44
+ catch {
45
+ /* ignore */
46
+ }
47
+ }
41
48
  // Resolve an asset URL against the navigated-to page (not the current one), so
42
49
  // relative srcs like "index.a1b2c3.js" load from the new page's directory.
43
50
  function resolveSrc(src, baseUrl) {
@@ -53,9 +60,6 @@ function resolveSrc(src, baseUrl) {
53
60
  }
54
61
  return new URL(src, base).href;
55
62
  }
56
- /** Bounded set of asset URLs already emitted as `<link rel="prefetch">`. */
57
- const prefetchedAssets = new Set();
58
- const PREFETCHED_ASSETS_MAX = 128;
59
63
  /**
60
64
  * The per-page hydration chunk(s) a prefetched document will need, as absolute
61
65
  * URLs, excluding the shared runtime chunk and anything already loaded. Prefetching
@@ -87,711 +91,1676 @@ export function pageAssetURLs(html, baseUrl, loaded) {
87
91
  .forEach((l) => consider(l.getAttribute('href')));
88
92
  return out;
89
93
  }
90
- /**
91
- * Programmatic SPA navigation. Falls back to a full page load when the router
92
- * has not initialized (e.g. before hydration). Returns false when handled
93
- * client-side, true when a full navigation was triggered.
94
- */
95
- export function navigate(url, opts = {}) {
96
- if (navigateImpl) {
97
- navigateImpl(url, opts);
98
- return false;
94
+ // Router state (module scope, survives reinitRouter).
95
+ let initialized = false;
96
+ let navSeq = 0;
97
+ let pendingAbort;
98
+ let keySeq = 0;
99
+ let currentKey = '';
100
+ /** pathname+search of the document currently rendered in #root. */
101
+ let renderedPath = '';
102
+ let status = 'idle';
103
+ const listeners = new Set();
104
+ /** Prefetched documents (LRU with TTL; an entry is consumed by the navigation that uses it). */
105
+ const prefetchCache = new Map();
106
+ const prefetchInflight = new Map();
107
+ const PREFETCH_CACHE_MAX = 30;
108
+ const DEFAULT_PREFETCH_TTL = 30000;
109
+ /** Saved scroll positions keyed by history entry key (bounded). */
110
+ const scrollPositions = new Map();
111
+ const SCROLL_HISTORY_MAX = 50;
112
+ /** Bounded set of asset URLs already emitted as `<link rel="prefetch">`. */
113
+ const prefetchedAssets = new Set();
114
+ const PREFETCHED_ASSETS_MAX = 128;
115
+ const errorPageCache = new Map();
116
+ let prefetchTimers = new Map();
117
+ let prefetchObserver = null;
118
+ let loadingOverlay = [];
119
+ /** Output prefix of intercepting-route fragments (see the compiler's parallel.go). */
120
+ const INTERCEPT_PREFIX = '_krate/i';
121
+ const TRANSITION_MS = 150;
122
+ const PREFETCH_DELAY = 200;
123
+ function now() {
124
+ return typeof performance !== 'undefined' && performance.now ? performance.now() : Date.now();
125
+ }
126
+ function newKey() {
127
+ keySeq++;
128
+ return Date.now().toString(36) + '-' + keySeq.toString(36);
129
+ }
130
+ function cacheKey(url) {
131
+ try {
132
+ const u = new URL(url, location.href);
133
+ u.hash = '';
134
+ return u.href;
135
+ }
136
+ catch {
137
+ return url;
99
138
  }
100
- if (typeof location !== 'undefined')
101
- location.href = url;
102
- return true;
103
139
  }
104
- export function initRouter() {
105
- if (typeof document === 'undefined')
140
+ function pathOf(url) {
141
+ const u = new URL(url, location.href);
142
+ return normPath(u.pathname) + u.search;
143
+ }
144
+ function hardNavigate(url, replace = false) {
145
+ const hook = globalThis.__krateHardNavigate;
146
+ if (typeof hook === 'function') {
147
+ hook(url, replace);
106
148
  return;
107
- // Fix 4.4: Guard against multiple initRouter calls
108
- if (initialized)
149
+ }
150
+ if (replace)
151
+ location.replace(url);
152
+ else
153
+ location.assign(url);
154
+ }
155
+ function historyEntry(key, state) {
156
+ return { __krate: key, state: state === undefined ? null : state };
157
+ }
158
+ function entryKey(state) {
159
+ if (state && typeof state === 'object' && typeof state.__krate === 'string') {
160
+ return state.__krate;
161
+ }
162
+ return undefined;
163
+ }
164
+ /** The `state` passed to the navigation that created the current history entry. */
165
+ export function getHistoryState() {
166
+ if (typeof history === 'undefined')
167
+ return null;
168
+ const s = history.state;
169
+ if (entryKey(s) !== undefined)
170
+ return s.state;
171
+ return s;
172
+ }
173
+ function snapshot() {
174
+ const u = new URL(location.href);
175
+ return { url: u.href, pathname: stripBase(u.pathname), search: u.search, hash: u.hash, status };
176
+ }
177
+ /** Current router state (pathname without base path, search, hash, status). */
178
+ export function getNavigationState() {
179
+ if (typeof location === 'undefined') {
180
+ return { url: '', pathname: '/', search: '', hash: '', status: 'idle' };
181
+ }
182
+ return snapshot();
183
+ }
184
+ function emit() {
185
+ if (listeners.size === 0)
109
186
  return;
110
- initialized = true;
111
- // Reconcile from the app root so navigation between DIFFERENT shells (the
112
- // marketing layout's <main> and the docs layout's `.docs-page`) swaps the
113
- // whole shell instead of reconciling mismatched tree shapes (which dropped
114
- // the docs navbar/sidebar while still loading its CSS). Within one shell the
115
- // diff preserves unchanged nodes (sidebar/TOC) by key, so docs<->docs stays
116
- // cheap.
117
- const CONTENT_SEL = '#root, main, .docs-content';
118
- const TRANSITION_MS = 150;
119
- const PREFETCH_DELAY = 200;
120
- let notFoundHTML = null;
121
- let errorHTML = null;
122
- let prefetchTimers = new Map();
123
- let prefetchObserver = null;
124
- function findContentRoot(doc) {
125
- for (const sel of CONTENT_SEL.split(', ')) {
126
- const el = doc.querySelector(sel.trim());
127
- if (el)
128
- return el;
129
- }
130
- return doc.body;
131
- }
132
- function isLocalLink(a) {
133
- if (a.hasAttribute('data-krate-external'))
134
- return false;
135
- const href = a.getAttribute('href');
136
- if (!href)
137
- return false;
138
- if (href.startsWith('#') || href.startsWith('javascript:'))
139
- return false;
140
- if (a.origin !== location.origin)
141
- return false;
142
- if (a.target === '_blank')
143
- return false;
144
- return true;
187
+ const s = snapshot();
188
+ for (const fn of Array.from(listeners)) {
189
+ try {
190
+ fn(s);
191
+ }
192
+ catch (err) {
193
+ console.error(err);
194
+ }
145
195
  }
146
- // Above-the-fold/viewport prefetch is deferred to idle time so it never
147
- // competes with first paint; hover/focus keeps the 200ms intent debounce.
148
- function idle(fn) {
149
- const ric = window.requestIdleCallback;
150
- if (typeof ric === 'function')
151
- ric(fn, { timeout: 1000 });
152
- else
153
- setTimeout(fn, 50);
196
+ }
197
+ function setStatus(next) {
198
+ if (status === next)
199
+ return;
200
+ status = next;
201
+ emit();
202
+ }
203
+ /**
204
+ * Subscribes to navigation state changes (URL changes from SPA navigations,
205
+ * back/forward, hash changes, and loading status). Returns an unsubscribe
206
+ * function. The listener is not called immediately; read the current value
207
+ * with getNavigationState().
208
+ */
209
+ export function subscribeNavigation(fn) {
210
+ listeners.add(fn);
211
+ return () => {
212
+ listeners.delete(fn);
213
+ };
214
+ }
215
+ function dispatch(name, detail, cancelable = false) {
216
+ try {
217
+ const ev = new CustomEvent(name, { detail, cancelable });
218
+ window.dispatchEvent(ev);
219
+ return !ev.defaultPrevented;
154
220
  }
155
- // Prefetch only links that opted in and did not opt out (prefetch={false}).
156
- function shouldPrefetch(a) {
157
- const v = a.getAttribute('data-prefetch');
158
- return a.hasAttribute('data-prefetch') && v !== 'false' && v !== '0';
221
+ catch {
222
+ return true;
159
223
  }
160
- function prefetchAsset(url) {
161
- if (prefetchedAssets.has(url) || prefetchedAssets.size >= PREFETCHED_ASSETS_MAX)
162
- return;
163
- prefetchedAssets.add(url);
164
- const link = document.createElement('link');
165
- link.rel = 'prefetch';
166
- link.as = 'script';
167
- link.href = url;
168
- document.head.appendChild(link);
224
+ }
225
+ // Analytics hook: fires once after every successful SPA navigation. A throw
226
+ // inside the hook is ignored.
227
+ function notifyNavigation(url) {
228
+ try {
229
+ const hook = globalThis.__krate_onNavigation;
230
+ if (typeof hook === 'function')
231
+ hook(url);
169
232
  }
170
- function prefetchPage(url) {
171
- if (prefetchCache.has(url))
172
- return;
173
- fetch(url, { headers: { Accept: 'text/html' } })
174
- .then((res) => (res.ok ? res.text() : null))
175
- .then((html) => {
176
- if (!html)
177
- return;
178
- // Bounded LRU: evict the oldest entry when the cache is full.
179
- if (prefetchCache.size >= PREFETCH_CACHE_MAX) {
180
- const oldest = prefetchCache.keys().next().value;
181
- if (oldest !== undefined)
182
- prefetchCache.delete(oldest);
183
- }
184
- prefetchCache.set(url, html);
185
- // Warm the route's hydration chunk(s) too, not just its HTML.
186
- const loaded = new Set();
187
- document.querySelectorAll('script[src]').forEach((s) => loaded.add(s.src));
188
- for (const asset of pageAssetURLs(html, url, loaded))
189
- prefetchAsset(asset);
190
- })
191
- .catch(() => { });
192
- }
193
- function setupPrefetch() {
194
- // Hover/focus prefetching
195
- document.addEventListener('mouseover', prefetchHoverHandler);
196
- document.addEventListener('focusin', prefetchHoverHandler);
197
- // Viewport prefetching via IntersectionObserver
198
- if (typeof IntersectionObserver !== 'undefined') {
199
- prefetchObserver = new IntersectionObserver((entries) => {
200
- for (const entry of entries) {
201
- if (entry.isIntersecting) {
202
- const a = entry.target;
203
- const href = a.getAttribute('href');
204
- if (href && isLocalLink(a) && shouldPrefetch(a)) {
205
- const url = new URL(href, location.origin).href;
206
- idle(() => prefetchPage(url));
207
- }
208
- prefetchObserver.unobserve(entry.target);
209
- }
210
- }
211
- }, { rootMargin: '200px' });
212
- observePrefetchLinks();
213
- }
233
+ catch {
234
+ /* ignore hook failures */
214
235
  }
215
- function observePrefetchLinks() {
216
- if (!prefetchObserver)
217
- return;
218
- document.querySelectorAll('a[data-prefetch]').forEach((a) => {
219
- if (shouldPrefetch(a))
220
- prefetchObserver.observe(a);
221
- });
236
+ }
237
+ function saveScroll(key) {
238
+ if (!key)
239
+ return;
240
+ scrollPositions.delete(key);
241
+ if (scrollPositions.size >= SCROLL_HISTORY_MAX) {
242
+ const oldest = scrollPositions.keys().next().value;
243
+ if (oldest !== undefined)
244
+ scrollPositions.delete(oldest);
222
245
  }
223
- function cleanupPrefetch() {
224
- document.removeEventListener('mouseover', prefetchHoverHandler);
225
- document.removeEventListener('focusin', prefetchHoverHandler);
226
- for (const timer of prefetchTimers.values()) {
227
- clearTimeout(timer);
228
- }
229
- prefetchTimers.clear();
230
- if (prefetchObserver) {
231
- prefetchObserver.disconnect();
232
- prefetchObserver = null;
233
- }
246
+ scrollPositions.set(key, window.scrollY || 0);
247
+ }
248
+ // Prefetch cache
249
+ function prefetchTTL() {
250
+ const ttl = runtimeConfig().prefetchTTL;
251
+ return typeof ttl === 'number' && ttl >= 0 ? ttl : DEFAULT_PREFETCH_TTL;
252
+ }
253
+ function cachePut(key, doc) {
254
+ prefetchCache.delete(key);
255
+ while (prefetchCache.size >= PREFETCH_CACHE_MAX) {
256
+ const oldest = prefetchCache.keys().next().value;
257
+ if (oldest === undefined)
258
+ break;
259
+ prefetchCache.delete(oldest);
234
260
  }
235
- function prefetchHoverHandler(e) {
236
- const a = e.target.closest('a[data-prefetch]');
237
- if (!a || !shouldPrefetch(a) || !isLocalLink(a))
261
+ prefetchCache.set(key, doc);
262
+ }
263
+ /** Removes and returns a fresh cached document (hits are consumed). */
264
+ function cacheTake(key) {
265
+ const doc = prefetchCache.get(key);
266
+ if (!doc)
267
+ return undefined;
268
+ prefetchCache.delete(key);
269
+ if (now() - doc.at > prefetchTTL())
270
+ return undefined;
271
+ return doc;
272
+ }
273
+ /**
274
+ * Drops prefetched documents: one URL, or every entry when called without an
275
+ * argument. Server actions that revalidate data call this through the
276
+ * `krate:revalidate` event.
277
+ */
278
+ export function invalidatePrefetchCache(url) {
279
+ if (url === undefined) {
280
+ prefetchCache.clear();
281
+ return;
282
+ }
283
+ prefetchCache.delete(cacheKey(url));
284
+ }
285
+ function isHTMLType(ct) {
286
+ return /text\/html|application\/xhtml\+xml/i.test(ct);
287
+ }
288
+ function looksLikeHTML(body) {
289
+ return /^\s*(<!doctype html|<html|<head|<body)/i.test(body);
290
+ }
291
+ function prefetchAsset(url) {
292
+ if (prefetchedAssets.has(url) || prefetchedAssets.size >= PREFETCHED_ASSETS_MAX)
293
+ return;
294
+ prefetchedAssets.add(url);
295
+ const link = document.createElement('link');
296
+ link.rel = 'prefetch';
297
+ link.as = 'script';
298
+ link.href = url;
299
+ document.head.appendChild(link);
300
+ }
301
+ function prefetchPage(url) {
302
+ const key = cacheKey(url);
303
+ const cached = prefetchCache.get(key);
304
+ if (cached && now() - cached.at <= prefetchTTL())
305
+ return Promise.resolve();
306
+ const inflight = prefetchInflight.get(key);
307
+ if (inflight)
308
+ return inflight;
309
+ const p = fetch(key, { headers: { Accept: 'text/html' }, credentials: 'same-origin' })
310
+ .then(async (res) => {
311
+ // Only cache successful, same-origin HTML documents.
312
+ if (!res.ok)
238
313
  return;
239
- const href = a.getAttribute('href');
240
- if (!href)
314
+ const ct = res.headers.get('content-type') || '';
315
+ const finalUrl = res.url || key;
316
+ if (new URL(finalUrl, location.href).origin !== location.origin)
241
317
  return;
242
- const url = new URL(href, location.origin).href;
243
- if (prefetchCache.has(url))
318
+ const html = await res.text();
319
+ if (!(isHTMLType(ct) || (ct === '' && looksLikeHTML(html))))
244
320
  return;
245
- // Debounce: start prefetch after a short delay
246
- const existing = prefetchTimers.get(a);
247
- if (existing)
248
- clearTimeout(existing);
249
- const timer = setTimeout(() => {
250
- prefetchTimers.delete(a);
251
- prefetchPage(url);
252
- }, PREFETCH_DELAY);
253
- prefetchTimers.set(a, timer);
254
- }
255
- // Begin the visual transition (fade out + optional loading overlay) while a
256
- // page fetch is in flight, so navigation doesn't feel artificially delayed.
257
- let loadingOverlay = null;
258
- function beginTransition() {
259
- if (supportsViewTransitions())
260
- return; // native View Transition handles it
261
- const oldContent = findContentRoot(document);
262
- const loadingTemplate = document.querySelector('template[data-krate-loading]');
263
- if (loadingTemplate && loadingTemplate.content && oldContent) {
264
- // Non-destructive loading UI: overlay the template without wiping the
265
- // live DOM, so reconciliation still preserves node state.
266
- loadingOverlay = loadingTemplate.content.cloneNode(true);
267
- document.body.appendChild(loadingOverlay);
268
- }
269
- if (oldContent) {
270
- oldContent.style.transition = `opacity ${TRANSITION_MS}ms ease`;
271
- oldContent.style.opacity = '0';
272
- }
273
- }
274
- function endTransition() {
275
- if (supportsViewTransitions())
276
- return; // opacity was never touched
277
- if (loadingOverlay && loadingOverlay.parentNode) {
278
- loadingOverlay.parentNode.removeChild(loadingOverlay);
279
- }
280
- loadingOverlay = null;
281
- const oldContent = findContentRoot(document);
282
- if (oldContent) {
283
- oldContent.style.opacity = '1';
284
- }
285
- }
286
- // Analytics hook: fires once after every successful SPA navigation
287
- // (click, prefetch-cache, back/forward, and error-page replacements all flow
288
- // through swapContent/replacePage). A throw inside the hook is ignored.
289
- function notifyNavigation(url) {
290
- try {
291
- const hook = globalThis.__krate_onNavigation;
292
- if (typeof hook === 'function')
293
- hook(url);
294
- }
295
- catch {
296
- /* ignore hook failures */
297
- }
321
+ cachePut(key, { html, url: finalUrl, status: res.status, at: now() });
322
+ const loaded = new Set();
323
+ document.querySelectorAll('script[src]').forEach((s) => loaded.add(s.src));
324
+ for (const asset of pageAssetURLs(html, finalUrl, loaded))
325
+ prefetchAsset(asset);
326
+ })
327
+ .catch(() => {
328
+ // A failed prefetch is retried by the real navigation, which reports
329
+ // errors through krate:navigate-error.
330
+ })
331
+ .finally(() => {
332
+ prefetchInflight.delete(key);
333
+ });
334
+ prefetchInflight.set(key, p);
335
+ return p;
336
+ }
337
+ // Link helpers
338
+ function isLocalLink(a) {
339
+ if (a.hasAttribute('data-krate-external') || a.hasAttribute('download'))
340
+ return false;
341
+ const href = a.getAttribute('href');
342
+ if (!href || href.startsWith('javascript:'))
343
+ return false;
344
+ let u;
345
+ try {
346
+ u = new URL(href, location.href);
347
+ }
348
+ catch {
349
+ return false;
350
+ }
351
+ if (u.origin !== location.origin)
352
+ return false;
353
+ const target = a.getAttribute('target');
354
+ if (target && target !== '_self')
355
+ return false;
356
+ return true;
357
+ }
358
+ // Prefetch only links that opted in and did not opt out (prefetch={false}).
359
+ function shouldPrefetch(a) {
360
+ const v = a.getAttribute('data-prefetch');
361
+ return a.hasAttribute('data-prefetch') && v !== 'false' && v !== '0';
362
+ }
363
+ // Above-the-fold/viewport prefetch is deferred to idle time so it never
364
+ // competes with first paint; hover/focus keeps the 200ms intent debounce.
365
+ function idle(fn) {
366
+ const ric = window.requestIdleCallback;
367
+ if (typeof ric === 'function')
368
+ ric(fn, { timeout: 1000 });
369
+ else
370
+ setTimeout(fn, 50);
371
+ }
372
+ function prefetchHoverHandler(e) {
373
+ const t = e.target;
374
+ if (!t || typeof t.closest !== 'function')
375
+ return;
376
+ const a = t.closest('a[data-prefetch]');
377
+ if (!a || !shouldPrefetch(a) || !isLocalLink(a))
378
+ return;
379
+ const href = a.getAttribute('href');
380
+ if (!href)
381
+ return;
382
+ const url = new URL(href, location.href).href;
383
+ if (pathOf(url) === renderedPath)
384
+ return;
385
+ const existing = prefetchTimers.get(a);
386
+ if (existing)
387
+ clearTimeout(existing);
388
+ const timer = setTimeout(() => {
389
+ prefetchTimers.delete(a);
390
+ void prefetchPage(url);
391
+ }, PREFETCH_DELAY);
392
+ prefetchTimers.set(a, timer);
393
+ }
394
+ function observePrefetchLinks() {
395
+ if (!prefetchObserver)
396
+ return;
397
+ document.querySelectorAll('a[data-prefetch]').forEach((a) => {
398
+ if (shouldPrefetch(a))
399
+ prefetchObserver.observe(a);
400
+ });
401
+ }
402
+ function setupPrefetch() {
403
+ document.addEventListener('mouseover', prefetchHoverHandler);
404
+ document.addEventListener('focusin', prefetchHoverHandler);
405
+ if (typeof IntersectionObserver !== 'undefined') {
406
+ prefetchObserver = new IntersectionObserver((entries) => {
407
+ for (const entry of entries) {
408
+ if (!entry.isIntersecting)
409
+ continue;
410
+ const a = entry.target;
411
+ const href = a.getAttribute('href');
412
+ if (href && isLocalLink(a) && shouldPrefetch(a)) {
413
+ const url = new URL(href, location.href).href;
414
+ if (pathOf(url) !== renderedPath)
415
+ idle(() => void prefetchPage(url));
416
+ }
417
+ prefetchObserver.unobserve(entry.target);
418
+ }
419
+ }, { rootMargin: '200px' });
420
+ observePrefetchLinks();
298
421
  }
299
- function dispatchNavEvent(name, url) {
422
+ }
423
+ /**
424
+ * Inject Speculation Rules so the browser prefetches same-origin links ahead
425
+ * of hover, where supported. Falls back to the JS prefetch path elsewhere.
426
+ */
427
+ function setupSpeculationRules() {
428
+ const supports = typeof HTMLScriptElement !== 'undefined' ? HTMLScriptElement.supports : undefined;
429
+ if (typeof supports !== 'function' || !supports('speculationrules'))
430
+ return;
431
+ // An inline speculation-rules script needs a CSP hash or keyword that is not
432
+ // honoured next to script hashes, so under a CSP meta the JS prefetch path
433
+ // is used instead of emitting a blocked script.
434
+ if (document.querySelector('meta[http-equiv="Content-Security-Policy" i]'))
435
+ return;
436
+ try {
437
+ const script = document.createElement('script');
438
+ script.type = 'speculationrules';
439
+ script.textContent = JSON.stringify({
440
+ prefetch: [
441
+ {
442
+ where: {
443
+ and: [
444
+ { href_matches: '/*' },
445
+ { not: { href_matches: '/__krate/*' } },
446
+ { not: { href_matches: '/api/*' } },
447
+ ],
448
+ },
449
+ eagerness: 'moderate',
450
+ },
451
+ ],
452
+ });
453
+ document.head.appendChild(script);
454
+ }
455
+ catch {
456
+ /* ignore */
457
+ }
458
+ }
459
+ // Visual transition
460
+ /** Whether the user asked the OS/browser for reduced motion. */
461
+ function prefersReducedMotion() {
462
+ if (typeof window !== 'undefined' && window.matchMedia) {
300
463
  try {
301
- window.dispatchEvent(new CustomEvent(name, { detail: { url } }));
464
+ return window.matchMedia('(prefers-reduced-motion: reduce)').matches;
302
465
  }
303
466
  catch {
304
467
  /* ignore */
305
468
  }
306
469
  }
307
- /** Whether native View Transitions should wrap the SPA mutation. */
308
- function supportsViewTransitions() {
309
- if (runtimeConfig().viewTransitions === false)
310
- return false;
311
- if (typeof window !== 'undefined' && window.matchMedia) {
312
- try {
313
- if (window.matchMedia('(prefers-reduced-motion: reduce)').matches)
314
- return false;
470
+ return false;
471
+ }
472
+ /** Whether native View Transitions should wrap the SPA mutation. */
473
+ function supportsViewTransitions() {
474
+ if (runtimeConfig().viewTransitions === false)
475
+ return false;
476
+ if (prefersReducedMotion())
477
+ return false;
478
+ return typeof document.startViewTransition === 'function';
479
+ }
480
+ function appRoot(doc) {
481
+ return (doc.getElementById('root') || doc.body);
482
+ }
483
+ // While a fetch is in flight: overlay the loading.tsx template (if the page
484
+ // has one) and, without View Transitions, fade the content out.
485
+ function beginTransition() {
486
+ const tpl = document.querySelector('template[data-krate-loading]');
487
+ if (tpl && tpl.content && loadingOverlay.length === 0) {
488
+ // Non-destructive loading UI: overlay the template without wiping the
489
+ // live DOM, so the swap still sees the old tree.
490
+ const frag = tpl.content.cloneNode(true);
491
+ loadingOverlay = Array.from(frag.childNodes);
492
+ document.body.appendChild(frag);
493
+ }
494
+ // Reduced motion: no fade at all (the overlay above is static).
495
+ if (!supportsViewTransitions() && !prefersReducedMotion()) {
496
+ const el = appRoot(document);
497
+ el.style.transition = `opacity ${TRANSITION_MS}ms ease`;
498
+ el.style.opacity = '0';
499
+ }
500
+ }
501
+ function endTransition() {
502
+ for (const n of loadingOverlay) {
503
+ if (n.parentNode)
504
+ n.parentNode.removeChild(n);
505
+ }
506
+ loadingOverlay = [];
507
+ const el = appRoot(document);
508
+ if (el.style.opacity === '0')
509
+ el.style.opacity = '';
510
+ }
511
+ /**
512
+ * Apply `data-view-transition="name"` to `view-transition-name`. Persistent
513
+ * chrome (navbar/sidebar) keeps its name across mutations so it morphs
514
+ * instead of cross-fading.
515
+ */
516
+ function applyViewTransitionNames(root) {
517
+ root.querySelectorAll('[data-view-transition]').forEach((el) => {
518
+ const name = el.getAttribute('data-view-transition');
519
+ if (name)
520
+ el.style.viewTransitionName = name;
521
+ });
522
+ }
523
+ // Document reconciliation
524
+ /** How long a navigation waits for new stylesheets before swapping anyway. */
525
+ const STYLESHEET_TIMEOUT_MS = 3000;
526
+ /**
527
+ * Diff stylesheet <link>s by absolute URL (base-path and format safe). New
528
+ * links are inserted at the position they have in the incoming document (before
529
+ * the next kept link), so the cascade order matches a hard load. They load with
530
+ * media="not all" so they do not affect the outgoing page; stale links stay
531
+ * until commit() so the old page keeps its styles while the new ones load.
532
+ */
533
+ function prepareStylesheets(doc, baseUrl) {
534
+ const incoming = [];
535
+ doc.querySelectorAll('link[rel="stylesheet"]').forEach((s) => {
536
+ const href = s.getAttribute('href');
537
+ if (!href)
538
+ return;
539
+ const abs = new URL(href, baseUrl).href;
540
+ if (!incoming.includes(abs))
541
+ incoming.push(abs);
542
+ });
543
+ const live = new Map();
544
+ const stale = [];
545
+ document.querySelectorAll('link[rel="stylesheet"]').forEach((l) => {
546
+ const el = l;
547
+ if (!el.href)
548
+ return;
549
+ if (incoming.includes(el.href) && !live.has(el.href))
550
+ live.set(el.href, el);
551
+ else
552
+ stale.push(el);
553
+ });
554
+ const added = [];
555
+ const pending = [];
556
+ let prev = null;
557
+ incoming.forEach((abs, i) => {
558
+ let el = live.get(abs) || null;
559
+ if (!el) {
560
+ const link = document.createElement('link');
561
+ link.rel = 'stylesheet';
562
+ link.href = abs;
563
+ // Listen before insertion so a synchronous settle is not missed.
564
+ pending.push(new Promise((resolve) => {
565
+ const done = () => {
566
+ link.removeEventListener('load', done);
567
+ link.removeEventListener('error', done);
568
+ resolve();
569
+ };
570
+ link.addEventListener('load', done);
571
+ link.addEventListener('error', done);
572
+ }));
573
+ added.push({ link, media: link.getAttribute('media') });
574
+ link.media = 'not all';
575
+ if (prev) {
576
+ prev.after(link);
315
577
  }
316
- catch {
317
- /* ignore */
578
+ else {
579
+ const nextKept = incoming.slice(i + 1).map((h) => live.get(h)).find((l) => !!l);
580
+ if (nextKept)
581
+ nextKept.before(link);
582
+ else
583
+ document.head.appendChild(link);
318
584
  }
585
+ el = link;
319
586
  }
320
- return typeof document.startViewTransition === 'function';
321
- }
322
- /** Diff stylesheet <link>s by absolute URL (base-path and format safe). */
323
- function reconcileStylesheets(doc) {
324
- const newStyles = doc.querySelectorAll('link[rel="stylesheet"]');
325
- const newHrefs = new Set();
326
- newStyles.forEach((s) => {
327
- const href = s.getAttribute('href');
328
- if (href)
329
- newHrefs.add(new URL(href, location.origin).href);
330
- });
331
- document.querySelectorAll('link[rel="stylesheet"]').forEach((l) => {
332
- const abs = l.href;
333
- if (abs && !newHrefs.has(abs))
334
- l.remove();
587
+ prev = el;
588
+ });
589
+ let ready = Promise.resolve();
590
+ if (pending.length > 0) {
591
+ let timer;
592
+ const timeout = new Promise((resolve) => {
593
+ timer = setTimeout(resolve, STYLESHEET_TIMEOUT_MS);
335
594
  });
336
- const existing = new Set();
337
- document.querySelectorAll('link[rel="stylesheet"]').forEach((l) => existing.add(l.href));
338
- newStyles.forEach((s) => {
339
- const href = s.getAttribute('href');
340
- if (!href)
341
- return;
342
- const abs = new URL(href, location.origin).href;
343
- if (!existing.has(abs)) {
344
- const link = document.createElement('link');
345
- link.rel = 'stylesheet';
346
- link.href = abs;
347
- document.head.appendChild(link);
595
+ ready = Promise.race([Promise.all(pending).then(() => undefined), timeout]).then(() => clearTimeout(timer));
596
+ }
597
+ return {
598
+ ready,
599
+ commit() {
600
+ for (const { link, media } of added) {
601
+ if (media === null)
602
+ link.removeAttribute('media');
603
+ else
604
+ link.setAttribute('media', media);
348
605
  }
349
- });
606
+ stale.forEach((l) => l.remove());
607
+ },
608
+ abort() {
609
+ added.forEach(({ link }) => link.remove());
610
+ },
611
+ };
612
+ }
613
+ // Document-level <head> tags that change per page and must follow a swap.
614
+ const HEAD_SYNC_SEL = 'meta[name="description"], meta[name="robots"], meta[property^="og:"], meta[name^="twitter:"], link[rel="canonical"], script[type="application/ld+json"]';
615
+ function reconcileHeadMeta(doc) {
616
+ document.head.querySelectorAll(HEAD_SYNC_SEL).forEach((el) => el.remove());
617
+ doc.head.querySelectorAll(HEAD_SYNC_SEL).forEach((el) => {
618
+ document.head.appendChild(document.importNode(el, true));
619
+ });
620
+ }
621
+ function scriptsToLoad(doc, baseUrl) {
622
+ const keep = new Set();
623
+ document.querySelectorAll('script[src]:not([data-krate-spa])').forEach((s) => keep.add(s.src));
624
+ const out = [];
625
+ const seen = new Set();
626
+ doc.querySelectorAll('script[src]').forEach((s) => {
627
+ const src = s.getAttribute('src');
628
+ if (!src)
629
+ return;
630
+ const t = (s.getAttribute('type') || '').toLowerCase();
631
+ if (t && t !== 'module' && t !== 'text/javascript' && t !== 'application/javascript')
632
+ return;
633
+ const abs = resolveSrc(src, baseUrl);
634
+ if (!keep.has(abs) && !seen.has(abs)) {
635
+ seen.add(abs);
636
+ out.push({ src: abs, module: t === 'module' });
637
+ }
638
+ });
639
+ return out;
640
+ }
641
+ function loadScript(script) {
642
+ return new Promise((resolve) => {
643
+ const s = document.createElement('script');
644
+ s.src = script.src;
645
+ if (script.module)
646
+ s.type = 'module';
647
+ // Only page scripts are disposable across navigations; the shared runtime
648
+ // chunk stays in place.
649
+ if (!RUNTIME_CHUNK_RE.test(script.src))
650
+ s.setAttribute('data-krate-spa', '');
651
+ s.onload = () => resolve(true);
652
+ s.onerror = () => resolve(false);
653
+ document.body.appendChild(s);
654
+ });
655
+ }
656
+ // Scroll, focus, announcements
657
+ function hashTarget(hash) {
658
+ if (!hash || hash === '#')
659
+ return null;
660
+ let id = hash.slice(1);
661
+ try {
662
+ id = decodeURIComponent(id);
350
663
  }
351
- /**
352
- * Apply `data-view-transition="name"` to `view-transition-name`. Persistent
353
- * chrome (navbar/sidebar) keeps its name across mutations so it morphs
354
- * instead of cross-fading. Runs at init and after every swap.
355
- */
356
- function applyViewTransitionNames(root) {
357
- root.querySelectorAll('[data-view-transition]').forEach((el) => {
358
- const name = el.getAttribute('data-view-transition');
359
- if (name)
360
- el.style.viewTransitionName = name;
361
- });
664
+ catch {
665
+ /* keep raw */
666
+ }
667
+ return document.getElementById(id) || document.getElementsByName(id)[0] || null;
668
+ }
669
+ function scrollToHash(hash) {
670
+ const el = hashTarget(hash);
671
+ if (!el)
672
+ return false;
673
+ try {
674
+ el.scrollIntoView({ block: 'start' });
362
675
  }
363
- /** Move focus to the content root after navigation (a11y). */
364
- function focusContent() {
365
- const root = findContentRoot(document);
366
- if (!root)
676
+ catch {
677
+ /* ignore */
678
+ }
679
+ return true;
680
+ }
681
+ function applyScroll(url, req) {
682
+ if (req.kind === 'pop') {
683
+ const saved = req.restoreKey ? scrollPositions.get(req.restoreKey) : undefined;
684
+ if (saved !== undefined) {
685
+ window.scrollTo(0, saved);
367
686
  return;
368
- if (!root.hasAttribute('tabindex'))
369
- root.setAttribute('tabindex', '-1');
370
- try {
371
- root.focus({ preventScroll: true });
372
687
  }
373
- catch {
374
- try {
375
- root.focus();
376
- }
377
- catch {
378
- /* ignore */
688
+ }
689
+ const hash = new URL(url, location.href).hash;
690
+ if (scrollToHash(hash))
691
+ return;
692
+ if (req.scroll && req.kind !== 'refresh')
693
+ window.scrollTo(0, 0);
694
+ }
695
+ let focusedRoot = null;
696
+ /** Move focus to the content root after navigation (a11y). */
697
+ function focusContent() {
698
+ const active = document.activeElement;
699
+ // Focus inside a persisted region (e.g. a search box in a layout) stays put.
700
+ if (active && active !== document.body && active.isConnected && active !== focusedRoot)
701
+ return;
702
+ const root = appRoot(document);
703
+ if (!root.hasAttribute('tabindex')) {
704
+ root.setAttribute('tabindex', '-1');
705
+ focusedRoot = root;
706
+ root.addEventListener('blur', () => {
707
+ if (focusedRoot === root) {
708
+ root.removeAttribute('tabindex');
709
+ focusedRoot = null;
379
710
  }
380
- }
711
+ }, { once: true });
381
712
  }
382
- /**
383
- * Inject Speculation Rules so the browser prefetches same-origin links ahead
384
- * of hover, where supported. Falls back to the JS prefetch path elsewhere.
385
- */
386
- function setupSpeculationRules() {
387
- const supports = HTMLScriptElement.supports;
388
- if (typeof supports !== 'function' || !supports('speculationrules'))
389
- return;
713
+ try {
714
+ root.focus({ preventScroll: true });
715
+ }
716
+ catch {
717
+ /* ignore */
718
+ }
719
+ }
720
+ const ANNOUNCER_ID = '__krate-route-announcer';
721
+ function announce() {
722
+ let el = document.getElementById(ANNOUNCER_ID);
723
+ if (!el) {
724
+ el = document.createElement('div');
725
+ el.id = ANNOUNCER_ID;
726
+ el.setAttribute('aria-live', 'assertive');
727
+ el.setAttribute('aria-atomic', 'true');
728
+ el.setAttribute('role', 'status');
729
+ el.setAttribute('style', 'position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0');
730
+ document.body.appendChild(el);
731
+ }
732
+ const h1 = appRoot(document).querySelector('h1');
733
+ const text = document.title || (h1 && h1.textContent ? h1.textContent.trim() : '') || stripBase(location.pathname);
734
+ el.textContent = text;
735
+ }
736
+ /**
737
+ * Marks links matching the current route. An exact match gets
738
+ * aria-current="page" and data-krate-active="exact"; a link to an ancestor
739
+ * segment ("/docs" while on "/docs/intro", but never "/docs-old") gets
740
+ * data-krate-active="segment" so navigation sections can be styled.
741
+ */
742
+ function updateActiveLinks() {
743
+ const path = normPath(stripBase(location.pathname));
744
+ document.querySelectorAll('a[data-krate-link]').forEach((a) => {
745
+ const href = a.getAttribute('href');
746
+ let target = '';
390
747
  try {
391
- const script = document.createElement('script');
392
- script.type = 'speculationrules';
393
- script.textContent = JSON.stringify({
394
- prefetch: [
395
- {
396
- where: {
397
- and: [
398
- { href_matches: '/*' },
399
- { not: { href_matches: '/__krate/*' } },
400
- { not: { href_matches: '/api/*' } },
401
- ],
402
- },
403
- eagerness: 'moderate',
404
- },
405
- ],
406
- });
407
- document.head.appendChild(script);
748
+ target = href ? normPath(stripBase(new URL(href, location.href).pathname)) : '';
408
749
  }
409
750
  catch {
410
- /* ignore */
751
+ target = '';
411
752
  }
753
+ let active = '';
754
+ if (target && target === path)
755
+ active = 'exact';
756
+ else if (target && target !== '/' && path.startsWith(target + '/'))
757
+ active = 'segment';
758
+ if (active === 'exact')
759
+ a.setAttribute('aria-current', 'page');
760
+ else
761
+ a.removeAttribute('aria-current');
762
+ if (active)
763
+ a.setAttribute('data-krate-active', active);
764
+ else
765
+ a.removeAttribute('data-krate-active');
766
+ });
767
+ }
768
+ function fetchErrorPage(path) {
769
+ const url = basePath() + path;
770
+ if (errorPageCache.has(url))
771
+ return Promise.resolve(errorPageCache.get(url) ?? null);
772
+ return fetch(url, { headers: { Accept: 'text/html' }, credentials: 'same-origin' })
773
+ .then(async (res) => {
774
+ const html = res.ok ? await res.text() : null;
775
+ const out = html && looksLikeHTML(html) ? html : null;
776
+ errorPageCache.set(url, out);
777
+ return out;
778
+ })
779
+ .catch(() => null);
780
+ }
781
+ async function loadDocument(req, signal) {
782
+ const key = cacheKey(req.url);
783
+ if (!req.bypassCache) {
784
+ const inflight = prefetchInflight.get(key);
785
+ if (inflight)
786
+ await inflight;
787
+ if (signal.aborted)
788
+ return { ok: false, aborted: true };
789
+ const hit = cacheTake(key);
790
+ if (hit)
791
+ return { ok: true, doc: { html: hit.html, url: hit.url, status: hit.status } };
412
792
  }
413
- // The app shell lives in `#root` on every page (see generateHTML), so it is
414
- // the one stable swap target. Heuristic per-page content roots made different
415
- // shells/page shapes reconcile incorrectly (dropping the navbar); swapping
416
- // the whole shell is always correct and the new page's own scripts hydrate it.
417
- function appRoot(doc) {
418
- return (doc.getElementById('root') || doc.body);
419
- }
420
- // Document-level <head> tags that change per page and must follow a swap.
421
- const HEAD_SYNC_SEL = 'meta[name="description"], meta[property^="og:"], meta[name^="twitter:"], link[rel="canonical"], script[type="application/ld+json"]';
422
- function reconcileHeadMeta(doc) {
423
- document.head.querySelectorAll(HEAD_SYNC_SEL).forEach((el) => el.remove());
424
- doc.head.querySelectorAll(HEAD_SYNC_SEL).forEach((el) => {
425
- document.head.appendChild(document.importNode(el, true));
793
+ let res;
794
+ try {
795
+ res = await fetch(key, {
796
+ headers: { Accept: 'text/html' },
797
+ credentials: 'same-origin',
798
+ signal,
799
+ cache: req.bypassCache ? 'no-cache' : 'default',
426
800
  });
427
801
  }
428
- function swapContent(html, url, scripts, opts = {}) {
429
- const { replace = false, scroll = true, restoreScroll = false } = opts;
430
- const parser = new DOMParser();
431
- const doc = parser.parseFromString(html, 'text/html');
432
- const newContent = appRoot(doc);
433
- const oldContent = appRoot(document);
434
- if (!newContent || !oldContent) {
435
- location.href = url;
802
+ catch (err) {
803
+ if (err?.name === 'AbortError' || signal.aborted)
804
+ return { ok: false, aborted: true };
805
+ // Network failure: apps can cancel the hard-reload fallback (e.g. to show
806
+ // an offline banner) by calling preventDefault on the event.
807
+ const proceed = dispatch('krate:navigate-error', { url: req.url, status: 0, error: err }, true);
808
+ if (!proceed)
809
+ return { ok: false, aborted: true };
810
+ return { ok: false, hard: req.url };
811
+ }
812
+ const finalUrl = res.url || key;
813
+ if (new URL(finalUrl, location.href).origin !== location.origin) {
814
+ return { ok: false, hard: finalUrl };
815
+ }
816
+ const ct = res.headers.get('content-type') || '';
817
+ let body = '';
818
+ try {
819
+ body = await res.text();
820
+ }
821
+ catch (err) {
822
+ if (err?.name === 'AbortError' || signal.aborted)
823
+ return { ok: false, aborted: true };
824
+ body = '';
825
+ }
826
+ if (signal.aborted)
827
+ return { ok: false, aborted: true };
828
+ const html = isHTMLType(ct) || (ct === '' && looksLikeHTML(body));
829
+ // Preserve the hash of the requested URL across redirects.
830
+ const hash = new URL(req.url, location.href).hash;
831
+ const target = hash && !new URL(finalUrl).hash ? finalUrl + hash : finalUrl;
832
+ if (res.ok) {
833
+ // A non-HTML response (file download, JSON, PDF) is not a page: let the
834
+ // browser handle it.
835
+ if (!html)
836
+ return { ok: false, hard: target };
837
+ return { ok: true, doc: { html: body, url: target, status: res.status } };
838
+ }
839
+ dispatch('krate:navigate-error', { url: req.url, status: res.status });
840
+ // The server rendered an error document for this URL: show it in place.
841
+ if (html && looksLikeHTML(body))
842
+ return { ok: true, doc: { html: body, url: target, status: res.status } };
843
+ let fallback = null;
844
+ if (res.status === 404 || res.status === 410)
845
+ fallback = await fetchErrorPage('/404.html');
846
+ else if (res.status >= 500)
847
+ fallback = await fetchErrorPage('/500.html');
848
+ if (signal.aborted)
849
+ return { ok: false, aborted: true };
850
+ if (fallback)
851
+ return { ok: true, doc: { html: fallback, url: target, status: res.status } };
852
+ // Other statuses (401, 403, 429, ...) without an HTML body: the browser
853
+ // shows the real response.
854
+ return { ok: false, hard: target };
855
+ }
856
+ async function runNavigation(req) {
857
+ const from = location.href;
858
+ if (req.kind !== 'pop') {
859
+ const proceed = dispatch('krate:navigate-start', { url: req.url, from, kind: req.kind }, true);
860
+ if (!proceed)
436
861
  return;
437
- }
438
- dispatchNavEvent('krate:navigate-start', url);
439
- // The single synchronous DOM mutation point. Wrapped in a View Transition
440
- // when the browser supports it, so the SPA morph is animated natively.
441
- const runMutation = () => {
442
- const newTitle = doc.querySelector('title');
443
- if (newTitle)
444
- document.title = newTitle.textContent || '';
445
- // Dispose all active effects before replacing DOM
446
- if (typeof globalThis.disposeAll === 'function') {
447
- globalThis.disposeAll();
448
- }
449
- // Replace the entire app shell. This is deterministic for ANY page pair
450
- // (docs<->docs, marketing<->docs, different layouts): no structural mismatch
451
- // can drop chrome. The new page's scripts re-hydrate below, and View
452
- // Transitions keep the visual transition smooth.
453
- const nodes = Array.from(newContent.childNodes).map((n) => document.importNode(n, true));
454
- oldContent.replaceChildren(...nodes);
455
- reconcileStylesheets(doc);
456
- reconcileHeadMeta(doc);
457
- applyViewTransitionNames(document);
458
- };
459
- if (supportsViewTransitions()) {
460
- try {
461
- const vt = document.startViewTransition(runMutation);
462
- if (vt && vt.finished && typeof vt.finished.catch === 'function') {
463
- vt.finished.catch(() => { });
464
- }
465
- }
466
- catch {
467
- runMutation();
862
+ }
863
+ else {
864
+ dispatch('krate:navigate-start', { url: req.url, from, kind: req.kind });
865
+ }
866
+ const seq = ++navSeq;
867
+ if (pendingAbort)
868
+ pendingAbort.abort();
869
+ const ctrl = new AbortController();
870
+ pendingAbort = ctrl;
871
+ setStatus('loading');
872
+ const hasCached = !req.bypassCache && prefetchCache.has(cacheKey(req.url));
873
+ if (!hasCached)
874
+ beginTransition();
875
+ let result;
876
+ try {
877
+ result = await loadDocument(req, ctrl.signal);
878
+ }
879
+ finally {
880
+ if (pendingAbort === ctrl)
881
+ pendingAbort = undefined;
882
+ }
883
+ if (seq !== navSeq)
884
+ return; // superseded by a newer navigation
885
+ if (!result.ok) {
886
+ endTransition();
887
+ setStatus('idle');
888
+ if ('hard' in result)
889
+ hardNavigate(result.hard, req.kind === 'replace' || req.kind === 'refresh');
890
+ return;
891
+ }
892
+ await commitDocument(result.doc, req, seq);
893
+ }
894
+ async function commitDocument(loaded, req, seq) {
895
+ const doc = new DOMParser().parseFromString(loaded.html, 'text/html');
896
+ const url = loaded.url;
897
+ const newRoot = appRoot(doc);
898
+ const oldRoot = appRoot(document);
899
+ // Save the position of the entry we are leaving (pop saves in the handler).
900
+ if (req.kind === 'push')
901
+ saveScroll(currentKey);
902
+ const newChain = readRouteChain(doc);
903
+ const plan = planSwap(currentChain, newChain, location.href, url, doc);
904
+ // Load the incoming stylesheets before swapping so the new page (and kept
905
+ // layouts whose rules live in the per-page sheet) never renders unstyled.
906
+ const sheets = prepareStylesheets(doc, url);
907
+ await sheets.ready;
908
+ if (seq !== navSeq) {
909
+ sheets.abort();
910
+ return;
911
+ }
912
+ const mutate = () => {
913
+ const title = doc.querySelector('title');
914
+ if (title)
915
+ document.title = title.textContent || '';
916
+ const g = globalThis;
917
+ if (plan.keep.length > 0 && typeof g.krateDisposeExcept === 'function')
918
+ g.krateDisposeExcept(plan.keep);
919
+ else if (typeof g.disposeAll === 'function')
920
+ g.disposeAll();
921
+ if (plan.region) {
922
+ // Only the deepest boundary that differs is replaced; the kept layouts'
923
+ // DOM (and its state, focus and scroll containers) stays in place.
924
+ const { live, next } = plan.region;
925
+ clearBetween(live[0], live[1]);
926
+ const nodes = between(next[0], next[1]).map((n) => document.importNode(n, true));
927
+ for (const n of nodes)
928
+ live[1].parentNode.insertBefore(n, live[1]);
929
+ for (const sl of plan.slots) {
930
+ clearBetween(sl.live[0], sl.live[1]);
931
+ for (const n of between(sl.next[0], sl.next[1]))
932
+ sl.live[1].parentNode.insertBefore(document.importNode(n, true), sl.live[1]);
468
933
  }
934
+ syncLoadingTemplate(oldRoot, newRoot);
469
935
  }
470
936
  else {
471
- runMutation();
937
+ const nodes = Array.from(newRoot.childNodes).map((n) => document.importNode(n, true));
938
+ oldRoot.replaceChildren(...nodes);
939
+ }
940
+ currentChain = plan.chain;
941
+ // Detached slot content of earlier intercepts belonged to the old page.
942
+ interceptSnapshots.clear();
943
+ sheets.commit();
944
+ reconcileHeadMeta(doc);
945
+ applyViewTransitionNames(document);
946
+ };
947
+ await runMutation(mutate);
948
+ if (seq !== navSeq)
949
+ return;
950
+ endTransition();
951
+ // History: the DOM now shows the new route, so the URL follows it before
952
+ // any page script runs.
953
+ if (req.kind === 'push') {
954
+ currentKey = newKey();
955
+ history.pushState(historyEntry(currentKey, req.state), '', url);
956
+ }
957
+ else if (req.kind === 'replace') {
958
+ scrollPositions.delete(currentKey);
959
+ currentKey = newKey();
960
+ history.replaceState(historyEntry(currentKey, req.state), '', url);
961
+ }
962
+ else if (req.kind === 'refresh') {
963
+ if (url !== location.href)
964
+ history.replaceState(history.state, '', url);
965
+ }
966
+ else if (req.restoreKey) {
967
+ currentKey = req.restoreKey;
968
+ }
969
+ renderedPath = pathOf(location.href);
970
+ docPath = renderedPath;
971
+ syncParams(doc);
972
+ applyScroll(url, req);
973
+ if (req.kind !== 'pop' && req.kind !== 'refresh')
974
+ focusContent();
975
+ if (req.kind !== 'refresh')
976
+ announce();
977
+ updateActiveLinks();
978
+ dispatch('krate:navigate', { url: location.href, status: loaded.status });
979
+ notifyNavigation(location.href);
980
+ setStatus('idle');
981
+ // Page scripts re-run against the new DOM; the hydration code of kept
982
+ // layouts is skipped (krateEnterScope) because their bindings are live.
983
+ document.querySelectorAll('script[data-krate-spa]').forEach((s) => s.remove());
984
+ const srcs = scriptsToLoad(doc, url);
985
+ keepScopes(plan.skip);
986
+ const results = await Promise.all(srcs.map(loadScript));
987
+ keepScopes([]);
988
+ if (seq !== navSeq)
989
+ return;
990
+ if (results.some((ok) => !ok)) {
991
+ // A page chunk failed to load: the route would stay half-mounted, so do a
992
+ // full load of the document instead (loudly, through the error event).
993
+ dispatch('krate:navigate-error', { url: location.href, status: loaded.status, error: 'script-load' });
994
+ hardNavigate(location.href, true);
995
+ return;
996
+ }
997
+ refreshPageBindings();
998
+ dispatch('krate:navigate-end', { url: location.href, status: loaded.status });
999
+ }
1000
+ /**
1001
+ * Runs the DOM mutation, inside a View Transition when supported. Resolves
1002
+ * once the mutation has been applied (the transition's update callback has
1003
+ * run), so callers can touch the new DOM, history and focus afterwards.
1004
+ */
1005
+ function runMutation(mutate) {
1006
+ if (!supportsViewTransitions()) {
1007
+ mutate();
1008
+ return Promise.resolve();
1009
+ }
1010
+ let ran = false;
1011
+ const once = () => {
1012
+ if (ran)
1013
+ return;
1014
+ ran = true;
1015
+ mutate();
1016
+ };
1017
+ try {
1018
+ const vt = document.startViewTransition(once);
1019
+ if (vt && vt.finished && typeof vt.finished.catch === 'function')
1020
+ vt.finished.catch(() => { });
1021
+ const done = vt && vt.updateCallbackDone;
1022
+ if (done && typeof done.then === 'function') {
1023
+ return done.then(() => once(), () => once());
1024
+ }
1025
+ }
1026
+ catch {
1027
+ /* fall through */
1028
+ }
1029
+ once();
1030
+ return Promise.resolve();
1031
+ }
1032
+ let currentChain = [];
1033
+ function readRouteChain(doc) {
1034
+ const el = doc.getElementById('__krate_route');
1035
+ if (!el)
1036
+ return [];
1037
+ try {
1038
+ const info = JSON.parse(el.textContent || '{}');
1039
+ return Array.isArray(info.chain) ? info.chain : [];
1040
+ }
1041
+ catch {
1042
+ devWarn('unreadable #__krate_route route info; layouts will be remounted');
1043
+ return [];
1044
+ }
1045
+ }
1046
+ function segmentKey(url, depth) {
1047
+ const segs = stripBase(new URL(url, location.href).pathname).split('/').filter(Boolean);
1048
+ return (depth < 0 ? segs : segs.slice(0, depth)).join('/');
1049
+ }
1050
+ /** Finds the <!--kl:ID--> ... <!--/kl:ID--> (or ks: slot) sibling pair under root. */
1051
+ function findBoundary(root, id, kind = 'kl:') {
1052
+ const doc = root.ownerDocument || root;
1053
+ const walker = doc.createTreeWalker(root, 128 /* NodeFilter.SHOW_COMMENT */);
1054
+ const open = kind + id;
1055
+ const close = '/' + kind + id;
1056
+ while (walker.nextNode()) {
1057
+ const c = walker.currentNode;
1058
+ if (c.nodeValue !== open)
1059
+ continue;
1060
+ for (let n = c.nextSibling; n; n = n.nextSibling) {
1061
+ if (n.nodeType === 8 && n.nodeValue === close)
1062
+ return [c, n];
1063
+ }
1064
+ return null;
1065
+ }
1066
+ return null;
1067
+ }
1068
+ function between(start, end) {
1069
+ const out = [];
1070
+ for (let n = start.nextSibling; n && n !== end; n = n.nextSibling)
1071
+ out.push(n);
1072
+ return out;
1073
+ }
1074
+ function clearBetween(start, end) {
1075
+ const dispose = globalThis.disposeNode;
1076
+ for (const n of between(start, end)) {
1077
+ n.parentNode.removeChild(n);
1078
+ if (typeof dispose === 'function')
1079
+ dispose(n);
1080
+ }
1081
+ }
1082
+ function syncLoadingTemplate(liveRoot, nextRoot) {
1083
+ const sel = ':scope > template[data-krate-loading]';
1084
+ liveRoot.querySelectorAll(sel).forEach((t) => t.remove());
1085
+ nextRoot.querySelectorAll(sel).forEach((t) => liveRoot.appendChild(document.importNode(t, true)));
1086
+ }
1087
+ function keepScopes(ids) {
1088
+ const fn = globalThis.krateKeepScopes;
1089
+ if (typeof fn === 'function')
1090
+ fn(ids);
1091
+ }
1092
+ /**
1093
+ * Compares the layout chains of the current and next documents. The longest
1094
+ * common prefix of persistable layouts (same file, same URL segments) stays
1095
+ * mounted, and only the children region of the deepest kept layout is
1096
+ * replaced. Templates always end the prefix, so they remount on every
1097
+ * navigation through them. A shared layout that cannot be kept is reported
1098
+ * in dev (never silently). Slots of kept layouts are swapped when the new
1099
+ * route has a matching slot page and otherwise keep their content (a soft
1100
+ * navigation never resets a slot to its default).
1101
+ */
1102
+ function planSwap(oldChain, newChain, fromUrl, toUrl, doc) {
1103
+ const full = { keep: [], skip: [], region: null, slots: [], chain: newChain };
1104
+ let k = 0;
1105
+ while (k < oldChain.length && k < newChain.length) {
1106
+ const a = oldChain[k];
1107
+ const b = newChain[k];
1108
+ if (a.id !== b.id || a.k !== 'layout' || b.k !== 'layout')
1109
+ break;
1110
+ if (segmentKey(fromUrl, a.d) !== segmentKey(toUrl, b.d))
1111
+ break;
1112
+ if (!a.p || !b.p) {
1113
+ devWarn(`layout ${b.f || b.id} is remounted on this navigation: ${b.why || a.why || 'not persistable'}`);
1114
+ break;
472
1115
  }
473
- // Load new scripts, then rehydrate
474
- loadScripts(scripts, url).then(() => {
475
- try {
476
- rehydrate();
477
- observePrefetchLinks();
1116
+ k++;
1117
+ }
1118
+ if (k === 0)
1119
+ return full;
1120
+ if (typeof globalThis.krateDisposeExcept !== 'function') {
1121
+ devWarn('the runtime has no krateDisposeExcept; layouts are remounted');
1122
+ return full;
1123
+ }
1124
+ const id = newChain[k - 1].id;
1125
+ const live = findBoundary(appRoot(document), id);
1126
+ const next = findBoundary(appRoot(doc), id);
1127
+ if (!live || !next) {
1128
+ devWarn(`layout ${newChain[k - 1].f || id} boundary markers are missing; the whole page is swapped`);
1129
+ return full;
1130
+ }
1131
+ const keep = oldChain.slice(0, k).map((e) => e.id);
1132
+ const skip = keep.slice();
1133
+ const slots = [];
1134
+ const chain = newChain.slice();
1135
+ for (let j = 0; j < k; j++) {
1136
+ const oldSlots = oldChain[j].s || [];
1137
+ const merged = [];
1138
+ for (const ns of newChain[j].s || []) {
1139
+ const os = oldSlots.find((x) => x.key === ns.key);
1140
+ const liveSlot = findBoundary(appRoot(document), ns.key, 'ks:');
1141
+ const nextSlot = findBoundary(appRoot(doc), ns.key, 'ks:');
1142
+ if (os && liveSlot && (ns.src !== 'page' || !nextSlot)) {
1143
+ // No matching slot page for the new URL: the slot keeps its content.
1144
+ keep.push(os.scope);
1145
+ skip.push(os.scope, ns.scope);
1146
+ merged.push({ ...ns, scope: os.scope, src: os.src });
1147
+ continue;
478
1148
  }
479
- catch (err) {
480
- // Hydration threw (e.g. a page-side error or a compiler emission bug).
481
- // Rather than leave the route half-mounted against a live SPA DOM,
482
- // fall back to a full page load of the SSR HTML. The optional global
483
- // hook lets embedders be notified; a throw inside the hook is ignored.
484
- try {
485
- const hook = globalThis.__krate_onHydrationError;
486
- if (typeof hook === 'function')
487
- hook(err);
488
- }
489
- catch {
490
- /* ignore hook failures */
491
- }
492
- location.href = url;
1149
+ if (liveSlot && nextSlot) {
1150
+ slots.push({ live: liveSlot, next: nextSlot });
1151
+ merged.push(ns);
1152
+ continue;
493
1153
  }
494
- });
495
- endTransition();
496
- // History: replace keeps the current entry; push appends one (unless we
497
- // are restoring from a back/forward navigation).
498
- const prevUrl = location.pathname + location.search;
499
- if (replace) {
500
- history.replaceState({}, '', url);
1154
+ devWarn(`slot @${ns.n} markers are missing; the whole page is swapped`);
1155
+ return full;
501
1156
  }
502
- else {
503
- if (!restoreScroll) {
504
- if (scrollPositions.size >= SCROLL_HISTORY_MAX) {
505
- const oldest = scrollPositions.keys().next().value;
506
- if (oldest !== undefined)
507
- scrollPositions.delete(oldest);
1157
+ chain[j] = { ...newChain[j], s: merged };
1158
+ }
1159
+ return { keep, skip, region: { live, next }, slots, chain };
1160
+ }
1161
+ const interceptSnapshots = new Map();
1162
+ /** pathname+search of the last full document (the children route). */
1163
+ let docPath = '';
1164
+ function parsePattern(pattern) {
1165
+ const t = pattern.replace(/^\/+|\/+$/g, '');
1166
+ if (!t)
1167
+ return [];
1168
+ return t.split('/').map((p) => {
1169
+ if (p.startsWith('[[...') && p.endsWith(']]'))
1170
+ return { kind: 3, text: p.slice(5, -2) };
1171
+ if (p.startsWith('[...') && p.endsWith(']'))
1172
+ return { kind: 2, text: p.slice(4, -1) };
1173
+ if (p.startsWith('[') && p.endsWith(']'))
1174
+ return { kind: 1, text: p.slice(1, -1) };
1175
+ return { kind: 0, text: p };
1176
+ });
1177
+ }
1178
+ /** Mirrors the compiler's matchRoutePattern (static, [param], [...all], [[...opt]]). */
1179
+ export function matchRoutePattern(path, pattern) {
1180
+ const segs = parsePattern(pattern);
1181
+ const t = path.replace(/^\/+|\/+$/g, '');
1182
+ const parts = t ? t.split('/') : [];
1183
+ const params = {};
1184
+ for (let i = 0; i < segs.length; i++) {
1185
+ const s = segs[i];
1186
+ if (s.kind >= 2) {
1187
+ if (i !== segs.length - 1)
1188
+ return null;
1189
+ const rest = parts.slice(i);
1190
+ if (s.kind === 2 && rest.length === 0)
1191
+ return null;
1192
+ if (rest.some((r) => r === ''))
1193
+ return null;
1194
+ params[s.text] = rest.map(decodeSeg).join('/');
1195
+ return params;
1196
+ }
1197
+ if (i >= parts.length)
1198
+ return null;
1199
+ if (s.kind === 1) {
1200
+ if (!parts[i])
1201
+ return null;
1202
+ params[s.text] = decodeSeg(parts[i]);
1203
+ }
1204
+ else if (decodeSeg(parts[i]) !== s.text) {
1205
+ return null;
1206
+ }
1207
+ }
1208
+ return parts.length === segs.length ? params : null;
1209
+ }
1210
+ function decodeSeg(s) {
1211
+ try {
1212
+ return decodeURIComponent(s);
1213
+ }
1214
+ catch {
1215
+ return s;
1216
+ }
1217
+ }
1218
+ /** Negative when pattern a is more specific than b (static > dynamic > catch-all > optional). */
1219
+ export function compareRouteSpecificity(a, b) {
1220
+ const sa = parsePattern(a);
1221
+ const sb = parsePattern(b);
1222
+ for (let i = 0; i < sa.length && i < sb.length; i++) {
1223
+ if (sa[i].kind !== sb[i].kind)
1224
+ return sa[i].kind - sb[i].kind;
1225
+ if (sa[i].kind === 0 && sa[i].text !== sb[i].text)
1226
+ return sa[i].text < sb[i].text ? -1 : 1;
1227
+ }
1228
+ if (sa.length !== sb.length)
1229
+ return sb.length - sa.length;
1230
+ return a < b ? -1 : a > b ? 1 : 0;
1231
+ }
1232
+ function findIntercept(url) {
1233
+ const path = stripBase(new URL(url, location.href).pathname).replace(/^\/+|\/+$/g, '');
1234
+ let best = null;
1235
+ for (const entry of currentChain) {
1236
+ for (const slot of entry.s || []) {
1237
+ for (const pattern of slot.i || []) {
1238
+ if (!matchRoutePattern(path, pattern))
1239
+ continue;
1240
+ if (!best || compareRouteSpecificity(pattern, best.pattern) < 0) {
1241
+ best = { hit: { entry, slot, path }, pattern };
508
1242
  }
509
- scrollPositions.set(prevUrl, window.scrollY);
510
1243
  }
511
- history.pushState({}, '', url);
512
- }
513
- applyScroll(url, { restoreScroll, scroll });
514
- if (!restoreScroll)
515
- focusContent();
516
- updateActiveLinks();
517
- window.dispatchEvent(new CustomEvent('krate:navigate', { detail: { url } }));
518
- dispatchNavEvent('krate:navigate-end', url);
519
- notifyNavigation(url);
520
- }
521
- function handleHashScroll(url) {
522
- const hashIdx = url.indexOf('#');
523
- if (hashIdx < 0 || hashIdx === url.length - 1)
524
- return false;
525
- const hash = url.slice(hashIdx);
1244
+ }
1245
+ }
1246
+ if (best && !findBoundary(appRoot(document), best.hit.slot.key, 'ks:'))
1247
+ return null;
1248
+ return best ? best.hit : null;
1249
+ }
1250
+ function setSlotInfo(key, next) {
1251
+ currentChain = currentChain.map((e) => e.s && e.s.some((x) => x.key === key) ? { ...e, s: e.s.map((x) => (x.key === key ? next : x)) } : e);
1252
+ }
1253
+ function syncParams(doc) {
1254
+ for (const script of Array.from(doc.querySelectorAll('script:not([src])'))) {
1255
+ const m = /window\.__KRATE_PARAMS__\s*=\s*(\{[\s\S]*?\})\s*;?\s*$/.exec(script.textContent || '');
1256
+ if (!m)
1257
+ continue;
526
1258
  try {
527
- const el = document.querySelector(hash);
528
- if (el) {
529
- el.scrollIntoView({ behavior: 'smooth', block: 'start' });
530
- return true;
531
- }
1259
+ globalThis.__KRATE_PARAMS__ = JSON.parse(m[1]);
532
1260
  }
533
1261
  catch {
534
- return false;
1262
+ /* ignore */
535
1263
  }
536
- return false;
1264
+ return;
537
1265
  }
538
- function applyScroll(url, opts) {
539
- if (opts.restoreScroll) {
540
- const saved = scrollPositions.get(url);
541
- if (saved !== undefined) {
542
- window.scrollTo(0, saved);
543
- return;
544
- }
545
- }
546
- if (handleHashScroll(url))
1266
+ delete globalThis.__KRATE_PARAMS__;
1267
+ }
1268
+ function disposeScopes(ids) {
1269
+ const fn = globalThis.krateDisposeScopes;
1270
+ if (typeof fn === 'function')
1271
+ fn(ids);
1272
+ }
1273
+ /**
1274
+ * Soft navigation to a URL a mounted slot intercepts: the slot shows the
1275
+ * intercepting fragment while the URL becomes the target and the rest of
1276
+ * the page (including the children route) stays as it is. The slot's
1277
+ * previous content is kept detached (alive) and restored by going back.
1278
+ */
1279
+ async function runIntercept(req, hit) {
1280
+ const from = location.href;
1281
+ if (req.kind !== 'pop') {
1282
+ if (!dispatch('krate:navigate-start', { url: req.url, from, kind: req.kind, intercept: hit.slot.n }, true))
547
1283
  return;
548
- if (opts.scroll)
549
- window.scrollTo(0, 0);
550
- }
551
- // Mark the link matching the current route with aria-current="page".
552
- function updateActiveLinks() {
553
- const path = stripBase(location.pathname);
554
- document.querySelectorAll('a[data-krate-link]').forEach((a) => {
555
- const href = a.getAttribute('href');
556
- if (!href) {
557
- a.removeAttribute('aria-current');
558
- return;
559
- }
560
- let target = href;
561
- try {
562
- target = stripBase(new URL(href, location.origin).pathname);
563
- }
564
- catch {
565
- return;
566
- }
567
- const active = target === path ||
568
- (path === '/' && (target === '' || target === '/')) ||
569
- (target !== '/' && target.length > 1 && path.startsWith(target));
570
- if (active)
571
- a.setAttribute('aria-current', 'page');
572
- else
573
- a.removeAttribute('aria-current');
574
- });
575
1284
  }
576
- function loadScripts(scripts, baseUrl) {
577
- if (scripts.length === 0)
578
- return Promise.resolve();
579
- // Load all scripts in parallel (no serialization latency); hydration runs
580
- // once every script is loaded.
581
- return Promise.all(scripts.map((script) => {
582
- const src = script.getAttribute('src');
583
- return src ? loadScript(src, baseUrl) : Promise.resolve();
584
- })).then(() => undefined);
585
- }
586
- function loadScript(src, baseUrl) {
587
- return new Promise((resolve) => {
588
- const s = document.createElement('script');
589
- const resolved = resolveSrc(src, baseUrl);
590
- s.src = resolved;
591
- // Only page scripts are disposable across navigations - the shared
592
- // runtime chunk stays in place.
593
- if (!RUNTIME_CHUNK_RE.test(resolved))
594
- s.setAttribute('data-krate-spa', '');
595
- s.onload = () => resolve();
596
- s.onerror = () => resolve();
597
- document.body.appendChild(s);
1285
+ const seq = ++navSeq;
1286
+ if (pendingAbort)
1287
+ pendingAbort.abort();
1288
+ const ctrl = new AbortController();
1289
+ pendingAbort = ctrl;
1290
+ setStatus('loading');
1291
+ const fragURL = location.origin + basePath() + '/' + INTERCEPT_PREFIX + '/' + hit.slot.key + (hit.path ? '/' + hit.path : '');
1292
+ let html = '';
1293
+ let ok = false;
1294
+ try {
1295
+ const res = await fetch(fragURL, {
1296
+ headers: { Accept: 'text/html' },
1297
+ credentials: 'same-origin',
1298
+ signal: ctrl.signal,
1299
+ cache: req.bypassCache ? 'no-cache' : 'default',
598
1300
  });
1301
+ html = await res.text();
1302
+ ok = res.ok && (isHTMLType(res.headers.get('content-type') || '') || looksLikeHTML(html));
1303
+ if (!ok)
1304
+ dispatch('krate:navigate-error', { url: req.url, status: res.status, intercept: hit.slot.n });
599
1305
  }
600
- // Resolve a script URL against the navigated-to page (see module-level
601
- // resolveSrc), kept as a local alias for readability at call sites.
602
- function rehydrate() {
603
- if (typeof globalThis.__krate_hydrate === 'function') {
604
- globalThis.__krate_hydrate();
605
- }
606
- }
607
- function replacePage(html, url) {
608
- // Dispose all active effects before full page replacement
609
- if (typeof globalThis.disposeAll === 'function') {
610
- globalThis.disposeAll();
611
- }
612
- history.pushState({}, '', url);
613
- notifyNavigation(url);
614
- document.open();
615
- document.write(html);
616
- document.close();
617
- }
618
- function fetchNotFoundPage() {
619
- if (notFoundHTML !== null)
620
- return Promise.resolve(notFoundHTML);
621
- return fetch('/404.html', { headers: { Accept: 'text/html' } })
622
- .then((res) => {
623
- if (!res.ok)
624
- return null;
625
- return res.text();
626
- })
627
- .then((html) => {
628
- notFoundHTML = html;
629
- return html;
630
- })
631
- .catch(() => null);
632
- }
633
- function fetchErrorPage() {
634
- if (errorHTML !== null)
635
- return Promise.resolve(errorHTML);
636
- return fetch('/500.html', { headers: { Accept: 'text/html' } })
637
- .then((res) => {
638
- if (!res.ok)
639
- return null;
640
- return res.text();
641
- })
642
- .then((html) => {
643
- errorHTML = html;
644
- return html;
645
- })
646
- .catch(() => null);
647
- }
648
- function extractScripts(doc, baseUrl) {
649
- // Remove previously SPA-loaded page scripts. They must re-execute on every
650
- // visit (the reconciled DOM is new), and they'd otherwise accumulate.
651
- document.querySelectorAll('script[data-krate-spa]').forEach((s) => s.remove());
652
- const scripts = [];
653
- const existingSrcs = new Set();
654
- document.querySelectorAll('script[src]').forEach((s) => {
655
- existingSrcs.add(s.src);
656
- });
657
- doc.querySelectorAll('script[src]').forEach((s) => {
658
- const src = s.getAttribute('src');
659
- if (src && !existingSrcs.has(resolveSrc(src, baseUrl))) {
660
- scripts.push(s);
661
- }
662
- });
663
- return scripts;
664
- }
665
- function fetchAndSwap(url, opts = {}) {
666
- const seq = ++navSeq;
667
- // Check prefetch cache first - already-loaded content swaps instantly.
668
- const cached = prefetchCache.get(url);
669
- if (cached) {
670
- const parser = new DOMParser();
671
- const doc = parser.parseFromString(cached, 'text/html');
672
- swapContent(cached, url, extractScripts(doc, url), opts);
1306
+ catch (err) {
1307
+ if (err?.name === 'AbortError' || ctrl.signal.aborted)
673
1308
  return;
1309
+ dispatch('krate:navigate-error', { url: req.url, status: 0, error: err, intercept: hit.slot.n });
1310
+ }
1311
+ finally {
1312
+ if (pendingAbort === ctrl)
1313
+ pendingAbort = undefined;
1314
+ }
1315
+ if (seq !== navSeq)
1316
+ return;
1317
+ const doc = ok ? new DOMParser().parseFromString(html, 'text/html') : null;
1318
+ const next = doc ? findBoundary(appRoot(doc), hit.slot.key, 'ks:') : null;
1319
+ const live = findBoundary(appRoot(document), hit.slot.key, 'ks:');
1320
+ let frag = null;
1321
+ try {
1322
+ const el = doc && doc.getElementById('__krate_route');
1323
+ frag = el ? JSON.parse(el.textContent || '{}').frag || null : null;
1324
+ }
1325
+ catch {
1326
+ frag = null;
1327
+ }
1328
+ if (!doc || !next || !live || !frag || frag.key !== hit.slot.key || !frag.scope) {
1329
+ // The fragment is missing or malformed: show the real page instead,
1330
+ // loudly (the error event above, and a console warning).
1331
+ try {
1332
+ console.warn(`[krate router] intercepting route for ${req.url} (slot @${hit.slot.n}) could not be loaded; navigating to the page`);
674
1333
  }
675
- // Begin the fade/loading transition while the fetch is in flight.
676
- beginTransition();
677
- // Fix 4.6: Abort any in-flight navigation
678
- if (pendingAbort) {
679
- pendingAbort.abort();
1334
+ catch {
1335
+ /* ignore */
680
1336
  }
681
- pendingAbort = new AbortController();
682
- const signal = pendingAbort.signal;
683
- fetch(url, {
684
- headers: { Accept: 'text/html' },
685
- signal,
686
- })
687
- .then((res) => {
688
- if (seq !== navSeq)
689
- return; // superseded by a newer navigation
690
- if (!res.ok) {
691
- const page = res.status >= 500 ? fetchErrorPage() : fetchNotFoundPage();
692
- return page.then((html) => {
693
- if (seq !== navSeq)
694
- return;
695
- if (html) {
696
- // Error pages contain full layout - full page replacement
697
- replacePage(html, url);
698
- }
699
- else {
700
- location.href = url;
701
- }
702
- });
703
- }
704
- return res.text().then((html) => {
705
- if (seq !== navSeq)
706
- return; // superseded while reading the body
707
- const parser = new DOMParser();
708
- const doc = parser.parseFromString(html, 'text/html');
709
- swapContent(html, url, extractScripts(doc, url), opts);
710
- });
711
- })
712
- .catch((err) => {
713
- // Ignore aborted requests; otherwise abort the transition so the page
714
- // fades back in.
715
- if (err?.name !== 'AbortError') {
716
- endTransition();
717
- location.href = url;
718
- }
719
- })
720
- .finally(() => {
721
- if (pendingAbort && !signal.aborted) {
722
- pendingAbort = undefined;
723
- }
724
- });
1337
+ setStatus('idle');
1338
+ return runNavigation({ ...req });
725
1339
  }
726
- const clickHandler = (e) => {
727
- // Never intercept modified clicks (cmd/ctrl/shift/alt or middle button) -
728
- // they should open in a new tab or trigger browser behavior.
729
- if (e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey)
730
- return;
731
- const a = e.target.closest('a[data-krate-link]');
732
- if (!a || !isLocalLink(a))
1340
+ if (req.kind === 'push')
1341
+ saveScroll(currentKey);
1342
+ // Swap the slot content.
1343
+ if (hit.slot.src !== 'intercept') {
1344
+ interceptSnapshots.set(currentKey, { key: hit.slot.key, nodes: between(live[0], live[1]), slot: hit.slot, path: docPath });
1345
+ for (const n of between(live[0], live[1]))
1346
+ n.parentNode.removeChild(n);
1347
+ }
1348
+ else {
1349
+ disposeScopes([hit.slot.scope]);
1350
+ clearBetween(live[0], live[1]);
1351
+ }
1352
+ for (const n of between(next[0], next[1]))
1353
+ live[1].parentNode.insertBefore(document.importNode(n, true), live[1]);
1354
+ // A fragment only adds its stylesheets; the page keeps its own.
1355
+ const existing = new Set();
1356
+ document.querySelectorAll('link[rel="stylesheet"]').forEach((l) => existing.add(l.href));
1357
+ doc.querySelectorAll('link[rel="stylesheet"][href]').forEach((l) => {
1358
+ const abs = new URL(l.getAttribute('href'), fragURL).href;
1359
+ if (existing.has(abs))
733
1360
  return;
734
- e.preventDefault();
735
- const href = a.getAttribute('href');
736
- if (!href)
1361
+ const link = document.createElement('link');
1362
+ link.rel = 'stylesheet';
1363
+ link.href = abs;
1364
+ document.head.appendChild(link);
1365
+ });
1366
+ setSlotInfo(hit.slot.key, { ...hit.slot, scope: frag.scope, src: 'intercept' });
1367
+ const state = { __krate: '', state: req.state === undefined ? null : req.state, __kint: { key: hit.slot.key, base: docPath } };
1368
+ if (req.kind === 'push') {
1369
+ currentKey = newKey();
1370
+ state.__krate = currentKey;
1371
+ history.pushState(state, '', req.url);
1372
+ }
1373
+ else if (req.kind === 'replace') {
1374
+ currentKey = newKey();
1375
+ state.__krate = currentKey;
1376
+ history.replaceState(state, '', req.url);
1377
+ }
1378
+ else if (req.kind === 'pop' && req.restoreKey) {
1379
+ currentKey = req.restoreKey;
1380
+ }
1381
+ renderedPath = pathOf(location.href);
1382
+ syncParams(doc);
1383
+ updateActiveLinks();
1384
+ dispatch('krate:navigate', { url: location.href, status: 200, intercept: hit.slot.n });
1385
+ notifyNavigation(location.href);
1386
+ setStatus('idle');
1387
+ const srcs = scriptsToLoad(doc, fragURL);
1388
+ const results = await Promise.all(srcs.map(loadScript));
1389
+ if (seq !== navSeq)
1390
+ return;
1391
+ if (results.some((r) => !r)) {
1392
+ dispatch('krate:navigate-error', { url: location.href, status: 200, error: 'script-load', intercept: hit.slot.n });
1393
+ hardNavigate(location.href, true);
1394
+ return;
1395
+ }
1396
+ refreshPageBindings();
1397
+ dispatch('krate:navigate-end', { url: location.href, status: 200, intercept: hit.slot.n });
1398
+ }
1399
+ /** Back to the page an intercept was opened from: put the slot content back. */
1400
+ function restoreSnapshot(snap, key) {
1401
+ const live = findBoundary(appRoot(document), snap.key, 'ks:');
1402
+ const current = currentChain.flatMap((e) => e.s || []).find((x) => x.key === snap.key);
1403
+ if (!live || !current || current.src !== 'intercept')
1404
+ return false;
1405
+ disposeScopes([current.scope]);
1406
+ clearBetween(live[0], live[1]);
1407
+ for (const n of snap.nodes)
1408
+ live[1].parentNode.insertBefore(n, live[1]);
1409
+ setSlotInfo(snap.key, snap.slot);
1410
+ interceptSnapshots.delete(key);
1411
+ currentKey = key;
1412
+ renderedPath = pathOf(location.href);
1413
+ const saved = scrollPositions.get(key);
1414
+ if (saved !== undefined)
1415
+ window.scrollTo(0, saved);
1416
+ updateActiveLinks();
1417
+ dispatch('krate:navigate', { url: location.href, status: 200 });
1418
+ notifyNavigation(location.href);
1419
+ emit();
1420
+ return true;
1421
+ }
1422
+ function sameDocument(url) {
1423
+ return pathOf(url) === renderedPath;
1424
+ }
1425
+ /** In-document navigation: only the hash (or nothing) changes. */
1426
+ function hashNavigate(url, req) {
1427
+ saveScroll(currentKey);
1428
+ if (url !== location.href || req.state !== undefined) {
1429
+ if (req.kind === 'replace') {
1430
+ history.replaceState(historyEntry(currentKey || newKey(), req.state), '', url);
1431
+ }
1432
+ else {
1433
+ currentKey = newKey();
1434
+ history.pushState(historyEntry(currentKey, req.state), '', url);
1435
+ }
1436
+ }
1437
+ const hash = new URL(url).hash;
1438
+ if (!scrollToHash(hash) && req.scroll && !hash)
1439
+ window.scrollTo(0, 0);
1440
+ emit();
1441
+ }
1442
+ function start(req) {
1443
+ let u;
1444
+ try {
1445
+ u = new URL(req.url, location.href);
1446
+ }
1447
+ catch {
1448
+ hardNavigate(req.url);
1449
+ return Promise.resolve();
1450
+ }
1451
+ if (u.origin !== location.origin) {
1452
+ hardNavigate(u.href, req.kind === 'replace');
1453
+ return Promise.resolve();
1454
+ }
1455
+ req.url = u.href;
1456
+ if ((req.kind === 'push' || req.kind === 'replace') && sameDocument(u.href) && (u.hash || u.href === location.href)) {
1457
+ hashNavigate(u.href, req);
1458
+ return Promise.resolve();
1459
+ }
1460
+ if (req.kind === 'push' || req.kind === 'replace') {
1461
+ const hit = findIntercept(u.href);
1462
+ if (hit)
1463
+ return runIntercept(req, hit);
1464
+ }
1465
+ return runNavigation(req);
1466
+ }
1467
+ // Event handlers
1468
+ function clickHandler(e) {
1469
+ if (e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey)
1470
+ return;
1471
+ const t = e.target;
1472
+ if (!t || typeof t.closest !== 'function')
1473
+ return;
1474
+ const a = t.closest('a[data-krate-link]');
1475
+ if (!a || !isLocalLink(a))
1476
+ return;
1477
+ const href = a.getAttribute('href');
1478
+ if (!href)
1479
+ return;
1480
+ e.preventDefault();
1481
+ void start({
1482
+ url: new URL(href, location.href).href,
1483
+ kind: a.hasAttribute('data-krate-replace') ? 'replace' : 'push',
1484
+ scroll: a.getAttribute('data-krate-scroll') !== 'false',
1485
+ });
1486
+ }
1487
+ function submitHandler(e) {
1488
+ if (e.defaultPrevented)
1489
+ return;
1490
+ const form = e.target;
1491
+ if (!form || form.tagName !== 'FORM')
1492
+ return;
1493
+ if (form.hasAttribute('data-krate-reload'))
1494
+ return;
1495
+ const submitter = (e.submitter || null);
1496
+ const method = ((submitter && submitter.getAttribute('formmethod')) || form.getAttribute('method') || 'get').toLowerCase();
1497
+ if (method !== 'get')
1498
+ return;
1499
+ const target = (submitter && submitter.getAttribute('formtarget')) || form.getAttribute('target');
1500
+ if (target && target !== '_self')
1501
+ return;
1502
+ const actionAttr = (submitter && submitter.getAttribute('formaction')) || form.getAttribute('action') || '';
1503
+ let action;
1504
+ try {
1505
+ action = new URL(actionAttr || location.href, location.href);
1506
+ }
1507
+ catch {
1508
+ return;
1509
+ }
1510
+ if (action.origin !== location.origin || action.protocol.indexOf('http') !== 0)
1511
+ return;
1512
+ let data;
1513
+ try {
1514
+ data = submitter ? new FormData(form, submitter) : new FormData(form);
1515
+ }
1516
+ catch {
1517
+ data = new FormData(form);
1518
+ if (submitter && submitter.name)
1519
+ data.append(submitter.name, submitter.value);
1520
+ }
1521
+ const params = new URLSearchParams();
1522
+ for (const [k, v] of data.entries()) {
1523
+ // A file input cannot be encoded into a GET query; leave it to the browser.
1524
+ if (typeof v !== 'string')
737
1525
  return;
738
- const url = new URL(href, location.origin).href;
739
- const replace = a.hasAttribute('data-krate-replace');
740
- const scroll = a.getAttribute('data-krate-scroll') !== 'false';
741
- // Same-URL navigation (e.g. hash change): just update history + scroll.
742
- if (href === location.pathname + location.search + location.hash) {
743
- if (replace)
744
- history.replaceState({}, '', href);
745
- applyScroll(url, { scroll });
1526
+ params.append(k, v);
1527
+ }
1528
+ e.preventDefault();
1529
+ action.search = params.toString();
1530
+ action.hash = '';
1531
+ void start({ url: action.href, kind: 'push', scroll: true });
1532
+ }
1533
+ function popstateHandler(e) {
1534
+ // The URL already changed; remember where the user was on the entry left.
1535
+ saveScroll(currentKey);
1536
+ const key = entryKey(e.state);
1537
+ const url = location.href;
1538
+ if (pathOf(url) === renderedPath) {
1539
+ // Hash-only history step within the rendered document.
1540
+ currentKey = key || currentKey;
1541
+ const saved = key ? scrollPositions.get(key) : undefined;
1542
+ if (saved !== undefined)
1543
+ window.scrollTo(0, saved);
1544
+ else
1545
+ scrollToHash(location.hash);
1546
+ emit();
1547
+ return;
1548
+ }
1549
+ // Back to the page an intercept was opened from.
1550
+ const snap = key ? interceptSnapshots.get(key) : undefined;
1551
+ if (snap && key && snap.path === pathOf(url) && snap.path === docPath && restoreSnapshot(snap, key))
1552
+ return;
1553
+ // Back/forward to an intercepted entry while its base page is still shown.
1554
+ const kint = e.state && typeof e.state === 'object' ? e.state.__kint : null;
1555
+ if (kint && kint.base === docPath) {
1556
+ const hit = findIntercept(url);
1557
+ if (hit && hit.slot.key === kint.key) {
1558
+ void runIntercept({ url, kind: 'pop', scroll: false, restoreKey: key }, hit);
746
1559
  return;
747
1560
  }
748
- fetchAndSwap(url, { replace, scroll });
749
- };
750
- const popstateHandler = () => {
751
- fetchAndSwap(location.href, { restoreScroll: true });
752
- };
753
- document.addEventListener('click', clickHandler);
754
- window.addEventListener('popstate', popstateHandler);
755
- setupPrefetch();
756
- setupSpeculationRules();
1561
+ }
1562
+ void runNavigation({ url, kind: 'pop', scroll: true, restoreKey: key });
1563
+ }
1564
+ function revalidateHandler() {
1565
+ invalidatePrefetchCache();
1566
+ void refresh();
1567
+ }
1568
+ function pagehideHandler() {
1569
+ saveScroll(currentKey);
1570
+ // Hand scroll restoration back to the browser for reloads and cross-document
1571
+ // history steps.
1572
+ try {
1573
+ history.scrollRestoration = 'auto';
1574
+ }
1575
+ catch {
1576
+ /* ignore */
1577
+ }
1578
+ }
1579
+ function pageshowHandler() {
1580
+ try {
1581
+ history.scrollRestoration = 'manual';
1582
+ }
1583
+ catch {
1584
+ /* ignore */
1585
+ }
1586
+ }
1587
+ /** Per-page bindings refreshed after every swap (and by reinitRouter). */
1588
+ function refreshPageBindings() {
1589
+ observePrefetchLinks();
757
1590
  updateActiveLinks();
758
1591
  applyViewTransitionNames(document);
759
- // Expose the SPA navigation to `navigate()` (and any embedded UI).
760
- navigateImpl = (url, opts = {}) => {
761
- let sameOrigin = true;
1592
+ // Mark the page scripts as disposable so they're removed and re-executed
1593
+ // against the fresh DOM on the next navigation.
1594
+ document.querySelectorAll('script[src]').forEach((s) => {
1595
+ if (!RUNTIME_CHUNK_RE.test(s.src))
1596
+ s.setAttribute('data-krate-spa', '');
1597
+ });
1598
+ }
1599
+ // Public API
1600
+ function refresh() {
1601
+ if (!initialized || typeof location === 'undefined') {
1602
+ if (typeof location !== 'undefined')
1603
+ location.reload();
1604
+ return Promise.resolve();
1605
+ }
1606
+ if (renderedPath !== docPath) {
1607
+ // The URL shows an intercepted route: refresh the slot content.
1608
+ const hit = findIntercept(location.href);
1609
+ if (hit && hit.slot.src === 'intercept') {
1610
+ return runIntercept({ url: location.href, kind: 'refresh', scroll: false, bypassCache: true }, hit);
1611
+ }
1612
+ }
1613
+ return runNavigation({ url: location.href, kind: 'refresh', scroll: false, bypassCache: true });
1614
+ }
1615
+ function push(url, opts = {}) {
1616
+ if (!initialized) {
1617
+ if (typeof location !== 'undefined')
1618
+ location.assign(url);
1619
+ return Promise.resolve();
1620
+ }
1621
+ return start({ url, kind: 'push', scroll: opts.scroll !== false, state: opts.state });
1622
+ }
1623
+ function replace(url, opts = {}) {
1624
+ if (!initialized) {
1625
+ if (typeof location !== 'undefined')
1626
+ location.replace(url);
1627
+ return Promise.resolve();
1628
+ }
1629
+ return start({ url, kind: 'replace', scroll: opts.scroll !== false, state: opts.state });
1630
+ }
1631
+ /**
1632
+ * The router API. Every navigation method resolves once the new route's DOM
1633
+ * and URL are in place (page scripts may still be loading).
1634
+ *
1635
+ * - push(url, opts) / replace(url, opts): client navigation.
1636
+ * - back() / forward(): history traversal.
1637
+ * - refresh(): re-fetches the current route (bypassing the prefetch cache)
1638
+ * and swaps it in place, keeping scroll position and history.
1639
+ * - prefetch(url): warms the document (and its page chunk) for a later visit.
1640
+ */
1641
+ export const krateRouter = {
1642
+ push,
1643
+ replace,
1644
+ back() {
1645
+ if (typeof history !== 'undefined')
1646
+ history.back();
1647
+ },
1648
+ forward() {
1649
+ if (typeof history !== 'undefined')
1650
+ history.forward();
1651
+ },
1652
+ refresh,
1653
+ prefetch(url) {
1654
+ if (!initialized || typeof location === 'undefined')
1655
+ return Promise.resolve();
1656
+ let u;
762
1657
  try {
763
- sameOrigin = new URL(url, location.href).origin === location.origin;
1658
+ u = new URL(url, location.href);
764
1659
  }
765
1660
  catch {
766
- sameOrigin = false;
1661
+ return Promise.resolve();
767
1662
  }
768
- if (!sameOrigin) {
769
- location.href = url;
770
- return;
1663
+ if (u.origin !== location.origin)
1664
+ return Promise.resolve();
1665
+ return prefetchPage(u.href);
1666
+ },
1667
+ subscribe: subscribeNavigation,
1668
+ getState: getNavigationState,
1669
+ invalidate: invalidatePrefetchCache,
1670
+ };
1671
+ /**
1672
+ * Programmatic SPA navigation. Falls back to a full page load when the router
1673
+ * has not initialized (e.g. before hydration). Returns false when handled
1674
+ * client-side, true when a full navigation was triggered.
1675
+ */
1676
+ export function navigate(url, opts = {}) {
1677
+ if (initialized) {
1678
+ void (opts.replace ? replace(url, opts) : push(url, opts));
1679
+ return false;
1680
+ }
1681
+ if (typeof location !== 'undefined') {
1682
+ if (opts.replace)
1683
+ location.replace(url);
1684
+ else
1685
+ location.assign(url);
1686
+ }
1687
+ return true;
1688
+ }
1689
+ export function initRouter() {
1690
+ if (typeof document === 'undefined')
1691
+ return;
1692
+ if (initialized) {
1693
+ refreshPageBindings();
1694
+ return;
1695
+ }
1696
+ initialized = true;
1697
+ renderedPath = pathOf(location.href);
1698
+ currentChain = readRouteChain(document);
1699
+ docPath = renderedPath;
1700
+ currentKey = entryKey(history.state) || newKey();
1701
+ if (entryKey(history.state) === undefined) {
1702
+ try {
1703
+ history.replaceState(historyEntry(currentKey, history.state), '', location.href);
771
1704
  }
772
- fetchAndSwap(new URL(url, location.href).href, opts);
773
- };
774
- // Mark the initially-loaded page scripts as disposable so they're removed and
775
- // re-executed against the fresh DOM when the user navigates back to this
776
- // page. The shared runtime chunk is the exception and persists.
777
- document.querySelectorAll('script[src]').forEach((s) => {
778
- if (!RUNTIME_CHUNK_RE.test(s.src)) {
779
- s.setAttribute('data-krate-spa', '');
1705
+ catch {
1706
+ /* ignore */
780
1707
  }
781
- });
782
- routerCleanup = () => {
783
- document.removeEventListener('click', clickHandler);
784
- window.removeEventListener('popstate', popstateHandler);
785
- cleanupPrefetch();
786
- navigateImpl = null;
787
- };
1708
+ }
1709
+ try {
1710
+ history.scrollRestoration = 'manual';
1711
+ }
1712
+ catch {
1713
+ /* ignore */
1714
+ }
1715
+ document.addEventListener('click', clickHandler);
1716
+ document.addEventListener('submit', submitHandler);
1717
+ window.addEventListener('popstate', popstateHandler);
1718
+ window.addEventListener('krate:revalidate', revalidateHandler);
1719
+ window.addEventListener('pagehide', pagehideHandler);
1720
+ window.addEventListener('pageshow', pageshowHandler);
1721
+ setupPrefetch();
1722
+ setupSpeculationRules();
1723
+ refreshPageBindings();
788
1724
  }
789
- /** Dispose old effects, re-register router listeners for new page. */
1725
+ /**
1726
+ * Called at the end of every page hydration script. The router keeps its
1727
+ * listeners and caches; only the per-page bindings are refreshed.
1728
+ */
790
1729
  export function reinitRouter() {
791
- if (routerCleanup) {
792
- routerCleanup();
793
- routerCleanup = null;
794
- }
795
- initialized = false;
796
1730
  initRouter();
797
1731
  }
1732
+ /** Tears the router down (tests and embedders that unmount Krate). */
1733
+ export function destroyRouter() {
1734
+ if (!initialized)
1735
+ return;
1736
+ initialized = false;
1737
+ document.removeEventListener('click', clickHandler);
1738
+ document.removeEventListener('submit', submitHandler);
1739
+ window.removeEventListener('popstate', popstateHandler);
1740
+ window.removeEventListener('krate:revalidate', revalidateHandler);
1741
+ window.removeEventListener('pagehide', pagehideHandler);
1742
+ window.removeEventListener('pageshow', pageshowHandler);
1743
+ document.removeEventListener('mouseover', prefetchHoverHandler);
1744
+ document.removeEventListener('focusin', prefetchHoverHandler);
1745
+ for (const timer of prefetchTimers.values())
1746
+ clearTimeout(timer);
1747
+ prefetchTimers = new Map();
1748
+ if (prefetchObserver) {
1749
+ prefetchObserver.disconnect();
1750
+ prefetchObserver = null;
1751
+ }
1752
+ if (pendingAbort)
1753
+ pendingAbort.abort();
1754
+ pendingAbort = undefined;
1755
+ navSeq++;
1756
+ prefetchCache.clear();
1757
+ prefetchInflight.clear();
1758
+ scrollPositions.clear();
1759
+ errorPageCache.clear();
1760
+ listeners.clear();
1761
+ status = 'idle';
1762
+ loadingOverlay = [];
1763
+ currentChain = [];
1764
+ interceptSnapshots.clear();
1765
+ docPath = '';
1766
+ }