@krate/runtime 0.5.0-rc.2 → 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.
- package/dist/actions.d.ts +7 -0
- package/dist/actions.js +21 -3
- package/dist/actions.test.js +8 -410
- package/dist/after.d.ts +28 -0
- package/dist/after.js +48 -0
- package/dist/after.test.js +58 -0
- package/dist/assets-static.d.ts +10 -1
- package/dist/assets-static.js +10 -2
- package/dist/base-path.js +4 -3
- package/dist/builtin-tags.d.ts +12 -0
- package/dist/builtin-tags.js +42 -0
- package/dist/builtin-tags.test.js +12 -0
- package/dist/cache-adapter.test.js +4 -203
- package/dist/cache-scope.d.ts +2 -0
- package/dist/cache.test.js +1 -197
- package/dist/cloudflare-workers.d.ts +2 -0
- package/dist/cloudflare-workers.js +27 -0
- package/dist/dev-overlay.d.ts +54 -3
- package/dist/dev-overlay.js +469 -76
- package/dist/dom.js +3 -1
- package/dist/events.test.js +2 -407
- package/dist/handler-html.test.js +1 -202
- package/dist/handler-routing.js +3 -0
- package/dist/handler-segments.d.ts +6 -0
- package/dist/handler-segments.js +16 -2
- package/dist/handler-segments.test.js +8 -200
- package/dist/head-tags.d.ts +9 -0
- package/dist/head-tags.js +85 -1
- package/dist/head-tags.test.js +18 -125
- package/dist/index.d.ts +1 -5
- package/dist/index.js +3 -0
- package/dist/inline-action-token.test.js +31 -0
- package/dist/jsx-svg-types.test.js +58 -0
- package/dist/jsx-types.d.ts +92 -1
- package/dist/krate-core.js +1 -1
- package/dist/krate-dev.js +384 -65
- package/dist/krate-f-actions.js +1 -1
- package/dist/krate-f-navigation.js +1 -1
- package/dist/krate-f-router-lite.js +1 -1
- package/dist/krate-f-router.js +1 -1
- package/dist/krate-features.json +2 -0
- package/dist/krate-hydrate-lite.js +5 -5
- package/dist/krate-hydrate.js +5 -5
- package/dist/krate-runtime.js +5 -5
- package/dist/link-base-path.test.js +28 -0
- package/dist/node-server.test.js +1 -355
- package/dist/platform.d.ts +52 -0
- package/dist/platform.js +57 -0
- package/dist/platform.test.js +44 -0
- package/dist/router-nav.test.js +15 -444
- package/dist/router.js +39 -1
- package/dist/server-handler.d.ts +48 -0
- package/dist/server-handler.js +272 -16
- package/dist/server-handler.test.js +54 -388
- package/dist/server-renderer.test.js +0 -104
- package/dist/server.d.ts +15 -5
- package/dist/server.js +149 -22
- package/dist/server.test.js +52 -60
- package/dist/site-config.d.ts +13 -0
- package/dist/site-config.js +28 -0
- package/dist/site-config.test.js +30 -0
- package/dist/ssr-core-behavior.test.js +3 -515
- package/dist/testing.d.ts +59 -0
- package/dist/testing.js +88 -0
- package/dist/testing.test.js +73 -0
- package/package.json +9 -1
- package/dist/action-context.test.js +0 -72
- package/dist/base-path.test.js +0 -88
- package/dist/class-component.test.js +0 -462
- package/dist/class-helpers.test.js +0 -169
- package/dist/context.test.js +0 -57
- package/dist/derived.test.js +0 -140
- package/dist/dev-overlay.test.js +0 -165
- package/dist/discrete.test.js +0 -100
- package/dist/dom.test.d.ts +0 -1
- package/dist/dom.test.js +0 -39
- package/dist/effect-errors.test.d.ts +0 -1
- package/dist/effect-errors.test.js +0 -199
- package/dist/effects.test.d.ts +0 -1
- package/dist/effects.test.js +0 -485
- package/dist/handler-routing.test.d.ts +0 -1
- package/dist/handler-routing.test.js +0 -99
- package/dist/highlight-bind.test.d.ts +0 -1
- package/dist/highlight-bind.test.js +0 -124
- package/dist/highlight.test.d.ts +0 -1
- package/dist/highlight.test.js +0 -56
- package/dist/lanes.test.d.ts +0 -1
- package/dist/lanes.test.js +0 -59
- package/dist/list.test.d.ts +0 -1
- package/dist/list.test.js +0 -435
- package/dist/metadata.test.d.ts +0 -1
- package/dist/metadata.test.js +0 -167
- package/dist/navigation.test.d.ts +0 -1
- package/dist/navigation.test.js +0 -130
- package/dist/optimistic-lanes.test.d.ts +0 -1
- package/dist/optimistic-lanes.test.js +0 -45
- package/dist/patterns.test.d.ts +0 -1
- package/dist/patterns.test.js +0 -125
- package/dist/portal.test.d.ts +0 -1
- package/dist/portal.test.js +0 -99
- package/dist/react-effects.test.d.ts +0 -1
- package/dist/react-effects.test.js +0 -133
- package/dist/react-suspense.test.d.ts +0 -1
- package/dist/react-suspense.test.js +0 -194
- package/dist/react.test.d.ts +0 -1
- package/dist/react.test.js +0 -60
- package/dist/react19.test.d.ts +0 -1
- package/dist/react19.test.js +0 -176
- package/dist/reactivity-core.test.d.ts +0 -1
- package/dist/reactivity-core.test.js +0 -152
- package/dist/reconcile.test.d.ts +0 -1
- package/dist/reconcile.test.js +0 -110
- package/dist/refs.test.d.ts +0 -1
- package/dist/refs.test.js +0 -257
- package/dist/router-layout.test.d.ts +0 -1
- package/dist/router-layout.test.js +0 -249
- package/dist/router-slots.test.d.ts +0 -1
- package/dist/router-slots.test.js +0 -144
- package/dist/router-speculation.test.d.ts +0 -1
- package/dist/router-speculation.test.js +0 -25
- package/dist/router-styles.test.d.ts +0 -1
- package/dist/router-styles.test.js +0 -98
- package/dist/router.test.d.ts +0 -1
- package/dist/router.test.js +0 -36
- package/dist/server-async.test.d.ts +0 -1
- package/dist/server-async.test.js +0 -216
- package/dist/server-highlight.test.d.ts +0 -1
- package/dist/server-highlight.test.js +0 -32
- package/dist/signal-lanes.test.d.ts +0 -1
- package/dist/signal-lanes.test.js +0 -32
- package/dist/slots.test.d.ts +0 -1
- package/dist/slots.test.js +0 -187
- package/dist/snapshots.test.d.ts +0 -1
- package/dist/snapshots.test.js +0 -208
- package/dist/ssr-core.test.d.ts +0 -1
- package/dist/ssr-core.test.js +0 -324
- package/dist/static-memory.test.d.ts +0 -1
- package/dist/static-memory.test.js +0 -26
- package/dist/storage.test.d.ts +0 -1
- package/dist/storage.test.js +0 -46
- package/dist/suspense-actions.test.d.ts +0 -1
- package/dist/suspense-actions.test.js +0 -72
- package/dist/suspense.test.d.ts +0 -1
- package/dist/suspense.test.js +0 -556
- /package/dist/{action-context.test.d.ts → after.test.d.ts} +0 -0
- /package/dist/{base-path.test.d.ts → builtin-tags.test.d.ts} +0 -0
- /package/dist/{class-component.test.d.ts → inline-action-token.test.d.ts} +0 -0
- /package/dist/{class-helpers.test.d.ts → jsx-svg-types.test.d.ts} +0 -0
- /package/dist/{context.test.d.ts → link-base-path.test.d.ts} +0 -0
- /package/dist/{derived.test.d.ts → platform.test.d.ts} +0 -0
- /package/dist/{dev-overlay.test.d.ts → site-config.test.d.ts} +0 -0
- /package/dist/{discrete.test.d.ts → testing.test.d.ts} +0 -0
package/dist/server-handler.js
CHANGED
|
@@ -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;
|
|
@@ -193,6 +294,10 @@ export function createKrateHandler(options) {
|
|
|
193
294
|
const staticOnly = new Set(data.staticOnlyRoutes.map(normalizeRoutePattern));
|
|
194
295
|
const sha256Hex = options.sha256Hex || portableSha256Hex;
|
|
195
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 || "";
|
|
196
301
|
const segEntries = data.segments || [];
|
|
197
302
|
const segPages = data.segmentPages || {};
|
|
198
303
|
const segDirByRoute = new Map();
|
|
@@ -243,7 +348,7 @@ export function createKrateHandler(options) {
|
|
|
243
348
|
let sharedAdapter = null;
|
|
244
349
|
const instanceId = Math.random().toString(36).slice(2) + Date.now().toString(36);
|
|
245
350
|
// Pages: most specific route first, like SSRServer.FindPageForRoute.
|
|
246
|
-
const pagesBySpecificity =
|
|
351
|
+
const pagesBySpecificity = data.pages.filter((p) => !p.segment).sort((a, b) => compareRouteSpecificity(a.route, b.route));
|
|
247
352
|
const manifest = { pages: data.pages, regions: data.regions };
|
|
248
353
|
const core = createSSRCore({
|
|
249
354
|
manifest,
|
|
@@ -266,7 +371,7 @@ export function createKrateHandler(options) {
|
|
|
266
371
|
ppr: cfg.ssr.ppr,
|
|
267
372
|
pprRevalidate: cfg.ssr.pprRevalidate,
|
|
268
373
|
background: (p) => {
|
|
269
|
-
if (latestWaitUntil)
|
|
374
|
+
if (!platformWaitUntil(p) && latestWaitUntil)
|
|
270
375
|
latestWaitUntil(p);
|
|
271
376
|
},
|
|
272
377
|
});
|
|
@@ -351,7 +456,7 @@ export function createKrateHandler(options) {
|
|
|
351
456
|
return null;
|
|
352
457
|
let result;
|
|
353
458
|
try {
|
|
354
|
-
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);
|
|
355
460
|
result = await handler(request);
|
|
356
461
|
}
|
|
357
462
|
catch (e) {
|
|
@@ -533,7 +638,35 @@ export function createKrateHandler(options) {
|
|
|
533
638
|
return staticLayer.isAsset(p);
|
|
534
639
|
return staticLayer.exists(p);
|
|
535
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
|
+
}
|
|
536
667
|
function redirectToCanonicalSlash(rs) {
|
|
668
|
+
if (slashMode !== "always")
|
|
669
|
+
return null;
|
|
537
670
|
const p = rs.path;
|
|
538
671
|
if (p === "" || p.endsWith("/") || isFileLikePath(p))
|
|
539
672
|
return null;
|
|
@@ -547,7 +680,13 @@ export function createKrateHandler(options) {
|
|
|
547
680
|
return finish(rs, 301, null);
|
|
548
681
|
}
|
|
549
682
|
/** Answers 404 with a not-found page; segment pages are never cached. */
|
|
550
|
-
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
|
+
}
|
|
551
690
|
rs.res.set("Content-Type", "text/html; charset=utf-8");
|
|
552
691
|
rs.res.delete("Cache-Control");
|
|
553
692
|
rs.res.delete("Etag");
|
|
@@ -556,7 +695,7 @@ export function createKrateHandler(options) {
|
|
|
556
695
|
return finish(rs, status, page.match ? renderSegmentPage(page.html, page.match) : page.html);
|
|
557
696
|
}
|
|
558
697
|
/** The 403 or 401 response of a request whose render called forbidden() or unauthorized(). */
|
|
559
|
-
function accessDenied(rs, status, route) {
|
|
698
|
+
async function accessDenied(rs, status, route) {
|
|
560
699
|
rs.res.delete("X-Krate-Cache");
|
|
561
700
|
const page = errorPage(rs.path, status, route);
|
|
562
701
|
if (page)
|
|
@@ -569,6 +708,8 @@ export function createKrateHandler(options) {
|
|
|
569
708
|
const p = rs.path;
|
|
570
709
|
if (isInternalOutputPath(p))
|
|
571
710
|
return notFoundText(rs);
|
|
711
|
+
if (notFoundPageURL(p))
|
|
712
|
+
return answerNotFoundPageURL(rs);
|
|
572
713
|
if (p.endsWith(".map"))
|
|
573
714
|
rs.res.set("Content-Type", "application/json; charset=utf-8");
|
|
574
715
|
rs.res.set("Cache-Control", staticCacheControl(p, hashed));
|
|
@@ -593,7 +734,13 @@ export function createKrateHandler(options) {
|
|
|
593
734
|
const wantsHTML = isHTMLDocRequest(p) || (rs.headers.get("accept") || "").includes("text/html");
|
|
594
735
|
// Conditional headers dropped by an outer layer (flash notices) must not reach the file server.
|
|
595
736
|
const sreq = rs.headers === rs.request.headers ? rs.request : new Request(rs.request.url, { method: rs.request.method, headers: rs.headers });
|
|
596
|
-
|
|
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
|
+
}
|
|
597
744
|
if (served && served.status !== 404)
|
|
598
745
|
return mergeStaticResponse(rs, served);
|
|
599
746
|
const page404 = wantsHTML ? errorPage(p, 404, { closed: closedPattern }) : null;
|
|
@@ -628,6 +775,8 @@ export function createKrateHandler(options) {
|
|
|
628
775
|
const denied = pageMethodAllowed(rs);
|
|
629
776
|
if (denied)
|
|
630
777
|
return denied;
|
|
778
|
+
if (notFoundPageURL(rs.path))
|
|
779
|
+
return answerNotFoundPageURL(rs);
|
|
631
780
|
if (data.pages.length === 0)
|
|
632
781
|
return staticHandler(rs);
|
|
633
782
|
let route = requestRoute(rs.path);
|
|
@@ -667,6 +816,19 @@ export function createKrateHandler(options) {
|
|
|
667
816
|
return finish(rs, 200, baked);
|
|
668
817
|
return staticHandler(rs);
|
|
669
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
|
+
}
|
|
670
832
|
/** Renders the regions of a shell like /__krate/regions does and returns one frame per region. */
|
|
671
833
|
function startRegionRenders(page, route, shell, renderReq) {
|
|
672
834
|
const list = shell.all.map((b) => ({
|
|
@@ -692,9 +854,10 @@ export function createKrateHandler(options) {
|
|
|
692
854
|
}
|
|
693
855
|
});
|
|
694
856
|
}
|
|
695
|
-
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) {
|
|
696
858
|
let shell = shellInfo.shell;
|
|
697
|
-
|
|
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 };
|
|
698
861
|
const pending = startRegionRenders(page, route, shellInfo, renderReq);
|
|
699
862
|
if (outOfOrder && !isISR && canStreamOutOfOrder(shellInfo.all) && (!page.serverComponents || allSuspense(shellInfo.all))) {
|
|
700
863
|
return streamSiblingRegions(rs, route, shell, shellInfo, pending);
|
|
@@ -761,6 +924,12 @@ export function createKrateHandler(options) {
|
|
|
761
924
|
}
|
|
762
925
|
}
|
|
763
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
|
+
}
|
|
764
933
|
// A segment error page makes any failed render answer with that page
|
|
765
934
|
// instead of the baked body (build/serve.go failOnRenderErr).
|
|
766
935
|
const routeRef = { segDir: page.segDir !== undefined ? page.segDir : "" };
|
|
@@ -836,7 +1005,7 @@ export function createKrateHandler(options) {
|
|
|
836
1005
|
}
|
|
837
1006
|
html = mergeHead(html, title, head);
|
|
838
1007
|
}
|
|
839
|
-
return finish(rs, 200, html);
|
|
1008
|
+
return finish(rs, segmentStatus || 200, html);
|
|
840
1009
|
}
|
|
841
1010
|
// A <Head> inside a streamed Suspense region renders after the head of the
|
|
842
1011
|
// response has been sent. It is applied by the region's script instead, which
|
|
@@ -1050,6 +1219,8 @@ export function createKrateHandler(options) {
|
|
|
1050
1219
|
}
|
|
1051
1220
|
if (status === 413)
|
|
1052
1221
|
return finish(rs, 413, '{"error":"Request Entity Too Large"}');
|
|
1222
|
+
if (status === 504)
|
|
1223
|
+
return finish(rs, 504, '{"error":"Gateway Timeout"}');
|
|
1053
1224
|
return finish(rs, status < 400 ? 500 : status, '{"error":"Internal Server Error"}');
|
|
1054
1225
|
}
|
|
1055
1226
|
function allowList(mod) {
|
|
@@ -1281,16 +1452,58 @@ export function createKrateHandler(options) {
|
|
|
1281
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.`);
|
|
1282
1453
|
return apiFailure(rs, 500);
|
|
1283
1454
|
}
|
|
1455
|
+
const budgetSec = (data.apiMaxDuration && data.apiMaxDuration[file]) || 0;
|
|
1456
|
+
const abort = budgetSec ? new AbortController() : undefined;
|
|
1457
|
+
let timer;
|
|
1284
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
|
+
}
|
|
1285
1470
|
const request = attachCookies(new Request(fullURL(rs), {
|
|
1286
1471
|
method: rs.method,
|
|
1287
1472
|
headers: new Headers(rs.request.headers),
|
|
1288
1473
|
body: body && body.byteLength > 0 ? body : undefined,
|
|
1289
|
-
signal
|
|
1290
|
-
}));
|
|
1474
|
+
signal,
|
|
1475
|
+
}), basePath);
|
|
1291
1476
|
const scope = { kind: "api", paths: [], tags: [] };
|
|
1292
|
-
const
|
|
1293
|
-
|
|
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
|
+
}
|
|
1294
1507
|
writeHeaderPairs(rs.res, headerPairs(out.headers));
|
|
1295
1508
|
const status = out.status < 100 || out.status > 999 ? 502 : out.status;
|
|
1296
1509
|
if (headOnly || rs.method === "HEAD" || !out.body || NO_BODY_STATUS.has(status)) {
|
|
@@ -1301,6 +1514,10 @@ export function createKrateHandler(options) {
|
|
|
1301
1514
|
return new Response(out.body, { status, headers: rs.res });
|
|
1302
1515
|
}
|
|
1303
1516
|
catch (err) {
|
|
1517
|
+
if (err && err.krateTimeout) {
|
|
1518
|
+
console.error(`[krate] ${err.message}: ${rs.method} ${rs.path}`);
|
|
1519
|
+
return apiFailure(rs, 504);
|
|
1520
|
+
}
|
|
1304
1521
|
// notFound(), forbidden() and unauthorized() end the request with that status.
|
|
1305
1522
|
const fallback = httpFallbackStatus(err);
|
|
1306
1523
|
if (fallback === 403 || fallback === 401)
|
|
@@ -1313,6 +1530,10 @@ export function createKrateHandler(options) {
|
|
|
1313
1530
|
console.error(`[krate] API error (${rs.method} ${rs.path}): ${(err && err.stack) || err}`);
|
|
1314
1531
|
return apiFailure(rs, 500);
|
|
1315
1532
|
}
|
|
1533
|
+
finally {
|
|
1534
|
+
if (timer)
|
|
1535
|
+
clearTimeout(timer);
|
|
1536
|
+
}
|
|
1316
1537
|
}
|
|
1317
1538
|
// Server actions
|
|
1318
1539
|
const actionById = new Map(data.actions.map((a) => [a.id, a]));
|
|
@@ -1572,6 +1793,23 @@ export function createKrateHandler(options) {
|
|
|
1572
1793
|
catch {
|
|
1573
1794
|
return withHeaders(rs, actionFail(400, "Invalid server action request body"));
|
|
1574
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
|
+
}
|
|
1575
1813
|
const ctx = makeActionContext(reqHeaders, id, rs.path);
|
|
1576
1814
|
const scope = { kind: "action", paths: [], tags: [] };
|
|
1577
1815
|
let result;
|
|
@@ -1712,6 +1950,10 @@ export function createKrateHandler(options) {
|
|
|
1712
1950
|
const blocked = await runMiddleware(rs2);
|
|
1713
1951
|
if (blocked)
|
|
1714
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;
|
|
1715
1957
|
return redirectRewriteHandler(rs2);
|
|
1716
1958
|
});
|
|
1717
1959
|
}
|
|
@@ -1744,6 +1986,16 @@ export function createKrateHandler(options) {
|
|
|
1744
1986
|
return blocked;
|
|
1745
1987
|
return actionHandler(rs);
|
|
1746
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
|
+
}
|
|
1747
1999
|
return pageChain(rs);
|
|
1748
2000
|
}
|
|
1749
2001
|
function applySecurityAndHeaders(rs) {
|
|
@@ -1801,7 +2053,11 @@ export function createKrateHandler(options) {
|
|
|
1801
2053
|
return finish(rs, 204, null);
|
|
1802
2054
|
return null;
|
|
1803
2055
|
}
|
|
1804
|
-
return
|
|
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) {
|
|
1805
2061
|
if (ctx.waitUntil)
|
|
1806
2062
|
latestWaitUntil = ctx.waitUntil.bind(ctx);
|
|
1807
2063
|
request = sanitizeForwarded(request);
|
|
@@ -1861,6 +2117,6 @@ export function createKrateHandler(options) {
|
|
|
1861
2117
|
}
|
|
1862
2118
|
return httpError(rs, "Internal Server Error", 500);
|
|
1863
2119
|
}
|
|
1864
|
-
}
|
|
2120
|
+
}
|
|
1865
2121
|
}
|
|
1866
2122
|
export { isDynamicPattern };
|