@krate/runtime 0.5.0-beta.3 → 0.5.0-rc.10

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 (219) hide show
  1. package/dist/action-context.js +1 -1
  2. package/dist/actions.d.ts +7 -0
  3. package/dist/actions.js +34 -10
  4. package/dist/after.d.ts +28 -0
  5. package/dist/after.js +48 -0
  6. package/dist/assets-static.d.ts +10 -1
  7. package/dist/assets-static.js +10 -2
  8. package/dist/base-path.d.ts +7 -0
  9. package/dist/base-path.js +20 -0
  10. package/dist/boundary.js +1 -1
  11. package/dist/builtin-tags.d.ts +12 -0
  12. package/dist/builtin-tags.js +42 -0
  13. package/dist/cache-adapter.js +1 -1
  14. package/dist/cache-scope.d.ts +8 -0
  15. package/dist/cache-scope.js +14 -1
  16. package/dist/cloudflare-workers.d.ts +2 -0
  17. package/dist/cloudflare-workers.js +27 -0
  18. package/dist/context.d.ts +5 -0
  19. package/dist/context.js +28 -17
  20. package/dist/dev-overlay.d.ts +54 -3
  21. package/dist/dev-overlay.js +496 -91
  22. package/dist/dom.d.ts +4 -0
  23. package/dist/dom.js +62 -16
  24. package/dist/effects.js +43 -10
  25. package/dist/events.d.ts +2 -0
  26. package/dist/events.js +18 -0
  27. package/dist/flight-props.d.ts +7 -0
  28. package/dist/flight-props.js +105 -0
  29. package/dist/handler-html.js +4 -4
  30. package/dist/handler-routing.d.ts +2 -23
  31. package/dist/handler-routing.js +9 -190
  32. package/dist/handler-segments.d.ts +6 -0
  33. package/dist/handler-segments.js +18 -4
  34. package/dist/head-tags.d.ts +9 -0
  35. package/dist/head-tags.js +93 -6
  36. package/dist/highlight-bind.js +1 -1
  37. package/dist/highlight.d.ts +3 -2
  38. package/dist/highlight.js +17 -12
  39. package/dist/hints.d.ts +25 -2
  40. package/dist/hints.js +147 -74
  41. package/dist/index.d.ts +2 -0
  42. package/dist/index.js +3 -0
  43. package/dist/island-swap.d.ts +47 -0
  44. package/dist/island-swap.js +635 -0
  45. package/dist/jsx-dev-runtime.d.ts +1 -1
  46. package/dist/jsx-types.d.ts +99 -3
  47. package/dist/krate-core.js +1 -1
  48. package/dist/krate-dev.js +407 -80
  49. package/dist/krate-f-actions.js +1 -1
  50. package/dist/krate-f-classes.js +1 -1
  51. package/dist/krate-f-highlight.js +1 -1
  52. package/dist/krate-f-list.js +1 -1
  53. package/dist/krate-f-navigation.js +1 -1
  54. package/dist/krate-f-router-lite.js +1 -1
  55. package/dist/krate-f-router.js +1 -1
  56. package/dist/krate-features.json +455 -0
  57. package/dist/krate-hydrate-lite.js +5 -5
  58. package/dist/krate-hydrate.js +5 -5
  59. package/dist/krate-island-swap.js +1 -0
  60. package/dist/krate-runtime.js +5 -5
  61. package/dist/krate-suspense.js +1 -1
  62. package/dist/list.d.ts +14 -4
  63. package/dist/list.js +30 -23
  64. package/dist/metadata.js +5 -2
  65. package/dist/navigation-react.d.ts +13 -0
  66. package/dist/navigation-react.js +86 -0
  67. package/dist/navigation.d.ts +19 -0
  68. package/dist/navigation.js +35 -0
  69. package/dist/node-server.js +3 -3
  70. package/dist/og.js +1 -1
  71. package/dist/platform.d.ts +52 -0
  72. package/dist/platform.js +57 -0
  73. package/dist/react-compat.d.ts +39 -0
  74. package/dist/react-compat.js +359 -0
  75. package/dist/react-server.d.ts +63 -0
  76. package/dist/react-server.js +125 -0
  77. package/dist/region-wire.d.ts +10 -0
  78. package/dist/region-wire.js +154 -0
  79. package/dist/request-context.js +1 -1
  80. package/dist/request-extras.d.ts +4 -0
  81. package/dist/request-extras.js +51 -0
  82. package/dist/resp.js +1 -1
  83. package/dist/route-source.d.ts +39 -0
  84. package/dist/route-source.js +532 -0
  85. package/dist/router-lite.js +3 -9
  86. package/dist/router.d.ts +1 -1
  87. package/dist/router.js +675 -100
  88. package/dist/server-handler.d.ts +69 -1
  89. package/dist/server-handler.js +515 -96
  90. package/dist/server-renderer.js +16 -7
  91. package/dist/server.d.ts +73 -16
  92. package/dist/server.js +619 -102
  93. package/dist/sha256.js +9 -9
  94. package/dist/signal.js +47 -20
  95. package/dist/site-config.d.ts +15 -0
  96. package/dist/site-config.js +28 -0
  97. package/dist/slot.d.ts +12 -0
  98. package/dist/slot.js +23 -0
  99. package/dist/ssr-core.d.ts +2 -0
  100. package/dist/ssr-core.js +12 -4
  101. package/dist/suspense.js +34 -2
  102. package/dist/testing.d.ts +62 -0
  103. package/dist/testing.js +90 -0
  104. package/dist/use-id.js +1 -1
  105. package/package.json +28 -3
  106. package/dist/action-context.test.d.ts +0 -1
  107. package/dist/action-context.test.js +0 -72
  108. package/dist/actions.test.d.ts +0 -1
  109. package/dist/actions.test.js +0 -477
  110. package/dist/cache-adapter.test.d.ts +0 -1
  111. package/dist/cache-adapter.test.js +0 -244
  112. package/dist/cache.test.d.ts +0 -1
  113. package/dist/cache.test.js +0 -233
  114. package/dist/class-component.test.d.ts +0 -1
  115. package/dist/class-component.test.js +0 -462
  116. package/dist/class-helpers.test.d.ts +0 -1
  117. package/dist/class-helpers.test.js +0 -169
  118. package/dist/context.test.d.ts +0 -1
  119. package/dist/context.test.js +0 -57
  120. package/dist/derived.test.d.ts +0 -1
  121. package/dist/derived.test.js +0 -140
  122. package/dist/dev-overlay.test.d.ts +0 -1
  123. package/dist/dev-overlay.test.js +0 -152
  124. package/dist/discrete.test.d.ts +0 -1
  125. package/dist/discrete.test.js +0 -100
  126. package/dist/dom.test.d.ts +0 -1
  127. package/dist/dom.test.js +0 -31
  128. package/dist/effect-errors.test.d.ts +0 -1
  129. package/dist/effect-errors.test.js +0 -163
  130. package/dist/effects.test.d.ts +0 -1
  131. package/dist/effects.test.js +0 -485
  132. package/dist/events.test.d.ts +0 -1
  133. package/dist/events.test.js +0 -447
  134. package/dist/handler-html.test.d.ts +0 -1
  135. package/dist/handler-html.test.js +0 -256
  136. package/dist/handler-routing.test.d.ts +0 -1
  137. package/dist/handler-routing.test.js +0 -99
  138. package/dist/handler-segments.test.d.ts +0 -1
  139. package/dist/handler-segments.test.js +0 -217
  140. package/dist/head-tags.test.d.ts +0 -1
  141. package/dist/head-tags.test.js +0 -131
  142. package/dist/highlight-bind.test.d.ts +0 -1
  143. package/dist/highlight-bind.test.js +0 -124
  144. package/dist/highlight.test.d.ts +0 -1
  145. package/dist/highlight.test.js +0 -56
  146. package/dist/lanes.test.d.ts +0 -1
  147. package/dist/lanes.test.js +0 -59
  148. package/dist/list.test.d.ts +0 -1
  149. package/dist/list.test.js +0 -344
  150. package/dist/metadata.test.d.ts +0 -1
  151. package/dist/metadata.test.js +0 -167
  152. package/dist/navigation.test.d.ts +0 -1
  153. package/dist/navigation.test.js +0 -130
  154. package/dist/node-server.test.d.ts +0 -1
  155. package/dist/node-server.test.js +0 -492
  156. package/dist/optimistic-lanes.test.d.ts +0 -1
  157. package/dist/optimistic-lanes.test.js +0 -45
  158. package/dist/patterns.test.d.ts +0 -1
  159. package/dist/patterns.test.js +0 -98
  160. package/dist/portal.test.d.ts +0 -1
  161. package/dist/portal.test.js +0 -99
  162. package/dist/react-effects.test.d.ts +0 -1
  163. package/dist/react-effects.test.js +0 -96
  164. package/dist/react-suspense.test.d.ts +0 -1
  165. package/dist/react-suspense.test.js +0 -194
  166. package/dist/react.test.d.ts +0 -1
  167. package/dist/react.test.js +0 -60
  168. package/dist/react19.test.d.ts +0 -1
  169. package/dist/react19.test.js +0 -176
  170. package/dist/reactivity-core.test.d.ts +0 -1
  171. package/dist/reactivity-core.test.js +0 -152
  172. package/dist/reconcile.test.d.ts +0 -1
  173. package/dist/reconcile.test.js +0 -110
  174. package/dist/refs.test.d.ts +0 -1
  175. package/dist/refs.test.js +0 -257
  176. package/dist/router-layout.test.d.ts +0 -1
  177. package/dist/router-layout.test.js +0 -249
  178. package/dist/router-nav.test.d.ts +0 -1
  179. package/dist/router-nav.test.js +0 -464
  180. package/dist/router-slots.test.d.ts +0 -1
  181. package/dist/router-slots.test.js +0 -144
  182. package/dist/router-speculation.test.d.ts +0 -1
  183. package/dist/router-speculation.test.js +0 -25
  184. package/dist/router-styles.test.d.ts +0 -1
  185. package/dist/router-styles.test.js +0 -98
  186. package/dist/router.test.d.ts +0 -1
  187. package/dist/router.test.js +0 -36
  188. package/dist/server-async.test.d.ts +0 -1
  189. package/dist/server-async.test.js +0 -216
  190. package/dist/server-handler.test.d.ts +0 -1
  191. package/dist/server-handler.test.js +0 -535
  192. package/dist/server-highlight.test.d.ts +0 -1
  193. package/dist/server-highlight.test.js +0 -32
  194. package/dist/server-renderer.test.d.ts +0 -1
  195. package/dist/server-renderer.test.js +0 -266
  196. package/dist/server.test.d.ts +0 -1
  197. package/dist/server.test.js +0 -88
  198. package/dist/sha256.test.d.ts +0 -1
  199. package/dist/sha256.test.js +0 -13
  200. package/dist/signal-lanes.test.d.ts +0 -1
  201. package/dist/signal-lanes.test.js +0 -32
  202. package/dist/signal.test.d.ts +0 -1
  203. package/dist/signal.test.js +0 -68
  204. package/dist/slots.test.d.ts +0 -1
  205. package/dist/slots.test.js +0 -169
  206. package/dist/snapshots.test.d.ts +0 -1
  207. package/dist/snapshots.test.js +0 -208
  208. package/dist/ssr-core-behavior.test.d.ts +0 -1
  209. package/dist/ssr-core-behavior.test.js +0 -620
  210. package/dist/ssr-core.test.d.ts +0 -1
  211. package/dist/ssr-core.test.js +0 -324
  212. package/dist/static-memory.test.d.ts +0 -1
  213. package/dist/static-memory.test.js +0 -26
  214. package/dist/storage.test.d.ts +0 -1
  215. package/dist/storage.test.js +0 -46
  216. package/dist/suspense-actions.test.d.ts +0 -1
  217. package/dist/suspense-actions.test.js +0 -72
  218. package/dist/suspense.test.d.ts +0 -1
  219. package/dist/suspense.test.js +0 -518
@@ -1,266 +0,0 @@
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
- });
@@ -1 +0,0 @@
1
- export {};
@@ -1,88 +0,0 @@
1
- import { describe, it, expect } from 'vitest';
2
- import { jsx, renderToString, goComponent } from './server';
3
- describe('renderToString', () => {
4
- it('renders nested elements and escapes text', () => {
5
- const node = jsx('div', { class: 'x', children: [jsx('span', { children: 'a & b' })] });
6
- expect(renderToString(node)).toBe('<div class="x"><span>a &amp; b</span></div>');
7
- });
8
- it('renders void elements without a close tag', () => {
9
- expect(renderToString(jsx('img', { src: '/x.png', alt: 'y' }))).toBe('<img src="/x.png" alt="y">');
10
- });
11
- it('invokes function components', () => {
12
- const Comp = () => jsx('p', { children: 'hi' });
13
- expect(renderToString(jsx(Comp, {}))).toBe('<p>hi</p>');
14
- });
15
- it('drops event and internal props', () => {
16
- const node = jsx('button', { onClick: () => undefined, children: 'x' });
17
- expect(renderToString(node)).toBe('<button>x</button>');
18
- });
19
- it('omits null/false-valued attributes', () => {
20
- expect(renderToString(jsx('input', { disabled: false, value: null }))).toBe('<input>');
21
- expect(renderToString(jsx('input', { disabled: true }))).toBe('<input disabled>');
22
- });
23
- it('passes raw HTML through without escaping', () => {
24
- expect(renderToString({ __raw: '<b>hi</b>' })).toBe('<b>hi</b>');
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
- });
46
- });
47
- describe('goComponent', () => {
48
- it('inlines baked HTML for an annotated server-tier call site', () => {
49
- const baked = { 'gc3_5_Badge': '<span class="badge">Hi</span>' };
50
- const node = goComponent('Badge', 'server', baked, { __krateGoId: 'gc3_5_Badge', label: 'Hi' });
51
- expect(renderToString(node)).toBe('<span class="badge">Hi</span>');
52
- });
53
- it('emits a marker for runtime-tier calls, encoding props + children', () => {
54
- const node = goComponent('Clock', 'runtime', null, { zone: 'UTC', children: ['a ', jsx('b', { children: 'c' })] }, 45);
55
- const html = renderToString(node);
56
- const m = html.match(/^<!--krate-go:Clock:(\d+):([A-Za-z0-9_-]+)-->$/);
57
- expect(m).not.toBeNull();
58
- expect(m[1]).toBe('45');
59
- const b64 = m[2].replace(/-/g, '+').replace(/_/g, '/');
60
- const payload = JSON.parse(Buffer.from(b64, 'base64').toString('utf8'));
61
- expect(payload.zone).toBe('UTC');
62
- expect(payload.children).toBe('a <b>c</b>');
63
- });
64
- it('falls back to a marker when a server call site is not in the baked map', () => {
65
- const node = goComponent('Badge', 'server', {}, { __krateGoId: 'missing', label: 'Hi' });
66
- expect(renderToString(node)).toMatch(/^<!--krate-go:Badge:0:/);
67
- });
68
- });
69
- describe('server actions', () => {
70
- it('renders an action function as a POST form endpoint', () => {
71
- const action = Object.assign(() => undefined, {
72
- actionUrl: '/base/__krate/action/a123',
73
- });
74
- const html = renderToString(jsx('form', { action, children: [] }));
75
- expect(html).toContain('action="/base/__krate/action/a123"');
76
- expect(html).toContain('method="post"');
77
- expect(html).toContain('data-krate-action');
78
- });
79
- it('renders a formAction function as a POST submit endpoint', () => {
80
- const action = Object.assign(() => undefined, {
81
- actionUrl: '/__krate/action/a456',
82
- });
83
- const html = renderToString(jsx('button', { formAction: action, children: 'go' }));
84
- expect(html).toContain('formaction="/__krate/action/a456"');
85
- expect(html).toContain('formmethod="post"');
86
- expect(html).toContain('data-krate-action');
87
- });
88
- });
@@ -1 +0,0 @@
1
- export {};
@@ -1,13 +0,0 @@
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
- });
@@ -1 +0,0 @@
1
- export {};
@@ -1,32 +0,0 @@
1
- import { describe, it, expect, beforeEach } from 'vitest';
2
- // Only signal.ts: the commit snapshot of React state must not depend on the
3
- // effect scheduler (effects.ts) being loaded.
4
- import { createSignal, createEffect, disposeAll, krateHookState } from './signal';
5
- const tick = () => new Promise((r) => setTimeout(r, 0));
6
- async function settle() {
7
- for (let i = 0; i < 4; i++)
8
- await tick();
9
- }
10
- describe('React state commits without the effect scheduler', () => {
11
- beforeEach(() => disposeAll());
12
- it('keeps a promise-driven state write when a plain signal is written in a later microtask', async () => {
13
- const [user, setUser] = createSignal('nobody', krateHookState);
14
- const [flag, setFlag] = createSignal(false);
15
- const seen = [];
16
- createEffect(() => void seen.push(user() + '/' + flag()));
17
- await Promise.resolve().then(() => {
18
- setUser('grace');
19
- queueMicrotask(() => setFlag(true));
20
- });
21
- await settle();
22
- // Read outside rendering: the committed value.
23
- expect(user()).toBe('grace');
24
- expect(seen[seen.length - 1]).toBe('grace/true');
25
- });
26
- it('commits a state write made outside any event', async () => {
27
- const [n, setN] = createSignal(0, krateHookState);
28
- setTimeout(() => setN(4), 0);
29
- await settle();
30
- expect(n()).toBe(4);
31
- });
32
- });
@@ -1 +0,0 @@
1
- export {};
@@ -1,68 +0,0 @@
1
- import { describe, it, expect, beforeEach } from 'vitest';
2
- import { createSignal, createEffect, createMemo, onCleanup, disposeAll, } from './signal';
3
- const flush = () => new Promise((r) => setTimeout(r, 0));
4
- describe('createSignal', () => {
5
- beforeEach(() => disposeAll());
6
- it('reads and writes values', () => {
7
- const [n, setN] = createSignal(1);
8
- expect(n()).toBe(1);
9
- setN(2);
10
- expect(n()).toBe(2);
11
- setN((p) => p + 3);
12
- expect(n()).toBe(5);
13
- });
14
- it('does not notify when the value is unchanged', async () => {
15
- const [n, setN] = createSignal(1);
16
- let runs = 0;
17
- createEffect(() => {
18
- n();
19
- runs++;
20
- });
21
- await flush();
22
- const before = runs;
23
- setN(1);
24
- await flush();
25
- expect(runs).toBe(before);
26
- });
27
- it('runs dependent effects with the new value', async () => {
28
- const [n, setN] = createSignal(0);
29
- let seen = -1;
30
- createEffect(() => {
31
- seen = n();
32
- });
33
- setN(7);
34
- await flush();
35
- expect(seen).toBe(7);
36
- });
37
- });
38
- describe('createMemo', () => {
39
- beforeEach(() => disposeAll());
40
- it('caches until a dependency changes', async () => {
41
- const [n, setN] = createSignal(2);
42
- let computations = 0;
43
- const doubled = createMemo(() => {
44
- computations++;
45
- return n() * 2;
46
- });
47
- await flush();
48
- expect(doubled()).toBe(4);
49
- expect(doubled()).toBe(4);
50
- expect(computations).toBe(1);
51
- setN(5);
52
- await flush();
53
- expect(doubled()).toBe(10);
54
- });
55
- });
56
- describe('onCleanup / disposeAll', () => {
57
- it('runs cleanups when the world is disposed', async () => {
58
- let cleaned = false;
59
- createEffect(() => {
60
- onCleanup(() => {
61
- cleaned = true;
62
- });
63
- });
64
- await flush();
65
- disposeAll();
66
- expect(cleaned).toBe(true);
67
- });
68
- });
@@ -1 +0,0 @@
1
- export {};
@@ -1,169 +0,0 @@
1
- import { describe, it, expect, beforeEach } from 'vitest';
2
- import { readFileSync } from 'node:fs';
3
- import { fileURLToPath } from 'node:url';
4
- import { dirname, resolve } from 'node:path';
5
- import { krateCondSwap, krateCondDetached, krateCondReset, krateSanitizeAttr, BLOCKED_URL } from './slots';
6
- import { createSignal, createEffect } from './signal';
7
- import { reconcileTrees } from './reconcile';
8
- const tick = () => new Promise((r) => setTimeout(r, 0));
9
- function startMarker(root, id) {
10
- const w = document.createTreeWalker(root, NodeFilter.SHOW_COMMENT);
11
- while (w.nextNode()) {
12
- if (w.currentNode.nodeValue === 'k:' + id)
13
- return w.currentNode;
14
- }
15
- throw new Error('marker not found: ' + id);
16
- }
17
- describe('krateCondSwap', () => {
18
- // happy-dom does not parse <tr> inside <template> per spec, so the
19
- // table-context case is covered by the Go emitter tests and the browser
20
- // conformance suite; the swap mechanics are identical for any element.
21
- it('swaps the active branch with the template branch', () => {
22
- document.body.innerHTML =
23
- '<ol><!--k:c1--><li>yes</li><!--/k:c1--></ol>' +
24
- '<template data-kc="c1" data-kb="a"><li>no</li></template>';
25
- const start = startMarker(document.body, 'c1');
26
- const tpl = document.querySelector('template[data-kc="c1"]');
27
- const tbody = document.querySelector('ol');
28
- const yesRow = tbody.querySelector('li');
29
- krateCondSwap(start, true, tpl);
30
- expect(tbody.textContent).toBe('yes');
31
- krateCondSwap(start, false, tpl);
32
- expect(tbody.querySelectorAll('li').length).toBe(1);
33
- expect(tbody.textContent).toBe('no');
34
- krateCondSwap(start, true, tpl);
35
- // The original (hydrated) node comes back, not a clone.
36
- expect(tbody.querySelector('li')).toBe(yesRow);
37
- });
38
- it('keeps bindings made on template content alive after the swap', async () => {
39
- document.body.innerHTML =
40
- '<ul><!--k:c2--><li>a</li><!--/k:c2--></ul><template data-kc="c2" data-kb="a"><li><button>b</button></li></template>';
41
- const tpl = document.querySelector('template');
42
- const btn = tpl.content.querySelector('button');
43
- let clicks = 0;
44
- btn.addEventListener('click', () => clicks++);
45
- const [on, setOn] = createSignal(true);
46
- const start = startMarker(document.body, 'c2');
47
- createEffect(() => krateCondSwap(start, !!on(), tpl));
48
- expect(document.querySelector('ul').textContent).toBe('a');
49
- setOn(false);
50
- await tick();
51
- const live = document.querySelector('ul button');
52
- expect(live).toBe(btn);
53
- live.click();
54
- expect(clicks).toBe(1);
55
- });
56
- it('starts from the consequent when the template holds it', () => {
57
- document.body.innerHTML = '<p><!--k:c3--><i>no</i><!--/k:c3--></p><template data-kc="c3" data-kb="c"><b>yes</b></template>';
58
- const start = startMarker(document.body, 'c3');
59
- const tpl = document.querySelector('template');
60
- krateCondSwap(start, false, tpl);
61
- expect(document.querySelector('p').innerHTML).toBe('<!--k:c3--><i>no</i><!--/k:c3-->');
62
- krateCondSwap(start, true, tpl);
63
- expect(document.querySelector('p').innerHTML).toBe('<!--k:c3--><b>yes</b><!--/k:c3-->');
64
- });
65
- it('treats a missing template as an empty branch', () => {
66
- document.body.innerHTML = '<div><!--k:c4--><b>x</b><!--/k:c4--></div>';
67
- const start = startMarker(document.body, 'c4');
68
- krateCondSwap(start, true, null);
69
- krateCondSwap(start, false, null);
70
- expect(document.querySelector('div').innerHTML).toBe('<!--k:c4--><!--/k:c4-->');
71
- krateCondSwap(start, true, null);
72
- expect(document.querySelector('div').textContent).toBe('x');
73
- });
74
- });
75
- describe('krateSanitizeAttr', () => {
76
- it('blocks javascript: URLs like React 19', () => {
77
- expect(krateSanitizeAttr('href', 'javascript:alert(1)')).toBe(BLOCKED_URL);
78
- expect(krateSanitizeAttr('src', ' \tJaVa\nScript:x')).toBe(BLOCKED_URL);
79
- expect(krateSanitizeAttr('xlink:href', 'javascript:x')).toBe(BLOCKED_URL);
80
- expect(krateSanitizeAttr('href', '/safe')).toBe('/safe');
81
- expect(krateSanitizeAttr('title', 'javascript:x')).toBe('javascript:x');
82
- });
83
- });
84
- describe('reconcile with conditional templates', () => {
85
- it('replaces a template whose content changed', () => {
86
- document.body.innerHTML = '<div id="root"><p>x</p><template data-kc="c1" data-kb="a"><b>old</b></template></div>';
87
- const root = document.getElementById('root');
88
- const next = document.createElement('div');
89
- next.id = 'root';
90
- next.innerHTML = '<p>x</p><template data-kc="c1" data-kb="a"><b>new</b></template>';
91
- reconcileTrees(root, next);
92
- const tpl = root.querySelector('template');
93
- expect(tpl.innerHTML).toBe('<b>new</b>');
94
- });
95
- });
96
- // The hydration bootstrap ships as a Go string constant appended to the
97
- // runtime chunk; run the real source against compiler-shaped markup.
98
- function loadBootstrap() {
99
- const here = dirname(fileURLToPath(import.meta.url));
100
- const src = readFileSync(resolve(here, '../../compiler/internal/renderer/newhydrate.go'), 'utf8');
101
- const start = src.indexOf('const HydrationBootstrapJS = `') + 'const HydrationBootstrapJS = `'.length;
102
- const end = src.indexOf('`\n', start);
103
- return src.slice(start, end);
104
- }
105
- describe('hydration bootstrap', () => {
106
- beforeEach(() => {
107
- const w = window;
108
- w.createEffect = createEffect;
109
- w.krateCondSwap = krateCondSwap;
110
- w.krateCondDetached = krateCondDetached;
111
- w.krateCondReset = krateCondReset;
112
- w.krateSanitizeAttr = krateSanitizeAttr;
113
- });
114
- it('binds handlers and text inside the inactive branch template, then toggles', async () => {
115
- document.body.innerHTML =
116
- '<div id="root"><ul><!--k:c--><li>on</li><!--/k:c--></ul>' +
117
- '<template data-kc="c" data-kb="a"><li><button data-k="k:btn">off</button><!--k:t-->0<!--/k:t--></li></template></div>';
118
- new Function(loadBootstrap())();
119
- const w = window;
120
- const [on, setOn] = createSignal(true);
121
- const [n, setN] = createSignal(0);
122
- let clicked = 0;
123
- w.kbindCond('c', () => on());
124
- w.kbindText('t', () => n());
125
- expect(w.findSlot('btn')).not.toBe(null);
126
- w.kbindEvent('btn', 'click', () => clicked++, false);
127
- expect(w.__krateErrs).toEqual([]);
128
- setN(5);
129
- setOn(false);
130
- await tick();
131
- const tbody = document.querySelector('ul');
132
- expect(tbody.textContent).toBe('off5');
133
- tbody.querySelector('button').click();
134
- expect(clicked).toBe(1);
135
- setOn(true);
136
- await tick();
137
- expect(tbody.textContent).toBe('on');
138
- setN(7);
139
- setOn(false);
140
- await tick();
141
- expect(tbody.textContent).toBe('off7');
142
- });
143
- it('finds nodes of a branch swapped out before its binding ran', async () => {
144
- document.body.innerHTML =
145
- '<div id="root"><p><!--k:c--><button data-k="k:b">ssr</button><!--/k:c--></p>' +
146
- '<template data-kc="c" data-kb="a"><i>client</i></template></div>';
147
- new Function(loadBootstrap())();
148
- const w = window;
149
- // The client state disagrees with the SSR state: the first run swaps.
150
- w.kbindCond('c', () => false);
151
- expect(document.querySelector('p').textContent).toBe('client');
152
- let clicks = 0;
153
- w.kbindEvent('b', 'click', () => clicks++, false);
154
- expect(w.findSlot('b')).not.toBe(null);
155
- w.findSlot('b').click();
156
- expect(clicks).toBe(1);
157
- });
158
- it('neutralizes javascript: URLs set by attribute bindings', async () => {
159
- document.body.innerHTML = '<div id="root"><a data-k="k:a">x</a></div>';
160
- new Function(loadBootstrap())();
161
- const [href, setHref] = createSignal('/ok');
162
- window.kbindAttr('a', 'href', () => href());
163
- const a = document.querySelector('a');
164
- expect(a.getAttribute('href')).toBe('/ok');
165
- setHref('javascript:alert(1)');
166
- await tick();
167
- expect(a.getAttribute('href')).toBe(BLOCKED_URL);
168
- });
169
- });