rosetack 0.1.3 → 0.1.5

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/src/cli/index.ts CHANGED
@@ -3,11 +3,16 @@
3
3
  import * as fs from 'fs';
4
4
  import * as path from 'path';
5
5
  import * as zlib from 'zlib';
6
+ import { createHash } from 'crypto';
6
7
  import { createRequire } from 'module';
7
8
  import { pathToFileURL, fileURLToPath } from 'url';
8
9
  import { buildProject, scanRoseFiles, scanComponentFiles, scriptOf, extractExports, loadPlugins, RoseError, errorInfo, type RouteInfo } from '../compiler/index.js';
9
10
  import { getHtmlShell, getClientSource, getStyles, shellOpen, clientScriptTag, securityHeaders, mintNonce, setBundleMode } from './shell.js';
10
11
  import { AI_PROMPT } from './prompt.js';
12
+ import { Readable } from 'stream';
13
+ import { createEdgeHandler } from './edge.js';
14
+ import { runShutdownHooks } from './shutdown.js';
15
+ import { requestOrigin } from './origin.js';
11
16
  import type * as ts from 'typescript';
12
17
 
13
18
  type Encoding = 'br' | 'gzip' | 'deflate';
@@ -39,6 +44,9 @@ function sendHtml(req: any, res: any, status: number, html: string, extraHeaders
39
44
  res.statusCode = status;
40
45
  res.setHeader('Content-Type', 'text/html; charset=utf-8');
41
46
  res.setHeader('Vary', 'Accept-Encoding');
47
+ if (!Object.keys(extraHeaders || {}).some((k) => k.toLowerCase() === 'cache-control')) {
48
+ res.setHeader('Cache-Control', 'no-cache');
49
+ }
42
50
  if (extraHeaders) for (const [k, v] of Object.entries(extraHeaders)) res.setHeader(k, v);
43
51
  let hash = 0x811c9dc5;
44
52
  for (let i = 0; i < html.length; i++) {
@@ -130,6 +138,23 @@ let serverModule: any = null;
130
138
  let serverMtime = -1;
131
139
  let serverVersion = 0;
132
140
 
141
+ function loadDotEnv(dir: string): void {
142
+ try {
143
+ const raw = fs.readFileSync(path.join(dir, '.env'), 'utf-8');
144
+ for (const line of raw.split(/\r?\n/)) {
145
+ const t = line.trim();
146
+ if (!t || t.startsWith('#')) continue;
147
+ const eq = t.indexOf('=');
148
+ if (eq <= 0) continue;
149
+ const k = t.slice(0, eq).trim();
150
+ let v = t.slice(eq + 1).trim();
151
+ if ((v.startsWith('"') && v.endsWith('"')) || (v.startsWith("'") && v.endsWith("'"))) v = v.slice(1, -1);
152
+ if (!(k in process.env)) process.env[k] = v;
153
+ }
154
+ } catch { }
155
+ }
156
+ loadDotEnv(process.cwd());
157
+
133
158
  async function loadServer(): Promise<any> {
134
159
  const file = path.join(OUT_DIR, 'server.js');
135
160
  const mtimeMs = fs.statSync(file).mtimeMs;
@@ -312,7 +337,7 @@ async function prerender(routes: RouteInfo[]): Promise<string[]> {
312
337
  };
313
338
 
314
339
  for (const info of routes) {
315
- if ((ssrModule.dynamicRoutes as string[]).includes(info.routePath)) {
340
+ if (((ssrModule.prerenderSkipRoutes as string[]) ?? []).includes(info.routePath)) {
316
341
  console.log(`dynamic route ${info.routePath}: per-request state (getContext/$store), rendered on demand`);
317
342
  continue;
318
343
  }
@@ -482,6 +507,18 @@ function crossSiteWrite(req: any): { status: number; body: string } | null {
482
507
  * in front when several workers share one stdout. Logged on the response's
483
508
  * finish, so a streamed route is recorded when it is actually done.
484
509
  */
510
+ /**
511
+ * The access line itself, shared by withAccessLog and the dynamic-render
512
+ * branch of `serve` (which returns before baseHandler, so it never goes
513
+ * through the wrapper). One formatter means both paths emit byte-identical
514
+ * shapes - the greppable contract test-cli asserts on.
515
+ */
516
+ function writeAccessLine(req: any, res: any, bytes: number, tag?: string, startedNs?: bigint): void {
517
+ const ms = Number(process.hrtime.bigint() - (startedNs ?? process.hrtime.bigint())) / 1e6;
518
+ const dur = ms >= 1 ? `${ms.toFixed(3)}ms` : `${(ms * 1000).toFixed(0)}us`;
519
+ console.log(`${new Date().toISOString().slice(0, 19)}Z${tag ? ` [${tag}]` : ''} ${req.method} ${req.url} ${res.statusCode} ${bytes}B ${dur}`);
520
+ }
521
+
485
522
  function withAccessLog(handler: (req: any, res: any) => void, tag?: string): (req: any, res: any) => void {
486
523
  return (req, res) => {
487
524
  const started = process.hrtime.bigint();
@@ -490,11 +527,7 @@ function withAccessLog(handler: (req: any, res: any) => void, tag?: string): (re
490
527
  const end = res.end.bind(res);
491
528
  res.write = (chunk: any, ...rest: any[]) => { if (chunk) bytes += Buffer.byteLength(chunk); return write(chunk, ...rest); };
492
529
  res.end = (chunk: any, ...rest: any[]) => { if (chunk) bytes += Buffer.byteLength(chunk); return end(chunk, ...rest); };
493
- res.on('finish', () => {
494
- const ms = Number(process.hrtime.bigint() - started) / 1e6;
495
- const dur = ms >= 1 ? `${ms.toFixed(3)}ms` : `${(ms * 1000).toFixed(0)}us`;
496
- console.log(`${new Date().toISOString().slice(0, 19)}Z${tag ? ` [${tag}]` : ''} ${req.method} ${req.url} ${res.statusCode} ${bytes}B ${dur}`);
497
- });
530
+ res.on('finish', () => writeAccessLine(req, res, bytes, tag, started));
498
531
  handler(req, res);
499
532
  };
500
533
  }
@@ -612,6 +645,8 @@ function settleDevBuild(): Promise<void> | null {
612
645
  }
613
646
 
614
647
  // Wrap a dev response so every HTML document carries the bridge (and the resumed state, once).
648
+ let invalidateHook: (() => void) | null = null;
649
+
615
650
  function devWrap(inner: (req: any, res: any) => void): (req: any, res: any) => void {
616
651
  devMode = true;
617
652
  return (req, res) => {
@@ -652,6 +687,27 @@ function serveStatic(dir: string, isr = false, dev = false): (req: any, res: any
652
687
  res.end(blocked.body);
653
688
  return;
654
689
  }
690
+ if (req.method === 'POST' && (req.url || '').startsWith('/__rosetack/revalidate')) {
691
+ const token = process.env.rosetack_REVALIDATE_TOKEN || '';
692
+ if (!token) { res.statusCode = 404; res.end(); return; }
693
+ if (req.headers['x-rosetack-token'] !== token) {
694
+ res.statusCode = 403; res.setHeader('content-type', 'application/json');
695
+ res.end(JSON.stringify({ error: 'invalid token' })); return;
696
+ }
697
+ let body = '';
698
+ req.on('data', (c) => { body += c; if (body.length > 1e6) req.destroy(); });
699
+ req.on('end', () => {
700
+ try {
701
+ const payload = JSON.parse(body || '{}');
702
+ if (invalidateHook) invalidateHook();
703
+ res.setHeader('content-type', 'application/json');
704
+ res.end(JSON.stringify({ revalidated: true, scope: payload.all ? 'all' : 'paths' }));
705
+ } catch (e: any) {
706
+ res.statusCode = 400; res.end(JSON.stringify({ error: String(e).slice(0, 120) }));
707
+ }
708
+ });
709
+ return;
710
+ }
655
711
  const want = pathnameOf(req.url || '/');
656
712
  const canonical = want.replace(/\/+$/, '') || '/';
657
713
  if (canonical !== want) {
@@ -700,6 +756,7 @@ function serveStatic(dir: string, isr = false, dev = false): (req: any, res: any
700
756
  body: body.length > 0 ? body : undefined,
701
757
  });
702
758
  ssrModule.setQuery?.(queryOf(req.url));
759
+ if ((req.method || 'GET') !== 'GET') ssrModule.invalidateRenderCache?.();
703
760
  let apiRes = await ssrModule.handleApi(req.method || 'GET', apiPath, request);
704
761
  if (hookCtx) apiRes = await ssrModule.runResponseHooks(hookCtx, apiRes);
705
762
  writeWebHeaders(apiRes, res);
@@ -729,6 +786,7 @@ function serveStatic(dir: string, isr = false, dev = false): (req: any, res: any
729
786
  }
730
787
  }
731
788
  ssrModule.setQuery?.(queryOf(req.url));
789
+ ssrModule.invalidateRenderCache?.();
732
790
  const page = await ssrModule.renderPage(pathnameOf(req.url || '/'), form);
733
791
  await sendPage(req, res, ssrModule, hookCtx, page, pathnameOf(req.url || '/'));
734
792
  } catch (err) {
@@ -797,7 +855,7 @@ function serveStatic(dir: string, isr = false, dev = false): (req: any, res: any
797
855
  };
798
856
  const fileHeaders: Record<string, string> = {
799
857
  'Content-Type': types[ext] || 'application/octet-stream',
800
- 'Cache-Control': rev ? `public, max-age=0, stale-while-revalidate=${rev.seconds}` : 'public, max-age=3600',
858
+ 'Cache-Control': devMode ? 'no-cache' : rev ? `public, max-age=0, stale-while-revalidate=${rev.seconds}` : 'public, max-age=3600',
801
859
  'ETag': entry.etag,
802
860
  'Vary': 'Accept-Encoding',
803
861
  };
@@ -871,7 +929,10 @@ function serveStatic(dir: string, isr = false, dev = false): (req: any, res: any
871
929
  done();
872
930
  return;
873
931
  }
874
- const page = await ssrModule.renderPage(safe2);
932
+ const hasQuery = (req.url || '').includes('?');
933
+ const page = req.method === 'GET' && !hasQuery && ssrModule.renderPageCached
934
+ ? await ssrModule.renderPageCached(safe2, String(req.headers.cookie || ''))
935
+ : await ssrModule.renderPage(safe2);
875
936
  await sendPage(req, res, ssrModule, hookCtx, page, safe2);
876
937
  }).catch((err: unknown) => {
877
938
  console.error(`rosetack: ${req.method} ${req.url} failed:`, err instanceof Error ? err.stack ?? err.message : err);
@@ -881,14 +942,31 @@ function serveStatic(dir: string, isr = false, dev = false): (req: any, res: any
881
942
  }
882
943
  res.statusCode = 500;
883
944
  res.setHeader('Content-Type', 'text/html; charset=utf-8');
884
- res.end('<h1>500</h1><p>Something went wrong rendering this page.</p>');
945
+ const devErr = err as { file?: string; line?: number | string; hint?: string };
946
+ let devDetail = '';
947
+ if (process.env.rosetack_DEV === '1' && err) {
948
+ const stack = err instanceof Error ? (err.stack || '').split('\n').slice(1, 7).join('\n') : '';
949
+ devDetail =
950
+ '<div style="margin:24px auto;max-width:860px;font:13px/1.6 ui-monospace,monospace;background:#1b1b1f;color:#e6e6ea;border:1px solid #3a3a42;border-radius:10px;padding:20px 24px;text-align:left;white-space:pre-wrap;word-break:break-word">' +
951
+ '<div style="font:600 15px/1.4 system-ui,sans-serif;color:#ff8b8b">Render failed: ' + escapeHtml(req.url || '') + '</div>' +
952
+ '<div style="margin:10px 0 0;color:#ffd479">' + escapeHtml(err instanceof Error ? err.message : err) + '</div>' +
953
+ (devErr.file ? '<div style="margin:6px 0 0;color:#9ad1ff">' + escapeHtml(devErr.file) + (devErr.line != null ? ':' + devErr.line : '') + '</div>' : '') +
954
+ (devErr.hint ? '<div style="margin:10px 0 0;color:#9fe8b0">Fix: ' + escapeHtml(devErr.hint) + '</div>' : '') +
955
+ (stack ? '<pre style="margin:12px 0 0;color:#8f8f9a">' + escapeHtml(stack) + '</pre>' : '') +
956
+ '</div>';
957
+ }
958
+ res.end('<h1>500</h1><p>Something went wrong rendering this page.</p>' + devDetail);
885
959
  });
886
960
  };
887
961
  }
888
962
 
963
+ /** HTML-escape for the dev error overlay (F10). */
964
+ function escapeHtml(v: unknown): string {
965
+ return String(v ?? '').replace(/[<>&"]/g, (ch) => ({ '<': '&lt;', '>': '&gt;', '&': '&amp;', '"': '&quot;' }[ch] as string));
966
+ }
967
+
889
968
  /** Strip the query string: routing matches the pathname, handlers read the full URL. */
890
- function pathnameOf(url: string | undefined): string {
891
- try {
969
+ function pathnameOf(url: string | undefined): string { try {
892
970
  return new URL(url || '/', 'http://localhost').pathname;
893
971
  } catch {
894
972
  return (url || '/').split('?')[0];
@@ -908,33 +986,29 @@ function queryOf(url: string | undefined): Record<string, string> {
908
986
  return q;
909
987
  }
910
988
 
911
- /**
912
- * P0-0 (bug report): listen on `port`, hopping to the next free one when it
913
- * is taken instead of crashing with EADDRINUSE. Two projects on one machine
914
- * (or a dev server that did not exit cleanly) is the everyday case, and a
915
- * stack trace plus a dead process is the worst possible answer to it: the
916
- * banner names the port actually used, so the URL is never a guess.
917
- *
918
- * The hop is bounded (20 tries) and every other error is fatal - silently
919
- * retrying a real fault would hide it.
920
- */
989
+ /** Listen on `port`, hopping to the next free one on EADDRINUSE. */
921
990
  function listenFree(server: any, port: number, onReady: (port: number) => void): void {
922
991
  const attempt = (p: number): void => {
923
- const onError = (err: any) => {
992
+ const cleanup = (): void => {
924
993
  server.removeListener('error', onError);
994
+ server.removeListener('listening', onListening);
995
+ };
996
+ const onError = (err: any): void => {
997
+ cleanup();
925
998
  if (err && err.code === 'EADDRINUSE' && p - port < 20) {
926
- console.log(`🌹 port ${p} is in use - trying ${p + 1}`);
927
999
  attempt(p + 1);
928
1000
  return;
929
1001
  }
930
1002
  console.error(`rosetack: cannot listen on port ${p}:`, err instanceof Error ? err.message : err);
931
1003
  process.exit(1);
932
1004
  };
933
- server.once('error', onError);
934
- server.listen(p, () => {
935
- server.removeListener('error', onError);
1005
+ const onListening = (): void => {
1006
+ cleanup();
936
1007
  onReady(p);
937
- });
1008
+ };
1009
+ server.once('error', onError);
1010
+ server.once('listening', onListening);
1011
+ server.listen(p);
938
1012
  };
939
1013
  attempt(port);
940
1014
  }
@@ -961,18 +1035,9 @@ async function freePort(from: number): Promise<number> {
961
1035
  }
962
1036
 
963
1037
  /**
964
- * The FRAMEWORK's version - one source of truth, no constant to drift.
965
- *
966
- * Three layouts answer, in order:
967
- * 1. src/FRAMEWORK_VERSION, a one-line stamp that ships beside the CLI
968
- * source. It is the only candidate that survives EMBEDDING: a real app
969
- * copies the framework's src/ into its own tree, where the nearest
970
- * package.json is the APP's - which is how a banner ended up naming the
971
- * app's version as the framework's for weeks, with no way to tell which
972
- * framework build was actually running.
973
- * 2. the package.json two directories up (this repo: the framework's own),
974
- * 3. the one beside the bundle (the published package: dist-cli/ + src/).
975
- * A test asserts the stamp equals package.json, so the two cannot drift.
1038
+ * The FRAMEWORK's version. FRAMEWORK_VERSION first because it is the only
1039
+ * candidate that survives embedding: an app copies this src/ into its own
1040
+ * tree, where the nearest package.json is the APP's.
976
1041
  */
977
1042
  function version(): string {
978
1043
  for (const rel of ['../FRAMEWORK_VERSION', '../../FRAMEWORK_VERSION', '../../package.json', '../package.json']) {
@@ -1005,6 +1070,8 @@ function projectTag(): string {
1005
1070
  }
1006
1071
 
1007
1072
  async function dev(): Promise<void> {
1073
+ devMode = true;
1074
+ process.env.rosetack_DEV = '1';
1008
1075
  console.log(`🌹 RoseTack v${version()}${projectTag()} dev server starting...`);
1009
1076
  try {
1010
1077
  await build();
@@ -1083,12 +1150,99 @@ async function serve(): Promise<void> {
1083
1150
  },
1084
1151
  };
1085
1152
  try {
1086
- await loadServer();
1153
+ const hooksMod = await loadServer();
1154
+ invalidateHook = () => { try { hooksMod.invalidateRenderCache(); } catch { } };
1087
1155
  } catch (err) {
1088
1156
  console.error('rosetack: dist/server.js failed to load for the serve hooks:', err instanceof Error ? err.message : String(err));
1089
1157
  }
1090
1158
  const http = await import('node:http');
1091
- const server = http.createServer(withAccessLog(serveStatic(OUT_DIR, true), `w${process.pid}`));
1159
+ const edgeReady = createEdgeHandler(OUT_DIR);
1160
+ edgeReady.then(async (handle) => {
1161
+ await ready;
1162
+ for (const r of (serverModule?.dynamicRoutes as string[] | undefined) || []) {
1163
+ if (r.includes(':')) continue;
1164
+ try {
1165
+ const res = await handle(new Request('http://localhost' + r));
1166
+ await res.arrayBuffer();
1167
+ } catch { /* a warm-up failure just means that route renders cold */ }
1168
+ }
1169
+ }).catch(() => {});
1170
+ const baseHandler = withAccessLog(serveStatic(OUT_DIR, true), `w${process.pid}`);
1171
+ const earlyHintLinks: string[] = (() => {
1172
+ try {
1173
+ const html = fs.readFileSync(path.join(OUT_DIR, 'index.html'), 'utf8');
1174
+ const links: string[] = [];
1175
+ for (const m of html.matchAll(/<script[^>]+src="([^"]+)"/g)) {
1176
+ const v = `<${m[1]}>; rel=preload; as=script`;
1177
+ if (!links.includes(v)) links.push(v);
1178
+ }
1179
+ for (const m of html.matchAll(/<link[^>]+rel="stylesheet"[^>]*>/g)) {
1180
+ const href = /href="([^"]+)"/.exec(m[0])?.[1];
1181
+ if (href) { const v = `<${href}>; rel=preload; as=style`; if (!links.includes(v)) links.push(v); }
1182
+ }
1183
+ for (const m of html.matchAll(/<link[^>]+href="([^"]+)"[^>]+rel="stylesheet"[^>]*>/g)) {
1184
+ const v = `<${m[1]}>; rel=preload; as=style`;
1185
+ if (!links.includes(v)) links.push(v);
1186
+ }
1187
+ return links;
1188
+ } catch { return []; }
1189
+ })();
1190
+ let dynRouteSet: Set<string> | null = null;
1191
+ const dynRoutesOf = (): Set<string> => {
1192
+ const list = (serverModule?.dynamicRoutes as string[] | undefined) || [];
1193
+ if (!dynRouteSet || dynRouteSet.size !== list.length) dynRouteSet = new Set(list);
1194
+ return dynRouteSet;
1195
+ };
1196
+ const server = http.createServer(async (req: any, res: any) => {
1197
+ let bytesWritten = 0;
1198
+ const started = process.hrtime.bigint();
1199
+ try {
1200
+ if ((req.method === 'GET' || req.method === 'HEAD') && dynRoutesOf().has(pathnameOf(req.url || '/'))) {
1201
+ const handle = await edgeReady;
1202
+ if (earlyHintLinks.length && req.method === 'GET' && String(req.headers.accept ?? '').includes('text/html')) {
1203
+ try { res.writeEarlyHints({ link: earlyHintLinks }); } catch { /* client gone: the render still finishes */ }
1204
+ }
1205
+ const url = requestOrigin(req, PORT) + (req.url || '/');
1206
+ const response = await handle(new Request(url, { method: req.method, headers: req.headers }));
1207
+ const access = () => writeAccessLine(req, res, bytesWritten, `w${process.pid}`, started);
1208
+ res.statusCode = response.status;
1209
+ response.headers.forEach((v: string, k: string) => res.setHeader(k, v));
1210
+ const htmlDoc = (response.headers.get('content-type') ?? '').startsWith('text/html');
1211
+ const enc = htmlDoc && req.method === 'GET' ? pickEncoding(req) : null;
1212
+ if (response.body && enc) {
1213
+ const raw = Buffer.from(await response.arrayBuffer());
1214
+ const etag = 'W/"' + createHash('sha1').update(raw).digest('base64url').slice(0, 24) + '"';
1215
+ if (req.headers['if-none-match'] === etag) {
1216
+ res.statusCode = 304;
1217
+ bytesWritten = 0;
1218
+ res.end();
1219
+ access();
1220
+ return;
1221
+ }
1222
+ const body = compress(enc, raw);
1223
+ res.setHeader('ETag', etag);
1224
+ res.setHeader('Content-Encoding', enc);
1225
+ res.setHeader('Content-Length', String(body.length));
1226
+ res.end(body);
1227
+ bytesWritten = body.length;
1228
+ access();
1229
+ return;
1230
+ }
1231
+ if (response.body) {
1232
+ const raw = Buffer.from(await response.arrayBuffer());
1233
+ bytesWritten = raw.length;
1234
+ res.end(raw);
1235
+ access();
1236
+ } else {
1237
+ res.end();
1238
+ bytesWritten = 0;
1239
+ access();
1240
+ }
1241
+ return;
1242
+ }
1243
+ } catch { /* any edge hiccup falls through to the proven pipeline */ }
1244
+ baseHandler(req, res);
1245
+ });
1092
1246
  server.requestTimeout = 30_000;
1093
1247
  server.headersTimeout = 65_000;
1094
1248
  server.keepAliveTimeout = 5_000;
@@ -1113,7 +1267,9 @@ async function serve(): Promise<void> {
1113
1267
  console.error('rosetack: plugin', p.name, 'onShutdown failed:', err instanceof Error ? err.message : err);
1114
1268
  }
1115
1269
  }
1116
- server.close(() => process.exit(0));
1270
+ server.close(() => {
1271
+ void runShutdownHooks('worker signal').finally(() => process.exit(0));
1272
+ });
1117
1273
  server.closeIdleConnections?.();
1118
1274
  setTimeout(() => process.exit(0), 5000).unref();
1119
1275
  };
@@ -0,0 +1,9 @@
1
+
2
+ export function requestOrigin(req: any, fallbackPort: number | string): string {
3
+ const rawProto = String(req.headers?.['x-forwarded-proto'] || '');
4
+ const proto = rawProto.split(',')[0]!.trim();
5
+ const scheme = proto === 'https' || proto === 'http' ? proto : 'http';
6
+ const rawHost = String(req.headers?.['x-forwarded-host'] || '');
7
+ const host = rawHost.split(',')[0]!.trim() || req.headers?.host || `localhost:${fallbackPort}`;
8
+ return `${scheme}://${host}`;
9
+ }