rosetack 0.1.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/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 +25 -7
- package/src/FRAMEWORK_VERSION +1 -1
- package/src/cli/edge.ts +58 -23
- package/src/cli/index.ts +521 -65
- package/src/cli/shell.ts +75 -22
- package/src/cli/test.ts +400 -0
- package/src/compiler/index.ts +1277 -191
- package/src/runtime/index.ts +356 -65
- package/src/types/rosetack.d.ts +142 -0
- package/.github/workflows/ci.yml +0 -72
- package/.github/workflows/release.yml +0 -122
- package/benchmark.ts +0 -227
- package/example/public/favicon.ico +0 -0
- package/example/public/logo.svg +0 -148
- package/example/public/rose-mark-black.png +0 -0
- package/example/public/rose-mark.png +0 -0
- package/example/public/rose-mono.png +0 -0
- package/example/rosetack.config.js +0 -10
- package/example/src/locales/en.json +0 -8
- package/example/src/locales/zh.json +0 -8
- package/example/src/pages/404.rose +0 -15
- package/example/src/pages/500.rose +0 -10
- package/example/src/pages/[lang]/about.rose +0 -40
- package/example/src/pages/_layout.rose +0 -33
- package/example/src/pages/_middleware.rose +0 -37
- package/example/src/pages/about.rose +0 -67
- package/example/src/pages/admin.rose +0 -27
- package/example/src/pages/api/hello.rose +0 -19
- package/example/src/pages/api/login.rose +0 -55
- package/example/src/pages/api/posts.rose +0 -80
- package/example/src/pages/api/secret.rose +0 -14
- package/example/src/pages/blog/[id].rose +0 -25
- package/example/src/pages/broken.rose +0 -16
- package/example/src/pages/fresh.rose +0 -22
- package/example/src/pages/garden.rose +0 -27
- package/example/src/pages/index.rose +0 -84
- package/example/src/pages/sign.rose +0 -45
- package/example/src/pages/thorn.rose +0 -23
- package/example/src/pages/vault.rose +0 -14
- package/go.mod +0 -3
- package/main.go +0 -470
- package/tools/release-notes.mjs +0 -113
- package/tsconfig.json +0 -17
package/src/cli/index.ts
CHANGED
|
@@ -5,9 +5,13 @@
|
|
|
5
5
|
import * as fs from 'fs';
|
|
6
6
|
import * as path from 'path';
|
|
7
7
|
import * as zlib from 'zlib';
|
|
8
|
+
import { createRequire } from 'module';
|
|
8
9
|
import { pathToFileURL, fileURLToPath } from 'url';
|
|
9
|
-
import { buildProject, type RouteInfo } from '../compiler/index.js';
|
|
10
|
-
import { getHtmlShell, getClientSource, shellOpen, clientScriptTag, securityHeaders, setBundleMode } from './shell.js';
|
|
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';
|
|
11
15
|
|
|
12
16
|
// --- wire performance: compression + conditional caching (stdlib only) --- The Go binary
|
|
13
17
|
// already compresses …
|
|
@@ -15,7 +19,7 @@ type Encoding = 'br' | 'gzip' | 'deflate';
|
|
|
15
19
|
|
|
16
20
|
function pickEncoding(req: any): Encoding | null {
|
|
17
21
|
const ae: string = req.headers['accept-encoding'] || '';
|
|
18
|
-
//
|
|
22
|
+
// Trade-off: substring match, no q-value parsing - every browser that sends
|
|
19
23
|
// br also accepts gzip, and br > gzip > deflate is the quality order.
|
|
20
24
|
if (ae.includes('br')) return 'br';
|
|
21
25
|
if (ae.includes('gzip')) return 'gzip';
|
|
@@ -23,14 +27,18 @@ function pickEncoding(req: any): Encoding | null {
|
|
|
23
27
|
return null;
|
|
24
28
|
}
|
|
25
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
|
+
|
|
26
34
|
function compress(enc: Encoding, data: string | Buffer): Buffer {
|
|
27
|
-
if (enc === 'br') return zlib.brotliCompressSync(data);
|
|
35
|
+
if (enc === 'br') return zlib.brotliCompressSync(data, { params: brotliFast });
|
|
28
36
|
if (enc === 'gzip') return zlib.gzipSync(data);
|
|
29
37
|
return zlib.deflateSync(data);
|
|
30
38
|
}
|
|
31
39
|
|
|
32
40
|
function createCompressor(enc: Encoding): zlib.Gzip | zlib.Deflate | zlib.BrotliCompress {
|
|
33
|
-
if (enc === 'br') return zlib.createBrotliCompress();
|
|
41
|
+
if (enc === 'br') return zlib.createBrotliCompress({ params: brotliFast });
|
|
34
42
|
if (enc === 'gzip') return zlib.createGzip();
|
|
35
43
|
return zlib.createDeflate();
|
|
36
44
|
}
|
|
@@ -83,13 +91,40 @@ async function sendWebResponse(web: any, res: any): Promise<void> {
|
|
|
83
91
|
res.end(Buffer.from(await web.arrayBuffer()));
|
|
84
92
|
}
|
|
85
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
|
+
|
|
86
119
|
// Static files: raw + both compressed forms cached per mtime (dev rebuilds change mtime;
|
|
87
120
|
// preview never does).
|
|
88
121
|
const fileCache = new Map<string, { mtimeMs: number; raw: Buffer; br: Buffer; gzip: Buffer; etag: string }>();
|
|
89
122
|
|
|
90
|
-
//
|
|
91
|
-
//
|
|
123
|
+
// (the "the framework is real" gate): the CLI builds ANY project, not just this repo's
|
|
124
|
+
// demo.
|
|
92
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 …
|
|
93
128
|
const OUT_DIR = path.join(process.cwd(), 'dist');
|
|
94
129
|
// PORT env override (default 3000): lets a preview server run beside a dev
|
|
95
130
|
// server on the same machine - the e2e ISR test does exactly that.
|
|
@@ -120,7 +155,7 @@ async function loadServer(): Promise<any> {
|
|
|
120
155
|
}
|
|
121
156
|
|
|
122
157
|
async function build(): Promise<void> {
|
|
123
|
-
|
|
158
|
+
// The build reports the bundle mode ('inline' | 'split') so the
|
|
124
159
|
// shell follows it for every document, header and streaming tag it emits
|
|
125
160
|
const { routes, bundle } = await buildProject(SRC_DIR, OUT_DIR);
|
|
126
161
|
// The previous build's prerendered output must not survive: a route that stopped being
|
|
@@ -133,20 +168,20 @@ async function build(): Promise<void> {
|
|
|
133
168
|
// routes, so their real 500 status survives (a flushed response cannot change its
|
|
134
169
|
// status).
|
|
135
170
|
await fs.promises.writeFile(path.join(OUT_DIR, 'broken.json'), JSON.stringify(skipped));
|
|
136
|
-
|
|
137
|
-
|
|
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.
|
|
138
173
|
const ssrModule = await loadServer();
|
|
139
174
|
await fs.promises.writeFile(path.join(OUT_DIR, 'headers.json'), JSON.stringify({
|
|
140
175
|
default: securityHeaders(getClientSource()),
|
|
141
176
|
routes: ssrModule.routeHeaders ?? [],
|
|
142
177
|
}));
|
|
143
|
-
|
|
144
|
-
|
|
178
|
+
// Precompressed brotli siblings (dist/<file>.br) for the Go single binary. The binary
|
|
179
|
+
// embeds dist/ verbatim …
|
|
145
180
|
await writeBrotli(OUT_DIR);
|
|
146
181
|
}
|
|
147
182
|
|
|
148
183
|
/**
|
|
149
|
-
* Write dist/<file>.br next to every compressible text file.
|
|
184
|
+
* Write dist/<file>.br next to every compressible text file. trade-off:
|
|
150
185
|
* extension allowlist + zlib's default quality - a 30 KB document
|
|
151
186
|
* compresses in ~10 ms at build time, once, forever.
|
|
152
187
|
*/
|
|
@@ -168,16 +203,19 @@ async function writeBrotli(dir: string): Promise<void> {
|
|
|
168
203
|
* baked API bodies, with their brotli siblings. Everything else in dist/
|
|
169
204
|
* (the bundles, styles) was just rewritten by buildProject.
|
|
170
205
|
*
|
|
171
|
-
*
|
|
206
|
+
* Trade-off: Windows hands out transient EPERM/EBUSY when an antivirus or
|
|
172
207
|
* the search indexer holds a just-written file, so a couple of retries
|
|
173
208
|
* per file - a build that fails because a scanner blinked is the worst
|
|
174
209
|
* kind of flake.
|
|
175
210
|
*/
|
|
176
|
-
async function clearPrerendered(dir: string): Promise<void> {
|
|
211
|
+
async function clearPrerendered(dir: string, depth = 0): Promise<void> {
|
|
177
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;
|
|
178
216
|
const p = path.join(dir, e.name);
|
|
179
217
|
if (e.isDirectory()) {
|
|
180
|
-
await clearPrerendered(p);
|
|
218
|
+
await clearPrerendered(p, depth + 1);
|
|
181
219
|
continue;
|
|
182
220
|
}
|
|
183
221
|
if (!/\.(?:html|json)(?:\.br)?$/.test(e.name)) continue;
|
|
@@ -200,7 +238,7 @@ async function clearPrerendered(dir: string): Promise<void> {
|
|
|
200
238
|
* enumerated and prerendered per value; params without `params` keep
|
|
201
239
|
* rendering on demand. A route exporting `revalidate = N` is baked like
|
|
202
240
|
* any other and then kept fresh by the preview server's stale-while-
|
|
203
|
-
* revalidate pass (ISR
|
|
241
|
+
* revalidate pass (ISR).
|
|
204
242
|
*/
|
|
205
243
|
async function prerender(routes: RouteInfo[]): Promise<string[]> {
|
|
206
244
|
const ssrModule = await loadServer();
|
|
@@ -224,9 +262,9 @@ async function prerender(routes: RouteInfo[]): Promise<string[]> {
|
|
|
224
262
|
}
|
|
225
263
|
const routeDir = routePath === '/' ? OUT_DIR : path.join(OUT_DIR, routePath.slice(1));
|
|
226
264
|
await fs.promises.mkdir(routeDir, { recursive: true });
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
await fs.promises.writeFile(path.join(routeDir, 'index.html'), getHtmlShell(page.html, page.state, page.head, page.csr !== false));
|
|
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));
|
|
230
268
|
console.log(`prerendered ${routePath} -> ${path.relative(process.cwd(), path.join(routeDir, 'index.html'))}`);
|
|
231
269
|
};
|
|
232
270
|
|
|
@@ -306,17 +344,27 @@ function enumerateParams(pattern: string, names: string[], raw: Record<string, u
|
|
|
306
344
|
// path even when a middleware exists (a middleware guards pages, not files).
|
|
307
345
|
const ASSET_EXT = new Set(['.js', '.css', '.json', '.png', '.jpg', '.jpeg', '.gif', '.svg', '.ico', '.webp', '.woff', '.woff2', '.txt', '.xml']);
|
|
308
346
|
|
|
309
|
-
// Response headers for a page document
|
|
310
|
-
|
|
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> {
|
|
311
350
|
const headers: Record<string, string> = {};
|
|
312
|
-
for (const [k, v] of Object.entries(securityHeaders(getClientSource()))) headers[k.toLowerCase()] = v;
|
|
351
|
+
for (const [k, v] of Object.entries(securityHeaders(getClientSource(), nonce))) headers[k.toLowerCase()] = v;
|
|
313
352
|
const own = ssrModule.headersFor?.(pathname) as Record<string, string> | null | undefined;
|
|
314
353
|
if (own) for (const [k, v] of Object.entries(own)) headers[k.toLowerCase()] = v;
|
|
315
354
|
return headers;
|
|
316
355
|
}
|
|
317
356
|
|
|
318
|
-
|
|
319
|
-
|
|
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).
|
|
320
368
|
const isrBusy = new Set<string>();
|
|
321
369
|
function revalidateInBackground(routePath: string, filePath: string): void {
|
|
322
370
|
if (isrBusy.has(filePath)) return;
|
|
@@ -326,9 +374,9 @@ function revalidateInBackground(routePath: string, filePath: string): void {
|
|
|
326
374
|
const ssrModule = await loadServer();
|
|
327
375
|
const page = await ssrModule.renderPage(routePath);
|
|
328
376
|
if (page.status === 200) {
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
await fs.promises.writeFile(filePath, getHtmlShell(page.html, page.state, page.head, page.csr !== false));
|
|
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));
|
|
332
380
|
fileCache.delete(filePath);
|
|
333
381
|
console.log(`rosetack: revalidated ${routePath} in the background`);
|
|
334
382
|
}
|
|
@@ -340,8 +388,8 @@ function revalidateInBackground(routePath: string, filePath: string): void {
|
|
|
340
388
|
})();
|
|
341
389
|
}
|
|
342
390
|
|
|
343
|
-
// ---
|
|
344
|
-
//
|
|
391
|
+
// --- production server posture -------------------------------------- "Can run a real app"
|
|
392
|
+
// is a threshold …
|
|
345
393
|
|
|
346
394
|
/** A request body is bounded. 1 MB holds any form and any JSON API call a
|
|
347
395
|
* site this size makes; a deployment that needs more sets it explicitly. */
|
|
@@ -424,6 +472,49 @@ function withAccessLog(handler: (req: any, res: any) => void, tag?: string): (re
|
|
|
424
472
|
};
|
|
425
473
|
}
|
|
426
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
|
+
|
|
427
518
|
function serveStatic(dir: string, isr = false): (req: any, res: any) => void {
|
|
428
519
|
return (req, res) => {
|
|
429
520
|
// The origin guard runs before everything else - middleware, api dispatch, the static
|
|
@@ -438,6 +529,20 @@ function serveStatic(dir: string, isr = false): (req: any, res: any) => void {
|
|
|
438
529
|
// Everything below needs the server module (API dispatch, POST actions, SSR), so load
|
|
439
530
|
// it once up front: the import is cached until dist/server.js changes on disk …
|
|
440
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
|
+
}
|
|
441
546
|
// Middleware (pages/_middleware.rose) runs exactly once per request, before anything
|
|
442
547
|
// else: a returned Response short-circuits the whole request …
|
|
443
548
|
const apiPath0 = pathnameOf(req.url);
|
|
@@ -445,7 +550,7 @@ function serveStatic(dir: string, isr = false): (req: any, res: any) => void {
|
|
|
445
550
|
if (!isPagePost && ssrModule.middleware) {
|
|
446
551
|
const mw = await ssrModule.runMiddleware(req);
|
|
447
552
|
if (mw) {
|
|
448
|
-
await sendWebResponse(mw, res);
|
|
553
|
+
await sendWebResponse(hookCtx ? await ssrModule.runResponseHooks(hookCtx, mw) : mw, res);
|
|
449
554
|
return;
|
|
450
555
|
}
|
|
451
556
|
}
|
|
@@ -464,7 +569,8 @@ function serveStatic(dir: string, isr = false): (req: any, res: any) => void {
|
|
|
464
569
|
headers,
|
|
465
570
|
body: body.length > 0 ? body : undefined,
|
|
466
571
|
});
|
|
467
|
-
|
|
572
|
+
let apiRes = await ssrModule.handleApi(req.method || 'GET', apiPath, request);
|
|
573
|
+
if (hookCtx) apiRes = await ssrModule.runResponseHooks(hookCtx, apiRes);
|
|
468
574
|
writeWebHeaders(apiRes, res);
|
|
469
575
|
res.statusCode = apiRes.status;
|
|
470
576
|
res.end(Buffer.from(await apiRes.arrayBuffer()));
|
|
@@ -490,12 +596,12 @@ function serveStatic(dir: string, isr = false): (req: any, res: any) => void {
|
|
|
490
596
|
if (ssrModule.middleware) {
|
|
491
597
|
const mw = await ssrModule.runMiddleware(req, form);
|
|
492
598
|
if (mw) {
|
|
493
|
-
await sendWebResponse(mw, res);
|
|
599
|
+
await sendWebResponse(hookCtx ? await ssrModule.runResponseHooks(hookCtx, mw) : mw, res);
|
|
494
600
|
return;
|
|
495
601
|
}
|
|
496
602
|
}
|
|
497
603
|
const page = await ssrModule.renderPage(req.url || '/', form);
|
|
498
|
-
|
|
604
|
+
await sendPage(req, res, ssrModule, hookCtx, page, pathnameOf(req.url || '/'));
|
|
499
605
|
} catch {
|
|
500
606
|
res.statusCode = 400;
|
|
501
607
|
res.end('Bad request');
|
|
@@ -519,8 +625,8 @@ function serveStatic(dir: string, isr = false): (req: any, res: any) => void {
|
|
|
519
625
|
filePath = path.join(filePath, 'index.html');
|
|
520
626
|
}
|
|
521
627
|
|
|
522
|
-
|
|
523
|
-
|
|
628
|
+
// Build-time precompression siblings (dist/<file>.br, read by the Go binary) are internal
|
|
629
|
+
// artifacts.
|
|
524
630
|
if (/\.(?:br|gz)$/i.test(safe)) {
|
|
525
631
|
const base = filePath.replace(/\.(?:br|gz)$/i, '');
|
|
526
632
|
if (fs.existsSync(base)) filePath = base;
|
|
@@ -532,8 +638,8 @@ function serveStatic(dir: string, isr = false): (req: any, res: any) => void {
|
|
|
532
638
|
const isDynamic = !isAsset && (ssrModule.dynamicRoutes as string[] | undefined)?.includes(pathnameOf(req.url));
|
|
533
639
|
if (!isDynamic && fs.existsSync(filePath) && fs.statSync(filePath).isFile()) {
|
|
534
640
|
const st = fs.statSync(filePath);
|
|
535
|
-
|
|
536
|
-
|
|
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 …
|
|
537
643
|
const rev = isAsset ? undefined : ((ssrModule.revalidate as { pattern: string; seconds: number }[]) || [])
|
|
538
644
|
.find((r) => ssrModule.matchRoute(r.pattern, pathnameOf(req.url)));
|
|
539
645
|
if (isr && rev && Date.now() - st.mtimeMs > rev.seconds * 1000) {
|
|
@@ -545,8 +651,10 @@ function serveStatic(dir: string, isr = false): (req: any, res: any) => void {
|
|
|
545
651
|
entry = {
|
|
546
652
|
mtimeMs: st.mtimeMs,
|
|
547
653
|
raw,
|
|
654
|
+
// A file's compressed forms are computed ONCE and then served from this cache
|
|
655
|
+
// forever …
|
|
548
656
|
br: zlib.brotliCompressSync(raw),
|
|
549
|
-
gzip: zlib.gzipSync(raw),
|
|
657
|
+
gzip: zlib.gzipSync(raw, { level: 9 }),
|
|
550
658
|
etag: `W/"${st.size}-${st.mtimeMs}"`,
|
|
551
659
|
};
|
|
552
660
|
fileCache.set(filePath, entry);
|
|
@@ -564,16 +672,26 @@ function serveStatic(dir: string, isr = false): (req: any, res: any) => void {
|
|
|
564
672
|
'.mp4': 'video/mp4',
|
|
565
673
|
'.mp3': 'audio/mpeg',
|
|
566
674
|
};
|
|
567
|
-
res.setHeader('Content-Type', types[ext] || 'application/octet-stream');
|
|
568
675
|
// An ISR route's file is swapped every `revalidate` seconds, so the cache must not
|
|
569
676
|
// outlive the window: revalidate every visit (a bodiless 304 when nothing changed) …
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
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);
|
|
577
695
|
}
|
|
578
696
|
if (req.headers['if-none-match'] === entry.etag) {
|
|
579
697
|
res.statusCode = 304;
|
|
@@ -581,7 +699,7 @@ function serveStatic(dir: string, isr = false): (req: any, res: any) => void {
|
|
|
581
699
|
return;
|
|
582
700
|
}
|
|
583
701
|
const enc = pickEncoding(req);
|
|
584
|
-
res.statusCode =
|
|
702
|
+
res.statusCode = status;
|
|
585
703
|
if (enc) {
|
|
586
704
|
res.setHeader('Content-Encoding', enc);
|
|
587
705
|
res.end(enc === 'br' ? entry.br : enc === 'gzip' ? entry.gzip : compress('deflate', entry.raw));
|
|
@@ -600,30 +718,57 @@ function serveStatic(dir: string, isr = false): (req: any, res: any) => void {
|
|
|
600
718
|
const safe2 = req.url || '/';
|
|
601
719
|
if (!broken.has(safe2) && ssrModule.canStream(safe2) && !ssrModule.isNoJs(safe2)) {
|
|
602
720
|
const enc = pickEncoding(req);
|
|
603
|
-
|
|
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;
|
|
604
734
|
res.setHeader('Content-Type', 'text/html; charset=utf-8');
|
|
605
735
|
res.setHeader('Vary', 'Accept-Encoding');
|
|
606
|
-
for (const [k, v] of Object.entries(
|
|
736
|
+
for (const [k, v] of Object.entries(headers)) res.setHeader(k, v);
|
|
607
737
|
let write: (chunk: string) => void;
|
|
608
738
|
let done: () => void;
|
|
609
739
|
if (enc) {
|
|
610
740
|
res.setHeader('Content-Encoding', enc);
|
|
611
741
|
const compressor = createCompressor(enc);
|
|
612
742
|
compressor.pipe(res);
|
|
613
|
-
|
|
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());
|
|
614
756
|
done = () => compressor.end();
|
|
615
757
|
} else {
|
|
616
758
|
write = (chunk) => res.write(chunk);
|
|
617
759
|
done = () => res.end();
|
|
618
760
|
}
|
|
619
|
-
|
|
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));
|
|
620
765
|
done();
|
|
621
766
|
return;
|
|
622
767
|
}
|
|
623
768
|
// buffered: POST actions, unmatched routes (404), known-broken routes (500), and csr
|
|
624
769
|
// = false routes …
|
|
625
770
|
const page = await ssrModule.renderPage(safe2);
|
|
626
|
-
|
|
771
|
+
await sendPage(req, res, ssrModule, hookCtx, page, pathnameOf(safe2));
|
|
627
772
|
}).catch(() => {
|
|
628
773
|
res.statusCode = 404;
|
|
629
774
|
res.end('Not found');
|
|
@@ -643,14 +788,18 @@ function pathnameOf(url: string | undefined): string {
|
|
|
643
788
|
/**
|
|
644
789
|
* The version from package.json - one source of truth, no constant to drift.
|
|
645
790
|
* Resolved from THIS module (not the cwd): the banner names the framework's
|
|
646
|
-
* version even when it builds somebody else's project.
|
|
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.
|
|
647
794
|
*/
|
|
648
795
|
function version(): string {
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
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 */ }
|
|
653
801
|
}
|
|
802
|
+
return '0.0.0';
|
|
654
803
|
}
|
|
655
804
|
|
|
656
805
|
async function dev(): Promise<void> {
|
|
@@ -689,7 +838,7 @@ async function preview(): Promise<void> {
|
|
|
689
838
|
await build();
|
|
690
839
|
const http = await import('http');
|
|
691
840
|
// isr=true: routes exporting `revalidate = N` are served stale-then-swapped
|
|
692
|
-
|
|
841
|
+
// from disk . Dev passes nothing (it rebuilds on change).
|
|
693
842
|
const server = http.createServer(serveStatic(OUT_DIR, true));
|
|
694
843
|
|
|
695
844
|
server.listen(PORT, () => {
|
|
@@ -698,16 +847,16 @@ async function preview(): Promise<void> {
|
|
|
698
847
|
}
|
|
699
848
|
|
|
700
849
|
/**
|
|
701
|
-
*
|
|
850
|
+
* `rosetack serve` runs what `build` produced - no rebuild, no
|
|
702
851
|
* watcher, production semantics (a preview that re-rendered on the fly
|
|
703
852
|
* could serve a half-written file). Multi-core through the stdlib cluster:
|
|
704
853
|
* the primary supervises and serves no traffic, the workers serve; every
|
|
705
854
|
* request is logged; SIGTERM drains in-flight work and exits.
|
|
706
855
|
*
|
|
707
|
-
*
|
|
856
|
+
* Boundaries, stated plainly:
|
|
708
857
|
* - each worker is its own process with its own dist/server.js module.
|
|
709
858
|
* Module-scope state is therefore per-worker, which is what $store()
|
|
710
|
-
*
|
|
859
|
+
* fixes: writes broadcast through the primary, reads stay
|
|
711
860
|
* local-synchronous. ISR revalidation may run in more than one worker
|
|
712
861
|
* for one route: the guard is per-worker and the cost is one duplicate
|
|
713
862
|
* render.
|
|
@@ -732,7 +881,8 @@ async function serve(): Promise<void> {
|
|
|
732
881
|
const PORT = Number(process.env.PORT) || 3000;
|
|
733
882
|
if (cluster.isPrimary) {
|
|
734
883
|
for (let i = 0; i < workers; i++) cluster.fork();
|
|
735
|
-
|
|
884
|
+
// The store relay. A worker broadcasts every $store write here; the primary forwards each
|
|
885
|
+
// patch to every OTHER worker …
|
|
736
886
|
cluster.on('message', (worker: any, msg: any) => {
|
|
737
887
|
if (!msg || msg.type !== 'rosetack:store') return;
|
|
738
888
|
for (const w of Object.values<any>(cluster.workers ?? {})) {
|
|
@@ -752,6 +902,14 @@ async function serve(): Promise<void> {
|
|
|
752
902
|
}
|
|
753
903
|
// worker the primary's death is the worker's death: no orphan holding the port
|
|
754
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
|
+
}
|
|
755
913
|
const http = await import('node:http');
|
|
756
914
|
const server = http.createServer(withAccessLog(serveStatic(OUT_DIR, true), `w${process.pid}`));
|
|
757
915
|
// A client that stalls mid-request is dropped instead of holding a worker;
|
|
@@ -759,8 +917,29 @@ async function serve(): Promise<void> {
|
|
|
759
917
|
server.requestTimeout = 30_000;
|
|
760
918
|
server.headersTimeout = 65_000; // must exceed requestTimeout
|
|
761
919
|
server.keepAliveTimeout = 5_000;
|
|
762
|
-
server.listen(PORT, () =>
|
|
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
|
+
});
|
|
763
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
|
+
}
|
|
764
943
|
server.close(() => process.exit(0)); // finish what is in flight
|
|
765
944
|
server.closeIdleConnections?.(); // drop the idle keep-alive sockets
|
|
766
945
|
setTimeout(() => process.exit(0), 5000).unref(); // a stuck one must not hold the worker
|
|
@@ -769,9 +948,286 @@ async function serve(): Promise<void> {
|
|
|
769
948
|
process.on('SIGINT', stop);
|
|
770
949
|
}
|
|
771
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
|
+
|
|
772
1226
|
const cmd = process.argv[2];
|
|
773
1227
|
if (cmd === 'dev') dev();
|
|
774
1228
|
else if (cmd === 'build') build();
|
|
775
1229
|
else if (cmd === 'preview') preview();
|
|
776
1230
|
else if (cmd === 'serve') serve();
|
|
777
|
-
else
|
|
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)');
|