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

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 +1832 -0
  104. package/dist/server-handler.test.d.ts +1 -0
  105. package/dist/server-handler.test.js +535 -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,43 @@
1
+ export type SegmentKind = "notFound" | "error" | "forbidden" | "unauthorized";
2
+ /** The segment page role that answers each status. */
3
+ export declare const SEGMENT_KIND_OF_STATUS: Record<401 | 403 | 404 | 500, SegmentKind>;
4
+ /** One directory's segment pages (manifest.json segments[]). */
5
+ export interface SegmentEntry {
6
+ key: string;
7
+ dir: string;
8
+ group?: boolean;
9
+ notFound?: string;
10
+ error?: string;
11
+ forbidden?: string;
12
+ unauthorized?: string;
13
+ }
14
+ export interface SegmentMatch {
15
+ /** Page path relative to the output dir ("blog/404.html"). */
16
+ file: string;
17
+ key: string;
18
+ /** Dynamic-segment values when matched against a URL, else undefined. */
19
+ params?: Record<string, string>;
20
+ }
21
+ /**
22
+ * Returns the nearest segment page of a kind. matched: the request matched a
23
+ * route whose source directory is segDir, so the lookup walks up from it.
24
+ * Otherwise the longest URL-prefix entry outside route groups wins (static >
25
+ * [param] > catch-all).
26
+ */
27
+ export declare function lookupSegmentPage(entries: SegmentEntry[], kind: SegmentKind, urlPath: string, matched: boolean, segDir: string): SegmentMatch | null;
28
+ export interface ServerError {
29
+ name: string;
30
+ message: string;
31
+ digest: string;
32
+ stack?: string;
33
+ }
34
+ /** The error prop for a failed request: sanitized outside dev, digest always kept. */
35
+ export declare function newServerError(message: string, stack: string, digest: string, dev: boolean): ServerError;
36
+ /**
37
+ * Turns a built error page into the response for one failed request: the error
38
+ * placeholders are replaced with the escaped error and the error is injected
39
+ * as a JSON data block before </head>.
40
+ */
41
+ export declare function fillServerError(page: string, e: ServerError): string;
42
+ /** A segment page filled for one response (dynamic dir params, then the error). */
43
+ export declare function renderSegmentPage(html: string, m: SegmentMatch, err?: ServerError): string;
@@ -0,0 +1,115 @@
1
+ // Per-segment not-found and error pages for the portable handler: a port of
2
+ // build/segments.go (LookupSegmentPage) and build/segmentserve.go
3
+ // (newServerError, fillServerError). Pure functions over manifest data.
4
+ import { applyDynamicRouteParams, compareRouteSpecificity, goHTMLEscape, matchRoutePattern, parseRoutePattern, trimSlashes, } from "./handler-routing.js";
5
+ /** The segment page role that answers each status. */
6
+ export const SEGMENT_KIND_OF_STATUS = {
7
+ 401: "unauthorized",
8
+ 403: "forbidden",
9
+ 404: "notFound",
10
+ 500: "error",
11
+ };
12
+ function entryPage(e, kind) {
13
+ switch (kind) {
14
+ case "error":
15
+ return e.error || "";
16
+ case "forbidden":
17
+ return e.forbidden || "";
18
+ case "unauthorized":
19
+ return e.unauthorized || "";
20
+ default:
21
+ return e.notFound || "";
22
+ }
23
+ }
24
+ /**
25
+ * Returns the nearest segment page of a kind. matched: the request matched a
26
+ * route whose source directory is segDir, so the lookup walks up from it.
27
+ * Otherwise the longest URL-prefix entry outside route groups wins (static >
28
+ * [param] > catch-all).
29
+ */
30
+ export function lookupSegmentPage(entries, kind, urlPath, matched, segDir) {
31
+ if (matched) {
32
+ const byKey = new Map();
33
+ for (const e of entries)
34
+ byKey.set(e.key, e);
35
+ let dir = segDir;
36
+ for (;;) {
37
+ const e = byKey.get(dir);
38
+ if (e && entryPage(e, kind) !== "")
39
+ return { file: entryPage(e, kind), key: e.key };
40
+ if (dir === "")
41
+ return null;
42
+ const i = dir.lastIndexOf("/");
43
+ dir = i >= 0 ? dir.slice(0, i) : "";
44
+ }
45
+ }
46
+ let best = null;
47
+ let bestParams;
48
+ for (const e of entries) {
49
+ if (entryPage(e, kind) === "" || e.group)
50
+ continue;
51
+ const params = matchRoutePrefix(urlPath, e.dir);
52
+ if (!params)
53
+ continue;
54
+ if (!best || compareRouteSpecificity(e.dir, best.dir) < 0) {
55
+ best = e;
56
+ bestParams = params;
57
+ }
58
+ }
59
+ if (!best)
60
+ return null;
61
+ return { file: entryPage(best, kind), key: best.key, params: bestParams };
62
+ }
63
+ /** Matches the leading segments of urlPath; a trailing catch-all takes the rest. */
64
+ function matchRoutePrefix(urlPath, pattern) {
65
+ const segs = parseRoutePattern(pattern);
66
+ if (segs.length === 0)
67
+ return {};
68
+ const trimmed = trimSlashes(urlPath);
69
+ const parts = trimmed === "" ? [] : trimmed.split("/");
70
+ const last = segs[segs.length - 1];
71
+ if (last.kind === 2 || last.kind === 3)
72
+ return matchRoutePattern(urlPath, pattern);
73
+ if (parts.length < segs.length)
74
+ return null;
75
+ return matchRoutePattern("/" + parts.slice(0, segs.length).join("/"), pattern);
76
+ }
77
+ /** The error prop for a failed request: sanitized outside dev, digest always kept. */
78
+ export function newServerError(message, stack, digest, dev) {
79
+ if (!dev)
80
+ return { name: "Error", message: "Internal Server Error", digest };
81
+ const e = { name: "Error", message: message || "Internal Server Error", digest };
82
+ if (stack)
83
+ e.stack = stack;
84
+ return e;
85
+ }
86
+ function escapeJSONForScript(s) {
87
+ return s.replace(/</g, "\\u003c").replace(/>/g, "\\u003e").replace(/&/g, "\\u0026").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
88
+ }
89
+ /**
90
+ * Turns a built error page into the response for one failed request: the error
91
+ * placeholders are replaced with the escaped error and the error is injected
92
+ * as a JSON data block before </head>.
93
+ */
94
+ export function fillServerError(page, e) {
95
+ const subs = [
96
+ ["__KRATE_ERR_NAME__", e.name],
97
+ ["__KRATE_ERR_MESSAGE__", e.message],
98
+ ["__KRATE_ERR_DIGEST__", e.digest],
99
+ ["__KRATE_ERR_STACK__", e.stack || ""],
100
+ ];
101
+ for (const [sentinel, val] of subs)
102
+ page = page.split(sentinel).join(goHTMLEscape(val));
103
+ const block = '<script type="application/json" id="__krate_error">' + escapeJSONForScript(JSON.stringify(e)) + "</script>";
104
+ const at = page.indexOf("</head>");
105
+ return at >= 0 ? page.slice(0, at) + block + page.slice(at) : block + page;
106
+ }
107
+ /** A segment page filled for one response (dynamic dir params, then the error). */
108
+ export function renderSegmentPage(html, m, err) {
109
+ let page = html;
110
+ if (m.params && Object.keys(m.params).length > 0)
111
+ page = applyDynamicRouteParams(page, m.params);
112
+ if (err)
113
+ page = fillServerError(page, err);
114
+ return page;
115
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,217 @@
1
+ // @vitest-environment node
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", () => {
8
+ const entries = [
9
+ { key: "", dir: "", notFound: "404.html", error: "500.html" },
10
+ { 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
+ ];
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
+ }
73
+ });
74
+ });
75
+ describe("error prop", () => {
76
+ it("is sanitized in production and escaped into the page", () => {
77
+ const e = newServerError("secret <b>", "at x", "abc1234567", false);
78
+ expect(e).toEqual({ name: "Error", message: "Internal Server Error", digest: "abc1234567" });
79
+ const dev = newServerError("a<b>", "at y", "d", true);
80
+ const out = fillServerError("<html><head></head><body>__KRATE_ERR_MESSAGE__|__KRATE_ERR_DIGEST__|__KRATE_ERR_STACK__</body></html>", dev);
81
+ expect(out).toContain("a&lt;b&gt;|d|at y");
82
+ expect(out).toContain('<script type="application/json" id="__krate_error">{"name":"Error","message":"a\\u003cb\\u003e","digest":"d","stack":"at y"}</script></head>');
83
+ });
84
+ });
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
+ });
@@ -0,0 +1,51 @@
1
+ export declare const HEAD_OPEN = "<!--krate-head-->";
2
+ export declare const HEAD_CLOSE = "<!--/krate-head-->";
3
+ export interface HeadSplit {
4
+ /** Text of the last <title> in the rendered page (already HTML-escaped). */
5
+ title: string;
6
+ /** Head tags (meta, link, script, ...) lifted out of every <Head>. */
7
+ head: string;
8
+ /** The rendered html without <Head> blocks and titles. */
9
+ html: string;
10
+ }
11
+ /**
12
+ * Splits the document head content out of rendered page html: the <title>
13
+ * (the last one that is not inside an <svg>, as with static <Head> hoisting
14
+ * where a nested Head overrides its parent) and everything inside <Head>
15
+ * markers. Both are removed from the returned html.
16
+ */
17
+ export declare function takeHead(html: string): HeadSplit;
18
+ export interface HeadElement {
19
+ name: string;
20
+ /** Start and end offsets in the scanned text. */
21
+ start: number;
22
+ end: number;
23
+ attrs: Map<string, string>;
24
+ /** Text of a script/style/noscript element. */
25
+ inner: string;
26
+ }
27
+ /**
28
+ * Scans the elements of head markup: tag, attributes (quoted, unquoted and
29
+ * valueless, as the HTML tokenizer reads them) and the raw text of script,
30
+ * style and noscript. Comments and text between elements are skipped.
31
+ */
32
+ export declare function scanHeadElements(s: string): HeadElement[];
33
+ /** The dedupe key of an element ("" when it never replaces another). */
34
+ export declare function headKey(el: HeadElement): string;
35
+ export interface HeadTag {
36
+ html: string;
37
+ key: string;
38
+ el: HeadElement;
39
+ }
40
+ /** The head tags of a <Head> fragment: only head content, last single key wins. */
41
+ export declare function parseHeadTags(fragment: string): HeadTag[];
42
+ /**
43
+ * Merges page head content into the head section of a document: `head` is the
44
+ * text from the start of the document up to (not including) </head>. Returns
45
+ * the new head section.
46
+ */
47
+ export declare function mergeHeadSection(head: string, title: string, fragment: string): string;
48
+ /** Index where the head section of a document ends (</head>, else <body), or -1. */
49
+ export declare function headEndOf(doc: string): number;
50
+ /** Merges the title and head tags into the head of a whole document. */
51
+ export declare function mergeHead(doc: string, title: string, fragment: string): string;