@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,144 @@
1
+ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
2
+ import { initRouter, destroyRouter, krateRouter, matchRoutePattern, compareRouteSpecificity } from './router';
3
+ import { disposeAll, krateDisposeExcept, krateDisposeScopes, krateKeepScopes } from './signal';
4
+ const KEY = '_sabc_modal';
5
+ function chain(src, scope) {
6
+ const info = {
7
+ v: 1,
8
+ chain: [{ id: '_lroot_', k: 'layout', d: 0, p: true, s: [{ n: 'modal', key: KEY, scope, src, i: ['photo/[id]'] }] }],
9
+ };
10
+ return `<script type="application/json" id="__krate_route">${JSON.stringify(info)}</script>`;
11
+ }
12
+ function shell(children, slot) {
13
+ return `<nav id="nav">nav</nav><main><!--kl:_lroot_-->${children}<!--/kl:_lroot_--></main><aside id="slot"><!--ks:${KEY}-->${slot}<!--/ks:${KEY}--></aside>`;
14
+ }
15
+ function doc(title, root, info) {
16
+ return `<!doctype html><html><head><title>${title}</title></head><body><div id="root">${root}</div>${info}</body></html>`;
17
+ }
18
+ function fragment(id) {
19
+ const info = { v: 1, frag: { key: KEY, scope: '_lfrag_', target: 'photo/[id]' } };
20
+ return `<!doctype html><html><head><title>x</title></head><body><div id="root"><!--ks:${KEY}--><div id="modal">Modal ${id}</div><!--/ks:${KEY}--></div><script type="application/json" id="__krate_route">${JSON.stringify(info)}</script></body></html>`;
21
+ }
22
+ let routes;
23
+ let fetchMock;
24
+ beforeEach(() => {
25
+ destroyRouter();
26
+ disposeAll();
27
+ const g = globalThis;
28
+ g.__KRATE_CFG__ = { viewTransitions: false };
29
+ g.krateDisposeExcept = krateDisposeExcept;
30
+ g.krateDisposeScopes = krateDisposeScopes;
31
+ g.krateKeepScopes = krateKeepScopes;
32
+ g.disposeAll = disposeAll;
33
+ g.__krateHardNavigate = () => { };
34
+ routes = {
35
+ '/_krate/i/_sabc_modal/photo/1': { body: fragment('1') },
36
+ '/_krate/i/_sabc_modal/photo/2': { body: fragment('2') },
37
+ '/about': { body: doc('About', shell('<p id="about">about</p>', '<i id="def"></i>'), chain('default', '_ldef_')) },
38
+ '/photo/1': { body: doc('Photo', shell('<h1 id="photo">photo</h1>', '<i id="def"></i>'), chain('default', '_ldef_')) },
39
+ };
40
+ fetchMock = vi.fn(async (input) => {
41
+ const u = new URL(input, location.href);
42
+ const r = routes[u.pathname];
43
+ const status = r ? (r.status ?? 200) : 404;
44
+ return {
45
+ ok: status < 300,
46
+ status,
47
+ url: u.href,
48
+ headers: new Headers({ 'content-type': r ? 'text/html' : 'text/plain' }),
49
+ text: async () => (r ? r.body : 'missing'),
50
+ };
51
+ });
52
+ vi.stubGlobal('fetch', fetchMock);
53
+ history.replaceState(null, '', '/');
54
+ document.head.innerHTML = '<title>Feed</title>';
55
+ document.body.innerHTML = `<div id="root">${shell('<section id="feed">feed</section>', '<i id="def"></i>')}</div>${chain('default', '_ldef_')}`;
56
+ initRouter();
57
+ });
58
+ afterEach(() => {
59
+ destroyRouter();
60
+ vi.unstubAllGlobals();
61
+ const g = globalThis;
62
+ for (const k of ['__KRATE_CFG__', 'krateDisposeExcept', 'krateDisposeScopes', 'krateKeepScopes', 'disposeAll', '__krateHardNavigate'])
63
+ delete g[k];
64
+ });
65
+ async function settle() {
66
+ for (let i = 0; i < 20; i++)
67
+ await Promise.resolve();
68
+ await new Promise((r) => setTimeout(r, 0));
69
+ }
70
+ function pop(state, url) {
71
+ history.replaceState(state, '', url);
72
+ window.dispatchEvent(new PopStateEvent('popstate', { state }));
73
+ }
74
+ describe('intercepting routes', () => {
75
+ it('soft navigation renders the intercepting fragment into the slot', async () => {
76
+ const feed = document.getElementById('feed');
77
+ await krateRouter.push('/photo/1');
78
+ expect(fetchMock.mock.calls.map((c) => new URL(c[0]).pathname)).toEqual(['/_krate/i/_sabc_modal/photo/1']);
79
+ expect(location.pathname).toBe('/photo/1');
80
+ expect(document.getElementById('modal').textContent).toBe('Modal 1');
81
+ expect(document.getElementById('feed')).toBe(feed);
82
+ expect(document.getElementById('def')).toBeNull();
83
+ });
84
+ it('back restores the slot content without refetching; forward reopens it', async () => {
85
+ const homeState = history.state;
86
+ const def = document.getElementById('def');
87
+ await krateRouter.push('/photo/1');
88
+ const photoState = history.state;
89
+ fetchMock.mockClear();
90
+ pop(homeState, '/');
91
+ await settle();
92
+ expect(fetchMock).not.toHaveBeenCalled();
93
+ expect(document.getElementById('modal')).toBeNull();
94
+ expect(document.getElementById('def')).toBe(def);
95
+ pop(photoState, '/photo/1');
96
+ await settle();
97
+ expect(document.getElementById('modal').textContent).toBe('Modal 1');
98
+ });
99
+ it('chained intercepts replace the fragment', async () => {
100
+ await krateRouter.push('/photo/1');
101
+ await krateRouter.push('/photo/2');
102
+ expect(document.getElementById('modal').textContent).toBe('Modal 2');
103
+ expect(document.querySelectorAll('#modal').length).toBe(1);
104
+ });
105
+ it('a soft navigation without a slot match keeps the slot content', async () => {
106
+ await krateRouter.push('/photo/1');
107
+ await krateRouter.push('/about');
108
+ expect(document.getElementById('about')).not.toBeNull();
109
+ expect(document.getElementById('modal').textContent).toBe('Modal 1');
110
+ });
111
+ it('a slot page match on the new route replaces the slot', async () => {
112
+ routes['/settings'] = {
113
+ body: doc('Settings', shell('<p id="settings">s</p>', '<b id="slot-settings"></b>'), chain('page', '_lset_')),
114
+ };
115
+ await krateRouter.push('/photo/1');
116
+ await krateRouter.push('/settings');
117
+ expect(document.getElementById('modal')).toBeNull();
118
+ expect(document.getElementById('slot-settings')).not.toBeNull();
119
+ });
120
+ it('falls back to the real page (with an error event) when the fragment is missing', async () => {
121
+ delete routes['/_krate/i/_sabc_modal/photo/1'];
122
+ const errs = [];
123
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => { });
124
+ window.addEventListener('krate:navigate-error', (e) => errs.push(e.detail));
125
+ await krateRouter.push('/photo/1');
126
+ await settle();
127
+ warn.mockRestore();
128
+ expect(errs.length).toBeGreaterThan(0);
129
+ expect(document.getElementById('photo')).not.toBeNull();
130
+ });
131
+ });
132
+ describe('route patterns', () => {
133
+ it('matches catch-alls like the compiler', () => {
134
+ expect(matchRoutePattern('/docs/a/b', 'docs/[...slug]')).toEqual({ slug: 'a/b' });
135
+ expect(matchRoutePattern('/docs', 'docs/[...slug]')).toBeNull();
136
+ expect(matchRoutePattern('/shop', 'shop/[[...f]]')).toEqual({ f: '' });
137
+ expect(matchRoutePattern('/photo/7', 'photo/[id]')).toEqual({ id: '7' });
138
+ });
139
+ it('orders static > dynamic > catch-all > optional catch-all', () => {
140
+ const list = ['shop/[[...f]]', 'shop/[...f]', 'shop/[id]', 'shop/cart'];
141
+ list.sort(compareRouteSpecificity);
142
+ expect(list).toEqual(['shop/cart', 'shop/[id]', 'shop/[...f]', 'shop/[[...f]]']);
143
+ });
144
+ });
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,25 @@
1
+ import { describe, it, expect, afterEach, vi } from 'vitest';
2
+ import { initRouter, destroyRouter } from './router';
3
+ function boot(head) {
4
+ destroyRouter();
5
+ globalThis.__KRATE_CFG__ = { viewTransitions: false };
6
+ document.head.innerHTML = '<title>x</title>' + head;
7
+ document.body.innerHTML = '<div id="root"></div>';
8
+ initRouter();
9
+ }
10
+ describe('router speculation rules', () => {
11
+ afterEach(() => {
12
+ destroyRouter();
13
+ vi.unstubAllGlobals();
14
+ });
15
+ it('injects the rules when the browser supports them and no CSP meta exists', () => {
16
+ HTMLScriptElement.supports = (t) => t === 'speculationrules';
17
+ boot('');
18
+ expect(document.querySelector('script[type="speculationrules"]')).not.toBeNull();
19
+ });
20
+ it('skips the inline rules under a CSP meta', () => {
21
+ HTMLScriptElement.supports = (t) => t === 'speculationrules';
22
+ boot('<meta http-equiv="Content-Security-Policy" content="script-src \'self\'">');
23
+ expect(document.querySelector('script[type="speculationrules"]')).toBeNull();
24
+ });
25
+ });
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,98 @@
1
+ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
2
+ import { initRouter, destroyRouter, navigate } from './router';
3
+ function page(title, head, body) {
4
+ return `<!doctype html><html><head><title>${title}</title>${head}</head><body><div id="root">${body}</div></body></html>`;
5
+ }
6
+ const sheet = (name) => `<link rel="stylesheet" href="/${name}.css">`;
7
+ let routes;
8
+ function hrefs() {
9
+ return Array.from(document.querySelectorAll('link[rel="stylesheet"]')).map((l) => new URL(l.href).pathname);
10
+ }
11
+ function linkFor(name) {
12
+ return Array.from(document.querySelectorAll('link[rel="stylesheet"]')).find((l) => new URL(l.href).pathname === `/${name}.css`) ?? null;
13
+ }
14
+ async function tick() {
15
+ for (let i = 0; i < 20; i++)
16
+ await Promise.resolve();
17
+ await new Promise((r) => setTimeout(r, 0));
18
+ for (let i = 0; i < 20; i++)
19
+ await Promise.resolve();
20
+ }
21
+ beforeEach(() => {
22
+ destroyRouter();
23
+ globalThis.__KRATE_CFG__ = { viewTransitions: false };
24
+ history.replaceState(null, '', '/');
25
+ routes = {};
26
+ // happy-dom tries to fetch the stylesheets; the tests settle them by hand.
27
+ vi.spyOn(console, 'error').mockImplementation(() => { });
28
+ vi.stubGlobal('fetch', vi.fn(async (input) => {
29
+ const u = new URL(input, location.href);
30
+ const body = routes[u.pathname] ?? '';
31
+ return {
32
+ ok: true,
33
+ status: 200,
34
+ url: u.href,
35
+ redirected: false,
36
+ headers: new Headers({ 'content-type': 'text/html; charset=utf-8' }),
37
+ text: async () => body,
38
+ };
39
+ }));
40
+ document.head.innerHTML = '<title>Home</title>' + sheet('page-a') + sheet('tw');
41
+ document.body.innerHTML = '<div id="root"><p>home</p></div>';
42
+ initRouter();
43
+ });
44
+ afterEach(() => {
45
+ destroyRouter();
46
+ vi.unstubAllGlobals();
47
+ vi.restoreAllMocks();
48
+ vi.useRealTimers();
49
+ });
50
+ describe('router stylesheets', () => {
51
+ it('keeps the incoming document order and removes stale sheets after the swap', async () => {
52
+ routes['/b'] = page('B', sheet('page-b') + sheet('tw'), '<p>b</p>');
53
+ const nav = navigate('/b');
54
+ await tick();
55
+ // Still on the old page: the old sheet stays until the new one loaded.
56
+ expect(document.querySelector('#root').textContent).toBe('home');
57
+ expect(linkFor('page-a')).not.toBeNull();
58
+ const added = linkFor('page-b');
59
+ expect(added.getAttribute('media')).toBe('not all');
60
+ added.dispatchEvent(new Event('load'));
61
+ await nav;
62
+ await tick();
63
+ expect(document.querySelector('#root').textContent).toBe('b');
64
+ expect(hrefs()).toEqual(['/page-b.css', '/tw.css']);
65
+ expect(linkFor('page-b').hasAttribute('media')).toBe(false);
66
+ });
67
+ it('waits for the new sheet to load before swapping', async () => {
68
+ routes['/b'] = page('B', sheet('tw') + sheet('page-b'), '<p>b</p>');
69
+ const nav = navigate('/b');
70
+ await tick();
71
+ expect(document.querySelector('#root').textContent).toBe('home');
72
+ expect(hrefs()).toEqual(['/page-a.css', '/tw.css', '/page-b.css']);
73
+ linkFor('page-b').dispatchEvent(new Event('load'));
74
+ await nav;
75
+ await tick();
76
+ expect(document.querySelector('#root').textContent).toBe('b');
77
+ expect(hrefs()).toEqual(['/tw.css', '/page-b.css']);
78
+ });
79
+ it('proceeds when a stylesheet fails to load', async () => {
80
+ routes['/b'] = page('B', sheet('page-b') + sheet('tw'), '<p>b</p>');
81
+ const nav = navigate('/b');
82
+ await tick();
83
+ linkFor('page-b').dispatchEvent(new Event('error'));
84
+ await nav;
85
+ await tick();
86
+ expect(document.querySelector('#root').textContent).toBe('b');
87
+ });
88
+ it('proceeds after the timeout when a stylesheet never settles', async () => {
89
+ routes['/b'] = page('B', sheet('page-b') + sheet('tw'), '<p>b</p>');
90
+ vi.useFakeTimers();
91
+ const nav = navigate('/b');
92
+ await vi.advanceTimersByTimeAsync(3100);
93
+ await nav;
94
+ await vi.advanceTimersByTimeAsync(10);
95
+ expect(document.querySelector('#root').textContent).toBe('b');
96
+ expect(hrefs()).toEqual(['/page-b.css', '/tw.css']);
97
+ });
98
+ });
package/dist/router.d.ts CHANGED
@@ -6,11 +6,69 @@
6
6
  */
7
7
  export declare function pageAssetURLs(html: string, baseUrl: string, loaded: Set<string>): string[];
8
8
  export interface NavigateOptions {
9
+ /** Replace the current history entry instead of pushing a new one. */
9
10
  replace?: boolean;
11
+ /** Scroll to the top (or the URL hash) after navigating (default true). */
10
12
  scroll?: boolean;
11
- /** State stored on the new history entry. */
13
+ /** State stored on the new history entry (read it with getHistoryState()). */
12
14
  state?: unknown;
13
15
  }
16
+ /** Snapshot of the router state delivered to subscribeNavigation listeners. */
17
+ export interface NavigationState {
18
+ /** Absolute URL of the rendered route. */
19
+ url: string;
20
+ /** Pathname without the configured base path. */
21
+ pathname: string;
22
+ search: string;
23
+ hash: string;
24
+ /** 'loading' while a navigation is in flight, 'idle' otherwise. */
25
+ status: 'idle' | 'loading';
26
+ }
27
+ /** The `state` passed to the navigation that created the current history entry. */
28
+ export declare function getHistoryState(): unknown;
29
+ /** Current router state (pathname without base path, search, hash, status). */
30
+ export declare function getNavigationState(): NavigationState;
31
+ /**
32
+ * Subscribes to navigation state changes (URL changes from SPA navigations,
33
+ * back/forward, hash changes, and loading status). Returns an unsubscribe
34
+ * function. The listener is not called immediately; read the current value
35
+ * with getNavigationState().
36
+ */
37
+ export declare function subscribeNavigation(fn: (s: NavigationState) => void): () => void;
38
+ /**
39
+ * Drops prefetched documents: one URL, or every entry when called without an
40
+ * argument. Server actions that revalidate data call this through the
41
+ * `krate:revalidate` event.
42
+ */
43
+ export declare function invalidatePrefetchCache(url?: string): void;
44
+ /** Mirrors the compiler's matchRoutePattern (static, [param], [...all], [[...opt]]). */
45
+ export declare function matchRoutePattern(path: string, pattern: string): Record<string, string> | null;
46
+ /** Negative when pattern a is more specific than b (static > dynamic > catch-all > optional). */
47
+ export declare function compareRouteSpecificity(a: string, b: string): number;
48
+ declare function refresh(): Promise<void>;
49
+ declare function push(url: string, opts?: NavigateOptions): Promise<void>;
50
+ declare function replace(url: string, opts?: NavigateOptions): Promise<void>;
51
+ /**
52
+ * The router API. Every navigation method resolves once the new route's DOM
53
+ * and URL are in place (page scripts may still be loading).
54
+ *
55
+ * - push(url, opts) / replace(url, opts): client navigation.
56
+ * - back() / forward(): history traversal.
57
+ * - refresh(): re-fetches the current route (bypassing the prefetch cache)
58
+ * and swaps it in place, keeping scroll position and history.
59
+ * - prefetch(url): warms the document (and its page chunk) for a later visit.
60
+ */
61
+ export declare const krateRouter: {
62
+ push: typeof push;
63
+ replace: typeof replace;
64
+ back(): void;
65
+ forward(): void;
66
+ refresh: typeof refresh;
67
+ prefetch(url: string): Promise<void>;
68
+ subscribe: typeof subscribeNavigation;
69
+ getState: typeof getNavigationState;
70
+ invalidate: typeof invalidatePrefetchCache;
71
+ };
14
72
  /**
15
73
  * Programmatic SPA navigation. Falls back to a full page load when the router
16
74
  * has not initialized (e.g. before hydration). Returns false when handled
@@ -18,5 +76,11 @@ export interface NavigateOptions {
18
76
  */
19
77
  export declare function navigate(url: string, opts?: NavigateOptions): boolean;
20
78
  export declare function initRouter(): void;
21
- /** Dispose old effects, re-register router listeners for new page. */
79
+ /**
80
+ * Called at the end of every page hydration script. The router keeps its
81
+ * listeners and caches; only the per-page bindings are refreshed.
82
+ */
22
83
  export declare function reinitRouter(): void;
84
+ /** Tears the router down (tests and embedders that unmount Krate). */
85
+ export declare function destroyRouter(): void;
86
+ export {};