@krate/runtime 0.5.0-beta.1 → 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 (134) hide show
  1. package/dist/actions.js +2 -1
  2. package/dist/assets-static.d.ts +5 -0
  3. package/dist/assets-static.js +31 -0
  4. package/dist/boundary.d.ts +12 -0
  5. package/dist/boundary.js +53 -13
  6. package/dist/cache-adapter.d.ts +113 -0
  7. package/dist/cache-adapter.js +217 -0
  8. package/dist/cache-adapter.test.d.ts +1 -0
  9. package/dist/cache-adapter.test.js +244 -0
  10. package/dist/cache-redis.d.ts +27 -0
  11. package/dist/cache-redis.js +110 -0
  12. package/dist/cache-scope.d.ts +25 -9
  13. package/dist/cache-scope.js +60 -12
  14. package/dist/cache.d.ts +1 -0
  15. package/dist/cache.js +3 -3
  16. package/dist/class-component.js +6 -0
  17. package/dist/class-component.test.js +53 -2
  18. package/dist/dev-overlay.js +10 -10
  19. package/dist/dom.d.ts +8 -0
  20. package/dist/dom.js +28 -0
  21. package/dist/effect-errors.test.d.ts +1 -0
  22. package/dist/effect-errors.test.js +163 -0
  23. package/dist/effects.d.ts +8 -0
  24. package/dist/effects.js +13 -0
  25. package/dist/error-overlay.js +4 -4
  26. package/dist/handler-html.d.ts +63 -0
  27. package/dist/handler-html.js +285 -0
  28. package/dist/handler-html.test.d.ts +1 -0
  29. package/dist/handler-html.test.js +256 -0
  30. package/dist/handler-routing.d.ts +83 -0
  31. package/dist/handler-routing.js +579 -0
  32. package/dist/handler-routing.test.d.ts +1 -0
  33. package/dist/handler-routing.test.js +99 -0
  34. package/dist/handler-segments.d.ts +43 -0
  35. package/dist/handler-segments.js +115 -0
  36. package/dist/handler-segments.test.d.ts +1 -0
  37. package/dist/handler-segments.test.js +217 -0
  38. package/dist/head-tags.d.ts +51 -0
  39. package/dist/head-tags.js +329 -0
  40. package/dist/head-tags.test.d.ts +1 -0
  41. package/dist/head-tags.test.js +131 -0
  42. package/dist/highlight-bind.d.ts +42 -0
  43. package/dist/highlight-bind.js +176 -0
  44. package/dist/highlight-bind.test.d.ts +1 -0
  45. package/dist/highlight-bind.test.js +124 -0
  46. package/dist/highlight.d.ts +93 -0
  47. package/dist/highlight.js +426 -0
  48. package/dist/highlight.test.d.ts +1 -0
  49. package/dist/highlight.test.js +56 -0
  50. package/dist/hints.d.ts +19 -0
  51. package/dist/hints.js +97 -0
  52. package/dist/index.d.ts +3 -0
  53. package/dist/index.js +2 -0
  54. package/dist/jsx-types.d.ts +11 -0
  55. package/dist/krate-core.js +1 -1
  56. package/dist/krate-dev.js +10 -10
  57. package/dist/krate-f-actions.js +1 -1
  58. package/dist/krate-f-classes.js +5 -5
  59. package/dist/krate-f-highlight.js +2 -0
  60. package/dist/krate-f-list.js +1 -1
  61. package/dist/krate-f-navigation.js +2 -0
  62. package/dist/krate-f-router.js +1 -1
  63. package/dist/krate-features.json +254 -0
  64. package/dist/krate-hydrate-lite.js +5 -5
  65. package/dist/krate-hydrate.js +5 -5
  66. package/dist/krate-runtime.js +5 -5
  67. package/dist/list.js +4 -2
  68. package/dist/metadata-routes.d.ts +75 -0
  69. package/dist/metadata-routes.js +76 -0
  70. package/dist/metadata.d.ts +222 -0
  71. package/dist/metadata.js +452 -0
  72. package/dist/metadata.test.d.ts +1 -0
  73. package/dist/metadata.test.js +167 -0
  74. package/dist/navigation-server.d.ts +27 -0
  75. package/dist/navigation-server.js +90 -0
  76. package/dist/navigation.d.ts +37 -0
  77. package/dist/navigation.js +195 -0
  78. package/dist/navigation.test.d.ts +1 -0
  79. package/dist/navigation.test.js +130 -0
  80. package/dist/node-server.d.ts +22 -0
  81. package/dist/node-server.js +436 -0
  82. package/dist/node-server.test.d.ts +1 -0
  83. package/dist/node-server.test.js +492 -0
  84. package/dist/og-files.d.ts +2 -0
  85. package/dist/og-files.js +19 -0
  86. package/dist/og.d.ts +56 -0
  87. package/dist/og.js +156 -0
  88. package/dist/react.d.ts +47 -0
  89. package/dist/react.js +59 -1
  90. package/dist/react19.test.d.ts +1 -0
  91. package/dist/react19.test.js +176 -0
  92. package/dist/request-context.d.ts +23 -0
  93. package/dist/request-context.js +45 -0
  94. package/dist/resp.d.ts +55 -0
  95. package/dist/resp.js +239 -0
  96. package/dist/router-layout.test.js +70 -0
  97. package/dist/router-nav.test.js +27 -0
  98. package/dist/router.js +59 -4
  99. package/dist/segmented-lru.d.ts +19 -0
  100. package/dist/segmented-lru.js +87 -0
  101. package/dist/server-async.test.js +23 -1
  102. package/dist/server-handler.d.ts +165 -0
  103. package/dist/server-handler.js +1826 -0
  104. package/dist/server-handler.test.d.ts +1 -0
  105. package/dist/server-handler.test.js +522 -0
  106. package/dist/server-highlight.test.d.ts +1 -0
  107. package/dist/server-highlight.test.js +32 -0
  108. package/dist/server-renderer.js +146 -788
  109. package/dist/server-renderer.test.d.ts +1 -0
  110. package/dist/server-renderer.test.js +266 -0
  111. package/dist/server.d.ts +12 -1
  112. package/dist/server.js +42 -6
  113. package/dist/sha256.d.ts +1 -0
  114. package/dist/sha256.js +66 -0
  115. package/dist/sha256.test.d.ts +1 -0
  116. package/dist/sha256.test.js +13 -0
  117. package/dist/shared-isr.d.ts +31 -0
  118. package/dist/shared-isr.js +142 -0
  119. package/dist/signal.js +63 -8
  120. package/dist/ssr-core-behavior.test.d.ts +1 -0
  121. package/dist/ssr-core-behavior.test.js +620 -0
  122. package/dist/ssr-core.d.ts +175 -0
  123. package/dist/ssr-core.js +940 -0
  124. package/dist/ssr-core.test.d.ts +1 -0
  125. package/dist/ssr-core.test.js +324 -0
  126. package/dist/static-memory.d.ts +3 -0
  127. package/dist/static-memory.js +47 -0
  128. package/dist/static-memory.test.d.ts +1 -0
  129. package/dist/static-memory.test.js +26 -0
  130. package/dist/test-redis.d.ts +12 -0
  131. package/dist/test-redis.js +131 -0
  132. package/dist/use-id.d.ts +8 -0
  133. package/dist/use-id.js +40 -0
  134. package/package.json +29 -1
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
+ }
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
+ });
@@ -58,5 +58,28 @@ export interface NotFoundSignal extends Error {
58
58
  export declare function notFound(): never;
59
59
  /** isNotFoundSignal reports whether err was thrown by notFound(). */
60
60
  export declare function isNotFoundSignal(err: unknown): boolean;
61
+ /** Thrown by forbidden() and unauthorized(); the host answers 403 or 401. */
62
+ export interface HTTPFallbackSignal extends Error {
63
+ __krateHTTPStatus: 401 | 403;
64
+ digest: string;
65
+ }
66
+ /**
67
+ * Stops rendering and responds with 403 and the nearest forbidden page
68
+ * (forbidden.tsx or 403.tsx). Works in pages, layouts, async server
69
+ * components, server actions and API routes.
70
+ */
71
+ export declare function forbidden(): never;
72
+ /**
73
+ * Stops rendering and responds with 401 and the nearest unauthorized page
74
+ * (unauthorized.tsx or 401.tsx). Works wherever forbidden() does.
75
+ */
76
+ export declare function unauthorized(): never;
77
+ /**
78
+ * accessDeniedStatus returns 403 or 401 when err was thrown by forbidden() or
79
+ * unauthorized() (or the matching Next.js digest), else 0.
80
+ */
81
+ export declare function accessDeniedStatus(err: unknown): 401 | 403 | 0;
82
+ /** httpFallbackStatus is 404, 403 or 401 for notFound(), forbidden() and unauthorized() signals, else 0. */
83
+ export declare function httpFallbackStatus(err: unknown): 401 | 403 | 404 | 0;
61
84
  /** redirectTarget returns the URL of a redirect() signal, or "" for other errors. */
62
85
  export declare function redirectTarget(err: unknown): string;
@@ -89,6 +89,51 @@ export function isNotFoundSignal(err) {
89
89
  return e.__krateNotFound === true || e.digest === 'NEXT_NOT_FOUND' || e.message === 'NEXT_NOT_FOUND' ||
90
90
  (typeof e.digest === 'string' && e.digest.startsWith('NEXT_HTTP_ERROR_FALLBACK;404'));
91
91
  }
92
+ function httpFallback(status) {
93
+ const err = new Error(status === 403 ? 'NEXT_FORBIDDEN' : 'NEXT_UNAUTHORIZED');
94
+ err.__krateHTTPStatus = status;
95
+ err.digest = 'NEXT_HTTP_ERROR_FALLBACK;' + status;
96
+ throw err;
97
+ }
98
+ /**
99
+ * Stops rendering and responds with 403 and the nearest forbidden page
100
+ * (forbidden.tsx or 403.tsx). Works in pages, layouts, async server
101
+ * components, server actions and API routes.
102
+ */
103
+ export function forbidden() {
104
+ return httpFallback(403);
105
+ }
106
+ /**
107
+ * Stops rendering and responds with 401 and the nearest unauthorized page
108
+ * (unauthorized.tsx or 401.tsx). Works wherever forbidden() does.
109
+ */
110
+ export function unauthorized() {
111
+ return httpFallback(401);
112
+ }
113
+ /**
114
+ * accessDeniedStatus returns 403 or 401 when err was thrown by forbidden() or
115
+ * unauthorized() (or the matching Next.js digest), else 0.
116
+ */
117
+ export function accessDeniedStatus(err) {
118
+ if (!err || typeof err !== 'object')
119
+ return 0;
120
+ const e = err;
121
+ if (e.__krateHTTPStatus === 403 || e.__krateHTTPStatus === 401)
122
+ return e.__krateHTTPStatus;
123
+ if (typeof e.digest === 'string') {
124
+ if (e.digest === 'NEXT_HTTP_ERROR_FALLBACK;403')
125
+ return 403;
126
+ if (e.digest === 'NEXT_HTTP_ERROR_FALLBACK;401')
127
+ return 401;
128
+ }
129
+ return 0;
130
+ }
131
+ /** httpFallbackStatus is 404, 403 or 401 for notFound(), forbidden() and unauthorized() signals, else 0. */
132
+ export function httpFallbackStatus(err) {
133
+ if (isNotFoundSignal(err))
134
+ return 404;
135
+ return accessDeniedStatus(err);
136
+ }
92
137
  /** redirectTarget returns the URL of a redirect() signal, or "" for other errors. */
93
138
  export function redirectTarget(err) {
94
139
  if (!err || typeof err !== 'object')
package/dist/resp.d.ts ADDED
@@ -0,0 +1,55 @@
1
+ export type RespValue = string | number | null | RespValue[] | Buffer;
2
+ export declare class RespError extends Error {
3
+ constructor(message: string);
4
+ }
5
+ export interface RespOptions {
6
+ host: string;
7
+ port: number;
8
+ tls?: boolean;
9
+ username?: string;
10
+ password?: string;
11
+ db?: number;
12
+ /** Milliseconds to wait for a connection (default 1000). */
13
+ connectTimeoutMs?: number;
14
+ /** Milliseconds to wait for one reply (default 1000). */
15
+ commandTimeoutMs?: number;
16
+ }
17
+ /** Parses redis://[user:password@]host[:port][/db] and rediss:// (TLS) URLs. */
18
+ export declare function parseRedisURL(url: string): RespOptions;
19
+ /** Encodes a command as a RESP array of bulk strings. */
20
+ export declare function encodeCommand(args: Array<string | number | Buffer>): Buffer;
21
+ /** Incremental reply parser: push chunks, take complete replies. */
22
+ export declare class RespParser {
23
+ private buf;
24
+ push(chunk: Buffer): void;
25
+ /** The next complete reply, or undefined when more bytes are needed. */
26
+ next(): RespValue | RespError | undefined;
27
+ private line;
28
+ private parse;
29
+ }
30
+ /** One connection: commands are written in order and answered in order. */
31
+ export declare class RespConnection {
32
+ private readonly opts;
33
+ private socket;
34
+ private connecting;
35
+ private pending;
36
+ private parser;
37
+ private closed;
38
+ /** Called with each pushed pub/sub message (type, channel, payload). */
39
+ onPush?: (kind: string, channel: string, payload: string) => void;
40
+ /** Called after the socket dropped (not after close()). */
41
+ onDisconnect?: (err?: Error) => void;
42
+ constructor(opts: RespOptions);
43
+ private connect;
44
+ private attach;
45
+ private settle;
46
+ private handshake;
47
+ private write;
48
+ /** Sends a command and resolves with its reply. */
49
+ command(...args: Array<string | number | Buffer>): Promise<RespValue>;
50
+ /** Writes a command without waiting for a reply (pub/sub subscribe uses pushes). */
51
+ send(...args: Array<string | number | Buffer>): Promise<void>;
52
+ /** Opens the connection now (used by the subscriber to reconnect). */
53
+ ensure(): Promise<void>;
54
+ close(): void;
55
+ }