@krate/runtime 0.5.0-alpha.4 → 0.5.0-beta.2

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 (165) hide show
  1. package/dist/action-context.d.ts +5 -1
  2. package/dist/action-context.js +33 -3
  3. package/dist/action-context.test.js +26 -1
  4. package/dist/actions.d.ts +12 -1
  5. package/dist/actions.js +84 -4
  6. package/dist/actions.test.js +61 -1
  7. package/dist/assets-static.d.ts +5 -0
  8. package/dist/assets-static.js +31 -0
  9. package/dist/boundary.d.ts +12 -0
  10. package/dist/boundary.js +53 -13
  11. package/dist/cache-adapter.d.ts +113 -0
  12. package/dist/cache-adapter.js +217 -0
  13. package/dist/cache-adapter.test.d.ts +1 -0
  14. package/dist/cache-adapter.test.js +244 -0
  15. package/dist/cache-redis.d.ts +27 -0
  16. package/dist/cache-redis.js +110 -0
  17. package/dist/cache-scope.d.ts +25 -9
  18. package/dist/cache-scope.js +64 -13
  19. package/dist/cache.d.ts +1 -0
  20. package/dist/cache.js +3 -3
  21. package/dist/cache.test.js +16 -0
  22. package/dist/class-component.js +6 -0
  23. package/dist/class-component.test.js +53 -2
  24. package/dist/class-helpers.d.ts +4 -4
  25. package/dist/class-helpers.js +357 -32
  26. package/dist/class-helpers.test.d.ts +1 -0
  27. package/dist/class-helpers.test.js +169 -0
  28. package/dist/context.d.ts +16 -2
  29. package/dist/context.js +44 -3
  30. package/dist/dev-overlay.js +85 -12
  31. package/dist/dev-overlay.test.js +22 -0
  32. package/dist/dom.d.ts +15 -0
  33. package/dist/dom.js +97 -3
  34. package/dist/effect-errors.test.d.ts +1 -0
  35. package/dist/effect-errors.test.js +163 -0
  36. package/dist/effects.d.ts +8 -0
  37. package/dist/effects.js +13 -0
  38. package/dist/error-overlay.js +7 -7
  39. package/dist/handler-html.d.ts +63 -0
  40. package/dist/handler-html.js +285 -0
  41. package/dist/handler-html.test.d.ts +1 -0
  42. package/dist/handler-html.test.js +256 -0
  43. package/dist/handler-routing.d.ts +83 -0
  44. package/dist/handler-routing.js +579 -0
  45. package/dist/handler-routing.test.d.ts +1 -0
  46. package/dist/handler-routing.test.js +99 -0
  47. package/dist/handler-segments.d.ts +43 -0
  48. package/dist/handler-segments.js +115 -0
  49. package/dist/handler-segments.test.d.ts +1 -0
  50. package/dist/handler-segments.test.js +217 -0
  51. package/dist/head-tags.d.ts +51 -0
  52. package/dist/head-tags.js +329 -0
  53. package/dist/head-tags.test.d.ts +1 -0
  54. package/dist/head-tags.test.js +131 -0
  55. package/dist/highlight-bind.d.ts +42 -0
  56. package/dist/highlight-bind.js +176 -0
  57. package/dist/highlight-bind.test.d.ts +1 -0
  58. package/dist/highlight-bind.test.js +124 -0
  59. package/dist/highlight.d.ts +93 -0
  60. package/dist/highlight.js +426 -0
  61. package/dist/highlight.test.d.ts +1 -0
  62. package/dist/highlight.test.js +56 -0
  63. package/dist/hints.d.ts +19 -0
  64. package/dist/hints.js +97 -0
  65. package/dist/hook-args.d.ts +7 -0
  66. package/dist/hook-args.js +10 -0
  67. package/dist/htmlspec-attributes.d.ts +1 -0
  68. package/dist/htmlspec-attributes.js +159 -0
  69. package/dist/index.d.ts +4 -0
  70. package/dist/index.js +3 -0
  71. package/dist/jsx-types.d.ts +11 -0
  72. package/dist/krate-core.js +2 -0
  73. package/dist/krate-dev.js +75 -12
  74. package/dist/krate-f-actions.js +2 -0
  75. package/dist/krate-f-classes.js +8 -0
  76. package/dist/krate-f-helpers.js +2 -0
  77. package/dist/krate-f-highlight.js +2 -0
  78. package/dist/krate-f-list.js +2 -0
  79. package/dist/krate-f-navigation.js +2 -0
  80. package/dist/krate-f-router-lite.js +2 -0
  81. package/dist/krate-f-router.js +2 -0
  82. package/dist/krate-features.json +493 -0
  83. package/dist/krate-hydrate-lite.js +5 -5
  84. package/dist/krate-hydrate.js +5 -5
  85. package/dist/krate-runtime.js +5 -5
  86. package/dist/list.js +4 -2
  87. package/dist/metadata-routes.d.ts +75 -0
  88. package/dist/metadata-routes.js +76 -0
  89. package/dist/metadata.d.ts +222 -0
  90. package/dist/metadata.js +452 -0
  91. package/dist/metadata.test.d.ts +1 -0
  92. package/dist/metadata.test.js +167 -0
  93. package/dist/navigation-server.d.ts +27 -0
  94. package/dist/navigation-server.js +90 -0
  95. package/dist/navigation.d.ts +37 -0
  96. package/dist/navigation.js +195 -0
  97. package/dist/navigation.test.d.ts +1 -0
  98. package/dist/navigation.test.js +130 -0
  99. package/dist/node-server.d.ts +22 -0
  100. package/dist/node-server.js +436 -0
  101. package/dist/node-server.test.d.ts +1 -0
  102. package/dist/node-server.test.js +492 -0
  103. package/dist/og-files.d.ts +2 -0
  104. package/dist/og-files.js +19 -0
  105. package/dist/og.d.ts +56 -0
  106. package/dist/og.js +156 -0
  107. package/dist/patterns.test.d.ts +1 -0
  108. package/dist/patterns.test.js +98 -0
  109. package/dist/react.d.ts +47 -0
  110. package/dist/react.js +59 -1
  111. package/dist/react19.test.d.ts +1 -0
  112. package/dist/react19.test.js +176 -0
  113. package/dist/reactivity-core.test.d.ts +1 -0
  114. package/dist/reactivity-core.test.js +152 -0
  115. package/dist/reconcile.js +4 -2
  116. package/dist/request-context.d.ts +23 -0
  117. package/dist/request-context.js +45 -0
  118. package/dist/resp.d.ts +55 -0
  119. package/dist/resp.js +239 -0
  120. package/dist/router-layout.test.js +70 -0
  121. package/dist/router-nav.test.js +65 -0
  122. package/dist/router-speculation.test.d.ts +1 -0
  123. package/dist/router-speculation.test.js +25 -0
  124. package/dist/router-styles.test.d.ts +1 -0
  125. package/dist/router-styles.test.js +98 -0
  126. package/dist/router.js +175 -36
  127. package/dist/segmented-lru.d.ts +19 -0
  128. package/dist/segmented-lru.js +87 -0
  129. package/dist/server-async.test.js +43 -1
  130. package/dist/server-handler.d.ts +165 -0
  131. package/dist/server-handler.js +1826 -0
  132. package/dist/server-handler.test.d.ts +1 -0
  133. package/dist/server-handler.test.js +522 -0
  134. package/dist/server-highlight.test.d.ts +1 -0
  135. package/dist/server-highlight.test.js +32 -0
  136. package/dist/server-renderer.js +165 -720
  137. package/dist/server-renderer.test.d.ts +1 -0
  138. package/dist/server-renderer.test.js +266 -0
  139. package/dist/server.d.ts +13 -1
  140. package/dist/server.js +131 -16
  141. package/dist/server.test.js +20 -0
  142. package/dist/sha256.d.ts +1 -0
  143. package/dist/sha256.js +66 -0
  144. package/dist/sha256.test.d.ts +1 -0
  145. package/dist/sha256.test.js +13 -0
  146. package/dist/shared-isr.d.ts +31 -0
  147. package/dist/shared-isr.js +142 -0
  148. package/dist/signal.d.ts +3 -2
  149. package/dist/signal.js +163 -23
  150. package/dist/slots.js +12 -1
  151. package/dist/ssr-core-behavior.test.d.ts +1 -0
  152. package/dist/ssr-core-behavior.test.js +620 -0
  153. package/dist/ssr-core.d.ts +175 -0
  154. package/dist/ssr-core.js +940 -0
  155. package/dist/ssr-core.test.d.ts +1 -0
  156. package/dist/ssr-core.test.js +324 -0
  157. package/dist/static-memory.d.ts +3 -0
  158. package/dist/static-memory.js +47 -0
  159. package/dist/static-memory.test.d.ts +1 -0
  160. package/dist/static-memory.test.js +26 -0
  161. package/dist/test-redis.d.ts +12 -0
  162. package/dist/test-redis.js +131 -0
  163. package/dist/use-id.d.ts +8 -0
  164. package/dist/use-id.js +40 -0
  165. package/package.json +30 -2
package/dist/og.js ADDED
@@ -0,0 +1,156 @@
1
+ // ImageResponse: JSX in, PNG out, for opengraph-image.tsx and twitter-image.tsx
2
+ // (the same shape as next/og). The element tree is serialized here and drawn by
3
+ // the Krate server in Go (internal/ogimage): there is no headless browser, no
4
+ // native module and no dependency. Only the subset documented in the Metadata
5
+ // routes guide is drawn; anything else is a build error that names it.
6
+ //
7
+ // export default function Image() {
8
+ // return new ImageResponse(<div style={{ fontSize: 96, background: "white" }}>Hello</div>, { width: 1200, height: 630 });
9
+ // }
10
+ import { readLocalImage } from './og-files.js';
11
+ const FRAGMENT_TYPES = new Set();
12
+ function toBase64(data) {
13
+ const bytes = data instanceof ArrayBuffer ? new Uint8Array(data) : new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
14
+ const B = globalThis.Buffer;
15
+ if (B)
16
+ return B.from(bytes).toString('base64');
17
+ let s = '';
18
+ for (let i = 0; i < bytes.length; i++)
19
+ s += String.fromCharCode(bytes[i]);
20
+ return btoa(s);
21
+ }
22
+ function textOf(v) {
23
+ return typeof v === 'number' ? String(v) : v;
24
+ }
25
+ /** Serializes a JSX value to the renderer's tree. Function components are called. */
26
+ export function serializeElement(node, path = 'root') {
27
+ if (node === null || node === undefined || node === false || node === true)
28
+ return [];
29
+ if (typeof node === 'string' || typeof node === 'number')
30
+ return [{ type: 'text', text: textOf(node) }];
31
+ if (Array.isArray(node))
32
+ return node.flatMap((c, i) => serializeElement(c, `${path}[${i}]`));
33
+ if (typeof node !== 'object')
34
+ throw new TypeError(`ImageResponse: ${path} is not an element`);
35
+ const el = node;
36
+ if (typeof el.__raw === 'string')
37
+ throw new TypeError(`ImageResponse: ${path} is raw HTML, which is not supported`);
38
+ const props = { ...(el.props || {}) };
39
+ const children = el.children || [];
40
+ if (typeof el.type === 'function') {
41
+ const out = el.type({ ...props, children: children.length === 1 ? children[0] : children });
42
+ if (out && typeof out.then === 'function') {
43
+ throw new TypeError(`ImageResponse: ${path} is an async component; resolve its data before building the image`);
44
+ }
45
+ return serializeElement(out, path);
46
+ }
47
+ if (typeof el.type !== 'string') {
48
+ if (FRAGMENT_TYPES.has(el.type))
49
+ return serializeElement(children, path);
50
+ throw new TypeError(`ImageResponse: ${path} has an unsupported element type`);
51
+ }
52
+ if (props.tw !== undefined)
53
+ throw new TypeError(`ImageResponse: the tw prop is not supported (${path} <${el.type}>); use the style prop`);
54
+ const style = { ...(typeof props.style === 'object' && props.style ? props.style : {}) };
55
+ const out = { type: 'element', tag: el.type, style };
56
+ if (el.type === 'img') {
57
+ out.src = typeof props.src === 'string' ? props.src : '';
58
+ if (props.width !== undefined && style.width === undefined)
59
+ style.width = props.width;
60
+ if (props.height !== undefined && style.height === undefined)
61
+ style.height = props.height;
62
+ return [out];
63
+ }
64
+ out.children = children.flatMap((c, i) => serializeElement(c, `${path}>${el.type}[${i}]`));
65
+ return [out];
66
+ }
67
+ /** The renderer spec for an element and options. */
68
+ export function buildImageSpec(element, options = {}) {
69
+ const nodes = serializeElement(element);
70
+ if (nodes.length !== 1)
71
+ throw new TypeError('ImageResponse expects one root element');
72
+ const spec = { width: options.width ?? 1200, height: options.height ?? 630, tree: nodes[0] };
73
+ if (options.fonts && options.fonts.length) {
74
+ spec.fonts = options.fonts.map((f) => ({ name: f.name, data: toBase64(f.data), weight: f.weight, style: f.style }));
75
+ }
76
+ return spec;
77
+ }
78
+ const MIME = { png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', gif: 'image/gif', webp: 'image/webp' };
79
+ /**
80
+ * Replaces the src of every <img> (a file path under root or public/, or an
81
+ * http(s) URL) with a data: URI, so the Go renderer needs no network or file
82
+ * access. Run at build time and before a per-request render.
83
+ */
84
+ export async function inlineImages(spec, root) {
85
+ const visit = async (n) => {
86
+ if (n.type !== 'element')
87
+ return;
88
+ if (n.tag === 'img' && n.src && !n.src.startsWith('data:'))
89
+ n.src = await loadImage(n.src, root);
90
+ for (const c of n.children || [])
91
+ await visit(c);
92
+ };
93
+ await visit(spec.tree);
94
+ }
95
+ async function loadImage(src, root) {
96
+ const ext = (src.split(/[?#]/)[0].split('.').pop() || 'png').toLowerCase();
97
+ const mime = MIME[ext] || 'image/png';
98
+ if (/^https?:\/\//i.test(src)) {
99
+ const res = await fetch(src);
100
+ if (!res.ok)
101
+ throw new Error(`ImageResponse: ${src} answered ${res.status}`);
102
+ return `data:${res.headers.get('content-type') || mime};base64,${toBase64(new Uint8Array(await res.arrayBuffer()))}`;
103
+ }
104
+ const data = await readLocalImage(src, root);
105
+ if (data)
106
+ return `data:${mime};base64,${toBase64(data)}`;
107
+ throw new Error(`ImageResponse: cannot find the image ${src} (looked in public/ and the project root)`);
108
+ }
109
+ function env(name) {
110
+ const proc = globalThis.process;
111
+ return (proc && proc.env && proc.env[name]) || '';
112
+ }
113
+ /** Draws the spec on the Krate server (per-request path); the build calls the renderer directly. */
114
+ async function renderOnHost(spec) {
115
+ const host = env('KRATE_HOST_URL');
116
+ const secret = env('KRATE_INTERNAL_SECRET');
117
+ if (!host || !secret) {
118
+ throw new Error('ImageResponse can only be drawn by the Krate server: at build time (opengraph-image files) or in a route served by `krate start` with the Node API runtime. This runtime has no renderer.');
119
+ }
120
+ await inlineImages(spec, env('KRATE_ROOT') || '.');
121
+ const res = await fetch(host.replace(/\/$/, '') + '/__krate/internal/image', {
122
+ method: 'POST',
123
+ headers: { 'content-type': 'application/json', 'x-krate-internal': secret },
124
+ body: JSON.stringify(spec),
125
+ });
126
+ if (!res.ok)
127
+ throw new Error(`ImageResponse: the renderer answered ${res.status}: ${await res.text()}`);
128
+ return new Uint8Array(await res.arrayBuffer());
129
+ }
130
+ /**
131
+ * A Response that carries a PNG. Built from JSX with the same options as
132
+ * Next.js's ImageResponse (width, height, fonts, status, headers).
133
+ */
134
+ export class ImageResponse extends Response {
135
+ constructor(element, options = {}) {
136
+ const spec = buildImageSpec(element, options);
137
+ const body = new ReadableStream({
138
+ async pull(controller) {
139
+ try {
140
+ controller.enqueue(await renderOnHost(spec));
141
+ controller.close();
142
+ }
143
+ catch (err) {
144
+ controller.error(err);
145
+ }
146
+ },
147
+ });
148
+ const headers = new Headers(options.headers);
149
+ if (!headers.has('content-type'))
150
+ headers.set('content-type', 'image/png');
151
+ if (!headers.has('cache-control'))
152
+ headers.set('cache-control', 'public, max-age=31536000, immutable');
153
+ super(body, { status: options.status ?? 200, statusText: options.statusText, headers });
154
+ this.__krateImage = spec;
155
+ }
156
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -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/react.d.ts CHANGED
@@ -18,6 +18,7 @@
18
18
  * minimal.
19
19
  */
20
20
  import { h, type Component as FnComponent } from './dom.js';
21
+ import { krateHintPreload, krateHintPreinit, krateHintPreconnect, krateHintPrefetchDNS, krateHintPreloadModule, krateHintPreinitModule } from './hints.js';
21
22
  import { requestFormReset as krateRequestFormReset, type FormStatus } from './actions.js';
22
23
  /** React's `Fragment` marker; `createElement(Fragment, ...)` yields a fragment. */
23
24
  export declare const Fragment: unique symbol;
@@ -67,6 +68,26 @@ export declare function Profiler(props: {
67
68
  onRender?: unknown;
68
69
  children?: unknown;
69
70
  }): Node;
71
+ /**
72
+ * React 19.2's Activity for code the compiler did not lower: the children are
73
+ * always rendered inside a `display:contents` wrapper that hides them when
74
+ * `mode` is "hidden", so their state is kept. (Source components get the full
75
+ * semantics, including effect cleanup while hidden, from the compiler.)
76
+ */
77
+ export declare function Activity(props: {
78
+ mode?: 'visible' | 'hidden';
79
+ children?: unknown;
80
+ }): Node;
81
+ /**
82
+ * ViewTransition names its element child for the View Transitions API.
83
+ * Children that are not a host element render unchanged.
84
+ */
85
+ export declare function ViewTransition(props: {
86
+ name?: string;
87
+ default?: string;
88
+ children?: unknown;
89
+ }): Node;
90
+ export declare const unstable_ViewTransition: typeof ViewTransition;
70
91
  /**
71
92
  * A Suspense boundary. Children that suspend render as placeholders; while
72
93
  * any placeholder under this boundary is pending the fallback is shown, and
@@ -102,6 +123,25 @@ export declare function useReducer<S, A, I = S>(reducer: (state: S, action: A) =
102
123
  export declare function useMemo<T>(factory: () => T, _deps?: unknown[]): T;
103
124
  /** Memoized callback: one identity for the component's lifetime. */
104
125
  export declare function useCallback<T extends (...args: never[]) => unknown>(fn: T, _deps?: unknown[]): T;
126
+ /**
127
+ * React's cache() memoizes per request on the server; Krate renders a page
128
+ * once, so it returns the function. (The compiler lowers calls to it.)
129
+ */
130
+ export declare function cache<T extends (...args: never[]) => unknown>(fn: T): T;
131
+ /** The React version whose API this runtime follows. */
132
+ export declare const version = "19.2.0";
133
+ /** React's owner stack is a development aid; production builds return null. */
134
+ export declare function captureOwnerStack(): string | null;
135
+ /**
136
+ * SuspenseList orders the reveal of the boundaries inside it. Krate reveals
137
+ * each boundary on its own, so it renders its children.
138
+ */
139
+ export declare function SuspenseList(props: {
140
+ children?: unknown;
141
+ }): Node;
142
+ export declare const unstable_SuspenseList: typeof SuspenseList;
143
+ /** React 19.2's useEffectEvent: a function that always runs the latest closure. */
144
+ export declare const useEffectEvent: <T extends (...args: never[]) => unknown>(fn: T) => T;
105
145
  export declare function useRef<T = unknown>(initial?: T): RefObject<T>;
106
146
  type EffectCallback = () => void | (() => void);
107
147
  /** Passive effect: runs after paint, re-runs when a live dependency changes. */
@@ -143,6 +183,13 @@ export declare function useActionState<State, Payload>(action: (prev: State, pay
143
183
  * code without an element, it reports an idle status.
144
184
  */
145
185
  export declare function useFormStatus(): FormStatus;
186
+ /** React DOM resource hints. */
187
+ export declare const preload: typeof krateHintPreload;
188
+ export declare const preinit: typeof krateHintPreinit;
189
+ export declare const preconnect: typeof krateHintPreconnect;
190
+ export declare const prefetchDNS: typeof krateHintPrefetchDNS;
191
+ export declare const preloadModule: typeof krateHintPreloadModule;
192
+ export declare const preinitModule: typeof krateHintPreinitModule;
146
193
  /** React DOM `requestFormReset(form)`. */
147
194
  export declare const requestFormReset: typeof krateRequestFormReset;
148
195
  /**
package/dist/react.js CHANGED
@@ -20,9 +20,10 @@
20
20
  import { h, krateTrackNode } from './dom.js';
21
21
  import { getOwner, handleError } from './boundary.js';
22
22
  import { createSignal, createReducer, isSignalGetter } from './signal.js';
23
- import { createEffectDeps } from './effects.js';
23
+ import { createEffectDeps, createEffectEvent } from './effects.js';
24
24
  import { krateSetRef } from './refs.js';
25
25
  import { krateEventRoot } from './events.js';
26
+ import { krateHintPreload, krateHintPreinit, krateHintPreconnect, krateHintPrefetchDNS, krateHintPreloadModule, krateHintPreinitModule, } from './hints.js';
26
27
  import { createContext as krateCreateContext } from './context.js';
27
28
  import { cloneElement as krateCloneElement } from './class-helpers.js';
28
29
  import { jsx as krateJsx } from './jsx-runtime.js';
@@ -223,6 +224,33 @@ export const StrictMode = Fragment;
223
224
  export function Profiler(props) {
224
225
  return fragmentChildren(toArray(props.children));
225
226
  }
227
+ /**
228
+ * React 19.2's Activity for code the compiler did not lower: the children are
229
+ * always rendered inside a `display:contents` wrapper that hides them when
230
+ * `mode` is "hidden", so their state is kept. (Source components get the full
231
+ * semantics, including effect cleanup while hidden, from the compiler.)
232
+ */
233
+ export function Activity(props) {
234
+ const wrapper = h('krate-activity', { style: () => 'display:' + (props.mode === 'hidden' ? 'none' : 'contents') }, ...toArray(props.children));
235
+ return wrapper;
236
+ }
237
+ /**
238
+ * ViewTransition names its element child for the View Transitions API.
239
+ * Children that are not a host element render unchanged.
240
+ */
241
+ export function ViewTransition(props) {
242
+ const frag = fragmentChildren(toArray(props.children));
243
+ const first = Array.from(frag.childNodes).find((n) => n.nodeType === 1);
244
+ if (first) {
245
+ first.setAttribute('data-view-transition', props.name || 'krate-vt-' + ++viewTransitionSeq);
246
+ if (props.default && props.default !== 'auto' && props.default !== 'none') {
247
+ first.setAttribute('data-view-transition-class', props.default);
248
+ }
249
+ }
250
+ return frag;
251
+ }
252
+ let viewTransitionSeq = 0;
253
+ export const unstable_ViewTransition = ViewTransition;
226
254
  /**
227
255
  * A Suspense boundary. Children that suspend render as placeholders; while
228
256
  * any placeholder under this boundary is pending the fallback is shown, and
@@ -312,6 +340,29 @@ export function useMemo(factory, _deps) {
312
340
  export function useCallback(fn, _deps) {
313
341
  return fn;
314
342
  }
343
+ /**
344
+ * React's cache() memoizes per request on the server; Krate renders a page
345
+ * once, so it returns the function. (The compiler lowers calls to it.)
346
+ */
347
+ export function cache(fn) {
348
+ return fn;
349
+ }
350
+ /** The React version whose API this runtime follows. */
351
+ export const version = '19.2.0';
352
+ /** React's owner stack is a development aid; production builds return null. */
353
+ export function captureOwnerStack() {
354
+ return null;
355
+ }
356
+ /**
357
+ * SuspenseList orders the reveal of the boundaries inside it. Krate reveals
358
+ * each boundary on its own, so it renders its children.
359
+ */
360
+ export function SuspenseList(props) {
361
+ return fragmentChildren(toArray(props.children));
362
+ }
363
+ export const unstable_SuspenseList = SuspenseList;
364
+ /** React 19.2's useEffectEvent: a function that always runs the latest closure. */
365
+ export const useEffectEvent = createEffectEvent;
315
366
  export function useRef(initial) {
316
367
  return { current: initial ?? null };
317
368
  }
@@ -381,6 +432,13 @@ export function useActionState(action, initial, _permalink) {
381
432
  export function useFormStatus() {
382
433
  return { pending: false, data: null, method: null, action: null };
383
434
  }
435
+ /** React DOM resource hints. */
436
+ export const preload = krateHintPreload;
437
+ export const preinit = krateHintPreinit;
438
+ export const preconnect = krateHintPreconnect;
439
+ export const prefetchDNS = krateHintPrefetchDNS;
440
+ export const preloadModule = krateHintPreloadModule;
441
+ export const preinitModule = krateHintPreinitModule;
384
442
  /** React DOM `requestFormReset(form)`. */
385
443
  export const requestFormReset = krateRequestFormReset;
386
444
  /**
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,176 @@
1
+ import { describe, it, expect, beforeEach } from 'vitest';
2
+ import { createSignal, createEffect, disposeAll } from './signal';
3
+ import { createEffectEvent } from './effects';
4
+ import { krateWithIdScope, __krate_useId } from './use-id';
5
+ import { h, krateCustomProp } from './dom';
6
+ import { Activity, ViewTransition, useEffectEvent, createElement } from './react';
7
+ const tick = () => new Promise((r) => setTimeout(r, 0));
8
+ describe('createEffectEvent', () => {
9
+ beforeEach(() => disposeAll());
10
+ it('always runs the latest closure over live state', () => {
11
+ const [n, setN] = createSignal(0);
12
+ const seen = [];
13
+ const onTick = createEffectEvent(() => void seen.push(n()));
14
+ onTick();
15
+ setN(5);
16
+ onTick();
17
+ expect(seen).toEqual([0, 5]);
18
+ });
19
+ it('does not subscribe the caller to what it reads', async () => {
20
+ const [n, setN] = createSignal(0);
21
+ let runs = 0;
22
+ const onTick = createEffectEvent(() => n());
23
+ createEffect(() => {
24
+ runs++;
25
+ onTick();
26
+ });
27
+ setN(1);
28
+ await tick();
29
+ expect(runs).toBe(1);
30
+ });
31
+ it('forwards arguments, this and the result', () => {
32
+ const e = createEffectEvent(function (a, b) {
33
+ return this.k + a + b;
34
+ });
35
+ expect(e.call({ k: 1 }, 2, 3)).toBe(6);
36
+ });
37
+ it('is exported by the compat runtime as useEffectEvent', () => {
38
+ expect(useEffectEvent).toBe(createEffectEvent);
39
+ });
40
+ });
41
+ describe('useId at runtime', () => {
42
+ it('numbers ids per list row scope and falls back to a global counter', () => {
43
+ const a = krateWithIdScope('L:$a', () => [__krate_useId(), __krate_useId()]);
44
+ const b = krateWithIdScope('L:$b', () => [__krate_useId()]);
45
+ expect(a).toEqual(['krate-L:$a-u0', 'krate-L:$a-u1']);
46
+ expect(b).toEqual(['krate-L:$b-u0']);
47
+ const x = __krate_useId();
48
+ const y = __krate_useId();
49
+ expect(x).not.toBe(y);
50
+ expect(x.startsWith('krate_u')).toBe(true);
51
+ });
52
+ it('encodes characters that are not valid in an id', () => {
53
+ const id = krateWithIdScope('L:$a b/ü', () => __krate_useId());
54
+ expect(id).toBe('krate-L:$a%20b%2F%C3%BC-u0');
55
+ });
56
+ it('keeps the outer scope when the inner one has no prefix', () => {
57
+ const ids = krateWithIdScope('L:$a', () => [__krate_useId(), krateWithIdScope('', () => __krate_useId())]);
58
+ expect(ids).toEqual(['krate-L:$a-u0', 'krate-L:$a-u1']);
59
+ });
60
+ it('restores the scope after the callback throws', () => {
61
+ expect(() => krateWithIdScope('L:$a', () => {
62
+ throw new Error('x');
63
+ })).toThrow('x');
64
+ expect(__krate_useId().startsWith('krate_u')).toBe(true);
65
+ });
66
+ });
67
+ describe('custom element props', () => {
68
+ it('sets objects, arrays and functions as properties', () => {
69
+ const el = document.createElement('my-thing');
70
+ const obj = { a: 1 };
71
+ const fn = () => 1;
72
+ expect(krateCustomProp(el, 'data', obj)).toBe(true);
73
+ expect(krateCustomProp(el, 'list', [1])).toBe(true);
74
+ expect(krateCustomProp(el, 'cb', fn)).toBe(true);
75
+ const rec = el;
76
+ expect(rec.data).toBe(obj);
77
+ expect(rec.cb).toBe(fn);
78
+ expect(el.hasAttribute('data')).toBe(false);
79
+ });
80
+ it('leaves primitives to attributes unless the element defines the property', () => {
81
+ const el = document.createElement('my-thing');
82
+ expect(krateCustomProp(el, 's', 'str')).toBe(false);
83
+ class Defined extends HTMLElement {
84
+ constructor() {
85
+ super(...arguments);
86
+ this.count = 0;
87
+ }
88
+ }
89
+ customElements.define('defined-thing', Defined);
90
+ const d = document.createElement('defined-thing');
91
+ expect(krateCustomProp(d, 'count', 3)).toBe(true);
92
+ expect(d.count).toBe(3);
93
+ });
94
+ it('ignores ordinary elements and dashed names', () => {
95
+ expect(krateCustomProp(document.createElement('div'), 'data', {})).toBe(false);
96
+ expect(krateCustomProp(document.createElement('my-thing'), 'data-x', {})).toBe(false);
97
+ });
98
+ it('re-applies an object once the element class is defined', async () => {
99
+ const el = document.createElement('late-thing');
100
+ document.body.appendChild(el);
101
+ const obj = { v: 1 };
102
+ krateCustomProp(el, 'data', obj);
103
+ const seen = [];
104
+ class Late extends HTMLElement {
105
+ set data(v) {
106
+ seen.push(v);
107
+ }
108
+ get data() {
109
+ return seen[seen.length - 1];
110
+ }
111
+ }
112
+ customElements.define('late-thing', Late);
113
+ await customElements.whenDefined('late-thing');
114
+ await tick();
115
+ expect(seen).toContain(obj);
116
+ el.remove();
117
+ });
118
+ it('h() routes props of a custom element through the property rules', () => {
119
+ const obj = { a: 1 };
120
+ const el = h('my-card', { data: obj, title: 'x', open: true });
121
+ expect(el.data).toBe(obj);
122
+ expect(el.getAttribute('title')).toBe('x');
123
+ expect(el.getAttribute('open')).toBe('');
124
+ expect(el.hasAttribute('data')).toBe(false);
125
+ });
126
+ });
127
+ describe('Activity and ViewTransition (unlowered code)', () => {
128
+ beforeEach(() => disposeAll());
129
+ it('Activity renders its children and hides them in hidden mode', async () => {
130
+ const [mode, setMode] = createSignal('visible');
131
+ const root = Activity({
132
+ get mode() {
133
+ return mode();
134
+ },
135
+ children: createElement('p', null, 'kept'),
136
+ });
137
+ document.body.appendChild(root);
138
+ expect(root.querySelector('p').textContent).toBe('kept');
139
+ expect(root.style.display).toBe('contents');
140
+ setMode('hidden');
141
+ await tick();
142
+ expect(root.style.display).toBe('none');
143
+ expect(root.querySelector('p').textContent).toBe('kept');
144
+ root.remove();
145
+ });
146
+ it('ViewTransition names its first element child and keeps the rest', () => {
147
+ const frag = ViewTransition({
148
+ name: 'hero',
149
+ default: 'slow',
150
+ children: [createElement('h1', null, 'T'), createElement('p', null, 'rest')],
151
+ });
152
+ const h1 = frag.querySelector('h1');
153
+ expect(h1.getAttribute('data-view-transition')).toBe('hero');
154
+ expect(h1.getAttribute('data-view-transition-class')).toBe('slow');
155
+ expect(frag.querySelector('p').hasAttribute('data-view-transition')).toBe(false);
156
+ expect(frag.textContent).toBe('Trest');
157
+ });
158
+ });
159
+ describe('resource hints', () => {
160
+ it('adds each link once', async () => {
161
+ const { krateHintPreload, krateHintPreconnect, krateHintPreinit, krateHintPrefetchDNS } = await import('./hints');
162
+ krateHintPreload('/a.css', { as: 'style' });
163
+ krateHintPreload('/a.css', { as: 'style' });
164
+ krateHintPreconnect('https://example.com');
165
+ krateHintPrefetchDNS('https://example.com');
166
+ krateHintPreinit('/b.css', { as: 'style' });
167
+ krateHintPreinit('/c.js', { as: 'script' });
168
+ const q = (s) => document.head.querySelectorAll(s).length;
169
+ expect(q('link[rel="preload"][href="/a.css"]')).toBe(1);
170
+ expect(document.head.querySelector('link[rel="preload"]').getAttribute('as')).toBe('style');
171
+ expect(q('link[rel="preconnect"][href="https://example.com"]')).toBe(1);
172
+ expect(q('link[rel="dns-prefetch"][href="https://example.com"]')).toBe(1);
173
+ expect(q('link[rel="stylesheet"][href="/b.css"]')).toBe(1);
174
+ expect(q('script[src="/c.js"]')).toBe(1);
175
+ });
176
+ });
@@ -0,0 +1 @@
1
+ export {};