rosetack 0.1.4 → 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.
@@ -2,6 +2,7 @@
2
2
 
3
3
  import * as fs from 'fs';
4
4
  import * as path from 'path';
5
+ import * as os from 'os';
5
6
  import { pathToFileURL, fileURLToPath } from 'url';
6
7
  import * as esbuild from 'esbuild';
7
8
  import { RoseError, lineOf, lineAt } from './errors.js';
@@ -12,7 +13,7 @@ const COMPONENT_RE = /<script>([\s\S]*?)<\/script>/;
12
13
  const TEMPLATE_RE = /<template>([\s\S]*?)<\/template>/;
13
14
  const HEAD_RE = /<head>([\s\S]*?)<\/head>/;
14
15
  const STYLE_RE = /<style>([\s\S]*?)<\/style>/;
15
- const DECL_RE = /(?:let|const|var)\s+(\w+)[^=]*=\s*\$(state|data|kv|persist)\b/g;
16
+ const DECL_RE = /(?:let|const|var)\s+(\w+)[^=]*=\s*\$(state|data|kv|persist|derived)\b/g;
16
17
  const DECL_CAST_RE = /^\s+as\s+[^;\n]+/;
17
18
  const SETSTATE_RE = /\$setState\(([^,]+),\s*([^)]+)\)/g;
18
19
  const EVENT_RE = /on:(\w+)=\{([^}]+)\}/g;
@@ -112,6 +113,8 @@ export interface CompileResult {
112
113
  * baked file cannot carry a fresh nonce.
113
114
  */
114
115
  cspNonce?: boolean;
116
+ /** a route's script references globalThis.__rosetackAuth - emit the node:crypto auth helpers */
117
+ usesrosetackAuth?: boolean;
115
118
  /**
116
119
  * The component's props - `export let title = 'x'` in its script.
117
120
  * A prop is a plain value the caller passes per invocation (never a
@@ -875,6 +878,116 @@ function hoistImports(script: string): { imports: string; rest: string } {
875
878
  return { imports: imports.join('\n'), rest: rest.join('\n') };
876
879
  }
877
880
 
881
+ const __compileMemo = new Map<string, CompileResult>();
882
+ function compileMemoKey(
883
+ filePath: string,
884
+ publicDir: string,
885
+ scopeKey: string,
886
+ isApi: boolean,
887
+ registry: RoseRegistry,
888
+ ): string | null {
889
+ let st: fs.Stats;
890
+ try { st = fs.statSync(filePath); } catch { return null; }
891
+ const reg: string[] = [];
892
+ for (const [p, e] of registry) reg.push(`${p}#${e.index}:${e.scopeKey}:${e.slots.join('|')}`);
893
+ return [filePath, String(st.mtimeMs), String(st.size), scopeKey, isApi ? '1' : '0', reg.join(';')].join('\u0000');
894
+ }
895
+ const __compilerStamp = (() => {
896
+ try { return String(fs.statSync(fileURLToPath(import.meta.url)).mtimeMs); } catch { return 'noid'; }
897
+ })();
898
+ const __diskCacheDir = (() => {
899
+ try {
900
+ const dir = path.join(os.tmpdir(), 'rosetack-compile-cache');
901
+ fs.mkdirSync(dir, { recursive: true });
902
+ return dir;
903
+ } catch { return null; }
904
+ })();
905
+ let __diskWrites = 0;
906
+ function __fnv1a(str: string): string {
907
+ let h = 0x811c9dc5;
908
+ for (let i = 0; i < str.length; i++) {
909
+ h ^= str.charCodeAt(i);
910
+ h = Math.imul(h, 0x01000193);
911
+ }
912
+ return (h >>> 0).toString(16).padStart(8, '0');
913
+ }
914
+ // Assets inlined at compile time travel inside the cached module, so a public/ edit has to
915
+ // invalidate it: before this …
916
+ const __publicFpCache = new Map<string, { key: string; at: number }>();
917
+ function publicFingerprint(publicDir: string): string {
918
+ const now = Date.now();
919
+ const cached = __publicFpCache.get(publicDir);
920
+ if (cached && now - cached.at < 500) return cached.key;
921
+ const parts: string[] = [];
922
+ const walk = (rel: string): void => {
923
+ let entries: { name: string; isDirectory(): boolean }[];
924
+ try { entries = fs.readdirSync(path.join(publicDir, rel), { withFileTypes: true }); } catch { return; }
925
+ entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
926
+ for (const e of entries) {
927
+ const r = rel ? rel + '/' + e.name : e.name;
928
+ if (e.isDirectory()) { walk(r); continue; }
929
+ try {
930
+ const s = fs.statSync(path.join(publicDir, r));
931
+ parts.push(r + '\u0001' + String(s.mtimeMs) + '\u0001' + String(s.size));
932
+ } catch { parts.push(r + '\u0001gone'); }
933
+ }
934
+ };
935
+ walk('');
936
+ const key = '__pub(' + __fnv1a(parts.join('\u0002')) + ')';
937
+ __publicFpCache.set(publicDir, { key, at: now });
938
+ return key;
939
+ }
940
+ function __diskFile(key: string): string {
941
+ return path.join(__diskCacheDir!, __fnv1a(key + '|' + __compilerStamp) + '.json');
942
+ }
943
+ function __diskGet(key: string): CompileResult | null {
944
+ if (!__diskCacheDir || process.env.rosetack_NO_DISK_CACHE === '1') return null;
945
+ try {
946
+ const obj = JSON.parse(fs.readFileSync(__diskFile(key), 'utf-8'));
947
+ if (obj && typeof obj === 'object' && typeof (obj as any).ssr === 'string') return obj as CompileResult;
948
+ } catch { /* miss / corrupt: fall through to fresh compile */ }
949
+ return null;
950
+ }
951
+ function __diskSet(key: string, result: CompileResult): void {
952
+ if (!__diskCacheDir || process.env.rosetack_NO_DISK_CACHE === '1') return;
953
+ try {
954
+ fs.writeFileSync(__diskFile(key), JSON.stringify(result));
955
+ if ((__diskWrites++ & 511) === 0) {
956
+ try {
957
+ const entries = fs.readdirSync(__diskCacheDir!);
958
+ if (entries.length > 5000) {
959
+ for (const e of entries) { try { fs.unlinkSync(path.join(__diskCacheDir!, e)); } catch { /* ignore */ } }
960
+ }
961
+ } catch { /* ignore */ }
962
+ }
963
+ } catch { /* disk full / permission: ignore, in-process memo still holds */ }
964
+ }
965
+
966
+ async function compileComponentMemo(
967
+ filePath: string,
968
+ publicDir: string,
969
+ scopeKey: string,
970
+ isApi: boolean,
971
+ plugins: Plugin[],
972
+ registry: RoseRegistry,
973
+ ): Promise<CompileResult> {
974
+ if (plugins.length > 0) return compileComponent(filePath, publicDir, scopeKey, isApi, plugins, registry);
975
+ const key = compileMemoKey(filePath, publicDir, scopeKey, isApi, registry);
976
+ if (key) {
977
+ const hit = __compileMemo.get(key);
978
+ if (hit) return { ...hit };
979
+ const disk = __diskGet(key);
980
+ if (disk) return disk;
981
+ }
982
+ const result = await compileComponent(filePath, publicDir, scopeKey, isApi, plugins, registry);
983
+ if (key) {
984
+ if (__compileMemo.size > 500) __compileMemo.clear();
985
+ __compileMemo.set(key, result);
986
+ __diskSet(key, result);
987
+ }
988
+ return result;
989
+ }
990
+
878
991
  export async function compileComponent(filePath: string, publicDir: string, scopeKey: string, isApi = false, plugins: Plugin[] = [], registry: RoseRegistry = new Map()): Promise<CompileResult> {
879
992
  let source = await fs.promises.readFile(filePath, 'utf-8');
880
993
  for (const p of plugins) {
@@ -929,6 +1042,7 @@ export async function compileComponent(filePath: string, publicDir: string, scop
929
1042
  const scriptMatch = source.match(COMPONENT_RE);
930
1043
  const roseResolved = resolveRoseImports(scriptMatch?.[1] ?? '', filePath, registry);
931
1044
  const rawScript = roseResolved.script;
1045
+ const usesrosetackAuth = rawScript.includes('__rosetackAuth');
932
1046
  const roseImports = roseResolved.imports;
933
1047
  const { imports: importStmts, rest: scriptNoImports } = hoistImports(rawScript);
934
1048
  if (path.basename(filePath) !== '_middleware.rose') {
@@ -1070,9 +1184,10 @@ export async function compileComponent(filePath: string, publicDir: string, scop
1070
1184
  if (/<form[^>]*\son:[a-z]+\s*=/i.test(source) || /\$action:|data-on-/.test(source)) {
1071
1185
  clientReasons.push('a form bound to a client dispatch ($action)');
1072
1186
  }
1073
- const lifecycle = rawScript.match(/\b(?:onMount|onCleanup|refresh|adopt|\$action|\$setState)\s*\(/);
1187
+ const lifecycle = rawScript.match(/\b(?:onMount|onCleanup|refresh|adopt)\s*\(|(?:\$action|\$effect)\s*\(/);
1074
1188
  if (lifecycle) clientReasons.push(`${lifecycle[0].replace(/\s*\($/, '')}()`);
1075
1189
  if (source.includes('{#defer')) clientReasons.push('{#defer} progressive content');
1190
+ if (source.includes('{#await')) clientReasons.push('{#await} async block');
1076
1191
  const needsClient = clientReasons.length > 0;
1077
1192
 
1078
1193
  const jsWarnings: string[] = [];
@@ -1105,6 +1220,8 @@ export async function compileComponent(filePath: string, publicDir: string, scop
1105
1220
 
1106
1221
  const decls = extractDecls(script);
1107
1222
  const stateDecls = decls.filter((d) => d.kind === 'state' || d.kind === 'kv' || d.kind === 'persist');
1223
+ const derivedNames = decls.filter((d) => d.kind === 'derived').map((d) => d.name);
1224
+ const callifyNames = [...stateDecls.map((s) => s.name), ...derivedNames];
1108
1225
 
1109
1226
  const setterNames = new Map<string, string>();
1110
1227
  stateDecls.forEach((s) => setterNames.set(s.name, `set${capitalize(s.name)}`));
@@ -1119,17 +1236,20 @@ export async function compileComponent(filePath: string, publicDir: string, scop
1119
1236
  if (d.kind === 'persist') {
1120
1237
  return `const [${d.name}, ${setterNames.get(d.name)!}] = persistState(${JSON.stringify(key)}, ${d.expr});`;
1121
1238
  }
1239
+ if (d.kind === 'derived') {
1240
+ return `const ${d.name} = () => (${callifyStateReads(d.expr, callifyNames)});`;
1241
+ }
1122
1242
  if (d.kind === 'kv') {
1123
1243
  const mTtl = /^(.*)\s*,\s*(\d+)\s*$/s.exec(d.expr);
1124
1244
  const fnExpr = mTtl ? mTtl[1] : d.expr;
1125
1245
  const ttl = mTtl ? mTtl[2] : '300';
1126
- return `const __had_${d.name} = hasState(${JSON.stringify(key)});
1246
+ return `const __seeded_${d.name} = isSeeded(${JSON.stringify(key)});
1127
1247
  const [${d.name}, set${capitalize(d.name)}] = state(${JSON.stringify(key)}, null);
1128
- if (!__had_${d.name}) set${capitalize(d.name)}(await globalThis.__rosetackKvApi.kvMemo(${JSON.stringify('__kvh:' + scopeKey + ':' + d.name)}, ${fnExpr}, ${ttl}));`;
1248
+ if (!__seeded_${d.name}) { const __v_${d.name} = await globalThis.__rosetackKvApi.kvMemo(${JSON.stringify('__kvh:' + scopeKey + ':' + d.name)}, ${fnExpr}, ${ttl}); set${capitalize(d.name)}(__v_${d.name}); markSeeded(${JSON.stringify(key)}); }`;
1129
1249
  }
1130
- return `const __had_${d.name} = hasState(${JSON.stringify(key)});
1250
+ return `const __seeded_${d.name} = isSeeded(${JSON.stringify(key)});
1131
1251
  const [${d.name}, set${capitalize(d.name)}] = state(${JSON.stringify(key)}, null);
1132
- if (!__had_${d.name}) set${capitalize(d.name)}(await $data(${fn}));`;
1252
+ if (!__seeded_${d.name}) { const __v_${d.name} = await $data(${fn}); set${capitalize(d.name)}(__v_${d.name}); markSeeded(${JSON.stringify(key)}); }`;
1133
1253
  };
1134
1254
 
1135
1255
  const nestedDecls: (typeof decls)[number][] = [];
@@ -1137,7 +1257,14 @@ if (!__had_${d.name}) set${capitalize(d.name)}(await $data(${fn}));`;
1137
1257
  let pos = 0;
1138
1258
  decls.forEach((d, i) => {
1139
1259
  const top = braceDepthAt(script, d.start) === 0;
1140
- if (!top) nestedDecls.push(d);
1260
+ if (!top) {
1261
+ if (d.kind === 'derived') {
1262
+ throw new Error(
1263
+ `${filePath}: $derived must be a top-level declaration - inside a function body a plain const arrow already does this natively`,
1264
+ );
1265
+ }
1266
+ nestedDecls.push(d);
1267
+ }
1141
1268
  spliced += script.slice(pos, d.start) + (top ? `'__rvdecl${i}__';` : '');
1142
1269
  pos = d.end;
1143
1270
  });
@@ -1145,28 +1272,33 @@ if (!__had_${d.name}) set${capitalize(d.name)}(await $data(${fn}));`;
1145
1272
 
1146
1273
  let cleanScript = spliced.replace(SETSTATE_RE, (_, key, val) => {
1147
1274
  const trimmedKey = key.trim().replace(/^['"`]|['"`]$/g, '');
1275
+ if (derivedNames.includes(trimmedKey)) {
1276
+ throw new Error(
1277
+ `${filePath}: $setState('${trimmedKey}', ...) - a $derived value is read-only; make it $state or derive a different expression`,
1278
+ );
1279
+ }
1148
1280
  const setter = setterNames.get(trimmedKey) || `set${capitalize(trimmedKey)}`;
1149
1281
  return `${setter}(${val})`;
1150
1282
  });
1151
- cleanScript = callifyStateReads(cleanScript, stateDecls.map((s) => s.name));
1283
+ cleanScript = callifyStateReads(cleanScript, callifyNames);
1152
1284
  cleanScript = cleanScript.replace(/'__rvdecl(\d+)__';/g, (_m, i) => declCode(decls[Number(i)]));
1153
1285
 
1154
1286
  const stateDeclsCode = nestedDecls.filter((d) => d.kind === 'state').map(declCode).join('\n');
1155
1287
  const dataDeclsCode = nestedDecls.filter((d) => d.kind === 'data').map(declCode).join('\n');
1156
1288
 
1157
- const templateCalled = callifyTemplateExprs(template, stateDecls.map((s) => s.name));
1289
+ const templateCalled = callifyTemplateExprs(template, callifyNames);
1158
1290
  const imgDefaulted = templateCalled
1159
1291
  .replace(/<img\b(?![^>]*?\sloading=)/gi, '<img loading="lazy"')
1160
1292
  .replace(/<img\b(?![^>]*?\sdecoding=)/gi, '<img decoding="async"')
1161
1293
  const wired = wireEventBindings(imgDefaulted, actionNames, filePath);
1162
1294
 
1163
- const stateKeys = decls.map((d) => d.name);
1295
+ const stateKeys = decls.filter((d) => d.kind !== 'derived').map((d) => d.name);
1164
1296
 
1165
1297
  const bindBindings: Array<{ event: string; fn: string }> = [];
1166
1298
  let bindCounter = 0;
1167
1299
  const bindExpanded = wired.template.replace(
1168
- /\sbind:(value|checked|this)\s*=\s*\{([\w$]+)(?:\(\))?\}/g,
1169
- (whole, kind: string, name: string) => {
1300
+ /\sbind:(value|checked|this|open)\s*=\s*\{([\w$]+)(?:\(\))?\}/g,
1301
+ (whole, kind: string, name: string, offset: number, str: string) => {
1170
1302
  if (!stateKeys.includes(name)) {
1171
1303
  throw new Error(
1172
1304
  `${filePath}: bind:${kind}={${name}} must name a $state declaration` +
@@ -1174,6 +1306,23 @@ if (!__had_${d.name}) set${capitalize(d.name)}(await $data(${fn}));`;
1174
1306
  );
1175
1307
  }
1176
1308
  if (kind === 'this') return ` data-bind-this="${name}"`;
1309
+ const tagStart = str.lastIndexOf('<', offset);
1310
+ const tagText = tagStart >= 0 ? str.slice(tagStart, offset) : '';
1311
+ if (kind === 'value' && /^<select[\s>]/i.test(tagText) && /\smultiple\b/i.test(tagText)) {
1312
+ const setterM = setterNames.get(name)!;
1313
+ const hnameM = `__rvbind_${scopeKey.replace(/\W/g, '_')}_${bindCounter++}`;
1314
+ bindBindings.push({
1315
+ event: 'change',
1316
+ fn: `${hnameM}: (e) => ${setterM}(Array.from(e.target.selectedOptions, (o) => o.value))`,
1317
+ });
1318
+ return ` data-selmulti={${name}().join(',')} data-on-change="${hnameM}"`;
1319
+ }
1320
+ if (kind === 'open') {
1321
+ const setterO = setterNames.get(name)!;
1322
+ const hnameO = `__rvbind_${scopeKey.replace(/\W/g, '_')}_${bindCounter++}`;
1323
+ bindBindings.push({ event: 'toggle', fn: `${hnameO}: (e) => ${setterO}(e.target.open)` });
1324
+ return ` open={${name}()} data-on-toggle="${hnameO}"`;
1325
+ }
1177
1326
  const setter = setterNames.get(name)!;
1178
1327
  const evt = kind === 'checked' ? 'change' : 'input';
1179
1328
  const hname = `__rvbind_${scopeKey.replace(/\W/g, '_')}_${bindCounter++}`;
@@ -1182,7 +1331,7 @@ if (!__had_${d.name}) set${capitalize(d.name)}(await $data(${fn}));`;
1182
1331
  fn:
1183
1332
  kind === 'checked'
1184
1333
  ? `${hname}: (e) => ${setter}(e.target.checked)`
1185
- : `${hname}: (e) => { const t = e.target; ${setter}(t.type === 'number' || t.type === 'range' ? t.valueAsNumber : t.value); }`,
1334
+ : `${hname}: (e) => { const t = e.target; const raw = t.type === 'number' || t.type === 'range' ? t.valueAsNumber : t.value; ${setter}(typeof raw === 'number' && Number.isNaN(raw) ? null : raw); }`,
1186
1335
  });
1187
1336
  const evtAttr = kind === 'checked'
1188
1337
  ? ` data-on-change="${hname}"`
@@ -1267,11 +1416,15 @@ if (!__had_${d.name}) set${capitalize(d.name)}(await $data(${fn}));`;
1267
1416
  : ` data-use="${name}"`,
1268
1417
  );
1269
1418
  const classExpanded = expandClassDirectives(useExpanded, filePath);
1270
- const styleExpanded = expandStyleDirectives(classExpanded, filePath);
1271
- const keyExpanded = expandKeyBlocks(styleExpanded, filePath);
1419
+ const classMerged = mergeStaticClass(classExpanded);
1420
+ const styleExpanded = expandStyleDirectives(classMerged, filePath);
1421
+ const transExpanded = expandTransitionDirectives(styleExpanded, filePath);
1422
+ const animExpanded = expandAnimateDirectives(transExpanded, filePath);
1423
+ const keyExpanded = expandKeyBlocks(animExpanded, filePath);
1272
1424
  const elseExpanded = expandIfElse(keyExpanded);
1273
1425
  const deferExpanded = expandDeferBlocks(elseExpanded);
1274
- const fbExpanded = expandBoundaryFallbacks(deferExpanded.template, filePath);
1426
+ const awaitExpanded = expandAwaitBlocks(deferExpanded.template, filePath);
1427
+ const fbExpanded = expandBoundaryFallbacks(awaitExpanded.template, filePath);
1275
1428
  const ssrTemplate = rewriteQuotedExprAttrs(fbExpanded
1276
1429
  .replace(SLOT_NAMED_RE, (_w: unknown, attrs: string, fallback: string) => {
1277
1430
  const call = `{__slot(${encodeSlotCall(attrs)})}`;
@@ -1299,10 +1452,12 @@ if (!__had_${d.name}) set${capitalize(d.name)}(await $data(${fn}));`;
1299
1452
  const ssrExports = actions.length > 0 ? `${exportStmts}\n${actions.map((a) => a.stmt).join('\n')}` : exportStmts;
1300
1453
  const ssrGuard = guard ? `\n${guard}` : '';
1301
1454
  const isMiddleware = path.basename(filePath) === '_middleware.rose';
1455
+ const bootCode = deferBootCode(deferExpanded.count, deferExpanded.holds)
1456
+ + (awaitExpanded.blocks.length ? '\n' + awaitBootCode(awaitExpanded.blocks) : '');
1302
1457
  const ssr = isMiddleware
1303
1458
  ? `${RUNTIME_IMPORTS}\n\n${importStmts}\n\n${ssrExports}\n${ssrGuard}\n\n${cleanScript}\n`
1304
- : generateSSR(cleanScript + deferBootCode(deferExpanded.count, deferExpanded.holds), compiledTemplate, stateDeclsCode, ssrExports, compiledHead, props, hasNamedSlots, importStmts, isComponent, ssrGuard, actions.length > 0, dataDeclsCode);
1305
- const client = generateClient(cleanScript + deferBootCode(deferExpanded.count, deferExpanded.holds), compiledTemplate, stateDeclsCode, eventBindings, exportStmts, compiledHead, props, hasNamedSlots, importStmts, isComponent, dataDeclsCode);
1459
+ : generateSSR(cleanScript + bootCode, compiledTemplate, stateDeclsCode, ssrExports, compiledHead, props, hasNamedSlots, importStmts, isComponent, ssrGuard, actions.length > 0, dataDeclsCode);
1460
+ const client = generateClient(cleanScript + bootCode, compiledTemplate, stateDeclsCode, eventBindings, exportStmts, compiledHead, props, hasNamedSlots, importStmts, isComponent, dataDeclsCode);
1306
1461
 
1307
1462
  return {
1308
1463
  ssr: rewriteRoseImports(ssr, 'ssr'),
@@ -1327,6 +1482,7 @@ if (!__had_${d.name}) set${capitalize(d.name)}(await $data(${fn}));`;
1327
1482
  jsWarnings,
1328
1483
  headers,
1329
1484
  cspNonce,
1485
+ usesrosetackAuth,
1330
1486
  props,
1331
1487
  roseImports,
1332
1488
  isComponent,
@@ -1355,8 +1511,15 @@ function minifyDecls(block: string): string {
1355
1511
  * pass through unscoped (their from/to/to selectors are not selectors).
1356
1512
  * Global element rules (:root/html/body) belong in the shell's STYLES.
1357
1513
  */
1358
- function scopeCss(css: string, key: string): string {
1514
+ export function scopeCss(css: string, key: string): string {
1359
1515
  const attr = `[data-rosetack-c="${key}"]`;
1516
+ const scopeOneSelector = (s: string): string => {
1517
+ const t = s.trim();
1518
+ if (!t.includes(':global')) return `${attr} ${t}`;
1519
+ const stripped = t.replace(/:global\([^()]*\)/g, (m) => m.slice(8, -1)).trim();
1520
+ const outside = t.replace(/:global\([^()]*\)/g, '').trim();
1521
+ return outside ? `${attr} ${stripped}` : stripped;
1522
+ };
1360
1523
  const clean = css.replace(/\/\*[\s\S]*?\*\//g, '');
1361
1524
  let out = '';
1362
1525
  let prelude = '';
@@ -1376,7 +1539,7 @@ function scopeCss(css: string, key: string): string {
1376
1539
  if (sel.startsWith('@')) {
1377
1540
  out += `${sel}{${/^@(?:-[\w]+-)?keyframes/.test(sel) ? minifyDecls(block) : scopeCss(block, key)}}`;
1378
1541
  } else if (sel) {
1379
- const scoped = sel.split(',').map((s) => `${attr} ${s.trim()}`).join(',');
1542
+ const scoped = sel.split(',').map((s) => scopeOneSelector(s)).join(',');
1380
1543
  out += `${scoped}{${minifyDecls(block)}}`;
1381
1544
  }
1382
1545
  prelude = '';
@@ -1602,7 +1765,7 @@ function extractDecls(script: string): Decl[] {
1602
1765
  if (script[end] === ';') end++;
1603
1766
  decls.push({
1604
1767
  name: m[1],
1605
- kind: m[2] as 'state' | 'data' | 'persist',
1768
+ kind: m[2] as 'state' | 'data' | 'persist' | 'kv' | 'derived',
1606
1769
  expr: script.slice(open, i - 1).trim(),
1607
1770
  start: m.index,
1608
1771
  end,
@@ -1852,6 +2015,53 @@ function expandIfElseOnce(template: string): { template: string; changed: boolea
1852
2015
  return { template: out, changed };
1853
2016
  }
1854
2017
 
2018
+ /**
2019
+ * F32: a static class and a reactive class={expr} on ONE tag are two writers
2020
+ * for a single attribute - the HTML parser keeps the first, so the reactive
2021
+ * half silently never renders and the first update wipes the static value.
2022
+ * Merge: the static value becomes the BASE of the expression's result via an
2023
+ * inline wrapper - object results are seeded with { "static": true, ...rest },
2024
+ * string results are prefixed, null keeps the base. Runs after the class:
2025
+ * directive pass (which already fails on static+directive+reactive conflicts
2026
+ * it cannot own).
2027
+ */
2028
+ function mergeStaticClass(template: string): string {
2029
+ if (!/\sclass\s*=\s*"/.test(template) || !/\sclass\s*=\s*\{/.test(template)) return template;
2030
+ const TAG_RE = /<([a-zA-Z][^\s>/]*)((?:[^>"']|"[^"]*"|'[^']*')*?)(\/?)>/g;
2031
+ let out = '';
2032
+ let pos = 0;
2033
+ let m: RegExpExecArray | null;
2034
+ TAG_RE.lastIndex = 0;
2035
+ while ((m = TAG_RE.exec(template))) {
2036
+ const [whole, tag, attrs, selfClose] = m;
2037
+ const sm = /\sclass\s*=\s*"([^"]*)"/.exec(attrs);
2038
+ if (!sm) continue;
2039
+ const rm = /\sclass\s*=\s*\{/.exec(attrs);
2040
+ if (!rm || rm.index === sm.index) continue;
2041
+ const open = attrs.indexOf('{', rm.index);
2042
+ let depth = 1;
2043
+ let j = open + 1;
2044
+ while (j < attrs.length && depth > 0) {
2045
+ const ch = attrs[j];
2046
+ if (ch === '"' || ch === "'") { j = skipQuoted(attrs, j); continue; }
2047
+ if (ch === '{') depth++;
2048
+ else if (ch === '}') depth--;
2049
+ j++;
2050
+ }
2051
+ if (depth !== 0) continue;
2052
+ const expr = attrs.slice(open + 1, j - 1);
2053
+ const base = JSON.stringify(sm[1]);
2054
+ const merged = ` class={((v) => v == null ? ${base} : typeof v === 'object' ? ({ ${base}: true, ...v }) : (${base} + ' ' + v))(${expr})}`;
2055
+ const lo = Math.min(sm.index, rm.index);
2056
+ const hiEnd = Math.max(sm.index + sm[0].length, j);
2057
+ const newAttrs = attrs.slice(0, lo) + merged + attrs.slice(hiEnd);
2058
+ out += template.slice(pos, m.index) + `<${tag}${newAttrs}${selfClose}>`;
2059
+ pos = m.index + whole.length;
2060
+ }
2061
+ out += template.slice(pos);
2062
+ return out;
2063
+ }
2064
+
1855
2065
  /**
1856
2066
  * F2c (class: directive): `class:NAME={expr}` merges with the tag's static
1857
2067
  * class into ONE reactive class attribute whose closure concatenates the
@@ -1925,6 +2135,152 @@ function expandClassDirectives(template: string, filePath: string): string {
1925
2135
  * the expected precedence. Same quote-aware tag scanner and same
1926
2136
  * reactive-class={...} conflict rule as expandClassDirectives.
1927
2137
  */
2138
+
2139
+ /**
2140
+ * F20: `transition:fn` - enter/leave transitions.
2141
+ *
2142
+ * A `transition:fn` directive on an element tells the runtime to animate it
2143
+ * in (on mount) and out (on unmount). The directive is parsed here at build
2144
+ * time and emitted as a `data-transition` attribute the runtime reads to
2145
+ * pick the transition effect. Built-in transitions (fade, slide, fly) are
2146
+ * registered in the runtime and applied through the `transition()` helper.
2147
+ *
2148
+ * Syntax: `transition:fn` or `transition:fn={params}`.
2149
+ *
2150
+ * Example: `<div transition:fade>` or `<div transition:fade={duration: 300}>`.
2151
+ */
2152
+ function expandTransitionDirectives(template: string, filePath: string): string {
2153
+ if (!/\s(?:transition|in|out):/.test(template)) return template;
2154
+ const TAG_RE = /<([a-zA-Z][^\s>/]*)((?:[^>"']|"[^"]*"|'[^']*')*?)(\/?)>/g;
2155
+ let out = '';
2156
+ let pos = 0;
2157
+ let m: RegExpExecArray | null;
2158
+ TAG_RE.lastIndex = 0;
2159
+ while ((m = TAG_RE.exec(template))) {
2160
+ const [whole, tag, attrs, selfClose] = m;
2161
+ if (!attrs.includes('transition:') && !/\s(?:in|out):/.test(attrs)) continue;
2162
+ const pairs: Array<{ dir: string; name: string; params: string; start: number; end: number }> = [];
2163
+ const NAME_RE = /\s(transition|in|out):([\w-]+)(?:\s*=\s*\{)?/g;
2164
+ let nm: RegExpExecArray | null;
2165
+ while ((nm = NAME_RE.exec(attrs))) {
2166
+ let start = nm.index;
2167
+ let end = nm.index + nm[0].length;
2168
+ let params = '';
2169
+ if (nm[0].endsWith('{')) {
2170
+ let depth = 1;
2171
+ let i = end;
2172
+ while (i < attrs.length && depth > 0) {
2173
+ const ch = attrs[i];
2174
+ if (ch === '"' || ch === "'") { i = skipQuoted(attrs, i); continue; }
2175
+ if (ch === '{') depth++;
2176
+ else if (ch === '}') depth--;
2177
+ i++;
2178
+ }
2179
+ if (depth !== 0) {
2180
+ throw new RoseError('E-TEMPLATE', `${filePath}: transition:${nm[1]}={...} is missing its closing brace`, { file: filePath, hint: 'the transition params expression needs a matching } before the tag ends' });
2181
+ }
2182
+ params = attrs.slice(end, i - 1);
2183
+ end = i;
2184
+ }
2185
+ pairs.push({ dir: nm[1] === 'transition' ? '' : nm[1], name: nm[2], params, start, end });
2186
+ }
2187
+ if (pairs.length === 0) continue;
2188
+ let transitionValue = '';
2189
+ for (const p of pairs) {
2190
+ if (transitionValue) transitionValue += '|';
2191
+ transitionValue += (p.dir ? p.dir + ':' : '') + p.name + (p.params ? ':' + p.params : '');
2192
+ }
2193
+ let newAttrs = attrs;
2194
+ for (let k = pairs.length - 1; k >= 0; k--) {
2195
+ newAttrs = newAttrs.slice(0, pairs[k].start) + newAttrs.slice(pairs[k].end);
2196
+ }
2197
+ const transRe = /\sdata-transition\s*=\s*("([^"]*)"|'([^']*)'|\{[^}]*\})/;
2198
+ const tm = transRe.exec(newAttrs);
2199
+ if (tm) {
2200
+ const existing = tm[2] ?? tm[3] ?? '';
2201
+ newAttrs = newAttrs.replace(transRe, ` data-transition="${existing}${transitionValue ? (existing ? '|' : '') + transitionValue : ""}"`);
2202
+ } else {
2203
+ newAttrs = ` data-transition="${transitionValue}"` + newAttrs;
2204
+ }
2205
+ out += template.slice(pos, m.index) + `<${tag}${newAttrs}${selfClose}>`;
2206
+ pos = m.index + whole.length;
2207
+ }
2208
+ out += template.slice(pos);
2209
+ return out;
2210
+ }
2211
+
2212
+ /**
2213
+ * F21: `animate:fn` - FLIP (First/Last/Invert/Play) animations.
2214
+ *
2215
+ * A `animate:fn` directive on an element tells the runtime to animate it
2216
+ * when its position changes (e.g., list reordering). The directive is parsed
2217
+ * here at build time and emitted as a `data-animate` attribute the runtime
2218
+ * reads to pick the animation effect. Built-in animations (flip) are
2219
+ * registered in the runtime and applied through the `animate()` helper.
2220
+ *
2221
+ * Syntax: `animate:fn` or `animate:fn={params}`.
2222
+ *
2223
+ * Example: `<div animate:flip>` or `<div animate:flip={duration: 300}>`.
2224
+ */
2225
+ function expandAnimateDirectives(template: string, filePath: string): string {
2226
+ if (!template.includes('animate:')) return template;
2227
+ const TAG_RE = /<([a-zA-Z][^\s>/]*)((?:[^>"']|"[^"]*"|'[^']*')*?)(\/?)>/g;
2228
+ let out = '';
2229
+ let pos = 0;
2230
+ let m: RegExpExecArray | null;
2231
+ TAG_RE.lastIndex = 0;
2232
+ while ((m = TAG_RE.exec(template))) {
2233
+ const [whole, tag, attrs, selfClose] = m;
2234
+ if (!attrs.includes('animate:')) continue;
2235
+ const pairs: Array<{ name: string; params: string; start: number; end: number }> = [];
2236
+ const NAME_RE = /\sanimate:([\w-]+)(?:\s*=\s*\{)?/g;
2237
+ let nm: RegExpExecArray | null;
2238
+ while ((nm = NAME_RE.exec(attrs))) {
2239
+ let start = nm.index;
2240
+ let end = nm.index + nm[0].length;
2241
+ let params = '';
2242
+ if (nm[0].endsWith('{')) {
2243
+ let depth = 1;
2244
+ let i = end;
2245
+ while (i < attrs.length && depth > 0) {
2246
+ const ch = attrs[i];
2247
+ if (ch === '"' || ch === "'") { i = skipQuoted(attrs, i); continue; }
2248
+ if (ch === '{') depth++;
2249
+ else if (ch === '}') depth--;
2250
+ i++;
2251
+ }
2252
+ if (depth !== 0) {
2253
+ throw new RoseError('E-TEMPLATE', `${filePath}: animate:${nm[1]}={...} is missing its closing brace`, { file: filePath, hint: 'the animate params expression needs a matching } before the tag ends' });
2254
+ }
2255
+ params = attrs.slice(end, i - 1);
2256
+ end = i;
2257
+ }
2258
+ pairs.push({ name: nm[1], params, start, end });
2259
+ }
2260
+ let animateValue = '';
2261
+ for (const p of pairs) {
2262
+ if (animateValue) animateValue += '|';
2263
+ animateValue += p.name + (p.params ? ':' + p.params : '');
2264
+ }
2265
+ let newAttrs = attrs;
2266
+ for (let k = pairs.length - 1; k >= 0; k--) {
2267
+ newAttrs = newAttrs.slice(0, pairs[k].start) + newAttrs.slice(pairs[k].end);
2268
+ }
2269
+ const animRe = /\sdata-animate\s*=\s*("([^"]*)"|'([^']*)'|\{[^}]*\})/;
2270
+ const am = animRe.exec(newAttrs);
2271
+ if (am) {
2272
+ const existing = am[2] ?? am[3] ?? '';
2273
+ newAttrs = newAttrs.replace(animRe, ` data-animate="${existing}${animateValue ? (existing ? '|' : '') + animateValue : ""}"`);
2274
+ } else {
2275
+ newAttrs = ` data-animate="${animateValue}"` + newAttrs;
2276
+ }
2277
+ out += template.slice(pos, m.index) + `<${tag}${newAttrs}${selfClose}>`;
2278
+ pos = m.index + whole.length;
2279
+ }
2280
+ out += template.slice(pos);
2281
+ return out;
2282
+ }
2283
+
1928
2284
  function expandStyleDirectives(template: string, filePath: string): string {
1929
2285
  if (!template.includes('style:')) return template;
1930
2286
  const TAG_RE = /<([a-zA-Z][^\s>/]*)((?:[^>"']|"[^"]*"|'[^']*')*?)(\/?)>/g;
@@ -2061,6 +2417,7 @@ function expandIfElse(template: string): string { for (let pass = 0; pass < 10;
2061
2417
  }
2062
2418
 
2063
2419
  function expandDeferBlocks(template: string): { template: string; count: number; holds: number[] } {
2420
+
2064
2421
  if (!DEFER_ENABLED) {
2065
2422
  const openRe = /\{#defer(?:\s+hold=\\d+)?\}/g;
2066
2423
  let out = '';
@@ -2130,14 +2487,118 @@ function deferBootCode(count: number, holds: number[] = []): string {
2130
2487
  return code;
2131
2488
  }
2132
2489
 
2133
- function findBlock(src: string, kind: 'if' | 'each' | 'boundary' | 'island'): RegExpExecArray | null {
2490
+ interface AwaitBlock { n: number; expr: string; thenVar: string; catchVar: string }
2491
+ function expandAwaitBlocks(template: string, filePath: string): { template: string; blocks: AwaitBlock[] } {
2492
+ let out = '';
2493
+ let pos = 0;
2494
+ let n = 0;
2495
+ const blocks: AwaitBlock[] = [];
2496
+ for (;;) {
2497
+ const openAt = template.indexOf('{#await', pos);
2498
+ if (openAt < 0) break;
2499
+ let i = openAt + 7;
2500
+ let brace = 1;
2501
+ while (i < template.length && brace > 0) {
2502
+ const c = template[i];
2503
+ if (c === '{') brace++;
2504
+ else if (c === '}') brace--;
2505
+ i++;
2506
+ }
2507
+ if (brace !== 0) break;
2508
+ const openLen = i - openAt;
2509
+ const expr = template.slice(openAt + 7, i - 1).trim();
2510
+ if (!expr) {
2511
+ throw new RoseError('E-TEMPLATE', `${filePath}: {#await} needs a promise expression`, {
2512
+ file: filePath, hint: 'write {#await fetchUsers()}...{:then users}...{/await}' });
2513
+ }
2514
+ const blockOpenRe = /\{\#(if|each|boundary|island|await)\b/g;
2515
+ const blockCloseRe = /\{\/(if|each|boundary|island|await)\}/g;
2516
+ const thenRe = /\{:then\b([^}]*)\}/g;
2517
+ const catchRe = /\{:catch\b([^}]*)\}/g;
2518
+ let d = 1;
2519
+ let j = i;
2520
+ let thenAt = -1, catchAt = -1, closeAt = -1;
2521
+ let thenRaw = '', catchRaw = '';
2522
+ for (;;) {
2523
+ blockOpenRe.lastIndex = j;
2524
+ blockCloseRe.lastIndex = j;
2525
+ thenRe.lastIndex = j;
2526
+ catchRe.lastIndex = j;
2527
+ const nextOpen = blockOpenRe.exec(template);
2528
+ const nextClose = blockCloseRe.exec(template);
2529
+ const nextThen = thenRe.exec(template);
2530
+ const nextCatch = catchRe.exec(template);
2531
+ let nearestPos = Infinity, kind = '', m: RegExpExecArray | null = null;
2532
+ const consider = (mm: RegExpExecArray | null, k: string) => {
2533
+ if (mm && mm.index < nearestPos) { nearestPos = mm.index; kind = k; m = mm; }
2534
+ };
2535
+ consider(nextOpen, 'open'); consider(nextClose, 'close');
2536
+ consider(nextThen, 'then'); consider(nextCatch, 'catch');
2537
+ if (!m) break;
2538
+ if (kind === 'open') { d++; j = m.index + m[0].length; continue; }
2539
+ if (kind === 'close') {
2540
+ if (d === 1 && m[1] === 'await') { closeAt = m.index; break; }
2541
+ d--; j = m.index + m[0].length; continue;
2542
+ }
2543
+ if (d === 1) {
2544
+ if (kind === 'then' && thenAt < 0) { thenAt = m.index; thenRaw = m[1]; }
2545
+ else if (kind === 'catch' && catchAt < 0) { catchAt = m.index; catchRaw = m[1]; }
2546
+ }
2547
+ j = m.index + m[0].length;
2548
+ }
2549
+ if (closeAt < 0 || thenAt < 0) break;
2550
+ const thenTokenEnd = thenAt + 7 + thenRaw.length;
2551
+ const catchTokenEnd = catchAt >= 0 ? catchAt + 7 + catchRaw.length : -1;
2552
+ const pending = template.slice(i, thenAt);
2553
+ const thenBody = template.slice(thenTokenEnd, catchAt >= 0 ? catchAt : closeAt);
2554
+ const catchBody = catchAt >= 0 ? template.slice(catchTokenEnd, closeAt) : '';
2555
+ const thenVarRaw = thenRaw.trim();
2556
+ const catchVarRaw = catchRaw.trim();
2557
+ const thenVar = /^\w+$/.test(thenVarRaw) ? thenVarRaw : `__rvAwaitThen${n + 1}`;
2558
+ const catchVar = catchAt >= 0 ? (/^\w+$/.test(catchVarRaw) ? catchVarRaw : `__rvAwaitCatch${n + 1}`) : '';
2559
+ n++;
2560
+ const nn = n;
2561
+ const stateName = `__rvAwait${nn}`;
2562
+ blocks.push({ n: nn, expr, thenVar, catchVar });
2563
+ out += template.slice(pos, openAt);
2564
+ out += `{#if ${stateName}().status === 'pending'}` + pending + '{/if}\n';
2565
+ out += `{#each (${stateName}().status === 'resolved' ? [${stateName}().value] : []) as ${thenVar}}` + thenBody + '{/each}\n';
2566
+ if (catchAt >= 0) {
2567
+ out += `{#each (${stateName}().status === 'rejected' ? [${stateName}().error] : []) as ${catchVar}}` + catchBody + '{/each}\n';
2568
+ }
2569
+ pos = closeAt + 8;
2570
+ }
2571
+ if (n === 0) return { template, blocks };
2572
+ out += template.slice(pos);
2573
+ return { template: out, blocks };
2574
+ }
2575
+
2576
+ function awaitBootCode(blocks: AwaitBlock[]): string {
2577
+ let code = '';
2578
+ for (const b of blocks) {
2579
+ const stateName = `__rvAwait${b.n}`;
2580
+ code += `const [${stateName}, set${stateName}] = state("__rvawait${b.n}", { status: 'pending', value: null, error: null });\n`;
2581
+ code += `onMount(function () {\n`;
2582
+ code += ` Promise.resolve(${b.expr}).then(function (__rvAwaitVal) {\n`;
2583
+ code += ` set${stateName}({ status: 'resolved', value: __rvAwaitVal });\n`;
2584
+ code += ` }).catch(function (__rvAwaitErr) {\n`;
2585
+ code += ` set${stateName}({ status: 'rejected', error: __rvAwaitErr });\n`;
2586
+ code += ` });\n`;
2587
+ code += `});\n`;
2588
+ }
2589
+ return code;
2590
+ }
2591
+
2592
+ function findBlock(src: string, kind: 'if' | 'each' | 'boundary' | 'island' | 'snippet'): RegExpExecArray | null {
2134
2593
  const head = kind === 'boundary'
2135
2594
  ? /\{#boundary(?:\s+([^}]*))?\}/g
2136
2595
  : kind === 'if'
2137
2596
  ? /\{#if\s+([^}]+)\}/g
2138
2597
  : kind === 'island'
2139
2598
  ? /\{#island(?:\s+name="([^"]*)")?(?:\s+hydrate="([^"]*)")?\s*\}/g
2140
- : /\{#each\s+([^}]+?)\s+as\s+(\{[^{}]*\}|\[[^[\]]*\]|\w+)(?:\s*,\s*(\w+))?\}/g;
2599
+ : kind === 'snippet'
2600
+ ? /\{#snippet\s+(\w+)(?:\s*\(([^)]+)\))?\s*\}/g
2601
+ : /\{#each\s+([^}]+?)\s+as\s+(\{[^{}]*\}|\[[^[\]]*\]|\w+)(?:\s*,\s*(\w+))?(?:\s*\(([^)]+)\))?\}/g;
2141
2602
  const closeRe = new RegExp(`\\{/${kind}\\}`, 'g');
2142
2603
  let open: RegExpExecArray | null;
2143
2604
  while ((open = head.exec(src))) {
@@ -2161,7 +2622,8 @@ function findBlock(src: string, kind: 'if' | 'each' | 'boundary' | 'island'): Re
2161
2622
  const content = src.slice(afterOpen, nextClose.index);
2162
2623
  const groups = kind === 'boundary' ? [open[1] ?? '', content]
2163
2624
  : kind === 'island' ? [open[1] ?? '', open[2] ?? '', content]
2164
- : kind === 'if' ? [open[1], content] : [open[1], open[2], open[3] ?? '', content];
2625
+ : kind === 'snippet' ? [open[1], open[2] ?? '', content]
2626
+ : kind === 'if' ? [open[1], content] : [open[1], open[2], open[3] ?? '', open[4] ?? '', content];
2165
2627
  const arr = [src.slice(start, i), ...groups] as unknown as RegExpExecArray;
2166
2628
  (arr as any).index = start;
2167
2629
  return arr;
@@ -2241,7 +2703,19 @@ function compileHead(head: string): string {
2241
2703
  * Adversarial probing found all three in one afternoon; a template compiler
2242
2704
  * that emits broken code silently is the worst failure mode it has.
2243
2705
  */
2244
- const KNOWN_CLOSERS = new Set(['if', 'each', 'boundary', 'island']);
2706
+ const KNOWN_CLOSERS = new Set(['if', 'each', 'boundary', 'island', 'await', 'snippet']);
2707
+ const __blockResCache = new Map<string, { open: RegExp; close: RegExp }>();
2708
+ function blockCloseRes(kind: string): { open: RegExp; close: RegExp } {
2709
+ let hit = __blockResCache.get(kind);
2710
+ if (!hit) {
2711
+ hit = {
2712
+ open: new RegExp(`\\{#${kind}\\b[^}]*\\}`, 'g'),
2713
+ close: new RegExp(`\\{/${kind}\\}`, 'g'),
2714
+ };
2715
+ __blockResCache.set(kind, hit);
2716
+ }
2717
+ return hit;
2718
+ }
2245
2719
  function assertKnownDirectives(template: string, filePath: string): void {
2246
2720
  const rawRanges: Array<[number, number]> = [];
2247
2721
  const RAW_OPEN = /<(style|script|noscript)\b[^>]*>/gi;
@@ -2273,11 +2747,25 @@ function assertKnownDirectives(template: string, filePath: string): void {
2273
2747
  );
2274
2748
  }
2275
2749
  if (word === 'else') {
2276
- throw new RoseError(
2277
- 'E-TEMPLATE',
2278
- `${filePath}: a stray {:else} with no {#if} above it`,
2279
- { file: filePath, line: lineAt(template, m), hint: '{:else} / {:else if cond} belong inside an {#if} ... {/if} block - {#if cond}A{:else}B{/if}' },
2280
- );
2750
+ const netOpens = (re: RegExp, closer: string, at: number): number => {
2751
+ let n = 0, mm: RegExpExecArray | null;
2752
+ re.lastIndex = 0;
2753
+ while ((mm = re.exec(template))) { if (mm.index >= at) break; if (!inRaw(mm.index)) n++; }
2754
+ const cr = new RegExp(closer, 'g');
2755
+ let c = 0;
2756
+ while ((mm = cr.exec(template))) { if (mm.index >= at) break; if (!inRaw(mm.index)) c++; }
2757
+ return n - c;
2758
+ };
2759
+ const ifNet = netOpens(/\{#if\b/g, '\\{/if\\b', m.index);
2760
+ const eachNet = netOpens(/\{#each\b/g, '\\{/each\\b', m.index);
2761
+ if (ifNet <= 0 && eachNet <= 0) {
2762
+ throw new RoseError(
2763
+ 'E-TEMPLATE',
2764
+ `${filePath}: a stray {:else} with no {#if} or {#each} above it`,
2765
+ { file: filePath, line: lineAt(template, m), hint: '{:else} belongs inside an {#if} ... {/if} or {#each} ... {/each} block' },
2766
+ );
2767
+ }
2768
+ continue;
2281
2769
  }
2282
2770
  if (word === 'fallback') {
2283
2771
  throw new RoseError(
@@ -2286,25 +2774,42 @@ function assertKnownDirectives(template: string, filePath: string): void {
2286
2774
  { file: filePath, line: lineAt(template, m), hint: '{:fallback} belongs directly inside a {#boundary} ... {/boundary} block' },
2287
2775
  );
2288
2776
  }
2777
+ if (word === 'then' || word === 'catch') {
2778
+ const opensBefore = (re: RegExp, at: number): number => {
2779
+ re.lastIndex = 0;
2780
+ let n = 0, mm: RegExpExecArray | null;
2781
+ while ((mm = re.exec(template))) { if (mm.index >= at) break; if (!inRaw(mm.index)) n++; }
2782
+ return n;
2783
+ };
2784
+ const open = opensBefore(/\{#await\b/g, m.index);
2785
+ const close = opensBefore(/\{\/await\b/g, m.index);
2786
+ if (open <= close) {
2787
+ throw new RoseError(
2788
+ 'E-TEMPLATE',
2789
+ `${filePath}: a stray {:${word}} with no {#await} above it`,
2790
+ { file: filePath, line: lineAt(template, m), hint: '{:then} / {:catch} belong inside an {#await} ... {/await} block' },
2791
+ );
2792
+ }
2793
+ continue;
2794
+ }
2289
2795
  throw new RoseError(
2290
2796
  'E-TEMPLATE',
2291
2797
  `${filePath}: {:${word}} is not a rosetack directive`,
2292
2798
  { file: filePath, line: lineAt(template, m), hint: 'rosetack templates support {#if}/{:else}, {#each} and {#boundary}' },
2293
2799
  );
2294
2800
  }
2295
- const OPENER_RE = /\{#(if|each|boundary|island)\b([^}]*)\}/g;
2801
+ const OPENER_RE = /\{#(if|each|boundary|island|await)\b([^}]*)\}/g;
2296
2802
  while ((m = OPENER_RE.exec(template))) {
2297
2803
  if (inRaw(m.index)) continue;
2298
2804
  const [, kind, head] = m;
2299
- if (kind === 'each' && !/\bas\s+(\{[^{}]*\}?|\[[^[\]]*\]?|\w+)(?:\s*,\s*\w+)?\s*$/.test(head)) {
2805
+ if (kind === 'each' && !/\bas\s+(\{[^{}]*\}?|\[[^[\]]*\]?|\w+)(?:\s*,\s*\w+)?(?:\s*\([^)]*\))?\s*$/.test(head)) {
2300
2806
  throw new RoseError(
2301
2807
  'E-TEMPLATE',
2302
2808
  `${filePath}: {#each ${head.trim()}} is missing its item name`,
2303
2809
  { file: filePath, line: lineAt(template, m), hint: 'write {#each items() as item} - the name after `as` is what the block body reads (item.id, item.name)' },
2304
2810
  );
2305
2811
  }
2306
- const OPEN_RE = new RegExp(`\\{#${kind}\\b[^}]*\\}`, 'g');
2307
- const CLOSE_RE = new RegExp(`\\{/${kind}\\}`, 'g');
2812
+ const { open: OPEN_RE, close: CLOSE_RE } = blockCloseRes(kind);
2308
2813
  let depth = 1;
2309
2814
  let i = m.index + m[0].length;
2310
2815
  for (;;) {
@@ -2389,6 +2894,8 @@ function compileTemplate(
2389
2894
 
2390
2895
  const nextId = () => `${depth}_${blockId++}`;
2391
2896
 
2897
+ if (depth === 0) result += 'const __snip = {};\n';
2898
+
2392
2899
  while (remaining.length > 0) {
2393
2900
  const ifMatch = findBlock(remaining, 'if');
2394
2901
  const eachMatch = findBlock(remaining, 'each');
@@ -2399,12 +2906,14 @@ function compileTemplate(
2399
2906
  : null;
2400
2907
  const compTag = comps.size > 0 ? findCompTag(remaining, comps) : null;
2401
2908
  const islandMatch = findBlock(remaining, 'island');
2909
+ const snippetMatch = findBlock(remaining, 'snippet');
2402
2910
 
2403
2911
  const candidates: Array<{ type: string; match: RegExpExecArray; index: number; tag?: CompTag }> = [];
2404
2912
  if (ifMatch?.index !== undefined) candidates.push({ type: 'if', match: ifMatch, index: ifMatch.index });
2405
2913
  if (eachMatch?.index !== undefined) candidates.push({ type: 'each', match: eachMatch, index: eachMatch.index });
2406
2914
  if (boundaryMatch?.index !== undefined) candidates.push({ type: 'boundary', match: boundaryMatch, index: boundaryMatch.index });
2407
2915
  if (islandMatch?.index !== undefined) candidates.push({ type: 'island', match: islandMatch, index: islandMatch.index });
2916
+ if (snippetMatch?.index !== undefined) candidates.push({ type: 'snippet', match: snippetMatch, index: snippetMatch.index });
2408
2917
  if (exprMatch?.index !== undefined) candidates.push({ type: 'expr', match: exprMatch, index: exprMatch.index });
2409
2918
  if (compTag) candidates.push({ type: 'comp', match: exprMatch!, index: compTag.start, tag: compTag });
2410
2919
  const earliest = candidates.length > 0
@@ -2453,7 +2962,7 @@ function compileTemplate(
2453
2962
  }
2454
2963
  remaining = remaining.substring(earliest.index + earliest.match[0].length);
2455
2964
  } else if (earliest.type === 'each') {
2456
- const [, items, item, index, content] = earliest.match;
2965
+ const [, items, item, index, key, content] = earliest.match;
2457
2966
  const before = remaining.substring(0, earliest.index);
2458
2967
  if (before) result += emitChunk(before, acc, closes, scope);
2459
2968
  const call = autoCall(items);
@@ -2472,9 +2981,23 @@ function compileTemplate(
2472
2981
  scoped += content.trim().slice(lastSpan);
2473
2982
  const inner = compileTemplate(scoped, 'h', '__c', '__s', depth + 1, effMarkers, comps, islandDepth);
2474
2983
  const body = isDestructure ? `const ${item} = __s; ${inner}` : inner;
2984
+ let keyFn = '';
2985
+ if (key) {
2986
+ if (isDestructure) {
2987
+ throw new RoseError(
2988
+ 'E-TEMPLATE',
2989
+ `${filePath}: a keyed {#each} keys on a named item's property - write {#each xs as x (x.id)}, not a destructuring pattern`,
2990
+ { file: filePath, hint: 'name the item first, then key on one of its properties' },
2991
+ );
2992
+ }
2993
+ let k = key.trim();
2994
+ if (itemRe) k = k.replace(itemRe, '__s');
2995
+ if (indexRe) k = k.replace(indexRe, '__i');
2996
+ keyFn = `, (__s, __i) => (${k})`;
2997
+ }
2475
2998
  result += `const __b${id} = (__s, __c${index ? ', __i' : ''}) => { let h = ''; ${body} return h; };\n`;
2476
2999
  if (effMarkers) {
2477
- result += `${acc} += eachMark(${closes}, () => (${call}), __b${id});\n`;
3000
+ result += `${acc} += eachMark(${closes}, () => (${call}), __b${id}${keyFn});\n`;
2478
3001
  } else {
2479
3002
  const param = isDestructure ? '__s' : item;
2480
3003
  result += `${acc} += (${call}).map((${param}${index ? ', __i' : ''}) => __b${id}(${param}, []${index ? ', __i' : ''}))).join('');\n`;
@@ -2506,6 +3029,15 @@ function compileTemplate(
2506
3029
  : `try { __bd${id} = __b${id}(${closes}); } catch (e) { $setBoundaryError(e); __bd${id} = ${fbBlock ? `__bf${id}(${closes})` : JSON.stringify(BOUNDARY_FALLBACK)}; }\n`;
2507
3030
  result += `${acc} += __bd${id};\n`;
2508
3031
  remaining = remaining.substring(earliest.index + earliest.match[0].length);
3032
+ } else if (earliest.type === 'snippet') {
3033
+ const [, name, params, content] = earliest.match;
3034
+ const before = remaining.substring(0, earliest.index);
3035
+ if (before) result += emitChunk(before, acc, closes, scope);
3036
+ const id = nextId();
3037
+ const paramList = params ? params.split(',').map(p => p.trim()).filter(Boolean).join(',') : '';
3038
+ const inner = compileTemplate(content.trim(), 'h', '__c', '__s', depth + 1, effMarkers, comps, islandDepth);
3039
+ result += `__snip.${name} = (__s, __c${paramList ? ',' + paramList : ''}) => { let h = ''; ${inner} return h; };\n`;
3040
+ remaining = remaining.substring(earliest.index + earliest.match[0].length);
2509
3041
  } else if (earliest.type === 'comp') {
2510
3042
  const tag = earliest.tag!;
2511
3043
  if (tag.start > 0) result += emitChunk(remaining.substring(0, tag.start), acc, closes, scope);
@@ -2539,7 +3071,7 @@ function compileTemplate(
2539
3071
  }
2540
3072
  content = out + content.slice(lastSpan);
2541
3073
  }
2542
- return `${JSON.stringify(nm)}: (__s, __c) => { let h = ''; ${compileTemplate(content, 'h', '__c', '__s', depth + 1, effMarkers, comps, islandDepth)} return h; }`;
3074
+ return `${JSON.stringify(nm)}: (__s, __c) => { let h = ''; ${compileTemplate(content, 'h', '__c', scope, depth + 1, effMarkers, comps, islandDepth)} return h; }`;
2543
3075
  });
2544
3076
  const propsObj = parseCompAttrs(tag.attrs)
2545
3077
  .filter((a) => a.name !== 'slot')
@@ -2610,6 +3142,32 @@ function compileTemplate(
2610
3142
  remaining = remaining.substring(earliest.index + earliest.match[0].length);
2611
3143
  continue;
2612
3144
  }
3145
+ const dbgMatch = /^@debug\b([\s\S]*)$/.exec(trimmed);
3146
+ if (dbgMatch) {
3147
+ if (before) result += emitChunk(before, acc, closes, scope);
3148
+ const names = dbgMatch[1].trim().replace(/,$/, '');
3149
+ result += names
3150
+ ? `console.log('[rosetack:debug]', { ${names} });\n`
3151
+ : `console.log('[rosetack:debug]'); debugger;\n`;
3152
+ remaining = remaining.substring(earliest.index + earliest.match[0].length);
3153
+ continue;
3154
+ }
3155
+ const renderMatch = /^@render\s+([A-Za-z_$][\w$]*)\s*\(([\s\S]*)\)\s*$/.exec(trimmed);
3156
+ if (renderMatch) {
3157
+ const ahead = new RegExp(`\\{#snippet\\s+${renderMatch[1]}\\b`).test(remaining.substring(earliest.index + earliest.match[0].length));
3158
+ if (ahead) {
3159
+ throw new RoseError(
3160
+ 'E-TEMPLATE',
3161
+ `${filePath}: {@render ${renderMatch[1]}} runs before its {#snippet ${renderMatch[1]}} is defined`,
3162
+ { file: filePath, hint: 'move the {#snippet} definition above the {@render} call - definitions register as the statement stream reaches them' },
3163
+ );
3164
+ }
3165
+ if (before) result += emitChunk(before, acc, closes, scope);
3166
+ const renderArgs = renderMatch[2].trim();
3167
+ result += `${acc} += ((__snip && __snip.${renderMatch[1]}) ? __snip.${renderMatch[1]}(${scope ?? 'null'}, ${closes}${renderArgs ? ', ' + renderArgs : ''}) : '');\n`;
3168
+ remaining = remaining.substring(earliest.index + earliest.match[0].length);
3169
+ continue;
3170
+ }
2613
3171
  const attrMatch = before.match(/([\w-]+)=\s*$/);
2614
3172
  if (attrMatch) {
2615
3173
  const lit = before.slice(0, before.length - attrMatch[0].length);
@@ -2640,7 +3198,11 @@ interface CompTag {
2640
3198
  selfClosing: boolean;
2641
3199
  }
2642
3200
 
2643
- // Scan one tag from its `<` to its `>`, quote- and brace-aware so a `>` inside an attribute expression (`title={a > b}`) does not end the tag.
3201
+ /**
3202
+ * Scan one tag from its `<` to its `>`, quote- and brace-aware so a `>` inside
3203
+ * an attribute expression (`title={a > b}`) does not end the tag. Returns the
3204
+ * index just past `>`, or -1 when the tag is never closed.
3205
+ */
2644
3206
  function scanTagEnd(src: string, start: number): number {
2645
3207
  let j = start + 1;
2646
3208
  let quote = '';
@@ -2774,6 +3336,7 @@ function splitSlots(src: string): { def: string; named: Array<[string, string]>
2774
3336
  let i = 0;
2775
3337
  let elemDepth = 0;
2776
3338
  let blockDepth = 0;
3339
+ const blockStack: Array<{ header: string; type: string }> = [];
2777
3340
  while (i < src.length) {
2778
3341
  const lt = src.indexOf('<', i);
2779
3342
  const ob = src.indexOf('{#', i);
@@ -2788,8 +3351,14 @@ function splitSlots(src: string): { def: string; named: Array<[string, string]>
2788
3351
  if (next === ob || next === cb) {
2789
3352
  const close = src.indexOf('}', next);
2790
3353
  const token = src.slice(next, close < 0 ? src.length : close + 1);
2791
- if (next === ob) blockDepth++;
2792
- else blockDepth = Math.max(0, blockDepth - 1);
3354
+ if (next === ob) {
3355
+ const m = /^\{#(\w+)/.exec(token);
3356
+ blockStack.push({ header: token, type: m ? m[1] : '' });
3357
+ blockDepth++;
3358
+ } else {
3359
+ blockDepth = Math.max(0, blockDepth - 1);
3360
+ if (blockStack.length) blockStack.pop();
3361
+ }
2793
3362
  def += token;
2794
3363
  i = next + token.length;
2795
3364
  continue;
@@ -2816,20 +3385,16 @@ function splitSlots(src: string): { def: string; named: Array<[string, string]>
2816
3385
  }
2817
3386
  if (!selfClosing && !isVoid) elemDepth++;
2818
3387
  const slotName = /\bslot\s*=\s*["'](\w+)["']/.exec(tagText)?.[1];
2819
- if (slotName && (elemDepth !== 1 || blockDepth !== 0)) {
2820
- throw new RoseError('E-TEMPLATE', `slot="${slotName}" on <${nm[2]}> must be a direct child of the component - it is nested inside another element or an {#if}/{#each} block`, { hint: 'place <slot name="..."> directly inside the component tag - wrap the ELEMENTS around the slot, not the slot inside them' });
2821
- }
2822
- if (slotName) {
2823
- const stripped = tagText.replace(/\s*slot\s*=\s*["']\w+["']/, '');
3388
+ if (slotName && elemDepth === 1 && blockDepth === 0) {
2824
3389
  if (selfClosing || isVoid) {
2825
- named.set(slotName, (named.get(slotName) ?? '') + stripped);
3390
+ named.set(slotName, (named.get(slotName) ?? '') + tagText.replace(/\s*slot\s*=\s*["']\w+["']/, ''));
2826
3391
  } else {
2827
3392
  const closeIdx = findClose(src, end, nm[2]);
2828
- if (closeIdx < 0) throw new RoseError('E-TEMPLATE', `unclosed <${nm[2]}> inside slot="${slotName}"`, { hint: `add the matching </${nm[2]}> inside the slot content` });
3393
+ if (closeIdx < 0) throw new RoseError('E-TEMPLATE', `unclosed <${nm[2]}> inside slot="${slotName}"`, { hint: `add the matching </${nm[2]}>` });
2829
3394
  const tail = `</${nm[2]}>`;
2830
3395
  const inner = src.slice(end, closeIdx);
2831
3396
  rejectNestedSlot(inner, slotName);
2832
- named.set(slotName, (named.get(slotName) ?? '') + stripped + inner + tail);
3397
+ named.set(slotName, (named.get(slotName) ?? '') + tagText.replace(/\s*slot\s*=\s*["']\w+["']/, '') + inner + tail);
2833
3398
  elemDepth = Math.max(0, elemDepth - 1);
2834
3399
  i = closeIdx + tail.length;
2835
3400
  continue;
@@ -2837,6 +3402,32 @@ function splitSlots(src: string): { def: string; named: Array<[string, string]>
2837
3402
  i = end;
2838
3403
  continue;
2839
3404
  }
3405
+ if (slotName && blockDepth > 0) {
3406
+ const stripped = tagText.replace(/\s*slot\s*=\s*["']\w+["']/, '');
3407
+ let lifted = '';
3408
+ for (const b of blockStack) lifted += b.header;
3409
+ lifted += stripped;
3410
+ if (selfClosing || isVoid) {
3411
+ for (let k = blockStack.length - 1; k >= 0; k--) lifted += `{/${blockStack[k].type}}`;
3412
+ named.set(slotName, (named.get(slotName) ?? '') + lifted);
3413
+ i = end;
3414
+ continue;
3415
+ }
3416
+ const closeIdx = findClose(src, end, nm[2]);
3417
+ if (closeIdx < 0) throw new RoseError('E-TEMPLATE', `unclosed <${nm[2]}> inside slot="${slotName}"`, { hint: `add the matching </${nm[2]}>` });
3418
+ const tail = `</${nm[2]}>`;
3419
+ lifted += src.slice(end, closeIdx) + tail;
3420
+ for (let k = blockStack.length - 1; k >= 0; k--) lifted += `{/${blockStack[k].type}}`;
3421
+ named.set(slotName, (named.get(slotName) ?? '') + lifted);
3422
+ elemDepth = Math.max(0, elemDepth - 1);
3423
+ i = closeIdx + tail.length;
3424
+ continue;
3425
+ }
3426
+ if (slotName) {
3427
+ throw new RoseError('E-TEMPLATE', `slot="${slotName}" on <${nm[2]}> must be a direct child of the component, or wrapped only by an {#if}/{#each}/{#boundary} block - it is nested inside another element`, {
3428
+ hint: 'place the element with slot="..." directly inside the component tag, or inside a single {#if}/{#each} block - wrapping it in another element is not yet supported',
3429
+ });
3430
+ }
2840
3431
  def += tagText;
2841
3432
  i = end;
2842
3433
  }
@@ -2859,7 +3450,8 @@ const IMG_MIME: Record<string, string> = {
2859
3450
  '.svg': 'image/svg+xml',
2860
3451
  '.ico': 'image/x-icon',
2861
3452
  };
2862
- const INLINE_IMG_MAX = 4096;
3453
+ const INLINE_IMG_MAX = 8192;
3454
+ const INLINE_SVG_MAX = 16384;
2863
3455
 
2864
3456
  import { readImageSize } from "../cli/image-size";
2865
3457
  import { scanContentDir, renderMarkdown, buildRss } from "../cli/content";
@@ -2895,6 +3487,20 @@ function listImageVariants(publicDir: string, url: string): Array<{ url: string;
2895
3487
  return out.sort((a, b) => a.width - b.width);
2896
3488
  }
2897
3489
 
3490
+ const __imgReadCache = new Map<string, { mtime: number; buffer: Buffer; dims: { width: number; height: number } | null }>();
3491
+ function cachedImageRead(filePath: string): { buffer: Buffer; dims: { width: number; height: number } | null } | null {
3492
+ let st: fs.Stats;
3493
+ try { st = fs.statSync(filePath); } catch { return null; }
3494
+ const hit = __imgReadCache.get(filePath);
3495
+ if (hit && hit.mtime === st.mtimeMs) return { buffer: hit.buffer, dims: hit.dims };
3496
+ let buffer: Buffer;
3497
+ try { buffer = fs.readFileSync(filePath); } catch { return null; }
3498
+ const dims = readImageSize(filePath);
3499
+ const entry = { mtime: st.mtimeMs, buffer, dims };
3500
+ __imgReadCache.set(filePath, entry);
3501
+ return { buffer, dims: entry.dims };
3502
+ }
3503
+
2898
3504
  function inlineImages(template: string, publicDir: string): string {
2899
3505
  return template.replace(IMG_RE, (tag) => {
2900
3506
  const src = tag.match(/\bsrc="(\/[^"{}]+)"/);
@@ -2904,17 +3510,15 @@ function inlineImages(template: string, publicDir: string): string {
2904
3510
  if (!mime) return tag;
2905
3511
  const rel = src[1].replace(/^\/public(?=\/)/, '');
2906
3512
  const filePath = path.join(publicDir, rel);
2907
- let file: Buffer;
2908
- try {
2909
- file = fs.readFileSync(filePath);
2910
- } catch {
2911
- return tag;
2912
- }
3513
+ const read = cachedImageRead(filePath);
3514
+ if (!read) return tag;
3515
+ const file = read.buffer;
2913
3516
  const authorDims = /\swidth=/.test(tag) || /\sheight=/.test(tag);
2914
- const dims = authorDims ? null : readImageSize(filePath);
3517
+ const dims = authorDims ? null : read.dims;
2915
3518
  const withDims = (t: string): string =>
2916
3519
  dims ? t.replace(/<img\b/, `<img width="${dims.width}" height="${dims.height}"`) : t;
2917
- if (file.length > INLINE_IMG_MAX) {
3520
+ const inlineMax = ext === '.svg' ? INLINE_SVG_MAX : INLINE_IMG_MAX;
3521
+ if (file.length > inlineMax) {
2918
3522
  const hasSS = /\ssrcset=/.test(tag) || /\ssizes=/.test(tag);
2919
3523
  const variants = hasSS ? [] : listImageVariants(publicDir, rel);
2920
3524
  if (!variants.length) return withDims(tag);
@@ -2967,7 +3571,7 @@ function compileSlot(acc: string): string {
2967
3571
  return `${acc} += String(children);\n`;
2968
3572
  }
2969
3573
 
2970
- const RUNTIME_IMPORTS = `import { state, setState, persistState, $data, hasState, esc, refresh, onMount, onCleanup, getContext, $query, $t, bestLocale, localeDir, ensureLocale, loadLocale, handlers, directives, $cookies, $sessionCookie, $store, ActionError, $actionError, $actionErrorOrThrow, $boundaryFallback, $setBoundaryError, $boundaryError, $append, $prepend, $merge, applyStateDeltas, textMark, attrMark, boolAttrMark, ifMark, eachMark, headMark, rawMark, slotBlockMark, redirect, notFound } from './runtime.js';`;
3574
+ const RUNTIME_IMPORTS = `import { state, setState, persistState, $data, hasState, isSeeded, markSeeded, esc, refresh, onMount, onCleanup, $effect, getContext, $query, $t, bestLocale, localeDir, ensureLocale, loadLocale, handlers, directives, $cookies, $sessionCookie, $store, ActionError, $actionError, $actionErrorOrThrow, $actionPending, $boundaryFallback, $setBoundaryError, $boundaryError, $append, $prepend, $merge, applyStateDeltas, textMark, attrMark, boolAttrMark, ifMark, eachMark, headMark, rawMark, slotBlockMark, redirect, notFound } from './runtime.js';`;
2971
3575
 
2972
3576
  const API_RUNTIME_HELPERS = RUNTIME_IMPORTS
2973
3577
  .replace(/^import\s*\{/, '')
@@ -3229,7 +3833,7 @@ export async function buildProject(root: string, outDir: string): Promise<{ rout
3229
3833
  files.map((f, i) => [f, { index: i, scopeKey: scopeKeys[i], slots: scanSlotDecls(f) }])
3230
3834
  );
3231
3835
  const compiled = await Promise.all(
3232
- files.map((f, i) => compileComponent(f, path.join(root, 'public'), scopeKeys[i], infos[i].isApi, plugins, registry))
3836
+ files.map((f, i) => compileComponentMemo(f, path.join(root, 'public'), scopeKeys[i], infos[i].isApi, plugins, registry))
3233
3837
  );
3234
3838
 
3235
3839
  const importsOf = new Map<number, number[]>();
@@ -3483,11 +4087,13 @@ export const hasResponseHooks = hooks.some((p) => p.onResponse);
3483
4087
  })
3484
4088
  .join(',\n ');
3485
4089
 
4090
+ const appUsesAuth = compiled.some((c) => c.usesrosetackAuth);
4091
+
3486
4092
  const serverEntry = `
3487
4093
  ${serverImports}
3488
4094
  import { renderMarkdown } from './content-md.ts';
3489
- import crypto from 'node:crypto';
3490
- import { setState, persistState, clearRequestState, serializeState, resetRequestContext, setRequestQuery, isLocale, setLocales, localeList, localeDir, setStoreTransport, applyStorePatch, ActionError, StateDelta, setStateDelta, esc } from './runtime.js';
4095
+ ${appUsesAuth ? "import crypto from 'node:crypto';" : "// no route references __rosetackAuth: the node:crypto auth helpers are omitted, keeping the bundle edge-loadable"}
4096
+ import { setState, persistState, clearRequestState, isolateRender, serializeState, resetRequestContext, installContextStore, setRequestQuery, isLocale, setLocales, localeList, localeDir, setStoreTransport, applyStorePatch, ActionError, StateDelta, setStateDelta, esc } from './runtime.js';
3491
4097
  ${runtimePlugins.length > 0
3492
4098
  ? `import { hooks as __pluginHooks, hasRequestHooks as __hasRequestHooks, hasResponseHooks as __hasResponseHooks } from './plugins.js';`
3493
4099
  : `// no plugin declares a runtime hook, so there is no plugins
@@ -3546,6 +4152,7 @@ if (typeof process !== 'undefined' && typeof process.send === 'function') {
3546
4152
  });
3547
4153
  }
3548
4154
 
4155
+
3549
4156
  // (the cross-machine seam): the cluster relay above covers ONE machine.
3550
4157
  export function __installStoreTransport(send: (name: string, value: unknown) => void): void {
3551
4158
  setStoreTransport(send);
@@ -3566,6 +4173,11 @@ export const routeParams = {
3566
4173
 
3567
4174
  // Routes whose component reads the request context (getContext()), mutates a shared store ($store()), reads the query ($query(), P0-1)
3568
4175
  export const dynamicRoutes = [
4176
+ ${pages.filter(({ i }) => compiled[i].usesContext || compiled[i].cspNonce || compiled[i].buffer || compiled[i].controlSignal || compiled[i].needsClient).map(({ info }) => `'${info.routePath}'`).join(',\n ')}
4177
+ ];
4178
+
4179
+ // Routes that the prerender function should skip (not bake into static files).
4180
+ export const prerenderSkipRoutes = [
3569
4181
  ${pages.filter(({ i }) => compiled[i].usesContext || compiled[i].cspNonce || compiled[i].buffer || compiled[i].controlSignal).map(({ info }) => `'${info.routePath}'`).join(',\n ')}
3570
4182
  ];
3571
4183
 
@@ -3589,6 +4201,8 @@ const __dynCache = new Map();
3589
4201
  export function invalidateRenderCache(): void {
3590
4202
  __dynCache.clear();
3591
4203
  }
4204
+
4205
+
3592
4206
  // Application KV cache primitive (server-side, per-worker in-memory): a zero-dependency store for expensive computations.
3593
4207
  const __kvStore = new Map<string, { v: unknown; exp: number }>();
3594
4208
  // Content collections: src/content/<coll>/*.md scanned once at build time,
@@ -3702,6 +4316,7 @@ function sse(handler: (send: (event: string, data: unknown) => void) => Promise<
3702
4316
  });
3703
4317
  }
3704
4318
  globalThis.__rosetackExtras = { v, jobs, sse };
4319
+ ${appUsesAuth ? `
3705
4320
  const auth = {
3706
4321
  hashPassword(password: string): string {
3707
4322
  const salt = crypto.randomBytes(16).toString("hex");
@@ -3743,6 +4358,7 @@ const auth = {
3743
4358
  },
3744
4359
  };
3745
4360
  globalThis.__rosetackAuth = auth;
4361
+ ` : "// __rosetackAuth helpers omitted: no route references them (keeps the bundle free of node:crypto and edge-loadable)"}
3746
4362
 
3747
4363
  export async function $kv(key: string, compute: () => unknown | Promise<unknown>, ttlSeconds = 300): Promise<unknown> {
3748
4364
  const hit = kv.get(key);
@@ -3973,7 +4589,15 @@ function extractHead(rendered) {
3973
4589
 
3974
4590
  // Form: the submitted FormData of a progressive-enhancement POST.
3975
4591
  export async function renderPage(pathname, form) {
4592
+ // Renders DO overlap in one process: prod-server warms every route in the background at startup.
4593
+ return isolateRender(() => renderPageIsolated(pathname, form));
4594
+ }
4595
+
4596
+ async function renderPageIsolated(pathname, form) {
3976
4597
  clearRequestState();
4598
+ // Cold-start readiness gate (oboext #8): await the app's published DB-ready promise before any $data() read.
4599
+ const appReady = globalThis.__rosetackAppReady;
4600
+ if (appReady) await appReady;
3977
4601
  for (const route of routes) {
3978
4602
  if (matchRoute(route.pattern, pathname)) {
3979
4603
  const patternParts = route.pattern.split('/');
@@ -4142,7 +4766,15 @@ export async function handleApi(method, pathname, request) {
4142
4766
 
4143
4767
  // === Streaming SSR === The static shell (doctype, <head>, body + container open) flushes BEFORE the - possibly slow - render completes: the first byte.
4144
4768
  export async function renderPageStream(pathname, write, shellOpen, clientTag) {
4769
+ // Isolated for the same reason as renderPage: a streaming render awaits inside route.render()
4770
+ return isolateRender(() => renderPageStreamIsolated(pathname, write, shellOpen, clientTag));
4771
+ }
4772
+
4773
+ async function renderPageStreamIsolated(pathname, write, shellOpen, clientTag) {
4145
4774
  clearRequestState();
4775
+ // Cold-start readiness gate (oboext #8): same contract as renderPage — await the app's published DB-ready promise before streaming the shell.
4776
+ const appReady = globalThis.__rosetackAppReady;
4777
+ if (appReady) await appReady;
4146
4778
  for (const route of routes) {
4147
4779
  if (matchRoute(route.pattern, pathname)) {
4148
4780
  const patternParts = route.pattern.split('/');
@@ -4199,6 +4831,11 @@ export async function renderPageStream(pathname, write, shellOpen, clientTag) {
4199
4831
  }
4200
4832
  return 404;
4201
4833
  }
4834
+ // Prevent tree-shaking of invalidateRenderCache (called from prod-server.ts / edge.ts on non-GET writes).
4835
+ void invalidateRenderCache;
4836
+
4837
+ // Same reason, for the per-request context store: prod-server.ts installs an AsyncLocalStorage adapter.
4838
+ export { installContextStore };
4202
4839
  `;
4203
4840
  try {
4204
4841
  const patterns = [...pages, ...apiRoutes].map(({ info }) => info.pattern);
@@ -4281,7 +4918,7 @@ export async function renderPageStream(pathname, write, shellOpen, clientTag) {
4281
4918
 
4282
4919
  const prefetchMode = compiled.find((c) => c.prefetch)?.prefetch ?? 'all';
4283
4920
  const vitalsOn = compiled.some((c) => c.vitals === true);
4284
- const vitalsBlock = vitalsOn
4921
+ const vitalsBlock = vitalsOn
4285
4922
  ? `\n// the app asked for web-vitals - measure once, at boot, and let the\n// app decide where the numbers go (one 'rosetack:vitals' CustomEvent per metric).\nreportVitals();\n`
4286
4923
  : '';
4287
4924
 
@@ -4309,7 +4946,7 @@ export async function renderPageStream(pathname, write, shellOpen, clientTag) {
4309
4946
 
4310
4947
  const clientEntry = `
4311
4948
  ${clientImports}
4312
- import { setState, resumeState, clearRequestState, resetEffects, wire, isolateStateAsync, restoreState, setRefreshHook, clearMounts, flushMounts, adoptCleanups, handlers, setActionDispatcher, setLocales, setLocalePacks, ensureLocale, isLocale, localeDir, setPrefetchOverride, serializeState, setFxOwner, resetContainerFx, esc } from './runtime.js';
4949
+ import { state, setState, resumeState, clearRequestState, resetEffects, wire, isolateStateAsync, restoreState, setRefreshHook, clearMounts, flushMounts, adoptCleanups, handlers, setActionDispatcher, setLocales, setLocalePacks, ensureLocale, isLocale, localeDir, setPrefetchOverride, serializeState, setFxOwner, resetContainerFx, esc } from './runtime.js';
4313
4950
 
4314
4951
  // I18n: the dictionaries baked at build time - the client renders any PRELOADED locale from the bundle.
4315
4952
  setLocales(${clientLocalesJson}, '${defaultLocale}');
@@ -4524,11 +5161,19 @@ async function postForm(body, container, pathname) {
4524
5161
  // Call a page's server action by name from any event handler: <button on:click={like}> compiles to $action('like').
4525
5162
  export async function $action(name, e) {
4526
5163
  if (e && e.preventDefault) e.preventDefault();
5164
+ // F34: the pending flag is ordinary signal state - {#if $actionPending()}
5165
+ // disables a submit button while the action is in flight, reactively.
5166
+ const [__rvPending, __rvSetPending] = state('actionPending', false);
5167
+ __rvSetPending(true);
4527
5168
  const body = new FormData();
4528
5169
  body.append('__action', name);
4529
5170
  // An event inside a mount belongs to that mount - the attribute is kept in step with what is currently mounted.
4530
5171
  const box = e && e.target && e.target.closest ? e.target.closest('[data-rosetack]') : null;
4531
- return postForm(body, box || undefined, box ? box.getAttribute('data-rosetack') : undefined);
5172
+ try {
5173
+ return await postForm(body, box || undefined, box ? box.getAttribute('data-rosetack') : undefined);
5174
+ } finally {
5175
+ __rvSetPending(false);
5176
+ }
4532
5177
  }
4533
5178
  // F17: hand the dispatcher to the runtime, so wire() can serve a server action bound to a non-delegated event (on:keydown="$action:save") the same way.
4534
5179
  setActionDispatcher($action);