@krate/runtime 0.5.0-beta.1 → 0.5.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (134) hide show
  1. package/dist/actions.js +2 -1
  2. package/dist/assets-static.d.ts +5 -0
  3. package/dist/assets-static.js +31 -0
  4. package/dist/boundary.d.ts +12 -0
  5. package/dist/boundary.js +53 -13
  6. package/dist/cache-adapter.d.ts +113 -0
  7. package/dist/cache-adapter.js +217 -0
  8. package/dist/cache-adapter.test.d.ts +1 -0
  9. package/dist/cache-adapter.test.js +244 -0
  10. package/dist/cache-redis.d.ts +27 -0
  11. package/dist/cache-redis.js +110 -0
  12. package/dist/cache-scope.d.ts +25 -9
  13. package/dist/cache-scope.js +60 -12
  14. package/dist/cache.d.ts +1 -0
  15. package/dist/cache.js +3 -3
  16. package/dist/class-component.js +6 -0
  17. package/dist/class-component.test.js +53 -2
  18. package/dist/dev-overlay.js +10 -10
  19. package/dist/dom.d.ts +8 -0
  20. package/dist/dom.js +28 -0
  21. package/dist/effect-errors.test.d.ts +1 -0
  22. package/dist/effect-errors.test.js +163 -0
  23. package/dist/effects.d.ts +8 -0
  24. package/dist/effects.js +13 -0
  25. package/dist/error-overlay.js +4 -4
  26. package/dist/handler-html.d.ts +63 -0
  27. package/dist/handler-html.js +285 -0
  28. package/dist/handler-html.test.d.ts +1 -0
  29. package/dist/handler-html.test.js +256 -0
  30. package/dist/handler-routing.d.ts +83 -0
  31. package/dist/handler-routing.js +579 -0
  32. package/dist/handler-routing.test.d.ts +1 -0
  33. package/dist/handler-routing.test.js +99 -0
  34. package/dist/handler-segments.d.ts +43 -0
  35. package/dist/handler-segments.js +115 -0
  36. package/dist/handler-segments.test.d.ts +1 -0
  37. package/dist/handler-segments.test.js +217 -0
  38. package/dist/head-tags.d.ts +51 -0
  39. package/dist/head-tags.js +329 -0
  40. package/dist/head-tags.test.d.ts +1 -0
  41. package/dist/head-tags.test.js +131 -0
  42. package/dist/highlight-bind.d.ts +42 -0
  43. package/dist/highlight-bind.js +176 -0
  44. package/dist/highlight-bind.test.d.ts +1 -0
  45. package/dist/highlight-bind.test.js +124 -0
  46. package/dist/highlight.d.ts +93 -0
  47. package/dist/highlight.js +426 -0
  48. package/dist/highlight.test.d.ts +1 -0
  49. package/dist/highlight.test.js +56 -0
  50. package/dist/hints.d.ts +19 -0
  51. package/dist/hints.js +97 -0
  52. package/dist/index.d.ts +3 -0
  53. package/dist/index.js +2 -0
  54. package/dist/jsx-types.d.ts +11 -0
  55. package/dist/krate-core.js +1 -1
  56. package/dist/krate-dev.js +10 -10
  57. package/dist/krate-f-actions.js +1 -1
  58. package/dist/krate-f-classes.js +5 -5
  59. package/dist/krate-f-highlight.js +2 -0
  60. package/dist/krate-f-list.js +1 -1
  61. package/dist/krate-f-navigation.js +2 -0
  62. package/dist/krate-f-router.js +1 -1
  63. package/dist/krate-features.json +254 -0
  64. package/dist/krate-hydrate-lite.js +5 -5
  65. package/dist/krate-hydrate.js +5 -5
  66. package/dist/krate-runtime.js +5 -5
  67. package/dist/list.js +4 -2
  68. package/dist/metadata-routes.d.ts +75 -0
  69. package/dist/metadata-routes.js +76 -0
  70. package/dist/metadata.d.ts +222 -0
  71. package/dist/metadata.js +452 -0
  72. package/dist/metadata.test.d.ts +1 -0
  73. package/dist/metadata.test.js +167 -0
  74. package/dist/navigation-server.d.ts +27 -0
  75. package/dist/navigation-server.js +90 -0
  76. package/dist/navigation.d.ts +37 -0
  77. package/dist/navigation.js +195 -0
  78. package/dist/navigation.test.d.ts +1 -0
  79. package/dist/navigation.test.js +130 -0
  80. package/dist/node-server.d.ts +22 -0
  81. package/dist/node-server.js +436 -0
  82. package/dist/node-server.test.d.ts +1 -0
  83. package/dist/node-server.test.js +492 -0
  84. package/dist/og-files.d.ts +2 -0
  85. package/dist/og-files.js +19 -0
  86. package/dist/og.d.ts +56 -0
  87. package/dist/og.js +156 -0
  88. package/dist/react.d.ts +47 -0
  89. package/dist/react.js +59 -1
  90. package/dist/react19.test.d.ts +1 -0
  91. package/dist/react19.test.js +176 -0
  92. package/dist/request-context.d.ts +23 -0
  93. package/dist/request-context.js +45 -0
  94. package/dist/resp.d.ts +55 -0
  95. package/dist/resp.js +239 -0
  96. package/dist/router-layout.test.js +70 -0
  97. package/dist/router-nav.test.js +27 -0
  98. package/dist/router.js +59 -4
  99. package/dist/segmented-lru.d.ts +19 -0
  100. package/dist/segmented-lru.js +87 -0
  101. package/dist/server-async.test.js +23 -1
  102. package/dist/server-handler.d.ts +165 -0
  103. package/dist/server-handler.js +1826 -0
  104. package/dist/server-handler.test.d.ts +1 -0
  105. package/dist/server-handler.test.js +522 -0
  106. package/dist/server-highlight.test.d.ts +1 -0
  107. package/dist/server-highlight.test.js +32 -0
  108. package/dist/server-renderer.js +146 -788
  109. package/dist/server-renderer.test.d.ts +1 -0
  110. package/dist/server-renderer.test.js +266 -0
  111. package/dist/server.d.ts +12 -1
  112. package/dist/server.js +42 -6
  113. package/dist/sha256.d.ts +1 -0
  114. package/dist/sha256.js +66 -0
  115. package/dist/sha256.test.d.ts +1 -0
  116. package/dist/sha256.test.js +13 -0
  117. package/dist/shared-isr.d.ts +31 -0
  118. package/dist/shared-isr.js +142 -0
  119. package/dist/signal.js +63 -8
  120. package/dist/ssr-core-behavior.test.d.ts +1 -0
  121. package/dist/ssr-core-behavior.test.js +620 -0
  122. package/dist/ssr-core.d.ts +175 -0
  123. package/dist/ssr-core.js +940 -0
  124. package/dist/ssr-core.test.d.ts +1 -0
  125. package/dist/ssr-core.test.js +324 -0
  126. package/dist/static-memory.d.ts +3 -0
  127. package/dist/static-memory.js +47 -0
  128. package/dist/static-memory.test.d.ts +1 -0
  129. package/dist/static-memory.test.js +26 -0
  130. package/dist/test-redis.d.ts +12 -0
  131. package/dist/test-redis.js +131 -0
  132. package/dist/use-id.d.ts +8 -0
  133. package/dist/use-id.js +40 -0
  134. package/package.json +29 -1
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,324 @@
1
+ // @vitest-environment node
2
+ import { afterEach, describe, expect, it, vi } from "vitest";
3
+ import { createSSRCore, ISRCache, MemoryIsrStore, takeHeadTitle } from "./ssr-core.js";
4
+ import { Head, jsx } from "./server.js";
5
+ function makeCore(maxCacheSize, revalidate = 30) {
6
+ let renders = 0;
7
+ const page = { route: "/plain/[id]", source: "plain.tsx", mode: "isr", revalidate, bundlePath: "plain" };
8
+ const core = createSSRCore({
9
+ manifest: { pages: [page], regions: {} },
10
+ maxCacheSize,
11
+ loadPageModule: async () => ({ default: (props) => jsx("p", { children: `plain-${props.params.id}-${++renders}` }) }),
12
+ loadRuntimeRenderer: () => () => "",
13
+ });
14
+ const render = (id) => core.renderPage({ route: "/plain/[id]", url: `/plain/${id}`, method: "GET", headers: {}, params: { id } });
15
+ return { core, render, renders: () => renders };
16
+ }
17
+ afterEach(() => vi.useRealTimers());
18
+ describe("ISR page cache eviction", () => {
19
+ it("keeps a hot page when many cold variants are requested", async () => {
20
+ const { render } = makeCore(8);
21
+ expect((await render("hot")).cacheStatus).toBe("miss");
22
+ for (let i = 0; i < 40; i++) {
23
+ await render("x" + i);
24
+ expect((await render("hot")).cacheStatus, "after x" + i).toBe("hit");
25
+ }
26
+ });
27
+ it("evicts the least recently used entry first", () => {
28
+ const c = new ISRCache(2);
29
+ const entry = (html) => ({ html, timestamp: Date.now() });
30
+ c.set("a", entry("a"));
31
+ c.set("b", entry("b"));
32
+ c.get("a");
33
+ c.set("c", entry("c"));
34
+ expect(c.get("a")).toBeDefined();
35
+ expect(c.get("b")).toBeUndefined();
36
+ });
37
+ });
38
+ describe("ISR background refresh", () => {
39
+ it("skips variants that are younger than their window", async () => {
40
+ const { core, render, renders } = makeCore(8, 30);
41
+ await render("a");
42
+ await render("b");
43
+ expect(renders()).toBe(2);
44
+ const fresh = await core.applyInternalOp("refresh-route", { route: "/plain/[id]" });
45
+ expect(fresh.refreshed).toBe(0);
46
+ expect(renders()).toBe(2);
47
+ vi.useFakeTimers();
48
+ vi.setSystemTime(Date.now() + 31000);
49
+ const stale = await core.applyInternalOp("refresh-route", { route: "/plain/[id]" });
50
+ expect(stale.refreshed).toBe(2);
51
+ expect(renders()).toBe(4);
52
+ });
53
+ });
54
+ describe("page region title", () => {
55
+ it("moves the <title> out of the region html", async () => {
56
+ const page = { route: "/t", source: "t.tsx", mode: "ssr", bundlePath: "t" };
57
+ const core = createSSRCore({
58
+ manifest: { pages: [page], regions: {} },
59
+ maxCacheSize: 4,
60
+ loadPageModule: async () => ({
61
+ default: () => jsx("div", { children: [jsx("title", { children: "Async Title" }), jsx("h1", { children: "hello" })] }),
62
+ }),
63
+ loadRuntimeRenderer: () => () => "",
64
+ });
65
+ const frame = await core.renderPageRegion(page, "page", { route: "/t", url: "/t", method: "GET", headers: {}, params: {} });
66
+ expect(frame.title).toBe("Async Title");
67
+ expect(frame.html).toContain("<h1>hello</h1>");
68
+ expect(frame.html).not.toContain("<title");
69
+ });
70
+ it("carries <Head> meta, link and script tags on the frame, out of the body", async () => {
71
+ const page = { route: "/t", source: "t.tsx", mode: "ssr", bundlePath: "t" };
72
+ const core = createSSRCore({
73
+ manifest: { pages: [page], regions: {} },
74
+ maxCacheSize: 4,
75
+ loadPageModule: async () => ({
76
+ default: () => jsx("div", {
77
+ children: [
78
+ jsx(Head, { children: [jsx("meta", { name: "description", content: "d" }), jsx("link", { rel: "canonical", href: "/c" })] }),
79
+ jsx("h1", { children: "hello" }),
80
+ ],
81
+ }),
82
+ }),
83
+ loadRuntimeRenderer: () => () => "",
84
+ });
85
+ const frame = await core.renderPageRegion(page, "page", { route: "/t", url: "/t", method: "GET", headers: {}, params: {} });
86
+ expect(frame.head).toBe('<meta name="description" content="d"><link rel="canonical" href="/c">');
87
+ expect(frame.html).toBe("<div><h1>hello</h1></div>");
88
+ });
89
+ it("carries the <Head> of a server component region, on a cache hit too", async () => {
90
+ const page = { route: "/t", source: "t.tsx", mode: "isr", revalidate: 60, bundlePath: "t" };
91
+ const region = { id: "r", serverExport: "R", revalidate: 60 };
92
+ const core = createSSRCore({
93
+ manifest: { pages: [page], regions: {} },
94
+ maxCacheSize: 4,
95
+ loadPageModule: async () => ({
96
+ R: () => jsx("p", { children: [jsx(Head, { children: jsx("meta", { name: "author", content: "Ada" }) }), "by Ada"] }),
97
+ }),
98
+ loadRuntimeRenderer: () => () => "",
99
+ });
100
+ const req = { route: "/t", url: "/t", method: "GET", headers: {}, params: {} };
101
+ for (const status of ["miss", "hit"]) {
102
+ const frame = await core.renderRegion(page, region, req);
103
+ expect(frame.cacheStatus).toBe(status);
104
+ expect(frame.head).toBe('<meta name="author" content="Ada">');
105
+ expect(frame.html).toBe("<p>by Ada</p>");
106
+ }
107
+ });
108
+ it("keeps svg <title> elements and prefers the last document title", () => {
109
+ const out = takeHeadTitle('<svg><title>Icon</title></svg><title>One</title><p>x</p><title>Two</title>');
110
+ expect(out.title).toBe("Two");
111
+ expect(out.html).toBe("<svg><title>Icon</title></svg><p>x</p>");
112
+ expect(takeHeadTitle("<svg><title>Only</title></svg>")).toEqual({ title: "", html: "<svg><title>Only</title></svg>" });
113
+ });
114
+ });
115
+ describe("server component region cache keys", () => {
116
+ function regionCore() {
117
+ let renders = 0;
118
+ const page = { route: "/feed", source: "feed.tsx", mode: "isr", revalidate: 60, bundlePath: "feed" };
119
+ const region = { id: "list", serverExport: "List", revalidate: 60 };
120
+ const core = createSSRCore({
121
+ manifest: { pages: [page], regions: {} },
122
+ maxCacheSize: 8,
123
+ loadPageModule: async () => ({
124
+ List: (props) => jsx("p", { children: `page-${props.query?.page ?? "none"}-${++renders}` }),
125
+ Whole: (props) => jsx("p", { children: Object.keys(props.query || {}).join(",") + "-" + ++renders }),
126
+ }),
127
+ loadRuntimeRenderer: () => () => "",
128
+ });
129
+ const render = (query, r = region) => core.renderRegion(page, r, { route: "/feed", url: "/feed", method: "GET", headers: {}, params: {}, query });
130
+ return { render, renders: () => renders, region };
131
+ }
132
+ it("shares one entry across query keys the region never reads", async () => {
133
+ const { render, renders } = regionCore();
134
+ expect((await render({ page: "1" })).cacheStatus).toBe("miss");
135
+ expect(renders()).toBe(1);
136
+ for (let i = 0; i < 20; i++) {
137
+ const f = await render({ page: "1", utm: "junk" + i });
138
+ expect(f.cacheStatus, "junk " + i).toBe("hit");
139
+ }
140
+ expect(renders()).toBe(1);
141
+ expect((await render({ page: "2" })).cacheStatus).toBe("miss");
142
+ expect((await render({ page: "1" })).html).toContain("page-1-1");
143
+ });
144
+ it("a bare first request does not make the region look query-independent", async () => {
145
+ const { render } = regionCore();
146
+ expect((await render({})).html).toContain("page-none-1");
147
+ const f = await render({ page: "7" });
148
+ expect(f.cacheStatus).toBe("miss");
149
+ expect(f.html).toContain("page-7-");
150
+ expect((await render({ page: "7", utm: "x" })).cacheStatus).toBe("hit");
151
+ expect((await render({ page: "8" })).html).toContain("page-8-");
152
+ expect((await render({})).html).toContain("page-none-1");
153
+ });
154
+ it("keeps a hot region when a client sweeps random query values", async () => {
155
+ const { render } = regionCore();
156
+ await render({ page: "1" });
157
+ for (let i = 0; i < 40; i++)
158
+ await render({ page: "1", sweep: String(i) });
159
+ expect((await render({ page: "1" })).cacheStatus).toBe("hit");
160
+ });
161
+ it("falls back to the whole query when the region enumerates it", async () => {
162
+ const { render, renders, region } = regionCore();
163
+ const whole = { ...region, id: "whole", serverExport: "Whole" };
164
+ await render({ a: "1" }, whole);
165
+ expect((await render({ a: "1", b: "2" }, whole)).cacheStatus).toBe("miss");
166
+ expect((await render({ a: "1", b: "2" }, whole)).cacheStatus).toBe("hit");
167
+ expect(renders()).toBe(2);
168
+ });
169
+ });
170
+ describe("runtime bundle region cache keys", () => {
171
+ // A runtime component bundle (an IIFE with __krate_render) gets its props as
172
+ // an object whose query records the keys it reads.
173
+ function bundleCore(render, maxCacheSize = 8) {
174
+ let renders = 0;
175
+ const page = { route: "/feed", source: "feed.tsx", mode: "isr", revalidate: 60, bundlePath: "feed" };
176
+ const region = { id: "list", bundlePath: "r/list", revalidate: 60, props: { nested: { n: 1 } } };
177
+ const core = createSSRCore({
178
+ manifest: { pages: [page], regions: {} },
179
+ maxCacheSize,
180
+ loadPageModule: async () => ({}),
181
+ loadRuntimeRenderer: () => (props) => {
182
+ renders++;
183
+ return render(typeof props === "string" ? JSON.parse(props) : props);
184
+ },
185
+ });
186
+ const run = (query) => core.renderRegion(page, region, { route: "/feed", url: "/feed", method: "GET", headers: {}, params: {}, query });
187
+ return { run, renders: () => renders, region };
188
+ }
189
+ it("keys a region on the query keys it reads, so random values share one entry", async () => {
190
+ const { run, renders } = bundleCore((p) => `<p>page-${p.query?.page ?? "none"}</p>`);
191
+ expect((await run({ page: "1" })).cacheStatus).toBe("miss");
192
+ for (let i = 0; i < 50; i++) {
193
+ const f = await run({ page: "1", utm: "junk" + i, [`k${i}`]: "v" });
194
+ expect(f.cacheStatus, "junk " + i).toBe("hit");
195
+ }
196
+ expect(renders()).toBe(1);
197
+ const other = await run({ page: "2" });
198
+ expect(other.cacheStatus).toBe("miss");
199
+ expect(other.html).toBe("<p>page-2</p>");
200
+ expect((await run({ page: "1" })).html).toBe("<p>page-1</p>");
201
+ });
202
+ it("a region that never reads the query shares one entry for every query", async () => {
203
+ const { run, renders } = bundleCore(() => "<p>static</p>");
204
+ await run({ a: "1" });
205
+ for (let i = 0; i < 20; i++)
206
+ expect((await run({ ["x" + i]: "y" })).cacheStatus).toBe("hit");
207
+ expect((await run({})).cacheStatus).toBe("hit");
208
+ expect(renders()).toBe(1);
209
+ });
210
+ it("keys on the whole query when the region enumerates it", async () => {
211
+ const { run, renders } = bundleCore((p) => `<p>${Object.keys(p.query || {}).join(",")}</p>`);
212
+ await run({ a: "1" });
213
+ expect((await run({ a: "1", b: "2" })).cacheStatus).toBe("miss");
214
+ expect((await run({ a: "1", b: "2" })).cacheStatus).toBe("hit");
215
+ expect(renders()).toBe(2);
216
+ });
217
+ it("serializing the props reads everything too", async () => {
218
+ const { run } = bundleCore((p) => `<p>${JSON.stringify(p)}</p>`);
219
+ await run({ a: "1" });
220
+ expect((await run({ a: "1", b: "2" })).cacheStatus).toBe("miss");
221
+ });
222
+ it("does not let a bundle change the manifest's baked props", async () => {
223
+ const { run, region } = bundleCore((p) => {
224
+ p.nested.n++;
225
+ return `<p>${p.nested.n}</p>`;
226
+ });
227
+ expect((await run({})).html).toBe("<p>2</p>");
228
+ expect(region.props.nested.n).toBe(1);
229
+ });
230
+ it("renders instead of guessing when it does not know what a region reads", async () => {
231
+ // An entry cached by a request without a query must not answer a request
232
+ // with one when the reads are unknown (a fresh process after a restart).
233
+ const page = { route: "/feed", source: "feed.tsx", mode: "isr", revalidate: 60, bundlePath: "feed" };
234
+ const region = { id: "list", bundlePath: "r/list", revalidate: 60 };
235
+ const mk = () => createSSRCore({
236
+ manifest: { pages: [page], regions: {} },
237
+ maxCacheSize: 8,
238
+ loadPageModule: async () => ({}),
239
+ loadRuntimeRenderer: () => (props) => `<p>page-${props.query?.page ?? "none"}</p>`,
240
+ });
241
+ const first = mk();
242
+ const r = (core, query) => core.renderRegion(page, region, { route: "/feed", url: "/feed", method: "GET", headers: {}, params: {}, query });
243
+ expect((await r(first, {})).html).toBe("<p>page-none</p>");
244
+ expect((await r(first, { page: "2" })).html).toBe("<p>page-2</p>");
245
+ });
246
+ });
247
+ describe("page cache never answers a query it cannot match", () => {
248
+ it("after a restart the persisted entry of the bare page does not answer ?page=2", async () => {
249
+ const page = { route: "/list", source: "list.tsx", mode: "isr", revalidate: 60, bundlePath: "list" };
250
+ const store = new MemoryIsrStore(8);
251
+ const mk = () => createSSRCore({
252
+ manifest: { pages: [page], regions: {} },
253
+ isrStore: store,
254
+ loadPageModule: async () => ({
255
+ default: async (props) => {
256
+ const { page: n } = await props.searchParams;
257
+ return jsx("p", { children: `page-${n ?? "none"}` });
258
+ },
259
+ }),
260
+ loadRuntimeRenderer: () => () => "",
261
+ });
262
+ const req = (query) => ({ route: "/list", url: "/list", method: "GET", headers: {}, params: {}, query });
263
+ const before = mk();
264
+ expect((await before.renderPage(req({}))).html).toBe("<p>page-none</p>");
265
+ // A new process shares the persisted entries but has not learned what the page reads.
266
+ const after = mk();
267
+ const hit = await after.renderPage(req({}));
268
+ expect(hit.cacheStatus).toBe("hit");
269
+ const second = await after.renderPage(req({ page: "2" }));
270
+ expect(second.html).toBe("<p>page-2</p>");
271
+ expect(second.cacheStatus).toBe("miss");
272
+ expect((await after.renderPage(req({ page: "2" }))).cacheStatus).toBe("hit");
273
+ expect((await after.renderPage(req({ page: "3" }))).html).toBe("<p>page-3</p>");
274
+ });
275
+ it("a page that reads no query key is cached once for every query string", async () => {
276
+ const page = { route: "/plain", source: "p.tsx", mode: "isr", revalidate: 60, bundlePath: "p" };
277
+ let renders = 0;
278
+ const core = createSSRCore({
279
+ manifest: { pages: [page], regions: {} },
280
+ maxCacheSize: 8,
281
+ loadPageModule: async () => ({ default: () => jsx("p", { children: "n" + ++renders }) }),
282
+ loadRuntimeRenderer: () => () => "",
283
+ });
284
+ const req = (query) => ({ route: "/plain", url: "/plain", method: "GET", headers: {}, params: {}, query });
285
+ await core.renderPage(req({ a: "1" }));
286
+ for (let i = 0; i < 30; i++)
287
+ expect((await core.renderPage(req({ ["q" + i]: "v" }))).cacheStatus).toBe("hit");
288
+ expect(renders).toBe(1);
289
+ });
290
+ });
291
+ describe("one client cannot flush the page and region caches", () => {
292
+ it("keeps a page that was hit when 520 one-off variants follow it", async () => {
293
+ const { render } = makeCore(512);
294
+ expect((await render("hot")).cacheStatus).toBe("miss");
295
+ expect((await render("hot")).cacheStatus).toBe("hit");
296
+ expect((await render("hot")).cacheStatus).toBe("hit");
297
+ for (let i = 1; i <= 520; i++)
298
+ await render("x" + i);
299
+ expect((await render("hot")).cacheStatus).toBe("hit");
300
+ });
301
+ it("keeps a hot region when a client mints 520 params variants", async () => {
302
+ const page = { route: "/p/[id]", source: "p.tsx", mode: "isr", revalidate: 60, bundlePath: "p" };
303
+ const region = { id: "r", bundlePath: "r/r", revalidate: 60 };
304
+ const core = createSSRCore({
305
+ manifest: { pages: [page], regions: {} },
306
+ maxCacheSize: 512,
307
+ loadPageModule: async () => ({}),
308
+ loadRuntimeRenderer: () => (props) => `<p>${props.params.id}</p>`,
309
+ });
310
+ const run = (id) => core.renderRegion(page, region, { route: "/p/[id]", url: "/p/" + id, method: "GET", headers: {}, params: { id }, query: {} });
311
+ await run("hot");
312
+ expect((await run("hot")).cacheStatus).toBe("hit");
313
+ for (let i = 1; i <= 520; i++)
314
+ await run("x" + i);
315
+ expect((await run("hot")).cacheStatus).toBe("hit");
316
+ });
317
+ it("still evicts one-off entries and bounds the cache", () => {
318
+ const c = new ISRCache(4);
319
+ const entry = (html) => ({ html, timestamp: Date.now() });
320
+ for (let i = 0; i < 100; i++)
321
+ c.set("k" + i, entry("v"));
322
+ expect(c.size).toBe(4);
323
+ });
324
+ });
@@ -0,0 +1,3 @@
1
+ import type { StaticLayer } from "./server-handler.js";
2
+ /** pages maps dist-relative slash paths ("about/index.html") to their HTML. */
3
+ export declare function createMemoryStaticLayer(pages: Record<string, string>): StaticLayer;
@@ -0,0 +1,47 @@
1
+ // A StaticLayer over prerendered HTML pages carried in the server bundle. The
2
+ // platforms whose CDN would otherwise serve static pages before the function
3
+ // (Vercel, Netlify) route page requests to the function when the project has
4
+ // middleware; the function then answers prerendered pages from here, after the
5
+ // middleware ran. Assets are never held here: they keep going to the CDN.
6
+ import { baseName } from "./handler-routing.js";
7
+ function decode(p) {
8
+ try {
9
+ return decodeURIComponent(p);
10
+ }
11
+ catch {
12
+ return p;
13
+ }
14
+ }
15
+ /** pages maps dist-relative slash paths ("about/index.html") to their HTML. */
16
+ export function createMemoryStaticLayer(pages) {
17
+ const find = (urlPath) => {
18
+ const rel = decode(urlPath).replace(/^\/+/, "");
19
+ if (rel === "")
20
+ return pages["index.html"] !== undefined ? { key: "index.html", redirect: false } : null;
21
+ if (rel.endsWith("/")) {
22
+ const k = rel + "index.html";
23
+ return pages[k] !== undefined ? { key: k, redirect: false } : null;
24
+ }
25
+ if (pages[rel] !== undefined)
26
+ return { key: rel, redirect: false };
27
+ const k = rel + "/index.html";
28
+ return pages[k] !== undefined ? { key: k, redirect: true } : null;
29
+ };
30
+ return {
31
+ exists: (urlPath) => find(urlPath) !== null,
32
+ isAsset: () => false,
33
+ async serve(request, urlPath) {
34
+ const hit = find(urlPath);
35
+ if (!hit)
36
+ return null;
37
+ if (hit.redirect) {
38
+ const u = new URL(request.url);
39
+ return new Response(null, { status: 301, headers: { Location: baseName(urlPath) + "/" + u.search } });
40
+ }
41
+ return new Response(request.method === "HEAD" ? null : pages[hit.key], {
42
+ status: 200,
43
+ headers: { "Content-Type": "text/html; charset=utf-8" },
44
+ });
45
+ },
46
+ };
47
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,26 @@
1
+ // @vitest-environment node
2
+ import { describe, expect, it } from "vitest";
3
+ import { createMemoryStaticLayer } from "./static-memory.js";
4
+ describe("createMemoryStaticLayer", () => {
5
+ const layer = createMemoryStaticLayer({ "index.html": "home", "about/index.html": "about", "404.html": "nf" });
6
+ const req = (p, method = "GET") => new Request("https://x.test" + p + "?q=1", { method });
7
+ it("finds pages by directory and file path", async () => {
8
+ expect(await layer.exists("/")).toBe(true);
9
+ expect(await layer.exists("/about/")).toBe(true);
10
+ expect(await layer.exists("/about")).toBe(true);
11
+ expect(await layer.exists("/404.html")).toBe(true);
12
+ expect(await layer.exists("/nope/")).toBe(false);
13
+ expect(await layer.isAsset("/about/")).toBe(false);
14
+ });
15
+ it("serves HTML, redirects a bare directory and answers HEAD without a body", async () => {
16
+ const ok = (await layer.serve(req("/about/"), "/about/"));
17
+ expect(ok.status).toBe(200);
18
+ expect(ok.headers.get("content-type")).toBe("text/html; charset=utf-8");
19
+ expect(await ok.text()).toBe("about");
20
+ const redir = (await layer.serve(req("/about"), "/about"));
21
+ expect(redir.status).toBe(301);
22
+ expect(redir.headers.get("location")).toBe("about/?q=1");
23
+ expect(await (await layer.serve(req("/", "HEAD"), "/")).text()).toBe("");
24
+ expect(await layer.serve(req("/zzz/"), "/zzz/")).toBeNull();
25
+ });
26
+ });
@@ -0,0 +1,12 @@
1
+ export interface FakeRedis {
2
+ readonly port: number;
3
+ /** Drops every connection and stops listening (a Redis that died). */
4
+ kill(): Promise<void>;
5
+ /** Listens again on the same port. */
6
+ revive(): Promise<void>;
7
+ keys(): string[];
8
+ commands: string[][];
9
+ }
10
+ export declare function startFakeRedis(opts?: {
11
+ password?: string;
12
+ }): Promise<FakeRedis>;
@@ -0,0 +1,131 @@
1
+ // A tiny in-process RESP server for tests: the subset of Redis the cache adapter
2
+ // uses (strings, sets, expiry, pub/sub). It can be killed and revived on its port.
3
+ import net from 'node:net';
4
+ import { RespParser } from './resp.js';
5
+ export async function startFakeRedis(opts = {}) {
6
+ const strings = new Map();
7
+ const sets = new Map();
8
+ const expires = new Map();
9
+ const subs = new Map();
10
+ const sockets = new Set();
11
+ const commands = [];
12
+ let server;
13
+ let port = 0;
14
+ const alive = (k) => {
15
+ const e = expires.get(k);
16
+ if (e !== undefined && e <= Date.now()) {
17
+ strings.delete(k);
18
+ sets.delete(k);
19
+ expires.delete(k);
20
+ }
21
+ };
22
+ const bulk = (v) => (v === null ? '$-1\r\n' : `$${Buffer.byteLength(v)}\r\n${v}\r\n`);
23
+ const arr = (items) => `*${items.length}\r\n${items.map((i) => bulk(i)).join('')}`;
24
+ function handle(sock, args) {
25
+ commands.push(args);
26
+ const cmd = args[0].toUpperCase();
27
+ switch (cmd) {
28
+ case 'AUTH':
29
+ return opts.password !== undefined && args[args.length - 1] !== opts.password ? '-WRONGPASS invalid password\r\n' : '+OK\r\n';
30
+ case 'SELECT':
31
+ case 'PING':
32
+ return '+OK\r\n';
33
+ case 'GET':
34
+ alive(args[1]);
35
+ return bulk(strings.has(args[1]) ? strings.get(args[1]) : null);
36
+ case 'SET':
37
+ strings.set(args[1], args[2]);
38
+ expires.delete(args[1]);
39
+ if (args[3] && args[3].toUpperCase() === 'EX')
40
+ expires.set(args[1], Date.now() + parseInt(args[4], 10) * 1000);
41
+ return '+OK\r\n';
42
+ case 'DEL': {
43
+ let n = 0;
44
+ for (const k of args.slice(1)) {
45
+ alive(k);
46
+ if (strings.delete(k))
47
+ n++;
48
+ if (sets.delete(k))
49
+ n++;
50
+ }
51
+ return `:${n}\r\n`;
52
+ }
53
+ case 'SADD': {
54
+ let s = sets.get(args[1]);
55
+ if (!s)
56
+ sets.set(args[1], (s = new Set()));
57
+ let n = 0;
58
+ for (const m of args.slice(2)) {
59
+ if (!s.has(m)) {
60
+ s.add(m);
61
+ n++;
62
+ }
63
+ }
64
+ return `:${n}\r\n`;
65
+ }
66
+ case 'SMEMBERS':
67
+ alive(args[1]);
68
+ return arr([...(sets.get(args[1]) || [])]);
69
+ case 'EXPIRE':
70
+ expires.set(args[1], Date.now() + parseInt(args[2], 10) * 1000);
71
+ return ':1\r\n';
72
+ case 'PUBLISH': {
73
+ const targets = subs.get(args[1]) || new Set();
74
+ for (const t of targets)
75
+ t.write(`*3\r\n${bulk('message')}${bulk(args[1])}${bulk(args[2])}`);
76
+ return `:${targets.size}\r\n`;
77
+ }
78
+ case 'SUBSCRIBE': {
79
+ let s = subs.get(args[1]);
80
+ if (!s)
81
+ subs.set(args[1], (s = new Set()));
82
+ s.add(sock);
83
+ return `*3\r\n${bulk('subscribe')}${bulk(args[1])}:1\r\n`;
84
+ }
85
+ default:
86
+ return `-ERR unknown command ${cmd}\r\n`;
87
+ }
88
+ }
89
+ function listen() {
90
+ return new Promise((resolve) => {
91
+ server = net.createServer((sock) => {
92
+ sockets.add(sock);
93
+ const parser = new RespParser();
94
+ sock.on('data', (chunk) => {
95
+ parser.push(chunk);
96
+ for (;;) {
97
+ const cmd = parser.next();
98
+ if (cmd === undefined)
99
+ return;
100
+ sock.write(handle(sock, cmd.map(String)));
101
+ }
102
+ });
103
+ sock.on('close', () => {
104
+ sockets.delete(sock);
105
+ for (const s of subs.values())
106
+ s.delete(sock);
107
+ });
108
+ sock.on('error', () => { });
109
+ });
110
+ server.listen(port, '127.0.0.1', () => {
111
+ port = server.address().port;
112
+ resolve();
113
+ });
114
+ });
115
+ }
116
+ await listen();
117
+ const stop = () => new Promise((resolve) => {
118
+ for (const s of sockets)
119
+ s.destroy();
120
+ server.close(() => resolve());
121
+ });
122
+ return {
123
+ get port() {
124
+ return port;
125
+ },
126
+ kill: stop,
127
+ revive: listen,
128
+ keys: () => [...strings.keys()],
129
+ commands,
130
+ };
131
+ }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Run `fn` with useId() numbering scoped to a list row. The compiler numbers
3
+ * the useId() calls of a server-rendered row `<prefix>-u0`, `-u1`, ... in
4
+ * render order, so a row adopted from the server keeps its ids.
5
+ */
6
+ export declare function krateWithIdScope<T>(prefix: string, fn: () => T): T;
7
+ /** The compiled form of React's useId(). */
8
+ export declare function __krate_useId(): string;
package/dist/use-id.js ADDED
@@ -0,0 +1,40 @@
1
+ // useId() for components that render on the client. Most useId() calls are
2
+ // resolved by the compiler to a literal that the HTML and the hydration code
3
+ // share; this covers the components the runtime itself creates, such as the
4
+ // rows of a keyed list.
5
+ let scope = null;
6
+ let counter = 0;
7
+ const encoder = typeof TextEncoder !== 'undefined' ? new TextEncoder() : null;
8
+ /**
9
+ * Percent-encodes every byte of an id part outside [A-Za-z0-9_.:$-], so a list
10
+ * key such as "a b" still makes a valid id. The compiler applies the same rule.
11
+ */
12
+ function idSafe(s) {
13
+ return s.replace(/[^A-Za-z0-9_.:$-]/gu, (c) => {
14
+ const bytes = encoder ? Array.from(encoder.encode(c)) : [c.charCodeAt(0) & 0xff];
15
+ return bytes.map((b) => '%' + b.toString(16).toUpperCase().padStart(2, '0')).join('');
16
+ });
17
+ }
18
+ /**
19
+ * Run `fn` with useId() numbering scoped to a list row. The compiler numbers
20
+ * the useId() calls of a server-rendered row `<prefix>-u0`, `-u1`, ... in
21
+ * render order, so a row adopted from the server keeps its ids.
22
+ */
23
+ export function krateWithIdScope(prefix, fn) {
24
+ if (!prefix)
25
+ return fn();
26
+ const saved = scope;
27
+ scope = { prefix: idSafe(prefix), n: 0 };
28
+ try {
29
+ return fn();
30
+ }
31
+ finally {
32
+ scope = saved;
33
+ }
34
+ }
35
+ /** The compiled form of React's useId(). */
36
+ export function __krate_useId() {
37
+ if (scope)
38
+ return 'krate-' + scope.prefix + '-u' + scope.n++;
39
+ return 'krate_u' + counter++;
40
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@krate/runtime",
3
- "version": "0.5.0-beta.1",
3
+ "version": "0.5.0-beta.2",
4
4
  "description": "Client-side runtime for Krate - signals, hydration, SPA router, resources, and context.",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -34,6 +34,10 @@
34
34
  "types": "./dist/server.d.ts",
35
35
  "default": "./dist/server.js"
36
36
  },
37
+ "./highlight": {
38
+ "types": "./dist/highlight.d.ts",
39
+ "default": "./dist/highlight.js"
40
+ },
37
41
  "./cache": {
38
42
  "types": "./dist/cache.d.ts",
39
43
  "default": "./dist/cache.js"
@@ -65,6 +69,30 @@
65
69
  "./slot": {
66
70
  "types": "./dist/slot.d.ts",
67
71
  "default": "./dist/slot.js"
72
+ },
73
+ "./server-handler": {
74
+ "types": "./dist/server-handler.d.ts",
75
+ "default": "./dist/server-handler.js"
76
+ },
77
+ "./node-server": {
78
+ "types": "./dist/node-server.d.ts",
79
+ "default": "./dist/node-server.js"
80
+ },
81
+ "./assets-static": {
82
+ "types": "./dist/assets-static.d.ts",
83
+ "default": "./dist/assets-static.js"
84
+ },
85
+ "./cache-adapter": {
86
+ "types": "./dist/cache-adapter.d.ts",
87
+ "default": "./dist/cache-adapter.js"
88
+ },
89
+ "./cache-redis": {
90
+ "types": "./dist/cache-redis.d.ts",
91
+ "default": "./dist/cache-redis.js"
92
+ },
93
+ "./og": {
94
+ "types": "./dist/og.d.ts",
95
+ "default": "./dist/og.js"
68
96
  }
69
97
  },
70
98
  "files": [