rosetack 0.1.2 → 0.1.3
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/deploy/cloudflare/functions/[[path]].ts +61 -0
- package/deploy/cloudflare/wrangler.toml +14 -0
- package/deploy/netlify/functions/rosetack.ts +38 -0
- package/deploy/netlify.toml +17 -0
- package/devtools/devtools.html +7 -0
- package/devtools/devtools.js +1 -0
- package/devtools/manifest.json +8 -0
- package/devtools/panel.html +28 -0
- package/devtools/panel.js +54 -0
- package/dist-cli/compiler.mjs +818 -445
- package/dist-cli/edge.mjs +115 -39
- package/dist-cli/rosetack.mjs +1078 -529
- package/dist-cli/runtime.mjs +115 -34
- package/dist-cli/test.mjs +875 -464
- package/package.json +4 -3
- package/src/FRAMEWORK_VERSION +1 -1
- package/src/cli/edge.ts +69 -61
- package/src/cli/index.ts +243 -328
- package/src/cli/prompt.ts +4 -1
- package/src/cli/shell.ts +67 -69
- package/src/cli/test.ts +9 -70
- package/src/compiler/index.ts +921 -851
- package/src/runtime/index.ts +155 -158
- package/src/types/rosetack.d.ts +16 -66
- package/templates/admin/package.json +14 -0
- package/templates/admin/rosetack.config.js +1 -0
- package/templates/admin/src/pages/_middleware.rose +33 -0
- package/templates/admin/src/pages/api/items.rose +37 -0
- package/templates/admin/src/pages/api/login.rose +25 -0
- package/templates/admin/src/pages/index.rose +79 -0
- package/templates/api/package.json +14 -0
- package/templates/api/rosetack.config.js +1 -0
- package/templates/api/src/pages/api/health.rose +7 -0
- package/templates/api/src/pages/api/items.rose +46 -0
- package/templates/api/src/pages/api/login.rose +24 -0
- package/templates/api/src/pages/index.rose +25 -0
- package/templates/blog/package.json +14 -0
- package/templates/blog/rosetack.config.js +1 -0
- package/templates/blog/src/pages/404.rose +2 -0
- package/templates/blog/src/pages/_layout.rose +42 -0
- package/templates/blog/src/pages/_middleware.rose +74 -0
- package/templates/blog/src/pages/admin.rose +85 -0
- package/templates/blog/src/pages/api/login.rose +46 -0
- package/templates/blog/src/pages/api/posts/[id].rose +37 -0
- package/templates/blog/src/pages/api/posts.rose +72 -0
- package/templates/blog/src/pages/index.rose +31 -0
- package/templates/blog/src/pages/post/[id].rose +36 -0
- package/templates/site/package.json +14 -0
- package/templates/site/rosetack.config.js +1 -0
- package/templates/site/src/pages/404.rose +2 -0
- package/templates/site/src/pages/_layout.rose +40 -0
- package/templates/site/src/pages/about.rose +6 -0
- package/templates/site/src/pages/index.rose +13 -0
- package/templates/site/src/pages/pricing.rose +8 -0
package/src/cli/index.ts
CHANGED
|
@@ -1,6 +1,4 @@
|
|
|
1
|
-
|
|
2
|
-
* rosetack CLI - simplest possible SSR + static server
|
|
3
|
-
*/
|
|
1
|
+
// rosetack CLI - simplest possible SSR + static server
|
|
4
2
|
|
|
5
3
|
import * as fs from 'fs';
|
|
6
4
|
import * as path from 'path';
|
|
@@ -10,26 +8,18 @@ import { pathToFileURL, fileURLToPath } from 'url';
|
|
|
10
8
|
import { buildProject, scanRoseFiles, scanComponentFiles, scriptOf, extractExports, loadPlugins, RoseError, errorInfo, type RouteInfo } from '../compiler/index.js';
|
|
11
9
|
import { getHtmlShell, getClientSource, getStyles, shellOpen, clientScriptTag, securityHeaders, mintNonce, setBundleMode } from './shell.js';
|
|
12
10
|
import { AI_PROMPT } from './prompt.js';
|
|
13
|
-
// Type-only: erased by esbuild/tsx, so the published CLI stays a ~100 KB bundle with no
|
|
14
|
-
// TypeScript dependency.
|
|
15
11
|
import type * as ts from 'typescript';
|
|
16
12
|
|
|
17
|
-
// --- wire performance: compression + conditional caching (stdlib only) --- The Go binary
|
|
18
|
-
// already compresses …
|
|
19
13
|
type Encoding = 'br' | 'gzip' | 'deflate';
|
|
20
14
|
|
|
21
15
|
function pickEncoding(req: any): Encoding | null {
|
|
22
16
|
const ae: string = req.headers['accept-encoding'] || '';
|
|
23
|
-
// Trade-off: substring match, no q-value parsing - every browser that sends
|
|
24
|
-
// br also accepts gzip, and br > gzip > deflate is the quality order.
|
|
25
17
|
if (ae.includes('br')) return 'br';
|
|
26
18
|
if (ae.includes('gzip')) return 'gzip';
|
|
27
19
|
if (ae.includes('deflate')) return 'deflate';
|
|
28
20
|
return null;
|
|
29
21
|
}
|
|
30
22
|
|
|
31
|
-
// Brotli's default quality (11) spends ~108 ms of CPU on a 32 KB document; quality 5 does
|
|
32
|
-
// the same document in ~2.4 ms for 9% more bytes (measured, Node 22).
|
|
33
23
|
const brotliFast = { [zlib.constants.BROTLI_PARAM_QUALITY]: 5 };
|
|
34
24
|
|
|
35
25
|
function compress(enc: Encoding, data: string | Buffer): Buffer {
|
|
@@ -50,8 +40,6 @@ function sendHtml(req: any, res: any, status: number, html: string, extraHeaders
|
|
|
50
40
|
res.setHeader('Content-Type', 'text/html; charset=utf-8');
|
|
51
41
|
res.setHeader('Vary', 'Accept-Encoding');
|
|
52
42
|
if (extraHeaders) for (const [k, v] of Object.entries(extraHeaders)) res.setHeader(k, v);
|
|
53
|
-
// A weak ETag over the rendered bytes: revalidation answers a bodiless 304 for dynamic
|
|
54
|
-
// renders too …
|
|
55
43
|
let hash = 0x811c9dc5;
|
|
56
44
|
for (let i = 0; i < html.length; i++) {
|
|
57
45
|
hash ^= html.charCodeAt(i);
|
|
@@ -73,8 +61,6 @@ function sendHtml(req: any, res: any, status: number, html: string, extraHeaders
|
|
|
73
61
|
}
|
|
74
62
|
}
|
|
75
63
|
|
|
76
|
-
// Copy a Web-standard Response's headers onto the Node response. set-cookie is the one
|
|
77
|
-
// header that may legally repeat, and res.setHeader overwrites …
|
|
78
64
|
function writeWebHeaders(web: any, res: any): void {
|
|
79
65
|
const cookies = web.headers.getSetCookie?.() ?? [];
|
|
80
66
|
web.headers.forEach((v: string, k: string) => {
|
|
@@ -84,86 +70,62 @@ function writeWebHeaders(web: any, res: any): void {
|
|
|
84
70
|
if (cookies.length) res.setHeader('set-cookie', cookies);
|
|
85
71
|
}
|
|
86
72
|
|
|
87
|
-
// A middleware's short-circuit: a Web-standard Response (status, headers, body) written
|
|
88
|
-
// straight to the Node response - a redirect, an auth wall, a rewrite.
|
|
89
73
|
async function sendWebResponse(web: any, res: any): Promise<void> {
|
|
90
74
|
writeWebHeaders(web, res);
|
|
91
75
|
res.statusCode = web.status;
|
|
92
76
|
res.end(Buffer.from(await web.arrayBuffer()));
|
|
93
77
|
}
|
|
94
78
|
|
|
95
|
-
|
|
96
|
-
* Send a rendered page document - through onResponse first . The
|
|
97
|
-
* hook sees the status, headers and body exactly as they will go on the
|
|
98
|
-
* wire and may replace them, so the ETag inside sendHtml is then computed
|
|
99
|
-
* over the bytes actually sent. One helper for the POST-action path and the
|
|
100
|
-
* buffered GET path: same hook, same order, no drift between them.
|
|
101
|
-
*/
|
|
79
|
+
// Send a rendered page document - through onResponse first .
|
|
102
80
|
async function sendPage(req: any, res: any, ssrModule: any, hookCtx: any, page: any, routePath: string): Promise<void> {
|
|
103
81
|
let status = page.status ?? 200;
|
|
104
|
-
|
|
105
|
-
|
|
82
|
+
if (page.redirect) {
|
|
83
|
+
const body = `<!DOCTYPE html><title>Redirecting</title><p>Redirecting to <a href="${page.redirect}">${page.redirect}</a>.</p>`;
|
|
84
|
+
let headers: Record<string, any> = pageHeaders(ssrModule, routePath, '');
|
|
85
|
+
if (hookCtx) {
|
|
86
|
+
const out = await ssrModule.runResponseHooks(hookCtx, new Response(body, {
|
|
87
|
+
status,
|
|
88
|
+
headers: { 'content-type': 'text/html; charset=utf-8', location: page.redirect, ...headers },
|
|
89
|
+
}));
|
|
90
|
+
status = out.status;
|
|
91
|
+
headers = webHeadersToNode(out);
|
|
92
|
+
}
|
|
93
|
+
headers.location = page.redirect;
|
|
94
|
+
res.statusCode = status;
|
|
95
|
+
res.setHeader('Content-Type', 'text/html; charset=utf-8');
|
|
96
|
+
res.setHeader('Location', page.redirect);
|
|
97
|
+
for (const [k, v] of Object.entries(headers)) if (k !== 'location') res.setHeader(k, v);
|
|
98
|
+
res.end(body);
|
|
99
|
+
return;
|
|
100
|
+
}
|
|
106
101
|
const nonce = nonceFor(ssrModule, routePath);
|
|
107
|
-
|
|
108
|
-
// always lands here or in the stream below - never on the baked-file path …
|
|
109
|
-
let html = getHtmlShell(page.html, page.state, page.head, page.csr !== false, page.lang, page.dir, nonce);
|
|
102
|
+
let html = getHtmlShell(page.html, page.state, page.head, page.csr !== false, page.lang, page.dir, nonce, page.shell !== false);
|
|
110
103
|
let headers: Record<string, any> = pageHeaders(ssrModule, routePath, nonce);
|
|
111
104
|
if (hookCtx) {
|
|
112
|
-
// P0-3: the document's content-type travels WITH the Response. The WHATWG constructor
|
|
113
|
-
// fills in text/plain when it is missing …
|
|
114
105
|
const out = await ssrModule.runResponseHooks(hookCtx, new Response(html, {
|
|
115
106
|
status,
|
|
116
107
|
headers: { 'content-type': 'text/html; charset=utf-8', ...headers },
|
|
117
108
|
}));
|
|
118
109
|
status = out.status;
|
|
119
110
|
headers = webHeadersToNode(out);
|
|
120
|
-
// P0-4: a hook that READ the body and returned the same Response cannot have it read
|
|
121
|
-
// again (TypeError: body already used) …
|
|
122
111
|
html = out.bodyUsed ? html : await out.text();
|
|
123
112
|
}
|
|
124
113
|
sendHtml(req, res, status, html, headers);
|
|
125
114
|
}
|
|
126
115
|
|
|
127
|
-
// Static files: raw + both compressed forms cached per mtime (dev rebuilds change mtime;
|
|
128
|
-
// preview never does).
|
|
129
116
|
const fileCache = new Map<string, { mtimeMs: number; raw: Buffer; br: Buffer; gzip: Buffer; etag: string }>();
|
|
130
117
|
|
|
131
|
-
// P0-0 (bug report): `--port N` (or `--port=N`), the same override the PORT env gives, as
|
|
132
|
-
// an argument …
|
|
133
118
|
const __portArg = process.argv.find((a) => a === '--port' || a.startsWith('--port='));
|
|
134
119
|
if (__portArg) {
|
|
135
120
|
const __v = __portArg.includes('=') ? __portArg.slice('--port='.length) : process.argv[process.argv.indexOf(__portArg) + 1];
|
|
136
121
|
if (__v && Number(__v) > 0) process.env.PORT = __v;
|
|
137
122
|
}
|
|
138
123
|
|
|
139
|
-
// (the "the framework is real" gate): the CLI builds ANY project, not just this repo's
|
|
140
|
-
// demo.
|
|
141
124
|
const SRC_DIR = process.argv[3] && !process.argv[3].startsWith('-') ? path.resolve(process.argv[3]) : process.cwd();
|
|
142
|
-
// The deploy dir is ./dist of the directory the command ran from - a documented contract
|
|
143
|
-
// (test-cli.mjs asserts it): building a project that is not the cwd still drops its output …
|
|
144
125
|
const OUT_DIR = path.join(process.cwd(), 'dist');
|
|
145
|
-
// PORT env override (default 3000): lets a preview server run beside a dev
|
|
146
|
-
// server on the same machine - the e2e ISR test does exactly that.
|
|
147
126
|
const PORT = Number(process.env.PORT) || 3000;
|
|
148
127
|
|
|
149
|
-
|
|
150
|
-
* Import dist/server.js, cached until the file changes on disk.
|
|
151
|
-
*
|
|
152
|
-
* The dev server rebuilds it on file changes, so a plain import() would
|
|
153
|
-
* serve the cached (stale) module - re-import when mtime moves. But the
|
|
154
|
-
* import must NOT be per-request: server state (stores mutated by server
|
|
155
|
-
* actions) lives in that module, and a fresh import per request would
|
|
156
|
-
* reset it on every hit, so an action's effect would vanish immediately.
|
|
157
|
-
*
|
|
158
|
-
* The dev re-import needs a NEW PATH, not a new `?v=` query: tsx's ESM
|
|
159
|
-
* loader (which `npm run dev` runs the CLI through) caches by resolved
|
|
160
|
-
* path and ignores the search string, so the query trick silently handed
|
|
161
|
-
* back the previous module - a rebuild that served the OLD code until the
|
|
162
|
-
* NEXT rebuild landed, which is exactly the "hot reload" a developer
|
|
163
|
-
* cannot trust. A copied file under dist/.build/ (which every build
|
|
164
|
-
* deletes, and which never ships) is a new module under any loader.
|
|
165
|
-
* Preview and serve never rebuild, so they import dist/server.js itself.
|
|
166
|
-
*/
|
|
128
|
+
// Import dist/server.js, cached until the file changes on disk. Preview and serve never rebuild, so they import dist/server.js itself.
|
|
167
129
|
let serverModule: any = null;
|
|
168
130
|
let serverMtime = -1;
|
|
169
131
|
let serverVersion = 0;
|
|
@@ -186,32 +148,37 @@ async function loadServer(): Promise<any> {
|
|
|
186
148
|
}
|
|
187
149
|
|
|
188
150
|
async function build(): Promise<void> {
|
|
189
|
-
// The build reports the bundle mode ('inline' | 'split') so the
|
|
190
|
-
// shell follows it for every document, header and streaming tag it emits
|
|
191
151
|
const { routes, bundle } = await buildProject(SRC_DIR, OUT_DIR);
|
|
192
|
-
// The previous build's prerendered output must not survive: a route that stopped being
|
|
193
|
-
// static (it started reading getContext() or $store()) would otherwise leave its old
|
|
194
|
-
// baked …
|
|
195
152
|
await clearPrerendered(OUT_DIR);
|
|
196
153
|
setBundleMode(bundle);
|
|
197
154
|
const skipped = await prerender(routes);
|
|
198
|
-
// The broken-route manifest: the server reads it to pick the buffered path for these
|
|
199
|
-
// routes, so their real 500 status survives (a flushed response cannot change its
|
|
200
|
-
// status).
|
|
201
155
|
await fs.promises.writeFile(path.join(OUT_DIR, 'broken.json'), JSON.stringify(skipped));
|
|
202
|
-
// Per-route response headers for the Go binary, which has no compiler: it reads this file
|
|
203
|
-
// and merges the entries over its own responses.
|
|
204
156
|
const ssrModule = await loadServer();
|
|
205
157
|
await fs.promises.writeFile(path.join(OUT_DIR, 'headers.json'), JSON.stringify({
|
|
206
158
|
default: securityHeaders(getClientSource()),
|
|
207
159
|
routes: ssrModule.routeHeaders ?? [],
|
|
208
160
|
}));
|
|
209
|
-
// Precompressed brotli siblings (dist/<file>.br) for the Go single binary. The binary
|
|
210
|
-
// embeds dist/ verbatim …
|
|
211
161
|
await writeBrotli(OUT_DIR);
|
|
212
|
-
// What this build actually costs on the wire, per route. Runs
|
|
213
|
-
// after writeBrotli so the br column is the file the Go binary serves.
|
|
214
162
|
await analyze(OUT_DIR, (ssrModule.dynamicRoutes as string[] | undefined) ?? []);
|
|
163
|
+
|
|
164
|
+
if (argv.includes('--static')) {
|
|
165
|
+
const dyn = (ssrModule.dynamicRoutes as string[] | undefined) ?? [];
|
|
166
|
+
const unbakedApi = Object.entries((ssrModule.apiPrerender ?? {}) as Record<string, boolean>)
|
|
167
|
+
.filter(([, baked]) => !baked)
|
|
168
|
+
.map(([routePath]) => routePath);
|
|
169
|
+
const paramless = routes
|
|
170
|
+
.filter((r) => r.paramNames.length > 0 && !((ssrModule.routeParams ?? {}) as Record<string, unknown>)[r.routePath])
|
|
171
|
+
.map((r) => r.routePath);
|
|
172
|
+
const problems = [...new Set([...dyn, ...unbakedApi, ...paramless, ...skipped])];
|
|
173
|
+
if (problems.length > 0) {
|
|
174
|
+
console.error('rosetack: --static export refused - these routes need a server:');
|
|
175
|
+
for (const p of problems) console.error(` ${p}`);
|
|
176
|
+
console.error('(getContext()/$store()/$query(), csp.nonce, buffer = true, an unbaked /api route, a param route with no export const params, or a route the middleware walled)');
|
|
177
|
+
console.error('drop --static to build the normal dist (the dynamic half renders on demand on Node/edge)');
|
|
178
|
+
process.exit(1);
|
|
179
|
+
}
|
|
180
|
+
console.log('rosetack: static export verified - every route is a baked file, no server needed');
|
|
181
|
+
}
|
|
215
182
|
}
|
|
216
183
|
|
|
217
184
|
/**
|
|
@@ -293,8 +260,6 @@ async function analyze(outDir: string, dynamic: string[]): Promise<void> {
|
|
|
293
260
|
*/
|
|
294
261
|
async function clearPrerendered(dir: string, depth = 0): Promise<void> {
|
|
295
262
|
for (const e of await fs.promises.readdir(dir, { withFileTypes: true })) {
|
|
296
|
-
// Dist/locales/ holds the runtime locale packs the build just wrote (i18n.preload's
|
|
297
|
-
// leftovers) - they are .json files like any prerendered body, but they are build output …
|
|
298
263
|
if (depth === 0 && e.name === 'locales' && e.isDirectory()) continue;
|
|
299
264
|
const p = path.join(dir, e.name);
|
|
300
265
|
if (e.isDirectory()) {
|
|
@@ -327,36 +292,26 @@ async function prerender(routes: RouteInfo[]): Promise<string[]> {
|
|
|
327
292
|
const ssrModule = await loadServer();
|
|
328
293
|
const skipped: string[] = [];
|
|
329
294
|
const write = async (routePath: string) => {
|
|
330
|
-
// a synthetic cookie-less request: the middleware runs at build time too, and a route
|
|
331
|
-
// it short-circuits (an auth wall, a maintenance rewrite) simply is not static …
|
|
332
295
|
const mw = await ssrModule.runMiddleware({ method: 'GET', url: routePath, headers: {} });
|
|
333
296
|
if (mw) {
|
|
334
297
|
console.error(`prerender skipped for ${routePath}: the middleware short-circuits at build time`);
|
|
335
298
|
skipped.push(routePath);
|
|
336
299
|
return;
|
|
337
300
|
}
|
|
338
|
-
// P0-1: a baked document has no request and therefore no query - say so
|
|
339
|
-
// explicitly, so a query from the previous render can never leak in.
|
|
340
301
|
ssrModule.setQuery?.({});
|
|
341
302
|
const page = await ssrModule.renderPage(routePath);
|
|
342
303
|
if (page.status === 500) {
|
|
343
|
-
// The route's render failed and the error page rendered instead. Do NOT bake that
|
|
344
|
-
// into a static file: a static server can only answer 200 …
|
|
345
304
|
console.error(`prerender skipped for ${routePath}: render failed, the error page rendered`);
|
|
346
305
|
skipped.push(routePath);
|
|
347
306
|
return;
|
|
348
307
|
}
|
|
349
308
|
const routeDir = routePath === '/' ? OUT_DIR : path.join(OUT_DIR, routePath.slice(1));
|
|
350
309
|
await fs.promises.mkdir(routeDir, { recursive: true });
|
|
351
|
-
|
|
352
|
-
// state script, so a visitor who lands on it runs zero JavaScript.
|
|
353
|
-
await fs.promises.writeFile(path.join(routeDir, 'index.html'), getHtmlShell(page.html, page.state, page.head, page.csr !== false, page.lang, page.dir));
|
|
310
|
+
await fs.promises.writeFile(path.join(routeDir, 'index.html'), getHtmlShell(page.html, page.state, page.head, page.csr !== false, page.lang, page.dir, '', page.shell !== false));
|
|
354
311
|
console.log(`prerendered ${routePath} -> ${path.relative(process.cwd(), path.join(routeDir, 'index.html'))}`);
|
|
355
312
|
};
|
|
356
313
|
|
|
357
314
|
for (const info of routes) {
|
|
358
|
-
// routes that read the request context (getContext()) or a shared store ($store()) are
|
|
359
|
-
// dynamic by construction: the bag is per-request and the store is per-process …
|
|
360
315
|
if ((ssrModule.dynamicRoutes as string[]).includes(info.routePath)) {
|
|
361
316
|
console.log(`dynamic route ${info.routePath}: per-request state (getContext/$store), rendered on demand`);
|
|
362
317
|
continue;
|
|
@@ -365,15 +320,11 @@ async function prerender(routes: RouteInfo[]): Promise<string[]> {
|
|
|
365
320
|
try {
|
|
366
321
|
await write(info.routePath);
|
|
367
322
|
} catch (err) {
|
|
368
|
-
// One broken route (e.g. throwing $data) must not fail the whole build;
|
|
369
|
-
// it simply keeps rendering on demand.
|
|
370
323
|
console.error(`prerender skipped for ${info.routePath}: ${err instanceof Error ? err.message : err}`);
|
|
371
324
|
skipped.push(info.routePath);
|
|
372
325
|
}
|
|
373
326
|
continue;
|
|
374
327
|
}
|
|
375
|
-
// dynamic route: enumerate the exported params map, if any. The maps are re-exported by
|
|
376
|
-
// the server bundle (routeParams) …
|
|
377
328
|
try {
|
|
378
329
|
const paramsExport = (ssrModule.routeParams as Record<string, unknown>)?.[info.routePath];
|
|
379
330
|
const raw = typeof paramsExport === 'function' ? await (paramsExport as () => unknown)() : paramsExport;
|
|
@@ -386,9 +337,6 @@ async function prerender(routes: RouteInfo[]): Promise<string[]> {
|
|
|
386
337
|
}
|
|
387
338
|
}
|
|
388
339
|
|
|
389
|
-
// API routes that opt in (export const prerender = true) bake their GET body into
|
|
390
|
-
// dist/api/<route>.json: the Go single binary then serves the read-only API with zero
|
|
391
|
-
// Node.
|
|
392
340
|
const apiPrerender = (ssrModule.apiPrerender as Record<string, boolean>) ?? {};
|
|
393
341
|
for (const [routePath, on] of Object.entries(apiPrerender)) {
|
|
394
342
|
if (!on) continue;
|
|
@@ -421,17 +369,17 @@ function enumerateParams(pattern: string, names: string[], raw: Record<string, u
|
|
|
421
369
|
let i = 0;
|
|
422
370
|
return pattern
|
|
423
371
|
.split('/')
|
|
424
|
-
.map((seg) =>
|
|
372
|
+
.map((seg) => {
|
|
373
|
+
if (seg.startsWith(':')) return encodeURIComponent(values[i++]);
|
|
374
|
+
if (seg.startsWith('*')) return values[i++].split('/').map(encodeURIComponent).join('/');
|
|
375
|
+
return seg;
|
|
376
|
+
})
|
|
425
377
|
.join('/');
|
|
426
378
|
});
|
|
427
379
|
}
|
|
428
380
|
|
|
429
|
-
// Extensions the static branch serves without touching the router: assets keep their fast
|
|
430
|
-
// path even when a middleware exists (a middleware guards pages, not files).
|
|
431
381
|
const ASSET_EXT = new Set(['.js', '.css', '.json', '.png', '.jpg', '.jpeg', '.gif', '.svg', '.ico', '.webp', '.woff', '.woff2', '.txt', '.xml']);
|
|
432
382
|
|
|
433
|
-
// Response headers for a page document: the strict CSP (hashed over the exact inlined
|
|
434
|
-
// bundle + bootstrap bytes …
|
|
435
383
|
function pageHeaders(ssrModule: any, pathname: string, nonce = ''): Record<string, string> {
|
|
436
384
|
const headers: Record<string, string> = {};
|
|
437
385
|
for (const [k, v] of Object.entries(securityHeaders(getClientSource(), nonce))) headers[k.toLowerCase()] = v;
|
|
@@ -449,8 +397,6 @@ function nonceFor(ssrModule: any, pathname: string): string {
|
|
|
449
397
|
return ssrModule.cspNonce?.(pathname) ? mintNonce() : '';
|
|
450
398
|
}
|
|
451
399
|
|
|
452
|
-
// ISR background pass: re-render a stale baked route and swap its file, while the
|
|
453
|
-
// triggering request was already answered from disk (stale-while-revalidate).
|
|
454
400
|
const isrBusy = new Set<string>();
|
|
455
401
|
function revalidateInBackground(routePath: string, filePath: string): void {
|
|
456
402
|
if (isrBusy.has(filePath)) return;
|
|
@@ -458,14 +404,10 @@ function revalidateInBackground(routePath: string, filePath: string): void {
|
|
|
458
404
|
void (async () => {
|
|
459
405
|
try {
|
|
460
406
|
const ssrModule = await loadServer();
|
|
461
|
-
// P0-1: the background pass has no request either - an empty query, so
|
|
462
|
-
// the swapped file never carries another visitor's search terms.
|
|
463
407
|
ssrModule.setQuery?.({});
|
|
464
408
|
const page = await ssrModule.renderPage(routePath);
|
|
465
409
|
if (page.status === 200) {
|
|
466
|
-
|
|
467
|
-
// zero-JS, or the first stale window would silently inline the bundle into its baked file
|
|
468
|
-
await fs.promises.writeFile(filePath, getHtmlShell(page.html, page.state, page.head, page.csr !== false, page.lang, page.dir));
|
|
410
|
+
await fs.promises.writeFile(filePath, getHtmlShell(page.html, page.state, page.head, page.csr !== false, page.lang, page.dir, '', page.shell !== false));
|
|
469
411
|
fileCache.delete(filePath);
|
|
470
412
|
console.log(`rosetack: revalidated ${routePath} in the background`);
|
|
471
413
|
}
|
|
@@ -477,9 +419,6 @@ function revalidateInBackground(routePath: string, filePath: string): void {
|
|
|
477
419
|
})();
|
|
478
420
|
}
|
|
479
421
|
|
|
480
|
-
// --- production server posture -------------------------------------- "Can run a real app"
|
|
481
|
-
// is a threshold …
|
|
482
|
-
|
|
483
422
|
/** A request body is bounded. 1 MB holds any form and any JSON API call a
|
|
484
423
|
* site this size makes; a deployment that needs more sets it explicitly. */
|
|
485
424
|
const MAX_BODY = Number(process.env.rosetack_MAX_BODY) || 1024 * 1024;
|
|
@@ -506,7 +445,6 @@ function readBody(req: any, res: any, onDone: (body: any) => void): void {
|
|
|
506
445
|
chunks.push(c);
|
|
507
446
|
});
|
|
508
447
|
req.on('end', () => { if (!refused) onDone(Buffer.concat(chunks)); });
|
|
509
|
-
// an aborted upload must not throw an unhandled 'error' and take the process down with it
|
|
510
448
|
req.on('error', () => {});
|
|
511
449
|
}
|
|
512
450
|
|
|
@@ -584,7 +522,7 @@ async function hookContext(req: any): Promise<{
|
|
|
584
522
|
for (const [k, v] of Object.entries(req.headers)) {
|
|
585
523
|
if (v !== undefined) headers[k] = Array.isArray(v) ? v.join(', ') : String(v);
|
|
586
524
|
}
|
|
587
|
-
|
|
525
|
+
const request = new Request(`http://${req.headers.host || 'localhost'}${req.url}`, {
|
|
588
526
|
method: req.method || 'GET',
|
|
589
527
|
headers,
|
|
590
528
|
});
|
|
@@ -604,14 +542,9 @@ function webHeadersToNode(web: any): Record<string, any> {
|
|
|
604
542
|
return out;
|
|
605
543
|
}
|
|
606
544
|
|
|
607
|
-
// --- dev-only live reload + state bridge --- The dev server rebuilds on change …
|
|
608
545
|
const DEV_BRIDGE = `<script>(function(){var es=new EventSource('/__rosetack_reload');es.onmessage=function(m){if(m.data!=='rebuild')return;es.close();var s=window.__rosetack?window.__rosetack.state():null;if(s)fetch('/__rosetack_state',{method:'POST',body:s,headers:{'content-type':'application/json'}}).catch(function(){});setTimeout(function(){location.reload()},40)}})()</script>`;
|
|
609
|
-
// One slot: the next document a dev client asks for carries it back. trade-off: a single
|
|
610
|
-
// browser tab is the dev case …
|
|
611
546
|
let devResume: string | null = null;
|
|
612
547
|
const devClients = new Set<any>();
|
|
613
|
-
// Set once, when the dev server wraps its handler: this process serves dev documents, so
|
|
614
|
-
// sendHtml answers them buffered and uncompressed …
|
|
615
548
|
let devMode = false;
|
|
616
549
|
|
|
617
550
|
function devReload(req: any, res: any): void {
|
|
@@ -629,7 +562,7 @@ function devSaveState(req: any, res: any): void {
|
|
|
629
562
|
let body = '';
|
|
630
563
|
req.on('data', (c: any) => {
|
|
631
564
|
body += c;
|
|
632
|
-
if (body.length > 1e6) req.destroy();
|
|
565
|
+
if (body.length > 1e6) req.destroy();
|
|
633
566
|
});
|
|
634
567
|
req.on('end', () => {
|
|
635
568
|
try {
|
|
@@ -651,14 +584,34 @@ function devNotify(): void {
|
|
|
651
584
|
}
|
|
652
585
|
}
|
|
653
586
|
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
587
|
+
let devBuild: Promise<void> | null = null;
|
|
588
|
+
let devBuildPending = false;
|
|
589
|
+
|
|
590
|
+
function startDevBuild(): Promise<void> {
|
|
591
|
+
if (!devBuild) {
|
|
592
|
+
devBuild = (async () => {
|
|
593
|
+
try {
|
|
594
|
+
console.log('Rebuilding...');
|
|
595
|
+
await build();
|
|
596
|
+
devNotify();
|
|
597
|
+
} catch (err) {
|
|
598
|
+
console.error('Build failed (server still running):', err instanceof Error ? err.message : String(err));
|
|
599
|
+
} finally {
|
|
600
|
+
devBuild = null;
|
|
601
|
+
devBuildPending = false;
|
|
602
|
+
}
|
|
603
|
+
})();
|
|
604
|
+
}
|
|
605
|
+
return devBuild;
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
/** Q2: the promise to await before routing, or null when nothing is building. */
|
|
609
|
+
function settleDevBuild(): Promise<void> | null {
|
|
610
|
+
if (!devMode || (!devBuild && !devBuildPending)) return null;
|
|
611
|
+
return startDevBuild();
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
// Wrap a dev response so every HTML document carries the bridge (and the resumed state, once).
|
|
662
615
|
function devWrap(inner: (req: any, res: any) => void): (req: any, res: any) => void {
|
|
663
616
|
devMode = true;
|
|
664
617
|
return (req, res) => {
|
|
@@ -666,8 +619,6 @@ function devWrap(inner: (req: any, res: any) => void): (req: any, res: any) => v
|
|
|
666
619
|
if (url.startsWith('/__rosetack_reload')) return devReload(req, res);
|
|
667
620
|
if (url.startsWith('/__rosetack_state') && req.method === 'POST') return devSaveState(req, res);
|
|
668
621
|
let injected = false;
|
|
669
|
-
// The resumed snapshot belongs to the NEXT request, whatever it turns out to be: a
|
|
670
|
-
// document that answers 304 (nothing changed) consumes it too …
|
|
671
622
|
const seed = devResume;
|
|
672
623
|
devResume = null;
|
|
673
624
|
const isHtml = () => String(res.getHeader('content-type') || '').includes('text/html');
|
|
@@ -675,9 +626,9 @@ function devWrap(inner: (req: any, res: any) => void): (req: any, res: any) => v
|
|
|
675
626
|
if (injected || !isHtml()) return chunk;
|
|
676
627
|
const s = Buffer.isBuffer(chunk) ? chunk.toString('utf8') : String(chunk);
|
|
677
628
|
const at = s.indexOf('<head>');
|
|
678
|
-
if (at < 0) return chunk;
|
|
629
|
+
if (at < 0) return chunk;
|
|
679
630
|
injected = true;
|
|
680
|
-
const resume = seed ? `<script>window.__rosetack_resume=${seed.replace(
|
|
631
|
+
const resume = seed ? `<script>window.__rosetack_resume=${seed.replace(/<\/script>/g, '')}</script>` : '';
|
|
681
632
|
const out = s.slice(0, at + 6) + resume + DEV_BRIDGE + s.slice(at + 6);
|
|
682
633
|
return Buffer.isBuffer(chunk) ? Buffer.from(out, 'utf8') : out;
|
|
683
634
|
};
|
|
@@ -694,8 +645,6 @@ function devWrap(inner: (req: any, res: any) => void): (req: any, res: any) => v
|
|
|
694
645
|
|
|
695
646
|
function serveStatic(dir: string, isr = false, dev = false): (req: any, res: any) => void {
|
|
696
647
|
return (req, res) => {
|
|
697
|
-
// The origin guard runs before everything else - middleware, api dispatch, the static
|
|
698
|
-
// lookup - because a cross-site write must not reach any of them.
|
|
699
648
|
const blocked = crossSiteWrite(req);
|
|
700
649
|
if (blocked) {
|
|
701
650
|
res.statusCode = blocked.status;
|
|
@@ -703,25 +652,31 @@ function serveStatic(dir: string, isr = false, dev = false): (req: any, res: any
|
|
|
703
652
|
res.end(blocked.body);
|
|
704
653
|
return;
|
|
705
654
|
}
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
655
|
+
const want = pathnameOf(req.url || '/');
|
|
656
|
+
const canonical = want.replace(/\/+$/, '') || '/';
|
|
657
|
+
if (canonical !== want) {
|
|
658
|
+
let search = '';
|
|
659
|
+
try { search = new URL(req.url || '/', 'http://localhost').search; } catch { }
|
|
660
|
+
const to = canonical + search;
|
|
661
|
+
res.statusCode = 308;
|
|
662
|
+
res.setHeader('Location', to);
|
|
663
|
+
res.setHeader('Content-Type', 'text/html; charset=utf-8');
|
|
664
|
+
res.end(`<!DOCTYPE html><title>Redirecting</title><p>Redirecting to <a href="${to}">${to}</a>.</p>`);
|
|
665
|
+
return;
|
|
666
|
+
}
|
|
667
|
+
const settled = settleDevBuild();
|
|
668
|
+
const ready = settled ? settled.then(() => loadServer()) : loadServer();
|
|
669
|
+
ready.then(async (ssrModule: any) => {
|
|
711
670
|
const hookCtx = ssrModule.hasRequestHooks === true || ssrModule.hasResponseHooks === true
|
|
712
671
|
? await hookContext(req)
|
|
713
672
|
: null;
|
|
714
673
|
if (hookCtx) {
|
|
715
674
|
const short = await ssrModule.runRequestHooks(hookCtx);
|
|
716
675
|
if (short) {
|
|
717
|
-
// the short-circuit rides through onResponse like every other
|
|
718
|
-
// response, so a header-adding hook sees it too
|
|
719
676
|
await sendWebResponse(await ssrModule.runResponseHooks(hookCtx, short), res);
|
|
720
677
|
return;
|
|
721
678
|
}
|
|
722
679
|
}
|
|
723
|
-
// Middleware (pages/_middleware.rose) runs exactly once per request, before anything
|
|
724
|
-
// else: a returned Response short-circuits the whole request …
|
|
725
680
|
const apiPath0 = pathnameOf(req.url);
|
|
726
681
|
const isPagePost = req.method === 'POST' && !ssrModule.isApi(apiPath0);
|
|
727
682
|
if (!isPagePost && ssrModule.middleware) {
|
|
@@ -731,8 +686,6 @@ function serveStatic(dir: string, isr = false, dev = false): (req: any, res: any
|
|
|
731
686
|
return;
|
|
732
687
|
}
|
|
733
688
|
}
|
|
734
|
-
// API routes (pages/api/*.rose) dispatch FIRST: the /api namespace answers JSON,
|
|
735
|
-
// never the static shell or an HTML page …
|
|
736
689
|
const apiPath = pathnameOf(req.url);
|
|
737
690
|
if (ssrModule.isApi(apiPath)) {
|
|
738
691
|
readBody(req, res, async (body) => {
|
|
@@ -746,15 +699,14 @@ function serveStatic(dir: string, isr = false, dev = false): (req: any, res: any
|
|
|
746
699
|
headers,
|
|
747
700
|
body: body.length > 0 ? body : undefined,
|
|
748
701
|
});
|
|
749
|
-
// P0-1: an api handler reads the query from its Request's URL (the full one,
|
|
750
|
-
// query included) …
|
|
751
702
|
ssrModule.setQuery?.(queryOf(req.url));
|
|
752
703
|
let apiRes = await ssrModule.handleApi(req.method || 'GET', apiPath, request);
|
|
753
704
|
if (hookCtx) apiRes = await ssrModule.runResponseHooks(hookCtx, apiRes);
|
|
754
705
|
writeWebHeaders(apiRes, res);
|
|
755
706
|
res.statusCode = apiRes.status;
|
|
756
707
|
res.end(Buffer.from(await apiRes.arrayBuffer()));
|
|
757
|
-
} catch {
|
|
708
|
+
} catch (err) {
|
|
709
|
+
console.error(`rosetack: ${req.method} ${req.url} api handler failed:`, err instanceof Error ? err.stack ?? err.message : String(err));
|
|
758
710
|
res.statusCode = 500;
|
|
759
711
|
res.setHeader('Content-Type', 'application/json');
|
|
760
712
|
res.end('{"error":"api handler failed"}');
|
|
@@ -763,16 +715,12 @@ function serveStatic(dir: string, isr = false, dev = false): (req: any, res: any
|
|
|
763
715
|
return;
|
|
764
716
|
}
|
|
765
717
|
|
|
766
|
-
// POST: run the matched route's server action (progressive-enhancement form). This
|
|
767
|
-
// must precede the static lookup: prerendered files exist on disk and would otherwise …
|
|
768
718
|
if (req.method === 'POST') {
|
|
769
719
|
readBody(req, res, async (body) => {
|
|
770
720
|
try {
|
|
771
721
|
const form = await new Response(body, {
|
|
772
722
|
headers: { 'content-type': req.headers['content-type'] || 'application/x-www-form-urlencoded' },
|
|
773
723
|
}).formData();
|
|
774
|
-
// the middleware pass for page POSTs: it rides with the parsed FormData so it
|
|
775
|
-
// can read form fields, and its context seeds the action + render below
|
|
776
724
|
if (ssrModule.middleware) {
|
|
777
725
|
const mw = await ssrModule.runMiddleware(req, form);
|
|
778
726
|
if (mw) {
|
|
@@ -780,14 +728,10 @@ function serveStatic(dir: string, isr = false, dev = false): (req: any, res: any
|
|
|
780
728
|
return;
|
|
781
729
|
}
|
|
782
730
|
}
|
|
783
|
-
// P0-1: the POST is routed by pathname too, and its query (if the form was
|
|
784
|
-
// posted to /search?ref=x) reaches the render through $query() like every other …
|
|
785
731
|
ssrModule.setQuery?.(queryOf(req.url));
|
|
786
732
|
const page = await ssrModule.renderPage(pathnameOf(req.url || '/'), form);
|
|
787
733
|
await sendPage(req, res, ssrModule, hookCtx, page, pathnameOf(req.url || '/'));
|
|
788
734
|
} catch (err) {
|
|
789
|
-
// A silent "Bad request" is how a framework bug hides: the stack goes to stderr
|
|
790
|
-
// (the same rule the GET path follows) …
|
|
791
735
|
console.error(`rosetack: POST ${pathnameOf(req.url || '/')} failed:`, err instanceof Error ? err.stack : err);
|
|
792
736
|
if (!res.headersSent) {
|
|
793
737
|
res.statusCode = 400;
|
|
@@ -798,8 +742,6 @@ function serveStatic(dir: string, isr = false, dev = false): (req: any, res: any
|
|
|
798
742
|
return;
|
|
799
743
|
}
|
|
800
744
|
|
|
801
|
-
// P0-1: routing matches the PATHNAME. The query string rides along to the handlers
|
|
802
|
-
// ($query(), the api Request) but never into a route pattern …
|
|
803
745
|
let safe = path.normalize(pathnameOf(req.url || '/')).replace(/^(\.\.(\/)?)+/, '');
|
|
804
746
|
if (safe === '\\' || safe === '/') safe = '/';
|
|
805
747
|
let filePath = path.join(dir, safe);
|
|
@@ -810,26 +752,19 @@ function serveStatic(dir: string, isr = false, dev = false): (req: any, res: any
|
|
|
810
752
|
if (fs.existsSync(pubFile)) filePath = pubFile;
|
|
811
753
|
}
|
|
812
754
|
|
|
813
|
-
// Directory -> index.html (prerendered routes live at /<route>/index.html)
|
|
814
755
|
if (fs.existsSync(filePath) && fs.statSync(filePath).isDirectory()) {
|
|
815
756
|
filePath = path.join(filePath, 'index.html');
|
|
816
757
|
}
|
|
817
758
|
|
|
818
|
-
// Build-time precompression siblings (dist/<file>.br, read by the Go binary) are internal
|
|
819
|
-
// artifacts.
|
|
820
759
|
if (/\.(?:br|gz)$/i.test(safe)) {
|
|
821
760
|
const base = filePath.replace(/\.(?:br|gz)$/i, '');
|
|
822
761
|
if (fs.existsSync(base)) filePath = base;
|
|
823
762
|
}
|
|
824
763
|
|
|
825
|
-
// Serve real files directly - compressed + conditionally cached, so a repeat visit
|
|
826
|
-
// costs a 304 instead of the full document. Assets always take this path.
|
|
827
764
|
const isAsset = ASSET_EXT.has(path.extname(safe).toLowerCase());
|
|
828
765
|
const isDynamic = !isAsset && (ssrModule.dynamicRoutes as string[] | undefined)?.includes(pathnameOf(req.url));
|
|
829
766
|
if (!isDynamic && fs.existsSync(filePath) && fs.statSync(filePath).isFile()) {
|
|
830
767
|
const st = fs.statSync(filePath);
|
|
831
|
-
// ISR: a route exporting `revalidate = N` keeps its baked file for N seconds. Once stale,
|
|
832
|
-
// THIS request is still served from disk - stale-while-revalidate: instant TTFB …
|
|
833
768
|
const rev = isAsset ? undefined : ((ssrModule.revalidate as { pattern: string; seconds: number }[]) || [])
|
|
834
769
|
.find((r) => ssrModule.matchRoute(r.pattern, pathnameOf(req.url)));
|
|
835
770
|
if (isr && rev && Date.now() - st.mtimeMs > rev.seconds * 1000) {
|
|
@@ -841,8 +776,6 @@ function serveStatic(dir: string, isr = false, dev = false): (req: any, res: any
|
|
|
841
776
|
entry = {
|
|
842
777
|
mtimeMs: st.mtimeMs,
|
|
843
778
|
raw,
|
|
844
|
-
// A file's compressed forms are computed ONCE and then served from this cache
|
|
845
|
-
// forever …
|
|
846
779
|
br: zlib.brotliCompressSync(raw),
|
|
847
780
|
gzip: zlib.gzipSync(raw, { level: 9 }),
|
|
848
781
|
etag: `W/"${st.size}-${st.mtimeMs}"`,
|
|
@@ -862,19 +795,13 @@ function serveStatic(dir: string, isr = false, dev = false): (req: any, res: any
|
|
|
862
795
|
'.mp4': 'video/mp4',
|
|
863
796
|
'.mp3': 'audio/mpeg',
|
|
864
797
|
};
|
|
865
|
-
// An ISR route's file is swapped every `revalidate` seconds, so the cache must not
|
|
866
|
-
// outlive the window: revalidate every visit (a bodiless 304 when nothing changed) …
|
|
867
798
|
const fileHeaders: Record<string, string> = {
|
|
868
799
|
'Content-Type': types[ext] || 'application/octet-stream',
|
|
869
800
|
'Cache-Control': rev ? `public, max-age=0, stale-while-revalidate=${rev.seconds}` : 'public, max-age=3600',
|
|
870
801
|
'ETag': entry.etag,
|
|
871
802
|
'Vary': 'Accept-Encoding',
|
|
872
803
|
};
|
|
873
|
-
// Per-route response headers: a prerendered document carries the same policy the live
|
|
874
|
-
// render would send - the strict CSP plus the route's own exported headers.
|
|
875
804
|
if (ext === '.html') Object.assign(fileHeaders, pageHeaders(ssrModule, pathnameOf(req.url)));
|
|
876
|
-
// OnResponse on the file path too, so a header-adding plugin sees EVERY response and not
|
|
877
|
-
// just the rendered ones.
|
|
878
805
|
let status = 200;
|
|
879
806
|
if (hookCtx) {
|
|
880
807
|
const out = await ssrModule.runResponseHooks(hookCtx, new Response(null, { status, headers: fileHeaders }));
|
|
@@ -888,8 +815,6 @@ function serveStatic(dir: string, isr = false, dev = false): (req: any, res: any
|
|
|
888
815
|
res.end();
|
|
889
816
|
return;
|
|
890
817
|
}
|
|
891
|
-
// Dev answers the file uncompressed: the reload bridge injects into the body, and a
|
|
892
|
-
// compressed body has no `<head>` left to find.
|
|
893
818
|
const enc = devMode ? null : pickEncoding(req);
|
|
894
819
|
res.statusCode = status;
|
|
895
820
|
if (enc) {
|
|
@@ -901,26 +826,15 @@ function serveStatic(dir: string, isr = false, dev = false): (req: any, res: any
|
|
|
901
826
|
return;
|
|
902
827
|
}
|
|
903
828
|
|
|
904
|
-
// Otherwise render the route via SSR (dynamic routes, 404s, and every page route when
|
|
905
|
-
// a middleware exists: its per-request context must be live …
|
|
906
829
|
let broken = new Set<string>();
|
|
907
830
|
try {
|
|
908
831
|
broken = new Set(JSON.parse(fs.readFileSync(path.join(dir, 'broken.json'), 'utf-8')));
|
|
909
832
|
} catch { /* no manifest: nothing known-broken */ }
|
|
910
|
-
// P0-1: the pathname, never the raw url - see the static branch above. The query
|
|
911
|
-
// reaches the render through $query() (setQuery below) …
|
|
912
833
|
const safe2 = pathnameOf(req.url || '/');
|
|
913
|
-
// P0-1: the query is per request and belongs to the render, not the
|
|
914
|
-
// route - set once, before either path below reads $query().
|
|
915
834
|
ssrModule.setQuery?.(queryOf(req.url));
|
|
916
|
-
// P0-2: `buffer = true` routes take the buffered path even when they could stream …
|
|
917
835
|
if (!dev && !broken.has(safe2) && !ssrModule.isBuffered?.(safe2) && ssrModule.canStream(safe2) && !ssrModule.isNoJs(safe2)) {
|
|
918
836
|
const enc = pickEncoding(req);
|
|
919
|
-
// onResponse runs BEFORE the first flush, while the status and headers can still change:
|
|
920
|
-
// the hook is handed a bodyless Response carrying them …
|
|
921
837
|
let status = 200;
|
|
922
|
-
// The nonce is minted before the first flush, because a streamed response cannot change
|
|
923
|
-
// its headers afterwards - and the document's script tag is written into that same stream …
|
|
924
838
|
const nonce = nonceFor(ssrModule, safe2);
|
|
925
839
|
let headers: Record<string, any> = pageHeaders(ssrModule, safe2, nonce);
|
|
926
840
|
if (hookCtx) {
|
|
@@ -938,8 +852,6 @@ function serveStatic(dir: string, isr = false, dev = false): (req: any, res: any
|
|
|
938
852
|
res.setHeader('Content-Encoding', enc);
|
|
939
853
|
const compressor = createCompressor(enc);
|
|
940
854
|
compressor.pipe(res);
|
|
941
|
-
// The shell must reach the socket NOW. Without a flush zlib emits nothing until
|
|
942
|
-
// end() …
|
|
943
855
|
let flushed = false;
|
|
944
856
|
write = (chunk) => {
|
|
945
857
|
compressor.write(chunk);
|
|
@@ -948,32 +860,22 @@ function serveStatic(dir: string, isr = false, dev = false): (req: any, res: any
|
|
|
948
860
|
compressor.flush(zlib.constants.Z_FULL_FLUSH);
|
|
949
861
|
}
|
|
950
862
|
};
|
|
951
|
-
// pipe() forwards data but not errors, and an unhandled 'error' event kills the
|
|
952
|
-
// worker.
|
|
953
863
|
compressor.on('error', () => res.destroy());
|
|
954
864
|
done = () => compressor.end();
|
|
955
865
|
} else {
|
|
956
866
|
write = (chunk) => res.write(chunk);
|
|
957
867
|
done = () => res.end();
|
|
958
868
|
}
|
|
959
|
-
// The streamed shell opens before the render, so its <html
|
|
960
|
-
// lang>/<dir> come from the pathname (the server bundle's docAttrs)
|
|
961
869
|
const doc = ssrModule.docAttrs(safe2);
|
|
962
|
-
await ssrModule.renderPageStream(safe2, write, shellOpen(getStyles(), doc.lang, doc.dir), clientScriptTag(getClientSource(), nonce));
|
|
870
|
+
await ssrModule.renderPageStream(safe2, write, shellOpen(getStyles(), doc.lang, doc.dir, !ssrModule.shellOff(safe2)), clientScriptTag(getClientSource(), nonce));
|
|
963
871
|
done();
|
|
964
872
|
return;
|
|
965
873
|
}
|
|
966
|
-
// buffered: POST actions, unmatched routes (404), known-broken routes (500), and csr
|
|
967
|
-
// = false routes …
|
|
968
874
|
const page = await ssrModule.renderPage(safe2);
|
|
969
875
|
await sendPage(req, res, ssrModule, hookCtx, page, safe2);
|
|
970
876
|
}).catch((err: unknown) => {
|
|
971
|
-
// P0-4: a failure in the pipeline is a 500 with the reason on stderr, never a 9-byte
|
|
972
|
-
// 404 …
|
|
973
877
|
console.error(`rosetack: ${req.method} ${req.url} failed:`, err instanceof Error ? err.stack ?? err.message : err);
|
|
974
878
|
if (res.headersSent) {
|
|
975
|
-
// a stream already left: the status is committed, so the only honest
|
|
976
|
-
// move is to drop the socket and let the client retry
|
|
977
879
|
res.destroy();
|
|
978
880
|
return;
|
|
979
881
|
}
|
|
@@ -1059,54 +961,67 @@ async function freePort(from: number): Promise<number> {
|
|
|
1059
961
|
}
|
|
1060
962
|
|
|
1061
963
|
/**
|
|
1062
|
-
* The version
|
|
1063
|
-
*
|
|
1064
|
-
*
|
|
1065
|
-
*
|
|
1066
|
-
* is
|
|
964
|
+
* The FRAMEWORK's version - one source of truth, no constant to drift.
|
|
965
|
+
*
|
|
966
|
+
* Three layouts answer, in order:
|
|
967
|
+
* 1. src/FRAMEWORK_VERSION, a one-line stamp that ships beside the CLI
|
|
968
|
+
* source. It is the only candidate that survives EMBEDDING: a real app
|
|
969
|
+
* copies the framework's src/ into its own tree, where the nearest
|
|
970
|
+
* package.json is the APP's - which is how a banner ended up naming the
|
|
971
|
+
* app's version as the framework's for weeks, with no way to tell which
|
|
972
|
+
* framework build was actually running.
|
|
973
|
+
* 2. the package.json two directories up (this repo: the framework's own),
|
|
974
|
+
* 3. the one beside the bundle (the published package: dist-cli/ + src/).
|
|
975
|
+
* A test asserts the stamp equals package.json, so the two cannot drift.
|
|
1067
976
|
*/
|
|
1068
977
|
function version(): string {
|
|
1069
|
-
for (const rel of ['../../package.json', '../package.json']) {
|
|
978
|
+
for (const rel of ['../FRAMEWORK_VERSION', '../../FRAMEWORK_VERSION', '../../package.json', '../package.json']) {
|
|
1070
979
|
try {
|
|
1071
|
-
const
|
|
980
|
+
const raw = fs.readFileSync(fileURLToPath(new URL(rel, import.meta.url)), 'utf-8');
|
|
981
|
+
const v = rel.endsWith('FRAMEWORK_VERSION') ? raw.trim() : JSON.parse(raw).version;
|
|
1072
982
|
if (v) return v;
|
|
1073
983
|
} catch { /* not this layout */ }
|
|
1074
984
|
}
|
|
1075
985
|
return '0.0.0';
|
|
1076
986
|
}
|
|
1077
987
|
|
|
988
|
+
/**
|
|
989
|
+
* The PROJECT's version, when it is a different package from the framework.
|
|
990
|
+
* A project that embeds the CLI source (the way a real app does) has its own
|
|
991
|
+
* package.json, and a banner that named only that one left the operator
|
|
992
|
+
* unable to tell which FRAMEWORK build was actually running - the two
|
|
993
|
+
* versions advanced independently for weeks. The banner now names both:
|
|
994
|
+
* "rosetack v0.4.0 - project: my-app v0.1.1". Absent (running inside the
|
|
995
|
+
* framework repo itself, or a directory with no package.json) -> nothing.
|
|
996
|
+
*/
|
|
997
|
+
function projectTag(): string {
|
|
998
|
+
try {
|
|
999
|
+
const pkg = JSON.parse(fs.readFileSync(path.join(process.cwd(), 'package.json'), 'utf-8'));
|
|
1000
|
+
if (!pkg.version || pkg.name === 'rosetack') return '';
|
|
1001
|
+
return ` - project: ${pkg.name} v${pkg.version}`;
|
|
1002
|
+
} catch {
|
|
1003
|
+
return '';
|
|
1004
|
+
}
|
|
1005
|
+
}
|
|
1006
|
+
|
|
1078
1007
|
async function dev(): Promise<void> {
|
|
1079
|
-
console.log(`🌹 RoseTack v${version()} dev server starting...`);
|
|
1008
|
+
console.log(`🌹 RoseTack v${version()}${projectTag()} dev server starting...`);
|
|
1080
1009
|
try {
|
|
1081
1010
|
await build();
|
|
1082
1011
|
} catch (err) {
|
|
1083
|
-
// A broken .rose file must not prevent the server from starting; the
|
|
1084
|
-
// watcher below rebuilds as soon as the file is fixed.
|
|
1085
1012
|
console.error('Initial build failed (server still running):', err instanceof Error ? err.message : err);
|
|
1086
1013
|
}
|
|
1087
1014
|
|
|
1088
1015
|
let timeout: any;
|
|
1089
1016
|
fs.watch(SRC_DIR, { recursive: true }, () => {
|
|
1017
|
+
devBuildPending = true;
|
|
1090
1018
|
clearTimeout(timeout);
|
|
1091
|
-
timeout = setTimeout(
|
|
1092
|
-
try {
|
|
1093
|
-
console.log('Rebuilding...');
|
|
1094
|
-
await build();
|
|
1095
|
-
// Tell the open tabs. Without this the rebuild lands on disk and the browser keeps showing
|
|
1096
|
-
// the previous document until the developer thinks to refresh …
|
|
1097
|
-
devNotify();
|
|
1098
|
-
} catch (err) {
|
|
1099
|
-
// Never let a user-code error kill the dev server.
|
|
1100
|
-
console.error('Build failed (server still running):', err instanceof Error ? err.message : String(err));
|
|
1101
|
-
}
|
|
1102
|
-
}, 200);
|
|
1019
|
+
timeout = setTimeout(() => { void startDevBuild(); }, 200);
|
|
1103
1020
|
});
|
|
1104
1021
|
|
|
1105
1022
|
const http = await import('http');
|
|
1106
1023
|
const server = http.createServer(devWrap(serveStatic(OUT_DIR, false, true)));
|
|
1107
1024
|
|
|
1108
|
-
// P0-0: an occupied port hops to the next free one (and says so) instead of
|
|
1109
|
-
// killing the server with EADDRINUSE.
|
|
1110
1025
|
listenFree(server, PORT, (port) => {
|
|
1111
1026
|
console.log('🌹 http://localhost:' + port);
|
|
1112
1027
|
});
|
|
@@ -1115,56 +1030,26 @@ async function dev(): Promise<void> {
|
|
|
1115
1030
|
async function preview(): Promise<void> {
|
|
1116
1031
|
await build();
|
|
1117
1032
|
const http = await import('http');
|
|
1118
|
-
// isr=true: routes exporting `revalidate = N` are served stale-then-swapped
|
|
1119
|
-
// from disk . Dev passes nothing (it rebuilds on change).
|
|
1120
1033
|
const server = http.createServer(serveStatic(OUT_DIR, true));
|
|
1121
1034
|
|
|
1122
|
-
// P0-0: same hop as the dev server - a preview that cannot bind its port
|
|
1123
|
-
// moves to the next one and prints it.
|
|
1124
1035
|
listenFree(server, PORT, (port) => {
|
|
1125
|
-
console.log(`🌹 RoseTack v${version()} preview at http://localhost
|
|
1036
|
+
console.log(`🌹 RoseTack v${version()}${projectTag()} preview at http://localhost:${port}`);
|
|
1126
1037
|
});
|
|
1127
1038
|
}
|
|
1128
1039
|
|
|
1129
|
-
|
|
1130
|
-
* `rosetack serve` runs what `build` produced - no rebuild, no
|
|
1131
|
-
* watcher, production semantics (a preview that re-rendered on the fly
|
|
1132
|
-
* could serve a half-written file). Multi-core through the stdlib cluster:
|
|
1133
|
-
* the primary supervises and serves no traffic, the workers serve; every
|
|
1134
|
-
* request is logged; SIGTERM drains in-flight work and exits.
|
|
1135
|
-
*
|
|
1136
|
-
* Boundaries, stated plainly:
|
|
1137
|
-
* - each worker is its own process with its own dist/server.js module.
|
|
1138
|
-
* Module-scope state is therefore per-worker, which is what $store()
|
|
1139
|
-
* fixes: writes broadcast through the primary, reads stay
|
|
1140
|
-
* local-synchronous. ISR revalidation may run in more than one worker
|
|
1141
|
-
* for one route: the guard is per-worker and the cost is one duplicate
|
|
1142
|
-
* render.
|
|
1143
|
-
* - the signal-driven drain is POSIX behavior. On Windows a kill() is
|
|
1144
|
-
* abrupt by the platform's design, so the worker instead exits on the
|
|
1145
|
-
* primary's death (the disconnect handler below) - a killed primary must
|
|
1146
|
-
* never leave orphans holding the port.
|
|
1147
|
-
*/
|
|
1040
|
+
|
|
1148
1041
|
async function serve(): Promise<void> {
|
|
1149
1042
|
if (!fs.existsSync(path.join(OUT_DIR, 'server.js'))) {
|
|
1150
1043
|
console.error(`rosetack: ${OUT_DIR} has no server.js - run rosetack build first`);
|
|
1151
1044
|
process.exit(1);
|
|
1152
1045
|
}
|
|
1153
|
-
// .default: node:cluster is an `export =` module, so the dynamic import
|
|
1154
|
-
// hands back the namespace with the real module on `.default`
|
|
1155
1046
|
const cluster = (await import('node:cluster')).default as any;
|
|
1156
|
-
// Round-robin the accepts between workers. The default leaves the handout to the
|
|
1157
|
-
// operating system …
|
|
1158
1047
|
cluster.schedulingPolicy = cluster.SCHED_RR;
|
|
1159
1048
|
const os = await import('node:os');
|
|
1160
1049
|
const workers = Math.max(1, Number(process.env.rosetack_WORKERS) || os.cpus().length);
|
|
1161
1050
|
if (cluster.isPrimary) {
|
|
1162
|
-
// P0-0 (bug report): ONE port for the whole cluster, chosen once by the primary and
|
|
1163
|
-
// handed to every worker through the environment.
|
|
1164
1051
|
const port = await freePort(Number(process.env.PORT) || 3000);
|
|
1165
1052
|
for (let i = 0; i < workers; i++) cluster.fork({ PORT: String(port) });
|
|
1166
|
-
// The store relay. A worker broadcasts every $store write here; the primary forwards each
|
|
1167
|
-
// patch to every OTHER worker …
|
|
1168
1053
|
cluster.on('message', (worker: any, msg: any) => {
|
|
1169
1054
|
if (!msg || msg.type !== 'rosetack:store') return;
|
|
1170
1055
|
for (const w of Object.values<any>(cluster.workers ?? {})) {
|
|
@@ -1179,41 +1064,45 @@ async function serve(): Promise<void> {
|
|
|
1179
1064
|
process.on('SIGTERM', stop);
|
|
1180
1065
|
process.on('SIGINT', stop);
|
|
1181
1066
|
cluster.on('exit', () => { if (--live <= 0) process.exit(0); });
|
|
1182
|
-
console.log(`🌹 RoseTack v${version()} serve: ${workers} worker${workers > 1 ? 's' : ''} on http://localhost:${port} (cluster, bounded bodies, graceful shutdown, access log on stdout)`);
|
|
1067
|
+
console.log(`🌹 RoseTack v${version()}${projectTag()} serve: ${workers} worker${workers > 1 ? 's' : ''} on http://localhost:${port} (cluster, bounded bodies, graceful shutdown, access log on stdout)`);
|
|
1183
1068
|
return;
|
|
1184
1069
|
}
|
|
1185
|
-
// worker the primary's death is the worker's death: no orphan holding the port
|
|
1186
1070
|
process.on('disconnect', () => process.exit(0));
|
|
1187
|
-
// OnServe / onShutdown - the worker's lifecycle. A plugin that owns a resource (a
|
|
1188
|
-
// connection pool, a warm cache) opens it here and closes it in the drain …
|
|
1189
1071
|
let servicePlugins: any[] = [];
|
|
1190
1072
|
try {
|
|
1191
1073
|
servicePlugins = (await loadPlugins(SRC_DIR)).filter((p) => p && p.onServe);
|
|
1192
1074
|
} catch (err) {
|
|
1193
|
-
console.error('rosetack: rosetack.config.js failed to load for the serve hooks:', err instanceof Error ? err.message : err);
|
|
1075
|
+
console.error('rosetack: rosetack.config.js failed to load for the serve hooks:', err instanceof Error ? err.message : String(err));
|
|
1076
|
+
}
|
|
1077
|
+
const storeBridge = {
|
|
1078
|
+
install: (send: ((name: string, value: unknown) => void) | null) => {
|
|
1079
|
+
try { serverModule?.__installStoreTransport?.(send); } catch { /* a stale dist: no bridge, no crash */ }
|
|
1080
|
+
},
|
|
1081
|
+
deliver: (name: string, value: unknown) => {
|
|
1082
|
+
try { serverModule?.__deliverStorePatch?.(name, value); } catch { }
|
|
1083
|
+
},
|
|
1084
|
+
};
|
|
1085
|
+
try {
|
|
1086
|
+
await loadServer();
|
|
1087
|
+
} catch (err) {
|
|
1088
|
+
console.error('rosetack: dist/server.js failed to load for the serve hooks:', err instanceof Error ? err.message : String(err));
|
|
1194
1089
|
}
|
|
1195
1090
|
const http = await import('node:http');
|
|
1196
1091
|
const server = http.createServer(withAccessLog(serveStatic(OUT_DIR, true), `w${process.pid}`));
|
|
1197
|
-
// A client that stalls mid-request is dropped instead of holding a worker;
|
|
1198
|
-
// idle keep-alive sockets close so a drained worker can actually exit.
|
|
1199
1092
|
server.requestTimeout = 30_000;
|
|
1200
|
-
server.headersTimeout = 65_000;
|
|
1093
|
+
server.headersTimeout = 65_000;
|
|
1201
1094
|
server.keepAliveTimeout = 5_000;
|
|
1202
|
-
// P0-0: the worker binds the port the primary chose; if that one was taken in the
|
|
1203
|
-
// meantime it hops instead of dying with an unhandled 'error' …
|
|
1204
1095
|
listenFree(server, PORT, async (port) => {
|
|
1205
1096
|
console.log(`🌹 RoseTack worker ${process.pid} listening on http://localhost:${port}`);
|
|
1206
1097
|
for (const p of servicePlugins) {
|
|
1207
1098
|
try {
|
|
1208
|
-
await p.onServe({ port, workers });
|
|
1099
|
+
await p.onServe({ port, workers, store: storeBridge });
|
|
1209
1100
|
} catch (err) {
|
|
1210
|
-
console.error('rosetack: plugin', p.name, 'onServe failed:', err instanceof Error ? err.message : err);
|
|
1101
|
+
console.error('rosetack: plugin', p.name, 'onServe failed:', err instanceof Error ? err.message : String(err));
|
|
1211
1102
|
}
|
|
1212
1103
|
}
|
|
1213
1104
|
});
|
|
1214
1105
|
const stop = () => {
|
|
1215
|
-
// onShutdown first: close what onServe opened, then drain. A throwing
|
|
1216
|
-
// hook must not stop the drain - the process still exits on the timer.
|
|
1217
1106
|
for (const p of servicePlugins) {
|
|
1218
1107
|
if (!p.onShutdown) continue;
|
|
1219
1108
|
try {
|
|
@@ -1224,28 +1113,94 @@ async function serve(): Promise<void> {
|
|
|
1224
1113
|
console.error('rosetack: plugin', p.name, 'onShutdown failed:', err instanceof Error ? err.message : err);
|
|
1225
1114
|
}
|
|
1226
1115
|
}
|
|
1227
|
-
server.close(() => process.exit(0));
|
|
1228
|
-
server.closeIdleConnections?.();
|
|
1229
|
-
setTimeout(() => process.exit(0), 5000).unref();
|
|
1116
|
+
server.close(() => process.exit(0));
|
|
1117
|
+
server.closeIdleConnections?.();
|
|
1118
|
+
setTimeout(() => process.exit(0), 5000).unref();
|
|
1230
1119
|
};
|
|
1231
1120
|
process.on('SIGTERM', stop);
|
|
1232
1121
|
process.on('SIGINT', stop);
|
|
1233
1122
|
}
|
|
1234
1123
|
|
|
1124
|
+
|
|
1125
|
+
function templatesDir(): string | null {
|
|
1126
|
+
for (const rel of ['../../templates', '../templates']) {
|
|
1127
|
+
const p = fileURLToPath(new URL(rel, import.meta.url));
|
|
1128
|
+
if (fs.existsSync(p)) return p;
|
|
1129
|
+
}
|
|
1130
|
+
return null;
|
|
1131
|
+
}
|
|
1132
|
+
|
|
1133
|
+
/** The TypeScript-ready files every scaffolded project gets: the ambient
|
|
1134
|
+
* globals (editors and tsc both see them) and a strict tsconfig. */
|
|
1135
|
+
function writeTypeScriptReady(dir: string): void {
|
|
1136
|
+
fs.writeFileSync(path.join(dir, 'rosetack-env.d.ts'), `/// <reference types="rosetack" />\n`);
|
|
1137
|
+
fs.writeFileSync(path.join(dir, 'tsconfig.json'), JSON.stringify({
|
|
1138
|
+
compilerOptions: {
|
|
1139
|
+
target: 'ES2022',
|
|
1140
|
+
module: 'ESNext',
|
|
1141
|
+
moduleResolution: 'bundler',
|
|
1142
|
+
lib: ['ES2022', 'DOM', 'DOM.Iterable'],
|
|
1143
|
+
strict: true,
|
|
1144
|
+
noEmit: true,
|
|
1145
|
+
skipLibCheck: true,
|
|
1146
|
+
},
|
|
1147
|
+
include: ['rosetack-env.d.ts', 'src/**/*.ts'],
|
|
1148
|
+
}, null, 2) + '\n');
|
|
1149
|
+
}
|
|
1150
|
+
|
|
1151
|
+
|
|
1152
|
+
function copyTemplate(dir: string, name: string, display: string): void {
|
|
1153
|
+
const base = templatesDir();
|
|
1154
|
+
const shipped = base ? path.resolve(base, name) : '';
|
|
1155
|
+
const src = fs.existsSync(shipped) ? shipped : path.resolve(name);
|
|
1156
|
+
if (!fs.existsSync(src) || !fs.statSync(src).isDirectory()) {
|
|
1157
|
+
const available = base ? fs.readdirSync(base).join(', ') : '(none found)';
|
|
1158
|
+
console.error(`rosetack: no template '${name}' - available: ${available} (or pass a path to any project directory)`);
|
|
1159
|
+
process.exit(1);
|
|
1160
|
+
}
|
|
1161
|
+
fs.cpSync(src, dir, {
|
|
1162
|
+
recursive: true,
|
|
1163
|
+
filter: (s) => !/(^|[\\/])(node_modules|dist|\.git)([\\/]|$)/.test(s),
|
|
1164
|
+
});
|
|
1165
|
+
const pkgFile = path.join(dir, 'package.json');
|
|
1166
|
+
if (fs.existsSync(pkgFile)) {
|
|
1167
|
+
const pkg = JSON.parse(fs.readFileSync(pkgFile, 'utf8'));
|
|
1168
|
+
pkg.name = path.basename(dir);
|
|
1169
|
+
if (pkg.dependencies?.rosetack) pkg.dependencies.rosetack = `^${version()}`;
|
|
1170
|
+
pkg.devDependencies = { ...pkg.devDependencies, typescript: '^5.6.0' };
|
|
1171
|
+
fs.writeFileSync(pkgFile, JSON.stringify(pkg, null, 2) + '\n');
|
|
1172
|
+
}
|
|
1173
|
+
writeTypeScriptReady(dir);
|
|
1174
|
+
console.log(`🌹 RoseTack new: ${display}/ from the '${path.basename(src)}' template`);
|
|
1175
|
+
console.log(`\n cd ${display}`);
|
|
1176
|
+
console.log(` npm install && npm run dev`);
|
|
1177
|
+
console.log(` npm run build # then deploy dist/`);
|
|
1178
|
+
}
|
|
1179
|
+
|
|
1235
1180
|
/**
|
|
1236
1181
|
* `rosetack new <name>` - a starting project. The smallest thing that builds
|
|
1237
1182
|
* and runs and shows the syntax: one page (state, {#if}, {#each}, a scoped
|
|
1238
1183
|
* style), one README naming the three commands. Not a second demo app - the
|
|
1239
1184
|
* point is that a new developer's first `rosetack build` works in seconds.
|
|
1240
1185
|
*
|
|
1186
|
+
* `rosetack new <name> --template <t>` - the
|
|
1187
|
+
* official templates (blog, api, admin, site) copied verbatim, with the
|
|
1188
|
+
* dependency rewritten to the published package. A name that is not a
|
|
1189
|
+
* shipped template is resolved as a PATH, so any project directory works as
|
|
1190
|
+
* a template (a team's own starter, a checkout's examples/).
|
|
1191
|
+
*
|
|
1241
1192
|
* Trade-off: three files, written from strings. No template engine, no
|
|
1242
1193
|
* dependency, no `npm install` run on the developer's behalf (they may use
|
|
1243
1194
|
* pnpm/yarn/bun, and a surprise install is worse than a printed command).
|
|
1244
1195
|
*/
|
|
1245
1196
|
async function scaffold(): Promise<void> {
|
|
1246
|
-
const
|
|
1247
|
-
|
|
1248
|
-
|
|
1197
|
+
const args = argv.slice(1);
|
|
1198
|
+
const tplIdx = args.indexOf('--template');
|
|
1199
|
+
const template = tplIdx >= 0 ? args[tplIdx + 1] : null;
|
|
1200
|
+
const name = args.find((a, i) => !a.startsWith('-') && i !== (tplIdx >= 0 ? tplIdx + 1 : -1));
|
|
1201
|
+
if (!name || (tplIdx >= 0 && !template)) {
|
|
1202
|
+
const available = templatesDir() ? fs.readdirSync(templatesDir()!).join(', ') : 'blog, api, admin, site';
|
|
1203
|
+
console.log(`Usage: rosetack new <name> [--template <name>] (creates <name>/ with a page that builds; --template copies an official template - ${available} - or any project directory)`);
|
|
1249
1204
|
return;
|
|
1250
1205
|
}
|
|
1251
1206
|
const dir = path.resolve(name);
|
|
@@ -1253,6 +1208,12 @@ async function scaffold(): Promise<void> {
|
|
|
1253
1208
|
console.error(`rosetack: ${dir} already exists - pick another name`);
|
|
1254
1209
|
process.exit(1);
|
|
1255
1210
|
}
|
|
1211
|
+
|
|
1212
|
+
if (template) {
|
|
1213
|
+
copyTemplate(dir, template, name);
|
|
1214
|
+
return;
|
|
1215
|
+
}
|
|
1216
|
+
|
|
1256
1217
|
const pages = path.join(dir, 'src', 'pages');
|
|
1257
1218
|
fs.mkdirSync(pages, { recursive: true });
|
|
1258
1219
|
|
|
@@ -1268,33 +1229,13 @@ async function scaffold(): Promise<void> {
|
|
|
1268
1229
|
check: 'rosetack check',
|
|
1269
1230
|
},
|
|
1270
1231
|
dependencies: { rosetack: `^${version()}` },
|
|
1271
|
-
// TypeScript is a first-class citizen: .rose scripts are typed, and `npm run check`
|
|
1272
|
-
// type-checks every one of them with THIS project's TypeScript …
|
|
1273
1232
|
devDependencies: { typescript: '^5.6.0' },
|
|
1274
1233
|
}, null, 2) + '\n');
|
|
1275
1234
|
|
|
1276
|
-
|
|
1277
|
-
// pulled in from the installed package: editors and tsc both see them.
|
|
1278
|
-
fs.writeFileSync(path.join(dir, 'rosetack-env.d.ts'), `/// <reference types="rosetack" />\n`);
|
|
1279
|
-
fs.writeFileSync(path.join(dir, 'tsconfig.json'), JSON.stringify({
|
|
1280
|
-
compilerOptions: {
|
|
1281
|
-
target: 'ES2022',
|
|
1282
|
-
module: 'ESNext',
|
|
1283
|
-
moduleResolution: 'bundler',
|
|
1284
|
-
lib: ['ES2022', 'DOM', 'DOM.Iterable'],
|
|
1285
|
-
strict: true,
|
|
1286
|
-
noEmit: true,
|
|
1287
|
-
skipLibCheck: true,
|
|
1288
|
-
},
|
|
1289
|
-
// the env file first (it is what makes the globals visible), then any
|
|
1290
|
-
// .ts the project grows - .rose scripts are checked by `npm run check`
|
|
1291
|
-
include: ['rosetack-env.d.ts', 'src/**/*.ts'],
|
|
1292
|
-
}, null, 2) + '\n');
|
|
1235
|
+
writeTypeScriptReady(dir);
|
|
1293
1236
|
|
|
1294
1237
|
fs.writeFileSync(path.join(pages, 'index.rose'), `<script>
|
|
1295
|
-
|
|
1296
|
-
// The script block is TypeScript - interfaces, annotations, generics and
|
|
1297
|
-
// casts all compile, and \`npm run check\` type-checks them.
|
|
1238
|
+
|
|
1298
1239
|
interface Item { label: string }
|
|
1299
1240
|
|
|
1300
1241
|
let count = $state(0);
|
|
@@ -1303,8 +1244,8 @@ async function scaffold(): Promise<void> {
|
|
|
1303
1244
|
|
|
1304
1245
|
function increment() { $setState('count', count() + 1); }
|
|
1305
1246
|
function toggleList() { $setState('showList', !showList()); }
|
|
1306
|
-
|
|
1307
|
-
|
|
1247
|
+
|
|
1248
|
+
|
|
1308
1249
|
let first: Item = $data((): Item => ({ label: items()[0] ?? 'nothing yet' }));
|
|
1309
1250
|
</script>
|
|
1310
1251
|
|
|
@@ -1342,7 +1283,6 @@ npm run check # type-checks every .rose script
|
|
|
1342
1283
|
Add a route by adding a file: \`src/pages/about.rose\` serves \`/about\`.
|
|
1343
1284
|
\`src/pages/_layout.rose\` wraps every route, \`src/pages/_middleware.rose\`
|
|
1344
1285
|
runs before every request, \`src/pages/api/*.rose\` answers JSON.
|
|
1345
|
-
Full syntax: the README of the rosetack package.
|
|
1346
1286
|
`);
|
|
1347
1287
|
|
|
1348
1288
|
fs.writeFileSync(path.join(dir, '.gitignore'), 'node_modules/\ndist/\n');
|
|
@@ -1377,8 +1317,6 @@ async function check(): Promise<void> {
|
|
|
1377
1317
|
process.exit(1);
|
|
1378
1318
|
}
|
|
1379
1319
|
|
|
1380
|
-
// The project's typescript, resolved FROM the project: the framework must not drag its
|
|
1381
|
-
// own copy into a user's install …
|
|
1382
1320
|
let tsMod: typeof ts;
|
|
1383
1321
|
try {
|
|
1384
1322
|
const req = createRequire(pathToFileURL(path.join(SRC_DIR, 'package.json')));
|
|
@@ -1388,21 +1326,14 @@ async function check(): Promise<void> {
|
|
|
1388
1326
|
process.exit(1);
|
|
1389
1327
|
}
|
|
1390
1328
|
|
|
1391
|
-
// rosetack's ambient globals, resolved from the COMPILER's own location:
|
|
1392
|
-
// src/types/rosetack.d.ts is a sibling in the repo and two levels down in
|
|
1393
|
-
// the published package (same two layouts as the runtime entry).
|
|
1394
1329
|
const nextTo = (rel: string[]) => rel.map((r) => fileURLToPath(new URL(r, import.meta.url))).find((p) => fs.existsSync(p));
|
|
1395
1330
|
const typesFile = nextTo(['../types/rosetack.d.ts', '../src/types/rosetack.d.ts']);
|
|
1396
1331
|
if (!typesFile) {
|
|
1397
1332
|
console.error('rosetack: the type definitions (src/types/rosetack.d.ts) were not found next to the compiler');
|
|
1398
1333
|
process.exit(1);
|
|
1399
1334
|
}
|
|
1400
|
-
// The runtime source, for scripts that import helpers from './runtime.js' (the module the
|
|
1401
|
-
// compiler generates beside the intermediates).
|
|
1402
1335
|
const runtimeSource = nextTo(['../runtime/index.ts', '../src/runtime/index.ts']);
|
|
1403
1336
|
|
|
1404
|
-
// Each script becomes a virtual file NAMED after its .rose file, padded so a diagnostic's
|
|
1405
|
-
// line/column are the .rose file's own: the <script> tag sits on line L …
|
|
1406
1337
|
const norm = (f: string) => path.resolve(f).replace(/\\/g, '/');
|
|
1407
1338
|
const virtual = new Map<string, string>();
|
|
1408
1339
|
let checked = 0;
|
|
@@ -1410,7 +1341,7 @@ async function check(): Promise<void> {
|
|
|
1410
1341
|
const source = await fs.promises.readFile(file, 'utf-8');
|
|
1411
1342
|
const m = /<script>/.exec(source);
|
|
1412
1343
|
const script = scriptOf(source);
|
|
1413
|
-
if (!script) continue;
|
|
1344
|
+
if (!script) continue;
|
|
1414
1345
|
const tagLine = source.slice(0, m!.index + '<script>'.length).split('\n').length;
|
|
1415
1346
|
const wired = runtimeSource
|
|
1416
1347
|
? script.replace(/['"]\.\/runtime\.js['"]/g, JSON.stringify(runtimeSource.replace(/\\/g, '/')))
|
|
@@ -1423,14 +1354,12 @@ async function check(): Promise<void> {
|
|
|
1423
1354
|
return;
|
|
1424
1355
|
}
|
|
1425
1356
|
|
|
1426
|
-
// An imported component's binding IS its render function (the compiler rewrites `import
|
|
1427
|
-
// Card from '...Card.rose'` to `import { render as Card }`) …
|
|
1428
1357
|
const propType = (def: string | null): string => {
|
|
1429
|
-
if (!def) return 'unknown';
|
|
1358
|
+
if (!def) return 'unknown';
|
|
1430
1359
|
if (/^['"`]/.test(def)) return 'string';
|
|
1431
1360
|
if (/^-?\d+(\.\d+)?$/.test(def)) return 'number';
|
|
1432
1361
|
if (/^(true|false)$/.test(def)) return 'boolean';
|
|
1433
|
-
return 'unknown';
|
|
1362
|
+
return 'unknown';
|
|
1434
1363
|
};
|
|
1435
1364
|
const ROSE_IMPORT_RE = /['"](\.[^'"]+\.rose)['"]/g;
|
|
1436
1365
|
const declared = new Set<string>();
|
|
@@ -1441,7 +1370,7 @@ async function check(): Promise<void> {
|
|
|
1441
1370
|
const target = norm(path.resolve(path.dirname(file), spec[1]));
|
|
1442
1371
|
if (target === file || declared.has(target)) continue;
|
|
1443
1372
|
const targetSource = await fs.promises.readFile(target, 'utf-8').catch(() => null);
|
|
1444
|
-
if (targetSource === null) continue;
|
|
1373
|
+
if (targetSource === null) continue;
|
|
1445
1374
|
const props = extractExports(scriptOf(targetSource) ?? '').props;
|
|
1446
1375
|
virtual.set(`${target}.d.ts`, [
|
|
1447
1376
|
`declare function render(closes: unknown[], children: string, __props: { ${props.map((p) => `${p.name}?: ${propType(p.def)}`).join('; ')} }, __slots?: Record<string, unknown>): string;`,
|
|
@@ -1459,18 +1388,11 @@ async function check(): Promise<void> {
|
|
|
1459
1388
|
module: tsMod.ModuleKind.ESNext,
|
|
1460
1389
|
moduleResolution: tsMod.ModuleResolutionKind.Bundler,
|
|
1461
1390
|
lib: ['lib.es2022.d.ts', 'lib.dom.d.ts', 'lib.dom.iterable.d.ts'],
|
|
1462
|
-
// the virtual files are named after the .rose files (so a diagnostic points at the real
|
|
1463
|
-
// path) …
|
|
1464
1391
|
allowNonTsExtensions: true,
|
|
1465
|
-
// the rewired './runtime.js' import points at a real .ts source
|
|
1466
1392
|
allowImportingTsExtensions: true,
|
|
1467
|
-
// `types` is deliberately NOT set: the project's own @types packages (@types/node for
|
|
1468
|
-
// node:sqlite, say) load automatically, the way they do for the user's own .ts files.
|
|
1469
1393
|
skipLibCheck: true,
|
|
1470
1394
|
};
|
|
1471
1395
|
const host = tsMod.createCompilerHost(options);
|
|
1472
|
-
// @types discovery starts at the project root, not the process cwd - the
|
|
1473
|
-
// command works from anywhere, like every other rosetack command.
|
|
1474
1396
|
host.getCurrentDirectory = () => path.resolve(SRC_DIR);
|
|
1475
1397
|
const realRead = host.readFile.bind(host);
|
|
1476
1398
|
const realGet = host.getSourceFile.bind(host);
|
|
@@ -1481,11 +1403,7 @@ async function check(): Promise<void> {
|
|
|
1481
1403
|
return src ? tsMod.createSourceFile(f, src, version, true) : realGet(f, version, onError, shouldCreate);
|
|
1482
1404
|
};
|
|
1483
1405
|
|
|
1484
|
-
// rosetack's ambient globals as a program root: a global .d.ts contributes its
|
|
1485
|
-
// declarations to every file in the program …
|
|
1486
1406
|
const program = tsMod.createProgram([...virtual.keys(), typesFile], options, host);
|
|
1487
|
-
// Only the project's own scripts: an error inside @types/node or inside rosetack's
|
|
1488
|
-
// runtime source is not the user's bug …
|
|
1489
1407
|
const diagnostics = tsMod.getPreEmitDiagnostics(program)
|
|
1490
1408
|
.filter((d) => d.file && virtual.has(norm(d.file.fileName)));
|
|
1491
1409
|
if (diagnostics.length === 0) {
|
|
@@ -1493,7 +1411,6 @@ async function check(): Promise<void> {
|
|
|
1493
1411
|
return;
|
|
1494
1412
|
}
|
|
1495
1413
|
for (const d of diagnostics) {
|
|
1496
|
-
// paths relative to the project root, the way tsc prints them
|
|
1497
1414
|
const at = d.file ? tsMod.getLineAndCharacterOfPosition(d.file, d.start ?? 0) : null;
|
|
1498
1415
|
const where = d.file && at
|
|
1499
1416
|
? `${path.relative(SRC_DIR, d.file.fileName)}(${at.line + 1},${at.character + 1})`
|
|
@@ -1509,8 +1426,6 @@ async function check(): Promise<void> {
|
|
|
1509
1426
|
|
|
1510
1427
|
const argv = process.argv.slice(2);
|
|
1511
1428
|
const cmd = argv[0];
|
|
1512
|
-
// --json: failures print as a machine-readable envelope on stdout - the code, the file, the
|
|
1513
|
-
// line and the hint, one JSON object an agent can parse and act on.
|
|
1514
1429
|
const asJson = argv.includes('--json');
|
|
1515
1430
|
|
|
1516
1431
|
/** Print a failure the way its reader needs it. A RoseError is the
|
|
@@ -1538,4 +1453,4 @@ else if (cmd === 'serve') void serve().catch(reportFailure);
|
|
|
1538
1453
|
else if (cmd === 'new') void scaffold().catch(reportFailure);
|
|
1539
1454
|
else if (cmd === 'check') void check().catch(reportFailure);
|
|
1540
1455
|
else if (cmd === 'prompt') console.log(AI_PROMPT);
|
|
1541
|
-
else console.log('Usage: rosetack dev|build|preview|serve|new|check|prompt [dir] [--json] (dir defaults to the current directory; dist/ is written there; --json prints build failures as machine-readable JSON)');
|
|
1456
|
+
else console.log('Usage: rosetack dev|build|preview|serve|new|check|prompt [dir] [--json] [--static] (dir defaults to the current directory; dist/ is written there; --json prints build failures as machine-readable JSON; --static verifies the build is deployable with no server at all; `new <name> [--template blog|api|admin|site]` scaffolds a project)');
|