@krate/runtime 0.4.0-rc.3 → 0.4.0-rc.5
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/class-helpers.d.ts +4 -4
- package/dist/class-helpers.js +5 -5
- package/dist/context.d.ts +18 -1
- package/dist/context.js +27 -7
- package/dist/dev-overlay.d.ts +37 -0
- package/dist/dev-overlay.js +583 -0
- package/dist/dev-overlay.test.d.ts +1 -0
- package/dist/dev-overlay.test.js +130 -0
- package/dist/dom.js +5 -5
- package/dist/error-overlay.d.ts +1 -1
- package/dist/error-overlay.js +1 -1
- package/dist/index.d.ts +4 -3
- package/dist/index.js +2 -2
- package/dist/krate-dev.js +490 -0
- package/dist/krate-hydrate.js +1 -1
- package/dist/krate-runtime.js +1 -1
- package/dist/reconcile.js +25 -21
- package/dist/reconcile.test.d.ts +1 -0
- package/dist/reconcile.test.js +47 -0
- package/dist/router.d.ts +12 -0
- package/dist/router.js +239 -54
- package/dist/server-jsx-runtime.js +1 -1
- package/dist/server-renderer.js +64 -24
- package/dist/server.js +13 -13
- package/dist/server.test.d.ts +1 -0
- package/dist/server.test.js +26 -0
- package/dist/signal.d.ts +44 -10
- package/dist/signal.js +22 -15
- package/package.json +1 -1
package/dist/router.js
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
|
-
import { reconcileTrees } from './reconcile.js';
|
|
2
1
|
let initialized = false;
|
|
3
2
|
let pendingAbort;
|
|
4
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;
|
|
5
7
|
/** Cache for prefetched page HTML keyed by URL (bounded LRU). */
|
|
6
8
|
const prefetchCache = new Map();
|
|
7
9
|
const PREFETCH_CACHE_MAX = 30;
|
|
@@ -15,6 +17,41 @@ const SCROLL_HISTORY_MAX = 50;
|
|
|
15
17
|
* removed before loading a new page and re-appended.
|
|
16
18
|
*/
|
|
17
19
|
const RUNTIME_CHUNK_RE = /\/chunks\/runtime\.[^/]+\.js$/;
|
|
20
|
+
function runtimeConfig() {
|
|
21
|
+
return globalThis.__KRATE_CFG__ || {};
|
|
22
|
+
}
|
|
23
|
+
/** Normalizes the configured base path to "" or "/prefix" (no trailing slash). */
|
|
24
|
+
function basePath() {
|
|
25
|
+
const bp = runtimeConfig().basePath || '';
|
|
26
|
+
if (!bp || bp === '/')
|
|
27
|
+
return '';
|
|
28
|
+
return '/' + bp.replace(/^\/+|\/+$/g, '');
|
|
29
|
+
}
|
|
30
|
+
/** Strips the base path from a pathname so route comparisons are consistent. */
|
|
31
|
+
function stripBase(pathname) {
|
|
32
|
+
const bp = basePath();
|
|
33
|
+
if (bp && (pathname === bp || pathname.startsWith(bp + '/'))) {
|
|
34
|
+
const rest = pathname.slice(bp.length);
|
|
35
|
+
return rest === '' ? '/' : rest;
|
|
36
|
+
}
|
|
37
|
+
return pathname;
|
|
38
|
+
}
|
|
39
|
+
// Set during initRouter so the exported `navigate()` can drive the SPA router.
|
|
40
|
+
let navigateImpl = null;
|
|
41
|
+
/**
|
|
42
|
+
* Programmatic SPA navigation. Falls back to a full page load when the router
|
|
43
|
+
* has not initialized (e.g. before hydration). Returns false when handled
|
|
44
|
+
* client-side, true when a full navigation was triggered.
|
|
45
|
+
*/
|
|
46
|
+
export function navigate(url, opts = {}) {
|
|
47
|
+
if (navigateImpl) {
|
|
48
|
+
navigateImpl(url, opts);
|
|
49
|
+
return false;
|
|
50
|
+
}
|
|
51
|
+
if (typeof location !== 'undefined')
|
|
52
|
+
location.href = url;
|
|
53
|
+
return true;
|
|
54
|
+
}
|
|
18
55
|
export function initRouter() {
|
|
19
56
|
if (typeof document === 'undefined')
|
|
20
57
|
return;
|
|
@@ -22,7 +59,13 @@ export function initRouter() {
|
|
|
22
59
|
if (initialized)
|
|
23
60
|
return;
|
|
24
61
|
initialized = true;
|
|
25
|
-
|
|
62
|
+
// Reconcile from the app root so navigation between DIFFERENT shells (the
|
|
63
|
+
// marketing layout's <main> and the docs layout's `.docs-page`) swaps the
|
|
64
|
+
// whole shell instead of reconciling mismatched tree shapes (which dropped
|
|
65
|
+
// the docs navbar/sidebar while still loading its CSS). Within one shell the
|
|
66
|
+
// diff preserves unchanged nodes (sidebar/TOC) by key, so docs<->docs stays
|
|
67
|
+
// cheap.
|
|
68
|
+
const CONTENT_SEL = '#root, main, .docs-content';
|
|
26
69
|
const TRANSITION_MS = 150;
|
|
27
70
|
const PREFETCH_DELAY = 200;
|
|
28
71
|
let notFoundHTML = null;
|
|
@@ -134,23 +177,12 @@ export function initRouter() {
|
|
|
134
177
|
}, PREFETCH_DELAY);
|
|
135
178
|
prefetchTimers.set(a, timer);
|
|
136
179
|
}
|
|
137
|
-
function stripHandlerProps(root) {
|
|
138
|
-
const walker = document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT);
|
|
139
|
-
let node = walker.nextNode();
|
|
140
|
-
while (node) {
|
|
141
|
-
const el = node;
|
|
142
|
-
for (const key of Object.keys(el)) {
|
|
143
|
-
if (key.indexOf('__krate_') === 0) {
|
|
144
|
-
delete el[key];
|
|
145
|
-
}
|
|
146
|
-
}
|
|
147
|
-
node = walker.nextNode();
|
|
148
|
-
}
|
|
149
|
-
}
|
|
150
180
|
// Begin the visual transition (fade out + optional loading overlay) while a
|
|
151
181
|
// page fetch is in flight, so navigation doesn't feel artificially delayed.
|
|
152
182
|
let loadingOverlay = null;
|
|
153
183
|
function beginTransition() {
|
|
184
|
+
if (supportsViewTransitions())
|
|
185
|
+
return; // native View Transition handles it
|
|
154
186
|
const oldContent = findContentRoot(document);
|
|
155
187
|
const loadingTemplate = document.querySelector('template[data-krate-loading]');
|
|
156
188
|
if (loadingTemplate && loadingTemplate.content && oldContent) {
|
|
@@ -165,6 +197,8 @@ export function initRouter() {
|
|
|
165
197
|
}
|
|
166
198
|
}
|
|
167
199
|
function endTransition() {
|
|
200
|
+
if (supportsViewTransitions())
|
|
201
|
+
return; // opacity was never touched
|
|
168
202
|
if (loadingOverlay && loadingOverlay.parentNode) {
|
|
169
203
|
loadingOverlay.parentNode.removeChild(loadingOverlay);
|
|
170
204
|
}
|
|
@@ -187,57 +221,180 @@ export function initRouter() {
|
|
|
187
221
|
/* ignore hook failures */
|
|
188
222
|
}
|
|
189
223
|
}
|
|
190
|
-
function
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
const doc = parser.parseFromString(html, 'text/html');
|
|
194
|
-
const newContent = findContentRoot(doc);
|
|
195
|
-
const oldContent = findContentRoot(document);
|
|
196
|
-
if (!newContent || !oldContent) {
|
|
197
|
-
location.href = url;
|
|
198
|
-
return;
|
|
224
|
+
function dispatchNavEvent(name, url) {
|
|
225
|
+
try {
|
|
226
|
+
window.dispatchEvent(new CustomEvent(name, { detail: { url } }));
|
|
199
227
|
}
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
document.title = newTitle.textContent || '';
|
|
203
|
-
// Dispose all active effects before replacing DOM
|
|
204
|
-
if (typeof globalThis.disposeAll === 'function') {
|
|
205
|
-
globalThis.disposeAll();
|
|
228
|
+
catch {
|
|
229
|
+
/* ignore */
|
|
206
230
|
}
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
231
|
+
}
|
|
232
|
+
/** Whether native View Transitions should wrap the SPA mutation. */
|
|
233
|
+
function supportsViewTransitions() {
|
|
234
|
+
if (runtimeConfig().viewTransitions === false)
|
|
235
|
+
return false;
|
|
236
|
+
if (typeof window !== 'undefined' && window.matchMedia) {
|
|
237
|
+
try {
|
|
238
|
+
if (window.matchMedia('(prefers-reduced-motion: reduce)').matches)
|
|
239
|
+
return false;
|
|
240
|
+
}
|
|
241
|
+
catch {
|
|
242
|
+
/* ignore */
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
return typeof document.startViewTransition === 'function';
|
|
246
|
+
}
|
|
247
|
+
/** Diff stylesheet <link>s by absolute URL (base-path and format safe). */
|
|
248
|
+
function reconcileStylesheets(doc) {
|
|
215
249
|
const newStyles = doc.querySelectorAll('link[rel="stylesheet"]');
|
|
216
250
|
const newHrefs = new Set();
|
|
217
251
|
newStyles.forEach((s) => {
|
|
218
252
|
const href = s.getAttribute('href');
|
|
219
253
|
if (href)
|
|
220
|
-
newHrefs.add(href);
|
|
254
|
+
newHrefs.add(new URL(href, location.origin).href);
|
|
221
255
|
});
|
|
222
256
|
document.querySelectorAll('link[rel="stylesheet"]').forEach((l) => {
|
|
223
|
-
const
|
|
224
|
-
if (
|
|
257
|
+
const abs = l.href;
|
|
258
|
+
if (abs && !newHrefs.has(abs))
|
|
225
259
|
l.remove();
|
|
226
|
-
}
|
|
227
|
-
});
|
|
228
|
-
const existingHrefs = new Set();
|
|
229
|
-
document.querySelectorAll('link[rel="stylesheet"]').forEach((l) => {
|
|
230
|
-
existingHrefs.add(l.href);
|
|
231
260
|
});
|
|
261
|
+
const existing = new Set();
|
|
262
|
+
document.querySelectorAll('link[rel="stylesheet"]').forEach((l) => existing.add(l.href));
|
|
232
263
|
newStyles.forEach((s) => {
|
|
233
264
|
const href = s.getAttribute('href');
|
|
234
|
-
if (
|
|
265
|
+
if (!href)
|
|
266
|
+
return;
|
|
267
|
+
const abs = new URL(href, location.origin).href;
|
|
268
|
+
if (!existing.has(abs)) {
|
|
235
269
|
const link = document.createElement('link');
|
|
236
270
|
link.rel = 'stylesheet';
|
|
237
|
-
link.href =
|
|
271
|
+
link.href = abs;
|
|
238
272
|
document.head.appendChild(link);
|
|
239
273
|
}
|
|
240
274
|
});
|
|
275
|
+
}
|
|
276
|
+
/**
|
|
277
|
+
* Apply `data-view-transition="name"` to `view-transition-name`. Persistent
|
|
278
|
+
* chrome (navbar/sidebar) keeps its name across mutations so it morphs
|
|
279
|
+
* instead of cross-fading. Runs at init and after every swap.
|
|
280
|
+
*/
|
|
281
|
+
function applyViewTransitionNames(root) {
|
|
282
|
+
root.querySelectorAll('[data-view-transition]').forEach((el) => {
|
|
283
|
+
const name = el.getAttribute('data-view-transition');
|
|
284
|
+
if (name)
|
|
285
|
+
el.style.viewTransitionName = name;
|
|
286
|
+
});
|
|
287
|
+
}
|
|
288
|
+
/** Move focus to the content root after navigation (a11y). */
|
|
289
|
+
function focusContent() {
|
|
290
|
+
const root = findContentRoot(document);
|
|
291
|
+
if (!root)
|
|
292
|
+
return;
|
|
293
|
+
if (!root.hasAttribute('tabindex'))
|
|
294
|
+
root.setAttribute('tabindex', '-1');
|
|
295
|
+
try {
|
|
296
|
+
root.focus({ preventScroll: true });
|
|
297
|
+
}
|
|
298
|
+
catch {
|
|
299
|
+
try {
|
|
300
|
+
root.focus();
|
|
301
|
+
}
|
|
302
|
+
catch {
|
|
303
|
+
/* ignore */
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
/**
|
|
308
|
+
* Inject Speculation Rules so the browser prefetches same-origin links ahead
|
|
309
|
+
* of hover, where supported. Falls back to the JS prefetch path elsewhere.
|
|
310
|
+
*/
|
|
311
|
+
function setupSpeculationRules() {
|
|
312
|
+
const supports = HTMLScriptElement.supports;
|
|
313
|
+
if (typeof supports !== 'function' || !supports('speculationrules'))
|
|
314
|
+
return;
|
|
315
|
+
try {
|
|
316
|
+
const script = document.createElement('script');
|
|
317
|
+
script.type = 'speculationrules';
|
|
318
|
+
script.textContent = JSON.stringify({
|
|
319
|
+
prefetch: [
|
|
320
|
+
{
|
|
321
|
+
where: {
|
|
322
|
+
and: [
|
|
323
|
+
{ href_matches: '/*' },
|
|
324
|
+
{ not: { href_matches: '/__krate/*' } },
|
|
325
|
+
{ not: { href_matches: '/api/*' } },
|
|
326
|
+
],
|
|
327
|
+
},
|
|
328
|
+
eagerness: 'moderate',
|
|
329
|
+
},
|
|
330
|
+
],
|
|
331
|
+
});
|
|
332
|
+
document.head.appendChild(script);
|
|
333
|
+
}
|
|
334
|
+
catch {
|
|
335
|
+
/* ignore */
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
// The app shell lives in `#root` on every page (see generateHTML), so it is
|
|
339
|
+
// the one stable swap target. Heuristic per-page content roots made different
|
|
340
|
+
// shells/page shapes reconcile incorrectly (dropping the navbar); swapping
|
|
341
|
+
// the whole shell is always correct and the new page's own scripts hydrate it.
|
|
342
|
+
function appRoot(doc) {
|
|
343
|
+
return (doc.getElementById('root') || doc.body);
|
|
344
|
+
}
|
|
345
|
+
// Document-level <head> tags that change per page and must follow a swap.
|
|
346
|
+
const HEAD_SYNC_SEL = 'meta[name="description"], meta[property^="og:"], meta[name^="twitter:"], link[rel="canonical"], script[type="application/ld+json"]';
|
|
347
|
+
function reconcileHeadMeta(doc) {
|
|
348
|
+
document.head.querySelectorAll(HEAD_SYNC_SEL).forEach((el) => el.remove());
|
|
349
|
+
doc.head.querySelectorAll(HEAD_SYNC_SEL).forEach((el) => {
|
|
350
|
+
document.head.appendChild(document.importNode(el, true));
|
|
351
|
+
});
|
|
352
|
+
}
|
|
353
|
+
function swapContent(html, url, scripts, opts = {}) {
|
|
354
|
+
const { replace = false, scroll = true, restoreScroll = false } = opts;
|
|
355
|
+
const parser = new DOMParser();
|
|
356
|
+
const doc = parser.parseFromString(html, 'text/html');
|
|
357
|
+
const newContent = appRoot(doc);
|
|
358
|
+
const oldContent = appRoot(document);
|
|
359
|
+
if (!newContent || !oldContent) {
|
|
360
|
+
location.href = url;
|
|
361
|
+
return;
|
|
362
|
+
}
|
|
363
|
+
dispatchNavEvent('krate:navigate-start', url);
|
|
364
|
+
// The single synchronous DOM mutation point. Wrapped in a View Transition
|
|
365
|
+
// when the browser supports it, so the SPA morph is animated natively.
|
|
366
|
+
const runMutation = () => {
|
|
367
|
+
const newTitle = doc.querySelector('title');
|
|
368
|
+
if (newTitle)
|
|
369
|
+
document.title = newTitle.textContent || '';
|
|
370
|
+
// Dispose all active effects before replacing DOM
|
|
371
|
+
if (typeof globalThis.disposeAll === 'function') {
|
|
372
|
+
globalThis.disposeAll();
|
|
373
|
+
}
|
|
374
|
+
// Replace the entire app shell. This is deterministic for ANY page pair
|
|
375
|
+
// (docs<->docs, marketing<->docs, different layouts): no structural mismatch
|
|
376
|
+
// can drop chrome. The new page's scripts re-hydrate below, and View
|
|
377
|
+
// Transitions keep the visual transition smooth.
|
|
378
|
+
const nodes = Array.from(newContent.childNodes).map((n) => document.importNode(n, true));
|
|
379
|
+
oldContent.replaceChildren(...nodes);
|
|
380
|
+
reconcileStylesheets(doc);
|
|
381
|
+
reconcileHeadMeta(doc);
|
|
382
|
+
applyViewTransitionNames(document);
|
|
383
|
+
};
|
|
384
|
+
if (supportsViewTransitions()) {
|
|
385
|
+
try {
|
|
386
|
+
const vt = document.startViewTransition(runMutation);
|
|
387
|
+
if (vt && vt.finished && typeof vt.finished.catch === 'function') {
|
|
388
|
+
vt.finished.catch(() => { });
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
catch {
|
|
392
|
+
runMutation();
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
else {
|
|
396
|
+
runMutation();
|
|
397
|
+
}
|
|
241
398
|
// Load new scripts, then rehydrate
|
|
242
399
|
loadScripts(scripts, url).then(() => {
|
|
243
400
|
try {
|
|
@@ -279,8 +436,11 @@ export function initRouter() {
|
|
|
279
436
|
history.pushState({}, '', url);
|
|
280
437
|
}
|
|
281
438
|
applyScroll(url, { restoreScroll, scroll });
|
|
439
|
+
if (!restoreScroll)
|
|
440
|
+
focusContent();
|
|
282
441
|
updateActiveLinks();
|
|
283
442
|
window.dispatchEvent(new CustomEvent('krate:navigate', { detail: { url } }));
|
|
443
|
+
dispatchNavEvent('krate:navigate-end', url);
|
|
284
444
|
notifyNavigation(url);
|
|
285
445
|
}
|
|
286
446
|
function handleHashScroll(url) {
|
|
@@ -315,7 +475,7 @@ export function initRouter() {
|
|
|
315
475
|
}
|
|
316
476
|
// Mark the link matching the current route with aria-current="page".
|
|
317
477
|
function updateActiveLinks() {
|
|
318
|
-
const path = location.pathname;
|
|
478
|
+
const path = stripBase(location.pathname);
|
|
319
479
|
document.querySelectorAll('a[data-krate-link]').forEach((a) => {
|
|
320
480
|
const href = a.getAttribute('href');
|
|
321
481
|
if (!href) {
|
|
@@ -324,7 +484,7 @@ export function initRouter() {
|
|
|
324
484
|
}
|
|
325
485
|
let target = href;
|
|
326
486
|
try {
|
|
327
|
-
target = new URL(href, location.origin).pathname;
|
|
487
|
+
target = stripBase(new URL(href, location.origin).pathname);
|
|
328
488
|
}
|
|
329
489
|
catch {
|
|
330
490
|
return;
|
|
@@ -353,7 +513,7 @@ export function initRouter() {
|
|
|
353
513
|
const s = document.createElement('script');
|
|
354
514
|
const resolved = resolveSrc(src, baseUrl);
|
|
355
515
|
s.src = resolved;
|
|
356
|
-
// Only page scripts are disposable across navigations
|
|
516
|
+
// Only page scripts are disposable across navigations - the shared
|
|
357
517
|
// runtime chunk stays in place.
|
|
358
518
|
if (!RUNTIME_CHUNK_RE.test(resolved))
|
|
359
519
|
s.setAttribute('data-krate-spa', '');
|
|
@@ -441,7 +601,8 @@ export function initRouter() {
|
|
|
441
601
|
return scripts;
|
|
442
602
|
}
|
|
443
603
|
function fetchAndSwap(url, opts = {}) {
|
|
444
|
-
|
|
604
|
+
const seq = ++navSeq;
|
|
605
|
+
// Check prefetch cache first - already-loaded content swaps instantly.
|
|
445
606
|
const cached = prefetchCache.get(url);
|
|
446
607
|
if (cached) {
|
|
447
608
|
const parser = new DOMParser();
|
|
@@ -462,11 +623,15 @@ export function initRouter() {
|
|
|
462
623
|
signal,
|
|
463
624
|
})
|
|
464
625
|
.then((res) => {
|
|
626
|
+
if (seq !== navSeq)
|
|
627
|
+
return; // superseded by a newer navigation
|
|
465
628
|
if (!res.ok) {
|
|
466
629
|
const page = res.status >= 500 ? fetchErrorPage() : fetchNotFoundPage();
|
|
467
630
|
return page.then((html) => {
|
|
631
|
+
if (seq !== navSeq)
|
|
632
|
+
return;
|
|
468
633
|
if (html) {
|
|
469
|
-
// Error pages contain full layout
|
|
634
|
+
// Error pages contain full layout - full page replacement
|
|
470
635
|
replacePage(html, url);
|
|
471
636
|
}
|
|
472
637
|
else {
|
|
@@ -475,6 +640,8 @@ export function initRouter() {
|
|
|
475
640
|
});
|
|
476
641
|
}
|
|
477
642
|
return res.text().then((html) => {
|
|
643
|
+
if (seq !== navSeq)
|
|
644
|
+
return; // superseded while reading the body
|
|
478
645
|
const parser = new DOMParser();
|
|
479
646
|
const doc = parser.parseFromString(html, 'text/html');
|
|
480
647
|
swapContent(html, url, extractScripts(doc, url), opts);
|
|
@@ -495,7 +662,7 @@ export function initRouter() {
|
|
|
495
662
|
});
|
|
496
663
|
}
|
|
497
664
|
const clickHandler = (e) => {
|
|
498
|
-
// Never intercept modified clicks (cmd/ctrl/shift/alt or middle button)
|
|
665
|
+
// Never intercept modified clicks (cmd/ctrl/shift/alt or middle button) -
|
|
499
666
|
// they should open in a new tab or trigger browser behavior.
|
|
500
667
|
if (e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey)
|
|
501
668
|
return;
|
|
@@ -524,7 +691,24 @@ export function initRouter() {
|
|
|
524
691
|
document.addEventListener('click', clickHandler);
|
|
525
692
|
window.addEventListener('popstate', popstateHandler);
|
|
526
693
|
setupPrefetch();
|
|
694
|
+
setupSpeculationRules();
|
|
527
695
|
updateActiveLinks();
|
|
696
|
+
applyViewTransitionNames(document);
|
|
697
|
+
// Expose the SPA navigation to `navigate()` (and any embedded UI).
|
|
698
|
+
navigateImpl = (url, opts = {}) => {
|
|
699
|
+
let sameOrigin = true;
|
|
700
|
+
try {
|
|
701
|
+
sameOrigin = new URL(url, location.href).origin === location.origin;
|
|
702
|
+
}
|
|
703
|
+
catch {
|
|
704
|
+
sameOrigin = false;
|
|
705
|
+
}
|
|
706
|
+
if (!sameOrigin) {
|
|
707
|
+
location.href = url;
|
|
708
|
+
return;
|
|
709
|
+
}
|
|
710
|
+
fetchAndSwap(new URL(url, location.href).href, opts);
|
|
711
|
+
};
|
|
528
712
|
// Mark the initially-loaded page scripts as disposable so they're removed and
|
|
529
713
|
// re-executed against the fresh DOM when the user navigates back to this
|
|
530
714
|
// page. The shared runtime chunk is the exception and persists.
|
|
@@ -537,6 +721,7 @@ export function initRouter() {
|
|
|
537
721
|
document.removeEventListener('click', clickHandler);
|
|
538
722
|
window.removeEventListener('popstate', popstateHandler);
|
|
539
723
|
cleanupPrefetch();
|
|
724
|
+
navigateImpl = null;
|
|
540
725
|
};
|
|
541
726
|
}
|
|
542
727
|
/** Dispose old effects, re-register router listeners for new page. */
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// @krate/runtime/server/jsx-runtime
|
|
1
|
+
// @krate/runtime/server/jsx-runtime - Server-compatible JSX runtime.
|
|
2
2
|
// The functions are re-exported from ./server.js (single source of truth) so
|
|
3
3
|
// the JSX transform and its types never drift between the two server subpaths.
|
|
4
4
|
export { Fragment, jsx, jsxs } from './server.js';
|
package/dist/server-renderer.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// @krate/runtime/server-renderer
|
|
1
|
+
// @krate/runtime/server-renderer - Node.js HTTP server for SSR/ISR/Streaming
|
|
2
2
|
// Receives render requests from the Go server and returns HTML.
|
|
3
3
|
import http from "node:http";
|
|
4
4
|
import fs from "node:fs";
|
|
@@ -14,7 +14,7 @@ function setupStream(res) {
|
|
|
14
14
|
socket.setNoDelay(true);
|
|
15
15
|
}
|
|
16
16
|
}
|
|
17
|
-
//
|
|
17
|
+
// ISR Cache (variant-aware, SWR, persisted)
|
|
18
18
|
// A page's cache key is the route plus its per-request variant (params +
|
|
19
19
|
// query). Two dynamic-route requests (e.g. /video/a and /video/b) render
|
|
20
20
|
// different HTML, so they must never share a cache slot.
|
|
@@ -102,6 +102,10 @@ const isrCache = new ISRCache(parseInt(process.env.KRATE_SSR_MAX_CACHE || "", 10
|
|
|
102
102
|
// renderTimeoutMs bounds a single renderToString call so one pathological page
|
|
103
103
|
// cannot pin the sidecar. 0 disables the bound.
|
|
104
104
|
const renderTimeoutMs = parseInt(process.env.KRATE_SSR_TIMEOUT || "", 10) || 5000;
|
|
105
|
+
// Partial Prerendering: cache dynamic regions on non-ISR pages with this
|
|
106
|
+
// window (overridable per region via `export const revalidate`).
|
|
107
|
+
const pprEnabled = process.env.KRATE_PPR === "1";
|
|
108
|
+
const pprRevalidate = parseInt(process.env.KRATE_PPR_REVALIDATE || "", 10) || 60;
|
|
105
109
|
// withRenderTimeout rejects if p does not settle within renderTimeoutMs. The
|
|
106
110
|
// underlying render keeps running (JS cannot cancel it), but the request fails
|
|
107
111
|
// fast rather than hanging.
|
|
@@ -113,7 +117,7 @@ function withRenderTimeout(p) {
|
|
|
113
117
|
p.then((v) => { clearTimeout(timer); resolve(v); }, (e) => { clearTimeout(timer); reject(e); });
|
|
114
118
|
});
|
|
115
119
|
}
|
|
116
|
-
// ISR cache persistence
|
|
120
|
+
// ISR cache persistence - survives renderer restarts so a bounce doesn't
|
|
117
121
|
// cold-render every ISR variant. Written debounced (coalesced) to the build
|
|
118
122
|
// output dir (.krate/isr-cache.json), overridable via KRATE_ISR_CACHE.
|
|
119
123
|
let isrCacheFile = process.env.KRATE_ISR_CACHE || "";
|
|
@@ -152,7 +156,7 @@ function loadIsrCache() {
|
|
|
152
156
|
console.error("[krate-ssr] ISR cache load failed:", err.message);
|
|
153
157
|
}
|
|
154
158
|
}
|
|
155
|
-
//
|
|
159
|
+
// Page Module Loader
|
|
156
160
|
const moduleCache = new Map();
|
|
157
161
|
async function loadPageModule(page) {
|
|
158
162
|
// Prefer pre-compiled server bundle over raw source
|
|
@@ -180,7 +184,7 @@ async function loadPageModule(page) {
|
|
|
180
184
|
throw err;
|
|
181
185
|
}
|
|
182
186
|
}
|
|
183
|
-
//
|
|
187
|
+
// Renderer
|
|
184
188
|
let manifest = null;
|
|
185
189
|
let projectRoot = "";
|
|
186
190
|
function findPage(route) {
|
|
@@ -209,7 +213,7 @@ function buildProps(req) {
|
|
|
209
213
|
props.query = req.query;
|
|
210
214
|
return props;
|
|
211
215
|
}
|
|
212
|
-
// renderFresh renders a page component and
|
|
216
|
+
// renderFresh renders a page component and - for ISR pages - stores the result.
|
|
213
217
|
// Extracted so background revalidation shares exactly the same render path.
|
|
214
218
|
async function renderFresh(page, req) {
|
|
215
219
|
try {
|
|
@@ -271,7 +275,7 @@ function revalidateInBackground(page, req) {
|
|
|
271
275
|
// keeping the entries in place. This is the non-destructive counterpart of
|
|
272
276
|
// /__krate/ssr/revalidate (which clears a route). The Go server's periodic ISR
|
|
273
277
|
// timer calls this so cached pages stay fresh without evicting dynamic
|
|
274
|
-
// variants
|
|
278
|
+
// variants - eviction would turn a request that should be a HIT into a MISS.
|
|
275
279
|
const inFlightRouteRefreshes = new Map();
|
|
276
280
|
function refreshRouteVariants(page) {
|
|
277
281
|
const running = inFlightRouteRefreshes.get(page.route);
|
|
@@ -340,12 +344,11 @@ async function renderPage(req) {
|
|
|
340
344
|
response.cacheStatus = "miss";
|
|
341
345
|
return response;
|
|
342
346
|
}
|
|
343
|
-
//
|
|
344
|
-
//
|
|
347
|
+
// Region rendering (static-first)
|
|
345
348
|
// The Go server owns the page: it serves the build-time static shell with the
|
|
346
|
-
//
|
|
349
|
+
// <!-suspense:ID-> markers and baked fallbacks, then asks the sidecar to render
|
|
347
350
|
// ONLY the page's dynamic regions. Each region is rendered by its compiled
|
|
348
|
-
// runtime component bundle (server-components/<Name>.runtime.js
|
|
351
|
+
// runtime component bundle (server-components/<Name>.runtime.js - an IIFE that
|
|
349
352
|
// defines globalThis.__krate_render(propsJSON)) with the build-time baked props,
|
|
350
353
|
// so nothing is re-derived at request time.
|
|
351
354
|
const runtimeBundleCache = new Map();
|
|
@@ -380,20 +383,53 @@ function regionProps(region, req) {
|
|
|
380
383
|
const regionCache = new Map();
|
|
381
384
|
const regionRevalidation = new Map();
|
|
382
385
|
const inFlightRegionRevalidations = new Map();
|
|
386
|
+
// Region cache is bounded (FIFO eviction) so a long-lived sidecar cannot grow
|
|
387
|
+
// without limit across many dynamic region variants.
|
|
388
|
+
const REGION_CACHE_MAX = parseInt(process.env.KRATE_SSR_MAX_CACHE || "", 10) || 512;
|
|
389
|
+
function regionCacheSet(key, html) {
|
|
390
|
+
if (regionCache.size >= REGION_CACHE_MAX && !regionCache.has(key)) {
|
|
391
|
+
const oldest = regionCache.keys().next().value;
|
|
392
|
+
if (oldest !== undefined)
|
|
393
|
+
regionCache.delete(oldest);
|
|
394
|
+
}
|
|
395
|
+
regionCache.set(key, { html, timestamp: Date.now() });
|
|
396
|
+
}
|
|
397
|
+
function clearRegionCache() {
|
|
398
|
+
regionCache.clear();
|
|
399
|
+
regionRevalidation.clear();
|
|
400
|
+
}
|
|
401
|
+
function clearRegionCacheForRoute(route) {
|
|
402
|
+
const prefix = route + "::";
|
|
403
|
+
for (const key of Array.from(regionCache.keys())) {
|
|
404
|
+
if (key.startsWith(prefix))
|
|
405
|
+
regionCache.delete(key);
|
|
406
|
+
}
|
|
407
|
+
}
|
|
383
408
|
function regionCacheKey(page, regionId, req) {
|
|
384
409
|
return variantKey({ route: page.route + "::" + regionId, params: req.params, query: req.query });
|
|
385
410
|
}
|
|
411
|
+
// regionInterval resolves a region's cache window: its own revalidate directive
|
|
412
|
+
// wins, else the page's ISR cadence; non-ISR pages with no directive are 0.
|
|
413
|
+
function regionInterval(page, region) {
|
|
414
|
+
if (region.revalidate && region.revalidate > 0)
|
|
415
|
+
return region.revalidate;
|
|
416
|
+
if (page.mode === "isr")
|
|
417
|
+
return page.revalidate || 60;
|
|
418
|
+
if (pprEnabled)
|
|
419
|
+
return pprRevalidate;
|
|
420
|
+
return 0;
|
|
421
|
+
}
|
|
386
422
|
function renderRegionFresh(region, req) {
|
|
387
423
|
const render = loadRuntimeRenderer(region.bundlePath);
|
|
388
|
-
return render(JSON.stringify(regionProps(region, req)));
|
|
424
|
+
return withRenderTimeout(Promise.resolve().then(() => render(JSON.stringify(regionProps(region, req)))));
|
|
389
425
|
}
|
|
390
426
|
function revalidateRegionInBackground(page, region, req, key) {
|
|
391
427
|
if (inFlightRegionRevalidations.has(key))
|
|
392
428
|
return;
|
|
393
429
|
const p = (async () => {
|
|
394
430
|
try {
|
|
395
|
-
const html = renderRegionFresh(region, req);
|
|
396
|
-
|
|
431
|
+
const html = await renderRegionFresh(region, req);
|
|
432
|
+
regionCacheSet(key, html);
|
|
397
433
|
console.log(`[krate-ssr] Revalidated region ${key} (SWR)`);
|
|
398
434
|
}
|
|
399
435
|
catch (err) {
|
|
@@ -412,8 +448,9 @@ async function renderRegion(page, region, req) {
|
|
|
412
448
|
return { type: "error", id: region.id, status: 400, error: "region has no runtime bundle" };
|
|
413
449
|
}
|
|
414
450
|
const key = regionCacheKey(page, region.id, req);
|
|
415
|
-
|
|
416
|
-
|
|
451
|
+
const interval = regionInterval(page, region);
|
|
452
|
+
const cacheable = interval > 0;
|
|
453
|
+
if (cacheable) {
|
|
417
454
|
regionRevalidation.set(key, interval);
|
|
418
455
|
const cached = regionCache.get(key);
|
|
419
456
|
const stale = cached && (Date.now() - cached.timestamp) / 1000 > interval;
|
|
@@ -426,12 +463,12 @@ async function renderRegion(page, region, req) {
|
|
|
426
463
|
}
|
|
427
464
|
}
|
|
428
465
|
try {
|
|
429
|
-
const html = renderRegionFresh(region, req);
|
|
430
|
-
if (
|
|
431
|
-
|
|
466
|
+
const html = await renderRegionFresh(region, req);
|
|
467
|
+
if (cacheable) {
|
|
468
|
+
regionCacheSet(key, html);
|
|
432
469
|
}
|
|
433
470
|
const frame = { type: "region", id: region.id, status: 200, html };
|
|
434
|
-
if (
|
|
471
|
+
if (cacheable)
|
|
435
472
|
frame.cacheStatus = "miss";
|
|
436
473
|
return frame;
|
|
437
474
|
}
|
|
@@ -474,7 +511,7 @@ function extractTitle(html) {
|
|
|
474
511
|
const match = html.match(/<title[^>]*>([\s\S]*?)<\/title>/i);
|
|
475
512
|
return match ? match[1].trim() : "";
|
|
476
513
|
}
|
|
477
|
-
//
|
|
514
|
+
// HTTP Server
|
|
478
515
|
const PORT = parseInt(process.env.KRATE_SSR_PORT || "3100", 10);
|
|
479
516
|
const manifestPath = process.env.KRATE_MANIFEST || "";
|
|
480
517
|
const root = process.env.KRATE_ROOT || process.cwd();
|
|
@@ -520,6 +557,7 @@ const server = http.createServer(async (req, res) => {
|
|
|
520
557
|
try {
|
|
521
558
|
const { route: targetRoute } = JSON.parse(body);
|
|
522
559
|
isrCache.deleteRoute(targetRoute);
|
|
560
|
+
clearRegionCacheForRoute(targetRoute);
|
|
523
561
|
// Trigger re-render of the base variant.
|
|
524
562
|
const page = findPage(targetRoute);
|
|
525
563
|
if (page) {
|
|
@@ -545,6 +583,7 @@ const server = http.createServer(async (req, res) => {
|
|
|
545
583
|
const { route: targetRoute } = JSON.parse(body);
|
|
546
584
|
const page = findPage(targetRoute);
|
|
547
585
|
const refreshed = page && page.mode === "isr" ? await refreshRouteVariants(page) : 0;
|
|
586
|
+
clearRegionCacheForRoute(targetRoute);
|
|
548
587
|
res.writeHead(200, { "Content-Type": "application/json" });
|
|
549
588
|
res.end(JSON.stringify({ ok: true, refreshed }));
|
|
550
589
|
}
|
|
@@ -573,6 +612,7 @@ const server = http.createServer(async (req, res) => {
|
|
|
573
612
|
// re-read on demand, so clearing all of them is cheap and avoids tracking
|
|
574
613
|
// which component maps to which route here.
|
|
575
614
|
runtimeBundleCache.clear();
|
|
615
|
+
clearRegionCache();
|
|
576
616
|
res.writeHead(200, { "Content-Type": "application/json" });
|
|
577
617
|
res.end(JSON.stringify({ ok: true }));
|
|
578
618
|
}
|
|
@@ -582,7 +622,7 @@ const server = http.createServer(async (req, res) => {
|
|
|
582
622
|
}
|
|
583
623
|
return;
|
|
584
624
|
}
|
|
585
|
-
//
|
|
625
|
+
// /__krate/regions - render ONLY a page's dynamic regions
|
|
586
626
|
// One NDJSON frame per region, written as its own chunk so the Go server
|
|
587
627
|
// forwards each region progressively and splices it into the static shell.
|
|
588
628
|
// The Go server sends the splice markers it parsed from the shell; the
|
|
@@ -630,7 +670,7 @@ const server = http.createServer(async (req, res) => {
|
|
|
630
670
|
writeJsonLine(res, await renderRegion(page, region, renderReq));
|
|
631
671
|
}
|
|
632
672
|
else {
|
|
633
|
-
// Unknown region id
|
|
673
|
+
// Unknown region id - keep the baked content by sending no frame.
|
|
634
674
|
writeJsonLine(res, { type: "skip", id: r.id });
|
|
635
675
|
}
|
|
636
676
|
}
|
|
@@ -644,7 +684,7 @@ const server = http.createServer(async (req, res) => {
|
|
|
644
684
|
res.end();
|
|
645
685
|
return;
|
|
646
686
|
}
|
|
647
|
-
//
|
|
687
|
+
// Direct page requests (non-proxied)
|
|
648
688
|
// Collect request headers
|
|
649
689
|
const headers = {};
|
|
650
690
|
for (const [key, value] of Object.entries(req.headers)) {
|