@krate/runtime 0.5.0-alpha.3 → 0.5.0-alpha.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.
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,174 @@
1
+ import { afterEach, describe, expect, it } from 'vitest';
2
+ import { cookies, headers } from './action-context.js';
3
+ import { getRequestContext, isNotFoundSignal, notFound, 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
+ });
78
+ describe('renderToString with async components', () => {
79
+ it('throws instead of rendering an empty string', () => {
80
+ async function Page() {
81
+ return jsx('p', { children: 'x' });
82
+ }
83
+ expect(() => renderToString(jsx(Page, {}))).toThrow(/<Page> returned a Promise/);
84
+ });
85
+ });
86
+ describe('request context', () => {
87
+ const ctx = {
88
+ url: '/p',
89
+ method: 'GET',
90
+ headers: new Headers({ 'x-test': 'yes', cookie: 'sid=abc; theme=dark' }),
91
+ cookies: parseCookieHeader('sid=abc; theme=dark'),
92
+ params: {},
93
+ searchParams: {},
94
+ };
95
+ it('serves headers() and cookies() inside a server render, sync and awaited', async () => {
96
+ withRequestStore(ctx);
97
+ expect(getRequestContext()?.url).toBe('/p');
98
+ expect(headers().get('x-test')).toBe('yes');
99
+ expect((await headers()).get('x-test')).toBe('yes');
100
+ const jar = cookies();
101
+ expect(jar.get('sid')).toEqual({ name: 'sid', value: 'abc' });
102
+ expect((await cookies()).get('theme').value).toBe('dark');
103
+ expect(jar.getAll()).toHaveLength(2);
104
+ });
105
+ it('refuses to modify cookies during a render', () => {
106
+ withRequestStore(ctx);
107
+ expect(() => cookies().set('a', 'b')).toThrow(/server action/);
108
+ });
109
+ it('throws outside any request or action scope', () => {
110
+ expect(() => headers()).toThrow(/server component/);
111
+ });
112
+ });
113
+ describe('thenable params', () => {
114
+ it('supports property access and await', async () => {
115
+ const params = thenableRecord({ slug: 'hello' });
116
+ expect(params.slug).toBe('hello');
117
+ const awaited = await params;
118
+ expect(awaited.slug).toBe('hello');
119
+ expect(JSON.stringify(params)).toBe('{"slug":"hello"}');
120
+ expect(Object.keys(params)).toEqual(['slug']);
121
+ });
122
+ });
123
+ describe('render signals', () => {
124
+ it('notFound() throws a recognizable signal', () => {
125
+ let caught;
126
+ try {
127
+ notFound();
128
+ }
129
+ catch (e) {
130
+ caught = e;
131
+ }
132
+ expect(isNotFoundSignal(caught)).toBe(true);
133
+ expect(isNotFoundSignal(new Error('other'))).toBe(false);
134
+ });
135
+ it('redirectTarget understands Krate and Next.js redirect errors', () => {
136
+ expect(redirectTarget(Object.assign(new Error('x'), { __krateRedirect: '/a' }))).toBe('/a');
137
+ expect(redirectTarget(new Error('NEXT_REDIRECT:/b'))).toBe('/b');
138
+ expect(redirectTarget(Object.assign(new Error('NEXT_REDIRECT'), { digest: 'NEXT_REDIRECT;replace;/c;307;' }))).toBe('/c');
139
+ expect(redirectTarget(new Error('nope'))).toBe('');
140
+ });
141
+ });
142
+ describe('clientBoundary', () => {
143
+ function Counter(props) {
144
+ return props.start;
145
+ }
146
+ // A stand-in for the Preact server render of the client module.
147
+ const render = (_c, props, children) => `<button>${props.start}</button>${children ?? ''}`;
148
+ it('renders an island marker with serialized props and server-rendered children', async () => {
149
+ const Boundary = clientBoundary('m1', 'Counter', '/chunks/c.js', Counter, render);
150
+ async function ServerPart() {
151
+ await tick();
152
+ return jsx('em', { children: 'from server' });
153
+ }
154
+ const html = await renderToStringAsync(jsx(Boundary, { start: 3, children: jsx(ServerPart, {}) }));
155
+ expect(html).toContain('<krate-island style="display:contents" data-module="m1" data-export="Counter" data-src="/chunks/c.js"');
156
+ expect(html).toContain('data-props="{&quot;start&quot;:3,&quot;__krateChildren&quot;:&quot;&lt;em&gt;from server&lt;/em&gt;&quot;}"');
157
+ expect(html).toContain('<button>3</button><em>from server</em></krate-island>');
158
+ });
159
+ it('passes server actions as references', async () => {
160
+ const action = Object.assign(async () => { }, { actionUrl: '/__krate/action/a1' });
161
+ const Boundary = clientBoundary('m1', 'Counter', '/c.js', Counter, render);
162
+ const html = await renderToStringAsync(jsx(Boundary, { start: 1, onSave: action }));
163
+ expect(html).toContain('&quot;onSave&quot;:{&quot;__krateAction&quot;:&quot;/__krate/action/a1&quot;}');
164
+ });
165
+ it('rejects functions, class instances and JSX props with the prop path', async () => {
166
+ const Boundary = clientBoundary('m1', 'Counter', '/c.js', Counter, render);
167
+ await expect(renderToStringAsync(jsx(Boundary, { onClick: () => { } }))).rejects.toThrow(/Prop `onClick` passed to client component <Counter> is a function/);
168
+ await expect(renderToStringAsync(jsx(Boundary, { opts: { when: new Date(0) } }))).rejects.toThrow(/Prop `opts.when` .* an instance of Date/);
169
+ await expect(renderToStringAsync(jsx(Boundary, { icon: jsx('i', {}) }))).rejects.toThrow(/only `children` can carry/);
170
+ });
171
+ it('returns non-function exports unchanged', () => {
172
+ expect(clientBoundary('m1', 'LIMIT', '/c.js', 5, render)).toBe(5);
173
+ });
174
+ });