@krate/runtime 0.5.0-rc.2 → 0.5.0-rc.4

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 (155) hide show
  1. package/dist/actions.d.ts +7 -0
  2. package/dist/actions.js +21 -3
  3. package/dist/actions.test.js +8 -410
  4. package/dist/after.d.ts +28 -0
  5. package/dist/after.js +48 -0
  6. package/dist/after.test.js +58 -0
  7. package/dist/assets-static.d.ts +10 -1
  8. package/dist/assets-static.js +10 -2
  9. package/dist/base-path.js +4 -3
  10. package/dist/builtin-tags.d.ts +12 -0
  11. package/dist/builtin-tags.js +42 -0
  12. package/dist/builtin-tags.test.js +12 -0
  13. package/dist/cache-adapter.test.js +4 -203
  14. package/dist/cache-scope.d.ts +2 -0
  15. package/dist/cache.test.js +1 -197
  16. package/dist/cloudflare-workers.d.ts +2 -0
  17. package/dist/cloudflare-workers.js +27 -0
  18. package/dist/dev-overlay.d.ts +54 -3
  19. package/dist/dev-overlay.js +469 -76
  20. package/dist/dom.js +3 -1
  21. package/dist/events.test.js +2 -407
  22. package/dist/handler-html.test.js +1 -202
  23. package/dist/handler-routing.js +3 -0
  24. package/dist/handler-segments.d.ts +6 -0
  25. package/dist/handler-segments.js +16 -2
  26. package/dist/handler-segments.test.js +8 -200
  27. package/dist/head-tags.d.ts +9 -0
  28. package/dist/head-tags.js +85 -1
  29. package/dist/head-tags.test.js +18 -125
  30. package/dist/index.d.ts +1 -5
  31. package/dist/index.js +3 -0
  32. package/dist/inline-action-token.test.js +31 -0
  33. package/dist/jsx-svg-types.test.js +58 -0
  34. package/dist/jsx-types.d.ts +92 -1
  35. package/dist/krate-core.js +1 -1
  36. package/dist/krate-dev.js +384 -65
  37. package/dist/krate-f-actions.js +1 -1
  38. package/dist/krate-f-navigation.js +1 -1
  39. package/dist/krate-f-router-lite.js +1 -1
  40. package/dist/krate-f-router.js +1 -1
  41. package/dist/krate-features.json +2 -0
  42. package/dist/krate-hydrate-lite.js +5 -5
  43. package/dist/krate-hydrate.js +5 -5
  44. package/dist/krate-runtime.js +5 -5
  45. package/dist/link-base-path.test.js +28 -0
  46. package/dist/node-server.test.js +1 -355
  47. package/dist/platform.d.ts +52 -0
  48. package/dist/platform.js +57 -0
  49. package/dist/platform.test.js +44 -0
  50. package/dist/router-nav.test.js +15 -444
  51. package/dist/router.js +39 -1
  52. package/dist/server-handler.d.ts +48 -0
  53. package/dist/server-handler.js +279 -17
  54. package/dist/server-handler.test.js +54 -388
  55. package/dist/server-renderer.test.js +0 -104
  56. package/dist/server.d.ts +15 -5
  57. package/dist/server.js +149 -22
  58. package/dist/server.test.js +52 -60
  59. package/dist/site-config.d.ts +13 -0
  60. package/dist/site-config.js +28 -0
  61. package/dist/site-config.test.js +30 -0
  62. package/dist/slot.d.ts +12 -0
  63. package/dist/slot.js +23 -0
  64. package/dist/slot.test.js +25 -0
  65. package/dist/ssr-core-behavior.test.js +3 -515
  66. package/dist/testing.d.ts +59 -0
  67. package/dist/testing.js +88 -0
  68. package/dist/testing.test.js +73 -0
  69. package/package.json +9 -1
  70. package/dist/action-context.test.js +0 -72
  71. package/dist/base-path.test.js +0 -88
  72. package/dist/class-component.test.js +0 -462
  73. package/dist/class-helpers.test.js +0 -169
  74. package/dist/context.test.js +0 -57
  75. package/dist/derived.test.js +0 -140
  76. package/dist/dev-overlay.test.js +0 -165
  77. package/dist/discrete.test.js +0 -100
  78. package/dist/dom.test.js +0 -39
  79. package/dist/effect-errors.test.d.ts +0 -1
  80. package/dist/effect-errors.test.js +0 -199
  81. package/dist/effects.test.d.ts +0 -1
  82. package/dist/effects.test.js +0 -485
  83. package/dist/handler-routing.test.d.ts +0 -1
  84. package/dist/handler-routing.test.js +0 -99
  85. package/dist/highlight-bind.test.d.ts +0 -1
  86. package/dist/highlight-bind.test.js +0 -124
  87. package/dist/highlight.test.d.ts +0 -1
  88. package/dist/highlight.test.js +0 -56
  89. package/dist/lanes.test.d.ts +0 -1
  90. package/dist/lanes.test.js +0 -59
  91. package/dist/list.test.d.ts +0 -1
  92. package/dist/list.test.js +0 -435
  93. package/dist/metadata.test.d.ts +0 -1
  94. package/dist/metadata.test.js +0 -167
  95. package/dist/navigation.test.d.ts +0 -1
  96. package/dist/navigation.test.js +0 -130
  97. package/dist/optimistic-lanes.test.d.ts +0 -1
  98. package/dist/optimistic-lanes.test.js +0 -45
  99. package/dist/patterns.test.d.ts +0 -1
  100. package/dist/patterns.test.js +0 -125
  101. package/dist/portal.test.d.ts +0 -1
  102. package/dist/portal.test.js +0 -99
  103. package/dist/react-effects.test.d.ts +0 -1
  104. package/dist/react-effects.test.js +0 -133
  105. package/dist/react-suspense.test.d.ts +0 -1
  106. package/dist/react-suspense.test.js +0 -194
  107. package/dist/react.test.d.ts +0 -1
  108. package/dist/react.test.js +0 -60
  109. package/dist/react19.test.d.ts +0 -1
  110. package/dist/react19.test.js +0 -176
  111. package/dist/reactivity-core.test.d.ts +0 -1
  112. package/dist/reactivity-core.test.js +0 -152
  113. package/dist/reconcile.test.d.ts +0 -1
  114. package/dist/reconcile.test.js +0 -110
  115. package/dist/refs.test.d.ts +0 -1
  116. package/dist/refs.test.js +0 -257
  117. package/dist/router-layout.test.d.ts +0 -1
  118. package/dist/router-layout.test.js +0 -249
  119. package/dist/router-slots.test.d.ts +0 -1
  120. package/dist/router-slots.test.js +0 -144
  121. package/dist/router-speculation.test.d.ts +0 -1
  122. package/dist/router-speculation.test.js +0 -25
  123. package/dist/router-styles.test.d.ts +0 -1
  124. package/dist/router-styles.test.js +0 -98
  125. package/dist/router.test.d.ts +0 -1
  126. package/dist/router.test.js +0 -36
  127. package/dist/server-async.test.d.ts +0 -1
  128. package/dist/server-async.test.js +0 -216
  129. package/dist/server-highlight.test.d.ts +0 -1
  130. package/dist/server-highlight.test.js +0 -32
  131. package/dist/signal-lanes.test.d.ts +0 -1
  132. package/dist/signal-lanes.test.js +0 -32
  133. package/dist/slots.test.d.ts +0 -1
  134. package/dist/slots.test.js +0 -187
  135. package/dist/snapshots.test.d.ts +0 -1
  136. package/dist/snapshots.test.js +0 -208
  137. package/dist/ssr-core.test.d.ts +0 -1
  138. package/dist/ssr-core.test.js +0 -324
  139. package/dist/static-memory.test.d.ts +0 -1
  140. package/dist/static-memory.test.js +0 -26
  141. package/dist/storage.test.d.ts +0 -1
  142. package/dist/storage.test.js +0 -46
  143. package/dist/suspense-actions.test.d.ts +0 -1
  144. package/dist/suspense-actions.test.js +0 -72
  145. package/dist/suspense.test.d.ts +0 -1
  146. package/dist/suspense.test.js +0 -556
  147. /package/dist/{action-context.test.d.ts → after.test.d.ts} +0 -0
  148. /package/dist/{base-path.test.d.ts → builtin-tags.test.d.ts} +0 -0
  149. /package/dist/{class-component.test.d.ts → inline-action-token.test.d.ts} +0 -0
  150. /package/dist/{class-helpers.test.d.ts → jsx-svg-types.test.d.ts} +0 -0
  151. /package/dist/{context.test.d.ts → link-base-path.test.d.ts} +0 -0
  152. /package/dist/{derived.test.d.ts → platform.test.d.ts} +0 -0
  153. /package/dist/{dev-overlay.test.d.ts → site-config.test.d.ts} +0 -0
  154. /package/dist/{discrete.test.d.ts → slot.test.d.ts} +0 -0
  155. /package/dist/{dom.test.d.ts → testing.test.d.ts} +0 -0
@@ -1,10 +1,9 @@
1
1
  // @vitest-environment node
2
2
  import { AsyncLocalStorage } from "node:async_hooks";
3
- import { createHash } from "node:crypto";
4
3
  import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
5
- import { createSSRCore, variantKey } from "./ssr-core.js";
6
- import { cacheRuntime, installRenderStore, markNoStore, patchFetch, recordCacheRead } from "./cache-scope.js";
7
- import { forbidden, notFound, unauthorized } from "./request-context.js";
4
+ import { createSSRCore } from "./ssr-core.js";
5
+ import { installRenderStore, markNoStore } from "./cache-scope.js";
6
+ import { forbidden, unauthorized } from "./request-context.js";
8
7
  import { jsx } from "./server.js";
9
8
  // The renderer installs the cache scope store once per process; so does this file.
10
9
  installRenderStore(new AsyncLocalStorage());
@@ -41,132 +40,7 @@ function make(s) {
41
40
  }
42
41
  const req = (route, extra = {}) => ({ route, url: route, method: "GET", headers: {}, ...extra });
43
42
  const page = (route, mode = "ssr", extra = {}) => ({ route, source: route + ".tsx", mode, bundlePath: route, ...extra });
44
- const text = (s) => () => jsx("p", { children: s });
45
- describe("variantKey", () => {
46
- it("sorts and encodes params and query, and keeps them apart", () => {
47
- expect(variantKey({ route: "/r" })).toBe("/r");
48
- expect(variantKey({ route: "/r", params: { b: "2", a: "1 x" } })).toBe("/r?a=1%20x&b=2");
49
- expect(variantKey({ route: "/r", query: { q: "a&b=c" } })).toBe("/r#q=a%26b%3Dc");
50
- // a param and a query value with the same name are different variants
51
- expect(variantKey({ route: "/r", params: { a: "1" } })).not.toBe(variantKey({ route: "/r", query: { a: "1" } }));
52
- expect(variantKey({ route: "/r", params: { a: "1" }, query: { a: "1" } })).toBe("/r?a=1#a=1");
53
- });
54
- it("gives two dynamic params two keys", () => {
55
- expect(variantKey({ route: "/v/[id]", params: { id: "a" } })).not.toBe(variantKey({ route: "/v/[id]", params: { id: "b" } }));
56
- });
57
- });
58
- describe("generateMetadata in a page render", () => {
59
- const body = (s) => () => jsx("p", { children: s });
60
- it("puts the tags in front of the html as a head block, merged with the layouts the build bundled", async () => {
61
- const { core } = make({
62
- pages: [page("/m/[id]")],
63
- modules: {
64
- "/m/[id]": {
65
- default: body("hi"),
66
- async generateMetadata({ params }, parent) {
67
- const { id } = await params;
68
- return { title: "Item " + id, description: String((await parent).description) };
69
- },
70
- __krateMetadata: [{ file: "_layout.tsx", mod: { metadata: { title: { default: "Site", template: "%s | Site" }, description: "layout" } } }],
71
- },
72
- },
73
- });
74
- const r = await core.renderPage(req("/m/[id]", { params: { id: "7" } }));
75
- expect(r.status).toBe(200);
76
- expect(r.html).toBe("<!--krate-head--><title>Item 7 | Site</title>\n<meta name=\"description\" content=\"layout\"><!--/krate-head--><p>hi</p>");
77
- });
78
- it("is skipped when only literal metadata exists (the build bakes it)", async () => {
79
- const { core } = make({ pages: [page("/m")], modules: { "/m": { default: body("hi"), metadata: { title: "T" } } } });
80
- expect((await core.renderPage(req("/m"))).html).toBe("<p>hi</p>");
81
- });
82
- it("still renders the page when generateMetadata throws, and logs it", async () => {
83
- const { core } = make({
84
- pages: [page("/m")],
85
- modules: { "/m": { default: body("hi"), generateMetadata: () => { throw new Error("boom"); } } },
86
- });
87
- const r = await core.renderPage(req("/m"));
88
- expect(r).toMatchObject({ status: 200, html: "<p>hi</p>" });
89
- expect(errors.some((e) => String(e[0]).includes("generateMetadata"))).toBe(true);
90
- });
91
- it("answers 404 for notFound() in generateMetadata and caches nothing", async () => {
92
- const { core } = make({
93
- pages: [page("/m", "isr", { revalidate: 60 })],
94
- modules: { "/m": { default: body("hi"), generateMetadata: () => notFound() } },
95
- });
96
- expect(await core.renderPage(req("/m"))).toMatchObject({ status: 404, notFound: true });
97
- expect(await core.renderPage(req("/m"))).toMatchObject({ status: 404, notFound: true });
98
- });
99
- it("caches the head block with the ISR entry and serves it on a hit", async () => {
100
- let calls = 0;
101
- const { core } = make({
102
- pages: [page("/m", "isr", { revalidate: 60 })],
103
- modules: { "/m": { default: body("hi"), generateMetadata: () => { calls++; return { title: "C" + calls }; } } },
104
- });
105
- const first = await core.renderPage(req("/m"));
106
- const second = await core.renderPage(req("/m"));
107
- expect(first.cacheStatus).toBe("miss");
108
- expect(second.cacheStatus).toBe("hit");
109
- expect(second.html).toBe(first.html);
110
- expect(second.html).toContain("<title>C1</title>");
111
- expect(calls).toBe(1);
112
- });
113
- it("shares the data cache with the page: one request for a URL both read", async () => {
114
- let upstream = 0;
115
- vi.stubGlobal("fetch", vi.fn(async () => new Response(JSON.stringify({ title: "From API", n: ++upstream }), { headers: { "content-type": "application/json" } })));
116
- cacheRuntime().fetchPatched = false;
117
- patchFetch();
118
- const read = async () => (await fetch("http://data/post/1", { next: { tags: ["post:1"], revalidate: 60 } })).json();
119
- const { core } = make({
120
- pages: [page("/d")],
121
- modules: {
122
- "/d": {
123
- default: async () => jsx("p", { children: (await read()).title }),
124
- generateMetadata: async () => ({ title: (await read()).title }),
125
- },
126
- },
127
- });
128
- const r = await core.renderPage(req("/d"));
129
- expect(r.html).toContain("<title>From API</title>");
130
- expect(r.html).toContain("<p>From API</p>");
131
- expect(upstream).toBe(1);
132
- vi.unstubAllGlobals();
133
- cacheRuntime().fetchPatched = false;
134
- });
135
- it("records the cache reads of generateMetadata on the same render, so the entry is tagged and no-store holds", async () => {
136
- const { core } = make({
137
- pages: [page("/t", "isr", { revalidate: 60 })],
138
- modules: {
139
- "/t": {
140
- default: body("hi"),
141
- generateMetadata: () => {
142
- recordCacheRead(["posts"], undefined);
143
- return { title: "Tagged" };
144
- },
145
- },
146
- },
147
- });
148
- expect((await core.renderPage(req("/t"))).cacheStatus).toBe("miss");
149
- expect((await core.renderPage(req("/t"))).cacheStatus).toBe("hit");
150
- // revalidateTag("posts") purges the entry: generateMetadata read the tag.
151
- expect(await core.isrStore.deleteTags(["posts"])).toBe(1);
152
- expect((await core.renderPage(req("/t"))).cacheStatus).toBe("miss");
153
- });
154
- });
155
43
  describe("renderPage", () => {
156
- it("answers 404 for a route that is not in the manifest", async () => {
157
- const { core } = make({ pages: [page("/a")] });
158
- expect(await core.renderPage(req("/zzz"))).toMatchObject({ status: 404, notFound: true, html: "" });
159
- });
160
- it("finds a page with or without its trailing slash, and keeps '/' intact", async () => {
161
- const { core } = make({
162
- pages: [page("/a/"), page("/b"), page("/")],
163
- modules: { "/a/": { default: text("A") }, "/b": { default: text("B") }, "/": { default: text("root") } },
164
- });
165
- expect((await core.renderPage(req("/a"))).html).toBe("<p>A</p>");
166
- expect((await core.renderPage(req("/b/"))).html).toBe("<p>B</p>");
167
- expect((await core.renderPage(req("/"))).html).toBe("<p>root</p>");
168
- expect(core.findPage("/missing/")).toBeUndefined();
169
- });
170
44
  it("escapes text and attribute values coming from the request", async () => {
171
45
  const { core } = make({
172
46
  pages: [page("/e")],
@@ -184,40 +58,6 @@ describe("renderPage", () => {
184
58
  expect(r.html).toContain("title=");
185
59
  expect(r.html).toContain("&lt;b&gt;&amp;");
186
60
  });
187
- it("hands the page awaitable params and searchParams", async () => {
188
- const { core } = make({
189
- pages: [page("/p/[id]")],
190
- modules: {
191
- "/p/[id]": {
192
- default: async (props) => {
193
- const { id } = await props.params;
194
- const { tab } = await props.searchParams;
195
- return jsx("p", { children: `${id}/${tab}/${props.params.id}/${props.searchParams.tab}` });
196
- },
197
- },
198
- },
199
- });
200
- const r = await core.renderPage(req("/p/[id]", { params: { id: "7" }, query: { tab: "x" } }));
201
- expect(r.html).toBe("<p>7/x/7/x</p>");
202
- });
203
- it("serves request headers and cookies to server components", async () => {
204
- const { getRequestContext } = await import("./request-context.js");
205
- const seen = [];
206
- const { core } = make({
207
- pages: [page("/h")],
208
- modules: {
209
- "/h": {
210
- default: () => {
211
- const c = getRequestContext();
212
- seen.push(c.headers.get("x-test") + "|" + c.cookies.get("sid"));
213
- return jsx("p", { children: "ok" });
214
- },
215
- },
216
- },
217
- });
218
- await core.renderPage(req("/h", { headers: { "x-test": "yes", cookie: "sid=abc; other=1" } }));
219
- expect(seen).toEqual(["yes|abc"]);
220
- });
221
61
  describe("failures", () => {
222
62
  const boom = () => () => {
223
63
  const e = new Error("boom");
@@ -233,29 +73,6 @@ describe("renderPage", () => {
233
73
  expect(r.digest).toMatch(/^[0-9a-f]{10}$/);
234
74
  expect(errors.flat().join(" ")).toContain(`digest ${r.digest}`);
235
75
  });
236
- it("computes the digest as sha256(message + newline + stack) cut to 10 hex digits, the same on every host", async () => {
237
- // Pinned: build/segmentserve.go errorDigest must produce this exact value.
238
- const golden = "8a2474a04d";
239
- const portable = make({ pages: [page("/b")], modules: { "/b": { default: boom() } } });
240
- const node = make({
241
- pages: [page("/b")],
242
- modules: { "/b": { default: boom() } },
243
- opts: { sha256Hex: (s) => createHash("sha256").update(s).digest("hex") },
244
- });
245
- expect((await portable.core.renderPage(req("/b"))).digest).toBe(golden);
246
- expect((await node.core.renderPage(req("/b"))).digest).toBe(golden);
247
- expect(createHash("sha256").update("boom\nat x").digest("hex").slice(0, 10)).toBe(golden);
248
- });
249
- it("turns a missing default export into a 500", async () => {
250
- const { core } = make({ pages: [page("/n")], modules: { "/n": {} } });
251
- expect(await core.renderPage(req("/n"))).toMatchObject({ status: 500, html: "" });
252
- });
253
- it("turns a module that cannot load into a 500", async () => {
254
- const { core } = make({ pages: [page("/n")], modules: {} });
255
- const r = await core.renderPage(req("/n"));
256
- expect(r.status).toBe(500);
257
- expect(r.error).toContain("no module");
258
- });
259
76
  it("maps forbidden() to 403 and unauthorized() to 401 and never caches them", async () => {
260
77
  const { core } = make({
261
78
  pages: [{ ...page("/fb"), mode: "isr", revalidate: 60 }, page("/un")],
@@ -267,98 +84,9 @@ describe("renderPage", () => {
267
84
  expect(await core.renderPage(req("/un"))).toMatchObject({ status: 401, denied: 401 });
268
85
  expect(await core.renderPage(req("/un"))).not.toHaveProperty("notFound");
269
86
  });
270
- it("maps notFound() to 404 and a redirect signal to 307", async () => {
271
- const { core } = make({
272
- pages: [page("/nf"), page("/rd"), page("/rd2")],
273
- modules: {
274
- "/nf": { default: () => notFound() },
275
- "/rd": {
276
- default: () => {
277
- throw Object.assign(new Error("NEXT_REDIRECT"), { __krateRedirect: "/login" });
278
- },
279
- },
280
- "/rd2": {
281
- default: () => {
282
- throw Object.assign(new Error("x"), { digest: "NEXT_REDIRECT;replace;/next;307" });
283
- },
284
- },
285
- },
286
- });
287
- expect(await core.renderPage(req("/nf"))).toMatchObject({ status: 404, notFound: true });
288
- expect(await core.renderPage(req("/rd"))).toMatchObject({ status: 307, redirect: "/login" });
289
- expect(await core.renderPage(req("/rd2"))).toMatchObject({ status: 307, redirect: "/next" });
290
- expect(errors).toEqual([]);
291
- });
292
- it("stops a render that outlives the timeout", async () => {
293
- const { core } = make({
294
- pages: [page("/slow")],
295
- modules: { "/slow": { default: () => new Promise(() => { }) } },
296
- opts: { timeoutMs: 30 },
297
- });
298
- const r = await core.renderPage(req("/slow"));
299
- expect(r.status).toBe(500);
300
- expect(r.error).toBe("render timed out after 30ms");
301
- });
302
87
  });
303
88
  });
304
89
  describe("ISR pages", () => {
305
- function isr(extra = {}, revalidate = 10) {
306
- let n = 0;
307
- const s = make({
308
- pages: [page("/i/[id]", "isr", { revalidate })],
309
- modules: {
310
- "/i/[id]": {
311
- default: (props) => {
312
- const q = props.searchParams.page;
313
- return jsx("p", { children: `${props.params.id}:${q ?? "-"}:${++n}` });
314
- },
315
- },
316
- },
317
- opts: extra,
318
- });
319
- return { ...s, renders: () => n, get: (id, query) => s.core.renderPage(req("/i/[id]", { params: { id }, query })) };
320
- }
321
- it("reports miss, then hit, and keeps variants apart", async () => {
322
- const { get, renders } = isr();
323
- expect(await get("a")).toMatchObject({ cacheStatus: "miss", html: "<p>a:-:1</p>" });
324
- expect(await get("a")).toMatchObject({ cacheStatus: "hit", cached: true, html: "<p>a:-:1</p>" });
325
- expect(await get("b")).toMatchObject({ cacheStatus: "miss", html: "<p>b:-:2</p>" });
326
- expect(renders()).toBe(2);
327
- });
328
- it("keys the cache by the query keys the page read, and only those", async () => {
329
- const { get, renders } = isr();
330
- expect((await get("a", { page: "1", utm: "x" })).cacheStatus).toBe("miss");
331
- // the page read `page`, not `utm`: another utm value shares the entry
332
- expect(await get("a", { page: "1", utm: "y" })).toMatchObject({ cacheStatus: "hit", html: "<p>a:1:1</p>" });
333
- // another `page` is another page
334
- expect(await get("a", { page: "2" })).toMatchObject({ cacheStatus: "miss", html: "<p>a:2:2</p>" });
335
- expect(renders()).toBe(2);
336
- });
337
- it("keys a page that enumerates the whole query by the whole query", async () => {
338
- let n = 0;
339
- const { core } = make({
340
- pages: [page("/all", "isr", { revalidate: 10 })],
341
- modules: { "/all": { default: (props) => jsx("p", { children: `${JSON.stringify(Object.keys(props.searchParams).sort())}:${++n}` }) } },
342
- });
343
- const get = (query) => core.renderPage(req("/all", { query }));
344
- expect((await get({ a: "1" })).cacheStatus).toBe("miss");
345
- expect((await get({ a: "1" })).cacheStatus).toBe("hit");
346
- expect((await get({ a: "1", b: "2" })).cacheStatus).toBe("miss");
347
- expect(n).toBe(2);
348
- });
349
- it("serves a stale entry at once and refreshes it once in the background", async () => {
350
- vi.useFakeTimers();
351
- const { get, renders, settle } = isr({}, 10);
352
- await get("a");
353
- vi.setSystemTime(Date.now() + 11000);
354
- const [s1, s2] = await Promise.all([get("a"), get("a")]);
355
- expect(s1).toMatchObject({ cacheStatus: "stale", html: "<p>a:-:1</p>" });
356
- expect(s2.cacheStatus).toBe("stale");
357
- await settle();
358
- // two concurrent stale requests shared one refresh
359
- expect(renders()).toBe(2);
360
- expect(await get("a")).toMatchObject({ cacheStatus: "hit", html: "<p>a:-:2</p>" });
361
- });
362
90
  it("does not cache a render that opted out, nor one that was invalidated while it ran", async () => {
363
91
  let n = 0;
364
92
  const { core } = make({
@@ -377,244 +105,4 @@ describe("ISR pages", () => {
377
105
  expect(a).toMatchObject({ noStore: true, cacheStatus: "miss", html: "<p>1</p>" });
378
106
  expect(b).toMatchObject({ cacheStatus: "miss", html: "<p>2</p>" });
379
107
  });
380
- it("ties entries to the tags the render read, so a tag invalidation finds them", async () => {
381
- let n = 0;
382
- const changes = [];
383
- const { core } = make({
384
- pages: [page("/t/[id]", "isr", { revalidate: 100 })],
385
- modules: {
386
- "/t/[id]": {
387
- default: (props) => {
388
- recordCacheRead(["posts", "post:" + props.params.id], undefined);
389
- return jsx("p", { children: String(++n) });
390
- },
391
- },
392
- },
393
- opts: { onIsrChange: (immediate) => void changes.push(immediate) },
394
- });
395
- const get = (id) => core.renderPage(req("/t/[id]", { params: { id } }));
396
- await get("1");
397
- await get("2");
398
- expect((await get("1")).cacheStatus).toBe("hit");
399
- expect(changes).toEqual([false, false]);
400
- const out = await core.applyInternalOp("cache-invalidate", { tags: ["post:1"] });
401
- expect(out).toMatchObject({ ok: true, isrEntries: 1 });
402
- expect(changes[changes.length - 1]).toBe(true);
403
- expect((await get("1")).cacheStatus).toBe("miss");
404
- expect((await get("2")).cacheStatus).toBe("hit");
405
- const all = await core.applyInternalOp("cache-invalidate", { tags: ["posts"] });
406
- expect(all.isrEntries).toBe(2);
407
- });
408
- });
409
- describe("applyInternalOp", () => {
410
- function counter() {
411
- let n = 0;
412
- const s = make({
413
- pages: [page("/c/[id]", "isr", { revalidate: 100 }), page("/live", "ssr")],
414
- modules: {
415
- "/c/[id]": { default: (props) => jsx("p", { children: `${props.params?.id ?? "base"}:${++n}` }) },
416
- "/live": { default: text("live") },
417
- },
418
- });
419
- return { ...s, renders: () => n, get: (id) => s.core.renderPage(req("/c/[id]", id ? { params: { id } } : {})) };
420
- }
421
- it("cache-invalidate with a path target drops one params variant, or the whole route without params", async () => {
422
- const { core, get } = counter();
423
- await get("a");
424
- await get("b");
425
- expect(await core.applyInternalOp("cache-invalidate", { targets: [{ route: "/c/[id]", params: { id: "a" } }] })).toMatchObject({ ok: true, isrEntries: 1 });
426
- expect((await get("a")).cacheStatus).toBe("miss");
427
- expect((await get("b")).cacheStatus).toBe("hit");
428
- expect(await core.applyInternalOp("cache-invalidate", { targets: [{ route: "/c/[id]" }] })).toMatchObject({ isrEntries: 2 });
429
- expect((await get("b")).cacheStatus).toBe("miss");
430
- });
431
- it("cache-invalidate ignores malformed input", async () => {
432
- const { core } = counter();
433
- expect(await core.applyInternalOp("cache-invalidate", { tags: [1, "", null], targets: [null, { route: 5 }, "x"] })).toMatchObject({ ok: true, isrEntries: 0, regionEntries: 0 });
434
- });
435
- it("revalidate-route clears every variant and renders the base variant again", async () => {
436
- const { core, get, renders } = counter();
437
- await get("a");
438
- const before = renders();
439
- expect(await core.applyInternalOp("revalidate-route", { route: "/c/[id]" })).toEqual({ ok: true });
440
- expect(renders()).toBe(before + 1);
441
- expect((await get("a")).cacheStatus).toBe("miss");
442
- });
443
- it("refresh-route does nothing for a page that is not ISR", async () => {
444
- const { core } = counter();
445
- expect(await core.applyInternalOp("refresh-route", { route: "/live" })).toEqual({ ok: true, refreshed: 0 });
446
- expect(await core.applyInternalOp("refresh-route", { route: "/missing" })).toEqual({ ok: true, refreshed: 0 });
447
- });
448
- it("devInvalidate drops cached variants of a route", async () => {
449
- const { core, get } = counter();
450
- await get("a");
451
- core.devInvalidate("/c/[id]");
452
- expect((await get("a")).cacheStatus).toBe("miss");
453
- });
454
- });
455
- describe("regions", () => {
456
- const region = (id, extra = {}) => ({ id, bundlePath: "r/" + id, ...extra });
457
- it("rejects a region without a bundle; it is fatal only for a page with server components", async () => {
458
- const plain = make({ pages: [page("/p")], regions: {} });
459
- expect(await plain.core.renderRegion(page("/p"), { id: "x" }, req("/p"))).toMatchObject({ type: "error", id: "x", status: 400, fatal: false });
460
- const sc = make({ pages: [page("/p", "ssr", { serverComponents: true })] });
461
- expect(await sc.core.renderRegion(page("/p", "ssr", { serverComponents: true }), { id: "x" }, req("/p"))).toMatchObject({ fatal: true });
462
- });
463
- it("passes the baked props with the request params and query to the runtime bundle", async () => {
464
- const seen = [];
465
- const { core } = make({
466
- pages: [page("/p")],
467
- runtime: {
468
- "r/a": (json) => {
469
- seen.push(JSON.parse(typeof json === "string" ? json : JSON.stringify(json)));
470
- return "<i>A</i>";
471
- },
472
- },
473
- });
474
- const frame = await core.renderRegion(page("/p"), region("a", { props: { price: 5 } }), req("/p", { params: { id: "1" }, query: { q: "x" } }));
475
- expect(frame).toEqual({ type: "region", id: "a", status: 200, html: "<i>A</i>" });
476
- expect(seen).toEqual([{ price: 5, params: { id: "1" }, query: { q: "x" } }]);
477
- seen.length = 0;
478
- await core.renderRegion(page("/p"), region("a", { props: { price: 5 } }), req("/p", { params: {}, query: {} }));
479
- expect(seen).toEqual([{ price: 5 }]);
480
- });
481
- it("does not cache regions of a plain SSR page", async () => {
482
- let n = 0;
483
- const { core } = make({ pages: [page("/p")], runtime: { "r/a": () => `<i>${++n}</i>` } });
484
- const a = await core.renderRegion(page("/p"), region("a"), req("/p"));
485
- const b = await core.renderRegion(page("/p"), region("a"), req("/p"));
486
- expect([a.html, b.html, a.cacheStatus]).toEqual(["<i>1</i>", "<i>2</i>", undefined]);
487
- });
488
- it("caches regions of an ISR page for the page window: miss, hit, stale with one background refresh", async () => {
489
- vi.useFakeTimers();
490
- let n = 0;
491
- const p = page("/p/[id]", "isr", { revalidate: 10 });
492
- const { core, settle } = make({ pages: [p], runtime: { "r/a": () => `<i>${++n}</i>` } });
493
- const r = region("a");
494
- const q = req("/p/[id]", { params: { id: "1" } });
495
- expect(await core.renderRegion(p, r, q)).toMatchObject({ html: "<i>1</i>", cacheStatus: "miss" });
496
- expect(await core.renderRegion(p, r, q)).toMatchObject({ html: "<i>1</i>", cacheStatus: "hit", cached: true });
497
- // another params variant is another entry
498
- expect(await core.renderRegion(p, r, req("/p/[id]", { params: { id: "2" } }))).toMatchObject({ html: "<i>2</i>", cacheStatus: "miss" });
499
- vi.setSystemTime(Date.now() + 11000);
500
- const [a, b] = await Promise.all([core.renderRegion(p, r, q), core.renderRegion(p, r, q)]);
501
- expect([a.cacheStatus, b.cacheStatus]).toEqual(["stale", "stale"]);
502
- await settle();
503
- expect(n).toBe(3);
504
- expect(await core.renderRegion(p, r, q)).toMatchObject({ html: "<i>3</i>", cacheStatus: "hit" });
505
- });
506
- it("lets the region's own window win, and ppr caches the regions of a non-ISR page", async () => {
507
- let n = 0;
508
- const own = make({ pages: [page("/p")], runtime: { "r/a": () => `<i>${++n}</i>` } });
509
- const p = page("/p");
510
- expect((await own.core.renderRegion(p, region("a", { revalidate: 30 }), req("/p"))).cacheStatus).toBe("miss");
511
- expect((await own.core.renderRegion(p, region("a", { revalidate: 30 }), req("/p"))).cacheStatus).toBe("hit");
512
- let m = 0;
513
- const ppr = make({ pages: [page("/p")], runtime: { "r/a": () => `<i>${++m}</i>` }, opts: { ppr: true } });
514
- expect((await ppr.core.renderRegion(p, region("a"), req("/p"))).cacheStatus).toBe("miss");
515
- expect((await ppr.core.renderRegion(p, region("a"), req("/p"))).cacheStatus).toBe("hit");
516
- });
517
- it("does not cache a region that read uncached data", async () => {
518
- let n = 0;
519
- const p = page("/p/[id]", "isr", { revalidate: 10 });
520
- const { core } = make({
521
- pages: [p],
522
- runtime: {
523
- "r/a": () => {
524
- markNoStore();
525
- return `<i>${++n}</i>`;
526
- },
527
- },
528
- });
529
- const first = await core.renderRegion(p, region("a"), req("/p/[id]"));
530
- expect(first).toMatchObject({ noStore: true, cacheStatus: "miss" });
531
- expect((await core.renderRegion(p, region("a"), req("/p/[id]"))).html).toBe("<i>2</i>");
532
- });
533
- it("reports a failing region as an error frame with a digest, fatal only for server components", async () => {
534
- const fail = () => {
535
- const e = new Error("boom");
536
- e.stack = "at x";
537
- throw e;
538
- };
539
- const { core } = make({ pages: [page("/p")], runtime: { "r/a": fail }, modules: { "/p": { Broken: fail } } });
540
- const plain = await core.renderRegion(page("/p"), region("a"), req("/p"));
541
- expect(plain).toMatchObject({ type: "error", id: "a", status: 500, error: "boom", digest: "8a2474a04d", fatal: false });
542
- const server = await core.renderRegion(page("/p"), { id: "s", serverExport: "Broken" }, req("/p"));
543
- expect(server).toMatchObject({ type: "error", status: 500, fatal: true });
544
- });
545
- it("answers a region that calls forbidden() or unauthorized() with a 403 or 401 frame", async () => {
546
- const { core } = make({
547
- pages: [page("/p")],
548
- runtime: { "r/fb": () => forbidden(), "r/un": () => unauthorized() },
549
- });
550
- expect(await core.renderRegion(page("/p"), region("fb"), req("/p"))).toEqual({ type: "region", id: "fb", status: 403, html: "", denied: 403 });
551
- expect(await core.renderRegion(page("/p"), region("un"), req("/p"))).toEqual({ type: "region", id: "un", status: 401, html: "", denied: 401 });
552
- });
553
- it("answers a region that calls notFound() with a 404 frame and a redirect with a 307 frame", async () => {
554
- const { core } = make({
555
- pages: [page("/p")],
556
- runtime: {
557
- "r/nf": () => notFound(),
558
- "r/rd": () => {
559
- throw Object.assign(new Error("r"), { __krateRedirect: "/to" });
560
- },
561
- },
562
- });
563
- expect(await core.renderRegion(page("/p"), region("nf"), req("/p"))).toEqual({ type: "region", id: "nf", status: 404, html: "", notFound: true });
564
- expect(await core.renderRegion(page("/p"), region("rd"), req("/p"))).toEqual({ type: "region", id: "rd", status: 307, html: "", redirect: "/to" });
565
- });
566
- it("renders an async server component region from the page bundle's export", async () => {
567
- const { core } = make({
568
- pages: [page("/p")],
569
- modules: {
570
- "/p": {
571
- Price: async (props) => {
572
- await new Promise((ok) => setTimeout(ok, 5));
573
- return jsx("b", { children: `${props.item}:${props.params.id}` });
574
- },
575
- },
576
- },
577
- });
578
- const frame = await core.renderRegion(page("/p"), { id: "s", serverExport: "Price", props: { item: "pen" } }, req("/p", { params: { id: "9" } }));
579
- expect(frame).toMatchObject({ type: "region", status: 200, html: "<b>pen:9</b>" });
580
- const missing = await core.renderRegion(page("/p"), { id: "s", serverExport: "Nope" }, req("/p"));
581
- expect(missing).toMatchObject({ type: "error", status: 500, fatal: true });
582
- expect(String(missing.error)).toContain("does not export Nope");
583
- });
584
- });
585
- describe("renderPageRegion", () => {
586
- it("wraps a page render as a coarse region frame and extracts the title", async () => {
587
- const { core } = make({
588
- pages: [page("/p", "ssr")],
589
- modules: { "/p": { default: () => jsx("main", { children: [jsx("title", { children: "Hello &amp; bye" }), jsx("p", { children: "x" })] }) } },
590
- });
591
- const frame = await core.renderPageRegion(page("/p"), "page", req("/p"));
592
- expect(frame).toMatchObject({ type: "region", id: "page", kind: "page", status: 200 });
593
- expect(frame.title).toBe("Hello &amp;amp; bye");
594
- expect(String(frame.html)).toContain("<p>x</p>");
595
- });
596
- it("carries cache status, not-found, redirect and error details", async () => {
597
- const { core } = make({
598
- pages: [page("/i", "isr", { revalidate: 10 }), page("/nf"), page("/rd"), page("/err", "ssr", { serverComponents: true }), page("/err2")],
599
- modules: {
600
- "/i": { default: text("i") },
601
- "/nf": { default: () => notFound() },
602
- "/rd": {
603
- default: () => {
604
- throw Object.assign(new Error("r"), { __krateRedirect: "/to" });
605
- },
606
- },
607
- "/err": { default: () => { throw new Error("bad"); } },
608
- "/err2": { default: () => { throw new Error("bad"); } },
609
- },
610
- });
611
- expect(await core.renderPageRegion(page("/i", "isr", { revalidate: 10 }), "page", req("/i"))).toMatchObject({ cacheStatus: "miss" });
612
- expect(await core.renderPageRegion(page("/nf"), "page", req("/nf"))).toMatchObject({ status: 404, notFound: true });
613
- expect(await core.renderPageRegion(page("/rd"), "page", req("/rd"))).toMatchObject({ status: 307, redirect: "/to" });
614
- const fatal = await core.renderPageRegion(page("/err", "ssr", { serverComponents: true }), "page", req("/err"));
615
- expect(fatal).toMatchObject({ status: 500, error: "bad", fatal: true });
616
- expect(fatal.digest).toMatch(/^[0-9a-f]{10}$/);
617
- const soft = await core.renderPageRegion(page("/err2"), "page", req("/err2"));
618
- expect(soft.fatal).toBeUndefined();
619
- });
620
108
  });
@@ -0,0 +1,59 @@
1
+ /**
2
+ * Test helpers, exported from `@krate/runtime/testing`. They call an API route
3
+ * module or a server action in-process, without a running server. Node only
4
+ * (it uses AsyncLocalStorage); import it from your test files, never from app
5
+ * code.
6
+ */
7
+ export type RouteMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE" | "HEAD" | "OPTIONS";
8
+ export type RouteHandler = (request: Request, context: {
9
+ params: Record<string, string>;
10
+ }) => Response | Promise<Response>;
11
+ /** An imported `src/api/*.ts` module: named method exports and/or a default Web handler. */
12
+ export type RouteModule = Partial<Record<RouteMethod, RouteHandler>> & {
13
+ default?: unknown;
14
+ };
15
+ export interface CallRouteOptions {
16
+ /** Dynamic segments of the route (`[id]` -> `{ id: "7" }`). */
17
+ params?: Record<string, string>;
18
+ headers?: HeadersInit;
19
+ /** A JSON body; sets `content-type: application/json`. */
20
+ json?: unknown;
21
+ /** A raw body (string, FormData, ...). Ignored when `json` is set. */
22
+ body?: BodyInit | null;
23
+ }
24
+ /**
25
+ * Calls a route module the way the server does: the named export for `method`
26
+ * (HEAD falls back to GET without a body, OPTIONS answers `Allow`), else a
27
+ * default Web-style handler, else a 405 with `Allow`. `target` is a path
28
+ * (`"/api/users/7?x=1"`), an absolute URL, or a ready `Request`.
29
+ */
30
+ export declare function callRoute(mod: RouteModule, method: RouteMethod, target: string | Request, options?: CallRouteOptions): Promise<Response>;
31
+ export interface ActionCallOptions {
32
+ /** Request headers the action sees through `headers()`. */
33
+ headers?: HeadersInit;
34
+ /** Cookies the request carried; the action reads them with `cookies()`. */
35
+ cookies?: Record<string, string>;
36
+ /** The page URL path the action was submitted from. */
37
+ url?: string;
38
+ /** The action id; only visible through `getActionContext()`. */
39
+ actionId?: string;
40
+ }
41
+ export interface SetCookieCall {
42
+ name: string;
43
+ /** Empty string for a delete. */
44
+ value: string;
45
+ options?: Record<string, unknown>;
46
+ deleted: boolean;
47
+ }
48
+ export interface ActionCallResult<T> {
49
+ /** What the action returned. A thrown error (including `redirect()`) rejects instead. */
50
+ result: T;
51
+ /** Every `cookies().set()` / `delete()` call, in order. */
52
+ setCookies: SetCookieCall[];
53
+ }
54
+ /**
55
+ * Runs a server action function with the request context a real call has, so
56
+ * `cookies()`, `headers()` and `getActionContext()` from `@krate/runtime/server`
57
+ * work. The action is the plain exported function you imported from the module.
58
+ */
59
+ export declare function runAction<T>(action: () => T | Promise<T>, options?: ActionCallOptions): Promise<ActionCallResult<T>>;