rosetack 0.1.3 → 0.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,475 @@
1
+ (globalThis as any).__rosetack_SKIP_MINIFY = true;
2
+
3
+ import http from 'node:http';
4
+ import { Readable } from 'node:stream';
5
+ import fs from 'node:fs';
6
+ import path from 'node:path';
7
+ import zlib from 'node:zlib';
8
+ import { createHash } from 'node:crypto';
9
+ import { AsyncLocalStorage } from 'node:async_hooks';
10
+ import { fileURLToPath } from 'node:url';
11
+ import { createEdgeHandler } from './edge.ts';
12
+ import { onShutdown, runShutdownHooks } from './shutdown.ts';
13
+ import { requestOrigin } from './origin.ts';
14
+
15
+ const dist = fileURLToPath(new URL('./', import.meta.url));
16
+ const port = Number(process.env.PORT || 8080);
17
+ let handle: ((request: Request) => Promise<Response>) | null = null;
18
+ let mod: any = null;
19
+ let warmList: string[] = [];
20
+
21
+ const requestAls = new AsyncLocalStorage<Record<string, unknown>>();
22
+
23
+ /** Run `fn` with a private per-request context bag. */
24
+ function runIsolated<T>(fn: () => T): T {
25
+ return requestAls.run({}, fn);
26
+ }
27
+
28
+ // Extra roots searched for baked assets, after `dist` itself.
29
+ let extraRoots: string[] | null = null;
30
+ function resolveStaticRoots(): string[] {
31
+ if (extraRoots) return extraRoots;
32
+ const seen = new Set<string>([dist]);
33
+ const add = (p: string) => {
34
+ if (p && !seen.has(p)) seen.add(p);
35
+ };
36
+ if (process.env.VERCEL || process.env.AWS_LAMBDA_FUNCTION_NAME) {
37
+ add(path.join(dist, '..'));
38
+ add(path.join(dist, '..', '..'));
39
+ add(path.resolve(dist, '..', 'public'));
40
+ add(path.resolve(dist, '..', 'oboext'));
41
+ }
42
+ add(path.join(dist, 'oboext'));
43
+ add(path.resolve(dist, '..', 'oboext'));
44
+ add(path.resolve(process.cwd(), 'oboext'));
45
+ extraRoots = [...seen];
46
+ return extraRoots;
47
+ }
48
+
49
+ // A request path that must never reach the dynamic render.
50
+ function isBakedAssetPath(pathname: string): boolean {
51
+ return (
52
+ pathname.startsWith('/public/') ||
53
+ pathname.startsWith('/icons/') ||
54
+ pathname.startsWith('/vendor/') ||
55
+ pathname === '/favicon.ico'
56
+ );
57
+ }
58
+
59
+ const earlyHintLinks: string[] = (() => {
60
+ try {
61
+ const html = fs.readFileSync(path.join(dist, 'index.html'), 'utf8');
62
+ const links: string[] = [];
63
+ for (const m of html.matchAll(/<script[^>]+src="([^"]+)"/g)) {
64
+ const v = `<${m[1]}>; rel=preload; as=script`;
65
+ if (!links.includes(v)) links.push(v);
66
+ }
67
+ for (const m of html.matchAll(/<link[^>]+rel="stylesheet"[^>]*>/g)) {
68
+ const href = /href="([^"]+)"/.exec(m[0])?.[1];
69
+ if (href) { const v = `<${href}>; rel=preload; as=style`; if (!links.includes(v)) links.push(v); }
70
+ }
71
+ for (const m of html.matchAll(/<link[^>]+href="([^"]+)"[^>]+rel="stylesheet"[^>]*>/g)) {
72
+ const v = `<${m[1]}>; rel=preload; as=style`;
73
+ if (!links.includes(v)) links.push(v);
74
+ }
75
+ return links;
76
+ } catch { return []; }
77
+ })();
78
+
79
+ const ready = createEdgeHandler(dist).then(async (h) => {
80
+ handle = h;
81
+ try {
82
+ mod = await import(new URL('./server.js', import.meta.url).href);
83
+ warmList = ['/', ...((mod.dynamicRoutes as string[]) || []).filter((r: string) => !r.includes(':'))];
84
+ mod.invalidateRenderCache?.();
85
+ } catch { /* warm list stays just the home route */ }
86
+ mod?.installContextStore?.({
87
+ getStore: () => requestAls.getStore(),
88
+ run: (store: Record<string, unknown>, fn: () => unknown) => requestAls.run(store, fn),
89
+ });
90
+ return h;
91
+ });
92
+
93
+ const shouldWarm = !process.env.VERCEL;
94
+ if (shouldWarm) ready.then(async (h) => {
95
+ for (const r of warmList) {
96
+ try {
97
+ const res = await runIsolated(() => h(new Request('http://localhost' + r)));
98
+ const buf = await res.arrayBuffer();
99
+ const suspect = res.status === 200 && res.headers.get('content-type')?.includes('text/html') && buf.byteLength < 2048;
100
+ console.log('[rosetack] warm', r, 'status=' + res.status, 'bytes=' + buf.byteLength, suspect ? 'SUSPECT-EMPTY' : '');
101
+ } catch (e) {
102
+ console.error('[rosetack] warm', r, 'FAILED:', (e as Error)?.stack ?? e);
103
+ }
104
+ }
105
+ }).catch((e) => console.error('[rosetack] warm loop aborted:', (e as Error)?.stack ?? e));
106
+
107
+ const hotCache = new Map<string, { raw: Buffer; br: Buffer; gzip: Buffer; headers: Record<string, string>; etag: string; fetchedAt: number; refreshing?: boolean }>();
108
+ const HOT_TTL = 10_000;
109
+
110
+ /**
111
+ * One access line per request on stdout - the same greppable shape the CLI's
112
+ * `rosetack serve` writes, so one grep works across every rosetack server.
113
+ *
114
+ * prod-server had NO access log at all: the platform request log showed a
115
+ * status and a duration, and the server itself said nothing, so a blank first
116
+ * visit was reported repeatedly with nothing to read. Every response exit in
117
+ * the http handler calls this, which makes a log export readable line by line
118
+ * against what the render actually produced.
119
+ */
120
+ function writeAccessLine(req: any, res: any, bytes: number): void {
121
+ console.log(`${new Date().toISOString().slice(0, 19)}Z ${req.method} ${req.url} ${res.statusCode} ${bytes}B`);
122
+ }
123
+
124
+ function fnv(s: string): string {
125
+ let h = 0x811c9dc5;
126
+ for (let i = 0; i < s.length; i++) {
127
+ h ^= s.charCodeAt(i);
128
+ h = (h * 0x01000193) >>> 0;
129
+ }
130
+ return h.toString(16);
131
+ }
132
+
133
+ async function refetchHot(pathname: string, cookieHeader: string): Promise<void> {
134
+ const headers: Record<string, string> = { 'user-agent': 'rosetack-hot' };
135
+ if (cookieHeader) headers.cookie = cookieHeader;
136
+ const response = await runIsolated(() => handle!(new Request('http://localhost' + pathname, { headers })));
137
+ const csp = response.headers.get('content-security-policy') || '';
138
+ const key = pathname + '|' + fnv(cookieHeader);
139
+ if (response.status !== 200 || csp.includes('nonce-')) {
140
+ hotCache.delete(key);
141
+ return;
142
+ }
143
+ const head: Record<string, string> = {};
144
+ response.headers.forEach((v, k) => { if (k !== 'content-length' && k !== 'date' && k !== 'content-encoding') head[k] = v; });
145
+ const raw = Buffer.from(await response.arrayBuffer());
146
+ const compressed = raw.length > 1024;
147
+ hotCache.set(key, {
148
+ raw,
149
+ br: compressed ? zlib.brotliCompressSync(raw) : raw,
150
+ gzip: compressed ? zlib.gzipSync(raw, { level: 9 }) : raw,
151
+ compressed,
152
+ headers: head,
153
+ etag: `W/"${raw.length}-${fnv(cookieHeader)}"`,
154
+ fetchedAt: Date.now(),
155
+ });
156
+ }
157
+
158
+ function warmHot(pathname: string, cookieHeader: string): void {
159
+ refetchHot(pathname, cookieHeader)
160
+ .catch(() => {
161
+ const e = hotCache.get(pathname + '|' + fnv(cookieHeader));
162
+ if (e) { e.refreshing = false; e.fetchedAt = Date.now() - HOT_TTL + 2000; }
163
+ })
164
+ .finally(() => {
165
+ const e = hotCache.get(pathname + '|' + fnv(cookieHeader));
166
+ if (e) e.refreshing = false;
167
+ });
168
+ }
169
+
170
+ function tryHot(req: http.IncomingMessage, res: http.ServerResponse): boolean {
171
+ if (req.method !== 'GET') return false;
172
+ const q = req.url || '/';
173
+ const qm = q.indexOf('?');
174
+ if (qm >= 0) return false;
175
+ const cookieHeader = String(req.headers.cookie || '');
176
+ const key = q + '|' + fnv(cookieHeader);
177
+ const entry = hotCache.get(key);
178
+ if (!entry) return false;
179
+ const age = Date.now() - entry.fetchedAt;
180
+ if (age > HOT_TTL && !entry.refreshing) {
181
+ entry.refreshing = true;
182
+ warmHot(q, cookieHeader);
183
+ }
184
+ res.statusCode = 200;
185
+ for (const k in entry.headers) res.setHeader(k, entry.headers[k]);
186
+ res.setHeader('ETag', entry.etag);
187
+ if (req.headers['if-none-match'] === entry.etag) {
188
+ res.statusCode = 304;
189
+ res.end();
190
+ writeAccessLine(req, res, 0);
191
+ return true;
192
+ }
193
+ const compressed = (entry as any).compressed !== false;
194
+ const accept = String(req.headers['accept-encoding'] || '');
195
+ const enc = compressed ? (/br\b/i.test(accept) ? 'br' : /gzip\b/i.test(accept) ? 'gzip' : null) : null;
196
+ if (enc) {
197
+ res.setHeader('Content-Encoding', enc);
198
+ const body = enc === 'br' ? entry.br : entry.gzip;
199
+ res.end(body);
200
+ writeAccessLine(req, res, body.length);
201
+ } else {
202
+ res.end(entry.raw);
203
+ writeAccessLine(req, res, entry.raw.length);
204
+ }
205
+ return true;
206
+ }
207
+
208
+ function fillHot(pathname: string, cookieHeader: string, response: Response): void {
209
+ const csp = response.headers.get('content-security-policy') || '';
210
+ if (response.status !== 200 || csp.includes('nonce-')) return;
211
+ const head: Record<string, string> = {};
212
+ response.headers.forEach((v, k) => { if (k !== 'content-length' && k !== 'date' && k !== 'content-encoding') head[k] = v; });
213
+ response.arrayBuffer().then((ab) => {
214
+ const raw = Buffer.from(ab);
215
+ hotCache.set(pathname + '|' + fnv(cookieHeader), {
216
+ raw,
217
+ compressed: raw.length > 1024,
218
+ br: raw.length > 1024 ? zlib.brotliCompressSync(raw) : raw,
219
+ gzip: raw.length > 1024 ? zlib.gzipSync(raw, { level: 9 }) : raw,
220
+ headers: head,
221
+ etag: `W/"${raw.length}-${fnv(cookieHeader)}"`,
222
+ fetchedAt: Date.now(),
223
+ });
224
+ }).catch(() => {});
225
+ }
226
+
227
+ const fileCache = new Map<string, { raw: Buffer; br: Buffer; gzip: Buffer; etag: string; mtimeMs: number }>();
228
+ const TYPES: Record<string, string> = {
229
+ '.html': 'text/html; charset=utf-8',
230
+ '.js': 'application/javascript; charset=utf-8',
231
+ '.css': 'text/css; charset=utf-8',
232
+ '.json': 'application/json; charset=utf-8',
233
+ '.svg': 'image/svg+xml',
234
+ '.png': 'image/png',
235
+ '.jpg': 'image/jpeg',
236
+ '.webp': 'image/webp',
237
+ '.ico': 'image/x-icon',
238
+ '.woff2': 'font/woff2',
239
+ '.txt': 'text/plain; charset=utf-8',
240
+ '.xml': 'application/xml',
241
+ '.webmanifest': 'application/manifest+json',
242
+ };
243
+
244
+ try {
245
+ const raw = fs.readFileSync(new URL('../.env', import.meta.url), 'utf-8');
246
+ for (const line of raw.split(/\r?\n/)) {
247
+ const t = line.trim();
248
+ if (!t || t.startsWith('#')) continue;
249
+ const eq = t.indexOf('=');
250
+ if (eq <= 0) continue;
251
+ const k = t.slice(0, eq).trim();
252
+ let v = t.slice(eq + 1).trim();
253
+ if ((v.startsWith('"') && v.endsWith('"')) || (v.startsWith("'") && v.endsWith("'"))) v = v.slice(1, -1);
254
+ if (!(k in process.env)) process.env[k] = v;
255
+ }
256
+ } catch { /* no .env: fine */ }
257
+ const REVALIDATE_TOKEN = process.env.rosetack_REVALIDATE_TOKEN || '';
258
+ let revalidateMod: any = null;
259
+
260
+ function handleRevalidate(req: http.IncomingMessage, res: http.ServerResponse): boolean {
261
+ if (req.method !== 'POST' || !req.url!.startsWith('/__rosetack/revalidate')) return false;
262
+ if (!REVALIDATE_TOKEN) { res.statusCode = 404; res.end(); return true; }
263
+ if (req.headers['x-rosetack-token'] !== REVALIDATE_TOKEN) {
264
+ res.statusCode = 403; res.setHeader('content-type', 'application/json');
265
+ res.end(JSON.stringify({ error: 'invalid token' })); return true;
266
+ }
267
+ let body = '';
268
+ req.on('data', (c) => { body += c; if (body.length > 1e6) req.destroy(); });
269
+ req.on('end', () => {
270
+ try {
271
+ if (!revalidateMod) revalidateMod = mod;
272
+ const payload = JSON.parse(body || '{}');
273
+ if (payload.all) {
274
+ revalidateMod.invalidateRenderCache();
275
+ res.end(JSON.stringify({ revalidated: true, scope: 'all' }));
276
+ } else {
277
+ let n = 0;
278
+ for (const p of payload.paths || []) n += revalidateMod.invalidatePath(String(p));
279
+ res.end(JSON.stringify({ revalidated: true, paths: (payload.paths || []).length, dropped: n }));
280
+ }
281
+ } catch (e: any) {
282
+ res.statusCode = 400; res.end(JSON.stringify({ error: String(e).slice(0, 120) }));
283
+ }
284
+ });
285
+ return true;
286
+ }
287
+
288
+ function serveStatic(req: http.IncomingMessage, res: http.ServerResponse, rawUrl: string): boolean {
289
+ let pathname: string;
290
+ try {
291
+ pathname = decodeURIComponent(new URL('http://localhost' + rawUrl).pathname);
292
+ } catch {
293
+ return false;
294
+ }
295
+ if (pathname.includes('\0') || pathname.includes('..')) return false;
296
+ const ext = path.extname(pathname).toLowerCase();
297
+ if (!TYPES[ext]) return false;
298
+ let filePath = '';
299
+ let st: fs.Stats | null = null;
300
+ for (const root of resolveStaticRoots()) {
301
+ const candidate = path.join(root, pathname);
302
+ if (!candidate.startsWith(root)) continue;
303
+ try {
304
+ const s = fs.statSync(candidate);
305
+ if (!s.isFile()) continue;
306
+ filePath = candidate;
307
+ st = s;
308
+ break;
309
+ } catch {
310
+ // not under this root; try the next one
311
+ }
312
+ }
313
+ if (!st) return false;
314
+ let entry = fileCache.get(filePath);
315
+ if (!entry || entry.mtimeMs !== st.mtimeMs) {
316
+ const raw = fs.readFileSync(filePath);
317
+ entry = {
318
+ raw,
319
+ compressed: raw.length > 1024,
320
+ br: raw.length > 1024 ? zlib.brotliCompressSync(raw) : raw,
321
+ gzip: raw.length > 1024 ? zlib.gzipSync(raw, { level: 9 }) : raw,
322
+ etag: `W/"${st.size}-${st.mtimeMs}"`,
323
+ mtimeMs: st.mtimeMs,
324
+ };
325
+ fileCache.set(filePath, entry);
326
+ if (fileCache.size > 500) fileCache.delete(fileCache.keys().next().value as string);
327
+ }
328
+ res.statusCode = 200;
329
+ res.setHeader('Content-Type', TYPES[ext]);
330
+ res.setHeader('ETag', entry.etag);
331
+ res.setHeader('Vary', 'Accept-Encoding');
332
+ const isEntryDoc = pathname === '/' || pathname.endsWith('/') || TYPES[ext].startsWith('text/html');
333
+ res.setHeader('Cache-Control', isEntryDoc ? 'public, max-age=0, must-revalidate' : 'public, max-age=3600');
334
+ if (req.headers['if-none-match'] === entry.etag) {
335
+ res.statusCode = 304;
336
+ res.end();
337
+ writeAccessLine(req, res, 0);
338
+ return true;
339
+ }
340
+ const compressed = (entry as any).compressed !== false;
341
+ const accept = String(req.headers['accept-encoding'] || '');
342
+ const enc = compressed ? (/br\b/i.test(accept) ? 'br' : /gzip\b/i.test(accept) ? 'gzip' : null) : null;
343
+ if (enc) {
344
+ res.setHeader('Content-Encoding', enc);
345
+ const body = enc === 'br' ? entry.br : entry.gzip;
346
+ res.end(body);
347
+ writeAccessLine(req, res, body.length);
348
+ } else {
349
+ res.end(entry.raw);
350
+ writeAccessLine(req, res, entry.raw.length);
351
+ }
352
+ return true;
353
+ }
354
+
355
+ const server = http.createServer(async (req, res) => {
356
+ try {
357
+ await ready;
358
+ if (handleRevalidate(req, res)) return;
359
+ if (req.method !== 'GET' && req.method !== 'HEAD') {
360
+ hotCache.clear();
361
+ const fn = (mod as any).invalidateRenderCache;
362
+ if (typeof fn === 'function') fn();
363
+ }
364
+ if (hotCache.size > 0 && tryHot(req, res)) return;
365
+ if (req.method === 'GET' && !req.headers.cookie && hotCache.size === 0) {
366
+ for (const r of warmList) warmHot(r, '');
367
+ }
368
+ if (hotCache.size > 0 && tryHot(req, res)) return;
369
+ if (req.method === 'GET' || req.method === 'HEAD') {
370
+ if (serveStatic(req, res, req.url || '/')) return;
371
+ let p = '/';
372
+ try {
373
+ p = decodeURIComponent(new URL('http://localhost' + (req.url || '/')).pathname);
374
+ } catch {
375
+ p = req.url || '/';
376
+ }
377
+ p = p.split('?')[0]!;
378
+ if (isBakedAssetPath(p)) {
379
+ res.statusCode = 404;
380
+ res.setHeader('Content-Type', 'text/plain; charset=utf-8');
381
+ res.setHeader('Cache-Control', 'public, max-age=60');
382
+ res.end('not found');
383
+ writeAccessLine(req, res, 0);
384
+ return;
385
+ }
386
+ }
387
+ const url = requestOrigin(req, port) + (req.url || '/');
388
+ const init: RequestInit = { method: req.method, headers: req.headers as any };
389
+ if (req.method !== 'GET' && req.method !== 'HEAD') {
390
+ (init as any).body = Readable.toWeb(req) as any;
391
+ (init as any).duplex = 'half';
392
+ }
393
+ const cookieHeader = String(req.headers.cookie || '');
394
+ if (earlyHintLinks.length && req.method === 'GET' && String(req.headers.accept ?? '').includes('text/html')) {
395
+ try { res.writeEarlyHints({ link: earlyHintLinks }); } catch { /* client gone: the render still finishes */ }
396
+ }
397
+ const replayable = req.method === 'GET' || req.method === 'HEAD';
398
+ let response: Response;
399
+ try {
400
+ response = await runIsolated(() => handle!(new Request(url, init)));
401
+ } catch (err) {
402
+ if (!replayable) throw err;
403
+ console.warn('[rosetack] render failed, retrying once:', (err as Error)?.message ?? err);
404
+ await new Promise((r) => setTimeout(r, 200));
405
+ response = await runIsolated(() => handle!(new Request(url, init)));
406
+ }
407
+ if (req.method === 'GET') fillHot(req.url || '/', cookieHeader, response.clone());
408
+ res.statusCode = response.status;
409
+ response.headers.forEach((v, k) => res.setHeader(k, v));
410
+ const htmlDoc = (response.headers.get('content-type') ?? '').startsWith('text/html');
411
+ const accept = String(req.headers['accept-encoding'] ?? '');
412
+ if (response.body && htmlDoc && (accept.includes('br') || accept.includes('gzip'))) {
413
+ const raw = Buffer.from(await response.arrayBuffer());
414
+ const etag = 'W/"' + createHash('sha1').update(raw).digest('base64url').slice(0, 24) + '"';
415
+ if (req.method === 'GET' && req.headers['if-none-match'] === etag) {
416
+ res.statusCode = 304;
417
+ res.end();
418
+ writeAccessLine(req, res, 0);
419
+ return;
420
+ }
421
+ res.setHeader('ETag', etag);
422
+ const compressed = accept.includes('br')
423
+ ? zlib.brotliCompressSync(raw)
424
+ : zlib.gzipSync(raw);
425
+ res.setHeader('Content-Encoding', accept.includes('br') ? 'br' : 'gzip');
426
+ res.setHeader('Content-Length', String(compressed.length));
427
+ res.end(compressed);
428
+ writeAccessLine(req, res, compressed.length);
429
+ } else if (response.body) {
430
+ const raw = Buffer.from(await response.arrayBuffer());
431
+ res.end(raw);
432
+ writeAccessLine(req, res, raw.length);
433
+ } else {
434
+ res.end();
435
+ writeAccessLine(req, res, 0);
436
+ }
437
+ } catch (err) {
438
+ console.error('[rosetack] request failed:', (err as Error)?.stack ?? err);
439
+ if (!res.headersSent) {
440
+ res.statusCode = 500;
441
+ res.setHeader('Content-Type', 'text/plain; charset=utf-8');
442
+ }
443
+ res.end('server error');
444
+ writeAccessLine(req, res, 13);
445
+ }
446
+ });
447
+
448
+ if (!process.env.VERCEL) {
449
+ server.listen(port, () => {
450
+ console.log(`🌹 RoseTack prod server on http://localhost:${port}`);
451
+ });
452
+
453
+ let stopping = false;
454
+ const stop = (signal: NodeJS.Signals) => {
455
+ if (stopping) return;
456
+ stopping = true;
457
+ const force = setTimeout(() => process.exit(1), 10_000);
458
+ force.unref?.();
459
+ server.close(() => {
460
+ void runShutdownHooks(signal).finally(() => {
461
+ clearTimeout(force);
462
+ process.exit(0);
463
+ });
464
+ });
465
+ server.closeIdleConnections?.();
466
+ };
467
+ process.on('SIGINT', () => stop('SIGINT'));
468
+ process.on('SIGTERM', () => stop('SIGTERM'));
469
+ }
470
+
471
+ export default server;
472
+
473
+ export { onShutdown, runShutdownHooks };
474
+
475
+ void mod?.invalidateRenderCache;
package/src/cli/prompt.ts CHANGED
@@ -1,17 +1,4 @@
1
- /**
2
- * The canonical .rose authoring contract, printed by `rosetack prompt`.
3
- *
4
- * Why a command and not a doc page: the audience is as often an AI agent as
5
- * a human, and the agent needs the contract at the moment it writes code,
6
- * not a URL to go read. One command, stdout, no network - the same shape as
7
- * every other tool an agent already shells out to.
8
- *
9
- * The content is the compiler's actual rules, in the order a page meets
10
- * them: file layout, the script block, the template, head and styles,
11
- * events and actions, the exports, the npm boundary, and the error
12
- * contract. Anything the compiler REFUSES is listed as a rule here, so a
13
- * correct page compiles on the first try.
14
- */
1
+ // The canonical .rose authoring contract, printed by `rosetack prompt`.
15
2
  export const AI_PROMPT = `# rosetack authoring contract (printed by \`rosetack prompt\`)
16
3
 
17
4
  rosetack is a zero-hydration web framework: a .rose file compiles to a server
@@ -56,6 +43,12 @@ Rules the compiler enforces (breaking one fails the build):
56
43
  type arguments ($state<Post[]>([])) are all erased from the shipped bundles.
57
44
  - $state / $data declarations are top-level statements. The declared name IS the
58
45
  getter: write count() in the template and the script, never bare count.
46
+ $persist is $state backed by localStorage: let theme = $persist('light') —
47
+ the value survives reloads (SSR renders the initial; the client re-seeds
48
+ from storage at boot).
49
+ $derived is computed state: let sq = $derived(n * n) — a read-only getter
50
+ that recomputes from the signals its expression reads; $setState on it is a
51
+ build error. Top-level only (in a function body, use a plain const arrow).
59
52
  - A route param (pages/blog/[id].rose) is read as state too: declare it
60
53
  (\`let id = $state('1')\`) and read id() - the server overwrites the default
61
54
  with the URL's value, and export const params = { id: [...] } bakes those
@@ -65,11 +58,84 @@ Rules the compiler enforces (breaking one fails the build):
65
58
  the value down as a prop.
66
59
  - Template interpolation {expr} is HTML-escaped. {@html expr} is the explicit
67
60
  trusted-HTML escape hatch - use it only for content you control.
68
- - Blocks: {#if cond}...{/if}, {#each items as item}...{/each},
69
- {#boundary}...{/boundary}. There is NO {:else} - nest a second {#if}.
61
+ {@debug a, b} logs those values (as they are AT that point in the render);
62
+ bare {@debug} also breaks into the debugger. Neither emits HTML. {@const name
63
+ = expr} is a template-level binding: it evaluates once and is visible to every
64
+ expression that follows in the same scope (use it to name a computed value
65
+ inside {#each} without re-evaluating, or to shorten a long expression).
66
+ - Blocks: {#if cond}...{:else if cond2}...{:else}...{/if},
67
+ {#each items as item, i}...{:else}...{/each} (i is the zero-based index, the
68
+ {:else} renders when the list is empty, and the item may be a DESTRUCTURING
69
+ pattern - {#each items as {name, price}} or {#each entries as [k, v]} - the
70
+ body then reads the properties/elements directly),
71
+ {#key expr}...{/key} (re-creates the
72
+ body whenever expr changes), {#boundary}...{:fallback}...{/boundary} (the
73
+ fallback renders on a throw; {$boundaryError()?.message} reads the caught
74
+ error), {#island name="x"}...{/island} (partial hydration) and
75
+ {#defer}...{/defer} (progressive render; hold=N keeps the skeleton up at
76
+ least N ms), and {#await promise}...{:then value}...{:catch error}...{/await}
77
+ (the server renders the pending branch, the client flips to the resolved
78
+ value once the promise settles, or to the caught error if it rejects; the
79
+ {:then} / {:catch} names are in scope only inside their branch, and {:catch}
80
+ is optional). There is NO {:else} branch of its own: a bare {:else} with no
81
+ block around it is a build error - inside {#each} it means "the list is
82
+ empty", inside {#if} it is the final else.
83
+ - Keyed each: {#each todos() as t (t.id)} — the key makes wire() reconcile:
84
+ rows whose key and rendered html are unchanged KEEP their DOM nodes (focus,
85
+ unbound input text, loaded images survive; reorders become moves). Rows
86
+ with handlers/actions/refs/transitions/components rebuild fresh. The key
87
+ needs a named item — {#each xs as x (x.id)}, not a destructuring pattern.
88
+ - Snippets: {#snippet name(a, b)}...{/snippet} defines a parameterized
89
+ fragment; {@render name(x, y)} calls it and inlines the markup. Define the
90
+ snippet BEFORE the render call (top-down execution order — the compiler
91
+ rejects the reverse). Reactive content inside works per call.
92
+ - Transitions: transition:fade (both directions), in:fade (enter only),
93
+ out:fade (mounts at rest, leave only). Built-ins: fade, slide, fly, zoom,
94
+ slide-up/down/left/right, scale, spin, blur, stagger; params via
95
+ transition:fade={300} or transition:fade={duration: 300} (the trailing
96
+ number wins), or the bare name (300 ms default). Custom: register
97
+ globalThis.__rosetackTransitions.NAME = (el, duration, phase) => cleanup? —
98
+ a transition:NAME that is not a built-in falls through to it (phase
99
+ 'both'/'in'/'out'; built-ins always win).
100
+ - $actionPending() is true while a server action is in flight: use it to
101
+ disable the submit button reactively ({#if $actionPending()}).
102
+ - $setState('k', (x) => x + 1) supports a FUNCTIONAL UPDATER: when the new
103
+ value is a function it receives the current value and returns the next one.
104
+ (State that must literally store a function cannot use this form.)
105
+ - <input type="number" bind:value={n}>: clearing the field stores 'null'
106
+ (NOT 'NaN') so bound math (n() + 1) stays clean instead of going NaN. The
107
+ empty field renders as '' on write-back.
108
+ - Scroll listeners are passive by default (they cannot preventDefault), which
109
+ keeps the constant scroll event off the main-thread critical path.
110
+ - Scoped CSS: component <style> rules scope under the component. Use
111
+ :global(X) to unscope one compound (.card :global(.md)); a selector made
112
+ only of :global(...) groups emits fully unscoped (:global(body){...}).
113
+ - animate:flip={duration: 300} (or animate:flip={300}) passes a DURATION
114
+ param to the FLIP animation; the trailing number is parsed even though object
115
+ params carry their own colons. Registered animation names work the same way.
116
+ - <select multiple bind:value={arr}> binds an ARRAY of selected values
117
+ (declare $state([])); state changes drive option.selected properties.
118
+ - Two-way binding: <input bind:value={q}> / <input type="checkbox"
119
+ bind:checked={on}> / <select bind:value={s}>. Numeric inputs coerce through
120
+ valueAsNumber. Radio groups: <input type="radio" value="free"
121
+ bind:group={plan}> - the group state holds the selected value and every
122
+ radio's checked state follows it. bind:this={ref} captures the ELEMENT into
123
+ a $state slot (declare it: let ref = $state(null)) - call ref().focus() or
124
+ measure it after mount. A bind:* name must be a $state declaration.
125
+ - Conditional attributes: class:NAME={expr} and style:PROP={expr} merge with
126
+ the tag's static class/style into one reactive attribute.
127
+ - Boolean attributes (checked/disabled/...) are presence-correct: a false
128
+ expression omits the attribute entirely.
129
+ - use:NAME attaches a registered element action: directives.NAME = (el, param)
130
+ => { ...; return { update: (p) => ..., destroy: () => ... } } (or return a
131
+ cleanup function). A reactive param: use:tooltip={text} - the action's
132
+ update half re-runs when text changes; the param arrives JSON-parsed.
70
133
  - A <slot> with attributes is a named slot and must declare its name:
71
134
  <slot name="row" item={post} />. A named slot must be a DIRECT child of the
72
- component tag - never inside another element or an {#if}/{#each} block.
135
+ component tag, OR wrapped by a single {#if}/{#each}/{#boundary} block (F21:
136
+ the block is reconstructed around the slot and the lifted content reads the
137
+ parent scope, so a gated slot still projects). A named slot inside a plain
138
+ wrapper element (a <div>, not a block) is still a build error.
73
139
  - Every component tag needs its matching close tag (or self-closes with />).
74
140
  - In <head>: <title>, <meta>, <link>, <style>, <script>, <noscript> all pass
75
141
  through. A <style> inside <head> is document CSS; a <style> in the body is
@@ -81,8 +147,19 @@ Rules the compiler enforces (breaking one fails the build):
81
147
 
82
148
  ## Events and server actions
83
149
 
84
- - on:click={handler} wires a client event. The handler is a named function from
85
- the script or an inline arrow: on:click={() => $setState('n', n() + 1)}.
150
+ - on:EVENT={handler} wires a client event - ANY event, not just click. The
151
+ handler is a named function from the script or an inline arrow:
152
+ on:click={() => $setState('n', n() + 1)}, on:keydown={noteKey}.
153
+ click/input/change/submit ride one delegated listener per event type; every
154
+ other event (keydown, focus, scroll, mouseenter, ...) is bound directly on
155
+ the element by wire(), so no handler is ever silently dead. |window /
156
+ |document move the binding onto the global instead (Escape closes the modal,
157
+ scroll, resize) - one target per handler.
158
+ Modifiers ride the event: on:submit|preventDefault={save} (supported:
159
+ |preventDefault, |stopPropagation, |self - only when the event target IS the
160
+ bound element, |once - unbind after the first run). capture/passive are NOT
161
+ supported: they are listener options and one delegated listener per event
162
+ type cannot carry per-element options.
86
163
  - A server action is an exported async function. Call it from a native form
87
164
  (method="POST", no JS needed - progressive enhancement) or from any event
88
165
  (on:click={like} - one POST, in-place adopt). Its return value is an