@krate/runtime 0.5.0-alpha.4 → 0.5.0-beta.1
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 +5 -1
- package/dist/action-context.js +33 -3
- package/dist/action-context.test.js +26 -1
- package/dist/actions.d.ts +12 -1
- package/dist/actions.js +83 -4
- package/dist/actions.test.js +61 -1
- package/dist/cache-scope.js +4 -1
- package/dist/cache.test.js +16 -0
- package/dist/class-helpers.d.ts +4 -4
- package/dist/class-helpers.js +357 -32
- package/dist/class-helpers.test.d.ts +1 -0
- package/dist/class-helpers.test.js +169 -0
- package/dist/context.d.ts +16 -2
- package/dist/context.js +44 -3
- package/dist/dev-overlay.js +75 -2
- package/dist/dev-overlay.test.js +22 -0
- package/dist/dom.d.ts +7 -0
- package/dist/dom.js +69 -3
- package/dist/error-overlay.js +4 -4
- package/dist/hook-args.d.ts +7 -0
- package/dist/hook-args.js +10 -0
- package/dist/htmlspec-attributes.d.ts +1 -0
- package/dist/htmlspec-attributes.js +159 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/krate-core.js +2 -0
- package/dist/krate-dev.js +65 -2
- package/dist/krate-f-actions.js +2 -0
- package/dist/krate-f-classes.js +8 -0
- package/dist/krate-f-helpers.js +2 -0
- package/dist/krate-f-list.js +2 -0
- package/dist/krate-f-router-lite.js +2 -0
- package/dist/krate-f-router.js +2 -0
- package/dist/krate-features.json +239 -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/patterns.test.d.ts +1 -0
- package/dist/patterns.test.js +98 -0
- package/dist/reactivity-core.test.d.ts +1 -0
- package/dist/reactivity-core.test.js +152 -0
- package/dist/reconcile.js +4 -2
- package/dist/router-nav.test.js +38 -0
- package/dist/router-speculation.test.d.ts +1 -0
- package/dist/router-speculation.test.js +25 -0
- package/dist/router-styles.test.d.ts +1 -0
- package/dist/router-styles.test.js +98 -0
- package/dist/router.js +116 -32
- package/dist/server-async.test.js +20 -0
- package/dist/server-renderer.js +109 -22
- package/dist/server.d.ts +1 -0
- package/dist/server.js +90 -11
- package/dist/server.test.js +20 -0
- package/dist/signal.d.ts +3 -2
- package/dist/signal.js +104 -19
- package/dist/slots.js +12 -1
- package/package.json +2 -2
|
@@ -74,6 +74,26 @@ describe('renderToStringAsync', () => {
|
|
|
74
74
|
}
|
|
75
75
|
await expect(renderToStringAsync(jsx('div', { children: jsx(Boom, {}) }))).rejects.toThrow('db down');
|
|
76
76
|
});
|
|
77
|
+
it('renders a class error boundary around a failing async server component', async () => {
|
|
78
|
+
class Boundary {
|
|
79
|
+
constructor(props) {
|
|
80
|
+
this.state = { error: null };
|
|
81
|
+
this.props = props;
|
|
82
|
+
}
|
|
83
|
+
static getDerivedStateFromError(error) { return { error }; }
|
|
84
|
+
render() {
|
|
85
|
+
if (this.state.error)
|
|
86
|
+
return jsx('p', { children: 'fallback: ' + this.state.error.message });
|
|
87
|
+
return this.props.children;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
async function Boom() {
|
|
91
|
+
await tick();
|
|
92
|
+
throw new Error('server boom');
|
|
93
|
+
}
|
|
94
|
+
const html = await renderToStringAsync(jsx(Boundary, { children: jsx(Boom, {}) }));
|
|
95
|
+
expect(html).toContain('fallback: server boom');
|
|
96
|
+
});
|
|
77
97
|
});
|
|
78
98
|
describe('renderToString with async components', () => {
|
|
79
99
|
it('throws instead of rendering an empty string', () => {
|
package/dist/server-renderer.js
CHANGED
|
@@ -9,7 +9,7 @@ import { pathToFileURL } from "node:url";
|
|
|
9
9
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
10
10
|
import { timingSafeEqual } from "node:crypto";
|
|
11
11
|
import { jsx, renderToStringAsync } from "./server.js";
|
|
12
|
-
import { isNotFoundSignal, parseCookieHeader, redirectTarget, thenableRecord, } from "./request-context.js";
|
|
12
|
+
import { isNotFoundSignal, parseCookieHeader, redirectTarget, thenable, thenableRecord, } from "./request-context.js";
|
|
13
13
|
import { cacheRuntime, installRenderStore, patchFetch, routeDataTag, withCacheScope, } from "./cache-scope.js";
|
|
14
14
|
// Render cache scopes (tags / revalidate windows read during a render) and the
|
|
15
15
|
// Next-style fetch data cache. Installed once per process; page bundles share
|
|
@@ -118,11 +118,70 @@ function variantKey(req) {
|
|
|
118
118
|
key += "#" + query;
|
|
119
119
|
return key;
|
|
120
120
|
}
|
|
121
|
+
function newQueryTracker() {
|
|
122
|
+
return { keys: new Set(), all: false };
|
|
123
|
+
}
|
|
124
|
+
function trackedQuery(query, t) {
|
|
125
|
+
const target = { ...(query || {}) };
|
|
126
|
+
const note = (prop) => {
|
|
127
|
+
if (typeof prop === "string" && prop !== "then" && prop !== "toJSON" && prop !== "constructor")
|
|
128
|
+
t.keys.add(prop);
|
|
129
|
+
};
|
|
130
|
+
return new Proxy(target, {
|
|
131
|
+
get(obj, prop, recv) {
|
|
132
|
+
note(prop);
|
|
133
|
+
return Reflect.get(obj, prop, recv);
|
|
134
|
+
},
|
|
135
|
+
has(obj, prop) {
|
|
136
|
+
note(prop);
|
|
137
|
+
return Reflect.has(obj, prop);
|
|
138
|
+
},
|
|
139
|
+
ownKeys(obj) {
|
|
140
|
+
t.all = true;
|
|
141
|
+
return Reflect.ownKeys(obj);
|
|
142
|
+
},
|
|
143
|
+
getOwnPropertyDescriptor(obj, prop) {
|
|
144
|
+
note(prop);
|
|
145
|
+
return Reflect.getOwnPropertyDescriptor(obj, prop);
|
|
146
|
+
},
|
|
147
|
+
});
|
|
148
|
+
}
|
|
149
|
+
// pageQueryReads remembers, per route+params variant, which query keys renders
|
|
150
|
+
// have read ("all" when a render enumerated the whole query).
|
|
151
|
+
const pageQueryReads = new Map();
|
|
152
|
+
function pageBaseKey(req) {
|
|
153
|
+
return variantKey({ route: req.route, params: req.params });
|
|
154
|
+
}
|
|
155
|
+
// pageKey is the ISR cache key for a request: params, plus only the query keys
|
|
156
|
+
// previous renders of this variant read.
|
|
157
|
+
function pageKey(req) {
|
|
158
|
+
const reads = pageQueryReads.get(pageBaseKey(req));
|
|
159
|
+
if (!reads)
|
|
160
|
+
return pageBaseKey(req);
|
|
161
|
+
if (reads === "all")
|
|
162
|
+
return variantKey(req);
|
|
163
|
+
const picked = {};
|
|
164
|
+
for (const k of [...reads].sort()) {
|
|
165
|
+
if (req.query && Object.prototype.hasOwnProperty.call(req.query, k))
|
|
166
|
+
picked[k] = req.query[k];
|
|
167
|
+
}
|
|
168
|
+
return variantKey({ route: req.route, params: req.params, query: picked });
|
|
169
|
+
}
|
|
170
|
+
function recordQueryReads(req, t) {
|
|
171
|
+
const base = pageBaseKey(req);
|
|
172
|
+
let cur = pageQueryReads.get(base);
|
|
173
|
+
if (t.all)
|
|
174
|
+
cur = "all";
|
|
175
|
+
else if (t.keys.size > 0 && cur !== "all")
|
|
176
|
+
cur = new Set([...(cur || []), ...t.keys]);
|
|
177
|
+
if (cur)
|
|
178
|
+
pageQueryReads.set(base, cur);
|
|
179
|
+
}
|
|
121
180
|
class ISRCache {
|
|
122
181
|
constructor(maxSize = 512) {
|
|
123
182
|
this.cache = new Map();
|
|
124
183
|
this.byTag = new Map();
|
|
125
|
-
this.revalidationIntervals = new Map(); // route
|
|
184
|
+
this.revalidationIntervals = new Map(); // route -> seconds
|
|
126
185
|
this.maxSize = maxSize;
|
|
127
186
|
}
|
|
128
187
|
setRevalidation(route, seconds) {
|
|
@@ -274,7 +333,7 @@ function withRenderTimeout(p) {
|
|
|
274
333
|
let isrCacheFile = process.env.KRATE_ISR_CACHE || "";
|
|
275
334
|
let persistTimer = null;
|
|
276
335
|
function isrCachePath() {
|
|
277
|
-
return isrCacheFile || path.join(
|
|
336
|
+
return isrCacheFile || path.join(OUT_DIR, ".krate", "isr-cache.json");
|
|
278
337
|
}
|
|
279
338
|
function persistIsrNow() {
|
|
280
339
|
if (SSR_WORKERS > 1)
|
|
@@ -328,7 +387,7 @@ async function loadPageModule(page) {
|
|
|
328
387
|
let fileUrl;
|
|
329
388
|
if (page.bundlePath) {
|
|
330
389
|
// Pre-compiled bundle: bundlePath is relative to outDir (dist/)
|
|
331
|
-
const bundleAbs = path.resolve(
|
|
390
|
+
const bundleAbs = path.resolve(OUT_DIR, page.bundlePath);
|
|
332
391
|
fileUrl = pathToFileURL(bundleAbs).href;
|
|
333
392
|
}
|
|
334
393
|
else {
|
|
@@ -371,7 +430,7 @@ const requestStore = (() => {
|
|
|
371
430
|
g[key] = new AsyncLocalStorage();
|
|
372
431
|
return g[key];
|
|
373
432
|
})();
|
|
374
|
-
function requestContextFor(req) {
|
|
433
|
+
function requestContextFor(req, tracker) {
|
|
375
434
|
const h = new Headers();
|
|
376
435
|
for (const [k, v] of Object.entries(req.headers || {})) {
|
|
377
436
|
if (typeof v === "string") {
|
|
@@ -389,11 +448,11 @@ function requestContextFor(req) {
|
|
|
389
448
|
headers: h,
|
|
390
449
|
cookies: parseCookieHeader(h.get("cookie")),
|
|
391
450
|
params: { ...(req.params || {}) },
|
|
392
|
-
searchParams: { ...(req.query || {}) },
|
|
451
|
+
searchParams: tracker ? trackedQuery(req.query, tracker) : { ...(req.query || {}) },
|
|
393
452
|
};
|
|
394
453
|
}
|
|
395
|
-
function withRequest(req, fn) {
|
|
396
|
-
return requestStore.run(requestContextFor(req), fn);
|
|
454
|
+
function withRequest(req, fn, tracker) {
|
|
455
|
+
return requestStore.run(requestContextFor(req, tracker), fn);
|
|
397
456
|
}
|
|
398
457
|
// renderSignal maps notFound()/redirect() thrown during a render to a response.
|
|
399
458
|
function renderSignal(err) {
|
|
@@ -404,7 +463,7 @@ function renderSignal(err) {
|
|
|
404
463
|
return { html: "", status: 307, redirect: to };
|
|
405
464
|
return null;
|
|
406
465
|
}
|
|
407
|
-
function buildProps(req) {
|
|
466
|
+
function buildProps(req, tracker) {
|
|
408
467
|
// Page-level data fetching (getStaticProps/getServerSideProps) has been
|
|
409
468
|
// removed; per-request data is provided by server components (@server),
|
|
410
469
|
// runtime components (@runtime), and middleware instead. Dynamic-route
|
|
@@ -417,6 +476,15 @@ function buildProps(req) {
|
|
|
417
476
|
const props = {};
|
|
418
477
|
if (req.params)
|
|
419
478
|
props.params = thenableRecord(req.params);
|
|
479
|
+
if (tracker) {
|
|
480
|
+
// Reads through the view are recorded; awaiting it resolves to another
|
|
481
|
+
// tracked view so `const { page } = await searchParams` records "page".
|
|
482
|
+
const view = trackedQuery(req.query, tracker);
|
|
483
|
+
props.searchParams = thenable(view, () => trackedQuery(req.query, tracker));
|
|
484
|
+
if (req.query)
|
|
485
|
+
props.query = trackedQuery(req.query, tracker);
|
|
486
|
+
return props;
|
|
487
|
+
}
|
|
420
488
|
props.searchParams = thenableRecord(req.query);
|
|
421
489
|
if (req.query)
|
|
422
490
|
props.query = req.query;
|
|
@@ -436,15 +504,18 @@ async function renderFresh(page, req) {
|
|
|
436
504
|
// Async server components (and plain sync pages) render through
|
|
437
505
|
// renderToStringAsync inside the request scope. The timeout bounds slow
|
|
438
506
|
// awaits (fetch); a page that blocks synchronously still blocks the loop.
|
|
439
|
-
const
|
|
507
|
+
const tracker = newQueryTracker();
|
|
508
|
+
const { result: html, scope, invalidated } = await withRenderTimeout(withCacheScope(page.route, () => withRequest(req, () => renderToStringAsync(jsx(Component, buildProps(req, tracker))), tracker)));
|
|
440
509
|
const response = {
|
|
441
510
|
html,
|
|
442
511
|
status: 200,
|
|
512
|
+
noStore: scope.noStore || invalidated,
|
|
443
513
|
};
|
|
444
514
|
// An uncacheable read (no-store) keeps the render out of the ISR cache, and
|
|
445
515
|
// a revalidation that landed mid-render means the HTML may be stale.
|
|
446
516
|
if (page.mode === "isr" && !scope.noStore && !invalidated) {
|
|
447
|
-
|
|
517
|
+
recordQueryReads(req, tracker);
|
|
518
|
+
isrCache.set(pageKey(req), {
|
|
448
519
|
html,
|
|
449
520
|
timestamp: Date.now(),
|
|
450
521
|
params: req.params,
|
|
@@ -469,7 +540,7 @@ async function renderFresh(page, req) {
|
|
|
469
540
|
// same promise instead of stampeding the renderer.
|
|
470
541
|
const inFlightRevalidations = new Map();
|
|
471
542
|
function revalidateInBackground(page, req) {
|
|
472
|
-
const key =
|
|
543
|
+
const key = pageKey(req);
|
|
473
544
|
if (inFlightRevalidations.has(key))
|
|
474
545
|
return;
|
|
475
546
|
const p = (async () => {
|
|
@@ -533,7 +604,7 @@ async function renderPage(req) {
|
|
|
533
604
|
if (page.mode === "isr") {
|
|
534
605
|
const interval = page.revalidate || 60;
|
|
535
606
|
isrCache.setRevalidation(page.route, interval);
|
|
536
|
-
const key =
|
|
607
|
+
const key = pageKey(req);
|
|
537
608
|
const cached = isrCache.get(key);
|
|
538
609
|
if (cached && !isrCache.isStale(key)) {
|
|
539
610
|
return {
|
|
@@ -575,7 +646,7 @@ function loadRuntimeRenderer(relPath) {
|
|
|
575
646
|
const cached = runtimeBundleCache.get(relPath);
|
|
576
647
|
if (cached)
|
|
577
648
|
return cached;
|
|
578
|
-
const abs = path.resolve(
|
|
649
|
+
const abs = path.resolve(OUT_DIR, relPath);
|
|
579
650
|
const code = fs.readFileSync(abs, "utf-8");
|
|
580
651
|
// Runtime components get the host's fetch (looked up per call, so a cache
|
|
581
652
|
// layer that wraps globalThis.fetch later still applies) and the web
|
|
@@ -739,6 +810,8 @@ async function renderRegion(page, region, req) {
|
|
|
739
810
|
const frame = { type: "region", id: region.id, status: 200, html };
|
|
740
811
|
if (cacheable)
|
|
741
812
|
frame.cacheStatus = "miss";
|
|
813
|
+
if (r.scope.noStore || r.invalidated)
|
|
814
|
+
frame.noStore = true;
|
|
742
815
|
return frame;
|
|
743
816
|
}
|
|
744
817
|
catch (err) {
|
|
@@ -782,6 +855,8 @@ async function renderPageRegion(page, id, req) {
|
|
|
782
855
|
frame.redirect = result.redirect;
|
|
783
856
|
if (result.error)
|
|
784
857
|
frame.error = result.error;
|
|
858
|
+
if (result.noStore)
|
|
859
|
+
frame.noStore = true;
|
|
785
860
|
if (page.serverComponents && frame.status >= 500)
|
|
786
861
|
frame.fatal = true;
|
|
787
862
|
// Title swap: the Go server replaces the baked <title> with the freshly
|
|
@@ -926,6 +1001,7 @@ function mergeOpResults(op, results) {
|
|
|
926
1001
|
const PORT = parseInt(process.env.KRATE_SSR_PORT || "3100", 10);
|
|
927
1002
|
const manifestPath = process.env.KRATE_MANIFEST || "";
|
|
928
1003
|
const root = process.env.KRATE_ROOT || process.cwd();
|
|
1004
|
+
const OUT_DIR = process.env.KRATE_OUT_DIR || path.join(root, "dist");
|
|
929
1005
|
projectRoot = root;
|
|
930
1006
|
// Load manifest
|
|
931
1007
|
if (manifestPath && fs.existsSync(manifestPath)) {
|
|
@@ -935,7 +1011,8 @@ if (manifestPath && fs.existsSync(manifestPath)) {
|
|
|
935
1011
|
}
|
|
936
1012
|
else {
|
|
937
1013
|
// Try default location
|
|
938
|
-
const
|
|
1014
|
+
const krateDefault = path.join(OUT_DIR, ".krate", "server-manifest.json");
|
|
1015
|
+
const defaultPath = fs.existsSync(krateDefault) ? krateDefault : path.join(OUT_DIR, "server-manifest.json");
|
|
939
1016
|
if (fs.existsSync(defaultPath)) {
|
|
940
1017
|
const data = fs.readFileSync(defaultPath, "utf-8");
|
|
941
1018
|
manifest = JSON.parse(data);
|
|
@@ -999,6 +1076,11 @@ const server = http.createServer(async (req, res) => {
|
|
|
999
1076
|
// sidecar renders each one (a component region from the manifest, or a
|
|
1000
1077
|
// coarse "page" region that renders the whole page component for SSR/ISR).
|
|
1001
1078
|
if (route === "/__krate/regions" && req.method === "POST") {
|
|
1079
|
+
if (!internalAuthorized(req)) {
|
|
1080
|
+
res.writeHead(403, { "Content-Type": "application/json" });
|
|
1081
|
+
res.end(JSON.stringify({ error: "forbidden" }));
|
|
1082
|
+
return;
|
|
1083
|
+
}
|
|
1002
1084
|
res.writeHead(200, {
|
|
1003
1085
|
"Content-Type": "application/x-ndjson; charset=utf-8",
|
|
1004
1086
|
"Cache-Control": "no-store",
|
|
@@ -1041,9 +1123,9 @@ const server = http.createServer(async (req, res) => {
|
|
|
1041
1123
|
// Unknown region id - keep the baked content by sending no frame.
|
|
1042
1124
|
return Promise.resolve({ type: "skip", id: r.id });
|
|
1043
1125
|
});
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1126
|
+
// Write each frame as soon as it resolves. Async server components finish
|
|
1127
|
+
// out of document order, and the Go host inserts each chunk at its marker.
|
|
1128
|
+
await Promise.all(pending.map(async (p) => writeJsonLine(res, await p)));
|
|
1047
1129
|
writeJsonLine(res, { type: "end", count: regions.length });
|
|
1048
1130
|
}
|
|
1049
1131
|
catch (err) {
|
|
@@ -1054,6 +1136,11 @@ const server = http.createServer(async (req, res) => {
|
|
|
1054
1136
|
return;
|
|
1055
1137
|
}
|
|
1056
1138
|
// Direct page requests (non-proxied)
|
|
1139
|
+
if (!internalAuthorized(req)) {
|
|
1140
|
+
res.writeHead(403, { "Content-Type": "application/json" });
|
|
1141
|
+
res.end(JSON.stringify({ error: "forbidden" }));
|
|
1142
|
+
return;
|
|
1143
|
+
}
|
|
1057
1144
|
// Collect request headers
|
|
1058
1145
|
const headers = {};
|
|
1059
1146
|
for (const [key, value] of Object.entries(req.headers)) {
|
|
@@ -1069,7 +1156,7 @@ const server = http.createServer(async (req, res) => {
|
|
|
1069
1156
|
const result = await renderPage(renderReq);
|
|
1070
1157
|
if (result.notFound) {
|
|
1071
1158
|
// Try to serve 404.html from dist
|
|
1072
|
-
const notFoundPath = path.join(
|
|
1159
|
+
const notFoundPath = path.join(OUT_DIR, "404.html");
|
|
1073
1160
|
if (fs.existsSync(notFoundPath)) {
|
|
1074
1161
|
const html = fs.readFileSync(notFoundPath, "utf-8");
|
|
1075
1162
|
res.writeHead(404, { "Content-Type": "text/html; charset=utf-8" });
|
|
@@ -1088,7 +1175,7 @@ const server = http.createServer(async (req, res) => {
|
|
|
1088
1175
|
}
|
|
1089
1176
|
if (result.status === 500) {
|
|
1090
1177
|
// Try to serve 500.html from dist
|
|
1091
|
-
const errorPath = path.join(
|
|
1178
|
+
const errorPath = path.join(OUT_DIR, "500.html");
|
|
1092
1179
|
if (fs.existsSync(errorPath)) {
|
|
1093
1180
|
const html = fs.readFileSync(errorPath, "utf-8");
|
|
1094
1181
|
res.writeHead(500, { "Content-Type": "text/html; charset=utf-8" });
|
|
@@ -1133,14 +1220,14 @@ else {
|
|
|
1133
1220
|
catch {
|
|
1134
1221
|
// not listening yet
|
|
1135
1222
|
}
|
|
1136
|
-
server.listen(PORT);
|
|
1223
|
+
server.listen(PORT, "127.0.0.1");
|
|
1137
1224
|
}, 100);
|
|
1138
1225
|
return;
|
|
1139
1226
|
}
|
|
1140
1227
|
}
|
|
1141
1228
|
throw err;
|
|
1142
1229
|
});
|
|
1143
|
-
server.listen(PORT, () => {
|
|
1230
|
+
server.listen(PORT, "127.0.0.1", () => {
|
|
1144
1231
|
console.log(`[krate-ssr] Renderer server listening on port ${PORT}`);
|
|
1145
1232
|
});
|
|
1146
1233
|
}
|
package/dist/server.d.ts
CHANGED
|
@@ -9,6 +9,7 @@ export declare function createEffect(_fn: () => void): () => void;
|
|
|
9
9
|
export declare function createMemo<T>(fn: () => T): () => T;
|
|
10
10
|
export declare function krateDerived<T>(fn: () => T, _triggers?: () => unknown): () => T;
|
|
11
11
|
export declare function krateHook<T>(value: T | (() => T)): () => T;
|
|
12
|
+
export declare function krateParam<T>(value: T | (() => T)): T;
|
|
12
13
|
export declare function onCleanup(_fn: () => void): void;
|
|
13
14
|
export declare function onMount(_fn: () => void): void;
|
|
14
15
|
interface RawHTML {
|
package/dist/server.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
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
|
+
import { ATTR_ALIASES } from './htmlspec-attributes.js';
|
|
3
4
|
export { getActionContext, headers, cookies, redirect } from './action-context.js';
|
|
4
5
|
export { revalidatePath, revalidateTag, unstable_cache, unstable_noStore } from './cache.js';
|
|
5
6
|
export { getRequestContext, notFound } from './request-context.js';
|
|
@@ -40,6 +41,10 @@ export function krateHook(value) {
|
|
|
40
41
|
return value;
|
|
41
42
|
return () => value;
|
|
42
43
|
}
|
|
44
|
+
// Reads a custom hook parameter that a call site passed as a derived getter.
|
|
45
|
+
export function krateParam(value) {
|
|
46
|
+
return typeof value === "function" && derivedGetters.has(value) ? value() : value;
|
|
47
|
+
}
|
|
43
48
|
export function onCleanup(_fn) {
|
|
44
49
|
// No-op on server
|
|
45
50
|
}
|
|
@@ -117,6 +122,22 @@ function asyncInSyncRender(where) {
|
|
|
117
122
|
`are rendered per request by the SSR sidecar through renderToStringAsync; a synchronous ` +
|
|
118
123
|
`render (for example inside goComponent children) cannot await them.`);
|
|
119
124
|
}
|
|
125
|
+
function isClassComponent(fn) {
|
|
126
|
+
return typeof fn === "function" && fn.prototype && typeof fn.prototype.render === "function";
|
|
127
|
+
}
|
|
128
|
+
function classFallback(type, instance, error) {
|
|
129
|
+
if (typeof type.getDerivedStateFromError !== "function")
|
|
130
|
+
throw error;
|
|
131
|
+
instance.state = { ...(instance.state || {}), ...(type.getDerivedStateFromError(error) || {}) };
|
|
132
|
+
try {
|
|
133
|
+
if (typeof instance.componentDidCatch === "function")
|
|
134
|
+
instance.componentDidCatch(error, { componentStack: "" });
|
|
135
|
+
}
|
|
136
|
+
catch {
|
|
137
|
+
// A throwing componentDidCatch must not hide the original render error.
|
|
138
|
+
}
|
|
139
|
+
return instance.render();
|
|
140
|
+
}
|
|
120
141
|
function renderNode(node) {
|
|
121
142
|
if (node == null || node === false)
|
|
122
143
|
return "";
|
|
@@ -139,31 +160,68 @@ function renderNode(node) {
|
|
|
139
160
|
function isServerAction(v) {
|
|
140
161
|
return typeof v === "function" && typeof v.actionUrl === "string";
|
|
141
162
|
}
|
|
163
|
+
const UNITLESS = new Set([
|
|
164
|
+
"animation-iteration-count", "aspect-ratio", "border-image-outset", "border-image-slice",
|
|
165
|
+
"border-image-width", "box-flex", "box-flex-group", "box-ordinal-group", "column-count",
|
|
166
|
+
"columns", "flex", "flex-grow", "flex-positive", "flex-shrink", "flex-negative", "flex-order",
|
|
167
|
+
"grid-area", "grid-row", "grid-row-end", "grid-row-span", "grid-row-start", "grid-column",
|
|
168
|
+
"grid-column-end", "grid-column-span", "grid-column-start", "font-weight", "line-clamp",
|
|
169
|
+
"line-height", "opacity", "order", "orphans", "scale", "tab-size", "widows", "z-index", "zoom",
|
|
170
|
+
"fill-opacity", "flood-opacity", "stop-opacity", "stroke-dasharray", "stroke-dashoffset",
|
|
171
|
+
"stroke-miterlimit", "stroke-opacity", "stroke-width",
|
|
172
|
+
]);
|
|
173
|
+
const URL_ATTRS = new Set(["href", "src", "action", "formaction", "xlink:href"]);
|
|
174
|
+
// eslint-disable-next-line no-control-regex
|
|
175
|
+
const JS_URL = /^[\u0000-\u001F ]*j[\r\n\t]*a[\r\n\t]*v[\r\n\t]*a[\r\n\t]*s[\r\n\t]*c[\r\n\t]*r[\r\n\t]*i[\r\n\t]*p[\r\n\t]*t[\r\n\t]*:/i;
|
|
176
|
+
const BLOCKED_URL = "javascript:throw new Error('React has blocked a javascript: URL as a security precaution.')";
|
|
177
|
+
function cssName(key) {
|
|
178
|
+
if (key.startsWith("--"))
|
|
179
|
+
return key;
|
|
180
|
+
const name = key.replace(/[A-Z]/g, (c) => "-" + c.toLowerCase());
|
|
181
|
+
return name.startsWith("ms-") ? "-" + name : name;
|
|
182
|
+
}
|
|
183
|
+
function styleString(value) {
|
|
184
|
+
const out = [];
|
|
185
|
+
for (const key of Object.keys(value)) {
|
|
186
|
+
const v = value[key];
|
|
187
|
+
if (v == null || typeof v === "boolean" || v === "")
|
|
188
|
+
continue;
|
|
189
|
+
const prop = cssName(key);
|
|
190
|
+
const bare = prop.replace(/^-(webkit|moz|ms|o)-/, "");
|
|
191
|
+
const text = typeof v === "number" && v !== 0 && !prop.startsWith("--") && !UNITLESS.has(bare)
|
|
192
|
+
? v + "px"
|
|
193
|
+
: String(v);
|
|
194
|
+
out.push(prop + ":" + text);
|
|
195
|
+
}
|
|
196
|
+
return out.join(";");
|
|
197
|
+
}
|
|
142
198
|
function setAttr(key, val) {
|
|
199
|
+
if (key === "children" || key === "key" || key === "ref" || key === "dangerouslySetInnerHTML")
|
|
200
|
+
return "";
|
|
201
|
+
const name = ATTR_ALIASES[key] || key;
|
|
143
202
|
if (val == null || val === false)
|
|
144
203
|
return "";
|
|
145
204
|
if (val === true)
|
|
146
|
-
return ` ${
|
|
147
|
-
if (
|
|
205
|
+
return ` ${name}`;
|
|
206
|
+
if (name === "action" && isServerAction(val)) {
|
|
148
207
|
return ` action="${escapeHTML(val.actionUrl)}" data-krate-action`;
|
|
149
208
|
}
|
|
150
|
-
if (
|
|
209
|
+
if (name === "formaction" && isServerAction(val)) {
|
|
151
210
|
return ` formaction="${escapeHTML(val.actionUrl)}" formmethod="post" data-krate-action`;
|
|
152
211
|
}
|
|
153
212
|
// Client function actions run only after hydration; they have no HTML form.
|
|
154
213
|
if (typeof val === "function")
|
|
155
214
|
return "";
|
|
156
|
-
if (key === "class")
|
|
157
|
-
return ` class="${escapeHTML(String(val))}"`;
|
|
158
215
|
if (key === "style" && typeof val === "object") {
|
|
159
|
-
const css =
|
|
160
|
-
|
|
161
|
-
.join(";");
|
|
162
|
-
return ` style="${escapeHTML(css)}"`;
|
|
216
|
+
const css = styleString(val);
|
|
217
|
+
return css ? ` style="${escapeHTML(css)}"` : "";
|
|
163
218
|
}
|
|
164
219
|
if (key.startsWith("on") || key.startsWith("__"))
|
|
165
220
|
return "";
|
|
166
|
-
|
|
221
|
+
let text = String(val);
|
|
222
|
+
if (URL_ATTRS.has(name.toLowerCase()) && JS_URL.test(text))
|
|
223
|
+
text = BLOCKED_URL;
|
|
224
|
+
return ` ${name}="${escapeHTML(text)}"`;
|
|
167
225
|
}
|
|
168
226
|
export function renderToString(node) {
|
|
169
227
|
return renderNode(node);
|
|
@@ -215,6 +273,15 @@ async function resolveTree(node) {
|
|
|
215
273
|
const entries = await Promise.all(Object.entries(props).map(async ([k, v]) => [k, isJSXValue(v) ? await resolveTree(v) : v]));
|
|
216
274
|
callProps = { ...Object.fromEntries(entries), children: await resolveTree(children) };
|
|
217
275
|
}
|
|
276
|
+
if (isClassComponent(fn)) {
|
|
277
|
+
const instance = new fn(callProps);
|
|
278
|
+
try {
|
|
279
|
+
return await resolveTree(instance.render());
|
|
280
|
+
}
|
|
281
|
+
catch (error) {
|
|
282
|
+
return resolveTree(classFallback(fn, instance, error));
|
|
283
|
+
}
|
|
284
|
+
}
|
|
218
285
|
let out = fn(callProps);
|
|
219
286
|
if (isThenable(out))
|
|
220
287
|
out = await out;
|
|
@@ -224,6 +291,15 @@ function renderElement(el) {
|
|
|
224
291
|
const { type, props, children } = el;
|
|
225
292
|
// Component
|
|
226
293
|
if (typeof type === "function") {
|
|
294
|
+
if (isClassComponent(type)) {
|
|
295
|
+
const instance = new type({ ...props, children });
|
|
296
|
+
try {
|
|
297
|
+
return renderNode(instance.render());
|
|
298
|
+
}
|
|
299
|
+
catch (error) {
|
|
300
|
+
return renderNode(classFallback(type, instance, error));
|
|
301
|
+
}
|
|
302
|
+
}
|
|
227
303
|
const result = type({ ...props, children });
|
|
228
304
|
if (isThenable(result))
|
|
229
305
|
throw asyncInSyncRender(`<${componentName(type)}>`);
|
|
@@ -240,7 +316,10 @@ function renderElement(el) {
|
|
|
240
316
|
if (VOID_ELEMENTS.has(tag)) {
|
|
241
317
|
return `<${tag}${attrs}>`;
|
|
242
318
|
}
|
|
243
|
-
const
|
|
319
|
+
const dangerous = props.dangerouslySetInnerHTML;
|
|
320
|
+
const inner = dangerous && typeof dangerous === "object" && typeof dangerous.__html === "string"
|
|
321
|
+
? dangerous.__html
|
|
322
|
+
: children.map(renderNode).join("");
|
|
244
323
|
return `<${tag}${attrs}>${inner}</${tag}>`;
|
|
245
324
|
}
|
|
246
325
|
// Streaming SSR via Suspense
|
package/dist/server.test.js
CHANGED
|
@@ -23,6 +23,26 @@ describe('renderToString', () => {
|
|
|
23
23
|
it('passes raw HTML through without escaping', () => {
|
|
24
24
|
expect(renderToString({ __raw: '<b>hi</b>' })).toBe('<b>hi</b>');
|
|
25
25
|
});
|
|
26
|
+
it('maps React attribute aliases like the compiler renderer', () => {
|
|
27
|
+
const html = renderToString(jsx('label', { className: 'x', htmlFor: 'name', children: 'Name' }));
|
|
28
|
+
expect(html).toBe('<label class="x" for="name">Name</label>');
|
|
29
|
+
});
|
|
30
|
+
it('serializes style objects with unitless exceptions', () => {
|
|
31
|
+
const html = renderToString(jsx('div', {
|
|
32
|
+
style: { backgroundColor: 'red', marginTop: 4, opacity: 0.5, zIndex: 2, '--raw': 1 },
|
|
33
|
+
}));
|
|
34
|
+
expect(html).toBe('<div style="background-color:red;margin-top:4px;opacity:0.5;z-index:2;--raw:1"></div>');
|
|
35
|
+
});
|
|
36
|
+
it('renders dangerouslySetInnerHTML instead of an attribute', () => {
|
|
37
|
+
const html = renderToString(jsx('div', { dangerouslySetInnerHTML: { __html: '<b>hi</b>' } }));
|
|
38
|
+
expect(html).toBe('<div><b>hi</b></div>');
|
|
39
|
+
});
|
|
40
|
+
it('blocks javascript: URLs and drops reserved props', () => {
|
|
41
|
+
const html = renderToString(jsx('a', { href: 'javascript:alert(1)', ref: {}, key: 'k', children: 'x' }));
|
|
42
|
+
expect(html).toContain('href="javascript:throw new Error(');
|
|
43
|
+
expect(html).not.toContain(' ref=');
|
|
44
|
+
expect(html).not.toContain(' key=');
|
|
45
|
+
});
|
|
26
46
|
});
|
|
27
47
|
describe('goComponent', () => {
|
|
28
48
|
it('inlines baked HTML for an annotated server-tier call site', () => {
|
package/dist/signal.d.ts
CHANGED
|
@@ -151,9 +151,10 @@ export interface CSSARIAOptions {
|
|
|
151
151
|
* Accessibility semantics to synthesize. Defaults are native (radios,
|
|
152
152
|
* checkboxes) and ship no JS. Presets that need synthesized state
|
|
153
153
|
* (`tabs`, `listbox`, `accordion`, `disclosure`, `dialog`, `menu`,
|
|
154
|
-
* `popover`) inject a tiny ARIA
|
|
154
|
+
* `popover`, `nav`) inject a tiny keyboard and ARIA enhancer automatically:
|
|
155
|
+
* Enter/Space/Escape/arrow keys, focus move/trap/restore, aria-expanded.
|
|
155
156
|
*/
|
|
156
|
-
as?: 'radiogroup' | 'tabs' | 'tablist' | 'listbox' | 'menu' | 'menubar' | 'accordion' | 'disclosure' | 'dialog' | 'modal' | 'popover' | 'switch' | 'checkbox';
|
|
157
|
+
as?: 'radiogroup' | 'tabs' | 'tablist' | 'listbox' | 'menu' | 'menubar' | 'nav' | 'accordion' | 'disclosure' | 'dialog' | 'modal' | 'popover' | 'switch' | 'checkbox';
|
|
157
158
|
/** Accessible label for the scope container. */
|
|
158
159
|
label?: string;
|
|
159
160
|
/** Raw ARIA overrides (`{ role, 'aria-controls', panelRole }`); `false` opts out of all ARIA. */
|