@krate/runtime 0.5.0-beta.3 → 0.5.0-rc.10
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/action-context.js +1 -1
- package/dist/actions.d.ts +7 -0
- package/dist/actions.js +34 -10
- package/dist/after.d.ts +28 -0
- package/dist/after.js +48 -0
- package/dist/assets-static.d.ts +10 -1
- package/dist/assets-static.js +10 -2
- package/dist/base-path.d.ts +7 -0
- package/dist/base-path.js +20 -0
- package/dist/boundary.js +1 -1
- package/dist/builtin-tags.d.ts +12 -0
- package/dist/builtin-tags.js +42 -0
- package/dist/cache-adapter.js +1 -1
- package/dist/cache-scope.d.ts +8 -0
- package/dist/cache-scope.js +14 -1
- package/dist/cloudflare-workers.d.ts +2 -0
- package/dist/cloudflare-workers.js +27 -0
- package/dist/context.d.ts +5 -0
- package/dist/context.js +28 -17
- package/dist/dev-overlay.d.ts +54 -3
- package/dist/dev-overlay.js +496 -91
- package/dist/dom.d.ts +4 -0
- package/dist/dom.js +62 -16
- package/dist/effects.js +43 -10
- package/dist/events.d.ts +2 -0
- package/dist/events.js +18 -0
- package/dist/flight-props.d.ts +7 -0
- package/dist/flight-props.js +105 -0
- package/dist/handler-html.js +4 -4
- package/dist/handler-routing.d.ts +2 -23
- package/dist/handler-routing.js +9 -190
- package/dist/handler-segments.d.ts +6 -0
- package/dist/handler-segments.js +18 -4
- package/dist/head-tags.d.ts +9 -0
- package/dist/head-tags.js +93 -6
- package/dist/highlight-bind.js +1 -1
- package/dist/highlight.d.ts +3 -2
- package/dist/highlight.js +17 -12
- package/dist/hints.d.ts +25 -2
- package/dist/hints.js +147 -74
- package/dist/index.d.ts +2 -0
- package/dist/index.js +3 -0
- package/dist/island-swap.d.ts +47 -0
- package/dist/island-swap.js +635 -0
- package/dist/jsx-dev-runtime.d.ts +1 -1
- package/dist/jsx-types.d.ts +99 -3
- package/dist/krate-core.js +1 -1
- package/dist/krate-dev.js +407 -80
- package/dist/krate-f-actions.js +1 -1
- package/dist/krate-f-classes.js +1 -1
- package/dist/krate-f-highlight.js +1 -1
- package/dist/krate-f-list.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 +455 -0
- package/dist/krate-hydrate-lite.js +5 -5
- package/dist/krate-hydrate.js +5 -5
- package/dist/krate-island-swap.js +1 -0
- package/dist/krate-runtime.js +5 -5
- package/dist/krate-suspense.js +1 -1
- package/dist/list.d.ts +14 -4
- package/dist/list.js +30 -23
- package/dist/metadata.js +5 -2
- package/dist/navigation-react.d.ts +13 -0
- package/dist/navigation-react.js +86 -0
- package/dist/navigation.d.ts +19 -0
- package/dist/navigation.js +35 -0
- package/dist/node-server.js +3 -3
- package/dist/og.js +1 -1
- package/dist/platform.d.ts +52 -0
- package/dist/platform.js +57 -0
- package/dist/react-compat.d.ts +39 -0
- package/dist/react-compat.js +359 -0
- package/dist/react-server.d.ts +63 -0
- package/dist/react-server.js +125 -0
- package/dist/region-wire.d.ts +10 -0
- package/dist/region-wire.js +154 -0
- package/dist/request-context.js +1 -1
- package/dist/request-extras.d.ts +4 -0
- package/dist/request-extras.js +51 -0
- package/dist/resp.js +1 -1
- package/dist/route-source.d.ts +39 -0
- package/dist/route-source.js +532 -0
- package/dist/router-lite.js +3 -9
- package/dist/router.d.ts +1 -1
- package/dist/router.js +675 -100
- package/dist/server-handler.d.ts +69 -1
- package/dist/server-handler.js +515 -96
- package/dist/server-renderer.js +16 -7
- package/dist/server.d.ts +73 -16
- package/dist/server.js +619 -102
- package/dist/sha256.js +9 -9
- package/dist/signal.js +47 -20
- package/dist/site-config.d.ts +15 -0
- package/dist/site-config.js +28 -0
- package/dist/slot.d.ts +12 -0
- package/dist/slot.js +23 -0
- package/dist/ssr-core.d.ts +2 -0
- package/dist/ssr-core.js +12 -4
- package/dist/suspense.js +34 -2
- package/dist/testing.d.ts +62 -0
- package/dist/testing.js +90 -0
- package/dist/use-id.js +1 -1
- package/package.json +28 -3
- package/dist/action-context.test.d.ts +0 -1
- package/dist/action-context.test.js +0 -72
- package/dist/actions.test.d.ts +0 -1
- package/dist/actions.test.js +0 -477
- package/dist/cache-adapter.test.d.ts +0 -1
- package/dist/cache-adapter.test.js +0 -244
- package/dist/cache.test.d.ts +0 -1
- package/dist/cache.test.js +0 -233
- package/dist/class-component.test.d.ts +0 -1
- package/dist/class-component.test.js +0 -462
- package/dist/class-helpers.test.d.ts +0 -1
- package/dist/class-helpers.test.js +0 -169
- package/dist/context.test.d.ts +0 -1
- package/dist/context.test.js +0 -57
- package/dist/derived.test.d.ts +0 -1
- package/dist/derived.test.js +0 -140
- package/dist/dev-overlay.test.d.ts +0 -1
- package/dist/dev-overlay.test.js +0 -152
- package/dist/discrete.test.d.ts +0 -1
- package/dist/discrete.test.js +0 -100
- package/dist/dom.test.d.ts +0 -1
- package/dist/dom.test.js +0 -31
- package/dist/effect-errors.test.d.ts +0 -1
- package/dist/effect-errors.test.js +0 -163
- package/dist/effects.test.d.ts +0 -1
- package/dist/effects.test.js +0 -485
- package/dist/events.test.d.ts +0 -1
- package/dist/events.test.js +0 -447
- package/dist/handler-html.test.d.ts +0 -1
- package/dist/handler-html.test.js +0 -256
- package/dist/handler-routing.test.d.ts +0 -1
- package/dist/handler-routing.test.js +0 -99
- package/dist/handler-segments.test.d.ts +0 -1
- package/dist/handler-segments.test.js +0 -217
- package/dist/head-tags.test.d.ts +0 -1
- package/dist/head-tags.test.js +0 -131
- 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 -344
- 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/node-server.test.d.ts +0 -1
- package/dist/node-server.test.js +0 -492
- 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 -98
- 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 -96
- 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-nav.test.d.ts +0 -1
- package/dist/router-nav.test.js +0 -464
- 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-handler.test.d.ts +0 -1
- package/dist/server-handler.test.js +0 -535
- package/dist/server-highlight.test.d.ts +0 -1
- package/dist/server-highlight.test.js +0 -32
- package/dist/server-renderer.test.d.ts +0 -1
- package/dist/server-renderer.test.js +0 -266
- package/dist/server.test.d.ts +0 -1
- package/dist/server.test.js +0 -88
- package/dist/sha256.test.d.ts +0 -1
- package/dist/sha256.test.js +0 -13
- package/dist/signal-lanes.test.d.ts +0 -1
- package/dist/signal-lanes.test.js +0 -32
- package/dist/signal.test.d.ts +0 -1
- package/dist/signal.test.js +0 -68
- package/dist/slots.test.d.ts +0 -1
- package/dist/slots.test.js +0 -169
- package/dist/snapshots.test.d.ts +0 -1
- package/dist/snapshots.test.js +0 -208
- package/dist/ssr-core-behavior.test.d.ts +0 -1
- package/dist/ssr-core-behavior.test.js +0 -620
- 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 -518
package/dist/server-handler.js
CHANGED
|
@@ -11,16 +11,39 @@
|
|
|
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";
|
|
17
|
-
import { applyDynamicRouteParams, baseName, cleanPath, compareRouteSpecificity, compileMatcher, extName, goRedirect,
|
|
19
|
+
import { applyDynamicRouteParams, baseName, cleanPath, compareRouteSpecificity, compileMatcher, extName, goRedirect, IMMUTABLE_CACHE_CONTROL, isDynamicPattern, isFileLikePath, isHTMLDocRequest, isInternalOutputPath, matchRoutePattern, normalizeRoutePattern, requestRoute, rewriteTargetPath, staticCacheControl, } from "./handler-routing.js";
|
|
20
|
+
import { attachCookies } from "./request-extras.js";
|
|
21
|
+
import { buildDestination, compileMatcher as compileRuleMatcher, mergeRequestQuery } from "./route-source.js";
|
|
18
22
|
import { lookupSegmentPage, newServerError, renderSegmentPage, SEGMENT_KIND_OF_STATUS, } from "./handler-segments.js";
|
|
19
23
|
import { httpFallbackStatus } from "./request-context.js";
|
|
20
24
|
import { sha256Hex as portableSha256Hex } from "./sha256.js";
|
|
21
25
|
import { INVALIDATE_CHANNEL, cacheSpecFromConfig } from "./cache-adapter.js";
|
|
22
26
|
import { isrStoreFor } from "./shared-isr.js";
|
|
23
27
|
import { createMemoryStaticLayer } from "./static-memory.js";
|
|
28
|
+
/** The API route key serving URL path p, or "" when no metadata route does. */
|
|
29
|
+
export function matchMetaRoute(routes, p) {
|
|
30
|
+
for (const r of routes || []) {
|
|
31
|
+
if (r.path) {
|
|
32
|
+
if (p === r.path)
|
|
33
|
+
return r.key;
|
|
34
|
+
continue;
|
|
35
|
+
}
|
|
36
|
+
const prefix = r.prefix || "";
|
|
37
|
+
const suffix = r.suffix || "";
|
|
38
|
+
if (p.length <= prefix.length + suffix.length || !p.startsWith(prefix) || !p.endsWith(suffix))
|
|
39
|
+
continue;
|
|
40
|
+
const id = p.slice(prefix.length, p.length - suffix.length);
|
|
41
|
+
if (/[/\\]/.test(id) || id === "." || id === "..")
|
|
42
|
+
continue;
|
|
43
|
+
return r.key.replace(/\[id\]$/, "") + id;
|
|
44
|
+
}
|
|
45
|
+
return "";
|
|
46
|
+
}
|
|
24
47
|
// Internals
|
|
25
48
|
const NO_BODY_STATUS = new Set([101, 204, 205, 304]);
|
|
26
49
|
const KRATE_METHODS = ["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"];
|
|
@@ -35,6 +58,28 @@ function globalStore(name) {
|
|
|
35
58
|
g[key] = new AsyncLocalStorage();
|
|
36
59
|
return g[key];
|
|
37
60
|
}
|
|
61
|
+
/**
|
|
62
|
+
* Runs fn with the platform of a request (or of a Worker event such as a cron
|
|
63
|
+
* trigger) published to getPlatform() / getCloudflareContext(). The generated
|
|
64
|
+
* Cloudflare Worker wraps the exports of src/cloudflare.ts with it.
|
|
65
|
+
*/
|
|
66
|
+
export function runWithPlatform(target, ctx, fn) {
|
|
67
|
+
const platform = {
|
|
68
|
+
target,
|
|
69
|
+
env: ctx.env && typeof ctx.env === "object" ? ctx.env : {},
|
|
70
|
+
ctx: {
|
|
71
|
+
waitUntil: (work) => {
|
|
72
|
+
if (ctx.waitUntil)
|
|
73
|
+
ctx.waitUntil(work);
|
|
74
|
+
else
|
|
75
|
+
void Promise.resolve(work).catch(() => { });
|
|
76
|
+
},
|
|
77
|
+
passThroughOnException: ctx.passThroughOnException ? () => ctx.passThroughOnException() : undefined,
|
|
78
|
+
},
|
|
79
|
+
cf: ctx.cf,
|
|
80
|
+
};
|
|
81
|
+
return globalStore("krate.platform.store").run(platform, fn);
|
|
82
|
+
}
|
|
38
83
|
function safeDecode(p) {
|
|
39
84
|
try {
|
|
40
85
|
return decodeURIComponent(p);
|
|
@@ -43,6 +88,22 @@ function safeDecode(p) {
|
|
|
43
88
|
return p;
|
|
44
89
|
}
|
|
45
90
|
}
|
|
91
|
+
/**
|
|
92
|
+
* The name/value pairs of a headers rule: an object, or Next's array of
|
|
93
|
+
* { key, value } where a repeated name (any case) keeps its last value.
|
|
94
|
+
*/
|
|
95
|
+
export function ruleHeaderPairs(h) {
|
|
96
|
+
if (!Array.isArray(h))
|
|
97
|
+
return Object.entries(h);
|
|
98
|
+
const out = [];
|
|
99
|
+
for (const { key, value } of h) {
|
|
100
|
+
const at = out.findIndex(([k]) => k.toLowerCase() === String(key).toLowerCase());
|
|
101
|
+
if (at !== -1)
|
|
102
|
+
out.splice(at, 1);
|
|
103
|
+
out.push([String(key), String(value)]);
|
|
104
|
+
}
|
|
105
|
+
return out;
|
|
106
|
+
}
|
|
46
107
|
function textResponse(rs, status, body, contentType = "text/plain; charset=utf-8") {
|
|
47
108
|
rs.res.set("Content-Type", contentType);
|
|
48
109
|
return finish(rs, status, body);
|
|
@@ -100,46 +161,6 @@ function isHTTPSRequest(headers) {
|
|
|
100
161
|
function isStaticAssetPath(p) {
|
|
101
162
|
return STATIC_ASSET_EXTS.has(extName(p).toLowerCase());
|
|
102
163
|
}
|
|
103
|
-
function requestCookiesOf(headers) {
|
|
104
|
-
const jar = new Map();
|
|
105
|
-
for (const part of String(headers.get("cookie") || "").split(";")) {
|
|
106
|
-
const i = part.indexOf("=");
|
|
107
|
-
if (i <= 0)
|
|
108
|
-
continue;
|
|
109
|
-
const name = part.slice(0, i).trim();
|
|
110
|
-
if (!name || jar.has(name))
|
|
111
|
-
continue;
|
|
112
|
-
// Same parsing as the action context and the Node sidecar: unquote, then percent-decode.
|
|
113
|
-
let value = part.slice(i + 1).trim();
|
|
114
|
-
if (value.startsWith('"') && value.endsWith('"'))
|
|
115
|
-
value = value.slice(1, -1);
|
|
116
|
-
try {
|
|
117
|
-
value = decodeURIComponent(value);
|
|
118
|
-
}
|
|
119
|
-
catch {
|
|
120
|
-
// keep the raw value
|
|
121
|
-
}
|
|
122
|
-
jar.set(name, value);
|
|
123
|
-
}
|
|
124
|
-
return jar;
|
|
125
|
-
}
|
|
126
|
-
function attachCookies(request) {
|
|
127
|
-
try {
|
|
128
|
-
const jar = requestCookiesOf(request.headers);
|
|
129
|
-
Object.defineProperty(request, "cookies", {
|
|
130
|
-
value: {
|
|
131
|
-
get: (n) => (jar.has(String(n)) ? { name: String(n), value: jar.get(String(n)) } : undefined),
|
|
132
|
-
getAll: (n) => [...jar].filter(([k]) => n === undefined || k === String(n)).map(([name, value]) => ({ name, value })),
|
|
133
|
-
has: (n) => jar.has(String(n)),
|
|
134
|
-
},
|
|
135
|
-
enumerable: false,
|
|
136
|
-
});
|
|
137
|
-
}
|
|
138
|
-
catch {
|
|
139
|
-
// frozen request objects keep working without the cookies accessor
|
|
140
|
-
}
|
|
141
|
-
return request;
|
|
142
|
-
}
|
|
143
164
|
const sleepMicrotask = () => Promise.resolve();
|
|
144
165
|
const PLATFORMS = {
|
|
145
166
|
node: { forwardedHostProto: false, clientIP: [] },
|
|
@@ -176,6 +197,56 @@ function resolveFlashSecret(option, target) {
|
|
|
176
197
|
hex += b.toString(16).padStart(2, "0");
|
|
177
198
|
return hex;
|
|
178
199
|
}
|
|
200
|
+
function decodeInlineValue(v) {
|
|
201
|
+
if (Array.isArray(v))
|
|
202
|
+
return v.map(decodeInlineValue);
|
|
203
|
+
if (v && typeof v === "object") {
|
|
204
|
+
const o = v;
|
|
205
|
+
if (typeof o.$ === "string") {
|
|
206
|
+
if (o.$ === "u")
|
|
207
|
+
return undefined;
|
|
208
|
+
if (o.$ === "n")
|
|
209
|
+
return BigInt(o.v);
|
|
210
|
+
if (o.$ === "d")
|
|
211
|
+
return new Date(o.v);
|
|
212
|
+
if (o.$ === "o") {
|
|
213
|
+
const wrapped = {};
|
|
214
|
+
for (const k of Object.keys(o.v))
|
|
215
|
+
wrapped[k] = decodeInlineValue(o.v[k]);
|
|
216
|
+
return wrapped;
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
const out = {};
|
|
220
|
+
for (const k of Object.keys(o))
|
|
221
|
+
out[k] = decodeInlineValue(o[k]);
|
|
222
|
+
return out;
|
|
223
|
+
}
|
|
224
|
+
return v;
|
|
225
|
+
}
|
|
226
|
+
/**
|
|
227
|
+
* Opens the closure token of an inline server action: AES-256-GCM over the
|
|
228
|
+
* JSON of the captured values, authenticated against the action id, with the
|
|
229
|
+
* key derived from the action secret (the format the server renderer seals).
|
|
230
|
+
*/
|
|
231
|
+
export async function openInlineToken(token, entry, secret) {
|
|
232
|
+
if (typeof token !== "string" || !token.startsWith("k1."))
|
|
233
|
+
throw new Error("missing closure token");
|
|
234
|
+
if (!secret)
|
|
235
|
+
throw new Error("no action encryption key");
|
|
236
|
+
const b64 = token.slice(3).replace(/-/g, "+").replace(/_/g, "/");
|
|
237
|
+
const bin = atob(b64 + "=".repeat((4 - (b64.length % 4)) % 4));
|
|
238
|
+
const raw = Uint8Array.from(bin, (c) => c.charCodeAt(0));
|
|
239
|
+
if (raw.length < 12 + 16)
|
|
240
|
+
throw new Error("truncated closure token");
|
|
241
|
+
const enc = new TextEncoder();
|
|
242
|
+
const digest = await crypto.subtle.digest("SHA-256", enc.encode("krate-inline-action\0" + secret));
|
|
243
|
+
const key = await crypto.subtle.importKey("raw", digest, "AES-GCM", false, ["decrypt"]);
|
|
244
|
+
const plain = await crypto.subtle.decrypt({ name: "AES-GCM", iv: raw.subarray(0, 12), additionalData: enc.encode(entry.id) }, key, raw.subarray(12));
|
|
245
|
+
const values = JSON.parse(new TextDecoder().decode(plain));
|
|
246
|
+
if (!Array.isArray(values) || values.length !== (entry.captures || []).length)
|
|
247
|
+
throw new Error("closure token does not match the action");
|
|
248
|
+
return values.map(decodeInlineValue);
|
|
249
|
+
}
|
|
179
250
|
// Handler factory
|
|
180
251
|
export function createKrateHandler(options) {
|
|
181
252
|
const { data, modules } = options;
|
|
@@ -186,10 +257,17 @@ export function createKrateHandler(options) {
|
|
|
186
257
|
const trustProxy = options.trustProxy !== undefined ? options.trustProxy : cfg.trustProxy === undefined ? null : cfg.trustProxy;
|
|
187
258
|
const platform = PLATFORMS[target];
|
|
188
259
|
const basePath = cfg.basePath || "";
|
|
260
|
+
// Server-rendered <Link>s read the base path from here, as in the browser.
|
|
261
|
+
if (basePath)
|
|
262
|
+
globalThis.__KRATE_CFG__ = { basePath };
|
|
189
263
|
const hashed = new Set(data.hashedAssets);
|
|
190
264
|
const staticOnly = new Set(data.staticOnlyRoutes.map(normalizeRoutePattern));
|
|
191
265
|
const sha256Hex = options.sha256Hex || portableSha256Hex;
|
|
192
266
|
const flashSecret = resolveFlashSecret(options.flashSecret, target);
|
|
267
|
+
// Inline-action values are sealed with KRATE_ACTION_SECRET; the key is never part of the bundle.
|
|
268
|
+
// A deployed handler never falls back to the build's local key file.
|
|
269
|
+
globalThis[Symbol.for("krate.action.deployed")] = true;
|
|
270
|
+
const actionSecret = globalThis.process?.env?.KRATE_ACTION_SECRET || "";
|
|
193
271
|
const segEntries = data.segments || [];
|
|
194
272
|
const segPages = data.segmentPages || {};
|
|
195
273
|
const segDirByRoute = new Map();
|
|
@@ -240,7 +318,7 @@ export function createKrateHandler(options) {
|
|
|
240
318
|
let sharedAdapter = null;
|
|
241
319
|
const instanceId = Math.random().toString(36).slice(2) + Date.now().toString(36);
|
|
242
320
|
// Pages: most specific route first, like SSRServer.FindPageForRoute.
|
|
243
|
-
const pagesBySpecificity =
|
|
321
|
+
const pagesBySpecificity = data.pages.filter((p) => !p.segment).sort((a, b) => compareRouteSpecificity(a.route, b.route));
|
|
244
322
|
const manifest = { pages: data.pages, regions: data.regions };
|
|
245
323
|
const core = createSSRCore({
|
|
246
324
|
manifest,
|
|
@@ -263,7 +341,7 @@ export function createKrateHandler(options) {
|
|
|
263
341
|
ppr: cfg.ssr.ppr,
|
|
264
342
|
pprRevalidate: cfg.ssr.pprRevalidate,
|
|
265
343
|
background: (p) => {
|
|
266
|
-
if (latestWaitUntil)
|
|
344
|
+
if (!platformWaitUntil(p) && latestWaitUntil)
|
|
267
345
|
latestWaitUntil(p);
|
|
268
346
|
},
|
|
269
347
|
});
|
|
@@ -348,7 +426,7 @@ export function createKrateHandler(options) {
|
|
|
348
426
|
return null;
|
|
349
427
|
let result;
|
|
350
428
|
try {
|
|
351
|
-
const request = attachCookies(new Request(fullURL(rs), { method: rs.method, headers: new Headers(rs.request.headers) }));
|
|
429
|
+
const request = attachCookies(new Request(fullURL(rs), { method: rs.method, headers: new Headers(rs.request.headers) }), basePath);
|
|
352
430
|
result = await handler(request);
|
|
353
431
|
}
|
|
354
432
|
catch (e) {
|
|
@@ -359,15 +437,23 @@ export function createKrateHandler(options) {
|
|
|
359
437
|
let next = false;
|
|
360
438
|
let rewrite = "";
|
|
361
439
|
const hdrs = [];
|
|
440
|
+
let keep = null;
|
|
441
|
+
const vals = new Map();
|
|
362
442
|
for (const [k, v] of headerPairs(result.headers)) {
|
|
363
443
|
if (k === "x-middleware-next")
|
|
364
444
|
next = true;
|
|
365
445
|
else if (k === "x-middleware-rewrite")
|
|
366
446
|
rewrite = v;
|
|
447
|
+
else if (k === "x-middleware-override-headers")
|
|
448
|
+
keep = new Set(v.split(",").map((n) => n.trim().toLowerCase()).filter(Boolean));
|
|
449
|
+
else if (k.startsWith("x-middleware-request-"))
|
|
450
|
+
vals.set(k.slice("x-middleware-request-".length), v);
|
|
367
451
|
else
|
|
368
452
|
hdrs.push([k, v]);
|
|
369
453
|
}
|
|
370
454
|
if (next || rewrite) {
|
|
455
|
+
if (keep)
|
|
456
|
+
overrideRequestHeaders(rs, keep, vals);
|
|
371
457
|
writeHeaderPairs(rs.res, hdrs);
|
|
372
458
|
if (rewrite)
|
|
373
459
|
applyRewrite(rs, rewrite);
|
|
@@ -380,6 +466,23 @@ export function createKrateHandler(options) {
|
|
|
380
466
|
status = 500;
|
|
381
467
|
return finish(rs, status, rs.method === "HEAD" || !body ? null : body);
|
|
382
468
|
}
|
|
469
|
+
/** NextResponse.next({ request: { headers } }): the downstream request keeps only the listed headers, with the given values. */
|
|
470
|
+
function overrideRequestHeaders(rs, keep, vals) {
|
|
471
|
+
const edit = (h) => {
|
|
472
|
+
const out = new Headers();
|
|
473
|
+
h.forEach((v, k) => {
|
|
474
|
+
if (keep.has(k.toLowerCase()))
|
|
475
|
+
out.set(k, v);
|
|
476
|
+
});
|
|
477
|
+
for (const [k, v] of vals)
|
|
478
|
+
if (keep.has(k) && k !== "host")
|
|
479
|
+
out.set(k, v);
|
|
480
|
+
return out;
|
|
481
|
+
};
|
|
482
|
+
const shared = rs.headers === rs.request.headers;
|
|
483
|
+
rs.request = new Request(rs.request, { headers: edit(rs.request.headers) });
|
|
484
|
+
rs.headers = shared ? rs.request.headers : edit(rs.headers);
|
|
485
|
+
}
|
|
383
486
|
function middlewareFailed(rs, err) {
|
|
384
487
|
console.error(`[krate] middleware error: ${rs.method} ${rs.path}: ${(err && err.stack) || err}`);
|
|
385
488
|
// Fail closed: continuing would turn a broken auth check into an unauthenticated request.
|
|
@@ -388,15 +491,15 @@ export function createKrateHandler(options) {
|
|
|
388
491
|
}
|
|
389
492
|
function applyRewrite(rs, target) {
|
|
390
493
|
const i = target.indexOf("://");
|
|
391
|
-
if (i
|
|
494
|
+
if (i !== -1) {
|
|
392
495
|
const rest = target.slice(i + 3);
|
|
393
496
|
const j = rest.indexOf("/");
|
|
394
|
-
target = j
|
|
497
|
+
target = j !== -1 ? rest.slice(j) : "/";
|
|
395
498
|
}
|
|
396
499
|
let p = target;
|
|
397
500
|
let q = "";
|
|
398
501
|
const qi = target.indexOf("?");
|
|
399
|
-
if (qi
|
|
502
|
+
if (qi !== -1) {
|
|
400
503
|
p = target.slice(0, qi);
|
|
401
504
|
q = target.slice(qi + 1);
|
|
402
505
|
}
|
|
@@ -530,7 +633,38 @@ export function createKrateHandler(options) {
|
|
|
530
633
|
return staticLayer.isAsset(p);
|
|
531
634
|
return staticLayer.exists(p);
|
|
532
635
|
}
|
|
636
|
+
/** trailingSlash: "always" (default) sends /x to /x/, "never" sends /x/ to /x, "ignore" serves both. */
|
|
637
|
+
const slashMode = cfg.trailingSlash || "always";
|
|
638
|
+
/** The /404 and /404.html URLs of the not-found page itself answer 404, never the file or a redirect to it. */
|
|
639
|
+
function notFoundPageURL(p) {
|
|
640
|
+
return p === "/404" || p === "/404/" || p === "/404.html";
|
|
641
|
+
}
|
|
642
|
+
async function answerNotFoundPageURL(rs) {
|
|
643
|
+
const page = errorPage(rs.path, 404);
|
|
644
|
+
if (page)
|
|
645
|
+
return custom404(rs, page);
|
|
646
|
+
return notFoundText(rs, true);
|
|
647
|
+
}
|
|
648
|
+
/**
|
|
649
|
+
* trailingSlash "never": a path ending in "/" (pages, files, API routes, any
|
|
650
|
+
* method) gets a 308 to the slashless path before config redirects and
|
|
651
|
+
* middleware, as in Next (mirrors slashlessTarget in serve_pages.go). The
|
|
652
|
+
* not-found page's URLs and internal routes are left alone.
|
|
653
|
+
*/
|
|
654
|
+
function redirectToSlashless(rs) {
|
|
655
|
+
const p = rs.path;
|
|
656
|
+
if (slashMode !== "never" || p.length < 2 || !p.endsWith("/") || p.startsWith("/__krate") || p === "/healthz" || p === "/readyz" || notFoundPageURL(p))
|
|
657
|
+
return null;
|
|
658
|
+
// "//evil.example/" must not become a scheme-relative Location.
|
|
659
|
+
const target = "/" + rs.rawPath.replace(/\/+$/, "").replace(/^[/\\]+/, "");
|
|
660
|
+
if (target === "/")
|
|
661
|
+
return null;
|
|
662
|
+
rs.res.set("Location", target + (rs.search || ""));
|
|
663
|
+
return finish(rs, 308, null);
|
|
664
|
+
}
|
|
533
665
|
function redirectToCanonicalSlash(rs) {
|
|
666
|
+
if (slashMode !== "always")
|
|
667
|
+
return null;
|
|
534
668
|
const p = rs.path;
|
|
535
669
|
if (p === "" || p.endsWith("/") || isFileLikePath(p))
|
|
536
670
|
return null;
|
|
@@ -544,7 +678,13 @@ export function createKrateHandler(options) {
|
|
|
544
678
|
return finish(rs, 301, null);
|
|
545
679
|
}
|
|
546
680
|
/** Answers 404 with a not-found page; segment pages are never cached. */
|
|
547
|
-
function custom404(rs, page, status = 404) {
|
|
681
|
+
async function custom404(rs, page, status = 404) {
|
|
682
|
+
if (page.match && page.match.route) {
|
|
683
|
+
// A page that renders per request: the baked file is only its shell.
|
|
684
|
+
const rendered = await renderSegmentPage404(rs, page.match, status);
|
|
685
|
+
if (rendered)
|
|
686
|
+
return rendered;
|
|
687
|
+
}
|
|
548
688
|
rs.res.set("Content-Type", "text/html; charset=utf-8");
|
|
549
689
|
rs.res.delete("Cache-Control");
|
|
550
690
|
rs.res.delete("Etag");
|
|
@@ -553,7 +693,7 @@ export function createKrateHandler(options) {
|
|
|
553
693
|
return finish(rs, status, page.match ? renderSegmentPage(page.html, page.match) : page.html);
|
|
554
694
|
}
|
|
555
695
|
/** The 403 or 401 response of a request whose render called forbidden() or unauthorized(). */
|
|
556
|
-
function accessDenied(rs, status, route) {
|
|
696
|
+
async function accessDenied(rs, status, route) {
|
|
557
697
|
rs.res.delete("X-Krate-Cache");
|
|
558
698
|
const page = errorPage(rs.path, status, route);
|
|
559
699
|
if (page)
|
|
@@ -566,9 +706,13 @@ export function createKrateHandler(options) {
|
|
|
566
706
|
const p = rs.path;
|
|
567
707
|
if (isInternalOutputPath(p))
|
|
568
708
|
return notFoundText(rs);
|
|
709
|
+
if (notFoundPageURL(p))
|
|
710
|
+
return answerNotFoundPageURL(rs);
|
|
569
711
|
if (p.endsWith(".map"))
|
|
570
712
|
rs.res.set("Content-Type", "application/json; charset=utf-8");
|
|
571
|
-
|
|
713
|
+
// A Cache-Control from a headers rule wins (public/ files cached longer).
|
|
714
|
+
if (!rs.res.has("Cache-Control"))
|
|
715
|
+
rs.res.set("Cache-Control", staticCacheControl(p, hashed));
|
|
572
716
|
let closedPattern = "";
|
|
573
717
|
if (!(await staticRouteExists(p))) {
|
|
574
718
|
for (const t of templates) {
|
|
@@ -587,12 +731,24 @@ export function createKrateHandler(options) {
|
|
|
587
731
|
}
|
|
588
732
|
}
|
|
589
733
|
}
|
|
590
|
-
const wantsHTML = isHTMLDocRequest(p) || (rs.headers.get("accept") || "").includes("text/html");
|
|
734
|
+
const wantsHTML = isHTMLDocRequest(p) || extName(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
|
-
|
|
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);
|
|
746
|
+
// An unknown URL follows the same slash rule as a page, then answers 404 at its canonical form.
|
|
747
|
+
if (p !== "/api" && !p.startsWith("/api/") && !p.startsWith("/__krate") && !p.split("/").some((seg) => seg.startsWith("."))) {
|
|
748
|
+
const slash = redirectToCanonicalSlash(rs);
|
|
749
|
+
if (slash)
|
|
750
|
+
return slash;
|
|
751
|
+
}
|
|
596
752
|
const page404 = wantsHTML ? errorPage(p, 404, { closed: closedPattern }) : null;
|
|
597
753
|
if (page404)
|
|
598
754
|
return custom404(rs, page404);
|
|
@@ -625,6 +781,8 @@ export function createKrateHandler(options) {
|
|
|
625
781
|
const denied = pageMethodAllowed(rs);
|
|
626
782
|
if (denied)
|
|
627
783
|
return denied;
|
|
784
|
+
if (notFoundPageURL(rs.path))
|
|
785
|
+
return answerNotFoundPageURL(rs);
|
|
628
786
|
if (data.pages.length === 0)
|
|
629
787
|
return staticHandler(rs);
|
|
630
788
|
let route = requestRoute(rs.path);
|
|
@@ -645,7 +803,8 @@ export function createKrateHandler(options) {
|
|
|
645
803
|
const query = queryOf(rs);
|
|
646
804
|
rs.res.set("Content-Type", "text/html; charset=utf-8");
|
|
647
805
|
rs.res.set("X-Content-Type-Options", "nosniff");
|
|
648
|
-
|
|
806
|
+
// A Cache-Control that middleware or a headers rule already set wins over the default.
|
|
807
|
+
if (!isISR && !rs.res.has("Cache-Control"))
|
|
649
808
|
rs.res.set("Cache-Control", "no-store");
|
|
650
809
|
let reval = 0;
|
|
651
810
|
if (isISR) {
|
|
@@ -664,6 +823,19 @@ export function createKrateHandler(options) {
|
|
|
664
823
|
return finish(rs, 200, baked);
|
|
665
824
|
return staticHandler(rs);
|
|
666
825
|
}
|
|
826
|
+
/** Renders a segment page that renders per request, with the status of its role. Null: the baked shell answers. */
|
|
827
|
+
async function renderSegmentPage404(rs, m, status) {
|
|
828
|
+
const route = m.route || "";
|
|
829
|
+
const page = data.pages.find((p) => p.route === route);
|
|
830
|
+
const shell = loadShell(route);
|
|
831
|
+
if (!page || !shell || !shell.ok)
|
|
832
|
+
return null;
|
|
833
|
+
rs.res.set("Content-Type", "text/html; charset=utf-8");
|
|
834
|
+
rs.res.set("Cache-Control", "no-store");
|
|
835
|
+
rs.res.delete("Etag");
|
|
836
|
+
rs.res.delete("Last-Modified");
|
|
837
|
+
return servePageRegions(rs, shell, page, route, m.params || {}, queryOf(rs), headerMap(rs), false, 0, false, status);
|
|
838
|
+
}
|
|
667
839
|
/** Renders the regions of a shell like /__krate/regions does and returns one frame per region. */
|
|
668
840
|
function startRegionRenders(page, route, shell, renderReq) {
|
|
669
841
|
const list = shell.all.map((b) => ({
|
|
@@ -689,9 +861,10 @@ export function createKrateHandler(options) {
|
|
|
689
861
|
}
|
|
690
862
|
});
|
|
691
863
|
}
|
|
692
|
-
async function servePageRegions(rs, shellInfo, page, route, params, query, headers, isISR, revalidate, outOfOrder) {
|
|
693
|
-
|
|
694
|
-
|
|
864
|
+
async function servePageRegions(rs, shellInfo, page, route, params, query, headers, isISR, revalidate, outOfOrder, segmentStatus = 0) {
|
|
865
|
+
const shell = shellInfo.shell;
|
|
866
|
+
// A segment page renders for the URL that missed, not for its own route.
|
|
867
|
+
const renderReq = { route, url: segmentStatus ? rs.path : route, method: "GET", headers, params, query };
|
|
695
868
|
const pending = startRegionRenders(page, route, shellInfo, renderReq);
|
|
696
869
|
if (outOfOrder && !isISR && canStreamOutOfOrder(shellInfo.all) && (!page.serverComponents || allSuspense(shellInfo.all))) {
|
|
697
870
|
return streamSiblingRegions(rs, route, shell, shellInfo, pending);
|
|
@@ -710,6 +883,7 @@ export function createKrateHandler(options) {
|
|
|
710
883
|
let errStack = "";
|
|
711
884
|
let errDigest = "";
|
|
712
885
|
let noStore = false;
|
|
886
|
+
let errorCaught = false;
|
|
713
887
|
for (const frame of await Promise.all(pending)) {
|
|
714
888
|
switch (frame.type) {
|
|
715
889
|
case "region": {
|
|
@@ -723,6 +897,8 @@ export function createKrateHandler(options) {
|
|
|
723
897
|
}
|
|
724
898
|
if (frame.noStore)
|
|
725
899
|
noStore = true;
|
|
900
|
+
if (frame.errorCaught)
|
|
901
|
+
errorCaught = true;
|
|
726
902
|
if (id === "page") {
|
|
727
903
|
isISRFrame = !!frame.cacheStatus;
|
|
728
904
|
cacheStatus = frame.cacheStatus || "";
|
|
@@ -758,6 +934,12 @@ export function createKrateHandler(options) {
|
|
|
758
934
|
}
|
|
759
935
|
}
|
|
760
936
|
}
|
|
937
|
+
// A segment page that failed, or asked for another answer, leaves the response to its baked shell.
|
|
938
|
+
if (segmentStatus && (renderErr || fatalErr || notFound || denied || redirect)) {
|
|
939
|
+
if (renderErr)
|
|
940
|
+
console.error(`[krate] Segment page render error (${route}): ${renderErr}`);
|
|
941
|
+
return null;
|
|
942
|
+
}
|
|
761
943
|
// A segment error page makes any failed render answer with that page
|
|
762
944
|
// instead of the baked body (build/serve.go failOnRenderErr).
|
|
763
945
|
const routeRef = { segDir: page.segDir !== undefined ? page.segDir : "" };
|
|
@@ -795,12 +977,19 @@ export function createKrateHandler(options) {
|
|
|
795
977
|
}
|
|
796
978
|
if (isISR && isISRFrame && cacheStatus)
|
|
797
979
|
rs.res.set("X-Krate-Cache", cacheStatus.toUpperCase());
|
|
798
|
-
if (
|
|
980
|
+
if (errorCaught) {
|
|
981
|
+
// The fallback is an error response: no CDN may keep it, whatever cache
|
|
982
|
+
// headers the route or middleware set.
|
|
983
|
+
rs.res.set("X-Krate-Error", "render");
|
|
984
|
+
rs.res.delete("X-Krate-Cache");
|
|
985
|
+
rs.res.set("Cache-Control", "no-store");
|
|
986
|
+
}
|
|
987
|
+
else if (isISR) {
|
|
799
988
|
if (noStore || renderErr) {
|
|
800
989
|
rs.res.set("Cache-Control", "private, no-store");
|
|
801
990
|
rs.res.delete("X-Krate-Cache");
|
|
802
991
|
}
|
|
803
|
-
else {
|
|
992
|
+
else if (!rs.res.has("Cache-Control")) {
|
|
804
993
|
const r = revalidate > 0 ? revalidate : 60;
|
|
805
994
|
rs.res.set("Cache-Control", `public, s-maxage=${r}, stale-while-revalidate=${2 * r}`);
|
|
806
995
|
}
|
|
@@ -833,7 +1022,7 @@ export function createKrateHandler(options) {
|
|
|
833
1022
|
}
|
|
834
1023
|
html = mergeHead(html, title, head);
|
|
835
1024
|
}
|
|
836
|
-
return finish(rs, 200, html);
|
|
1025
|
+
return finish(rs, errorCaught ? 500 : segmentStatus || 200, html);
|
|
837
1026
|
}
|
|
838
1027
|
// A <Head> inside a streamed Suspense region renders after the head of the
|
|
839
1028
|
// response has been sent. It is applied by the region's script instead, which
|
|
@@ -880,22 +1069,75 @@ export function createKrateHandler(options) {
|
|
|
880
1069
|
return new Response(null, { status: 200, headers: rs.res });
|
|
881
1070
|
return new Response(body, { status: 200, headers: rs.res });
|
|
882
1071
|
}
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
const
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
1072
|
+
function compileRules(rules, kind) {
|
|
1073
|
+
const out = [];
|
|
1074
|
+
for (const rule of rules) {
|
|
1075
|
+
try {
|
|
1076
|
+
out.push({ rule, matcher: compileRuleMatcher(rule.source, kind, rule.has, rule.missing) });
|
|
1077
|
+
}
|
|
1078
|
+
catch (err) {
|
|
1079
|
+
console.error(`[krate] skipped ${kind} rule ${JSON.stringify(rule.source)}: ${err.message}`);
|
|
1080
|
+
}
|
|
1081
|
+
}
|
|
1082
|
+
return out;
|
|
1083
|
+
}
|
|
1084
|
+
const insideRedirects = compileRules(basePath ? cfg.redirects.filter((rd) => rd.basePath !== false) : cfg.redirects, "redirect");
|
|
1085
|
+
const outsideRedirects = compileRules(basePath ? cfg.redirects.filter((rd) => rd.basePath === false) : [], "redirect");
|
|
1086
|
+
const rewriteRules = compileRules(cfg.rewrites, "rewrite");
|
|
1087
|
+
const headerRules = compileRules(cfg.headers, "header");
|
|
1088
|
+
function condRequest(rs) {
|
|
1089
|
+
return { headers: rs.headers, url: new URL(rs.request.url) };
|
|
1090
|
+
}
|
|
1091
|
+
/** Answers the first redirect whose source and conditions match; the request query is carried over. */
|
|
1092
|
+
function configRedirect(rs, p, rules) {
|
|
1093
|
+
if (!rules.length)
|
|
1094
|
+
return null;
|
|
1095
|
+
const creq = condRequest(rs);
|
|
1096
|
+
for (const { rule, matcher } of rules) {
|
|
1097
|
+
const m = matcher.match(p, creq);
|
|
1098
|
+
if (m) {
|
|
1099
|
+
const dest = mergeRequestQuery(buildDestination(rule.destination, m), rs.search);
|
|
1100
|
+
const status = rule.statusCode || (rule.permanent ? 301 : 302);
|
|
1101
|
+
return goRedirect(dest, p, rs.method, status, rs.res);
|
|
890
1102
|
}
|
|
891
1103
|
}
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
1104
|
+
return null;
|
|
1105
|
+
}
|
|
1106
|
+
/** Prefixes a root-relative Location from inside the base path. */
|
|
1107
|
+
function withBaseLocation(res) {
|
|
1108
|
+
const loc = res.headers.get("location");
|
|
1109
|
+
if (!loc || !loc.startsWith("/") || loc.startsWith("//"))
|
|
1110
|
+
return res;
|
|
1111
|
+
const headers = new Headers(res.headers);
|
|
1112
|
+
headers.set("location", basePath + loc);
|
|
1113
|
+
return new Response(res.body, { status: res.status, statusText: res.statusText, headers });
|
|
1114
|
+
}
|
|
1115
|
+
async function redirectRewriteHandler(rs) {
|
|
1116
|
+
const p = rs.path;
|
|
1117
|
+
if (rewriteRules.length) {
|
|
1118
|
+
const creq = condRequest(rs);
|
|
1119
|
+
for (const { rule, matcher } of rewriteRules) {
|
|
1120
|
+
const m = matcher.match(p, creq);
|
|
1121
|
+
if (!m)
|
|
1122
|
+
continue;
|
|
1123
|
+
let rewritten = buildDestination(rule.destination, m);
|
|
1124
|
+
let rewrittenQuery = "";
|
|
1125
|
+
const q = rewritten.indexOf("?");
|
|
1126
|
+
if (q !== -1) {
|
|
1127
|
+
rewrittenQuery = rewritten.slice(q);
|
|
1128
|
+
rewritten = rewritten.slice(0, q);
|
|
1129
|
+
}
|
|
895
1130
|
rs.path = rewriteTargetPath(safeDecode(rewritten));
|
|
1131
|
+
if (rewrittenQuery) {
|
|
1132
|
+
const merged = mergeRequestQuery(rewrittenQuery, rs.search);
|
|
1133
|
+
rs.search = merged === "?" ? "" : merged;
|
|
1134
|
+
}
|
|
896
1135
|
break;
|
|
897
1136
|
}
|
|
898
1137
|
}
|
|
1138
|
+
// A rewrite onto an API route is answered by the API handler (mux sent this request down the page chain).
|
|
1139
|
+
if (rs.path === "/api" || rs.path.startsWith("/api/"))
|
|
1140
|
+
return apiHandler(rs);
|
|
899
1141
|
return pageHandler(rs);
|
|
900
1142
|
}
|
|
901
1143
|
// API routes
|
|
@@ -922,12 +1164,15 @@ export function createKrateHandler(options) {
|
|
|
922
1164
|
continue;
|
|
923
1165
|
const rest = k.slice(prefix.length);
|
|
924
1166
|
const i = rest.indexOf("/");
|
|
925
|
-
|
|
926
|
-
|
|
1167
|
+
// A name can be both a route file and a directory ([id].ts next to [id]/download.ts).
|
|
1168
|
+
if (i === -1)
|
|
1169
|
+
out.set(rest + "\0f", false);
|
|
927
1170
|
else
|
|
928
|
-
out.set(rest.slice(0, i), true);
|
|
1171
|
+
out.set(rest.slice(0, i) + "\0d", true);
|
|
929
1172
|
}
|
|
930
|
-
return [...out
|
|
1173
|
+
return [...out.keys()]
|
|
1174
|
+
.sort(strCmp)
|
|
1175
|
+
.map((k) => ({ name: k.slice(0, -2), isDir: out.get(k) }));
|
|
931
1176
|
}
|
|
932
1177
|
function strCmp(a, b) {
|
|
933
1178
|
return a < b ? -1 : a > b ? 1 : 0;
|
|
@@ -940,6 +1185,9 @@ export function createKrateHandler(options) {
|
|
|
940
1185
|
const idx = join(dir, "index");
|
|
941
1186
|
return apiKeys.has(idx) ? idx : "";
|
|
942
1187
|
}
|
|
1188
|
+
// A static leaf wins over dynamic siblings at every depth.
|
|
1189
|
+
if (segs.length === 1 && apiKeys.has(join(dir, segs[0])))
|
|
1190
|
+
return join(dir, segs[0]);
|
|
943
1191
|
const next = join(dir, segs[0]);
|
|
944
1192
|
if (apiDirs.has(next)) {
|
|
945
1193
|
const hit = resolveDynamicAPIDir(next, segs.slice(1));
|
|
@@ -1009,10 +1257,6 @@ export function createKrateHandler(options) {
|
|
|
1009
1257
|
}
|
|
1010
1258
|
return params;
|
|
1011
1259
|
}
|
|
1012
|
-
function jsonResponse(rs, status, obj) {
|
|
1013
|
-
rs.res.set("Content-Type", "application/json");
|
|
1014
|
-
return finish(rs, status, JSON.stringify(obj));
|
|
1015
|
-
}
|
|
1016
1260
|
function apiFailure(rs, status, allow) {
|
|
1017
1261
|
rs.res.set("Content-Type", "application/json");
|
|
1018
1262
|
rs.res.set("Cache-Control", "no-store");
|
|
@@ -1028,6 +1272,8 @@ export function createKrateHandler(options) {
|
|
|
1028
1272
|
}
|
|
1029
1273
|
if (status === 413)
|
|
1030
1274
|
return finish(rs, 413, '{"error":"Request Entity Too Large"}');
|
|
1275
|
+
if (status === 504)
|
|
1276
|
+
return finish(rs, 504, '{"error":"Gateway Timeout"}');
|
|
1031
1277
|
return finish(rs, status < 400 ? 500 : status, '{"error":"Internal Server Error"}');
|
|
1032
1278
|
}
|
|
1033
1279
|
function allowList(mod) {
|
|
@@ -1259,16 +1505,58 @@ export function createKrateHandler(options) {
|
|
|
1259
1505
|
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
1506
|
return apiFailure(rs, 500);
|
|
1261
1507
|
}
|
|
1508
|
+
const budgetSec = (data.apiMaxDuration && data.apiMaxDuration[file]) || 0;
|
|
1509
|
+
const abort = budgetSec ? new AbortController() : undefined;
|
|
1510
|
+
let timer;
|
|
1262
1511
|
try {
|
|
1512
|
+
let signal = rs.request.signal;
|
|
1513
|
+
if (abort) {
|
|
1514
|
+
const upstream = rs.request.signal;
|
|
1515
|
+
if (upstream) {
|
|
1516
|
+
if (upstream.aborted)
|
|
1517
|
+
abort.abort(upstream.reason);
|
|
1518
|
+
else
|
|
1519
|
+
upstream.addEventListener("abort", () => abort.abort(upstream.reason), { once: true });
|
|
1520
|
+
}
|
|
1521
|
+
signal = abort.signal;
|
|
1522
|
+
}
|
|
1263
1523
|
const request = attachCookies(new Request(fullURL(rs), {
|
|
1264
1524
|
method: rs.method,
|
|
1265
1525
|
headers: new Headers(rs.request.headers),
|
|
1266
1526
|
body: body && body.byteLength > 0 ? body : undefined,
|
|
1267
|
-
signal
|
|
1268
|
-
}));
|
|
1527
|
+
signal,
|
|
1528
|
+
}), basePath);
|
|
1269
1529
|
const scope = { kind: "api", paths: [], tags: [] };
|
|
1270
|
-
const
|
|
1271
|
-
|
|
1530
|
+
const work = async () => {
|
|
1531
|
+
const res = await revalidateStore.run(scope, () => runRoute(request, async () => toResponse(await fn(request, { params: apiRouteParams(file, rs.path) }))));
|
|
1532
|
+
await flushRevalidate(scope);
|
|
1533
|
+
return res;
|
|
1534
|
+
};
|
|
1535
|
+
let out;
|
|
1536
|
+
if (abort) {
|
|
1537
|
+
const deadline = new Promise((_, reject) => {
|
|
1538
|
+
timer = setTimeout(() => {
|
|
1539
|
+
const err = new Error(`API route exceeded its maxDuration of ${budgetSec}s`);
|
|
1540
|
+
err.krateTimeout = true;
|
|
1541
|
+
reject(err);
|
|
1542
|
+
abort.abort(err);
|
|
1543
|
+
}, budgetSec * 1000);
|
|
1544
|
+
});
|
|
1545
|
+
out = await Promise.race([work(), deadline]);
|
|
1546
|
+
}
|
|
1547
|
+
else {
|
|
1548
|
+
out = await work();
|
|
1549
|
+
}
|
|
1550
|
+
if (scope.after && scope.after.length > 0) {
|
|
1551
|
+
// after() tasks start once this handler has returned the response.
|
|
1552
|
+
const later = new Promise((resolve) => setTimeout(resolve, 0)).then(async () => {
|
|
1553
|
+
await revalidateStore.run(scope, () => runAfterTasks(scope));
|
|
1554
|
+
await flushRevalidate(scope).catch((e) => console.error(`[krate] revalidation after() failed: ${e}`));
|
|
1555
|
+
});
|
|
1556
|
+
const keepAlive = rs.ctx.waitUntil ? rs.ctx.waitUntil.bind(rs.ctx) : latestWaitUntil;
|
|
1557
|
+
if (keepAlive)
|
|
1558
|
+
keepAlive(later);
|
|
1559
|
+
}
|
|
1272
1560
|
writeHeaderPairs(rs.res, headerPairs(out.headers));
|
|
1273
1561
|
const status = out.status < 100 || out.status > 999 ? 502 : out.status;
|
|
1274
1562
|
if (headOnly || rs.method === "HEAD" || !out.body || NO_BODY_STATUS.has(status)) {
|
|
@@ -1279,6 +1567,10 @@ export function createKrateHandler(options) {
|
|
|
1279
1567
|
return new Response(out.body, { status, headers: rs.res });
|
|
1280
1568
|
}
|
|
1281
1569
|
catch (err) {
|
|
1570
|
+
if (err && err.krateTimeout) {
|
|
1571
|
+
console.error(`[krate] ${err.message}: ${rs.method} ${rs.path}`);
|
|
1572
|
+
return apiFailure(rs, 504);
|
|
1573
|
+
}
|
|
1282
1574
|
// notFound(), forbidden() and unauthorized() end the request with that status.
|
|
1283
1575
|
const fallback = httpFallbackStatus(err);
|
|
1284
1576
|
if (fallback === 403 || fallback === 401)
|
|
@@ -1291,6 +1583,10 @@ export function createKrateHandler(options) {
|
|
|
1291
1583
|
console.error(`[krate] API error (${rs.method} ${rs.path}): ${(err && err.stack) || err}`);
|
|
1292
1584
|
return apiFailure(rs, 500);
|
|
1293
1585
|
}
|
|
1586
|
+
finally {
|
|
1587
|
+
if (timer)
|
|
1588
|
+
clearTimeout(timer);
|
|
1589
|
+
}
|
|
1294
1590
|
}
|
|
1295
1591
|
// Server actions
|
|
1296
1592
|
const actionById = new Map(data.actions.map((a) => [a.id, a]));
|
|
@@ -1369,21 +1665,58 @@ export function createKrateHandler(options) {
|
|
|
1369
1665
|
};
|
|
1370
1666
|
return { actionId: id, url: urlPath, method: "POST", headers, cookies, setCookies };
|
|
1371
1667
|
}
|
|
1668
|
+
// Runs an API route inside the action store so headers(), cookies() and
|
|
1669
|
+
// redirect() work in it like in a server action: cookies it sets are added to
|
|
1670
|
+
// the response and a redirect() signal becomes a 307.
|
|
1671
|
+
async function runRoute(request, run) {
|
|
1672
|
+
const ctx = makeActionContext(request.headers, "", new URL(request.url).pathname);
|
|
1673
|
+
ctx.method = request.method;
|
|
1674
|
+
let out;
|
|
1675
|
+
try {
|
|
1676
|
+
out = await actionStore.run(ctx, run);
|
|
1677
|
+
}
|
|
1678
|
+
catch (e) {
|
|
1679
|
+
if (!e || typeof e.__krateRedirect !== "string")
|
|
1680
|
+
throw e;
|
|
1681
|
+
out = new Response(null, { status: 307, headers: { location: e.__krateRedirect, "cache-control": "no-store" } });
|
|
1682
|
+
}
|
|
1683
|
+
if (ctx.setCookies.length > 0) {
|
|
1684
|
+
const h = new Headers(out.headers);
|
|
1685
|
+
for (const c of ctx.setCookies)
|
|
1686
|
+
h.append("set-cookie", c);
|
|
1687
|
+
out = new Response(out.body, { status: out.status, statusText: out.statusText, headers: h });
|
|
1688
|
+
}
|
|
1689
|
+
return out;
|
|
1690
|
+
}
|
|
1372
1691
|
function safeActionRedirect(value) {
|
|
1373
1692
|
if (typeof value !== "string")
|
|
1374
1693
|
return "";
|
|
1375
1694
|
const to = value.trim();
|
|
1376
|
-
if (!to || to.charAt(0) !== "/" || to.charAt(1) === "/" || to.
|
|
1695
|
+
if (!to || to.charAt(0) !== "/" || to.charAt(1) === "/" || to.includes("\\"))
|
|
1377
1696
|
return "";
|
|
1378
|
-
if (/[\u0000-\
|
|
1697
|
+
if (/[\u0000-\u001F\u007F]/.test(to))
|
|
1379
1698
|
return "";
|
|
1380
1699
|
return to;
|
|
1381
1700
|
}
|
|
1701
|
+
// An absolute http(s) URL from a redirect() signal that marked itself external
|
|
1702
|
+
// (the OAuth redirect of @krate/auth signIn()). A redirect returned in an
|
|
1703
|
+
// action's result is never external.
|
|
1704
|
+
function safeExternalRedirect(value) {
|
|
1705
|
+
if (typeof value !== "string" || /[\u0000-\u001F\u007F\\]/.test(value))
|
|
1706
|
+
return "";
|
|
1707
|
+
try {
|
|
1708
|
+
const u = new URL(value.trim());
|
|
1709
|
+
return u.protocol === "https:" || u.protocol === "http:" ? u.href : "";
|
|
1710
|
+
}
|
|
1711
|
+
catch {
|
|
1712
|
+
return "";
|
|
1713
|
+
}
|
|
1714
|
+
}
|
|
1382
1715
|
function sanitizeActionReturn(value, rs) {
|
|
1383
1716
|
value = value.trim();
|
|
1384
1717
|
if (!value)
|
|
1385
1718
|
return "";
|
|
1386
|
-
if (value.startsWith("/") && !value.startsWith("//") && !/[\\\r\n]/.test(value) && !/[\u0000-\
|
|
1719
|
+
if (value.startsWith("/") && !value.startsWith("//") && !/[\\\r\n]/.test(value) && !/[\u0000-\u001F\u007F]/.test(value))
|
|
1387
1720
|
return value;
|
|
1388
1721
|
let u;
|
|
1389
1722
|
try {
|
|
@@ -1550,18 +1883,38 @@ export function createKrateHandler(options) {
|
|
|
1550
1883
|
catch {
|
|
1551
1884
|
return withHeaders(rs, actionFail(400, "Invalid server action request body"));
|
|
1552
1885
|
}
|
|
1886
|
+
if (entry.inline && entry.captures && entry.captures.length > 0) {
|
|
1887
|
+
// A hoisted inline action: its closed-over values arrive sealed in a token
|
|
1888
|
+
// (the first leading argument, or the URL query for JSON calls).
|
|
1889
|
+
let token = typeof args[0] === "string" && args[0].startsWith("k1.") ? args.shift() : null;
|
|
1890
|
+
if (!token) {
|
|
1891
|
+
const q = leadingActionArgs(query.get("__krate_args"));
|
|
1892
|
+
if (q && typeof q[0] === "string" && q[0].startsWith("k1."))
|
|
1893
|
+
token = q[0];
|
|
1894
|
+
}
|
|
1895
|
+
try {
|
|
1896
|
+
args.unshift(...(await openInlineToken(token, entry, actionSecret)));
|
|
1897
|
+
}
|
|
1898
|
+
catch (e) {
|
|
1899
|
+
console.error(`[krate] rejected closure data for server action ${entry.source || id}: ${e.message}`);
|
|
1900
|
+
return withHeaders(rs, actionFail(400, "Invalid server action request"));
|
|
1901
|
+
}
|
|
1902
|
+
}
|
|
1553
1903
|
const ctx = makeActionContext(reqHeaders, id, rs.path);
|
|
1554
1904
|
const scope = { kind: "action", paths: [], tags: [] };
|
|
1555
1905
|
let result;
|
|
1556
1906
|
let redirect = "";
|
|
1907
|
+
let external = false;
|
|
1557
1908
|
let failure = null;
|
|
1558
1909
|
let fallback = 0;
|
|
1559
1910
|
try {
|
|
1560
1911
|
result = await revalidateStore.run(scope, () => actionStore.run(ctx, () => fn(...args)));
|
|
1561
1912
|
}
|
|
1562
1913
|
catch (e) {
|
|
1563
|
-
if (e && typeof e.__krateRedirect === "string")
|
|
1914
|
+
if (e && typeof e.__krateRedirect === "string") {
|
|
1564
1915
|
redirect = e.__krateRedirect;
|
|
1916
|
+
external = e.__krateRedirectExternal === true;
|
|
1917
|
+
}
|
|
1565
1918
|
else if ((fallback = httpFallbackStatus(e)))
|
|
1566
1919
|
failure = null;
|
|
1567
1920
|
else
|
|
@@ -1577,7 +1930,7 @@ export function createKrateHandler(options) {
|
|
|
1577
1930
|
}
|
|
1578
1931
|
if (!redirect && result && typeof result === "object" && typeof result.redirect === "string")
|
|
1579
1932
|
redirect = result.redirect;
|
|
1580
|
-
redirect = safeActionRedirect(redirect);
|
|
1933
|
+
redirect = external ? safeExternalRedirect(redirect) : safeActionRedirect(redirect);
|
|
1581
1934
|
if (fallback && !failure)
|
|
1582
1935
|
return withHeaders(rs, actionFallback(rs, fallback, fetchMode, ctx.setCookies, reqHeaders.get("x-krate-return") || ""));
|
|
1583
1936
|
let body = "";
|
|
@@ -1585,6 +1938,8 @@ export function createKrateHandler(options) {
|
|
|
1585
1938
|
const envelope = { ok: true, result: result === undefined ? null : result };
|
|
1586
1939
|
if (redirect)
|
|
1587
1940
|
envelope.redirect = redirect;
|
|
1941
|
+
if (redirect && external)
|
|
1942
|
+
envelope.external = true;
|
|
1588
1943
|
if (revalidation) {
|
|
1589
1944
|
envelope.revalidated = true;
|
|
1590
1945
|
envelope.revalidation = revalidation;
|
|
@@ -1695,6 +2050,16 @@ export function createKrateHandler(options) {
|
|
|
1695
2050
|
}
|
|
1696
2051
|
async function mux(rs) {
|
|
1697
2052
|
const p = rs.path;
|
|
2053
|
+
// trailingSlash "never", then config redirects, answer first: before
|
|
2054
|
+
// middleware, and for /api too.
|
|
2055
|
+
const slashless = redirectToSlashless(rs);
|
|
2056
|
+
if (slashless)
|
|
2057
|
+
return slashless;
|
|
2058
|
+
if (!(p.startsWith("/__krate/") || p === "/healthz" || p === "/readyz")) {
|
|
2059
|
+
const redirected = configRedirect(rs, p, insideRedirects);
|
|
2060
|
+
if (redirected)
|
|
2061
|
+
return redirected;
|
|
2062
|
+
}
|
|
1698
2063
|
// net/http.ServeMux cleans the escaped path and redirects when it changed.
|
|
1699
2064
|
const raw = rs.rawPath;
|
|
1700
2065
|
const cleaned = cleanPath(raw) + (raw.endsWith("/") && raw !== "/" ? "/" : "");
|
|
@@ -1722,6 +2087,16 @@ export function createKrateHandler(options) {
|
|
|
1722
2087
|
return blocked;
|
|
1723
2088
|
return actionHandler(rs);
|
|
1724
2089
|
}
|
|
2090
|
+
if (data.metaRoutes && (rs.method === "GET" || rs.method === "HEAD")) {
|
|
2091
|
+
const key = matchMetaRoute(data.metaRoutes, p);
|
|
2092
|
+
if (key) {
|
|
2093
|
+
const blocked = await runMiddleware(rs);
|
|
2094
|
+
if (blocked)
|
|
2095
|
+
return blocked;
|
|
2096
|
+
rs.path = "/api/" + key;
|
|
2097
|
+
return apiHandler(rs);
|
|
2098
|
+
}
|
|
2099
|
+
}
|
|
1725
2100
|
return pageChain(rs);
|
|
1726
2101
|
}
|
|
1727
2102
|
function applySecurityAndHeaders(rs) {
|
|
@@ -1740,11 +2115,36 @@ export function createKrateHandler(options) {
|
|
|
1740
2115
|
h.set("Strict-Transport-Security", sec.hsts);
|
|
1741
2116
|
if (sec.csp)
|
|
1742
2117
|
h.set("Content-Security-Policy", sec.csp);
|
|
1743
|
-
|
|
1744
|
-
|
|
1745
|
-
|
|
1746
|
-
|
|
2118
|
+
}
|
|
2119
|
+
/**
|
|
2120
|
+
* Applies the matching headers rules to the finished response, so they win
|
|
2121
|
+
* over a header a handler set (a file's Cache-Control) except the immutable
|
|
2122
|
+
* Cache-Control of a content-hashed asset.
|
|
2123
|
+
*/
|
|
2124
|
+
function withHeaderRules(rs, path, res) {
|
|
2125
|
+
if (!headerRules.length)
|
|
2126
|
+
return res;
|
|
2127
|
+
const creq = condRequest(rs);
|
|
2128
|
+
let headers = null;
|
|
2129
|
+
for (const { rule, matcher } of headerRules) {
|
|
2130
|
+
if (!matcher.match(path, creq))
|
|
2131
|
+
continue;
|
|
2132
|
+
headers ?? (headers = new Headers(res.headers));
|
|
2133
|
+
const keepCache = headers.get("cache-control") === IMMUTABLE_CACHE_CONTROL;
|
|
2134
|
+
for (const [k, v] of ruleHeaderPairs(rule.headers)) {
|
|
2135
|
+
if (keepCache && k.toLowerCase() === "cache-control")
|
|
2136
|
+
continue;
|
|
2137
|
+
if (k.toLowerCase() === "vary") {
|
|
2138
|
+
if (!(headers.get("vary") || "").toLowerCase().includes(v.toLowerCase()))
|
|
2139
|
+
headers.append("Vary", v);
|
|
2140
|
+
}
|
|
2141
|
+
else
|
|
2142
|
+
headers.set(k, v);
|
|
2143
|
+
}
|
|
1747
2144
|
}
|
|
2145
|
+
if (!headers)
|
|
2146
|
+
return res;
|
|
2147
|
+
return new Response(res.body, { status: res.status, statusText: res.statusText, headers });
|
|
1748
2148
|
}
|
|
1749
2149
|
/** corsMiddleware; returns a Response for a preflight. */
|
|
1750
2150
|
function applyCORS(rs) {
|
|
@@ -1779,7 +2179,11 @@ export function createKrateHandler(options) {
|
|
|
1779
2179
|
return finish(rs, 204, null);
|
|
1780
2180
|
return null;
|
|
1781
2181
|
}
|
|
1782
|
-
return
|
|
2182
|
+
return function handle(request, ctx = {}) {
|
|
2183
|
+
// Every page, API route, action and middleware of the request sees the same platform.
|
|
2184
|
+
return runWithPlatform(target, ctx, () => handleRequest(request, ctx));
|
|
2185
|
+
};
|
|
2186
|
+
async function handleRequest(request, ctx) {
|
|
1783
2187
|
if (ctx.waitUntil)
|
|
1784
2188
|
latestWaitUntil = ctx.waitUntil.bind(ctx);
|
|
1785
2189
|
request = sanitizeForwarded(request);
|
|
@@ -1795,11 +2199,21 @@ export function createKrateHandler(options) {
|
|
|
1795
2199
|
origin: requestOrigin(request, url),
|
|
1796
2200
|
ctx,
|
|
1797
2201
|
};
|
|
2202
|
+
let headerPath = rs.path;
|
|
2203
|
+
const finalize = (res) => withHeaderRules(rs, headerPath, res);
|
|
1798
2204
|
try {
|
|
1799
2205
|
// Mount under the base path: requests outside it redirect (GET/HEAD) or 404.
|
|
2206
|
+
// The app then sees base-less paths, so a root-relative Location it
|
|
2207
|
+
// answers with gets the base on the way out.
|
|
2208
|
+
let mounted = false;
|
|
1800
2209
|
if (basePath) {
|
|
1801
2210
|
const p = rs.path;
|
|
1802
2211
|
if (!(p.startsWith("/__krate/") || p === "/healthz" || p === "/readyz")) {
|
|
2212
|
+
const outside = configRedirect(rs, p, outsideRedirects);
|
|
2213
|
+
if (outside) {
|
|
2214
|
+
applySecurityAndHeaders(rs);
|
|
2215
|
+
return outside;
|
|
2216
|
+
}
|
|
1803
2217
|
if (p === basePath || p === basePath + "/")
|
|
1804
2218
|
rs.path = "/";
|
|
1805
2219
|
else if (p.startsWith(basePath + "/"))
|
|
@@ -1810,23 +2224,28 @@ export function createKrateHandler(options) {
|
|
|
1810
2224
|
return goRedirect(basePath + (p.startsWith("/") ? p : "/" + p), p, rs.method, 307, rs.res);
|
|
1811
2225
|
return notFoundText(rs);
|
|
1812
2226
|
}
|
|
2227
|
+
mounted = true;
|
|
2228
|
+
if (rs.rawPath.startsWith(basePath))
|
|
2229
|
+
rs.rawPath = rs.rawPath.slice(basePath.length) || "/";
|
|
1813
2230
|
}
|
|
1814
2231
|
}
|
|
1815
2232
|
applySecurityAndHeaders(rs);
|
|
2233
|
+
headerPath = rs.path;
|
|
1816
2234
|
const preflight = applyCORS(rs);
|
|
1817
2235
|
if (preflight)
|
|
1818
|
-
return preflight;
|
|
2236
|
+
return finalize(mounted ? withBaseLocation(preflight) : preflight);
|
|
1819
2237
|
await sleepMicrotask();
|
|
1820
|
-
|
|
2238
|
+
const res = await mux(rs);
|
|
2239
|
+
return finalize(mounted ? withBaseLocation(res) : res);
|
|
1821
2240
|
}
|
|
1822
2241
|
catch (err) {
|
|
1823
2242
|
console.error(`[krate] panic recovered: ${rs.method} ${rs.path}: ${(err && err.stack) || err}`);
|
|
1824
2243
|
if (rs.path.startsWith("/api/")) {
|
|
1825
2244
|
rs.res.set("Content-Type", "application/json");
|
|
1826
|
-
return finish(rs, 500, '{"error":"Internal Server Error"}');
|
|
2245
|
+
return finalize(finish(rs, 500, '{"error":"Internal Server Error"}'));
|
|
1827
2246
|
}
|
|
1828
|
-
return httpError(rs, "Internal Server Error", 500);
|
|
2247
|
+
return finalize(httpError(rs, "Internal Server Error", 500));
|
|
1829
2248
|
}
|
|
1830
|
-
}
|
|
2249
|
+
}
|
|
1831
2250
|
}
|
|
1832
2251
|
export { isDynamicPattern };
|