@krate/runtime 0.1.0

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.
@@ -0,0 +1,468 @@
1
+ // @krate/runtime/server-renderer — Node.js HTTP server for SSR/ISR/Streaming
2
+ // Receives render requests from the Go server and returns HTML.
3
+ import http from "node:http";
4
+ import fs from "node:fs";
5
+ import path from "node:path";
6
+ import { pathToFileURL } from "node:url";
7
+ import { renderToString, setStreamingResolved, resetBoundaryCounter } from "./server.js";
8
+ // Force TCP_NODELAY on socket to prevent Nagle buffering chunks together.
9
+ // Must be called BEFORE the first write for it to take effect.
10
+ function setupStream(res) {
11
+ const socket = res.socket;
12
+ if (socket && typeof socket.setNoDelay === 'function') {
13
+ socket.setNoDelay(true);
14
+ }
15
+ }
16
+ // ── ISR Cache ────────────────────────────────────────────────────────────────
17
+ class ISRCache {
18
+ constructor(maxSize = 128) {
19
+ this.cache = new Map();
20
+ this.revalidationIntervals = new Map(); // route → seconds
21
+ this.maxSize = maxSize;
22
+ }
23
+ setRevalidation(route, seconds) {
24
+ this.revalidationIntervals.set(route, seconds);
25
+ }
26
+ get(route) {
27
+ return this.cache.get(route);
28
+ }
29
+ set(route, entry) {
30
+ if (this.cache.size >= this.maxSize) {
31
+ const oldest = this.cache.keys().next().value;
32
+ if (oldest)
33
+ this.cache.delete(oldest);
34
+ }
35
+ this.cache.set(route, entry);
36
+ }
37
+ isStale(route) {
38
+ const entry = this.cache.get(route);
39
+ const interval = this.revalidationIntervals.get(route);
40
+ if (!entry || !interval)
41
+ return false;
42
+ return (Date.now() - entry.timestamp) / 1000 > interval;
43
+ }
44
+ delete(route) {
45
+ this.cache.delete(route);
46
+ }
47
+ }
48
+ // ── Page Module Loader ───────────────────────────────────────────────────────
49
+ const moduleCache = new Map();
50
+ async function loadPageModule(page) {
51
+ // Prefer pre-compiled server bundle over raw source
52
+ const key = page.bundlePath || page.source;
53
+ if (moduleCache.has(key)) {
54
+ return moduleCache.get(key);
55
+ }
56
+ let fileUrl;
57
+ if (page.bundlePath) {
58
+ // Pre-compiled bundle: bundlePath is relative to outDir (dist/)
59
+ const bundleAbs = path.resolve(root, "dist", page.bundlePath);
60
+ fileUrl = pathToFileURL(bundleAbs).href;
61
+ }
62
+ else {
63
+ // Fallback: raw source (legacy mode)
64
+ fileUrl = pathToFileURL(path.resolve(page.source)).href;
65
+ }
66
+ try {
67
+ const mod = await import(fileUrl + "?t=" + Date.now());
68
+ moduleCache.set(key, mod);
69
+ return mod;
70
+ }
71
+ catch (err) {
72
+ console.error(`[krate-ssr] Failed to load module for ${page.route}:`, err.message);
73
+ throw err;
74
+ }
75
+ }
76
+ // ── Renderer ─────────────────────────────────────────────────────────────────
77
+ const isrCache = new ISRCache();
78
+ let manifest = null;
79
+ let projectRoot = "";
80
+ function findPage(route) {
81
+ if (!manifest)
82
+ return undefined;
83
+ // Try exact match first, then strip trailing slash
84
+ let page = manifest.pages.find((p) => p.route === route);
85
+ if (!page && route !== "/") {
86
+ page = manifest.pages.find((p) => p.route === route + "/");
87
+ }
88
+ if (!page && route.endsWith("/")) {
89
+ page = manifest.pages.find((p) => p.route === route.slice(0, -1));
90
+ }
91
+ return page;
92
+ }
93
+ async function renderPage(req) {
94
+ const page = findPage(req.route);
95
+ if (!page) {
96
+ return { html: "", status: 404, notFound: true };
97
+ }
98
+ // ISR: serve from cache if available and not stale
99
+ if (page.mode === "isr") {
100
+ isrCache.setRevalidation(page.route, page.revalidate || 60);
101
+ const cached = isrCache.get(page.route);
102
+ if (cached && !isrCache.isStale(page.route)) {
103
+ return {
104
+ html: cached.html,
105
+ status: 200,
106
+ headHTML: cached.headHTML,
107
+ scriptHTML: cached.scriptHTML,
108
+ cached: true,
109
+ };
110
+ }
111
+ }
112
+ try {
113
+ const mod = await loadPageModule(page);
114
+ let props = {};
115
+ let redirect;
116
+ let notFound = false;
117
+ // Run data-fetching hooks. getServerSideProps runs here (per-request);
118
+ // getStaticProps normally runs at build time but is honored here so SSR /
119
+ // streaming pages with async props render real data instead of {}.
120
+ const dataFn = mod.getServerSideProps || mod.getStaticProps;
121
+ if (typeof dataFn === "function") {
122
+ try {
123
+ const data = await dataFn({
124
+ params: req.params,
125
+ query: req.query,
126
+ headers: req.headers,
127
+ method: req.method,
128
+ url: req.url,
129
+ });
130
+ if (data && typeof data === "object") {
131
+ if (data.notFound) {
132
+ notFound = true;
133
+ }
134
+ else if (data.redirect) {
135
+ redirect =
136
+ typeof data.redirect === "string"
137
+ ? data.redirect
138
+ : data.redirect.destination || data.redirect;
139
+ }
140
+ else if (data.props && typeof data.props === "object") {
141
+ props = data.props;
142
+ }
143
+ }
144
+ }
145
+ catch (err) {
146
+ console.error(`[krate] ${dataFn.name || "getServerSideProps"} failed for ${req.route}:`, err);
147
+ return { html: "", status: 500 };
148
+ }
149
+ }
150
+ if (notFound) {
151
+ return { html: "", status: 404, notFound: true };
152
+ }
153
+ if (redirect) {
154
+ return { html: "", status: 302, redirect };
155
+ }
156
+ // Get the default export (the component)
157
+ const Component = mod.default;
158
+ if (!Component) {
159
+ return { html: "", status: 500 };
160
+ }
161
+ // Render the component to HTML
162
+ const jsxNode = Component(props);
163
+ const html = renderToString(jsxNode);
164
+ // Extract head/script content from the render
165
+ const headHTML = extractHeadHTML(html);
166
+ const scriptHTML = extractScriptHTML(html);
167
+ const response = {
168
+ html,
169
+ status: 200,
170
+ headHTML,
171
+ scriptHTML,
172
+ };
173
+ // ISR: cache the result
174
+ if (page.mode === "isr") {
175
+ isrCache.set(page.route, {
176
+ html,
177
+ timestamp: Date.now(),
178
+ headHTML,
179
+ scriptHTML,
180
+ });
181
+ }
182
+ return response;
183
+ }
184
+ catch (err) {
185
+ console.error(`[krate] Error rendering ${req.route}:`, err);
186
+ return { html: "", status: 500 };
187
+ }
188
+ }
189
+ function extractHeadHTML(html) {
190
+ const match = html.match(/<!--head-start-->(.*?)<!--head-end-->/s);
191
+ return match ? match[1] : "";
192
+ }
193
+ function extractScriptHTML(html) {
194
+ const match = html.match(/<!--script-start-->(.*?)<!--script-end-->/s);
195
+ return match ? match[1] : "";
196
+ }
197
+ // ── HTTP Server ──────────────────────────────────────────────────────────────
198
+ const PORT = parseInt(process.env.KRATE_SSR_PORT || "3100", 10);
199
+ const manifestPath = process.env.KRATE_MANIFEST || "";
200
+ const root = process.env.KRATE_ROOT || process.cwd();
201
+ projectRoot = root;
202
+ // Load manifest
203
+ if (manifestPath && fs.existsSync(manifestPath)) {
204
+ const data = fs.readFileSync(manifestPath, "utf-8");
205
+ manifest = JSON.parse(data);
206
+ console.log(`[krate-ssr] Loaded manifest: ${manifest.pages.length} SSR/ISR/streaming pages`);
207
+ }
208
+ else {
209
+ // Try default location
210
+ const defaultPath = path.join(root, "dist", "server-manifest.json");
211
+ if (fs.existsSync(defaultPath)) {
212
+ const data = fs.readFileSync(defaultPath, "utf-8");
213
+ manifest = JSON.parse(data);
214
+ console.log(`[krate-ssr] Loaded manifest: ${manifest.pages.length} SSR/ISR/streaming pages`);
215
+ }
216
+ else {
217
+ console.error("[krate-ssr] No manifest found. SSR pages will not be served.");
218
+ }
219
+ }
220
+ const server = http.createServer(async (req, res) => {
221
+ const url = new URL(req.url || "/", `http://${req.headers.host || "localhost"}`);
222
+ const route = url.pathname;
223
+ // Health check
224
+ if (route === "/__krate/ssr/health") {
225
+ res.writeHead(200, { "Content-Type": "application/json" });
226
+ res.end(JSON.stringify({ ok: true, pages: manifest?.pages?.length || 0 }));
227
+ return;
228
+ }
229
+ // ISR revalidation endpoint (called by Go server in background)
230
+ if (route === "/__krate/ssr/revalidate" && req.method === "POST") {
231
+ let body = "";
232
+ for await (const chunk of req)
233
+ body += chunk;
234
+ try {
235
+ const { route: targetRoute } = JSON.parse(body);
236
+ isrCache.delete(targetRoute);
237
+ // Trigger re-render
238
+ const page = findPage(targetRoute);
239
+ if (page) {
240
+ await renderPage({
241
+ route: targetRoute,
242
+ url: targetRoute,
243
+ method: "GET",
244
+ headers: {},
245
+ });
246
+ }
247
+ res.writeHead(200, { "Content-Type": "application/json" });
248
+ res.end(JSON.stringify({ ok: true }));
249
+ }
250
+ catch (err) {
251
+ res.writeHead(500, { "Content-Type": "application/json" });
252
+ res.end(JSON.stringify({ error: err.message }));
253
+ }
254
+ return;
255
+ }
256
+ // Module cache invalidation (called on file change in dev mode)
257
+ if (route === "/__krate/ssr/invalidate" && req.method === "POST") {
258
+ let body = "";
259
+ for await (const chunk of req)
260
+ body += chunk;
261
+ try {
262
+ const { route: targetRoute, source, bundlePath } = JSON.parse(body);
263
+ // Invalidate ISR cache for this route
264
+ isrCache.delete(targetRoute);
265
+ // Invalidate module cache for the source file or bundle
266
+ const key = bundlePath || source;
267
+ if (key && moduleCache.has(key)) {
268
+ moduleCache.delete(key);
269
+ console.log(`[krate-ssr] Invalidated cache for ${targetRoute} (${key})`);
270
+ }
271
+ res.writeHead(200, { "Content-Type": "application/json" });
272
+ res.end(JSON.stringify({ ok: true }));
273
+ }
274
+ catch (err) {
275
+ res.writeHead(500, { "Content-Type": "application/json" });
276
+ res.end(JSON.stringify({ error: err.message }));
277
+ }
278
+ return;
279
+ }
280
+ // ── /__krate/render — called by Go server for SSR/ISR/Streaming ──────────
281
+ if (route === "/__krate/render" && req.method === "POST") {
282
+ let body = "";
283
+ for await (const chunk of req)
284
+ body += chunk;
285
+ try {
286
+ const parsed = JSON.parse(body);
287
+ const renderReq = {
288
+ route: parsed.route,
289
+ url: parsed.url || "/",
290
+ method: parsed.method || "GET",
291
+ headers: parsed.headers || {},
292
+ params: parsed.params,
293
+ query: parsed.query,
294
+ };
295
+ const page = findPage(renderReq.route);
296
+ // Streaming mode: two-phase render for real Suspense fallback
297
+ if (page?.mode === "streaming") {
298
+ res.writeHead(200, {
299
+ "Content-Type": "text/html; charset=utf-8",
300
+ "Transfer-Encoding": "chunked",
301
+ "X-Content-Type-Options": "nosniff",
302
+ });
303
+ setupStream(res);
304
+ const mod = await loadPageModule(page);
305
+ const Component = mod.default;
306
+ if (!Component) {
307
+ res.end();
308
+ return;
309
+ }
310
+ // Phase 1: Render with empty props → Suspense shows fallback
311
+ resetBoundaryCounter();
312
+ setStreamingResolved(false);
313
+ const fallbackJsx = Component({});
314
+ const fallbackHtml = renderToString(fallbackJsx);
315
+ res.write(fallbackHtml);
316
+ // Phase 2: Re-render with resolved props (no data-fetching needed)
317
+ resetBoundaryCounter();
318
+ setStreamingResolved(true);
319
+ const resolvedJsx = Component({});
320
+ const resolvedHtml = renderToString(resolvedJsx);
321
+ setStreamingResolved(false);
322
+ // Extract resolved content per Suspense boundary from markers
323
+ const resolvedMap = {};
324
+ const markerRe = /<!--suspense-resolved:(\d+)-->([\s\S]*?)<!--\/suspense-resolved:\1-->/g;
325
+ let m;
326
+ while ((m = markerRe.exec(resolvedHtml)) !== null) {
327
+ resolvedMap[m[1]] = m[2];
328
+ }
329
+ // Send targeted replacement script — only replaces fallback spans, preserves surrounding HTML
330
+ const script = `<script>(function(){var m=${JSON.stringify(resolvedMap)};Object.keys(m).forEach(function(id){var s=document.querySelector('span[data-suspense="'+id+'"]');if(s)s.outerHTML=m[id]});var t=document.querySelectorAll('template[data-suspense]');t.forEach(function(el){el.remove()})})()</script>`;
331
+ res.write(script);
332
+ res.end();
333
+ return;
334
+ }
335
+ // SSR/ISR: standard single-phase render
336
+ const result = await renderPage(renderReq);
337
+ // Return JSON response
338
+ res.writeHead(result.status, {
339
+ "Content-Type": "application/json; charset=utf-8",
340
+ });
341
+ res.end(JSON.stringify(result));
342
+ }
343
+ catch (err) {
344
+ console.error("[krate-ssr] Error in /__krate/render:", err.message);
345
+ if (res.headersSent) {
346
+ // Headers already sent (e.g. streaming mode) — write error inline
347
+ res.write(`<script>console.error("[krate-ssr]",${JSON.stringify(err.message)})</script>`);
348
+ res.end();
349
+ }
350
+ else {
351
+ res.writeHead(500, { "Content-Type": "application/json" });
352
+ res.end(JSON.stringify({ html: "", status: 500 }));
353
+ }
354
+ }
355
+ return;
356
+ }
357
+ // ── Direct page requests (non-proxied) ──────────────────────────────────
358
+ // Collect request headers
359
+ const headers = {};
360
+ for (const [key, value] of Object.entries(req.headers)) {
361
+ if (typeof value === "string")
362
+ headers[key] = value;
363
+ }
364
+ const renderReq = {
365
+ route,
366
+ url: req.url || "/",
367
+ method: req.method || "GET",
368
+ headers,
369
+ };
370
+ const result = await renderPage(renderReq);
371
+ if (result.notFound) {
372
+ // Try to serve 404.html from dist
373
+ const notFoundPath = path.join(root, "dist", "404.html");
374
+ if (fs.existsSync(notFoundPath)) {
375
+ const html = fs.readFileSync(notFoundPath, "utf-8");
376
+ res.writeHead(404, { "Content-Type": "text/html; charset=utf-8" });
377
+ res.end(html);
378
+ }
379
+ else {
380
+ res.writeHead(404, { "Content-Type": "text/html; charset=utf-8" });
381
+ res.end("<html><body><h1>404 Not Found</h1></body></html>");
382
+ }
383
+ return;
384
+ }
385
+ if (result.redirect) {
386
+ res.writeHead(302, { Location: result.redirect });
387
+ res.end();
388
+ return;
389
+ }
390
+ if (result.status === 500) {
391
+ // Try to serve 500.html from dist
392
+ const errorPath = path.join(root, "dist", "500.html");
393
+ if (fs.existsSync(errorPath)) {
394
+ const html = fs.readFileSync(errorPath, "utf-8");
395
+ res.writeHead(500, { "Content-Type": "text/html; charset=utf-8" });
396
+ res.end(html);
397
+ }
398
+ else {
399
+ res.writeHead(500, { "Content-Type": "text/html; charset=utf-8" });
400
+ res.end("<html><body><h1>Internal Server Error</h1></body></html>");
401
+ }
402
+ return;
403
+ }
404
+ // Streaming SSR: two-phase render for direct requests
405
+ const streamingPage = manifest?.pages?.find((p) => p.route === route);
406
+ if (streamingPage?.mode === "streaming") {
407
+ try {
408
+ const mod = await loadPageModule(streamingPage);
409
+ const Component = mod.default;
410
+ if (!Component) {
411
+ res.writeHead(500, { "Content-Type": "text/html; charset=utf-8" });
412
+ res.end("<html><body><h1>500</h1></body></html>");
413
+ return;
414
+ }
415
+ res.writeHead(200, {
416
+ "Content-Type": "text/html; charset=utf-8",
417
+ "Transfer-Encoding": "chunked",
418
+ "X-Content-Type-Options": "nosniff",
419
+ });
420
+ setupStream(res);
421
+ // Phase 1: fallback
422
+ resetBoundaryCounter();
423
+ setStreamingResolved(false);
424
+ const fallbackHtml = renderToString(Component({}));
425
+ res.write(fallbackHtml);
426
+ // Phase 2: re-render with resolved props (no data-fetching needed)
427
+ resetBoundaryCounter();
428
+ setStreamingResolved(true);
429
+ const resolvedHtml = renderToString(Component({}));
430
+ setStreamingResolved(false);
431
+ // Extract resolved content per Suspense boundary from markers
432
+ const resolvedMap = {};
433
+ const markerRe = /<!--suspense-resolved:(\d+)-->([\s\S]*?)<!--\/suspense-resolved:\1-->/g;
434
+ let m;
435
+ while ((m = markerRe.exec(resolvedHtml)) !== null) {
436
+ resolvedMap[m[1]] = m[2];
437
+ }
438
+ const script = `<script>(function(){var m=${JSON.stringify(resolvedMap)};Object.keys(m).forEach(function(id){var s=document.querySelector('span[data-suspense="'+id+'"]');if(s)s.outerHTML=m[id]});var t=document.querySelectorAll('template[data-suspense]');t.forEach(function(el){el.remove()})})()</script>`;
439
+ res.write(script);
440
+ res.end();
441
+ return;
442
+ }
443
+ catch (err) {
444
+ console.error("[krate-ssr] Error in streaming direct render:", err.message);
445
+ if (res.headersSent) {
446
+ res.write(`<script>console.error("[krate-ssr]",${JSON.stringify(err.message)})</script>`);
447
+ res.end();
448
+ }
449
+ else {
450
+ res.writeHead(500, { "Content-Type": "text/html; charset=utf-8" });
451
+ res.end("<html><body><h1>Internal Server Error</h1></body></html>");
452
+ }
453
+ return;
454
+ }
455
+ }
456
+ // Regular SSR/ISR response
457
+ const headers_extra = {
458
+ "Content-Type": "text/html; charset=utf-8",
459
+ };
460
+ if (result.cached) {
461
+ headers_extra["X-Krate-Cache"] = "HIT";
462
+ }
463
+ res.writeHead(result.status, headers_extra);
464
+ res.end(result.html);
465
+ });
466
+ server.listen(PORT, () => {
467
+ console.log(`[krate-ssr] Renderer server listening on port ${PORT}`);
468
+ });
@@ -0,0 +1,87 @@
1
+ export declare function createSignal<T>(initial: T): [() => T, (v: T | ((prev: T) => T)) => void];
2
+ export declare function createEffect(_fn: () => void): () => void;
3
+ export declare function createMemo<T>(fn: () => T): () => T;
4
+ export declare function onCleanup(_fn: () => void): void;
5
+ export declare function onMount(fn: () => void): void;
6
+ interface RawHTML {
7
+ __raw: string;
8
+ }
9
+ type JSXNode = string | number | boolean | null | undefined | JSXNode[] | JSXElement | RawHTML;
10
+ interface JSXElement {
11
+ type: string | Function;
12
+ props: Record<string, any>;
13
+ children: JSXNode[];
14
+ }
15
+ export declare function Fragment(_props: {
16
+ children?: JSXNode;
17
+ }): JSXNode;
18
+ export declare function jsx(type: string | Function, props: Record<string, any>, _key?: string): JSXElement;
19
+ export declare const jsxs: typeof jsx;
20
+ export declare function renderToString(node: JSXNode): string;
21
+ export declare function setStreamingResolved(v: boolean): void;
22
+ export declare function resetBoundaryCounter(): void;
23
+ interface SuspenseProps {
24
+ fallback: JSXNode;
25
+ children: JSXNode;
26
+ }
27
+ export declare function Suspense(props: SuspenseProps): JSXNode;
28
+ export declare function Head(props: {
29
+ children?: JSXNode;
30
+ }): JSXNode;
31
+ export declare function Script(props: {
32
+ src?: string;
33
+ children?: string;
34
+ }): JSXNode;
35
+ export declare function Style(props: {
36
+ children?: string;
37
+ }): JSXNode;
38
+ export declare function Link(props: {
39
+ href?: string;
40
+ prefetch?: boolean;
41
+ replace?: boolean;
42
+ scroll?: boolean;
43
+ children?: JSXNode;
44
+ [key: string]: any;
45
+ }): JSXNode;
46
+ export declare function Image(props: {
47
+ src?: string;
48
+ alt?: string;
49
+ width?: number;
50
+ height?: number;
51
+ [key: string]: any;
52
+ }): JSXNode;
53
+ export declare function Icon(_props: {
54
+ name?: string;
55
+ [key: string]: any;
56
+ }): JSXNode;
57
+ export interface GetServerSidePropsContext {
58
+ params?: Record<string, string>;
59
+ query?: Record<string, string>;
60
+ req: {
61
+ url: string;
62
+ method: string;
63
+ headers: Record<string, string>;
64
+ };
65
+ res: {
66
+ statusCode: number;
67
+ setHeader(name: string, value: string): void;
68
+ };
69
+ }
70
+ export interface GetServerSidePropsResult<P> {
71
+ props: P;
72
+ redirect?: {
73
+ destination: string;
74
+ permanent?: boolean;
75
+ };
76
+ notFound?: true;
77
+ }
78
+ export interface GetStaticPropsResult<P> {
79
+ props: P;
80
+ revalidate?: number;
81
+ redirect?: {
82
+ destination: string;
83
+ permanent?: boolean;
84
+ };
85
+ notFound?: true;
86
+ }
87
+ export {};