@seip/bluebird-js 0.1.6 → 0.1.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/core/render.js CHANGED
@@ -1,728 +1,736 @@
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";
19
- import RenderCache from "./render-cache.js";
20
- import ViewLoader from "./view-loader.js";
21
-
22
- const props = Config.props();
23
- const DEBUG = props.debug;
24
- const RENDER_CACHE_TTL = parseInt(process.env.RENDER_CACHE_TTL || "300", 10);
25
-
26
- /**
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>}
33
- */
34
- async function resolveOutputToHtml(output, ctx = {}) {
35
- if (output === null || output === undefined || output === false) {
36
- return "";
37
- }
38
- if (isSafeHtml(output)) {
39
- return output.toString();
40
- }
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}`;
46
- }
47
- return rendered;
48
- }
49
- return String(output ?? "");
50
- }
51
-
52
- /**
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.
56
- */
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;
93
- }
94
- if (options.minWidth !== undefined) {
95
- styleObj.minWidth =
96
- typeof options.minWidth === "number" ? `${options.minWidth}px` : options.minWidth;
97
- }
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
- }
117
-
118
- /**
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.
122
- * @returns {Promise<string>}
123
- */
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 || "";
137
- }
138
-
139
- /**
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>}
145
- */
146
- static async partial(res, partialName, data = {}) {
147
- return this.send(res, partialName, { ...data, _layout: false });
148
- }
149
-
150
- /**
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.
158
- * @returns {Promise<any>}
159
- */
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);
172
- }
173
-
174
- /**
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.
181
- * @returns {Promise<any>}
182
- */
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) {
193
- const cached = await RenderCache.lookup(cacheKey);
194
- if (cached) {
195
- res.set("Content-Type", "text/html; charset=utf-8");
196
- if (isPartialRequest) {
197
- res.set("X-Bluebird-Partial", "1");
198
- }
199
- res.set("X-Bluebird-Cache", "HIT");
200
- return res.send(cached);
201
- }
202
- }
203
-
204
- const view = await ViewLoader.load(viewName);
205
- if (!view) {
206
- return res.status(404).json({ message: `View '${viewName}' not found.` });
207
- }
208
-
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
- };
262
-
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);
267
-
268
- const layoutName =
269
- data._layout !== undefined
270
- ? data._layout
271
- : view.module.layout !== undefined
272
- ? view.module.layout
273
- : "main";
274
-
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
- }
331
- }
332
- } else {
333
- rendered = view.content || "";
334
- }
335
-
336
- if (ttl !== undefined && ttl > 0 && !DEBUG) {
337
- await RenderCache.store(cacheKey, rendered, ttl);
338
- }
339
-
340
- res.set("Content-Type", "text/html; charset=utf-8");
341
- if (isPartialRequest) {
342
- res.set("X-Bluebird-Partial", "1");
343
- }
344
- res.set("X-Bluebird-Cache", "MISS");
345
- return res.send(rendered);
346
- }
347
-
348
- /**
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.
355
- */
356
- static view(viewName, dataOrFn = {}, ttl) {
357
- return async (req, res) => {
358
- const resolvedData = typeof dataOrFn === "function" ? await dataOrFn(req, res) : dataOrFn;
359
- return Render.send(res, viewName, resolvedData, ttl);
360
- };
361
- }
362
-
363
- /**
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.
367
- * @param {Object} [options={}]
368
- * @param {boolean} [options.allowAuthenticated=false]
369
- * @returns {Function}
370
- */
371
- static cache(seconds, options = {}) {
372
- const ttl = seconds ?? RENDER_CACHE_TTL;
373
- const allowAuthenticated = options.allowAuthenticated === true;
374
-
375
- return async (req, res, next) => {
376
- if (DEBUG || req.method !== "GET") return next();
377
-
378
- if (!allowAuthenticated && (req.headers.authorization || req.cookies?.auth || req.user)) {
379
- return next();
380
- }
381
-
382
- const isPartial = req.headers?.["x-bluebird-partial"] === "1" || req.query?._partial === "1";
383
- const key = `route:${isPartial ? "partial:" : ""}${req.originalUrl}`;
384
- const cached = await RenderCache.lookup(key);
385
-
386
- if (cached) {
387
- res.set("Content-Type", "text/html; charset=utf-8");
388
- if (isPartial) {
389
- res.set("X-Bluebird-Partial", "1");
390
- }
391
- res.set("X-Bluebird-Cache", "HIT");
392
- return res.send(cached);
393
- }
394
-
395
- const originalSend = res.send.bind(res);
396
- res.send = async (body) => {
397
- if (typeof body === "string" && res.statusCode === 200) {
398
- await RenderCache.store(key, body, ttl);
399
- }
400
- res.set("X-Bluebird-Cache", "MISS");
401
- return originalSend(body);
402
- };
403
-
404
- next();
405
- };
406
- }
407
-
408
- /**
409
- * Performs SPA-aware or standard HTTP redirect.
410
- * @param {import('express').Request} req
411
- * @param {import('express').Response} res
412
- * @param {string} url
413
- * @param {number} [status=302]
414
- */
415
- 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
- return res.redirect(status, url);
421
- }
422
-
423
- /**
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.
648
- */
649
- static clearTemplateCache() {
650
- ViewLoader.clearCache();
651
- RenderCache.clearMemory();
652
- }
653
-
654
- /**
655
- * Invalidates caches for specific views or route keys.
656
- * @param {string|string[]} [keys]
657
- * @returns {Promise<void>}
658
- */
659
- static async invalidate(keys) {
660
- ViewLoader.clearCache();
661
- await RenderCache.invalidate(keys);
662
- }
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
- }
714
-
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
- export default Render;
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;