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.
@@ -1,6 +1,7 @@
1
1
  // src/compiler/index.ts
2
2
  import * as fs3 from "fs";
3
3
  import * as path2 from "path";
4
+ import * as os from "os";
4
5
  import { pathToFileURL, fileURLToPath } from "url";
5
6
  import * as esbuild from "esbuild";
6
7
 
@@ -45,9 +46,9 @@ function errorInfo(err) {
45
46
 
46
47
  // src/cli/image-size.ts
47
48
  import fs from "node:fs";
48
- function readImageSize(filePath) {
49
+ function readImageSize(filePath2) {
49
50
  try {
50
- const fd = fs.openSync(filePath, "r");
51
+ const fd = fs.openSync(filePath2, "r");
51
52
  const buf = Buffer.alloc(64);
52
53
  const read = fs.readSync(fd, buf, 0, 64, 0);
53
54
  fs.closeSync(fd);
@@ -62,7 +63,7 @@ function readImageSize(filePath) {
62
63
  return parseWebP(buf);
63
64
  }
64
65
  if (buf[0] === 255 && buf[1] === 216) {
65
- return parseJpeg(filePath);
66
+ return parseJpeg(filePath2);
66
67
  }
67
68
  return null;
68
69
  } catch {
@@ -85,8 +86,8 @@ function parseWebP(buf) {
85
86
  }
86
87
  return null;
87
88
  }
88
- function parseJpeg(filePath) {
89
- const fd = fs.openSync(filePath, "r");
89
+ function parseJpeg(filePath2) {
90
+ const fd = fs.openSync(filePath2, "r");
90
91
  try {
91
92
  const buf = Buffer.alloc(4);
92
93
  let pos = 2;
@@ -241,7 +242,7 @@ var COMPONENT_RE = /<script>([\s\S]*?)<\/script>/;
241
242
  var TEMPLATE_RE = /<template>([\s\S]*?)<\/template>/;
242
243
  var HEAD_RE = /<head>([\s\S]*?)<\/head>/;
243
244
  var STYLE_RE = /<style>([\s\S]*?)<\/style>/;
244
- var DECL_RE = /(?:let|const|var)\s+(\w+)[^=]*=\s*\$(state|data|kv|persist)\b/g;
245
+ var DECL_RE = /(?:let|const|var)\s+(\w+)[^=]*=\s*\$(state|data|kv|persist|derived)\b/g;
245
246
  var DECL_CAST_RE = /^\s+as\s+[^;\n]+/;
246
247
  var SETSTATE_RE = /\$setState\(([^,]+),\s*([^)]+)\)/g;
247
248
  var SLOT_RE = /<slot\s*\/>|<slot>([\s\S]*?)<\/slot>/g;
@@ -694,7 +695,7 @@ function nodeOnlyImports(importStmts) {
694
695
  }
695
696
  return out;
696
697
  }
697
- function wireEventBindings(template, actionNames, filePath = "<template>") {
698
+ function wireEventBindings(template, actionNames, filePath2 = "<template>") {
698
699
  const bindings = [];
699
700
  let out = "";
700
701
  let rest = template;
@@ -719,7 +720,7 @@ function wireEventBindings(template, actionNames, filePath = "<template>") {
719
720
  if (targets.length > 1) {
720
721
  throw new RoseError(
721
722
  "E-TEMPLATE",
722
- `${filePath}: on:${m[1]} carries both |${targets.join(" and |")}`,
723
+ `${filePath2}: on:${m[1]} carries both |${targets.join(" and |")}`,
723
724
  { hint: "a handler binds to one target - the element (default), |window or |document" }
724
725
  );
725
726
  }
@@ -728,7 +729,7 @@ function wireEventBindings(template, actionNames, filePath = "<template>") {
728
729
  if (!KNOWN_MODS.includes(mod)) {
729
730
  throw new RoseError(
730
731
  "E-TEMPLATE",
731
- `${filePath}: unknown event modifier |${mod}`,
732
+ `${filePath2}: unknown event modifier |${mod}`,
732
733
  { hint: `the supported modifiers are ${KNOWN_MODS.map((k) => "|" + k).join(" ")} - capture/passive are listener options a delegated listener cannot carry per element; anything else belongs inside the handler body` }
733
734
  );
734
735
  }
@@ -763,7 +764,7 @@ function wireEventBindings(template, actionNames, filePath = "<template>") {
763
764
  if (mods.length && actionNames.has(expr)) {
764
765
  throw new RoseError(
765
766
  "E-TEMPLATE",
766
- `${filePath}: event modifiers are not supported on the server action ${expr}`,
767
+ `${filePath2}: event modifiers are not supported on the server action ${expr}`,
767
768
  { hint: "$action already preventDefaults - drop the modifiers, or bind a local handler that calls $action" }
768
769
  );
769
770
  }
@@ -785,10 +786,10 @@ function wireEventBindings(template, actionNames, filePath = "<template>") {
785
786
  }
786
787
  return { template: out, bindings };
787
788
  }
788
- function scanSlotDecls(filePath) {
789
+ function scanSlotDecls(filePath2) {
789
790
  let src;
790
791
  try {
791
- src = fs3.readFileSync(filePath, "utf-8");
792
+ src = fs3.readFileSync(filePath2, "utf-8");
792
793
  } catch {
793
794
  return [];
794
795
  }
@@ -841,17 +842,104 @@ function hoistImports(script) {
841
842
  if (buf) imports.push(buf.join("\n"));
842
843
  return { imports: imports.join("\n"), rest: rest.join("\n") };
843
844
  }
844
- async function compileComponent(filePath, publicDir, scopeKey, isApi = false, plugins = [], registry = /* @__PURE__ */ new Map()) {
845
- let source = await fs3.promises.readFile(filePath, "utf-8");
845
+ var __compileMemo = /* @__PURE__ */ new Map();
846
+ function compileMemoKey(filePath2, publicDir, scopeKey, isApi, registry) {
847
+ let st;
848
+ try {
849
+ st = fs3.statSync(filePath2);
850
+ } catch {
851
+ return null;
852
+ }
853
+ const reg = [];
854
+ for (const [p, e] of registry) reg.push(`${p}#${e.index}:${e.scopeKey}:${e.slots.join("|")}`);
855
+ return [filePath2, String(st.mtimeMs), String(st.size), scopeKey, isApi ? "1" : "0", reg.join(";")].join("\0");
856
+ }
857
+ var __compilerStamp = (() => {
858
+ try {
859
+ return String(fs3.statSync(fileURLToPath(import.meta.url)).mtimeMs);
860
+ } catch {
861
+ return "noid";
862
+ }
863
+ })();
864
+ var __diskCacheDir = (() => {
865
+ try {
866
+ const dir = path2.join(os.tmpdir(), "rosetack-compile-cache");
867
+ fs3.mkdirSync(dir, { recursive: true });
868
+ return dir;
869
+ } catch {
870
+ return null;
871
+ }
872
+ })();
873
+ var __diskWrites = 0;
874
+ function __fnv1a(str) {
875
+ let h = 2166136261;
876
+ for (let i = 0; i < str.length; i++) {
877
+ h ^= str.charCodeAt(i);
878
+ h = Math.imul(h, 16777619);
879
+ }
880
+ return (h >>> 0).toString(16).padStart(8, "0");
881
+ }
882
+ function __diskFile(key) {
883
+ return path2.join(__diskCacheDir, __fnv1a(key + "|" + __compilerStamp) + ".json");
884
+ }
885
+ function __diskGet(key) {
886
+ if (!__diskCacheDir || process.env.rosetack_NO_DISK_CACHE === "1") return null;
887
+ try {
888
+ const obj = JSON.parse(fs3.readFileSync(__diskFile(key), "utf-8"));
889
+ if (obj && typeof obj === "object" && typeof obj.ssr === "string") return obj;
890
+ } catch {
891
+ }
892
+ return null;
893
+ }
894
+ function __diskSet(key, result) {
895
+ if (!__diskCacheDir || process.env.rosetack_NO_DISK_CACHE === "1") return;
896
+ try {
897
+ fs3.writeFileSync(__diskFile(key), JSON.stringify(result));
898
+ if ((__diskWrites++ & 511) === 0) {
899
+ try {
900
+ const entries = fs3.readdirSync(__diskCacheDir);
901
+ if (entries.length > 5e3) {
902
+ for (const e of entries) {
903
+ try {
904
+ fs3.unlinkSync(path2.join(__diskCacheDir, e));
905
+ } catch {
906
+ }
907
+ }
908
+ }
909
+ } catch {
910
+ }
911
+ }
912
+ } catch {
913
+ }
914
+ }
915
+ async function compileComponentMemo(filePath2, publicDir, scopeKey, isApi, plugins, registry) {
916
+ if (plugins.length > 0) return compileComponent(filePath2, publicDir, scopeKey, isApi, plugins, registry);
917
+ const key = compileMemoKey(filePath2, publicDir, scopeKey, isApi, registry);
918
+ if (key) {
919
+ const hit = __compileMemo.get(key);
920
+ if (hit) return { ...hit };
921
+ const disk = __diskGet(key);
922
+ if (disk) return disk;
923
+ }
924
+ const result = await compileComponent(filePath2, publicDir, scopeKey, isApi, plugins, registry);
925
+ if (key) {
926
+ if (__compileMemo.size > 500) __compileMemo.clear();
927
+ __compileMemo.set(key, result);
928
+ __diskSet(key, result);
929
+ }
930
+ return result;
931
+ }
932
+ async function compileComponent(filePath2, publicDir, scopeKey, isApi = false, plugins = [], registry = /* @__PURE__ */ new Map()) {
933
+ let source = await fs3.promises.readFile(filePath2, "utf-8");
846
934
  for (const p of plugins) {
847
935
  if (!p.transform) continue;
848
936
  try {
849
- source = await p.transform(source, filePath);
937
+ source = await p.transform(source, filePath2);
850
938
  } catch (err) {
851
939
  throw new RoseError(
852
940
  "E-PLUGIN",
853
- `plugin ${p.name} failed on ${path2.basename(filePath)}: ${err instanceof Error ? err.message : String(err)}`,
854
- { file: filePath, hint: "the error above came from inside the plugin - fix its transform() (or remove the plugin from rosetack.config.js)" }
941
+ `plugin ${p.name} failed on ${path2.basename(filePath2)}: ${err instanceof Error ? err.message : String(err)}`,
942
+ { file: filePath2, hint: "the error above came from inside the plugin - fix its transform() (or remove the plugin from rosetack.config.js)" }
855
943
  );
856
944
  }
857
945
  }
@@ -861,7 +949,7 @@ async function compileComponent(filePath, publicDir, scopeKey, isApi = false, pl
861
949
  const apiMethods = [...rawScript2.matchAll(/(?:^|\n)\s*export\s+(?:async\s+)?function\s+(\w+)\s*\(/g)].map((m) => m[1]).filter((name) => HTTP_METHODS.has(name));
862
950
  const usesContext2 = /getContext\s*\(/.test(rawScript2);
863
951
  const hasPrerender = !usesContext2 && /(?:^|\n)\s*export\s+(?:const|let|var)\s+prerender\s*=\s*true\b/.test(rawScript2);
864
- const hoisted = hoistImports(resolveRoseImports(rawScript2, filePath, registry).script);
952
+ const hoisted = hoistImports(resolveRoseImports(rawScript2, filePath2, registry).script);
865
953
  const ownRuntimeImports = new Set(
866
954
  [...rawScript2.matchAll(/import\s*\{([^}]*)\}\s*from\s*['"]\.\/runtime\.js['"]/g)].flatMap((m) => m[1].split(",").map((s) => s.trim().split(/\s+as\s+/)[0]).filter(Boolean))
867
955
  );
@@ -889,30 +977,31 @@ ${hoisted.rest}`, "ssr").trim()}`,
889
977
  const scopedStyle = styleMatch?.[1] ? scopeCss(styleMatch[1], scopeKey) : "";
890
978
  const sourceNoBlocks = sourceNoHead.replace(STYLE_RE, "");
891
979
  const scriptMatch = source.match(COMPONENT_RE);
892
- const roseResolved = resolveRoseImports(scriptMatch?.[1] ?? "", filePath, registry);
980
+ const roseResolved = resolveRoseImports(scriptMatch?.[1] ?? "", filePath2, registry);
893
981
  const rawScript = roseResolved.script;
982
+ const usesrosetackAuth = rawScript.includes("__rosetackAuth");
894
983
  const roseImports = roseResolved.imports;
895
984
  const { imports: importStmts, rest: scriptNoImports } = hoistImports(rawScript);
896
- if (path2.basename(filePath) !== "_middleware.rose") {
985
+ if (path2.basename(filePath2) !== "_middleware.rose") {
897
986
  for (const spec of nodeOnlyImports(importStmts)) {
898
987
  const at = importStmts.indexOf(spec);
899
988
  throw new RoseError(
900
989
  "E-NODE-ONLY",
901
- `${filePath}: cannot import '${spec}' in a page or component - it never reaches the browser. This module's script ships to the client (its $data bodies included), so move the import to src/pages/_middleware.rose or a pages/api/*.rose handler: those are server-only, and the rows travel to the page through getContext() / $data.`,
990
+ `${filePath2}: cannot import '${spec}' in a page or component - it never reaches the browser. This module's script ships to the client (its $data bodies included), so move the import to src/pages/_middleware.rose or a pages/api/*.rose handler: those are server-only, and the rows travel to the page through getContext() / $data.`,
902
991
  {
903
- file: filePath,
992
+ file: filePath2,
904
993
  line: at >= 0 ? lineOf(importStmts, at) : void 0,
905
994
  hint: `'${spec}' is a server-only module: import it inside src/pages/_middleware.rose (or a pages/api/*.rose handler) instead - a page/component script ships to the browser`
906
995
  }
907
996
  );
908
997
  }
909
998
  }
910
- const isComponent = registry.get(filePath)?.scopeKey.startsWith("components/") ?? false;
999
+ const isComponent = registry.get(filePath2)?.scopeKey.startsWith("components/") ?? false;
911
1000
  if (isComponent && /\$data\s*\(/.test(rawScript)) {
912
1001
  throw new RoseError(
913
1002
  "E-EXPORT",
914
- `${filePath}: $data() is not allowed in a component - an imported component renders synchronously inside its parent. Fetch in the page's $data (or pages/_middleware.rose) and pass the value down as a prop: <Card user={user()}>.`,
915
- { file: filePath, hint: "move the fetch to the page (or the middleware) and pass the value down as a prop" }
1003
+ `${filePath2}: $data() is not allowed in a component - an imported component renders synchronously inside its parent. Fetch in the page's $data (or pages/_middleware.rose) and pass the value down as a prop: <Card user={user()}>.`,
1004
+ { file: filePath2, hint: "move the fetch to the page (or the middleware) and pass the value down as a prop" }
916
1005
  );
917
1006
  }
918
1007
  const usesContext = /getContext\s*\(/.test(rawScript) || /\$store\s*\(/.test(rawScript) || /\$query\s*\(/.test(rawScript);
@@ -926,8 +1015,8 @@ ${hoisted.rest}`, "ssr").trim()}`,
926
1015
  if (prefetch && !["off", "hover", "viewport", "all"].includes(prefetch)) {
927
1016
  throw new RoseError(
928
1017
  "E-EXPORT",
929
- `${filePath}: export const prefetch must be 'off', 'hover', 'viewport' or 'all'`,
930
- { file: filePath, line: lineAt(rawScript, prefetchMatch), hint: "prefetch is the app-global link strategy, declared once in the root _layout.rose: 'off' | 'hover' (default) | 'viewport' | 'all'" }
1018
+ `${filePath2}: export const prefetch must be 'off', 'hover', 'viewport' or 'all'`,
1019
+ { file: filePath2, line: lineAt(rawScript, prefetchMatch), hint: "prefetch is the app-global link strategy, declared once in the root _layout.rose: 'off' | 'hover' (default) | 'viewport' | 'all'" }
931
1020
  );
932
1021
  }
933
1022
  const vitalsMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+vitals\s*=\s*([^;\n]+)\s*;?/);
@@ -935,8 +1024,8 @@ ${hoisted.rest}`, "ssr").trim()}`,
935
1024
  if (vitalsMatch && !vitals) {
936
1025
  throw new RoseError(
937
1026
  "E-EXPORT",
938
- `${filePath}: export const vitals must be true (or be absent - the hook ships only when an app asks for it)`,
939
- { file: filePath, line: lineAt(rawScript, vitalsMatch), hint: "omit the export entirely, or set it to exactly true - the web-vitals hook is opt-in per app" }
1027
+ `${filePath2}: export const vitals must be true (or be absent - the hook ships only when an app asks for it)`,
1028
+ { file: filePath2, line: lineAt(rawScript, vitalsMatch), hint: "omit the export entirely, or set it to exactly true - the web-vitals hook is opt-in per app" }
940
1029
  );
941
1030
  }
942
1031
  const bundleMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+bundle\s*=\s*['"`](\w+)['"`]\s*;?/);
@@ -944,8 +1033,8 @@ ${hoisted.rest}`, "ssr").trim()}`,
944
1033
  if (bundle && !["inline", "split"].includes(bundle)) {
945
1034
  throw new RoseError(
946
1035
  "E-EXPORT",
947
- `${filePath}: export const bundle must be 'inline' or 'split'`,
948
- { file: filePath, line: lineAt(rawScript, bundleMatch), hint: "'inline' (default) is the single-document mode; 'split' is mode B for large apps - route-level chunks, loaded on demand" }
1036
+ `${filePath2}: export const bundle must be 'inline' or 'split'`,
1037
+ { file: filePath2, line: lineAt(rawScript, bundleMatch), hint: "'inline' (default) is the single-document mode; 'split' is mode B for large apps - route-level chunks, loaded on demand" }
949
1038
  );
950
1039
  }
951
1040
  const csrMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+csr\s*=\s*(true|false)\s*;?/);
@@ -961,9 +1050,9 @@ ${hoisted.rest}`, "ssr").trim()}`,
961
1050
  const deadSrc = dead === (/\son:[a-z]+\s*=/.exec(source) ?? void 0) ? source : rawScript;
962
1051
  throw new RoseError(
963
1052
  "E-EXPORT",
964
- `${filePath}: csr = false cannot ship ${dead[0].trim()} - event wiring, onMount/onCleanup and refresh() all need the client bundle. (Forms still work without JS: a native POST runs the server action.)`,
1053
+ `${filePath2}: csr = false cannot ship ${dead[0].trim()} - event wiring, onMount/onCleanup and refresh() all need the client bundle. (Forms still work without JS: a native POST runs the server action.)`,
965
1054
  {
966
- file: filePath,
1055
+ file: filePath2,
967
1056
  line: lineAt(deadSrc, dead),
968
1057
  hint: 'drop csr = false (let the compiler decide), or remove the client-only code - a native <form method="POST"> server action works without the bundle'
969
1058
  }
@@ -979,15 +1068,15 @@ ${hoisted.rest}`, "ssr").trim()}`,
979
1068
  } catch {
980
1069
  throw new RoseError(
981
1070
  "E-EXPORT",
982
- `${filePath}: export const headers must be an object literal`,
983
- { file: filePath, hint: "write it as one literal: export const headers = { 'x-robots-tag': 'noindex' }" }
1071
+ `${filePath2}: export const headers must be an object literal`,
1072
+ { file: filePath2, hint: "write it as one literal: export const headers = { 'x-robots-tag': 'noindex' }" }
984
1073
  );
985
1074
  }
986
1075
  if (!value || typeof value !== "object" || Array.isArray(value) || Object.values(value).some((v) => typeof v !== "string")) {
987
1076
  throw new RoseError(
988
1077
  "E-EXPORT",
989
- `${filePath}: export const headers must be a flat map of string -> string`,
990
- { file: filePath, hint: "every value must be a string literal (a number or an array fails here instead of shipping verbatim)" }
1078
+ `${filePath2}: export const headers must be a flat map of string -> string`,
1079
+ { file: filePath2, hint: "every value must be a string literal (a number or an array fails here instead of shipping verbatim)" }
991
1080
  );
992
1081
  }
993
1082
  headers = value;
@@ -1001,16 +1090,16 @@ ${hoisted.rest}`, "ssr").trim()}`,
1001
1090
  } catch {
1002
1091
  throw new RoseError(
1003
1092
  "E-EXPORT",
1004
- `${filePath}: export const csp must be an object literal`,
1005
- { file: filePath, hint: "write it as one literal: export const csp = { nonce: true }" }
1093
+ `${filePath2}: export const csp must be an object literal`,
1094
+ { file: filePath2, hint: "write it as one literal: export const csp = { nonce: true }" }
1006
1095
  );
1007
1096
  }
1008
1097
  const nonce = value?.nonce;
1009
1098
  if (nonce !== void 0 && typeof nonce !== "boolean") {
1010
1099
  throw new RoseError(
1011
1100
  "E-EXPORT",
1012
- `${filePath}: csp.nonce must be a boolean`,
1013
- { file: filePath, hint: "csp.nonce is a switch: true (per-request nonce, the route becomes dynamic) or absent (the default hashed policy)" }
1101
+ `${filePath2}: csp.nonce must be a boolean`,
1102
+ { file: filePath2, hint: "csp.nonce is a switch: true (per-request nonce, the route becomes dynamic) or absent (the default hashed policy)" }
1014
1103
  );
1015
1104
  }
1016
1105
  cspNonce = nonce === true;
@@ -1023,9 +1112,10 @@ ${hoisted.rest}`, "ssr").trim()}`,
1023
1112
  if (/<form[^>]*\son:[a-z]+\s*=/i.test(source) || /\$action:|data-on-/.test(source)) {
1024
1113
  clientReasons.push("a form bound to a client dispatch ($action)");
1025
1114
  }
1026
- const lifecycle = rawScript.match(/\b(?:onMount|onCleanup|refresh|adopt|\$action|\$setState)\s*\(/);
1115
+ const lifecycle = rawScript.match(/\b(?:onMount|onCleanup|refresh|adopt)\s*\(|(?:\$action|\$effect)\s*\(/);
1027
1116
  if (lifecycle) clientReasons.push(`${lifecycle[0].replace(/\s*\($/, "")}()`);
1028
1117
  if (source.includes("{#defer")) clientReasons.push("{#defer} progressive content");
1118
+ if (source.includes("{#await")) clientReasons.push("{#await} async block");
1029
1119
  const needsClient = clientReasons.length > 0;
1030
1120
  const jsWarnings = [];
1031
1121
  if (!needsClient) {
@@ -1051,6 +1141,8 @@ ${hoisted.rest}`, "ssr").trim()}`,
1051
1141
  const template = scopedStyle ? injectScopeAttr(inlineImages(rawTemplate, publicDir), scopeKey) : inlineImages(rawTemplate, publicDir);
1052
1142
  const decls = extractDecls(script);
1053
1143
  const stateDecls = decls.filter((d) => d.kind === "state" || d.kind === "kv" || d.kind === "persist");
1144
+ const derivedNames = decls.filter((d) => d.kind === "derived").map((d) => d.name);
1145
+ const callifyNames = [...stateDecls.map((s) => s.name), ...derivedNames];
1054
1146
  const setterNames = /* @__PURE__ */ new Map();
1055
1147
  stateDecls.forEach((s) => setterNames.set(s.name, `set${capitalize(s.name)}`));
1056
1148
  const declCode = (d) => {
@@ -1063,65 +1155,97 @@ ${hoisted.rest}`, "ssr").trim()}`,
1063
1155
  if (d.kind === "persist") {
1064
1156
  return `const [${d.name}, ${setterNames.get(d.name)}] = persistState(${JSON.stringify(key)}, ${d.expr});`;
1065
1157
  }
1158
+ if (d.kind === "derived") {
1159
+ return `const ${d.name} = () => (${callifyStateReads(d.expr, callifyNames)});`;
1160
+ }
1066
1161
  if (d.kind === "kv") {
1067
1162
  const mTtl = /^(.*)\s*,\s*(\d+)\s*$/s.exec(d.expr);
1068
1163
  const fnExpr = mTtl ? mTtl[1] : d.expr;
1069
1164
  const ttl = mTtl ? mTtl[2] : "300";
1070
- return `const __had_${d.name} = hasState(${JSON.stringify(key)});
1165
+ return `const __seeded_${d.name} = isSeeded(${JSON.stringify(key)});
1071
1166
  const [${d.name}, set${capitalize(d.name)}] = state(${JSON.stringify(key)}, null);
1072
- if (!__had_${d.name}) set${capitalize(d.name)}(await globalThis.__rosetackKvApi.kvMemo(${JSON.stringify("__kvh:" + scopeKey + ":" + d.name)}, ${fnExpr}, ${ttl}));`;
1167
+ 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)}); }`;
1073
1168
  }
1074
- return `const __had_${d.name} = hasState(${JSON.stringify(key)});
1169
+ return `const __seeded_${d.name} = isSeeded(${JSON.stringify(key)});
1075
1170
  const [${d.name}, set${capitalize(d.name)}] = state(${JSON.stringify(key)}, null);
1076
- if (!__had_${d.name}) set${capitalize(d.name)}(await $data(${fn}));`;
1171
+ if (!__seeded_${d.name}) { const __v_${d.name} = await $data(${fn}); set${capitalize(d.name)}(__v_${d.name}); markSeeded(${JSON.stringify(key)}); }`;
1077
1172
  };
1078
1173
  const nestedDecls = [];
1079
1174
  let spliced = "";
1080
1175
  let pos = 0;
1081
1176
  decls.forEach((d, i) => {
1082
1177
  const top = braceDepthAt(script, d.start) === 0;
1083
- if (!top) nestedDecls.push(d);
1178
+ if (!top) {
1179
+ if (d.kind === "derived") {
1180
+ throw new Error(
1181
+ `${filePath2}: $derived must be a top-level declaration - inside a function body a plain const arrow already does this natively`
1182
+ );
1183
+ }
1184
+ nestedDecls.push(d);
1185
+ }
1084
1186
  spliced += script.slice(pos, d.start) + (top ? `'__rvdecl${i}__';` : "");
1085
1187
  pos = d.end;
1086
1188
  });
1087
1189
  spliced += script.slice(pos);
1088
1190
  let cleanScript = spliced.replace(SETSTATE_RE, (_, key, val) => {
1089
1191
  const trimmedKey = key.trim().replace(/^['"`]|['"`]$/g, "");
1192
+ if (derivedNames.includes(trimmedKey)) {
1193
+ throw new Error(
1194
+ `${filePath2}: $setState('${trimmedKey}', ...) - a $derived value is read-only; make it $state or derive a different expression`
1195
+ );
1196
+ }
1090
1197
  const setter = setterNames.get(trimmedKey) || `set${capitalize(trimmedKey)}`;
1091
1198
  return `${setter}(${val})`;
1092
1199
  });
1093
- cleanScript = callifyStateReads(cleanScript, stateDecls.map((s) => s.name));
1200
+ cleanScript = callifyStateReads(cleanScript, callifyNames);
1094
1201
  cleanScript = cleanScript.replace(/'__rvdecl(\d+)__';/g, (_m, i) => declCode(decls[Number(i)]));
1095
1202
  const stateDeclsCode = nestedDecls.filter((d) => d.kind === "state").map(declCode).join("\n");
1096
1203
  const dataDeclsCode = nestedDecls.filter((d) => d.kind === "data").map(declCode).join("\n");
1097
- const templateCalled = callifyTemplateExprs(template, stateDecls.map((s) => s.name));
1204
+ const templateCalled = callifyTemplateExprs(template, callifyNames);
1098
1205
  const imgDefaulted = templateCalled.replace(/<img\b(?![^>]*?\sloading=)/gi, '<img loading="lazy"').replace(/<img\b(?![^>]*?\sdecoding=)/gi, '<img decoding="async"');
1099
- const wired = wireEventBindings(imgDefaulted, actionNames, filePath);
1100
- const stateKeys = decls.map((d) => d.name);
1206
+ const wired = wireEventBindings(imgDefaulted, actionNames, filePath2);
1207
+ const stateKeys = decls.filter((d) => d.kind !== "derived").map((d) => d.name);
1101
1208
  const bindBindings = [];
1102
1209
  let bindCounter = 0;
1103
1210
  const bindExpanded = wired.template.replace(
1104
- /\sbind:(value|checked|this)\s*=\s*\{([\w$]+)(?:\(\))?\}/g,
1105
- (whole, kind, name) => {
1211
+ /\sbind:(value|checked|this|open)\s*=\s*\{([\w$]+)(?:\(\))?\}/g,
1212
+ (whole, kind, name, offset, str) => {
1106
1213
  if (!stateKeys.includes(name)) {
1107
1214
  throw new Error(
1108
- `${filePath}: bind:${kind}={${name}} must name a $state declaration` + (stateKeys.length ? ` (state keys here: ${stateKeys.join(", ")})` : " (this file declares no $state)")
1215
+ `${filePath2}: bind:${kind}={${name}} must name a $state declaration` + (stateKeys.length ? ` (state keys here: ${stateKeys.join(", ")})` : " (this file declares no $state)")
1109
1216
  );
1110
1217
  }
1111
1218
  if (kind === "this") return ` data-bind-this="${name}"`;
1219
+ const tagStart = str.lastIndexOf("<", offset);
1220
+ const tagText = tagStart >= 0 ? str.slice(tagStart, offset) : "";
1221
+ if (kind === "value" && /^<select[\s>]/i.test(tagText) && /\smultiple\b/i.test(tagText)) {
1222
+ const setterM = setterNames.get(name);
1223
+ const hnameM = `__rvbind_${scopeKey.replace(/\W/g, "_")}_${bindCounter++}`;
1224
+ bindBindings.push({
1225
+ event: "change",
1226
+ fn: `${hnameM}: (e) => ${setterM}(Array.from(e.target.selectedOptions, (o) => o.value))`
1227
+ });
1228
+ return ` data-selmulti={${name}().join(',')} data-on-change="${hnameM}"`;
1229
+ }
1230
+ if (kind === "open") {
1231
+ const setterO = setterNames.get(name);
1232
+ const hnameO = `__rvbind_${scopeKey.replace(/\W/g, "_")}_${bindCounter++}`;
1233
+ bindBindings.push({ event: "toggle", fn: `${hnameO}: (e) => ${setterO}(e.target.open)` });
1234
+ return ` open={${name}()} data-on-toggle="${hnameO}"`;
1235
+ }
1112
1236
  const setter = setterNames.get(name);
1113
1237
  const evt = kind === "checked" ? "change" : "input";
1114
1238
  const hname = `__rvbind_${scopeKey.replace(/\W/g, "_")}_${bindCounter++}`;
1115
1239
  bindBindings.push({
1116
1240
  event: evt,
1117
- fn: kind === "checked" ? `${hname}: (e) => ${setter}(e.target.checked)` : `${hname}: (e) => { const t = e.target; ${setter}(t.type === 'number' || t.type === 'range' ? t.valueAsNumber : t.value); }`
1241
+ fn: kind === "checked" ? `${hname}: (e) => ${setter}(e.target.checked)` : `${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); }`
1118
1242
  });
1119
1243
  const evtAttr = kind === "checked" ? ` data-on-change="${hname}"` : ` data-on-input="${hname}" data-on-change="${hname}"`;
1120
1244
  return ` ${kind}={${name}()}${evtAttr}`;
1121
1245
  }
1122
1246
  );
1123
1247
  const comps = new Map(roseImports.map((r) => {
1124
- const abs = path2.resolve(path2.dirname(filePath), r.specifier);
1248
+ const abs = path2.resolve(path2.dirname(filePath2), r.specifier);
1125
1249
  const hit = registry.get(abs);
1126
1250
  return [r.name, { index: hit.index, slots: hit.slots }];
1127
1251
  }));
@@ -1142,14 +1266,14 @@ if (!__had_${d.name}) set${capitalize(d.name)}(await $data(${fn}));`;
1142
1266
  if (!stateKeys.includes(name)) {
1143
1267
  throw new RoseError(
1144
1268
  "E-TEMPLATE",
1145
- `${filePath}: bind:group={${name}} must name a $state declaration`,
1269
+ `${filePath2}: bind:group={${name}} must name a $state declaration`,
1146
1270
  { hint: "the group state holds the selected value (radio) or an ARRAY of checked values (checkbox) - declare it: let " + name + ' = $state("")' }
1147
1271
  );
1148
1272
  }
1149
1273
  if (!/\stype\s*=\s*["'](radio|checkbox)["']/.test(attrs)) {
1150
1274
  throw new RoseError(
1151
1275
  "E-TEMPLATE",
1152
- `${filePath}: bind:group is for radio and checkbox inputs`,
1276
+ `${filePath2}: bind:group is for radio and checkbox inputs`,
1153
1277
  { hint: '<input type="radio" value="v" bind:group={state}> holds the selected value; type="checkbox" holds an ARRAY of the checked values (declare the state as $state([]))' }
1154
1278
  );
1155
1279
  }
@@ -1158,14 +1282,14 @@ if (!__had_${d.name}) set${capitalize(d.name)}(await $data(${fn}));`;
1158
1282
  if (!vm || /\{/.test(vm[0])) {
1159
1283
  throw new RoseError(
1160
1284
  "E-TEMPLATE",
1161
- `${filePath}: a bind:group input needs a static value attribute`,
1285
+ `${filePath2}: a bind:group input needs a static value attribute`,
1162
1286
  { hint: '<input type="radio" value="free" bind:group={plan}> - the value IS what the state receives' }
1163
1287
  );
1164
1288
  }
1165
1289
  if (/\schecked\s*=/.test(attrs)) {
1166
1290
  throw new RoseError(
1167
1291
  "E-TEMPLATE",
1168
- `${filePath}: a bind:group input cannot also carry checked=`,
1292
+ `${filePath2}: a bind:group input cannot also carry checked=`,
1169
1293
  { hint: "the group state alone decides which inputs are checked" }
1170
1294
  );
1171
1295
  }
@@ -1188,19 +1312,23 @@ if (!__had_${d.name}) set${capitalize(d.name)}(await $data(${fn}));`;
1188
1312
  /\suse:([\w-]+)(\s*=\s*\{([\s\S]*?)\})?/g,
1189
1313
  (_w, name, hasParam, expr) => hasParam ? ` data-use="${name}" data-use-param={JSON.stringify(${expr})}` : ` data-use="${name}"`
1190
1314
  );
1191
- const classExpanded = expandClassDirectives(useExpanded, filePath);
1192
- const styleExpanded = expandStyleDirectives(classExpanded, filePath);
1193
- const keyExpanded = expandKeyBlocks(styleExpanded, filePath);
1315
+ const classExpanded = expandClassDirectives(useExpanded, filePath2);
1316
+ const classMerged = mergeStaticClass(classExpanded);
1317
+ const styleExpanded = expandStyleDirectives(classMerged, filePath2);
1318
+ const transExpanded = expandTransitionDirectives(styleExpanded, filePath2);
1319
+ const animExpanded = expandAnimateDirectives(transExpanded, filePath2);
1320
+ const keyExpanded = expandKeyBlocks(animExpanded, filePath2);
1194
1321
  const elseExpanded = expandIfElse(keyExpanded);
1195
1322
  const deferExpanded = expandDeferBlocks(elseExpanded);
1196
- const fbExpanded = expandBoundaryFallbacks(deferExpanded.template, filePath);
1323
+ const awaitExpanded = expandAwaitBlocks(deferExpanded.template, filePath2);
1324
+ const fbExpanded = expandBoundaryFallbacks(awaitExpanded.template, filePath2);
1197
1325
  const ssrTemplate = rewriteQuotedExprAttrs(fbExpanded.replace(SLOT_NAMED_RE, (_w, attrs, fallback) => {
1198
1326
  const call = `{__slot(${encodeSlotCall(attrs)})}`;
1199
1327
  if (fallback) {
1200
1328
  if (/\{[^{}]*\}/.test(fallback)) {
1201
1329
  throw new RoseError(
1202
1330
  "E-TEMPLATE",
1203
- `${filePath}: slot fallback content must be static markup`,
1331
+ `${filePath2}: slot fallback content must be static markup`,
1204
1332
  { hint: "a {expr} inside a slot fallback has no reactive scope here - render the dynamic part in the parent and pass it as the slot content" }
1205
1333
  );
1206
1334
  }
@@ -1208,7 +1336,7 @@ if (!__had_${d.name}) set${capitalize(d.name)}(await $data(${fn}));`;
1208
1336
  }
1209
1337
  return call;
1210
1338
  }).replace(SLOT_RE, (_w, fallback) => fallback && fallback.trim() ? `{__slotDefault(${JSON.stringify(fallback)})}` : "{__slot__}"), comps);
1211
- assertKnownDirectives(ssrTemplate, filePath);
1339
+ assertKnownDirectives(ssrTemplate, filePath2);
1212
1340
  const compiledTemplate = compileTemplate(ssrTemplate, "h", "__c", null, 0, true, comps);
1213
1341
  const compiledHead = headContent.trim() ? compileHead(headContent) : "";
1214
1342
  const hasNamedSlots = /<slot\s+[^>]*\bname\s*=/.test(template);
@@ -1216,7 +1344,8 @@ if (!__had_${d.name}) set${capitalize(d.name)}(await $data(${fn}));`;
1216
1344
  ${actions.map((a) => a.stmt).join("\n")}` : exportStmts;
1217
1345
  const ssrGuard = guard ? `
1218
1346
  ${guard}` : "";
1219
- const isMiddleware = path2.basename(filePath) === "_middleware.rose";
1347
+ const isMiddleware = path2.basename(filePath2) === "_middleware.rose";
1348
+ const bootCode = deferBootCode(deferExpanded.count, deferExpanded.holds) + (awaitExpanded.blocks.length ? "\n" + awaitBootCode(awaitExpanded.blocks) : "");
1220
1349
  const ssr = isMiddleware ? `${RUNTIME_IMPORTS}
1221
1350
 
1222
1351
  ${importStmts}
@@ -1225,8 +1354,8 @@ ${ssrExports}
1225
1354
  ${ssrGuard}
1226
1355
 
1227
1356
  ${cleanScript}
1228
- ` : generateSSR(cleanScript + deferBootCode(deferExpanded.count, deferExpanded.holds), compiledTemplate, stateDeclsCode, ssrExports, compiledHead, props, hasNamedSlots, importStmts, isComponent, ssrGuard, actions.length > 0, dataDeclsCode);
1229
- const client = generateClient(cleanScript + deferBootCode(deferExpanded.count, deferExpanded.holds), compiledTemplate, stateDeclsCode, eventBindings, exportStmts, compiledHead, props, hasNamedSlots, importStmts, isComponent, dataDeclsCode);
1357
+ ` : generateSSR(cleanScript + bootCode, compiledTemplate, stateDeclsCode, ssrExports, compiledHead, props, hasNamedSlots, importStmts, isComponent, ssrGuard, actions.length > 0, dataDeclsCode);
1358
+ const client = generateClient(cleanScript + bootCode, compiledTemplate, stateDeclsCode, eventBindings, exportStmts, compiledHead, props, hasNamedSlots, importStmts, isComponent, dataDeclsCode);
1230
1359
  return {
1231
1360
  ssr: rewriteRoseImports(ssr, "ssr"),
1232
1361
  client: rewriteRoseImports(client, "client"),
@@ -1250,6 +1379,7 @@ ${cleanScript}
1250
1379
  jsWarnings,
1251
1380
  headers,
1252
1381
  cspNonce,
1382
+ usesrosetackAuth,
1253
1383
  props,
1254
1384
  roseImports,
1255
1385
  isComponent
@@ -1263,6 +1393,13 @@ function minifyDecls(block) {
1263
1393
  }
1264
1394
  function scopeCss(css, key) {
1265
1395
  const attr = `[data-rosetack-c="${key}"]`;
1396
+ const scopeOneSelector = (s) => {
1397
+ const t = s.trim();
1398
+ if (!t.includes(":global")) return `${attr} ${t}`;
1399
+ const stripped = t.replace(/:global\([^()]*\)/g, (m) => m.slice(8, -1)).trim();
1400
+ const outside = t.replace(/:global\([^()]*\)/g, "").trim();
1401
+ return outside ? `${attr} ${stripped}` : stripped;
1402
+ };
1266
1403
  const clean = css.replace(/\/\*[\s\S]*?\*\//g, "");
1267
1404
  let out = "";
1268
1405
  let prelude = "";
@@ -1282,7 +1419,7 @@ function scopeCss(css, key) {
1282
1419
  if (sel.startsWith("@")) {
1283
1420
  out += `${sel}{${/^@(?:-[\w]+-)?keyframes/.test(sel) ? minifyDecls(block) : scopeCss(block, key)}}`;
1284
1421
  } else if (sel) {
1285
- const scoped = sel.split(",").map((s) => `${attr} ${s.trim()}`).join(",");
1422
+ const scoped = sel.split(",").map((s) => scopeOneSelector(s)).join(",");
1286
1423
  out += `${scoped}{${minifyDecls(block)}}`;
1287
1424
  }
1288
1425
  prelude = "";
@@ -1573,7 +1710,7 @@ function autoCall(expr) {
1573
1710
  return /^[A-Za-z_$][\w$]*$/.test(e) ? `${e}()` : e;
1574
1711
  }
1575
1712
  var DEFER_ENABLED = true;
1576
- function expandKeyBlocks(template, filePath) {
1713
+ function expandKeyBlocks(template, filePath2) {
1577
1714
  if (!template.includes("{#key")) return template;
1578
1715
  for (let pass = 0; pass < 10; pass++) {
1579
1716
  const OPEN_RE = /\{#key\s+([^}]+)\}/g;
@@ -1601,7 +1738,7 @@ function expandKeyBlocks(template, filePath) {
1601
1738
  if (closeAt < 0) {
1602
1739
  throw new RoseError(
1603
1740
  "E-TEMPLATE",
1604
- `${filePath}: {#key ${expr}} is never closed`,
1741
+ `${filePath2}: {#key ${expr}} is never closed`,
1605
1742
  { hint: "every {#key} needs its {/key}" }
1606
1743
  );
1607
1744
  }
@@ -1702,7 +1839,46 @@ function expandIfElseOnce(template) {
1702
1839
  }
1703
1840
  return { template: out, changed };
1704
1841
  }
1705
- function expandClassDirectives(template, filePath) {
1842
+ function mergeStaticClass(template) {
1843
+ if (!/\sclass\s*=\s*"/.test(template) || !/\sclass\s*=\s*\{/.test(template)) return template;
1844
+ const TAG_RE = /<([a-zA-Z][^\s>/]*)((?:[^>"']|"[^"]*"|'[^']*')*?)(\/?)>/g;
1845
+ let out = "";
1846
+ let pos = 0;
1847
+ let m;
1848
+ TAG_RE.lastIndex = 0;
1849
+ while (m = TAG_RE.exec(template)) {
1850
+ const [whole, tag, attrs, selfClose] = m;
1851
+ const sm = /\sclass\s*=\s*"([^"]*)"/.exec(attrs);
1852
+ if (!sm) continue;
1853
+ const rm = /\sclass\s*=\s*\{/.exec(attrs);
1854
+ if (!rm || rm.index === sm.index) continue;
1855
+ const open = attrs.indexOf("{", rm.index);
1856
+ let depth = 1;
1857
+ let j = open + 1;
1858
+ while (j < attrs.length && depth > 0) {
1859
+ const ch = attrs[j];
1860
+ if (ch === '"' || ch === "'") {
1861
+ j = skipQuoted(attrs, j);
1862
+ continue;
1863
+ }
1864
+ if (ch === "{") depth++;
1865
+ else if (ch === "}") depth--;
1866
+ j++;
1867
+ }
1868
+ if (depth !== 0) continue;
1869
+ const expr = attrs.slice(open + 1, j - 1);
1870
+ const base = JSON.stringify(sm[1]);
1871
+ const merged = ` class={((v) => v == null ? ${base} : typeof v === 'object' ? ({ ${base}: true, ...v }) : (${base} + ' ' + v))(${expr})}`;
1872
+ const lo = Math.min(sm.index, rm.index);
1873
+ const hiEnd = Math.max(sm.index + sm[0].length, j);
1874
+ const newAttrs = attrs.slice(0, lo) + merged + attrs.slice(hiEnd);
1875
+ out += template.slice(pos, m.index) + `<${tag}${newAttrs}${selfClose}>`;
1876
+ pos = m.index + whole.length;
1877
+ }
1878
+ out += template.slice(pos);
1879
+ return out;
1880
+ }
1881
+ function expandClassDirectives(template, filePath2) {
1706
1882
  if (!template.includes("class:")) return template;
1707
1883
  const TAG_RE = /<([a-zA-Z][^\s>/]*)((?:[^>"']|"[^"]*"|'[^']*')*?)(\/?)>/g;
1708
1884
  let out = "";
@@ -1729,14 +1905,14 @@ function expandClassDirectives(template, filePath) {
1729
1905
  i++;
1730
1906
  }
1731
1907
  if (depth !== 0) {
1732
- throw new RoseError("E-TEMPLATE", `${filePath}: class:${nm[1]}={...} is missing its closing brace`, { file: filePath, hint: "the binding expression needs a matching } before the tag ends" });
1908
+ throw new RoseError("E-TEMPLATE", `${filePath2}: class:${nm[1]}={...} is missing its closing brace`, { file: filePath2, hint: "the binding expression needs a matching } before the tag ends" });
1733
1909
  }
1734
1910
  pairs.push({ name: nm[1], expr: attrs.slice(nm.index + nm[0].length, i - 1), start: nm.index, end: i });
1735
1911
  }
1736
1912
  const clsRe = /(\sclass\s*=\s*)("([^"]*)"|'([^']*)'|\{[^}]*\})/;
1737
1913
  const clsM = clsRe.exec(attrs);
1738
1914
  if (clsM && clsM[2].startsWith("{")) {
1739
- throw new RoseError("E-TEMPLATE", `${filePath}: <${tag}> has both class={...} and class: directives`, { file: filePath, hint: 'merge them: move the dynamic part into a class:NAME={expr} and keep the rest in class="..."' });
1915
+ throw new RoseError("E-TEMPLATE", `${filePath2}: <${tag}> has both class={...} and class: directives`, { file: filePath2, hint: 'merge them: move the dynamic part into a class:NAME={expr} and keep the rest in class="..."' });
1740
1916
  }
1741
1917
  const staticCls = clsM ? clsM[3] ?? clsM[4] ?? "" : "";
1742
1918
  let closure = `(${JSON.stringify(staticCls)}`;
@@ -1760,7 +1936,130 @@ function expandClassDirectives(template, filePath) {
1760
1936
  out += template.slice(pos);
1761
1937
  return out;
1762
1938
  }
1763
- function expandStyleDirectives(template, filePath) {
1939
+ function expandTransitionDirectives(template, filePath2) {
1940
+ if (!/\s(?:transition|in|out):/.test(template)) return template;
1941
+ const TAG_RE = /<([a-zA-Z][^\s>/]*)((?:[^>"']|"[^"]*"|'[^']*')*?)(\/?)>/g;
1942
+ let out = "";
1943
+ let pos = 0;
1944
+ let m;
1945
+ TAG_RE.lastIndex = 0;
1946
+ while (m = TAG_RE.exec(template)) {
1947
+ const [whole, tag, attrs, selfClose] = m;
1948
+ if (!attrs.includes("transition:") && !/\s(?:in|out):/.test(attrs)) continue;
1949
+ const pairs = [];
1950
+ const NAME_RE = /\s(transition|in|out):([\w-]+)(?:\s*=\s*\{)?/g;
1951
+ let nm;
1952
+ while (nm = NAME_RE.exec(attrs)) {
1953
+ let start = nm.index;
1954
+ let end = nm.index + nm[0].length;
1955
+ let params = "";
1956
+ if (nm[0].endsWith("{")) {
1957
+ let depth = 1;
1958
+ let i = end;
1959
+ while (i < attrs.length && depth > 0) {
1960
+ const ch = attrs[i];
1961
+ if (ch === '"' || ch === "'") {
1962
+ i = skipQuoted(attrs, i);
1963
+ continue;
1964
+ }
1965
+ if (ch === "{") depth++;
1966
+ else if (ch === "}") depth--;
1967
+ i++;
1968
+ }
1969
+ if (depth !== 0) {
1970
+ throw new RoseError("E-TEMPLATE", `${filePath2}: transition:${nm[1]}={...} is missing its closing brace`, { file: filePath2, hint: "the transition params expression needs a matching } before the tag ends" });
1971
+ }
1972
+ params = attrs.slice(end, i - 1);
1973
+ end = i;
1974
+ }
1975
+ pairs.push({ dir: nm[1] === "transition" ? "" : nm[1], name: nm[2], params, start, end });
1976
+ }
1977
+ if (pairs.length === 0) continue;
1978
+ let transitionValue = "";
1979
+ for (const p of pairs) {
1980
+ if (transitionValue) transitionValue += "|";
1981
+ transitionValue += (p.dir ? p.dir + ":" : "") + p.name + (p.params ? ":" + p.params : "");
1982
+ }
1983
+ let newAttrs = attrs;
1984
+ for (let k = pairs.length - 1; k >= 0; k--) {
1985
+ newAttrs = newAttrs.slice(0, pairs[k].start) + newAttrs.slice(pairs[k].end);
1986
+ }
1987
+ const transRe = /\sdata-transition\s*=\s*("([^"]*)"|'([^']*)'|\{[^}]*\})/;
1988
+ const tm = transRe.exec(newAttrs);
1989
+ if (tm) {
1990
+ const existing = tm[2] ?? tm[3] ?? "";
1991
+ newAttrs = newAttrs.replace(transRe, ` data-transition="${existing}${transitionValue ? (existing ? "|" : "") + transitionValue : ""}"`);
1992
+ } else {
1993
+ newAttrs = ` data-transition="${transitionValue}"` + newAttrs;
1994
+ }
1995
+ out += template.slice(pos, m.index) + `<${tag}${newAttrs}${selfClose}>`;
1996
+ pos = m.index + whole.length;
1997
+ }
1998
+ out += template.slice(pos);
1999
+ return out;
2000
+ }
2001
+ function expandAnimateDirectives(template, filePath2) {
2002
+ if (!template.includes("animate:")) return template;
2003
+ const TAG_RE = /<([a-zA-Z][^\s>/]*)((?:[^>"']|"[^"]*"|'[^']*')*?)(\/?)>/g;
2004
+ let out = "";
2005
+ let pos = 0;
2006
+ let m;
2007
+ TAG_RE.lastIndex = 0;
2008
+ while (m = TAG_RE.exec(template)) {
2009
+ const [whole, tag, attrs, selfClose] = m;
2010
+ if (!attrs.includes("animate:")) continue;
2011
+ const pairs = [];
2012
+ const NAME_RE = /\sanimate:([\w-]+)(?:\s*=\s*\{)?/g;
2013
+ let nm;
2014
+ while (nm = NAME_RE.exec(attrs)) {
2015
+ let start = nm.index;
2016
+ let end = nm.index + nm[0].length;
2017
+ let params = "";
2018
+ if (nm[0].endsWith("{")) {
2019
+ let depth = 1;
2020
+ let i = end;
2021
+ while (i < attrs.length && depth > 0) {
2022
+ const ch = attrs[i];
2023
+ if (ch === '"' || ch === "'") {
2024
+ i = skipQuoted(attrs, i);
2025
+ continue;
2026
+ }
2027
+ if (ch === "{") depth++;
2028
+ else if (ch === "}") depth--;
2029
+ i++;
2030
+ }
2031
+ if (depth !== 0) {
2032
+ throw new RoseError("E-TEMPLATE", `${filePath2}: animate:${nm[1]}={...} is missing its closing brace`, { file: filePath2, hint: "the animate params expression needs a matching } before the tag ends" });
2033
+ }
2034
+ params = attrs.slice(end, i - 1);
2035
+ end = i;
2036
+ }
2037
+ pairs.push({ name: nm[1], params, start, end });
2038
+ }
2039
+ let animateValue = "";
2040
+ for (const p of pairs) {
2041
+ if (animateValue) animateValue += "|";
2042
+ animateValue += p.name + (p.params ? ":" + p.params : "");
2043
+ }
2044
+ let newAttrs = attrs;
2045
+ for (let k = pairs.length - 1; k >= 0; k--) {
2046
+ newAttrs = newAttrs.slice(0, pairs[k].start) + newAttrs.slice(pairs[k].end);
2047
+ }
2048
+ const animRe = /\sdata-animate\s*=\s*("([^"]*)"|'([^']*)'|\{[^}]*\})/;
2049
+ const am = animRe.exec(newAttrs);
2050
+ if (am) {
2051
+ const existing = am[2] ?? am[3] ?? "";
2052
+ newAttrs = newAttrs.replace(animRe, ` data-animate="${existing}${animateValue ? (existing ? "|" : "") + animateValue : ""}"`);
2053
+ } else {
2054
+ newAttrs = ` data-animate="${animateValue}"` + newAttrs;
2055
+ }
2056
+ out += template.slice(pos, m.index) + `<${tag}${newAttrs}${selfClose}>`;
2057
+ pos = m.index + whole.length;
2058
+ }
2059
+ out += template.slice(pos);
2060
+ return out;
2061
+ }
2062
+ function expandStyleDirectives(template, filePath2) {
1764
2063
  if (!template.includes("style:")) return template;
1765
2064
  const TAG_RE = /<([a-zA-Z][^\s>/]*)((?:[^>"']|"[^"]*"|'[^']*')*?)(\/?)>/g;
1766
2065
  let out = "";
@@ -1787,14 +2086,14 @@ function expandStyleDirectives(template, filePath) {
1787
2086
  i++;
1788
2087
  }
1789
2088
  if (depth !== 0) {
1790
- throw new RoseError("E-TEMPLATE", `${filePath}: style:${nm[1]}={...} is missing its closing brace`, { file: filePath, hint: "the binding expression needs a matching } before the tag ends" });
2089
+ throw new RoseError("E-TEMPLATE", `${filePath2}: style:${nm[1]}={...} is missing its closing brace`, { file: filePath2, hint: "the binding expression needs a matching } before the tag ends" });
1791
2090
  }
1792
2091
  pairs.push({ prop: nm[1], expr: attrs.slice(nm.index + nm[0].length, i - 1), start: nm.index, end: i });
1793
2092
  }
1794
2093
  const styleRe = /(\sstyle\s*=\s*)("([^"]*)"|'([^']*)'|\{[^}]*\})/;
1795
2094
  const stM = styleRe.exec(attrs);
1796
2095
  if (stM && stM[2].startsWith("{")) {
1797
- throw new RoseError("E-TEMPLATE", `${filePath}: <${tag}> has both style={...} and style: directives`, { file: filePath, hint: 'keep the static declarations in style="..." and move the dynamic ones to style:PROP={expr}' });
2096
+ throw new RoseError("E-TEMPLATE", `${filePath2}: <${tag}> has both style={...} and style: directives`, { file: filePath2, hint: 'keep the static declarations in style="..." and move the dynamic ones to style:PROP={expr}' });
1798
2097
  }
1799
2098
  const staticStyle = stM ? stM[3] ?? stM[4] ?? "" : "";
1800
2099
  let closure = `${JSON.stringify(staticStyle.endsWith(";") || staticStyle === "" ? staticStyle : staticStyle + ";")}`;
@@ -1817,7 +2116,7 @@ function expandStyleDirectives(template, filePath) {
1817
2116
  out += template.slice(pos);
1818
2117
  return out;
1819
2118
  }
1820
- function expandBoundaryFallbacks(template, filePath) {
2119
+ function expandBoundaryFallbacks(template, filePath2) {
1821
2120
  if (!template.includes("{:fallback")) return template;
1822
2121
  for (let pass = 0; pass < 10; pass++) {
1823
2122
  const TOK_RE = /\{#boundary\}|\{\/boundary\}|\{:fallback\}/g;
@@ -1861,12 +2160,12 @@ function expandBoundaryFallbacks(template, filePath) {
1861
2160
  if (top !== "boundary") {
1862
2161
  throw new RoseError(
1863
2162
  "E-TEMPLATE",
1864
- `${filePath}: {:fallback} must sit directly inside a {#boundary} block`,
2163
+ `${filePath2}: {:fallback} must sit directly inside a {#boundary} block`,
1865
2164
  { hint: "move it out of the {#if}/{#each} it sits in, or keep the conditional fallback in the parent" }
1866
2165
  );
1867
2166
  }
1868
2167
  if (fbAt >= 0) {
1869
- throw new RoseError("E-TEMPLATE", `${filePath}: a {#boundary} can carry only one {:fallback}`, { hint: "remove the extra {:fallback} segment" });
2168
+ throw new RoseError("E-TEMPLATE", `${filePath2}: a {#boundary} can carry only one {:fallback}`, { hint: "remove the extra {:fallback} segment" });
1870
2169
  }
1871
2170
  fbAt = tm3.index;
1872
2171
  fbLen = tok.length;
@@ -1974,8 +2273,137 @@ function deferBootCode(count, holds = []) {
1974
2273
  }
1975
2274
  return code;
1976
2275
  }
2276
+ function expandAwaitBlocks(template, filePath2) {
2277
+ let out = "";
2278
+ let pos = 0;
2279
+ let n = 0;
2280
+ const blocks = [];
2281
+ for (; ; ) {
2282
+ const openAt = template.indexOf("{#await", pos);
2283
+ if (openAt < 0) break;
2284
+ let i = openAt + 7;
2285
+ let brace = 1;
2286
+ while (i < template.length && brace > 0) {
2287
+ const c = template[i];
2288
+ if (c === "{") brace++;
2289
+ else if (c === "}") brace--;
2290
+ i++;
2291
+ }
2292
+ if (brace !== 0) break;
2293
+ const openLen = i - openAt;
2294
+ const expr = template.slice(openAt + 7, i - 1).trim();
2295
+ if (!expr) {
2296
+ throw new RoseError("E-TEMPLATE", `${filePath2}: {#await} needs a promise expression`, {
2297
+ file: filePath2,
2298
+ hint: "write {#await fetchUsers()}...{:then users}...{/await}"
2299
+ });
2300
+ }
2301
+ const blockOpenRe = /\{\#(if|each|boundary|island|await)\b/g;
2302
+ const blockCloseRe = /\{\/(if|each|boundary|island|await)\}/g;
2303
+ const thenRe = /\{:then\b([^}]*)\}/g;
2304
+ const catchRe = /\{:catch\b([^}]*)\}/g;
2305
+ let d = 1;
2306
+ let j = i;
2307
+ let thenAt = -1, catchAt = -1, closeAt = -1;
2308
+ let thenRaw = "", catchRaw = "";
2309
+ for (; ; ) {
2310
+ blockOpenRe.lastIndex = j;
2311
+ blockCloseRe.lastIndex = j;
2312
+ thenRe.lastIndex = j;
2313
+ catchRe.lastIndex = j;
2314
+ const nextOpen = blockOpenRe.exec(template);
2315
+ const nextClose = blockCloseRe.exec(template);
2316
+ const nextThen = thenRe.exec(template);
2317
+ const nextCatch = catchRe.exec(template);
2318
+ let nearestPos = Infinity, kind = "", m = null;
2319
+ const consider = (mm, k) => {
2320
+ if (mm && mm.index < nearestPos) {
2321
+ nearestPos = mm.index;
2322
+ kind = k;
2323
+ m = mm;
2324
+ }
2325
+ };
2326
+ consider(nextOpen, "open");
2327
+ consider(nextClose, "close");
2328
+ consider(nextThen, "then");
2329
+ consider(nextCatch, "catch");
2330
+ if (!m) break;
2331
+ if (kind === "open") {
2332
+ d++;
2333
+ j = m.index + m[0].length;
2334
+ continue;
2335
+ }
2336
+ if (kind === "close") {
2337
+ if (d === 1 && m[1] === "await") {
2338
+ closeAt = m.index;
2339
+ break;
2340
+ }
2341
+ d--;
2342
+ j = m.index + m[0].length;
2343
+ continue;
2344
+ }
2345
+ if (d === 1) {
2346
+ if (kind === "then" && thenAt < 0) {
2347
+ thenAt = m.index;
2348
+ thenRaw = m[1];
2349
+ } else if (kind === "catch" && catchAt < 0) {
2350
+ catchAt = m.index;
2351
+ catchRaw = m[1];
2352
+ }
2353
+ }
2354
+ j = m.index + m[0].length;
2355
+ }
2356
+ if (closeAt < 0 || thenAt < 0) break;
2357
+ const thenTokenEnd = thenAt + 7 + thenRaw.length;
2358
+ const catchTokenEnd = catchAt >= 0 ? catchAt + 7 + catchRaw.length : -1;
2359
+ const pending = template.slice(i, thenAt);
2360
+ const thenBody = template.slice(thenTokenEnd, catchAt >= 0 ? catchAt : closeAt);
2361
+ const catchBody = catchAt >= 0 ? template.slice(catchTokenEnd, closeAt) : "";
2362
+ const thenVarRaw = thenRaw.trim();
2363
+ const catchVarRaw = catchRaw.trim();
2364
+ const thenVar = /^\w+$/.test(thenVarRaw) ? thenVarRaw : `__rvAwaitThen${n + 1}`;
2365
+ const catchVar = catchAt >= 0 ? /^\w+$/.test(catchVarRaw) ? catchVarRaw : `__rvAwaitCatch${n + 1}` : "";
2366
+ n++;
2367
+ const nn = n;
2368
+ const stateName = `__rvAwait${nn}`;
2369
+ blocks.push({ n: nn, expr, thenVar, catchVar });
2370
+ out += template.slice(pos, openAt);
2371
+ out += `{#if ${stateName}().status === 'pending'}` + pending + "{/if}\n";
2372
+ out += `{#each (${stateName}().status === 'resolved' ? [${stateName}().value] : []) as ${thenVar}}` + thenBody + "{/each}\n";
2373
+ if (catchAt >= 0) {
2374
+ out += `{#each (${stateName}().status === 'rejected' ? [${stateName}().error] : []) as ${catchVar}}` + catchBody + "{/each}\n";
2375
+ }
2376
+ pos = closeAt + 8;
2377
+ }
2378
+ if (n === 0) return { template, blocks };
2379
+ out += template.slice(pos);
2380
+ return { template: out, blocks };
2381
+ }
2382
+ function awaitBootCode(blocks) {
2383
+ let code = "";
2384
+ for (const b of blocks) {
2385
+ const stateName = `__rvAwait${b.n}`;
2386
+ code += `const [${stateName}, set${stateName}] = state("__rvawait${b.n}", { status: 'pending', value: null, error: null });
2387
+ `;
2388
+ code += `onMount(function () {
2389
+ `;
2390
+ code += ` Promise.resolve(${b.expr}).then(function (__rvAwaitVal) {
2391
+ `;
2392
+ code += ` set${stateName}({ status: 'resolved', value: __rvAwaitVal });
2393
+ `;
2394
+ code += ` }).catch(function (__rvAwaitErr) {
2395
+ `;
2396
+ code += ` set${stateName}({ status: 'rejected', error: __rvAwaitErr });
2397
+ `;
2398
+ code += ` });
2399
+ `;
2400
+ code += `});
2401
+ `;
2402
+ }
2403
+ return code;
2404
+ }
1977
2405
  function findBlock(src, kind) {
1978
- const head = kind === "boundary" ? /\{#boundary(?:\s+([^}]*))?\}/g : kind === "if" ? /\{#if\s+([^}]+)\}/g : kind === "island" ? /\{#island(?:\s+name="([^"]*)")?(?:\s+hydrate="([^"]*)")?\s*\}/g : /\{#each\s+([^}]+?)\s+as\s+(\{[^{}]*\}|\[[^[\]]*\]|\w+)(?:\s*,\s*(\w+))?\}/g;
2406
+ const head = kind === "boundary" ? /\{#boundary(?:\s+([^}]*))?\}/g : kind === "if" ? /\{#if\s+([^}]+)\}/g : kind === "island" ? /\{#island(?:\s+name="([^"]*)")?(?:\s+hydrate="([^"]*)")?\s*\}/g : kind === "snippet" ? /\{#snippet\s+(\w+)(?:\s*\(([^)]+)\))?\s*\}/g : /\{#each\s+([^}]+?)\s+as\s+(\{[^{}]*\}|\[[^[\]]*\]|\w+)(?:\s*,\s*(\w+))?(?:\s*\(([^)]+)\))?\}/g;
1979
2407
  const closeRe = new RegExp(`\\{/${kind}\\}`, "g");
1980
2408
  let open;
1981
2409
  while (open = head.exec(src)) {
@@ -1997,7 +2425,7 @@ function findBlock(src, kind) {
1997
2425
  i = nextClose.index + nextClose[0].length;
1998
2426
  if (--depth === 0) {
1999
2427
  const content = src.slice(afterOpen, nextClose.index);
2000
- const groups = kind === "boundary" ? [open[1] ?? "", content] : kind === "island" ? [open[1] ?? "", open[2] ?? "", content] : kind === "if" ? [open[1], content] : [open[1], open[2], open[3] ?? "", content];
2428
+ const groups = kind === "boundary" ? [open[1] ?? "", content] : kind === "island" ? [open[1] ?? "", open[2] ?? "", content] : kind === "snippet" ? [open[1], open[2] ?? "", content] : kind === "if" ? [open[1], content] : [open[1], open[2], open[3] ?? "", open[4] ?? "", content];
2001
2429
  const arr = [src.slice(start, i), ...groups];
2002
2430
  arr.index = start;
2003
2431
  return arr;
@@ -2040,8 +2468,20 @@ function compileHead(head) {
2040
2468
  flush();
2041
2469
  return out;
2042
2470
  }
2043
- var KNOWN_CLOSERS = /* @__PURE__ */ new Set(["if", "each", "boundary", "island"]);
2044
- function assertKnownDirectives(template, filePath) {
2471
+ var KNOWN_CLOSERS = /* @__PURE__ */ new Set(["if", "each", "boundary", "island", "await", "snippet"]);
2472
+ var __blockResCache = /* @__PURE__ */ new Map();
2473
+ function blockCloseRes(kind) {
2474
+ let hit = __blockResCache.get(kind);
2475
+ if (!hit) {
2476
+ hit = {
2477
+ open: new RegExp(`\\{#${kind}\\b[^}]*\\}`, "g"),
2478
+ close: new RegExp(`\\{/${kind}\\}`, "g")
2479
+ };
2480
+ __blockResCache.set(kind, hit);
2481
+ }
2482
+ return hit;
2483
+ }
2484
+ function assertKnownDirectives(template, filePath2) {
2045
2485
  const rawRanges = [];
2046
2486
  const RAW_OPEN = /<(style|script|noscript)\b[^>]*>/gi;
2047
2487
  let raw;
@@ -2067,43 +2507,83 @@ function assertKnownDirectives(template, filePath) {
2067
2507
  if (sigil === "/") {
2068
2508
  throw new RoseError(
2069
2509
  "E-TEMPLATE",
2070
- `${filePath}: {/${word}} does not close anything`,
2071
- { file: filePath, line: lineAt(template, m), hint: "the closers are {/if}, {/each} and {/boundary} - one per block you opened" }
2510
+ `${filePath2}: {/${word}} does not close anything`,
2511
+ { file: filePath2, line: lineAt(template, m), hint: "the closers are {/if}, {/each} and {/boundary} - one per block you opened" }
2072
2512
  );
2073
2513
  }
2074
2514
  if (word === "else") {
2075
- throw new RoseError(
2076
- "E-TEMPLATE",
2077
- `${filePath}: a stray {:else} with no {#if} above it`,
2078
- { file: filePath, line: lineAt(template, m), hint: "{:else} / {:else if cond} belong inside an {#if} ... {/if} block - {#if cond}A{:else}B{/if}" }
2079
- );
2515
+ const netOpens = (re, closer, at) => {
2516
+ let n = 0, mm;
2517
+ re.lastIndex = 0;
2518
+ while (mm = re.exec(template)) {
2519
+ if (mm.index >= at) break;
2520
+ if (!inRaw(mm.index)) n++;
2521
+ }
2522
+ const cr = new RegExp(closer, "g");
2523
+ let c = 0;
2524
+ while (mm = cr.exec(template)) {
2525
+ if (mm.index >= at) break;
2526
+ if (!inRaw(mm.index)) c++;
2527
+ }
2528
+ return n - c;
2529
+ };
2530
+ const ifNet = netOpens(/\{#if\b/g, "\\{/if\\b", m.index);
2531
+ const eachNet = netOpens(/\{#each\b/g, "\\{/each\\b", m.index);
2532
+ if (ifNet <= 0 && eachNet <= 0) {
2533
+ throw new RoseError(
2534
+ "E-TEMPLATE",
2535
+ `${filePath2}: a stray {:else} with no {#if} or {#each} above it`,
2536
+ { file: filePath2, line: lineAt(template, m), hint: "{:else} belongs inside an {#if} ... {/if} or {#each} ... {/each} block" }
2537
+ );
2538
+ }
2539
+ continue;
2080
2540
  }
2081
2541
  if (word === "fallback") {
2082
2542
  throw new RoseError(
2083
2543
  "E-TEMPLATE",
2084
- `${filePath}: a stray {:fallback} with no {#boundary} above it`,
2085
- { file: filePath, line: lineAt(template, m), hint: "{:fallback} belongs directly inside a {#boundary} ... {/boundary} block" }
2544
+ `${filePath2}: a stray {:fallback} with no {#boundary} above it`,
2545
+ { file: filePath2, line: lineAt(template, m), hint: "{:fallback} belongs directly inside a {#boundary} ... {/boundary} block" }
2086
2546
  );
2087
2547
  }
2548
+ if (word === "then" || word === "catch") {
2549
+ const opensBefore = (re, at) => {
2550
+ re.lastIndex = 0;
2551
+ let n = 0, mm;
2552
+ while (mm = re.exec(template)) {
2553
+ if (mm.index >= at) break;
2554
+ if (!inRaw(mm.index)) n++;
2555
+ }
2556
+ return n;
2557
+ };
2558
+ const open = opensBefore(/\{#await\b/g, m.index);
2559
+ const close = opensBefore(/\{\/await\b/g, m.index);
2560
+ if (open <= close) {
2561
+ throw new RoseError(
2562
+ "E-TEMPLATE",
2563
+ `${filePath2}: a stray {:${word}} with no {#await} above it`,
2564
+ { file: filePath2, line: lineAt(template, m), hint: "{:then} / {:catch} belong inside an {#await} ... {/await} block" }
2565
+ );
2566
+ }
2567
+ continue;
2568
+ }
2088
2569
  throw new RoseError(
2089
2570
  "E-TEMPLATE",
2090
- `${filePath}: {:${word}} is not a rosetack directive`,
2091
- { file: filePath, line: lineAt(template, m), hint: "rosetack templates support {#if}/{:else}, {#each} and {#boundary}" }
2571
+ `${filePath2}: {:${word}} is not a rosetack directive`,
2572
+ { file: filePath2, line: lineAt(template, m), hint: "rosetack templates support {#if}/{:else}, {#each} and {#boundary}" }
2092
2573
  );
2093
2574
  }
2094
- const OPENER_RE = /\{#(if|each|boundary|island)\b([^}]*)\}/g;
2575
+ const OPENER_RE = /\{#(if|each|boundary|island|await)\b([^}]*)\}/g;
2095
2576
  while (m = OPENER_RE.exec(template)) {
2096
2577
  if (inRaw(m.index)) continue;
2097
2578
  const [, kind, head] = m;
2098
- if (kind === "each" && !/\bas\s+(\{[^{}]*\}?|\[[^[\]]*\]?|\w+)(?:\s*,\s*\w+)?\s*$/.test(head)) {
2579
+ if (kind === "each" && !/\bas\s+(\{[^{}]*\}?|\[[^[\]]*\]?|\w+)(?:\s*,\s*\w+)?(?:\s*\([^)]*\))?\s*$/.test(head)) {
2099
2580
  throw new RoseError(
2100
2581
  "E-TEMPLATE",
2101
- `${filePath}: {#each ${head.trim()}} is missing its item name`,
2102
- { 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)" }
2582
+ `${filePath2}: {#each ${head.trim()}} is missing its item name`,
2583
+ { file: filePath2, line: lineAt(template, m), hint: "write {#each items() as item} - the name after `as` is what the block body reads (item.id, item.name)" }
2103
2584
  );
2104
2585
  }
2105
- const OPEN_RE = new RegExp(`\\{#${kind}\\b[^}]*\\}`, "g");
2106
- const CLOSE_RE = new RegExp(`\\{/${kind}\\}`, "g");
2586
+ const { open: OPEN_RE, close: CLOSE_RE } = blockCloseRes(kind);
2107
2587
  let depth = 1;
2108
2588
  let i = m.index + m[0].length;
2109
2589
  for (; ; ) {
@@ -2122,8 +2602,8 @@ function assertKnownDirectives(template, filePath) {
2122
2602
  if (depth !== 0) {
2123
2603
  throw new RoseError(
2124
2604
  "E-TEMPLATE",
2125
- `${filePath}: unclosed {#${kind}} - every block needs its {/${kind}}`,
2126
- { file: filePath, line: lineAt(template, m), hint: `add the matching {/${kind}} (an inner {#if} or {#each} closes first, deepest first)` }
2605
+ `${filePath2}: unclosed {#${kind}} - every block needs its {/${kind}}`,
2606
+ { file: filePath2, line: lineAt(template, m), hint: `add the matching {/${kind}} (an inner {#if} or {#each} closes first, deepest first)` }
2127
2607
  );
2128
2608
  }
2129
2609
  }
@@ -2156,6 +2636,7 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
2156
2636
  const islandsMode = /\{#island\b/.test(template);
2157
2637
  const effMarkers = markers && (!islandsMode || islandDepth > 0);
2158
2638
  const nextId = () => `${depth}_${blockId++}`;
2639
+ if (depth === 0) result += "const __snip = {};\n";
2159
2640
  while (remaining.length > 0) {
2160
2641
  const ifMatch = findBlock(remaining, "if");
2161
2642
  const eachMatch = findBlock(remaining, "each");
@@ -2164,11 +2645,13 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
2164
2645
  const exprMatch = firstExpr ? Object.assign([remaining.slice(firstExpr.start, firstExpr.end + 1), firstExpr.expr], { index: firstExpr.start }) : null;
2165
2646
  const compTag = comps.size > 0 ? findCompTag(remaining, comps) : null;
2166
2647
  const islandMatch = findBlock(remaining, "island");
2648
+ const snippetMatch = findBlock(remaining, "snippet");
2167
2649
  const candidates = [];
2168
2650
  if (ifMatch?.index !== void 0) candidates.push({ type: "if", match: ifMatch, index: ifMatch.index });
2169
2651
  if (eachMatch?.index !== void 0) candidates.push({ type: "each", match: eachMatch, index: eachMatch.index });
2170
2652
  if (boundaryMatch?.index !== void 0) candidates.push({ type: "boundary", match: boundaryMatch, index: boundaryMatch.index });
2171
2653
  if (islandMatch?.index !== void 0) candidates.push({ type: "island", match: islandMatch, index: islandMatch.index });
2654
+ if (snippetMatch?.index !== void 0) candidates.push({ type: "snippet", match: snippetMatch, index: snippetMatch.index });
2172
2655
  if (exprMatch?.index !== void 0) candidates.push({ type: "expr", match: exprMatch, index: exprMatch.index });
2173
2656
  if (compTag) candidates.push({ type: "comp", match: exprMatch, index: compTag.start, tag: compTag });
2174
2657
  const earliest = candidates.length > 0 ? candidates.reduce((a, b) => a.index <= b.index ? a : b) : null;
@@ -2214,7 +2697,7 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
2214
2697
  }
2215
2698
  remaining = remaining.substring(earliest.index + earliest.match[0].length);
2216
2699
  } else if (earliest.type === "each") {
2217
- const [, items, item, index, content] = earliest.match;
2700
+ const [, items, item, index, key, content] = earliest.match;
2218
2701
  const before = remaining.substring(0, earliest.index);
2219
2702
  if (before) result += emitChunk(before, acc, closes, scope);
2220
2703
  const call = autoCall(items);
@@ -2233,10 +2716,24 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
2233
2716
  scoped += content.trim().slice(lastSpan);
2234
2717
  const inner = compileTemplate(scoped, "h", "__c", "__s", depth + 1, effMarkers, comps, islandDepth);
2235
2718
  const body = isDestructure ? `const ${item} = __s; ${inner}` : inner;
2719
+ let keyFn = "";
2720
+ if (key) {
2721
+ if (isDestructure) {
2722
+ throw new RoseError(
2723
+ "E-TEMPLATE",
2724
+ `${filePath}: a keyed {#each} keys on a named item's property - write {#each xs as x (x.id)}, not a destructuring pattern`,
2725
+ { file: filePath, hint: "name the item first, then key on one of its properties" }
2726
+ );
2727
+ }
2728
+ let k = key.trim();
2729
+ if (itemRe) k = k.replace(itemRe, "__s");
2730
+ if (indexRe) k = k.replace(indexRe, "__i");
2731
+ keyFn = `, (__s, __i) => (${k})`;
2732
+ }
2236
2733
  result += `const __b${id} = (__s, __c${index ? ", __i" : ""}) => { let h = ''; ${body} return h; };
2237
2734
  `;
2238
2735
  if (effMarkers) {
2239
- result += `${acc} += eachMark(${closes}, () => (${call}), __b${id});
2736
+ result += `${acc} += eachMark(${closes}, () => (${call}), __b${id}${keyFn});
2240
2737
  `;
2241
2738
  } else {
2242
2739
  const param = isDestructure ? "__s" : item;
@@ -2272,6 +2769,16 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
2272
2769
  ` : `try { __bd${id} = __b${id}(${closes}); } catch (e) { $setBoundaryError(e); __bd${id} = ${fbBlock ? `__bf${id}(${closes})` : JSON.stringify(BOUNDARY_FALLBACK)}; }
2273
2770
  `;
2274
2771
  result += `${acc} += __bd${id};
2772
+ `;
2773
+ remaining = remaining.substring(earliest.index + earliest.match[0].length);
2774
+ } else if (earliest.type === "snippet") {
2775
+ const [, name, params, content] = earliest.match;
2776
+ const before = remaining.substring(0, earliest.index);
2777
+ if (before) result += emitChunk(before, acc, closes, scope);
2778
+ const id = nextId();
2779
+ const paramList = params ? params.split(",").map((p) => p.trim()).filter(Boolean).join(",") : "";
2780
+ const inner = compileTemplate(content.trim(), "h", "__c", "__s", depth + 1, effMarkers, comps, islandDepth);
2781
+ result += `__snip.${name} = (__s, __c${paramList ? "," + paramList : ""}) => { let h = ''; ${inner} return h; };
2275
2782
  `;
2276
2783
  remaining = remaining.substring(earliest.index + earliest.match[0].length);
2277
2784
  } else if (earliest.type === "comp") {
@@ -2308,7 +2815,7 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
2308
2815
  }
2309
2816
  content = out + content.slice(lastSpan);
2310
2817
  }
2311
- return `${JSON.stringify(nm)}: (__s, __c) => { let h = ''; ${compileTemplate(content, "h", "__c", "__s", depth + 1, effMarkers, comps, islandDepth)} return h; }`;
2818
+ return `${JSON.stringify(nm)}: (__s, __c) => { let h = ''; ${compileTemplate(content, "h", "__c", scope, depth + 1, effMarkers, comps, islandDepth)} return h; }`;
2312
2819
  });
2313
2820
  const propsObj = parseCompAttrs(tag.attrs).filter((a) => a.name !== "slot").map((a) => {
2314
2821
  if (a.kind === "spread") return `...(${a.value})`;
@@ -2382,6 +2889,33 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
2382
2889
  remaining = remaining.substring(earliest.index + earliest.match[0].length);
2383
2890
  continue;
2384
2891
  }
2892
+ const dbgMatch = /^@debug\b([\s\S]*)$/.exec(trimmed);
2893
+ if (dbgMatch) {
2894
+ if (before) result += emitChunk(before, acc, closes, scope);
2895
+ const names = dbgMatch[1].trim().replace(/,$/, "");
2896
+ result += names ? `console.log('[rosetack:debug]', { ${names} });
2897
+ ` : `console.log('[rosetack:debug]'); debugger;
2898
+ `;
2899
+ remaining = remaining.substring(earliest.index + earliest.match[0].length);
2900
+ continue;
2901
+ }
2902
+ const renderMatch = /^@render\s+([A-Za-z_$][\w$]*)\s*\(([\s\S]*)\)\s*$/.exec(trimmed);
2903
+ if (renderMatch) {
2904
+ const ahead = new RegExp(`\\{#snippet\\s+${renderMatch[1]}\\b`).test(remaining.substring(earliest.index + earliest.match[0].length));
2905
+ if (ahead) {
2906
+ throw new RoseError(
2907
+ "E-TEMPLATE",
2908
+ `${filePath}: {@render ${renderMatch[1]}} runs before its {#snippet ${renderMatch[1]}} is defined`,
2909
+ { file: filePath, hint: "move the {#snippet} definition above the {@render} call - definitions register as the statement stream reaches them" }
2910
+ );
2911
+ }
2912
+ if (before) result += emitChunk(before, acc, closes, scope);
2913
+ const renderArgs = renderMatch[2].trim();
2914
+ result += `${acc} += ((__snip && __snip.${renderMatch[1]}) ? __snip.${renderMatch[1]}(${scope ?? "null"}, ${closes}${renderArgs ? ", " + renderArgs : ""}) : '');
2915
+ `;
2916
+ remaining = remaining.substring(earliest.index + earliest.match[0].length);
2917
+ continue;
2918
+ }
2385
2919
  const attrMatch = before.match(/([\w-]+)=\s*$/);
2386
2920
  if (attrMatch) {
2387
2921
  const lit = before.slice(0, before.length - attrMatch[0].length);
@@ -2510,6 +3044,7 @@ function splitSlots(src) {
2510
3044
  let i = 0;
2511
3045
  let elemDepth = 0;
2512
3046
  let blockDepth = 0;
3047
+ const blockStack = [];
2513
3048
  while (i < src.length) {
2514
3049
  const lt = src.indexOf("<", i);
2515
3050
  const ob = src.indexOf("{#", i);
@@ -2524,8 +3059,14 @@ function splitSlots(src) {
2524
3059
  if (next === ob || next === cb) {
2525
3060
  const close = src.indexOf("}", next);
2526
3061
  const token = src.slice(next, close < 0 ? src.length : close + 1);
2527
- if (next === ob) blockDepth++;
2528
- else blockDepth = Math.max(0, blockDepth - 1);
3062
+ if (next === ob) {
3063
+ const m = /^\{#(\w+)/.exec(token);
3064
+ blockStack.push({ header: token, type: m ? m[1] : "" });
3065
+ blockDepth++;
3066
+ } else {
3067
+ blockDepth = Math.max(0, blockDepth - 1);
3068
+ if (blockStack.length) blockStack.pop();
3069
+ }
2529
3070
  def += token;
2530
3071
  i = next + token.length;
2531
3072
  continue;
@@ -2552,20 +3093,16 @@ function splitSlots(src) {
2552
3093
  }
2553
3094
  if (!selfClosing && !isVoid) elemDepth++;
2554
3095
  const slotName = /\bslot\s*=\s*["'](\w+)["']/.exec(tagText)?.[1];
2555
- if (slotName && (elemDepth !== 1 || blockDepth !== 0)) {
2556
- 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' });
2557
- }
2558
- if (slotName) {
2559
- const stripped = tagText.replace(/\s*slot\s*=\s*["']\w+["']/, "");
3096
+ if (slotName && elemDepth === 1 && blockDepth === 0) {
2560
3097
  if (selfClosing || isVoid) {
2561
- named.set(slotName, (named.get(slotName) ?? "") + stripped);
3098
+ named.set(slotName, (named.get(slotName) ?? "") + tagText.replace(/\s*slot\s*=\s*["']\w+["']/, ""));
2562
3099
  } else {
2563
3100
  const closeIdx = findClose(src, end, nm[2]);
2564
- if (closeIdx < 0) throw new RoseError("E-TEMPLATE", `unclosed <${nm[2]}> inside slot="${slotName}"`, { hint: `add the matching </${nm[2]}> inside the slot content` });
3101
+ if (closeIdx < 0) throw new RoseError("E-TEMPLATE", `unclosed <${nm[2]}> inside slot="${slotName}"`, { hint: `add the matching </${nm[2]}>` });
2565
3102
  const tail = `</${nm[2]}>`;
2566
3103
  const inner = src.slice(end, closeIdx);
2567
3104
  rejectNestedSlot(inner, slotName);
2568
- named.set(slotName, (named.get(slotName) ?? "") + stripped + inner + tail);
3105
+ named.set(slotName, (named.get(slotName) ?? "") + tagText.replace(/\s*slot\s*=\s*["']\w+["']/, "") + inner + tail);
2569
3106
  elemDepth = Math.max(0, elemDepth - 1);
2570
3107
  i = closeIdx + tail.length;
2571
3108
  continue;
@@ -2573,6 +3110,32 @@ function splitSlots(src) {
2573
3110
  i = end;
2574
3111
  continue;
2575
3112
  }
3113
+ if (slotName && blockDepth > 0) {
3114
+ const stripped = tagText.replace(/\s*slot\s*=\s*["']\w+["']/, "");
3115
+ let lifted = "";
3116
+ for (const b of blockStack) lifted += b.header;
3117
+ lifted += stripped;
3118
+ if (selfClosing || isVoid) {
3119
+ for (let k = blockStack.length - 1; k >= 0; k--) lifted += `{/${blockStack[k].type}}`;
3120
+ named.set(slotName, (named.get(slotName) ?? "") + lifted);
3121
+ i = end;
3122
+ continue;
3123
+ }
3124
+ const closeIdx = findClose(src, end, nm[2]);
3125
+ if (closeIdx < 0) throw new RoseError("E-TEMPLATE", `unclosed <${nm[2]}> inside slot="${slotName}"`, { hint: `add the matching </${nm[2]}>` });
3126
+ const tail = `</${nm[2]}>`;
3127
+ lifted += src.slice(end, closeIdx) + tail;
3128
+ for (let k = blockStack.length - 1; k >= 0; k--) lifted += `{/${blockStack[k].type}}`;
3129
+ named.set(slotName, (named.get(slotName) ?? "") + lifted);
3130
+ elemDepth = Math.max(0, elemDepth - 1);
3131
+ i = closeIdx + tail.length;
3132
+ continue;
3133
+ }
3134
+ if (slotName) {
3135
+ 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`, {
3136
+ 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'
3137
+ });
3138
+ }
2576
3139
  def += tagText;
2577
3140
  i = end;
2578
3141
  }
@@ -2593,7 +3156,8 @@ var IMG_MIME = {
2593
3156
  ".svg": "image/svg+xml",
2594
3157
  ".ico": "image/x-icon"
2595
3158
  };
2596
- var INLINE_IMG_MAX = 4096;
3159
+ var INLINE_IMG_MAX = 8192;
3160
+ var INLINE_SVG_MAX = 16384;
2597
3161
  function listImageVariants(publicDir, url) {
2598
3162
  const ext = path2.extname(url);
2599
3163
  const base = path2.basename(url, ext);
@@ -2616,6 +3180,27 @@ function listImageVariants(publicDir, url) {
2616
3180
  }
2617
3181
  return out.sort((a, b) => a.width - b.width);
2618
3182
  }
3183
+ var __imgReadCache = /* @__PURE__ */ new Map();
3184
+ function cachedImageRead(filePath2) {
3185
+ let st;
3186
+ try {
3187
+ st = fs3.statSync(filePath2);
3188
+ } catch {
3189
+ return null;
3190
+ }
3191
+ const hit = __imgReadCache.get(filePath2);
3192
+ if (hit && hit.mtime === st.mtimeMs) return { buffer: hit.buffer, dims: hit.dims };
3193
+ let buffer;
3194
+ try {
3195
+ buffer = fs3.readFileSync(filePath2);
3196
+ } catch {
3197
+ return null;
3198
+ }
3199
+ const dims = readImageSize(filePath2);
3200
+ const entry = { mtime: st.mtimeMs, buffer, dims };
3201
+ __imgReadCache.set(filePath2, entry);
3202
+ return { buffer, dims: entry.dims };
3203
+ }
2619
3204
  function inlineImages(template, publicDir) {
2620
3205
  return template.replace(IMG_RE, (tag) => {
2621
3206
  const src = tag.match(/\bsrc="(\/[^"{}]+)"/);
@@ -2624,17 +3209,15 @@ function inlineImages(template, publicDir) {
2624
3209
  const mime = IMG_MIME[ext];
2625
3210
  if (!mime) return tag;
2626
3211
  const rel = src[1].replace(/^\/public(?=\/)/, "");
2627
- const filePath = path2.join(publicDir, rel);
2628
- let file;
2629
- try {
2630
- file = fs3.readFileSync(filePath);
2631
- } catch {
2632
- return tag;
2633
- }
3212
+ const filePath2 = path2.join(publicDir, rel);
3213
+ const read = cachedImageRead(filePath2);
3214
+ if (!read) return tag;
3215
+ const file = read.buffer;
2634
3216
  const authorDims = /\swidth=/.test(tag) || /\sheight=/.test(tag);
2635
- const dims = authorDims ? null : readImageSize(filePath);
3217
+ const dims = authorDims ? null : read.dims;
2636
3218
  const withDims = (t) => dims ? t.replace(/<img\b/, `<img width="${dims.width}" height="${dims.height}"`) : t;
2637
- if (file.length > INLINE_IMG_MAX) {
3219
+ const inlineMax = ext === ".svg" ? INLINE_SVG_MAX : INLINE_IMG_MAX;
3220
+ if (file.length > inlineMax) {
2638
3221
  const hasSS = /\ssrcset=/.test(tag) || /\ssizes=/.test(tag);
2639
3222
  const variants = hasSS ? [] : listImageVariants(publicDir, rel);
2640
3223
  if (!variants.length) return withDims(tag);
@@ -2675,7 +3258,7 @@ function compileSlot(acc) {
2675
3258
  return `${acc} += String(children);
2676
3259
  `;
2677
3260
  }
2678
- var 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';`;
3261
+ var 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';`;
2679
3262
  var API_RUNTIME_HELPERS = RUNTIME_IMPORTS.replace(/^import\s*\{/, "").replace(/\}\s*from[\s\S]*$/, "").split(",").map((s) => s.trim()).filter(Boolean);
2680
3263
  function propsCode(props) {
2681
3264
  if (props.length === 0) return "";
@@ -2845,7 +3428,7 @@ async function buildProject(root, outDir) {
2845
3428
  files.map((f, i) => [f, { index: i, scopeKey: scopeKeys[i], slots: scanSlotDecls(f) }])
2846
3429
  );
2847
3430
  const compiled = await Promise.all(
2848
- files.map((f, i) => compileComponent(f, path2.join(root, "public"), scopeKeys[i], infos[i].isApi, plugins, registry))
3431
+ files.map((f, i) => compileComponentMemo(f, path2.join(root, "public"), scopeKeys[i], infos[i].isApi, plugins, registry))
2849
3432
  );
2850
3433
  const importsOf = /* @__PURE__ */ new Map();
2851
3434
  files.forEach((_, i) => {
@@ -3050,11 +3633,12 @@ ${notFoundEntries.map((e) => ` ['${e.prefix}', ${e.render}${e.flags}],`).join("
3050
3633
  const guardFlag = compiled[i].guardName ? `, guard: beforeAction_${i}` : "";
3051
3634
  return `{ pattern: '${info.pattern}', path: '${info.routePath}', render: ${compose(i)}, actions: ${actionMap ? `{ ${actionMap} }` : "null"}${guardFlag}${csrFlag}${shellFlag}${bufferFlag}${signalFlag} }`;
3052
3635
  }).join(",\n ");
3636
+ const appUsesAuth = compiled.some((c) => c.usesrosetackAuth);
3053
3637
  const serverEntry = `
3054
3638
  ${serverImports}
3055
3639
  import { renderMarkdown } from './content-md.ts';
3056
- import crypto from 'node:crypto';
3057
- import { setState, persistState, clearRequestState, serializeState, resetRequestContext, setRequestQuery, isLocale, setLocales, localeList, localeDir, setStoreTransport, applyStorePatch, ActionError, StateDelta, setStateDelta, esc } from './runtime.js';
3640
+ ${appUsesAuth ? "import crypto from 'node:crypto';" : "// no route references __rosetackAuth: the node:crypto auth helpers are omitted, keeping the bundle edge-loadable"}
3641
+ import { setState, persistState, clearRequestState, isolateRender, serializeState, resetRequestContext, installContextStore, setRequestQuery, isLocale, setLocales, localeList, localeDir, setStoreTransport, applyStorePatch, ActionError, StateDelta, setStateDelta, esc } from './runtime.js';
3058
3642
  ${runtimePlugins.length > 0 ? `import { hooks as __pluginHooks, hasRequestHooks as __hasRequestHooks, hasResponseHooks as __hasResponseHooks } from './plugins.js';` : `// no plugin declares a runtime hook, so there is no plugins
3059
3643
  // module to import - the runners below stay no-ops and the servers call them
3060
3644
  // unconditionally (one code path, no flags to keep in sync).
@@ -3111,6 +3695,7 @@ if (typeof process !== 'undefined' && typeof process.send === 'function') {
3111
3695
  });
3112
3696
  }
3113
3697
 
3698
+
3114
3699
  // (the cross-machine seam): the cluster relay above covers ONE machine.
3115
3700
  export function __installStoreTransport(send: (name: string, value: unknown) => void): void {
3116
3701
  setStoreTransport(send);
@@ -3131,6 +3716,11 @@ export const routeParams = {
3131
3716
 
3132
3717
  // Routes whose component reads the request context (getContext()), mutates a shared store ($store()), reads the query ($query(), P0-1)
3133
3718
  export const dynamicRoutes = [
3719
+ ${pages.filter(({ i }) => compiled[i].usesContext || compiled[i].cspNonce || compiled[i].buffer || compiled[i].controlSignal || compiled[i].needsClient).map(({ info }) => `'${info.routePath}'`).join(",\n ")}
3720
+ ];
3721
+
3722
+ // Routes that the prerender function should skip (not bake into static files).
3723
+ export const prerenderSkipRoutes = [
3134
3724
  ${pages.filter(({ i }) => compiled[i].usesContext || compiled[i].cspNonce || compiled[i].buffer || compiled[i].controlSignal).map(({ info }) => `'${info.routePath}'`).join(",\n ")}
3135
3725
  ];
3136
3726
 
@@ -3154,6 +3744,8 @@ const __dynCache = new Map();
3154
3744
  export function invalidateRenderCache(): void {
3155
3745
  __dynCache.clear();
3156
3746
  }
3747
+
3748
+
3157
3749
  // Application KV cache primitive (server-side, per-worker in-memory): a zero-dependency store for expensive computations.
3158
3750
  const __kvStore = new Map<string, { v: unknown; exp: number }>();
3159
3751
  // Content collections: src/content/<coll>/*.md scanned once at build time,
@@ -3267,6 +3859,7 @@ function sse(handler: (send: (event: string, data: unknown) => void) => Promise<
3267
3859
  });
3268
3860
  }
3269
3861
  globalThis.__rosetackExtras = { v, jobs, sse };
3862
+ ${appUsesAuth ? `
3270
3863
  const auth = {
3271
3864
  hashPassword(password: string): string {
3272
3865
  const salt = crypto.randomBytes(16).toString("hex");
@@ -3308,6 +3901,7 @@ const auth = {
3308
3901
  },
3309
3902
  };
3310
3903
  globalThis.__rosetackAuth = auth;
3904
+ ` : "// __rosetackAuth helpers omitted: no route references them (keeps the bundle free of node:crypto and edge-loadable)"}
3311
3905
 
3312
3906
  export async function $kv(key: string, compute: () => unknown | Promise<unknown>, ttlSeconds = 300): Promise<unknown> {
3313
3907
  const hit = kv.get(key);
@@ -3538,7 +4132,15 @@ function extractHead(rendered) {
3538
4132
 
3539
4133
  // Form: the submitted FormData of a progressive-enhancement POST.
3540
4134
  export async function renderPage(pathname, form) {
4135
+ // Renders DO overlap in one process: prod-server warms every route in the background at startup.
4136
+ return isolateRender(() => renderPageIsolated(pathname, form));
4137
+ }
4138
+
4139
+ async function renderPageIsolated(pathname, form) {
3541
4140
  clearRequestState();
4141
+ // Cold-start readiness gate (oboext #8): await the app's published DB-ready promise before any $data() read.
4142
+ const appReady = globalThis.__rosetackAppReady;
4143
+ if (appReady) await appReady;
3542
4144
  for (const route of routes) {
3543
4145
  if (matchRoute(route.pattern, pathname)) {
3544
4146
  const patternParts = route.pattern.split('/');
@@ -3707,7 +4309,15 @@ export async function handleApi(method, pathname, request) {
3707
4309
 
3708
4310
  // === Streaming SSR === The static shell (doctype, <head>, body + container open) flushes BEFORE the - possibly slow - render completes: the first byte.
3709
4311
  export async function renderPageStream(pathname, write, shellOpen, clientTag) {
4312
+ // Isolated for the same reason as renderPage: a streaming render awaits inside route.render()
4313
+ return isolateRender(() => renderPageStreamIsolated(pathname, write, shellOpen, clientTag));
4314
+ }
4315
+
4316
+ async function renderPageStreamIsolated(pathname, write, shellOpen, clientTag) {
3710
4317
  clearRequestState();
4318
+ // Cold-start readiness gate (oboext #8): same contract as renderPage \u2014 await the app's published DB-ready promise before streaming the shell.
4319
+ const appReady = globalThis.__rosetackAppReady;
4320
+ if (appReady) await appReady;
3711
4321
  for (const route of routes) {
3712
4322
  if (matchRoute(route.pattern, pathname)) {
3713
4323
  const patternParts = route.pattern.split('/');
@@ -3764,6 +4374,11 @@ export async function renderPageStream(pathname, write, shellOpen, clientTag) {
3764
4374
  }
3765
4375
  return 404;
3766
4376
  }
4377
+ // Prevent tree-shaking of invalidateRenderCache (called from prod-server.ts / edge.ts on non-GET writes).
4378
+ void invalidateRenderCache;
4379
+
4380
+ // Same reason, for the per-request context store: prod-server.ts installs an AsyncLocalStorage adapter.
4381
+ export { installContextStore };
3767
4382
  `;
3768
4383
  try {
3769
4384
  const patterns = [...pages, ...apiRoutes].map(({ info }) => info.pattern);
@@ -3857,7 +4472,7 @@ reportVitals();
3857
4472
  if (!known) {` : ` if (langIdx >= 0 && !isLocale(pathname.split('/')[langIdx])) {`;
3858
4473
  const clientEntry = `
3859
4474
  ${clientImports}
3860
- 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';
4475
+ 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';
3861
4476
 
3862
4477
  // I18n: the dictionaries baked at build time - the client renders any PRELOADED locale from the bundle.
3863
4478
  setLocales(${clientLocalesJson}, '${defaultLocale}');
@@ -4075,11 +4690,19 @@ async function postForm(body, container, pathname) {
4075
4690
  // Call a page's server action by name from any event handler: <button on:click={like}> compiles to $action('like').
4076
4691
  export async function $action(name, e) {
4077
4692
  if (e && e.preventDefault) e.preventDefault();
4693
+ // F34: the pending flag is ordinary signal state - {#if $actionPending()}
4694
+ // disables a submit button while the action is in flight, reactively.
4695
+ const [__rvPending, __rvSetPending] = state('actionPending', false);
4696
+ __rvSetPending(true);
4078
4697
  const body = new FormData();
4079
4698
  body.append('__action', name);
4080
4699
  // An event inside a mount belongs to that mount - the attribute is kept in step with what is currently mounted.
4081
4700
  const box = e && e.target && e.target.closest ? e.target.closest('[data-rosetack]') : null;
4082
- return postForm(body, box || undefined, box ? box.getAttribute('data-rosetack') : undefined);
4701
+ try {
4702
+ return await postForm(body, box || undefined, box ? box.getAttribute('data-rosetack') : undefined);
4703
+ } finally {
4704
+ __rvSetPending(false);
4705
+ }
4083
4706
  }
4084
4707
  // 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.
4085
4708
  setActionDispatcher($action);
@@ -4348,12 +4971,12 @@ function isAncestorDir(layoutPath, pagePath) {
4348
4971
  const pageDir = path2.dirname(pagePath);
4349
4972
  return pageDir === layoutDir || pageDir.startsWith(layoutDir + path2.sep);
4350
4973
  }
4351
- function getRouteInfo(filePath, root) {
4974
+ function getRouteInfo(filePath2, root) {
4352
4975
  const pagesDir = path2.join(root, "src", "pages");
4353
- const relative2 = path2.relative(pagesDir, filePath).replace(/\\/g, "/");
4976
+ const relative2 = path2.relative(pagesDir, filePath2).replace(/\\/g, "/");
4354
4977
  const withoutExt = relative2.replace(/\.rose$/, "");
4355
4978
  const base = path2.posix.basename(withoutExt);
4356
- const isComponent = filePath.replace(/\\/g, "/").includes("/src/components/");
4979
+ const isComponent = filePath2.replace(/\\/g, "/").includes("/src/components/");
4357
4980
  const isLayout = !isComponent && base === "_layout";
4358
4981
  const isNotFound = !isComponent && (base === "404" || base === "_notfound");
4359
4982
  const isError = !isComponent && base === "500";
@@ -4377,7 +5000,7 @@ function getRouteInfo(filePath, root) {
4377
5000
  routePath = "/" + routeParts.join("/");
4378
5001
  }
4379
5002
  return {
4380
- filePath,
5003
+ filePath: filePath2,
4381
5004
  routePath,
4382
5005
  pattern: routePath,
4383
5006
  paramNames: parts.flatMap((p) => {
@@ -4411,6 +5034,7 @@ export {
4411
5034
  loadPlugins,
4412
5035
  scanComponentFiles,
4413
5036
  scanRoseFiles,
5037
+ scopeCss,
4414
5038
  scriptOf,
4415
5039
  templateExprSpans
4416
5040
  };