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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (165) hide show
  1. package/dist/action-context.d.ts +5 -1
  2. package/dist/action-context.js +33 -3
  3. package/dist/action-context.test.js +26 -1
  4. package/dist/actions.d.ts +12 -1
  5. package/dist/actions.js +84 -4
  6. package/dist/actions.test.js +61 -1
  7. package/dist/assets-static.d.ts +5 -0
  8. package/dist/assets-static.js +31 -0
  9. package/dist/boundary.d.ts +12 -0
  10. package/dist/boundary.js +53 -13
  11. package/dist/cache-adapter.d.ts +113 -0
  12. package/dist/cache-adapter.js +217 -0
  13. package/dist/cache-adapter.test.d.ts +1 -0
  14. package/dist/cache-adapter.test.js +244 -0
  15. package/dist/cache-redis.d.ts +27 -0
  16. package/dist/cache-redis.js +110 -0
  17. package/dist/cache-scope.d.ts +25 -9
  18. package/dist/cache-scope.js +64 -13
  19. package/dist/cache.d.ts +1 -0
  20. package/dist/cache.js +3 -3
  21. package/dist/cache.test.js +16 -0
  22. package/dist/class-component.js +6 -0
  23. package/dist/class-component.test.js +53 -2
  24. package/dist/class-helpers.d.ts +4 -4
  25. package/dist/class-helpers.js +357 -32
  26. package/dist/class-helpers.test.d.ts +1 -0
  27. package/dist/class-helpers.test.js +169 -0
  28. package/dist/context.d.ts +16 -2
  29. package/dist/context.js +44 -3
  30. package/dist/dev-overlay.js +85 -12
  31. package/dist/dev-overlay.test.js +22 -0
  32. package/dist/dom.d.ts +15 -0
  33. package/dist/dom.js +97 -3
  34. package/dist/effect-errors.test.d.ts +1 -0
  35. package/dist/effect-errors.test.js +163 -0
  36. package/dist/effects.d.ts +8 -0
  37. package/dist/effects.js +13 -0
  38. package/dist/error-overlay.js +7 -7
  39. package/dist/handler-html.d.ts +63 -0
  40. package/dist/handler-html.js +285 -0
  41. package/dist/handler-html.test.d.ts +1 -0
  42. package/dist/handler-html.test.js +256 -0
  43. package/dist/handler-routing.d.ts +83 -0
  44. package/dist/handler-routing.js +579 -0
  45. package/dist/handler-routing.test.d.ts +1 -0
  46. package/dist/handler-routing.test.js +99 -0
  47. package/dist/handler-segments.d.ts +43 -0
  48. package/dist/handler-segments.js +115 -0
  49. package/dist/handler-segments.test.d.ts +1 -0
  50. package/dist/handler-segments.test.js +217 -0
  51. package/dist/head-tags.d.ts +51 -0
  52. package/dist/head-tags.js +329 -0
  53. package/dist/head-tags.test.d.ts +1 -0
  54. package/dist/head-tags.test.js +131 -0
  55. package/dist/highlight-bind.d.ts +42 -0
  56. package/dist/highlight-bind.js +176 -0
  57. package/dist/highlight-bind.test.d.ts +1 -0
  58. package/dist/highlight-bind.test.js +124 -0
  59. package/dist/highlight.d.ts +93 -0
  60. package/dist/highlight.js +426 -0
  61. package/dist/highlight.test.d.ts +1 -0
  62. package/dist/highlight.test.js +56 -0
  63. package/dist/hints.d.ts +19 -0
  64. package/dist/hints.js +97 -0
  65. package/dist/hook-args.d.ts +7 -0
  66. package/dist/hook-args.js +10 -0
  67. package/dist/htmlspec-attributes.d.ts +1 -0
  68. package/dist/htmlspec-attributes.js +159 -0
  69. package/dist/index.d.ts +4 -0
  70. package/dist/index.js +3 -0
  71. package/dist/jsx-types.d.ts +11 -0
  72. package/dist/krate-core.js +2 -0
  73. package/dist/krate-dev.js +75 -12
  74. package/dist/krate-f-actions.js +2 -0
  75. package/dist/krate-f-classes.js +8 -0
  76. package/dist/krate-f-helpers.js +2 -0
  77. package/dist/krate-f-highlight.js +2 -0
  78. package/dist/krate-f-list.js +2 -0
  79. package/dist/krate-f-navigation.js +2 -0
  80. package/dist/krate-f-router-lite.js +2 -0
  81. package/dist/krate-f-router.js +2 -0
  82. package/dist/krate-features.json +493 -0
  83. package/dist/krate-hydrate-lite.js +5 -5
  84. package/dist/krate-hydrate.js +5 -5
  85. package/dist/krate-runtime.js +5 -5
  86. package/dist/list.js +4 -2
  87. package/dist/metadata-routes.d.ts +75 -0
  88. package/dist/metadata-routes.js +76 -0
  89. package/dist/metadata.d.ts +222 -0
  90. package/dist/metadata.js +452 -0
  91. package/dist/metadata.test.d.ts +1 -0
  92. package/dist/metadata.test.js +167 -0
  93. package/dist/navigation-server.d.ts +27 -0
  94. package/dist/navigation-server.js +90 -0
  95. package/dist/navigation.d.ts +37 -0
  96. package/dist/navigation.js +195 -0
  97. package/dist/navigation.test.d.ts +1 -0
  98. package/dist/navigation.test.js +130 -0
  99. package/dist/node-server.d.ts +22 -0
  100. package/dist/node-server.js +436 -0
  101. package/dist/node-server.test.d.ts +1 -0
  102. package/dist/node-server.test.js +492 -0
  103. package/dist/og-files.d.ts +2 -0
  104. package/dist/og-files.js +19 -0
  105. package/dist/og.d.ts +56 -0
  106. package/dist/og.js +156 -0
  107. package/dist/patterns.test.d.ts +1 -0
  108. package/dist/patterns.test.js +98 -0
  109. package/dist/react.d.ts +47 -0
  110. package/dist/react.js +59 -1
  111. package/dist/react19.test.d.ts +1 -0
  112. package/dist/react19.test.js +176 -0
  113. package/dist/reactivity-core.test.d.ts +1 -0
  114. package/dist/reactivity-core.test.js +152 -0
  115. package/dist/reconcile.js +4 -2
  116. package/dist/request-context.d.ts +23 -0
  117. package/dist/request-context.js +45 -0
  118. package/dist/resp.d.ts +55 -0
  119. package/dist/resp.js +239 -0
  120. package/dist/router-layout.test.js +70 -0
  121. package/dist/router-nav.test.js +65 -0
  122. package/dist/router-speculation.test.d.ts +1 -0
  123. package/dist/router-speculation.test.js +25 -0
  124. package/dist/router-styles.test.d.ts +1 -0
  125. package/dist/router-styles.test.js +98 -0
  126. package/dist/router.js +175 -36
  127. package/dist/segmented-lru.d.ts +19 -0
  128. package/dist/segmented-lru.js +87 -0
  129. package/dist/server-async.test.js +43 -1
  130. package/dist/server-handler.d.ts +165 -0
  131. package/dist/server-handler.js +1826 -0
  132. package/dist/server-handler.test.d.ts +1 -0
  133. package/dist/server-handler.test.js +522 -0
  134. package/dist/server-highlight.test.d.ts +1 -0
  135. package/dist/server-highlight.test.js +32 -0
  136. package/dist/server-renderer.js +165 -720
  137. package/dist/server-renderer.test.d.ts +1 -0
  138. package/dist/server-renderer.test.js +266 -0
  139. package/dist/server.d.ts +13 -1
  140. package/dist/server.js +131 -16
  141. package/dist/server.test.js +20 -0
  142. package/dist/sha256.d.ts +1 -0
  143. package/dist/sha256.js +66 -0
  144. package/dist/sha256.test.d.ts +1 -0
  145. package/dist/sha256.test.js +13 -0
  146. package/dist/shared-isr.d.ts +31 -0
  147. package/dist/shared-isr.js +142 -0
  148. package/dist/signal.d.ts +3 -2
  149. package/dist/signal.js +163 -23
  150. package/dist/slots.js +12 -1
  151. package/dist/ssr-core-behavior.test.d.ts +1 -0
  152. package/dist/ssr-core-behavior.test.js +620 -0
  153. package/dist/ssr-core.d.ts +175 -0
  154. package/dist/ssr-core.js +940 -0
  155. package/dist/ssr-core.test.d.ts +1 -0
  156. package/dist/ssr-core.test.js +324 -0
  157. package/dist/static-memory.d.ts +3 -0
  158. package/dist/static-memory.js +47 -0
  159. package/dist/static-memory.test.d.ts +1 -0
  160. package/dist/static-memory.test.js +26 -0
  161. package/dist/test-redis.d.ts +12 -0
  162. package/dist/test-redis.js +131 -0
  163. package/dist/use-id.d.ts +8 -0
  164. package/dist/use-id.js +40 -0
  165. package/package.json +30 -2
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,266 @@
1
+ // @vitest-environment node
2
+ //
3
+ // End-to-end test of the Node SSR sidecar. server-renderer.ts starts a server
4
+ // when it is loaded, so the test runs the built dist/server-renderer.js as the
5
+ // Go host does: with KRATE_* environment variables, a server manifest and page
6
+ // bundles on disk, and talks to it over HTTP. Skipped when the runtime has not
7
+ // been built (KRATE_REQUIRE_E2E=1 turns that into a failure, as in CI).
8
+ import { spawn } from "node:child_process";
9
+ import { createHash } from "node:crypto";
10
+ import fs from "node:fs";
11
+ import net from "node:net";
12
+ import os from "node:os";
13
+ import path from "node:path";
14
+ import { pathToFileURL } from "node:url";
15
+ import { afterAll, beforeAll, describe, expect, it } from "vitest";
16
+ const here = path.dirname(new URL(import.meta.url).pathname);
17
+ const renderer = path.resolve(here, "..", "dist", "server-renderer.js");
18
+ const serverJs = path.resolve(here, "..", "dist", "server.js");
19
+ const built = fs.existsSync(renderer) && fs.existsSync(serverJs);
20
+ if (!built && process.env.KRATE_REQUIRE_E2E) {
21
+ throw new Error("dist/server-renderer.js is missing (KRATE_REQUIRE_E2E is set): build @krate/runtime first");
22
+ }
23
+ const SECRET = "test-secret";
24
+ let tmp = "";
25
+ let out = "";
26
+ let isrFile = "";
27
+ let child = null;
28
+ let port = 0;
29
+ let logs = "";
30
+ function freePort() {
31
+ return new Promise((resolve, reject) => {
32
+ const s = net.createServer();
33
+ s.once("error", reject);
34
+ s.listen(0, "127.0.0.1", () => {
35
+ const p = s.address().port;
36
+ s.close(() => resolve(p));
37
+ });
38
+ });
39
+ }
40
+ function write(rel, data) {
41
+ const f = path.join(out, rel);
42
+ fs.mkdirSync(path.dirname(f), { recursive: true });
43
+ fs.writeFileSync(f, data);
44
+ }
45
+ const jsxImport = `import { jsx } from ${JSON.stringify(pathToFileURL(serverJs).href)};\n`;
46
+ function bundles() {
47
+ write("pages/ssr.mjs", jsxImport +
48
+ `export default (props) => jsx("main", { children: [jsx("title", { children: "T " + ((props.params || {}).id || "") }), jsx("p", { children: "q=" + ((props.query || {}).q || "") })] });\n`);
49
+ write("pages/isr.mjs", jsxImport + `let n = 0;\nexport default () => jsx("p", { children: "isr-render-" + (++n) });\n`);
50
+ write("pages/boom.mjs", jsxImport + `export default () => { const e = new Error("secret detail"); e.stack = "at x"; throw e; };\n`);
51
+ write("pages/redirect.mjs", jsxImport + `export default () => { throw Object.assign(new Error("r"), { __krateRedirect: "/login" }); };\n`);
52
+ write("pages/missing.mjs", jsxImport + `export default () => { throw Object.assign(new Error("NEXT_NOT_FOUND"), { __krateNotFound: true, digest: "NEXT_NOT_FOUND" }); };\n`);
53
+ write("pages/regions.mjs", jsxImport +
54
+ `export const Slow = async () => { await new Promise((ok) => setTimeout(ok, 250)); return jsx("i", { children: "slow" }); };\n` +
55
+ `export const Fast = async () => jsx("i", { children: "fast" });\n` +
56
+ `export const Bad = async () => { throw new Error("region failed"); };\n` +
57
+ `export default () => jsx("p", { children: "whole page" });\n`);
58
+ write("rt/price.js", `globalThis.__krate_render = (json) => { const p = typeof json === "string" ? JSON.parse(json) : json; return "<b>" + p.price + "/" + (p.params ? p.params.id : "-") + "</b>"; };\n`);
59
+ write("404.html", "<h1>custom not found</h1>");
60
+ write("500.html", "<h1>custom error</h1>");
61
+ const page = (route, mode, bundle, extra = {}) => ({ route, source: route + ".tsx", mode, bundlePath: "pages/" + bundle + ".mjs", ...extra });
62
+ write(".krate/server-manifest.json", JSON.stringify({
63
+ pages: [
64
+ page("/ssr/[id]", "ssr", "ssr"),
65
+ page("/isr", "isr", "isr", { revalidate: 300 }),
66
+ page("/boom", "ssr", "boom"),
67
+ page("/redirect", "ssr", "redirect"),
68
+ page("/missing", "ssr", "missing"),
69
+ page("/regions", "ssr", "regions", { serverComponents: true }),
70
+ ],
71
+ regions: {
72
+ "/regions": [
73
+ { id: "slow", serverExport: "Slow" },
74
+ { id: "fast", serverExport: "Fast" },
75
+ { id: "bad", serverExport: "Bad" },
76
+ { id: "price", bundlePath: "rt/price.js", props: { price: 12 } },
77
+ ],
78
+ },
79
+ }));
80
+ }
81
+ async function start() {
82
+ port = await freePort();
83
+ logs = "";
84
+ child = spawn(process.execPath, [renderer], {
85
+ env: {
86
+ PATH: process.env.PATH,
87
+ KRATE_SSR_PORT: String(port),
88
+ KRATE_OUT_DIR: out,
89
+ KRATE_ROOT: tmp,
90
+ KRATE_INTERNAL_SECRET: SECRET,
91
+ KRATE_ISR_CACHE: isrFile,
92
+ },
93
+ stdio: ["ignore", "pipe", "pipe"],
94
+ });
95
+ child.stdout.on("data", (d) => (logs += d));
96
+ child.stderr.on("data", (d) => (logs += d));
97
+ const deadline = Date.now() + 15000;
98
+ for (;;) {
99
+ try {
100
+ const r = await fetch(`http://127.0.0.1:${port}/__krate/ssr/health`);
101
+ if (r.ok)
102
+ return;
103
+ }
104
+ catch {
105
+ // not listening yet
106
+ }
107
+ if (child.exitCode !== null)
108
+ throw new Error("renderer exited early:\n" + logs);
109
+ if (Date.now() > deadline)
110
+ throw new Error("renderer did not start:\n" + logs);
111
+ await new Promise((ok) => setTimeout(ok, 50));
112
+ }
113
+ }
114
+ async function stop() {
115
+ const c = child;
116
+ child = null;
117
+ if (!c || c.exitCode !== null)
118
+ return;
119
+ await new Promise((ok) => {
120
+ c.once("exit", () => ok());
121
+ c.kill("SIGKILL");
122
+ });
123
+ }
124
+ const secret = { "x-krate-internal": SECRET };
125
+ const url = (p) => `http://127.0.0.1:${port}${p}`;
126
+ async function regions(body, headers = secret) {
127
+ const res = await fetch(url("/__krate/regions"), { method: "POST", headers, body: JSON.stringify(body) });
128
+ const text = await res.text();
129
+ return { res, frames: text.split("\n").filter(Boolean).map((l) => JSON.parse(l)) };
130
+ }
131
+ describe.skipIf(!built)("server-renderer sidecar", () => {
132
+ beforeAll(async () => {
133
+ tmp = fs.mkdtempSync(path.join(os.tmpdir(), "krate-ssr-"));
134
+ out = path.join(tmp, "dist");
135
+ isrFile = path.join(tmp, "isr-cache.json");
136
+ bundles();
137
+ await start();
138
+ }, 30000);
139
+ afterAll(async () => {
140
+ await stop();
141
+ fs.rmSync(tmp, { recursive: true, force: true });
142
+ });
143
+ it("reports health with the number of SSR pages", async () => {
144
+ const r = await fetch(url("/__krate/ssr/health"));
145
+ expect(await r.json()).toEqual({ ok: true, pages: 6 });
146
+ });
147
+ describe("internal endpoints need the host's secret", () => {
148
+ it("refuses regions, revalidation and direct renders without it", async () => {
149
+ expect((await regions({ route: "/regions", url: "/regions" }, {})).res.status).toBe(403);
150
+ expect((await fetch(url("/__krate/ssr/cache-invalidate"), { method: "POST", body: "{}" })).status).toBe(403);
151
+ expect((await fetch(url("/__krate/ssr/cache-invalidate"), { method: "POST", body: "{}", headers: { "x-krate-internal": "wrong" } })).status).toBe(403);
152
+ expect((await fetch(url("/ssr/[id]"))).status).toBe(403);
153
+ });
154
+ it("answers 405 to a GET on a mutating endpoint, before the secret check", async () => {
155
+ const r = await fetch(url("/__krate/ssr/revalidate"));
156
+ expect(r.status).toBe(405);
157
+ expect(r.headers.get("allow")).toBe("POST");
158
+ });
159
+ it("applies an authorised invalidation and reports the counts", async () => {
160
+ const r = await fetch(url("/__krate/ssr/cache-invalidate"), { method: "POST", headers: secret, body: JSON.stringify({ tags: ["nothing"] }) });
161
+ expect(r.status).toBe(200);
162
+ expect(await r.json()).toMatchObject({ ok: true, workers: 1, isrEntries: 0, regionEntries: 0 });
163
+ const bad = await fetch(url("/__krate/ssr/cache-invalidate"), { method: "POST", headers: secret, body: "{not json" });
164
+ expect(bad.status).toBe(500);
165
+ });
166
+ });
167
+ describe("direct page requests", () => {
168
+ it("renders a request-time page; a direct request carries no params or query", async () => {
169
+ // The Go host asks for regions instead and forwards both (see below).
170
+ const r = await fetch(url("/ssr/[id]?q=1"), { headers: secret });
171
+ expect(r.status).toBe(200);
172
+ expect(r.headers.get("content-type")).toBe("text/html; charset=utf-8");
173
+ expect(await r.text()).toContain("<p>q=</p>");
174
+ });
175
+ it("serves the build's 404 page for an unknown route and for notFound()", async () => {
176
+ for (const p of ["/nowhere", "/missing"]) {
177
+ const r = await fetch(url(p), { headers: secret });
178
+ expect(r.status, p).toBe(404);
179
+ expect(await r.text()).toBe("<h1>custom not found</h1>");
180
+ }
181
+ });
182
+ it("serves the build's 500 page for a failing render, without the error text", async () => {
183
+ const r = await fetch(url("/boom"), { headers: secret });
184
+ expect(r.status).toBe(500);
185
+ const body = await r.text();
186
+ expect(body).toBe("<h1>custom error</h1>");
187
+ expect(body).not.toContain("secret detail");
188
+ const digest = createHash("sha256").update("secret detail\nat x").digest("hex").slice(0, 10);
189
+ expect(logs).toContain(`digest ${digest}`);
190
+ });
191
+ it("redirects with 307 and a Location header", async () => {
192
+ const r = await fetch(url("/redirect"), { headers: secret, redirect: "manual" });
193
+ expect(r.status).toBe(307);
194
+ expect(r.headers.get("location")).toBe("/login");
195
+ });
196
+ it("marks ISR responses from the cache", async () => {
197
+ const a = await fetch(url("/isr"), { headers: secret });
198
+ const first = await a.text();
199
+ expect(a.headers.get("x-krate-cache")).toBeNull();
200
+ const b = await fetch(url("/isr"), { headers: secret });
201
+ expect(b.headers.get("x-krate-cache")).toBe("HIT");
202
+ expect(await b.text()).toBe(first);
203
+ });
204
+ });
205
+ describe("/__krate/regions", () => {
206
+ const body = (extra = {}) => ({ route: "/regions", url: "/regions", method: "GET", headers: {}, ...extra });
207
+ it("streams frames as regions finish, not in document order, and ends with a count", async () => {
208
+ const { res, frames } = await regions(body({ regions: [{ id: "slow" }, { id: "fast" }, { id: "price" }], params: { id: "9" } }));
209
+ expect(res.headers.get("content-type")).toContain("application/x-ndjson");
210
+ expect(res.headers.get("cache-control")).toBe("no-store");
211
+ expect(frames[frames.length - 1]).toEqual({ type: "end", count: 3 });
212
+ const ids = frames.filter((f) => f.type === "region").map((f) => f.id);
213
+ expect(ids).toHaveLength(3);
214
+ expect(ids.indexOf("slow")).toBe(2); // the 250ms region is written last
215
+ const byId = Object.fromEntries(frames.filter((f) => f.type === "region").map((f) => [f.id, f.html]));
216
+ expect(byId).toEqual({ slow: "<i>slow</i>", fast: "<i>fast</i>", price: "<b>12/9</b>" });
217
+ });
218
+ it("reports a failing server component region as a fatal error frame with a digest", async () => {
219
+ const { frames } = await regions(body({ regions: [{ id: "bad" }, { id: "fast" }] }));
220
+ const bad = frames.find((f) => f.id === "bad");
221
+ expect(bad).toMatchObject({ type: "error", status: 500, fatal: true, error: "region failed" });
222
+ expect(bad.digest).toMatch(/^[0-9a-f]{10}$/);
223
+ expect(frames.find((f) => f.id === "fast")).toMatchObject({ type: "region", html: "<i>fast</i>" });
224
+ expect(frames[frames.length - 1]).toEqual({ type: "end", count: 2 });
225
+ });
226
+ it("falls back to the manifest's regions when the host sends no list", async () => {
227
+ const { frames } = await regions(body());
228
+ expect(frames.filter((f) => f.type !== "end").map((f) => f.id).sort()).toEqual(["bad", "fast", "price", "slow"]);
229
+ });
230
+ it("skips an unknown region id, so its baked content stays", async () => {
231
+ const { frames } = await regions(body({ regions: [{ id: "ghost" }] }));
232
+ expect(frames).toEqual([{ type: "skip", id: "ghost" }, { type: "end", count: 1 }]);
233
+ });
234
+ it("renders a coarse page region through the page ISR path", async () => {
235
+ const { frames } = await regions({ route: "/ssr/[id]", url: "/ssr/5", method: "GET", headers: {}, params: { id: "5" }, query: { q: "z" }, regions: [{ id: "page", kind: "page" }] });
236
+ expect(frames[0]).toMatchObject({ type: "region", id: "page", kind: "page", status: 200, title: "T 5" });
237
+ expect(String(frames[0].html)).toContain("<p>q=z</p>");
238
+ });
239
+ it("answers an unknown route with an error frame and an end frame", async () => {
240
+ const { frames } = await regions({ route: "/none", url: "/none", method: "GET", headers: {} });
241
+ expect(frames).toEqual([{ type: "error", status: 404, error: "no such page" }, { type: "end", count: 0 }]);
242
+ });
243
+ it("turns a malformed body into an error frame, not a crash", async () => {
244
+ const res = await fetch(url("/__krate/regions"), { method: "POST", headers: secret, body: "{nope" });
245
+ const frames = (await res.text()).split("\n").filter(Boolean).map((l) => JSON.parse(l));
246
+ expect(frames[0]).toMatchObject({ type: "error", status: 500 });
247
+ expect((await fetch(url("/__krate/ssr/health"))).status).toBe(200);
248
+ });
249
+ });
250
+ it("keeps rendered ISR pages across a restart", async () => {
251
+ // Warm an ISR variant, wait for the debounced write, bounce the process.
252
+ const first = await (await fetch(url("/isr"), { headers: secret })).text();
253
+ const deadline = Date.now() + 5000;
254
+ while (!fs.existsSync(isrFile) && Date.now() < deadline)
255
+ await new Promise((ok) => setTimeout(ok, 100));
256
+ expect(fs.existsSync(isrFile)).toBe(true);
257
+ const saved = JSON.parse(fs.readFileSync(isrFile, "utf-8"));
258
+ expect(saved.entries.some((e) => e.key === "/isr" && e.html === first)).toBe(true);
259
+ await stop();
260
+ await start();
261
+ const again = await fetch(url("/isr"), { headers: secret });
262
+ expect(again.headers.get("x-krate-cache")).toBe("HIT");
263
+ expect(await again.text()).toBe(first);
264
+ expect(logs).toContain("Loaded 1 persisted ISR entries");
265
+ }, 30000);
266
+ });
package/dist/server.d.ts CHANGED
@@ -2,13 +2,22 @@ export { getActionContext, headers, cookies, redirect } from './action-context.j
2
2
  export type { ActionContext, ActionCookies, ActionCookieOptions } from './action-context.js';
3
3
  export { revalidatePath, revalidateTag, unstable_cache, unstable_noStore } from './cache.js';
4
4
  export type { RevalidatePathType, UnstableCacheOptions } from './cache.js';
5
- export { getRequestContext, notFound } from './request-context.js';
5
+ export { getRequestContext, notFound, forbidden, unauthorized } from './request-context.js';
6
+ export { usePathname, useSearchParams, useParams, useRouter, useSelectedLayoutSegment, useSelectedLayoutSegments, permanentRedirect, } from './navigation-server.js';
7
+ export type { AppRouterInstance } from './navigation-server.js';
6
8
  export type { RequestContext, RequestCookies } from './request-context.js';
9
+ export { resolveMetadata, renderMetadataTags, metadataHeadTags } from './metadata.js';
10
+ export { renderSitemapXML, renderRobotsTXT, renderManifestJSON } from './metadata-routes.js';
11
+ export type { MetadataRoute, SitemapEntry, RobotsFile, RobotsRule, ManifestFile } from './metadata-routes.js';
12
+ export { ImageResponse } from './og.js';
13
+ export type { ImageResponseOptions } from './og.js';
14
+ export type { Metadata, ResolvingMetadata, ResolvingViewport, Viewport, MetadataSegment, MetadataModule, MetadataProps } from './metadata.js';
7
15
  export declare function createSignal<T>(initial: T): [() => T, (v: T | ((prev: T) => T)) => void];
8
16
  export declare function createEffect(_fn: () => void): () => void;
9
17
  export declare function createMemo<T>(fn: () => T): () => T;
10
18
  export declare function krateDerived<T>(fn: () => T, _triggers?: () => unknown): () => T;
11
19
  export declare function krateHook<T>(value: T | (() => T)): () => T;
20
+ export declare function krateParam<T>(value: T | (() => T)): T;
12
21
  export declare function onCleanup(_fn: () => void): void;
13
22
  export declare function onMount(_fn: () => void): void;
14
23
  interface RawHTML {
@@ -53,6 +62,8 @@ type ClientRender = (component: unknown, props: Record<string, unknown>, childre
53
62
  * browser. Children are rendered on the server and passed as HTML.
54
63
  */
55
64
  export declare function clientBoundary(moduleId: string, exportName: string, src: string, impl: unknown, render: ClientRender): unknown;
65
+ export declare const HEAD_OPEN = "<!--krate-head-->";
66
+ export declare const HEAD_CLOSE = "<!--/krate-head-->";
56
67
  export declare function Head(props: {
57
68
  children?: JSXNode;
58
69
  }): JSXNode;
@@ -84,5 +95,6 @@ export declare function Icon(_props: {
84
95
  }): JSXNode;
85
96
  export declare function SyntaxHighlight(props: {
86
97
  lang?: string;
98
+ highlight?: string;
87
99
  children?: any;
88
100
  }): JSXNode;
package/dist/server.js CHANGED
@@ -1,8 +1,14 @@
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';
4
+ import { highlight as highlightCode, trimSpace } from './highlight.js';
3
5
  export { getActionContext, headers, cookies, redirect } from './action-context.js';
4
6
  export { revalidatePath, revalidateTag, unstable_cache, unstable_noStore } from './cache.js';
5
- export { getRequestContext, notFound } from './request-context.js';
7
+ export { getRequestContext, notFound, forbidden, unauthorized } from './request-context.js';
8
+ export { usePathname, useSearchParams, useParams, useRouter, useSelectedLayoutSegment, useSelectedLayoutSegments, permanentRedirect, } from './navigation-server.js';
9
+ export { resolveMetadata, renderMetadataTags, metadataHeadTags } from './metadata.js';
10
+ export { renderSitemapXML, renderRobotsTXT, renderManifestJSON } from './metadata-routes.js';
11
+ export { ImageResponse } from './og.js';
6
12
  // Signal (server: returns initial value, no reactivity)
7
13
  export function createSignal(initial) {
8
14
  let value = initial;
@@ -40,6 +46,10 @@ export function krateHook(value) {
40
46
  return value;
41
47
  return () => value;
42
48
  }
49
+ // Reads a custom hook parameter that a call site passed as a derived getter.
50
+ export function krateParam(value) {
51
+ return typeof value === "function" && derivedGetters.has(value) ? value() : value;
52
+ }
43
53
  export function onCleanup(_fn) {
44
54
  // No-op on server
45
55
  }
@@ -117,6 +127,22 @@ function asyncInSyncRender(where) {
117
127
  `are rendered per request by the SSR sidecar through renderToStringAsync; a synchronous ` +
118
128
  `render (for example inside goComponent children) cannot await them.`);
119
129
  }
130
+ function isClassComponent(fn) {
131
+ return typeof fn === "function" && fn.prototype && typeof fn.prototype.render === "function";
132
+ }
133
+ function classFallback(type, instance, error) {
134
+ if (typeof type.getDerivedStateFromError !== "function")
135
+ throw error;
136
+ instance.state = { ...(instance.state || {}), ...(type.getDerivedStateFromError(error) || {}) };
137
+ try {
138
+ if (typeof instance.componentDidCatch === "function")
139
+ instance.componentDidCatch(error, { componentStack: "" });
140
+ }
141
+ catch {
142
+ // A throwing componentDidCatch must not hide the original render error.
143
+ }
144
+ return instance.render();
145
+ }
120
146
  function renderNode(node) {
121
147
  if (node == null || node === false)
122
148
  return "";
@@ -139,31 +165,68 @@ function renderNode(node) {
139
165
  function isServerAction(v) {
140
166
  return typeof v === "function" && typeof v.actionUrl === "string";
141
167
  }
168
+ const UNITLESS = new Set([
169
+ "animation-iteration-count", "aspect-ratio", "border-image-outset", "border-image-slice",
170
+ "border-image-width", "box-flex", "box-flex-group", "box-ordinal-group", "column-count",
171
+ "columns", "flex", "flex-grow", "flex-positive", "flex-shrink", "flex-negative", "flex-order",
172
+ "grid-area", "grid-row", "grid-row-end", "grid-row-span", "grid-row-start", "grid-column",
173
+ "grid-column-end", "grid-column-span", "grid-column-start", "font-weight", "line-clamp",
174
+ "line-height", "opacity", "order", "orphans", "scale", "tab-size", "widows", "z-index", "zoom",
175
+ "fill-opacity", "flood-opacity", "stop-opacity", "stroke-dasharray", "stroke-dashoffset",
176
+ "stroke-miterlimit", "stroke-opacity", "stroke-width",
177
+ ]);
178
+ const URL_ATTRS = new Set(["href", "src", "action", "formaction", "xlink:href"]);
179
+ // eslint-disable-next-line no-control-regex
180
+ 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;
181
+ const BLOCKED_URL = "javascript:throw new Error('React has blocked a javascript: URL as a security precaution.')";
182
+ function cssName(key) {
183
+ if (key.startsWith("--"))
184
+ return key;
185
+ const name = key.replace(/[A-Z]/g, (c) => "-" + c.toLowerCase());
186
+ return name.startsWith("ms-") ? "-" + name : name;
187
+ }
188
+ function styleString(value) {
189
+ const out = [];
190
+ for (const key of Object.keys(value)) {
191
+ const v = value[key];
192
+ if (v == null || typeof v === "boolean" || v === "")
193
+ continue;
194
+ const prop = cssName(key);
195
+ const bare = prop.replace(/^-(webkit|moz|ms|o)-/, "");
196
+ const text = typeof v === "number" && v !== 0 && !prop.startsWith("--") && !UNITLESS.has(bare)
197
+ ? v + "px"
198
+ : String(v);
199
+ out.push(prop + ":" + text);
200
+ }
201
+ return out.join(";");
202
+ }
142
203
  function setAttr(key, val) {
204
+ if (key === "children" || key === "key" || key === "ref" || key === "dangerouslySetInnerHTML")
205
+ return "";
206
+ const name = ATTR_ALIASES[key] || key;
143
207
  if (val == null || val === false)
144
208
  return "";
145
209
  if (val === true)
146
- return ` ${key}`;
147
- if (key === "action" && isServerAction(val)) {
210
+ return ` ${name}`;
211
+ if (name === "action" && isServerAction(val)) {
148
212
  return ` action="${escapeHTML(val.actionUrl)}" data-krate-action`;
149
213
  }
150
- if ((key === "formAction" || key === "formaction") && isServerAction(val)) {
214
+ if (name === "formaction" && isServerAction(val)) {
151
215
  return ` formaction="${escapeHTML(val.actionUrl)}" formmethod="post" data-krate-action`;
152
216
  }
153
217
  // Client function actions run only after hydration; they have no HTML form.
154
218
  if (typeof val === "function")
155
219
  return "";
156
- if (key === "class")
157
- return ` class="${escapeHTML(String(val))}"`;
158
220
  if (key === "style" && typeof val === "object") {
159
- const css = Object.entries(val)
160
- .map(([k, v]) => `${k}:${v}`)
161
- .join(";");
162
- return ` style="${escapeHTML(css)}"`;
221
+ const css = styleString(val);
222
+ return css ? ` style="${escapeHTML(css)}"` : "";
163
223
  }
164
224
  if (key.startsWith("on") || key.startsWith("__"))
165
225
  return "";
166
- return ` ${key}="${escapeHTML(String(val))}"`;
226
+ let text = String(val);
227
+ if (URL_ATTRS.has(name.toLowerCase()) && JS_URL.test(text))
228
+ text = BLOCKED_URL;
229
+ return ` ${name}="${escapeHTML(text)}"`;
167
230
  }
168
231
  export function renderToString(node) {
169
232
  return renderNode(node);
@@ -215,15 +278,48 @@ async function resolveTree(node) {
215
278
  const entries = await Promise.all(Object.entries(props).map(async ([k, v]) => [k, isJSXValue(v) ? await resolveTree(v) : v]));
216
279
  callProps = { ...Object.fromEntries(entries), children: await resolveTree(children) };
217
280
  }
281
+ if (isClassComponent(fn)) {
282
+ const instance = new fn(callProps);
283
+ try {
284
+ return await resolveTree(instance.render());
285
+ }
286
+ catch (error) {
287
+ return resolveTree(classFallback(fn, instance, error));
288
+ }
289
+ }
218
290
  let out = fn(callProps);
219
291
  if (isThenable(out))
220
292
  out = await out;
221
293
  return resolveTree(out);
222
294
  }
295
+ // rawTextContent renders the children of <script>/<style>: their text is raw
296
+ // text in HTML, so entity escaping would corrupt JSON-LD and inline code. The
297
+ // static compiler emits it the same way; only a sequence that could end the
298
+ // element or open a comment is neutralised.
299
+ function rawTextContent(tag, children) {
300
+ let out = "";
301
+ for (const c of children) {
302
+ if (typeof c === "string")
303
+ out += c;
304
+ else
305
+ out += renderNode(c);
306
+ }
307
+ out = out.replace(tag === "script" ? /<\/(script)/gi : /<\/(style)/gi, "<\\/$1");
308
+ return tag === "script" ? out.replace(/<!--/g, "<\\!--") : out;
309
+ }
223
310
  function renderElement(el) {
224
311
  const { type, props, children } = el;
225
312
  // Component
226
313
  if (typeof type === "function") {
314
+ if (isClassComponent(type)) {
315
+ const instance = new type({ ...props, children });
316
+ try {
317
+ return renderNode(instance.render());
318
+ }
319
+ catch (error) {
320
+ return renderNode(classFallback(type, instance, error));
321
+ }
322
+ }
227
323
  const result = type({ ...props, children });
228
324
  if (isThenable(result))
229
325
  throw asyncInSyncRender(`<${componentName(type)}>`);
@@ -240,7 +336,12 @@ function renderElement(el) {
240
336
  if (VOID_ELEMENTS.has(tag)) {
241
337
  return `<${tag}${attrs}>`;
242
338
  }
243
- const inner = children.map(renderNode).join("");
339
+ const dangerous = props.dangerouslySetInnerHTML;
340
+ const inner = dangerous && typeof dangerous === "object" && typeof dangerous.__html === "string"
341
+ ? dangerous.__html
342
+ : tag === "script" || tag === "style"
343
+ ? rawTextContent(tag, children)
344
+ : children.map(renderNode).join("");
244
345
  return `<${tag}${attrs}>${inner}</${tag}>`;
245
346
  }
246
347
  // Streaming SSR via Suspense
@@ -361,10 +462,15 @@ export function clientBoundary(moduleId, exportName, src, impl, render) {
361
462
  return Boundary;
362
463
  }
363
464
  // Built-in Components (server stubs)
364
- // Head - renders children into the page head at build time.
365
- // On the server, we just render children; the build pipeline extracts them.
465
+ // Head - renders children into the page head. At build time the compiler
466
+ // hoists them. In a request-time render the children come out between two
467
+ // comment markers, and the host (ssr-core takeHead) moves what sits between
468
+ // them into the document <head> of the response instead of leaving it in the
469
+ // body.
470
+ export const HEAD_OPEN = "<!--krate-head-->";
471
+ export const HEAD_CLOSE = "<!--/krate-head-->";
366
472
  export function Head(props) {
367
- return props.children ?? "";
473
+ return [raw(HEAD_OPEN), props.children ?? "", raw(HEAD_CLOSE)];
368
474
  }
369
475
  // Script - renders a <script> tag.
370
476
  export function Script(props) {
@@ -430,10 +536,19 @@ export function Image(props) {
430
536
  export function Icon(_props) {
431
537
  return raw("<span></span>");
432
538
  }
433
- // SyntaxHighlight - renders a <pre><code> block (Go compiler handles chroma highlighting at build time).
539
+ // SyntaxHighlight - renders a <pre><code> block. The Go compiler highlights code it knows at build
540
+ // time; code that only exists at request time is highlighted here with the same lexers (see
541
+ // highlight.ts), when the language's tables are loaded and the text is within its limits, and is
542
+ // written as plain text otherwise.
434
543
  export function SyntaxHighlight(props) {
435
544
  const lang = props.lang || "";
436
545
  const code = props.children != null ? String(props.children) : "";
546
+ const lines = props.highlight || "";
547
+ const html = lang ? highlightCode(trimSpace(code), lang, lines || undefined) : null;
548
+ if (html !== null) {
549
+ const attr = lines ? ` data-highlight-lines="${escapeHTML(lines)}"` : "";
550
+ return raw(`<pre class="chroma"${attr}><code class="language-${escapeHTML(lang)}">${html}</code></pre>`);
551
+ }
437
552
  const cls = lang ? `chroma language-${lang}` : "chroma";
438
553
  return raw(`<pre class="chroma"><code class="${escapeHTML(cls)}">${escapeHTML(code)}</code></pre>`);
439
554
  }
@@ -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', () => {
@@ -0,0 +1 @@
1
+ export declare function sha256Hex(input: string): string;
package/dist/sha256.js ADDED
@@ -0,0 +1,66 @@
1
+ // Portable synchronous SHA-256 (no node:crypto, no Web Crypto) so the render
2
+ // core can compute the same error digest on Node, Workers and edge hosts.
3
+ const K = new Uint32Array([
4
+ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
5
+ 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
6
+ 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
7
+ 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
8
+ 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
9
+ 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
10
+ 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
11
+ 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
12
+ ]);
13
+ export function sha256Hex(input) {
14
+ const msg = new TextEncoder().encode(input);
15
+ const bitLen = msg.length * 8;
16
+ const total = (((msg.length + 9 + 63) >> 6) << 6);
17
+ const buf = new Uint8Array(total);
18
+ buf.set(msg);
19
+ buf[msg.length] = 0x80;
20
+ const view = new DataView(buf.buffer);
21
+ view.setUint32(total - 8, Math.floor(bitLen / 0x100000000), false);
22
+ view.setUint32(total - 4, bitLen >>> 0, false);
23
+ const h = new Uint32Array([
24
+ 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
25
+ ]);
26
+ const w = new Uint32Array(64);
27
+ const rotr = (x, n) => (x >>> n) | (x << (32 - n));
28
+ for (let off = 0; off < total; off += 64) {
29
+ for (let i = 0; i < 16; i++)
30
+ w[i] = view.getUint32(off + i * 4, false);
31
+ for (let i = 16; i < 64; i++) {
32
+ const s0 = rotr(w[i - 15], 7) ^ rotr(w[i - 15], 18) ^ (w[i - 15] >>> 3);
33
+ const s1 = rotr(w[i - 2], 17) ^ rotr(w[i - 2], 19) ^ (w[i - 2] >>> 10);
34
+ w[i] = (w[i - 16] + s0 + w[i - 7] + s1) | 0;
35
+ }
36
+ let [a, b, c, d, e, f, g, hh] = h;
37
+ for (let i = 0; i < 64; i++) {
38
+ const S1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25);
39
+ const ch = (e & f) ^ (~e & g);
40
+ const t1 = (hh + S1 + ch + K[i] + w[i]) | 0;
41
+ const S0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22);
42
+ const maj = (a & b) ^ (a & c) ^ (b & c);
43
+ const t2 = (S0 + maj) | 0;
44
+ hh = g;
45
+ g = f;
46
+ f = e;
47
+ e = (d + t1) | 0;
48
+ d = c;
49
+ c = b;
50
+ b = a;
51
+ a = (t1 + t2) | 0;
52
+ }
53
+ h[0] += a;
54
+ h[1] += b;
55
+ h[2] += c;
56
+ h[3] += d;
57
+ h[4] += e;
58
+ h[5] += f;
59
+ h[6] += g;
60
+ h[7] += hh;
61
+ }
62
+ let out = "";
63
+ for (let i = 0; i < 8; i++)
64
+ out += h[i].toString(16).padStart(8, "0");
65
+ return out;
66
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,13 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { createHash } from "node:crypto";
3
+ import { sha256Hex } from "./sha256.js";
4
+ describe("portable sha256", () => {
5
+ it("matches node:crypto across block boundaries and UTF-8", () => {
6
+ for (const s of ["", "abc", "a".repeat(55), "a".repeat(56), "a".repeat(63), "a".repeat(64), "a".repeat(1000), "héllo 世界 😀"]) {
7
+ expect(sha256Hex(s)).toBe(createHash("sha256").update(s).digest("hex"));
8
+ }
9
+ });
10
+ it("error digest fixed vector", () => {
11
+ expect(sha256Hex("boom\nat x").slice(0, 10)).toBe("8a2474a04d");
12
+ });
13
+ });