@krate/runtime 0.5.0-rc.4 → 0.5.0-rc.6
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/actions.js +10 -1
- package/dist/cache-scope.d.ts +6 -0
- package/dist/cache-scope.js +14 -1
- package/dist/context.d.ts +5 -0
- package/dist/context.js +28 -17
- package/dist/flight-props.d.ts +7 -0
- package/dist/flight-props.js +105 -0
- package/dist/hints.d.ts +25 -2
- package/dist/hints.js +148 -74
- package/dist/index.d.ts +1 -0
- package/dist/krate-core.js +1 -1
- package/dist/krate-f-actions.js +1 -1
- package/dist/krate-f-list.js +1 -1
- package/dist/krate-f-navigation.js +1 -1
- package/dist/krate-f-router.js +1 -1
- package/dist/krate-features.json +24 -0
- package/dist/krate-hydrate-lite.js +5 -5
- package/dist/krate-hydrate.js +5 -5
- package/dist/krate-runtime.js +5 -5
- package/dist/list.d.ts +14 -4
- package/dist/list.js +4 -5
- package/dist/navigation-react.d.ts +13 -0
- package/dist/navigation-react.js +86 -0
- package/dist/navigation.d.ts +19 -0
- package/dist/navigation.js +35 -0
- package/dist/react-compat.d.ts +26 -0
- package/dist/react-compat.js +292 -0
- package/dist/react-server.d.ts +63 -0
- package/dist/react-server.js +125 -0
- package/dist/router.js +9 -0
- package/dist/server-handler.js +89 -10
- package/dist/server.d.ts +57 -10
- package/dist/server.js +455 -94
- package/dist/ssr-core.d.ts +2 -0
- package/dist/ssr-core.js +8 -0
- package/package.json +19 -2
- package/dist/actions.test.d.ts +0 -1
- package/dist/actions.test.js +0 -75
- package/dist/after.test.d.ts +0 -1
- package/dist/after.test.js +0 -58
- package/dist/builtin-tags.test.d.ts +0 -1
- package/dist/builtin-tags.test.js +0 -12
- package/dist/cache-adapter.test.d.ts +0 -1
- package/dist/cache-adapter.test.js +0 -45
- package/dist/cache.test.d.ts +0 -1
- package/dist/cache.test.js +0 -37
- package/dist/events.test.d.ts +0 -1
- package/dist/events.test.js +0 -42
- package/dist/handler-html.test.d.ts +0 -1
- package/dist/handler-html.test.js +0 -55
- package/dist/handler-segments.test.d.ts +0 -1
- package/dist/handler-segments.test.js +0 -25
- package/dist/head-tags.test.d.ts +0 -1
- package/dist/head-tags.test.js +0 -24
- package/dist/inline-action-token.test.d.ts +0 -1
- package/dist/inline-action-token.test.js +0 -31
- package/dist/jsx-svg-types.test.d.ts +0 -1
- package/dist/jsx-svg-types.test.js +0 -58
- package/dist/link-base-path.test.d.ts +0 -1
- package/dist/link-base-path.test.js +0 -28
- package/dist/node-server.test.d.ts +0 -1
- package/dist/node-server.test.js +0 -138
- package/dist/platform.test.d.ts +0 -1
- package/dist/platform.test.js +0 -44
- package/dist/router-nav.test.d.ts +0 -1
- package/dist/router-nav.test.js +0 -130
- package/dist/server-handler.test.d.ts +0 -1
- package/dist/server-handler.test.js +0 -247
- package/dist/server-renderer.test.d.ts +0 -1
- package/dist/server-renderer.test.js +0 -162
- package/dist/server.test.d.ts +0 -1
- package/dist/server.test.js +0 -80
- package/dist/sha256.test.d.ts +0 -1
- package/dist/sha256.test.js +0 -13
- package/dist/signal.test.d.ts +0 -1
- package/dist/signal.test.js +0 -68
- package/dist/site-config.test.d.ts +0 -1
- package/dist/site-config.test.js +0 -30
- package/dist/slot.test.d.ts +0 -1
- package/dist/slot.test.js +0 -25
- package/dist/ssr-core-behavior.test.d.ts +0 -1
- package/dist/ssr-core-behavior.test.js +0 -108
- package/dist/testing.test.d.ts +0 -1
- package/dist/testing.test.js +0 -73
package/dist/server.js
CHANGED
|
@@ -3,6 +3,10 @@
|
|
|
3
3
|
import { ATTR_ALIASES } from './htmlspec-attributes.js';
|
|
4
4
|
import { withBase } from './base-path.js';
|
|
5
5
|
import { highlight as highlightCode, trimSpace } from './highlight.js';
|
|
6
|
+
import { accessDeniedStatus, isNotFoundSignal, redirectTarget } from './request-context.js';
|
|
7
|
+
import { sha256Hex } from './sha256.js';
|
|
8
|
+
import { markErrorCaught } from './cache-scope.js';
|
|
9
|
+
import { encodeProp } from './flight-props.js';
|
|
6
10
|
export { getActionContext, headers, cookies, redirect } from './action-context.js';
|
|
7
11
|
export { revalidatePath, revalidateTag, unstable_cache, unstable_noStore } from './cache.js';
|
|
8
12
|
export { after } from './after.js';
|
|
@@ -133,6 +137,164 @@ function asyncInSyncRender(where) {
|
|
|
133
137
|
function isClassComponent(fn) {
|
|
134
138
|
return typeof fn === "function" && fn.prototype && typeof fn.prototype.render === "function";
|
|
135
139
|
}
|
|
140
|
+
// React element types that are objects or symbols rather than functions. A
|
|
141
|
+
// package compiled for React (Radix's Slot is a forwardRef) hands these to a
|
|
142
|
+
// dynamic tag (`const Comp = asChild ? Slot.Root : "button"`), so the server
|
|
143
|
+
// renderer must run them as components instead of printing them as a tag name.
|
|
144
|
+
const R_ELEMENT = [Symbol.for("react.element"), Symbol.for("react.transitional.element")];
|
|
145
|
+
const R_FORWARD_REF = Symbol.for("react.forward_ref");
|
|
146
|
+
const R_MEMO = Symbol.for("react.memo");
|
|
147
|
+
const R_LAZY = Symbol.for("react.lazy");
|
|
148
|
+
const R_PROVIDER = Symbol.for("react.provider");
|
|
149
|
+
const R_CONTEXT = Symbol.for("react.context");
|
|
150
|
+
const R_CONSUMER = Symbol.for("react.consumer");
|
|
151
|
+
const R_FRAGMENT = Symbol.for("react.fragment");
|
|
152
|
+
const R_SUSPENSE = Symbol.for("react.suspense");
|
|
153
|
+
const exoticCache = new WeakMap();
|
|
154
|
+
function describeType(type) {
|
|
155
|
+
if (typeof type === "symbol")
|
|
156
|
+
return type.toString();
|
|
157
|
+
if (type && typeof type === "object") {
|
|
158
|
+
const t = type;
|
|
159
|
+
const tag = typeof t.$$typeof === "symbol" ? t.$$typeof.toString() : undefined;
|
|
160
|
+
return tag ? `an object (${tag})` : "an object";
|
|
161
|
+
}
|
|
162
|
+
return String(type);
|
|
163
|
+
}
|
|
164
|
+
function notRenderable(type) {
|
|
165
|
+
return new Error(`Cannot render an element whose type is ${describeType(type)}. A server render can run strings, ` +
|
|
166
|
+
`function and class components, and React forwardRef, memo, lazy and context types; ` +
|
|
167
|
+
`pass a component or an HTML tag name instead.`);
|
|
168
|
+
}
|
|
169
|
+
// isSlotType reports Radix's Slot (createSlot names it `<owner>.Slot`). Its
|
|
170
|
+
// own render clones React elements and cannot work on Krate's, so the server
|
|
171
|
+
// uses ServerSlot for it.
|
|
172
|
+
function isSlotType(type) {
|
|
173
|
+
return typeof type.displayName === "string" && /(^|\.)Slot$/.test(type.displayName);
|
|
174
|
+
}
|
|
175
|
+
function childElements(children) {
|
|
176
|
+
return children.filter((c) => c != null && c !== false && !(typeof c === "string" && c.trim() === ""));
|
|
177
|
+
}
|
|
178
|
+
function mergeSlotProps(slot, child) {
|
|
179
|
+
const out = { ...slot, ...child };
|
|
180
|
+
for (const key of Object.keys(child)) {
|
|
181
|
+
const sv = slot[key];
|
|
182
|
+
const cv = child[key];
|
|
183
|
+
if (/^on[A-Z]/.test(key) && typeof sv === "function" && typeof cv === "function") {
|
|
184
|
+
out[key] = (...args) => {
|
|
185
|
+
cv(...args);
|
|
186
|
+
sv(...args);
|
|
187
|
+
};
|
|
188
|
+
}
|
|
189
|
+
else if (key === "style" && sv && cv && typeof sv === "object" && typeof cv === "object") {
|
|
190
|
+
out[key] = { ...sv, ...cv };
|
|
191
|
+
}
|
|
192
|
+
else if ((key === "className" || key === "class") && sv && cv) {
|
|
193
|
+
out[key] = `${sv} ${cv}`;
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
return out;
|
|
197
|
+
}
|
|
198
|
+
// ServerSlot is Radix's Slot for the server: it renders its single child
|
|
199
|
+
// element with the Slot's own props merged onto it (the child wins, class
|
|
200
|
+
// names join, handlers compose).
|
|
201
|
+
function ServerSlot(allProps) {
|
|
202
|
+
const { children, ref: _ref, ...slotProps } = allProps;
|
|
203
|
+
const kids = childElements(Array.isArray(children) ? children.flat(Infinity) : children == null ? [] : [children]);
|
|
204
|
+
const child = kids.length === 1 ? normalizeNode(kids[0]) : undefined;
|
|
205
|
+
if (!isElement(child))
|
|
206
|
+
return kids;
|
|
207
|
+
return { type: child.type, props: mergeSlotProps(slotProps, child.props), children: child.children };
|
|
208
|
+
}
|
|
209
|
+
// toReactElement converts a React element object (made by a package's own
|
|
210
|
+
// React) into Krate's element shape.
|
|
211
|
+
function isReactElement(v) {
|
|
212
|
+
return v != null && typeof v === "object" && R_ELEMENT.includes(v.$$typeof);
|
|
213
|
+
}
|
|
214
|
+
function normalizeNode(node) {
|
|
215
|
+
if (!isReactElement(node))
|
|
216
|
+
return node;
|
|
217
|
+
const { children, ref: _ref, ...rest } = node.props ?? {};
|
|
218
|
+
const kids = Array.isArray(children) ? children.flat(Infinity) : children != null ? [children] : [];
|
|
219
|
+
return { type: node.type, props: rest, children: kids };
|
|
220
|
+
}
|
|
221
|
+
function foreignContext(type) {
|
|
222
|
+
if (type.$$typeof === R_PROVIDER)
|
|
223
|
+
return { ctx: type._context, provider: true };
|
|
224
|
+
if (type.$$typeof === R_CONSUMER)
|
|
225
|
+
return { ctx: type._context, provider: false };
|
|
226
|
+
if (type._context)
|
|
227
|
+
return { ctx: type._context, provider: false };
|
|
228
|
+
return { ctx: type, provider: type.Provider === type };
|
|
229
|
+
}
|
|
230
|
+
// withContextValue renders under a foreign Provider: consumers below read the
|
|
231
|
+
// value while its children are resolved.
|
|
232
|
+
function scopedContextFn(ctx, provider) {
|
|
233
|
+
if (provider) {
|
|
234
|
+
const Provider = (props) => props.children;
|
|
235
|
+
Provider.__krateForeignProvider = ctx;
|
|
236
|
+
return Provider;
|
|
237
|
+
}
|
|
238
|
+
const Consumer = (props) => consumerChild(props)(ctx._currentValue);
|
|
239
|
+
Consumer.__krateForeignConsumer = ctx;
|
|
240
|
+
return Consumer;
|
|
241
|
+
}
|
|
242
|
+
function consumerChild(props) {
|
|
243
|
+
const render = Array.isArray(props.children) && props.children.length === 1 ? props.children[0] : props.children;
|
|
244
|
+
if (typeof render !== "function")
|
|
245
|
+
throw new Error("A context Consumer needs a function as its child.");
|
|
246
|
+
return render;
|
|
247
|
+
}
|
|
248
|
+
// exoticType resolves a non-string, non-function element type to something
|
|
249
|
+
// the renderer can run. A pending React.lazy throws its promise.
|
|
250
|
+
function exoticType(type) {
|
|
251
|
+
if (typeof type === "string" || typeof type === "function")
|
|
252
|
+
return type;
|
|
253
|
+
if (type === R_FRAGMENT || type === R_SUSPENSE)
|
|
254
|
+
return Fragment;
|
|
255
|
+
if (type == null || typeof type !== "object")
|
|
256
|
+
throw notRenderable(type);
|
|
257
|
+
switch (type.$$typeof) {
|
|
258
|
+
case R_MEMO:
|
|
259
|
+
return exoticType(type.type);
|
|
260
|
+
case R_LAZY:
|
|
261
|
+
return exoticType(type._init(type._payload));
|
|
262
|
+
case R_FORWARD_REF: {
|
|
263
|
+
let fn = exoticCache.get(type);
|
|
264
|
+
if (!fn) {
|
|
265
|
+
fn = isSlotType(type) ? ServerSlot : (props) => type.render(props, props.ref ?? null);
|
|
266
|
+
exoticCache.set(type, fn);
|
|
267
|
+
}
|
|
268
|
+
return fn;
|
|
269
|
+
}
|
|
270
|
+
case R_PROVIDER:
|
|
271
|
+
case R_CONSUMER:
|
|
272
|
+
case R_CONTEXT: {
|
|
273
|
+
let fn = exoticCache.get(type);
|
|
274
|
+
if (!fn) {
|
|
275
|
+
const { ctx, provider } = foreignContext(type);
|
|
276
|
+
fn = scopedContextFn(ctx, provider);
|
|
277
|
+
exoticCache.set(type, fn);
|
|
278
|
+
}
|
|
279
|
+
return fn;
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
throw notRenderable(type);
|
|
283
|
+
}
|
|
284
|
+
// runForeignProvider evaluates `run` with a foreign Provider's value in place.
|
|
285
|
+
function withProviderValue(fn, props, run) {
|
|
286
|
+
const ctx = fn.__krateForeignProvider;
|
|
287
|
+
if (!ctx)
|
|
288
|
+
return run();
|
|
289
|
+
const prev = ctx._currentValue;
|
|
290
|
+
ctx._currentValue = props.value;
|
|
291
|
+
try {
|
|
292
|
+
return run();
|
|
293
|
+
}
|
|
294
|
+
finally {
|
|
295
|
+
ctx._currentValue = prev;
|
|
296
|
+
}
|
|
297
|
+
}
|
|
136
298
|
function classFallback(type, instance, error) {
|
|
137
299
|
if (typeof type.getDerivedStateFromError !== "function")
|
|
138
300
|
throw error;
|
|
@@ -146,6 +308,41 @@ function classFallback(type, instance, error) {
|
|
|
146
308
|
}
|
|
147
309
|
return instance.render();
|
|
148
310
|
}
|
|
311
|
+
/**
|
|
312
|
+
* ServerErrorBoundary is the request-time form of a segment's error.tsx under
|
|
313
|
+
* an async layout: it renders `children`, and when rendering them throws it
|
|
314
|
+
* renders `<fallback error={{ name, message, digest }} />` in their place.
|
|
315
|
+
* notFound(), forbidden(), unauthorized() and redirect() signals pass through.
|
|
316
|
+
* The visitor sees a generic message and a digest; the real error is logged
|
|
317
|
+
* with the same digest. The render's scope records the catch, so the host
|
|
318
|
+
* answers 500 with no-store instead of a cacheable 200.
|
|
319
|
+
*/
|
|
320
|
+
export class ServerErrorBoundary {
|
|
321
|
+
constructor(props) {
|
|
322
|
+
this.state = { error: undefined };
|
|
323
|
+
this.props = props;
|
|
324
|
+
}
|
|
325
|
+
static getDerivedStateFromError(error) {
|
|
326
|
+
if (isNotFoundSignal(error) || accessDeniedStatus(error) || redirectTarget(error))
|
|
327
|
+
throw error;
|
|
328
|
+
return { error: describeBoundaryError(error) };
|
|
329
|
+
}
|
|
330
|
+
render() {
|
|
331
|
+
const err = this.state.error;
|
|
332
|
+
if (!err)
|
|
333
|
+
return this.props.children;
|
|
334
|
+
return jsx(this.props.fallback, { error: err });
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
function describeBoundaryError(error) {
|
|
338
|
+
const e = error;
|
|
339
|
+
const message = (e && e.message) || String(error);
|
|
340
|
+
const stack = (e && typeof e.stack === "string" && e.stack) || "";
|
|
341
|
+
const digest = sha256Hex(message + "\n" + stack).slice(0, 10);
|
|
342
|
+
console.error(`[krate] Error caught by an error boundary (digest ${digest}):`, error);
|
|
343
|
+
markErrorCaught();
|
|
344
|
+
return { name: "Error", message: "Internal Server Error", digest };
|
|
345
|
+
}
|
|
149
346
|
function renderNode(node) {
|
|
150
347
|
if (node == null || node === false)
|
|
151
348
|
return "";
|
|
@@ -161,6 +358,8 @@ function renderNode(node) {
|
|
|
161
358
|
return node.map(renderNode).join("");
|
|
162
359
|
if (typeof node === "object" && "__raw" in node)
|
|
163
360
|
return node.__raw;
|
|
361
|
+
if (isReactElement(node))
|
|
362
|
+
return renderElement(normalizeNode(node));
|
|
164
363
|
if (typeof node === "object" && "type" in node)
|
|
165
364
|
return renderElement(node);
|
|
166
365
|
return "";
|
|
@@ -258,42 +457,70 @@ function isJSXValue(v) {
|
|
|
258
457
|
// render their children eagerly (marked __krateEagerChildren, e.g. Link) get
|
|
259
458
|
// their children and JSX-valued props resolved first, so an async component
|
|
260
459
|
// passed as a child still renders.
|
|
261
|
-
async function resolveTree(node) {
|
|
460
|
+
async function resolveTree(node, vals) {
|
|
262
461
|
if (isThenable(node))
|
|
263
|
-
return resolveTree(await node);
|
|
462
|
+
return resolveTree(await node, vals);
|
|
264
463
|
if (node == null || typeof node !== "object")
|
|
265
464
|
return node;
|
|
266
465
|
if (Array.isArray(node))
|
|
267
|
-
return Promise.all(node.map(resolveTree));
|
|
466
|
+
return Promise.all(node.map((n) => resolveTree(n, vals)));
|
|
268
467
|
if ("__raw" in node)
|
|
269
468
|
return node;
|
|
469
|
+
if (isReactElement(node))
|
|
470
|
+
node = normalizeNode(node);
|
|
270
471
|
if (!isElement(node))
|
|
271
472
|
return node;
|
|
272
473
|
const { type, props, children } = node;
|
|
273
|
-
if (typeof type
|
|
274
|
-
return { type, props, children: (await Promise.all(children.map(resolveTree))) };
|
|
474
|
+
if (typeof type === "string") {
|
|
475
|
+
return { type, props, children: (await Promise.all(children.map((n) => resolveTree(n, vals)))) };
|
|
476
|
+
}
|
|
477
|
+
const step = await expandComponent(node, vals);
|
|
478
|
+
return resolveTree(step.out, step.vals);
|
|
479
|
+
}
|
|
480
|
+
// expandComponent runs one component element (function, class, React exotic
|
|
481
|
+
// type, foreign Provider or Consumer) and returns what it rendered, with the
|
|
482
|
+
// context values in scope for that output.
|
|
483
|
+
async function expandComponent(node, vals) {
|
|
484
|
+
const { type, props, children } = node;
|
|
485
|
+
let fn = type;
|
|
486
|
+
while (typeof fn !== "function") {
|
|
487
|
+
try {
|
|
488
|
+
fn = exoticType(fn);
|
|
489
|
+
}
|
|
490
|
+
catch (e) {
|
|
491
|
+
if (!isThenable(e))
|
|
492
|
+
throw e;
|
|
493
|
+
await e;
|
|
494
|
+
}
|
|
275
495
|
}
|
|
276
|
-
const fn = type;
|
|
277
496
|
if (fn.__krateSuspense)
|
|
278
|
-
return
|
|
497
|
+
return { out: children, vals };
|
|
279
498
|
let callProps = { ...props, children };
|
|
280
499
|
if (fn.__krateEagerChildren) {
|
|
281
|
-
const entries = await Promise.all(Object.entries(props).map(async ([k, v]) => [k, isJSXValue(v) ? await resolveTree(v) : v]));
|
|
282
|
-
callProps = { ...Object.fromEntries(entries), children: await resolveTree(children) };
|
|
500
|
+
const entries = await Promise.all(Object.entries(props).map(async ([k, v]) => [k, isJSXValue(v) ? await resolveTree(v, vals) : v]));
|
|
501
|
+
callProps = { ...Object.fromEntries(entries), children: await resolveTree(children, vals) };
|
|
283
502
|
}
|
|
284
503
|
if (isClassComponent(fn)) {
|
|
285
504
|
const instance = new fn(callProps);
|
|
286
505
|
try {
|
|
287
|
-
return await resolveTree(instance.render());
|
|
506
|
+
return { out: await resolveTree(instance.render(), vals), vals };
|
|
288
507
|
}
|
|
289
508
|
catch (error) {
|
|
290
|
-
return
|
|
509
|
+
return { out: classFallback(fn, instance, error), vals };
|
|
291
510
|
}
|
|
292
511
|
}
|
|
293
|
-
|
|
512
|
+
if (fn.__krateForeignConsumer) {
|
|
513
|
+
const ctx = fn.__krateForeignConsumer;
|
|
514
|
+
return { out: consumerChild(callProps)(vals?.has(ctx) ? vals.get(ctx) : ctx._currentValue), vals };
|
|
515
|
+
}
|
|
516
|
+
// A client boundary also gets the context values in scope (slotValues).
|
|
517
|
+
let out = fn.__krateClient ? fn(callProps, vals) : fn(callProps);
|
|
294
518
|
if (isThenable(out))
|
|
295
519
|
out = await out;
|
|
296
|
-
|
|
520
|
+
if (fn.__krateForeignProvider) {
|
|
521
|
+
return { out, vals: new Map(vals).set(fn.__krateForeignProvider, props.value) };
|
|
522
|
+
}
|
|
523
|
+
return { out, vals };
|
|
297
524
|
}
|
|
298
525
|
// rawTextContent renders the children of <script>/<style>: their text is raw
|
|
299
526
|
// text in HTML, so entity escaping would corrupt JSON-LD and inline code. The
|
|
@@ -313,6 +540,18 @@ function rawTextContent(tag, children) {
|
|
|
313
540
|
function renderElement(el) {
|
|
314
541
|
const { type, props, children } = el;
|
|
315
542
|
// Component
|
|
543
|
+
if (typeof type !== "string" && typeof type !== "function") {
|
|
544
|
+
let fn;
|
|
545
|
+
try {
|
|
546
|
+
fn = exoticType(type);
|
|
547
|
+
}
|
|
548
|
+
catch (e) {
|
|
549
|
+
if (isThenable(e))
|
|
550
|
+
throw asyncInSyncRender("A lazy component");
|
|
551
|
+
throw e;
|
|
552
|
+
}
|
|
553
|
+
return renderElement({ type: fn, props, children });
|
|
554
|
+
}
|
|
316
555
|
if (typeof type === "function") {
|
|
317
556
|
if (isClassComponent(type)) {
|
|
318
557
|
const instance = new type({ ...props, children });
|
|
@@ -326,7 +565,7 @@ function renderElement(el) {
|
|
|
326
565
|
const result = type({ ...props, children });
|
|
327
566
|
if (isThenable(result))
|
|
328
567
|
throw asyncInSyncRender(`<${componentName(type)}>`);
|
|
329
|
-
return renderNode(result);
|
|
568
|
+
return withProviderValue(type, props, () => renderNode(result));
|
|
330
569
|
}
|
|
331
570
|
// HTML element
|
|
332
571
|
const tag = type;
|
|
@@ -378,59 +617,66 @@ export function Suspense(props) {
|
|
|
378
617
|
`<template data-suspense="${id}">${inner}</template>`);
|
|
379
618
|
}
|
|
380
619
|
Suspense.__krateSuspense = true;
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
620
|
+
/**
|
|
621
|
+
* lazy() in a server tree: the loader's module is imported while the page
|
|
622
|
+
* renders and its component renders in place. Nothing is code-split to the
|
|
623
|
+
* browser, so a server-only module can be loaded this way.
|
|
624
|
+
*/
|
|
625
|
+
export function lazy(loader) {
|
|
626
|
+
let loaded;
|
|
627
|
+
return async function Lazy(props) {
|
|
628
|
+
loaded ?? (loaded = Promise.resolve(loader()));
|
|
629
|
+
const mod = await loaded;
|
|
630
|
+
const C = typeof mod === "function" ? mod : mod?.default;
|
|
631
|
+
if (typeof C !== "function") {
|
|
632
|
+
throw new Error("lazy(): the loader did not resolve to a component; export it as the module's default or return it from .then()");
|
|
633
|
+
}
|
|
634
|
+
return jsx(C, props);
|
|
635
|
+
};
|
|
393
636
|
}
|
|
637
|
+
// slotValues is the ContextValues entry holding the client context forwarded
|
|
638
|
+
// into a server-rendered slot of a client component: nested client
|
|
639
|
+
// components render inside it, as they would in one React tree.
|
|
640
|
+
const slotValues = {};
|
|
641
|
+
let slotSeq = 0;
|
|
642
|
+
function deferSlot(ctx, node, done) {
|
|
643
|
+
slotSeq = (slotSeq + 1) % 1e9;
|
|
644
|
+
const id = slotSeq.toString(36) + Math.random().toString(36).slice(2, 8);
|
|
645
|
+
const token = `<!--krate-slot:${id}-->`;
|
|
646
|
+
ctx.slots.push({ token, id, node, done: (html) => done(html, id), vals: ctx.vals });
|
|
647
|
+
return token;
|
|
648
|
+
}
|
|
649
|
+
// mergeSlotValues layers the values a component provides at a slot over the
|
|
650
|
+
// ones forwarded into the component.
|
|
651
|
+
function mergeSlotValues(outer, own) {
|
|
652
|
+
if (!own)
|
|
653
|
+
return outer;
|
|
654
|
+
if (!outer || outer.length === 0)
|
|
655
|
+
return own;
|
|
656
|
+
const keys = new Set(own.map((e) => e.k));
|
|
657
|
+
return outer.filter((e) => !keys.has(e.k)).concat(own);
|
|
658
|
+
}
|
|
659
|
+
const flightIsAction = (v) => (isServerAction(v) ? v.actionUrl : undefined);
|
|
660
|
+
const flightIsJSX = (v) => isElement(v) || "__raw" in v;
|
|
394
661
|
// serializeClientProp converts a prop crossing from the server to a client
|
|
395
|
-
// component into JSON-safe data
|
|
396
|
-
// chunk turns back into callable
|
|
397
|
-
//
|
|
662
|
+
// component into JSON-safe data (see flight-props.ts for the encoding). Server
|
|
663
|
+
// actions become references the client chunk turns back into callable
|
|
664
|
+
// proxies; anything JSON and the tag encoding cannot carry faithfully throws
|
|
665
|
+
// with the offending prop path.
|
|
398
666
|
function serializeClientProp(v, path, component) {
|
|
399
|
-
if (v === null || typeof v === "string" || typeof v === "boolean")
|
|
400
|
-
return v;
|
|
401
|
-
if (typeof v === "number") {
|
|
402
|
-
if (!Number.isFinite(v))
|
|
403
|
-
throw clientPropError(path, component, `the number ${v}`);
|
|
404
|
-
return v;
|
|
405
|
-
}
|
|
406
667
|
if (v === undefined)
|
|
407
668
|
return undefined;
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
if (isElement(v) || "__raw" in v) {
|
|
414
|
-
throw clientPropError(path, component, "JSX", "only `children` can carry server-rendered JSX into a client component");
|
|
415
|
-
}
|
|
416
|
-
const proto = Object.getPrototypeOf(v);
|
|
417
|
-
if (proto !== Object.prototype && proto !== null)
|
|
418
|
-
throw clientPropError(path, component, describeValue(v));
|
|
419
|
-
const out = {};
|
|
420
|
-
for (const [k, x] of Object.entries(v)) {
|
|
421
|
-
const sv = serializeClientProp(x, `${path}.${k}`, component);
|
|
422
|
-
if (sv !== undefined)
|
|
423
|
-
out[k] = sv;
|
|
424
|
-
}
|
|
425
|
-
return out;
|
|
426
|
-
}
|
|
427
|
-
throw clientPropError(path, component, describeValue(v));
|
|
669
|
+
return encodeProp(v, path, {
|
|
670
|
+
isAction: flightIsAction,
|
|
671
|
+
isJSX: flightIsJSX,
|
|
672
|
+
fail: (p, what, hint) => clientPropError(p, component, what, hint),
|
|
673
|
+
});
|
|
428
674
|
}
|
|
429
675
|
function clientPropError(path, component, what, hint) {
|
|
430
676
|
return new Error(`Prop \`${path}\` passed to client component <${component}> is ${what}, which cannot be sent from a server ` +
|
|
431
677
|
`component to the client. ` +
|
|
432
|
-
(hint || "Pass
|
|
433
|
-
"move event handlers and class instances into the client component."));
|
|
678
|
+
(hint || "Pass serializable data (strings, numbers, booleans, null, undefined, bigint, Date, Map, Set, typed arrays, " +
|
|
679
|
+
"plain objects, arrays) or a server action; move event handlers and class instances into the client component."));
|
|
434
680
|
}
|
|
435
681
|
function clientRegistry() {
|
|
436
682
|
const g = globalThis;
|
|
@@ -453,12 +699,44 @@ function hasClientElement(node) {
|
|
|
453
699
|
return true;
|
|
454
700
|
return typeof node.type === "string" && node.children.some(hasClientElement);
|
|
455
701
|
}
|
|
456
|
-
|
|
702
|
+
// isSlotValue reports whether a prop holds server-rendered JSX (an element, raw
|
|
703
|
+
// HTML, or an array containing either). Such a prop is a slot: it is rendered
|
|
704
|
+
// on the server and revived on the client like `children`.
|
|
705
|
+
function isSlotValue(v) {
|
|
706
|
+
if (Array.isArray(v))
|
|
707
|
+
return v.some(isSlotValue);
|
|
708
|
+
return v != null && typeof v === "object" && (isElement(v) || "__raw" in v);
|
|
709
|
+
}
|
|
710
|
+
// slotProp renders a JSX-valued prop. A slot without client components of its
|
|
711
|
+
// own travels as HTML; one with them (or any slot when tree is set) travels as
|
|
712
|
+
// a tree that keeps those components in the island's Preact tree.
|
|
713
|
+
async function slotProp(v, ctx, tree) {
|
|
714
|
+
if (tree || hasClientElement(v)) {
|
|
715
|
+
const nested = { hydrate: false, component: ctx.component, slots: ctx.slots, vals: ctx.vals };
|
|
716
|
+
const out = await toFlight(v, nested);
|
|
717
|
+
if (nested.hydrate)
|
|
718
|
+
ctx.hydrate = true;
|
|
719
|
+
return { __krateSlotTree: out };
|
|
720
|
+
}
|
|
721
|
+
const slot = { __krateSlotHTML: "" };
|
|
722
|
+
slot.__krateSlotHTML = deferSlot(ctx, v, (html, id) => {
|
|
723
|
+
if (html !== null)
|
|
724
|
+
slot.__krateSlotHTML = html;
|
|
725
|
+
else {
|
|
726
|
+
delete slot.__krateSlotHTML;
|
|
727
|
+
slot.__krateSlotRef = id;
|
|
728
|
+
}
|
|
729
|
+
});
|
|
730
|
+
return slot;
|
|
731
|
+
}
|
|
732
|
+
// clientProps serializes the props of a client component, rendering the
|
|
733
|
+
// JSX-valued ones (any name, not only `children`) as slots.
|
|
734
|
+
async function clientProps(props, ctx, tree) {
|
|
457
735
|
const out = {};
|
|
458
736
|
for (const [k, v] of Object.entries(props)) {
|
|
459
737
|
if (k === "key" || k === "children")
|
|
460
738
|
continue;
|
|
461
|
-
const sv = serializeClientProp(v, k, ctx.component);
|
|
739
|
+
const sv = isSlotValue(v) ? await slotProp(v, ctx, tree) : serializeClientProp(v, k, ctx.component);
|
|
462
740
|
if (sv !== undefined)
|
|
463
741
|
out[k] = sv;
|
|
464
742
|
}
|
|
@@ -468,9 +746,15 @@ function flightProps(props, ctx) {
|
|
|
468
746
|
// that keeps nested client components as components, so they render inside the
|
|
469
747
|
// parent's Preact tree and share its context (Radix Dialog.Root with its
|
|
470
748
|
// Trigger and Content). Everything else is host markup or server-rendered HTML.
|
|
471
|
-
|
|
749
|
+
//
|
|
750
|
+
// With inline set (the children of an asChild component) a server component
|
|
751
|
+
// at the top of a child is run here instead of becoming HTML, until a host
|
|
752
|
+
// element or client component comes out: Radix's Slot clones that element and
|
|
753
|
+
// merges its handlers, ref and ARIA props into it, as it does with the React
|
|
754
|
+
// element RSC hands it. Client components in its output stay in the tree.
|
|
755
|
+
async function toFlight(node, ctx, inline = false) {
|
|
472
756
|
if (isThenable(node))
|
|
473
|
-
return toFlight(await node, ctx);
|
|
757
|
+
return toFlight(await node, ctx, inline);
|
|
474
758
|
if (node == null || typeof node === "boolean")
|
|
475
759
|
return [];
|
|
476
760
|
if (typeof node === "string" || typeof node === "number")
|
|
@@ -478,18 +762,20 @@ async function toFlight(node, ctx) {
|
|
|
478
762
|
if (Array.isArray(node)) {
|
|
479
763
|
const out = [];
|
|
480
764
|
for (const n of node)
|
|
481
|
-
out.push(...(await toFlight(n, ctx)));
|
|
765
|
+
out.push(...(await toFlight(n, ctx, inline)));
|
|
482
766
|
return out;
|
|
483
767
|
}
|
|
484
768
|
if (typeof node !== "object")
|
|
485
769
|
return [];
|
|
486
770
|
if ("__raw" in node)
|
|
487
|
-
return [
|
|
771
|
+
return [htmlSlot(ctx, node)];
|
|
772
|
+
if (inline && isReactElement(node))
|
|
773
|
+
node = normalizeNode(node);
|
|
488
774
|
if (!isElement(node))
|
|
489
775
|
return [];
|
|
490
776
|
const { type, props, children } = node;
|
|
491
777
|
if (typeof type === "string") {
|
|
492
|
-
return [{ $: "e", t: type, p:
|
|
778
|
+
return [{ $: "e", t: type, p: await clientProps(props, ctx, true), c: await toFlight(children, ctx) }];
|
|
493
779
|
}
|
|
494
780
|
if (type === Link) {
|
|
495
781
|
return [{ $: "e", t: "a", p: linkAttributes({ ...props, children }), c: await toFlight(children, ctx) }];
|
|
@@ -499,12 +785,55 @@ async function toFlight(node, ctx) {
|
|
|
499
785
|
if (ref.hydrate)
|
|
500
786
|
ctx.hydrate = true;
|
|
501
787
|
const nested = { ...ctx, component: ref.exportName };
|
|
502
|
-
const c = await toFlight(children, nested);
|
|
788
|
+
const c = await toFlight(children, nested, !!props.asChild);
|
|
503
789
|
if (nested.hydrate)
|
|
504
790
|
ctx.hydrate = true;
|
|
505
|
-
|
|
791
|
+
if (props.asChild)
|
|
792
|
+
warnUncloneable(ref.exportName, c);
|
|
793
|
+
return [{ $: "c", m: ref.moduleId, e: ref.exportName, s: ref.src, p: await clientProps(props, nested, true), c }];
|
|
506
794
|
}
|
|
507
|
-
|
|
795
|
+
if (inline) {
|
|
796
|
+
const step = await expandComponent(node, ctx.vals);
|
|
797
|
+
const nested = { ...ctx, vals: step.vals };
|
|
798
|
+
const out = await toFlight(step.out, nested, true);
|
|
799
|
+
if (nested.hydrate)
|
|
800
|
+
ctx.hydrate = true;
|
|
801
|
+
return out;
|
|
802
|
+
}
|
|
803
|
+
return [htmlSlot(ctx, node)];
|
|
804
|
+
}
|
|
805
|
+
// htmlSlot is a server-rendered part of a children tree: { $: "h", h: html },
|
|
806
|
+
// or { $: "h", r: id } once the component has rendered it into the document.
|
|
807
|
+
function htmlSlot(ctx, node) {
|
|
808
|
+
const slot = { $: "h", h: "" };
|
|
809
|
+
slot.h = deferSlot(ctx, node, (html, id) => {
|
|
810
|
+
if (html !== null)
|
|
811
|
+
slot.h = html;
|
|
812
|
+
else {
|
|
813
|
+
delete slot.h;
|
|
814
|
+
slot.r = id;
|
|
815
|
+
}
|
|
816
|
+
});
|
|
817
|
+
return slot;
|
|
818
|
+
}
|
|
819
|
+
// propsScript is the JSON script that carries an island's props, placed just
|
|
820
|
+
// before its <krate-island>. Every "<" is escaped, so no "</script" or "<!--"
|
|
821
|
+
// in a value can end the script or open a comment.
|
|
822
|
+
function propsScript(data) {
|
|
823
|
+
return `<script type="application/json" data-krate-props>${JSON.stringify(data).replace(/</g, "\\u003c")}</script>`;
|
|
824
|
+
}
|
|
825
|
+
const warnedUncloneable = new Set();
|
|
826
|
+
// warnUncloneable reports an asChild component whose child reached the
|
|
827
|
+
// client as server-rendered HTML (raw HTML, a deferred slot), which its Slot
|
|
828
|
+
// cannot clone or merge props into.
|
|
829
|
+
function warnUncloneable(component, tree) {
|
|
830
|
+
if (!tree.some((n) => n != null && typeof n === "object" && n.$ === "h"))
|
|
831
|
+
return;
|
|
832
|
+
if (warnedUncloneable.has(component))
|
|
833
|
+
return;
|
|
834
|
+
warnedUncloneable.add(component);
|
|
835
|
+
console.warn(`[krate] <${component} asChild> received a child rendered to HTML, so it cannot merge its props and handlers ` +
|
|
836
|
+
`into it. Pass a single element or a component that renders one (not raw HTML) as the child.`);
|
|
508
837
|
}
|
|
509
838
|
function wrapClientNamespace(moduleId, exportName, src, ns, render, hydrate) {
|
|
510
839
|
const out = {};
|
|
@@ -527,13 +856,16 @@ function wrapClientNamespace(moduleId, exportName, src, ns, render, hydrate) {
|
|
|
527
856
|
* clientBoundary wraps an export of a `"use client"` module, or a component
|
|
528
857
|
* of a React package, for the server bundle of a page that renders server
|
|
529
858
|
* components. The server renders the component's initial HTML (render) and,
|
|
530
|
-
* when it hydrates, puts it in a <krate-island> marker
|
|
531
|
-
* serialized props; the per-module client chunk at src
|
|
532
|
-
* browser. A component without state or effects (hydrate
|
|
533
|
-
* is plain HTML. Children are rendered on the server
|
|
534
|
-
*
|
|
535
|
-
*
|
|
536
|
-
*
|
|
859
|
+
* when it hydrates, puts it in a <krate-island> marker preceded by a JSON
|
|
860
|
+
* script with its serialized props; the per-module client chunk at src
|
|
861
|
+
* hydrates it in the browser. A component without state or effects (hydrate
|
|
862
|
+
* false, an icon) is plain HTML. Children are rendered on the server into the
|
|
863
|
+
* component's HTML and adopted there by the browser (see DeferredSlot), or,
|
|
864
|
+
* when they hold client components of their own, sent as a tree that keeps
|
|
865
|
+
* those components in the same Preact tree. The children of an asChild component
|
|
866
|
+
* always travel as a tree, with a server component at the top of a child run
|
|
867
|
+
* to the element it renders, so the component's Slot can clone it. A
|
|
868
|
+
* namespace export (Radix's Dialog) is wrapped member by member. With `flight` the children always travel as a
|
|
537
869
|
* tree (a real-React island rebuilds them as elements, not HTML).
|
|
538
870
|
*/
|
|
539
871
|
export function clientBoundary(moduleId, exportName, src, impl, render, hydrate = true, flight = false) {
|
|
@@ -543,34 +875,47 @@ export function clientBoundary(moduleId, exportName, src, impl, render, hydrate
|
|
|
543
875
|
if (typeof impl !== "function")
|
|
544
876
|
return impl;
|
|
545
877
|
const name = impl.displayName || impl.name || exportName;
|
|
546
|
-
const Boundary = async (props) => {
|
|
878
|
+
const Boundary = async (props, vals) => {
|
|
547
879
|
const { children, ...rest } = props || {};
|
|
548
|
-
const
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
continue;
|
|
552
|
-
const sv = serializeClientProp(v, k, name);
|
|
553
|
-
if (sv !== undefined)
|
|
554
|
-
data[k] = sv;
|
|
555
|
-
}
|
|
880
|
+
const slots = [];
|
|
881
|
+
const slotCtx = { hydrate: false, component: name, slots, vals };
|
|
882
|
+
const data = await clientProps(rest, slotCtx, flight);
|
|
556
883
|
const hasChildren = children != null && !(Array.isArray(children) && children.length === 0);
|
|
557
|
-
let hydrates = hydrate;
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
884
|
+
let hydrates = hydrate || slotCtx.hydrate;
|
|
885
|
+
// An asChild component clones its child, so the child travels as a tree.
|
|
886
|
+
const asChild = !!rest.asChild;
|
|
887
|
+
if (hasChildren && (flight || asChild || hasClientElement(children))) {
|
|
888
|
+
const ctx = { hydrate: false, component: exportName, slots, vals };
|
|
889
|
+
data.__krateTree = await toFlight(children, ctx, asChild);
|
|
562
890
|
if (ctx.hydrate)
|
|
563
891
|
hydrates = true;
|
|
892
|
+
if (asChild)
|
|
893
|
+
warnUncloneable(exportName, data.__krateTree);
|
|
564
894
|
}
|
|
565
895
|
else if (hasChildren) {
|
|
566
|
-
|
|
567
|
-
data.__krateChildren = childrenHTML;
|
|
896
|
+
data.__krateChildren = deferSlot(slotCtx, children, (html, id) => (data.__krateChildren = html ?? { __krateSlotRef: id }));
|
|
568
897
|
}
|
|
569
|
-
const
|
|
898
|
+
const fwd = vals?.get(slotValues);
|
|
899
|
+
const capture = {};
|
|
900
|
+
let html = render(impl, data, null, fwd, capture);
|
|
901
|
+
const rendered = await Promise.all(slots.map(async (s) => {
|
|
902
|
+
const scope = mergeSlotValues(fwd, capture[s.token]);
|
|
903
|
+
const base = s.vals ?? vals;
|
|
904
|
+
const inner = scope ? new Map(base).set(slotValues, scope) : base;
|
|
905
|
+
return renderNode(await resolveTree(s.node, inner));
|
|
906
|
+
}));
|
|
907
|
+
// A slot whose token is in the render is in the document: the browser
|
|
908
|
+
// adopts those nodes, so they are not sent again inside the props.
|
|
909
|
+
const placed = slots.map((s) => html.includes(s.token));
|
|
910
|
+
slots.forEach((s, i) => {
|
|
911
|
+
s.done(placed[i] ? null : rendered[i]);
|
|
912
|
+
html = html.split(s.token).join(rendered[i]);
|
|
913
|
+
});
|
|
570
914
|
if (!hydrates)
|
|
571
915
|
return raw(html);
|
|
572
|
-
return raw(
|
|
573
|
-
|
|
916
|
+
return raw(propsScript(data) +
|
|
917
|
+
`<krate-island style="display:contents" data-module="${escapeHTML(moduleId)}" data-export="${escapeHTML(exportName)}" ` +
|
|
918
|
+
`data-src="${escapeHTML(src)}">${html}</krate-island>`);
|
|
574
919
|
};
|
|
575
920
|
Object.defineProperty(Boundary, "name", { value: name });
|
|
576
921
|
const ref = { moduleId, exportName, src, impl, hydrate };
|
|
@@ -637,6 +982,22 @@ function linkAttributes(props) {
|
|
|
637
982
|
attrs.rel = "noopener noreferrer";
|
|
638
983
|
if (rest.className)
|
|
639
984
|
attrs.class = String(rest.className);
|
|
985
|
+
// Every other attribute reaches the anchor, so data-*, aria-*, class and
|
|
986
|
+
// style that a Slot (asChild) merges onto a Link are not lost.
|
|
987
|
+
for (const [key, v] of Object.entries(rest)) {
|
|
988
|
+
const name = ATTR_ALIASES[key] || key;
|
|
989
|
+
if (name in attrs || v == null || v === false || typeof v === "function")
|
|
990
|
+
continue;
|
|
991
|
+
if (key === "key" || key === "ref" || key === "className" || key === "dangerouslySetInnerHTML" || key.startsWith("on") || key.startsWith("__"))
|
|
992
|
+
continue;
|
|
993
|
+
if (key === "style" && typeof v === "object") {
|
|
994
|
+
const css = styleString(v);
|
|
995
|
+
if (css)
|
|
996
|
+
attrs.style = css;
|
|
997
|
+
continue;
|
|
998
|
+
}
|
|
999
|
+
attrs[name] = v === true ? "" : String(v);
|
|
1000
|
+
}
|
|
640
1001
|
return attrs;
|
|
641
1002
|
}
|
|
642
1003
|
// Link - renders an <a> tag wired for SPA navigation (server renderer).
|