@krate/runtime 0.4.0-rc.2 → 0.4.0-rc.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/dev-overlay.d.ts +15 -0
- package/dist/dev-overlay.js +446 -0
- package/dist/dev-overlay.test.d.ts +1 -0
- package/dist/dev-overlay.test.js +99 -0
- package/dist/index.d.ts +2 -1
- package/dist/index.js +1 -1
- package/dist/krate-dev.js +373 -0
- package/dist/krate-hydrate.js +1 -1
- package/dist/krate-runtime.js +1 -1
- package/dist/router.d.ts +12 -0
- package/dist/router.js +235 -50
- package/dist/server-renderer.js +50 -9
- 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;
|
|
@@ -441,6 +601,7 @@ export function initRouter() {
|
|
|
441
601
|
return scripts;
|
|
442
602
|
}
|
|
443
603
|
function fetchAndSwap(url, opts = {}) {
|
|
604
|
+
const seq = ++navSeq;
|
|
444
605
|
// Check prefetch cache first — already-loaded content swaps instantly.
|
|
445
606
|
const cached = prefetchCache.get(url);
|
|
446
607
|
if (cached) {
|
|
@@ -462,9 +623,13 @@ 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
634
|
// Error pages contain full layout — full page replacement
|
|
470
635
|
replacePage(html, url);
|
|
@@ -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);
|
|
@@ -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. */
|
package/dist/server-renderer.js
CHANGED
|
@@ -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.
|
|
@@ -380,20 +384,53 @@ function regionProps(region, req) {
|
|
|
380
384
|
const regionCache = new Map();
|
|
381
385
|
const regionRevalidation = new Map();
|
|
382
386
|
const inFlightRegionRevalidations = new Map();
|
|
387
|
+
// Region cache is bounded (FIFO eviction) so a long-lived sidecar cannot grow
|
|
388
|
+
// without limit across many dynamic region variants.
|
|
389
|
+
const REGION_CACHE_MAX = parseInt(process.env.KRATE_SSR_MAX_CACHE || "", 10) || 512;
|
|
390
|
+
function regionCacheSet(key, html) {
|
|
391
|
+
if (regionCache.size >= REGION_CACHE_MAX && !regionCache.has(key)) {
|
|
392
|
+
const oldest = regionCache.keys().next().value;
|
|
393
|
+
if (oldest !== undefined)
|
|
394
|
+
regionCache.delete(oldest);
|
|
395
|
+
}
|
|
396
|
+
regionCache.set(key, { html, timestamp: Date.now() });
|
|
397
|
+
}
|
|
398
|
+
function clearRegionCache() {
|
|
399
|
+
regionCache.clear();
|
|
400
|
+
regionRevalidation.clear();
|
|
401
|
+
}
|
|
402
|
+
function clearRegionCacheForRoute(route) {
|
|
403
|
+
const prefix = route + "::";
|
|
404
|
+
for (const key of Array.from(regionCache.keys())) {
|
|
405
|
+
if (key.startsWith(prefix))
|
|
406
|
+
regionCache.delete(key);
|
|
407
|
+
}
|
|
408
|
+
}
|
|
383
409
|
function regionCacheKey(page, regionId, req) {
|
|
384
410
|
return variantKey({ route: page.route + "::" + regionId, params: req.params, query: req.query });
|
|
385
411
|
}
|
|
412
|
+
// regionInterval resolves a region's cache window: its own revalidate directive
|
|
413
|
+
// wins, else the page's ISR cadence; non-ISR pages with no directive are 0.
|
|
414
|
+
function regionInterval(page, region) {
|
|
415
|
+
if (region.revalidate && region.revalidate > 0)
|
|
416
|
+
return region.revalidate;
|
|
417
|
+
if (page.mode === "isr")
|
|
418
|
+
return page.revalidate || 60;
|
|
419
|
+
if (pprEnabled)
|
|
420
|
+
return pprRevalidate;
|
|
421
|
+
return 0;
|
|
422
|
+
}
|
|
386
423
|
function renderRegionFresh(region, req) {
|
|
387
424
|
const render = loadRuntimeRenderer(region.bundlePath);
|
|
388
|
-
return render(JSON.stringify(regionProps(region, req)));
|
|
425
|
+
return withRenderTimeout(Promise.resolve().then(() => render(JSON.stringify(regionProps(region, req)))));
|
|
389
426
|
}
|
|
390
427
|
function revalidateRegionInBackground(page, region, req, key) {
|
|
391
428
|
if (inFlightRegionRevalidations.has(key))
|
|
392
429
|
return;
|
|
393
430
|
const p = (async () => {
|
|
394
431
|
try {
|
|
395
|
-
const html = renderRegionFresh(region, req);
|
|
396
|
-
|
|
432
|
+
const html = await renderRegionFresh(region, req);
|
|
433
|
+
regionCacheSet(key, html);
|
|
397
434
|
console.log(`[krate-ssr] Revalidated region ${key} (SWR)`);
|
|
398
435
|
}
|
|
399
436
|
catch (err) {
|
|
@@ -412,8 +449,9 @@ async function renderRegion(page, region, req) {
|
|
|
412
449
|
return { type: "error", id: region.id, status: 400, error: "region has no runtime bundle" };
|
|
413
450
|
}
|
|
414
451
|
const key = regionCacheKey(page, region.id, req);
|
|
415
|
-
|
|
416
|
-
|
|
452
|
+
const interval = regionInterval(page, region);
|
|
453
|
+
const cacheable = interval > 0;
|
|
454
|
+
if (cacheable) {
|
|
417
455
|
regionRevalidation.set(key, interval);
|
|
418
456
|
const cached = regionCache.get(key);
|
|
419
457
|
const stale = cached && (Date.now() - cached.timestamp) / 1000 > interval;
|
|
@@ -426,12 +464,12 @@ async function renderRegion(page, region, req) {
|
|
|
426
464
|
}
|
|
427
465
|
}
|
|
428
466
|
try {
|
|
429
|
-
const html = renderRegionFresh(region, req);
|
|
430
|
-
if (
|
|
431
|
-
|
|
467
|
+
const html = await renderRegionFresh(region, req);
|
|
468
|
+
if (cacheable) {
|
|
469
|
+
regionCacheSet(key, html);
|
|
432
470
|
}
|
|
433
471
|
const frame = { type: "region", id: region.id, status: 200, html };
|
|
434
|
-
if (
|
|
472
|
+
if (cacheable)
|
|
435
473
|
frame.cacheStatus = "miss";
|
|
436
474
|
return frame;
|
|
437
475
|
}
|
|
@@ -520,6 +558,7 @@ const server = http.createServer(async (req, res) => {
|
|
|
520
558
|
try {
|
|
521
559
|
const { route: targetRoute } = JSON.parse(body);
|
|
522
560
|
isrCache.deleteRoute(targetRoute);
|
|
561
|
+
clearRegionCacheForRoute(targetRoute);
|
|
523
562
|
// Trigger re-render of the base variant.
|
|
524
563
|
const page = findPage(targetRoute);
|
|
525
564
|
if (page) {
|
|
@@ -545,6 +584,7 @@ const server = http.createServer(async (req, res) => {
|
|
|
545
584
|
const { route: targetRoute } = JSON.parse(body);
|
|
546
585
|
const page = findPage(targetRoute);
|
|
547
586
|
const refreshed = page && page.mode === "isr" ? await refreshRouteVariants(page) : 0;
|
|
587
|
+
clearRegionCacheForRoute(targetRoute);
|
|
548
588
|
res.writeHead(200, { "Content-Type": "application/json" });
|
|
549
589
|
res.end(JSON.stringify({ ok: true, refreshed }));
|
|
550
590
|
}
|
|
@@ -573,6 +613,7 @@ const server = http.createServer(async (req, res) => {
|
|
|
573
613
|
// re-read on demand, so clearing all of them is cheap and avoids tracking
|
|
574
614
|
// which component maps to which route here.
|
|
575
615
|
runtimeBundleCache.clear();
|
|
616
|
+
clearRegionCache();
|
|
576
617
|
res.writeHead(200, { "Content-Type": "application/json" });
|
|
577
618
|
res.end(JSON.stringify({ ok: true }));
|
|
578
619
|
}
|