@krate/runtime 0.5.0-rc.16 → 0.5.0-rc.18

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.
package/dist/list.js CHANGED
@@ -24,7 +24,7 @@
24
24
  */
25
25
  import { createEffect, createRoot, createSignal, onCleanup, untrack } from './signal.js';
26
26
  import { krateUnmount, krateWithOwner } from './effects.js';
27
- import { adoptValue, appendChild, disposeNode, insertAt, removeRest, trackEffect, withDOM, withVNodes, } from './dom.js';
27
+ import { adoptValue, appendChild, disposeNode, insertAt, krateRemoveNode, removeRest, trackEffect, withDOM, withVNodes, } from './dom.js';
28
28
  import { krateMuteEvents } from './events.js';
29
29
  import { krateWithIdScope } from './use-id.js';
30
30
  /** Canonical key: explicit keys are `$` + String(key); implicit keys are the index. */
@@ -141,8 +141,13 @@ function disposeRange(start, end, markers) {
141
141
  let n = start.nextSibling;
142
142
  while (n && n !== end) {
143
143
  const next = n.nextSibling;
144
- disposeNode(n);
145
- parent.removeChild(n);
144
+ // A removed row's element may stay for its exit animation (see krateSetExitHook).
145
+ if (markers)
146
+ krateRemoveNode(parent, n);
147
+ else {
148
+ disposeNode(n);
149
+ parent.removeChild(n);
150
+ }
146
151
  n = next;
147
152
  }
148
153
  if (markers) {
package/dist/metadata.js CHANGED
@@ -13,8 +13,10 @@
13
13
  // languages, media, types), openGraph, twitter, icons, manifest, themeColor,
14
14
  // viewport (string), verification, appleWebApp, formatDetection, category,
15
15
  // itunes, appLinks, archives, assets, bookmarks and other. metadataBase resolves
16
- // relative URLs. Anything else is ignored.
16
+ // relative URLs (not icons, which stay as written). Anything else is ignored.
17
17
  import { httpFallbackStatus, isDynamicUsageError, redirectTarget, thenableRecord } from './request-context.js';
18
+ // The viewport Next.js starts from before merging viewport exports.
19
+ const DEFAULT_VIEWPORT = { width: 'device-width', initialScale: 1 };
18
20
  function isThenable(v) {
19
21
  return !!v && typeof v.then === 'function';
20
22
  }
@@ -106,7 +108,18 @@ export async function resolveMetadata(segments, rawProps) {
106
108
  acc = mergeSegment(acc, own);
107
109
  if (mod && mod.viewport && typeof mod.viewport === 'object') {
108
110
  const { themeColor, colorScheme, ...rest } = mod.viewport;
109
- acc = mergeSegment(acc, { viewport: rest, ...(themeColor !== undefined ? { themeColor } : {}), ...(colorScheme !== undefined ? { colorScheme } : {}) });
111
+ // Like Next.js, a viewport export sets only the keys it names, over the
112
+ // parents' viewport and the defaults (width=device-width, initial-scale=1).
113
+ const merged = {};
114
+ if (Object.keys(rest).length > 0) {
115
+ const prev = acc.metadata.viewport;
116
+ merged.viewport = { ...(prev && typeof prev === 'object' ? prev : DEFAULT_VIEWPORT), ...rest };
117
+ }
118
+ if (themeColor !== undefined)
119
+ merged.themeColor = themeColor;
120
+ if (colorScheme !== undefined)
121
+ merged.colorScheme = colorScheme;
122
+ acc = mergeSegment(acc, merged);
110
123
  }
111
124
  if (seg.files)
112
125
  acc = mergeFiles(acc, fillParams(seg.files, rawProps.params), own);
@@ -308,8 +321,10 @@ export function renderMetadataTags(md, templates = {}) {
308
321
  push(meta('name', 'category', md.category));
309
322
  if (md.itunes)
310
323
  push(meta('name', 'apple-itunes-app', `app-id=${md.itunes.appId}${md.itunes.appArgument ? `, app-argument=${md.itunes.appArgument}` : ''}`));
324
+ // Icons keep the URL as written (Next.js does not resolve them against
325
+ // metadataBase); a relative URL is served from the site itself.
311
326
  if (md.icons)
312
- renderIcons(md.icons, base, push);
327
+ renderIcons(md.icons, push);
313
328
  if (md.verification) {
314
329
  const v = md.verification;
315
330
  for (const x of toArray(v.google))
@@ -367,12 +382,12 @@ export function renderMetadataTags(md, templates = {}) {
367
382
  push(meta('name', k, x));
368
383
  return tags.join('\n');
369
384
  }
370
- function renderIcons(icons, base, push) {
385
+ function renderIcons(icons, push) {
371
386
  const asDesc = (i, rel) => (typeof i === 'string' || i instanceof URL ? { url: i, rel } : { rel, ...i });
372
387
  const emit = (list, rel) => {
373
388
  for (const i of toArray(list)) {
374
389
  const d = asDesc(i, rel);
375
- push(link({ rel: d.rel || rel, href: resolveBaseJoin(d.url, base), type: d.type, sizes: d.sizes, media: d.media, color: d.color, fetchpriority: d.fetchPriority }));
390
+ push(link({ rel: d.rel || rel, href: String(d.url), type: d.type, sizes: d.sizes, media: d.media, color: d.color, fetchpriority: d.fetchPriority }));
376
391
  }
377
392
  };
378
393
  if (typeof icons === 'string' || icons instanceof URL || Array.isArray(icons)) {
@@ -0,0 +1,4 @@
1
+ /** Splits comma-joined Set-Cookie lines; the comma in an Expires date stays inside its cookie. */
2
+ export declare function splitSetCookieList(s: string): string[];
3
+ /** The request Cookie header after applying Set-Cookie lines: set replaces, expired removes. */
4
+ export declare function mergeCookieHeader(cookie: string, lines: string[], now?: number): string;
@@ -0,0 +1,67 @@
1
+ // Next's x-middleware-set-cookie protocol: NextResponse.next() lists the
2
+ // cookies middleware set (Set-Cookie lines joined with commas), and the server
3
+ // applies them to the request it forwards so cookies() sees them.
4
+ /** Splits comma-joined Set-Cookie lines; the comma in an Expires date stays inside its cookie. */
5
+ export function splitSetCookieList(s) {
6
+ const out = [];
7
+ let start = 0;
8
+ for (let i = 0; i < s.length; i++) {
9
+ if (s[i] !== ",")
10
+ continue;
11
+ let j = i + 1;
12
+ while (j < s.length && (s[j] === " " || s[j] === "\t"))
13
+ j++;
14
+ let k = j;
15
+ while (k < s.length && s[k] !== "=" && s[k] !== ";" && s[k] !== "," && s[k] !== " ")
16
+ k++;
17
+ if (k > j && s[k] === "=") {
18
+ const part = s.slice(start, i).trim();
19
+ if (part)
20
+ out.push(part);
21
+ start = j;
22
+ i = j - 1;
23
+ }
24
+ }
25
+ const last = s.slice(start).trim();
26
+ if (last)
27
+ out.push(last);
28
+ return out;
29
+ }
30
+ /** The request Cookie header after applying Set-Cookie lines: set replaces, expired removes. */
31
+ export function mergeCookieHeader(cookie, lines, now = Date.now()) {
32
+ const jar = new Map();
33
+ for (const part of cookie.split(";")) {
34
+ const p = part.trim();
35
+ if (!p)
36
+ continue;
37
+ const eq = p.indexOf("=");
38
+ jar.set(eq === -1 ? p : p.slice(0, eq).trim(), eq === -1 ? "" : p.slice(eq + 1));
39
+ }
40
+ for (const value of lines) {
41
+ for (const line of splitSetCookieList(value)) {
42
+ const attrs = line.split(";");
43
+ const first = attrs.shift().trim();
44
+ const eq = first.indexOf("=");
45
+ if (eq <= 0)
46
+ continue;
47
+ const name = first.slice(0, eq).trim();
48
+ let expired = false;
49
+ for (const a of attrs) {
50
+ const i = a.indexOf("=");
51
+ const key = (i === -1 ? a : a.slice(0, i)).trim().toLowerCase();
52
+ const val = i === -1 ? "" : a.slice(i + 1).trim();
53
+ if (key === "max-age" && Number(val) <= 0)
54
+ expired = true;
55
+ if (key === "expires") {
56
+ const t = Date.parse(val);
57
+ if (!Number.isNaN(t) && t <= now)
58
+ expired = true;
59
+ }
60
+ }
61
+ jar.delete(name);
62
+ if (!expired)
63
+ jar.set(name, first.slice(eq + 1).trim());
64
+ }
65
+ }
66
+ return Array.from(jar, ([k, v]) => `${k}=${v}`).join("; ");
67
+ }
@@ -9,7 +9,7 @@
9
9
  import { getRequestContext } from './request-context.js';
10
10
  import * as serverNav from './navigation-server.js';
11
11
  import { krateRouter } from './router.js';
12
- import { krateRouteStore, krateMatchParams, krateLayoutSegments } from './navigation.js';
12
+ import { krateRouteStore, krateMatchParams, krateLayoutSegments, krateMarkPrerenderUnknown } from './navigation.js';
13
13
  const routerInstance = {
14
14
  push: (href, options) => void krateRouter.push(href, options),
15
15
  replace: (href, options) => void krateRouter.replace(href, options),
@@ -47,6 +47,7 @@ export function createValueNavigationHooks(useSyncExternalStore) {
47
47
  useSearchParams() {
48
48
  if (getRequestContext())
49
49
  return serverNav.useSearchParams();
50
+ krateMarkPrerenderUnknown();
50
51
  const s = route();
51
52
  if (s.search !== paramsKey) {
52
53
  paramsKey = s.search;
@@ -4,6 +4,13 @@ interface RouteSnapshot {
4
4
  /** The route pattern of the current document ("/blog/[slug]"), "" for a static route. */
5
5
  route: string;
6
6
  }
7
+ /**
8
+ * Records that a build-time render read a route value it cannot know (the
9
+ * path of a page rendered per request, or the query): the compiler then has
10
+ * the island render over its server markup in the browser instead of
11
+ * hydrating it, so attributes made from that value are patched.
12
+ */
13
+ export declare function krateMarkPrerenderUnknown(): void;
7
14
  /**
8
15
  * An external store of the route for React-model components (Preact compat and
9
16
  * real React islands), which read hook results as plain values and re-render
@@ -32,9 +32,33 @@ function documentRoute() {
32
32
  function cleanPath(pathname) {
33
33
  return pathname.length > 1 && pathname.endsWith('/') ? pathname.replace(/\/+$/, '') || '/' : pathname;
34
34
  }
35
+ /**
36
+ * The page a build-time render outside the browser is for: the compiler sets
37
+ * __KRATE_PRERENDER__ before it server renders an island, so the router hooks
38
+ * see the page's path instead of "/".
39
+ */
40
+ function prerenderSnapshot() {
41
+ const nav = globalThis.__KRATE_PRERENDER__;
42
+ if (nav && typeof nav.pathname === 'string') {
43
+ return { pathname: cleanPath(nav.pathname), search: '', route: typeof nav.route === 'string' ? nav.route : '' };
44
+ }
45
+ krateMarkPrerenderUnknown();
46
+ return { pathname: '/', search: '', route: '' };
47
+ }
48
+ /**
49
+ * Records that a build-time render read a route value it cannot know (the
50
+ * path of a page rendered per request, or the query): the compiler then has
51
+ * the island render over its server markup in the browser instead of
52
+ * hydrating it, so attributes made from that value are patched.
53
+ */
54
+ export function krateMarkPrerenderUnknown() {
55
+ if (typeof location !== 'undefined')
56
+ return;
57
+ globalThis.__KRATE_PRERENDER_NAV_UNKNOWN__ = true;
58
+ }
35
59
  function snapshot() {
36
60
  if (typeof location === 'undefined')
37
- return { pathname: '/', search: '', route: '' };
61
+ return prerenderSnapshot();
38
62
  const { pathname, search } = getNavigationState();
39
63
  return { pathname: cleanPath(pathname), search, route: documentRoute() };
40
64
  }
@@ -119,6 +143,7 @@ export function usePathname() {
119
143
  export function useSearchParams() {
120
144
  if (getRequestContext())
121
145
  return serverNav.useSearchParams();
146
+ krateMarkPrerenderUnknown();
122
147
  const read = routeState();
123
148
  const derived = krateDerived(() => new URLSearchParams(read().search));
124
149
  return describe(derived, () => read().search);
@@ -18,6 +18,10 @@ function reportError(err) {
18
18
  console.error(err);
19
19
  }
20
20
  const SHARED = '__krateReactCompat';
21
+ // The redirects server actions followed (see actions.ts).
22
+ function redirectCount() {
23
+ return globalThis.__krateActionRedirects || 0;
24
+ }
21
25
  /**
22
26
  * Builds the additions once per Preact instance: the `react` and `react-dom`
23
27
  * modules of a bundle (and of every island chunk) share one action scope and
@@ -207,7 +211,12 @@ function build(c, options) {
207
211
  const run = l.chain.then(async () => {
208
212
  if (l.cancelled)
209
213
  return;
214
+ const before = redirectCount();
210
215
  const next = await l.action(l.state, payload);
216
+ // A redirecting action has no next state (Next throws there): the
217
+ // page is being replaced, so the island keeps its state.
218
+ if (redirectCount() !== before)
219
+ return;
211
220
  l.state = next;
212
221
  setState(() => next);
213
222
  });
package/dist/react.d.ts CHANGED
@@ -212,6 +212,7 @@ export declare function startTransition(fn: () => unknown): void;
212
212
  */
213
213
  export declare function use<T>(value: PromiseLike<T> | ReactContext<T>): T;
214
214
  export declare function flushSync<T>(fn: () => T): T;
215
+ export { unstable_batchedUpdates, findDOMNode, render, hydrate, unmountComponentAtNode } from './hints.js';
215
216
  /**
216
217
  * Runtime portal (content rendered by `h()` after hydration; compiled source
217
218
  * components lower createPortal to an anchor instead, see portal.ts). The
@@ -246,4 +247,3 @@ export declare const reactCompat: {
246
247
  h: typeof h;
247
248
  Fragment: symbol;
248
249
  };
249
- export {};
package/dist/react.js CHANGED
@@ -477,6 +477,11 @@ export function use(value) {
477
477
  export function flushSync(fn) {
478
478
  return fn();
479
479
  }
480
+ // react-dom resolves to this module in page bundles and build-time
481
+ // evaluation, so it has the react-dom exports of the server facade (hints.ts)
482
+ // too: the APIs React 19 removed import fine and only a call fails, with
483
+ // KR8001.
484
+ export { unstable_batchedUpdates, findDOMNode, render, hydrate, unmountComponentAtNode } from './hints.js';
480
485
  /**
481
486
  * Runtime portal (content rendered by `h()` after hydration; compiled source
482
487
  * components lower createPortal to an anchor instead, see portal.ts). The
package/dist/router.js CHANGED
@@ -382,9 +382,10 @@ function storeInitialDocument(key, url) {
382
382
  if (savingData())
383
383
  return;
384
384
  const gen = cacheGen;
385
+ const release = watchUnload();
385
386
  idle(() => {
386
- if (historyDocs.has(key) || gen !== cacheGen)
387
- return;
387
+ if (historyDocs.has(key) || gen !== cacheGen || unloading)
388
+ return release();
388
389
  fetch(cacheKey(url), { headers: { Accept: 'text/html' }, credentials: 'same-origin' })
389
390
  .then(async (res) => {
390
391
  if (!res.ok || /no-store/i.test(res.headers.get('cache-control') || ''))
@@ -402,9 +403,36 @@ function storeInitialDocument(key, url) {
402
403
  })
403
404
  .catch(() => {
404
405
  /* back falls back to a normal fetch */
405
- });
406
+ })
407
+ .finally(release);
406
408
  });
407
409
  }
410
+ // True once the page started unloading (a hard navigation is pending). A fetch
411
+ // started then fails at once, and WebKit reports it as a page error even when
412
+ // the rejection is handled, so the idle copy of the first entry is skipped.
413
+ // The beforeunload listener is attached only while that copy is pending: some
414
+ // browsers keep a page with one out of the back/forward cache.
415
+ let unloading = false;
416
+ let unloadWatchers = 0;
417
+ function onBeforeUnload() {
418
+ unloading = true;
419
+ // A download or a 204 response fires beforeunload but keeps the page.
420
+ setTimeout(() => {
421
+ unloading = false;
422
+ }, 3000);
423
+ }
424
+ function watchUnload() {
425
+ if (unloadWatchers++ === 0)
426
+ window.addEventListener('beforeunload', onBeforeUnload);
427
+ let released = false;
428
+ return () => {
429
+ if (released)
430
+ return;
431
+ released = true;
432
+ if (--unloadWatchers === 0)
433
+ window.removeEventListener('beforeunload', onBeforeUnload);
434
+ };
435
+ }
408
436
  function isHTMLType(ct) {
409
437
  return /text\/html|application\/xhtml\+xml/i.test(ct);
410
438
  }
@@ -998,12 +1026,27 @@ function hashTarget(hash) {
998
1026
  }
999
1027
  return document.getElementById(id) || document.getElementsByName(id)[0] || null;
1000
1028
  }
1029
+ function pageScroller() {
1030
+ const s = globalThis.__krate_scroller;
1031
+ return s && typeof s.scrollTo === 'function' ? s : undefined;
1032
+ }
1033
+ function scrollPage(y, reason) {
1034
+ const s = pageScroller();
1035
+ if (s)
1036
+ s.scrollTo(y, reason);
1037
+ else
1038
+ window.scrollTo(0, y);
1039
+ }
1001
1040
  function scrollToHash(hash) {
1002
1041
  const el = hashTarget(hash);
1003
1042
  if (!el)
1004
1043
  return false;
1005
1044
  try {
1006
- el.scrollIntoView({ block: 'start' });
1045
+ const s = pageScroller();
1046
+ if (s)
1047
+ s.scrollTo(el, 'hash');
1048
+ else
1049
+ el.scrollIntoView({ block: 'start' });
1007
1050
  }
1008
1051
  catch {
1009
1052
  /* ignore */
@@ -1011,10 +1054,12 @@ function scrollToHash(hash) {
1011
1054
  return true;
1012
1055
  }
1013
1056
  function applyScroll(url, req) {
1057
+ // The new page has rendered: the scroller measures it before scrolling.
1058
+ pageScroller()?.resize();
1014
1059
  if (req.kind === 'pop') {
1015
1060
  const saved = req.restoreKey ? scrollPositions.get(req.restoreKey) : undefined;
1016
1061
  if (saved !== undefined) {
1017
- window.scrollTo(0, saved);
1062
+ scrollPage(saved, 'restore');
1018
1063
  return;
1019
1064
  }
1020
1065
  }
@@ -1022,7 +1067,7 @@ function applyScroll(url, req) {
1022
1067
  if (scrollToHash(hash))
1023
1068
  return;
1024
1069
  if (req.scroll && req.kind !== 'refresh')
1025
- window.scrollTo(0, 0);
1070
+ scrollPage(0, 'top');
1026
1071
  }
1027
1072
  let focusedRoot = null;
1028
1073
  // Attributes that tell a focused control apart from its siblings, in addition
@@ -2013,7 +2058,7 @@ function restoreSnapshot(snap, key) {
2013
2058
  renderedPath = pathOf(location.href);
2014
2059
  const saved = scrollPositions.get(key);
2015
2060
  if (saved !== undefined)
2016
- window.scrollTo(0, saved);
2061
+ scrollPage(saved, 'restore');
2017
2062
  updateActiveLinks();
2018
2063
  dispatch('krate:navigate', { url: location.href, status: 200 });
2019
2064
  notifyNavigation(location.href);
@@ -2054,7 +2099,7 @@ function hashNavigate(url, req) {
2054
2099
  }
2055
2100
  const hash = new URL(url).hash;
2056
2101
  if (!scrollToHash(hash) && req.scroll && !hash)
2057
- window.scrollTo(0, 0);
2102
+ scrollPage(0, 'top');
2058
2103
  emit();
2059
2104
  }
2060
2105
  function start(req) {
@@ -2176,7 +2221,7 @@ function popstateHandler(e) {
2176
2221
  currentKey = key || currentKey;
2177
2222
  const saved = key ? scrollPositions.get(key) : undefined;
2178
2223
  if (saved !== undefined)
2179
- window.scrollTo(0, saved);
2224
+ scrollPage(saved, 'restore');
2180
2225
  else
2181
2226
  scrollToHash(location.hash);
2182
2227
  emit();
@@ -2213,6 +2258,7 @@ function pagehideHandler() {
2213
2258
  }
2214
2259
  }
2215
2260
  function pageshowHandler() {
2261
+ unloading = false;
2216
2262
  try {
2217
2263
  history.scrollRestoration = 'manual';
2218
2264
  }
@@ -19,6 +19,7 @@ import { allSuspense, canStreamOutOfOrder, FLASH_COOKIE, flashPayloadOf, injectF
19
19
  import { mergeHead } from "./head-tags.js";
20
20
  import { applyDynamicRouteParams, baseName, cleanPath, compareRouteSpecificity, compileMatcher, extName, goRedirect, IMMUTABLE_CACHE_CONTROL, isDynamicPattern, isFileLikePath, isHTMLDocRequest, isInternalOutputPath, matchRoutePattern, normalizeRoutePattern, requestRoute, rewriteTargetPath, staticCacheControl, } from "./handler-routing.js";
21
21
  import { attachCookies } from "./request-extras.js";
22
+ import { mergeCookieHeader } from "./middleware-cookies.js";
22
23
  import { buildDestination, compileMatcher as compileRuleMatcher, mergeRequestQuery } from "./route-source.js";
23
24
  import { lookupSegmentPage, newServerError, renderSegmentPage, SEGMENT_KIND_OF_STATUS, } from "./handler-segments.js";
24
25
  import { httpFallbackStatus } from "./request-context.js";
@@ -415,6 +416,47 @@ export function createKrateHandler(options) {
415
416
  return false;
416
417
  return !!(await staticLayer.exists(p));
417
418
  }
419
+ /** Files the build generated: middleware never runs for them, as Next apps exclude _next/static. */
420
+ async function isBuildAsset(p) {
421
+ if (!staticLayer || !(hashed.has(p) || /^\/(?:chunks|workers|_krate)\//.test(p)))
422
+ return false;
423
+ return !!(await staticLayer.exists(p));
424
+ }
425
+ /**
426
+ * The URL and path middleware sees. A server action POST shows the page it
427
+ * was posted from, as Next posts actions to the page URL; the action still
428
+ * runs at its own endpoint.
429
+ */
430
+ function middlewareView(rs) {
431
+ const own = { url: fullURL(rs), path: rs.path };
432
+ if (rs.method !== "POST" || !rs.path.startsWith("/__krate/action/"))
433
+ return own;
434
+ let ret = sanitizeActionReturn(new URLSearchParams(rs.search).get("__krate_return") || "", rs);
435
+ if (!ret)
436
+ ret = sanitizeActionReturn(rs.headers.get("x-krate-return") || "", rs);
437
+ if (!ret)
438
+ ret = sanitizeActionReturn(rs.headers.get("referer") || "", rs);
439
+ if (!ret)
440
+ return own;
441
+ let u;
442
+ try {
443
+ u = new URL(ret, rs.origin);
444
+ }
445
+ catch {
446
+ return own;
447
+ }
448
+ let path = u.pathname;
449
+ if (basePath && (path === basePath || path.startsWith(basePath + "/")))
450
+ path = path.slice(basePath.length) || "/";
451
+ let decoded = path;
452
+ try {
453
+ decoded = decodeURIComponent(path);
454
+ }
455
+ catch {
456
+ // keep the escaped form
457
+ }
458
+ return { url: rs.origin + path + u.search, path: decoded };
459
+ }
418
460
  /** Runs middleware; a Response ends the request, null continues (headers/rewrite already applied). */
419
461
  async function runMiddleware(rs) {
420
462
  const p = rs.path;
@@ -436,13 +478,16 @@ export function createKrateHandler(options) {
436
478
  catch (e) {
437
479
  return middlewareFailed(rs, e);
438
480
  }
481
+ if (await isBuildAsset(p))
482
+ return null;
439
483
  if (!matchers && (await skipsMiddleware(p)))
440
484
  return null;
441
- if (matchers && !matchers.some((re) => re.test(p)))
485
+ const view = middlewareView(rs);
486
+ if (matchers && !matchers.some((re) => re.test(view.path)))
442
487
  return null;
443
488
  let result;
444
489
  try {
445
- const request = attachCookies(new Request(fullURL(rs), { method: rs.method, headers: new Headers(rs.request.headers) }), basePath);
490
+ const request = attachCookies(new Request(view.url, { method: rs.method, headers: new Headers(rs.request.headers) }), basePath);
446
491
  result = await handler(request);
447
492
  }
448
493
  catch (e) {
@@ -455,6 +500,7 @@ export function createKrateHandler(options) {
455
500
  const hdrs = [];
456
501
  let keep = null;
457
502
  const vals = new Map();
503
+ const setCookies = [];
458
504
  for (const [k, v] of headerPairs(result.headers)) {
459
505
  if (k === "x-middleware-next")
460
506
  next = true;
@@ -464,14 +510,20 @@ export function createKrateHandler(options) {
464
510
  keep = new Set(v.split(",").map((n) => n.trim().toLowerCase()).filter(Boolean));
465
511
  else if (k.startsWith("x-middleware-request-"))
466
512
  vals.set(k.slice("x-middleware-request-".length), v);
467
- else
513
+ else if (k === "x-middleware-set-cookie")
514
+ setCookies.push(v);
515
+ // The rest of Next's x-middleware-* protocol never reaches the client.
516
+ else if (!k.startsWith("x-middleware-"))
468
517
  hdrs.push([k, v]);
469
518
  }
470
519
  if (next || rewrite) {
471
520
  if (keep)
472
521
  overrideRequestHeaders(rs, keep, vals);
522
+ if (setCookies.length > 0)
523
+ mergeMiddlewareCookies(rs, setCookies);
473
524
  writeHeaderPairs(rs.res, hdrs);
474
- if (rewrite)
525
+ // A server action runs where it was posted, whatever its page rewrites to.
526
+ if (rewrite && !p.startsWith("/__krate/action/"))
475
527
  applyRewrite(rs, rewrite);
476
528
  return null;
477
529
  }
@@ -499,6 +551,19 @@ export function createKrateHandler(options) {
499
551
  rs.request = new Request(rs.request, { headers: edit(rs.request.headers) });
500
552
  rs.headers = shared ? rs.request.headers : edit(rs.headers);
501
553
  }
554
+ /** x-middleware-set-cookie: cookies middleware set join the request cookies, so cookies() sees them. */
555
+ function mergeMiddlewareCookies(rs, lines) {
556
+ const edit = (h) => {
557
+ const out = new Headers(h);
558
+ out.set("cookie", mergeCookieHeader(h.get("cookie") ?? "", lines));
559
+ if (out.get("cookie") === "")
560
+ out.delete("cookie");
561
+ return out;
562
+ };
563
+ const shared = rs.headers === rs.request.headers;
564
+ rs.request = new Request(rs.request, { headers: edit(rs.request.headers) });
565
+ rs.headers = shared ? rs.request.headers : edit(rs.headers);
566
+ }
502
567
  function middlewareFailed(rs, err) {
503
568
  console.error(`[krate] middleware error: ${rs.method} ${rs.path}: ${(err && err.stack) || err}`);
504
569
  // Fail closed: continuing would turn a broken auth check into an unauthenticated request.
@@ -1735,6 +1800,28 @@ export function createKrateHandler(options) {
1735
1800
  return "";
1736
1801
  }
1737
1802
  }
1803
+ // What Next's redirect() takes: a path or an absolute URL. A URL on the
1804
+ // request's host becomes its path; another origin is followed with a full
1805
+ // navigation, but only when redirect() itself named it (thrown).
1806
+ function actionRedirectTarget(value, host, thrown) {
1807
+ const none = { to: "", external: false };
1808
+ if (typeof value !== "string")
1809
+ return none;
1810
+ const v = value.trim();
1811
+ if (!/^https?:\/\//i.test(v))
1812
+ return { to: safeActionRedirect(v), external: false };
1813
+ let u;
1814
+ try {
1815
+ u = new URL(v);
1816
+ }
1817
+ catch {
1818
+ return none;
1819
+ }
1820
+ const own = String(host || "").split(",")[0].trim().toLowerCase();
1821
+ if (own && u.host.toLowerCase() === own)
1822
+ return { to: safeActionRedirect(u.pathname + u.search + u.hash), external: false };
1823
+ return thrown ? { to: safeExternalRedirect(v), external: true } : none;
1824
+ }
1738
1825
  function sanitizeActionReturn(value, rs) {
1739
1826
  value = value.trim();
1740
1827
  if (!value)
@@ -1942,6 +2029,7 @@ export function createKrateHandler(options) {
1942
2029
  let result;
1943
2030
  let redirect = "";
1944
2031
  let external = false;
2032
+ let thrown = false;
1945
2033
  let failure = null;
1946
2034
  let fallback = 0;
1947
2035
  try {
@@ -1951,6 +2039,7 @@ export function createKrateHandler(options) {
1951
2039
  if (e && typeof e.__krateRedirect === "string") {
1952
2040
  redirect = e.__krateRedirect;
1953
2041
  external = e.__krateRedirectExternal === true;
2042
+ thrown = true;
1954
2043
  }
1955
2044
  else if ((fallback = httpFallbackStatus(e)))
1956
2045
  failure = null;
@@ -1967,7 +2056,10 @@ export function createKrateHandler(options) {
1967
2056
  }
1968
2057
  if (!redirect && result && typeof result === "object" && typeof result.redirect === "string")
1969
2058
  redirect = result.redirect;
1970
- redirect = external ? safeExternalRedirect(redirect) : safeActionRedirect(redirect);
2059
+ if (external)
2060
+ redirect = safeExternalRedirect(redirect);
2061
+ else
2062
+ ({ to: redirect, external } = actionRedirectTarget(redirect, reqHeaders.get("x-forwarded-host") || reqHeaders.get("host"), thrown));
1971
2063
  if (fallback && !failure)
1972
2064
  return withHeaders(rs, actionFallback(rs, fallback, fetchMode, ctx.setCookies, reqHeaders.get("x-krate-return") || ""));
1973
2065
  let body = "";
package/dist/server.d.ts CHANGED
@@ -123,9 +123,10 @@ export declare const ISLAND_CLOSE = "<!--/krate-island-->";
123
123
  * always travel as a tree, with a server component at the top of a child run
124
124
  * to the element it renders, so the component's Slot can clone it. A
125
125
  * namespace export (Radix's Dialog) is wrapped member by member. With `flight` the children always travel as a
126
- * tree (a real-React island rebuilds them as elements, not HTML).
126
+ * tree (a real-React island rebuilds them as elements, not HTML). pkg names
127
+ * the package specifier of a package component (no "use client"), for errors.
127
128
  */
128
- export declare function clientBoundary(moduleId: string, exportName: string, src: string, impl: unknown, render: ClientRender, hydrate?: boolean, flight?: boolean): unknown;
129
+ export declare function clientBoundary(moduleId: string, exportName: string, src: string, impl: unknown, render: ClientRender, hydrate?: boolean, flight?: boolean, pkg?: string): unknown;
129
130
  export declare const HEAD_OPEN = "<!--krate-head-->";
130
131
  export declare const HEAD_CLOSE = "<!--/krate-head-->";
131
132
  export declare function Head(props: {