@krate/runtime 0.5.0-alpha.3 → 0.5.0-alpha.4

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/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,1592 @@ 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;
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
+ }
195
+ }
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;
220
+ }
221
+ catch {
144
222
  return true;
145
223
  }
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);
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);
154
232
  }
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';
233
+ catch {
234
+ /* ignore hook failures */
159
235
  }
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);
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);
169
245
  }
170
- function prefetchPage(url) {
171
- if (prefetchCache.has(url))
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);
260
+ }
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)
172
313
  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
- }
314
+ const ct = res.headers.get('content-type') || '';
315
+ const finalUrl = res.url || key;
316
+ if (new URL(finalUrl, location.href).origin !== location.origin)
317
+ return;
318
+ const html = await res.text();
319
+ if (!(isHTMLType(ct) || (ct === '' && looksLikeHTML(html))))
320
+ return;
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));
210
416
  }
211
- }, { rootMargin: '200px' });
212
- observePrefetchLinks();
213
- }
417
+ prefetchObserver.unobserve(entry.target);
418
+ }
419
+ }, { rootMargin: '200px' });
420
+ observePrefetchLinks();
214
421
  }
215
- function observePrefetchLinks() {
216
- if (!prefetchObserver)
217
- return;
218
- document.querySelectorAll('a[data-prefetch]').forEach((a) => {
219
- if (shouldPrefetch(a))
220
- prefetchObserver.observe(a);
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
+ try {
432
+ const script = document.createElement('script');
433
+ script.type = 'speculationrules';
434
+ script.textContent = JSON.stringify({
435
+ prefetch: [
436
+ {
437
+ where: {
438
+ and: [
439
+ { href_matches: '/*' },
440
+ { not: { href_matches: '/__krate/*' } },
441
+ { not: { href_matches: '/api/*' } },
442
+ ],
443
+ },
444
+ eagerness: 'moderate',
445
+ },
446
+ ],
221
447
  });
448
+ document.head.appendChild(script);
222
449
  }
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
- }
450
+ catch {
451
+ /* ignore */
234
452
  }
235
- function prefetchHoverHandler(e) {
236
- const a = e.target.closest('a[data-prefetch]');
237
- if (!a || !shouldPrefetch(a) || !isLocalLink(a))
238
- return;
239
- const href = a.getAttribute('href');
240
- if (!href)
241
- return;
242
- const url = new URL(href, location.origin).href;
243
- if (prefetchCache.has(url))
244
- 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) {
453
+ }
454
+ // Visual transition
455
+ /** Whether native View Transitions should wrap the SPA mutation. */
456
+ function supportsViewTransitions() {
457
+ if (runtimeConfig().viewTransitions === false)
458
+ return false;
459
+ if (typeof window !== 'undefined' && window.matchMedia) {
290
460
  try {
291
- const hook = globalThis.__krate_onNavigation;
292
- if (typeof hook === 'function')
293
- hook(url);
461
+ if (window.matchMedia('(prefers-reduced-motion: reduce)').matches)
462
+ return false;
294
463
  }
295
464
  catch {
296
- /* ignore hook failures */
465
+ /* ignore */
297
466
  }
298
467
  }
299
- function dispatchNavEvent(name, url) {
300
- try {
301
- window.dispatchEvent(new CustomEvent(name, { detail: { url } }));
302
- }
303
- catch {
304
- /* ignore */
468
+ return typeof document.startViewTransition === 'function';
469
+ }
470
+ function appRoot(doc) {
471
+ return (doc.getElementById('root') || doc.body);
472
+ }
473
+ // While a fetch is in flight: overlay the loading.tsx template (if the page
474
+ // has one) and, without View Transitions, fade the content out.
475
+ function beginTransition() {
476
+ const tpl = document.querySelector('template[data-krate-loading]');
477
+ if (tpl && tpl.content && loadingOverlay.length === 0) {
478
+ // Non-destructive loading UI: overlay the template without wiping the
479
+ // live DOM, so the swap still sees the old tree.
480
+ const frag = tpl.content.cloneNode(true);
481
+ loadingOverlay = Array.from(frag.childNodes);
482
+ document.body.appendChild(frag);
483
+ }
484
+ if (!supportsViewTransitions()) {
485
+ const el = appRoot(document);
486
+ el.style.transition = `opacity ${TRANSITION_MS}ms ease`;
487
+ el.style.opacity = '0';
488
+ }
489
+ }
490
+ function endTransition() {
491
+ for (const n of loadingOverlay) {
492
+ if (n.parentNode)
493
+ n.parentNode.removeChild(n);
494
+ }
495
+ loadingOverlay = [];
496
+ const el = appRoot(document);
497
+ if (el.style.opacity === '0')
498
+ el.style.opacity = '';
499
+ }
500
+ /**
501
+ * Apply `data-view-transition="name"` to `view-transition-name`. Persistent
502
+ * chrome (navbar/sidebar) keeps its name across mutations so it morphs
503
+ * instead of cross-fading.
504
+ */
505
+ function applyViewTransitionNames(root) {
506
+ root.querySelectorAll('[data-view-transition]').forEach((el) => {
507
+ const name = el.getAttribute('data-view-transition');
508
+ if (name)
509
+ el.style.viewTransitionName = name;
510
+ });
511
+ }
512
+ // Document reconciliation
513
+ /** Diff stylesheet <link>s by absolute URL (base-path and format safe). */
514
+ function reconcileStylesheets(doc, baseUrl) {
515
+ const newStyles = doc.querySelectorAll('link[rel="stylesheet"]');
516
+ const newHrefs = new Set();
517
+ newStyles.forEach((s) => {
518
+ const href = s.getAttribute('href');
519
+ if (href)
520
+ newHrefs.add(new URL(href, baseUrl).href);
521
+ });
522
+ document.querySelectorAll('link[rel="stylesheet"]').forEach((l) => {
523
+ const abs = l.href;
524
+ if (abs && !newHrefs.has(abs))
525
+ l.remove();
526
+ });
527
+ const existing = new Set();
528
+ document.querySelectorAll('link[rel="stylesheet"]').forEach((l) => existing.add(l.href));
529
+ newStyles.forEach((s) => {
530
+ const href = s.getAttribute('href');
531
+ if (!href)
532
+ return;
533
+ const abs = new URL(href, baseUrl).href;
534
+ if (!existing.has(abs)) {
535
+ const link = document.createElement('link');
536
+ link.rel = 'stylesheet';
537
+ link.href = abs;
538
+ document.head.appendChild(link);
305
539
  }
540
+ });
541
+ }
542
+ // Document-level <head> tags that change per page and must follow a swap.
543
+ const HEAD_SYNC_SEL = 'meta[name="description"], meta[name="robots"], meta[property^="og:"], meta[name^="twitter:"], link[rel="canonical"], script[type="application/ld+json"]';
544
+ function reconcileHeadMeta(doc) {
545
+ document.head.querySelectorAll(HEAD_SYNC_SEL).forEach((el) => el.remove());
546
+ doc.head.querySelectorAll(HEAD_SYNC_SEL).forEach((el) => {
547
+ document.head.appendChild(document.importNode(el, true));
548
+ });
549
+ }
550
+ function scriptsToLoad(doc, baseUrl) {
551
+ const keep = new Set();
552
+ document.querySelectorAll('script[src]:not([data-krate-spa])').forEach((s) => keep.add(s.src));
553
+ const out = [];
554
+ doc.querySelectorAll('script[src]').forEach((s) => {
555
+ const src = s.getAttribute('src');
556
+ if (!src)
557
+ return;
558
+ const t = (s.getAttribute('type') || '').toLowerCase();
559
+ if (t && t !== 'module' && t !== 'text/javascript' && t !== 'application/javascript')
560
+ return;
561
+ const abs = resolveSrc(src, baseUrl);
562
+ if (!keep.has(abs) && !out.includes(abs))
563
+ out.push(abs);
564
+ });
565
+ return out;
566
+ }
567
+ function loadScript(src) {
568
+ return new Promise((resolve) => {
569
+ const s = document.createElement('script');
570
+ s.src = src;
571
+ // Only page scripts are disposable across navigations; the shared runtime
572
+ // chunk stays in place.
573
+ if (!RUNTIME_CHUNK_RE.test(src))
574
+ s.setAttribute('data-krate-spa', '');
575
+ s.onload = () => resolve(true);
576
+ s.onerror = () => resolve(false);
577
+ document.body.appendChild(s);
578
+ });
579
+ }
580
+ // Scroll, focus, announcements
581
+ function hashTarget(hash) {
582
+ if (!hash || hash === '#')
583
+ return null;
584
+ let id = hash.slice(1);
585
+ try {
586
+ id = decodeURIComponent(id);
306
587
  }
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;
315
- }
316
- catch {
317
- /* ignore */
318
- }
588
+ catch {
589
+ /* keep raw */
590
+ }
591
+ return document.getElementById(id) || document.getElementsByName(id)[0] || null;
592
+ }
593
+ function scrollToHash(hash) {
594
+ const el = hashTarget(hash);
595
+ if (!el)
596
+ return false;
597
+ try {
598
+ el.scrollIntoView({ block: 'start' });
599
+ }
600
+ catch {
601
+ /* ignore */
602
+ }
603
+ return true;
604
+ }
605
+ function applyScroll(url, req) {
606
+ if (req.kind === 'pop') {
607
+ const saved = req.restoreKey ? scrollPositions.get(req.restoreKey) : undefined;
608
+ if (saved !== undefined) {
609
+ window.scrollTo(0, saved);
610
+ return;
319
611
  }
320
- return typeof document.startViewTransition === 'function';
321
612
  }
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();
335
- });
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);
613
+ const hash = new URL(url, location.href).hash;
614
+ if (scrollToHash(hash))
615
+ return;
616
+ if (req.scroll && req.kind !== 'refresh')
617
+ window.scrollTo(0, 0);
618
+ }
619
+ let focusedRoot = null;
620
+ /** Move focus to the content root after navigation (a11y). */
621
+ function focusContent() {
622
+ const active = document.activeElement;
623
+ // Focus inside a persisted region (e.g. a search box in a layout) stays put.
624
+ if (active && active !== document.body && active.isConnected && active !== focusedRoot)
625
+ return;
626
+ const root = appRoot(document);
627
+ if (!root.hasAttribute('tabindex')) {
628
+ root.setAttribute('tabindex', '-1');
629
+ focusedRoot = root;
630
+ root.addEventListener('blur', () => {
631
+ if (focusedRoot === root) {
632
+ root.removeAttribute('tabindex');
633
+ focusedRoot = null;
348
634
  }
349
- });
635
+ }, { once: true });
350
636
  }
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
- });
637
+ try {
638
+ root.focus({ preventScroll: true });
362
639
  }
363
- /** Move focus to the content root after navigation (a11y). */
364
- function focusContent() {
365
- const root = findContentRoot(document);
366
- if (!root)
367
- return;
368
- if (!root.hasAttribute('tabindex'))
369
- root.setAttribute('tabindex', '-1');
640
+ catch {
641
+ /* ignore */
642
+ }
643
+ }
644
+ const ANNOUNCER_ID = '__krate-route-announcer';
645
+ function announce() {
646
+ let el = document.getElementById(ANNOUNCER_ID);
647
+ if (!el) {
648
+ el = document.createElement('div');
649
+ el.id = ANNOUNCER_ID;
650
+ el.setAttribute('aria-live', 'assertive');
651
+ el.setAttribute('aria-atomic', 'true');
652
+ el.setAttribute('role', 'status');
653
+ 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');
654
+ document.body.appendChild(el);
655
+ }
656
+ const h1 = appRoot(document).querySelector('h1');
657
+ const text = document.title || (h1 && h1.textContent ? h1.textContent.trim() : '') || stripBase(location.pathname);
658
+ el.textContent = text;
659
+ }
660
+ /**
661
+ * Marks links matching the current route. An exact match gets
662
+ * aria-current="page" and data-krate-active="exact"; a link to an ancestor
663
+ * segment ("/docs" while on "/docs/intro", but never "/docs-old") gets
664
+ * data-krate-active="segment" so navigation sections can be styled.
665
+ */
666
+ function updateActiveLinks() {
667
+ const path = normPath(stripBase(location.pathname));
668
+ document.querySelectorAll('a[data-krate-link]').forEach((a) => {
669
+ const href = a.getAttribute('href');
670
+ let target = '';
370
671
  try {
371
- root.focus({ preventScroll: true });
672
+ target = href ? normPath(stripBase(new URL(href, location.href).pathname)) : '';
372
673
  }
373
674
  catch {
374
- try {
375
- root.focus();
376
- }
377
- catch {
378
- /* ignore */
379
- }
675
+ target = '';
380
676
  }
677
+ let active = '';
678
+ if (target && target === path)
679
+ active = 'exact';
680
+ else if (target && target !== '/' && path.startsWith(target + '/'))
681
+ active = 'segment';
682
+ if (active === 'exact')
683
+ a.setAttribute('aria-current', 'page');
684
+ else
685
+ a.removeAttribute('aria-current');
686
+ if (active)
687
+ a.setAttribute('data-krate-active', active);
688
+ else
689
+ a.removeAttribute('data-krate-active');
690
+ });
691
+ }
692
+ function fetchErrorPage(path) {
693
+ const url = basePath() + path;
694
+ if (errorPageCache.has(url))
695
+ return Promise.resolve(errorPageCache.get(url) ?? null);
696
+ return fetch(url, { headers: { Accept: 'text/html' }, credentials: 'same-origin' })
697
+ .then(async (res) => {
698
+ const html = res.ok ? await res.text() : null;
699
+ const out = html && looksLikeHTML(html) ? html : null;
700
+ errorPageCache.set(url, out);
701
+ return out;
702
+ })
703
+ .catch(() => null);
704
+ }
705
+ async function loadDocument(req, signal) {
706
+ const key = cacheKey(req.url);
707
+ if (!req.bypassCache) {
708
+ const inflight = prefetchInflight.get(key);
709
+ if (inflight)
710
+ await inflight;
711
+ if (signal.aborted)
712
+ return { ok: false, aborted: true };
713
+ const hit = cacheTake(key);
714
+ if (hit)
715
+ return { ok: true, doc: { html: hit.html, url: hit.url, status: hit.status } };
716
+ }
717
+ let res;
718
+ try {
719
+ res = await fetch(key, {
720
+ headers: { Accept: 'text/html' },
721
+ credentials: 'same-origin',
722
+ signal,
723
+ cache: req.bypassCache ? 'no-cache' : 'default',
724
+ });
725
+ }
726
+ catch (err) {
727
+ if (err?.name === 'AbortError' || signal.aborted)
728
+ return { ok: false, aborted: true };
729
+ // Network failure: apps can cancel the hard-reload fallback (e.g. to show
730
+ // an offline banner) by calling preventDefault on the event.
731
+ const proceed = dispatch('krate:navigate-error', { url: req.url, status: 0, error: err }, true);
732
+ if (!proceed)
733
+ return { ok: false, aborted: true };
734
+ return { ok: false, hard: req.url };
381
735
  }
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'))
736
+ const finalUrl = res.url || key;
737
+ if (new URL(finalUrl, location.href).origin !== location.origin) {
738
+ return { ok: false, hard: finalUrl };
739
+ }
740
+ const ct = res.headers.get('content-type') || '';
741
+ let body = '';
742
+ try {
743
+ body = await res.text();
744
+ }
745
+ catch (err) {
746
+ if (err?.name === 'AbortError' || signal.aborted)
747
+ return { ok: false, aborted: true };
748
+ body = '';
749
+ }
750
+ if (signal.aborted)
751
+ return { ok: false, aborted: true };
752
+ const html = isHTMLType(ct) || (ct === '' && looksLikeHTML(body));
753
+ // Preserve the hash of the requested URL across redirects.
754
+ const hash = new URL(req.url, location.href).hash;
755
+ const target = hash && !new URL(finalUrl).hash ? finalUrl + hash : finalUrl;
756
+ if (res.ok) {
757
+ // A non-HTML response (file download, JSON, PDF) is not a page: let the
758
+ // browser handle it.
759
+ if (!html)
760
+ return { ok: false, hard: target };
761
+ return { ok: true, doc: { html: body, url: target, status: res.status } };
762
+ }
763
+ dispatch('krate:navigate-error', { url: req.url, status: res.status });
764
+ // The server rendered an error document for this URL: show it in place.
765
+ if (html && looksLikeHTML(body))
766
+ return { ok: true, doc: { html: body, url: target, status: res.status } };
767
+ let fallback = null;
768
+ if (res.status === 404 || res.status === 410)
769
+ fallback = await fetchErrorPage('/404.html');
770
+ else if (res.status >= 500)
771
+ fallback = await fetchErrorPage('/500.html');
772
+ if (signal.aborted)
773
+ return { ok: false, aborted: true };
774
+ if (fallback)
775
+ return { ok: true, doc: { html: fallback, url: target, status: res.status } };
776
+ // Other statuses (401, 403, 429, ...) without an HTML body: the browser
777
+ // shows the real response.
778
+ return { ok: false, hard: target };
779
+ }
780
+ async function runNavigation(req) {
781
+ const from = location.href;
782
+ if (req.kind !== 'pop') {
783
+ const proceed = dispatch('krate:navigate-start', { url: req.url, from, kind: req.kind }, true);
784
+ if (!proceed)
389
785
  return;
390
- 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);
786
+ }
787
+ else {
788
+ dispatch('krate:navigate-start', { url: req.url, from, kind: req.kind });
789
+ }
790
+ const seq = ++navSeq;
791
+ if (pendingAbort)
792
+ pendingAbort.abort();
793
+ const ctrl = new AbortController();
794
+ pendingAbort = ctrl;
795
+ setStatus('loading');
796
+ const hasCached = !req.bypassCache && prefetchCache.has(cacheKey(req.url));
797
+ if (!hasCached)
798
+ beginTransition();
799
+ let result;
800
+ try {
801
+ result = await loadDocument(req, ctrl.signal);
802
+ }
803
+ finally {
804
+ if (pendingAbort === ctrl)
805
+ pendingAbort = undefined;
806
+ }
807
+ if (seq !== navSeq)
808
+ return; // superseded by a newer navigation
809
+ if (!result.ok) {
810
+ endTransition();
811
+ setStatus('idle');
812
+ if ('hard' in result)
813
+ hardNavigate(result.hard, req.kind === 'replace' || req.kind === 'refresh');
814
+ return;
815
+ }
816
+ await commitDocument(result.doc, req, seq);
817
+ }
818
+ async function commitDocument(loaded, req, seq) {
819
+ const doc = new DOMParser().parseFromString(loaded.html, 'text/html');
820
+ const url = loaded.url;
821
+ const newRoot = appRoot(doc);
822
+ const oldRoot = appRoot(document);
823
+ // Save the position of the entry we are leaving (pop saves in the handler).
824
+ if (req.kind === 'push')
825
+ saveScroll(currentKey);
826
+ const newChain = readRouteChain(doc);
827
+ const plan = planSwap(currentChain, newChain, location.href, url, doc);
828
+ const mutate = () => {
829
+ const title = doc.querySelector('title');
830
+ if (title)
831
+ document.title = title.textContent || '';
832
+ const g = globalThis;
833
+ if (plan.keep.length > 0 && typeof g.krateDisposeExcept === 'function')
834
+ g.krateDisposeExcept(plan.keep);
835
+ else if (typeof g.disposeAll === 'function')
836
+ g.disposeAll();
837
+ if (plan.region) {
838
+ // Only the deepest boundary that differs is replaced; the kept layouts'
839
+ // DOM (and its state, focus and scroll containers) stays in place.
840
+ const { live, next } = plan.region;
841
+ clearBetween(live[0], live[1]);
842
+ const nodes = between(next[0], next[1]).map((n) => document.importNode(n, true));
843
+ for (const n of nodes)
844
+ live[1].parentNode.insertBefore(n, live[1]);
845
+ for (const sl of plan.slots) {
846
+ clearBetween(sl.live[0], sl.live[1]);
847
+ for (const n of between(sl.next[0], sl.next[1]))
848
+ sl.live[1].parentNode.insertBefore(document.importNode(n, true), sl.live[1]);
849
+ }
850
+ syncLoadingTemplate(oldRoot, newRoot);
408
851
  }
409
- catch {
410
- /* ignore */
852
+ else {
853
+ const nodes = Array.from(newRoot.childNodes).map((n) => document.importNode(n, true));
854
+ oldRoot.replaceChildren(...nodes);
411
855
  }
856
+ currentChain = plan.chain;
857
+ // Detached slot content of earlier intercepts belonged to the old page.
858
+ interceptSnapshots.clear();
859
+ reconcileStylesheets(doc, url);
860
+ reconcileHeadMeta(doc);
861
+ applyViewTransitionNames(document);
862
+ };
863
+ await runMutation(mutate);
864
+ if (seq !== navSeq)
865
+ return;
866
+ endTransition();
867
+ // History: the DOM now shows the new route, so the URL follows it before
868
+ // any page script runs.
869
+ if (req.kind === 'push') {
870
+ currentKey = newKey();
871
+ history.pushState(historyEntry(currentKey, req.state), '', url);
412
872
  }
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);
873
+ else if (req.kind === 'replace') {
874
+ scrollPositions.delete(currentKey);
875
+ currentKey = newKey();
876
+ history.replaceState(historyEntry(currentKey, req.state), '', url);
419
877
  }
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));
426
- });
878
+ else if (req.kind === 'refresh') {
879
+ if (url !== location.href)
880
+ history.replaceState(history.state, '', url);
881
+ }
882
+ else if (req.restoreKey) {
883
+ currentKey = req.restoreKey;
884
+ }
885
+ renderedPath = pathOf(location.href);
886
+ docPath = renderedPath;
887
+ syncParams(doc);
888
+ applyScroll(url, req);
889
+ if (req.kind !== 'pop' && req.kind !== 'refresh')
890
+ focusContent();
891
+ if (req.kind !== 'refresh')
892
+ announce();
893
+ updateActiveLinks();
894
+ dispatch('krate:navigate', { url: location.href, status: loaded.status });
895
+ notifyNavigation(location.href);
896
+ setStatus('idle');
897
+ // Page scripts re-run against the new DOM; the hydration code of kept
898
+ // layouts is skipped (krateEnterScope) because their bindings are live.
899
+ document.querySelectorAll('script[data-krate-spa]').forEach((s) => s.remove());
900
+ const srcs = scriptsToLoad(doc, url);
901
+ keepScopes(plan.skip);
902
+ const results = await Promise.all(srcs.map(loadScript));
903
+ keepScopes([]);
904
+ if (seq !== navSeq)
905
+ return;
906
+ if (results.some((ok) => !ok)) {
907
+ // A page chunk failed to load: the route would stay half-mounted, so do a
908
+ // full load of the document instead (loudly, through the error event).
909
+ dispatch('krate:navigate-error', { url: location.href, status: loaded.status, error: 'script-load' });
910
+ hardNavigate(location.href, true);
911
+ return;
427
912
  }
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;
913
+ refreshPageBindings();
914
+ dispatch('krate:navigate-end', { url: location.href, status: loaded.status });
915
+ }
916
+ /**
917
+ * Runs the DOM mutation, inside a View Transition when supported. Resolves
918
+ * once the mutation has been applied (the transition's update callback has
919
+ * run), so callers can touch the new DOM, history and focus afterwards.
920
+ */
921
+ function runMutation(mutate) {
922
+ if (!supportsViewTransitions()) {
923
+ mutate();
924
+ return Promise.resolve();
925
+ }
926
+ let ran = false;
927
+ const once = () => {
928
+ if (ran)
436
929
  return;
930
+ ran = true;
931
+ mutate();
932
+ };
933
+ try {
934
+ const vt = document.startViewTransition(once);
935
+ if (vt && vt.finished && typeof vt.finished.catch === 'function')
936
+ vt.finished.catch(() => { });
937
+ const done = vt && vt.updateCallbackDone;
938
+ if (done && typeof done.then === 'function') {
939
+ return done.then(() => once(), () => once());
437
940
  }
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();
468
- }
941
+ }
942
+ catch {
943
+ /* fall through */
944
+ }
945
+ once();
946
+ return Promise.resolve();
947
+ }
948
+ let currentChain = [];
949
+ function readRouteChain(doc) {
950
+ const el = doc.getElementById('__krate_route');
951
+ if (!el)
952
+ return [];
953
+ try {
954
+ const info = JSON.parse(el.textContent || '{}');
955
+ return Array.isArray(info.chain) ? info.chain : [];
956
+ }
957
+ catch {
958
+ devWarn('unreadable #__krate_route route info; layouts will be remounted');
959
+ return [];
960
+ }
961
+ }
962
+ function segmentKey(url, depth) {
963
+ const segs = stripBase(new URL(url, location.href).pathname).split('/').filter(Boolean);
964
+ return (depth < 0 ? segs : segs.slice(0, depth)).join('/');
965
+ }
966
+ /** Finds the <!--kl:ID--> ... <!--/kl:ID--> (or ks: slot) sibling pair under root. */
967
+ function findBoundary(root, id, kind = 'kl:') {
968
+ const doc = root.ownerDocument || root;
969
+ const walker = doc.createTreeWalker(root, 128 /* NodeFilter.SHOW_COMMENT */);
970
+ const open = kind + id;
971
+ const close = '/' + kind + id;
972
+ while (walker.nextNode()) {
973
+ const c = walker.currentNode;
974
+ if (c.nodeValue !== open)
975
+ continue;
976
+ for (let n = c.nextSibling; n; n = n.nextSibling) {
977
+ if (n.nodeType === 8 && n.nodeValue === close)
978
+ return [c, n];
469
979
  }
470
- else {
471
- runMutation();
980
+ return null;
981
+ }
982
+ return null;
983
+ }
984
+ function between(start, end) {
985
+ const out = [];
986
+ for (let n = start.nextSibling; n && n !== end; n = n.nextSibling)
987
+ out.push(n);
988
+ return out;
989
+ }
990
+ function clearBetween(start, end) {
991
+ const dispose = globalThis.disposeNode;
992
+ for (const n of between(start, end)) {
993
+ n.parentNode.removeChild(n);
994
+ if (typeof dispose === 'function')
995
+ dispose(n);
996
+ }
997
+ }
998
+ function syncLoadingTemplate(liveRoot, nextRoot) {
999
+ const sel = ':scope > template[data-krate-loading]';
1000
+ liveRoot.querySelectorAll(sel).forEach((t) => t.remove());
1001
+ nextRoot.querySelectorAll(sel).forEach((t) => liveRoot.appendChild(document.importNode(t, true)));
1002
+ }
1003
+ function keepScopes(ids) {
1004
+ const fn = globalThis.krateKeepScopes;
1005
+ if (typeof fn === 'function')
1006
+ fn(ids);
1007
+ }
1008
+ /**
1009
+ * Compares the layout chains of the current and next documents. The longest
1010
+ * common prefix of persistable layouts (same file, same URL segments) stays
1011
+ * mounted, and only the children region of the deepest kept layout is
1012
+ * replaced. Templates always end the prefix, so they remount on every
1013
+ * navigation through them. A shared layout that cannot be kept is reported
1014
+ * in dev (never silently). Slots of kept layouts are swapped when the new
1015
+ * route has a matching slot page and otherwise keep their content (a soft
1016
+ * navigation never resets a slot to its default).
1017
+ */
1018
+ function planSwap(oldChain, newChain, fromUrl, toUrl, doc) {
1019
+ const full = { keep: [], skip: [], region: null, slots: [], chain: newChain };
1020
+ let k = 0;
1021
+ while (k < oldChain.length && k < newChain.length) {
1022
+ const a = oldChain[k];
1023
+ const b = newChain[k];
1024
+ if (a.id !== b.id || a.k !== 'layout' || b.k !== 'layout')
1025
+ break;
1026
+ if (segmentKey(fromUrl, a.d) !== segmentKey(toUrl, b.d))
1027
+ break;
1028
+ if (!a.p || !b.p) {
1029
+ devWarn(`layout ${b.f || b.id} is remounted on this navigation: ${b.why || a.why || 'not persistable'}`);
1030
+ break;
472
1031
  }
473
- // Load new scripts, then rehydrate
474
- loadScripts(scripts, url).then(() => {
475
- try {
476
- rehydrate();
477
- observePrefetchLinks();
1032
+ k++;
1033
+ }
1034
+ if (k === 0)
1035
+ return full;
1036
+ if (typeof globalThis.krateDisposeExcept !== 'function') {
1037
+ devWarn('the runtime has no krateDisposeExcept; layouts are remounted');
1038
+ return full;
1039
+ }
1040
+ const id = newChain[k - 1].id;
1041
+ const live = findBoundary(appRoot(document), id);
1042
+ const next = findBoundary(appRoot(doc), id);
1043
+ if (!live || !next) {
1044
+ devWarn(`layout ${newChain[k - 1].f || id} boundary markers are missing; the whole page is swapped`);
1045
+ return full;
1046
+ }
1047
+ const keep = oldChain.slice(0, k).map((e) => e.id);
1048
+ const skip = keep.slice();
1049
+ const slots = [];
1050
+ const chain = newChain.slice();
1051
+ for (let j = 0; j < k; j++) {
1052
+ const oldSlots = oldChain[j].s || [];
1053
+ const merged = [];
1054
+ for (const ns of newChain[j].s || []) {
1055
+ const os = oldSlots.find((x) => x.key === ns.key);
1056
+ const liveSlot = findBoundary(appRoot(document), ns.key, 'ks:');
1057
+ const nextSlot = findBoundary(appRoot(doc), ns.key, 'ks:');
1058
+ if (os && liveSlot && (ns.src !== 'page' || !nextSlot)) {
1059
+ // No matching slot page for the new URL: the slot keeps its content.
1060
+ keep.push(os.scope);
1061
+ skip.push(os.scope, ns.scope);
1062
+ merged.push({ ...ns, scope: os.scope, src: os.src });
1063
+ continue;
478
1064
  }
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;
1065
+ if (liveSlot && nextSlot) {
1066
+ slots.push({ live: liveSlot, next: nextSlot });
1067
+ merged.push(ns);
1068
+ continue;
493
1069
  }
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);
1070
+ devWarn(`slot @${ns.n} markers are missing; the whole page is swapped`);
1071
+ return full;
501
1072
  }
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);
1073
+ chain[j] = { ...newChain[j], s: merged };
1074
+ }
1075
+ return { keep, skip, region: { live, next }, slots, chain };
1076
+ }
1077
+ const interceptSnapshots = new Map();
1078
+ /** pathname+search of the last full document (the children route). */
1079
+ let docPath = '';
1080
+ function parsePattern(pattern) {
1081
+ const t = pattern.replace(/^\/+|\/+$/g, '');
1082
+ if (!t)
1083
+ return [];
1084
+ return t.split('/').map((p) => {
1085
+ if (p.startsWith('[[...') && p.endsWith(']]'))
1086
+ return { kind: 3, text: p.slice(5, -2) };
1087
+ if (p.startsWith('[...') && p.endsWith(']'))
1088
+ return { kind: 2, text: p.slice(4, -1) };
1089
+ if (p.startsWith('[') && p.endsWith(']'))
1090
+ return { kind: 1, text: p.slice(1, -1) };
1091
+ return { kind: 0, text: p };
1092
+ });
1093
+ }
1094
+ /** Mirrors the compiler's matchRoutePattern (static, [param], [...all], [[...opt]]). */
1095
+ export function matchRoutePattern(path, pattern) {
1096
+ const segs = parsePattern(pattern);
1097
+ const t = path.replace(/^\/+|\/+$/g, '');
1098
+ const parts = t ? t.split('/') : [];
1099
+ const params = {};
1100
+ for (let i = 0; i < segs.length; i++) {
1101
+ const s = segs[i];
1102
+ if (s.kind >= 2) {
1103
+ if (i !== segs.length - 1)
1104
+ return null;
1105
+ const rest = parts.slice(i);
1106
+ if (s.kind === 2 && rest.length === 0)
1107
+ return null;
1108
+ if (rest.some((r) => r === ''))
1109
+ return null;
1110
+ params[s.text] = rest.map(decodeSeg).join('/');
1111
+ return params;
1112
+ }
1113
+ if (i >= parts.length)
1114
+ return null;
1115
+ if (s.kind === 1) {
1116
+ if (!parts[i])
1117
+ return null;
1118
+ params[s.text] = decodeSeg(parts[i]);
1119
+ }
1120
+ else if (decodeSeg(parts[i]) !== s.text) {
1121
+ return null;
1122
+ }
1123
+ }
1124
+ return parts.length === segs.length ? params : null;
1125
+ }
1126
+ function decodeSeg(s) {
1127
+ try {
1128
+ return decodeURIComponent(s);
1129
+ }
1130
+ catch {
1131
+ return s;
1132
+ }
1133
+ }
1134
+ /** Negative when pattern a is more specific than b (static > dynamic > catch-all > optional). */
1135
+ export function compareRouteSpecificity(a, b) {
1136
+ const sa = parsePattern(a);
1137
+ const sb = parsePattern(b);
1138
+ for (let i = 0; i < sa.length && i < sb.length; i++) {
1139
+ if (sa[i].kind !== sb[i].kind)
1140
+ return sa[i].kind - sb[i].kind;
1141
+ if (sa[i].kind === 0 && sa[i].text !== sb[i].text)
1142
+ return sa[i].text < sb[i].text ? -1 : 1;
1143
+ }
1144
+ if (sa.length !== sb.length)
1145
+ return sb.length - sa.length;
1146
+ return a < b ? -1 : a > b ? 1 : 0;
1147
+ }
1148
+ function findIntercept(url) {
1149
+ const path = stripBase(new URL(url, location.href).pathname).replace(/^\/+|\/+$/g, '');
1150
+ let best = null;
1151
+ for (const entry of currentChain) {
1152
+ for (const slot of entry.s || []) {
1153
+ for (const pattern of slot.i || []) {
1154
+ if (!matchRoutePattern(path, pattern))
1155
+ continue;
1156
+ if (!best || compareRouteSpecificity(pattern, best.pattern) < 0) {
1157
+ best = { hit: { entry, slot, path }, pattern };
508
1158
  }
509
- scrollPositions.set(prevUrl, window.scrollY);
510
1159
  }
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);
1160
+ }
1161
+ }
1162
+ if (best && !findBoundary(appRoot(document), best.hit.slot.key, 'ks:'))
1163
+ return null;
1164
+ return best ? best.hit : null;
1165
+ }
1166
+ function setSlotInfo(key, next) {
1167
+ 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);
1168
+ }
1169
+ function syncParams(doc) {
1170
+ for (const script of Array.from(doc.querySelectorAll('script:not([src])'))) {
1171
+ const m = /window\.__KRATE_PARAMS__\s*=\s*(\{[\s\S]*?\})\s*;?\s*$/.exec(script.textContent || '');
1172
+ if (!m)
1173
+ continue;
526
1174
  try {
527
- const el = document.querySelector(hash);
528
- if (el) {
529
- el.scrollIntoView({ behavior: 'smooth', block: 'start' });
530
- return true;
531
- }
1175
+ globalThis.__KRATE_PARAMS__ = JSON.parse(m[1]);
532
1176
  }
533
1177
  catch {
534
- return false;
1178
+ /* ignore */
535
1179
  }
536
- return false;
1180
+ return;
537
1181
  }
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))
1182
+ delete globalThis.__KRATE_PARAMS__;
1183
+ }
1184
+ function disposeScopes(ids) {
1185
+ const fn = globalThis.krateDisposeScopes;
1186
+ if (typeof fn === 'function')
1187
+ fn(ids);
1188
+ }
1189
+ /**
1190
+ * Soft navigation to a URL a mounted slot intercepts: the slot shows the
1191
+ * intercepting fragment while the URL becomes the target and the rest of
1192
+ * the page (including the children route) stays as it is. The slot's
1193
+ * previous content is kept detached (alive) and restored by going back.
1194
+ */
1195
+ async function runIntercept(req, hit) {
1196
+ const from = location.href;
1197
+ if (req.kind !== 'pop') {
1198
+ if (!dispatch('krate:navigate-start', { url: req.url, from, kind: req.kind, intercept: hit.slot.n }, true))
547
1199
  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
1200
  }
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);
1201
+ const seq = ++navSeq;
1202
+ if (pendingAbort)
1203
+ pendingAbort.abort();
1204
+ const ctrl = new AbortController();
1205
+ pendingAbort = ctrl;
1206
+ setStatus('loading');
1207
+ const fragURL = location.origin + basePath() + '/' + INTERCEPT_PREFIX + '/' + hit.slot.key + (hit.path ? '/' + hit.path : '');
1208
+ let html = '';
1209
+ let ok = false;
1210
+ try {
1211
+ const res = await fetch(fragURL, {
1212
+ headers: { Accept: 'text/html' },
1213
+ credentials: 'same-origin',
1214
+ signal: ctrl.signal,
1215
+ cache: req.bypassCache ? 'no-cache' : 'default',
598
1216
  });
1217
+ html = await res.text();
1218
+ ok = res.ok && (isHTMLType(res.headers.get('content-type') || '') || looksLikeHTML(html));
1219
+ if (!ok)
1220
+ dispatch('krate:navigate-error', { url: req.url, status: res.status, intercept: hit.slot.n });
599
1221
  }
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);
1222
+ catch (err) {
1223
+ if (err?.name === 'AbortError' || ctrl.signal.aborted)
673
1224
  return;
1225
+ dispatch('krate:navigate-error', { url: req.url, status: 0, error: err, intercept: hit.slot.n });
1226
+ }
1227
+ finally {
1228
+ if (pendingAbort === ctrl)
1229
+ pendingAbort = undefined;
1230
+ }
1231
+ if (seq !== navSeq)
1232
+ return;
1233
+ const doc = ok ? new DOMParser().parseFromString(html, 'text/html') : null;
1234
+ const next = doc ? findBoundary(appRoot(doc), hit.slot.key, 'ks:') : null;
1235
+ const live = findBoundary(appRoot(document), hit.slot.key, 'ks:');
1236
+ let frag = null;
1237
+ try {
1238
+ const el = doc && doc.getElementById('__krate_route');
1239
+ frag = el ? JSON.parse(el.textContent || '{}').frag || null : null;
1240
+ }
1241
+ catch {
1242
+ frag = null;
1243
+ }
1244
+ if (!doc || !next || !live || !frag || frag.key !== hit.slot.key || !frag.scope) {
1245
+ // The fragment is missing or malformed: show the real page instead,
1246
+ // loudly (the error event above, and a console warning).
1247
+ try {
1248
+ console.warn(`[krate router] intercepting route for ${req.url} (slot @${hit.slot.n}) could not be loaded; navigating to the page`);
674
1249
  }
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();
1250
+ catch {
1251
+ /* ignore */
680
1252
  }
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
- });
1253
+ setStatus('idle');
1254
+ return runNavigation({ ...req });
725
1255
  }
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))
1256
+ if (req.kind === 'push')
1257
+ saveScroll(currentKey);
1258
+ // Swap the slot content.
1259
+ if (hit.slot.src !== 'intercept') {
1260
+ interceptSnapshots.set(currentKey, { key: hit.slot.key, nodes: between(live[0], live[1]), slot: hit.slot, path: docPath });
1261
+ for (const n of between(live[0], live[1]))
1262
+ n.parentNode.removeChild(n);
1263
+ }
1264
+ else {
1265
+ disposeScopes([hit.slot.scope]);
1266
+ clearBetween(live[0], live[1]);
1267
+ }
1268
+ for (const n of between(next[0], next[1]))
1269
+ live[1].parentNode.insertBefore(document.importNode(n, true), live[1]);
1270
+ // A fragment only adds its stylesheets; the page keeps its own.
1271
+ const existing = new Set();
1272
+ document.querySelectorAll('link[rel="stylesheet"]').forEach((l) => existing.add(l.href));
1273
+ doc.querySelectorAll('link[rel="stylesheet"][href]').forEach((l) => {
1274
+ const abs = new URL(l.getAttribute('href'), fragURL).href;
1275
+ if (existing.has(abs))
733
1276
  return;
734
- e.preventDefault();
735
- const href = a.getAttribute('href');
736
- if (!href)
1277
+ const link = document.createElement('link');
1278
+ link.rel = 'stylesheet';
1279
+ link.href = abs;
1280
+ document.head.appendChild(link);
1281
+ });
1282
+ setSlotInfo(hit.slot.key, { ...hit.slot, scope: frag.scope, src: 'intercept' });
1283
+ const state = { __krate: '', state: req.state === undefined ? null : req.state, __kint: { key: hit.slot.key, base: docPath } };
1284
+ if (req.kind === 'push') {
1285
+ currentKey = newKey();
1286
+ state.__krate = currentKey;
1287
+ history.pushState(state, '', req.url);
1288
+ }
1289
+ else if (req.kind === 'replace') {
1290
+ currentKey = newKey();
1291
+ state.__krate = currentKey;
1292
+ history.replaceState(state, '', req.url);
1293
+ }
1294
+ else if (req.kind === 'pop' && req.restoreKey) {
1295
+ currentKey = req.restoreKey;
1296
+ }
1297
+ renderedPath = pathOf(location.href);
1298
+ syncParams(doc);
1299
+ updateActiveLinks();
1300
+ dispatch('krate:navigate', { url: location.href, status: 200, intercept: hit.slot.n });
1301
+ notifyNavigation(location.href);
1302
+ setStatus('idle');
1303
+ const srcs = scriptsToLoad(doc, fragURL);
1304
+ const results = await Promise.all(srcs.map(loadScript));
1305
+ if (seq !== navSeq)
1306
+ return;
1307
+ if (results.some((r) => !r)) {
1308
+ dispatch('krate:navigate-error', { url: location.href, status: 200, error: 'script-load', intercept: hit.slot.n });
1309
+ hardNavigate(location.href, true);
1310
+ return;
1311
+ }
1312
+ refreshPageBindings();
1313
+ dispatch('krate:navigate-end', { url: location.href, status: 200, intercept: hit.slot.n });
1314
+ }
1315
+ /** Back to the page an intercept was opened from: put the slot content back. */
1316
+ function restoreSnapshot(snap, key) {
1317
+ const live = findBoundary(appRoot(document), snap.key, 'ks:');
1318
+ const current = currentChain.flatMap((e) => e.s || []).find((x) => x.key === snap.key);
1319
+ if (!live || !current || current.src !== 'intercept')
1320
+ return false;
1321
+ disposeScopes([current.scope]);
1322
+ clearBetween(live[0], live[1]);
1323
+ for (const n of snap.nodes)
1324
+ live[1].parentNode.insertBefore(n, live[1]);
1325
+ setSlotInfo(snap.key, snap.slot);
1326
+ interceptSnapshots.delete(key);
1327
+ currentKey = key;
1328
+ renderedPath = pathOf(location.href);
1329
+ const saved = scrollPositions.get(key);
1330
+ if (saved !== undefined)
1331
+ window.scrollTo(0, saved);
1332
+ updateActiveLinks();
1333
+ dispatch('krate:navigate', { url: location.href, status: 200 });
1334
+ notifyNavigation(location.href);
1335
+ emit();
1336
+ return true;
1337
+ }
1338
+ function sameDocument(url) {
1339
+ return pathOf(url) === renderedPath;
1340
+ }
1341
+ /** In-document navigation: only the hash (or nothing) changes. */
1342
+ function hashNavigate(url, req) {
1343
+ saveScroll(currentKey);
1344
+ if (url !== location.href || req.state !== undefined) {
1345
+ if (req.kind === 'replace') {
1346
+ history.replaceState(historyEntry(currentKey || newKey(), req.state), '', url);
1347
+ }
1348
+ else {
1349
+ currentKey = newKey();
1350
+ history.pushState(historyEntry(currentKey, req.state), '', url);
1351
+ }
1352
+ }
1353
+ const hash = new URL(url).hash;
1354
+ if (!scrollToHash(hash) && req.scroll && !hash)
1355
+ window.scrollTo(0, 0);
1356
+ emit();
1357
+ }
1358
+ function start(req) {
1359
+ let u;
1360
+ try {
1361
+ u = new URL(req.url, location.href);
1362
+ }
1363
+ catch {
1364
+ hardNavigate(req.url);
1365
+ return Promise.resolve();
1366
+ }
1367
+ if (u.origin !== location.origin) {
1368
+ hardNavigate(u.href, req.kind === 'replace');
1369
+ return Promise.resolve();
1370
+ }
1371
+ req.url = u.href;
1372
+ if ((req.kind === 'push' || req.kind === 'replace') && sameDocument(u.href) && (u.hash || u.href === location.href)) {
1373
+ hashNavigate(u.href, req);
1374
+ return Promise.resolve();
1375
+ }
1376
+ if (req.kind === 'push' || req.kind === 'replace') {
1377
+ const hit = findIntercept(u.href);
1378
+ if (hit)
1379
+ return runIntercept(req, hit);
1380
+ }
1381
+ return runNavigation(req);
1382
+ }
1383
+ // Event handlers
1384
+ function clickHandler(e) {
1385
+ if (e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey)
1386
+ return;
1387
+ const t = e.target;
1388
+ if (!t || typeof t.closest !== 'function')
1389
+ return;
1390
+ const a = t.closest('a[data-krate-link]');
1391
+ if (!a || !isLocalLink(a))
1392
+ return;
1393
+ const href = a.getAttribute('href');
1394
+ if (!href)
1395
+ return;
1396
+ e.preventDefault();
1397
+ void start({
1398
+ url: new URL(href, location.href).href,
1399
+ kind: a.hasAttribute('data-krate-replace') ? 'replace' : 'push',
1400
+ scroll: a.getAttribute('data-krate-scroll') !== 'false',
1401
+ });
1402
+ }
1403
+ function submitHandler(e) {
1404
+ if (e.defaultPrevented)
1405
+ return;
1406
+ const form = e.target;
1407
+ if (!form || form.tagName !== 'FORM')
1408
+ return;
1409
+ if (form.hasAttribute('data-krate-reload'))
1410
+ return;
1411
+ const submitter = (e.submitter || null);
1412
+ const method = ((submitter && submitter.getAttribute('formmethod')) || form.getAttribute('method') || 'get').toLowerCase();
1413
+ if (method !== 'get')
1414
+ return;
1415
+ const target = (submitter && submitter.getAttribute('formtarget')) || form.getAttribute('target');
1416
+ if (target && target !== '_self')
1417
+ return;
1418
+ const actionAttr = (submitter && submitter.getAttribute('formaction')) || form.getAttribute('action') || '';
1419
+ let action;
1420
+ try {
1421
+ action = new URL(actionAttr || location.href, location.href);
1422
+ }
1423
+ catch {
1424
+ return;
1425
+ }
1426
+ if (action.origin !== location.origin || action.protocol.indexOf('http') !== 0)
1427
+ return;
1428
+ let data;
1429
+ try {
1430
+ data = submitter ? new FormData(form, submitter) : new FormData(form);
1431
+ }
1432
+ catch {
1433
+ data = new FormData(form);
1434
+ if (submitter && submitter.name)
1435
+ data.append(submitter.name, submitter.value);
1436
+ }
1437
+ const params = new URLSearchParams();
1438
+ for (const [k, v] of data.entries()) {
1439
+ // A file input cannot be encoded into a GET query; leave it to the browser.
1440
+ if (typeof v !== 'string')
737
1441
  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 });
1442
+ params.append(k, v);
1443
+ }
1444
+ e.preventDefault();
1445
+ action.search = params.toString();
1446
+ action.hash = '';
1447
+ void start({ url: action.href, kind: 'push', scroll: true });
1448
+ }
1449
+ function popstateHandler(e) {
1450
+ // The URL already changed; remember where the user was on the entry left.
1451
+ saveScroll(currentKey);
1452
+ const key = entryKey(e.state);
1453
+ const url = location.href;
1454
+ if (pathOf(url) === renderedPath) {
1455
+ // Hash-only history step within the rendered document.
1456
+ currentKey = key || currentKey;
1457
+ const saved = key ? scrollPositions.get(key) : undefined;
1458
+ if (saved !== undefined)
1459
+ window.scrollTo(0, saved);
1460
+ else
1461
+ scrollToHash(location.hash);
1462
+ emit();
1463
+ return;
1464
+ }
1465
+ // Back to the page an intercept was opened from.
1466
+ const snap = key ? interceptSnapshots.get(key) : undefined;
1467
+ if (snap && key && snap.path === pathOf(url) && snap.path === docPath && restoreSnapshot(snap, key))
1468
+ return;
1469
+ // Back/forward to an intercepted entry while its base page is still shown.
1470
+ const kint = e.state && typeof e.state === 'object' ? e.state.__kint : null;
1471
+ if (kint && kint.base === docPath) {
1472
+ const hit = findIntercept(url);
1473
+ if (hit && hit.slot.key === kint.key) {
1474
+ void runIntercept({ url, kind: 'pop', scroll: false, restoreKey: key }, hit);
746
1475
  return;
747
1476
  }
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();
1477
+ }
1478
+ void runNavigation({ url, kind: 'pop', scroll: true, restoreKey: key });
1479
+ }
1480
+ function revalidateHandler() {
1481
+ invalidatePrefetchCache();
1482
+ void refresh();
1483
+ }
1484
+ function pagehideHandler() {
1485
+ saveScroll(currentKey);
1486
+ // Hand scroll restoration back to the browser for reloads and cross-document
1487
+ // history steps.
1488
+ try {
1489
+ history.scrollRestoration = 'auto';
1490
+ }
1491
+ catch {
1492
+ /* ignore */
1493
+ }
1494
+ }
1495
+ function pageshowHandler() {
1496
+ try {
1497
+ history.scrollRestoration = 'manual';
1498
+ }
1499
+ catch {
1500
+ /* ignore */
1501
+ }
1502
+ }
1503
+ /** Per-page bindings refreshed after every swap (and by reinitRouter). */
1504
+ function refreshPageBindings() {
1505
+ observePrefetchLinks();
757
1506
  updateActiveLinks();
758
1507
  applyViewTransitionNames(document);
759
- // Expose the SPA navigation to `navigate()` (and any embedded UI).
760
- navigateImpl = (url, opts = {}) => {
761
- let sameOrigin = true;
1508
+ // Mark the page scripts as disposable so they're removed and re-executed
1509
+ // against the fresh DOM on the next navigation.
1510
+ document.querySelectorAll('script[src]').forEach((s) => {
1511
+ if (!RUNTIME_CHUNK_RE.test(s.src))
1512
+ s.setAttribute('data-krate-spa', '');
1513
+ });
1514
+ }
1515
+ // Public API
1516
+ function refresh() {
1517
+ if (!initialized || typeof location === 'undefined') {
1518
+ if (typeof location !== 'undefined')
1519
+ location.reload();
1520
+ return Promise.resolve();
1521
+ }
1522
+ if (renderedPath !== docPath) {
1523
+ // The URL shows an intercepted route: refresh the slot content.
1524
+ const hit = findIntercept(location.href);
1525
+ if (hit && hit.slot.src === 'intercept') {
1526
+ return runIntercept({ url: location.href, kind: 'refresh', scroll: false, bypassCache: true }, hit);
1527
+ }
1528
+ }
1529
+ return runNavigation({ url: location.href, kind: 'refresh', scroll: false, bypassCache: true });
1530
+ }
1531
+ function push(url, opts = {}) {
1532
+ if (!initialized) {
1533
+ if (typeof location !== 'undefined')
1534
+ location.assign(url);
1535
+ return Promise.resolve();
1536
+ }
1537
+ return start({ url, kind: 'push', scroll: opts.scroll !== false, state: opts.state });
1538
+ }
1539
+ function replace(url, opts = {}) {
1540
+ if (!initialized) {
1541
+ if (typeof location !== 'undefined')
1542
+ location.replace(url);
1543
+ return Promise.resolve();
1544
+ }
1545
+ return start({ url, kind: 'replace', scroll: opts.scroll !== false, state: opts.state });
1546
+ }
1547
+ /**
1548
+ * The router API. Every navigation method resolves once the new route's DOM
1549
+ * and URL are in place (page scripts may still be loading).
1550
+ *
1551
+ * - push(url, opts) / replace(url, opts): client navigation.
1552
+ * - back() / forward(): history traversal.
1553
+ * - refresh(): re-fetches the current route (bypassing the prefetch cache)
1554
+ * and swaps it in place, keeping scroll position and history.
1555
+ * - prefetch(url): warms the document (and its page chunk) for a later visit.
1556
+ */
1557
+ export const krateRouter = {
1558
+ push,
1559
+ replace,
1560
+ back() {
1561
+ if (typeof history !== 'undefined')
1562
+ history.back();
1563
+ },
1564
+ forward() {
1565
+ if (typeof history !== 'undefined')
1566
+ history.forward();
1567
+ },
1568
+ refresh,
1569
+ prefetch(url) {
1570
+ if (!initialized || typeof location === 'undefined')
1571
+ return Promise.resolve();
1572
+ let u;
762
1573
  try {
763
- sameOrigin = new URL(url, location.href).origin === location.origin;
1574
+ u = new URL(url, location.href);
764
1575
  }
765
1576
  catch {
766
- sameOrigin = false;
1577
+ return Promise.resolve();
767
1578
  }
768
- if (!sameOrigin) {
769
- location.href = url;
770
- return;
1579
+ if (u.origin !== location.origin)
1580
+ return Promise.resolve();
1581
+ return prefetchPage(u.href);
1582
+ },
1583
+ subscribe: subscribeNavigation,
1584
+ getState: getNavigationState,
1585
+ invalidate: invalidatePrefetchCache,
1586
+ };
1587
+ /**
1588
+ * Programmatic SPA navigation. Falls back to a full page load when the router
1589
+ * has not initialized (e.g. before hydration). Returns false when handled
1590
+ * client-side, true when a full navigation was triggered.
1591
+ */
1592
+ export function navigate(url, opts = {}) {
1593
+ if (initialized) {
1594
+ void (opts.replace ? replace(url, opts) : push(url, opts));
1595
+ return false;
1596
+ }
1597
+ if (typeof location !== 'undefined') {
1598
+ if (opts.replace)
1599
+ location.replace(url);
1600
+ else
1601
+ location.assign(url);
1602
+ }
1603
+ return true;
1604
+ }
1605
+ export function initRouter() {
1606
+ if (typeof document === 'undefined')
1607
+ return;
1608
+ if (initialized) {
1609
+ refreshPageBindings();
1610
+ return;
1611
+ }
1612
+ initialized = true;
1613
+ renderedPath = pathOf(location.href);
1614
+ currentChain = readRouteChain(document);
1615
+ docPath = renderedPath;
1616
+ currentKey = entryKey(history.state) || newKey();
1617
+ if (entryKey(history.state) === undefined) {
1618
+ try {
1619
+ history.replaceState(historyEntry(currentKey, history.state), '', location.href);
771
1620
  }
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', '');
1621
+ catch {
1622
+ /* ignore */
780
1623
  }
781
- });
782
- routerCleanup = () => {
783
- document.removeEventListener('click', clickHandler);
784
- window.removeEventListener('popstate', popstateHandler);
785
- cleanupPrefetch();
786
- navigateImpl = null;
787
- };
1624
+ }
1625
+ try {
1626
+ history.scrollRestoration = 'manual';
1627
+ }
1628
+ catch {
1629
+ /* ignore */
1630
+ }
1631
+ document.addEventListener('click', clickHandler);
1632
+ document.addEventListener('submit', submitHandler);
1633
+ window.addEventListener('popstate', popstateHandler);
1634
+ window.addEventListener('krate:revalidate', revalidateHandler);
1635
+ window.addEventListener('pagehide', pagehideHandler);
1636
+ window.addEventListener('pageshow', pageshowHandler);
1637
+ setupPrefetch();
1638
+ setupSpeculationRules();
1639
+ refreshPageBindings();
788
1640
  }
789
- /** Dispose old effects, re-register router listeners for new page. */
1641
+ /**
1642
+ * Called at the end of every page hydration script. The router keeps its
1643
+ * listeners and caches; only the per-page bindings are refreshed.
1644
+ */
790
1645
  export function reinitRouter() {
791
- if (routerCleanup) {
792
- routerCleanup();
793
- routerCleanup = null;
794
- }
795
- initialized = false;
796
1646
  initRouter();
797
1647
  }
1648
+ /** Tears the router down (tests and embedders that unmount Krate). */
1649
+ export function destroyRouter() {
1650
+ if (!initialized)
1651
+ return;
1652
+ initialized = false;
1653
+ document.removeEventListener('click', clickHandler);
1654
+ document.removeEventListener('submit', submitHandler);
1655
+ window.removeEventListener('popstate', popstateHandler);
1656
+ window.removeEventListener('krate:revalidate', revalidateHandler);
1657
+ window.removeEventListener('pagehide', pagehideHandler);
1658
+ window.removeEventListener('pageshow', pageshowHandler);
1659
+ document.removeEventListener('mouseover', prefetchHoverHandler);
1660
+ document.removeEventListener('focusin', prefetchHoverHandler);
1661
+ for (const timer of prefetchTimers.values())
1662
+ clearTimeout(timer);
1663
+ prefetchTimers = new Map();
1664
+ if (prefetchObserver) {
1665
+ prefetchObserver.disconnect();
1666
+ prefetchObserver = null;
1667
+ }
1668
+ if (pendingAbort)
1669
+ pendingAbort.abort();
1670
+ pendingAbort = undefined;
1671
+ navSeq++;
1672
+ prefetchCache.clear();
1673
+ prefetchInflight.clear();
1674
+ scrollPositions.clear();
1675
+ errorPageCache.clear();
1676
+ listeners.clear();
1677
+ status = 'idle';
1678
+ loadingOverlay = [];
1679
+ currentChain = [];
1680
+ interceptSnapshots.clear();
1681
+ docPath = '';
1682
+ }