@krate/runtime 0.5.0-rc.2 → 0.5.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.
Files changed (155) hide show
  1. package/dist/actions.d.ts +7 -0
  2. package/dist/actions.js +21 -3
  3. package/dist/actions.test.js +8 -410
  4. package/dist/after.d.ts +28 -0
  5. package/dist/after.js +48 -0
  6. package/dist/after.test.js +58 -0
  7. package/dist/assets-static.d.ts +10 -1
  8. package/dist/assets-static.js +10 -2
  9. package/dist/base-path.js +4 -3
  10. package/dist/builtin-tags.d.ts +12 -0
  11. package/dist/builtin-tags.js +42 -0
  12. package/dist/builtin-tags.test.js +12 -0
  13. package/dist/cache-adapter.test.js +4 -203
  14. package/dist/cache-scope.d.ts +2 -0
  15. package/dist/cache.test.js +1 -197
  16. package/dist/cloudflare-workers.d.ts +2 -0
  17. package/dist/cloudflare-workers.js +27 -0
  18. package/dist/dev-overlay.d.ts +54 -3
  19. package/dist/dev-overlay.js +469 -76
  20. package/dist/dom.js +3 -1
  21. package/dist/events.test.js +2 -407
  22. package/dist/handler-html.test.js +1 -202
  23. package/dist/handler-routing.js +3 -0
  24. package/dist/handler-segments.d.ts +6 -0
  25. package/dist/handler-segments.js +16 -2
  26. package/dist/handler-segments.test.js +8 -200
  27. package/dist/head-tags.d.ts +9 -0
  28. package/dist/head-tags.js +85 -1
  29. package/dist/head-tags.test.js +18 -125
  30. package/dist/index.d.ts +1 -5
  31. package/dist/index.js +3 -0
  32. package/dist/inline-action-token.test.js +31 -0
  33. package/dist/jsx-svg-types.test.js +58 -0
  34. package/dist/jsx-types.d.ts +92 -1
  35. package/dist/krate-core.js +1 -1
  36. package/dist/krate-dev.js +384 -65
  37. package/dist/krate-f-actions.js +1 -1
  38. package/dist/krate-f-navigation.js +1 -1
  39. package/dist/krate-f-router-lite.js +1 -1
  40. package/dist/krate-f-router.js +1 -1
  41. package/dist/krate-features.json +2 -0
  42. package/dist/krate-hydrate-lite.js +5 -5
  43. package/dist/krate-hydrate.js +5 -5
  44. package/dist/krate-runtime.js +5 -5
  45. package/dist/link-base-path.test.js +28 -0
  46. package/dist/node-server.test.js +1 -355
  47. package/dist/platform.d.ts +52 -0
  48. package/dist/platform.js +57 -0
  49. package/dist/platform.test.js +44 -0
  50. package/dist/router-nav.test.js +15 -444
  51. package/dist/router.js +39 -1
  52. package/dist/server-handler.d.ts +48 -0
  53. package/dist/server-handler.js +279 -17
  54. package/dist/server-handler.test.js +54 -388
  55. package/dist/server-renderer.test.js +0 -104
  56. package/dist/server.d.ts +15 -5
  57. package/dist/server.js +149 -22
  58. package/dist/server.test.js +52 -60
  59. package/dist/site-config.d.ts +13 -0
  60. package/dist/site-config.js +28 -0
  61. package/dist/site-config.test.js +30 -0
  62. package/dist/slot.d.ts +12 -0
  63. package/dist/slot.js +23 -0
  64. package/dist/slot.test.js +25 -0
  65. package/dist/ssr-core-behavior.test.js +3 -515
  66. package/dist/testing.d.ts +59 -0
  67. package/dist/testing.js +88 -0
  68. package/dist/testing.test.js +73 -0
  69. package/package.json +9 -1
  70. package/dist/action-context.test.js +0 -72
  71. package/dist/base-path.test.js +0 -88
  72. package/dist/class-component.test.js +0 -462
  73. package/dist/class-helpers.test.js +0 -169
  74. package/dist/context.test.js +0 -57
  75. package/dist/derived.test.js +0 -140
  76. package/dist/dev-overlay.test.js +0 -165
  77. package/dist/discrete.test.js +0 -100
  78. package/dist/dom.test.js +0 -39
  79. package/dist/effect-errors.test.d.ts +0 -1
  80. package/dist/effect-errors.test.js +0 -199
  81. package/dist/effects.test.d.ts +0 -1
  82. package/dist/effects.test.js +0 -485
  83. package/dist/handler-routing.test.d.ts +0 -1
  84. package/dist/handler-routing.test.js +0 -99
  85. package/dist/highlight-bind.test.d.ts +0 -1
  86. package/dist/highlight-bind.test.js +0 -124
  87. package/dist/highlight.test.d.ts +0 -1
  88. package/dist/highlight.test.js +0 -56
  89. package/dist/lanes.test.d.ts +0 -1
  90. package/dist/lanes.test.js +0 -59
  91. package/dist/list.test.d.ts +0 -1
  92. package/dist/list.test.js +0 -435
  93. package/dist/metadata.test.d.ts +0 -1
  94. package/dist/metadata.test.js +0 -167
  95. package/dist/navigation.test.d.ts +0 -1
  96. package/dist/navigation.test.js +0 -130
  97. package/dist/optimistic-lanes.test.d.ts +0 -1
  98. package/dist/optimistic-lanes.test.js +0 -45
  99. package/dist/patterns.test.d.ts +0 -1
  100. package/dist/patterns.test.js +0 -125
  101. package/dist/portal.test.d.ts +0 -1
  102. package/dist/portal.test.js +0 -99
  103. package/dist/react-effects.test.d.ts +0 -1
  104. package/dist/react-effects.test.js +0 -133
  105. package/dist/react-suspense.test.d.ts +0 -1
  106. package/dist/react-suspense.test.js +0 -194
  107. package/dist/react.test.d.ts +0 -1
  108. package/dist/react.test.js +0 -60
  109. package/dist/react19.test.d.ts +0 -1
  110. package/dist/react19.test.js +0 -176
  111. package/dist/reactivity-core.test.d.ts +0 -1
  112. package/dist/reactivity-core.test.js +0 -152
  113. package/dist/reconcile.test.d.ts +0 -1
  114. package/dist/reconcile.test.js +0 -110
  115. package/dist/refs.test.d.ts +0 -1
  116. package/dist/refs.test.js +0 -257
  117. package/dist/router-layout.test.d.ts +0 -1
  118. package/dist/router-layout.test.js +0 -249
  119. package/dist/router-slots.test.d.ts +0 -1
  120. package/dist/router-slots.test.js +0 -144
  121. package/dist/router-speculation.test.d.ts +0 -1
  122. package/dist/router-speculation.test.js +0 -25
  123. package/dist/router-styles.test.d.ts +0 -1
  124. package/dist/router-styles.test.js +0 -98
  125. package/dist/router.test.d.ts +0 -1
  126. package/dist/router.test.js +0 -36
  127. package/dist/server-async.test.d.ts +0 -1
  128. package/dist/server-async.test.js +0 -216
  129. package/dist/server-highlight.test.d.ts +0 -1
  130. package/dist/server-highlight.test.js +0 -32
  131. package/dist/signal-lanes.test.d.ts +0 -1
  132. package/dist/signal-lanes.test.js +0 -32
  133. package/dist/slots.test.d.ts +0 -1
  134. package/dist/slots.test.js +0 -187
  135. package/dist/snapshots.test.d.ts +0 -1
  136. package/dist/snapshots.test.js +0 -208
  137. package/dist/ssr-core.test.d.ts +0 -1
  138. package/dist/ssr-core.test.js +0 -324
  139. package/dist/static-memory.test.d.ts +0 -1
  140. package/dist/static-memory.test.js +0 -26
  141. package/dist/storage.test.d.ts +0 -1
  142. package/dist/storage.test.js +0 -46
  143. package/dist/suspense-actions.test.d.ts +0 -1
  144. package/dist/suspense-actions.test.js +0 -72
  145. package/dist/suspense.test.d.ts +0 -1
  146. package/dist/suspense.test.js +0 -556
  147. /package/dist/{action-context.test.d.ts → after.test.d.ts} +0 -0
  148. /package/dist/{base-path.test.d.ts → builtin-tags.test.d.ts} +0 -0
  149. /package/dist/{class-component.test.d.ts → inline-action-token.test.d.ts} +0 -0
  150. /package/dist/{class-helpers.test.d.ts → jsx-svg-types.test.d.ts} +0 -0
  151. /package/dist/{context.test.d.ts → link-base-path.test.d.ts} +0 -0
  152. /package/dist/{derived.test.d.ts → platform.test.d.ts} +0 -0
  153. /package/dist/{dev-overlay.test.d.ts → site-config.test.d.ts} +0 -0
  154. /package/dist/{discrete.test.d.ts → slot.test.d.ts} +0 -0
  155. /package/dist/{dom.test.d.ts → testing.test.d.ts} +0 -0
@@ -1,144 +0,0 @@
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
- });
@@ -1 +0,0 @@
1
- export {};
@@ -1,25 +0,0 @@
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
- });
@@ -1 +0,0 @@
1
- export {};
@@ -1,98 +0,0 @@
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
- });
@@ -1 +0,0 @@
1
- export {};
@@ -1,36 +0,0 @@
1
- import { describe, it, expect } from 'vitest';
2
- import { pageAssetURLs } from './router';
3
- const HTML = `<!doctype html><html><head>
4
- <link rel="modulepreload" href="/chunks/runtime.abc123.js">
5
- <link rel="modulepreload" href="index.1234.js">
6
- <link rel="preload" as="script" href="/assets/extra-5678.js">
7
- </head><body>
8
- <script src="/chunks/runtime.abc123.js"></script>
9
- <script src="index.1234.js"></script>
10
- <script src="/api/track.js"></script>
11
- </body></html>`;
12
- describe('pageAssetURLs', () => {
13
- it('extracts page scripts, excluding the shared runtime chunk', () => {
14
- const urls = pageAssetURLs(HTML, 'https://example.com/about/', new Set());
15
- expect(urls).toContain('https://example.com/about/index.1234.js');
16
- expect(urls).toContain('https://example.com/api/track.js');
17
- expect(urls).not.toContain('https://example.com/chunks/runtime.abc123.js');
18
- });
19
- it('dedupes across script and modulepreload tags', () => {
20
- const urls = pageAssetURLs(HTML, 'https://example.com/about/', new Set());
21
- expect(urls.filter((u) => u.endsWith('/index.1234.js')).length).toBe(1);
22
- });
23
- it('picks up preload/modulepreload-only assets', () => {
24
- const urls = pageAssetURLs(HTML, 'https://example.com/about/', new Set());
25
- expect(urls).toContain('https://example.com/assets/extra-5678.js');
26
- });
27
- it('skips already-loaded assets', () => {
28
- const loaded = new Set(['https://example.com/about/index.1234.js']);
29
- const urls = pageAssetURLs(HTML, 'https://example.com/about/', loaded);
30
- expect(urls).not.toContain('https://example.com/about/index.1234.js');
31
- });
32
- it('resolves relative srcs against the target page directory', () => {
33
- const urls = pageAssetURLs(HTML, 'https://example.com/about', new Set());
34
- expect(urls).toContain('https://example.com/index.1234.js');
35
- });
36
- });
@@ -1 +0,0 @@
1
- export {};
@@ -1,216 +0,0 @@
1
- import { afterEach, describe, expect, it } from 'vitest';
2
- import { cookies, headers } from './action-context.js';
3
- import { getRequestContext, isNotFoundSignal, notFound, forbidden, unauthorized, accessDeniedStatus, httpFallbackStatus, parseCookieHeader, redirectTarget, thenableRecord, } from './request-context.js';
4
- import { Link, Suspense, clientBoundary, jsx, renderToString, renderToStringAsync } from './server.js';
5
- const REQUEST_KEY = Symbol.for('krate.request.store');
6
- function withRequestStore(ctx) {
7
- globalThis[REQUEST_KEY] = { getStore: () => ctx };
8
- }
9
- afterEach(() => {
10
- delete globalThis[REQUEST_KEY];
11
- });
12
- const tick = () => new Promise((r) => setTimeout(r, 0));
13
- describe('renderToStringAsync', () => {
14
- it('awaits an async page component', async () => {
15
- async function Page(props) {
16
- await tick();
17
- return jsx('h1', { children: props.title });
18
- }
19
- expect(await renderToStringAsync(jsx(Page, { title: 'Hi <you>' }))).toBe('<h1>Hi &lt;you&gt;</h1>');
20
- });
21
- it('awaits async children at any depth', async () => {
22
- async function Leaf(props) {
23
- await tick();
24
- return jsx('li', { children: String(props.n) });
25
- }
26
- function List() {
27
- return jsx('ul', { children: [jsx(Leaf, { n: 1 }), jsx(Leaf, { n: 2 })] });
28
- }
29
- async function Page() {
30
- await tick();
31
- return jsx('main', { children: jsx(List, {}) });
32
- }
33
- expect(await renderToStringAsync(jsx(Page, {}))).toBe('<main><ul><li>1</li><li>2</li></ul></main>');
34
- });
35
- it('resolves sibling async components in parallel', async () => {
36
- const order = [];
37
- let releaseA;
38
- const gateA = new Promise((r) => (releaseA = r));
39
- async function A() {
40
- await gateA;
41
- order.push('A');
42
- return 'a';
43
- }
44
- async function B() {
45
- order.push('B');
46
- releaseA();
47
- return 'b';
48
- }
49
- // B releases A's gate: a sequential renderer would deadlock waiting on A.
50
- const html = await renderToStringAsync(jsx('p', { children: [jsx(A, {}), jsx(B, {})] }));
51
- expect(html).toBe('<p>ab</p>');
52
- expect(order).toEqual(['B', 'A']);
53
- });
54
- it('renders the resolved children of <Suspense>, not the fallback', async () => {
55
- async function Slow() {
56
- await tick();
57
- return jsx('p', { children: 'done' });
58
- }
59
- const html = await renderToStringAsync(jsx(Suspense, { fallback: jsx('span', { children: 'loading' }), children: jsx(Slow, {}) }));
60
- expect(html).toBe('<p>done</p>');
61
- });
62
- it('resolves async children passed to eager built-ins like <Link>', async () => {
63
- async function Label() {
64
- await tick();
65
- return 'Docs';
66
- }
67
- const html = await renderToStringAsync(jsx(Link, { href: '/docs', children: jsx(Label, {}) }));
68
- expect(html).toContain('>Docs</a>');
69
- });
70
- it('rejects when an async component throws', async () => {
71
- async function Boom() {
72
- await tick();
73
- throw new Error('db down');
74
- }
75
- await expect(renderToStringAsync(jsx('div', { children: jsx(Boom, {}) }))).rejects.toThrow('db down');
76
- });
77
- it('renders a class error boundary around a failing async server component', async () => {
78
- class Boundary {
79
- constructor(props) {
80
- this.state = { error: null };
81
- this.props = props;
82
- }
83
- static getDerivedStateFromError(error) { return { error }; }
84
- render() {
85
- if (this.state.error)
86
- return jsx('p', { children: 'fallback: ' + this.state.error.message });
87
- return this.props.children;
88
- }
89
- }
90
- async function Boom() {
91
- await tick();
92
- throw new Error('server boom');
93
- }
94
- const html = await renderToStringAsync(jsx(Boundary, { children: jsx(Boom, {}) }));
95
- expect(html).toContain('fallback: server boom');
96
- });
97
- });
98
- describe('renderToString with async components', () => {
99
- it('throws instead of rendering an empty string', () => {
100
- async function Page() {
101
- return jsx('p', { children: 'x' });
102
- }
103
- expect(() => renderToString(jsx(Page, {}))).toThrow(/<Page> returned a Promise/);
104
- });
105
- });
106
- describe('request context', () => {
107
- const ctx = {
108
- url: '/p',
109
- method: 'GET',
110
- headers: new Headers({ 'x-test': 'yes', cookie: 'sid=abc; theme=dark' }),
111
- cookies: parseCookieHeader('sid=abc; theme=dark'),
112
- params: {},
113
- searchParams: {},
114
- };
115
- it('serves headers() and cookies() inside a server render, sync and awaited', async () => {
116
- withRequestStore(ctx);
117
- expect(getRequestContext()?.url).toBe('/p');
118
- expect(headers().get('x-test')).toBe('yes');
119
- expect((await headers()).get('x-test')).toBe('yes');
120
- const jar = cookies();
121
- expect(jar.get('sid')).toEqual({ name: 'sid', value: 'abc' });
122
- expect((await cookies()).get('theme').value).toBe('dark');
123
- expect(jar.getAll()).toHaveLength(2);
124
- });
125
- it('refuses to modify cookies during a render', () => {
126
- withRequestStore(ctx);
127
- expect(() => cookies().set('a', 'b')).toThrow(/server action/);
128
- });
129
- it('throws outside any request or action scope', () => {
130
- expect(() => headers()).toThrow(/server component/);
131
- });
132
- });
133
- describe('thenable params', () => {
134
- it('supports property access and await', async () => {
135
- const params = thenableRecord({ slug: 'hello' });
136
- expect(params.slug).toBe('hello');
137
- const awaited = await params;
138
- expect(awaited.slug).toBe('hello');
139
- expect(JSON.stringify(params)).toBe('{"slug":"hello"}');
140
- expect(Object.keys(params)).toEqual(['slug']);
141
- });
142
- });
143
- describe('render signals', () => {
144
- it('notFound() throws a recognizable signal', () => {
145
- let caught;
146
- try {
147
- notFound();
148
- }
149
- catch (e) {
150
- caught = e;
151
- }
152
- expect(isNotFoundSignal(caught)).toBe(true);
153
- expect(isNotFoundSignal(new Error('other'))).toBe(false);
154
- });
155
- it('forbidden() and unauthorized() throw signals with the Next.js digest', () => {
156
- const catchOf = (fn) => {
157
- try {
158
- fn();
159
- }
160
- catch (e) {
161
- return e;
162
- }
163
- };
164
- const f = catchOf(forbidden);
165
- const u = catchOf(unauthorized);
166
- expect(accessDeniedStatus(f)).toBe(403);
167
- expect(accessDeniedStatus(u)).toBe(401);
168
- expect(f.digest).toBe('NEXT_HTTP_ERROR_FALLBACK;403');
169
- expect(u.digest).toBe('NEXT_HTTP_ERROR_FALLBACK;401');
170
- expect(accessDeniedStatus(Object.assign(new Error('x'), { digest: 'NEXT_HTTP_ERROR_FALLBACK;403' }))).toBe(403);
171
- expect(accessDeniedStatus(new Error('other'))).toBe(0);
172
- expect(isNotFoundSignal(f)).toBe(false);
173
- expect(httpFallbackStatus(catchOf(notFound))).toBe(404);
174
- expect(httpFallbackStatus(f)).toBe(403);
175
- expect(httpFallbackStatus(undefined)).toBe(0);
176
- });
177
- it('redirectTarget understands Krate and Next.js redirect errors', () => {
178
- expect(redirectTarget(Object.assign(new Error('x'), { __krateRedirect: '/a' }))).toBe('/a');
179
- expect(redirectTarget(new Error('NEXT_REDIRECT:/b'))).toBe('/b');
180
- expect(redirectTarget(Object.assign(new Error('NEXT_REDIRECT'), { digest: 'NEXT_REDIRECT;replace;/c;307;' }))).toBe('/c');
181
- expect(redirectTarget(new Error('nope'))).toBe('');
182
- });
183
- });
184
- describe('clientBoundary', () => {
185
- function Counter(props) {
186
- return props.start;
187
- }
188
- // A stand-in for the Preact server render of the client module.
189
- const render = (_c, props, children) => `<button>${props.start}</button>${children ?? ''}`;
190
- it('renders an island marker with serialized props and server-rendered children', async () => {
191
- const Boundary = clientBoundary('m1', 'Counter', '/chunks/c.js', Counter, render);
192
- async function ServerPart() {
193
- await tick();
194
- return jsx('em', { children: 'from server' });
195
- }
196
- const html = await renderToStringAsync(jsx(Boundary, { start: 3, children: jsx(ServerPart, {}) }));
197
- expect(html).toContain('<krate-island style="display:contents" data-module="m1" data-export="Counter" data-src="/chunks/c.js"');
198
- expect(html).toContain('data-props="{&quot;start&quot;:3,&quot;__krateChildren&quot;:&quot;&lt;em&gt;from server&lt;/em&gt;&quot;}"');
199
- expect(html).toContain('<button>3</button><em>from server</em></krate-island>');
200
- });
201
- it('passes server actions as references', async () => {
202
- const action = Object.assign(async () => { }, { actionUrl: '/__krate/action/a1' });
203
- const Boundary = clientBoundary('m1', 'Counter', '/c.js', Counter, render);
204
- const html = await renderToStringAsync(jsx(Boundary, { start: 1, onSave: action }));
205
- expect(html).toContain('&quot;onSave&quot;:{&quot;__krateAction&quot;:&quot;/__krate/action/a1&quot;}');
206
- });
207
- it('rejects functions, class instances and JSX props with the prop path', async () => {
208
- const Boundary = clientBoundary('m1', 'Counter', '/c.js', Counter, render);
209
- await expect(renderToStringAsync(jsx(Boundary, { onClick: () => { } }))).rejects.toThrow(/Prop `onClick` passed to client component <Counter> is a function/);
210
- await expect(renderToStringAsync(jsx(Boundary, { opts: { when: new Date(0) } }))).rejects.toThrow(/Prop `opts.when` .* an instance of Date/);
211
- await expect(renderToStringAsync(jsx(Boundary, { icon: jsx('i', {}) }))).rejects.toThrow(/only `children` can carry/);
212
- });
213
- it('returns non-function exports unchanged', () => {
214
- expect(clientBoundary('m1', 'LIMIT', '/c.js', 5, render)).toBe(5);
215
- });
216
- });
@@ -1 +0,0 @@
1
- export {};
@@ -1,32 +0,0 @@
1
- import { beforeAll, describe, expect, it } from "vitest";
2
- import { SyntaxHighlight, renderToString } from "./server";
3
- import { registerLanguage } from "./highlight";
4
- const table = {
5
- n: "Toy",
6
- t: ["nx", "mi", ""],
7
- s: [[["[a-z]+", 0], ["[0-9]+", 1], ["[ \\n]+", 2]]],
8
- };
9
- beforeAll(() => registerLanguage(table, ["toy"]));
10
- const html = (n) => renderToString(n);
11
- describe("SyntaxHighlight on the server", () => {
12
- it("highlights a language whose tables are loaded", () => {
13
- const out = html(SyntaxHighlight({ lang: "toy", children: "ab 12" }));
14
- expect(out).toContain('<pre class="chroma"><code class="language-toy">');
15
- expect(out).toContain('<span class="nx">ab</span>');
16
- expect(out).toContain('<span class="mi">12</span>');
17
- });
18
- it("marks lines and keeps the attribute the compiler writes", () => {
19
- const out = html(SyntaxHighlight({ lang: "toy", children: "a\nb", highlight: "2" }));
20
- expect(out).toContain('data-highlight-lines="2"');
21
- expect(out).toContain('<span class="line hl">');
22
- });
23
- it("writes plain escaped text for other languages and for unsafe input", () => {
24
- expect(html(SyntaxHighlight({ lang: "cobol", children: "<b>" }))).toContain("&lt;b&gt;");
25
- expect(html(SyntaxHighlight({ children: "a & b" }))).toContain("a &amp; b");
26
- const big = html(SyntaxHighlight({ lang: "toy", children: "a".repeat(70000) }));
27
- expect(big).not.toContain('class="line"');
28
- expect(big.length).toBeGreaterThan(70000);
29
- const long = html(SyntaxHighlight({ lang: "toy", children: "a".repeat(3000) }));
30
- expect(long).not.toContain('class="line"');
31
- });
32
- });
@@ -1 +0,0 @@
1
- export {};
@@ -1,32 +0,0 @@
1
- import { describe, it, expect, beforeEach } from 'vitest';
2
- // Only signal.ts: the commit snapshot of React state must not depend on the
3
- // effect scheduler (effects.ts) being loaded.
4
- import { createSignal, createEffect, disposeAll, krateHookState } from './signal';
5
- const tick = () => new Promise((r) => setTimeout(r, 0));
6
- async function settle() {
7
- for (let i = 0; i < 4; i++)
8
- await tick();
9
- }
10
- describe('React state commits without the effect scheduler', () => {
11
- beforeEach(() => disposeAll());
12
- it('keeps a promise-driven state write when a plain signal is written in a later microtask', async () => {
13
- const [user, setUser] = createSignal('nobody', krateHookState);
14
- const [flag, setFlag] = createSignal(false);
15
- const seen = [];
16
- createEffect(() => void seen.push(user() + '/' + flag()));
17
- await Promise.resolve().then(() => {
18
- setUser('grace');
19
- queueMicrotask(() => setFlag(true));
20
- });
21
- await settle();
22
- // Read outside rendering: the committed value.
23
- expect(user()).toBe('grace');
24
- expect(seen[seen.length - 1]).toBe('grace/true');
25
- });
26
- it('commits a state write made outside any event', async () => {
27
- const [n, setN] = createSignal(0, krateHookState);
28
- setTimeout(() => setN(4), 0);
29
- await settle();
30
- expect(n()).toBe(4);
31
- });
32
- });
@@ -1 +0,0 @@
1
- export {};