@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.
Files changed (165) hide show
  1. package/dist/action-context.d.ts +5 -1
  2. package/dist/action-context.js +33 -3
  3. package/dist/action-context.test.js +26 -1
  4. package/dist/actions.d.ts +12 -1
  5. package/dist/actions.js +84 -4
  6. package/dist/actions.test.js +61 -1
  7. package/dist/assets-static.d.ts +5 -0
  8. package/dist/assets-static.js +31 -0
  9. package/dist/boundary.d.ts +12 -0
  10. package/dist/boundary.js +53 -13
  11. package/dist/cache-adapter.d.ts +113 -0
  12. package/dist/cache-adapter.js +217 -0
  13. package/dist/cache-adapter.test.d.ts +1 -0
  14. package/dist/cache-adapter.test.js +244 -0
  15. package/dist/cache-redis.d.ts +27 -0
  16. package/dist/cache-redis.js +110 -0
  17. package/dist/cache-scope.d.ts +25 -9
  18. package/dist/cache-scope.js +64 -13
  19. package/dist/cache.d.ts +1 -0
  20. package/dist/cache.js +3 -3
  21. package/dist/cache.test.js +16 -0
  22. package/dist/class-component.js +6 -0
  23. package/dist/class-component.test.js +53 -2
  24. package/dist/class-helpers.d.ts +4 -4
  25. package/dist/class-helpers.js +357 -32
  26. package/dist/class-helpers.test.d.ts +1 -0
  27. package/dist/class-helpers.test.js +169 -0
  28. package/dist/context.d.ts +16 -2
  29. package/dist/context.js +44 -3
  30. package/dist/dev-overlay.js +85 -12
  31. package/dist/dev-overlay.test.js +22 -0
  32. package/dist/dom.d.ts +15 -0
  33. package/dist/dom.js +97 -3
  34. package/dist/effect-errors.test.d.ts +1 -0
  35. package/dist/effect-errors.test.js +163 -0
  36. package/dist/effects.d.ts +8 -0
  37. package/dist/effects.js +13 -0
  38. package/dist/error-overlay.js +7 -7
  39. package/dist/handler-html.d.ts +63 -0
  40. package/dist/handler-html.js +285 -0
  41. package/dist/handler-html.test.d.ts +1 -0
  42. package/dist/handler-html.test.js +256 -0
  43. package/dist/handler-routing.d.ts +83 -0
  44. package/dist/handler-routing.js +579 -0
  45. package/dist/handler-routing.test.d.ts +1 -0
  46. package/dist/handler-routing.test.js +99 -0
  47. package/dist/handler-segments.d.ts +43 -0
  48. package/dist/handler-segments.js +115 -0
  49. package/dist/handler-segments.test.d.ts +1 -0
  50. package/dist/handler-segments.test.js +217 -0
  51. package/dist/head-tags.d.ts +51 -0
  52. package/dist/head-tags.js +329 -0
  53. package/dist/head-tags.test.d.ts +1 -0
  54. package/dist/head-tags.test.js +131 -0
  55. package/dist/highlight-bind.d.ts +42 -0
  56. package/dist/highlight-bind.js +176 -0
  57. package/dist/highlight-bind.test.d.ts +1 -0
  58. package/dist/highlight-bind.test.js +124 -0
  59. package/dist/highlight.d.ts +93 -0
  60. package/dist/highlight.js +426 -0
  61. package/dist/highlight.test.d.ts +1 -0
  62. package/dist/highlight.test.js +56 -0
  63. package/dist/hints.d.ts +19 -0
  64. package/dist/hints.js +97 -0
  65. package/dist/hook-args.d.ts +7 -0
  66. package/dist/hook-args.js +10 -0
  67. package/dist/htmlspec-attributes.d.ts +1 -0
  68. package/dist/htmlspec-attributes.js +159 -0
  69. package/dist/index.d.ts +4 -0
  70. package/dist/index.js +3 -0
  71. package/dist/jsx-types.d.ts +11 -0
  72. package/dist/krate-core.js +2 -0
  73. package/dist/krate-dev.js +75 -12
  74. package/dist/krate-f-actions.js +2 -0
  75. package/dist/krate-f-classes.js +8 -0
  76. package/dist/krate-f-helpers.js +2 -0
  77. package/dist/krate-f-highlight.js +2 -0
  78. package/dist/krate-f-list.js +2 -0
  79. package/dist/krate-f-navigation.js +2 -0
  80. package/dist/krate-f-router-lite.js +2 -0
  81. package/dist/krate-f-router.js +2 -0
  82. package/dist/krate-features.json +493 -0
  83. package/dist/krate-hydrate-lite.js +5 -5
  84. package/dist/krate-hydrate.js +5 -5
  85. package/dist/krate-runtime.js +5 -5
  86. package/dist/list.js +4 -2
  87. package/dist/metadata-routes.d.ts +75 -0
  88. package/dist/metadata-routes.js +76 -0
  89. package/dist/metadata.d.ts +222 -0
  90. package/dist/metadata.js +452 -0
  91. package/dist/metadata.test.d.ts +1 -0
  92. package/dist/metadata.test.js +167 -0
  93. package/dist/navigation-server.d.ts +27 -0
  94. package/dist/navigation-server.js +90 -0
  95. package/dist/navigation.d.ts +37 -0
  96. package/dist/navigation.js +195 -0
  97. package/dist/navigation.test.d.ts +1 -0
  98. package/dist/navigation.test.js +130 -0
  99. package/dist/node-server.d.ts +22 -0
  100. package/dist/node-server.js +436 -0
  101. package/dist/node-server.test.d.ts +1 -0
  102. package/dist/node-server.test.js +492 -0
  103. package/dist/og-files.d.ts +2 -0
  104. package/dist/og-files.js +19 -0
  105. package/dist/og.d.ts +56 -0
  106. package/dist/og.js +156 -0
  107. package/dist/patterns.test.d.ts +1 -0
  108. package/dist/patterns.test.js +98 -0
  109. package/dist/react.d.ts +47 -0
  110. package/dist/react.js +59 -1
  111. package/dist/react19.test.d.ts +1 -0
  112. package/dist/react19.test.js +176 -0
  113. package/dist/reactivity-core.test.d.ts +1 -0
  114. package/dist/reactivity-core.test.js +152 -0
  115. package/dist/reconcile.js +4 -2
  116. package/dist/request-context.d.ts +23 -0
  117. package/dist/request-context.js +45 -0
  118. package/dist/resp.d.ts +55 -0
  119. package/dist/resp.js +239 -0
  120. package/dist/router-layout.test.js +70 -0
  121. package/dist/router-nav.test.js +65 -0
  122. package/dist/router-speculation.test.d.ts +1 -0
  123. package/dist/router-speculation.test.js +25 -0
  124. package/dist/router-styles.test.d.ts +1 -0
  125. package/dist/router-styles.test.js +98 -0
  126. package/dist/router.js +175 -36
  127. package/dist/segmented-lru.d.ts +19 -0
  128. package/dist/segmented-lru.js +87 -0
  129. package/dist/server-async.test.js +43 -1
  130. package/dist/server-handler.d.ts +165 -0
  131. package/dist/server-handler.js +1826 -0
  132. package/dist/server-handler.test.d.ts +1 -0
  133. package/dist/server-handler.test.js +522 -0
  134. package/dist/server-highlight.test.d.ts +1 -0
  135. package/dist/server-highlight.test.js +32 -0
  136. package/dist/server-renderer.js +165 -720
  137. package/dist/server-renderer.test.d.ts +1 -0
  138. package/dist/server-renderer.test.js +266 -0
  139. package/dist/server.d.ts +13 -1
  140. package/dist/server.js +131 -16
  141. package/dist/server.test.js +20 -0
  142. package/dist/sha256.d.ts +1 -0
  143. package/dist/sha256.js +66 -0
  144. package/dist/sha256.test.d.ts +1 -0
  145. package/dist/sha256.test.js +13 -0
  146. package/dist/shared-isr.d.ts +31 -0
  147. package/dist/shared-isr.js +142 -0
  148. package/dist/signal.d.ts +3 -2
  149. package/dist/signal.js +163 -23
  150. package/dist/slots.js +12 -1
  151. package/dist/ssr-core-behavior.test.d.ts +1 -0
  152. package/dist/ssr-core-behavior.test.js +620 -0
  153. package/dist/ssr-core.d.ts +175 -0
  154. package/dist/ssr-core.js +940 -0
  155. package/dist/ssr-core.test.d.ts +1 -0
  156. package/dist/ssr-core.test.js +324 -0
  157. package/dist/static-memory.d.ts +3 -0
  158. package/dist/static-memory.js +47 -0
  159. package/dist/static-memory.test.d.ts +1 -0
  160. package/dist/static-memory.test.js +26 -0
  161. package/dist/test-redis.d.ts +12 -0
  162. package/dist/test-redis.js +131 -0
  163. package/dist/use-id.d.ts +8 -0
  164. package/dist/use-id.js +40 -0
  165. package/package.json +30 -2
@@ -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 { jsx, renderToStringAsync } from "./server.js";
12
- import { isNotFoundSignal, parseCookieHeader, redirectTarget, thenableRecord, } from "./request-context.js";
13
- import { cacheRuntime, installRenderStore, patchFetch, routeDataTag, withCacheScope, } from "./cache-scope.js";
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,220 +105,69 @@ function setupStream(res) {
103
105
  socket.setNoDelay(true);
104
106
  }
105
107
  }
106
- // ISR Cache (variant-aware, SWR, persisted)
107
- // A page's cache key is the route plus its per-request variant (params +
108
- // query). Two dynamic-route requests (e.g. /video/a and /video/b) render
109
- // different HTML, so they must never share a cache slot.
110
- function variantKey(req) {
111
- const enc = (v) => Object.keys(v).sort().map((k) => `${encodeURIComponent(k)}=${encodeURIComponent(v[k])}`).join("&");
112
- const params = req.params ? enc(req.params) : "";
113
- const query = req.query ? enc(req.query) : "";
114
- let key = req.route;
115
- if (params)
116
- key += "?" + params;
117
- if (query)
118
- key += "#" + query;
119
- return key;
120
- }
121
- class ISRCache {
122
- constructor(maxSize = 512) {
123
- this.cache = new Map();
124
- this.byTag = new Map();
125
- this.revalidationIntervals = new Map(); // route → seconds
126
- this.maxSize = maxSize;
127
- }
128
- setRevalidation(route, seconds) {
129
- this.revalidationIntervals.set(route, seconds);
130
- }
131
- get(key) {
132
- return this.cache.get(key);
133
- }
134
- set(key, entry) {
135
- if (this.cache.has(key))
136
- this.delete(key);
137
- if (this.cache.size >= this.maxSize) {
138
- const oldest = this.cache.keys().next().value;
139
- if (oldest)
140
- this.delete(oldest);
141
- }
142
- this.cache.set(key, entry);
143
- for (const t of entry.tags || []) {
144
- let keys = this.byTag.get(t);
145
- if (!keys)
146
- this.byTag.set(t, (keys = new Set()));
147
- keys.add(key);
148
- }
149
- }
150
- delete(key) {
151
- const entry = this.cache.get(key);
152
- if (!entry)
153
- return false;
154
- this.cache.delete(key);
155
- for (const t of entry.tags || []) {
156
- const keys = this.byTag.get(t);
157
- if (keys) {
158
- keys.delete(key);
159
- if (keys.size === 0)
160
- this.byTag.delete(t);
161
- }
162
- }
163
- return true;
164
- }
165
- get size() {
166
- return this.cache.size;
167
- }
168
- isStale(key) {
169
- const entry = this.cache.get(key);
170
- const route = key.split("?")[0].split("#")[0];
171
- let interval = this.revalidationIntervals.get(route) || 0;
172
- if (entry && entry.revalidate && entry.revalidate > 0 && (!interval || entry.revalidate < interval)) {
173
- interval = entry.revalidate;
174
- }
175
- if (!entry || !interval)
176
- return false;
177
- return (Date.now() - entry.timestamp) / 1000 > interval;
178
- }
179
- // deleteRoute removes every variant of a route (used by revalidation/invalidation).
180
- deleteRoute(route) {
181
- let n = 0;
182
- for (const key of [...this.cache.keys()]) {
183
- if (key === route || key.startsWith(route + "?") || key.startsWith(route + "#")) {
184
- if (this.delete(key))
185
- n++;
186
- }
187
- }
188
- return n;
189
- }
190
- // deleteVariant removes one params variant of a route (every query variant
191
- // of it), e.g. /blog/[slug] with {slug: "a"} for revalidatePath("/blog/a").
192
- deleteVariant(route, params) {
193
- const base = variantKey({ route, params });
194
- let n = 0;
195
- for (const key of [...this.cache.keys()]) {
196
- if (key === base || key.startsWith(base + "#")) {
197
- if (this.delete(key))
198
- n++;
199
- }
200
- }
201
- return n;
202
- }
203
- // deleteTags removes every entry whose render read one of tags.
204
- deleteTags(tags) {
205
- let n = 0;
206
- for (const t of tags) {
207
- const keys = this.byTag.get(t);
208
- if (!keys)
209
- continue;
210
- for (const key of [...keys]) {
211
- if (this.delete(key))
212
- n++;
213
- }
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);
214
119
  }
215
- return n;
216
- }
217
- // entriesForRoute returns a snapshot of the cached variants for a route so a
218
- // background refresh can iterate them without mutating during iteration.
219
- entriesForRoute(route) {
220
- const out = [];
221
- for (const [key, entry] of this.cache) {
222
- if (key === route || key.startsWith(route + "?") || key.startsWith(route + "#")) {
223
- out.push([key, entry]);
224
- }
120
+ catch (e) {
121
+ if (!e || e.code !== "EPERM")
122
+ process.exit(0);
225
123
  }
226
- return out;
227
- }
228
- serialize() {
229
- return {
230
- entries: [...this.cache.entries()].map(([key, entry]) => ({ key, ...entry })),
231
- };
232
- }
233
- hydrate(data) {
234
- if (!data || !Array.isArray(data.entries))
235
- return;
236
- for (const e of data.entries) {
237
- if (e && typeof e.key === "string" && typeof e.html === "string") {
238
- this.set(e.key, {
239
- html: e.html,
240
- timestamp: typeof e.timestamp === "number" ? e.timestamp : Date.now(),
241
- params: e.params && typeof e.params === "object" ? e.params : undefined,
242
- query: e.query && typeof e.query === "object" ? e.query : undefined,
243
- tags: Array.isArray(e.tags) ? e.tags.filter((t) => typeof t === "string") : undefined,
244
- revalidate: typeof e.revalidate === "number" ? e.revalidate : undefined,
245
- });
246
- }
247
- }
248
- }
249
- }
250
- // ISR cache size and the render timeout are configurable via the compiler
251
- // (ssr.maxCacheSize / ssr.timeout), which exports them to the sidecar env.
252
- const isrCache = new ISRCache(parseInt(process.env.KRATE_SSR_MAX_CACHE || "", 10) || 512);
253
- // renderTimeoutMs bounds a single renderToString call so one pathological page
254
- // cannot pin the sidecar. 0 disables the bound.
255
- const renderTimeoutMs = parseInt(process.env.KRATE_SSR_TIMEOUT || "", 10) || 5000;
256
- // Partial Prerendering: cache dynamic regions on non-ISR pages with this
257
- // window (overridable per region via `export const revalidate`).
258
- const pprEnabled = process.env.KRATE_PPR === "1";
259
- const pprRevalidate = parseInt(process.env.KRATE_PPR_REVALIDATE || "", 10) || 60;
260
- // withRenderTimeout rejects if p does not settle within renderTimeoutMs. The
261
- // underlying render keeps running (JS cannot cancel it), but the request fails
262
- // fast rather than hanging.
263
- function withRenderTimeout(p) {
264
- if (renderTimeoutMs <= 0)
265
- return p;
266
- return new Promise((resolve, reject) => {
267
- const timer = setTimeout(() => reject(new Error(`render timed out after ${renderTimeoutMs}ms`)), renderTimeoutMs);
268
- p.then((v) => { clearTimeout(timer); resolve(v); }, (e) => { clearTimeout(timer); reject(e); });
269
- });
124
+ }, 2000);
125
+ parentWatch.unref();
270
126
  }
271
- // ISR cache persistence - survives renderer restarts so a bounce doesn't
272
- // cold-render every ISR variant. Written debounced (coalesced) to the build
273
- // output dir (.krate/isr-cache.json), overridable via KRATE_ISR_CACHE.
274
- let isrCacheFile = process.env.KRATE_ISR_CACHE || "";
275
- let persistTimer = null;
276
- function isrCachePath() {
277
- return isrCacheFile || path.join(root, "dist", ".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`);
278
132
  }
279
- function persistIsrNow() {
280
- if (SSR_WORKERS > 1)
281
- return;
282
- if (persistTimer) {
283
- clearTimeout(persistTimer);
284
- persistTimer = null;
285
- }
286
- try {
287
- const data = isrCache.serialize();
288
- const file = isrCachePath();
289
- fs.mkdirSync(path.dirname(file), { recursive: true });
290
- 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`);
291
141
  }
292
- catch (err) {
293
- console.error("[krate-ssr] ISR cache persist failed:", err.message);
142
+ else {
143
+ console.error("[krate-ssr] No manifest found. SSR pages will not be served.");
294
144
  }
295
145
  }
296
- function scheduleIsrPersist() {
297
- // Clustered: multiple workers would race on the same cache file; keep the ISR
298
- // cache in memory only.
299
- if (SSR_WORKERS > 1)
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))
300
151
  return;
301
- if (persistTimer)
302
- clearTimeout(persistTimer);
303
- persistTimer = setTimeout(persistIsrNow, 1000);
304
- }
305
- function loadIsrCache() {
306
152
  try {
307
- const file = isrCachePath();
308
- if (fs.existsSync(file)) {
309
- const data = JSON.parse(fs.readFileSync(file, "utf-8"));
310
- isrCache.hydrate(data);
311
- const n = isrCache.size;
312
- if (n > 0)
313
- console.log(`[krate-ssr] Loaded ${n} persisted ISR entries`);
314
- }
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);
315
168
  }
316
- catch (err) {
317
- console.error("[krate-ssr] ISR cache load failed:", err.message);
318
- }
319
- }
169
+ })();
170
+ // Module loaders (node:fs / node:vm live here, not in the render core)
320
171
  // Page Module Loader
321
172
  const moduleCache = new Map();
322
173
  async function loadPageModule(page) {
@@ -328,7 +179,7 @@ async function loadPageModule(page) {
328
179
  let fileUrl;
329
180
  if (page.bundlePath) {
330
181
  // Pre-compiled bundle: bundlePath is relative to outDir (dist/)
331
- const bundleAbs = path.resolve(root, "dist", page.bundlePath);
182
+ const bundleAbs = path.resolve(OUT_DIR, page.bundlePath);
332
183
  fileUrl = pathToFileURL(bundleAbs).href;
333
184
  }
334
185
  else {
@@ -345,237 +196,14 @@ async function loadPageModule(page) {
345
196
  throw err;
346
197
  }
347
198
  }
348
- // Renderer
349
- let manifest = null;
350
- let projectRoot = "";
351
- function findPage(route) {
352
- if (!manifest)
353
- return undefined;
354
- // Try exact match first, then strip trailing slash
355
- let page = manifest.pages.find((p) => p.route === route);
356
- if (!page && route !== "/") {
357
- page = manifest.pages.find((p) => p.route === route + "/");
358
- }
359
- if (!page && route.endsWith("/")) {
360
- page = manifest.pages.find((p) => p.route === route.slice(0, -1));
361
- }
362
- return page;
363
- }
364
- // Request scope for server components: headers()/cookies() from
365
- // @krate/runtime/server read it through the global store symbol, so it works
366
- // no matter which copy of the runtime a page bundle resolved.
367
- const requestStore = (() => {
368
- const key = Symbol.for("krate.request.store");
369
- const g = globalThis;
370
- if (!g[key])
371
- g[key] = new AsyncLocalStorage();
372
- return g[key];
373
- })();
374
- function requestContextFor(req) {
375
- const h = new Headers();
376
- for (const [k, v] of Object.entries(req.headers || {})) {
377
- if (typeof v === "string") {
378
- try {
379
- h.set(k, v);
380
- }
381
- catch {
382
- // skip header names the WHATWG Headers class rejects
383
- }
384
- }
385
- }
386
- return {
387
- url: req.url || req.route,
388
- method: req.method || "GET",
389
- headers: h,
390
- cookies: parseCookieHeader(h.get("cookie")),
391
- params: { ...(req.params || {}) },
392
- searchParams: { ...(req.query || {}) },
393
- };
394
- }
395
- function withRequest(req, fn) {
396
- return requestStore.run(requestContextFor(req), fn);
397
- }
398
- // renderSignal maps notFound()/redirect() thrown during a render to a response.
399
- function renderSignal(err) {
400
- if (isNotFoundSignal(err))
401
- return { html: "", status: 404, notFound: true };
402
- const to = redirectTarget(err);
403
- if (to)
404
- return { html: "", status: 307, redirect: to };
405
- return null;
406
- }
407
- function buildProps(req) {
408
- // Page-level data fetching (getStaticProps/getServerSideProps) has been
409
- // removed; per-request data is provided by server components (@server),
410
- // runtime components (@runtime), and middleware instead. Dynamic-route
411
- // params and query parameters extracted by the Go server are forwarded so
412
- // `({ params }) => ...` pages receive their real values at render time.
413
- // params and searchParams are plain objects that can also be awaited, so
414
- // both `params.slug` and Next.js 15's `const { slug } = await params` work.
415
- // The Go server always forwards params (empty for static routes); a direct
416
- // request without them keeps params undefined, as before.
417
- const props = {};
418
- if (req.params)
419
- props.params = thenableRecord(req.params);
420
- props.searchParams = thenableRecord(req.query);
421
- if (req.query)
422
- props.query = req.query;
423
- return props;
424
- }
425
- // renderFresh renders a page component and - for ISR pages - stores the result.
426
- // Extracted so background revalidation shares exactly the same render path.
427
- async function renderFresh(page, req) {
428
- try {
429
- const mod = await loadPageModule(page);
430
- const Component = mod.default;
431
- if (!Component) {
432
- return { html: "", status: 500 };
433
- }
434
- // The render runs in a cache scope that records the tags / revalidate
435
- // windows its data reads declared (fetch next options, unstable_cache).
436
- // Async server components (and plain sync pages) render through
437
- // renderToStringAsync inside the request scope. The timeout bounds slow
438
- // awaits (fetch); a page that blocks synchronously still blocks the loop.
439
- const { result: html, scope, invalidated } = await withRenderTimeout(withCacheScope(page.route, () => withRequest(req, () => renderToStringAsync(jsx(Component, buildProps(req))))));
440
- const response = {
441
- html,
442
- status: 200,
443
- };
444
- // An uncacheable read (no-store) keeps the render out of the ISR cache, and
445
- // a revalidation that landed mid-render means the HTML may be stale.
446
- if (page.mode === "isr" && !scope.noStore && !invalidated) {
447
- isrCache.set(variantKey(req), {
448
- html,
449
- timestamp: Date.now(),
450
- params: req.params,
451
- query: req.query,
452
- tags: scope.tags.size ? [...scope.tags] : undefined,
453
- revalidate: scope.revalidate || undefined,
454
- });
455
- scheduleIsrPersist();
456
- }
457
- return response;
458
- }
459
- catch (err) {
460
- const signal = renderSignal(err);
461
- if (signal)
462
- return signal;
463
- console.error(`[krate] Error rendering ${req.route}:`, err);
464
- return { html: "", status: 500, error: (err && err.message) || String(err) };
465
- }
466
- }
467
- // Single-flight background revalidation for stale-while-revalidate. While a
468
- // revalidation for a given variant is in flight, concurrent requests share the
469
- // same promise instead of stampeding the renderer.
470
- const inFlightRevalidations = new Map();
471
- function revalidateInBackground(page, req) {
472
- const key = variantKey(req);
473
- if (inFlightRevalidations.has(key))
474
- return;
475
- const p = (async () => {
476
- try {
477
- const rendered = await renderFresh(page, req);
478
- if (rendered.status === 200) {
479
- console.log(`[krate-ssr] Revalidated ${key} (SWR)`);
480
- }
481
- }
482
- catch (err) {
483
- console.error(`[krate-ssr] SWR revalidation failed ${key}:`, err.message);
484
- }
485
- finally {
486
- inFlightRevalidations.delete(key);
487
- }
488
- })();
489
- inFlightRevalidations.set(key, p);
490
- }
491
- // Time-based ISR regeneration: re-render every cached variant of a route while
492
- // keeping the entries in place. This is the non-destructive counterpart of
493
- // /__krate/ssr/revalidate (which clears a route). The Go server's periodic ISR
494
- // timer calls this so cached pages stay fresh without evicting dynamic
495
- // variants - eviction would turn a request that should be a HIT into a MISS.
496
- const inFlightRouteRefreshes = new Map();
497
- function refreshRouteVariants(page) {
498
- const running = inFlightRouteRefreshes.get(page.route);
499
- if (running)
500
- return running;
501
- const p = (async () => {
502
- try {
503
- const variants = isrCache.entriesForRoute(page.route);
504
- let refreshed = 0;
505
- for (const [, entry] of variants) {
506
- const req = {
507
- route: page.route,
508
- url: page.route,
509
- method: "GET",
510
- headers: {},
511
- params: entry.params,
512
- query: entry.query,
513
- };
514
- const rendered = await renderFresh(page, req);
515
- if (rendered.status === 200)
516
- refreshed++;
517
- }
518
- return refreshed;
519
- }
520
- finally {
521
- inFlightRouteRefreshes.delete(page.route);
522
- }
523
- })();
524
- inFlightRouteRefreshes.set(page.route, p);
525
- return p;
526
- }
527
- async function renderPage(req) {
528
- const page = findPage(req.route);
529
- if (!page) {
530
- return { html: "", status: 404, notFound: true };
531
- }
532
- // ISR: serve from cache with stale-while-revalidate.
533
- if (page.mode === "isr") {
534
- const interval = page.revalidate || 60;
535
- isrCache.setRevalidation(page.route, interval);
536
- const key = variantKey(req);
537
- const cached = isrCache.get(key);
538
- if (cached && !isrCache.isStale(key)) {
539
- return {
540
- html: cached.html,
541
- status: 200,
542
- cached: true,
543
- cacheStatus: "hit",
544
- };
545
- }
546
- if (cached) {
547
- // Entry is stale: serve it immediately and refresh in the background so
548
- // the next request (and any concurrent ones) get fresh HTML. No stampede:
549
- // revalidateInBackground is single-flight per variant key.
550
- revalidateInBackground(page, req);
551
- return {
552
- html: cached.html,
553
- status: 200,
554
- cached: true,
555
- cacheStatus: "stale",
556
- };
557
- }
558
- }
559
- const response = await renderFresh(page, req);
560
- if (page.mode === "isr")
561
- response.cacheStatus = "miss";
562
- return response;
563
- }
564
- // Region rendering (static-first)
565
- // The Go server owns the page: it serves the build-time static shell with the
566
- // <!-suspense:ID-> markers and baked fallbacks, then asks the sidecar to render
567
- // ONLY the page's dynamic regions. Each region is rendered by its compiled
568
- // runtime component bundle (server-components/<Name>.runtime.js - an IIFE that
569
- // defines globalThis.__krate_render(propsJSON)) with the build-time baked props,
570
- // so nothing is re-derived at request time.
571
199
  const runtimeBundleCache = new Map();
572
200
  // loadRuntimeRenderer loads a compiled runtime component bundle and returns its
573
- // __krate_render(propsJSON) function. Bundles are cached by bundle path.
201
+ // __krate_render(props) function (props as an object or JSON). Bundles are cached by bundle path.
574
202
  function loadRuntimeRenderer(relPath) {
575
203
  const cached = runtimeBundleCache.get(relPath);
576
204
  if (cached)
577
205
  return cached;
578
- const abs = path.resolve(root, "dist", relPath);
206
+ const abs = path.resolve(OUT_DIR, relPath);
579
207
  const code = fs.readFileSync(abs, "utf-8");
580
208
  // Runtime components get the host's fetch (looked up per call, so a cache
581
209
  // layer that wraps globalThis.fetch later still applies) and the web
@@ -594,281 +222,103 @@ function loadRuntimeRenderer(relPath) {
594
222
  runtimeBundleCache.set(relPath, render);
595
223
  return render;
596
224
  }
597
- function regionProps(region, req) {
598
- const props = { ...(region.props || {}) };
599
- if (req.params && Object.keys(req.params).length > 0)
600
- props.params = req.params;
601
- if (req.query && Object.keys(req.query).length > 0)
602
- props.query = req.query;
603
- return props;
604
- }
605
- const regionCache = new Map();
606
- const regionRevalidation = new Map();
607
- const inFlightRegionRevalidations = new Map();
608
- // Region cache is bounded (FIFO eviction) so a long-lived sidecar cannot grow
609
- // without limit across many dynamic region variants.
610
- const REGION_CACHE_MAX = parseInt(process.env.KRATE_SSR_MAX_CACHE || "", 10) || 512;
611
- function paramsKeyOf(params) {
612
- return variantKey({ route: "", params });
613
- }
614
- function regionCacheSet(key, html, page, req, scope) {
615
- if (regionCache.size >= REGION_CACHE_MAX && !regionCache.has(key)) {
616
- const oldest = regionCache.keys().next().value;
617
- if (oldest !== undefined)
618
- regionCache.delete(oldest);
619
- }
620
- regionCache.set(key, {
621
- html,
622
- timestamp: Date.now(),
623
- route: page.route,
624
- paramsKey: paramsKeyOf(req.params),
625
- tags: scope && scope.tags.size ? [...scope.tags] : undefined,
626
- });
627
- }
628
- // invalidateRegions removes region entries for a route (optionally one params
629
- // variant) and/or entries whose render read one of tags.
630
- function invalidateRegions(route, params, tags) {
631
- const pkey = params ? paramsKeyOf(params) : null;
632
- let n = 0;
633
- for (const [key, e] of Array.from(regionCache.entries())) {
634
- const routeHit = route !== null && e.route === route && (pkey === null || e.paramsKey === pkey);
635
- const tagHit = tags.length > 0 && !!e.tags && e.tags.some((t) => tags.includes(t));
636
- if (routeHit || tagHit) {
637
- regionCache.delete(key);
638
- n++;
639
- }
640
- }
641
- return n;
642
- }
643
- function clearRegionCache() {
644
- regionCache.clear();
645
- 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");
646
252
  }
647
- function clearRegionCacheForRoute(route) {
648
- const prefix = route + "::";
649
- for (const key of Array.from(regionCache.keys())) {
650
- if (key.startsWith(prefix))
651
- regionCache.delete(key);
253
+ function persistIsrNow() {
254
+ if (SSR_WORKERS > 1)
255
+ return;
256
+ if (persistTimer) {
257
+ clearTimeout(persistTimer);
258
+ persistTimer = null;
652
259
  }
653
- }
654
- function regionCacheKey(page, regionId, req) {
655
- return variantKey({ route: page.route + "::" + regionId, params: req.params, query: req.query });
656
- }
657
- // regionInterval resolves a region's cache window: its own revalidate directive
658
- // wins, else the page's ISR cadence; non-ISR pages with no directive are 0.
659
- function regionInterval(page, region) {
660
- if (region.revalidate && region.revalidate > 0)
661
- return region.revalidate;
662
- if (page.mode === "isr")
663
- return page.revalidate || 60;
664
- if (pprEnabled)
665
- return pprRevalidate;
666
- return 0;
667
- }
668
- async function renderRegionFresh(page, region, req) {
669
- if (region.serverExport) {
670
- const out = await withRenderTimeout(withCacheScope(page.route, () => withRequest(req, () => renderServerExport(page, region, req))));
671
- 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));
672
265
  }
673
- const render = loadRuntimeRenderer(region.bundlePath);
674
- const out = await withRenderTimeout(withCacheScope(page.route, () => render(JSON.stringify(regionProps(region, req)))));
675
- return { html: out.result, scope: out.scope, invalidated: out.invalidated };
676
- }
677
- function regionCacheable(r) {
678
- return !r.scope.noStore && !r.invalidated;
679
- }
680
- // renderServerExport renders an async server component region with the page's
681
- // own server bundle, which exports the component under region.serverExport.
682
- async function renderServerExport(page, region, req) {
683
- const mod = await loadPageModule(page);
684
- const Comp = mod[region.serverExport];
685
- if (typeof Comp !== "function") {
686
- 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);
687
268
  }
688
- const props = regionProps(region, req);
689
- if (props.params && typeof props.params === "object")
690
- props.params = thenableRecord(props.params);
691
- return renderToStringAsync(jsx(Comp, props));
692
269
  }
693
- function revalidateRegionInBackground(page, region, req, key) {
694
- if (inFlightRegionRevalidations.has(key))
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)
695
274
  return;
696
- const p = (async () => {
697
- try {
698
- const r = await renderRegionFresh(page, region, req);
699
- if (regionCacheable(r))
700
- regionCacheSet(key, r.html, page, req, r.scope);
701
- console.log(`[krate-ssr] Revalidated region ${key} (SWR)`);
702
- }
703
- catch (err) {
704
- console.error(`[krate-ssr] Region SWR revalidation failed ${key}:`, err.message);
705
- }
706
- finally {
707
- inFlightRegionRevalidations.delete(key);
708
- }
709
- })();
710
- inFlightRegionRevalidations.set(key, p);
275
+ if (persistTimer)
276
+ clearTimeout(persistTimer);
277
+ persistTimer = setTimeout(persistIsrNow, 1000);
711
278
  }
712
- // renderRegion renders one region, applying region-level ISR caching for ISR
713
- // pages. Returns an NDJSON frame.
714
- async function renderRegion(page, region, req) {
715
- if (!region.bundlePath && !region.serverExport) {
716
- return { type: "error", id: region.id, status: 400, error: "region has no runtime bundle", fatal: !!page.serverComponents };
717
- }
718
- const key = regionCacheKey(page, region.id, req);
719
- const interval = regionInterval(page, region);
720
- const cacheable = interval > 0;
721
- if (cacheable) {
722
- regionRevalidation.set(key, interval);
723
- const cached = regionCache.get(key);
724
- const stale = cached && (Date.now() - cached.timestamp) / 1000 > interval;
725
- if (cached && !stale) {
726
- return { type: "region", id: region.id, status: 200, html: cached.html, cached: true, cacheStatus: "hit" };
727
- }
728
- if (cached) {
729
- revalidateRegionInBackground(page, region, req, key);
730
- return { type: "region", id: region.id, status: 200, html: cached.html, cached: true, cacheStatus: "stale" };
731
- }
732
- }
279
+ function loadIsrCache() {
733
280
  try {
734
- const r = await renderRegionFresh(page, region, req);
735
- const html = r.html;
736
- if (cacheable && regionCacheable(r)) {
737
- regionCacheSet(key, html, page, req, r.scope);
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`);
738
288
  }
739
- const frame = { type: "region", id: region.id, status: 200, html };
740
- if (cacheable)
741
- frame.cacheStatus = "miss";
742
- return frame;
743
289
  }
744
290
  catch (err) {
745
- const signal = renderSignal(err);
746
- if (signal) {
747
- const frame = { type: "region", id: region.id, status: signal.status, html: "" };
748
- if (signal.notFound)
749
- frame.notFound = true;
750
- if (signal.redirect)
751
- frame.redirect = signal.redirect;
752
- return frame;
753
- }
754
- console.error(`[krate-ssr] Region render failed ${page.route}::${region.id}:`, err);
755
- // A server component region has no meaningful baked content, so its
756
- // failure is fatal for the response (the Go server answers 500).
757
- 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);
758
292
  }
759
293
  }
760
- function writeJsonLine(res, obj) {
761
- res.write(JSON.stringify(obj) + "\n");
762
- }
763
- // renderPageRegion renders a coarse whole-page region (SSR/ISR pages whose
764
- // entire body is request-time dynamic). It reuses renderPage so the page-level
765
- // variant-aware ISR cache, stale-while-revalidate, and revalidation all apply.
766
- // Returns an NDJSON region frame; the Go server splices html into the shell at
767
- // the "page" marker and keeps the baked body when the render fails.
768
- async function renderPageRegion(page, id, req) {
769
- const result = await renderPage(req);
770
- const frame = {
771
- type: "region",
772
- id,
773
- kind: "page",
774
- status: result.status || 200,
775
- html: result.html || "",
776
- };
777
- if (result.cacheStatus)
778
- frame.cacheStatus = result.cacheStatus;
779
- if (result.notFound)
780
- frame.notFound = true;
781
- if (result.redirect)
782
- frame.redirect = result.redirect;
783
- if (result.error)
784
- frame.error = result.error;
785
- if (page.serverComponents && frame.status >= 500)
786
- frame.fatal = true;
787
- // Title swap: the Go server replaces the baked <title> with the freshly
788
- // rendered one so params-driven pages update the browser tab.
789
- const title = extractTitle(result.html);
790
- if (title !== "")
791
- frame.title = title;
792
- return frame;
793
- }
794
- function extractTitle(html) {
795
- const match = html.match(/<title[^>]*>([\s\S]*?)<\/title>/i);
796
- return match ? match[1].trim() : "";
797
- }
294
+ loadIsrCache();
798
295
  const INTERNAL_OPS = {
799
296
  "/__krate/ssr/revalidate": "revalidate-route",
800
297
  "/__krate/ssr/refresh": "refresh-route",
801
298
  "/__krate/ssr/invalidate": "dev-invalidate",
802
299
  "/__krate/ssr/cache-invalidate": "cache-invalidate",
803
300
  };
804
- function stringList(v) {
805
- return Array.isArray(v) ? v.filter((x) => typeof x === "string" && x !== "") : [];
806
- }
807
301
  // applyInternalOp applies one internal operation to this process's caches.
808
302
  async function applyInternalOp(op, payload) {
809
- switch (op) {
810
- case "revalidate-route": {
811
- const targetRoute = String(payload.route || "");
812
- isrCache.deleteRoute(targetRoute);
813
- clearRegionCacheForRoute(targetRoute);
814
- cacheRuntime().invalidate({});
815
- persistIsrNow();
816
- const page = findPage(targetRoute);
817
- if (page) {
818
- await renderFresh(page, { route: targetRoute, url: targetRoute, method: "GET", headers: {} });
819
- }
820
- return { ok: true };
821
- }
822
- case "refresh-route": {
823
- const targetRoute = String(payload.route || "");
824
- const page = findPage(targetRoute);
825
- const refreshed = page && page.mode === "isr" ? await refreshRouteVariants(page) : 0;
826
- clearRegionCacheForRoute(targetRoute);
827
- return { ok: true, refreshed };
828
- }
829
- case "dev-invalidate": {
830
- const { route: targetRoute, source, bundlePath } = payload;
831
- // Invalidate ISR cache for this route (all variants)
832
- isrCache.deleteRoute(targetRoute);
833
- // Invalidate module cache for the source file or bundle
834
- const key = bundlePath || source;
835
- if (key && moduleCache.has(key)) {
836
- moduleCache.delete(key);
837
- console.log(`[krate-ssr] Invalidated cache for ${targetRoute} (${key})`);
838
- }
839
- // Runtime component bundles are recompiled in place on a dev rebuild, but
840
- // their render functions are cached for the process lifetime. Clear them
841
- // so the next region render picks up the new code. Bundles are tiny and
842
- // re-read on demand, so clearing all of them is cheap and avoids tracking
843
- // which component maps to which route here.
844
- runtimeBundleCache.clear();
845
- clearRegionCache();
846
- return { ok: true };
847
- }
848
- case "cache-invalidate": {
849
- const tags = stringList(payload.tags);
850
- const targets = Array.isArray(payload.targets)
851
- ? payload.targets.filter((t) => t && typeof t.route === "string")
852
- : [];
853
- // Path targets also drop the data their renders cached (implicit tag).
854
- const dataTags = tags.concat(targets.map((t) => routeDataTag(t.route)));
855
- const { dataEntries } = cacheRuntime().invalidate({ tags: dataTags });
856
- let isrEntries = 0;
857
- let regionEntries = 0;
858
- for (const t of targets) {
859
- const params = t.params && typeof t.params === "object" ? t.params : null;
860
- isrEntries += params ? isrCache.deleteVariant(t.route, params) : isrCache.deleteRoute(t.route);
861
- regionEntries += invalidateRegions(t.route, params, []);
862
- }
863
- if (tags.length) {
864
- isrEntries += isrCache.deleteTags(tags);
865
- regionEntries += invalidateRegions(null, null, tags);
866
- }
867
- if (isrEntries > 0)
868
- persistIsrNow();
869
- return { ok: true, isrEntries, regionEntries, dataEntries };
870
- }
871
- }
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");
872
322
  }
873
323
  // Cluster fan-out (worker side). broadcastInternalOp resolves with one result
874
324
  // per live worker once every worker applied the operation.
@@ -922,30 +372,6 @@ function mergeOpResults(op, results) {
922
372
  }
923
373
  return out;
924
374
  }
925
- // HTTP Server
926
- const PORT = parseInt(process.env.KRATE_SSR_PORT || "3100", 10);
927
- const manifestPath = process.env.KRATE_MANIFEST || "";
928
- const root = process.env.KRATE_ROOT || process.cwd();
929
- projectRoot = root;
930
- // Load manifest
931
- if (manifestPath && fs.existsSync(manifestPath)) {
932
- const data = fs.readFileSync(manifestPath, "utf-8");
933
- manifest = JSON.parse(data);
934
- console.log(`[krate-ssr] Loaded manifest: ${manifest.pages.length} SSR/ISR/streaming pages`);
935
- }
936
- else {
937
- // Try default location
938
- const defaultPath = path.join(root, "dist", "server-manifest.json");
939
- if (fs.existsSync(defaultPath)) {
940
- const data = fs.readFileSync(defaultPath, "utf-8");
941
- manifest = JSON.parse(data);
942
- console.log(`[krate-ssr] Loaded manifest: ${manifest.pages.length} SSR/ISR/streaming pages`);
943
- }
944
- else {
945
- console.error("[krate-ssr] No manifest found. SSR pages will not be served.");
946
- }
947
- }
948
- loadIsrCache();
949
375
  function parseBody(req) {
950
376
  return new Promise((resolve) => {
951
377
  let body = "";
@@ -999,6 +425,11 @@ const server = http.createServer(async (req, res) => {
999
425
  // sidecar renders each one (a component region from the manifest, or a
1000
426
  // coarse "page" region that renders the whole page component for SSR/ISR).
1001
427
  if (route === "/__krate/regions" && req.method === "POST") {
428
+ if (!internalAuthorized(req)) {
429
+ res.writeHead(403, { "Content-Type": "application/json" });
430
+ res.end(JSON.stringify({ error: "forbidden" }));
431
+ return;
432
+ }
1002
433
  res.writeHead(200, {
1003
434
  "Content-Type": "application/x-ndjson; charset=utf-8",
1004
435
  "Cache-Control": "no-store",
@@ -1041,9 +472,9 @@ const server = http.createServer(async (req, res) => {
1041
472
  // Unknown region id - keep the baked content by sending no frame.
1042
473
  return Promise.resolve({ type: "skip", id: r.id });
1043
474
  });
1044
- for (const p of pending) {
1045
- writeJsonLine(res, await p);
1046
- }
475
+ // Write each frame as soon as it resolves. Async server components finish
476
+ // out of document order, and the Go host inserts each chunk at its marker.
477
+ await Promise.all(pending.map(async (p) => writeJsonLine(res, await p)));
1047
478
  writeJsonLine(res, { type: "end", count: regions.length });
1048
479
  }
1049
480
  catch (err) {
@@ -1054,6 +485,11 @@ const server = http.createServer(async (req, res) => {
1054
485
  return;
1055
486
  }
1056
487
  // Direct page requests (non-proxied)
488
+ if (!internalAuthorized(req)) {
489
+ res.writeHead(403, { "Content-Type": "application/json" });
490
+ res.end(JSON.stringify({ error: "forbidden" }));
491
+ return;
492
+ }
1057
493
  // Collect request headers
1058
494
  const headers = {};
1059
495
  for (const [key, value] of Object.entries(req.headers)) {
@@ -1069,7 +505,7 @@ const server = http.createServer(async (req, res) => {
1069
505
  const result = await renderPage(renderReq);
1070
506
  if (result.notFound) {
1071
507
  // Try to serve 404.html from dist
1072
- const notFoundPath = path.join(root, "dist", "404.html");
508
+ const notFoundPath = path.join(OUT_DIR, "404.html");
1073
509
  if (fs.existsSync(notFoundPath)) {
1074
510
  const html = fs.readFileSync(notFoundPath, "utf-8");
1075
511
  res.writeHead(404, { "Content-Type": "text/html; charset=utf-8" });
@@ -1081,6 +517,13 @@ const server = http.createServer(async (req, res) => {
1081
517
  }
1082
518
  return;
1083
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
+ }
1084
527
  if (result.redirect) {
1085
528
  res.writeHead(result.status === 307 ? 307 : 302, { Location: result.redirect });
1086
529
  res.end();
@@ -1088,7 +531,7 @@ const server = http.createServer(async (req, res) => {
1088
531
  }
1089
532
  if (result.status === 500) {
1090
533
  // Try to serve 500.html from dist
1091
- const errorPath = path.join(root, "dist", "500.html");
534
+ const errorPath = path.join(OUT_DIR, "500.html");
1092
535
  if (fs.existsSync(errorPath)) {
1093
536
  const html = fs.readFileSync(errorPath, "utf-8");
1094
537
  res.writeHead(500, { "Content-Type": "text/html; charset=utf-8" });
@@ -1108,7 +551,9 @@ const server = http.createServer(async (req, res) => {
1108
551
  headers_extra["X-Krate-Cache"] = result.cacheStatus === "stale" ? "STALE" : "HIT";
1109
552
  }
1110
553
  res.writeHead(result.status, headers_extra);
1111
- res.end(result.html);
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, ""));
1112
557
  });
1113
558
  if (isClusterPrimary) {
1114
559
  // The primary only supervises; workers own the listening socket.
@@ -1133,14 +578,14 @@ else {
1133
578
  catch {
1134
579
  // not listening yet
1135
580
  }
1136
- server.listen(PORT);
581
+ server.listen(PORT, "127.0.0.1");
1137
582
  }, 100);
1138
583
  return;
1139
584
  }
1140
585
  }
1141
586
  throw err;
1142
587
  });
1143
- server.listen(PORT, () => {
588
+ server.listen(PORT, "127.0.0.1", () => {
1144
589
  console.log(`[krate-ssr] Renderer server listening on port ${PORT}`);
1145
590
  });
1146
591
  }