@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,86 +1,6 @@
1
1
  // @vitest-environment node
2
2
  import { describe, expect, it } from "vitest";
3
- import { allSuspense, canStreamOutOfOrder, flashMessages, injectFlashNotice, parseRegionShell, regionReplaceScript, replaceTitle, requestFlash, signFlash, verifyFlash, flashPayloadOf, splitBodyScripts, spliceShell, } from "./handler-html.js";
4
- const suspense = (id, inner = "") => `<!--suspense:${id}-->${inner}<!--/suspense:${id}-->`;
5
- const region = (id, inner = "") => `<!--region:${id}-->${inner}<!--/region:${id}-->`;
6
- function splice(shell, html) {
7
- const parsed = parseRegionShell(shell);
8
- expect(parsed.ok).toBe(true);
9
- const out = [];
10
- spliceShell(shell, parsed.roots, new Map(Object.entries(html)), (c) => out.push(c));
11
- return out.join("");
12
- }
13
- describe("parseRegionShell", () => {
14
- it("reports a shell without markers as not ok", () => {
15
- const p = parseRegionShell("<html><body>static</body></html>");
16
- expect(p.ok).toBe(false);
17
- expect(p.roots).toEqual([]);
18
- });
19
- it("finds sibling and nested markers in document order", () => {
20
- const shell = `<main>${suspense("a", "fb-a")}${region("b", suspense("c", "fb-c"))}</main>`;
21
- const p = parseRegionShell(shell);
22
- expect(p.ok).toBe(true);
23
- expect(p.all.map((b) => b.id)).toEqual(["a", "b", "c"]);
24
- expect(p.roots.map((b) => b.id)).toEqual(["a", "b"]);
25
- expect(p.roots[1].children.map((b) => b.id)).toEqual(["c"]);
26
- const a = p.all[0];
27
- expect(shell.slice(a.openEnd, a.fbEnd)).toBe("fb-a");
28
- });
29
- it("rejects a marker whose closing comment is missing, dropping partial results", () => {
30
- const p = parseRegionShell(`${suspense("a", "x")}<!--suspense:b-->never closed`);
31
- expect(p.ok).toBe(false);
32
- expect(p.roots).toEqual([]);
33
- expect(p.all).toEqual([]);
34
- });
35
- it("does not confuse a region and a suspense marker that share an id", () => {
36
- const p = parseRegionShell(`<!--suspense:x-->s<!--/region:x-->`);
37
- expect(p.ok).toBe(false);
38
- });
39
- });
40
- describe("streaming mode", () => {
41
- it("streams siblings out of order, but not the coarse page region or nested markers", () => {
42
- expect(canStreamOutOfOrder(parseRegionShell(suspense("a") + suspense("b")).all)).toBe(true);
43
- expect(canStreamOutOfOrder(parseRegionShell(suspense("page")).all)).toBe(false);
44
- expect(canStreamOutOfOrder(parseRegionShell(suspense("a", suspense("b"))).all)).toBe(false);
45
- expect(canStreamOutOfOrder([])).toBe(false);
46
- });
47
- it("allSuspense is false as soon as one region marker is present", () => {
48
- expect(allSuspense(parseRegionShell(suspense("a") + suspense("b")).all)).toBe(true);
49
- expect(allSuspense(parseRegionShell(suspense("a") + region("b")).all)).toBe(false);
50
- });
51
- });
52
- describe("splitBodyScripts", () => {
53
- it("defers the first body script and everything after it", () => {
54
- const [head, tail] = splitBodyScripts("<html><body><p>x</p><SCRIPT src=/a.js></SCRIPT></body></html>");
55
- expect(head).toBe("<html><body><p>x</p>");
56
- expect(tail).toBe("<SCRIPT src=/a.js></SCRIPT></body></html>");
57
- });
58
- it("ignores a script in <head>", () => {
59
- const shell = "<html><head><script>1</script></head><body><p>x</p></body></html>";
60
- const [head, tail] = splitBodyScripts(shell);
61
- expect(head).toBe("<html><head><script>1</script></head><body><p>x</p>");
62
- expect(tail).toBe("</body></html>");
63
- });
64
- it("returns the whole shell when there is no body", () => {
65
- expect(splitBodyScripts("<p>fragment</p>")).toEqual(["<p>fragment</p>", ""]);
66
- });
67
- it("round-trips: head + tail is the original", () => {
68
- const shell = "<body>a<script>b</script>c</body>";
69
- const [h, t] = splitBodyScripts(shell);
70
- expect(h + t).toBe(shell);
71
- });
72
- });
73
- describe("replaceTitle", () => {
74
- it("swaps the content and drops title attributes", () => {
75
- expect(replaceTitle('<head><title data-x="1">Old</title></head>', "New")).toBe("<head><title>New</title></head>");
76
- });
77
- it("leaves a shell without a title alone", () => {
78
- expect(replaceTitle("<head></head>", "New")).toBe("<head></head>");
79
- });
80
- it("does not interpret replacement patterns in the new title", () => {
81
- expect(replaceTitle("<title>Old</title>", "Cost $& $1 $$")).toBe("<title>Cost $& $1 $$</title>");
82
- });
83
- });
3
+ import { injectFlashNotice, regionReplaceScript, requestFlash, signFlash, } from "./handler-html.js";
84
4
  describe("regionReplaceScript", () => {
85
5
  const payloadOf = (script) => {
86
6
  const m = /var html=(".*?");var kinds=/s.exec(script);
@@ -97,64 +17,6 @@ describe("regionReplaceScript", () => {
97
17
  expect(script).not.toContain("\u2029");
98
18
  expect(payloadOf(script)).toBe(html);
99
19
  });
100
- it("quotes the id as a JSON string", () => {
101
- const script = regionReplaceScript("a\"b'c\\d", "x");
102
- expect(script).toContain('var id="a\\"b\'c\\\\d";');
103
- });
104
- it("executes against a minimal DOM and replaces only the marked block", () => {
105
- // Run the generated script with stub DOM objects to check the splice logic.
106
- const comments = [
107
- { nodeType: 8, nodeValue: "suspense:r1", nextSibling: null },
108
- { nodeType: 8, nodeValue: "/suspense:r1", nextSibling: null },
109
- ];
110
- comments[0].nextSibling = { nodeType: 3, nodeValue: "fallback", nextSibling: comments[1] };
111
- const calls = [];
112
- let idx = -1;
113
- const doc = {
114
- documentElement: {},
115
- createTreeWalker: () => ({
116
- get currentNode() {
117
- return comments[idx];
118
- },
119
- nextNode: () => ++idx < comments.length,
120
- }),
121
- createRange: () => ({
122
- setStartAfter: (n) => calls.push("start:" + n.nodeValue),
123
- setEndBefore: (n) => calls.push("end:" + n.nodeValue),
124
- deleteContents: () => calls.push("delete"),
125
- insertNode: (n) => calls.push("insert:" + n),
126
- }),
127
- createElement: () => {
128
- const t = { content: "<c>", set innerHTML(v) { t.content = v; } };
129
- return t;
130
- },
131
- };
132
- const code = regionReplaceScript("r1", "<b>done</b>").replace(/^<script[^>]*>/, "").replace(/<\/script>$/, "");
133
- new Function("document", "NodeFilter", code)(doc, { SHOW_COMMENT: 128 });
134
- expect(calls).toEqual(["start:suspense:r1", "end:/suspense:r1", "delete", "insert:<b>done</b>"]);
135
- });
136
- });
137
- describe("spliceShell", () => {
138
- it("replaces the baked content of a marker and keeps the markers and the rest of the shell", () => {
139
- const shell = `<main>${suspense("a", "loading")}<footer>f</footer></main>`;
140
- expect(splice(shell, { a: "<p>done</p>" })).toBe(`<main>${suspense("a", "<p>done</p>")}<footer>f</footer></main>`);
141
- });
142
- it("keeps the baked fallback of a region that produced no HTML", () => {
143
- const shell = `${suspense("a", "fb-a")}|${suspense("b", "fb-b")}`;
144
- expect(splice(shell, { b: "B" })).toBe(`${suspense("a", "fb-a")}|${suspense("b", "B")}`);
145
- });
146
- it("descends into a suspense fallback to fill nested regions", () => {
147
- const shell = suspense("outer", `shell ${region("inner", "baked-inner")} end`);
148
- expect(splice(shell, { inner: "NEW" })).toBe(suspense("outer", `shell ${region("inner", "NEW")} end`));
149
- });
150
- it("lets the outer region win over nested ones when both have HTML", () => {
151
- const shell = suspense("outer", region("inner", "baked"));
152
- expect(splice(shell, { outer: "OUT", inner: "IN" })).toBe(suspense("outer", "OUT"));
153
- });
154
- it("leaves a standalone runtime region empty when it produced no HTML (same as the Go host)", () => {
155
- const shell = `a${region("r", suspense("s", "baked"))}b`;
156
- expect(splice(shell, { s: "IGNORED" })).toBe(`a${region("r")}b`);
157
- });
158
20
  });
159
21
  const SECRET = "krate-test-flash-secret-0123456789";
160
22
  // The same vector is pinned in internal/build/serve_flash_test.go: what the Go
@@ -167,20 +29,6 @@ async function flashCookie(payload, secret = SECRET) {
167
29
  }
168
30
  describe("requestFlash", () => {
169
31
  const payload = { a: "act1", r: { error: "Name is required" } };
170
- it("reads the signed flash cookie among other cookies", async () => {
171
- const got = await requestFlash(`theme=dark; krate_flash=${await flashCookie(payload)}; x=1`, SECRET);
172
- expect(got?.payload).toEqual(payload);
173
- });
174
- it("accepts a quoted value and returns the payload part as raw", async () => {
175
- const got = await requestFlash(`krate_flash="${await flashCookie(payload)}"`, SECRET);
176
- expect(got?.payload).toEqual(payload);
177
- expect(got?.raw).toBe(VECTOR_PAYLOAD);
178
- });
179
- it("signs and verifies the same bytes as the Go host", async () => {
180
- expect(await signFlash(SECRET, VECTOR_PAYLOAD)).toBe(VECTOR_COOKIE);
181
- expect(await verifyFlash(SECRET, VECTOR_COOKIE)).toBe(VECTOR_PAYLOAD);
182
- expect(flashPayloadOf("act1", { error: "Name is required" })).toBe(VECTOR_PAYLOAD);
183
- });
184
32
  it("never trusts an unsigned, forged or foreign-signed cookie", async () => {
185
33
  const unsigned = await flashCookie(payload, null);
186
34
  expect(await requestFlash(`krate_flash=${unsigned}`, SECRET)).toBeNull();
@@ -195,47 +43,8 @@ describe("requestFlash", () => {
195
43
  expect(await requestFlash(`krate_flash=${VECTOR_COOKIE}`, null)).toBeNull();
196
44
  expect(await requestFlash(`krate_flash=${VECTOR_COOKIE}`, "")).toBeNull();
197
45
  });
198
- it("does not match a cookie that merely ends with the name", async () => {
199
- expect(await requestFlash(`other_krate_flash=${await flashCookie(payload)}`, SECRET)).toBeNull();
200
- });
201
- it("returns null for no header, an empty value, bad base64, bad JSON or no action id", async () => {
202
- expect(await requestFlash(null, SECRET)).toBeNull();
203
- expect(await requestFlash("krate_flash=", SECRET)).toBeNull();
204
- expect(await requestFlash("krate_flash=%%%", SECRET)).toBeNull();
205
- expect(await requestFlash(`krate_flash=${await signFlash(SECRET, Buffer.from("not json").toString("base64url"))}`, SECRET)).toBeNull();
206
- expect(await requestFlash(`krate_flash=${await flashCookie({ a: "", r: "x" })}`, SECRET)).toBeNull();
207
- expect(await requestFlash(`krate_flash=${await flashCookie({ r: "x" })}`, SECRET)).toBeNull();
208
- });
209
- it("decodes multi-byte text", async () => {
210
- const got = await requestFlash(`krate_flash=${await flashCookie({ a: "a", r: "café €" })}`, SECRET);
211
- expect(got?.payload.r).toBe("café €");
212
- });
213
- });
214
- describe("flashMessages", () => {
215
- it("collects strings in a stable order (sorted keys, array order), trimmed", () => {
216
- expect(flashMessages({ b: " second ", a: "first", c: ["x", "", " ", "y"], n: 5, ok: true })).toEqual(["first", "second", "x", "y"]);
217
- });
218
- it("stops descending after a few levels", () => {
219
- expect(flashMessages({ a: { b: { c: { d: "too deep" } } } })).toEqual([]);
220
- expect(flashMessages({ a: { b: { c: "kept" } } })).toEqual(["kept"]);
221
- });
222
- it("handles a bare string and empty values", () => {
223
- expect(flashMessages("hi")).toEqual(["hi"]);
224
- expect(flashMessages(null)).toEqual([]);
225
- expect(flashMessages(undefined)).toEqual([]);
226
- });
227
46
  });
228
47
  describe("injectFlashNotice", () => {
229
- const page = `<body><form method="post" action="/__krate/action/save"><input name="n"></form><form action="/__krate/action/other"></form></body>`;
230
- it("inserts the notice right after the opening tag of the form that produced it", () => {
231
- const out = injectFlashNotice(page, "RAW", { a: "save", r: { error: "Bad <name>" } });
232
- expect(out).not.toBeNull();
233
- const first = out.indexOf("krate-flash");
234
- expect(first).toBeGreaterThan(out.indexOf('action="/__krate/action/save"'));
235
- expect(first).toBeLessThan(out.indexOf('<input name="n">'));
236
- // the other form is untouched
237
- expect(out.match(/krate-flash"/g)).toHaveLength(1);
238
- });
239
48
  it("escapes the message, the action id and the cookie value", () => {
240
49
  const out = injectFlashNotice(`<form action="/__krate/action/a&quot;b"></form>`, 'v"><img src=x onerror=alert(1)>', { a: 'a&quot;b', r: "<script>alert(1)</script>" });
241
50
  expect(out).not.toContain("<script>");
@@ -243,14 +52,4 @@ describe("injectFlashNotice", () => {
243
52
  expect(out).toContain("&lt;script&gt;");
244
53
  expect(out).toContain('role="alert"');
245
54
  });
246
- it("matches an action id that contains regex characters literally", () => {
247
- const html = `<form action="/__krate/action/a.b+c"></form><form action="/__krate/action/aXb+c"></form>`;
248
- const out = injectFlashNotice(html, "v", { a: "a.b+c", r: "msg" });
249
- expect(out.indexOf("krate-flash")).toBeLessThan(out.indexOf("aXb+c"));
250
- expect(out.match(/krate-flash"/g)).toHaveLength(1);
251
- });
252
- it("returns null when there is nothing to show or no matching form", () => {
253
- expect(injectFlashNotice(page, "v", { a: "save", r: 7 })).toBeNull();
254
- expect(injectFlashNotice(page, "v", { a: "missing", r: "msg" })).toBeNull();
255
- });
256
55
  });
@@ -178,6 +178,9 @@ export function isInternalOutputPath(urlPath) {
178
178
  const p = cleanPath("/" + decodePath(urlPath).replace(/\\/g, "/"));
179
179
  if (p === "/.krate" || p.startsWith("/.krate/"))
180
180
  return true;
181
+ // The shell of a segment page that renders per request is not a page of the site.
182
+ if (/(^|\/)__(401|403|404|500)(\/(index\.html)?)?$/.test(p))
183
+ return true;
181
184
  return p === "/server-manifest.json" || p === "/api-node" || p.startsWith("/api-node/");
182
185
  }
183
186
  export function isHiddenName(name) {
@@ -10,6 +10,8 @@ export interface SegmentEntry {
10
10
  error?: string;
11
11
  forbidden?: string;
12
12
  unauthorized?: string;
13
+ /** Roles whose page renders per request (its file holds the baked shell). */
14
+ dynamic?: SegmentKind[];
13
15
  }
14
16
  export interface SegmentMatch {
15
17
  /** Page path relative to the output dir ("blog/404.html"). */
@@ -17,7 +19,11 @@ export interface SegmentMatch {
17
19
  key: string;
18
20
  /** Dynamic-segment values when matched against a URL, else undefined. */
19
21
  params?: Record<string, string>;
22
+ /** The renderer's route for a page that renders per request (build/segments.go SegmentRoute). */
23
+ route?: string;
20
24
  }
25
+ /** The route the renderer knows a request-time segment page by ("/__404", "/blog/__404"). */
26
+ export declare function segmentRoute(key: string, kind: SegmentKind): string;
21
27
  /**
22
28
  * Returns the nearest segment page of a kind. matched: the request matched a
23
29
  * route whose source directory is segDir, so the lookup walks up from it.
@@ -9,6 +9,20 @@ export const SEGMENT_KIND_OF_STATUS = {
9
9
  404: "notFound",
10
10
  500: "error",
11
11
  };
12
+ const KIND_STATUS = { notFound: 404, error: 500, forbidden: 403, unauthorized: 401 };
13
+ /** The route the renderer knows a request-time segment page by ("/__404", "/blog/__404"). */
14
+ export function segmentRoute(key, kind) {
15
+ const dir = "__" + KIND_STATUS[kind];
16
+ return key === "" ? "/" + dir : "/" + key + "/" + dir;
17
+ }
18
+ function matchOf(e, kind, params) {
19
+ const m = { file: entryPage(e, kind), key: e.key };
20
+ if (params)
21
+ m.params = params;
22
+ if (e.dynamic && e.dynamic.includes(kind))
23
+ m.route = segmentRoute(e.key, kind);
24
+ return m;
25
+ }
12
26
  function entryPage(e, kind) {
13
27
  switch (kind) {
14
28
  case "error":
@@ -36,7 +50,7 @@ export function lookupSegmentPage(entries, kind, urlPath, matched, segDir) {
36
50
  for (;;) {
37
51
  const e = byKey.get(dir);
38
52
  if (e && entryPage(e, kind) !== "")
39
- return { file: entryPage(e, kind), key: e.key };
53
+ return matchOf(e, kind);
40
54
  if (dir === "")
41
55
  return null;
42
56
  const i = dir.lastIndexOf("/");
@@ -58,7 +72,7 @@ export function lookupSegmentPage(entries, kind, urlPath, matched, segDir) {
58
72
  }
59
73
  if (!best)
60
74
  return null;
61
- return { file: entryPage(best, kind), key: best.key, params: bestParams };
75
+ return matchOf(best, kind, bestParams);
62
76
  }
63
77
  /** Matches the leading segments of urlPath; a trailing catch-all takes the rest. */
64
78
  function matchRoutePrefix(urlPath, pattern) {
@@ -1,75 +1,16 @@
1
1
  // @vitest-environment node
2
2
  import { describe, expect, it } from "vitest";
3
- import { fillServerError, lookupSegmentPage, newServerError, SEGMENT_KIND_OF_STATUS } from "./handler-segments.js";
4
- import { createKrateHandler } from "./server-handler.js";
5
- import { jsx } from "./server.js";
6
- describe("lookupSegmentPage (port of build/segments.go)", () => {
7
- it("URL walk", () => {
3
+ import { fillServerError, lookupSegmentPage, newServerError, segmentRoute } from "./handler-segments.js";
4
+ describe("request-time segment pages", () => {
5
+ it("names the renderer route of a dynamic entry and only of that role", () => {
8
6
  const entries = [
9
- { key: "", dir: "", notFound: "404.html", error: "500.html" },
7
+ { key: "", dir: "", notFound: "404.html", error: "500.html", dynamic: ["notFound"] },
10
8
  { key: "blog", dir: "blog", notFound: "blog/404.html" },
11
- { key: "blog/new", dir: "blog/new", notFound: "blog/new/404.html" },
12
- { key: "blog/[slug]", dir: "blog/[slug]", notFound: "blog/[slug]/404.html" },
13
- { key: "docs/[...rest]", dir: "docs/[...rest]", notFound: "docs/[...rest]/404.html" },
14
- { key: "(shop)", dir: "", group: true, notFound: "(shop)/404.html" },
15
- { key: "(shop)/cart", dir: "cart", group: true, notFound: "(shop)/cart/404.html" },
16
9
  ];
17
- const cases = [
18
- ["/", "notFound", "404.html"],
19
- ["/nope", "notFound", "404.html"],
20
- ["/blog/", "notFound", "blog/404.html"],
21
- ["/blog", "notFound", "blog/404.html"],
22
- ["/blog/new/x/y", "notFound", "blog/new/404.html"],
23
- ["/blog/hello", "notFound", "blog/[slug]/404.html", "hello"],
24
- ["/blog/hello/deeper/still", "notFound", "blog/[slug]/404.html", "hello"],
25
- ["/docs", "notFound", "404.html"],
26
- ["/docs/a/b/c", "notFound", "docs/[...rest]/404.html"],
27
- ["/cart/x", "notFound", "404.html"],
28
- ["/blog/x", "error", "500.html"],
29
- ];
30
- for (const [path, kind, want, slug] of cases) {
31
- const m = lookupSegmentPage(entries, kind, path, false, "");
32
- expect(m && m.file, `${kind} ${path}`).toBe(want);
33
- if (slug)
34
- expect(m.params.slug).toBe(slug);
35
- }
36
- expect(lookupSegmentPage([], "notFound", "/x", false, "")).toBeNull();
37
- expect(lookupSegmentPage([{ key: "blog", dir: "blog", notFound: "blog/404.html" }], "notFound", "/x", false, "")).toBeNull();
38
- });
39
- it("finds forbidden and unauthorized pages like not-found pages", () => {
40
- const entries = [
41
- { key: "", dir: "", forbidden: "403.html" },
42
- { key: "admin", dir: "admin", forbidden: "admin/403.html", unauthorized: "admin/401.html" },
43
- ];
44
- expect(lookupSegmentPage(entries, "forbidden", "/x", true, "admin/users")?.file).toBe("admin/403.html");
45
- expect(lookupSegmentPage(entries, "forbidden", "/x", true, "blog")?.file).toBe("403.html");
46
- expect(lookupSegmentPage(entries, "unauthorized", "/x", true, "admin")?.file).toBe("admin/401.html");
47
- expect(lookupSegmentPage(entries, "unauthorized", "/x", true, "blog")).toBeNull();
48
- expect(lookupSegmentPage(entries, "forbidden", "/admin/zzz", false, "")?.file).toBe("admin/403.html");
49
- expect(SEGMENT_KIND_OF_STATUS[401]).toBe("unauthorized");
50
- expect(SEGMENT_KIND_OF_STATUS[403]).toBe("forbidden");
51
- });
52
- it("route walk", () => {
53
- const entries = [
54
- { key: "", dir: "", notFound: "404.html" },
55
- { key: "(shop)", dir: "", group: true, notFound: "(shop)/404.html", error: "(shop)/500.html" },
56
- { key: "(shop)/cart", dir: "cart", group: true, notFound: "(shop)/cart/404.html" },
57
- { key: "blog", dir: "blog", error: "blog/500.html" },
58
- ];
59
- const cases = [
60
- ["", "notFound", "404.html"],
61
- ["(shop)", "notFound", "(shop)/404.html"],
62
- ["(shop)/cart", "notFound", "(shop)/cart/404.html"],
63
- ["(shop)/cart/[id]", "notFound", "(shop)/cart/404.html"],
64
- ["(shop)/cart", "error", "(shop)/500.html"],
65
- ["blog", "notFound", "404.html"],
66
- ["blog/[slug]", "error", "blog/500.html"],
67
- ["other", "error", ""],
68
- ];
69
- for (const [segDir, kind, want] of cases) {
70
- const m = lookupSegmentPage(entries, kind, "/ignored", true, segDir);
71
- expect(m ? m.file : "", `${kind} ${segDir}`).toBe(want);
72
- }
10
+ expect(lookupSegmentPage(entries, "notFound", "/x", false, "")).toEqual({ file: "404.html", key: "", params: {}, route: "/__404" });
11
+ expect(lookupSegmentPage(entries, "error", "/x", false, "")?.route).toBeUndefined();
12
+ expect(lookupSegmentPage(entries, "notFound", "/blog/x", true, "blog")?.route).toBeUndefined();
13
+ expect(segmentRoute("shop/blog", "unauthorized")).toBe("/shop/blog/__401");
73
14
  });
74
15
  });
75
16
  describe("error prop", () => {
@@ -82,136 +23,3 @@ describe("error prop", () => {
82
23
  expect(out).toContain('<script type="application/json" id="__krate_error">{"name":"Error","message":"a\\u003cb\\u003e","digest":"d","stack":"at y"}</script></head>');
83
24
  });
84
25
  });
85
- const config = {
86
- basePath: "",
87
- trustProxy: true,
88
- maxBodyBytes: 1 << 20,
89
- maxAPIBodyBytes: 1 << 20,
90
- redirects: [],
91
- rewrites: [],
92
- headers: [],
93
- security: { nosniff: true, frameOptions: "", referrerPolicy: "", permissionsPolicy: "", hsts: "", csp: "" },
94
- cors: { enabled: false, origins: [], methods: [], headers: [], credentials: false, maxAge: 0 },
95
- ssr: { timeout: 2000, maxCacheSize: 16, ppr: false, pprRevalidate: 60 },
96
- };
97
- const shell = (id) => `<html><head><title>t</title></head><body><!--suspense:page-->baked ${id}<!--/suspense:page--></body></html>`;
98
- function segData() {
99
- return {
100
- version: 1,
101
- config,
102
- pages: [
103
- { route: "/blog/boom", mode: "ssr", bundlePath: "boom", segDir: "blog" },
104
- { route: "/blog/gone", mode: "ssr", bundlePath: "gone", segDir: "blog" },
105
- { route: "/blog/[slug]", mode: "isr", revalidate: 30, bundlePath: "slug", segDir: "blog" },
106
- { route: "/boom", mode: "ssr", bundlePath: "boom", segDir: "" },
107
- ],
108
- regions: {},
109
- allPages: [{ route: "/blog/[slug]", mode: "isr", segDir: "blog" }, { route: "/blog/closed/[id]", mode: "ssg", segDir: "blog" }],
110
- shells: { "/blog/boom": shell("a"), "/blog/gone": shell("b"), "/blog/[slug]": shell("c"), "/boom": shell("d") },
111
- templates: [{ pattern: "blog/closed/[id]", html: "<html><head></head><body>t</body></html>" }],
112
- staticOnlyRoutes: ["/blog/closed/[id]"],
113
- hashedAssets: [],
114
- html404: "<h1>global 404</h1>",
115
- html500: "",
116
- segments: [
117
- { key: "", dir: "", notFound: "404.html", error: "500.html" },
118
- { key: "blog", dir: "blog", notFound: "blog/404.html", error: "blog/500.html" },
119
- { key: "docs/[...rest]", dir: "docs/[...rest]", notFound: "docs/[...rest]/404.html" },
120
- ],
121
- segmentPages: {
122
- "404.html": "<html><head></head><body>root 404</body></html>",
123
- "500.html": "<html><head></head><body>root 500 __KRATE_ERR_DIGEST__</body></html>",
124
- "blog/404.html": "<html><head></head><body>blog 404</body></html>",
125
- "blog/500.html": "<html><head></head><body>blog 500 __KRATE_ERR_MESSAGE__ __KRATE_ERR_DIGEST__ __KRATE_ERR_STACK__</body></html>",
126
- "docs/[...rest]/404.html": "<html><head></head><body>docs 404 __KRATE_PARAM_rest__</body></html>",
127
- },
128
- apiRoutes: [],
129
- actions: [],
130
- hasMiddleware: false,
131
- };
132
- }
133
- let slugRenders = 0;
134
- const mods = {
135
- pages: {
136
- boom: { default: () => { throw new Error("secret <boom>"); } },
137
- gone: { default: async () => { const { notFound } = await import("./server.js"); notFound(); return jsx("p", {}); } },
138
- slug: { default: () => jsx("main", { children: "slug " + ++slugRenders }) },
139
- },
140
- };
141
- describe("segment pages in the handler", () => {
142
- const handler = createKrateHandler({ target: "node", data: segData(), modules: mods });
143
- const get = (p) => handler(new Request("http://localhost" + p, { headers: { accept: "text/html" } }));
144
- const errors = console.error;
145
- const quiet = () => { console.error = () => { }; };
146
- const loud = () => { console.error = errors; };
147
- it("unmatched URLs use the nearest segment 404", async () => {
148
- const r = await get("/blog/nothing/at/all");
149
- expect(r.status).toBe(404);
150
- expect(r.headers.get("cache-control")).toBe("no-store");
151
- expect(await r.text()).toContain("blog 404");
152
- expect(await (await get("/zzz")).text()).toContain("root 404");
153
- const d = await get("/docs/a/b");
154
- expect(d.status).toBe(404);
155
- expect(await d.text()).toContain("docs 404 a/b");
156
- });
157
- it("a closed dynamic route resolves through its directory", async () => {
158
- const r = await get("/blog/closed/42/");
159
- expect(r.status).toBe(404);
160
- expect(await r.text()).toContain("blog 404");
161
- });
162
- it("notFound() answers the route's nearest page and is not cached", async () => {
163
- const r = await get("/blog/gone/");
164
- expect(r.status).toBe(404);
165
- expect(r.headers.get("cache-control")).toBe("no-store");
166
- expect(await r.text()).toContain("blog 404");
167
- });
168
- it("a failed render answers the segment error page with the digest", async () => {
169
- quiet();
170
- try {
171
- const r = await get("/blog/boom/");
172
- expect(r.status).toBe(500);
173
- expect(r.headers.get("x-krate-error")).toBe("render");
174
- expect(r.headers.get("cache-control")).toBe("no-store");
175
- const body = await r.text();
176
- expect(body).toContain("blog 500 Internal Server Error ");
177
- expect(body).not.toContain("secret");
178
- const m = /"digest":"([0-9a-f]{10})"/.exec(body);
179
- expect(m).not.toBeNull();
180
- expect(body).toContain('id="__krate_error"');
181
- const root = await (await get("/boom/")).text();
182
- expect(root).toContain("root 500 ");
183
- }
184
- finally {
185
- loud();
186
- }
187
- });
188
- it("ISR serves from cache, but never stores failed or not-found renders", async () => {
189
- const a = await get("/blog/x/");
190
- expect(a.status).toBe(200);
191
- expect(a.headers.get("x-krate-cache")).toBe("MISS");
192
- expect((await get("/blog/x/")).headers.get("x-krate-cache")).toBe("HIT");
193
- expect(slugRenders).toBe(1);
194
- });
195
- it("an ISR page that throws is rendered again, not cached", async () => {
196
- quiet();
197
- try {
198
- let n = 0;
199
- const d = segData();
200
- const h = createKrateHandler({
201
- target: "node",
202
- data: d,
203
- modules: { pages: { ...mods.pages, slug: { default: () => { n++; throw new Error("x"); } } } },
204
- });
205
- for (let i = 0; i < 2; i++) {
206
- const r = await h(new Request("http://localhost/blog/y/"));
207
- expect(r.status).toBe(500);
208
- expect(r.headers.get("cache-control")).toBe("no-store");
209
- expect(await r.text()).toContain("blog 500");
210
- }
211
- expect(n).toBe(2);
212
- }
213
- finally {
214
- loud();
215
- }
216
- });
217
- });
@@ -47,5 +47,14 @@ export declare function parseHeadTags(fragment: string): HeadTag[];
47
47
  export declare function mergeHeadSection(head: string, title: string, fragment: string): string;
48
48
  /** Index where the head section of a document ends (</head>, else <body), or -1. */
49
49
  export declare function headEndOf(doc: string): number;
50
+ export type DocAttrs = Map<string, string>;
51
+ /** Removes the <html> and <body> elements from a head fragment and returns their attributes. */
52
+ export declare function splitDocTags(fragment: string): {
53
+ rest: string;
54
+ html: DocAttrs;
55
+ body: DocAttrs;
56
+ };
57
+ /** Sets attrs on the first start tag of `name` in doc, keeping the attributes it already has. */
58
+ export declare function setStartTagAttrs(doc: string, name: string, attrs: DocAttrs): string;
50
59
  /** Merges the title and head tags into the head of a whole document. */
51
60
  export declare function mergeHead(doc: string, title: string, fragment: string): string;
package/dist/head-tags.js CHANGED
@@ -318,6 +318,87 @@ export function headEndOf(doc) {
318
318
  return h;
319
319
  return lower.indexOf("<body");
320
320
  }
321
+ const ATTR_NAME = /^[A-Za-z_:][-A-Za-z0-9_:.]*$/;
322
+ function decodeAttr(v) {
323
+ return v.replace(/&(quot|amp|lt|gt|apos|#34|#39);/g, (_m, e) => {
324
+ switch (e) {
325
+ case "quot":
326
+ case "#34":
327
+ return '"';
328
+ case "lt":
329
+ return "<";
330
+ case "gt":
331
+ return ">";
332
+ case "apos":
333
+ case "#39":
334
+ return "'";
335
+ default:
336
+ return "&";
337
+ }
338
+ });
339
+ }
340
+ /** Removes the <html> and <body> elements from a head fragment and returns their attributes. */
341
+ export function splitDocTags(fragment) {
342
+ const html = new Map();
343
+ const body = new Map();
344
+ if (!/<(html|body)[\s>\/]/i.test(fragment))
345
+ return { rest: fragment, html, body };
346
+ let rest = "";
347
+ let at = 0;
348
+ for (const el of scanHeadElements(fragment)) {
349
+ if (el.name !== "html" && el.name !== "body")
350
+ continue;
351
+ const target = el.name === "html" ? html : body;
352
+ for (const [k, v] of el.attrs)
353
+ if (ATTR_NAME.test(k))
354
+ target.set(k, decodeAttr(v));
355
+ rest += fragment.slice(at, el.start);
356
+ at = el.end;
357
+ }
358
+ rest += fragment.slice(at);
359
+ return { rest: rest.replace(/<\/(html|body)\s*>/gi, ""), html, body };
360
+ }
361
+ function renderAttrs(attrs) {
362
+ return [...attrs.entries()]
363
+ .filter(([k]) => ATTR_NAME.test(k))
364
+ .sort((x, y) => (x[0] < y[0] ? -1 : x[0] > y[0] ? 1 : 0))
365
+ .map(([k, v]) => (v === "" ? " " + k : " " + k + '="' + escapeAttr(v) + '"'))
366
+ .join("");
367
+ }
368
+ function escapeAttr(v) {
369
+ return v.replace(/[&<>"']/g, (c) => (c === '"' ? "&quot;" : c === "&" ? "&amp;" : c === "<" ? "&lt;" : c === ">" ? "&gt;" : "&#39;"));
370
+ }
371
+ /** Sets attrs on the first start tag of `name` in doc, keeping the attributes it already has. */
372
+ export function setStartTagAttrs(doc, name, attrs) {
373
+ if (attrs.size === 0)
374
+ return doc;
375
+ const re = new RegExp("<" + name + "(?=[\\s>/])", "i");
376
+ const m = re.exec(doc);
377
+ if (!m)
378
+ return doc;
379
+ let end = m.index + 1;
380
+ let quote = "";
381
+ for (; end < doc.length; end++) {
382
+ const c = doc[end];
383
+ if (quote) {
384
+ if (c === quote)
385
+ quote = "";
386
+ }
387
+ else if (c === '"' || c === "'")
388
+ quote = c;
389
+ else if (c === ">") {
390
+ end++;
391
+ break;
392
+ }
393
+ }
394
+ const merged = new Map();
395
+ for (const [k, v] of scanHeadElements(doc.slice(m.index, end))[0]?.attrs ?? [])
396
+ if (ATTR_NAME.test(k))
397
+ merged.set(k, decodeAttr(v));
398
+ for (const [k, v] of attrs)
399
+ merged.set(k, v);
400
+ return doc.slice(0, m.index) + "<" + name + renderAttrs(merged) + ">" + doc.slice(end);
401
+ }
321
402
  /** Merges the title and head tags into the head of a whole document. */
322
403
  export function mergeHead(doc, title, fragment) {
323
404
  if (title === "" && fragment === "")
@@ -325,5 +406,8 @@ export function mergeHead(doc, title, fragment) {
325
406
  const end = headEndOf(doc);
326
407
  if (end === -1)
327
408
  return doc;
328
- return mergeHeadSection(doc.slice(0, end), title, fragment) + doc.slice(end);
409
+ const { rest, html, body } = splitDocTags(fragment);
410
+ let out = mergeHeadSection(doc.slice(0, end), title, rest) + doc.slice(end);
411
+ out = setStartTagAttrs(out, "html", html);
412
+ return setStartTagAttrs(out, "body", body);
329
413
  }