rosetack 0.1.3 → 0.1.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/deploy/api/rosetack.ts +11 -21
- package/deploy/server.cjs +4 -0
- package/dist-cli/compiler.mjs +2139 -255
- package/dist-cli/edge.mjs +132 -17
- package/dist-cli/rosetack.mjs +2739 -350
- package/dist-cli/runtime.mjs +882 -32
- package/dist-cli/test.mjs +2221 -286
- package/package.json +9 -1
- package/src/FRAMEWORK_VERSION +1 -1
- package/src/cli/content.ts +186 -0
- package/src/cli/edge.ts +21 -3
- package/src/cli/image-size.ts +83 -0
- package/src/cli/index.ts +198 -42
- package/src/cli/origin.ts +9 -0
- package/src/cli/prod-server.ts +475 -0
- package/src/cli/prompt.ts +96 -19
- package/src/cli/shell.ts +79 -11
- package/src/cli/shutdown.ts +54 -0
- package/src/compiler/index.ts +1865 -96
- package/src/runtime/index.ts +991 -46
- package/src/types/rosetack.d.ts +3 -0
package/src/compiler/index.ts
CHANGED
|
@@ -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,14 +13,14 @@ 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)\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;
|
|
19
|
-
const SLOT_RE = /<slot\s
|
|
20
|
+
const SLOT_RE = /<slot\s*\/>|<slot>([\s\S]*?)<\/slot>/g;
|
|
20
21
|
/** A named slot: `<slot name="row" item={post} />` . The lookahead
|
|
21
22
|
* keeps the plain `<slot />` out of it - that one is the default slot. */
|
|
22
|
-
const SLOT_NAMED_RE = /<slot\s+((?=[^>]*\bname\s*=)[^>]*?)
|
|
23
|
+
const SLOT_NAMED_RE = /<slot\s+((?=[^>]*\bname\s*=)[^>]*?)(?:\/>|>([\s\S]*?)<\/slot>)/g;
|
|
23
24
|
|
|
24
25
|
// Encode a named slot tag as the template expression `__slot('row', [['item', (post)]])` - array pairs.
|
|
25
26
|
function encodeSlotCall(attrs: string): string {
|
|
@@ -55,6 +56,8 @@ export interface CompileResult {
|
|
|
55
56
|
usesContext?: boolean;
|
|
56
57
|
/** the component exports `revalidate = N` (ISR window in seconds) */
|
|
57
58
|
revalidate?: number;
|
|
59
|
+
/** the component exports `cache = N` (per-request render memo, seconds) */
|
|
60
|
+
cache?: number;
|
|
58
61
|
/** the component exports `csr = false` (document ships without the client bundle) */
|
|
59
62
|
csr?: boolean;
|
|
60
63
|
/**
|
|
@@ -110,6 +113,8 @@ export interface CompileResult {
|
|
|
110
113
|
* baked file cannot carry a fresh nonce.
|
|
111
114
|
*/
|
|
112
115
|
cspNonce?: boolean;
|
|
116
|
+
/** a route's script references globalThis.__rosetackAuth - emit the node:crypto auth helpers */
|
|
117
|
+
usesrosetackAuth?: boolean;
|
|
113
118
|
/**
|
|
114
119
|
* The component's props - `export let title = 'x'` in its script.
|
|
115
120
|
* A prop is a plain value the caller passes per invocation (never a
|
|
@@ -147,7 +152,7 @@ export interface RouteInfo {
|
|
|
147
152
|
|
|
148
153
|
interface Decl {
|
|
149
154
|
name: string;
|
|
150
|
-
kind: 'state' | 'data';
|
|
155
|
+
kind: 'state' | 'data' | 'kv' | 'persist';
|
|
151
156
|
expr: string;
|
|
152
157
|
start: number;
|
|
153
158
|
end: number;
|
|
@@ -707,19 +712,48 @@ function nodeOnlyImports(importStmts: string): string[] {
|
|
|
707
712
|
* the state declarations, so the arrow closes over the same `count()`/`setN`
|
|
708
713
|
* the rest of the page uses.
|
|
709
714
|
*/
|
|
710
|
-
function wireEventBindings(template: string, actionNames: Set<string>): {
|
|
715
|
+
function wireEventBindings(template: string, actionNames: Set<string>, filePath = '<template>'): {
|
|
711
716
|
template: string;
|
|
712
717
|
bindings: Array<{ event: string; fn: string }>;
|
|
713
718
|
} {
|
|
714
719
|
const bindings: Array<{ event: string; fn: string }> = [];
|
|
715
720
|
let out = '';
|
|
716
721
|
let rest = template;
|
|
722
|
+
const TARGET_MODS: Record<string, string> = { window: 'w', document: 'd' };
|
|
723
|
+
const MOD_PRE: Record<string, (p: string) => string> = {
|
|
724
|
+
preventDefault: () => 'e.preventDefault()',
|
|
725
|
+
stopPropagation: () => 'e.stopPropagation()',
|
|
726
|
+
self: (p) => `const __self = e.target.closest && e.target.closest('[data-${p}-' + e.type + ']'); if (__self && e.target !== __self) return;`,
|
|
727
|
+
};
|
|
728
|
+
const MOD_POST: Record<string, (p: string) => string> = {
|
|
729
|
+
once: (p) => `const __o = e.target && e.target.closest ? e.target.closest('[data-${p}-' + e.type + ']') : null; if (__o) __o.removeAttribute('data-${p}-' + e.type);`,
|
|
730
|
+
};
|
|
731
|
+
const KNOWN_MODS: string[] = [...Object.keys(MOD_PRE), ...Object.keys(MOD_POST), ...Object.keys(TARGET_MODS)];
|
|
717
732
|
for (;;) {
|
|
718
|
-
const m = /\bon:(\w+)\s*=\s*\{/.exec(rest);
|
|
733
|
+
const m = /\bon:(\w+)((?:\|\w+)*)\s*=\s*\{/.exec(rest);
|
|
719
734
|
if (!m) {
|
|
720
735
|
out += rest;
|
|
721
736
|
break;
|
|
722
737
|
}
|
|
738
|
+
const mods = m[2] ? m[2].slice(1).split('|') : [];
|
|
739
|
+
const targets = mods.filter((mod) => TARGET_MODS[mod]);
|
|
740
|
+
if (targets.length > 1) {
|
|
741
|
+
throw new RoseError(
|
|
742
|
+
'E-TEMPLATE',
|
|
743
|
+
`${filePath}: on:${m[1]} carries both |${targets.join(' and |')}`,
|
|
744
|
+
{ hint: 'a handler binds to one target - the element (default), |window or |document' },
|
|
745
|
+
);
|
|
746
|
+
}
|
|
747
|
+
const prefix = targets.length ? 'on' + TARGET_MODS[targets[0]] : 'on';
|
|
748
|
+
for (const mod of mods) {
|
|
749
|
+
if (!KNOWN_MODS.includes(mod)) {
|
|
750
|
+
throw new RoseError(
|
|
751
|
+
'E-TEMPLATE',
|
|
752
|
+
`${filePath}: unknown event modifier |${mod}`,
|
|
753
|
+
{ 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` },
|
|
754
|
+
);
|
|
755
|
+
}
|
|
756
|
+
}
|
|
723
757
|
out += rest.slice(0, m.index);
|
|
724
758
|
let i = m.index + m[0].length;
|
|
725
759
|
let depth = 1;
|
|
@@ -741,7 +775,24 @@ function wireEventBindings(template: string, actionNames: Set<string>): {
|
|
|
741
775
|
i++;
|
|
742
776
|
}
|
|
743
777
|
const expr = rest.slice(m.index + m[0].length, i).trim();
|
|
744
|
-
|
|
778
|
+
const wrap = (body: string): string => {
|
|
779
|
+
if (!mods.length) return body;
|
|
780
|
+
const pre = mods.filter((mod) => MOD_PRE[mod]).map((mod) => MOD_PRE[mod](prefix));
|
|
781
|
+
const post = mods.filter((mod) => MOD_POST[mod]).map((mod) => MOD_POST[mod](prefix));
|
|
782
|
+
return `(e) => {${pre.length ? ' ' + pre.join('; ') + ';' : ''} (${body})(e);${post.length ? ' ' + post.join('; ') + ';' : ''} }`;
|
|
783
|
+
};
|
|
784
|
+
if (mods.length && actionNames.has(expr)) {
|
|
785
|
+
throw new RoseError(
|
|
786
|
+
'E-TEMPLATE',
|
|
787
|
+
`${filePath}: event modifiers are not supported on the server action ${expr}`,
|
|
788
|
+
{ hint: '$action already preventDefaults - drop the modifiers, or bind a local handler that calls $action' },
|
|
789
|
+
);
|
|
790
|
+
}
|
|
791
|
+
if (mods.length) {
|
|
792
|
+
const name = `__h${bindings.length}`;
|
|
793
|
+
out += `data-${prefix}-${m[1]}="${name}"`;
|
|
794
|
+
bindings.push({ event: m[1], fn: `${name}: ${wrap(expr)}` });
|
|
795
|
+
} else if (actionNames.has(expr)) {
|
|
745
796
|
out += `data-on-${m[1]}="$action:${expr}"`;
|
|
746
797
|
} else if (/^\w+$/.test(expr)) {
|
|
747
798
|
out += `data-on-${m[1]}="${expr}"`;
|
|
@@ -827,6 +878,116 @@ function hoistImports(script: string): { imports: string; rest: string } {
|
|
|
827
878
|
return { imports: imports.join('\n'), rest: rest.join('\n') };
|
|
828
879
|
}
|
|
829
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
|
+
|
|
830
991
|
export async function compileComponent(filePath: string, publicDir: string, scopeKey: string, isApi = false, plugins: Plugin[] = [], registry: RoseRegistry = new Map()): Promise<CompileResult> {
|
|
831
992
|
let source = await fs.promises.readFile(filePath, 'utf-8');
|
|
832
993
|
for (const p of plugins) {
|
|
@@ -881,6 +1042,7 @@ export async function compileComponent(filePath: string, publicDir: string, scop
|
|
|
881
1042
|
const scriptMatch = source.match(COMPONENT_RE);
|
|
882
1043
|
const roseResolved = resolveRoseImports(scriptMatch?.[1] ?? '', filePath, registry);
|
|
883
1044
|
const rawScript = roseResolved.script;
|
|
1045
|
+
const usesrosetackAuth = rawScript.includes('__rosetackAuth');
|
|
884
1046
|
const roseImports = roseResolved.imports;
|
|
885
1047
|
const { imports: importStmts, rest: scriptNoImports } = hoistImports(rawScript);
|
|
886
1048
|
if (path.basename(filePath) !== '_middleware.rose') {
|
|
@@ -913,6 +1075,8 @@ export async function compileComponent(filePath: string, publicDir: string, scop
|
|
|
913
1075
|
const hasParams = /(?:^|\n)\s*export\s+(?:(?:const|let|var)\s+|(?:async\s+)?function\s+)params\b/.test(rawScript);
|
|
914
1076
|
const revalidateMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+revalidate\s*=\s*(\d+)\s*;?/);
|
|
915
1077
|
const revalidate = revalidateMatch ? Number(revalidateMatch[1]) : undefined;
|
|
1078
|
+
const cacheMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+cache\s*=\s*(\d+)\s*;?/);
|
|
1079
|
+
const cacheSeconds = cacheMatch ? Number(cacheMatch[1]) : undefined;
|
|
916
1080
|
const prefetchMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+prefetch\s*=\s*['"`](\w+)['"`]\s*;?/);
|
|
917
1081
|
const prefetch = prefetchMatch ? prefetchMatch[1] : undefined;
|
|
918
1082
|
if (prefetch && !['off', 'hover', 'viewport', 'all'].includes(prefetch)) {
|
|
@@ -1020,8 +1184,10 @@ export async function compileComponent(filePath: string, publicDir: string, scop
|
|
|
1020
1184
|
if (/<form[^>]*\son:[a-z]+\s*=/i.test(source) || /\$action:|data-on-/.test(source)) {
|
|
1021
1185
|
clientReasons.push('a form bound to a client dispatch ($action)');
|
|
1022
1186
|
}
|
|
1023
|
-
const lifecycle = rawScript.match(/\b(?:onMount|onCleanup|refresh|adopt
|
|
1187
|
+
const lifecycle = rawScript.match(/\b(?:onMount|onCleanup|refresh|adopt)\s*\(|(?:\$action|\$effect)\s*\(/);
|
|
1024
1188
|
if (lifecycle) clientReasons.push(`${lifecycle[0].replace(/\s*\($/, '')}()`);
|
|
1189
|
+
if (source.includes('{#defer')) clientReasons.push('{#defer} progressive content');
|
|
1190
|
+
if (source.includes('{#await')) clientReasons.push('{#await} async block');
|
|
1025
1191
|
const needsClient = clientReasons.length > 0;
|
|
1026
1192
|
|
|
1027
1193
|
const jsWarnings: string[] = [];
|
|
@@ -1053,7 +1219,9 @@ export async function compileComponent(filePath: string, publicDir: string, scop
|
|
|
1053
1219
|
: inlineImages(rawTemplate, publicDir);
|
|
1054
1220
|
|
|
1055
1221
|
const decls = extractDecls(script);
|
|
1056
|
-
const stateDecls = decls.filter((d) => d.kind === 'state');
|
|
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];
|
|
1057
1225
|
|
|
1058
1226
|
const setterNames = new Map<string, string>();
|
|
1059
1227
|
stateDecls.forEach((s) => setterNames.set(s.name, `set${capitalize(s.name)}`));
|
|
@@ -1065,9 +1233,23 @@ export async function compileComponent(filePath: string, publicDir: string, scop
|
|
|
1065
1233
|
}
|
|
1066
1234
|
const isFn = d.expr.includes('=>') || d.expr.startsWith('function');
|
|
1067
1235
|
const fn = isFn ? d.expr : `() => (${d.expr})`;
|
|
1068
|
-
|
|
1236
|
+
if (d.kind === 'persist') {
|
|
1237
|
+
return `const [${d.name}, ${setterNames.get(d.name)!}] = persistState(${JSON.stringify(key)}, ${d.expr});`;
|
|
1238
|
+
}
|
|
1239
|
+
if (d.kind === 'derived') {
|
|
1240
|
+
return `const ${d.name} = () => (${callifyStateReads(d.expr, callifyNames)});`;
|
|
1241
|
+
}
|
|
1242
|
+
if (d.kind === 'kv') {
|
|
1243
|
+
const mTtl = /^(.*)\s*,\s*(\d+)\s*$/s.exec(d.expr);
|
|
1244
|
+
const fnExpr = mTtl ? mTtl[1] : d.expr;
|
|
1245
|
+
const ttl = mTtl ? mTtl[2] : '300';
|
|
1246
|
+
return `const __seeded_${d.name} = isSeeded(${JSON.stringify(key)});
|
|
1069
1247
|
const [${d.name}, set${capitalize(d.name)}] = state(${JSON.stringify(key)}, null);
|
|
1070
|
-
if (!
|
|
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)}); }`;
|
|
1249
|
+
}
|
|
1250
|
+
return `const __seeded_${d.name} = isSeeded(${JSON.stringify(key)});
|
|
1251
|
+
const [${d.name}, set${capitalize(d.name)}] = state(${JSON.stringify(key)}, null);
|
|
1252
|
+
if (!__seeded_${d.name}) { const __v_${d.name} = await $data(${fn}); set${capitalize(d.name)}(__v_${d.name}); markSeeded(${JSON.stringify(key)}); }`;
|
|
1071
1253
|
};
|
|
1072
1254
|
|
|
1073
1255
|
const nestedDecls: (typeof decls)[number][] = [];
|
|
@@ -1075,7 +1257,14 @@ if (!__had_${d.name}) set${capitalize(d.name)}(await $data(${fn}));`;
|
|
|
1075
1257
|
let pos = 0;
|
|
1076
1258
|
decls.forEach((d, i) => {
|
|
1077
1259
|
const top = braceDepthAt(script, d.start) === 0;
|
|
1078
|
-
if (!top)
|
|
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
|
+
}
|
|
1079
1268
|
spliced += script.slice(pos, d.start) + (top ? `'__rvdecl${i}__';` : '');
|
|
1080
1269
|
pos = d.end;
|
|
1081
1270
|
});
|
|
@@ -1083,29 +1272,178 @@ if (!__had_${d.name}) set${capitalize(d.name)}(await $data(${fn}));`;
|
|
|
1083
1272
|
|
|
1084
1273
|
let cleanScript = spliced.replace(SETSTATE_RE, (_, key, val) => {
|
|
1085
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
|
+
}
|
|
1086
1280
|
const setter = setterNames.get(trimmedKey) || `set${capitalize(trimmedKey)}`;
|
|
1087
1281
|
return `${setter}(${val})`;
|
|
1088
1282
|
});
|
|
1089
|
-
cleanScript = callifyStateReads(cleanScript,
|
|
1283
|
+
cleanScript = callifyStateReads(cleanScript, callifyNames);
|
|
1090
1284
|
cleanScript = cleanScript.replace(/'__rvdecl(\d+)__';/g, (_m, i) => declCode(decls[Number(i)]));
|
|
1091
1285
|
|
|
1092
1286
|
const stateDeclsCode = nestedDecls.filter((d) => d.kind === 'state').map(declCode).join('\n');
|
|
1093
1287
|
const dataDeclsCode = nestedDecls.filter((d) => d.kind === 'data').map(declCode).join('\n');
|
|
1094
1288
|
|
|
1095
|
-
const templateCalled = callifyTemplateExprs(template,
|
|
1096
|
-
const
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
const
|
|
1289
|
+
const templateCalled = callifyTemplateExprs(template, callifyNames);
|
|
1290
|
+
const imgDefaulted = templateCalled
|
|
1291
|
+
.replace(/<img\b(?![^>]*?\sloading=)/gi, '<img loading="lazy"')
|
|
1292
|
+
.replace(/<img\b(?![^>]*?\sdecoding=)/gi, '<img decoding="async"')
|
|
1293
|
+
const wired = wireEventBindings(imgDefaulted, actionNames, filePath);
|
|
1294
|
+
|
|
1295
|
+
const stateKeys = decls.filter((d) => d.kind !== 'derived').map((d) => d.name);
|
|
1296
|
+
|
|
1297
|
+
const bindBindings: Array<{ event: string; fn: string }> = [];
|
|
1298
|
+
let bindCounter = 0;
|
|
1299
|
+
const bindExpanded = wired.template.replace(
|
|
1300
|
+
/\sbind:(value|checked|this|open)\s*=\s*\{([\w$]+)(?:\(\))?\}/g,
|
|
1301
|
+
(whole, kind: string, name: string, offset: number, str: string) => {
|
|
1302
|
+
if (!stateKeys.includes(name)) {
|
|
1303
|
+
throw new Error(
|
|
1304
|
+
`${filePath}: bind:${kind}={${name}} must name a $state declaration` +
|
|
1305
|
+
(stateKeys.length ? ` (state keys here: ${stateKeys.join(', ')})` : ' (this file declares no $state)'),
|
|
1306
|
+
);
|
|
1307
|
+
}
|
|
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
|
+
}
|
|
1326
|
+
const setter = setterNames.get(name)!;
|
|
1327
|
+
const evt = kind === 'checked' ? 'change' : 'input';
|
|
1328
|
+
const hname = `__rvbind_${scopeKey.replace(/\W/g, '_')}_${bindCounter++}`;
|
|
1329
|
+
bindBindings.push({
|
|
1330
|
+
event: evt,
|
|
1331
|
+
fn:
|
|
1332
|
+
kind === 'checked'
|
|
1333
|
+
? `${hname}: (e) => ${setter}(e.target.checked)`
|
|
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); }`,
|
|
1335
|
+
});
|
|
1336
|
+
const evtAttr = kind === 'checked'
|
|
1337
|
+
? ` data-on-change="${hname}"`
|
|
1338
|
+
: ` data-on-input="${hname}" data-on-change="${hname}"`;
|
|
1339
|
+
return ` ${kind}={${name}()}${evtAttr}`;
|
|
1340
|
+
},
|
|
1341
|
+
);
|
|
1100
1342
|
|
|
1101
1343
|
const comps = new Map(roseImports.map((r) => {
|
|
1102
1344
|
const abs = path.resolve(path.dirname(filePath), r.specifier);
|
|
1103
1345
|
const hit = registry.get(abs)!;
|
|
1104
1346
|
return [r.name, { index: hit.index, slots: hit.slots }] as const;
|
|
1105
1347
|
}));
|
|
1106
|
-
const
|
|
1107
|
-
|
|
1108
|
-
|
|
1348
|
+
const groupBindings: Array<{ event: string; fn: string }> = [];
|
|
1349
|
+
let groupCounter = 0;
|
|
1350
|
+
const TAG_SCAN_RE = /<([a-zA-Z][^\s>/]*)((?:[^>"']|"[^"]*"|'[^']*')*?)(\/?)>/g;
|
|
1351
|
+
const groupExpanded = (() => {
|
|
1352
|
+
if (!bindExpanded.includes('bind:group')) return bindExpanded;
|
|
1353
|
+
let out = '';
|
|
1354
|
+
let pos = 0;
|
|
1355
|
+
let m: RegExpExecArray | null;
|
|
1356
|
+
TAG_SCAN_RE.lastIndex = 0;
|
|
1357
|
+
while ((m = TAG_SCAN_RE.exec(bindExpanded))) {
|
|
1358
|
+
const [whole, tag, attrs, selfClose] = m;
|
|
1359
|
+
const gm = /\sbind:group\s*=\s*\{([\w$]+)(?:\(\))?\}/.exec(attrs);
|
|
1360
|
+
if (!gm) continue;
|
|
1361
|
+
const name = gm[1];
|
|
1362
|
+
if (!stateKeys.includes(name)) {
|
|
1363
|
+
throw new RoseError(
|
|
1364
|
+
'E-TEMPLATE',
|
|
1365
|
+
`${filePath}: bind:group={${name}} must name a $state declaration`,
|
|
1366
|
+
{ hint: 'the group state holds the selected value (radio) or an ARRAY of checked values (checkbox) - declare it: let ' + name + ' = $state("")' },
|
|
1367
|
+
);
|
|
1368
|
+
}
|
|
1369
|
+
if (!/\stype\s*=\s*["'](radio|checkbox)["']/.test(attrs)) {
|
|
1370
|
+
throw new RoseError(
|
|
1371
|
+
'E-TEMPLATE',
|
|
1372
|
+
`${filePath}: bind:group is for radio and checkbox inputs`,
|
|
1373
|
+
{ 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([]))' },
|
|
1374
|
+
);
|
|
1375
|
+
}
|
|
1376
|
+
const isArrayGroup = /\stype\s*=\s*["']checkbox["']/.test(attrs);
|
|
1377
|
+
const vm = /\svalue\s*=\s*"([^"]*)"|\svalue\s*=\s*'([^']*)'/.exec(attrs);
|
|
1378
|
+
if (!vm || /\{/.test(vm[0])) {
|
|
1379
|
+
throw new RoseError(
|
|
1380
|
+
'E-TEMPLATE',
|
|
1381
|
+
`${filePath}: a bind:group input needs a static value attribute`,
|
|
1382
|
+
{ hint: '<input type="radio" value="free" bind:group={plan}> - the value IS what the state receives' },
|
|
1383
|
+
);
|
|
1384
|
+
}
|
|
1385
|
+
if (/\schecked\s*=/.test(attrs)) {
|
|
1386
|
+
throw new RoseError(
|
|
1387
|
+
'E-TEMPLATE',
|
|
1388
|
+
`${filePath}: a bind:group input cannot also carry checked=`,
|
|
1389
|
+
{ hint: 'the group state alone decides which inputs are checked' },
|
|
1390
|
+
);
|
|
1391
|
+
}
|
|
1392
|
+
const setter = setterNames.get(name)!;
|
|
1393
|
+
const hname = `__rvbg_${scopeKey.replace(/\W/g, '_')}_${groupCounter++}`;
|
|
1394
|
+
const groupValue = JSON.stringify(vm[1] ?? vm[2]);
|
|
1395
|
+
const checkedExpr = isArrayGroup
|
|
1396
|
+
? `${name}().includes(${groupValue})`
|
|
1397
|
+
: `${name}() === ${groupValue}`;
|
|
1398
|
+
const handlerBody = isArrayGroup
|
|
1399
|
+
? `${setter}(e.target.checked ? [...${name}(), ${groupValue}] : ${name}().filter((x) => x !== ${groupValue}))`
|
|
1400
|
+
: `${setter}(e.target.value)`;
|
|
1401
|
+
groupBindings.push({ event: 'change', fn: `${hname}: (e) => { ${handlerBody}; }` });
|
|
1402
|
+
const newAttrs = attrs.replace(gm[0], ` checked={${checkedExpr}} data-on-change="${hname}"`);
|
|
1403
|
+
out += bindExpanded.slice(pos, m.index) + `<${tag}${newAttrs}${selfClose}>`;
|
|
1404
|
+
pos = m.index + whole.length;
|
|
1405
|
+
}
|
|
1406
|
+
if (pos === 0) return bindExpanded;
|
|
1407
|
+
out += bindExpanded.slice(pos);
|
|
1408
|
+
return out;
|
|
1409
|
+
})();
|
|
1410
|
+
const eventBindings = wired.bindings.concat(bindBindings, groupBindings);
|
|
1411
|
+
const useExpanded = groupExpanded.replace(
|
|
1412
|
+
/\suse:([\w-]+)(\s*=\s*\{([\s\S]*?)\})?/g,
|
|
1413
|
+
(_w, name: string, hasParam: string | undefined, expr: string) =>
|
|
1414
|
+
hasParam
|
|
1415
|
+
? ` data-use="${name}" data-use-param={JSON.stringify(${expr})}`
|
|
1416
|
+
: ` data-use="${name}"`,
|
|
1417
|
+
);
|
|
1418
|
+
const classExpanded = expandClassDirectives(useExpanded, 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);
|
|
1424
|
+
const elseExpanded = expandIfElse(keyExpanded);
|
|
1425
|
+
const deferExpanded = expandDeferBlocks(elseExpanded);
|
|
1426
|
+
const awaitExpanded = expandAwaitBlocks(deferExpanded.template, filePath);
|
|
1427
|
+
const fbExpanded = expandBoundaryFallbacks(awaitExpanded.template, filePath);
|
|
1428
|
+
const ssrTemplate = rewriteQuotedExprAttrs(fbExpanded
|
|
1429
|
+
.replace(SLOT_NAMED_RE, (_w: unknown, attrs: string, fallback: string) => {
|
|
1430
|
+
const call = `{__slot(${encodeSlotCall(attrs)})}`;
|
|
1431
|
+
if (fallback) {
|
|
1432
|
+
if (/\{[^{}]*\}/.test(fallback)) {
|
|
1433
|
+
throw new RoseError(
|
|
1434
|
+
'E-TEMPLATE',
|
|
1435
|
+
`${filePath}: slot fallback content must be static markup`,
|
|
1436
|
+
{ 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' },
|
|
1437
|
+
);
|
|
1438
|
+
}
|
|
1439
|
+
return `{__slot(${encodeSlotCall(attrs)}, ${JSON.stringify(fallback)})}`;
|
|
1440
|
+
}
|
|
1441
|
+
return call;
|
|
1442
|
+
})
|
|
1443
|
+
.replace(SLOT_RE, (_w: unknown, fallback: string) =>
|
|
1444
|
+
fallback && fallback.trim()
|
|
1445
|
+
? `{__slotDefault(${JSON.stringify(fallback)})}`
|
|
1446
|
+
: '{__slot__}'), comps);
|
|
1109
1447
|
assertKnownDirectives(ssrTemplate, filePath);
|
|
1110
1448
|
const compiledTemplate = compileTemplate(ssrTemplate, 'h', '__c', null, 0, true, comps);
|
|
1111
1449
|
const compiledHead = headContent.trim() ? compileHead(headContent) : '';
|
|
@@ -1114,10 +1452,12 @@ if (!__had_${d.name}) set${capitalize(d.name)}(await $data(${fn}));`;
|
|
|
1114
1452
|
const ssrExports = actions.length > 0 ? `${exportStmts}\n${actions.map((a) => a.stmt).join('\n')}` : exportStmts;
|
|
1115
1453
|
const ssrGuard = guard ? `\n${guard}` : '';
|
|
1116
1454
|
const isMiddleware = path.basename(filePath) === '_middleware.rose';
|
|
1455
|
+
const bootCode = deferBootCode(deferExpanded.count, deferExpanded.holds)
|
|
1456
|
+
+ (awaitExpanded.blocks.length ? '\n' + awaitBootCode(awaitExpanded.blocks) : '');
|
|
1117
1457
|
const ssr = isMiddleware
|
|
1118
1458
|
? `${RUNTIME_IMPORTS}\n\n${importStmts}\n\n${ssrExports}\n${ssrGuard}\n\n${cleanScript}\n`
|
|
1119
|
-
: generateSSR(cleanScript, compiledTemplate, stateDeclsCode, ssrExports, compiledHead, props, hasNamedSlots, importStmts, isComponent, ssrGuard, actions.length > 0, dataDeclsCode);
|
|
1120
|
-
const client = generateClient(cleanScript, 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);
|
|
1121
1461
|
|
|
1122
1462
|
return {
|
|
1123
1463
|
ssr: rewriteRoseImports(ssr, 'ssr'),
|
|
@@ -1129,6 +1469,7 @@ if (!__had_${d.name}) set${capitalize(d.name)}(await $data(${fn}));`;
|
|
|
1129
1469
|
hasParams,
|
|
1130
1470
|
usesContext,
|
|
1131
1471
|
revalidate,
|
|
1472
|
+
cache: cacheSeconds,
|
|
1132
1473
|
csr,
|
|
1133
1474
|
shell,
|
|
1134
1475
|
buffer,
|
|
@@ -1141,6 +1482,7 @@ if (!__had_${d.name}) set${capitalize(d.name)}(await $data(${fn}));`;
|
|
|
1141
1482
|
jsWarnings,
|
|
1142
1483
|
headers,
|
|
1143
1484
|
cspNonce,
|
|
1485
|
+
usesrosetackAuth,
|
|
1144
1486
|
props,
|
|
1145
1487
|
roseImports,
|
|
1146
1488
|
isComponent,
|
|
@@ -1169,8 +1511,15 @@ function minifyDecls(block: string): string {
|
|
|
1169
1511
|
* pass through unscoped (their from/to/to selectors are not selectors).
|
|
1170
1512
|
* Global element rules (:root/html/body) belong in the shell's STYLES.
|
|
1171
1513
|
*/
|
|
1172
|
-
function scopeCss(css: string, key: string): string {
|
|
1514
|
+
export function scopeCss(css: string, key: string): string {
|
|
1173
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
|
+
};
|
|
1174
1523
|
const clean = css.replace(/\/\*[\s\S]*?\*\//g, '');
|
|
1175
1524
|
let out = '';
|
|
1176
1525
|
let prelude = '';
|
|
@@ -1190,7 +1539,7 @@ function scopeCss(css: string, key: string): string {
|
|
|
1190
1539
|
if (sel.startsWith('@')) {
|
|
1191
1540
|
out += `${sel}{${/^@(?:-[\w]+-)?keyframes/.test(sel) ? minifyDecls(block) : scopeCss(block, key)}}`;
|
|
1192
1541
|
} else if (sel) {
|
|
1193
|
-
const scoped = sel.split(',').map((s) =>
|
|
1542
|
+
const scoped = sel.split(',').map((s) => scopeOneSelector(s)).join(',');
|
|
1194
1543
|
out += `${scoped}{${minifyDecls(block)}}`;
|
|
1195
1544
|
}
|
|
1196
1545
|
prelude = '';
|
|
@@ -1364,6 +1713,21 @@ export function extractExports(script: string): { clean: string; exports: string
|
|
|
1364
1713
|
return { clean: out, exports: stmts.join('\n'), actions, props, guard: guards.join('\n') };
|
|
1365
1714
|
}
|
|
1366
1715
|
|
|
1716
|
+
const REGEX_PRECEDERS = new Set('(,=:[!&|?{};+-*%<>~^'.split(''));
|
|
1717
|
+
function isRegexStart(src: string, i: number): boolean {
|
|
1718
|
+
let j = i - 1;
|
|
1719
|
+
while (j >= 0 && /\s/.test(src[j])) j--;
|
|
1720
|
+
if (j < 0) return true;
|
|
1721
|
+
const p = src[j];
|
|
1722
|
+
if (REGEX_PRECEDERS.has(p)) return true;
|
|
1723
|
+
if (/[A-Za-z0-9_$]/.test(p)) {
|
|
1724
|
+
const w = /([A-Za-z_$][A-Za-z0-9_$]*)$/.exec(src.slice(0, j + 1));
|
|
1725
|
+
if (!w) return false;
|
|
1726
|
+
return ['return', 'typeof', 'instanceof', 'in', 'of', 'new', 'delete', 'void', 'throw', 'case', 'do', 'else'].includes(w[1]);
|
|
1727
|
+
}
|
|
1728
|
+
return false;
|
|
1729
|
+
}
|
|
1730
|
+
|
|
1367
1731
|
function extractDecls(script: string): Decl[] {
|
|
1368
1732
|
const decls: Decl[] = [];
|
|
1369
1733
|
DECL_RE.lastIndex = 0;
|
|
@@ -1401,7 +1765,7 @@ function extractDecls(script: string): Decl[] {
|
|
|
1401
1765
|
if (script[end] === ';') end++;
|
|
1402
1766
|
decls.push({
|
|
1403
1767
|
name: m[1],
|
|
1404
|
-
kind: m[2] as 'state' | 'data',
|
|
1768
|
+
kind: m[2] as 'state' | 'data' | 'persist' | 'kv' | 'derived',
|
|
1405
1769
|
expr: script.slice(open, i - 1).trim(),
|
|
1406
1770
|
start: m.index,
|
|
1407
1771
|
end,
|
|
@@ -1452,6 +1816,21 @@ function braceDepthAt(src: string, index: number): number {
|
|
|
1452
1816
|
i = close === -1 ? src.length : close + 2;
|
|
1453
1817
|
continue;
|
|
1454
1818
|
}
|
|
1819
|
+
if (ch === '/' && isRegexStart(src, i)) {
|
|
1820
|
+
i++;
|
|
1821
|
+
let inClass = false;
|
|
1822
|
+
while (i < index) {
|
|
1823
|
+
const c2 = src[i];
|
|
1824
|
+
if (c2 === '\\') { i += 2; continue; }
|
|
1825
|
+
if (inClass) { if (c2 === ']') inClass = false; i++; continue; }
|
|
1826
|
+
if (c2 === '[') { inClass = true; i++; continue; }
|
|
1827
|
+
if (c2 === '/') { i++; break; }
|
|
1828
|
+
if (c2 === '\n') break;
|
|
1829
|
+
i++;
|
|
1830
|
+
}
|
|
1831
|
+
while (i < index && /[a-z]/.test(src[i])) i++;
|
|
1832
|
+
continue;
|
|
1833
|
+
}
|
|
1455
1834
|
if (ch === '{') depth++;
|
|
1456
1835
|
else if (ch === '}') depth--;
|
|
1457
1836
|
i++;
|
|
@@ -1484,12 +1863,742 @@ function autoCall(expr: string): string {
|
|
|
1484
1863
|
* Returns a RegExpExecArray-shaped value (index + capture groups in the
|
|
1485
1864
|
* same order the old regexes produced) so the call sites are unchanged.
|
|
1486
1865
|
*/
|
|
1487
|
-
|
|
1866
|
+
|
|
1867
|
+
const DEFER_ENABLED = true;
|
|
1868
|
+
|
|
1869
|
+
/**
|
|
1870
|
+
* F4 ({#key} block): `{#key expr}body{/key}` re-creates the body whenever
|
|
1871
|
+
* `expr` changes - the escape hatch for DOM whose local state must reset
|
|
1872
|
+
* (a form re-keyed by its subject, a chart re-keyed by its dataset).
|
|
1873
|
+
* Pure compiler sugar: it desugars to `{#each [expr] as __rvkv}body{/each}` -
|
|
1874
|
+
* the each's items closure reads expr, so any dependency change re-runs the
|
|
1875
|
+
* map and rebuilds every node, which IS key semantics. Zero runtime change.
|
|
1876
|
+
* Unclosed blocks fail loudly here instead of rendering as prose.
|
|
1877
|
+
*/
|
|
1878
|
+
function expandKeyBlocks(template: string, filePath: string): string {
|
|
1879
|
+
if (!template.includes('{#key')) return template;
|
|
1880
|
+
for (let pass = 0; pass < 10; pass++) {
|
|
1881
|
+
const OPEN_RE = /\{#key\s+([^}]+)\}/g;
|
|
1882
|
+
OPEN_RE.lastIndex = 0;
|
|
1883
|
+
const openM = OPEN_RE.exec(template);
|
|
1884
|
+
if (!openM) return template;
|
|
1885
|
+
const expr = openM[1].trim();
|
|
1886
|
+
const bodyStart = openM.index + openM[0].length;
|
|
1887
|
+
const TOK_RE = /\{[#\/](?:key|if|each|boundary|island)\b[^}]*\}/g;
|
|
1888
|
+
TOK_RE.lastIndex = bodyStart;
|
|
1889
|
+
let depth = 1;
|
|
1890
|
+
let closeAt = -1;
|
|
1891
|
+
let tm: RegExpExecArray | null;
|
|
1892
|
+
while ((tm = TOK_RE.exec(template))) {
|
|
1893
|
+
if (tm[0].startsWith('{#')) { depth++; continue; }
|
|
1894
|
+
depth--;
|
|
1895
|
+
if (depth === 0) { closeAt = tm.index; break; }
|
|
1896
|
+
}
|
|
1897
|
+
if (closeAt < 0) {
|
|
1898
|
+
throw new RoseError(
|
|
1899
|
+
'E-TEMPLATE',
|
|
1900
|
+
`${filePath}: {#key ${expr}} is never closed`,
|
|
1901
|
+
{ hint: 'every {#key} needs its {/key}' },
|
|
1902
|
+
);
|
|
1903
|
+
}
|
|
1904
|
+
template =
|
|
1905
|
+
template.slice(0, openM.index) +
|
|
1906
|
+
`{#each [${expr}] as __rvkv}` +
|
|
1907
|
+
template.slice(bodyStart, closeAt) +
|
|
1908
|
+
'{/each}' +
|
|
1909
|
+
template.slice(closeAt + '{/key}'.length);
|
|
1910
|
+
}
|
|
1911
|
+
return template;
|
|
1912
|
+
}
|
|
1913
|
+
|
|
1914
|
+
/**
|
|
1915
|
+
* F2 (ergonomics): `{:else}` and `{:else if cond}` on {#if} blocks - the
|
|
1916
|
+
* branch syntax every other template language has, retracted here after the
|
|
1917
|
+
* author judged the earlier refusal over-strict. One pass walks every {#if}
|
|
1918
|
+
* block, splits its TOP-LEVEL `{:else}` chain (nested blocks' elses are
|
|
1919
|
+
* theirs), and re-emits the block as complementary {#if}s:
|
|
1920
|
+
* {#if A}a{:else}b{/if} -> {#if A}a{/if}{#if !(A)}b{/if}
|
|
1921
|
+
* {#if A}a{:else if B}b{:else}c{/if}
|
|
1922
|
+
* -> {#if A}a{/if}{#if !(A)}{#if B}b{/if}{#if !(B)}c{/if}{/if}
|
|
1923
|
+
* Zero new runtime, zero new marker kinds: wire()/ifMark already adopt and
|
|
1924
|
+
* flip both shapes, and each condition re-evaluates - free for the pure
|
|
1925
|
+
* state reads that are the only legal condition kind here. Runs BEFORE
|
|
1926
|
+
* defer expansion (so a {:else} inside a {#defer} body lands on expanded
|
|
1927
|
+
* ground) and repeated until stable, because nested ifs with their own
|
|
1928
|
+
* elses surface one level per pass. Defer bodies are transparent to the
|
|
1929
|
+
* depth walk on purpose: {#defer} is not a block kind, and every {#if}
|
|
1930
|
+
* inside it is balanced on its own.
|
|
1931
|
+
*/
|
|
1932
|
+
function expandIfElseOnce(template: string): { template: string; changed: boolean } {
|
|
1933
|
+
const TOK_RE = /\{#(?:if|each|boundary|island)\b[^}]*\}|\{\/(?:if|each|boundary|island)\s*\}|\{:else(?:\s+if\s+[^}]*)?\}/g;
|
|
1934
|
+
let out = '';
|
|
1935
|
+
let pos = 0;
|
|
1936
|
+
let changed = false;
|
|
1937
|
+
for (;;) {
|
|
1938
|
+
const openM = /\{#(if|each)\s+([^}]+)\}/g.exec(template.slice(pos));
|
|
1939
|
+
if (!openM) { out += template.slice(pos); break; }
|
|
1940
|
+
const kind = openM[1];
|
|
1941
|
+
const head = openM[2];
|
|
1942
|
+
const start = pos + openM.index;
|
|
1943
|
+
const cond = kind === 'if' ? head.trim() : '';
|
|
1944
|
+
const bodyStart = start + openM[0].length;
|
|
1945
|
+
out += template.slice(pos, start);
|
|
1946
|
+
|
|
1947
|
+
TOK_RE.lastIndex = bodyStart;
|
|
1948
|
+
let depth = 1;
|
|
1949
|
+
let closeAt = -1;
|
|
1950
|
+
let closeLen = 0;
|
|
1951
|
+
const elses: Array<{ at: number; len: number; cond: string | null }> = [];
|
|
1952
|
+
let tm: RegExpExecArray | null;
|
|
1953
|
+
while ((tm = TOK_RE.exec(template))) {
|
|
1954
|
+
const tok = tm[0];
|
|
1955
|
+
if (tok.startsWith('{:else')) {
|
|
1956
|
+
if (depth === 1) {
|
|
1957
|
+
const condM = /^\{:else\s+if\s+([^}]*)\}$/.exec(tok);
|
|
1958
|
+
elses.push({ at: tm.index, len: tok.length, cond: condM ? condM[1].trim() : null });
|
|
1959
|
+
}
|
|
1960
|
+
continue;
|
|
1961
|
+
}
|
|
1962
|
+
if (tok.startsWith('{#')) { depth++; continue; }
|
|
1963
|
+
depth--;
|
|
1964
|
+
if (depth === 0) { closeAt = tm.index; closeLen = tok.length; break; }
|
|
1965
|
+
}
|
|
1966
|
+
if (closeAt < 0 || elses.length === 0) {
|
|
1967
|
+
out += template.slice(start, closeAt < 0 ? template.length : closeAt + closeLen);
|
|
1968
|
+
if (closeAt < 0) break;
|
|
1969
|
+
pos = closeAt + closeLen;
|
|
1970
|
+
continue;
|
|
1971
|
+
}
|
|
1972
|
+
const body = template.slice(bodyStart, closeAt);
|
|
1973
|
+
if (kind === 'each') {
|
|
1974
|
+
const lastBare = [...elses].reverse().find((e) => e.cond === null);
|
|
1975
|
+
if (!lastBare) {
|
|
1976
|
+
out += template.slice(start, closeAt + closeLen);
|
|
1977
|
+
pos = closeAt + closeLen;
|
|
1978
|
+
continue;
|
|
1979
|
+
}
|
|
1980
|
+
const relLast = lastBare.at - bodyStart;
|
|
1981
|
+
const eachBody = body.slice(0, relLast);
|
|
1982
|
+
const elseBody = body.slice(relLast + lastBare.len);
|
|
1983
|
+
const itemsExpr = head.replace(/\s+as\s+[\w,\s]*$/, '').trim();
|
|
1984
|
+
out += template.slice(start, bodyStart) + eachBody + '{/each}'
|
|
1985
|
+
+ `{#if !(${itemsExpr}.length)}${elseBody}{/if}`;
|
|
1986
|
+
pos = closeAt + closeLen;
|
|
1987
|
+
changed = true;
|
|
1988
|
+
continue;
|
|
1989
|
+
}
|
|
1990
|
+
const branches: Array<{ cond: string | null; body: string }> = [];
|
|
1991
|
+
let cursor = 0;
|
|
1992
|
+
for (let i = 0; i < elses.length; i++) {
|
|
1993
|
+
const e = elses[i];
|
|
1994
|
+
const rel = e.at - bodyStart;
|
|
1995
|
+
branches.push({ cond: i === 0 ? null : elses[i - 1].cond, body: body.slice(cursor, rel) });
|
|
1996
|
+
cursor = rel + e.len;
|
|
1997
|
+
}
|
|
1998
|
+
branches.push({ cond: elses[elses.length - 1].cond, body: body.slice(cursor) });
|
|
1999
|
+
const first = branches.shift()!;
|
|
2000
|
+
const build = (bs: Array<{ cond: string | null; body: string }>): string => {
|
|
2001
|
+
if (!bs.length) return '';
|
|
2002
|
+
const head = bs[0];
|
|
2003
|
+
const rest = bs.slice(1);
|
|
2004
|
+
if (head.cond == null) return head.body;
|
|
2005
|
+
let s = `{#if ${head.cond}}${head.body}{/if}`;
|
|
2006
|
+
if (rest.length) s += `{#if !(${head.cond})}` + build(rest) + `{/if}`;
|
|
2007
|
+
return s;
|
|
2008
|
+
};
|
|
2009
|
+
let emitted = `{#if ${cond}}${first.body}{/if}`;
|
|
2010
|
+
if (branches.length) emitted += `{#if !(${cond})}` + build(branches) + `{/if}`;
|
|
2011
|
+
out += emitted;
|
|
2012
|
+
pos = closeAt + closeLen;
|
|
2013
|
+
changed = true;
|
|
2014
|
+
}
|
|
2015
|
+
return { template: out, changed };
|
|
2016
|
+
}
|
|
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
|
+
|
|
2065
|
+
/**
|
|
2066
|
+
* F2c (class: directive): `class:NAME={expr}` merges with the tag's static
|
|
2067
|
+
* class into ONE reactive class attribute whose closure concatenates the
|
|
2068
|
+
* static value plus each conditional segment - one attrMark, one data-b
|
|
2069
|
+
* marker, all conditions re-evaluated together on every toggle. This runs
|
|
2070
|
+
* AFTER callifyTemplateExprs, so the expressions arrive pre-callified and
|
|
2071
|
+
* are re-emitted verbatim inside a template literal. A tag that already
|
|
2072
|
+
* carries a REACTIVE class={...} cannot merge (two writers, one attribute)
|
|
2073
|
+
* and fails here, at the .rose file.
|
|
2074
|
+
*/
|
|
2075
|
+
function expandClassDirectives(template: string, filePath: string): string {
|
|
2076
|
+
if (!template.includes('class:')) return template;
|
|
2077
|
+
const TAG_RE = /<([a-zA-Z][^\s>/]*)((?:[^>"']|"[^"]*"|'[^']*')*?)(\/?)>/g;
|
|
2078
|
+
let out = '';
|
|
2079
|
+
let pos = 0;
|
|
2080
|
+
let m: RegExpExecArray | null;
|
|
2081
|
+
TAG_RE.lastIndex = 0;
|
|
2082
|
+
while ((m = TAG_RE.exec(template))) {
|
|
2083
|
+
const [whole, tag, attrs, selfClose] = m;
|
|
2084
|
+
if (!attrs.includes('class:')) continue;
|
|
2085
|
+
const pairs: Array<{ name: string; expr: string; start: number; end: number }> = [];
|
|
2086
|
+
const NAME_RE = /\sclass:([\w-]+)\s*=\s*\{/g;
|
|
2087
|
+
let nm: RegExpExecArray | null;
|
|
2088
|
+
while ((nm = NAME_RE.exec(attrs))) {
|
|
2089
|
+
let i = nm.index + nm[0].length;
|
|
2090
|
+
let depth = 1;
|
|
2091
|
+
while (i < attrs.length && depth > 0) {
|
|
2092
|
+
const ch = attrs[i];
|
|
2093
|
+
if (ch === '"' || ch === "'") { i = skipQuoted(attrs, i); continue; }
|
|
2094
|
+
if (ch === '{') depth++;
|
|
2095
|
+
else if (ch === '}') depth--;
|
|
2096
|
+
i++;
|
|
2097
|
+
}
|
|
2098
|
+
if (depth !== 0) {
|
|
2099
|
+
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' });
|
|
2100
|
+
}
|
|
2101
|
+
pairs.push({ name: nm[1], expr: attrs.slice(nm.index + nm[0].length, i - 1), start: nm.index, end: i });
|
|
2102
|
+
}
|
|
2103
|
+
const clsRe = /(\sclass\s*=\s*)("([^"]*)"|'([^']*)'|\{[^}]*\})/;
|
|
2104
|
+
const clsM = clsRe.exec(attrs);
|
|
2105
|
+
if (clsM && clsM[2].startsWith('{')) {
|
|
2106
|
+
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="..."' });
|
|
2107
|
+
}
|
|
2108
|
+
const staticCls = clsM ? (clsM[3] ?? clsM[4] ?? '') : '';
|
|
2109
|
+
let closure = `(${JSON.stringify(staticCls)}`;
|
|
2110
|
+
for (const p of pairs) {
|
|
2111
|
+
closure += `+((${p.expr})?${JSON.stringify(' ' + p.name)}:'')`;
|
|
2112
|
+
}
|
|
2113
|
+
closure += `)`;
|
|
2114
|
+
let newAttrs = attrs;
|
|
2115
|
+
for (let k = pairs.length - 1; k >= 0; k--) {
|
|
2116
|
+
newAttrs = newAttrs.slice(0, pairs[k].start) + newAttrs.slice(pairs[k].end);
|
|
2117
|
+
}
|
|
2118
|
+
if (clsM) {
|
|
2119
|
+
newAttrs = newAttrs.replace(clsRe, ` class={${closure}}`);
|
|
2120
|
+
} else {
|
|
2121
|
+
newAttrs = ` class={${closure}}` + newAttrs;
|
|
2122
|
+
}
|
|
2123
|
+
out += template.slice(pos, m.index) + `<${tag}${newAttrs}${selfClose}>`;
|
|
2124
|
+
pos = m.index + whole.length;
|
|
2125
|
+
}
|
|
2126
|
+
if (pos === 0) return template;
|
|
2127
|
+
out += template.slice(pos);
|
|
2128
|
+
return out;
|
|
2129
|
+
}
|
|
2130
|
+
|
|
2131
|
+
/**
|
|
2132
|
+
* F2f (style: directive): `style:PROP={expr}` merges with the tag's static
|
|
2133
|
+
* style into ONE reactive style attribute - the overrides are appended AFTER
|
|
2134
|
+
* the static declarations, so CSS last-wins makes them authoritative, exactly
|
|
2135
|
+
* the expected precedence. Same quote-aware tag scanner and same
|
|
2136
|
+
* reactive-class={...} conflict rule as expandClassDirectives.
|
|
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
|
+
|
|
2284
|
+
function expandStyleDirectives(template: string, filePath: string): string {
|
|
2285
|
+
if (!template.includes('style:')) return template;
|
|
2286
|
+
const TAG_RE = /<([a-zA-Z][^\s>/]*)((?:[^>"']|"[^"]*"|'[^']*')*?)(\/?)>/g;
|
|
2287
|
+
let out = '';
|
|
2288
|
+
let pos = 0;
|
|
2289
|
+
let m: RegExpExecArray | null;
|
|
2290
|
+
TAG_RE.lastIndex = 0;
|
|
2291
|
+
while ((m = TAG_RE.exec(template))) {
|
|
2292
|
+
const [whole, tag, attrs, selfClose] = m;
|
|
2293
|
+
if (!attrs.includes('style:')) continue;
|
|
2294
|
+
const pairs: Array<{ prop: string; expr: string; start: number; end: number }> = [];
|
|
2295
|
+
const NAME_RE = /\sstyle:([\w-]+)\s*=\s*\{/g;
|
|
2296
|
+
let nm: RegExpExecArray | null;
|
|
2297
|
+
while ((nm = NAME_RE.exec(attrs))) {
|
|
2298
|
+
let i = nm.index + nm[0].length;
|
|
2299
|
+
let depth = 1;
|
|
2300
|
+
while (i < attrs.length && depth > 0) {
|
|
2301
|
+
const ch = attrs[i];
|
|
2302
|
+
if (ch === '"' || ch === "'") { i = skipQuoted(attrs, i); continue; }
|
|
2303
|
+
if (ch === '{') depth++;
|
|
2304
|
+
else if (ch === '}') depth--;
|
|
2305
|
+
i++;
|
|
2306
|
+
}
|
|
2307
|
+
if (depth !== 0) {
|
|
2308
|
+
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' });
|
|
2309
|
+
}
|
|
2310
|
+
pairs.push({ prop: nm[1], expr: attrs.slice(nm.index + nm[0].length, i - 1), start: nm.index, end: i });
|
|
2311
|
+
}
|
|
2312
|
+
const styleRe = /(\sstyle\s*=\s*)("([^"]*)"|'([^']*)'|\{[^}]*\})/;
|
|
2313
|
+
const stM = styleRe.exec(attrs);
|
|
2314
|
+
if (stM && stM[2].startsWith('{')) {
|
|
2315
|
+
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}' });
|
|
2316
|
+
}
|
|
2317
|
+
const staticStyle = stM ? (stM[3] ?? stM[4] ?? '') : '';
|
|
2318
|
+
let closure = `${JSON.stringify(staticStyle.endsWith(';') || staticStyle === '' ? staticStyle : staticStyle + ';')}`;
|
|
2319
|
+
for (const p of pairs) {
|
|
2320
|
+
closure += `+${JSON.stringify(p.prop + ':')}+(${p.expr})+';'`;
|
|
2321
|
+
}
|
|
2322
|
+
let newAttrs = attrs;
|
|
2323
|
+
for (let k = pairs.length - 1; k >= 0; k--) {
|
|
2324
|
+
newAttrs = newAttrs.slice(0, pairs[k].start) + newAttrs.slice(pairs[k].end);
|
|
2325
|
+
}
|
|
2326
|
+
if (stM) {
|
|
2327
|
+
newAttrs = newAttrs.replace(styleRe, ` style={${closure}}`);
|
|
2328
|
+
} else {
|
|
2329
|
+
newAttrs = ` style={${closure}}` + newAttrs;
|
|
2330
|
+
}
|
|
2331
|
+
out += template.slice(pos, m.index) + `<${tag}${newAttrs}${selfClose}>`;
|
|
2332
|
+
pos = m.index + whole.length;
|
|
2333
|
+
}
|
|
2334
|
+
if (pos === 0) return template;
|
|
2335
|
+
out += template.slice(pos);
|
|
2336
|
+
return out;
|
|
2337
|
+
}
|
|
2338
|
+
|
|
2339
|
+
/**
|
|
2340
|
+
* F11 (boundary {:fallback}): extracts each {#boundary} block's top-level
|
|
2341
|
+
* `{:fallback}` segment and encodes it as a base64 `__fb` attribute on the
|
|
2342
|
+
* boundary opener — base64 so the encoded markup survives every `[^}]*`
|
|
2343
|
+
* attr scan downstream. The dispatch decodes it and compiles the fallback
|
|
2344
|
+
* like any block (reactive exprs supported). Nested boundaries surface one
|
|
2345
|
+
* level per pass; a stray {:fallback} is left for assertKnownDirectives.
|
|
2346
|
+
*/
|
|
2347
|
+
function expandBoundaryFallbacks(template: string, filePath: string): string {
|
|
2348
|
+
if (!template.includes('{:fallback')) return template;
|
|
2349
|
+
for (let pass = 0; pass < 10; pass++) {
|
|
2350
|
+
const TOK_RE = /\{#boundary\}|\{\/boundary\}|\{:fallback\}/g;
|
|
2351
|
+
let out = '';
|
|
2352
|
+
let pos = 0;
|
|
2353
|
+
let changed = false;
|
|
2354
|
+
let tm: RegExpExecArray | null;
|
|
2355
|
+
while ((tm = TOK_RE.exec(template))) {
|
|
2356
|
+
if (tm[0] !== '{#boundary}') continue;
|
|
2357
|
+
const start = tm.index;
|
|
2358
|
+
const bodyStart = start + tm[0].length;
|
|
2359
|
+
let depth = 1;
|
|
2360
|
+
let closeAt = -1;
|
|
2361
|
+
let tm2: RegExpExecArray | null;
|
|
2362
|
+
while ((tm2 = TOK_RE.exec(template))) {
|
|
2363
|
+
if (tm2[0] === '{#boundary}') { depth++; continue; }
|
|
2364
|
+
if (tm2[0] === '{/boundary}') { depth--; if (depth === 0) { closeAt = tm2.index; break; } }
|
|
2365
|
+
}
|
|
2366
|
+
if (closeAt < 0) break;
|
|
2367
|
+
const body = template.slice(bodyStart, closeAt);
|
|
2368
|
+
const BTOK2 = /\{#(boundary|if|each|key|island)(?:\s+[^}]*)?\}|\{\/(?:boundary|if|each|key|island)\s*\}|\{:fallback\}/g;
|
|
2369
|
+
const kindStack = ['boundary'];
|
|
2370
|
+
let d = 1;
|
|
2371
|
+
let fbAt = -1;
|
|
2372
|
+
let fbLen = 0;
|
|
2373
|
+
let tm3: RegExpExecArray | null;
|
|
2374
|
+
BTOK2.lastIndex = 0;
|
|
2375
|
+
while ((tm3 = BTOK2.exec(body))) {
|
|
2376
|
+
const tok = tm3[0];
|
|
2377
|
+
if (tok === '{:fallback}') {
|
|
2378
|
+
const top = kindStack[kindStack.length - 1];
|
|
2379
|
+
if (top !== 'boundary') {
|
|
2380
|
+
throw new RoseError(
|
|
2381
|
+
'E-TEMPLATE',
|
|
2382
|
+
`${filePath}: {:fallback} must sit directly inside a {#boundary} block`,
|
|
2383
|
+
{ hint: 'move it out of the {#if}/{#each} it sits in, or keep the conditional fallback in the parent' },
|
|
2384
|
+
);
|
|
2385
|
+
}
|
|
2386
|
+
if (fbAt >= 0) {
|
|
2387
|
+
throw new RoseError('E-TEMPLATE', `${filePath}: a {#boundary} can carry only one {:fallback}`, { hint: 'remove the extra {:fallback} segment' });
|
|
2388
|
+
}
|
|
2389
|
+
fbAt = tm3.index;
|
|
2390
|
+
fbLen = tok.length;
|
|
2391
|
+
continue;
|
|
2392
|
+
}
|
|
2393
|
+
if (tok.startsWith('{#')) { d++; kindStack.push(tok.slice(2, tok.length - 1).trim().split(/\s/)[0]); continue; }
|
|
2394
|
+
d--; kindStack.pop();
|
|
2395
|
+
}
|
|
2396
|
+
if (fbAt < 0) continue;
|
|
2397
|
+
const custom = body.slice(0, fbAt);
|
|
2398
|
+
const fbMarkup = body.slice(fbAt + fbLen);
|
|
2399
|
+
const b64 = Buffer.from(fbMarkup, 'utf-8').toString('base64');
|
|
2400
|
+
out += template.slice(pos, start) + `{#boundary __fb="${b64}"}` + custom + '{/boundary}';
|
|
2401
|
+
pos = closeAt + '{/boundary}'.length;
|
|
2402
|
+
changed = true;
|
|
2403
|
+
}
|
|
2404
|
+
if (!changed) break;
|
|
2405
|
+
template = out + template.slice(pos);
|
|
2406
|
+
}
|
|
2407
|
+
return template;
|
|
2408
|
+
}
|
|
2409
|
+
|
|
2410
|
+
function expandIfElse(template: string): string { for (let pass = 0; pass < 10; pass++) {
|
|
2411
|
+
if (!/\{:else\b/.test(template)) return template;
|
|
2412
|
+
const r = expandIfElseOnce(template);
|
|
2413
|
+
template = r.template;
|
|
2414
|
+
if (!r.changed) return template;
|
|
2415
|
+
}
|
|
2416
|
+
return template;
|
|
2417
|
+
}
|
|
2418
|
+
|
|
2419
|
+
function expandDeferBlocks(template: string): { template: string; count: number; holds: number[] } {
|
|
2420
|
+
|
|
2421
|
+
if (!DEFER_ENABLED) {
|
|
2422
|
+
const openRe = /\{#defer(?:\s+hold=\\d+)?\}/g;
|
|
2423
|
+
let out = '';
|
|
2424
|
+
let dpos = 0;
|
|
2425
|
+
for (;;) {
|
|
2426
|
+
openRe.lastIndex = dpos;
|
|
2427
|
+
const openM = openRe.exec(template);
|
|
2428
|
+
if (!openM) break;
|
|
2429
|
+
const openAt = openM.index;
|
|
2430
|
+
const openLen = openM[0].length;
|
|
2431
|
+
const closeAt = template.indexOf('{/defer}', openAt + openLen);
|
|
2432
|
+
if (closeAt < 0) break;
|
|
2433
|
+
out += template.slice(dpos, openAt) + template.slice(openAt + openLen, closeAt);
|
|
2434
|
+
dpos = closeAt + 8;
|
|
2435
|
+
}
|
|
2436
|
+
return { template: dpos === 0 ? template : out, count: 0, holds: [] };
|
|
2437
|
+
}
|
|
2438
|
+
let count = 0;
|
|
2439
|
+
const holds: number[] = [];
|
|
2440
|
+
let out = '';
|
|
2441
|
+
let pos = 0;
|
|
2442
|
+
const openRe = /\{#defer(?:\s+hold=(\d+))?\}/g;
|
|
2443
|
+
for (;;) {
|
|
2444
|
+
openRe.lastIndex = pos;
|
|
2445
|
+
const openM = openRe.exec(template);
|
|
2446
|
+
if (!openM) break;
|
|
2447
|
+
const openAt = openM.index;
|
|
2448
|
+
const openLen = openM[0].length;
|
|
2449
|
+
const hold = openM[1] ? Number(openM[1]) : 0;
|
|
2450
|
+
let depth = 1;
|
|
2451
|
+
let i = openAt + openLen;
|
|
2452
|
+
let closeAt = -1;
|
|
2453
|
+
while (i < template.length) {
|
|
2454
|
+
openRe.lastIndex = i;
|
|
2455
|
+
const nextOpenM = openRe.exec(template);
|
|
2456
|
+
const nextOpen = nextOpenM ? nextOpenM.index : -1;
|
|
2457
|
+
const nextClose = template.indexOf('{/defer}', i);
|
|
2458
|
+
if (nextClose < 0) break;
|
|
2459
|
+
if (nextOpen >= 0 && nextOpen < nextClose) { depth++; i = nextOpen + nextOpenM![0].length; continue; }
|
|
2460
|
+
depth--;
|
|
2461
|
+
if (depth === 0) { closeAt = nextClose; break; }
|
|
2462
|
+
i = nextClose + 8;
|
|
2463
|
+
}
|
|
2464
|
+
if (closeAt < 0) break;
|
|
2465
|
+
const content = template.slice(openAt + openLen, closeAt);
|
|
2466
|
+
holds.push(hold);
|
|
2467
|
+
const n = ++count;
|
|
2468
|
+
out += template.slice(pos, openAt);
|
|
2469
|
+
out += '{#if __rvDefer' + n + '()}' + content + '{/if}' + '\n' +
|
|
2470
|
+
'{#if !__rvDefer' + n + '()}<div class="rv-defer-loading"></div>{/if}';
|
|
2471
|
+
pos = closeAt + 8;
|
|
2472
|
+
}
|
|
2473
|
+
if (count === 0) return { template, count: 0, holds: [] };
|
|
2474
|
+
out += template.slice(pos);
|
|
2475
|
+
return { template: out, count, holds };
|
|
2476
|
+
}
|
|
2477
|
+
|
|
2478
|
+
function deferBootCode(count: number, holds: number[] = []): string {
|
|
2479
|
+
let code = '';
|
|
2480
|
+
for (let n = 1; n <= count; n++) {
|
|
2481
|
+
code += 'const [__rvDefer' + n + ', set__rvDefer' + n + '] = state("__rvdefer' + n + '", false);\n';
|
|
2482
|
+
const hold = holds[n - 1] || 0;
|
|
2483
|
+
code += hold > 0
|
|
2484
|
+
? 'onMount(function () { setTimeout(function () { set__rvDefer' + n + '(true); }, ' + hold + '); });\n'
|
|
2485
|
+
: 'onMount(function () { requestAnimationFrame(function () { requestAnimationFrame(function () { set__rvDefer' + n + '(true); }); }); });\n';
|
|
2486
|
+
}
|
|
2487
|
+
return code;
|
|
2488
|
+
}
|
|
2489
|
+
|
|
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 {
|
|
1488
2593
|
const head = kind === 'boundary'
|
|
1489
|
-
? /\{#boundary
|
|
2594
|
+
? /\{#boundary(?:\s+([^}]*))?\}/g
|
|
1490
2595
|
: kind === 'if'
|
|
1491
2596
|
? /\{#if\s+([^}]+)\}/g
|
|
1492
|
-
:
|
|
2597
|
+
: kind === 'island'
|
|
2598
|
+
? /\{#island(?:\s+name="([^"]*)")?(?:\s+hydrate="([^"]*)")?\s*\}/g
|
|
2599
|
+
: kind === 'snippet'
|
|
2600
|
+
? /\{#snippet\s+(\w+)(?:\s*\(([^)]+)\))?\s*\}/g
|
|
2601
|
+
: /\{#each\s+([^}]+?)\s+as\s+(\{[^{}]*\}|\[[^[\]]*\]|\w+)(?:\s*,\s*(\w+))?(?:\s*\(([^)]+)\))?\}/g;
|
|
1493
2602
|
const closeRe = new RegExp(`\\{/${kind}\\}`, 'g');
|
|
1494
2603
|
let open: RegExpExecArray | null;
|
|
1495
2604
|
while ((open = head.exec(src))) {
|
|
@@ -1511,7 +2620,10 @@ function findBlock(src: string, kind: 'if' | 'each' | 'boundary'): RegExpExecArr
|
|
|
1511
2620
|
i = nextClose.index + nextClose[0].length;
|
|
1512
2621
|
if (--depth === 0) {
|
|
1513
2622
|
const content = src.slice(afterOpen, nextClose.index);
|
|
1514
|
-
const groups = kind === 'boundary' ? [
|
|
2623
|
+
const groups = kind === 'boundary' ? [open[1] ?? '', content]
|
|
2624
|
+
: kind === 'island' ? [open[1] ?? '', open[2] ?? '', content]
|
|
2625
|
+
: kind === 'snippet' ? [open[1], open[2] ?? '', content]
|
|
2626
|
+
: kind === 'if' ? [open[1], content] : [open[1], open[2], open[3] ?? '', open[4] ?? '', content];
|
|
1515
2627
|
const arr = [src.slice(start, i), ...groups] as unknown as RegExpExecArray;
|
|
1516
2628
|
(arr as any).index = start;
|
|
1517
2629
|
return arr;
|
|
@@ -1591,7 +2703,19 @@ function compileHead(head: string): string {
|
|
|
1591
2703
|
* Adversarial probing found all three in one afternoon; a template compiler
|
|
1592
2704
|
* that emits broken code silently is the worst failure mode it has.
|
|
1593
2705
|
*/
|
|
1594
|
-
const KNOWN_CLOSERS = new Set(['if', 'each', 'boundary']);
|
|
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
|
+
}
|
|
1595
2719
|
function assertKnownDirectives(template: string, filePath: string): void {
|
|
1596
2720
|
const rawRanges: Array<[number, number]> = [];
|
|
1597
2721
|
const RAW_OPEN = /<(style|script|noscript)\b[^>]*>/gi;
|
|
@@ -1623,31 +2747,69 @@ function assertKnownDirectives(template: string, filePath: string): void {
|
|
|
1623
2747
|
);
|
|
1624
2748
|
}
|
|
1625
2749
|
if (word === 'else') {
|
|
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;
|
|
2769
|
+
}
|
|
2770
|
+
if (word === 'fallback') {
|
|
1626
2771
|
throw new RoseError(
|
|
1627
2772
|
'E-TEMPLATE',
|
|
1628
|
-
`${filePath}: {:
|
|
1629
|
-
{ file: filePath, line: lineAt(template, m), hint: '
|
|
2773
|
+
`${filePath}: a stray {:fallback} with no {#boundary} above it`,
|
|
2774
|
+
{ file: filePath, line: lineAt(template, m), hint: '{:fallback} belongs directly inside a {#boundary} ... {/boundary} block' },
|
|
1630
2775
|
);
|
|
1631
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
|
+
}
|
|
1632
2795
|
throw new RoseError(
|
|
1633
2796
|
'E-TEMPLATE',
|
|
1634
2797
|
`${filePath}: {:${word}} is not a rosetack directive`,
|
|
1635
|
-
{ file: filePath, line: lineAt(template, m), hint:
|
|
2798
|
+
{ file: filePath, line: lineAt(template, m), hint: 'rosetack templates support {#if}/{:else}, {#each} and {#boundary}' },
|
|
1636
2799
|
);
|
|
1637
2800
|
}
|
|
1638
|
-
const OPENER_RE = /\{#(if|each|boundary)\b([^}]*)\}/g;
|
|
2801
|
+
const OPENER_RE = /\{#(if|each|boundary|island|await)\b([^}]*)\}/g;
|
|
1639
2802
|
while ((m = OPENER_RE.exec(template))) {
|
|
1640
2803
|
if (inRaw(m.index)) continue;
|
|
1641
2804
|
const [, kind, head] = m;
|
|
1642
|
-
if (kind === 'each' && !/\bas\s+(\w+)
|
|
2805
|
+
if (kind === 'each' && !/\bas\s+(\{[^{}]*\}?|\[[^[\]]*\]?|\w+)(?:\s*,\s*\w+)?(?:\s*\([^)]*\))?\s*$/.test(head)) {
|
|
1643
2806
|
throw new RoseError(
|
|
1644
2807
|
'E-TEMPLATE',
|
|
1645
2808
|
`${filePath}: {#each ${head.trim()}} is missing its item name`,
|
|
1646
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)' },
|
|
1647
2810
|
);
|
|
1648
2811
|
}
|
|
1649
|
-
const OPEN_RE =
|
|
1650
|
-
const CLOSE_RE = new RegExp(`\\{/${kind}\\}`, 'g');
|
|
2812
|
+
const { open: OPEN_RE, close: CLOSE_RE } = blockCloseRes(kind);
|
|
1651
2813
|
let depth = 1;
|
|
1652
2814
|
let i = m.index + m[0].length;
|
|
1653
2815
|
for (;;) {
|
|
@@ -1720,14 +2882,20 @@ function compileTemplate(
|
|
|
1720
2882
|
scope: string | null,
|
|
1721
2883
|
depth: number,
|
|
1722
2884
|
markers = true,
|
|
1723
|
-
comps: Map<string, { index: number; slots: Array<{ name: string; props: string[] }> }> = new Map()
|
|
2885
|
+
comps: Map<string, { index: number; slots: Array<{ name: string; props: string[] }> }> = new Map(),
|
|
2886
|
+
islandDepth = 0
|
|
1724
2887
|
): string {
|
|
1725
2888
|
let result = '';
|
|
1726
2889
|
let remaining = template;
|
|
1727
2890
|
let blockId = 0;
|
|
1728
2891
|
|
|
2892
|
+
const islandsMode = /\{#island\b/.test(template);
|
|
2893
|
+
const effMarkers = markers && (!islandsMode || islandDepth > 0);
|
|
2894
|
+
|
|
1729
2895
|
const nextId = () => `${depth}_${blockId++}`;
|
|
1730
2896
|
|
|
2897
|
+
if (depth === 0) result += 'const __snip = {};\n';
|
|
2898
|
+
|
|
1731
2899
|
while (remaining.length > 0) {
|
|
1732
2900
|
const ifMatch = findBlock(remaining, 'if');
|
|
1733
2901
|
const eachMatch = findBlock(remaining, 'each');
|
|
@@ -1737,11 +2905,15 @@ function compileTemplate(
|
|
|
1737
2905
|
? Object.assign([remaining.slice(firstExpr.start, firstExpr.end + 1), firstExpr.expr], { index: firstExpr.start }) as unknown as RegExpExecArray
|
|
1738
2906
|
: null;
|
|
1739
2907
|
const compTag = comps.size > 0 ? findCompTag(remaining, comps) : null;
|
|
2908
|
+
const islandMatch = findBlock(remaining, 'island');
|
|
2909
|
+
const snippetMatch = findBlock(remaining, 'snippet');
|
|
1740
2910
|
|
|
1741
2911
|
const candidates: Array<{ type: string; match: RegExpExecArray; index: number; tag?: CompTag }> = [];
|
|
1742
2912
|
if (ifMatch?.index !== undefined) candidates.push({ type: 'if', match: ifMatch, index: ifMatch.index });
|
|
1743
2913
|
if (eachMatch?.index !== undefined) candidates.push({ type: 'each', match: eachMatch, index: eachMatch.index });
|
|
1744
2914
|
if (boundaryMatch?.index !== undefined) candidates.push({ type: 'boundary', match: boundaryMatch, index: boundaryMatch.index });
|
|
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 });
|
|
1745
2917
|
if (exprMatch?.index !== undefined) candidates.push({ type: 'expr', match: exprMatch, index: exprMatch.index });
|
|
1746
2918
|
if (compTag) candidates.push({ type: 'comp', match: exprMatch!, index: compTag.start, tag: compTag });
|
|
1747
2919
|
const earliest = candidates.length > 0
|
|
@@ -1781,50 +2953,91 @@ function compileTemplate(
|
|
|
1781
2953
|
const call = autoCall(cond);
|
|
1782
2954
|
const id = nextId();
|
|
1783
2955
|
const innerScope = scope ?? '__s';
|
|
1784
|
-
const inner = compileTemplate(content.trim(), 'h', '__c', innerScope, depth + 1,
|
|
2956
|
+
const inner = compileTemplate(content.trim(), 'h', '__c', innerScope, depth + 1, effMarkers, comps, islandDepth);
|
|
1785
2957
|
result += `const __b${id} = (__s, __c) => { let h = ''; ${inner} return h; };\n`;
|
|
1786
|
-
if (
|
|
2958
|
+
if (effMarkers) {
|
|
1787
2959
|
result += `${acc} += ifMark(${closes}, () => (${call}), __b${id}${scope ? `, ${scope}` : ''});\n`;
|
|
1788
2960
|
} else {
|
|
1789
2961
|
result += `${acc} += (${call}) ? __b${id}(${scope ?? 'undefined'}, []) : '';\n`;
|
|
1790
2962
|
}
|
|
1791
2963
|
remaining = remaining.substring(earliest.index + earliest.match[0].length);
|
|
1792
2964
|
} else if (earliest.type === 'each') {
|
|
1793
|
-
const [, items, item, content] = earliest.match;
|
|
2965
|
+
const [, items, item, index, key, content] = earliest.match;
|
|
1794
2966
|
const before = remaining.substring(0, earliest.index);
|
|
1795
2967
|
if (before) result += emitChunk(before, acc, closes, scope);
|
|
1796
2968
|
const call = autoCall(items);
|
|
1797
2969
|
const id = nextId();
|
|
1798
|
-
const
|
|
2970
|
+
const isDestructure = /^[{[]/.test(item);
|
|
2971
|
+
const itemRe = isDestructure ? null : new RegExp(`\\b${item}\\b`, 'g');
|
|
2972
|
+
const indexRe = index ? new RegExp(`\\b${index}\\b`, 'g') : null;
|
|
1799
2973
|
let scoped = '';
|
|
1800
2974
|
let lastSpan = 0;
|
|
1801
2975
|
for (const s of templateExprSpans(content.trim())) {
|
|
1802
|
-
|
|
2976
|
+
let expr = itemRe ? s.expr.replace(itemRe, '__s') : s.expr;
|
|
2977
|
+
if (indexRe) expr = expr.replace(indexRe, '__i');
|
|
2978
|
+
scoped += content.trim().slice(lastSpan, s.start) + '{' + expr + '}';
|
|
1803
2979
|
lastSpan = s.end + 1;
|
|
1804
2980
|
}
|
|
1805
2981
|
scoped += content.trim().slice(lastSpan);
|
|
1806
|
-
const inner = compileTemplate(scoped, 'h', '__c', '__s', depth + 1,
|
|
1807
|
-
|
|
1808
|
-
|
|
1809
|
-
|
|
2982
|
+
const inner = compileTemplate(scoped, 'h', '__c', '__s', depth + 1, effMarkers, comps, islandDepth);
|
|
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
|
+
}
|
|
2998
|
+
result += `const __b${id} = (__s, __c${index ? ', __i' : ''}) => { let h = ''; ${body} return h; };\n`;
|
|
2999
|
+
if (effMarkers) {
|
|
3000
|
+
result += `${acc} += eachMark(${closes}, () => (${call}), __b${id}${keyFn});\n`;
|
|
1810
3001
|
} else {
|
|
1811
|
-
|
|
3002
|
+
const param = isDestructure ? '__s' : item;
|
|
3003
|
+
result += `${acc} += (${call}).map((${param}${index ? ', __i' : ''}) => __b${id}(${param}, []${index ? ', __i' : ''}))).join('');\n`;
|
|
1812
3004
|
}
|
|
1813
3005
|
remaining = remaining.substring(earliest.index + earliest.match[0].length);
|
|
1814
3006
|
} else if (earliest.type === 'boundary') {
|
|
1815
|
-
const [, content] = earliest.match;
|
|
3007
|
+
const [, fbAttr, content] = earliest.match;
|
|
3008
|
+
let fallbackSrc = '';
|
|
3009
|
+
if (fbAttr) {
|
|
3010
|
+
const fbM = /__fb="([A-Za-z0-9+/=]*)"/.exec(fbAttr);
|
|
3011
|
+
if (fbM) fallbackSrc = Buffer.from(fbM[1], 'base64').toString('utf-8');
|
|
3012
|
+
}
|
|
3013
|
+
const custom = content;
|
|
1816
3014
|
const before = remaining.substring(0, earliest.index);
|
|
1817
3015
|
if (before) result += emitChunk(before, acc, closes, scope);
|
|
1818
3016
|
const id = nextId();
|
|
1819
|
-
const catchesAction = /\$action:|<form[\s>]/.test(
|
|
1820
|
-
const inner = compileTemplate(
|
|
3017
|
+
const catchesAction = /\$action:|<form[\s>]/.test(custom);
|
|
3018
|
+
const inner = compileTemplate(custom.trim(), 'h', closes, scope, depth + 1, effMarkers, comps, islandDepth);
|
|
1821
3019
|
result += `const __b${id} = (__c) => { let h = ''; ${inner} return h; };\n`;
|
|
3020
|
+
let fbBlock = '';
|
|
3021
|
+
if (fallbackSrc.trim()) {
|
|
3022
|
+
const fbInner = compileTemplate(fallbackSrc.trim(), 'h', closes, scope, depth + 1, effMarkers, comps, islandDepth);
|
|
3023
|
+
fbBlock = `const __bf${id} = (__c) => { let h = ''; ${fbInner} return h; };\n`;
|
|
3024
|
+
}
|
|
3025
|
+
result += fbBlock;
|
|
1822
3026
|
result += `let __bd${id} = '';\n`;
|
|
1823
3027
|
result += catchesAction
|
|
1824
|
-
? `try { $actionErrorOrThrow(); __bd${id} = __b${id}(${closes}); } catch (e) { __bd${id} = $boundaryFallback(e); }\n`
|
|
1825
|
-
: `try { __bd${id} = __b${id}(${closes}); } catch { __bd${id} = ${JSON.stringify(BOUNDARY_FALLBACK)}; }\n`;
|
|
3028
|
+
? `try { $actionErrorOrThrow(); __bd${id} = __b${id}(${closes}); } catch (e) { $setBoundaryError(e); __bd${id} = ${fbBlock ? `__bf${id}(${closes})` : '$boundaryFallback(e)'}; }\n`
|
|
3029
|
+
: `try { __bd${id} = __b${id}(${closes}); } catch (e) { $setBoundaryError(e); __bd${id} = ${fbBlock ? `__bf${id}(${closes})` : JSON.stringify(BOUNDARY_FALLBACK)}; }\n`;
|
|
1826
3030
|
result += `${acc} += __bd${id};\n`;
|
|
1827
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);
|
|
1828
3041
|
} else if (earliest.type === 'comp') {
|
|
1829
3042
|
const tag = earliest.tag!;
|
|
1830
3043
|
if (tag.start > 0) result += emitChunk(remaining.substring(0, tag.start), acc, closes, scope);
|
|
@@ -1843,7 +3056,7 @@ function compileTemplate(
|
|
|
1843
3056
|
const { def, named } = splitSlots(childrenSrc);
|
|
1844
3057
|
const hasChildren = def.trim().length > 0;
|
|
1845
3058
|
if (hasChildren) {
|
|
1846
|
-
result += `const __ch${id} = (__s, __c) => { let h = ''; ${compileTemplate(def, 'h', '__c', scope, depth + 1,
|
|
3059
|
+
result += `const __ch${id} = (__s, __c) => { let h = ''; ${compileTemplate(def, 'h', '__c', scope, depth + 1, effMarkers, comps, islandDepth)} return h; };\n`;
|
|
1847
3060
|
}
|
|
1848
3061
|
const slotFns = named.map(([nm, src]) => {
|
|
1849
3062
|
const decl = entry.slots.find((s) => s.name === nm);
|
|
@@ -1858,11 +3071,12 @@ function compileTemplate(
|
|
|
1858
3071
|
}
|
|
1859
3072
|
content = out + content.slice(lastSpan);
|
|
1860
3073
|
}
|
|
1861
|
-
return `${JSON.stringify(nm)}: (__s, __c) => { let h = ''; ${compileTemplate(content, 'h', '__c',
|
|
3074
|
+
return `${JSON.stringify(nm)}: (__s, __c) => { let h = ''; ${compileTemplate(content, 'h', '__c', scope, depth + 1, effMarkers, comps, islandDepth)} return h; }`;
|
|
1862
3075
|
});
|
|
1863
3076
|
const propsObj = parseCompAttrs(tag.attrs)
|
|
1864
3077
|
.filter((a) => a.name !== 'slot')
|
|
1865
3078
|
.map((a) => {
|
|
3079
|
+
if (a.kind === 'spread') return `...(${a.value})`;
|
|
1866
3080
|
const key = a.name.startsWith('on:') ? `on${capitalize(a.name.slice(3))}` : a.name;
|
|
1867
3081
|
const val = a.kind === 'expr' ? `(${a.value})` : a.kind === 'str' ? JSON.stringify(a.value) : 'true';
|
|
1868
3082
|
return `${JSON.stringify(key)}: ${val}`;
|
|
@@ -1871,20 +3085,47 @@ function compileTemplate(
|
|
|
1871
3085
|
const childrenArg = hasChildren ? `__ch${id}(${scope ?? 'undefined'}, ${closes})` : `''`;
|
|
1872
3086
|
result += `${acc} += ${tag.name}(${closes}, ${childrenArg}, { ${propsObj} }, { ${slotFns.join(', ')} });\n`;
|
|
1873
3087
|
remaining = rest;
|
|
3088
|
+
} else if (earliest.type === 'island') {
|
|
3089
|
+
const [, name, hydrate, content] = earliest.match;
|
|
3090
|
+
const before = remaining.substring(0, earliest.index);
|
|
3091
|
+
if (before) result += emitChunk(before, acc, closes, scope);
|
|
3092
|
+
const hydrateAttr = hydrate === 'visible' || hydrate === 'idle'
|
|
3093
|
+
? ` data-rv-island-hydrate="${hydrate}"`
|
|
3094
|
+
: '';
|
|
3095
|
+
result += `${acc} += ${JSON.stringify(`<div data-rv-island="${name || ''}"${hydrateAttr}>`)};\n`;
|
|
3096
|
+
const inner = compileTemplate(content.trim(), 'h', '__c', scope, depth + 1, markers, comps, islandDepth + 1);
|
|
3097
|
+
result += inner;
|
|
3098
|
+
result += `${acc} += '</div>';\n`;
|
|
3099
|
+
remaining = remaining.substring(earliest.index + earliest.match[0].length);
|
|
1874
3100
|
} else {
|
|
1875
3101
|
const [, expr] = earliest.match;
|
|
1876
3102
|
const trimmed = expr.trim();
|
|
1877
3103
|
const before = remaining.substring(0, earliest.index);
|
|
3104
|
+
const constMatch = /^@const\s+([A-Za-z_$][\w$]*)\s*=\s*([\s\S]+)$/.exec(trimmed);
|
|
3105
|
+
if (constMatch) {
|
|
3106
|
+
if (before) result += emitChunk(before, acc, closes, scope);
|
|
3107
|
+
result += `const ${constMatch[1]} = (${constMatch[2].trim()});\n`;
|
|
3108
|
+
remaining = remaining.substring(earliest.index + earliest.match[0].length);
|
|
3109
|
+
continue;
|
|
3110
|
+
}
|
|
1878
3111
|
if (trimmed === '__slot__') {
|
|
1879
3112
|
if (before) result += emitChunk(before, acc, closes, scope);
|
|
1880
3113
|
result += compileSlot(acc);
|
|
1881
3114
|
remaining = remaining.substring(earliest.index + earliest.match[0].length);
|
|
1882
3115
|
continue;
|
|
1883
3116
|
}
|
|
1884
|
-
const
|
|
3117
|
+
const slotDefault = /^__slotDefault\(("(?:[^"\\]|\\.)*")\)$/.exec(trimmed);
|
|
3118
|
+
if (slotDefault) {
|
|
3119
|
+
if (before) result += emitChunk(before, acc, closes, scope);
|
|
3120
|
+
result += `${acc} += __slotDefault(children, ${slotDefault[1]});\n`;
|
|
3121
|
+
remaining = remaining.substring(earliest.index + earliest.match[0].length);
|
|
3122
|
+
continue;
|
|
3123
|
+
}
|
|
3124
|
+
const slotCall = /^__slot\((['"])(\w+)\1, \[([\s\S]*?)\](?:,\s*("(?:[^"\\]|\\.)*"))?\)$/.exec(trimmed);
|
|
1885
3125
|
if (slotCall) {
|
|
1886
3126
|
if (before) result += emitChunk(before, acc, closes, scope);
|
|
1887
|
-
|
|
3127
|
+
const fb = slotCall[4] ? `, ${slotCall[4]}` : '';
|
|
3128
|
+
result += `${acc} += __slotBlock(${closes}, __sl, ${JSON.stringify(slotCall[2])}, [${slotCall[3]}]${fb});\n`;
|
|
1888
3129
|
remaining = remaining.substring(earliest.index + earliest.match[0].length);
|
|
1889
3130
|
continue;
|
|
1890
3131
|
}
|
|
@@ -1892,7 +3133,7 @@ function compileTemplate(
|
|
|
1892
3133
|
if (rawMatch) {
|
|
1893
3134
|
if (before) result += emitChunk(before, acc, closes, scope);
|
|
1894
3135
|
const expr = rawMatch[1].trim();
|
|
1895
|
-
if (!
|
|
3136
|
+
if (!effMarkers) {
|
|
1896
3137
|
result += `${acc} += String(${expr} ?? '');\n`;
|
|
1897
3138
|
} else {
|
|
1898
3139
|
const fn = scope ? `(${scope}) => (${expr})` : `() => (${expr})`;
|
|
@@ -1901,16 +3142,42 @@ function compileTemplate(
|
|
|
1901
3142
|
remaining = remaining.substring(earliest.index + earliest.match[0].length);
|
|
1902
3143
|
continue;
|
|
1903
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
|
+
}
|
|
1904
3171
|
const attrMatch = before.match(/([\w-]+)=\s*$/);
|
|
1905
3172
|
if (attrMatch) {
|
|
1906
3173
|
const lit = before.slice(0, before.length - attrMatch[0].length);
|
|
1907
3174
|
if (lit) result += emitChunk(lit, acc, closes, scope);
|
|
1908
|
-
result += emitAttr(attrMatch[1], trimmed, acc, closes, scope,
|
|
3175
|
+
result += emitAttr(attrMatch[1], trimmed, acc, closes, scope, effMarkers);
|
|
1909
3176
|
} else {
|
|
1910
3177
|
if (before) result += emitChunk(before, acc, closes, scope);
|
|
1911
3178
|
const after = remaining.substring(earliest.index + earliest.match[0].length);
|
|
1912
3179
|
const pair = after.length > 0 && !/^<[a-zA-Z/!]/.test(after) && !after.startsWith('{');
|
|
1913
|
-
result += emitText(trimmed, acc, closes, scope,
|
|
3180
|
+
result += emitText(trimmed, acc, closes, scope, effMarkers, pair);
|
|
1914
3181
|
}
|
|
1915
3182
|
remaining = remaining.substring(earliest.index + earliest.match[0].length);
|
|
1916
3183
|
}
|
|
@@ -1931,7 +3198,11 @@ interface CompTag {
|
|
|
1931
3198
|
selfClosing: boolean;
|
|
1932
3199
|
}
|
|
1933
3200
|
|
|
1934
|
-
|
|
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
|
+
*/
|
|
1935
3206
|
function scanTagEnd(src: string, start: number): number {
|
|
1936
3207
|
let j = start + 1;
|
|
1937
3208
|
let quote = '';
|
|
@@ -1986,13 +3257,19 @@ function findClose(src: string, from: number, name: string): number {
|
|
|
1986
3257
|
return -1;
|
|
1987
3258
|
}
|
|
1988
3259
|
|
|
1989
|
-
interface CompAttr { name: string; kind: 'expr' | 'str' | 'bool'; value: string }
|
|
3260
|
+
interface CompAttr { name: string; kind: 'expr' | 'str' | 'bool' | 'spread'; value: string }
|
|
1990
3261
|
|
|
1991
3262
|
/** Parse a component tag's attributes into prop={expr} / prop="lit" / bool. */
|
|
1992
3263
|
function parseCompAttrs(attrs: string): CompAttr[] {
|
|
1993
3264
|
const out: CompAttr[] = [];
|
|
1994
3265
|
let i = 0;
|
|
1995
3266
|
while (i < attrs.length) {
|
|
3267
|
+
const spread = /^\s*\{\.\.\.([^}]*)\}/.exec(attrs.slice(i));
|
|
3268
|
+
if (spread) {
|
|
3269
|
+
out.push({ name: '...', kind: 'spread', value: spread[1].trim() });
|
|
3270
|
+
i += spread[0].length;
|
|
3271
|
+
continue;
|
|
3272
|
+
}
|
|
1996
3273
|
const nm = /^\s*([\w:.-]+)/.exec(attrs.slice(i));
|
|
1997
3274
|
if (!nm) break;
|
|
1998
3275
|
i += nm[0].length;
|
|
@@ -2059,6 +3336,7 @@ function splitSlots(src: string): { def: string; named: Array<[string, string]>
|
|
|
2059
3336
|
let i = 0;
|
|
2060
3337
|
let elemDepth = 0;
|
|
2061
3338
|
let blockDepth = 0;
|
|
3339
|
+
const blockStack: Array<{ header: string; type: string }> = [];
|
|
2062
3340
|
while (i < src.length) {
|
|
2063
3341
|
const lt = src.indexOf('<', i);
|
|
2064
3342
|
const ob = src.indexOf('{#', i);
|
|
@@ -2073,8 +3351,14 @@ function splitSlots(src: string): { def: string; named: Array<[string, string]>
|
|
|
2073
3351
|
if (next === ob || next === cb) {
|
|
2074
3352
|
const close = src.indexOf('}', next);
|
|
2075
3353
|
const token = src.slice(next, close < 0 ? src.length : close + 1);
|
|
2076
|
-
if (next === ob)
|
|
2077
|
-
|
|
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
|
+
}
|
|
2078
3362
|
def += token;
|
|
2079
3363
|
i = next + token.length;
|
|
2080
3364
|
continue;
|
|
@@ -2101,20 +3385,16 @@ function splitSlots(src: string): { def: string; named: Array<[string, string]>
|
|
|
2101
3385
|
}
|
|
2102
3386
|
if (!selfClosing && !isVoid) elemDepth++;
|
|
2103
3387
|
const slotName = /\bslot\s*=\s*["'](\w+)["']/.exec(tagText)?.[1];
|
|
2104
|
-
if (slotName &&
|
|
2105
|
-
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' });
|
|
2106
|
-
}
|
|
2107
|
-
if (slotName) {
|
|
2108
|
-
const stripped = tagText.replace(/\s*slot\s*=\s*["']\w+["']/, '');
|
|
3388
|
+
if (slotName && elemDepth === 1 && blockDepth === 0) {
|
|
2109
3389
|
if (selfClosing || isVoid) {
|
|
2110
|
-
named.set(slotName, (named.get(slotName) ?? '') +
|
|
3390
|
+
named.set(slotName, (named.get(slotName) ?? '') + tagText.replace(/\s*slot\s*=\s*["']\w+["']/, ''));
|
|
2111
3391
|
} else {
|
|
2112
3392
|
const closeIdx = findClose(src, end, nm[2]);
|
|
2113
|
-
if (closeIdx < 0) throw new RoseError('E-TEMPLATE', `unclosed <${nm[2]}> inside slot="${slotName}"`, { hint: `add the matching </${nm[2]}
|
|
3393
|
+
if (closeIdx < 0) throw new RoseError('E-TEMPLATE', `unclosed <${nm[2]}> inside slot="${slotName}"`, { hint: `add the matching </${nm[2]}>` });
|
|
2114
3394
|
const tail = `</${nm[2]}>`;
|
|
2115
3395
|
const inner = src.slice(end, closeIdx);
|
|
2116
3396
|
rejectNestedSlot(inner, slotName);
|
|
2117
|
-
named.set(slotName, (named.get(slotName) ?? '') +
|
|
3397
|
+
named.set(slotName, (named.get(slotName) ?? '') + tagText.replace(/\s*slot\s*=\s*["']\w+["']/, '') + inner + tail);
|
|
2118
3398
|
elemDepth = Math.max(0, elemDepth - 1);
|
|
2119
3399
|
i = closeIdx + tail.length;
|
|
2120
3400
|
continue;
|
|
@@ -2122,6 +3402,32 @@ function splitSlots(src: string): { def: string; named: Array<[string, string]>
|
|
|
2122
3402
|
i = end;
|
|
2123
3403
|
continue;
|
|
2124
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
|
+
}
|
|
2125
3431
|
def += tagText;
|
|
2126
3432
|
i = end;
|
|
2127
3433
|
}
|
|
@@ -2144,7 +3450,56 @@ const IMG_MIME: Record<string, string> = {
|
|
|
2144
3450
|
'.svg': 'image/svg+xml',
|
|
2145
3451
|
'.ico': 'image/x-icon',
|
|
2146
3452
|
};
|
|
2147
|
-
const INLINE_IMG_MAX =
|
|
3453
|
+
const INLINE_IMG_MAX = 8192;
|
|
3454
|
+
const INLINE_SVG_MAX = 16384;
|
|
3455
|
+
|
|
3456
|
+
import { readImageSize } from "../cli/image-size";
|
|
3457
|
+
import { scanContentDir, renderMarkdown, buildRss } from "../cli/content";
|
|
3458
|
+
|
|
3459
|
+
/**
|
|
3460
|
+
* A4 (responsive variants): the sibling `name.wNNN.ext` files of a local
|
|
3461
|
+
* image (e.g. `hero.jpg` with `hero.w400.jpg` / `hero.w800.jpg` next to it
|
|
3462
|
+
* in public/) become a sorted srcset on the URL-kept <img>. Zero-dependency
|
|
3463
|
+
* by design - the variants themselves are plain files, generated by whatever
|
|
3464
|
+
* resizer the app prefers (oboext ships tools/make-variants.mjs). Author-set
|
|
3465
|
+
* srcset/sizes always win; no variants means no attribute, byte-identical.
|
|
3466
|
+
*/
|
|
3467
|
+
function listImageVariants(publicDir: string, url: string): Array<{ url: string; width: number }> {
|
|
3468
|
+
const ext = path.extname(url);
|
|
3469
|
+
const base = path.basename(url, ext);
|
|
3470
|
+
const dirUrl = url.slice(0, url.length - (base + ext).length);
|
|
3471
|
+
let entries: string[];
|
|
3472
|
+
try {
|
|
3473
|
+
entries = fs.readdirSync(path.join(publicDir, path.dirname(url)));
|
|
3474
|
+
} catch {
|
|
3475
|
+
return [];
|
|
3476
|
+
}
|
|
3477
|
+
const re = new RegExp(
|
|
3478
|
+
'^' + base.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '\\.w(\\d+)' + ext.replace('.', '\\.') + '$',
|
|
3479
|
+
'i',
|
|
3480
|
+
);
|
|
3481
|
+
const out: Array<{ url: string; width: number }> = [];
|
|
3482
|
+
for (const e of entries) {
|
|
3483
|
+
const m = re.exec(e);
|
|
3484
|
+
const width = m ? Number(m[1]) : 0;
|
|
3485
|
+
if (width > 0) out.push({ url: `${dirUrl}${base}.w${width}${ext}`, width });
|
|
3486
|
+
}
|
|
3487
|
+
return out.sort((a, b) => a.width - b.width);
|
|
3488
|
+
}
|
|
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
|
+
}
|
|
2148
3503
|
|
|
2149
3504
|
function inlineImages(template: string, publicDir: string): string {
|
|
2150
3505
|
return template.replace(IMG_RE, (tag) => {
|
|
@@ -2153,17 +3508,27 @@ function inlineImages(template: string, publicDir: string): string {
|
|
|
2153
3508
|
const ext = path.extname(src[1]).toLowerCase();
|
|
2154
3509
|
const mime = IMG_MIME[ext];
|
|
2155
3510
|
if (!mime) return tag;
|
|
2156
|
-
|
|
2157
|
-
|
|
2158
|
-
|
|
2159
|
-
|
|
2160
|
-
|
|
3511
|
+
const rel = src[1].replace(/^\/public(?=\/)/, '');
|
|
3512
|
+
const filePath = path.join(publicDir, rel);
|
|
3513
|
+
const read = cachedImageRead(filePath);
|
|
3514
|
+
if (!read) return tag;
|
|
3515
|
+
const file = read.buffer;
|
|
3516
|
+
const authorDims = /\swidth=/.test(tag) || /\sheight=/.test(tag);
|
|
3517
|
+
const dims = authorDims ? null : read.dims;
|
|
3518
|
+
const withDims = (t: string): string =>
|
|
3519
|
+
dims ? t.replace(/<img\b/, `<img width="${dims.width}" height="${dims.height}"`) : t;
|
|
3520
|
+
const inlineMax = ext === '.svg' ? INLINE_SVG_MAX : INLINE_IMG_MAX;
|
|
3521
|
+
if (file.length > inlineMax) {
|
|
3522
|
+
const hasSS = /\ssrcset=/.test(tag) || /\ssizes=/.test(tag);
|
|
3523
|
+
const variants = hasSS ? [] : listImageVariants(publicDir, rel);
|
|
3524
|
+
if (!variants.length) return withDims(tag);
|
|
3525
|
+
const srcset = variants.map((v) => `${v.url} ${v.width}w`).join(', ');
|
|
3526
|
+
return withDims(tag.replace(/<img\b/, `<img srcset="${srcset}"`));
|
|
2161
3527
|
}
|
|
2162
|
-
if (file.length > INLINE_IMG_MAX) return tag;
|
|
2163
3528
|
const uri = ext === '.svg'
|
|
2164
3529
|
? `data:image/svg+xml,${file.toString('utf-8').replace(/%/g, '%25').replace(/#/g, '%23').replace(/\{/g, '%7B').replace(/\}/g, '%7D').replace(/"/g, '%22')}`
|
|
2165
3530
|
: `data:${mime};base64,${file.toString('base64')}`;
|
|
2166
|
-
return tag.replace(src[0], `src="${uri}"`);
|
|
3531
|
+
return withDims(tag.replace(src[0], `src="${uri}"`));
|
|
2167
3532
|
});
|
|
2168
3533
|
}
|
|
2169
3534
|
|
|
@@ -2184,12 +3549,17 @@ function emitText(expr: string, acc: string, closes: string, scope: string | nul
|
|
|
2184
3549
|
}
|
|
2185
3550
|
|
|
2186
3551
|
/** Emit a reactive attribute through the runtime's attrMark(). */
|
|
3552
|
+
const BOOLEAN_ATTRS = new Set(['checked', 'disabled', 'readonly', 'required', 'selected', 'multiple', 'autofocus', 'open']);
|
|
3553
|
+
|
|
2187
3554
|
function emitAttr(attr: string, expr: string, acc: string, closes: string, scope: string | null, markers = true): string {
|
|
2188
3555
|
if (!markers) {
|
|
2189
3556
|
return `${acc} += '${attr}="' + esc(${expr}) + '"';\n`;
|
|
2190
3557
|
}
|
|
2191
3558
|
const fn = scope ? `(${scope}) => (${expr})` : `() => (${expr})`;
|
|
2192
3559
|
const arg = scope ? `, ${scope}` : '';
|
|
3560
|
+
if (BOOLEAN_ATTRS.has(attr)) {
|
|
3561
|
+
return `${acc} += boolAttrMark(${closes}, ${fn}, '${attr}'${arg});\n`;
|
|
3562
|
+
}
|
|
2193
3563
|
return `${acc} += attrMark(${closes}, ${fn}, '${attr}'${arg});\n`;
|
|
2194
3564
|
}
|
|
2195
3565
|
|
|
@@ -2201,7 +3571,7 @@ function compileSlot(acc: string): string {
|
|
|
2201
3571
|
return `${acc} += String(children);\n`;
|
|
2202
3572
|
}
|
|
2203
3573
|
|
|
2204
|
-
const RUNTIME_IMPORTS = `import { state, setState, $data, hasState, esc, refresh, onMount, onCleanup, getContext, $query, $t, bestLocale, localeDir, ensureLocale, loadLocale, handlers, $cookies, $sessionCookie, $store, ActionError, $actionError, $actionErrorOrThrow, $boundaryFallback, $append, $prepend, $merge, applyStateDeltas, textMark, attrMark, 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';`;
|
|
2205
3575
|
|
|
2206
3576
|
const API_RUNTIME_HELPERS = RUNTIME_IMPORTS
|
|
2207
3577
|
.replace(/^import\s*\{/, '')
|
|
@@ -2230,7 +3600,16 @@ const SLOT_HELPER = `const __slot = (sl, name, pairs) => {
|
|
|
2230
3600
|
for (let i = 0; i < pairs.length; i++) o[pairs[i][0]] = pairs[i][1];
|
|
2231
3601
|
return { o, fn };
|
|
2232
3602
|
};
|
|
2233
|
-
const __slotBlock = (closes, sl, name, pairs) =>
|
|
3603
|
+
const __slotBlock = (closes, sl, name, pairs, fallback) => {
|
|
3604
|
+
const hit = __slot(sl, name, pairs);
|
|
3605
|
+
if (hit) return slotBlockMark(closes, hit);
|
|
3606
|
+
return fallback || '';
|
|
3607
|
+
};
|
|
3608
|
+
const __slotDefault = (children, fallback) => {
|
|
3609
|
+
const c = children == null ? '' : String(children);
|
|
3610
|
+
if (c.trim()) return c;
|
|
3611
|
+
return fallback || '';
|
|
3612
|
+
};`;
|
|
2234
3613
|
|
|
2235
3614
|
function generateSSR(script: string, templateFn: string, stateDeclsCode: string, exports = '', headFn = '', props: Array<{ name: string; def: string | null }> = [], namedSlots = false, imports = '', isComponent = false, guard = '', hasActions = false, dataDeclsCode = ''): string {
|
|
2236
3615
|
const headCode = headFn
|
|
@@ -2454,7 +3833,7 @@ export async function buildProject(root: string, outDir: string): Promise<{ rout
|
|
|
2454
3833
|
files.map((f, i) => [f, { index: i, scopeKey: scopeKeys[i], slots: scanSlotDecls(f) }])
|
|
2455
3834
|
);
|
|
2456
3835
|
const compiled = await Promise.all(
|
|
2457
|
-
files.map((f, i) =>
|
|
3836
|
+
files.map((f, i) => compileComponentMemo(f, path.join(root, 'public'), scopeKeys[i], infos[i].isApi, plugins, registry))
|
|
2458
3837
|
);
|
|
2459
3838
|
|
|
2460
3839
|
const importsOf = new Map<number, number[]>();
|
|
@@ -2535,6 +3914,9 @@ export async function buildProject(root: string, outDir: string): Promise<{ rout
|
|
|
2535
3914
|
const buildDir = path.join(outDir, '.build');
|
|
2536
3915
|
await fs.promises.rm(buildDir, { recursive: true, force: true });
|
|
2537
3916
|
await fs.promises.mkdir(buildDir, { recursive: true });
|
|
3917
|
+
const contentSrcCands = [path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'cli', 'content.ts'), path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'src', 'cli', 'content.ts')];
|
|
3918
|
+
const contentSrc = contentSrcCands.find((c) => fs.existsSync(c)) ?? contentSrcCands[0];
|
|
3919
|
+
fs.copyFileSync(contentSrc, path.join(buildDir, 'content-md.ts'));
|
|
2538
3920
|
|
|
2539
3921
|
const runtimePlugins = plugins.filter((p) => p && (p.onRequest || p.onResponse));
|
|
2540
3922
|
if (runtimePlugins.length > 0) {
|
|
@@ -2664,13 +4046,13 @@ export const hasResponseHooks = hooks.some((p) => p.onResponse);
|
|
|
2664
4046
|
const dir = path.posix.dirname(rel);
|
|
2665
4047
|
const prefix = dir === '.' ? '/' : '/' + dir;
|
|
2666
4048
|
const flags = routeShellOff(infos, compiled, i) ? ', { shell: false }' : '';
|
|
2667
|
-
return { prefix, render:
|
|
4049
|
+
return { prefix, render: compose(i), flags };
|
|
2668
4050
|
})
|
|
2669
4051
|
.sort((a, b) => b.prefix.length - a.prefix.length);
|
|
2670
4052
|
const notFoundTable = `[\n${notFoundEntries.map((e) => ` ['${e.prefix}', ${e.render}${e.flags}],`).join('\n')}\n]`;
|
|
2671
4053
|
|
|
2672
4054
|
const errIdx = infos.findIndex((info) => info.isError);
|
|
2673
|
-
const errorRender = errIdx >= 0 ?
|
|
4055
|
+
const errorRender = errIdx >= 0 ? compose(errIdx) : 'null';
|
|
2674
4056
|
|
|
2675
4057
|
const middlewareIdx = infos.findIndex((info) => info.isMiddleware);
|
|
2676
4058
|
|
|
@@ -2705,9 +4087,13 @@ export const hasResponseHooks = hooks.some((p) => p.onResponse);
|
|
|
2705
4087
|
})
|
|
2706
4088
|
.join(',\n ');
|
|
2707
4089
|
|
|
4090
|
+
const appUsesAuth = compiled.some((c) => c.usesrosetackAuth);
|
|
4091
|
+
|
|
2708
4092
|
const serverEntry = `
|
|
2709
4093
|
${serverImports}
|
|
2710
|
-
import {
|
|
4094
|
+
import { renderMarkdown } from './content-md.ts';
|
|
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';
|
|
2711
4097
|
${runtimePlugins.length > 0
|
|
2712
4098
|
? `import { hooks as __pluginHooks, hasRequestHooks as __hasRequestHooks, hasResponseHooks as __hasResponseHooks } from './plugins.js';`
|
|
2713
4099
|
: `// no plugin declares a runtime hook, so there is no plugins
|
|
@@ -2766,6 +4152,7 @@ if (typeof process !== 'undefined' && typeof process.send === 'function') {
|
|
|
2766
4152
|
});
|
|
2767
4153
|
}
|
|
2768
4154
|
|
|
4155
|
+
|
|
2769
4156
|
// (the cross-machine seam): the cluster relay above covers ONE machine.
|
|
2770
4157
|
export function __installStoreTransport(send: (name: string, value: unknown) => void): void {
|
|
2771
4158
|
setStoreTransport(send);
|
|
@@ -2786,6 +4173,11 @@ export const routeParams = {
|
|
|
2786
4173
|
|
|
2787
4174
|
// Routes whose component reads the request context (getContext()), mutates a shared store ($store()), reads the query ($query(), P0-1)
|
|
2788
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 = [
|
|
2789
4181
|
${pages.filter(({ i }) => compiled[i].usesContext || compiled[i].cspNonce || compiled[i].buffer || compiled[i].controlSignal).map(({ info }) => `'${info.routePath}'`).join(',\n ')}
|
|
2790
4182
|
];
|
|
2791
4183
|
|
|
@@ -2801,6 +4193,239 @@ export const revalidate = [
|
|
|
2801
4193
|
${pages.filter(({ i }) => compiled[i].revalidate !== undefined && !compiled[i].usesContext).map(({ info, i }) => `{ pattern: '${info.pattern}', seconds: ${compiled[i].revalidate} }`).join(',\n ')}
|
|
2802
4194
|
];
|
|
2803
4195
|
|
|
4196
|
+
// Per-request render memo (export const cache = N): a dynamic route's whole renderPage result is memoized for N seconds.
|
|
4197
|
+
export const routeCaches = [
|
|
4198
|
+
${pages.filter(({ i }) => compiled[i].cache !== undefined).map(({ info, i }) => `{ pattern: '${info.pattern}', seconds: ${compiled[i].cache} }`).join(',\n ')}
|
|
4199
|
+
];
|
|
4200
|
+
const __dynCache = new Map();
|
|
4201
|
+
export function invalidateRenderCache(): void {
|
|
4202
|
+
__dynCache.clear();
|
|
4203
|
+
}
|
|
4204
|
+
|
|
4205
|
+
|
|
4206
|
+
// Application KV cache primitive (server-side, per-worker in-memory): a zero-dependency store for expensive computations.
|
|
4207
|
+
const __kvStore = new Map<string, { v: unknown; exp: number }>();
|
|
4208
|
+
// Content collections: src/content/<coll>/*.md scanned once at build time,
|
|
4209
|
+
|
|
4210
|
+
const contentCollections = ${JSON.stringify(scanContentDir(path.join(root, 'src', 'content')))};
|
|
4211
|
+
export const kv = {
|
|
4212
|
+
get(key: string): unknown {
|
|
4213
|
+
const e = __kvStore.get(key);
|
|
4214
|
+
if (!e) return undefined;
|
|
4215
|
+
if (e.exp < Date.now()) { __kvStore.delete(key); return undefined; }
|
|
4216
|
+
return e.v;
|
|
4217
|
+
},
|
|
4218
|
+
set(key: string, value: unknown, ttlSeconds = 300): void {
|
|
4219
|
+
if (__kvStore.size > 1000) {
|
|
4220
|
+
const cutoff = Date.now();
|
|
4221
|
+
for (const [k, e] of __kvStore) { if (e.exp < cutoff) __kvStore.delete(k); }
|
|
4222
|
+
if (__kvStore.size > 2000) __kvStore.clear();
|
|
4223
|
+
}
|
|
4224
|
+
__kvStore.set(key, { v: value, exp: Date.now() + ttlSeconds * 1000 });
|
|
4225
|
+
},
|
|
4226
|
+
del(key: string): void { __kvStore.delete(key); },
|
|
4227
|
+
has(key: string): boolean {
|
|
4228
|
+
const e = __kvStore.get(key);
|
|
4229
|
+
return !!e && e.exp >= Date.now();
|
|
4230
|
+
},
|
|
4231
|
+
};
|
|
4232
|
+
globalThis.__rosetackKvApi = { kv, kvMemo: $kv };
|
|
4233
|
+
globalThis.__rosetackContent = {
|
|
4234
|
+
list: (coll: string, filter?: { tag: string }) => {
|
|
4235
|
+
let items = contentCollections[coll] ?? [];
|
|
4236
|
+
if (filter?.tag) items = items.filter((e) => ((e.frontmatter.tags as string[] | undefined) ?? []).includes(filter.tag));
|
|
4237
|
+
return items.map((e) => ({ slug: e.slug, ...e.frontmatter }));
|
|
4238
|
+
},
|
|
4239
|
+
rss: (coll: string, opts: { title: string; origin: string; description?: string }) => {
|
|
4240
|
+
return buildRss(contentCollections[coll] ?? [], opts);
|
|
4241
|
+
},
|
|
4242
|
+
get: (coll: string, slug: string, vars?: Record<string, unknown>) => {
|
|
4243
|
+
const e = (contentCollections[coll] ?? []).find((x) => x.slug === slug);
|
|
4244
|
+
if (!e) return null;
|
|
4245
|
+
return { slug: e.slug, ...e.frontmatter, html: renderMarkdown(e.body, vars), toc: e.toc, readingTime: e.readingTime, wordCount: e.wordCount, excerpt: e.excerpt };
|
|
4246
|
+
},
|
|
4247
|
+
};
|
|
4248
|
+
|
|
4249
|
+
const v = {
|
|
4250
|
+
validate(body: Record<string, unknown>, rules: Record<string, string[]>): { ok: boolean; errors: Record<string, string>; values: Record<string, unknown> } {
|
|
4251
|
+
const errors: Record<string, string> = {};
|
|
4252
|
+
const values: Record<string, unknown> = {};
|
|
4253
|
+
for (const [field, ruleList] of Object.entries(rules)) {
|
|
4254
|
+
let val = body[field];
|
|
4255
|
+
for (const rule of ruleList) {
|
|
4256
|
+
if (val === undefined || val === null || val === "") {
|
|
4257
|
+
if (rule === "required") errors[field] = field + " is required";
|
|
4258
|
+
else if (rule.startsWith("default:")) val = rule.slice(8);
|
|
4259
|
+
continue;
|
|
4260
|
+
}
|
|
4261
|
+
if (rule === "string") val = String(val);
|
|
4262
|
+
else if (rule === "trim") val = String(val).trim();
|
|
4263
|
+
else if (rule === "number") {
|
|
4264
|
+
const num = Number(val);
|
|
4265
|
+
if (Number.isNaN(num)) errors[field] = field + " must be a number";
|
|
4266
|
+
else val = num;
|
|
4267
|
+
} else if (rule === "email") {
|
|
4268
|
+
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(String(val))) errors[field] = field + " must be a valid email";
|
|
4269
|
+
} else if (rule.startsWith("min:")) {
|
|
4270
|
+
const min = Number(rule.slice(4));
|
|
4271
|
+
if (typeof val === "number" ? val < min : String(val).length < min) errors[field] = field + " must be at least " + min;
|
|
4272
|
+
} else if (rule.startsWith("max:")) {
|
|
4273
|
+
const max = Number(rule.slice(4));
|
|
4274
|
+
if (typeof val === "number" ? val > max : String(val).length > max) errors[field] = field + " must be at most " + max;
|
|
4275
|
+
}
|
|
4276
|
+
}
|
|
4277
|
+
values[field] = val;
|
|
4278
|
+
}
|
|
4279
|
+
return { ok: Object.keys(errors).length === 0, errors, values };
|
|
4280
|
+
},
|
|
4281
|
+
};
|
|
4282
|
+
|
|
4283
|
+
const jobs = {
|
|
4284
|
+
_timers: new Map<string, ReturnType<typeof setInterval>>(),
|
|
4285
|
+
every(name: string, seconds: number, fn: () => void | Promise<void>): void {
|
|
4286
|
+
if (this._timers.has(name)) return;
|
|
4287
|
+
const t = setInterval(() => { Promise.resolve(fn()).catch(() => {}); }, seconds * 1000);
|
|
4288
|
+
this._timers.set(name, t as any);
|
|
4289
|
+
},
|
|
4290
|
+
cancel(name: string): void {
|
|
4291
|
+
const t = this._timers.get(name);
|
|
4292
|
+
if (t) { clearInterval(t); this._timers.delete(name); }
|
|
4293
|
+
},
|
|
4294
|
+
cancelAll(): void { for (const t of this._timers.values()) clearInterval(t); this._timers.clear(); }
|
|
4295
|
+
};
|
|
4296
|
+
|
|
4297
|
+
function sse(handler: (send: (event: string, data: unknown) => void) => Promise<void> | void): Response {
|
|
4298
|
+
const encoder = new TextEncoder();
|
|
4299
|
+
const stream = new ReadableStream({
|
|
4300
|
+
async start(controller) {
|
|
4301
|
+
let closed = false;
|
|
4302
|
+
const send = (event: string, data: unknown) => {
|
|
4303
|
+
if (closed) return;
|
|
4304
|
+
controller.enqueue(encoder.encode("event: " + event + "\\ndata: " + JSON.stringify(data) + "\\n\\n"));
|
|
4305
|
+
};
|
|
4306
|
+
try {
|
|
4307
|
+
await handler(send);
|
|
4308
|
+
} finally {
|
|
4309
|
+
closed = true;
|
|
4310
|
+
try { controller.close(); } catch { }
|
|
4311
|
+
}
|
|
4312
|
+
},
|
|
4313
|
+
});
|
|
4314
|
+
return new Response(stream, {
|
|
4315
|
+
headers: { "content-type": "text/event-stream; charset=utf-8", "cache-control": "no-cache", "connection": "keep-alive" },
|
|
4316
|
+
});
|
|
4317
|
+
}
|
|
4318
|
+
globalThis.__rosetackExtras = { v, jobs, sse };
|
|
4319
|
+
${appUsesAuth ? `
|
|
4320
|
+
const auth = {
|
|
4321
|
+
hashPassword(password: string): string {
|
|
4322
|
+
const salt = crypto.randomBytes(16).toString("hex");
|
|
4323
|
+
const hash = crypto.scryptSync(password, salt, 32).toString("hex");
|
|
4324
|
+
return salt + ":" + hash;
|
|
4325
|
+
},
|
|
4326
|
+
verifyPassword(password: string, stored: string): boolean {
|
|
4327
|
+
const [salt, hash] = stored.split(":");
|
|
4328
|
+
if (!salt || !hash) return false;
|
|
4329
|
+
return crypto.timingSafeEqual(Buffer.from(hash, "hex"), crypto.scryptSync(password, salt, 32));
|
|
4330
|
+
},
|
|
4331
|
+
signSession(data: Record<string, unknown>, secret: string, ttlSeconds = 86400): string {
|
|
4332
|
+
const payload = Buffer.from(JSON.stringify({ ...data, exp: Date.now() + ttlSeconds * 1000 })).toString("base64url");
|
|
4333
|
+
const sig = crypto.createHmac("sha256", secret).update(payload).digest("base64url");
|
|
4334
|
+
return payload + "." + sig;
|
|
4335
|
+
},
|
|
4336
|
+
verifySession<T = Record<string, unknown>>(token: string, secret: string): T | null {
|
|
4337
|
+
const dot = token.lastIndexOf(".");
|
|
4338
|
+
if (dot < 0) return null;
|
|
4339
|
+
const payload = token.slice(0, dot);
|
|
4340
|
+
const sig = token.slice(dot + 1);
|
|
4341
|
+
const expect = crypto.createHmac("sha256", secret).update(payload).digest("base64url");
|
|
4342
|
+
try {
|
|
4343
|
+
if (!crypto.timingSafeEqual(Buffer.from(sig), Buffer.from(expect))) return null;
|
|
4344
|
+
} catch { return null; }
|
|
4345
|
+
try {
|
|
4346
|
+
const data = JSON.parse(Buffer.from(payload, "base64url").toString());
|
|
4347
|
+
if (data.exp < Date.now()) return null;
|
|
4348
|
+
return data as T;
|
|
4349
|
+
} catch { return null; }
|
|
4350
|
+
},
|
|
4351
|
+
csrfToken(secret: string, sessionId: string): string {
|
|
4352
|
+
return crypto.createHmac("sha256", secret).update(sessionId).digest("hex");
|
|
4353
|
+
},
|
|
4354
|
+
verifyCsrf(token: string, secret: string, sessionId: string): boolean {
|
|
4355
|
+
try {
|
|
4356
|
+
return crypto.timingSafeEqual(Buffer.from(token), Buffer.from(this.csrfToken(secret, sessionId)));
|
|
4357
|
+
} catch { return false; }
|
|
4358
|
+
},
|
|
4359
|
+
};
|
|
4360
|
+
globalThis.__rosetackAuth = auth;
|
|
4361
|
+
` : "// __rosetackAuth helpers omitted: no route references them (keeps the bundle free of node:crypto and edge-loadable)"}
|
|
4362
|
+
|
|
4363
|
+
export async function $kv(key: string, compute: () => unknown | Promise<unknown>, ttlSeconds = 300): Promise<unknown> {
|
|
4364
|
+
const hit = kv.get(key);
|
|
4365
|
+
if (hit !== undefined) return hit;
|
|
4366
|
+
const v = await compute();
|
|
4367
|
+
if (v !== undefined) kv.set(key, v, ttlSeconds);
|
|
4368
|
+
return v;
|
|
4369
|
+
}
|
|
4370
|
+
export function isCachedRoute(pathname: string): boolean {
|
|
4371
|
+
return routeCaches.some((r) => matchRoute(r.pattern, pathname));
|
|
4372
|
+
}
|
|
4373
|
+
export function invalidatePath(pathname: string): number {
|
|
4374
|
+
let n = 0;
|
|
4375
|
+
for (const key of [...__dynCache.keys()]) {
|
|
4376
|
+
if (key.startsWith(pathname + '|')) { __dynCache.delete(key); n++; }
|
|
4377
|
+
}
|
|
4378
|
+
return n;
|
|
4379
|
+
}
|
|
4380
|
+
export function peekRenderCache(pathname: string, cookieHeader: string): ReturnType<typeof renderPage> | null {
|
|
4381
|
+
const cfg = routeCaches.find((r) => matchRoute(r.pattern, pathname));
|
|
4382
|
+
if (!cfg) return null;
|
|
4383
|
+
let h = 0x811c9dc5;
|
|
4384
|
+
const c = cookieHeader || '';
|
|
4385
|
+
for (let i = 0; i < c.length; i++) {
|
|
4386
|
+
h ^= c.charCodeAt(i);
|
|
4387
|
+
h = (h * 0x01000193) >>> 0;
|
|
4388
|
+
}
|
|
4389
|
+
const hit = __dynCache.get(pathname + '|' + h.toString(16));
|
|
4390
|
+
return hit && hit.expires > Date.now() ? hit.page : null;
|
|
4391
|
+
}
|
|
4392
|
+
export async function renderPageCached(pathname: string, cookieHeader: string): Promise<ReturnType<typeof renderPage>> {
|
|
4393
|
+
const cfg = routeCaches.find((r) => matchRoute(r.pattern, pathname));
|
|
4394
|
+
if (!cfg) return renderPage(pathname);
|
|
4395
|
+
let h = 0x811c9dc5;
|
|
4396
|
+
for (let i = 0; i < cookieHeader.length; i++) {
|
|
4397
|
+
h ^= cookieHeader.charCodeAt(i);
|
|
4398
|
+
h = (h * 0x01000193) >>> 0;
|
|
4399
|
+
}
|
|
4400
|
+
const key = pathname + '|' + h.toString(16);
|
|
4401
|
+
const hit = __dynCache.get(key);
|
|
4402
|
+
if (hit && hit.expires > Date.now()) {
|
|
4403
|
+
__dynCache.delete(key);
|
|
4404
|
+
__dynCache.set(key, hit);
|
|
4405
|
+
return hit.page;
|
|
4406
|
+
}
|
|
4407
|
+
// Stale-while-revalidate: an EXPIRED entry still answers instantly while one background render refreshes it - the TTL boundary never spikes.
|
|
4408
|
+
if (hit && !hit.refreshing) {
|
|
4409
|
+
hit.refreshing = true;
|
|
4410
|
+
renderPage(pathname).then((fresh: any) => {
|
|
4411
|
+
if (fresh.status === 200 && !fresh.redirect) {
|
|
4412
|
+
__dynCache.set(key, { page: fresh, expires: Date.now() + cfg.seconds * 1000 });
|
|
4413
|
+
} else {
|
|
4414
|
+
__dynCache.delete(key);
|
|
4415
|
+
}
|
|
4416
|
+
}).catch(() => { __dynCache.delete(key); });
|
|
4417
|
+
return hit.page;
|
|
4418
|
+
}
|
|
4419
|
+
const page = await renderPage(pathname);
|
|
4420
|
+
if (page.status === 200 && !page.redirect) {
|
|
4421
|
+
__dynCache.set(key, { page, expires: Date.now() + cfg.seconds * 1000 });
|
|
4422
|
+
if (__dynCache.size > 300) {
|
|
4423
|
+
__dynCache.delete(__dynCache.keys().next().value as string);
|
|
4424
|
+
}
|
|
4425
|
+
}
|
|
4426
|
+
return page;
|
|
4427
|
+
}
|
|
4428
|
+
|
|
2804
4429
|
// Pages/_middleware.rose: a Web-standard request handler that runs before every render on the server (pages, POSTs, api calls alike).
|
|
2805
4430
|
export const middleware = ${middlewareIdx >= 0 ? 'middlewareMod.handle ?? null' : 'null'};
|
|
2806
4431
|
|
|
@@ -2915,7 +4540,14 @@ export function docAttrs(pathname) {
|
|
|
2915
4540
|
|
|
2916
4541
|
// Paint a fallback page (404/500) and serialize its state.
|
|
2917
4542
|
async function renderFallback(pathname, render) {
|
|
2918
|
-
|
|
4543
|
+
// Split mode: the not-found entry's render is a loader object — resolve it through getRender (which memoizes the composed function) exactly like.
|
|
4544
|
+
let fn = render;
|
|
4545
|
+
if (typeof fn !== 'function' && fn && typeof fn.load === 'function') {
|
|
4546
|
+
|
|
4547
|
+
// { render } once the route's chunk graph is loaded
|
|
4548
|
+
fn = (await fn.load()).render;
|
|
4549
|
+
}
|
|
4550
|
+
const { html, head } = extractHead(await fn([], ''));
|
|
2919
4551
|
const state = JSON.stringify({ __route: pathname, ...JSON.parse(serializeState()) });
|
|
2920
4552
|
return { html, state, head, ...docAttrs(pathname) };
|
|
2921
4553
|
}
|
|
@@ -2957,7 +4589,15 @@ function extractHead(rendered) {
|
|
|
2957
4589
|
|
|
2958
4590
|
// Form: the submitted FormData of a progressive-enhancement POST.
|
|
2959
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) {
|
|
2960
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;
|
|
2961
4601
|
for (const route of routes) {
|
|
2962
4602
|
if (matchRoute(route.pattern, pathname)) {
|
|
2963
4603
|
const patternParts = route.pattern.split('/');
|
|
@@ -3022,8 +4662,27 @@ export async function renderPage(pathname, form) {
|
|
|
3022
4662
|
return await notFoundPage(pathname);
|
|
3023
4663
|
}
|
|
3024
4664
|
console.error('rosetack: render failed for', pathname, err instanceof Error ? err.message : err);
|
|
3025
|
-
|
|
3026
|
-
|
|
4665
|
+
// F10: in dev the response body carries the real error — message, file:line and the fix hint.
|
|
4666
|
+
let devDetail = '';
|
|
4667
|
+
if (process.env.rosetack_DEV === '1' && err) {
|
|
4668
|
+
const msg = esc(err instanceof Error ? err.message : String(err));
|
|
4669
|
+
const file = esc(String(err.file || ''));
|
|
4670
|
+
const line = err.line != null ? esc(String(err.line)) : '';
|
|
4671
|
+
const hint = esc(String(err.hint || ''));
|
|
4672
|
+
const stack = esc(err instanceof Error ? (err.stack || '').split('\\n').slice(1, 7).join('\\n') : '');
|
|
4673
|
+
devDetail = '<div style="margin:24px auto;max-width:860px;font:13px/1.6 ui-monospace,monospace;background:#1b1b1f;color:#e6e6ea;border:1px solid #3a3a42;border-radius:10px;padding:20px 24px;text-align:left;white-space:pre-wrap;word-break:break-word">'
|
|
4674
|
+
+ '<div style="font:600 15px/1.4 system-ui,sans-serif;color:#ff8b8b">Render failed: ' + esc(pathname) + '</div>'
|
|
4675
|
+
+ '<div style="margin:10px 0 0;color:#ffd479">' + msg + '</div>'
|
|
4676
|
+
+ (file ? '<div style="margin:6px 0 0;color:#9ad1ff">' + file + (line ? ':' + line : '') + '</div>' : '')
|
|
4677
|
+
+ (hint ? '<div style="margin:10px 0 0;color:#9fe8b0">Fix: ' + hint + '</div>' : '')
|
|
4678
|
+
+ (stack ? '<pre style="margin:12px 0 0;color:#8f8f9a">' + stack + '</pre>' : '')
|
|
4679
|
+
+ '</div>';
|
|
4680
|
+
}
|
|
4681
|
+
if (errorPage) {
|
|
4682
|
+
const fb = await renderFallback(pathname, errorPage);
|
|
4683
|
+
return { ...fb, html: fb.html + devDetail, status: 500 };
|
|
4684
|
+
}
|
|
4685
|
+
return { html: '<h1>500</h1><p>Something went wrong rendering this page.</p>' + devDetail, state: '{}', head: [], status: 500, ...docAttrs(pathname) };
|
|
3027
4686
|
}
|
|
3028
4687
|
// __route tells the bootstrap which route this document was rendered for.
|
|
3029
4688
|
const state = JSON.stringify({ __route: pathname, ...JSON.parse(serializeState()) });
|
|
@@ -3107,7 +4766,15 @@ export async function handleApi(method, pathname, request) {
|
|
|
3107
4766
|
|
|
3108
4767
|
// === Streaming SSR === The static shell (doctype, <head>, body + container open) flushes BEFORE the - possibly slow - render completes: the first byte.
|
|
3109
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) {
|
|
3110
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;
|
|
3111
4778
|
for (const route of routes) {
|
|
3112
4779
|
if (matchRoute(route.pattern, pathname)) {
|
|
3113
4780
|
const patternParts = route.pattern.split('/');
|
|
@@ -3130,7 +4797,24 @@ export async function renderPageStream(pathname, write, shellOpen, clientTag) {
|
|
|
3130
4797
|
} catch (err) {
|
|
3131
4798
|
|
|
3132
4799
|
console.error('rosetack: render failed for', pathname, err instanceof Error ? err.message : err);
|
|
3133
|
-
|
|
4800
|
+
// F10: dev carries the real error in the body here too — the shell
|
|
4801
|
+
// is out, so the detail rides after the error page body.
|
|
4802
|
+
let devDetail = '';
|
|
4803
|
+
if (process.env.rosetack_DEV === '1' && err) {
|
|
4804
|
+
const msg = esc(err instanceof Error ? err.message : String(err));
|
|
4805
|
+
const file = esc(String(err.file || ''));
|
|
4806
|
+
const line = err.line != null ? esc(String(err.line)) : '';
|
|
4807
|
+
const hint = esc(String(err.hint || ''));
|
|
4808
|
+
const stack = esc(err instanceof Error ? (err.stack || '').split('\\n').slice(1, 7).join('\\n') : '');
|
|
4809
|
+
devDetail = '<div style="margin:24px auto;max-width:860px;font:13px/1.6 ui-monospace,monospace;background:#1b1b1f;color:#e6e6ea;border:1px solid #3a3a42;border-radius:10px;padding:20px 24px;text-align:left;white-space:pre-wrap;word-break:break-word">'
|
|
4810
|
+
+ '<div style="font:600 15px/1.4 system-ui,sans-serif;color:#ff8b8b">Render failed: ' + esc(pathname) + '</div>'
|
|
4811
|
+
+ '<div style="margin:10px 0 0;color:#ffd479">' + msg + '</div>'
|
|
4812
|
+
+ (file ? '<div style="margin:6px 0 0;color:#9ad1ff">' + file + (line ? ':' + line : '') + '</div>' : '')
|
|
4813
|
+
+ (hint ? '<div style="margin:10px 0 0;color:#9fe8b0">Fix: ' + hint + '</div>' : '')
|
|
4814
|
+
+ (stack ? '<pre style="margin:12px 0 0;color:#8f8f9a">' + stack + '</pre>' : '')
|
|
4815
|
+
+ '</div>';
|
|
4816
|
+
}
|
|
4817
|
+
html = errorPage ? extractHead(await errorPage([], '')).html + devDetail : '<h1>500</h1><p>Something went wrong rendering this page.</p>' + devDetail;
|
|
3134
4818
|
}
|
|
3135
4819
|
write(html);
|
|
3136
4820
|
// Csr: false ( auto since #29): a no-JS route's document ends here - no state script, no inlined bundle.
|
|
@@ -3147,7 +4831,49 @@ export async function renderPageStream(pathname, write, shellOpen, clientTag) {
|
|
|
3147
4831
|
}
|
|
3148
4832
|
return 404;
|
|
3149
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 };
|
|
3150
4839
|
`;
|
|
4840
|
+
try {
|
|
4841
|
+
const patterns = [...pages, ...apiRoutes].map(({ info }) => info.pattern);
|
|
4842
|
+
const uniq = [...new Set(patterns)].sort();
|
|
4843
|
+
const lit = uniq.map((p) => JSON.stringify(p)).join(" | ") || "'/'";
|
|
4844
|
+
const paramsOf = (pattern: string): string[] =>
|
|
4845
|
+
(pattern.match(/:[\w]+|\*\*[\w]+|\*[\w]+/g) ?? []).map((m) => m.replace(/^[*:]+/, ""));
|
|
4846
|
+
const paramSig = uniq
|
|
4847
|
+
.map((p) => {
|
|
4848
|
+
const ps = paramsOf(p);
|
|
4849
|
+
if (!ps.length) return "";
|
|
4850
|
+
return " " + JSON.stringify(p) + ": { " + ps.map((n) => n + ": string | number").join("; ") + " };\n";
|
|
4851
|
+
})
|
|
4852
|
+
.join("");
|
|
4853
|
+
const outDirTs = path.join(root, "src", ".rosetack");
|
|
4854
|
+
await fs.promises.mkdir(outDirTs, { recursive: true });
|
|
4855
|
+
const srcLines = [
|
|
4856
|
+
"// GENERATED by rosetack build - do not edit.",
|
|
4857
|
+
"export type RoutePath = " + lit + ";",
|
|
4858
|
+
"export const routePatterns = " + JSON.stringify(uniq) + " as const;",
|
|
4859
|
+
"export type RouteParams = {",
|
|
4860
|
+
paramSig,
|
|
4861
|
+
"};",
|
|
4862
|
+
"/** Build a URL from a route pattern and its params. */",
|
|
4863
|
+
"export function url(",
|
|
4864
|
+
" path: RoutePath,",
|
|
4865
|
+
" params: RouteParams[keyof RouteParams] = {} as never,",
|
|
4866
|
+
"): string {",
|
|
4867
|
+
" let out = path as string;",
|
|
4868
|
+
" for (const [k, v] of Object.entries(params as Record<string, string | number>)) {",
|
|
4869
|
+
" out = out.replace(new RegExp('[:*]+' + k, 'g'), String(v));",
|
|
4870
|
+
" }",
|
|
4871
|
+
" return out;",
|
|
4872
|
+
"}",
|
|
4873
|
+
].join("\n") + "\n";
|
|
4874
|
+
await fs.promises.writeFile(path.join(outDirTs, "routes.ts"), srcLines);
|
|
4875
|
+
} catch { /* types are a convenience: never fail the build over them */ }
|
|
4876
|
+
|
|
3151
4877
|
await fs.promises.writeFile(path.join(buildDir, 'server-entry.js'), serverEntry);
|
|
3152
4878
|
await esbuild.build({
|
|
3153
4879
|
entryPoints: [path.join(buildDir, 'server-entry.js')],
|
|
@@ -3159,6 +4885,25 @@ export async function renderPageStream(pathname, write, shellOpen, clientTag) {
|
|
|
3159
4885
|
...TS_LOADER,
|
|
3160
4886
|
});
|
|
3161
4887
|
|
|
4888
|
+
await esbuild.build({
|
|
4889
|
+
entryPoints: [(() => {
|
|
4890
|
+
const here = path.dirname(fileURLToPath(import.meta.url));
|
|
4891
|
+
for (const cand of [path.join(here, '..', 'cli', 'prod-server.ts'), path.join(here, '..', 'src', 'cli', 'prod-server.ts')]) {
|
|
4892
|
+
if (fs.existsSync(cand)) return cand;
|
|
4893
|
+
}
|
|
4894
|
+
return path.join(here, '..', 'cli', 'prod-server.ts');
|
|
4895
|
+
})()],
|
|
4896
|
+
bundle: true,
|
|
4897
|
+
outfile: path.join(outDir, 'prod.mjs'),
|
|
4898
|
+
format: 'esm',
|
|
4899
|
+
platform: 'node',
|
|
4900
|
+
write: true,
|
|
4901
|
+
banner: {
|
|
4902
|
+
js: "import { createRequire } from 'node:module'; import { fileURLToPath as __f2p } from 'node:url'; import { dirname as __dn } from 'node:path'; const require = createRequire(import.meta.url); const __filename = __f2p(import.meta.url); const __dirname = __dn(__filename);"
|
|
4903
|
+
},
|
|
4904
|
+
...TS_LOADER,
|
|
4905
|
+
});
|
|
4906
|
+
|
|
3162
4907
|
const clientImports = split ? '' : compiled
|
|
3163
4908
|
.map((_, i) => ({ i }))
|
|
3164
4909
|
.filter(({ i }) => !infos[i].isApi && !infos[i].isMiddleware && reachable.has(i))
|
|
@@ -3173,7 +4918,7 @@ export async function renderPageStream(pathname, write, shellOpen, clientTag) {
|
|
|
3173
4918
|
|
|
3174
4919
|
const prefetchMode = compiled.find((c) => c.prefetch)?.prefetch ?? 'all';
|
|
3175
4920
|
const vitalsOn = compiled.some((c) => c.vitals === true);
|
|
3176
|
-
|
|
4921
|
+
const vitalsBlock = vitalsOn
|
|
3177
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`
|
|
3178
4923
|
: '';
|
|
3179
4924
|
|
|
@@ -3201,7 +4946,7 @@ export async function renderPageStream(pathname, write, shellOpen, clientTag) {
|
|
|
3201
4946
|
|
|
3202
4947
|
const clientEntry = `
|
|
3203
4948
|
${clientImports}
|
|
3204
|
-
import { setState, resumeState, clearRequestState, resetEffects, wire, isolateStateAsync, restoreState, setRefreshHook, clearMounts, flushMounts, adoptCleanups, handlers, setLocales, setLocalePacks, ensureLocale, isLocale, localeDir, setPrefetchOverride, serializeState, setFxOwner, resetContainerFx } 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';
|
|
3205
4950
|
|
|
3206
4951
|
// I18n: the dictionaries baked at build time - the client renders any PRELOADED locale from the bundle.
|
|
3207
4952
|
setLocales(${clientLocalesJson}, '${defaultLocale}');
|
|
@@ -3416,12 +5161,22 @@ async function postForm(body, container, pathname) {
|
|
|
3416
5161
|
// Call a page's server action by name from any event handler: <button on:click={like}> compiles to $action('like').
|
|
3417
5162
|
export async function $action(name, e) {
|
|
3418
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);
|
|
3419
5168
|
const body = new FormData();
|
|
3420
5169
|
body.append('__action', name);
|
|
3421
5170
|
// An event inside a mount belongs to that mount - the attribute is kept in step with what is currently mounted.
|
|
3422
5171
|
const box = e && e.target && e.target.closest ? e.target.closest('[data-rosetack]') : null;
|
|
3423
|
-
|
|
5172
|
+
try {
|
|
5173
|
+
return await postForm(body, box || undefined, box ? box.getAttribute('data-rosetack') : undefined);
|
|
5174
|
+
} finally {
|
|
5175
|
+
__rvSetPending(false);
|
|
5176
|
+
}
|
|
3424
5177
|
}
|
|
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.
|
|
5179
|
+
setActionDispatcher($action);
|
|
3425
5180
|
|
|
3426
5181
|
export { postForm };
|
|
3427
5182
|
|
|
@@ -3453,6 +5208,16 @@ async function __withOwner(container, fn) {
|
|
|
3453
5208
|
setFxOwner(null);
|
|
3454
5209
|
}
|
|
3455
5210
|
}
|
|
5211
|
+
// View Transition on SPA swaps (B9): the DOM swap rides one cross-fade when the browser supports it; reduced-motion users and environments without.
|
|
5212
|
+
async function __swap(container, html) {
|
|
5213
|
+
const reduce = typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches;
|
|
5214
|
+
if (typeof document.startViewTransition === 'function' && !reduce) {
|
|
5215
|
+
const vt = document.startViewTransition(() => { container.innerHTML = html; });
|
|
5216
|
+
await vt.updateCallbackDone.catch(() => {});
|
|
5217
|
+
} else {
|
|
5218
|
+
container.innerHTML = html;
|
|
5219
|
+
}
|
|
5220
|
+
}
|
|
3456
5221
|
|
|
3457
5222
|
export async function start(container, pathname, initial) {
|
|
3458
5223
|
clearMounts(); // stale mounts from a failed render never fire
|
|
@@ -3475,7 +5240,7 @@ ${langDirBlock}
|
|
|
3475
5240
|
prefetchCache.delete(pathname);
|
|
3476
5241
|
__navReset(container);
|
|
3477
5242
|
restoreState(hit.state);
|
|
3478
|
-
container
|
|
5243
|
+
await __swap(container, hit.html);
|
|
3479
5244
|
await __withOwner(container, () => {
|
|
3480
5245
|
wire(container, hit.closes);
|
|
3481
5246
|
bindEvents(container);
|
|
@@ -3500,15 +5265,18 @@ ${langDirBlock}
|
|
|
3500
5265
|
if (err && err.__rosetack === 'redirect') { signal = err.path; return; }
|
|
3501
5266
|
|
|
3502
5267
|
|
|
5268
|
+
console.error('rosetack: client render failed for', pathname, err instanceof Error ? err.message : err);
|
|
3503
5269
|
broken = true;
|
|
3504
5270
|
return;
|
|
3505
5271
|
}
|
|
3506
|
-
if (!initial) container
|
|
5272
|
+
if (!initial) await __swap(container, html);
|
|
3507
5273
|
wire(container, closes);
|
|
3508
5274
|
bindEvents(container);
|
|
3509
5275
|
flushMounts();
|
|
3510
5276
|
});
|
|
3511
5277
|
if (signal === 'notFound') {
|
|
5278
|
+
// T17: a client-side render of a $data route without a prefetch entry has no data source (the server fills the context bag) - the correct.
|
|
5279
|
+
if (!initial) { try { location.assign(pathname); return; } catch { } }
|
|
3512
5280
|
await paintFallback(container, notFoundFor(pathname), '<h1>404</h1><p>Page not found</p>');
|
|
3513
5281
|
return;
|
|
3514
5282
|
}
|
|
@@ -3595,6 +5363,7 @@ setRefreshHook(async () => {
|
|
|
3595
5363
|
format: 'esm',
|
|
3596
5364
|
platform: 'browser',
|
|
3597
5365
|
minify: true,
|
|
5366
|
+
|
|
3598
5367
|
write: true,
|
|
3599
5368
|
...TS_LOADER,
|
|
3600
5369
|
});
|