@krate/runtime 0.5.0-alpha.4 → 0.5.0-beta.2
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.d.ts +5 -1
- package/dist/action-context.js +33 -3
- package/dist/action-context.test.js +26 -1
- package/dist/actions.d.ts +12 -1
- package/dist/actions.js +84 -4
- package/dist/actions.test.js +61 -1
- package/dist/assets-static.d.ts +5 -0
- package/dist/assets-static.js +31 -0
- package/dist/boundary.d.ts +12 -0
- package/dist/boundary.js +53 -13
- package/dist/cache-adapter.d.ts +113 -0
- package/dist/cache-adapter.js +217 -0
- package/dist/cache-adapter.test.d.ts +1 -0
- package/dist/cache-adapter.test.js +244 -0
- package/dist/cache-redis.d.ts +27 -0
- package/dist/cache-redis.js +110 -0
- package/dist/cache-scope.d.ts +25 -9
- package/dist/cache-scope.js +64 -13
- package/dist/cache.d.ts +1 -0
- package/dist/cache.js +3 -3
- package/dist/cache.test.js +16 -0
- package/dist/class-component.js +6 -0
- package/dist/class-component.test.js +53 -2
- package/dist/class-helpers.d.ts +4 -4
- package/dist/class-helpers.js +357 -32
- package/dist/class-helpers.test.d.ts +1 -0
- package/dist/class-helpers.test.js +169 -0
- package/dist/context.d.ts +16 -2
- package/dist/context.js +44 -3
- package/dist/dev-overlay.js +85 -12
- package/dist/dev-overlay.test.js +22 -0
- package/dist/dom.d.ts +15 -0
- package/dist/dom.js +97 -3
- package/dist/effect-errors.test.d.ts +1 -0
- package/dist/effect-errors.test.js +163 -0
- package/dist/effects.d.ts +8 -0
- package/dist/effects.js +13 -0
- package/dist/error-overlay.js +7 -7
- package/dist/handler-html.d.ts +63 -0
- package/dist/handler-html.js +285 -0
- package/dist/handler-html.test.d.ts +1 -0
- package/dist/handler-html.test.js +256 -0
- package/dist/handler-routing.d.ts +83 -0
- package/dist/handler-routing.js +579 -0
- package/dist/handler-routing.test.d.ts +1 -0
- package/dist/handler-routing.test.js +99 -0
- package/dist/handler-segments.d.ts +43 -0
- package/dist/handler-segments.js +115 -0
- package/dist/handler-segments.test.d.ts +1 -0
- package/dist/handler-segments.test.js +217 -0
- package/dist/head-tags.d.ts +51 -0
- package/dist/head-tags.js +329 -0
- package/dist/head-tags.test.d.ts +1 -0
- package/dist/head-tags.test.js +131 -0
- package/dist/highlight-bind.d.ts +42 -0
- package/dist/highlight-bind.js +176 -0
- package/dist/highlight-bind.test.d.ts +1 -0
- package/dist/highlight-bind.test.js +124 -0
- package/dist/highlight.d.ts +93 -0
- package/dist/highlight.js +426 -0
- package/dist/highlight.test.d.ts +1 -0
- package/dist/highlight.test.js +56 -0
- package/dist/hints.d.ts +19 -0
- package/dist/hints.js +97 -0
- package/dist/hook-args.d.ts +7 -0
- package/dist/hook-args.js +10 -0
- package/dist/htmlspec-attributes.d.ts +1 -0
- package/dist/htmlspec-attributes.js +159 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +3 -0
- package/dist/jsx-types.d.ts +11 -0
- package/dist/krate-core.js +2 -0
- package/dist/krate-dev.js +75 -12
- package/dist/krate-f-actions.js +2 -0
- package/dist/krate-f-classes.js +8 -0
- package/dist/krate-f-helpers.js +2 -0
- package/dist/krate-f-highlight.js +2 -0
- package/dist/krate-f-list.js +2 -0
- package/dist/krate-f-navigation.js +2 -0
- package/dist/krate-f-router-lite.js +2 -0
- package/dist/krate-f-router.js +2 -0
- package/dist/krate-features.json +493 -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/list.js +4 -2
- package/dist/metadata-routes.d.ts +75 -0
- package/dist/metadata-routes.js +76 -0
- package/dist/metadata.d.ts +222 -0
- package/dist/metadata.js +452 -0
- package/dist/metadata.test.d.ts +1 -0
- package/dist/metadata.test.js +167 -0
- package/dist/navigation-server.d.ts +27 -0
- package/dist/navigation-server.js +90 -0
- package/dist/navigation.d.ts +37 -0
- package/dist/navigation.js +195 -0
- package/dist/navigation.test.d.ts +1 -0
- package/dist/navigation.test.js +130 -0
- package/dist/node-server.d.ts +22 -0
- package/dist/node-server.js +436 -0
- package/dist/node-server.test.d.ts +1 -0
- package/dist/node-server.test.js +492 -0
- package/dist/og-files.d.ts +2 -0
- package/dist/og-files.js +19 -0
- package/dist/og.d.ts +56 -0
- package/dist/og.js +156 -0
- package/dist/patterns.test.d.ts +1 -0
- package/dist/patterns.test.js +98 -0
- package/dist/react.d.ts +47 -0
- package/dist/react.js +59 -1
- package/dist/react19.test.d.ts +1 -0
- package/dist/react19.test.js +176 -0
- package/dist/reactivity-core.test.d.ts +1 -0
- package/dist/reactivity-core.test.js +152 -0
- package/dist/reconcile.js +4 -2
- package/dist/request-context.d.ts +23 -0
- package/dist/request-context.js +45 -0
- package/dist/resp.d.ts +55 -0
- package/dist/resp.js +239 -0
- package/dist/router-layout.test.js +70 -0
- package/dist/router-nav.test.js +65 -0
- package/dist/router-speculation.test.d.ts +1 -0
- package/dist/router-speculation.test.js +25 -0
- package/dist/router-styles.test.d.ts +1 -0
- package/dist/router-styles.test.js +98 -0
- package/dist/router.js +175 -36
- package/dist/segmented-lru.d.ts +19 -0
- package/dist/segmented-lru.js +87 -0
- package/dist/server-async.test.js +43 -1
- package/dist/server-handler.d.ts +165 -0
- package/dist/server-handler.js +1826 -0
- package/dist/server-handler.test.d.ts +1 -0
- package/dist/server-handler.test.js +522 -0
- package/dist/server-highlight.test.d.ts +1 -0
- package/dist/server-highlight.test.js +32 -0
- package/dist/server-renderer.js +165 -720
- package/dist/server-renderer.test.d.ts +1 -0
- package/dist/server-renderer.test.js +266 -0
- package/dist/server.d.ts +13 -1
- package/dist/server.js +131 -16
- package/dist/server.test.js +20 -0
- package/dist/sha256.d.ts +1 -0
- package/dist/sha256.js +66 -0
- package/dist/sha256.test.d.ts +1 -0
- package/dist/sha256.test.js +13 -0
- package/dist/shared-isr.d.ts +31 -0
- package/dist/shared-isr.js +142 -0
- package/dist/signal.d.ts +3 -2
- package/dist/signal.js +163 -23
- package/dist/slots.js +12 -1
- package/dist/ssr-core-behavior.test.d.ts +1 -0
- package/dist/ssr-core-behavior.test.js +620 -0
- package/dist/ssr-core.d.ts +175 -0
- package/dist/ssr-core.js +940 -0
- package/dist/ssr-core.test.d.ts +1 -0
- package/dist/ssr-core.test.js +324 -0
- package/dist/static-memory.d.ts +3 -0
- package/dist/static-memory.js +47 -0
- package/dist/static-memory.test.d.ts +1 -0
- package/dist/static-memory.test.js +26 -0
- package/dist/test-redis.d.ts +12 -0
- package/dist/test-redis.js +131 -0
- package/dist/use-id.d.ts +8 -0
- package/dist/use-id.js +40 -0
- package/package.json +30 -2
|
@@ -0,0 +1,1826 @@
|
|
|
1
|
+
// @krate/runtime/server-handler - the portable Krate server.
|
|
2
|
+
//
|
|
3
|
+
// createKrateHandler(options) returns a Web-standard (Request) => Promise<Response>
|
|
4
|
+
// that does, per request, what the Go host (`krate start`) does: config redirects,
|
|
5
|
+
// rewrites and headers, middleware, route matching, static-template pages,
|
|
6
|
+
// SSR/ISR/streaming pages with region splicing, JS/TS API routes, server actions,
|
|
7
|
+
// no-JS flash notices, security headers and the cache policy. It runs on Node,
|
|
8
|
+
// Vercel, Netlify and Cloudflare Workers: there is no Go, no node:fs and no
|
|
9
|
+
// node:vm in this module. Everything it needs (build data, page modules, API
|
|
10
|
+
// routes, actions, middleware) is handed in by the bundle entry the compiler
|
|
11
|
+
// generates (`krate deploy`), and static files come from a pluggable layer.
|
|
12
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
13
|
+
import { createSSRCore, MemoryIsrStore, } from "./ssr-core.js";
|
|
14
|
+
import { cacheRuntime, installRenderStore, patchFetch } from "./cache-scope.js";
|
|
15
|
+
import { allSuspense, canStreamOutOfOrder, FLASH_COOKIE, flashPayloadOf, injectFlashNotice, parseRegionShell, regionReplaceScript, requestFlash, signFlash, spliceShell, splitBodyScripts, } from "./handler-html.js";
|
|
16
|
+
import { mergeHead } from "./head-tags.js";
|
|
17
|
+
import { applyDynamicRouteParams, baseName, cleanPath, compareRouteSpecificity, compileMatcher, extName, goRedirect, headerSourceMatches, isDynamicPattern, isFileLikePath, isHTMLDocRequest, isInternalOutputPath, matchRedirect, matchRoutePattern, normalizeRoutePattern, requestRoute, rewriteDestination, rewriteTargetPath, staticCacheControl, } from "./handler-routing.js";
|
|
18
|
+
import { lookupSegmentPage, newServerError, renderSegmentPage, SEGMENT_KIND_OF_STATUS, } from "./handler-segments.js";
|
|
19
|
+
import { httpFallbackStatus } from "./request-context.js";
|
|
20
|
+
import { sha256Hex as portableSha256Hex } from "./sha256.js";
|
|
21
|
+
import { INVALIDATE_CHANNEL, cacheSpecFromConfig } from "./cache-adapter.js";
|
|
22
|
+
import { isrStoreFor } from "./shared-isr.js";
|
|
23
|
+
import { createMemoryStaticLayer } from "./static-memory.js";
|
|
24
|
+
// Internals
|
|
25
|
+
const NO_BODY_STATUS = new Set([101, 204, 205, 304]);
|
|
26
|
+
const KRATE_METHODS = ["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"];
|
|
27
|
+
const STATIC_ASSET_EXTS = new Set([
|
|
28
|
+
".css", ".js", ".mjs", ".map", ".png", ".jpg", ".jpeg", ".gif", ".svg", ".webp", ".avif", ".ico", ".woff", ".woff2",
|
|
29
|
+
".ttf", ".otf", ".eot", ".mp4", ".webm", ".mp3", ".wav", ".ogg", ".wasm", ".txt", ".xml", ".webmanifest", ".pdf", ".zip",
|
|
30
|
+
]);
|
|
31
|
+
function globalStore(name) {
|
|
32
|
+
const key = Symbol.for(name);
|
|
33
|
+
const g = globalThis;
|
|
34
|
+
if (!g[key])
|
|
35
|
+
g[key] = new AsyncLocalStorage();
|
|
36
|
+
return g[key];
|
|
37
|
+
}
|
|
38
|
+
function safeDecode(p) {
|
|
39
|
+
try {
|
|
40
|
+
return decodeURIComponent(p);
|
|
41
|
+
}
|
|
42
|
+
catch {
|
|
43
|
+
return p;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
function textResponse(rs, status, body, contentType = "text/plain; charset=utf-8") {
|
|
47
|
+
rs.res.set("Content-Type", contentType);
|
|
48
|
+
return finish(rs, status, body);
|
|
49
|
+
}
|
|
50
|
+
/** http.Error */
|
|
51
|
+
function httpError(rs, message, status) {
|
|
52
|
+
rs.res.delete("Content-Length");
|
|
53
|
+
rs.res.set("Content-Type", "text/plain; charset=utf-8");
|
|
54
|
+
rs.res.set("X-Content-Type-Options", "nosniff");
|
|
55
|
+
return finish(rs, status, message + "\n");
|
|
56
|
+
}
|
|
57
|
+
/** http.NotFound; after a file-server miss Go also drops the entity headers. */
|
|
58
|
+
function notFoundText(rs, fileServer = false) {
|
|
59
|
+
if (fileServer)
|
|
60
|
+
for (const h of ["Content-Encoding", "Etag", "Last-Modified", "Cache-Control"])
|
|
61
|
+
rs.res.delete(h);
|
|
62
|
+
return httpError(rs, "404 page not found", 404);
|
|
63
|
+
}
|
|
64
|
+
function finish(rs, status, body) {
|
|
65
|
+
const noBody = NO_BODY_STATUS.has(status) || rs.method === "HEAD";
|
|
66
|
+
return new Response(noBody ? null : body, { status, headers: rs.res });
|
|
67
|
+
}
|
|
68
|
+
/** writeHeaderPairs: repeated Set-Cookie append, everything else replaces what earlier layers set. */
|
|
69
|
+
function writeHeaderPairs(h, pairs) {
|
|
70
|
+
const seen = new Set();
|
|
71
|
+
for (const [k0, v] of pairs) {
|
|
72
|
+
const k = k0.toLowerCase();
|
|
73
|
+
if (k === "set-cookie") {
|
|
74
|
+
h.append("Set-Cookie", v);
|
|
75
|
+
continue;
|
|
76
|
+
}
|
|
77
|
+
if (!seen.has(k)) {
|
|
78
|
+
h.delete(k);
|
|
79
|
+
seen.add(k);
|
|
80
|
+
}
|
|
81
|
+
h.append(k, v);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
function headerPairs(headers) {
|
|
85
|
+
const out = [];
|
|
86
|
+
const anyH = headers;
|
|
87
|
+
const cookies = typeof anyH.getSetCookie === "function" ? anyH.getSetCookie() : [];
|
|
88
|
+
headers.forEach((v, k) => {
|
|
89
|
+
if (k.toLowerCase() !== "set-cookie")
|
|
90
|
+
out.push([k, v]);
|
|
91
|
+
});
|
|
92
|
+
for (const c of cookies)
|
|
93
|
+
out.push(["set-cookie", c]);
|
|
94
|
+
return out;
|
|
95
|
+
}
|
|
96
|
+
/** The scheme the client used, from the X-Forwarded-Proto the server sets or a trusted proxy sends. */
|
|
97
|
+
function isHTTPSRequest(headers) {
|
|
98
|
+
return (headers.get("x-forwarded-proto") || "").split(",")[0].trim().toLowerCase() === "https";
|
|
99
|
+
}
|
|
100
|
+
function isStaticAssetPath(p) {
|
|
101
|
+
return STATIC_ASSET_EXTS.has(extName(p).toLowerCase());
|
|
102
|
+
}
|
|
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
|
+
const sleepMicrotask = () => Promise.resolve();
|
|
144
|
+
const PLATFORMS = {
|
|
145
|
+
node: { forwardedHostProto: false, clientIP: [] },
|
|
146
|
+
vercel: { forwardedHostProto: true, clientIP: ["x-real-ip", "x-forwarded-for"] },
|
|
147
|
+
netlify: { forwardedHostProto: false, clientIP: ["x-nf-client-connection-ip"] },
|
|
148
|
+
cloudflare: { forwardedHostProto: false, clientIP: ["cf-connecting-ip"] },
|
|
149
|
+
};
|
|
150
|
+
const MIN_FLASH_SECRET = 16;
|
|
151
|
+
let warnedFlashSecret = false;
|
|
152
|
+
/**
|
|
153
|
+
* The key flash cookies are signed with, or null when this deployment cannot
|
|
154
|
+
* sign them reliably. A configured key (option or KRATE_FLASH_SECRET) is shared
|
|
155
|
+
* by every instance. The node target is one long-lived process, so a random
|
|
156
|
+
* key per process is enough (replicas behind a load balancer need the shared
|
|
157
|
+
* key). A serverless instance has no memory the next one shares: without a key
|
|
158
|
+
* the flash is not carried at all rather than failing on a random instance.
|
|
159
|
+
*/
|
|
160
|
+
function resolveFlashSecret(option, target) {
|
|
161
|
+
const env = globalThis.process?.env;
|
|
162
|
+
const configured = option || (env && env.KRATE_FLASH_SECRET) || "";
|
|
163
|
+
if (configured) {
|
|
164
|
+
if (configured.length < MIN_FLASH_SECRET && !warnedFlashSecret) {
|
|
165
|
+
warnedFlashSecret = true;
|
|
166
|
+
console.warn(`[krate] KRATE_FLASH_SECRET is shorter than ${MIN_FLASH_SECRET} characters: use a random value of at least 32 bytes.`);
|
|
167
|
+
}
|
|
168
|
+
return configured;
|
|
169
|
+
}
|
|
170
|
+
if (target !== "node")
|
|
171
|
+
return null;
|
|
172
|
+
const bytes = new Uint8Array(32);
|
|
173
|
+
crypto.getRandomValues(bytes);
|
|
174
|
+
let hex = "";
|
|
175
|
+
for (const b of bytes)
|
|
176
|
+
hex += b.toString(16).padStart(2, "0");
|
|
177
|
+
return hex;
|
|
178
|
+
}
|
|
179
|
+
// Handler factory
|
|
180
|
+
export function createKrateHandler(options) {
|
|
181
|
+
const { data, modules } = options;
|
|
182
|
+
const cfg = data.config;
|
|
183
|
+
const target = options.target;
|
|
184
|
+
// Prerendered pages carried in the bundle (platforms that route pages through the function for middleware).
|
|
185
|
+
const staticLayer = options.static || (data.staticPages ? createMemoryStaticLayer(data.staticPages) : undefined);
|
|
186
|
+
const trustProxy = options.trustProxy !== undefined ? options.trustProxy : cfg.trustProxy === undefined ? null : cfg.trustProxy;
|
|
187
|
+
const platform = PLATFORMS[target];
|
|
188
|
+
const basePath = cfg.basePath || "";
|
|
189
|
+
const hashed = new Set(data.hashedAssets);
|
|
190
|
+
const staticOnly = new Set(data.staticOnlyRoutes.map(normalizeRoutePattern));
|
|
191
|
+
const sha256Hex = options.sha256Hex || portableSha256Hex;
|
|
192
|
+
const flashSecret = resolveFlashSecret(options.flashSecret, target);
|
|
193
|
+
const segEntries = data.segments || [];
|
|
194
|
+
const segPages = data.segmentPages || {};
|
|
195
|
+
const segDirByRoute = new Map();
|
|
196
|
+
for (const p of data.allPages)
|
|
197
|
+
if (p.segDir !== undefined)
|
|
198
|
+
segDirByRoute.set(normalizeRoutePattern(p.route), p.segDir);
|
|
199
|
+
for (const p of data.pages)
|
|
200
|
+
if (p.segDir !== undefined)
|
|
201
|
+
segDirByRoute.set(normalizeRoutePattern(p.route), p.segDir);
|
|
202
|
+
/**
|
|
203
|
+
* errorPage is the single place that picks the error page for a request:
|
|
204
|
+
* the nearest segment page (build/segments.go LookupSegmentPage), else the
|
|
205
|
+
* global 404/500. segDir is the directory of the matched route; closed names
|
|
206
|
+
* a dynamic route that matched the URL but rejected its params. null means
|
|
207
|
+
* no custom page.
|
|
208
|
+
*/
|
|
209
|
+
function errorPage(urlPath, status, route) {
|
|
210
|
+
const kind = SEGMENT_KIND_OF_STATUS[status];
|
|
211
|
+
if (segEntries.length > 0) {
|
|
212
|
+
let m = null;
|
|
213
|
+
const closedDir = route && route.closed ? segDirByRoute.get(normalizeRoutePattern(route.closed)) : undefined;
|
|
214
|
+
if (closedDir !== undefined)
|
|
215
|
+
m = lookupSegmentPage(segEntries, kind, urlPath, true, closedDir);
|
|
216
|
+
else if (route && route.segDir !== undefined)
|
|
217
|
+
m = lookupSegmentPage(segEntries, kind, urlPath, true, route.segDir);
|
|
218
|
+
else
|
|
219
|
+
m = lookupSegmentPage(segEntries, kind, urlPath, false, "");
|
|
220
|
+
const html = m ? segPages[m.file] : undefined;
|
|
221
|
+
if (m && html !== undefined)
|
|
222
|
+
return { html, match: m };
|
|
223
|
+
}
|
|
224
|
+
const global = status === 404 ? data.html404 : status === 500 ? data.html500 : "";
|
|
225
|
+
return global ? { html: global, match: null } : null;
|
|
226
|
+
}
|
|
227
|
+
let requestSeq = 0;
|
|
228
|
+
let latestWaitUntil;
|
|
229
|
+
// Stores shared with @krate/runtime/server (headers(), cookies(), revalidatePath()).
|
|
230
|
+
const actionStore = globalStore("krate.action.store");
|
|
231
|
+
const revalidateStore = globalStore("krate.revalidate.store");
|
|
232
|
+
if (!cacheRuntime().renderStore)
|
|
233
|
+
installRenderStore(new AsyncLocalStorage());
|
|
234
|
+
patchFetch();
|
|
235
|
+
// The ISR and data caches: this instance's memory, or the shared cache adapter.
|
|
236
|
+
const memoryIsr = new MemoryIsrStore(cfg.ssr.maxCacheSize > 0 ? cfg.ssr.maxCacheSize : 512);
|
|
237
|
+
const sharedCache = options.isrStore
|
|
238
|
+
? { store: options.isrStore, ready: Promise.resolve(null) }
|
|
239
|
+
: isrStoreFor(options.cache ?? cacheSpecFromConfig(cfg.cache), memoryIsr);
|
|
240
|
+
let sharedAdapter = null;
|
|
241
|
+
const instanceId = Math.random().toString(36).slice(2) + Date.now().toString(36);
|
|
242
|
+
// Pages: most specific route first, like SSRServer.FindPageForRoute.
|
|
243
|
+
const pagesBySpecificity = [...data.pages].sort((a, b) => compareRouteSpecificity(a.route, b.route));
|
|
244
|
+
const manifest = { pages: data.pages, regions: data.regions };
|
|
245
|
+
const core = createSSRCore({
|
|
246
|
+
manifest,
|
|
247
|
+
sha256Hex: options.sha256Hex,
|
|
248
|
+
isrStore: sharedCache.store,
|
|
249
|
+
loadPageModule: async (page) => {
|
|
250
|
+
const mod = modules.pages && modules.pages[page.bundlePath || ""];
|
|
251
|
+
if (!mod)
|
|
252
|
+
throw new Error(`server bundle for ${page.route} is not part of this deployment (${page.bundlePath})`);
|
|
253
|
+
return mod;
|
|
254
|
+
},
|
|
255
|
+
loadRuntimeRenderer: (relPath) => {
|
|
256
|
+
const fn = modules.runtime && modules.runtime[relPath];
|
|
257
|
+
if (typeof fn !== "function")
|
|
258
|
+
throw new Error(`runtime component bundle ${relPath} is not part of this deployment`);
|
|
259
|
+
return fn;
|
|
260
|
+
},
|
|
261
|
+
maxCacheSize: cfg.ssr.maxCacheSize,
|
|
262
|
+
timeoutMs: cfg.ssr.timeout > 0 ? cfg.ssr.timeout : 5000,
|
|
263
|
+
ppr: cfg.ssr.ppr,
|
|
264
|
+
pprRevalidate: cfg.ssr.pprRevalidate,
|
|
265
|
+
background: (p) => {
|
|
266
|
+
if (latestWaitUntil)
|
|
267
|
+
latestWaitUntil(p);
|
|
268
|
+
},
|
|
269
|
+
});
|
|
270
|
+
const shells = new Map();
|
|
271
|
+
function loadShell(route) {
|
|
272
|
+
let e = shells.get(route);
|
|
273
|
+
if (!e) {
|
|
274
|
+
const html = data.shells[route];
|
|
275
|
+
if (html === undefined)
|
|
276
|
+
return null;
|
|
277
|
+
e = parseRegionShell(html);
|
|
278
|
+
shells.set(route, e);
|
|
279
|
+
}
|
|
280
|
+
return e;
|
|
281
|
+
}
|
|
282
|
+
function findPageForRoute(urlPath) {
|
|
283
|
+
for (const p of pagesBySpecificity) {
|
|
284
|
+
const params = matchRoutePattern(urlPath, p.route);
|
|
285
|
+
if (params)
|
|
286
|
+
return { page: p, params };
|
|
287
|
+
}
|
|
288
|
+
return null;
|
|
289
|
+
}
|
|
290
|
+
const templates = [...data.templates].sort((a, b) => compareRouteSpecificity(a.pattern, b.pattern));
|
|
291
|
+
const corsOrigins = cfg.cors.origins.length ? cfg.cors.origins : ["*"];
|
|
292
|
+
// Middleware
|
|
293
|
+
let mwMatchers;
|
|
294
|
+
function middlewareMatchers() {
|
|
295
|
+
if (mwMatchers !== undefined)
|
|
296
|
+
return mwMatchers;
|
|
297
|
+
const mod = modules.middleware;
|
|
298
|
+
const m = mod && (mod.matcher !== undefined ? mod.matcher : mod.config && mod.config.matcher);
|
|
299
|
+
if (m === undefined || m === null)
|
|
300
|
+
return (mwMatchers = null);
|
|
301
|
+
mwMatchers = (Array.isArray(m) ? m : [m]).map((e) => {
|
|
302
|
+
if (e && typeof e === "object") {
|
|
303
|
+
if (e.has || e.missing || e.locale === false) {
|
|
304
|
+
throw new Error('middleware matcher has/missing/locale conditions are not supported; use a path-only matcher');
|
|
305
|
+
}
|
|
306
|
+
return compileMatcher(e.source);
|
|
307
|
+
}
|
|
308
|
+
return compileMatcher(e);
|
|
309
|
+
});
|
|
310
|
+
return mwMatchers;
|
|
311
|
+
}
|
|
312
|
+
/**
|
|
313
|
+
* A matcher-less middleware is skipped only for a path that is a real file in
|
|
314
|
+
* the static layer. The extension alone is not enough: /api/files/x.pdf is a
|
|
315
|
+
* dynamic route that merely looks like a file.
|
|
316
|
+
*/
|
|
317
|
+
async function skipsMiddleware(p) {
|
|
318
|
+
if (!staticLayer || !isStaticAssetPath(p))
|
|
319
|
+
return false;
|
|
320
|
+
if (p === "/api" || p.startsWith("/api/") || p.startsWith("/__krate/"))
|
|
321
|
+
return false;
|
|
322
|
+
return !!(await staticLayer.exists(p));
|
|
323
|
+
}
|
|
324
|
+
/** Runs middleware; a Response ends the request, null continues (headers/rewrite already applied). */
|
|
325
|
+
async function runMiddleware(rs) {
|
|
326
|
+
const p = rs.path;
|
|
327
|
+
if (p.startsWith("/__krate/") && !p.startsWith("/__krate/action/"))
|
|
328
|
+
return null;
|
|
329
|
+
const mod = modules.middleware;
|
|
330
|
+
if (!data.hasMiddleware || !mod || typeof mod.middleware !== "function")
|
|
331
|
+
return null;
|
|
332
|
+
let matchers;
|
|
333
|
+
try {
|
|
334
|
+
matchers = middlewareMatchers();
|
|
335
|
+
}
|
|
336
|
+
catch (e) {
|
|
337
|
+
return middlewareFailed(rs, e);
|
|
338
|
+
}
|
|
339
|
+
if (!matchers && (await skipsMiddleware(p)))
|
|
340
|
+
return null;
|
|
341
|
+
if (matchers && !matchers.some((re) => re.test(p)))
|
|
342
|
+
return null;
|
|
343
|
+
let result;
|
|
344
|
+
try {
|
|
345
|
+
const request = attachCookies(new Request(fullURL(rs), { method: rs.method, headers: new Headers(rs.request.headers) }));
|
|
346
|
+
result = await mod.middleware(request);
|
|
347
|
+
}
|
|
348
|
+
catch (e) {
|
|
349
|
+
return middlewareFailed(rs, e);
|
|
350
|
+
}
|
|
351
|
+
if (result === undefined || result === null || typeof result.status !== "number")
|
|
352
|
+
return null;
|
|
353
|
+
let next = false;
|
|
354
|
+
let rewrite = "";
|
|
355
|
+
const hdrs = [];
|
|
356
|
+
for (const [k, v] of headerPairs(result.headers)) {
|
|
357
|
+
if (k === "x-middleware-next")
|
|
358
|
+
next = true;
|
|
359
|
+
else if (k === "x-middleware-rewrite")
|
|
360
|
+
rewrite = v;
|
|
361
|
+
else
|
|
362
|
+
hdrs.push([k, v]);
|
|
363
|
+
}
|
|
364
|
+
if (next || rewrite) {
|
|
365
|
+
writeHeaderPairs(rs.res, hdrs);
|
|
366
|
+
if (rewrite)
|
|
367
|
+
applyRewrite(rs, rewrite);
|
|
368
|
+
return null;
|
|
369
|
+
}
|
|
370
|
+
const body = result.status === 204 ? "" : await result.text();
|
|
371
|
+
writeHeaderPairs(rs.res, hdrs);
|
|
372
|
+
let status = result.status;
|
|
373
|
+
if (status < 100 || status > 999)
|
|
374
|
+
status = 500;
|
|
375
|
+
return finish(rs, status, rs.method === "HEAD" || !body ? null : body);
|
|
376
|
+
}
|
|
377
|
+
function middlewareFailed(rs, err) {
|
|
378
|
+
console.error(`[krate] middleware error: ${rs.method} ${rs.path}: ${(err && err.stack) || err}`);
|
|
379
|
+
// Fail closed: continuing would turn a broken auth check into an unauthenticated request.
|
|
380
|
+
rs.res.set("Cache-Control", "no-store");
|
|
381
|
+
return httpError(rs, "middleware failed", 503);
|
|
382
|
+
}
|
|
383
|
+
function applyRewrite(rs, target) {
|
|
384
|
+
const i = target.indexOf("://");
|
|
385
|
+
if (i >= 0) {
|
|
386
|
+
const rest = target.slice(i + 3);
|
|
387
|
+
const j = rest.indexOf("/");
|
|
388
|
+
target = j >= 0 ? rest.slice(j) : "/";
|
|
389
|
+
}
|
|
390
|
+
let p = target;
|
|
391
|
+
let q = "";
|
|
392
|
+
const qi = target.indexOf("?");
|
|
393
|
+
if (qi >= 0) {
|
|
394
|
+
p = target.slice(0, qi);
|
|
395
|
+
q = target.slice(qi + 1);
|
|
396
|
+
}
|
|
397
|
+
if (!p.startsWith("/"))
|
|
398
|
+
p = "/" + p;
|
|
399
|
+
rs.path = rewriteTargetPath(p);
|
|
400
|
+
if (q)
|
|
401
|
+
rs.search = "?" + q;
|
|
402
|
+
}
|
|
403
|
+
// Request helpers
|
|
404
|
+
// sanitizeForwarded makes the forwarding headers of a request mean what the
|
|
405
|
+
// rest of the handler (and middleware, API routes, actions) takes them to
|
|
406
|
+
// mean, whatever the client sent:
|
|
407
|
+
// - x-forwarded-host/proto come from the platform when it guarantees them
|
|
408
|
+
// (or from the proxy of yours when trustProxy is true), else from the
|
|
409
|
+
// request URL;
|
|
410
|
+
// - on a serverless platform x-forwarded-for / x-real-ip carry the one
|
|
411
|
+
// client address the platform reports (never a chain the client wrote),
|
|
412
|
+
// and `forwarded` is dropped. trustProxy: true leaves them as delivered.
|
|
413
|
+
// The node target is normalised by the node server before it gets here.
|
|
414
|
+
function sanitizeForwarded(request) {
|
|
415
|
+
const url = new URL(request.url);
|
|
416
|
+
const h = new Headers(request.headers);
|
|
417
|
+
const trustHostProto = trustProxy === null ? platform.forwardedHostProto : trustProxy;
|
|
418
|
+
const first = (name) => (h.get(name) || "").split(",")[0].trim();
|
|
419
|
+
const proto = first("x-forwarded-proto").toLowerCase();
|
|
420
|
+
const host = first("x-forwarded-host");
|
|
421
|
+
if (trustHostProto) {
|
|
422
|
+
h.set("x-forwarded-proto", proto === "http" || proto === "https" ? proto : url.protocol.replace(":", ""));
|
|
423
|
+
h.set("x-forwarded-host", host || url.host);
|
|
424
|
+
}
|
|
425
|
+
else {
|
|
426
|
+
h.set("x-forwarded-proto", url.protocol.replace(":", ""));
|
|
427
|
+
h.set("x-forwarded-host", url.host);
|
|
428
|
+
}
|
|
429
|
+
if (target !== "node" && trustProxy !== true) {
|
|
430
|
+
h.delete("forwarded");
|
|
431
|
+
h.delete("x-real-ip");
|
|
432
|
+
h.delete("x-forwarded-for");
|
|
433
|
+
let ip = "";
|
|
434
|
+
if (trustProxy === null) {
|
|
435
|
+
for (const name of platform.clientIP) {
|
|
436
|
+
const v = (request.headers.get(name) || "").split(",")[0].trim();
|
|
437
|
+
if (v) {
|
|
438
|
+
ip = v;
|
|
439
|
+
break;
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
if (ip) {
|
|
444
|
+
h.set("x-forwarded-for", ip);
|
|
445
|
+
h.set("x-real-ip", ip);
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
return new Request(request, { headers: h });
|
|
449
|
+
}
|
|
450
|
+
// handle() has run sanitizeForwarded: the forwarded headers can be read as they are.
|
|
451
|
+
function requestOrigin(request, url) {
|
|
452
|
+
const proto = (request.headers.get("x-forwarded-proto") || "").split(",")[0].trim().toLowerCase();
|
|
453
|
+
const host = (request.headers.get("x-forwarded-host") || "").split(",")[0].trim();
|
|
454
|
+
const scheme = proto === "http" || proto === "https" ? proto : url.protocol.replace(":", "");
|
|
455
|
+
return scheme + "://" + (host || url.host);
|
|
456
|
+
}
|
|
457
|
+
function requestHost(rs) {
|
|
458
|
+
const h = (rs.request.headers.get("x-forwarded-host") || "").split(",")[0].trim();
|
|
459
|
+
return h || new URL(rs.request.url).host;
|
|
460
|
+
}
|
|
461
|
+
function fullURL(rs) {
|
|
462
|
+
return rs.origin + encodeURI(rs.path).replace(/%25([0-9A-Fa-f]{2})/g, "%$1") + rs.search;
|
|
463
|
+
}
|
|
464
|
+
function queryOf(rs) {
|
|
465
|
+
const out = {};
|
|
466
|
+
const sp = new URLSearchParams(rs.search);
|
|
467
|
+
for (const k of new Set(sp.keys()))
|
|
468
|
+
out[k] = sp.get(k);
|
|
469
|
+
return out;
|
|
470
|
+
}
|
|
471
|
+
function headerMap(rs) {
|
|
472
|
+
const out = {};
|
|
473
|
+
rs.headers.forEach((v, k) => {
|
|
474
|
+
if (k !== "host")
|
|
475
|
+
out[canonicalHeader(k)] = v;
|
|
476
|
+
});
|
|
477
|
+
return out;
|
|
478
|
+
}
|
|
479
|
+
function canonicalHeader(k) {
|
|
480
|
+
return k.split("-").map((s) => (s ? s[0].toUpperCase() + s.slice(1) : s)).join("-");
|
|
481
|
+
}
|
|
482
|
+
async function readBody(rs, limit) {
|
|
483
|
+
if (rs.method === "GET" || rs.method === "HEAD" || !rs.request.body)
|
|
484
|
+
return null;
|
|
485
|
+
const declared = Number(rs.request.headers.get("content-length") || 0);
|
|
486
|
+
if (limit > 0 && declared > limit)
|
|
487
|
+
return "too-large";
|
|
488
|
+
const reader = rs.request.body.getReader();
|
|
489
|
+
const chunks = [];
|
|
490
|
+
let total = 0;
|
|
491
|
+
for (;;) {
|
|
492
|
+
const r = await reader.read();
|
|
493
|
+
if (r.done)
|
|
494
|
+
break;
|
|
495
|
+
total += r.value.byteLength;
|
|
496
|
+
if (limit > 0 && total > limit) {
|
|
497
|
+
try {
|
|
498
|
+
await reader.cancel();
|
|
499
|
+
}
|
|
500
|
+
catch {
|
|
501
|
+
// already closed
|
|
502
|
+
}
|
|
503
|
+
return "too-large";
|
|
504
|
+
}
|
|
505
|
+
chunks.push(r.value);
|
|
506
|
+
}
|
|
507
|
+
const out = new Uint8Array(total);
|
|
508
|
+
let off = 0;
|
|
509
|
+
for (const c of chunks) {
|
|
510
|
+
out.set(c, off);
|
|
511
|
+
off += c.byteLength;
|
|
512
|
+
}
|
|
513
|
+
return out;
|
|
514
|
+
}
|
|
515
|
+
// Static layer and 404
|
|
516
|
+
function staticRouteExists(p) {
|
|
517
|
+
return staticLayer ? staticLayer.exists(p) : false;
|
|
518
|
+
}
|
|
519
|
+
/** shouldServeStatic: a concrete static file shadows dynamic routes, but never a request-time page. */
|
|
520
|
+
async function shouldServeStatic(p, page) {
|
|
521
|
+
if (!staticLayer)
|
|
522
|
+
return false;
|
|
523
|
+
if (page)
|
|
524
|
+
return staticLayer.isAsset(p);
|
|
525
|
+
return staticLayer.exists(p);
|
|
526
|
+
}
|
|
527
|
+
function redirectToCanonicalSlash(rs) {
|
|
528
|
+
const p = rs.path;
|
|
529
|
+
if (p === "" || p.endsWith("/") || isFileLikePath(p))
|
|
530
|
+
return null;
|
|
531
|
+
if (rs.method !== "GET" && rs.method !== "HEAD")
|
|
532
|
+
return null;
|
|
533
|
+
// "./" keeps a segment such as "ftp:3232235777" or "\\host" from parsing as an absolute URL.
|
|
534
|
+
let target = "./" + baseName(p) + "/";
|
|
535
|
+
if (rs.search)
|
|
536
|
+
target += rs.search;
|
|
537
|
+
rs.res.set("Location", target);
|
|
538
|
+
return finish(rs, 301, null);
|
|
539
|
+
}
|
|
540
|
+
/** Answers 404 with a not-found page; segment pages are never cached. */
|
|
541
|
+
function custom404(rs, page, status = 404) {
|
|
542
|
+
rs.res.set("Content-Type", "text/html; charset=utf-8");
|
|
543
|
+
rs.res.delete("Cache-Control");
|
|
544
|
+
rs.res.delete("Etag");
|
|
545
|
+
rs.res.delete("Last-Modified");
|
|
546
|
+
rs.res.set("Cache-Control", "no-store");
|
|
547
|
+
return finish(rs, status, page.match ? renderSegmentPage(page.html, page.match) : page.html);
|
|
548
|
+
}
|
|
549
|
+
/** The 403 or 401 response of a request whose render called forbidden() or unauthorized(). */
|
|
550
|
+
function accessDenied(rs, status, route) {
|
|
551
|
+
rs.res.delete("X-Krate-Cache");
|
|
552
|
+
const page = errorPage(rs.path, status, route);
|
|
553
|
+
if (page)
|
|
554
|
+
return custom404(rs, page, status);
|
|
555
|
+
rs.res.set("Cache-Control", "no-store");
|
|
556
|
+
return httpError(rs, status === 403 ? "403 Forbidden" : "401 Unauthorized", status);
|
|
557
|
+
}
|
|
558
|
+
/** handlerWith404: internal-path guard, cache policy, dynamic templates, static files, custom 404. */
|
|
559
|
+
async function staticHandler(rs) {
|
|
560
|
+
const p = rs.path;
|
|
561
|
+
if (isInternalOutputPath(p))
|
|
562
|
+
return notFoundText(rs);
|
|
563
|
+
if (p.endsWith(".map"))
|
|
564
|
+
rs.res.set("Content-Type", "application/json; charset=utf-8");
|
|
565
|
+
rs.res.set("Cache-Control", staticCacheControl(p, hashed));
|
|
566
|
+
let closedPattern = "";
|
|
567
|
+
if (!(await staticRouteExists(p))) {
|
|
568
|
+
for (const t of templates) {
|
|
569
|
+
if (staticOnly.has(normalizeRoutePattern(t.pattern))) {
|
|
570
|
+
if (!closedPattern && matchRoutePattern(p, t.pattern))
|
|
571
|
+
closedPattern = t.pattern;
|
|
572
|
+
continue;
|
|
573
|
+
}
|
|
574
|
+
const params = matchRoutePattern(p, t.pattern);
|
|
575
|
+
if (params) {
|
|
576
|
+
const slash = redirectToCanonicalSlash(rs);
|
|
577
|
+
if (slash)
|
|
578
|
+
return slash;
|
|
579
|
+
rs.res.set("Content-Type", "text/html; charset=utf-8");
|
|
580
|
+
return finish(rs, 200, applyDynamicRouteParams(t.html, params));
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
}
|
|
584
|
+
const wantsHTML = isHTMLDocRequest(p) || (rs.headers.get("accept") || "").includes("text/html");
|
|
585
|
+
// Conditional headers dropped by an outer layer (flash notices) must not reach the file server.
|
|
586
|
+
const sreq = rs.headers === rs.request.headers ? rs.request : new Request(rs.request.url, { method: rs.request.method, headers: rs.headers });
|
|
587
|
+
const served = staticLayer ? await staticLayer.serve(sreq, p) : null;
|
|
588
|
+
if (served && served.status !== 404)
|
|
589
|
+
return mergeStaticResponse(rs, served);
|
|
590
|
+
const page404 = wantsHTML ? errorPage(p, 404, { closed: closedPattern }) : null;
|
|
591
|
+
if (page404)
|
|
592
|
+
return custom404(rs, page404);
|
|
593
|
+
return notFoundText(rs, true);
|
|
594
|
+
}
|
|
595
|
+
/** Static responses bring their own headers; layers that ran earlier (security, cache policy) stay unless replaced. */
|
|
596
|
+
function mergeStaticResponse(rs, served) {
|
|
597
|
+
served.headers.forEach((v, k) => {
|
|
598
|
+
if (k.toLowerCase() === "set-cookie")
|
|
599
|
+
return;
|
|
600
|
+
rs.res.set(k, v);
|
|
601
|
+
});
|
|
602
|
+
return new Response(rs.method === "HEAD" ? null : served.body, { status: served.status, headers: rs.res });
|
|
603
|
+
}
|
|
604
|
+
// Pages
|
|
605
|
+
function pageMethodAllowed(rs) {
|
|
606
|
+
switch (rs.method) {
|
|
607
|
+
case "GET":
|
|
608
|
+
case "HEAD":
|
|
609
|
+
return null;
|
|
610
|
+
case "OPTIONS":
|
|
611
|
+
rs.res.set("Allow", "GET, HEAD, OPTIONS");
|
|
612
|
+
return finish(rs, 204, null);
|
|
613
|
+
}
|
|
614
|
+
rs.res.set("Allow", "GET, HEAD");
|
|
615
|
+
return httpError(rs, "method not allowed", 405);
|
|
616
|
+
}
|
|
617
|
+
const PLAIN_500 = "<!doctype html><title>500</title><h1>Internal Server Error</h1>";
|
|
618
|
+
async function pageHandler(rs) {
|
|
619
|
+
const denied = pageMethodAllowed(rs);
|
|
620
|
+
if (denied)
|
|
621
|
+
return denied;
|
|
622
|
+
if (data.pages.length === 0)
|
|
623
|
+
return staticHandler(rs);
|
|
624
|
+
let route = requestRoute(rs.path);
|
|
625
|
+
const found = findPageForRoute(route);
|
|
626
|
+
const page = found ? found.page : null;
|
|
627
|
+
if (await shouldServeStatic(rs.path, page))
|
|
628
|
+
return staticHandler(rs);
|
|
629
|
+
if (!found || !page)
|
|
630
|
+
return staticHandler(rs);
|
|
631
|
+
const slash = redirectToCanonicalSlash(rs);
|
|
632
|
+
if (slash)
|
|
633
|
+
return slash;
|
|
634
|
+
const isISR = page.mode === "isr";
|
|
635
|
+
if (page.route)
|
|
636
|
+
route = page.route;
|
|
637
|
+
const params = found.params || {};
|
|
638
|
+
const headers = headerMap(rs);
|
|
639
|
+
const query = queryOf(rs);
|
|
640
|
+
rs.res.set("Content-Type", "text/html; charset=utf-8");
|
|
641
|
+
rs.res.set("X-Content-Type-Options", "nosniff");
|
|
642
|
+
if (!isISR)
|
|
643
|
+
rs.res.set("Cache-Control", "no-store");
|
|
644
|
+
let reval = 0;
|
|
645
|
+
if (isISR) {
|
|
646
|
+
reval = page.revalidate && page.revalidate > 0 ? page.revalidate : 60;
|
|
647
|
+
}
|
|
648
|
+
const outOfOrder = page.mode === "streaming";
|
|
649
|
+
const shell = loadShell(route);
|
|
650
|
+
if (shell && shell.ok) {
|
|
651
|
+
const result = await servePageRegions(rs, shell, page, route, params, query, headers, isISR, reval, outOfOrder);
|
|
652
|
+
if (result)
|
|
653
|
+
return result;
|
|
654
|
+
}
|
|
655
|
+
// No region markers in the shell: the page is fully static. Serve the baked shell.
|
|
656
|
+
const baked = data.shells[route];
|
|
657
|
+
if (baked !== undefined)
|
|
658
|
+
return finish(rs, 200, baked);
|
|
659
|
+
return staticHandler(rs);
|
|
660
|
+
}
|
|
661
|
+
/** Renders the regions of a shell like /__krate/regions does and returns one frame per region. */
|
|
662
|
+
function startRegionRenders(page, route, shell, renderReq) {
|
|
663
|
+
const list = shell.all.map((b) => ({
|
|
664
|
+
id: b.id,
|
|
665
|
+
kind: b.kind === "suspense" && b.id === "page" ? "page" : "component",
|
|
666
|
+
}));
|
|
667
|
+
const metas = data.regions[route] || [];
|
|
668
|
+
return list.map(async (r) => {
|
|
669
|
+
try {
|
|
670
|
+
if (r.kind === "page")
|
|
671
|
+
return (await core.renderPageRegion(page, r.id, renderReq));
|
|
672
|
+
const region = metas.find((m) => m.id === r.id);
|
|
673
|
+
if (region)
|
|
674
|
+
return (await core.renderRegion(page, region, renderReq));
|
|
675
|
+
return { type: "skip", id: r.id };
|
|
676
|
+
}
|
|
677
|
+
catch (err) {
|
|
678
|
+
const message = (err && err.message) || String(err);
|
|
679
|
+
const stack = (err && typeof err.stack === "string" && err.stack) || "";
|
|
680
|
+
const digest = sha256Hex(message + "\n" + stack).slice(0, 10);
|
|
681
|
+
console.error(`[krate] region ${route}::${r.id} failed (digest ${digest}):`, err);
|
|
682
|
+
return { type: "error", id: r.id, status: 500, error: message, stack, digest };
|
|
683
|
+
}
|
|
684
|
+
});
|
|
685
|
+
}
|
|
686
|
+
async function servePageRegions(rs, shellInfo, page, route, params, query, headers, isISR, revalidate, outOfOrder) {
|
|
687
|
+
let shell = shellInfo.shell;
|
|
688
|
+
const renderReq = { route, url: route, method: "GET", headers, params, query };
|
|
689
|
+
const pending = startRegionRenders(page, route, shellInfo, renderReq);
|
|
690
|
+
if (outOfOrder && !isISR && canStreamOutOfOrder(shellInfo.all) && (!page.serverComponents || allSuspense(shellInfo.all))) {
|
|
691
|
+
return streamSiblingRegions(rs, route, shell, shellInfo, pending);
|
|
692
|
+
}
|
|
693
|
+
// Ordered assembly: wait for every region, then decide status, headers and body.
|
|
694
|
+
const regionHTML = new Map();
|
|
695
|
+
let isISRFrame = false;
|
|
696
|
+
let cacheStatus = "";
|
|
697
|
+
// The <title> and <Head> tags each region rendered, by region id.
|
|
698
|
+
const frameHead = new Map();
|
|
699
|
+
let notFound = false;
|
|
700
|
+
let denied = 0;
|
|
701
|
+
let redirect = "";
|
|
702
|
+
let renderErr = "";
|
|
703
|
+
let fatalErr = "";
|
|
704
|
+
let errStack = "";
|
|
705
|
+
let errDigest = "";
|
|
706
|
+
let noStore = false;
|
|
707
|
+
for (const frame of await Promise.all(pending)) {
|
|
708
|
+
switch (frame.type) {
|
|
709
|
+
case "region": {
|
|
710
|
+
const id = frame.id || "";
|
|
711
|
+
if (id !== "page" && (frame.notFound || frame.denied || frame.redirect)) {
|
|
712
|
+
notFound = notFound || !!frame.notFound;
|
|
713
|
+
denied = denied || frame.denied || 0;
|
|
714
|
+
if (!redirect)
|
|
715
|
+
redirect = frame.redirect || "";
|
|
716
|
+
continue;
|
|
717
|
+
}
|
|
718
|
+
if (frame.noStore)
|
|
719
|
+
noStore = true;
|
|
720
|
+
if (id === "page") {
|
|
721
|
+
isISRFrame = !!frame.cacheStatus;
|
|
722
|
+
cacheStatus = frame.cacheStatus || "";
|
|
723
|
+
notFound = !!frame.notFound;
|
|
724
|
+
denied = denied || frame.denied || 0;
|
|
725
|
+
redirect = frame.redirect || "";
|
|
726
|
+
if ((frame.status || 0) >= 500 || frame.error) {
|
|
727
|
+
renderErr = frame.error || `page-region render failed with status ${frame.status}`;
|
|
728
|
+
errStack = frame.stack || "";
|
|
729
|
+
errDigest = frame.digest || "";
|
|
730
|
+
if (frame.fatal)
|
|
731
|
+
fatalErr = renderErr;
|
|
732
|
+
continue;
|
|
733
|
+
}
|
|
734
|
+
if (frame.notFound || frame.denied)
|
|
735
|
+
continue;
|
|
736
|
+
}
|
|
737
|
+
regionHTML.set(id, frame.html || "");
|
|
738
|
+
if (frame.title || frame.head)
|
|
739
|
+
frameHead.set(id, { title: frame.title || "", head: frame.head || "" });
|
|
740
|
+
break;
|
|
741
|
+
}
|
|
742
|
+
case "error": {
|
|
743
|
+
const msg = frame.error || `region ${frame.id} render failed with status ${frame.status}`;
|
|
744
|
+
if (frame.fatal && !fatalErr)
|
|
745
|
+
fatalErr = msg;
|
|
746
|
+
if (!renderErr) {
|
|
747
|
+
renderErr = msg;
|
|
748
|
+
errStack = frame.stack || "";
|
|
749
|
+
errDigest = frame.digest || "";
|
|
750
|
+
}
|
|
751
|
+
break;
|
|
752
|
+
}
|
|
753
|
+
}
|
|
754
|
+
}
|
|
755
|
+
// A segment error page makes any failed render answer with that page
|
|
756
|
+
// instead of the baked body (build/serve.go failOnRenderErr).
|
|
757
|
+
const routeRef = { segDir: page.segDir !== undefined ? page.segDir : "" };
|
|
758
|
+
const segError = errorPage(rs.path, 500, routeRef);
|
|
759
|
+
if (segError && segError.match && renderErr && !fatalErr && !notFound && !denied && !redirect)
|
|
760
|
+
fatalErr = renderErr;
|
|
761
|
+
if (fatalErr) {
|
|
762
|
+
// A server component failed: there is no meaningful baked body, so answer 500.
|
|
763
|
+
const srvErr = newServerError(fatalErr, errStack, errDigest || sha256Hex(fatalErr + "\n" + errStack).slice(0, 10), false);
|
|
764
|
+
console.error(`[krate] Render error (${route}) [digest ${srvErr.digest}]: ${fatalErr}`);
|
|
765
|
+
if (errStack)
|
|
766
|
+
console.error(errStack);
|
|
767
|
+
rs.res.set("X-Krate-Error", "render");
|
|
768
|
+
rs.res.delete("X-Krate-Cache");
|
|
769
|
+
rs.res.set("Cache-Control", "no-store");
|
|
770
|
+
rs.res.set("Content-Type", "text/html; charset=utf-8");
|
|
771
|
+
if (segError && segError.match)
|
|
772
|
+
return finish(rs, 500, renderSegmentPage(segError.html, segError.match, srvErr));
|
|
773
|
+
return finish(rs, 500, segError ? segError.html : PLAIN_500);
|
|
774
|
+
}
|
|
775
|
+
if (notFound || denied || redirect) {
|
|
776
|
+
if (redirect)
|
|
777
|
+
return goRedirect(redirect, rs.path, rs.method, 302, rs.res);
|
|
778
|
+
if (denied)
|
|
779
|
+
return accessDenied(rs, denied, routeRef);
|
|
780
|
+
const page404 = errorPage(rs.path, 404, routeRef);
|
|
781
|
+
if (page404)
|
|
782
|
+
return custom404(rs, page404);
|
|
783
|
+
rs.res.set("Cache-Control", "no-store");
|
|
784
|
+
return notFoundText(rs);
|
|
785
|
+
}
|
|
786
|
+
if (renderErr) {
|
|
787
|
+
console.error(`[krate] Page region error (${route}): ${renderErr}`);
|
|
788
|
+
rs.res.set("X-Krate-Error", "render");
|
|
789
|
+
}
|
|
790
|
+
if (isISR && isISRFrame && cacheStatus)
|
|
791
|
+
rs.res.set("X-Krate-Cache", cacheStatus.toUpperCase());
|
|
792
|
+
if (isISR) {
|
|
793
|
+
if (noStore || renderErr) {
|
|
794
|
+
rs.res.set("Cache-Control", "private, no-store");
|
|
795
|
+
rs.res.delete("X-Krate-Cache");
|
|
796
|
+
}
|
|
797
|
+
else {
|
|
798
|
+
const r = revalidate > 0 ? revalidate : 60;
|
|
799
|
+
rs.res.set("Cache-Control", `public, s-maxage=${r}, stale-while-revalidate=${2 * r}`);
|
|
800
|
+
}
|
|
801
|
+
}
|
|
802
|
+
let html = "";
|
|
803
|
+
spliceShell(shell, shellInfo.roots, regionHTML, (c) => (html += c));
|
|
804
|
+
// The title and <Head> tags go into the head after splicing: the marker
|
|
805
|
+
// offsets belong to the baked shell. Only regions that ended up in the
|
|
806
|
+
// page count (the children of a replaced region are dropped with it).
|
|
807
|
+
if (frameHead.size > 0) {
|
|
808
|
+
const live = new Set();
|
|
809
|
+
const walk = (children) => {
|
|
810
|
+
for (const b of children) {
|
|
811
|
+
if (regionHTML.has(b.id))
|
|
812
|
+
live.add(b.id);
|
|
813
|
+
else if (b.kind === "suspense")
|
|
814
|
+
walk(b.children);
|
|
815
|
+
}
|
|
816
|
+
};
|
|
817
|
+
walk(shellInfo.roots);
|
|
818
|
+
let title = "";
|
|
819
|
+
let head = "";
|
|
820
|
+
for (const b of shellInfo.all) {
|
|
821
|
+
const h = live.has(b.id) ? frameHead.get(b.id) : undefined;
|
|
822
|
+
if (!h)
|
|
823
|
+
continue;
|
|
824
|
+
if (h.title)
|
|
825
|
+
title = h.title;
|
|
826
|
+
head += h.head;
|
|
827
|
+
}
|
|
828
|
+
html = mergeHead(html, title, head);
|
|
829
|
+
}
|
|
830
|
+
return finish(rs, 200, html);
|
|
831
|
+
}
|
|
832
|
+
// A <Head> inside a streamed Suspense region renders after the head of the
|
|
833
|
+
// response has been sent. It is applied by the region's script instead, which
|
|
834
|
+
// crawlers that do not run scripts never see: warn once per region.
|
|
835
|
+
const warnedStreamedHead = new Set();
|
|
836
|
+
function warnStreamedHead(route, id) {
|
|
837
|
+
const key = route + "::" + id;
|
|
838
|
+
if (warnedStreamedHead.has(key))
|
|
839
|
+
return;
|
|
840
|
+
warnedStreamedHead.add(key);
|
|
841
|
+
console.warn(`[krate] <Head> inside the streamed region ${id} of ${route} reaches the document only through the region's script: ` +
|
|
842
|
+
"crawlers that do not run scripts will not see it. Move it into the page component outside <Suspense>.");
|
|
843
|
+
}
|
|
844
|
+
/** Sibling Suspense regions stream in completion order after the shell. */
|
|
845
|
+
function streamSiblingRegions(rs, route, shell, shellInfo, pending) {
|
|
846
|
+
const [prefix, tail] = splitBodyScripts(shell);
|
|
847
|
+
const enc = new TextEncoder();
|
|
848
|
+
const method = rs.method;
|
|
849
|
+
const body = new ReadableStream({
|
|
850
|
+
async start(controller) {
|
|
851
|
+
controller.enqueue(enc.encode(prefix));
|
|
852
|
+
await Promise.all(pending.map(async (p) => {
|
|
853
|
+
const f = await p;
|
|
854
|
+
if (f.type !== "region" || !f.id)
|
|
855
|
+
return;
|
|
856
|
+
if (f.notFound || f.denied || f.redirect || f.fatal || (f.status || 0) >= 500 || f.error) {
|
|
857
|
+
// The shell is already on the wire: keep the baked fallback for this region.
|
|
858
|
+
if (f.error)
|
|
859
|
+
console.error(`[krate] region ${f.id} failed: ${f.error}`);
|
|
860
|
+
return;
|
|
861
|
+
}
|
|
862
|
+
if (!f.html && !f.head && !f.title)
|
|
863
|
+
return;
|
|
864
|
+
if (f.head || f.title)
|
|
865
|
+
warnStreamedHead(route, f.id);
|
|
866
|
+
controller.enqueue(enc.encode(regionReplaceScript(f.id, f.html || "", f.head, f.title)));
|
|
867
|
+
}));
|
|
868
|
+
controller.enqueue(enc.encode(tail));
|
|
869
|
+
controller.close();
|
|
870
|
+
},
|
|
871
|
+
});
|
|
872
|
+
void shellInfo;
|
|
873
|
+
if (method === "HEAD")
|
|
874
|
+
return new Response(null, { status: 200, headers: rs.res });
|
|
875
|
+
return new Response(body, { status: 200, headers: rs.res });
|
|
876
|
+
}
|
|
877
|
+
// Redirects and rewrites
|
|
878
|
+
async function redirectRewriteHandler(rs) {
|
|
879
|
+
const p = rs.path;
|
|
880
|
+
for (const rd of cfg.redirects) {
|
|
881
|
+
if (matchRedirect(p, rd.source)) {
|
|
882
|
+
const dest = rewriteDestination(p, rd.source, rd.destination);
|
|
883
|
+
return goRedirect(dest, p, rs.method, rd.permanent ? 301 : 302, rs.res);
|
|
884
|
+
}
|
|
885
|
+
}
|
|
886
|
+
for (const rw of cfg.rewrites) {
|
|
887
|
+
if (matchRedirect(p, rw.source)) {
|
|
888
|
+
const rewritten = rewriteDestination(p, rw.source, rw.destination);
|
|
889
|
+
rs.path = rewriteTargetPath(safeDecode(rewritten));
|
|
890
|
+
break;
|
|
891
|
+
}
|
|
892
|
+
}
|
|
893
|
+
return pageHandler(rs);
|
|
894
|
+
}
|
|
895
|
+
// API routes
|
|
896
|
+
const apiKeys = new Set(data.apiRoutes);
|
|
897
|
+
const apiDirs = new Set(); // "" and every directory prefix
|
|
898
|
+
apiDirs.add("");
|
|
899
|
+
for (const k of data.apiRoutes) {
|
|
900
|
+
const segs = k.split("/");
|
|
901
|
+
for (let i = 1; i < segs.length; i++)
|
|
902
|
+
apiDirs.add(segs.slice(0, i).join("/"));
|
|
903
|
+
}
|
|
904
|
+
function isDynamicSegment(name) {
|
|
905
|
+
return name.startsWith("[") && name.endsWith("]") && !name.startsWith("[...") && !name.startsWith("[[...");
|
|
906
|
+
}
|
|
907
|
+
function isCatchAllSegment(name) {
|
|
908
|
+
return name.startsWith("[...") || name.startsWith("[[...");
|
|
909
|
+
}
|
|
910
|
+
/** Directory entries of the virtual API tree, in a stable order. */
|
|
911
|
+
function apiEntries(dir) {
|
|
912
|
+
const prefix = dir === "" ? "" : dir + "/";
|
|
913
|
+
const out = new Map();
|
|
914
|
+
for (const k of data.apiRoutes) {
|
|
915
|
+
if (!k.startsWith(prefix))
|
|
916
|
+
continue;
|
|
917
|
+
const rest = k.slice(prefix.length);
|
|
918
|
+
const i = rest.indexOf("/");
|
|
919
|
+
if (i < 0)
|
|
920
|
+
out.set(rest, out.get(rest) || false);
|
|
921
|
+
else
|
|
922
|
+
out.set(rest.slice(0, i), true);
|
|
923
|
+
}
|
|
924
|
+
return [...out].sort((a, b) => strCmp(a[0], b[0])).map(([name, isDir]) => ({ name, isDir }));
|
|
925
|
+
}
|
|
926
|
+
function strCmp(a, b) {
|
|
927
|
+
return a < b ? -1 : a > b ? 1 : 0;
|
|
928
|
+
}
|
|
929
|
+
function resolveDynamicAPIDir(dir, segs) {
|
|
930
|
+
if (!apiDirs.has(dir))
|
|
931
|
+
return "";
|
|
932
|
+
const join = (a, b) => (a === "" ? b : a + "/" + b);
|
|
933
|
+
if (segs.length === 0) {
|
|
934
|
+
const idx = join(dir, "index");
|
|
935
|
+
return apiKeys.has(idx) ? idx : "";
|
|
936
|
+
}
|
|
937
|
+
const next = join(dir, segs[0]);
|
|
938
|
+
if (apiDirs.has(next)) {
|
|
939
|
+
const hit = resolveDynamicAPIDir(next, segs.slice(1));
|
|
940
|
+
if (hit)
|
|
941
|
+
return hit;
|
|
942
|
+
}
|
|
943
|
+
for (const e of apiEntries(dir)) {
|
|
944
|
+
const full = join(dir, e.name);
|
|
945
|
+
if (e.isDir) {
|
|
946
|
+
if (isCatchAllSegment(e.name) && segs.length > 0) {
|
|
947
|
+
const idx = join(full, "index");
|
|
948
|
+
if (apiKeys.has(idx))
|
|
949
|
+
return idx;
|
|
950
|
+
}
|
|
951
|
+
if (isDynamicSegment(e.name) && segs.length > 0) {
|
|
952
|
+
const hit = resolveDynamicAPIDir(full, segs.slice(1));
|
|
953
|
+
if (hit)
|
|
954
|
+
return hit;
|
|
955
|
+
}
|
|
956
|
+
continue;
|
|
957
|
+
}
|
|
958
|
+
if (isCatchAllSegment(e.name) && (segs.length > 0 || e.name.startsWith("[[...")))
|
|
959
|
+
return full;
|
|
960
|
+
if (segs.length === 1 && isDynamicSegment(e.name))
|
|
961
|
+
return full;
|
|
962
|
+
}
|
|
963
|
+
return "";
|
|
964
|
+
}
|
|
965
|
+
/** Port of APIRouteRuntime.resolveAPIFile over the inlined route keys. */
|
|
966
|
+
function resolveAPIFile(relPath) {
|
|
967
|
+
let rel = safeDecode(relPath).split("/").filter((s) => s !== "").join("/");
|
|
968
|
+
if (rel === "")
|
|
969
|
+
rel = "index";
|
|
970
|
+
if (rel.includes("\0") || rel.includes("\\"))
|
|
971
|
+
return "";
|
|
972
|
+
if (rel.split("/").includes(".."))
|
|
973
|
+
return "";
|
|
974
|
+
if (apiKeys.has(rel))
|
|
975
|
+
return rel;
|
|
976
|
+
if (apiKeys.has(rel + "/index"))
|
|
977
|
+
return rel + "/index";
|
|
978
|
+
return resolveDynamicAPIDir("", rel.split("/"));
|
|
979
|
+
}
|
|
980
|
+
function apiRouteParams(file, reqPath) {
|
|
981
|
+
let rel = file;
|
|
982
|
+
if (rel === "index")
|
|
983
|
+
rel = "";
|
|
984
|
+
else if (rel.endsWith("/index"))
|
|
985
|
+
rel = rel.slice(0, -6);
|
|
986
|
+
const fileSegs = rel === "" ? [] : rel.split("/");
|
|
987
|
+
const rawPath = reqPath.replace(/^\/api/, "");
|
|
988
|
+
const pathSegs = rawPath === "" || rawPath === "/" ? [] : rawPath.replace(/^\/+|\/+$/g, "").split("/").map(safeDecode);
|
|
989
|
+
const params = {};
|
|
990
|
+
for (let i = 0; i < fileSegs.length; i++) {
|
|
991
|
+
const seg = fileSegs[i];
|
|
992
|
+
if (seg.startsWith("[[...") && seg.endsWith("]]")) {
|
|
993
|
+
if (i < pathSegs.length)
|
|
994
|
+
params[seg.slice(5, -2)] = pathSegs.slice(i).join("/");
|
|
995
|
+
return params;
|
|
996
|
+
}
|
|
997
|
+
if (seg.startsWith("[...") && seg.endsWith("]")) {
|
|
998
|
+
params[seg.slice(4, -1)] = pathSegs.slice(Math.min(i, pathSegs.length)).join("/");
|
|
999
|
+
return params;
|
|
1000
|
+
}
|
|
1001
|
+
if (seg.startsWith("[") && seg.endsWith("]") && i < pathSegs.length)
|
|
1002
|
+
params[seg.slice(1, -1)] = pathSegs[i];
|
|
1003
|
+
}
|
|
1004
|
+
return params;
|
|
1005
|
+
}
|
|
1006
|
+
function jsonResponse(rs, status, obj) {
|
|
1007
|
+
rs.res.set("Content-Type", "application/json");
|
|
1008
|
+
return finish(rs, status, JSON.stringify(obj));
|
|
1009
|
+
}
|
|
1010
|
+
function apiFailure(rs, status, allow) {
|
|
1011
|
+
rs.res.set("Content-Type", "application/json");
|
|
1012
|
+
rs.res.set("Cache-Control", "no-store");
|
|
1013
|
+
if (status === 404)
|
|
1014
|
+
return finish(rs, 404, '{"error":"API Route Not Found"}');
|
|
1015
|
+
if (status === 403)
|
|
1016
|
+
return finish(rs, 403, '{"error":"Forbidden"}');
|
|
1017
|
+
if (status === 401)
|
|
1018
|
+
return finish(rs, 401, '{"error":"Unauthorized"}');
|
|
1019
|
+
if (status === 405) {
|
|
1020
|
+
rs.res.set("Allow", (allow || []).join(", "));
|
|
1021
|
+
return finish(rs, 405, '{"error":"Method Not Allowed"}');
|
|
1022
|
+
}
|
|
1023
|
+
if (status === 413)
|
|
1024
|
+
return finish(rs, 413, '{"error":"Request Entity Too Large"}');
|
|
1025
|
+
return finish(rs, status < 400 ? 500 : status, '{"error":"Internal Server Error"}');
|
|
1026
|
+
}
|
|
1027
|
+
function allowList(mod) {
|
|
1028
|
+
const out = KRATE_METHODS.filter((m) => typeof mod[m] === "function");
|
|
1029
|
+
if (out.includes("GET") && !out.includes("HEAD"))
|
|
1030
|
+
out.push("HEAD");
|
|
1031
|
+
if (out.length && !out.includes("OPTIONS"))
|
|
1032
|
+
out.push("OPTIONS");
|
|
1033
|
+
return out;
|
|
1034
|
+
}
|
|
1035
|
+
function isForeignResponse(v) {
|
|
1036
|
+
return (v && typeof v === "object" && typeof v.status === "number" && !Array.isArray(v) &&
|
|
1037
|
+
(typeof v.text === "function" || typeof v.arrayBuffer === "function" || "body" in v || "headers" in v));
|
|
1038
|
+
}
|
|
1039
|
+
async function toResponse(v) {
|
|
1040
|
+
if (v instanceof Response)
|
|
1041
|
+
return v;
|
|
1042
|
+
if (isForeignResponse(v)) {
|
|
1043
|
+
let headers;
|
|
1044
|
+
if (!v.headers)
|
|
1045
|
+
headers = new Headers();
|
|
1046
|
+
else if (v.headers instanceof Headers)
|
|
1047
|
+
headers = v.headers;
|
|
1048
|
+
else if (typeof v.headers.entries === "function")
|
|
1049
|
+
headers = new Headers(v.headers.entries());
|
|
1050
|
+
else
|
|
1051
|
+
headers = new Headers(v.headers);
|
|
1052
|
+
const bodyP = typeof v.arrayBuffer === "function" ? v.arrayBuffer() : typeof v.text === "function" ? v.text() : v.body;
|
|
1053
|
+
const b = await bodyP;
|
|
1054
|
+
const empty = v.status === 204 || v.status === 304 || b === undefined || b === null || b === "" || b.byteLength === 0;
|
|
1055
|
+
return new Response(empty ? null : b, { status: v.status < 200 ? 200 : v.status, headers });
|
|
1056
|
+
}
|
|
1057
|
+
if (v === undefined || v === null)
|
|
1058
|
+
return new Response(null, { status: 204 });
|
|
1059
|
+
const json = JSON.stringify(v);
|
|
1060
|
+
if (json === undefined)
|
|
1061
|
+
return new Response(null, { status: 204 });
|
|
1062
|
+
return new Response(json, { status: 200, headers: { "content-type": "application/json" } });
|
|
1063
|
+
}
|
|
1064
|
+
// Revalidation, applied to this instance's caches.
|
|
1065
|
+
// Other instances' revalidations: their shared-cache entries are gone already,
|
|
1066
|
+
// so only this instance's in-memory caches need clearing.
|
|
1067
|
+
void sharedCache.ready.then(async (adapter) => {
|
|
1068
|
+
if (!adapter)
|
|
1069
|
+
return;
|
|
1070
|
+
sharedAdapter = adapter;
|
|
1071
|
+
try {
|
|
1072
|
+
await adapter.subscribe(INVALIDATE_CHANNEL, (message) => {
|
|
1073
|
+
if (message === "*") {
|
|
1074
|
+
core.devInvalidate("");
|
|
1075
|
+
return;
|
|
1076
|
+
}
|
|
1077
|
+
try {
|
|
1078
|
+
const m = JSON.parse(message);
|
|
1079
|
+
if (m.origin === instanceId)
|
|
1080
|
+
return;
|
|
1081
|
+
void core.applyInternalOp("cache-invalidate", { targets: m.targets || [], tags: m.tags || [] });
|
|
1082
|
+
}
|
|
1083
|
+
catch {
|
|
1084
|
+
/* not ours */
|
|
1085
|
+
}
|
|
1086
|
+
});
|
|
1087
|
+
}
|
|
1088
|
+
catch (err) {
|
|
1089
|
+
console.warn(`[krate] could not subscribe to cache invalidations: ${err?.message || err}`);
|
|
1090
|
+
}
|
|
1091
|
+
});
|
|
1092
|
+
async function applyRevalidation(payload) {
|
|
1093
|
+
const revalidated = [];
|
|
1094
|
+
const skipped = [];
|
|
1095
|
+
const targets = [];
|
|
1096
|
+
for (const p of payload.paths) {
|
|
1097
|
+
const r = resolveRevalidatePath(p.path, p.type || "page");
|
|
1098
|
+
if (r.error) {
|
|
1099
|
+
skipped.push({ target: p.path, reason: r.error });
|
|
1100
|
+
continue;
|
|
1101
|
+
}
|
|
1102
|
+
skipped.push(...r.skipped);
|
|
1103
|
+
if (r.targets.length) {
|
|
1104
|
+
targets.push(...r.targets);
|
|
1105
|
+
revalidated.push({ target: p.path, kind: "path", routes: r.targets.map((t) => t.route) });
|
|
1106
|
+
}
|
|
1107
|
+
}
|
|
1108
|
+
const tags = payload.tags.map((t) => t.trim()).filter(Boolean);
|
|
1109
|
+
for (const t of tags)
|
|
1110
|
+
revalidated.push({ target: t, kind: "tag" });
|
|
1111
|
+
if (targets.length || tags.length) {
|
|
1112
|
+
await sharedCache.ready;
|
|
1113
|
+
await core.applyInternalOp("cache-invalidate", { targets, tags });
|
|
1114
|
+
if (sharedAdapter) {
|
|
1115
|
+
// The shared store is already purged; tell the other instances to drop
|
|
1116
|
+
// what they hold in memory (their region caches).
|
|
1117
|
+
try {
|
|
1118
|
+
await sharedAdapter.publish(INVALIDATE_CHANNEL, JSON.stringify({ origin: instanceId, targets, tags }));
|
|
1119
|
+
}
|
|
1120
|
+
catch (err) {
|
|
1121
|
+
console.warn(`[krate] could not tell the other instances about the revalidation: ${err?.message || err}`);
|
|
1122
|
+
}
|
|
1123
|
+
}
|
|
1124
|
+
else if (target !== "node") {
|
|
1125
|
+
for (const r of revalidated) {
|
|
1126
|
+
skipped.push({
|
|
1127
|
+
target: r.target,
|
|
1128
|
+
reason: `${target} runs many instances: only this instance's caches were invalidated; other instances keep serving their cached copy until it expires (add a shared cache store with createKrateHandler({ isrStore }) or redeploy)`,
|
|
1129
|
+
});
|
|
1130
|
+
}
|
|
1131
|
+
}
|
|
1132
|
+
}
|
|
1133
|
+
return { revalidated, skipped };
|
|
1134
|
+
}
|
|
1135
|
+
function routeUnder(route, prefix) {
|
|
1136
|
+
if (prefix === "/")
|
|
1137
|
+
return true;
|
|
1138
|
+
const rs = route.replace(/^\/+|\/+$/g, "").split("/");
|
|
1139
|
+
const ps = prefix.replace(/^\/+|\/+$/g, "").split("/");
|
|
1140
|
+
if (rs.length < ps.length)
|
|
1141
|
+
return false;
|
|
1142
|
+
for (let i = 0; i < ps.length; i++) {
|
|
1143
|
+
if (rs[i] === ps[i])
|
|
1144
|
+
continue;
|
|
1145
|
+
if (rs[i].startsWith("[") && rs[i].endsWith("]"))
|
|
1146
|
+
continue;
|
|
1147
|
+
return false;
|
|
1148
|
+
}
|
|
1149
|
+
return true;
|
|
1150
|
+
}
|
|
1151
|
+
function resolveRevalidatePath(reqPath, type) {
|
|
1152
|
+
const none = { targets: [], skipped: [] };
|
|
1153
|
+
let p = reqPath;
|
|
1154
|
+
const qi = p.search(/[?#]/);
|
|
1155
|
+
if (qi >= 0)
|
|
1156
|
+
p = p.slice(0, qi);
|
|
1157
|
+
if (!p.startsWith("/"))
|
|
1158
|
+
return { ...none, error: 'path must start with "/"' };
|
|
1159
|
+
p = cleanPath(p);
|
|
1160
|
+
if (p !== "/")
|
|
1161
|
+
p = p.replace(/\/+$/, "");
|
|
1162
|
+
if (type !== "page" && type !== "layout")
|
|
1163
|
+
return { ...none, error: `unknown revalidatePath type "${type}" (want "page" or "layout")` };
|
|
1164
|
+
const staticSkip = (route) => ({
|
|
1165
|
+
target: route,
|
|
1166
|
+
reason: `route ${route} is static (SSG): its HTML was baked at build time and cannot be revalidated at runtime; make the page ISR (export const revalidate = N) or SSR (export const dynamic = "force-dynamic"), or rebuild`,
|
|
1167
|
+
});
|
|
1168
|
+
const requestTime = (m) => m === "ssr" || m === "isr" || m === "streaming";
|
|
1169
|
+
const targets = [];
|
|
1170
|
+
const skipped = [];
|
|
1171
|
+
const add = (pm, params) => {
|
|
1172
|
+
if (!requestTime(pm.mode))
|
|
1173
|
+
skipped.push(staticSkip(pm.route));
|
|
1174
|
+
else
|
|
1175
|
+
targets.push({ route: pm.route, params });
|
|
1176
|
+
};
|
|
1177
|
+
if (type === "layout") {
|
|
1178
|
+
for (const pm of [...data.allPages].sort((a, b) => strCmp(a.route, b.route)))
|
|
1179
|
+
if (routeUnder(pm.route, p))
|
|
1180
|
+
add(pm);
|
|
1181
|
+
if (targets.length === 0 && skipped.length === 0)
|
|
1182
|
+
return { ...none, error: `no page at or below ${p}` };
|
|
1183
|
+
return { targets, skipped };
|
|
1184
|
+
}
|
|
1185
|
+
for (const pm of data.allPages) {
|
|
1186
|
+
if (pm.route === p) {
|
|
1187
|
+
add(pm);
|
|
1188
|
+
return { targets, skipped };
|
|
1189
|
+
}
|
|
1190
|
+
}
|
|
1191
|
+
const dyn = data.allPages.filter((pm) => pm.route.includes("[")).sort((a, b) => (a.route.match(/\[/g) || []).length - (b.route.match(/\[/g) || []).length);
|
|
1192
|
+
for (const pm of dyn) {
|
|
1193
|
+
const params = matchRoutePattern(p, pm.route);
|
|
1194
|
+
if (params) {
|
|
1195
|
+
if (!requestTime(pm.mode))
|
|
1196
|
+
return { targets: [], skipped: [{ target: p, reason: staticSkip(pm.route).reason }] };
|
|
1197
|
+
add(pm, params);
|
|
1198
|
+
return { targets, skipped };
|
|
1199
|
+
}
|
|
1200
|
+
}
|
|
1201
|
+
return { ...none, error: `no page matches ${p}` };
|
|
1202
|
+
}
|
|
1203
|
+
async function flushRevalidate(scope) {
|
|
1204
|
+
if (!scope || (scope.paths.length === 0 && scope.tags.length === 0))
|
|
1205
|
+
return null;
|
|
1206
|
+
const payload = { paths: scope.paths.slice(), tags: Array.from(new Set(scope.tags)) };
|
|
1207
|
+
scope.paths.length = 0;
|
|
1208
|
+
scope.tags.length = 0;
|
|
1209
|
+
const result = await applyRevalidation(payload);
|
|
1210
|
+
for (const s of result.skipped)
|
|
1211
|
+
console.warn(`[krate] revalidation skipped for ${s.target}: ${s.reason}`);
|
|
1212
|
+
return payload;
|
|
1213
|
+
}
|
|
1214
|
+
async function apiHandler(rs) {
|
|
1215
|
+
const limit = cfg.maxAPIBodyBytes;
|
|
1216
|
+
const relPath = rs.path.replace(/^\/api/, "") || "/index";
|
|
1217
|
+
const file = resolveAPIFile(relPath);
|
|
1218
|
+
if (!file)
|
|
1219
|
+
return apiFailure(rs, 404);
|
|
1220
|
+
const body = await readBody(rs, limit);
|
|
1221
|
+
if (body === "too-large")
|
|
1222
|
+
return apiFailure(rs, 413);
|
|
1223
|
+
const mod = modules.api && modules.api[file];
|
|
1224
|
+
if (!mod) {
|
|
1225
|
+
console.error(`[krate] API route ${file} is not part of this deployment`);
|
|
1226
|
+
return apiFailure(rs, 500);
|
|
1227
|
+
}
|
|
1228
|
+
const method = rs.method.toUpperCase();
|
|
1229
|
+
let fn = mod[method];
|
|
1230
|
+
let named = typeof fn === "function";
|
|
1231
|
+
let headOnly = false;
|
|
1232
|
+
if (!named && method === "HEAD" && typeof mod.GET === "function") {
|
|
1233
|
+
fn = mod.GET;
|
|
1234
|
+
named = true;
|
|
1235
|
+
headOnly = true;
|
|
1236
|
+
}
|
|
1237
|
+
if (!named) {
|
|
1238
|
+
if (typeof mod.default === "function")
|
|
1239
|
+
fn = mod.default;
|
|
1240
|
+
else {
|
|
1241
|
+
const allow = allowList(mod);
|
|
1242
|
+
if (method === "OPTIONS" && allow.length) {
|
|
1243
|
+
rs.res.set("Allow", allow.join(", "));
|
|
1244
|
+
return finish(rs, 204, null);
|
|
1245
|
+
}
|
|
1246
|
+
if (allow.length)
|
|
1247
|
+
return apiFailure(rs, 405, allow);
|
|
1248
|
+
console.error(`[krate] API route ${file} must export a handler function (GET, POST, etc. or default).`);
|
|
1249
|
+
return apiFailure(rs, 500);
|
|
1250
|
+
}
|
|
1251
|
+
}
|
|
1252
|
+
if (!named && fn.length >= 2) {
|
|
1253
|
+
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.`);
|
|
1254
|
+
return apiFailure(rs, 500);
|
|
1255
|
+
}
|
|
1256
|
+
try {
|
|
1257
|
+
const request = attachCookies(new Request(fullURL(rs), {
|
|
1258
|
+
method: rs.method,
|
|
1259
|
+
headers: new Headers(rs.request.headers),
|
|
1260
|
+
body: body && body.byteLength > 0 ? body : undefined,
|
|
1261
|
+
signal: rs.request.signal,
|
|
1262
|
+
}));
|
|
1263
|
+
const scope = { kind: "api", paths: [], tags: [] };
|
|
1264
|
+
const out = await revalidateStore.run(scope, async () => toResponse(await fn(request, { params: apiRouteParams(file, rs.path) })));
|
|
1265
|
+
await flushRevalidate(scope);
|
|
1266
|
+
writeHeaderPairs(rs.res, headerPairs(out.headers));
|
|
1267
|
+
const status = out.status < 100 || out.status > 999 ? 502 : out.status;
|
|
1268
|
+
if (headOnly || rs.method === "HEAD" || !out.body || NO_BODY_STATUS.has(status)) {
|
|
1269
|
+
if (out.body)
|
|
1270
|
+
void out.body.cancel().catch(() => { });
|
|
1271
|
+
return finish(rs, status, null);
|
|
1272
|
+
}
|
|
1273
|
+
return new Response(out.body, { status, headers: rs.res });
|
|
1274
|
+
}
|
|
1275
|
+
catch (err) {
|
|
1276
|
+
// notFound(), forbidden() and unauthorized() end the request with that status.
|
|
1277
|
+
const fallback = httpFallbackStatus(err);
|
|
1278
|
+
if (fallback === 403 || fallback === 401)
|
|
1279
|
+
return apiFailure(rs, fallback);
|
|
1280
|
+
if (fallback === 404) {
|
|
1281
|
+
rs.res.set("Content-Type", "application/json");
|
|
1282
|
+
rs.res.set("Cache-Control", "no-store");
|
|
1283
|
+
return finish(rs, 404, '{"error":"Not Found"}');
|
|
1284
|
+
}
|
|
1285
|
+
console.error(`[krate] API error (${rs.method} ${rs.path}): ${(err && err.stack) || err}`);
|
|
1286
|
+
return apiFailure(rs, 500);
|
|
1287
|
+
}
|
|
1288
|
+
}
|
|
1289
|
+
// Server actions
|
|
1290
|
+
const actionById = new Map(data.actions.map((a) => [a.id, a]));
|
|
1291
|
+
const ACTION_COOKIE_NAME = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
|
|
1292
|
+
function serializeActionCookie(name, value, opts) {
|
|
1293
|
+
const o = opts || {};
|
|
1294
|
+
if (!ACTION_COOKIE_NAME.test(name))
|
|
1295
|
+
throw new TypeError("invalid cookie name: " + name);
|
|
1296
|
+
let s = name + "=" + encodeURIComponent(String(value));
|
|
1297
|
+
const p = o.path === undefined ? "/" : String(o.path);
|
|
1298
|
+
if (p && !/[;\r\n]/.test(p))
|
|
1299
|
+
s += "; Path=" + p;
|
|
1300
|
+
if (o.domain && !/[;\r\n]/.test(String(o.domain)))
|
|
1301
|
+
s += "; Domain=" + o.domain;
|
|
1302
|
+
if (typeof o.maxAge === "number" && isFinite(o.maxAge))
|
|
1303
|
+
s += "; Max-Age=" + Math.floor(o.maxAge);
|
|
1304
|
+
if (o.expires instanceof Date)
|
|
1305
|
+
s += "; Expires=" + o.expires.toUTCString();
|
|
1306
|
+
if (o.httpOnly !== false)
|
|
1307
|
+
s += "; HttpOnly";
|
|
1308
|
+
const same = o.sameSite === undefined ? "Lax" : o.sameSite;
|
|
1309
|
+
const sameText = same ? (same === true ? "Strict" : String(same).replace(/[^A-Za-z]/g, "")) : "";
|
|
1310
|
+
// Browsers drop SameSite=None cookies that are not Secure.
|
|
1311
|
+
if (o.secure || sameText.toLowerCase() === "none")
|
|
1312
|
+
s += "; Secure";
|
|
1313
|
+
if (sameText)
|
|
1314
|
+
s += "; SameSite=" + sameText;
|
|
1315
|
+
return s;
|
|
1316
|
+
}
|
|
1317
|
+
function parseActionCookies(header) {
|
|
1318
|
+
const jar = new Map();
|
|
1319
|
+
for (const part of String(header || "").split(";")) {
|
|
1320
|
+
const i = part.indexOf("=");
|
|
1321
|
+
if (i <= 0)
|
|
1322
|
+
continue;
|
|
1323
|
+
const name = part.slice(0, i).trim();
|
|
1324
|
+
if (!name || jar.has(name))
|
|
1325
|
+
continue;
|
|
1326
|
+
let value = part.slice(i + 1).trim();
|
|
1327
|
+
if (value.startsWith('"') && value.endsWith('"'))
|
|
1328
|
+
value = value.slice(1, -1);
|
|
1329
|
+
try {
|
|
1330
|
+
value = decodeURIComponent(value);
|
|
1331
|
+
}
|
|
1332
|
+
catch {
|
|
1333
|
+
// keep the raw value
|
|
1334
|
+
}
|
|
1335
|
+
jar.set(name, value);
|
|
1336
|
+
}
|
|
1337
|
+
return jar;
|
|
1338
|
+
}
|
|
1339
|
+
function makeActionContext(headers, id, urlPath) {
|
|
1340
|
+
const jar = parseActionCookies(headers.get("cookie"));
|
|
1341
|
+
const setCookies = [];
|
|
1342
|
+
// Cookies set over https are Secure unless the action says otherwise.
|
|
1343
|
+
const https = isHTTPSRequest(headers);
|
|
1344
|
+
const withSecure = (opts) => Object.assign({}, opts, { secure: opts && opts.secure !== undefined ? opts.secure : https });
|
|
1345
|
+
const cookies = {
|
|
1346
|
+
get(name) {
|
|
1347
|
+
return jar.get(name);
|
|
1348
|
+
},
|
|
1349
|
+
getAll() {
|
|
1350
|
+
return Array.from(jar, ([name, value]) => ({ name, value }));
|
|
1351
|
+
},
|
|
1352
|
+
has(name) {
|
|
1353
|
+
return jar.has(name);
|
|
1354
|
+
},
|
|
1355
|
+
set(name, value, opts) {
|
|
1356
|
+
setCookies.push(serializeActionCookie(name, value, withSecure(opts)));
|
|
1357
|
+
jar.set(name, String(value));
|
|
1358
|
+
},
|
|
1359
|
+
delete(name, opts) {
|
|
1360
|
+
setCookies.push(serializeActionCookie(name, "", withSecure(Object.assign({}, opts, { maxAge: 0 }))));
|
|
1361
|
+
jar.delete(name);
|
|
1362
|
+
},
|
|
1363
|
+
};
|
|
1364
|
+
return { actionId: id, url: urlPath, method: "POST", headers, cookies, setCookies };
|
|
1365
|
+
}
|
|
1366
|
+
function safeActionRedirect(value) {
|
|
1367
|
+
if (typeof value !== "string")
|
|
1368
|
+
return "";
|
|
1369
|
+
const to = value.trim();
|
|
1370
|
+
if (!to || to.charAt(0) !== "/" || to.charAt(1) === "/" || to.indexOf("\\") !== -1)
|
|
1371
|
+
return "";
|
|
1372
|
+
if (/[\u0000-\u001f\u007f]/.test(to))
|
|
1373
|
+
return "";
|
|
1374
|
+
return to;
|
|
1375
|
+
}
|
|
1376
|
+
function sanitizeActionReturn(value, rs) {
|
|
1377
|
+
value = value.trim();
|
|
1378
|
+
if (!value)
|
|
1379
|
+
return "";
|
|
1380
|
+
if (value.startsWith("/") && !value.startsWith("//") && !/[\\\r\n]/.test(value) && !/[\u0000-\u001f\u007f]/.test(value))
|
|
1381
|
+
return value;
|
|
1382
|
+
let u;
|
|
1383
|
+
try {
|
|
1384
|
+
u = new URL(value);
|
|
1385
|
+
}
|
|
1386
|
+
catch {
|
|
1387
|
+
return "";
|
|
1388
|
+
}
|
|
1389
|
+
if (!u.host)
|
|
1390
|
+
return "";
|
|
1391
|
+
if (u.host.toLowerCase() !== requestHost(rs).toLowerCase() || (u.protocol !== "http:" && u.protocol !== "https:"))
|
|
1392
|
+
return "";
|
|
1393
|
+
return u.pathname + u.search;
|
|
1394
|
+
}
|
|
1395
|
+
function actionHeaders(type, cookies) {
|
|
1396
|
+
const h = new Headers({ "content-type": type, "cache-control": "no-store" });
|
|
1397
|
+
for (const c of cookies || [])
|
|
1398
|
+
h.append("set-cookie", c);
|
|
1399
|
+
return h;
|
|
1400
|
+
}
|
|
1401
|
+
function actionFail(status, message, digest, cookies) {
|
|
1402
|
+
const error = { message };
|
|
1403
|
+
if (digest)
|
|
1404
|
+
error.digest = digest;
|
|
1405
|
+
return new Response(JSON.stringify({ ok: false, error }), { status, headers: actionHeaders("application/json", cookies) });
|
|
1406
|
+
}
|
|
1407
|
+
/**
|
|
1408
|
+
* actionFallback answers an action that called notFound(), forbidden() or
|
|
1409
|
+
* unauthorized(): JSON for the fetch client, else the nearest segment page of
|
|
1410
|
+
* the page the form was posted from (the sanitized return path).
|
|
1411
|
+
*/
|
|
1412
|
+
function actionFallback(rs, status, fetchMode, cookies, returnTo) {
|
|
1413
|
+
const label = status === 403 ? "Forbidden" : status === 401 ? "Unauthorized" : "Not Found";
|
|
1414
|
+
if (fetchMode)
|
|
1415
|
+
return actionFail(status, label, undefined, cookies);
|
|
1416
|
+
const headers = actionHeaders("text/html; charset=utf-8", cookies);
|
|
1417
|
+
headers.set("Cache-Control", "no-store");
|
|
1418
|
+
let from = "/";
|
|
1419
|
+
try {
|
|
1420
|
+
if (returnTo)
|
|
1421
|
+
from = safeDecode(new URL(returnTo, "http://x").pathname);
|
|
1422
|
+
if (basePath && (from === basePath || from.startsWith(basePath + "/")))
|
|
1423
|
+
from = from.slice(basePath.length) || "/";
|
|
1424
|
+
}
|
|
1425
|
+
catch {
|
|
1426
|
+
from = "/";
|
|
1427
|
+
}
|
|
1428
|
+
const page = errorPage(from, status);
|
|
1429
|
+
if (page)
|
|
1430
|
+
return new Response(page.match ? renderSegmentPage(page.html, page.match) : page.html, { status, headers });
|
|
1431
|
+
headers.set("Content-Type", "text/plain; charset=utf-8");
|
|
1432
|
+
return new Response(status + " " + label + "\n", { status, headers });
|
|
1433
|
+
}
|
|
1434
|
+
function randomDigest() {
|
|
1435
|
+
const bytes = new Uint8Array(6);
|
|
1436
|
+
crypto.getRandomValues(bytes);
|
|
1437
|
+
return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
|
|
1438
|
+
}
|
|
1439
|
+
function leadingActionArgs(raw) {
|
|
1440
|
+
if (raw == null || raw === "")
|
|
1441
|
+
return [];
|
|
1442
|
+
try {
|
|
1443
|
+
const v = JSON.parse(String(raw));
|
|
1444
|
+
return Array.isArray(v) ? v : [];
|
|
1445
|
+
}
|
|
1446
|
+
catch {
|
|
1447
|
+
return null;
|
|
1448
|
+
}
|
|
1449
|
+
}
|
|
1450
|
+
async function actionHandler(rs) {
|
|
1451
|
+
const limit = cfg.maxAPIBodyBytes;
|
|
1452
|
+
const fetchModeHeader = (rs.headers.get("x-krate-action") || "").toLowerCase() === "fetch";
|
|
1453
|
+
const wantsJSON = fetchModeHeader || (rs.headers.get("accept") || "").includes("application/json");
|
|
1454
|
+
const fail = (status, msg) => {
|
|
1455
|
+
rs.res.set("Cache-Control", "no-store");
|
|
1456
|
+
if (wantsJSON) {
|
|
1457
|
+
rs.res.set("Content-Type", "application/json");
|
|
1458
|
+
return finish(rs, status, JSON.stringify({ error: { message: msg }, ok: false }) + "\n");
|
|
1459
|
+
}
|
|
1460
|
+
return httpError(rs, msg, status);
|
|
1461
|
+
};
|
|
1462
|
+
rs.res.set("Cache-Control", "no-store");
|
|
1463
|
+
if (rs.method !== "POST") {
|
|
1464
|
+
rs.res.set("Allow", "POST");
|
|
1465
|
+
return fail(405, "method not allowed");
|
|
1466
|
+
}
|
|
1467
|
+
if (!sameOriginAction(rs))
|
|
1468
|
+
return fail(403, "cross-site server action rejected");
|
|
1469
|
+
const declared = Number(rs.headers.get("content-length") || 0);
|
|
1470
|
+
if (limit > 0 && declared > limit)
|
|
1471
|
+
return fail(413, "server action request body too large");
|
|
1472
|
+
let ret = sanitizeActionReturn(new URLSearchParams(rs.search).get("__krate_return") || "", rs);
|
|
1473
|
+
if (!ret)
|
|
1474
|
+
ret = sanitizeActionReturn(rs.headers.get("x-krate-return") || "", rs);
|
|
1475
|
+
if (!ret && !fetchModeHeader)
|
|
1476
|
+
ret = sanitizeActionReturn(rs.headers.get("referer") || "", rs);
|
|
1477
|
+
// Re-run through the sidecar semantics (krateRunAction).
|
|
1478
|
+
const reqHeaders = new Headers(rs.request.headers);
|
|
1479
|
+
if (ret)
|
|
1480
|
+
reqHeaders.set("x-krate-return", ret);
|
|
1481
|
+
else
|
|
1482
|
+
reqHeaders.delete("x-krate-return");
|
|
1483
|
+
const site = (reqHeaders.get("sec-fetch-site") || "").toLowerCase();
|
|
1484
|
+
if (site === "cross-site")
|
|
1485
|
+
return withHeaders(rs, actionFail(403, "cross-site server action rejected"));
|
|
1486
|
+
const origin = reqHeaders.get("origin");
|
|
1487
|
+
const host = requestHost(rs);
|
|
1488
|
+
if (origin && host) {
|
|
1489
|
+
try {
|
|
1490
|
+
if (new URL(origin).host !== host)
|
|
1491
|
+
return withHeaders(rs, actionFail(403, "cross-origin server action rejected"));
|
|
1492
|
+
}
|
|
1493
|
+
catch {
|
|
1494
|
+
return withHeaders(rs, actionFail(403, "invalid action origin"));
|
|
1495
|
+
}
|
|
1496
|
+
}
|
|
1497
|
+
let id = "";
|
|
1498
|
+
try {
|
|
1499
|
+
id = decodeURIComponent(rs.path.slice("/__krate/action/".length));
|
|
1500
|
+
}
|
|
1501
|
+
catch {
|
|
1502
|
+
// not decodable: no action matches
|
|
1503
|
+
}
|
|
1504
|
+
const entry = actionById.get(id);
|
|
1505
|
+
if (!entry)
|
|
1506
|
+
return withHeaders(rs, actionFail(404, "Server action not found"));
|
|
1507
|
+
const mod = modules.actions && modules.actions[entry.file];
|
|
1508
|
+
if (!mod) {
|
|
1509
|
+
console.error(`[krate] server action module ${entry.file} is not part of this deployment`);
|
|
1510
|
+
return withHeaders(rs, actionFail(500, "Server action failed"));
|
|
1511
|
+
}
|
|
1512
|
+
const fn = entry.export === "default" ? mod.default || mod[entry.export] : mod[entry.export];
|
|
1513
|
+
if (typeof fn !== "function")
|
|
1514
|
+
return withHeaders(rs, actionFail(500, "Server action export is not a function"));
|
|
1515
|
+
const fetchMode = String(reqHeaders.get("x-krate-action") || "") === "fetch";
|
|
1516
|
+
const bodyBytes = await readBody(rs, limit);
|
|
1517
|
+
if (bodyBytes === "too-large")
|
|
1518
|
+
return withHeaders(rs, actionFail(413, "server action request body too large"));
|
|
1519
|
+
const query = new URLSearchParams(rs.search);
|
|
1520
|
+
let args;
|
|
1521
|
+
try {
|
|
1522
|
+
const probe = new Request(fullURL(rs), {
|
|
1523
|
+
method: "POST",
|
|
1524
|
+
headers: reqHeaders,
|
|
1525
|
+
body: bodyBytes && bodyBytes.byteLength > 0 ? bodyBytes : undefined,
|
|
1526
|
+
});
|
|
1527
|
+
if (String(reqHeaders.get("content-type") || "").includes("application/json")) {
|
|
1528
|
+
const payload = await probe.json();
|
|
1529
|
+
args = payload && Array.isArray(payload.args) ? payload.args : [];
|
|
1530
|
+
}
|
|
1531
|
+
else {
|
|
1532
|
+
const fd = await probe.formData();
|
|
1533
|
+
let raw = fd.get("__krate_args");
|
|
1534
|
+
fd.delete("__krate_args");
|
|
1535
|
+
if (raw == null)
|
|
1536
|
+
raw = query.get("__krate_args");
|
|
1537
|
+
const lead = leadingActionArgs(raw);
|
|
1538
|
+
if (lead === null)
|
|
1539
|
+
throw new Error("bad __krate_args");
|
|
1540
|
+
args = lead;
|
|
1541
|
+
args.push(fd);
|
|
1542
|
+
}
|
|
1543
|
+
}
|
|
1544
|
+
catch {
|
|
1545
|
+
return withHeaders(rs, actionFail(400, "Invalid server action request body"));
|
|
1546
|
+
}
|
|
1547
|
+
const ctx = makeActionContext(reqHeaders, id, rs.path);
|
|
1548
|
+
const scope = { kind: "action", paths: [], tags: [] };
|
|
1549
|
+
let result;
|
|
1550
|
+
let redirect = "";
|
|
1551
|
+
let failure = null;
|
|
1552
|
+
let fallback = 0;
|
|
1553
|
+
try {
|
|
1554
|
+
result = await revalidateStore.run(scope, () => actionStore.run(ctx, () => fn(...args)));
|
|
1555
|
+
}
|
|
1556
|
+
catch (e) {
|
|
1557
|
+
if (e && typeof e.__krateRedirect === "string")
|
|
1558
|
+
redirect = e.__krateRedirect;
|
|
1559
|
+
else if ((fallback = httpFallbackStatus(e)))
|
|
1560
|
+
failure = null;
|
|
1561
|
+
else
|
|
1562
|
+
failure = e === undefined ? new Error("undefined") : e;
|
|
1563
|
+
}
|
|
1564
|
+
let revalidation = null;
|
|
1565
|
+
try {
|
|
1566
|
+
revalidation = await flushRevalidate(scope);
|
|
1567
|
+
}
|
|
1568
|
+
catch (e) {
|
|
1569
|
+
if (!failure)
|
|
1570
|
+
failure = e;
|
|
1571
|
+
}
|
|
1572
|
+
if (!redirect && result && typeof result === "object" && typeof result.redirect === "string")
|
|
1573
|
+
redirect = result.redirect;
|
|
1574
|
+
redirect = safeActionRedirect(redirect);
|
|
1575
|
+
if (fallback && !failure)
|
|
1576
|
+
return withHeaders(rs, actionFallback(rs, fallback, fetchMode, ctx.setCookies, reqHeaders.get("x-krate-return") || ""));
|
|
1577
|
+
let body = "";
|
|
1578
|
+
if (!failure && fetchMode) {
|
|
1579
|
+
const envelope = { ok: true, result: result === undefined ? null : result };
|
|
1580
|
+
if (redirect)
|
|
1581
|
+
envelope.redirect = redirect;
|
|
1582
|
+
if (revalidation) {
|
|
1583
|
+
envelope.revalidated = true;
|
|
1584
|
+
envelope.revalidation = revalidation;
|
|
1585
|
+
}
|
|
1586
|
+
try {
|
|
1587
|
+
body = JSON.stringify(envelope);
|
|
1588
|
+
}
|
|
1589
|
+
catch (e) {
|
|
1590
|
+
failure = e;
|
|
1591
|
+
}
|
|
1592
|
+
}
|
|
1593
|
+
if (failure) {
|
|
1594
|
+
const digest = randomDigest();
|
|
1595
|
+
console.error(`[krate] server action ${entry.export} (${entry.source || id}) failed, digest ${digest}:`, failure);
|
|
1596
|
+
if (fetchMode)
|
|
1597
|
+
return withHeaders(rs, actionFail(500, "Server action failed", digest, ctx.setCookies));
|
|
1598
|
+
return withHeaders(rs, new Response("Server action failed (digest " + digest + ")\n", { status: 500, headers: actionHeaders("text/plain; charset=utf-8", ctx.setCookies) }));
|
|
1599
|
+
}
|
|
1600
|
+
if (fetchMode)
|
|
1601
|
+
return withHeaders(rs, new Response(body, { status: 200, headers: actionHeaders("application/json", ctx.setCookies) }));
|
|
1602
|
+
const headers = actionHeaders("text/plain; charset=utf-8", ctx.setCookies);
|
|
1603
|
+
headers.set("location", redirect || reqHeaders.get("x-krate-return") || "/");
|
|
1604
|
+
// The returned state would be lost across the 303; carry it in a short-lived
|
|
1605
|
+
// signed cookie. A page can set cookies for sibling hosts, so an unsigned one
|
|
1606
|
+
// is never read back (see resolveFlashSecret for the deployments without a key).
|
|
1607
|
+
if (!redirect && result !== undefined) {
|
|
1608
|
+
if (flashSecret === null) {
|
|
1609
|
+
if (!warnedFlashSecret) {
|
|
1610
|
+
warnedFlashSecret = true;
|
|
1611
|
+
console.warn("[krate] action state is not shown after a no-JS form submit on this target: set KRATE_FLASH_SECRET (a random string of at least 32 bytes, the same on every instance) to enable it");
|
|
1612
|
+
}
|
|
1613
|
+
}
|
|
1614
|
+
else {
|
|
1615
|
+
try {
|
|
1616
|
+
const payload = flashPayloadOf(id, result);
|
|
1617
|
+
if (payload.length <= 2800) {
|
|
1618
|
+
const flash = await signFlash(flashSecret, payload);
|
|
1619
|
+
headers.append("set-cookie", FLASH_COOKIE + "=" + flash + "; Path=/; Max-Age=60; SameSite=Lax" + (isHTTPSRequest(reqHeaders) ? "; Secure" : ""));
|
|
1620
|
+
}
|
|
1621
|
+
else
|
|
1622
|
+
console.warn(`[krate] action ${entry.export} returned state too large to carry across the redirect; it is not shown after a no-JS submit`);
|
|
1623
|
+
}
|
|
1624
|
+
catch {
|
|
1625
|
+
// unserializable state is not carried
|
|
1626
|
+
}
|
|
1627
|
+
}
|
|
1628
|
+
}
|
|
1629
|
+
return withHeaders(rs, new Response(null, { status: 303, headers }));
|
|
1630
|
+
}
|
|
1631
|
+
/** Layers a handler-built Response on the headers the outer layers set (security, middleware). */
|
|
1632
|
+
function withHeaders(rs, out) {
|
|
1633
|
+
const merged = new Headers(rs.res);
|
|
1634
|
+
writeHeaderPairs(merged, headerPairs(out.headers));
|
|
1635
|
+
const noBody = NO_BODY_STATUS.has(out.status) || rs.method === "HEAD";
|
|
1636
|
+
return new Response(noBody ? null : out.body, { status: out.status, headers: merged });
|
|
1637
|
+
}
|
|
1638
|
+
function sameOriginAction(rs) {
|
|
1639
|
+
if ((rs.headers.get("sec-fetch-site") || "").toLowerCase() === "cross-site")
|
|
1640
|
+
return false;
|
|
1641
|
+
const origin = (rs.headers.get("origin") || "").trim();
|
|
1642
|
+
if (!origin)
|
|
1643
|
+
return true;
|
|
1644
|
+
let u;
|
|
1645
|
+
try {
|
|
1646
|
+
u = new URL(origin);
|
|
1647
|
+
}
|
|
1648
|
+
catch {
|
|
1649
|
+
return false;
|
|
1650
|
+
}
|
|
1651
|
+
if (!u.host)
|
|
1652
|
+
return false;
|
|
1653
|
+
return u.host.toLowerCase() === requestHost(rs).toLowerCase();
|
|
1654
|
+
}
|
|
1655
|
+
// The chain
|
|
1656
|
+
/** flashNoticeMiddleware: render pending no-JS form feedback into a page. */
|
|
1657
|
+
async function flashNotice(rs, next) {
|
|
1658
|
+
if (rs.method !== "GET" || (extName(rs.path) !== "" && !isHTMLDocRequest(rs.path)))
|
|
1659
|
+
return next(rs);
|
|
1660
|
+
const flash = await requestFlash(rs.headers.get("cookie"), flashSecret);
|
|
1661
|
+
if (!flash)
|
|
1662
|
+
return next(rs);
|
|
1663
|
+
// The page is rendered fresh with the notice: drop conditional and range headers.
|
|
1664
|
+
const headers = new Headers(rs.headers);
|
|
1665
|
+
for (const h of ["If-None-Match", "If-Modified-Since", "If-Match", "If-Unmodified-Since", "If-Range", "Range"])
|
|
1666
|
+
headers.delete(h);
|
|
1667
|
+
rs.headers = headers;
|
|
1668
|
+
const out = await next(rs);
|
|
1669
|
+
if (out.status !== 200 || !(out.headers.get("content-type") || "").startsWith("text/html") || out.headers.get("content-encoding"))
|
|
1670
|
+
return out;
|
|
1671
|
+
const text = await out.text();
|
|
1672
|
+
const injected = injectFlashNotice(text, flash.raw, flash.payload);
|
|
1673
|
+
const outHeaders = new Headers(out.headers);
|
|
1674
|
+
if (injected === null)
|
|
1675
|
+
return new Response(text, { status: out.status, headers: outHeaders });
|
|
1676
|
+
outHeaders.set("Cache-Control", "no-store");
|
|
1677
|
+
outHeaders.delete("Etag");
|
|
1678
|
+
outHeaders.delete("Last-Modified");
|
|
1679
|
+
outHeaders.append("Set-Cookie", FLASH_COOKIE + "=; Path=/; Max-Age=0; SameSite=Lax");
|
|
1680
|
+
return new Response(injected, { status: 200, headers: outHeaders });
|
|
1681
|
+
}
|
|
1682
|
+
async function pageChain(rs) {
|
|
1683
|
+
return flashNotice(rs, async (rs2) => {
|
|
1684
|
+
const blocked = await runMiddleware(rs2);
|
|
1685
|
+
if (blocked)
|
|
1686
|
+
return blocked;
|
|
1687
|
+
return redirectRewriteHandler(rs2);
|
|
1688
|
+
});
|
|
1689
|
+
}
|
|
1690
|
+
async function mux(rs) {
|
|
1691
|
+
const p = rs.path;
|
|
1692
|
+
// net/http.ServeMux cleans the escaped path and redirects when it changed.
|
|
1693
|
+
const raw = rs.rawPath;
|
|
1694
|
+
const cleaned = cleanPath(raw) + (raw.endsWith("/") && raw !== "/" ? "/" : "");
|
|
1695
|
+
if (raw !== "" && cleaned !== raw && rs.method !== "CONNECT") {
|
|
1696
|
+
let target = cleaned;
|
|
1697
|
+
if (rs.search)
|
|
1698
|
+
target += rs.search;
|
|
1699
|
+
return goRedirect(target, p, rs.method, 307, rs.res);
|
|
1700
|
+
}
|
|
1701
|
+
if (p === "/healthz")
|
|
1702
|
+
return textResponse(rs, 200, "ok\n");
|
|
1703
|
+
if (p === "/readyz")
|
|
1704
|
+
return textResponse(rs, 200, "ready\n");
|
|
1705
|
+
if (p === "/api")
|
|
1706
|
+
return goRedirect("/api/", p, rs.method, 307, rs.res);
|
|
1707
|
+
if (p.startsWith("/api/")) {
|
|
1708
|
+
const blocked = await runMiddleware(rs);
|
|
1709
|
+
if (blocked)
|
|
1710
|
+
return blocked;
|
|
1711
|
+
return apiHandler(rs);
|
|
1712
|
+
}
|
|
1713
|
+
if (p.startsWith("/__krate/action/") && data.actions.length > 0) {
|
|
1714
|
+
const blocked = await runMiddleware(rs);
|
|
1715
|
+
if (blocked)
|
|
1716
|
+
return blocked;
|
|
1717
|
+
return actionHandler(rs);
|
|
1718
|
+
}
|
|
1719
|
+
return pageChain(rs);
|
|
1720
|
+
}
|
|
1721
|
+
function applySecurityAndHeaders(rs) {
|
|
1722
|
+
const sec = cfg.security;
|
|
1723
|
+
const h = rs.res;
|
|
1724
|
+
h.set("X-Request-Id", "req-" + ++requestSeq);
|
|
1725
|
+
if (sec.nosniff)
|
|
1726
|
+
h.set("X-Content-Type-Options", "nosniff");
|
|
1727
|
+
if (sec.frameOptions)
|
|
1728
|
+
h.set("X-Frame-Options", sec.frameOptions);
|
|
1729
|
+
if (sec.referrerPolicy)
|
|
1730
|
+
h.set("Referrer-Policy", sec.referrerPolicy);
|
|
1731
|
+
if (sec.permissionsPolicy)
|
|
1732
|
+
h.set("Permissions-Policy", sec.permissionsPolicy);
|
|
1733
|
+
if (sec.hsts)
|
|
1734
|
+
h.set("Strict-Transport-Security", sec.hsts);
|
|
1735
|
+
if (sec.csp)
|
|
1736
|
+
h.set("Content-Security-Policy", sec.csp);
|
|
1737
|
+
for (const rule of cfg.headers) {
|
|
1738
|
+
if (headerSourceMatches(rule.source, rs.path))
|
|
1739
|
+
for (const [k, v] of Object.entries(rule.headers))
|
|
1740
|
+
h.set(k, v);
|
|
1741
|
+
}
|
|
1742
|
+
}
|
|
1743
|
+
/** corsMiddleware; returns a Response for a preflight. */
|
|
1744
|
+
function applyCORS(rs) {
|
|
1745
|
+
const c = cfg.cors;
|
|
1746
|
+
if (!c.enabled)
|
|
1747
|
+
return null;
|
|
1748
|
+
const allowAll = corsOrigins.length === 1 && corsOrigins[0] === "*";
|
|
1749
|
+
const hasWildcard = corsOrigins.includes("*");
|
|
1750
|
+
const origin = rs.headers.get("origin") || "";
|
|
1751
|
+
let allowed = "";
|
|
1752
|
+
if (allowAll && c.credentials) {
|
|
1753
|
+
// A wildcard cannot be combined with credentials.
|
|
1754
|
+
}
|
|
1755
|
+
else if (allowAll) {
|
|
1756
|
+
allowed = "*";
|
|
1757
|
+
}
|
|
1758
|
+
else if (origin && corsOrigins.some((o) => o === "*" || o.toLowerCase() === origin.toLowerCase()) && !(c.credentials && hasWildcard)) {
|
|
1759
|
+
allowed = origin;
|
|
1760
|
+
rs.res.append("Vary", "Origin");
|
|
1761
|
+
}
|
|
1762
|
+
if (allowed) {
|
|
1763
|
+
const h = rs.res;
|
|
1764
|
+
h.set("Access-Control-Allow-Origin", allowed);
|
|
1765
|
+
h.set("Access-Control-Allow-Methods", (c.methods.length ? c.methods : ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"]).join(", "));
|
|
1766
|
+
h.set("Access-Control-Allow-Headers", (c.headers.length ? c.headers : ["Content-Type", "Authorization"]).join(", "));
|
|
1767
|
+
if (c.credentials)
|
|
1768
|
+
h.set("Access-Control-Allow-Credentials", "true");
|
|
1769
|
+
if (c.maxAge > 0)
|
|
1770
|
+
h.set("Access-Control-Max-Age", String(c.maxAge));
|
|
1771
|
+
}
|
|
1772
|
+
if (rs.method === "OPTIONS" && rs.headers.get("access-control-request-method"))
|
|
1773
|
+
return finish(rs, 204, null);
|
|
1774
|
+
return null;
|
|
1775
|
+
}
|
|
1776
|
+
return async function handle(request, ctx = {}) {
|
|
1777
|
+
if (ctx.waitUntil)
|
|
1778
|
+
latestWaitUntil = ctx.waitUntil.bind(ctx);
|
|
1779
|
+
request = sanitizeForwarded(request);
|
|
1780
|
+
const url = new URL(request.url);
|
|
1781
|
+
const rs = {
|
|
1782
|
+
request,
|
|
1783
|
+
method: request.method.toUpperCase(),
|
|
1784
|
+
path: safeDecode(url.pathname),
|
|
1785
|
+
rawPath: url.pathname,
|
|
1786
|
+
search: url.search,
|
|
1787
|
+
res: new Headers(),
|
|
1788
|
+
headers: request.headers,
|
|
1789
|
+
origin: requestOrigin(request, url),
|
|
1790
|
+
ctx,
|
|
1791
|
+
};
|
|
1792
|
+
try {
|
|
1793
|
+
// Mount under the base path: requests outside it redirect (GET/HEAD) or 404.
|
|
1794
|
+
if (basePath) {
|
|
1795
|
+
const p = rs.path;
|
|
1796
|
+
if (!(p.startsWith("/__krate/") || p === "/healthz" || p === "/readyz")) {
|
|
1797
|
+
if (p === basePath || p === basePath + "/")
|
|
1798
|
+
rs.path = "/";
|
|
1799
|
+
else if (p.startsWith(basePath + "/"))
|
|
1800
|
+
rs.path = p.slice(basePath.length);
|
|
1801
|
+
else {
|
|
1802
|
+
applySecurityAndHeaders(rs);
|
|
1803
|
+
if (rs.method === "GET" || rs.method === "HEAD")
|
|
1804
|
+
return goRedirect(basePath + (p.startsWith("/") ? p : "/" + p), p, rs.method, 307, rs.res);
|
|
1805
|
+
return notFoundText(rs);
|
|
1806
|
+
}
|
|
1807
|
+
}
|
|
1808
|
+
}
|
|
1809
|
+
applySecurityAndHeaders(rs);
|
|
1810
|
+
const preflight = applyCORS(rs);
|
|
1811
|
+
if (preflight)
|
|
1812
|
+
return preflight;
|
|
1813
|
+
await sleepMicrotask();
|
|
1814
|
+
return await mux(rs);
|
|
1815
|
+
}
|
|
1816
|
+
catch (err) {
|
|
1817
|
+
console.error(`[krate] panic recovered: ${rs.method} ${rs.path}: ${(err && err.stack) || err}`);
|
|
1818
|
+
if (rs.path.startsWith("/api/")) {
|
|
1819
|
+
rs.res.set("Content-Type", "application/json");
|
|
1820
|
+
return finish(rs, 500, '{"error":"Internal Server Error"}');
|
|
1821
|
+
}
|
|
1822
|
+
return httpError(rs, "Internal Server Error", 500);
|
|
1823
|
+
}
|
|
1824
|
+
};
|
|
1825
|
+
}
|
|
1826
|
+
export { isDynamicPattern };
|