rosetack 0.0.0 → 0.1.1
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/LICENSE +21 -0
- package/deploy/Dockerfile.node +25 -0
- package/deploy/Dockerfile.static +34 -0
- package/deploy/api/rosetack.ts +29 -0
- package/deploy/docker-compose.yml +33 -0
- package/deploy/fly.toml +28 -0
- package/deploy/vercel.json +13 -0
- package/dist-cli/compiler.mjs +2302 -0
- package/dist-cli/edge.mjs +297 -0
- package/dist-cli/rosetack.mjs +3411 -0
- package/dist-cli/runtime.mjs +619 -0
- package/dist-cli/test.mjs +2696 -0
- package/pack.mjs +49 -0
- package/package.json +50 -11
- package/src/FRAMEWORK_VERSION +1 -0
- package/src/cli/edge.ts +162 -0
- package/src/cli/index.ts +1233 -0
- package/src/cli/shell.ts +337 -0
- package/src/cli/test.ts +400 -0
- package/src/compiler/index.ts +3076 -0
- package/src/runtime/index.ts +915 -0
- package/src/types/rosetack.d.ts +142 -0
- package/README.md +0 -3
- package/index.js +0 -12
package/src/cli/index.ts
ADDED
|
@@ -0,0 +1,1233 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* rosetack CLI - simplest possible SSR + static server
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import * as fs from 'fs';
|
|
6
|
+
import * as path from 'path';
|
|
7
|
+
import * as zlib from 'zlib';
|
|
8
|
+
import { createRequire } from 'module';
|
|
9
|
+
import { pathToFileURL, fileURLToPath } from 'url';
|
|
10
|
+
import { buildProject, scanRoseFiles, scanComponentFiles, scriptOf, extractExports, loadPlugins, type RouteInfo } from '../compiler/index.js';
|
|
11
|
+
import { getHtmlShell, getClientSource, getStyles, shellOpen, clientScriptTag, securityHeaders, mintNonce, setBundleMode } from './shell.js';
|
|
12
|
+
// Type-only: erased by esbuild/tsx, so the published CLI stays a ~100 KB bundle with no
|
|
13
|
+
// TypeScript dependency.
|
|
14
|
+
import type * as ts from 'typescript';
|
|
15
|
+
|
|
16
|
+
// --- wire performance: compression + conditional caching (stdlib only) --- The Go binary
|
|
17
|
+
// already compresses …
|
|
18
|
+
type Encoding = 'br' | 'gzip' | 'deflate';
|
|
19
|
+
|
|
20
|
+
function pickEncoding(req: any): Encoding | null {
|
|
21
|
+
const ae: string = req.headers['accept-encoding'] || '';
|
|
22
|
+
// Trade-off: substring match, no q-value parsing - every browser that sends
|
|
23
|
+
// br also accepts gzip, and br > gzip > deflate is the quality order.
|
|
24
|
+
if (ae.includes('br')) return 'br';
|
|
25
|
+
if (ae.includes('gzip')) return 'gzip';
|
|
26
|
+
if (ae.includes('deflate')) return 'deflate';
|
|
27
|
+
return null;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// Brotli's default quality (11) spends ~108 ms of CPU on a 32 KB document; quality 5 does
|
|
31
|
+
// the same document in ~2.4 ms for 9% more bytes (measured, Node 22).
|
|
32
|
+
const brotliFast = { [zlib.constants.BROTLI_PARAM_QUALITY]: 5 };
|
|
33
|
+
|
|
34
|
+
function compress(enc: Encoding, data: string | Buffer): Buffer {
|
|
35
|
+
if (enc === 'br') return zlib.brotliCompressSync(data, { params: brotliFast });
|
|
36
|
+
if (enc === 'gzip') return zlib.gzipSync(data);
|
|
37
|
+
return zlib.deflateSync(data);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function createCompressor(enc: Encoding): zlib.Gzip | zlib.Deflate | zlib.BrotliCompress {
|
|
41
|
+
if (enc === 'br') return zlib.createBrotliCompress({ params: brotliFast });
|
|
42
|
+
if (enc === 'gzip') return zlib.createGzip();
|
|
43
|
+
return zlib.createDeflate();
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Send a full HTML document, compressed when the client accepts it. */
|
|
47
|
+
function sendHtml(req: any, res: any, status: number, html: string, extraHeaders?: Record<string, string>): void {
|
|
48
|
+
res.statusCode = status;
|
|
49
|
+
res.setHeader('Content-Type', 'text/html; charset=utf-8');
|
|
50
|
+
res.setHeader('Vary', 'Accept-Encoding');
|
|
51
|
+
if (extraHeaders) for (const [k, v] of Object.entries(extraHeaders)) res.setHeader(k, v);
|
|
52
|
+
// A weak ETag over the rendered bytes: revalidation answers a bodiless 304 for dynamic
|
|
53
|
+
// renders too …
|
|
54
|
+
let hash = 0x811c9dc5;
|
|
55
|
+
for (let i = 0; i < html.length; i++) {
|
|
56
|
+
hash ^= html.charCodeAt(i);
|
|
57
|
+
hash = (hash * 0x01000193) >>> 0;
|
|
58
|
+
}
|
|
59
|
+
const etag = `W/"${html.length}-${hash.toString(16)}"`;
|
|
60
|
+
if (req.headers['if-none-match'] === etag) {
|
|
61
|
+
res.statusCode = 304;
|
|
62
|
+
res.end();
|
|
63
|
+
return;
|
|
64
|
+
}
|
|
65
|
+
res.setHeader('ETag', etag);
|
|
66
|
+
const enc = pickEncoding(req);
|
|
67
|
+
if (enc) {
|
|
68
|
+
res.setHeader('Content-Encoding', enc);
|
|
69
|
+
res.end(compress(enc, html));
|
|
70
|
+
} else {
|
|
71
|
+
res.end(html);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// Copy a Web-standard Response's headers onto the Node response. set-cookie is the one
|
|
76
|
+
// header that may legally repeat, and res.setHeader overwrites …
|
|
77
|
+
function writeWebHeaders(web: any, res: any): void {
|
|
78
|
+
const cookies = web.headers.getSetCookie?.() ?? [];
|
|
79
|
+
web.headers.forEach((v: string, k: string) => {
|
|
80
|
+
if (cookies.length && k.toLowerCase() === 'set-cookie') return;
|
|
81
|
+
res.setHeader(k, v);
|
|
82
|
+
});
|
|
83
|
+
if (cookies.length) res.setHeader('set-cookie', cookies);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// A middleware's short-circuit: a Web-standard Response (status, headers, body) written
|
|
87
|
+
// straight to the Node response - a redirect, an auth wall, a rewrite.
|
|
88
|
+
async function sendWebResponse(web: any, res: any): Promise<void> {
|
|
89
|
+
writeWebHeaders(web, res);
|
|
90
|
+
res.statusCode = web.status;
|
|
91
|
+
res.end(Buffer.from(await web.arrayBuffer()));
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Send a rendered page document - through onResponse first . The
|
|
96
|
+
* hook sees the status, headers and body exactly as they will go on the
|
|
97
|
+
* wire and may replace them, so the ETag inside sendHtml is then computed
|
|
98
|
+
* over the bytes actually sent. One helper for the POST-action path and the
|
|
99
|
+
* buffered GET path: same hook, same order, no drift between them.
|
|
100
|
+
*/
|
|
101
|
+
async function sendPage(req: any, res: any, ssrModule: any, hookCtx: any, page: any, routePath: string): Promise<void> {
|
|
102
|
+
let status = page.status ?? 200;
|
|
103
|
+
// page.lang/page.dir are the locale the render used: the document's <html> attributes
|
|
104
|
+
// follow the route's [lang] segment.
|
|
105
|
+
const nonce = nonceFor(ssrModule, routePath);
|
|
106
|
+
// a nonce route is dynamic by construction (the compiler put it in dynamicRoutes), so it
|
|
107
|
+
// always lands here or in the stream below - never on the baked-file path …
|
|
108
|
+
let html = getHtmlShell(page.html, page.state, page.head, page.csr !== false, page.lang, page.dir, nonce);
|
|
109
|
+
let headers: Record<string, any> = pageHeaders(ssrModule, routePath, nonce);
|
|
110
|
+
if (hookCtx) {
|
|
111
|
+
const out = await ssrModule.runResponseHooks(hookCtx, new Response(html, { status, headers }));
|
|
112
|
+
status = out.status;
|
|
113
|
+
headers = webHeadersToNode(out);
|
|
114
|
+
html = await out.text();
|
|
115
|
+
}
|
|
116
|
+
sendHtml(req, res, status, html, headers);
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// Static files: raw + both compressed forms cached per mtime (dev rebuilds change mtime;
|
|
120
|
+
// preview never does).
|
|
121
|
+
const fileCache = new Map<string, { mtimeMs: number; raw: Buffer; br: Buffer; gzip: Buffer; etag: string }>();
|
|
122
|
+
|
|
123
|
+
// (the "the framework is real" gate): the CLI builds ANY project, not just this repo's
|
|
124
|
+
// demo.
|
|
125
|
+
const SRC_DIR = process.argv[3] ? path.resolve(process.argv[3]) : process.cwd();
|
|
126
|
+
// The deploy dir is ./dist of the directory the command ran from - a documented contract
|
|
127
|
+
// (test-cli.mjs asserts it): building a project that is not the cwd still drops its output …
|
|
128
|
+
const OUT_DIR = path.join(process.cwd(), 'dist');
|
|
129
|
+
// PORT env override (default 3000): lets a preview server run beside a dev
|
|
130
|
+
// server on the same machine - the e2e ISR test does exactly that.
|
|
131
|
+
const PORT = Number(process.env.PORT) || 3000;
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* Import dist/server.js, cached until the file changes on disk.
|
|
135
|
+
*
|
|
136
|
+
* The dev server rebuilds it on file changes, so a plain import() would
|
|
137
|
+
* serve the cached (stale) module - re-import when mtime moves. But the
|
|
138
|
+
* import must NOT be per-request: server state (stores mutated by server
|
|
139
|
+
* actions) lives in that module, and a fresh import per request would
|
|
140
|
+
* reset it on every hit, so an action's effect would vanish immediately.
|
|
141
|
+
*/
|
|
142
|
+
let serverModule: any = null;
|
|
143
|
+
let serverMtime = -1;
|
|
144
|
+
let serverVersion = 0;
|
|
145
|
+
|
|
146
|
+
async function loadServer(): Promise<any> {
|
|
147
|
+
const file = path.join(OUT_DIR, 'server.js');
|
|
148
|
+
const mtimeMs = fs.statSync(file).mtimeMs;
|
|
149
|
+
if (!serverModule || mtimeMs !== serverMtime) {
|
|
150
|
+
serverMtime = mtimeMs;
|
|
151
|
+
serverVersion++;
|
|
152
|
+
serverModule = await import(pathToFileURL(file).href + '?v=' + serverVersion);
|
|
153
|
+
}
|
|
154
|
+
return serverModule;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
async function build(): Promise<void> {
|
|
158
|
+
// The build reports the bundle mode ('inline' | 'split') so the
|
|
159
|
+
// shell follows it for every document, header and streaming tag it emits
|
|
160
|
+
const { routes, bundle } = await buildProject(SRC_DIR, OUT_DIR);
|
|
161
|
+
// The previous build's prerendered output must not survive: a route that stopped being
|
|
162
|
+
// static (it started reading getContext() or $store()) would otherwise leave its old
|
|
163
|
+
// baked …
|
|
164
|
+
await clearPrerendered(OUT_DIR);
|
|
165
|
+
setBundleMode(bundle);
|
|
166
|
+
const skipped = await prerender(routes);
|
|
167
|
+
// The broken-route manifest: the server reads it to pick the buffered path for these
|
|
168
|
+
// routes, so their real 500 status survives (a flushed response cannot change its
|
|
169
|
+
// status).
|
|
170
|
+
await fs.promises.writeFile(path.join(OUT_DIR, 'broken.json'), JSON.stringify(skipped));
|
|
171
|
+
// Per-route response headers for the Go binary, which has no compiler: it reads this file
|
|
172
|
+
// and merges the entries over its own responses.
|
|
173
|
+
const ssrModule = await loadServer();
|
|
174
|
+
await fs.promises.writeFile(path.join(OUT_DIR, 'headers.json'), JSON.stringify({
|
|
175
|
+
default: securityHeaders(getClientSource()),
|
|
176
|
+
routes: ssrModule.routeHeaders ?? [],
|
|
177
|
+
}));
|
|
178
|
+
// Precompressed brotli siblings (dist/<file>.br) for the Go single binary. The binary
|
|
179
|
+
// embeds dist/ verbatim …
|
|
180
|
+
await writeBrotli(OUT_DIR);
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* Write dist/<file>.br next to every compressible text file. trade-off:
|
|
185
|
+
* extension allowlist + zlib's default quality - a 30 KB document
|
|
186
|
+
* compresses in ~10 ms at build time, once, forever.
|
|
187
|
+
*/
|
|
188
|
+
const BROTLI_EXT = new Set(['.html', '.js', '.css', '.json', '.svg', '.txt']);
|
|
189
|
+
async function writeBrotli(dir: string): Promise<void> {
|
|
190
|
+
for (const e of await fs.promises.readdir(dir, { withFileTypes: true })) {
|
|
191
|
+
const p = path.join(dir, e.name);
|
|
192
|
+
if (e.isDirectory()) {
|
|
193
|
+
await writeBrotli(p);
|
|
194
|
+
continue;
|
|
195
|
+
}
|
|
196
|
+
if (!BROTLI_EXT.has(path.extname(e.name).toLowerCase())) continue;
|
|
197
|
+
await fs.promises.writeFile(p + '.br', zlib.brotliCompressSync(await fs.promises.readFile(p)));
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/**
|
|
202
|
+
* Delete the prerendered output of a previous build: HTML documents and
|
|
203
|
+
* baked API bodies, with their brotli siblings. Everything else in dist/
|
|
204
|
+
* (the bundles, styles) was just rewritten by buildProject.
|
|
205
|
+
*
|
|
206
|
+
* Trade-off: Windows hands out transient EPERM/EBUSY when an antivirus or
|
|
207
|
+
* the search indexer holds a just-written file, so a couple of retries
|
|
208
|
+
* per file - a build that fails because a scanner blinked is the worst
|
|
209
|
+
* kind of flake.
|
|
210
|
+
*/
|
|
211
|
+
async function clearPrerendered(dir: string, depth = 0): Promise<void> {
|
|
212
|
+
for (const e of await fs.promises.readdir(dir, { withFileTypes: true })) {
|
|
213
|
+
// Dist/locales/ holds the runtime locale packs the build just wrote (i18n.preload's
|
|
214
|
+
// leftovers) - they are .json files like any prerendered body, but they are build output …
|
|
215
|
+
if (depth === 0 && e.name === 'locales' && e.isDirectory()) continue;
|
|
216
|
+
const p = path.join(dir, e.name);
|
|
217
|
+
if (e.isDirectory()) {
|
|
218
|
+
await clearPrerendered(p, depth + 1);
|
|
219
|
+
continue;
|
|
220
|
+
}
|
|
221
|
+
if (!/\.(?:html|json)(?:\.br)?$/.test(e.name)) continue;
|
|
222
|
+
for (let attempt = 0; ; attempt++) {
|
|
223
|
+
try {
|
|
224
|
+
await fs.promises.rm(p, { force: true });
|
|
225
|
+
break;
|
|
226
|
+
} catch (err) {
|
|
227
|
+
if (attempt >= 2 || !/EPERM|EBUSY|EACCES/.test(String(err))) throw err;
|
|
228
|
+
await new Promise((r) => setTimeout(r, 50 * (attempt + 1)));
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/**
|
|
235
|
+
* Prerender every static route to dist/<route>/index.html at build time.
|
|
236
|
+
* Those files are served straight from disk: zero server work, instant TTFB.
|
|
237
|
+
* Dynamic routes with an exported `params` map (e.g. blog posts) are
|
|
238
|
+
* enumerated and prerendered per value; params without `params` keep
|
|
239
|
+
* rendering on demand. A route exporting `revalidate = N` is baked like
|
|
240
|
+
* any other and then kept fresh by the preview server's stale-while-
|
|
241
|
+
* revalidate pass (ISR).
|
|
242
|
+
*/
|
|
243
|
+
async function prerender(routes: RouteInfo[]): Promise<string[]> {
|
|
244
|
+
const ssrModule = await loadServer();
|
|
245
|
+
const skipped: string[] = [];
|
|
246
|
+
const write = async (routePath: string) => {
|
|
247
|
+
// a synthetic cookie-less request: the middleware runs at build time too, and a route
|
|
248
|
+
// it short-circuits (an auth wall, a maintenance rewrite) simply is not static …
|
|
249
|
+
const mw = await ssrModule.runMiddleware({ method: 'GET', url: routePath, headers: {} });
|
|
250
|
+
if (mw) {
|
|
251
|
+
console.error(`prerender skipped for ${routePath}: the middleware short-circuits at build time`);
|
|
252
|
+
skipped.push(routePath);
|
|
253
|
+
return;
|
|
254
|
+
}
|
|
255
|
+
const page = await ssrModule.renderPage(routePath);
|
|
256
|
+
if (page.status === 500) {
|
|
257
|
+
// The route's render failed and the error page rendered instead. Do NOT bake that
|
|
258
|
+
// into a static file: a static server can only answer 200 …
|
|
259
|
+
console.error(`prerender skipped for ${routePath}: render failed, the error page rendered`);
|
|
260
|
+
skipped.push(routePath);
|
|
261
|
+
return;
|
|
262
|
+
}
|
|
263
|
+
const routeDir = routePath === '/' ? OUT_DIR : path.join(OUT_DIR, routePath.slice(1));
|
|
264
|
+
await fs.promises.mkdir(routeDir, { recursive: true });
|
|
265
|
+
// csr = false routes bake a JS-free document: the file on disk carries no bundle and no
|
|
266
|
+
// state script, so a visitor who lands on it runs zero JavaScript.
|
|
267
|
+
await fs.promises.writeFile(path.join(routeDir, 'index.html'), getHtmlShell(page.html, page.state, page.head, page.csr !== false, page.lang, page.dir));
|
|
268
|
+
console.log(`prerendered ${routePath} -> ${path.relative(process.cwd(), path.join(routeDir, 'index.html'))}`);
|
|
269
|
+
};
|
|
270
|
+
|
|
271
|
+
for (const info of routes) {
|
|
272
|
+
// routes that read the request context (getContext()) or a shared store ($store()) are
|
|
273
|
+
// dynamic by construction: the bag is per-request and the store is per-process …
|
|
274
|
+
if ((ssrModule.dynamicRoutes as string[]).includes(info.routePath)) {
|
|
275
|
+
console.log(`dynamic route ${info.routePath}: per-request state (getContext/$store), rendered on demand`);
|
|
276
|
+
continue;
|
|
277
|
+
}
|
|
278
|
+
if (info.paramNames.length === 0) {
|
|
279
|
+
try {
|
|
280
|
+
await write(info.routePath);
|
|
281
|
+
} catch (err) {
|
|
282
|
+
// One broken route (e.g. throwing $data) must not fail the whole build;
|
|
283
|
+
// it simply keeps rendering on demand.
|
|
284
|
+
console.error(`prerender skipped for ${info.routePath}: ${err instanceof Error ? err.message : err}`);
|
|
285
|
+
skipped.push(info.routePath);
|
|
286
|
+
}
|
|
287
|
+
continue;
|
|
288
|
+
}
|
|
289
|
+
// dynamic route: enumerate the exported params map, if any. The maps are re-exported by
|
|
290
|
+
// the server bundle (routeParams) …
|
|
291
|
+
try {
|
|
292
|
+
const paramsExport = (ssrModule.routeParams as Record<string, unknown>)?.[info.routePath];
|
|
293
|
+
const raw = typeof paramsExport === 'function' ? await (paramsExport as () => unknown)() : paramsExport;
|
|
294
|
+
const paths = enumerateParams(info.pattern, info.paramNames, (raw ?? {}) as Record<string, unknown>);
|
|
295
|
+
for (const p of paths) await write(p);
|
|
296
|
+
if (paths.length === 0) console.log(`dynamic route ${info.routePath}: no params export, rendered on demand`);
|
|
297
|
+
} catch (err) {
|
|
298
|
+
console.error(`prerender skipped for ${info.routePath}: ${err instanceof Error ? err.message : err}`);
|
|
299
|
+
skipped.push(info.routePath);
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
// API routes that opt in (export const prerender = true) bake their GET body into
|
|
304
|
+
// dist/api/<route>.json: the Go single binary then serves the read-only API with zero
|
|
305
|
+
// Node.
|
|
306
|
+
const apiPrerender = (ssrModule.apiPrerender as Record<string, boolean>) ?? {};
|
|
307
|
+
for (const [routePath, on] of Object.entries(apiPrerender)) {
|
|
308
|
+
if (!on) continue;
|
|
309
|
+
try {
|
|
310
|
+
const res = await ssrModule.handleApi('GET', routePath, new Request('http://localhost' + routePath));
|
|
311
|
+
if (res.status !== 200) {
|
|
312
|
+
console.error(`api prerender skipped for ${routePath}: GET answered ${res.status}`);
|
|
313
|
+
continue;
|
|
314
|
+
}
|
|
315
|
+
const body = await res.text();
|
|
316
|
+
const outFile = path.join(OUT_DIR, routePath.slice(1) + '.json');
|
|
317
|
+
await fs.promises.mkdir(path.dirname(outFile), { recursive: true });
|
|
318
|
+
await fs.promises.writeFile(outFile, body);
|
|
319
|
+
console.log(`prerendered api ${routePath} -> ${path.relative(process.cwd(), outFile)}`);
|
|
320
|
+
} catch (err) {
|
|
321
|
+
console.error(`api prerender skipped for ${routePath}: ${err instanceof Error ? err.message : err}`);
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
return skipped;
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
/** Cartesian product of the params map -> concrete URL paths for the pattern. */
|
|
328
|
+
function enumerateParams(pattern: string, names: string[], raw: Record<string, unknown>): string[] {
|
|
329
|
+
let combos: string[][] = [[]];
|
|
330
|
+
for (const name of names) {
|
|
331
|
+
const values = (Array.isArray(raw[name]) ? raw[name] : []).map((v) => String(v));
|
|
332
|
+
combos = combos.flatMap((c) => values.map((v) => [...c, v]));
|
|
333
|
+
}
|
|
334
|
+
return combos.map((values) => {
|
|
335
|
+
let i = 0;
|
|
336
|
+
return pattern
|
|
337
|
+
.split('/')
|
|
338
|
+
.map((seg) => (seg.startsWith(':') ? encodeURIComponent(values[i++]) : seg))
|
|
339
|
+
.join('/');
|
|
340
|
+
});
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
// Extensions the static branch serves without touching the router: assets keep their fast
|
|
344
|
+
// path even when a middleware exists (a middleware guards pages, not files).
|
|
345
|
+
const ASSET_EXT = new Set(['.js', '.css', '.json', '.png', '.jpg', '.jpeg', '.gif', '.svg', '.ico', '.webp', '.woff', '.woff2', '.txt', '.xml']);
|
|
346
|
+
|
|
347
|
+
// Response headers for a page document: the strict CSP (hashed over the exact inlined
|
|
348
|
+
// bundle + bootstrap bytes …
|
|
349
|
+
function pageHeaders(ssrModule: any, pathname: string, nonce = ''): Record<string, string> {
|
|
350
|
+
const headers: Record<string, string> = {};
|
|
351
|
+
for (const [k, v] of Object.entries(securityHeaders(getClientSource(), nonce))) headers[k.toLowerCase()] = v;
|
|
352
|
+
const own = ssrModule.headersFor?.(pathname) as Record<string, string> | null | undefined;
|
|
353
|
+
if (own) for (const [k, v] of Object.entries(own)) headers[k.toLowerCase()] = v;
|
|
354
|
+
return headers;
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
/**
|
|
358
|
+
* The nonce for one response, or '' when the route keeps the hashed policy
|
|
359
|
+
* . Only the routes that exported `csp = { nonce: true }` ask for one,
|
|
360
|
+
* so every other document is byte-for-byte what it was.
|
|
361
|
+
*/
|
|
362
|
+
function nonceFor(ssrModule: any, pathname: string): string {
|
|
363
|
+
return ssrModule.cspNonce?.(pathname) ? mintNonce() : '';
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
// ISR background pass: re-render a stale baked route and swap its file, while the
|
|
367
|
+
// triggering request was already answered from disk (stale-while-revalidate).
|
|
368
|
+
const isrBusy = new Set<string>();
|
|
369
|
+
function revalidateInBackground(routePath: string, filePath: string): void {
|
|
370
|
+
if (isrBusy.has(filePath)) return;
|
|
371
|
+
isrBusy.add(filePath);
|
|
372
|
+
void (async () => {
|
|
373
|
+
try {
|
|
374
|
+
const ssrModule = await loadServer();
|
|
375
|
+
const page = await ssrModule.renderPage(routePath);
|
|
376
|
+
if (page.status === 200) {
|
|
377
|
+
// the swap must honor the route's csr decision: a zero-JS route revalidated here stays
|
|
378
|
+
// zero-JS, or the first stale window would silently inline the bundle into its baked file
|
|
379
|
+
await fs.promises.writeFile(filePath, getHtmlShell(page.html, page.state, page.head, page.csr !== false, page.lang, page.dir));
|
|
380
|
+
fileCache.delete(filePath);
|
|
381
|
+
console.log(`rosetack: revalidated ${routePath} in the background`);
|
|
382
|
+
}
|
|
383
|
+
} catch (err) {
|
|
384
|
+
console.error('rosetack: background revalidation failed for', routePath, err instanceof Error ? err.message : err);
|
|
385
|
+
} finally {
|
|
386
|
+
isrBusy.delete(filePath);
|
|
387
|
+
}
|
|
388
|
+
})();
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
// --- production server posture -------------------------------------- "Can run a real app"
|
|
392
|
+
// is a threshold …
|
|
393
|
+
|
|
394
|
+
/** A request body is bounded. 1 MB holds any form and any JSON API call a
|
|
395
|
+
* site this size makes; a deployment that needs more sets it explicitly. */
|
|
396
|
+
const MAX_BODY = Number(process.env.rosetack_MAX_BODY) || 1024 * 1024;
|
|
397
|
+
|
|
398
|
+
/**
|
|
399
|
+
* Collect a request body, refusing anything past MAX_BODY with a 413. The
|
|
400
|
+
* refusal stops buffering immediately, so a client streaming 10 GB gets one
|
|
401
|
+
* small response instead of a 10 GB buffer.
|
|
402
|
+
*/
|
|
403
|
+
function readBody(req: any, res: any, onDone: (body: any) => void): void {
|
|
404
|
+
const chunks: Buffer[] = [];
|
|
405
|
+
let size = 0;
|
|
406
|
+
let refused = false;
|
|
407
|
+
req.on('data', (c: Buffer) => {
|
|
408
|
+
if (refused) return;
|
|
409
|
+
size += c.length;
|
|
410
|
+
if (size > MAX_BODY) {
|
|
411
|
+
refused = true;
|
|
412
|
+
res.statusCode = 413;
|
|
413
|
+
res.setHeader('Content-Type', 'text/plain; charset=utf-8');
|
|
414
|
+
res.end(`Payload too large (limit ${MAX_BODY} bytes)`);
|
|
415
|
+
return;
|
|
416
|
+
}
|
|
417
|
+
chunks.push(c);
|
|
418
|
+
});
|
|
419
|
+
req.on('end', () => { if (!refused) onDone(Buffer.concat(chunks)); });
|
|
420
|
+
// an aborted upload must not throw an unhandled 'error' and take the process down with it
|
|
421
|
+
req.on('error', () => {});
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
/**
|
|
425
|
+
* CSRF: a state-changing request that did not come from this site is
|
|
426
|
+
* refused before anything else runs. Browsers stamp every cross-origin POST
|
|
427
|
+
* with an Origin header, so the check is free for real browsers; a client
|
|
428
|
+
* that sends neither Origin nor Sec-Fetch-Site (curl, a health check, the
|
|
429
|
+
* test suites) is not attackable by CSRF - the attack rides the victim's
|
|
430
|
+
* cookies in a browser - so it passes. Returns the refusal, or null.
|
|
431
|
+
*/
|
|
432
|
+
function crossSiteWrite(req: any): { status: number; body: string } | null {
|
|
433
|
+
const m = req.method;
|
|
434
|
+
if (m !== 'POST' && m !== 'PUT' && m !== 'PATCH' && m !== 'DELETE') return null;
|
|
435
|
+
const origin = req.headers.origin;
|
|
436
|
+
if (origin) {
|
|
437
|
+
let host: string;
|
|
438
|
+
try {
|
|
439
|
+
host = new URL(origin).host;
|
|
440
|
+
} catch {
|
|
441
|
+
return { status: 403, body: 'Cross-site request blocked (unparsable Origin header)' };
|
|
442
|
+
}
|
|
443
|
+
return host === req.headers.host ? null : { status: 403, body: 'Cross-site request blocked (Origin does not match Host)' };
|
|
444
|
+
}
|
|
445
|
+
const site = req.headers['sec-fetch-site'];
|
|
446
|
+
if (site && site !== 'same-origin' && site !== 'same-site' && site !== 'none') {
|
|
447
|
+
return { status: 403, body: `Cross-site request blocked (sec-fetch-site: ${site})` };
|
|
448
|
+
}
|
|
449
|
+
return null;
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
/**
|
|
453
|
+
* One access line per request on stdout - the same greppable shape the Go
|
|
454
|
+
* binary writes (`ts method path status bytes duration`), with the worker id
|
|
455
|
+
* in front when several workers share one stdout. Logged on the response's
|
|
456
|
+
* finish, so a streamed route is recorded when it is actually done.
|
|
457
|
+
*/
|
|
458
|
+
function withAccessLog(handler: (req: any, res: any) => void, tag?: string): (req: any, res: any) => void {
|
|
459
|
+
return (req, res) => {
|
|
460
|
+
const started = process.hrtime.bigint();
|
|
461
|
+
let bytes = 0;
|
|
462
|
+
const write = res.write.bind(res);
|
|
463
|
+
const end = res.end.bind(res);
|
|
464
|
+
res.write = (chunk: any, ...rest: any[]) => { if (chunk) bytes += Buffer.byteLength(chunk); return write(chunk, ...rest); };
|
|
465
|
+
res.end = (chunk: any, ...rest: any[]) => { if (chunk) bytes += Buffer.byteLength(chunk); return end(chunk, ...rest); };
|
|
466
|
+
res.on('finish', () => {
|
|
467
|
+
const ms = Number(process.hrtime.bigint() - started) / 1e6;
|
|
468
|
+
const dur = ms >= 1 ? `${ms.toFixed(3)}ms` : `${(ms * 1000).toFixed(0)}us`;
|
|
469
|
+
console.log(`${new Date().toISOString().slice(0, 19)}Z${tag ? ` [${tag}]` : ''} ${req.method} ${req.url} ${res.statusCode} ${bytes}B ${dur}`);
|
|
470
|
+
});
|
|
471
|
+
handler(req, res);
|
|
472
|
+
};
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
/**
|
|
476
|
+
* The context a runtime plugin hook receives. Node's
|
|
477
|
+
* IncomingMessage is not a Web Request and a hook must not care which server
|
|
478
|
+
* it runs on, so the CLI builds the same object the edge adapter already
|
|
479
|
+
* has. Built only when the project declares a runtime hook (the server
|
|
480
|
+
* bundle exports the flags) - the hot path never pays for the feature.
|
|
481
|
+
*
|
|
482
|
+
* The body is deliberately not attached: the servers read it lazily, and
|
|
483
|
+
* buffering it for every request would cost the fast path. A hook that needs
|
|
484
|
+
* the submitted form uses pages/_middleware.rose, which already rides with
|
|
485
|
+
* the parsed FormData.
|
|
486
|
+
*/
|
|
487
|
+
async function hookContext(req: any): Promise<{
|
|
488
|
+
request: Request;
|
|
489
|
+
url: URL;
|
|
490
|
+
method: string;
|
|
491
|
+
pathname: string;
|
|
492
|
+
state: Record<string, unknown>;
|
|
493
|
+
}> {
|
|
494
|
+
const headers: Record<string, string> = {};
|
|
495
|
+
for (const [k, v] of Object.entries(req.headers)) {
|
|
496
|
+
if (v !== undefined) headers[k] = Array.isArray(v) ? v.join(', ') : String(v);
|
|
497
|
+
}
|
|
498
|
+
const request = new Request(`http://${req.headers.host || 'localhost'}${req.url}`, {
|
|
499
|
+
method: req.method || 'GET',
|
|
500
|
+
headers,
|
|
501
|
+
});
|
|
502
|
+
const url = new URL(request.url);
|
|
503
|
+
return { request, url, method: request.method, pathname: url.pathname, state: {} };
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
/** A Web Response's headers as a Node header record, set-cookie kept whole. */
|
|
507
|
+
function webHeadersToNode(web: any): Record<string, any> {
|
|
508
|
+
const out: Record<string, any> = {};
|
|
509
|
+
const cookies = web.headers.getSetCookie?.() ?? [];
|
|
510
|
+
web.headers.forEach((v: string, k: string) => {
|
|
511
|
+
if (cookies.length && k.toLowerCase() === 'set-cookie') return;
|
|
512
|
+
out[k] = v;
|
|
513
|
+
});
|
|
514
|
+
if (cookies.length) out['set-cookie'] = cookies;
|
|
515
|
+
return out;
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
function serveStatic(dir: string, isr = false): (req: any, res: any) => void {
|
|
519
|
+
return (req, res) => {
|
|
520
|
+
// The origin guard runs before everything else - middleware, api dispatch, the static
|
|
521
|
+
// lookup - because a cross-site write must not reach any of them.
|
|
522
|
+
const blocked = crossSiteWrite(req);
|
|
523
|
+
if (blocked) {
|
|
524
|
+
res.statusCode = blocked.status;
|
|
525
|
+
res.setHeader('Content-Type', 'text/plain; charset=utf-8');
|
|
526
|
+
res.end(blocked.body);
|
|
527
|
+
return;
|
|
528
|
+
}
|
|
529
|
+
// Everything below needs the server module (API dispatch, POST actions, SSR), so load
|
|
530
|
+
// it once up front: the import is cached until dist/server.js changes on disk …
|
|
531
|
+
loadServer().then(async (ssrModule: any) => {
|
|
532
|
+
// Runtime hooks: onRequest runs after the origin guard and BEFORE middleware and routing,
|
|
533
|
+
// and may short-circuit the request with its own Response …
|
|
534
|
+
const hookCtx = ssrModule.hasRequestHooks === true || ssrModule.hasResponseHooks === true
|
|
535
|
+
? await hookContext(req)
|
|
536
|
+
: null;
|
|
537
|
+
if (hookCtx) {
|
|
538
|
+
const short = await ssrModule.runRequestHooks(hookCtx);
|
|
539
|
+
if (short) {
|
|
540
|
+
// the short-circuit rides through onResponse like every other
|
|
541
|
+
// response, so a header-adding hook sees it too
|
|
542
|
+
await sendWebResponse(await ssrModule.runResponseHooks(hookCtx, short), res);
|
|
543
|
+
return;
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
// Middleware (pages/_middleware.rose) runs exactly once per request, before anything
|
|
547
|
+
// else: a returned Response short-circuits the whole request …
|
|
548
|
+
const apiPath0 = pathnameOf(req.url);
|
|
549
|
+
const isPagePost = req.method === 'POST' && !ssrModule.isApi(apiPath0);
|
|
550
|
+
if (!isPagePost && ssrModule.middleware) {
|
|
551
|
+
const mw = await ssrModule.runMiddleware(req);
|
|
552
|
+
if (mw) {
|
|
553
|
+
await sendWebResponse(hookCtx ? await ssrModule.runResponseHooks(hookCtx, mw) : mw, res);
|
|
554
|
+
return;
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
// API routes (pages/api/*.rose) dispatch FIRST: the /api namespace answers JSON,
|
|
558
|
+
// never the static shell or an HTML page …
|
|
559
|
+
const apiPath = pathnameOf(req.url);
|
|
560
|
+
if (ssrModule.isApi(apiPath)) {
|
|
561
|
+
readBody(req, res, async (body) => {
|
|
562
|
+
try {
|
|
563
|
+
const headers: Record<string, string> = {};
|
|
564
|
+
for (const [k, v] of Object.entries(req.headers)) {
|
|
565
|
+
if (v !== undefined) headers[k] = Array.isArray(v) ? v.join(', ') : String(v);
|
|
566
|
+
}
|
|
567
|
+
const request = new Request(`http://${req.headers.host || 'localhost'}${req.url}`, {
|
|
568
|
+
method: req.method || 'GET',
|
|
569
|
+
headers,
|
|
570
|
+
body: body.length > 0 ? body : undefined,
|
|
571
|
+
});
|
|
572
|
+
let apiRes = await ssrModule.handleApi(req.method || 'GET', apiPath, request);
|
|
573
|
+
if (hookCtx) apiRes = await ssrModule.runResponseHooks(hookCtx, apiRes);
|
|
574
|
+
writeWebHeaders(apiRes, res);
|
|
575
|
+
res.statusCode = apiRes.status;
|
|
576
|
+
res.end(Buffer.from(await apiRes.arrayBuffer()));
|
|
577
|
+
} catch {
|
|
578
|
+
res.statusCode = 500;
|
|
579
|
+
res.setHeader('Content-Type', 'application/json');
|
|
580
|
+
res.end('{"error":"api handler failed"}');
|
|
581
|
+
}
|
|
582
|
+
});
|
|
583
|
+
return;
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
// POST: run the matched route's server action (progressive-enhancement form). This
|
|
587
|
+
// must precede the static lookup: prerendered files exist on disk and would otherwise …
|
|
588
|
+
if (req.method === 'POST') {
|
|
589
|
+
readBody(req, res, async (body) => {
|
|
590
|
+
try {
|
|
591
|
+
const form = await new Response(body, {
|
|
592
|
+
headers: { 'content-type': req.headers['content-type'] || 'application/x-www-form-urlencoded' },
|
|
593
|
+
}).formData();
|
|
594
|
+
// the middleware pass for page POSTs: it rides with the parsed FormData so it
|
|
595
|
+
// can read form fields, and its context seeds the action + render below
|
|
596
|
+
if (ssrModule.middleware) {
|
|
597
|
+
const mw = await ssrModule.runMiddleware(req, form);
|
|
598
|
+
if (mw) {
|
|
599
|
+
await sendWebResponse(hookCtx ? await ssrModule.runResponseHooks(hookCtx, mw) : mw, res);
|
|
600
|
+
return;
|
|
601
|
+
}
|
|
602
|
+
}
|
|
603
|
+
const page = await ssrModule.renderPage(req.url || '/', form);
|
|
604
|
+
await sendPage(req, res, ssrModule, hookCtx, page, pathnameOf(req.url || '/'));
|
|
605
|
+
} catch {
|
|
606
|
+
res.statusCode = 400;
|
|
607
|
+
res.end('Bad request');
|
|
608
|
+
}
|
|
609
|
+
});
|
|
610
|
+
return;
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
let safe = path.normalize(req.url || '/').replace(/^(\.\.(\/)?)+/, '');
|
|
614
|
+
if (safe === '\\' || safe === '/') safe = '/';
|
|
615
|
+
let filePath = path.join(dir, safe);
|
|
616
|
+
// A file in public/ answers at the root too: pages link /logo.svg, not
|
|
617
|
+
// /public/logo.svg, and the build keeps the bytes under public/.
|
|
618
|
+
if (!fs.existsSync(filePath) && ASSET_EXT.has(path.extname(safe).toLowerCase())) {
|
|
619
|
+
const pubFile = path.join(dir, 'public', safe);
|
|
620
|
+
if (fs.existsSync(pubFile)) filePath = pubFile;
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
// Directory -> index.html (prerendered routes live at /<route>/index.html)
|
|
624
|
+
if (fs.existsSync(filePath) && fs.statSync(filePath).isDirectory()) {
|
|
625
|
+
filePath = path.join(filePath, 'index.html');
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
// Build-time precompression siblings (dist/<file>.br, read by the Go binary) are internal
|
|
629
|
+
// artifacts.
|
|
630
|
+
if (/\.(?:br|gz)$/i.test(safe)) {
|
|
631
|
+
const base = filePath.replace(/\.(?:br|gz)$/i, '');
|
|
632
|
+
if (fs.existsSync(base)) filePath = base;
|
|
633
|
+
}
|
|
634
|
+
|
|
635
|
+
// Serve real files directly - compressed + conditionally cached, so a repeat visit
|
|
636
|
+
// costs a 304 instead of the full document. Assets always take this path.
|
|
637
|
+
const isAsset = ASSET_EXT.has(path.extname(safe).toLowerCase());
|
|
638
|
+
const isDynamic = !isAsset && (ssrModule.dynamicRoutes as string[] | undefined)?.includes(pathnameOf(req.url));
|
|
639
|
+
if (!isDynamic && fs.existsSync(filePath) && fs.statSync(filePath).isFile()) {
|
|
640
|
+
const st = fs.statSync(filePath);
|
|
641
|
+
// ISR: a route exporting `revalidate = N` keeps its baked file for N seconds. Once stale,
|
|
642
|
+
// THIS request is still served from disk - stale-while-revalidate: instant TTFB …
|
|
643
|
+
const rev = isAsset ? undefined : ((ssrModule.revalidate as { pattern: string; seconds: number }[]) || [])
|
|
644
|
+
.find((r) => ssrModule.matchRoute(r.pattern, pathnameOf(req.url)));
|
|
645
|
+
if (isr && rev && Date.now() - st.mtimeMs > rev.seconds * 1000) {
|
|
646
|
+
revalidateInBackground(pathnameOf(req.url), filePath);
|
|
647
|
+
}
|
|
648
|
+
let entry = fileCache.get(filePath);
|
|
649
|
+
if (!entry || entry.mtimeMs !== st.mtimeMs) {
|
|
650
|
+
const raw = fs.readFileSync(filePath);
|
|
651
|
+
entry = {
|
|
652
|
+
mtimeMs: st.mtimeMs,
|
|
653
|
+
raw,
|
|
654
|
+
// A file's compressed forms are computed ONCE and then served from this cache
|
|
655
|
+
// forever …
|
|
656
|
+
br: zlib.brotliCompressSync(raw),
|
|
657
|
+
gzip: zlib.gzipSync(raw, { level: 9 }),
|
|
658
|
+
etag: `W/"${st.size}-${st.mtimeMs}"`,
|
|
659
|
+
};
|
|
660
|
+
fileCache.set(filePath, entry);
|
|
661
|
+
}
|
|
662
|
+
const ext = path.extname(filePath);
|
|
663
|
+
const types: Record<string, string> = {
|
|
664
|
+
'.html': 'text/html',
|
|
665
|
+
'.js': 'application/javascript',
|
|
666
|
+
'.css': 'text/css',
|
|
667
|
+
'.json': 'application/json',
|
|
668
|
+
'.png': 'image/png',
|
|
669
|
+
'.svg': 'image/svg+xml',
|
|
670
|
+
'.ico': 'image/x-icon',
|
|
671
|
+
'.woff2': 'font/woff2',
|
|
672
|
+
'.mp4': 'video/mp4',
|
|
673
|
+
'.mp3': 'audio/mpeg',
|
|
674
|
+
};
|
|
675
|
+
// An ISR route's file is swapped every `revalidate` seconds, so the cache must not
|
|
676
|
+
// outlive the window: revalidate every visit (a bodiless 304 when nothing changed) …
|
|
677
|
+
const fileHeaders: Record<string, string> = {
|
|
678
|
+
'Content-Type': types[ext] || 'application/octet-stream',
|
|
679
|
+
'Cache-Control': rev ? `public, max-age=0, stale-while-revalidate=${rev.seconds}` : 'public, max-age=3600',
|
|
680
|
+
'ETag': entry.etag,
|
|
681
|
+
'Vary': 'Accept-Encoding',
|
|
682
|
+
};
|
|
683
|
+
// Per-route response headers: a prerendered document carries the same policy the live
|
|
684
|
+
// render would send - the strict CSP plus the route's own exported headers.
|
|
685
|
+
if (ext === '.html') Object.assign(fileHeaders, pageHeaders(ssrModule, pathnameOf(req.url)));
|
|
686
|
+
// OnResponse on the file path too, so a header-adding plugin sees EVERY response and not
|
|
687
|
+
// just the rendered ones.
|
|
688
|
+
let status = 200;
|
|
689
|
+
if (hookCtx) {
|
|
690
|
+
const out = await ssrModule.runResponseHooks(hookCtx, new Response(null, { status, headers: fileHeaders }));
|
|
691
|
+
status = out.status;
|
|
692
|
+
for (const [k, v] of Object.entries(webHeadersToNode(out))) res.setHeader(k, v);
|
|
693
|
+
} else {
|
|
694
|
+
for (const [k, v] of Object.entries(fileHeaders)) res.setHeader(k, v);
|
|
695
|
+
}
|
|
696
|
+
if (req.headers['if-none-match'] === entry.etag) {
|
|
697
|
+
res.statusCode = 304;
|
|
698
|
+
res.end();
|
|
699
|
+
return;
|
|
700
|
+
}
|
|
701
|
+
const enc = pickEncoding(req);
|
|
702
|
+
res.statusCode = status;
|
|
703
|
+
if (enc) {
|
|
704
|
+
res.setHeader('Content-Encoding', enc);
|
|
705
|
+
res.end(enc === 'br' ? entry.br : enc === 'gzip' ? entry.gzip : compress('deflate', entry.raw));
|
|
706
|
+
} else {
|
|
707
|
+
res.end(entry.raw);
|
|
708
|
+
}
|
|
709
|
+
return;
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
// Otherwise render the route via SSR (dynamic routes, 404s, and every page route when
|
|
713
|
+
// a middleware exists: its per-request context must be live …
|
|
714
|
+
let broken = new Set<string>();
|
|
715
|
+
try {
|
|
716
|
+
broken = new Set(JSON.parse(fs.readFileSync(path.join(dir, 'broken.json'), 'utf-8')));
|
|
717
|
+
} catch { /* no manifest: nothing known-broken */ }
|
|
718
|
+
const safe2 = req.url || '/';
|
|
719
|
+
if (!broken.has(safe2) && ssrModule.canStream(safe2) && !ssrModule.isNoJs(safe2)) {
|
|
720
|
+
const enc = pickEncoding(req);
|
|
721
|
+
// onResponse runs BEFORE the first flush, while the status and headers can still change:
|
|
722
|
+
// the hook is handed a bodyless Response carrying them …
|
|
723
|
+
let status = 200;
|
|
724
|
+
// The nonce is minted before the first flush, because a streamed response cannot change
|
|
725
|
+
// its headers afterwards - and the document's script tag is written into that same stream …
|
|
726
|
+
const nonce = nonceFor(ssrModule, pathnameOf(safe2));
|
|
727
|
+
let headers: Record<string, any> = pageHeaders(ssrModule, pathnameOf(safe2), nonce);
|
|
728
|
+
if (hookCtx) {
|
|
729
|
+
const out = await ssrModule.runResponseHooks(hookCtx, new Response(null, { status, headers }));
|
|
730
|
+
status = out.status;
|
|
731
|
+
headers = webHeadersToNode(out);
|
|
732
|
+
}
|
|
733
|
+
res.statusCode = status;
|
|
734
|
+
res.setHeader('Content-Type', 'text/html; charset=utf-8');
|
|
735
|
+
res.setHeader('Vary', 'Accept-Encoding');
|
|
736
|
+
for (const [k, v] of Object.entries(headers)) res.setHeader(k, v);
|
|
737
|
+
let write: (chunk: string) => void;
|
|
738
|
+
let done: () => void;
|
|
739
|
+
if (enc) {
|
|
740
|
+
res.setHeader('Content-Encoding', enc);
|
|
741
|
+
const compressor = createCompressor(enc);
|
|
742
|
+
compressor.pipe(res);
|
|
743
|
+
// The shell must reach the socket NOW. Without a flush zlib emits nothing until
|
|
744
|
+
// end() …
|
|
745
|
+
let flushed = false;
|
|
746
|
+
write = (chunk) => {
|
|
747
|
+
compressor.write(chunk);
|
|
748
|
+
if (!flushed) {
|
|
749
|
+
flushed = true;
|
|
750
|
+
compressor.flush(zlib.constants.Z_FULL_FLUSH);
|
|
751
|
+
}
|
|
752
|
+
};
|
|
753
|
+
// pipe() forwards data but not errors, and an unhandled 'error' event kills the
|
|
754
|
+
// worker.
|
|
755
|
+
compressor.on('error', () => res.destroy());
|
|
756
|
+
done = () => compressor.end();
|
|
757
|
+
} else {
|
|
758
|
+
write = (chunk) => res.write(chunk);
|
|
759
|
+
done = () => res.end();
|
|
760
|
+
}
|
|
761
|
+
// The streamed shell opens before the render, so its <html
|
|
762
|
+
// lang>/<dir> come from the pathname (the server bundle's docAttrs)
|
|
763
|
+
const doc = ssrModule.docAttrs(safe2);
|
|
764
|
+
await ssrModule.renderPageStream(safe2, write, shellOpen(getStyles(), doc.lang, doc.dir), clientScriptTag(getClientSource(), nonce));
|
|
765
|
+
done();
|
|
766
|
+
return;
|
|
767
|
+
}
|
|
768
|
+
// buffered: POST actions, unmatched routes (404), known-broken routes (500), and csr
|
|
769
|
+
// = false routes …
|
|
770
|
+
const page = await ssrModule.renderPage(safe2);
|
|
771
|
+
await sendPage(req, res, ssrModule, hookCtx, page, pathnameOf(safe2));
|
|
772
|
+
}).catch(() => {
|
|
773
|
+
res.statusCode = 404;
|
|
774
|
+
res.end('Not found');
|
|
775
|
+
});
|
|
776
|
+
};
|
|
777
|
+
}
|
|
778
|
+
|
|
779
|
+
/** Strip the query string: routing matches the pathname, handlers read the full URL. */
|
|
780
|
+
function pathnameOf(url: string | undefined): string {
|
|
781
|
+
try {
|
|
782
|
+
return new URL(url || '/', 'http://localhost').pathname;
|
|
783
|
+
} catch {
|
|
784
|
+
return (url || '/').split('?')[0];
|
|
785
|
+
}
|
|
786
|
+
}
|
|
787
|
+
|
|
788
|
+
/**
|
|
789
|
+
* The version from package.json - one source of truth, no constant to drift.
|
|
790
|
+
* Resolved from THIS module (not the cwd): the banner names the framework's
|
|
791
|
+
* version even when it builds somebody else's project. Two layouts answer:
|
|
792
|
+
* in the repo this module sits at src/cli/, in the published package the CLI
|
|
793
|
+
* is bundled to dist-cli/ with the sources beside it - so try both.
|
|
794
|
+
*/
|
|
795
|
+
function version(): string {
|
|
796
|
+
for (const rel of ['../../package.json', '../package.json']) {
|
|
797
|
+
try {
|
|
798
|
+
const v = JSON.parse(fs.readFileSync(fileURLToPath(new URL(rel, import.meta.url)), 'utf-8')).version;
|
|
799
|
+
if (v) return v;
|
|
800
|
+
} catch { /* not this layout */ }
|
|
801
|
+
}
|
|
802
|
+
return '0.0.0';
|
|
803
|
+
}
|
|
804
|
+
|
|
805
|
+
async function dev(): Promise<void> {
|
|
806
|
+
console.log(`🌹 RoseTack v${version()} dev server starting...`);
|
|
807
|
+
try {
|
|
808
|
+
await build();
|
|
809
|
+
} catch (err) {
|
|
810
|
+
// A broken .rose file must not prevent the server from starting; the
|
|
811
|
+
// watcher below rebuilds as soon as the file is fixed.
|
|
812
|
+
console.error('Initial build failed (server still running):', err instanceof Error ? err.message : err);
|
|
813
|
+
}
|
|
814
|
+
|
|
815
|
+
let timeout: any;
|
|
816
|
+
fs.watch(SRC_DIR, { recursive: true }, () => {
|
|
817
|
+
clearTimeout(timeout);
|
|
818
|
+
timeout = setTimeout(async () => {
|
|
819
|
+
try {
|
|
820
|
+
console.log('Rebuilding...');
|
|
821
|
+
await build();
|
|
822
|
+
} catch (err) {
|
|
823
|
+
// Never let a user-code error kill the dev server.
|
|
824
|
+
console.error('Build failed (server still running):', err instanceof Error ? err.message : err);
|
|
825
|
+
}
|
|
826
|
+
}, 200);
|
|
827
|
+
});
|
|
828
|
+
|
|
829
|
+
const http = await import('http');
|
|
830
|
+
const server = http.createServer(serveStatic(OUT_DIR));
|
|
831
|
+
|
|
832
|
+
server.listen(PORT, () => {
|
|
833
|
+
console.log('🌹 http://localhost:' + PORT);
|
|
834
|
+
});
|
|
835
|
+
}
|
|
836
|
+
|
|
837
|
+
async function preview(): Promise<void> {
|
|
838
|
+
await build();
|
|
839
|
+
const http = await import('http');
|
|
840
|
+
// isr=true: routes exporting `revalidate = N` are served stale-then-swapped
|
|
841
|
+
// from disk . Dev passes nothing (it rebuilds on change).
|
|
842
|
+
const server = http.createServer(serveStatic(OUT_DIR, true));
|
|
843
|
+
|
|
844
|
+
server.listen(PORT, () => {
|
|
845
|
+
console.log(`🌹 RoseTack v${version()} preview at http://localhost:` + PORT);
|
|
846
|
+
});
|
|
847
|
+
}
|
|
848
|
+
|
|
849
|
+
/**
|
|
850
|
+
* `rosetack serve` runs what `build` produced - no rebuild, no
|
|
851
|
+
* watcher, production semantics (a preview that re-rendered on the fly
|
|
852
|
+
* could serve a half-written file). Multi-core through the stdlib cluster:
|
|
853
|
+
* the primary supervises and serves no traffic, the workers serve; every
|
|
854
|
+
* request is logged; SIGTERM drains in-flight work and exits.
|
|
855
|
+
*
|
|
856
|
+
* Boundaries, stated plainly:
|
|
857
|
+
* - each worker is its own process with its own dist/server.js module.
|
|
858
|
+
* Module-scope state is therefore per-worker, which is what $store()
|
|
859
|
+
* fixes: writes broadcast through the primary, reads stay
|
|
860
|
+
* local-synchronous. ISR revalidation may run in more than one worker
|
|
861
|
+
* for one route: the guard is per-worker and the cost is one duplicate
|
|
862
|
+
* render.
|
|
863
|
+
* - the signal-driven drain is POSIX behavior. On Windows a kill() is
|
|
864
|
+
* abrupt by the platform's design, so the worker instead exits on the
|
|
865
|
+
* primary's death (the disconnect handler below) - a killed primary must
|
|
866
|
+
* never leave orphans holding the port.
|
|
867
|
+
*/
|
|
868
|
+
async function serve(): Promise<void> {
|
|
869
|
+
if (!fs.existsSync(path.join(OUT_DIR, 'server.js'))) {
|
|
870
|
+
console.error(`rosetack: ${OUT_DIR} has no server.js - run rosetack build first`);
|
|
871
|
+
process.exit(1);
|
|
872
|
+
}
|
|
873
|
+
// .default: node:cluster is an `export =` module, so the dynamic import
|
|
874
|
+
// hands back the namespace with the real module on `.default`
|
|
875
|
+
const cluster = (await import('node:cluster')).default as any;
|
|
876
|
+
// Round-robin the accepts between workers. The default leaves the handout to the
|
|
877
|
+
// operating system …
|
|
878
|
+
cluster.schedulingPolicy = cluster.SCHED_RR;
|
|
879
|
+
const os = await import('node:os');
|
|
880
|
+
const workers = Math.max(1, Number(process.env.rosetack_WORKERS) || os.cpus().length);
|
|
881
|
+
const PORT = Number(process.env.PORT) || 3000;
|
|
882
|
+
if (cluster.isPrimary) {
|
|
883
|
+
for (let i = 0; i < workers; i++) cluster.fork();
|
|
884
|
+
// The store relay. A worker broadcasts every $store write here; the primary forwards each
|
|
885
|
+
// patch to every OTHER worker …
|
|
886
|
+
cluster.on('message', (worker: any, msg: any) => {
|
|
887
|
+
if (!msg || msg.type !== 'rosetack:store') return;
|
|
888
|
+
for (const w of Object.values<any>(cluster.workers ?? {})) {
|
|
889
|
+
if (w && w.id !== worker.id) w.send(msg);
|
|
890
|
+
}
|
|
891
|
+
});
|
|
892
|
+
let live = workers;
|
|
893
|
+
const stop = () => {
|
|
894
|
+
for (const w of Object.values<any>(cluster.workers ?? {})) w.kill();
|
|
895
|
+
setTimeout(() => process.exit(0), 5000).unref();
|
|
896
|
+
};
|
|
897
|
+
process.on('SIGTERM', stop);
|
|
898
|
+
process.on('SIGINT', stop);
|
|
899
|
+
cluster.on('exit', () => { if (--live <= 0) process.exit(0); });
|
|
900
|
+
console.log(`🌹 RoseTack v${version()} serve: ${workers} worker${workers > 1 ? 's' : ''} on http://localhost:${PORT} (cluster, bounded bodies, graceful shutdown, access log on stdout)`);
|
|
901
|
+
return;
|
|
902
|
+
}
|
|
903
|
+
// worker the primary's death is the worker's death: no orphan holding the port
|
|
904
|
+
process.on('disconnect', () => process.exit(0));
|
|
905
|
+
// OnServe / onShutdown - the worker's lifecycle. A plugin that owns a resource (a
|
|
906
|
+
// connection pool, a warm cache) opens it here and closes it in the drain …
|
|
907
|
+
let servicePlugins: any[] = [];
|
|
908
|
+
try {
|
|
909
|
+
servicePlugins = (await loadPlugins(SRC_DIR)).filter((p) => p && p.onServe);
|
|
910
|
+
} catch (err) {
|
|
911
|
+
console.error('rosetack: rosetack.config.js failed to load for the serve hooks:', err instanceof Error ? err.message : err);
|
|
912
|
+
}
|
|
913
|
+
const http = await import('node:http');
|
|
914
|
+
const server = http.createServer(withAccessLog(serveStatic(OUT_DIR, true), `w${process.pid}`));
|
|
915
|
+
// A client that stalls mid-request is dropped instead of holding a worker;
|
|
916
|
+
// idle keep-alive sockets close so a drained worker can actually exit.
|
|
917
|
+
server.requestTimeout = 30_000;
|
|
918
|
+
server.headersTimeout = 65_000; // must exceed requestTimeout
|
|
919
|
+
server.keepAliveTimeout = 5_000;
|
|
920
|
+
server.listen(PORT, async () => {
|
|
921
|
+
console.log(`🌹 RoseTack worker ${process.pid} listening on http://localhost:${PORT}`);
|
|
922
|
+
for (const p of servicePlugins) {
|
|
923
|
+
try {
|
|
924
|
+
await p.onServe({ port: PORT, workers });
|
|
925
|
+
} catch (err) {
|
|
926
|
+
console.error('rosetack: plugin', p.name, 'onServe failed:', err instanceof Error ? err.message : err);
|
|
927
|
+
}
|
|
928
|
+
}
|
|
929
|
+
});
|
|
930
|
+
const stop = () => {
|
|
931
|
+
// onShutdown first: close what onServe opened, then drain. A throwing
|
|
932
|
+
// hook must not stop the drain - the process still exits on the timer.
|
|
933
|
+
for (const p of servicePlugins) {
|
|
934
|
+
if (!p.onShutdown) continue;
|
|
935
|
+
try {
|
|
936
|
+
void Promise.resolve(p.onShutdown()).catch((err: unknown) => {
|
|
937
|
+
console.error('rosetack: plugin', p.name, 'onShutdown failed:', err instanceof Error ? err.message : err);
|
|
938
|
+
});
|
|
939
|
+
} catch (err) {
|
|
940
|
+
console.error('rosetack: plugin', p.name, 'onShutdown failed:', err instanceof Error ? err.message : err);
|
|
941
|
+
}
|
|
942
|
+
}
|
|
943
|
+
server.close(() => process.exit(0)); // finish what is in flight
|
|
944
|
+
server.closeIdleConnections?.(); // drop the idle keep-alive sockets
|
|
945
|
+
setTimeout(() => process.exit(0), 5000).unref(); // a stuck one must not hold the worker
|
|
946
|
+
};
|
|
947
|
+
process.on('SIGTERM', stop);
|
|
948
|
+
process.on('SIGINT', stop);
|
|
949
|
+
}
|
|
950
|
+
|
|
951
|
+
/**
|
|
952
|
+
* `rosetack new <name>` - a starting project. The smallest thing that builds
|
|
953
|
+
* and runs and shows the syntax: one page (state, {#if}, {#each}, a scoped
|
|
954
|
+
* style), one README naming the three commands. Not a second demo app - the
|
|
955
|
+
* point is that a new developer's first `rosetack build` works in seconds.
|
|
956
|
+
*
|
|
957
|
+
* Trade-off: three files, written from strings. No template engine, no
|
|
958
|
+
* dependency, no `npm install` run on the developer's behalf (they may use
|
|
959
|
+
* pnpm/yarn/bun, and a surprise install is worse than a printed command).
|
|
960
|
+
*/
|
|
961
|
+
async function scaffold(): Promise<void> {
|
|
962
|
+
const name = process.argv[3];
|
|
963
|
+
if (!name || name.startsWith('-')) {
|
|
964
|
+
console.log('Usage: rosetack new <name> (creates <name>/ with a page that builds)');
|
|
965
|
+
return;
|
|
966
|
+
}
|
|
967
|
+
const dir = path.resolve(name);
|
|
968
|
+
if (fs.existsSync(dir)) {
|
|
969
|
+
console.error(`rosetack: ${dir} already exists - pick another name`);
|
|
970
|
+
process.exit(1);
|
|
971
|
+
}
|
|
972
|
+
const pages = path.join(dir, 'src', 'pages');
|
|
973
|
+
fs.mkdirSync(pages, { recursive: true });
|
|
974
|
+
|
|
975
|
+
fs.writeFileSync(path.join(dir, 'package.json'), JSON.stringify({
|
|
976
|
+
name: path.basename(dir),
|
|
977
|
+
private: true,
|
|
978
|
+
type: 'module',
|
|
979
|
+
scripts: {
|
|
980
|
+
dev: 'rosetack dev',
|
|
981
|
+
build: 'rosetack build',
|
|
982
|
+
preview: 'rosetack preview',
|
|
983
|
+
serve: 'rosetack serve',
|
|
984
|
+
check: 'rosetack check',
|
|
985
|
+
},
|
|
986
|
+
dependencies: { rosetack: `^${version()}` },
|
|
987
|
+
// TypeScript is a first-class citizen: .rose scripts are typed, and `npm run check`
|
|
988
|
+
// type-checks every one of them with THIS project's TypeScript …
|
|
989
|
+
devDependencies: { typescript: '^5.6.0' },
|
|
990
|
+
}, null, 2) + '\n');
|
|
991
|
+
|
|
992
|
+
// The ambient globals a .rose script can call ($state, $data, $t, ...),
|
|
993
|
+
// pulled in from the installed package: editors and tsc both see them.
|
|
994
|
+
fs.writeFileSync(path.join(dir, 'rosetack-env.d.ts'), `/// <reference types="rosetack" />\n`);
|
|
995
|
+
fs.writeFileSync(path.join(dir, 'tsconfig.json'), JSON.stringify({
|
|
996
|
+
compilerOptions: {
|
|
997
|
+
target: 'ES2022',
|
|
998
|
+
module: 'ESNext',
|
|
999
|
+
moduleResolution: 'bundler',
|
|
1000
|
+
lib: ['ES2022', 'DOM', 'DOM.Iterable'],
|
|
1001
|
+
strict: true,
|
|
1002
|
+
noEmit: true,
|
|
1003
|
+
skipLibCheck: true,
|
|
1004
|
+
},
|
|
1005
|
+
// the env file first (it is what makes the globals visible), then any
|
|
1006
|
+
// .ts the project grows - .rose scripts are checked by `npm run check`
|
|
1007
|
+
include: ['rosetack-env.d.ts', 'src/**/*.ts'],
|
|
1008
|
+
}, null, 2) + '\n');
|
|
1009
|
+
|
|
1010
|
+
fs.writeFileSync(path.join(pages, 'index.rose'), `<script>
|
|
1011
|
+
// One file per route: markup, script and styles together.
|
|
1012
|
+
// The script block is TypeScript - interfaces, annotations, generics and
|
|
1013
|
+
// casts all compile, and \`npm run check\` type-checks them.
|
|
1014
|
+
interface Item { label: string }
|
|
1015
|
+
|
|
1016
|
+
let count = $state(0);
|
|
1017
|
+
let items = $state<string[]>(['zero hydration', 'one request', 'no build config']);
|
|
1018
|
+
let showList = $state(true);
|
|
1019
|
+
|
|
1020
|
+
function increment() { $setState('count', count() + 1); }
|
|
1021
|
+
function toggleList() { $setState('showList', !showList()); }
|
|
1022
|
+
// typed server data: the body runs per request on the server (and ships
|
|
1023
|
+
// to the client, where it re-runs on a client-side navigation)
|
|
1024
|
+
let first: Item = $data((): Item => ({ label: items()[0] ?? 'nothing yet' }));
|
|
1025
|
+
</script>
|
|
1026
|
+
|
|
1027
|
+
<h1>🌹 RoseTack</h1>
|
|
1028
|
+
<p>Count: <strong>{count()}</strong> - first item: {first().label}</p>
|
|
1029
|
+
<button on:click={increment}>Increment</button>
|
|
1030
|
+
<button on:click={toggleList}>{showList() ? 'Hide' : 'Show'} the list</button>
|
|
1031
|
+
|
|
1032
|
+
{#if showList()}
|
|
1033
|
+
<ul>
|
|
1034
|
+
{#each items() as item}
|
|
1035
|
+
<li>{item}</li>
|
|
1036
|
+
{/each}
|
|
1037
|
+
</ul>
|
|
1038
|
+
{/if}
|
|
1039
|
+
|
|
1040
|
+
<style>
|
|
1041
|
+
body { font-family: system-ui, sans-serif; margin: 2rem; }
|
|
1042
|
+
button { padding: 0.5rem 1rem; margin-right: 0.5rem; }
|
|
1043
|
+
</style>
|
|
1044
|
+
`);
|
|
1045
|
+
|
|
1046
|
+
fs.writeFileSync(path.join(dir, 'README.md'), `# ${path.basename(dir)}
|
|
1047
|
+
|
|
1048
|
+
A rosetack project. One file per route in \`src/pages/\`.
|
|
1049
|
+
|
|
1050
|
+
\`\`\`bash
|
|
1051
|
+
npm install # pulls the rosetack package (and typescript, for checking)
|
|
1052
|
+
npm run dev # dev server with hot rebuild: http://localhost:3000
|
|
1053
|
+
npm run build # compiles to dist/
|
|
1054
|
+
npm run serve # production runner (cluster, access log, graceful shutdown)
|
|
1055
|
+
npm run check # type-checks every .rose script
|
|
1056
|
+
\`\`\`
|
|
1057
|
+
|
|
1058
|
+
Add a route by adding a file: \`src/pages/about.rose\` serves \`/about\`.
|
|
1059
|
+
\`src/pages/_layout.rose\` wraps every route, \`src/pages/_middleware.rose\`
|
|
1060
|
+
runs before every request, \`src/pages/api/*.rose\` answers JSON.
|
|
1061
|
+
Full syntax: the README of the rosetack package.
|
|
1062
|
+
`);
|
|
1063
|
+
|
|
1064
|
+
fs.writeFileSync(path.join(dir, '.gitignore'), 'node_modules/\ndist/\n');
|
|
1065
|
+
|
|
1066
|
+
console.log(`🌹 Created ${dir}`);
|
|
1067
|
+
console.log(` src/pages/index.rose - a typed page that builds and runs`);
|
|
1068
|
+
console.log(` rosetack-env.d.ts + tsconfig.json - the script globals, typed`);
|
|
1069
|
+
console.log(`\n cd ${name}`);
|
|
1070
|
+
console.log(` npm install && npm run dev`);
|
|
1071
|
+
console.log(` npm run check # type-checks every .rose script`);
|
|
1072
|
+
}
|
|
1073
|
+
|
|
1074
|
+
/**
|
|
1075
|
+
* `rosetack check [dir]` - type-check every .rose script with the
|
|
1076
|
+
* PROJECT's own TypeScript.
|
|
1077
|
+
*
|
|
1078
|
+
* esbuild strips types without checking them, so a wrong argument type or a
|
|
1079
|
+
* typo in an interface is invisible at build time: the build succeeds and the
|
|
1080
|
+
* bug ships. This closes that hole - it extracts the exact block the compiler
|
|
1081
|
+
* embeds (scriptOf, one regex, one truth), pads it so line and column numbers
|
|
1082
|
+
* still point at the .rose file, and runs the project's TypeScript over all
|
|
1083
|
+
* of them in one program, with rosetack's own globals in scope.
|
|
1084
|
+
*
|
|
1085
|
+
* No TypeScript in the project is a hard error: a check that cannot run must
|
|
1086
|
+
* never pass silently. trade-off: no temp files, no tsconfig parsing - an
|
|
1087
|
+
* in-memory compiler host and fixed strict options, documented.
|
|
1088
|
+
*/
|
|
1089
|
+
async function check(): Promise<void> {
|
|
1090
|
+
const files = [...(await scanRoseFiles(SRC_DIR)), ...(await scanComponentFiles(SRC_DIR))];
|
|
1091
|
+
if (files.length === 0) {
|
|
1092
|
+
console.error(`rosetack: no .rose pages found under ${path.join(SRC_DIR, 'src', 'pages')} - run rosetack check from a project root, or pass one: rosetack check <dir>`);
|
|
1093
|
+
process.exit(1);
|
|
1094
|
+
}
|
|
1095
|
+
|
|
1096
|
+
// The project's typescript, resolved FROM the project: the framework must not drag its
|
|
1097
|
+
// own copy into a user's install …
|
|
1098
|
+
let tsMod: typeof ts;
|
|
1099
|
+
try {
|
|
1100
|
+
const req = createRequire(pathToFileURL(path.join(SRC_DIR, 'package.json')));
|
|
1101
|
+
tsMod = await import(pathToFileURL(req.resolve('typescript')).href) as typeof ts;
|
|
1102
|
+
} catch {
|
|
1103
|
+
console.error(`rosetack: type checking needs typescript in this project - npm i -D typescript`);
|
|
1104
|
+
process.exit(1);
|
|
1105
|
+
}
|
|
1106
|
+
|
|
1107
|
+
// rosetack's ambient globals, resolved from the COMPILER's own location:
|
|
1108
|
+
// src/types/rosetack.d.ts is a sibling in the repo and two levels down in
|
|
1109
|
+
// the published package (same two layouts as the runtime entry).
|
|
1110
|
+
const nextTo = (rel: string[]) => rel.map((r) => fileURLToPath(new URL(r, import.meta.url))).find((p) => fs.existsSync(p));
|
|
1111
|
+
const typesFile = nextTo(['../types/rosetack.d.ts', '../src/types/rosetack.d.ts']);
|
|
1112
|
+
if (!typesFile) {
|
|
1113
|
+
console.error('rosetack: the type definitions (src/types/rosetack.d.ts) were not found next to the compiler');
|
|
1114
|
+
process.exit(1);
|
|
1115
|
+
}
|
|
1116
|
+
// The runtime source, for scripts that import helpers from './runtime.js' (the module the
|
|
1117
|
+
// compiler generates beside the intermediates).
|
|
1118
|
+
const runtimeSource = nextTo(['../runtime/index.ts', '../src/runtime/index.ts']);
|
|
1119
|
+
|
|
1120
|
+
// Each script becomes a virtual file NAMED after its .rose file, padded so a diagnostic's
|
|
1121
|
+
// line/column are the .rose file's own: the <script> tag sits on line L …
|
|
1122
|
+
const norm = (f: string) => path.resolve(f).replace(/\\/g, '/');
|
|
1123
|
+
const virtual = new Map<string, string>();
|
|
1124
|
+
let checked = 0;
|
|
1125
|
+
for (const file of files) {
|
|
1126
|
+
const source = await fs.promises.readFile(file, 'utf-8');
|
|
1127
|
+
const m = /<script>/.exec(source);
|
|
1128
|
+
const script = scriptOf(source);
|
|
1129
|
+
if (!script) continue; // a pure-markup component has nothing to check
|
|
1130
|
+
const tagLine = source.slice(0, m!.index + '<script>'.length).split('\n').length;
|
|
1131
|
+
const wired = runtimeSource
|
|
1132
|
+
? script.replace(/['"]\.\/runtime\.js['"]/g, JSON.stringify(runtimeSource.replace(/\\/g, '/')))
|
|
1133
|
+
: script;
|
|
1134
|
+
virtual.set(norm(file), '\n'.repeat(tagLine - 1) + wired);
|
|
1135
|
+
checked++;
|
|
1136
|
+
}
|
|
1137
|
+
if (checked === 0) {
|
|
1138
|
+
console.log('rosetack: no .rose scripts to check');
|
|
1139
|
+
return;
|
|
1140
|
+
}
|
|
1141
|
+
|
|
1142
|
+
// An imported component's binding IS its render function (the compiler rewrites `import
|
|
1143
|
+
// Card from '...Card.rose'` to `import { render as Card }`) …
|
|
1144
|
+
const propType = (def: string | null): string => {
|
|
1145
|
+
if (!def) return 'unknown'; // `export let x;`
|
|
1146
|
+
if (/^['"`]/.test(def)) return 'string';
|
|
1147
|
+
if (/^-?\d+(\.\d+)?$/.test(def)) return 'number';
|
|
1148
|
+
if (/^(true|false)$/.test(def)) return 'boolean';
|
|
1149
|
+
return 'unknown'; // null, a call, an object: the honest answer
|
|
1150
|
+
};
|
|
1151
|
+
const ROSE_IMPORT_RE = /['"](\.[^'"]+\.rose)['"]/g;
|
|
1152
|
+
const declared = new Set<string>();
|
|
1153
|
+
for (const file of [...virtual.keys()]) {
|
|
1154
|
+
const script = scriptOf(await fs.promises.readFile(file, 'utf-8').catch(() => ''));
|
|
1155
|
+
if (!script) continue;
|
|
1156
|
+
for (const spec of script.matchAll(ROSE_IMPORT_RE)) {
|
|
1157
|
+
const target = norm(path.resolve(path.dirname(file), spec[1]));
|
|
1158
|
+
if (target === file || declared.has(target)) continue;
|
|
1159
|
+
const targetSource = await fs.promises.readFile(target, 'utf-8').catch(() => null);
|
|
1160
|
+
if (targetSource === null) continue; // the build reports a missing import loudly; the checker stays out of its way
|
|
1161
|
+
const props = extractExports(scriptOf(targetSource) ?? '').props;
|
|
1162
|
+
virtual.set(`${target}.d.ts`, [
|
|
1163
|
+
`declare function render(closes: unknown[], children: string, __props: { ${props.map((p) => `${p.name}?: ${propType(p.def)}`).join('; ')} }, __slots?: Record<string, unknown>): string;`,
|
|
1164
|
+
'export default render;',
|
|
1165
|
+
'',
|
|
1166
|
+
].join('\n'));
|
|
1167
|
+
declared.add(target);
|
|
1168
|
+
}
|
|
1169
|
+
}
|
|
1170
|
+
|
|
1171
|
+
const options: ts.CompilerOptions = {
|
|
1172
|
+
noEmit: true,
|
|
1173
|
+
strict: true,
|
|
1174
|
+
target: tsMod.ScriptTarget.ES2022,
|
|
1175
|
+
module: tsMod.ModuleKind.ESNext,
|
|
1176
|
+
moduleResolution: tsMod.ModuleResolutionKind.Bundler,
|
|
1177
|
+
lib: ['lib.es2022.d.ts', 'lib.dom.d.ts', 'lib.dom.iterable.d.ts'],
|
|
1178
|
+
// the virtual files are named after the .rose files (so a diagnostic points at the real
|
|
1179
|
+
// path) …
|
|
1180
|
+
allowNonTsExtensions: true,
|
|
1181
|
+
// the rewired './runtime.js' import points at a real .ts source
|
|
1182
|
+
allowImportingTsExtensions: true,
|
|
1183
|
+
// `types` is deliberately NOT set: the project's own @types packages (@types/node for
|
|
1184
|
+
// node:sqlite, say) load automatically, the way they do for the user's own .ts files.
|
|
1185
|
+
skipLibCheck: true,
|
|
1186
|
+
};
|
|
1187
|
+
const host = tsMod.createCompilerHost(options);
|
|
1188
|
+
// @types discovery starts at the project root, not the process cwd - the
|
|
1189
|
+
// command works from anywhere, like every other rosetack command.
|
|
1190
|
+
host.getCurrentDirectory = () => path.resolve(SRC_DIR);
|
|
1191
|
+
const realRead = host.readFile.bind(host);
|
|
1192
|
+
const realGet = host.getSourceFile.bind(host);
|
|
1193
|
+
host.readFile = (f) => virtual.get(norm(f)) ?? realRead(f);
|
|
1194
|
+
host.fileExists = (f) => virtual.has(norm(f)) || tsMod.sys.fileExists(f);
|
|
1195
|
+
host.getSourceFile = (f, version, onError, shouldCreate) => {
|
|
1196
|
+
const src = virtual.get(norm(f));
|
|
1197
|
+
return src ? tsMod.createSourceFile(f, src, version, true) : realGet(f, version, onError, shouldCreate);
|
|
1198
|
+
};
|
|
1199
|
+
|
|
1200
|
+
// rosetack's ambient globals as a program root: a global .d.ts contributes its
|
|
1201
|
+
// declarations to every file in the program …
|
|
1202
|
+
const program = tsMod.createProgram([...virtual.keys(), typesFile], options, host);
|
|
1203
|
+
// Only the project's own scripts: an error inside @types/node or inside rosetack's
|
|
1204
|
+
// runtime source is not the user's bug …
|
|
1205
|
+
const diagnostics = tsMod.getPreEmitDiagnostics(program)
|
|
1206
|
+
.filter((d) => d.file && virtual.has(norm(d.file.fileName)));
|
|
1207
|
+
if (diagnostics.length === 0) {
|
|
1208
|
+
console.log(`rosetack: ${checked} script${checked === 1 ? '' : 's'} type-checked, no errors`);
|
|
1209
|
+
return;
|
|
1210
|
+
}
|
|
1211
|
+
for (const d of diagnostics) {
|
|
1212
|
+
// paths relative to the project root, the way tsc prints them
|
|
1213
|
+
const at = d.file ? tsMod.getLineAndCharacterOfPosition(d.file, d.start ?? 0) : null;
|
|
1214
|
+
const where = d.file && at
|
|
1215
|
+
? `${path.relative(SRC_DIR, d.file.fileName)}(${at.line + 1},${at.character + 1})`
|
|
1216
|
+
: 'rosetack';
|
|
1217
|
+
const text = tsMod.flattenDiagnosticMessageText(d.messageText, '\n');
|
|
1218
|
+
const kind = d.category === 1 ? 'error' : 'warning';
|
|
1219
|
+
console.error(`${where}: ${kind} TS${d.code}: ${text}`);
|
|
1220
|
+
}
|
|
1221
|
+
const errors = diagnostics.filter((d) => d.category === 1).length;
|
|
1222
|
+
console.error(`rosetack: ${errors} type error${errors === 1 ? '' : 's'} in ${checked} script${checked === 1 ? '' : 's'}`);
|
|
1223
|
+
process.exit(1);
|
|
1224
|
+
}
|
|
1225
|
+
|
|
1226
|
+
const cmd = process.argv[2];
|
|
1227
|
+
if (cmd === 'dev') dev();
|
|
1228
|
+
else if (cmd === 'build') build();
|
|
1229
|
+
else if (cmd === 'preview') preview();
|
|
1230
|
+
else if (cmd === 'serve') serve();
|
|
1231
|
+
else if (cmd === 'new') scaffold();
|
|
1232
|
+
else if (cmd === 'check') check();
|
|
1233
|
+
else console.log('Usage: rosetack dev|build|preview|serve|new|check [dir] (dir defaults to the current directory; dist/ is written there)');
|