@krate/runtime 0.5.0-rc.1 → 0.5.0-rc.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 (153) hide show
  1. package/dist/actions.d.ts +7 -0
  2. package/dist/actions.js +23 -8
  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.d.ts +7 -0
  10. package/dist/base-path.js +20 -0
  11. package/dist/builtin-tags.d.ts +12 -0
  12. package/dist/builtin-tags.js +42 -0
  13. package/dist/builtin-tags.test.js +12 -0
  14. package/dist/cache-adapter.test.js +4 -203
  15. package/dist/cache-scope.d.ts +2 -0
  16. package/dist/cache.test.js +1 -197
  17. package/dist/cloudflare-workers.d.ts +2 -0
  18. package/dist/cloudflare-workers.js +27 -0
  19. package/dist/dev-overlay.d.ts +54 -3
  20. package/dist/dev-overlay.js +469 -76
  21. package/dist/dom.js +17 -2
  22. package/dist/events.test.js +2 -407
  23. package/dist/handler-html.test.js +1 -202
  24. package/dist/handler-routing.js +3 -0
  25. package/dist/handler-segments.d.ts +6 -0
  26. package/dist/handler-segments.js +16 -2
  27. package/dist/handler-segments.test.js +8 -200
  28. package/dist/head-tags.d.ts +9 -0
  29. package/dist/head-tags.js +85 -1
  30. package/dist/head-tags.test.js +18 -125
  31. package/dist/index.d.ts +1 -0
  32. package/dist/index.js +3 -0
  33. package/dist/inline-action-token.test.js +31 -0
  34. package/dist/jsx-svg-types.test.js +58 -0
  35. package/dist/jsx-types.d.ts +92 -1
  36. package/dist/krate-core.js +1 -1
  37. package/dist/krate-dev.js +384 -65
  38. package/dist/krate-f-actions.js +1 -1
  39. package/dist/krate-f-navigation.js +1 -1
  40. package/dist/krate-f-router-lite.js +1 -1
  41. package/dist/krate-f-router.js +1 -1
  42. package/dist/krate-features.json +2 -0
  43. package/dist/krate-hydrate-lite.js +5 -5
  44. package/dist/krate-hydrate.js +5 -5
  45. package/dist/krate-runtime.js +5 -5
  46. package/dist/link-base-path.test.js +28 -0
  47. package/dist/metadata.js +3 -0
  48. package/dist/node-server.test.js +1 -355
  49. package/dist/platform.d.ts +52 -0
  50. package/dist/platform.js +57 -0
  51. package/dist/platform.test.js +44 -0
  52. package/dist/router-lite.js +3 -9
  53. package/dist/router-nav.test.js +15 -444
  54. package/dist/router.js +51 -18
  55. package/dist/server-handler.d.ts +49 -0
  56. package/dist/server-handler.js +311 -21
  57. package/dist/server-handler.test.js +56 -344
  58. package/dist/server-renderer.test.js +0 -104
  59. package/dist/server.d.ts +15 -5
  60. package/dist/server.js +150 -22
  61. package/dist/server.test.js +52 -60
  62. package/dist/site-config.d.ts +13 -0
  63. package/dist/site-config.js +28 -0
  64. package/dist/site-config.test.js +30 -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/class-component.test.js +0 -462
  72. package/dist/class-helpers.test.js +0 -169
  73. package/dist/context.test.js +0 -57
  74. package/dist/derived.test.js +0 -140
  75. package/dist/dev-overlay.test.js +0 -165
  76. package/dist/discrete.test.js +0 -100
  77. package/dist/dom.test.js +0 -39
  78. package/dist/effect-errors.test.d.ts +0 -1
  79. package/dist/effect-errors.test.js +0 -199
  80. package/dist/effects.test.d.ts +0 -1
  81. package/dist/effects.test.js +0 -485
  82. package/dist/handler-routing.test.d.ts +0 -1
  83. package/dist/handler-routing.test.js +0 -99
  84. package/dist/highlight-bind.test.d.ts +0 -1
  85. package/dist/highlight-bind.test.js +0 -124
  86. package/dist/highlight.test.d.ts +0 -1
  87. package/dist/highlight.test.js +0 -56
  88. package/dist/lanes.test.d.ts +0 -1
  89. package/dist/lanes.test.js +0 -59
  90. package/dist/list.test.d.ts +0 -1
  91. package/dist/list.test.js +0 -435
  92. package/dist/metadata.test.d.ts +0 -1
  93. package/dist/metadata.test.js +0 -167
  94. package/dist/navigation.test.d.ts +0 -1
  95. package/dist/navigation.test.js +0 -130
  96. package/dist/optimistic-lanes.test.d.ts +0 -1
  97. package/dist/optimistic-lanes.test.js +0 -45
  98. package/dist/patterns.test.d.ts +0 -1
  99. package/dist/patterns.test.js +0 -125
  100. package/dist/portal.test.d.ts +0 -1
  101. package/dist/portal.test.js +0 -99
  102. package/dist/react-effects.test.d.ts +0 -1
  103. package/dist/react-effects.test.js +0 -133
  104. package/dist/react-suspense.test.d.ts +0 -1
  105. package/dist/react-suspense.test.js +0 -194
  106. package/dist/react.test.d.ts +0 -1
  107. package/dist/react.test.js +0 -60
  108. package/dist/react19.test.d.ts +0 -1
  109. package/dist/react19.test.js +0 -176
  110. package/dist/reactivity-core.test.d.ts +0 -1
  111. package/dist/reactivity-core.test.js +0 -152
  112. package/dist/reconcile.test.d.ts +0 -1
  113. package/dist/reconcile.test.js +0 -110
  114. package/dist/refs.test.d.ts +0 -1
  115. package/dist/refs.test.js +0 -257
  116. package/dist/router-layout.test.d.ts +0 -1
  117. package/dist/router-layout.test.js +0 -249
  118. package/dist/router-slots.test.d.ts +0 -1
  119. package/dist/router-slots.test.js +0 -144
  120. package/dist/router-speculation.test.d.ts +0 -1
  121. package/dist/router-speculation.test.js +0 -25
  122. package/dist/router-styles.test.d.ts +0 -1
  123. package/dist/router-styles.test.js +0 -98
  124. package/dist/router.test.d.ts +0 -1
  125. package/dist/router.test.js +0 -36
  126. package/dist/server-async.test.d.ts +0 -1
  127. package/dist/server-async.test.js +0 -216
  128. package/dist/server-highlight.test.d.ts +0 -1
  129. package/dist/server-highlight.test.js +0 -32
  130. package/dist/signal-lanes.test.d.ts +0 -1
  131. package/dist/signal-lanes.test.js +0 -32
  132. package/dist/slots.test.d.ts +0 -1
  133. package/dist/slots.test.js +0 -187
  134. package/dist/snapshots.test.d.ts +0 -1
  135. package/dist/snapshots.test.js +0 -208
  136. package/dist/ssr-core.test.d.ts +0 -1
  137. package/dist/ssr-core.test.js +0 -324
  138. package/dist/static-memory.test.d.ts +0 -1
  139. package/dist/static-memory.test.js +0 -26
  140. package/dist/storage.test.d.ts +0 -1
  141. package/dist/storage.test.js +0 -46
  142. package/dist/suspense-actions.test.d.ts +0 -1
  143. package/dist/suspense-actions.test.js +0 -72
  144. package/dist/suspense.test.d.ts +0 -1
  145. package/dist/suspense.test.js +0 -556
  146. /package/dist/{action-context.test.d.ts → after.test.d.ts} +0 -0
  147. /package/dist/{class-component.test.d.ts → builtin-tags.test.d.ts} +0 -0
  148. /package/dist/{class-helpers.test.d.ts → inline-action-token.test.d.ts} +0 -0
  149. /package/dist/{context.test.d.ts → jsx-svg-types.test.d.ts} +0 -0
  150. /package/dist/{derived.test.d.ts → link-base-path.test.d.ts} +0 -0
  151. /package/dist/{dev-overlay.test.d.ts → platform.test.d.ts} +0 -0
  152. /package/dist/{discrete.test.d.ts → site-config.test.d.ts} +0 -0
  153. /package/dist/{dom.test.d.ts → testing.test.d.ts} +0 -0
@@ -24,6 +24,7 @@ export interface HandlerConfig {
24
24
  source: string;
25
25
  destination: string;
26
26
  permanent?: boolean;
27
+ basePath?: boolean;
27
28
  }>;
28
29
  rewrites: Array<{
29
30
  source: string;
@@ -56,6 +57,8 @@ export interface HandlerConfig {
56
57
  ppr: boolean;
57
58
  pprRevalidate: number;
58
59
  };
60
+ /** Page URL form: "always" (default) redirects /x to /x/, "never" redirects /x/ to /x, "ignore" serves both. */
61
+ trailingSlash?: "always" | "never" | "ignore";
59
62
  }
60
63
  export interface HandlerPage {
61
64
  route: string;
@@ -66,12 +69,29 @@ export interface HandlerPage {
66
69
  serverComponents?: boolean;
67
70
  /** Source directory relative to the pages root, route groups kept (segment page lookup). */
68
71
  segDir?: string;
72
+ /** A segment page that renders per request: reached through its synthetic route, never a URL. */
73
+ segment?: boolean;
69
74
  }
75
+ /**
76
+ * A per-request metadata route. `path` is an exact URL; `prefix` and `suffix`
77
+ * match /sitemap/<id>.xml, where `key` ends in "/[id]".
78
+ */
79
+ export interface MetaRoute {
80
+ path?: string;
81
+ prefix?: string;
82
+ suffix?: string;
83
+ key: string;
84
+ }
85
+ /** The API route key serving URL path p, or "" when no metadata route does. */
86
+ export declare function matchMetaRoute(routes: MetaRoute[] | undefined, p: string): string;
70
87
  export interface ActionEntry {
71
88
  id: string;
72
89
  export: string;
73
90
  file: string;
74
91
  source?: string;
92
+ /** A hoisted inline server action; `captures` names the sealed values it receives first. */
93
+ inline?: boolean;
94
+ captures?: string[];
75
95
  }
76
96
  /** Build data the compiler inlines into the server bundle. */
77
97
  export interface KrateServerData {
@@ -105,6 +125,17 @@ export interface KrateServerData {
105
125
  staticPages?: Record<string, string>;
106
126
  /** API route keys: file path under the API dir without extension ("items/[id]"). */
107
127
  apiRoutes: string[];
128
+ /**
129
+ * Per-route request budgets in seconds (`export const maxDuration`), keyed
130
+ * like apiRoutes. A handler still running at the deadline is aborted
131
+ * (request.signal) and the request answered 504.
132
+ */
133
+ apiMaxDuration?: Record<string, number>;
134
+ /**
135
+ * Metadata routes (robots.ts, sitemap.ts, manifest.ts) that run per request:
136
+ * a public URL served by the API route `key`.
137
+ */
138
+ metaRoutes?: MetaRoute[];
108
139
  actions: ActionEntry[];
109
140
  hasMiddleware: boolean;
110
141
  }
@@ -132,6 +163,12 @@ export interface StaticLayer {
132
163
  export interface HandlerContext {
133
164
  /** Keeps the instance alive for work that outlives the response. */
134
165
  waitUntil?(work: Promise<unknown>): void;
166
+ /** Cloudflare only: let the request fall through to the origin when the Worker throws. */
167
+ passThroughOnException?(): void;
168
+ /** The platform's bindings (the Worker `env` on cloudflare), reachable from page code through getPlatform(). */
169
+ env?: unknown;
170
+ /** Cloudflare's `request.cf` properties. */
171
+ cf?: Record<string, unknown>;
135
172
  }
136
173
  export interface HandlerOptions {
137
174
  target: DeployTarget;
@@ -161,5 +198,17 @@ export interface HandlerOptions {
161
198
  flashSecret?: string;
162
199
  }
163
200
  export type KrateHandler = (request: Request, ctx?: HandlerContext) => Promise<Response>;
201
+ /**
202
+ * Runs fn with the platform of a request (or of a Worker event such as a cron
203
+ * trigger) published to getPlatform() / getCloudflareContext(). The generated
204
+ * Cloudflare Worker wraps the exports of src/cloudflare.ts with it.
205
+ */
206
+ export declare function runWithPlatform<R>(target: DeployTarget, ctx: HandlerContext, fn: () => R): R;
207
+ /**
208
+ * Opens the closure token of an inline server action: AES-256-GCM over the
209
+ * JSON of the captured values, authenticated against the action id, with the
210
+ * key derived from the action secret (the format the server renderer seals).
211
+ */
212
+ export declare function openInlineToken(token: unknown, entry: ActionEntry, secret: string): Promise<unknown[]>;
164
213
  export declare function createKrateHandler(options: HandlerOptions): KrateHandler;
165
214
  export { isDynamicPattern };
@@ -11,6 +11,8 @@
11
11
  // generates (`krate deploy`), and static files come from a pluggable layer.
12
12
  import { AsyncLocalStorage } from "node:async_hooks";
13
13
  import { createSSRCore, MemoryIsrStore, } from "./ssr-core.js";
14
+ import { runAfterTasks } from "./after.js";
15
+ import { platformWaitUntil } from "./platform.js";
14
16
  import { cacheRuntime, installRenderStore, patchFetch } from "./cache-scope.js";
15
17
  import { allSuspense, canStreamOutOfOrder, FLASH_COOKIE, flashPayloadOf, injectFlashNotice, parseRegionShell, regionReplaceScript, requestFlash, signFlash, spliceShell, splitBodyScripts, } from "./handler-html.js";
16
18
  import { mergeHead } from "./head-tags.js";
@@ -21,6 +23,25 @@ import { sha256Hex as portableSha256Hex } from "./sha256.js";
21
23
  import { INVALIDATE_CHANNEL, cacheSpecFromConfig } from "./cache-adapter.js";
22
24
  import { isrStoreFor } from "./shared-isr.js";
23
25
  import { createMemoryStaticLayer } from "./static-memory.js";
26
+ /** The API route key serving URL path p, or "" when no metadata route does. */
27
+ export function matchMetaRoute(routes, p) {
28
+ for (const r of routes || []) {
29
+ if (r.path) {
30
+ if (p === r.path)
31
+ return r.key;
32
+ continue;
33
+ }
34
+ const prefix = r.prefix || "";
35
+ const suffix = r.suffix || "";
36
+ if (p.length <= prefix.length + suffix.length || !p.startsWith(prefix) || !p.endsWith(suffix))
37
+ continue;
38
+ const id = p.slice(prefix.length, p.length - suffix.length);
39
+ if (/[\/\\]/.test(id) || id === "." || id === "..")
40
+ continue;
41
+ return r.key.replace(/\[id\]$/, "") + id;
42
+ }
43
+ return "";
44
+ }
24
45
  // Internals
25
46
  const NO_BODY_STATUS = new Set([101, 204, 205, 304]);
26
47
  const KRATE_METHODS = ["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"];
@@ -35,6 +56,28 @@ function globalStore(name) {
35
56
  g[key] = new AsyncLocalStorage();
36
57
  return g[key];
37
58
  }
59
+ /**
60
+ * Runs fn with the platform of a request (or of a Worker event such as a cron
61
+ * trigger) published to getPlatform() / getCloudflareContext(). The generated
62
+ * Cloudflare Worker wraps the exports of src/cloudflare.ts with it.
63
+ */
64
+ export function runWithPlatform(target, ctx, fn) {
65
+ const platform = {
66
+ target,
67
+ env: ctx.env && typeof ctx.env === "object" ? ctx.env : {},
68
+ ctx: {
69
+ waitUntil: (work) => {
70
+ if (ctx.waitUntil)
71
+ ctx.waitUntil(work);
72
+ else
73
+ void Promise.resolve(work).catch(() => { });
74
+ },
75
+ passThroughOnException: ctx.passThroughOnException ? () => ctx.passThroughOnException() : undefined,
76
+ },
77
+ cf: ctx.cf,
78
+ };
79
+ return globalStore("krate.platform.store").run(platform, fn);
80
+ }
38
81
  function safeDecode(p) {
39
82
  try {
40
83
  return decodeURIComponent(p);
@@ -123,7 +166,7 @@ function requestCookiesOf(headers) {
123
166
  }
124
167
  return jar;
125
168
  }
126
- function attachCookies(request) {
169
+ function attachCookies(request, basePath = "") {
127
170
  try {
128
171
  const jar = requestCookiesOf(request.headers);
129
172
  Object.defineProperty(request, "cookies", {
@@ -134,12 +177,20 @@ function attachCookies(request) {
134
177
  },
135
178
  enumerable: false,
136
179
  });
180
+ Object.defineProperty(request, "nextUrl", { value: makeNextUrl(request.url, basePath), enumerable: false });
137
181
  }
138
182
  catch {
139
183
  // frozen request objects keep working without the cookies accessor
140
184
  }
141
185
  return request;
142
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
+ }
143
194
  const sleepMicrotask = () => Promise.resolve();
144
195
  const PLATFORMS = {
145
196
  node: { forwardedHostProto: false, clientIP: [] },
@@ -176,6 +227,56 @@ function resolveFlashSecret(option, target) {
176
227
  hex += b.toString(16).padStart(2, "0");
177
228
  return hex;
178
229
  }
230
+ function decodeInlineValue(v) {
231
+ if (Array.isArray(v))
232
+ return v.map(decodeInlineValue);
233
+ if (v && typeof v === "object") {
234
+ const o = v;
235
+ if (typeof o.$ === "string") {
236
+ if (o.$ === "u")
237
+ return undefined;
238
+ if (o.$ === "n")
239
+ return BigInt(o.v);
240
+ if (o.$ === "d")
241
+ return new Date(o.v);
242
+ if (o.$ === "o") {
243
+ const wrapped = {};
244
+ for (const k of Object.keys(o.v))
245
+ wrapped[k] = decodeInlineValue(o.v[k]);
246
+ return wrapped;
247
+ }
248
+ }
249
+ const out = {};
250
+ for (const k of Object.keys(o))
251
+ out[k] = decodeInlineValue(o[k]);
252
+ return out;
253
+ }
254
+ return v;
255
+ }
256
+ /**
257
+ * Opens the closure token of an inline server action: AES-256-GCM over the
258
+ * JSON of the captured values, authenticated against the action id, with the
259
+ * key derived from the action secret (the format the server renderer seals).
260
+ */
261
+ export async function openInlineToken(token, entry, secret) {
262
+ if (typeof token !== "string" || !token.startsWith("k1."))
263
+ throw new Error("missing closure token");
264
+ if (!secret)
265
+ throw new Error("no action encryption key");
266
+ const b64 = token.slice(3).replace(/-/g, "+").replace(/_/g, "/");
267
+ const bin = atob(b64 + "=".repeat((4 - (b64.length % 4)) % 4));
268
+ const raw = Uint8Array.from(bin, (c) => c.charCodeAt(0));
269
+ if (raw.length < 12 + 16)
270
+ throw new Error("truncated closure token");
271
+ const enc = new TextEncoder();
272
+ const digest = await crypto.subtle.digest("SHA-256", enc.encode("krate-inline-action\0" + secret));
273
+ const key = await crypto.subtle.importKey("raw", digest, "AES-GCM", false, ["decrypt"]);
274
+ const plain = await crypto.subtle.decrypt({ name: "AES-GCM", iv: raw.subarray(0, 12), additionalData: enc.encode(entry.id) }, key, raw.subarray(12));
275
+ const values = JSON.parse(new TextDecoder().decode(plain));
276
+ if (!Array.isArray(values) || values.length !== (entry.captures || []).length)
277
+ throw new Error("closure token does not match the action");
278
+ return values.map(decodeInlineValue);
279
+ }
179
280
  // Handler factory
180
281
  export function createKrateHandler(options) {
181
282
  const { data, modules } = options;
@@ -186,10 +287,17 @@ export function createKrateHandler(options) {
186
287
  const trustProxy = options.trustProxy !== undefined ? options.trustProxy : cfg.trustProxy === undefined ? null : cfg.trustProxy;
187
288
  const platform = PLATFORMS[target];
188
289
  const basePath = cfg.basePath || "";
290
+ // Server-rendered <Link>s read the base path from here, as in the browser.
291
+ if (basePath)
292
+ globalThis.__KRATE_CFG__ = { basePath };
189
293
  const hashed = new Set(data.hashedAssets);
190
294
  const staticOnly = new Set(data.staticOnlyRoutes.map(normalizeRoutePattern));
191
295
  const sha256Hex = options.sha256Hex || portableSha256Hex;
192
296
  const flashSecret = resolveFlashSecret(options.flashSecret, target);
297
+ // Inline-action values are sealed with KRATE_ACTION_SECRET; the key is never part of the bundle.
298
+ // A deployed handler never falls back to the build's local key file.
299
+ globalThis[Symbol.for("krate.action.deployed")] = true;
300
+ const actionSecret = globalThis.process?.env?.KRATE_ACTION_SECRET || "";
193
301
  const segEntries = data.segments || [];
194
302
  const segPages = data.segmentPages || {};
195
303
  const segDirByRoute = new Map();
@@ -240,7 +348,7 @@ export function createKrateHandler(options) {
240
348
  let sharedAdapter = null;
241
349
  const instanceId = Math.random().toString(36).slice(2) + Date.now().toString(36);
242
350
  // Pages: most specific route first, like SSRServer.FindPageForRoute.
243
- const pagesBySpecificity = [...data.pages].sort((a, b) => compareRouteSpecificity(a.route, b.route));
351
+ const pagesBySpecificity = data.pages.filter((p) => !p.segment).sort((a, b) => compareRouteSpecificity(a.route, b.route));
244
352
  const manifest = { pages: data.pages, regions: data.regions };
245
353
  const core = createSSRCore({
246
354
  manifest,
@@ -263,7 +371,7 @@ export function createKrateHandler(options) {
263
371
  ppr: cfg.ssr.ppr,
264
372
  pprRevalidate: cfg.ssr.pprRevalidate,
265
373
  background: (p) => {
266
- if (latestWaitUntil)
374
+ if (!platformWaitUntil(p) && latestWaitUntil)
267
375
  latestWaitUntil(p);
268
376
  },
269
377
  });
@@ -348,7 +456,7 @@ export function createKrateHandler(options) {
348
456
  return null;
349
457
  let result;
350
458
  try {
351
- const request = attachCookies(new Request(fullURL(rs), { method: rs.method, headers: new Headers(rs.request.headers) }));
459
+ const request = attachCookies(new Request(fullURL(rs), { method: rs.method, headers: new Headers(rs.request.headers) }), basePath);
352
460
  result = await handler(request);
353
461
  }
354
462
  catch (e) {
@@ -530,7 +638,35 @@ export function createKrateHandler(options) {
530
638
  return staticLayer.isAsset(p);
531
639
  return staticLayer.exists(p);
532
640
  }
641
+ /** trailingSlash: "always" (default) sends /x to /x/, "never" sends /x/ to /x, "ignore" serves both. */
642
+ const slashMode = cfg.trailingSlash || "always";
643
+ /** The /404 and /404.html URLs of the not-found page itself answer 404, never the file or a redirect to it. */
644
+ function notFoundPageURL(p) {
645
+ return p === "/404" || p === "/404/" || p === "/404.html";
646
+ }
647
+ async function answerNotFoundPageURL(rs) {
648
+ const page = errorPage(rs.path, 404);
649
+ if (page)
650
+ return custom404(rs, page);
651
+ return notFoundText(rs, true);
652
+ }
653
+ /** trailingSlash "never": a page URL ending in a slash redirects to the slashless URL. */
654
+ function redirectToSlashless(rs) {
655
+ const p = rs.path;
656
+ if (slashMode !== "never" || p.length < 2 || !p.endsWith("/") || notFoundPageURL(p))
657
+ return null;
658
+ if (rs.method !== "GET" && rs.method !== "HEAD")
659
+ return null;
660
+ const trimmed = p.replace(/\/+$/, "");
661
+ if (trimmed === "" || isFileLikePath(trimmed) || trimmed === "/api" || trimmed.startsWith("/api/") || trimmed.startsWith("/__krate"))
662
+ return null;
663
+ // "../" keeps a segment such as "ftp:3232235777" from parsing as an absolute URL.
664
+ rs.res.set("Location", "../" + baseName(trimmed) + (rs.search || ""));
665
+ return finish(rs, 301, null);
666
+ }
533
667
  function redirectToCanonicalSlash(rs) {
668
+ if (slashMode !== "always")
669
+ return null;
534
670
  const p = rs.path;
535
671
  if (p === "" || p.endsWith("/") || isFileLikePath(p))
536
672
  return null;
@@ -544,7 +680,13 @@ export function createKrateHandler(options) {
544
680
  return finish(rs, 301, null);
545
681
  }
546
682
  /** Answers 404 with a not-found page; segment pages are never cached. */
547
- function custom404(rs, page, status = 404) {
683
+ async function custom404(rs, page, status = 404) {
684
+ if (page.match && page.match.route) {
685
+ // A page that renders per request: the baked file is only its shell.
686
+ const rendered = await renderSegmentPage404(rs, page.match, status);
687
+ if (rendered)
688
+ return rendered;
689
+ }
548
690
  rs.res.set("Content-Type", "text/html; charset=utf-8");
549
691
  rs.res.delete("Cache-Control");
550
692
  rs.res.delete("Etag");
@@ -553,7 +695,7 @@ export function createKrateHandler(options) {
553
695
  return finish(rs, status, page.match ? renderSegmentPage(page.html, page.match) : page.html);
554
696
  }
555
697
  /** The 403 or 401 response of a request whose render called forbidden() or unauthorized(). */
556
- function accessDenied(rs, status, route) {
698
+ async function accessDenied(rs, status, route) {
557
699
  rs.res.delete("X-Krate-Cache");
558
700
  const page = errorPage(rs.path, status, route);
559
701
  if (page)
@@ -566,6 +708,8 @@ export function createKrateHandler(options) {
566
708
  const p = rs.path;
567
709
  if (isInternalOutputPath(p))
568
710
  return notFoundText(rs);
711
+ if (notFoundPageURL(p))
712
+ return answerNotFoundPageURL(rs);
569
713
  if (p.endsWith(".map"))
570
714
  rs.res.set("Content-Type", "application/json; charset=utf-8");
571
715
  rs.res.set("Cache-Control", staticCacheControl(p, hashed));
@@ -590,7 +734,13 @@ export function createKrateHandler(options) {
590
734
  const wantsHTML = isHTMLDocRequest(p) || (rs.headers.get("accept") || "").includes("text/html");
591
735
  // Conditional headers dropped by an outer layer (flash notices) must not reach the file server.
592
736
  const sreq = rs.headers === rs.request.headers ? rs.request : new Request(rs.request.url, { method: rs.request.method, headers: rs.headers });
593
- const served = staticLayer ? await staticLayer.serve(sreq, p) : null;
737
+ let served = staticLayer ? await staticLayer.serve(sreq, p) : null;
738
+ if (staticLayer && served && slashMode !== "always" && !p.endsWith("/") && [301, 302, 307, 308].includes(served.status)) {
739
+ // A layer answers a folder URL with a redirect to its slash form; the other modes serve the index in place.
740
+ const inPlace = await staticLayer.serve(sreq, p + "/");
741
+ if (inPlace && inPlace.status !== 404)
742
+ served = inPlace;
743
+ }
594
744
  if (served && served.status !== 404)
595
745
  return mergeStaticResponse(rs, served);
596
746
  const page404 = wantsHTML ? errorPage(p, 404, { closed: closedPattern }) : null;
@@ -625,6 +775,8 @@ export function createKrateHandler(options) {
625
775
  const denied = pageMethodAllowed(rs);
626
776
  if (denied)
627
777
  return denied;
778
+ if (notFoundPageURL(rs.path))
779
+ return answerNotFoundPageURL(rs);
628
780
  if (data.pages.length === 0)
629
781
  return staticHandler(rs);
630
782
  let route = requestRoute(rs.path);
@@ -664,6 +816,19 @@ export function createKrateHandler(options) {
664
816
  return finish(rs, 200, baked);
665
817
  return staticHandler(rs);
666
818
  }
819
+ /** Renders a segment page that renders per request, with the status of its role. Null: the baked shell answers. */
820
+ async function renderSegmentPage404(rs, m, status) {
821
+ const route = m.route || "";
822
+ const page = data.pages.find((p) => p.route === route);
823
+ const shell = loadShell(route);
824
+ if (!page || !shell || !shell.ok)
825
+ return null;
826
+ rs.res.set("Content-Type", "text/html; charset=utf-8");
827
+ rs.res.set("Cache-Control", "no-store");
828
+ rs.res.delete("Etag");
829
+ rs.res.delete("Last-Modified");
830
+ return servePageRegions(rs, shell, page, route, m.params || {}, queryOf(rs), headerMap(rs), false, 0, false, status);
831
+ }
667
832
  /** Renders the regions of a shell like /__krate/regions does and returns one frame per region. */
668
833
  function startRegionRenders(page, route, shell, renderReq) {
669
834
  const list = shell.all.map((b) => ({
@@ -689,9 +854,10 @@ export function createKrateHandler(options) {
689
854
  }
690
855
  });
691
856
  }
692
- async function servePageRegions(rs, shellInfo, page, route, params, query, headers, isISR, revalidate, outOfOrder) {
857
+ async function servePageRegions(rs, shellInfo, page, route, params, query, headers, isISR, revalidate, outOfOrder, segmentStatus = 0) {
693
858
  let shell = shellInfo.shell;
694
- const renderReq = { route, url: route, method: "GET", headers, params, query };
859
+ // A segment page renders for the URL that missed, not for its own route.
860
+ const renderReq = { route, url: segmentStatus ? rs.path : route, method: "GET", headers, params, query };
695
861
  const pending = startRegionRenders(page, route, shellInfo, renderReq);
696
862
  if (outOfOrder && !isISR && canStreamOutOfOrder(shellInfo.all) && (!page.serverComponents || allSuspense(shellInfo.all))) {
697
863
  return streamSiblingRegions(rs, route, shell, shellInfo, pending);
@@ -758,6 +924,12 @@ export function createKrateHandler(options) {
758
924
  }
759
925
  }
760
926
  }
927
+ // A segment page that failed, or asked for another answer, leaves the response to its baked shell.
928
+ if (segmentStatus && (renderErr || fatalErr || notFound || denied || redirect)) {
929
+ if (renderErr)
930
+ console.error(`[krate] Segment page render error (${route}): ${renderErr}`);
931
+ return null;
932
+ }
761
933
  // A segment error page makes any failed render answer with that page
762
934
  // instead of the baked body (build/serve.go failOnRenderErr).
763
935
  const routeRef = { segDir: page.segDir !== undefined ? page.segDir : "" };
@@ -833,7 +1005,7 @@ export function createKrateHandler(options) {
833
1005
  }
834
1006
  html = mergeHead(html, title, head);
835
1007
  }
836
- return finish(rs, 200, html);
1008
+ return finish(rs, segmentStatus || 200, html);
837
1009
  }
838
1010
  // A <Head> inside a streamed Suspense region renders after the head of the
839
1011
  // response has been sent. It is applied by the region's script instead, which
@@ -881,14 +1053,33 @@ export function createKrateHandler(options) {
881
1053
  return new Response(body, { status: 200, headers: rs.res });
882
1054
  }
883
1055
  // Redirects and rewrites
884
- async function redirectRewriteHandler(rs) {
885
- const p = rs.path;
886
- for (const rd of cfg.redirects) {
1056
+ // Under a base path, basePath: false rules match the full path before the
1057
+ // base is stripped (see handle) and stay out of this list.
1058
+ const insideRedirects = basePath ? cfg.redirects.filter((rd) => rd.basePath !== false) : cfg.redirects;
1059
+ const outsideRedirects = basePath ? cfg.redirects.filter((rd) => rd.basePath === false) : [];
1060
+ function configRedirect(rs, p, rules) {
1061
+ for (const rd of rules) {
887
1062
  if (matchRedirect(p, rd.source)) {
888
1063
  const dest = rewriteDestination(p, rd.source, rd.destination);
889
1064
  return goRedirect(dest, p, rs.method, rd.permanent ? 301 : 302, rs.res);
890
1065
  }
891
1066
  }
1067
+ return null;
1068
+ }
1069
+ /** Prefixes a root-relative Location from inside the base path. */
1070
+ function withBaseLocation(res) {
1071
+ const loc = res.headers.get("location");
1072
+ if (!loc || !loc.startsWith("/") || loc.startsWith("//"))
1073
+ return res;
1074
+ const headers = new Headers(res.headers);
1075
+ headers.set("location", basePath + loc);
1076
+ return new Response(res.body, { status: res.status, statusText: res.statusText, headers });
1077
+ }
1078
+ async function redirectRewriteHandler(rs) {
1079
+ const p = rs.path;
1080
+ const redirected = configRedirect(rs, p, insideRedirects);
1081
+ if (redirected)
1082
+ return redirected;
892
1083
  for (const rw of cfg.rewrites) {
893
1084
  if (matchRedirect(p, rw.source)) {
894
1085
  const rewritten = rewriteDestination(p, rw.source, rw.destination);
@@ -1028,6 +1219,8 @@ export function createKrateHandler(options) {
1028
1219
  }
1029
1220
  if (status === 413)
1030
1221
  return finish(rs, 413, '{"error":"Request Entity Too Large"}');
1222
+ if (status === 504)
1223
+ return finish(rs, 504, '{"error":"Gateway Timeout"}');
1031
1224
  return finish(rs, status < 400 ? 500 : status, '{"error":"Internal Server Error"}');
1032
1225
  }
1033
1226
  function allowList(mod) {
@@ -1259,16 +1452,58 @@ export function createKrateHandler(options) {
1259
1452
  console.error(`[krate] API route ${file} uses the legacy (req, res) handler, which the portable server does not support; export named handlers (GET, POST, ...) that take a Request and return a Response.`);
1260
1453
  return apiFailure(rs, 500);
1261
1454
  }
1455
+ const budgetSec = (data.apiMaxDuration && data.apiMaxDuration[file]) || 0;
1456
+ const abort = budgetSec ? new AbortController() : undefined;
1457
+ let timer;
1262
1458
  try {
1459
+ let signal = rs.request.signal;
1460
+ if (abort) {
1461
+ const upstream = rs.request.signal;
1462
+ if (upstream) {
1463
+ if (upstream.aborted)
1464
+ abort.abort(upstream.reason);
1465
+ else
1466
+ upstream.addEventListener("abort", () => abort.abort(upstream.reason), { once: true });
1467
+ }
1468
+ signal = abort.signal;
1469
+ }
1263
1470
  const request = attachCookies(new Request(fullURL(rs), {
1264
1471
  method: rs.method,
1265
1472
  headers: new Headers(rs.request.headers),
1266
1473
  body: body && body.byteLength > 0 ? body : undefined,
1267
- signal: rs.request.signal,
1268
- }));
1474
+ signal,
1475
+ }), basePath);
1269
1476
  const scope = { kind: "api", paths: [], tags: [] };
1270
- const out = await revalidateStore.run(scope, async () => toResponse(await fn(request, { params: apiRouteParams(file, rs.path) })));
1271
- await flushRevalidate(scope);
1477
+ const work = async () => {
1478
+ const res = await revalidateStore.run(scope, async () => toResponse(await fn(request, { params: apiRouteParams(file, rs.path) })));
1479
+ await flushRevalidate(scope);
1480
+ return res;
1481
+ };
1482
+ let out;
1483
+ if (abort) {
1484
+ const deadline = new Promise((_, reject) => {
1485
+ timer = setTimeout(() => {
1486
+ const err = new Error(`API route exceeded its maxDuration of ${budgetSec}s`);
1487
+ err.krateTimeout = true;
1488
+ reject(err);
1489
+ abort.abort(err);
1490
+ }, budgetSec * 1000);
1491
+ });
1492
+ out = await Promise.race([work(), deadline]);
1493
+ }
1494
+ else {
1495
+ out = await work();
1496
+ }
1497
+ if (scope.after && scope.after.length > 0) {
1498
+ // after() tasks start once this handler has returned the response.
1499
+ const later = new Promise((resolve) => setTimeout(resolve, 0)).then(async () => {
1500
+ await revalidateStore.run(scope, () => runAfterTasks(scope));
1501
+ await flushRevalidate(scope).catch((e) => console.error(`[krate] revalidation after() failed: ${e}`));
1502
+ });
1503
+ const keepAlive = rs.ctx.waitUntil ? rs.ctx.waitUntil.bind(rs.ctx) : latestWaitUntil;
1504
+ if (keepAlive)
1505
+ keepAlive(later);
1506
+ }
1272
1507
  writeHeaderPairs(rs.res, headerPairs(out.headers));
1273
1508
  const status = out.status < 100 || out.status > 999 ? 502 : out.status;
1274
1509
  if (headOnly || rs.method === "HEAD" || !out.body || NO_BODY_STATUS.has(status)) {
@@ -1279,6 +1514,10 @@ export function createKrateHandler(options) {
1279
1514
  return new Response(out.body, { status, headers: rs.res });
1280
1515
  }
1281
1516
  catch (err) {
1517
+ if (err && err.krateTimeout) {
1518
+ console.error(`[krate] ${err.message}: ${rs.method} ${rs.path}`);
1519
+ return apiFailure(rs, 504);
1520
+ }
1282
1521
  // notFound(), forbidden() and unauthorized() end the request with that status.
1283
1522
  const fallback = httpFallbackStatus(err);
1284
1523
  if (fallback === 403 || fallback === 401)
@@ -1291,6 +1530,10 @@ export function createKrateHandler(options) {
1291
1530
  console.error(`[krate] API error (${rs.method} ${rs.path}): ${(err && err.stack) || err}`);
1292
1531
  return apiFailure(rs, 500);
1293
1532
  }
1533
+ finally {
1534
+ if (timer)
1535
+ clearTimeout(timer);
1536
+ }
1294
1537
  }
1295
1538
  // Server actions
1296
1539
  const actionById = new Map(data.actions.map((a) => [a.id, a]));
@@ -1550,6 +1793,23 @@ export function createKrateHandler(options) {
1550
1793
  catch {
1551
1794
  return withHeaders(rs, actionFail(400, "Invalid server action request body"));
1552
1795
  }
1796
+ if (entry.inline && entry.captures && entry.captures.length > 0) {
1797
+ // A hoisted inline action: its closed-over values arrive sealed in a token
1798
+ // (the first leading argument, or the URL query for JSON calls).
1799
+ let token = typeof args[0] === "string" && args[0].startsWith("k1.") ? args.shift() : null;
1800
+ if (!token) {
1801
+ const q = leadingActionArgs(query.get("__krate_args"));
1802
+ if (q && typeof q[0] === "string" && q[0].startsWith("k1."))
1803
+ token = q[0];
1804
+ }
1805
+ try {
1806
+ args.unshift(...(await openInlineToken(token, entry, actionSecret)));
1807
+ }
1808
+ catch (e) {
1809
+ console.error(`[krate] rejected closure data for server action ${entry.source || id}: ${e.message}`);
1810
+ return withHeaders(rs, actionFail(400, "Invalid server action request"));
1811
+ }
1812
+ }
1553
1813
  const ctx = makeActionContext(reqHeaders, id, rs.path);
1554
1814
  const scope = { kind: "action", paths: [], tags: [] };
1555
1815
  let result;
@@ -1690,6 +1950,10 @@ export function createKrateHandler(options) {
1690
1950
  const blocked = await runMiddleware(rs2);
1691
1951
  if (blocked)
1692
1952
  return blocked;
1953
+ // Checked on the requested URL, before a rewrite changes the internal path.
1954
+ const slashless = redirectToSlashless(rs2);
1955
+ if (slashless)
1956
+ return slashless;
1693
1957
  return redirectRewriteHandler(rs2);
1694
1958
  });
1695
1959
  }
@@ -1722,6 +1986,16 @@ export function createKrateHandler(options) {
1722
1986
  return blocked;
1723
1987
  return actionHandler(rs);
1724
1988
  }
1989
+ if (data.metaRoutes && (rs.method === "GET" || rs.method === "HEAD")) {
1990
+ const key = matchMetaRoute(data.metaRoutes, p);
1991
+ if (key) {
1992
+ const blocked = await runMiddleware(rs);
1993
+ if (blocked)
1994
+ return blocked;
1995
+ rs.path = "/api/" + key;
1996
+ return apiHandler(rs);
1997
+ }
1998
+ }
1725
1999
  return pageChain(rs);
1726
2000
  }
1727
2001
  function applySecurityAndHeaders(rs) {
@@ -1779,7 +2053,11 @@ export function createKrateHandler(options) {
1779
2053
  return finish(rs, 204, null);
1780
2054
  return null;
1781
2055
  }
1782
- return async function handle(request, ctx = {}) {
2056
+ return function handle(request, ctx = {}) {
2057
+ // Every page, API route, action and middleware of the request sees the same platform.
2058
+ return runWithPlatform(target, ctx, () => handleRequest(request, ctx));
2059
+ };
2060
+ async function handleRequest(request, ctx) {
1783
2061
  if (ctx.waitUntil)
1784
2062
  latestWaitUntil = ctx.waitUntil.bind(ctx);
1785
2063
  request = sanitizeForwarded(request);
@@ -1797,9 +2075,17 @@ export function createKrateHandler(options) {
1797
2075
  };
1798
2076
  try {
1799
2077
  // Mount under the base path: requests outside it redirect (GET/HEAD) or 404.
2078
+ // The app then sees base-less paths, so a root-relative Location it
2079
+ // answers with gets the base on the way out.
2080
+ let mounted = false;
1800
2081
  if (basePath) {
1801
2082
  const p = rs.path;
1802
2083
  if (!(p.startsWith("/__krate/") || p === "/healthz" || p === "/readyz")) {
2084
+ const outside = configRedirect(rs, p, outsideRedirects);
2085
+ if (outside) {
2086
+ applySecurityAndHeaders(rs);
2087
+ return outside;
2088
+ }
1803
2089
  if (p === basePath || p === basePath + "/")
1804
2090
  rs.path = "/";
1805
2091
  else if (p.startsWith(basePath + "/"))
@@ -1810,14 +2096,18 @@ export function createKrateHandler(options) {
1810
2096
  return goRedirect(basePath + (p.startsWith("/") ? p : "/" + p), p, rs.method, 307, rs.res);
1811
2097
  return notFoundText(rs);
1812
2098
  }
2099
+ mounted = true;
2100
+ if (rs.rawPath.startsWith(basePath))
2101
+ rs.rawPath = rs.rawPath.slice(basePath.length) || "/";
1813
2102
  }
1814
2103
  }
1815
2104
  applySecurityAndHeaders(rs);
1816
2105
  const preflight = applyCORS(rs);
1817
2106
  if (preflight)
1818
- return preflight;
2107
+ return mounted ? withBaseLocation(preflight) : preflight;
1819
2108
  await sleepMicrotask();
1820
- return await mux(rs);
2109
+ const res = await mux(rs);
2110
+ return mounted ? withBaseLocation(res) : res;
1821
2111
  }
1822
2112
  catch (err) {
1823
2113
  console.error(`[krate] panic recovered: ${rs.method} ${rs.path}: ${(err && err.stack) || err}`);
@@ -1827,6 +2117,6 @@ export function createKrateHandler(options) {
1827
2117
  }
1828
2118
  return httpError(rs, "Internal Server Error", 500);
1829
2119
  }
1830
- };
2120
+ }
1831
2121
  }
1832
2122
  export { isDynamicPattern };