@krate/runtime 0.5.0-alpha.2 → 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.
- package/dist/action-context.d.ts +56 -0
- package/dist/action-context.js +73 -0
- package/dist/action-context.test.d.ts +1 -0
- package/dist/action-context.test.js +47 -0
- package/dist/actions.d.ts +120 -0
- package/dist/actions.js +550 -0
- package/dist/actions.test.d.ts +1 -0
- package/dist/actions.test.js +417 -0
- package/dist/boundary.d.ts +121 -0
- package/dist/boundary.js +429 -0
- package/dist/cache-scope.d.ts +118 -0
- package/dist/cache-scope.js +311 -0
- package/dist/cache.d.ts +55 -0
- package/dist/cache.js +155 -0
- package/dist/cache.test.d.ts +1 -0
- package/dist/cache.test.js +217 -0
- package/dist/class-component.d.ts +66 -0
- package/dist/class-component.js +633 -0
- package/dist/class-component.test.d.ts +1 -0
- package/dist/class-component.test.js +411 -0
- package/dist/context.d.ts +13 -0
- package/dist/context.js +58 -32
- package/dist/context.test.d.ts +1 -0
- package/dist/context.test.js +57 -0
- package/dist/derived.test.d.ts +1 -0
- package/dist/derived.test.js +140 -0
- package/dist/discrete.test.d.ts +1 -0
- package/dist/discrete.test.js +100 -0
- package/dist/dom.d.ts +55 -0
- package/dist/dom.js +414 -63
- package/dist/effects.d.ts +88 -0
- package/dist/effects.js +790 -0
- package/dist/effects.test.d.ts +1 -0
- package/dist/effects.test.js +485 -0
- package/dist/events.d.ts +58 -0
- package/dist/events.js +503 -0
- package/dist/events.test.d.ts +1 -0
- package/dist/events.test.js +447 -0
- package/dist/index.d.ts +14 -4
- package/dist/index.js +9 -3
- package/dist/jsx-types.d.ts +2 -0
- package/dist/krate-hydrate-lite.js +7 -1
- package/dist/krate-hydrate.js +7 -1
- package/dist/krate-runtime.js +7 -1
- package/dist/krate-suspense.js +2 -0
- package/dist/lanes.test.d.ts +1 -0
- package/dist/lanes.test.js +59 -0
- package/dist/list.d.ts +20 -0
- package/dist/list.js +466 -0
- package/dist/list.test.d.ts +1 -0
- package/dist/list.test.js +344 -0
- package/dist/optimistic-lanes.test.d.ts +1 -0
- package/dist/optimistic-lanes.test.js +45 -0
- package/dist/portal.d.ts +47 -0
- package/dist/portal.js +189 -0
- package/dist/portal.test.d.ts +1 -0
- package/dist/portal.test.js +99 -0
- package/dist/react-effects.test.d.ts +1 -0
- package/dist/react-effects.test.js +96 -0
- package/dist/react-suspense.test.d.ts +1 -0
- package/dist/react-suspense.test.js +194 -0
- package/dist/react.d.ts +132 -32
- package/dist/react.js +335 -81
- package/dist/react.test.js +12 -2
- package/dist/reconcile.js +13 -0
- package/dist/refs.d.ts +33 -0
- package/dist/refs.js +142 -0
- package/dist/refs.test.d.ts +1 -0
- package/dist/refs.test.js +257 -0
- package/dist/request-context.d.ts +62 -0
- package/dist/request-context.js +107 -0
- package/dist/resource.js +20 -1
- package/dist/router-layout.test.d.ts +1 -0
- package/dist/router-layout.test.js +179 -0
- package/dist/router-lite.d.ts +25 -0
- package/dist/router-lite.js +73 -0
- package/dist/router-nav.test.d.ts +1 -0
- package/dist/router-nav.test.js +399 -0
- package/dist/router-slots.test.d.ts +1 -0
- package/dist/router-slots.test.js +144 -0
- package/dist/router.d.ts +66 -2
- package/dist/router.js +1535 -650
- package/dist/server-async.test.d.ts +1 -0
- package/dist/server-async.test.js +174 -0
- package/dist/server-renderer.js +494 -119
- package/dist/server.d.ts +27 -1
- package/dist/server.js +187 -1
- package/dist/server.test.js +20 -0
- package/dist/signal-lanes.test.d.ts +1 -0
- package/dist/signal-lanes.test.js +32 -0
- package/dist/signal.d.ts +186 -1
- package/dist/signal.js +896 -66
- package/dist/slots.d.ts +22 -0
- package/dist/slots.js +134 -0
- package/dist/slots.test.d.ts +1 -0
- package/dist/slots.test.js +169 -0
- package/dist/snapshots.test.d.ts +1 -0
- package/dist/snapshots.test.js +208 -0
- package/dist/suspense-actions.test.d.ts +1 -0
- package/dist/suspense-actions.test.js +72 -0
- package/dist/suspense.d.ts +220 -0
- package/dist/suspense.js +901 -0
- package/dist/suspense.test.d.ts +1 -0
- package/dist/suspense.test.js +518 -0
- package/package.json +5 -1
package/dist/server.d.ts
CHANGED
|
@@ -1,6 +1,14 @@
|
|
|
1
|
+
export { getActionContext, headers, cookies, redirect } from './action-context.js';
|
|
2
|
+
export type { ActionContext, ActionCookies, ActionCookieOptions } from './action-context.js';
|
|
3
|
+
export { revalidatePath, revalidateTag, unstable_cache, unstable_noStore } from './cache.js';
|
|
4
|
+
export type { RevalidatePathType, UnstableCacheOptions } from './cache.js';
|
|
5
|
+
export { getRequestContext, notFound } from './request-context.js';
|
|
6
|
+
export type { RequestContext, RequestCookies } from './request-context.js';
|
|
1
7
|
export declare function createSignal<T>(initial: T): [() => T, (v: T | ((prev: T) => T)) => void];
|
|
2
8
|
export declare function createEffect(_fn: () => void): () => void;
|
|
3
9
|
export declare function createMemo<T>(fn: () => T): () => T;
|
|
10
|
+
export declare function krateDerived<T>(fn: () => T, _triggers?: () => unknown): () => T;
|
|
11
|
+
export declare function krateHook<T>(value: T | (() => T)): () => T;
|
|
4
12
|
export declare function onCleanup(_fn: () => void): void;
|
|
5
13
|
export declare function onMount(_fn: () => void): void;
|
|
6
14
|
interface RawHTML {
|
|
@@ -19,6 +27,16 @@ export declare function Fragment(_props: {
|
|
|
19
27
|
export declare function jsx(type: string | Function, props: Record<string, any>, _key?: string): JSXElement;
|
|
20
28
|
export declare const jsxs: typeof jsx;
|
|
21
29
|
export declare function renderToString(node: JSXNode): string;
|
|
30
|
+
/**
|
|
31
|
+
* renderToStringAsync renders a tree that may contain async (server)
|
|
32
|
+
* components. Every Promise-returning component is awaited, at any depth, and
|
|
33
|
+
* sibling subtrees resolve in parallel. Errors thrown by a component (or a
|
|
34
|
+
* rejected Promise) reject the returned Promise; nothing renders as "".
|
|
35
|
+
*
|
|
36
|
+
* <Suspense> renders its resolved children: the whole tree is awaited before
|
|
37
|
+
* any HTML is produced, so there is no fallback to show.
|
|
38
|
+
*/
|
|
39
|
+
export declare function renderToStringAsync(node: unknown): Promise<string>;
|
|
22
40
|
export declare function setStreamingResolved(v: boolean): void;
|
|
23
41
|
export declare function resetBoundaryCounter(): void;
|
|
24
42
|
interface SuspenseProps {
|
|
@@ -26,6 +44,15 @@ interface SuspenseProps {
|
|
|
26
44
|
children: JSXNode;
|
|
27
45
|
}
|
|
28
46
|
export declare function Suspense(props: SuspenseProps): JSXNode;
|
|
47
|
+
type ClientRender = (component: unknown, props: Record<string, unknown>, childrenHTML: string | null) => string;
|
|
48
|
+
/**
|
|
49
|
+
* clientBoundary wraps an export of a `"use client"` module for the server
|
|
50
|
+
* bundle of a page that renders server components. The server renders the
|
|
51
|
+
* component's initial HTML (render) into a <krate-island> marker carrying its
|
|
52
|
+
* serialized props; the per-module client chunk at src hydrates it in the
|
|
53
|
+
* browser. Children are rendered on the server and passed as HTML.
|
|
54
|
+
*/
|
|
55
|
+
export declare function clientBoundary(moduleId: string, exportName: string, src: string, impl: unknown, render: ClientRender): unknown;
|
|
29
56
|
export declare function Head(props: {
|
|
30
57
|
children?: JSXNode;
|
|
31
58
|
}): JSXNode;
|
|
@@ -59,4 +86,3 @@ export declare function SyntaxHighlight(props: {
|
|
|
59
86
|
lang?: string;
|
|
60
87
|
children?: any;
|
|
61
88
|
}): JSXNode;
|
|
62
|
-
export {};
|
package/dist/server.js
CHANGED
|
@@ -1,5 +1,8 @@
|
|
|
1
1
|
// @krate/runtime/server - Server-side rendering runtime
|
|
2
2
|
// Provides the same API as the client runtime but renders to HTML strings.
|
|
3
|
+
export { getActionContext, headers, cookies, redirect } from './action-context.js';
|
|
4
|
+
export { revalidatePath, revalidateTag, unstable_cache, unstable_noStore } from './cache.js';
|
|
5
|
+
export { getRequestContext, notFound } from './request-context.js';
|
|
3
6
|
// Signal (server: returns initial value, no reactivity)
|
|
4
7
|
export function createSignal(initial) {
|
|
5
8
|
let value = initial;
|
|
@@ -24,6 +27,19 @@ export function createMemo(fn) {
|
|
|
24
27
|
return cached;
|
|
25
28
|
};
|
|
26
29
|
}
|
|
30
|
+
// Derived render values (krateDerived) and custom hook results (krateHook)
|
|
31
|
+
// have no dependencies to track on the server: each read recomputes.
|
|
32
|
+
const derivedGetters = new WeakSet();
|
|
33
|
+
export function krateDerived(fn, _triggers) {
|
|
34
|
+
const read = () => fn();
|
|
35
|
+
derivedGetters.add(read);
|
|
36
|
+
return read;
|
|
37
|
+
}
|
|
38
|
+
export function krateHook(value) {
|
|
39
|
+
if (typeof value === "function" && derivedGetters.has(value))
|
|
40
|
+
return value;
|
|
41
|
+
return () => value;
|
|
42
|
+
}
|
|
27
43
|
export function onCleanup(_fn) {
|
|
28
44
|
// No-op on server
|
|
29
45
|
}
|
|
@@ -90,9 +106,22 @@ function escapeHTML(str) {
|
|
|
90
106
|
.replace(/"/g, """)
|
|
91
107
|
.replace(/'/g, "'");
|
|
92
108
|
}
|
|
109
|
+
function isThenable(v) {
|
|
110
|
+
return v != null && (typeof v === "object" || typeof v === "function") && typeof v.then === "function";
|
|
111
|
+
}
|
|
112
|
+
function componentName(fn) {
|
|
113
|
+
return fn.displayName || fn.name || "anonymous";
|
|
114
|
+
}
|
|
115
|
+
function asyncInSyncRender(where) {
|
|
116
|
+
return new Error(`${where} returned a Promise during a synchronous renderToString. Async server components ` +
|
|
117
|
+
`are rendered per request by the SSR sidecar through renderToStringAsync; a synchronous ` +
|
|
118
|
+
`render (for example inside goComponent children) cannot await them.`);
|
|
119
|
+
}
|
|
93
120
|
function renderNode(node) {
|
|
94
121
|
if (node == null || node === false)
|
|
95
122
|
return "";
|
|
123
|
+
if (isThenable(node))
|
|
124
|
+
throw asyncInSyncRender("A child value");
|
|
96
125
|
if (typeof node === "string")
|
|
97
126
|
return escapeHTML(node);
|
|
98
127
|
if (typeof node === "number")
|
|
@@ -107,11 +136,23 @@ function renderNode(node) {
|
|
|
107
136
|
return renderElement(node);
|
|
108
137
|
return "";
|
|
109
138
|
}
|
|
139
|
+
function isServerAction(v) {
|
|
140
|
+
return typeof v === "function" && typeof v.actionUrl === "string";
|
|
141
|
+
}
|
|
110
142
|
function setAttr(key, val) {
|
|
111
143
|
if (val == null || val === false)
|
|
112
144
|
return "";
|
|
113
145
|
if (val === true)
|
|
114
146
|
return ` ${key}`;
|
|
147
|
+
if (key === "action" && isServerAction(val)) {
|
|
148
|
+
return ` action="${escapeHTML(val.actionUrl)}" data-krate-action`;
|
|
149
|
+
}
|
|
150
|
+
if ((key === "formAction" || key === "formaction") && isServerAction(val)) {
|
|
151
|
+
return ` formaction="${escapeHTML(val.actionUrl)}" formmethod="post" data-krate-action`;
|
|
152
|
+
}
|
|
153
|
+
// Client function actions run only after hydration; they have no HTML form.
|
|
154
|
+
if (typeof val === "function")
|
|
155
|
+
return "";
|
|
115
156
|
if (key === "class")
|
|
116
157
|
return ` class="${escapeHTML(String(val))}"`;
|
|
117
158
|
if (key === "style" && typeof val === "object") {
|
|
@@ -127,16 +168,73 @@ function setAttr(key, val) {
|
|
|
127
168
|
export function renderToString(node) {
|
|
128
169
|
return renderNode(node);
|
|
129
170
|
}
|
|
171
|
+
/**
|
|
172
|
+
* renderToStringAsync renders a tree that may contain async (server)
|
|
173
|
+
* components. Every Promise-returning component is awaited, at any depth, and
|
|
174
|
+
* sibling subtrees resolve in parallel. Errors thrown by a component (or a
|
|
175
|
+
* rejected Promise) reject the returned Promise; nothing renders as "".
|
|
176
|
+
*
|
|
177
|
+
* <Suspense> renders its resolved children: the whole tree is awaited before
|
|
178
|
+
* any HTML is produced, so there is no fallback to show.
|
|
179
|
+
*/
|
|
180
|
+
export async function renderToStringAsync(node) {
|
|
181
|
+
const resolved = await resolveTree(node);
|
|
182
|
+
return renderNode(resolved);
|
|
183
|
+
}
|
|
184
|
+
function isElement(v) {
|
|
185
|
+
return v != null && typeof v === "object" && "type" in v && "props" in v && Array.isArray(v.children);
|
|
186
|
+
}
|
|
187
|
+
function isJSXValue(v) {
|
|
188
|
+
return isElement(v) || isThenable(v) || (Array.isArray(v) && v.some(isJSXValue));
|
|
189
|
+
}
|
|
190
|
+
// resolveTree expands function components top-down into a tree of host
|
|
191
|
+
// elements, raw HTML and primitives, awaiting async components. Built-ins that
|
|
192
|
+
// render their children eagerly (marked __krateEagerChildren, e.g. Link) get
|
|
193
|
+
// their children and JSX-valued props resolved first, so an async component
|
|
194
|
+
// passed as a child still renders.
|
|
195
|
+
async function resolveTree(node) {
|
|
196
|
+
if (isThenable(node))
|
|
197
|
+
return resolveTree(await node);
|
|
198
|
+
if (node == null || typeof node !== "object")
|
|
199
|
+
return node;
|
|
200
|
+
if (Array.isArray(node))
|
|
201
|
+
return Promise.all(node.map(resolveTree));
|
|
202
|
+
if ("__raw" in node)
|
|
203
|
+
return node;
|
|
204
|
+
if (!isElement(node))
|
|
205
|
+
return node;
|
|
206
|
+
const { type, props, children } = node;
|
|
207
|
+
if (typeof type !== "function") {
|
|
208
|
+
return { type, props, children: (await Promise.all(children.map(resolveTree))) };
|
|
209
|
+
}
|
|
210
|
+
const fn = type;
|
|
211
|
+
if (fn.__krateSuspense)
|
|
212
|
+
return resolveTree(children);
|
|
213
|
+
let callProps = { ...props, children };
|
|
214
|
+
if (fn.__krateEagerChildren) {
|
|
215
|
+
const entries = await Promise.all(Object.entries(props).map(async ([k, v]) => [k, isJSXValue(v) ? await resolveTree(v) : v]));
|
|
216
|
+
callProps = { ...Object.fromEntries(entries), children: await resolveTree(children) };
|
|
217
|
+
}
|
|
218
|
+
let out = fn(callProps);
|
|
219
|
+
if (isThenable(out))
|
|
220
|
+
out = await out;
|
|
221
|
+
return resolveTree(out);
|
|
222
|
+
}
|
|
130
223
|
function renderElement(el) {
|
|
131
224
|
const { type, props, children } = el;
|
|
132
225
|
// Component
|
|
133
226
|
if (typeof type === "function") {
|
|
134
227
|
const result = type({ ...props, children });
|
|
228
|
+
if (isThenable(result))
|
|
229
|
+
throw asyncInSyncRender(`<${componentName(type)}>`);
|
|
135
230
|
return renderNode(result);
|
|
136
231
|
}
|
|
137
232
|
// HTML element
|
|
138
233
|
const tag = type;
|
|
139
|
-
const
|
|
234
|
+
const renderProps = tag === "form" && isServerAction(props.action) && props.method == null
|
|
235
|
+
? { ...props, method: "post" }
|
|
236
|
+
: props;
|
|
237
|
+
const attrs = Object.entries(renderProps)
|
|
140
238
|
.map(([k, v]) => setAttr(k, v))
|
|
141
239
|
.join("");
|
|
142
240
|
if (VOID_ELEMENTS.has(tag)) {
|
|
@@ -175,6 +273,93 @@ export function Suspense(props) {
|
|
|
175
273
|
return raw(`<span data-suspense="${id}">${fallback}</span>` +
|
|
176
274
|
`<template data-suspense="${id}">${inner}</template>`);
|
|
177
275
|
}
|
|
276
|
+
Suspense.__krateSuspense = true;
|
|
277
|
+
function describeValue(v) {
|
|
278
|
+
if (typeof v === "function")
|
|
279
|
+
return "a function";
|
|
280
|
+
if (typeof v === "symbol")
|
|
281
|
+
return "a symbol";
|
|
282
|
+
if (typeof v === "bigint")
|
|
283
|
+
return "a bigint";
|
|
284
|
+
if (v && typeof v === "object") {
|
|
285
|
+
const ctor = Object.getPrototypeOf(v)?.constructor?.name;
|
|
286
|
+
return ctor ? `an instance of ${ctor}` : "a non-plain object";
|
|
287
|
+
}
|
|
288
|
+
return typeof v;
|
|
289
|
+
}
|
|
290
|
+
// serializeClientProp converts a prop crossing from the server to a client
|
|
291
|
+
// component into JSON-safe data. Server actions become references the client
|
|
292
|
+
// chunk turns back into callable proxies; anything else that JSON cannot carry
|
|
293
|
+
// faithfully throws with the offending prop path.
|
|
294
|
+
function serializeClientProp(v, path, component) {
|
|
295
|
+
if (v === null || typeof v === "string" || typeof v === "boolean")
|
|
296
|
+
return v;
|
|
297
|
+
if (typeof v === "number") {
|
|
298
|
+
if (!Number.isFinite(v))
|
|
299
|
+
throw clientPropError(path, component, `the number ${v}`);
|
|
300
|
+
return v;
|
|
301
|
+
}
|
|
302
|
+
if (v === undefined)
|
|
303
|
+
return undefined;
|
|
304
|
+
if (isServerAction(v))
|
|
305
|
+
return { __krateAction: v.actionUrl };
|
|
306
|
+
if (Array.isArray(v))
|
|
307
|
+
return v.map((x, i) => serializeClientProp(x, `${path}[${i}]`, component));
|
|
308
|
+
if (typeof v === "object") {
|
|
309
|
+
if (isElement(v) || "__raw" in v) {
|
|
310
|
+
throw clientPropError(path, component, "JSX", "only `children` can carry server-rendered JSX into a client component");
|
|
311
|
+
}
|
|
312
|
+
const proto = Object.getPrototypeOf(v);
|
|
313
|
+
if (proto !== Object.prototype && proto !== null)
|
|
314
|
+
throw clientPropError(path, component, describeValue(v));
|
|
315
|
+
const out = {};
|
|
316
|
+
for (const [k, x] of Object.entries(v)) {
|
|
317
|
+
const sv = serializeClientProp(x, `${path}.${k}`, component);
|
|
318
|
+
if (sv !== undefined)
|
|
319
|
+
out[k] = sv;
|
|
320
|
+
}
|
|
321
|
+
return out;
|
|
322
|
+
}
|
|
323
|
+
throw clientPropError(path, component, describeValue(v));
|
|
324
|
+
}
|
|
325
|
+
function clientPropError(path, component, what, hint) {
|
|
326
|
+
return new Error(`Prop \`${path}\` passed to client component <${component}> is ${what}, which cannot be sent from a server ` +
|
|
327
|
+
`component to the client. ` +
|
|
328
|
+
(hint || "Pass JSON-serializable data (strings, numbers, booleans, null, plain objects, arrays) or a server action; " +
|
|
329
|
+
"move event handlers and class instances into the client component."));
|
|
330
|
+
}
|
|
331
|
+
/**
|
|
332
|
+
* clientBoundary wraps an export of a `"use client"` module for the server
|
|
333
|
+
* bundle of a page that renders server components. The server renders the
|
|
334
|
+
* component's initial HTML (render) into a <krate-island> marker carrying its
|
|
335
|
+
* serialized props; the per-module client chunk at src hydrates it in the
|
|
336
|
+
* browser. Children are rendered on the server and passed as HTML.
|
|
337
|
+
*/
|
|
338
|
+
export function clientBoundary(moduleId, exportName, src, impl, render) {
|
|
339
|
+
if (typeof impl !== "function")
|
|
340
|
+
return impl;
|
|
341
|
+
const name = impl.displayName || impl.name || exportName;
|
|
342
|
+
const Boundary = async (props) => {
|
|
343
|
+
const { children, ...rest } = props || {};
|
|
344
|
+
const data = {};
|
|
345
|
+
for (const [k, v] of Object.entries(rest)) {
|
|
346
|
+
if (k === "key")
|
|
347
|
+
continue;
|
|
348
|
+
const sv = serializeClientProp(v, k, name);
|
|
349
|
+
if (sv !== undefined)
|
|
350
|
+
data[k] = sv;
|
|
351
|
+
}
|
|
352
|
+
const hasChildren = children != null && !(Array.isArray(children) && children.length === 0);
|
|
353
|
+
const childrenHTML = hasChildren ? await renderToStringAsync(children) : null;
|
|
354
|
+
if (childrenHTML !== null)
|
|
355
|
+
data.__krateChildren = childrenHTML;
|
|
356
|
+
const html = render(impl, data, childrenHTML);
|
|
357
|
+
return raw(`<krate-island style="display:contents" data-module="${escapeHTML(moduleId)}" data-export="${escapeHTML(exportName)}" ` +
|
|
358
|
+
`data-src="${escapeHTML(src)}" data-props="${escapeHTML(JSON.stringify(data))}">${html}</krate-island>`);
|
|
359
|
+
};
|
|
360
|
+
Object.defineProperty(Boundary, "name", { value: name });
|
|
361
|
+
return Boundary;
|
|
362
|
+
}
|
|
178
363
|
// Built-in Components (server stubs)
|
|
179
364
|
// Head - renders children into the page head at build time.
|
|
180
365
|
// On the server, we just render children; the build pipeline extracts them.
|
|
@@ -226,6 +411,7 @@ export function Link(props) {
|
|
|
226
411
|
const inner = children != null ? renderNode(children) : "";
|
|
227
412
|
return raw(`<a ${attrs.join(" ")}>${inner}</a>`);
|
|
228
413
|
}
|
|
414
|
+
Link.__krateEagerChildren = true;
|
|
229
415
|
// Image - renders an <img> tag (server stub; Go compiler handles full responsive output at build time).
|
|
230
416
|
export function Image(props) {
|
|
231
417
|
const { src = "", alt = "", width, height, ...rest } = props;
|
package/dist/server.test.js
CHANGED
|
@@ -46,3 +46,23 @@ describe('goComponent', () => {
|
|
|
46
46
|
expect(renderToString(node)).toMatch(/^<!--krate-go:Badge:0:/);
|
|
47
47
|
});
|
|
48
48
|
});
|
|
49
|
+
describe('server actions', () => {
|
|
50
|
+
it('renders an action function as a POST form endpoint', () => {
|
|
51
|
+
const action = Object.assign(() => undefined, {
|
|
52
|
+
actionUrl: '/base/__krate/action/a123',
|
|
53
|
+
});
|
|
54
|
+
const html = renderToString(jsx('form', { action, children: [] }));
|
|
55
|
+
expect(html).toContain('action="/base/__krate/action/a123"');
|
|
56
|
+
expect(html).toContain('method="post"');
|
|
57
|
+
expect(html).toContain('data-krate-action');
|
|
58
|
+
});
|
|
59
|
+
it('renders a formAction function as a POST submit endpoint', () => {
|
|
60
|
+
const action = Object.assign(() => undefined, {
|
|
61
|
+
actionUrl: '/__krate/action/a456',
|
|
62
|
+
});
|
|
63
|
+
const html = renderToString(jsx('button', { formAction: action, children: 'go' }));
|
|
64
|
+
expect(html).toContain('formaction="/__krate/action/a456"');
|
|
65
|
+
expect(html).toContain('formmethod="post"');
|
|
66
|
+
expect(html).toContain('data-krate-action');
|
|
67
|
+
});
|
|
68
|
+
});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,32 @@
|
|
|
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
|
+
});
|
package/dist/signal.d.ts
CHANGED
|
@@ -6,7 +6,144 @@ export interface SignalOptions<T> {
|
|
|
6
6
|
* the key, store (local/session/memory), serialization, and cross-tab sync.
|
|
7
7
|
*/
|
|
8
8
|
persist?: PersistSpec<T>;
|
|
9
|
+
/**
|
|
10
|
+
* React state semantics (set by the compiler for useState/useReducer).
|
|
11
|
+
* Outside Krate's render phase (event handlers, effect bodies, cleanups)
|
|
12
|
+
* the getter returns the value of the last commit, so a handler sees its
|
|
13
|
+
* render's snapshot and a cleanup sees the render its effect ran for.
|
|
14
|
+
* Writes still apply immediately to functional updaters, and an update made
|
|
15
|
+
* outside a discrete event commits in a later task, as React schedules it.
|
|
16
|
+
*/
|
|
17
|
+
react?: boolean;
|
|
18
|
+
}
|
|
19
|
+
/** Signal options that give a signal React state semantics. */
|
|
20
|
+
export declare const krateHookState: {
|
|
21
|
+
readonly react: true;
|
|
22
|
+
};
|
|
23
|
+
/**
|
|
24
|
+
* Owner integration (installed by boundary.ts). An owner is the component
|
|
25
|
+
* instance that is current while code runs; effects, cleanups and mount
|
|
26
|
+
* callbacks created under it are tied to it, and errors they throw are routed
|
|
27
|
+
* to it (error boundaries, Suspense). With no hooks installed every code path
|
|
28
|
+
* below behaves exactly as before.
|
|
29
|
+
*/
|
|
30
|
+
export interface OwnerHooks {
|
|
31
|
+
/** The owner active right now, or null. */
|
|
32
|
+
current(): unknown;
|
|
33
|
+
/** Runs fn with owner current, routing anything it throws. */
|
|
34
|
+
run(owner: unknown, fn: () => void): void;
|
|
35
|
+
/** Registers fn to run when owner is unmounted. */
|
|
36
|
+
cleanup(owner: unknown, fn: () => void): void;
|
|
37
|
+
/** Routes an error thrown by owner's code; true when handled. */
|
|
38
|
+
error(owner: unknown, err: unknown): boolean;
|
|
9
39
|
}
|
|
40
|
+
/** Installs (or with null removes) the owner integration hooks. */
|
|
41
|
+
export declare function setOwnerHooks(hooks: OwnerHooks | null): void;
|
|
42
|
+
/**
|
|
43
|
+
* Enters the route scope `id` for the hydration code that follows. Returns
|
|
44
|
+
* false when the SPA router kept that layout mounted: its bindings and
|
|
45
|
+
* effects are still live and must not be created twice.
|
|
46
|
+
*/
|
|
47
|
+
export declare function krateEnterScope(id: string): boolean;
|
|
48
|
+
/** Leaves the current route scope (see krateEnterScope). */
|
|
49
|
+
export declare function krateLeaveScope(): void;
|
|
50
|
+
/**
|
|
51
|
+
* The route scope new effects and owners are tagged with (internal): the
|
|
52
|
+
* running effect's scope, else the scope whose hydration code is running,
|
|
53
|
+
* else the current component owner's scope (code running later, e.g. an
|
|
54
|
+
* event handler of a layout component).
|
|
55
|
+
*/
|
|
56
|
+
export declare function krateCurrentScope(): string | null;
|
|
57
|
+
/** Sets the layout scopes the router kept mounted for the next hydration (internal). */
|
|
58
|
+
export declare function krateKeepScopes(ids: string[]): void;
|
|
59
|
+
/** Records the route scope of an owner key (internal; see effects.ts). */
|
|
60
|
+
export declare function krateTagOwner(owner: unknown, scope: string | null): void;
|
|
61
|
+
/**
|
|
62
|
+
* Disposes every effect created under `owner` and runs its top-level
|
|
63
|
+
* onCleanup callbacks (internal, used when a component unmounts).
|
|
64
|
+
*/
|
|
65
|
+
export declare function krateDisposeOwner(owner: unknown): void;
|
|
66
|
+
/**
|
|
67
|
+
* Runs fn as render work: React state reads see the latest values rather than
|
|
68
|
+
* the last commit's (internal; the class component render phase).
|
|
69
|
+
*/
|
|
70
|
+
export declare function krateRenderPhase<T>(fn: () => T): T;
|
|
71
|
+
/** Records the current React state values as commit `epoch` (internal). */
|
|
72
|
+
export declare function krateCommitSnapshot(): number;
|
|
73
|
+
/** The epoch of the last commit snapshot (internal). */
|
|
74
|
+
export declare function krateEpoch(): number;
|
|
75
|
+
/** Runs fn reading React state as of commit `at` (internal). */
|
|
76
|
+
export declare function krateReadAt<T>(at: number | null, fn: () => T): T;
|
|
77
|
+
/** Drops snapshot history older than commit `min` (internal). */
|
|
78
|
+
export declare function kratePruneSnapshots(min: number): void;
|
|
79
|
+
/**
|
|
80
|
+
* Runs fn with its signal writes in the transition lane: they commit in a
|
|
81
|
+
* later task, like React's transition and default updates, even for plain
|
|
82
|
+
* signals. Used for the updates an async action makes when it settles
|
|
83
|
+
* (pending flags, results), so the pending render stays on screen for at
|
|
84
|
+
* least one task, as it does in React.
|
|
85
|
+
*/
|
|
86
|
+
export declare function krateTransitionWrites<T>(fn: () => T): T;
|
|
87
|
+
/** Reports whether a native event type is discrete (React's SyncLane). */
|
|
88
|
+
export declare function krateIsDiscrete(type: string): boolean;
|
|
89
|
+
/**
|
|
90
|
+
* Runs the handlers of one native event dispatch. For a discrete event
|
|
91
|
+
* (click, input, keydown, submit, change, focus, ...) the updates they made
|
|
92
|
+
* are flushed synchronously when `flush` is set, as React does at the end of
|
|
93
|
+
* a discrete event: render, commit, layout and passive effects all run before
|
|
94
|
+
* the browser event returns. Continuous events keep the normal batching.
|
|
95
|
+
*/
|
|
96
|
+
export declare function krateRunEvent(type: string, flush: boolean, fn: () => void): void;
|
|
97
|
+
/** Marks a commit in progress (internal): writes there flush in a microtask. */
|
|
98
|
+
export declare function krateCommitting(on: boolean): void;
|
|
99
|
+
/** Reports and clears whether the pending commit came from a discrete event. */
|
|
100
|
+
export declare function krateTakeSyncLane(): boolean;
|
|
101
|
+
/** Returns the current component owner (internal, used by effects.ts). */
|
|
102
|
+
export declare function krateGetOwner(): unknown;
|
|
103
|
+
/** Sets the current component owner and returns the previous one (internal). */
|
|
104
|
+
export declare function krateSetOwner(owner: unknown): unknown;
|
|
105
|
+
/** Registers fn to run before every effect flush starts (internal). */
|
|
106
|
+
export declare function krateOnBeforeFlush(fn: () => void): void;
|
|
107
|
+
/** Registers fn to run after every settled effect flush (internal). */
|
|
108
|
+
export declare function krateOnAfterFlush(fn: () => void): void;
|
|
109
|
+
/**
|
|
110
|
+
* Registers fn to run at the start of disposeAll (internal). For a partial
|
|
111
|
+
* teardown (krateDisposeExcept / krateDisposeScopes) `gone` reports which
|
|
112
|
+
* route scopes are torn down; it is null for a full teardown.
|
|
113
|
+
*/
|
|
114
|
+
export declare function krateOnDispose(fn: (gone: ((scope: string | null) => boolean) | null) => void): void;
|
|
115
|
+
/** Reports whether signal writes are waiting for the next flush. */
|
|
116
|
+
export declare function kratePendingFlush(): boolean;
|
|
117
|
+
/**
|
|
118
|
+
* Runs fn without subscribing the surrounding effect to the signals it reads.
|
|
119
|
+
*/
|
|
120
|
+
export declare function untrack<T>(fn: () => T): T;
|
|
121
|
+
/**
|
|
122
|
+
* Runs fn once after the pending effect queue has fully drained (including
|
|
123
|
+
* effects scheduled while it drained) and the after-flush hooks ran, so the
|
|
124
|
+
* DOM reflects every write made so far. Schedules a flush when none is
|
|
125
|
+
* pending. Used by the class component commit phase.
|
|
126
|
+
*/
|
|
127
|
+
export declare function afterFlush(fn: () => void): void;
|
|
128
|
+
/**
|
|
129
|
+
* Same-value equality used for every React-facing comparison (state
|
|
130
|
+
* bail-out, dependency arrays): Object.is, so NaN equals NaN and +0 differs
|
|
131
|
+
* from -0.
|
|
132
|
+
*/
|
|
133
|
+
export declare function sameValue(a: unknown, b: unknown): boolean;
|
|
134
|
+
/**
|
|
135
|
+
* Partial teardown for a soft navigation that keeps some layouts mounted:
|
|
136
|
+
* disposes every effect, cleanup and component owner whose route scope is
|
|
137
|
+
* not in `keep`. With an empty `keep` this is disposeAll().
|
|
138
|
+
*/
|
|
139
|
+
export declare function krateDisposeExcept(keep: string[]): void;
|
|
140
|
+
/**
|
|
141
|
+
* Disposes only the effects, cleanups and component owners of the given
|
|
142
|
+
* route scopes (a parallel-route slot whose content is replaced).
|
|
143
|
+
*/
|
|
144
|
+
export declare function krateDisposeScopes(ids: string[]): void;
|
|
145
|
+
/** The route scope encoded in a layout/slot id ("_lHASH_x" -> "_lHASH_"), else null. */
|
|
146
|
+
export declare function krateScopeOfId(id: string): string | null;
|
|
10
147
|
export declare function disposeAll(): void;
|
|
11
148
|
/** ARIA role presets and raw overrides accepted by every CSS primitive. */
|
|
12
149
|
export interface CSSARIAOptions {
|
|
@@ -141,8 +278,56 @@ export declare function createCSSStack<K extends string>(_nodes: readonly K[], _
|
|
|
141
278
|
peek: () => K;
|
|
142
279
|
}, CSSStackActions<K>];
|
|
143
280
|
export declare function createSignal<T>(initial: T, options?: SignalOptions<T>): [() => T, (next: T | ((prev: T) => T)) => void];
|
|
281
|
+
/**
|
|
282
|
+
* A lazily evaluated derived value: the compile target of a React render-body
|
|
283
|
+
* value (`const total = rows.reduce(...)`). The getter recomputes on read when
|
|
284
|
+
* a signal (or another derived value) it read last time has changed since, so
|
|
285
|
+
* every reader in a flush sees the same current value. Nothing is computed
|
|
286
|
+
* until the first read, and a write only marks it stale. triggers, when
|
|
287
|
+
* given, is read for its subscriptions only: an object or array literal built
|
|
288
|
+
* in render gets a new identity whenever the component would re-render.
|
|
289
|
+
*/
|
|
290
|
+
export declare function krateDerived<T>(fn: () => T, triggers?: () => unknown): () => T;
|
|
291
|
+
/** Reports whether fn is a getter returned by krateDerived. */
|
|
292
|
+
export declare function isDerivedGetter(fn: unknown): boolean;
|
|
293
|
+
/**
|
|
294
|
+
* Normalizes a custom hook's return value to a getter. A hook compiled from
|
|
295
|
+
* React source returns a derived getter for a render-dependent result; any
|
|
296
|
+
* other value (a hook from a plain module, a constant) is wrapped so the call
|
|
297
|
+
* site can read every hook result the same way.
|
|
298
|
+
*/
|
|
299
|
+
export declare function krateHook<T>(value: T | (() => T)): () => T;
|
|
300
|
+
/** Reports whether fn is a getter returned by createSignal. */
|
|
301
|
+
export declare function isSignalGetter(fn: unknown): boolean;
|
|
302
|
+
/**
|
|
303
|
+
* Registers fn to run when a flush has no pending effects, before the
|
|
304
|
+
* after-flush hooks. Signal writes it makes are flushed first (internal).
|
|
305
|
+
*/
|
|
306
|
+
export declare function krateOnSettle(fn: () => void): void;
|
|
307
|
+
/** Ensures a flush runs soon even when no signal was written (internal). */
|
|
308
|
+
export declare function krateRequestFlush(): void;
|
|
309
|
+
/**
|
|
310
|
+
* Runs the after-flush hooks now. Used when no signal flush is pending (for
|
|
311
|
+
* example, right after hydration registered effects).
|
|
312
|
+
*/
|
|
313
|
+
export declare function runAfterFlush(): void;
|
|
314
|
+
/**
|
|
315
|
+
* Synchronously flushes pending signal effects and the commit that follows
|
|
316
|
+
* them (the building block for flushSync and tests).
|
|
317
|
+
*/
|
|
318
|
+
export declare function krateFlushSync(): void;
|
|
144
319
|
export declare function createEffect(fn: () => void): () => void;
|
|
145
320
|
export declare function onCleanup(fn: () => void): void;
|
|
321
|
+
/**
|
|
322
|
+
* Run `fn` in a new ownership root. Effects, memos, onCleanup callbacks and
|
|
323
|
+
* onMount callbacks registered while it runs (and the cleanups those mount
|
|
324
|
+
* callbacks register) belong to the root and are torn down, in registration
|
|
325
|
+
* order, when the returned `dispose` is called. Signal reads inside `fn` are
|
|
326
|
+
* not tracked by any enclosing effect. Keyed list rows and keyed remounts use
|
|
327
|
+
* one root per row so a removed row runs its cleanups without touching its
|
|
328
|
+
* siblings.
|
|
329
|
+
*/
|
|
330
|
+
export declare function createRoot<T>(fn: (dispose: () => void) => T): T;
|
|
146
331
|
export declare function onMount(fn: () => void): void;
|
|
147
332
|
export declare function createMemo<T>(fn: () => T): () => T;
|
|
148
333
|
/**
|
|
@@ -152,7 +337,7 @@ export declare function createMemo<T>(fn: () => T): () => T;
|
|
|
152
337
|
* other signal. Used both directly and as the lowering target for React's
|
|
153
338
|
* `useReducer`.
|
|
154
339
|
*/
|
|
155
|
-
export declare function createReducer<S, A>(reducer: (state: S, action: A) => S, initial: S): [() => S, (action: A) => void];
|
|
340
|
+
export declare function createReducer<S, A, I = S>(reducer: (state: S, action: A) => S, initial: I, init?: ((arg: I) => S) | SignalOptions<S> | null, options?: SignalOptions<S>): [() => S, (action: A) => void];
|
|
156
341
|
/** A mutable ref object. `current` starts as `initial` and is assigned the
|
|
157
342
|
* DOM element when passed as `ref={refObj}` on an element. */
|
|
158
343
|
export interface RefObject<T> {
|