@seip/bluebird-js 0.1.7 → 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 (148) hide show
  1. package/AGENTS.md +726 -620
  2. package/README.md +615 -607
  3. package/app/models/user.js +19 -0
  4. package/app/resources/html/home.html +137 -0
  5. package/app/resources/html/layouts/main.html +54 -0
  6. package/app/resources/html/notFound.html +14 -0
  7. package/app/resources/html/terms.html +46 -0
  8. package/app/resources/index.html +27 -0
  9. package/app/resources/layouts/AppLayout.jsx +89 -0
  10. package/app/resources/main.jsx +18 -0
  11. package/app/resources/pages/Dashboard.jsx +98 -0
  12. package/app/resources/pages/Home.jsx +140 -0
  13. package/app/resources/pages/Login.jsx +35 -0
  14. package/app/resources/pages/NotFound.jsx +16 -0
  15. package/app/resources/pages/Register.jsx +55 -0
  16. package/app/resources/routes.jsx +54 -0
  17. package/app/resources/spa.js +67 -0
  18. package/app/resources/styles.css +9 -0
  19. package/app/routes/api.js +85 -50
  20. package/app/routes/auth.js +209 -0
  21. package/app/routes/web.js +59 -47
  22. package/core/ai.js +30 -10
  23. package/core/app.d.ts +2 -18
  24. package/core/app.js +987 -801
  25. package/core/auth.d.ts +2 -13
  26. package/core/auth.js +444 -326
  27. package/core/cli/build.js +37 -0
  28. package/core/cli/dev.js +155 -0
  29. package/core/cli/doctor.js +37 -2
  30. package/core/cli/export.js +191 -0
  31. package/core/cli/init.js +91 -322
  32. package/core/cli/nginx.js +1 -1
  33. package/core/cli/templates.js +139 -0
  34. package/core/cli/view.js +98 -161
  35. package/core/config.js +44 -2
  36. package/core/csrf.js +156 -24
  37. package/core/database.js +1184 -1131
  38. package/core/debug.js +1 -1
  39. package/core/html.js +8 -1
  40. package/core/index.d.ts +126 -310
  41. package/core/paths.js +55 -0
  42. package/core/ratelimit.js +10 -1
  43. package/core/react/client/api.js +237 -0
  44. package/core/react/client/auth.js +236 -0
  45. package/core/react/client/components.js +1321 -0
  46. package/core/react/client/i18n.js +338 -0
  47. package/core/react/client/index.d.ts +249 -0
  48. package/core/react/client/index.js +49 -0
  49. package/core/react/client/router.js +26 -0
  50. package/core/react/client/theme.css +512 -0
  51. package/core/render-cache.js +250 -212
  52. package/core/render.d.ts +25 -21
  53. package/core/render.js +738 -736
  54. package/core/router.d.ts +2 -3
  55. package/core/router.js +171 -171
  56. package/core/seo.js +10 -0
  57. package/core/spa.js +599 -0
  58. package/core/view-loader.js +155 -613
  59. package/core/vite-plugin.d.ts +18 -0
  60. package/core/vite-plugin.js +162 -0
  61. package/core/vite.js +250 -145
  62. package/index.js +22 -18
  63. package/jsconfig.json +5 -3
  64. package/package.json +114 -92
  65. package/production.md +8 -3
  66. package/public/js/bluebird.js +1160 -0
  67. package/templates/_auth/app/database.js +19 -0
  68. package/templates/_auth/app/models/user.js +22 -0
  69. package/templates/_auth/app/routes/auth-router.js +304 -0
  70. package/templates/_base/app/resources/html/layouts/main.html +55 -0
  71. package/templates/_base/app/resources/html/notFound.html +14 -0
  72. package/templates/_base/app/resources/index.html +27 -0
  73. package/templates/_base/app/resources/styles.css +9 -0
  74. package/templates/api/app/models/note.js +18 -0
  75. package/templates/api/app/routes/api.js +82 -0
  76. package/templates/api/app/routes/auth.js +11 -0
  77. package/templates/api/index.js +19 -0
  78. package/templates/api/template.json +13 -0
  79. package/templates/auth/app/mail.js +11 -0
  80. package/templates/auth/app/models/password_reset.js +18 -0
  81. package/templates/auth/app/resources/html/home.html +21 -0
  82. package/templates/auth/app/resources/html/partials/nav.html +2 -0
  83. package/templates/auth/app/resources/layouts/AppLayout.jsx +60 -0
  84. package/templates/auth/app/resources/main.jsx +18 -0
  85. package/templates/auth/app/resources/pages/Dashboard.jsx +51 -0
  86. package/templates/auth/app/resources/pages/ForgotPassword.jsx +34 -0
  87. package/templates/auth/app/resources/pages/Login.jsx +36 -0
  88. package/templates/auth/app/resources/pages/NotFound.jsx +16 -0
  89. package/templates/auth/app/resources/pages/Profile.jsx +99 -0
  90. package/templates/auth/app/resources/pages/Register.jsx +50 -0
  91. package/templates/auth/app/resources/pages/ResetPassword.jsx +50 -0
  92. package/templates/auth/app/resources/routes.jsx +54 -0
  93. package/templates/auth/app/resources/spa.js +29 -0
  94. package/templates/auth/app/routes/api.js +17 -0
  95. package/templates/auth/app/routes/auth.js +13 -0
  96. package/templates/auth/app/routes/web.js +21 -0
  97. package/templates/auth/index.js +19 -0
  98. package/templates/auth/template.json +15 -0
  99. package/templates/blank/app/models/.gitkeep +0 -0
  100. package/templates/blank/app/resources/html/home.html +27 -0
  101. package/templates/blank/app/resources/html/partials/nav.html +1 -0
  102. package/templates/blank/app/resources/main.jsx +16 -0
  103. package/templates/blank/app/resources/pages/Home.jsx +42 -0
  104. package/templates/blank/app/resources/pages/NotFound.jsx +27 -0
  105. package/templates/blank/app/resources/routes.jsx +15 -0
  106. package/templates/blank/app/resources/spa.js +24 -0
  107. package/templates/blank/app/routes/api.js +11 -0
  108. package/templates/blank/app/routes/web.js +21 -0
  109. package/templates/blank/index.js +13 -0
  110. package/templates/blank/template.json +12 -0
  111. package/templates/blog/app/lib/blog.js +149 -0
  112. package/templates/blog/app/models/post.js +22 -0
  113. package/templates/blog/app/resources/html/home.html +28 -0
  114. package/templates/blog/app/resources/html/not-found.html +5 -0
  115. package/templates/blog/app/resources/html/partials/nav.html +2 -0
  116. package/templates/blog/app/resources/html/partials/post-card.html +9 -0
  117. package/templates/blog/app/resources/html/post.html +8 -0
  118. package/templates/blog/app/resources/layouts/AdminLayout.jsx +54 -0
  119. package/templates/blog/app/resources/main.jsx +18 -0
  120. package/templates/blog/app/resources/pages/Login.jsx +31 -0
  121. package/templates/blog/app/resources/pages/NotFound.jsx +16 -0
  122. package/templates/blog/app/resources/pages/PostEditor.jsx +51 -0
  123. package/templates/blog/app/resources/pages/Posts.jsx +83 -0
  124. package/templates/blog/app/resources/pages/Register.jsx +43 -0
  125. package/templates/blog/app/resources/routes.jsx +51 -0
  126. package/templates/blog/app/resources/spa.js +25 -0
  127. package/templates/blog/app/resources/styles.css +40 -0
  128. package/templates/blog/app/routes/api.js +77 -0
  129. package/templates/blog/app/routes/auth.js +10 -0
  130. package/templates/blog/app/routes/web.js +114 -0
  131. package/templates/blog/index.js +21 -0
  132. package/templates/blog/template.json +14 -0
  133. package/vite.config.js +11 -0
  134. package/app/views/components/Header.jsx +0 -42
  135. package/app/views/components/LiveCounter.jsx +0 -67
  136. package/app/views/layouts/main/view.jsx +0 -201
  137. package/app/views/legal/terms.html +0 -29
  138. package/app/views/pages/about.jsx +0 -98
  139. package/app/views/pages/dashboard.jsx +0 -278
  140. package/app/views/pages/index.jsx +0 -123
  141. package/app/views/pages/login.jsx +0 -141
  142. package/core/actions.d.ts +0 -4
  143. package/core/actions.js +0 -355
  144. package/core/jsx.d.ts +0 -38
  145. package/core/jsx.js +0 -1597
  146. package/core/vite.d.ts +0 -3
  147. package/public/js/bluebird-client.js +0 -3265
  148. package/public/js/tailwind.js +0 -8
package/core/render.js CHANGED
@@ -1,736 +1,738 @@
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
- client,
19
- Script,
20
- SCRIPT_ELEMENT,
21
- action,
22
- } from "./jsx.js";
23
- import RenderCache from "./render-cache.js";
24
- import ViewLoader from "./view-loader.js";
25
-
26
- const props = Config.props();
27
- const DEBUG = props.debug;
28
- const RENDER_CACHE_TTL = parseInt(process.env.RENDER_CACHE_TTL || "300", 10);
29
-
30
- /**
31
- * Resolves any rendered output (JSX element tree, SafeHtml, Promise, or string) into an HTML string.
32
- * Automatically prepends `<!DOCTYPE html>` when a JSX layout returns a root `<html>` element.
33
- *
34
- * @param {any} output
35
- * @param {Object} [ctx={}]
36
- * @returns {Promise<string>}
37
- */
38
- async function resolveOutputToHtml(output, ctx = {}) {
39
- if (output === null || output === undefined || output === false) {
40
- return "";
41
- }
42
- if (isSafeHtml(output)) {
43
- return output.toString();
44
- }
45
- if (isJsxElement(output) || Array.isArray(output)) {
46
- const isRootHtmlTag = isJsxElement(output) && output.type === "html";
47
- const rendered = await renderJsxToString(output, ctx);
48
- if (isRootHtmlTag && !rendered.trimStart().toLowerCase().startsWith("<!doctype")) {
49
- return `<!DOCTYPE html>\n${rendered}`;
50
- }
51
- return rendered;
52
- }
53
- return String(output ?? "");
54
- }
55
-
56
- /**
57
- * Modern JavaScript & React JSX HTML rendering engine for Bluebird.js.
58
- * Standardizes on zero-build JSX and JS view modules, SafeHtml tagged templates,
59
- * progressive layouts, client hydration with skeleton anti-CLS locking, and multi-tier caching.
60
- */
61
- export class Render {
62
- /**
63
- * Generates declarative HTML markup for client-side island hydration with optional
64
- * skeleton fallback and anti-accordion dimension locking (`minHeight`, `minWidth`).
65
- *
66
- * @param {string|Function} name - Island component name or function.
67
- * @param {Object} [islandProps={}] - Initial props passed to the component.
68
- * @param {Object} [options={}] - Island options.
69
- * @param {boolean} [options.persist=false] - Preserves island across View Transitions.
70
- * @param {string|SafeHtml|Object} [options.fallback=""] - Fallback or skeleton HTML/JSX content.
71
- * @param {string|SafeHtml|Object} [options.skeleton] - Skeleton HTML/JSX content to prevent layout shift.
72
- * @param {string|number} [options.minHeight] - CSS min-height to lock vertical space and prevent CLS.
73
- * @param {string|number} [options.minWidth] - CSS min-width to lock horizontal space.
74
- * @param {string} [options.className] - CSS class for the island wrapper.
75
- * @param {Object|string} [options.style] - Inline styles for the island wrapper.
76
- * @param {boolean} [options.ssr=false] - Whether to mark container for hydration of server-rendered markup.
77
- * @param {string} [options.tag="div"] - Container tag name.
78
- * @returns {string} Declarative HTML markup.
79
- */
80
- static island(name, islandProps = {}, options = {}) {
81
- const tag = options.tag || "div";
82
- const resolvedName =
83
- typeof name === "function"
84
- ? name.displayName || name.name || "Island"
85
- : String(name);
86
- const persistAttr = options.persist ? ' data-persist="true"' : "";
87
- const hydrateAttr = options.ssr ? ' data-hydrate="true"' : "";
88
- const classAttr = options.className ? ` class="${escapeHtml(options.className)}"` : "";
89
-
90
- const styleObj =
91
- typeof options.style === "object" && options.style !== null
92
- ? { ...options.style }
93
- : {};
94
- if (options.minHeight !== undefined) {
95
- styleObj.minHeight =
96
- typeof options.minHeight === "number" ? `${options.minHeight}px` : options.minHeight;
97
- }
98
- if (options.minWidth !== undefined) {
99
- styleObj.minWidth =
100
- typeof options.minWidth === "number" ? `${options.minWidth}px` : options.minWidth;
101
- }
102
- const styleStr =
103
- typeof options.style === "string" ? options.style : serializeStyle(styleObj);
104
- const styleAttr = styleStr ? ` style="${escapeHtml(styleStr)}"` : "";
105
-
106
- const serializedProps = escapeHtml(safeJson(islandProps));
107
- const rawFallback =
108
- options.skeleton !== undefined
109
- ? options.skeleton
110
- : options.fallback !== undefined
111
- ? options.fallback
112
- : "";
113
- const fallbackStr = isSafeHtml(rawFallback)
114
- ? rawFallback.toString()
115
- : typeof rawFallback === "string"
116
- ? rawFallback
117
- : "";
118
-
119
- return `<${tag} data-island="${escapeHtml(resolvedName)}" data-props="${serializedProps}"${persistAttr}${hydrateAttr}${classAttr}${styleAttr}>${fallbackStr}</${tag}>`;
120
- }
121
-
122
- /**
123
- * Synchronously or asynchronously renders a component or view (`.jsx` or `.js`) to a raw HTML string.
124
- * @param {string} viewName - Component or view name.
125
- * @param {Object} [data={}] - Props and context.
126
- * @returns {Promise<string>}
127
- */
128
- static async component(viewName, data = {}) {
129
- const view = await ViewLoader.load(viewName);
130
- if (!view) return "";
131
-
132
- if (view.type === "js" || view.type === "jsx") {
133
- const renderFn =
134
- typeof view.module.default === "function" ? view.module.default : view.module;
135
- const ctx = { data };
136
- const output = await renderFn(data, ctx);
137
- return resolveOutputToHtml(output, ctx);
138
- }
139
-
140
- return view.content || "";
141
- }
142
-
143
- /**
144
- * Sends a rendered partial fragment without applying a layout.
145
- * @param {import('express').Response} res - Express response object.
146
- * @param {string} partialName - View or component name.
147
- * @param {Object} [data={}] - Data to pass.
148
- * @returns {Promise<any>}
149
- */
150
- static async partial(res, partialName, data = {}) {
151
- return this.send(res, partialName, { ...data, _layout: false });
152
- }
153
-
154
- /**
155
- * Serves an unparsed, raw HTML file without layouts or server interpolation.
156
- * Ideal for legal policies, static terms, or offline pages.
157
- *
158
- * @param {import('express').Response} res - Express response object.
159
- * @param {string} relativePath - Path to HTML file inside app/views.
160
- * @param {Object} [options={}] - Optional HTTP cache settings.
161
- * @param {number} [options.ttl] - Cache TTL in seconds.
162
- * @returns {Promise<any>}
163
- */
164
- static async html(res, relativePath, options = {}) {
165
- const view = await ViewLoader.load(relativePath);
166
- if (!view || !view.content) {
167
- return res.status(404).json({ message: `Static HTML '${relativePath}' not found.` });
168
- }
169
-
170
- if (options.ttl && options.ttl > 0 && !DEBUG) {
171
- res.set("Cache-Control", `public, max-age=${options.ttl}`);
172
- }
173
-
174
- res.set("Content-Type", "text/html; charset=utf-8");
175
- return res.send(view.content);
176
- }
177
-
178
- /**
179
- * Sends a rendered HTML view response (`.jsx`, `.js`, or `.html`) with full layout and head asset resolution.
180
- *
181
- * @param {import('express').Response} res - Express response object.
182
- * @param {string} viewName - Logical view identifier.
183
- * @param {Object} [data={}] - Data passed to the view and layout.
184
- * @param {number} [ttl] - Optional route cache TTL in seconds.
185
- * @returns {Promise<any>}
186
- */
187
- static async send(res, viewName, data = {}, ttl) {
188
- const locals = res.locals || {};
189
- const appLocals = res.req?.app?.locals || {};
190
- const isPartialRequest =
191
- data._layout === false ||
192
- res.req?.headers?.["x-bluebird-partial"] === "1" ||
193
- res.req?.query?._partial === "1";
194
-
195
- const cacheKey = `view:${isPartialRequest ? "partial:" : ""}${viewName}`;
196
- if (ttl !== undefined && ttl > 0 && !DEBUG) {
197
- const cached = await RenderCache.lookup(cacheKey);
198
- if (cached) {
199
- res.set("Content-Type", "text/html; charset=utf-8");
200
- if (isPartialRequest) {
201
- res.set("X-Bluebird-Partial", "1");
202
- }
203
- res.set("X-Bluebird-Cache", "HIT");
204
- return res.send(cached);
205
- }
206
- }
207
-
208
- const view = await ViewLoader.load(viewName);
209
- if (!view) {
210
- return res.status(404).json({ message: `View '${viewName}' not found.` });
211
- }
212
-
213
- let rendered = "";
214
-
215
- if (view.type === "js" || view.type === "jsx") {
216
- const viewData = { ...data };
217
- let csrfToken =
218
- locals.csrfToken ||
219
- (typeof res.req?.csrfToken === "function" ? res.req.csrfToken() : "") ||
220
- res.req?.cookies?.["_csrf"] ||
221
- res.req?.session?.csrfToken ||
222
- "";
223
-
224
- if (!csrfToken && typeof res.cookie === "function") {
225
- try {
226
- const { Csrf } = await import("./csrf.js");
227
- csrfToken = Csrf.generateToken();
228
- res.cookie("_csrf", csrfToken, {
229
- httpOnly: false,
230
- sameSite: "lax",
231
- secure: Config.isDesktop() ? false : Boolean(!DEBUG),
232
- path: "/",
233
- });
234
- } catch {}
235
- }
236
- const flash =
237
- locals.flash ||
238
- (typeof res.req?.flash === "function" ? res.req.flash() : null) ||
239
- null;
240
-
241
- const ctx = {
242
- req: res.req,
243
- res,
244
- user: res.req?.user,
245
- csrfToken,
246
- flash,
247
- locals,
248
- appLocals,
249
- data: viewData,
250
- };
251
-
252
- if (typeof view.module.load === "function") {
253
- const loadedData = await view.module.load(ctx);
254
- if (loadedData && typeof loadedData === "object") {
255
- Object.assign(viewData, loadedData);
256
- }
257
- }
258
-
259
- const mergedData = {
260
- ...appLocals,
261
- ...locals,
262
- csrfToken,
263
- ...(flash ? { flash } : {}),
264
- ...viewData,
265
- };
266
-
267
- const renderFn =
268
- typeof view.module.default === "function" ? view.module.default : view.module;
269
- const content = await renderFn(mergedData, ctx);
270
- const bodyHtml = await resolveOutputToHtml(content, ctx);
271
-
272
- const layoutName =
273
- data._layout !== undefined
274
- ? data._layout
275
- : view.module.layout !== undefined
276
- ? view.module.layout
277
- : "main";
278
-
279
- if (isPartialRequest || layoutName === false) {
280
- rendered = bodyHtml;
281
- } else {
282
- const layoutView = await ViewLoader.loadLayout(layoutName);
283
- if (layoutView && (layoutView.type === "js" || layoutView.type === "jsx")) {
284
- let headData = {
285
- title: ctx.title || mergedData.title || "Bluebird App",
286
- tags: ctx.headTags || [],
287
- };
288
- if (view.module.head) {
289
- const declaredHead =
290
- typeof view.module.head === "function"
291
- ? await view.module.head(mergedData, ctx)
292
- : view.module.head;
293
- if (declaredHead && typeof declaredHead === "object") {
294
- Object.assign(headData, declaredHead);
295
- }
296
- if (ctx.title) {
297
- headData.title = ctx.title;
298
- }
299
- }
300
-
301
- const layoutFn =
302
- typeof layoutView.module.default === "function"
303
- ? layoutView.module.default
304
- : layoutView.module;
305
-
306
- const safeBody = html.raw(bodyHtml);
307
- const layoutOutput = await layoutFn({
308
- body: safeBody,
309
- content: safeBody,
310
- children: safeBody,
311
- head: headData,
312
- ctx,
313
- data: mergedData,
314
- });
315
-
316
- rendered = await resolveOutputToHtml(layoutOutput, ctx);
317
-
318
- if (ctx.headTags && ctx.headTags.length > 0 && rendered.includes("</head>")) {
319
- if (ctx.title) {
320
- rendered = rendered.replace(
321
- /<title>[^<]*<\/title>/i,
322
- `<title>${escapeHtml(ctx.title)}</title>`
323
- );
324
- }
325
- const extraTags = ctx.headTags.filter(
326
- (t) => !t.startsWith("<title>") && !rendered.includes(t)
327
- );
328
- if (extraTags.length > 0) {
329
- rendered = rendered.replace("</head>", ` ${extraTags.join("\n ")}\n</head>`);
330
- }
331
- }
332
- } else {
333
- rendered = bodyHtml;
334
- }
335
- }
336
- } else {
337
- rendered = view.content || "";
338
- }
339
-
340
- if (ttl !== undefined && ttl > 0 && !DEBUG) {
341
- await RenderCache.store(cacheKey, rendered, ttl);
342
- }
343
-
344
- res.set("Content-Type", "text/html; charset=utf-8");
345
- if (isPartialRequest) {
346
- res.set("X-Bluebird-Partial", "1");
347
- }
348
- res.set("X-Bluebird-Cache", "MISS");
349
- return res.send(rendered);
350
- }
351
-
352
- /**
353
- * Express route handler generator.
354
- * Supports static props object or a dynamic provider function (req, res) => Object | Promise<Object>.
355
- * @param {string} viewName - Logical view name.
356
- * @param {Object|Function} [dataOrFn={}] - Static props or dynamic provider function.
357
- * @param {number} [ttl] - Optional route cache duration in seconds.
358
- * @returns {Function} Express route handler.
359
- */
360
- static view(viewName, dataOrFn = {}, ttl) {
361
- return async (req, res) => {
362
- const resolvedData = typeof dataOrFn === "function" ? await dataOrFn(req, res) : dataOrFn;
363
- return Render.send(res, viewName, resolvedData, ttl);
364
- };
365
- }
366
-
367
- /**
368
- * Express middleware that caches the rendered HTML response for GET requests.
369
- * Respects partial requests with dedicated cache partitions.
370
- * @param {number} [seconds] - Cache duration in seconds.
371
- * @param {Object} [options={}]
372
- * @param {boolean} [options.allowAuthenticated=false]
373
- * @returns {Function}
374
- */
375
- static cache(seconds, options = {}) {
376
- const ttl = seconds ?? RENDER_CACHE_TTL;
377
- const allowAuthenticated = options.allowAuthenticated === true;
378
-
379
- return async (req, res, next) => {
380
- if (DEBUG || req.method !== "GET") return next();
381
-
382
- if (!allowAuthenticated && (req.headers.authorization || req.cookies?.auth || req.user)) {
383
- return next();
384
- }
385
-
386
- const isPartial = req.headers?.["x-bluebird-partial"] === "1" || req.query?._partial === "1";
387
- const key = `route:${isPartial ? "partial:" : ""}${req.originalUrl}`;
388
- const cached = await RenderCache.lookup(key);
389
-
390
- if (cached) {
391
- res.set("Content-Type", "text/html; charset=utf-8");
392
- if (isPartial) {
393
- res.set("X-Bluebird-Partial", "1");
394
- }
395
- res.set("X-Bluebird-Cache", "HIT");
396
- return res.send(cached);
397
- }
398
-
399
- const originalSend = res.send.bind(res);
400
- res.send = async (body) => {
401
- if (typeof body === "string" && res.statusCode === 200) {
402
- await RenderCache.store(key, body, ttl);
403
- }
404
- res.set("X-Bluebird-Cache", "MISS");
405
- return originalSend(body);
406
- };
407
-
408
- next();
409
- };
410
- }
411
-
412
- /**
413
- * Performs SPA-aware or standard HTTP redirect.
414
- * @param {import('express').Request} req
415
- * @param {import('express').Response} res
416
- * @param {string} url
417
- * @param {number} [status=302]
418
- */
419
- static redirect(req, res, url, status = 302) {
420
- if (req.headers?.["x-bluebird-client-router"] === "1") {
421
- res.set("X-Bluebird-Redirect", url);
422
- return res.status(200).json({ redirect: url });
423
- }
424
- return res.redirect(status, url);
425
- }
426
-
427
- /**
428
- * Streams progressive HTML chunks with out-of-order deferred content resolution and <Suspense> support,
429
- * rendering inside the layout unless requested as a partial.
430
- * If cache TTL is configured and cached response exists, serves instant cache hit without streaming overhead.
431
- * When streaming a cache-miss response, caches the final assembled HTML for instant subsequent hits.
432
- *
433
- * @param {import('express').Response} res - Express response object.
434
- * @param {string} viewName - Logical view identifier.
435
- * @param {Object} [data={}] - Initial data and promises.
436
- * @param {number|Object} [options={}] - Cache duration (seconds) or options ({ ttl }).
437
- * @returns {Promise<void>}
438
- */
439
- static async stream(res, viewName, data = {}, options = {}) {
440
- const ttlOption = typeof options === "number" ? options : options?.ttl;
441
- const isPartialRequest =
442
- data._layout === false ||
443
- res.req?.headers?.["x-bluebird-partial"] === "1" ||
444
- res.req?.query?._partial === "1";
445
-
446
- const view = await ViewLoader.load(viewName);
447
- if (!view) {
448
- res.status(404).json({ message: `View '${viewName}' not found.` });
449
- return;
450
- }
451
-
452
- const resolvedTtl =
453
- ttlOption !== undefined
454
- ? ttlOption
455
- : view.module?.cache !== undefined
456
- ? view.module.cache
457
- : 0;
458
-
459
- const cacheKey = `view:stream:${isPartialRequest ? "partial:" : ""}${viewName}`;
460
- if (resolvedTtl > 0 && !DEBUG) {
461
- const cached = await RenderCache.lookup(cacheKey);
462
- if (cached) {
463
- res.set("Content-Type", "text/html; charset=utf-8");
464
- if (isPartialRequest) {
465
- res.set("X-Bluebird-Partial", "1");
466
- }
467
- res.set("X-Bluebird-Cache", "HIT");
468
- return res.send(cached);
469
- }
470
- }
471
-
472
- res.setHeader("Content-Type", "text/html; charset=utf-8");
473
- res.setHeader("Transfer-Encoding", "chunked");
474
- res.setHeader("X-Content-Type-Options", "nosniff");
475
- res.setHeader("X-Bluebird-Cache", "MISS");
476
-
477
- const deferredTokens = [];
478
- const streamData = { ...data };
479
- const proxyData = new Proxy(streamData, {
480
- get(target, prop) {
481
- const val = target[prop];
482
- if (val && typeof val === "object" && val.__bluebird_deferred__) {
483
- deferredTokens.push({ prop: String(prop), ...val });
484
- return html.raw(`<div id="bb-defer-${String(prop)}">${val.fallback}</div>`);
485
- }
486
- return val;
487
- },
488
- });
489
-
490
- const locals = res.locals || {};
491
- const appLocals = res.req?.app?.locals || {};
492
-
493
- let initialHtml = "";
494
- const ctx = {
495
- req: res.req,
496
- res,
497
- user: res.req?.user,
498
- locals,
499
- appLocals,
500
- data: proxyData,
501
- isStreaming: true,
502
- suspenseCounter: 0,
503
- suspenseTasks: [],
504
- headTags: [],
505
- title: "",
506
- };
507
-
508
- if (view.type === "js" || view.type === "jsx") {
509
- if (typeof view.module.load === "function") {
510
- const loadedData = await view.module.load(ctx);
511
- if (loadedData && typeof loadedData === "object") {
512
- Object.assign(streamData, loadedData);
513
- }
514
- }
515
-
516
- const mergedData = {
517
- ...appLocals,
518
- ...locals,
519
- ...proxyData,
520
- };
521
-
522
- const renderFn =
523
- typeof view.module.default === "function" ? view.module.default : view.module;
524
- const content = await renderFn(mergedData, ctx);
525
- const bodyHtml = await resolveOutputToHtml(content, ctx);
526
-
527
- const layoutName =
528
- data._layout !== undefined
529
- ? data._layout
530
- : view.module.layout !== undefined
531
- ? view.module.layout
532
- : "main";
533
-
534
- if (isPartialRequest || layoutName === false) {
535
- initialHtml = bodyHtml;
536
- } else {
537
- const layoutView = await ViewLoader.loadLayout(layoutName);
538
- if (layoutView && (layoutView.type === "js" || layoutView.type === "jsx")) {
539
- let headData = {
540
- title: ctx.title || mergedData.title || "Bluebird App",
541
- tags: ctx.headTags || [],
542
- };
543
- if (view.module.head) {
544
- const declaredHead =
545
- typeof view.module.head === "function"
546
- ? await view.module.head(mergedData, ctx)
547
- : view.module.head;
548
- if (declaredHead && typeof declaredHead === "object") {
549
- Object.assign(headData, declaredHead);
550
- }
551
- if (ctx.title) {
552
- headData.title = ctx.title;
553
- }
554
- }
555
-
556
- const layoutFn =
557
- typeof layoutView.module.default === "function"
558
- ? layoutView.module.default
559
- : layoutView.module;
560
-
561
- const safeBody = html.raw(bodyHtml);
562
- const layoutOutput = await layoutFn({
563
- body: safeBody,
564
- content: safeBody,
565
- children: safeBody,
566
- head: headData,
567
- ctx,
568
- data: mergedData,
569
- });
570
-
571
- initialHtml = await resolveOutputToHtml(layoutOutput, ctx);
572
-
573
- if (ctx.headTags && ctx.headTags.length > 0 && initialHtml.includes("</head>")) {
574
- if (ctx.title) {
575
- initialHtml = initialHtml.replace(
576
- /<title>[^<]*<\/title>/i,
577
- `<title>${escapeHtml(ctx.title)}</title>`
578
- );
579
- }
580
- const extraTags = ctx.headTags.filter(
581
- (t) => !t.startsWith("<title>") && !initialHtml.includes(t)
582
- );
583
- if (extraTags.length > 0) {
584
- initialHtml = initialHtml.replace(
585
- "</head>",
586
- ` ${extraTags.join("\n ")}\n</head>`
587
- );
588
- }
589
- }
590
- } else {
591
- initialHtml = bodyHtml;
592
- }
593
- }
594
- } else {
595
- initialHtml = view.content || "";
596
- }
597
-
598
- res.write(initialHtml);
599
- let assembledHtml = initialHtml;
600
-
601
- if (deferredTokens.length > 0) {
602
- await Promise.all(
603
- deferredTokens.map(async (token) => {
604
- try {
605
- const resolved = await token.promise;
606
- const finalContent = await token.renderer(resolved);
607
- const strContent = await resolveOutputToHtml(finalContent);
608
- 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>`;
609
- res.write(script);
610
- assembledHtml = assembledHtml.replace(
611
- new RegExp(`<div id="bb-defer-${token.prop}">[\\s\\S]*?<\\/div>`),
612
- `<div id="bb-defer-${token.prop}">${strContent}</div>`
613
- );
614
- } catch (err) {
615
- res.write(`<script>console.error("Deferred stream error on ${token.prop}:", ${safeJson(err.message)});</script>`);
616
- }
617
- })
618
- );
619
- }
620
-
621
- if (ctx.suspenseTasks && ctx.suspenseTasks.length > 0) {
622
- await Promise.all(
623
- ctx.suspenseTasks.map(async (taskPromise) => {
624
- try {
625
- const task = await taskPromise;
626
- if (task.success) {
627
- 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>`;
628
- res.write(script);
629
- assembledHtml = assembledHtml.replace(
630
- new RegExp(`<div id="${task.id}">[\\s\\S]*?<\\/div>`),
631
- `<div id="${task.id}">${task.html}</div>`
632
- );
633
- } else {
634
- res.write(`<script>console.error("Suspense error on ${task.id}:", ${safeJson(task.error?.message || "Render error")});</script>`);
635
- }
636
- } catch (err) {
637
- res.write(`<script>console.error("Suspense execution error:", ${safeJson(err.message)});</script>`);
638
- }
639
- })
640
- );
641
- }
642
-
643
- if (resolvedTtl > 0 && !DEBUG) {
644
- await RenderCache.store(cacheKey, assembledHtml, resolvedTtl);
645
- }
646
-
647
- res.end();
648
- }
649
-
650
- /**
651
- * Clears all in-memory view and template caches.
652
- */
653
- static clearTemplateCache() {
654
- ViewLoader.clearCache();
655
- RenderCache.clearMemory();
656
- }
657
-
658
- /**
659
- * Invalidates caches for specific views or route keys.
660
- * @param {string|string[]} [keys]
661
- * @returns {Promise<void>}
662
- */
663
- static async invalidate(keys) {
664
- ViewLoader.clearCache();
665
- await RenderCache.invalidate(keys);
666
- }
667
-
668
- /**
669
- * Automatically discovers views in `app/views/` (ignoring `layouts`, `components`, `partials`, `islands`, and `api`)
670
- * and mounts them as GET routes with their exported `route`, `cache`, `middlewares`, `seo`, and `layout` settings.
671
- *
672
- * @param {import('./router.js').Router} [targetRouter] - Optional Router instance to register routes on.
673
- * @returns {Promise<Array<{viewName: string, routePath: string, cache: number, seo: boolean}>>}
674
- */
675
- static async autoRoutes(targetRouter) {
676
- const discovered = await ViewLoader.discoverRoutes();
677
- if (!targetRouter) return discovered;
678
-
679
- const [{ Seo }, { Actions }] = await Promise.all([
680
- import("./seo.js"),
681
- import("./actions.js"),
682
- ]);
683
-
684
- for (const item of discovered) {
685
- const handlers = [...item.middlewares];
686
- if (item.cache > 0) {
687
- handlers.push(Render.cache(item.cache));
688
- }
689
- handlers.push(
690
- Render.view(item.viewName, (req) => ({
691
- user: req.user,
692
- params: req.params,
693
- query: req.query,
694
- }))
695
- );
696
-
697
- if (item.seo) {
698
- Seo.registerRoute(targetRouter.path || "/", item.routePath, targetRouter._languages || []);
699
- }
700
-
701
- const prevSeo = targetRouter._seo;
702
- targetRouter._seo = false;
703
- targetRouter.get(item.routePath, ...handlers);
704
- targetRouter._seo = prevSeo;
705
-
706
- if (item.actions) {
707
- const postHandlers = [
708
- ...item.middlewares,
709
- Actions.createDispatcher(item.viewName, item.actions),
710
- ];
711
- targetRouter.post(item.routePath, ...postHandlers);
712
- }
713
- }
714
-
715
- return discovered;
716
- }
717
- }
718
-
719
- export {
720
- h,
721
- Fragment,
722
- Island,
723
- Client,
724
- ErrorBoundary,
725
- Suspense,
726
- Head,
727
- Title,
728
- Meta,
729
- useAction,
730
- useActionState,
731
- client,
732
- Script,
733
- SCRIPT_ELEMENT,
734
- action,
735
- };
736
- export default Render;
1
+ import Config from "./config.js";
2
+ import { escapeHtml, isSafeHtml, SafeHtml } from "./html.js";
3
+ import RenderCache from "./render-cache.js";
4
+ import ViewLoader from "./view-loader.js";
5
+ import ViteBridge from "./vite.js";
6
+ import Csrf from "./csrf.js";
7
+
8
+ const DEBUG = Config.props().debug;
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();
18
+
19
+ /**
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}
59
+ */
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 });
203
+ }
204
+
205
+ if (lastIndex < source.length) {
206
+ pushNode({ type: "text", value: source.slice(lastIndex) });
207
+ }
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);
213
+ }
214
+ compiledCache.set(source, root.body);
215
+ }
216
+
217
+ return root.body;
218
+ }
219
+
220
+ /**
221
+ * Safely retrieves an own property or collection `.length` without traversing prototypes.
222
+ * @param {any} target
223
+ * @param {string} key
224
+ * @returns {any}
225
+ */
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;
287
+ }
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
+ }
426
+ }
427
+ }
428
+ return out;
429
+ }
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 {
437
+ /**
438
+ * Renders an HTML template string directly with the supplied data context.
439
+ * @param {string} template
440
+ * @param {Object} [data={}]
441
+ * @param {Object} [ctx={}]
442
+ * @returns {Promise<string>}
443
+ */
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);
448
+ }
449
+
450
+ /**
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>}
456
+ */
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);
461
+ }
462
+
463
+ /**
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]
476
+ * @returns {Promise<any>}
477
+ */
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);
482
+ }
483
+
484
+ /**
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]
491
+ * @returns {Promise<any>}
492
+ */
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) {
507
+ const cached = await RenderCache.lookup(cacheKey);
508
+ if (cached) {
509
+ res.set("Content-Type", "text/html; charset=utf-8");
510
+ res.set("X-Bluebird-Cache", "HIT");
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));
516
+ }
517
+ }
518
+
519
+ const view = await ViewLoader.load(viewName);
520
+ if (!view) {
521
+ return res.status(404).json({ message: `View '${viewName}' not found.` });
522
+ }
523
+
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;
542
+
543
+ const renderCtx = {
544
+ req,
545
+ res,
546
+ vite: ViteBridge.from(req) || ViteBridge.from(res),
547
+ };
548
+
549
+ let body = view.content || "";
550
+ if (!opts.raw) {
551
+ body = await this.renderString(body, viewData, renderCtx);
552
+ }
553
+
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);
563
+ }
564
+ }
565
+
566
+ if (DEBUG && !partialRequest && renderCtx.vite?.mode === "dev" && /<head[\s>]/i.test(rendered)) {
567
+ rendered = await renderCtx.vite.transformHtml(req?.originalUrl || req?.url || "/", rendered);
568
+ }
569
+
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}`);
576
+ }
577
+ res.set("Content-Type", "text/html; charset=utf-8");
578
+ res.set("X-Bluebird-Cache", "MISS");
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));
617
+ }
618
+
619
+ /**
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}
625
+ */
626
+ static view(viewName, dataOrFn = {}, options = {}) {
627
+ return async (req, res) => {
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),
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;
663
+ }
664
+
665
+ /**
666
+ * Express middleware caching HTML responses of GET routes.
667
+ * @param {number} [seconds]
668
+ * @param {Object} [options={}]
669
+ * @param {boolean} [options.allowAuthenticated=false]
670
+ * @param {string[]} [options.query=[]]
671
+ * @returns {Function}
672
+ */
673
+ static cache(seconds, options = {}) {
674
+ const ttl = seconds ?? RENDER_CACHE_TTL;
675
+ const allowAuthenticated = options.allowAuthenticated === true;
676
+ const queryKeys = Array.isArray(options.query) ? options.query : [];
677
+
678
+ return async (req, res, next) => {
679
+ if (DEBUG || req.method !== "GET") return next();
680
+ if (!allowAuthenticated && isAuthenticatedRequest(req)) return next();
681
+
682
+ const key = buildCacheKey("route", req, queryKeys);
683
+ if (!key) return next();
684
+
685
+ const cached = await RenderCache.lookup(key);
686
+ if (cached) {
687
+ res.set("Content-Type", "text/html; charset=utf-8");
688
+ res.set("X-Bluebird-Cache", "HIT");
689
+ return res.send(applyCspNonce(detokenizeFromCache(cached, Csrf.ensure(req, res)), res));
690
+ }
691
+
692
+ const originalSend = res.send.bind(res);
693
+ res.send = async (body) => {
694
+ res.send = originalSend;
695
+ if (typeof body === "string" && res.statusCode === 200) {
696
+ const token = res.locals?.csrfToken || req.cookies?._csrf || "";
697
+ await RenderCache.store(key, tokenizeForCache(stripCspNonce(body, res), token), ttl);
698
+ }
699
+ res.set("X-Bluebird-Cache", "MISS");
700
+ return originalSend(body);
701
+ };
702
+ next();
703
+ };
704
+ }
705
+
706
+ /**
707
+ * Performs a standard HTTP redirect.
708
+ * @param {import('express').Request} req
709
+ * @param {import('express').Response} res
710
+ * @param {string} url
711
+ * @param {number} [status=302]
712
+ */
713
+ static redirect(req, res, url, status = 302) {
714
+ return res.redirect(status, url);
715
+ }
716
+
717
+ /**
718
+ * Clears all in-memory view, compiled template, and render caches.
719
+ */
720
+ static clearTemplateCache() {
721
+ compiledCache.clear();
722
+ ViewLoader.clearCache();
723
+ RenderCache.clearMemory();
724
+ }
725
+
726
+ /**
727
+ * Invalidates cached views and routes for paths or cache keys.
728
+ * @param {string|string[]} [keys]
729
+ * @returns {Promise<void>}
730
+ */
731
+ static async invalidate(keys) {
732
+ compiledCache.clear();
733
+ ViewLoader.clearCache();
734
+ await RenderCache.invalidate(keys);
735
+ }
736
+ }
737
+
738
+ export default Render;