@krate/runtime 0.5.0-rc.1 → 0.5.0-rc.11

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 (214) 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 +470 -77
  22. package/dist/dom.js +18 -3
  23. package/dist/effects.js +2 -2
  24. package/dist/flight-props.d.ts +7 -0
  25. package/dist/flight-props.js +105 -0
  26. package/dist/handler-html.js +4 -4
  27. package/dist/handler-routing.d.ts +2 -23
  28. package/dist/handler-routing.js +9 -190
  29. package/dist/handler-segments.d.ts +6 -0
  30. package/dist/handler-segments.js +18 -4
  31. package/dist/head-tags.d.ts +9 -0
  32. package/dist/head-tags.js +93 -6
  33. package/dist/highlight-bind.js +1 -1
  34. package/dist/highlight.d.ts +3 -2
  35. package/dist/highlight.js +17 -12
  36. package/dist/hints.d.ts +25 -2
  37. package/dist/hints.js +147 -74
  38. package/dist/index.d.ts +2 -0
  39. package/dist/index.js +3 -0
  40. package/dist/island-swap.d.ts +47 -0
  41. package/dist/island-swap.js +635 -0
  42. package/dist/jsx-dev-runtime.d.ts +1 -1
  43. package/dist/jsx-types.d.ts +99 -3
  44. package/dist/krate-core.js +1 -1
  45. package/dist/krate-dev.js +385 -66
  46. package/dist/krate-f-actions.js +1 -1
  47. package/dist/krate-f-classes.js +1 -1
  48. package/dist/krate-f-highlight.js +1 -1
  49. package/dist/krate-f-list.js +1 -1
  50. package/dist/krate-f-navigation.js +1 -1
  51. package/dist/krate-f-router-lite.js +1 -1
  52. package/dist/krate-f-router.js +1 -1
  53. package/dist/krate-features.json +454 -0
  54. package/dist/krate-hydrate-lite.js +5 -5
  55. package/dist/krate-hydrate.js +5 -5
  56. package/dist/krate-island-swap.js +1 -0
  57. package/dist/krate-runtime.js +5 -5
  58. package/dist/list.d.ts +14 -4
  59. package/dist/list.js +4 -5
  60. package/dist/metadata.js +5 -2
  61. package/dist/navigation-react.d.ts +13 -0
  62. package/dist/navigation-react.js +86 -0
  63. package/dist/navigation.d.ts +19 -0
  64. package/dist/navigation.js +35 -0
  65. package/dist/node-server.js +3 -3
  66. package/dist/og.js +1 -1
  67. package/dist/platform.d.ts +52 -0
  68. package/dist/platform.js +57 -0
  69. package/dist/react-compat.d.ts +39 -0
  70. package/dist/react-compat.js +359 -0
  71. package/dist/react-server.d.ts +63 -0
  72. package/dist/react-server.js +125 -0
  73. package/dist/region-wire.d.ts +10 -0
  74. package/dist/region-wire.js +154 -0
  75. package/dist/request-context.js +1 -1
  76. package/dist/request-extras.d.ts +4 -0
  77. package/dist/request-extras.js +51 -0
  78. package/dist/resp.js +1 -1
  79. package/dist/route-source.d.ts +39 -0
  80. package/dist/route-source.js +532 -0
  81. package/dist/router-lite.js +3 -9
  82. package/dist/router.d.ts +1 -1
  83. package/dist/router.js +628 -98
  84. package/dist/server-handler.d.ts +69 -1
  85. package/dist/server-handler.js +515 -96
  86. package/dist/server-renderer.js +16 -7
  87. package/dist/server.d.ts +73 -16
  88. package/dist/server.js +619 -102
  89. package/dist/sha256.js +9 -9
  90. package/dist/signal.js +0 -6
  91. package/dist/site-config.d.ts +15 -0
  92. package/dist/site-config.js +28 -0
  93. package/dist/slot.d.ts +12 -0
  94. package/dist/slot.js +23 -0
  95. package/dist/ssr-core.d.ts +2 -0
  96. package/dist/ssr-core.js +12 -4
  97. package/dist/testing.d.ts +62 -0
  98. package/dist/testing.js +90 -0
  99. package/dist/use-id.js +1 -1
  100. package/package.json +28 -3
  101. package/dist/action-context.test.d.ts +0 -1
  102. package/dist/action-context.test.js +0 -72
  103. package/dist/actions.test.d.ts +0 -1
  104. package/dist/actions.test.js +0 -477
  105. package/dist/cache-adapter.test.d.ts +0 -1
  106. package/dist/cache-adapter.test.js +0 -244
  107. package/dist/cache.test.d.ts +0 -1
  108. package/dist/cache.test.js +0 -233
  109. package/dist/class-component.test.d.ts +0 -1
  110. package/dist/class-component.test.js +0 -462
  111. package/dist/class-helpers.test.d.ts +0 -1
  112. package/dist/class-helpers.test.js +0 -169
  113. package/dist/context.test.d.ts +0 -1
  114. package/dist/context.test.js +0 -57
  115. package/dist/derived.test.d.ts +0 -1
  116. package/dist/derived.test.js +0 -140
  117. package/dist/dev-overlay.test.d.ts +0 -1
  118. package/dist/dev-overlay.test.js +0 -165
  119. package/dist/discrete.test.d.ts +0 -1
  120. package/dist/discrete.test.js +0 -100
  121. package/dist/dom.test.d.ts +0 -1
  122. package/dist/dom.test.js +0 -39
  123. package/dist/effect-errors.test.d.ts +0 -1
  124. package/dist/effect-errors.test.js +0 -199
  125. package/dist/effects.test.d.ts +0 -1
  126. package/dist/effects.test.js +0 -485
  127. package/dist/events.test.d.ts +0 -1
  128. package/dist/events.test.js +0 -447
  129. package/dist/handler-html.test.d.ts +0 -1
  130. package/dist/handler-html.test.js +0 -256
  131. package/dist/handler-routing.test.d.ts +0 -1
  132. package/dist/handler-routing.test.js +0 -99
  133. package/dist/handler-segments.test.d.ts +0 -1
  134. package/dist/handler-segments.test.js +0 -217
  135. package/dist/head-tags.test.d.ts +0 -1
  136. package/dist/head-tags.test.js +0 -131
  137. package/dist/highlight-bind.test.d.ts +0 -1
  138. package/dist/highlight-bind.test.js +0 -124
  139. package/dist/highlight.test.d.ts +0 -1
  140. package/dist/highlight.test.js +0 -56
  141. package/dist/lanes.test.d.ts +0 -1
  142. package/dist/lanes.test.js +0 -59
  143. package/dist/list.test.d.ts +0 -1
  144. package/dist/list.test.js +0 -435
  145. package/dist/metadata.test.d.ts +0 -1
  146. package/dist/metadata.test.js +0 -167
  147. package/dist/navigation.test.d.ts +0 -1
  148. package/dist/navigation.test.js +0 -130
  149. package/dist/node-server.test.d.ts +0 -1
  150. package/dist/node-server.test.js +0 -492
  151. package/dist/optimistic-lanes.test.d.ts +0 -1
  152. package/dist/optimistic-lanes.test.js +0 -45
  153. package/dist/patterns.test.d.ts +0 -1
  154. package/dist/patterns.test.js +0 -125
  155. package/dist/portal.test.d.ts +0 -1
  156. package/dist/portal.test.js +0 -99
  157. package/dist/react-effects.test.d.ts +0 -1
  158. package/dist/react-effects.test.js +0 -133
  159. package/dist/react-suspense.test.d.ts +0 -1
  160. package/dist/react-suspense.test.js +0 -194
  161. package/dist/react.test.d.ts +0 -1
  162. package/dist/react.test.js +0 -60
  163. package/dist/react19.test.d.ts +0 -1
  164. package/dist/react19.test.js +0 -176
  165. package/dist/reactivity-core.test.d.ts +0 -1
  166. package/dist/reactivity-core.test.js +0 -152
  167. package/dist/reconcile.test.d.ts +0 -1
  168. package/dist/reconcile.test.js +0 -110
  169. package/dist/refs.test.d.ts +0 -1
  170. package/dist/refs.test.js +0 -257
  171. package/dist/router-layout.test.d.ts +0 -1
  172. package/dist/router-layout.test.js +0 -249
  173. package/dist/router-nav.test.d.ts +0 -1
  174. package/dist/router-nav.test.js +0 -559
  175. package/dist/router-slots.test.d.ts +0 -1
  176. package/dist/router-slots.test.js +0 -144
  177. package/dist/router-speculation.test.d.ts +0 -1
  178. package/dist/router-speculation.test.js +0 -25
  179. package/dist/router-styles.test.d.ts +0 -1
  180. package/dist/router-styles.test.js +0 -98
  181. package/dist/router.test.d.ts +0 -1
  182. package/dist/router.test.js +0 -36
  183. package/dist/server-async.test.d.ts +0 -1
  184. package/dist/server-async.test.js +0 -216
  185. package/dist/server-handler.test.d.ts +0 -1
  186. package/dist/server-handler.test.js +0 -535
  187. package/dist/server-highlight.test.d.ts +0 -1
  188. package/dist/server-highlight.test.js +0 -32
  189. package/dist/server-renderer.test.d.ts +0 -1
  190. package/dist/server-renderer.test.js +0 -266
  191. package/dist/server.test.d.ts +0 -1
  192. package/dist/server.test.js +0 -88
  193. package/dist/sha256.test.d.ts +0 -1
  194. package/dist/sha256.test.js +0 -13
  195. package/dist/signal-lanes.test.d.ts +0 -1
  196. package/dist/signal-lanes.test.js +0 -32
  197. package/dist/signal.test.d.ts +0 -1
  198. package/dist/signal.test.js +0 -68
  199. package/dist/slots.test.d.ts +0 -1
  200. package/dist/slots.test.js +0 -187
  201. package/dist/snapshots.test.d.ts +0 -1
  202. package/dist/snapshots.test.js +0 -208
  203. package/dist/ssr-core-behavior.test.d.ts +0 -1
  204. package/dist/ssr-core-behavior.test.js +0 -620
  205. package/dist/ssr-core.test.d.ts +0 -1
  206. package/dist/ssr-core.test.js +0 -324
  207. package/dist/static-memory.test.d.ts +0 -1
  208. package/dist/static-memory.test.js +0 -26
  209. package/dist/storage.test.d.ts +0 -1
  210. package/dist/storage.test.js +0 -46
  211. package/dist/suspense-actions.test.d.ts +0 -1
  212. package/dist/suspense-actions.test.js +0 -72
  213. package/dist/suspense.test.d.ts +0 -1
  214. package/dist/suspense.test.js +0 -556
@@ -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 {};