@krate/runtime 0.5.0-rc.15 → 0.5.0-rc.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/NOTICE +10 -0
  2. package/README.md +92 -1
  3. package/dist/actions.js +10 -5
  4. package/dist/cache-scope.d.ts +10 -2
  5. package/dist/cache-scope.js +26 -4
  6. package/dist/context.js +3 -0
  7. package/dist/dev/app.js +6 -2
  8. package/dist/dev/modal.js +9 -9
  9. package/dist/dev/panel.js +3 -1
  10. package/dist/dev/sourcemap.d.ts +5 -0
  11. package/dist/dev/sourcemap.js +36 -2
  12. package/dist/dev/util.d.ts +6 -0
  13. package/dist/dev/util.js +1 -0
  14. package/dist/dom.d.ts +26 -0
  15. package/dist/dom.js +78 -5
  16. package/dist/flight-props.d.ts +8 -0
  17. package/dist/flight-props.js +44 -0
  18. package/dist/hints.d.ts +12 -0
  19. package/dist/hints.js +32 -2
  20. package/dist/index.d.ts +4 -0
  21. package/dist/island-swap.js +46 -8
  22. package/dist/krate-core.js +1 -1
  23. package/dist/krate-dev.js +14 -14
  24. package/dist/krate-f-actions.js +1 -1
  25. package/dist/krate-f-list.js +1 -1
  26. package/dist/krate-f-navigation.js +1 -1
  27. package/dist/krate-f-router.js +1 -1
  28. package/dist/krate-features.json +32 -1
  29. package/dist/krate-hydrate-lite.js +5 -5
  30. package/dist/krate-hydrate.js +5 -5
  31. package/dist/krate-island-swap.js +1 -1
  32. package/dist/krate-runtime.js +5 -5
  33. package/dist/list.js +8 -3
  34. package/dist/memsize.d.ts +14 -0
  35. package/dist/memsize.js +71 -0
  36. package/dist/metadata.js +20 -5
  37. package/dist/middleware-cookies.d.ts +4 -0
  38. package/dist/middleware-cookies.js +67 -0
  39. package/dist/navigation-react.js +2 -1
  40. package/dist/navigation.d.ts +7 -0
  41. package/dist/navigation.js +26 -1
  42. package/dist/react-compat.js +9 -0
  43. package/dist/react.d.ts +1 -1
  44. package/dist/react.js +5 -0
  45. package/dist/router.js +55 -9
  46. package/dist/segmented-lru.d.ts +14 -1
  47. package/dist/segmented-lru.js +90 -21
  48. package/dist/server-handler.d.ts +1 -0
  49. package/dist/server-handler.js +100 -6
  50. package/dist/server-renderer.js +4 -1
  51. package/dist/server.d.ts +6 -3
  52. package/dist/server.js +78 -38
  53. package/dist/shared-isr.js +2 -1
  54. package/dist/signal.js +13 -3
  55. package/dist/slots.js +8 -1
  56. package/dist/ssr-core.d.ts +10 -2
  57. package/dist/ssr-core.js +19 -6
  58. package/package.json +3 -2
package/dist/list.js CHANGED
@@ -24,7 +24,7 @@
24
24
  */
25
25
  import { createEffect, createRoot, createSignal, onCleanup, untrack } from './signal.js';
26
26
  import { krateUnmount, krateWithOwner } from './effects.js';
27
- import { adoptValue, appendChild, disposeNode, insertAt, removeRest, trackEffect, withDOM, withVNodes, } from './dom.js';
27
+ import { adoptValue, appendChild, disposeNode, insertAt, krateRemoveNode, removeRest, trackEffect, withDOM, withVNodes, } from './dom.js';
28
28
  import { krateMuteEvents } from './events.js';
29
29
  import { krateWithIdScope } from './use-id.js';
30
30
  /** Canonical key: explicit keys are `$` + String(key); implicit keys are the index. */
@@ -141,8 +141,13 @@ function disposeRange(start, end, markers) {
141
141
  let n = start.nextSibling;
142
142
  while (n && n !== end) {
143
143
  const next = n.nextSibling;
144
- disposeNode(n);
145
- parent.removeChild(n);
144
+ // A removed row's element may stay for its exit animation (see krateSetExitHook).
145
+ if (markers)
146
+ krateRemoveNode(parent, n);
147
+ else {
148
+ disposeNode(n);
149
+ parent.removeChild(n);
150
+ }
146
151
  n = next;
147
152
  }
148
153
  if (markers) {
@@ -0,0 +1,14 @@
1
+ export declare function approxBytes(value: unknown, maxDepth?: number): number;
2
+ /** The default memory budget of the render caches, in bytes. */
3
+ export declare const DEFAULT_CACHE_BYTES: number;
4
+ /**
5
+ * The byte budgets of the in-memory caches, from KRATE_SSR_CACHE_BYTES (the
6
+ * total for one process; 0 or unset is the default). Rendered pages get half,
7
+ * PPR regions and the data cache a quarter each.
8
+ */
9
+ export declare function cacheByteBudgets(total?: number): {
10
+ pages: number;
11
+ regions: number;
12
+ data: number;
13
+ };
14
+ export declare function cacheBytesFromEnv(env: Record<string, string | undefined> | undefined): number;
@@ -0,0 +1,71 @@
1
+ // Approximate retained size of cached values, for byte-bounded caches. It
2
+ // counts string characters as bytes (V8 stores ASCII text one byte per
3
+ // character), adds a small fixed cost per object, array, key and number, and
4
+ // stops at maxDepth so a deep or cyclic value costs a bounded walk.
5
+ const OBJECT_COST = 32;
6
+ const SLOT_COST = 8;
7
+ export function approxBytes(value, maxDepth = 8) {
8
+ const seen = new Set();
9
+ const walk = (v, depth) => {
10
+ switch (typeof v) {
11
+ case "string":
12
+ return v.length + 16;
13
+ case "number":
14
+ case "boolean":
15
+ case "undefined":
16
+ case "symbol":
17
+ return SLOT_COST;
18
+ case "bigint":
19
+ return 16;
20
+ case "function":
21
+ return OBJECT_COST;
22
+ }
23
+ if (v === null)
24
+ return SLOT_COST;
25
+ const o = v;
26
+ if (seen.has(o))
27
+ return SLOT_COST;
28
+ seen.add(o);
29
+ if (ArrayBuffer.isView(o))
30
+ return o.byteLength + OBJECT_COST;
31
+ if (o instanceof ArrayBuffer)
32
+ return o.byteLength + OBJECT_COST;
33
+ if (depth >= maxDepth)
34
+ return OBJECT_COST;
35
+ let n = OBJECT_COST;
36
+ if (Array.isArray(o)) {
37
+ for (const item of o)
38
+ n += SLOT_COST + walk(item, depth + 1);
39
+ return n;
40
+ }
41
+ if (o instanceof Map) {
42
+ for (const [k, item] of o)
43
+ n += walk(k, depth + 1) + walk(item, depth + 1);
44
+ return n;
45
+ }
46
+ if (o instanceof Set) {
47
+ for (const item of o)
48
+ n += SLOT_COST + walk(item, depth + 1);
49
+ return n;
50
+ }
51
+ for (const k of Object.keys(o))
52
+ n += k.length + SLOT_COST + walk(o[k], depth + 1);
53
+ return n;
54
+ };
55
+ return walk(value, 0);
56
+ }
57
+ /** The default memory budget of the render caches, in bytes. */
58
+ export const DEFAULT_CACHE_BYTES = 64 * 1024 * 1024;
59
+ /**
60
+ * The byte budgets of the in-memory caches, from KRATE_SSR_CACHE_BYTES (the
61
+ * total for one process; 0 or unset is the default). Rendered pages get half,
62
+ * PPR regions and the data cache a quarter each.
63
+ */
64
+ export function cacheByteBudgets(total) {
65
+ const t = total && total > 0 ? total : DEFAULT_CACHE_BYTES;
66
+ return { pages: Math.floor(t / 2), regions: Math.floor(t / 4), data: Math.floor(t / 4) };
67
+ }
68
+ export function cacheBytesFromEnv(env) {
69
+ const n = Number(env?.KRATE_SSR_CACHE_BYTES);
70
+ return Number.isFinite(n) && n > 0 ? Math.floor(n) : 0;
71
+ }
package/dist/metadata.js CHANGED
@@ -13,8 +13,10 @@
13
13
  // languages, media, types), openGraph, twitter, icons, manifest, themeColor,
14
14
  // viewport (string), verification, appleWebApp, formatDetection, category,
15
15
  // itunes, appLinks, archives, assets, bookmarks and other. metadataBase resolves
16
- // relative URLs. Anything else is ignored.
16
+ // relative URLs (not icons, which stay as written). Anything else is ignored.
17
17
  import { httpFallbackStatus, isDynamicUsageError, redirectTarget, thenableRecord } from './request-context.js';
18
+ // The viewport Next.js starts from before merging viewport exports.
19
+ const DEFAULT_VIEWPORT = { width: 'device-width', initialScale: 1 };
18
20
  function isThenable(v) {
19
21
  return !!v && typeof v.then === 'function';
20
22
  }
@@ -106,7 +108,18 @@ export async function resolveMetadata(segments, rawProps) {
106
108
  acc = mergeSegment(acc, own);
107
109
  if (mod && mod.viewport && typeof mod.viewport === 'object') {
108
110
  const { themeColor, colorScheme, ...rest } = mod.viewport;
109
- acc = mergeSegment(acc, { viewport: rest, ...(themeColor !== undefined ? { themeColor } : {}), ...(colorScheme !== undefined ? { colorScheme } : {}) });
111
+ // Like Next.js, a viewport export sets only the keys it names, over the
112
+ // parents' viewport and the defaults (width=device-width, initial-scale=1).
113
+ const merged = {};
114
+ if (Object.keys(rest).length > 0) {
115
+ const prev = acc.metadata.viewport;
116
+ merged.viewport = { ...(prev && typeof prev === 'object' ? prev : DEFAULT_VIEWPORT), ...rest };
117
+ }
118
+ if (themeColor !== undefined)
119
+ merged.themeColor = themeColor;
120
+ if (colorScheme !== undefined)
121
+ merged.colorScheme = colorScheme;
122
+ acc = mergeSegment(acc, merged);
110
123
  }
111
124
  if (seg.files)
112
125
  acc = mergeFiles(acc, fillParams(seg.files, rawProps.params), own);
@@ -308,8 +321,10 @@ export function renderMetadataTags(md, templates = {}) {
308
321
  push(meta('name', 'category', md.category));
309
322
  if (md.itunes)
310
323
  push(meta('name', 'apple-itunes-app', `app-id=${md.itunes.appId}${md.itunes.appArgument ? `, app-argument=${md.itunes.appArgument}` : ''}`));
324
+ // Icons keep the URL as written (Next.js does not resolve them against
325
+ // metadataBase); a relative URL is served from the site itself.
311
326
  if (md.icons)
312
- renderIcons(md.icons, base, push);
327
+ renderIcons(md.icons, push);
313
328
  if (md.verification) {
314
329
  const v = md.verification;
315
330
  for (const x of toArray(v.google))
@@ -367,12 +382,12 @@ export function renderMetadataTags(md, templates = {}) {
367
382
  push(meta('name', k, x));
368
383
  return tags.join('\n');
369
384
  }
370
- function renderIcons(icons, base, push) {
385
+ function renderIcons(icons, push) {
371
386
  const asDesc = (i, rel) => (typeof i === 'string' || i instanceof URL ? { url: i, rel } : { rel, ...i });
372
387
  const emit = (list, rel) => {
373
388
  for (const i of toArray(list)) {
374
389
  const d = asDesc(i, rel);
375
- push(link({ rel: d.rel || rel, href: resolveBaseJoin(d.url, base), type: d.type, sizes: d.sizes, media: d.media, color: d.color, fetchpriority: d.fetchPriority }));
390
+ push(link({ rel: d.rel || rel, href: String(d.url), type: d.type, sizes: d.sizes, media: d.media, color: d.color, fetchpriority: d.fetchPriority }));
376
391
  }
377
392
  };
378
393
  if (typeof icons === 'string' || icons instanceof URL || Array.isArray(icons)) {
@@ -0,0 +1,4 @@
1
+ /** Splits comma-joined Set-Cookie lines; the comma in an Expires date stays inside its cookie. */
2
+ export declare function splitSetCookieList(s: string): string[];
3
+ /** The request Cookie header after applying Set-Cookie lines: set replaces, expired removes. */
4
+ export declare function mergeCookieHeader(cookie: string, lines: string[], now?: number): string;
@@ -0,0 +1,67 @@
1
+ // Next's x-middleware-set-cookie protocol: NextResponse.next() lists the
2
+ // cookies middleware set (Set-Cookie lines joined with commas), and the server
3
+ // applies them to the request it forwards so cookies() sees them.
4
+ /** Splits comma-joined Set-Cookie lines; the comma in an Expires date stays inside its cookie. */
5
+ export function splitSetCookieList(s) {
6
+ const out = [];
7
+ let start = 0;
8
+ for (let i = 0; i < s.length; i++) {
9
+ if (s[i] !== ",")
10
+ continue;
11
+ let j = i + 1;
12
+ while (j < s.length && (s[j] === " " || s[j] === "\t"))
13
+ j++;
14
+ let k = j;
15
+ while (k < s.length && s[k] !== "=" && s[k] !== ";" && s[k] !== "," && s[k] !== " ")
16
+ k++;
17
+ if (k > j && s[k] === "=") {
18
+ const part = s.slice(start, i).trim();
19
+ if (part)
20
+ out.push(part);
21
+ start = j;
22
+ i = j - 1;
23
+ }
24
+ }
25
+ const last = s.slice(start).trim();
26
+ if (last)
27
+ out.push(last);
28
+ return out;
29
+ }
30
+ /** The request Cookie header after applying Set-Cookie lines: set replaces, expired removes. */
31
+ export function mergeCookieHeader(cookie, lines, now = Date.now()) {
32
+ const jar = new Map();
33
+ for (const part of cookie.split(";")) {
34
+ const p = part.trim();
35
+ if (!p)
36
+ continue;
37
+ const eq = p.indexOf("=");
38
+ jar.set(eq === -1 ? p : p.slice(0, eq).trim(), eq === -1 ? "" : p.slice(eq + 1));
39
+ }
40
+ for (const value of lines) {
41
+ for (const line of splitSetCookieList(value)) {
42
+ const attrs = line.split(";");
43
+ const first = attrs.shift().trim();
44
+ const eq = first.indexOf("=");
45
+ if (eq <= 0)
46
+ continue;
47
+ const name = first.slice(0, eq).trim();
48
+ let expired = false;
49
+ for (const a of attrs) {
50
+ const i = a.indexOf("=");
51
+ const key = (i === -1 ? a : a.slice(0, i)).trim().toLowerCase();
52
+ const val = i === -1 ? "" : a.slice(i + 1).trim();
53
+ if (key === "max-age" && Number(val) <= 0)
54
+ expired = true;
55
+ if (key === "expires") {
56
+ const t = Date.parse(val);
57
+ if (!Number.isNaN(t) && t <= now)
58
+ expired = true;
59
+ }
60
+ }
61
+ jar.delete(name);
62
+ if (!expired)
63
+ jar.set(name, first.slice(eq + 1).trim());
64
+ }
65
+ }
66
+ return Array.from(jar, ([k, v]) => `${k}=${v}`).join("; ");
67
+ }
@@ -9,7 +9,7 @@
9
9
  import { getRequestContext } from './request-context.js';
10
10
  import * as serverNav from './navigation-server.js';
11
11
  import { krateRouter } from './router.js';
12
- import { krateRouteStore, krateMatchParams, krateLayoutSegments } from './navigation.js';
12
+ import { krateRouteStore, krateMatchParams, krateLayoutSegments, krateMarkPrerenderUnknown } from './navigation.js';
13
13
  const routerInstance = {
14
14
  push: (href, options) => void krateRouter.push(href, options),
15
15
  replace: (href, options) => void krateRouter.replace(href, options),
@@ -47,6 +47,7 @@ export function createValueNavigationHooks(useSyncExternalStore) {
47
47
  useSearchParams() {
48
48
  if (getRequestContext())
49
49
  return serverNav.useSearchParams();
50
+ krateMarkPrerenderUnknown();
50
51
  const s = route();
51
52
  if (s.search !== paramsKey) {
52
53
  paramsKey = s.search;
@@ -4,6 +4,13 @@ interface RouteSnapshot {
4
4
  /** The route pattern of the current document ("/blog/[slug]"), "" for a static route. */
5
5
  route: string;
6
6
  }
7
+ /**
8
+ * Records that a build-time render read a route value it cannot know (the
9
+ * path of a page rendered per request, or the query): the compiler then has
10
+ * the island render over its server markup in the browser instead of
11
+ * hydrating it, so attributes made from that value are patched.
12
+ */
13
+ export declare function krateMarkPrerenderUnknown(): void;
7
14
  /**
8
15
  * An external store of the route for React-model components (Preact compat and
9
16
  * real React islands), which read hook results as plain values and re-render
@@ -32,9 +32,33 @@ function documentRoute() {
32
32
  function cleanPath(pathname) {
33
33
  return pathname.length > 1 && pathname.endsWith('/') ? pathname.replace(/\/+$/, '') || '/' : pathname;
34
34
  }
35
+ /**
36
+ * The page a build-time render outside the browser is for: the compiler sets
37
+ * __KRATE_PRERENDER__ before it server renders an island, so the router hooks
38
+ * see the page's path instead of "/".
39
+ */
40
+ function prerenderSnapshot() {
41
+ const nav = globalThis.__KRATE_PRERENDER__;
42
+ if (nav && typeof nav.pathname === 'string') {
43
+ return { pathname: cleanPath(nav.pathname), search: '', route: typeof nav.route === 'string' ? nav.route : '' };
44
+ }
45
+ krateMarkPrerenderUnknown();
46
+ return { pathname: '/', search: '', route: '' };
47
+ }
48
+ /**
49
+ * Records that a build-time render read a route value it cannot know (the
50
+ * path of a page rendered per request, or the query): the compiler then has
51
+ * the island render over its server markup in the browser instead of
52
+ * hydrating it, so attributes made from that value are patched.
53
+ */
54
+ export function krateMarkPrerenderUnknown() {
55
+ if (typeof location !== 'undefined')
56
+ return;
57
+ globalThis.__KRATE_PRERENDER_NAV_UNKNOWN__ = true;
58
+ }
35
59
  function snapshot() {
36
60
  if (typeof location === 'undefined')
37
- return { pathname: '/', search: '', route: '' };
61
+ return prerenderSnapshot();
38
62
  const { pathname, search } = getNavigationState();
39
63
  return { pathname: cleanPath(pathname), search, route: documentRoute() };
40
64
  }
@@ -119,6 +143,7 @@ export function usePathname() {
119
143
  export function useSearchParams() {
120
144
  if (getRequestContext())
121
145
  return serverNav.useSearchParams();
146
+ krateMarkPrerenderUnknown();
122
147
  const read = routeState();
123
148
  const derived = krateDerived(() => new URLSearchParams(read().search));
124
149
  return describe(derived, () => read().search);
@@ -18,6 +18,10 @@ function reportError(err) {
18
18
  console.error(err);
19
19
  }
20
20
  const SHARED = '__krateReactCompat';
21
+ // The redirects server actions followed (see actions.ts).
22
+ function redirectCount() {
23
+ return globalThis.__krateActionRedirects || 0;
24
+ }
21
25
  /**
22
26
  * Builds the additions once per Preact instance: the `react` and `react-dom`
23
27
  * modules of a bundle (and of every island chunk) share one action scope and
@@ -207,7 +211,12 @@ function build(c, options) {
207
211
  const run = l.chain.then(async () => {
208
212
  if (l.cancelled)
209
213
  return;
214
+ const before = redirectCount();
210
215
  const next = await l.action(l.state, payload);
216
+ // A redirecting action has no next state (Next throws there): the
217
+ // page is being replaced, so the island keeps its state.
218
+ if (redirectCount() !== before)
219
+ return;
211
220
  l.state = next;
212
221
  setState(() => next);
213
222
  });
package/dist/react.d.ts CHANGED
@@ -212,6 +212,7 @@ export declare function startTransition(fn: () => unknown): void;
212
212
  */
213
213
  export declare function use<T>(value: PromiseLike<T> | ReactContext<T>): T;
214
214
  export declare function flushSync<T>(fn: () => T): T;
215
+ export { unstable_batchedUpdates, findDOMNode, render, hydrate, unmountComponentAtNode } from './hints.js';
215
216
  /**
216
217
  * Runtime portal (content rendered by `h()` after hydration; compiled source
217
218
  * components lower createPortal to an anchor instead, see portal.ts). The
@@ -246,4 +247,3 @@ export declare const reactCompat: {
246
247
  h: typeof h;
247
248
  Fragment: symbol;
248
249
  };
249
- export {};
package/dist/react.js CHANGED
@@ -477,6 +477,11 @@ export function use(value) {
477
477
  export function flushSync(fn) {
478
478
  return fn();
479
479
  }
480
+ // react-dom resolves to this module in page bundles and build-time
481
+ // evaluation, so it has the react-dom exports of the server facade (hints.ts)
482
+ // too: the APIs React 19 removed import fine and only a call fails, with
483
+ // KR8001.
484
+ export { unstable_batchedUpdates, findDOMNode, render, hydrate, unmountComponentAtNode } from './hints.js';
480
485
  /**
481
486
  * Runtime portal (content rendered by `h()` after hydration; compiled source
482
487
  * components lower createPortal to an anchor instead, see portal.ts). The
package/dist/router.js CHANGED
@@ -382,9 +382,10 @@ function storeInitialDocument(key, url) {
382
382
  if (savingData())
383
383
  return;
384
384
  const gen = cacheGen;
385
+ const release = watchUnload();
385
386
  idle(() => {
386
- if (historyDocs.has(key) || gen !== cacheGen)
387
- return;
387
+ if (historyDocs.has(key) || gen !== cacheGen || unloading)
388
+ return release();
388
389
  fetch(cacheKey(url), { headers: { Accept: 'text/html' }, credentials: 'same-origin' })
389
390
  .then(async (res) => {
390
391
  if (!res.ok || /no-store/i.test(res.headers.get('cache-control') || ''))
@@ -402,9 +403,36 @@ function storeInitialDocument(key, url) {
402
403
  })
403
404
  .catch(() => {
404
405
  /* back falls back to a normal fetch */
405
- });
406
+ })
407
+ .finally(release);
406
408
  });
407
409
  }
410
+ // True once the page started unloading (a hard navigation is pending). A fetch
411
+ // started then fails at once, and WebKit reports it as a page error even when
412
+ // the rejection is handled, so the idle copy of the first entry is skipped.
413
+ // The beforeunload listener is attached only while that copy is pending: some
414
+ // browsers keep a page with one out of the back/forward cache.
415
+ let unloading = false;
416
+ let unloadWatchers = 0;
417
+ function onBeforeUnload() {
418
+ unloading = true;
419
+ // A download or a 204 response fires beforeunload but keeps the page.
420
+ setTimeout(() => {
421
+ unloading = false;
422
+ }, 3000);
423
+ }
424
+ function watchUnload() {
425
+ if (unloadWatchers++ === 0)
426
+ window.addEventListener('beforeunload', onBeforeUnload);
427
+ let released = false;
428
+ return () => {
429
+ if (released)
430
+ return;
431
+ released = true;
432
+ if (--unloadWatchers === 0)
433
+ window.removeEventListener('beforeunload', onBeforeUnload);
434
+ };
435
+ }
408
436
  function isHTMLType(ct) {
409
437
  return /text\/html|application\/xhtml\+xml/i.test(ct);
410
438
  }
@@ -998,12 +1026,27 @@ function hashTarget(hash) {
998
1026
  }
999
1027
  return document.getElementById(id) || document.getElementsByName(id)[0] || null;
1000
1028
  }
1029
+ function pageScroller() {
1030
+ const s = globalThis.__krate_scroller;
1031
+ return s && typeof s.scrollTo === 'function' ? s : undefined;
1032
+ }
1033
+ function scrollPage(y, reason) {
1034
+ const s = pageScroller();
1035
+ if (s)
1036
+ s.scrollTo(y, reason);
1037
+ else
1038
+ window.scrollTo(0, y);
1039
+ }
1001
1040
  function scrollToHash(hash) {
1002
1041
  const el = hashTarget(hash);
1003
1042
  if (!el)
1004
1043
  return false;
1005
1044
  try {
1006
- el.scrollIntoView({ block: 'start' });
1045
+ const s = pageScroller();
1046
+ if (s)
1047
+ s.scrollTo(el, 'hash');
1048
+ else
1049
+ el.scrollIntoView({ block: 'start' });
1007
1050
  }
1008
1051
  catch {
1009
1052
  /* ignore */
@@ -1011,10 +1054,12 @@ function scrollToHash(hash) {
1011
1054
  return true;
1012
1055
  }
1013
1056
  function applyScroll(url, req) {
1057
+ // The new page has rendered: the scroller measures it before scrolling.
1058
+ pageScroller()?.resize();
1014
1059
  if (req.kind === 'pop') {
1015
1060
  const saved = req.restoreKey ? scrollPositions.get(req.restoreKey) : undefined;
1016
1061
  if (saved !== undefined) {
1017
- window.scrollTo(0, saved);
1062
+ scrollPage(saved, 'restore');
1018
1063
  return;
1019
1064
  }
1020
1065
  }
@@ -1022,7 +1067,7 @@ function applyScroll(url, req) {
1022
1067
  if (scrollToHash(hash))
1023
1068
  return;
1024
1069
  if (req.scroll && req.kind !== 'refresh')
1025
- window.scrollTo(0, 0);
1070
+ scrollPage(0, 'top');
1026
1071
  }
1027
1072
  let focusedRoot = null;
1028
1073
  // Attributes that tell a focused control apart from its siblings, in addition
@@ -2013,7 +2058,7 @@ function restoreSnapshot(snap, key) {
2013
2058
  renderedPath = pathOf(location.href);
2014
2059
  const saved = scrollPositions.get(key);
2015
2060
  if (saved !== undefined)
2016
- window.scrollTo(0, saved);
2061
+ scrollPage(saved, 'restore');
2017
2062
  updateActiveLinks();
2018
2063
  dispatch('krate:navigate', { url: location.href, status: 200 });
2019
2064
  notifyNavigation(location.href);
@@ -2054,7 +2099,7 @@ function hashNavigate(url, req) {
2054
2099
  }
2055
2100
  const hash = new URL(url).hash;
2056
2101
  if (!scrollToHash(hash) && req.scroll && !hash)
2057
- window.scrollTo(0, 0);
2102
+ scrollPage(0, 'top');
2058
2103
  emit();
2059
2104
  }
2060
2105
  function start(req) {
@@ -2176,7 +2221,7 @@ function popstateHandler(e) {
2176
2221
  currentKey = key || currentKey;
2177
2222
  const saved = key ? scrollPositions.get(key) : undefined;
2178
2223
  if (saved !== undefined)
2179
- window.scrollTo(0, saved);
2224
+ scrollPage(saved, 'restore');
2180
2225
  else
2181
2226
  scrollToHash(location.hash);
2182
2227
  emit();
@@ -2213,6 +2258,7 @@ function pagehideHandler() {
2213
2258
  }
2214
2259
  }
2215
2260
  function pageshowHandler() {
2261
+ unloading = false;
2216
2262
  try {
2217
2263
  history.scrollRestoration = 'manual';
2218
2264
  }
@@ -1,17 +1,30 @@
1
+ export interface ByteLimit<V> {
2
+ maxBytes: number;
3
+ sizeOf: (value: V) => number;
4
+ }
1
5
  export declare class SegmentedLRU<V> {
2
6
  private probation;
3
7
  private protectedSeg;
4
8
  private readonly max;
5
9
  private readonly protectedMax;
6
- constructor(maxSize: number);
10
+ private readonly limit?;
11
+ private readonly sizes;
12
+ private used;
13
+ constructor(maxSize: number, limit?: ByteLimit<V>);
7
14
  get size(): number;
15
+ /** The summed sizes of the entries (0 without a byte limit). */
16
+ get bytes(): number;
8
17
  has(key: string): boolean;
9
18
  /** Reads an entry without counting as a use. */
10
19
  peek(key: string): V | undefined;
11
20
  /** Reads an entry and counts the use: probation entries are promoted. */
12
21
  get(key: string): V | undefined;
22
+ private demoteColdest;
13
23
  /** Stores an entry. An existing key keeps its segment. Returns the evicted entries. */
14
24
  set(key: string, value: V): Array<[string, V]>;
25
+ private evictOldest;
26
+ private fitBytes;
27
+ private account;
15
28
  delete(key: string): boolean;
16
29
  clear(): void;
17
30
  keys(): string[];