@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.
Files changed (152) hide show
  1. package/.vscode/extensions.json +7 -7
  2. package/.vscode/settings.json +10 -10
  3. package/AGENTS.md +266 -116
  4. package/README.md +258 -245
  5. package/app/models/user.js +19 -0
  6. package/app/resources/html/home.html +137 -0
  7. package/app/resources/html/layouts/main.html +54 -0
  8. package/app/resources/html/notFound.html +14 -0
  9. package/app/resources/html/terms.html +46 -0
  10. package/app/resources/index.html +27 -0
  11. package/app/resources/layouts/AppLayout.jsx +89 -0
  12. package/app/resources/main.jsx +18 -0
  13. package/app/resources/pages/Dashboard.jsx +98 -0
  14. package/app/resources/pages/Home.jsx +140 -0
  15. package/app/resources/pages/Login.jsx +35 -0
  16. package/app/resources/pages/NotFound.jsx +16 -0
  17. package/app/resources/pages/Register.jsx +55 -0
  18. package/app/resources/routes.jsx +54 -0
  19. package/app/resources/spa.js +67 -0
  20. package/app/resources/styles.css +9 -0
  21. package/app/routes/api.js +85 -50
  22. package/app/routes/auth.js +209 -0
  23. package/app/routes/web.js +49 -37
  24. package/core/ai.d.ts +151 -151
  25. package/core/ai.js +1071 -1051
  26. package/core/app.d.ts +2 -18
  27. package/core/app.js +978 -792
  28. package/core/auth.d.ts +2 -13
  29. package/core/auth.js +444 -326
  30. package/core/cli/backup.js +167 -167
  31. package/core/cli/build.js +37 -0
  32. package/core/cli/dev.js +155 -0
  33. package/core/cli/doctor.js +37 -2
  34. package/core/cli/export.js +191 -0
  35. package/core/cli/init.js +101 -332
  36. package/core/cli/nginx.js +1 -1
  37. package/core/cli/templates.js +139 -0
  38. package/core/cli/view.js +73 -136
  39. package/core/config.js +44 -2
  40. package/core/csrf.js +156 -24
  41. package/core/database.js +737 -684
  42. package/core/debug.js +1 -1
  43. package/core/html.js +8 -1
  44. package/core/index.d.ts +1286 -1431
  45. package/core/paths.js +55 -0
  46. package/core/ratelimit.js +10 -1
  47. package/core/react/client/api.js +237 -0
  48. package/core/react/client/auth.js +236 -0
  49. package/core/react/client/components.js +1321 -0
  50. package/core/react/client/i18n.js +338 -0
  51. package/core/react/client/index.d.ts +249 -0
  52. package/core/react/client/index.js +49 -0
  53. package/core/react/client/router.js +26 -0
  54. package/core/react/client/theme.css +512 -0
  55. package/core/render-cache.js +250 -212
  56. package/core/render.d.ts +25 -21
  57. package/core/render.js +613 -603
  58. package/core/router.d.ts +2 -3
  59. package/core/router.js +171 -171
  60. package/core/seo.js +10 -0
  61. package/core/spa.js +599 -0
  62. package/core/view-loader.js +81 -455
  63. package/core/vite-plugin.d.ts +18 -0
  64. package/core/vite-plugin.js +162 -0
  65. package/core/vite.js +250 -145
  66. package/index.js +22 -18
  67. package/jsconfig.json +5 -3
  68. package/package.json +114 -92
  69. package/production.md +8 -3
  70. package/public/js/bluebird.js +1160 -0
  71. package/templates/_auth/app/database.js +19 -0
  72. package/templates/_auth/app/models/user.js +22 -0
  73. package/templates/_auth/app/routes/auth-router.js +304 -0
  74. package/templates/_base/app/resources/html/layouts/main.html +55 -0
  75. package/templates/_base/app/resources/html/notFound.html +14 -0
  76. package/templates/_base/app/resources/index.html +27 -0
  77. package/templates/_base/app/resources/styles.css +9 -0
  78. package/templates/api/app/models/note.js +18 -0
  79. package/templates/api/app/routes/api.js +82 -0
  80. package/templates/api/app/routes/auth.js +11 -0
  81. package/templates/api/index.js +19 -0
  82. package/templates/api/template.json +13 -0
  83. package/templates/auth/app/mail.js +11 -0
  84. package/templates/auth/app/models/password_reset.js +18 -0
  85. package/templates/auth/app/resources/html/home.html +21 -0
  86. package/templates/auth/app/resources/html/partials/nav.html +2 -0
  87. package/templates/auth/app/resources/layouts/AppLayout.jsx +60 -0
  88. package/templates/auth/app/resources/main.jsx +18 -0
  89. package/templates/auth/app/resources/pages/Dashboard.jsx +51 -0
  90. package/templates/auth/app/resources/pages/ForgotPassword.jsx +34 -0
  91. package/templates/auth/app/resources/pages/Login.jsx +36 -0
  92. package/templates/auth/app/resources/pages/NotFound.jsx +16 -0
  93. package/templates/auth/app/resources/pages/Profile.jsx +99 -0
  94. package/templates/auth/app/resources/pages/Register.jsx +50 -0
  95. package/templates/auth/app/resources/pages/ResetPassword.jsx +50 -0
  96. package/templates/auth/app/resources/routes.jsx +54 -0
  97. package/templates/auth/app/resources/spa.js +29 -0
  98. package/templates/auth/app/routes/api.js +17 -0
  99. package/templates/auth/app/routes/auth.js +13 -0
  100. package/templates/auth/app/routes/web.js +21 -0
  101. package/templates/auth/index.js +19 -0
  102. package/templates/auth/template.json +15 -0
  103. package/templates/blank/app/models/.gitkeep +0 -0
  104. package/templates/blank/app/resources/html/home.html +27 -0
  105. package/templates/blank/app/resources/html/partials/nav.html +1 -0
  106. package/templates/blank/app/resources/main.jsx +16 -0
  107. package/templates/blank/app/resources/pages/Home.jsx +42 -0
  108. package/templates/blank/app/resources/pages/NotFound.jsx +27 -0
  109. package/templates/blank/app/resources/routes.jsx +15 -0
  110. package/templates/blank/app/resources/spa.js +24 -0
  111. package/templates/blank/app/routes/api.js +11 -0
  112. package/templates/blank/app/routes/web.js +21 -0
  113. package/templates/blank/index.js +13 -0
  114. package/templates/blank/template.json +12 -0
  115. package/templates/blog/app/lib/blog.js +149 -0
  116. package/templates/blog/app/models/post.js +22 -0
  117. package/templates/blog/app/resources/html/home.html +28 -0
  118. package/templates/blog/app/resources/html/not-found.html +5 -0
  119. package/templates/blog/app/resources/html/partials/nav.html +2 -0
  120. package/templates/blog/app/resources/html/partials/post-card.html +9 -0
  121. package/templates/blog/app/resources/html/post.html +8 -0
  122. package/templates/blog/app/resources/layouts/AdminLayout.jsx +54 -0
  123. package/templates/blog/app/resources/main.jsx +18 -0
  124. package/templates/blog/app/resources/pages/Login.jsx +31 -0
  125. package/templates/blog/app/resources/pages/NotFound.jsx +16 -0
  126. package/templates/blog/app/resources/pages/PostEditor.jsx +51 -0
  127. package/templates/blog/app/resources/pages/Posts.jsx +83 -0
  128. package/templates/blog/app/resources/pages/Register.jsx +43 -0
  129. package/templates/blog/app/resources/routes.jsx +51 -0
  130. package/templates/blog/app/resources/spa.js +25 -0
  131. package/templates/blog/app/resources/styles.css +40 -0
  132. package/templates/blog/app/routes/api.js +77 -0
  133. package/templates/blog/app/routes/auth.js +10 -0
  134. package/templates/blog/app/routes/web.js +114 -0
  135. package/templates/blog/index.js +21 -0
  136. package/templates/blog/template.json +14 -0
  137. package/vite.config.js +11 -0
  138. package/app/views/about.jsx +0 -98
  139. package/app/views/components/Header.jsx +0 -42
  140. package/app/views/components/LiveCounter.jsx +0 -66
  141. package/app/views/dashboard.jsx +0 -300
  142. package/app/views/index.jsx +0 -123
  143. package/app/views/layouts/main/view.jsx +0 -201
  144. package/app/views/legal/terms.html +0 -29
  145. package/app/views/login.jsx +0 -141
  146. package/core/actions.d.ts +0 -4
  147. package/core/actions.js +0 -329
  148. package/core/jsx.d.ts +0 -38
  149. package/core/jsx.js +0 -1432
  150. package/core/vite.d.ts +0 -3
  151. package/public/js/bluebird-client.js +0 -3161
  152. 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 { html, SafeHtml, escapeHtml, safeJson, isSafeHtml } from "./html.js";
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 props = Config.props();
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
- * Resolves any rendered output (JSX element tree, SafeHtml, Promise, or string) into an HTML string.
28
- * Automatically prepends `<!DOCTYPE html>` when a JSX layout returns a root `<html>` element.
29
- *
30
- * @param {any} output
31
- * @param {Object} [ctx={}]
32
- * @returns {Promise<string>}
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
- async function resolveOutputToHtml(output, ctx = {}) {
35
- if (output === null || output === undefined || output === false) {
36
- return "";
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
- if (isSafeHtml(output)) {
39
- return output.toString();
204
+
205
+ if (lastIndex < source.length) {
206
+ pushNode({ type: "text", value: source.slice(lastIndex) });
40
207
  }
41
- if (isJsxElement(output) || Array.isArray(output)) {
42
- const isRootHtmlTag = isJsxElement(output) && output.type === "html";
43
- const rendered = await renderJsxToString(output, ctx);
44
- if (isRootHtmlTag && !rendered.trimStart().toLowerCase().startsWith("<!doctype")) {
45
- return `<!DOCTYPE html>\n${rendered}`;
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
- return rendered;
214
+ compiledCache.set(source, root.body);
48
215
  }
49
- return String(output ?? "");
216
+
217
+ return root.body;
50
218
  }
51
219
 
52
220
  /**
53
- * Modern JavaScript & React JSX HTML rendering engine for Bluebird.js.
54
- * Standardizes on zero-build JSX and JS view modules, SafeHtml tagged templates,
55
- * progressive layouts, client hydration with skeleton anti-CLS locking, and multi-tier caching.
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
- export class Render {
58
- /**
59
- * Generates declarative HTML markup for client-side island hydration with optional
60
- * skeleton fallback and anti-accordion dimension locking (`minHeight`, `minWidth`).
61
- *
62
- * @param {string|Function} name - Island component name or function.
63
- * @param {Object} [islandProps={}] - Initial props passed to the component.
64
- * @param {Object} [options={}] - Island options.
65
- * @param {boolean} [options.persist=false] - Preserves island across View Transitions.
66
- * @param {string|SafeHtml|Object} [options.fallback=""] - Fallback or skeleton HTML/JSX content.
67
- * @param {string|SafeHtml|Object} [options.skeleton] - Skeleton HTML/JSX content to prevent layout shift.
68
- * @param {string|number} [options.minHeight] - CSS min-height to lock vertical space and prevent CLS.
69
- * @param {string|number} [options.minWidth] - CSS min-width to lock horizontal space.
70
- * @param {string} [options.className] - CSS class for the island wrapper.
71
- * @param {Object|string} [options.style] - Inline styles for the island wrapper.
72
- * @param {boolean} [options.ssr=false] - Whether to mark container for hydration of server-rendered markup.
73
- * @param {string} [options.tag="div"] - Container tag name.
74
- * @returns {string} Declarative HTML markup.
75
- */
76
- static island(name, islandProps = {}, options = {}) {
77
- const tag = options.tag || "div";
78
- const resolvedName =
79
- typeof name === "function"
80
- ? name.displayName || name.name || "Island"
81
- : String(name);
82
- const persistAttr = options.persist ? ' data-persist="true"' : "";
83
- const hydrateAttr = options.ssr ? ' data-hydrate="true"' : "";
84
- const classAttr = options.className ? ` class="${escapeHtml(options.className)}"` : "";
85
-
86
- const styleObj =
87
- typeof options.style === "object" && options.style !== null
88
- ? { ...options.style }
89
- : {};
90
- if (options.minHeight !== undefined) {
91
- styleObj.minHeight =
92
- typeof options.minHeight === "number" ? `${options.minHeight}px` : options.minHeight;
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 (options.minWidth !== undefined) {
95
- styleObj.minWidth =
96
- typeof options.minWidth === "number" ? `${options.minWidth}px` : options.minWidth;
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
- * Synchronously or asynchronously renders a component or view (`.jsx` or `.js`) to a raw HTML string.
120
- * @param {string} viewName - Component or view name.
121
- * @param {Object} [data={}] - Props and context.
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 component(viewName, data = {}) {
125
- const view = await ViewLoader.load(viewName);
126
- if (!view) return "";
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
- * Sends a rendered partial fragment without applying a layout.
141
- * @param {import('express').Response} res - Express response object.
142
- * @param {string} partialName - View or component name.
143
- * @param {Object} [data={}] - Data to pass.
144
- * @returns {Promise<any>}
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 partial(res, partialName, data = {}) {
147
- return this.send(res, partialName, { ...data, _layout: false });
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
- * Serves an unparsed, raw HTML file without layouts or server interpolation.
152
- * Ideal for legal policies, static terms, or offline pages.
153
- *
154
- * @param {import('express').Response} res - Express response object.
155
- * @param {string} relativePath - Path to HTML file inside app/views.
156
- * @param {Object} [options={}] - Optional HTTP cache settings.
157
- * @param {number} [options.ttl] - Cache TTL in seconds.
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, relativePath, options = {}) {
161
- const view = await ViewLoader.load(relativePath);
162
- if (!view || !view.content) {
163
- return res.status(404).json({ message: `Static HTML '${relativePath}' not found.` });
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
- * Sends a rendered HTML view response (`.jsx`, `.js`, or `.html`) with full layout and head asset resolution.
176
- *
177
- * @param {import('express').Response} res - Express response object.
178
- * @param {string} viewName - Logical view identifier.
179
- * @param {Object} [data={}] - Data passed to the view and layout.
180
- * @param {number} [ttl] - Optional route cache TTL in seconds.
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 = {}, ttl) {
184
- const locals = res.locals || {};
185
- const appLocals = res.req?.app?.locals || {};
186
- const isPartialRequest =
187
- data._layout === false ||
188
- res.req?.headers?.["x-bluebird-partial"] === "1" ||
189
- res.req?.query?._partial === "1";
190
-
191
- const cacheKey = `view:${isPartialRequest ? "partial:" : ""}${viewName}`;
192
- if (ttl !== undefined && ttl > 0 && !DEBUG) {
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
- return res.send(cached);
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
- let rendered = "";
210
-
211
- if (view.type === "js" || view.type === "jsx") {
212
- const viewData = { ...data };
213
- let csrfToken =
214
- locals.csrfToken ||
215
- (typeof res.req?.csrfToken === "function" ? res.req.csrfToken() : "") ||
216
- res.req?.cookies?.["_csrf"] ||
217
- res.req?.session?.csrfToken ||
218
- "";
219
-
220
- if (!csrfToken && typeof res.cookie === "function") {
221
- try {
222
- const { Csrf } = await import("./csrf.js");
223
- csrfToken = Csrf.generateToken();
224
- res.cookie("_csrf", csrfToken, {
225
- httpOnly: false,
226
- sameSite: "lax",
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
- const renderFn =
264
- typeof view.module.default === "function" ? view.module.default : view.module;
265
- const content = await renderFn(mergedData, ctx);
266
- const bodyHtml = await resolveOutputToHtml(content, ctx);
543
+ const renderCtx = {
544
+ req,
545
+ res,
546
+ vite: ViteBridge.from(req) || ViteBridge.from(res),
547
+ };
267
548
 
268
- const layoutName =
269
- data._layout !== undefined
270
- ? data._layout
271
- : view.module.layout !== undefined
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
- if (isPartialRequest || layoutName === false) {
276
- rendered = bodyHtml;
277
- } else {
278
- const layoutView = await ViewLoader.loadLayout(layoutName);
279
- if (layoutView && (layoutView.type === "js" || layoutView.type === "jsx")) {
280
- let headData = {
281
- title: ctx.title || mergedData.title || "Bluebird App",
282
- tags: ctx.headTags || [],
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 (ttl !== undefined && ttl > 0 && !DEBUG) {
337
- await RenderCache.store(cacheKey, rendered, ttl);
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.set("Content-Type", "text/html; charset=utf-8");
341
- if (isPartialRequest) {
342
- res.set("X-Bluebird-Partial", "1");
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 generator.
350
- * Supports static props object or a dynamic provider function (req, res) => Object | Promise<Object>.
351
- * @param {string} viewName - Logical view name.
352
- * @param {Object|Function} [dataOrFn={}] - Static props or dynamic provider function.
353
- * @param {number} [ttl] - Optional route cache duration in seconds.
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 = {}, ttl) {
626
+ static view(viewName, dataOrFn = {}, options = {}) {
357
627
  return async (req, res) => {
358
- const resolvedData = typeof dataOrFn === "function" ? await dataOrFn(req, res) : dataOrFn;
359
- return Render.send(res, viewName, resolvedData, ttl);
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 that caches the rendered HTML response for GET requests.
365
- * Respects partial requests with dedicated cache partitions.
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
- if (!allowAuthenticated && (req.headers.authorization || req.cookies?.auth || req.user)) {
379
- return next();
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
- await RenderCache.store(key, body, ttl);
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 SPA-aware or standard HTTP redirect.
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
- * Streams progressive HTML chunks with out-of-order deferred content resolution and <Suspense> support,
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 caches for specific views or route keys.
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;