@seip/bluebird-js 0.1.6 → 0.2.0
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/.vscode/extensions.json +7 -7
- package/.vscode/settings.json +10 -10
- package/AGENTS.md +266 -116
- package/README.md +258 -245
- package/app/models/user.js +19 -0
- package/app/resources/html/home.html +137 -0
- package/app/resources/html/layouts/main.html +54 -0
- package/app/resources/html/notFound.html +14 -0
- package/app/resources/html/terms.html +46 -0
- package/app/resources/index.html +27 -0
- package/app/resources/layouts/AppLayout.jsx +89 -0
- package/app/resources/main.jsx +18 -0
- package/app/resources/pages/Dashboard.jsx +98 -0
- package/app/resources/pages/Home.jsx +140 -0
- package/app/resources/pages/Login.jsx +35 -0
- package/app/resources/pages/NotFound.jsx +16 -0
- package/app/resources/pages/Register.jsx +55 -0
- package/app/resources/routes.jsx +54 -0
- package/app/resources/spa.js +67 -0
- package/app/resources/styles.css +9 -0
- package/app/routes/api.js +85 -50
- package/app/routes/auth.js +209 -0
- package/app/routes/web.js +49 -37
- package/core/ai.d.ts +151 -151
- package/core/ai.js +1071 -1051
- package/core/app.d.ts +2 -18
- package/core/app.js +978 -792
- package/core/auth.d.ts +2 -13
- package/core/auth.js +444 -326
- package/core/cli/backup.js +167 -167
- package/core/cli/build.js +37 -0
- package/core/cli/dev.js +155 -0
- package/core/cli/doctor.js +37 -2
- package/core/cli/export.js +191 -0
- package/core/cli/init.js +101 -332
- package/core/cli/nginx.js +1 -1
- package/core/cli/templates.js +139 -0
- package/core/cli/view.js +73 -136
- package/core/config.js +44 -2
- package/core/csrf.js +156 -24
- package/core/database.js +737 -684
- package/core/debug.js +1 -1
- package/core/html.js +8 -1
- package/core/index.d.ts +1286 -1431
- package/core/paths.js +55 -0
- package/core/ratelimit.js +10 -1
- package/core/react/client/api.js +237 -0
- package/core/react/client/auth.js +236 -0
- package/core/react/client/components.js +1321 -0
- package/core/react/client/i18n.js +338 -0
- package/core/react/client/index.d.ts +249 -0
- package/core/react/client/index.js +49 -0
- package/core/react/client/router.js +26 -0
- package/core/react/client/theme.css +512 -0
- package/core/render-cache.js +250 -212
- package/core/render.d.ts +25 -21
- package/core/render.js +613 -603
- package/core/router.d.ts +2 -3
- package/core/router.js +171 -171
- package/core/seo.js +10 -0
- package/core/spa.js +599 -0
- package/core/view-loader.js +81 -455
- package/core/vite-plugin.d.ts +18 -0
- package/core/vite-plugin.js +162 -0
- package/core/vite.js +250 -145
- package/index.js +22 -18
- package/jsconfig.json +5 -3
- package/package.json +114 -92
- package/production.md +8 -3
- package/public/js/bluebird.js +1160 -0
- package/templates/_auth/app/database.js +19 -0
- package/templates/_auth/app/models/user.js +22 -0
- package/templates/_auth/app/routes/auth-router.js +304 -0
- package/templates/_base/app/resources/html/layouts/main.html +55 -0
- package/templates/_base/app/resources/html/notFound.html +14 -0
- package/templates/_base/app/resources/index.html +27 -0
- package/templates/_base/app/resources/styles.css +9 -0
- package/templates/api/app/models/note.js +18 -0
- package/templates/api/app/routes/api.js +82 -0
- package/templates/api/app/routes/auth.js +11 -0
- package/templates/api/index.js +19 -0
- package/templates/api/template.json +13 -0
- package/templates/auth/app/mail.js +11 -0
- package/templates/auth/app/models/password_reset.js +18 -0
- package/templates/auth/app/resources/html/home.html +21 -0
- package/templates/auth/app/resources/html/partials/nav.html +2 -0
- package/templates/auth/app/resources/layouts/AppLayout.jsx +60 -0
- package/templates/auth/app/resources/main.jsx +18 -0
- package/templates/auth/app/resources/pages/Dashboard.jsx +51 -0
- package/templates/auth/app/resources/pages/ForgotPassword.jsx +34 -0
- package/templates/auth/app/resources/pages/Login.jsx +36 -0
- package/templates/auth/app/resources/pages/NotFound.jsx +16 -0
- package/templates/auth/app/resources/pages/Profile.jsx +99 -0
- package/templates/auth/app/resources/pages/Register.jsx +50 -0
- package/templates/auth/app/resources/pages/ResetPassword.jsx +50 -0
- package/templates/auth/app/resources/routes.jsx +54 -0
- package/templates/auth/app/resources/spa.js +29 -0
- package/templates/auth/app/routes/api.js +17 -0
- package/templates/auth/app/routes/auth.js +13 -0
- package/templates/auth/app/routes/web.js +21 -0
- package/templates/auth/index.js +19 -0
- package/templates/auth/template.json +15 -0
- package/templates/blank/app/models/.gitkeep +0 -0
- package/templates/blank/app/resources/html/home.html +27 -0
- package/templates/blank/app/resources/html/partials/nav.html +1 -0
- package/templates/blank/app/resources/main.jsx +16 -0
- package/templates/blank/app/resources/pages/Home.jsx +42 -0
- package/templates/blank/app/resources/pages/NotFound.jsx +27 -0
- package/templates/blank/app/resources/routes.jsx +15 -0
- package/templates/blank/app/resources/spa.js +24 -0
- package/templates/blank/app/routes/api.js +11 -0
- package/templates/blank/app/routes/web.js +21 -0
- package/templates/blank/index.js +13 -0
- package/templates/blank/template.json +12 -0
- package/templates/blog/app/lib/blog.js +149 -0
- package/templates/blog/app/models/post.js +22 -0
- package/templates/blog/app/resources/html/home.html +28 -0
- package/templates/blog/app/resources/html/not-found.html +5 -0
- package/templates/blog/app/resources/html/partials/nav.html +2 -0
- package/templates/blog/app/resources/html/partials/post-card.html +9 -0
- package/templates/blog/app/resources/html/post.html +8 -0
- package/templates/blog/app/resources/layouts/AdminLayout.jsx +54 -0
- package/templates/blog/app/resources/main.jsx +18 -0
- package/templates/blog/app/resources/pages/Login.jsx +31 -0
- package/templates/blog/app/resources/pages/NotFound.jsx +16 -0
- package/templates/blog/app/resources/pages/PostEditor.jsx +51 -0
- package/templates/blog/app/resources/pages/Posts.jsx +83 -0
- package/templates/blog/app/resources/pages/Register.jsx +43 -0
- package/templates/blog/app/resources/routes.jsx +51 -0
- package/templates/blog/app/resources/spa.js +25 -0
- package/templates/blog/app/resources/styles.css +40 -0
- package/templates/blog/app/routes/api.js +77 -0
- package/templates/blog/app/routes/auth.js +10 -0
- package/templates/blog/app/routes/web.js +114 -0
- package/templates/blog/index.js +21 -0
- package/templates/blog/template.json +14 -0
- package/vite.config.js +11 -0
- package/app/views/about.jsx +0 -98
- package/app/views/components/Header.jsx +0 -42
- package/app/views/components/LiveCounter.jsx +0 -66
- package/app/views/dashboard.jsx +0 -300
- package/app/views/index.jsx +0 -123
- package/app/views/layouts/main/view.jsx +0 -201
- package/app/views/legal/terms.html +0 -29
- package/app/views/login.jsx +0 -141
- package/core/actions.d.ts +0 -4
- package/core/actions.js +0 -329
- package/core/jsx.d.ts +0 -38
- package/core/jsx.js +0 -1432
- package/core/vite.d.ts +0 -3
- package/public/js/bluebird-client.js +0 -3161
- package/public/js/tailwind.js +0 -8
package/core/render.js
CHANGED
|
@@ -1,203 +1,518 @@
|
|
|
1
1
|
import Config from "./config.js";
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
h,
|
|
5
|
-
Fragment,
|
|
6
|
-
Island,
|
|
7
|
-
Client,
|
|
8
|
-
ErrorBoundary,
|
|
9
|
-
Suspense,
|
|
10
|
-
Head,
|
|
11
|
-
Title,
|
|
12
|
-
Meta,
|
|
13
|
-
useAction,
|
|
14
|
-
useActionState,
|
|
15
|
-
isJsxElement,
|
|
16
|
-
renderJsxToString,
|
|
17
|
-
serializeStyle,
|
|
18
|
-
} from "./jsx.js";
|
|
2
|
+
import { escapeHtml, isSafeHtml, SafeHtml } from "./html.js";
|
|
19
3
|
import RenderCache from "./render-cache.js";
|
|
20
4
|
import ViewLoader from "./view-loader.js";
|
|
5
|
+
import ViteBridge from "./vite.js";
|
|
6
|
+
import Csrf from "./csrf.js";
|
|
21
7
|
|
|
22
|
-
const
|
|
23
|
-
const DEBUG = props.debug;
|
|
8
|
+
const DEBUG = Config.props().debug;
|
|
24
9
|
const RENDER_CACHE_TTL = parseInt(process.env.RENDER_CACHE_TTL || "300", 10);
|
|
10
|
+
const CSRF_PLACEHOLDER = "__BB_CSRF_TOKEN__";
|
|
11
|
+
const IGNORED_CACHE_QUERY_KEYS = new Set(["_partial"]);
|
|
12
|
+
const MAX_PARTIAL_DEPTH = 16;
|
|
13
|
+
const MAX_COMPILED_CACHE = 500;
|
|
14
|
+
const BANNED_PROPS = new Set(["__proto__", "constructor", "prototype"]);
|
|
15
|
+
const TOKEN_REGEX = /(\{\{\{[\s\S]*?\}\}\}|\{\{[\s\S]*?\}\})/g;
|
|
16
|
+
|
|
17
|
+
const compiledCache = new Map();
|
|
25
18
|
|
|
26
19
|
/**
|
|
27
|
-
*
|
|
28
|
-
*
|
|
29
|
-
*
|
|
30
|
-
* @param {
|
|
31
|
-
* @
|
|
32
|
-
|
|
20
|
+
* Replaces the request CSRF token with a placeholder before storing HTML in a shared cache,
|
|
21
|
+
* so cached responses never leak one visitor's token to another.
|
|
22
|
+
* @param {string} body
|
|
23
|
+
* @param {string} token
|
|
24
|
+
* @returns {string}
|
|
25
|
+
*/
|
|
26
|
+
export function tokenizeForCache(body, token) {
|
|
27
|
+
if (!token || typeof body !== "string") return body;
|
|
28
|
+
return body.split(token).join(CSRF_PLACEHOLDER);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Restores the current request's CSRF token into a cached response.
|
|
33
|
+
* @param {string} body
|
|
34
|
+
* @param {string} token
|
|
35
|
+
* @returns {string}
|
|
36
|
+
*/
|
|
37
|
+
export function detokenizeFromCache(body, token) {
|
|
38
|
+
if (typeof body !== "string" || !body.includes(CSRF_PLACEHOLDER)) return body;
|
|
39
|
+
return body.split(CSRF_PLACEHOLDER).join(token || "");
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Adds the per-request CSP nonce (`res.locals.cspNonce`) to every inline `<script>` and `<style>` tag.
|
|
44
|
+
* @param {string} htmlStr
|
|
45
|
+
* @param {import('express').Response} res
|
|
46
|
+
* @returns {string}
|
|
47
|
+
*/
|
|
48
|
+
export function applyCspNonce(htmlStr, res) {
|
|
49
|
+
const nonce = res?.locals?.cspNonce;
|
|
50
|
+
if (!nonce || typeof htmlStr !== "string") return htmlStr;
|
|
51
|
+
return htmlStr.replace(/<(script|style)\b(?![^>]*\bnonce=)/gi, `<$1 nonce="${escapeHtml(nonce)}"`);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Removes the current request nonce from HTML before caching it.
|
|
56
|
+
* @param {string} htmlStr
|
|
57
|
+
* @param {import('express').Response} res
|
|
58
|
+
* @returns {string}
|
|
33
59
|
*/
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
60
|
+
export function stripCspNonce(htmlStr, res) {
|
|
61
|
+
const nonce = res?.locals?.cspNonce;
|
|
62
|
+
if (!nonce || typeof htmlStr !== "string") return htmlStr;
|
|
63
|
+
return htmlStr.split(` nonce="${escapeHtml(nonce)}"`).join("");
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Builds a render cache key from the full request path (`baseUrl` + `path`), an allowlist of query parameters,
|
|
68
|
+
* and the request language (`#lang=xx` when it is not the default `en`), so cached pages never leak across languages.
|
|
69
|
+
* Returns `null` when the request carries query parameters outside the allowlist.
|
|
70
|
+
* @param {string} prefix
|
|
71
|
+
* @param {import('express').Request} req
|
|
72
|
+
* @param {string[]} [queryKeys=[]]
|
|
73
|
+
* @param {string} [suffix=""]
|
|
74
|
+
* @returns {string|null}
|
|
75
|
+
*/
|
|
76
|
+
export function buildCacheKey(prefix, req, queryKeys = [], suffix = "") {
|
|
77
|
+
if (!req) return suffix ? `${prefix}:${suffix}` : prefix;
|
|
78
|
+
const query = req.query || {};
|
|
79
|
+
const allowed = new Set(queryKeys);
|
|
80
|
+
const parts = [];
|
|
81
|
+
for (const key of Object.keys(query).sort()) {
|
|
82
|
+
if (IGNORED_CACHE_QUERY_KEYS.has(key)) continue;
|
|
83
|
+
if (!allowed.has(key)) return null;
|
|
84
|
+
const val = query[key];
|
|
85
|
+
parts.push(`${encodeURIComponent(key)}=${encodeURIComponent(Array.isArray(val) ? val.join(",") : String(val))}`);
|
|
86
|
+
}
|
|
87
|
+
const relPath = req.path || (req.originalUrl || req.url || "").split("?")[0] || "/";
|
|
88
|
+
const pathname = req.baseUrl ? `${req.baseUrl}${relPath === "/" ? "" : relPath}` || "/" : relPath;
|
|
89
|
+
const base = suffix ? `${prefix}:${pathname}:${suffix}` : `${prefix}:${pathname}`;
|
|
90
|
+
const langPart = typeof req.lang === "string" && req.lang && req.lang !== "en" ? `#lang=${encodeURIComponent(req.lang)}` : "";
|
|
91
|
+
return `${base}${parts.length ? `?${parts.join("&")}` : ""}${langPart}`;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Checks whether a request carries authentication credentials.
|
|
96
|
+
* @param {import('express').Request} req
|
|
97
|
+
* @returns {boolean}
|
|
98
|
+
*/
|
|
99
|
+
export function isAuthenticatedRequest(req) {
|
|
100
|
+
return Boolean(req?.user || req?.cookies?.auth || req?.headers?.authorization);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Compiles an HTML template string containing `{{ }}` directives into an AST.
|
|
105
|
+
* @param {string} source
|
|
106
|
+
* @returns {Array<Object>}
|
|
107
|
+
*/
|
|
108
|
+
function compileTemplate(source) {
|
|
109
|
+
if (typeof source !== "string") return [];
|
|
110
|
+
if (!DEBUG && compiledCache.has(source)) {
|
|
111
|
+
return compiledCache.get(source);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
const root = { type: "root", body: [] };
|
|
115
|
+
const stack = [{ node: root, branch: "body" }];
|
|
116
|
+
const pushNode = (node) => {
|
|
117
|
+
const top = stack[stack.length - 1];
|
|
118
|
+
top.node[top.branch].push(node);
|
|
119
|
+
};
|
|
120
|
+
|
|
121
|
+
let lastIndex = 0;
|
|
122
|
+
TOKEN_REGEX.lastIndex = 0;
|
|
123
|
+
let match;
|
|
124
|
+
|
|
125
|
+
while ((match = TOKEN_REGEX.exec(source)) !== null) {
|
|
126
|
+
const token = match[0];
|
|
127
|
+
if (match.index > 0 && source[match.index - 1] === "\\") {
|
|
128
|
+
pushNode({ type: "text", value: source.slice(lastIndex, match.index - 1) + token });
|
|
129
|
+
lastIndex = TOKEN_REGEX.lastIndex;
|
|
130
|
+
continue;
|
|
131
|
+
}
|
|
132
|
+
if (match.index > lastIndex) {
|
|
133
|
+
pushNode({ type: "text", value: source.slice(lastIndex, match.index) });
|
|
134
|
+
}
|
|
135
|
+
lastIndex = TOKEN_REGEX.lastIndex;
|
|
136
|
+
|
|
137
|
+
if (token.startsWith("{{{") && token.endsWith("}}}")) {
|
|
138
|
+
const expr = token.slice(3, -3).trim();
|
|
139
|
+
const viteMatch = expr.match(/^vite\s+(.+)$/);
|
|
140
|
+
if (viteMatch) {
|
|
141
|
+
pushNode({ type: "vite", entry: viteMatch[1].trim().replace(/^['"]|['"]$/g, "") });
|
|
142
|
+
} else {
|
|
143
|
+
pushNode({ type: "raw", expr });
|
|
144
|
+
}
|
|
145
|
+
continue;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
const inner = token.slice(2, -2).trim();
|
|
149
|
+
if (!inner || inner.startsWith("!")) {
|
|
150
|
+
continue;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
if (inner.startsWith(">")) {
|
|
154
|
+
pushNode({ type: "partial", name: inner.slice(1).trim() });
|
|
155
|
+
continue;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
const viteMatch = inner.match(/^vite\s+(.+)$/);
|
|
159
|
+
if (viteMatch) {
|
|
160
|
+
pushNode({ type: "vite", entry: viteMatch[1].trim().replace(/^['"]|['"]$/g, "") });
|
|
161
|
+
continue;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
const ifMatch = inner.match(/^#?if\s+([\s\S]+)$/);
|
|
165
|
+
if (ifMatch) {
|
|
166
|
+
const node = { type: "if", expr: ifMatch[1].trim(), then: [], else: [] };
|
|
167
|
+
pushNode(node);
|
|
168
|
+
stack.push({ node, branch: "then" });
|
|
169
|
+
continue;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
if (inner === "else" || inner === "#else") {
|
|
173
|
+
const top = stack[stack.length - 1];
|
|
174
|
+
if (top && (top.node.type === "if" || top.node.type === "each")) {
|
|
175
|
+
top.branch = "else";
|
|
176
|
+
}
|
|
177
|
+
continue;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
if (inner === "/if" || inner === "endif") {
|
|
181
|
+
if (stack.length > 1 && stack[stack.length - 1].node.type === "if") {
|
|
182
|
+
stack.pop();
|
|
183
|
+
}
|
|
184
|
+
continue;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
const eachMatch = inner.match(/^#?each\s+([\s\S]+)$/);
|
|
188
|
+
if (eachMatch) {
|
|
189
|
+
const node = { type: "each", expr: eachMatch[1].trim(), body: [], else: [] };
|
|
190
|
+
pushNode(node);
|
|
191
|
+
stack.push({ node, branch: "body" });
|
|
192
|
+
continue;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
if (inner === "/each" || inner === "endeach") {
|
|
196
|
+
if (stack.length > 1 && stack[stack.length - 1].node.type === "each") {
|
|
197
|
+
stack.pop();
|
|
198
|
+
}
|
|
199
|
+
continue;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
pushNode({ type: "var", expr: inner });
|
|
37
203
|
}
|
|
38
|
-
|
|
39
|
-
|
|
204
|
+
|
|
205
|
+
if (lastIndex < source.length) {
|
|
206
|
+
pushNode({ type: "text", value: source.slice(lastIndex) });
|
|
40
207
|
}
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
208
|
+
|
|
209
|
+
if (!DEBUG) {
|
|
210
|
+
if (compiledCache.size >= MAX_COMPILED_CACHE) {
|
|
211
|
+
const firstKey = compiledCache.keys().next().value;
|
|
212
|
+
if (firstKey !== undefined) compiledCache.delete(firstKey);
|
|
46
213
|
}
|
|
47
|
-
|
|
214
|
+
compiledCache.set(source, root.body);
|
|
48
215
|
}
|
|
49
|
-
|
|
216
|
+
|
|
217
|
+
return root.body;
|
|
50
218
|
}
|
|
51
219
|
|
|
52
220
|
/**
|
|
53
|
-
*
|
|
54
|
-
*
|
|
55
|
-
*
|
|
221
|
+
* Safely retrieves an own property or collection `.length` without traversing prototypes.
|
|
222
|
+
* @param {any} target
|
|
223
|
+
* @param {string} key
|
|
224
|
+
* @returns {any}
|
|
56
225
|
*/
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
const
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
226
|
+
function safeProp(target, key) {
|
|
227
|
+
if (target === null || target === undefined || BANNED_PROPS.has(key)) return undefined;
|
|
228
|
+
if ((Array.isArray(target) || typeof target === "string") && key === "length") {
|
|
229
|
+
return target.length;
|
|
230
|
+
}
|
|
231
|
+
if (typeof target === "object" && Object.prototype.hasOwnProperty.call(target, key)) {
|
|
232
|
+
return target[key];
|
|
233
|
+
}
|
|
234
|
+
return undefined;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/**
|
|
238
|
+
* Resolves a dot-delimited expression or literal across the scope stack.
|
|
239
|
+
* @param {Array<Object>} scopes
|
|
240
|
+
* @param {string} rawExpr
|
|
241
|
+
* @returns {any}
|
|
242
|
+
*/
|
|
243
|
+
function resolveExpr(scopes, rawExpr) {
|
|
244
|
+
const expr = String(rawExpr || "").trim();
|
|
245
|
+
if (!expr) return undefined;
|
|
246
|
+
if (expr === "true") return true;
|
|
247
|
+
if (expr === "false") return false;
|
|
248
|
+
if (expr === "null") return null;
|
|
249
|
+
if (/^-?\d+(\.\d+)?$/.test(expr)) return Number(expr);
|
|
250
|
+
if ((expr.startsWith('"') && expr.endsWith('"')) || (expr.startsWith("'") && expr.endsWith("'"))) {
|
|
251
|
+
return expr.slice(1, -1);
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
if (expr === "." || expr === "this") {
|
|
255
|
+
const top = scopes[0];
|
|
256
|
+
return top && typeof top === "object" && "__this__" in top ? top.__this__ : top;
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
let depthOffset = 0;
|
|
260
|
+
let pathStr = expr;
|
|
261
|
+
while (pathStr.startsWith("../")) {
|
|
262
|
+
depthOffset++;
|
|
263
|
+
pathStr = pathStr.slice(3);
|
|
264
|
+
}
|
|
265
|
+
if (pathStr.startsWith("./")) {
|
|
266
|
+
pathStr = pathStr.slice(2);
|
|
267
|
+
} else if (pathStr.startsWith("this.")) {
|
|
268
|
+
pathStr = pathStr.slice(5);
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
const segments = pathStr.split(".");
|
|
272
|
+
const firstSeg = segments[0];
|
|
273
|
+
if (BANNED_PROPS.has(firstSeg)) return undefined;
|
|
274
|
+
|
|
275
|
+
let base = undefined;
|
|
276
|
+
let found = false;
|
|
277
|
+
for (let i = depthOffset; i < scopes.length; i++) {
|
|
278
|
+
const scope = scopes[i];
|
|
279
|
+
if (scope === null || scope === undefined) continue;
|
|
280
|
+
const candidateTarget = typeof scope === "object" && "__this__" in scope && firstSeg !== "@index" && firstSeg !== "@number" && firstSeg !== "@first" && firstSeg !== "@last"
|
|
281
|
+
? (typeof scope.__this__ === "object" && scope.__this__ !== null && Object.prototype.hasOwnProperty.call(scope.__this__, firstSeg) ? scope.__this__ : scope)
|
|
282
|
+
: scope;
|
|
283
|
+
if (typeof candidateTarget === "object" && Object.prototype.hasOwnProperty.call(candidateTarget, firstSeg)) {
|
|
284
|
+
base = candidateTarget[firstSeg];
|
|
285
|
+
found = true;
|
|
286
|
+
break;
|
|
93
287
|
}
|
|
94
|
-
if (
|
|
95
|
-
|
|
96
|
-
|
|
288
|
+
if ((Array.isArray(candidateTarget) || typeof candidateTarget === "string") && firstSeg === "length") {
|
|
289
|
+
base = candidateTarget.length;
|
|
290
|
+
found = true;
|
|
291
|
+
break;
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
if (!found) return undefined;
|
|
296
|
+
let current = base;
|
|
297
|
+
for (let i = 1; i < segments.length; i++) {
|
|
298
|
+
current = safeProp(current, segments[i]);
|
|
299
|
+
if (current === undefined || current === null) return current;
|
|
300
|
+
}
|
|
301
|
+
return current;
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
/**
|
|
305
|
+
* Evaluates a conditional expression supporting negation and equality operators.
|
|
306
|
+
* @param {Array<Object>} scopes
|
|
307
|
+
* @param {string} rawExpr
|
|
308
|
+
* @returns {boolean}
|
|
309
|
+
*/
|
|
310
|
+
function evaluateCondition(scopes, rawExpr) {
|
|
311
|
+
const expr = String(rawExpr || "").trim();
|
|
312
|
+
if (!expr) return false;
|
|
313
|
+
|
|
314
|
+
const opMatch = expr.match(/^([\s\S]+?)\s*(===|!==|==|!=)\s*([\s\S]+)$/);
|
|
315
|
+
if (opMatch) {
|
|
316
|
+
const left = resolveExpr(scopes, opMatch[1]);
|
|
317
|
+
const op = opMatch[2];
|
|
318
|
+
const right = resolveExpr(scopes, opMatch[3]);
|
|
319
|
+
if (op === "===") return left === right;
|
|
320
|
+
if (op === "!==") return left !== right;
|
|
321
|
+
if (op === "==") return left == right;
|
|
322
|
+
return left != right;
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
if (expr.startsWith("!")) {
|
|
326
|
+
return !evaluateCondition(scopes, expr.slice(1));
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
const val = resolveExpr(scopes, expr);
|
|
330
|
+
return Array.isArray(val) ? val.length > 0 : Boolean(val);
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
/**
|
|
334
|
+
* Formats an interpolated value as escaped HTML unless it is SafeHtml or raw.
|
|
335
|
+
* @param {any} val
|
|
336
|
+
* @param {boolean} raw
|
|
337
|
+
* @returns {string}
|
|
338
|
+
*/
|
|
339
|
+
function formatOutput(val, raw = false) {
|
|
340
|
+
if (val === null || val === undefined || val === false) return "";
|
|
341
|
+
if (isSafeHtml(val)) return val.toString();
|
|
342
|
+
return raw ? String(val) : escapeHtml(val);
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
/**
|
|
346
|
+
* Resolves a Vite asset tag for `{{ vite "..." }}` directives.
|
|
347
|
+
* @param {string} entry
|
|
348
|
+
* @param {Object} ctx
|
|
349
|
+
* @returns {string}
|
|
350
|
+
*/
|
|
351
|
+
function resolveViteTag(entry, ctx) {
|
|
352
|
+
const bridge = ctx?.vite || ViteBridge.from(ctx?.req) || ViteBridge.from(ctx?.res);
|
|
353
|
+
if (bridge) {
|
|
354
|
+
return bridge.assetTags(entry).all;
|
|
355
|
+
}
|
|
356
|
+
const fallback = new ViteBridge({ root: Config.appDir(), dev: DEBUG });
|
|
357
|
+
if (!DEBUG && fallback.loadManifestSync()) {
|
|
358
|
+
return fallback.assetTags(entry).all;
|
|
359
|
+
}
|
|
360
|
+
const clean = String(entry || "").replace(/^\/+/, "");
|
|
361
|
+
if (/\.(css|scss|sass|less|styl)$/i.test(clean)) {
|
|
362
|
+
return `<link rel="stylesheet" href="/${escapeHtml(clean)}">`;
|
|
363
|
+
}
|
|
364
|
+
return `<script type="module" src="/${escapeHtml(clean)}"></script>`;
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
/**
|
|
368
|
+
* Evaluates a compiled AST against a scope stack.
|
|
369
|
+
* @param {Array<Object>} nodes
|
|
370
|
+
* @param {Array<Object>} scopes
|
|
371
|
+
* @param {Object} ctx
|
|
372
|
+
* @param {number} depth
|
|
373
|
+
* @returns {Promise<string>}
|
|
374
|
+
*/
|
|
375
|
+
async function evaluateAst(nodes, scopes, ctx, depth = 0) {
|
|
376
|
+
let out = "";
|
|
377
|
+
for (let i = 0; i < nodes.length; i++) {
|
|
378
|
+
const node = nodes[i];
|
|
379
|
+
if (node.type === "text") {
|
|
380
|
+
out += node.value;
|
|
381
|
+
} else if (node.type === "var") {
|
|
382
|
+
out += formatOutput(resolveExpr(scopes, node.expr), false);
|
|
383
|
+
} else if (node.type === "raw") {
|
|
384
|
+
out += formatOutput(resolveExpr(scopes, node.expr), true);
|
|
385
|
+
} else if (node.type === "vite") {
|
|
386
|
+
out += resolveViteTag(node.entry, ctx);
|
|
387
|
+
} else if (node.type === "partial") {
|
|
388
|
+
if (depth >= MAX_PARTIAL_DEPTH) continue;
|
|
389
|
+
const partial = await ViewLoader.loadPartial(node.name);
|
|
390
|
+
if (partial?.content) {
|
|
391
|
+
const partialAst = compileTemplate(partial.content);
|
|
392
|
+
out += await evaluateAst(partialAst, scopes, ctx, depth + 1);
|
|
393
|
+
}
|
|
394
|
+
} else if (node.type === "if") {
|
|
395
|
+
const branch = evaluateCondition(scopes, node.expr) ? node.then : node.else;
|
|
396
|
+
if (branch.length > 0) {
|
|
397
|
+
out += await evaluateAst(branch, scopes, ctx, depth);
|
|
398
|
+
}
|
|
399
|
+
} else if (node.type === "each") {
|
|
400
|
+
const list = resolveExpr(scopes, node.expr);
|
|
401
|
+
if (Array.isArray(list) && list.length > 0) {
|
|
402
|
+
for (let idx = 0; idx < list.length; idx++) {
|
|
403
|
+
const item = list[idx];
|
|
404
|
+
const iterScope =
|
|
405
|
+
item && typeof item === "object" && !Array.isArray(item)
|
|
406
|
+
? {
|
|
407
|
+
...item,
|
|
408
|
+
__this__: item,
|
|
409
|
+
"@index": idx,
|
|
410
|
+
"@number": idx + 1,
|
|
411
|
+
"@first": idx === 0,
|
|
412
|
+
"@last": idx === list.length - 1,
|
|
413
|
+
}
|
|
414
|
+
: {
|
|
415
|
+
__this__: item,
|
|
416
|
+
"@index": idx,
|
|
417
|
+
"@number": idx + 1,
|
|
418
|
+
"@first": idx === 0,
|
|
419
|
+
"@last": idx === list.length - 1,
|
|
420
|
+
};
|
|
421
|
+
out += await evaluateAst(node.body, [iterScope, ...scopes], ctx, depth);
|
|
422
|
+
}
|
|
423
|
+
} else if (node.else.length > 0) {
|
|
424
|
+
out += await evaluateAst(node.else, scopes, ctx, depth);
|
|
425
|
+
}
|
|
97
426
|
}
|
|
98
|
-
const styleStr =
|
|
99
|
-
typeof options.style === "string" ? options.style : serializeStyle(styleObj);
|
|
100
|
-
const styleAttr = styleStr ? ` style="${escapeHtml(styleStr)}"` : "";
|
|
101
|
-
|
|
102
|
-
const serializedProps = escapeHtml(safeJson(islandProps));
|
|
103
|
-
const rawFallback =
|
|
104
|
-
options.skeleton !== undefined
|
|
105
|
-
? options.skeleton
|
|
106
|
-
: options.fallback !== undefined
|
|
107
|
-
? options.fallback
|
|
108
|
-
: "";
|
|
109
|
-
const fallbackStr = isSafeHtml(rawFallback)
|
|
110
|
-
? rawFallback.toString()
|
|
111
|
-
: typeof rawFallback === "string"
|
|
112
|
-
? rawFallback
|
|
113
|
-
: "";
|
|
114
|
-
|
|
115
|
-
return `<${tag} data-island="${escapeHtml(resolvedName)}" data-props="${serializedProps}"${persistAttr}${hydrateAttr}${classAttr}${styleAttr}>${fallbackStr}</${tag}>`;
|
|
116
427
|
}
|
|
428
|
+
return out;
|
|
429
|
+
}
|
|
117
430
|
|
|
431
|
+
/**
|
|
432
|
+
* HTML SSR template rendering engine for Bluebird.js.
|
|
433
|
+
* Supports `.html` views, `{{var}}`, `{{{raw}}}`, `{{if}}` / `{{else}}`, `{{each}}`,
|
|
434
|
+
* `{{> partial}}`, `{{ vite "entry" }}`, HTML layouts (`{{{ body }}}`), and multi-tier caching.
|
|
435
|
+
*/
|
|
436
|
+
export class Render {
|
|
118
437
|
/**
|
|
119
|
-
*
|
|
120
|
-
* @param {string}
|
|
121
|
-
* @param {Object} [data={}]
|
|
438
|
+
* Renders an HTML template string directly with the supplied data context.
|
|
439
|
+
* @param {string} template
|
|
440
|
+
* @param {Object} [data={}]
|
|
441
|
+
* @param {Object} [ctx={}]
|
|
122
442
|
* @returns {Promise<string>}
|
|
123
443
|
*/
|
|
124
|
-
static async
|
|
125
|
-
const
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
if (view.type === "js" || view.type === "jsx") {
|
|
129
|
-
const renderFn =
|
|
130
|
-
typeof view.module.default === "function" ? view.module.default : view.module;
|
|
131
|
-
const ctx = { data };
|
|
132
|
-
const output = await renderFn(data, ctx);
|
|
133
|
-
return resolveOutputToHtml(output, ctx);
|
|
134
|
-
}
|
|
135
|
-
|
|
136
|
-
return view.content || "";
|
|
444
|
+
static async renderString(template, data = {}, ctx = {}) {
|
|
445
|
+
const ast = compileTemplate(template);
|
|
446
|
+
const scope = data && typeof data === "object" ? { ...data } : {};
|
|
447
|
+
return evaluateAst(ast, [scope], ctx, 0);
|
|
137
448
|
}
|
|
138
449
|
|
|
139
450
|
/**
|
|
140
|
-
*
|
|
141
|
-
* @param {
|
|
142
|
-
* @param {
|
|
143
|
-
* @param {Object} [
|
|
144
|
-
* @returns {Promise<
|
|
451
|
+
* Renders an HTML partial or view file to an HTML string without layouts.
|
|
452
|
+
* @param {string} viewName
|
|
453
|
+
* @param {Object} [data={}]
|
|
454
|
+
* @param {Object} [ctx={}]
|
|
455
|
+
* @returns {Promise<string>}
|
|
145
456
|
*/
|
|
146
|
-
static async
|
|
147
|
-
|
|
457
|
+
static async component(viewName, data = {}, ctx = {}) {
|
|
458
|
+
const view = (await ViewLoader.loadPartial(viewName)) || (await ViewLoader.load(viewName));
|
|
459
|
+
if (!view?.content) return "";
|
|
460
|
+
return this.renderString(view.content, data, ctx);
|
|
148
461
|
}
|
|
149
462
|
|
|
150
463
|
/**
|
|
151
|
-
*
|
|
152
|
-
*
|
|
153
|
-
*
|
|
154
|
-
* @param {
|
|
155
|
-
* @param {
|
|
156
|
-
* @param {Object} [options={}]
|
|
157
|
-
* @param {
|
|
464
|
+
* Renders and sends an HTML view (`app/resources/html/*.html`) with `{{ }}` interpolation, optional layout,
|
|
465
|
+
* browser/server caching, CSRF token restoration, and CSP nonce injection.
|
|
466
|
+
* @param {import('express').Response} res
|
|
467
|
+
* @param {string} viewName
|
|
468
|
+
* @param {Object} [data={}]
|
|
469
|
+
* @param {number|Object} [options={}]
|
|
470
|
+
* @param {string|false} [options.layout]
|
|
471
|
+
* @param {number} [options.cache]
|
|
472
|
+
* @param {number} [options.ttl]
|
|
473
|
+
* @param {string[]} [options.query]
|
|
474
|
+
* @param {string[]} [options.cacheQuery]
|
|
475
|
+
* @param {boolean} [options.raw=false]
|
|
158
476
|
* @returns {Promise<any>}
|
|
159
477
|
*/
|
|
160
|
-
static async html(res,
|
|
161
|
-
const
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
}
|
|
165
|
-
|
|
166
|
-
if (options.ttl && options.ttl > 0 && !DEBUG) {
|
|
167
|
-
res.set("Cache-Control", `public, max-age=${options.ttl}`);
|
|
168
|
-
}
|
|
169
|
-
|
|
170
|
-
res.set("Content-Type", "text/html; charset=utf-8");
|
|
171
|
-
return res.send(view.content);
|
|
478
|
+
static async html(res, viewName, data = {}, options = {}) {
|
|
479
|
+
const templateData = data && typeof data === "object" ? data : {};
|
|
480
|
+
const normalizedOptions = typeof options === "number" ? { cache: options } : options || {};
|
|
481
|
+
return this.send(res, viewName, templateData, normalizedOptions);
|
|
172
482
|
}
|
|
173
483
|
|
|
174
484
|
/**
|
|
175
|
-
*
|
|
176
|
-
*
|
|
177
|
-
* @param {import('express').Response} res
|
|
178
|
-
* @param {string} viewName
|
|
179
|
-
* @param {Object} [data={}]
|
|
180
|
-
* @param {number
|
|
485
|
+
* Renders and sends an HTML view (`app/resources/html/*.html`) wrapped in an optional layout.
|
|
486
|
+
* Never mutates the caller's `data` object and never leaks CSRF tokens through shared caches.
|
|
487
|
+
* @param {import('express').Response} res
|
|
488
|
+
* @param {string} viewName
|
|
489
|
+
* @param {Object} [data={}]
|
|
490
|
+
* @param {number|{ttl?: number, cache?: number, layout?: string|false, query?: string[], cacheQuery?: string[], raw?: boolean}} [ttlOrOptions]
|
|
181
491
|
* @returns {Promise<any>}
|
|
182
492
|
*/
|
|
183
|
-
static async send(res, viewName, data = {},
|
|
184
|
-
const
|
|
185
|
-
const
|
|
186
|
-
const
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
const
|
|
192
|
-
|
|
493
|
+
static async send(res, viewName, data = {}, ttlOrOptions) {
|
|
494
|
+
const req = res.req;
|
|
495
|
+
const opts = this._normalizeOptions(ttlOrOptions, data);
|
|
496
|
+
const partialRequest =
|
|
497
|
+
opts.layout === false ||
|
|
498
|
+
req?.headers?.["x-bluebird-partial"] === "1" ||
|
|
499
|
+
req?.query?._partial === "1";
|
|
500
|
+
|
|
501
|
+
const canCache = opts.cache > 0 && !DEBUG && !isAuthenticatedRequest(req);
|
|
502
|
+
const cacheKey = canCache
|
|
503
|
+
? buildCacheKey("view", req, opts.query, `${partialRequest ? "partial:" : ""}${viewName}`)
|
|
504
|
+
: null;
|
|
505
|
+
|
|
506
|
+
if (cacheKey) {
|
|
193
507
|
const cached = await RenderCache.lookup(cacheKey);
|
|
194
508
|
if (cached) {
|
|
195
509
|
res.set("Content-Type", "text/html; charset=utf-8");
|
|
196
|
-
if (isPartialRequest) {
|
|
197
|
-
res.set("X-Bluebird-Partial", "1");
|
|
198
|
-
}
|
|
199
510
|
res.set("X-Bluebird-Cache", "HIT");
|
|
200
|
-
|
|
511
|
+
if (opts.ttl > 0 && !DEBUG) {
|
|
512
|
+
res.set("Cache-Control", `public, max-age=${opts.ttl}`);
|
|
513
|
+
}
|
|
514
|
+
const token = typeof res.cookie === "function" ? Csrf.ensure(req, res) : "";
|
|
515
|
+
return res.send(applyCspNonce(detokenizeFromCache(cached, token), res));
|
|
201
516
|
}
|
|
202
517
|
}
|
|
203
518
|
|
|
@@ -206,523 +521,218 @@ export class Render {
|
|
|
206
521
|
return res.status(404).json({ message: `View '${viewName}' not found.` });
|
|
207
522
|
}
|
|
208
523
|
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
secure: Config.isDesktop() ? false : Boolean(!DEBUG),
|
|
228
|
-
path: "/",
|
|
229
|
-
});
|
|
230
|
-
} catch {}
|
|
231
|
-
}
|
|
232
|
-
const flash =
|
|
233
|
-
locals.flash ||
|
|
234
|
-
(typeof res.req?.flash === "function" ? res.req.flash() : null) ||
|
|
235
|
-
null;
|
|
236
|
-
|
|
237
|
-
const ctx = {
|
|
238
|
-
req: res.req,
|
|
239
|
-
res,
|
|
240
|
-
user: res.req?.user,
|
|
241
|
-
csrfToken,
|
|
242
|
-
flash,
|
|
243
|
-
locals,
|
|
244
|
-
appLocals,
|
|
245
|
-
data: viewData,
|
|
246
|
-
};
|
|
247
|
-
|
|
248
|
-
if (typeof view.module.load === "function") {
|
|
249
|
-
const loadedData = await view.module.load(ctx);
|
|
250
|
-
if (loadedData && typeof loadedData === "object") {
|
|
251
|
-
Object.assign(viewData, loadedData);
|
|
252
|
-
}
|
|
253
|
-
}
|
|
254
|
-
|
|
255
|
-
const mergedData = {
|
|
256
|
-
...appLocals,
|
|
257
|
-
...locals,
|
|
258
|
-
csrfToken,
|
|
259
|
-
...(flash ? { flash } : {}),
|
|
260
|
-
...viewData,
|
|
261
|
-
};
|
|
524
|
+
const csrfToken = typeof res.cookie === "function" ? Csrf.ensure(req, res) : "";
|
|
525
|
+
const lang = data?.lang || res.locals?.lang || req?.lang || "en";
|
|
526
|
+
const viewData = {
|
|
527
|
+
...(req?.app?.locals || {}),
|
|
528
|
+
...(res.locals || {}),
|
|
529
|
+
lang,
|
|
530
|
+
csrf: csrfToken,
|
|
531
|
+
csrfToken,
|
|
532
|
+
csrfField: new SafeHtml(`<input type="hidden" name="_csrf" value="${escapeHtml(csrfToken)}">`),
|
|
533
|
+
url: req?.originalUrl || req?.url || "/",
|
|
534
|
+
path: req?.path || "/",
|
|
535
|
+
appUrl: Config.props().appUrl,
|
|
536
|
+
...data,
|
|
537
|
+
};
|
|
538
|
+
delete viewData._cache;
|
|
539
|
+
delete viewData._layout;
|
|
540
|
+
delete viewData._raw;
|
|
541
|
+
delete viewData._viteBridge;
|
|
262
542
|
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
543
|
+
const renderCtx = {
|
|
544
|
+
req,
|
|
545
|
+
res,
|
|
546
|
+
vite: ViteBridge.from(req) || ViteBridge.from(res),
|
|
547
|
+
};
|
|
267
548
|
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
? view.module.layout
|
|
273
|
-
: "main";
|
|
549
|
+
let body = view.content || "";
|
|
550
|
+
if (!opts.raw) {
|
|
551
|
+
body = await this.renderString(body, viewData, renderCtx);
|
|
552
|
+
}
|
|
274
553
|
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
if (view.module.head) {
|
|
285
|
-
const declaredHead =
|
|
286
|
-
typeof view.module.head === "function"
|
|
287
|
-
? await view.module.head(mergedData, ctx)
|
|
288
|
-
: view.module.head;
|
|
289
|
-
if (declaredHead && typeof declaredHead === "object") {
|
|
290
|
-
Object.assign(headData, declaredHead);
|
|
291
|
-
}
|
|
292
|
-
if (ctx.title) {
|
|
293
|
-
headData.title = ctx.title;
|
|
294
|
-
}
|
|
295
|
-
}
|
|
296
|
-
|
|
297
|
-
const layoutFn =
|
|
298
|
-
typeof layoutView.module.default === "function"
|
|
299
|
-
? layoutView.module.default
|
|
300
|
-
: layoutView.module;
|
|
301
|
-
|
|
302
|
-
const safeBody = html.raw(bodyHtml);
|
|
303
|
-
const layoutOutput = await layoutFn({
|
|
304
|
-
body: safeBody,
|
|
305
|
-
content: safeBody,
|
|
306
|
-
children: safeBody,
|
|
307
|
-
head: headData,
|
|
308
|
-
ctx,
|
|
309
|
-
data: mergedData,
|
|
310
|
-
});
|
|
311
|
-
|
|
312
|
-
rendered = await resolveOutputToHtml(layoutOutput, ctx);
|
|
313
|
-
|
|
314
|
-
if (ctx.headTags && ctx.headTags.length > 0 && rendered.includes("</head>")) {
|
|
315
|
-
if (ctx.title) {
|
|
316
|
-
rendered = rendered.replace(
|
|
317
|
-
/<title>[^<]*<\/title>/i,
|
|
318
|
-
`<title>${escapeHtml(ctx.title)}</title>`
|
|
319
|
-
);
|
|
320
|
-
}
|
|
321
|
-
const extraTags = ctx.headTags.filter(
|
|
322
|
-
(t) => !t.startsWith("<title>") && !rendered.includes(t)
|
|
323
|
-
);
|
|
324
|
-
if (extraTags.length > 0) {
|
|
325
|
-
rendered = rendered.replace("</head>", ` ${extraTags.join("\n ")}\n</head>`);
|
|
326
|
-
}
|
|
327
|
-
}
|
|
328
|
-
} else {
|
|
329
|
-
rendered = bodyHtml;
|
|
330
|
-
}
|
|
554
|
+
let rendered = body;
|
|
555
|
+
if (opts.layout && !partialRequest) {
|
|
556
|
+
const layout = await ViewLoader.loadLayout(opts.layout);
|
|
557
|
+
if (layout?.content) {
|
|
558
|
+
const layoutData = {
|
|
559
|
+
...viewData,
|
|
560
|
+
body: new SafeHtml(body),
|
|
561
|
+
};
|
|
562
|
+
rendered = await this.renderString(layout.content, layoutData, renderCtx);
|
|
331
563
|
}
|
|
332
|
-
} else {
|
|
333
|
-
rendered = view.content || "";
|
|
334
564
|
}
|
|
335
565
|
|
|
336
|
-
if (
|
|
337
|
-
await
|
|
566
|
+
if (DEBUG && !partialRequest && renderCtx.vite?.mode === "dev" && /<head[\s>]/i.test(rendered)) {
|
|
567
|
+
rendered = await renderCtx.vite.transformHtml(req?.originalUrl || req?.url || "/", rendered);
|
|
338
568
|
}
|
|
339
569
|
|
|
340
|
-
res.
|
|
341
|
-
|
|
342
|
-
|
|
570
|
+
if (cacheKey && (res.statusCode === 200 || res.statusCode === undefined)) {
|
|
571
|
+
await RenderCache.store(cacheKey, tokenizeForCache(rendered, csrfToken), opts.cache);
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
if (opts.ttl > 0 && !DEBUG) {
|
|
575
|
+
res.set("Cache-Control", `public, max-age=${opts.ttl}`);
|
|
343
576
|
}
|
|
577
|
+
res.set("Content-Type", "text/html; charset=utf-8");
|
|
344
578
|
res.set("X-Bluebird-Cache", "MISS");
|
|
345
|
-
return res.send(rendered);
|
|
579
|
+
return res.send(applyCspNonce(rendered, res));
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
/**
|
|
583
|
+
* Sends a partial HTML view without applying a layout.
|
|
584
|
+
* @param {import('express').Response} res
|
|
585
|
+
* @param {string} partialName
|
|
586
|
+
* @param {Object} [data={}]
|
|
587
|
+
* @returns {Promise<any>}
|
|
588
|
+
*/
|
|
589
|
+
static async partial(res, partialName, data = {}) {
|
|
590
|
+
const view = (await ViewLoader.loadPartial(partialName)) || (await ViewLoader.load(partialName));
|
|
591
|
+
if (!view) {
|
|
592
|
+
return res.status(404).json({ message: `Partial '${partialName}' not found.` });
|
|
593
|
+
}
|
|
594
|
+
const req = res.req;
|
|
595
|
+
const csrfToken = typeof res.cookie === "function" ? Csrf.ensure(req, res) : "";
|
|
596
|
+
const lang = data?.lang || res.locals?.lang || req?.lang || "en";
|
|
597
|
+
const viewData = {
|
|
598
|
+
...(req?.app?.locals || {}),
|
|
599
|
+
...(res.locals || {}),
|
|
600
|
+
lang,
|
|
601
|
+
csrf: csrfToken,
|
|
602
|
+
csrfToken,
|
|
603
|
+
csrfField: new SafeHtml(`<input type="hidden" name="_csrf" value="${escapeHtml(csrfToken)}">`),
|
|
604
|
+
...data,
|
|
605
|
+
};
|
|
606
|
+
delete viewData._cache;
|
|
607
|
+
delete viewData._layout;
|
|
608
|
+
delete viewData._viteBridge;
|
|
609
|
+
|
|
610
|
+
const rendered = await this.renderString(view.content, viewData, {
|
|
611
|
+
req,
|
|
612
|
+
res,
|
|
613
|
+
vite: ViteBridge.from(req) || ViteBridge.from(res),
|
|
614
|
+
});
|
|
615
|
+
res.set("Content-Type", "text/html; charset=utf-8");
|
|
616
|
+
return res.send(applyCspNonce(rendered, res));
|
|
346
617
|
}
|
|
347
618
|
|
|
348
619
|
/**
|
|
349
|
-
* Express route handler
|
|
350
|
-
*
|
|
351
|
-
* @param {
|
|
352
|
-
* @param {Object
|
|
353
|
-
* @
|
|
354
|
-
* @returns {Function} Express route handler.
|
|
620
|
+
* Creates an Express route handler that renders an HTML view with optional dynamic data loader.
|
|
621
|
+
* @param {string} viewName
|
|
622
|
+
* @param {Object|Function} [dataOrFn={}] - Static data object or `(req, res) => data`.
|
|
623
|
+
* @param {number|Object} [options={}]
|
|
624
|
+
* @returns {Function}
|
|
355
625
|
*/
|
|
356
|
-
static view(viewName, dataOrFn = {},
|
|
626
|
+
static view(viewName, dataOrFn = {}, options = {}) {
|
|
357
627
|
return async (req, res) => {
|
|
358
|
-
const
|
|
359
|
-
return Render.send(res, viewName,
|
|
628
|
+
const data = typeof dataOrFn === "function" ? await dataOrFn(req, res) : dataOrFn;
|
|
629
|
+
return Render.send(res, viewName, data, options);
|
|
630
|
+
};
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
/**
|
|
634
|
+
* Normalizes layout, cache, ttl, raw, and query allowlist options.
|
|
635
|
+
* @param {number|Object} [ttlOrOptions]
|
|
636
|
+
* @param {Object} [data={}]
|
|
637
|
+
* @returns {{ cache: number, ttl: number, layout: string|false|undefined, query: string[], raw: boolean }}
|
|
638
|
+
* @private
|
|
639
|
+
*/
|
|
640
|
+
static _normalizeOptions(ttlOrOptions, data = {}) {
|
|
641
|
+
const out = {
|
|
642
|
+
cache: 0,
|
|
643
|
+
ttl: 0,
|
|
644
|
+
layout: data?._layout,
|
|
645
|
+
query: [],
|
|
646
|
+
raw: Boolean(data?._raw),
|
|
360
647
|
};
|
|
648
|
+
if (typeof ttlOrOptions === "number") {
|
|
649
|
+
out.cache = ttlOrOptions;
|
|
650
|
+
} else if (ttlOrOptions && typeof ttlOrOptions === "object") {
|
|
651
|
+
if (ttlOrOptions.cache !== undefined) out.cache = Number(ttlOrOptions.cache) || 0;
|
|
652
|
+
else if (ttlOrOptions.ttl !== undefined && !ttlOrOptions.raw) out.cache = Number(ttlOrOptions.ttl) || 0;
|
|
653
|
+
if (ttlOrOptions.ttl !== undefined) out.ttl = Number(ttlOrOptions.ttl) || 0;
|
|
654
|
+
if (ttlOrOptions.layout !== undefined) out.layout = ttlOrOptions.layout;
|
|
655
|
+
if (Array.isArray(ttlOrOptions.cacheQuery)) out.query = ttlOrOptions.cacheQuery;
|
|
656
|
+
else if (Array.isArray(ttlOrOptions.query)) out.query = ttlOrOptions.query;
|
|
657
|
+
if (ttlOrOptions.raw !== undefined) out.raw = Boolean(ttlOrOptions.raw);
|
|
658
|
+
}
|
|
659
|
+
if (data?._cache !== undefined && !out.cache) {
|
|
660
|
+
out.cache = Number(data._cache) || 0;
|
|
661
|
+
}
|
|
662
|
+
return out;
|
|
361
663
|
}
|
|
362
664
|
|
|
363
665
|
/**
|
|
364
|
-
* Express middleware
|
|
365
|
-
*
|
|
366
|
-
* @param {number} [seconds] - Cache duration in seconds.
|
|
666
|
+
* Express middleware caching HTML responses of GET routes.
|
|
667
|
+
* @param {number} [seconds]
|
|
367
668
|
* @param {Object} [options={}]
|
|
368
669
|
* @param {boolean} [options.allowAuthenticated=false]
|
|
670
|
+
* @param {string[]} [options.query=[]]
|
|
369
671
|
* @returns {Function}
|
|
370
672
|
*/
|
|
371
673
|
static cache(seconds, options = {}) {
|
|
372
674
|
const ttl = seconds ?? RENDER_CACHE_TTL;
|
|
373
675
|
const allowAuthenticated = options.allowAuthenticated === true;
|
|
676
|
+
const queryKeys = Array.isArray(options.query) ? options.query : [];
|
|
374
677
|
|
|
375
678
|
return async (req, res, next) => {
|
|
376
679
|
if (DEBUG || req.method !== "GET") return next();
|
|
680
|
+
if (!allowAuthenticated && isAuthenticatedRequest(req)) return next();
|
|
377
681
|
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
}
|
|
682
|
+
const key = buildCacheKey("route", req, queryKeys);
|
|
683
|
+
if (!key) return next();
|
|
381
684
|
|
|
382
|
-
const isPartial = req.headers?.["x-bluebird-partial"] === "1" || req.query?._partial === "1";
|
|
383
|
-
const key = `route:${isPartial ? "partial:" : ""}${req.originalUrl}`;
|
|
384
685
|
const cached = await RenderCache.lookup(key);
|
|
385
|
-
|
|
386
686
|
if (cached) {
|
|
387
687
|
res.set("Content-Type", "text/html; charset=utf-8");
|
|
388
|
-
if (isPartial) {
|
|
389
|
-
res.set("X-Bluebird-Partial", "1");
|
|
390
|
-
}
|
|
391
688
|
res.set("X-Bluebird-Cache", "HIT");
|
|
392
|
-
return res.send(cached);
|
|
689
|
+
return res.send(applyCspNonce(detokenizeFromCache(cached, Csrf.ensure(req, res)), res));
|
|
393
690
|
}
|
|
394
691
|
|
|
395
692
|
const originalSend = res.send.bind(res);
|
|
396
693
|
res.send = async (body) => {
|
|
694
|
+
res.send = originalSend;
|
|
397
695
|
if (typeof body === "string" && res.statusCode === 200) {
|
|
398
|
-
|
|
696
|
+
const token = res.locals?.csrfToken || req.cookies?._csrf || "";
|
|
697
|
+
await RenderCache.store(key, tokenizeForCache(stripCspNonce(body, res), token), ttl);
|
|
399
698
|
}
|
|
400
699
|
res.set("X-Bluebird-Cache", "MISS");
|
|
401
700
|
return originalSend(body);
|
|
402
701
|
};
|
|
403
|
-
|
|
404
702
|
next();
|
|
405
703
|
};
|
|
406
704
|
}
|
|
407
705
|
|
|
408
706
|
/**
|
|
409
|
-
* Performs
|
|
707
|
+
* Performs a standard HTTP redirect.
|
|
410
708
|
* @param {import('express').Request} req
|
|
411
709
|
* @param {import('express').Response} res
|
|
412
710
|
* @param {string} url
|
|
413
711
|
* @param {number} [status=302]
|
|
414
712
|
*/
|
|
415
713
|
static redirect(req, res, url, status = 302) {
|
|
416
|
-
if (req.headers?.["x-bluebird-client-router"] === "1") {
|
|
417
|
-
res.set("X-Bluebird-Redirect", url);
|
|
418
|
-
return res.status(200).json({ redirect: url });
|
|
419
|
-
}
|
|
420
714
|
return res.redirect(status, url);
|
|
421
715
|
}
|
|
422
716
|
|
|
423
717
|
/**
|
|
424
|
-
*
|
|
425
|
-
* rendering inside the layout unless requested as a partial.
|
|
426
|
-
* If cache TTL is configured and cached response exists, serves instant cache hit without streaming overhead.
|
|
427
|
-
* When streaming a cache-miss response, caches the final assembled HTML for instant subsequent hits.
|
|
428
|
-
*
|
|
429
|
-
* @param {import('express').Response} res - Express response object.
|
|
430
|
-
* @param {string} viewName - Logical view identifier.
|
|
431
|
-
* @param {Object} [data={}] - Initial data and promises.
|
|
432
|
-
* @param {number|Object} [options={}] - Cache duration (seconds) or options ({ ttl }).
|
|
433
|
-
* @returns {Promise<void>}
|
|
434
|
-
*/
|
|
435
|
-
static async stream(res, viewName, data = {}, options = {}) {
|
|
436
|
-
const ttlOption = typeof options === "number" ? options : options?.ttl;
|
|
437
|
-
const isPartialRequest =
|
|
438
|
-
data._layout === false ||
|
|
439
|
-
res.req?.headers?.["x-bluebird-partial"] === "1" ||
|
|
440
|
-
res.req?.query?._partial === "1";
|
|
441
|
-
|
|
442
|
-
const view = await ViewLoader.load(viewName);
|
|
443
|
-
if (!view) {
|
|
444
|
-
res.status(404).json({ message: `View '${viewName}' not found.` });
|
|
445
|
-
return;
|
|
446
|
-
}
|
|
447
|
-
|
|
448
|
-
const resolvedTtl =
|
|
449
|
-
ttlOption !== undefined
|
|
450
|
-
? ttlOption
|
|
451
|
-
: view.module?.cache !== undefined
|
|
452
|
-
? view.module.cache
|
|
453
|
-
: 0;
|
|
454
|
-
|
|
455
|
-
const cacheKey = `view:stream:${isPartialRequest ? "partial:" : ""}${viewName}`;
|
|
456
|
-
if (resolvedTtl > 0 && !DEBUG) {
|
|
457
|
-
const cached = await RenderCache.lookup(cacheKey);
|
|
458
|
-
if (cached) {
|
|
459
|
-
res.set("Content-Type", "text/html; charset=utf-8");
|
|
460
|
-
if (isPartialRequest) {
|
|
461
|
-
res.set("X-Bluebird-Partial", "1");
|
|
462
|
-
}
|
|
463
|
-
res.set("X-Bluebird-Cache", "HIT");
|
|
464
|
-
return res.send(cached);
|
|
465
|
-
}
|
|
466
|
-
}
|
|
467
|
-
|
|
468
|
-
res.setHeader("Content-Type", "text/html; charset=utf-8");
|
|
469
|
-
res.setHeader("Transfer-Encoding", "chunked");
|
|
470
|
-
res.setHeader("X-Content-Type-Options", "nosniff");
|
|
471
|
-
res.setHeader("X-Bluebird-Cache", "MISS");
|
|
472
|
-
|
|
473
|
-
const deferredTokens = [];
|
|
474
|
-
const streamData = { ...data };
|
|
475
|
-
const proxyData = new Proxy(streamData, {
|
|
476
|
-
get(target, prop) {
|
|
477
|
-
const val = target[prop];
|
|
478
|
-
if (val && typeof val === "object" && val.__bluebird_deferred__) {
|
|
479
|
-
deferredTokens.push({ prop: String(prop), ...val });
|
|
480
|
-
return html.raw(`<div id="bb-defer-${String(prop)}">${val.fallback}</div>`);
|
|
481
|
-
}
|
|
482
|
-
return val;
|
|
483
|
-
},
|
|
484
|
-
});
|
|
485
|
-
|
|
486
|
-
const locals = res.locals || {};
|
|
487
|
-
const appLocals = res.req?.app?.locals || {};
|
|
488
|
-
|
|
489
|
-
let initialHtml = "";
|
|
490
|
-
const ctx = {
|
|
491
|
-
req: res.req,
|
|
492
|
-
res,
|
|
493
|
-
user: res.req?.user,
|
|
494
|
-
locals,
|
|
495
|
-
appLocals,
|
|
496
|
-
data: proxyData,
|
|
497
|
-
isStreaming: true,
|
|
498
|
-
suspenseCounter: 0,
|
|
499
|
-
suspenseTasks: [],
|
|
500
|
-
headTags: [],
|
|
501
|
-
title: "",
|
|
502
|
-
};
|
|
503
|
-
|
|
504
|
-
if (view.type === "js" || view.type === "jsx") {
|
|
505
|
-
if (typeof view.module.load === "function") {
|
|
506
|
-
const loadedData = await view.module.load(ctx);
|
|
507
|
-
if (loadedData && typeof loadedData === "object") {
|
|
508
|
-
Object.assign(streamData, loadedData);
|
|
509
|
-
}
|
|
510
|
-
}
|
|
511
|
-
|
|
512
|
-
const mergedData = {
|
|
513
|
-
...appLocals,
|
|
514
|
-
...locals,
|
|
515
|
-
...proxyData,
|
|
516
|
-
};
|
|
517
|
-
|
|
518
|
-
const renderFn =
|
|
519
|
-
typeof view.module.default === "function" ? view.module.default : view.module;
|
|
520
|
-
const content = await renderFn(mergedData, ctx);
|
|
521
|
-
const bodyHtml = await resolveOutputToHtml(content, ctx);
|
|
522
|
-
|
|
523
|
-
const layoutName =
|
|
524
|
-
data._layout !== undefined
|
|
525
|
-
? data._layout
|
|
526
|
-
: view.module.layout !== undefined
|
|
527
|
-
? view.module.layout
|
|
528
|
-
: "main";
|
|
529
|
-
|
|
530
|
-
if (isPartialRequest || layoutName === false) {
|
|
531
|
-
initialHtml = bodyHtml;
|
|
532
|
-
} else {
|
|
533
|
-
const layoutView = await ViewLoader.loadLayout(layoutName);
|
|
534
|
-
if (layoutView && (layoutView.type === "js" || layoutView.type === "jsx")) {
|
|
535
|
-
let headData = {
|
|
536
|
-
title: ctx.title || mergedData.title || "Bluebird App",
|
|
537
|
-
tags: ctx.headTags || [],
|
|
538
|
-
};
|
|
539
|
-
if (view.module.head) {
|
|
540
|
-
const declaredHead =
|
|
541
|
-
typeof view.module.head === "function"
|
|
542
|
-
? await view.module.head(mergedData, ctx)
|
|
543
|
-
: view.module.head;
|
|
544
|
-
if (declaredHead && typeof declaredHead === "object") {
|
|
545
|
-
Object.assign(headData, declaredHead);
|
|
546
|
-
}
|
|
547
|
-
if (ctx.title) {
|
|
548
|
-
headData.title = ctx.title;
|
|
549
|
-
}
|
|
550
|
-
}
|
|
551
|
-
|
|
552
|
-
const layoutFn =
|
|
553
|
-
typeof layoutView.module.default === "function"
|
|
554
|
-
? layoutView.module.default
|
|
555
|
-
: layoutView.module;
|
|
556
|
-
|
|
557
|
-
const safeBody = html.raw(bodyHtml);
|
|
558
|
-
const layoutOutput = await layoutFn({
|
|
559
|
-
body: safeBody,
|
|
560
|
-
content: safeBody,
|
|
561
|
-
children: safeBody,
|
|
562
|
-
head: headData,
|
|
563
|
-
ctx,
|
|
564
|
-
data: mergedData,
|
|
565
|
-
});
|
|
566
|
-
|
|
567
|
-
initialHtml = await resolveOutputToHtml(layoutOutput, ctx);
|
|
568
|
-
|
|
569
|
-
if (ctx.headTags && ctx.headTags.length > 0 && initialHtml.includes("</head>")) {
|
|
570
|
-
if (ctx.title) {
|
|
571
|
-
initialHtml = initialHtml.replace(
|
|
572
|
-
/<title>[^<]*<\/title>/i,
|
|
573
|
-
`<title>${escapeHtml(ctx.title)}</title>`
|
|
574
|
-
);
|
|
575
|
-
}
|
|
576
|
-
const extraTags = ctx.headTags.filter(
|
|
577
|
-
(t) => !t.startsWith("<title>") && !initialHtml.includes(t)
|
|
578
|
-
);
|
|
579
|
-
if (extraTags.length > 0) {
|
|
580
|
-
initialHtml = initialHtml.replace(
|
|
581
|
-
"</head>",
|
|
582
|
-
` ${extraTags.join("\n ")}\n</head>`
|
|
583
|
-
);
|
|
584
|
-
}
|
|
585
|
-
}
|
|
586
|
-
} else {
|
|
587
|
-
initialHtml = bodyHtml;
|
|
588
|
-
}
|
|
589
|
-
}
|
|
590
|
-
} else {
|
|
591
|
-
initialHtml = view.content || "";
|
|
592
|
-
}
|
|
593
|
-
|
|
594
|
-
res.write(initialHtml);
|
|
595
|
-
let assembledHtml = initialHtml;
|
|
596
|
-
|
|
597
|
-
if (deferredTokens.length > 0) {
|
|
598
|
-
await Promise.all(
|
|
599
|
-
deferredTokens.map(async (token) => {
|
|
600
|
-
try {
|
|
601
|
-
const resolved = await token.promise;
|
|
602
|
-
const finalContent = await token.renderer(resolved);
|
|
603
|
-
const strContent = await resolveOutputToHtml(finalContent);
|
|
604
|
-
const script = `<template id="bb-defer-tpl-${token.prop}">${strContent}</template><script>(function(){var el=document.getElementById("bb-defer-${token.prop}");var tpl=document.getElementById("bb-defer-tpl-${token.prop}");if(el&&tpl){el.innerHTML="";el.appendChild(tpl.content);tpl.remove();if(window.Bluebird&&window.Bluebird.hydrate){window.Bluebird.hydrate(el);}}})();</script>`;
|
|
605
|
-
res.write(script);
|
|
606
|
-
assembledHtml = assembledHtml.replace(
|
|
607
|
-
new RegExp(`<div id="bb-defer-${token.prop}">[\\s\\S]*?<\\/div>`),
|
|
608
|
-
`<div id="bb-defer-${token.prop}">${strContent}</div>`
|
|
609
|
-
);
|
|
610
|
-
} catch (err) {
|
|
611
|
-
res.write(`<script>console.error("Deferred stream error on ${token.prop}:", ${safeJson(err.message)});</script>`);
|
|
612
|
-
}
|
|
613
|
-
})
|
|
614
|
-
);
|
|
615
|
-
}
|
|
616
|
-
|
|
617
|
-
if (ctx.suspenseTasks && ctx.suspenseTasks.length > 0) {
|
|
618
|
-
await Promise.all(
|
|
619
|
-
ctx.suspenseTasks.map(async (taskPromise) => {
|
|
620
|
-
try {
|
|
621
|
-
const task = await taskPromise;
|
|
622
|
-
if (task.success) {
|
|
623
|
-
const script = `<template id="${task.id}-tpl">${task.html}</template><script>(function(){var el=document.getElementById("${task.id}");var tpl=document.getElementById("${task.id}-tpl");if(el&&tpl){el.innerHTML="";el.appendChild(tpl.content);tpl.remove();if(window.Bluebird&&window.Bluebird.hydrate){window.Bluebird.hydrate(el);}}})();</script>`;
|
|
624
|
-
res.write(script);
|
|
625
|
-
assembledHtml = assembledHtml.replace(
|
|
626
|
-
new RegExp(`<div id="${task.id}">[\\s\\S]*?<\\/div>`),
|
|
627
|
-
`<div id="${task.id}">${task.html}</div>`
|
|
628
|
-
);
|
|
629
|
-
} else {
|
|
630
|
-
res.write(`<script>console.error("Suspense error on ${task.id}:", ${safeJson(task.error?.message || "Render error")});</script>`);
|
|
631
|
-
}
|
|
632
|
-
} catch (err) {
|
|
633
|
-
res.write(`<script>console.error("Suspense execution error:", ${safeJson(err.message)});</script>`);
|
|
634
|
-
}
|
|
635
|
-
})
|
|
636
|
-
);
|
|
637
|
-
}
|
|
638
|
-
|
|
639
|
-
if (resolvedTtl > 0 && !DEBUG) {
|
|
640
|
-
await RenderCache.store(cacheKey, assembledHtml, resolvedTtl);
|
|
641
|
-
}
|
|
642
|
-
|
|
643
|
-
res.end();
|
|
644
|
-
}
|
|
645
|
-
|
|
646
|
-
/**
|
|
647
|
-
* Clears all in-memory view and template caches.
|
|
718
|
+
* Clears all in-memory view, compiled template, and render caches.
|
|
648
719
|
*/
|
|
649
720
|
static clearTemplateCache() {
|
|
721
|
+
compiledCache.clear();
|
|
650
722
|
ViewLoader.clearCache();
|
|
651
723
|
RenderCache.clearMemory();
|
|
652
724
|
}
|
|
653
725
|
|
|
654
726
|
/**
|
|
655
|
-
* Invalidates
|
|
727
|
+
* Invalidates cached views and routes for paths or cache keys.
|
|
656
728
|
* @param {string|string[]} [keys]
|
|
657
729
|
* @returns {Promise<void>}
|
|
658
730
|
*/
|
|
659
731
|
static async invalidate(keys) {
|
|
732
|
+
compiledCache.clear();
|
|
660
733
|
ViewLoader.clearCache();
|
|
661
734
|
await RenderCache.invalidate(keys);
|
|
662
735
|
}
|
|
663
|
-
|
|
664
|
-
/**
|
|
665
|
-
* Automatically discovers views in `app/views/` (ignoring `layouts`, `components`, `partials`, `islands`, and `api`)
|
|
666
|
-
* and mounts them as GET routes with their exported `route`, `cache`, `middlewares`, `seo`, and `layout` settings.
|
|
667
|
-
*
|
|
668
|
-
* @param {import('./router.js').Router} [targetRouter] - Optional Router instance to register routes on.
|
|
669
|
-
* @returns {Promise<Array<{viewName: string, routePath: string, cache: number, seo: boolean}>>}
|
|
670
|
-
*/
|
|
671
|
-
static async autoRoutes(targetRouter) {
|
|
672
|
-
const discovered = await ViewLoader.discoverRoutes();
|
|
673
|
-
if (!targetRouter) return discovered;
|
|
674
|
-
|
|
675
|
-
const [{ Seo }, { Actions }] = await Promise.all([
|
|
676
|
-
import("./seo.js"),
|
|
677
|
-
import("./actions.js"),
|
|
678
|
-
]);
|
|
679
|
-
|
|
680
|
-
for (const item of discovered) {
|
|
681
|
-
const handlers = [...item.middlewares];
|
|
682
|
-
if (item.cache > 0) {
|
|
683
|
-
handlers.push(Render.cache(item.cache));
|
|
684
|
-
}
|
|
685
|
-
handlers.push(
|
|
686
|
-
Render.view(item.viewName, (req) => ({
|
|
687
|
-
user: req.user,
|
|
688
|
-
params: req.params,
|
|
689
|
-
query: req.query,
|
|
690
|
-
}))
|
|
691
|
-
);
|
|
692
|
-
|
|
693
|
-
if (item.seo) {
|
|
694
|
-
Seo.registerRoute(targetRouter.path || "/", item.routePath, targetRouter._languages || []);
|
|
695
|
-
}
|
|
696
|
-
|
|
697
|
-
const prevSeo = targetRouter._seo;
|
|
698
|
-
targetRouter._seo = false;
|
|
699
|
-
targetRouter.get(item.routePath, ...handlers);
|
|
700
|
-
targetRouter._seo = prevSeo;
|
|
701
|
-
|
|
702
|
-
if (item.actions) {
|
|
703
|
-
const postHandlers = [
|
|
704
|
-
...item.middlewares,
|
|
705
|
-
Actions.createDispatcher(item.viewName, item.actions),
|
|
706
|
-
];
|
|
707
|
-
targetRouter.post(item.routePath, ...postHandlers);
|
|
708
|
-
}
|
|
709
|
-
}
|
|
710
|
-
|
|
711
|
-
return discovered;
|
|
712
|
-
}
|
|
713
736
|
}
|
|
714
737
|
|
|
715
|
-
export {
|
|
716
|
-
h,
|
|
717
|
-
Fragment,
|
|
718
|
-
Island,
|
|
719
|
-
Client,
|
|
720
|
-
ErrorBoundary,
|
|
721
|
-
Suspense,
|
|
722
|
-
Head,
|
|
723
|
-
Title,
|
|
724
|
-
Meta,
|
|
725
|
-
useAction,
|
|
726
|
-
useActionState,
|
|
727
|
-
};
|
|
728
738
|
export default Render;
|