@krate/runtime 0.5.0-rc.6 → 0.5.0-rc.8

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.
@@ -1,5 +1,6 @@
1
1
  import { type IsrStore, type RegionMeta } from "./ssr-core.js";
2
2
  import { isDynamicPattern } from "./handler-routing.js";
3
+ import { type RouteCondition } from "./route-source.js";
3
4
  import { type SegmentEntry } from "./handler-segments.js";
4
5
  import { type CacheAdapter, type CacheSpec } from "./cache-adapter.js";
5
6
  export type DeployTarget = "node" | "vercel" | "netlify" | "cloudflare";
@@ -24,15 +25,25 @@ export interface HandlerConfig {
24
25
  source: string;
25
26
  destination: string;
26
27
  permanent?: boolean;
28
+ statusCode?: number;
29
+ has?: RouteCondition[];
30
+ missing?: RouteCondition[];
27
31
  basePath?: boolean;
28
32
  }>;
29
33
  rewrites: Array<{
30
34
  source: string;
31
35
  destination: string;
36
+ has?: RouteCondition[];
37
+ missing?: RouteCondition[];
32
38
  }>;
33
39
  headers: Array<{
34
40
  source: string;
35
- headers: Record<string, string>;
41
+ headers: Record<string, string> | Array<{
42
+ key: string;
43
+ value: string;
44
+ }>;
45
+ has?: RouteCondition[];
46
+ missing?: RouteCondition[];
36
47
  }>;
37
48
  /** Resolved security headers; an empty string means "do not send". */
38
49
  security: {
@@ -204,6 +215,14 @@ export type KrateHandler = (request: Request, ctx?: HandlerContext) => Promise<R
204
215
  * Cloudflare Worker wraps the exports of src/cloudflare.ts with it.
205
216
  */
206
217
  export declare function runWithPlatform<R>(target: DeployTarget, ctx: HandlerContext, fn: () => R): R;
218
+ /**
219
+ * The name/value pairs of a headers rule: an object, or Next's array of
220
+ * { key, value } where a repeated name (any case) keeps its last value.
221
+ */
222
+ export declare function ruleHeaderPairs(h: Record<string, string> | Array<{
223
+ key: string;
224
+ value: string;
225
+ }>): Array<[string, string]>;
207
226
  /**
208
227
  * Opens the closure token of an inline server action: AES-256-GCM over the
209
228
  * JSON of the captured values, authenticated against the action id, with the
@@ -16,7 +16,9 @@ import { platformWaitUntil } from "./platform.js";
16
16
  import { cacheRuntime, installRenderStore, patchFetch } from "./cache-scope.js";
17
17
  import { allSuspense, canStreamOutOfOrder, FLASH_COOKIE, flashPayloadOf, injectFlashNotice, parseRegionShell, regionReplaceScript, requestFlash, signFlash, spliceShell, splitBodyScripts, } from "./handler-html.js";
18
18
  import { mergeHead } from "./head-tags.js";
19
- import { applyDynamicRouteParams, baseName, cleanPath, compareRouteSpecificity, compileMatcher, extName, goRedirect, headerSourceMatches, isDynamicPattern, isFileLikePath, isHTMLDocRequest, isInternalOutputPath, matchRedirect, matchRoutePattern, normalizeRoutePattern, requestRoute, rewriteDestination, rewriteTargetPath, staticCacheControl, } from "./handler-routing.js";
19
+ import { applyDynamicRouteParams, baseName, cleanPath, compareRouteSpecificity, compileMatcher, extName, goRedirect, IMMUTABLE_CACHE_CONTROL, isDynamicPattern, isFileLikePath, isHTMLDocRequest, isInternalOutputPath, matchRoutePattern, normalizeRoutePattern, requestRoute, rewriteTargetPath, staticCacheControl, } from "./handler-routing.js";
20
+ import { attachCookies } from "./request-extras.js";
21
+ import { buildDestination, compileMatcher as compileRuleMatcher, mergeRequestQuery } from "./route-source.js";
20
22
  import { lookupSegmentPage, newServerError, renderSegmentPage, SEGMENT_KIND_OF_STATUS, } from "./handler-segments.js";
21
23
  import { httpFallbackStatus } from "./request-context.js";
22
24
  import { sha256Hex as portableSha256Hex } from "./sha256.js";
@@ -86,6 +88,22 @@ function safeDecode(p) {
86
88
  return p;
87
89
  }
88
90
  }
91
+ /**
92
+ * The name/value pairs of a headers rule: an object, or Next's array of
93
+ * { key, value } where a repeated name (any case) keeps its last value.
94
+ */
95
+ export function ruleHeaderPairs(h) {
96
+ if (!Array.isArray(h))
97
+ return Object.entries(h);
98
+ const out = [];
99
+ for (const { key, value } of h) {
100
+ const at = out.findIndex(([k]) => k.toLowerCase() === String(key).toLowerCase());
101
+ if (at >= 0)
102
+ out.splice(at, 1);
103
+ out.push([String(key), String(value)]);
104
+ }
105
+ return out;
106
+ }
89
107
  function textResponse(rs, status, body, contentType = "text/plain; charset=utf-8") {
90
108
  rs.res.set("Content-Type", contentType);
91
109
  return finish(rs, status, body);
@@ -143,54 +161,6 @@ function isHTTPSRequest(headers) {
143
161
  function isStaticAssetPath(p) {
144
162
  return STATIC_ASSET_EXTS.has(extName(p).toLowerCase());
145
163
  }
146
- function requestCookiesOf(headers) {
147
- const jar = new Map();
148
- for (const part of String(headers.get("cookie") || "").split(";")) {
149
- const i = part.indexOf("=");
150
- if (i <= 0)
151
- continue;
152
- const name = part.slice(0, i).trim();
153
- if (!name || jar.has(name))
154
- continue;
155
- // Same parsing as the action context and the Node sidecar: unquote, then percent-decode.
156
- let value = part.slice(i + 1).trim();
157
- if (value.startsWith('"') && value.endsWith('"'))
158
- value = value.slice(1, -1);
159
- try {
160
- value = decodeURIComponent(value);
161
- }
162
- catch {
163
- // keep the raw value
164
- }
165
- jar.set(name, value);
166
- }
167
- return jar;
168
- }
169
- function attachCookies(request, basePath = "") {
170
- try {
171
- const jar = requestCookiesOf(request.headers);
172
- Object.defineProperty(request, "cookies", {
173
- value: {
174
- get: (n) => (jar.has(String(n)) ? { name: String(n), value: jar.get(String(n)) } : undefined),
175
- getAll: (n) => [...jar].filter(([k]) => n === undefined || k === String(n)).map(([name, value]) => ({ name, value })),
176
- has: (n) => jar.has(String(n)),
177
- },
178
- enumerable: false,
179
- });
180
- Object.defineProperty(request, "nextUrl", { value: makeNextUrl(request.url, basePath), enumerable: false });
181
- }
182
- catch {
183
- // frozen request objects keep working without the cookies accessor
184
- }
185
- return request;
186
- }
187
- /** A URL carrying Next's NextURL extras: basePath (pathname never includes it) and clone(). */
188
- function makeNextUrl(href, basePath) {
189
- const u = new URL(href);
190
- Object.defineProperty(u, "basePath", { value: basePath, enumerable: false });
191
- Object.defineProperty(u, "clone", { value: () => makeNextUrl(u.href, basePath), enumerable: false });
192
- return u;
193
- }
194
164
  const sleepMicrotask = () => Promise.resolve();
195
165
  const PLATFORMS = {
196
166
  node: { forwardedHostProto: false, clientIP: [] },
@@ -675,19 +645,22 @@ export function createKrateHandler(options) {
675
645
  return custom404(rs, page);
676
646
  return notFoundText(rs, true);
677
647
  }
678
- /** trailingSlash "never": a page URL ending in a slash redirects to the slashless URL. */
679
- function redirectToSlashless(rs, requested = rs.path) {
680
- const p = requested;
681
- if (slashMode !== "never" || p.length < 2 || !p.endsWith("/") || notFoundPageURL(p))
682
- return null;
683
- if (rs.method !== "GET" && rs.method !== "HEAD")
648
+ /**
649
+ * trailingSlash "never": a path ending in "/" (pages, files, API routes, any
650
+ * method) gets a 308 to the slashless path before config redirects and
651
+ * middleware, as in Next (mirrors slashlessTarget in serve_pages.go). The
652
+ * not-found page's URLs and internal routes are left alone.
653
+ */
654
+ function redirectToSlashless(rs) {
655
+ const p = rs.path;
656
+ if (slashMode !== "never" || p.length < 2 || !p.endsWith("/") || p.startsWith("/__krate") || p === "/healthz" || p === "/readyz" || notFoundPageURL(p))
684
657
  return null;
685
- const trimmed = p.replace(/\/+$/, "");
686
- if (trimmed === "" || isFileLikePath(trimmed) || trimmed === "/api" || trimmed.startsWith("/api/") || trimmed.startsWith("/__krate"))
658
+ // "//evil.example/" must not become a scheme-relative Location.
659
+ const target = "/" + rs.rawPath.replace(/\/+$/, "").replace(/^[\/\\]+/, "");
660
+ if (target === "/")
687
661
  return null;
688
- // "../" keeps a segment such as "ftp:3232235777" from parsing as an absolute URL.
689
- rs.res.set("Location", "../" + baseName(trimmed) + (rs.search || ""));
690
- return finish(rs, 301, null);
662
+ rs.res.set("Location", target + (rs.search || ""));
663
+ return finish(rs, 308, null);
691
664
  }
692
665
  function redirectToCanonicalSlash(rs) {
693
666
  if (slashMode !== "always")
@@ -737,7 +710,9 @@ export function createKrateHandler(options) {
737
710
  return answerNotFoundPageURL(rs);
738
711
  if (p.endsWith(".map"))
739
712
  rs.res.set("Content-Type", "application/json; charset=utf-8");
740
- rs.res.set("Cache-Control", staticCacheControl(p, hashed));
713
+ // A Cache-Control from a headers rule wins (public/ files cached longer).
714
+ if (!rs.res.has("Cache-Control"))
715
+ rs.res.set("Cache-Control", staticCacheControl(p, hashed));
741
716
  let closedPattern = "";
742
717
  if (!(await staticRouteExists(p))) {
743
718
  for (const t of templates) {
@@ -1094,16 +1069,36 @@ export function createKrateHandler(options) {
1094
1069
  return new Response(null, { status: 200, headers: rs.res });
1095
1070
  return new Response(body, { status: 200, headers: rs.res });
1096
1071
  }
1097
- // Redirects and rewrites
1098
- // Under a base path, basePath: false rules match the full path before the
1099
- // base is stripped (see handle) and stay out of this list.
1100
- const insideRedirects = basePath ? cfg.redirects.filter((rd) => rd.basePath !== false) : cfg.redirects;
1101
- const outsideRedirects = basePath ? cfg.redirects.filter((rd) => rd.basePath === false) : [];
1072
+ function compileRules(rules, kind) {
1073
+ const out = [];
1074
+ for (const rule of rules) {
1075
+ try {
1076
+ out.push({ rule, matcher: compileRuleMatcher(rule.source, kind, rule.has, rule.missing) });
1077
+ }
1078
+ catch (err) {
1079
+ console.error(`[krate] skipped ${kind} rule ${JSON.stringify(rule.source)}: ${err.message}`);
1080
+ }
1081
+ }
1082
+ return out;
1083
+ }
1084
+ const insideRedirects = compileRules(basePath ? cfg.redirects.filter((rd) => rd.basePath !== false) : cfg.redirects, "redirect");
1085
+ const outsideRedirects = compileRules(basePath ? cfg.redirects.filter((rd) => rd.basePath === false) : [], "redirect");
1086
+ const rewriteRules = compileRules(cfg.rewrites, "rewrite");
1087
+ const headerRules = compileRules(cfg.headers, "header");
1088
+ function condRequest(rs) {
1089
+ return { headers: rs.headers, url: new URL(rs.request.url) };
1090
+ }
1091
+ /** Answers the first redirect whose source and conditions match; the request query is carried over. */
1102
1092
  function configRedirect(rs, p, rules) {
1103
- for (const rd of rules) {
1104
- if (matchRedirect(p, rd.source)) {
1105
- const dest = rewriteDestination(p, rd.source, rd.destination);
1106
- return goRedirect(dest, p, rs.method, rd.permanent ? 301 : 302, rs.res);
1093
+ if (!rules.length)
1094
+ return null;
1095
+ const creq = condRequest(rs);
1096
+ for (const { rule, matcher } of rules) {
1097
+ const m = matcher.match(p, creq);
1098
+ if (m) {
1099
+ const dest = mergeRequestQuery(buildDestination(rule.destination, m), rs.search);
1100
+ const status = rule.statusCode || (rule.permanent ? 301 : 302);
1101
+ return goRedirect(dest, p, rs.method, status, rs.res);
1107
1102
  }
1108
1103
  }
1109
1104
  return null;
@@ -1119,16 +1114,30 @@ export function createKrateHandler(options) {
1119
1114
  }
1120
1115
  async function redirectRewriteHandler(rs) {
1121
1116
  const p = rs.path;
1122
- const redirected = configRedirect(rs, p, insideRedirects);
1123
- if (redirected)
1124
- return redirected;
1125
- for (const rw of cfg.rewrites) {
1126
- if (matchRedirect(p, rw.source)) {
1127
- const rewritten = rewriteDestination(p, rw.source, rw.destination);
1117
+ if (rewriteRules.length) {
1118
+ const creq = condRequest(rs);
1119
+ for (const { rule, matcher } of rewriteRules) {
1120
+ const m = matcher.match(p, creq);
1121
+ if (!m)
1122
+ continue;
1123
+ let rewritten = buildDestination(rule.destination, m);
1124
+ let rewrittenQuery = "";
1125
+ const q = rewritten.indexOf("?");
1126
+ if (q >= 0) {
1127
+ rewrittenQuery = rewritten.slice(q);
1128
+ rewritten = rewritten.slice(0, q);
1129
+ }
1128
1130
  rs.path = rewriteTargetPath(safeDecode(rewritten));
1131
+ if (rewrittenQuery) {
1132
+ const merged = mergeRequestQuery(rewrittenQuery, rs.search);
1133
+ rs.search = merged === "?" ? "" : merged;
1134
+ }
1129
1135
  break;
1130
1136
  }
1131
1137
  }
1138
+ // A rewrite onto an API route is answered by the API handler (mux sent this request down the page chain).
1139
+ if (rs.path === "/api" || rs.path.startsWith("/api/"))
1140
+ return apiHandler(rs);
1132
1141
  return pageHandler(rs);
1133
1142
  }
1134
1143
  // API routes
@@ -1155,12 +1164,15 @@ export function createKrateHandler(options) {
1155
1164
  continue;
1156
1165
  const rest = k.slice(prefix.length);
1157
1166
  const i = rest.indexOf("/");
1167
+ // A name can be both a route file and a directory ([id].ts next to [id]/download.ts).
1158
1168
  if (i < 0)
1159
- out.set(rest, out.get(rest) || false);
1169
+ out.set(rest + "\0f", false);
1160
1170
  else
1161
- out.set(rest.slice(0, i), true);
1171
+ out.set(rest.slice(0, i) + "\0d", true);
1162
1172
  }
1163
- return [...out].sort((a, b) => strCmp(a[0], b[0])).map(([name, isDir]) => ({ name, isDir }));
1173
+ return [...out.keys()]
1174
+ .sort(strCmp)
1175
+ .map((k) => ({ name: k.slice(0, -2), isDir: out.get(k) }));
1164
1176
  }
1165
1177
  function strCmp(a, b) {
1166
1178
  return a < b ? -1 : a > b ? 1 : 0;
@@ -1173,6 +1185,9 @@ export function createKrateHandler(options) {
1173
1185
  const idx = join(dir, "index");
1174
1186
  return apiKeys.has(idx) ? idx : "";
1175
1187
  }
1188
+ // A static leaf wins over dynamic siblings at every depth.
1189
+ if (segs.length === 1 && apiKeys.has(join(dir, segs[0])))
1190
+ return join(dir, segs[0]);
1176
1191
  const next = join(dir, segs[0]);
1177
1192
  if (apiDirs.has(next)) {
1178
1193
  const hit = resolveDynamicAPIDir(next, segs.slice(1));
@@ -2031,19 +2046,24 @@ export function createKrateHandler(options) {
2031
2046
  }
2032
2047
  async function pageChain(rs) {
2033
2048
  return flashNotice(rs, async (rs2) => {
2034
- const requested = rs2.path;
2035
2049
  const blocked = await runMiddleware(rs2);
2036
2050
  if (blocked)
2037
2051
  return blocked;
2038
- // Checked on the requested URL, before a rewrite changes the internal path.
2039
- const slashless = redirectToSlashless(rs2, requested);
2040
- if (slashless)
2041
- return slashless;
2042
2052
  return redirectRewriteHandler(rs2);
2043
2053
  });
2044
2054
  }
2045
2055
  async function mux(rs) {
2046
2056
  const p = rs.path;
2057
+ // trailingSlash "never", then config redirects, answer first: before
2058
+ // middleware, and for /api too.
2059
+ const slashless = redirectToSlashless(rs);
2060
+ if (slashless)
2061
+ return slashless;
2062
+ if (!(p.startsWith("/__krate/") || p === "/healthz" || p === "/readyz")) {
2063
+ const redirected = configRedirect(rs, p, insideRedirects);
2064
+ if (redirected)
2065
+ return redirected;
2066
+ }
2047
2067
  // net/http.ServeMux cleans the escaped path and redirects when it changed.
2048
2068
  const raw = rs.rawPath;
2049
2069
  const cleaned = cleanPath(raw) + (raw.endsWith("/") && raw !== "/" ? "/" : "");
@@ -2099,11 +2119,36 @@ export function createKrateHandler(options) {
2099
2119
  h.set("Strict-Transport-Security", sec.hsts);
2100
2120
  if (sec.csp)
2101
2121
  h.set("Content-Security-Policy", sec.csp);
2102
- for (const rule of cfg.headers) {
2103
- if (headerSourceMatches(rule.source, rs.path))
2104
- for (const [k, v] of Object.entries(rule.headers))
2105
- h.set(k, v);
2122
+ }
2123
+ /**
2124
+ * Applies the matching headers rules to the finished response, so they win
2125
+ * over a header a handler set (a file's Cache-Control) except the immutable
2126
+ * Cache-Control of a content-hashed asset.
2127
+ */
2128
+ function withHeaderRules(rs, path, res) {
2129
+ if (!headerRules.length)
2130
+ return res;
2131
+ const creq = condRequest(rs);
2132
+ let headers = null;
2133
+ for (const { rule, matcher } of headerRules) {
2134
+ if (!matcher.match(path, creq))
2135
+ continue;
2136
+ headers ?? (headers = new Headers(res.headers));
2137
+ const keepCache = headers.get("cache-control") === IMMUTABLE_CACHE_CONTROL;
2138
+ for (const [k, v] of ruleHeaderPairs(rule.headers)) {
2139
+ if (keepCache && k.toLowerCase() === "cache-control")
2140
+ continue;
2141
+ if (k.toLowerCase() === "vary") {
2142
+ if (!(headers.get("vary") || "").toLowerCase().includes(v.toLowerCase()))
2143
+ headers.append("Vary", v);
2144
+ }
2145
+ else
2146
+ headers.set(k, v);
2147
+ }
2106
2148
  }
2149
+ if (!headers)
2150
+ return res;
2151
+ return new Response(res.body, { status: res.status, statusText: res.statusText, headers });
2107
2152
  }
2108
2153
  /** corsMiddleware; returns a Response for a preflight. */
2109
2154
  function applyCORS(rs) {
@@ -2158,6 +2203,8 @@ export function createKrateHandler(options) {
2158
2203
  origin: requestOrigin(request, url),
2159
2204
  ctx,
2160
2205
  };
2206
+ let headerPath = rs.path;
2207
+ const finalize = (res) => withHeaderRules(rs, headerPath, res);
2161
2208
  try {
2162
2209
  // Mount under the base path: requests outside it redirect (GET/HEAD) or 404.
2163
2210
  // The app then sees base-less paths, so a root-relative Location it
@@ -2187,20 +2234,21 @@ export function createKrateHandler(options) {
2187
2234
  }
2188
2235
  }
2189
2236
  applySecurityAndHeaders(rs);
2237
+ headerPath = rs.path;
2190
2238
  const preflight = applyCORS(rs);
2191
2239
  if (preflight)
2192
- return mounted ? withBaseLocation(preflight) : preflight;
2240
+ return finalize(mounted ? withBaseLocation(preflight) : preflight);
2193
2241
  await sleepMicrotask();
2194
2242
  const res = await mux(rs);
2195
- return mounted ? withBaseLocation(res) : res;
2243
+ return finalize(mounted ? withBaseLocation(res) : res);
2196
2244
  }
2197
2245
  catch (err) {
2198
2246
  console.error(`[krate] panic recovered: ${rs.method} ${rs.path}: ${(err && err.stack) || err}`);
2199
2247
  if (rs.path.startsWith("/api/")) {
2200
2248
  rs.res.set("Content-Type", "application/json");
2201
- return finish(rs, 500, '{"error":"Internal Server Error"}');
2249
+ return finalize(finish(rs, 500, '{"error":"Internal Server Error"}'));
2202
2250
  }
2203
- return httpError(rs, "Internal Server Error", 500);
2251
+ return finalize(httpError(rs, "Internal Server Error", 500));
2204
2252
  }
2205
2253
  }
2206
2254
  }
package/dist/server.d.ts CHANGED
@@ -102,13 +102,18 @@ type SlotValues = {
102
102
  k: string;
103
103
  v: unknown;
104
104
  }[];
105
+ export declare const ISLAND_OPEN = "krate-island:";
106
+ export declare const ISLAND_CLOSE = "<!--/krate-island-->";
105
107
  /**
106
108
  * clientBoundary wraps an export of a `"use client"` module, or a component
107
109
  * of a React package, for the server bundle of a page that renders server
108
110
  * components. The server renders the component's initial HTML (render) and,
109
- * when it hydrates, puts it in a <krate-island> marker preceded by a JSON
110
- * script with its serialized props; the per-module client chunk at src
111
- * hydrates it in the browser. A component without state or effects (hydrate
111
+ * when it hydrates, puts it between <!--krate-island:{...}--> (module,
112
+ * export, chunk and serialized props) and <!--/krate-island--> with no
113
+ * element around it; the per-module client chunk at src hydrates those nodes
114
+ * in the browser. A real-React island (flight) gets a <krate-island> element
115
+ * instead, preceded by a JSON script with its props, because createRoot needs
116
+ * a container. A component without state or effects (hydrate
112
117
  * false, an icon) is plain HTML. Children are rendered on the server into the
113
118
  * component's HTML and adopted there by the browser (see DeferredSlot), or,
114
119
  * when they hold client components of their own, sent as a tree that keeps
@@ -124,13 +129,8 @@ export declare const HEAD_CLOSE = "<!--/krate-head-->";
124
129
  export declare function Head(props: {
125
130
  children?: JSXNode;
126
131
  }): JSXNode;
127
- export declare function Script(props: {
128
- src?: string;
129
- children?: string;
130
- }): JSXNode;
131
- export declare function Style(props: {
132
- children?: string;
133
- }): JSXNode;
132
+ export declare function Script(props: Record<string, any>): JSXNode;
133
+ export declare function Style(props: Record<string, any>): JSXNode;
134
134
  export declare function Link(props: {
135
135
  href?: string;
136
136
  prefetch?: boolean;
package/dist/server.js CHANGED
@@ -646,6 +646,8 @@ function deferSlot(ctx, node, done) {
646
646
  ctx.slots.push({ token, id, node, done: (html) => done(html, id), vals: ctx.vals });
647
647
  return token;
648
648
  }
649
+ // slotClose is the marker that ends the HTML of the slot with this id.
650
+ const slotClose = (id) => `<!--/krate-slot:${id}-->`;
649
651
  // mergeSlotValues layers the values a component provides at a slot over the
650
652
  // ones forwarded into the component.
651
653
  function mergeSlotValues(outer, own) {
@@ -816,12 +818,29 @@ function htmlSlot(ctx, node) {
816
818
  });
817
819
  return slot;
818
820
  }
819
- // propsScript is the JSON script that carries an island's props, placed just
820
- // before its <krate-island>. Every "<" is escaped, so no "</script" or "<!--"
821
- // in a value can end the script or open a comment.
821
+ // propsScript is the JSON script that carries a real-React island's props,
822
+ // placed just before its <krate-island>. Every "<" is escaped, so no
823
+ // "</script" or "<!--" in a value can end the script or open a comment.
822
824
  function propsScript(data) {
823
825
  return `<script type="application/json" data-krate-props>${JSON.stringify(data).replace(/</g, "\\u003c")}</script>`;
824
826
  }
827
+ // ISLAND_OPEN starts the comment that opens a Preact island; ISLAND_CLOSE is
828
+ // the comment that ends it. The island's HTML sits between them with no
829
+ // element of its own, so child combinators and sibling selectors of the
830
+ // parent (space-y-*, divide-*, > :first-child) see the component's root
831
+ // nodes, as in React.
832
+ export const ISLAND_OPEN = "krate-island:";
833
+ export const ISLAND_CLOSE = "<!--/krate-island-->";
834
+ // islandOpen is the opening comment of a Preact island: its module, export,
835
+ // chunk and props as JSON. "<", ">" and "--" are escaped (they occur only in
836
+ // strings), so no value can end the comment or open another one.
837
+ function islandOpen(moduleId, exportName, src, props) {
838
+ const json = JSON.stringify({ m: moduleId, e: exportName, s: src, p: props })
839
+ .replace(/</g, "\\u003c")
840
+ .replace(/>/g, "\\u003e")
841
+ .replace(/--/g, "-\\u002d");
842
+ return `<!--${ISLAND_OPEN}${json}-->`;
843
+ }
825
844
  const warnedUncloneable = new Set();
826
845
  // warnUncloneable reports an asChild component whose child reached the
827
846
  // client as server-rendered HTML (raw HTML, a deferred slot), which its Slot
@@ -856,9 +875,12 @@ function wrapClientNamespace(moduleId, exportName, src, ns, render, hydrate) {
856
875
  * clientBoundary wraps an export of a `"use client"` module, or a component
857
876
  * of a React package, for the server bundle of a page that renders server
858
877
  * components. The server renders the component's initial HTML (render) and,
859
- * when it hydrates, puts it in a <krate-island> marker preceded by a JSON
860
- * script with its serialized props; the per-module client chunk at src
861
- * hydrates it in the browser. A component without state or effects (hydrate
878
+ * when it hydrates, puts it between <!--krate-island:{...}--> (module,
879
+ * export, chunk and serialized props) and <!--/krate-island--> with no
880
+ * element around it; the per-module client chunk at src hydrates those nodes
881
+ * in the browser. A real-React island (flight) gets a <krate-island> element
882
+ * instead, preceded by a JSON script with its props, because createRoot needs
883
+ * a container. A component without state or effects (hydrate
862
884
  * false, an icon) is plain HTML. Children are rendered on the server into the
863
885
  * component's HTML and adopted there by the browser (see DeferredSlot), or,
864
886
  * when they hold client components of their own, sent as a tree that keeps
@@ -905,14 +927,21 @@ export function clientBoundary(moduleId, exportName, src, impl, render, hydrate
905
927
  return renderNode(await resolveTree(s.node, inner));
906
928
  }));
907
929
  // A slot whose token is in the render is in the document: the browser
908
- // adopts those nodes, so they are not sent again inside the props.
930
+ // adopts those nodes, so they are not sent again inside the props. An
931
+ // island keeps the token as the slot's open marker and closes it after
932
+ // the HTML; a component without an island needs no markers.
909
933
  const placed = slots.map((s) => html.includes(s.token));
910
934
  slots.forEach((s, i) => {
911
935
  s.done(placed[i] ? null : rendered[i]);
912
- html = html.split(s.token).join(rendered[i]);
936
+ html = html.split(s.token).join(hydrates ? s.token + rendered[i] + slotClose(s.id) : rendered[i]);
913
937
  });
914
938
  if (!hydrates)
915
939
  return raw(html);
940
+ // A real-React island (flight) mounts with createRoot, which needs an
941
+ // element of its own; a Preact island hydrates the nodes between its two
942
+ // comments in place.
943
+ if (!flight)
944
+ return raw(islandOpen(moduleId, exportName, src, data) + html + ISLAND_CLOSE);
916
945
  return raw(propsScript(data) +
917
946
  `<krate-island style="display:contents" data-module="${escapeHTML(moduleId)}" data-export="${escapeHTML(exportName)}" ` +
918
947
  `data-src="${escapeHTML(src)}">${html}</krate-island>`);
@@ -934,16 +963,15 @@ export const HEAD_CLOSE = "<!--/krate-head-->";
934
963
  export function Head(props) {
935
964
  return [raw(HEAD_OPEN), props.children ?? "", raw(HEAD_CLOSE)];
936
965
  }
937
- // Script - renders a <script> tag.
966
+ // Script and Style render the element in place with every attribute (src,
967
+ // defer, async, data-*, nonce, ...), as the static compiler does. Their
968
+ // children are raw text. `strategy` is next/script's and has no HTML meaning.
938
969
  export function Script(props) {
939
- if (props.src) {
940
- return `<script src="${escapeHTML(props.src)}"></script>`;
941
- }
942
- return `<script>${props.children ?? ""}</script>`;
970
+ const { strategy: _strategy, ...rest } = props;
971
+ return jsx("script", rest);
943
972
  }
944
- // Style - renders a <style> tag.
945
973
  export function Style(props) {
946
- return `<style>${props.children ?? ""}</style>`;
974
+ return jsx("style", props);
947
975
  }
948
976
  // linkAttributes computes the attributes of a <Link> anchor. An empty string
949
977
  // stands for a boolean attribute.
@@ -4,6 +4,8 @@ export interface KrateRuntimeConfig {
4
4
  viewTransitions?: boolean | 'auto';
5
5
  /** Milliseconds a prefetched document stays fresh (default 30000). */
6
6
  prefetchTTL?: number;
7
+ /** Default link prefetch: "viewport" also prefetches links as they scroll into view. */
8
+ prefetch?: 'intent' | 'viewport';
7
9
  /** Set by `krate dev`: enables router dev warnings. */
8
10
  dev?: boolean;
9
11
  }
package/dist/testing.d.ts CHANGED
@@ -4,8 +4,9 @@
4
4
  * (it uses AsyncLocalStorage); import it from your test files, never from app
5
5
  * code.
6
6
  */
7
+ import type { KrateRequest } from "./after.js";
7
8
  export type RouteMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE" | "HEAD" | "OPTIONS";
8
- export type RouteHandler = (request: Request, context: {
9
+ export type RouteHandler = (request: KrateRequest, context: {
9
10
  params: Record<string, string>;
10
11
  }) => Response | Promise<Response>;
11
12
  /** An imported `src/api/*.ts` module: named method exports and/or a default Web handler. */
@@ -20,6 +21,8 @@ export interface CallRouteOptions {
20
21
  json?: unknown;
21
22
  /** A raw body (string, FormData, ...). Ignored when `json` is set. */
22
23
  body?: BodyInit | null;
24
+ /** The site base path, reported by request.nextUrl.basePath. */
25
+ basePath?: string;
23
26
  }
24
27
  /**
25
28
  * Calls a route module the way the server does: the named export for `method`
package/dist/testing.js CHANGED
@@ -5,6 +5,7 @@
5
5
  * code.
6
6
  */
7
7
  import { AsyncLocalStorage } from "node:async_hooks";
8
+ import { attachCookies } from "./request-extras.js";
8
9
  const METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"];
9
10
  /**
10
11
  * Calls a route module the way the server does: the named export for `method`
@@ -13,7 +14,8 @@ const METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"];
13
14
  * (`"/api/users/7?x=1"`), an absolute URL, or a ready `Request`.
14
15
  */
15
16
  export async function callRoute(mod, method, target, options = {}) {
16
- const request = toRequest(method, target, options);
17
+ // The server hands routes a Request with request.cookies and request.nextUrl.
18
+ const request = attachCookies(toRequest(method, target, options), options.basePath ?? "");
17
19
  const context = { params: options.params ?? {} };
18
20
  const named = (m) => (typeof mod[m] === "function" ? mod[m] : undefined);
19
21
  const fallback = typeof mod.default === "function" ? mod.default : undefined;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@krate/runtime",
3
- "version": "0.5.0-rc.6",
3
+ "version": "0.5.0-rc.8",
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",