rosetack 0.1.3 → 0.1.4
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/dist-cli/compiler.mjs +1391 -131
- package/dist-cli/edge.mjs +45 -10
- package/dist-cli/rosetack.mjs +1865 -254
- package/dist-cli/runtime.mjs +194 -13
- package/dist-cli/test.mjs +1466 -175
- package/package.json +1 -1
- package/src/FRAMEWORK_VERSION +1 -1
- package/src/cli/content.ts +186 -0
- package/src/cli/edge.ts +9 -1
- package/src/cli/image-size.ts +83 -0
- package/src/cli/index.ts +149 -7
- package/src/cli/prod-server.ts +324 -0
- package/src/cli/prompt.ts +47 -19
- package/src/cli/shell.ts +39 -6
- package/src/compiler/index.ts +1188 -64
- package/src/runtime/index.ts +215 -13
package/dist-cli/compiler.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// src/compiler/index.ts
|
|
2
|
-
import * as
|
|
3
|
-
import * as
|
|
2
|
+
import * as fs3 from "fs";
|
|
3
|
+
import * as path2 from "path";
|
|
4
4
|
import { pathToFileURL, fileURLToPath } from "url";
|
|
5
5
|
import * as esbuild from "esbuild";
|
|
6
6
|
|
|
@@ -43,16 +43,209 @@ function errorInfo(err) {
|
|
|
43
43
|
return { code: "E-UNKNOWN", message: err instanceof Error ? err.message : String(err) };
|
|
44
44
|
}
|
|
45
45
|
|
|
46
|
+
// src/cli/image-size.ts
|
|
47
|
+
import fs from "node:fs";
|
|
48
|
+
function readImageSize(filePath) {
|
|
49
|
+
try {
|
|
50
|
+
const fd = fs.openSync(filePath, "r");
|
|
51
|
+
const buf = Buffer.alloc(64);
|
|
52
|
+
const read = fs.readSync(fd, buf, 0, 64, 0);
|
|
53
|
+
fs.closeSync(fd);
|
|
54
|
+
if (read < 24) return null;
|
|
55
|
+
if (buf[0] === 137 && buf[1] === 80 && buf[2] === 78 && buf[3] === 71) {
|
|
56
|
+
return { width: buf.readUInt32BE(16), height: buf.readUInt32BE(20) };
|
|
57
|
+
}
|
|
58
|
+
if (buf.slice(0, 3).toString("latin1") === "GIF") {
|
|
59
|
+
return { width: buf.readUInt16LE(6), height: buf.readUInt16LE(8) };
|
|
60
|
+
}
|
|
61
|
+
if (buf.slice(0, 4).toString("latin1") === "RIFF" && buf.slice(8, 12).toString("latin1") === "WEBP") {
|
|
62
|
+
return parseWebP(buf);
|
|
63
|
+
}
|
|
64
|
+
if (buf[0] === 255 && buf[1] === 216) {
|
|
65
|
+
return parseJpeg(filePath);
|
|
66
|
+
}
|
|
67
|
+
return null;
|
|
68
|
+
} catch {
|
|
69
|
+
return null;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
function parseWebP(buf) {
|
|
73
|
+
const format = buf.slice(12, 16).toString("latin1");
|
|
74
|
+
if (format === "VP8 ") {
|
|
75
|
+
return { width: buf.readUInt16LE(26) & 16383, height: buf.readUInt16LE(28) & 16383 };
|
|
76
|
+
}
|
|
77
|
+
if (format === "VP8L") {
|
|
78
|
+
const b = buf.readUInt32LE(21);
|
|
79
|
+
return { width: (b & 16383) + 1, height: (b >> 14 & 16383) + 1 };
|
|
80
|
+
}
|
|
81
|
+
if (format === "VP8X") {
|
|
82
|
+
const w = buf.readUIntLE(24, 3) + 1;
|
|
83
|
+
const h = buf.readUIntLE(27, 3) + 1;
|
|
84
|
+
return { width: w, height: h };
|
|
85
|
+
}
|
|
86
|
+
return null;
|
|
87
|
+
}
|
|
88
|
+
function parseJpeg(filePath) {
|
|
89
|
+
const fd = fs.openSync(filePath, "r");
|
|
90
|
+
try {
|
|
91
|
+
const buf = Buffer.alloc(4);
|
|
92
|
+
let pos = 2;
|
|
93
|
+
for (let guard = 0; guard < 64; guard++) {
|
|
94
|
+
if (fs.readSync(fd, buf, 0, 4, pos) < 4) return null;
|
|
95
|
+
if (buf[0] !== 255) {
|
|
96
|
+
pos += 1;
|
|
97
|
+
continue;
|
|
98
|
+
}
|
|
99
|
+
const marker = buf[1];
|
|
100
|
+
if (marker === 216 || marker === 1 || marker >= 208 && marker <= 215) {
|
|
101
|
+
pos += 2;
|
|
102
|
+
continue;
|
|
103
|
+
}
|
|
104
|
+
const len = fs.readSync(fd, buf, 0, 2, pos + 2) < 2 ? 0 : buf.readUInt16BE(2);
|
|
105
|
+
if (marker >= 192 && marker <= 207 && marker !== 196 && marker !== 200 && marker !== 204) {
|
|
106
|
+
const seg = Buffer.alloc(8);
|
|
107
|
+
fs.readSync(fd, seg, 0, 8, pos + 4);
|
|
108
|
+
return { width: seg.readUInt16BE(3), height: seg.readUInt16BE(1) };
|
|
109
|
+
}
|
|
110
|
+
pos += 2 + len;
|
|
111
|
+
}
|
|
112
|
+
return null;
|
|
113
|
+
} finally {
|
|
114
|
+
fs.closeSync(fd);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
// src/cli/content.ts
|
|
119
|
+
import fs2 from "node:fs";
|
|
120
|
+
import path from "node:path";
|
|
121
|
+
function parseFrontmatter(raw) {
|
|
122
|
+
if (!raw.startsWith("---")) return { frontmatter: {}, body: raw };
|
|
123
|
+
const end = raw.indexOf("\n---", 3);
|
|
124
|
+
if (end < 0) return { frontmatter: {}, body: raw };
|
|
125
|
+
const head = raw.slice(4, end);
|
|
126
|
+
const body = raw.slice(raw.indexOf("\n", end + 1) + 1).replace(/^\s*\n/, "");
|
|
127
|
+
const frontmatter = {};
|
|
128
|
+
for (const line of head.split("\n")) {
|
|
129
|
+
const m = /^(\w[\w-]*):\s*(.*)$/.exec(line.trim());
|
|
130
|
+
if (!m) continue;
|
|
131
|
+
const [, k, v] = m;
|
|
132
|
+
const arr = /^\[(.+)\]$/.exec(v.trim());
|
|
133
|
+
frontmatter[k] = arr ? arr[1].split(",").map((x) => x.trim().replace(/^["']|["']$/g, "")) : v.trim().replace(/^["']|["']$/g, "");
|
|
134
|
+
}
|
|
135
|
+
return { frontmatter, body };
|
|
136
|
+
}
|
|
137
|
+
function interpolate(md, vars) {
|
|
138
|
+
return md.replace(/{{(\w[\w.]*)}}/g, (_m, k) => {
|
|
139
|
+
const v = k.split(".").reduce((o, p) => o == null ? o : o[p], vars);
|
|
140
|
+
return v === void 0 || v === null ? "" : String(v);
|
|
141
|
+
});
|
|
142
|
+
}
|
|
143
|
+
function renderMarkdown(md, vars) {
|
|
144
|
+
if (vars) md = interpolate(md, vars);
|
|
145
|
+
const blocks = [];
|
|
146
|
+
let src = md.replace(/```(\w*)\n([\s\S]*?)```/g, (_m, lang, code) => {
|
|
147
|
+
blocks.push(
|
|
148
|
+
`<pre data-lang="${lang}"><code>${code.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">")}</code></pre>`
|
|
149
|
+
);
|
|
150
|
+
return `\0CODE${blocks.length - 1}\0`;
|
|
151
|
+
});
|
|
152
|
+
const inline = (s) => s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/`([^`]+)`/g, "<code>$1</code>").replace(/\*\*([^*]+)\*\*/g, "<strong>$1</strong>").replace(/\*([^*]+)\*/g, "<em>$1</em>").replace(
|
|
153
|
+
/\[([^\]]+)\]\(([^)]+)\)/g,
|
|
154
|
+
'<a href="$2" rel="noopener">$1</a>'
|
|
155
|
+
);
|
|
156
|
+
const out = [];
|
|
157
|
+
let listOpen = null;
|
|
158
|
+
const closeList = () => {
|
|
159
|
+
if (listOpen) {
|
|
160
|
+
out.push(`</${listOpen}>`);
|
|
161
|
+
listOpen = null;
|
|
162
|
+
}
|
|
163
|
+
};
|
|
164
|
+
for (const line of src.split("\n")) {
|
|
165
|
+
const h = /^(#{1,4})\s+(.*)$/.exec(line);
|
|
166
|
+
const li = /^\s*[-*]\s+(.*)$/.exec(line);
|
|
167
|
+
const oli = /^\s*\d+\.\s+(.*)$/.exec(line);
|
|
168
|
+
if (h) {
|
|
169
|
+
closeList();
|
|
170
|
+
out.push(`<h${h[1].length}>${inline(h[2])}</h${h[1].length}>`);
|
|
171
|
+
} else if (li) {
|
|
172
|
+
if (listOpen !== "ul") {
|
|
173
|
+
closeList();
|
|
174
|
+
out.push("<ul>");
|
|
175
|
+
listOpen = "ul";
|
|
176
|
+
}
|
|
177
|
+
out.push(`<li>${inline(li[1])}</li>`);
|
|
178
|
+
} else if (oli) {
|
|
179
|
+
if (listOpen !== "ol") {
|
|
180
|
+
closeList();
|
|
181
|
+
out.push("<ol>");
|
|
182
|
+
listOpen = "ol";
|
|
183
|
+
}
|
|
184
|
+
out.push(`<li>${inline(oli[1])}</li>`);
|
|
185
|
+
} else if (line.trim() === "") {
|
|
186
|
+
closeList();
|
|
187
|
+
} else if (line.startsWith("\0CODE")) {
|
|
188
|
+
closeList();
|
|
189
|
+
out.push(line);
|
|
190
|
+
} else {
|
|
191
|
+
closeList();
|
|
192
|
+
out.push(`<p>${inline(line)}</p>`);
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
closeList();
|
|
196
|
+
return out.join("\n").replace(/\u0000CODE(\d+)\u0000/g, (_m, i) => blocks[Number(i)]);
|
|
197
|
+
}
|
|
198
|
+
function scanContentDir(contentDir) {
|
|
199
|
+
const collections = {};
|
|
200
|
+
if (!fs2.existsSync(contentDir)) return collections;
|
|
201
|
+
for (const coll of fs2.readdirSync(contentDir, { withFileTypes: true })) {
|
|
202
|
+
if (!coll.isDirectory()) continue;
|
|
203
|
+
const entries = [];
|
|
204
|
+
const dir = path.join(contentDir, coll.name);
|
|
205
|
+
for (const f of fs2.readdirSync(dir)) {
|
|
206
|
+
if (!f.endsWith(".md")) continue;
|
|
207
|
+
const raw = fs2.readFileSync(path.join(dir, f), "utf-8");
|
|
208
|
+
const { frontmatter, body } = parseFrontmatter(raw);
|
|
209
|
+
if (String(frontmatter.draft ?? "").toLowerCase() === "true") continue;
|
|
210
|
+
const slug = f.replace(/\.md$/, "");
|
|
211
|
+
const html = renderMarkdown(body);
|
|
212
|
+
const words = body.replace(/[#*`\[\]()>-]/g, " ").split(/\s+/).filter(Boolean).length;
|
|
213
|
+
const headings = [];
|
|
214
|
+
const tocHtml = html.replace(/<h([1-4])>([^<]+)<\/h\1>/g, (_m, lvl, txt) => {
|
|
215
|
+
const id = txt.toLowerCase().replace(/[^\w\s-]/g, "").trim().replace(/\s+/g, "-");
|
|
216
|
+
headings.push({ level: Number(lvl), text: txt, id });
|
|
217
|
+
return `<h${lvl} id="${id}">${txt}</h${lvl}>`;
|
|
218
|
+
});
|
|
219
|
+
entries.push({
|
|
220
|
+
slug,
|
|
221
|
+
frontmatter,
|
|
222
|
+
body,
|
|
223
|
+
html: tocHtml,
|
|
224
|
+
readingTime: Math.max(1, Math.round(words / 200)),
|
|
225
|
+
wordCount: words,
|
|
226
|
+
toc: headings,
|
|
227
|
+
excerpt: String(frontmatter.summary ?? "") || (html.match(/<p>([\s\S]*?)<\/p>/)?.[1] ?? "").replace(/<[^>]+>/g, "").slice(0, 160)
|
|
228
|
+
});
|
|
229
|
+
}
|
|
230
|
+
entries.sort(
|
|
231
|
+
(a, b) => String(b.frontmatter.date ?? "").localeCompare(String(a.frontmatter.date ?? ""))
|
|
232
|
+
);
|
|
233
|
+
collections[coll.name] = entries;
|
|
234
|
+
}
|
|
235
|
+
return collections;
|
|
236
|
+
}
|
|
237
|
+
globalThis.__rosetackContentMk = renderMarkdown;
|
|
238
|
+
|
|
46
239
|
// src/compiler/index.ts
|
|
47
240
|
var COMPONENT_RE = /<script>([\s\S]*?)<\/script>/;
|
|
48
241
|
var TEMPLATE_RE = /<template>([\s\S]*?)<\/template>/;
|
|
49
242
|
var HEAD_RE = /<head>([\s\S]*?)<\/head>/;
|
|
50
243
|
var STYLE_RE = /<style>([\s\S]*?)<\/style>/;
|
|
51
|
-
var DECL_RE = /(?:let|const|var)\s+(\w+)[^=]*=\s*\$(state|data)\b/g;
|
|
244
|
+
var DECL_RE = /(?:let|const|var)\s+(\w+)[^=]*=\s*\$(state|data|kv|persist)\b/g;
|
|
52
245
|
var DECL_CAST_RE = /^\s+as\s+[^;\n]+/;
|
|
53
246
|
var SETSTATE_RE = /\$setState\(([^,]+),\s*([^)]+)\)/g;
|
|
54
|
-
var SLOT_RE = /<slot\s
|
|
55
|
-
var SLOT_NAMED_RE = /<slot\s+((?=[^>]*\bname\s*=)[^>]*?)
|
|
247
|
+
var SLOT_RE = /<slot\s*\/>|<slot>([\s\S]*?)<\/slot>/g;
|
|
248
|
+
var SLOT_NAMED_RE = /<slot\s+((?=[^>]*\bname\s*=)[^>]*?)(?:\/>|>([\s\S]*?)<\/slot>)/g;
|
|
56
249
|
function encodeSlotCall(attrs) {
|
|
57
250
|
const name = /\bname\s*=\s*["'](\w+)["']/.exec(attrs)?.[1];
|
|
58
251
|
if (!name) throw new RoseError("E-TEMPLATE", '<slot> with attributes must declare a name: <slot name="row" ... />', { hint: 'a slot carrying attributes is a NAMED slot - it must declare which one: <slot name="row" item={post} />' });
|
|
@@ -447,8 +640,8 @@ function scriptOf(source) {
|
|
|
447
640
|
return source.match(COMPONENT_RE)?.[1] ?? null;
|
|
448
641
|
}
|
|
449
642
|
async function loadConfig(root) {
|
|
450
|
-
const file =
|
|
451
|
-
if (!
|
|
643
|
+
const file = path2.join(root, "rosetack.config.js");
|
|
644
|
+
if (!fs3.existsSync(file)) return { plugins: [], i18n: {} };
|
|
452
645
|
const mod = await import(pathToFileURL(file).href + `?t=${Date.now()}`);
|
|
453
646
|
return {
|
|
454
647
|
plugins: mod.default ?? [],
|
|
@@ -461,12 +654,12 @@ async function loadPlugins(root) {
|
|
|
461
654
|
function resolveRoseImports(script, fromFile, registry) {
|
|
462
655
|
const imports = [];
|
|
463
656
|
const resolve2 = (spec, at) => {
|
|
464
|
-
const abs =
|
|
657
|
+
const abs = path2.resolve(path2.dirname(fromFile), spec);
|
|
465
658
|
const hit = registry.get(abs);
|
|
466
659
|
if (!hit) {
|
|
467
660
|
throw new RoseError(
|
|
468
661
|
"E-IMPORT",
|
|
469
|
-
`${
|
|
662
|
+
`${path2.basename(fromFile)}: cannot import '${spec}' - no .rose file at ${abs}. A component lives under src/components/ (or src/pages/) and is imported by relative path.`,
|
|
470
663
|
{
|
|
471
664
|
file: fromFile,
|
|
472
665
|
line: lineOf(script, at),
|
|
@@ -501,16 +694,45 @@ function nodeOnlyImports(importStmts) {
|
|
|
501
694
|
}
|
|
502
695
|
return out;
|
|
503
696
|
}
|
|
504
|
-
function wireEventBindings(template, actionNames) {
|
|
697
|
+
function wireEventBindings(template, actionNames, filePath = "<template>") {
|
|
505
698
|
const bindings = [];
|
|
506
699
|
let out = "";
|
|
507
700
|
let rest = template;
|
|
701
|
+
const TARGET_MODS = { window: "w", document: "d" };
|
|
702
|
+
const MOD_PRE = {
|
|
703
|
+
preventDefault: () => "e.preventDefault()",
|
|
704
|
+
stopPropagation: () => "e.stopPropagation()",
|
|
705
|
+
self: (p) => `const __self = e.target.closest && e.target.closest('[data-${p}-' + e.type + ']'); if (__self && e.target !== __self) return;`
|
|
706
|
+
};
|
|
707
|
+
const MOD_POST = {
|
|
708
|
+
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);`
|
|
709
|
+
};
|
|
710
|
+
const KNOWN_MODS = [...Object.keys(MOD_PRE), ...Object.keys(MOD_POST), ...Object.keys(TARGET_MODS)];
|
|
508
711
|
for (; ; ) {
|
|
509
|
-
const m = /\bon:(\w+)\s*=\s*\{/.exec(rest);
|
|
712
|
+
const m = /\bon:(\w+)((?:\|\w+)*)\s*=\s*\{/.exec(rest);
|
|
510
713
|
if (!m) {
|
|
511
714
|
out += rest;
|
|
512
715
|
break;
|
|
513
716
|
}
|
|
717
|
+
const mods = m[2] ? m[2].slice(1).split("|") : [];
|
|
718
|
+
const targets = mods.filter((mod) => TARGET_MODS[mod]);
|
|
719
|
+
if (targets.length > 1) {
|
|
720
|
+
throw new RoseError(
|
|
721
|
+
"E-TEMPLATE",
|
|
722
|
+
`${filePath}: on:${m[1]} carries both |${targets.join(" and |")}`,
|
|
723
|
+
{ hint: "a handler binds to one target - the element (default), |window or |document" }
|
|
724
|
+
);
|
|
725
|
+
}
|
|
726
|
+
const prefix = targets.length ? "on" + TARGET_MODS[targets[0]] : "on";
|
|
727
|
+
for (const mod of mods) {
|
|
728
|
+
if (!KNOWN_MODS.includes(mod)) {
|
|
729
|
+
throw new RoseError(
|
|
730
|
+
"E-TEMPLATE",
|
|
731
|
+
`${filePath}: unknown event modifier |${mod}`,
|
|
732
|
+
{ hint: `the supported modifiers are ${KNOWN_MODS.map((k) => "|" + k).join(" ")} - capture/passive are listener options a delegated listener cannot carry per element; anything else belongs inside the handler body` }
|
|
733
|
+
);
|
|
734
|
+
}
|
|
735
|
+
}
|
|
514
736
|
out += rest.slice(0, m.index);
|
|
515
737
|
let i = m.index + m[0].length;
|
|
516
738
|
let depth = 1;
|
|
@@ -532,7 +754,24 @@ function wireEventBindings(template, actionNames) {
|
|
|
532
754
|
i++;
|
|
533
755
|
}
|
|
534
756
|
const expr = rest.slice(m.index + m[0].length, i).trim();
|
|
535
|
-
|
|
757
|
+
const wrap = (body) => {
|
|
758
|
+
if (!mods.length) return body;
|
|
759
|
+
const pre = mods.filter((mod) => MOD_PRE[mod]).map((mod) => MOD_PRE[mod](prefix));
|
|
760
|
+
const post = mods.filter((mod) => MOD_POST[mod]).map((mod) => MOD_POST[mod](prefix));
|
|
761
|
+
return `(e) => {${pre.length ? " " + pre.join("; ") + ";" : ""} (${body})(e);${post.length ? " " + post.join("; ") + ";" : ""} }`;
|
|
762
|
+
};
|
|
763
|
+
if (mods.length && actionNames.has(expr)) {
|
|
764
|
+
throw new RoseError(
|
|
765
|
+
"E-TEMPLATE",
|
|
766
|
+
`${filePath}: event modifiers are not supported on the server action ${expr}`,
|
|
767
|
+
{ hint: "$action already preventDefaults - drop the modifiers, or bind a local handler that calls $action" }
|
|
768
|
+
);
|
|
769
|
+
}
|
|
770
|
+
if (mods.length) {
|
|
771
|
+
const name = `__h${bindings.length}`;
|
|
772
|
+
out += `data-${prefix}-${m[1]}="${name}"`;
|
|
773
|
+
bindings.push({ event: m[1], fn: `${name}: ${wrap(expr)}` });
|
|
774
|
+
} else if (actionNames.has(expr)) {
|
|
536
775
|
out += `data-on-${m[1]}="$action:${expr}"`;
|
|
537
776
|
} else if (/^\w+$/.test(expr)) {
|
|
538
777
|
out += `data-on-${m[1]}="${expr}"`;
|
|
@@ -549,7 +788,7 @@ function wireEventBindings(template, actionNames) {
|
|
|
549
788
|
function scanSlotDecls(filePath) {
|
|
550
789
|
let src;
|
|
551
790
|
try {
|
|
552
|
-
src =
|
|
791
|
+
src = fs3.readFileSync(filePath, "utf-8");
|
|
553
792
|
} catch {
|
|
554
793
|
return [];
|
|
555
794
|
}
|
|
@@ -603,7 +842,7 @@ function hoistImports(script) {
|
|
|
603
842
|
return { imports: imports.join("\n"), rest: rest.join("\n") };
|
|
604
843
|
}
|
|
605
844
|
async function compileComponent(filePath, publicDir, scopeKey, isApi = false, plugins = [], registry = /* @__PURE__ */ new Map()) {
|
|
606
|
-
let source = await
|
|
845
|
+
let source = await fs3.promises.readFile(filePath, "utf-8");
|
|
607
846
|
for (const p of plugins) {
|
|
608
847
|
if (!p.transform) continue;
|
|
609
848
|
try {
|
|
@@ -611,7 +850,7 @@ async function compileComponent(filePath, publicDir, scopeKey, isApi = false, pl
|
|
|
611
850
|
} catch (err) {
|
|
612
851
|
throw new RoseError(
|
|
613
852
|
"E-PLUGIN",
|
|
614
|
-
`plugin ${p.name} failed on ${
|
|
853
|
+
`plugin ${p.name} failed on ${path2.basename(filePath)}: ${err instanceof Error ? err.message : String(err)}`,
|
|
615
854
|
{ file: filePath, hint: "the error above came from inside the plugin - fix its transform() (or remove the plugin from rosetack.config.js)" }
|
|
616
855
|
);
|
|
617
856
|
}
|
|
@@ -654,7 +893,7 @@ ${hoisted.rest}`, "ssr").trim()}`,
|
|
|
654
893
|
const rawScript = roseResolved.script;
|
|
655
894
|
const roseImports = roseResolved.imports;
|
|
656
895
|
const { imports: importStmts, rest: scriptNoImports } = hoistImports(rawScript);
|
|
657
|
-
if (
|
|
896
|
+
if (path2.basename(filePath) !== "_middleware.rose") {
|
|
658
897
|
for (const spec of nodeOnlyImports(importStmts)) {
|
|
659
898
|
const at = importStmts.indexOf(spec);
|
|
660
899
|
throw new RoseError(
|
|
@@ -680,6 +919,8 @@ ${hoisted.rest}`, "ssr").trim()}`,
|
|
|
680
919
|
const hasParams = /(?:^|\n)\s*export\s+(?:(?:const|let|var)\s+|(?:async\s+)?function\s+)params\b/.test(rawScript);
|
|
681
920
|
const revalidateMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+revalidate\s*=\s*(\d+)\s*;?/);
|
|
682
921
|
const revalidate = revalidateMatch ? Number(revalidateMatch[1]) : void 0;
|
|
922
|
+
const cacheMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+cache\s*=\s*(\d+)\s*;?/);
|
|
923
|
+
const cacheSeconds = cacheMatch ? Number(cacheMatch[1]) : void 0;
|
|
683
924
|
const prefetchMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+prefetch\s*=\s*['"`](\w+)['"`]\s*;?/);
|
|
684
925
|
const prefetch = prefetchMatch ? prefetchMatch[1] : void 0;
|
|
685
926
|
if (prefetch && !["off", "hover", "viewport", "all"].includes(prefetch)) {
|
|
@@ -784,6 +1025,7 @@ ${hoisted.rest}`, "ssr").trim()}`,
|
|
|
784
1025
|
}
|
|
785
1026
|
const lifecycle = rawScript.match(/\b(?:onMount|onCleanup|refresh|adopt|\$action|\$setState)\s*\(/);
|
|
786
1027
|
if (lifecycle) clientReasons.push(`${lifecycle[0].replace(/\s*\($/, "")}()`);
|
|
1028
|
+
if (source.includes("{#defer")) clientReasons.push("{#defer} progressive content");
|
|
787
1029
|
const needsClient = clientReasons.length > 0;
|
|
788
1030
|
const jsWarnings = [];
|
|
789
1031
|
if (!needsClient) {
|
|
@@ -808,7 +1050,7 @@ ${hoisted.rest}`, "ssr").trim()}`,
|
|
|
808
1050
|
const rawTemplate = templateMatch ? templateMatch[1] : sourceNoBlocks.replace(COMPONENT_RE, "").trim();
|
|
809
1051
|
const template = scopedStyle ? injectScopeAttr(inlineImages(rawTemplate, publicDir), scopeKey) : inlineImages(rawTemplate, publicDir);
|
|
810
1052
|
const decls = extractDecls(script);
|
|
811
|
-
const stateDecls = decls.filter((d) => d.kind === "state");
|
|
1053
|
+
const stateDecls = decls.filter((d) => d.kind === "state" || d.kind === "kv" || d.kind === "persist");
|
|
812
1054
|
const setterNames = /* @__PURE__ */ new Map();
|
|
813
1055
|
stateDecls.forEach((s) => setterNames.set(s.name, `set${capitalize(s.name)}`));
|
|
814
1056
|
const declCode = (d) => {
|
|
@@ -818,6 +1060,17 @@ ${hoisted.rest}`, "ssr").trim()}`,
|
|
|
818
1060
|
}
|
|
819
1061
|
const isFn = d.expr.includes("=>") || d.expr.startsWith("function");
|
|
820
1062
|
const fn = isFn ? d.expr : `() => (${d.expr})`;
|
|
1063
|
+
if (d.kind === "persist") {
|
|
1064
|
+
return `const [${d.name}, ${setterNames.get(d.name)}] = persistState(${JSON.stringify(key)}, ${d.expr});`;
|
|
1065
|
+
}
|
|
1066
|
+
if (d.kind === "kv") {
|
|
1067
|
+
const mTtl = /^(.*)\s*,\s*(\d+)\s*$/s.exec(d.expr);
|
|
1068
|
+
const fnExpr = mTtl ? mTtl[1] : d.expr;
|
|
1069
|
+
const ttl = mTtl ? mTtl[2] : "300";
|
|
1070
|
+
return `const __had_${d.name} = hasState(${JSON.stringify(key)});
|
|
1071
|
+
const [${d.name}, set${capitalize(d.name)}] = state(${JSON.stringify(key)}, null);
|
|
1072
|
+
if (!__had_${d.name}) set${capitalize(d.name)}(await globalThis.__rosetackKvApi.kvMemo(${JSON.stringify("__kvh:" + scopeKey + ":" + d.name)}, ${fnExpr}, ${ttl}));`;
|
|
1073
|
+
}
|
|
821
1074
|
return `const __had_${d.name} = hasState(${JSON.stringify(key)});
|
|
822
1075
|
const [${d.name}, set${capitalize(d.name)}] = state(${JSON.stringify(key)}, null);
|
|
823
1076
|
if (!__had_${d.name}) set${capitalize(d.name)}(await $data(${fn}));`;
|
|
@@ -842,15 +1095,119 @@ if (!__had_${d.name}) set${capitalize(d.name)}(await $data(${fn}));`;
|
|
|
842
1095
|
const stateDeclsCode = nestedDecls.filter((d) => d.kind === "state").map(declCode).join("\n");
|
|
843
1096
|
const dataDeclsCode = nestedDecls.filter((d) => d.kind === "data").map(declCode).join("\n");
|
|
844
1097
|
const templateCalled = callifyTemplateExprs(template, stateDecls.map((s) => s.name));
|
|
845
|
-
const
|
|
846
|
-
const
|
|
1098
|
+
const imgDefaulted = templateCalled.replace(/<img\b(?![^>]*?\sloading=)/gi, '<img loading="lazy"').replace(/<img\b(?![^>]*?\sdecoding=)/gi, '<img decoding="async"');
|
|
1099
|
+
const wired = wireEventBindings(imgDefaulted, actionNames, filePath);
|
|
847
1100
|
const stateKeys = decls.map((d) => d.name);
|
|
1101
|
+
const bindBindings = [];
|
|
1102
|
+
let bindCounter = 0;
|
|
1103
|
+
const bindExpanded = wired.template.replace(
|
|
1104
|
+
/\sbind:(value|checked|this)\s*=\s*\{([\w$]+)(?:\(\))?\}/g,
|
|
1105
|
+
(whole, kind, name) => {
|
|
1106
|
+
if (!stateKeys.includes(name)) {
|
|
1107
|
+
throw new Error(
|
|
1108
|
+
`${filePath}: bind:${kind}={${name}} must name a $state declaration` + (stateKeys.length ? ` (state keys here: ${stateKeys.join(", ")})` : " (this file declares no $state)")
|
|
1109
|
+
);
|
|
1110
|
+
}
|
|
1111
|
+
if (kind === "this") return ` data-bind-this="${name}"`;
|
|
1112
|
+
const setter = setterNames.get(name);
|
|
1113
|
+
const evt = kind === "checked" ? "change" : "input";
|
|
1114
|
+
const hname = `__rvbind_${scopeKey.replace(/\W/g, "_")}_${bindCounter++}`;
|
|
1115
|
+
bindBindings.push({
|
|
1116
|
+
event: evt,
|
|
1117
|
+
fn: kind === "checked" ? `${hname}: (e) => ${setter}(e.target.checked)` : `${hname}: (e) => { const t = e.target; ${setter}(t.type === 'number' || t.type === 'range' ? t.valueAsNumber : t.value); }`
|
|
1118
|
+
});
|
|
1119
|
+
const evtAttr = kind === "checked" ? ` data-on-change="${hname}"` : ` data-on-input="${hname}" data-on-change="${hname}"`;
|
|
1120
|
+
return ` ${kind}={${name}()}${evtAttr}`;
|
|
1121
|
+
}
|
|
1122
|
+
);
|
|
848
1123
|
const comps = new Map(roseImports.map((r) => {
|
|
849
|
-
const abs =
|
|
1124
|
+
const abs = path2.resolve(path2.dirname(filePath), r.specifier);
|
|
850
1125
|
const hit = registry.get(abs);
|
|
851
1126
|
return [r.name, { index: hit.index, slots: hit.slots }];
|
|
852
1127
|
}));
|
|
853
|
-
const
|
|
1128
|
+
const groupBindings = [];
|
|
1129
|
+
let groupCounter = 0;
|
|
1130
|
+
const TAG_SCAN_RE = /<([a-zA-Z][^\s>/]*)((?:[^>"']|"[^"]*"|'[^']*')*?)(\/?)>/g;
|
|
1131
|
+
const groupExpanded = (() => {
|
|
1132
|
+
if (!bindExpanded.includes("bind:group")) return bindExpanded;
|
|
1133
|
+
let out = "";
|
|
1134
|
+
let pos2 = 0;
|
|
1135
|
+
let m;
|
|
1136
|
+
TAG_SCAN_RE.lastIndex = 0;
|
|
1137
|
+
while (m = TAG_SCAN_RE.exec(bindExpanded)) {
|
|
1138
|
+
const [whole, tag, attrs, selfClose] = m;
|
|
1139
|
+
const gm = /\sbind:group\s*=\s*\{([\w$]+)(?:\(\))?\}/.exec(attrs);
|
|
1140
|
+
if (!gm) continue;
|
|
1141
|
+
const name = gm[1];
|
|
1142
|
+
if (!stateKeys.includes(name)) {
|
|
1143
|
+
throw new RoseError(
|
|
1144
|
+
"E-TEMPLATE",
|
|
1145
|
+
`${filePath}: bind:group={${name}} must name a $state declaration`,
|
|
1146
|
+
{ hint: "the group state holds the selected value (radio) or an ARRAY of checked values (checkbox) - declare it: let " + name + ' = $state("")' }
|
|
1147
|
+
);
|
|
1148
|
+
}
|
|
1149
|
+
if (!/\stype\s*=\s*["'](radio|checkbox)["']/.test(attrs)) {
|
|
1150
|
+
throw new RoseError(
|
|
1151
|
+
"E-TEMPLATE",
|
|
1152
|
+
`${filePath}: bind:group is for radio and checkbox inputs`,
|
|
1153
|
+
{ hint: '<input type="radio" value="v" bind:group={state}> holds the selected value; type="checkbox" holds an ARRAY of the checked values (declare the state as $state([]))' }
|
|
1154
|
+
);
|
|
1155
|
+
}
|
|
1156
|
+
const isArrayGroup = /\stype\s*=\s*["']checkbox["']/.test(attrs);
|
|
1157
|
+
const vm = /\svalue\s*=\s*"([^"]*)"|\svalue\s*=\s*'([^']*)'/.exec(attrs);
|
|
1158
|
+
if (!vm || /\{/.test(vm[0])) {
|
|
1159
|
+
throw new RoseError(
|
|
1160
|
+
"E-TEMPLATE",
|
|
1161
|
+
`${filePath}: a bind:group input needs a static value attribute`,
|
|
1162
|
+
{ hint: '<input type="radio" value="free" bind:group={plan}> - the value IS what the state receives' }
|
|
1163
|
+
);
|
|
1164
|
+
}
|
|
1165
|
+
if (/\schecked\s*=/.test(attrs)) {
|
|
1166
|
+
throw new RoseError(
|
|
1167
|
+
"E-TEMPLATE",
|
|
1168
|
+
`${filePath}: a bind:group input cannot also carry checked=`,
|
|
1169
|
+
{ hint: "the group state alone decides which inputs are checked" }
|
|
1170
|
+
);
|
|
1171
|
+
}
|
|
1172
|
+
const setter = setterNames.get(name);
|
|
1173
|
+
const hname = `__rvbg_${scopeKey.replace(/\W/g, "_")}_${groupCounter++}`;
|
|
1174
|
+
const groupValue = JSON.stringify(vm[1] ?? vm[2]);
|
|
1175
|
+
const checkedExpr = isArrayGroup ? `${name}().includes(${groupValue})` : `${name}() === ${groupValue}`;
|
|
1176
|
+
const handlerBody = isArrayGroup ? `${setter}(e.target.checked ? [...${name}(), ${groupValue}] : ${name}().filter((x) => x !== ${groupValue}))` : `${setter}(e.target.value)`;
|
|
1177
|
+
groupBindings.push({ event: "change", fn: `${hname}: (e) => { ${handlerBody}; }` });
|
|
1178
|
+
const newAttrs = attrs.replace(gm[0], ` checked={${checkedExpr}} data-on-change="${hname}"`);
|
|
1179
|
+
out += bindExpanded.slice(pos2, m.index) + `<${tag}${newAttrs}${selfClose}>`;
|
|
1180
|
+
pos2 = m.index + whole.length;
|
|
1181
|
+
}
|
|
1182
|
+
if (pos2 === 0) return bindExpanded;
|
|
1183
|
+
out += bindExpanded.slice(pos2);
|
|
1184
|
+
return out;
|
|
1185
|
+
})();
|
|
1186
|
+
const eventBindings = wired.bindings.concat(bindBindings, groupBindings);
|
|
1187
|
+
const useExpanded = groupExpanded.replace(
|
|
1188
|
+
/\suse:([\w-]+)(\s*=\s*\{([\s\S]*?)\})?/g,
|
|
1189
|
+
(_w, name, hasParam, expr) => hasParam ? ` data-use="${name}" data-use-param={JSON.stringify(${expr})}` : ` data-use="${name}"`
|
|
1190
|
+
);
|
|
1191
|
+
const classExpanded = expandClassDirectives(useExpanded, filePath);
|
|
1192
|
+
const styleExpanded = expandStyleDirectives(classExpanded, filePath);
|
|
1193
|
+
const keyExpanded = expandKeyBlocks(styleExpanded, filePath);
|
|
1194
|
+
const elseExpanded = expandIfElse(keyExpanded);
|
|
1195
|
+
const deferExpanded = expandDeferBlocks(elseExpanded);
|
|
1196
|
+
const fbExpanded = expandBoundaryFallbacks(deferExpanded.template, filePath);
|
|
1197
|
+
const ssrTemplate = rewriteQuotedExprAttrs(fbExpanded.replace(SLOT_NAMED_RE, (_w, attrs, fallback) => {
|
|
1198
|
+
const call = `{__slot(${encodeSlotCall(attrs)})}`;
|
|
1199
|
+
if (fallback) {
|
|
1200
|
+
if (/\{[^{}]*\}/.test(fallback)) {
|
|
1201
|
+
throw new RoseError(
|
|
1202
|
+
"E-TEMPLATE",
|
|
1203
|
+
`${filePath}: slot fallback content must be static markup`,
|
|
1204
|
+
{ hint: "a {expr} inside a slot fallback has no reactive scope here - render the dynamic part in the parent and pass it as the slot content" }
|
|
1205
|
+
);
|
|
1206
|
+
}
|
|
1207
|
+
return `{__slot(${encodeSlotCall(attrs)}, ${JSON.stringify(fallback)})}`;
|
|
1208
|
+
}
|
|
1209
|
+
return call;
|
|
1210
|
+
}).replace(SLOT_RE, (_w, fallback) => fallback && fallback.trim() ? `{__slotDefault(${JSON.stringify(fallback)})}` : "{__slot__}"), comps);
|
|
854
1211
|
assertKnownDirectives(ssrTemplate, filePath);
|
|
855
1212
|
const compiledTemplate = compileTemplate(ssrTemplate, "h", "__c", null, 0, true, comps);
|
|
856
1213
|
const compiledHead = headContent.trim() ? compileHead(headContent) : "";
|
|
@@ -859,7 +1216,7 @@ if (!__had_${d.name}) set${capitalize(d.name)}(await $data(${fn}));`;
|
|
|
859
1216
|
${actions.map((a) => a.stmt).join("\n")}` : exportStmts;
|
|
860
1217
|
const ssrGuard = guard ? `
|
|
861
1218
|
${guard}` : "";
|
|
862
|
-
const isMiddleware =
|
|
1219
|
+
const isMiddleware = path2.basename(filePath) === "_middleware.rose";
|
|
863
1220
|
const ssr = isMiddleware ? `${RUNTIME_IMPORTS}
|
|
864
1221
|
|
|
865
1222
|
${importStmts}
|
|
@@ -868,8 +1225,8 @@ ${ssrExports}
|
|
|
868
1225
|
${ssrGuard}
|
|
869
1226
|
|
|
870
1227
|
${cleanScript}
|
|
871
|
-
` : generateSSR(cleanScript, compiledTemplate, stateDeclsCode, ssrExports, compiledHead, props, hasNamedSlots, importStmts, isComponent, ssrGuard, actions.length > 0, dataDeclsCode);
|
|
872
|
-
const client = generateClient(cleanScript, compiledTemplate, stateDeclsCode, eventBindings, exportStmts, compiledHead, props, hasNamedSlots, importStmts, isComponent, dataDeclsCode);
|
|
1228
|
+
` : generateSSR(cleanScript + deferBootCode(deferExpanded.count, deferExpanded.holds), compiledTemplate, stateDeclsCode, ssrExports, compiledHead, props, hasNamedSlots, importStmts, isComponent, ssrGuard, actions.length > 0, dataDeclsCode);
|
|
1229
|
+
const client = generateClient(cleanScript + deferBootCode(deferExpanded.count, deferExpanded.holds), compiledTemplate, stateDeclsCode, eventBindings, exportStmts, compiledHead, props, hasNamedSlots, importStmts, isComponent, dataDeclsCode);
|
|
873
1230
|
return {
|
|
874
1231
|
ssr: rewriteRoseImports(ssr, "ssr"),
|
|
875
1232
|
client: rewriteRoseImports(client, "client"),
|
|
@@ -880,6 +1237,7 @@ ${cleanScript}
|
|
|
880
1237
|
hasParams,
|
|
881
1238
|
usesContext,
|
|
882
1239
|
revalidate,
|
|
1240
|
+
cache: cacheSeconds,
|
|
883
1241
|
csr,
|
|
884
1242
|
shell,
|
|
885
1243
|
buffer,
|
|
@@ -1070,6 +1428,20 @@ function extractExports(script) {
|
|
|
1070
1428
|
out += script.slice(pos);
|
|
1071
1429
|
return { clean: out, exports: stmts.join("\n"), actions, props, guard: guards.join("\n") };
|
|
1072
1430
|
}
|
|
1431
|
+
var REGEX_PRECEDERS = new Set("(,=:[!&|?{};+-*%<>~^".split(""));
|
|
1432
|
+
function isRegexStart(src, i) {
|
|
1433
|
+
let j = i - 1;
|
|
1434
|
+
while (j >= 0 && /\s/.test(src[j])) j--;
|
|
1435
|
+
if (j < 0) return true;
|
|
1436
|
+
const p = src[j];
|
|
1437
|
+
if (REGEX_PRECEDERS.has(p)) return true;
|
|
1438
|
+
if (/[A-Za-z0-9_$]/.test(p)) {
|
|
1439
|
+
const w = /([A-Za-z_$][A-Za-z0-9_$]*)$/.exec(src.slice(0, j + 1));
|
|
1440
|
+
if (!w) return false;
|
|
1441
|
+
return ["return", "typeof", "instanceof", "in", "of", "new", "delete", "void", "throw", "case", "do", "else"].includes(w[1]);
|
|
1442
|
+
}
|
|
1443
|
+
return false;
|
|
1444
|
+
}
|
|
1073
1445
|
function extractDecls(script) {
|
|
1074
1446
|
const decls = [];
|
|
1075
1447
|
DECL_RE.lastIndex = 0;
|
|
@@ -1161,6 +1533,35 @@ function braceDepthAt(src, index) {
|
|
|
1161
1533
|
i = close === -1 ? src.length : close + 2;
|
|
1162
1534
|
continue;
|
|
1163
1535
|
}
|
|
1536
|
+
if (ch === "/" && isRegexStart(src, i)) {
|
|
1537
|
+
i++;
|
|
1538
|
+
let inClass = false;
|
|
1539
|
+
while (i < index) {
|
|
1540
|
+
const c2 = src[i];
|
|
1541
|
+
if (c2 === "\\") {
|
|
1542
|
+
i += 2;
|
|
1543
|
+
continue;
|
|
1544
|
+
}
|
|
1545
|
+
if (inClass) {
|
|
1546
|
+
if (c2 === "]") inClass = false;
|
|
1547
|
+
i++;
|
|
1548
|
+
continue;
|
|
1549
|
+
}
|
|
1550
|
+
if (c2 === "[") {
|
|
1551
|
+
inClass = true;
|
|
1552
|
+
i++;
|
|
1553
|
+
continue;
|
|
1554
|
+
}
|
|
1555
|
+
if (c2 === "/") {
|
|
1556
|
+
i++;
|
|
1557
|
+
break;
|
|
1558
|
+
}
|
|
1559
|
+
if (c2 === "\n") break;
|
|
1560
|
+
i++;
|
|
1561
|
+
}
|
|
1562
|
+
while (i < index && /[a-z]/.test(src[i])) i++;
|
|
1563
|
+
continue;
|
|
1564
|
+
}
|
|
1164
1565
|
if (ch === "{") depth++;
|
|
1165
1566
|
else if (ch === "}") depth--;
|
|
1166
1567
|
i++;
|
|
@@ -1171,8 +1572,410 @@ function autoCall(expr) {
|
|
|
1171
1572
|
const e = expr.trim();
|
|
1172
1573
|
return /^[A-Za-z_$][\w$]*$/.test(e) ? `${e}()` : e;
|
|
1173
1574
|
}
|
|
1575
|
+
var DEFER_ENABLED = true;
|
|
1576
|
+
function expandKeyBlocks(template, filePath) {
|
|
1577
|
+
if (!template.includes("{#key")) return template;
|
|
1578
|
+
for (let pass = 0; pass < 10; pass++) {
|
|
1579
|
+
const OPEN_RE = /\{#key\s+([^}]+)\}/g;
|
|
1580
|
+
OPEN_RE.lastIndex = 0;
|
|
1581
|
+
const openM = OPEN_RE.exec(template);
|
|
1582
|
+
if (!openM) return template;
|
|
1583
|
+
const expr = openM[1].trim();
|
|
1584
|
+
const bodyStart = openM.index + openM[0].length;
|
|
1585
|
+
const TOK_RE = /\{[#\/](?:key|if|each|boundary|island)\b[^}]*\}/g;
|
|
1586
|
+
TOK_RE.lastIndex = bodyStart;
|
|
1587
|
+
let depth = 1;
|
|
1588
|
+
let closeAt = -1;
|
|
1589
|
+
let tm;
|
|
1590
|
+
while (tm = TOK_RE.exec(template)) {
|
|
1591
|
+
if (tm[0].startsWith("{#")) {
|
|
1592
|
+
depth++;
|
|
1593
|
+
continue;
|
|
1594
|
+
}
|
|
1595
|
+
depth--;
|
|
1596
|
+
if (depth === 0) {
|
|
1597
|
+
closeAt = tm.index;
|
|
1598
|
+
break;
|
|
1599
|
+
}
|
|
1600
|
+
}
|
|
1601
|
+
if (closeAt < 0) {
|
|
1602
|
+
throw new RoseError(
|
|
1603
|
+
"E-TEMPLATE",
|
|
1604
|
+
`${filePath}: {#key ${expr}} is never closed`,
|
|
1605
|
+
{ hint: "every {#key} needs its {/key}" }
|
|
1606
|
+
);
|
|
1607
|
+
}
|
|
1608
|
+
template = template.slice(0, openM.index) + `{#each [${expr}] as __rvkv}` + template.slice(bodyStart, closeAt) + "{/each}" + template.slice(closeAt + "{/key}".length);
|
|
1609
|
+
}
|
|
1610
|
+
return template;
|
|
1611
|
+
}
|
|
1612
|
+
function expandIfElseOnce(template) {
|
|
1613
|
+
const TOK_RE = /\{#(?:if|each|boundary|island)\b[^}]*\}|\{\/(?:if|each|boundary|island)\s*\}|\{:else(?:\s+if\s+[^}]*)?\}/g;
|
|
1614
|
+
let out = "";
|
|
1615
|
+
let pos = 0;
|
|
1616
|
+
let changed = false;
|
|
1617
|
+
for (; ; ) {
|
|
1618
|
+
const openM = /\{#(if|each)\s+([^}]+)\}/g.exec(template.slice(pos));
|
|
1619
|
+
if (!openM) {
|
|
1620
|
+
out += template.slice(pos);
|
|
1621
|
+
break;
|
|
1622
|
+
}
|
|
1623
|
+
const kind = openM[1];
|
|
1624
|
+
const head = openM[2];
|
|
1625
|
+
const start = pos + openM.index;
|
|
1626
|
+
const cond = kind === "if" ? head.trim() : "";
|
|
1627
|
+
const bodyStart = start + openM[0].length;
|
|
1628
|
+
out += template.slice(pos, start);
|
|
1629
|
+
TOK_RE.lastIndex = bodyStart;
|
|
1630
|
+
let depth = 1;
|
|
1631
|
+
let closeAt = -1;
|
|
1632
|
+
let closeLen = 0;
|
|
1633
|
+
const elses = [];
|
|
1634
|
+
let tm;
|
|
1635
|
+
while (tm = TOK_RE.exec(template)) {
|
|
1636
|
+
const tok = tm[0];
|
|
1637
|
+
if (tok.startsWith("{:else")) {
|
|
1638
|
+
if (depth === 1) {
|
|
1639
|
+
const condM = /^\{:else\s+if\s+([^}]*)\}$/.exec(tok);
|
|
1640
|
+
elses.push({ at: tm.index, len: tok.length, cond: condM ? condM[1].trim() : null });
|
|
1641
|
+
}
|
|
1642
|
+
continue;
|
|
1643
|
+
}
|
|
1644
|
+
if (tok.startsWith("{#")) {
|
|
1645
|
+
depth++;
|
|
1646
|
+
continue;
|
|
1647
|
+
}
|
|
1648
|
+
depth--;
|
|
1649
|
+
if (depth === 0) {
|
|
1650
|
+
closeAt = tm.index;
|
|
1651
|
+
closeLen = tok.length;
|
|
1652
|
+
break;
|
|
1653
|
+
}
|
|
1654
|
+
}
|
|
1655
|
+
if (closeAt < 0 || elses.length === 0) {
|
|
1656
|
+
out += template.slice(start, closeAt < 0 ? template.length : closeAt + closeLen);
|
|
1657
|
+
if (closeAt < 0) break;
|
|
1658
|
+
pos = closeAt + closeLen;
|
|
1659
|
+
continue;
|
|
1660
|
+
}
|
|
1661
|
+
const body = template.slice(bodyStart, closeAt);
|
|
1662
|
+
if (kind === "each") {
|
|
1663
|
+
const lastBare = [...elses].reverse().find((e) => e.cond === null);
|
|
1664
|
+
if (!lastBare) {
|
|
1665
|
+
out += template.slice(start, closeAt + closeLen);
|
|
1666
|
+
pos = closeAt + closeLen;
|
|
1667
|
+
continue;
|
|
1668
|
+
}
|
|
1669
|
+
const relLast = lastBare.at - bodyStart;
|
|
1670
|
+
const eachBody = body.slice(0, relLast);
|
|
1671
|
+
const elseBody = body.slice(relLast + lastBare.len);
|
|
1672
|
+
const itemsExpr = head.replace(/\s+as\s+[\w,\s]*$/, "").trim();
|
|
1673
|
+
out += template.slice(start, bodyStart) + eachBody + `{/each}{#if !(${itemsExpr}.length)}${elseBody}{/if}`;
|
|
1674
|
+
pos = closeAt + closeLen;
|
|
1675
|
+
changed = true;
|
|
1676
|
+
continue;
|
|
1677
|
+
}
|
|
1678
|
+
const branches = [];
|
|
1679
|
+
let cursor = 0;
|
|
1680
|
+
for (let i = 0; i < elses.length; i++) {
|
|
1681
|
+
const e = elses[i];
|
|
1682
|
+
const rel = e.at - bodyStart;
|
|
1683
|
+
branches.push({ cond: i === 0 ? null : elses[i - 1].cond, body: body.slice(cursor, rel) });
|
|
1684
|
+
cursor = rel + e.len;
|
|
1685
|
+
}
|
|
1686
|
+
branches.push({ cond: elses[elses.length - 1].cond, body: body.slice(cursor) });
|
|
1687
|
+
const first = branches.shift();
|
|
1688
|
+
const build2 = (bs) => {
|
|
1689
|
+
if (!bs.length) return "";
|
|
1690
|
+
const head2 = bs[0];
|
|
1691
|
+
const rest = bs.slice(1);
|
|
1692
|
+
if (head2.cond == null) return head2.body;
|
|
1693
|
+
let s = `{#if ${head2.cond}}${head2.body}{/if}`;
|
|
1694
|
+
if (rest.length) s += `{#if !(${head2.cond})}` + build2(rest) + `{/if}`;
|
|
1695
|
+
return s;
|
|
1696
|
+
};
|
|
1697
|
+
let emitted = `{#if ${cond}}${first.body}{/if}`;
|
|
1698
|
+
if (branches.length) emitted += `{#if !(${cond})}` + build2(branches) + `{/if}`;
|
|
1699
|
+
out += emitted;
|
|
1700
|
+
pos = closeAt + closeLen;
|
|
1701
|
+
changed = true;
|
|
1702
|
+
}
|
|
1703
|
+
return { template: out, changed };
|
|
1704
|
+
}
|
|
1705
|
+
function expandClassDirectives(template, filePath) {
|
|
1706
|
+
if (!template.includes("class:")) return template;
|
|
1707
|
+
const TAG_RE = /<([a-zA-Z][^\s>/]*)((?:[^>"']|"[^"]*"|'[^']*')*?)(\/?)>/g;
|
|
1708
|
+
let out = "";
|
|
1709
|
+
let pos = 0;
|
|
1710
|
+
let m;
|
|
1711
|
+
TAG_RE.lastIndex = 0;
|
|
1712
|
+
while (m = TAG_RE.exec(template)) {
|
|
1713
|
+
const [whole, tag, attrs, selfClose] = m;
|
|
1714
|
+
if (!attrs.includes("class:")) continue;
|
|
1715
|
+
const pairs = [];
|
|
1716
|
+
const NAME_RE = /\sclass:([\w-]+)\s*=\s*\{/g;
|
|
1717
|
+
let nm;
|
|
1718
|
+
while (nm = NAME_RE.exec(attrs)) {
|
|
1719
|
+
let i = nm.index + nm[0].length;
|
|
1720
|
+
let depth = 1;
|
|
1721
|
+
while (i < attrs.length && depth > 0) {
|
|
1722
|
+
const ch = attrs[i];
|
|
1723
|
+
if (ch === '"' || ch === "'") {
|
|
1724
|
+
i = skipQuoted(attrs, i);
|
|
1725
|
+
continue;
|
|
1726
|
+
}
|
|
1727
|
+
if (ch === "{") depth++;
|
|
1728
|
+
else if (ch === "}") depth--;
|
|
1729
|
+
i++;
|
|
1730
|
+
}
|
|
1731
|
+
if (depth !== 0) {
|
|
1732
|
+
throw new RoseError("E-TEMPLATE", `${filePath}: class:${nm[1]}={...} is missing its closing brace`, { file: filePath, hint: "the binding expression needs a matching } before the tag ends" });
|
|
1733
|
+
}
|
|
1734
|
+
pairs.push({ name: nm[1], expr: attrs.slice(nm.index + nm[0].length, i - 1), start: nm.index, end: i });
|
|
1735
|
+
}
|
|
1736
|
+
const clsRe = /(\sclass\s*=\s*)("([^"]*)"|'([^']*)'|\{[^}]*\})/;
|
|
1737
|
+
const clsM = clsRe.exec(attrs);
|
|
1738
|
+
if (clsM && clsM[2].startsWith("{")) {
|
|
1739
|
+
throw new RoseError("E-TEMPLATE", `${filePath}: <${tag}> has both class={...} and class: directives`, { file: filePath, hint: 'merge them: move the dynamic part into a class:NAME={expr} and keep the rest in class="..."' });
|
|
1740
|
+
}
|
|
1741
|
+
const staticCls = clsM ? clsM[3] ?? clsM[4] ?? "" : "";
|
|
1742
|
+
let closure = `(${JSON.stringify(staticCls)}`;
|
|
1743
|
+
for (const p of pairs) {
|
|
1744
|
+
closure += `+((${p.expr})?${JSON.stringify(" " + p.name)}:'')`;
|
|
1745
|
+
}
|
|
1746
|
+
closure += `)`;
|
|
1747
|
+
let newAttrs = attrs;
|
|
1748
|
+
for (let k = pairs.length - 1; k >= 0; k--) {
|
|
1749
|
+
newAttrs = newAttrs.slice(0, pairs[k].start) + newAttrs.slice(pairs[k].end);
|
|
1750
|
+
}
|
|
1751
|
+
if (clsM) {
|
|
1752
|
+
newAttrs = newAttrs.replace(clsRe, ` class={${closure}}`);
|
|
1753
|
+
} else {
|
|
1754
|
+
newAttrs = ` class={${closure}}` + newAttrs;
|
|
1755
|
+
}
|
|
1756
|
+
out += template.slice(pos, m.index) + `<${tag}${newAttrs}${selfClose}>`;
|
|
1757
|
+
pos = m.index + whole.length;
|
|
1758
|
+
}
|
|
1759
|
+
if (pos === 0) return template;
|
|
1760
|
+
out += template.slice(pos);
|
|
1761
|
+
return out;
|
|
1762
|
+
}
|
|
1763
|
+
function expandStyleDirectives(template, filePath) {
|
|
1764
|
+
if (!template.includes("style:")) return template;
|
|
1765
|
+
const TAG_RE = /<([a-zA-Z][^\s>/]*)((?:[^>"']|"[^"]*"|'[^']*')*?)(\/?)>/g;
|
|
1766
|
+
let out = "";
|
|
1767
|
+
let pos = 0;
|
|
1768
|
+
let m;
|
|
1769
|
+
TAG_RE.lastIndex = 0;
|
|
1770
|
+
while (m = TAG_RE.exec(template)) {
|
|
1771
|
+
const [whole, tag, attrs, selfClose] = m;
|
|
1772
|
+
if (!attrs.includes("style:")) continue;
|
|
1773
|
+
const pairs = [];
|
|
1774
|
+
const NAME_RE = /\sstyle:([\w-]+)\s*=\s*\{/g;
|
|
1775
|
+
let nm;
|
|
1776
|
+
while (nm = NAME_RE.exec(attrs)) {
|
|
1777
|
+
let i = nm.index + nm[0].length;
|
|
1778
|
+
let depth = 1;
|
|
1779
|
+
while (i < attrs.length && depth > 0) {
|
|
1780
|
+
const ch = attrs[i];
|
|
1781
|
+
if (ch === '"' || ch === "'") {
|
|
1782
|
+
i = skipQuoted(attrs, i);
|
|
1783
|
+
continue;
|
|
1784
|
+
}
|
|
1785
|
+
if (ch === "{") depth++;
|
|
1786
|
+
else if (ch === "}") depth--;
|
|
1787
|
+
i++;
|
|
1788
|
+
}
|
|
1789
|
+
if (depth !== 0) {
|
|
1790
|
+
throw new RoseError("E-TEMPLATE", `${filePath}: style:${nm[1]}={...} is missing its closing brace`, { file: filePath, hint: "the binding expression needs a matching } before the tag ends" });
|
|
1791
|
+
}
|
|
1792
|
+
pairs.push({ prop: nm[1], expr: attrs.slice(nm.index + nm[0].length, i - 1), start: nm.index, end: i });
|
|
1793
|
+
}
|
|
1794
|
+
const styleRe = /(\sstyle\s*=\s*)("([^"]*)"|'([^']*)'|\{[^}]*\})/;
|
|
1795
|
+
const stM = styleRe.exec(attrs);
|
|
1796
|
+
if (stM && stM[2].startsWith("{")) {
|
|
1797
|
+
throw new RoseError("E-TEMPLATE", `${filePath}: <${tag}> has both style={...} and style: directives`, { file: filePath, hint: 'keep the static declarations in style="..." and move the dynamic ones to style:PROP={expr}' });
|
|
1798
|
+
}
|
|
1799
|
+
const staticStyle = stM ? stM[3] ?? stM[4] ?? "" : "";
|
|
1800
|
+
let closure = `${JSON.stringify(staticStyle.endsWith(";") || staticStyle === "" ? staticStyle : staticStyle + ";")}`;
|
|
1801
|
+
for (const p of pairs) {
|
|
1802
|
+
closure += `+${JSON.stringify(p.prop + ":")}+(${p.expr})+';'`;
|
|
1803
|
+
}
|
|
1804
|
+
let newAttrs = attrs;
|
|
1805
|
+
for (let k = pairs.length - 1; k >= 0; k--) {
|
|
1806
|
+
newAttrs = newAttrs.slice(0, pairs[k].start) + newAttrs.slice(pairs[k].end);
|
|
1807
|
+
}
|
|
1808
|
+
if (stM) {
|
|
1809
|
+
newAttrs = newAttrs.replace(styleRe, ` style={${closure}}`);
|
|
1810
|
+
} else {
|
|
1811
|
+
newAttrs = ` style={${closure}}` + newAttrs;
|
|
1812
|
+
}
|
|
1813
|
+
out += template.slice(pos, m.index) + `<${tag}${newAttrs}${selfClose}>`;
|
|
1814
|
+
pos = m.index + whole.length;
|
|
1815
|
+
}
|
|
1816
|
+
if (pos === 0) return template;
|
|
1817
|
+
out += template.slice(pos);
|
|
1818
|
+
return out;
|
|
1819
|
+
}
|
|
1820
|
+
function expandBoundaryFallbacks(template, filePath) {
|
|
1821
|
+
if (!template.includes("{:fallback")) return template;
|
|
1822
|
+
for (let pass = 0; pass < 10; pass++) {
|
|
1823
|
+
const TOK_RE = /\{#boundary\}|\{\/boundary\}|\{:fallback\}/g;
|
|
1824
|
+
let out = "";
|
|
1825
|
+
let pos = 0;
|
|
1826
|
+
let changed = false;
|
|
1827
|
+
let tm;
|
|
1828
|
+
while (tm = TOK_RE.exec(template)) {
|
|
1829
|
+
if (tm[0] !== "{#boundary}") continue;
|
|
1830
|
+
const start = tm.index;
|
|
1831
|
+
const bodyStart = start + tm[0].length;
|
|
1832
|
+
let depth = 1;
|
|
1833
|
+
let closeAt = -1;
|
|
1834
|
+
let tm2;
|
|
1835
|
+
while (tm2 = TOK_RE.exec(template)) {
|
|
1836
|
+
if (tm2[0] === "{#boundary}") {
|
|
1837
|
+
depth++;
|
|
1838
|
+
continue;
|
|
1839
|
+
}
|
|
1840
|
+
if (tm2[0] === "{/boundary}") {
|
|
1841
|
+
depth--;
|
|
1842
|
+
if (depth === 0) {
|
|
1843
|
+
closeAt = tm2.index;
|
|
1844
|
+
break;
|
|
1845
|
+
}
|
|
1846
|
+
}
|
|
1847
|
+
}
|
|
1848
|
+
if (closeAt < 0) break;
|
|
1849
|
+
const body = template.slice(bodyStart, closeAt);
|
|
1850
|
+
const BTOK2 = /\{#(boundary|if|each|key|island)(?:\s+[^}]*)?\}|\{\/(?:boundary|if|each|key|island)\s*\}|\{:fallback\}/g;
|
|
1851
|
+
const kindStack = ["boundary"];
|
|
1852
|
+
let d = 1;
|
|
1853
|
+
let fbAt = -1;
|
|
1854
|
+
let fbLen = 0;
|
|
1855
|
+
let tm3;
|
|
1856
|
+
BTOK2.lastIndex = 0;
|
|
1857
|
+
while (tm3 = BTOK2.exec(body)) {
|
|
1858
|
+
const tok = tm3[0];
|
|
1859
|
+
if (tok === "{:fallback}") {
|
|
1860
|
+
const top = kindStack[kindStack.length - 1];
|
|
1861
|
+
if (top !== "boundary") {
|
|
1862
|
+
throw new RoseError(
|
|
1863
|
+
"E-TEMPLATE",
|
|
1864
|
+
`${filePath}: {:fallback} must sit directly inside a {#boundary} block`,
|
|
1865
|
+
{ hint: "move it out of the {#if}/{#each} it sits in, or keep the conditional fallback in the parent" }
|
|
1866
|
+
);
|
|
1867
|
+
}
|
|
1868
|
+
if (fbAt >= 0) {
|
|
1869
|
+
throw new RoseError("E-TEMPLATE", `${filePath}: a {#boundary} can carry only one {:fallback}`, { hint: "remove the extra {:fallback} segment" });
|
|
1870
|
+
}
|
|
1871
|
+
fbAt = tm3.index;
|
|
1872
|
+
fbLen = tok.length;
|
|
1873
|
+
continue;
|
|
1874
|
+
}
|
|
1875
|
+
if (tok.startsWith("{#")) {
|
|
1876
|
+
d++;
|
|
1877
|
+
kindStack.push(tok.slice(2, tok.length - 1).trim().split(/\s/)[0]);
|
|
1878
|
+
continue;
|
|
1879
|
+
}
|
|
1880
|
+
d--;
|
|
1881
|
+
kindStack.pop();
|
|
1882
|
+
}
|
|
1883
|
+
if (fbAt < 0) continue;
|
|
1884
|
+
const custom = body.slice(0, fbAt);
|
|
1885
|
+
const fbMarkup = body.slice(fbAt + fbLen);
|
|
1886
|
+
const b64 = Buffer.from(fbMarkup, "utf-8").toString("base64");
|
|
1887
|
+
out += template.slice(pos, start) + `{#boundary __fb="${b64}"}` + custom + "{/boundary}";
|
|
1888
|
+
pos = closeAt + "{/boundary}".length;
|
|
1889
|
+
changed = true;
|
|
1890
|
+
}
|
|
1891
|
+
if (!changed) break;
|
|
1892
|
+
template = out + template.slice(pos);
|
|
1893
|
+
}
|
|
1894
|
+
return template;
|
|
1895
|
+
}
|
|
1896
|
+
function expandIfElse(template) {
|
|
1897
|
+
for (let pass = 0; pass < 10; pass++) {
|
|
1898
|
+
if (!/\{:else\b/.test(template)) return template;
|
|
1899
|
+
const r = expandIfElseOnce(template);
|
|
1900
|
+
template = r.template;
|
|
1901
|
+
if (!r.changed) return template;
|
|
1902
|
+
}
|
|
1903
|
+
return template;
|
|
1904
|
+
}
|
|
1905
|
+
function expandDeferBlocks(template) {
|
|
1906
|
+
if (!DEFER_ENABLED) {
|
|
1907
|
+
const openRe2 = /\{#defer(?:\s+hold=\\d+)?\}/g;
|
|
1908
|
+
let out2 = "";
|
|
1909
|
+
let dpos = 0;
|
|
1910
|
+
for (; ; ) {
|
|
1911
|
+
openRe2.lastIndex = dpos;
|
|
1912
|
+
const openM = openRe2.exec(template);
|
|
1913
|
+
if (!openM) break;
|
|
1914
|
+
const openAt = openM.index;
|
|
1915
|
+
const openLen = openM[0].length;
|
|
1916
|
+
const closeAt = template.indexOf("{/defer}", openAt + openLen);
|
|
1917
|
+
if (closeAt < 0) break;
|
|
1918
|
+
out2 += template.slice(dpos, openAt) + template.slice(openAt + openLen, closeAt);
|
|
1919
|
+
dpos = closeAt + 8;
|
|
1920
|
+
}
|
|
1921
|
+
return { template: dpos === 0 ? template : out2, count: 0, holds: [] };
|
|
1922
|
+
}
|
|
1923
|
+
let count = 0;
|
|
1924
|
+
const holds = [];
|
|
1925
|
+
let out = "";
|
|
1926
|
+
let pos = 0;
|
|
1927
|
+
const openRe = /\{#defer(?:\s+hold=(\d+))?\}/g;
|
|
1928
|
+
for (; ; ) {
|
|
1929
|
+
openRe.lastIndex = pos;
|
|
1930
|
+
const openM = openRe.exec(template);
|
|
1931
|
+
if (!openM) break;
|
|
1932
|
+
const openAt = openM.index;
|
|
1933
|
+
const openLen = openM[0].length;
|
|
1934
|
+
const hold = openM[1] ? Number(openM[1]) : 0;
|
|
1935
|
+
let depth = 1;
|
|
1936
|
+
let i = openAt + openLen;
|
|
1937
|
+
let closeAt = -1;
|
|
1938
|
+
while (i < template.length) {
|
|
1939
|
+
openRe.lastIndex = i;
|
|
1940
|
+
const nextOpenM = openRe.exec(template);
|
|
1941
|
+
const nextOpen = nextOpenM ? nextOpenM.index : -1;
|
|
1942
|
+
const nextClose = template.indexOf("{/defer}", i);
|
|
1943
|
+
if (nextClose < 0) break;
|
|
1944
|
+
if (nextOpen >= 0 && nextOpen < nextClose) {
|
|
1945
|
+
depth++;
|
|
1946
|
+
i = nextOpen + nextOpenM[0].length;
|
|
1947
|
+
continue;
|
|
1948
|
+
}
|
|
1949
|
+
depth--;
|
|
1950
|
+
if (depth === 0) {
|
|
1951
|
+
closeAt = nextClose;
|
|
1952
|
+
break;
|
|
1953
|
+
}
|
|
1954
|
+
i = nextClose + 8;
|
|
1955
|
+
}
|
|
1956
|
+
if (closeAt < 0) break;
|
|
1957
|
+
const content = template.slice(openAt + openLen, closeAt);
|
|
1958
|
+
holds.push(hold);
|
|
1959
|
+
const n = ++count;
|
|
1960
|
+
out += template.slice(pos, openAt);
|
|
1961
|
+
out += "{#if __rvDefer" + n + "()}" + content + "{/if}\n{#if !__rvDefer" + n + '()}<div class="rv-defer-loading"></div>{/if}';
|
|
1962
|
+
pos = closeAt + 8;
|
|
1963
|
+
}
|
|
1964
|
+
if (count === 0) return { template, count: 0, holds: [] };
|
|
1965
|
+
out += template.slice(pos);
|
|
1966
|
+
return { template: out, count, holds };
|
|
1967
|
+
}
|
|
1968
|
+
function deferBootCode(count, holds = []) {
|
|
1969
|
+
let code = "";
|
|
1970
|
+
for (let n = 1; n <= count; n++) {
|
|
1971
|
+
code += "const [__rvDefer" + n + ", set__rvDefer" + n + '] = state("__rvdefer' + n + '", false);\n';
|
|
1972
|
+
const hold = holds[n - 1] || 0;
|
|
1973
|
+
code += hold > 0 ? "onMount(function () { setTimeout(function () { set__rvDefer" + n + "(true); }, " + hold + "); });\n" : "onMount(function () { requestAnimationFrame(function () { requestAnimationFrame(function () { set__rvDefer" + n + "(true); }); }); });\n";
|
|
1974
|
+
}
|
|
1975
|
+
return code;
|
|
1976
|
+
}
|
|
1174
1977
|
function findBlock(src, kind) {
|
|
1175
|
-
const head = kind === "boundary" ? /\{#boundary
|
|
1978
|
+
const head = kind === "boundary" ? /\{#boundary(?:\s+([^}]*))?\}/g : kind === "if" ? /\{#if\s+([^}]+)\}/g : kind === "island" ? /\{#island(?:\s+name="([^"]*)")?(?:\s+hydrate="([^"]*)")?\s*\}/g : /\{#each\s+([^}]+?)\s+as\s+(\{[^{}]*\}|\[[^[\]]*\]|\w+)(?:\s*,\s*(\w+))?\}/g;
|
|
1176
1979
|
const closeRe = new RegExp(`\\{/${kind}\\}`, "g");
|
|
1177
1980
|
let open;
|
|
1178
1981
|
while (open = head.exec(src)) {
|
|
@@ -1194,7 +1997,7 @@ function findBlock(src, kind) {
|
|
|
1194
1997
|
i = nextClose.index + nextClose[0].length;
|
|
1195
1998
|
if (--depth === 0) {
|
|
1196
1999
|
const content = src.slice(afterOpen, nextClose.index);
|
|
1197
|
-
const groups = kind === "boundary" ? [content] : kind === "if" ? [open[1], content] : [open[1], open[2], content];
|
|
2000
|
+
const groups = kind === "boundary" ? [open[1] ?? "", content] : kind === "island" ? [open[1] ?? "", open[2] ?? "", content] : kind === "if" ? [open[1], content] : [open[1], open[2], open[3] ?? "", content];
|
|
1198
2001
|
const arr = [src.slice(start, i), ...groups];
|
|
1199
2002
|
arr.index = start;
|
|
1200
2003
|
return arr;
|
|
@@ -1237,7 +2040,7 @@ function compileHead(head) {
|
|
|
1237
2040
|
flush();
|
|
1238
2041
|
return out;
|
|
1239
2042
|
}
|
|
1240
|
-
var KNOWN_CLOSERS = /* @__PURE__ */ new Set(["if", "each", "boundary"]);
|
|
2043
|
+
var KNOWN_CLOSERS = /* @__PURE__ */ new Set(["if", "each", "boundary", "island"]);
|
|
1241
2044
|
function assertKnownDirectives(template, filePath) {
|
|
1242
2045
|
const rawRanges = [];
|
|
1243
2046
|
const RAW_OPEN = /<(style|script|noscript)\b[^>]*>/gi;
|
|
@@ -1271,21 +2074,28 @@ function assertKnownDirectives(template, filePath) {
|
|
|
1271
2074
|
if (word === "else") {
|
|
1272
2075
|
throw new RoseError(
|
|
1273
2076
|
"E-TEMPLATE",
|
|
1274
|
-
`${filePath}: {:else}
|
|
1275
|
-
{ file: filePath, line: lineAt(template, m), hint: "
|
|
2077
|
+
`${filePath}: a stray {:else} with no {#if} above it`,
|
|
2078
|
+
{ file: filePath, line: lineAt(template, m), hint: "{:else} / {:else if cond} belong inside an {#if} ... {/if} block - {#if cond}A{:else}B{/if}" }
|
|
2079
|
+
);
|
|
2080
|
+
}
|
|
2081
|
+
if (word === "fallback") {
|
|
2082
|
+
throw new RoseError(
|
|
2083
|
+
"E-TEMPLATE",
|
|
2084
|
+
`${filePath}: a stray {:fallback} with no {#boundary} above it`,
|
|
2085
|
+
{ file: filePath, line: lineAt(template, m), hint: "{:fallback} belongs directly inside a {#boundary} ... {/boundary} block" }
|
|
1276
2086
|
);
|
|
1277
2087
|
}
|
|
1278
2088
|
throw new RoseError(
|
|
1279
2089
|
"E-TEMPLATE",
|
|
1280
2090
|
`${filePath}: {:${word}} is not a rosetack directive`,
|
|
1281
|
-
{ file: filePath, line: lineAt(template, m), hint: "rosetack templates support {#if}, {#each} and {#boundary}
|
|
2091
|
+
{ file: filePath, line: lineAt(template, m), hint: "rosetack templates support {#if}/{:else}, {#each} and {#boundary}" }
|
|
1282
2092
|
);
|
|
1283
2093
|
}
|
|
1284
|
-
const OPENER_RE = /\{#(if|each|boundary)\b([^}]*)\}/g;
|
|
2094
|
+
const OPENER_RE = /\{#(if|each|boundary|island)\b([^}]*)\}/g;
|
|
1285
2095
|
while (m = OPENER_RE.exec(template)) {
|
|
1286
2096
|
if (inRaw(m.index)) continue;
|
|
1287
2097
|
const [, kind, head] = m;
|
|
1288
|
-
if (kind === "each" && !/\bas\s+(\w+)
|
|
2098
|
+
if (kind === "each" && !/\bas\s+(\{[^{}]*\}?|\[[^[\]]*\]?|\w+)(?:\s*,\s*\w+)?\s*$/.test(head)) {
|
|
1289
2099
|
throw new RoseError(
|
|
1290
2100
|
"E-TEMPLATE",
|
|
1291
2101
|
`${filePath}: {#each ${head.trim()}} is missing its item name`,
|
|
@@ -1339,10 +2149,12 @@ function rewriteQuotedExprAttrs(template, comps) {
|
|
|
1339
2149
|
return `<${name}${rewritten}${selfClose ? " /" : ""}>`;
|
|
1340
2150
|
});
|
|
1341
2151
|
}
|
|
1342
|
-
function compileTemplate(template, acc, closes, scope, depth, markers = true, comps = /* @__PURE__ */ new Map()) {
|
|
2152
|
+
function compileTemplate(template, acc, closes, scope, depth, markers = true, comps = /* @__PURE__ */ new Map(), islandDepth = 0) {
|
|
1343
2153
|
let result = "";
|
|
1344
2154
|
let remaining = template;
|
|
1345
2155
|
let blockId = 0;
|
|
2156
|
+
const islandsMode = /\{#island\b/.test(template);
|
|
2157
|
+
const effMarkers = markers && (!islandsMode || islandDepth > 0);
|
|
1346
2158
|
const nextId = () => `${depth}_${blockId++}`;
|
|
1347
2159
|
while (remaining.length > 0) {
|
|
1348
2160
|
const ifMatch = findBlock(remaining, "if");
|
|
@@ -1351,10 +2163,12 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
|
|
|
1351
2163
|
const firstExpr = templateExprSpans(remaining)[0];
|
|
1352
2164
|
const exprMatch = firstExpr ? Object.assign([remaining.slice(firstExpr.start, firstExpr.end + 1), firstExpr.expr], { index: firstExpr.start }) : null;
|
|
1353
2165
|
const compTag = comps.size > 0 ? findCompTag(remaining, comps) : null;
|
|
2166
|
+
const islandMatch = findBlock(remaining, "island");
|
|
1354
2167
|
const candidates = [];
|
|
1355
2168
|
if (ifMatch?.index !== void 0) candidates.push({ type: "if", match: ifMatch, index: ifMatch.index });
|
|
1356
2169
|
if (eachMatch?.index !== void 0) candidates.push({ type: "each", match: eachMatch, index: eachMatch.index });
|
|
1357
2170
|
if (boundaryMatch?.index !== void 0) candidates.push({ type: "boundary", match: boundaryMatch, index: boundaryMatch.index });
|
|
2171
|
+
if (islandMatch?.index !== void 0) candidates.push({ type: "island", match: islandMatch, index: islandMatch.index });
|
|
1358
2172
|
if (exprMatch?.index !== void 0) candidates.push({ type: "expr", match: exprMatch, index: exprMatch.index });
|
|
1359
2173
|
if (compTag) candidates.push({ type: "comp", match: exprMatch, index: compTag.start, tag: compTag });
|
|
1360
2174
|
const earliest = candidates.length > 0 ? candidates.reduce((a, b) => a.index <= b.index ? a : b) : null;
|
|
@@ -1388,10 +2202,10 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
|
|
|
1388
2202
|
const call = autoCall(cond);
|
|
1389
2203
|
const id = nextId();
|
|
1390
2204
|
const innerScope = scope ?? "__s";
|
|
1391
|
-
const inner = compileTemplate(content.trim(), "h", "__c", innerScope, depth + 1,
|
|
2205
|
+
const inner = compileTemplate(content.trim(), "h", "__c", innerScope, depth + 1, effMarkers, comps, islandDepth);
|
|
1392
2206
|
result += `const __b${id} = (__s, __c) => { let h = ''; ${inner} return h; };
|
|
1393
2207
|
`;
|
|
1394
|
-
if (
|
|
2208
|
+
if (effMarkers) {
|
|
1395
2209
|
result += `${acc} += ifMark(${closes}, () => (${call}), __b${id}${scope ? `, ${scope}` : ""});
|
|
1396
2210
|
`;
|
|
1397
2211
|
} else {
|
|
@@ -1400,43 +2214,62 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
|
|
|
1400
2214
|
}
|
|
1401
2215
|
remaining = remaining.substring(earliest.index + earliest.match[0].length);
|
|
1402
2216
|
} else if (earliest.type === "each") {
|
|
1403
|
-
const [, items, item, content] = earliest.match;
|
|
2217
|
+
const [, items, item, index, content] = earliest.match;
|
|
1404
2218
|
const before = remaining.substring(0, earliest.index);
|
|
1405
2219
|
if (before) result += emitChunk(before, acc, closes, scope);
|
|
1406
2220
|
const call = autoCall(items);
|
|
1407
2221
|
const id = nextId();
|
|
1408
|
-
const
|
|
2222
|
+
const isDestructure = /^[{[]/.test(item);
|
|
2223
|
+
const itemRe = isDestructure ? null : new RegExp(`\\b${item}\\b`, "g");
|
|
2224
|
+
const indexRe = index ? new RegExp(`\\b${index}\\b`, "g") : null;
|
|
1409
2225
|
let scoped = "";
|
|
1410
2226
|
let lastSpan = 0;
|
|
1411
2227
|
for (const s of templateExprSpans(content.trim())) {
|
|
1412
|
-
|
|
2228
|
+
let expr = itemRe ? s.expr.replace(itemRe, "__s") : s.expr;
|
|
2229
|
+
if (indexRe) expr = expr.replace(indexRe, "__i");
|
|
2230
|
+
scoped += content.trim().slice(lastSpan, s.start) + "{" + expr + "}";
|
|
1413
2231
|
lastSpan = s.end + 1;
|
|
1414
2232
|
}
|
|
1415
2233
|
scoped += content.trim().slice(lastSpan);
|
|
1416
|
-
const inner = compileTemplate(scoped, "h", "__c", "__s", depth + 1,
|
|
1417
|
-
|
|
2234
|
+
const inner = compileTemplate(scoped, "h", "__c", "__s", depth + 1, effMarkers, comps, islandDepth);
|
|
2235
|
+
const body = isDestructure ? `const ${item} = __s; ${inner}` : inner;
|
|
2236
|
+
result += `const __b${id} = (__s, __c${index ? ", __i" : ""}) => { let h = ''; ${body} return h; };
|
|
1418
2237
|
`;
|
|
1419
|
-
if (
|
|
2238
|
+
if (effMarkers) {
|
|
1420
2239
|
result += `${acc} += eachMark(${closes}, () => (${call}), __b${id});
|
|
1421
2240
|
`;
|
|
1422
2241
|
} else {
|
|
1423
|
-
|
|
2242
|
+
const param = isDestructure ? "__s" : item;
|
|
2243
|
+
result += `${acc} += (${call}).map((${param}${index ? ", __i" : ""}) => __b${id}(${param}, []${index ? ", __i" : ""}))).join('');
|
|
1424
2244
|
`;
|
|
1425
2245
|
}
|
|
1426
2246
|
remaining = remaining.substring(earliest.index + earliest.match[0].length);
|
|
1427
2247
|
} else if (earliest.type === "boundary") {
|
|
1428
|
-
const [, content] = earliest.match;
|
|
2248
|
+
const [, fbAttr, content] = earliest.match;
|
|
2249
|
+
let fallbackSrc = "";
|
|
2250
|
+
if (fbAttr) {
|
|
2251
|
+
const fbM = /__fb="([A-Za-z0-9+/=]*)"/.exec(fbAttr);
|
|
2252
|
+
if (fbM) fallbackSrc = Buffer.from(fbM[1], "base64").toString("utf-8");
|
|
2253
|
+
}
|
|
2254
|
+
const custom = content;
|
|
1429
2255
|
const before = remaining.substring(0, earliest.index);
|
|
1430
2256
|
if (before) result += emitChunk(before, acc, closes, scope);
|
|
1431
2257
|
const id = nextId();
|
|
1432
|
-
const catchesAction = /\$action:|<form[\s>]/.test(
|
|
1433
|
-
const inner = compileTemplate(
|
|
2258
|
+
const catchesAction = /\$action:|<form[\s>]/.test(custom);
|
|
2259
|
+
const inner = compileTemplate(custom.trim(), "h", closes, scope, depth + 1, effMarkers, comps, islandDepth);
|
|
1434
2260
|
result += `const __b${id} = (__c) => { let h = ''; ${inner} return h; };
|
|
1435
2261
|
`;
|
|
2262
|
+
let fbBlock = "";
|
|
2263
|
+
if (fallbackSrc.trim()) {
|
|
2264
|
+
const fbInner = compileTemplate(fallbackSrc.trim(), "h", closes, scope, depth + 1, effMarkers, comps, islandDepth);
|
|
2265
|
+
fbBlock = `const __bf${id} = (__c) => { let h = ''; ${fbInner} return h; };
|
|
2266
|
+
`;
|
|
2267
|
+
}
|
|
2268
|
+
result += fbBlock;
|
|
1436
2269
|
result += `let __bd${id} = '';
|
|
1437
2270
|
`;
|
|
1438
|
-
result += catchesAction ? `try { $actionErrorOrThrow(); __bd${id} = __b${id}(${closes}); } catch (e) { __bd${id} = $boundaryFallback(e); }
|
|
1439
|
-
` : `try { __bd${id} = __b${id}(${closes}); } catch { __bd${id} = ${JSON.stringify(BOUNDARY_FALLBACK)}; }
|
|
2271
|
+
result += catchesAction ? `try { $actionErrorOrThrow(); __bd${id} = __b${id}(${closes}); } catch (e) { $setBoundaryError(e); __bd${id} = ${fbBlock ? `__bf${id}(${closes})` : "$boundaryFallback(e)"}; }
|
|
2272
|
+
` : `try { __bd${id} = __b${id}(${closes}); } catch (e) { $setBoundaryError(e); __bd${id} = ${fbBlock ? `__bf${id}(${closes})` : JSON.stringify(BOUNDARY_FALLBACK)}; }
|
|
1440
2273
|
`;
|
|
1441
2274
|
result += `${acc} += __bd${id};
|
|
1442
2275
|
`;
|
|
@@ -1459,7 +2292,7 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
|
|
|
1459
2292
|
const { def, named } = splitSlots(childrenSrc);
|
|
1460
2293
|
const hasChildren = def.trim().length > 0;
|
|
1461
2294
|
if (hasChildren) {
|
|
1462
|
-
result += `const __ch${id} = (__s, __c) => { let h = ''; ${compileTemplate(def, "h", "__c", scope, depth + 1,
|
|
2295
|
+
result += `const __ch${id} = (__s, __c) => { let h = ''; ${compileTemplate(def, "h", "__c", scope, depth + 1, effMarkers, comps, islandDepth)} return h; };
|
|
1463
2296
|
`;
|
|
1464
2297
|
}
|
|
1465
2298
|
const slotFns = named.map(([nm, src]) => {
|
|
@@ -1475,9 +2308,10 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
|
|
|
1475
2308
|
}
|
|
1476
2309
|
content = out + content.slice(lastSpan);
|
|
1477
2310
|
}
|
|
1478
|
-
return `${JSON.stringify(nm)}: (__s, __c) => { let h = ''; ${compileTemplate(content, "h", "__c", "__s", depth + 1,
|
|
2311
|
+
return `${JSON.stringify(nm)}: (__s, __c) => { let h = ''; ${compileTemplate(content, "h", "__c", "__s", depth + 1, effMarkers, comps, islandDepth)} return h; }`;
|
|
1479
2312
|
});
|
|
1480
2313
|
const propsObj = parseCompAttrs(tag.attrs).filter((a) => a.name !== "slot").map((a) => {
|
|
2314
|
+
if (a.kind === "spread") return `...(${a.value})`;
|
|
1481
2315
|
const key = a.name.startsWith("on:") ? `on${capitalize(a.name.slice(3))}` : a.name;
|
|
1482
2316
|
const val = a.kind === "expr" ? `(${a.value})` : a.kind === "str" ? JSON.stringify(a.value) : "true";
|
|
1483
2317
|
return `${JSON.stringify(key)}: ${val}`;
|
|
@@ -1486,20 +2320,49 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
|
|
|
1486
2320
|
result += `${acc} += ${tag.name}(${closes}, ${childrenArg}, { ${propsObj} }, { ${slotFns.join(", ")} });
|
|
1487
2321
|
`;
|
|
1488
2322
|
remaining = rest;
|
|
2323
|
+
} else if (earliest.type === "island") {
|
|
2324
|
+
const [, name, hydrate, content] = earliest.match;
|
|
2325
|
+
const before = remaining.substring(0, earliest.index);
|
|
2326
|
+
if (before) result += emitChunk(before, acc, closes, scope);
|
|
2327
|
+
const hydrateAttr = hydrate === "visible" || hydrate === "idle" ? ` data-rv-island-hydrate="${hydrate}"` : "";
|
|
2328
|
+
result += `${acc} += ${JSON.stringify(`<div data-rv-island="${name || ""}"${hydrateAttr}>`)};
|
|
2329
|
+
`;
|
|
2330
|
+
const inner = compileTemplate(content.trim(), "h", "__c", scope, depth + 1, markers, comps, islandDepth + 1);
|
|
2331
|
+
result += inner;
|
|
2332
|
+
result += `${acc} += '</div>';
|
|
2333
|
+
`;
|
|
2334
|
+
remaining = remaining.substring(earliest.index + earliest.match[0].length);
|
|
1489
2335
|
} else {
|
|
1490
2336
|
const [, expr] = earliest.match;
|
|
1491
2337
|
const trimmed = expr.trim();
|
|
1492
2338
|
const before = remaining.substring(0, earliest.index);
|
|
2339
|
+
const constMatch = /^@const\s+([A-Za-z_$][\w$]*)\s*=\s*([\s\S]+)$/.exec(trimmed);
|
|
2340
|
+
if (constMatch) {
|
|
2341
|
+
if (before) result += emitChunk(before, acc, closes, scope);
|
|
2342
|
+
result += `const ${constMatch[1]} = (${constMatch[2].trim()});
|
|
2343
|
+
`;
|
|
2344
|
+
remaining = remaining.substring(earliest.index + earliest.match[0].length);
|
|
2345
|
+
continue;
|
|
2346
|
+
}
|
|
1493
2347
|
if (trimmed === "__slot__") {
|
|
1494
2348
|
if (before) result += emitChunk(before, acc, closes, scope);
|
|
1495
2349
|
result += compileSlot(acc);
|
|
1496
2350
|
remaining = remaining.substring(earliest.index + earliest.match[0].length);
|
|
1497
2351
|
continue;
|
|
1498
2352
|
}
|
|
1499
|
-
const
|
|
2353
|
+
const slotDefault = /^__slotDefault\(("(?:[^"\\]|\\.)*")\)$/.exec(trimmed);
|
|
2354
|
+
if (slotDefault) {
|
|
2355
|
+
if (before) result += emitChunk(before, acc, closes, scope);
|
|
2356
|
+
result += `${acc} += __slotDefault(children, ${slotDefault[1]});
|
|
2357
|
+
`;
|
|
2358
|
+
remaining = remaining.substring(earliest.index + earliest.match[0].length);
|
|
2359
|
+
continue;
|
|
2360
|
+
}
|
|
2361
|
+
const slotCall = /^__slot\((['"])(\w+)\1, \[([\s\S]*?)\](?:,\s*("(?:[^"\\]|\\.)*"))?\)$/.exec(trimmed);
|
|
1500
2362
|
if (slotCall) {
|
|
1501
2363
|
if (before) result += emitChunk(before, acc, closes, scope);
|
|
1502
|
-
|
|
2364
|
+
const fb = slotCall[4] ? `, ${slotCall[4]}` : "";
|
|
2365
|
+
result += `${acc} += __slotBlock(${closes}, __sl, ${JSON.stringify(slotCall[2])}, [${slotCall[3]}]${fb});
|
|
1503
2366
|
`;
|
|
1504
2367
|
remaining = remaining.substring(earliest.index + earliest.match[0].length);
|
|
1505
2368
|
continue;
|
|
@@ -1508,7 +2371,7 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
|
|
|
1508
2371
|
if (rawMatch) {
|
|
1509
2372
|
if (before) result += emitChunk(before, acc, closes, scope);
|
|
1510
2373
|
const expr2 = rawMatch[1].trim();
|
|
1511
|
-
if (!
|
|
2374
|
+
if (!effMarkers) {
|
|
1512
2375
|
result += `${acc} += String(${expr2} ?? '');
|
|
1513
2376
|
`;
|
|
1514
2377
|
} else {
|
|
@@ -1523,12 +2386,12 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
|
|
|
1523
2386
|
if (attrMatch) {
|
|
1524
2387
|
const lit = before.slice(0, before.length - attrMatch[0].length);
|
|
1525
2388
|
if (lit) result += emitChunk(lit, acc, closes, scope);
|
|
1526
|
-
result += emitAttr(attrMatch[1], trimmed, acc, closes, scope,
|
|
2389
|
+
result += emitAttr(attrMatch[1], trimmed, acc, closes, scope, effMarkers);
|
|
1527
2390
|
} else {
|
|
1528
2391
|
if (before) result += emitChunk(before, acc, closes, scope);
|
|
1529
2392
|
const after = remaining.substring(earliest.index + earliest.match[0].length);
|
|
1530
2393
|
const pair = after.length > 0 && !/^<[a-zA-Z/!]/.test(after) && !after.startsWith("{");
|
|
1531
|
-
result += emitText(trimmed, acc, closes, scope,
|
|
2394
|
+
result += emitText(trimmed, acc, closes, scope, effMarkers, pair);
|
|
1532
2395
|
}
|
|
1533
2396
|
remaining = remaining.substring(earliest.index + earliest.match[0].length);
|
|
1534
2397
|
}
|
|
@@ -1588,6 +2451,12 @@ function parseCompAttrs(attrs) {
|
|
|
1588
2451
|
const out = [];
|
|
1589
2452
|
let i = 0;
|
|
1590
2453
|
while (i < attrs.length) {
|
|
2454
|
+
const spread = /^\s*\{\.\.\.([^}]*)\}/.exec(attrs.slice(i));
|
|
2455
|
+
if (spread) {
|
|
2456
|
+
out.push({ name: "...", kind: "spread", value: spread[1].trim() });
|
|
2457
|
+
i += spread[0].length;
|
|
2458
|
+
continue;
|
|
2459
|
+
}
|
|
1591
2460
|
const nm = /^\s*([\w:.-]+)/.exec(attrs.slice(i));
|
|
1592
2461
|
if (!nm) break;
|
|
1593
2462
|
i += nm[0].length;
|
|
@@ -1725,22 +2594,55 @@ var IMG_MIME = {
|
|
|
1725
2594
|
".ico": "image/x-icon"
|
|
1726
2595
|
};
|
|
1727
2596
|
var INLINE_IMG_MAX = 4096;
|
|
2597
|
+
function listImageVariants(publicDir, url) {
|
|
2598
|
+
const ext = path2.extname(url);
|
|
2599
|
+
const base = path2.basename(url, ext);
|
|
2600
|
+
const dirUrl = url.slice(0, url.length - (base + ext).length);
|
|
2601
|
+
let entries;
|
|
2602
|
+
try {
|
|
2603
|
+
entries = fs3.readdirSync(path2.join(publicDir, path2.dirname(url)));
|
|
2604
|
+
} catch {
|
|
2605
|
+
return [];
|
|
2606
|
+
}
|
|
2607
|
+
const re = new RegExp(
|
|
2608
|
+
"^" + base.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") + "\\.w(\\d+)" + ext.replace(".", "\\.") + "$",
|
|
2609
|
+
"i"
|
|
2610
|
+
);
|
|
2611
|
+
const out = [];
|
|
2612
|
+
for (const e of entries) {
|
|
2613
|
+
const m = re.exec(e);
|
|
2614
|
+
const width = m ? Number(m[1]) : 0;
|
|
2615
|
+
if (width > 0) out.push({ url: `${dirUrl}${base}.w${width}${ext}`, width });
|
|
2616
|
+
}
|
|
2617
|
+
return out.sort((a, b) => a.width - b.width);
|
|
2618
|
+
}
|
|
1728
2619
|
function inlineImages(template, publicDir) {
|
|
1729
2620
|
return template.replace(IMG_RE, (tag) => {
|
|
1730
2621
|
const src = tag.match(/\bsrc="(\/[^"{}]+)"/);
|
|
1731
2622
|
if (!src) return tag;
|
|
1732
|
-
const ext =
|
|
2623
|
+
const ext = path2.extname(src[1]).toLowerCase();
|
|
1733
2624
|
const mime = IMG_MIME[ext];
|
|
1734
2625
|
if (!mime) return tag;
|
|
2626
|
+
const rel = src[1].replace(/^\/public(?=\/)/, "");
|
|
2627
|
+
const filePath = path2.join(publicDir, rel);
|
|
1735
2628
|
let file;
|
|
1736
2629
|
try {
|
|
1737
|
-
file =
|
|
2630
|
+
file = fs3.readFileSync(filePath);
|
|
1738
2631
|
} catch {
|
|
1739
2632
|
return tag;
|
|
1740
2633
|
}
|
|
1741
|
-
|
|
2634
|
+
const authorDims = /\swidth=/.test(tag) || /\sheight=/.test(tag);
|
|
2635
|
+
const dims = authorDims ? null : readImageSize(filePath);
|
|
2636
|
+
const withDims = (t) => dims ? t.replace(/<img\b/, `<img width="${dims.width}" height="${dims.height}"`) : t;
|
|
2637
|
+
if (file.length > INLINE_IMG_MAX) {
|
|
2638
|
+
const hasSS = /\ssrcset=/.test(tag) || /\ssizes=/.test(tag);
|
|
2639
|
+
const variants = hasSS ? [] : listImageVariants(publicDir, rel);
|
|
2640
|
+
if (!variants.length) return withDims(tag);
|
|
2641
|
+
const srcset = variants.map((v) => `${v.url} ${v.width}w`).join(", ");
|
|
2642
|
+
return withDims(tag.replace(/<img\b/, `<img srcset="${srcset}"`));
|
|
2643
|
+
}
|
|
1742
2644
|
const uri = ext === ".svg" ? `data:image/svg+xml,${file.toString("utf-8").replace(/%/g, "%25").replace(/#/g, "%23").replace(/\{/g, "%7B").replace(/\}/g, "%7D").replace(/"/g, "%22")}` : `data:${mime};base64,${file.toString("base64")}`;
|
|
1743
|
-
return tag.replace(src[0], `src="${uri}"`);
|
|
2645
|
+
return withDims(tag.replace(src[0], `src="${uri}"`));
|
|
1744
2646
|
});
|
|
1745
2647
|
}
|
|
1746
2648
|
function emitText(expr, acc, closes, scope, markers = true, pair = false) {
|
|
@@ -1754,6 +2656,7 @@ function emitText(expr, acc, closes, scope, markers = true, pair = false) {
|
|
|
1754
2656
|
return `${acc} += textMark(${closes}, ${fn}${extra});
|
|
1755
2657
|
`;
|
|
1756
2658
|
}
|
|
2659
|
+
var BOOLEAN_ATTRS = /* @__PURE__ */ new Set(["checked", "disabled", "readonly", "required", "selected", "multiple", "autofocus", "open"]);
|
|
1757
2660
|
function emitAttr(attr, expr, acc, closes, scope, markers = true) {
|
|
1758
2661
|
if (!markers) {
|
|
1759
2662
|
return `${acc} += '${attr}="' + esc(${expr}) + '"';
|
|
@@ -1761,6 +2664,10 @@ function emitAttr(attr, expr, acc, closes, scope, markers = true) {
|
|
|
1761
2664
|
}
|
|
1762
2665
|
const fn = scope ? `(${scope}) => (${expr})` : `() => (${expr})`;
|
|
1763
2666
|
const arg = scope ? `, ${scope}` : "";
|
|
2667
|
+
if (BOOLEAN_ATTRS.has(attr)) {
|
|
2668
|
+
return `${acc} += boolAttrMark(${closes}, ${fn}, '${attr}'${arg});
|
|
2669
|
+
`;
|
|
2670
|
+
}
|
|
1764
2671
|
return `${acc} += attrMark(${closes}, ${fn}, '${attr}'${arg});
|
|
1765
2672
|
`;
|
|
1766
2673
|
}
|
|
@@ -1768,7 +2675,7 @@ function compileSlot(acc) {
|
|
|
1768
2675
|
return `${acc} += String(children);
|
|
1769
2676
|
`;
|
|
1770
2677
|
}
|
|
1771
|
-
var 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';`;
|
|
2678
|
+
var RUNTIME_IMPORTS = `import { state, setState, persistState, $data, hasState, esc, refresh, onMount, onCleanup, getContext, $query, $t, bestLocale, localeDir, ensureLocale, loadLocale, handlers, directives, $cookies, $sessionCookie, $store, ActionError, $actionError, $actionErrorOrThrow, $boundaryFallback, $setBoundaryError, $boundaryError, $append, $prepend, $merge, applyStateDeltas, textMark, attrMark, boolAttrMark, ifMark, eachMark, headMark, rawMark, slotBlockMark, redirect, notFound } from './runtime.js';`;
|
|
1772
2679
|
var API_RUNTIME_HELPERS = RUNTIME_IMPORTS.replace(/^import\s*\{/, "").replace(/\}\s*from[\s\S]*$/, "").split(",").map((s) => s.trim()).filter(Boolean);
|
|
1773
2680
|
function propsCode(props) {
|
|
1774
2681
|
if (props.length === 0) return "";
|
|
@@ -1781,7 +2688,16 @@ var SLOT_HELPER = `const __slot = (sl, name, pairs) => {
|
|
|
1781
2688
|
for (let i = 0; i < pairs.length; i++) o[pairs[i][0]] = pairs[i][1];
|
|
1782
2689
|
return { o, fn };
|
|
1783
2690
|
};
|
|
1784
|
-
const __slotBlock = (closes, sl, name, pairs) =>
|
|
2691
|
+
const __slotBlock = (closes, sl, name, pairs, fallback) => {
|
|
2692
|
+
const hit = __slot(sl, name, pairs);
|
|
2693
|
+
if (hit) return slotBlockMark(closes, hit);
|
|
2694
|
+
return fallback || '';
|
|
2695
|
+
};
|
|
2696
|
+
const __slotDefault = (children, fallback) => {
|
|
2697
|
+
const c = children == null ? '' : String(children);
|
|
2698
|
+
if (c.trim()) return c;
|
|
2699
|
+
return fallback || '';
|
|
2700
|
+
};`;
|
|
1785
2701
|
function generateSSR(script, templateFn, stateDeclsCode, exports = "", headFn = "", props = [], namedSlots = false, imports = "", isComponent = false, guard = "", hasActions = false, dataDeclsCode = "") {
|
|
1786
2702
|
const headCode = headFn ? `
|
|
1787
2703
|
const __head = () => { let __hd = ''; ${headFn} return __hd; };
|
|
@@ -1857,7 +2773,7 @@ function buildReport(infos, compiled) {
|
|
|
1857
2773
|
if (routeShipsNoJs(infos, compiled, i)) {
|
|
1858
2774
|
return `${info.routePath} zero-JS nothing in the chain needs the client`;
|
|
1859
2775
|
}
|
|
1860
|
-
const why = [i, ...layoutsOf(infos, i)].filter((ci) => compiled[ci].needsClient).map((ci) => `${(compiled[ci].clientReasons ?? ["needs the client"]).join(" + ")} in ${
|
|
2776
|
+
const why = [i, ...layoutsOf(infos, i)].filter((ci) => compiled[ci].needsClient).map((ci) => `${(compiled[ci].clientReasons ?? ["needs the client"]).join(" + ")} in ${path2.basename(infos[ci].filePath)}`).join("; ");
|
|
1861
2777
|
const forced = compiled[i].csr === true ? " (csr = true forces the bundle)" : "";
|
|
1862
2778
|
return `${info.routePath} client JS ${why}${forced}`;
|
|
1863
2779
|
});
|
|
@@ -1905,44 +2821,44 @@ for (const el of document.querySelectorAll('[data-rosetack]')) {
|
|
|
1905
2821
|
}
|
|
1906
2822
|
`;
|
|
1907
2823
|
async function buildProject(root, outDir) {
|
|
1908
|
-
await
|
|
1909
|
-
const stale = (await
|
|
1910
|
-
await Promise.all(stale.map((f) =>
|
|
2824
|
+
await fs3.promises.mkdir(outDir, { recursive: true });
|
|
2825
|
+
const stale = (await fs3.promises.readdir(outDir)).filter((f) => /^(?:comp-\d+\.(?:ssr|client)|runtime|(?:server|client)-entry)\.js$/.test(f));
|
|
2826
|
+
await Promise.all(stale.map((f) => fs3.promises.rm(path2.join(outDir, f), { force: true })));
|
|
1911
2827
|
const pageFiles = await scanRoseFiles(root);
|
|
1912
2828
|
const compFiles = await scanComponentFiles(root);
|
|
1913
2829
|
const files = [...pageFiles, ...compFiles];
|
|
1914
2830
|
if (pageFiles.length === 0) {
|
|
1915
2831
|
throw new RoseError(
|
|
1916
2832
|
"E-ROUTE",
|
|
1917
|
-
`no .rose pages found under ${
|
|
1918
|
-
{ file:
|
|
2833
|
+
`no .rose pages found under ${path2.join(root, "src", "pages")} - run rosetack from a project root, or pass one: rosetack build <dir>`,
|
|
2834
|
+
{ file: path2.join(root, "src", "pages"), hint: "create src/pages/index.rose in that directory (or run the command from the project root)" }
|
|
1919
2835
|
);
|
|
1920
2836
|
}
|
|
1921
2837
|
const infos = files.map((f) => ({ ...getRouteInfo(f, root) }));
|
|
1922
2838
|
const config = await loadConfig(root);
|
|
1923
2839
|
const plugins = config.plugins;
|
|
1924
2840
|
const scopeKeys = files.map((f, i) => {
|
|
1925
|
-
const base = infos[i].isComponent ?
|
|
1926
|
-
return
|
|
2841
|
+
const base = infos[i].isComponent ? path2.join(root, "src") : path2.join(root, "src", "pages");
|
|
2842
|
+
return path2.relative(base, f).replace(/\\/g, "/").replace(/\.rose$/, "");
|
|
1927
2843
|
});
|
|
1928
2844
|
const registry = new Map(
|
|
1929
2845
|
files.map((f, i) => [f, { index: i, scopeKey: scopeKeys[i], slots: scanSlotDecls(f) }])
|
|
1930
2846
|
);
|
|
1931
2847
|
const compiled = await Promise.all(
|
|
1932
|
-
files.map((f, i) => compileComponent(f,
|
|
2848
|
+
files.map((f, i) => compileComponent(f, path2.join(root, "public"), scopeKeys[i], infos[i].isApi, plugins, registry))
|
|
1933
2849
|
);
|
|
1934
2850
|
const importsOf = /* @__PURE__ */ new Map();
|
|
1935
2851
|
files.forEach((_, i) => {
|
|
1936
2852
|
const list = [];
|
|
1937
2853
|
for (const r of compiled[i].roseImports ?? []) {
|
|
1938
|
-
const abs =
|
|
2854
|
+
const abs = path2.resolve(path2.dirname(files[i]), r.specifier);
|
|
1939
2855
|
const hit = registry.get(abs);
|
|
1940
2856
|
if (hit) list.push(hit.index);
|
|
1941
2857
|
}
|
|
1942
2858
|
importsOf.set(i, list);
|
|
1943
2859
|
});
|
|
1944
2860
|
const needyDep = (i, seen = /* @__PURE__ */ new Set()) => {
|
|
1945
|
-
if (compiled[i].needsClient) return
|
|
2861
|
+
if (compiled[i].needsClient) return path2.basename(files[i]);
|
|
1946
2862
|
if (seen.has(i)) return null;
|
|
1947
2863
|
seen.add(i);
|
|
1948
2864
|
for (const dep of importsOf.get(i) ?? []) {
|
|
@@ -1964,7 +2880,7 @@ async function buildProject(root, outDir) {
|
|
|
1964
2880
|
if (reachable.has(i)) return;
|
|
1965
2881
|
reachable.add(i);
|
|
1966
2882
|
for (const r of compiled[i].roseImports ?? []) {
|
|
1967
|
-
const abs =
|
|
2883
|
+
const abs = path2.resolve(path2.dirname(files[i]), r.specifier);
|
|
1968
2884
|
const hit = registry.get(abs);
|
|
1969
2885
|
if (hit) visit(hit.index);
|
|
1970
2886
|
}
|
|
@@ -1973,13 +2889,13 @@ async function buildProject(root, outDir) {
|
|
|
1973
2889
|
if (!infos[i].isComponent) visit(i);
|
|
1974
2890
|
});
|
|
1975
2891
|
const styles = compiled.map((c, i) => reachable.has(i) ? c.style : "").filter(Boolean).join("\n");
|
|
1976
|
-
if (styles) await
|
|
1977
|
-
else await
|
|
2892
|
+
if (styles) await fs3.promises.writeFile(path2.join(outDir, "styles.css"), styles);
|
|
2893
|
+
else await fs3.promises.rm(path2.join(outDir, "styles.css"), { force: true });
|
|
1978
2894
|
let locales = {};
|
|
1979
2895
|
try {
|
|
1980
|
-
for (const f of await
|
|
2896
|
+
for (const f of await fs3.promises.readdir(path2.join(root, "src", "locales"))) {
|
|
1981
2897
|
if (!f.endsWith(".json")) continue;
|
|
1982
|
-
locales[f.slice(0, -5)] = JSON.parse(await
|
|
2898
|
+
locales[f.slice(0, -5)] = JSON.parse(await fs3.promises.readFile(path2.join(root, "src", "locales", f), "utf-8"));
|
|
1983
2899
|
}
|
|
1984
2900
|
} catch {
|
|
1985
2901
|
locales = {};
|
|
@@ -1991,21 +2907,24 @@ async function buildProject(root, outDir) {
|
|
|
1991
2907
|
for (const l of preload) {
|
|
1992
2908
|
if (!locales[l]) console.warn(`rosetack: i18n.preload lists '${l}' but there is no src/locales/${l}.json - ignored`);
|
|
1993
2909
|
}
|
|
1994
|
-
await
|
|
2910
|
+
await fs3.promises.rm(path2.join(outDir, "locales"), { recursive: true, force: true });
|
|
1995
2911
|
if (packed.length > 0) {
|
|
1996
|
-
const packDir =
|
|
1997
|
-
await
|
|
1998
|
-
for (const l of packed) await
|
|
2912
|
+
const packDir = path2.join(outDir, "locales");
|
|
2913
|
+
await fs3.promises.mkdir(packDir, { recursive: true });
|
|
2914
|
+
for (const l of packed) await fs3.promises.writeFile(path2.join(packDir, `${l}.json`), JSON.stringify(locales[l]));
|
|
1999
2915
|
}
|
|
2000
2916
|
const clientLocales = Object.fromEntries(Object.keys(locales).filter((l) => !packed.includes(l)).map((l) => [l, locales[l]]));
|
|
2001
2917
|
const clientLocalesJson = JSON.stringify(clientLocales).replace(/</g, "\\u003c");
|
|
2002
|
-
const buildDir =
|
|
2003
|
-
await
|
|
2004
|
-
await
|
|
2918
|
+
const buildDir = path2.join(outDir, ".build");
|
|
2919
|
+
await fs3.promises.rm(buildDir, { recursive: true, force: true });
|
|
2920
|
+
await fs3.promises.mkdir(buildDir, { recursive: true });
|
|
2921
|
+
const contentSrcCands = [path2.join(path2.dirname(fileURLToPath(import.meta.url)), "..", "cli", "content.ts"), path2.join(path2.dirname(fileURLToPath(import.meta.url)), "..", "src", "cli", "content.ts")];
|
|
2922
|
+
const contentSrc = contentSrcCands.find((c) => fs3.existsSync(c)) ?? contentSrcCands[0];
|
|
2923
|
+
fs3.copyFileSync(contentSrc, path2.join(buildDir, "content-md.ts"));
|
|
2005
2924
|
const runtimePlugins = plugins.filter((p) => p && (p.onRequest || p.onResponse));
|
|
2006
2925
|
if (runtimePlugins.length > 0) {
|
|
2007
|
-
const configRel =
|
|
2008
|
-
await
|
|
2926
|
+
const configRel = path2.relative(buildDir, path2.join(root, "rosetack.config.js")).replace(/\\/g, "/");
|
|
2927
|
+
await fs3.promises.writeFile(path2.join(buildDir, "plugins.js"), `
|
|
2009
2928
|
import config from ${JSON.stringify(configRel)};
|
|
2010
2929
|
|
|
2011
2930
|
const list = Array.isArray(config) ? config : [];
|
|
@@ -2017,21 +2936,21 @@ export const hasRequestHooks = hooks.some((p) => p.onRequest);
|
|
|
2017
2936
|
export const hasResponseHooks = hooks.some((p) => p.onResponse);
|
|
2018
2937
|
`);
|
|
2019
2938
|
}
|
|
2020
|
-
const runtimeEntry = ["../runtime/index.ts", "../src/runtime/index.ts"].map((rel) => fileURLToPath(new URL(rel, import.meta.url))).find((p) =>
|
|
2939
|
+
const runtimeEntry = ["../runtime/index.ts", "../src/runtime/index.ts"].map((rel) => fileURLToPath(new URL(rel, import.meta.url))).find((p) => fs3.existsSync(p));
|
|
2021
2940
|
if (!runtimeEntry) throw new RoseError("E-INTERNAL", "rosetack: the runtime source (src/runtime/index.ts) was not found next to the compiler", { hint: "the published package ships src/ beside dist-cli/ - reinstall it, or run from a checkout" });
|
|
2022
2941
|
await esbuild.build({
|
|
2023
2942
|
entryPoints: [runtimeEntry],
|
|
2024
2943
|
bundle: true,
|
|
2025
|
-
outfile:
|
|
2944
|
+
outfile: path2.join(buildDir, "runtime.js"),
|
|
2026
2945
|
format: "esm",
|
|
2027
2946
|
platform: "browser",
|
|
2028
2947
|
write: true
|
|
2029
2948
|
});
|
|
2030
2949
|
for (let i = 0; i < compiled.length; i++) {
|
|
2031
2950
|
const src = compiled[i].api ?? compiled[i].ssr;
|
|
2032
|
-
await
|
|
2951
|
+
await fs3.promises.writeFile(path2.join(buildDir, `comp-${i}.ssr.js`), src);
|
|
2033
2952
|
if (!infos[i].isApi) {
|
|
2034
|
-
await
|
|
2953
|
+
await fs3.promises.writeFile(path2.join(buildDir, `comp-${i}.client.js`), compiled[i].client);
|
|
2035
2954
|
}
|
|
2036
2955
|
}
|
|
2037
2956
|
const pages = infos.map((info, i) => ({ info, i })).filter(({ info }) => !info.isLayout && !info.isNotFound && !info.isError && !info.isApi && !info.isMiddleware && !info.isComponent).sort((a, b) => {
|
|
@@ -2093,17 +3012,17 @@ export const hasResponseHooks = hooks.some((p) => p.onResponse);
|
|
|
2093
3012
|
return named ? `import { render as render_${i}, ${named} } from './comp-${i}.ssr.js';` : `import { render as render_${i} } from './comp-${i}.ssr.js';`;
|
|
2094
3013
|
}).join("\n");
|
|
2095
3014
|
const notFoundEntries = infos.map((info, i) => ({ info, i })).filter(({ info }) => info.isNotFound).map(({ info, i }) => {
|
|
2096
|
-
const rel =
|
|
2097
|
-
const dir =
|
|
3015
|
+
const rel = path2.relative(path2.join(root, "src", "pages"), info.filePath).replace(/\\/g, "/");
|
|
3016
|
+
const dir = path2.posix.dirname(rel);
|
|
2098
3017
|
const prefix = dir === "." ? "/" : "/" + dir;
|
|
2099
3018
|
const flags = routeShellOff(infos, compiled, i) ? ", { shell: false }" : "";
|
|
2100
|
-
return { prefix, render:
|
|
3019
|
+
return { prefix, render: compose(i), flags };
|
|
2101
3020
|
}).sort((a, b) => b.prefix.length - a.prefix.length);
|
|
2102
3021
|
const notFoundTable = `[
|
|
2103
3022
|
${notFoundEntries.map((e) => ` ['${e.prefix}', ${e.render}${e.flags}],`).join("\n")}
|
|
2104
3023
|
]`;
|
|
2105
3024
|
const errIdx = infos.findIndex((info) => info.isError);
|
|
2106
|
-
const errorRender = errIdx >= 0 ?
|
|
3025
|
+
const errorRender = errIdx >= 0 ? compose(errIdx) : "null";
|
|
2107
3026
|
const middlewareIdx = infos.findIndex((info) => info.isMiddleware);
|
|
2108
3027
|
const serverRoutes = pages.map(({ info, i }) => {
|
|
2109
3028
|
const actionMap = compiled[i].actionNames.map((n) => `${n}: ${n}_${i}`).join(", ");
|
|
@@ -2133,7 +3052,9 @@ ${notFoundEntries.map((e) => ` ['${e.prefix}', ${e.render}${e.flags}],`).join("
|
|
|
2133
3052
|
}).join(",\n ");
|
|
2134
3053
|
const serverEntry = `
|
|
2135
3054
|
${serverImports}
|
|
2136
|
-
import {
|
|
3055
|
+
import { renderMarkdown } from './content-md.ts';
|
|
3056
|
+
import crypto from 'node:crypto';
|
|
3057
|
+
import { setState, persistState, clearRequestState, serializeState, resetRequestContext, setRequestQuery, isLocale, setLocales, localeList, localeDir, setStoreTransport, applyStorePatch, ActionError, StateDelta, setStateDelta, esc } from './runtime.js';
|
|
2137
3058
|
${runtimePlugins.length > 0 ? `import { hooks as __pluginHooks, hasRequestHooks as __hasRequestHooks, hasResponseHooks as __hasResponseHooks } from './plugins.js';` : `// no plugin declares a runtime hook, so there is no plugins
|
|
2138
3059
|
// module to import - the runners below stay no-ops and the servers call them
|
|
2139
3060
|
// unconditionally (one code path, no flags to keep in sync).
|
|
@@ -2225,6 +3146,235 @@ export const revalidate = [
|
|
|
2225
3146
|
${pages.filter(({ i }) => compiled[i].revalidate !== void 0 && !compiled[i].usesContext).map(({ info, i }) => `{ pattern: '${info.pattern}', seconds: ${compiled[i].revalidate} }`).join(",\n ")}
|
|
2226
3147
|
];
|
|
2227
3148
|
|
|
3149
|
+
// Per-request render memo (export const cache = N): a dynamic route's whole renderPage result is memoized for N seconds.
|
|
3150
|
+
export const routeCaches = [
|
|
3151
|
+
${pages.filter(({ i }) => compiled[i].cache !== void 0).map(({ info, i }) => `{ pattern: '${info.pattern}', seconds: ${compiled[i].cache} }`).join(",\n ")}
|
|
3152
|
+
];
|
|
3153
|
+
const __dynCache = new Map();
|
|
3154
|
+
export function invalidateRenderCache(): void {
|
|
3155
|
+
__dynCache.clear();
|
|
3156
|
+
}
|
|
3157
|
+
// Application KV cache primitive (server-side, per-worker in-memory): a zero-dependency store for expensive computations.
|
|
3158
|
+
const __kvStore = new Map<string, { v: unknown; exp: number }>();
|
|
3159
|
+
// Content collections: src/content/<coll>/*.md scanned once at build time,
|
|
3160
|
+
|
|
3161
|
+
const contentCollections = ${JSON.stringify(scanContentDir(path2.join(root, "src", "content")))};
|
|
3162
|
+
export const kv = {
|
|
3163
|
+
get(key: string): unknown {
|
|
3164
|
+
const e = __kvStore.get(key);
|
|
3165
|
+
if (!e) return undefined;
|
|
3166
|
+
if (e.exp < Date.now()) { __kvStore.delete(key); return undefined; }
|
|
3167
|
+
return e.v;
|
|
3168
|
+
},
|
|
3169
|
+
set(key: string, value: unknown, ttlSeconds = 300): void {
|
|
3170
|
+
if (__kvStore.size > 1000) {
|
|
3171
|
+
const cutoff = Date.now();
|
|
3172
|
+
for (const [k, e] of __kvStore) { if (e.exp < cutoff) __kvStore.delete(k); }
|
|
3173
|
+
if (__kvStore.size > 2000) __kvStore.clear();
|
|
3174
|
+
}
|
|
3175
|
+
__kvStore.set(key, { v: value, exp: Date.now() + ttlSeconds * 1000 });
|
|
3176
|
+
},
|
|
3177
|
+
del(key: string): void { __kvStore.delete(key); },
|
|
3178
|
+
has(key: string): boolean {
|
|
3179
|
+
const e = __kvStore.get(key);
|
|
3180
|
+
return !!e && e.exp >= Date.now();
|
|
3181
|
+
},
|
|
3182
|
+
};
|
|
3183
|
+
globalThis.__rosetackKvApi = { kv, kvMemo: $kv };
|
|
3184
|
+
globalThis.__rosetackContent = {
|
|
3185
|
+
list: (coll: string, filter?: { tag: string }) => {
|
|
3186
|
+
let items = contentCollections[coll] ?? [];
|
|
3187
|
+
if (filter?.tag) items = items.filter((e) => ((e.frontmatter.tags as string[] | undefined) ?? []).includes(filter.tag));
|
|
3188
|
+
return items.map((e) => ({ slug: e.slug, ...e.frontmatter }));
|
|
3189
|
+
},
|
|
3190
|
+
rss: (coll: string, opts: { title: string; origin: string; description?: string }) => {
|
|
3191
|
+
return buildRss(contentCollections[coll] ?? [], opts);
|
|
3192
|
+
},
|
|
3193
|
+
get: (coll: string, slug: string, vars?: Record<string, unknown>) => {
|
|
3194
|
+
const e = (contentCollections[coll] ?? []).find((x) => x.slug === slug);
|
|
3195
|
+
if (!e) return null;
|
|
3196
|
+
return { slug: e.slug, ...e.frontmatter, html: renderMarkdown(e.body, vars), toc: e.toc, readingTime: e.readingTime, wordCount: e.wordCount, excerpt: e.excerpt };
|
|
3197
|
+
},
|
|
3198
|
+
};
|
|
3199
|
+
|
|
3200
|
+
const v = {
|
|
3201
|
+
validate(body: Record<string, unknown>, rules: Record<string, string[]>): { ok: boolean; errors: Record<string, string>; values: Record<string, unknown> } {
|
|
3202
|
+
const errors: Record<string, string> = {};
|
|
3203
|
+
const values: Record<string, unknown> = {};
|
|
3204
|
+
for (const [field, ruleList] of Object.entries(rules)) {
|
|
3205
|
+
let val = body[field];
|
|
3206
|
+
for (const rule of ruleList) {
|
|
3207
|
+
if (val === undefined || val === null || val === "") {
|
|
3208
|
+
if (rule === "required") errors[field] = field + " is required";
|
|
3209
|
+
else if (rule.startsWith("default:")) val = rule.slice(8);
|
|
3210
|
+
continue;
|
|
3211
|
+
}
|
|
3212
|
+
if (rule === "string") val = String(val);
|
|
3213
|
+
else if (rule === "trim") val = String(val).trim();
|
|
3214
|
+
else if (rule === "number") {
|
|
3215
|
+
const num = Number(val);
|
|
3216
|
+
if (Number.isNaN(num)) errors[field] = field + " must be a number";
|
|
3217
|
+
else val = num;
|
|
3218
|
+
} else if (rule === "email") {
|
|
3219
|
+
if (!/^[^s@]+@[^s@]+.[^s@]+$/.test(String(val))) errors[field] = field + " must be a valid email";
|
|
3220
|
+
} else if (rule.startsWith("min:")) {
|
|
3221
|
+
const min = Number(rule.slice(4));
|
|
3222
|
+
if (typeof val === "number" ? val < min : String(val).length < min) errors[field] = field + " must be at least " + min;
|
|
3223
|
+
} else if (rule.startsWith("max:")) {
|
|
3224
|
+
const max = Number(rule.slice(4));
|
|
3225
|
+
if (typeof val === "number" ? val > max : String(val).length > max) errors[field] = field + " must be at most " + max;
|
|
3226
|
+
}
|
|
3227
|
+
}
|
|
3228
|
+
values[field] = val;
|
|
3229
|
+
}
|
|
3230
|
+
return { ok: Object.keys(errors).length === 0, errors, values };
|
|
3231
|
+
},
|
|
3232
|
+
};
|
|
3233
|
+
|
|
3234
|
+
const jobs = {
|
|
3235
|
+
_timers: new Map<string, ReturnType<typeof setInterval>>(),
|
|
3236
|
+
every(name: string, seconds: number, fn: () => void | Promise<void>): void {
|
|
3237
|
+
if (this._timers.has(name)) return;
|
|
3238
|
+
const t = setInterval(() => { Promise.resolve(fn()).catch(() => {}); }, seconds * 1000);
|
|
3239
|
+
this._timers.set(name, t as any);
|
|
3240
|
+
},
|
|
3241
|
+
cancel(name: string): void {
|
|
3242
|
+
const t = this._timers.get(name);
|
|
3243
|
+
if (t) { clearInterval(t); this._timers.delete(name); }
|
|
3244
|
+
},
|
|
3245
|
+
cancelAll(): void { for (const t of this._timers.values()) clearInterval(t); this._timers.clear(); }
|
|
3246
|
+
};
|
|
3247
|
+
|
|
3248
|
+
function sse(handler: (send: (event: string, data: unknown) => void) => Promise<void> | void): Response {
|
|
3249
|
+
const encoder = new TextEncoder();
|
|
3250
|
+
const stream = new ReadableStream({
|
|
3251
|
+
async start(controller) {
|
|
3252
|
+
let closed = false;
|
|
3253
|
+
const send = (event: string, data: unknown) => {
|
|
3254
|
+
if (closed) return;
|
|
3255
|
+
controller.enqueue(encoder.encode("event: " + event + "\\ndata: " + JSON.stringify(data) + "\\n\\n"));
|
|
3256
|
+
};
|
|
3257
|
+
try {
|
|
3258
|
+
await handler(send);
|
|
3259
|
+
} finally {
|
|
3260
|
+
closed = true;
|
|
3261
|
+
try { controller.close(); } catch { }
|
|
3262
|
+
}
|
|
3263
|
+
},
|
|
3264
|
+
});
|
|
3265
|
+
return new Response(stream, {
|
|
3266
|
+
headers: { "content-type": "text/event-stream; charset=utf-8", "cache-control": "no-cache", "connection": "keep-alive" },
|
|
3267
|
+
});
|
|
3268
|
+
}
|
|
3269
|
+
globalThis.__rosetackExtras = { v, jobs, sse };
|
|
3270
|
+
const auth = {
|
|
3271
|
+
hashPassword(password: string): string {
|
|
3272
|
+
const salt = crypto.randomBytes(16).toString("hex");
|
|
3273
|
+
const hash = crypto.scryptSync(password, salt, 32).toString("hex");
|
|
3274
|
+
return salt + ":" + hash;
|
|
3275
|
+
},
|
|
3276
|
+
verifyPassword(password: string, stored: string): boolean {
|
|
3277
|
+
const [salt, hash] = stored.split(":");
|
|
3278
|
+
if (!salt || !hash) return false;
|
|
3279
|
+
return crypto.timingSafeEqual(Buffer.from(hash, "hex"), crypto.scryptSync(password, salt, 32));
|
|
3280
|
+
},
|
|
3281
|
+
signSession(data: Record<string, unknown>, secret: string, ttlSeconds = 86400): string {
|
|
3282
|
+
const payload = Buffer.from(JSON.stringify({ ...data, exp: Date.now() + ttlSeconds * 1000 })).toString("base64url");
|
|
3283
|
+
const sig = crypto.createHmac("sha256", secret).update(payload).digest("base64url");
|
|
3284
|
+
return payload + "." + sig;
|
|
3285
|
+
},
|
|
3286
|
+
verifySession<T = Record<string, unknown>>(token: string, secret: string): T | null {
|
|
3287
|
+
const dot = token.lastIndexOf(".");
|
|
3288
|
+
if (dot < 0) return null;
|
|
3289
|
+
const payload = token.slice(0, dot);
|
|
3290
|
+
const sig = token.slice(dot + 1);
|
|
3291
|
+
const expect = crypto.createHmac("sha256", secret).update(payload).digest("base64url");
|
|
3292
|
+
try {
|
|
3293
|
+
if (!crypto.timingSafeEqual(Buffer.from(sig), Buffer.from(expect))) return null;
|
|
3294
|
+
} catch { return null; }
|
|
3295
|
+
try {
|
|
3296
|
+
const data = JSON.parse(Buffer.from(payload, "base64url").toString());
|
|
3297
|
+
if (data.exp < Date.now()) return null;
|
|
3298
|
+
return data as T;
|
|
3299
|
+
} catch { return null; }
|
|
3300
|
+
},
|
|
3301
|
+
csrfToken(secret: string, sessionId: string): string {
|
|
3302
|
+
return crypto.createHmac("sha256", secret).update(sessionId).digest("hex");
|
|
3303
|
+
},
|
|
3304
|
+
verifyCsrf(token: string, secret: string, sessionId: string): boolean {
|
|
3305
|
+
try {
|
|
3306
|
+
return crypto.timingSafeEqual(Buffer.from(token), Buffer.from(this.csrfToken(secret, sessionId)));
|
|
3307
|
+
} catch { return false; }
|
|
3308
|
+
},
|
|
3309
|
+
};
|
|
3310
|
+
globalThis.__rosetackAuth = auth;
|
|
3311
|
+
|
|
3312
|
+
export async function $kv(key: string, compute: () => unknown | Promise<unknown>, ttlSeconds = 300): Promise<unknown> {
|
|
3313
|
+
const hit = kv.get(key);
|
|
3314
|
+
if (hit !== undefined) return hit;
|
|
3315
|
+
const v = await compute();
|
|
3316
|
+
if (v !== undefined) kv.set(key, v, ttlSeconds);
|
|
3317
|
+
return v;
|
|
3318
|
+
}
|
|
3319
|
+
export function isCachedRoute(pathname: string): boolean {
|
|
3320
|
+
return routeCaches.some((r) => matchRoute(r.pattern, pathname));
|
|
3321
|
+
}
|
|
3322
|
+
export function invalidatePath(pathname: string): number {
|
|
3323
|
+
let n = 0;
|
|
3324
|
+
for (const key of [...__dynCache.keys()]) {
|
|
3325
|
+
if (key.startsWith(pathname + '|')) { __dynCache.delete(key); n++; }
|
|
3326
|
+
}
|
|
3327
|
+
return n;
|
|
3328
|
+
}
|
|
3329
|
+
export function peekRenderCache(pathname: string, cookieHeader: string): ReturnType<typeof renderPage> | null {
|
|
3330
|
+
const cfg = routeCaches.find((r) => matchRoute(r.pattern, pathname));
|
|
3331
|
+
if (!cfg) return null;
|
|
3332
|
+
let h = 0x811c9dc5;
|
|
3333
|
+
const c = cookieHeader || '';
|
|
3334
|
+
for (let i = 0; i < c.length; i++) {
|
|
3335
|
+
h ^= c.charCodeAt(i);
|
|
3336
|
+
h = (h * 0x01000193) >>> 0;
|
|
3337
|
+
}
|
|
3338
|
+
const hit = __dynCache.get(pathname + '|' + h.toString(16));
|
|
3339
|
+
return hit && hit.expires > Date.now() ? hit.page : null;
|
|
3340
|
+
}
|
|
3341
|
+
export async function renderPageCached(pathname: string, cookieHeader: string): Promise<ReturnType<typeof renderPage>> {
|
|
3342
|
+
const cfg = routeCaches.find((r) => matchRoute(r.pattern, pathname));
|
|
3343
|
+
if (!cfg) return renderPage(pathname);
|
|
3344
|
+
let h = 0x811c9dc5;
|
|
3345
|
+
for (let i = 0; i < cookieHeader.length; i++) {
|
|
3346
|
+
h ^= cookieHeader.charCodeAt(i);
|
|
3347
|
+
h = (h * 0x01000193) >>> 0;
|
|
3348
|
+
}
|
|
3349
|
+
const key = pathname + '|' + h.toString(16);
|
|
3350
|
+
const hit = __dynCache.get(key);
|
|
3351
|
+
if (hit && hit.expires > Date.now()) {
|
|
3352
|
+
__dynCache.delete(key);
|
|
3353
|
+
__dynCache.set(key, hit);
|
|
3354
|
+
return hit.page;
|
|
3355
|
+
}
|
|
3356
|
+
// Stale-while-revalidate: an EXPIRED entry still answers instantly while one background render refreshes it - the TTL boundary never spikes.
|
|
3357
|
+
if (hit && !hit.refreshing) {
|
|
3358
|
+
hit.refreshing = true;
|
|
3359
|
+
renderPage(pathname).then((fresh: any) => {
|
|
3360
|
+
if (fresh.status === 200 && !fresh.redirect) {
|
|
3361
|
+
__dynCache.set(key, { page: fresh, expires: Date.now() + cfg.seconds * 1000 });
|
|
3362
|
+
} else {
|
|
3363
|
+
__dynCache.delete(key);
|
|
3364
|
+
}
|
|
3365
|
+
}).catch(() => { __dynCache.delete(key); });
|
|
3366
|
+
return hit.page;
|
|
3367
|
+
}
|
|
3368
|
+
const page = await renderPage(pathname);
|
|
3369
|
+
if (page.status === 200 && !page.redirect) {
|
|
3370
|
+
__dynCache.set(key, { page, expires: Date.now() + cfg.seconds * 1000 });
|
|
3371
|
+
if (__dynCache.size > 300) {
|
|
3372
|
+
__dynCache.delete(__dynCache.keys().next().value as string);
|
|
3373
|
+
}
|
|
3374
|
+
}
|
|
3375
|
+
return page;
|
|
3376
|
+
}
|
|
3377
|
+
|
|
2228
3378
|
// Pages/_middleware.rose: a Web-standard request handler that runs before every render on the server (pages, POSTs, api calls alike).
|
|
2229
3379
|
export const middleware = ${middlewareIdx >= 0 ? "middlewareMod.handle ?? null" : "null"};
|
|
2230
3380
|
|
|
@@ -2339,7 +3489,14 @@ export function docAttrs(pathname) {
|
|
|
2339
3489
|
|
|
2340
3490
|
// Paint a fallback page (404/500) and serialize its state.
|
|
2341
3491
|
async function renderFallback(pathname, render) {
|
|
2342
|
-
|
|
3492
|
+
// Split mode: the not-found entry's render is a loader object \u2014 resolve it through getRender (which memoizes the composed function) exactly like.
|
|
3493
|
+
let fn = render;
|
|
3494
|
+
if (typeof fn !== 'function' && fn && typeof fn.load === 'function') {
|
|
3495
|
+
|
|
3496
|
+
// { render } once the route's chunk graph is loaded
|
|
3497
|
+
fn = (await fn.load()).render;
|
|
3498
|
+
}
|
|
3499
|
+
const { html, head } = extractHead(await fn([], ''));
|
|
2343
3500
|
const state = JSON.stringify({ __route: pathname, ...JSON.parse(serializeState()) });
|
|
2344
3501
|
return { html, state, head, ...docAttrs(pathname) };
|
|
2345
3502
|
}
|
|
@@ -2446,8 +3603,27 @@ export async function renderPage(pathname, form) {
|
|
|
2446
3603
|
return await notFoundPage(pathname);
|
|
2447
3604
|
}
|
|
2448
3605
|
console.error('rosetack: render failed for', pathname, err instanceof Error ? err.message : err);
|
|
2449
|
-
|
|
2450
|
-
|
|
3606
|
+
// F10: in dev the response body carries the real error \u2014 message, file:line and the fix hint.
|
|
3607
|
+
let devDetail = '';
|
|
3608
|
+
if (process.env.rosetack_DEV === '1' && err) {
|
|
3609
|
+
const msg = esc(err instanceof Error ? err.message : String(err));
|
|
3610
|
+
const file = esc(String(err.file || ''));
|
|
3611
|
+
const line = err.line != null ? esc(String(err.line)) : '';
|
|
3612
|
+
const hint = esc(String(err.hint || ''));
|
|
3613
|
+
const stack = esc(err instanceof Error ? (err.stack || '').split('\\n').slice(1, 7).join('\\n') : '');
|
|
3614
|
+
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">'
|
|
3615
|
+
+ '<div style="font:600 15px/1.4 system-ui,sans-serif;color:#ff8b8b">Render failed: ' + esc(pathname) + '</div>'
|
|
3616
|
+
+ '<div style="margin:10px 0 0;color:#ffd479">' + msg + '</div>'
|
|
3617
|
+
+ (file ? '<div style="margin:6px 0 0;color:#9ad1ff">' + file + (line ? ':' + line : '') + '</div>' : '')
|
|
3618
|
+
+ (hint ? '<div style="margin:10px 0 0;color:#9fe8b0">Fix: ' + hint + '</div>' : '')
|
|
3619
|
+
+ (stack ? '<pre style="margin:12px 0 0;color:#8f8f9a">' + stack + '</pre>' : '')
|
|
3620
|
+
+ '</div>';
|
|
3621
|
+
}
|
|
3622
|
+
if (errorPage) {
|
|
3623
|
+
const fb = await renderFallback(pathname, errorPage);
|
|
3624
|
+
return { ...fb, html: fb.html + devDetail, status: 500 };
|
|
3625
|
+
}
|
|
3626
|
+
return { html: '<h1>500</h1><p>Something went wrong rendering this page.</p>' + devDetail, state: '{}', head: [], status: 500, ...docAttrs(pathname) };
|
|
2451
3627
|
}
|
|
2452
3628
|
// __route tells the bootstrap which route this document was rendered for.
|
|
2453
3629
|
const state = JSON.stringify({ __route: pathname, ...JSON.parse(serializeState()) });
|
|
@@ -2554,7 +3730,24 @@ export async function renderPageStream(pathname, write, shellOpen, clientTag) {
|
|
|
2554
3730
|
} catch (err) {
|
|
2555
3731
|
|
|
2556
3732
|
console.error('rosetack: render failed for', pathname, err instanceof Error ? err.message : err);
|
|
2557
|
-
|
|
3733
|
+
// F10: dev carries the real error in the body here too \u2014 the shell
|
|
3734
|
+
// is out, so the detail rides after the error page body.
|
|
3735
|
+
let devDetail = '';
|
|
3736
|
+
if (process.env.rosetack_DEV === '1' && err) {
|
|
3737
|
+
const msg = esc(err instanceof Error ? err.message : String(err));
|
|
3738
|
+
const file = esc(String(err.file || ''));
|
|
3739
|
+
const line = err.line != null ? esc(String(err.line)) : '';
|
|
3740
|
+
const hint = esc(String(err.hint || ''));
|
|
3741
|
+
const stack = esc(err instanceof Error ? (err.stack || '').split('\\n').slice(1, 7).join('\\n') : '');
|
|
3742
|
+
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">'
|
|
3743
|
+
+ '<div style="font:600 15px/1.4 system-ui,sans-serif;color:#ff8b8b">Render failed: ' + esc(pathname) + '</div>'
|
|
3744
|
+
+ '<div style="margin:10px 0 0;color:#ffd479">' + msg + '</div>'
|
|
3745
|
+
+ (file ? '<div style="margin:6px 0 0;color:#9ad1ff">' + file + (line ? ':' + line : '') + '</div>' : '')
|
|
3746
|
+
+ (hint ? '<div style="margin:10px 0 0;color:#9fe8b0">Fix: ' + hint + '</div>' : '')
|
|
3747
|
+
+ (stack ? '<pre style="margin:12px 0 0;color:#8f8f9a">' + stack + '</pre>' : '')
|
|
3748
|
+
+ '</div>';
|
|
3749
|
+
}
|
|
3750
|
+
html = errorPage ? extractHead(await errorPage([], '')).html + devDetail : '<h1>500</h1><p>Something went wrong rendering this page.</p>' + devDetail;
|
|
2558
3751
|
}
|
|
2559
3752
|
write(html);
|
|
2560
3753
|
// Csr: false ( auto since #29): a no-JS route's document ends here - no state script, no inlined bundle.
|
|
@@ -2572,14 +3765,66 @@ export async function renderPageStream(pathname, write, shellOpen, clientTag) {
|
|
|
2572
3765
|
return 404;
|
|
2573
3766
|
}
|
|
2574
3767
|
`;
|
|
2575
|
-
|
|
3768
|
+
try {
|
|
3769
|
+
const patterns = [...pages, ...apiRoutes].map(({ info }) => info.pattern);
|
|
3770
|
+
const uniq = [...new Set(patterns)].sort();
|
|
3771
|
+
const lit = uniq.map((p) => JSON.stringify(p)).join(" | ") || "'/'";
|
|
3772
|
+
const paramsOf = (pattern) => (pattern.match(/:[\w]+|\*\*[\w]+|\*[\w]+/g) ?? []).map((m) => m.replace(/^[*:]+/, ""));
|
|
3773
|
+
const paramSig = uniq.map((p) => {
|
|
3774
|
+
const ps = paramsOf(p);
|
|
3775
|
+
if (!ps.length) return "";
|
|
3776
|
+
return " " + JSON.stringify(p) + ": { " + ps.map((n) => n + ": string | number").join("; ") + " };\n";
|
|
3777
|
+
}).join("");
|
|
3778
|
+
const outDirTs = path2.join(root, "src", ".rosetack");
|
|
3779
|
+
await fs3.promises.mkdir(outDirTs, { recursive: true });
|
|
3780
|
+
const srcLines = [
|
|
3781
|
+
"// GENERATED by rosetack build - do not edit.",
|
|
3782
|
+
"export type RoutePath = " + lit + ";",
|
|
3783
|
+
"export const routePatterns = " + JSON.stringify(uniq) + " as const;",
|
|
3784
|
+
"export type RouteParams = {",
|
|
3785
|
+
paramSig,
|
|
3786
|
+
"};",
|
|
3787
|
+
"/** Build a URL from a route pattern and its params. */",
|
|
3788
|
+
"export function url(",
|
|
3789
|
+
" path: RoutePath,",
|
|
3790
|
+
" params: RouteParams[keyof RouteParams] = {} as never,",
|
|
3791
|
+
"): string {",
|
|
3792
|
+
" let out = path as string;",
|
|
3793
|
+
" for (const [k, v] of Object.entries(params as Record<string, string | number>)) {",
|
|
3794
|
+
" out = out.replace(new RegExp('[:*]+' + k, 'g'), String(v));",
|
|
3795
|
+
" }",
|
|
3796
|
+
" return out;",
|
|
3797
|
+
"}"
|
|
3798
|
+
].join("\n") + "\n";
|
|
3799
|
+
await fs3.promises.writeFile(path2.join(outDirTs, "routes.ts"), srcLines);
|
|
3800
|
+
} catch {
|
|
3801
|
+
}
|
|
3802
|
+
await fs3.promises.writeFile(path2.join(buildDir, "server-entry.js"), serverEntry);
|
|
3803
|
+
await esbuild.build({
|
|
3804
|
+
entryPoints: [path2.join(buildDir, "server-entry.js")],
|
|
3805
|
+
bundle: true,
|
|
3806
|
+
outfile: path2.join(outDir, "server.js"),
|
|
3807
|
+
format: "esm",
|
|
3808
|
+
platform: "node",
|
|
3809
|
+
write: true,
|
|
3810
|
+
...TS_LOADER
|
|
3811
|
+
});
|
|
2576
3812
|
await esbuild.build({
|
|
2577
|
-
entryPoints: [
|
|
3813
|
+
entryPoints: [(() => {
|
|
3814
|
+
const here = path2.dirname(fileURLToPath(import.meta.url));
|
|
3815
|
+
for (const cand of [path2.join(here, "..", "cli", "prod-server.ts"), path2.join(here, "..", "src", "cli", "prod-server.ts")]) {
|
|
3816
|
+
if (fs3.existsSync(cand)) return cand;
|
|
3817
|
+
}
|
|
3818
|
+
return path2.join(here, "..", "cli", "prod-server.ts");
|
|
3819
|
+
})()],
|
|
2578
3820
|
bundle: true,
|
|
2579
|
-
outfile:
|
|
3821
|
+
outfile: path2.join(outDir, "prod.mjs"),
|
|
2580
3822
|
format: "esm",
|
|
2581
3823
|
platform: "node",
|
|
2582
3824
|
write: true,
|
|
3825
|
+
banner: {
|
|
3826
|
+
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);"
|
|
3827
|
+
},
|
|
2583
3828
|
...TS_LOADER
|
|
2584
3829
|
});
|
|
2585
3830
|
const clientImports = split ? "" : compiled.map((_, i) => ({ i })).filter(({ i }) => !infos[i].isApi && !infos[i].isMiddleware && reachable.has(i)).map(({ i }) => `import { render as render_${i} } from './comp-${i}.client.js';`).join("\n");
|
|
@@ -2612,7 +3857,7 @@ reportVitals();
|
|
|
2612
3857
|
if (!known) {` : ` if (langIdx >= 0 && !isLocale(pathname.split('/')[langIdx])) {`;
|
|
2613
3858
|
const clientEntry = `
|
|
2614
3859
|
${clientImports}
|
|
2615
|
-
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';
|
|
3860
|
+
import { setState, resumeState, clearRequestState, resetEffects, wire, isolateStateAsync, restoreState, setRefreshHook, clearMounts, flushMounts, adoptCleanups, handlers, setActionDispatcher, setLocales, setLocalePacks, ensureLocale, isLocale, localeDir, setPrefetchOverride, serializeState, setFxOwner, resetContainerFx, esc } from './runtime.js';
|
|
2616
3861
|
|
|
2617
3862
|
// I18n: the dictionaries baked at build time - the client renders any PRELOADED locale from the bundle.
|
|
2618
3863
|
setLocales(${clientLocalesJson}, '${defaultLocale}');
|
|
@@ -2836,6 +4081,8 @@ export async function $action(name, e) {
|
|
|
2836
4081
|
const box = e && e.target && e.target.closest ? e.target.closest('[data-rosetack]') : null;
|
|
2837
4082
|
return postForm(body, box || undefined, box ? box.getAttribute('data-rosetack') : undefined);
|
|
2838
4083
|
}
|
|
4084
|
+
// F17: hand the dispatcher to the runtime, so wire() can serve a server action bound to a non-delegated event (on:keydown="$action:save") the same way.
|
|
4085
|
+
setActionDispatcher($action);
|
|
2839
4086
|
|
|
2840
4087
|
export { postForm };
|
|
2841
4088
|
|
|
@@ -2867,6 +4114,16 @@ async function __withOwner(container, fn) {
|
|
|
2867
4114
|
setFxOwner(null);
|
|
2868
4115
|
}
|
|
2869
4116
|
}
|
|
4117
|
+
// View Transition on SPA swaps (B9): the DOM swap rides one cross-fade when the browser supports it; reduced-motion users and environments without.
|
|
4118
|
+
async function __swap(container, html) {
|
|
4119
|
+
const reduce = typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches;
|
|
4120
|
+
if (typeof document.startViewTransition === 'function' && !reduce) {
|
|
4121
|
+
const vt = document.startViewTransition(() => { container.innerHTML = html; });
|
|
4122
|
+
await vt.updateCallbackDone.catch(() => {});
|
|
4123
|
+
} else {
|
|
4124
|
+
container.innerHTML = html;
|
|
4125
|
+
}
|
|
4126
|
+
}
|
|
2870
4127
|
|
|
2871
4128
|
export async function start(container, pathname, initial) {
|
|
2872
4129
|
clearMounts(); // stale mounts from a failed render never fire
|
|
@@ -2889,7 +4146,7 @@ ${langDirBlock}
|
|
|
2889
4146
|
prefetchCache.delete(pathname);
|
|
2890
4147
|
__navReset(container);
|
|
2891
4148
|
restoreState(hit.state);
|
|
2892
|
-
container
|
|
4149
|
+
await __swap(container, hit.html);
|
|
2893
4150
|
await __withOwner(container, () => {
|
|
2894
4151
|
wire(container, hit.closes);
|
|
2895
4152
|
bindEvents(container);
|
|
@@ -2914,15 +4171,18 @@ ${langDirBlock}
|
|
|
2914
4171
|
if (err && err.__rosetack === 'redirect') { signal = err.path; return; }
|
|
2915
4172
|
|
|
2916
4173
|
|
|
4174
|
+
console.error('rosetack: client render failed for', pathname, err instanceof Error ? err.message : err);
|
|
2917
4175
|
broken = true;
|
|
2918
4176
|
return;
|
|
2919
4177
|
}
|
|
2920
|
-
if (!initial) container
|
|
4178
|
+
if (!initial) await __swap(container, html);
|
|
2921
4179
|
wire(container, closes);
|
|
2922
4180
|
bindEvents(container);
|
|
2923
4181
|
flushMounts();
|
|
2924
4182
|
});
|
|
2925
4183
|
if (signal === 'notFound') {
|
|
4184
|
+
// 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.
|
|
4185
|
+
if (!initial) { try { location.assign(pathname); return; } catch { } }
|
|
2926
4186
|
await paintFallback(container, notFoundFor(pathname), '<h1>404</h1><p>Page not found</p>');
|
|
2927
4187
|
return;
|
|
2928
4188
|
}
|
|
@@ -2985,11 +4245,11 @@ setRefreshHook(async () => {
|
|
|
2985
4245
|
await start(document.getElementById('app'), location.pathname, false);
|
|
2986
4246
|
});
|
|
2987
4247
|
`;
|
|
2988
|
-
await
|
|
4248
|
+
await fs3.promises.writeFile(path2.join(buildDir, "client-entry.js"), clientEntry);
|
|
2989
4249
|
if (split) {
|
|
2990
|
-
await
|
|
4250
|
+
await fs3.promises.rm(path2.join(outDir, "chunks"), { recursive: true, force: true });
|
|
2991
4251
|
await esbuild.build({
|
|
2992
|
-
entryPoints: [
|
|
4252
|
+
entryPoints: [path2.join(buildDir, "client-entry.js")],
|
|
2993
4253
|
bundle: true,
|
|
2994
4254
|
format: "esm",
|
|
2995
4255
|
platform: "browser",
|
|
@@ -3003,9 +4263,9 @@ setRefreshHook(async () => {
|
|
|
3003
4263
|
});
|
|
3004
4264
|
} else {
|
|
3005
4265
|
await esbuild.build({
|
|
3006
|
-
entryPoints: [
|
|
4266
|
+
entryPoints: [path2.join(buildDir, "client-entry.js")],
|
|
3007
4267
|
bundle: true,
|
|
3008
|
-
outfile:
|
|
4268
|
+
outfile: path2.join(outDir, "client.js"),
|
|
3009
4269
|
format: "esm",
|
|
3010
4270
|
platform: "browser",
|
|
3011
4271
|
minify: true,
|
|
@@ -3013,13 +4273,13 @@ setRefreshHook(async () => {
|
|
|
3013
4273
|
...TS_LOADER
|
|
3014
4274
|
});
|
|
3015
4275
|
}
|
|
3016
|
-
await
|
|
3017
|
-
await
|
|
3018
|
-
const publicDir =
|
|
3019
|
-
if (
|
|
3020
|
-
await
|
|
3021
|
-
const favicon =
|
|
3022
|
-
if (
|
|
4276
|
+
await fs3.promises.writeFile(path2.join(outDir, "mount.js"), MOUNT_ENTRY);
|
|
4277
|
+
await fs3.promises.rm(buildDir, { recursive: true, force: true });
|
|
4278
|
+
const publicDir = path2.join(root, "public");
|
|
4279
|
+
if (fs3.existsSync(publicDir)) {
|
|
4280
|
+
await fs3.promises.cp(publicDir, path2.join(outDir, "public"), { recursive: true });
|
|
4281
|
+
const favicon = path2.join(publicDir, "favicon.ico");
|
|
4282
|
+
if (fs3.existsSync(favicon)) await fs3.promises.copyFile(favicon, path2.join(outDir, "favicon.ico"));
|
|
3023
4283
|
}
|
|
3024
4284
|
console.log("rosetack zero-JS report:");
|
|
3025
4285
|
for (const line of buildReport(infos, compiled)) console.log(" " + line);
|
|
@@ -3033,7 +4293,7 @@ setRefreshHook(async () => {
|
|
|
3033
4293
|
g = { why: w, files: /* @__PURE__ */ new Map() };
|
|
3034
4294
|
warnGroups.set(w, g);
|
|
3035
4295
|
}
|
|
3036
|
-
const file =
|
|
4296
|
+
const file = path2.relative(root, infos[ci].filePath).replace(/\\/g, "/");
|
|
3037
4297
|
let routes = g.files.get(file);
|
|
3038
4298
|
if (!routes) {
|
|
3039
4299
|
routes = /* @__PURE__ */ new Set();
|
|
@@ -3054,13 +4314,13 @@ setRefreshHook(async () => {
|
|
|
3054
4314
|
return { routes: pages.map(({ info }) => info), bundle: bundleMode };
|
|
3055
4315
|
}
|
|
3056
4316
|
async function scanRoseFiles(root) {
|
|
3057
|
-
const pagesDir =
|
|
3058
|
-
if (!
|
|
4317
|
+
const pagesDir = path2.join(root, "src", "pages");
|
|
4318
|
+
if (!fs3.existsSync(pagesDir)) return [];
|
|
3059
4319
|
async function scan(dir) {
|
|
3060
|
-
const entries = await
|
|
4320
|
+
const entries = await fs3.promises.readdir(dir, { withFileTypes: true });
|
|
3061
4321
|
const files = [];
|
|
3062
4322
|
for (const entry of entries) {
|
|
3063
|
-
const full =
|
|
4323
|
+
const full = path2.join(dir, entry.name);
|
|
3064
4324
|
if (entry.isDirectory()) files.push(...await scan(full));
|
|
3065
4325
|
else if (entry.name.endsWith(".rose")) files.push(full);
|
|
3066
4326
|
}
|
|
@@ -3069,13 +4329,13 @@ async function scanRoseFiles(root) {
|
|
|
3069
4329
|
return scan(pagesDir);
|
|
3070
4330
|
}
|
|
3071
4331
|
async function scanComponentFiles(root) {
|
|
3072
|
-
const compDir =
|
|
3073
|
-
if (!
|
|
4332
|
+
const compDir = path2.join(root, "src", "components");
|
|
4333
|
+
if (!fs3.existsSync(compDir)) return [];
|
|
3074
4334
|
async function scan(dir) {
|
|
3075
|
-
const entries = await
|
|
4335
|
+
const entries = await fs3.promises.readdir(dir, { withFileTypes: true });
|
|
3076
4336
|
const files = [];
|
|
3077
4337
|
for (const entry of entries) {
|
|
3078
|
-
const full =
|
|
4338
|
+
const full = path2.join(dir, entry.name);
|
|
3079
4339
|
if (entry.isDirectory()) files.push(...await scan(full));
|
|
3080
4340
|
else if (entry.name.endsWith(".rose")) files.push(full);
|
|
3081
4341
|
}
|
|
@@ -3084,15 +4344,15 @@ async function scanComponentFiles(root) {
|
|
|
3084
4344
|
return scan(compDir);
|
|
3085
4345
|
}
|
|
3086
4346
|
function isAncestorDir(layoutPath, pagePath) {
|
|
3087
|
-
const layoutDir =
|
|
3088
|
-
const pageDir =
|
|
3089
|
-
return pageDir === layoutDir || pageDir.startsWith(layoutDir +
|
|
4347
|
+
const layoutDir = path2.dirname(layoutPath);
|
|
4348
|
+
const pageDir = path2.dirname(pagePath);
|
|
4349
|
+
return pageDir === layoutDir || pageDir.startsWith(layoutDir + path2.sep);
|
|
3090
4350
|
}
|
|
3091
4351
|
function getRouteInfo(filePath, root) {
|
|
3092
|
-
const pagesDir =
|
|
3093
|
-
const relative2 =
|
|
4352
|
+
const pagesDir = path2.join(root, "src", "pages");
|
|
4353
|
+
const relative2 = path2.relative(pagesDir, filePath).replace(/\\/g, "/");
|
|
3094
4354
|
const withoutExt = relative2.replace(/\.rose$/, "");
|
|
3095
|
-
const base =
|
|
4355
|
+
const base = path2.posix.basename(withoutExt);
|
|
3096
4356
|
const isComponent = filePath.replace(/\\/g, "/").includes("/src/components/");
|
|
3097
4357
|
const isLayout = !isComponent && base === "_layout";
|
|
3098
4358
|
const isNotFound = !isComponent && (base === "404" || base === "_notfound");
|