rosetack 0.1.2 → 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/deploy/cloudflare/functions/[[path]].ts +61 -0
- package/deploy/cloudflare/wrangler.toml +14 -0
- package/deploy/netlify/functions/rosetack.ts +38 -0
- package/deploy/netlify.toml +17 -0
- package/devtools/devtools.html +7 -0
- package/devtools/devtools.js +1 -0
- package/devtools/manifest.json +8 -0
- package/devtools/panel.html +28 -0
- package/devtools/panel.js +54 -0
- package/dist-cli/compiler.mjs +2194 -561
- package/dist-cli/edge.mjs +159 -48
- package/dist-cli/rosetack.mjs +2899 -739
- package/dist-cli/runtime.mjs +305 -43
- package/dist-cli/test.mjs +2332 -630
- package/package.json +4 -3
- package/src/FRAMEWORK_VERSION +1 -1
- package/src/cli/content.ts +186 -0
- package/src/cli/edge.ts +78 -62
- package/src/cli/image-size.ts +83 -0
- package/src/cli/index.ts +391 -334
- package/src/cli/prod-server.ts +324 -0
- package/src/cli/prompt.ts +51 -20
- package/src/cli/shell.ts +105 -74
- package/src/cli/test.ts +9 -70
- package/src/compiler/index.ts +2107 -913
- package/src/runtime/index.ts +367 -168
- package/src/types/rosetack.d.ts +16 -66
- package/templates/admin/package.json +14 -0
- package/templates/admin/rosetack.config.js +1 -0
- package/templates/admin/src/pages/_middleware.rose +33 -0
- package/templates/admin/src/pages/api/items.rose +37 -0
- package/templates/admin/src/pages/api/login.rose +25 -0
- package/templates/admin/src/pages/index.rose +79 -0
- package/templates/api/package.json +14 -0
- package/templates/api/rosetack.config.js +1 -0
- package/templates/api/src/pages/api/health.rose +7 -0
- package/templates/api/src/pages/api/items.rose +46 -0
- package/templates/api/src/pages/api/login.rose +24 -0
- package/templates/api/src/pages/index.rose +25 -0
- package/templates/blog/package.json +14 -0
- package/templates/blog/rosetack.config.js +1 -0
- package/templates/blog/src/pages/404.rose +2 -0
- package/templates/blog/src/pages/_layout.rose +42 -0
- package/templates/blog/src/pages/_middleware.rose +74 -0
- package/templates/blog/src/pages/admin.rose +85 -0
- package/templates/blog/src/pages/api/login.rose +46 -0
- package/templates/blog/src/pages/api/posts/[id].rose +37 -0
- package/templates/blog/src/pages/api/posts.rose +72 -0
- package/templates/blog/src/pages/index.rose +31 -0
- package/templates/blog/src/pages/post/[id].rose +36 -0
- package/templates/site/package.json +14 -0
- package/templates/site/rosetack.config.js +1 -0
- package/templates/site/src/pages/404.rose +2 -0
- package/templates/site/src/pages/_layout.rose +40 -0
- package/templates/site/src/pages/about.rose +6 -0
- package/templates/site/src/pages/index.rose +13 -0
- package/templates/site/src/pages/pricing.rose +8 -0
package/dist-cli/compiler.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// src/compiler/index.ts
|
|
2
|
-
import * as
|
|
3
|
-
import * as
|
|
2
|
+
import * as fs3 from "fs";
|
|
3
|
+
import * as path2 from "path";
|
|
4
4
|
import { pathToFileURL, fileURLToPath } from "url";
|
|
5
5
|
import * as esbuild from "esbuild";
|
|
6
6
|
|
|
@@ -43,16 +43,209 @@ function errorInfo(err) {
|
|
|
43
43
|
return { code: "E-UNKNOWN", message: err instanceof Error ? err.message : String(err) };
|
|
44
44
|
}
|
|
45
45
|
|
|
46
|
+
// src/cli/image-size.ts
|
|
47
|
+
import fs from "node:fs";
|
|
48
|
+
function readImageSize(filePath) {
|
|
49
|
+
try {
|
|
50
|
+
const fd = fs.openSync(filePath, "r");
|
|
51
|
+
const buf = Buffer.alloc(64);
|
|
52
|
+
const read = fs.readSync(fd, buf, 0, 64, 0);
|
|
53
|
+
fs.closeSync(fd);
|
|
54
|
+
if (read < 24) return null;
|
|
55
|
+
if (buf[0] === 137 && buf[1] === 80 && buf[2] === 78 && buf[3] === 71) {
|
|
56
|
+
return { width: buf.readUInt32BE(16), height: buf.readUInt32BE(20) };
|
|
57
|
+
}
|
|
58
|
+
if (buf.slice(0, 3).toString("latin1") === "GIF") {
|
|
59
|
+
return { width: buf.readUInt16LE(6), height: buf.readUInt16LE(8) };
|
|
60
|
+
}
|
|
61
|
+
if (buf.slice(0, 4).toString("latin1") === "RIFF" && buf.slice(8, 12).toString("latin1") === "WEBP") {
|
|
62
|
+
return parseWebP(buf);
|
|
63
|
+
}
|
|
64
|
+
if (buf[0] === 255 && buf[1] === 216) {
|
|
65
|
+
return parseJpeg(filePath);
|
|
66
|
+
}
|
|
67
|
+
return null;
|
|
68
|
+
} catch {
|
|
69
|
+
return null;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
function parseWebP(buf) {
|
|
73
|
+
const format = buf.slice(12, 16).toString("latin1");
|
|
74
|
+
if (format === "VP8 ") {
|
|
75
|
+
return { width: buf.readUInt16LE(26) & 16383, height: buf.readUInt16LE(28) & 16383 };
|
|
76
|
+
}
|
|
77
|
+
if (format === "VP8L") {
|
|
78
|
+
const b = buf.readUInt32LE(21);
|
|
79
|
+
return { width: (b & 16383) + 1, height: (b >> 14 & 16383) + 1 };
|
|
80
|
+
}
|
|
81
|
+
if (format === "VP8X") {
|
|
82
|
+
const w = buf.readUIntLE(24, 3) + 1;
|
|
83
|
+
const h = buf.readUIntLE(27, 3) + 1;
|
|
84
|
+
return { width: w, height: h };
|
|
85
|
+
}
|
|
86
|
+
return null;
|
|
87
|
+
}
|
|
88
|
+
function parseJpeg(filePath) {
|
|
89
|
+
const fd = fs.openSync(filePath, "r");
|
|
90
|
+
try {
|
|
91
|
+
const buf = Buffer.alloc(4);
|
|
92
|
+
let pos = 2;
|
|
93
|
+
for (let guard = 0; guard < 64; guard++) {
|
|
94
|
+
if (fs.readSync(fd, buf, 0, 4, pos) < 4) return null;
|
|
95
|
+
if (buf[0] !== 255) {
|
|
96
|
+
pos += 1;
|
|
97
|
+
continue;
|
|
98
|
+
}
|
|
99
|
+
const marker = buf[1];
|
|
100
|
+
if (marker === 216 || marker === 1 || marker >= 208 && marker <= 215) {
|
|
101
|
+
pos += 2;
|
|
102
|
+
continue;
|
|
103
|
+
}
|
|
104
|
+
const len = fs.readSync(fd, buf, 0, 2, pos + 2) < 2 ? 0 : buf.readUInt16BE(2);
|
|
105
|
+
if (marker >= 192 && marker <= 207 && marker !== 196 && marker !== 200 && marker !== 204) {
|
|
106
|
+
const seg = Buffer.alloc(8);
|
|
107
|
+
fs.readSync(fd, seg, 0, 8, pos + 4);
|
|
108
|
+
return { width: seg.readUInt16BE(3), height: seg.readUInt16BE(1) };
|
|
109
|
+
}
|
|
110
|
+
pos += 2 + len;
|
|
111
|
+
}
|
|
112
|
+
return null;
|
|
113
|
+
} finally {
|
|
114
|
+
fs.closeSync(fd);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
// src/cli/content.ts
|
|
119
|
+
import fs2 from "node:fs";
|
|
120
|
+
import path from "node:path";
|
|
121
|
+
function parseFrontmatter(raw) {
|
|
122
|
+
if (!raw.startsWith("---")) return { frontmatter: {}, body: raw };
|
|
123
|
+
const end = raw.indexOf("\n---", 3);
|
|
124
|
+
if (end < 0) return { frontmatter: {}, body: raw };
|
|
125
|
+
const head = raw.slice(4, end);
|
|
126
|
+
const body = raw.slice(raw.indexOf("\n", end + 1) + 1).replace(/^\s*\n/, "");
|
|
127
|
+
const frontmatter = {};
|
|
128
|
+
for (const line of head.split("\n")) {
|
|
129
|
+
const m = /^(\w[\w-]*):\s*(.*)$/.exec(line.trim());
|
|
130
|
+
if (!m) continue;
|
|
131
|
+
const [, k, v] = m;
|
|
132
|
+
const arr = /^\[(.+)\]$/.exec(v.trim());
|
|
133
|
+
frontmatter[k] = arr ? arr[1].split(",").map((x) => x.trim().replace(/^["']|["']$/g, "")) : v.trim().replace(/^["']|["']$/g, "");
|
|
134
|
+
}
|
|
135
|
+
return { frontmatter, body };
|
|
136
|
+
}
|
|
137
|
+
function interpolate(md, vars) {
|
|
138
|
+
return md.replace(/{{(\w[\w.]*)}}/g, (_m, k) => {
|
|
139
|
+
const v = k.split(".").reduce((o, p) => o == null ? o : o[p], vars);
|
|
140
|
+
return v === void 0 || v === null ? "" : String(v);
|
|
141
|
+
});
|
|
142
|
+
}
|
|
143
|
+
function renderMarkdown(md, vars) {
|
|
144
|
+
if (vars) md = interpolate(md, vars);
|
|
145
|
+
const blocks = [];
|
|
146
|
+
let src = md.replace(/```(\w*)\n([\s\S]*?)```/g, (_m, lang, code) => {
|
|
147
|
+
blocks.push(
|
|
148
|
+
`<pre data-lang="${lang}"><code>${code.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">")}</code></pre>`
|
|
149
|
+
);
|
|
150
|
+
return `\0CODE${blocks.length - 1}\0`;
|
|
151
|
+
});
|
|
152
|
+
const inline = (s) => s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/`([^`]+)`/g, "<code>$1</code>").replace(/\*\*([^*]+)\*\*/g, "<strong>$1</strong>").replace(/\*([^*]+)\*/g, "<em>$1</em>").replace(
|
|
153
|
+
/\[([^\]]+)\]\(([^)]+)\)/g,
|
|
154
|
+
'<a href="$2" rel="noopener">$1</a>'
|
|
155
|
+
);
|
|
156
|
+
const out = [];
|
|
157
|
+
let listOpen = null;
|
|
158
|
+
const closeList = () => {
|
|
159
|
+
if (listOpen) {
|
|
160
|
+
out.push(`</${listOpen}>`);
|
|
161
|
+
listOpen = null;
|
|
162
|
+
}
|
|
163
|
+
};
|
|
164
|
+
for (const line of src.split("\n")) {
|
|
165
|
+
const h = /^(#{1,4})\s+(.*)$/.exec(line);
|
|
166
|
+
const li = /^\s*[-*]\s+(.*)$/.exec(line);
|
|
167
|
+
const oli = /^\s*\d+\.\s+(.*)$/.exec(line);
|
|
168
|
+
if (h) {
|
|
169
|
+
closeList();
|
|
170
|
+
out.push(`<h${h[1].length}>${inline(h[2])}</h${h[1].length}>`);
|
|
171
|
+
} else if (li) {
|
|
172
|
+
if (listOpen !== "ul") {
|
|
173
|
+
closeList();
|
|
174
|
+
out.push("<ul>");
|
|
175
|
+
listOpen = "ul";
|
|
176
|
+
}
|
|
177
|
+
out.push(`<li>${inline(li[1])}</li>`);
|
|
178
|
+
} else if (oli) {
|
|
179
|
+
if (listOpen !== "ol") {
|
|
180
|
+
closeList();
|
|
181
|
+
out.push("<ol>");
|
|
182
|
+
listOpen = "ol";
|
|
183
|
+
}
|
|
184
|
+
out.push(`<li>${inline(oli[1])}</li>`);
|
|
185
|
+
} else if (line.trim() === "") {
|
|
186
|
+
closeList();
|
|
187
|
+
} else if (line.startsWith("\0CODE")) {
|
|
188
|
+
closeList();
|
|
189
|
+
out.push(line);
|
|
190
|
+
} else {
|
|
191
|
+
closeList();
|
|
192
|
+
out.push(`<p>${inline(line)}</p>`);
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
closeList();
|
|
196
|
+
return out.join("\n").replace(/\u0000CODE(\d+)\u0000/g, (_m, i) => blocks[Number(i)]);
|
|
197
|
+
}
|
|
198
|
+
function scanContentDir(contentDir) {
|
|
199
|
+
const collections = {};
|
|
200
|
+
if (!fs2.existsSync(contentDir)) return collections;
|
|
201
|
+
for (const coll of fs2.readdirSync(contentDir, { withFileTypes: true })) {
|
|
202
|
+
if (!coll.isDirectory()) continue;
|
|
203
|
+
const entries = [];
|
|
204
|
+
const dir = path.join(contentDir, coll.name);
|
|
205
|
+
for (const f of fs2.readdirSync(dir)) {
|
|
206
|
+
if (!f.endsWith(".md")) continue;
|
|
207
|
+
const raw = fs2.readFileSync(path.join(dir, f), "utf-8");
|
|
208
|
+
const { frontmatter, body } = parseFrontmatter(raw);
|
|
209
|
+
if (String(frontmatter.draft ?? "").toLowerCase() === "true") continue;
|
|
210
|
+
const slug = f.replace(/\.md$/, "");
|
|
211
|
+
const html = renderMarkdown(body);
|
|
212
|
+
const words = body.replace(/[#*`\[\]()>-]/g, " ").split(/\s+/).filter(Boolean).length;
|
|
213
|
+
const headings = [];
|
|
214
|
+
const tocHtml = html.replace(/<h([1-4])>([^<]+)<\/h\1>/g, (_m, lvl, txt) => {
|
|
215
|
+
const id = txt.toLowerCase().replace(/[^\w\s-]/g, "").trim().replace(/\s+/g, "-");
|
|
216
|
+
headings.push({ level: Number(lvl), text: txt, id });
|
|
217
|
+
return `<h${lvl} id="${id}">${txt}</h${lvl}>`;
|
|
218
|
+
});
|
|
219
|
+
entries.push({
|
|
220
|
+
slug,
|
|
221
|
+
frontmatter,
|
|
222
|
+
body,
|
|
223
|
+
html: tocHtml,
|
|
224
|
+
readingTime: Math.max(1, Math.round(words / 200)),
|
|
225
|
+
wordCount: words,
|
|
226
|
+
toc: headings,
|
|
227
|
+
excerpt: String(frontmatter.summary ?? "") || (html.match(/<p>([\s\S]*?)<\/p>/)?.[1] ?? "").replace(/<[^>]+>/g, "").slice(0, 160)
|
|
228
|
+
});
|
|
229
|
+
}
|
|
230
|
+
entries.sort(
|
|
231
|
+
(a, b) => String(b.frontmatter.date ?? "").localeCompare(String(a.frontmatter.date ?? ""))
|
|
232
|
+
);
|
|
233
|
+
collections[coll.name] = entries;
|
|
234
|
+
}
|
|
235
|
+
return collections;
|
|
236
|
+
}
|
|
237
|
+
globalThis.__rosetackContentMk = renderMarkdown;
|
|
238
|
+
|
|
46
239
|
// src/compiler/index.ts
|
|
47
240
|
var COMPONENT_RE = /<script>([\s\S]*?)<\/script>/;
|
|
48
241
|
var TEMPLATE_RE = /<template>([\s\S]*?)<\/template>/;
|
|
49
242
|
var HEAD_RE = /<head>([\s\S]*?)<\/head>/;
|
|
50
243
|
var STYLE_RE = /<style>([\s\S]*?)<\/style>/;
|
|
51
|
-
var DECL_RE = /(?:let|const|var)\s+(\w+)[^=]*=\s*\$(state|data)\b/g;
|
|
244
|
+
var DECL_RE = /(?:let|const|var)\s+(\w+)[^=]*=\s*\$(state|data|kv|persist)\b/g;
|
|
52
245
|
var DECL_CAST_RE = /^\s+as\s+[^;\n]+/;
|
|
53
246
|
var SETSTATE_RE = /\$setState\(([^,]+),\s*([^)]+)\)/g;
|
|
54
|
-
var SLOT_RE = /<slot\s
|
|
55
|
-
var SLOT_NAMED_RE = /<slot\s+((?=[^>]*\bname\s*=)[^>]*?)
|
|
247
|
+
var SLOT_RE = /<slot\s*\/>|<slot>([\s\S]*?)<\/slot>/g;
|
|
248
|
+
var SLOT_NAMED_RE = /<slot\s+((?=[^>]*\bname\s*=)[^>]*?)(?:\/>|>([\s\S]*?)<\/slot>)/g;
|
|
56
249
|
function encodeSlotCall(attrs) {
|
|
57
250
|
const name = /\bname\s*=\s*["'](\w+)["']/.exec(attrs)?.[1];
|
|
58
251
|
if (!name) throw new RoseError("E-TEMPLATE", '<slot> with attributes must declare a name: <slot name="row" ... />', { hint: 'a slot carrying attributes is a NAMED slot - it must declare which one: <slot name="row" item={post} />' });
|
|
@@ -216,21 +409,50 @@ function skipTemplate(src, i) {
|
|
|
216
409
|
}
|
|
217
410
|
return j;
|
|
218
411
|
}
|
|
412
|
+
function skipLiteral(src, i) {
|
|
413
|
+
const q = src[i];
|
|
414
|
+
if (q === '"' || q === "'") return skipQuoted(src, i);
|
|
415
|
+
if (q === "`") return skipTemplate(src, i);
|
|
416
|
+
if (q !== "/") return null;
|
|
417
|
+
if (src[i + 1] === "/" || src[i + 1] === "*") return null;
|
|
418
|
+
let b = i - 1;
|
|
419
|
+
while (b >= 0 && /\s/.test(src[b])) b--;
|
|
420
|
+
if (b >= 0) {
|
|
421
|
+
if (!"(,=:[!&|?{};+-*%~^".includes(src[b])) {
|
|
422
|
+
const word = /(\w+)$/.exec(src.slice(0, b + 1))?.[1] ?? "";
|
|
423
|
+
if (!["return", "typeof", "case", "in", "of", "new", "delete", "void", "do", "else", "instanceof", "yield", "await"].includes(word)) return null;
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
let j = i + 1;
|
|
427
|
+
let inClass = false;
|
|
428
|
+
while (j < src.length) {
|
|
429
|
+
const c = src[j];
|
|
430
|
+
if (c === "\\") {
|
|
431
|
+
j += 2;
|
|
432
|
+
continue;
|
|
433
|
+
}
|
|
434
|
+
if (c === "\n") return null;
|
|
435
|
+
if (inClass) {
|
|
436
|
+
if (c === "]") inClass = false;
|
|
437
|
+
} else if (c === "[") inClass = true;
|
|
438
|
+
else if (c === "/") {
|
|
439
|
+
j++;
|
|
440
|
+
break;
|
|
441
|
+
}
|
|
442
|
+
j++;
|
|
443
|
+
}
|
|
444
|
+
if (j > src.length) return null;
|
|
445
|
+
while (j < src.length && /[dgimsuvy]/.test(src[j])) j++;
|
|
446
|
+
return j;
|
|
447
|
+
}
|
|
219
448
|
function stripComments(src) {
|
|
220
449
|
let out = "";
|
|
221
450
|
let i = 0;
|
|
222
451
|
while (i < src.length) {
|
|
223
|
-
const
|
|
224
|
-
if (
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
i = end;
|
|
228
|
-
continue;
|
|
229
|
-
}
|
|
230
|
-
if (q === "`") {
|
|
231
|
-
const end = skipTemplate(src, i);
|
|
232
|
-
out += src.slice(i, end);
|
|
233
|
-
i = end;
|
|
452
|
+
const lit = skipLiteral(src, i);
|
|
453
|
+
if (lit !== null) {
|
|
454
|
+
out += src.slice(i, lit);
|
|
455
|
+
i = lit;
|
|
234
456
|
continue;
|
|
235
457
|
}
|
|
236
458
|
if (src.startsWith("//", i)) {
|
|
@@ -253,12 +475,173 @@ function stripComments(src) {
|
|
|
253
475
|
}
|
|
254
476
|
return out;
|
|
255
477
|
}
|
|
478
|
+
function stripGuardedBranches(src) {
|
|
479
|
+
const GUARD = /typeof\s+(?:window|document|navigator|location|localStorage|sessionStorage)\s*(!==|===)\s*["']undefined["']/y;
|
|
480
|
+
const ws = (i2) => {
|
|
481
|
+
while (i2 < src.length && /\s/.test(src[i2])) i2++;
|
|
482
|
+
return i2;
|
|
483
|
+
};
|
|
484
|
+
const ternaryColon = (q) => {
|
|
485
|
+
let depth = 0;
|
|
486
|
+
let i2 = q + 1;
|
|
487
|
+
while (i2 < src.length) {
|
|
488
|
+
const c = src[i2];
|
|
489
|
+
const lit = skipLiteral(src, i2);
|
|
490
|
+
if (lit !== null) {
|
|
491
|
+
i2 = lit;
|
|
492
|
+
continue;
|
|
493
|
+
}
|
|
494
|
+
if (c === "(" || c === "[" || c === "{") depth++;
|
|
495
|
+
else if (c === ")" || c === "]" || c === "}") {
|
|
496
|
+
depth--;
|
|
497
|
+
if (depth < 0) return -1;
|
|
498
|
+
} else if (depth === 0 && c === ":") return i2;
|
|
499
|
+
else if (depth === 0 && c === "?") {
|
|
500
|
+
const inner = ternaryColon(i2);
|
|
501
|
+
if (inner < 0) return -1;
|
|
502
|
+
i2 = inner + 1;
|
|
503
|
+
continue;
|
|
504
|
+
}
|
|
505
|
+
i2++;
|
|
506
|
+
}
|
|
507
|
+
return -1;
|
|
508
|
+
};
|
|
509
|
+
const exprEnd = (i2) => {
|
|
510
|
+
let depth = 0;
|
|
511
|
+
while (i2 < src.length) {
|
|
512
|
+
const c = src[i2];
|
|
513
|
+
const lit = skipLiteral(src, i2);
|
|
514
|
+
if (lit !== null) {
|
|
515
|
+
i2 = lit;
|
|
516
|
+
continue;
|
|
517
|
+
}
|
|
518
|
+
if (c === "(" || c === "[" || c === "{") depth++;
|
|
519
|
+
else if (c === ")" || c === "]" || c === "}") {
|
|
520
|
+
if (depth === 0) return i2;
|
|
521
|
+
depth--;
|
|
522
|
+
} else if (depth === 0 && (c === "," || c === ";")) return i2;
|
|
523
|
+
else if (depth === 0 && c === "?") {
|
|
524
|
+
const inner = ternaryColon(i2);
|
|
525
|
+
if (inner < 0) return src.length;
|
|
526
|
+
i2 = inner + 1;
|
|
527
|
+
continue;
|
|
528
|
+
}
|
|
529
|
+
i2++;
|
|
530
|
+
}
|
|
531
|
+
return src.length;
|
|
532
|
+
};
|
|
533
|
+
const braceEnd = (b) => {
|
|
534
|
+
let depth = 0;
|
|
535
|
+
let i2 = b;
|
|
536
|
+
while (i2 < src.length) {
|
|
537
|
+
const c = src[i2];
|
|
538
|
+
const lit = skipLiteral(src, i2);
|
|
539
|
+
if (lit !== null) {
|
|
540
|
+
i2 = lit;
|
|
541
|
+
continue;
|
|
542
|
+
}
|
|
543
|
+
if (c === "{") depth++;
|
|
544
|
+
else if (c === "}") {
|
|
545
|
+
depth--;
|
|
546
|
+
if (depth === 0) return i2;
|
|
547
|
+
}
|
|
548
|
+
i2++;
|
|
549
|
+
}
|
|
550
|
+
return src.length;
|
|
551
|
+
};
|
|
552
|
+
const stmtEnd = (i2) => {
|
|
553
|
+
let depth = 0;
|
|
554
|
+
while (i2 < src.length) {
|
|
555
|
+
const c = src[i2];
|
|
556
|
+
const lit = skipLiteral(src, i2);
|
|
557
|
+
if (lit !== null) {
|
|
558
|
+
i2 = lit;
|
|
559
|
+
continue;
|
|
560
|
+
}
|
|
561
|
+
if (c === "(" || c === "[" || c === "{") depth++;
|
|
562
|
+
else if (c === ")" || c === "]" || c === "}") {
|
|
563
|
+
if (depth === 0) return i2;
|
|
564
|
+
depth--;
|
|
565
|
+
} else if (depth === 0 && (c === ";" || c === "\n")) return i2;
|
|
566
|
+
i2++;
|
|
567
|
+
}
|
|
568
|
+
return src.length;
|
|
569
|
+
};
|
|
570
|
+
const isIfGuard = (src2, at) => {
|
|
571
|
+
let b = at - 1;
|
|
572
|
+
while (b >= 0 && /\s/.test(src2[b])) b--;
|
|
573
|
+
if (b < 0 || src2[b] !== "(") return false;
|
|
574
|
+
b--;
|
|
575
|
+
while (b >= 0 && /\s/.test(src2[b])) b--;
|
|
576
|
+
return b >= 1 && src2[b] === "f" && src2[b - 1] === "i" && (b < 2 || !/[\w$]/.test(src2[b - 2]));
|
|
577
|
+
};
|
|
578
|
+
const blanks = [];
|
|
579
|
+
let i = 0;
|
|
580
|
+
while (i < src.length) {
|
|
581
|
+
const lit = skipLiteral(src, i);
|
|
582
|
+
if (lit !== null) {
|
|
583
|
+
i = lit;
|
|
584
|
+
continue;
|
|
585
|
+
}
|
|
586
|
+
GUARD.lastIndex = i;
|
|
587
|
+
const m = GUARD.exec(src);
|
|
588
|
+
if (!m) {
|
|
589
|
+
i++;
|
|
590
|
+
continue;
|
|
591
|
+
}
|
|
592
|
+
const browserAfter = m[1] === "!==";
|
|
593
|
+
const j = ws(i + m[0].length);
|
|
594
|
+
const two = src.slice(j, j + 2);
|
|
595
|
+
if (two === "&&" && browserAfter) {
|
|
596
|
+
blanks.push([j + 2, exprEnd(j + 2)]);
|
|
597
|
+
} else if (two === "||" && !browserAfter) {
|
|
598
|
+
blanks.push([j + 2, exprEnd(j + 2)]);
|
|
599
|
+
} else if (src[j] === "?") {
|
|
600
|
+
const colon = ternaryColon(j);
|
|
601
|
+
if (colon < 0) {
|
|
602
|
+
if (browserAfter) blanks.push([j + 1, src.length]);
|
|
603
|
+
} else if (browserAfter) {
|
|
604
|
+
blanks.push([j + 1, colon]);
|
|
605
|
+
} else {
|
|
606
|
+
blanks.push([colon + 1, exprEnd(colon + 1)]);
|
|
607
|
+
}
|
|
608
|
+
} else if (src[j] === ")" && isIfGuard(src, i)) {
|
|
609
|
+
let bodyEnd;
|
|
610
|
+
const k = ws(j + 1);
|
|
611
|
+
if (src[k] === "{") {
|
|
612
|
+
bodyEnd = braceEnd(k);
|
|
613
|
+
if (browserAfter) blanks.push([k + 1, bodyEnd]);
|
|
614
|
+
} else {
|
|
615
|
+
bodyEnd = stmtEnd(k);
|
|
616
|
+
if (browserAfter) blanks.push([k, bodyEnd]);
|
|
617
|
+
}
|
|
618
|
+
const after = ws(bodyEnd + 1);
|
|
619
|
+
if (src.startsWith("else", after)) {
|
|
620
|
+
const e = ws(after + 4);
|
|
621
|
+
if (src[e] === "{") {
|
|
622
|
+
const close = braceEnd(e);
|
|
623
|
+
if (!browserAfter) blanks.push([e + 1, close]);
|
|
624
|
+
} else {
|
|
625
|
+
const stop = stmtEnd(e);
|
|
626
|
+
if (!browserAfter) blanks.push([e, stop]);
|
|
627
|
+
}
|
|
628
|
+
}
|
|
629
|
+
}
|
|
630
|
+
i = j;
|
|
631
|
+
}
|
|
632
|
+
if (blanks.length === 0) return src;
|
|
633
|
+
const out = [...src];
|
|
634
|
+
for (const [a, b] of blanks) {
|
|
635
|
+
for (let k = a; k < b && k < out.length; k++) if (out[k] !== "\n") out[k] = " ";
|
|
636
|
+
}
|
|
637
|
+
return out.join("");
|
|
638
|
+
}
|
|
256
639
|
function scriptOf(source) {
|
|
257
640
|
return source.match(COMPONENT_RE)?.[1] ?? null;
|
|
258
641
|
}
|
|
259
642
|
async function loadConfig(root) {
|
|
260
|
-
const file =
|
|
261
|
-
if (!
|
|
643
|
+
const file = path2.join(root, "rosetack.config.js");
|
|
644
|
+
if (!fs3.existsSync(file)) return { plugins: [], i18n: {} };
|
|
262
645
|
const mod = await import(pathToFileURL(file).href + `?t=${Date.now()}`);
|
|
263
646
|
return {
|
|
264
647
|
plugins: mod.default ?? [],
|
|
@@ -271,12 +654,12 @@ async function loadPlugins(root) {
|
|
|
271
654
|
function resolveRoseImports(script, fromFile, registry) {
|
|
272
655
|
const imports = [];
|
|
273
656
|
const resolve2 = (spec, at) => {
|
|
274
|
-
const abs =
|
|
657
|
+
const abs = path2.resolve(path2.dirname(fromFile), spec);
|
|
275
658
|
const hit = registry.get(abs);
|
|
276
659
|
if (!hit) {
|
|
277
660
|
throw new RoseError(
|
|
278
661
|
"E-IMPORT",
|
|
279
|
-
`${
|
|
662
|
+
`${path2.basename(fromFile)}: cannot import '${spec}' - no .rose file at ${abs}. A component lives under src/components/ (or src/pages/) and is imported by relative path.`,
|
|
280
663
|
{
|
|
281
664
|
file: fromFile,
|
|
282
665
|
line: lineOf(script, at),
|
|
@@ -311,16 +694,45 @@ function nodeOnlyImports(importStmts) {
|
|
|
311
694
|
}
|
|
312
695
|
return out;
|
|
313
696
|
}
|
|
314
|
-
function wireEventBindings(template, actionNames) {
|
|
697
|
+
function wireEventBindings(template, actionNames, filePath = "<template>") {
|
|
315
698
|
const bindings = [];
|
|
316
699
|
let out = "";
|
|
317
700
|
let rest = template;
|
|
701
|
+
const TARGET_MODS = { window: "w", document: "d" };
|
|
702
|
+
const MOD_PRE = {
|
|
703
|
+
preventDefault: () => "e.preventDefault()",
|
|
704
|
+
stopPropagation: () => "e.stopPropagation()",
|
|
705
|
+
self: (p) => `const __self = e.target.closest && e.target.closest('[data-${p}-' + e.type + ']'); if (__self && e.target !== __self) return;`
|
|
706
|
+
};
|
|
707
|
+
const MOD_POST = {
|
|
708
|
+
once: (p) => `const __o = e.target && e.target.closest ? e.target.closest('[data-${p}-' + e.type + ']') : null; if (__o) __o.removeAttribute('data-${p}-' + e.type);`
|
|
709
|
+
};
|
|
710
|
+
const KNOWN_MODS = [...Object.keys(MOD_PRE), ...Object.keys(MOD_POST), ...Object.keys(TARGET_MODS)];
|
|
318
711
|
for (; ; ) {
|
|
319
|
-
const m = /\bon:(\w+)\s*=\s*\{/.exec(rest);
|
|
712
|
+
const m = /\bon:(\w+)((?:\|\w+)*)\s*=\s*\{/.exec(rest);
|
|
320
713
|
if (!m) {
|
|
321
714
|
out += rest;
|
|
322
715
|
break;
|
|
323
716
|
}
|
|
717
|
+
const mods = m[2] ? m[2].slice(1).split("|") : [];
|
|
718
|
+
const targets = mods.filter((mod) => TARGET_MODS[mod]);
|
|
719
|
+
if (targets.length > 1) {
|
|
720
|
+
throw new RoseError(
|
|
721
|
+
"E-TEMPLATE",
|
|
722
|
+
`${filePath}: on:${m[1]} carries both |${targets.join(" and |")}`,
|
|
723
|
+
{ hint: "a handler binds to one target - the element (default), |window or |document" }
|
|
724
|
+
);
|
|
725
|
+
}
|
|
726
|
+
const prefix = targets.length ? "on" + TARGET_MODS[targets[0]] : "on";
|
|
727
|
+
for (const mod of mods) {
|
|
728
|
+
if (!KNOWN_MODS.includes(mod)) {
|
|
729
|
+
throw new RoseError(
|
|
730
|
+
"E-TEMPLATE",
|
|
731
|
+
`${filePath}: unknown event modifier |${mod}`,
|
|
732
|
+
{ hint: `the supported modifiers are ${KNOWN_MODS.map((k) => "|" + k).join(" ")} - capture/passive are listener options a delegated listener cannot carry per element; anything else belongs inside the handler body` }
|
|
733
|
+
);
|
|
734
|
+
}
|
|
735
|
+
}
|
|
324
736
|
out += rest.slice(0, m.index);
|
|
325
737
|
let i = m.index + m[0].length;
|
|
326
738
|
let depth = 1;
|
|
@@ -342,7 +754,24 @@ function wireEventBindings(template, actionNames) {
|
|
|
342
754
|
i++;
|
|
343
755
|
}
|
|
344
756
|
const expr = rest.slice(m.index + m[0].length, i).trim();
|
|
345
|
-
|
|
757
|
+
const wrap = (body) => {
|
|
758
|
+
if (!mods.length) return body;
|
|
759
|
+
const pre = mods.filter((mod) => MOD_PRE[mod]).map((mod) => MOD_PRE[mod](prefix));
|
|
760
|
+
const post = mods.filter((mod) => MOD_POST[mod]).map((mod) => MOD_POST[mod](prefix));
|
|
761
|
+
return `(e) => {${pre.length ? " " + pre.join("; ") + ";" : ""} (${body})(e);${post.length ? " " + post.join("; ") + ";" : ""} }`;
|
|
762
|
+
};
|
|
763
|
+
if (mods.length && actionNames.has(expr)) {
|
|
764
|
+
throw new RoseError(
|
|
765
|
+
"E-TEMPLATE",
|
|
766
|
+
`${filePath}: event modifiers are not supported on the server action ${expr}`,
|
|
767
|
+
{ hint: "$action already preventDefaults - drop the modifiers, or bind a local handler that calls $action" }
|
|
768
|
+
);
|
|
769
|
+
}
|
|
770
|
+
if (mods.length) {
|
|
771
|
+
const name = `__h${bindings.length}`;
|
|
772
|
+
out += `data-${prefix}-${m[1]}="${name}"`;
|
|
773
|
+
bindings.push({ event: m[1], fn: `${name}: ${wrap(expr)}` });
|
|
774
|
+
} else if (actionNames.has(expr)) {
|
|
346
775
|
out += `data-on-${m[1]}="$action:${expr}"`;
|
|
347
776
|
} else if (/^\w+$/.test(expr)) {
|
|
348
777
|
out += `data-on-${m[1]}="${expr}"`;
|
|
@@ -359,12 +788,13 @@ function wireEventBindings(template, actionNames) {
|
|
|
359
788
|
function scanSlotDecls(filePath) {
|
|
360
789
|
let src;
|
|
361
790
|
try {
|
|
362
|
-
src =
|
|
791
|
+
src = fs3.readFileSync(filePath, "utf-8");
|
|
363
792
|
} catch {
|
|
364
793
|
return [];
|
|
365
794
|
}
|
|
366
|
-
const
|
|
367
|
-
const
|
|
795
|
+
const noScript = src.replace(COMPONENT_RE, "");
|
|
796
|
+
const noBlocks = noScript.replace(STYLE_RE, "");
|
|
797
|
+
const tpl = noBlocks.match(TEMPLATE_RE)?.[1] ?? noBlocks.replace(HEAD_RE, "").trim();
|
|
368
798
|
const out = [];
|
|
369
799
|
for (const m of tpl.matchAll(/<slot\s+([^>]*?)\/?>/g)) {
|
|
370
800
|
const name = /\bname\s*=\s*["'](\w+)["']/.exec(m[1]);
|
|
@@ -412,7 +842,7 @@ function hoistImports(script) {
|
|
|
412
842
|
return { imports: imports.join("\n"), rest: rest.join("\n") };
|
|
413
843
|
}
|
|
414
844
|
async function compileComponent(filePath, publicDir, scopeKey, isApi = false, plugins = [], registry = /* @__PURE__ */ new Map()) {
|
|
415
|
-
let source = await
|
|
845
|
+
let source = await fs3.promises.readFile(filePath, "utf-8");
|
|
416
846
|
for (const p of plugins) {
|
|
417
847
|
if (!p.transform) continue;
|
|
418
848
|
try {
|
|
@@ -420,7 +850,7 @@ async function compileComponent(filePath, publicDir, scopeKey, isApi = false, pl
|
|
|
420
850
|
} catch (err) {
|
|
421
851
|
throw new RoseError(
|
|
422
852
|
"E-PLUGIN",
|
|
423
|
-
`plugin ${p.name} failed on ${
|
|
853
|
+
`plugin ${p.name} failed on ${path2.basename(filePath)}: ${err instanceof Error ? err.message : String(err)}`,
|
|
424
854
|
{ file: filePath, hint: "the error above came from inside the plugin - fix its transform() (or remove the plugin from rosetack.config.js)" }
|
|
425
855
|
);
|
|
426
856
|
}
|
|
@@ -432,6 +862,12 @@ async function compileComponent(filePath, publicDir, scopeKey, isApi = false, pl
|
|
|
432
862
|
const usesContext2 = /getContext\s*\(/.test(rawScript2);
|
|
433
863
|
const hasPrerender = !usesContext2 && /(?:^|\n)\s*export\s+(?:const|let|var)\s+prerender\s*=\s*true\b/.test(rawScript2);
|
|
434
864
|
const hoisted = hoistImports(resolveRoseImports(rawScript2, filePath, registry).script);
|
|
865
|
+
const ownRuntimeImports = new Set(
|
|
866
|
+
[...rawScript2.matchAll(/import\s*\{([^}]*)\}\s*from\s*['"]\.\/runtime\.js['"]/g)].flatMap((m) => m[1].split(",").map((s) => s.trim().split(/\s+as\s+/)[0]).filter(Boolean))
|
|
867
|
+
);
|
|
868
|
+
const helpers = API_RUNTIME_HELPERS.filter((n) => !ownRuntimeImports.has(n));
|
|
869
|
+
const runtimeImport = helpers.length > 0 ? `import { ${helpers.join(", ")} } from './runtime.js';
|
|
870
|
+
` : "";
|
|
435
871
|
return {
|
|
436
872
|
ssr: "",
|
|
437
873
|
client: "",
|
|
@@ -440,24 +876,24 @@ async function compileComponent(filePath, publicDir, scopeKey, isApi = false, pl
|
|
|
440
876
|
guardName: null,
|
|
441
877
|
style: "",
|
|
442
878
|
hasParams: false,
|
|
443
|
-
api:
|
|
444
|
-
${rewriteRoseImports(`${hoisted.imports}
|
|
879
|
+
api: `${runtimeImport}${rewriteRoseImports(`${hoisted.imports}
|
|
445
880
|
${hoisted.rest}`, "ssr").trim()}`,
|
|
446
881
|
apiMethods,
|
|
447
882
|
hasPrerender,
|
|
448
883
|
usesContext: usesContext2
|
|
449
884
|
};
|
|
450
885
|
}
|
|
451
|
-
const
|
|
886
|
+
const sourceNoScript = source.replace(COMPONENT_RE, "");
|
|
887
|
+
const sourceNoHead = sourceNoScript.replace(HEAD_RE, "");
|
|
452
888
|
const styleMatch = sourceNoHead.match(STYLE_RE);
|
|
453
889
|
const scopedStyle = styleMatch?.[1] ? scopeCss(styleMatch[1], scopeKey) : "";
|
|
454
890
|
const sourceNoBlocks = sourceNoHead.replace(STYLE_RE, "");
|
|
455
|
-
const scriptMatch =
|
|
891
|
+
const scriptMatch = source.match(COMPONENT_RE);
|
|
456
892
|
const roseResolved = resolveRoseImports(scriptMatch?.[1] ?? "", filePath, registry);
|
|
457
893
|
const rawScript = roseResolved.script;
|
|
458
894
|
const roseImports = roseResolved.imports;
|
|
459
895
|
const { imports: importStmts, rest: scriptNoImports } = hoistImports(rawScript);
|
|
460
|
-
if (
|
|
896
|
+
if (path2.basename(filePath) !== "_middleware.rose") {
|
|
461
897
|
for (const spec of nodeOnlyImports(importStmts)) {
|
|
462
898
|
const at = importStmts.indexOf(spec);
|
|
463
899
|
throw new RoseError(
|
|
@@ -483,6 +919,8 @@ ${hoisted.rest}`, "ssr").trim()}`,
|
|
|
483
919
|
const hasParams = /(?:^|\n)\s*export\s+(?:(?:const|let|var)\s+|(?:async\s+)?function\s+)params\b/.test(rawScript);
|
|
484
920
|
const revalidateMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+revalidate\s*=\s*(\d+)\s*;?/);
|
|
485
921
|
const revalidate = revalidateMatch ? Number(revalidateMatch[1]) : void 0;
|
|
922
|
+
const cacheMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+cache\s*=\s*(\d+)\s*;?/);
|
|
923
|
+
const cacheSeconds = cacheMatch ? Number(cacheMatch[1]) : void 0;
|
|
486
924
|
const prefetchMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+prefetch\s*=\s*['"`](\w+)['"`]\s*;?/);
|
|
487
925
|
const prefetch = prefetchMatch ? prefetchMatch[1] : void 0;
|
|
488
926
|
if (prefetch && !["off", "hover", "viewport", "all"].includes(prefetch)) {
|
|
@@ -512,8 +950,11 @@ ${hoisted.rest}`, "ssr").trim()}`,
|
|
|
512
950
|
}
|
|
513
951
|
const csrMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+csr\s*=\s*(true|false)\s*;?/);
|
|
514
952
|
const csr = csrMatch ? csrMatch[1] !== "false" : void 0;
|
|
953
|
+
const shellMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+shell\s*=\s*(true|false)\s*;?/);
|
|
954
|
+
const shell = shellMatch ? shellMatch[1] !== "false" : void 0;
|
|
515
955
|
const bufferMatch = rawScript.match(/(?:^|\n)\s*export\s+(?:const|let|var)\s+buffer\s*=\s*(true|false)\s*;?/);
|
|
516
956
|
const buffer = bufferMatch ? bufferMatch[1] !== "false" : void 0;
|
|
957
|
+
const controlSignal = /\b(?:redirect|notFound)\s*\(/.test(rawScript) || void 0;
|
|
517
958
|
if (csr === false) {
|
|
518
959
|
const dead = /\son:[a-z]+\s*=/.exec(source) ?? /\b(?:onMount|onCleanup|refresh)\s*\(/.exec(rawScript);
|
|
519
960
|
if (dead) {
|
|
@@ -584,30 +1025,32 @@ ${hoisted.rest}`, "ssr").trim()}`,
|
|
|
584
1025
|
}
|
|
585
1026
|
const lifecycle = rawScript.match(/\b(?:onMount|onCleanup|refresh|adopt|\$action|\$setState)\s*\(/);
|
|
586
1027
|
if (lifecycle) clientReasons.push(`${lifecycle[0].replace(/\s*\($/, "")}()`);
|
|
1028
|
+
if (source.includes("{#defer")) clientReasons.push("{#defer} progressive content");
|
|
587
1029
|
const needsClient = clientReasons.length > 0;
|
|
588
1030
|
const jsWarnings = [];
|
|
589
1031
|
if (!needsClient) {
|
|
590
1032
|
const codeOnly = stripComments(source);
|
|
591
1033
|
const scriptCodeOnly = stripComments(rawScript);
|
|
1034
|
+
const scriptScannable = stripGuardedBranches(scriptCodeOnly);
|
|
592
1035
|
if (/\son[a-z]+\s*=\s*["'][^"']*["']/i.test(codeOnly)) {
|
|
593
1036
|
jsWarnings.push('an inline on* attribute (e.g. onclick="...") - it cannot fire without the bundle; use on:click or set csr = true');
|
|
594
1037
|
}
|
|
595
1038
|
if (/javascript:/i.test(codeOnly)) {
|
|
596
1039
|
jsWarnings.push("a javascript: URL - it needs the bundle to run; link to a real route");
|
|
597
1040
|
}
|
|
598
|
-
if (/\b(?:eval|new Function)\s*\(/.test(
|
|
1041
|
+
if (/\b(?:eval|new Function)\s*\(/.test(scriptScannable)) {
|
|
599
1042
|
jsWarnings.push("eval()/new Function() - client code the predicate cannot see");
|
|
600
1043
|
}
|
|
601
|
-
if (/\b(?:document|window|localStorage|sessionStorage)\s*\.|\b(?:add|remove)EventListener\s*\(|\brequestAnimationFrame\s*\(|\bMutationObserver\b|\bnavigator\s*\.|\blocation\s*\.\s*(?:href|assign|replace|reload|pathname|search|hash|origin)\b|\b(?:setTimeout|setInterval)\s*\(/.test(
|
|
1044
|
+
if (/\b(?:document|window|localStorage|sessionStorage)\s*\.|\b(?:add|remove)EventListener\s*\(|\brequestAnimationFrame\s*\(|\bMutationObserver\b|\bnavigator\s*\.|\blocation\s*\.\s*(?:href|assign|replace|reload|pathname|search|hash|origin)\b|\b(?:setTimeout|setInterval)\s*\(/.test(scriptScannable)) {
|
|
602
1045
|
jsWarnings.push("browser-only code (document./window./addEventListener/a timer/...) - a JS-free document never ships this script to the browser, so it throws on the server or runs there and never reaches the client; if the route needs the browser, set csr = true");
|
|
603
1046
|
}
|
|
604
1047
|
}
|
|
605
1048
|
const templateMatch = sourceNoBlocks.match(TEMPLATE_RE);
|
|
606
|
-
const headContent =
|
|
1049
|
+
const headContent = sourceNoScript.match(HEAD_RE)?.[1] ?? "";
|
|
607
1050
|
const rawTemplate = templateMatch ? templateMatch[1] : sourceNoBlocks.replace(COMPONENT_RE, "").trim();
|
|
608
1051
|
const template = scopedStyle ? injectScopeAttr(inlineImages(rawTemplate, publicDir), scopeKey) : inlineImages(rawTemplate, publicDir);
|
|
609
1052
|
const decls = extractDecls(script);
|
|
610
|
-
const stateDecls = decls.filter((d) => d.kind === "state");
|
|
1053
|
+
const stateDecls = decls.filter((d) => d.kind === "state" || d.kind === "kv" || d.kind === "persist");
|
|
611
1054
|
const setterNames = /* @__PURE__ */ new Map();
|
|
612
1055
|
stateDecls.forEach((s) => setterNames.set(s.name, `set${capitalize(s.name)}`));
|
|
613
1056
|
const declCode = (d) => {
|
|
@@ -617,6 +1060,17 @@ ${hoisted.rest}`, "ssr").trim()}`,
|
|
|
617
1060
|
}
|
|
618
1061
|
const isFn = d.expr.includes("=>") || d.expr.startsWith("function");
|
|
619
1062
|
const fn = isFn ? d.expr : `() => (${d.expr})`;
|
|
1063
|
+
if (d.kind === "persist") {
|
|
1064
|
+
return `const [${d.name}, ${setterNames.get(d.name)}] = persistState(${JSON.stringify(key)}, ${d.expr});`;
|
|
1065
|
+
}
|
|
1066
|
+
if (d.kind === "kv") {
|
|
1067
|
+
const mTtl = /^(.*)\s*,\s*(\d+)\s*$/s.exec(d.expr);
|
|
1068
|
+
const fnExpr = mTtl ? mTtl[1] : d.expr;
|
|
1069
|
+
const ttl = mTtl ? mTtl[2] : "300";
|
|
1070
|
+
return `const __had_${d.name} = hasState(${JSON.stringify(key)});
|
|
1071
|
+
const [${d.name}, set${capitalize(d.name)}] = state(${JSON.stringify(key)}, null);
|
|
1072
|
+
if (!__had_${d.name}) set${capitalize(d.name)}(await globalThis.__rosetackKvApi.kvMemo(${JSON.stringify("__kvh:" + scopeKey + ":" + d.name)}, ${fnExpr}, ${ttl}));`;
|
|
1073
|
+
}
|
|
620
1074
|
return `const __had_${d.name} = hasState(${JSON.stringify(key)});
|
|
621
1075
|
const [${d.name}, set${capitalize(d.name)}] = state(${JSON.stringify(key)}, null);
|
|
622
1076
|
if (!__had_${d.name}) set${capitalize(d.name)}(await $data(${fn}));`;
|
|
@@ -641,15 +1095,120 @@ if (!__had_${d.name}) set${capitalize(d.name)}(await $data(${fn}));`;
|
|
|
641
1095
|
const stateDeclsCode = nestedDecls.filter((d) => d.kind === "state").map(declCode).join("\n");
|
|
642
1096
|
const dataDeclsCode = nestedDecls.filter((d) => d.kind === "data").map(declCode).join("\n");
|
|
643
1097
|
const templateCalled = callifyTemplateExprs(template, stateDecls.map((s) => s.name));
|
|
644
|
-
const
|
|
645
|
-
const
|
|
646
|
-
const ssrTemplate = wired.template.replace(SLOT_NAMED_RE, (_w, attrs) => `{__slot(${encodeSlotCall(attrs)})}`).replace(SLOT_RE, "{__slot__}");
|
|
1098
|
+
const imgDefaulted = templateCalled.replace(/<img\b(?![^>]*?\sloading=)/gi, '<img loading="lazy"').replace(/<img\b(?![^>]*?\sdecoding=)/gi, '<img decoding="async"');
|
|
1099
|
+
const wired = wireEventBindings(imgDefaulted, actionNames, filePath);
|
|
647
1100
|
const stateKeys = decls.map((d) => d.name);
|
|
1101
|
+
const bindBindings = [];
|
|
1102
|
+
let bindCounter = 0;
|
|
1103
|
+
const bindExpanded = wired.template.replace(
|
|
1104
|
+
/\sbind:(value|checked|this)\s*=\s*\{([\w$]+)(?:\(\))?\}/g,
|
|
1105
|
+
(whole, kind, name) => {
|
|
1106
|
+
if (!stateKeys.includes(name)) {
|
|
1107
|
+
throw new Error(
|
|
1108
|
+
`${filePath}: bind:${kind}={${name}} must name a $state declaration` + (stateKeys.length ? ` (state keys here: ${stateKeys.join(", ")})` : " (this file declares no $state)")
|
|
1109
|
+
);
|
|
1110
|
+
}
|
|
1111
|
+
if (kind === "this") return ` data-bind-this="${name}"`;
|
|
1112
|
+
const setter = setterNames.get(name);
|
|
1113
|
+
const evt = kind === "checked" ? "change" : "input";
|
|
1114
|
+
const hname = `__rvbind_${scopeKey.replace(/\W/g, "_")}_${bindCounter++}`;
|
|
1115
|
+
bindBindings.push({
|
|
1116
|
+
event: evt,
|
|
1117
|
+
fn: kind === "checked" ? `${hname}: (e) => ${setter}(e.target.checked)` : `${hname}: (e) => { const t = e.target; ${setter}(t.type === 'number' || t.type === 'range' ? t.valueAsNumber : t.value); }`
|
|
1118
|
+
});
|
|
1119
|
+
const evtAttr = kind === "checked" ? ` data-on-change="${hname}"` : ` data-on-input="${hname}" data-on-change="${hname}"`;
|
|
1120
|
+
return ` ${kind}={${name}()}${evtAttr}`;
|
|
1121
|
+
}
|
|
1122
|
+
);
|
|
648
1123
|
const comps = new Map(roseImports.map((r) => {
|
|
649
|
-
const abs =
|
|
1124
|
+
const abs = path2.resolve(path2.dirname(filePath), r.specifier);
|
|
650
1125
|
const hit = registry.get(abs);
|
|
651
1126
|
return [r.name, { index: hit.index, slots: hit.slots }];
|
|
652
1127
|
}));
|
|
1128
|
+
const groupBindings = [];
|
|
1129
|
+
let groupCounter = 0;
|
|
1130
|
+
const TAG_SCAN_RE = /<([a-zA-Z][^\s>/]*)((?:[^>"']|"[^"]*"|'[^']*')*?)(\/?)>/g;
|
|
1131
|
+
const groupExpanded = (() => {
|
|
1132
|
+
if (!bindExpanded.includes("bind:group")) return bindExpanded;
|
|
1133
|
+
let out = "";
|
|
1134
|
+
let pos2 = 0;
|
|
1135
|
+
let m;
|
|
1136
|
+
TAG_SCAN_RE.lastIndex = 0;
|
|
1137
|
+
while (m = TAG_SCAN_RE.exec(bindExpanded)) {
|
|
1138
|
+
const [whole, tag, attrs, selfClose] = m;
|
|
1139
|
+
const gm = /\sbind:group\s*=\s*\{([\w$]+)(?:\(\))?\}/.exec(attrs);
|
|
1140
|
+
if (!gm) continue;
|
|
1141
|
+
const name = gm[1];
|
|
1142
|
+
if (!stateKeys.includes(name)) {
|
|
1143
|
+
throw new RoseError(
|
|
1144
|
+
"E-TEMPLATE",
|
|
1145
|
+
`${filePath}: bind:group={${name}} must name a $state declaration`,
|
|
1146
|
+
{ hint: "the group state holds the selected value (radio) or an ARRAY of checked values (checkbox) - declare it: let " + name + ' = $state("")' }
|
|
1147
|
+
);
|
|
1148
|
+
}
|
|
1149
|
+
if (!/\stype\s*=\s*["'](radio|checkbox)["']/.test(attrs)) {
|
|
1150
|
+
throw new RoseError(
|
|
1151
|
+
"E-TEMPLATE",
|
|
1152
|
+
`${filePath}: bind:group is for radio and checkbox inputs`,
|
|
1153
|
+
{ hint: '<input type="radio" value="v" bind:group={state}> holds the selected value; type="checkbox" holds an ARRAY of the checked values (declare the state as $state([]))' }
|
|
1154
|
+
);
|
|
1155
|
+
}
|
|
1156
|
+
const isArrayGroup = /\stype\s*=\s*["']checkbox["']/.test(attrs);
|
|
1157
|
+
const vm = /\svalue\s*=\s*"([^"]*)"|\svalue\s*=\s*'([^']*)'/.exec(attrs);
|
|
1158
|
+
if (!vm || /\{/.test(vm[0])) {
|
|
1159
|
+
throw new RoseError(
|
|
1160
|
+
"E-TEMPLATE",
|
|
1161
|
+
`${filePath}: a bind:group input needs a static value attribute`,
|
|
1162
|
+
{ hint: '<input type="radio" value="free" bind:group={plan}> - the value IS what the state receives' }
|
|
1163
|
+
);
|
|
1164
|
+
}
|
|
1165
|
+
if (/\schecked\s*=/.test(attrs)) {
|
|
1166
|
+
throw new RoseError(
|
|
1167
|
+
"E-TEMPLATE",
|
|
1168
|
+
`${filePath}: a bind:group input cannot also carry checked=`,
|
|
1169
|
+
{ hint: "the group state alone decides which inputs are checked" }
|
|
1170
|
+
);
|
|
1171
|
+
}
|
|
1172
|
+
const setter = setterNames.get(name);
|
|
1173
|
+
const hname = `__rvbg_${scopeKey.replace(/\W/g, "_")}_${groupCounter++}`;
|
|
1174
|
+
const groupValue = JSON.stringify(vm[1] ?? vm[2]);
|
|
1175
|
+
const checkedExpr = isArrayGroup ? `${name}().includes(${groupValue})` : `${name}() === ${groupValue}`;
|
|
1176
|
+
const handlerBody = isArrayGroup ? `${setter}(e.target.checked ? [...${name}(), ${groupValue}] : ${name}().filter((x) => x !== ${groupValue}))` : `${setter}(e.target.value)`;
|
|
1177
|
+
groupBindings.push({ event: "change", fn: `${hname}: (e) => { ${handlerBody}; }` });
|
|
1178
|
+
const newAttrs = attrs.replace(gm[0], ` checked={${checkedExpr}} data-on-change="${hname}"`);
|
|
1179
|
+
out += bindExpanded.slice(pos2, m.index) + `<${tag}${newAttrs}${selfClose}>`;
|
|
1180
|
+
pos2 = m.index + whole.length;
|
|
1181
|
+
}
|
|
1182
|
+
if (pos2 === 0) return bindExpanded;
|
|
1183
|
+
out += bindExpanded.slice(pos2);
|
|
1184
|
+
return out;
|
|
1185
|
+
})();
|
|
1186
|
+
const eventBindings = wired.bindings.concat(bindBindings, groupBindings);
|
|
1187
|
+
const useExpanded = groupExpanded.replace(
|
|
1188
|
+
/\suse:([\w-]+)(\s*=\s*\{([\s\S]*?)\})?/g,
|
|
1189
|
+
(_w, name, hasParam, expr) => hasParam ? ` data-use="${name}" data-use-param={JSON.stringify(${expr})}` : ` data-use="${name}"`
|
|
1190
|
+
);
|
|
1191
|
+
const classExpanded = expandClassDirectives(useExpanded, filePath);
|
|
1192
|
+
const styleExpanded = expandStyleDirectives(classExpanded, filePath);
|
|
1193
|
+
const keyExpanded = expandKeyBlocks(styleExpanded, filePath);
|
|
1194
|
+
const elseExpanded = expandIfElse(keyExpanded);
|
|
1195
|
+
const deferExpanded = expandDeferBlocks(elseExpanded);
|
|
1196
|
+
const fbExpanded = expandBoundaryFallbacks(deferExpanded.template, filePath);
|
|
1197
|
+
const ssrTemplate = rewriteQuotedExprAttrs(fbExpanded.replace(SLOT_NAMED_RE, (_w, attrs, fallback) => {
|
|
1198
|
+
const call = `{__slot(${encodeSlotCall(attrs)})}`;
|
|
1199
|
+
if (fallback) {
|
|
1200
|
+
if (/\{[^{}]*\}/.test(fallback)) {
|
|
1201
|
+
throw new RoseError(
|
|
1202
|
+
"E-TEMPLATE",
|
|
1203
|
+
`${filePath}: slot fallback content must be static markup`,
|
|
1204
|
+
{ hint: "a {expr} inside a slot fallback has no reactive scope here - render the dynamic part in the parent and pass it as the slot content" }
|
|
1205
|
+
);
|
|
1206
|
+
}
|
|
1207
|
+
return `{__slot(${encodeSlotCall(attrs)}, ${JSON.stringify(fallback)})}`;
|
|
1208
|
+
}
|
|
1209
|
+
return call;
|
|
1210
|
+
}).replace(SLOT_RE, (_w, fallback) => fallback && fallback.trim() ? `{__slotDefault(${JSON.stringify(fallback)})}` : "{__slot__}"), comps);
|
|
1211
|
+
assertKnownDirectives(ssrTemplate, filePath);
|
|
653
1212
|
const compiledTemplate = compileTemplate(ssrTemplate, "h", "__c", null, 0, true, comps);
|
|
654
1213
|
const compiledHead = headContent.trim() ? compileHead(headContent) : "";
|
|
655
1214
|
const hasNamedSlots = /<slot\s+[^>]*\bname\s*=/.test(template);
|
|
@@ -657,7 +1216,7 @@ if (!__had_${d.name}) set${capitalize(d.name)}(await $data(${fn}));`;
|
|
|
657
1216
|
${actions.map((a) => a.stmt).join("\n")}` : exportStmts;
|
|
658
1217
|
const ssrGuard = guard ? `
|
|
659
1218
|
${guard}` : "";
|
|
660
|
-
const isMiddleware =
|
|
1219
|
+
const isMiddleware = path2.basename(filePath) === "_middleware.rose";
|
|
661
1220
|
const ssr = isMiddleware ? `${RUNTIME_IMPORTS}
|
|
662
1221
|
|
|
663
1222
|
${importStmts}
|
|
@@ -666,8 +1225,8 @@ ${ssrExports}
|
|
|
666
1225
|
${ssrGuard}
|
|
667
1226
|
|
|
668
1227
|
${cleanScript}
|
|
669
|
-
` : generateSSR(cleanScript, compiledTemplate, stateDeclsCode, ssrExports, compiledHead, props, hasNamedSlots, importStmts, isComponent, ssrGuard, actions.length > 0, dataDeclsCode);
|
|
670
|
-
const client = generateClient(cleanScript, compiledTemplate, stateDeclsCode, eventBindings, exportStmts, compiledHead, props, hasNamedSlots, importStmts, isComponent, dataDeclsCode);
|
|
1228
|
+
` : generateSSR(cleanScript + deferBootCode(deferExpanded.count, deferExpanded.holds), compiledTemplate, stateDeclsCode, ssrExports, compiledHead, props, hasNamedSlots, importStmts, isComponent, ssrGuard, actions.length > 0, dataDeclsCode);
|
|
1229
|
+
const client = generateClient(cleanScript + deferBootCode(deferExpanded.count, deferExpanded.holds), compiledTemplate, stateDeclsCode, eventBindings, exportStmts, compiledHead, props, hasNamedSlots, importStmts, isComponent, dataDeclsCode);
|
|
671
1230
|
return {
|
|
672
1231
|
ssr: rewriteRoseImports(ssr, "ssr"),
|
|
673
1232
|
client: rewriteRoseImports(client, "client"),
|
|
@@ -678,8 +1237,11 @@ ${cleanScript}
|
|
|
678
1237
|
hasParams,
|
|
679
1238
|
usesContext,
|
|
680
1239
|
revalidate,
|
|
1240
|
+
cache: cacheSeconds,
|
|
681
1241
|
csr,
|
|
1242
|
+
shell,
|
|
682
1243
|
buffer,
|
|
1244
|
+
controlSignal,
|
|
683
1245
|
prefetch,
|
|
684
1246
|
vitals,
|
|
685
1247
|
bundle,
|
|
@@ -866,6 +1428,20 @@ function extractExports(script) {
|
|
|
866
1428
|
out += script.slice(pos);
|
|
867
1429
|
return { clean: out, exports: stmts.join("\n"), actions, props, guard: guards.join("\n") };
|
|
868
1430
|
}
|
|
1431
|
+
var REGEX_PRECEDERS = new Set("(,=:[!&|?{};+-*%<>~^".split(""));
|
|
1432
|
+
function isRegexStart(src, i) {
|
|
1433
|
+
let j = i - 1;
|
|
1434
|
+
while (j >= 0 && /\s/.test(src[j])) j--;
|
|
1435
|
+
if (j < 0) return true;
|
|
1436
|
+
const p = src[j];
|
|
1437
|
+
if (REGEX_PRECEDERS.has(p)) return true;
|
|
1438
|
+
if (/[A-Za-z0-9_$]/.test(p)) {
|
|
1439
|
+
const w = /([A-Za-z_$][A-Za-z0-9_$]*)$/.exec(src.slice(0, j + 1));
|
|
1440
|
+
if (!w) return false;
|
|
1441
|
+
return ["return", "typeof", "instanceof", "in", "of", "new", "delete", "void", "throw", "case", "do", "else"].includes(w[1]);
|
|
1442
|
+
}
|
|
1443
|
+
return false;
|
|
1444
|
+
}
|
|
869
1445
|
function extractDecls(script) {
|
|
870
1446
|
const decls = [];
|
|
871
1447
|
DECL_RE.lastIndex = 0;
|
|
@@ -957,18 +1533,449 @@ function braceDepthAt(src, index) {
|
|
|
957
1533
|
i = close === -1 ? src.length : close + 2;
|
|
958
1534
|
continue;
|
|
959
1535
|
}
|
|
960
|
-
if (ch === "
|
|
961
|
-
|
|
962
|
-
|
|
1536
|
+
if (ch === "/" && isRegexStart(src, i)) {
|
|
1537
|
+
i++;
|
|
1538
|
+
let inClass = false;
|
|
1539
|
+
while (i < index) {
|
|
1540
|
+
const c2 = src[i];
|
|
1541
|
+
if (c2 === "\\") {
|
|
1542
|
+
i += 2;
|
|
1543
|
+
continue;
|
|
1544
|
+
}
|
|
1545
|
+
if (inClass) {
|
|
1546
|
+
if (c2 === "]") inClass = false;
|
|
1547
|
+
i++;
|
|
1548
|
+
continue;
|
|
1549
|
+
}
|
|
1550
|
+
if (c2 === "[") {
|
|
1551
|
+
inClass = true;
|
|
1552
|
+
i++;
|
|
1553
|
+
continue;
|
|
1554
|
+
}
|
|
1555
|
+
if (c2 === "/") {
|
|
1556
|
+
i++;
|
|
1557
|
+
break;
|
|
1558
|
+
}
|
|
1559
|
+
if (c2 === "\n") break;
|
|
1560
|
+
i++;
|
|
1561
|
+
}
|
|
1562
|
+
while (i < index && /[a-z]/.test(src[i])) i++;
|
|
1563
|
+
continue;
|
|
1564
|
+
}
|
|
1565
|
+
if (ch === "{") depth++;
|
|
1566
|
+
else if (ch === "}") depth--;
|
|
1567
|
+
i++;
|
|
1568
|
+
}
|
|
1569
|
+
return depth;
|
|
1570
|
+
}
|
|
1571
|
+
function autoCall(expr) {
|
|
1572
|
+
const e = expr.trim();
|
|
1573
|
+
return /^[A-Za-z_$][\w$]*$/.test(e) ? `${e}()` : e;
|
|
1574
|
+
}
|
|
1575
|
+
var DEFER_ENABLED = true;
|
|
1576
|
+
function expandKeyBlocks(template, filePath) {
|
|
1577
|
+
if (!template.includes("{#key")) return template;
|
|
1578
|
+
for (let pass = 0; pass < 10; pass++) {
|
|
1579
|
+
const OPEN_RE = /\{#key\s+([^}]+)\}/g;
|
|
1580
|
+
OPEN_RE.lastIndex = 0;
|
|
1581
|
+
const openM = OPEN_RE.exec(template);
|
|
1582
|
+
if (!openM) return template;
|
|
1583
|
+
const expr = openM[1].trim();
|
|
1584
|
+
const bodyStart = openM.index + openM[0].length;
|
|
1585
|
+
const TOK_RE = /\{[#\/](?:key|if|each|boundary|island)\b[^}]*\}/g;
|
|
1586
|
+
TOK_RE.lastIndex = bodyStart;
|
|
1587
|
+
let depth = 1;
|
|
1588
|
+
let closeAt = -1;
|
|
1589
|
+
let tm;
|
|
1590
|
+
while (tm = TOK_RE.exec(template)) {
|
|
1591
|
+
if (tm[0].startsWith("{#")) {
|
|
1592
|
+
depth++;
|
|
1593
|
+
continue;
|
|
1594
|
+
}
|
|
1595
|
+
depth--;
|
|
1596
|
+
if (depth === 0) {
|
|
1597
|
+
closeAt = tm.index;
|
|
1598
|
+
break;
|
|
1599
|
+
}
|
|
1600
|
+
}
|
|
1601
|
+
if (closeAt < 0) {
|
|
1602
|
+
throw new RoseError(
|
|
1603
|
+
"E-TEMPLATE",
|
|
1604
|
+
`${filePath}: {#key ${expr}} is never closed`,
|
|
1605
|
+
{ hint: "every {#key} needs its {/key}" }
|
|
1606
|
+
);
|
|
1607
|
+
}
|
|
1608
|
+
template = template.slice(0, openM.index) + `{#each [${expr}] as __rvkv}` + template.slice(bodyStart, closeAt) + "{/each}" + template.slice(closeAt + "{/key}".length);
|
|
1609
|
+
}
|
|
1610
|
+
return template;
|
|
1611
|
+
}
|
|
1612
|
+
function expandIfElseOnce(template) {
|
|
1613
|
+
const TOK_RE = /\{#(?:if|each|boundary|island)\b[^}]*\}|\{\/(?:if|each|boundary|island)\s*\}|\{:else(?:\s+if\s+[^}]*)?\}/g;
|
|
1614
|
+
let out = "";
|
|
1615
|
+
let pos = 0;
|
|
1616
|
+
let changed = false;
|
|
1617
|
+
for (; ; ) {
|
|
1618
|
+
const openM = /\{#(if|each)\s+([^}]+)\}/g.exec(template.slice(pos));
|
|
1619
|
+
if (!openM) {
|
|
1620
|
+
out += template.slice(pos);
|
|
1621
|
+
break;
|
|
1622
|
+
}
|
|
1623
|
+
const kind = openM[1];
|
|
1624
|
+
const head = openM[2];
|
|
1625
|
+
const start = pos + openM.index;
|
|
1626
|
+
const cond = kind === "if" ? head.trim() : "";
|
|
1627
|
+
const bodyStart = start + openM[0].length;
|
|
1628
|
+
out += template.slice(pos, start);
|
|
1629
|
+
TOK_RE.lastIndex = bodyStart;
|
|
1630
|
+
let depth = 1;
|
|
1631
|
+
let closeAt = -1;
|
|
1632
|
+
let closeLen = 0;
|
|
1633
|
+
const elses = [];
|
|
1634
|
+
let tm;
|
|
1635
|
+
while (tm = TOK_RE.exec(template)) {
|
|
1636
|
+
const tok = tm[0];
|
|
1637
|
+
if (tok.startsWith("{:else")) {
|
|
1638
|
+
if (depth === 1) {
|
|
1639
|
+
const condM = /^\{:else\s+if\s+([^}]*)\}$/.exec(tok);
|
|
1640
|
+
elses.push({ at: tm.index, len: tok.length, cond: condM ? condM[1].trim() : null });
|
|
1641
|
+
}
|
|
1642
|
+
continue;
|
|
1643
|
+
}
|
|
1644
|
+
if (tok.startsWith("{#")) {
|
|
1645
|
+
depth++;
|
|
1646
|
+
continue;
|
|
1647
|
+
}
|
|
1648
|
+
depth--;
|
|
1649
|
+
if (depth === 0) {
|
|
1650
|
+
closeAt = tm.index;
|
|
1651
|
+
closeLen = tok.length;
|
|
1652
|
+
break;
|
|
1653
|
+
}
|
|
1654
|
+
}
|
|
1655
|
+
if (closeAt < 0 || elses.length === 0) {
|
|
1656
|
+
out += template.slice(start, closeAt < 0 ? template.length : closeAt + closeLen);
|
|
1657
|
+
if (closeAt < 0) break;
|
|
1658
|
+
pos = closeAt + closeLen;
|
|
1659
|
+
continue;
|
|
1660
|
+
}
|
|
1661
|
+
const body = template.slice(bodyStart, closeAt);
|
|
1662
|
+
if (kind === "each") {
|
|
1663
|
+
const lastBare = [...elses].reverse().find((e) => e.cond === null);
|
|
1664
|
+
if (!lastBare) {
|
|
1665
|
+
out += template.slice(start, closeAt + closeLen);
|
|
1666
|
+
pos = closeAt + closeLen;
|
|
1667
|
+
continue;
|
|
1668
|
+
}
|
|
1669
|
+
const relLast = lastBare.at - bodyStart;
|
|
1670
|
+
const eachBody = body.slice(0, relLast);
|
|
1671
|
+
const elseBody = body.slice(relLast + lastBare.len);
|
|
1672
|
+
const itemsExpr = head.replace(/\s+as\s+[\w,\s]*$/, "").trim();
|
|
1673
|
+
out += template.slice(start, bodyStart) + eachBody + `{/each}{#if !(${itemsExpr}.length)}${elseBody}{/if}`;
|
|
1674
|
+
pos = closeAt + closeLen;
|
|
1675
|
+
changed = true;
|
|
1676
|
+
continue;
|
|
1677
|
+
}
|
|
1678
|
+
const branches = [];
|
|
1679
|
+
let cursor = 0;
|
|
1680
|
+
for (let i = 0; i < elses.length; i++) {
|
|
1681
|
+
const e = elses[i];
|
|
1682
|
+
const rel = e.at - bodyStart;
|
|
1683
|
+
branches.push({ cond: i === 0 ? null : elses[i - 1].cond, body: body.slice(cursor, rel) });
|
|
1684
|
+
cursor = rel + e.len;
|
|
1685
|
+
}
|
|
1686
|
+
branches.push({ cond: elses[elses.length - 1].cond, body: body.slice(cursor) });
|
|
1687
|
+
const first = branches.shift();
|
|
1688
|
+
const build2 = (bs) => {
|
|
1689
|
+
if (!bs.length) return "";
|
|
1690
|
+
const head2 = bs[0];
|
|
1691
|
+
const rest = bs.slice(1);
|
|
1692
|
+
if (head2.cond == null) return head2.body;
|
|
1693
|
+
let s = `{#if ${head2.cond}}${head2.body}{/if}`;
|
|
1694
|
+
if (rest.length) s += `{#if !(${head2.cond})}` + build2(rest) + `{/if}`;
|
|
1695
|
+
return s;
|
|
1696
|
+
};
|
|
1697
|
+
let emitted = `{#if ${cond}}${first.body}{/if}`;
|
|
1698
|
+
if (branches.length) emitted += `{#if !(${cond})}` + build2(branches) + `{/if}`;
|
|
1699
|
+
out += emitted;
|
|
1700
|
+
pos = closeAt + closeLen;
|
|
1701
|
+
changed = true;
|
|
1702
|
+
}
|
|
1703
|
+
return { template: out, changed };
|
|
1704
|
+
}
|
|
1705
|
+
function expandClassDirectives(template, filePath) {
|
|
1706
|
+
if (!template.includes("class:")) return template;
|
|
1707
|
+
const TAG_RE = /<([a-zA-Z][^\s>/]*)((?:[^>"']|"[^"]*"|'[^']*')*?)(\/?)>/g;
|
|
1708
|
+
let out = "";
|
|
1709
|
+
let pos = 0;
|
|
1710
|
+
let m;
|
|
1711
|
+
TAG_RE.lastIndex = 0;
|
|
1712
|
+
while (m = TAG_RE.exec(template)) {
|
|
1713
|
+
const [whole, tag, attrs, selfClose] = m;
|
|
1714
|
+
if (!attrs.includes("class:")) continue;
|
|
1715
|
+
const pairs = [];
|
|
1716
|
+
const NAME_RE = /\sclass:([\w-]+)\s*=\s*\{/g;
|
|
1717
|
+
let nm;
|
|
1718
|
+
while (nm = NAME_RE.exec(attrs)) {
|
|
1719
|
+
let i = nm.index + nm[0].length;
|
|
1720
|
+
let depth = 1;
|
|
1721
|
+
while (i < attrs.length && depth > 0) {
|
|
1722
|
+
const ch = attrs[i];
|
|
1723
|
+
if (ch === '"' || ch === "'") {
|
|
1724
|
+
i = skipQuoted(attrs, i);
|
|
1725
|
+
continue;
|
|
1726
|
+
}
|
|
1727
|
+
if (ch === "{") depth++;
|
|
1728
|
+
else if (ch === "}") depth--;
|
|
1729
|
+
i++;
|
|
1730
|
+
}
|
|
1731
|
+
if (depth !== 0) {
|
|
1732
|
+
throw new RoseError("E-TEMPLATE", `${filePath}: class:${nm[1]}={...} is missing its closing brace`, { file: filePath, hint: "the binding expression needs a matching } before the tag ends" });
|
|
1733
|
+
}
|
|
1734
|
+
pairs.push({ name: nm[1], expr: attrs.slice(nm.index + nm[0].length, i - 1), start: nm.index, end: i });
|
|
1735
|
+
}
|
|
1736
|
+
const clsRe = /(\sclass\s*=\s*)("([^"]*)"|'([^']*)'|\{[^}]*\})/;
|
|
1737
|
+
const clsM = clsRe.exec(attrs);
|
|
1738
|
+
if (clsM && clsM[2].startsWith("{")) {
|
|
1739
|
+
throw new RoseError("E-TEMPLATE", `${filePath}: <${tag}> has both class={...} and class: directives`, { file: filePath, hint: 'merge them: move the dynamic part into a class:NAME={expr} and keep the rest in class="..."' });
|
|
1740
|
+
}
|
|
1741
|
+
const staticCls = clsM ? clsM[3] ?? clsM[4] ?? "" : "";
|
|
1742
|
+
let closure = `(${JSON.stringify(staticCls)}`;
|
|
1743
|
+
for (const p of pairs) {
|
|
1744
|
+
closure += `+((${p.expr})?${JSON.stringify(" " + p.name)}:'')`;
|
|
1745
|
+
}
|
|
1746
|
+
closure += `)`;
|
|
1747
|
+
let newAttrs = attrs;
|
|
1748
|
+
for (let k = pairs.length - 1; k >= 0; k--) {
|
|
1749
|
+
newAttrs = newAttrs.slice(0, pairs[k].start) + newAttrs.slice(pairs[k].end);
|
|
1750
|
+
}
|
|
1751
|
+
if (clsM) {
|
|
1752
|
+
newAttrs = newAttrs.replace(clsRe, ` class={${closure}}`);
|
|
1753
|
+
} else {
|
|
1754
|
+
newAttrs = ` class={${closure}}` + newAttrs;
|
|
1755
|
+
}
|
|
1756
|
+
out += template.slice(pos, m.index) + `<${tag}${newAttrs}${selfClose}>`;
|
|
1757
|
+
pos = m.index + whole.length;
|
|
1758
|
+
}
|
|
1759
|
+
if (pos === 0) return template;
|
|
1760
|
+
out += template.slice(pos);
|
|
1761
|
+
return out;
|
|
1762
|
+
}
|
|
1763
|
+
function expandStyleDirectives(template, filePath) {
|
|
1764
|
+
if (!template.includes("style:")) return template;
|
|
1765
|
+
const TAG_RE = /<([a-zA-Z][^\s>/]*)((?:[^>"']|"[^"]*"|'[^']*')*?)(\/?)>/g;
|
|
1766
|
+
let out = "";
|
|
1767
|
+
let pos = 0;
|
|
1768
|
+
let m;
|
|
1769
|
+
TAG_RE.lastIndex = 0;
|
|
1770
|
+
while (m = TAG_RE.exec(template)) {
|
|
1771
|
+
const [whole, tag, attrs, selfClose] = m;
|
|
1772
|
+
if (!attrs.includes("style:")) continue;
|
|
1773
|
+
const pairs = [];
|
|
1774
|
+
const NAME_RE = /\sstyle:([\w-]+)\s*=\s*\{/g;
|
|
1775
|
+
let nm;
|
|
1776
|
+
while (nm = NAME_RE.exec(attrs)) {
|
|
1777
|
+
let i = nm.index + nm[0].length;
|
|
1778
|
+
let depth = 1;
|
|
1779
|
+
while (i < attrs.length && depth > 0) {
|
|
1780
|
+
const ch = attrs[i];
|
|
1781
|
+
if (ch === '"' || ch === "'") {
|
|
1782
|
+
i = skipQuoted(attrs, i);
|
|
1783
|
+
continue;
|
|
1784
|
+
}
|
|
1785
|
+
if (ch === "{") depth++;
|
|
1786
|
+
else if (ch === "}") depth--;
|
|
1787
|
+
i++;
|
|
1788
|
+
}
|
|
1789
|
+
if (depth !== 0) {
|
|
1790
|
+
throw new RoseError("E-TEMPLATE", `${filePath}: style:${nm[1]}={...} is missing its closing brace`, { file: filePath, hint: "the binding expression needs a matching } before the tag ends" });
|
|
1791
|
+
}
|
|
1792
|
+
pairs.push({ prop: nm[1], expr: attrs.slice(nm.index + nm[0].length, i - 1), start: nm.index, end: i });
|
|
1793
|
+
}
|
|
1794
|
+
const styleRe = /(\sstyle\s*=\s*)("([^"]*)"|'([^']*)'|\{[^}]*\})/;
|
|
1795
|
+
const stM = styleRe.exec(attrs);
|
|
1796
|
+
if (stM && stM[2].startsWith("{")) {
|
|
1797
|
+
throw new RoseError("E-TEMPLATE", `${filePath}: <${tag}> has both style={...} and style: directives`, { file: filePath, hint: 'keep the static declarations in style="..." and move the dynamic ones to style:PROP={expr}' });
|
|
1798
|
+
}
|
|
1799
|
+
const staticStyle = stM ? stM[3] ?? stM[4] ?? "" : "";
|
|
1800
|
+
let closure = `${JSON.stringify(staticStyle.endsWith(";") || staticStyle === "" ? staticStyle : staticStyle + ";")}`;
|
|
1801
|
+
for (const p of pairs) {
|
|
1802
|
+
closure += `+${JSON.stringify(p.prop + ":")}+(${p.expr})+';'`;
|
|
1803
|
+
}
|
|
1804
|
+
let newAttrs = attrs;
|
|
1805
|
+
for (let k = pairs.length - 1; k >= 0; k--) {
|
|
1806
|
+
newAttrs = newAttrs.slice(0, pairs[k].start) + newAttrs.slice(pairs[k].end);
|
|
1807
|
+
}
|
|
1808
|
+
if (stM) {
|
|
1809
|
+
newAttrs = newAttrs.replace(styleRe, ` style={${closure}}`);
|
|
1810
|
+
} else {
|
|
1811
|
+
newAttrs = ` style={${closure}}` + newAttrs;
|
|
1812
|
+
}
|
|
1813
|
+
out += template.slice(pos, m.index) + `<${tag}${newAttrs}${selfClose}>`;
|
|
1814
|
+
pos = m.index + whole.length;
|
|
1815
|
+
}
|
|
1816
|
+
if (pos === 0) return template;
|
|
1817
|
+
out += template.slice(pos);
|
|
1818
|
+
return out;
|
|
1819
|
+
}
|
|
1820
|
+
function expandBoundaryFallbacks(template, filePath) {
|
|
1821
|
+
if (!template.includes("{:fallback")) return template;
|
|
1822
|
+
for (let pass = 0; pass < 10; pass++) {
|
|
1823
|
+
const TOK_RE = /\{#boundary\}|\{\/boundary\}|\{:fallback\}/g;
|
|
1824
|
+
let out = "";
|
|
1825
|
+
let pos = 0;
|
|
1826
|
+
let changed = false;
|
|
1827
|
+
let tm;
|
|
1828
|
+
while (tm = TOK_RE.exec(template)) {
|
|
1829
|
+
if (tm[0] !== "{#boundary}") continue;
|
|
1830
|
+
const start = tm.index;
|
|
1831
|
+
const bodyStart = start + tm[0].length;
|
|
1832
|
+
let depth = 1;
|
|
1833
|
+
let closeAt = -1;
|
|
1834
|
+
let tm2;
|
|
1835
|
+
while (tm2 = TOK_RE.exec(template)) {
|
|
1836
|
+
if (tm2[0] === "{#boundary}") {
|
|
1837
|
+
depth++;
|
|
1838
|
+
continue;
|
|
1839
|
+
}
|
|
1840
|
+
if (tm2[0] === "{/boundary}") {
|
|
1841
|
+
depth--;
|
|
1842
|
+
if (depth === 0) {
|
|
1843
|
+
closeAt = tm2.index;
|
|
1844
|
+
break;
|
|
1845
|
+
}
|
|
1846
|
+
}
|
|
1847
|
+
}
|
|
1848
|
+
if (closeAt < 0) break;
|
|
1849
|
+
const body = template.slice(bodyStart, closeAt);
|
|
1850
|
+
const BTOK2 = /\{#(boundary|if|each|key|island)(?:\s+[^}]*)?\}|\{\/(?:boundary|if|each|key|island)\s*\}|\{:fallback\}/g;
|
|
1851
|
+
const kindStack = ["boundary"];
|
|
1852
|
+
let d = 1;
|
|
1853
|
+
let fbAt = -1;
|
|
1854
|
+
let fbLen = 0;
|
|
1855
|
+
let tm3;
|
|
1856
|
+
BTOK2.lastIndex = 0;
|
|
1857
|
+
while (tm3 = BTOK2.exec(body)) {
|
|
1858
|
+
const tok = tm3[0];
|
|
1859
|
+
if (tok === "{:fallback}") {
|
|
1860
|
+
const top = kindStack[kindStack.length - 1];
|
|
1861
|
+
if (top !== "boundary") {
|
|
1862
|
+
throw new RoseError(
|
|
1863
|
+
"E-TEMPLATE",
|
|
1864
|
+
`${filePath}: {:fallback} must sit directly inside a {#boundary} block`,
|
|
1865
|
+
{ hint: "move it out of the {#if}/{#each} it sits in, or keep the conditional fallback in the parent" }
|
|
1866
|
+
);
|
|
1867
|
+
}
|
|
1868
|
+
if (fbAt >= 0) {
|
|
1869
|
+
throw new RoseError("E-TEMPLATE", `${filePath}: a {#boundary} can carry only one {:fallback}`, { hint: "remove the extra {:fallback} segment" });
|
|
1870
|
+
}
|
|
1871
|
+
fbAt = tm3.index;
|
|
1872
|
+
fbLen = tok.length;
|
|
1873
|
+
continue;
|
|
1874
|
+
}
|
|
1875
|
+
if (tok.startsWith("{#")) {
|
|
1876
|
+
d++;
|
|
1877
|
+
kindStack.push(tok.slice(2, tok.length - 1).trim().split(/\s/)[0]);
|
|
1878
|
+
continue;
|
|
1879
|
+
}
|
|
1880
|
+
d--;
|
|
1881
|
+
kindStack.pop();
|
|
1882
|
+
}
|
|
1883
|
+
if (fbAt < 0) continue;
|
|
1884
|
+
const custom = body.slice(0, fbAt);
|
|
1885
|
+
const fbMarkup = body.slice(fbAt + fbLen);
|
|
1886
|
+
const b64 = Buffer.from(fbMarkup, "utf-8").toString("base64");
|
|
1887
|
+
out += template.slice(pos, start) + `{#boundary __fb="${b64}"}` + custom + "{/boundary}";
|
|
1888
|
+
pos = closeAt + "{/boundary}".length;
|
|
1889
|
+
changed = true;
|
|
1890
|
+
}
|
|
1891
|
+
if (!changed) break;
|
|
1892
|
+
template = out + template.slice(pos);
|
|
1893
|
+
}
|
|
1894
|
+
return template;
|
|
1895
|
+
}
|
|
1896
|
+
function expandIfElse(template) {
|
|
1897
|
+
for (let pass = 0; pass < 10; pass++) {
|
|
1898
|
+
if (!/\{:else\b/.test(template)) return template;
|
|
1899
|
+
const r = expandIfElseOnce(template);
|
|
1900
|
+
template = r.template;
|
|
1901
|
+
if (!r.changed) return template;
|
|
1902
|
+
}
|
|
1903
|
+
return template;
|
|
1904
|
+
}
|
|
1905
|
+
function expandDeferBlocks(template) {
|
|
1906
|
+
if (!DEFER_ENABLED) {
|
|
1907
|
+
const openRe2 = /\{#defer(?:\s+hold=\\d+)?\}/g;
|
|
1908
|
+
let out2 = "";
|
|
1909
|
+
let dpos = 0;
|
|
1910
|
+
for (; ; ) {
|
|
1911
|
+
openRe2.lastIndex = dpos;
|
|
1912
|
+
const openM = openRe2.exec(template);
|
|
1913
|
+
if (!openM) break;
|
|
1914
|
+
const openAt = openM.index;
|
|
1915
|
+
const openLen = openM[0].length;
|
|
1916
|
+
const closeAt = template.indexOf("{/defer}", openAt + openLen);
|
|
1917
|
+
if (closeAt < 0) break;
|
|
1918
|
+
out2 += template.slice(dpos, openAt) + template.slice(openAt + openLen, closeAt);
|
|
1919
|
+
dpos = closeAt + 8;
|
|
1920
|
+
}
|
|
1921
|
+
return { template: dpos === 0 ? template : out2, count: 0, holds: [] };
|
|
1922
|
+
}
|
|
1923
|
+
let count = 0;
|
|
1924
|
+
const holds = [];
|
|
1925
|
+
let out = "";
|
|
1926
|
+
let pos = 0;
|
|
1927
|
+
const openRe = /\{#defer(?:\s+hold=(\d+))?\}/g;
|
|
1928
|
+
for (; ; ) {
|
|
1929
|
+
openRe.lastIndex = pos;
|
|
1930
|
+
const openM = openRe.exec(template);
|
|
1931
|
+
if (!openM) break;
|
|
1932
|
+
const openAt = openM.index;
|
|
1933
|
+
const openLen = openM[0].length;
|
|
1934
|
+
const hold = openM[1] ? Number(openM[1]) : 0;
|
|
1935
|
+
let depth = 1;
|
|
1936
|
+
let i = openAt + openLen;
|
|
1937
|
+
let closeAt = -1;
|
|
1938
|
+
while (i < template.length) {
|
|
1939
|
+
openRe.lastIndex = i;
|
|
1940
|
+
const nextOpenM = openRe.exec(template);
|
|
1941
|
+
const nextOpen = nextOpenM ? nextOpenM.index : -1;
|
|
1942
|
+
const nextClose = template.indexOf("{/defer}", i);
|
|
1943
|
+
if (nextClose < 0) break;
|
|
1944
|
+
if (nextOpen >= 0 && nextOpen < nextClose) {
|
|
1945
|
+
depth++;
|
|
1946
|
+
i = nextOpen + nextOpenM[0].length;
|
|
1947
|
+
continue;
|
|
1948
|
+
}
|
|
1949
|
+
depth--;
|
|
1950
|
+
if (depth === 0) {
|
|
1951
|
+
closeAt = nextClose;
|
|
1952
|
+
break;
|
|
1953
|
+
}
|
|
1954
|
+
i = nextClose + 8;
|
|
1955
|
+
}
|
|
1956
|
+
if (closeAt < 0) break;
|
|
1957
|
+
const content = template.slice(openAt + openLen, closeAt);
|
|
1958
|
+
holds.push(hold);
|
|
1959
|
+
const n = ++count;
|
|
1960
|
+
out += template.slice(pos, openAt);
|
|
1961
|
+
out += "{#if __rvDefer" + n + "()}" + content + "{/if}\n{#if !__rvDefer" + n + '()}<div class="rv-defer-loading"></div>{/if}';
|
|
1962
|
+
pos = closeAt + 8;
|
|
963
1963
|
}
|
|
964
|
-
return
|
|
1964
|
+
if (count === 0) return { template, count: 0, holds: [] };
|
|
1965
|
+
out += template.slice(pos);
|
|
1966
|
+
return { template: out, count, holds };
|
|
965
1967
|
}
|
|
966
|
-
function
|
|
967
|
-
|
|
968
|
-
|
|
1968
|
+
function deferBootCode(count, holds = []) {
|
|
1969
|
+
let code = "";
|
|
1970
|
+
for (let n = 1; n <= count; n++) {
|
|
1971
|
+
code += "const [__rvDefer" + n + ", set__rvDefer" + n + '] = state("__rvdefer' + n + '", false);\n';
|
|
1972
|
+
const hold = holds[n - 1] || 0;
|
|
1973
|
+
code += hold > 0 ? "onMount(function () { setTimeout(function () { set__rvDefer" + n + "(true); }, " + hold + "); });\n" : "onMount(function () { requestAnimationFrame(function () { requestAnimationFrame(function () { set__rvDefer" + n + "(true); }); }); });\n";
|
|
1974
|
+
}
|
|
1975
|
+
return code;
|
|
969
1976
|
}
|
|
970
1977
|
function findBlock(src, kind) {
|
|
971
|
-
const head = kind === "boundary" ? /\{#boundary
|
|
1978
|
+
const head = kind === "boundary" ? /\{#boundary(?:\s+([^}]*))?\}/g : kind === "if" ? /\{#if\s+([^}]+)\}/g : kind === "island" ? /\{#island(?:\s+name="([^"]*)")?(?:\s+hydrate="([^"]*)")?\s*\}/g : /\{#each\s+([^}]+?)\s+as\s+(\{[^{}]*\}|\[[^[\]]*\]|\w+)(?:\s*,\s*(\w+))?\}/g;
|
|
972
1979
|
const closeRe = new RegExp(`\\{/${kind}\\}`, "g");
|
|
973
1980
|
let open;
|
|
974
1981
|
while (open = head.exec(src)) {
|
|
@@ -990,7 +1997,7 @@ function findBlock(src, kind) {
|
|
|
990
1997
|
i = nextClose.index + nextClose[0].length;
|
|
991
1998
|
if (--depth === 0) {
|
|
992
1999
|
const content = src.slice(afterOpen, nextClose.index);
|
|
993
|
-
const groups = kind === "boundary" ? [content] : kind === "if" ? [open[1], content] : [open[1], open[2], content];
|
|
2000
|
+
const groups = kind === "boundary" ? [open[1] ?? "", content] : kind === "island" ? [open[1] ?? "", open[2] ?? "", content] : kind === "if" ? [open[1], content] : [open[1], open[2], open[3] ?? "", content];
|
|
994
2001
|
const arr = [src.slice(start, i), ...groups];
|
|
995
2002
|
arr.index = start;
|
|
996
2003
|
return arr;
|
|
@@ -1033,10 +2040,121 @@ function compileHead(head) {
|
|
|
1033
2040
|
flush();
|
|
1034
2041
|
return out;
|
|
1035
2042
|
}
|
|
1036
|
-
|
|
2043
|
+
var KNOWN_CLOSERS = /* @__PURE__ */ new Set(["if", "each", "boundary", "island"]);
|
|
2044
|
+
function assertKnownDirectives(template, filePath) {
|
|
2045
|
+
const rawRanges = [];
|
|
2046
|
+
const RAW_OPEN = /<(style|script|noscript)\b[^>]*>/gi;
|
|
2047
|
+
let raw;
|
|
2048
|
+
while (raw = RAW_OPEN.exec(template)) {
|
|
2049
|
+
const tag = raw[1].toLowerCase();
|
|
2050
|
+
const closeAt = template.toLowerCase().indexOf(`</${tag}`, raw.index + raw[0].length);
|
|
2051
|
+
const gt = closeAt < 0 ? -1 : template.indexOf(">", closeAt);
|
|
2052
|
+
const end = gt < 0 ? template.length : gt + 1;
|
|
2053
|
+
rawRanges.push([raw.index, end]);
|
|
2054
|
+
RAW_OPEN.lastIndex = end;
|
|
2055
|
+
}
|
|
2056
|
+
const COMMENT_RE = /<!--[\s\S]*?-->/g;
|
|
2057
|
+
let note;
|
|
2058
|
+
while (note = COMMENT_RE.exec(template)) rawRanges.push([note.index, note.index + note[0].length]);
|
|
2059
|
+
rawRanges.sort((a, b) => a[0] - b[0]);
|
|
2060
|
+
const inRaw = (idx) => rawRanges.some(([s, e]) => idx >= s && idx < e);
|
|
2061
|
+
const DIRECTIVE_RE = /\{([:/])(\w+)\}/g;
|
|
2062
|
+
let m;
|
|
2063
|
+
while (m = DIRECTIVE_RE.exec(template)) {
|
|
2064
|
+
if (inRaw(m.index)) continue;
|
|
2065
|
+
const [, sigil, word] = m;
|
|
2066
|
+
if (sigil === "/" && KNOWN_CLOSERS.has(word)) continue;
|
|
2067
|
+
if (sigil === "/") {
|
|
2068
|
+
throw new RoseError(
|
|
2069
|
+
"E-TEMPLATE",
|
|
2070
|
+
`${filePath}: {/${word}} does not close anything`,
|
|
2071
|
+
{ file: filePath, line: lineAt(template, m), hint: "the closers are {/if}, {/each} and {/boundary} - one per block you opened" }
|
|
2072
|
+
);
|
|
2073
|
+
}
|
|
2074
|
+
if (word === "else") {
|
|
2075
|
+
throw new RoseError(
|
|
2076
|
+
"E-TEMPLATE",
|
|
2077
|
+
`${filePath}: a stray {:else} with no {#if} above it`,
|
|
2078
|
+
{ file: filePath, line: lineAt(template, m), hint: "{:else} / {:else if cond} belong inside an {#if} ... {/if} block - {#if cond}A{:else}B{/if}" }
|
|
2079
|
+
);
|
|
2080
|
+
}
|
|
2081
|
+
if (word === "fallback") {
|
|
2082
|
+
throw new RoseError(
|
|
2083
|
+
"E-TEMPLATE",
|
|
2084
|
+
`${filePath}: a stray {:fallback} with no {#boundary} above it`,
|
|
2085
|
+
{ file: filePath, line: lineAt(template, m), hint: "{:fallback} belongs directly inside a {#boundary} ... {/boundary} block" }
|
|
2086
|
+
);
|
|
2087
|
+
}
|
|
2088
|
+
throw new RoseError(
|
|
2089
|
+
"E-TEMPLATE",
|
|
2090
|
+
`${filePath}: {:${word}} is not a rosetack directive`,
|
|
2091
|
+
{ file: filePath, line: lineAt(template, m), hint: "rosetack templates support {#if}/{:else}, {#each} and {#boundary}" }
|
|
2092
|
+
);
|
|
2093
|
+
}
|
|
2094
|
+
const OPENER_RE = /\{#(if|each|boundary|island)\b([^}]*)\}/g;
|
|
2095
|
+
while (m = OPENER_RE.exec(template)) {
|
|
2096
|
+
if (inRaw(m.index)) continue;
|
|
2097
|
+
const [, kind, head] = m;
|
|
2098
|
+
if (kind === "each" && !/\bas\s+(\{[^{}]*\}?|\[[^[\]]*\]?|\w+)(?:\s*,\s*\w+)?\s*$/.test(head)) {
|
|
2099
|
+
throw new RoseError(
|
|
2100
|
+
"E-TEMPLATE",
|
|
2101
|
+
`${filePath}: {#each ${head.trim()}} is missing its item name`,
|
|
2102
|
+
{ file: filePath, line: lineAt(template, m), hint: "write {#each items() as item} - the name after `as` is what the block body reads (item.id, item.name)" }
|
|
2103
|
+
);
|
|
2104
|
+
}
|
|
2105
|
+
const OPEN_RE = new RegExp(`\\{#${kind}\\b[^}]*\\}`, "g");
|
|
2106
|
+
const CLOSE_RE = new RegExp(`\\{/${kind}\\}`, "g");
|
|
2107
|
+
let depth = 1;
|
|
2108
|
+
let i = m.index + m[0].length;
|
|
2109
|
+
for (; ; ) {
|
|
2110
|
+
OPEN_RE.lastIndex = i;
|
|
2111
|
+
CLOSE_RE.lastIndex = i;
|
|
2112
|
+
const nextOpen = OPEN_RE.exec(template);
|
|
2113
|
+
const nextClose = CLOSE_RE.exec(template);
|
|
2114
|
+
if (!nextClose) break;
|
|
2115
|
+
if (nextOpen && nextOpen.index < nextClose.index) {
|
|
2116
|
+
i = nextOpen.index + nextOpen[0].length;
|
|
2117
|
+
continue;
|
|
2118
|
+
}
|
|
2119
|
+
i = nextClose.index + nextClose[0].length;
|
|
2120
|
+
if (--depth === 0) break;
|
|
2121
|
+
}
|
|
2122
|
+
if (depth !== 0) {
|
|
2123
|
+
throw new RoseError(
|
|
2124
|
+
"E-TEMPLATE",
|
|
2125
|
+
`${filePath}: unclosed {#${kind}} - every block needs its {/${kind}}`,
|
|
2126
|
+
{ file: filePath, line: lineAt(template, m), hint: `add the matching {/${kind}} (an inner {#if} or {#each} closes first, deepest first)` }
|
|
2127
|
+
);
|
|
2128
|
+
}
|
|
2129
|
+
}
|
|
2130
|
+
}
|
|
2131
|
+
function rewriteQuotedExprAttrs(template, comps) {
|
|
2132
|
+
const TAG_RE = /<([a-zA-Z][\w-]*)((?:\s+[\w:-]+(?:=(?:"[^"]*"|'[^']*'|[^\s"'>]+))?)*)\s*(\/?)>/g;
|
|
2133
|
+
return template.replace(TAG_RE, (tag, name, attrs, selfClose) => {
|
|
2134
|
+
if (comps.has(name) || !/\{/.test(attrs)) return tag;
|
|
2135
|
+
const rewritten = attrs.replace(/([\w:-]+)="([^"]*)"/g, (whole, attr, value) => {
|
|
2136
|
+
if (!/\{/.test(value) || value.includes("`")) return whole;
|
|
2137
|
+
const spans = templateExprSpans(value);
|
|
2138
|
+
if (spans.length === 0) return whole;
|
|
2139
|
+
let expr = "";
|
|
2140
|
+
let last = 0;
|
|
2141
|
+
for (const s of spans) {
|
|
2142
|
+
if (last < s.start) expr += (expr ? " + " : "") + JSON.stringify(value.slice(last, s.start));
|
|
2143
|
+
expr += (expr ? " + " : "") + `(${s.expr})`;
|
|
2144
|
+
last = s.end + 1;
|
|
2145
|
+
}
|
|
2146
|
+
if (last < value.length) expr += (expr ? " + " : "") + JSON.stringify(value.slice(last));
|
|
2147
|
+
return `${attr}={${expr}}`;
|
|
2148
|
+
});
|
|
2149
|
+
return `<${name}${rewritten}${selfClose ? " /" : ""}>`;
|
|
2150
|
+
});
|
|
2151
|
+
}
|
|
2152
|
+
function compileTemplate(template, acc, closes, scope, depth, markers = true, comps = /* @__PURE__ */ new Map(), islandDepth = 0) {
|
|
1037
2153
|
let result = "";
|
|
1038
2154
|
let remaining = template;
|
|
1039
2155
|
let blockId = 0;
|
|
2156
|
+
const islandsMode = /\{#island\b/.test(template);
|
|
2157
|
+
const effMarkers = markers && (!islandsMode || islandDepth > 0);
|
|
1040
2158
|
const nextId = () => `${depth}_${blockId++}`;
|
|
1041
2159
|
while (remaining.length > 0) {
|
|
1042
2160
|
const ifMatch = findBlock(remaining, "if");
|
|
@@ -1045,13 +2163,34 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
|
|
|
1045
2163
|
const firstExpr = templateExprSpans(remaining)[0];
|
|
1046
2164
|
const exprMatch = firstExpr ? Object.assign([remaining.slice(firstExpr.start, firstExpr.end + 1), firstExpr.expr], { index: firstExpr.start }) : null;
|
|
1047
2165
|
const compTag = comps.size > 0 ? findCompTag(remaining, comps) : null;
|
|
2166
|
+
const islandMatch = findBlock(remaining, "island");
|
|
1048
2167
|
const candidates = [];
|
|
1049
2168
|
if (ifMatch?.index !== void 0) candidates.push({ type: "if", match: ifMatch, index: ifMatch.index });
|
|
1050
2169
|
if (eachMatch?.index !== void 0) candidates.push({ type: "each", match: eachMatch, index: eachMatch.index });
|
|
1051
2170
|
if (boundaryMatch?.index !== void 0) candidates.push({ type: "boundary", match: boundaryMatch, index: boundaryMatch.index });
|
|
2171
|
+
if (islandMatch?.index !== void 0) candidates.push({ type: "island", match: islandMatch, index: islandMatch.index });
|
|
1052
2172
|
if (exprMatch?.index !== void 0) candidates.push({ type: "expr", match: exprMatch, index: exprMatch.index });
|
|
1053
2173
|
if (compTag) candidates.push({ type: "comp", match: exprMatch, index: compTag.start, tag: compTag });
|
|
1054
2174
|
const earliest = candidates.length > 0 ? candidates.reduce((a, b) => a.index <= b.index ? a : b) : null;
|
|
2175
|
+
const rawOpenRe = /<(style|script|noscript)\b[^>]*>/g;
|
|
2176
|
+
const rawHit = rawOpenRe.exec(remaining);
|
|
2177
|
+
if (rawHit && earliest && rawHit.index < earliest.index) {
|
|
2178
|
+
const tag = rawHit[1].toLowerCase();
|
|
2179
|
+
const closeAt = remaining.toLowerCase().indexOf(`</${tag}`, rawHit.index + rawHit[0].length);
|
|
2180
|
+
const gt = closeAt < 0 ? -1 : remaining.indexOf(">", closeAt);
|
|
2181
|
+
const end = gt < 0 ? remaining.length : gt + 1;
|
|
2182
|
+
result += emitChunk(remaining.slice(0, end), acc, closes, scope);
|
|
2183
|
+
remaining = remaining.substring(end);
|
|
2184
|
+
continue;
|
|
2185
|
+
}
|
|
2186
|
+
const noteAt = remaining.indexOf("<!--");
|
|
2187
|
+
if (noteAt >= 0 && (!earliest || noteAt < earliest.index)) {
|
|
2188
|
+
const noteEnd = remaining.indexOf("-->", noteAt + 4);
|
|
2189
|
+
const end = noteEnd < 0 ? remaining.length : noteEnd + 3;
|
|
2190
|
+
result += emitChunk(remaining.slice(0, end), acc, closes, scope);
|
|
2191
|
+
remaining = remaining.substring(end);
|
|
2192
|
+
continue;
|
|
2193
|
+
}
|
|
1055
2194
|
if (!earliest) {
|
|
1056
2195
|
result += emitChunk(remaining, acc, closes, scope);
|
|
1057
2196
|
break;
|
|
@@ -1063,10 +2202,10 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
|
|
|
1063
2202
|
const call = autoCall(cond);
|
|
1064
2203
|
const id = nextId();
|
|
1065
2204
|
const innerScope = scope ?? "__s";
|
|
1066
|
-
const inner = compileTemplate(content.trim(), "h", "__c", innerScope, depth + 1,
|
|
2205
|
+
const inner = compileTemplate(content.trim(), "h", "__c", innerScope, depth + 1, effMarkers, comps, islandDepth);
|
|
1067
2206
|
result += `const __b${id} = (__s, __c) => { let h = ''; ${inner} return h; };
|
|
1068
2207
|
`;
|
|
1069
|
-
if (
|
|
2208
|
+
if (effMarkers) {
|
|
1070
2209
|
result += `${acc} += ifMark(${closes}, () => (${call}), __b${id}${scope ? `, ${scope}` : ""});
|
|
1071
2210
|
`;
|
|
1072
2211
|
} else {
|
|
@@ -1075,43 +2214,62 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
|
|
|
1075
2214
|
}
|
|
1076
2215
|
remaining = remaining.substring(earliest.index + earliest.match[0].length);
|
|
1077
2216
|
} else if (earliest.type === "each") {
|
|
1078
|
-
const [, items, item, content] = earliest.match;
|
|
2217
|
+
const [, items, item, index, content] = earliest.match;
|
|
1079
2218
|
const before = remaining.substring(0, earliest.index);
|
|
1080
2219
|
if (before) result += emitChunk(before, acc, closes, scope);
|
|
1081
2220
|
const call = autoCall(items);
|
|
1082
2221
|
const id = nextId();
|
|
1083
|
-
const
|
|
2222
|
+
const isDestructure = /^[{[]/.test(item);
|
|
2223
|
+
const itemRe = isDestructure ? null : new RegExp(`\\b${item}\\b`, "g");
|
|
2224
|
+
const indexRe = index ? new RegExp(`\\b${index}\\b`, "g") : null;
|
|
1084
2225
|
let scoped = "";
|
|
1085
2226
|
let lastSpan = 0;
|
|
1086
2227
|
for (const s of templateExprSpans(content.trim())) {
|
|
1087
|
-
|
|
2228
|
+
let expr = itemRe ? s.expr.replace(itemRe, "__s") : s.expr;
|
|
2229
|
+
if (indexRe) expr = expr.replace(indexRe, "__i");
|
|
2230
|
+
scoped += content.trim().slice(lastSpan, s.start) + "{" + expr + "}";
|
|
1088
2231
|
lastSpan = s.end + 1;
|
|
1089
2232
|
}
|
|
1090
2233
|
scoped += content.trim().slice(lastSpan);
|
|
1091
|
-
const inner = compileTemplate(scoped, "h", "__c", "__s", depth + 1,
|
|
1092
|
-
|
|
2234
|
+
const inner = compileTemplate(scoped, "h", "__c", "__s", depth + 1, effMarkers, comps, islandDepth);
|
|
2235
|
+
const body = isDestructure ? `const ${item} = __s; ${inner}` : inner;
|
|
2236
|
+
result += `const __b${id} = (__s, __c${index ? ", __i" : ""}) => { let h = ''; ${body} return h; };
|
|
1093
2237
|
`;
|
|
1094
|
-
if (
|
|
2238
|
+
if (effMarkers) {
|
|
1095
2239
|
result += `${acc} += eachMark(${closes}, () => (${call}), __b${id});
|
|
1096
2240
|
`;
|
|
1097
2241
|
} else {
|
|
1098
|
-
|
|
2242
|
+
const param = isDestructure ? "__s" : item;
|
|
2243
|
+
result += `${acc} += (${call}).map((${param}${index ? ", __i" : ""}) => __b${id}(${param}, []${index ? ", __i" : ""}))).join('');
|
|
1099
2244
|
`;
|
|
1100
2245
|
}
|
|
1101
2246
|
remaining = remaining.substring(earliest.index + earliest.match[0].length);
|
|
1102
2247
|
} else if (earliest.type === "boundary") {
|
|
1103
|
-
const [, content] = earliest.match;
|
|
2248
|
+
const [, fbAttr, content] = earliest.match;
|
|
2249
|
+
let fallbackSrc = "";
|
|
2250
|
+
if (fbAttr) {
|
|
2251
|
+
const fbM = /__fb="([A-Za-z0-9+/=]*)"/.exec(fbAttr);
|
|
2252
|
+
if (fbM) fallbackSrc = Buffer.from(fbM[1], "base64").toString("utf-8");
|
|
2253
|
+
}
|
|
2254
|
+
const custom = content;
|
|
1104
2255
|
const before = remaining.substring(0, earliest.index);
|
|
1105
2256
|
if (before) result += emitChunk(before, acc, closes, scope);
|
|
1106
2257
|
const id = nextId();
|
|
1107
|
-
const catchesAction = /\$action:|<form[\s>]/.test(
|
|
1108
|
-
const inner = compileTemplate(
|
|
2258
|
+
const catchesAction = /\$action:|<form[\s>]/.test(custom);
|
|
2259
|
+
const inner = compileTemplate(custom.trim(), "h", closes, scope, depth + 1, effMarkers, comps, islandDepth);
|
|
1109
2260
|
result += `const __b${id} = (__c) => { let h = ''; ${inner} return h; };
|
|
1110
2261
|
`;
|
|
2262
|
+
let fbBlock = "";
|
|
2263
|
+
if (fallbackSrc.trim()) {
|
|
2264
|
+
const fbInner = compileTemplate(fallbackSrc.trim(), "h", closes, scope, depth + 1, effMarkers, comps, islandDepth);
|
|
2265
|
+
fbBlock = `const __bf${id} = (__c) => { let h = ''; ${fbInner} return h; };
|
|
2266
|
+
`;
|
|
2267
|
+
}
|
|
2268
|
+
result += fbBlock;
|
|
1111
2269
|
result += `let __bd${id} = '';
|
|
1112
2270
|
`;
|
|
1113
|
-
result += catchesAction ? `try { $actionErrorOrThrow(); __bd${id} = __b${id}(${closes}); } catch (e) { __bd${id} = $boundaryFallback(e); }
|
|
1114
|
-
` : `try { __bd${id} = __b${id}(${closes}); } catch { __bd${id} = ${JSON.stringify(BOUNDARY_FALLBACK)}; }
|
|
2271
|
+
result += catchesAction ? `try { $actionErrorOrThrow(); __bd${id} = __b${id}(${closes}); } catch (e) { $setBoundaryError(e); __bd${id} = ${fbBlock ? `__bf${id}(${closes})` : "$boundaryFallback(e)"}; }
|
|
2272
|
+
` : `try { __bd${id} = __b${id}(${closes}); } catch (e) { $setBoundaryError(e); __bd${id} = ${fbBlock ? `__bf${id}(${closes})` : JSON.stringify(BOUNDARY_FALLBACK)}; }
|
|
1115
2273
|
`;
|
|
1116
2274
|
result += `${acc} += __bd${id};
|
|
1117
2275
|
`;
|
|
@@ -1134,7 +2292,7 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
|
|
|
1134
2292
|
const { def, named } = splitSlots(childrenSrc);
|
|
1135
2293
|
const hasChildren = def.trim().length > 0;
|
|
1136
2294
|
if (hasChildren) {
|
|
1137
|
-
result += `const __ch${id} = (__s, __c) => { let h = ''; ${compileTemplate(def, "h", "__c", scope, depth + 1,
|
|
2295
|
+
result += `const __ch${id} = (__s, __c) => { let h = ''; ${compileTemplate(def, "h", "__c", scope, depth + 1, effMarkers, comps, islandDepth)} return h; };
|
|
1138
2296
|
`;
|
|
1139
2297
|
}
|
|
1140
2298
|
const slotFns = named.map(([nm, src]) => {
|
|
@@ -1150,9 +2308,10 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
|
|
|
1150
2308
|
}
|
|
1151
2309
|
content = out + content.slice(lastSpan);
|
|
1152
2310
|
}
|
|
1153
|
-
return `${JSON.stringify(nm)}: (__s, __c) => { let h = ''; ${compileTemplate(content, "h", "__c", "__s", depth + 1,
|
|
2311
|
+
return `${JSON.stringify(nm)}: (__s, __c) => { let h = ''; ${compileTemplate(content, "h", "__c", "__s", depth + 1, effMarkers, comps, islandDepth)} return h; }`;
|
|
1154
2312
|
});
|
|
1155
2313
|
const propsObj = parseCompAttrs(tag.attrs).filter((a) => a.name !== "slot").map((a) => {
|
|
2314
|
+
if (a.kind === "spread") return `...(${a.value})`;
|
|
1156
2315
|
const key = a.name.startsWith("on:") ? `on${capitalize(a.name.slice(3))}` : a.name;
|
|
1157
2316
|
const val = a.kind === "expr" ? `(${a.value})` : a.kind === "str" ? JSON.stringify(a.value) : "true";
|
|
1158
2317
|
return `${JSON.stringify(key)}: ${val}`;
|
|
@@ -1161,20 +2320,49 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
|
|
|
1161
2320
|
result += `${acc} += ${tag.name}(${closes}, ${childrenArg}, { ${propsObj} }, { ${slotFns.join(", ")} });
|
|
1162
2321
|
`;
|
|
1163
2322
|
remaining = rest;
|
|
2323
|
+
} else if (earliest.type === "island") {
|
|
2324
|
+
const [, name, hydrate, content] = earliest.match;
|
|
2325
|
+
const before = remaining.substring(0, earliest.index);
|
|
2326
|
+
if (before) result += emitChunk(before, acc, closes, scope);
|
|
2327
|
+
const hydrateAttr = hydrate === "visible" || hydrate === "idle" ? ` data-rv-island-hydrate="${hydrate}"` : "";
|
|
2328
|
+
result += `${acc} += ${JSON.stringify(`<div data-rv-island="${name || ""}"${hydrateAttr}>`)};
|
|
2329
|
+
`;
|
|
2330
|
+
const inner = compileTemplate(content.trim(), "h", "__c", scope, depth + 1, markers, comps, islandDepth + 1);
|
|
2331
|
+
result += inner;
|
|
2332
|
+
result += `${acc} += '</div>';
|
|
2333
|
+
`;
|
|
2334
|
+
remaining = remaining.substring(earliest.index + earliest.match[0].length);
|
|
1164
2335
|
} else {
|
|
1165
2336
|
const [, expr] = earliest.match;
|
|
1166
2337
|
const trimmed = expr.trim();
|
|
1167
2338
|
const before = remaining.substring(0, earliest.index);
|
|
2339
|
+
const constMatch = /^@const\s+([A-Za-z_$][\w$]*)\s*=\s*([\s\S]+)$/.exec(trimmed);
|
|
2340
|
+
if (constMatch) {
|
|
2341
|
+
if (before) result += emitChunk(before, acc, closes, scope);
|
|
2342
|
+
result += `const ${constMatch[1]} = (${constMatch[2].trim()});
|
|
2343
|
+
`;
|
|
2344
|
+
remaining = remaining.substring(earliest.index + earliest.match[0].length);
|
|
2345
|
+
continue;
|
|
2346
|
+
}
|
|
1168
2347
|
if (trimmed === "__slot__") {
|
|
1169
2348
|
if (before) result += emitChunk(before, acc, closes, scope);
|
|
1170
2349
|
result += compileSlot(acc);
|
|
1171
2350
|
remaining = remaining.substring(earliest.index + earliest.match[0].length);
|
|
1172
2351
|
continue;
|
|
1173
2352
|
}
|
|
1174
|
-
const
|
|
2353
|
+
const slotDefault = /^__slotDefault\(("(?:[^"\\]|\\.)*")\)$/.exec(trimmed);
|
|
2354
|
+
if (slotDefault) {
|
|
2355
|
+
if (before) result += emitChunk(before, acc, closes, scope);
|
|
2356
|
+
result += `${acc} += __slotDefault(children, ${slotDefault[1]});
|
|
2357
|
+
`;
|
|
2358
|
+
remaining = remaining.substring(earliest.index + earliest.match[0].length);
|
|
2359
|
+
continue;
|
|
2360
|
+
}
|
|
2361
|
+
const slotCall = /^__slot\((['"])(\w+)\1, \[([\s\S]*?)\](?:,\s*("(?:[^"\\]|\\.)*"))?\)$/.exec(trimmed);
|
|
1175
2362
|
if (slotCall) {
|
|
1176
2363
|
if (before) result += emitChunk(before, acc, closes, scope);
|
|
1177
|
-
|
|
2364
|
+
const fb = slotCall[4] ? `, ${slotCall[4]}` : "";
|
|
2365
|
+
result += `${acc} += __slotBlock(${closes}, __sl, ${JSON.stringify(slotCall[2])}, [${slotCall[3]}]${fb});
|
|
1178
2366
|
`;
|
|
1179
2367
|
remaining = remaining.substring(earliest.index + earliest.match[0].length);
|
|
1180
2368
|
continue;
|
|
@@ -1183,7 +2371,7 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
|
|
|
1183
2371
|
if (rawMatch) {
|
|
1184
2372
|
if (before) result += emitChunk(before, acc, closes, scope);
|
|
1185
2373
|
const expr2 = rawMatch[1].trim();
|
|
1186
|
-
if (!
|
|
2374
|
+
if (!effMarkers) {
|
|
1187
2375
|
result += `${acc} += String(${expr2} ?? '');
|
|
1188
2376
|
`;
|
|
1189
2377
|
} else {
|
|
@@ -1198,12 +2386,12 @@ function compileTemplate(template, acc, closes, scope, depth, markers = true, co
|
|
|
1198
2386
|
if (attrMatch) {
|
|
1199
2387
|
const lit = before.slice(0, before.length - attrMatch[0].length);
|
|
1200
2388
|
if (lit) result += emitChunk(lit, acc, closes, scope);
|
|
1201
|
-
result += emitAttr(attrMatch[1], trimmed, acc, closes, scope,
|
|
2389
|
+
result += emitAttr(attrMatch[1], trimmed, acc, closes, scope, effMarkers);
|
|
1202
2390
|
} else {
|
|
1203
2391
|
if (before) result += emitChunk(before, acc, closes, scope);
|
|
1204
2392
|
const after = remaining.substring(earliest.index + earliest.match[0].length);
|
|
1205
2393
|
const pair = after.length > 0 && !/^<[a-zA-Z/!]/.test(after) && !after.startsWith("{");
|
|
1206
|
-
result += emitText(trimmed, acc, closes, scope,
|
|
2394
|
+
result += emitText(trimmed, acc, closes, scope, effMarkers, pair);
|
|
1207
2395
|
}
|
|
1208
2396
|
remaining = remaining.substring(earliest.index + earliest.match[0].length);
|
|
1209
2397
|
}
|
|
@@ -1263,6 +2451,12 @@ function parseCompAttrs(attrs) {
|
|
|
1263
2451
|
const out = [];
|
|
1264
2452
|
let i = 0;
|
|
1265
2453
|
while (i < attrs.length) {
|
|
2454
|
+
const spread = /^\s*\{\.\.\.([^}]*)\}/.exec(attrs.slice(i));
|
|
2455
|
+
if (spread) {
|
|
2456
|
+
out.push({ name: "...", kind: "spread", value: spread[1].trim() });
|
|
2457
|
+
i += spread[0].length;
|
|
2458
|
+
continue;
|
|
2459
|
+
}
|
|
1266
2460
|
const nm = /^\s*([\w:.-]+)/.exec(attrs.slice(i));
|
|
1267
2461
|
if (!nm) break;
|
|
1268
2462
|
i += nm[0].length;
|
|
@@ -1400,22 +2594,55 @@ var IMG_MIME = {
|
|
|
1400
2594
|
".ico": "image/x-icon"
|
|
1401
2595
|
};
|
|
1402
2596
|
var INLINE_IMG_MAX = 4096;
|
|
2597
|
+
function listImageVariants(publicDir, url) {
|
|
2598
|
+
const ext = path2.extname(url);
|
|
2599
|
+
const base = path2.basename(url, ext);
|
|
2600
|
+
const dirUrl = url.slice(0, url.length - (base + ext).length);
|
|
2601
|
+
let entries;
|
|
2602
|
+
try {
|
|
2603
|
+
entries = fs3.readdirSync(path2.join(publicDir, path2.dirname(url)));
|
|
2604
|
+
} catch {
|
|
2605
|
+
return [];
|
|
2606
|
+
}
|
|
2607
|
+
const re = new RegExp(
|
|
2608
|
+
"^" + base.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") + "\\.w(\\d+)" + ext.replace(".", "\\.") + "$",
|
|
2609
|
+
"i"
|
|
2610
|
+
);
|
|
2611
|
+
const out = [];
|
|
2612
|
+
for (const e of entries) {
|
|
2613
|
+
const m = re.exec(e);
|
|
2614
|
+
const width = m ? Number(m[1]) : 0;
|
|
2615
|
+
if (width > 0) out.push({ url: `${dirUrl}${base}.w${width}${ext}`, width });
|
|
2616
|
+
}
|
|
2617
|
+
return out.sort((a, b) => a.width - b.width);
|
|
2618
|
+
}
|
|
1403
2619
|
function inlineImages(template, publicDir) {
|
|
1404
2620
|
return template.replace(IMG_RE, (tag) => {
|
|
1405
2621
|
const src = tag.match(/\bsrc="(\/[^"{}]+)"/);
|
|
1406
2622
|
if (!src) return tag;
|
|
1407
|
-
const ext =
|
|
2623
|
+
const ext = path2.extname(src[1]).toLowerCase();
|
|
1408
2624
|
const mime = IMG_MIME[ext];
|
|
1409
2625
|
if (!mime) return tag;
|
|
2626
|
+
const rel = src[1].replace(/^\/public(?=\/)/, "");
|
|
2627
|
+
const filePath = path2.join(publicDir, rel);
|
|
1410
2628
|
let file;
|
|
1411
2629
|
try {
|
|
1412
|
-
file =
|
|
2630
|
+
file = fs3.readFileSync(filePath);
|
|
1413
2631
|
} catch {
|
|
1414
2632
|
return tag;
|
|
1415
2633
|
}
|
|
1416
|
-
|
|
2634
|
+
const authorDims = /\swidth=/.test(tag) || /\sheight=/.test(tag);
|
|
2635
|
+
const dims = authorDims ? null : readImageSize(filePath);
|
|
2636
|
+
const withDims = (t) => dims ? t.replace(/<img\b/, `<img width="${dims.width}" height="${dims.height}"`) : t;
|
|
2637
|
+
if (file.length > INLINE_IMG_MAX) {
|
|
2638
|
+
const hasSS = /\ssrcset=/.test(tag) || /\ssizes=/.test(tag);
|
|
2639
|
+
const variants = hasSS ? [] : listImageVariants(publicDir, rel);
|
|
2640
|
+
if (!variants.length) return withDims(tag);
|
|
2641
|
+
const srcset = variants.map((v) => `${v.url} ${v.width}w`).join(", ");
|
|
2642
|
+
return withDims(tag.replace(/<img\b/, `<img srcset="${srcset}"`));
|
|
2643
|
+
}
|
|
1417
2644
|
const uri = ext === ".svg" ? `data:image/svg+xml,${file.toString("utf-8").replace(/%/g, "%25").replace(/#/g, "%23").replace(/\{/g, "%7B").replace(/\}/g, "%7D").replace(/"/g, "%22")}` : `data:${mime};base64,${file.toString("base64")}`;
|
|
1418
|
-
return tag.replace(src[0], `src="${uri}"`);
|
|
2645
|
+
return withDims(tag.replace(src[0], `src="${uri}"`));
|
|
1419
2646
|
});
|
|
1420
2647
|
}
|
|
1421
2648
|
function emitText(expr, acc, closes, scope, markers = true, pair = false) {
|
|
@@ -1429,6 +2656,7 @@ function emitText(expr, acc, closes, scope, markers = true, pair = false) {
|
|
|
1429
2656
|
return `${acc} += textMark(${closes}, ${fn}${extra});
|
|
1430
2657
|
`;
|
|
1431
2658
|
}
|
|
2659
|
+
var BOOLEAN_ATTRS = /* @__PURE__ */ new Set(["checked", "disabled", "readonly", "required", "selected", "multiple", "autofocus", "open"]);
|
|
1432
2660
|
function emitAttr(attr, expr, acc, closes, scope, markers = true) {
|
|
1433
2661
|
if (!markers) {
|
|
1434
2662
|
return `${acc} += '${attr}="' + esc(${expr}) + '"';
|
|
@@ -1436,6 +2664,10 @@ function emitAttr(attr, expr, acc, closes, scope, markers = true) {
|
|
|
1436
2664
|
}
|
|
1437
2665
|
const fn = scope ? `(${scope}) => (${expr})` : `() => (${expr})`;
|
|
1438
2666
|
const arg = scope ? `, ${scope}` : "";
|
|
2667
|
+
if (BOOLEAN_ATTRS.has(attr)) {
|
|
2668
|
+
return `${acc} += boolAttrMark(${closes}, ${fn}, '${attr}'${arg});
|
|
2669
|
+
`;
|
|
2670
|
+
}
|
|
1439
2671
|
return `${acc} += attrMark(${closes}, ${fn}, '${attr}'${arg});
|
|
1440
2672
|
`;
|
|
1441
2673
|
}
|
|
@@ -1443,7 +2675,8 @@ function compileSlot(acc) {
|
|
|
1443
2675
|
return `${acc} += String(children);
|
|
1444
2676
|
`;
|
|
1445
2677
|
}
|
|
1446
|
-
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 } from './runtime.js';`;
|
|
2678
|
+
var RUNTIME_IMPORTS = `import { state, setState, persistState, $data, hasState, esc, refresh, onMount, onCleanup, getContext, $query, $t, bestLocale, localeDir, ensureLocale, loadLocale, handlers, directives, $cookies, $sessionCookie, $store, ActionError, $actionError, $actionErrorOrThrow, $boundaryFallback, $setBoundaryError, $boundaryError, $append, $prepend, $merge, applyStateDeltas, textMark, attrMark, boolAttrMark, ifMark, eachMark, headMark, rawMark, slotBlockMark, redirect, notFound } from './runtime.js';`;
|
|
2679
|
+
var API_RUNTIME_HELPERS = RUNTIME_IMPORTS.replace(/^import\s*\{/, "").replace(/\}\s*from[\s\S]*$/, "").split(",").map((s) => s.trim()).filter(Boolean);
|
|
1447
2680
|
function propsCode(props) {
|
|
1448
2681
|
if (props.length === 0) return "";
|
|
1449
2682
|
return props.map((p) => `const ${p.name} = __p.${p.name}${p.def ? ` ?? (${p.def})` : ""};`).join("\n");
|
|
@@ -1455,15 +2688,15 @@ var SLOT_HELPER = `const __slot = (sl, name, pairs) => {
|
|
|
1455
2688
|
for (let i = 0; i < pairs.length; i++) o[pairs[i][0]] = pairs[i][1];
|
|
1456
2689
|
return { o, fn };
|
|
1457
2690
|
};
|
|
1458
|
-
const __slotBlock = (closes, sl, name, pairs) => {
|
|
2691
|
+
const __slotBlock = (closes, sl, name, pairs, fallback) => {
|
|
1459
2692
|
const hit = __slot(sl, name, pairs);
|
|
1460
|
-
|
|
1461
|
-
|
|
1462
|
-
|
|
1463
|
-
|
|
1464
|
-
|
|
1465
|
-
|
|
1466
|
-
return
|
|
2693
|
+
if (hit) return slotBlockMark(closes, hit);
|
|
2694
|
+
return fallback || '';
|
|
2695
|
+
};
|
|
2696
|
+
const __slotDefault = (children, fallback) => {
|
|
2697
|
+
const c = children == null ? '' : String(children);
|
|
2698
|
+
if (c.trim()) return c;
|
|
2699
|
+
return fallback || '';
|
|
1467
2700
|
};`;
|
|
1468
2701
|
function generateSSR(script, templateFn, stateDeclsCode, exports = "", headFn = "", props = [], namedSlots = false, imports = "", isComponent = false, guard = "", hasActions = false, dataDeclsCode = "") {
|
|
1469
2702
|
const headCode = headFn ? `
|
|
@@ -1489,9 +2722,7 @@ export ${isComponent ? "function" : "async function"} render(closes, children, _
|
|
|
1489
2722
|
${script}
|
|
1490
2723
|
${stateDeclsCode}
|
|
1491
2724
|
${dataDeclsCode}
|
|
1492
|
-
|
|
1493
|
-
// applied to the state the declarations above just established (a no-op on
|
|
1494
|
-
// every path that is not a server action's re-render - see the runtime).
|
|
2725
|
+
|
|
1495
2726
|
${isComponent ? "" : "applyStateDeltas();"}
|
|
1496
2727
|
const __root = (__c, children) => { let h = ''; ${templateFn} return h; };
|
|
1497
2728
|
let __html = ${isComponent ? "" : "await "}__root(closes, children);${headCode}
|
|
@@ -1501,6 +2732,7 @@ export ${isComponent ? "function" : "async function"} render(closes, children, _
|
|
|
1501
2732
|
}
|
|
1502
2733
|
function generateClient(script, templateFn, stateDeclsCode, eventBindings, exports = "", headFn = "", props = [], namedSlots = false, imports = "", isComponent = false, dataDeclsCode = "") {
|
|
1503
2734
|
const handlerRegistry = eventBindings.length > 0 ? `Object.assign(handlers, { ${eventBindings.map((b) => b.fn).join(", ")} });` : "";
|
|
2735
|
+
const clientSetState = eventBindings.length > 0 ? `const $setState = (key, value) => setState(key, value);` : "";
|
|
1504
2736
|
const headCode = headFn ? `
|
|
1505
2737
|
const __head = () => { let __hd = ''; ${headFn} return __hd; };
|
|
1506
2738
|
__html += headMark(closes, __head);` : "";
|
|
@@ -1510,7 +2742,9 @@ ${RUNTIME_IMPORTS}
|
|
|
1510
2742
|
${imports}
|
|
1511
2743
|
|
|
1512
2744
|
${exports}
|
|
1513
|
-
|
|
2745
|
+
${clientSetState ? `
|
|
2746
|
+
${clientSetState}
|
|
2747
|
+
` : ""}
|
|
1514
2748
|
${namedSlots ? SLOT_HELPER : ""}
|
|
1515
2749
|
|
|
1516
2750
|
export ${isComponent ? "function" : "async function"} render(closes, children, __props, __slots) {
|
|
@@ -1533,55 +2767,98 @@ var routeShipsNoJs = (infos, compiled, i) => {
|
|
|
1533
2767
|
if (compiled[i].needsClient) return false;
|
|
1534
2768
|
return !layoutsOf(infos, i).some((li) => compiled[li].needsClient);
|
|
1535
2769
|
};
|
|
2770
|
+
var routeShellOff = (infos, compiled, i) => compiled[i].shell === false || layoutsOf(infos, i).some((li) => compiled[li].shell === false);
|
|
1536
2771
|
function buildReport(infos, compiled) {
|
|
1537
2772
|
return infos.map((info, i) => ({ info, i })).filter(({ info }) => !info.isLayout && !info.isNotFound && !info.isError && !info.isApi && !info.isMiddleware && !info.isComponent).map(({ info, i }) => {
|
|
1538
2773
|
if (routeShipsNoJs(infos, compiled, i)) {
|
|
1539
2774
|
return `${info.routePath} zero-JS nothing in the chain needs the client`;
|
|
1540
2775
|
}
|
|
1541
|
-
const why = [i, ...layoutsOf(infos, i)].filter((ci) => compiled[ci].needsClient).map((ci) => `${(compiled[ci].clientReasons ?? ["needs the client"]).join(" + ")} in ${
|
|
2776
|
+
const why = [i, ...layoutsOf(infos, i)].filter((ci) => compiled[ci].needsClient).map((ci) => `${(compiled[ci].clientReasons ?? ["needs the client"]).join(" + ")} in ${path2.basename(infos[ci].filePath)}`).join("; ");
|
|
1542
2777
|
const forced = compiled[i].csr === true ? " (csr = true forces the bundle)" : "";
|
|
1543
2778
|
return `${info.routePath} client JS ${why}${forced}`;
|
|
1544
2779
|
});
|
|
1545
2780
|
}
|
|
2781
|
+
var MOUNT_ENTRY = `
|
|
2782
|
+
import { start, postForm } from '/client.js';
|
|
2783
|
+
|
|
2784
|
+
for (const el of document.querySelectorAll('[data-rosetack]')) {
|
|
2785
|
+
const route = el.getAttribute('data-rosetack');
|
|
2786
|
+
const doc = await fetch(route).then((r) => (r.ok ? r.text() : ''));
|
|
2787
|
+
const parsed = new DOMParser().parseFromString(doc, 'text/html');
|
|
2788
|
+
// A JS-shipping document wraps its content in #app; a zero-JS route's content is the body's own (no wrapper).
|
|
2789
|
+
const app = parsed.getElementById('app');
|
|
2790
|
+
if (app) {
|
|
2791
|
+
el.innerHTML = app.innerHTML;
|
|
2792
|
+
} else {
|
|
2793
|
+
for (const node of Array.from(parsed.body.children)) {
|
|
2794
|
+
if (!/^(?:SCRIPT|LINK|STYLE)$/.test(node.tagName)) el.appendChild(node);
|
|
2795
|
+
}
|
|
2796
|
+
}
|
|
2797
|
+
// start() resumes from #__rosetack_state (zero hydration), so the state
|
|
2798
|
+
|
|
2799
|
+
const state = parsed.getElementById('__rosetack_state');
|
|
2800
|
+
if (state) el.appendChild(state);
|
|
2801
|
+
|
|
2802
|
+
const rendered = state ? JSON.parse(state.textContent || '{}').__route : null;
|
|
2803
|
+
await start(el, route, rendered === route);
|
|
2804
|
+
if (state) state.remove();
|
|
2805
|
+
|
|
2806
|
+
el.addEventListener('click', (e) => {
|
|
2807
|
+
const a = e.target.closest && e.target.closest('a[href^="/"]');
|
|
2808
|
+
if (!a || !el.contains(a)) return;
|
|
2809
|
+
e.preventDefault();
|
|
2810
|
+
el.setAttribute('data-rosetack', a.getAttribute('href'));
|
|
2811
|
+
start(el, a.getAttribute('href'), false);
|
|
2812
|
+
});
|
|
2813
|
+
// Progressive-enhancement forms work inside a mount too: the native POST would replace the HOST page.
|
|
2814
|
+
el.addEventListener('submit', (e) => {
|
|
2815
|
+
const f = e.target;
|
|
2816
|
+
if (!f || f.tagName !== 'FORM' || f.hasAttribute('data-on-submit')) return;
|
|
2817
|
+
if ((f.getAttribute('method') || '').toLowerCase() !== 'post') return;
|
|
2818
|
+
e.preventDefault();
|
|
2819
|
+
postForm(new FormData(f), el, el.getAttribute('data-rosetack'));
|
|
2820
|
+
});
|
|
2821
|
+
}
|
|
2822
|
+
`;
|
|
1546
2823
|
async function buildProject(root, outDir) {
|
|
1547
|
-
await
|
|
1548
|
-
const stale = (await
|
|
1549
|
-
await Promise.all(stale.map((f) =>
|
|
2824
|
+
await fs3.promises.mkdir(outDir, { recursive: true });
|
|
2825
|
+
const stale = (await fs3.promises.readdir(outDir)).filter((f) => /^(?:comp-\d+\.(?:ssr|client)|runtime|(?:server|client)-entry)\.js$/.test(f));
|
|
2826
|
+
await Promise.all(stale.map((f) => fs3.promises.rm(path2.join(outDir, f), { force: true })));
|
|
1550
2827
|
const pageFiles = await scanRoseFiles(root);
|
|
1551
2828
|
const compFiles = await scanComponentFiles(root);
|
|
1552
2829
|
const files = [...pageFiles, ...compFiles];
|
|
1553
2830
|
if (pageFiles.length === 0) {
|
|
1554
2831
|
throw new RoseError(
|
|
1555
2832
|
"E-ROUTE",
|
|
1556
|
-
`no .rose pages found under ${
|
|
1557
|
-
{ file:
|
|
2833
|
+
`no .rose pages found under ${path2.join(root, "src", "pages")} - run rosetack from a project root, or pass one: rosetack build <dir>`,
|
|
2834
|
+
{ file: path2.join(root, "src", "pages"), hint: "create src/pages/index.rose in that directory (or run the command from the project root)" }
|
|
1558
2835
|
);
|
|
1559
2836
|
}
|
|
1560
2837
|
const infos = files.map((f) => ({ ...getRouteInfo(f, root) }));
|
|
1561
2838
|
const config = await loadConfig(root);
|
|
1562
2839
|
const plugins = config.plugins;
|
|
1563
2840
|
const scopeKeys = files.map((f, i) => {
|
|
1564
|
-
const base = infos[i].isComponent ?
|
|
1565
|
-
return
|
|
2841
|
+
const base = infos[i].isComponent ? path2.join(root, "src") : path2.join(root, "src", "pages");
|
|
2842
|
+
return path2.relative(base, f).replace(/\\/g, "/").replace(/\.rose$/, "");
|
|
1566
2843
|
});
|
|
1567
2844
|
const registry = new Map(
|
|
1568
2845
|
files.map((f, i) => [f, { index: i, scopeKey: scopeKeys[i], slots: scanSlotDecls(f) }])
|
|
1569
2846
|
);
|
|
1570
2847
|
const compiled = await Promise.all(
|
|
1571
|
-
files.map((f, i) => compileComponent(f,
|
|
2848
|
+
files.map((f, i) => compileComponent(f, path2.join(root, "public"), scopeKeys[i], infos[i].isApi, plugins, registry))
|
|
1572
2849
|
);
|
|
1573
2850
|
const importsOf = /* @__PURE__ */ new Map();
|
|
1574
2851
|
files.forEach((_, i) => {
|
|
1575
2852
|
const list = [];
|
|
1576
2853
|
for (const r of compiled[i].roseImports ?? []) {
|
|
1577
|
-
const abs =
|
|
2854
|
+
const abs = path2.resolve(path2.dirname(files[i]), r.specifier);
|
|
1578
2855
|
const hit = registry.get(abs);
|
|
1579
2856
|
if (hit) list.push(hit.index);
|
|
1580
2857
|
}
|
|
1581
2858
|
importsOf.set(i, list);
|
|
1582
2859
|
});
|
|
1583
2860
|
const needyDep = (i, seen = /* @__PURE__ */ new Set()) => {
|
|
1584
|
-
if (compiled[i].needsClient) return
|
|
2861
|
+
if (compiled[i].needsClient) return path2.basename(files[i]);
|
|
1585
2862
|
if (seen.has(i)) return null;
|
|
1586
2863
|
seen.add(i);
|
|
1587
2864
|
for (const dep of importsOf.get(i) ?? []) {
|
|
@@ -1603,7 +2880,7 @@ async function buildProject(root, outDir) {
|
|
|
1603
2880
|
if (reachable.has(i)) return;
|
|
1604
2881
|
reachable.add(i);
|
|
1605
2882
|
for (const r of compiled[i].roseImports ?? []) {
|
|
1606
|
-
const abs =
|
|
2883
|
+
const abs = path2.resolve(path2.dirname(files[i]), r.specifier);
|
|
1607
2884
|
const hit = registry.get(abs);
|
|
1608
2885
|
if (hit) visit(hit.index);
|
|
1609
2886
|
}
|
|
@@ -1612,13 +2889,13 @@ async function buildProject(root, outDir) {
|
|
|
1612
2889
|
if (!infos[i].isComponent) visit(i);
|
|
1613
2890
|
});
|
|
1614
2891
|
const styles = compiled.map((c, i) => reachable.has(i) ? c.style : "").filter(Boolean).join("\n");
|
|
1615
|
-
if (styles) await
|
|
1616
|
-
else await
|
|
2892
|
+
if (styles) await fs3.promises.writeFile(path2.join(outDir, "styles.css"), styles);
|
|
2893
|
+
else await fs3.promises.rm(path2.join(outDir, "styles.css"), { force: true });
|
|
1617
2894
|
let locales = {};
|
|
1618
2895
|
try {
|
|
1619
|
-
for (const f of await
|
|
2896
|
+
for (const f of await fs3.promises.readdir(path2.join(root, "src", "locales"))) {
|
|
1620
2897
|
if (!f.endsWith(".json")) continue;
|
|
1621
|
-
locales[f.slice(0, -5)] = JSON.parse(await
|
|
2898
|
+
locales[f.slice(0, -5)] = JSON.parse(await fs3.promises.readFile(path2.join(root, "src", "locales", f), "utf-8"));
|
|
1622
2899
|
}
|
|
1623
2900
|
} catch {
|
|
1624
2901
|
locales = {};
|
|
@@ -1630,23 +2907,24 @@ async function buildProject(root, outDir) {
|
|
|
1630
2907
|
for (const l of preload) {
|
|
1631
2908
|
if (!locales[l]) console.warn(`rosetack: i18n.preload lists '${l}' but there is no src/locales/${l}.json - ignored`);
|
|
1632
2909
|
}
|
|
1633
|
-
await
|
|
2910
|
+
await fs3.promises.rm(path2.join(outDir, "locales"), { recursive: true, force: true });
|
|
1634
2911
|
if (packed.length > 0) {
|
|
1635
|
-
const packDir =
|
|
1636
|
-
await
|
|
1637
|
-
for (const l of packed) await
|
|
2912
|
+
const packDir = path2.join(outDir, "locales");
|
|
2913
|
+
await fs3.promises.mkdir(packDir, { recursive: true });
|
|
2914
|
+
for (const l of packed) await fs3.promises.writeFile(path2.join(packDir, `${l}.json`), JSON.stringify(locales[l]));
|
|
1638
2915
|
}
|
|
1639
2916
|
const clientLocales = Object.fromEntries(Object.keys(locales).filter((l) => !packed.includes(l)).map((l) => [l, locales[l]]));
|
|
1640
2917
|
const clientLocalesJson = JSON.stringify(clientLocales).replace(/</g, "\\u003c");
|
|
1641
|
-
const buildDir =
|
|
1642
|
-
await
|
|
1643
|
-
await
|
|
2918
|
+
const buildDir = path2.join(outDir, ".build");
|
|
2919
|
+
await fs3.promises.rm(buildDir, { recursive: true, force: true });
|
|
2920
|
+
await fs3.promises.mkdir(buildDir, { recursive: true });
|
|
2921
|
+
const contentSrcCands = [path2.join(path2.dirname(fileURLToPath(import.meta.url)), "..", "cli", "content.ts"), path2.join(path2.dirname(fileURLToPath(import.meta.url)), "..", "src", "cli", "content.ts")];
|
|
2922
|
+
const contentSrc = contentSrcCands.find((c) => fs3.existsSync(c)) ?? contentSrcCands[0];
|
|
2923
|
+
fs3.copyFileSync(contentSrc, path2.join(buildDir, "content-md.ts"));
|
|
1644
2924
|
const runtimePlugins = plugins.filter((p) => p && (p.onRequest || p.onResponse));
|
|
1645
2925
|
if (runtimePlugins.length > 0) {
|
|
1646
|
-
const configRel =
|
|
1647
|
-
await
|
|
1648
|
-
// Bundled into dist/server.js: these hooks run per request on every server
|
|
1649
|
-
// (Node, dev/preview, edge). Transform hooks already ran at build time.
|
|
2926
|
+
const configRel = path2.relative(buildDir, path2.join(root, "rosetack.config.js")).replace(/\\/g, "/");
|
|
2927
|
+
await fs3.promises.writeFile(path2.join(buildDir, "plugins.js"), `
|
|
1650
2928
|
import config from ${JSON.stringify(configRel)};
|
|
1651
2929
|
|
|
1652
2930
|
const list = Array.isArray(config) ? config : [];
|
|
@@ -1658,25 +2936,51 @@ export const hasRequestHooks = hooks.some((p) => p.onRequest);
|
|
|
1658
2936
|
export const hasResponseHooks = hooks.some((p) => p.onResponse);
|
|
1659
2937
|
`);
|
|
1660
2938
|
}
|
|
1661
|
-
const runtimeEntry = ["../runtime/index.ts", "../src/runtime/index.ts"].map((rel) => fileURLToPath(new URL(rel, import.meta.url))).find((p) =>
|
|
2939
|
+
const runtimeEntry = ["../runtime/index.ts", "../src/runtime/index.ts"].map((rel) => fileURLToPath(new URL(rel, import.meta.url))).find((p) => fs3.existsSync(p));
|
|
1662
2940
|
if (!runtimeEntry) throw new RoseError("E-INTERNAL", "rosetack: the runtime source (src/runtime/index.ts) was not found next to the compiler", { hint: "the published package ships src/ beside dist-cli/ - reinstall it, or run from a checkout" });
|
|
1663
2941
|
await esbuild.build({
|
|
1664
2942
|
entryPoints: [runtimeEntry],
|
|
1665
2943
|
bundle: true,
|
|
1666
|
-
outfile:
|
|
2944
|
+
outfile: path2.join(buildDir, "runtime.js"),
|
|
1667
2945
|
format: "esm",
|
|
1668
2946
|
platform: "browser",
|
|
1669
2947
|
write: true
|
|
1670
2948
|
});
|
|
1671
2949
|
for (let i = 0; i < compiled.length; i++) {
|
|
1672
2950
|
const src = compiled[i].api ?? compiled[i].ssr;
|
|
1673
|
-
await
|
|
2951
|
+
await fs3.promises.writeFile(path2.join(buildDir, `comp-${i}.ssr.js`), src);
|
|
1674
2952
|
if (!infos[i].isApi) {
|
|
1675
|
-
await
|
|
2953
|
+
await fs3.promises.writeFile(path2.join(buildDir, `comp-${i}.client.js`), compiled[i].client);
|
|
1676
2954
|
}
|
|
1677
2955
|
}
|
|
1678
|
-
const pages = infos.map((info, i) => ({ info, i })).filter(({ info }) => !info.isLayout && !info.isNotFound && !info.isError && !info.isApi && !info.isMiddleware && !info.isComponent)
|
|
1679
|
-
|
|
2956
|
+
const pages = infos.map((info, i) => ({ info, i })).filter(({ info }) => !info.isLayout && !info.isNotFound && !info.isError && !info.isApi && !info.isMiddleware && !info.isComponent).sort((a, b) => {
|
|
2957
|
+
const rank = (pattern) => {
|
|
2958
|
+
const segs = pattern.split("/");
|
|
2959
|
+
return [
|
|
2960
|
+
segs.filter((s) => s.startsWith("**")).length,
|
|
2961
|
+
segs.filter((s) => s.startsWith("*")).length,
|
|
2962
|
+
segs.filter((s) => s.startsWith(":")).length
|
|
2963
|
+
];
|
|
2964
|
+
};
|
|
2965
|
+
const ra = rank(a.info.pattern);
|
|
2966
|
+
const rb = rank(b.info.pattern);
|
|
2967
|
+
for (let k = 0; k < 3; k++) if (ra[k] !== rb[k]) return ra[k] - rb[k];
|
|
2968
|
+
return a.info.filePath < b.info.filePath ? -1 : 1;
|
|
2969
|
+
});
|
|
2970
|
+
const apiRoutes = infos.map((info, i) => ({ info, i })).filter(({ info }) => info.isApi).sort((a, b) => {
|
|
2971
|
+
const rank = (pattern) => {
|
|
2972
|
+
const segs = pattern.split("/");
|
|
2973
|
+
return [
|
|
2974
|
+
segs.filter((s) => s.startsWith("**")).length,
|
|
2975
|
+
segs.filter((s) => s.startsWith("*")).length,
|
|
2976
|
+
segs.filter((s) => s.startsWith(":")).length
|
|
2977
|
+
];
|
|
2978
|
+
};
|
|
2979
|
+
const ra = rank(a.info.pattern);
|
|
2980
|
+
const rb = rank(b.info.pattern);
|
|
2981
|
+
for (let k = 0; k < 3; k++) if (ra[k] !== rb[k]) return ra[k] - rb[k];
|
|
2982
|
+
return a.info.filePath < b.info.filePath ? -1 : 1;
|
|
2983
|
+
});
|
|
1680
2984
|
const compose = (idx) => {
|
|
1681
2985
|
let expr = `render_${idx}`;
|
|
1682
2986
|
for (const i of layoutsOf(infos, idx)) {
|
|
@@ -1707,10 +3011,18 @@ export const hasResponseHooks = hooks.some((p) => p.onResponse);
|
|
|
1707
3011
|
const named = [actionImports, guardImport].filter(Boolean).join(", ");
|
|
1708
3012
|
return named ? `import { render as render_${i}, ${named} } from './comp-${i}.ssr.js';` : `import { render as render_${i} } from './comp-${i}.ssr.js';`;
|
|
1709
3013
|
}).join("\n");
|
|
1710
|
-
const
|
|
1711
|
-
|
|
3014
|
+
const notFoundEntries = infos.map((info, i) => ({ info, i })).filter(({ info }) => info.isNotFound).map(({ info, i }) => {
|
|
3015
|
+
const rel = path2.relative(path2.join(root, "src", "pages"), info.filePath).replace(/\\/g, "/");
|
|
3016
|
+
const dir = path2.posix.dirname(rel);
|
|
3017
|
+
const prefix = dir === "." ? "/" : "/" + dir;
|
|
3018
|
+
const flags = routeShellOff(infos, compiled, i) ? ", { shell: false }" : "";
|
|
3019
|
+
return { prefix, render: compose(i), flags };
|
|
3020
|
+
}).sort((a, b) => b.prefix.length - a.prefix.length);
|
|
3021
|
+
const notFoundTable = `[
|
|
3022
|
+
${notFoundEntries.map((e) => ` ['${e.prefix}', ${e.render}${e.flags}],`).join("\n")}
|
|
3023
|
+
]`;
|
|
1712
3024
|
const errIdx = infos.findIndex((info) => info.isError);
|
|
1713
|
-
const errorRender = errIdx >= 0 ?
|
|
3025
|
+
const errorRender = errIdx >= 0 ? compose(errIdx) : "null";
|
|
1714
3026
|
const middlewareIdx = infos.findIndex((info) => info.isMiddleware);
|
|
1715
3027
|
const serverRoutes = pages.map(({ info, i }) => {
|
|
1716
3028
|
const actionMap = compiled[i].actionNames.map((n) => `${n}: ${n}_${i}`).join(", ");
|
|
@@ -1732,13 +3044,17 @@ export const hasResponseHooks = hooks.some((p) => p.onResponse);
|
|
|
1732
3044
|
}
|
|
1733
3045
|
}
|
|
1734
3046
|
const csrFlag = routeNoJs(i) ? ", csr: false" : "";
|
|
3047
|
+
const shellFlag = routeShellOff(infos, compiled, i) ? ", shell: false" : "";
|
|
1735
3048
|
const bufferFlag = compiled[i].buffer ? ", buffer: true" : "";
|
|
3049
|
+
const signalFlag = compiled[i].controlSignal ? ", signal: true" : "";
|
|
1736
3050
|
const guardFlag = compiled[i].guardName ? `, guard: beforeAction_${i}` : "";
|
|
1737
|
-
return `{ pattern: '${info.pattern}', path: '${info.routePath}', render: ${compose(i)}, actions: ${actionMap ? `{ ${actionMap} }` : "null"}${guardFlag}${csrFlag}${bufferFlag} }`;
|
|
3051
|
+
return `{ pattern: '${info.pattern}', path: '${info.routePath}', render: ${compose(i)}, actions: ${actionMap ? `{ ${actionMap} }` : "null"}${guardFlag}${csrFlag}${shellFlag}${bufferFlag}${signalFlag} }`;
|
|
1738
3052
|
}).join(",\n ");
|
|
1739
3053
|
const serverEntry = `
|
|
1740
3054
|
${serverImports}
|
|
1741
|
-
import {
|
|
3055
|
+
import { renderMarkdown } from './content-md.ts';
|
|
3056
|
+
import crypto from 'node:crypto';
|
|
3057
|
+
import { setState, persistState, clearRequestState, serializeState, resetRequestContext, setRequestQuery, isLocale, setLocales, localeList, localeDir, setStoreTransport, applyStorePatch, ActionError, StateDelta, setStateDelta, esc } from './runtime.js';
|
|
1742
3058
|
${runtimePlugins.length > 0 ? `import { hooks as __pluginHooks, hasRequestHooks as __hasRequestHooks, hasResponseHooks as __hasResponseHooks } from './plugins.js';` : `// no plugin declares a runtime hook, so there is no plugins
|
|
1743
3059
|
// module to import - the runners below stay no-ops and the servers call them
|
|
1744
3060
|
// unconditionally (one code path, no flags to keep in sync).
|
|
@@ -1746,12 +3062,7 @@ const __pluginHooks = [];
|
|
|
1746
3062
|
const __hasRequestHooks = false;
|
|
1747
3063
|
const __hasResponseHooks = false;`}
|
|
1748
3064
|
|
|
1749
|
-
|
|
1750
|
-
// middleware and may short-circuit the request with its own Response; onResponse
|
|
1751
|
-
// runs once the response exists and may replace it. Both are no-ops when the
|
|
1752
|
-
// project declares no runtime hooks. A throwing hook is logged and skipped -
|
|
1753
|
-
// the request continues - so a broken logging plugin can never take a site
|
|
1754
|
-
// down (a build-time transform, by contrast, fails loudly).
|
|
3065
|
+
|
|
1755
3066
|
export async function runRequestHooks(ctx) {
|
|
1756
3067
|
for (const p of __pluginHooks) {
|
|
1757
3068
|
if (!p.onRequest) continue;
|
|
@@ -1779,32 +3090,20 @@ export async function runResponseHooks(ctx, res) {
|
|
|
1779
3090
|
return out;
|
|
1780
3091
|
}
|
|
1781
3092
|
|
|
1782
|
-
|
|
1783
|
-
|
|
3093
|
+
|
|
3094
|
+
|
|
1784
3095
|
export const hasRequestHooks = __hasRequestHooks;
|
|
1785
3096
|
export const hasResponseHooks = __hasResponseHooks;
|
|
1786
3097
|
|
|
1787
|
-
// P0-1: the query of the request being rendered, for $query().
|
|
1788
|
-
// call this before every render (stream, buffered, POST, api) with the parsed
|
|
1789
|
-
// query string; routing itself matches the pathname, which is what fixed the
|
|
1790
|
-
// query-404. A render with no query (the build's prerender, the ISR
|
|
1791
|
-
// background pass) passes {} explicitly - the bag is per request, so a stale
|
|
1792
|
-
// one must never leak into the next.
|
|
3098
|
+
// P0-1: the query of the request being rendered, for $query().
|
|
1793
3099
|
export function setQuery(query) {
|
|
1794
3100
|
setRequestQuery(query || {});
|
|
1795
3101
|
}
|
|
1796
3102
|
|
|
1797
|
-
|
|
1798
|
-
// src/locales/*.json. A route segment named [lang] is the locale: the value
|
|
1799
|
-
// must name one of these dictionaries, and $t resolves keys against it.
|
|
3103
|
+
|
|
1800
3104
|
setLocales(${localesJson}, '${defaultLocale}');
|
|
1801
3105
|
|
|
1802
|
-
|
|
1803
|
-
// own process with its own dist/server.js module, so a $store write must
|
|
1804
|
-
// travel: this worker -> primary -> every other worker. process.send exists
|
|
1805
|
-
// only inside cluster workers, so a single-process runner (dev, preview,
|
|
1806
|
-
// the edge adapter) keeps the transport null and $store stays plain
|
|
1807
|
-
// per-process state - the documented boundary, not a bug.
|
|
3106
|
+
|
|
1808
3107
|
if (typeof process !== 'undefined' && typeof process.send === 'function') {
|
|
1809
3108
|
setStoreTransport((name, value) => process.send({ type: 'rosetack:store', name, value }));
|
|
1810
3109
|
process.on('message', (msg) => {
|
|
@@ -1812,76 +3111,274 @@ if (typeof process !== 'undefined' && typeof process.send === 'function') {
|
|
|
1812
3111
|
});
|
|
1813
3112
|
}
|
|
1814
3113
|
|
|
3114
|
+
// (the cross-machine seam): the cluster relay above covers ONE machine.
|
|
3115
|
+
export function __installStoreTransport(send: (name: string, value: unknown) => void): void {
|
|
3116
|
+
setStoreTransport(send);
|
|
3117
|
+
}
|
|
3118
|
+
export function __deliverStorePatch(name: string, value: unknown): void {
|
|
3119
|
+
applyStorePatch(name, value);
|
|
3120
|
+
}
|
|
3121
|
+
|
|
1815
3122
|
export { localeList };
|
|
1816
3123
|
export const defaultLocale = '${defaultLocale}';
|
|
1817
3124
|
|
|
1818
|
-
// Route params maps, re-exported for the build's prerender step: routePath
|
|
1819
|
-
// -> the component's exported params (a static map or a function). Reading
|
|
1820
|
-
// them through the server bundle keeps the deploy dir free of component
|
|
1821
|
-
// modules - both bundles are self-contained, nothing else may ship. Only
|
|
1822
|
-
// components that actually export params appear here (a missing export
|
|
1823
|
-
// means the dynamic route renders on demand).
|
|
3125
|
+
// Route params maps, re-exported for the build's prerender step: routePath -> the component's exported params (a static map or a function).
|
|
1824
3126
|
${pages.filter(({ i }) => compiled[i].hasParams).map(({ i }) => `import * as comp_${i} from './comp-${i}.ssr.js';`).join("\n")}
|
|
1825
3127
|
|
|
1826
3128
|
export const routeParams = {
|
|
1827
3129
|
${pages.filter(({ info, i }) => compiled[i].hasParams).map(({ info, i }) => `'${info.routePath}': comp_${i}.params`).join(",\n ")}
|
|
1828
3130
|
};
|
|
1829
3131
|
|
|
1830
|
-
// Routes whose component reads the request context (getContext()), mutates a
|
|
1831
|
-
// shared store ($store()), reads the query ($query(), P0-1), opted into
|
|
1832
|
-
// nonce-based CSP or into the buffered path (buffer = true, P0-2):
|
|
1833
|
-
// the bag is per-request, the store is per-process, a nonce is per-response,
|
|
1834
|
-
// and a buffered route's hooks must run per request - so these are dynamic.
|
|
1835
|
-
// The build never bakes them and the servers never answer them from a
|
|
1836
|
-
// prerendered file. Public routes keep the static fast path (file cache,
|
|
1837
|
-
// ETag/304, streaming) untouched.
|
|
3132
|
+
// Routes whose component reads the request context (getContext()), mutates a shared store ($store()), reads the query ($query(), P0-1)
|
|
1838
3133
|
export const dynamicRoutes = [
|
|
1839
|
-
${pages.filter(({ i }) => compiled[i].usesContext || compiled[i].cspNonce || compiled[i].buffer).map(({ info }) => `'${info.routePath}'`).join(",\n ")}
|
|
3134
|
+
${pages.filter(({ i }) => compiled[i].usesContext || compiled[i].cspNonce || compiled[i].buffer || compiled[i].controlSignal).map(({ info }) => `'${info.routePath}'`).join(",\n ")}
|
|
1840
3135
|
];
|
|
1841
3136
|
|
|
1842
|
-
// Which api routes opt into build-time baking (export const prerender = true):
|
|
1843
|
-
// routePath -> boolean. The build calls the GET handler once and writes the
|
|
1844
|
-
// body to dist/, so the Go single binary serves read-only APIs without Node.
|
|
3137
|
+
// Which api routes opt into build-time baking (export const prerender = true): routePath -> boolean.
|
|
1845
3138
|
${apiRoutes.filter(({ i }) => compiled[i].hasPrerender).map(({ i }) => `import * as api_${i} from './comp-${i}.ssr.js';`).join("\n")}
|
|
1846
3139
|
|
|
1847
3140
|
export const apiPrerender = {
|
|
1848
3141
|
${apiRoutes.map(({ info, i }) => `'${info.routePath}': ${compiled[i].hasPrerender ? `api_${i}.prerender === true` : "false"}`).join(",\n ")}
|
|
1849
3142
|
};
|
|
1850
3143
|
|
|
1851
|
-
|
|
1852
|
-
// bakes these routes like any other, and the preview server serves the
|
|
1853
|
-
// baked file for up to N seconds - after which the next request is answered
|
|
1854
|
-
// STALE (instant, from disk) while a background pass re-renders and swaps
|
|
1855
|
-
// the file (ISR). Routes that read the request context are
|
|
1856
|
-
// excluded: they render per request and have no baked file to revalidate.
|
|
1857
|
-
// The dev server ignores the window (it rebuilds on change), the edge
|
|
1858
|
-
// adapter renders live (always fresh), and the Go binary serves the baked
|
|
1859
|
-
// file forever - the same static-half boundary as page POSTs.
|
|
3144
|
+
|
|
1860
3145
|
export const revalidate = [
|
|
1861
3146
|
${pages.filter(({ i }) => compiled[i].revalidate !== void 0 && !compiled[i].usesContext).map(({ info, i }) => `{ pattern: '${info.pattern}', seconds: ${compiled[i].revalidate} }`).join(",\n ")}
|
|
1862
3147
|
];
|
|
1863
3148
|
|
|
1864
|
-
//
|
|
1865
|
-
|
|
1866
|
-
|
|
1867
|
-
|
|
1868
|
-
|
|
1869
|
-
|
|
3149
|
+
// Per-request render memo (export const cache = N): a dynamic route's whole renderPage result is memoized for N seconds.
|
|
3150
|
+
export const routeCaches = [
|
|
3151
|
+
${pages.filter(({ i }) => compiled[i].cache !== void 0).map(({ info, i }) => `{ pattern: '${info.pattern}', seconds: ${compiled[i].cache} }`).join(",\n ")}
|
|
3152
|
+
];
|
|
3153
|
+
const __dynCache = new Map();
|
|
3154
|
+
export function invalidateRenderCache(): void {
|
|
3155
|
+
__dynCache.clear();
|
|
3156
|
+
}
|
|
3157
|
+
// Application KV cache primitive (server-side, per-worker in-memory): a zero-dependency store for expensive computations.
|
|
3158
|
+
const __kvStore = new Map<string, { v: unknown; exp: number }>();
|
|
3159
|
+
// Content collections: src/content/<coll>/*.md scanned once at build time,
|
|
3160
|
+
|
|
3161
|
+
const contentCollections = ${JSON.stringify(scanContentDir(path2.join(root, "src", "content")))};
|
|
3162
|
+
export const kv = {
|
|
3163
|
+
get(key: string): unknown {
|
|
3164
|
+
const e = __kvStore.get(key);
|
|
3165
|
+
if (!e) return undefined;
|
|
3166
|
+
if (e.exp < Date.now()) { __kvStore.delete(key); return undefined; }
|
|
3167
|
+
return e.v;
|
|
3168
|
+
},
|
|
3169
|
+
set(key: string, value: unknown, ttlSeconds = 300): void {
|
|
3170
|
+
if (__kvStore.size > 1000) {
|
|
3171
|
+
const cutoff = Date.now();
|
|
3172
|
+
for (const [k, e] of __kvStore) { if (e.exp < cutoff) __kvStore.delete(k); }
|
|
3173
|
+
if (__kvStore.size > 2000) __kvStore.clear();
|
|
3174
|
+
}
|
|
3175
|
+
__kvStore.set(key, { v: value, exp: Date.now() + ttlSeconds * 1000 });
|
|
3176
|
+
},
|
|
3177
|
+
del(key: string): void { __kvStore.delete(key); },
|
|
3178
|
+
has(key: string): boolean {
|
|
3179
|
+
const e = __kvStore.get(key);
|
|
3180
|
+
return !!e && e.exp >= Date.now();
|
|
3181
|
+
},
|
|
3182
|
+
};
|
|
3183
|
+
globalThis.__rosetackKvApi = { kv, kvMemo: $kv };
|
|
3184
|
+
globalThis.__rosetackContent = {
|
|
3185
|
+
list: (coll: string, filter?: { tag: string }) => {
|
|
3186
|
+
let items = contentCollections[coll] ?? [];
|
|
3187
|
+
if (filter?.tag) items = items.filter((e) => ((e.frontmatter.tags as string[] | undefined) ?? []).includes(filter.tag));
|
|
3188
|
+
return items.map((e) => ({ slug: e.slug, ...e.frontmatter }));
|
|
3189
|
+
},
|
|
3190
|
+
rss: (coll: string, opts: { title: string; origin: string; description?: string }) => {
|
|
3191
|
+
return buildRss(contentCollections[coll] ?? [], opts);
|
|
3192
|
+
},
|
|
3193
|
+
get: (coll: string, slug: string, vars?: Record<string, unknown>) => {
|
|
3194
|
+
const e = (contentCollections[coll] ?? []).find((x) => x.slug === slug);
|
|
3195
|
+
if (!e) return null;
|
|
3196
|
+
return { slug: e.slug, ...e.frontmatter, html: renderMarkdown(e.body, vars), toc: e.toc, readingTime: e.readingTime, wordCount: e.wordCount, excerpt: e.excerpt };
|
|
3197
|
+
},
|
|
3198
|
+
};
|
|
3199
|
+
|
|
3200
|
+
const v = {
|
|
3201
|
+
validate(body: Record<string, unknown>, rules: Record<string, string[]>): { ok: boolean; errors: Record<string, string>; values: Record<string, unknown> } {
|
|
3202
|
+
const errors: Record<string, string> = {};
|
|
3203
|
+
const values: Record<string, unknown> = {};
|
|
3204
|
+
for (const [field, ruleList] of Object.entries(rules)) {
|
|
3205
|
+
let val = body[field];
|
|
3206
|
+
for (const rule of ruleList) {
|
|
3207
|
+
if (val === undefined || val === null || val === "") {
|
|
3208
|
+
if (rule === "required") errors[field] = field + " is required";
|
|
3209
|
+
else if (rule.startsWith("default:")) val = rule.slice(8);
|
|
3210
|
+
continue;
|
|
3211
|
+
}
|
|
3212
|
+
if (rule === "string") val = String(val);
|
|
3213
|
+
else if (rule === "trim") val = String(val).trim();
|
|
3214
|
+
else if (rule === "number") {
|
|
3215
|
+
const num = Number(val);
|
|
3216
|
+
if (Number.isNaN(num)) errors[field] = field + " must be a number";
|
|
3217
|
+
else val = num;
|
|
3218
|
+
} else if (rule === "email") {
|
|
3219
|
+
if (!/^[^s@]+@[^s@]+.[^s@]+$/.test(String(val))) errors[field] = field + " must be a valid email";
|
|
3220
|
+
} else if (rule.startsWith("min:")) {
|
|
3221
|
+
const min = Number(rule.slice(4));
|
|
3222
|
+
if (typeof val === "number" ? val < min : String(val).length < min) errors[field] = field + " must be at least " + min;
|
|
3223
|
+
} else if (rule.startsWith("max:")) {
|
|
3224
|
+
const max = Number(rule.slice(4));
|
|
3225
|
+
if (typeof val === "number" ? val > max : String(val).length > max) errors[field] = field + " must be at most " + max;
|
|
3226
|
+
}
|
|
3227
|
+
}
|
|
3228
|
+
values[field] = val;
|
|
3229
|
+
}
|
|
3230
|
+
return { ok: Object.keys(errors).length === 0, errors, values };
|
|
3231
|
+
},
|
|
3232
|
+
};
|
|
3233
|
+
|
|
3234
|
+
const jobs = {
|
|
3235
|
+
_timers: new Map<string, ReturnType<typeof setInterval>>(),
|
|
3236
|
+
every(name: string, seconds: number, fn: () => void | Promise<void>): void {
|
|
3237
|
+
if (this._timers.has(name)) return;
|
|
3238
|
+
const t = setInterval(() => { Promise.resolve(fn()).catch(() => {}); }, seconds * 1000);
|
|
3239
|
+
this._timers.set(name, t as any);
|
|
3240
|
+
},
|
|
3241
|
+
cancel(name: string): void {
|
|
3242
|
+
const t = this._timers.get(name);
|
|
3243
|
+
if (t) { clearInterval(t); this._timers.delete(name); }
|
|
3244
|
+
},
|
|
3245
|
+
cancelAll(): void { for (const t of this._timers.values()) clearInterval(t); this._timers.clear(); }
|
|
3246
|
+
};
|
|
3247
|
+
|
|
3248
|
+
function sse(handler: (send: (event: string, data: unknown) => void) => Promise<void> | void): Response {
|
|
3249
|
+
const encoder = new TextEncoder();
|
|
3250
|
+
const stream = new ReadableStream({
|
|
3251
|
+
async start(controller) {
|
|
3252
|
+
let closed = false;
|
|
3253
|
+
const send = (event: string, data: unknown) => {
|
|
3254
|
+
if (closed) return;
|
|
3255
|
+
controller.enqueue(encoder.encode("event: " + event + "\\ndata: " + JSON.stringify(data) + "\\n\\n"));
|
|
3256
|
+
};
|
|
3257
|
+
try {
|
|
3258
|
+
await handler(send);
|
|
3259
|
+
} finally {
|
|
3260
|
+
closed = true;
|
|
3261
|
+
try { controller.close(); } catch { }
|
|
3262
|
+
}
|
|
3263
|
+
},
|
|
3264
|
+
});
|
|
3265
|
+
return new Response(stream, {
|
|
3266
|
+
headers: { "content-type": "text/event-stream; charset=utf-8", "cache-control": "no-cache", "connection": "keep-alive" },
|
|
3267
|
+
});
|
|
3268
|
+
}
|
|
3269
|
+
globalThis.__rosetackExtras = { v, jobs, sse };
|
|
3270
|
+
const auth = {
|
|
3271
|
+
hashPassword(password: string): string {
|
|
3272
|
+
const salt = crypto.randomBytes(16).toString("hex");
|
|
3273
|
+
const hash = crypto.scryptSync(password, salt, 32).toString("hex");
|
|
3274
|
+
return salt + ":" + hash;
|
|
3275
|
+
},
|
|
3276
|
+
verifyPassword(password: string, stored: string): boolean {
|
|
3277
|
+
const [salt, hash] = stored.split(":");
|
|
3278
|
+
if (!salt || !hash) return false;
|
|
3279
|
+
return crypto.timingSafeEqual(Buffer.from(hash, "hex"), crypto.scryptSync(password, salt, 32));
|
|
3280
|
+
},
|
|
3281
|
+
signSession(data: Record<string, unknown>, secret: string, ttlSeconds = 86400): string {
|
|
3282
|
+
const payload = Buffer.from(JSON.stringify({ ...data, exp: Date.now() + ttlSeconds * 1000 })).toString("base64url");
|
|
3283
|
+
const sig = crypto.createHmac("sha256", secret).update(payload).digest("base64url");
|
|
3284
|
+
return payload + "." + sig;
|
|
3285
|
+
},
|
|
3286
|
+
verifySession<T = Record<string, unknown>>(token: string, secret: string): T | null {
|
|
3287
|
+
const dot = token.lastIndexOf(".");
|
|
3288
|
+
if (dot < 0) return null;
|
|
3289
|
+
const payload = token.slice(0, dot);
|
|
3290
|
+
const sig = token.slice(dot + 1);
|
|
3291
|
+
const expect = crypto.createHmac("sha256", secret).update(payload).digest("base64url");
|
|
3292
|
+
try {
|
|
3293
|
+
if (!crypto.timingSafeEqual(Buffer.from(sig), Buffer.from(expect))) return null;
|
|
3294
|
+
} catch { return null; }
|
|
3295
|
+
try {
|
|
3296
|
+
const data = JSON.parse(Buffer.from(payload, "base64url").toString());
|
|
3297
|
+
if (data.exp < Date.now()) return null;
|
|
3298
|
+
return data as T;
|
|
3299
|
+
} catch { return null; }
|
|
3300
|
+
},
|
|
3301
|
+
csrfToken(secret: string, sessionId: string): string {
|
|
3302
|
+
return crypto.createHmac("sha256", secret).update(sessionId).digest("hex");
|
|
3303
|
+
},
|
|
3304
|
+
verifyCsrf(token: string, secret: string, sessionId: string): boolean {
|
|
3305
|
+
try {
|
|
3306
|
+
return crypto.timingSafeEqual(Buffer.from(token), Buffer.from(this.csrfToken(secret, sessionId)));
|
|
3307
|
+
} catch { return false; }
|
|
3308
|
+
},
|
|
3309
|
+
};
|
|
3310
|
+
globalThis.__rosetackAuth = auth;
|
|
3311
|
+
|
|
3312
|
+
export async function $kv(key: string, compute: () => unknown | Promise<unknown>, ttlSeconds = 300): Promise<unknown> {
|
|
3313
|
+
const hit = kv.get(key);
|
|
3314
|
+
if (hit !== undefined) return hit;
|
|
3315
|
+
const v = await compute();
|
|
3316
|
+
if (v !== undefined) kv.set(key, v, ttlSeconds);
|
|
3317
|
+
return v;
|
|
3318
|
+
}
|
|
3319
|
+
export function isCachedRoute(pathname: string): boolean {
|
|
3320
|
+
return routeCaches.some((r) => matchRoute(r.pattern, pathname));
|
|
3321
|
+
}
|
|
3322
|
+
export function invalidatePath(pathname: string): number {
|
|
3323
|
+
let n = 0;
|
|
3324
|
+
for (const key of [...__dynCache.keys()]) {
|
|
3325
|
+
if (key.startsWith(pathname + '|')) { __dynCache.delete(key); n++; }
|
|
3326
|
+
}
|
|
3327
|
+
return n;
|
|
3328
|
+
}
|
|
3329
|
+
export function peekRenderCache(pathname: string, cookieHeader: string): ReturnType<typeof renderPage> | null {
|
|
3330
|
+
const cfg = routeCaches.find((r) => matchRoute(r.pattern, pathname));
|
|
3331
|
+
if (!cfg) return null;
|
|
3332
|
+
let h = 0x811c9dc5;
|
|
3333
|
+
const c = cookieHeader || '';
|
|
3334
|
+
for (let i = 0; i < c.length; i++) {
|
|
3335
|
+
h ^= c.charCodeAt(i);
|
|
3336
|
+
h = (h * 0x01000193) >>> 0;
|
|
3337
|
+
}
|
|
3338
|
+
const hit = __dynCache.get(pathname + '|' + h.toString(16));
|
|
3339
|
+
return hit && hit.expires > Date.now() ? hit.page : null;
|
|
3340
|
+
}
|
|
3341
|
+
export async function renderPageCached(pathname: string, cookieHeader: string): Promise<ReturnType<typeof renderPage>> {
|
|
3342
|
+
const cfg = routeCaches.find((r) => matchRoute(r.pattern, pathname));
|
|
3343
|
+
if (!cfg) return renderPage(pathname);
|
|
3344
|
+
let h = 0x811c9dc5;
|
|
3345
|
+
for (let i = 0; i < cookieHeader.length; i++) {
|
|
3346
|
+
h ^= cookieHeader.charCodeAt(i);
|
|
3347
|
+
h = (h * 0x01000193) >>> 0;
|
|
3348
|
+
}
|
|
3349
|
+
const key = pathname + '|' + h.toString(16);
|
|
3350
|
+
const hit = __dynCache.get(key);
|
|
3351
|
+
if (hit && hit.expires > Date.now()) {
|
|
3352
|
+
__dynCache.delete(key);
|
|
3353
|
+
__dynCache.set(key, hit);
|
|
3354
|
+
return hit.page;
|
|
3355
|
+
}
|
|
3356
|
+
// Stale-while-revalidate: an EXPIRED entry still answers instantly while one background render refreshes it - the TTL boundary never spikes.
|
|
3357
|
+
if (hit && !hit.refreshing) {
|
|
3358
|
+
hit.refreshing = true;
|
|
3359
|
+
renderPage(pathname).then((fresh: any) => {
|
|
3360
|
+
if (fresh.status === 200 && !fresh.redirect) {
|
|
3361
|
+
__dynCache.set(key, { page: fresh, expires: Date.now() + cfg.seconds * 1000 });
|
|
3362
|
+
} else {
|
|
3363
|
+
__dynCache.delete(key);
|
|
3364
|
+
}
|
|
3365
|
+
}).catch(() => { __dynCache.delete(key); });
|
|
3366
|
+
return hit.page;
|
|
3367
|
+
}
|
|
3368
|
+
const page = await renderPage(pathname);
|
|
3369
|
+
if (page.status === 200 && !page.redirect) {
|
|
3370
|
+
__dynCache.set(key, { page, expires: Date.now() + cfg.seconds * 1000 });
|
|
3371
|
+
if (__dynCache.size > 300) {
|
|
3372
|
+
__dynCache.delete(__dynCache.keys().next().value as string);
|
|
3373
|
+
}
|
|
3374
|
+
}
|
|
3375
|
+
return page;
|
|
3376
|
+
}
|
|
3377
|
+
|
|
3378
|
+
// Pages/_middleware.rose: a Web-standard request handler that runs before every render on the server (pages, POSTs, api calls alike).
|
|
1870
3379
|
export const middleware = ${middlewareIdx >= 0 ? "middlewareMod.handle ?? null" : "null"};
|
|
1871
3380
|
|
|
1872
|
-
// Routes whose DOCUMENTS ship without the client bundle (
|
|
1873
|
-
// decided by the compiler since #29): HTML + CSS only - no runtime, no
|
|
1874
|
-
// state script, zero JavaScript for whoever lands on them. The compiler
|
|
1875
|
-
// picks these automatically: a route whose whole chain needs nothing from
|
|
1876
|
-
// the client (no event wiring, no lifecycle, no action, no form) is a
|
|
1877
|
-
// content route. An exported "csr = true" forces the bundle back in; an
|
|
1878
|
-
// exported "csr = false" is the same decision, asserted. The route's render
|
|
1879
|
-
// function still rides in the client bundle, so a client-side navigation
|
|
1880
|
-
// from an interactive page paints it normally and a static deploy's SPA
|
|
1881
|
-
// fallback can render it too; only the document is JS-free.
|
|
1882
|
-
// isNoJs() lets the servers keep these routes on the buffered path: a
|
|
1883
|
-
// streamed no-JS document would carry the shell's default <title> (the
|
|
1884
|
-
// route head is applied client-side at boot, and there is no client).
|
|
3381
|
+
// Routes whose DOCUMENTS ship without the client bundle ( decided by the compiler since #29): HTML + CSS only - no runtime, no state script.
|
|
1885
3382
|
export const noJsRoutes = [
|
|
1886
3383
|
${pages.filter(({ i }) => routeNoJs(i)).map(({ info }) => `'${info.pattern}'`).join(",\n ")}
|
|
1887
3384
|
];
|
|
@@ -1890,21 +3387,12 @@ export function isNoJs(pathname) {
|
|
|
1890
3387
|
return noJsRoutes.some((pattern) => matchRoute(pattern, pathname));
|
|
1891
3388
|
}
|
|
1892
3389
|
|
|
1893
|
-
// P0-2 (bug report): routes that exported "buffer = true".
|
|
1894
|
-
// this BEFORE choosing a path: a streamed response commits its status and
|
|
1895
|
-
// headers before the body exists, so its onResponse hooks cannot see the
|
|
1896
|
-
// document and a render that throws mid-flight still answers 200. A buffered
|
|
1897
|
-
// route keeps every capability and gives up the early flush - the trade is
|
|
1898
|
-
// the route's to make, per route, not the framework's.
|
|
3390
|
+
// P0-2 (bug report): routes that exported "buffer = true".
|
|
1899
3391
|
export function isBuffered(pathname) {
|
|
1900
|
-
return routes.some((route) => route.buffer && matchRoute(route.pattern, pathname));
|
|
3392
|
+
return routes.some((route) => (route.buffer || route.signal) && matchRoute(route.pattern, pathname));
|
|
1901
3393
|
}
|
|
1902
3394
|
|
|
1903
|
-
|
|
1904
|
-
// map carries them into every response the servers write for it, merged
|
|
1905
|
-
// OVER the framework defaults (the strict CSP) - so an app can tighten or
|
|
1906
|
-
// relax the policy per route. Absent -> null, and the servers keep sending
|
|
1907
|
-
// the defaults alone.
|
|
3395
|
+
|
|
1908
3396
|
export const routeHeaders = [
|
|
1909
3397
|
${pages.filter(({ i }) => compiled[i].headers).map(({ info, i }) => `{ pattern: '${info.pattern}', headers: ${JSON.stringify(compiled[i].headers)} }`).join(",\n ")}
|
|
1910
3398
|
];
|
|
@@ -1914,14 +3402,7 @@ export function headersFor(pathname) {
|
|
|
1914
3402
|
return hit ? hit.headers : null;
|
|
1915
3403
|
}
|
|
1916
3404
|
|
|
1917
|
-
|
|
1918
|
-
// ). The servers ask this BEFORE writing a document: when it is true they
|
|
1919
|
-
// mint one random nonce per response, put it in the CSP header ('nonce-...'
|
|
1920
|
-
// plus 'strict-dynamic', so the document's own code may load more code) and
|
|
1921
|
-
// stamp the same value on the script tag. The default policy stays a hash -
|
|
1922
|
-
// cspNonceRoutes is empty for an app that never asks, so the fast path is
|
|
1923
|
-
// unchanged. The Go binary never sees this: these routes are dynamic, so it
|
|
1924
|
-
// has no baked file for them to serve.
|
|
3405
|
+
|
|
1925
3406
|
export const cspNonceRoutes = [
|
|
1926
3407
|
${pages.filter(({ i }) => compiled[i].cspNonce).map(({ info }) => `'${info.routePath}'`).join(",\n ")}
|
|
1927
3408
|
];
|
|
@@ -1930,9 +3411,7 @@ export function cspNonce(pathname) {
|
|
|
1930
3411
|
return cspNonceRoutes.some((pattern) => matchRoute(pattern, pathname));
|
|
1931
3412
|
}
|
|
1932
3413
|
|
|
1933
|
-
// A Web-standard Request from whatever the host provides: the edge adapter
|
|
1934
|
-
// passes one already; the Node server passes its IncomingMessage (plus the
|
|
1935
|
-
// already-parsed FormData for POSTs, so middleware can read form fields).
|
|
3414
|
+
// A Web-standard Request from whatever the host provides: the edge adapter passes one already; the Node server passes its IncomingMessage (plus).
|
|
1936
3415
|
function toWebRequest(raw, form) {
|
|
1937
3416
|
if (raw instanceof Request) return raw;
|
|
1938
3417
|
const init = { method: raw.method || 'GET', headers: new Headers(raw.headers || {}) };
|
|
@@ -1940,13 +3419,7 @@ function toWebRequest(raw, form) {
|
|
|
1940
3419
|
return new Request('http://' + (raw.headers?.host || 'localhost') + (raw.url || '/'), init);
|
|
1941
3420
|
}
|
|
1942
3421
|
|
|
1943
|
-
|
|
1944
|
-
// its short-circuit Response, or null to continue. The servers call this
|
|
1945
|
-
// EXACTLY ONCE per request, before anything else: it resets the per-request
|
|
1946
|
-
// context bag and the middleware fills it via getContext(), which $data,
|
|
1947
|
-
// server actions and api handlers then read while rendering. rawReq: the
|
|
1948
|
-
// host's request (Node IncomingMessage or a Web-standard Request); form:
|
|
1949
|
-
// the already-parsed FormData of a POST.
|
|
3422
|
+
|
|
1950
3423
|
export async function runMiddleware(rawReq, form) {
|
|
1951
3424
|
resetRequestContext();
|
|
1952
3425
|
if (!middleware || !rawReq) return null;
|
|
@@ -1958,10 +3431,7 @@ const routes = [
|
|
|
1958
3431
|
${serverRoutes}
|
|
1959
3432
|
];
|
|
1960
3433
|
|
|
1961
|
-
// API routes (pages/api/*.rose): pattern -> HTTP-method handlers. They never
|
|
1962
|
-
// render HTML and never reach the client bundle. The middleware ran before
|
|
1963
|
-
// this (the servers call runMiddleware() first), so handlers can read
|
|
1964
|
-
// getContext() for auth without re-running anything.
|
|
3434
|
+
// API routes (pages/api/*.rose): pattern -> HTTP-method handlers. They never render HTML and never reach the client bundle.
|
|
1965
3435
|
const apiRoutes = [
|
|
1966
3436
|
${apiRoutes.map(({ info, i }) => {
|
|
1967
3437
|
const handlers = (compiled[i].apiMethods ?? []).map((n) => `${n}: ${n}_${i}`).join(", ");
|
|
@@ -1969,19 +3439,40 @@ const apiRoutes = [
|
|
|
1969
3439
|
}).join(",\n ")}
|
|
1970
3440
|
];
|
|
1971
3441
|
|
|
1972
|
-
// pages
|
|
1973
|
-
|
|
3442
|
+
// Not-found pages, deepest segment first: the root 404.rose ('/') and any
|
|
3443
|
+
// pages/<seg>/_notfound.rose, each already composed with its layout chain.
|
|
3444
|
+
// notFoundFor picks the nearest one up the path - an /admin miss answers
|
|
3445
|
+
// the admin 404, a public miss the site's - and notFoundPage is the whole
|
|
3446
|
+
// answer (real 404 status, or the built-in plain 404 when the app has none).
|
|
3447
|
+
const notFoundRoutes = ${notFoundTable};
|
|
3448
|
+
const notFoundFor = (pathname) => {
|
|
3449
|
+
for (const [prefix, render] of notFoundRoutes) {
|
|
3450
|
+
if (prefix === '/' || pathname === prefix || pathname.startsWith(prefix + '/')) return render;
|
|
3451
|
+
}
|
|
3452
|
+
return null;
|
|
3453
|
+
};
|
|
3454
|
+
|
|
3455
|
+
const notFoundFlags = (pathname) => {
|
|
3456
|
+
for (const [prefix, render, flags] of notFoundRoutes) {
|
|
3457
|
+
if (prefix === '/' || pathname === prefix || pathname.startsWith(prefix + '/')) return flags || null;
|
|
3458
|
+
}
|
|
3459
|
+
return null;
|
|
3460
|
+
};
|
|
3461
|
+
const notFoundPage = async (pathname) => {
|
|
3462
|
+
const nf = notFoundFor(pathname);
|
|
3463
|
+
if (nf) {
|
|
3464
|
+
const page = await renderFallback(pathname, nf);
|
|
3465
|
+
// __notFound stamps the document so the client boot paints THIS route instead of re-rendering the matched one: a catch-all whose resolver threw.
|
|
3466
|
+
return { ...page, ...(notFoundFlags(pathname) || {}), status: 404, state: JSON.stringify({ __notFound: true, ...JSON.parse(page.state) }) };
|
|
3467
|
+
}
|
|
3468
|
+
return { html: '<h1>404</h1><p>Page not found</p>', state: JSON.stringify({ __route: pathname, __notFound: true }), head: [], status: 404, ...docAttrs(pathname) };
|
|
3469
|
+
};
|
|
3470
|
+
|
|
1974
3471
|
|
|
1975
|
-
// pages/500.rose (with its layouts) or null -> built-in plain 500: a route
|
|
1976
3472
|
// whose render throws degrades to this instead of failing the response.
|
|
1977
3473
|
const errorPage = ${errorRender};
|
|
1978
3474
|
|
|
1979
|
-
|
|
1980
|
-
// of its [lang] segment (the default when there is none, or when the segment
|
|
1981
|
-
// names no dictionary: that request 404s in the default language) and the
|
|
1982
|
-
// reading direction that locale implies. The buffered render returns the same
|
|
1983
|
-
// pair; the streaming path needs it BEFORE the shell flushes, which is why
|
|
1984
|
-
// the servers ask for it by pathname.
|
|
3475
|
+
|
|
1985
3476
|
export function docAttrs(pathname) {
|
|
1986
3477
|
for (const route of routes) {
|
|
1987
3478
|
if (!matchRoute(route.pattern, pathname)) continue;
|
|
@@ -1991,21 +3482,42 @@ export function docAttrs(pathname) {
|
|
|
1991
3482
|
const lang = pathname.split('/')[langIdx];
|
|
1992
3483
|
if (isLocale(lang)) return { lang, dir: localeDir(lang) };
|
|
1993
3484
|
}
|
|
1994
|
-
break;
|
|
3485
|
+
break;
|
|
1995
3486
|
}
|
|
1996
3487
|
return { lang: defaultLocale, dir: localeDir(defaultLocale) };
|
|
1997
3488
|
}
|
|
1998
3489
|
|
|
1999
3490
|
// Paint a fallback page (404/500) and serialize its state.
|
|
2000
3491
|
async function renderFallback(pathname, render) {
|
|
2001
|
-
|
|
3492
|
+
// Split mode: the not-found entry's render is a loader object \u2014 resolve it through getRender (which memoizes the composed function) exactly like.
|
|
3493
|
+
let fn = render;
|
|
3494
|
+
if (typeof fn !== 'function' && fn && typeof fn.load === 'function') {
|
|
3495
|
+
|
|
3496
|
+
// { render } once the route's chunk graph is loaded
|
|
3497
|
+
fn = (await fn.load()).render;
|
|
3498
|
+
}
|
|
3499
|
+
const { html, head } = extractHead(await fn([], ''));
|
|
2002
3500
|
const state = JSON.stringify({ __route: pathname, ...JSON.parse(serializeState()) });
|
|
2003
3501
|
return { html, state, head, ...docAttrs(pathname) };
|
|
2004
3502
|
}
|
|
2005
3503
|
|
|
2006
3504
|
export function matchRoute(pattern, pathname) {
|
|
3505
|
+
// Q0 (bug report): one canonical URL per route.
|
|
3506
|
+
pathname = pathname.replace(/\\/+$/, '') || '/';
|
|
2007
3507
|
const patternParts = pattern.split('/');
|
|
2008
3508
|
const pathParts = pathname.split('/');
|
|
3509
|
+
|
|
3510
|
+
const last = patternParts[patternParts.length - 1];
|
|
3511
|
+
if (last && (last.startsWith('*') || last.startsWith('**'))) {
|
|
3512
|
+
const fixed = patternParts.slice(0, -1);
|
|
3513
|
+
if (pathParts.length < fixed.length) return false;
|
|
3514
|
+
if (last.startsWith('*') && !last.startsWith('**') && pathParts.length === fixed.length) return false;
|
|
3515
|
+
for (let i = 0; i < fixed.length; i++) {
|
|
3516
|
+
if (fixed[i].startsWith(':')) continue;
|
|
3517
|
+
if (fixed[i] !== pathParts[i]) return false;
|
|
3518
|
+
}
|
|
3519
|
+
return true;
|
|
3520
|
+
}
|
|
2009
3521
|
if (patternParts.length !== pathParts.length) return false;
|
|
2010
3522
|
for (let i = 0; i < patternParts.length; i++) {
|
|
2011
3523
|
if (patternParts[i].startsWith(':')) continue;
|
|
@@ -2014,13 +3526,7 @@ export function matchRoute(pattern, pathname) {
|
|
|
2014
3526
|
return true;
|
|
2015
3527
|
}
|
|
2016
3528
|
|
|
2017
|
-
// Head blocks (one per component in the route chain) are pulled out of the
|
|
2018
|
-
// page html: the shell injects them into <head>, and the client re-applies
|
|
2019
|
-
// them on navigation. Document order is page-first, so the shell's keyed
|
|
2020
|
-
// merge lets a page override its layouts. The EMPTY marker pair stays in the
|
|
2021
|
-
// body so the client's wire() still finds the block: at boot it adopts the
|
|
2022
|
-
// shell-injected elements in place (marked with the same keys, so no
|
|
2023
|
-
// duplicates) and keeps the head reactive.
|
|
3529
|
+
// Head blocks (one per component in the route chain) are pulled out of the page html: the shell injects them into <head>.
|
|
2024
3530
|
function extractHead(rendered) {
|
|
2025
3531
|
const head = [];
|
|
2026
3532
|
const html = rendered.replace(/<!--\u27E6h:(\\d+)\u27E7-->([\\s\\S]*?)<!--\u27E6\\/h:\\1\u27E7-->/g, (_, id, content) => {
|
|
@@ -2030,18 +3536,7 @@ function extractHead(rendered) {
|
|
|
2030
3536
|
return { html, head };
|
|
2031
3537
|
}
|
|
2032
3538
|
|
|
2033
|
-
//
|
|
2034
|
-
// selected server action runs first and returns a state patch (e.g.
|
|
2035
|
-
// { guests: [...] }); seeding those keys BEFORE the render makes state()
|
|
2036
|
-
// adopt them, so the response is the page as it looks AFTER the action -
|
|
2037
|
-
// with or without JS. A __action field picks the action by name (default
|
|
2038
|
-
// 'action', the conventional <form method="POST"> target); a click handler
|
|
2039
|
-
// bound to an action ($action('like')) sends the same field.
|
|
2040
|
-
// A route whose render throws degrades to pages/500.rose (status 500) - or
|
|
2041
|
-
// the built-in plain 500 - instead of failing the whole response.
|
|
2042
|
-
// The middleware does NOT run here: the servers run it once per request via
|
|
2043
|
-
// runMiddleware() (which also seeds the request context), so a page render
|
|
2044
|
-
// never re-runs it.
|
|
3539
|
+
// Form: the submitted FormData of a progressive-enhancement POST.
|
|
2045
3540
|
export async function renderPage(pathname, form) {
|
|
2046
3541
|
clearRequestState();
|
|
2047
3542
|
for (const route of routes) {
|
|
@@ -2049,31 +3544,21 @@ export async function renderPage(pathname, form) {
|
|
|
2049
3544
|
const patternParts = route.pattern.split('/');
|
|
2050
3545
|
const pathParts = pathname.split('/');
|
|
2051
3546
|
for (let i = 0; i < patternParts.length; i++) {
|
|
2052
|
-
|
|
2053
|
-
|
|
2054
|
-
|
|
3547
|
+
const seg = patternParts[i];
|
|
3548
|
+
if (seg.startsWith(':')) setState(seg.slice(1), pathParts[i]);
|
|
3549
|
+
|
|
3550
|
+
|
|
3551
|
+
else if (seg.startsWith('*')) setState(seg.replace(/^\\*+/, ''), pathParts.slice(i));
|
|
2055
3552
|
}
|
|
2056
|
-
//
|
|
2057
|
-
// 404 - the URL is the contract, and rendering the page with fallback
|
|
2058
|
-
// strings would serve duplicate content under a bogus language
|
|
3553
|
+
// I18n: a [lang] segment naming no dictionary is a 404 - the URL is the contract.
|
|
2059
3554
|
const langIdx = patternParts.indexOf(':lang');
|
|
2060
3555
|
if (langIdx >= 0 && !isLocale(pathParts[langIdx])) {
|
|
2061
|
-
|
|
2062
|
-
return { html: '<h1>404</h1><p>Page not found</p>', state: '{}', head: [], status: 404, ...docAttrs(pathname) };
|
|
3556
|
+
return await notFoundPage(pathname);
|
|
2063
3557
|
}
|
|
2064
|
-
|
|
2065
|
-
|
|
3558
|
+
|
|
3559
|
+
|
|
2066
3560
|
const docLang = langIdx >= 0 ? pathParts[langIdx] : defaultLocale;
|
|
2067
|
-
// The action dispatch. The page's guard (exported
|
|
2068
|
-
// beforeAction) runs FIRST and vetoes with an ActionError - the
|
|
2069
|
-
// action-level permission check. Then the selected action runs and its
|
|
2070
|
-
// return value seeds this render's state, per key, so an incremental
|
|
2071
|
-
// patch ($append and friends) grows a large list by one row instead of
|
|
2072
|
-
// re-sending the whole thing. An ActionError from either half is a
|
|
2073
|
-
// BUSINESS failure: it is seeded as the 'actionError' state, the
|
|
2074
|
-
// response carries its status, and the page renders with the failure
|
|
2075
|
-
// visible (a {#boundary} around the action's widget contains it).
|
|
2076
|
-
// Anything else is a bug and keeps going to the 500 page.
|
|
3561
|
+
// The action dispatch. The page's guard (exported beforeAction) runs FIRST and vetoes with an ActionError - the action-level permission check.
|
|
2077
3562
|
let actionStatus = 0;
|
|
2078
3563
|
if (form && route.actions) {
|
|
2079
3564
|
const actionName = form.get('__action') || 'action';
|
|
@@ -2085,9 +3570,7 @@ export async function renderPage(pathname, form) {
|
|
|
2085
3570
|
if (patch && typeof patch === 'object') {
|
|
2086
3571
|
for (const key of Object.keys(patch)) {
|
|
2087
3572
|
const v = patch[key];
|
|
2088
|
-
// An incremental patch is RECORDED, not applied: the render's
|
|
2089
|
-
// own state declarations apply it, so the delta is relative to
|
|
2090
|
-
// the value the page was going to render anyway.
|
|
3573
|
+
// An incremental patch is RECORDED, not applied: the render's own state declarations apply.
|
|
2091
3574
|
if (v instanceof StateDelta) setStateDelta(key, v);
|
|
2092
3575
|
else setState(key, v);
|
|
2093
3576
|
}
|
|
@@ -2096,6 +3579,11 @@ export async function renderPage(pathname, form) {
|
|
|
2096
3579
|
if (err instanceof ActionError) {
|
|
2097
3580
|
setState('actionError', { action: actionName, message: err.message, code: err.code, field: err.field });
|
|
2098
3581
|
actionStatus = err.code;
|
|
3582
|
+
} else if (err && err.__rosetack === 'redirect') {
|
|
3583
|
+
|
|
3584
|
+
return { redirect: err.path, status: err.status ?? 303, ...docAttrs(pathname) };
|
|
3585
|
+
} else if (err && err.__rosetack === 'notFound') {
|
|
3586
|
+
return await notFoundPage(pathname);
|
|
2099
3587
|
} else {
|
|
2100
3588
|
throw err;
|
|
2101
3589
|
}
|
|
@@ -2106,32 +3594,46 @@ export async function renderPage(pathname, form) {
|
|
|
2106
3594
|
try {
|
|
2107
3595
|
rendered = extractHead(await route.render([], ''));
|
|
2108
3596
|
} catch (err) {
|
|
3597
|
+
// The control-flow pair: redirect() and notFound() are THROWN from inside the render (a $data body resolving a slug that no longer exists).
|
|
3598
|
+
const signal = err && err.__rosetack;
|
|
3599
|
+
if (signal === 'redirect') {
|
|
3600
|
+
return { redirect: err.path, status: err.status ?? 307, ...docAttrs(pathname) };
|
|
3601
|
+
}
|
|
3602
|
+
if (signal === 'notFound') {
|
|
3603
|
+
return await notFoundPage(pathname);
|
|
3604
|
+
}
|
|
2109
3605
|
console.error('rosetack: render failed for', pathname, err instanceof Error ? err.message : err);
|
|
2110
|
-
|
|
2111
|
-
|
|
3606
|
+
// F10: in dev the response body carries the real error \u2014 message, file:line and the fix hint.
|
|
3607
|
+
let devDetail = '';
|
|
3608
|
+
if (process.env.rosetack_DEV === '1' && err) {
|
|
3609
|
+
const msg = esc(err instanceof Error ? err.message : String(err));
|
|
3610
|
+
const file = esc(String(err.file || ''));
|
|
3611
|
+
const line = err.line != null ? esc(String(err.line)) : '';
|
|
3612
|
+
const hint = esc(String(err.hint || ''));
|
|
3613
|
+
const stack = esc(err instanceof Error ? (err.stack || '').split('\\n').slice(1, 7).join('\\n') : '');
|
|
3614
|
+
devDetail = '<div style="margin:24px auto;max-width:860px;font:13px/1.6 ui-monospace,monospace;background:#1b1b1f;color:#e6e6ea;border:1px solid #3a3a42;border-radius:10px;padding:20px 24px;text-align:left;white-space:pre-wrap;word-break:break-word">'
|
|
3615
|
+
+ '<div style="font:600 15px/1.4 system-ui,sans-serif;color:#ff8b8b">Render failed: ' + esc(pathname) + '</div>'
|
|
3616
|
+
+ '<div style="margin:10px 0 0;color:#ffd479">' + msg + '</div>'
|
|
3617
|
+
+ (file ? '<div style="margin:6px 0 0;color:#9ad1ff">' + file + (line ? ':' + line : '') + '</div>' : '')
|
|
3618
|
+
+ (hint ? '<div style="margin:10px 0 0;color:#9fe8b0">Fix: ' + hint + '</div>' : '')
|
|
3619
|
+
+ (stack ? '<pre style="margin:12px 0 0;color:#8f8f9a">' + stack + '</pre>' : '')
|
|
3620
|
+
+ '</div>';
|
|
3621
|
+
}
|
|
3622
|
+
if (errorPage) {
|
|
3623
|
+
const fb = await renderFallback(pathname, errorPage);
|
|
3624
|
+
return { ...fb, html: fb.html + devDetail, status: 500 };
|
|
3625
|
+
}
|
|
3626
|
+
return { html: '<h1>500</h1><p>Something went wrong rendering this page.</p>' + devDetail, state: '{}', head: [], status: 500, ...docAttrs(pathname) };
|
|
2112
3627
|
}
|
|
2113
3628
|
// __route tells the bootstrap which route this document was rendered for.
|
|
2114
|
-
// A static-file server may serve another route's document (SPA fallback);
|
|
2115
|
-
// the bootstrap then client-renders instead of adopting mismatched DOM.
|
|
2116
3629
|
const state = JSON.stringify({ __route: pathname, ...JSON.parse(serializeState()) });
|
|
2117
|
-
//
|
|
2118
|
-
|
|
2119
|
-
// asserted csr = false) - the document ships no runtime, no state
|
|
2120
|
-
// script, zero JavaScript. Every other route keeps the bundle. The
|
|
2121
|
-
// caller passes this straight to the shell as js.
|
|
2122
|
-
// Status is the failed action's code when one failed - the page
|
|
2123
|
-
// rendered fine, so the body is the page with the failure visible, and
|
|
2124
|
-
// the status says what happened (a 403 from the guard, a 422 from a
|
|
2125
|
-
// validation action). 200 otherwise.
|
|
2126
|
-
// Lang/dir are the document's <html> attributes - the locale
|
|
2127
|
-
// this route rendered in, and its reading direction.
|
|
2128
|
-
return { html: rendered.html, state, head: rendered.head, status: actionStatus || 200, csr: route.csr !== false, lang: docLang, dir: localeDir(docLang) };
|
|
3630
|
+
// Csr ( auto since #29): false when the compiler found nothing in the route's chain that needs the client (or the route asserted csr = false) .
|
|
3631
|
+
return { html: rendered.html, state, head: rendered.head, status: actionStatus || 200, csr: route.csr !== false, shell: route.shell !== false, lang: docLang, dir: localeDir(docLang) };
|
|
2129
3632
|
}
|
|
2130
3633
|
}
|
|
2131
|
-
|
|
2132
|
-
|
|
2133
|
-
|
|
2134
|
-
return { html: '<h1>404</h1><p>Page not found</p>', state: '{}', head: [], status: 404, ...docAttrs(pathname) };
|
|
3634
|
+
|
|
3635
|
+
|
|
3636
|
+
return await notFoundPage(pathname);
|
|
2135
3637
|
}
|
|
2136
3638
|
|
|
2137
3639
|
// Would renderPageStream handle this path? (matched route = stream, anything
|
|
@@ -2139,21 +3641,20 @@ export async function renderPage(pathname, form) {
|
|
|
2139
3641
|
export function canStream(pathname) {
|
|
2140
3642
|
return routes.some((route) => {
|
|
2141
3643
|
if (!matchRoute(route.pattern, pathname)) return false;
|
|
2142
|
-
//
|
|
2143
|
-
// streamed response cannot change its status - so it takes the buffered
|
|
2144
|
-
// path (renderPage returns the real 404), never the streaming one
|
|
3644
|
+
// I18n: an unknown locale must answer 404, and a streamed response cannot change its status - so it takes the buffered path (renderPage returns).
|
|
2145
3645
|
const langIdx = route.pattern.split('/').indexOf(':lang');
|
|
2146
3646
|
return langIdx < 0 || isLocale(pathname.split('/')[langIdx]);
|
|
2147
3647
|
});
|
|
2148
3648
|
}
|
|
2149
3649
|
|
|
2150
|
-
|
|
2151
|
-
|
|
2152
|
-
|
|
2153
|
-
|
|
2154
|
-
|
|
2155
|
-
|
|
2156
|
-
|
|
3650
|
+
|
|
3651
|
+
export function shellOff(pathname) {
|
|
3652
|
+
return routes.some(
|
|
3653
|
+
(route) => route.shell === false && matchRoute(route.pattern, pathname),
|
|
3654
|
+
);
|
|
3655
|
+
}
|
|
3656
|
+
|
|
3657
|
+
// === API routes === The /api namespace answers JSON, never HTML: an API client that hits an unknown path must not receive the SPA shell.
|
|
2157
3658
|
export function isApi(pathname) {
|
|
2158
3659
|
return pathname === '/api' || pathname.startsWith('/api/');
|
|
2159
3660
|
}
|
|
@@ -2177,7 +3678,25 @@ export async function handleApi(method, pathname, request) {
|
|
|
2177
3678
|
headers: { 'content-type': 'application/json', allow: Object.keys(route.handlers).join(', ') },
|
|
2178
3679
|
});
|
|
2179
3680
|
}
|
|
2180
|
-
|
|
3681
|
+
try {
|
|
3682
|
+
return toResponse(await fn(request));
|
|
3683
|
+
} catch (err) {
|
|
3684
|
+
|
|
3685
|
+
const signal = err && err.__rosetack;
|
|
3686
|
+
if (signal === 'redirect') {
|
|
3687
|
+
return new Response(JSON.stringify({ error: 'redirect', location: err.path }), {
|
|
3688
|
+
status: err.status ?? 307,
|
|
3689
|
+
headers: { 'content-type': 'application/json', location: err.path },
|
|
3690
|
+
});
|
|
3691
|
+
}
|
|
3692
|
+
if (signal === 'notFound') {
|
|
3693
|
+
return new Response(JSON.stringify({ error: 'not found' }), {
|
|
3694
|
+
status: 404,
|
|
3695
|
+
headers: { 'content-type': 'application/json' },
|
|
3696
|
+
});
|
|
3697
|
+
}
|
|
3698
|
+
throw err;
|
|
3699
|
+
}
|
|
2181
3700
|
}
|
|
2182
3701
|
}
|
|
2183
3702
|
return new Response(JSON.stringify({ error: 'not found' }), {
|
|
@@ -2186,18 +3705,7 @@ export async function handleApi(method, pathname, request) {
|
|
|
2186
3705
|
});
|
|
2187
3706
|
}
|
|
2188
3707
|
|
|
2189
|
-
// === Streaming SSR ===
|
|
2190
|
-
// The static shell (doctype, <head>, body + container open) flushes BEFORE
|
|
2191
|
-
// the - possibly slow - render completes: the first byte leaves in
|
|
2192
|
-
// microseconds instead of after every $data resolves. The route HTML, the
|
|
2193
|
-
// state script, and the inlined bundle follow as later chunks of one chunked
|
|
2194
|
-
// response - still exactly one request.
|
|
2195
|
-
// The route's <head> tags are NOT in the streamed document: the client
|
|
2196
|
-
// applies them at boot from the body's head markers, so JS users see the
|
|
2197
|
-
// correct head immediately; no-JS consumers of streamed responses get the
|
|
2198
|
-
// static shell head (prerendered files stay complete documents).
|
|
2199
|
-
// Returns 200 (matched; a render throw degrades to the error-page body) or
|
|
2200
|
-
// 404 (unmatched - nothing written, so the caller can still buffer).
|
|
3708
|
+
// === Streaming SSR === The static shell (doctype, <head>, body + container open) flushes BEFORE the - possibly slow - render completes: the first byte.
|
|
2201
3709
|
export async function renderPageStream(pathname, write, shellOpen, clientTag) {
|
|
2202
3710
|
clearRequestState();
|
|
2203
3711
|
for (const route of routes) {
|
|
@@ -2205,9 +3713,11 @@ export async function renderPageStream(pathname, write, shellOpen, clientTag) {
|
|
|
2205
3713
|
const patternParts = route.pattern.split('/');
|
|
2206
3714
|
const pathParts = pathname.split('/');
|
|
2207
3715
|
for (let i = 0; i < patternParts.length; i++) {
|
|
2208
|
-
|
|
2209
|
-
|
|
2210
|
-
|
|
3716
|
+
const seg = patternParts[i];
|
|
3717
|
+
if (seg.startsWith(':')) setState(seg.slice(1), pathParts[i]);
|
|
3718
|
+
|
|
3719
|
+
|
|
3720
|
+
else if (seg.startsWith('*')) setState(seg.replace(/^\\*+/, ''), pathParts.slice(i));
|
|
2211
3721
|
}
|
|
2212
3722
|
// i18n: an unknown locale must 404 BEFORE the shell flushes - a
|
|
2213
3723
|
// streamed response cannot change its status afterwards
|
|
@@ -2218,37 +3728,103 @@ export async function renderPageStream(pathname, write, shellOpen, clientTag) {
|
|
|
2218
3728
|
try {
|
|
2219
3729
|
html = extractHead(await route.render([], '')).html;
|
|
2220
3730
|
} catch (err) {
|
|
2221
|
-
|
|
2222
|
-
// (the status stays 200 - a real 500 needs the buffered path, which
|
|
2223
|
-
// the server picks for routes known-broken at build time)
|
|
3731
|
+
|
|
2224
3732
|
console.error('rosetack: render failed for', pathname, err instanceof Error ? err.message : err);
|
|
2225
|
-
|
|
3733
|
+
// F10: dev carries the real error in the body here too \u2014 the shell
|
|
3734
|
+
// is out, so the detail rides after the error page body.
|
|
3735
|
+
let devDetail = '';
|
|
3736
|
+
if (process.env.rosetack_DEV === '1' && err) {
|
|
3737
|
+
const msg = esc(err instanceof Error ? err.message : String(err));
|
|
3738
|
+
const file = esc(String(err.file || ''));
|
|
3739
|
+
const line = err.line != null ? esc(String(err.line)) : '';
|
|
3740
|
+
const hint = esc(String(err.hint || ''));
|
|
3741
|
+
const stack = esc(err instanceof Error ? (err.stack || '').split('\\n').slice(1, 7).join('\\n') : '');
|
|
3742
|
+
devDetail = '<div style="margin:24px auto;max-width:860px;font:13px/1.6 ui-monospace,monospace;background:#1b1b1f;color:#e6e6ea;border:1px solid #3a3a42;border-radius:10px;padding:20px 24px;text-align:left;white-space:pre-wrap;word-break:break-word">'
|
|
3743
|
+
+ '<div style="font:600 15px/1.4 system-ui,sans-serif;color:#ff8b8b">Render failed: ' + esc(pathname) + '</div>'
|
|
3744
|
+
+ '<div style="margin:10px 0 0;color:#ffd479">' + msg + '</div>'
|
|
3745
|
+
+ (file ? '<div style="margin:6px 0 0;color:#9ad1ff">' + file + (line ? ':' + line : '') + '</div>' : '')
|
|
3746
|
+
+ (hint ? '<div style="margin:10px 0 0;color:#9fe8b0">Fix: ' + hint + '</div>' : '')
|
|
3747
|
+
+ (stack ? '<pre style="margin:12px 0 0;color:#8f8f9a">' + stack + '</pre>' : '')
|
|
3748
|
+
+ '</div>';
|
|
3749
|
+
}
|
|
3750
|
+
html = errorPage ? extractHead(await errorPage([], '')).html + devDetail : '<h1>500</h1><p>Something went wrong rendering this page.</p>' + devDetail;
|
|
2226
3751
|
}
|
|
2227
3752
|
write(html);
|
|
2228
|
-
//
|
|
2229
|
-
// ends here - no state script, no inlined bundle. (The servers keep
|
|
2230
|
-
// these routes off the streaming path so their <head> is complete;
|
|
2231
|
-
// this is the correctness floor if one streams anyway.)
|
|
3753
|
+
// Csr: false ( auto since #29): a no-JS route's document ends here - no state script, no inlined bundle.
|
|
2232
3754
|
if (route.csr === false) {
|
|
2233
3755
|
write('</div>\\n</body>\\n</html>');
|
|
2234
3756
|
return 200;
|
|
2235
3757
|
}
|
|
2236
3758
|
const state = JSON.stringify({ __route: pathname, ...JSON.parse(serializeState()) });
|
|
2237
|
-
|
|
3759
|
+
// P1-6 (bug report): the JSON data block is embedded in the document.
|
|
3760
|
+
const stateSafe = state.replace(/</g, '\\\\u003c');
|
|
3761
|
+
write('</div>\\n <script type="application/json" id="__rosetack_state">' + stateSafe + '</script>\\n ' + clientTag + '\\n</body>\\n</html>');
|
|
2238
3762
|
return 200;
|
|
2239
3763
|
}
|
|
2240
3764
|
}
|
|
2241
3765
|
return 404;
|
|
2242
3766
|
}
|
|
2243
3767
|
`;
|
|
2244
|
-
|
|
3768
|
+
try {
|
|
3769
|
+
const patterns = [...pages, ...apiRoutes].map(({ info }) => info.pattern);
|
|
3770
|
+
const uniq = [...new Set(patterns)].sort();
|
|
3771
|
+
const lit = uniq.map((p) => JSON.stringify(p)).join(" | ") || "'/'";
|
|
3772
|
+
const paramsOf = (pattern) => (pattern.match(/:[\w]+|\*\*[\w]+|\*[\w]+/g) ?? []).map((m) => m.replace(/^[*:]+/, ""));
|
|
3773
|
+
const paramSig = uniq.map((p) => {
|
|
3774
|
+
const ps = paramsOf(p);
|
|
3775
|
+
if (!ps.length) return "";
|
|
3776
|
+
return " " + JSON.stringify(p) + ": { " + ps.map((n) => n + ": string | number").join("; ") + " };\n";
|
|
3777
|
+
}).join("");
|
|
3778
|
+
const outDirTs = path2.join(root, "src", ".rosetack");
|
|
3779
|
+
await fs3.promises.mkdir(outDirTs, { recursive: true });
|
|
3780
|
+
const srcLines = [
|
|
3781
|
+
"// GENERATED by rosetack build - do not edit.",
|
|
3782
|
+
"export type RoutePath = " + lit + ";",
|
|
3783
|
+
"export const routePatterns = " + JSON.stringify(uniq) + " as const;",
|
|
3784
|
+
"export type RouteParams = {",
|
|
3785
|
+
paramSig,
|
|
3786
|
+
"};",
|
|
3787
|
+
"/** Build a URL from a route pattern and its params. */",
|
|
3788
|
+
"export function url(",
|
|
3789
|
+
" path: RoutePath,",
|
|
3790
|
+
" params: RouteParams[keyof RouteParams] = {} as never,",
|
|
3791
|
+
"): string {",
|
|
3792
|
+
" let out = path as string;",
|
|
3793
|
+
" for (const [k, v] of Object.entries(params as Record<string, string | number>)) {",
|
|
3794
|
+
" out = out.replace(new RegExp('[:*]+' + k, 'g'), String(v));",
|
|
3795
|
+
" }",
|
|
3796
|
+
" return out;",
|
|
3797
|
+
"}"
|
|
3798
|
+
].join("\n") + "\n";
|
|
3799
|
+
await fs3.promises.writeFile(path2.join(outDirTs, "routes.ts"), srcLines);
|
|
3800
|
+
} catch {
|
|
3801
|
+
}
|
|
3802
|
+
await fs3.promises.writeFile(path2.join(buildDir, "server-entry.js"), serverEntry);
|
|
2245
3803
|
await esbuild.build({
|
|
2246
|
-
entryPoints: [
|
|
3804
|
+
entryPoints: [path2.join(buildDir, "server-entry.js")],
|
|
3805
|
+
bundle: true,
|
|
3806
|
+
outfile: path2.join(outDir, "server.js"),
|
|
3807
|
+
format: "esm",
|
|
3808
|
+
platform: "node",
|
|
3809
|
+
write: true,
|
|
3810
|
+
...TS_LOADER
|
|
3811
|
+
});
|
|
3812
|
+
await esbuild.build({
|
|
3813
|
+
entryPoints: [(() => {
|
|
3814
|
+
const here = path2.dirname(fileURLToPath(import.meta.url));
|
|
3815
|
+
for (const cand of [path2.join(here, "..", "cli", "prod-server.ts"), path2.join(here, "..", "src", "cli", "prod-server.ts")]) {
|
|
3816
|
+
if (fs3.existsSync(cand)) return cand;
|
|
3817
|
+
}
|
|
3818
|
+
return path2.join(here, "..", "cli", "prod-server.ts");
|
|
3819
|
+
})()],
|
|
2247
3820
|
bundle: true,
|
|
2248
|
-
outfile:
|
|
3821
|
+
outfile: path2.join(outDir, "prod.mjs"),
|
|
2249
3822
|
format: "esm",
|
|
2250
3823
|
platform: "node",
|
|
2251
3824
|
write: true,
|
|
3825
|
+
banner: {
|
|
3826
|
+
js: "import { createRequire } from 'node:module'; import { fileURLToPath as __f2p } from 'node:url'; import { dirname as __dn } from 'node:path'; const require = createRequire(import.meta.url); const __filename = __f2p(import.meta.url); const __dirname = __dn(__filename);"
|
|
3827
|
+
},
|
|
2252
3828
|
...TS_LOADER
|
|
2253
3829
|
});
|
|
2254
3830
|
const clientImports = split ? "" : compiled.map((_, i) => ({ i })).filter(({ i }) => !infos[i].isApi && !infos[i].isMiddleware && reachable.has(i)).map(({ i }) => `import { render as render_${i} } from './comp-${i}.client.js';`).join("\n");
|
|
@@ -2258,7 +3834,7 @@ export async function renderPageStream(pathname, write, shellOpen, clientTag) {
|
|
|
2258
3834
|
const vitalsBlock = vitalsOn ? `
|
|
2259
3835
|
// the app asked for web-vitals - measure once, at boot, and let the
|
|
2260
3836
|
// app decide where the numbers go (one 'rosetack:vitals' CustomEvent per metric).
|
|
2261
|
-
reportVitals;
|
|
3837
|
+
reportVitals();
|
|
2262
3838
|
` : "";
|
|
2263
3839
|
const hasLang = infos.some((i) => i.pattern.includes(":lang"));
|
|
2264
3840
|
const langDirBlock = hasLang ? ` // <html lang dir> follows the route - the one part of the document
|
|
@@ -2266,26 +3842,24 @@ reportVitals;
|
|
|
2266
3842
|
// logical properties both read it). A route with no [lang] segment
|
|
2267
3843
|
// returns to the default locale, and a bogus segment falls back to it
|
|
2268
3844
|
// too, exactly like the server's docAttrs.
|
|
3845
|
+
// Only when this container IS the document's app root. A mount
|
|
3846
|
+
// (dist/mount.js) renders into a foreign page, whose language and
|
|
3847
|
+
// direction belong to the host, not to the mounted route.
|
|
2269
3848
|
const seg = langIdx >= 0 ? pathname.split('/')[langIdx] : '';
|
|
2270
3849
|
const known = !seg || isLocale(seg);
|
|
2271
|
-
|
|
2272
|
-
|
|
2273
|
-
|
|
2274
|
-
|
|
2275
|
-
|
|
3850
|
+
if (container === document.getElementById('app')) {
|
|
3851
|
+
const docLang = known && seg ? seg : __defLocale;
|
|
3852
|
+
document.documentElement.lang = docLang;
|
|
3853
|
+
const docDir = localeDir(docLang);
|
|
3854
|
+
if (docDir) document.documentElement.setAttribute('dir', docDir);
|
|
3855
|
+
else document.documentElement.removeAttribute('dir');
|
|
3856
|
+
}
|
|
2276
3857
|
if (!known) {` : ` if (langIdx >= 0 && !isLocale(pathname.split('/')[langIdx])) {`;
|
|
2277
3858
|
const clientEntry = `
|
|
2278
3859
|
${clientImports}
|
|
2279
|
-
import { setState, resumeState, clearRequestState, resetEffects, wire, isolateStateAsync, restoreState, setRefreshHook, clearMounts, flushMounts, adoptCleanups, handlers, setLocales, setLocalePacks, ensureLocale, isLocale, localeDir, setPrefetchOverride, serializeState } from './runtime.js';
|
|
2280
|
-
|
|
2281
|
-
//
|
|
2282
|
-
// renders any PRELOADED locale from the bundle, so switching language costs
|
|
2283
|
-
// zero requests (the same bet as the inlined route table). a locale
|
|
2284
|
-
// the app left out of the preload (i18n.preload in rosetack.config.js) is a
|
|
2285
|
-
// pack instead: it lives at /locales/<lang>.json and applyParams() fetches it
|
|
2286
|
-
// on first use - one request per language per session, then it renders from
|
|
2287
|
-
// memory like any other. The default build preloads everything and ships no
|
|
2288
|
-
// packs at all.
|
|
3860
|
+
import { setState, resumeState, clearRequestState, resetEffects, wire, isolateStateAsync, restoreState, setRefreshHook, clearMounts, flushMounts, adoptCleanups, handlers, setActionDispatcher, setLocales, setLocalePacks, ensureLocale, isLocale, localeDir, setPrefetchOverride, serializeState, setFxOwner, resetContainerFx, esc } from './runtime.js';
|
|
3861
|
+
|
|
3862
|
+
// I18n: the dictionaries baked at build time - the client renders any PRELOADED locale from the bundle.
|
|
2289
3863
|
setLocales(${clientLocalesJson}, '${defaultLocale}');
|
|
2290
3864
|
setLocalePacks(${JSON.stringify(packed)});
|
|
2291
3865
|
${hasLang ? `// the default locale, kept beside setLocales' own copy so <html lang> can
|
|
@@ -2295,10 +3869,7 @@ ${vitalsOn ? `// the app asked for web-vitals. The import is what keeps
|
|
|
2295
3869
|
// reportVitals alive through minification and tree-shaking; the call is one
|
|
2296
3870
|
// statement at boot, before the first render.
|
|
2297
3871
|
import { reportVitals } from './runtime.js';` : ""}
|
|
2298
|
-
// The two pack doors, re-exported for an app that wants to warm a language
|
|
2299
|
-
// before its visitor asks for it (ensureLocale) or to feed a dictionary it
|
|
2300
|
-
// fetched itself (loadLocale). Both are already in the bundle - ensureLocale
|
|
2301
|
-
// is what applyParams calls - so the re-export costs the statement alone.
|
|
3872
|
+
// The two pack doors, re-exported for an app that wants to warm a language before its visitor asks for it (ensureLocale) or to feed a dictionary.
|
|
2302
3873
|
export { ensureLocale, loadLocale } from './runtime.js';
|
|
2303
3874
|
${vitalsBlock}
|
|
2304
3875
|
|
|
@@ -2306,14 +3877,7 @@ const routes = [
|
|
|
2306
3877
|
${clientRoutes}
|
|
2307
3878
|
];
|
|
2308
3879
|
|
|
2309
|
-
// === Mode B: lazy route chunks ===
|
|
2310
|
-
// Split mode's registry entries arrive without a render function: loadChain
|
|
2311
|
-
// loads the route's module graph (the page plus its layouts, one chunk per
|
|
2312
|
-
// module, the shared runtime in its own vendor chunk) in parallel and
|
|
2313
|
-
// composes it at runtime - the exact nesting compose() built at compile
|
|
2314
|
-
// time for inline mode. getRender memoizes the composed function on the
|
|
2315
|
-
// entry, so a chunk loads once per session; inline mode's entries are the
|
|
2316
|
-
// render functions themselves, so the helper is a pass-through there.
|
|
3880
|
+
// === Mode B: lazy route chunks === Split mode's registry entries arrive without a render function: loadChain loads the route's module graph (the page).
|
|
2317
3881
|
const loadChain = async (loaders) => {
|
|
2318
3882
|
const mods = await Promise.all(loaders.map((load) => load()));
|
|
2319
3883
|
let expr = (closes, children) => mods[0].render(closes, children);
|
|
@@ -2329,36 +3893,62 @@ const getRender = async (route) => {
|
|
|
2329
3893
|
return (route.render ??= (await route.load()).render);
|
|
2330
3894
|
};
|
|
2331
3895
|
|
|
2332
|
-
// pages
|
|
2333
|
-
const
|
|
3896
|
+
// Not-found pages, deepest segment first (the server's table, client half): the root 404.rose ('/') and any pages/<seg>/_notfound.rose.
|
|
3897
|
+
const notFoundRoutes = ${notFoundTable};
|
|
3898
|
+
const notFoundFor = (pathname) => {
|
|
3899
|
+
for (const [prefix, render] of notFoundRoutes) {
|
|
3900
|
+
if (prefix === '/' || pathname === prefix || pathname.startsWith(prefix + '/')) return render;
|
|
3901
|
+
}
|
|
3902
|
+
return null;
|
|
3903
|
+
};
|
|
2334
3904
|
|
|
2335
|
-
//
|
|
2336
|
-
// whose render throws on the client degrades to this instead of breaking
|
|
2337
|
-
// navigation.
|
|
3905
|
+
// Pages/500.rose (with its layouts) or null -> built-in plain 500: a route whose render throws on the client degrades to this instead of breaking.
|
|
2338
3906
|
const errorPage = ${errorRender};
|
|
2339
3907
|
|
|
2340
3908
|
// Paint a fallback page (404/500) into the container, wired like any render.
|
|
2341
|
-
async function paintFallback(container, page, builtin) {
|
|
2342
|
-
|
|
2343
|
-
clearRequestState();
|
|
3909
|
+
async function paintFallback(container, page, builtin, keepState = false) {
|
|
3910
|
+
if (!keepState) __navReset(container);
|
|
2344
3911
|
clearMounts(); // a failed render leaves stale mounts behind
|
|
2345
3912
|
// inline mode passes the render itself; split mode passes a loader
|
|
2346
3913
|
const render = page ? await getRender(page) : null;
|
|
2347
3914
|
if (render) {
|
|
2348
3915
|
const closes = [];
|
|
2349
|
-
|
|
2350
|
-
|
|
2351
|
-
|
|
2352
|
-
|
|
2353
|
-
|
|
3916
|
+
await __withOwner(container, async () => {
|
|
3917
|
+
const html = await render(closes, '');
|
|
3918
|
+
container.innerHTML = html;
|
|
3919
|
+
wire(container, closes);
|
|
3920
|
+
bindEvents(container);
|
|
3921
|
+
flushMounts();
|
|
3922
|
+
});
|
|
2354
3923
|
return;
|
|
2355
3924
|
}
|
|
2356
3925
|
container.innerHTML = builtin;
|
|
2357
3926
|
}
|
|
2358
3927
|
|
|
3928
|
+
|
|
3929
|
+
export async function startNotFound(container, pathname) {
|
|
3930
|
+
const el = document.getElementById('__rosetack_state');
|
|
3931
|
+
if (el) resumeState(el.textContent);
|
|
3932
|
+
await paintFallback(container, notFoundFor(pathname), '<h1>404</h1><p>Page not found</p>', true);
|
|
3933
|
+
}
|
|
3934
|
+
|
|
2359
3935
|
export function matchRoute(pattern, pathname) {
|
|
3936
|
+
// Q0 (bug report): one canonical URL per route.
|
|
3937
|
+
pathname = pathname.replace(/\\/+$/, '') || '/';
|
|
2360
3938
|
const patternParts = pattern.split('/');
|
|
2361
3939
|
const pathParts = pathname.split('/');
|
|
3940
|
+
|
|
3941
|
+
const last = patternParts[patternParts.length - 1];
|
|
3942
|
+
if (last && (last.startsWith('*') || last.startsWith('**'))) {
|
|
3943
|
+
const fixed = patternParts.slice(0, -1);
|
|
3944
|
+
if (pathParts.length < fixed.length) return false;
|
|
3945
|
+
if (last.startsWith('*') && !last.startsWith('**') && pathParts.length === fixed.length) return false;
|
|
3946
|
+
for (let i = 0; i < fixed.length; i++) {
|
|
3947
|
+
if (fixed[i].startsWith(':')) continue;
|
|
3948
|
+
if (fixed[i] !== pathParts[i]) return false;
|
|
3949
|
+
}
|
|
3950
|
+
return true;
|
|
3951
|
+
}
|
|
2362
3952
|
if (patternParts.length !== pathParts.length) return false;
|
|
2363
3953
|
for (let i = 0; i < patternParts.length; i++) {
|
|
2364
3954
|
if (patternParts[i].startsWith(':')) continue;
|
|
@@ -2367,85 +3957,64 @@ export function matchRoute(pattern, pathname) {
|
|
|
2367
3957
|
return true;
|
|
2368
3958
|
}
|
|
2369
3959
|
|
|
2370
|
-
// === Link prefetch ===
|
|
2371
|
-
// Hover / focus / touch an internal link and the target route renders NOW -
|
|
2372
|
-
// $data included - against a throwaway signal map. The click that follows
|
|
2373
|
-
// paints from the cached HTML: no await, no request, no spinner. Other
|
|
2374
|
-
// frameworks prefetch data only; rosetack prefetches the whole render because
|
|
2375
|
-
// the inlined bundle already contains every route.
|
|
2376
|
-
// Trade-off: the cache holds either a result or the in-flight promise (dedupes
|
|
2377
|
-
// hover storms); one isolated render runs at a time so signal-map swapping
|
|
2378
|
-
// stays correct without any merging logic. Entries are single-use: a consumed
|
|
2379
|
-
// entry disappears from the cache, which is also how tests observe a hit.
|
|
2380
|
-
// P1, three guards for link-heavy pages:
|
|
2381
|
-
// 1. strategy - the app declares "export const prefetch = 'off' | 'hover' |
|
|
2382
|
-
// 'viewport' | 'all'" (root layout); 'all' is the original behavior.
|
|
2383
|
-
// Trade-off: app-global, not per-route - per-route would carry the mode
|
|
2384
|
-
// in each document's shell.
|
|
2385
|
-
// 2. budget - renders are serialized by the queue, so "concurrency" is 1;
|
|
2386
|
-
// the budget caps the QUEUE: a hover storm past it drops the excess
|
|
2387
|
-
// instead of rendering fifty routes nobody clicks.
|
|
2388
|
-
// 3. LRU cap - unconsumed entries would otherwise live forever; the oldest
|
|
2389
|
-
// is evicted first (Map iteration order; entries are single-use, so
|
|
2390
|
-
// insertion order IS the recency order).
|
|
3960
|
+
// === Link prefetch === Hover / focus / touch an internal link and the target route renders NOW - $data included - against a throwaway signal map.
|
|
2391
3961
|
let prefetchMode = ${JSON.stringify(prefetchMode)};
|
|
2392
3962
|
export function setPrefetchMode(mode) { prefetchMode = mode; }
|
|
2393
3963
|
const PREFETCH_BUDGET = 8;
|
|
2394
3964
|
const PREFETCH_MAX_CACHED = 4;
|
|
2395
|
-
const prefetchCache = new Map();
|
|
3965
|
+
const prefetchCache = new Map();
|
|
2396
3966
|
let prefetchQueue = Promise.resolve();
|
|
2397
3967
|
let prefetchPending = 0;
|
|
2398
3968
|
|
|
2399
|
-
|
|
2400
|
-
// a runtime pack (i18n.preload) is awaited HERE - the one place every client
|
|
2401
|
-
// render path goes through (navigation, prefetch, action adopt) - so a packed
|
|
2402
|
-
// locale costs one request per session and then renders from memory. A
|
|
2403
|
-
// preloaded locale (the default: every dictionary inline) resolves without
|
|
2404
|
-
// touching the network, so the common path stays synchronous in spirit.
|
|
3969
|
+
|
|
2405
3970
|
async function applyParams(route, pathname) {
|
|
2406
3971
|
const patternParts = route.pattern.split('/');
|
|
2407
3972
|
const pathParts = pathname.split('/');
|
|
2408
3973
|
for (let i = 0; i < patternParts.length; i++) {
|
|
2409
|
-
|
|
3974
|
+
const seg = patternParts[i];
|
|
3975
|
+
if (seg.startsWith(':')) setState(seg.slice(1), pathParts[i]);
|
|
3976
|
+
|
|
3977
|
+
|
|
3978
|
+
else if (seg.startsWith('*')) setState(seg.replace(/^\\*+/, ''), pathParts.slice(i));
|
|
2410
3979
|
}
|
|
2411
3980
|
const langIdx = patternParts.indexOf(':lang');
|
|
2412
3981
|
if (langIdx >= 0) await ensureLocale(pathParts[langIdx]);
|
|
2413
3982
|
}
|
|
2414
3983
|
|
|
3984
|
+
|
|
3985
|
+
function __netOk() {
|
|
3986
|
+
const c = navigator.connection;
|
|
3987
|
+
if (!c) return true;
|
|
3988
|
+
if (c.saveData) return false;
|
|
3989
|
+
const t = c.effectiveType;
|
|
3990
|
+
return t !== 'slow-2g' && t !== '2g';
|
|
3991
|
+
}
|
|
3992
|
+
|
|
2415
3993
|
export function prefetch(pathname, source = 'hover') {
|
|
2416
3994
|
if (prefetchMode === 'off') return;
|
|
2417
3995
|
if (prefetchMode === 'hover' && source !== 'hover') return;
|
|
2418
3996
|
if (prefetchMode === 'viewport' && source !== 'viewport') return;
|
|
3997
|
+
if (!__netOk()) return; // save-data / 2g: no bytes before the click
|
|
2419
3998
|
if (prefetchCache.has(pathname)) return;
|
|
2420
|
-
if (pathname === location.pathname) return;
|
|
3999
|
+
if (pathname === location.pathname) return;
|
|
2421
4000
|
const route = routes.find((r) => matchRoute(r.pattern, pathname));
|
|
2422
4001
|
if (!route) return;
|
|
2423
|
-
if (prefetchPending >= PREFETCH_BUDGET) return; //
|
|
2424
|
-
// P0-1: the link may carry a query (/search?q=cats). $query() reads the
|
|
2425
|
-
// browser's own URL, which is the page being LEFT - so the prefetched
|
|
2426
|
-
// render would see the wrong one. Override it for the duration and clear
|
|
2427
|
-
// it after; the queue below serializes renders, so one slot is enough.
|
|
4002
|
+
if (prefetchPending >= PREFETCH_BUDGET) return; // Budget spent: drop it, a later hover retries. P0-1: the link may carry a query (/search?q=cats)
|
|
2428
4003
|
const qi = pathname.indexOf('?');
|
|
2429
4004
|
const qOverride = qi >= 0 ? Object.fromEntries(new URLSearchParams(pathname.slice(qi))) : null;
|
|
2430
4005
|
const p = prefetchQueue.then(async () => {
|
|
2431
4006
|
try {
|
|
2432
4007
|
setPrefetchOverride(qOverride);
|
|
2433
|
-
//
|
|
2434
|
-
// queued and the onCleanup disposers it registered: the paint that
|
|
2435
|
-
// consumes this entry replays the mounts after wiring and adopts the
|
|
2436
|
-
// cleanups, so the prefetched route's timers are disposed on the next
|
|
2437
|
-
// navigation like any live route's
|
|
4008
|
+
// The isolated render also captures the onMount callbacks the route queued and the onCleanup disposers it registered: the paint that consumes.
|
|
2438
4009
|
const { result, state, mounts, cleanups } = await isolateStateAsync(async () => {
|
|
2439
4010
|
await applyParams(route, pathname); // a packed locale's dictionary lands before the render
|
|
2440
4011
|
const closes = [];
|
|
2441
|
-
const render = await getRender(route);
|
|
4012
|
+
const render = await getRender(route);
|
|
2442
4013
|
const html = await render(closes, '');
|
|
2443
4014
|
return { html, closes };
|
|
2444
4015
|
});
|
|
2445
4016
|
const entry = { ...result, state, mounts, cleanups };
|
|
2446
|
-
prefetchCache.set(pathname, entry); //
|
|
2447
|
-
// evict oldest-first; in-flight promises are never evicted (evicting
|
|
2448
|
-
// one would only force a duplicate render)
|
|
4017
|
+
prefetchCache.set(pathname, entry); // Promise -> result. evict oldest-first; in-flight promises are never evicted (evicting. one would only force a duplicate render)
|
|
2449
4018
|
while (prefetchCache.size > PREFETCH_MAX_CACHED) {
|
|
2450
4019
|
const oldest = prefetchCache.keys().next().value;
|
|
2451
4020
|
if (prefetchCache.get(oldest) instanceof Promise) break;
|
|
@@ -2453,7 +4022,7 @@ export function prefetch(pathname, source = 'hover') {
|
|
|
2453
4022
|
}
|
|
2454
4023
|
return entry;
|
|
2455
4024
|
} catch {
|
|
2456
|
-
prefetchCache.delete(pathname);
|
|
4025
|
+
prefetchCache.delete(pathname);
|
|
2457
4026
|
return null;
|
|
2458
4027
|
} finally {
|
|
2459
4028
|
setPrefetchOverride(null);
|
|
@@ -2466,13 +4035,10 @@ export function prefetch(pathname, source = 'hover') {
|
|
|
2466
4035
|
}
|
|
2467
4036
|
|
|
2468
4037
|
export function prefetchStats() {
|
|
2469
|
-
return { cached: prefetchCache.size, pending: prefetchPending, mode: prefetchMode };
|
|
4038
|
+
return { cached: prefetchCache.size, pending: prefetchPending, mode: prefetchMode, network: __netOk() };
|
|
2470
4039
|
}
|
|
2471
4040
|
|
|
2472
|
-
// One delegated listener per event type on the app container: survives DOM
|
|
2473
|
-
// swaps and cloned blocks, so handlers never need re-binding. A handler
|
|
2474
|
-
// compiled from a server action (data-on-*="$action:name") dispatches to
|
|
2475
|
-
// $action instead of the local handler registry.
|
|
4041
|
+
// One delegated listener per event type on the app container: survives DOM swaps and cloned blocks, so handlers never need re-binding.
|
|
2476
4042
|
const DELEGATED = ['click', 'input', 'change', 'submit'];
|
|
2477
4043
|
function bindEvents(container) {
|
|
2478
4044
|
if (container.__rosetack_bound) return;
|
|
@@ -2489,48 +4055,76 @@ function bindEvents(container) {
|
|
|
2489
4055
|
}
|
|
2490
4056
|
}
|
|
2491
4057
|
|
|
2492
|
-
// === Server actions from any event ===
|
|
2493
|
-
|
|
2494
|
-
|
|
2495
|
-
|
|
2496
|
-
|
|
2497
|
-
|
|
2498
|
-
async function postForm(body) {
|
|
2499
|
-
const res = await fetch(location.pathname, { method: 'POST', body });
|
|
4058
|
+
// === Server actions from any event === POST the body to the current route and adopt the response in place: the server runs the selected action.
|
|
4059
|
+
async function postForm(body, container, pathname) {
|
|
4060
|
+
|
|
4061
|
+
const box = container || document.getElementById('app');
|
|
4062
|
+
const route = pathname || location.pathname;
|
|
4063
|
+
const res = await fetch(route, { method: 'POST', body });
|
|
2500
4064
|
const html = await res.text();
|
|
2501
4065
|
const doc = new DOMParser().parseFromString(html, 'text/html');
|
|
2502
4066
|
const next = doc.getElementById('app');
|
|
2503
4067
|
const st = doc.getElementById('__rosetack_state');
|
|
2504
4068
|
const paint = () => {
|
|
2505
|
-
|
|
2506
|
-
adopt(container, next ? next.innerHTML : '', st ? st.textContent : '{}');
|
|
4069
|
+
adopt(box, next ? next.innerHTML : '', st ? st.textContent : '{}', route);
|
|
2507
4070
|
};
|
|
2508
4071
|
if (document.startViewTransition) document.startViewTransition(paint);
|
|
2509
4072
|
else paint();
|
|
2510
4073
|
}
|
|
2511
4074
|
|
|
2512
|
-
// Call a page's server action by name from any event handler:
|
|
2513
|
-
// <button on:click={like}> compiles to $action('like'). Without JS the
|
|
2514
|
-
// binding is inert - the progressive-enhancement story stays with forms.
|
|
4075
|
+
// Call a page's server action by name from any event handler: <button on:click={like}> compiles to $action('like').
|
|
2515
4076
|
export async function $action(name, e) {
|
|
2516
4077
|
if (e && e.preventDefault) e.preventDefault();
|
|
2517
4078
|
const body = new FormData();
|
|
2518
4079
|
body.append('__action', name);
|
|
2519
|
-
|
|
4080
|
+
// An event inside a mount belongs to that mount - the attribute is kept in step with what is currently mounted.
|
|
4081
|
+
const box = e && e.target && e.target.closest ? e.target.closest('[data-rosetack]') : null;
|
|
4082
|
+
return postForm(body, box || undefined, box ? box.getAttribute('data-rosetack') : undefined);
|
|
2520
4083
|
}
|
|
4084
|
+
// F17: hand the dispatcher to the runtime, so wire() can serve a server action bound to a non-delegated event (on:keydown="$action:save") the same way.
|
|
4085
|
+
setActionDispatcher($action);
|
|
2521
4086
|
|
|
2522
4087
|
export { postForm };
|
|
2523
4088
|
|
|
2524
|
-
// The live signal graph as JSON - the same serializeState the zero-hydration
|
|
2525
|
-
// resume uses, exported so the bootstrap's dev seam (window.__rosetack.state())
|
|
2526
|
-
// can hand it to the dev server's reload bridge and to a devtools extension.
|
|
2527
|
-
// A local re-export on purpose: it keeps the binding alive through minification
|
|
2528
|
-
// for the bootstrap text appended after the bundle.
|
|
4089
|
+
// The live signal graph as JSON - the same serializeState the zero-hydration resume uses.
|
|
2529
4090
|
export { serializeState };
|
|
2530
4091
|
|
|
2531
|
-
//
|
|
2532
|
-
|
|
2533
|
-
|
|
4092
|
+
// Initial=true: adopt the SSR DOM (zero hydration) - wire reactive markers to the existing nodes and bind events.
|
|
4093
|
+
|
|
4094
|
+
|
|
4095
|
+
function __ownsDoc(container) {
|
|
4096
|
+
return container === document.getElementById('app');
|
|
4097
|
+
}
|
|
4098
|
+
function __navReset(container) {
|
|
4099
|
+
if (__ownsDoc(container)) {
|
|
4100
|
+
resetEffects();
|
|
4101
|
+
clearRequestState();
|
|
4102
|
+
} else {
|
|
4103
|
+
resetContainerFx(container);
|
|
4104
|
+
}
|
|
4105
|
+
}
|
|
4106
|
+
// Attribute everything a render creates (state keys, effects, onCleanups) to
|
|
4107
|
+
// its container. The document path sets no owner and keeps the global sets.
|
|
4108
|
+
async function __withOwner(container, fn) {
|
|
4109
|
+
if (__ownsDoc(container)) return fn();
|
|
4110
|
+
setFxOwner(container);
|
|
4111
|
+
try {
|
|
4112
|
+
return await fn();
|
|
4113
|
+
} finally {
|
|
4114
|
+
setFxOwner(null);
|
|
4115
|
+
}
|
|
4116
|
+
}
|
|
4117
|
+
// View Transition on SPA swaps (B9): the DOM swap rides one cross-fade when the browser supports it; reduced-motion users and environments without.
|
|
4118
|
+
async function __swap(container, html) {
|
|
4119
|
+
const reduce = typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches;
|
|
4120
|
+
if (typeof document.startViewTransition === 'function' && !reduce) {
|
|
4121
|
+
const vt = document.startViewTransition(() => { container.innerHTML = html; });
|
|
4122
|
+
await vt.updateCallbackDone.catch(() => {});
|
|
4123
|
+
} else {
|
|
4124
|
+
container.innerHTML = html;
|
|
4125
|
+
}
|
|
4126
|
+
}
|
|
4127
|
+
|
|
2534
4128
|
export async function start(container, pathname, initial) {
|
|
2535
4129
|
clearMounts(); // stale mounts from a failed render never fire
|
|
2536
4130
|
if (initial) {
|
|
@@ -2539,114 +4133,123 @@ export async function start(container, pathname, initial) {
|
|
|
2539
4133
|
}
|
|
2540
4134
|
for (const route of routes) {
|
|
2541
4135
|
if (matchRoute(route.pattern, pathname)) {
|
|
2542
|
-
//
|
|
2543
|
-
// (before the prefetch check: a cached entry for a bogus locale is
|
|
2544
|
-
// discarded, never painted)
|
|
4136
|
+
// I18n: an unknown locale paints the 404 page, same as the server (before the prefetch check: a cached entry for a bogus locale is discarded).
|
|
2545
4137
|
const langIdx = route.pattern.split('/').indexOf(':lang');
|
|
2546
4138
|
${langDirBlock}
|
|
2547
|
-
await paintFallback(container,
|
|
4139
|
+
await paintFallback(container, notFoundFor(pathname), '<h1>404</h1><p>Page not found</p>');
|
|
2548
4140
|
return;
|
|
2549
4141
|
}
|
|
2550
|
-
// Prefetched on hover/focus/touch: the render already ran, so paint its
|
|
2551
|
-
// HTML and adopt its signal entries - events then patch the very nodes
|
|
2552
|
-
// we wire, and no $data re-runs on click.
|
|
4142
|
+
// Prefetched on hover/focus/touch: the render already ran, so paint its HTML and adopt its signal entries - events then patch the very nodes we.
|
|
2553
4143
|
let hit = initial ? undefined : prefetchCache.get(pathname);
|
|
2554
4144
|
if (hit && typeof hit.then === 'function') hit = await hit; // in-flight: land it first
|
|
2555
4145
|
if (hit) {
|
|
2556
|
-
prefetchCache.delete(pathname);
|
|
2557
|
-
|
|
4146
|
+
prefetchCache.delete(pathname);
|
|
4147
|
+
__navReset(container);
|
|
2558
4148
|
restoreState(hit.state);
|
|
2559
|
-
container
|
|
2560
|
-
|
|
4149
|
+
await __swap(container, hit.html);
|
|
4150
|
+
await __withOwner(container, () => {
|
|
4151
|
+
wire(container, hit.closes);
|
|
4152
|
+
bindEvents(container);
|
|
4153
|
+
hit.mounts.forEach((fn) => fn());
|
|
4154
|
+
adoptCleanups(hit.cleanups);
|
|
4155
|
+
});
|
|
4156
|
+
return;
|
|
4157
|
+
}
|
|
4158
|
+
if (!initial) __navReset(container);
|
|
4159
|
+
let broken = false;
|
|
4160
|
+
let signal = null;
|
|
4161
|
+
await __withOwner(container, async () => {
|
|
4162
|
+
await applyParams(route, pathname);
|
|
4163
|
+
const closes = [];
|
|
4164
|
+
let html;
|
|
4165
|
+
try {
|
|
4166
|
+
const render = await getRender(route);
|
|
4167
|
+
html = await render(closes, '');
|
|
4168
|
+
} catch (err) {
|
|
4169
|
+
|
|
4170
|
+
if (err && err.__rosetack === 'notFound') { signal = 'notFound'; return; }
|
|
4171
|
+
if (err && err.__rosetack === 'redirect') { signal = err.path; return; }
|
|
4172
|
+
|
|
4173
|
+
|
|
4174
|
+
console.error('rosetack: client render failed for', pathname, err instanceof Error ? err.message : err);
|
|
4175
|
+
broken = true;
|
|
4176
|
+
return;
|
|
4177
|
+
}
|
|
4178
|
+
if (!initial) await __swap(container, html);
|
|
4179
|
+
wire(container, closes);
|
|
2561
4180
|
bindEvents(container);
|
|
2562
|
-
|
|
2563
|
-
|
|
4181
|
+
flushMounts();
|
|
4182
|
+
});
|
|
4183
|
+
if (signal === 'notFound') {
|
|
4184
|
+
// T17: a client-side render of a $data route without a prefetch entry has no data source (the server fills the context bag) - the correct.
|
|
4185
|
+
if (!initial) { try { location.assign(pathname); return; } catch { } }
|
|
4186
|
+
await paintFallback(container, notFoundFor(pathname), '<h1>404</h1><p>Page not found</p>');
|
|
2564
4187
|
return;
|
|
2565
4188
|
}
|
|
2566
|
-
if (
|
|
2567
|
-
|
|
2568
|
-
|
|
4189
|
+
if (signal) {
|
|
4190
|
+
location.href = signal;
|
|
4191
|
+
return;
|
|
2569
4192
|
}
|
|
2570
|
-
|
|
2571
|
-
const closes = [];
|
|
2572
|
-
let html;
|
|
2573
|
-
try {
|
|
2574
|
-
const render = await getRender(route); // split mode: loads the route's chunk here
|
|
2575
|
-
html = await render(closes, '');
|
|
2576
|
-
} catch {
|
|
2577
|
-
// the route itself is broken: degrade to pages/500.rose (or the
|
|
2578
|
-
// built-in plain 500) instead of leaving the container empty
|
|
4193
|
+
if (broken) {
|
|
2579
4194
|
await paintFallback(container, errorPage, '<h1>500</h1><p>Something went wrong rendering this page.</p>');
|
|
2580
|
-
return;
|
|
2581
4195
|
}
|
|
2582
|
-
if (!initial) container.innerHTML = html;
|
|
2583
|
-
wire(container, closes);
|
|
2584
|
-
bindEvents(container);
|
|
2585
|
-
flushMounts();
|
|
2586
4196
|
return;
|
|
2587
4197
|
}
|
|
2588
4198
|
}
|
|
2589
|
-
//
|
|
2590
|
-
|
|
2591
|
-
//
|
|
2592
|
-
|
|
2593
|
-
|
|
2594
|
-
|
|
4199
|
+
// Unmatched route: the nearest not-found page renders (with its head + interactivity) - a segment's _notfound.rose or the root 404.rose - else //.
|
|
4200
|
+
${hasLang ? ` // the same app-root gate as above - a mount never touches the
|
|
4201
|
+
// host document's language or direction.
|
|
4202
|
+
if (container === document.getElementById('app')) {
|
|
4203
|
+
document.documentElement.lang = __defLocale;
|
|
4204
|
+
document.documentElement.removeAttribute('dir');
|
|
4205
|
+
}` : ""}
|
|
4206
|
+
await paintFallback(container, notFoundFor(pathname), '<h1>404</h1><p>Page not found</p>');
|
|
2595
4207
|
}
|
|
2596
4208
|
|
|
2597
|
-
// Adopt a server-rendered response in place - the JS-enabled half of
|
|
2598
|
-
|
|
2599
|
-
|
|
2600
|
-
|
|
2601
|
-
|
|
2602
|
-
|
|
2603
|
-
export async function adopt(container, html, stateJson) {
|
|
2604
|
-
resetEffects();
|
|
2605
|
-
clearRequestState();
|
|
4209
|
+
// Adopt a server-rendered response in place - the JS-enabled half of progressive-enhancement forms: the bootstrap POSTs a <form method="POST">.
|
|
4210
|
+
export async function adopt(container, html, stateJson, pathname) {
|
|
4211
|
+
|
|
4212
|
+
|
|
4213
|
+
const route0 = pathname || location.pathname;
|
|
4214
|
+
__navReset(container);
|
|
2606
4215
|
clearMounts(); // stale mounts from a failed render never fire
|
|
2607
4216
|
resumeState(stateJson);
|
|
2608
4217
|
container.innerHTML = html;
|
|
2609
|
-
|
|
4218
|
+
|
|
2610
4219
|
const st = document.getElementById('__rosetack_state');
|
|
2611
4220
|
if (st) st.textContent = stateJson;
|
|
2612
4221
|
for (const route of routes) {
|
|
2613
|
-
if (matchRoute(route.pattern,
|
|
2614
|
-
await
|
|
2615
|
-
|
|
2616
|
-
|
|
2617
|
-
|
|
2618
|
-
|
|
2619
|
-
|
|
2620
|
-
|
|
2621
|
-
|
|
2622
|
-
|
|
2623
|
-
|
|
2624
|
-
|
|
2625
|
-
|
|
2626
|
-
|
|
4222
|
+
if (matchRoute(route.pattern, route0)) {
|
|
4223
|
+
await __withOwner(container, async () => {
|
|
4224
|
+
await applyParams(route, route0);
|
|
4225
|
+
const closes = [];
|
|
4226
|
+
try {
|
|
4227
|
+
const render = await getRender(route);
|
|
4228
|
+
await render(closes, '');
|
|
4229
|
+
} catch {
|
|
4230
|
+
|
|
4231
|
+
|
|
4232
|
+
return;
|
|
4233
|
+
}
|
|
4234
|
+
wire(container, closes);
|
|
4235
|
+
bindEvents(container);
|
|
4236
|
+
flushMounts();
|
|
4237
|
+
});
|
|
2627
4238
|
return;
|
|
2628
4239
|
}
|
|
2629
4240
|
}
|
|
2630
4241
|
}
|
|
2631
|
-
// === refresh() implementation ===
|
|
2632
|
-
// Re-render the current route in place: the client half of router.refresh()
|
|
2633
|
-
// (a router refresh) / (a full invalidation). Same machinery as a client-side
|
|
2634
|
-
// navigation to the current path - $data re-runs, state re-seeds from the
|
|
2635
|
-
// fresh render, wire() patches the marked nodes - but a refresh never lands
|
|
2636
|
-
// a prefetch entry: a hover from a minute ago is exactly what it exists to
|
|
2637
|
-
// bypass. Zero requests: the render (and its $data) runs in the page.
|
|
2638
|
-
// Trade-off: state resets like navigation (no per-key retention); add
|
|
2639
|
-
// retention when an app needs refresh-without-losing-input.
|
|
4242
|
+
// === refresh() implementation === Re-render the current route in place: the client half of router.refresh() (a router refresh) / (a full invalidation).
|
|
2640
4243
|
setRefreshHook(async () => {
|
|
2641
4244
|
prefetchCache.delete(location.pathname);
|
|
2642
4245
|
await start(document.getElementById('app'), location.pathname, false);
|
|
2643
4246
|
});
|
|
2644
4247
|
`;
|
|
2645
|
-
await
|
|
4248
|
+
await fs3.promises.writeFile(path2.join(buildDir, "client-entry.js"), clientEntry);
|
|
2646
4249
|
if (split) {
|
|
2647
|
-
await
|
|
4250
|
+
await fs3.promises.rm(path2.join(outDir, "chunks"), { recursive: true, force: true });
|
|
2648
4251
|
await esbuild.build({
|
|
2649
|
-
entryPoints: [
|
|
4252
|
+
entryPoints: [path2.join(buildDir, "client-entry.js")],
|
|
2650
4253
|
bundle: true,
|
|
2651
4254
|
format: "esm",
|
|
2652
4255
|
platform: "browser",
|
|
@@ -2660,9 +4263,9 @@ setRefreshHook(async () => {
|
|
|
2660
4263
|
});
|
|
2661
4264
|
} else {
|
|
2662
4265
|
await esbuild.build({
|
|
2663
|
-
entryPoints: [
|
|
4266
|
+
entryPoints: [path2.join(buildDir, "client-entry.js")],
|
|
2664
4267
|
bundle: true,
|
|
2665
|
-
outfile:
|
|
4268
|
+
outfile: path2.join(outDir, "client.js"),
|
|
2666
4269
|
format: "esm",
|
|
2667
4270
|
platform: "browser",
|
|
2668
4271
|
minify: true,
|
|
@@ -2670,36 +4273,54 @@ setRefreshHook(async () => {
|
|
|
2670
4273
|
...TS_LOADER
|
|
2671
4274
|
});
|
|
2672
4275
|
}
|
|
2673
|
-
await
|
|
2674
|
-
|
|
2675
|
-
|
|
2676
|
-
|
|
2677
|
-
await
|
|
2678
|
-
const
|
|
2679
|
-
await
|
|
2680
|
-
assets.map((a) => fs.promises.copyFile(path.join(publicDir, a), path.join(outPublic, a)))
|
|
2681
|
-
);
|
|
4276
|
+
await fs3.promises.writeFile(path2.join(outDir, "mount.js"), MOUNT_ENTRY);
|
|
4277
|
+
await fs3.promises.rm(buildDir, { recursive: true, force: true });
|
|
4278
|
+
const publicDir = path2.join(root, "public");
|
|
4279
|
+
if (fs3.existsSync(publicDir)) {
|
|
4280
|
+
await fs3.promises.cp(publicDir, path2.join(outDir, "public"), { recursive: true });
|
|
4281
|
+
const favicon = path2.join(publicDir, "favicon.ico");
|
|
4282
|
+
if (fs3.existsSync(favicon)) await fs3.promises.copyFile(favicon, path2.join(outDir, "favicon.ico"));
|
|
2682
4283
|
}
|
|
2683
4284
|
console.log("rosetack zero-JS report:");
|
|
2684
4285
|
for (const line of buildReport(infos, compiled)) console.log(" " + line);
|
|
4286
|
+
const warnGroups = /* @__PURE__ */ new Map();
|
|
2685
4287
|
for (const { info, i } of pages) {
|
|
2686
4288
|
if (!routeShipsNoJs(infos, compiled, i)) continue;
|
|
2687
4289
|
for (const ci of [i, ...layoutsOf(infos, i)]) {
|
|
2688
4290
|
for (const w of compiled[ci].jsWarnings ?? []) {
|
|
2689
|
-
|
|
4291
|
+
let g = warnGroups.get(w);
|
|
4292
|
+
if (!g) {
|
|
4293
|
+
g = { why: w, files: /* @__PURE__ */ new Map() };
|
|
4294
|
+
warnGroups.set(w, g);
|
|
4295
|
+
}
|
|
4296
|
+
const file = path2.relative(root, infos[ci].filePath).replace(/\\/g, "/");
|
|
4297
|
+
let routes = g.files.get(file);
|
|
4298
|
+
if (!routes) {
|
|
4299
|
+
routes = /* @__PURE__ */ new Set();
|
|
4300
|
+
g.files.set(file, routes);
|
|
4301
|
+
}
|
|
4302
|
+
routes.add(info.routePath);
|
|
2690
4303
|
}
|
|
2691
4304
|
}
|
|
2692
4305
|
}
|
|
4306
|
+
for (const g of warnGroups.values()) {
|
|
4307
|
+
const allRoutes = /* @__PURE__ */ new Set();
|
|
4308
|
+
for (const routes of g.files.values()) for (const r of routes) allRoutes.add(r);
|
|
4309
|
+
const parts = [...g.files.entries()].sort((a, b) => b[1].size - a[1].size).map(([file, routes]) => `${file} (${routes.size === 1 ? [...routes][0] : `${routes.size} routes`})`);
|
|
4310
|
+
const shown = parts.slice(0, 4).join(", ");
|
|
4311
|
+
const more = parts.length > 4 ? `, +${parts.length - 4} more files` : "";
|
|
4312
|
+
console.warn(`rosetack warning: ${allRoutes.size} routes ship zero JavaScript while their chain contains ${g.why} - ${shown}${more}`);
|
|
4313
|
+
}
|
|
2693
4314
|
return { routes: pages.map(({ info }) => info), bundle: bundleMode };
|
|
2694
4315
|
}
|
|
2695
4316
|
async function scanRoseFiles(root) {
|
|
2696
|
-
const pagesDir =
|
|
2697
|
-
if (!
|
|
4317
|
+
const pagesDir = path2.join(root, "src", "pages");
|
|
4318
|
+
if (!fs3.existsSync(pagesDir)) return [];
|
|
2698
4319
|
async function scan(dir) {
|
|
2699
|
-
const entries = await
|
|
4320
|
+
const entries = await fs3.promises.readdir(dir, { withFileTypes: true });
|
|
2700
4321
|
const files = [];
|
|
2701
4322
|
for (const entry of entries) {
|
|
2702
|
-
const full =
|
|
4323
|
+
const full = path2.join(dir, entry.name);
|
|
2703
4324
|
if (entry.isDirectory()) files.push(...await scan(full));
|
|
2704
4325
|
else if (entry.name.endsWith(".rose")) files.push(full);
|
|
2705
4326
|
}
|
|
@@ -2708,13 +4329,13 @@ async function scanRoseFiles(root) {
|
|
|
2708
4329
|
return scan(pagesDir);
|
|
2709
4330
|
}
|
|
2710
4331
|
async function scanComponentFiles(root) {
|
|
2711
|
-
const compDir =
|
|
2712
|
-
if (!
|
|
4332
|
+
const compDir = path2.join(root, "src", "components");
|
|
4333
|
+
if (!fs3.existsSync(compDir)) return [];
|
|
2713
4334
|
async function scan(dir) {
|
|
2714
|
-
const entries = await
|
|
4335
|
+
const entries = await fs3.promises.readdir(dir, { withFileTypes: true });
|
|
2715
4336
|
const files = [];
|
|
2716
4337
|
for (const entry of entries) {
|
|
2717
|
-
const full =
|
|
4338
|
+
const full = path2.join(dir, entry.name);
|
|
2718
4339
|
if (entry.isDirectory()) files.push(...await scan(full));
|
|
2719
4340
|
else if (entry.name.endsWith(".rose")) files.push(full);
|
|
2720
4341
|
}
|
|
@@ -2723,26 +4344,32 @@ async function scanComponentFiles(root) {
|
|
|
2723
4344
|
return scan(compDir);
|
|
2724
4345
|
}
|
|
2725
4346
|
function isAncestorDir(layoutPath, pagePath) {
|
|
2726
|
-
const layoutDir =
|
|
2727
|
-
const pageDir =
|
|
2728
|
-
return pageDir === layoutDir || pageDir.startsWith(layoutDir +
|
|
4347
|
+
const layoutDir = path2.dirname(layoutPath);
|
|
4348
|
+
const pageDir = path2.dirname(pagePath);
|
|
4349
|
+
return pageDir === layoutDir || pageDir.startsWith(layoutDir + path2.sep);
|
|
2729
4350
|
}
|
|
2730
4351
|
function getRouteInfo(filePath, root) {
|
|
2731
|
-
const pagesDir =
|
|
2732
|
-
const relative2 =
|
|
4352
|
+
const pagesDir = path2.join(root, "src", "pages");
|
|
4353
|
+
const relative2 = path2.relative(pagesDir, filePath).replace(/\\/g, "/");
|
|
2733
4354
|
const withoutExt = relative2.replace(/\.rose$/, "");
|
|
2734
|
-
const base =
|
|
4355
|
+
const base = path2.posix.basename(withoutExt);
|
|
2735
4356
|
const isComponent = filePath.replace(/\\/g, "/").includes("/src/components/");
|
|
2736
4357
|
const isLayout = !isComponent && base === "_layout";
|
|
2737
|
-
const isNotFound = !isComponent && base === "404";
|
|
4358
|
+
const isNotFound = !isComponent && (base === "404" || base === "_notfound");
|
|
2738
4359
|
const isError = !isComponent && base === "500";
|
|
2739
4360
|
const isApi = !isComponent && (withoutExt === "api" || withoutExt.startsWith("api/"));
|
|
2740
4361
|
const isMiddleware = !isComponent && withoutExt === "_middleware";
|
|
2741
|
-
let parts = withoutExt.split("/").filter((p) => p !== "_layout");
|
|
4362
|
+
let parts = withoutExt.split("/").filter((p) => p !== "_layout" && p !== "_notfound");
|
|
2742
4363
|
if (parts.length > 1 && parts[parts.length - 1] === "index") parts = parts.slice(0, -1);
|
|
2743
|
-
const
|
|
2744
|
-
|
|
2745
|
-
)
|
|
4364
|
+
const CATCH_ALL = /^\[\.\.\.(\w+)\]$/;
|
|
4365
|
+
const OPTIONAL_CATCH_ALL = /^\[\[\.\.\.(\w+)\]\]$/;
|
|
4366
|
+
const routeParts = parts.map((part) => {
|
|
4367
|
+
const optional = OPTIONAL_CATCH_ALL.exec(part);
|
|
4368
|
+
if (optional) return `**${optional[1]}`;
|
|
4369
|
+
const catchAll = CATCH_ALL.exec(part);
|
|
4370
|
+
if (catchAll) return `*${catchAll[1]}`;
|
|
4371
|
+
return part.startsWith("[") && part.endsWith("]") ? `:${part.slice(1, -1)}` : part;
|
|
4372
|
+
});
|
|
2746
4373
|
let routePath;
|
|
2747
4374
|
if (routeParts.length === 0 || routeParts.length === 1 && routeParts[0] === "index") {
|
|
2748
4375
|
routePath = "/";
|
|
@@ -2753,7 +4380,13 @@ function getRouteInfo(filePath, root) {
|
|
|
2753
4380
|
filePath,
|
|
2754
4381
|
routePath,
|
|
2755
4382
|
pattern: routePath,
|
|
2756
|
-
paramNames: parts.
|
|
4383
|
+
paramNames: parts.flatMap((p) => {
|
|
4384
|
+
const optional = OPTIONAL_CATCH_ALL.exec(p);
|
|
4385
|
+
if (optional) return [optional[1]];
|
|
4386
|
+
const catchAll = CATCH_ALL.exec(p);
|
|
4387
|
+
if (catchAll) return [catchAll[1]];
|
|
4388
|
+
return p.startsWith("[") && p.endsWith("]") ? [p.slice(1, -1)] : [];
|
|
4389
|
+
}),
|
|
2757
4390
|
isLayout,
|
|
2758
4391
|
isNotFound,
|
|
2759
4392
|
isError,
|