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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/dist/action-context.d.ts +14 -3
  2. package/dist/action-context.js +70 -4
  3. package/dist/action-context.test.js +26 -1
  4. package/dist/actions.d.ts +12 -1
  5. package/dist/actions.js +101 -5
  6. package/dist/actions.test.js +87 -1
  7. package/dist/cache-scope.d.ts +118 -0
  8. package/dist/cache-scope.js +314 -0
  9. package/dist/cache.d.ts +55 -0
  10. package/dist/cache.js +155 -0
  11. package/dist/cache.test.d.ts +1 -0
  12. package/dist/cache.test.js +233 -0
  13. package/dist/class-helpers.d.ts +4 -4
  14. package/dist/class-helpers.js +357 -32
  15. package/dist/class-helpers.test.d.ts +1 -0
  16. package/dist/class-helpers.test.js +169 -0
  17. package/dist/context.d.ts +16 -2
  18. package/dist/context.js +44 -3
  19. package/dist/dev-overlay.js +75 -2
  20. package/dist/dev-overlay.test.js +22 -0
  21. package/dist/dom.d.ts +7 -0
  22. package/dist/dom.js +69 -3
  23. package/dist/effects.js +74 -3
  24. package/dist/error-overlay.js +4 -4
  25. package/dist/hook-args.d.ts +7 -0
  26. package/dist/hook-args.js +10 -0
  27. package/dist/htmlspec-attributes.d.ts +1 -0
  28. package/dist/htmlspec-attributes.js +159 -0
  29. package/dist/index.d.ts +3 -2
  30. package/dist/index.js +2 -1
  31. package/dist/krate-core.js +2 -0
  32. package/dist/krate-dev.js +65 -2
  33. package/dist/krate-f-actions.js +2 -0
  34. package/dist/krate-f-classes.js +8 -0
  35. package/dist/krate-f-helpers.js +2 -0
  36. package/dist/krate-f-list.js +2 -0
  37. package/dist/krate-f-router-lite.js +2 -0
  38. package/dist/krate-f-router.js +2 -0
  39. package/dist/krate-features.json +239 -0
  40. package/dist/krate-hydrate-lite.js +5 -5
  41. package/dist/krate-hydrate.js +5 -5
  42. package/dist/krate-runtime.js +5 -5
  43. package/dist/patterns.test.d.ts +1 -0
  44. package/dist/patterns.test.js +98 -0
  45. package/dist/portal.d.ts +5 -1
  46. package/dist/portal.js +15 -4
  47. package/dist/reactivity-core.test.d.ts +1 -0
  48. package/dist/reactivity-core.test.js +152 -0
  49. package/dist/reconcile.js +4 -2
  50. package/dist/request-context.d.ts +62 -0
  51. package/dist/request-context.js +107 -0
  52. package/dist/router-layout.test.d.ts +1 -0
  53. package/dist/router-layout.test.js +179 -0
  54. package/dist/router-lite.d.ts +25 -0
  55. package/dist/router-lite.js +73 -0
  56. package/dist/router-nav.test.d.ts +1 -0
  57. package/dist/router-nav.test.js +437 -0
  58. package/dist/router-slots.test.d.ts +1 -0
  59. package/dist/router-slots.test.js +144 -0
  60. package/dist/router-speculation.test.d.ts +1 -0
  61. package/dist/router-speculation.test.js +25 -0
  62. package/dist/router-styles.test.d.ts +1 -0
  63. package/dist/router-styles.test.js +98 -0
  64. package/dist/router.d.ts +66 -2
  65. package/dist/router.js +1617 -648
  66. package/dist/server-async.test.d.ts +1 -0
  67. package/dist/server-async.test.js +194 -0
  68. package/dist/server-renderer.js +556 -132
  69. package/dist/server.d.ts +24 -0
  70. package/dist/server.js +247 -11
  71. package/dist/server.test.js +20 -0
  72. package/dist/signal.d.ts +41 -4
  73. package/dist/signal.js +254 -24
  74. package/dist/slots.d.ts +5 -1
  75. package/dist/slots.js +40 -3
  76. package/package.json +6 -2
@@ -0,0 +1,98 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import { h, krateSpread } from './dom';
3
+ import { createContext, krateContextRows } from './context';
4
+ import { createSignal, krateDerived } from './signal';
5
+ import { krateParam } from './hook-args';
6
+ import { krateCondSwap } from './slots';
7
+ import { krateOn } from './events';
8
+ const tick = () => new Promise((r) => setTimeout(r, 0));
9
+ const SVG_NS = 'http://www.w3.org/2000/svg';
10
+ describe('SVG elements created by h()', () => {
11
+ it('uses the SVG namespace for SVG-only tags and their children', () => {
12
+ const svg = h('svg', { width: '10' }, h('g', null, h('circle', { r: '2' })));
13
+ expect(svg.namespaceURI).toBe(SVG_NS);
14
+ const circle = svg.querySelector('circle');
15
+ expect(circle.namespaceURI).toBe(SVG_NS);
16
+ expect(circle.parentElement.localName).toBe('g');
17
+ });
18
+ it('re-creates an ambiguous tag appended to an SVG parent in the SVG namespace', () => {
19
+ const svg = h('svg', null, h('a', { href: '#x' }, h('path', { d: 'M0 0' })));
20
+ const a = svg.querySelector('a');
21
+ expect(a.namespaceURI).toBe(SVG_NS);
22
+ expect(a.getAttribute('href')).toBe('#x');
23
+ expect(a.firstElementChild.namespaceURI).toBe(SVG_NS);
24
+ });
25
+ it('keeps HTML inside a foreignObject', () => {
26
+ const fo = h('svg', null, h('foreignObject', null, h('a', { href: '#y' }, 'x')));
27
+ expect(fo.querySelector('a').namespaceURI).toBe('http://www.w3.org/1999/xhtml');
28
+ });
29
+ });
30
+ describe('krateCondSwap with an SVG template', () => {
31
+ it('unwraps the <svg> wrapper so the branch keeps the SVG namespace', () => {
32
+ document.body.innerHTML =
33
+ '<svg id="s"><!--k:c--><!--/k:c--></svg><template data-kc="c" data-kb="c" data-kns="svg"><svg><g id="grp"><path d="M0 0"></path></g></svg></template>';
34
+ const start = document.querySelector('svg').firstChild;
35
+ const tpl = document.querySelector('template');
36
+ krateCondSwap(start, true, tpl);
37
+ const g = document.getElementById('grp');
38
+ expect(g.namespaceURI).toBe(SVG_NS);
39
+ expect(g.parentElement.id).toBe('s');
40
+ expect(g.firstElementChild.namespaceURI).toBe(SVG_NS);
41
+ });
42
+ });
43
+ describe('krateSpread', () => {
44
+ it('applies attributes and handlers and removes keys that disappear', async () => {
45
+ const [on, setOn] = createSignal(true);
46
+ const el = document.createElement('button');
47
+ document.body.appendChild(el);
48
+ let clicks = 0;
49
+ krateSpread(el, () => (on() ? { title: 'x', className: 'a', onClick: () => clicks++ } : { className: 'b' }));
50
+ expect(el.getAttribute('title')).toBe('x');
51
+ expect(el.getAttribute('class')).toBe('a');
52
+ el.dispatchEvent(new Event('click', { bubbles: true }));
53
+ expect(clicks).toBe(1);
54
+ setOn(false);
55
+ await tick();
56
+ expect(el.hasAttribute('title')).toBe(false);
57
+ expect(el.getAttribute('class')).toBe('b');
58
+ el.dispatchEvent(new Event('click', { bubbles: true }));
59
+ expect(clicks).toBe(1);
60
+ });
61
+ });
62
+ describe('krateContextRows', () => {
63
+ it('shows live provider values to rows created under it', async () => {
64
+ const Sel = createContext('');
65
+ const [sel, setSel] = createSignal('a');
66
+ const row = krateContextRows([[Sel, () => sel()]], () => Sel.useContextLive());
67
+ const read = row();
68
+ expect(read()).toBe('a');
69
+ setSel('b');
70
+ expect(read()).toBe('b');
71
+ // Outside the rows the context has its default again.
72
+ expect(Sel.useContext()).toBe('');
73
+ });
74
+ });
75
+ describe('krateParam', () => {
76
+ it('unwraps a derived getter argument and passes other values through', () => {
77
+ const [n, setN] = createSignal(1);
78
+ const arg = krateDerived(() => n() * 2);
79
+ expect(krateParam(arg)).toBe(2);
80
+ setN(2);
81
+ expect(krateParam(arg)).toBe(4);
82
+ expect(krateParam(5)).toBe(5);
83
+ const fn = () => 1;
84
+ expect(krateParam(fn)).toBe(fn);
85
+ });
86
+ });
87
+ describe('krateOn unaffected by spread removal', () => {
88
+ it('removes a handler with null', () => {
89
+ const el = document.createElement('div');
90
+ document.body.appendChild(el);
91
+ let n = 0;
92
+ krateOn(el, 'onClick', () => n++);
93
+ el.dispatchEvent(new Event('click', { bubbles: true }));
94
+ krateOn(el, 'onClick', null);
95
+ el.dispatchEvent(new Event('click', { bubbles: true }));
96
+ expect(n).toBe(1);
97
+ });
98
+ });
package/dist/portal.d.ts CHANGED
@@ -38,6 +38,10 @@ export declare function kratePortalScan(roots: ParentNode[], visit: (content: Do
38
38
  * portals first, then portal templates under `roots` (not yet mounted).
39
39
  */
40
40
  export declare function kratePortalFind(selector: string, roots: ParentNode[]): Element | null;
41
- /** Forgets the portal state of the previous page (SPA navigation). */
41
+ /**
42
+ * Forgets the portal state of the previous page (SPA navigation). Portals
43
+ * whose anchor is still in the document (inside a layout the router kept
44
+ * mounted) stay mounted.
45
+ */
42
46
  export declare function kratePortalReset(): void;
43
47
  export {};
package/dist/portal.js CHANGED
@@ -170,9 +170,20 @@ export function kratePortalFind(selector, roots) {
170
170
  });
171
171
  return found;
172
172
  }
173
- /** Forgets the portal state of the previous page (SPA navigation). */
173
+ /**
174
+ * Forgets the portal state of the previous page (SPA navigation). Portals
175
+ * whose anchor is still in the document (inside a layout the router kept
176
+ * mounted) stay mounted.
177
+ */
174
178
  export function kratePortalReset() {
175
- for (const a of Array.from(mounted))
176
- kratePortalUnmount(a, true);
177
- resolvers.clear();
179
+ const live = new Set();
180
+ for (const a of Array.from(mounted)) {
181
+ if (!a.isConnected)
182
+ kratePortalUnmount(a, true);
183
+ else
184
+ live.add(a.getAttribute('data-krate-portal') || '');
185
+ }
186
+ for (const id of Array.from(resolvers.keys()))
187
+ if (!live.has(id))
188
+ resolvers.delete(id);
178
189
  }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,152 @@
1
+ import { describe, it, expect, beforeEach } from 'vitest';
2
+ import { createSignal, createEffect, createMemo, disposeAll, krateFlushSync, onCleanup } from './signal';
3
+ const tick = () => new Promise((r) => setTimeout(r, 0));
4
+ describe('effect update loops', () => {
5
+ beforeEach(() => disposeAll());
6
+ it('throws Maximum update depth exceeded for two effects that feed each other', () => {
7
+ const [a, setA] = createSignal(0);
8
+ const [b, setB] = createSignal(0);
9
+ createEffect(() => setB(a() + 1));
10
+ createEffect(() => setA(b() + 1));
11
+ expect(() => krateFlushSync()).toThrow(/Maximum update depth exceeded/);
12
+ // The queue was dropped: nothing is pending and later writes still work.
13
+ expect(() => krateFlushSync()).not.toThrow();
14
+ let seen = -1;
15
+ createEffect(() => {
16
+ seen = 1;
17
+ });
18
+ expect(seen).toBe(1);
19
+ });
20
+ it('keeps the event loop responsive after the loop is reported', async () => {
21
+ const [a, setA] = createSignal(0);
22
+ const [b, setB] = createSignal(0);
23
+ createEffect(() => setB(a() + 1));
24
+ createEffect(() => setA(b() + 1));
25
+ try {
26
+ krateFlushSync();
27
+ }
28
+ catch {
29
+ // reported
30
+ }
31
+ let ticked = false;
32
+ setTimeout(() => (ticked = true), 0);
33
+ await tick();
34
+ expect(ticked).toBe(true);
35
+ });
36
+ it('names the looping effect in the message', () => {
37
+ const [a, setA] = createSignal(0);
38
+ createEffect(function bumpCounter() {
39
+ setA(a() + 1);
40
+ });
41
+ // A self-write only reruns once; add a partner to make it loop.
42
+ const [b, setB] = createSignal(0);
43
+ createEffect(function ping() {
44
+ setB(a() + 1);
45
+ });
46
+ createEffect(function pong() {
47
+ setA(b() + 1);
48
+ });
49
+ expect(() => krateFlushSync()).toThrow(/ping|pong|bumpCounter/);
50
+ });
51
+ it('still settles a long but finite cascade', () => {
52
+ const sigs = Array.from({ length: 30 }, () => createSignal(0));
53
+ for (let i = 1; i < sigs.length; i++) {
54
+ createEffect(() => sigs[i][1](sigs[i - 1][0]() + 1));
55
+ }
56
+ sigs[0][1](1);
57
+ krateFlushSync();
58
+ expect(sigs[29][0]()).toBe(30);
59
+ });
60
+ });
61
+ describe('effect dependency tracking', () => {
62
+ beforeEach(() => disposeAll());
63
+ it('drops dependencies the last run did not read', () => {
64
+ const [cond, setCond] = createSignal(true);
65
+ const [x, setX] = createSignal(0);
66
+ const [y] = createSignal(0);
67
+ let runs = 0;
68
+ createEffect(() => {
69
+ runs++;
70
+ cond() ? x() : y();
71
+ });
72
+ expect(runs).toBe(1);
73
+ setCond(false);
74
+ krateFlushSync();
75
+ expect(runs).toBe(2);
76
+ setX(5);
77
+ krateFlushSync();
78
+ setX(6);
79
+ krateFlushSync();
80
+ expect(runs).toBe(2);
81
+ });
82
+ });
83
+ describe('nested effects', () => {
84
+ beforeEach(() => disposeAll());
85
+ it('disposes an inner effect when the parent effect re-runs', () => {
86
+ const [a, setA] = createSignal(0);
87
+ const [b, setB] = createSignal(0);
88
+ let innerRuns = 0;
89
+ createEffect(() => {
90
+ a();
91
+ createEffect(() => {
92
+ b();
93
+ innerRuns++;
94
+ });
95
+ });
96
+ expect(innerRuns).toBe(1);
97
+ setA(1);
98
+ krateFlushSync();
99
+ setA(2);
100
+ krateFlushSync();
101
+ expect(innerRuns).toBe(3);
102
+ innerRuns = 0;
103
+ setB(1);
104
+ krateFlushSync();
105
+ expect(innerRuns).toBe(1);
106
+ });
107
+ it('runs the inner effect cleanup when the parent re-runs', () => {
108
+ const [a, setA] = createSignal(0);
109
+ const log = [];
110
+ createEffect(() => {
111
+ const v = a();
112
+ createEffect(() => {
113
+ onCleanup(() => log.push('clean' + v));
114
+ });
115
+ });
116
+ setA(1);
117
+ krateFlushSync();
118
+ expect(log).toEqual(['clean0']);
119
+ });
120
+ });
121
+ describe('createMemo', () => {
122
+ beforeEach(() => disposeAll());
123
+ it('is current on a synchronous read after a write', () => {
124
+ const [a, setA] = createSignal(1);
125
+ const m = createMemo(() => a() * 10);
126
+ expect(m()).toBe(10);
127
+ setA(5);
128
+ expect(m()).toBe(50);
129
+ });
130
+ it('memoizes between writes and propagates to effects once', () => {
131
+ const [a, setA] = createSignal(1);
132
+ let computes = 0;
133
+ const m = createMemo(() => {
134
+ computes++;
135
+ return a() % 2;
136
+ });
137
+ let runs = 0;
138
+ createEffect(() => {
139
+ m();
140
+ runs++;
141
+ });
142
+ expect(m()).toBe(1);
143
+ expect(m()).toBe(1);
144
+ expect(computes).toBe(1);
145
+ setA(3);
146
+ krateFlushSync();
147
+ expect(runs).toBe(1);
148
+ setA(4);
149
+ krateFlushSync();
150
+ expect(runs).toBe(2);
151
+ });
152
+ });
package/dist/reconcile.js CHANGED
@@ -173,8 +173,9 @@ function syncAttributes(oldEl, newEl) {
173
173
  oldEl.setAttribute(name, value);
174
174
  }
175
175
  }
176
- // Pass 2: remove attributes no longer present.
177
- for (let i = 0; i < oldEl.attributes.length; i++) {
176
+ // Pass 2: remove attributes no longer present. Iterate backwards because
177
+ // removing an attribute shifts the live NamedNodeMap left.
178
+ for (let i = oldEl.attributes.length - 1; i >= 0; i--) {
178
179
  const name = oldEl.attributes[i].name;
179
180
  if (!newNames.has(name)) {
180
181
  oldEl.removeAttribute(name);
@@ -336,6 +337,7 @@ export function reconcileTrees(oldRoot, newRoot) {
336
337
  if (oldEl.tagName !== newEl.tagName) {
337
338
  const imported = document.importNode(newRoot, true);
338
339
  if (oldEl.parentNode) {
340
+ disposeNode(oldEl);
339
341
  oldEl.parentNode.replaceChild(imported, oldEl);
340
342
  }
341
343
  return;
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Request context for server components, exported from `@krate/runtime/server`.
3
+ *
4
+ * The SSR sidecar renders every page and region inside an AsyncLocalStorage
5
+ * scope and publishes it on `globalThis[Symbol.for('krate.request.store')]`.
6
+ * `headers()` and `cookies()` read that scope while a server component renders
7
+ * (and the action scope while a server action runs), so the same imports work
8
+ * in both places.
9
+ */
10
+ /** The request a server component is rendering for. */
11
+ export interface RequestContext {
12
+ url: string;
13
+ method: string;
14
+ headers: Headers;
15
+ /** Request cookies parsed from the Cookie header. */
16
+ cookies: Map<string, string>;
17
+ params: Record<string, string>;
18
+ searchParams: Record<string, string>;
19
+ }
20
+ /** The current render request, or undefined outside a server render. */
21
+ export declare function getRequestContext(): RequestContext | undefined;
22
+ /** Parses a Cookie request header into name/value pairs. */
23
+ export declare function parseCookieHeader(header: string | null | undefined): Map<string, string>;
24
+ /**
25
+ * thenable makes a value usable both synchronously and with `await`, matching
26
+ * Next.js 15 where `params`, `searchParams`, `cookies()` and `headers()` are
27
+ * Promises: `params.slug` and `(await params).slug` both work. The `then` is
28
+ * non-enumerable, so spreading or JSON-serializing the value is unaffected, and
29
+ * it resolves to a plain copy so awaiting never loops.
30
+ */
31
+ export declare function thenable<T extends object>(value: T, resolved: () => unknown): T & PromiseLike<T>;
32
+ /** thenableRecord wraps a plain record (route params, search params). */
33
+ export declare function thenableRecord<T extends Record<string, any>>(rec: T | undefined): T & PromiseLike<T>;
34
+ /** Read-only cookie view used while a server component renders. */
35
+ export interface RequestCookies {
36
+ get(name: string): {
37
+ name: string;
38
+ value: string;
39
+ } | undefined;
40
+ getAll(): Array<{
41
+ name: string;
42
+ value: string;
43
+ }>;
44
+ has(name: string): boolean;
45
+ set(name: string, value: string, options?: unknown): never;
46
+ delete(name: string, options?: unknown): never;
47
+ }
48
+ export declare function requestCookies(jar: Map<string, string>): RequestCookies;
49
+ /** Thrown by notFound(); the sidecar turns it into a 404 response. */
50
+ export interface NotFoundSignal extends Error {
51
+ __krateNotFound: true;
52
+ digest: string;
53
+ }
54
+ /**
55
+ * Stops rendering and responds with the 404 page. Works in server components
56
+ * (async pages and their children) rendered by the SSR sidecar.
57
+ */
58
+ export declare function notFound(): never;
59
+ /** isNotFoundSignal reports whether err was thrown by notFound(). */
60
+ export declare function isNotFoundSignal(err: unknown): boolean;
61
+ /** redirectTarget returns the URL of a redirect() signal, or "" for other errors. */
62
+ export declare function redirectTarget(err: unknown): string;
@@ -0,0 +1,107 @@
1
+ /**
2
+ * Request context for server components, exported from `@krate/runtime/server`.
3
+ *
4
+ * The SSR sidecar renders every page and region inside an AsyncLocalStorage
5
+ * scope and publishes it on `globalThis[Symbol.for('krate.request.store')]`.
6
+ * `headers()` and `cookies()` read that scope while a server component renders
7
+ * (and the action scope while a server action runs), so the same imports work
8
+ * in both places.
9
+ */
10
+ const REQUEST_STORE = Symbol.for('krate.request.store');
11
+ /** The current render request, or undefined outside a server render. */
12
+ export function getRequestContext() {
13
+ const store = globalThis[REQUEST_STORE];
14
+ return store && typeof store.getStore === 'function' ? store.getStore() : undefined;
15
+ }
16
+ /** Parses a Cookie request header into name/value pairs. */
17
+ export function parseCookieHeader(header) {
18
+ const out = new Map();
19
+ if (!header)
20
+ return out;
21
+ for (const part of header.split(';')) {
22
+ const eq = part.indexOf('=');
23
+ if (eq <= 0)
24
+ continue;
25
+ const name = part.slice(0, eq).trim();
26
+ let value = part.slice(eq + 1).trim();
27
+ if (value.startsWith('"') && value.endsWith('"'))
28
+ value = value.slice(1, -1);
29
+ try {
30
+ value = decodeURIComponent(value);
31
+ }
32
+ catch {
33
+ // keep the raw value when it is not valid percent-encoding
34
+ }
35
+ if (name && !out.has(name))
36
+ out.set(name, value);
37
+ }
38
+ return out;
39
+ }
40
+ /**
41
+ * thenable makes a value usable both synchronously and with `await`, matching
42
+ * Next.js 15 where `params`, `searchParams`, `cookies()` and `headers()` are
43
+ * Promises: `params.slug` and `(await params).slug` both work. The `then` is
44
+ * non-enumerable, so spreading or JSON-serializing the value is unaffected, and
45
+ * it resolves to a plain copy so awaiting never loops.
46
+ */
47
+ export function thenable(value, resolved) {
48
+ Object.defineProperty(value, 'then', {
49
+ value: (onFulfilled, onRejected) => Promise.resolve(resolved()).then(onFulfilled, onRejected),
50
+ enumerable: false,
51
+ configurable: true,
52
+ });
53
+ return value;
54
+ }
55
+ /** thenableRecord wraps a plain record (route params, search params). */
56
+ export function thenableRecord(rec) {
57
+ const plain = { ...(rec || {}) };
58
+ return thenable({ ...plain }, () => ({ ...plain }));
59
+ }
60
+ export function requestCookies(jar) {
61
+ const readOnly = (op) => {
62
+ throw new Error(`cookies().${op}() cannot be called while a server component renders; ` +
63
+ `modify cookies in a server action ("use server") or an API route instead`);
64
+ };
65
+ const make = () => ({
66
+ get: (name) => (jar.has(name) ? { name, value: jar.get(name) } : undefined),
67
+ getAll: () => [...jar.entries()].map(([name, value]) => ({ name, value })),
68
+ has: (name) => jar.has(name),
69
+ set: () => readOnly('set'),
70
+ delete: () => readOnly('delete'),
71
+ });
72
+ return thenable(make(), make);
73
+ }
74
+ /**
75
+ * Stops rendering and responds with the 404 page. Works in server components
76
+ * (async pages and their children) rendered by the SSR sidecar.
77
+ */
78
+ export function notFound() {
79
+ const err = new Error('NEXT_NOT_FOUND');
80
+ err.__krateNotFound = true;
81
+ err.digest = 'NEXT_NOT_FOUND';
82
+ throw err;
83
+ }
84
+ /** isNotFoundSignal reports whether err was thrown by notFound(). */
85
+ export function isNotFoundSignal(err) {
86
+ if (!err || typeof err !== 'object')
87
+ return false;
88
+ const e = err;
89
+ return e.__krateNotFound === true || e.digest === 'NEXT_NOT_FOUND' || e.message === 'NEXT_NOT_FOUND' ||
90
+ (typeof e.digest === 'string' && e.digest.startsWith('NEXT_HTTP_ERROR_FALLBACK;404'));
91
+ }
92
+ /** redirectTarget returns the URL of a redirect() signal, or "" for other errors. */
93
+ export function redirectTarget(err) {
94
+ if (!err || typeof err !== 'object')
95
+ return '';
96
+ const e = err;
97
+ if (typeof e.__krateRedirect === 'string')
98
+ return e.__krateRedirect;
99
+ if (typeof e.message === 'string' && e.message.startsWith('NEXT_REDIRECT:'))
100
+ return e.message.slice('NEXT_REDIRECT:'.length);
101
+ if (typeof e.digest === 'string' && e.digest.startsWith('NEXT_REDIRECT;')) {
102
+ const parts = e.digest.split(';');
103
+ if (parts.length >= 3)
104
+ return parts[2];
105
+ }
106
+ return '';
107
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,179 @@
1
+ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
2
+ import { initRouter, destroyRouter, krateRouter } from './router';
3
+ import { createEffect, createSignal, onCleanup, disposeAll, krateDisposeExcept, krateEnterScope, krateLeaveScope, krateKeepScopes, } from './signal';
4
+ function routeInfo(chain) {
5
+ return `<script type="application/json" id="__krate_route">${JSON.stringify({ v: 1, chain })}</script>`;
6
+ }
7
+ const LAYOUT = { id: '_lroot_', k: 'layout', d: 0, p: true };
8
+ function shell(inner, title = 'Nav') {
9
+ return `<header id="nav"><input id="q">${title}</header><!--kl:_lroot_-->${inner}<!--/kl:_lroot_-->`;
10
+ }
11
+ function doc(title, rootHTML, chain) {
12
+ return `<!doctype html><html><head><title>${title}</title></head><body><div id="root">${rootHTML}</div>${routeInfo(chain)}</body></html>`;
13
+ }
14
+ let routes;
15
+ function setup(rootHTML, chain, path = '/a') {
16
+ history.replaceState(null, '', path);
17
+ document.head.innerHTML = '<title>A</title>';
18
+ document.body.innerHTML = `<div id="root">${rootHTML}</div>${routeInfo(chain)}`;
19
+ initRouter();
20
+ }
21
+ beforeEach(() => {
22
+ destroyRouter();
23
+ disposeAll();
24
+ globalThis.__KRATE_CFG__ = { viewTransitions: false };
25
+ const g = globalThis;
26
+ g.krateDisposeExcept = krateDisposeExcept;
27
+ g.krateKeepScopes = krateKeepScopes;
28
+ g.disposeAll = disposeAll;
29
+ g.__krateHardNavigate = () => { };
30
+ routes = {};
31
+ vi.stubGlobal('fetch', vi.fn(async (input) => {
32
+ const u = new URL(input, location.href);
33
+ const body = routes[u.pathname];
34
+ return {
35
+ ok: !!body,
36
+ status: body ? 200 : 404,
37
+ url: u.href,
38
+ headers: new Headers({ 'content-type': 'text/html' }),
39
+ text: async () => body || '',
40
+ };
41
+ }));
42
+ });
43
+ afterEach(() => {
44
+ destroyRouter();
45
+ vi.unstubAllGlobals();
46
+ const g = globalThis;
47
+ delete g.krateDisposeExcept;
48
+ delete g.krateKeepScopes;
49
+ delete g.disposeAll;
50
+ delete g.__krateHardNavigate;
51
+ delete g.__KRATE_CFG__;
52
+ });
53
+ describe('layout persistence', () => {
54
+ it('keeps a shared layout mounted and swaps only its children', async () => {
55
+ setup(shell('<main>Page A</main>'), [LAYOUT]);
56
+ const nav = document.getElementById('nav');
57
+ document.getElementById('q').value = 'typed';
58
+ routes['/b'] = doc('B', shell('<main>Page B</main>'), [LAYOUT]);
59
+ await krateRouter.push('/b');
60
+ expect(document.querySelector('main').textContent).toBe('Page B');
61
+ expect(document.getElementById('nav')).toBe(nav);
62
+ expect(document.getElementById('q').value).toBe('typed');
63
+ });
64
+ it('keeps effects of the kept layout scope and disposes page effects', async () => {
65
+ setup(shell('<main>Page A</main>'), [LAYOUT]);
66
+ const log = [];
67
+ const [count, setCount] = createSignal(0);
68
+ // Layout hydration code runs inside its route scope.
69
+ expect(krateEnterScope('_lroot_')).toBe(true);
70
+ createEffect(() => {
71
+ log.push('layout:' + count());
72
+ onCleanup(() => log.push('layout-cleanup'));
73
+ });
74
+ krateLeaveScope();
75
+ // Page hydration code (no scope).
76
+ createEffect(() => {
77
+ onCleanup(() => log.push('page-cleanup'));
78
+ });
79
+ onCleanup(() => log.push('page-root-cleanup'));
80
+ log.length = 0;
81
+ routes['/b'] = doc('B', shell('<main>Page B</main>'), [LAYOUT]);
82
+ await krateRouter.push('/b');
83
+ expect(log).toContain('page-cleanup');
84
+ expect(log).toContain('page-root-cleanup');
85
+ expect(log).not.toContain('layout-cleanup');
86
+ log.length = 0;
87
+ setCount(1);
88
+ await new Promise((r) => setTimeout(r, 0));
89
+ // The layout effect is still live.
90
+ expect(log).toEqual(['layout-cleanup', 'layout:1']);
91
+ });
92
+ it('remounts layouts the compiler marked as not persistable', async () => {
93
+ globalThis.__KRATE_CFG__ = { viewTransitions: false, dev: true };
94
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => { });
95
+ const blocked = { ...LAYOUT, p: false, why: 'the page uses class components' };
96
+ setup(shell('<main>Page A</main>'), [blocked]);
97
+ const nav = document.getElementById('nav');
98
+ routes['/b'] = doc('B', shell('<main>Page B</main>'), [blocked]);
99
+ await krateRouter.push('/b');
100
+ expect(document.getElementById('nav')).not.toBe(nav);
101
+ expect(warn.mock.calls.some((c) => String(c[0]).includes('class components'))).toBe(true);
102
+ warn.mockRestore();
103
+ });
104
+ it('swaps the whole root when the layouts differ', async () => {
105
+ setup(shell('<main>Page A</main>'), [LAYOUT]);
106
+ const nav = document.getElementById('nav');
107
+ const other = { id: '_lother_', k: 'layout', d: 0, p: true };
108
+ routes['/b'] = doc('B', '<aside>other</aside><!--kl:_lother_--><main>B</main><!--/kl:_lother_-->', [other]);
109
+ await krateRouter.push('/b');
110
+ expect(nav.isConnected).toBe(false);
111
+ expect(document.querySelector('aside')).not.toBeNull();
112
+ });
113
+ it('remounts a layout under a dynamic segment when the segment value changes', async () => {
114
+ const section = { id: '_lpost_', k: 'layout', d: 2, p: true };
115
+ const html = (slug) => shell(`<div id="post-shell">${slug}<!--kl:_lpost_--><p>${slug}</p><!--/kl:_lpost_--></div>`);
116
+ setup(html('a'), [LAYOUT, section], '/blog/a');
117
+ const nav = document.getElementById('nav');
118
+ const postShell = document.getElementById('post-shell');
119
+ routes['/blog/b'] = doc('B', html('b'), [LAYOUT, section]);
120
+ await krateRouter.push('/blog/b');
121
+ // The root layout stays, the [slug] layout remounts.
122
+ expect(document.getElementById('nav')).toBe(nav);
123
+ expect(document.getElementById('post-shell')).not.toBe(postShell);
124
+ expect(document.querySelector('p').textContent).toBe('b');
125
+ });
126
+ });
127
+ describe('templates', () => {
128
+ it('remounts the template on every navigation, keeping the parent layout', async () => {
129
+ const tpl = { id: '_ltpl_', k: 'template', d: 0, p: false };
130
+ const html = (page) => shell(`<section id="tpl"><input id="t"><!--kl:_ltpl_--><main>${page}</main><!--/kl:_ltpl_--></section>`);
131
+ setup(html('A'), [LAYOUT, tpl]);
132
+ const nav = document.getElementById('nav');
133
+ const section = document.getElementById('tpl');
134
+ document.getElementById('t').value = 'stale';
135
+ routes['/b'] = doc('B', html('B'), [LAYOUT, tpl]);
136
+ await krateRouter.push('/b');
137
+ expect(document.getElementById('nav')).toBe(nav);
138
+ expect(document.getElementById('tpl')).not.toBe(section);
139
+ expect(document.getElementById('t').value).toBe('');
140
+ expect(document.querySelector('main').textContent).toBe('B');
141
+ });
142
+ });
143
+ describe('route scopes', () => {
144
+ it('krateEnterScope skips kept scopes only while the router keeps them', () => {
145
+ krateKeepScopes(['_lroot_']);
146
+ expect(krateEnterScope('_lroot_')).toBe(false);
147
+ expect(krateEnterScope('_lother_')).toBe(true);
148
+ krateLeaveScope();
149
+ krateKeepScopes([]);
150
+ expect(krateEnterScope('_lroot_')).toBe(true);
151
+ krateLeaveScope();
152
+ });
153
+ it('krateDisposeExcept([]) is a full teardown', () => {
154
+ const log = [];
155
+ krateEnterScope('_lroot_');
156
+ onCleanup(() => log.push('layout'));
157
+ krateLeaveScope();
158
+ onCleanup(() => log.push('page'));
159
+ krateDisposeExcept([]);
160
+ expect(log.sort()).toEqual(['layout', 'page']);
161
+ });
162
+ it('effects created later by a kept effect inherit its scope', async () => {
163
+ const log = [];
164
+ const [show, setShow] = createSignal(false);
165
+ krateEnterScope('_lroot_');
166
+ createEffect(() => {
167
+ if (show()) {
168
+ createEffect(() => onCleanup(() => log.push('nested')));
169
+ }
170
+ });
171
+ krateLeaveScope();
172
+ setShow(true);
173
+ await new Promise((r) => setTimeout(r, 0));
174
+ krateDisposeExcept(['_lroot_']);
175
+ expect(log).toEqual([]);
176
+ disposeAll();
177
+ expect(log).toEqual(['nested']);
178
+ });
179
+ });