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/test.mjs
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
// src/cli/test.ts
|
|
2
|
-
import * as
|
|
2
|
+
import * as fs5 from "fs";
|
|
3
3
|
import * as os from "os";
|
|
4
|
-
import * as
|
|
4
|
+
import * as path4 from "path";
|
|
5
5
|
import { pathToFileURL as pathToFileURL2 } from "url";
|
|
6
6
|
|
|
7
7
|
// src/compiler/index.ts
|
|
8
|
-
import * as
|
|
9
|
-
import * as
|
|
8
|
+
import * as fs3 from "fs";
|
|
9
|
+
import * as path2 from "path";
|
|
10
10
|
import { pathToFileURL, fileURLToPath } from "url";
|
|
11
11
|
import * as esbuild from "esbuild";
|
|
12
12
|
|
|
@@ -45,16 +45,209 @@ function lineAt(src, match) {
|
|
|
45
45
|
return match && match.index !== void 0 ? lineOf(src, match.index) : void 0;
|
|
46
46
|
}
|
|
47
47
|
|
|
48
|
+
// src/cli/image-size.ts
|
|
49
|
+
import fs from "node:fs";
|
|
50
|
+
function readImageSize(filePath) {
|
|
51
|
+
try {
|
|
52
|
+
const fd = fs.openSync(filePath, "r");
|
|
53
|
+
const buf = Buffer.alloc(64);
|
|
54
|
+
const read = fs.readSync(fd, buf, 0, 64, 0);
|
|
55
|
+
fs.closeSync(fd);
|
|
56
|
+
if (read < 24) return null;
|
|
57
|
+
if (buf[0] === 137 && buf[1] === 80 && buf[2] === 78 && buf[3] === 71) {
|
|
58
|
+
return { width: buf.readUInt32BE(16), height: buf.readUInt32BE(20) };
|
|
59
|
+
}
|
|
60
|
+
if (buf.slice(0, 3).toString("latin1") === "GIF") {
|
|
61
|
+
return { width: buf.readUInt16LE(6), height: buf.readUInt16LE(8) };
|
|
62
|
+
}
|
|
63
|
+
if (buf.slice(0, 4).toString("latin1") === "RIFF" && buf.slice(8, 12).toString("latin1") === "WEBP") {
|
|
64
|
+
return parseWebP(buf);
|
|
65
|
+
}
|
|
66
|
+
if (buf[0] === 255 && buf[1] === 216) {
|
|
67
|
+
return parseJpeg(filePath);
|
|
68
|
+
}
|
|
69
|
+
return null;
|
|
70
|
+
} catch {
|
|
71
|
+
return null;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
function parseWebP(buf) {
|
|
75
|
+
const format = buf.slice(12, 16).toString("latin1");
|
|
76
|
+
if (format === "VP8 ") {
|
|
77
|
+
return { width: buf.readUInt16LE(26) & 16383, height: buf.readUInt16LE(28) & 16383 };
|
|
78
|
+
}
|
|
79
|
+
if (format === "VP8L") {
|
|
80
|
+
const b = buf.readUInt32LE(21);
|
|
81
|
+
return { width: (b & 16383) + 1, height: (b >> 14 & 16383) + 1 };
|
|
82
|
+
}
|
|
83
|
+
if (format === "VP8X") {
|
|
84
|
+
const w = buf.readUIntLE(24, 3) + 1;
|
|
85
|
+
const h = buf.readUIntLE(27, 3) + 1;
|
|
86
|
+
return { width: w, height: h };
|
|
87
|
+
}
|
|
88
|
+
return null;
|
|
89
|
+
}
|
|
90
|
+
function parseJpeg(filePath) {
|
|
91
|
+
const fd = fs.openSync(filePath, "r");
|
|
92
|
+
try {
|
|
93
|
+
const buf = Buffer.alloc(4);
|
|
94
|
+
let pos = 2;
|
|
95
|
+
for (let guard = 0; guard < 64; guard++) {
|
|
96
|
+
if (fs.readSync(fd, buf, 0, 4, pos) < 4) return null;
|
|
97
|
+
if (buf[0] !== 255) {
|
|
98
|
+
pos += 1;
|
|
99
|
+
continue;
|
|
100
|
+
}
|
|
101
|
+
const marker = buf[1];
|
|
102
|
+
if (marker === 216 || marker === 1 || marker >= 208 && marker <= 215) {
|
|
103
|
+
pos += 2;
|
|
104
|
+
continue;
|
|
105
|
+
}
|
|
106
|
+
const len = fs.readSync(fd, buf, 0, 2, pos + 2) < 2 ? 0 : buf.readUInt16BE(2);
|
|
107
|
+
if (marker >= 192 && marker <= 207 && marker !== 196 && marker !== 200 && marker !== 204) {
|
|
108
|
+
const seg = Buffer.alloc(8);
|
|
109
|
+
fs.readSync(fd, seg, 0, 8, pos + 4);
|
|
110
|
+
return { width: seg.readUInt16BE(3), height: seg.readUInt16BE(1) };
|
|
111
|
+
}
|
|
112
|
+
pos += 2 + len;
|
|
113
|
+
}
|
|
114
|
+
return null;
|
|
115
|
+
} finally {
|
|
116
|
+
fs.closeSync(fd);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// src/cli/content.ts
|
|
121
|
+
import fs2 from "node:fs";
|
|
122
|
+
import path from "node:path";
|
|
123
|
+
function parseFrontmatter(raw) {
|
|
124
|
+
if (!raw.startsWith("---")) return { frontmatter: {}, body: raw };
|
|
125
|
+
const end = raw.indexOf("\n---", 3);
|
|
126
|
+
if (end < 0) return { frontmatter: {}, body: raw };
|
|
127
|
+
const head = raw.slice(4, end);
|
|
128
|
+
const body = raw.slice(raw.indexOf("\n", end + 1) + 1).replace(/^\s*\n/, "");
|
|
129
|
+
const frontmatter = {};
|
|
130
|
+
for (const line of head.split("\n")) {
|
|
131
|
+
const m = /^(\w[\w-]*):\s*(.*)$/.exec(line.trim());
|
|
132
|
+
if (!m) continue;
|
|
133
|
+
const [, k, v] = m;
|
|
134
|
+
const arr = /^\[(.+)\]$/.exec(v.trim());
|
|
135
|
+
frontmatter[k] = arr ? arr[1].split(",").map((x) => x.trim().replace(/^["']|["']$/g, "")) : v.trim().replace(/^["']|["']$/g, "");
|
|
136
|
+
}
|
|
137
|
+
return { frontmatter, body };
|
|
138
|
+
}
|
|
139
|
+
function interpolate(md, vars) {
|
|
140
|
+
return md.replace(/{{(\w[\w.]*)}}/g, (_m, k) => {
|
|
141
|
+
const v = k.split(".").reduce((o, p) => o == null ? o : o[p], vars);
|
|
142
|
+
return v === void 0 || v === null ? "" : String(v);
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
function renderMarkdown(md, vars) {
|
|
146
|
+
if (vars) md = interpolate(md, vars);
|
|
147
|
+
const blocks = [];
|
|
148
|
+
let src = md.replace(/```(\w*)\n([\s\S]*?)```/g, (_m, lang, code) => {
|
|
149
|
+
blocks.push(
|
|
150
|
+
`<pre data-lang="${lang}"><code>${code.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">")}</code></pre>`
|
|
151
|
+
);
|
|
152
|
+
return `\0CODE${blocks.length - 1}\0`;
|
|
153
|
+
});
|
|
154
|
+
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(
|
|
155
|
+
/\[([^\]]+)\]\(([^)]+)\)/g,
|
|
156
|
+
'<a href="$2" rel="noopener">$1</a>'
|
|
157
|
+
);
|
|
158
|
+
const out = [];
|
|
159
|
+
let listOpen = null;
|
|
160
|
+
const closeList = () => {
|
|
161
|
+
if (listOpen) {
|
|
162
|
+
out.push(`</${listOpen}>`);
|
|
163
|
+
listOpen = null;
|
|
164
|
+
}
|
|
165
|
+
};
|
|
166
|
+
for (const line of src.split("\n")) {
|
|
167
|
+
const h = /^(#{1,4})\s+(.*)$/.exec(line);
|
|
168
|
+
const li = /^\s*[-*]\s+(.*)$/.exec(line);
|
|
169
|
+
const oli = /^\s*\d+\.\s+(.*)$/.exec(line);
|
|
170
|
+
if (h) {
|
|
171
|
+
closeList();
|
|
172
|
+
out.push(`<h${h[1].length}>${inline(h[2])}</h${h[1].length}>`);
|
|
173
|
+
} else if (li) {
|
|
174
|
+
if (listOpen !== "ul") {
|
|
175
|
+
closeList();
|
|
176
|
+
out.push("<ul>");
|
|
177
|
+
listOpen = "ul";
|
|
178
|
+
}
|
|
179
|
+
out.push(`<li>${inline(li[1])}</li>`);
|
|
180
|
+
} else if (oli) {
|
|
181
|
+
if (listOpen !== "ol") {
|
|
182
|
+
closeList();
|
|
183
|
+
out.push("<ol>");
|
|
184
|
+
listOpen = "ol";
|
|
185
|
+
}
|
|
186
|
+
out.push(`<li>${inline(oli[1])}</li>`);
|
|
187
|
+
} else if (line.trim() === "") {
|
|
188
|
+
closeList();
|
|
189
|
+
} else if (line.startsWith("\0CODE")) {
|
|
190
|
+
closeList();
|
|
191
|
+
out.push(line);
|
|
192
|
+
} else {
|
|
193
|
+
closeList();
|
|
194
|
+
out.push(`<p>${inline(line)}</p>`);
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
closeList();
|
|
198
|
+
return out.join("\n").replace(/\u0000CODE(\d+)\u0000/g, (_m, i) => blocks[Number(i)]);
|
|
199
|
+
}
|
|
200
|
+
function scanContentDir(contentDir) {
|
|
201
|
+
const collections = {};
|
|
202
|
+
if (!fs2.existsSync(contentDir)) return collections;
|
|
203
|
+
for (const coll of fs2.readdirSync(contentDir, { withFileTypes: true })) {
|
|
204
|
+
if (!coll.isDirectory()) continue;
|
|
205
|
+
const entries = [];
|
|
206
|
+
const dir = path.join(contentDir, coll.name);
|
|
207
|
+
for (const f of fs2.readdirSync(dir)) {
|
|
208
|
+
if (!f.endsWith(".md")) continue;
|
|
209
|
+
const raw = fs2.readFileSync(path.join(dir, f), "utf-8");
|
|
210
|
+
const { frontmatter, body } = parseFrontmatter(raw);
|
|
211
|
+
if (String(frontmatter.draft ?? "").toLowerCase() === "true") continue;
|
|
212
|
+
const slug = f.replace(/\.md$/, "");
|
|
213
|
+
const html = renderMarkdown(body);
|
|
214
|
+
const words = body.replace(/[#*`\[\]()>-]/g, " ").split(/\s+/).filter(Boolean).length;
|
|
215
|
+
const headings = [];
|
|
216
|
+
const tocHtml = html.replace(/<h([1-4])>([^<]+)<\/h\1>/g, (_m, lvl, txt) => {
|
|
217
|
+
const id = txt.toLowerCase().replace(/[^\w\s-]/g, "").trim().replace(/\s+/g, "-");
|
|
218
|
+
headings.push({ level: Number(lvl), text: txt, id });
|
|
219
|
+
return `<h${lvl} id="${id}">${txt}</h${lvl}>`;
|
|
220
|
+
});
|
|
221
|
+
entries.push({
|
|
222
|
+
slug,
|
|
223
|
+
frontmatter,
|
|
224
|
+
body,
|
|
225
|
+
html: tocHtml,
|
|
226
|
+
readingTime: Math.max(1, Math.round(words / 200)),
|
|
227
|
+
wordCount: words,
|
|
228
|
+
toc: headings,
|
|
229
|
+
excerpt: String(frontmatter.summary ?? "") || (html.match(/<p>([\s\S]*?)<\/p>/)?.[1] ?? "").replace(/<[^>]+>/g, "").slice(0, 160)
|
|
230
|
+
});
|
|
231
|
+
}
|
|
232
|
+
entries.sort(
|
|
233
|
+
(a, b) => String(b.frontmatter.date ?? "").localeCompare(String(a.frontmatter.date ?? ""))
|
|
234
|
+
);
|
|
235
|
+
collections[coll.name] = entries;
|
|
236
|
+
}
|
|
237
|
+
return collections;
|
|
238
|
+
}
|
|
239
|
+
globalThis.__rosetackContentMk = renderMarkdown;
|
|
240
|
+
|
|
48
241
|
// src/compiler/index.ts
|
|
49
242
|
var COMPONENT_RE = /<script>([\s\S]*?)<\/script>/;
|
|
50
243
|
var TEMPLATE_RE = /<template>([\s\S]*?)<\/template>/;
|
|
51
244
|
var HEAD_RE = /<head>([\s\S]*?)<\/head>/;
|
|
52
245
|
var STYLE_RE = /<style>([\s\S]*?)<\/style>/;
|
|
53
|
-
var DECL_RE = /(?:let|const|var)\s+(\w+)[^=]*=\s*\$(state|data)\b/g;
|
|
246
|
+
var DECL_RE = /(?:let|const|var)\s+(\w+)[^=]*=\s*\$(state|data|kv|persist)\b/g;
|
|
54
247
|
var DECL_CAST_RE = /^\s+as\s+[^;\n]+/;
|
|
55
248
|
var SETSTATE_RE = /\$setState\(([^,]+),\s*([^)]+)\)/g;
|
|
56
|
-
var SLOT_RE = /<slot\s
|
|
57
|
-
var SLOT_NAMED_RE = /<slot\s+((?=[^>]*\bname\s*=)[^>]*?)
|
|
249
|
+
var SLOT_RE = /<slot\s*\/>|<slot>([\s\S]*?)<\/slot>/g;
|
|
250
|
+
var SLOT_NAMED_RE = /<slot\s+((?=[^>]*\bname\s*=)[^>]*?)(?:\/>|>([\s\S]*?)<\/slot>)/g;
|
|
58
251
|
function encodeSlotCall(attrs) {
|
|
59
252
|
const name = /\bname\s*=\s*["'](\w+)["']/.exec(attrs)?.[1];
|
|
60
253
|
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} />' });
|
|
@@ -446,8 +639,8 @@ function stripGuardedBranches(src) {
|
|
|
446
639
|
return out.join("");
|
|
447
640
|
}
|
|
448
641
|
async function loadConfig(root) {
|
|
449
|
-
const file =
|
|
450
|
-
if (!
|
|
642
|
+
const file = path2.join(root, "rosetack.config.js");
|
|
643
|
+
if (!fs3.existsSync(file)) return { plugins: [], i18n: {} };
|
|
451
644
|
const mod = await import(pathToFileURL(file).href + `?t=${Date.now()}`);
|
|
452
645
|
return {
|
|
453
646
|
plugins: mod.default ?? [],
|
|
@@ -457,12 +650,12 @@ async function loadConfig(root) {
|
|
|
457
650
|
function resolveRoseImports(script, fromFile, registry) {
|
|
458
651
|
const imports = [];
|
|
459
652
|
const resolve3 = (spec, at) => {
|
|
460
|
-
const abs =
|
|
653
|
+
const abs = path2.resolve(path2.dirname(fromFile), spec);
|
|
461
654
|
const hit = registry.get(abs);
|
|
462
655
|
if (!hit) {
|
|
463
656
|
throw new RoseError(
|
|
464
657
|
"E-IMPORT",
|
|
465
|
-
`${
|
|
658
|
+
`${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.`,
|
|
466
659
|
{
|
|
467
660
|
file: fromFile,
|
|
468
661
|
line: lineOf(script, at),
|
|
@@ -497,16 +690,45 @@ function nodeOnlyImports(importStmts) {
|
|
|
497
690
|
}
|
|
498
691
|
return out;
|
|
499
692
|
}
|
|
500
|
-
function wireEventBindings(template, actionNames) {
|
|
693
|
+
function wireEventBindings(template, actionNames, filePath = "<template>") {
|
|
501
694
|
const bindings = [];
|
|
502
695
|
let out = "";
|
|
503
696
|
let rest = template;
|
|
697
|
+
const TARGET_MODS = { window: "w", document: "d" };
|
|
698
|
+
const MOD_PRE = {
|
|
699
|
+
preventDefault: () => "e.preventDefault()",
|
|
700
|
+
stopPropagation: () => "e.stopPropagation()",
|
|
701
|
+
self: (p) => `const __self = e.target.closest && e.target.closest('[data-${p}-' + e.type + ']'); if (__self && e.target !== __self) return;`
|
|
702
|
+
};
|
|
703
|
+
const MOD_POST = {
|
|
704
|
+
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);`
|
|
705
|
+
};
|
|
706
|
+
const KNOWN_MODS = [...Object.keys(MOD_PRE), ...Object.keys(MOD_POST), ...Object.keys(TARGET_MODS)];
|
|
504
707
|
for (; ; ) {
|
|
505
|
-
const m = /\bon:(\w+)\s*=\s*\{/.exec(rest);
|
|
708
|
+
const m = /\bon:(\w+)((?:\|\w+)*)\s*=\s*\{/.exec(rest);
|
|
506
709
|
if (!m) {
|
|
507
710
|
out += rest;
|
|
508
711
|
break;
|
|
509
712
|
}
|
|
713
|
+
const mods = m[2] ? m[2].slice(1).split("|") : [];
|
|
714
|
+
const targets = mods.filter((mod) => TARGET_MODS[mod]);
|
|
715
|
+
if (targets.length > 1) {
|
|
716
|
+
throw new RoseError(
|
|
717
|
+
"E-TEMPLATE",
|
|
718
|
+
`${filePath}: on:${m[1]} carries both |${targets.join(" and |")}`,
|
|
719
|
+
{ hint: "a handler binds to one target - the element (default), |window or |document" }
|
|
720
|
+
);
|
|
721
|
+
}
|
|
722
|
+
const prefix = targets.length ? "on" + TARGET_MODS[targets[0]] : "on";
|
|
723
|
+
for (const mod of mods) {
|
|
724
|
+
if (!KNOWN_MODS.includes(mod)) {
|
|
725
|
+
throw new RoseError(
|
|
726
|
+
"E-TEMPLATE",
|
|
727
|
+
`${filePath}: unknown event modifier |${mod}`,
|
|
728
|
+
{ 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` }
|
|
729
|
+
);
|
|
730
|
+
}
|
|
731
|
+
}
|
|
510
732
|
out += rest.slice(0, m.index);
|
|
511
733
|
let i = m.index + m[0].length;
|
|
512
734
|
let depth = 1;
|
|
@@ -528,7 +750,24 @@ function wireEventBindings(template, actionNames) {
|
|
|
528
750
|
i++;
|
|
529
751
|
}
|
|
530
752
|
const expr = rest.slice(m.index + m[0].length, i).trim();
|
|
531
|
-
|
|
753
|
+
const wrap = (body) => {
|
|
754
|
+
if (!mods.length) return body;
|
|
755
|
+
const pre = mods.filter((mod) => MOD_PRE[mod]).map((mod) => MOD_PRE[mod](prefix));
|
|
756
|
+
const post = mods.filter((mod) => MOD_POST[mod]).map((mod) => MOD_POST[mod](prefix));
|
|
757
|
+
return `(e) => {${pre.length ? " " + pre.join("; ") + ";" : ""} (${body})(e);${post.length ? " " + post.join("; ") + ";" : ""} }`;
|
|
758
|
+
};
|
|
759
|
+
if (mods.length && actionNames.has(expr)) {
|
|
760
|
+
throw new RoseError(
|
|
761
|
+
"E-TEMPLATE",
|
|
762
|
+
`${filePath}: event modifiers are not supported on the server action ${expr}`,
|
|
763
|
+
{ hint: "$action already preventDefaults - drop the modifiers, or bind a local handler that calls $action" }
|
|
764
|
+
);
|
|
765
|
+
}
|
|
766
|
+
if (mods.length) {
|
|
767
|
+
const name = `__h${bindings.length}`;
|
|
768
|
+
out += `data-${prefix}-${m[1]}="${name}"`;
|
|
769
|
+
bindings.push({ event: m[1], fn: `${name}: ${wrap(expr)}` });
|
|
770
|
+
} else if (actionNames.has(expr)) {
|
|
532
771
|
out += `data-on-${m[1]}="$action:${expr}"`;
|
|
533
772
|
} else if (/^\w+$/.test(expr)) {
|
|
534
773
|
out += `data-on-${m[1]}="${expr}"`;
|
|
@@ -545,7 +784,7 @@ function wireEventBindings(template, actionNames) {
|
|
|
545
784
|
function scanSlotDecls(filePath) {
|
|
546
785
|
let src;
|
|
547
786
|
try {
|
|
548
|
-
src =
|
|
787
|
+
src = fs3.readFileSync(filePath, "utf-8");
|
|
549
788
|
} catch {
|
|
550
789
|
return [];
|
|
551
790
|
}
|
|
@@ -599,7 +838,7 @@ function hoistImports(script) {
|
|
|
599
838
|
return { imports: imports.join("\n"), rest: rest.join("\n") };
|
|
600
839
|
}
|
|
601
840
|
async function compileComponent(filePath, publicDir, scopeKey, isApi = false, plugins = [], registry = /* @__PURE__ */ new Map()) {
|
|
602
|
-
let source = await
|
|
841
|
+
let source = await fs3.promises.readFile(filePath, "utf-8");
|
|
603
842
|
for (const p of plugins) {
|
|
604
843
|
if (!p.transform) continue;
|
|
605
844
|
try {
|
|
@@ -607,7 +846,7 @@ async function compileComponent(filePath, publicDir, scopeKey, isApi = false, pl
|
|
|
607
846
|
} catch (err) {
|
|
608
847
|
throw new RoseError(
|
|
609
848
|
"E-PLUGIN",
|
|
610
|
-
`plugin ${p.name} failed on ${
|
|
849
|
+
`plugin ${p.name} failed on ${path2.basename(filePath)}: ${err instanceof Error ? err.message : String(err)}`,
|
|
611
850
|
{ file: filePath, hint: "the error above came from inside the plugin - fix its transform() (or remove the plugin from rosetack.config.js)" }
|
|
612
851
|
);
|
|
613
852
|
}
|
|
@@ -650,7 +889,7 @@ ${hoisted.rest}`, "ssr").trim()}`,
|
|
|
650
889
|
const rawScript = roseResolved.script;
|
|
651
890
|
const roseImports = roseResolved.imports;
|
|
652
891
|
const { imports: importStmts, rest: scriptNoImports } = hoistImports(rawScript);
|
|
653
|
-
if (
|
|
892
|
+
if (path2.basename(filePath) !== "_middleware.rose") {
|
|
654
893
|
for (const spec of nodeOnlyImports(importStmts)) {
|
|
655
894
|
const at = importStmts.indexOf(spec);
|
|
656
895
|
throw new RoseError(
|
|
@@ -676,6 +915,8 @@ ${hoisted.rest}`, "ssr").trim()}`,
|
|
|
676
915
|
const hasParams = /(?:^|\n)\s*export\s+(?:(?:const|let|var)\s+|(?:async\s+)?function\s+)params\b/.test(rawScript);
|
|
677
916
|
const revalidateMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+revalidate\s*=\s*(\d+)\s*;?/);
|
|
678
917
|
const revalidate = revalidateMatch ? Number(revalidateMatch[1]) : void 0;
|
|
918
|
+
const cacheMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+cache\s*=\s*(\d+)\s*;?/);
|
|
919
|
+
const cacheSeconds = cacheMatch ? Number(cacheMatch[1]) : void 0;
|
|
679
920
|
const prefetchMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+prefetch\s*=\s*['"`](\w+)['"`]\s*;?/);
|
|
680
921
|
const prefetch = prefetchMatch ? prefetchMatch[1] : void 0;
|
|
681
922
|
if (prefetch && !["off", "hover", "viewport", "all"].includes(prefetch)) {
|
|
@@ -780,6 +1021,7 @@ ${hoisted.rest}`, "ssr").trim()}`,
|
|
|
780
1021
|
}
|
|
781
1022
|
const lifecycle = rawScript.match(/\b(?:onMount|onCleanup|refresh|adopt|\$action|\$setState)\s*\(/);
|
|
782
1023
|
if (lifecycle) clientReasons.push(`${lifecycle[0].replace(/\s*\($/, "")}()`);
|
|
1024
|
+
if (source.includes("{#defer")) clientReasons.push("{#defer} progressive content");
|
|
783
1025
|
const needsClient = clientReasons.length > 0;
|
|
784
1026
|
const jsWarnings = [];
|
|
785
1027
|
if (!needsClient) {
|
|
@@ -804,7 +1046,7 @@ ${hoisted.rest}`, "ssr").trim()}`,
|
|
|
804
1046
|
const rawTemplate = templateMatch ? templateMatch[1] : sourceNoBlocks.replace(COMPONENT_RE, "").trim();
|
|
805
1047
|
const template = scopedStyle ? injectScopeAttr(inlineImages(rawTemplate, publicDir), scopeKey) : inlineImages(rawTemplate, publicDir);
|
|
806
1048
|
const decls = extractDecls(script);
|
|
807
|
-
const stateDecls = decls.filter((d) => d.kind === "state");
|
|
1049
|
+
const stateDecls = decls.filter((d) => d.kind === "state" || d.kind === "kv" || d.kind === "persist");
|
|
808
1050
|
const setterNames = /* @__PURE__ */ new Map();
|
|
809
1051
|
stateDecls.forEach((s) => setterNames.set(s.name, `set${capitalize(s.name)}`));
|
|
810
1052
|
const declCode = (d) => {
|
|
@@ -814,6 +1056,17 @@ ${hoisted.rest}`, "ssr").trim()}`,
|
|
|
814
1056
|
}
|
|
815
1057
|
const isFn = d.expr.includes("=>") || d.expr.startsWith("function");
|
|
816
1058
|
const fn = isFn ? d.expr : `() => (${d.expr})`;
|
|
1059
|
+
if (d.kind === "persist") {
|
|
1060
|
+
return `const [${d.name}, ${setterNames.get(d.name)}] = persistState(${JSON.stringify(key)}, ${d.expr});`;
|
|
1061
|
+
}
|
|
1062
|
+
if (d.kind === "kv") {
|
|
1063
|
+
const mTtl = /^(.*)\s*,\s*(\d+)\s*$/s.exec(d.expr);
|
|
1064
|
+
const fnExpr = mTtl ? mTtl[1] : d.expr;
|
|
1065
|
+
const ttl = mTtl ? mTtl[2] : "300";
|
|
1066
|
+
return `const __had_${d.name} = hasState(${JSON.stringify(key)});
|
|
1067
|
+
const [${d.name}, set${capitalize(d.name)}] = state(${JSON.stringify(key)}, null);
|
|
1068
|
+
if (!__had_${d.name}) set${capitalize(d.name)}(await globalThis.__rosetackKvApi.kvMemo(${JSON.stringify("__kvh:" + scopeKey + ":" + d.name)}, ${fnExpr}, ${ttl}));`;
|
|
1069
|
+
}
|
|
817
1070
|
return `const __had_${d.name} = hasState(${JSON.stringify(key)});
|
|
818
1071
|
const [${d.name}, set${capitalize(d.name)}] = state(${JSON.stringify(key)}, null);
|
|
819
1072
|
if (!__had_${d.name}) set${capitalize(d.name)}(await $data(${fn}));`;
|
|
@@ -838,15 +1091,119 @@ if (!__had_${d.name}) set${capitalize(d.name)}(await $data(${fn}));`;
|
|
|
838
1091
|
const stateDeclsCode = nestedDecls.filter((d) => d.kind === "state").map(declCode).join("\n");
|
|
839
1092
|
const dataDeclsCode = nestedDecls.filter((d) => d.kind === "data").map(declCode).join("\n");
|
|
840
1093
|
const templateCalled = callifyTemplateExprs(template, stateDecls.map((s) => s.name));
|
|
841
|
-
const
|
|
842
|
-
const
|
|
1094
|
+
const imgDefaulted = templateCalled.replace(/<img\b(?![^>]*?\sloading=)/gi, '<img loading="lazy"').replace(/<img\b(?![^>]*?\sdecoding=)/gi, '<img decoding="async"');
|
|
1095
|
+
const wired = wireEventBindings(imgDefaulted, actionNames, filePath);
|
|
843
1096
|
const stateKeys = decls.map((d) => d.name);
|
|
1097
|
+
const bindBindings = [];
|
|
1098
|
+
let bindCounter = 0;
|
|
1099
|
+
const bindExpanded = wired.template.replace(
|
|
1100
|
+
/\sbind:(value|checked|this)\s*=\s*\{([\w$]+)(?:\(\))?\}/g,
|
|
1101
|
+
(whole, kind, name) => {
|
|
1102
|
+
if (!stateKeys.includes(name)) {
|
|
1103
|
+
throw new Error(
|
|
1104
|
+
`${filePath}: bind:${kind}={${name}} must name a $state declaration` + (stateKeys.length ? ` (state keys here: ${stateKeys.join(", ")})` : " (this file declares no $state)")
|
|
1105
|
+
);
|
|
1106
|
+
}
|
|
1107
|
+
if (kind === "this") return ` data-bind-this="${name}"`;
|
|
1108
|
+
const setter = setterNames.get(name);
|
|
1109
|
+
const evt = kind === "checked" ? "change" : "input";
|
|
1110
|
+
const hname = `__rvbind_${scopeKey.replace(/\W/g, "_")}_${bindCounter++}`;
|
|
1111
|
+
bindBindings.push({
|
|
1112
|
+
event: evt,
|
|
1113
|
+
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); }`
|
|
1114
|
+
});
|
|
1115
|
+
const evtAttr = kind === "checked" ? ` data-on-change="${hname}"` : ` data-on-input="${hname}" data-on-change="${hname}"`;
|
|
1116
|
+
return ` ${kind}={${name}()}${evtAttr}`;
|
|
1117
|
+
}
|
|
1118
|
+
);
|
|
844
1119
|
const comps = new Map(roseImports.map((r) => {
|
|
845
|
-
const abs =
|
|
1120
|
+
const abs = path2.resolve(path2.dirname(filePath), r.specifier);
|
|
846
1121
|
const hit = registry.get(abs);
|
|
847
1122
|
return [r.name, { index: hit.index, slots: hit.slots }];
|
|
848
1123
|
}));
|
|
849
|
-
const
|
|
1124
|
+
const groupBindings = [];
|
|
1125
|
+
let groupCounter = 0;
|
|
1126
|
+
const TAG_SCAN_RE = /<([a-zA-Z][^\s>/]*)((?:[^>"']|"[^"]*"|'[^']*')*?)(\/?)>/g;
|
|
1127
|
+
const groupExpanded = (() => {
|
|
1128
|
+
if (!bindExpanded.includes("bind:group")) return bindExpanded;
|
|
1129
|
+
let out = "";
|
|
1130
|
+
let pos2 = 0;
|
|
1131
|
+
let m;
|
|
1132
|
+
TAG_SCAN_RE.lastIndex = 0;
|
|
1133
|
+
while (m = TAG_SCAN_RE.exec(bindExpanded)) {
|
|
1134
|
+
const [whole, tag, attrs, selfClose] = m;
|
|
1135
|
+
const gm = /\sbind:group\s*=\s*\{([\w$]+)(?:\(\))?\}/.exec(attrs);
|
|
1136
|
+
if (!gm) continue;
|
|
1137
|
+
const name = gm[1];
|
|
1138
|
+
if (!stateKeys.includes(name)) {
|
|
1139
|
+
throw new RoseError(
|
|
1140
|
+
"E-TEMPLATE",
|
|
1141
|
+
`${filePath}: bind:group={${name}} must name a $state declaration`,
|
|
1142
|
+
{ hint: "the group state holds the selected value (radio) or an ARRAY of checked values (checkbox) - declare it: let " + name + ' = $state("")' }
|
|
1143
|
+
);
|
|
1144
|
+
}
|
|
1145
|
+
if (!/\stype\s*=\s*["'](radio|checkbox)["']/.test(attrs)) {
|
|
1146
|
+
throw new RoseError(
|
|
1147
|
+
"E-TEMPLATE",
|
|
1148
|
+
`${filePath}: bind:group is for radio and checkbox inputs`,
|
|
1149
|
+
{ 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([]))' }
|
|
1150
|
+
);
|
|
1151
|
+
}
|
|
1152
|
+
const isArrayGroup = /\stype\s*=\s*["']checkbox["']/.test(attrs);
|
|
1153
|
+
const vm = /\svalue\s*=\s*"([^"]*)"|\svalue\s*=\s*'([^']*)'/.exec(attrs);
|
|
1154
|
+
if (!vm || /\{/.test(vm[0])) {
|
|
1155
|
+
throw new RoseError(
|
|
1156
|
+
"E-TEMPLATE",
|
|
1157
|
+
`${filePath}: a bind:group input needs a static value attribute`,
|
|
1158
|
+
{ hint: '<input type="radio" value="free" bind:group={plan}> - the value IS what the state receives' }
|
|
1159
|
+
);
|
|
1160
|
+
}
|
|
1161
|
+
if (/\schecked\s*=/.test(attrs)) {
|
|
1162
|
+
throw new RoseError(
|
|
1163
|
+
"E-TEMPLATE",
|
|
1164
|
+
`${filePath}: a bind:group input cannot also carry checked=`,
|
|
1165
|
+
{ hint: "the group state alone decides which inputs are checked" }
|
|
1166
|
+
);
|
|
1167
|
+
}
|
|
1168
|
+
const setter = setterNames.get(name);
|
|
1169
|
+
const hname = `__rvbg_${scopeKey.replace(/\W/g, "_")}_${groupCounter++}`;
|
|
1170
|
+
const groupValue = JSON.stringify(vm[1] ?? vm[2]);
|
|
1171
|
+
const checkedExpr = isArrayGroup ? `${name}().includes(${groupValue})` : `${name}() === ${groupValue}`;
|
|
1172
|
+
const handlerBody = isArrayGroup ? `${setter}(e.target.checked ? [...${name}(), ${groupValue}] : ${name}().filter((x) => x !== ${groupValue}))` : `${setter}(e.target.value)`;
|
|
1173
|
+
groupBindings.push({ event: "change", fn: `${hname}: (e) => { ${handlerBody}; }` });
|
|
1174
|
+
const newAttrs = attrs.replace(gm[0], ` checked={${checkedExpr}} data-on-change="${hname}"`);
|
|
1175
|
+
out += bindExpanded.slice(pos2, m.index) + `<${tag}${newAttrs}${selfClose}>`;
|
|
1176
|
+
pos2 = m.index + whole.length;
|
|
1177
|
+
}
|
|
1178
|
+
if (pos2 === 0) return bindExpanded;
|
|
1179
|
+
out += bindExpanded.slice(pos2);
|
|
1180
|
+
return out;
|
|
1181
|
+
})();
|
|
1182
|
+
const eventBindings = wired.bindings.concat(bindBindings, groupBindings);
|
|
1183
|
+
const useExpanded = groupExpanded.replace(
|
|
1184
|
+
/\suse:([\w-]+)(\s*=\s*\{([\s\S]*?)\})?/g,
|
|
1185
|
+
(_w, name, hasParam, expr) => hasParam ? ` data-use="${name}" data-use-param={JSON.stringify(${expr})}` : ` data-use="${name}"`
|
|
1186
|
+
);
|
|
1187
|
+
const classExpanded = expandClassDirectives(useExpanded, filePath);
|
|
1188
|
+
const styleExpanded = expandStyleDirectives(classExpanded, filePath);
|
|
1189
|
+
const keyExpanded = expandKeyBlocks(styleExpanded, filePath);
|
|
1190
|
+
const elseExpanded = expandIfElse(keyExpanded);
|
|
1191
|
+
const deferExpanded = expandDeferBlocks(elseExpanded);
|
|
1192
|
+
const fbExpanded = expandBoundaryFallbacks(deferExpanded.template, filePath);
|
|
1193
|
+
const ssrTemplate = rewriteQuotedExprAttrs(fbExpanded.replace(SLOT_NAMED_RE, (_w, attrs, fallback) => {
|
|
1194
|
+
const call = `{__slot(${encodeSlotCall(attrs)})}`;
|
|
1195
|
+
if (fallback) {
|
|
1196
|
+
if (/\{[^{}]*\}/.test(fallback)) {
|
|
1197
|
+
throw new RoseError(
|
|
1198
|
+
"E-TEMPLATE",
|
|
1199
|
+
`${filePath}: slot fallback content must be static markup`,
|
|
1200
|
+
{ 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" }
|
|
1201
|
+
);
|
|
1202
|
+
}
|
|
1203
|
+
return `{__slot(${encodeSlotCall(attrs)}, ${JSON.stringify(fallback)})}`;
|
|
1204
|
+
}
|
|
1205
|
+
return call;
|
|
1206
|
+
}).replace(SLOT_RE, (_w, fallback) => fallback && fallback.trim() ? `{__slotDefault(${JSON.stringify(fallback)})}` : "{__slot__}"), comps);
|
|
850
1207
|
assertKnownDirectives(ssrTemplate, filePath);
|
|
851
1208
|
const compiledTemplate = compileTemplate(ssrTemplate, "h", "__c", null, 0, true, comps);
|
|
852
1209
|
const compiledHead = headContent.trim() ? compileHead(headContent) : "";
|
|
@@ -855,7 +1212,7 @@ if (!__had_${d.name}) set${capitalize(d.name)}(await $data(${fn}));`;
|
|
|
855
1212
|
${actions.map((a) => a.stmt).join("\n")}` : exportStmts;
|
|
856
1213
|
const ssrGuard = guard ? `
|
|
857
1214
|
${guard}` : "";
|
|
858
|
-
const isMiddleware =
|
|
1215
|
+
const isMiddleware = path2.basename(filePath) === "_middleware.rose";
|
|
859
1216
|
const ssr = isMiddleware ? `${RUNTIME_IMPORTS}
|
|
860
1217
|
|
|
861
1218
|
${importStmts}
|
|
@@ -864,8 +1221,8 @@ ${ssrExports}
|
|
|
864
1221
|
${ssrGuard}
|
|
865
1222
|
|
|
866
1223
|
${cleanScript}
|
|
867
|
-
` : generateSSR(cleanScript, compiledTemplate, stateDeclsCode, ssrExports, compiledHead, props, hasNamedSlots, importStmts, isComponent, ssrGuard, actions.length > 0, dataDeclsCode);
|
|
868
|
-
const client = generateClient(cleanScript, compiledTemplate, stateDeclsCode, eventBindings, exportStmts, compiledHead, props, hasNamedSlots, importStmts, isComponent, dataDeclsCode);
|
|
1224
|
+
` : generateSSR(cleanScript + deferBootCode(deferExpanded.count, deferExpanded.holds), compiledTemplate, stateDeclsCode, ssrExports, compiledHead, props, hasNamedSlots, importStmts, isComponent, ssrGuard, actions.length > 0, dataDeclsCode);
|
|
1225
|
+
const client = generateClient(cleanScript + deferBootCode(deferExpanded.count, deferExpanded.holds), compiledTemplate, stateDeclsCode, eventBindings, exportStmts, compiledHead, props, hasNamedSlots, importStmts, isComponent, dataDeclsCode);
|
|
869
1226
|
return {
|
|
870
1227
|
ssr: rewriteRoseImports(ssr, "ssr"),
|
|
871
1228
|
client: rewriteRoseImports(client, "client"),
|
|
@@ -876,6 +1233,7 @@ ${cleanScript}
|
|
|
876
1233
|
hasParams,
|
|
877
1234
|
usesContext,
|
|
878
1235
|
revalidate,
|
|
1236
|
+
cache: cacheSeconds,
|
|
879
1237
|
csr,
|
|
880
1238
|
shell,
|
|
881
1239
|
buffer,
|
|
@@ -1066,6 +1424,20 @@ function extractExports(script) {
|
|
|
1066
1424
|
out += script.slice(pos);
|
|
1067
1425
|
return { clean: out, exports: stmts.join("\n"), actions, props, guard: guards.join("\n") };
|
|
1068
1426
|
}
|
|
1427
|
+
var REGEX_PRECEDERS = new Set("(,=:[!&|?{};+-*%<>~^".split(""));
|
|
1428
|
+
function isRegexStart(src, i) {
|
|
1429
|
+
let j = i - 1;
|
|
1430
|
+
while (j >= 0 && /\s/.test(src[j])) j--;
|
|
1431
|
+
if (j < 0) return true;
|
|
1432
|
+
const p = src[j];
|
|
1433
|
+
if (REGEX_PRECEDERS.has(p)) return true;
|
|
1434
|
+
if (/[A-Za-z0-9_$]/.test(p)) {
|
|
1435
|
+
const w = /([A-Za-z_$][A-Za-z0-9_$]*)$/.exec(src.slice(0, j + 1));
|
|
1436
|
+
if (!w) return false;
|
|
1437
|
+
return ["return", "typeof", "instanceof", "in", "of", "new", "delete", "void", "throw", "case", "do", "else"].includes(w[1]);
|
|
1438
|
+
}
|
|
1439
|
+
return false;
|
|
1440
|
+
}
|
|
1069
1441
|
function extractDecls(script) {
|
|
1070
1442
|
const decls = [];
|
|
1071
1443
|
DECL_RE.lastIndex = 0;
|
|
@@ -1157,6 +1529,35 @@ function braceDepthAt(src, index) {
|
|
|
1157
1529
|
i = close === -1 ? src.length : close + 2;
|
|
1158
1530
|
continue;
|
|
1159
1531
|
}
|
|
1532
|
+
if (ch === "/" && isRegexStart(src, i)) {
|
|
1533
|
+
i++;
|
|
1534
|
+
let inClass = false;
|
|
1535
|
+
while (i < index) {
|
|
1536
|
+
const c2 = src[i];
|
|
1537
|
+
if (c2 === "\\") {
|
|
1538
|
+
i += 2;
|
|
1539
|
+
continue;
|
|
1540
|
+
}
|
|
1541
|
+
if (inClass) {
|
|
1542
|
+
if (c2 === "]") inClass = false;
|
|
1543
|
+
i++;
|
|
1544
|
+
continue;
|
|
1545
|
+
}
|
|
1546
|
+
if (c2 === "[") {
|
|
1547
|
+
inClass = true;
|
|
1548
|
+
i++;
|
|
1549
|
+
continue;
|
|
1550
|
+
}
|
|
1551
|
+
if (c2 === "/") {
|
|
1552
|
+
i++;
|
|
1553
|
+
break;
|
|
1554
|
+
}
|
|
1555
|
+
if (c2 === "\n") break;
|
|
1556
|
+
i++;
|
|
1557
|
+
}
|
|
1558
|
+
while (i < index && /[a-z]/.test(src[i])) i++;
|
|
1559
|
+
continue;
|
|
1560
|
+
}
|
|
1160
1561
|
if (ch === "{") depth++;
|
|
1161
1562
|
else if (ch === "}") depth--;
|
|
1162
1563
|
i++;
|
|
@@ -1167,8 +1568,410 @@ function autoCall(expr) {
|
|
|
1167
1568
|
const e = expr.trim();
|
|
1168
1569
|
return /^[A-Za-z_$][\w$]*$/.test(e) ? `${e}()` : e;
|
|
1169
1570
|
}
|
|
1571
|
+
var DEFER_ENABLED = true;
|
|
1572
|
+
function expandKeyBlocks(template, filePath) {
|
|
1573
|
+
if (!template.includes("{#key")) return template;
|
|
1574
|
+
for (let pass = 0; pass < 10; pass++) {
|
|
1575
|
+
const OPEN_RE = /\{#key\s+([^}]+)\}/g;
|
|
1576
|
+
OPEN_RE.lastIndex = 0;
|
|
1577
|
+
const openM = OPEN_RE.exec(template);
|
|
1578
|
+
if (!openM) return template;
|
|
1579
|
+
const expr = openM[1].trim();
|
|
1580
|
+
const bodyStart = openM.index + openM[0].length;
|
|
1581
|
+
const TOK_RE = /\{[#\/](?:key|if|each|boundary|island)\b[^}]*\}/g;
|
|
1582
|
+
TOK_RE.lastIndex = bodyStart;
|
|
1583
|
+
let depth = 1;
|
|
1584
|
+
let closeAt = -1;
|
|
1585
|
+
let tm;
|
|
1586
|
+
while (tm = TOK_RE.exec(template)) {
|
|
1587
|
+
if (tm[0].startsWith("{#")) {
|
|
1588
|
+
depth++;
|
|
1589
|
+
continue;
|
|
1590
|
+
}
|
|
1591
|
+
depth--;
|
|
1592
|
+
if (depth === 0) {
|
|
1593
|
+
closeAt = tm.index;
|
|
1594
|
+
break;
|
|
1595
|
+
}
|
|
1596
|
+
}
|
|
1597
|
+
if (closeAt < 0) {
|
|
1598
|
+
throw new RoseError(
|
|
1599
|
+
"E-TEMPLATE",
|
|
1600
|
+
`${filePath}: {#key ${expr}} is never closed`,
|
|
1601
|
+
{ hint: "every {#key} needs its {/key}" }
|
|
1602
|
+
);
|
|
1603
|
+
}
|
|
1604
|
+
template = template.slice(0, openM.index) + `{#each [${expr}] as __rvkv}` + template.slice(bodyStart, closeAt) + "{/each}" + template.slice(closeAt + "{/key}".length);
|
|
1605
|
+
}
|
|
1606
|
+
return template;
|
|
1607
|
+
}
|
|
1608
|
+
function expandIfElseOnce(template) {
|
|
1609
|
+
const TOK_RE = /\{#(?:if|each|boundary|island)\b[^}]*\}|\{\/(?:if|each|boundary|island)\s*\}|\{:else(?:\s+if\s+[^}]*)?\}/g;
|
|
1610
|
+
let out = "";
|
|
1611
|
+
let pos = 0;
|
|
1612
|
+
let changed = false;
|
|
1613
|
+
for (; ; ) {
|
|
1614
|
+
const openM = /\{#(if|each)\s+([^}]+)\}/g.exec(template.slice(pos));
|
|
1615
|
+
if (!openM) {
|
|
1616
|
+
out += template.slice(pos);
|
|
1617
|
+
break;
|
|
1618
|
+
}
|
|
1619
|
+
const kind = openM[1];
|
|
1620
|
+
const head = openM[2];
|
|
1621
|
+
const start = pos + openM.index;
|
|
1622
|
+
const cond = kind === "if" ? head.trim() : "";
|
|
1623
|
+
const bodyStart = start + openM[0].length;
|
|
1624
|
+
out += template.slice(pos, start);
|
|
1625
|
+
TOK_RE.lastIndex = bodyStart;
|
|
1626
|
+
let depth = 1;
|
|
1627
|
+
let closeAt = -1;
|
|
1628
|
+
let closeLen = 0;
|
|
1629
|
+
const elses = [];
|
|
1630
|
+
let tm;
|
|
1631
|
+
while (tm = TOK_RE.exec(template)) {
|
|
1632
|
+
const tok = tm[0];
|
|
1633
|
+
if (tok.startsWith("{:else")) {
|
|
1634
|
+
if (depth === 1) {
|
|
1635
|
+
const condM = /^\{:else\s+if\s+([^}]*)\}$/.exec(tok);
|
|
1636
|
+
elses.push({ at: tm.index, len: tok.length, cond: condM ? condM[1].trim() : null });
|
|
1637
|
+
}
|
|
1638
|
+
continue;
|
|
1639
|
+
}
|
|
1640
|
+
if (tok.startsWith("{#")) {
|
|
1641
|
+
depth++;
|
|
1642
|
+
continue;
|
|
1643
|
+
}
|
|
1644
|
+
depth--;
|
|
1645
|
+
if (depth === 0) {
|
|
1646
|
+
closeAt = tm.index;
|
|
1647
|
+
closeLen = tok.length;
|
|
1648
|
+
break;
|
|
1649
|
+
}
|
|
1650
|
+
}
|
|
1651
|
+
if (closeAt < 0 || elses.length === 0) {
|
|
1652
|
+
out += template.slice(start, closeAt < 0 ? template.length : closeAt + closeLen);
|
|
1653
|
+
if (closeAt < 0) break;
|
|
1654
|
+
pos = closeAt + closeLen;
|
|
1655
|
+
continue;
|
|
1656
|
+
}
|
|
1657
|
+
const body = template.slice(bodyStart, closeAt);
|
|
1658
|
+
if (kind === "each") {
|
|
1659
|
+
const lastBare = [...elses].reverse().find((e) => e.cond === null);
|
|
1660
|
+
if (!lastBare) {
|
|
1661
|
+
out += template.slice(start, closeAt + closeLen);
|
|
1662
|
+
pos = closeAt + closeLen;
|
|
1663
|
+
continue;
|
|
1664
|
+
}
|
|
1665
|
+
const relLast = lastBare.at - bodyStart;
|
|
1666
|
+
const eachBody = body.slice(0, relLast);
|
|
1667
|
+
const elseBody = body.slice(relLast + lastBare.len);
|
|
1668
|
+
const itemsExpr = head.replace(/\s+as\s+[\w,\s]*$/, "").trim();
|
|
1669
|
+
out += template.slice(start, bodyStart) + eachBody + `{/each}{#if !(${itemsExpr}.length)}${elseBody}{/if}`;
|
|
1670
|
+
pos = closeAt + closeLen;
|
|
1671
|
+
changed = true;
|
|
1672
|
+
continue;
|
|
1673
|
+
}
|
|
1674
|
+
const branches = [];
|
|
1675
|
+
let cursor = 0;
|
|
1676
|
+
for (let i = 0; i < elses.length; i++) {
|
|
1677
|
+
const e = elses[i];
|
|
1678
|
+
const rel = e.at - bodyStart;
|
|
1679
|
+
branches.push({ cond: i === 0 ? null : elses[i - 1].cond, body: body.slice(cursor, rel) });
|
|
1680
|
+
cursor = rel + e.len;
|
|
1681
|
+
}
|
|
1682
|
+
branches.push({ cond: elses[elses.length - 1].cond, body: body.slice(cursor) });
|
|
1683
|
+
const first = branches.shift();
|
|
1684
|
+
const build2 = (bs) => {
|
|
1685
|
+
if (!bs.length) return "";
|
|
1686
|
+
const head2 = bs[0];
|
|
1687
|
+
const rest = bs.slice(1);
|
|
1688
|
+
if (head2.cond == null) return head2.body;
|
|
1689
|
+
let s = `{#if ${head2.cond}}${head2.body}{/if}`;
|
|
1690
|
+
if (rest.length) s += `{#if !(${head2.cond})}` + build2(rest) + `{/if}`;
|
|
1691
|
+
return s;
|
|
1692
|
+
};
|
|
1693
|
+
let emitted = `{#if ${cond}}${first.body}{/if}`;
|
|
1694
|
+
if (branches.length) emitted += `{#if !(${cond})}` + build2(branches) + `{/if}`;
|
|
1695
|
+
out += emitted;
|
|
1696
|
+
pos = closeAt + closeLen;
|
|
1697
|
+
changed = true;
|
|
1698
|
+
}
|
|
1699
|
+
return { template: out, changed };
|
|
1700
|
+
}
|
|
1701
|
+
function expandClassDirectives(template, filePath) {
|
|
1702
|
+
if (!template.includes("class:")) return template;
|
|
1703
|
+
const TAG_RE = /<([a-zA-Z][^\s>/]*)((?:[^>"']|"[^"]*"|'[^']*')*?)(\/?)>/g;
|
|
1704
|
+
let out = "";
|
|
1705
|
+
let pos = 0;
|
|
1706
|
+
let m;
|
|
1707
|
+
TAG_RE.lastIndex = 0;
|
|
1708
|
+
while (m = TAG_RE.exec(template)) {
|
|
1709
|
+
const [whole, tag, attrs, selfClose] = m;
|
|
1710
|
+
if (!attrs.includes("class:")) continue;
|
|
1711
|
+
const pairs = [];
|
|
1712
|
+
const NAME_RE = /\sclass:([\w-]+)\s*=\s*\{/g;
|
|
1713
|
+
let nm;
|
|
1714
|
+
while (nm = NAME_RE.exec(attrs)) {
|
|
1715
|
+
let i = nm.index + nm[0].length;
|
|
1716
|
+
let depth = 1;
|
|
1717
|
+
while (i < attrs.length && depth > 0) {
|
|
1718
|
+
const ch = attrs[i];
|
|
1719
|
+
if (ch === '"' || ch === "'") {
|
|
1720
|
+
i = skipQuoted(attrs, i);
|
|
1721
|
+
continue;
|
|
1722
|
+
}
|
|
1723
|
+
if (ch === "{") depth++;
|
|
1724
|
+
else if (ch === "}") depth--;
|
|
1725
|
+
i++;
|
|
1726
|
+
}
|
|
1727
|
+
if (depth !== 0) {
|
|
1728
|
+
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" });
|
|
1729
|
+
}
|
|
1730
|
+
pairs.push({ name: nm[1], expr: attrs.slice(nm.index + nm[0].length, i - 1), start: nm.index, end: i });
|
|
1731
|
+
}
|
|
1732
|
+
const clsRe = /(\sclass\s*=\s*)("([^"]*)"|'([^']*)'|\{[^}]*\})/;
|
|
1733
|
+
const clsM = clsRe.exec(attrs);
|
|
1734
|
+
if (clsM && clsM[2].startsWith("{")) {
|
|
1735
|
+
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="..."' });
|
|
1736
|
+
}
|
|
1737
|
+
const staticCls = clsM ? clsM[3] ?? clsM[4] ?? "" : "";
|
|
1738
|
+
let closure = `(${JSON.stringify(staticCls)}`;
|
|
1739
|
+
for (const p of pairs) {
|
|
1740
|
+
closure += `+((${p.expr})?${JSON.stringify(" " + p.name)}:'')`;
|
|
1741
|
+
}
|
|
1742
|
+
closure += `)`;
|
|
1743
|
+
let newAttrs = attrs;
|
|
1744
|
+
for (let k = pairs.length - 1; k >= 0; k--) {
|
|
1745
|
+
newAttrs = newAttrs.slice(0, pairs[k].start) + newAttrs.slice(pairs[k].end);
|
|
1746
|
+
}
|
|
1747
|
+
if (clsM) {
|
|
1748
|
+
newAttrs = newAttrs.replace(clsRe, ` class={${closure}}`);
|
|
1749
|
+
} else {
|
|
1750
|
+
newAttrs = ` class={${closure}}` + newAttrs;
|
|
1751
|
+
}
|
|
1752
|
+
out += template.slice(pos, m.index) + `<${tag}${newAttrs}${selfClose}>`;
|
|
1753
|
+
pos = m.index + whole.length;
|
|
1754
|
+
}
|
|
1755
|
+
if (pos === 0) return template;
|
|
1756
|
+
out += template.slice(pos);
|
|
1757
|
+
return out;
|
|
1758
|
+
}
|
|
1759
|
+
function expandStyleDirectives(template, filePath) {
|
|
1760
|
+
if (!template.includes("style:")) return template;
|
|
1761
|
+
const TAG_RE = /<([a-zA-Z][^\s>/]*)((?:[^>"']|"[^"]*"|'[^']*')*?)(\/?)>/g;
|
|
1762
|
+
let out = "";
|
|
1763
|
+
let pos = 0;
|
|
1764
|
+
let m;
|
|
1765
|
+
TAG_RE.lastIndex = 0;
|
|
1766
|
+
while (m = TAG_RE.exec(template)) {
|
|
1767
|
+
const [whole, tag, attrs, selfClose] = m;
|
|
1768
|
+
if (!attrs.includes("style:")) continue;
|
|
1769
|
+
const pairs = [];
|
|
1770
|
+
const NAME_RE = /\sstyle:([\w-]+)\s*=\s*\{/g;
|
|
1771
|
+
let nm;
|
|
1772
|
+
while (nm = NAME_RE.exec(attrs)) {
|
|
1773
|
+
let i = nm.index + nm[0].length;
|
|
1774
|
+
let depth = 1;
|
|
1775
|
+
while (i < attrs.length && depth > 0) {
|
|
1776
|
+
const ch = attrs[i];
|
|
1777
|
+
if (ch === '"' || ch === "'") {
|
|
1778
|
+
i = skipQuoted(attrs, i);
|
|
1779
|
+
continue;
|
|
1780
|
+
}
|
|
1781
|
+
if (ch === "{") depth++;
|
|
1782
|
+
else if (ch === "}") depth--;
|
|
1783
|
+
i++;
|
|
1784
|
+
}
|
|
1785
|
+
if (depth !== 0) {
|
|
1786
|
+
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" });
|
|
1787
|
+
}
|
|
1788
|
+
pairs.push({ prop: nm[1], expr: attrs.slice(nm.index + nm[0].length, i - 1), start: nm.index, end: i });
|
|
1789
|
+
}
|
|
1790
|
+
const styleRe = /(\sstyle\s*=\s*)("([^"]*)"|'([^']*)'|\{[^}]*\})/;
|
|
1791
|
+
const stM = styleRe.exec(attrs);
|
|
1792
|
+
if (stM && stM[2].startsWith("{")) {
|
|
1793
|
+
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}' });
|
|
1794
|
+
}
|
|
1795
|
+
const staticStyle = stM ? stM[3] ?? stM[4] ?? "" : "";
|
|
1796
|
+
let closure = `${JSON.stringify(staticStyle.endsWith(";") || staticStyle === "" ? staticStyle : staticStyle + ";")}`;
|
|
1797
|
+
for (const p of pairs) {
|
|
1798
|
+
closure += `+${JSON.stringify(p.prop + ":")}+(${p.expr})+';'`;
|
|
1799
|
+
}
|
|
1800
|
+
let newAttrs = attrs;
|
|
1801
|
+
for (let k = pairs.length - 1; k >= 0; k--) {
|
|
1802
|
+
newAttrs = newAttrs.slice(0, pairs[k].start) + newAttrs.slice(pairs[k].end);
|
|
1803
|
+
}
|
|
1804
|
+
if (stM) {
|
|
1805
|
+
newAttrs = newAttrs.replace(styleRe, ` style={${closure}}`);
|
|
1806
|
+
} else {
|
|
1807
|
+
newAttrs = ` style={${closure}}` + newAttrs;
|
|
1808
|
+
}
|
|
1809
|
+
out += template.slice(pos, m.index) + `<${tag}${newAttrs}${selfClose}>`;
|
|
1810
|
+
pos = m.index + whole.length;
|
|
1811
|
+
}
|
|
1812
|
+
if (pos === 0) return template;
|
|
1813
|
+
out += template.slice(pos);
|
|
1814
|
+
return out;
|
|
1815
|
+
}
|
|
1816
|
+
function expandBoundaryFallbacks(template, filePath) {
|
|
1817
|
+
if (!template.includes("{:fallback")) return template;
|
|
1818
|
+
for (let pass = 0; pass < 10; pass++) {
|
|
1819
|
+
const TOK_RE = /\{#boundary\}|\{\/boundary\}|\{:fallback\}/g;
|
|
1820
|
+
let out = "";
|
|
1821
|
+
let pos = 0;
|
|
1822
|
+
let changed = false;
|
|
1823
|
+
let tm;
|
|
1824
|
+
while (tm = TOK_RE.exec(template)) {
|
|
1825
|
+
if (tm[0] !== "{#boundary}") continue;
|
|
1826
|
+
const start = tm.index;
|
|
1827
|
+
const bodyStart = start + tm[0].length;
|
|
1828
|
+
let depth = 1;
|
|
1829
|
+
let closeAt = -1;
|
|
1830
|
+
let tm2;
|
|
1831
|
+
while (tm2 = TOK_RE.exec(template)) {
|
|
1832
|
+
if (tm2[0] === "{#boundary}") {
|
|
1833
|
+
depth++;
|
|
1834
|
+
continue;
|
|
1835
|
+
}
|
|
1836
|
+
if (tm2[0] === "{/boundary}") {
|
|
1837
|
+
depth--;
|
|
1838
|
+
if (depth === 0) {
|
|
1839
|
+
closeAt = tm2.index;
|
|
1840
|
+
break;
|
|
1841
|
+
}
|
|
1842
|
+
}
|
|
1843
|
+
}
|
|
1844
|
+
if (closeAt < 0) break;
|
|
1845
|
+
const body = template.slice(bodyStart, closeAt);
|
|
1846
|
+
const BTOK2 = /\{#(boundary|if|each|key|island)(?:\s+[^}]*)?\}|\{\/(?:boundary|if|each|key|island)\s*\}|\{:fallback\}/g;
|
|
1847
|
+
const kindStack = ["boundary"];
|
|
1848
|
+
let d = 1;
|
|
1849
|
+
let fbAt = -1;
|
|
1850
|
+
let fbLen = 0;
|
|
1851
|
+
let tm3;
|
|
1852
|
+
BTOK2.lastIndex = 0;
|
|
1853
|
+
while (tm3 = BTOK2.exec(body)) {
|
|
1854
|
+
const tok = tm3[0];
|
|
1855
|
+
if (tok === "{:fallback}") {
|
|
1856
|
+
const top = kindStack[kindStack.length - 1];
|
|
1857
|
+
if (top !== "boundary") {
|
|
1858
|
+
throw new RoseError(
|
|
1859
|
+
"E-TEMPLATE",
|
|
1860
|
+
`${filePath}: {:fallback} must sit directly inside a {#boundary} block`,
|
|
1861
|
+
{ hint: "move it out of the {#if}/{#each} it sits in, or keep the conditional fallback in the parent" }
|
|
1862
|
+
);
|
|
1863
|
+
}
|
|
1864
|
+
if (fbAt >= 0) {
|
|
1865
|
+
throw new RoseError("E-TEMPLATE", `${filePath}: a {#boundary} can carry only one {:fallback}`, { hint: "remove the extra {:fallback} segment" });
|
|
1866
|
+
}
|
|
1867
|
+
fbAt = tm3.index;
|
|
1868
|
+
fbLen = tok.length;
|
|
1869
|
+
continue;
|
|
1870
|
+
}
|
|
1871
|
+
if (tok.startsWith("{#")) {
|
|
1872
|
+
d++;
|
|
1873
|
+
kindStack.push(tok.slice(2, tok.length - 1).trim().split(/\s/)[0]);
|
|
1874
|
+
continue;
|
|
1875
|
+
}
|
|
1876
|
+
d--;
|
|
1877
|
+
kindStack.pop();
|
|
1878
|
+
}
|
|
1879
|
+
if (fbAt < 0) continue;
|
|
1880
|
+
const custom = body.slice(0, fbAt);
|
|
1881
|
+
const fbMarkup = body.slice(fbAt + fbLen);
|
|
1882
|
+
const b64 = Buffer.from(fbMarkup, "utf-8").toString("base64");
|
|
1883
|
+
out += template.slice(pos, start) + `{#boundary __fb="${b64}"}` + custom + "{/boundary}";
|
|
1884
|
+
pos = closeAt + "{/boundary}".length;
|
|
1885
|
+
changed = true;
|
|
1886
|
+
}
|
|
1887
|
+
if (!changed) break;
|
|
1888
|
+
template = out + template.slice(pos);
|
|
1889
|
+
}
|
|
1890
|
+
return template;
|
|
1891
|
+
}
|
|
1892
|
+
function expandIfElse(template) {
|
|
1893
|
+
for (let pass = 0; pass < 10; pass++) {
|
|
1894
|
+
if (!/\{:else\b/.test(template)) return template;
|
|
1895
|
+
const r = expandIfElseOnce(template);
|
|
1896
|
+
template = r.template;
|
|
1897
|
+
if (!r.changed) return template;
|
|
1898
|
+
}
|
|
1899
|
+
return template;
|
|
1900
|
+
}
|
|
1901
|
+
function expandDeferBlocks(template) {
|
|
1902
|
+
if (!DEFER_ENABLED) {
|
|
1903
|
+
const openRe2 = /\{#defer(?:\s+hold=\\d+)?\}/g;
|
|
1904
|
+
let out2 = "";
|
|
1905
|
+
let dpos = 0;
|
|
1906
|
+
for (; ; ) {
|
|
1907
|
+
openRe2.lastIndex = dpos;
|
|
1908
|
+
const openM = openRe2.exec(template);
|
|
1909
|
+
if (!openM) break;
|
|
1910
|
+
const openAt = openM.index;
|
|
1911
|
+
const openLen = openM[0].length;
|
|
1912
|
+
const closeAt = template.indexOf("{/defer}", openAt + openLen);
|
|
1913
|
+
if (closeAt < 0) break;
|
|
1914
|
+
out2 += template.slice(dpos, openAt) + template.slice(openAt + openLen, closeAt);
|
|
1915
|
+
dpos = closeAt + 8;
|
|
1916
|
+
}
|
|
1917
|
+
return { template: dpos === 0 ? template : out2, count: 0, holds: [] };
|
|
1918
|
+
}
|
|
1919
|
+
let count = 0;
|
|
1920
|
+
const holds = [];
|
|
1921
|
+
let out = "";
|
|
1922
|
+
let pos = 0;
|
|
1923
|
+
const openRe = /\{#defer(?:\s+hold=(\d+))?\}/g;
|
|
1924
|
+
for (; ; ) {
|
|
1925
|
+
openRe.lastIndex = pos;
|
|
1926
|
+
const openM = openRe.exec(template);
|
|
1927
|
+
if (!openM) break;
|
|
1928
|
+
const openAt = openM.index;
|
|
1929
|
+
const openLen = openM[0].length;
|
|
1930
|
+
const hold = openM[1] ? Number(openM[1]) : 0;
|
|
1931
|
+
let depth = 1;
|
|
1932
|
+
let i = openAt + openLen;
|
|
1933
|
+
let closeAt = -1;
|
|
1934
|
+
while (i < template.length) {
|
|
1935
|
+
openRe.lastIndex = i;
|
|
1936
|
+
const nextOpenM = openRe.exec(template);
|
|
1937
|
+
const nextOpen = nextOpenM ? nextOpenM.index : -1;
|
|
1938
|
+
const nextClose = template.indexOf("{/defer}", i);
|
|
1939
|
+
if (nextClose < 0) break;
|
|
1940
|
+
if (nextOpen >= 0 && nextOpen < nextClose) {
|
|
1941
|
+
depth++;
|
|
1942
|
+
i = nextOpen + nextOpenM[0].length;
|
|
1943
|
+
continue;
|
|
1944
|
+
}
|
|
1945
|
+
depth--;
|
|
1946
|
+
if (depth === 0) {
|
|
1947
|
+
closeAt = nextClose;
|
|
1948
|
+
break;
|
|
1949
|
+
}
|
|
1950
|
+
i = nextClose + 8;
|
|
1951
|
+
}
|
|
1952
|
+
if (closeAt < 0) break;
|
|
1953
|
+
const content = template.slice(openAt + openLen, closeAt);
|
|
1954
|
+
holds.push(hold);
|
|
1955
|
+
const n = ++count;
|
|
1956
|
+
out += template.slice(pos, openAt);
|
|
1957
|
+
out += "{#if __rvDefer" + n + "()}" + content + "{/if}\n{#if !__rvDefer" + n + '()}<div class="rv-defer-loading"></div>{/if}';
|
|
1958
|
+
pos = closeAt + 8;
|
|
1959
|
+
}
|
|
1960
|
+
if (count === 0) return { template, count: 0, holds: [] };
|
|
1961
|
+
out += template.slice(pos);
|
|
1962
|
+
return { template: out, count, holds };
|
|
1963
|
+
}
|
|
1964
|
+
function deferBootCode(count, holds = []) {
|
|
1965
|
+
let code = "";
|
|
1966
|
+
for (let n = 1; n <= count; n++) {
|
|
1967
|
+
code += "const [__rvDefer" + n + ", set__rvDefer" + n + '] = state("__rvdefer' + n + '", false);\n';
|
|
1968
|
+
const hold = holds[n - 1] || 0;
|
|
1969
|
+
code += hold > 0 ? "onMount(function () { setTimeout(function () { set__rvDefer" + n + "(true); }, " + hold + "); });\n" : "onMount(function () { requestAnimationFrame(function () { requestAnimationFrame(function () { set__rvDefer" + n + "(true); }); }); });\n";
|
|
1970
|
+
}
|
|
1971
|
+
return code;
|
|
1972
|
+
}
|
|
1170
1973
|
function findBlock(src, kind) {
|
|
1171
|
-
const head = kind === "boundary" ? /\{#boundary
|
|
1974
|
+
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;
|
|
1172
1975
|
const closeRe = new RegExp(`\\{/${kind}\\}`, "g");
|
|
1173
1976
|
let open;
|
|
1174
1977
|
while (open = head.exec(src)) {
|
|
@@ -1190,7 +1993,7 @@ function findBlock(src, kind) {
|
|
|
1190
1993
|
i = nextClose.index + nextClose[0].length;
|
|
1191
1994
|
if (--depth === 0) {
|
|
1192
1995
|
const content = src.slice(afterOpen, nextClose.index);
|
|
1193
|
-
const groups = kind === "boundary" ? [content] : kind === "if" ? [open[1], content] : [open[1], open[2], content];
|
|
1996
|
+
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];
|
|
1194
1997
|
const arr = [src.slice(start, i), ...groups];
|
|
1195
1998
|
arr.index = start;
|
|
1196
1999
|
return arr;
|
|
@@ -1233,7 +2036,7 @@ function compileHead(head) {
|
|
|
1233
2036
|
flush();
|
|
1234
2037
|
return out;
|
|
1235
2038
|
}
|
|
1236
|
-
var KNOWN_CLOSERS = /* @__PURE__ */ new Set(["if", "each", "boundary"]);
|
|
2039
|
+
var KNOWN_CLOSERS = /* @__PURE__ */ new Set(["if", "each", "boundary", "island"]);
|
|
1237
2040
|
function assertKnownDirectives(template, filePath) {
|
|
1238
2041
|
const rawRanges = [];
|
|
1239
2042
|
const RAW_OPEN = /<(style|script|noscript)\b[^>]*>/gi;
|
|
@@ -1267,21 +2070,28 @@ function assertKnownDirectives(template, filePath) {
|
|
|
1267
2070
|
if (word === "else") {
|
|
1268
2071
|
throw new RoseError(
|
|
1269
2072
|
"E-TEMPLATE",
|
|
1270
|
-
`${filePath}: {:else}
|
|
1271
|
-
{ file: filePath, line: lineAt(template, m), hint: "
|
|
2073
|
+
`${filePath}: a stray {:else} with no {#if} above it`,
|
|
2074
|
+
{ file: filePath, line: lineAt(template, m), hint: "{:else} / {:else if cond} belong inside an {#if} ... {/if} block - {#if cond}A{:else}B{/if}" }
|
|
2075
|
+
);
|
|
2076
|
+
}
|
|
2077
|
+
if (word === "fallback") {
|
|
2078
|
+
throw new RoseError(
|
|
2079
|
+
"E-TEMPLATE",
|
|
2080
|
+
`${filePath}: a stray {:fallback} with no {#boundary} above it`,
|
|
2081
|
+
{ file: filePath, line: lineAt(template, m), hint: "{:fallback} belongs directly inside a {#boundary} ... {/boundary} block" }
|
|
1272
2082
|
);
|
|
1273
2083
|
}
|
|
1274
2084
|
throw new RoseError(
|
|
1275
2085
|
"E-TEMPLATE",
|
|
1276
2086
|
`${filePath}: {:${word}} is not a rosetack directive`,
|
|
1277
|
-
{ file: filePath, line: lineAt(template, m), hint: "rosetack templates support {#if}, {#each} and {#boundary}
|
|
2087
|
+
{ file: filePath, line: lineAt(template, m), hint: "rosetack templates support {#if}/{:else}, {#each} and {#boundary}" }
|
|
1278
2088
|
);
|
|
1279
2089
|
}
|
|
1280
|
-
const OPENER_RE = /\{#(if|each|boundary)\b([^}]*)\}/g;
|
|
2090
|
+
const OPENER_RE = /\{#(if|each|boundary|island)\b([^}]*)\}/g;
|
|
1281
2091
|
while (m = OPENER_RE.exec(template)) {
|
|
1282
2092
|
if (inRaw(m.index)) continue;
|
|
1283
2093
|
const [, kind, head] = m;
|
|
1284
|
-
if (kind === "each" && !/\bas\s+(\w+)
|
|
2094
|
+
if (kind === "each" && !/\bas\s+(\{[^{}]*\}?|\[[^[\]]*\]?|\w+)(?:\s*,\s*\w+)?\s*$/.test(head)) {
|
|
1285
2095
|
throw new RoseError(
|
|
1286
2096
|
"E-TEMPLATE",
|
|
1287
2097
|
`${filePath}: {#each ${head.trim()}} is missing its item name`,
|
|
@@ -1335,10 +2145,12 @@ function rewriteQuotedExprAttrs(template, comps) {
|
|
|
1335
2145
|
return `<${name}${rewritten}${selfClose ? " /" : ""}>`;
|
|
1336
2146
|
});
|
|
1337
2147
|
}
|
|
1338
|
-
function compileTemplate(template, acc, closes, scope, depth, markers = true, comps = /* @__PURE__ */ new Map()) {
|
|
2148
|
+
function compileTemplate(template, acc, closes, scope, depth, markers = true, comps = /* @__PURE__ */ new Map(), islandDepth = 0) {
|
|
1339
2149
|
let result = "";
|
|
1340
2150
|
let remaining = template;
|
|
1341
2151
|
let blockId = 0;
|
|
2152
|
+
const islandsMode = /\{#island\b/.test(template);
|
|
2153
|
+
const effMarkers = markers && (!islandsMode || islandDepth > 0);
|
|
1342
2154
|
const nextId = () => `${depth}_${blockId++}`;
|
|
1343
2155
|
while (remaining.length > 0) {
|
|
1344
2156
|
const ifMatch = findBlock(remaining, "if");
|
|
@@ -1347,10 +2159,12 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
|
|
|
1347
2159
|
const firstExpr = templateExprSpans(remaining)[0];
|
|
1348
2160
|
const exprMatch = firstExpr ? Object.assign([remaining.slice(firstExpr.start, firstExpr.end + 1), firstExpr.expr], { index: firstExpr.start }) : null;
|
|
1349
2161
|
const compTag = comps.size > 0 ? findCompTag(remaining, comps) : null;
|
|
2162
|
+
const islandMatch = findBlock(remaining, "island");
|
|
1350
2163
|
const candidates = [];
|
|
1351
2164
|
if (ifMatch?.index !== void 0) candidates.push({ type: "if", match: ifMatch, index: ifMatch.index });
|
|
1352
2165
|
if (eachMatch?.index !== void 0) candidates.push({ type: "each", match: eachMatch, index: eachMatch.index });
|
|
1353
2166
|
if (boundaryMatch?.index !== void 0) candidates.push({ type: "boundary", match: boundaryMatch, index: boundaryMatch.index });
|
|
2167
|
+
if (islandMatch?.index !== void 0) candidates.push({ type: "island", match: islandMatch, index: islandMatch.index });
|
|
1354
2168
|
if (exprMatch?.index !== void 0) candidates.push({ type: "expr", match: exprMatch, index: exprMatch.index });
|
|
1355
2169
|
if (compTag) candidates.push({ type: "comp", match: exprMatch, index: compTag.start, tag: compTag });
|
|
1356
2170
|
const earliest = candidates.length > 0 ? candidates.reduce((a, b) => a.index <= b.index ? a : b) : null;
|
|
@@ -1384,10 +2198,10 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
|
|
|
1384
2198
|
const call = autoCall(cond);
|
|
1385
2199
|
const id = nextId();
|
|
1386
2200
|
const innerScope = scope ?? "__s";
|
|
1387
|
-
const inner = compileTemplate(content.trim(), "h", "__c", innerScope, depth + 1,
|
|
2201
|
+
const inner = compileTemplate(content.trim(), "h", "__c", innerScope, depth + 1, effMarkers, comps, islandDepth);
|
|
1388
2202
|
result += `const __b${id} = (__s, __c) => { let h = ''; ${inner} return h; };
|
|
1389
2203
|
`;
|
|
1390
|
-
if (
|
|
2204
|
+
if (effMarkers) {
|
|
1391
2205
|
result += `${acc} += ifMark(${closes}, () => (${call}), __b${id}${scope ? `, ${scope}` : ""});
|
|
1392
2206
|
`;
|
|
1393
2207
|
} else {
|
|
@@ -1396,43 +2210,62 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
|
|
|
1396
2210
|
}
|
|
1397
2211
|
remaining = remaining.substring(earliest.index + earliest.match[0].length);
|
|
1398
2212
|
} else if (earliest.type === "each") {
|
|
1399
|
-
const [, items, item, content] = earliest.match;
|
|
2213
|
+
const [, items, item, index, content] = earliest.match;
|
|
1400
2214
|
const before = remaining.substring(0, earliest.index);
|
|
1401
2215
|
if (before) result += emitChunk(before, acc, closes, scope);
|
|
1402
2216
|
const call = autoCall(items);
|
|
1403
2217
|
const id = nextId();
|
|
1404
|
-
const
|
|
2218
|
+
const isDestructure = /^[{[]/.test(item);
|
|
2219
|
+
const itemRe = isDestructure ? null : new RegExp(`\\b${item}\\b`, "g");
|
|
2220
|
+
const indexRe = index ? new RegExp(`\\b${index}\\b`, "g") : null;
|
|
1405
2221
|
let scoped = "";
|
|
1406
2222
|
let lastSpan = 0;
|
|
1407
2223
|
for (const s of templateExprSpans(content.trim())) {
|
|
1408
|
-
|
|
2224
|
+
let expr = itemRe ? s.expr.replace(itemRe, "__s") : s.expr;
|
|
2225
|
+
if (indexRe) expr = expr.replace(indexRe, "__i");
|
|
2226
|
+
scoped += content.trim().slice(lastSpan, s.start) + "{" + expr + "}";
|
|
1409
2227
|
lastSpan = s.end + 1;
|
|
1410
2228
|
}
|
|
1411
2229
|
scoped += content.trim().slice(lastSpan);
|
|
1412
|
-
const inner = compileTemplate(scoped, "h", "__c", "__s", depth + 1,
|
|
1413
|
-
|
|
2230
|
+
const inner = compileTemplate(scoped, "h", "__c", "__s", depth + 1, effMarkers, comps, islandDepth);
|
|
2231
|
+
const body = isDestructure ? `const ${item} = __s; ${inner}` : inner;
|
|
2232
|
+
result += `const __b${id} = (__s, __c${index ? ", __i" : ""}) => { let h = ''; ${body} return h; };
|
|
1414
2233
|
`;
|
|
1415
|
-
if (
|
|
2234
|
+
if (effMarkers) {
|
|
1416
2235
|
result += `${acc} += eachMark(${closes}, () => (${call}), __b${id});
|
|
1417
2236
|
`;
|
|
1418
2237
|
} else {
|
|
1419
|
-
|
|
2238
|
+
const param = isDestructure ? "__s" : item;
|
|
2239
|
+
result += `${acc} += (${call}).map((${param}${index ? ", __i" : ""}) => __b${id}(${param}, []${index ? ", __i" : ""}))).join('');
|
|
1420
2240
|
`;
|
|
1421
2241
|
}
|
|
1422
2242
|
remaining = remaining.substring(earliest.index + earliest.match[0].length);
|
|
1423
2243
|
} else if (earliest.type === "boundary") {
|
|
1424
|
-
const [, content] = earliest.match;
|
|
2244
|
+
const [, fbAttr, content] = earliest.match;
|
|
2245
|
+
let fallbackSrc = "";
|
|
2246
|
+
if (fbAttr) {
|
|
2247
|
+
const fbM = /__fb="([A-Za-z0-9+/=]*)"/.exec(fbAttr);
|
|
2248
|
+
if (fbM) fallbackSrc = Buffer.from(fbM[1], "base64").toString("utf-8");
|
|
2249
|
+
}
|
|
2250
|
+
const custom = content;
|
|
1425
2251
|
const before = remaining.substring(0, earliest.index);
|
|
1426
2252
|
if (before) result += emitChunk(before, acc, closes, scope);
|
|
1427
2253
|
const id = nextId();
|
|
1428
|
-
const catchesAction = /\$action:|<form[\s>]/.test(
|
|
1429
|
-
const inner = compileTemplate(
|
|
2254
|
+
const catchesAction = /\$action:|<form[\s>]/.test(custom);
|
|
2255
|
+
const inner = compileTemplate(custom.trim(), "h", closes, scope, depth + 1, effMarkers, comps, islandDepth);
|
|
1430
2256
|
result += `const __b${id} = (__c) => { let h = ''; ${inner} return h; };
|
|
1431
2257
|
`;
|
|
2258
|
+
let fbBlock = "";
|
|
2259
|
+
if (fallbackSrc.trim()) {
|
|
2260
|
+
const fbInner = compileTemplate(fallbackSrc.trim(), "h", closes, scope, depth + 1, effMarkers, comps, islandDepth);
|
|
2261
|
+
fbBlock = `const __bf${id} = (__c) => { let h = ''; ${fbInner} return h; };
|
|
2262
|
+
`;
|
|
2263
|
+
}
|
|
2264
|
+
result += fbBlock;
|
|
1432
2265
|
result += `let __bd${id} = '';
|
|
1433
2266
|
`;
|
|
1434
|
-
result += catchesAction ? `try { $actionErrorOrThrow(); __bd${id} = __b${id}(${closes}); } catch (e) { __bd${id} = $boundaryFallback(e); }
|
|
1435
|
-
` : `try { __bd${id} = __b${id}(${closes}); } catch { __bd${id} = ${JSON.stringify(BOUNDARY_FALLBACK)}; }
|
|
2267
|
+
result += catchesAction ? `try { $actionErrorOrThrow(); __bd${id} = __b${id}(${closes}); } catch (e) { $setBoundaryError(e); __bd${id} = ${fbBlock ? `__bf${id}(${closes})` : "$boundaryFallback(e)"}; }
|
|
2268
|
+
` : `try { __bd${id} = __b${id}(${closes}); } catch (e) { $setBoundaryError(e); __bd${id} = ${fbBlock ? `__bf${id}(${closes})` : JSON.stringify(BOUNDARY_FALLBACK)}; }
|
|
1436
2269
|
`;
|
|
1437
2270
|
result += `${acc} += __bd${id};
|
|
1438
2271
|
`;
|
|
@@ -1455,7 +2288,7 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
|
|
|
1455
2288
|
const { def, named } = splitSlots(childrenSrc);
|
|
1456
2289
|
const hasChildren = def.trim().length > 0;
|
|
1457
2290
|
if (hasChildren) {
|
|
1458
|
-
result += `const __ch${id} = (__s, __c) => { let h = ''; ${compileTemplate(def, "h", "__c", scope, depth + 1,
|
|
2291
|
+
result += `const __ch${id} = (__s, __c) => { let h = ''; ${compileTemplate(def, "h", "__c", scope, depth + 1, effMarkers, comps, islandDepth)} return h; };
|
|
1459
2292
|
`;
|
|
1460
2293
|
}
|
|
1461
2294
|
const slotFns = named.map(([nm, src]) => {
|
|
@@ -1471,9 +2304,10 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
|
|
|
1471
2304
|
}
|
|
1472
2305
|
content = out + content.slice(lastSpan);
|
|
1473
2306
|
}
|
|
1474
|
-
return `${JSON.stringify(nm)}: (__s, __c) => { let h = ''; ${compileTemplate(content, "h", "__c", "__s", depth + 1,
|
|
2307
|
+
return `${JSON.stringify(nm)}: (__s, __c) => { let h = ''; ${compileTemplate(content, "h", "__c", "__s", depth + 1, effMarkers, comps, islandDepth)} return h; }`;
|
|
1475
2308
|
});
|
|
1476
2309
|
const propsObj = parseCompAttrs(tag.attrs).filter((a) => a.name !== "slot").map((a) => {
|
|
2310
|
+
if (a.kind === "spread") return `...(${a.value})`;
|
|
1477
2311
|
const key = a.name.startsWith("on:") ? `on${capitalize(a.name.slice(3))}` : a.name;
|
|
1478
2312
|
const val = a.kind === "expr" ? `(${a.value})` : a.kind === "str" ? JSON.stringify(a.value) : "true";
|
|
1479
2313
|
return `${JSON.stringify(key)}: ${val}`;
|
|
@@ -1482,20 +2316,49 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
|
|
|
1482
2316
|
result += `${acc} += ${tag.name}(${closes}, ${childrenArg}, { ${propsObj} }, { ${slotFns.join(", ")} });
|
|
1483
2317
|
`;
|
|
1484
2318
|
remaining = rest;
|
|
2319
|
+
} else if (earliest.type === "island") {
|
|
2320
|
+
const [, name, hydrate, content] = earliest.match;
|
|
2321
|
+
const before = remaining.substring(0, earliest.index);
|
|
2322
|
+
if (before) result += emitChunk(before, acc, closes, scope);
|
|
2323
|
+
const hydrateAttr = hydrate === "visible" || hydrate === "idle" ? ` data-rv-island-hydrate="${hydrate}"` : "";
|
|
2324
|
+
result += `${acc} += ${JSON.stringify(`<div data-rv-island="${name || ""}"${hydrateAttr}>`)};
|
|
2325
|
+
`;
|
|
2326
|
+
const inner = compileTemplate(content.trim(), "h", "__c", scope, depth + 1, markers, comps, islandDepth + 1);
|
|
2327
|
+
result += inner;
|
|
2328
|
+
result += `${acc} += '</div>';
|
|
2329
|
+
`;
|
|
2330
|
+
remaining = remaining.substring(earliest.index + earliest.match[0].length);
|
|
1485
2331
|
} else {
|
|
1486
2332
|
const [, expr] = earliest.match;
|
|
1487
2333
|
const trimmed = expr.trim();
|
|
1488
2334
|
const before = remaining.substring(0, earliest.index);
|
|
2335
|
+
const constMatch = /^@const\s+([A-Za-z_$][\w$]*)\s*=\s*([\s\S]+)$/.exec(trimmed);
|
|
2336
|
+
if (constMatch) {
|
|
2337
|
+
if (before) result += emitChunk(before, acc, closes, scope);
|
|
2338
|
+
result += `const ${constMatch[1]} = (${constMatch[2].trim()});
|
|
2339
|
+
`;
|
|
2340
|
+
remaining = remaining.substring(earliest.index + earliest.match[0].length);
|
|
2341
|
+
continue;
|
|
2342
|
+
}
|
|
1489
2343
|
if (trimmed === "__slot__") {
|
|
1490
2344
|
if (before) result += emitChunk(before, acc, closes, scope);
|
|
1491
2345
|
result += compileSlot(acc);
|
|
1492
2346
|
remaining = remaining.substring(earliest.index + earliest.match[0].length);
|
|
1493
2347
|
continue;
|
|
1494
2348
|
}
|
|
1495
|
-
const
|
|
2349
|
+
const slotDefault = /^__slotDefault\(("(?:[^"\\]|\\.)*")\)$/.exec(trimmed);
|
|
2350
|
+
if (slotDefault) {
|
|
2351
|
+
if (before) result += emitChunk(before, acc, closes, scope);
|
|
2352
|
+
result += `${acc} += __slotDefault(children, ${slotDefault[1]});
|
|
2353
|
+
`;
|
|
2354
|
+
remaining = remaining.substring(earliest.index + earliest.match[0].length);
|
|
2355
|
+
continue;
|
|
2356
|
+
}
|
|
2357
|
+
const slotCall = /^__slot\((['"])(\w+)\1, \[([\s\S]*?)\](?:,\s*("(?:[^"\\]|\\.)*"))?\)$/.exec(trimmed);
|
|
1496
2358
|
if (slotCall) {
|
|
1497
2359
|
if (before) result += emitChunk(before, acc, closes, scope);
|
|
1498
|
-
|
|
2360
|
+
const fb = slotCall[4] ? `, ${slotCall[4]}` : "";
|
|
2361
|
+
result += `${acc} += __slotBlock(${closes}, __sl, ${JSON.stringify(slotCall[2])}, [${slotCall[3]}]${fb});
|
|
1499
2362
|
`;
|
|
1500
2363
|
remaining = remaining.substring(earliest.index + earliest.match[0].length);
|
|
1501
2364
|
continue;
|
|
@@ -1504,7 +2367,7 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
|
|
|
1504
2367
|
if (rawMatch) {
|
|
1505
2368
|
if (before) result += emitChunk(before, acc, closes, scope);
|
|
1506
2369
|
const expr2 = rawMatch[1].trim();
|
|
1507
|
-
if (!
|
|
2370
|
+
if (!effMarkers) {
|
|
1508
2371
|
result += `${acc} += String(${expr2} ?? '');
|
|
1509
2372
|
`;
|
|
1510
2373
|
} else {
|
|
@@ -1519,12 +2382,12 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
|
|
|
1519
2382
|
if (attrMatch) {
|
|
1520
2383
|
const lit = before.slice(0, before.length - attrMatch[0].length);
|
|
1521
2384
|
if (lit) result += emitChunk(lit, acc, closes, scope);
|
|
1522
|
-
result += emitAttr(attrMatch[1], trimmed, acc, closes, scope,
|
|
2385
|
+
result += emitAttr(attrMatch[1], trimmed, acc, closes, scope, effMarkers);
|
|
1523
2386
|
} else {
|
|
1524
2387
|
if (before) result += emitChunk(before, acc, closes, scope);
|
|
1525
2388
|
const after = remaining.substring(earliest.index + earliest.match[0].length);
|
|
1526
2389
|
const pair = after.length > 0 && !/^<[a-zA-Z/!]/.test(after) && !after.startsWith("{");
|
|
1527
|
-
result += emitText(trimmed, acc, closes, scope,
|
|
2390
|
+
result += emitText(trimmed, acc, closes, scope, effMarkers, pair);
|
|
1528
2391
|
}
|
|
1529
2392
|
remaining = remaining.substring(earliest.index + earliest.match[0].length);
|
|
1530
2393
|
}
|
|
@@ -1584,6 +2447,12 @@ function parseCompAttrs(attrs) {
|
|
|
1584
2447
|
const out = [];
|
|
1585
2448
|
let i = 0;
|
|
1586
2449
|
while (i < attrs.length) {
|
|
2450
|
+
const spread = /^\s*\{\.\.\.([^}]*)\}/.exec(attrs.slice(i));
|
|
2451
|
+
if (spread) {
|
|
2452
|
+
out.push({ name: "...", kind: "spread", value: spread[1].trim() });
|
|
2453
|
+
i += spread[0].length;
|
|
2454
|
+
continue;
|
|
2455
|
+
}
|
|
1587
2456
|
const nm = /^\s*([\w:.-]+)/.exec(attrs.slice(i));
|
|
1588
2457
|
if (!nm) break;
|
|
1589
2458
|
i += nm[0].length;
|
|
@@ -1721,22 +2590,55 @@ var IMG_MIME = {
|
|
|
1721
2590
|
".ico": "image/x-icon"
|
|
1722
2591
|
};
|
|
1723
2592
|
var INLINE_IMG_MAX = 4096;
|
|
2593
|
+
function listImageVariants(publicDir, url) {
|
|
2594
|
+
const ext = path2.extname(url);
|
|
2595
|
+
const base = path2.basename(url, ext);
|
|
2596
|
+
const dirUrl = url.slice(0, url.length - (base + ext).length);
|
|
2597
|
+
let entries;
|
|
2598
|
+
try {
|
|
2599
|
+
entries = fs3.readdirSync(path2.join(publicDir, path2.dirname(url)));
|
|
2600
|
+
} catch {
|
|
2601
|
+
return [];
|
|
2602
|
+
}
|
|
2603
|
+
const re = new RegExp(
|
|
2604
|
+
"^" + base.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") + "\\.w(\\d+)" + ext.replace(".", "\\.") + "$",
|
|
2605
|
+
"i"
|
|
2606
|
+
);
|
|
2607
|
+
const out = [];
|
|
2608
|
+
for (const e of entries) {
|
|
2609
|
+
const m = re.exec(e);
|
|
2610
|
+
const width = m ? Number(m[1]) : 0;
|
|
2611
|
+
if (width > 0) out.push({ url: `${dirUrl}${base}.w${width}${ext}`, width });
|
|
2612
|
+
}
|
|
2613
|
+
return out.sort((a, b) => a.width - b.width);
|
|
2614
|
+
}
|
|
1724
2615
|
function inlineImages(template, publicDir) {
|
|
1725
2616
|
return template.replace(IMG_RE, (tag) => {
|
|
1726
2617
|
const src = tag.match(/\bsrc="(\/[^"{}]+)"/);
|
|
1727
2618
|
if (!src) return tag;
|
|
1728
|
-
const ext =
|
|
2619
|
+
const ext = path2.extname(src[1]).toLowerCase();
|
|
1729
2620
|
const mime = IMG_MIME[ext];
|
|
1730
2621
|
if (!mime) return tag;
|
|
2622
|
+
const rel = src[1].replace(/^\/public(?=\/)/, "");
|
|
2623
|
+
const filePath = path2.join(publicDir, rel);
|
|
1731
2624
|
let file;
|
|
1732
2625
|
try {
|
|
1733
|
-
file =
|
|
2626
|
+
file = fs3.readFileSync(filePath);
|
|
1734
2627
|
} catch {
|
|
1735
2628
|
return tag;
|
|
1736
2629
|
}
|
|
1737
|
-
|
|
2630
|
+
const authorDims = /\swidth=/.test(tag) || /\sheight=/.test(tag);
|
|
2631
|
+
const dims = authorDims ? null : readImageSize(filePath);
|
|
2632
|
+
const withDims = (t) => dims ? t.replace(/<img\b/, `<img width="${dims.width}" height="${dims.height}"`) : t;
|
|
2633
|
+
if (file.length > INLINE_IMG_MAX) {
|
|
2634
|
+
const hasSS = /\ssrcset=/.test(tag) || /\ssizes=/.test(tag);
|
|
2635
|
+
const variants = hasSS ? [] : listImageVariants(publicDir, rel);
|
|
2636
|
+
if (!variants.length) return withDims(tag);
|
|
2637
|
+
const srcset = variants.map((v) => `${v.url} ${v.width}w`).join(", ");
|
|
2638
|
+
return withDims(tag.replace(/<img\b/, `<img srcset="${srcset}"`));
|
|
2639
|
+
}
|
|
1738
2640
|
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")}`;
|
|
1739
|
-
return tag.replace(src[0], `src="${uri}"`);
|
|
2641
|
+
return withDims(tag.replace(src[0], `src="${uri}"`));
|
|
1740
2642
|
});
|
|
1741
2643
|
}
|
|
1742
2644
|
function emitText(expr, acc, closes, scope, markers = true, pair = false) {
|
|
@@ -1750,6 +2652,7 @@ function emitText(expr, acc, closes, scope, markers = true, pair = false) {
|
|
|
1750
2652
|
return `${acc} += textMark(${closes}, ${fn}${extra});
|
|
1751
2653
|
`;
|
|
1752
2654
|
}
|
|
2655
|
+
var BOOLEAN_ATTRS = /* @__PURE__ */ new Set(["checked", "disabled", "readonly", "required", "selected", "multiple", "autofocus", "open"]);
|
|
1753
2656
|
function emitAttr(attr, expr, acc, closes, scope, markers = true) {
|
|
1754
2657
|
if (!markers) {
|
|
1755
2658
|
return `${acc} += '${attr}="' + esc(${expr}) + '"';
|
|
@@ -1757,6 +2660,10 @@ function emitAttr(attr, expr, acc, closes, scope, markers = true) {
|
|
|
1757
2660
|
}
|
|
1758
2661
|
const fn = scope ? `(${scope}) => (${expr})` : `() => (${expr})`;
|
|
1759
2662
|
const arg = scope ? `, ${scope}` : "";
|
|
2663
|
+
if (BOOLEAN_ATTRS.has(attr)) {
|
|
2664
|
+
return `${acc} += boolAttrMark(${closes}, ${fn}, '${attr}'${arg});
|
|
2665
|
+
`;
|
|
2666
|
+
}
|
|
1760
2667
|
return `${acc} += attrMark(${closes}, ${fn}, '${attr}'${arg});
|
|
1761
2668
|
`;
|
|
1762
2669
|
}
|
|
@@ -1764,7 +2671,7 @@ function compileSlot(acc) {
|
|
|
1764
2671
|
return `${acc} += String(children);
|
|
1765
2672
|
`;
|
|
1766
2673
|
}
|
|
1767
|
-
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';`;
|
|
2674
|
+
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';`;
|
|
1768
2675
|
var API_RUNTIME_HELPERS = RUNTIME_IMPORTS.replace(/^import\s*\{/, "").replace(/\}\s*from[\s\S]*$/, "").split(",").map((s) => s.trim()).filter(Boolean);
|
|
1769
2676
|
function propsCode(props) {
|
|
1770
2677
|
if (props.length === 0) return "";
|
|
@@ -1777,7 +2684,16 @@ var SLOT_HELPER = `const __slot = (sl, name, pairs) => {
|
|
|
1777
2684
|
for (let i = 0; i < pairs.length; i++) o[pairs[i][0]] = pairs[i][1];
|
|
1778
2685
|
return { o, fn };
|
|
1779
2686
|
};
|
|
1780
|
-
const __slotBlock = (closes, sl, name, pairs) =>
|
|
2687
|
+
const __slotBlock = (closes, sl, name, pairs, fallback) => {
|
|
2688
|
+
const hit = __slot(sl, name, pairs);
|
|
2689
|
+
if (hit) return slotBlockMark(closes, hit);
|
|
2690
|
+
return fallback || '';
|
|
2691
|
+
};
|
|
2692
|
+
const __slotDefault = (children, fallback) => {
|
|
2693
|
+
const c = children == null ? '' : String(children);
|
|
2694
|
+
if (c.trim()) return c;
|
|
2695
|
+
return fallback || '';
|
|
2696
|
+
};`;
|
|
1781
2697
|
function generateSSR(script, templateFn, stateDeclsCode, exports = "", headFn = "", props = [], namedSlots = false, imports = "", isComponent = false, guard = "", hasActions = false, dataDeclsCode = "") {
|
|
1782
2698
|
const headCode = headFn ? `
|
|
1783
2699
|
const __head = () => { let __hd = ''; ${headFn} return __hd; };
|
|
@@ -1853,7 +2769,7 @@ function buildReport(infos, compiled) {
|
|
|
1853
2769
|
if (routeShipsNoJs(infos, compiled, i)) {
|
|
1854
2770
|
return `${info.routePath} zero-JS nothing in the chain needs the client`;
|
|
1855
2771
|
}
|
|
1856
|
-
const why = [i, ...layoutsOf(infos, i)].filter((ci) => compiled[ci].needsClient).map((ci) => `${(compiled[ci].clientReasons ?? ["needs the client"]).join(" + ")} in ${
|
|
2772
|
+
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("; ");
|
|
1857
2773
|
const forced = compiled[i].csr === true ? " (csr = true forces the bundle)" : "";
|
|
1858
2774
|
return `${info.routePath} client JS ${why}${forced}`;
|
|
1859
2775
|
});
|
|
@@ -1901,44 +2817,44 @@ for (const el of document.querySelectorAll('[data-rosetack]')) {
|
|
|
1901
2817
|
}
|
|
1902
2818
|
`;
|
|
1903
2819
|
async function buildProject(root, outDir) {
|
|
1904
|
-
await
|
|
1905
|
-
const stale = (await
|
|
1906
|
-
await Promise.all(stale.map((f) =>
|
|
2820
|
+
await fs3.promises.mkdir(outDir, { recursive: true });
|
|
2821
|
+
const stale = (await fs3.promises.readdir(outDir)).filter((f) => /^(?:comp-\d+\.(?:ssr|client)|runtime|(?:server|client)-entry)\.js$/.test(f));
|
|
2822
|
+
await Promise.all(stale.map((f) => fs3.promises.rm(path2.join(outDir, f), { force: true })));
|
|
1907
2823
|
const pageFiles = await scanRoseFiles(root);
|
|
1908
2824
|
const compFiles = await scanComponentFiles(root);
|
|
1909
2825
|
const files = [...pageFiles, ...compFiles];
|
|
1910
2826
|
if (pageFiles.length === 0) {
|
|
1911
2827
|
throw new RoseError(
|
|
1912
2828
|
"E-ROUTE",
|
|
1913
|
-
`no .rose pages found under ${
|
|
1914
|
-
{ file:
|
|
2829
|
+
`no .rose pages found under ${path2.join(root, "src", "pages")} - run rosetack from a project root, or pass one: rosetack build <dir>`,
|
|
2830
|
+
{ file: path2.join(root, "src", "pages"), hint: "create src/pages/index.rose in that directory (or run the command from the project root)" }
|
|
1915
2831
|
);
|
|
1916
2832
|
}
|
|
1917
2833
|
const infos = files.map((f) => ({ ...getRouteInfo(f, root) }));
|
|
1918
2834
|
const config = await loadConfig(root);
|
|
1919
2835
|
const plugins = config.plugins;
|
|
1920
2836
|
const scopeKeys = files.map((f, i) => {
|
|
1921
|
-
const base = infos[i].isComponent ?
|
|
1922
|
-
return
|
|
2837
|
+
const base = infos[i].isComponent ? path2.join(root, "src") : path2.join(root, "src", "pages");
|
|
2838
|
+
return path2.relative(base, f).replace(/\\/g, "/").replace(/\.rose$/, "");
|
|
1923
2839
|
});
|
|
1924
2840
|
const registry = new Map(
|
|
1925
2841
|
files.map((f, i) => [f, { index: i, scopeKey: scopeKeys[i], slots: scanSlotDecls(f) }])
|
|
1926
2842
|
);
|
|
1927
2843
|
const compiled = await Promise.all(
|
|
1928
|
-
files.map((f, i) => compileComponent(f,
|
|
2844
|
+
files.map((f, i) => compileComponent(f, path2.join(root, "public"), scopeKeys[i], infos[i].isApi, plugins, registry))
|
|
1929
2845
|
);
|
|
1930
2846
|
const importsOf = /* @__PURE__ */ new Map();
|
|
1931
2847
|
files.forEach((_, i) => {
|
|
1932
2848
|
const list = [];
|
|
1933
2849
|
for (const r of compiled[i].roseImports ?? []) {
|
|
1934
|
-
const abs =
|
|
2850
|
+
const abs = path2.resolve(path2.dirname(files[i]), r.specifier);
|
|
1935
2851
|
const hit = registry.get(abs);
|
|
1936
2852
|
if (hit) list.push(hit.index);
|
|
1937
2853
|
}
|
|
1938
2854
|
importsOf.set(i, list);
|
|
1939
2855
|
});
|
|
1940
2856
|
const needyDep = (i, seen = /* @__PURE__ */ new Set()) => {
|
|
1941
|
-
if (compiled[i].needsClient) return
|
|
2857
|
+
if (compiled[i].needsClient) return path2.basename(files[i]);
|
|
1942
2858
|
if (seen.has(i)) return null;
|
|
1943
2859
|
seen.add(i);
|
|
1944
2860
|
for (const dep of importsOf.get(i) ?? []) {
|
|
@@ -1960,7 +2876,7 @@ async function buildProject(root, outDir) {
|
|
|
1960
2876
|
if (reachable.has(i)) return;
|
|
1961
2877
|
reachable.add(i);
|
|
1962
2878
|
for (const r of compiled[i].roseImports ?? []) {
|
|
1963
|
-
const abs =
|
|
2879
|
+
const abs = path2.resolve(path2.dirname(files[i]), r.specifier);
|
|
1964
2880
|
const hit = registry.get(abs);
|
|
1965
2881
|
if (hit) visit(hit.index);
|
|
1966
2882
|
}
|
|
@@ -1969,13 +2885,13 @@ async function buildProject(root, outDir) {
|
|
|
1969
2885
|
if (!infos[i].isComponent) visit(i);
|
|
1970
2886
|
});
|
|
1971
2887
|
const styles = compiled.map((c, i) => reachable.has(i) ? c.style : "").filter(Boolean).join("\n");
|
|
1972
|
-
if (styles) await
|
|
1973
|
-
else await
|
|
2888
|
+
if (styles) await fs3.promises.writeFile(path2.join(outDir, "styles.css"), styles);
|
|
2889
|
+
else await fs3.promises.rm(path2.join(outDir, "styles.css"), { force: true });
|
|
1974
2890
|
let locales = {};
|
|
1975
2891
|
try {
|
|
1976
|
-
for (const f of await
|
|
2892
|
+
for (const f of await fs3.promises.readdir(path2.join(root, "src", "locales"))) {
|
|
1977
2893
|
if (!f.endsWith(".json")) continue;
|
|
1978
|
-
locales[f.slice(0, -5)] = JSON.parse(await
|
|
2894
|
+
locales[f.slice(0, -5)] = JSON.parse(await fs3.promises.readFile(path2.join(root, "src", "locales", f), "utf-8"));
|
|
1979
2895
|
}
|
|
1980
2896
|
} catch {
|
|
1981
2897
|
locales = {};
|
|
@@ -1987,21 +2903,24 @@ async function buildProject(root, outDir) {
|
|
|
1987
2903
|
for (const l of preload) {
|
|
1988
2904
|
if (!locales[l]) console.warn(`rosetack: i18n.preload lists '${l}' but there is no src/locales/${l}.json - ignored`);
|
|
1989
2905
|
}
|
|
1990
|
-
await
|
|
2906
|
+
await fs3.promises.rm(path2.join(outDir, "locales"), { recursive: true, force: true });
|
|
1991
2907
|
if (packed.length > 0) {
|
|
1992
|
-
const packDir =
|
|
1993
|
-
await
|
|
1994
|
-
for (const l of packed) await
|
|
2908
|
+
const packDir = path2.join(outDir, "locales");
|
|
2909
|
+
await fs3.promises.mkdir(packDir, { recursive: true });
|
|
2910
|
+
for (const l of packed) await fs3.promises.writeFile(path2.join(packDir, `${l}.json`), JSON.stringify(locales[l]));
|
|
1995
2911
|
}
|
|
1996
2912
|
const clientLocales = Object.fromEntries(Object.keys(locales).filter((l) => !packed.includes(l)).map((l) => [l, locales[l]]));
|
|
1997
2913
|
const clientLocalesJson = JSON.stringify(clientLocales).replace(/</g, "\\u003c");
|
|
1998
|
-
const buildDir =
|
|
1999
|
-
await
|
|
2000
|
-
await
|
|
2914
|
+
const buildDir = path2.join(outDir, ".build");
|
|
2915
|
+
await fs3.promises.rm(buildDir, { recursive: true, force: true });
|
|
2916
|
+
await fs3.promises.mkdir(buildDir, { recursive: true });
|
|
2917
|
+
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")];
|
|
2918
|
+
const contentSrc = contentSrcCands.find((c) => fs3.existsSync(c)) ?? contentSrcCands[0];
|
|
2919
|
+
fs3.copyFileSync(contentSrc, path2.join(buildDir, "content-md.ts"));
|
|
2001
2920
|
const runtimePlugins = plugins.filter((p) => p && (p.onRequest || p.onResponse));
|
|
2002
2921
|
if (runtimePlugins.length > 0) {
|
|
2003
|
-
const configRel =
|
|
2004
|
-
await
|
|
2922
|
+
const configRel = path2.relative(buildDir, path2.join(root, "rosetack.config.js")).replace(/\\/g, "/");
|
|
2923
|
+
await fs3.promises.writeFile(path2.join(buildDir, "plugins.js"), `
|
|
2005
2924
|
import config from ${JSON.stringify(configRel)};
|
|
2006
2925
|
|
|
2007
2926
|
const list = Array.isArray(config) ? config : [];
|
|
@@ -2013,21 +2932,21 @@ export const hasRequestHooks = hooks.some((p) => p.onRequest);
|
|
|
2013
2932
|
export const hasResponseHooks = hooks.some((p) => p.onResponse);
|
|
2014
2933
|
`);
|
|
2015
2934
|
}
|
|
2016
|
-
const runtimeEntry = ["../runtime/index.ts", "../src/runtime/index.ts"].map((rel) => fileURLToPath(new URL(rel, import.meta.url))).find((p) =>
|
|
2935
|
+
const runtimeEntry = ["../runtime/index.ts", "../src/runtime/index.ts"].map((rel) => fileURLToPath(new URL(rel, import.meta.url))).find((p) => fs3.existsSync(p));
|
|
2017
2936
|
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" });
|
|
2018
2937
|
await esbuild.build({
|
|
2019
2938
|
entryPoints: [runtimeEntry],
|
|
2020
2939
|
bundle: true,
|
|
2021
|
-
outfile:
|
|
2940
|
+
outfile: path2.join(buildDir, "runtime.js"),
|
|
2022
2941
|
format: "esm",
|
|
2023
2942
|
platform: "browser",
|
|
2024
2943
|
write: true
|
|
2025
2944
|
});
|
|
2026
2945
|
for (let i = 0; i < compiled.length; i++) {
|
|
2027
2946
|
const src = compiled[i].api ?? compiled[i].ssr;
|
|
2028
|
-
await
|
|
2947
|
+
await fs3.promises.writeFile(path2.join(buildDir, `comp-${i}.ssr.js`), src);
|
|
2029
2948
|
if (!infos[i].isApi) {
|
|
2030
|
-
await
|
|
2949
|
+
await fs3.promises.writeFile(path2.join(buildDir, `comp-${i}.client.js`), compiled[i].client);
|
|
2031
2950
|
}
|
|
2032
2951
|
}
|
|
2033
2952
|
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) => {
|
|
@@ -2089,17 +3008,17 @@ export const hasResponseHooks = hooks.some((p) => p.onResponse);
|
|
|
2089
3008
|
return named ? `import { render as render_${i}, ${named} } from './comp-${i}.ssr.js';` : `import { render as render_${i} } from './comp-${i}.ssr.js';`;
|
|
2090
3009
|
}).join("\n");
|
|
2091
3010
|
const notFoundEntries = infos.map((info, i) => ({ info, i })).filter(({ info }) => info.isNotFound).map(({ info, i }) => {
|
|
2092
|
-
const rel =
|
|
2093
|
-
const dir =
|
|
3011
|
+
const rel = path2.relative(path2.join(root, "src", "pages"), info.filePath).replace(/\\/g, "/");
|
|
3012
|
+
const dir = path2.posix.dirname(rel);
|
|
2094
3013
|
const prefix = dir === "." ? "/" : "/" + dir;
|
|
2095
3014
|
const flags = routeShellOff(infos, compiled, i) ? ", { shell: false }" : "";
|
|
2096
|
-
return { prefix, render:
|
|
3015
|
+
return { prefix, render: compose(i), flags };
|
|
2097
3016
|
}).sort((a, b) => b.prefix.length - a.prefix.length);
|
|
2098
3017
|
const notFoundTable = `[
|
|
2099
3018
|
${notFoundEntries.map((e) => ` ['${e.prefix}', ${e.render}${e.flags}],`).join("\n")}
|
|
2100
3019
|
]`;
|
|
2101
3020
|
const errIdx = infos.findIndex((info) => info.isError);
|
|
2102
|
-
const errorRender = errIdx >= 0 ?
|
|
3021
|
+
const errorRender = errIdx >= 0 ? compose(errIdx) : "null";
|
|
2103
3022
|
const middlewareIdx = infos.findIndex((info) => info.isMiddleware);
|
|
2104
3023
|
const serverRoutes = pages.map(({ info, i }) => {
|
|
2105
3024
|
const actionMap = compiled[i].actionNames.map((n) => `${n}: ${n}_${i}`).join(", ");
|
|
@@ -2129,7 +3048,9 @@ ${notFoundEntries.map((e) => ` ['${e.prefix}', ${e.render}${e.flags}],`).join("
|
|
|
2129
3048
|
}).join(",\n ");
|
|
2130
3049
|
const serverEntry = `
|
|
2131
3050
|
${serverImports}
|
|
2132
|
-
import {
|
|
3051
|
+
import { renderMarkdown } from './content-md.ts';
|
|
3052
|
+
import crypto from 'node:crypto';
|
|
3053
|
+
import { setState, persistState, clearRequestState, serializeState, resetRequestContext, setRequestQuery, isLocale, setLocales, localeList, localeDir, setStoreTransport, applyStorePatch, ActionError, StateDelta, setStateDelta, esc } from './runtime.js';
|
|
2133
3054
|
${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
|
|
2134
3055
|
// module to import - the runners below stay no-ops and the servers call them
|
|
2135
3056
|
// unconditionally (one code path, no flags to keep in sync).
|
|
@@ -2221,6 +3142,235 @@ export const revalidate = [
|
|
|
2221
3142
|
${pages.filter(({ i }) => compiled[i].revalidate !== void 0 && !compiled[i].usesContext).map(({ info, i }) => `{ pattern: '${info.pattern}', seconds: ${compiled[i].revalidate} }`).join(",\n ")}
|
|
2222
3143
|
];
|
|
2223
3144
|
|
|
3145
|
+
// Per-request render memo (export const cache = N): a dynamic route's whole renderPage result is memoized for N seconds.
|
|
3146
|
+
export const routeCaches = [
|
|
3147
|
+
${pages.filter(({ i }) => compiled[i].cache !== void 0).map(({ info, i }) => `{ pattern: '${info.pattern}', seconds: ${compiled[i].cache} }`).join(",\n ")}
|
|
3148
|
+
];
|
|
3149
|
+
const __dynCache = new Map();
|
|
3150
|
+
export function invalidateRenderCache(): void {
|
|
3151
|
+
__dynCache.clear();
|
|
3152
|
+
}
|
|
3153
|
+
// Application KV cache primitive (server-side, per-worker in-memory): a zero-dependency store for expensive computations.
|
|
3154
|
+
const __kvStore = new Map<string, { v: unknown; exp: number }>();
|
|
3155
|
+
// Content collections: src/content/<coll>/*.md scanned once at build time,
|
|
3156
|
+
|
|
3157
|
+
const contentCollections = ${JSON.stringify(scanContentDir(path2.join(root, "src", "content")))};
|
|
3158
|
+
export const kv = {
|
|
3159
|
+
get(key: string): unknown {
|
|
3160
|
+
const e = __kvStore.get(key);
|
|
3161
|
+
if (!e) return undefined;
|
|
3162
|
+
if (e.exp < Date.now()) { __kvStore.delete(key); return undefined; }
|
|
3163
|
+
return e.v;
|
|
3164
|
+
},
|
|
3165
|
+
set(key: string, value: unknown, ttlSeconds = 300): void {
|
|
3166
|
+
if (__kvStore.size > 1000) {
|
|
3167
|
+
const cutoff = Date.now();
|
|
3168
|
+
for (const [k, e] of __kvStore) { if (e.exp < cutoff) __kvStore.delete(k); }
|
|
3169
|
+
if (__kvStore.size > 2000) __kvStore.clear();
|
|
3170
|
+
}
|
|
3171
|
+
__kvStore.set(key, { v: value, exp: Date.now() + ttlSeconds * 1000 });
|
|
3172
|
+
},
|
|
3173
|
+
del(key: string): void { __kvStore.delete(key); },
|
|
3174
|
+
has(key: string): boolean {
|
|
3175
|
+
const e = __kvStore.get(key);
|
|
3176
|
+
return !!e && e.exp >= Date.now();
|
|
3177
|
+
},
|
|
3178
|
+
};
|
|
3179
|
+
globalThis.__rosetackKvApi = { kv, kvMemo: $kv };
|
|
3180
|
+
globalThis.__rosetackContent = {
|
|
3181
|
+
list: (coll: string, filter?: { tag: string }) => {
|
|
3182
|
+
let items = contentCollections[coll] ?? [];
|
|
3183
|
+
if (filter?.tag) items = items.filter((e) => ((e.frontmatter.tags as string[] | undefined) ?? []).includes(filter.tag));
|
|
3184
|
+
return items.map((e) => ({ slug: e.slug, ...e.frontmatter }));
|
|
3185
|
+
},
|
|
3186
|
+
rss: (coll: string, opts: { title: string; origin: string; description?: string }) => {
|
|
3187
|
+
return buildRss(contentCollections[coll] ?? [], opts);
|
|
3188
|
+
},
|
|
3189
|
+
get: (coll: string, slug: string, vars?: Record<string, unknown>) => {
|
|
3190
|
+
const e = (contentCollections[coll] ?? []).find((x) => x.slug === slug);
|
|
3191
|
+
if (!e) return null;
|
|
3192
|
+
return { slug: e.slug, ...e.frontmatter, html: renderMarkdown(e.body, vars), toc: e.toc, readingTime: e.readingTime, wordCount: e.wordCount, excerpt: e.excerpt };
|
|
3193
|
+
},
|
|
3194
|
+
};
|
|
3195
|
+
|
|
3196
|
+
const v = {
|
|
3197
|
+
validate(body: Record<string, unknown>, rules: Record<string, string[]>): { ok: boolean; errors: Record<string, string>; values: Record<string, unknown> } {
|
|
3198
|
+
const errors: Record<string, string> = {};
|
|
3199
|
+
const values: Record<string, unknown> = {};
|
|
3200
|
+
for (const [field, ruleList] of Object.entries(rules)) {
|
|
3201
|
+
let val = body[field];
|
|
3202
|
+
for (const rule of ruleList) {
|
|
3203
|
+
if (val === undefined || val === null || val === "") {
|
|
3204
|
+
if (rule === "required") errors[field] = field + " is required";
|
|
3205
|
+
else if (rule.startsWith("default:")) val = rule.slice(8);
|
|
3206
|
+
continue;
|
|
3207
|
+
}
|
|
3208
|
+
if (rule === "string") val = String(val);
|
|
3209
|
+
else if (rule === "trim") val = String(val).trim();
|
|
3210
|
+
else if (rule === "number") {
|
|
3211
|
+
const num = Number(val);
|
|
3212
|
+
if (Number.isNaN(num)) errors[field] = field + " must be a number";
|
|
3213
|
+
else val = num;
|
|
3214
|
+
} else if (rule === "email") {
|
|
3215
|
+
if (!/^[^s@]+@[^s@]+.[^s@]+$/.test(String(val))) errors[field] = field + " must be a valid email";
|
|
3216
|
+
} else if (rule.startsWith("min:")) {
|
|
3217
|
+
const min = Number(rule.slice(4));
|
|
3218
|
+
if (typeof val === "number" ? val < min : String(val).length < min) errors[field] = field + " must be at least " + min;
|
|
3219
|
+
} else if (rule.startsWith("max:")) {
|
|
3220
|
+
const max = Number(rule.slice(4));
|
|
3221
|
+
if (typeof val === "number" ? val > max : String(val).length > max) errors[field] = field + " must be at most " + max;
|
|
3222
|
+
}
|
|
3223
|
+
}
|
|
3224
|
+
values[field] = val;
|
|
3225
|
+
}
|
|
3226
|
+
return { ok: Object.keys(errors).length === 0, errors, values };
|
|
3227
|
+
},
|
|
3228
|
+
};
|
|
3229
|
+
|
|
3230
|
+
const jobs = {
|
|
3231
|
+
_timers: new Map<string, ReturnType<typeof setInterval>>(),
|
|
3232
|
+
every(name: string, seconds: number, fn: () => void | Promise<void>): void {
|
|
3233
|
+
if (this._timers.has(name)) return;
|
|
3234
|
+
const t = setInterval(() => { Promise.resolve(fn()).catch(() => {}); }, seconds * 1000);
|
|
3235
|
+
this._timers.set(name, t as any);
|
|
3236
|
+
},
|
|
3237
|
+
cancel(name: string): void {
|
|
3238
|
+
const t = this._timers.get(name);
|
|
3239
|
+
if (t) { clearInterval(t); this._timers.delete(name); }
|
|
3240
|
+
},
|
|
3241
|
+
cancelAll(): void { for (const t of this._timers.values()) clearInterval(t); this._timers.clear(); }
|
|
3242
|
+
};
|
|
3243
|
+
|
|
3244
|
+
function sse(handler: (send: (event: string, data: unknown) => void) => Promise<void> | void): Response {
|
|
3245
|
+
const encoder = new TextEncoder();
|
|
3246
|
+
const stream = new ReadableStream({
|
|
3247
|
+
async start(controller) {
|
|
3248
|
+
let closed = false;
|
|
3249
|
+
const send = (event: string, data: unknown) => {
|
|
3250
|
+
if (closed) return;
|
|
3251
|
+
controller.enqueue(encoder.encode("event: " + event + "\\ndata: " + JSON.stringify(data) + "\\n\\n"));
|
|
3252
|
+
};
|
|
3253
|
+
try {
|
|
3254
|
+
await handler(send);
|
|
3255
|
+
} finally {
|
|
3256
|
+
closed = true;
|
|
3257
|
+
try { controller.close(); } catch { }
|
|
3258
|
+
}
|
|
3259
|
+
},
|
|
3260
|
+
});
|
|
3261
|
+
return new Response(stream, {
|
|
3262
|
+
headers: { "content-type": "text/event-stream; charset=utf-8", "cache-control": "no-cache", "connection": "keep-alive" },
|
|
3263
|
+
});
|
|
3264
|
+
}
|
|
3265
|
+
globalThis.__rosetackExtras = { v, jobs, sse };
|
|
3266
|
+
const auth = {
|
|
3267
|
+
hashPassword(password: string): string {
|
|
3268
|
+
const salt = crypto.randomBytes(16).toString("hex");
|
|
3269
|
+
const hash = crypto.scryptSync(password, salt, 32).toString("hex");
|
|
3270
|
+
return salt + ":" + hash;
|
|
3271
|
+
},
|
|
3272
|
+
verifyPassword(password: string, stored: string): boolean {
|
|
3273
|
+
const [salt, hash] = stored.split(":");
|
|
3274
|
+
if (!salt || !hash) return false;
|
|
3275
|
+
return crypto.timingSafeEqual(Buffer.from(hash, "hex"), crypto.scryptSync(password, salt, 32));
|
|
3276
|
+
},
|
|
3277
|
+
signSession(data: Record<string, unknown>, secret: string, ttlSeconds = 86400): string {
|
|
3278
|
+
const payload = Buffer.from(JSON.stringify({ ...data, exp: Date.now() + ttlSeconds * 1000 })).toString("base64url");
|
|
3279
|
+
const sig = crypto.createHmac("sha256", secret).update(payload).digest("base64url");
|
|
3280
|
+
return payload + "." + sig;
|
|
3281
|
+
},
|
|
3282
|
+
verifySession<T = Record<string, unknown>>(token: string, secret: string): T | null {
|
|
3283
|
+
const dot = token.lastIndexOf(".");
|
|
3284
|
+
if (dot < 0) return null;
|
|
3285
|
+
const payload = token.slice(0, dot);
|
|
3286
|
+
const sig = token.slice(dot + 1);
|
|
3287
|
+
const expect = crypto.createHmac("sha256", secret).update(payload).digest("base64url");
|
|
3288
|
+
try {
|
|
3289
|
+
if (!crypto.timingSafeEqual(Buffer.from(sig), Buffer.from(expect))) return null;
|
|
3290
|
+
} catch { return null; }
|
|
3291
|
+
try {
|
|
3292
|
+
const data = JSON.parse(Buffer.from(payload, "base64url").toString());
|
|
3293
|
+
if (data.exp < Date.now()) return null;
|
|
3294
|
+
return data as T;
|
|
3295
|
+
} catch { return null; }
|
|
3296
|
+
},
|
|
3297
|
+
csrfToken(secret: string, sessionId: string): string {
|
|
3298
|
+
return crypto.createHmac("sha256", secret).update(sessionId).digest("hex");
|
|
3299
|
+
},
|
|
3300
|
+
verifyCsrf(token: string, secret: string, sessionId: string): boolean {
|
|
3301
|
+
try {
|
|
3302
|
+
return crypto.timingSafeEqual(Buffer.from(token), Buffer.from(this.csrfToken(secret, sessionId)));
|
|
3303
|
+
} catch { return false; }
|
|
3304
|
+
},
|
|
3305
|
+
};
|
|
3306
|
+
globalThis.__rosetackAuth = auth;
|
|
3307
|
+
|
|
3308
|
+
export async function $kv(key: string, compute: () => unknown | Promise<unknown>, ttlSeconds = 300): Promise<unknown> {
|
|
3309
|
+
const hit = kv.get(key);
|
|
3310
|
+
if (hit !== undefined) return hit;
|
|
3311
|
+
const v = await compute();
|
|
3312
|
+
if (v !== undefined) kv.set(key, v, ttlSeconds);
|
|
3313
|
+
return v;
|
|
3314
|
+
}
|
|
3315
|
+
export function isCachedRoute(pathname: string): boolean {
|
|
3316
|
+
return routeCaches.some((r) => matchRoute(r.pattern, pathname));
|
|
3317
|
+
}
|
|
3318
|
+
export function invalidatePath(pathname: string): number {
|
|
3319
|
+
let n = 0;
|
|
3320
|
+
for (const key of [...__dynCache.keys()]) {
|
|
3321
|
+
if (key.startsWith(pathname + '|')) { __dynCache.delete(key); n++; }
|
|
3322
|
+
}
|
|
3323
|
+
return n;
|
|
3324
|
+
}
|
|
3325
|
+
export function peekRenderCache(pathname: string, cookieHeader: string): ReturnType<typeof renderPage> | null {
|
|
3326
|
+
const cfg = routeCaches.find((r) => matchRoute(r.pattern, pathname));
|
|
3327
|
+
if (!cfg) return null;
|
|
3328
|
+
let h = 0x811c9dc5;
|
|
3329
|
+
const c = cookieHeader || '';
|
|
3330
|
+
for (let i = 0; i < c.length; i++) {
|
|
3331
|
+
h ^= c.charCodeAt(i);
|
|
3332
|
+
h = (h * 0x01000193) >>> 0;
|
|
3333
|
+
}
|
|
3334
|
+
const hit = __dynCache.get(pathname + '|' + h.toString(16));
|
|
3335
|
+
return hit && hit.expires > Date.now() ? hit.page : null;
|
|
3336
|
+
}
|
|
3337
|
+
export async function renderPageCached(pathname: string, cookieHeader: string): Promise<ReturnType<typeof renderPage>> {
|
|
3338
|
+
const cfg = routeCaches.find((r) => matchRoute(r.pattern, pathname));
|
|
3339
|
+
if (!cfg) return renderPage(pathname);
|
|
3340
|
+
let h = 0x811c9dc5;
|
|
3341
|
+
for (let i = 0; i < cookieHeader.length; i++) {
|
|
3342
|
+
h ^= cookieHeader.charCodeAt(i);
|
|
3343
|
+
h = (h * 0x01000193) >>> 0;
|
|
3344
|
+
}
|
|
3345
|
+
const key = pathname + '|' + h.toString(16);
|
|
3346
|
+
const hit = __dynCache.get(key);
|
|
3347
|
+
if (hit && hit.expires > Date.now()) {
|
|
3348
|
+
__dynCache.delete(key);
|
|
3349
|
+
__dynCache.set(key, hit);
|
|
3350
|
+
return hit.page;
|
|
3351
|
+
}
|
|
3352
|
+
// Stale-while-revalidate: an EXPIRED entry still answers instantly while one background render refreshes it - the TTL boundary never spikes.
|
|
3353
|
+
if (hit && !hit.refreshing) {
|
|
3354
|
+
hit.refreshing = true;
|
|
3355
|
+
renderPage(pathname).then((fresh: any) => {
|
|
3356
|
+
if (fresh.status === 200 && !fresh.redirect) {
|
|
3357
|
+
__dynCache.set(key, { page: fresh, expires: Date.now() + cfg.seconds * 1000 });
|
|
3358
|
+
} else {
|
|
3359
|
+
__dynCache.delete(key);
|
|
3360
|
+
}
|
|
3361
|
+
}).catch(() => { __dynCache.delete(key); });
|
|
3362
|
+
return hit.page;
|
|
3363
|
+
}
|
|
3364
|
+
const page = await renderPage(pathname);
|
|
3365
|
+
if (page.status === 200 && !page.redirect) {
|
|
3366
|
+
__dynCache.set(key, { page, expires: Date.now() + cfg.seconds * 1000 });
|
|
3367
|
+
if (__dynCache.size > 300) {
|
|
3368
|
+
__dynCache.delete(__dynCache.keys().next().value as string);
|
|
3369
|
+
}
|
|
3370
|
+
}
|
|
3371
|
+
return page;
|
|
3372
|
+
}
|
|
3373
|
+
|
|
2224
3374
|
// Pages/_middleware.rose: a Web-standard request handler that runs before every render on the server (pages, POSTs, api calls alike).
|
|
2225
3375
|
export const middleware = ${middlewareIdx >= 0 ? "middlewareMod.handle ?? null" : "null"};
|
|
2226
3376
|
|
|
@@ -2335,7 +3485,14 @@ export function docAttrs(pathname) {
|
|
|
2335
3485
|
|
|
2336
3486
|
// Paint a fallback page (404/500) and serialize its state.
|
|
2337
3487
|
async function renderFallback(pathname, render) {
|
|
2338
|
-
|
|
3488
|
+
// Split mode: the not-found entry's render is a loader object \u2014 resolve it through getRender (which memoizes the composed function) exactly like.
|
|
3489
|
+
let fn = render;
|
|
3490
|
+
if (typeof fn !== 'function' && fn && typeof fn.load === 'function') {
|
|
3491
|
+
|
|
3492
|
+
// { render } once the route's chunk graph is loaded
|
|
3493
|
+
fn = (await fn.load()).render;
|
|
3494
|
+
}
|
|
3495
|
+
const { html, head } = extractHead(await fn([], ''));
|
|
2339
3496
|
const state = JSON.stringify({ __route: pathname, ...JSON.parse(serializeState()) });
|
|
2340
3497
|
return { html, state, head, ...docAttrs(pathname) };
|
|
2341
3498
|
}
|
|
@@ -2442,8 +3599,27 @@ export async function renderPage(pathname, form) {
|
|
|
2442
3599
|
return await notFoundPage(pathname);
|
|
2443
3600
|
}
|
|
2444
3601
|
console.error('rosetack: render failed for', pathname, err instanceof Error ? err.message : err);
|
|
2445
|
-
|
|
2446
|
-
|
|
3602
|
+
// F10: in dev the response body carries the real error \u2014 message, file:line and the fix hint.
|
|
3603
|
+
let devDetail = '';
|
|
3604
|
+
if (process.env.rosetack_DEV === '1' && err) {
|
|
3605
|
+
const msg = esc(err instanceof Error ? err.message : String(err));
|
|
3606
|
+
const file = esc(String(err.file || ''));
|
|
3607
|
+
const line = err.line != null ? esc(String(err.line)) : '';
|
|
3608
|
+
const hint = esc(String(err.hint || ''));
|
|
3609
|
+
const stack = esc(err instanceof Error ? (err.stack || '').split('\\n').slice(1, 7).join('\\n') : '');
|
|
3610
|
+
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">'
|
|
3611
|
+
+ '<div style="font:600 15px/1.4 system-ui,sans-serif;color:#ff8b8b">Render failed: ' + esc(pathname) + '</div>'
|
|
3612
|
+
+ '<div style="margin:10px 0 0;color:#ffd479">' + msg + '</div>'
|
|
3613
|
+
+ (file ? '<div style="margin:6px 0 0;color:#9ad1ff">' + file + (line ? ':' + line : '') + '</div>' : '')
|
|
3614
|
+
+ (hint ? '<div style="margin:10px 0 0;color:#9fe8b0">Fix: ' + hint + '</div>' : '')
|
|
3615
|
+
+ (stack ? '<pre style="margin:12px 0 0;color:#8f8f9a">' + stack + '</pre>' : '')
|
|
3616
|
+
+ '</div>';
|
|
3617
|
+
}
|
|
3618
|
+
if (errorPage) {
|
|
3619
|
+
const fb = await renderFallback(pathname, errorPage);
|
|
3620
|
+
return { ...fb, html: fb.html + devDetail, status: 500 };
|
|
3621
|
+
}
|
|
3622
|
+
return { html: '<h1>500</h1><p>Something went wrong rendering this page.</p>' + devDetail, state: '{}', head: [], status: 500, ...docAttrs(pathname) };
|
|
2447
3623
|
}
|
|
2448
3624
|
// __route tells the bootstrap which route this document was rendered for.
|
|
2449
3625
|
const state = JSON.stringify({ __route: pathname, ...JSON.parse(serializeState()) });
|
|
@@ -2550,7 +3726,24 @@ export async function renderPageStream(pathname, write, shellOpen, clientTag) {
|
|
|
2550
3726
|
} catch (err) {
|
|
2551
3727
|
|
|
2552
3728
|
console.error('rosetack: render failed for', pathname, err instanceof Error ? err.message : err);
|
|
2553
|
-
|
|
3729
|
+
// F10: dev carries the real error in the body here too \u2014 the shell
|
|
3730
|
+
// is out, so the detail rides after the error page body.
|
|
3731
|
+
let devDetail = '';
|
|
3732
|
+
if (process.env.rosetack_DEV === '1' && err) {
|
|
3733
|
+
const msg = esc(err instanceof Error ? err.message : String(err));
|
|
3734
|
+
const file = esc(String(err.file || ''));
|
|
3735
|
+
const line = err.line != null ? esc(String(err.line)) : '';
|
|
3736
|
+
const hint = esc(String(err.hint || ''));
|
|
3737
|
+
const stack = esc(err instanceof Error ? (err.stack || '').split('\\n').slice(1, 7).join('\\n') : '');
|
|
3738
|
+
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">'
|
|
3739
|
+
+ '<div style="font:600 15px/1.4 system-ui,sans-serif;color:#ff8b8b">Render failed: ' + esc(pathname) + '</div>'
|
|
3740
|
+
+ '<div style="margin:10px 0 0;color:#ffd479">' + msg + '</div>'
|
|
3741
|
+
+ (file ? '<div style="margin:6px 0 0;color:#9ad1ff">' + file + (line ? ':' + line : '') + '</div>' : '')
|
|
3742
|
+
+ (hint ? '<div style="margin:10px 0 0;color:#9fe8b0">Fix: ' + hint + '</div>' : '')
|
|
3743
|
+
+ (stack ? '<pre style="margin:12px 0 0;color:#8f8f9a">' + stack + '</pre>' : '')
|
|
3744
|
+
+ '</div>';
|
|
3745
|
+
}
|
|
3746
|
+
html = errorPage ? extractHead(await errorPage([], '')).html + devDetail : '<h1>500</h1><p>Something went wrong rendering this page.</p>' + devDetail;
|
|
2554
3747
|
}
|
|
2555
3748
|
write(html);
|
|
2556
3749
|
// Csr: false ( auto since #29): a no-JS route's document ends here - no state script, no inlined bundle.
|
|
@@ -2568,16 +3761,68 @@ export async function renderPageStream(pathname, write, shellOpen, clientTag) {
|
|
|
2568
3761
|
return 404;
|
|
2569
3762
|
}
|
|
2570
3763
|
`;
|
|
2571
|
-
|
|
3764
|
+
try {
|
|
3765
|
+
const patterns = [...pages, ...apiRoutes].map(({ info }) => info.pattern);
|
|
3766
|
+
const uniq = [...new Set(patterns)].sort();
|
|
3767
|
+
const lit = uniq.map((p) => JSON.stringify(p)).join(" | ") || "'/'";
|
|
3768
|
+
const paramsOf = (pattern) => (pattern.match(/:[\w]+|\*\*[\w]+|\*[\w]+/g) ?? []).map((m) => m.replace(/^[*:]+/, ""));
|
|
3769
|
+
const paramSig = uniq.map((p) => {
|
|
3770
|
+
const ps = paramsOf(p);
|
|
3771
|
+
if (!ps.length) return "";
|
|
3772
|
+
return " " + JSON.stringify(p) + ": { " + ps.map((n) => n + ": string | number").join("; ") + " };\n";
|
|
3773
|
+
}).join("");
|
|
3774
|
+
const outDirTs = path2.join(root, "src", ".rosetack");
|
|
3775
|
+
await fs3.promises.mkdir(outDirTs, { recursive: true });
|
|
3776
|
+
const srcLines = [
|
|
3777
|
+
"// GENERATED by rosetack build - do not edit.",
|
|
3778
|
+
"export type RoutePath = " + lit + ";",
|
|
3779
|
+
"export const routePatterns = " + JSON.stringify(uniq) + " as const;",
|
|
3780
|
+
"export type RouteParams = {",
|
|
3781
|
+
paramSig,
|
|
3782
|
+
"};",
|
|
3783
|
+
"/** Build a URL from a route pattern and its params. */",
|
|
3784
|
+
"export function url(",
|
|
3785
|
+
" path: RoutePath,",
|
|
3786
|
+
" params: RouteParams[keyof RouteParams] = {} as never,",
|
|
3787
|
+
"): string {",
|
|
3788
|
+
" let out = path as string;",
|
|
3789
|
+
" for (const [k, v] of Object.entries(params as Record<string, string | number>)) {",
|
|
3790
|
+
" out = out.replace(new RegExp('[:*]+' + k, 'g'), String(v));",
|
|
3791
|
+
" }",
|
|
3792
|
+
" return out;",
|
|
3793
|
+
"}"
|
|
3794
|
+
].join("\n") + "\n";
|
|
3795
|
+
await fs3.promises.writeFile(path2.join(outDirTs, "routes.ts"), srcLines);
|
|
3796
|
+
} catch {
|
|
3797
|
+
}
|
|
3798
|
+
await fs3.promises.writeFile(path2.join(buildDir, "server-entry.js"), serverEntry);
|
|
2572
3799
|
await esbuild.build({
|
|
2573
|
-
entryPoints: [
|
|
3800
|
+
entryPoints: [path2.join(buildDir, "server-entry.js")],
|
|
2574
3801
|
bundle: true,
|
|
2575
|
-
outfile:
|
|
3802
|
+
outfile: path2.join(outDir, "server.js"),
|
|
2576
3803
|
format: "esm",
|
|
2577
3804
|
platform: "node",
|
|
2578
3805
|
write: true,
|
|
2579
3806
|
...TS_LOADER
|
|
2580
3807
|
});
|
|
3808
|
+
await esbuild.build({
|
|
3809
|
+
entryPoints: [(() => {
|
|
3810
|
+
const here = path2.dirname(fileURLToPath(import.meta.url));
|
|
3811
|
+
for (const cand of [path2.join(here, "..", "cli", "prod-server.ts"), path2.join(here, "..", "src", "cli", "prod-server.ts")]) {
|
|
3812
|
+
if (fs3.existsSync(cand)) return cand;
|
|
3813
|
+
}
|
|
3814
|
+
return path2.join(here, "..", "cli", "prod-server.ts");
|
|
3815
|
+
})()],
|
|
3816
|
+
bundle: true,
|
|
3817
|
+
outfile: path2.join(outDir, "prod.mjs"),
|
|
3818
|
+
format: "esm",
|
|
3819
|
+
platform: "node",
|
|
3820
|
+
write: true,
|
|
3821
|
+
banner: {
|
|
3822
|
+
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);"
|
|
3823
|
+
},
|
|
3824
|
+
...TS_LOADER
|
|
3825
|
+
});
|
|
2581
3826
|
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");
|
|
2582
3827
|
const clientRoutes = pages.map(({ info, i }) => split ? `{ pattern: '${info.pattern}', ${loaderInner(i)} }` : `{ pattern: '${info.pattern}', render: ${compose(i)} }`).join(",\n ");
|
|
2583
3828
|
const prefetchMode = compiled.find((c) => c.prefetch)?.prefetch ?? "all";
|
|
@@ -2608,7 +3853,7 @@ reportVitals();
|
|
|
2608
3853
|
if (!known) {` : ` if (langIdx >= 0 && !isLocale(pathname.split('/')[langIdx])) {`;
|
|
2609
3854
|
const clientEntry = `
|
|
2610
3855
|
${clientImports}
|
|
2611
|
-
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';
|
|
3856
|
+
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';
|
|
2612
3857
|
|
|
2613
3858
|
// I18n: the dictionaries baked at build time - the client renders any PRELOADED locale from the bundle.
|
|
2614
3859
|
setLocales(${clientLocalesJson}, '${defaultLocale}');
|
|
@@ -2832,6 +4077,8 @@ export async function $action(name, e) {
|
|
|
2832
4077
|
const box = e && e.target && e.target.closest ? e.target.closest('[data-rosetack]') : null;
|
|
2833
4078
|
return postForm(body, box || undefined, box ? box.getAttribute('data-rosetack') : undefined);
|
|
2834
4079
|
}
|
|
4080
|
+
// 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.
|
|
4081
|
+
setActionDispatcher($action);
|
|
2835
4082
|
|
|
2836
4083
|
export { postForm };
|
|
2837
4084
|
|
|
@@ -2863,6 +4110,16 @@ async function __withOwner(container, fn) {
|
|
|
2863
4110
|
setFxOwner(null);
|
|
2864
4111
|
}
|
|
2865
4112
|
}
|
|
4113
|
+
// View Transition on SPA swaps (B9): the DOM swap rides one cross-fade when the browser supports it; reduced-motion users and environments without.
|
|
4114
|
+
async function __swap(container, html) {
|
|
4115
|
+
const reduce = typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches;
|
|
4116
|
+
if (typeof document.startViewTransition === 'function' && !reduce) {
|
|
4117
|
+
const vt = document.startViewTransition(() => { container.innerHTML = html; });
|
|
4118
|
+
await vt.updateCallbackDone.catch(() => {});
|
|
4119
|
+
} else {
|
|
4120
|
+
container.innerHTML = html;
|
|
4121
|
+
}
|
|
4122
|
+
}
|
|
2866
4123
|
|
|
2867
4124
|
export async function start(container, pathname, initial) {
|
|
2868
4125
|
clearMounts(); // stale mounts from a failed render never fire
|
|
@@ -2885,7 +4142,7 @@ ${langDirBlock}
|
|
|
2885
4142
|
prefetchCache.delete(pathname);
|
|
2886
4143
|
__navReset(container);
|
|
2887
4144
|
restoreState(hit.state);
|
|
2888
|
-
container
|
|
4145
|
+
await __swap(container, hit.html);
|
|
2889
4146
|
await __withOwner(container, () => {
|
|
2890
4147
|
wire(container, hit.closes);
|
|
2891
4148
|
bindEvents(container);
|
|
@@ -2910,15 +4167,18 @@ ${langDirBlock}
|
|
|
2910
4167
|
if (err && err.__rosetack === 'redirect') { signal = err.path; return; }
|
|
2911
4168
|
|
|
2912
4169
|
|
|
4170
|
+
console.error('rosetack: client render failed for', pathname, err instanceof Error ? err.message : err);
|
|
2913
4171
|
broken = true;
|
|
2914
4172
|
return;
|
|
2915
4173
|
}
|
|
2916
|
-
if (!initial) container
|
|
4174
|
+
if (!initial) await __swap(container, html);
|
|
2917
4175
|
wire(container, closes);
|
|
2918
4176
|
bindEvents(container);
|
|
2919
4177
|
flushMounts();
|
|
2920
4178
|
});
|
|
2921
4179
|
if (signal === 'notFound') {
|
|
4180
|
+
// 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.
|
|
4181
|
+
if (!initial) { try { location.assign(pathname); return; } catch { } }
|
|
2922
4182
|
await paintFallback(container, notFoundFor(pathname), '<h1>404</h1><p>Page not found</p>');
|
|
2923
4183
|
return;
|
|
2924
4184
|
}
|
|
@@ -2981,11 +4241,11 @@ setRefreshHook(async () => {
|
|
|
2981
4241
|
await start(document.getElementById('app'), location.pathname, false);
|
|
2982
4242
|
});
|
|
2983
4243
|
`;
|
|
2984
|
-
await
|
|
4244
|
+
await fs3.promises.writeFile(path2.join(buildDir, "client-entry.js"), clientEntry);
|
|
2985
4245
|
if (split) {
|
|
2986
|
-
await
|
|
4246
|
+
await fs3.promises.rm(path2.join(outDir, "chunks"), { recursive: true, force: true });
|
|
2987
4247
|
await esbuild.build({
|
|
2988
|
-
entryPoints: [
|
|
4248
|
+
entryPoints: [path2.join(buildDir, "client-entry.js")],
|
|
2989
4249
|
bundle: true,
|
|
2990
4250
|
format: "esm",
|
|
2991
4251
|
platform: "browser",
|
|
@@ -2999,9 +4259,9 @@ setRefreshHook(async () => {
|
|
|
2999
4259
|
});
|
|
3000
4260
|
} else {
|
|
3001
4261
|
await esbuild.build({
|
|
3002
|
-
entryPoints: [
|
|
4262
|
+
entryPoints: [path2.join(buildDir, "client-entry.js")],
|
|
3003
4263
|
bundle: true,
|
|
3004
|
-
outfile:
|
|
4264
|
+
outfile: path2.join(outDir, "client.js"),
|
|
3005
4265
|
format: "esm",
|
|
3006
4266
|
platform: "browser",
|
|
3007
4267
|
minify: true,
|
|
@@ -3009,13 +4269,13 @@ setRefreshHook(async () => {
|
|
|
3009
4269
|
...TS_LOADER
|
|
3010
4270
|
});
|
|
3011
4271
|
}
|
|
3012
|
-
await
|
|
3013
|
-
await
|
|
3014
|
-
const publicDir =
|
|
3015
|
-
if (
|
|
3016
|
-
await
|
|
3017
|
-
const favicon =
|
|
3018
|
-
if (
|
|
4272
|
+
await fs3.promises.writeFile(path2.join(outDir, "mount.js"), MOUNT_ENTRY);
|
|
4273
|
+
await fs3.promises.rm(buildDir, { recursive: true, force: true });
|
|
4274
|
+
const publicDir = path2.join(root, "public");
|
|
4275
|
+
if (fs3.existsSync(publicDir)) {
|
|
4276
|
+
await fs3.promises.cp(publicDir, path2.join(outDir, "public"), { recursive: true });
|
|
4277
|
+
const favicon = path2.join(publicDir, "favicon.ico");
|
|
4278
|
+
if (fs3.existsSync(favicon)) await fs3.promises.copyFile(favicon, path2.join(outDir, "favicon.ico"));
|
|
3019
4279
|
}
|
|
3020
4280
|
console.log("rosetack zero-JS report:");
|
|
3021
4281
|
for (const line of buildReport(infos, compiled)) console.log(" " + line);
|
|
@@ -3029,7 +4289,7 @@ setRefreshHook(async () => {
|
|
|
3029
4289
|
g = { why: w, files: /* @__PURE__ */ new Map() };
|
|
3030
4290
|
warnGroups.set(w, g);
|
|
3031
4291
|
}
|
|
3032
|
-
const file =
|
|
4292
|
+
const file = path2.relative(root, infos[ci].filePath).replace(/\\/g, "/");
|
|
3033
4293
|
let routes = g.files.get(file);
|
|
3034
4294
|
if (!routes) {
|
|
3035
4295
|
routes = /* @__PURE__ */ new Set();
|
|
@@ -3050,13 +4310,13 @@ setRefreshHook(async () => {
|
|
|
3050
4310
|
return { routes: pages.map(({ info }) => info), bundle: bundleMode };
|
|
3051
4311
|
}
|
|
3052
4312
|
async function scanRoseFiles(root) {
|
|
3053
|
-
const pagesDir =
|
|
3054
|
-
if (!
|
|
4313
|
+
const pagesDir = path2.join(root, "src", "pages");
|
|
4314
|
+
if (!fs3.existsSync(pagesDir)) return [];
|
|
3055
4315
|
async function scan(dir) {
|
|
3056
|
-
const entries = await
|
|
4316
|
+
const entries = await fs3.promises.readdir(dir, { withFileTypes: true });
|
|
3057
4317
|
const files = [];
|
|
3058
4318
|
for (const entry of entries) {
|
|
3059
|
-
const full =
|
|
4319
|
+
const full = path2.join(dir, entry.name);
|
|
3060
4320
|
if (entry.isDirectory()) files.push(...await scan(full));
|
|
3061
4321
|
else if (entry.name.endsWith(".rose")) files.push(full);
|
|
3062
4322
|
}
|
|
@@ -3065,13 +4325,13 @@ async function scanRoseFiles(root) {
|
|
|
3065
4325
|
return scan(pagesDir);
|
|
3066
4326
|
}
|
|
3067
4327
|
async function scanComponentFiles(root) {
|
|
3068
|
-
const compDir =
|
|
3069
|
-
if (!
|
|
4328
|
+
const compDir = path2.join(root, "src", "components");
|
|
4329
|
+
if (!fs3.existsSync(compDir)) return [];
|
|
3070
4330
|
async function scan(dir) {
|
|
3071
|
-
const entries = await
|
|
4331
|
+
const entries = await fs3.promises.readdir(dir, { withFileTypes: true });
|
|
3072
4332
|
const files = [];
|
|
3073
4333
|
for (const entry of entries) {
|
|
3074
|
-
const full =
|
|
4334
|
+
const full = path2.join(dir, entry.name);
|
|
3075
4335
|
if (entry.isDirectory()) files.push(...await scan(full));
|
|
3076
4336
|
else if (entry.name.endsWith(".rose")) files.push(full);
|
|
3077
4337
|
}
|
|
@@ -3080,15 +4340,15 @@ async function scanComponentFiles(root) {
|
|
|
3080
4340
|
return scan(compDir);
|
|
3081
4341
|
}
|
|
3082
4342
|
function isAncestorDir(layoutPath, pagePath) {
|
|
3083
|
-
const layoutDir =
|
|
3084
|
-
const pageDir =
|
|
3085
|
-
return pageDir === layoutDir || pageDir.startsWith(layoutDir +
|
|
4343
|
+
const layoutDir = path2.dirname(layoutPath);
|
|
4344
|
+
const pageDir = path2.dirname(pagePath);
|
|
4345
|
+
return pageDir === layoutDir || pageDir.startsWith(layoutDir + path2.sep);
|
|
3086
4346
|
}
|
|
3087
4347
|
function getRouteInfo(filePath, root) {
|
|
3088
|
-
const pagesDir =
|
|
3089
|
-
const relative3 =
|
|
4348
|
+
const pagesDir = path2.join(root, "src", "pages");
|
|
4349
|
+
const relative3 = path2.relative(pagesDir, filePath).replace(/\\/g, "/");
|
|
3090
4350
|
const withoutExt = relative3.replace(/\.rose$/, "");
|
|
3091
|
-
const base =
|
|
4351
|
+
const base = path2.posix.basename(withoutExt);
|
|
3092
4352
|
const isComponent = filePath.replace(/\\/g, "/").includes("/src/components/");
|
|
3093
4353
|
const isLayout = !isComponent && base === "_layout";
|
|
3094
4354
|
const isNotFound = !isComponent && (base === "404" || base === "_notfound");
|
|
@@ -3136,24 +4396,24 @@ function capitalize(s) {
|
|
|
3136
4396
|
}
|
|
3137
4397
|
|
|
3138
4398
|
// src/cli/shell.ts
|
|
3139
|
-
import * as
|
|
3140
|
-
import * as
|
|
4399
|
+
import * as fs4 from "fs";
|
|
4400
|
+
import * as path3 from "path";
|
|
3141
4401
|
import * as esbuild2 from "esbuild";
|
|
3142
|
-
var OUT_DIR =
|
|
4402
|
+
var OUT_DIR = path3.join(process.cwd(), "dist");
|
|
3143
4403
|
var styleCache = null;
|
|
3144
4404
|
function getStyles() {
|
|
3145
|
-
const file =
|
|
4405
|
+
const file = path3.join(OUT_DIR, "styles.css");
|
|
3146
4406
|
try {
|
|
3147
|
-
const st =
|
|
4407
|
+
const st = fs4.statSync(file);
|
|
3148
4408
|
if (!styleCache || styleCache.mtimeMs !== st.mtimeMs) {
|
|
3149
|
-
styleCache = { mtimeMs: st.mtimeMs, source:
|
|
4409
|
+
styleCache = { mtimeMs: st.mtimeMs, source: fs4.readFileSync(file, "utf-8") };
|
|
3150
4410
|
}
|
|
3151
4411
|
return styleCache.source;
|
|
3152
4412
|
} catch {
|
|
3153
4413
|
return "";
|
|
3154
4414
|
}
|
|
3155
4415
|
}
|
|
3156
|
-
var
|
|
4416
|
+
var BOOTSTRAP_SOURCE = `
|
|
3157
4417
|
// shell = false: the document's SSR content sits directly in <body> - no
|
|
3158
4418
|
// #app wrapper, no demo styles, so a real theme's CSS owns the document from
|
|
3159
4419
|
// the first byte (and a JS-less visitor never sees either). The bundle still
|
|
@@ -3276,14 +4536,45 @@ if (__state.__notFound) {
|
|
|
3276
4536
|
} else {
|
|
3277
4537
|
start(__app, window.location.pathname);
|
|
3278
4538
|
}
|
|
3279
|
-
|
|
3280
|
-
var
|
|
3281
|
-
|
|
3282
|
-
|
|
4539
|
+
`;
|
|
4540
|
+
var BOOTSTRAP_CACHE = null;
|
|
4541
|
+
function bootstrap() {
|
|
4542
|
+
if (BOOTSTRAP_CACHE === null) {
|
|
4543
|
+
if (globalThis.__rosetack_SKIP_MINIFY) {
|
|
4544
|
+
BOOTSTRAP_CACHE = BOOTSTRAP_SOURCE;
|
|
4545
|
+
} else {
|
|
4546
|
+
try {
|
|
4547
|
+
BOOTSTRAP_CACHE = esbuild2.transformSync(BOOTSTRAP_SOURCE, { minify: true }).code;
|
|
4548
|
+
} catch {
|
|
4549
|
+
BOOTSTRAP_CACHE = BOOTSTRAP_SOURCE;
|
|
4550
|
+
}
|
|
4551
|
+
}
|
|
4552
|
+
}
|
|
4553
|
+
return BOOTSTRAP_CACHE;
|
|
4554
|
+
}
|
|
4555
|
+
var EXTERNAL_BOOTSTRAP_CACHE = null;
|
|
4556
|
+
function externalBootstrap() {
|
|
4557
|
+
if (EXTERNAL_BOOTSTRAP_CACHE === null) EXTERNAL_BOOTSTRAP_CACHE = `
|
|
4558
|
+
import { start, startNotFound, prefetch, postForm, prefetchStats, serializeState } from '/client.js';
|
|
4559
|
+
${bootstrap()}`;
|
|
4560
|
+
return EXTERNAL_BOOTSTRAP_CACHE;
|
|
4561
|
+
}
|
|
3283
4562
|
function inlineScript(client) {
|
|
4563
|
+
const m = /\bexport\s*\{([^}]*)\}\s*;?\s*$/.exec(client);
|
|
4564
|
+
let body = client;
|
|
4565
|
+
let aliases = "";
|
|
4566
|
+
if (m) {
|
|
4567
|
+
body = client.slice(0, m.index) + client.slice(m.index + m[0].length);
|
|
4568
|
+
aliases = m[1].split(",").map((pair) => {
|
|
4569
|
+
const parts = pair.split(" as ").map((x) => x.trim());
|
|
4570
|
+
if (parts.length === 1 || parts[0] === parts[1]) return "";
|
|
4571
|
+
return parts[0] && parts[1] ? `var ${parts[1]} = ${parts[0]};` : "";
|
|
4572
|
+
}).join("");
|
|
4573
|
+
}
|
|
3284
4574
|
return `
|
|
3285
|
-
${
|
|
3286
|
-
${
|
|
4575
|
+
${body}
|
|
4576
|
+
${aliases}
|
|
4577
|
+
${bootstrap()}`;
|
|
3287
4578
|
}
|
|
3288
4579
|
var FAVICON = '<link rel="icon" type="image/png" href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAMAAABEpIrGAAAAYFBMVEWsADn/M2Z/AH8AAADsHmT6IGvnHWLoHWLrHWPpHWLnHGLqHWP/AAD/AFX/AH3qGmX/AP/kHV7qHFyqAFXqJGTbH1/qIGLZF2D1J1jxIGjMAGbfGl3yIGflHF//AD/MM2ZAdgeTAAAAIHRSTlMEBQIA+P5Ob9GQMbEBAwITASoQAxESNxcKTwUxx20EBW1qAJ8AAAHfSURBVHjalVOLbtswDNRGiqRIWYqdV9u9/v8vd7TTAimGDRMSQ5SOx+NDhf6xyv8BlqX/DbDg7xt1+tr7HwCnM9Grqi/jnOY4fQLAFqtNJGlm+cTQx0+awcxTtZkKm5n35QOQu2mVayNVidoU+6Dl9AB02jQazuALEeK2wmLPm4MBwbkxi7A3eIt8V5jcrkCUU78E4GBoxHBt3nhDFGGu7H2UThPgGlHFuUnDz+TO1eFWnRYAXgwACUZ8WyO2aNhUSRkrnVMDAEyIDwUeNsEEURK7TgBOCwDmHoja/JukPmwzMM9+KjQIWdst3FNWU3wAWAGAUuplEHyq3blRqzUhyFlcEMUEmZUutQJxRWaeyhHOlG58OWSgK3koTSWLIWrQcUVKNusPhGYta4phlWtWA6yOQtUKOsl75tJ2QOiWdo171DyvcsnmVjBYPRBO8MwC7Ca7BbKPScU165TqxV/XOO7RL0mGFaVGJdt+CupQnEMA695gjMSgMt7Gr3de8FjT0BSaSzBKYDiT84M51TraediWI1X2iRNLIaa3Fw+uD76qiHBMFIBvc85NDSo0dj0Q8mV8TPU4Hg6UYS7p4gCZP7+LngsvAl3a0p7vV09vczzAYywfxvPj7QvWg/Fx9BsLaBn5YAGOoQAAAABJRU5ErkJggg==">';
|
|
3289
4580
|
var STYLES = `
|
|
@@ -3342,7 +4633,7 @@ function mergeHeadBlocks(blocks) {
|
|
|
3342
4633
|
function clientScriptTag(client, nonce = "") {
|
|
3343
4634
|
const n = nonce ? ` nonce="${nonce}"` : "";
|
|
3344
4635
|
return client ? `<script type="module"${n}>${inlineScript(client)}</script>` : `<script type="module"${n} src="/client.js"></script>
|
|
3345
|
-
<script type="module"${n}>${
|
|
4636
|
+
<script type="module"${n}>${externalBootstrap()}</script>`;
|
|
3346
4637
|
}
|
|
3347
4638
|
function buildShell(ssrHtml, stateJson, client, head = [], styles = getStyles(), js = true, lang = "en", dir = "", nonce = "", shell = true) {
|
|
3348
4639
|
const clientTag = clientScriptTag(client, nonce);
|
|
@@ -3387,50 +4678,50 @@ function buildShell(ssrHtml, stateJson, client, head = [], styles = getStyles(),
|
|
|
3387
4678
|
// src/cli/test.ts
|
|
3388
4679
|
var GRAFTED = ["document", "Node", "NodeFilter", "FormData", "DOMParser", "location", "fetch", "Event", "CustomEvent", "MutationObserver", "requestAnimationFrame"];
|
|
3389
4680
|
function projectRootOf(file) {
|
|
3390
|
-
let dir =
|
|
4681
|
+
let dir = path4.dirname(path4.resolve(file));
|
|
3391
4682
|
for (; ; ) {
|
|
3392
|
-
if (
|
|
3393
|
-
const parent =
|
|
4683
|
+
if (fs5.existsSync(path4.join(dir, "src", "pages"))) return dir;
|
|
4684
|
+
const parent = path4.dirname(dir);
|
|
3394
4685
|
if (parent === dir) throw new Error(`rosetack/test: ${file} is not inside a project (no src/pages found above it)`);
|
|
3395
4686
|
dir = parent;
|
|
3396
4687
|
}
|
|
3397
4688
|
}
|
|
3398
4689
|
function routeOf(file, root) {
|
|
3399
|
-
const rel =
|
|
4690
|
+
const rel = path4.relative(path4.join(root, "src", "pages"), path4.resolve(file)).replace(/\\/g, "/").replace(/\.rose$/, "");
|
|
3400
4691
|
if (rel === "index") return "/";
|
|
3401
4692
|
const segs = rel.split("/").map((s) => s.startsWith("[") && s.endsWith("]") ? `:${s.slice(1, -1)}` : s);
|
|
3402
4693
|
return "/" + segs.join("/");
|
|
3403
4694
|
}
|
|
3404
4695
|
function copyTree(from, to) {
|
|
3405
|
-
|
|
3406
|
-
for (const e of
|
|
3407
|
-
const src =
|
|
3408
|
-
const dst =
|
|
4696
|
+
fs5.mkdirSync(to, { recursive: true });
|
|
4697
|
+
for (const e of fs5.readdirSync(from, { withFileTypes: true })) {
|
|
4698
|
+
const src = path4.join(from, e.name);
|
|
4699
|
+
const dst = path4.join(to, e.name);
|
|
3409
4700
|
if (e.isDirectory()) copyTree(src, dst);
|
|
3410
|
-
else
|
|
4701
|
+
else fs5.copyFileSync(src, dst);
|
|
3411
4702
|
}
|
|
3412
4703
|
}
|
|
3413
4704
|
function propAttrs(props) {
|
|
3414
4705
|
return Object.entries(props).map(([k, v]) => `${k}={${JSON.stringify(v) ?? "undefined"}}`).join(" ");
|
|
3415
4706
|
}
|
|
3416
4707
|
async function test(file, opts = {}) {
|
|
3417
|
-
const target =
|
|
3418
|
-
if (!
|
|
4708
|
+
const target = path4.resolve(file);
|
|
4709
|
+
if (!fs5.existsSync(target)) throw new Error(`rosetack/test: no such file: ${target}`);
|
|
3419
4710
|
const root = projectRootOf(target);
|
|
3420
|
-
const rel =
|
|
4711
|
+
const rel = path4.relative(root, target).replace(/\\/g, "/");
|
|
3421
4712
|
const isComponent = rel.startsWith("src/components/");
|
|
3422
|
-
const dir = opts.dir ??
|
|
4713
|
+
const dir = opts.dir ?? fs5.mkdtempSync(path4.join(os.tmpdir(), "rosetack-test-"));
|
|
3423
4714
|
for (const item of ["src", "public"]) {
|
|
3424
|
-
const from =
|
|
3425
|
-
if (
|
|
4715
|
+
const from = path4.join(root, item);
|
|
4716
|
+
if (fs5.existsSync(from)) copyTree(from, path4.join(dir, item));
|
|
3426
4717
|
}
|
|
3427
4718
|
for (const item of ["rosetack.config.js"]) {
|
|
3428
|
-
const from =
|
|
3429
|
-
if (
|
|
4719
|
+
const from = path4.join(root, item);
|
|
4720
|
+
if (fs5.existsSync(from)) fs5.copyFileSync(from, path4.join(dir, item));
|
|
3430
4721
|
}
|
|
3431
4722
|
let route;
|
|
3432
4723
|
if (isComponent) {
|
|
3433
|
-
const specifier =
|
|
4724
|
+
const specifier = path4.relative(path4.join(dir, "src", "pages"), path4.join(dir, rel)).replace(/\\/g, "/");
|
|
3434
4725
|
const attrs = propAttrs(opts.props ?? {});
|
|
3435
4726
|
const page = `<script>
|
|
3436
4727
|
import Target from '${specifier}';
|
|
@@ -3440,27 +4731,27 @@ async function test(file, opts = {}) {
|
|
|
3440
4731
|
<Target ${attrs} />
|
|
3441
4732
|
</template>
|
|
3442
4733
|
`;
|
|
3443
|
-
|
|
4734
|
+
fs5.writeFileSync(path4.join(dir, "src", "pages", "__rosetack_test.rose"), page);
|
|
3444
4735
|
route = "/__rosetack_test";
|
|
3445
4736
|
} else {
|
|
3446
4737
|
route = opts.route ?? routeOf(target, root);
|
|
3447
4738
|
}
|
|
3448
|
-
const outDir =
|
|
4739
|
+
const outDir = path4.join(dir, "dist");
|
|
3449
4740
|
await buildProject(dir, outDir);
|
|
3450
|
-
const serverUrl = pathToFileURL2(
|
|
3451
|
-
const clientUrl = pathToFileURL2(
|
|
4741
|
+
const serverUrl = pathToFileURL2(path4.join(outDir, "server.js")).href;
|
|
4742
|
+
const clientUrl = pathToFileURL2(path4.join(outDir, "client.js")).href;
|
|
3452
4743
|
const mod = await import(serverUrl);
|
|
3453
|
-
const clientSource =
|
|
4744
|
+
const clientSource = fs5.readFileSync(path4.join(outDir, "client.js"), "utf-8");
|
|
3454
4745
|
let styles = "";
|
|
3455
4746
|
try {
|
|
3456
|
-
styles =
|
|
4747
|
+
styles = fs5.readFileSync(path4.join(outDir, "styles.css"), "utf-8");
|
|
3457
4748
|
} catch {
|
|
3458
4749
|
}
|
|
3459
4750
|
if (opts.keep) console.log(`rosetack/test: built ${target} -> ${outDir}`);
|
|
3460
4751
|
if (!opts.dir && !opts.keep) {
|
|
3461
4752
|
process.once("exit", () => {
|
|
3462
4753
|
try {
|
|
3463
|
-
|
|
4754
|
+
fs5.rmSync(dir, { recursive: true, force: true });
|
|
3464
4755
|
} catch {
|
|
3465
4756
|
}
|
|
3466
4757
|
});
|
|
@@ -3517,9 +4808,9 @@ async function test(file, opts = {}) {
|
|
|
3517
4808
|
globalThis.fetch = async (url, init) => {
|
|
3518
4809
|
const pathname = String(url).startsWith("http") ? new URL(String(url)).pathname : String(url);
|
|
3519
4810
|
if (pathname.startsWith("/locales/") && pathname.endsWith(".json")) {
|
|
3520
|
-
const file2 =
|
|
3521
|
-
if (!
|
|
3522
|
-
return { ok: true, json: async () => JSON.parse(
|
|
4811
|
+
const file2 = path4.join(outDir, pathname.slice(1));
|
|
4812
|
+
if (!fs5.existsSync(file2)) return { ok: false, json: async () => ({}) };
|
|
4813
|
+
return { ok: true, json: async () => JSON.parse(fs5.readFileSync(file2, "utf-8")) };
|
|
3523
4814
|
}
|
|
3524
4815
|
requests++;
|
|
3525
4816
|
const next = await request(pathname, req, init?.body);
|