@krate/runtime 0.5.0-beta.1 → 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/actions.js +2 -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 +60 -12
- package/dist/cache.d.ts +1 -0
- package/dist/cache.js +3 -3
- package/dist/class-component.js +6 -0
- package/dist/class-component.test.js +53 -2
- package/dist/dev-overlay.js +10 -10
- package/dist/dom.d.ts +8 -0
- package/dist/dom.js +28 -0
- 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 +4 -4
- 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/index.d.ts +3 -0
- package/dist/index.js +2 -0
- package/dist/jsx-types.d.ts +11 -0
- package/dist/krate-core.js +1 -1
- package/dist/krate-dev.js +10 -10
- package/dist/krate-f-actions.js +1 -1
- package/dist/krate-f-classes.js +5 -5
- package/dist/krate-f-highlight.js +2 -0
- package/dist/krate-f-list.js +1 -1
- package/dist/krate-f-navigation.js +2 -0
- package/dist/krate-f-router.js +1 -1
- package/dist/krate-features.json +254 -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/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/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 +27 -0
- package/dist/router.js +59 -4
- package/dist/segmented-lru.d.ts +19 -0
- package/dist/segmented-lru.js +87 -0
- package/dist/server-async.test.js +23 -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 +146 -788
- package/dist/server-renderer.test.d.ts +1 -0
- package/dist/server-renderer.test.js +266 -0
- package/dist/server.d.ts +12 -1
- package/dist/server.js +42 -6
- 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.js +63 -8
- 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 +29 -1
package/dist/server-renderer.js
CHANGED
|
@@ -7,10 +7,12 @@ import path from "node:path";
|
|
|
7
7
|
import vm from "node:vm";
|
|
8
8
|
import { pathToFileURL } from "node:url";
|
|
9
9
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
10
|
-
import { timingSafeEqual } from "node:crypto";
|
|
11
|
-
import {
|
|
12
|
-
import {
|
|
13
|
-
import {
|
|
10
|
+
import { createHash, timingSafeEqual } from "node:crypto";
|
|
11
|
+
import { createSSRCore, MemoryIsrStore, } from "./ssr-core.js";
|
|
12
|
+
import { installRenderStore, patchFetch } from "./cache-scope.js";
|
|
13
|
+
import { cacheSpecFromEnv } from "./cache-adapter.js";
|
|
14
|
+
import { isrStoreFor } from "./shared-isr.js";
|
|
15
|
+
import { registerLanguage, setFenceResolver } from "./highlight.js";
|
|
14
16
|
// Render cache scopes (tags / revalidate windows read during a render) and the
|
|
15
17
|
// Next-style fetch data cache. Installed once per process; page bundles share
|
|
16
18
|
// the state through globalThis.
|
|
@@ -103,279 +105,69 @@ function setupStream(res) {
|
|
|
103
105
|
socket.setNoDelay(true);
|
|
104
106
|
}
|
|
105
107
|
}
|
|
106
|
-
//
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
if (query)
|
|
118
|
-
key += "#" + query;
|
|
119
|
-
return key;
|
|
120
|
-
}
|
|
121
|
-
function newQueryTracker() {
|
|
122
|
-
return { keys: new Set(), all: false };
|
|
123
|
-
}
|
|
124
|
-
function trackedQuery(query, t) {
|
|
125
|
-
const target = { ...(query || {}) };
|
|
126
|
-
const note = (prop) => {
|
|
127
|
-
if (typeof prop === "string" && prop !== "then" && prop !== "toJSON" && prop !== "constructor")
|
|
128
|
-
t.keys.add(prop);
|
|
129
|
-
};
|
|
130
|
-
return new Proxy(target, {
|
|
131
|
-
get(obj, prop, recv) {
|
|
132
|
-
note(prop);
|
|
133
|
-
return Reflect.get(obj, prop, recv);
|
|
134
|
-
},
|
|
135
|
-
has(obj, prop) {
|
|
136
|
-
note(prop);
|
|
137
|
-
return Reflect.has(obj, prop);
|
|
138
|
-
},
|
|
139
|
-
ownKeys(obj) {
|
|
140
|
-
t.all = true;
|
|
141
|
-
return Reflect.ownKeys(obj);
|
|
142
|
-
},
|
|
143
|
-
getOwnPropertyDescriptor(obj, prop) {
|
|
144
|
-
note(prop);
|
|
145
|
-
return Reflect.getOwnPropertyDescriptor(obj, prop);
|
|
146
|
-
},
|
|
147
|
-
});
|
|
148
|
-
}
|
|
149
|
-
// pageQueryReads remembers, per route+params variant, which query keys renders
|
|
150
|
-
// have read ("all" when a render enumerated the whole query).
|
|
151
|
-
const pageQueryReads = new Map();
|
|
152
|
-
function pageBaseKey(req) {
|
|
153
|
-
return variantKey({ route: req.route, params: req.params });
|
|
154
|
-
}
|
|
155
|
-
// pageKey is the ISR cache key for a request: params, plus only the query keys
|
|
156
|
-
// previous renders of this variant read.
|
|
157
|
-
function pageKey(req) {
|
|
158
|
-
const reads = pageQueryReads.get(pageBaseKey(req));
|
|
159
|
-
if (!reads)
|
|
160
|
-
return pageBaseKey(req);
|
|
161
|
-
if (reads === "all")
|
|
162
|
-
return variantKey(req);
|
|
163
|
-
const picked = {};
|
|
164
|
-
for (const k of [...reads].sort()) {
|
|
165
|
-
if (req.query && Object.prototype.hasOwnProperty.call(req.query, k))
|
|
166
|
-
picked[k] = req.query[k];
|
|
167
|
-
}
|
|
168
|
-
return variantKey({ route: req.route, params: req.params, query: picked });
|
|
169
|
-
}
|
|
170
|
-
function recordQueryReads(req, t) {
|
|
171
|
-
const base = pageBaseKey(req);
|
|
172
|
-
let cur = pageQueryReads.get(base);
|
|
173
|
-
if (t.all)
|
|
174
|
-
cur = "all";
|
|
175
|
-
else if (t.keys.size > 0 && cur !== "all")
|
|
176
|
-
cur = new Set([...(cur || []), ...t.keys]);
|
|
177
|
-
if (cur)
|
|
178
|
-
pageQueryReads.set(base, cur);
|
|
179
|
-
}
|
|
180
|
-
class ISRCache {
|
|
181
|
-
constructor(maxSize = 512) {
|
|
182
|
-
this.cache = new Map();
|
|
183
|
-
this.byTag = new Map();
|
|
184
|
-
this.revalidationIntervals = new Map(); // route -> seconds
|
|
185
|
-
this.maxSize = maxSize;
|
|
186
|
-
}
|
|
187
|
-
setRevalidation(route, seconds) {
|
|
188
|
-
this.revalidationIntervals.set(route, seconds);
|
|
189
|
-
}
|
|
190
|
-
get(key) {
|
|
191
|
-
return this.cache.get(key);
|
|
192
|
-
}
|
|
193
|
-
set(key, entry) {
|
|
194
|
-
if (this.cache.has(key))
|
|
195
|
-
this.delete(key);
|
|
196
|
-
if (this.cache.size >= this.maxSize) {
|
|
197
|
-
const oldest = this.cache.keys().next().value;
|
|
198
|
-
if (oldest)
|
|
199
|
-
this.delete(oldest);
|
|
200
|
-
}
|
|
201
|
-
this.cache.set(key, entry);
|
|
202
|
-
for (const t of entry.tags || []) {
|
|
203
|
-
let keys = this.byTag.get(t);
|
|
204
|
-
if (!keys)
|
|
205
|
-
this.byTag.set(t, (keys = new Set()));
|
|
206
|
-
keys.add(key);
|
|
207
|
-
}
|
|
208
|
-
}
|
|
209
|
-
delete(key) {
|
|
210
|
-
const entry = this.cache.get(key);
|
|
211
|
-
if (!entry)
|
|
212
|
-
return false;
|
|
213
|
-
this.cache.delete(key);
|
|
214
|
-
for (const t of entry.tags || []) {
|
|
215
|
-
const keys = this.byTag.get(t);
|
|
216
|
-
if (keys) {
|
|
217
|
-
keys.delete(key);
|
|
218
|
-
if (keys.size === 0)
|
|
219
|
-
this.byTag.delete(t);
|
|
220
|
-
}
|
|
221
|
-
}
|
|
222
|
-
return true;
|
|
223
|
-
}
|
|
224
|
-
get size() {
|
|
225
|
-
return this.cache.size;
|
|
226
|
-
}
|
|
227
|
-
isStale(key) {
|
|
228
|
-
const entry = this.cache.get(key);
|
|
229
|
-
const route = key.split("?")[0].split("#")[0];
|
|
230
|
-
let interval = this.revalidationIntervals.get(route) || 0;
|
|
231
|
-
if (entry && entry.revalidate && entry.revalidate > 0 && (!interval || entry.revalidate < interval)) {
|
|
232
|
-
interval = entry.revalidate;
|
|
233
|
-
}
|
|
234
|
-
if (!entry || !interval)
|
|
235
|
-
return false;
|
|
236
|
-
return (Date.now() - entry.timestamp) / 1000 > interval;
|
|
237
|
-
}
|
|
238
|
-
// deleteRoute removes every variant of a route (used by revalidation/invalidation).
|
|
239
|
-
deleteRoute(route) {
|
|
240
|
-
let n = 0;
|
|
241
|
-
for (const key of [...this.cache.keys()]) {
|
|
242
|
-
if (key === route || key.startsWith(route + "?") || key.startsWith(route + "#")) {
|
|
243
|
-
if (this.delete(key))
|
|
244
|
-
n++;
|
|
245
|
-
}
|
|
246
|
-
}
|
|
247
|
-
return n;
|
|
248
|
-
}
|
|
249
|
-
// deleteVariant removes one params variant of a route (every query variant
|
|
250
|
-
// of it), e.g. /blog/[slug] with {slug: "a"} for revalidatePath("/blog/a").
|
|
251
|
-
deleteVariant(route, params) {
|
|
252
|
-
const base = variantKey({ route, params });
|
|
253
|
-
let n = 0;
|
|
254
|
-
for (const key of [...this.cache.keys()]) {
|
|
255
|
-
if (key === base || key.startsWith(base + "#")) {
|
|
256
|
-
if (this.delete(key))
|
|
257
|
-
n++;
|
|
258
|
-
}
|
|
259
|
-
}
|
|
260
|
-
return n;
|
|
261
|
-
}
|
|
262
|
-
// deleteTags removes every entry whose render read one of tags.
|
|
263
|
-
deleteTags(tags) {
|
|
264
|
-
let n = 0;
|
|
265
|
-
for (const t of tags) {
|
|
266
|
-
const keys = this.byTag.get(t);
|
|
267
|
-
if (!keys)
|
|
268
|
-
continue;
|
|
269
|
-
for (const key of [...keys]) {
|
|
270
|
-
if (this.delete(key))
|
|
271
|
-
n++;
|
|
272
|
-
}
|
|
273
|
-
}
|
|
274
|
-
return n;
|
|
275
|
-
}
|
|
276
|
-
// entriesForRoute returns a snapshot of the cached variants for a route so a
|
|
277
|
-
// background refresh can iterate them without mutating during iteration.
|
|
278
|
-
entriesForRoute(route) {
|
|
279
|
-
const out = [];
|
|
280
|
-
for (const [key, entry] of this.cache) {
|
|
281
|
-
if (key === route || key.startsWith(route + "?") || key.startsWith(route + "#")) {
|
|
282
|
-
out.push([key, entry]);
|
|
283
|
-
}
|
|
108
|
+
// Configuration and manifest
|
|
109
|
+
const PORT = parseInt(process.env.KRATE_SSR_PORT || "3100", 10);
|
|
110
|
+
const manifestPath = process.env.KRATE_MANIFEST || "";
|
|
111
|
+
const root = process.env.KRATE_ROOT || process.cwd();
|
|
112
|
+
const OUT_DIR = process.env.KRATE_OUT_DIR || path.join(root, "dist");
|
|
113
|
+
// Exit when the Krate host dies: a SIGKILL or OOM kill gives it no chance to stop its sidecars.
|
|
114
|
+
const PARENT_PID = parseInt(process.env.KRATE_PARENT_PID || "", 10);
|
|
115
|
+
if (PARENT_PID > 0) {
|
|
116
|
+
const parentWatch = setInterval(() => {
|
|
117
|
+
try {
|
|
118
|
+
process.kill(PARENT_PID, 0);
|
|
284
119
|
}
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
return {
|
|
289
|
-
entries: [...this.cache.entries()].map(([key, entry]) => ({ key, ...entry })),
|
|
290
|
-
};
|
|
291
|
-
}
|
|
292
|
-
hydrate(data) {
|
|
293
|
-
if (!data || !Array.isArray(data.entries))
|
|
294
|
-
return;
|
|
295
|
-
for (const e of data.entries) {
|
|
296
|
-
if (e && typeof e.key === "string" && typeof e.html === "string") {
|
|
297
|
-
this.set(e.key, {
|
|
298
|
-
html: e.html,
|
|
299
|
-
timestamp: typeof e.timestamp === "number" ? e.timestamp : Date.now(),
|
|
300
|
-
params: e.params && typeof e.params === "object" ? e.params : undefined,
|
|
301
|
-
query: e.query && typeof e.query === "object" ? e.query : undefined,
|
|
302
|
-
tags: Array.isArray(e.tags) ? e.tags.filter((t) => typeof t === "string") : undefined,
|
|
303
|
-
revalidate: typeof e.revalidate === "number" ? e.revalidate : undefined,
|
|
304
|
-
});
|
|
305
|
-
}
|
|
120
|
+
catch (e) {
|
|
121
|
+
if (!e || e.code !== "EPERM")
|
|
122
|
+
process.exit(0);
|
|
306
123
|
}
|
|
307
|
-
}
|
|
308
|
-
|
|
309
|
-
// ISR cache size and the render timeout are configurable via the compiler
|
|
310
|
-
// (ssr.maxCacheSize / ssr.timeout), which exports them to the sidecar env.
|
|
311
|
-
const isrCache = new ISRCache(parseInt(process.env.KRATE_SSR_MAX_CACHE || "", 10) || 512);
|
|
312
|
-
// renderTimeoutMs bounds a single renderToString call so one pathological page
|
|
313
|
-
// cannot pin the sidecar. 0 disables the bound.
|
|
314
|
-
const renderTimeoutMs = parseInt(process.env.KRATE_SSR_TIMEOUT || "", 10) || 5000;
|
|
315
|
-
// Partial Prerendering: cache dynamic regions on non-ISR pages with this
|
|
316
|
-
// window (overridable per region via `export const revalidate`).
|
|
317
|
-
const pprEnabled = process.env.KRATE_PPR === "1";
|
|
318
|
-
const pprRevalidate = parseInt(process.env.KRATE_PPR_REVALIDATE || "", 10) || 60;
|
|
319
|
-
// withRenderTimeout rejects if p does not settle within renderTimeoutMs. The
|
|
320
|
-
// underlying render keeps running (JS cannot cancel it), but the request fails
|
|
321
|
-
// fast rather than hanging.
|
|
322
|
-
function withRenderTimeout(p) {
|
|
323
|
-
if (renderTimeoutMs <= 0)
|
|
324
|
-
return p;
|
|
325
|
-
return new Promise((resolve, reject) => {
|
|
326
|
-
const timer = setTimeout(() => reject(new Error(`render timed out after ${renderTimeoutMs}ms`)), renderTimeoutMs);
|
|
327
|
-
p.then((v) => { clearTimeout(timer); resolve(v); }, (e) => { clearTimeout(timer); reject(e); });
|
|
328
|
-
});
|
|
124
|
+
}, 2000);
|
|
125
|
+
parentWatch.unref();
|
|
329
126
|
}
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
function isrCachePath() {
|
|
336
|
-
return isrCacheFile || path.join(OUT_DIR, ".krate", "isr-cache.json");
|
|
127
|
+
let manifest = null;
|
|
128
|
+
if (manifestPath && fs.existsSync(manifestPath)) {
|
|
129
|
+
const data = fs.readFileSync(manifestPath, "utf-8");
|
|
130
|
+
manifest = JSON.parse(data);
|
|
131
|
+
console.log(`[krate-ssr] Loaded manifest: ${manifest.pages.length} SSR/ISR/streaming pages`);
|
|
337
132
|
}
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
const data = isrCache.serialize();
|
|
347
|
-
const file = isrCachePath();
|
|
348
|
-
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
349
|
-
fs.writeFileSync(file, JSON.stringify(data));
|
|
133
|
+
else {
|
|
134
|
+
// Try default location
|
|
135
|
+
const krateDefault = path.join(OUT_DIR, ".krate", "server-manifest.json");
|
|
136
|
+
const defaultPath = fs.existsSync(krateDefault) ? krateDefault : path.join(OUT_DIR, "server-manifest.json");
|
|
137
|
+
if (fs.existsSync(defaultPath)) {
|
|
138
|
+
const data = fs.readFileSync(defaultPath, "utf-8");
|
|
139
|
+
manifest = JSON.parse(data);
|
|
140
|
+
console.log(`[krate-ssr] Loaded manifest: ${manifest.pages.length} SSR/ISR/streaming pages`);
|
|
350
141
|
}
|
|
351
|
-
|
|
352
|
-
console.error("[krate-ssr]
|
|
142
|
+
else {
|
|
143
|
+
console.error("[krate-ssr] No manifest found. SSR pages will not be served.");
|
|
353
144
|
}
|
|
354
145
|
}
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
146
|
+
// Request-time syntax highlighting: the build writes the lexer tables of the
|
|
147
|
+
// languages the server pages use, and <SyntaxHighlight> highlights with them.
|
|
148
|
+
(function loadHighlightTables() {
|
|
149
|
+
const file = path.join(OUT_DIR, ".krate", "highlight.json");
|
|
150
|
+
if (!fs.existsSync(file))
|
|
359
151
|
return;
|
|
360
|
-
if (persistTimer)
|
|
361
|
-
clearTimeout(persistTimer);
|
|
362
|
-
persistTimer = setTimeout(persistIsrNow, 1000);
|
|
363
|
-
}
|
|
364
|
-
function loadIsrCache() {
|
|
365
152
|
try {
|
|
366
|
-
const
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
153
|
+
const bundle = JSON.parse(fs.readFileSync(file, "utf-8"));
|
|
154
|
+
const names = new Map();
|
|
155
|
+
for (const [k, v] of Object.entries(bundle.keys)) {
|
|
156
|
+
if (!names.has(v))
|
|
157
|
+
names.set(v, []);
|
|
158
|
+
names.get(v).push(k);
|
|
159
|
+
}
|
|
160
|
+
for (const t of bundle.tables)
|
|
161
|
+
registerLanguage(t, names.get(t.n.toLowerCase()));
|
|
162
|
+
const fences = bundle.fences;
|
|
163
|
+
if (fences)
|
|
164
|
+
setFenceResolver((n) => Object.prototype.hasOwnProperty.call(fences, n.trim().toLowerCase()));
|
|
165
|
+
}
|
|
166
|
+
catch (e) {
|
|
167
|
+
console.error("[krate-ssr] Could not load highlight tables; code is rendered as plain text:", e);
|
|
377
168
|
}
|
|
378
|
-
}
|
|
169
|
+
})();
|
|
170
|
+
// Module loaders (node:fs / node:vm live here, not in the render core)
|
|
379
171
|
// Page Module Loader
|
|
380
172
|
const moduleCache = new Map();
|
|
381
173
|
async function loadPageModule(page) {
|
|
@@ -404,244 +196,9 @@ async function loadPageModule(page) {
|
|
|
404
196
|
throw err;
|
|
405
197
|
}
|
|
406
198
|
}
|
|
407
|
-
// Renderer
|
|
408
|
-
let manifest = null;
|
|
409
|
-
let projectRoot = "";
|
|
410
|
-
function findPage(route) {
|
|
411
|
-
if (!manifest)
|
|
412
|
-
return undefined;
|
|
413
|
-
// Try exact match first, then strip trailing slash
|
|
414
|
-
let page = manifest.pages.find((p) => p.route === route);
|
|
415
|
-
if (!page && route !== "/") {
|
|
416
|
-
page = manifest.pages.find((p) => p.route === route + "/");
|
|
417
|
-
}
|
|
418
|
-
if (!page && route.endsWith("/")) {
|
|
419
|
-
page = manifest.pages.find((p) => p.route === route.slice(0, -1));
|
|
420
|
-
}
|
|
421
|
-
return page;
|
|
422
|
-
}
|
|
423
|
-
// Request scope for server components: headers()/cookies() from
|
|
424
|
-
// @krate/runtime/server read it through the global store symbol, so it works
|
|
425
|
-
// no matter which copy of the runtime a page bundle resolved.
|
|
426
|
-
const requestStore = (() => {
|
|
427
|
-
const key = Symbol.for("krate.request.store");
|
|
428
|
-
const g = globalThis;
|
|
429
|
-
if (!g[key])
|
|
430
|
-
g[key] = new AsyncLocalStorage();
|
|
431
|
-
return g[key];
|
|
432
|
-
})();
|
|
433
|
-
function requestContextFor(req, tracker) {
|
|
434
|
-
const h = new Headers();
|
|
435
|
-
for (const [k, v] of Object.entries(req.headers || {})) {
|
|
436
|
-
if (typeof v === "string") {
|
|
437
|
-
try {
|
|
438
|
-
h.set(k, v);
|
|
439
|
-
}
|
|
440
|
-
catch {
|
|
441
|
-
// skip header names the WHATWG Headers class rejects
|
|
442
|
-
}
|
|
443
|
-
}
|
|
444
|
-
}
|
|
445
|
-
return {
|
|
446
|
-
url: req.url || req.route,
|
|
447
|
-
method: req.method || "GET",
|
|
448
|
-
headers: h,
|
|
449
|
-
cookies: parseCookieHeader(h.get("cookie")),
|
|
450
|
-
params: { ...(req.params || {}) },
|
|
451
|
-
searchParams: tracker ? trackedQuery(req.query, tracker) : { ...(req.query || {}) },
|
|
452
|
-
};
|
|
453
|
-
}
|
|
454
|
-
function withRequest(req, fn, tracker) {
|
|
455
|
-
return requestStore.run(requestContextFor(req, tracker), fn);
|
|
456
|
-
}
|
|
457
|
-
// renderSignal maps notFound()/redirect() thrown during a render to a response.
|
|
458
|
-
function renderSignal(err) {
|
|
459
|
-
if (isNotFoundSignal(err))
|
|
460
|
-
return { html: "", status: 404, notFound: true };
|
|
461
|
-
const to = redirectTarget(err);
|
|
462
|
-
if (to)
|
|
463
|
-
return { html: "", status: 307, redirect: to };
|
|
464
|
-
return null;
|
|
465
|
-
}
|
|
466
|
-
function buildProps(req, tracker) {
|
|
467
|
-
// Page-level data fetching (getStaticProps/getServerSideProps) has been
|
|
468
|
-
// removed; per-request data is provided by server components (@server),
|
|
469
|
-
// runtime components (@runtime), and middleware instead. Dynamic-route
|
|
470
|
-
// params and query parameters extracted by the Go server are forwarded so
|
|
471
|
-
// `({ params }) => ...` pages receive their real values at render time.
|
|
472
|
-
// params and searchParams are plain objects that can also be awaited, so
|
|
473
|
-
// both `params.slug` and Next.js 15's `const { slug } = await params` work.
|
|
474
|
-
// The Go server always forwards params (empty for static routes); a direct
|
|
475
|
-
// request without them keeps params undefined, as before.
|
|
476
|
-
const props = {};
|
|
477
|
-
if (req.params)
|
|
478
|
-
props.params = thenableRecord(req.params);
|
|
479
|
-
if (tracker) {
|
|
480
|
-
// Reads through the view are recorded; awaiting it resolves to another
|
|
481
|
-
// tracked view so `const { page } = await searchParams` records "page".
|
|
482
|
-
const view = trackedQuery(req.query, tracker);
|
|
483
|
-
props.searchParams = thenable(view, () => trackedQuery(req.query, tracker));
|
|
484
|
-
if (req.query)
|
|
485
|
-
props.query = trackedQuery(req.query, tracker);
|
|
486
|
-
return props;
|
|
487
|
-
}
|
|
488
|
-
props.searchParams = thenableRecord(req.query);
|
|
489
|
-
if (req.query)
|
|
490
|
-
props.query = req.query;
|
|
491
|
-
return props;
|
|
492
|
-
}
|
|
493
|
-
// renderFresh renders a page component and - for ISR pages - stores the result.
|
|
494
|
-
// Extracted so background revalidation shares exactly the same render path.
|
|
495
|
-
async function renderFresh(page, req) {
|
|
496
|
-
try {
|
|
497
|
-
const mod = await loadPageModule(page);
|
|
498
|
-
const Component = mod.default;
|
|
499
|
-
if (!Component) {
|
|
500
|
-
return { html: "", status: 500 };
|
|
501
|
-
}
|
|
502
|
-
// The render runs in a cache scope that records the tags / revalidate
|
|
503
|
-
// windows its data reads declared (fetch next options, unstable_cache).
|
|
504
|
-
// Async server components (and plain sync pages) render through
|
|
505
|
-
// renderToStringAsync inside the request scope. The timeout bounds slow
|
|
506
|
-
// awaits (fetch); a page that blocks synchronously still blocks the loop.
|
|
507
|
-
const tracker = newQueryTracker();
|
|
508
|
-
const { result: html, scope, invalidated } = await withRenderTimeout(withCacheScope(page.route, () => withRequest(req, () => renderToStringAsync(jsx(Component, buildProps(req, tracker))), tracker)));
|
|
509
|
-
const response = {
|
|
510
|
-
html,
|
|
511
|
-
status: 200,
|
|
512
|
-
noStore: scope.noStore || invalidated,
|
|
513
|
-
};
|
|
514
|
-
// An uncacheable read (no-store) keeps the render out of the ISR cache, and
|
|
515
|
-
// a revalidation that landed mid-render means the HTML may be stale.
|
|
516
|
-
if (page.mode === "isr" && !scope.noStore && !invalidated) {
|
|
517
|
-
recordQueryReads(req, tracker);
|
|
518
|
-
isrCache.set(pageKey(req), {
|
|
519
|
-
html,
|
|
520
|
-
timestamp: Date.now(),
|
|
521
|
-
params: req.params,
|
|
522
|
-
query: req.query,
|
|
523
|
-
tags: scope.tags.size ? [...scope.tags] : undefined,
|
|
524
|
-
revalidate: scope.revalidate || undefined,
|
|
525
|
-
});
|
|
526
|
-
scheduleIsrPersist();
|
|
527
|
-
}
|
|
528
|
-
return response;
|
|
529
|
-
}
|
|
530
|
-
catch (err) {
|
|
531
|
-
const signal = renderSignal(err);
|
|
532
|
-
if (signal)
|
|
533
|
-
return signal;
|
|
534
|
-
console.error(`[krate] Error rendering ${req.route}:`, err);
|
|
535
|
-
return { html: "", status: 500, error: (err && err.message) || String(err) };
|
|
536
|
-
}
|
|
537
|
-
}
|
|
538
|
-
// Single-flight background revalidation for stale-while-revalidate. While a
|
|
539
|
-
// revalidation for a given variant is in flight, concurrent requests share the
|
|
540
|
-
// same promise instead of stampeding the renderer.
|
|
541
|
-
const inFlightRevalidations = new Map();
|
|
542
|
-
function revalidateInBackground(page, req) {
|
|
543
|
-
const key = pageKey(req);
|
|
544
|
-
if (inFlightRevalidations.has(key))
|
|
545
|
-
return;
|
|
546
|
-
const p = (async () => {
|
|
547
|
-
try {
|
|
548
|
-
const rendered = await renderFresh(page, req);
|
|
549
|
-
if (rendered.status === 200) {
|
|
550
|
-
console.log(`[krate-ssr] Revalidated ${key} (SWR)`);
|
|
551
|
-
}
|
|
552
|
-
}
|
|
553
|
-
catch (err) {
|
|
554
|
-
console.error(`[krate-ssr] SWR revalidation failed ${key}:`, err.message);
|
|
555
|
-
}
|
|
556
|
-
finally {
|
|
557
|
-
inFlightRevalidations.delete(key);
|
|
558
|
-
}
|
|
559
|
-
})();
|
|
560
|
-
inFlightRevalidations.set(key, p);
|
|
561
|
-
}
|
|
562
|
-
// Time-based ISR regeneration: re-render every cached variant of a route while
|
|
563
|
-
// keeping the entries in place. This is the non-destructive counterpart of
|
|
564
|
-
// /__krate/ssr/revalidate (which clears a route). The Go server's periodic ISR
|
|
565
|
-
// timer calls this so cached pages stay fresh without evicting dynamic
|
|
566
|
-
// variants - eviction would turn a request that should be a HIT into a MISS.
|
|
567
|
-
const inFlightRouteRefreshes = new Map();
|
|
568
|
-
function refreshRouteVariants(page) {
|
|
569
|
-
const running = inFlightRouteRefreshes.get(page.route);
|
|
570
|
-
if (running)
|
|
571
|
-
return running;
|
|
572
|
-
const p = (async () => {
|
|
573
|
-
try {
|
|
574
|
-
const variants = isrCache.entriesForRoute(page.route);
|
|
575
|
-
let refreshed = 0;
|
|
576
|
-
for (const [, entry] of variants) {
|
|
577
|
-
const req = {
|
|
578
|
-
route: page.route,
|
|
579
|
-
url: page.route,
|
|
580
|
-
method: "GET",
|
|
581
|
-
headers: {},
|
|
582
|
-
params: entry.params,
|
|
583
|
-
query: entry.query,
|
|
584
|
-
};
|
|
585
|
-
const rendered = await renderFresh(page, req);
|
|
586
|
-
if (rendered.status === 200)
|
|
587
|
-
refreshed++;
|
|
588
|
-
}
|
|
589
|
-
return refreshed;
|
|
590
|
-
}
|
|
591
|
-
finally {
|
|
592
|
-
inFlightRouteRefreshes.delete(page.route);
|
|
593
|
-
}
|
|
594
|
-
})();
|
|
595
|
-
inFlightRouteRefreshes.set(page.route, p);
|
|
596
|
-
return p;
|
|
597
|
-
}
|
|
598
|
-
async function renderPage(req) {
|
|
599
|
-
const page = findPage(req.route);
|
|
600
|
-
if (!page) {
|
|
601
|
-
return { html: "", status: 404, notFound: true };
|
|
602
|
-
}
|
|
603
|
-
// ISR: serve from cache with stale-while-revalidate.
|
|
604
|
-
if (page.mode === "isr") {
|
|
605
|
-
const interval = page.revalidate || 60;
|
|
606
|
-
isrCache.setRevalidation(page.route, interval);
|
|
607
|
-
const key = pageKey(req);
|
|
608
|
-
const cached = isrCache.get(key);
|
|
609
|
-
if (cached && !isrCache.isStale(key)) {
|
|
610
|
-
return {
|
|
611
|
-
html: cached.html,
|
|
612
|
-
status: 200,
|
|
613
|
-
cached: true,
|
|
614
|
-
cacheStatus: "hit",
|
|
615
|
-
};
|
|
616
|
-
}
|
|
617
|
-
if (cached) {
|
|
618
|
-
// Entry is stale: serve it immediately and refresh in the background so
|
|
619
|
-
// the next request (and any concurrent ones) get fresh HTML. No stampede:
|
|
620
|
-
// revalidateInBackground is single-flight per variant key.
|
|
621
|
-
revalidateInBackground(page, req);
|
|
622
|
-
return {
|
|
623
|
-
html: cached.html,
|
|
624
|
-
status: 200,
|
|
625
|
-
cached: true,
|
|
626
|
-
cacheStatus: "stale",
|
|
627
|
-
};
|
|
628
|
-
}
|
|
629
|
-
}
|
|
630
|
-
const response = await renderFresh(page, req);
|
|
631
|
-
if (page.mode === "isr")
|
|
632
|
-
response.cacheStatus = "miss";
|
|
633
|
-
return response;
|
|
634
|
-
}
|
|
635
|
-
// Region rendering (static-first)
|
|
636
|
-
// The Go server owns the page: it serves the build-time static shell with the
|
|
637
|
-
// <!-suspense:ID-> markers and baked fallbacks, then asks the sidecar to render
|
|
638
|
-
// ONLY the page's dynamic regions. Each region is rendered by its compiled
|
|
639
|
-
// runtime component bundle (server-components/<Name>.runtime.js - an IIFE that
|
|
640
|
-
// defines globalThis.__krate_render(propsJSON)) with the build-time baked props,
|
|
641
|
-
// so nothing is re-derived at request time.
|
|
642
199
|
const runtimeBundleCache = new Map();
|
|
643
200
|
// loadRuntimeRenderer loads a compiled runtime component bundle and returns its
|
|
644
|
-
// __krate_render(
|
|
201
|
+
// __krate_render(props) function (props as an object or JSON). Bundles are cached by bundle path.
|
|
645
202
|
function loadRuntimeRenderer(relPath) {
|
|
646
203
|
const cached = runtimeBundleCache.get(relPath);
|
|
647
204
|
if (cached)
|
|
@@ -665,285 +222,103 @@ function loadRuntimeRenderer(relPath) {
|
|
|
665
222
|
runtimeBundleCache.set(relPath, render);
|
|
666
223
|
return render;
|
|
667
224
|
}
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
paramsKey: paramsKeyOf(req.params),
|
|
696
|
-
tags: scope && scope.tags.size ? [...scope.tags] : undefined,
|
|
697
|
-
});
|
|
698
|
-
}
|
|
699
|
-
// invalidateRegions removes region entries for a route (optionally one params
|
|
700
|
-
// variant) and/or entries whose render read one of tags.
|
|
701
|
-
function invalidateRegions(route, params, tags) {
|
|
702
|
-
const pkey = params ? paramsKeyOf(params) : null;
|
|
703
|
-
let n = 0;
|
|
704
|
-
for (const [key, e] of Array.from(regionCache.entries())) {
|
|
705
|
-
const routeHit = route !== null && e.route === route && (pkey === null || e.paramsKey === pkey);
|
|
706
|
-
const tagHit = tags.length > 0 && !!e.tags && e.tags.some((t) => tags.includes(t));
|
|
707
|
-
if (routeHit || tagHit) {
|
|
708
|
-
regionCache.delete(key);
|
|
709
|
-
n++;
|
|
710
|
-
}
|
|
711
|
-
}
|
|
712
|
-
return n;
|
|
713
|
-
}
|
|
714
|
-
function clearRegionCache() {
|
|
715
|
-
regionCache.clear();
|
|
716
|
-
regionRevalidation.clear();
|
|
225
|
+
// Render core
|
|
226
|
+
const pprEnabledEnv = process.env.KRATE_PPR === "1";
|
|
227
|
+
const isrMemory = new MemoryIsrStore(parseInt(process.env.KRATE_SSR_MAX_CACHE || "", 10) || 512);
|
|
228
|
+
// With a shared cache adapter (KRATE_CACHE) the ISR cache and the data cache live
|
|
229
|
+
// in the adapter, so every instance serves and invalidates the same pages.
|
|
230
|
+
const sharedCache = isrStoreFor(cacheSpecFromEnv(process.env), isrMemory);
|
|
231
|
+
const core = createSSRCore({
|
|
232
|
+
manifest,
|
|
233
|
+
sha256Hex: (input) => createHash("sha256").update(input).digest("hex"),
|
|
234
|
+
isrStore: sharedCache.store,
|
|
235
|
+
loadPageModule,
|
|
236
|
+
loadRuntimeRenderer,
|
|
237
|
+
maxCacheSize: parseInt(process.env.KRATE_SSR_MAX_CACHE || "", 10) || 512,
|
|
238
|
+
timeoutMs: parseInt(process.env.KRATE_SSR_TIMEOUT || "", 10) || 5000,
|
|
239
|
+
ppr: pprEnabledEnv,
|
|
240
|
+
pprRevalidate: parseInt(process.env.KRATE_PPR_REVALIDATE || "", 10) || 60,
|
|
241
|
+
onIsrChange: (immediate) => (immediate ? persistIsrNow() : scheduleIsrPersist()),
|
|
242
|
+
});
|
|
243
|
+
const isrCache = isrMemory.cache;
|
|
244
|
+
const { findPage, renderPage, renderRegion, renderPageRegion } = core;
|
|
245
|
+
// ISR cache persistence - survives renderer restarts so a bounce doesn't
|
|
246
|
+
// cold-render every ISR variant. Written debounced (coalesced) to the build
|
|
247
|
+
// output dir (.krate/isr-cache.json), overridable via KRATE_ISR_CACHE.
|
|
248
|
+
let isrCacheFile = process.env.KRATE_ISR_CACHE || "";
|
|
249
|
+
let persistTimer = null;
|
|
250
|
+
function isrCachePath() {
|
|
251
|
+
return isrCacheFile || path.join(OUT_DIR, ".krate", "isr-cache.json");
|
|
717
252
|
}
|
|
718
|
-
function
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
253
|
+
function persistIsrNow() {
|
|
254
|
+
if (SSR_WORKERS > 1)
|
|
255
|
+
return;
|
|
256
|
+
if (persistTimer) {
|
|
257
|
+
clearTimeout(persistTimer);
|
|
258
|
+
persistTimer = null;
|
|
723
259
|
}
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
}
|
|
728
|
-
|
|
729
|
-
// wins, else the page's ISR cadence; non-ISR pages with no directive are 0.
|
|
730
|
-
function regionInterval(page, region) {
|
|
731
|
-
if (region.revalidate && region.revalidate > 0)
|
|
732
|
-
return region.revalidate;
|
|
733
|
-
if (page.mode === "isr")
|
|
734
|
-
return page.revalidate || 60;
|
|
735
|
-
if (pprEnabled)
|
|
736
|
-
return pprRevalidate;
|
|
737
|
-
return 0;
|
|
738
|
-
}
|
|
739
|
-
async function renderRegionFresh(page, region, req) {
|
|
740
|
-
if (region.serverExport) {
|
|
741
|
-
const out = await withRenderTimeout(withCacheScope(page.route, () => withRequest(req, () => renderServerExport(page, region, req))));
|
|
742
|
-
return { html: out.result, scope: out.scope, invalidated: out.invalidated };
|
|
260
|
+
try {
|
|
261
|
+
const data = isrCache.serialize();
|
|
262
|
+
const file = isrCachePath();
|
|
263
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
264
|
+
fs.writeFileSync(file, JSON.stringify(data));
|
|
743
265
|
}
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
return { html: out.result, scope: out.scope, invalidated: out.invalidated };
|
|
747
|
-
}
|
|
748
|
-
function regionCacheable(r) {
|
|
749
|
-
return !r.scope.noStore && !r.invalidated;
|
|
750
|
-
}
|
|
751
|
-
// renderServerExport renders an async server component region with the page's
|
|
752
|
-
// own server bundle, which exports the component under region.serverExport.
|
|
753
|
-
async function renderServerExport(page, region, req) {
|
|
754
|
-
const mod = await loadPageModule(page);
|
|
755
|
-
const Comp = mod[region.serverExport];
|
|
756
|
-
if (typeof Comp !== "function") {
|
|
757
|
-
throw new Error(`server bundle for ${page.route} does not export ${region.serverExport}`);
|
|
266
|
+
catch (err) {
|
|
267
|
+
console.error("[krate-ssr] ISR cache persist failed:", err.message);
|
|
758
268
|
}
|
|
759
|
-
const props = regionProps(region, req);
|
|
760
|
-
if (props.params && typeof props.params === "object")
|
|
761
|
-
props.params = thenableRecord(props.params);
|
|
762
|
-
return renderToStringAsync(jsx(Comp, props));
|
|
763
269
|
}
|
|
764
|
-
function
|
|
765
|
-
|
|
270
|
+
function scheduleIsrPersist() {
|
|
271
|
+
// Clustered: multiple workers would race on the same cache file; keep the ISR
|
|
272
|
+
// cache in memory only.
|
|
273
|
+
if (SSR_WORKERS > 1)
|
|
766
274
|
return;
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
if (regionCacheable(r))
|
|
771
|
-
regionCacheSet(key, r.html, page, req, r.scope);
|
|
772
|
-
console.log(`[krate-ssr] Revalidated region ${key} (SWR)`);
|
|
773
|
-
}
|
|
774
|
-
catch (err) {
|
|
775
|
-
console.error(`[krate-ssr] Region SWR revalidation failed ${key}:`, err.message);
|
|
776
|
-
}
|
|
777
|
-
finally {
|
|
778
|
-
inFlightRegionRevalidations.delete(key);
|
|
779
|
-
}
|
|
780
|
-
})();
|
|
781
|
-
inFlightRegionRevalidations.set(key, p);
|
|
275
|
+
if (persistTimer)
|
|
276
|
+
clearTimeout(persistTimer);
|
|
277
|
+
persistTimer = setTimeout(persistIsrNow, 1000);
|
|
782
278
|
}
|
|
783
|
-
|
|
784
|
-
// pages. Returns an NDJSON frame.
|
|
785
|
-
async function renderRegion(page, region, req) {
|
|
786
|
-
if (!region.bundlePath && !region.serverExport) {
|
|
787
|
-
return { type: "error", id: region.id, status: 400, error: "region has no runtime bundle", fatal: !!page.serverComponents };
|
|
788
|
-
}
|
|
789
|
-
const key = regionCacheKey(page, region.id, req);
|
|
790
|
-
const interval = regionInterval(page, region);
|
|
791
|
-
const cacheable = interval > 0;
|
|
792
|
-
if (cacheable) {
|
|
793
|
-
regionRevalidation.set(key, interval);
|
|
794
|
-
const cached = regionCache.get(key);
|
|
795
|
-
const stale = cached && (Date.now() - cached.timestamp) / 1000 > interval;
|
|
796
|
-
if (cached && !stale) {
|
|
797
|
-
return { type: "region", id: region.id, status: 200, html: cached.html, cached: true, cacheStatus: "hit" };
|
|
798
|
-
}
|
|
799
|
-
if (cached) {
|
|
800
|
-
revalidateRegionInBackground(page, region, req, key);
|
|
801
|
-
return { type: "region", id: region.id, status: 200, html: cached.html, cached: true, cacheStatus: "stale" };
|
|
802
|
-
}
|
|
803
|
-
}
|
|
279
|
+
function loadIsrCache() {
|
|
804
280
|
try {
|
|
805
|
-
const
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
281
|
+
const file = isrCachePath();
|
|
282
|
+
if (fs.existsSync(file)) {
|
|
283
|
+
const data = JSON.parse(fs.readFileSync(file, "utf-8"));
|
|
284
|
+
isrCache.hydrate(data);
|
|
285
|
+
const n = isrCache.size;
|
|
286
|
+
if (n > 0)
|
|
287
|
+
console.log(`[krate-ssr] Loaded ${n} persisted ISR entries`);
|
|
809
288
|
}
|
|
810
|
-
const frame = { type: "region", id: region.id, status: 200, html };
|
|
811
|
-
if (cacheable)
|
|
812
|
-
frame.cacheStatus = "miss";
|
|
813
|
-
if (r.scope.noStore || r.invalidated)
|
|
814
|
-
frame.noStore = true;
|
|
815
|
-
return frame;
|
|
816
289
|
}
|
|
817
290
|
catch (err) {
|
|
818
|
-
|
|
819
|
-
if (signal) {
|
|
820
|
-
const frame = { type: "region", id: region.id, status: signal.status, html: "" };
|
|
821
|
-
if (signal.notFound)
|
|
822
|
-
frame.notFound = true;
|
|
823
|
-
if (signal.redirect)
|
|
824
|
-
frame.redirect = signal.redirect;
|
|
825
|
-
return frame;
|
|
826
|
-
}
|
|
827
|
-
console.error(`[krate-ssr] Region render failed ${page.route}::${region.id}:`, err);
|
|
828
|
-
// A server component region has no meaningful baked content, so its
|
|
829
|
-
// failure is fatal for the response (the Go server answers 500).
|
|
830
|
-
return { type: "error", id: region.id, status: 500, error: (err && err.message) || String(err), fatal: !!(region.serverExport || page.serverComponents) };
|
|
291
|
+
console.error("[krate-ssr] ISR cache load failed:", err.message);
|
|
831
292
|
}
|
|
832
293
|
}
|
|
833
|
-
|
|
834
|
-
res.write(JSON.stringify(obj) + "\n");
|
|
835
|
-
}
|
|
836
|
-
// renderPageRegion renders a coarse whole-page region (SSR/ISR pages whose
|
|
837
|
-
// entire body is request-time dynamic). It reuses renderPage so the page-level
|
|
838
|
-
// variant-aware ISR cache, stale-while-revalidate, and revalidation all apply.
|
|
839
|
-
// Returns an NDJSON region frame; the Go server splices html into the shell at
|
|
840
|
-
// the "page" marker and keeps the baked body when the render fails.
|
|
841
|
-
async function renderPageRegion(page, id, req) {
|
|
842
|
-
const result = await renderPage(req);
|
|
843
|
-
const frame = {
|
|
844
|
-
type: "region",
|
|
845
|
-
id,
|
|
846
|
-
kind: "page",
|
|
847
|
-
status: result.status || 200,
|
|
848
|
-
html: result.html || "",
|
|
849
|
-
};
|
|
850
|
-
if (result.cacheStatus)
|
|
851
|
-
frame.cacheStatus = result.cacheStatus;
|
|
852
|
-
if (result.notFound)
|
|
853
|
-
frame.notFound = true;
|
|
854
|
-
if (result.redirect)
|
|
855
|
-
frame.redirect = result.redirect;
|
|
856
|
-
if (result.error)
|
|
857
|
-
frame.error = result.error;
|
|
858
|
-
if (result.noStore)
|
|
859
|
-
frame.noStore = true;
|
|
860
|
-
if (page.serverComponents && frame.status >= 500)
|
|
861
|
-
frame.fatal = true;
|
|
862
|
-
// Title swap: the Go server replaces the baked <title> with the freshly
|
|
863
|
-
// rendered one so params-driven pages update the browser tab.
|
|
864
|
-
const title = extractTitle(result.html);
|
|
865
|
-
if (title !== "")
|
|
866
|
-
frame.title = title;
|
|
867
|
-
return frame;
|
|
868
|
-
}
|
|
869
|
-
function extractTitle(html) {
|
|
870
|
-
const match = html.match(/<title[^>]*>([\s\S]*?)<\/title>/i);
|
|
871
|
-
return match ? match[1].trim() : "";
|
|
872
|
-
}
|
|
294
|
+
loadIsrCache();
|
|
873
295
|
const INTERNAL_OPS = {
|
|
874
296
|
"/__krate/ssr/revalidate": "revalidate-route",
|
|
875
297
|
"/__krate/ssr/refresh": "refresh-route",
|
|
876
298
|
"/__krate/ssr/invalidate": "dev-invalidate",
|
|
877
299
|
"/__krate/ssr/cache-invalidate": "cache-invalidate",
|
|
878
300
|
};
|
|
879
|
-
function stringList(v) {
|
|
880
|
-
return Array.isArray(v) ? v.filter((x) => typeof x === "string" && x !== "") : [];
|
|
881
|
-
}
|
|
882
301
|
// applyInternalOp applies one internal operation to this process's caches.
|
|
883
302
|
async function applyInternalOp(op, payload) {
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
}
|
|
904
|
-
case "dev-invalidate": {
|
|
905
|
-
const { route: targetRoute, source, bundlePath } = payload;
|
|
906
|
-
// Invalidate ISR cache for this route (all variants)
|
|
907
|
-
isrCache.deleteRoute(targetRoute);
|
|
908
|
-
// Invalidate module cache for the source file or bundle
|
|
909
|
-
const key = bundlePath || source;
|
|
910
|
-
if (key && moduleCache.has(key)) {
|
|
911
|
-
moduleCache.delete(key);
|
|
912
|
-
console.log(`[krate-ssr] Invalidated cache for ${targetRoute} (${key})`);
|
|
913
|
-
}
|
|
914
|
-
// Runtime component bundles are recompiled in place on a dev rebuild, but
|
|
915
|
-
// their render functions are cached for the process lifetime. Clear them
|
|
916
|
-
// so the next region render picks up the new code. Bundles are tiny and
|
|
917
|
-
// re-read on demand, so clearing all of them is cheap and avoids tracking
|
|
918
|
-
// which component maps to which route here.
|
|
919
|
-
runtimeBundleCache.clear();
|
|
920
|
-
clearRegionCache();
|
|
921
|
-
return { ok: true };
|
|
922
|
-
}
|
|
923
|
-
case "cache-invalidate": {
|
|
924
|
-
const tags = stringList(payload.tags);
|
|
925
|
-
const targets = Array.isArray(payload.targets)
|
|
926
|
-
? payload.targets.filter((t) => t && typeof t.route === "string")
|
|
927
|
-
: [];
|
|
928
|
-
// Path targets also drop the data their renders cached (implicit tag).
|
|
929
|
-
const dataTags = tags.concat(targets.map((t) => routeDataTag(t.route)));
|
|
930
|
-
const { dataEntries } = cacheRuntime().invalidate({ tags: dataTags });
|
|
931
|
-
let isrEntries = 0;
|
|
932
|
-
let regionEntries = 0;
|
|
933
|
-
for (const t of targets) {
|
|
934
|
-
const params = t.params && typeof t.params === "object" ? t.params : null;
|
|
935
|
-
isrEntries += params ? isrCache.deleteVariant(t.route, params) : isrCache.deleteRoute(t.route);
|
|
936
|
-
regionEntries += invalidateRegions(t.route, params, []);
|
|
937
|
-
}
|
|
938
|
-
if (tags.length) {
|
|
939
|
-
isrEntries += isrCache.deleteTags(tags);
|
|
940
|
-
regionEntries += invalidateRegions(null, null, tags);
|
|
941
|
-
}
|
|
942
|
-
if (isrEntries > 0)
|
|
943
|
-
persistIsrNow();
|
|
944
|
-
return { ok: true, isrEntries, regionEntries, dataEntries };
|
|
945
|
-
}
|
|
946
|
-
}
|
|
303
|
+
if (op !== "dev-invalidate")
|
|
304
|
+
return core.applyInternalOp(op, payload);
|
|
305
|
+
const { route: targetRoute, source, bundlePath } = payload;
|
|
306
|
+
// Invalidate the page and region caches for this route, then the module
|
|
307
|
+
// cache for the source file or bundle.
|
|
308
|
+
const key = bundlePath || source;
|
|
309
|
+
if (key && moduleCache.has(key)) {
|
|
310
|
+
moduleCache.delete(key);
|
|
311
|
+
console.log(`[krate-ssr] Invalidated cache for ${targetRoute} (${key})`);
|
|
312
|
+
}
|
|
313
|
+
// Runtime component bundles are recompiled in place on a dev rebuild, but
|
|
314
|
+
// their render functions are cached for the process lifetime. Clear them
|
|
315
|
+
// so the next region render picks up the new code.
|
|
316
|
+
runtimeBundleCache.clear();
|
|
317
|
+
core.devInvalidate(targetRoute);
|
|
318
|
+
return { ok: true };
|
|
319
|
+
}
|
|
320
|
+
function writeJsonLine(res, obj) {
|
|
321
|
+
res.write(JSON.stringify(obj) + "\n");
|
|
947
322
|
}
|
|
948
323
|
// Cluster fan-out (worker side). broadcastInternalOp resolves with one result
|
|
949
324
|
// per live worker once every worker applied the operation.
|
|
@@ -997,32 +372,6 @@ function mergeOpResults(op, results) {
|
|
|
997
372
|
}
|
|
998
373
|
return out;
|
|
999
374
|
}
|
|
1000
|
-
// HTTP Server
|
|
1001
|
-
const PORT = parseInt(process.env.KRATE_SSR_PORT || "3100", 10);
|
|
1002
|
-
const manifestPath = process.env.KRATE_MANIFEST || "";
|
|
1003
|
-
const root = process.env.KRATE_ROOT || process.cwd();
|
|
1004
|
-
const OUT_DIR = process.env.KRATE_OUT_DIR || path.join(root, "dist");
|
|
1005
|
-
projectRoot = root;
|
|
1006
|
-
// Load manifest
|
|
1007
|
-
if (manifestPath && fs.existsSync(manifestPath)) {
|
|
1008
|
-
const data = fs.readFileSync(manifestPath, "utf-8");
|
|
1009
|
-
manifest = JSON.parse(data);
|
|
1010
|
-
console.log(`[krate-ssr] Loaded manifest: ${manifest.pages.length} SSR/ISR/streaming pages`);
|
|
1011
|
-
}
|
|
1012
|
-
else {
|
|
1013
|
-
// Try default location
|
|
1014
|
-
const krateDefault = path.join(OUT_DIR, ".krate", "server-manifest.json");
|
|
1015
|
-
const defaultPath = fs.existsSync(krateDefault) ? krateDefault : path.join(OUT_DIR, "server-manifest.json");
|
|
1016
|
-
if (fs.existsSync(defaultPath)) {
|
|
1017
|
-
const data = fs.readFileSync(defaultPath, "utf-8");
|
|
1018
|
-
manifest = JSON.parse(data);
|
|
1019
|
-
console.log(`[krate-ssr] Loaded manifest: ${manifest.pages.length} SSR/ISR/streaming pages`);
|
|
1020
|
-
}
|
|
1021
|
-
else {
|
|
1022
|
-
console.error("[krate-ssr] No manifest found. SSR pages will not be served.");
|
|
1023
|
-
}
|
|
1024
|
-
}
|
|
1025
|
-
loadIsrCache();
|
|
1026
375
|
function parseBody(req) {
|
|
1027
376
|
return new Promise((resolve) => {
|
|
1028
377
|
let body = "";
|
|
@@ -1168,6 +517,13 @@ const server = http.createServer(async (req, res) => {
|
|
|
1168
517
|
}
|
|
1169
518
|
return;
|
|
1170
519
|
}
|
|
520
|
+
if (result.denied) {
|
|
521
|
+
const denied = path.join(OUT_DIR, result.denied + ".html");
|
|
522
|
+
const fallback = result.denied === 403 ? "<html><body><h1>403 Forbidden</h1></body></html>" : "<html><body><h1>401 Unauthorized</h1></body></html>";
|
|
523
|
+
res.writeHead(result.denied, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store" });
|
|
524
|
+
res.end(fs.existsSync(denied) ? fs.readFileSync(denied, "utf-8") : fallback);
|
|
525
|
+
return;
|
|
526
|
+
}
|
|
1171
527
|
if (result.redirect) {
|
|
1172
528
|
res.writeHead(result.status === 307 ? 307 : 302, { Location: result.redirect });
|
|
1173
529
|
res.end();
|
|
@@ -1195,7 +551,9 @@ const server = http.createServer(async (req, res) => {
|
|
|
1195
551
|
headers_extra["X-Krate-Cache"] = result.cacheStatus === "stale" ? "STALE" : "HIT";
|
|
1196
552
|
}
|
|
1197
553
|
res.writeHead(result.status, headers_extra);
|
|
1198
|
-
|
|
554
|
+
// A direct page response has no document to merge into: <Head> children stay
|
|
555
|
+
// where they rendered, without their markers.
|
|
556
|
+
res.end(result.html.replace(/<!--\/?krate-head-->/g, ""));
|
|
1199
557
|
});
|
|
1200
558
|
if (isClusterPrimary) {
|
|
1201
559
|
// The primary only supervises; workers own the listening socket.
|